@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,619 @@
1
+ 'use strict';
2
+ /**
3
+ * loop.cjs — the adaptive half of the wave loop (Phase 29, LOOP-01).
4
+ *
5
+ * `loop.candidates --engagement <dir> [--emit] [--json]` deterministically
6
+ * diffs the CURRENT engagement state against existing plans and derives
7
+ * ADAPTIVE plan candidates. It is a pure derivation over state that other
8
+ * modules own — every input is read through the existing accessors, never
9
+ * re-parsed ad hoc:
10
+ *
11
+ * enabled packs pack.enabled(dir) (config.yaml)
12
+ * methodology config.load(dir).cfg (scope-applicability)
13
+ * scope scope.parse / scope.check (the GRAPH-06 in-scope gate)
14
+ * recorded hosts recon.readSurface(dir) (recon.add-host state)
15
+ * objective path graph.shortest(dir) (ADR-025 foothold→objective)
16
+ * clientlist rows clientlist.list per slug (Phase 19 snapshots)
17
+ * existing plans approvals.planIds + fm.parse (the checklist.cjs
18
+ * convention: frontmatter `checklist:` IS the
19
+ * source of truth for coverage — approved or not)
20
+ *
21
+ * Candidate sources, all deterministic:
22
+ *
23
+ * (a) new-host — items of enabled, scope-applicable packs
24
+ * (pack.yaml `applies_to` ∋ the engagement
25
+ * methodology; a pack with no applies_to is
26
+ * methodology-agnostic) that are uncovered by ANY
27
+ * existing plan and newly enabled by in-scope hosts
28
+ * recorded in recon state. The rationale names the
29
+ * first (sorted) in-scope host.
30
+ * (b) objective-edge — unpursued edges on the graph.shortest
31
+ * foothold→objective path: an edge is covered when
32
+ * some existing plan cites an item that tests the
33
+ * edge's CWE; uncovered edges map to their covering
34
+ * checklist items (items whose id/title/tests cite
35
+ * that CWE). An edge with no covering item produces
36
+ * NO candidate (nothing citable — LOOP-03's named-gap
37
+ * reporting is the surface for that).
38
+ * (c) clientlist-row — clientlist rows not covered by any existing plan
39
+ * and now derivable as testable: no verdict tier yet
40
+ * AND no open blocker note.
41
+ *
42
+ * --emit writes each candidate as plans/PLAN-<next>.md with frontmatter
43
+ * `origin: adaptive` and NO approval — unapproved by construction. The human
44
+ * (or orchestrator `approve`) gate is the ONLY path into a wave:
45
+ * subagent.wave reads approvals.approvedPlans, so emitting candidates never
46
+ * changes what runs (structure-tested in loop-candidates.test.cjs).
47
+ *
48
+ * Deterministic: sorted inputs, sorted output, sequential next plan ids, no
49
+ * timestamps — the same engagement state always yields the same candidates.
50
+ * Read-only without --emit. Fails CLOSED on a missing/invalid engagement.
51
+ */
52
+ const fs = require('node:fs');
53
+ const path = require('node:path');
54
+
55
+ const fm = require('./frontmatter.cjs');
56
+ const paths = require('./paths.cjs');
57
+ const config = require('./config.cjs');
58
+ const packLib = require('./pack.cjs');
59
+ const scope = require('./scope.cjs');
60
+ const recon = require('./recon.cjs');
61
+ const graph = require('./graph.cjs');
62
+ const state = require('./state.cjs');
63
+ const approvals = require('./approvals.cjs');
64
+ const clientlist = require('./clientlist.cjs');
65
+ const findings = require('./findings.cjs');
66
+
67
+ const SOURCE_RANK = { 'new-host': 0, 'objective-edge': 1, 'clientlist-row': 2 };
68
+
69
+ // Phase 29 (LOOP-02): the worker-discovery ingest — the writeback door at the
70
+ // wave boundary. Workers record discoveries in their scratch and RETURN the
71
+ // file path (SPAWN-PROTOCOL rule 6); the orchestrator — only — ingests it
72
+ // here, BEFORE loop.candidates, so newly recorded in-scope hosts feed the
73
+ // derivation.
74
+ //
75
+ // DOOR-LEVEL refusal: recon.recordHost validates FORMAT (empty host, unsafe
76
+ // chars, ports) but not scope — the scope gate lives at consumption
77
+ // (graph.build / loop.candidates filter). Worker discoveries enter through
78
+ // THIS door instead: every entry is scope-checked (scope.parse +
79
+ // scope.check verdict allow) BEFORE any write. In-scope entries are recorded
80
+ // via the existing recon.recordHost (semantics untouched); out-of-scope
81
+ // entries are REFUSED per-entry — the host is named in the result, recorded
82
+ // NOWHERE, never silently dropped. Two fail-closed layers:
83
+ // ATOMIC — malformed file / non-array / invalid entry shape → ok:false,
84
+ // NOTHING recorded (validation of EVERY entry precedes ANY
85
+ // write; a bad first entry stops the in-scope second one too);
86
+ // per-entry — a mixed file reports [{host, accepted|refused, reason}].
87
+ //
88
+ // The evidence hash chain is not involved (ingest never touches evidence/);
89
+ // recordHost itself becoming scope-refusing is logged as candidate
90
+ // hardening in the plan SUMMARY (design observation, deliberately NOT
91
+ // changed here).
92
+
93
+ /** the discovery-entry keys (schema: {host, port?, source?}) */
94
+ const DISCOVERY_KEYS = ['host', 'port', 'source'];
95
+
96
+ // recon.cjs's markdown-injection guard (T-06-02), mirrored here so a crafted
97
+ // host is refused at the DOOR (shape validation, atomically) instead of
98
+ // throwing out of recordHost mid-write.
99
+ const UNSAFE_HOST_CHARS = /[|\r\n\[\]<>`]/;
100
+
101
+ /** one entry's shape validation; returns an error detail string or null */
102
+ function discoveryEntryError(entry) {
103
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
104
+ return 'entry must be an object';
105
+ }
106
+ for (const k of Object.keys(entry)) {
107
+ if (!DISCOVERY_KEYS.includes(k)) {
108
+ return `unknown key "${k}" (allowed: ${DISCOVERY_KEYS.join(', ')})`;
109
+ }
110
+ }
111
+ if (typeof entry.host !== 'string' || entry.host.trim() === '') {
112
+ return 'host must be a non-empty string';
113
+ }
114
+ const normHost = scope.extractHost(entry.host);
115
+ if (!normHost) return 'host is required (nothing recognizable after normalization)';
116
+ if (UNSAFE_HOST_CHARS.test(normHost)) {
117
+ return `host has unsafe markdown/control chars: ${JSON.stringify(normHost)}`;
118
+ }
119
+ if (entry.port !== undefined) {
120
+ const p = Number(entry.port);
121
+ if (!Number.isInteger(p) || p < 1 || p > 65535) {
122
+ return `port must be an integer 1..65535 (got ${JSON.stringify(entry.port)})`;
123
+ }
124
+ }
125
+ if (entry.source !== undefined && typeof entry.source !== 'string') {
126
+ return 'source must be a string (plan/worker provenance)';
127
+ }
128
+ return null;
129
+ }
130
+
131
+ /**
132
+ * ingestDiscoveries — scope-validated serial ingest of a worker discovery
133
+ * file (a JSON array of {host, port?, source?}). Returns the
134
+ * { ok, error, data } envelope; data on success:
135
+ * { engagement, file, results: [{host, status: 'accepted'|'refused',
136
+ * reason}], counts: { accepted, refused } }
137
+ * Fails CLOSED (ok:false, nothing recorded) on a missing/invalid engagement,
138
+ * a missing/unreadable file, non-JSON, a non-array, or ANY invalid entry
139
+ * shape — atomically, before the first write.
140
+ */
141
+ function ingestDiscoveries(engagementDir, filePath) {
142
+ if (!engagementDir || String(engagementDir).trim() === '') {
143
+ return { ok: false, error: 'loop.ingest-discoveries requires an engagement dir', data: null };
144
+ }
145
+ const abs = path.resolve(String(engagementDir).trim());
146
+ if (!state.isEngagement(abs)) {
147
+ return {
148
+ ok: false,
149
+ error: 'engagement not found (no STATE.md with status frontmatter) at the given path',
150
+ data: null,
151
+ };
152
+ }
153
+ if (!filePath || String(filePath).trim() === '') {
154
+ return {
155
+ ok: false,
156
+ error: 'loop.ingest-discoveries requires a discovery file path (--file <path>)',
157
+ data: null,
158
+ };
159
+ }
160
+ const file = path.resolve(String(filePath).trim());
161
+
162
+ let text;
163
+ try {
164
+ text = fs.readFileSync(file, 'utf8');
165
+ } catch {
166
+ return { ok: false, error: `discovery file not found or unreadable: ${file}`, data: null };
167
+ }
168
+ let parsed;
169
+ try {
170
+ parsed = JSON.parse(text);
171
+ } catch (e) {
172
+ return { ok: false, error: `discovery file is not valid JSON: ${e.message}`, data: null };
173
+ }
174
+ if (!Array.isArray(parsed)) {
175
+ return {
176
+ ok: false,
177
+ error: `discovery file must be a JSON array of {host, port?, source?} entries — got ${parsed === null ? 'null' : typeof parsed}`,
178
+ data: null,
179
+ };
180
+ }
181
+
182
+ // ATOMIC: validate EVERY entry's shape BEFORE any write — one bad entry
183
+ // refuses the whole file, in-scope siblings included.
184
+ for (let i = 0; i < parsed.length; i++) {
185
+ const detail = discoveryEntryError(parsed[i]);
186
+ if (detail) {
187
+ return { ok: false, error: `invalid discovery entry at index ${i}: ${detail}`, data: null };
188
+ }
189
+ }
190
+
191
+ // The scope AST: unreadable/absent scope -> empty AST -> scope.check
192
+ // default-denies EVERYTHING (door-level; nothing sneaks in without scope).
193
+ const scopeAst = (() => {
194
+ try {
195
+ return scope.parse(fs.readFileSync(paths.scopeFile(abs), 'utf8'));
196
+ } catch {
197
+ return { assets: [], outOfScope: [] };
198
+ }
199
+ })();
200
+
201
+ const results = [];
202
+ const counts = { accepted: 0, refused: 0 };
203
+ for (const entry of parsed) {
204
+ const normHost = scope.extractHost(entry.host);
205
+ const verdict = scope.check(scopeAst, normHost);
206
+ if (verdict.verdict === 'allow') {
207
+ try {
208
+ recon.recordHost(abs, {
209
+ host: normHost,
210
+ services: entry.port !== undefined ? [{ port: Number(entry.port) }] : [],
211
+ });
212
+ counts.accepted += 1;
213
+ results.push({ host: normHost, status: 'accepted', reason: verdict.reason });
214
+ } catch (e) {
215
+ // door-level belt-and-braces: a recordHost refusal (format-level)
216
+ // records NOTHING for this entry and is surfaced, never swallowed.
217
+ counts.refused += 1;
218
+ results.push({ host: normHost, status: 'refused', reason: `record refused: ${e.message}` });
219
+ }
220
+ } else {
221
+ counts.refused += 1;
222
+ results.push({ host: normHost, status: 'refused', reason: verdict.reason });
223
+ }
224
+ }
225
+ return { ok: true, error: null, data: { engagement: abs, file, results, counts } };
226
+ }
227
+
228
+ /** codepoint sort — stable across locales/node versions (no localeCompare) */
229
+ function byCodepoint(a, b) {
230
+ return a < b ? -1 : a > b ? 1 : 0;
231
+ }
232
+
233
+ /** checklist.cjs normalizeIds semantics: string | "a,b" | [..] -> trimmed ids */
234
+ function normalizeIds(v) {
235
+ if (v === undefined || v === null) return [];
236
+ const arr = Array.isArray(v) ? v : String(v).split(',');
237
+ return arr.map((s) => String(s).trim()).filter(Boolean);
238
+ }
239
+
240
+ /**
241
+ * nextPlanId — the id the NEXT emitted plan takes, given the sorted existing
242
+ * ids. Numeric ids advance max+1 zero-padded to >= 3 (the SWARM-01 '001'
243
+ * convention); a plans/ dir with no numeric ids starts at '001'.
244
+ */
245
+ function nextPlanId(ids) {
246
+ let max = 0;
247
+ for (const id of ids) {
248
+ const m = /^(\d+)$/.exec(id);
249
+ if (m) max = Math.max(max, parseInt(m[1], 10));
250
+ }
251
+ return String(max + 1).padStart(3, '0');
252
+ }
253
+
254
+ /** every checklist id cited by ANY existing plan (approved or not) */
255
+ function citedIds(engagementDir) {
256
+ const out = new Set();
257
+ for (const id of approvals.planIds(engagementDir)) {
258
+ let data = {};
259
+ try {
260
+ data = fm.parse(fs.readFileSync(path.join(paths.plansDir(engagementDir), `PLAN-${id}.md`), 'utf8')).data || {};
261
+ } catch {
262
+ continue; // unreadable plan: contributes no cites (fail-closed, like coverage)
263
+ }
264
+ for (const cid of normalizeIds(data.checklist)) out.add(cid);
265
+ }
266
+ return out;
267
+ }
268
+
269
+ /** enabled packs that are scope-applicable: applies_to missing (agnostic) or ∋ methodology */
270
+ function applicablePacks(engagementDir, packsRoot) {
271
+ const { cfg } = config.load(engagementDir);
272
+ const methodology = String(cfg.methodology || '').trim().toLowerCase();
273
+ const out = [];
274
+ const warnings = [];
275
+ for (const slug of packLib.enabled(engagementDir)) {
276
+ let p;
277
+ try {
278
+ p = packLib.load(packsRoot, slug);
279
+ } catch (e) {
280
+ warnings.push(`enabled pack not loadable: ${slug} (${e.message})`);
281
+ continue;
282
+ }
283
+ const applies = (p.meta && Array.isArray(p.meta.applies_to) ? p.meta.applies_to : null);
284
+ if (applies && !applies.some((a) => String(a).trim().toLowerCase() === methodology)) continue;
285
+ out.push({ slug, items: p.checklist || [] });
286
+ }
287
+ return { packs: out, warnings };
288
+ }
289
+
290
+ /** searchable text of one checklist item (the CWE-cite surface for edges) */
291
+ function itemText(item) {
292
+ return [item.id, item.title, ...(item.tests || [])].join(' ');
293
+ }
294
+
295
+ /** the digits of a CWE reference ('CWE-548' | '548' -> '548'; null when absent) */
296
+ function cweDigits(cwe) {
297
+ if (cwe == null) return null;
298
+ const m = /(\d+)/.exec(String(cwe));
299
+ return m ? m[1] : null;
300
+ }
301
+
302
+ /**
303
+ * The GATE-INVARIANT derivation. Returns the { ok, error, data } envelope.
304
+ * data: { engagement, candidates[], counts{}, emitted[], warnings[] } where
305
+ * each candidate is { source, plan, pack, items[], rationale{ source, ... } }.
306
+ */
307
+ function candidates({ engagementDir, emit = false, packsRoot } = {}) {
308
+ if (!engagementDir || String(engagementDir).trim() === '') {
309
+ return { ok: false, error: 'loop.candidates requires an engagement dir', data: null };
310
+ }
311
+ const abs = path.resolve(String(engagementDir).trim());
312
+ if (!state.isEngagement(abs)) {
313
+ return {
314
+ ok: false,
315
+ error: 'engagement not found (no STATE.md with status frontmatter) at the given path',
316
+ data: null,
317
+ };
318
+ }
319
+ const packsRootAbs = packsRoot
320
+ ? path.resolve(packsRoot)
321
+ : (process.env.PENSIEVE_PACKS_DIR || path.resolve(__dirname, '../../../packs'));
322
+
323
+ const warnings = [];
324
+ const covered = citedIds(abs);
325
+ const { packs, warnings: packWarnings } = applicablePacks(abs, packsRootAbs);
326
+ warnings.push(...packWarnings);
327
+
328
+ // every item of every applicable pack, deduped by id (first pack wins)
329
+ const allItems = new Map(); // id -> { item, pack }
330
+ for (const p of packs) {
331
+ for (const item of p.items) {
332
+ if (!allItems.has(item.id)) allItems.set(item.id, { item, pack: p.slug });
333
+ }
334
+ }
335
+
336
+ const out = [];
337
+
338
+ // ---- (a) new-host: in-scope recorded hosts enable uncovered items ----
339
+ const scopeAst = (() => {
340
+ try {
341
+ return scope.parse(fs.readFileSync(paths.scopeFile(abs), 'utf8'));
342
+ } catch {
343
+ return { assets: [], outOfScope: [] };
344
+ }
345
+ })();
346
+ const inScopeHosts = recon
347
+ .readSurface(abs)
348
+ .hosts
349
+ .map((h) => (h && h.host ? scope.extractHost(h.host) : ''))
350
+ .filter(Boolean)
351
+ .filter((host) => scope.check(scopeAst, host).verdict === 'allow')
352
+ .sort(byCodepoint);
353
+ const claimedItems = new Set();
354
+ if (inScopeHosts.length > 0) {
355
+ const enablingHost = inScopeHosts[0];
356
+ for (const id of [...allItems.keys()].sort(byCodepoint)) {
357
+ if (covered.has(id)) continue;
358
+ claimedItems.add(id);
359
+ out.push({
360
+ source: 'new-host',
361
+ pack: allItems.get(id).pack,
362
+ items: [id],
363
+ rationale: { source: 'new-host', host: enablingHost },
364
+ });
365
+ }
366
+ }
367
+
368
+ // ---- (b) objective-edge: unpursued edges on the shortest path ----
369
+ // graph.shortest's `hops` are the FULL path edges (cwe/attackStep included);
370
+ // its `edges` projection strips cwe, so hops is the edge output reused here.
371
+ const shortest = graph.shortest(abs);
372
+ if (shortest && shortest.ok && Array.isArray(shortest.hops)) {
373
+ for (const edge of shortest.hops) {
374
+ const digits = cweDigits(edge.cwe);
375
+ if (!digits) continue;
376
+ const re = new RegExp(`cwe[-\\s]?${digits}\\b`, 'i');
377
+ const covering = [...allItems.keys()]
378
+ .filter((id) => re.test(itemText(allItems.get(id).item)))
379
+ .sort(byCodepoint);
380
+ if (covering.length === 0) continue; // unmapped edge: no citable item, no candidate
381
+ const edgeCovered = covering.some((id) => covered.has(id));
382
+ if (edgeCovered) continue; // an existing plan already pursues this edge
383
+ for (const id of covering) {
384
+ if (claimedItems.has(id)) continue; // already a (higher-priority) new-host candidate
385
+ claimedItems.add(id);
386
+ out.push({
387
+ source: 'objective-edge',
388
+ pack: allItems.get(id).pack,
389
+ items: [id],
390
+ rationale: {
391
+ source: 'objective-edge',
392
+ edge: `${edge.from}->${edge.to}`,
393
+ from: edge.from,
394
+ to: edge.to,
395
+ cwe: edge.cwe || null,
396
+ },
397
+ });
398
+ }
399
+ }
400
+ }
401
+
402
+ // ---- (c) clientlist-row: uncovered, verdict-less, blocker-less rows ----
403
+ const clDir = path.join(abs, 'clientlist');
404
+ if (fs.existsSync(clDir)) {
405
+ for (const f of fs.readdirSync(clDir).filter((x) => x.endsWith('.json')).sort(byCodepoint)) {
406
+ const slug = f.replace(/\.json$/, '');
407
+ let listed;
408
+ try {
409
+ listed = clientlist.list(abs, { slug });
410
+ } catch {
411
+ continue; // unreadable snapshot contributes no rows (fail-closed)
412
+ }
413
+ for (const row of listed.rows || []) {
414
+ if (covered.has(row.id)) continue; // covered by any existing plan cite
415
+ if (row.verdict) continue; // already answered — nothing left to test
416
+ if (row.blocker_note) continue; // open blocker: not testable yet
417
+ out.push({
418
+ source: 'clientlist-row',
419
+ pack: null,
420
+ items: [row.id],
421
+ rationale: { source: 'clientlist-row', row: row.id, slug },
422
+ });
423
+ }
424
+ }
425
+ }
426
+
427
+ // ---- deterministic order: source rank, then item id; then plan ids ----
428
+ out.sort((a, b) => {
429
+ const r = SOURCE_RANK[a.source] - SOURCE_RANK[b.source];
430
+ if (r !== 0) return r;
431
+ return byCodepoint(a.items[0], b.items[0]);
432
+ });
433
+
434
+ const ids = approvals.planIds(abs);
435
+ let seq = parseInt(nextPlanId(ids), 10);
436
+ for (const c of out) {
437
+ c.plan = `PLAN-${String(seq).padStart(3, '0')}`;
438
+ seq += 1;
439
+ }
440
+
441
+ const counts = { 'new-host': 0, 'objective-edge': 0, 'clientlist-row': 0 };
442
+ for (const c of out) counts[c.source] += 1;
443
+
444
+ // ---- --emit: write each candidate as an UNAPPROVED adaptive plan ----
445
+ const emitted = [];
446
+ if (emit) {
447
+ for (const c of out) {
448
+ const id = c.plan.replace(/^PLAN-/, '');
449
+ const file = path.join(paths.plansDir(abs), `PLAN-${id}.md`);
450
+ if (fs.existsSync(file)) continue; // never overwrite (id collision = skip)
451
+ fs.writeFileSync(file, renderPlan(c, allItems), 'utf8');
452
+ emitted.push(id);
453
+ }
454
+ }
455
+
456
+ return {
457
+ ok: true,
458
+ error: null,
459
+ data: {
460
+ engagement: abs,
461
+ candidates: out.map(({ source, plan, pack, items, rationale }) => ({ source, plan, pack, items, rationale })),
462
+ counts,
463
+ emitted,
464
+ warnings,
465
+ },
466
+ };
467
+ }
468
+
469
+ // ---- Phase 30 (LOOP-03): the deterministic goal verifier ----
470
+ //
471
+ // `goal.verify --engagement <dir> [--json]` closes the loop on evidence: the
472
+ // objective's reachability is judged against VALIDATED findings only, and
473
+ // untested legs become named gaps feeding the same adaptive candidates. It
474
+ // is a thin deterministic verdict over graph.shortest + the findings
475
+ // register — zero LLM, zero writes:
476
+ //
477
+ // path graph.shortest(abs) — the shortest foothold→objective path,
478
+ // hops first (the FULL edges: cwe included; the .edges projection
479
+ // strips cwe). loadGraph reuses a persisted surface/graph.json
480
+ // when present, else computes — the lab's v0.8 empty-path guard
481
+ // (4a676dd) is the seed of this check.
482
+ // coverage the LIVE register via findings.gate().validated — the passing
483
+ // set is findings.cjs PASSING_STATUSES (validated and beyond)
484
+ // read through its accessor, never redefined here. An edge is
485
+ // COVERED when a cited confirming finding (hop.sources
486
+ // `finding/<id>`) is in that set — so a leg claimed by a DRAFT
487
+ // finding, or suspended for retest (retest_pending), is a gap.
488
+ // verdict clean — objective unreachable (per the owner-approved brief an
489
+ // unreachable objective is NOT a gap) or the shortest path fully
490
+ // covered; gap — reachable while no fully-covered path exists.
491
+ // Gaps name the exact uncovered edges (from/to/cwe) and the
492
+ // covering plan candidates — the 29-01 objective-edge mapping
493
+ // (items whose id/title/tests cite the edge's CWE; an edge with
494
+ // no covering item is still a named gap, candidates: []).
495
+ //
496
+ // Deterministic: path order (Dijkstra), codepoint-sorted cited findings and
497
+ // candidates, no timestamps. Fail-closed: ok:false on missing/invalid
498
+ // engagement, graph.shortest's refusal reused verbatim (missing objective),
499
+ // and an unparsable surface/graph.json (shortest throws -> caught here).
500
+ function verifyGoal({ engagementDir, packsRoot } = {}) {
501
+ if (!engagementDir || String(engagementDir).trim() === '') {
502
+ return { ok: false, error: 'goal.verify requires an engagement dir', data: null };
503
+ }
504
+ const abs = path.resolve(String(engagementDir).trim());
505
+ if (!state.isEngagement(abs)) {
506
+ return {
507
+ ok: false,
508
+ error: 'engagement not found (no STATE.md with status frontmatter) at the given path',
509
+ data: null,
510
+ };
511
+ }
512
+ const packsRootAbs = packsRoot
513
+ ? path.resolve(packsRoot)
514
+ : (process.env.PENSIEVE_PACKS_DIR || path.resolve(__dirname, '../../../packs'));
515
+
516
+ let shortest;
517
+ try {
518
+ shortest = graph.shortest(abs);
519
+ } catch (e) {
520
+ return { ok: false, error: `broken engagement graph: ${e.message}`, data: null };
521
+ }
522
+ if (!shortest.ok && shortest.error !== 'no path to objective') {
523
+ // missing/unmatched objective — graph.shortest's own refusal, reused.
524
+ return { ok: false, error: shortest.error, data: null };
525
+ }
526
+
527
+ // the passing set: findings.cjs PASSING_STATUSES via its accessor
528
+ // (gate().validated) — the live register decides, not graph build time.
529
+ const passing = new Set(findings.gate(abs).validated);
530
+
531
+ // covering items for a gap: the 29-01 objective-edge mapping (same packs,
532
+ // same item text surface, same CWE regex). Only loaded when a path exists.
533
+ const warnings = [];
534
+ let allItems = new Map(); // id -> { item, pack }
535
+ if (shortest.ok) {
536
+ const { packs, warnings: packWarnings } = applicablePacks(abs, packsRootAbs);
537
+ warnings.push(...packWarnings);
538
+ for (const p of packs) {
539
+ for (const item of p.items) {
540
+ if (!allItems.has(item.id)) allItems.set(item.id, { item, pack: p.slug });
541
+ }
542
+ }
543
+ }
544
+
545
+ const edges = [];
546
+ for (const hop of shortest.ok ? shortest.hops : []) {
547
+ const cited = [...new Set((hop.sources || [])
548
+ .filter((s) => String(s).startsWith('finding/'))
549
+ .map((s) => String(s).slice('finding/'.length)))]
550
+ .sort(byCodepoint);
551
+ const covered = cited.some((id) => passing.has(id));
552
+ let candidates = [];
553
+ if (!covered) {
554
+ const digits = cweDigits(hop.cwe);
555
+ if (digits) {
556
+ const re = new RegExp(`cwe[-\\s]?${digits}\\b`, 'i');
557
+ candidates = [...allItems.keys()]
558
+ .filter((id) => re.test(itemText(allItems.get(id).item)))
559
+ .sort(byCodepoint)
560
+ .map((id) => ({ item: id, pack: allItems.get(id).pack }));
561
+ }
562
+ }
563
+ edges.push({ from: hop.from, to: hop.to, cwe: hop.cwe || null, covered, findings: cited, candidates });
564
+ }
565
+ const gaps = edges.filter((e) => !e.covered);
566
+
567
+ const g = shortest.ok ? null : graph.readGraph(abs);
568
+ return {
569
+ ok: true,
570
+ error: null,
571
+ data: {
572
+ engagement: abs,
573
+ objective: shortest.ok ? shortest.objective : (g && g.objective) || null,
574
+ verdict: gaps.length > 0 ? 'gap' : 'clean',
575
+ reason: !shortest.ok ? 'objective-unreachable' : (gaps.length > 0 ? 'uncovered-edges' : 'path-covered'),
576
+ path: shortest.ok ? shortest.path : null,
577
+ edges,
578
+ gaps,
579
+ warnings,
580
+ },
581
+ };
582
+ }
583
+
584
+ /** the emitted plan file: origin adaptive, NO approval, per-item cite. */
585
+ function renderPlan(c, allItems) {
586
+ const info = allItems.get(c.items[0]);
587
+ const title = info ? info.item.title : null;
588
+ const lines = [
589
+ '## Objective',
590
+ '',
591
+ 'Adaptive follow-up plan (origin: adaptive) — derived by `pensieve-sdk',
592
+ 'loop.candidates` from the CURRENT engagement state, NOT the initial plan set.',
593
+ '',
594
+ `- Source: ${c.source}`,
595
+ c.rationale.host ? `- Enabling host: ${c.rationale.host}` : null,
596
+ c.rationale.edge ? `- Unpursued objective-path edge: ${c.rationale.edge} (${c.rationale.cwe || 'CWE n/a'})` : null,
597
+ c.rationale.row ? `- Client checklist row: ${c.rationale.row} (snapshot ${c.rationale.slug})` : null,
598
+ `- Pack item: ${c.items[0]}${title ? ` — ${title}` : ''}`,
599
+ c.pack ? `- Pack: ${c.pack}` : null,
600
+ '',
601
+ '## Status',
602
+ '',
603
+ 'UNAPPROVED by construction. This plan requires the human/orchestrator approve',
604
+ 'gate (`pensieve-sdk approve --engagement <dir> --artifact plan:<id>`) before it',
605
+ 'can EVER run — `subagent.wave` only takes approved plans.',
606
+ ].filter((l) => l !== null);
607
+ return fm.stringify(
608
+ {
609
+ id: c.plan,
610
+ ...(c.pack ? { pack: c.pack } : {}),
611
+ origin: 'adaptive',
612
+ checklist: c.items.slice(),
613
+ rationale: `${c.source} ${c.rationale.host || c.rationale.edge || c.rationale.row || ''}`.trim(),
614
+ },
615
+ '\n' + lines.join('\n') + '\n'
616
+ );
617
+ }
618
+
619
+ module.exports = { candidates, nextPlanId, ingestDiscoveries, verifyGoal };
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+ /**
3
+ * migrate.cjs — flatten a legacy .pentest/ engagement in place (v0.6 01-01).
4
+ *
5
+ * Pre-01-01 engagements keep every engagement file under <root>/.pentest/.
6
+ * migrate moves ALL of .pentest's contents up to the engagement root and
7
+ * removes the empty .pentest dir. Safety rules:
8
+ * - collision refusal: if ANY top-level name inside .pentest/ already
9
+ * exists at the root, NOTHING is moved and the error lists every
10
+ * colliding name (the human resolves, then re-runs).
11
+ * - idempotent: a flat engagement (STATE.md with status frontmatter, no
12
+ * .pentest) reports already_flat and changes nothing.
13
+ * - the registry needs no update: it stores the engagement root path,
14
+ * which does not change.
15
+ */
16
+
17
+ const fs = require('node:fs');
18
+ const path = require('node:path');
19
+ const state = require('./state.cjs');
20
+
21
+ function migrate(engagementDir) {
22
+ if (!engagementDir) throw new Error('migrate requires --engagement <dir>');
23
+ const root = path.resolve(engagementDir);
24
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
25
+ throw new Error(`engagement dir not found: ${root}`);
26
+ }
27
+ const legacy = path.join(root, '.pentest');
28
+
29
+ if (!fs.existsSync(legacy)) {
30
+ if (state.isEngagement(root)) {
31
+ return { migrated: false, already_flat: true, moved: [] };
32
+ }
33
+ throw new Error('not an engagement: no .pentest directory and no STATE.md status marker at the given path');
34
+ }
35
+ if (!fs.statSync(legacy).isDirectory()) {
36
+ throw new Error('found .pentest but it is not a directory — refusing to migrate');
37
+ }
38
+
39
+ const entries = fs.readdirSync(legacy);
40
+ const collisions = entries.filter((name) => fs.existsSync(path.join(root, name)));
41
+ if (collisions.length) {
42
+ throw new Error(
43
+ `migrate refused — ${collisions.length} name collision(s) between .pentest/ and the engagement root: `
44
+ + collisions.join(', ') + '. Resolve them (rename/remove the root copies), then re-run.'
45
+ );
46
+ }
47
+
48
+ const moved = [];
49
+ for (const name of entries) {
50
+ fs.renameSync(path.join(legacy, name), path.join(root, name));
51
+ moved.push(name);
52
+ }
53
+ fs.rmdirSync(legacy); // empty by construction at this point
54
+ return { migrated: true, already_flat: false, moved };
55
+ }
56
+
57
+ module.exports = { migrate };