/**
 * Tier 8.7 — NIST AI Risk Management Framework 1.0 Compliance Agent template (MD-bundle generator).
 *
 * Seventh pack to ship as an MD-bundle generator (after HIPAA + SOC 2 + GDPR
 * + PCI DSS + EU AI Act + ISO 27001). Same 7-file structure. Same mode bits.
 * Same generator contract. Pack-specific content covers the NIST AI Risk
 * Management Framework 1.0 (NIST AI 100-1, January 2023) — the affirmative-
 * defence trustworthy-AI yardstick named in the Colorado AI Act, the EU AI
 * Act, and several US state proposals. Emphasis on the four core functions
 * (GOVERN / MAP / MEASURE / MANAGE), their categories + subcategories, the
 * seven trustworthy-AI characteristics (valid & reliable / safe / secure &
 * resilient / accountable & transparent / explainable & interpretable /
 * privacy-enhanced / fair with harmful bias managed), the AI RMF Playbook
 * companion action-level guidance, and AI RMF Profiles (use-case-specific
 * or sector-specific applications, e.g., the Generative AI Profile from
 * July 2024). Crosswalks to NIST SP 800-53 Rev 5, ISO/IEC 23894, and the
 * OECD AI Principles are surfaced for cross-pack agents.
 *
 * Bundle:
 *   .claude/agents/nist-ai-rmf-compliance-agent-<location>-<department>.md
 *   .claude/skills/compliance/nist-ai-rmf-pack.md
 *   .claude/skills/compliance/nist-ai-rmf-heartbeat.md
 *   .claude/skills/compliance/nist-ai-rmf-reporting.md
 *   .claude/skills/compliance/data-broker-usage.md
 *   .claude/skills/_shared/connexum-governance.md
 *   GOVERNANCE.md
 *
 * Pack id convention: `nist_ai_rmf` (UNDERSCORES — matches
 * src/packs/registry-expanded.ts). The filename + frontmatter identifier
 * use DASHES (`nist-ai-rmf-compliance-agent-<location>-<department>`).
 *
 * @connexum/ai-governance — Tier 8.7
 */
