@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,1045 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * pensieve-sdk — the deterministic bridge between agents and engagement state.
5
+ * Every command prints ONE JSON envelope to stdout:
6
+ * {"ok": true, "data": ...}
7
+ * {"ok": false, "error": "sanitized message"}
8
+ *
9
+ * Usage: pensieve-sdk <command> [positional] [--key value ...]
10
+ */
11
+
12
+ const path = require('node:path');
13
+ const { spawnSync } = require('node:child_process');
14
+ const security = require('../lib/security.cjs');
15
+ const scope = require('../lib/scope.cjs');
16
+ const liveness = require('../lib/liveness.cjs');
17
+ const fm = require('../lib/frontmatter.cjs');
18
+ const config = require('../lib/config.cjs');
19
+ const state = require('../lib/state.cjs');
20
+ const target = require('../lib/target.cjs');
21
+ const paths = require('../lib/paths.cjs');
22
+ const ids = require('../lib/ids.cjs');
23
+ const evidence = require('../lib/evidence.cjs');
24
+ const cvss = require('../lib/cvss.cjs');
25
+ const findings = require('../lib/findings.cjs');
26
+ const init = require('../lib/init.cjs');
27
+ const env = require('../lib/env.cjs');
28
+ const fs = require('node:fs');
29
+ const pack = require('../lib/pack.cjs');
30
+ const sarif = require('../lib/sarif.cjs');
31
+ const tools = require('../lib/tools.cjs');
32
+ const monitor = require('../lib/monitor.cjs');
33
+ const report = require('../lib/report.cjs');
34
+ const pdf = require('../lib/pdf.cjs');
35
+ const approvals = require('../lib/approvals.cjs');
36
+ const graph = require('../lib/graph.cjs');
37
+ const closeLib = require('../lib/close.cjs');
38
+ const migrateLib = require('../lib/migrate.cjs');
39
+ const auditLib = require('../lib/audit.cjs');
40
+ const subagent = require('../lib/subagent.cjs');
41
+ const checklist = require('../lib/checklist.cjs');
42
+ const clientlist = require('../lib/clientlist.cjs');
43
+ const recon = require('../lib/recon.cjs');
44
+ const skills = require('../lib/skills.cjs');
45
+ const runbook = require('../lib/runbook.cjs');
46
+ const vault = require('../lib/vault.cjs');
47
+ // Phase 29 (LOOP-01): the adaptive-candidate derivation. Its own lib home —
48
+ // see lib/loop.cjs for why (state derivation over pack/checklist/graph/recon/
49
+ // clientlist accessors, not a subagent spawn-bridge concern).
50
+ const loop = require('../lib/loop.cjs');
51
+
52
+ // 31-01 / SCOP-03: the repo packs root is the resolver's PRIMARY root — the
53
+ // user root ($PENSIEVE_HOME/packs) merges in inside pack.cjs (ONE resolver).
54
+ const PACKS_ROOT = pack.repoRoot();
55
+
56
+ function parseArgs(argv) {
57
+ const positional = [];
58
+ const opts = {};
59
+ for (let i = 0; i < argv.length; i++) {
60
+ const a = argv[i];
61
+ if (a.startsWith('--')) {
62
+ const key = a.slice(2);
63
+ if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) opts[key] = argv[++i];
64
+ else opts[key] = true;
65
+ } else positional.push(a);
66
+ }
67
+ return { positional, opts };
68
+ }
69
+
70
+ function readScopeFile(dir) {
71
+ return scope.parse(fs.readFileSync(paths.scopeFile(dir), 'utf8'));
72
+ }
73
+
74
+ function requireEngagement(opts) {
75
+ const dir = opts.engagement;
76
+ if (!dir) throw new Error('missing --engagement <dir>');
77
+ // flat-layout marker (v0.6 01-01): STATE.md with a status frontmatter field.
78
+ // Legacy .pentest/ engagements must go through engagement.migrate first.
79
+ if (!state.isEngagement(dir)) {
80
+ throw new Error(`engagement not found (no STATE.md with status frontmatter) at the given path`);
81
+ }
82
+ return dir;
83
+ }
84
+
85
+ // target profiles take --host (a bare asset), not an engagement dir.
86
+ function requireHost(opts) {
87
+ if (!opts || !opts.host) throw new Error('missing --host <host>');
88
+ return opts.host;
89
+ }
90
+
91
+ // positional `key=value` pairs -> object (token_names is comma-separated -> list)
92
+ function parseFields(pairs) {
93
+ const out = {};
94
+ for (const p of pairs) {
95
+ const eq = p.indexOf('=');
96
+ if (eq === -1) continue;
97
+ const k = p.slice(0, eq).trim();
98
+ let v = p.slice(eq + 1);
99
+ if (k === 'token_names') v = v.split(',').map((s) => s.trim()).filter(Boolean);
100
+ out[k] = v;
101
+ }
102
+ return out;
103
+ }
104
+
105
+ const ENGAGEMENT_COMMANDS = new Set([
106
+ 'scope.check', 'scope.check-command', 'scope.egress-conf', 'scope.set-box', 'scope.set-checklists', 'config.load',
107
+ // NPX-05 (v1.2): the autonomy dial recorder — scoping-interview answer.
108
+ 'scope.set-autonomy',
109
+ // REACH-01 (v1.1): the contained reachability pre-check — engagement-scoped
110
+ // (reads SCOPE.md, probes through the engagement's own compose network).
111
+ 'scope.liveness',
112
+ 'state.set-status', 'state.pause', 'state.resume', 'state.history', 'evidence.put', 'evidence.verify', 'evidence.verify-chain',
113
+ 'findings.add', 'findings.status', 'findings.list', 'findings.gate', 'findings.ingest', 'findings.attest-clean',
114
+ 'findings.retest-request', 'findings.retest-record', 'findings.update', 'report.compile', 'report.verify', 'report.pdf',
115
+ // ADR-025: objective-driven attack graph (MAP/PLAN/REPORT wiring).
116
+ 'graph.build', 'graph.shortest', 'graph.simulate',
117
+ 'engagement.close',
118
+ 'approve', 'ai-approve', 'plans.approved', 'engagement.audit',
119
+ 'env.render', 'env.up', 'env.down', 'env.status', 'env.proxy-env', 'monitor.scan',
120
+ 'tools.check', 'tools.install',
121
+ 'pack.enabled', 'pack.enable', 'pack.disable',
122
+ // Wave 3 (GSD subagent orchestration): record + verify need a real
123
+ // engagement dir (receipts go under <engagement>/runs/delegations/).
124
+ // list + brief are registry-level (operate on the repo agents/ dir).
125
+ 'subagent.record', 'subagent.verify',
126
+ // Phase 27 (HERM-01): the next-wave derivation reads engagement state
127
+ // (approvals + receipts + config clamp).
128
+ 'subagent.wave',
129
+ // checklist.coverage inspects plans/ inside the engagement dir.
130
+ 'checklist.coverage',
131
+ // client checklist engine (Phase 19): all verbs operate on engagement
132
+ // state (<engagement>/clientlist/) — import copies the client workbook in,
133
+ // the rest read/write the snapshot.
134
+ 'clientlist.import', 'clientlist.list', 'clientlist.write', 'clientlist.export', 'clientlist.status',
135
+ // GRAPH-06: reconner records in-scope discovered hosts into recon/surface.json.
136
+ 'recon.add-host',
137
+ // Phase 22 (RETEST-01): recon-time marker baseline + retest-time diff.
138
+ 'recon.fingerprint', 'recon.fingerprint-diff',
139
+ // Phase 23 (VAULT-01): the credential vault verbs — they operate on the
140
+ // engagement's gitignored 0600 <engagement>/.env slot file.
141
+ 'vault.set', 'vault.get', 'vault.list', 'vault.verify',
142
+ // Phase 29 (LOOP-01): the adaptive plan-candidate derivation reads
143
+ // engagement state (enabled packs + scope + recon surface + graph +
144
+ // clientlist + plans/) and, with --emit, writes plans/ inside the
145
+ // engagement dir.
146
+ 'loop.candidates',
147
+ // Phase 29 (LOOP-02): the worker-discovery writeback — ingests a worker's
148
+ // scratch discoveries.json scope-validated at the door and records the
149
+ // in-scope entries into the engagement's recon surface.
150
+ 'loop.ingest-discoveries',
151
+ // Phase 30 (LOOP-03): the deterministic goal verifier reads engagement
152
+ // state (graph.shortest path + the live findings register) and answers a
153
+ // coverage verdict — read-only, zero LLM.
154
+ 'goal.verify',
155
+ ]);
156
+
157
+ // Phase 19 19-02 (task 6) — fail-closed argument surface for the clientlist
158
+ // verbs. parseArgs collects EVERY --flag; handlers read only the ones they
159
+ // know, so a typo'd flag (--blocker instead of --blocker-note) used to be
160
+ // silently DROPPED while the verb reported ok — a write that "succeeded"
161
+ // without recording the operator's input. Unknown flags are now refused with
162
+ // the flag named and the accepted set listed. Phase 20 (EVID-01, plan 20-01):
163
+ // evidence.put joins the whitelist — its --screenshot/--caption linkage must
164
+ // not silently drop a typo'd figure or caption flag.
165
+ const STRICT_FLAG_VERBS = {
166
+ 'clientlist.import': ['engagement', 'slug'],
167
+ 'clientlist.list': ['engagement', 'slug'],
168
+ 'clientlist.write': ['engagement', 'slug', 'id', 'tier', 'done', 'reason',
169
+ 'finding-id', 'evidence', 'notes', 'blocker-note'],
170
+ 'clientlist.export': ['engagement', 'slug', 'out'],
171
+ 'clientlist.status': ['engagement', 'slug'],
172
+ 'evidence.put': ['engagement', 'finding_id', 'note', 'screenshot', 'caption'],
173
+ // REACH-03 (v1.1): engagement.close joins the whitelist — a typo'd
174
+ // --reason/--by must refuse, not silently close the wrong way.
175
+ 'engagement.close': ['engagement', 'note', 'reason', 'by'],
176
+ // REACH-01 (v1.1): liveness takes no flags beyond the engagement dir.
177
+ 'scope.liveness': ['engagement'],
178
+ // Phase 20 (EVID-01, plan 20-02): report.compile joins the whitelist —
179
+ // --deliverable-dir must not be silently dropped on a typo.
180
+ 'report.compile': ['engagement', 'variant', 'deliverable-dir'],
181
+ // Phase 22 (RETEST-01, plan 22-01): marker pairs are positional (the
182
+ // repeatable form); --json / --live carry a single JSON object alternative.
183
+ // A typo'd --marke/--liv must refuse, not silently drop the baseline input.
184
+ 'recon.fingerprint': ['engagement', 'json'],
185
+ 'recon.fingerprint-diff': ['engagement', 'live'],
186
+ // Phase 33 (REP-01): findings.add joins the whitelist — the structured
187
+ // standard flags are WRITE inputs; a typo'd --desciption must refuse BEFORE
188
+ // any register file is written, not silently record a finding without the
189
+ // standard fields the operator believed they had supplied.
190
+ 'findings.add': ['engagement', 'title', 'cwe', 'cvss', 'cvss_vector', 'assets', 'summary',
191
+ 'evidence', 'json', 'description', 'poc', 'poc-evidence',
192
+ 'impact-demonstrated', 'impact-potential', 'impact-technical', 'impact-business',
193
+ 'remediation', 'references-owasp'],
194
+ // 36-01 (TD-01): findings.update joins the whitelist — the SAME standard
195
+ // field flags as findings.add (write inputs), so a typo'd --desciption must
196
+ // refuse BEFORE any register file is written, not silently "succeed" without
197
+ // the fields the operator believed they had supplied. --cvss/--cvss_vector
198
+ // are deliberately ACCEPTED by the whitelist but REFUSED by the lib's
199
+ // immutability rule (the refusal points at registering a new finding);
200
+ // --status is NOT an accepted flag at all — transitions belong to
201
+ // findings.status, whose gates update must never bypass.
202
+ 'findings.update': ['engagement', 'cvss', 'cvss_vector', 'assets', 'evidence', 'description', 'poc', 'poc-evidence',
203
+ 'impact-demonstrated', 'impact-potential', 'impact-technical', 'impact-business',
204
+ 'remediation', 'references-owasp'],
205
+ // 34-02 (REP-04): findings.status joins the whitelist — --by/--note are the
206
+ // owner gate of risk_accepted, WRITE inputs. A typo'd --bu must refuse
207
+ // BEFORE any register file is written, not silently record an acceptance
208
+ // without the accountable owner the operator believed they had supplied.
209
+ 'findings.status': ['engagement', 'by', 'note'],
210
+ // Phase 23 (VAULT-01): the vault verbs join the whitelist. vault.set takes
211
+ // the KEY positionally and the VALUE ON STDIN — there is deliberately no
212
+ // --value flag, so a secret can never land in argv (shell history /
213
+ // transcripts). vault.get has NO flag that prints a value, ever.
214
+ 'vault.set': ['engagement'],
215
+ 'vault.get': ['engagement', 'key'],
216
+ 'vault.list': ['engagement'],
217
+ 'vault.verify': ['engagement', 'key'],
218
+ // Phase 27 (HERM-01, 27-01): the wave derivation is read-only engagement
219
+ // state — a typo'd flag (--engagment) must refuse, not silently produce a
220
+ // wave from the wrong dir (or none). --json is the explicit envelope form
221
+ // (output is ALWAYS the JSON envelope, like every verb).
222
+ 'subagent.wave': ['engagement', 'json'],
223
+ // Phase 29 (LOOP-01): the adaptive-candidate derivation. Read-only surface
224
+ // except --emit; a typo'd flag (--emitt) must refuse BEFORE any state is
225
+ // touched — never silently derive (or, worse, emit) from a wrong flag.
226
+ 'loop.candidates': ['engagement', 'emit', 'json'],
227
+ // Phase 29 (LOOP-02): the worker-discovery ingest writes recon state (the
228
+ // in-scope entries only); a typo'd flag (--fil) must refuse BEFORE any
229
+ // state is touched — never silently record a partial discovery file.
230
+ 'loop.ingest-discoveries': ['engagement', 'file', 'json'],
231
+ // Phase 30 (LOOP-03): the goal verifier is read-only; a typo'd flag
232
+ // (--jsonn) must refuse rather than silently verify from a wrong dir.
233
+ 'goal.verify': ['engagement', 'json'],
234
+ // 31-02 / SCOP-02: the scaffold verb — a WRITE (mint) into one of the pack
235
+ // roots; a typo'd flag (--repoo) must refuse BEFORE anything is minted.
236
+ // --json is the explicit envelope form (output is ALWAYS the envelope).
237
+ 'pack.scaffold': ['repo', 'json'],
238
+ // 32-01 / SCOP-01: the checklist-selection recorder — a WRITE into
239
+ // config.yaml (enabled_packs), SCOPE.md (## Checklists) and clientlist/.
240
+ // A typo'd flag (--pack, --client_workbook) must refuse BEFORE any state is
241
+ // touched. --json is the explicit envelope form (output is ALWAYS the
242
+ // envelope, like every verb).
243
+ 'scope.set-checklists': ['engagement', 'packs', 'client-workbook', 'json'],
244
+ };
245
+
246
+ function refuseUnknownFlags(cmd, opts) {
247
+ const allowed = STRICT_FLAG_VERBS[cmd];
248
+ if (!allowed) return;
249
+ const unknown = Object.keys(opts).filter((k) => !allowed.includes(k));
250
+ if (unknown.length > 0) {
251
+ throw new Error(
252
+ `unknown option --${unknown[0]} for ${cmd} — accepted: `
253
+ + allowed.map((f) => `--${f}`).join(' ')
254
+ );
255
+ }
256
+ }
257
+
258
+ // `--port 80,443` -> [{ port: 80 }, { port: 443 }]. Undefined/bare flag -> [].
259
+ function parsePortsOpt(port) {
260
+ if (!port || port === true) return [];
261
+ return String(port).split(',').map((s) => s.trim()).filter(Boolean)
262
+ .map((s) => ({ port: parseInt(s, 10) }));
263
+ }
264
+
265
+ // REP-01 helpers for findings.add: comma-split ordered lists ('a,b' -> [a,b]).
266
+ function splitListOpt(v) {
267
+ if (v == null || v === true) return [];
268
+ return String(v).split(',').map((s) => s.trim()).filter(Boolean);
269
+ }
270
+
271
+ // '--poc-evidence 1=E-aaa,2=E-bbb+E-ccc' -> { '1': ['E-aaa'], '2': ['E-bbb','E-ccc'] }
272
+ // (steps are 1-based positions in --poc; + separates several artifacts of one step)
273
+ function parsePocEvidenceOpt(v) {
274
+ if (v == null || v === true) return {};
275
+ const map = {};
276
+ for (const pair of splitListOpt(v)) {
277
+ const eq = pair.indexOf('=');
278
+ if (eq <= 0) {
279
+ throw new Error(`--poc-evidence expects step=evidence pairs ("1=E-aaa,2=E-bbb") — got "${pair}"`);
280
+ }
281
+ const step = pair.slice(0, eq).trim();
282
+ const ids = pair.slice(eq + 1).split('+').map((s) => s.trim()).filter(Boolean);
283
+ if (!/^\d+$/.test(step) || !ids.length) {
284
+ throw new Error(`--poc-evidence expects step=evidence pairs ("1=E-aaa,2=E-bbb") — got "${pair}"`);
285
+ }
286
+ map[step] = ids;
287
+ }
288
+ return map;
289
+ }
290
+
291
+ const COMMANDS = {
292
+ // target profiles (v0.6 05-02): cross-engagement, registry-level (NOT in
293
+ // ENGAGEMENT_COMMANDS — they do not need an engagement dir, they need --host).
294
+ 'target.get': ({ opts }) => {
295
+ const t = target.get(requireHost(opts));
296
+ return t ? { known: true, host: t.host, file: t.file, profile: { ...t.data, body: t.body } } : { known: false, host: target.sanitizeHost(opts.host) };
297
+ },
298
+ 'target.put': ({ positional, opts }) => target.put(requireHost(opts), parseFields(positional)),
299
+ 'target.list': () => ({ targets: target.list() }),
300
+ 'target.recognize': ({ opts }) => target.recognize(requireHost(opts)),
301
+ 'target.remove': ({ opts }) => ({ removed: target.remove(requireHost(opts)) }),
302
+
303
+ 'scope.check': ({ positional, opts }) =>
304
+ scope.check(readScopeFile(opts.engagement), positional[0]),
305
+ 'scope.check-command': ({ positional, opts }) =>
306
+ scope.checkCommand(readScopeFile(opts.engagement), positional.join(' ')),
307
+ // REACH-01 (v1.1): contained reachability pre-check — probes every
308
+ // in-scope host through the engagement proxy, classifies the squid
309
+ // error ids, writes the ledger + the recon/LIVENESS.md verdict.
310
+ 'scope.liveness': ({ opts }) => liveness.liveness(opts.engagement),
311
+ 'scope.egress-conf': ({ opts }) =>
312
+ ({ conf: env.renderAllowlist(opts.engagement) }),
313
+
314
+ // BOX-01: scoper records box level (+ optional waivers) into config.yaml.
315
+ // agent-skills (Phase 8, SKILL-01): resolve an agent's runbooks into a verbatim
316
+ // <agent_skills> block. NOT in ENGAGEMENT_COMMANDS — it degrades to an empty
317
+ // block when no --engagement is given (skills.agentSkills guards undefined).
318
+ // Returns {data, format:'text'} so main() writes it raw (not JSON-wrapped).
319
+ 'agent-skills': ({ positional, opts }) =>
320
+ skills.agentSkills(positional[0], opts.engagement, { packsRoot: PACKS_ROOT }),
321
+
322
+ // RUNBOOK-01 presence gate. Not an ENGAGEMENT_COMMAND (lints a path or pack slug).
323
+ // ok -> { linted: N } (exit 0); any incomplete runbook -> throw (respond ok:false,
324
+ // exitCode 1) with a message naming each incomplete file and its missing parts.
325
+ 'runbook-lint': ({ positional }) => {
326
+ const { ok, results } = runbook.collect(positional[0], { packsRoot: PACKS_ROOT });
327
+ if (!ok) {
328
+ const report = results
329
+ .filter((r) => r.missing.length)
330
+ .map((r) => `${r.path}: missing ${r.missing.join(', ')}`)
331
+ .join('; ');
332
+ throw new Error(`runbook-lint failed — ${report}`);
333
+ }
334
+ return { linted: results.length };
335
+ },
336
+
337
+ // runbook-item (QUICK-01): resolve one checklist item ID to its active-pack
338
+ // runbook path. NOT in ENGAGEMENT_COMMANDS (needs only --engagement to read
339
+ // enabled packs). Hit -> {data:path, format:'text'} raw path exit 0. Miss ->
340
+ // throw naming the ID + searched packs; main()'s catch -> ok:false + exit 1
341
+ // (SC4: unknown ID changes nothing — find is read-only).
342
+ 'runbook-item': ({ positional, opts }) => {
343
+ const hit = runbook.find(positional[0], { engagementDir: opts.engagement, packsRoot: PACKS_ROOT });
344
+ if (hit) return { data: hit.path, format: 'text' };
345
+ const packs = pack.enabled(opts.engagement);
346
+ throw new Error(
347
+ `runbook-item: unknown item ${positional[0]} — not found in enabled packs: ${packs.join(', ') || '(none)'}`
348
+ );
349
+ },
350
+
351
+ 'scope.set-box': ({ positional, opts }) =>
352
+ scope.recordBox(opts.engagement, {
353
+ box: positional[0] || opts.box,
354
+ sourceWaiver: opts['source-waiver'] === true,
355
+ credentialsWaiver: opts['credentials-waiver'],
356
+ }),
357
+
358
+ // NPX-05 (v1.2): the autonomy dial recorder. Validated then written to
359
+ // config.yaml (the dial's source of truth — never STATE.md).
360
+ 'scope.set-autonomy': ({ positional, opts }) =>
361
+ scope.recordAutonomy(opts.engagement, { level: positional[0] || opts.level }),
362
+
363
+ // 32-01 / SCOP-01: the scoping interview's checklist-selection recorder.
364
+ // VALIDATE-THEN-WRITE (see lib/scope.cjs setChecklists): every slug resolves
365
+ // across BOTH pack roots and the client workbook imports BEFORE any
366
+ // engagement state is written. Refusals pass through RAW (report.pdf
367
+ // convention): the unknown-slug envelope names the searched ROOTS and the
368
+ // collision envelope names BOTH paths — sanitizeError would redact every
369
+ // one of them to "[path]", and the paths ARE the remedy.
370
+ 'scope.set-checklists': ({ opts }) => {
371
+ if (!opts.packs) throw new Error('scope.set-checklists requires --packs <slugs,comma-separated>');
372
+ const r = scope.setChecklists(opts.engagement, {
373
+ packs: opts.packs,
374
+ clientWorkbook: opts['client-workbook'] || null,
375
+ packsRoot: PACKS_ROOT,
376
+ });
377
+ return r.ok ? (({ ok, ...data }) => data)(r) : r;
378
+ },
379
+
380
+ 'frontmatter.get': ({ positional }) => ({ value: fm.get(fs.readFileSync(positional[0], 'utf8'), positional[1]) }),
381
+ 'frontmatter.set': ({ positional }) => {
382
+ const out = fm.set(fs.readFileSync(positional[0], 'utf8'), positional[1], positional[2]);
383
+ fs.writeFileSync(positional[0], out);
384
+ return { written: positional[0] };
385
+ },
386
+
387
+ 'config.load': ({ opts }) => config.load(opts.engagement),
388
+
389
+ // GRAPH-06: record an in-scope discovered host (+ optional --port list) into
390
+ // the per-engagement recon surface (recon/surface.json) the attack graph reads.
391
+ 'recon.add-host': ({ positional, opts }) =>
392
+ recon.recordHost(opts.engagement, {
393
+ host: positional[0] || opts.host,
394
+ services: parsePortsOpt(opts.port),
395
+ }),
396
+
397
+ // Phase 22 (RETEST-01, plan 22-01): capture the recon marker baseline
398
+ // (recon/FINGERPRINT.md) and diff live markers against it at retest time.
399
+ // Marker pairs come as repeatable positional key=value args, or as one JSON
400
+ // object via --json (write) / --live (diff). The SDK never fetches — the
401
+ // reconner extracts headers/cookies/build strings and supplies the pairs.
402
+ 'recon.fingerprint': ({ positional, opts }) =>
403
+ recon.fingerprint(opts.engagement,
404
+ [...positional, ...(opts.json !== undefined ? [String(opts.json)] : [])]),
405
+ 'recon.fingerprint-diff': ({ positional, opts }) =>
406
+ recon.fingerprintDiff(opts.engagement,
407
+ [...positional, ...(opts.live !== undefined ? [String(opts.live)] : [])]),
408
+
409
+ // --engagement wins over cwd traversal (v0.6 01-02, brief 1.1): validate
410
+ // the marker, then use the dir directly — never silently fall back to cwd.
411
+ 'state.current': ({ opts }) => {
412
+ if (opts.engagement) {
413
+ const dir = path.resolve(opts.engagement);
414
+ if (!state.isEngagement(dir)) {
415
+ throw new Error('engagement not found (no STATE.md with status frontmatter) at the given path');
416
+ }
417
+ return { engagement: dir };
418
+ }
419
+ return { engagement: state.current(process.cwd()) };
420
+ },
421
+ 'state.list': () => state.list(),
422
+ 'state.set-status': ({ positional, opts }) => ({ status: state.setStatus(opts.engagement, positional[0]) }),
423
+ // NOT in ENGAGEMENT_COMMANDS: sync exists to REPAIR engagements whose
424
+ // STATE.md lost its status frontmatter — requireEngagement would reject
425
+ // exactly the dirs this command fixes. It validates the dir itself.
426
+ 'state.sync': ({ opts }) => state.sync(opts.engagement),
427
+ // registry-level op (not engagement-dependent): reports both lists
428
+ 'state.prune': () => state.prune(),
429
+ 'state.pause': ({ positional, opts }) => ({ file: state.pause(opts.engagement, positional.join(' ') || opts.note || '') }),
430
+ 'state.resume': ({ opts }) => state.resumeInfo(opts.engagement),
431
+ // checkpoint audit trail (v0.6 05-01): the monotonic STATE_HISTORY.jsonl
432
+ 'state.history': ({ opts }) => ({ history: state.readHistory(opts.engagement) }),
433
+
434
+ // v0.6 03-01 (VIZ-04 / brief 3.4): unlinked evidence is a convention
435
+ // warning, not a refusal — evidence with no --finding_id cannot be traced
436
+ // to a claim. The store still succeeds; data.warnings flags it so the
437
+ // operator/agent links it (or confirms it backs an attest-clean verdict).
438
+ 'evidence.put': ({ positional, opts }) => {
439
+ const rec = evidence.store(opts.engagement, positional[0], opts);
440
+ // REACH-06 (v1.1): the unlinked-evidence warning is phase-gated — before
441
+ // testing there are no findings for recon evidence to trace to yet
442
+ // (the live walkthrough was warned on every recon artifact). Fail-open
443
+ // on an unreadable status: the warning is a convention, not a gate.
444
+ let warnUnlinked = true;
445
+ try {
446
+ warnUnlinked = ['testing', 'validating', 'validated-static', 'reporting', 'retesting']
447
+ .includes(state.readStatus(opts.engagement));
448
+ } catch { /* unreadable state — keep the warning */ }
449
+ const warnings = opts.finding_id ? [] : (warnUnlinked ? [
450
+ `unlinked evidence: ${rec.id} stored without --finding_id — every artifact should trace to a finding `
451
+ + '(re-cite it via findings.add --evidence, or link it at findings.retest-record / findings.attest-clean)',
452
+ ] : []);
453
+ // Phase 23 (VAULT-01): warn (stderr, non-fatal) when a vault KEY NAME leaks
454
+ // into the note or the raw-file basename. Names the key only — the value
455
+ // is never logged; the operator decides whether the evidence is safe.
456
+ const vaultLeak = evidence.vaultKeyLeakWarning(opts.engagement,
457
+ [opts.note || '', positional[0] ? path.basename(positional[0]) : '']);
458
+ if (vaultLeak) {
459
+ warnings.push(vaultLeak);
460
+ process.stderr.write(`warning: ${vaultLeak}\n`);
461
+ }
462
+ return { ...rec, warnings };
463
+ },
464
+ 'evidence.verify': ({ positional, opts }) => evidence.verify(opts.engagement, positional[0]),
465
+ 'evidence.verify-chain': ({ opts }) => evidence.verifyChain(opts.engagement),
466
+
467
+ 'cvss.score': ({ positional }) => cvss.score(positional[0]),
468
+
469
+ // Phase 33 (REP-01): the structured standard fields. Repeatable/ordered
470
+ // values follow the house comma-split convention (--evidence/--assets/
471
+ // --remediation/--impact-*); --poc splits on '|' instead because steps
472
+ // naturally contain commas ("GET /x, which returns y"); --poc-evidence maps
473
+ // 1-based step numbers to evidence ids ("1=E-aaa,2=E-bbb+E-ccc"); every
474
+ // cited id — --evidence, inline '[E-id]' in poc steps, --poc-evidence
475
+ // values — is ledger-verified in findings.add (fail-closed).
476
+ 'findings.add': ({ opts }) => findings.add(opts.engagement, {
477
+ title: opts.title, cwe: opts.cwe, cvss_vector: opts.cvss || opts.cvss_vector,
478
+ assets: opts.assets ? String(opts.assets).split(',') : [], summary: opts.summary || '',
479
+ evidence: opts.evidence ? String(opts.evidence).split(',').map((s) => s.trim()).filter(Boolean) : [],
480
+ description: opts.description || '',
481
+ poc: opts.poc ? String(opts.poc).split('|').map((s) => s.trim()).filter(Boolean) : [],
482
+ pocEvidence: parsePocEvidenceOpt(opts['poc-evidence']),
483
+ impact: {
484
+ demonstrated: splitListOpt(opts['impact-demonstrated']),
485
+ potential: splitListOpt(opts['impact-potential']),
486
+ technical: splitListOpt(opts['impact-technical']),
487
+ business: splitListOpt(opts['impact-business']),
488
+ },
489
+ remediation: splitListOpt(opts.remediation),
490
+ referencesOwasp: opts['references-owasp'] != null ? splitListOpt(opts['references-owasp']) : null,
491
+ }),
492
+ // 36-01 (TD-01): findings.update <id> — complete/edit an EXISTING record in
493
+ // place. Same field flags as findings.add (provided fields REPLACE stored
494
+ // ones; unprovided untouched); --cvss is accepted by the whitelist but
495
+ // REFUSED by the lib (id + cvss vector/score/severity letter are immutable —
496
+ // register a new finding instead); status is NOT settable here (the
497
+ // findings.status gates still own the draft->validated transition).
498
+ 'findings.update': ({ positional, opts }) => findings.update(opts.engagement, positional[0], {
499
+ cvss: opts.cvss || opts.cvss_vector || null,
500
+ description: opts.description !== undefined ? opts.description : undefined,
501
+ poc: opts.poc !== undefined ? String(opts.poc).split('|').map((s) => s.trim()).filter(Boolean) : undefined,
502
+ pocEvidence: opts['poc-evidence'] !== undefined ? parsePocEvidenceOpt(opts['poc-evidence']) : undefined,
503
+ impact: {
504
+ demonstrated: opts['impact-demonstrated'] !== undefined ? splitListOpt(opts['impact-demonstrated']) : undefined,
505
+ potential: opts['impact-potential'] !== undefined ? splitListOpt(opts['impact-potential']) : undefined,
506
+ technical: opts['impact-technical'] !== undefined ? splitListOpt(opts['impact-technical']) : undefined,
507
+ business: opts['impact-business'] !== undefined ? splitListOpt(opts['impact-business']) : undefined,
508
+ },
509
+ remediation: opts.remediation !== undefined ? splitListOpt(opts.remediation) : undefined,
510
+ assets: opts.assets !== undefined ? String(opts.assets).split(',') : undefined,
511
+ referencesOwasp: opts['references-owasp'] !== undefined ? splitListOpt(opts['references-owasp']) : undefined,
512
+ evidence: opts.evidence !== undefined ? String(opts.evidence).split(',').map((s) => s.trim()).filter(Boolean) : undefined,
513
+ }),
514
+ // 34-01 (REP-02): a gate refusal (findings-standard) passes through as its
515
+ // own ok:false envelope — gate name + the full every-missing-section-at-once
516
+ // message, UNSANITIZED (sanitizeError would truncate it at 300 chars; this
517
+ // is the same pass-through main() already gives report.pdf envelopes).
518
+ 'findings.status': ({ positional, opts }) => {
519
+ try {
520
+ // 34-02 (REP-04): --by/--note ride the verb into the owner gate —
521
+ // refused fail-closed by the lib when risk_accepted lacks either.
522
+ return findings.setStatus(opts.engagement, positional[0], positional[1], {
523
+ by: opts.by, note: opts.note,
524
+ });
525
+ } catch (e) {
526
+ if (e && e.gate) return { ok: false, gate: e.gate, error: e.message };
527
+ throw e;
528
+ }
529
+ },
530
+ // 34-02 (REP-04): the register read renders the closure vocabulary next to
531
+ // the machine status (closure_status), so every consumer of the list output
532
+ // sees the standard's wording without re-deriving it.
533
+ 'findings.list': ({ opts }) => findings
534
+ .list(opts.engagement, opts.status ? { status: opts.status } : {})
535
+ .map((r) => ({ ...r, closure_status: findings.closureStatus(r.status) })),
536
+ 'findings.gate': ({ opts }) => findings.gate(opts.engagement),
537
+ // v0.6 02-01 follow-up: register the 01-03 zero-findings attestation gate
538
+ // (lib shipped in 0b2eaca but the CLI command was never wired — caught by
539
+ // the 02-01 executor). Same --evidence parsing as findings.add.
540
+ 'findings.attest-clean': ({ opts }) =>
541
+ findings.attestClean(opts.engagement,
542
+ opts.evidence ? String(opts.evidence).split(',').map((s) => s.trim()).filter(Boolean) : []),
543
+ 'findings.retest-request': ({ positional, opts }) => findings.retestRequest(opts.engagement, positional[0]),
544
+ 'findings.retest-record': ({ positional, opts }) => findings.retestRecord(opts.engagement, positional[0], {
545
+ verdict: opts.verdict,
546
+ evidence: opts.evidence ? String(opts.evidence).split(',') : [],
547
+ note: opts.note || '',
548
+ // 36-01 (TD-02): the standard's section-9 closure fields (free text,
549
+ // rendered in the document + RETEST.md; '_not recorded_' when absent)
550
+ endpoint: opts.endpoint || '',
551
+ steps: opts.steps || '',
552
+ }),
553
+ 'report.compile': ({ opts }) => report.compile(opts.engagement, {
554
+ variant: opts.variant || 'client',
555
+ // 20-02: assemble the client deliverable folder (README + workbook +
556
+ // sheets + figures, COPY semantics) next to the normal compile.
557
+ deliverableDir: opts['deliverable-dir'] || null,
558
+ }),
559
+ // v0.6 01-03 (brief 1.6): the report gate. compile() deliberately leaves
560
+ // reporter _TODO: placeholders in REPORT.md/EXEC.md, so verify is a distinct
561
+ // command the reporter must clear before the engagement may be delivered:
562
+ // - rejects any remaining placeholder (TODO/FIXME/REDACTED) in report/*
563
+ // - rejects any findings-table row that is missing from the register
564
+ // (findings/INDEX.md), extra relative to it, or with a severity that
565
+ // differs from the sdk-computed register severity.
566
+ 'report.verify': ({ opts }) => {
567
+ const v = report.verifyReport(opts.engagement);
568
+ if (v.ok === false) {
569
+ // The CLI wrapper catches this and produces the {ok:false, error} envelope.
570
+ // report.verifyReport itself returns {ok, error, checks} per the spec
571
+ // contract; the CLI command's JSON output must be top-level ok:false
572
+ // when the report gate refuses.
573
+ throw new Error(v.error);
574
+ }
575
+ return { checks: v.checks };
576
+ },
577
+ 'engagement.close': ({ opts }) => closeLib.close(opts.engagement, {
578
+ note: opts.note || '',
579
+ reason: opts.reason || 'completed',
580
+ by: opts.by || '',
581
+ }),
582
+
583
+ // Phase 23 (VAULT-01): the credential vault verbs. vault.set reads the VALUE
584
+ // FROM STDIN (never argv — values must not land in shell history or
585
+ // transcripts); one trailing newline is stripped so `echo`/heredoc piping is
586
+ // ergonomic. Every response surface is MASKED (key, length, sha8) — there is
587
+ // deliberately no flag anywhere that prints a value.
588
+ 'vault.set': ({ positional, opts }) => {
589
+ if (positional.length < 1) throw new Error('vault.set requires <key> (value arrives on stdin)');
590
+ let raw;
591
+ try {
592
+ raw = fs.readFileSync(0, 'utf8'); // fd 0 = stdin (piped)
593
+ } catch {
594
+ throw new Error('vault.set could not read the value from stdin — pipe it (e.g. printf %s "value" | pensieve-sdk vault.set KEY --engagement DIR)');
595
+ }
596
+ const value = raw.replace(/\r?\n$/, ''); // strip ONE trailing newline (echo/heredoc)
597
+ return vault.set(opts.engagement, positional[0], value);
598
+ },
599
+ 'vault.get': ({ opts }) => {
600
+ if (!opts.key) throw new Error('vault.get requires --key <name> (masked read-back: length + sha8 prefix — values are never printed)');
601
+ return vault.getMasked(opts.engagement, opts.key);
602
+ },
603
+ 'vault.list': ({ opts }) => ({ keys: vault.list(opts.engagement) }),
604
+ 'vault.verify': ({ opts }) => {
605
+ if (!opts.key) throw new Error('vault.verify requires --key <name>');
606
+ return vault.verify(opts.engagement, opts.key);
607
+ },
608
+ // v0.6 03-01 (VIZ-01 + VIZ-02 / brief 3.1–3.2): deterministic compliance
609
+ // report — drift becomes one command away instead of invisible. Envelope
610
+ // stays ok:true (the audit RAN); compliance verdict lives in data.ok and
611
+ // the failed check names in data.drift.
612
+ 'engagement.audit': ({ opts }) => auditLib.audit(opts.engagement),
613
+ // v0.6 01-04 (brief 1.11 / ADR-014 lane-B): formal PDF export. Gated on
614
+ // report.verify pass + recorded report approval; the Python/ReportLab
615
+ // renderer is probed on the host and a miss returns exact setup
616
+ // instructions (ok:false envelope). The envelope is passed through UNTHROWN
617
+ // (see main): routing the instructions through security.sanitizeError would
618
+ // strip the venv paths and truncate the message.
619
+ 'report.pdf': ({ opts }) => {
620
+ const r = pdf.render(opts.engagement, { out: opts.out || null });
621
+ return r.ok ? r.data : r;
622
+ },
623
+ // ADR-025: objective-driven attack graph (MAP/PLAN/REPORT wiring).
624
+ // graph.build (MAP): emits surface/graph.json + ATTACK-GRAPH.md from
625
+ // SCOPE + validated findings + evidence + PROJECT objective/crown.
626
+ // Failures (empty scope) throw so the CLI emits a top-level ok:false.
627
+ 'graph.build': ({ positional, opts }) => {
628
+ const r = graph.build(opts.engagement);
629
+ if (!r.ok) throw new Error(r.error);
630
+ return r;
631
+ },
632
+ // graph.shortest (PLAN): Dijkstra from each in-scope foothold to the
633
+ // objective; <objective> arg resolves by kind, label, or crown artifact.
634
+ 'graph.shortest': ({ positional, opts }) => {
635
+ const r = graph.shortest(opts.engagement, positional[0]);
636
+ if (!r.ok) throw new Error(r.error);
637
+ return r;
638
+ },
639
+ // graph.simulate (REPORT): chokepoints + per-node pivot impact.
640
+ 'graph.simulate': ({ positional, opts }) => graph.simulate(opts.engagement),
641
+ // v0.6 01-03 item 5 (ADR-023): the checkpoint writer. Humans never hand-edit
642
+ // approval frontmatter — this command records the checkpoint deterministically
643
+ // (approved/approved_by/approved_at) on SCOPE.md, plans/PLAN-<id>.md, or
644
+ // report/REPORT.md. state.set-status refuses boundary transitions without it.
645
+ 'approve': ({ opts }) => {
646
+ const r = approvals.approve(opts.engagement, { artifact: opts.artifact, by: opts.by });
647
+ if (!r.ok) throw new Error(r.error);
648
+ return r.data;
649
+ },
650
+ // SWARM-02: the test swarm's approved-only work list { approved, unapproved, total }.
651
+ // A convenience list, not the ROE gate (planned->testing already refuses unapproved).
652
+ 'plans.approved': ({ opts }) => approvals.approvedPlans(opts.engagement),
653
+ // AI-as-approver (v0.6 05-04): guardrailed, verdict-recording approval.
654
+ // escalate is a normal outcome (ok:true, verdict:'escalate'); only a true
655
+ // error (rubber stamp, bad input) throws.
656
+ 'ai-approve': ({ opts }) => {
657
+ const r = approvals.aiApprove(opts.engagement, {
658
+ artifact: opts.artifact,
659
+ by: opts.by,
660
+ confidence: opts.confidence !== undefined ? parseFloat(opts.confidence) : undefined,
661
+ reasoning: opts.reasoning,
662
+ evidence: opts.evidence ? String(opts.evidence).split(',').map((s) => s.trim()).filter(Boolean) : [],
663
+ });
664
+ if (!r.ok) throw new Error(r.error);
665
+ return r.data;
666
+ },
667
+ // NOT in ENGAGEMENT_COMMANDS: migrate exists to convert LEGACY .pentest/
668
+ // engagements, which the flat-marker requireEngagement would reject. It
669
+ // validates the dir itself.
670
+ 'engagement.migrate': ({ opts }) => migrateLib.migrate(opts.engagement),
671
+ 'pack.learn': ({ opts }) => pack.learn(PACKS_ROOT, opts.pack, { item: opts.item, source: opts.source }),
672
+ 'pack.learnings': ({ positional }) => pack.learnings(PACKS_ROOT, positional[0]),
673
+ 'pack.promote': ({ positional }) => pack.promote(PACKS_ROOT, positional[0], positional[1]),
674
+ // autonomous learning (v0.6 05-03): confirm = applied-and-worked provenance;
675
+ // auto-promotes at the threshold. revert = the human veto (pulls it back out).
676
+ 'pack.confirm': ({ positional, opts }) => pack.confirm(PACKS_ROOT, positional[0], positional[1], { by: opts.by || opts.source || '', note: opts.note || '' }),
677
+ 'pack.revert': ({ positional }) => pack.revert(PACKS_ROOT, positional[0], positional[1]),
678
+ 'findings.sarif': ({ opts }) => {
679
+ const rows = findings.list(opts.engagement, opts.status ? { status: opts.status } : { status: 'validated' });
680
+ const log = sarif.buildSarif(rows, { engagement: path.basename(opts.engagement) });
681
+ const out = opts.out || path.join(paths.reportDir(opts.engagement), 'findings.sarif');
682
+ fs.mkdirSync(path.dirname(out), { recursive: true });
683
+ fs.writeFileSync(out, JSON.stringify(log, null, 2) + '\n');
684
+ return { written: out, results: log.runs[0].results.length };
685
+ },
686
+ 'findings.ingest': ({ opts }) => {
687
+ if (!opts.file) throw new Error('findings.ingest requires --file <sarif>');
688
+ const log = JSON.parse(fs.readFileSync(opts.file, 'utf8'));
689
+ const drafts = sarif.parseSarif(log).map((row) => findings.add(opts.engagement, row));
690
+ return { imported: drafts.length, ids: drafts.map((d) => d.id) };
691
+ },
692
+
693
+ // Wave 3 (GSD v1.43.0-rc2 subagent orchestration): the deterministic bridge
694
+ // between the orchestrator and the nine agents/pensieve-*.md contracts. list/
695
+ // brief are registry-level (no engagement); record/verify need a real
696
+ // engagement dir.
697
+ 'subagent.list': () => subagent.list({ agentsDir: process.env.PENSIEVE_AGENT_DIR }),
698
+ 'subagent.brief': ({ positional, opts }) => {
699
+ if (positional.length < 1) throw new Error("subagent.brief requires <agent>");
700
+ // Mirror agent-skills graceful-empty: absent --engagement -> no injected block.
701
+ // Return the composed prompt raw ({format:'text'}) so the spawn gets it verbatim.
702
+ const result = subagent.brief({
703
+ agent: positional[0],
704
+ unit: opts.unit || '',
705
+ agentsDir: process.env.PENSIEVE_AGENT_DIR,
706
+ engagementDir: opts.engagement,
707
+ packsRoot: PACKS_ROOT,
708
+ });
709
+ return { data: result.prompt, format: 'text' };
710
+ },
711
+ 'subagent.record': ({ positional, opts }) => {
712
+ if (positional.length < 1) throw new Error('subagent.record requires <agent>');
713
+ return subagent.record({
714
+ engagementDir: opts.engagement,
715
+ agent: positional[0],
716
+ unit: opts.unit || '',
717
+ marker: opts.marker || null,
718
+ summary: opts.summary || '',
719
+ artifacts: opts.artifacts ? String(opts.artifacts).split(',').map((s) => s.trim()).filter(Boolean) : null,
720
+ agentsDir: process.env.PENSIEVE_AGENT_DIR,
721
+ });
722
+ },
723
+ 'subagent.verify': ({ positional, opts }) => {
724
+ if (positional.length < 1) throw new Error('subagent.verify requires <agent>');
725
+ return subagent.verify({ engagementDir: opts.engagement, agent: positional[0], agentsDir: process.env.PENSIEVE_AGENT_DIR });
726
+ },
727
+ // Phase 27 (HERM-01): the NEXT capped wave — approved plans minus recorded
728
+ // receipts, clamped by config.maxParallelItems. Read-only; fails closed.
729
+ 'subagent.wave': ({ opts }) => {
730
+ const r = subagent.wave({ engagementDir: opts.engagement });
731
+ if (!r.ok) throw new Error(r.error);
732
+ return r.data;
733
+ },
734
+
735
+ // Phase 29 (LOOP-01): deterministic ADAPTIVE plan candidates — the current
736
+ // engagement state diffed against existing plan coverage (new-host /
737
+ // objective-edge / clientlist-row sources). --emit writes them as
738
+ // plans/PLAN-<next>.md with origin: adaptive and NO approval: the approve
739
+ // gate stays the only path into a wave. Read-only without --emit.
740
+ 'loop.candidates': ({ opts }) => {
741
+ const r = loop.candidates({
742
+ engagementDir: opts.engagement,
743
+ emit: opts.emit === true,
744
+ packsRoot: PACKS_ROOT,
745
+ });
746
+ if (!r.ok) throw new Error(r.error);
747
+ return r.data;
748
+ },
749
+
750
+ // Phase 29 (LOOP-02): the worker-discovery writeback at the wave boundary.
751
+ // Workers record discoveries under their scratch (SPAWN-PROTOCOL rule 6);
752
+ // the ORCHESTRATOR — only — ingests them here: every entry is scope-checked
753
+ // at the DOOR before any write, out-of-scope hosts are refused per-entry
754
+ // (named, recorded nowhere), and a malformed file refuses atomically.
755
+ 'loop.ingest-discoveries': ({ opts }) => {
756
+ const r = loop.ingestDiscoveries(opts.engagement, opts.file);
757
+ if (!r.ok) throw new Error(r.error);
758
+ return r.data;
759
+ },
760
+
761
+ // Phase 30 (LOOP-03): the deterministic goal verifier — a coverage
762
+ // verdict over graph.shortest + the live findings register. `gap` is a
763
+ // VERDICT, not an error (ok:true); the named gaps feed adaptive candidates.
764
+ // Read-only, zero LLM.
765
+ 'goal.verify': ({ opts }) => {
766
+ const r = loop.verifyGoal({ engagementDir: opts.engagement, packsRoot: PACKS_ROOT });
767
+ if (!r.ok) throw new Error(r.error);
768
+ return r.data;
769
+ },
770
+
771
+ init: ({ opts }) => init.initEngagement({ client: opts.client, target: opts.target, methodology: opts.methodology, cwd: opts.cwd }),
772
+
773
+ 'env.render': ({ opts }) => ({ dir: env.renderEnvFiles(opts.engagement) }),
774
+ 'env.up': ({ opts }) => ({ out: env.up(opts.engagement) }),
775
+ 'env.down': ({ opts }) => ({ out: env.down(opts.engagement) }),
776
+ 'env.status': ({ opts }) => {
777
+ const s = env.status(opts.engagement);
778
+ return { out: s.out, warnings: s.warnings };
779
+ },
780
+ 'env.proxy-env': ({ opts }) => env.proxyEnv(opts.engagement),
781
+ 'monitor.scan': ({ opts }) => {
782
+ const egress = findContainer(opts.engagement, 'egress');
783
+ if (!egress) throw new Error('egress not running — env.up first');
784
+ const log = spawnSync('docker', ['exec', egress, 'cat', '/var/log/squid/access.log'], { encoding: 'utf8' }).stdout || '';
785
+ const stats = monitor.scanAccessLog(log);
786
+ const alerts = monitor.detectAlerts(stats);
787
+ if (alerts.length) {
788
+ const file = path.join(paths.envDir(opts.engagement), 'waf-alerts.log');
789
+ fs.mkdirSync(path.dirname(file), { recursive: true });
790
+ fs.appendFileSync(file, alerts.map((a) => `${new Date().toISOString()} [${a.signal}] ${a.detail}`).join('\n') + '\n');
791
+ }
792
+ // ADR-014 crash safety (v0.6 01-02, brief 1.7): warn when a stale
793
+ // provisioning window is left open (marker + dead/no install pid), naming
794
+ // the pre-window allowlist backup for restore.
795
+ const windowWarn = env.windowWarning(opts.engagement);
796
+ return {
797
+ hosts: stats.length,
798
+ requests: stats.reduce((n, s) => n + s.total, 0),
799
+ alerts,
800
+ warnings: windowWarn ? [windowWarn] : [],
801
+ };
802
+ },
803
+
804
+ 'pack.list': () => pack.list(PACKS_ROOT),
805
+ 'pack.load': ({ positional }) => pack.load(PACKS_ROOT, positional[0]),
806
+ 'pack.ingest': ({ positional }) => pack.ingest(PACKS_ROOT, positional[0], positional[1]),
807
+ // 31-02 / SCOP-02: the authoring half — scaffold a COMPLETE, valid-as-is
808
+ // pack skeleton (PACK-FORMAT v1.0 exactly + example checklist rows + a
809
+ // lint-clean runbook stub). Default target is the USER root
810
+ // ($PENSIEVE_HOME/packs/<area>/<name>/); --repo contributes into the repo
811
+ // tree (an EXISTING top-level area, or custom/). Existing-slug and
812
+ // collision refusals pass through RAW (report.pdf convention): the named
813
+ // paths ARE the remedy, and security.sanitizeError would redact both to
814
+ // "[path]".
815
+ 'pack.scaffold': ({ positional, opts }) => {
816
+ if (!positional[0]) throw new Error('pack.scaffold requires <slug> — the area/name shape (e.g. custom/my-checks)');
817
+ try {
818
+ return pack.scaffold(PACKS_ROOT, positional[0], { repo: Boolean(opts.repo) });
819
+ } catch (e) {
820
+ if (e && e.collision) {
821
+ return { ok: false, gate: 'pack-collision', error: e.message, ...e.collision };
822
+ }
823
+ if (e && e.existing) {
824
+ return { ok: false, gate: 'pack-exists', error: e.message, ...e.existing };
825
+ }
826
+ throw e;
827
+ }
828
+ },
829
+ 'pack.enabled': ({ opts }) => pack.enabled(opts.engagement),
830
+ // 31-01 / SCOP-03: a colliding slug is REFUSED ok:false naming BOTH
831
+ // filesystem paths. Raw passthrough envelope (report.pdf convention): the
832
+ // two paths ARE the remedy, and security.sanitizeError would redact both
833
+ // to "[path]" — main() writes this envelope verbatim, exit 1.
834
+ 'pack.enable': ({ opts, positional }) => {
835
+ try {
836
+ return pack.enable(opts.engagement, positional[0], { packsRoot: PACKS_ROOT });
837
+ } catch (e) {
838
+ if (e && e.collision) {
839
+ return { ok: false, gate: 'pack-collision', error: e.message, ...e.collision };
840
+ }
841
+ throw e;
842
+ }
843
+ },
844
+ 'pack.disable': ({ opts, positional }) => pack.disable(opts.engagement, positional[0]),
845
+
846
+ // checklist: pick from a pack's checklist (registry-level: list) and
847
+ // verify a plan's picks against its reference pack (engagement-level:
848
+ // coverage). Mirrors the Wave 3 subagent.list/brief vs record/verify
849
+ // split — list is registry-level; coverage needs a real engagement dir.
850
+ 'checklist.list': ({ opts }) => {
851
+ if (!opts.pack) throw new Error('checklist.list requires --pack <slug>');
852
+ return checklist.list(PACKS_ROOT, {
853
+ slug: opts.pack,
854
+ select: opts.select,
855
+ });
856
+ },
857
+ 'checklist.coverage': ({ opts }) => {
858
+ return checklist.coverage(opts.engagement, {
859
+ packsRoot: PACKS_ROOT,
860
+ planFile: opts['plan-file'],
861
+ pack: opts.pack,
862
+ });
863
+ },
864
+
865
+ // client checklist engine (Phase 19, CHK-01): the client's tracker is the
866
+ // contract. import copies the workbook byte-for-byte into the engagement
867
+ // and freezes scenario hashes; write/list/export operate on the snapshot;
868
+ // export renders an UPDATED COPY writing only verdict/evidence/notes cells
869
+ // (drift-refused, atomic). status lands with plan task 5.
870
+ 'clientlist.import': ({ positional, opts }) => {
871
+ if (positional.length < 1) throw new Error('clientlist.import requires <file.csv|xlsx>');
872
+ const r = clientlist.importWorkbook(opts.engagement, { file: positional[0], slug: opts.slug });
873
+ return r.ok ? (({ ok, ...data }) => data)(r) : r; // miss envelope passes through main()
874
+ },
875
+ 'clientlist.write': ({ opts }) => clientlist.write(opts.engagement, {
876
+ slug: opts.slug,
877
+ id: opts.id,
878
+ tier: opts.tier, // CLI cannot pass null; --tier '' / absent means "not set"
879
+ done: opts.done,
880
+ reason: opts.reason,
881
+ finding_id: opts['finding-id'],
882
+ evidence: opts.evidence,
883
+ notes: opts.notes,
884
+ blocker_note: opts['blocker-note'],
885
+ }),
886
+ 'clientlist.list': ({ opts }) => clientlist.list(opts.engagement, { slug: opts.slug }),
887
+ 'clientlist.export': ({ opts }) => {
888
+ const r = clientlist.exportWorkbook(opts.engagement, { slug: opts.slug, out: opts.out || null });
889
+ return r.ok ? (({ ok, ...data }) => data)(r) : r;
890
+ },
891
+ 'clientlist.status': ({ opts }) => clientlist.status(opts.engagement, { slug: opts.slug }),
892
+
893
+ // ADR-014: JIT provisioning. check = probe toolbox for pack tools;
894
+ // install = apt/pip into the RUNNING toolbox (lane A only), logged.
895
+ 'tools.check': ({ opts }) => {
896
+ const slugs = [].concat(opts.pack || []);
897
+ if (!slugs.length) throw new Error('tools.check needs --pack <slug> (repeatable)');
898
+ const declared = slugs.flatMap((s) => tools.parseTools((pack.load(PACKS_ROOT, s).meta.tools) || []));
899
+ const box = findToolbox(opts.engagement);
900
+ const present = new Set();
901
+ if (box) {
902
+ for (const t of declared) {
903
+ if (t.lane === 'B') continue; // host tools probed on host below
904
+ const r = spawnSync('docker', ['exec', box, 'sh', '-c', `command -v ${t.name}`], { encoding: 'utf8' });
905
+ if (r.status === 0) present.add(t.name);
906
+ }
907
+ for (const t of declared.filter((x) => x.lane === 'B')) {
908
+ const r = spawnSync('sh', ['-c', `command -v ${t.name}`], { encoding: 'utf8' });
909
+ if (r.status === 0) present.add(t.name);
910
+ }
911
+ }
912
+ const plan = tools.planActions(declared, present);
913
+ return { toolbox: box || null, env_up: Boolean(box), plan };
914
+ },
915
+
916
+ 'tools.install': ({ opts }) => {
917
+ if (!opts.tool) throw new Error('tools.install needs --tool <name>');
918
+ const slugs = [].concat(opts.pack || []);
919
+ const declared = slugs.flatMap((s) => tools.parseTools((pack.load(PACKS_ROOT, s).meta.tools) || []));
920
+ const row = declared.find((t) => t.name === opts.tool);
921
+ if (!row) throw new Error(`tool ${opts.tool} not declared by packs: ${slugs.join(', ')}`);
922
+ const [action] = tools.planActions([row], new Set());
923
+ if (action.action !== 'install') return { tool: row.name, action: action.action, instructions: action.instructions || action.note || null };
924
+ const box = findContainer(opts.engagement, 'toolbox');
925
+ if (!box) throw new Error('toolbox not running — env.up first');
926
+ const egress = findContainer(opts.engagement, 'egress');
927
+ const hosts = tools.provisioningHosts(row.kind);
928
+ const [cmd] = tools.installCommands([action]);
929
+
930
+ // PROVISIONING WINDOW (ADR-014 crash safety, v0.6 01-02 / brief 1.7; retargeted
931
+ // by 13-CONTEXT): the toolbox has no route out and the target lane is SCOPE-only.
932
+ // 80/443 live on the SEPARATE provision lane (provision.txt), EMPTY at rest. We
933
+ // WIDEN provision.txt host-side with the pinned package-registry hosts (via the rw
934
+ // bind mount), reconfigure squid to re-read it, install, then empty it again. The
935
+ // target allowlist.txt is never touched. Before widening, openProvisioningWindow
936
+ // records the pre-window state on the HOST — a byte-for-byte provision.txt backup
937
+ // (env/provision.pre-provision.bak) plus a marker (env/provisioning-window.open)
938
+ // naming our pid. If the process crashes mid-window, the marker survives and
939
+ // env.status / monitor.scan warn; a human restores from the backup. On a clean
940
+ // close the marker is removed and provision.txt emptied (backup kept for reference).
941
+ const windowOpened = Boolean(egress) && hosts.length > 0;
942
+ const provisionFile = path.join(paths.envDir(opts.engagement), 'provision.txt');
943
+ if (egress && hosts.length > 0) {
944
+ env.openProvisioningWindow(opts.engagement, hosts); // host-side: widen provision.txt + marker
945
+ } else if (!egress) {
946
+ throw new Error('egress container not found — cannot open a provisioning window');
947
+ }
948
+
949
+ const win = (c) => spawnSync('docker', ['exec', egress, 'sh', '-c', c], { encoding: 'utf8' });
950
+ if (egress && hosts.length) {
951
+ // the host write already went through the rw bind mount; squid just re-reads it.
952
+ const w = win('squid -k reconfigure');
953
+ if (w.status !== 0) {
954
+ try { fs.writeFileSync(provisionFile, ''); } catch { /* best-effort narrow */ }
955
+ win('squid -k reconfigure 2>/dev/null');
956
+ // NOTE: on window-open failure we deliberately do NOT close the host marker —
957
+ // crash-safety (brief 1.7). env.status / monitor.scan keep warning until a
958
+ // human restores (from env/provision.pre-provision.bak or re-running env.render).
959
+ throw new Error(`provisioning window failed to open (squid reconfigure): ${w.stderr?.slice(-200)}`);
960
+ }
961
+ }
962
+ let r;
963
+ try {
964
+ r = spawnSync('docker', ['exec', '-u', '0', box, 'sh', '-c', cmd], { encoding: 'utf8', timeout: 600000 });
965
+ } finally {
966
+ // Narrowing the provision lane ALWAYS runs (clean or crash) so egress is never
967
+ // left wider than at rest. Empty provision.txt host-side (writes through the rw
968
+ // bind mount) and reconfigure. The host marker (if left open) stays the
969
+ // crash-safety warning source — we do NOT remove it here.
970
+ if (egress && hosts.length) {
971
+ try { fs.writeFileSync(provisionFile, ''); } catch { /* best-effort narrow */ }
972
+ win('squid -k reconfigure');
973
+ }
974
+ }
975
+ if (r.status !== 0) {
976
+ // Install failed: the marker stays open (we do NOT call closeProvisioningWindow
977
+ // here) so env.status / monitor.scan keep warning. The finally above already
978
+ // restored the in-container allowlist. (crash-safety, brief 1.7)
979
+ throw new Error(`install failed: ${r.stderr?.slice(-400)}`);
980
+ }
981
+ // Clean close: the window is done. Remove the marker only; the host-side
982
+ // pre-window backup is kept for human reference.
983
+ if (windowOpened) {
984
+ env.closeProvisioningWindow(opts.engagement);
985
+ }
986
+ const log = path.join(paths.envDir(opts.engagement), 'provisioned.log');
987
+ fs.appendFileSync(log, `${new Date().toISOString()} ${row.name} (${row.kind}: ${row.spec}) approved; window=[${hosts.join(',')}]; installed into ${box}\n`);
988
+ const verify = spawnSync('docker', ['exec', box, 'sh', '-c', `command -v ${row.name}`], { encoding: 'utf8' });
989
+ return { tool: row.name, action: 'installed', verified: verify.status === 0, window: hosts, log };
990
+ },
991
+ };
992
+
993
+ // container for an engagement role (compose project = ids.composeProjectName —
994
+ // the SAME derivation env.renderCompose emits, so lookups and up never drift
995
+ // (v0.6 01-02, brief 1.8))
996
+ function findContainer(engagementDir, role) {
997
+ const project = ids.composeProjectName(engagementDir);
998
+ const r = spawnSync('docker', ['ps', '--filter', `name=${project}-${role}`, '--format', '{{.Names}}'], { encoding: 'utf8' });
999
+ const name = (r.stdout || '').split('\n').filter(Boolean)[0];
1000
+ return name || null;
1001
+ }
1002
+ const findToolbox = (dir) => findContainer(dir, 'toolbox');
1003
+
1004
+ function main() {
1005
+ const [cmd, ...rest] = process.argv.slice(2);
1006
+ const respond = (obj) => { process.stdout.write(JSON.stringify(obj) + '\n'); };
1007
+
1008
+ if (!cmd || cmd === 'help' || cmd === '--help') {
1009
+ respond({ ok: true, data: { commands: Object.keys(COMMANDS) } });
1010
+ return;
1011
+ }
1012
+ const handler = COMMANDS[cmd];
1013
+ if (!handler) {
1014
+ respond({ ok: false, error: `unknown command: ${cmd}` });
1015
+ process.exitCode = 1;
1016
+ return;
1017
+ }
1018
+ try {
1019
+ const args = parseArgs(rest);
1020
+ refuseUnknownFlags(cmd, args.opts); // fail-closed BEFORE any state is touched
1021
+ if (ENGAGEMENT_COMMANDS.has(cmd)) requireEngagement(args.opts);
1022
+ const result = handler(args);
1023
+ // report.pdf returns its own {ok:false, gate, error, instructions}
1024
+ // envelope on refusal — passed through verbatim so the lane-B setup
1025
+ // instructions survive unsanitized (paths intact, not truncated).
1026
+ if (result && result.ok === false && result.gate) {
1027
+ respond(result);
1028
+ process.exitCode = 1;
1029
+ return;
1030
+ }
1031
+ // raw-text passthrough (SKILL-01): handlers returning {format:'text'} write
1032
+ // their verbatim data (possibly the empty string) directly, so a spawn prompt
1033
+ // can embed $(pensieve-sdk agent-skills …) raw — no JSON envelope.
1034
+ if (result && result.format === 'text') {
1035
+ process.stdout.write(String(result.data ?? '') + '\n');
1036
+ return;
1037
+ }
1038
+ respond({ ok: true, data: result ?? null });
1039
+ } catch (e) {
1040
+ respond({ ok: false, error: security.sanitizeError(e) });
1041
+ process.exitCode = 1;
1042
+ }
1043
+ }
1044
+
1045
+ main();