@abdulr7man/pensieve 0.0.0-stage → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/LICENSE +684 -0
  2. package/README.md +180 -2
  3. package/VERSION +1 -0
  4. package/agents/README.md +16 -0
  5. package/agents/pensieve-code-auditor.md +58 -0
  6. package/agents/pensieve-mapper.md +46 -0
  7. package/agents/pensieve-planner.md +67 -0
  8. package/agents/pensieve-reconner.md +76 -0
  9. package/agents/pensieve-reporter.md +61 -0
  10. package/agents/pensieve-roe-checker.md +46 -0
  11. package/agents/pensieve-scoper.md +77 -0
  12. package/agents/pensieve-tester.md +83 -0
  13. package/agents/pensieve-validator.md +62 -0
  14. package/bin/pensieve +452 -0
  15. package/bin/pensieve-installer.cjs +5 -0
  16. package/commands/pensieve-close.md +6 -0
  17. package/commands/pensieve-map.md +6 -0
  18. package/commands/pensieve-new-engagement.md +6 -0
  19. package/commands/pensieve-pause.md +15 -0
  20. package/commands/pensieve-plan.md +6 -0
  21. package/commands/pensieve-progress.md +34 -0
  22. package/commands/pensieve-quick.md +8 -0
  23. package/commands/pensieve-recon.md +6 -0
  24. package/commands/pensieve-report.md +6 -0
  25. package/commands/pensieve-resume.md +6 -0
  26. package/commands/pensieve-retest.md +10 -0
  27. package/commands/pensieve-scope.md +49 -0
  28. package/commands/pensieve-surface.md +8 -0
  29. package/commands/pensieve-test.md +6 -0
  30. package/commands/pensieve-validate.md +6 -0
  31. package/docker/Dockerfile.pensieve-toolbox +75 -0
  32. package/docker/compose.pensieve-net.yml +37 -0
  33. package/docker/squid.conf.template +21 -0
  34. package/package.json +39 -4
  35. package/packs/ad/ad-killchain/checklist.md +64 -0
  36. package/packs/ad/ad-killchain/pack.yaml +19 -0
  37. package/packs/cloud/cloud-cis/checklist.md +66 -0
  38. package/packs/cloud/cloud-cis/pack.yaml +20 -0
  39. package/packs/fintech/practice-core/checklist.md +33 -0
  40. package/packs/fintech/practice-core/learnings.md +5 -0
  41. package/packs/fintech/practice-core/pack.yaml +18 -0
  42. package/packs/infra/ptes-infra/checklist.md +22 -0
  43. package/packs/infra/ptes-infra/pack.yaml +19 -0
  44. package/packs/mobile/owasp-masvs/checklist.md +80 -0
  45. package/packs/mobile/owasp-masvs/pack.yaml +20 -0
  46. package/packs/owasp-api-v4/checklist.md +85 -0
  47. package/packs/owasp-api-v4/learnings.md +6 -0
  48. package/packs/owasp-api-v4/pack.yaml +23 -0
  49. package/packs/owasp-api-v4/runbooks/API1/SKILL.md +66 -0
  50. package/packs/owasp-api-v4/runbooks/API10/SKILL.md +67 -0
  51. package/packs/owasp-api-v4/runbooks/API2/SKILL.md +129 -0
  52. package/packs/owasp-api-v4/runbooks/API3/SKILL.md +55 -0
  53. package/packs/owasp-api-v4/runbooks/API4/SKILL.md +59 -0
  54. package/packs/owasp-api-v4/runbooks/API5/SKILL.md +60 -0
  55. package/packs/owasp-api-v4/runbooks/API6/SKILL.md +63 -0
  56. package/packs/owasp-api-v4/runbooks/API7/SKILL.md +70 -0
  57. package/packs/owasp-api-v4/runbooks/API8/SKILL.md +72 -0
  58. package/packs/owasp-api-v4/runbooks/API9/SKILL.md +66 -0
  59. package/packs/thickclient/thickclient-core/checklist.md +60 -0
  60. package/packs/thickclient/thickclient-core/pack.yaml +24 -0
  61. package/packs/web/asvs-l2/checklist.md +50 -0
  62. package/packs/web/asvs-l2/learnings.md +6 -0
  63. package/packs/web/asvs-l2/pack.yaml +19 -0
  64. package/packs/web/asvs-l2/runbooks/V2-AUTH-ENUM/SKILL.md +75 -0
  65. package/packs/web/asvs-l2/runbooks/V2-AUTH-LIVE/SKILL.md +78 -0
  66. package/packs/web/asvs-l2/runbooks/V2-AUTH-MFA/SKILL.md +76 -0
  67. package/packs/web/asvs-l2/runbooks/V2-AUTH-RATE/SKILL.md +72 -0
  68. package/packs/web/owasp-testing-checklist/checklist.md +52 -0
  69. package/packs/web/owasp-testing-checklist/learnings.md +47 -0
  70. package/packs/web/owasp-testing-checklist/pack.yaml +21 -0
  71. package/packs/web/unauth-perimeter/checklist.md +72 -0
  72. package/packs/web/unauth-perimeter/pack.yaml +18 -0
  73. package/packs/web/unauth-perimeter/runbooks/PERIM-01/SKILL.md +60 -0
  74. package/packs/web/unauth-perimeter/runbooks/PERIM-02/SKILL.md +63 -0
  75. package/packs/web/unauth-perimeter/runbooks/PERIM-03/SKILL.md +62 -0
  76. package/packs/web/unauth-perimeter/runbooks/PERIM-04/SKILL.md +75 -0
  77. package/packs/web/unauth-perimeter/runbooks/PERIM-05/SKILL.md +66 -0
  78. package/packs/web/unauth-perimeter/runbooks/PERIM-06/SKILL.md +59 -0
  79. package/packs/web/unauth-perimeter/runbooks/PERIM-07/SKILL.md +56 -0
  80. package/packs/web/unauth-perimeter/runbooks/PERIM-08/SKILL.md +57 -0
  81. package/packs/web/unauth-perimeter/runbooks/PERIM-09/SKILL.md +62 -0
  82. package/packs/web/unauth-perimeter/runbooks/PERIM-10/SKILL.md +60 -0
  83. package/packs/whitebox/code-audit-core/checklist.md +36 -0
  84. package/packs/whitebox/code-audit-core/learnings.md +6 -0
  85. package/packs/whitebox/code-audit-core/pack.yaml +14 -0
  86. package/prompts/orchestrator-core.md +52 -0
  87. package/reference/attack-playbooks.md +57 -0
  88. package/reference/otp-relay.md +98 -0
  89. package/reference/param-profiles.md +48 -0
  90. package/reference/templates/FINDING.md +97 -0
  91. package/reference/tool-selection.md +64 -0
  92. package/reference/vulnerability-finding-standard.md +80 -0
  93. package/runtimes/hermes/hooks/injection-scan.py +290 -0
  94. package/runtimes/hermes/hooks/scope-guard.py +136 -0
  95. package/skills/pensieve/SKILL.md +134 -0
  96. package/skills/pensieve-close/SKILL.md +31 -0
  97. package/skills/pensieve-map/SKILL.md +25 -0
  98. package/skills/pensieve-new-engagement/SKILL.md +28 -0
  99. package/skills/pensieve-pause/SKILL.md +22 -0
  100. package/skills/pensieve-plan/SKILL.md +39 -0
  101. package/skills/pensieve-progress/SKILL.md +35 -0
  102. package/skills/pensieve-quick/SKILL.md +47 -0
  103. package/skills/pensieve-recon/SKILL.md +30 -0
  104. package/skills/pensieve-report/SKILL.md +46 -0
  105. package/skills/pensieve-resume/SKILL.md +33 -0
  106. package/skills/pensieve-retest/SKILL.md +35 -0
  107. package/skills/pensieve-scope/SKILL.md +35 -0
  108. package/skills/pensieve-surface/SKILL.md +36 -0
  109. package/skills/pensieve-test/SKILL.md +35 -0
  110. package/skills/pensieve-validate/SKILL.md +28 -0
  111. package/skills/pensieve-wiki/SKILL.md +39 -0
  112. package/src/installer/cli.cjs +209 -0
  113. package/src/installer/home.cjs +155 -0
  114. package/src/installer/runtimes.cjs +276 -0
  115. package/src/installer/uninstall.cjs +342 -0
  116. package/src/pensieve-sdk/bin/pensieve-sdk.cjs +1045 -0
  117. package/src/pensieve-sdk/lib/agent-translate.cjs +50 -0
  118. package/src/pensieve-sdk/lib/approvals.cjs +408 -0
  119. package/src/pensieve-sdk/lib/audit.cjs +290 -0
  120. package/src/pensieve-sdk/lib/checklist.cjs +337 -0
  121. package/src/pensieve-sdk/lib/clientlist.cjs +814 -0
  122. package/src/pensieve-sdk/lib/close.cjs +133 -0
  123. package/src/pensieve-sdk/lib/config.cjs +156 -0
  124. package/src/pensieve-sdk/lib/cvss.cjs +91 -0
  125. package/src/pensieve-sdk/lib/env.cjs +272 -0
  126. package/src/pensieve-sdk/lib/evidence.cjs +217 -0
  127. package/src/pensieve-sdk/lib/findings.cjs +1096 -0
  128. package/src/pensieve-sdk/lib/frontmatter.cjs +178 -0
  129. package/src/pensieve-sdk/lib/graph.cjs +607 -0
  130. package/src/pensieve-sdk/lib/ids.cjs +63 -0
  131. package/src/pensieve-sdk/lib/init.cjs +79 -0
  132. package/src/pensieve-sdk/lib/liveness.cjs +176 -0
  133. package/src/pensieve-sdk/lib/loop.cjs +619 -0
  134. package/src/pensieve-sdk/lib/migrate.cjs +57 -0
  135. package/src/pensieve-sdk/lib/monitor.cjs +69 -0
  136. package/src/pensieve-sdk/lib/pack.cjs +607 -0
  137. package/src/pensieve-sdk/lib/paths.cjs +73 -0
  138. package/src/pensieve-sdk/lib/pdf.cjs +291 -0
  139. package/src/pensieve-sdk/lib/recon.cjs +296 -0
  140. package/src/pensieve-sdk/lib/renderers/__pycache__/formal_report.cpython-314.pyc +0 -0
  141. package/src/pensieve-sdk/lib/renderers/formal_report.py +608 -0
  142. package/src/pensieve-sdk/lib/report.cjs +1135 -0
  143. package/src/pensieve-sdk/lib/runbook.cjs +124 -0
  144. package/src/pensieve-sdk/lib/sarif.cjs +154 -0
  145. package/src/pensieve-sdk/lib/scope.cjs +621 -0
  146. package/src/pensieve-sdk/lib/security.cjs +61 -0
  147. package/src/pensieve-sdk/lib/skills.cjs +193 -0
  148. package/src/pensieve-sdk/lib/state.cjs +610 -0
  149. package/src/pensieve-sdk/lib/subagent.cjs +658 -0
  150. package/src/pensieve-sdk/lib/target.cjs +149 -0
  151. package/src/pensieve-sdk/lib/tools.cjs +66 -0
  152. package/src/pensieve-sdk/lib/vault.cjs +122 -0
  153. package/src/pensieve-sdk/lib/vendor/cvss40.LICENSE +22 -0
  154. package/src/pensieve-sdk/lib/vendor/cvss40.js +1208 -0
  155. package/src/pensieve-sdk/package.json +11 -0
  156. package/templates/ACCOUNTS.md +35 -0
  157. package/templates/ATTACK-SURFACE.md +30 -0
  158. package/templates/FINDING.md +43 -0
  159. package/templates/PLAN.md +33 -0
  160. package/templates/PROJECT.md +29 -0
  161. package/templates/ROE.md +50 -0
  162. package/templates/RUN-LOG.md +19 -0
  163. package/templates/SCOPE.md +32 -0
  164. package/templates/VALIDATION.md +62 -0
  165. package/templates/report/REPORT.md +49 -0
  166. package/workflows/close.md +34 -0
  167. package/workflows/map.md +39 -0
  168. package/workflows/new-engagement.md +37 -0
  169. package/workflows/plan.md +45 -0
  170. package/workflows/progress.md +28 -0
  171. package/workflows/quick.md +67 -0
  172. package/workflows/recon.md +87 -0
  173. package/workflows/report.md +51 -0
  174. package/workflows/resume.md +26 -0
  175. package/workflows/retest.md +53 -0
  176. package/workflows/scope.md +47 -0
  177. package/workflows/surface.md +29 -0
  178. package/workflows/test.md +95 -0
  179. package/workflows/validate.md +34 -0
