# Governance

> Use when starting a project and needing architecture documentation, logging an architecture decision (ADR) or tech decision (TDR), maintaining the trade-off matrix, checking which governance gates are missing or incomplete, drawing architecture diagrams, auditing code for security and tech debt, or sanitizing PII and internal network topologies. Triggers: "set up the project", "write an ADR", "write a TDR", "record tech decision", "verify compliance", "draw [diagram type]", "audit this", "audit <path>", "sanitize PII".

- Skill: `thegeekybeng/governance` (Agent Skill)
- Install (CLI): `npx skillmds@latest add thegeekybeng/governance`
- Raw SKILL.md: https://api.skillmd.com/api/skills/thegeekybeng/governance/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: thegeekybeng (https://skillmd.com/u/thegeekybeng)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/thegeekybeng/governance

---


# Governance — Master Skill

## Skill Classification

| Mode       | Class                          | What it means                                                       |
| ---------- | ------------------------------ | ------------------------------------------------------------------- |
| `verify`   | DETERMINISTIC                  | File existence + pattern checks. Same input → same output.          |
| `adr`      | DETERMINISTIC                  | Format enforcement. Architecture invariants, topology, structural.  |
| `tdr`      | DETERMINISTIC                  | Rule 8 format enforcement. Technology/package selection & exit path.|
| `scaffold` | GROUNDED                       | TOGAF-mapped structure. Sources cited with edition and date.        |
| `diagram`  | MODEL-JUDGMENT                 | Content is model-assessed; mandatory conditions are rule-enforced.  |
| `audit`    | MODEL-JUDGMENT + GROUNDED      | Findings require interpretation; CWE/OWASP citations are grounded.  |
| `sanitize` | DETERMINISTIC + MODEL-JUDGMENT | Regex scanning for PII, model judgment for contextual abstractions. |

**DETERMINISTIC** — findings are verifiable without AI.
**GROUNDED** — claims traceable to external authority with confidence levels.
**MODEL-JUDGMENT** — requires AI interpretation; review before acting.

---

## Mode Selection

| Mode       | Trigger Phrases                                                                                                                               |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `scaffold` | "set up the project", "init .ai-arch", "initialize governance", "scaffold architecture", "start from scratch", "do this from scratch"         |
| `adr`      | "log architecture decision", "write an ADR", "record architecture choice", structural topology/tier/auth/boundary decision                    |
| `tdr`      | "log tech decision", "write a TDR", "record technology choice", "add new dependency", "add library", "choose package", framework selection    |
| `verify`   | "verify compliance", "check governance", "check gates", "audit .ai-arch", "verify .ai-arch", "governance check", "check compliance"           |
| `diagram`  | "draw [diagram type]", "draw context", "draw ERD", "draw deployment", "draw sequence for", "draw data flow", "draw state", "draw container"   |
| `audit`    | "audit this", "audit [path]", "run dev audit", "check code quality", "audit for tech debt", "security audit"                                  |
| `sanitize` | "sanitize PII", "scrub the repo", "obfuscate internal IPs", "clean up personal data", "abstract hardware"                                     |

If mode is ambiguous, ask: "Which governance mode? scaffold / adr / tdr / verify / diagram / audit / sanitize"

---

---

## MODE: `scaffold`

Initialize the `.ai-arch/` Architecture Repository for any new or existing project.

### When to scaffold

- User starts a new project
- User says "set up the project properly" or "do this from scratch"
- A project directory exists but has no `.ai-arch/` folder
- User asks about project documentation, ADRs, or NFRs

### Step 1 — Ask for project context (if not already known)

Confirm before creating files:

1. What does this project do? (one sentence)
2. Who are the users? (list roles)
3. What is the deployment target? (NAS, cloud, laptop, etc.)
4. What data does it handle? (PII? Financial? Public?)
5. What is the timeline / team size?

Extract from existing context if already described. Do NOT ask questions already answered.

### Step 2 — Create the .ai-arch/ directory structure

Create all 10 files in `<project-root>/.ai-arch/` and a `charts/` directory:

```text
.ai-arch/
  01_README.md                  ← What this folder is + TOGAF mapping
  02_PROJECT_CONTEXT.md         ← Why, who, what it is NOT
  03_PRE_PROJECT_CHECKLIST.md   ← 6 governance documents (fill from context)
  04_ASSUMPTIONS.md             ← What must be true for the system to work
  05_COMPLEXITY_ANALYSIS.md     ← Effort estimate with reasoning
  06_ARCHITECTURE_OVERVIEW.md   ← Conceptual layer diagram prose (HTML Link)
  07_ARCHITECTURE_DECISIONS.md  ← Empty ADR log, ready for entries
  08_AI_ASSISTANCE_MAP.md       ← Track AI-generated vs human files
  09_API_REFERENCE.md           ← Core API endpoint catalog
  10_OBSERVABILITY_STRATEGY.md  ← L.M.T.A Framework (Logs, Metrics, Traces, Alerts)
  charts/                       ← Dynamic HTML Architecture Charts
  AUDIT_SCORES.json             ← Audit history (created on first audit run)
  pc2e/                         ← PC2E Mandatory Workspaces files
    SYSTEM_LOG.md
    PORTS.md
    Project_Context.md
    SECURITY_FRAMEWORK.md
```

