@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,658 @@
1
+ 'use strict';
2
+ /**
3
+ * subagent.cjs — deterministic subagent orchestration (Wave 3, GSD
4
+ * v1.43.0-rc2 sub-agent contracts).
5
+ *
6
+ * The orchestrator (an agent) delegates work to the nine `agents/pensieve-*.md`
7
+ * sub-agents. This library is the *deterministic bridge* the SDK exposes; it
8
+ * does NOT execute the agents (that is the Hermes orchestrator's job — it
9
+ * spawns them and collects their output). It provides:
10
+ *
11
+ * - list() : registry of the agent contracts (repo agents/ dir)
12
+ * - brief() : composed delegation brief for one agent + unit
13
+ * - record() : durable receipt under runs/delegations/<runId> (self-report)
14
+ * - verify() : independent gate — declared artifact paths MUST exist;
15
+ * self-reports are NOT evidence (mirrors report.verify)
16
+ *
17
+ * Design mirrors approvals.cjs: deterministic, idempotent, durable records,
18
+ * and gated verification.
19
+ */
20
+ const fs = require('node:fs');
21
+ const path = require('node:path');
22
+ const skills = require('./skills.cjs');
23
+ const approvals = require('./approvals.cjs');
24
+ const config = require('./config.cjs');
25
+ const paths = require('./paths.cjs');
26
+ const state = require('./state.cjs');
27
+ const fm = require('./frontmatter.cjs');
28
+
29
+ const AGENTS_DIR = path.resolve(__dirname, '../../../agents');
30
+
31
+ // GSD contract alias: `roes-checker` (extra 's') is a long-standing alias.
32
+ const AGENT_ALIASES = Object.freeze({
33
+ 'roes-checker': 'roe-checker',
34
+ });
35
+
36
+ // Delegation map: subagent -> engagement command (agents/README.md / orchestrator-core.md).
37
+ const DELEGATION_COMMANDS = Object.freeze({
38
+ 'scoper': 'new-engagement',
39
+ 'reconner': 'recon',
40
+ 'mapper': 'map',
41
+ 'planner': 'plan',
42
+ 'tester': 'test',
43
+ 'validator': 'validate',
44
+ 'code-auditor': 'audit',
45
+ 'reporter': 'report',
46
+ 'roe-checker': 'roe',
47
+ });
48
+
49
+ /* ---------------------------------------------------------------------------
50
+ * Agent contract parsing
51
+ * --------------------------------------------------------------------------- */
52
+
53
+ // Frontmatter single-value getter (description, model_tier).
54
+ function fmValue(content, label) {
55
+ const m = content.match(new RegExp('^' + label + '\\s*:\\s*(.+)$', 'm'));
56
+ return m ? m[1].trim() : '';
57
+ }
58
+
59
+ // Frontmatter `tools: [...]` or `tools: a, b`.
60
+ function parseTools(content) {
61
+ const m = content.match(/^tools:\s*(.+)$/m);
62
+ if (!m) return [];
63
+ const raw = m[1].trim().replace(/^\[/, '').replace(/\]$/, '').trim();
64
+ return raw ? raw.split(',').map((t) => t.trim()).filter(Boolean) : [];
65
+ }
66
+
67
+ // The section that declares output: "## Output contract" (most agents) or
68
+ // "# OUTPUT" (pensieve-code-auditor). Returns the lines between that heading and
69
+ // the next heading.
70
+ function outputSectionLines(content) {
71
+ const lines = content.split('\n');
72
+ let start = -1;
73
+ for (let i = 0; i < lines.length; i++) {
74
+ if (/^#{1,2}\s*(Output contract|OUTPUT)\b/i.test(lines[i].trim())) {
75
+ start = i;
76
+ break;
77
+ }
78
+ }
79
+ if (start === -1) return [];
80
+ let end = lines.length;
81
+ for (let i = start + 1; i < lines.length; i++) {
82
+ if (/^#{1,2}\s/.test(lines[i].trim())) {
83
+ end = i;
84
+ break;
85
+ }
86
+ }
87
+ return lines.slice(start, end);
88
+ }
89
+
90
+ // Path-like tokens from text: contain '/' or end in '.md'. Keeps template
91
+ // tokens (<id>, *, NNN).
92
+ function extractPaths(text) {
93
+ const tokens = text.match(/[A-Za-z0-9_\-<>*\.\/]+/g) || [];
94
+ const out = [];
95
+ for (const t of tokens) {
96
+ const clean = t.trim();
97
+ if (clean.length > 2 && (clean.includes('/') || /\.md$/i.test(clean))) {
98
+ if (!out.includes(clean)) out.push(clean);
99
+ }
100
+ }
101
+ return out;
102
+ }
103
+
104
+ // `- Files: runs/RUN-*.md ..., findings/F-*.md ...` bullets (and their
105
+ // indented continuation lines). Returns declared artifact path templates.
106
+ function collectOutputFiles(section) {
107
+ const out = [];
108
+ for (let i = 0; i < section.length; i++) {
109
+ const m = section[i].trim().match(/^(?:-\s*)?(?:Files|File|Updated)\s*:\s*(.*)$/);
110
+ if (!m) continue;
111
+ const parts = [section[i]];
112
+ let j = i + 1;
113
+ while (j < section.length && /^[ \t]{2,}\S/.test(section[j])) {
114
+ parts.push(section[j]);
115
+ j++;
116
+ }
117
+ out.push(...extractPaths(parts.join(' ')));
118
+ }
119
+ return out.filter((x, idx, arr) => arr.indexOf(x) === idx);
120
+ }
121
+
122
+ // `- Terminal marker: `## ...`` bullets; gather backtick-enclosed tokens from
123
+ // the marker line and its indented continuation lines (disjunctions span 2
124
+ // lines for pensieve-validator / pensieve-roe-checker).
125
+ function collectMarkers(section) {
126
+ const start = section.findIndex((l) => /Terminal marker:/i.test(l));
127
+ if (start === -1) return [];
128
+ const out = [];
129
+ let i = start;
130
+ while (i < section.length) {
131
+ const ln = section[i];
132
+ const bt = ln.match(/`([^`]+)`/g) || [];
133
+ out.push(...bt.map((b) => b.replace(/`/g, '').trim()));
134
+ i += 1;
135
+ // continuation lines of the marker bullet are indented
136
+ if (i < section.length && /^[ \t]{2,}\S/.test(section[i])) continue;
137
+ break;
138
+ }
139
+ return out.filter(Boolean).filter((x, idx, arr) => arr.indexOf(x) === idx);
140
+ }
141
+
142
+ function parseAgentFile(content) {
143
+ return {
144
+ description: fmValue(content, 'description'),
145
+ marker: collectMarkers(outputSectionLines(content)),
146
+ files: collectOutputFiles(outputSectionLines(content)),
147
+ tools: parseTools(content),
148
+ };
149
+ }
150
+
151
+ /* ---------------------------------------------------------------------------
152
+ * Internal helpers
153
+ * --------------------------------------------------------------------------- */
154
+
155
+ function resolveAgent(agent, agentsDir) {
156
+ if (!agent || String(agent).trim() === '') {
157
+ throw new Error('missing agent');
158
+ }
159
+ // Accept both the short name ('tester') and the full agent file name
160
+ // ('pensieve-tester') the orchestrator passes at spawn.
161
+ const bare = String(agent).trim().toLowerCase().replace(/^pensieve-/, '');
162
+ const key = AGENT_ALIASES[bare] || bare;
163
+ const rows = list({ agentsDir });
164
+ const row = rows.find((a) => a.name === key);
165
+ if (!row) {
166
+ const names = rows.map((a) => a.name).join(', ');
167
+ throw new Error(`unknown agent '${agent}'; available: ${names}`);
168
+ }
169
+ return row;
170
+ }
171
+
172
+ function pad3(n) {
173
+ return String(n).padStart(3, '0');
174
+ }
175
+
176
+ function unitSlug(unit) {
177
+ return String(unit).replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/, '').slice(0, 40) || 'unit';
178
+ }
179
+
180
+ function yamlScalar(v) {
181
+ const s = String(v);
182
+ if (s.includes(': ') || s.includes('\n') || s.includes('#') || s.startsWith('- ') || s.startsWith(' ')) {
183
+ return JSON.stringify(s);
184
+ }
185
+ return s;
186
+ }
187
+
188
+ // Convert a declared marker template to an anchored, case-insensitive regex.
189
+ // Placeholder `<...>` tokens become `.*` (so a real marker with the token filled
190
+ // in still matches the declared template).
191
+ function markerSatisfies(declared, provided) {
192
+ if (declared == null || provided == null) return false;
193
+ const parts = String(declared).split(/(<[^>]*>)/);
194
+ const pattern = parts
195
+ .map((p) => (p.startsWith('<') ? '.*' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
196
+ .join('');
197
+ return new RegExp('^' + pattern + '$', 'i').test(String(provided).trim());
198
+ }
199
+
200
+ // Convert a single-level glob (with '*' and '<...>') to an anchored regex.
201
+ function globToRe(glob) {
202
+ let out = '';
203
+ for (const ch of glob) {
204
+ if (ch === '*') {
205
+ out += '.*';
206
+ } else {
207
+ const special = '^$.*+?()|[]{}\\';
208
+ out += special.includes(ch) ? '\\' + ch : ch;
209
+ }
210
+ }
211
+ return out;
212
+ }
213
+
214
+ function isTemplate(p) {
215
+ return p.includes('*') || p.includes('<') || /-[NNn]{3,}\b/.test(p);
216
+ }
217
+
218
+ function patternFrom(p) {
219
+ return p.replace(/<[^>]+>/g, '*').replace(/-[NNn]{3,}\b/g, '-*');
220
+ }
221
+
222
+ /* ---------------------------------------------------------------------------
223
+ * public API
224
+ * --------------------------------------------------------------------------- */
225
+
226
+ function list({ agentsDir = AGENTS_DIR } = {}) {
227
+ const abs = path.resolve(agentsDir);
228
+ if (!fs.existsSync(abs)) return [];
229
+ const files = fs.readdirSync(abs).filter((f) => f.startsWith('pensieve-') && f.endsWith('.md')).sort();
230
+ return files.map((file) => {
231
+ const name = file.replace(/\.md$/, '').replace(/^pensieve-/, '');
232
+ const parsed = parseAgentFile(fs.readFileSync(path.join(abs, file), 'utf8'));
233
+ return {
234
+ name,
235
+ file,
236
+ description: parsed.description,
237
+ // primary (first) terminal template, as a string; all templates in `markers`
238
+ marker: parsed.marker[0] || '',
239
+ markers: parsed.marker.slice(),
240
+ files: parsed.files,
241
+ tools: parsed.tools,
242
+ command: DELEGATION_COMMANDS[name] || null,
243
+ };
244
+ });
245
+ }
246
+
247
+ function brief({ agent, unit = '', agentsDir = AGENTS_DIR, engagementDir, packsRoot } = {}) {
248
+ const row = resolveAgent(agent, agentsDir);
249
+ const fileAbs = path.resolve(agentsDir, row.file);
250
+ const contract = fs.readFileSync(fileAbs, 'utf8');
251
+ const promptParts = [
252
+ `Delegate this unit to the ${row.name} sub-agent (contract: ${row.file}).`,
253
+ '',
254
+ `Command: ${row.command || 'n/a'}`,
255
+ `Unit: ${unit || ''}`,
256
+ `Required tools: ${row.tools.join(', ') || 'n/a'}`,
257
+ `Files to produce: ${row.files.join(', ') || 'n/a'}`,
258
+ `Terminal marker(s) to end with: ${row.marker || row.markers.join(' | ') || 'n/a'}`,
259
+ '',
260
+ "END the sub-agent's run by printing the terminal marker shown above (fill any <token> with real values).",
261
+ '',
262
+ '### Agent contract',
263
+ contract,
264
+ ];
265
+ // INJECT-02: agent-aware pack runbooks, appended AFTER the contract. Empty
266
+ // (no engagement / no matching pack) -> nothing added, byte-identical brief (SC3).
267
+ if (engagementDir) {
268
+ const injected = skills.agentSkills('pensieve-' + row.name, engagementDir, { packsRoot });
269
+ if (injected && injected.data !== '') {
270
+ promptParts.push('', '### Agent skills', injected.data);
271
+ }
272
+ }
273
+ const prompt = promptParts.join('\n');
274
+ return {
275
+ agent: row.name,
276
+ file: row.file,
277
+ description: row.description,
278
+ marker: row.marker,
279
+ files: row.files,
280
+ tools: row.tools,
281
+ command: row.command || null,
282
+ prompt,
283
+ contract,
284
+ };
285
+ }
286
+
287
+ function record({ engagementDir, agent, unit = '', marker = null, summary = '', artifacts = null, agentsDir = AGENTS_DIR } = {}) {
288
+ if (!engagementDir) throw new Error('missing engagementDir');
289
+ const row = resolveAgent(agent, agentsDir);
290
+ const abs = path.resolve(engagementDir);
291
+
292
+ const provided = marker == null || String(marker).trim() === '' ? null : String(marker).trim();
293
+ let storedMarker;
294
+ if (provided) {
295
+ // A reported marker is only valid if it satisfies one of the declared
296
+ // terminal templates (case-insensitive, <token> -> any).
297
+ if (!row.markers.some((d) => markerSatisfies(d, provided))) {
298
+ throw new Error(
299
+ `marker '${provided}' does not match the declared marker(s) for agent '${agent}': ${row.markers.join(' | ')}`
300
+ );
301
+ }
302
+ storedMarker = provided;
303
+ } else {
304
+ // None provided: default to the declared primary template (it IS the
305
+ // canonical declared marker, so no validation is needed).
306
+ storedMarker = row.marker;
307
+ if (!storedMarker) {
308
+ throw new Error(`agent '${agent}' has no declared marker and no marker provided`);
309
+ }
310
+ }
311
+
312
+ const art =
313
+ artifacts && artifacts.length
314
+ ? artifacts.map((a) => String(a).trim()).filter(Boolean)
315
+ : row.files.slice();
316
+
317
+ const now = new Date();
318
+ const iso = now.toISOString();
319
+ const datePart = iso.slice(0, 10).replace(/-/g, '');
320
+ // HHMMSS (no colons) so the runId is filesystem-safe and matches the
321
+ // RUN-YYYYMMDD-HHMMSS-<unitslug>-NNN design.
322
+ const timePart = iso.slice(11, 19).replace(/:/g, '');
323
+ const slug = unitSlug(unit);
324
+ const base = `RUN-${datePart}-${timePart}-${slug}`;
325
+
326
+ const runsDir = path.join(abs, 'runs', 'delegations');
327
+ fs.mkdirSync(runsDir, { recursive: true });
328
+
329
+ let maxSeq = 0;
330
+ if (fs.existsSync(runsDir)) {
331
+ for (const f of fs.readdirSync(runsDir)) {
332
+ if (f.startsWith(base + '-') && f.match(/-(\d+)$/)) {
333
+ const m = f.match(/-(\d+)$/);
334
+ maxSeq = Math.max(maxSeq, parseInt(m[1], 10));
335
+ }
336
+ }
337
+ }
338
+ let seq = maxSeq + 1;
339
+ let runId = `${base}-${pad3(seq)}`;
340
+ while (fs.existsSync(path.join(runsDir, runId))) {
341
+ seq += 1;
342
+ runId = `${base}-${pad3(seq)}`;
343
+ }
344
+
345
+ const fm = (key, value) => {
346
+ // Plain (unquoted) YAML scalar. Safe for the values we store: agent/unit
347
+ // (lowercase), at (ISO timestamp), run_id (alphanum-hyphen), marker
348
+ // (backtick-stripped template text, no leading indicator), and the
349
+ // comma-joined artifact string (no ': ' / '#' / '-' sequences).
350
+ const s = String(value);
351
+ return s.includes(': ') || s.startsWith('# ') || s.startsWith('---')
352
+ ? JSON.stringify(s)
353
+ : s;
354
+ };
355
+ const frontmatter = [
356
+ `agent: ${fm('agent', row.name)}`,
357
+ `unit: ${fm('unit', unit || '')}`,
358
+ `marker: ${fm('marker', storedMarker)}`,
359
+ `run_id: ${runId}`,
360
+ `at: ${iso}`,
361
+ `artifacts: ${fm('artifacts', art.join(', ') || '')}`,
362
+ ];
363
+
364
+ const body = [
365
+ '# Delegation receipt',
366
+ '',
367
+ `**Agent:** ${row.name}`,
368
+ `**Unit:** ${unit || '(none)'}`,
369
+ `**Run ID:** ${runId}`,
370
+ `**At:** ${iso}`,
371
+ '',
372
+ '## Marker (self-reported)',
373
+ '',
374
+ `> ${storedMarker}`,
375
+ '',
376
+ '## Summary',
377
+ '',
378
+ summary ? summary : '(no summary provided)',
379
+ '',
380
+ '## Self-reported artifacts (NOT evidence)',
381
+ '',
382
+ art.length ? art.map((a, i) => `${i + 1}. ${a}`).join('\n') : '(none declared)',
383
+ ].join('\n');
384
+
385
+ const content = frontmatter.join('\n') + '\n---\n' + body + '\n';
386
+ const fp = path.join(runsDir, runId);
387
+ fs.writeFileSync(fp, content, 'utf8');
388
+
389
+ return {
390
+ ok: true,
391
+ agent: row.name,
392
+ unit: unit || '',
393
+ marker: storedMarker,
394
+ runId,
395
+ at: iso,
396
+ artifacts: art.slice(),
397
+ path: fp,
398
+ };
399
+ }
400
+
401
+ function matchSingleLevel(dir, pattern) {
402
+ if (!fs.existsSync(dir)) return [];
403
+ let entries;
404
+ try {
405
+ entries = fs.readdirSync(dir);
406
+ } catch (e) {
407
+ return [];
408
+ }
409
+ const re = new RegExp('^' + globToRe(pattern) + '$');
410
+ return entries.filter((f) => re.test(f));
411
+ }
412
+
413
+ function checkArtifact(engagementDir, declared) {
414
+ const isTpl = isTemplate(declared);
415
+ if (!isTpl) {
416
+ const abs = path.join(engagementDir, declared);
417
+ const ok = fs.existsSync(abs);
418
+ return {
419
+ declared,
420
+ status: ok ? 'found' : 'missing',
421
+ ok,
422
+ matched: ok ? [declared] : [],
423
+ };
424
+ }
425
+ const declaredDir = path.dirname(path.join(engagementDir, declared));
426
+ const pattern = patternFrom(path.basename(declared));
427
+ const matches = matchSingleLevel(declaredDir, pattern);
428
+ const ok = matches.length >= 1;
429
+ return {
430
+ declared,
431
+ status: ok ? 'template-matched' : 'missing',
432
+ ok,
433
+ matched: ok ? matches : [],
434
+ };
435
+ }
436
+
437
+ // Receipt marker findings-count for one agent: receipts are plain-YAML-head
438
+ // files under runs/delegations/ (record() writer format: `agent:` and
439
+ // `marker:` raw scalar lines). Returns [] when none exist.
440
+ function agentReceiptMarkers(abs, agentName) {
441
+ const dir = path.join(abs, 'runs', 'delegations');
442
+ if (!fs.existsSync(dir)) return [];
443
+ const out = [];
444
+ for (const f of fs.readdirSync(dir)) {
445
+ const p = path.join(dir, f);
446
+ if (!fs.statSync(p).isFile()) continue;
447
+ const text = fs.readFileSync(p, 'utf8');
448
+ const agent = (text.match(/^agent:\s*(.+)$/m) || [])[1] || '';
449
+ const unq = (s) => s.replace(/^"|"$/g, '');
450
+ if (unq(agent.trim()) !== agentName) continue;
451
+ const marker = unq(((text.match(/^marker:\s*(.+)$/m) || [])[1] || '').trim());
452
+ out.push(marker);
453
+ }
454
+ return out;
455
+ }
456
+
457
+ function verify({ engagementDir, agent, agentsDir = AGENTS_DIR } = {}) {
458
+ if (!engagementDir) throw new Error('missing engagementDir');
459
+ const row = resolveAgent(agent, agentsDir);
460
+ const abs = path.resolve(engagementDir);
461
+ // Conditional findings artifacts (v0.16 live proof): a clean zero-finding
462
+ // run produces no findings files BY CONTRACT. A findings/ artifact is
463
+ // satisfied when the glob matches OR receipts exist for this agent and
464
+ // every one declares findings=0. A receipt claiming findings>0 still
465
+ // requires the files; no receipts keeps the strict legacy behavior.
466
+ const markers = agentReceiptMarkers(abs, row.name);
467
+ const cleanRun = markers.length > 0 && markers.every((m) => {
468
+ const n = (m.match(/findings=(\d+)/) || [])[1];
469
+ return n !== undefined && parseInt(n, 10) === 0;
470
+ });
471
+ const checks = (row.files || []).map((declared) => {
472
+ const c = checkArtifact(abs, declared);
473
+ if (!c.ok && cleanRun && declared.replace(/\\/g, '/').startsWith('findings/')) {
474
+ return { ...c, ok: true, status: 'optional-clean' };
475
+ }
476
+ return c;
477
+ });
478
+ const missing = checks.filter((c) => !c.ok).map((c) => c.declared);
479
+ const found = checks.filter((c) => c.ok).map((c) => c.declared);
480
+ return {
481
+ ok: true,
482
+ verdict: missing.length === 0 ? 'pass' : 'fail',
483
+ agent: row.name,
484
+ missing,
485
+ found,
486
+ artifacts: checks,
487
+ };
488
+ }
489
+
490
+ /* ---------------------------------------------------------------------------
491
+ * wave() — Phase 27 (HERM-01): the deterministic NEXT-WAVE derivation.
492
+ * ---------------------------------------------------------------------------
493
+ */
494
+
495
+ // Receipt units already recorded under runs/delegations/. record() writes the
496
+ // receipt head as plain YAML lines up to the `---` body fence (no leading
497
+ // fence). The unit is read as the RAW scalar of the `unit:` line: the shared
498
+ // YAML parser coerces `unit: 001` to the NUMBER 1, losing the plan id's
499
+ // leading zeros — and record()'s own writer emits plain (or JSON-quoted)
500
+ // scalars, so the verbatim line is exact. A plan "has a receipt" when some
501
+ // receipt's `unit:` equals the plan id (the exact --unit the workflow passes
502
+ // at spawn).
503
+ function receiptUnitFromHead(head) {
504
+ const m = head.match(/^unit: (.*)$/m);
505
+ if (!m) return '';
506
+ let raw = m[1].trim();
507
+ if (raw.startsWith('"') && raw.endsWith('"')) {
508
+ try { raw = String(JSON.parse(raw)); } catch { /* keep the raw text */ }
509
+ }
510
+ return raw;
511
+ }
512
+
513
+ function receiptUnits(engagementDir) {
514
+ const dir = path.join(paths.runsDir(engagementDir), 'delegations');
515
+ if (!fs.existsSync(dir)) return new Set();
516
+ const units = new Set();
517
+ for (const f of fs.readdirSync(dir)) {
518
+ const fp = path.join(dir, f);
519
+ let isFile = false;
520
+ try { isFile = fs.statSync(fp).isFile(); } catch { continue; }
521
+ if (!isFile) continue;
522
+ let text;
523
+ try { text = fs.readFileSync(fp, 'utf8'); } catch { continue; }
524
+ const fence = text.indexOf('\n---\n');
525
+ const unit = receiptUnitFromHead(fence === -1 ? text : text.slice(0, fence));
526
+ if (unit !== '') units.add(unit);
527
+ }
528
+ return units;
529
+ }
530
+
531
+ /* ---------------------------------------------------------------------------
532
+ * TD-09 (36-03): PATH-aware wave ordering.
533
+ * ---------------------------------------------------------------------------
534
+ */
535
+
536
+ // plans/PATH.md — the planner's execution order (waves table: each row is a
537
+ // wave, the "Plans (run in listed order)" column carries that wave's plan
538
+ // ids). ONLY that column is authoritative: prose mentions of plan ids
539
+ // (graph-state notes, gate rationales, deviation justifications) must never
540
+ // reorder anything. Ids are cited as 'PLAN-001' or bare '001' — both
541
+ // normalize to the plan id. Read-only; a missing PATH.md is simply no order.
542
+ function pathPlanOrder(engagementDir) {
543
+ const file = path.join(paths.plansDir(engagementDir), 'PATH.md');
544
+ let text;
545
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
546
+ const order = [];
547
+ const seen = new Set();
548
+ const lines = text.split('\n');
549
+ let i = 0;
550
+ while (i < lines.length) {
551
+ if (!/^\s*\|/.test(lines[i])) { i += 1; continue; }
552
+ const table = [];
553
+ while (i < lines.length && /^\s*\|/.test(lines[i])) { table.push(lines[i]); i += 1; }
554
+ // header row: locate the "Plans" column (the separator row below it
555
+ // contributes no ids, so it needs no special case)
556
+ const header = (table[0] || '').split('|').map((c) => c.trim().toLowerCase());
557
+ const col = header.findIndex((c) => /\bplans?\b/.test(c));
558
+ if (col === -1) continue;
559
+ for (let r = 1; r < table.length; r++) {
560
+ const cell = (table[r].split('|')[col] || '');
561
+ // single left-to-right pass: 'PLAN-<id>' citations and bare '<nnn>'
562
+ // citations keep their listed order
563
+ for (const m of cell.matchAll(/plan-([a-z0-9-]+)|\b(\d{3})\b/gi)) {
564
+ const id = String(m[1] || m[2] || '').toLowerCase();
565
+ if (id && !seen.has(id)) { seen.add(id); order.push(id); }
566
+ }
567
+ }
568
+ }
569
+ return order;
570
+ }
571
+
572
+ /**
573
+ * TD-09: order the pending (approved-unrun) plans by the planner's PATH.md
574
+ * execution order. Plans absent from PATH — adaptive candidates the planner
575
+ * never saw — keep today's approval order AFTER the covered ones. A PATH.md
576
+ * that is absent or covers nothing pending returns `pending` itself: the
577
+ * ordering is a no-op and the wave is byte-identical to the legacy one.
578
+ * Id matching is case-insensitive (PATH citations normalize to lowercase).
579
+ */
580
+ function orderByPath(pending, pathOrder) {
581
+ if (!pathOrder.length) return pending;
582
+ const byLower = new Map(pending.map((id) => [String(id).toLowerCase(), id]));
583
+ const covered = [];
584
+ for (const id of pathOrder) {
585
+ const key = String(id).toLowerCase();
586
+ const hit = byLower.get(key);
587
+ if (hit !== undefined) { covered.push(hit); byLower.delete(key); }
588
+ }
589
+ const uncovered = [...byLower.values()]; // Map preserves pending (approval) order
590
+ return covered.concat(uncovered);
591
+ }
592
+
593
+ /**
594
+ * wave({ engagementDir }) — the NEXT capped wave for the orchestrator:
595
+ *
596
+ * approved plans (approvals.approvedPlans — the SAME checkpoint state the
597
+ * planned->testing gate reads; only approved plans ever run)
598
+ * MINUS plans with a recorded delegation receipt (runs/delegations/, receipt
599
+ * `unit:` == plan id — a plan that already ran is not re-issued)
600
+ * ordered by plans/PATH.md execution order when it covers pending plans
601
+ * (TD-09: the planner's waves decide; plans absent from PATH append in
602
+ * approval order after the covered ones; absent/empty PATH is a no-op)
603
+ * sliced to config.maxParallelItems(cfg) — the CFG-01 ROE no-DoS clamp,
604
+ * NEVER the raw config value, so a hand-edit cannot exceed the tier ceiling.
605
+ *
606
+ * Deterministic: sorted plan ids (approvals.planIds sorts), no timestamps —
607
+ * the same engagement state always yields the same wave. Read-only: nothing
608
+ * is written, so repeated calls are identical (the caller advances the wave
609
+ * by recording receipts). Fails CLOSED: a missing/invalid engagement returns
610
+ * ok:false, never a guessed wave.
611
+ */
612
+ function wave({ engagementDir } = {}) {
613
+ if (!engagementDir || String(engagementDir).trim() === '') {
614
+ return { ok: false, error: 'subagent.wave requires an engagement dir', data: null };
615
+ }
616
+ const abs = path.resolve(String(engagementDir).trim());
617
+ if (!state.isEngagement(abs)) {
618
+ return {
619
+ ok: false,
620
+ error: 'engagement not found (no STATE.md with status frontmatter) at the given path',
621
+ data: null,
622
+ };
623
+ }
624
+ const approved = approvals.approvedPlans(abs).approved; // sorted plan ids
625
+ const recorded = receiptUnits(abs);
626
+ const pending = approved.filter((id) => !recorded.has(id));
627
+ const ordered = orderByPath(pending, pathPlanOrder(abs));
628
+ const { cfg } = config.load(abs);
629
+ const cap = config.maxParallelItems(cfg);
630
+ const next = ordered.slice(0, cap);
631
+ return {
632
+ ok: true,
633
+ error: null,
634
+ data: {
635
+ engagement: abs,
636
+ cap,
637
+ approved: approved.length,
638
+ pending: pending.length,
639
+ wave: next.map((id) => ({
640
+ plan: id,
641
+ brief: `pensieve-sdk subagent.brief pensieve-tester --engagement ${abs} --unit ${id}`,
642
+ })),
643
+ remaining: pending.length - next.length,
644
+ },
645
+ };
646
+ }
647
+
648
+ module.exports = {
649
+ list,
650
+ brief,
651
+ record,
652
+ verify,
653
+ wave,
654
+ // exported for tests / tooling
655
+ unitSlug,
656
+ AGENT_ALIASES,
657
+ DELEGATION_COMMANDS,
658
+ };