@@ -0,0 +1,1096 @@
1
+ 'use strict';
2
+ /**
3
+ * findings.cjs — findings register: add, status machine, report gate, index (ADR-005/006).
4
+ * Status flow: draft -> validated|rejected; validated -> retest_pending -> retested_pass|retested_fail
5
+ * | validated -> risk_accepted (34-02 REP-04: owner-gated terminal closure)
6
+ * CVSS score/severity are COMPUTED from the vector here — never taken from the caller.
7
+ */
8
+
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const fm = require('./frontmatter.cjs');
12
+ const cvss = require('./cvss.cjs');
13
+ const paths = require('./paths.cjs');
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Phase 33 (REP-01): severity-letter finding IDs + structured standard fields
17
+ // (binding contract: reference/vulnerability-finding-standard.md).
18
+ //
19
+ // New registrations are IDed by SEVERITY LETTER + per-severity sequence
20
+ // (C-1, C-2 / H-1 / M-1 / L-1 / I-1), assigned ONCE from the SDK-computed
21
+ // CVSS bucket and IMMUTABLE — later status changes or re-scores never touch
22
+ // the id; the CURRENT severity stays its own stored/displayed field. Legacy
23
+ // F-### ids from existing engagements remain valid forever and resolve
24
+ // everywhere alongside the letter format (one resolver, below).
25
+ // ---------------------------------------------------------------------------
26
+
27
+ /** rank for the canonical register order (severity desc, then registration) */
28
+ const SEVERITY_RANK = { Critical: 4, High: 3, Medium: 2, Low: 1, None: 0, Informational: 0 };
29
+ /** CVSS bucket (cvss.severityBand: >=9.0 C, >=7.0 H, >=4.0 M, >0 L, 0.0 I) -> id letter */
30
+ const SEVERITY_LETTER = { Critical: 'C', High: 'H', Medium: 'M', Low: 'L', None: 'I', Informational: 'I' };
31
+ /** the Affected Assets fields of the standard (section 3) */
32
+ const AFFECTED_KEYS = ['app', 'env', 'host', 'endpoint', 'method', 'parameter', 'ip'];
33
+
34
+ /**
35
+ * CWE -> OWASP Top 10 / API Security Top 10 derivation (standard section 8:
36
+ * auto-derived from the CWE, best-effort, OVERRIDABLE via --references-owasp,
37
+ * and never forced when nothing maps). One CWE may derive several references
38
+ * (e.g. CWE-639 -> A01 access control AND API1 BOLA).
39
+ */
40
+ const CWE_TO_OWASP = [
41
+ { ref: 'OWASP Top 10 A01:2021 — Broken Access Control',
42
+ cwes: [22, 35, 59, 276, 284, 285, 402, 425, 441, 552, 639, 654, 668, 862, 863, 869] },
43
+ { ref: 'OWASP Top 10 A02:2021 — Cryptographic Failures',
44
+ cwes: [261, 295, 310, 319, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 335, 336, 337, 338, 340, 347] },
45
+ { ref: 'OWASP Top 10 A03:2021 — Injection',
46
+ cwes: [20, 74, 75, 77, 78, 79, 80, 83, 87, 88, 89, 90, 91, 93, 94, 95, 96, 97, 98, 99, 113, 116] },
47
+ { ref: 'OWASP Top 10 A05:2021 — Security Misconfiguration',
48
+ cwes: [2, 11, 13, 15, 16, 260, 315, 520, 521, 538, 541, 542, 547, 611, 614, 756] },
49
+ { ref: 'OWASP Top 10 A07:2021 — Identification and Authentication Failures',
50
+ cwes: [255, 259, 287, 288, 290, 294, 303, 307, 346, 384, 613, 640, 798, 916] },
51
+ { ref: 'OWASP API Security Top 10 API1:2023 — Broken Object Level Authorization',
52
+ cwes: [284, 285, 639, 862, 863] },
53
+ { ref: 'OWASP API Security Top 10 API2:2023 — Broken Authentication',
54
+ cwes: [287, 303, 613, 798] },
55
+ ];
56
+
57
+ function deriveOwaspRefs(cwe) {
58
+ const n = cweNumber(cwe);
59
+ if (n == null) return [];
60
+ return CWE_TO_OWASP.filter((e) => e.cwes.includes(n)).map((e) => e.ref);
61
+ }
62
+
63
+ /** severity-letter id for the NEXT registration of the given bucket letter */
64
+ function nextLetterId(existingIds, letter) {
65
+ let max = 0;
66
+ const re = new RegExp(`^${letter}-(\\d+)$`);
67
+ for (const id of existingIds || []) {
68
+ const m = re.exec(String(id));
69
+ if (m) max = Math.max(max, parseInt(m[1], 10));
70
+ }
71
+ return `${letter}-${max + 1}`;
72
+ }
73
+
74
+ /** global registration order: legacy F-number, or the stored seq of new-format rows */
75
+ function regSeqOf(f) {
76
+ if (typeof f.seq === 'number') return f.seq;
77
+ const m = /^F-(\d{3,})$/.exec(String(f.id || ''));
78
+ return m ? parseInt(m[1], 10) : Number.MAX_SAFE_INTEGER;
79
+ }
80
+
81
+ function nextRegSeq(rows) {
82
+ let max = 0;
83
+ for (const r of rows) max = Math.max(max, regSeqOf(r));
84
+ return max + 1;
85
+ }
86
+
87
+ /**
88
+ * normalizeFindingId — the canonical form used for EVERY id comparison:
89
+ * legacy F-### loses its zero padding (F-001/F-1/f-1 -> F-1), letter ids are
90
+ * uppercased (c-1 -> C-1). One rule, applied to both the stored and the
91
+ * supplied id, so both formats resolve everywhere through resolveFinding.
92
+ */
93
+ function normalizeFindingId(id) {
94
+ const s = String(id ?? '').trim();
95
+ if (!s) return '';
96
+ const m = /^f-(\d+)$/i.exec(s);
97
+ if (m) return `F-${parseInt(m[1], 10)}`;
98
+ return s.toUpperCase();
99
+ }
100
+
101
+ /** THE dual-format resolver: finds a register row by legacy F-### or letter id */
102
+ function resolveFinding(rows, id) {
103
+ const want = normalizeFindingId(id);
104
+ if (!want) return undefined;
105
+ return rows.find((r) => normalizeFindingId(r.id) === want);
106
+ }
107
+
108
+ /**
109
+ * parseAssetsTokens — --assets accepts BOTH shapes in one list:
110
+ * bare tokens (legacy array entries: scope asset ids / free-form tags) and
111
+ * key=value pairs for the standard's Affected Assets fields. key=value
112
+ * values DOUBLE as legacy array entries so asset->finding graph linkage
113
+ * (which matches array entries against in-scope asset ids/labels) keeps
114
+ * working. Unknown structured keys refuse fail-closed (typo protection).
115
+ */
116
+ function parseAssetsTokens(tokens) {
117
+ const list = [];
118
+ const affected = {};
119
+ for (const raw of (tokens || []).map((t) => String(t).trim()).filter(Boolean)) {
120
+ const eq = raw.indexOf('=');
121
+ if (eq > 0) {
122
+ const key = raw.slice(0, eq).trim().toLowerCase();
123
+ const val = raw.slice(eq + 1).trim();
124
+ if (!AFFECTED_KEYS.includes(key)) {
125
+ throw new Error(
126
+ `findings.add: unknown structured asset key "${key}" (in "${raw}") — accepted keys: `
127
+ + AFFECTED_KEYS.join(', ')
128
+ );
129
+ }
130
+ if (!val) throw new Error(`findings.add: structured asset "${raw}" has an empty value`);
131
+ affected[key] = val;
132
+ list.push(val);
133
+ } else {
134
+ list.push(raw);
135
+ }
136
+ }
137
+ return { list, affected };
138
+ }
139
+
140
+ function listOf(v) {
141
+ return (Array.isArray(v) ? v : (v == null ? [] : [v])).map((s) => String(s).trim()).filter(Boolean);
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Phase 33 (REP-01, plan 33-02): the finding DOCUMENT layer — the 9-section
146
+ // rendering of reference/vulnerability-finding-standard.md. The frontmatter
147
+ // stays the source of truth; the body is a DETERMINISTIC derived artifact
148
+ // (same record -> byte-identical document, no clocks in section bodies).
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /** the explicit marker for sections a legacy record cannot fill (never fabricated) */
152
+ const LEGACY_MARKER = '_not recorded — legacy format_';
153
+ /** the marker for closure fields no retest has filled yet (not a legacy issue — just not done) */
154
+ const NOT_RECORDED = '_not recorded_';
155
+
156
+ /** machine status -> the standard's section-9 closure vocabulary */
157
+ const STANDARD_STATUS = {
158
+ draft: 'Open',
159
+ validated: 'Open',
160
+ 'validated-static': 'Open',
161
+ rejected: 'Not Fixed (rejected at validation)',
162
+ retest_pending: 'Open (retest requested)',
163
+ retested_pass: 'Fixed',
164
+ retested_fail: 'Not Fixed',
165
+ risk_accepted: 'Risk Accepted',
166
+ };
167
+ const CLOSED_STATUSES = new Set(['rejected', 'retested_pass', 'retested_fail', 'risk_accepted']);
168
+
169
+ /**
170
+ * closureStatus — the standard's section-9 wording for a machine status (the
171
+ * ONE vocabulary accessor, 34-02 REP-04): validated is Open (awaiting retest),
172
+ * retest_pending is Open with the request named, retested_pass/retested_fail
173
+ * are Fixed/Not Fixed, risk_accepted is Risk Accepted, rejected is Not Fixed
174
+ * with the rejection point named. 'Partially Fixed' and 'Not Applicable' are
175
+ * DOCUMENTATION-ONLY statuses of the standard — they enter via the retest
176
+ * note, never as machine states (no status here invents them).
177
+ */
178
+ function closureStatus(status) {
179
+ return STANDARD_STATUS[status] || 'Open';
180
+ }
181
+
182
+ /** section 3 label/value rows: the standard's Affected Assets fields, in order */
183
+ const AFFECTED_LABELS = [
184
+ ['app', 'Application'], ['env', 'Environment'], ['host', 'Host'], ['endpoint', 'Endpoint'],
185
+ ['method', 'HTTP Method'], ['parameter', 'Parameter'], ['ip', 'IP'],
186
+ ];
187
+
188
+ /**
189
+ * closureLines — section 9's closure lines, the ONE renderer shared by the
190
+ * finding document layer (renderDocumentBody) and the report layer (REPORT.md
191
+ * finding blocks + the PDF payload, 35-01 REP-03): the current machine status
192
+ * in the standard vocabulary, the retest record's fields (date, endpoint,
193
+ * steps, observed result, supporting evidence — '_not recorded_' when the
194
+ * record does not carry them), the final status (the vocabulary word once
195
+ * closed, '_pending closure_' while open), the note, and the owner-signed
196
+ * risk acceptance when present. A pure function of the record.
197
+ */
198
+ function closureLines(data) {
199
+ const vocab = closureStatus(data.status);
200
+ const retest = data.retest && typeof data.retest === 'object' ? data.retest : {};
201
+ const risk = data.risk_acceptance && typeof data.risk_acceptance === 'object' ? data.risk_acceptance : null;
202
+ const lines = [
203
+ `- Current status: ${vocab} (register state: ${data.status})`,
204
+ `- Retest date: ${retest.date || NOT_RECORDED}`,
205
+ `- Tested endpoint: ${retest.endpoint || NOT_RECORDED}`,
206
+ `- Validation steps: ${retest.steps || NOT_RECORDED}`,
207
+ `- Observed result: ${retest.verdict === 'pass'
208
+ ? 'FIX VERIFIED — the reproduction no longer succeeds'
209
+ : retest.verdict === 'fail' ? 'STILL REPRODUCIBLE — the fix is ineffective' : NOT_RECORDED}`,
210
+ `- Final status: ${CLOSED_STATUSES.has(data.status) ? vocab : '_pending closure_'}`,
211
+ `- Supporting evidence: ${listOf(retest.evidence).join(', ') || NOT_RECORDED}`,
212
+ ];
213
+ if (retest.note) lines.push(`- Note: ${retest.note}`);
214
+ // 34-02 (REP-04): the owner-signed acceptance — who, when, why — rendered
215
+ // from the stored risk record (never a live clock), per the standard's
216
+ // 'Risk Accepted (with justification)'.
217
+ if (risk) {
218
+ lines.push(`- Risk accepted by: ${risk.by} on ${risk.date} — ${risk.note}`);
219
+ }
220
+ return lines;
221
+ }
222
+
223
+ /** the ledger lookup for inline rendering: caption (or note), figure if linked */
224
+ function evidenceEntry(dir, eid) {
225
+ const evidenceLib = require('./evidence.cjs');
226
+ const v = evidenceLib.verify(dir, eid);
227
+ if (!v.ok) return { id: eid, caption: '_not in the ledger_', figure: null };
228
+ const rec = v.record;
229
+ return {
230
+ id: eid,
231
+ caption: rec.caption || rec.note || '_no caption recorded_',
232
+ figure: rec.screenshot || null,
233
+ };
234
+ }
235
+
236
+ /** the citations a PoC step carries: inline [E-id] tokens (in order) + the poc_evidence mapping */
237
+ function citationsForStep(stepText, mapped) {
238
+ const out = [];
239
+ for (const m of String(stepText || '').matchAll(/\[(E-[0-9a-f]+)\]/gi)) {
240
+ if (!out.includes(m[1])) out.push(m[1]);
241
+ }
242
+ for (const eid of mapped || []) {
243
+ if (!out.includes(eid)) out.push(eid);
244
+ }
245
+ return out;
246
+ }
247
+
248
+ /**
249
+ * renderDocumentBody — the 9 sections in the EXACT standard order, evidence
250
+ * COMBINED into the PoC (each ordered step immediately followed by its cited
251
+ * artifacts as numbered Evidence entries), Impact with Demonstrated-before-
252
+ * Potential separation, Retest/Validation carrying the current machine status
253
+ * in the standard vocabulary + closure fields. Deterministic: a pure function
254
+ * of the record and the evidence ledger (no clocks).
255
+ */
256
+ function renderDocumentBody(dir, data, relPath) {
257
+ const L = [];
258
+ const push = (...lines) => L.push(...lines);
259
+
260
+ // -- section 1: Finding ID + Title --------------------------------------
261
+ push(`# ${data.id}: ${data.title}`);
262
+ const summary = typeof data.summary === 'string' ? data.summary.trim() : '';
263
+ if (summary) push('', `_${summary}_`);
264
+
265
+ // -- section 2: Severity & Risk Rating ----------------------------------
266
+ const band = data.severity === 'None' || data.severity == null ? 'Informational' : data.severity;
267
+ const business = listOf(data.impact && data.impact.business);
268
+ push('', '## Severity & Risk Rating', '',
269
+ `- Severity band: ${band}`,
270
+ `- CVSS base score: ${data.cvss_score} (SDK-computed)`,
271
+ `- CVSS vector: \`${data.cvss_vector}\``,
272
+ `- Business context: ${business.length ? business.join('; ') : LEGACY_MARKER}`);
273
+
274
+ // -- section 3: Affected Assets ------------------------------------------
275
+ const affected = data.affected && typeof data.affected === 'object' ? data.affected : {};
276
+ const assetLines = AFFECTED_LABELS
277
+ .filter(([key]) => affected[key])
278
+ .map(([key, label]) => `- ${label}: ${affected[key]}`);
279
+ const shown = new Set(Object.values(affected));
280
+ for (const tag of listOf(data.assets)) {
281
+ if (!shown.has(tag)) assetLines.push(`- Registered asset: ${tag}`);
282
+ }
283
+ push('', '## Affected Assets', '', ...(assetLines.length ? assetLines : [LEGACY_MARKER]));
284
+
285
+ // -- section 4: Description ----------------------------------------------
286
+ const description = typeof data.description === 'string' ? data.description.trim() : '';
287
+ push('', '## Description', '', description || LEGACY_MARKER);
288
+
289
+ // -- section 5: Technical Details / Proof of Concept (evidence COMBINED) --
290
+ push('', '## Technical Details / Proof of Concept');
291
+ const poc = listOf(data.poc);
292
+ const pocEvidence = data.poc_evidence && typeof data.poc_evidence === 'object' ? data.poc_evidence : {};
293
+ if (!poc.length) {
294
+ push('', LEGACY_MARKER);
295
+ } else {
296
+ let evN = 0;
297
+ const cited = new Set();
298
+ poc.forEach((step, i) => {
299
+ const n = i + 1;
300
+ const ids = citationsForStep(step, listOf(pocEvidence[String(n)]));
301
+ push('', `${n}. ${step}`);
302
+ if (ids.length) {
303
+ const entries = ids.map((eid) => { evN += 1; cited.add(eid); return [evN, evidenceEntry(dir, eid)]; });
304
+ push('');
305
+ for (const [n2, e] of entries) {
306
+ push(` - Evidence ${n2} — ${e.id}: ${e.caption}`);
307
+ if (e.figure) {
308
+ const rel = path.relative(path.dirname(relPath || 'findings/x.md'), e.figure).split(path.sep).join('/');
309
+ push(` - Figure — Evidence ${n2}: ![${e.id}](${rel})`);
310
+ }
311
+ }
312
+ }
313
+ });
314
+ // register evidence no step cites still belongs INSIDE the PoC section
315
+ // (the standard forbids a standalone evidence section)
316
+ const uncited = listOf(data.evidence).filter((eid) => !cited.has(eid));
317
+ if (uncited.length) {
318
+ push('', 'Additional register evidence (not cited by a PoC step):', '');
319
+ for (const eid of uncited) {
320
+ evN += 1;
321
+ const e = evidenceEntry(dir, eid);
322
+ push(`- Evidence ${evN} — ${e.id}: ${e.caption}`);
323
+ }
324
+ }
325
+ }
326
+
327
+ // -- section 6: Impact (Demonstrated FIRST, then Potential) --------------
328
+ const impact = data.impact && typeof data.impact === 'object' ? data.impact : {};
329
+ const impactBlocks = [
330
+ ['Demonstrated impact (proved during this assessment):', listOf(impact.demonstrated)],
331
+ ['Potential impact (substantiated, not demonstrated):', listOf(impact.potential)],
332
+ ['Technical impact:', listOf(impact.technical)],
333
+ ['Business impact:', listOf(impact.business)],
334
+ ];
335
+ push('', '## Impact');
336
+ for (const [header, items] of impactBlocks) {
337
+ push('', header, '', ...(items.length ? items.map((it) => `- ${it}`) : [`- ${LEGACY_MARKER}`]));
338
+ }
339
+
340
+ // -- section 7: Remediation ----------------------------------------------
341
+ const remediation = listOf(data.remediation);
342
+ push('', '## Remediation', '',
343
+ ...(remediation.length
344
+ ? remediation.map((r, i) => `${i + 1}. ${r}`)
345
+ : [LEGACY_MARKER]));
346
+
347
+ // -- section 8: References ------------------------------------------------
348
+ push('', '## References', '',
349
+ `- CWE: ${data.cwe || LEGACY_MARKER}`);
350
+ if (data.references_owasp == null) {
351
+ push(`- OWASP: ${LEGACY_MARKER}`);
352
+ } else if (!data.references_owasp.length) {
353
+ push('- OWASP: none derived (unmapped CWE — nothing forced)');
354
+ } else {
355
+ for (const ref of data.references_owasp) push(`- OWASP: ${ref}`);
356
+ }
357
+
358
+ // -- section 9: Retest / Validation ---------------------------------------
359
+ push('', '## Retest / Validation', '', ...closureLines(data));
360
+
361
+ return '\n' + L.join('\n') + '\n';
362
+ }
363
+
364
+ /** the appended `## Retest — <date>` log lanes (retestRecord) survive re-renders verbatim */
365
+ function retestLogSections(body) {
366
+ const out = [];
367
+ let cur = null;
368
+ for (const line of String(body).split('\n')) {
369
+ if (/^## Retest — /.test(line)) { cur = [line]; out.push(cur); continue; }
370
+ if (cur) {
371
+ if (/^## /.test(line)) cur = null;
372
+ else cur.push(line);
373
+ }
374
+ }
375
+ const text = out.map((l) => l.join('\n').replace(/\s+$/, '')).join('\n\n');
376
+ // single blank line before the first lane — byte-identical to what the
377
+ // retestRecord append itself produces (content\n + \n## Retest — ...)
378
+ return text ? '\n' + text : '';
379
+ }
380
+
381
+ /** a body is in the standard 9-section shape iff it carries the section-9 signature */
382
+ function isStandardShape(body) {
383
+ return /^## Retest \/ Validation$/m.test(String(body));
384
+ }
385
+
386
+ /**
387
+ * the standard body + any preserved retest log lanes, normalized to exactly
388
+ * one trailing newline — so the composition is byte-stable across re-renders
389
+ * (the retestRecord append leaves a trailing newline; the log extraction
390
+ * strips it; this puts it back deterministically).
391
+ */
392
+ function standardBodyWithLogs(dir, data, relPath, oldBody) {
393
+ const body = renderDocumentBody(dir, data, relPath) + retestLogSections(oldBody);
394
+ return body.endsWith('\n') ? body : body + '\n';
395
+ }
396
+
397
+ /** the `## <name>` section text of a body (legacy harvesting) */
398
+ function sectionText(body, name) {
399
+ const lines = String(body).split('\n');
400
+ const start = lines.findIndex((l) => l === `## ${name}`);
401
+ if (start === -1) return '';
402
+ const rest = lines.slice(start + 1);
403
+ const end = rest.findIndex((l) => /^## /.test(l));
404
+ return (end === -1 ? rest : rest.slice(0, end)).join('\n').trim();
405
+ }
406
+
407
+ /**
408
+ * renderDocument — (re)render a finding's .md in the 9-section standard shape
409
+ * from its record. Legacy records (F-### or letter-id without the structured
410
+ * fields) render EXPLICIT markers for what they lack — never fabricated
411
+ * content; their legacy Summary prose is harvested into the record so nothing
412
+ * real is lost. Appended `## Retest — ` log lanes are preserved verbatim.
413
+ * Idempotent: the same record renders byte-identically.
414
+ */
415
+ function renderDocument(dir, id) {
416
+ const found = resolveFinding(allFindings(dir), id);
417
+ if (!found) throw new Error(`finding not found: ${id}`);
418
+ const abs = paths.resolve(dir, found.path);
419
+ const { data, body } = fm.parse(fs.readFileSync(abs, 'utf8'));
420
+ if (data.summary == null || String(data.summary).trim() === '') {
421
+ const legacy = sectionText(body, 'Summary');
422
+ if (legacy && legacy !== '_pending_') data.summary = legacy;
423
+ }
424
+ const next = fm.stringify(data, standardBodyWithLogs(dir, data, found.path, body));
425
+ fs.writeFileSync(abs, next);
426
+ return { id: data.id, path: found.path, rendered: true };
427
+ }
428
+
429
+
430
+
431
+ const TRANSITIONS = {
432
+ draft: ['validated', 'rejected', 'validated-static'],
433
+ validated: ['retest_pending', 'risk_accepted'],
434
+ 'validated-static': [], // static-only verdict: no dynamic replay -> no retest lane
435
+ rejected: [],
436
+ retest_pending: ['retested_pass', 'retested_fail'],
437
+ retested_pass: [],
438
+ retested_fail: ['retest_pending'],
439
+ // 34-02 (REP-04): owner-gated terminal CLOSURE. Reachable ONLY from
440
+ // validated — the open, independently-proven finding the owner is accepting.
441
+ // The retest lane (retest_pending/retested_fail) and the producer/refusal
442
+ // states cannot reach it; and like retested_pass it has no exits.
443
+ risk_accepted: [],
444
+ };
445
+
446
+ // ---- Phase 21 (VAL-01): CWE-class-conditional validation controls ----
447
+ //
448
+ // Two hard-won validation rules become deterministic SDK gates instead of
449
+ // agent discipline, enforced at the draft->validated transition, fail-closed
450
+ // BEFORE any status write. Both classes come from the real operational record:
451
+ // TLS_FLOOR (CWE 319/310/326/327) — a silent TLS1.3 negotiation once faked
452
+ // a NULL-cipher acceptance: the replay must PROVE the protocol was forced
453
+ // (forced-protocol:) and the cipher observed on that forced protocol
454
+ // (control-cipher:).
455
+ // DISCLOSURE (CWE 200/209) — 200-with-friendly-error bodies are the endemic
456
+ // disclosure false-positive: the record must quote the actual response
457
+ // BODY (a fenced ```body-quote block), never a status code alone.
458
+ const TLS_FLOOR_CWES = new Set([319, 310, 326, 327]);
459
+ const DISCLOSURE_CWES = new Set([200, 209]);
460
+
461
+ /** 'CWE-319' / 'cwe 319' / '319' -> 319; anything unparsable/absent -> null */
462
+ function cweNumber(cwe) {
463
+ if (cwe == null) return null;
464
+ const m = /(\d+)\s*$/.exec(String(cwe).trim());
465
+ return m ? parseInt(m[1], 10) : null;
466
+ }
467
+
468
+ /** the validator-record convention (agents/pensieve-validator.md): one file per finding */
469
+ function validationRecordRel(id) { return path.join('findings', `VALIDATION-${id}.md`); }
470
+
471
+ /** line-prefix grep: the marker must START its own line — prose mentions are not controls */
472
+ function hasMarkerLine(text, marker) {
473
+ return text.split(/\r?\n/).some((line) => line.startsWith(marker));
474
+ }
475
+
476
+ /** fenced ```body-quote block holding >=1 line with >10 non-space chars (the actual body, not 'HTTP 200') */
477
+ function hasBodyQuote(text) {
478
+ const lines = text.split(/\r?\n/);
479
+ let inBlock = false;
480
+ for (const line of lines) {
481
+ const t = line.trim();
482
+ if (!inBlock) {
483
+ if (/^```body-quote\b/.test(t)) inBlock = true;
484
+ } else if (/^```$/.test(t)) {
485
+ inBlock = false;
486
+ } else if (t.replace(/\s/g, '').length > 10) {
487
+ return true;
488
+ }
489
+ }
490
+ return false;
491
+ }
492
+
493
+ /**
494
+ * enforceValidationControls — called by setStatus BEFORE the status write.
495
+ * - only the dynamic `validated` verdict is controlled: `validated-static`
496
+ * is the white-box lane (no replay by definition) and rejected/retest
497
+ * transitions are untouched;
498
+ * - findings outside both CWE classes validate exactly as before (no record
499
+ * is read for them);
500
+ * - refusal names the finding id, the CWE class, and the missing control,
501
+ * and leaves all state untouched (fail-closed, no partial writes).
502
+ */
503
+ function enforceValidationControls(dir, found, nextStatus) {
504
+ if (nextStatus !== 'validated') return;
505
+ const cwe = cweNumber(found.cwe);
506
+ const isTlsFloor = TLS_FLOOR_CWES.has(cwe);
507
+ const isDisclosure = DISCLOSURE_CWES.has(cwe);
508
+ if (!isTlsFloor && !isDisclosure) return;
509
+ const rel = validationRecordRel(found.id);
510
+ const cls = isTlsFloor ? 'TLS-floor (CWE 319/310/326/327)' : 'disclosure (CWE 200/209)';
511
+ const abs = paths.resolve(dir, rel);
512
+ if (!fs.existsSync(abs)) {
513
+ throw new Error(
514
+ `${found.id} refused: CWE class ${cls} — no validation record at ${rel}; the control markers cannot be checked`
515
+ );
516
+ }
517
+ const record = fs.readFileSync(abs, 'utf8');
518
+ if (isTlsFloor) {
519
+ const missing = [];
520
+ if (!hasMarkerLine(record, 'forced-protocol:')) {
521
+ missing.push('forced-protocol: (the replay FORCED the exact protocol — silent negotiation once faked a NULL-cipher accept)');
522
+ }
523
+ if (!hasMarkerLine(record, 'control-cipher:')) {
524
+ missing.push('control-cipher: (the cipher observed ON the forced protocol)');
525
+ }
526
+ if (missing.length) {
527
+ throw new Error(`${found.id} refused: CWE class ${cls} — ${rel} missing markers: ${missing.join('; ')}`);
528
+ }
529
+ } else if (!hasBodyQuote(record)) {
530
+ throw new Error(
531
+ `${found.id} refused: CWE class ${cls} — ${rel} missing control: body-quote `
532
+ + '(a fenced ```body-quote block quoting the actual response BODY — a status code alone, '
533
+ + "e.g. 'HTTP 200 returned', is not disclosure proof)"
534
+ );
535
+ }
536
+ }
537
+
538
+
539
+ // ---- Phase 34 (REP-02): the mandatory-sections gate (findings-standard) ----
540
+ //
541
+ // reference/vulnerability-finding-standard.md stops being a template and
542
+ // becomes a GATE: no finding leaves draft for `validated` until its MANDATORY
543
+ // sections exist on the STORED record (the 33-01 field shapes — the gate reads
544
+ // the record, never a re-parse of the rendered document). This rides the exact
545
+ // 21-01 refusal pattern: fail-closed BEFORE the status write, ONE message
546
+ // naming EVERY missing section at once, nothing changed on refusal.
547
+ //
548
+ // affected-assets section 3 — structured identifiers OR registered tags
549
+ // description section 4 — the root cause
550
+ // poc-with-inline-evidence section 5 — >=1 step AND >=1 citation, and every
551
+ // cited [E-id] re-verified against the ledger (the
552
+ // DOCUMENT state, not just the add-time check)
553
+ // impact section 6 — at least DEMONSTRATED impact
554
+ // remediation section 7 — an actionable fix
555
+ //
556
+ // title + severity computed at add — can never be missing
557
+ // references section 8 — recommended-only, NEVER blocks
558
+ //
559
+ // Legacy / field-less records (F-### or letter ids without the structured
560
+ // fields) refuse the SAME way — no grandfathering into validated. Completing
561
+ // an existing record in place is a findings.update verb, DEFERRED (34-01
562
+ // SUMMARY); completion today is a NEW record registered with the add-time
563
+ // flags. `validated-static` (the white-box lane) keeps the VAL-01 exemption:
564
+ // no dynamic replay, no controls — and no standard gate either.
565
+
566
+ /** the mandatory sections missing from a stored record, in standard order */
567
+ function standardSectionGaps(dir, found) {
568
+ const gaps = [];
569
+ const affected = found.affected && typeof found.affected === 'object' ? found.affected : {};
570
+ if (!Object.keys(affected).length && !listOf(found.assets).length) {
571
+ gaps.push('affected-assets (no asset identifiers recorded — app/env/host/endpoint/method/parameter/ip, or a registered asset tag)');
572
+ }
573
+ if (!String(found.description || '').trim()) {
574
+ gaps.push('description (the root cause is undocumented)');
575
+ }
576
+ const poc = listOf(found.poc);
577
+ const pocEvidence = found.poc_evidence && typeof found.poc_evidence === 'object' ? found.poc_evidence : {};
578
+ if (!poc.length) {
579
+ gaps.push('poc-with-inline-evidence (no reproduction steps)');
580
+ } else {
581
+ // every [E-id] a step cites — inline tokens first, then the poc_evidence
582
+ // mapping for that step — deduped in citation order
583
+ const cited = [];
584
+ for (let i = 0; i < poc.length; i += 1) {
585
+ for (const eid of citationsForStep(poc[i], listOf(pocEvidence[String(i + 1)]))) {
586
+ if (!cited.includes(eid)) cited.push(eid);
587
+ }
588
+ }
589
+ if (!cited.length) {
590
+ gaps.push('poc-with-inline-evidence (poc: no evidence citations — every claim-carrying step must cite its proof [E-id] inline, evidence detached from the steps it proves proves nothing)');
591
+ } else {
592
+ // the gate re-verifies the DOCUMENT state: add-time verification is not
593
+ // enough once the ledger can drift (tamper/reorder) after registration
594
+ const evidenceLib = require('./evidence.cjs');
595
+ const drifted = cited.filter((eid) => !evidenceLib.verify(dir, eid).ok);
596
+ if (drifted.length) {
597
+ gaps.push(`poc-with-inline-evidence (citations no longer verify in the ledger: ${drifted.join(', ')})`);
598
+ }
599
+ }
600
+ }
601
+ const impact = found.impact && typeof found.impact === 'object' ? found.impact : {};
602
+ if (!listOf(impact.demonstrated).length) {
603
+ gaps.push('impact (no demonstrated impact — separate demonstrated from potential, never claim what was not shown)');
604
+ }
605
+ if (!listOf(found.remediation).length) {
606
+ gaps.push('remediation (no actionable fix recorded)');
607
+ }
608
+ return gaps;
609
+ }
610
+
611
+ /**
612
+ * enforceStandardSections — the REP-02 gate, called by setStatus after the
613
+ * 21-01 class controls and BEFORE the status write. The thrown Error carries
614
+ * `gate: 'findings-standard'`; the CLI surfaces it as its own ok:false
615
+ * envelope with the gate name and the full message (the report.pdf
616
+ * pass-through pattern — sanitizeError would truncate the every-section-
617
+ * at-once message at 300 chars).
618
+ */
619
+ function enforceStandardSections(dir, found, nextStatus) {
620
+ if (nextStatus !== 'validated') return;
621
+ const gaps = standardSectionGaps(dir, found);
622
+ if (!gaps.length) return;
623
+ const err = new Error(
624
+ `${found.id} refused: findings-standard gate — missing mandatory sections: ${gaps.join('; ')}. `
625
+ + 'A finding leaves draft for validated only when the standard '
626
+ + '(reference/vulnerability-finding-standard.md) is complete on its record; references are '
627
+ + 'recommended-only and never block. Nothing was changed.'
628
+ );
629
+ err.gate = 'findings-standard';
630
+ throw err;
631
+ }
632
+
633
+
634
+ // ---- Phase 34 (REP-04, plan 34-02): risk_accepted — the owner gate -------
635
+ //
636
+ // The standard's Risk Accepted becomes a REAL machine state, but an
637
+ // acceptance is a signed decision, not a status flip: it requires BOTH the
638
+ // accountable owner (--by) and the recorded justification (--note), checked
639
+ // fail-closed BEFORE any write (the 21-01/34-01 pattern — one refusal names
640
+ // every missing input, nothing is changed). The record stores who/when/why
641
+ // (risk_acceptance: { by, date, note }); the date is recorded ONCE, like
642
+ // retest.date, so document re-renders stay deterministic (no live clocks in
643
+ // bodies). The state itself is terminal closure — PASSING_STATUSES is
644
+ // UNCHANGED: risk_accepted does not cover a goal path (goal.verify still
645
+ // gaps it); it only closes the finding.
646
+ function enforceRiskAcceptance(found, meta) {
647
+ const by = typeof meta.by === 'string' ? meta.by.trim() : '';
648
+ const note = typeof meta.note === 'string' ? meta.note.trim() : '';
649
+ const missing = [];
650
+ if (!by) missing.push('--by <owner> (the accountable owner accepting the risk)');
651
+ if (!note) missing.push("--note '<justification>' (why the residual risk is acceptable)");
652
+ if (missing.length) {
653
+ throw new Error(
654
+ `${found.id} refused: risk_accepted requires BOTH --by and --note — missing: ${missing.join('; ')}. `
655
+ + 'An acceptance without an accountable owner or a recorded justification is an opinion, '
656
+ + 'not a closure. Nothing was changed.'
657
+ );
658
+ }
659
+ return { by, date: new Date().toISOString().slice(0, 10), note };
660
+ }
661
+
662
+
663
+ // brief 1.5 (v0.6 01-03 / ADR-012): the white-box lane. A finding resolved
664
+ // by static (white-box) review alone — validated-static — is a PASSING verdict
665
+ // for the findings gate, exactly like a dynamically validated one. It just
666
+ // cannot enter the retest lane (no dynamic replay was performed).
667
+ const PASSING_STATUSES = new Set(['validated', 'validated-static', 'retested_pass', 'retested_fail']);
668
+ function isPassing(f) { return PASSING_STATUSES.has(f.status); }
669
+
670
+ function findingsDir(dir) { return paths.findingsDir(dir); }
671
+
672
+ function slugTitle(t) {
673
+ return t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-{2,}/g, '-').replace(/^-|-$/g, '').slice(0, 60);
674
+ }
675
+
676
+ function readFindingFile(file) {
677
+ const { data } = fm.parse(fs.readFileSync(file, 'utf8'));
678
+ return data;
679
+ }
680
+
681
+ /**
682
+ * the register read — THE single choke point every consumer goes through.
683
+ * Accepts BOTH id formats' files (legacy F-### and severity-letter C/H/M/L/I)
684
+ * and returns the canonical order: severity desc, then registration order
685
+ * (global seq; legacy rows derive theirs from the F-number). The filename
686
+ * sort the letter format would break at N>=10 (C-10 < C-2 lexically) is
687
+ * therefore never relied upon.
688
+ */
689
+ const FINDING_FILE_RE = /^(?:F-\d+|[CHMLI]-\d+).*\.md$/;
690
+
691
+ function allFindings(dir) {
692
+ const fd = findingsDir(dir);
693
+ if (!fs.existsSync(fd)) return [];
694
+ const rows = fs.readdirSync(fd)
695
+ .filter((f) => FINDING_FILE_RE.test(f))
696
+ .map((f) => ({ ...readFindingFile(path.join(fd, f)), path: path.join('findings', f) }));
697
+ const rank = (r) => SEVERITY_RANK[r.severity] ?? 0;
698
+ return rows.sort((a, b) => (rank(b) - rank(a)) || (regSeqOf(a) - regSeqOf(b))
699
+ || String(a.id).localeCompare(String(b.id)));
700
+ }
701
+
702
+ function rebuildIndex(dir) {
703
+ const rows = allFindings(dir);
704
+ const lines = [
705
+ '# Findings Index',
706
+ '',
707
+ '| ID | Title | CWE | CVSS | Severity | Status |',
708
+ '|----|-------|-----|------|----------|--------|',
709
+ ...rows.map((r) => `| ${r.id} | ${String(r.title).replace(/\|/g, '\\|')} | ${r.cwe} | ${r.cvss_score} | ${r.severity} | ${r.status} |`),
710
+ '',
711
+ ];
712
+ fs.writeFileSync(paths.findingsIndex(dir), lines.join('\n'));
713
+ }
714
+
715
+ function add(dir, {
716
+ title, cwe, cvss_vector, assets = [], summary = '', evidence = [],
717
+ // ---- Phase 33 (REP-01) structured standard fields. ALL optional at add —
718
+ // REP-02 enforces completeness at the draft->validated transition, not here.
719
+ // Evidence citations they carry (poc inline '[E-id]', poc-evidence mapping)
720
+ // join the SAME ledger verification as --evidence (fail-closed at add).
721
+ description = '',
722
+ poc = [], // ordered steps; inline '[E-id]' citations allowed
723
+ pocEvidence = {}, // { stepNumber(1-based): [evidence ids] }
724
+ impact = {}, // { demonstrated[], potential[], technical[], business[] }
725
+ remediation = [], // ordered
726
+ referencesOwasp = null, // array — overrides the CWE auto-derivation
727
+ } = {}) {
728
+ if (!title || !cvss_vector) throw new Error('finding requires title and cvss_vector');
729
+ // brief 1.4 (v0.6 01-03): every evidence id cited by a finding MUST exist in
730
+ // the hash-chained ledger (evidence/INDEX.md). A finding is a claim; it must
731
+ // be bound to proof we can re-verify. REP-01 extends the SAME bar to the
732
+ // citations carried by the structured fields (poc steps cite inline,
733
+ // --poc-evidence maps step numbers) — every cited id, wherever it appears,
734
+ // is verified, and the refusal names the offending id(s) so the operator
735
+ // can correct a typo / stale id rather than silently dropping the linkage.
736
+ const evidenceLib = require('./evidence.cjs');
737
+ const evidenceList = listOf(evidence);
738
+ const pocList = listOf(poc);
739
+ const pocEvidenceMap = {};
740
+ for (const [step, ids] of Object.entries(pocEvidence || {})) {
741
+ const l = listOf(ids);
742
+ if (l.length) pocEvidenceMap[String(step)] = l;
743
+ }
744
+ const cited = new Set(evidenceList);
745
+ for (const step of pocList) {
746
+ for (const m of String(step).matchAll(/\[(E-[0-9a-f]+)\]/gi)) cited.add(m[1]);
747
+ }
748
+ for (const ids of Object.values(pocEvidenceMap)) for (const eid of ids) cited.add(eid);
749
+ for (const eid of cited) {
750
+ const v = evidenceLib.verify(dir, eid);
751
+ if (!v.ok) {
752
+ throw new Error(`findings.add: cited evidence id ${eid} is not in the ledger — ${v.reason}`);
753
+ }
754
+ }
755
+ const scored = cvss.score(cvss_vector); // throws on malformed vector
756
+ const rows = allFindings(dir);
757
+ // ID: severity letter from the SDK-computed bucket + INDEPENDENT per-severity
758
+ // counter. Assigned ONCE, immutable from here on (later status changes /
759
+ // re-scores never rewrite it — the current severity is its own field below).
760
+ const letter = SEVERITY_LETTER[scored.severity] || 'I';
761
+ const id = nextLetterId(rows.map((f) => f.id), letter);
762
+ const seq = nextRegSeq(rows); // global registration order (register sort key)
763
+ const { list: assetList, affected } = parseAssetsTokens(assets);
764
+ const impactFields = {
765
+ demonstrated: listOf(impact.demonstrated),
766
+ potential: listOf(impact.potential),
767
+ technical: listOf(impact.technical),
768
+ business: listOf(impact.business),
769
+ };
770
+ const data = {
771
+ id, title, cwe: cwe || null,
772
+ cvss_vector, cvss_score: scored.score, severity: scored.severity,
773
+ status: 'draft', assets: assetList, evidence: evidenceList,
774
+ // REP-01 structured standard fields
775
+ description: description || null,
776
+ poc: pocList,
777
+ poc_evidence: pocEvidenceMap,
778
+ impact: impactFields,
779
+ remediation: listOf(remediation),
780
+ affected,
781
+ references_owasp: referencesOwasp != null ? listOf(referencesOwasp) : deriveOwaspRefs(cwe),
782
+ seq,
783
+ summary: summary || null, // 33-02: stored (not just body-embedded) so re-renders are lossless
784
+ created: new Date().toISOString().slice(0, 10),
785
+ };
786
+ // 33-02 (REP-01 document layer): a finding carrying structured standard
787
+ // fields is written DIRECTLY in the 9-section standard shape; a field-less
788
+ // add keeps the legacy 4-section template (the historical record shape —
789
+ // renderDocument upgrades it on demand, with explicit markers).
790
+ const hasStandardFields = Boolean((description || '').trim())
791
+ || pocList.length > 0
792
+ || Object.values(impactFields).some((l) => l.length > 0)
793
+ || listOf(remediation).length > 0;
794
+ const rel = path.join('findings', `${id}-${slugTitle(title)}.md`);
795
+ const body = hasStandardFields
796
+ ? renderDocumentBody(dir, data, rel)
797
+ : `\n## Summary\n\n${summary || '_pending_'}\n\n## Attack Narrative\n\n_pending_\n\n## Evidence\n\n_pending_\n\n## Remediation\n\n_pending_\n`;
798
+ fs.mkdirSync(findingsDir(dir), { recursive: true });
799
+ fs.writeFileSync(paths.resolve(dir, rel), fm.stringify(data, body));
800
+ rebuildIndex(dir);
801
+ return { ...data, path: rel };
802
+ }
803
+
804
+ /**
805
+ * update — complete/edit an EXISTING record in place (36-01, closing the
806
+ * 34-01 deferral). Takes the SAME field inputs as add(); provided fields
807
+ * REPLACE the stored ones, unprovided fields are untouched. IMMUTABLE: the
808
+ * finding id, the cvss vector/score/severity letter (a --cvss input is
809
+ * REFUSED pointing at registering a new finding — the id scheme is assigned
810
+ * once at registration), and the status (transitions belong to
811
+ * findings.status, so the REP-02 gates still run on the completed record —
812
+ * update NEVER weakens them). Works on BOTH id formats through the ONE
813
+ * dual-format resolver. The add-time evidence bar rides along: every id the
814
+ * RESULTING record cites (--evidence, inline [E-id] in poc steps,
815
+ * --poc-evidence values) is ledger-verified fail-closed BEFORE any write.
816
+ * After the write the document re-renders (renderDocument — a legacy body is
817
+ * upgraded to the standard shape on demand) and rebuildIndex refreshes the
818
+ * register index; repeated renders stay byte-stable.
819
+ */
820
+ function update(dir, id, {
821
+ cvss: newCvss = null,
822
+ description, poc, pocEvidence, impact = {}, remediation,
823
+ assets, referencesOwasp, evidence,
824
+ } = {}) {
825
+ const found = resolveFinding(allFindings(dir), id);
826
+ if (!found) throw new Error(`finding not found: ${id}`);
827
+ if (newCvss != null && String(newCvss).trim() !== '') {
828
+ throw new Error(
829
+ `${found.id} refused: findings.update cannot change the cvss vector/score/severity — `
830
+ + 'the id scheme is assigned ONCE at registration and the severity letter is immutable. '
831
+ + 'Register a NEW finding (findings.add --title ... --cvss ...) for the re-scored issue. '
832
+ + 'Nothing was changed.'
833
+ );
834
+ }
835
+ const abs = paths.resolve(dir, found.path);
836
+ const { data, body } = fm.parse(fs.readFileSync(abs, 'utf8'));
837
+ const updated = [];
838
+
839
+ // -- section 4: description (string) ------------------------------------
840
+ if (description !== undefined) {
841
+ data.description = String(description || '') || null; // the add-time shape
842
+ updated.push('description');
843
+ }
844
+ // -- section 5: poc steps + the step->evidence mapping ------------------
845
+ if (poc !== undefined) {
846
+ data.poc = listOf(poc);
847
+ updated.push('poc');
848
+ }
849
+ if (pocEvidence !== undefined) {
850
+ const map = {};
851
+ for (const [step, ids] of Object.entries(pocEvidence || {})) {
852
+ const l = listOf(ids);
853
+ if (l.length) map[String(step)] = l;
854
+ }
855
+ data.poc_evidence = map;
856
+ updated.push('poc-evidence');
857
+ }
858
+ // -- section 6: impact — sub-fields replace INDIVIDUALLY ----------------
859
+ const impactStored = data.impact && typeof data.impact === 'object' && !Array.isArray(data.impact)
860
+ ? { ...data.impact } : {};
861
+ for (const key of ['demonstrated', 'potential', 'technical', 'business']) {
862
+ if (impact[key] !== undefined) {
863
+ impactStored[key] = listOf(impact[key]);
864
+ updated.push(`impact-${key}`);
865
+ }
866
+ }
867
+ if (updated.some((u) => u.startsWith('impact-'))) data.impact = impactStored;
868
+ // -- section 7: remediation (ordered) ------------------------------------
869
+ if (remediation !== undefined) {
870
+ data.remediation = listOf(remediation);
871
+ updated.push('remediation');
872
+ }
873
+ // -- section 3: assets — ONE input populates both shapes (the add-time
874
+ // parser: bare tokens = legacy array entries, key=value = structured fields;
875
+ // unknown structured keys refuse fail-closed)
876
+ if (assets !== undefined) {
877
+ const { list, affected } = parseAssetsTokens(listOf(assets));
878
+ data.assets = list;
879
+ data.affected = affected;
880
+ updated.push('assets');
881
+ }
882
+ // -- section 8: references (recommended-only — never gates) --------------
883
+ if (referencesOwasp !== undefined) {
884
+ data.references_owasp = listOf(referencesOwasp);
885
+ updated.push('references-owasp');
886
+ }
887
+ // -- ledger links (--evidence) -------------------------------------------
888
+ if (evidence !== undefined) {
889
+ data.evidence = listOf(evidence);
890
+ updated.push('evidence');
891
+ }
892
+
893
+ // the 33-01 evidence bar, re-run over the RESULTING record's citations —
894
+ // fail-closed BEFORE any write, naming the offending id(s).
895
+ const evidenceLib = require('./evidence.cjs');
896
+ const cited = new Set(listOf(data.evidence));
897
+ for (const step of listOf(data.poc)) {
898
+ for (const m of String(step).matchAll(/\[(E-[0-9a-f]+)\]/gi)) cited.add(m[1]);
899
+ }
900
+ const pe = data.poc_evidence && typeof data.poc_evidence === 'object' ? data.poc_evidence : {};
901
+ for (const ids of Object.values(pe)) for (const eid of listOf(ids)) cited.add(eid);
902
+ for (const eid of cited) {
903
+ const v = evidenceLib.verify(dir, eid);
904
+ if (!v.ok) {
905
+ throw new Error(`findings.update: cited evidence id ${eid} is not in the ledger — ${v.reason}`);
906
+ }
907
+ }
908
+
909
+ // write the record (body untouched here — renderDocument re-renders it
910
+ // from the record below, upgrading legacy bodies on demand)
911
+ fs.writeFileSync(abs, fm.stringify(data, body));
912
+ renderDocument(dir, id);
913
+ rebuildIndex(dir);
914
+ const row = resolveFinding(allFindings(dir), id);
915
+ return { ...row, updated };
916
+ }
917
+
918
+ function setStatus(dir, id, status, meta = {}) {
919
+ if (!(status in TRANSITIONS)) throw new Error(`unknown finding status: ${status}`);
920
+ // REP-01: the ONE dual-format resolver — legacy F-### and C/H/M/L/I ids
921
+ // both land here; ids are matched, never mutated, by any status change.
922
+ const found = resolveFinding(allFindings(dir), id);
923
+ if (!found) throw new Error(`finding not found: ${id}`);
924
+ const allowed = TRANSITIONS[found.status];
925
+ if (!allowed.includes(status)) {
926
+ throw new Error(`invalid transition: ${found.status} -> ${status} (allowed: ${allowed.join('|') || 'none'})`);
927
+ }
928
+ enforceValidationControls(dir, found, status); // Phase 21 VAL-01: fail-closed BEFORE the write
929
+ enforceStandardSections(dir, found, status); // Phase 34 REP-02: mandatory sections before the write
930
+ // Phase 34 REP-04: the owner gate — checked and stamped only for the
931
+ // acceptance itself (every other transition ignores by/note entirely).
932
+ const risk = status === 'risk_accepted' ? enforceRiskAcceptance(found, meta) : null;
933
+ const abs = paths.resolve(dir, found.path);
934
+ let next = fm.set(fs.readFileSync(abs, 'utf8'), 'status', status);
935
+ if (risk) next = fm.set(next, 'risk_acceptance', risk);
936
+ // 33-02: a document in the standard 9-section shape re-renders on every
937
+ // status change so section 9 always carries the CURRENT machine status.
938
+ // Legacy-template bodies are left byte-untouched (history is never rewritten
939
+ // implicitly — renderDocument upgrades them on demand).
940
+ const parsed = fm.parse(next);
941
+ if (isStandardShape(parsed.body)) {
942
+ next = fm.stringify(parsed.data, standardBodyWithLogs(dir, parsed.data, found.path, parsed.body));
943
+ }
944
+ fs.writeFileSync(abs, next);
945
+ rebuildIndex(dir);
946
+ return { id, status };
947
+ }
948
+
949
+ function list(dir, filter = {}) {
950
+ let rows = allFindings(dir);
951
+ if (filter.id) rows = rows.filter((r) => resolveFinding([r], filter.id)); // dual-format
952
+ if (filter.status) rows = rows.filter((r) => r.status === filter.status);
953
+ return rows;
954
+ }
955
+
956
+ /**
957
+ * attestClean(dir, evidenceIds[]) — zero-findings gate (v0.6 01-03, ADR-023
958
+ * extension / brief 1.3). A genuinely clean engagement (zero findings) can
959
+ * pass the gate, but ONLY if the operator supplies evidence ids that back
960
+ * the "no findings" verdict — same evidence bar as add/retest-record. Refuses:
961
+ * - a non-empty register (you cannot attest "clean" while findings exist);
962
+ * - with no evidence ids (a verdict without proof is an assertion);
963
+ * - with any evidence id that is missing / hash-tampered in the ledger
964
+ * (evidence.verify), naming the offending id(s).
965
+ * On success it stamps an ATTESTATION block into findings/INDEX.md and the
966
+ * gate opens (report_ready) — the report may compile with zero findings.
967
+ */
968
+ function attestClean(dir, evidenceIds) {
969
+ const rows = allFindings(dir);
970
+ if (rows.length > 0) {
971
+ throw new Error(`findings.register is non-empty (${rows.length} finding(s)) — 'clean' is not a valid attestation (brief 1.3: zero-findings gate)`);
972
+ }
973
+ const ids = (evidenceIds || []).map((s) => String(s).trim()).filter(Boolean);
974
+ if (ids.length === 0) {
975
+ throw new Error(`attestClean requires at least one evidence id (--evidence E-id[,E-id]) — a clean verdict without evidence is an assertion (brief 1.3)`);
976
+ }
977
+ const evidenceLib = require('./evidence.cjs');
978
+ for (const eid of ids) {
979
+ const v = evidenceLib.verify(dir, eid);
980
+ if (!v.ok) {
981
+ throw new Error(`attestClean evidence invalid: ${eid} — ${v.reason}`);
982
+ }
983
+ }
984
+ const file = paths.findingsIndex(dir);
985
+ if (fs.existsSync(file)) {
986
+ fs.unlinkSync(file);
987
+ }
988
+ rebuildIndex(dir);
989
+ const stamp = fs.readFileSync(file, 'utf8');
990
+ const attLine = `## ATTESTATION\n\n- **clean verdict**: registered 0 findings; evidence ${ids.join(', ')}`;
991
+ fs.writeFileSync(file, stamp + '\n' + attLine + '\n');
992
+ return { attested: true, evidence: ids, findings: rows.length };
993
+ }
994
+
995
+ function gate(dir) {
996
+ const rows = allFindings(dir);
997
+ const drafts = rows.filter((r) => r.status === 'draft').map((r) => r.id);
998
+ // "resolved / accepted" = a passing status (brief 1.5: the white-box lane,
999
+ // validated-static, counts as passing alongside the dynamic verdicts).
1000
+ const validated = rows.filter((r) => isPassing(r)).map((r) => r.id);
1001
+ const validatedStatic = rows.filter((r) => r.status === 'validated-static').map((r) => r.id);
1002
+ // zero-findings: opens ONLY when attestClean stamped the register (brief 1.3)
1003
+ const clean = fs.existsSync(paths.findingsIndex(dir))
1004
+ ? /## ATTESTATION/.test(fs.readFileSync(paths.findingsIndex(dir), 'utf8'))
1005
+ : false;
1006
+ return {
1007
+ total: rows.length,
1008
+ draft: drafts,
1009
+ validated,
1010
+ validatedStatic,
1011
+ rejected: rows.filter((r) => r.status === 'rejected').map((r) => r.id),
1012
+ clean,
1013
+ report_ready: (rows.length === 0 && clean) || (rows.length > 0 && drafts.length === 0),
1014
+ };
1015
+ }
1016
+
1017
+ /**
1018
+ * retestRequest — move validated findings into the retest lane (ADR-020).
1019
+ * No id = ALL currently-validated findings. Returns the moved ids.
1020
+ */
1021
+ function retestRequest(dir, id) {
1022
+ const targets = id ? [id] : list(dir, { status: 'validated' }).map((f) => f.id);
1023
+ if (!targets.length) throw new Error('no validated findings to retest');
1024
+ return targets.map((fid) => setStatus(dir, fid, 'retest_pending'));
1025
+ }
1026
+
1027
+ /**
1028
+ * retestRecord — record an evidence-bound retest verdict (ADR-020).
1029
+ * pass = fix verified (replay no longer reproduces) -> retested_pass
1030
+ * fail = still reproducible -> retested_fail (can re-enter retest_pending)
1031
+ * A verdict without verified replay evidence is REFUSED — same bar as add.
1032
+ */
1033
+ function retestRecord(dir, id, { verdict, evidence: evIds = [], note = '', endpoint = '', steps = '' } = {}) {
1034
+ if (!['pass', 'fail'].includes(verdict)) throw new Error('verdict must be pass|fail');
1035
+ if (!evIds.length) {
1036
+ throw new Error('retest verdict requires replay evidence (--evidence E-id[,E-id]) — a verdict without proof is an assertion');
1037
+ }
1038
+ const evidenceLib = require('./evidence.cjs');
1039
+ for (const eid of evIds) {
1040
+ const v = evidenceLib.verify(dir, eid);
1041
+ if (!v.ok) throw new Error(`retest evidence invalid: ${eid} — ${v.reason}`);
1042
+ }
1043
+ const status = verdict === 'pass' ? 'retested_pass' : 'retested_fail';
1044
+ // 33-02 (REP-01 document layer): the closure block is persisted BEFORE the
1045
+ // status write so a standard-shape document re-renders section 9 with real
1046
+ // closure fields (retest date, observed result, supporting evidence).
1047
+ const target = resolveFinding(allFindings(dir), id);
1048
+ if (!target) throw new Error(`finding not found: ${id}`);
1049
+ const closure = {
1050
+ date: new Date().toISOString().slice(0, 10),
1051
+ verdict,
1052
+ evidence: evIds,
1053
+ };
1054
+ if (note) closure.note = note;
1055
+ // 36-01 (TD-02): the standard's section-9 closure fields — the endpoint the
1056
+ // replay actually hit and the validation steps actually performed. Free-text
1057
+ // strings, stored ONLY when supplied: a record closed without them keeps
1058
+ // rendering the honest '_not recorded_' markers (never fabricated).
1059
+ if (endpoint) closure.endpoint = String(endpoint).trim();
1060
+ if (steps) closure.steps = String(steps).trim();
1061
+ const abs = paths.resolve(dir, target.path);
1062
+ fs.writeFileSync(abs, fm.set(fs.readFileSync(abs, 'utf8'), 'retest', closure));
1063
+ setStatus(dir, id, status); // enforces retest_pending -> retested_* (dual-format resolver) + re-render
1064
+ const found = resolveFinding(allFindings(dir), id);
1065
+ if (!found) throw new Error(`finding not found: ${id}`);
1066
+ const text = fs.readFileSync(abs, 'utf8');
1067
+ const section = [
1068
+ '',
1069
+ `## Retest — ${new Date().toISOString().slice(0, 10)}`,
1070
+ '',
1071
+ `- Verdict: ${verdict === 'pass' ? 'FIX VERIFIED — the reproduction no longer succeeds' : 'STILL REPRODUCIBLE — the fix is ineffective'}`,
1072
+ // 34-02 (REP-04): the closure vocabulary on the retest output itself —
1073
+ // the lane states the standard's final status, not just the machine verdict
1074
+ `- Final status: ${closureStatus(status)}`,
1075
+ `- Evidence: ${evIds.join(', ')}`,
1076
+ ...(note ? [`- Note: ${note}`] : []),
1077
+ '',
1078
+ ].join('\n');
1079
+ fs.writeFileSync(abs, text.replace(/\s*$/, '\n') + section);
1080
+ return { id, status, evidence: evIds };
1081
+ }
1082
+
1083
+ module.exports = { add, update, setStatus, list, gate, attestClean, retestRequest, retestRecord,
1084
+ enforceValidationControls, TRANSITIONS,
1085
+ // Phase 34 (REP-02): the mandatory-sections gate at draft->validated
1086
+ enforceStandardSections, standardSectionGaps,
1087
+ // Phase 34 (REP-04, 34-02): the owner-gated terminal closure + the ONE
1088
+ // closure-vocabulary accessor every render surface goes through
1089
+ enforceRiskAcceptance, closureStatus,
1090
+ // Phase 35 (REP-03, 35-01): the shared section renderers/sources the report
1091
+ // layer REUSES (REPORT.md blocks + the PDF payload) — never forked
1092
+ closureLines, AFFECTED_LABELS, citationsForStep, evidenceEntry,
1093
+ // Phase 33 (REP-01): the dual-format resolver + severity-letter helpers
1094
+ resolveFinding, normalizeFindingId, SEVERITY_LETTER, SEVERITY_RANK, deriveOwaspRefs,
1095
+ // Phase 33 (REP-01, 33-02): the 9-section document renderer
1096
+ renderDocument };