### Step 3 — Generate ARCHITECTURE_OVERVIEW.md

**1. Create the high-res HTML diagram in `charts/architecture-overview.html`:**
Do NOT use Mermaid. Use HTML/CSS Grid and Flexbox to build a responsive, native architecture diagram.

- Must include a "Download as PNG" button natively powered by `<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>` and a simple click handler.
- Build a dark-mode layered stack: Business → Integration → Intelligence → Delivery
- Include vertical pillars for Data Persistence and Security/Gov
- Avoid absolute positioning; use CSS Flexbox/Grid

**2. Create `06_ARCHITECTURE_OVERVIEW.md`:**

- Do NOT include Mermaid blocks.
- Provide a clear markdown link: `👉 **[View the High-Res HTML Layered Architecture](charts/architecture-overview.html)**`
- Follow the link with: one prose paragraph per layer + one per cross-cutting bar.

### Step 4 — Add .ai-arch/ to .gitignore

```gitignore
# AI Architecture Repository — internal governance notes, gitignored
.ai-arch/
```

### Step 5 — Fill each file from project context

- **PRE_PROJECT_CHECKLIST.md**: Complete all 6 sections — Business Case, Stakeholder RACI, NFRs (minimum: performance, security, data retention), Data Classification, Risk Register, Assumptions.
- **COMPLEXITY_ANALYSIS.md**: Traditional dev vs AI-augmented table, effort drivers, human judgment tasks.
- **ARCHITECTURE_DECISIONS.md**: Initialize `## Architectural & Technical Trade-Off Matrix` table at the top with a baseline entry, and create ADR-001 immediately (framework/stack choice vs alternatives).
- **pc2e/SYSTEM_LOG.md**: Initialize `## Technical Decision Records (TDR)` section template.
- **01_README.md**: Include TOGAF ADM Deliverable Mapping (see table below).

**TOGAF ADM Deliverable Mapping (embed in 01_README.md):**

```markdown
## TOGAF ADM Deliverable Mapping

| File | TOGAF Phase | Deliverable |
|------|-------------|-------------|
| 01_README.md | Preliminary | Architecture Repository orientation + TOGAF mapping |
| 02_PROJECT_CONTEXT.md | Phase A | Statement of Architecture Work |
| 03_PRE_PROJECT_CHECKLIST.md | Preliminary | Architecture Principles + Capability Assessment |
| 04_ASSUMPTIONS.md | Phase A | Architecture Vision — assumptions & constraints |
| 05_COMPLEXITY_ANALYSIS.md | Phase A | Architecture Vision — feasibility & effort |
| 06_ARCHITECTURE_OVERVIEW.md | Phase A | Architecture Vision (HTML layer diagram) |
| 07_ARCHITECTURE_DECISIONS.md | A–D | Architecture Decision Log (append-only) |
| 08_AI_ASSISTANCE_MAP.md | B–D | Architecture Definition Document — provenance |
| 09_API_REFERENCE.md | Phase C | Architecture Definition Document — interfaces |
| 10_OBSERVABILITY_STRATEGY.md | F–G | Migration Planning / Implementation Governance |
| charts/ | B–D | Domain views |

Source: TOGAF® Standard, 10th Edition (Open Group, 2022). Confidence: HIGH.
```

**Interview Answer (embed in PRE_PROJECT_CHECKLIST.md bottom):**
> "Six documents before any code is written: Business Case, Stakeholder RACI, NFRs, Data Classification, Risk Register, and Assumptions. The most commonly skipped and most consequential is NFRs — without them, you cannot justify a single architecture decision."

### Scaffold Rules

- Never leave placeholder text in generated files
- ADRs must always include rejected alternatives — a decision without alternatives is a guess
- AI_ASSISTANCE_MAP.md must list every file created by AI in this session
- ASSUMPTIONS.md must distinguish: infrastructure assumptions (could be wrong) vs business assumptions (require domain expert)

---

---

## MODE: `adr`

Write a new Architecture Decision Record.

### When to write ADR (vs TDR)

- **Use ADR for macro-architectural decisions**:
  - System topology, deployment model, physical/virtual tier splits (e.g. edge vs remote compute node)
  - Data storage paradigm (relational vs document vs graph), replication, and data sovereignty boundaries
  - Authentication and authorization models (RBAC, JWT, session lifecycle, multi-tenant data isolation)
  - Communication patterns and protocols (REST vs gRPC vs SSE vs WebSockets, synchronous vs message queues)
  - Boundary contracts, structural seams, and major architectural refactorings
- User explicitly asks to "log an architecture decision" or "write an ADR".
- *Do not use ADR for specific packages, libraries, or tool additions — use `tdr` mode instead.*

### ADR Format (strict)

```markdown
## ADR-XXX — [Decision Title] ([DATE YYYY-MM-DD])

**Context:**
[2-4 sentences. What was the situation? What architectural forces, constraints, or security vectors were active?]

**Decision:** [One clear sentence stating what architectural approach or structure was chosen.]

**Consequences (+):**
- [Positive architectural outcome or capability gained 1]
- [Positive architectural outcome or capability gained 2]

**Consequences (−):**
- [Negative outcome, architectural debt, or operational trade-off 1]
- [Negative outcome, architectural debt, or operational trade-off 2]

**Rejected alternatives:** [Alternative A] ([why rejected with technical rationale]); [Alternative B] ([why rejected with technical rationale]).
```