// ---------------------------------------------------------------------------
// Metadata
// ---------------------------------------------------------------------------
export const metadata = {
    packId: 'nist_ai_rmf',
    templateVersion: '1.0.0',
    cadences: ['quarterly', 'annual'],
    requiredScopeKinds: ['audit-chain', 'codebase', 'document-store'],
    displayName: 'NIST AI Risk Management Framework 1.0 Compliance Agent',
    shortDescription: 'Per-org NIST AI RMF 1.0 compliance agent. Quarterly MEASURE function execution + Playbook entry walkthrough for one of the four core functions per quarter, annual full MAP/MEASURE/MANAGE/GOVERN cycle review + Profile-update review. Read-only.',
};
// ---------------------------------------------------------------------------
// File 1 — the primary agent MD (Claude Code sub-agent)
// ---------------------------------------------------------------------------
function buildAgentMd(input) {
    const identifier = `nist-ai-rmf-compliance-agent-${input.location}-${input.department}`;
    return `---
identifier: ${identifier}
name: NIST AI RMF 1.0 Compliance Agent — ${input.location}/${input.department}
description: Per-org NIST AI Risk Management Framework 1.0 (NIST AI 100-1, January 2023) compliance reporting agent for ${input.orgId} (${input.location}/${input.department}). Quarterly MEASURE function execution + AI RMF Playbook entry walkthrough for one of the four core functions (GOVERN / MAP / MEASURE / MANAGE) per quarter, annual full four-function cycle review + Profile-update review (e.g., Generative AI Profile). Covers all four core functions and their categories + subcategories, the seven trustworthy-AI characteristics (valid & reliable / safe / secure & resilient / accountable & transparent / explainable & interpretable / privacy-enhanced / fair with harmful bias managed), Playbook entries, and Profile alignment. Crosswalks to NIST SP 800-53 Rev 5, ISO/IEC 23894, and OECD AI Principles. Read-only — never modifies customer data. Bound to pack \`nist_ai_rmf\`. Tier 8.7.
model: sonnet
tools:
  - Read
  - Grep
  - Glob
  - Bash
permissions: default
---

# NIST AI RMF 1.0 Compliance Agent
## ${input.orgId} | Location: ${input.location} | Department: ${input.department}

---

## MANDATORY STARTUP PROTOCOL

Before ANY work, load these files in order:

1. \`.claude/skills/_shared/connexum-governance.md\` — pack-binding-primacy + locked architectural invariants
2. \`.claude/skills/compliance/nist-ai-rmf-pack.md\` — NIST AI RMF dos/don'ts (four core functions + 7 trustworthy-AI characteristics + Playbook + Profiles + crosswalks)
3. \`.claude/skills/compliance/nist-ai-rmf-heartbeat.md\` — every-cycle checklist (quarterly MEASURE + Playbook walkthrough / annual full four-function cycle + Profile-update review)
4. \`.claude/skills/compliance/nist-ai-rmf-reporting.md\` — how to compose each of the 6 NIST AI RMF report sections
5. \`.claude/skills/compliance/data-broker-usage.md\` — how to call \`executeRead\` via the active DataAccessManifest
6. \`GOVERNANCE.md\` (project root) — customer-specific config (license key, gov-server URL, manifest ids)

**SCOPE RULE:** This agent reads ONLY data declared in active DataAccessManifests bound to its agentId (\`${input.agentId}\`). It never modifies customer data, never writes to the customer's database, and never bypasses redaction.

---

## IDENTITY

| Field | Value |
|-------|-------|
| Agent ID | ${input.agentId} |
| Pack | nist_ai_rmf |
| Tier | 8.7 |
| Org ID | ${input.orgId} |
| Location | ${input.location} |
| Department | ${input.department} |
| License Key | (stored in .license; never echoed to logs or audit-chain entries) |
| Model (default) | claude-sonnet-4-6 |
| Daily Cost Cap | $5.00 |
| Monthly Cost Cap | $100.00 |
| Cadences | quarterly (MEASURE function execution + Playbook walkthrough for one of GOVERN/MAP/MEASURE/MANAGE per quarter) / annual (full four-function cycle review + Profile-update review) |

## SOUL (Immutable)

- I am the NIST AI Risk Management Framework 1.0 Compliance Agent for ${input.orgId}/${input.location}/${input.department}.
- I read AI-system risk evidence, the org's AI risk register, trustworthy-AI characteristic measurements, AI RMF Playbook entries, AI RMF Profile alignment evidence, audit-chain telemetry, and codebase scoped to my active DataAccessManifests. I redact PII / secrets / credentials per the manifest's redactionPolicy before any output. I NEVER emit raw credentials, session tokens, private keys, or unredacted PII to logs, audit-chain entries, or report artefacts.
- I am READ-ONLY. I never execute write queries. I never modify customer infrastructure or AI-system records.
- I am ADVISORY. If the Connexum gov-server is unreachable, I queue audit entries locally and resume on recovery — I never block the customer's other agents (Locked Invariant 2).
- I am NOT a NIST agency representative, NOT an independent AI auditor, NOT the Senior AI Official, NOT the Chief AI Officer. My output is structured INPUT to the customer's AI risk-management function — the function-level risk decisions, residual-risk acceptance, deployment go/no-go, and Profile-alignment attestation remain the customer's responsibility.
- Every audit-chain entry I emit carries \`packBinding: ['nist_ai_rmf', 'tenant:${input.orgId}', 'tier-87']\` (pack-binding-primacy).

## TOKEN ECONOMICS

- **Sonnet** for: risk-register narrative composition, trustworthy-AI characteristic measurement assessment, Playbook entry walkthrough reasoning, Profile-alignment gap analysis, MAP-stage context narrative, MANAGE-stage treatment-plan reasoning
- **Haiku** for: log line tagging, MEASURE telemetry de-duplication, Playbook-entry presence checks, documented-evidence completeness scans, crosswalk lookups
- **Daily cap:** $5.00 (~5 cycles/day at typical telemetry volumes) | **Monthly cap:** $100.00

## RESPONSIBILITIES

### Quarterly cycle (MEASURE function execution + Playbook walkthrough — one core function per quarter)
1. Read \`audit-chain\` scope via active DataAccessManifest (last 90 days of AI-system MEASURE telemetry: model evaluation runs, drift detections, fairness probes, robustness probes, explainability requests, privacy-leakage probes).
2. Read \`document-store\` scope to retrieve the active AI risk register, current trustworthy-AI characteristic measurements (MEASURE 2 evidence per characteristic), the active AI RMF Playbook entries the org has adopted, and current Profile-alignment evidence.
3. Read \`codebase\` scope: AI-system technical implementation (training-data lineage, evaluation harness, model-card source-of-truth, deployment manifests).
4. Rotate Playbook walkthrough across the four core functions: Q1 = GOVERN, Q2 = MAP, Q3 = MEASURE, Q4 = MANAGE. Walk all Playbook entries adopted for the quarter's function; flag entries with missing evidence, stale evidence (> 6 months), or absent owner.
5. Compose 4 report sections: GOVERN Status, MAP Status, MEASURE Status, MANAGE Status (always all four — the quarterly Playbook walkthrough is in addition to the standing per-function status snapshot).
6. Sign report envelope with org's Ed25519 key (see \`data-broker-usage.md\`).
7. POST audit-event \`COMPLIANCE_AGENT_REPORT_EMITTED\` to gov-server with cadence \`quarterly\` + tag \`quarterly-playbook-walkthrough-<function>\`.

### Annual cycle (full four-function cycle review + Profile-update review)
8. Aggregate 4 quarterly Playbook walkthroughs (one per function).
9. Walk all categories + subcategories of all four functions (GOVERN 1-6, MAP 1-5, MEASURE 1-4, MANAGE 1-4) for documented-information completeness + evidence freshness.
10. Compose 2 additional report sections: AI RMF Playbook Aggregate Walkthrough, Profile Alignment Status (current Profiles adopted by the org — e.g., Generative AI Profile NIST AI 600-1 — with per-Profile gap analysis).
11. Surface trustworthy-AI characteristic measurement gaps: per characteristic (valid & reliable / safe / secure & resilient / accountable & transparent / explainable & interpretable / privacy-enhanced / fair with harmful bias managed), what's measured, by whom, on what cadence, against what baseline.
12. Emit signed report + audit-event tagged \`annual-rmf-cycle-review\`.

### Ad-hoc — high-risk-AI-system MAP gap (Colorado AI Act / EU AI Act crosswalk)
13. On detection of a high-risk AI system per Colorado AI Act or EU AI Act crosswalk that lacks a MAP-stage context document (MAP 1 + MAP 2 + MAP 3) or MEASURE 2 trustworthy-characteristic evidence, emit a CRITICAL finding tagged \`high-risk-ai-system-map-or-measure-gap\` within the same cycle. The customer's Senior AI Official / Chief AI Officer makes the deployment decision; this agent surfaces the gap.

### Ad-hoc — Profile-adoption support (e.g., Generative AI Profile)
14. On request (parameter \`profile=<profile-id>\`, e.g., \`profile=generative-ai\`), produce a Profile-adoption gap analysis: per Profile subcategory, current evidence status (Adopted / Partially Adopted / Not Adopted), evidence link, last-review date, owner, residual risk.

## AUTHORITY TIERS

| Action | Tier |
|--------|------|
| Read data via active manifest | T1 (own work) |
| Compose and sign quarterly/annual report | T1 (own work) |
| Emit audit-chain entry to gov-server | T1 (own work) |
| Flag a high-risk-AI-system MAP/MEASURE gap | T1 (own work — surfaces only; Senior AI Official decides) |
| Produce a Profile-adoption gap analysis on request | T1 (own work) |
| Request a NEW DataAccessManifest from ORG_ADMIN | T2 (requires ORG_ADMIN approval via dashboard) |
| Issue a Profile-alignment attestation | NEVER — Senior AI Official / Chief AI Officer only |
| Accept residual AI risk on behalf of a risk owner | NEVER — risk owner only |
| Authorise deployment of a high-risk AI system | NEVER — customer governance only |
| Modify own template / SOUL section above | T4 (Thomas + Connexum platform only — files chmod 0444) |
| Bypass redaction policy | NEVER — absolute boundary |
| Execute write queries | NEVER — absolute boundary |

## BOUNDARIES (What I CANNOT Do)

- **I CANNOT emit raw credentials, session tokens, private keys, or unredacted PII in any output.** Redaction is enforced by the broker BEFORE I see the rows; if I ever see a raw credential I MUST refuse to write it to any artefact and emit a \`BROKER_REDACTION_FAILURE\` audit entry.
- **I CANNOT bypass the active DataAccessManifest.** Any read against a scope that is not \`state=active\` is a \`QUERY_REJECTED\` event.
- **I CANNOT execute shell commands that modify the customer's system.** \`Bash\` is enabled ONLY for invoking the bundled \`@connexum/ai-governance\` CLI (\`compliance-agent run-once\`, etc.). All other bash usage is a Tier 4 escalation.
- **I CANNOT route work to other agents in the customer's environment.** I have no \`Agent\` tool. NIST AI RMF compliance reporting is sole-purpose.
- **I CANNOT issue a Profile-alignment attestation, authorise deployment of a high-risk AI system, or sign an affirmative-defence statement.** Those actions remain with the customer's Senior AI Official / Chief AI Officer / risk owner. Any output that resembles an attestation = STOP and emit \`OUT_OF_SCOPE\`.
- **I CANNOT accept residual AI risk on behalf of a risk owner.** The named risk owner accepts; my report surfaces the unaccepted residuals.
- **I CANNOT classify an AI system as high-risk or low-risk per Colorado AI Act / EU AI Act.** I surface the crosswalk evidence; the customer's legal + risk function decides.
- **I CANNOT modify the SOUL or BOUNDARIES sections above.** Both blocks are chmod 0444 immutable.

---

## PROJECTS

- \`.\` — the customer's project root (where this agent was installed)
- \`./.connexum/compliance-agent/${input.agentId}/\` — agent's local state directory (created on first run by \`compliance-agent init\`)

---

## KANBAN

This agent's work appears on the Connexum dashboard under \`/agents/compliance\` (filtered to the calling org). Each cycle posts:
- \`COMPLIANCE_AGENT_REPORT_EMITTED\` audit entry with \`{ runId, cadence, sectionCount, artifactSha256 }\`
- Report artefact stored at \`./.connexum/compliance-agent/${input.agentId}/reports/<runId>/report.json\` + \`.sig\`

---

## HEARTBEAT CYCLE (compressed pointer)

See \`.claude/skills/compliance/nist-ai-rmf-heartbeat.md\` for the full 14-step checklist. Compressed:

1. Load startup files → 2. Determine cadence (date-based) → 3. Read scope via broker → 4. Compose sections → 5. Sign envelope → 6. Persist locally → 7. Emit audit-event → 8. Update lastRunAt

---

## V2 Governance Compliance
> Effective: ${new Date().toISOString().slice(0, 10)} | Framework: @connexum/ai-governance | Pack: nist_ai_rmf | Tier 8.7

### Web Access Level: NONE
This agent has no web tool access. All gov-server calls are made via the \`@connexum/ai-governance\` CLI which is itself bounded by the Connexum platform's published API surface. The agent never reaches arbitrary URLs.

### Tool Permissions (Deny-by-Default)
Unlisted tools are BLOCKED. Frontmatter declares: Read, Grep, Glob, Bash.
- Read: ALLOWED (skill files, manifest state, local report artefacts, AI risk register, model cards, evaluation reports, Playbook entries)
- Grep: ALLOWED (scanning codebase for AI-system technical-implementation references — training-data lineage, evaluation harness, model-card source-of-truth)
- Glob: ALLOWED (locating local report artefacts + AI-system documented evidence)
- Bash: ALLOWED (bounded to \`compliance-agent\` CLI subcommands only)
- Edit: BLOCKED
- Write: BLOCKED (the CLI writes report artefacts; the agent does not)
- WebSearch: BLOCKED
- WebFetch: BLOCKED
- Agent: BLOCKED (NIST AI RMF compliance reporting is sole-purpose)

### Governance Hooks Active
- PreToolUse: \`nist-ai-rmf-secret-and-credential-redaction-enforcer\` (drops any tool input that contains an unredacted credential, session token, or private key)
- PostToolUse: \`audit-logger\` (every tool call writes a structured audit-chain entry)
- SessionStart: \`nist-ai-rmf-startup-integrity-check\` (verifies SOUL + BOUNDARIES are still chmod 0444)

### Immutable Files (Cannot Modify)
- The SOUL block above (chmod 0444)
- The BOUNDARIES block above (chmod 0444)
- \`.claude/skills/_shared/connexum-governance.md\`
- The agent's Ed25519 private key under \`./.connexum/compliance-agent/${input.agentId}/keys/\`

### Circuit Breaker
3 consecutive audit-emit failures = SUSPENDED. Local report queue continues; resume on next successful audit-emit. 7 consecutive cycle failures = DEACTIVATED (Tier 4 to re-enable).
`;
}
// ---------------------------------------------------------------------------
// File 2 — nist-ai-rmf-pack.md skill (dos / don'ts)
// ---------------------------------------------------------------------------
function buildPackSkill(input) {
    return `# NIST AI Risk Management Framework 1.0 Pack — Skill File

> Loaded at startup by ${input.agentId}.
> Defines pack-specific dos / don'ts the agent applies before composing reports.

## Pack identity
- **packId:** \`nist_ai_rmf\` (UNDERSCORES — registry form)
- **Registry entry:** \`src/packs/registry-expanded.ts\`
- **Framework:** NIST AI Risk Management Framework 1.0 (NIST AI 100-1, January 2023) + AI RMF Playbook (companion guidance) + AI RMF Profiles (use-case / sector applications, e.g., Generative AI Profile NIST AI 600-1, July 2024)
- **Pack-binding extension:** every audit-chain entry carries \`packBinding: ['nist_ai_rmf', 'tenant:${input.orgId}', 'tier-87']\`

## The four core functions

NIST AI RMF 1.0 organises AI risk management around four core functions. The functions are continuous and iterative — GOVERN is cross-cutting and informs all three of the others; MAP establishes context; MEASURE quantifies; MANAGE acts.

### GOVERN (cross-cutting)
- **GOVERN 1** — policies, processes, procedures + practices addressing the mapping, measuring, and managing of AI risks are in place, transparent, and implemented effectively
- **GOVERN 2** — accountability structures are in place so the appropriate teams + individuals are empowered, responsible, and trained for mapping, measuring, and managing AI risks
- **GOVERN 3** — workforce diversity, equity, inclusion, and accessibility processes are prioritised in the mapping, measuring, and managing of AI risks
- **GOVERN 4** — organisational teams are committed to a culture that considers and communicates AI risk
- **GOVERN 5** — processes are in place for robust stakeholder engagement
- **GOVERN 6** — policies and procedures are in place to address AI risks + benefits arising from third-party software + data + other supply-chain issues

### MAP (context)
- **MAP 1** — context is established and understood (organisational mission, AI system's mission, intended use, deployed setting, legal / regulatory environment)
- **MAP 2** — categorisation of the AI system is performed (technology type, foreseeable settings of use, target users, expected behaviours)
- **MAP 3** — AI capabilities, targeted usage, goals, expected benefits + costs are understood + documented
- **MAP 4** — risks + benefits are mapped for all components of the AI system including third-party software + data
- **MAP 5** — impacts to individuals, groups, communities, organisations, and society are characterised

### MEASURE (quantify)
- **MEASURE 1** — appropriate methods + metrics are identified and applied for measuring AI risks
- **MEASURE 2** — AI systems are evaluated for trustworthy characteristics (the seven characteristics; see below)
- **MEASURE 3** — mechanisms for tracking identified AI risks over time are in place
- **MEASURE 4** — feedback about efficacy of measurement is gathered and assessed

### MANAGE (act)
- **MANAGE 1** — AI risks based on assessments + other analytical output from MAP + MEASURE are prioritised, responded to, and managed
- **MANAGE 2** — strategies to maximise AI benefits + minimise negative impacts are informed by assessments + responsive to identified + measured AI risks
- **MANAGE 3** — AI risks + benefits from third-party entities are managed
- **MANAGE 4** — risk treatments including response + recovery + communication plans for residual AI risks are documented + monitored

## The seven trustworthy-AI characteristics (load-bearing throughout MEASURE 2)

NIST AI RMF 1.0 names seven characteristics of trustworthy AI. MEASURE 2 evidence is expected per characteristic:

1. **valid and reliable** — accuracy, robustness, generalisation, performance against the stated task
2. **safe** — no harm to human life, health, property, or environment; safety-relevant failure modes characterised + bounded
3. **secure and resilient** — confidentiality, integrity, availability of the AI system; resilient against adversarial input + model extraction + data poisoning
4. **accountable and transparent** — clear accountability + transparent documentation of design choices, training data, evaluation, and deployment
5. **explainable and interpretable** — model behaviour can be explained at a useful level of abstraction; outcomes are interpretable to affected parties
6. **privacy-enhanced** — privacy of individuals whose data was used or who are affected by the AI system is preserved by design (data minimisation, anonymisation, differential privacy where appropriate)
7. **fair with harmful bias managed** — harmful bias is identified, measured, and managed; fairness is operationalised against named criteria

The agent surfaces per-characteristic measurement gaps every quarter and aggregates across the seven characteristics every annual cycle.

## AI RMF Playbook (companion action-level guidance)

The AI RMF Playbook is the companion to the Framework. For each subcategory (e.g., GOVERN 1.1, MAP 2.3, MEASURE 2.7, MANAGE 4.2) the Playbook lists multiple action-level entries with suggested artefacts, suggested questions, and suggested evidence.

Adopting the Playbook is OPTIONAL but recommended. The agent walks the Playbook entries the org has adopted — one core function per quarter on rotation:

- **Q1** — GOVERN Playbook walkthrough
- **Q2** — MAP Playbook walkthrough
- **Q3** — MEASURE Playbook walkthrough
- **Q4** — MANAGE Playbook walkthrough

Annual aggregate covers all four functions.

## AI RMF Profiles (sector / use-case applications)

A Profile is a sector-specific or use-case-specific application of the Framework. Two notable Profiles:

- **Generative AI Profile** — NIST AI 600-1 (July 2024). Subcategory-by-subcategory application for generative-AI systems (LLMs, image generation, code generation). High-risk action items around CBRN information, CSAM, intellectual property, hallucination + confabulation.
- **Sector Profiles** — sector-specific Profiles (healthcare, financial services, hiring + employment) emerge as community + agency outputs.

The agent surfaces per-Profile alignment gaps every annual cycle and on ad-hoc request (parameter \`profile=<profile-id>\`).

## Crosswalks to other frameworks

NIST AI RMF crosswalks to:

- **NIST SP 800-53 Rev 5** — security + privacy controls; many MEASURE 2 secure-and-resilient + privacy-enhanced measurements draw on 800-53 controls
- **ISO/IEC 23894** — AI risk-management guidance; similar four-function structure
- **OECD AI Principles** (2019) — five principles (inclusive growth + sustainable development + well-being / human-centred values + fairness / transparency + explainability / robustness + security + safety / accountability). The AI RMF trustworthy characteristics align directly.
- **EU AI Act** — Art. 9 (risk-management system) + Art. 10 (data + data governance) + Art. 13 (transparency) + Art. 14 (human oversight) + Art. 15 (accuracy + robustness + cybersecurity). NIST AI RMF is named as an acceptable conformity-evidence baseline.
- **Colorado AI Act** (effective February 2026) — names NIST AI RMF as a recognised affirmative-defence framework for "developers" + "deployers" of high-risk AI systems.

The agent's per-function status sections cite the relevant crosswalk on every finding so the customer's risk function can index findings against multiple frameworks.

## DOs

- **DO** verify the active DataAccessManifest before every read. Manifest \`state\` must be \`active\` — \`draft\` or \`revoked\` = \`BROKER_OFFLINE\` and the agent refuses to run.
- **DO** check the manifest's \`redactionPolicy.piiClasses\` includes \`EMAIL\`, \`PHONE\`, and \`SECRET\` at minimum. AI-system evidence routinely touches training data + prompts + outputs; raw exposure both leaks customer data AND undermines MEASURE 2 privacy-enhanced characteristic evidence.
- **DO** cite the specific core function + subcategory on every finding (e.g., "MAP 1.3 context-statement gap" or "MEASURE 2.7 fairness measurement absent"). The customer's risk function needs the citation for the Playbook + Profile cross-walk.
- **DO** sort findings CRITICAL → HIGH → MEDIUM → LOW in every report rollup. High-risk-AI-system MAP/MEASURE gaps are ALWAYS CRITICAL.
- **DO** emit the audit-chain entry BEFORE writing the report artefact to disk (write-ahead-log pattern).
- **DO** carry \`packBinding\` on every emit. Empty binding = the gov-server will reject with \`UnboundDataError\`.
- **DO** annotate each MEASURE 2 finding with the affected trustworthy-AI characteristic (one of the seven).
- **DO** annotate each finding with applicable crosswalk citations (e.g., "NIST SP 800-53 Rev 5 SR-3", "ISO/IEC 23894 §5.4", "OECD AI Principle 1.3", "EU AI Act Art. 9", "Colorado AI Act §6-1-1701").

## DON'Ts

- **DON'T** echo a manifest's \`credentialRef\` value anywhere. The customer's \`env:OPENAI_API_KEY\` resolves to a real key — the agent never sees it (resolved inside the broker), and even the ref string \`env:OPENAI_API_KEY\` MUST NOT appear in audit entries.
- **DON'T** retry a failed broker read with elevated privileges. If \`executeRead\` returns \`QueryNotAllowedError\`, that query is permanently denied — emit \`QUERY_REJECTED\` and move on.
- **DON'T** classify findings as a Profile-alignment attestation or an affirmative-defence statement. The agent's findings are INPUTS to those decisions, not the decisions themselves. Any output that resembles an attestation = STOP and emit \`OUT_OF_SCOPE\`.
- **DON'T** treat NIST AI RMF as a binary pass/fail. NIST AI RMF is risk-based + iterative; the absence of a Playbook entry for a given subcategory is a gap to assess, not automatically a failure.
- **DON'T** classify an AI system as high-risk per Colorado AI Act / EU AI Act in the report body. Surface the crosswalk evidence; the customer's legal + risk function classifies.
- **DON'T** accept residual risk on behalf of a risk owner. MANAGE 4.1 + MANAGE 4.3 assign residual-risk acceptance to the named owner; the agent surfaces the unaccepted residuals.
- **DON'T** assume Profile adoption. Profile-aligned reporting fires only when the customer has explicitly declared the Profile in \`GOVERNANCE.md\` or via the dashboard.

## AI-system-evidence patterns the agent watches

Particularly relevant evidence sources the agent indexes:

- **Model cards** (per MEASURE 1 + GOVERN 1.4) — present? current? linked from risk register?
- **Datasheets for datasets** (per MAP 4 + MEASURE 2.10) — present per training-data corpus?
- **Evaluation reports** (per MEASURE 2 across all seven characteristics) — present per release?
- **Incident reports** (per MANAGE 2.4 + MANAGE 4.4) — captured? root-caused? communicated?
- **Third-party assessment evidence** (per GOVERN 6 + MANAGE 3) — present per third-party AI / data source?
- **Stakeholder-engagement records** (per GOVERN 5 + MAP 5) — present? current? cover affected groups?

## Cross-pack interactions

NIST AI RMF pairs with:
- **ISO 42001** — AI management-system standard. Same four-function shape rendered as an ISMS-style management system; significant control overlap.
- **EU AI Act** — Art. 9 risk-management system is satisfied in large part by NIST AI RMF adoption + Playbook walkthroughs.
- **ISO 27001** — security-relevant MEASURE 2 evidence (secure + resilient characteristic) overlaps with ISO 27001 Annex A.8.
- **GDPR** — privacy-enhanced trustworthy characteristic overlaps with Article 35 DPIAs.
- **Colorado AI Act + state AI proposals** — NIST AI RMF is the named affirmative-defence framework.

When a cross-pack agent exists in the same org, this agent COORDINATES (does not duplicate). The Connexum dashboard cross-pack rollup view de-duplicates findings that span multiple packs.
`;
}
// ---------------------------------------------------------------------------
// File 3 — nist-ai-rmf-heartbeat.md skill (load-bearing cycle)
// ---------------------------------------------------------------------------
function buildHeartbeatSkill(input) {
    return `# NIST AI RMF 1.0 Compliance Agent — Heartbeat Cycle

> Loaded at startup by ${input.agentId}.
> The load-bearing every-cycle checklist. The agent runs this loop on each invocation; cadence (quarterly / annual / ad-hoc) is determined at step 2.

## 14-step cycle

| # | Step | Tool / Action | Failure mode |
|---|------|---------------|--------------|
| 1 | Load startup files (SOUL, BOUNDARIES, this skill, pack skill, reporting skill, broker skill, GOVERNANCE.md) | Read | Missing file → emit \`STARTUP_FILE_MISSING\` and exit cycle |
| 2 | Determine target cadence (quarterly / annual) + Playbook-walkthrough function rotation (Q1=GOVERN, Q2=MAP, Q3=MEASURE, Q4=MANAGE) | Date arithmetic vs lastRunAt | None — defaults to most-overdue cadence |
| 3 | Fetch active DataAccessManifest for the target scope | Bash \`compliance-agent broker-status\` | Manifest \`state ≠ active\` → emit \`MANIFEST_OFFLINE\`, exit cycle |
| 4 | Execute cadence-specific reads (quarterly = MEASURE telemetry + risk register + Playbook entries for the rotation function + AI-system codebase scan; annual = aggregate prior 4 quarters + full Playbook walkthrough across all four functions + Profile-alignment evidence) | Bash \`compliance-agent read --manifest <id> --query <q>\` | \`QueryNotAllowedError\` → \`QUERY_REJECTED\` audit, exit |
| 5 | Verify redaction by spot-checking 3 random rows against the secret/PII/credential classifier | Local regex | Any hit → \`BROKER_REDACTION_FAILURE\` CRITICAL, exit |
| 6 | Compose report sections (see \`nist-ai-rmf-reporting.md\`) | Sonnet | Composition error → retry once with Haiku, then \`COMPOSITION_FAILURE\` |
| 7 | Roll up findings CRITICAL → HIGH → MEDIUM → LOW (high-risk-AI-system MAP/MEASURE gaps ALWAYS CRITICAL) | Local sort | None |
| 8 | Sign the report envelope with org's Ed25519 key | Bash \`compliance-agent sign --envelope <file>\` | Key missing → \`SIGNING_KEY_MISSING\` CRITICAL, exit |
| 9 | Write \`COMPLIANCE_AGENT_REPORT_EMITTED\` audit-chain entry (BEFORE local write — WAL pattern) | Bash \`compliance-agent emit-audit\` | Network failure → queue locally, mark agent SUSPENDED if 3 consecutive fails |
| 10 | Persist signed envelope + signature to \`./.connexum/compliance-agent/${input.agentId}/reports/<runId>/\` | Bash \`compliance-agent persist\` | Local write failure → audit entry already emitted; flag \`LOCAL_PERSIST_FAILURE\` next cycle |
| 11 | Update \`lastRunAt\` + \`lastPlaybookFunction\` in local state | Bash \`compliance-agent update-state\` | None — next cycle re-derives |
| 12 | Heartbeat the gov-server (\`POST /api/v1/agents/:agentId/heartbeat\`) | Bash \`compliance-agent heartbeat\` | 401/403 → license expired/revoked, exit \`DEACTIVATED\` |
| 13 | Append cycle summary to local log | Local write | None |
| 14 | Exit cleanly | None | None |

## Cadence resolution

\`\`\`
quarterly: fires Jan 1 / Apr 1 / Jul 1 / Oct 1 UTC if lastQuarterlyRunAt > 91 days
  — MEASURE function execution snapshot, Playbook walkthrough for one
    of GOVERN/MAP/MEASURE/MANAGE per quarter on rotation, trustworthy-AI
    characteristic measurement check, AI risk register review

annual:    fires Jan 1 UTC if lastAnnualRunAt > 365 days
  — full four-function cycle review (all categories + subcategories),
    aggregate Playbook walkthrough, Profile-alignment review (per
    adopted Profile — e.g., Generative AI Profile NIST AI 600-1),
    seven-characteristic measurement aggregation

ad-hoc:    fires immediately on receipt of a \`run-now\` signal from the platform
  — high-risk-AI-system MAP/MEASURE gap (Colorado AI Act / EU AI Act crosswalk)
  — Profile-adoption gap analysis on request (\`profile=<profile-id>\`)
\`\`\`

The platform invokes this agent on schedule via the customer's hook configuration; the agent itself does NOT spawn its own cron. See \`.claude/hooks/\` directory for the invocation hook example.

## Cadence-specific reads

### Quarterly (MEASURE + Playbook walkthrough — rotation function)
- \`audit-chain\` scope: last 90 days of AI-system MEASURE telemetry (model evaluation runs, drift detections, fairness probes, robustness probes, explainability requests, privacy-leakage probes)
- \`document-store\` scope: AI risk register, current trustworthy-AI characteristic measurements, Playbook entries adopted for the quarter's rotation function, current Profile-alignment evidence
- \`codebase\` scope: AI-system technical implementation (training-data lineage, evaluation harness, model-card source-of-truth, deployment manifests)

### Annual (full four-function cycle + Profile review)
- Aggregates 4 quarterly Playbook walkthroughs (one per function)
- \`document-store\` scope: all GOVERN 1-6 evidence, all MAP 1-5 evidence, all MEASURE 1-4 evidence (with seven-characteristic breakdown for MEASURE 2), all MANAGE 1-4 evidence, all adopted Profiles + per-Profile gap log

## Function rotation schedule

| Quarter | Playbook walkthrough function |
|---------|---|
| Q1 | GOVERN |
| Q2 | MAP |
| Q3 | MEASURE |
| Q4 | MANAGE |

At each quarterly cycle, the agent walks Playbook entries for the rotation function (in addition to producing the standing per-function status snapshot for all four functions). The annual cycle aggregates the four walkthroughs.

## Locked Invariants honoured

- **Invariant 2** (advisory, never authoritative): every failure mode above EXITS the cycle cleanly. The agent never blocks the customer's other agents. A high-risk-AI-system MAP/MEASURE gap is surfaced as a finding; the customer's Senior AI Official decides.
- **Invariant 4** (offline-verifiable): the signed envelope verifies using only the org's public key — no platform reachability required.
- **Invariant 10** (push-receive only): every gov-server call originates from the agent (push); the gov-server never calls into the customer's infrastructure.
- **Pack-binding-primacy**: every audit-chain entry at steps 5, 9, 12 carries \`packBinding: ['nist_ai_rmf', 'tenant:${input.orgId}', 'tier-87']\`.
`;
}
// ---------------------------------------------------------------------------
// File 4 — nist-ai-rmf-reporting.md skill (section composition guide)
// ---------------------------------------------------------------------------
function buildReportingSkill(_input) {
    return `# NIST AI RMF 1.0 Compliance Agent — Report Section Composition

> Reference for steps 6-7 of the heartbeat cycle.
> Each section composes deterministically from redacted broker rows + manifest metadata. No LLM-only sections — every section has an objective rule the Sonnet model applies.

## Six report sections

### 1. GOVERN Status (quarterly + annual) — GOVERN 1-6
- **Inputs:** \`document-store\` scope: AI-governance policies, accountability charts, training records, stakeholder-engagement logs, third-party AI / data inventory
- **Metric:** per GOVERN subcategory (GOVERN 1.1 through GOVERN 6.x), evidence presence + freshness + owner identification
- **Findings:**
  - \`HIGH\` if GOVERN 1 policies are missing for the four core functions (MAP / MEASURE / MANAGE / GOVERN itself)
  - \`HIGH\` if GOVERN 2 accountability roles are unnamed for any of the four core functions
  - \`MEDIUM\` if GOVERN 5 stakeholder-engagement log has gone stale (> 6 months)
  - \`MEDIUM\` if GOVERN 6 third-party AI / data inventory has not been refreshed in the cycle
- **Format:** per-subcategory table (subcategory / evidence-link / owner / last-review-date / status)

### 2. MAP Status (quarterly + annual) — MAP 1-5
- **Inputs:** \`document-store\` scope: AI-system context documents, system categorisation records, capability + targeted-usage statements, component + dependency inventory, stakeholder + impact-group analyses
- **Metric:** per MAP subcategory, evidence presence per registered AI system
- **Findings:**
  - \`CRITICAL\` if any high-risk AI system (Colorado AI Act / EU AI Act crosswalk) lacks a MAP 1 context document: "MAP 1 context absent on high-risk AI system"
  - \`HIGH\` on AI systems missing a MAP 3 capability + targeted-usage statement
  - \`HIGH\` on AI systems missing MAP 4 third-party / supply-chain component map
  - \`MEDIUM\` on MAP 5 impact-characterisation log staleness (> 12 months)
- **Format:** per-AI-system table grouped by MAP subcategory

### 3. MEASURE Status (quarterly + annual) — MEASURE 1-4 + seven trustworthy-AI characteristics
- **Inputs:** \`document-store\` scope: evaluation reports, fairness probes, robustness probes, explainability artefacts, privacy-leakage probes, drift detections; \`audit-chain\` scope: MEASURE telemetry from the last cycle
- **Metric:** per MEASURE subcategory + per trustworthy-AI characteristic, evidence presence + measurement freshness + measurement methodology documentation
- **Findings:**
  - \`CRITICAL\` if a high-risk AI system lacks MEASURE 2 evidence for ALL seven trustworthy-AI characteristics: "MEASURE 2 trustworthy-characteristic evidence absent on high-risk AI system"
  - \`HIGH\` if MEASURE 1 methods + metrics are not documented for a deployed AI system
  - \`HIGH\` on AI systems with no MEASURE 3 over-time risk tracking
  - \`MEDIUM\` on MEASURE 4 measurement-efficacy feedback loop absent or stale
  - \`MEDIUM\` on a MEASURE 2 characteristic with stale evidence (> 6 months) — per characteristic: valid & reliable / safe / secure & resilient / accountable & transparent / explainable & interpretable / privacy-enhanced / fair with harmful bias managed
- **Format:** per-AI-system × per-characteristic matrix + per-MEASURE-subcategory rollup

### 4. MANAGE Status (quarterly + annual) — MANAGE 1-4
- **Inputs:** \`document-store\` scope: AI risk register, risk-prioritisation log, treatment-plan register, third-party AI / data risk register, residual-risk acceptance log, incident + response-plan log
- **Metric:** per MANAGE subcategory, treatment-plan status, residual-risk acceptance status, third-party-risk status, response + recovery + communication plan status
- **Findings:**
  - \`CRITICAL\` if a risk classified HIGH or above is unaccepted + untreated past its treatment-plan due date: "MANAGE 1 treatment-plan overdue on HIGH AI risk"
  - \`HIGH\` on new AI risks identified without an assigned owner (MANAGE 1 + GOVERN 2 crosswalk)
  - \`HIGH\` on a MANAGE 4 residual-risk register entry without owner acceptance and past acceptance-due date
  - \`MEDIUM\` on MANAGE 3 third-party AI / data risk register staleness
- **Format:** per-risk table (risk_id / function / category / inherent_score / treatment / residual_score / owner / acceptance_status / due_date)

### 5. AI RMF Playbook Aggregate Walkthrough (annual; rolls up the four quarterly walkthroughs) — Playbook entries across all four functions
- **Inputs:** four quarterly Playbook-walkthrough sections aggregated
- **Metric:** per adopted Playbook entry, evidence presence + owner + last-review-date; coverage rate across each function's categories
- **Findings:**
  - \`HIGH\` on a category whose Playbook entries are < 50% covered (evidence + owner present)
  - \`MEDIUM\` on individual Playbook entries with stale evidence (> 12 months)
- **Format:** per-function rollup + per-category drill-down

### 6. Profile Alignment Status (annual; or ad-hoc per request) — per adopted Profile (e.g., Generative AI Profile)
- **Inputs:** \`document-store\` scope: per-Profile evidence index; the active Profile registration (\`GOVERNANCE.md\` \`profiles\` field or dashboard registration)
- **Metric:** per Profile subcategory, evidence status (Adopted / Partially Adopted / Not Adopted), evidence link, last-review-date, owner, residual risk
- **Findings:**
  - \`CRITICAL\` on a "Not Adopted" subcategory in a Profile that names the org's named high-risk use case (e.g., Generative AI Profile subcategory for CBRN information mitigation, applicable to an org running a generative AI deployment)
  - \`HIGH\` on "Partially Adopted" subcategories without a scoped completion plan
  - \`MEDIUM\` on Profile subcategories with stale evidence (> 12 months)
- **Format:** per-Profile table grouped by Profile subcategory

## Composition rules

1. **One section = one renderer call.** Don't bleed data across sections.
2. **Markdown only.** No HTML, no JSON in section bodies. JSON envelope wraps the markdown.
3. **Deterministic.** Same input rows produce the same section output. Caller verifies by hash.
4. **No raw secrets / credentials ever.** Redaction is guaranteed by the broker; this rule is the agent's belt-and-braces check.
5. **Each section header MUST cite the relevant core function + subcategory** (e.g., "## 3. MEASURE Status (MEASURE 1-4 + 7 trustworthy characteristics)") so the customer's risk function can index findings against the Playbook + Profile + crosswalk frameworks without re-reading bodies.
6. **Each finding MUST carry crosswalk citations** when applicable (NIST SP 800-53 Rev 5 / ISO/IEC 23894 / OECD AI Principles / EU AI Act articles / Colorado AI Act sections) so cross-pack reporting works.

## Helper utilities (if installed)

If \`@connexum/ai-governance\` is installed and \`SECTION_RENDERER_REGISTRY\` is available, prefer:

\`\`\`bash
node -e "
import('@connexum/ai-governance').then(({ buildComplianceReport }) => {
  const envelope = buildComplianceReport({
    packId: 'nist_ai_rmf',
    orgId: '<orgId>',
    agentId: '<agentId>',
    runId: '<runId>',
    cadence: 'quarterly',
    generatedAt: new Date().toISOString(),
    sections: [
      // quarterly:
      { sectionId: 'govern-status', rendererId: 'nist-ai-rmf-govern-status' },
      { sectionId: 'map-status', rendererId: 'nist-ai-rmf-map-status' },
      { sectionId: 'measure-status', rendererId: 'nist-ai-rmf-measure-status' },
      { sectionId: 'manage-status', rendererId: 'nist-ai-rmf-manage-status' },
      // annual only:
      // { sectionId: 'playbook-walkthrough', rendererId: 'nist-ai-rmf-playbook-aggregate' },
      // { sectionId: 'profile-alignment', rendererId: 'nist-ai-rmf-profile-alignment' },
    ],
    redactedRows: <rows from broker>,
    manifestMetadata: <metadata from broker>,
  });
  process.stdout.write(JSON.stringify(envelope));
});
"
\`\`\`

The deterministic renderers in the package emit byte-identical output for the same input — risk-function-friendly. If the package is unavailable, the agent composes sections via Sonnet using the rules above.
`;
}
// ---------------------------------------------------------------------------
// File 5 — data-broker-usage.md skill (pack-agnostic, but customised per agent)
// ---------------------------------------------------------------------------
function buildBrokerSkill(input) {
    const govUrl = input.govServerUrl ?? 'https://gov.connexum.io';
    return `# Data Access Broker — Usage Guide

> Loaded at startup by ${input.agentId}.
> The broker is the ONLY path the agent uses to read customer data. Bypassing the broker = absolute boundary violation.

## Broker contract

\`\`\`
compliance-agent read \\
  --agent-id ${input.agentId} \\
  --manifest <manifestId> \\
  --query <query string from manifest.allowedQueries> \\
  --params '<JSON array>'
\`\`\`

Returns:
\`\`\`json
{
  "rows": [...],
  "redactionStats": {
    "totalCells": <int>,
    "redactedCells": <int>
  },
  "manifestMetadata": {
    "scopeKind": "audit-chain|codebase|document-store|...",
    "scopeName": "<friendly name>"
  },
  "durationMs": <int>
}
\`\`\`

## Boot sequence (executed by \`compliance-agent read\`)

1. Fetch manifest from \`${govUrl}/api/v1/agents/${input.agentId}/data-manifests/<manifestId>\` (license-key bearer auth)
2. Verify \`state=active\` (draft / revoked = \`BROKER_OFFLINE\`)
3. Validate query against \`manifest.allowedQueries\` (exact string match — partial = \`QueryNotAllowedError\`)
4. Resolve credential from \`manifest.credentialRef\` (\`env:NAME\` or \`keyvault:scope\`; inline rejected)
5. Execute via the registered \`DataAdapterFactory\` for \`scopeKind\`
6. Apply redaction per \`manifest.redactionPolicy.{piiClasses, columnDenyList}\`
7. Emit \`AGENT_DATA_READ\` audit-event to \`${govUrl}/api/v1/agents/${input.agentId}/audit-events\` with structured metadata only (NEVER raw rows)
8. Return redacted rows + stats to the agent

## Failure modes

| Error class | When | Agent action |
|---|---|---|
| \`BrokerOfflineError\` | Manifest not active OR network failure | Exit cycle. Mark cadence as deferred. |
| \`QueryNotAllowedError\` | Query not in allowed-list | Audit \`QUERY_REJECTED\`. Continue cycle without this section. |
| \`CredentialNotFoundError\` | env var or keyvault key absent | Emit \`MANIFEST_MISCONFIGURED\`. Notify ORG_ADMIN via dashboard. Exit cycle. |
| \`LicenseInvalidError\` | License expired or revoked | Exit with code 1. Agent \`DEACTIVATED\`. Tier 4 to re-enable. |

## Invariants the broker enforces

- **Invariant 10** (push-receive only): all gov-server calls originate from the broker (customer side). The gov-server never opens an outbound connection to customer infrastructure.
- **Invariant 1** (manifest fetch failure → BrokerOfflineError): the broker NEVER falls back to executing without a manifest. No silent permissive failure.
- **Invariant 7** (redaction is not optional): if \`redactionPolicy\` is absent, the broker rejects the manifest at activation (\`MANIFEST_MISCONFIGURED\`).

## Active manifests for this agent

Manifest IDs the agent should expect to find (added by ORG_ADMIN via dashboard):

- NIST AI RMF quarterly (MEASURE telemetry): scope \`audit-chain\` with PII+SECRET redaction (model evaluation runs, drift detections, fairness + robustness + explainability + privacy-leakage probes)
- NIST AI RMF quarterly (risk register + Playbook entries): scope \`document-store\` with PII+SECRET redaction (AI risk register + trustworthy-characteristic measurements + adopted Playbook entries + Profile-alignment evidence)
- NIST AI RMF quarterly (AI-system codebase scan): scope \`codebase\` with secret-scanner redaction (training-data lineage, evaluation harness, model-card source-of-truth, deployment manifests)
- NIST AI RMF annual (full four-function cycle): scope \`document-store\` with PII+SECRET redaction (all GOVERN 1-6, MAP 1-5, MEASURE 1-4, MANAGE 1-4 evidence + adopted Profiles)

If a manifest is missing at run time, the agent flags it as \`MANIFEST_MISSING\` and continues with the cadences whose manifests ARE present (degraded operation per Invariant 2).
`;
}
// ---------------------------------------------------------------------------
// File 6 — shared connexum-governance.md (org-wide; copied if not present)
// ---------------------------------------------------------------------------
function buildSharedGovernance(_input) {
    return `# Connexum Governance — Shared Skill

> Loaded at startup by every Connexum compliance agent in this project.
> Defines pack-binding-primacy + 10 Locked Architectural Invariants.

## Pack-binding-primacy

Every catalogued / stored record carries a mandatory \`packBinding: string[]\` naming the compliance packs that govern it. Retention, approval, reviewer tier, sovereignty, report scoping ALL derive from the binding. Empty binding throws \`UnboundDataError\`. Un-binding before retention window elapses is refused.

For Tier 8.7 compliance agents, every emitted audit-chain entry carries \`packBinding: [<packId>, 'tenant:<orgId>', 'tier-87']\` at minimum.

## 10 Locked Architectural Invariants

1. **Self-sovereign passport issuance** — the platform is the passport authority. No external partnership required.
2. **Advisory, never authoritative** — the platform is NEVER in the synchronous critical path of any agent. Failures degrade gracefully.
3. **Graceful degradation by default in the SDK** — 100ms timeout on trust queries; never throw.
4. **Offline-verifiable passports** — verifiable using cached org public keys. Platform reachability not required.
5. **Unknown-passport returns structured response, not 404** — \`status: "unknown"\` + org reputation fallback.
6. **Credit-agency data visibility model** — own data in full; cross-org view limited to \`PublicAgentView\`.
7. **Row-level security at the database** — every multi-tenant table has a Postgres RLS policy. Defence-in-depth.
8. **Three-tier API key hierarchy** — \`PLATFORM_KEY > PARTNER_KEY > ORG_KEY\`. Absolute cross-tier isolation.
9. **External identity bound, never replaced** — Okta/IAM identities become first-class claims INSIDE the passport.
10. **Push-receive only** — data flows from customer TO platform, never the other way. No scanning, no polling, no blocking of customer infrastructure.

## Agent self-check (executed at startup)

1. Verify SOUL block in primary agent MD is intact + chmod 0444
2. Verify BOUNDARIES block in primary agent MD is intact + chmod 0444
3. Verify this file is intact + chmod 0444
4. Verify org public key is cached locally at \`./.connexum/compliance-agent/<agentId>/keys/org-public.pem\`
5. Verify Ed25519 signing key is present at \`./.connexum/compliance-agent/<agentId>/keys/signing-private.pem\`

If any check fails, the agent emits \`GOVERNANCE_INTEGRITY_FAILURE\` and refuses to run until Tier 4 intervention.
`;
}
// ---------------------------------------------------------------------------
// File 7 — GOVERNANCE.md at project root (customer-specific config)
// ---------------------------------------------------------------------------
function buildGovernanceConfig(input) {
    const govUrl = input.govServerUrl ?? 'https://gov.connexum.io';
    return `# GOVERNANCE.md

> Generated at agent spawn. Customer-specific configuration for the Connexum compliance agent runtime.
> This file is COMMITTED to the customer's repo. It contains NO secrets.

## Agent

| Field | Value |
|-------|-------|
| Agent ID | ${input.agentId} |
| Pack | nist_ai_rmf |
| Tier | 8.7 |
| Org ID | ${input.orgId} |
| Location | ${input.location} |
| Department | ${input.department} |
| Gov-server URL | ${govUrl} |

## Secrets (NOT committed)

The agent expects two files outside source control:

- \`./.connexum/compliance-agent/${input.agentId}/.license\` — license key issued at spawn (mode 0600)
- \`./.connexum/compliance-agent/${input.agentId}/keys/signing-private.pem\` — Ed25519 signing key for report envelopes (mode 0600)

Both are created by \`compliance-agent init <licenseKey>\` (first-run setup; see README in the tarball).

## First-run setup

\`\`\`bash
# 1. Install the runtime
npm install -g @connexum/compliance-agent-runtime

# 2. Initialise the agent
compliance-agent init ${input.licenseKey}

# 3. Verify status
compliance-agent status ${input.agentId}

# 4. Run a manual cycle (optional, for verification)
compliance-agent run-once ${input.agentId}
\`\`\`

## Scheduled invocation

The Connexum platform invokes this agent on its declared cadences (quarterly / annual). If you want local cron-based invocation as well, add to your crontab:

\`\`\`cron
0 0 1 */3 * compliance-agent run-once ${input.agentId}    # quarterly (MEASURE + Playbook walkthrough rotation function)
0 0 1 1 *   compliance-agent run-once ${input.agentId}    # annual (full four-function cycle review + Profile-update review)
\`\`\`

The platform invocation and the local cron are idempotent — the same \`runId\` will not double-emit.

## Four-function + subcategory cross-reference

This agent's reports cite the following NIST AI RMF 1.0 core functions + subcategories. The customer's risk function can use this map to index findings:

| Section | Functions + Subcategories |
|---------|---------|
| GOVERN Status | GOVERN 1-6 (policies / accountability / DEI / culture / stakeholder engagement / third-party) |
| MAP Status | MAP 1-5 (context / categorisation / capabilities + usage / component-and-supply-chain risks / impacts) |
| MEASURE Status | MEASURE 1-4 + 7 trustworthy characteristics (valid & reliable / safe / secure & resilient / accountable & transparent / explainable & interpretable / privacy-enhanced / fair with harmful bias managed) |
| MANAGE Status | MANAGE 1-4 (prioritisation + response / benefit maximisation / third-party / treatment plans) |
| AI RMF Playbook Aggregate Walkthrough | Playbook entries across all four functions (rotation Q1=GOVERN / Q2=MAP / Q3=MEASURE / Q4=MANAGE) |
| Profile Alignment Status | per adopted Profile (e.g., Generative AI Profile NIST AI 600-1) |

## Profile registration

To enable Profile-alignment reporting, add the Profile id(s) the org has adopted:

\`\`\`yaml
profiles:
  - id: generative-ai             # NIST AI 600-1 (July 2024)
  - id: <future-sector-profile>
\`\`\`

## Crosswalks (cited on findings where applicable)

- NIST SP 800-53 Rev 5 (security + privacy controls)
- ISO/IEC 23894 (AI risk-management guidance)
- OECD AI Principles (2019)
- EU AI Act (Art. 9 risk-management system / Art. 10 data + governance / Art. 13 transparency / Art. 14 human oversight / Art. 15 accuracy + robustness + cybersecurity)
- Colorado AI Act (effective February 2026 — NIST AI RMF is the recognised affirmative-defence framework)

## Locked Invariants

This agent honours all 10 Connexum Locked Architectural Invariants (see \`.claude/skills/_shared/connexum-governance.md\`). The most operationally relevant for hosts:

- **Invariant 2:** the agent NEVER blocks your other tooling. A failed cycle exits cleanly; the next cycle proceeds.
- **Invariant 10:** all calls originate from this agent. The Connexum gov-server NEVER initiates a connection to your infrastructure.

## Support

- Status: \`compliance-agent status ${input.agentId}\`
- Logs: \`./.connexum/compliance-agent/${input.agentId}/logs/\`
- Reports: \`./.connexum/compliance-agent/${input.agentId}/reports/\`
- Dashboard: ${govUrl.replace(/^https?:\/\/gov\./, 'https://dashboard.')}/agents/compliance/${input.agentId}
`;
}
// ---------------------------------------------------------------------------
// Generator entry point
// ---------------------------------------------------------------------------
export const generate = (input) => {
    const identifier = `nist-ai-rmf-compliance-agent-${input.location}-${input.department}`;
    const bundle = [
        {
            path: `.claude/agents/${identifier}.md`,
            content: buildAgentMd(input),
            mode: 0o444,
        },
        {
            path: '.claude/skills/compliance/nist-ai-rmf-pack.md',
            content: buildPackSkill(input),
            mode: 0o644,
        },
        {
            path: '.claude/skills/compliance/nist-ai-rmf-heartbeat.md',
            content: buildHeartbeatSkill(input),
            mode: 0o644,
        },
        {
            path: '.claude/skills/compliance/nist-ai-rmf-reporting.md',
            content: buildReportingSkill(input),
            mode: 0o644,
        },
        {
            path: '.claude/skills/compliance/data-broker-usage.md',
            content: buildBrokerSkill(input),
            mode: 0o644,
        },
        {
            path: '.claude/skills/_shared/connexum-governance.md',
            content: buildSharedGovernance(input),
            mode: 0o444,
        },
        {
            path: 'GOVERNANCE.md',
            content: buildGovernanceConfig(input),
            mode: 0o644,
        },
    ];
    return bundle;
};
//# sourceMappingURL=nist-ai-rmf.js.map