@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,1135 @@
1
+ 'use strict';
2
+ /**
3
+ * report.cjs — deterministic report assembly (ADR-019, M3).
4
+ *
5
+ * The sdk assembles every DETERMINISTIC part of the deliverable — gate,
6
+ * severity ordering copied from the register, per-finding sections inlined
7
+ * from the finding files, appendix manifests — so "every severity traces to
8
+ * the sdk" is literally true: code copies numbers, agents never retype them.
9
+ * Prose sections (executive summary, compliance mapping) are emitted as
10
+ * TODO placeholders for the pensieve-reporter agent to write.
11
+ *
12
+ * Variants: client (full report/REPORT.md), exec (1-page report/EXEC.md),
13
+ * retest (verdict table report/RETEST.md).
14
+ */
15
+
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+ const fm = require('./frontmatter.cjs');
19
+ const findings = require('./findings.cjs');
20
+ const evidence = require('./evidence.cjs');
21
+ const pack = require('./pack.cjs');
22
+ const paths = require('./paths.cjs');
23
+ const graph = require('./graph.cjs');
24
+ const config = require('./config.cjs');
25
+ const clientlist = require('./clientlist.cjs');
26
+
27
+ const PACKS_ROOT = process.env.PENSIEVE_PACKS_DIR
28
+ || path.join(__dirname, '..', '..', '..', 'packs');
29
+
30
+ function readOr(file, fallback = '') {
31
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : fallback;
32
+ }
33
+
34
+ /** split a markdown body into { heading: content } on '## ' boundaries;
35
+ * duplicate headings (e.g. several 'Retest — <date>' lanes) get suffixed */
36
+ function sections(body) {
37
+ const out = {};
38
+ let cur = null;
39
+ for (const line of body.split('\n')) {
40
+ const m = line.match(/^##\s+(.+?)\s*$/);
41
+ if (m) {
42
+ cur = m[1];
43
+ let n = 2;
44
+ while (cur in out) cur = `${m[1]} #${n++}`;
45
+ out[cur] = '';
46
+ } else if (cur) out[cur] += line + '\n';
47
+ }
48
+ for (const k of Object.keys(out)) out[k] = out[k].trim();
49
+ return out;
50
+ }
51
+
52
+ function scopeSection(text, name) {
53
+ const m = text.match(new RegExp(`## ${name}\\n([\\s\\S]*?)(?=\\n## |$)`));
54
+ return m ? m[1].trim() : '';
55
+ }
56
+
57
+ function findingDetail(dir, f) {
58
+ const abs = paths.resolve(dir, f.path);
59
+ const { body } = fm.parse(readOr(abs));
60
+ return sections(body);
61
+ }
62
+
63
+ function gateAndChain(dir) {
64
+ const g = findings.gate(dir);
65
+ if (!g.report_ready) {
66
+ throw new Error(`report gate refuses: ${g.total === 0 ? 'no findings registered' : `unresolved drafts: ${g.draft.join(', ')}`}`);
67
+ }
68
+ const chain = evidence.verifyChain(dir);
69
+ if (!chain.ok) {
70
+ throw new Error(`evidence chain broken — report refused (ADR-016): ${chain.reason || `broken at seq ${chain.broken_at}`}`);
71
+ }
72
+ return g;
73
+ }
74
+
75
+ function sortedReportFindings(dir) {
76
+ // 35-01 (REP-05, the 34-02 follow-up): an owner-accepted finding closed the
77
+ // register row exactly like a verified fix does — it renders in the client
78
+ // findings table (and the PDF findings set) with its closure verdict, it is
79
+ // never silently dropped from what the client reads.
80
+ return findings.list(dir)
81
+ .filter((r) => r.status === 'validated' || r.status.startsWith('retested') || r.status === 'risk_accepted')
82
+ .sort((a, b) => b.cvss_score - a.cvss_score || String(a.id).localeCompare(String(b.id)));
83
+ }
84
+
85
+ // ---------------------------------------------------------------------------
86
+ // Phase 20 (EVID-01, plan 20-01): figure-bearing evidence records render as
87
+ // the client-standard reproduction interleave — 'Step N' prose block + a
88
+ // markdown image linked RELATIVE to the emitted report + 'What to look at:'
89
+ // caption line (quoting the caption; a generic deterministic caption when none
90
+ // was recorded at put time). Only records carrying a screenshot consume a step
91
+ // number; text-only records stay prose citations. A finding with no figure
92
+ // evidence contributes NOTHING here, so its rendered body stays byte-identical
93
+ // to the pre-20 renderer (pinned by tests/pensieve-sdk/report.test.cjs).
94
+ //
95
+ // Phase 35 (REP-03, plan 35-01): the interleave gained TWO extensions —
96
+ // - extraIds: figure-bearing ids cited by the structured PoC steps (inline
97
+ // [E-id] / poc_evidence) but never registered on --evidence render too,
98
+ // appended in citation order AFTER the register's own figures;
99
+ // - reportDir === null selects the PAYLOAD mode (the PDF finding payload):
100
+ // each figure renders as a one-line caption reference pointing at the
101
+ // appendix manifest instead of the markdown image link.
102
+ // ---------------------------------------------------------------------------
103
+ function figureSteps(r, recById, engagementDir, reportDir, extraIds = []) {
104
+ const steps = [];
105
+ let n = 0;
106
+ const ids = [...(r.evidence || [])];
107
+ for (const eid of extraIds || []) {
108
+ if (!ids.includes(eid)) ids.push(eid);
109
+ }
110
+ for (const eid of ids) {
111
+ const rec = recById.get(String(eid).trim());
112
+ if (!rec || !rec.screenshot) continue;
113
+ n += 1;
114
+ const caption = rec.caption || `terminal capture ${rec.id} (no caption recorded)`;
115
+ if (reportDir) {
116
+ const link = path.relative(reportDir, paths.resolve(engagementDir, rec.screenshot))
117
+ .split(path.sep).join('/');
118
+ steps.push(
119
+ `**Step ${n}.** ${caption}`,
120
+ '',
121
+ `![Step ${n} — ${rec.id}](${link})`,
122
+ '',
123
+ `**What to look at:** ${caption}`,
124
+ ''
125
+ );
126
+ } else {
127
+ steps.push(`- Figure ${n} — ${rec.id}: ${caption} (see Appendix — Evidence manifest)`);
128
+ }
129
+ }
130
+ return steps;
131
+ }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Phase 35 (REP-03, plan 35-01): the 9-section finding block. What the client
135
+ // READS follows reference/vulnerability-finding-standard.md — REPORT.md
136
+ // finding blocks render the standard's nine sections in order:
137
+ // 1. Finding Title the '### <id> <title> — <band> (CVSS <score>)' heading
138
+ // 2. Severity & Risk the badge line: band — score — vector
139
+ // 3. Affected Assets the label/value table (the standard's 7 fields)
140
+ // 4. Description the root cause
141
+ // 5. PoC ordered steps with the evidence COMBINED inline
142
+ // (the 20-01 step/figure interleave, extended)
143
+ // 6. Impact demonstrated first, then potential; technical/business
144
+ // 7. Remediation ordered
145
+ // 8. References CWE + derived/overridden OWASP mappings
146
+ // 9. Retest / Validation the closure vocabulary (closureLines)
147
+ // Report-level sections (exec summary, scope, methodology, limitations) stay
148
+ // REPORT-level — never inside a finding block.
149
+ //
150
+ // SOURCING is structured-fields-FIRST (the 33-01 record fields) with the
151
+ // legacy det['Summary'/'Attack Narrative'/'Evidence'/'Remediation'] prose as
152
+ // the fallback for legacy records — the 33-02 follow-up: a complete record
153
+ // never renders '_pending_' placeholder prose, a legacy record never has
154
+ // content fabricated for it, and a section nothing sources renders the
155
+ // explicit '_not recorded_' marker.
156
+ //
157
+ // ONE sourcing, two render surfaces: `lines` is the REPORT.md block and
158
+ // `sections` is the ordered 9-section payload pdf.cjs feeds formal_report.py
159
+ // (the PDF carries the same section shape; key order is pinned by
160
+ // tests/pensieve-sdk/report-standard.test.cjs).
161
+ // ---------------------------------------------------------------------------
162
+
163
+ /** the report layer's explicit marker (the document layer's convention) */
164
+ const NOT_RECORDED = '_not recorded_';
165
+
166
+ function listOf(v) {
167
+ return (Array.isArray(v) ? v : (v == null ? [] : [v])).map((s) => String(s).trim()).filter(Boolean);
168
+ }
169
+
170
+ /** legacy section prose, or null when the legacy body has nothing real there */
171
+ function legacyProse(det, key) {
172
+ const t = det && det[key] ? String(det[key]).trim() : '';
173
+ return t && t !== '_pending_' ? t : null;
174
+ }
175
+
176
+ /** the standard's section keys/labels, in the pinned order */
177
+ const STANDARD_SECTIONS = [
178
+ ['title', 'Finding Title'],
179
+ ['severity', 'Severity & Risk Rating'],
180
+ ['assets', 'Affected Assets'],
181
+ ['description', 'Description'],
182
+ ['poc', 'Technical Details / Proof of Concept'],
183
+ ['impact', 'Impact'],
184
+ ['remediation', 'Remediation'],
185
+ ['references', 'References'],
186
+ ['retest', 'Retest / Validation'],
187
+ ];
188
+
189
+ /**
190
+ * findingBlock(dir, r, { reportDir, det, recById }) — the 9-section standard
191
+ * block for one register row. `reportDir` selects the surface: a real report
192
+ * directory renders the REPORT.md markdown (figure links relative to it);
193
+ * null renders the PDF payload (figure captions as appendix references).
194
+ * Deterministic: a pure function of the record + the evidence ledger.
195
+ */
196
+ function findingBlock(dir, r, { reportDir = null, det = null, recById = null } = {}) {
197
+ det = det || findingDetail(dir, r);
198
+ recById = recById || new Map(evidence.readIndex(dir).map((e) => [e.id, e]));
199
+
200
+ const band = sevLabel(r);
201
+ const summary = typeof r.summary === 'string' ? r.summary.trim() : '';
202
+
203
+ // ---- shared section sources: structured FIRST, legacy fallback ----------
204
+ const assetRows = [];
205
+ const shown = new Set();
206
+ const affected = r.affected && typeof r.affected === 'object' ? r.affected : {};
207
+ for (const [key, label] of findings.AFFECTED_LABELS) {
208
+ if (affected[key]) {
209
+ assetRows.push([label, String(affected[key])]);
210
+ shown.add(String(affected[key]));
211
+ }
212
+ }
213
+ for (const tag of listOf(r.assets)) {
214
+ if (!shown.has(tag)) assetRows.push(['Registered asset', tag]);
215
+ }
216
+
217
+ const description = String(r.description || '').trim() || legacyProse(det, 'Summary') || NOT_RECORDED;
218
+
219
+ // ---- the PoC section: ordered steps, each IMMEDIATELY followed by the
220
+ // evidence it cites; figure-bearing artifacts render through the (extended)
221
+ // 20-01 interleave so a figure is NEVER rendered twice ------------------
222
+ const pocSteps = listOf(r.poc);
223
+ const pocEvidence = r.poc_evidence && typeof r.poc_evidence === 'object' ? r.poc_evidence : {};
224
+ const stepLines = [];
225
+ const figureIds = []; // figure-bearing cited ids, in citation order
226
+ const cited = new Set();
227
+ let evN = 0;
228
+ for (let i = 0; i < pocSteps.length; i += 1) {
229
+ stepLines.push(`${i + 1}. ${pocSteps[i]}`);
230
+ const ids = findings.citationsForStep(pocSteps[i], listOf(pocEvidence[String(i + 1)]));
231
+ const entries = [];
232
+ for (const eid of ids) {
233
+ cited.add(eid);
234
+ const e = findings.evidenceEntry(dir, eid);
235
+ if (e.figure) {
236
+ if (!figureIds.includes(eid)) figureIds.push(eid);
237
+ } else {
238
+ entries.push(e);
239
+ }
240
+ }
241
+ if (entries.length) {
242
+ stepLines.push('');
243
+ for (const e of entries) {
244
+ evN += 1;
245
+ stepLines.push(` - Evidence ${evN} — ${e.id}: ${e.caption}`);
246
+ }
247
+ }
248
+ }
249
+ if (!pocSteps.length) {
250
+ // legacy record: the narrative + evidence prose land INSIDE the PoC section
251
+ const legacyNarrative = legacyProse(det, 'Attack Narrative');
252
+ const legacyEvidence = legacyProse(det, 'Evidence');
253
+ if (legacyNarrative) stepLines.push(legacyNarrative, '');
254
+ if (legacyEvidence) stepLines.push(`**Evidence.** ${legacyEvidence}`, '');
255
+ }
256
+ // register evidence no step cites stays INSIDE the PoC section (the standard
257
+ // forbids a standalone evidence section); figures among it render through
258
+ // the interleave, text-only records render as numbered entries
259
+ const additionalEntries = [];
260
+ for (const eid of listOf(r.evidence)) {
261
+ if (cited.has(eid)) continue;
262
+ const rec = recById.get(String(eid).trim());
263
+ if (rec && rec.screenshot) continue;
264
+ const e = findings.evidenceEntry(dir, eid);
265
+ evN += 1;
266
+ additionalEntries.push(`- Evidence ${evN} — ${e.id}: ${e.caption}`);
267
+ }
268
+ const additionalLines = additionalEntries.length
269
+ ? ['', 'Additional register evidence (not cited by a PoC step):', '', ...additionalEntries]
270
+ : [];
271
+ const anyFigure = [...listOf(r.evidence), ...figureIds].some((eid) => {
272
+ const rec = recById.get(String(eid).trim());
273
+ return rec && rec.screenshot;
274
+ });
275
+ const pocSectionLines = (rd) => [
276
+ ...stepLines,
277
+ ...(stepLines.length || anyFigure ? [] : [NOT_RECORDED]),
278
+ ...figureSteps(r, recById, dir, rd, figureIds),
279
+ ...additionalLines,
280
+ ];
281
+
282
+ // ---- impact: demonstrated FIRST, then potential; technical + business ----
283
+ const impact = r.impact && typeof r.impact === 'object' ? r.impact : {};
284
+ const impactLines = [];
285
+ for (const [header, items] of [
286
+ ['Demonstrated impact (proved during this assessment):', listOf(impact.demonstrated)],
287
+ ['Potential impact (substantiated, not demonstrated):', listOf(impact.potential)],
288
+ ['Technical impact:', listOf(impact.technical)],
289
+ ['Business impact:', listOf(impact.business)],
290
+ ]) {
291
+ impactLines.push(header, '', ...(items.length ? items.map((it) => `- ${it}`) : [`- ${NOT_RECORDED}`]), '');
292
+ }
293
+
294
+ // ---- remediation: ordered; references; section 9 (closure vocabulary) ----
295
+ const remediation = listOf(r.remediation);
296
+ const remediationLines = remediation.length
297
+ ? remediation.map((x, i) => `${i + 1}. ${x}`)
298
+ : [legacyProse(det, 'Remediation') || NOT_RECORDED];
299
+ const refLines = [`- CWE: ${r.cwe || NOT_RECORDED}`];
300
+ if (Array.isArray(r.references_owasp)) {
301
+ if (!r.references_owasp.length) {
302
+ refLines.push('- OWASP: none derived (unmapped CWE — nothing forced)');
303
+ } else {
304
+ for (const ref of r.references_owasp) refLines.push(`- OWASP: ${ref}`);
305
+ }
306
+ }
307
+ const closure = findings.closureLines(r);
308
+ const business = listOf(impact.business);
309
+
310
+ // ---- the ordered 9-section payload (pdf.cjs -> formal_report.py) --------
311
+ const sections = STANDARD_SECTIONS.map(([key, label]) => {
312
+ const text = {
313
+ title: `${r.id} ${r.title} — ${band} (CVSS ${r.cvss_score})`,
314
+ severity: [
315
+ `- Severity band: ${band}`,
316
+ `- CVSS base score: ${r.cvss_score} (SDK-computed)`,
317
+ `- CVSS vector: ${r.cvss_vector}`,
318
+ `- Business context: ${business.length ? business.join('; ') : NOT_RECORDED}`,
319
+ ].join('\n'),
320
+ assets: (assetRows.length ? assetRows : [[NOT_RECORDED, null]])
321
+ .map(([k, v]) => (v == null ? `- ${NOT_RECORDED}` : `- ${k}: ${v}`)).join('\n'),
322
+ description,
323
+ poc: pocSectionLines(null).join('\n'),
324
+ impact: impactLines.join('\n'),
325
+ remediation: remediationLines.join('\n'),
326
+ references: refLines.join('\n'),
327
+ retest: closure.join('\n'),
328
+ }[key];
329
+ return { key, label, text };
330
+ });
331
+
332
+ // ---- the REPORT.md block ------------------------------------------------
333
+ const lines = [];
334
+ lines.push(`### ${r.id} ${r.title} — ${band} (CVSS ${r.cvss_score})`, '');
335
+ if (summary) lines.push(`_${summary}_`, '');
336
+ lines.push(`**Severity & Risk Rating:** ${band} — CVSS ${r.cvss_score} — \`${r.cvss_vector}\``, '');
337
+ if (assetRows.length) {
338
+ lines.push(
339
+ '**Affected assets:**', '',
340
+ '| Field | Value |',
341
+ '|-------|-------|',
342
+ ...assetRows.map(([k, v]) => `| ${escCell(k)} | ${escCell(v)} |`),
343
+ ''
344
+ );
345
+ } else {
346
+ lines.push(`**Affected assets:** ${NOT_RECORDED}`, '');
347
+ }
348
+ lines.push(`**Description.** ${description}`, '');
349
+ lines.push('**Technical Details / Proof of Concept.**', '', ...pocSectionLines(reportDir), '');
350
+ lines.push('**Impact.**', '', ...impactLines);
351
+ lines.push('**Remediation.**', '', ...remediationLines, '');
352
+ lines.push('**References.**', '', ...refLines, '');
353
+ lines.push('**Retest / Validation.**', '', ...closure, '');
354
+ return { lines, sections };
355
+ }
356
+
357
+ // ---------------------------------------------------------------------------
358
+ // Phase 20 (EVID-01, plan 20-02): --deliverable-dir assembly. The deliverable
359
+ // folder is the CLIENT handoff package, assembled by COPY from the engagement
360
+ // (the repo stays the source of truth — nothing is moved or deleted):
361
+ // <dir>/README.md auto-README (engagement id, date, status, clientlist
362
+ // progress digest, findings counts, figures manifest)
363
+ // <dir>/workbook/ clientlist.export output — ONLY when a clientlist
364
+ // snapshot exists
365
+ // <dir>/sheets/ per-sheet markdown status tables (same condition)
366
+ // <dir>/figures/ every evidence screenshot, named <evidence-id>.<ext>
367
+ // A missing figure file fails the WHOLE assembly (a broken ledger must not
368
+ // ship a half-empty package); a clientlist export refusal (drift / missing
369
+ // bridge) propagates the same way.
370
+ // ---------------------------------------------------------------------------
371
+
372
+ // client-facing text for a checklist row's verdict state — the rendering twin
373
+ // of clientlist.cjs verdictCellText (kept local: coverage is never fabricated)
374
+ function checklistVerdictText(row) {
375
+ if (row.verdict && row.verdict.tier === 'no_done') return `No (done: ${row.verdict.done})`;
376
+ if (row.verdict && row.verdict.tier === 'no_na') return `No (N/A: ${row.verdict.reason})`;
377
+ if (row.verdict && row.verdict.tier === 'yes') return `Yes (finding: ${row.verdict.finding_id})`;
378
+ if (!row.verdict && row.blocker_note) return `Blocked: ${row.blocker_note}`;
379
+ return '_not answered_';
380
+ }
381
+
382
+ function sheetStatusMarkdown(snap, sheet, rows) {
383
+ const lines = [
384
+ `# ${snap.slug} — sheet "${sheet.name}" (${rows.length} rows)`,
385
+ '',
386
+ '| ID | Row | Scenario | Verdict | Evidence | Notes |',
387
+ '|----|-----|----------|---------|----------|-------|',
388
+ ];
389
+ const esc = (s) => String(s == null ? '' : s).replace(/\|/g, '\\|').replace(/\n/g, ' ');
390
+ for (const r of rows) {
391
+ lines.push(
392
+ `| ${r.id} | ${esc(r.row_number || '')} | ${esc(r.scenario_text)} | ${esc(checklistVerdictText(r))} `
393
+ + `| ${esc((r.evidence || []).join(', '))} | ${esc(r.notes)} |`
394
+ );
395
+ }
396
+ lines.push('');
397
+ return lines;
398
+ }
399
+
400
+ function assembleDeliverable(dir, outDir, { rows, rejected }) {
401
+ fs.mkdirSync(path.join(outDir, 'figures'), { recursive: true });
402
+
403
+ // figures/ — every screenshot in the ledger, collected as <evidence-id>.<ext>
404
+ // (citation linkage is resolved from the findings REGISTER — findings cite
405
+ // evidence, not the other way round)
406
+ const citingByEvidence = new Map();
407
+ for (const f of findings.list(dir)) {
408
+ for (const eid of f.evidence || []) {
409
+ const k = String(eid).trim();
410
+ citingByEvidence.set(k, [...(citingByEvidence.get(k) || []), f.id]);
411
+ }
412
+ }
413
+ const figures = [];
414
+ const manifest = [];
415
+ for (const rec of evidence.readIndex(dir)) {
416
+ if (!rec.screenshot) continue;
417
+ const src = paths.resolve(dir, rec.screenshot);
418
+ if (!fs.existsSync(src)) {
419
+ throw new Error(`deliverable refused: figure for evidence ${rec.id} is missing at ${rec.screenshot} (broken ledger — investigate, don't ship)`);
420
+ }
421
+ const fname = `${rec.id}${path.extname(rec.screenshot) || '.png'}`;
422
+ fs.copyFileSync(src, path.join(outDir, 'figures', fname));
423
+ figures.push(fname);
424
+ const caption = rec.caption || `terminal capture ${rec.id} (no caption recorded)`;
425
+ const cited = [...new Set(citingByEvidence.get(rec.id) || [])];
426
+ manifest.push(`- ${fname} — ${caption}${cited.length ? ` (cited by ${cited.join(', ')})` : ''}`);
427
+ }
428
+
429
+ // workbook/ + sheets/ — only when a clientlist snapshot exists
430
+ const clDir = path.join(dir, 'clientlist');
431
+ const slugs = fs.existsSync(clDir)
432
+ ? fs.readdirSync(clDir).filter((f) => f.endsWith('.json')).sort().map((f) => f.replace(/\.json$/, ''))
433
+ : [];
434
+ const workbook = [];
435
+ const sheets = [];
436
+ const slugify = clientlist._internals.slugify;
437
+ for (const slug of slugs) {
438
+ const snap = clientlist.list(dir, { slug });
439
+
440
+ // updated workbook export — written DIRECTLY into the deliverable (the
441
+ // engagement's pristine copy and snapshot are never touched)
442
+ const stem = snap.source.file.replace(/\.[^.]+$/, '');
443
+ const ext = snap.source.format === 'xlsx' ? '.xlsx' : '.csv';
444
+ const outPath = path.join(outDir, 'workbook', `${stem}-updated${ext}`);
445
+ const exp = clientlist.exportWorkbook(dir, { slug, out: outPath });
446
+ if (exp.ok === false) {
447
+ throw new Error(`deliverable refused: clientlist export for "${slug}" failed: ${exp.error}`);
448
+ }
449
+ workbook.push(path.relative(outDir, exp.out));
450
+
451
+ // per-sheet status tables
452
+ for (const sheet of snap.sheets) {
453
+ const rows = snap.rows.filter((r) => r.sheet === sheet.name);
454
+ const file = path.join(outDir, 'sheets', `${slug}--${slugify(sheet.name)}.md`);
455
+ fs.mkdirSync(path.dirname(file), { recursive: true });
456
+ fs.writeFileSync(file, sheetStatusMarkdown(snap, sheet, rows).join('\n'));
457
+ sheets.push(path.relative(outDir, file));
458
+ }
459
+ }
460
+
461
+ // README.md — the auto summary + manifest (design decision 3)
462
+ const id = path.basename(dir);
463
+ const state = fm.parse(readOr(path.join(dir, 'STATE.md')));
464
+ const digest = clientlist.progressDigest(dir);
465
+ const readme = [
466
+ `# Deliverables — ${id}`,
467
+ '',
468
+ `- Engagement: ${id}`,
469
+ `- Assembled: ${new Date().toISOString()}`,
470
+ `- Status: ${state.data && state.data.status ? state.data.status : '_unknown_'}`,
471
+ `- Findings: ${rows.length} reportable (validated/retested/risk-accepted), ${rejected.length} rejected`,
472
+ `- Clientlist: ${digest || '_none imported_'}`,
473
+ '',
474
+ '## Contents',
475
+ '',
476
+ ...(slugs.length
477
+ ? [
478
+ '- `workbook/` — updated client checklist export (one per imported snapshot)',
479
+ '- `sheets/` — per-sheet checklist status tables (coverage is never fabricated; untouched rows say so)',
480
+ ]
481
+ : ['- _no clientlist imported — no workbook/ or sheets/ in this package_']),
482
+ '- `figures/` — evidence screenshots, named `<evidence-id>.<ext>` (the engagement repo remains the source of truth; this folder is a copy)',
483
+ '',
484
+ '## Figures manifest',
485
+ '',
486
+ ...(manifest.length ? manifest : ['_no figures recorded_']),
487
+ '',
488
+ ].join('\n');
489
+ const readmePath = path.join(outDir, 'README.md');
490
+ fs.writeFileSync(readmePath, readme);
491
+
492
+ return { dir: outDir, readme: readmePath, workbook, sheets, figures };
493
+ }
494
+
495
+
496
+ function appendixManifests(dir) {
497
+ const ev = evidence.readIndex(dir);
498
+ const runsDir = paths.runsDir(dir);
499
+ const runs = fs.existsSync(runsDir) ? fs.readdirSync(runsDir).filter((f) => f.endsWith('.md')).sort() : [];
500
+ let toolLines = [];
501
+ for (const slug of pack.enabled(dir)) {
502
+ try {
503
+ const manifest = pack.load(PACKS_ROOT, slug);
504
+ for (const t of manifest.tools || []) toolLines.push(`${t} (${slug})`);
505
+ } catch { toolLines.push(`n/a (${slug} — manifest unreadable)`); }
506
+ }
507
+ if (!toolLines.length) toolLines = ['_none declared_'];
508
+ return { evidence: ev, runs, toolLines };
509
+ }
510
+
511
+ function severityCounts(rows) {
512
+ const order = ['Critical', 'High', 'Medium', 'Low', 'Informational'];
513
+ const counts = {};
514
+ for (const r of rows) {
515
+ const sev = sevLabel(r);
516
+ counts[sev] = (counts[sev] || 0) + 1;
517
+ }
518
+ return order.filter((s) => counts[s]).map((s) => `| ${s} | ${counts[s]} |`);
519
+ }
520
+
521
+ // CVSS 0.0 scores as severity 'None' (cvss.cjs); display as Informational.
522
+ function sevLabel(r) {
523
+ return r.severity === 'None' ? 'Informational' : r.severity;
524
+ }
525
+
526
+ // ---------------------------------------------------------------------------
527
+ // ADR-025 — objective-driven attack graph. The client report's "Attack Path"
528
+ // and "Defensive Implications" sections are ASSEMBLED BY CODE from the graph
529
+ // (surface/graph.json, or a fresh compute) — the SDK copies nodes, hops,
530
+ // findings and severities; no number is retyped. The sections are emitted only
531
+ // when an objective is declared; if the graph is unavailable the report still
532
+ // assembles (the graph commands report their own errors).
533
+ // ---------------------------------------------------------------------------
534
+
535
+ function escCell(s) {
536
+ return String(s == null ? '' : s).replace(/\|/g, '\\|');
537
+ }
538
+
539
+ function attackPathBody(pathRes, g, rows) {
540
+ const nodeById = new Map();
541
+ if (g.nodes) for (const n of g.nodes) nodeById.set(n.id, n);
542
+ const sevById = new Map(rows.map((r) => [r.id, sevLabel(r)]));
543
+ const objective = g.objective || (pathRes && pathRes.objective) || '';
544
+ const lines = [];
545
+ lines.push(`**Objective:** ${escCell(objective)}`);
546
+ if (g.crownArtifact) {
547
+ lines.push(`**Crown artifact:** ${escCell(g.crownArtifact)}`);
548
+ }
549
+ lines.push('');
550
+ const hops = pathRes && pathRes.ok && Array.isArray(pathRes.hops) ? pathRes.hops : [];
551
+ if (hops.length) {
552
+ lines.push('| Hop | From | To | Finding | Evidence | Severity |');
553
+ lines.push('|-----|------|----|---------|----------|----------|');
554
+ hops.forEach((e, i) => {
555
+ const fnode = (nodeById.get(e.to) && nodeById.get(e.to).type === 'finding')
556
+ ? e.to
557
+ : (nodeById.get(e.from) && nodeById.get(e.from).type === 'finding')
558
+ ? e.from
559
+ : null;
560
+ const evidence = Array.isArray(e.evidence) && e.evidence.length
561
+ ? e.evidence.join(', ')
562
+ : '_n/a_';
563
+ const severity = fnode && sevById.has(fnode) ? escCell(sevById.get(fnode)) : '_n/a_';
564
+ lines.push(
565
+ `| ${i + 1} | ${escCell(e.from)} | ${escCell(e.to)} | ${escCell(fnode || '_n/a_')} | ${escCell(evidence)} | ${severity} |`
566
+ );
567
+ });
568
+ lines.push('');
569
+ const total = hops.length;
570
+ lines.push(
571
+ `**Route weight:** ${escCell(String(pathRes.totalWeight || total))} — ` +
572
+ `${total} hop${total === 1 ? '' : 's'} from foothhold to objective.`
573
+ );
574
+ lines.push('');
575
+ } else {
576
+ lines.push(
577
+ '_No confirmed path to the objective yet: no validated finding currently links a ' +
578
+ 'scoped foothold to it. The graph is in place (surface/graph.json); the cheapest ' +
579
+ 'route is assembled here and asserted by the shortest-path solver as soon as such ' +
580
+ 'a finding is validated. No hop is claimed in this section._'
581
+ );
582
+ lines.push('');
583
+ }
584
+ return lines;
585
+ }
586
+
587
+ function defensiveImplicationsBody(sim, g) {
588
+ const nodes = g && g.nodes ? g.nodes : [];
589
+ const labelOf = (id) => {
590
+ const n = nodes.find((x) => x.id === id);
591
+ return n ? (n.label || n.id) : String(id);
592
+ };
593
+ const lines = [];
594
+ const chokepoints = sim && sim.ok ? (Array.isArray(sim.chokepoints) ? sim.chokepoints : []) : [];
595
+ if (chokepoints.length === 0) {
596
+ lines.push(
597
+ '_No chokepoint identified: removing no single node breaks every route to the ' +
598
+ 'objective (no confirmed route yet, or multiple independent routes exist)._'
599
+ );
600
+ lines.push('');
601
+ } else {
602
+ lines.push('| Chokepoint | Defensive implication |');
603
+ lines.push('|------------|-----------------------|');
604
+ chokepoints.forEach((c) => {
605
+ lines.push(
606
+ `| ${escCell(c)} | removing this control makes the objective unreachable — the highest-leverage ` +
607
+ 'remediation target; after the fix, re-run the simulate command and confirm ' +
608
+ 'the objective is no longer reachable |'
609
+ );
610
+ });
611
+ lines.push('');
612
+ }
613
+ lines.push(
614
+ '_Chokepoints come from the simulate command (graph.simulate): nodes whose removal ' +
615
+ 'makes the objective unreachable. Fixing a chokepoint kills every confirmed route ' +
616
+ 'to the objective — it is both the top remediation and the retest anchor._'
617
+ );
618
+ lines.push('');
619
+ return lines;
620
+ }
621
+
622
+ // ---------------------------------------------------------------------------
623
+ // Phase 22 (RETEST-01, plan 22-01): retest verdict flips. Grounding semantics
624
+ // (findings.cjs TRANSITIONS): validated -> retest_pending -> retested_pass |
625
+ // retested_fail, where retested_pass = the fix HELD (FIXED) and retested_fail
626
+ // = still vulnerable (RETAINED) — both gate-passing statuses. Upgrades flip
627
+ // verdicts BOTH ways, so the section lists BOTH directions with counts and
628
+ // never implies fixes are the only outcome. Rendered ONLY when a retested_*
629
+ // finding exists; without one the report stays byte-identical (pinned in
630
+ // report.test.cjs). A WORSE post-upgrade finding is a NEW registration — the
631
+ // register is append-only history — and the section states that rule in one
632
+ // line.
633
+ // ---------------------------------------------------------------------------
634
+ function flipSummaryBody(fixed, retained) {
635
+ const listLines = (fs2) => fs2.length
636
+ ? fs2.map((r) => `- ${r.id} ${escCell(r.title)} — ${sevLabel(r)} (CVSS ${r.cvss_score})`)
637
+ : ['_none_'];
638
+ return [
639
+ '',
640
+ 'Upgrades flip verdicts in BOTH directions — this section lists each side',
641
+ 'explicitly: fixes that held AND findings that stayed vulnerable.',
642
+ '',
643
+ `**Fixed — fix held (retested_pass): ${fixed.length} finding${fixed.length === 1 ? '' : 's'}.** `,
644
+ 'The reproduction no longer succeeds after the upgrade.',
645
+ ...listLines(fixed),
646
+ '',
647
+ `**Retained — still vulnerable (retested_fail): ${retained.length} finding${retained.length === 1 ? '' : 's'}.** `,
648
+ 'The fix is ineffective; the finding stands after the upgrade.',
649
+ ...listLines(retained),
650
+ '',
651
+ 'A finding that got WORSE after the upgrade is never overwritten: it is registered as a NEW finding.',
652
+ ];
653
+ }
654
+
655
+ // ---------------------------------------------------------------------------
656
+ // Phase 34 (REP-04, plan 34-02): closure entries in RETEST.md. The standard
657
+ // (reference/vulnerability-finding-standard.md section 9) documents closure
658
+ // per finding: retest date, tested endpoint, validation steps, observed
659
+ // result, final status, supporting evidence — sourced from the STORED
660
+ // records (the existing retest record plus the new risk_accepted record),
661
+ // never fabricated: a field the record does not carry renders the explicit
662
+ // _not recorded_ marker (the document layer's convention). The final status
663
+ // is the closure vocabulary (findings.cjs closureStatus — validated 'Open',
664
+ // retest_pending 'Open (retest requested)', retested_pass 'Fixed',
665
+ // retested_fail 'Not Fixed', risk_accepted 'Risk Accepted', rejected 'Not
666
+ // Fixed (rejected at validation)').
667
+ // ---------------------------------------------------------------------------
668
+ const CLOSURE_NOT_RECORDED = '_not recorded_';
669
+
670
+ function closureEntryLines(r) {
671
+ const retest = r.retest && typeof r.retest === 'object' ? r.retest : {};
672
+ const risk = r.risk_acceptance && typeof r.risk_acceptance === 'object' ? r.risk_acceptance : null;
673
+ const observed = retest.verdict === 'pass'
674
+ ? 'FIX VERIFIED — the reproduction no longer succeeds'
675
+ : retest.verdict === 'fail'
676
+ ? 'STILL REPRODUCIBLE — the fix is ineffective'
677
+ : CLOSURE_NOT_RECORDED;
678
+ const evIds = Array.isArray(retest.evidence) ? retest.evidence : [];
679
+ const lines = [
680
+ `- Retest date: ${retest.date || CLOSURE_NOT_RECORDED}`,
681
+ `- Tested endpoint: ${retest.endpoint || CLOSURE_NOT_RECORDED}`,
682
+ `- Validation steps: ${retest.steps || CLOSURE_NOT_RECORDED}`,
683
+ `- Observed result: ${observed}`,
684
+ `- Final status: ${findings.closureStatus(r.status)}`,
685
+ `- Supporting evidence: ${evIds.join(', ') || CLOSURE_NOT_RECORDED}`,
686
+ ];
687
+ if (retest.note) lines.push(`- Note: ${retest.note}`);
688
+ if (risk) lines.push(`- Risk accepted by: ${risk.by} (${risk.date}) — ${risk.note}`);
689
+ return lines;
690
+ }
691
+
692
+ function compile(dir, { variant = 'client', deliverableDir = null } = {}) {
693
+ gateAndChain(dir);
694
+ const id = path.basename(dir);
695
+ const rows = sortedReportFindings(dir);
696
+ const rejected = findings.list(dir, { status: 'rejected' });
697
+ const project = readOr(paths.projectFile(dir));
698
+ const scopeText = readOr(paths.scopeFile(dir));
699
+ const accounts = readOr(paths.accountsFile(dir)).trim();
700
+ const { cfg } = config.load(dir);
701
+ const { evidence: evManifest, runs, toolLines } = appendixManifests(dir);
702
+ const reportDir = paths.reportDir(dir);
703
+ fs.mkdirSync(reportDir, { recursive: true });
704
+
705
+ // 20-02: assemble the client deliverable folder (COPY semantics — the
706
+ // engagement stays the source of truth) when --deliverable-dir is given,
707
+ // and attach its inventory to every variant's result envelope.
708
+ const finish = (res) => (deliverableDir
709
+ ? { ...res, deliverable: assembleDeliverable(dir, path.resolve(deliverableDir), { rows, rejected }) }
710
+ : res);
711
+
712
+ // 35-01 (REP-05): the status cell of an owner-accepted row carries the
713
+ // standard's closure verdict — the same wording the retest document's
714
+ // verdict table uses (one vocabulary everywhere a status shows)
715
+ const statusCell = (r) => (r.status === 'risk_accepted' ? 'RISK ACCEPTED' : r.status);
716
+ const findingsTable = [
717
+ '| ID | Title | CWE | CVSS | Severity | Status |',
718
+ '|----|-------|-----|------|----------|--------|',
719
+ ...rows.map((r) => `| ${r.id} | ${String(r.title).replace(/\|/g, '\\|')} | ${r.cwe} | ${r.cvss_score} | ${sevLabel(r)} | ${statusCell(r)} |`),
720
+ ];
721
+
722
+ if (variant === 'exec') {
723
+ const out = path.join(reportDir, 'EXEC.md');
724
+ fs.writeFileSync(out, [
725
+ `# Executive Summary — ${id}`,
726
+ '',
727
+ `_TODO: reporter writes the leadership narrative (risk posture, the 3–5`,
728
+ `findings that matter most, the single most important remediation)._`,
729
+ '',
730
+ '## Findings by severity',
731
+ '',
732
+ '| Severity | Count |',
733
+ '|----------|-------|',
734
+ ...severityCounts(rows),
735
+ '',
736
+ '## Findings register',
737
+ '',
738
+ ...findingsTable,
739
+ '',
740
+ ].join('\n'));
741
+ return finish({ written: out, variant, findings: rows.length });
742
+ }
743
+
744
+ if (variant === 'retest') {
745
+ const out = path.join(reportDir, 'RETEST.md');
746
+ // 34-02 (REP-04): the retest document is the CLOSURE document — the
747
+ // owner-accepted register joins the retested one (an acceptance closes a
748
+ // finding exactly like a verified fix does), same severity-desc order.
749
+ // 35-01 (REP-05): sortedReportFindings now INCLUDES risk_accepted, so the
750
+ // closure rows ARE the report rows — no separate append, no duplicates.
751
+ const closureRows = rows;
752
+ const verdictCell = (r) => (r.status === 'risk_accepted'
753
+ ? 'RISK ACCEPTED'
754
+ : r.status.replace('retested_', '').toUpperCase());
755
+ const lines = [
756
+ `# Retest Verdicts — ${id}`,
757
+ '',
758
+ '| ID | Title | Severity | Verdict |',
759
+ '|----|-------|----------|---------|',
760
+ ...closureRows.map((r) => `| ${r.id} | ${String(r.title).replace(/\|/g, '\\|')} | ${sevLabel(r)} | ${verdictCell(r)} |`),
761
+ '',
762
+ ];
763
+ for (const r of closureRows) {
764
+ const det = findingDetail(dir, r);
765
+ const retestSections = Object.keys(det).filter((k) => k.startsWith('Retest'));
766
+ for (const k of retestSections) lines.push(`### ${r.id} — ${k}`, '', det[k], '');
767
+ }
768
+ // 34-02 (REP-04): the standard's closure entry per CLOSED finding —
769
+ // retested_* or risk_accepted; a validated row has no closure record yet.
770
+ for (const r of closureRows) {
771
+ if (!(r.status.startsWith('retested') || r.status === 'risk_accepted')) continue;
772
+ lines.push(`### ${r.id} — Closure`, '', ...closureEntryLines(r), '');
773
+ }
774
+ fs.writeFileSync(out, lines.join('\n'));
775
+ return finish({ written: out, variant, findings: closureRows.length });
776
+ }
777
+
778
+ // client (default): full REPORT.md
779
+ const draftPath = path.join(dir, 'report', 'REPORT.md');
780
+
781
+ // ADR-025: the Attack Path + Defensive Implications sections are ASSEMBLED
782
+ // BY CODE from the graph (surface/graph.json, or a fresh compute) when an
783
+ // objective is declared; they sit between Findings and Compliance Mapping.
784
+ // If the graph is unavailable, the sections are omitted and the rest of the
785
+ // report still assembles (the graph commands report their own errors).
786
+ let g = null, pathRes = null, sim = null;
787
+ try {
788
+ // The graph is first built at `mapped`, before any finding exists. By the
789
+ // time we compile (reporting / retest), the register is settled — rebuild
790
+ // so the Attack Path reflects the real findings (and retest verdicts), not
791
+ // the finding-less mapped-time graph. If no objective is set, build is a
792
+ // graceful no-op and we fall back to whatever is stored.
793
+ try { graph.build(dir); } catch (e) { /* keep the stored graph.json */ }
794
+ g = graph.readGraph(dir);
795
+ pathRes = g ? graph.shortest(dir, g.objective || undefined) : null;
796
+ sim = g ? graph.simulate(dir) : null;
797
+ } catch (e) {
798
+ g = pathRes = sim = null;
799
+ }
800
+ const hasObjective = !!(g && g.objective);
801
+
802
+ const findingBodies = [];
803
+ // EVID-01: ledger records by id — figure lookup for the step interleave
804
+ const recById = new Map(evManifest.map((e) => [e.id, e]));
805
+ for (const r of rows) {
806
+ const det = findingDetail(dir, r);
807
+ // 35-01 (REP-03): the 9-section standard block — structured fields first,
808
+ // legacy det[] prose as the fallback (never '_pending_' for a complete
809
+ // record), evidence combined into the PoC through the 20-01 interleave
810
+ findingBodies.push(...findingBlock(dir, r, { reportDir, det, recById }).lines);
811
+ // legacy '## Retest — <date>' log lanes ride after the block (the standard's
812
+ // section 9 above is sourced from the record itself)
813
+ for (const k of Object.keys(det).filter((x) => /^Retest — /.test(x))) {
814
+ findingBodies.push(`**${k}.** ${det[k]}`, '');
815
+ }
816
+ }
817
+
818
+ // Phase 22 (RETEST-01): the flip summary renders ONLY when a retested_*
819
+ // finding exists — placed after the findings summary. Without retested
820
+ // findings the sections array is unchanged and the report byte-identical
821
+ // (pinned by the 22-01 tests).
822
+ const fixedRows = rows.filter((r) => r.status === 'retested_pass');
823
+ const retainedRows = rows.filter((r) => r.status === 'retested_fail');
824
+ const hasRetested = fixedRows.length + retainedRows.length > 0;
825
+
826
+ const sections = [
827
+ { h: 'Executive Summary', body: [
828
+ '',
829
+ '_TODO: reporter writes this — leadership language, the 3–5 findings that',
830
+ 'matter most, the single most important remediation. One page max._',
831
+ '',
832
+ '### Findings by severity',
833
+ '',
834
+ ...severityCounts(rows),
835
+ ] },
836
+ { h: 'Scope & Methodology', body: [
837
+ '',
838
+ `**Box level:** ${cfg.box || '_not recorded_'}`,
839
+ '',
840
+ '### In scope (from SCOPE.md)',
841
+ '',
842
+ scopeSection(scopeText, 'In Scope') || '_see SCOPE.md_',
843
+ '',
844
+ '### Project',
845
+ '',
846
+ scopeSection(project, 'Objectives') || '_see PROJECT.md_',
847
+ '',
848
+ '### Coverage limitations (verbatim from SCOPE.md)',
849
+ '',
850
+ scopeSection(scopeText, 'Coverage notes') || '_none stated_',
851
+ ] },
852
+ { h: 'Findings', body: [
853
+ '',
854
+ ...findingsTable,
855
+ '',
856
+ ...findingBodies,
857
+ ] },
858
+ ...(hasRetested
859
+ ? [{ h: 'Retest Verdict Flips', body: flipSummaryBody(fixedRows, retainedRows) }]
860
+ : []),
861
+ ...(hasObjective
862
+ ? [
863
+ { h: 'Attack Path', body: attackPathBody(pathRes, g, rows) },
864
+ { h: 'Defensive Implications', body: defensiveImplicationsBody(sim, g) },
865
+ ]
866
+ : []),
867
+ { h: 'Compliance Mapping', body: [
868
+ '',
869
+ '_TODO: reporter maps findings + pack coverage to the client frameworks',
870
+ 'named in PROJECT.md (SAMA CSF / PCI DSS / …). Mark gaps explicitly —',
871
+ 'never invent a mapping._',
872
+ ] },
873
+ { h: 'Appendix', body: [
874
+ '',
875
+ '### Tools (enabled packs)',
876
+ '',
877
+ ...toolLines.map((t) => `- ${t}`),
878
+ '',
879
+ '### Accounts',
880
+ '',
881
+ accounts || '_none_',
882
+ '',
883
+ '### Evidence manifest (hash-chained ledger, ADR-016)',
884
+ '',
885
+ ...evManifest.map((e) => `- ${e.id} — ${e.path} (sha256 ${String(e.sha256).slice(0, 12)}…)`),
886
+ '',
887
+ '### Raw-log manifest (runs/)',
888
+ '',
889
+ ...(runs.length ? runs.map((r) => `- ${r}`) : ['_no run logs_']),
890
+ '',
891
+ '### Rejected findings (did not meet the validation bar)',
892
+ '',
893
+ ...(rejected.length
894
+ ? rejected.map((r) => `- ${r.id} ${r.title} — rejected at independent replay`)
895
+ : ['_none_']),
896
+ ] },
897
+ ];
898
+ const parts = [`# Penetration Test Report — ${id}`];
899
+ let n = 1;
900
+ for (const s of sections) {
901
+ parts.push(`## ${n++}. ${s.h}`, ...s.body, '');
902
+ }
903
+ fs.writeFileSync(draftPath, parts.join('\n'));
904
+ return finish({ written: draftPath, variant, findings: rows.length, rejected: rejected.length });
905
+ }
906
+
907
+ /**
908
+ * ---------- v0.6 01-03: report.verify (brief 1.6 / ADR-023) ----------
909
+ *
910
+ * verifyReport is the "report gate". It is the deterministic backstop that would
911
+ * have caught the 20260924 delivery (a report marked REVIEW-READY while the
912
+ * register was empty / inconsistent):
913
+ *
914
+ * 1. PLACEHOLDER SCAN — the reporter must have replaced every _TODO: / FIXME
915
+ * / REDACTED block that report.compile emits. A fresh (unfilled) REPORT.md
916
+ * is therefore REFUSED.
917
+ * 2. REGISTER SYNC — the findings table rendered into the report must match
918
+ * the findings register (findings/INDEX.md) exactly: same set of finding
919
+ * ids and same severity per id. Any missing, extra, or severity-divergent
920
+ * row is a REFUSAL that names the offending id.
921
+ *
922
+ * The check is two-sided and deterministic: the severity used is normalized so
923
+ * the client-facing "Informational" band (sevLabel) and the register's raw
924
+ * "None" severity compare equal. report.compile deliberately emits placeholders
925
+ * for the reporter, so compile() does NOT call verifyReport(); the `report.verify`
926
+ * CLI command is the separate gate the reporter must clear before delivery.
927
+ */
928
+ const PLACEHOLDER_RE = /[Tt]ODO|[Ff]IXME|[Rr]EDACTED/g;
929
+ const PLACEHOLDER_MARKERS_RE = /[Tt]ODO|[Ff]IXME|[Rr]EDACTED/;
930
+
931
+ // Split a markdown table row into cells. report.compile escapes pipes inside
932
+ // titles/cwe as \\| so a literal "|" in a cell doesn't break alignment; the
933
+ // unescaped form would silently split that cell into two. Restore them first.
934
+ function splitCells(line) {
935
+ return line.replace(/\\\|/g, '\x00').split('|').map((c) => c.replace(/\x00/g, '|').trim());
936
+ }
937
+
938
+ // A row is the table separator iff every non-empty cell is dashes/colons.
939
+ function isSeparatorRow(cells) {
940
+ return cells.some((c) => /^[\-:]+$/.test(c))
941
+ && cells.every((c) => /^[\-: ]*$/.test(c));
942
+ }
943
+
944
+ /**
945
+ * parseFindingsRows — extract the findings-register table from any markdown
946
+ * document. Returns [{id, title, cwe, cvss, severity, status}, ...]. Only
947
+ * tables whose header row reads `| ID | ... | Severity |` are considered
948
+ * (this disambiguates the findings register from the severity-count table
949
+ * `| Severity | Count |` and the retest verdict table
950
+ * `| ID | Title | Severity | Verdict |`).
951
+ */
952
+ function parseFindingsRows(text) {
953
+ const lines = text.split('\n');
954
+ const rows = [];
955
+ let i = 0;
956
+ while (i < lines.length) {
957
+ if (lines[i].trim().startsWith('|')) {
958
+ const run = [];
959
+ while (i < lines.length && lines[i].trim().startsWith('|')) {
960
+ run.push(lines[i]);
961
+ i++;
962
+ }
963
+ const cells = run.map(splitCells);
964
+ const headerIdx = cells.findIndex((c) => c[1] === 'ID' && c[5] === 'Severity');
965
+ if (headerIdx === -1) continue;
966
+ for (let r = headerIdx + 1; r < cells.length; r++) {
967
+ const c = cells[r];
968
+ if (isSeparatorRow(c)) continue;
969
+ if (c.length < 6) continue;
970
+ rows.push({ id: c[1], title: c[2] || '', cwe: c[3] || '', cvss: c[4] || '', severity: c[5], status: c[6] || '' });
971
+ }
972
+ } else {
973
+ i++;
974
+ }
975
+ }
976
+ return rows;
977
+ }
978
+
979
+ // Client-facing severity band: "None" (CVSS 0.0) is displayed as
980
+ // "Informational" (report.cjs sevLabel); the raw register uses "None".
981
+ // Normalize so the two sides compare equal.
982
+ function normSeverity(s) {
983
+ let v = String(s == null ? '' : s).trim();
984
+ if (!v) return '';
985
+ if (v.toLowerCase() === 'none') return 'Informational';
986
+ return v.charAt(0).toUpperCase() + v.slice(1);
987
+ }
988
+
989
+ /** ADR-025 — parse the "## N. Attack Path" table rows out of a report.
990
+ * Returns null if the section is absent (nothing to ground), otherwise an
991
+ * array of {from, to, finding} for each hop row. */
992
+ function attackPathRows(text) {
993
+ const lines = text.split('\n');
994
+ const startIdx = lines.findIndex((l) => /^##\s.+\bAttack Path\b/i.test(l));
995
+ if (startIdx === -1) return null;
996
+ const endIdx = lines.findIndex((l, i) => i > startIdx && /^##\s.+$/.test(l));
997
+ const sectionLines = endIdx === -1 ? lines.slice(startIdx + 1) : lines.slice(startIdx + 1, endIdx);
998
+ const rows = [];
999
+ let header = null;
1000
+ for (const l of sectionLines) {
1001
+ if (!l.trim().startsWith('|')) continue;
1002
+ const cells = splitCells(l);
1003
+ const candidate = { from: -1, to: -1, finding: -1 };
1004
+ cells.forEach((c, idx) => {
1005
+ const k = c.toLowerCase();
1006
+ if (k === 'from' && candidate.from < 0) candidate.from = idx;
1007
+ else if (k === 'to' && candidate.to < 0) candidate.to = idx;
1008
+ else if (k === 'finding' && candidate.finding < 0) candidate.finding = idx;
1009
+ });
1010
+ if (candidate.from >= 0 && candidate.to >= 0 && candidate.finding >= 0) {
1011
+ header = candidate;
1012
+ continue;
1013
+ }
1014
+ if (!header) continue;
1015
+ if (isSeparatorRow(cells)) continue;
1016
+ rows.push({
1017
+ from: (cells[header.from] || '').trim(),
1018
+ to: (cells[header.to] || '').trim(),
1019
+ finding: (cells[header.finding] || '').trim(),
1020
+ });
1021
+ }
1022
+ const body = lines.slice(startIdx, endIdx === -1 ? lines.length : endIdx).join('\n');
1023
+ return { rows, body };
1024
+ }
1025
+
1026
+ function verifyReport(engagementDir) {
1027
+ if (!engagementDir) throw new Error('report.verify requires --engagement <dir>');
1028
+ const reportDir = paths.reportDir(engagementDir);
1029
+ let reportFile;
1030
+ if (fs.existsSync(path.join(reportDir, 'REPORT.md'))) reportFile = path.join(reportDir, 'REPORT.md');
1031
+ else if (fs.existsSync(path.join(reportDir, 'EXEC.md'))) reportFile = path.join(reportDir, 'EXEC.md');
1032
+ else {
1033
+ throw new Error('no compiled report at report/REPORT.md (run report.compile first) — cannot verify an uncompiled report (v0.6 01-03)');
1034
+ }
1035
+ const errors = [];
1036
+
1037
+ // 1. placeholder scan across every compiled report file in report/.
1038
+ const mdFiles = fs.existsSync(reportDir)
1039
+ ? fs.readdirSync(reportDir).filter((f) => f.endsWith('.md'))
1040
+ : [];
1041
+ for (const f of mdFiles) {
1042
+ const t = fs.readFileSync(path.join(reportDir, f), 'utf8');
1043
+ const hits = t.split('\n').filter((l) => PLACEHOLDER_MARKERS_RE.test(l));
1044
+ if (hits.length) {
1045
+ const first = hits[0].trim();
1046
+ errors.push(`${f}: ${hits.length} unfilled reporter placeholder(s) remain — e.g. "${first.slice(0, 80)}"`);
1047
+ }
1048
+ }
1049
+
1050
+ // 2. findings table vs findings register (findings/INDEX.md).
1051
+ const registerFile = paths.findingsIndex(engagementDir);
1052
+ const registerRows = fs.existsSync(registerFile)
1053
+ ? parseFindingsRows(fs.readFileSync(registerFile, 'utf8'))
1054
+ : [];
1055
+ const reportRows = parseFindingsRows(fs.readFileSync(reportFile, 'utf8'));
1056
+ const reportText = fs.readFileSync(reportFile, 'utf8');
1057
+ const byIdRegister = new Map(registerRows.map((r) => [r.id, r]));
1058
+ const byIdReport = new Map(reportRows.map((r) => [r.id, r]));
1059
+ for (const r of registerRows) {
1060
+ if (!byIdReport.has(r.id)) {
1061
+ errors.push(`findings table is missing register finding ${r.id} ("${r.title || ''}")`);
1062
+ }
1063
+ }
1064
+ for (const r of reportRows) {
1065
+ const reg = byIdRegister.get(r.id);
1066
+ if (!reg) {
1067
+ errors.push(`findings table lists finding ${r.id} which is not in the register`);
1068
+ } else if (normSeverity(r.severity) !== normSeverity(reg.severity)) {
1069
+ errors.push(`severity divergence for ${r.id}: report="${r.severity}" register="${reg.severity}"`);
1070
+ }
1071
+ }
1072
+
1073
+ // 3. ADR-025 — the Attack Path section, when present, must be grounded.
1074
+ // - every cited finding is in the register,
1075
+ // - every path node exists in the graph and any asset node is in-scope,
1076
+ // - the declared objective is named in the section.
1077
+ const ap = attackPathRows(reportText);
1078
+ let g = null;
1079
+ if (ap) {
1080
+ try {
1081
+ g = graph.readGraph(engagementDir);
1082
+ } catch (e) {
1083
+ g = null;
1084
+ }
1085
+ for (const r of ap.rows) {
1086
+ if (r.finding && !byIdRegister.has(r.finding)) {
1087
+ errors.push(`attack path cites finding ${r.finding} that is not in the register`);
1088
+ }
1089
+ }
1090
+ const nodeById = g && Array.isArray(g.nodes)
1091
+ ? new Map(g.nodes.map((n) => [n.id, n]))
1092
+ : new Map();
1093
+ const allPathIds = new Set();
1094
+ for (const r of ap.rows) {
1095
+ if (r.from) allPathIds.add(r.from);
1096
+ if (r.to) allPathIds.add(r.to);
1097
+ }
1098
+ for (const nid of allPathIds) {
1099
+ const n = nodeById.get(nid);
1100
+ if (!n) {
1101
+ errors.push(`attack path references unknown node ${nid} (not in the graph)`);
1102
+ } else if (n.type === 'asset' && n.inScope !== true) {
1103
+ errors.push(`attack path uses out-of-scope asset node ${nid}`);
1104
+ }
1105
+ }
1106
+ if (g && g.objective) {
1107
+ const obj = String(g.objective);
1108
+ if (!ap.body.includes(obj)) {
1109
+ errors.push(`attack path section does not name the declared objective ${obj}`);
1110
+ }
1111
+ }
1112
+ if (ap.rows.length && !g) {
1113
+ errors.push('attack path is present but the graph (surface/graph.json) is unreadable — cannot ground the hops');
1114
+ }
1115
+ }
1116
+
1117
+ return {
1118
+ ok: errors.length === 0,
1119
+ error: errors.length ? errors.join(' ') : null,
1120
+ checks: {
1121
+ placeholders: errors.filter((e) => /placeholder/.test(e)).length,
1122
+ findings: { report: reportRows.length, register: registerRows.length },
1123
+ attackPath: ap ? { rows: ap.rows.length } : undefined,
1124
+ },
1125
+ };
1126
+ }
1127
+
1128
+ // internals are exported for lib/pdf.cjs (v0.6 01-04): the PDF payload must
1129
+ // assemble findings with the EXACT same ordering/severity normalization the
1130
+ // markdown report uses — one implementation, two consumers. parseFindingsRows
1131
+ // is additionally consumed by lib/audit.cjs (v0.6 03-01): the findings-index
1132
+ // and report-freshness checks parse the SAME table shape verifyReport does.
1133
+ // 35-01 (REP-03): findingBlock is the shared 9-section source — REPORT.md
1134
+ // blocks and the PDF payload sections both come from it.
1135
+ module.exports = { compile, verifyReport, sortedReportFindings, sevLabel, sections, findingDetail, parseFindingsRows, findingBlock };