### ADR Rules

1. **Rejected alternatives are mandatory.** Minimum 2 per ADR with explicit technical rejection reasons. A decision without alternatives is an unvalidated assumption.
2. **ADRs are never edited.** If reversed or revised, write a new sequential ADR and mark the old one `[SUPERSEDED by ADR-XXX]`.
3. **Number sequentially.** Read existing `07_ARCHITECTURE_DECISIONS.md` to determine the next number (e.g. ADR-001, ADR-002).
4. **Date it accurately.** Date when the decision was agreed upon (YYYY-MM-DD), not documented.
5. **Consequences must be honest.** List real operational and architectural negatives. An ADR with only positives is ungrounded.
6. **Mandatory Trade-Off Matrix Update:** When appending an ADR to `07_ARCHITECTURE_DECISIONS.md`, the agent MUST immediately append or update the corresponding row in the `## Architectural & Technical Trade-Off Matrix` at the top of `07_ARCHITECTURE_DECISIONS.md`. Also update `08_AI_ASSISTANCE_MAP.md`.

---

---

## MODE: `tdr`

Write a new Technical Decision Record adhering to Global Rule 8.

### When to write TDR (vs ADR)

- **Use TDR for technology, package, library, and runtime choices**:
  - Introducing any new dependency, framework, npm/pip package, or external tool to a project (Rule 8)
  - Selecting between competing libraries (e.g., Next.js 15 vs Next.js 16, Prisma vs Drizzle, Pino vs Winston, sessionStorage vs localStorage)
  - Concrete runtime utilities, compilation scripts, or CI gate verification helpers (e.g., custom Node audit script vs audit-ci)
  - Choosing specific runtime engines, container base images, or database client drivers
- User asks to "write a TDR", "record tech decision", "log technology choice", or when introducing a dependency.

### TDR Format (strict adhering to Global Rule 8)

```markdown
### TDR-XX: [Technology / Package / Tool Title]

* **Status**: Approved & Implemented ([DATE YYYY-MM-DD])
* **Context**: [2-4 sentences explaining why this technology/tool was needed, the technical gap, or security requirement]
* **Proposed Solution**: [Clear explanation of what the technology does and why this choice over alternatives]
* **Trade-offs & Known Limitations**:
  * [Trade-off or limitation 1]
  * [Trade-off or limitation 2]
* **Alternatives Considered**:
  1. *[Alternative A]*: [Why rejected - concrete technical rationale]
  2. *[Alternative B]*: [Why rejected - concrete technical rationale]
* **Decision**: [Clear concluding rationale for this specific technology]
* **Migration Path**: [Clear exit/migration path if the technology becomes unmaintained, deprecated, or needs upgrading]
```

### TDR Rules

1. **Mandatory 4 Core Fields (Rule 8):**
   - What it does and why this choice over alternatives
   - Trade-offs and known limitations
   - At least 2 alternatives considered with explicit technical rejection reasons
   - Migration path if it becomes unmaintained, deprecated, or needs major version migration
2. **Storage Target:** Append to `SYSTEM_LOG.md` (or `.ai-arch/pc2e/SYSTEM_LOG.md` or a project `docs/decisions/` directory as specified by Rule 8).
3. **Number sequentially:** Read existing `SYSTEM_LOG.md` to determine the next number (e.g., TDR-01, TDR-02).
4. **Mandatory Trade-Off Matrix Update:** When logging a TDR, the agent MUST immediately append or update the corresponding row in the `## Architectural & Technical Trade-Off Matrix` located at the top of `.ai-arch/07_ARCHITECTURE_DECISIONS.md`.
5. **No undocumented packages:** Never install or commit a new package or framework without a matching TDR.

---

---

## Architectural & Technical Trade-Off Matrix

Every project maintaining `.ai-arch/` MUST maintain a consolidated **Architectural & Technical Trade-Off Matrix** at the top of `07_ARCHITECTURE_DECISIONS.md`.

### Matrix Purpose

To provide a scannable, cross-cutting index of all deliberate trade-offs across architecture (ADRs) and technologies (TDRs), ensuring that engineering teams and AI agents immediately understand the costs accepted, compensatory controls applied, and review triggers for every major choice.

### 7-Column Standard Schema

```markdown
## Architectural & Technical Trade-Off Matrix

| ID | Decision / Component | Category / Dimension | Benefit Gained (+) | Cost / Trade-off Incurred (−) | Compensating Control / Mitigation | Review / Revisit Trigger |
|---|---|---|---|---|---|---|
| ADR-001 | 3-Tier Edge vs Compute Split | Hardware & Memory | Recovers 8GB+ RAM on primary edge node | Network latency & distributed complexity | Encrypted mesh VPN, automated proxy routing | Edge node hardware upgrade |
| TDR-04 | Next.js 15 Framework Upgrade | Framework & Supply Chain | Resolves critical CVEs within 512MB RAM ceiling | Requires async route parameters | Async parameter handler pattern & backport LTS | Edge container build memory limit increased |
```

