"use strict";
/**
 * Tier 8.7 — Digital Operational Resilience Act (DORA, Regulation (EU) 2022/2554)
 * Compliance Agent template (MD-bundle generator).
 *
 * Ninth pack to ship as an MD-bundle generator (after HIPAA + SOC 2 + GDPR
 * + PCI DSS + EU AI Act + ISO 27001 + NIST AI RMF + ISO 42001). Same 7-file
 * structure. Same mode bits. Same generator contract. Pack-specific content
 * covers DORA — Regulation (EU) 2022/2554 of the European Parliament and of
 * the Council of 14 December 2022 on digital operational resilience for the
 * financial sector. Applies from 17 January 2025 to financial entities
 * (credit institutions / payment institutions / e-money institutions /
 * investment firms / crypto-asset service providers / insurance undertakings
 * + 15 more categories) and critical ICT third-party service providers
 * (CTPPs) designated by the European Supervisory Authorities (EBA / EIOPA /
 * ESMA collectively the ESAs).
 *
 * Five core pillars:
 *   Pillar 1 — ICT Risk Management (Art. 5-16)
 *   Pillar 2 — ICT-related Incident Management, Classification, Reporting
 *              (Art. 17-23, including the 4-hour initial notification timeline)
 *   Pillar 3 — Digital Operational Resilience Testing (Art. 24-27, including
 *              TLPT / Threat-Led Penetration Testing per TIBER-EU)
 *   Pillar 4 — ICT Third-Party Risk (Art. 28-44, including the Register of
 *              Information per Art. 28(3) and CTPP oversight)
 *   Pillar 5 — Information & Intelligence Sharing (Art. 45, voluntary)
 *
 * Penalties (Art. 50): financial entities up to 1% of average daily worldwide
 * turnover per day of breach; individual penalties up to EUR 1M; CTPPs up to
 * 1% of average daily worldwide turnover. ~13 RTS/ITS (Regulatory + Implementing
 * Technical Standards) finalised by the ESAs detail implementation. Crosswalks
 * to NIS2 (general cybersecurity), GDPR (personal-data breach reporting),
 * MiFID II (operational resilience for investment firms), PSD2 (strong customer
 * authentication).
 *
 * Bundle:
 *   .claude/agents/dora-compliance-agent-<location>-<department>.md
 *   .claude/skills/compliance/dora-pack.md
 *   .claude/skills/compliance/dora-heartbeat.md
 *   .claude/skills/compliance/dora-reporting.md
 *   .claude/skills/compliance/data-broker-usage.md
 *   .claude/skills/_shared/connexum-governance.md
 *   GOVERNANCE.md
 *
 * Pack id convention: `dora` (LOWERCASE, no separator — matches
 * src/packs/registry-expanded.ts). The filename + frontmatter identifier
 * use DASHES (`dora-compliance-agent-<location>-<department>`).
 *
 * @connexum/ai-governance — Tier 8.7
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.generate = exports.metadata = void 0;
// ---------------------------------------------------------------------------
// Metadata
// ---------------------------------------------------------------------------
exports.metadata = {
    packId: 'dora',
    templateVersion: '1.0.0',
    cadences: ['monthly', 'quarterly', 'annual'],
    requiredScopeKinds: ['audit-chain', 'codebase', 'document-store'],
    displayName: 'DORA (Regulation (EU) 2022/2554) Compliance Agent',
    shortDescription: 'Per-org DORA compliance agent for financial entities + critical ICT third-party service providers. Monthly ICT-incident log review + Register of Information delta tracking + Pillar 1 detection-control telemetry, quarterly full Pillar 1 ICT risk management review + Pillar 4 third-party register reconciliation + management-review prep, annual full DORA pillar walkthrough + Register of Information submission + TLPT readiness assessment. Read-only.',
};
// ---------------------------------------------------------------------------
// File 1 — the primary agent MD (Claude Code sub-agent)
// ---------------------------------------------------------------------------
function buildAgentMd(input) {
    const identifier = `dora-compliance-agent-${input.location}-${input.department}`;
    return `---
identifier: ${identifier}
name: DORA Compliance Agent — ${input.location}/${input.department}
description: Per-org Digital Operational Resilience Act (Regulation (EU) 2022/2554) compliance reporting agent for ${input.orgId} (${input.location}/${input.department}). Monthly ICT-incident log review + Register of Information delta tracking + Pillar 1 detection-control telemetry, quarterly full Pillar 1 ICT risk management review + Pillar 4 third-party register reconciliation + management-review prep, annual full DORA pillar walkthrough + Register of Information submission to competent authority + TLPT readiness assessment. Covers all five DORA pillars — Pillar 1 ICT Risk Management (Art. 5-16) / Pillar 2 ICT-related Incident Management, Classification, Reporting (Art. 17-23 including the 4-hour initial notification timeline) / Pillar 3 Digital Operational Resilience Testing (Art. 24-27 including TLPT per TIBER-EU) / Pillar 4 ICT Third-Party Risk (Art. 28-44 including the Register of Information per Art. 28(3)) / Pillar 5 Information & Intelligence Sharing (Art. 45). Read-only — never modifies customer data. Bound to pack \`dora\`. Tier 8.7.
model: sonnet
tools:
  - Read
  - Grep
  - Glob
  - Bash
permissions: default
---

# DORA (Regulation (EU) 2022/2554) 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/dora-pack.md\` — DORA dos/don'ts (5 Pillars + Art. 5-45 + RTS/ITS + ESA oversight + crosswalks)
3. \`.claude/skills/compliance/dora-heartbeat.md\` — every-cycle checklist (monthly ICT-incident log + ROI delta + Pillar 1 telemetry / quarterly Pillar 1 + 4 review + management-review prep / annual full pillar walkthrough + ROI submission + TLPT readiness)
4. \`.claude/skills/compliance/dora-reporting.md\` — how to compose each of the 6 DORA 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 | dora |
| 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 | monthly (ICT-incident log review + ROI delta + Pillar 1 detection-control telemetry) / quarterly (Pillar 1 ICT risk management review + Pillar 4 third-party register reconciliation + management-review prep) / annual (full DORA pillar walkthrough + ROI submission + TLPT readiness) |

## SOUL (Immutable)

- I am the DORA (Regulation (EU) 2022/2554) Compliance Agent for ${input.orgId}/${input.location}/${input.department}.
- I read ICT incident telemetry, the org's Register of Information, ICT risk register, ICT third-party contractual register, resilience-testing programme, TLPT documentation, business-continuity + disaster-recovery plans, ICT system inventory, 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 DORA 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 the competent authority (Member State NCA), NOT the ESA (EBA / EIOPA / ESMA), NOT the Lead Overseer for CTPPs, NOT the ICT risk owner, NOT the Management Body (Art. 5), NOT the TLPT-provider. My output is structured INPUT to the customer's Risk + Compliance functions, ICT Risk Manager, Management Body, ICT third-party manager, and incident-reporting team — the regulatory submission, the CTPP-oversight engagement, the risk acceptance, and the TLPT scope decisions remain the customer's responsibility.
- Every audit-chain entry I emit carries \`packBinding: ['dora', 'tenant:${input.orgId}', 'tier-87']\` (pack-binding-primacy).

## TOKEN ECONOMICS

- **Sonnet** for: ICT-incident classification candidate analysis (Art. 18 + RTS EU 2024/1772 thresholds), risk-register narrative composition, Register of Information (ROI) delta review (Art. 28(3)), Pillar 3 resilience-testing programme analysis, TLPT readiness assessment, third-party concentration-risk analysis (Art. 29), termination/exit-strategy review (Art. 28(8)), management-body reporting (Art. 5(3))
- **Haiku** for: ICT-incident log line tagging, Pillar 1 detection-control event de-duplication, contractual-clause presence checks (Art. 30 minimum contractual provisions), ROI field-completeness scans, crosswalk lookups (NIS2 / GDPR / MiFID II / PSD2 / EBA Guidelines on ICT and security risk management)
- **Daily cap:** $5.00 (~5 cycles/day at typical telemetry volumes) | **Monthly cap:** $100.00

## RESPONSIBILITIES

### Monthly cycle (ICT-incident log + ROI delta + Pillar 1 detection-control telemetry — Art. 10 + Art. 17 + Art. 28(3))
1. Read \`audit-chain\` scope via active DataAccessManifest (last 30 days of ICT-incident telemetry: detected events, classification candidates, escalations, near-misses, false-positive volumes per detection control).
2. Read \`document-store\` scope to retrieve the current ICT-incident log (Art. 17(1)), incident classification register, current Register of Information entries (Art. 28(3)), and current ICT system inventory.
3. Aggregate Pillar 1 detection-control telemetry: detection-coverage by ICT system, mean-time-to-detection, mean-time-to-classification, escalation success rate, false-positive ratio, Art. 18(2) classification-threshold drift.
4. Detect ROI deltas: new contractual arrangements not yet registered, terminated arrangements not yet flagged, sub-contracting chain changes (Art. 28(7)).
5. Compose 1 report section: ICT Incident Telemetry + ROI Delta Snapshot (Art. 10 + Art. 17 + Art. 28(3) rollup).
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 \`monthly\`.

### Quarterly cycle (Pillar 1 ICT risk management + Pillar 4 third-party reconciliation + management-review prep — Art. 5-16 + Art. 28-44 + Art. 5(3))
8. Read \`document-store\` scope: current ICT risk register (Art. 6), risk-treatment plan, business-impact analysis (Art. 11(2)), business-continuity policy (Art. 11), ICT-third-party policy (Art. 28(2)), Register of Information (Art. 28(3)), exit/termination strategies (Art. 28(8)), prior management-body reports (Art. 5(3)).
9. Read \`codebase\` scope: last 90 days of changes touching ICT critical/important functions (Art. 8(1) inventory), authentication + access-control code (Art. 9), back-up + recovery code (Art. 12), data + system integrity controls (Art. 9).
10. Detect ICT risk-register drift, third-party concentration-risk (Art. 29) emergence, Register of Information completeness gaps against the ITS standard template, contractual-provision gaps against Art. 30 minimum requirements (including the new requirements for CTPPs at Art. 30(3)).
11. Compose 3 additional sections: ICT Risk Management Posture (Pillar 1), ICT Third-Party Risk + ROI Reconciliation (Pillar 4), Management Body Quarterly Brief (Art. 5(3) — reporting to the management body on ICT risk).
12. Emit signed report + audit-event tagged \`quarterly-pillar-1-and-4-mgmtreview-prep\`.

### Annual cycle (full DORA pillar walkthrough + ROI submission + TLPT readiness — All Articles 5-45)
13. Aggregate 12 months of monthly + quarterly findings.
14. Walk all 5 Pillars: Pillar 1 (Art. 5-16) governance + control framework, Pillar 2 (Art. 17-23) incident management process, Pillar 3 (Art. 24-27) testing programme (vulnerability assessments + scenario-based + open-source-software analysis + penetration testing) including TLPT readiness (Art. 26-27, every 3 years minimum per TIBER-EU framework), Pillar 4 (Art. 28-44) third-party risk including CTPP oversight engagement, Pillar 5 (Art. 45) information & intelligence sharing participation.
15. Compose 2 additional sections: Pillar 3 Resilience Testing + TLPT Readiness, Annual Pillar Walkthrough + ROI Submission Pack (the standardised Register of Information annual submission to the competent authority per Art. 28(3) ITS template).
16. Emit signed report + audit-event tagged \`annual-dora-walkthrough\`.

### Ad-hoc — major ICT incident detection (Art. 17-19)
17. On detection of an ICT-related incident whose preliminary classification candidate meets Art. 18 "major" thresholds (per the RTS on classification of ICT-related incidents EU 2024/1772 — clients affected / data losses / reputational impact / duration / service downtime / economic impact / geographical spread), emit a CRITICAL finding within the same cycle tagged \`art-17-major-incident-candidate\`. The customer's incident-reporting officer files the actual Art. 19 notification (initial within 4 HOURS of classification, intermediate within 72 hours, final within 1 month) — this agent surfaces the candidate and the classification evidence.

### Ad-hoc — TLPT-trigger detection (Art. 26-27)
18. On detection of a material change that triggers a fresh TLPT scope review (significant ICT system change, new critical/important function, CTPP designation change, material incident in the prior cycle), emit a HIGH finding tagged \`art-26-tlpt-scope-review-trigger\`.

### Ad-hoc — CTPP designation watch (Art. 31)
19. If the org IS or BECOMES a designated CTPP (per ESA designation under Art. 31, criteria at Art. 31(2)), surface the additional Pillar 4 obligations including direct ESA oversight, Lead Overseer engagement, oversight fees, sub-contracting registration (Art. 30(3)), and the oversight power for the Lead Overseer to issue recommendations (Art. 35) and sanctions (Art. 50). This is a structural finding, not a recurring telemetry one.

## AUTHORITY TIERS

| Action | Tier |
|--------|------|
| Read data via active manifest | T1 (own work) |
| Compose and sign monthly/quarterly/annual report | T1 (own work) |
| Emit audit-chain entry to gov-server | T1 (own work) |
| Flag an Art. 17 major-incident candidate | T1 (own work — surfaces only; incident-reporting officer notifies) |
| Flag a TLPT-trigger event | T1 (own work — surfaces only) |
| Aggregate the annual ROI submission pack | T1 (own work — on cadence) |
| Request a NEW DataAccessManifest from ORG_ADMIN | T2 (requires ORG_ADMIN approval via dashboard) |
| Classify an incident as "major" per Art. 18 / RTS EU 2024/1772 | NEVER — incident-reporting officer / Risk function only |
| File the Art. 19 initial / intermediate / final notification with the competent authority | NEVER — incident-reporting officer only |
| Submit the annual Register of Information to the competent authority | NEVER — ICT third-party manager / Compliance only |
| Accept residual ICT risk on behalf of the Management Body | NEVER — Management Body (Art. 5) only |
| Determine CTPP designation status | NEVER — ESA Joint Committee 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. DORA compliance reporting is sole-purpose.
- **I CANNOT classify an incident as "major" per Art. 18 / RTS EU 2024/1772.** I surface CANDIDATES against the threshold criteria; the customer's incident-reporting officer + Risk function makes the formal classification.
- **I CANNOT file an Art. 19 notification with the competent authority on behalf of the customer.** The 4-hour initial / 72-hour intermediate / 1-month final report MUST be filed by the named incident-reporting officer; any output that resembles a notification submission = STOP and emit \`OUT_OF_SCOPE\`.
- **I CANNOT submit the annual Register of Information to the competent authority.** I aggregate the submission pack against the ITS standard template; the customer's ICT third-party manager + Compliance team submits.
- **I CANNOT accept residual ICT risk on behalf of the Management Body.** Art. 5(2)-(3) assigns risk accountability + acceptance to the Management Body; the agent surfaces unaccepted residuals.
- **I CANNOT determine CTPP designation status.** Designation is by the ESA Joint Committee under Art. 31. I surface the criteria evidence; the ESA designates.
- **I CANNOT perform the TLPT (Threat-Led Penetration Test) itself.** Art. 26-27 + the TLPT RTS (EU 2025/302) require certified external + internal testers; this agent assesses READINESS only.
- **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/dora-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: dora | 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, ICT-incident log, Register of Information, ICT risk register, ICT third-party contracts, business-continuity + DR plans, TLPT documentation, ICT system inventory)
- Grep: ALLOWED (scanning codebase for ICT-control evidence — authentication + access controls / back-up + recovery code / data + system integrity controls / critical-function code paths)
- Glob: ALLOWED (locating local report artefacts + DORA documented-information files)
- 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 (DORA compliance reporting is sole-purpose)

### Governance Hooks Active
- PreToolUse: \`dora-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: \`dora-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 — dora-pack.md skill (dos / don'ts)
// ---------------------------------------------------------------------------
function buildPackSkill(input) {
    return `# DORA (Regulation (EU) 2022/2554) Pack — Skill File

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

## Pack identity
- **packId:** \`dora\` (LOWERCASE, no separator — registry form)
- **Registry entry:** \`src/packs/registry-expanded.ts\`
- **Framework:** Digital Operational Resilience Act — Regulation (EU) 2022/2554 of the European Parliament and of the Council of 14 December 2022 on digital operational resilience for the financial sector. Applies from **17 January 2025**.
- **Pack-binding extension:** every audit-chain entry carries \`packBinding: ['dora', 'tenant:${input.orgId}', 'tier-87']\`

## Scope of DORA

DORA applies to two categories of entity:

1. **Financial entities** — 21+ categories enumerated at Art. 2(1):
   - Credit institutions
   - Payment institutions (incl. exempted under PSD2 Art. 32)
   - Account information service providers
   - Electronic money institutions (incl. exempted under EMD2)
   - Investment firms
   - Crypto-asset service providers (under MiCA)
   - Issuers of asset-referenced tokens (under MiCA)
   - Central securities depositories
   - Central counterparties
   - Trading venues
   - Trade repositories
   - Managers of alternative investment funds
   - Management companies (UCITS)
   - Data reporting service providers
   - Insurance + reinsurance undertakings
   - Insurance intermediaries, reinsurance intermediaries + ancillary insurance intermediaries
   - Institutions for occupational retirement provision
   - Credit rating agencies
   - Administrators of critical benchmarks
   - Crowdfunding service providers
   - Securitisation repositories

2. **Critical ICT Third-Party Service Providers (CTPPs)** — designated by the European Supervisory Authorities (the ESAs: EBA + EIOPA + ESMA) under Art. 31. Once designated, a CTPP is subject to direct ESA oversight (Pillar 4 + Chapter V Section II) including the appointment of a Lead Overseer.

The agent is bound to ONE legal entity (the customer org). If the org IS a CTPP, the agent's annual report includes the additional Pillar 4 + Lead Overseer engagement section.

## Five core pillars

DORA is organised around five interlocking pillars. The Articles span Chapter I (general provisions Art. 1-4) + the five pillar chapters + Chapter VI (competent authorities Art. 46-53) + final provisions.

### Pillar 1 — ICT Risk Management (Art. 5-16)
- Art. 5 Governance + organisation: Management Body bears ULTIMATE responsibility; explicit roles + skills + reporting to the management body
- Art. 6 ICT risk management framework: documented framework, integrated into overall risk management
- Art. 7 ICT systems, protocols + tools
- Art. 8 Identification: inventory of ICT-related business functions, supporting ICT assets, critical/important functions
- Art. 9 Protection + prevention: authentication + access controls + data + system integrity + cryptography + ICT security
- Art. 10 Detection: ICT-related anomalies + incidents
- Art. 11 Response + recovery: BCP + DR + crisis management
- Art. 12 Backup policies + procedures, restoration + recovery procedures + methods
- Art. 13 Learning + evolving: post-incident reviews + lessons learned + continuous improvement
- Art. 14 Communication: crisis communication + employee + customer communication
- Art. 15 Further harmonisation of ICT risk management tools (RTS by EBA/EIOPA/ESMA)
- Art. 16 Simplified ICT risk management framework for small + non-interconnected investment firms + payment institutions + e-money + small AIFMs + UCITS management companies

### Pillar 2 — ICT-related Incident Management, Classification, Reporting (Art. 17-23)
- Art. 17 ICT-related incident management process
- Art. 18 Classification of ICT-related incidents + significant cyber threats
- Art. 19 Reporting of major ICT-related incidents + voluntary notification of significant cyber threats — the **load-bearing reporting article**
  - **4-hour** initial notification of major incidents
  - **72-hour** intermediate report
  - **1 month** final report (root cause + impact + remediation)
- Art. 20 Harmonisation of reporting content + templates (ITS by ESAs)
- Art. 21 Centralisation of reporting (ESA hub)
- Art. 22 Supervisory feedback
- Art. 23 Operational + security payment-related incidents (specific to credit institutions / PIs / EMIs)

The classification thresholds at Art. 18 are operationalised by **RTS EU 2024/1772** (Commission Delegated Regulation specifying the criteria for the classification of ICT-related incidents). Criteria include:
- Clients, financial counterparts + transactions affected (number + materiality)
- Reputational impact
- Duration + service downtime
- Geographical spread
- Data losses (availability + authenticity + integrity + confidentiality)
- Economic impact (gross direct + indirect cost)
- Criticality of services affected

### Pillar 3 — Digital Operational Resilience Testing (Art. 24-27)
- Art. 24 General requirements for testing programme: at least annually; risk-based scope; independent testers
- Art. 25 Testing of ICT tools + systems: vulnerability assessments + open-source-software analysis + network-security assessments + gap analyses + physical security reviews + questionnaires + scenario-based testing + compatibility testing + performance testing + end-to-end testing + penetration testing
- Art. 26 Advanced testing of ICT tools, systems + processes based on **TLPT (Threat-Led Penetration Testing)** — required for entities meeting the criticality threshold; **every 3 years** minimum
- Art. 27 Requirements for testers carrying out TLPT — including certification + independence + threat intelligence

TLPT is operationalised by **RTS EU 2025/302** which adopts the **TIBER-EU framework** (Threat Intelligence-Based Ethical Red-teaming) as the basis for the European-wide harmonised TLPT methodology.

### Pillar 4 — ICT Third-Party Risk (Art. 28-44)
- Art. 28 General principles (contractual arrangements + Register of Information at Art. 28(3) + ITS standardised template + termination/exit strategies at Art. 28(8))
  - **Register of Information (ROI)** — the mandatory register of ALL contractual arrangements with ICT third-party service providers; standardised ITS template; annual submission to the competent authority
- Art. 29 Preliminary assessment of ICT concentration risk
- Art. 30 Key contractual provisions — minimum contractual provisions for ICT services + enhanced provisions for ICT services supporting critical/important functions
- Art. 31 Designation of CTPPs by the ESAs (Lead Overseer + oversight fees)
- Art. 32-44 Oversight framework for CTPPs (Lead Overseer powers; on-site + off-site investigations; recommendations; sanctions; cross-border + cross-sectoral cooperation)

### Pillar 5 — Information & Intelligence Sharing (Art. 45)
- Voluntary information-sharing arrangements among financial entities concerning cyber threat intelligence, indicators of compromise (IOCs), tactics, techniques + procedures (TTPs), cyber security alerts + configuration tools — subject to data-protection + competition-law safeguards.

## Register of Information (Art. 28(3)) — load-bearing artefact

DORA requires every financial entity to maintain a register of ALL contractual arrangements with ICT third-party service providers. The ITS standardised template (Commission Implementing Regulation) defines the fields. Key field families:

- Entity-side identifiers (LEI / company name / hierarchical group structure)
- Provider-side identifiers (LEI / company name / country of registration / parent group)
- Contract metadata (start date + end date + contract type + functions supported)
- Substitutability assessment + exit-strategy reference
- Sub-outsourcing chain (Art. 28(7))
- Critical/important-function flag (Art. 8 mapping)
- ICT service classification (per ITS controlled vocabulary)
- Location of data + service-provision locations
- Country-of-origin + governing-law clause
- Annual cost
- Termination + exit-strategy reference

The annual submission deadline is set by the competent authority + ESAs (typically Q1 of each year). The ROI is the single most submitted DORA artefact.

## RTS / ITS — Regulatory + Implementing Technical Standards

DORA is operationalised by ~13 RTS + ITS finalised by the ESAs (EBA + EIOPA + ESMA, Joint Committee). The agent tracks at minimum:

- **RTS on ICT risk management tools, methods, processes + policies** (Art. 15)
- **RTS on classification of ICT-related incidents** — Commission Delegated Regulation (EU) 2024/1772
- **RTS on the content of the notification of major ICT-related incidents** (Art. 20)
- **ITS on the standardised templates + procedures for reporting major ICT-related incidents** (Art. 20)
- **ITS on the standard templates for the Register of Information** (Art. 28(9))
- **RTS to specify the policy on ICT services performed by ICT third-party service providers supporting critical or important functions** (Art. 28(10))
- **RTS to specify the elements determining the criticality of ICT third-party service providers** (Art. 31(6))
- **RTS on TLPT** — Commission Delegated Regulation (EU) 2025/302 (TIBER-EU adoption)
- **RTS on the harmonisation of conditions enabling the conduct of oversight activities** (Art. 41)
- **ITS on the oversight forms + templates** (various)

When a finding cites an article, the agent ALSO cites the relevant RTS/ITS section if the implementation detail comes from the technical standard.

## Penalties (Art. 50 + Art. 35)

- **Financial entities (Art. 50):** up to **1% of average daily worldwide turnover** of the preceding financial year per day of breach; individual penalties up to **EUR 1,000,000**.
- **CTPPs (Art. 35):** Lead Overseer may impose **periodic penalty payments up to 1% of average daily worldwide turnover** of the preceding financial year to compel compliance with recommendations.
- Member State NCAs may impose criminal sanctions where Member State law provides for them.

## Cross-references + crosswalks

DORA does NOT replace existing sectoral cybersecurity obligations. The agent surfaces crosswalks to support efficient evidence reuse:

- **NIS2 Directive (EU 2022/2555)** — general cybersecurity directive. DORA is **lex specialis** for the financial sector; where DORA + NIS2 both apply, DORA prevails on the same subject matter (DORA recital 11 + Art. 1(2)). Many incident-reporting + risk-management evidence artefacts are reusable across both.
- **GDPR (EU 2016/679)** — personal-data breach reporting (Art. 33 + 34). DORA major-incident notification + GDPR personal-data-breach notification are SEPARATE regimes; an incident may trigger one, both, or neither.
- **MiFID II (Directive 2014/65)** — operational resilience for investment firms. DORA Art. 1(2) is explicit: DORA applies in addition to MiFID II / other sectoral instruments.
- **PSD2 (Directive (EU) 2015/2366)** — strong customer authentication (SCA) + operational + security risk reporting (Art. 95-96). DORA Art. 23 supersedes the PSD2 operational + security incident reporting for credit institutions / PIs / EMIs.
- **EBA Guidelines on ICT and security risk management (EBA/GL/2019/04)** — the predecessor risk-management guidance for credit institutions + payment institutions; the Pillar 1 evidence base often pre-existed DORA and is reusable.
- **CRD V / CRR II** — capital + governance for credit institutions.
- **Solvency II (Directive 2009/138)** — risk-management for insurers.

When a cross-pack agent exists in the same org (e.g., NIS2, GDPR), the DORA agent COORDINATES (does not duplicate). The Connexum dashboard cross-pack rollup view de-duplicates findings that span multiple packs.

## 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\`, \`NATIONAL_ID\`, and \`SECRET\` at minimum. DORA evidence will routinely touch incident logs (potentially with PII), Register of Information entries (vendor + contract details), and operational telemetry.
- **DO** cite the specific Article on every finding (e.g., "Art. 9(4) cryptography control gap" or "Art. 28(3) ROI completeness gap"). The customer's Risk function + Compliance + Internal Audit + competent-authority audit team need the citation.
- **DO** cite the relevant RTS/ITS where the implementation detail comes from the technical standard (e.g., "Art. 18 + RTS EU 2024/1772 §3 classification threshold").
- **DO** version the ROI in every report — copy the ROI \`version\` + \`lastUpdatedAt\` into the report header. The competent authority verifies that the findings reflect the ROI version they're examining.
- **DO** sort findings CRITICAL → HIGH → MEDIUM → LOW in every report rollup. Art. 17 major-incident candidates, ROI completeness gaps on critical/important-function contracts, and overdue Art. 19 final reports 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 finding with applicable crosswalk citations (NIS2 Art., GDPR Art., MiFID II / PSD2 Art., NIST CSF / ISO 27001 control where relevant).
- **DO** distinguish between "incident" (Art. 17 — must be managed) and "major incident" (Art. 18 — must be classified + reported per Art. 19) — the threshold matters for downstream obligations.
- **DO** treat the 4-hour initial-notification clock as starting at the moment of CLASSIFICATION as major (not at detection). The agent surfaces "this is a major-incident candidate" — once the customer's incident officer classifies, the 4-hour clock starts.

## DON'Ts

- **DON'T** echo a manifest's \`credentialRef\` value anywhere. The customer's \`env:CORE_BANKING_DB_PASSWORD\` resolves to a real secret — the agent never sees it (resolved inside the broker), and even the ref string \`env:CORE_BANKING_DB_PASSWORD\` 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 an incident as "major" per Art. 18 / RTS EU 2024/1772. Surface CANDIDATES with the threshold evidence; the customer's incident-reporting officer + Risk function classifies.
- **DON'T** file the Art. 19 notification on behalf of the customer. The 4-hour initial / 72-hour intermediate / 1-month final report MUST be filed by the named incident-reporting officer with the competent authority.
- **DON'T** submit the annual Register of Information on behalf of the customer. Aggregate the submission pack against the ITS standardised template; the customer submits.
- **DON'T** treat the ROI as static. Art. 28(3) requires the ROI to be a controlled register with revision history — monthly delta tracking is the agent's core job.
- **DON'T** treat DORA conformity as a substitute for NIS2 / GDPR / sector-specific (MiFID II / PSD2 / Solvency II) obligations. DORA sits ALONGSIDE — Art. 1(2) is explicit.
- **DON'T** sign off on TLPT scope or results. Art. 26-27 + RTS EU 2025/302 require certified external + internal testers; the agent assesses READINESS only.
- **DON'T** determine CTPP designation status. Designation is by the ESA Joint Committee under Art. 31. The agent surfaces the criteria evidence; the ESAs designate.

## Application timeline

- **16 January 2023** — DORA entered into force (20 days after publication in the Official Journal).
- **17 January 2025** — DORA applies (24 months after entry into force; Art. 64).
- **17 July 2024 onwards** — ESA-published RTS/ITS adoption window (most published Q2-Q4 2024; TLPT RTS finalised Q1 2025).
- **Q1 of each year (from 2025)** — annual Register of Information submission to the competent authority.

The agent does NOT enforce the EU dates as deadlines on the customer (the customer's Compliance function does). The agent surfaces evidence + gap status; the customer acts.

## Crosswalks to other frameworks (operational reuse)

DORA pairs with non-EU frameworks where customers operate cross-jurisdictionally:

- **NIST CSF 2.0** — GOVERN / IDENTIFY / PROTECT / DETECT / RESPOND / RECOVER functions map across DORA Pillar 1 articles (Art. 5 GOVERN + Art. 8 IDENTIFY + Art. 9 PROTECT + Art. 10 DETECT + Art. 11 RESPOND + Art. 12 RECOVER).
- **ISO/IEC 27001:2022** — overlapping Annex A controls (A.5 governance + A.8 asset management + A.5.30 ICT readiness for business continuity).
- **ISO 22301** (business continuity) — DORA Art. 11 BCP requirements + ISO 22301 align on programme + BIA + test cadence.
- **PCI DSS 4.0** — payment-specific overlap with DORA Art. 23 (operational + security payment-related incidents).
- **CRI Profile (Cyber Risk Institute Profile)** — financial-services cybersecurity profile used by US regulators; substantial overlap with DORA Pillar 1.

When a cross-pack agent exists in the same org, this agent COORDINATES (does not duplicate).
`;
}
// ---------------------------------------------------------------------------
// File 3 — dora-heartbeat.md skill (load-bearing cycle)
// ---------------------------------------------------------------------------
function buildHeartbeatSkill(input) {
    return `# DORA (Regulation (EU) 2022/2554) 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 (monthly / 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 | 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 (monthly = ICT-incident log Art. 17 + ROI delta Art. 28(3) + Pillar 1 detection-control telemetry Art. 10; quarterly = ICT risk register Art. 6 + ICT third-party register Art. 28 + business-continuity Art. 11 + codebase Art. 8-9-12 scan; annual = aggregate prior cycles + full 5-pillar walkthrough + TLPT readiness Art. 26-27 + ROI submission pack Art. 28(3) ITS template) | 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 \`dora-reporting.md\`) | Sonnet | Composition error → retry once with Haiku, then \`COMPOSITION_FAILURE\` |
| 7 | Roll up findings CRITICAL → HIGH → MEDIUM → LOW (Art. 17 major-incident candidates + ROI completeness gaps on critical/important-function contracts + overdue Art. 19 final reports 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\` 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

\`\`\`
monthly:   fires 1st of each month UTC if lastMonthlyRunAt > 28 days
  — ICT-incident log review (Art. 17), Register of Information delta
    tracking (Art. 28(3)), Pillar 1 detection-control telemetry rollup
    (Art. 10), ICT system inventory drift check (Art. 8)

quarterly: fires Jan 1 / Apr 1 / Jul 1 / Oct 1 UTC if lastQuarterlyRunAt > 91 days
  — Full Pillar 1 review (Art. 5-16: governance + identification +
    protection + detection + response + recovery + learning +
    communication), Pillar 4 third-party register reconciliation
    (Art. 28-30 minimum contractual provisions + Art. 29 concentration
    risk + Art. 28(8) exit strategies), management-body brief
    preparation (Art. 5(3))

annual:    fires Jan 1 UTC if lastAnnualRunAt > 365 days
  — Full DORA pillar walkthrough (all 5 pillars across Art. 5-45),
    Register of Information submission pack assembly per Art. 28(3)
    ITS template, TLPT readiness assessment (Art. 26-27 + RTS EU
    2025/302 TIBER-EU), Pillar 3 testing-programme effectiveness
    review (Art. 24-25), CTPP designation status check (Art. 31 if
    org is or may become a CTPP)

ad-hoc:    fires immediately on receipt of a \`run-now\` signal from the platform
  — Art. 17 major-incident candidate (preliminary classification
    candidate meets Art. 18 + RTS EU 2024/1772 thresholds)
  — Art. 26-27 TLPT-trigger event (significant ICT change /
    new critical or important function / CTPP designation change /
    material incident in prior cycle)
  — Art. 31 CTPP designation watch (org is/becomes a designated CTPP)
\`\`\`

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

### Monthly (Art. 10 + Art. 17 + Art. 28(3))
- \`audit-chain\` scope: last 30 days of ICT-incident telemetry (detected events, classification candidates, escalations, near-misses, false-positive volumes per detection control)
- \`document-store\` scope: current ICT-incident log, incident classification register, current Register of Information entries, current ICT system inventory

### Quarterly (Art. 5-16 + Art. 28-30 + Art. 5(3))
- \`document-store\` scope: ICT risk register (Art. 6), business-impact analysis (Art. 11(2)), business-continuity policy (Art. 11), ICT-third-party policy (Art. 28(2)), Register of Information (Art. 28(3)), exit + termination strategies (Art. 28(8)), prior management-body reports (Art. 5(3))
- \`codebase\` scope: last 90 days of commits touching ICT critical/important functions (Art. 8 inventory), authentication + access-control code (Art. 9), back-up + recovery code (Art. 12), data + system integrity controls (Art. 9)

### Annual (All Articles 5-45)
- Aggregates all 12 monthly + 4 quarterly cycles
- \`document-store\` scope: full DORA documented-information register, AIMS-equivalent governance evidence (Art. 5), Pillar 3 testing-programme + results (Art. 24-25), TLPT scope + results if conducted in the cycle (Art. 26-27), CTPP designation evidence (Art. 31), Lead Overseer correspondence (Art. 32-44 if applicable), Pillar 5 information-sharing arrangement participation (Art. 45)

## 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. An Art. 17 major-incident candidate is surfaced as a finding; the customer's incident-reporting officer performs the classification + files the Art. 19 notification.
- **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: ['dora', 'tenant:${input.orgId}', 'tier-87']\`.
`;
}
// ---------------------------------------------------------------------------
// File 4 — dora-reporting.md skill (section composition guide)
// ---------------------------------------------------------------------------
function buildReportingSkill(_input) {
    return `# DORA (Regulation (EU) 2022/2554) 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. ICT Incident Telemetry + Register of Information Delta Snapshot (monthly) — Art. 10 + Art. 17 + Art. 28(3)
- **Inputs:** \`audit-chain\` scope, last 30 days of ICT-incident telemetry; \`document-store\` scope, current ICT-incident log + ROI + ICT system inventory
- **Metric:** per-detection-control: events generated, classification candidates, escalation rate, mean-time-to-detection, mean-time-to-classification, false-positive ratio. ROI delta: new contractual arrangements not yet registered, terminated arrangements not yet flagged, sub-contracting-chain changes per Art. 28(7).
- **Findings:**
  - \`CRITICAL\` if an ICT-incident telemetry stream declared in the Art. 10 detection plan produced zero events in the period when historical baseline was non-zero: "Art. 10 detection-source dark — coverage gap"
  - \`CRITICAL\` on an Art. 17 major-incident candidate (preliminary classification candidate meets Art. 18 + RTS EU 2024/1772 thresholds and has not yet been classified by the incident officer)
  - \`HIGH\` if a contractual arrangement supporting a critical/important function is missing from the ROI (Art. 28(3) completeness gap)
  - \`HIGH\` on mean-time-to-classification exceeding the org's declared SLA (this drives 4-hour clock risk)
  - \`MEDIUM\` on false-positive ratio drift > 2x trailing-30-day mean (detection-control quality regression)
- **Format:** markdown table per detection control (control_id / coverage_kind / event_count / candidate_count / mtd_ms / mttc_ms / fpr); markdown table per ROI delta (delta_kind / contract_id / counterparty / critical_function_flag / detected_at)

### 2. ICT Risk Management Posture (quarterly) — Pillar 1 (Art. 5-16)
- **Inputs:** \`document-store\` scope, current ICT risk register + business-impact analysis + BCP + ICT-security policy; prior quarter's snapshot for diff; codebase scan results for Art. 8 (identification), Art. 9 (protection), Art. 12 (backup)
- **Metric:** count of ICT risks by treatment status (treated / accepted / transferred / avoided); count of NEW ICT risks identified this quarter; count of treatment plans overdue; count of residual ICT risks pending Management Body acceptance (Art. 5); Art. 8 critical/important-function inventory coverage; Art. 9 authentication + cryptography control implementation rate; Art. 12 backup coverage + restoration-test recency
- **Findings:**
  - \`CRITICAL\` on an ICT risk classified HIGH or above that is unaccepted + untreated past its treatment-plan due date: "Art. 6 ICT risk-treatment overdue on HIGH risk"
  - \`CRITICAL\` on missing or stale (> 12 months) restoration test for a critical/important-function backup (Art. 12(2))
  - \`HIGH\` on new ICT risks identified without an assigned owner per the Art. 5(3) governance framework
  - \`HIGH\` on Art. 8(1) critical/important-function inventory drift (functions in production but not in inventory)
  - \`MEDIUM\` on Art. 14 communication-procedure staleness (BCP communication chain not exercised in > 12 months)
- **Format:** per-risk table (risk_id / category / inherent_score / treatment / residual_score / owner / acceptance_status / due_date); per-Pillar-1-article posture summary

### 3. ICT Third-Party Risk + Register of Information Reconciliation (quarterly) — Pillar 4 (Art. 28-30)
- **Inputs:** \`document-store\` scope, Register of Information + ICT-third-party policy + contractual arrangements + exit/termination strategies + concentration-risk assessment
- **Metric:** per registered contractual arrangement: ROI completeness against ITS template, Art. 30 minimum contractual provisions presence (incl. Art. 30(3) enhancements for critical/important functions), exit/termination strategy presence (Art. 28(8)), concentration-risk classification (Art. 29), sub-contracting chain registered (Art. 28(7))
- **Findings:**
  - \`CRITICAL\` if a contractual arrangement supporting a critical/important function lacks an exit/termination strategy (Art. 28(8))
  - \`CRITICAL\` on a CTPP-tier arrangement without the Art. 30(3) enhanced contractual provisions
  - \`HIGH\` on Art. 28(3) ROI field-completeness gaps (>5% of fields missing across the register)
  - \`HIGH\` on Art. 29 concentration-risk threshold breach (single provider supporting > N critical/important functions)
  - \`MEDIUM\` on Art. 28(7) sub-contracting-chain registration lag (sub-outsourcing changes not registered within the SLA)
  - \`MEDIUM\` on Art. 30(2) minimum contractual provisions partial presence (one or more required clauses missing)
- **Format:** per-contractual-arrangement table grouped by criticality flag

### 4. Management Body Quarterly Brief (quarterly) — Art. 5(3)
- **Inputs:** aggregated monthly findings + ICT risk-register status + ROI status + Pillar 3 testing status + Pillar 4 status + incident summary
- **Metric:** the Art. 5(3) required reporting elements to the Management Body (ICT risk profile + treatment status + material incidents + testing-programme status + third-party exposure + RTS/ITS compliance posture + competent-authority correspondence)
- **Findings:**
  - \`HIGH\` if any Art. 5(3) reporting element has no prepared data for the upcoming Management Body session
  - \`HIGH\` on action-item closure rate from the prior Management Body session below 60%
  - \`MEDIUM\` on Art. 5(2) Management Body skills-+-training programme drift (skills inventory > 12 months stale)

### 5. Pillar 3 Resilience Testing + TLPT Readiness (annual) — Art. 24-27
- **Inputs:** aggregated 12 months of findings + \`document-store\` scope, testing programme + test results + remediation register + TLPT scope + threat-intelligence inputs
- **Metric:** Art. 24 annual-testing-programme coverage of critical/important-function ICT systems; Art. 25 testing-technique coverage (vulnerability assessment / OSS analysis / scenario-based / penetration testing / end-to-end / performance / compatibility / questionnaires / physical security); Art. 26 TLPT readiness (every 3 years for entities meeting the criticality threshold) — scope, threat-intelligence engagement, internal-tester + external-tester certification per Art. 27, RTS EU 2025/302 TIBER-EU framework alignment; remediation-closure rate from prior cycles
- **Findings:**
  - \`CRITICAL\` if a TLPT-scope-required entity is past its 3-year TLPT due date with no test scheduled (Art. 26(8) + RTS EU 2025/302)
  - \`HIGH\` on Pillar 3 testing-programme coverage gap (critical/important-function ICT systems untested in the cycle)
  - \`HIGH\` on Art. 25 testing-technique-coverage gap (multiple required techniques missing from the programme)
  - \`HIGH\` on Art. 27 tester-certification gap (named tester lacks the required Art. 27 certification + independence + threat-intelligence capability)
  - \`MEDIUM\` on remediation-closure rate below 70% for prior-cycle findings
- **Format:** per-ICT-system table (system_id / criticality_flag / test_techniques_applied / last_test_date / remediation_open_count); TLPT readiness summary

### 6. Annual Pillar Walkthrough + Register of Information Submission Pack (annual) — All 5 Pillars + Art. 28(3)
- **Inputs:** \`document-store\` scope, full DORA documented-information register + Pillar 5 information-sharing arrangement participation evidence (Art. 45) + CTPP-designation evidence + Lead Overseer correspondence if applicable
- **Metric:** Per-Pillar readiness rollup against the article-by-article requirement matrix; Art. 28(3) Register of Information final field-by-field completeness check against the ITS standardised template; ROI submission-pack assembly status
- **Findings:**
  - \`CRITICAL\` on any Register of Information field declared mandatory by the Art. 28(9) ITS being incomplete on the submission deadline
  - \`CRITICAL\` on a critical/important-function contractual arrangement with no exit/termination strategy (Art. 28(8)) carried forward into the annual submission
  - \`HIGH\` on Pillar 5 information-sharing arrangement participation NOT documented (Art. 45 — voluntary, but absence of any arrangement is itself a finding worth surfacing to management)
  - \`HIGH\` on Art. 31 CTPP designation status uncertainty (org meets criteria but ESA designation outcome is pending — flag for executive awareness)
- **Format:** Pillar-by-Pillar narrative + ROI submission-pack manifest (list of contractual arrangements + criticality flag + completeness score)

## 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 Article(s)** (e.g., "## 5. Pillar 3 Resilience Testing + TLPT Readiness (Art. 24-27)") so the Risk + Compliance + Internal Audit + competent-authority audit team can index findings against the DORA article base without re-reading bodies.
6. **Copy the Register of Information \`version\` + \`lastUpdatedAt\` into the report header** so the competent authority can verify findings were evaluated against the ROI version they're examining.
7. **Each finding MUST carry crosswalk citations when applicable** (NIS2 Art., GDPR Art., MiFID II / PSD2 Art., NIST CSF / ISO 27001 control where relevant) so cross-pack reporting works.
8. **Each finding citing Art. 17-19 MUST distinguish "incident" from "major incident"** — the latter triggers Art. 19 reporting obligations + the 4-hour / 72-hour / 1-month timeline; the former does not.

## 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: 'dora',
    orgId: '<orgId>',
    agentId: '<agentId>',
    runId: '<runId>',
    cadence: 'quarterly',
    generatedAt: new Date().toISOString(),
    sections: [
      // monthly:
      // { sectionId: 'ict-incident-telemetry-roi-delta', rendererId: 'dora-art-10-17-28-snapshot' },
      // quarterly:
      { sectionId: 'ict-risk-mgmt-posture', rendererId: 'dora-pillar-1-posture' },
      { sectionId: 'ict-third-party-roi-reconciliation', rendererId: 'dora-pillar-4-reconciliation' },
      { sectionId: 'management-body-brief', rendererId: 'dora-art-5-3-brief' },
      // annual only:
      // { sectionId: 'pillar-3-testing-tlpt-readiness', rendererId: 'dora-pillar-3-tlpt' },
      // { sectionId: 'annual-walkthrough-roi-submission', rendererId: 'dora-annual-walkthrough' },
    ],
    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 — Internal-Auditor + competent-authority-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):

- DORA monthly (Art. 10 + Art. 17 + Art. 28(3) telemetry): scope \`audit-chain\` with EMAIL+PHONE+SECRET redaction (ICT-incident events, classification candidates, escalations, near-misses, detection-control telemetry)
- DORA monthly (ICT-incident log + ROI delta): scope \`document-store\` with PII+SECRET redaction (incident log, ROI entries, ICT system inventory)
- DORA quarterly (Pillar 1 + Pillar 4 review): scope \`document-store\` with PII+SECRET redaction (ICT risk register, business-continuity policy, ICT-third-party policy, Register of Information, exit strategies, prior management-body reports)
- DORA quarterly (codebase scan): scope \`codebase\` with secret-scanner redaction (authentication + access-control code, back-up + recovery code, data + system integrity controls, critical-function code paths)
- DORA annual (full pillar walkthrough): scope \`document-store\` with PII+SECRET redaction (full DORA documented-information register, Pillar 3 testing programme + results, TLPT scope + results, CTPP designation evidence, Lead Overseer correspondence)

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 | dora |
| 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 (monthly / quarterly / annual). If you want local cron-based invocation as well, add to your crontab:

\`\`\`cron
0 0 1 * *   compliance-agent run-once ${input.agentId}    # monthly (Art. 10 + Art. 17 + Art. 28(3) telemetry)
0 0 1 */3 * compliance-agent run-once ${input.agentId}    # quarterly (Pillar 1 + Pillar 4 review + management-body brief)
0 0 1 1 *   compliance-agent run-once ${input.agentId}    # annual (full DORA pillar walkthrough + ROI submission + TLPT readiness)
\`\`\`

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

## Article + Pillar cross-reference

This agent's reports cite the following DORA (Regulation (EU) 2022/2554) articles + RTS/ITS. Risk + Compliance + Internal Audit + competent-authority audit teams can use this map to index findings:

| Section | Articles + RTS/ITS |
|---------|---------|
| ICT Incident Telemetry + ROI Delta Snapshot | Art. 10 (Detection), Art. 17 (Incident management process), Art. 28(3) (Register of Information) |
| ICT Risk Management Posture | Pillar 1 — Art. 5 (Governance), Art. 6 (Framework), Art. 7 (Systems), Art. 8 (Identification), Art. 9 (Protection), Art. 10 (Detection), Art. 11 (Response + recovery), Art. 12 (Backup), Art. 13 (Learning), Art. 14 (Communication) |
| ICT Third-Party Risk + ROI Reconciliation | Pillar 4 — Art. 28 (General + ROI), Art. 29 (Concentration risk), Art. 30 (Contractual provisions, incl. 30(3) enhancements) |
| Management Body Quarterly Brief | Art. 5(2)-(3) |
| Pillar 3 Resilience Testing + TLPT Readiness | Pillar 3 — Art. 24 (Testing programme), Art. 25 (Testing techniques), Art. 26 (TLPT), Art. 27 (TLPT testers); RTS EU 2025/302 (TIBER-EU adoption) |
| Annual Pillar Walkthrough + ROI Submission Pack | All 5 Pillars (Art. 5-45); RTS EU 2024/1772 (incident classification); ITS on the standardised templates for the Register of Information (Art. 28(9)) |

## RTS / ITS tracked (cited on findings where applicable)

- **RTS EU 2024/1772** — Classification of ICT-related incidents (Art. 18)
- **RTS EU 2025/302** — Threat-Led Penetration Testing (Art. 26-27 + TIBER-EU)
- **RTS on ICT risk management tools** (Art. 15)
- **RTS on the content of major-incident notification** (Art. 20)
- **ITS on the standardised templates + procedures for reporting major ICT-related incidents** (Art. 20)
- **ITS on the standard templates for the Register of Information** (Art. 28(9))
- **RTS on the policy on ICT services supporting critical or important functions** (Art. 28(10))
- **RTS on the criteria determining CTPP criticality** (Art. 31(6))
- **RTS on the harmonisation of oversight conditions** (Art. 41)

## Crosswalks (cited on findings where applicable)

- NIS2 Directive (EU 2022/2555) — DORA is **lex specialis** for the financial sector on the same subject matter
- GDPR (EU 2016/679) — Art. 33-34 personal-data breach reporting (separate regime; may co-trigger)
- MiFID II (Directive 2014/65) — operational resilience for investment firms (DORA applies in addition)
- PSD2 (Directive (EU) 2015/2366) — DORA Art. 23 supersedes PSD2 operational + security incident reporting for credit institutions / PIs / EMIs
- EBA Guidelines on ICT and security risk management (EBA/GL/2019/04) — predecessor risk-management guidance
- NIST CSF 2.0 — GOVERN / IDENTIFY / PROTECT / DETECT / RESPOND / RECOVER ↔ DORA Pillar 1 article coverage
- ISO/IEC 27001:2022 — overlapping Annex A controls
- ISO 22301 — business continuity
- PCI DSS 4.0 — payment-specific (Art. 23 overlap)
- CRI Profile — financial-services cybersecurity profile

## Application + submission dates

- **17 January 2025** — DORA applies. Pre-existing programmes (BCM, ICT-security, third-party risk) must be DORA-aligned by this date.
- **Q1 of each year (from 2025)** — annual Register of Information submission to the competent authority (date set by the competent authority + ESAs).

## 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
// ---------------------------------------------------------------------------
const generate = (input) => {
    const identifier = `dora-compliance-agent-${input.location}-${input.department}`;
    const bundle = [
        {
            path: `.claude/agents/${identifier}.md`,
            content: buildAgentMd(input),
            mode: 0o444,
        },
        {
            path: '.claude/skills/compliance/dora-pack.md',
            content: buildPackSkill(input),
            mode: 0o644,
        },
        {
            path: '.claude/skills/compliance/dora-heartbeat.md',
            content: buildHeartbeatSkill(input),
            mode: 0o644,
        },
        {
            path: '.claude/skills/compliance/dora-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;
};
exports.generate = generate;
//# sourceMappingURL=dora.js.map