### Column Definitions

- **ID**: `ADR-XXX` or `TDR-XX`. If superseded, append `[SUPERSEDED by ADR-YYY]`.
- **Decision / Component**: Short name of the decision, subsystem, seam, or technology.
- **Category / Dimension**: Non-functional attribute impacted (e.g. Memory & Hardware, Security & ACE, Storage & PDPA, Multi-Tenancy & Isolation, Framework & Supply Chain, Observability, Latency).
- **Benefit Gained (+)**: Primary positive outcome, capability unlocked, or risk mitigated.
- **Cost / Trade-off Incurred (−)**: Operational cost, technical debt, or limitation accepted.
- **Compensating Control / Mitigation**: Active mechanism implemented to safeguard against the accepted cost.
- **Review / Revisit Trigger**: Measurable threshold or event when the decision should be revisited.

### Maintenance & Synchronization Rules

1. **Synchronous Append:** Whenever an ADR or TDR is created, its trade-off row MUST be appended to the matrix during the same edit.
2. **Immutability with Supersession:** Historical rows are never deleted; if a decision is superseded, append `[SUPERSEDED by ADR-YYY]` to the ID and annotate the review trigger.
3. **Completeness:** Gate 2 verification validates that every active ADR and TDR has a corresponding row in the matrix.

---

---

## Synergy with `/improve-codebase-architecture`

When using `/improve-codebase-architecture` to explore deepening opportunities, identify shallow modules, or create seams:

1. **Deepened Seam / Module Extraction**:
   - If an architectural refactor consolidates shallow modules behind a deep interface, creates a seam, or modifies service boundaries, dispatch `/governance adr` to log the structural pattern and update the Trade-Off Matrix.
2. **New Utility / Package Adoption**:
   - If refactoring requires importing an external package, parser, or library, dispatch `/governance tdr` adhering to Rule 8 (What/Why, Trade-offs, 2 Alternatives, Migration Path) and update the Trade-Off Matrix.
3. **Rejection Persistence**:
   - If the user rejects an architectural candidate with a load-bearing architectural reason during the grilling loop, record an ADR documenting the rejection and alternatives so future architecture reviews do not re-suggest it.

---

---

## MODE: `verify`

Deterministically check which governance gates are missing or incomplete.

### Flags

- **Default (no flag):** `--fast` mode. File existence and pattern matching only. **DETERMINISTIC** — findings are reproducible without AI interpretation.
- **`--deep` flag:** Also checks file contents for semantic completeness. **MODEL-JUDGMENT** — output labelled as such. User specifies: "verify compliance --deep" or "deep governance check".

### Gate 1 — .ai-arch/ presence

Check: does `.ai-arch/` exist with all 10 required files?

Required files: `01_README.md`, `02_PROJECT_CONTEXT.md`, `03_PRE_PROJECT_CHECKLIST.md`, `04_ASSUMPTIONS.md`, `05_COMPLEXITY_ANALYSIS.md`, `06_ARCHITECTURE_OVERVIEW.md`, `07_ARCHITECTURE_DECISIONS.md`, `08_AI_ASSISTANCE_MAP.md`, `09_API_REFERENCE.md`, `10_OBSERVABILITY_STRATEGY.md`

`PASS`: all 10 present | `PARTIAL`: some missing | `FAIL`: .ai-arch/ absent

### Gate 2 — ADR, TDR & Trade-Off Matrix Quality

Deterministic checks across architectural decisions, technical decisions, and the consolidated trade-off matrix:

1. **ADR Check (`07_ARCHITECTURE_DECISIONS.md`):**
   - `PASS`: Every ADR contains `**Rejected alternatives:**` with visible text and minimum 2 alternatives.
   - `INCOMPLETE`: Pattern found but empty, just a dash, or fewer than 2 alternatives.
   - `MISSING`: No ADRs present at all.

2. **TDR Check (`SYSTEM_LOG.md` or `pc2e/SYSTEM_LOG.md` or `docs/decisions/`):**
   - `PASS`: Every TDR contains all 4 mandatory Global Rule 8 elements:
     - What it does and why this choice over alternatives
     - Trade-offs and known limitations
     - At least 2 alternatives considered with technical rejection reasons
     - Migration path if unmaintained or deprecated
   - `INCOMPLETE`: One or more mandatory Rule 8 fields missing.
   - `MISSING`: Dependencies or packages added to project without recorded TDRs.

3. **Trade-Off Matrix Check (`07_ARCHITECTURE_DECISIONS.md`):**
   - `PASS`: `## Architectural & Technical Trade-Off Matrix` table exists with all 7 columns, and every active ADR and TDR has a corresponding mapped row.
   - `PARTIAL`: Matrix table exists but some ADRs or TDRs are missing mapped rows.
   - `FAIL`: Matrix table missing or empty.

Report: N of M ADRs compliant, X of Y TDRs compliant, Trade-Off Matrix synchronized (Z entries mapped).

### Gate 3 — Data classification consistency

Read `03_PRE_PROJECT_CHECKLIST.md` → locate Data Classification section.

**--fast mode (existence only):**

- Sensitive/sovereign data present → check `charts/dataflow.html` exists
- Relational DB confirmed (grep `07_ARCHITECTURE_DECISIONS.md` for: PostgreSQL/MySQL/SQLite/postgres/mariadb) → check `charts/erd.html` exists
- Sovereign/edge/hybrid infra (grep for: sovereign/edge/hybrid/NAS/on-premise) → check `charts/deployment.html` exists

**--deep mode (content check, MODEL-JUDGMENT):**

- If `charts/erd.html` exists: does it contain entity definitions with PII annotations where required?
- If `charts/dataflow.html` exists: does it show data crossing trust boundaries?
- Label all content findings as MODEL-JUDGMENT in output.

### Gate 4 — AI component governance

Grep `06_ARCHITECTURE_OVERVIEW.md` and `03_PRE_PROJECT_CHECKLIST.md` for: `LLM / AI / Ollama / agent / GPT / model / inference / transformer`

If found:

- `PASS`: PRE_PROJECT_CHECKLIST references any documented AI runtime governance framework
- `FAIL`: AI component found with no governance reference
- Remediation: Document your AI governance framework in the Risk Register. Minimum controls required: anti-hallucination rules, prompt injection defence (structural fencing), context window bounding, phantom commitment prevention, mandatory audit logging.

### Gate 5 — NFR completeness

`03_PRE_PROJECT_CHECKLIST.md` must contain minimum 3 NFR types:

- Performance (grep: performance/latency/response time/throughput/SLA)
- Security (grep: security/authentication/authorisation/OWASP)
- Data retention (grep: retention/deletion/archive/purge)

`PASS`: all 3 found | `PARTIAL`: 1-2 found | `FAIL`: none

### Gate 6 — Observability Readiness

Check `10_OBSERVABILITY_STRATEGY.md` for L.M.T.A (Logs, Metrics, Traces, Alerts) coverage.

- **--fast mode**: File exists.
- **--deep mode**: Check if strategy for Logs, Metrics, Traces, and Alerts are defined and aligned with standards (e.g. OpenTelemetry).

`PASS`: LMTA defined | `PARTIAL`: Incomplete | `FAIL`: File missing or empty

### Gate 7 — README Quality

Check for the existence and completeness of the root `README.md` file.

- **--fast mode**: Checks if `README.md` exists in the repository root.
- **--deep mode**: Checks if `README.md` contains sections for:
  - Prerequisites (e.g. Node.js/Docker versions).
  - Package installation scripts (npm/pnpm/yarn/bun).
  - Standard runtime execution commands (dev, build, start, test).
  - Environment variables configuration details.

`PASS`: Root README.md exists and contains all required sections | `PARTIAL`: Exists but missing key sections | `FAIL`: Root README.md missing or empty

### Gate 8 — Version Management & Auto-Updates

Check for automated package update configurations.

- **--fast mode**: Checks if `.github/dependabot.yml` or `renovate.json` exists.
- **--deep mode**: Verifies if dependencies are pinned (no loose `*` or wide ranges for critical libraries) and configured to receive auto-updates.

`PASS`: Auto-update configurations present and configured | `PARTIAL`: Config exists but inactive or unpinned dependencies found | `FAIL`: No automated update configurations found

### Gate 9 — Repository Community Standards

Verify that standard repository community guidelines and issue templates exist.

- **--fast mode**: Checks if `LICENSE`, `SECURITY.md`, `CODE_OF_CONDUCT.md`, `SUPPORT.md`, and `CONTRIBUTING.md` exist in the root folder.
- **--deep mode**: Verifies that `.github/ISSUE_TEMPLATE/bug_report.md` and `feature_request.md` are present, configured with default assignees, and warn users against public vulnerability reports.

`PASS`: All files and templates exist | `PARTIAL`: Standard files exist but templates missing | `FAIL`: Any core file (LICENSE/SECURITY) is missing

### Gate 10 — PII Compliance & Sanitisation

Ensure that personal developer data is not hardcoded inside committed repository files.

- **--fast mode**: Scans files (README, Security, Code of Conduct) for hardcoded email/username patterns.
- **--deep mode**: Verifies that:
  - Maintainer contact details are dynamically populated from `.env` variables (`MAINTAINER_NAME`, `MAINTAINER_EMAIL`, `MAINTAINER_GITHUB`).
  - Codebase uses a template compiler (`compileTemplates.ts`) to generate final markdown files from clean template sources (`templates/community/*.template`).

`PASS`: PII compliant and templated | `PARTIAL`: No hardcoded details found but lacks template compilation | `FAIL`: Hardcoded personal credentials or emails found in committed files

### Delta from AUDIT_SCORES.json

If `AUDIT_SCORES.json` exists in `.ai-arch/`: read the last verify run and show which gates changed status since then. No delta if no history.

### Output format

```markdown
# Compliance Verification Report

**Repo:** [path]  **Date:** [timestamp]  **Mode:** [--fast / --deep]

## Gate Results

| Gate | Status | Detail |
|------|--------|--------|
| .ai-arch/ presence | ✅ PASS | 10/10 files present |
| ADR quality | ⚠️ PARTIAL | 2 of 4 ADRs missing rejected alternatives |
| Data classification | ✅ PASS | dataflow.html and erd.html present |
| AI governance | ❌ FAIL | AI component found; no governance framework documented in checklist |
| NFR completeness | ✅ PASS | Performance, Security, Retention confirmed |
| Observability | ✅ PASS | LMTA Strategy defined |
| README Quality | ✅ PASS | Root README.md present with prerequisites |
| Version Management | ❌ FAIL | dependabot.yml and renovate.json missing |
| Community Standards | ✅ PASS | LICENSE, SECURITY, and CODE_OF_CONDUCT present |
| PII Compliance | ✅ PASS | All credentials dynamically templated from env |

**Score:** 7.5/10  **Status:** PARTIALLY COMPLIANT

## Findings

### ❌ Gate 4 — AI Governance Missing
- **File:** .ai-arch/03_PRE_PROJECT_CHECKLIST.md
- **Finding:** ARCHITECTURE_OVERVIEW references Ollama. No runtime governance framework documented.
- **Remediation:** Document your AI governance framework in the Risk Register section.
  Minimum controls: anti-hallucination rules, prompt injection defence (structural fencing),
  context window bounding, phantom commitment prevention, mandatory audit logging,
  loop-breaking protocol.
- **Class:** DETERMINISTIC (AI component detected by grep)

### ⚠️ Gate 2 — ADR-003 Missing Rejected Alternatives
- **File:** .ai-arch/07_ARCHITECTURE_DECISIONS.md
- **Finding:** ADR-003 — pattern "**Rejected alternatives:**" not found.
- **Remediation:** Add minimum 2 rejected alternatives.
- **Class:** DETERMINISTIC (pattern match)
```

After each verify run, append to `AUDIT_SCORES.json`:

```json
{
  "date": "YYYY-MM-DD",
  "mode": "--fast",
  "gates": {"presence": "PASS", "adr_quality": "PARTIAL", "data_class": "PASS", "ai_governance": "FAIL", "nfr": "PASS", "observability": "PASS", "readme_quality": "PASS", "version_mgmt": "FAIL", "community_standards": "PASS", "pii_compliance": "PASS"},
  "score": 7.5
}
```

---

---

## MODE: `diagram`

Generate dynamic HTML/CSS charts in `.ai-arch/charts/`. **Do NOT use Mermaid.**

### Invocation

User names the diagram: "draw context diagram", "draw ERD", "draw sequence for [flow]", "draw deployment diagram", "draw state diagram for [entity]", "draw data flow", "draw container diagram".

If not explicitly requested, only `06_ARCHITECTURE_OVERVIEW.md` (the conceptual layer diagram) is generated — always mandatory.

### HTML Generation Rules

- **No Mermaid:** Build visual diagrams natively using HTML, CSS Grid, and CSS Flexbox. Avoid brittle absolute positioning.
- **Export Script:** Every generated `.html` chart MUST include `<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>` and a simple "Download as PNG" button at the top right of the UI.

### Mandatory conditions (rule-enforced)

| Diagram                  | Mandatory when                                                      |
| ------------------------ | ------------------------------------------------------------------- |
| `charts/erd.html`        | Relational DB confirmed in any ADR                                  |
| `charts/dataflow.html`   | Any data classified sensitive or sovereign in PRE_PROJECT_CHECKLIST |
| `charts/deployment.html` | Sovereign, edge, or hybrid infrastructure present                   |

### Sub-diagrams

**1. Context Diagram (C1) — `charts/context.html`**
System as single box at centre. External actors and services as surrounding boxes. Arrows show interaction direction and what flows. Nothing inside the system box — outside-in view only.

**2. Container Diagram (C2) — `charts/containers.html`**
Each major deployable unit as a box, labelled with technology (e.g., "React + Next.js", "FastAPI", "Ollama"). Arrows between units labelled with protocol. Every technology here must have a corresponding ADR in `07_ARCHITECTURE_DECISIONS.md`.

**3. Sequence Diagram — `charts/sequence_[flow_name].html`**
Vertical timelines or swimlanes per actor/component. Horizontal or flowing vertical blocks in order. Governance gates and HitL checkpoints shown as explicit steps. Max 15 interactions per diagram — break into sub-flows if longer.

**4. Deployment Diagram — `charts/deployment.html`**
Physical/virtual machines, containers, networks, security zones. Shows where each container runs. Network boundaries as nested CSS Grid rectangles. Data flow arrows labelled with what crosses each boundary and whether it's a trust/sovereignty boundary.

**5. State Diagram — `charts/state_[entity_name].html`**
States as nodes, transitions as arrows labelled with trigger event. Guards in square brackets [condition]. Governance gates as explicit states. One file per lifecycle entity. Only for entities whose lifecycle drives business logic.

**6. ERD — `charts/erd.html`**
Entities with key attributes laid out in grid cards. Relationships with cardinality. Primary and foreign keys marked. Any entity containing PII or sensitive data must be annotated with its classification level. Must align with data classification in PRE_PROJECT_CHECKLIST.

**7. Data Flow Diagram — `charts/dataflow.html`**
Data sources (left) → processing/transformation (middle) → destinations (right). Arrows labelled with what data moves and whether it crosses a trust or sovereignty boundary.

### Folder structure

```text
.ai-arch/
├── 01_README.md
├── 02_PROJECT_CONTEXT.md
├── 03_PRE_PROJECT_CHECKLIST.md
├── 04_ASSUMPTIONS.md
├── 05_COMPLEXITY_ANALYSIS.md
├── 06_ARCHITECTURE_OVERVIEW.md    ← always mandatory
├── 07_ARCHITECTURE_DECISIONS.md
├── 08_AI_ASSISTANCE_MAP.md
├── 09_API_REFERENCE.md
├── 10_OBSERVABILITY_STRATEGY.md
├── AUDIT_SCORES.json
├── pc2e/
│   ├── SYSTEM_LOG.md              ← PC2E Mandatory Audit Trail
│   ├── PORTS.md                   ← PC2E Mandatory Port Ledger
│   ├── Project_Context.md         ← PC2E Mandatory High-Level Service Map
│   └── SECURITY_FRAMEWORK.md      ← PC2E Mandatory Security Standards
└── charts/
    ├── context.html
    ├── containers.html
    ├── sequence_[flow].html
    ├── deployment.html
    ├── state_[entity].html
    ├── erd.html
    └── dataflow.html
```

---

---

## MODE: `audit`

Six-pillar code audit with CWE/OWASP citations and weighted comparable scoring.

### Step 1 — Determine scope

If path or context already specified, proceed. Otherwise ask: "What should I audit? (directory / feature branch / entire project)"

### Step 2 — Check for audit history

Read `.ai-arch/AUDIT_SCORES.json` if it exists. If present, show delta after scoring.

### Pillars

Execute all six in order. Severity levels: `CRITICAL`, `HIGH`, `MEDIUM`, `LOW`, `INFO`.

---

#### Pillar 1: Tech Debt

**Check for:**

- Dead code, unused imports, unused dependencies
- TODO/FIXME/HACK/XXX comments (count and categorise)
- Duplicated logic (copy-paste patterns)
- Overly complex functions (cyclomatic complexity > 10, functions > 50 lines)
- Outdated dependencies (major version behind)
- Missing or stale tests for critical paths
- Inconsistent naming conventions
- Hardcoded magic numbers or strings without constants
- Circular dependencies
- Missing error handling (bare catches, swallowed errors)

**Tools:** `grep_search` for TODOs/FIXMEs/hardcoded values, `list_dir` + `view_file` for structure/complexity, `run_command` for `npm outdated` or equivalent, ESLint MCP (`lint-files`) if available.

---

#### Pillar 2: Security

**Check for:**

- Hardcoded secrets (grep: `password=`, `api_key=`, `secret=`, `token=`, base64 credentials, bearer tokens)
- SQL injection (string concatenation in queries vs parameterised)
- XSS (unsanitised input rendered in HTML/JSX)
- CSRF (forms without tokens, missing SameSite cookies)
- Insecure dependencies (`npm audit` or equivalent)
- Missing auth/authorisation on routes
- Overly permissive CORS
- Missing rate limiting on public endpoints
- PII in logs
- Insecure file operations (path traversal, unrestricted uploads)
- Missing input validation on API boundaries
- Docker security (running as root, mounting docker.sock, privileged mode)
- GitHub Actions security:
  - Non-SHA pinned actions (CWE-1395: using tag-based actions instead of SHA hashes).
  - Excessive default permissions for GITHUB_TOKEN (e.g. missing `permissions: read-all` or explicit minimal scopes in workflow configs).
  - Raw secret exposure (CWE-798: writing secrets directly into run steps/logs).
  - Workflow command injection (CWE-94: evaluating untrusted variables like `github.event.issue.title` inside shell scripts without escaping/passing via env variables).

**Every security finding MUST cite:**

```text
- **CWE:** CWE-[ID] ([name])
- **OWASP:** A[NN]:2025 ([category name])
```

If no CWE/OWASP mapping: downgrade to `INFO`. Do not fabricate mappings.

**Reference table (embed, do not hallucinate IDs):**

| Issue                      | CWE      | OWASP 2025                                |
| -------------------------- | -------- | ----------------------------------------- |
| Hardcoded credentials      | CWE-798  | A07: Authentication Failures              |
| SQL injection              | CWE-89   | A05: Injection                            |
| XSS                        | CWE-79   | A05: Injection                            |
| CSRF                       | CWE-352  | A01: Broken Access Control                |
| Path traversal             | CWE-22   | A01: Broken Access Control                |
| Missing rate limiting      | CWE-770  | A06: Insecure Design                      |
| Missing auth on route      | CWE-306  | A07: Authentication Failures              |
| Insecure dependency        | CWE-1395 | A03: Software Supply Chain Failures       |
| PII in logs                | CWE-532  | A09: Security Logging & Alerting Failures |
| Overly permissive CORS     | CWE-942  | A02: Security Misconfiguration            |
| Missing input validation   | CWE-20   | A05: Injection                            |
| Privileged container       | CWE-250  | A02: Security Misconfiguration            |
| Uses tag-based action      | CWE-1395 | A03: Software Supply Chain Failures       |
| GITHUB_TOKEN write access  | CWE-250  | A02: Security Misconfiguration            |
| Workflow command injection | CWE-94   | A05: Injection                            |

**AI Component Detection (sub-check within Pillar 2):**

Grep for: `openai`, `anthropic`, `gemini`, `ollama`, `langchain`, `langgraph`, `crewai`, `agent`, `llm`, `inference`

If found and no governance documented:

```text
Severity: HIGH
CWE: CWE-1188 (Insecure Default Initialization — insufficient AI oversight)
OWASP: A02: Security Misconfiguration
Description: AI component detected without documented runtime governance framework.
Remediation: Apply a structured AI governance framework covering:
  - Anti-hallucination rules (verify before claiming, cite sources)
  - Prompt injection defence (wrap untrusted inputs in explicit structural fences)
  - Context window bounding (hard clamp num_ctx at API boundary to prevent VRAM exhaustion)
  - Loop-breaking protocol (detect and break agent runaway loops)
  - Phantom commitment prevention (no post-session notifications promised)
  - Mandatory audit logging (all AI decisions logged with rationale)
Document the chosen framework in .ai-arch/03_PRE_PROJECT_CHECKLIST.md Risk Register.
```

If a documented governance framework is already referenced/applied: downgrade to `INFO — AI governance present`.

**Tools:** `grep_search`, `run_command` for `npm audit`, `docker inspect`, `view_file` for workflow yaml configurations.

---

#### Pillar 3: Deployability

**Check for:**

- Missing or broken Dockerfile / docker-compose.yml
- Missing health check endpoints
- Missing or incomplete CI/CD configuration (e.g. GitHub Actions workflows)
- Environment-specific hardcoding (localhost URLs, hardcoded ports in app code)
- Missing `.env.example` or undocumented environment variables
- Build reproducibility (pinned versions, lockfile present)
- Missing graceful shutdown handling (SIGTERM/SIGINT)
- Database migration strategy
- Missing production logging
- Unnecessary dev dependencies in production image
- Missing resource limits in container config
- Rollback strategy documentation
- Mismatched or conflicting lockfiles (e.g. both `package-lock.json` and `pnpm-lock.yaml` in the same directory, causing deployment non-determinism).
- Out-of-sync lockfile (lockfile modified date older than package.json, or dependency mismatches).
- Mismatch between package manager commands in scripts (e.g. calling `npm run` when the codebase uses `pnpm`).
- Missing runtime configuration details or unpinned Node.js/Bun/Deno runtime engines block in `package.json`.
- Missing automated dependency update configuration (e.g. `.github/dependabot.yml` or `renovate.json`).

**Tools:** `view_file` for Dockerfiles, compose files, CI configs, package.json, and lockfiles. `grep_search` for hardcoded URLs/localhost and dependency manager commands. `list_dir` to verify expected files and detect duplicate lockfiles.

---

#### Pillar 4: Scalability

**Check for:**

- N+1 query patterns (ORM calls inside loops)
- Missing database indexes on filtered/joined columns
- Synchronous blocking operations in request handlers
- Missing caching strategy
- Monolithic coupling (no clear service boundaries)
- Missing pagination on list endpoints
- Large payloads without streaming
- Missing connection pooling
- Single points of failure (no failover)
- Missing queue/async processing for heavy operations
- Unbounded data growth without archival
- Missing observability (no metrics, no tracing)

**Tools:** `grep_search` for query patterns, `view_file` for DB queries and API handlers.

---

#### Pillar 5: Privacy (PDPA/GDPR)

**Check for:**

- PII collection without documented purpose (names, emails, phone, NRIC, addresses)
- Missing data retention policies
- PII in logs, error messages, stack traces
- Missing encryption at rest and in transit
- Missing consent mechanisms
- Missing data subject access/deletion capabilities
- Cross-border data transfer without safeguards
- Third-party sharing without data processing agreements
- Overly broad data collection
- Missing anonymisation/pseudonymisation for analytics
- Missing audit trail for PII access

**Tools:** `grep_search` for PII field patterns (email, phone, nric, address in schemas), `view_file` for data models and API responses.

---

#### Pillar 6: Observability

**Check for:**

- Missing structured logging framework (e.g., Winston, Pino, Serilog)
- Missing distributed tracing (e.g., OpenTelemetry, Jaeger, Zipkin)
- Missing metrics exposure (e.g., Prometheus `/metrics` endpoint)
- Missing comprehensive health endpoints (`/health/liveness`, `/health/readiness`)
- Hardcoded log destinations instead of stdout/stderr
- Uncaught exception handlers missing logging
- Missing alert routing definitions
- Lack of correlation IDs across distributed boundaries

**Tools:** `grep_search` for logger configurations, OpenTelemetry SDKs, health endpoints, and `view_file` for observability strategy (`10_OBSERVABILITY_STRATEGY.md`).

---

### Step 3 — Score and output

**Weighting formula:**

```text
Pillar weights (sum = 100%):
  Security:       25%
  Tech Debt:      20%
  Deployability:  15%
  Privacy:        15%
  Observability:  15%
  Scalability:    10%

Per-finding deductions (pillar score starts at 10, minimum 0):
  CRITICAL: -3.0
  HIGH:     -2.0
  MEDIUM:   -0.5
  LOW:      -0.1

Weighted overall = Σ (pillar_score × pillar_weight)
```

This formula is fixed. Every audit uses it. Two audits of 

…(truncated)
