@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,50 @@
1
+ 'use strict';
2
+ // Neutral -> runtime agent frontmatter translator (zero dependency).
3
+ // One neutral agent contract is the single source of truth; the installer
4
+ // translates it per runtime. Only the 4 mapped tools and 2 tiers are grantable;
5
+ // any unknown token throws (no silent privilege grant — ISO-01 / T-15-01).
6
+
7
+ // neutral tool token -> Claude Code tool name. Kept in one place so the Hermes
8
+ // branch can reuse the seam later.
9
+ const TOOL_MAP = Object.freeze({
10
+ read_file: 'Read',
11
+ write_file: 'Write',
12
+ terminal: 'Bash',
13
+ patch: 'Edit',
14
+ });
15
+
16
+ // neutral model_tier -> Claude Code subagent `model:` alias (CC-valid values).
17
+ const MODEL_MAP = Object.freeze({
18
+ DEFAULT: 'sonnet',
19
+ DEEP: 'opus',
20
+ });
21
+
22
+ // Rewrite ONLY the frontmatter `tools:`/`model_tier:` lines; body stays byte-for-byte.
23
+ function translateAgent(neutralContent, runtime) {
24
+ if (runtime !== 'claude-code') {
25
+ throw new Error(`translateAgent: unsupported runtime "${runtime}"`);
26
+ }
27
+ const fm = neutralContent.match(/^(---\n)([\s\S]*?)(\n---\n)/);
28
+ if (!fm) throw new Error('translateAgent: input has no frontmatter block');
29
+
30
+ const lines = fm[2].split('\n').map((line) => {
31
+ const tools = line.match(/^tools:\s*\[(.*)\]\s*$/);
32
+ if (tools) {
33
+ const mapped = tools[1].split(',').map((t) => t.trim()).filter(Boolean).map((tok) => {
34
+ if (!(tok in TOOL_MAP)) throw new Error(`translateAgent: unknown tool token "${tok}"`);
35
+ return TOOL_MAP[tok];
36
+ });
37
+ return `tools: [${mapped.join(', ')}]`;
38
+ }
39
+ const tier = line.match(/^model_tier:\s*(\S+)\s*$/);
40
+ if (tier) {
41
+ if (!(tier[1] in MODEL_MAP)) throw new Error(`translateAgent: unknown model_tier "${tier[1]}"`);
42
+ return `model: ${MODEL_MAP[tier[1]]}`;
43
+ }
44
+ return line;
45
+ });
46
+
47
+ return fm[1] + lines.join('\n') + fm[3] + neutralContent.slice(fm[0].length);
48
+ }
49
+
50
+ module.exports = { translateAgent, TOOL_MAP, MODEL_MAP };
@@ -0,0 +1,408 @@
1
+ 'use strict';
2
+ /**
3
+ * approvals.cjs — checkpoints recorded as artifact frontmatter (v0.6 01-03
4
+ * item 5, ADR-023 / brief 1.10; extends ADR-009).
5
+ *
6
+ * ADR-009 put human checkpoints at loop boundaries but never said where the
7
+ * CHECKPOINT OUTCOME lives — agents proceeded while PLAN headers still read
8
+ * "pending human approval". This module makes the checkpoint machine-readable:
9
+ * `approved: true` + `approved_by: <name>` + `approved_at: <ISO8601>` written
10
+ * INTO the frontmatter of the artifact being approved, by this deterministic
11
+ * writer (humans never hand-edit frontmatter; hand-edits are exactly what
12
+ * broke STATE.md).
13
+ *
14
+ * Artifact keys:
15
+ * scope -> SCOPE.md
16
+ * plan:<id> -> plans/PLAN-<id>.md
17
+ * report -> report/REPORT.md
18
+ *
19
+ * state.setStatus refuses the boundary transitions (scoped->recon,
20
+ * planned->testing, reporting->delivered) without these fields. yolo
21
+ * engagements do NOT skip boundary approvals (ADR-009: "checkpoints at
22
+ * boundaries, never skipped") — they RECORD the scope approval via
23
+ * autoApproveScope (by 'owner-yolo-preauthorized'); plan/report approvals
24
+ * stay explicit.
25
+ */
26
+
27
+ const fs = require('node:fs');
28
+ const path = require('node:path');
29
+ const fm = require('./frontmatter.cjs');
30
+ const paths = require('./paths.cjs');
31
+ const config = require('./config.cjs');
32
+ const scope = require('./scope.cjs');
33
+
34
+ const YOLO_PREAUTHORIZED_BY = 'owner-yolo-preauthorized';
35
+ // NPX-05 (v1.2): autonomous-mode provenance. Full walk-away means the
36
+ // checkpoint is still RECORDED — with this name — so the audit trail always
37
+ // shows WHICH mode approved what. The pre-v1.2 'yolo' vocabulary read-side
38
+ // aliases to autonomous (config.cjs), so old engagements flow through here.
39
+ const AUTONOMOUS_MODE_BY = 'autonomous-mode';
40
+
41
+ /**
42
+ * Resolve an artifact key to its file. Returns { file } or { error }.
43
+ * plan:<id> ids are restricted to [A-Za-z0-9-] — the id becomes a filename,
44
+ * so path separators / traversal are never accepted.
45
+ */
46
+ function artifactPath(engagementDir, artifact) {
47
+ if (typeof artifact !== 'string' || !artifact.trim()) {
48
+ return { error: 'approve requires an artifact: scope | liveness | plan:<id> | report' };
49
+ }
50
+ const a = artifact.trim();
51
+ if (a === 'scope') return { file: paths.scopeFile(engagementDir) };
52
+ // REACH-02 (v1.1): the unreachable-override checkpoint — the human records
53
+ // the decision to continue past an unreachable liveness verdict ON the
54
+ // verdict artifact itself (recon/LIVENESS.md).
55
+ if (a === 'liveness') return { file: path.join(paths.reconDir(engagementDir), 'LIVENESS.md') };
56
+ if (a === 'report') return { file: path.join(paths.reportDir(engagementDir), 'REPORT.md') };
57
+ const m = /^plan:([A-Za-z0-9-]+)$/.exec(a);
58
+ if (m) return { file: path.join(paths.plansDir(engagementDir), `PLAN-${m[1]}.md`) };
59
+ return { error: `unsupported artifact: ${a} (expected scope, liveness, plan:<id>, or report)` };
60
+ }
61
+
62
+ /**
63
+ * approve(dir, { artifact, by }) — write the checkpoint frontmatter onto the
64
+ * artifact. Idempotent: re-approving updates approved_by/approved_at in place
65
+ * (exactly one approved key, never a duplicate) and preserves every other
66
+ * frontmatter field plus the body.
67
+ *
68
+ * Returns a JSON-style envelope { ok, error, data } — approval refusal is a
69
+ * normal outcome, not an exception.
70
+ */
71
+ function approve(engagementDir, { artifact, by } = {}) {
72
+ if (!engagementDir) {
73
+ return { ok: false, error: 'approve requires an engagement dir', data: null };
74
+ }
75
+ const resolved = artifactPath(engagementDir, artifact);
76
+ if (resolved.error) return { ok: false, error: resolved.error, data: null };
77
+ if (typeof by !== 'string' || !by.trim()) {
78
+ return { ok: false, error: 'approve requires --by <name> — a checkpoint without a named approver is not a checkpoint', data: null };
79
+ }
80
+ const file = resolved.file;
81
+ if (!fs.existsSync(file)) {
82
+ return { ok: false, error: `cannot approve ${artifact}: the artifact file does not exist (${path.basename(file)}) — write the artifact before recording its checkpoint`, data: null };
83
+ }
84
+ // v0.10 14-01 (SEED-004 / HARDEN-04): fail-closed on a loopback in-scope target
85
+ // at the second scope-finalization choke point (defense in depth). Reuses the
86
+ // shared scope.loopbackTargets predicate — the gate is not duplicated.
87
+ if (artifact && artifact.trim() === 'scope') {
88
+ const bad = scope.loopbackTargets(scope.parse(fs.readFileSync(file, 'utf8')));
89
+ if (bad.length) {
90
+ return { ok: false, error:
91
+ `cannot approve scope: loopback in-scope target rejected (SEED-004/HARDEN-04) — ${bad.join(', ')} — `
92
+ + 'join the target container to pensieve-net and scope its service name + internal port '
93
+ + 'instead (see lab/run.sh), e.g. juice-shop:3000', data: null };
94
+ }
95
+ }
96
+ const at = new Date().toISOString();
97
+ let out = fm.set(fs.readFileSync(file, 'utf8'), 'approved', true);
98
+ out = fm.set(out, 'approved_by', by.trim());
99
+ out = fm.set(out, 'approved_at', at);
100
+ fs.writeFileSync(file, out);
101
+ return { ok: true, error: null, data: { artifact: artifact.trim(), file, approved: true, approved_by: by.trim(), approved_at: at } };
102
+ }
103
+
104
+ /** isApproved(dir, artifact) — boolean; false for unknown keys/missing files. */
105
+ function isApproved(engagementDir, artifact) {
106
+ const resolved = artifactPath(engagementDir, artifact);
107
+ if (resolved.error) return false;
108
+ try {
109
+ return fm.get(fs.readFileSync(resolved.file, 'utf8'), 'approved') === true;
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ /** planIds(dir) — sorted ids of every plans/PLAN-*.md ([] when no plans dir). */
116
+ function planIds(engagementDir) {
117
+ const dir = paths.plansDir(engagementDir);
118
+ if (!fs.existsSync(dir)) return [];
119
+ return fs.readdirSync(dir)
120
+ .map((f) => /^PLAN-([A-Za-z0-9-]+)\.md$/.exec(f))
121
+ .filter(Boolean)
122
+ .map((m) => m[1])
123
+ .sort();
124
+ }
125
+
126
+ /** unapprovedPlans(dir) — ids of PLAN-*.md files without the checkpoint. */
127
+ function unapprovedPlans(engagementDir) {
128
+ return planIds(engagementDir).filter((id) => !isApproved(engagementDir, `plan:${id}`));
129
+ }
130
+
131
+ /**
132
+ * approvedPlans(dir) — SWARM-02 swarm work-list: { approved, unapproved, total }.
133
+ * `approved` = planIds filtered by isApproved('plan:<id>'); `unapproved` = the rest.
134
+ * This is a convenience list for the test swarm, NOT the ROE gate — the real gate
135
+ * is the planned->testing state transition (state.cjs), which already refuses to
136
+ * advance while any plan is unapproved. This query cannot widen what runs.
137
+ */
138
+ function approvedPlans(engagementDir) {
139
+ const all = planIds(engagementDir);
140
+ const approved = all.filter((id) => isApproved(engagementDir, `plan:${id}`));
141
+ return { approved, unapproved: all.filter((id) => !approved.includes(id)), total: all.length };
142
+ }
143
+
144
+ /**
145
+ * allApproved(dir, artifactType) — 'plans' requires EVERY plans/PLAN-*.md to
146
+ * be approved (vacuously true with zero plans); 'scope'/'report' delegate to
147
+ * isApproved.
148
+ */
149
+ function allApproved(engagementDir, artifactType) {
150
+ if (artifactType === 'plans') return unapprovedPlans(engagementDir).length === 0;
151
+ if (artifactType === 'scope' || artifactType === 'report') return isApproved(engagementDir, artifactType);
152
+ return false;
153
+ }
154
+
155
+ /**
156
+ * approvalGate(dir) — { ok, errors[] } across all checkpoint artifacts;
157
+ * every error names the missing approval and the command that records it.
158
+ */
159
+ function approvalGate(engagementDir) {
160
+ const errors = [];
161
+ if (!fs.existsSync(paths.scopeFile(engagementDir))) {
162
+ errors.push('SCOPE.md is missing — write the scope, then record the checkpoint: pensieve-sdk approve --engagement <dir> --artifact scope --by <name>');
163
+ } else if (!isApproved(engagementDir, 'scope')) {
164
+ errors.push('SCOPE.md is not approved — record the checkpoint: pensieve-sdk approve --engagement <dir> --artifact scope --by <name>');
165
+ }
166
+ const pending = unapprovedPlans(engagementDir);
167
+ if (pending.length) {
168
+ errors.push(`unapproved plan(s): ${pending.map((id) => `plan:${id}`).join(', ')} — every plans/PLAN-*.md needs the checkpoint: pensieve-sdk approve --engagement <dir> --artifact plan:<id> --by <name>`);
169
+ }
170
+ const reportFile = path.join(paths.reportDir(engagementDir), 'REPORT.md');
171
+ if (!fs.existsSync(reportFile)) {
172
+ errors.push('report/REPORT.md is missing — compile the report, then record the checkpoint: pensieve-sdk approve --engagement <dir> --artifact report --by <name>');
173
+ } else if (!isApproved(engagementDir, 'report')) {
174
+ errors.push('report/REPORT.md is not approved — record the checkpoint: pensieve-sdk approve --engagement <dir> --artifact report --by <name>');
175
+ }
176
+ return { ok: errors.length === 0, errors };
177
+ }
178
+
179
+ /**
180
+ * autoRecord(dir, artifact) — NPX-05 (v1.2) autonomous-mode checkpoint
181
+ * recording. FULL WALK-AWAY, with the two things that keep it honest:
182
+ *
183
+ * 1. RECORDED, never skipped: approved_by autonomous-mode is written onto
184
+ * the artifact, so every audit trail shows the mode that approved it.
185
+ * 2. BLOCKERS STILL STOP: any failed guardrail (account gap, ROE
186
+ * violation/HUMAN NEEDED, hard-stop WAF alert) refuses the
187
+ * auto-record — the boundary gate then refuses and the agent surfaces
188
+ * it. A missing artifact file refuses too (the report must be compiled
189
+ * before its checkpoint can exist). Autonomy is not silence.
190
+ *
191
+ * aiApprove's confidence floor does NOT apply here: the human chose
192
+ * walk-away; guardrails are the objective safety checks that remain.
193
+ */
194
+ function autoRecord(engagementDir, artifact) {
195
+ const resolved = artifactPath(engagementDir, artifact);
196
+ if (resolved.error) return { ok: false, error: resolved.error, data: null };
197
+ if (!fs.existsSync(resolved.file)) {
198
+ return { ok: true, error: null, data: { artifact, auto_approved: false, blocked: ['artifact does not exist — write it before its checkpoint'] } };
199
+ }
200
+ const failed = guardrails(engagementDir).filter((g) => !g.ok);
201
+ if (failed.length) {
202
+ return {
203
+ ok: true, error: null,
204
+ data: { artifact, auto_approved: false, blocked: failed.map((g) => `${g.name}: ${g.reason}`) },
205
+ };
206
+ }
207
+ const r = approve(engagementDir, { artifact, by: AUTONOMOUS_MODE_BY });
208
+ if (!r.ok) return r;
209
+ return { ok: true, error: null, data: { ...r.data, auto_approved: true, autonomy: 'autonomous' } };
210
+ }
211
+
212
+ /**
213
+ * autoApproveScope(dir) — NPX-05: autonomy: autonomous (formerly yolo)
214
+ * pre-authorizes WITHIN scope/payload limits, so the SCOPE checkpoint is
215
+ * recorded automatically — RECORDED, never skipped, and refused when a
216
+ * guardrail is failing. Other levels are a no-op: supervised keeps the
217
+ * human checkpoint; semi-autonomous keeps scope human too (only plans go
218
+ * through the AI approver). Idempotent.
219
+ *
220
+ * autonomy is read from the engagement config (config.yaml via config.load),
221
+ * the same source of truth every other dial uses — never from STATE.md.
222
+ */
223
+ function autoApproveScope(engagementDir) {
224
+ const { cfg } = config.load(engagementDir);
225
+ if (cfg.autonomy !== 'autonomous') {
226
+ return { ok: true, error: null, data: { auto_approved: false, autonomy: cfg.autonomy } };
227
+ }
228
+ const r = autoRecord(engagementDir, 'scope');
229
+ if (!r.ok) return r;
230
+ return { ok: true, error: null, data: { ...r.data, auto_approved: r.data.auto_approved, autonomy: 'autonomous' } };
231
+ }
232
+
233
+ /**
234
+ * autoApprovePlans(dir) — NPX-05: autonomous mode records the plan
235
+ * checkpoints (approved_by autonomous-mode) for every UNapproved plan.
236
+ * semi-autonomous is a NO-OP by design: its plans go through aiApprove
237
+ * (guardrails + confidence floor), and scope/report stay human. supervised
238
+ * is a no-op. Mechanical gates untouched: plans that do not exist are not
239
+ * created; guardrail failures block and surface.
240
+ */
241
+ function autoApprovePlans(engagementDir) {
242
+ const { cfg } = config.load(engagementDir);
243
+ if (cfg.autonomy !== 'autonomous') {
244
+ return { ok: true, error: null, data: { auto_approved: false, autonomy: cfg.autonomy, stamped: [], blocked: [] } };
245
+ }
246
+ const stamped = [];
247
+ const blocked = [];
248
+ for (const id of unapprovedPlans(engagementDir)) {
249
+ const r = autoRecord(engagementDir, `plan:${id}`);
250
+ if (!r.ok) return r;
251
+ if (r.data.auto_approved) stamped.push(`plan:${id}`);
252
+ else blocked.push({ plan: `plan:${id}`, blocked: r.data.blocked });
253
+ }
254
+ return { ok: true, error: null, data: { auto_approved: stamped.length > 0, autonomy: 'autonomous', stamped, blocked } };
255
+ }
256
+
257
+ /**
258
+ * autoApproveReport(dir) — NPX-05: autonomous mode records the report
259
+ * checkpoint. The report must EXIST (report.compile ran) and the
260
+ * guardrails must be clean — report.verify itself is a separate,
261
+ * untouched mechanical gate at the reporting->delivered boundary.
262
+ */
263
+ function autoApproveReport(engagementDir) {
264
+ const { cfg } = config.load(engagementDir);
265
+ if (cfg.autonomy !== 'autonomous') {
266
+ return { ok: true, error: null, data: { auto_approved: false, autonomy: cfg.autonomy } };
267
+ }
268
+ const r = autoRecord(engagementDir, 'report');
269
+ if (!r.ok) return r;
270
+ return { ok: true, error: null, data: { ...r.data, auto_approved: r.data.auto_approved, autonomy: 'autonomous' } };
271
+ }
272
+
273
+ /* ---- AI-as-approver (v0.6 05-04 / ADR-024) ----
274
+ * The AI is the approver of record: it records a verdict + confidence +
275
+ * reasoning + cited evidence. The checkpoint is auto-accepted ONLY inside the
276
+ * guardrails; a low confidence OR any failed guardrail -> verdict 'escalate'
277
+ * (## HUMAN NEEDED) and the checkpoint is NOT recorded. The human stays the
278
+ * exception handler via the existing approve() command.
279
+ *
280
+ * The confidence floor is the AI's self-assessment; the guardrails are the
281
+ * objective safety checks. Together they make this NOT a blind auto-approve:
282
+ * a rubber stamp (empty reasoning / no evidence) is refused outright.
283
+ */
284
+ const AI_CONFIDENCE_FLOOR = 0.8;
285
+
286
+ /** floorFrom(cfg) — the engagement's AI-approval confidence floor: the
287
+ * ai_confidence_floor dial (config.yaml / PENSIEVE_AI_CONFIDENCE_FLOOR) when it
288
+ * is a valid number in [0,1], else the AI_CONFIDENCE_FLOOR default. */
289
+ function floorFrom(cfg) {
290
+ const v = parseFloat(cfg && cfg.ai_confidence_floor);
291
+ return (!Number.isNaN(v) && v >= 0 && v <= 1) ? v : AI_CONFIDENCE_FLOOR;
292
+ }
293
+
294
+ function guardrailScope(engagementDir) {
295
+ const f = paths.scopeFile(engagementDir);
296
+ if (!fs.existsSync(f)) return { name: 'scope', ok: false, reason: 'SCOPE.md missing' };
297
+ const ast = scope.parse(fs.readFileSync(f, 'utf8'));
298
+ if (!ast.assets.length) return { name: 'scope', ok: false, reason: 'SCOPE.md declares no in-scope assets' };
299
+ return { name: 'scope', ok: true, reason: `${ast.assets.length} in-scope asset(s)` };
300
+ }
301
+
302
+ function guardrailAccounts(engagementDir) {
303
+ const f = paths.accountsFile(engagementDir);
304
+ if (!fs.existsSync(f)) return { name: 'accounts', ok: true, reason: 'no ACCOUNTS.md (unauthenticated scope)' };
305
+ if (/##\s*HUMAN NEEDED/i.test(fs.readFileSync(f, 'utf8'))) {
306
+ return { name: 'accounts', ok: false, reason: 'ACCOUNTS.md has an open ## HUMAN NEEDED (account gap)' };
307
+ }
308
+ return { name: 'accounts', ok: true, reason: 'no account gap' };
309
+ }
310
+
311
+ function guardrailRoe(engagementDir) {
312
+ const f = paths.resolve(engagementDir, 'ROE.md');
313
+ if (!fs.existsSync(f)) return { name: 'roe', ok: false, reason: 'ROE.md missing (no authorization reference)' };
314
+ const text = fs.readFileSync(f, 'utf8');
315
+ if (/##\s*HUMAN NEEDED/i.test(text) || /violation:\s*open/i.test(text)) {
316
+ return { name: 'roe', ok: false, reason: 'ROE has an open violation / HUMAN NEEDED marker' };
317
+ }
318
+ return { name: 'roe', ok: true, reason: 'ROE clean' };
319
+ }
320
+
321
+ function guardrailWaf(engagementDir) {
322
+ const f = path.join(paths.envDir(engagementDir), 'waf-alerts.log');
323
+ if (!fs.existsSync(f)) return { name: 'waf', ok: true, reason: 'no WAF alerts recorded' };
324
+ const hard = fs.readFileSync(f, 'utf8').split('\n').filter((l) => /\[(waf_blocking|origin_overload)\]/.test(l));
325
+ if (hard.length) return { name: 'waf', ok: false, reason: `${hard.length} hard-stop WAF/tripwire alert(s) recorded` };
326
+ return { name: 'waf', ok: true, reason: 'no hard-stop WAF/tripwire alerts' };
327
+ }
328
+
329
+ function guardrails(engagementDir) {
330
+ return [guardrailScope(engagementDir), guardrailAccounts(engagementDir), guardrailRoe(engagementDir), guardrailWaf(engagementDir)];
331
+ }
332
+
333
+ function escalateHuman(engagementDir, { artifact, by, confidence, reasons, reasoning, at }) {
334
+ const f = path.join(path.resolve(engagementDir), 'HUMAN-NEEDED.md');
335
+ if (!fs.existsSync(f)) {
336
+ fs.writeFileSync(f, '# Human needed\n\n_AI-approval escalations (v0.6 05-04): the AI approver deferred these to a human._\n');
337
+ }
338
+ const block = [
339
+ '',
340
+ `## ${at} — ai-approve ${artifact} (escalate)`,
341
+ `- approver: ${by}`,
342
+ `- confidence: ${confidence}`,
343
+ `- failed guardrails / floor: ${reasons.join('; ')}`,
344
+ `- reasoning: ${reasoning}`,
345
+ `- action: human reviews, then records the checkpoint: pensieve-sdk approve --engagement <dir> --artifact ${artifact} --by <name>`,
346
+ '',
347
+ ].join('\n');
348
+ fs.appendFileSync(f, block);
349
+ }
350
+
351
+ /**
352
+ * aiApprove(engagementDir, {artifact, by, confidence, reasoning, evidence}) ->
353
+ * { ok, error, data }. data.verdict is 'approved' (checkpoint recorded) or
354
+ * 'escalate' (deferred to a human; checkpoint NOT recorded).
355
+ */
356
+ function aiApprove(engagementDir, { artifact, by, confidence, reasoning, evidence } = {}) {
357
+ if (!engagementDir) return { ok: false, error: 'ai-approve requires an engagement dir', data: null };
358
+ const resolved = artifactPath(engagementDir, artifact);
359
+ if (resolved.error) return { ok: false, error: resolved.error, data: null };
360
+ if (typeof by !== 'string' || !by.trim()) return { ok: false, error: 'ai-approve requires --by <agent> — the approver of record', data: null };
361
+ if (!fs.existsSync(resolved.file)) return { ok: false, error: `cannot approve ${artifact}: the artifact file does not exist — write it first`, data: null };
362
+ if (typeof reasoning !== 'string' || !reasoning.trim()) return { ok: false, error: 'ai-approve requires --reasoning "<why this is safe to approve>" — a verdict without reasoning is a rubber stamp', data: null };
363
+ const ev = Array.isArray(evidence) ? evidence.filter(Boolean) : [];
364
+ const needsEvidence = String(artifact).trim() !== 'scope'; // scope is the first checkpoint — nothing to cite yet
365
+ if (needsEvidence && ev.length === 0) return { ok: false, error: 'ai-approve requires --evidence <E-id> for a plan/report — a verdict without cited evidence is a rubber stamp', data: null };
366
+
367
+ const conf = typeof confidence === 'number' ? confidence : parseFloat(confidence);
368
+ const confVal = Number.isNaN(conf) ? 0 : conf;
369
+ const { cfg } = config.load(engagementDir);
370
+ const floor = floorFrom(cfg);
371
+ const confOk = confVal >= floor;
372
+ const checks = guardrails(engagementDir);
373
+ const failed = checks.filter((c) => !c.ok);
374
+ const escalate = failed.length > 0 || !confOk;
375
+ const at = new Date().toISOString();
376
+
377
+ // record the full structured verdict on the artifact frontmatter
378
+ let out = fm.set(fs.readFileSync(resolved.file, 'utf8'), 'approval_kind', 'ai');
379
+ out = fm.set(out, 'approval_verdict', escalate ? 'escalate' : 'approved');
380
+ out = fm.set(out, 'approval_confidence', confVal);
381
+ out = fm.set(out, 'approval_reasoning', reasoning.trim());
382
+ if (ev.length) out = fm.set(out, 'approval_evidence', ev);
383
+
384
+ if (escalate) {
385
+ const reasons = [
386
+ ...failed.map((c) => `${c.name}: ${c.reason}`),
387
+ ...(!confOk ? [`confidence ${confVal} < floor ${floor}`] : []),
388
+ ];
389
+ out = fm.set(out, 'approved', false);
390
+ out = fm.set(out, 'escalation_reasons', reasons);
391
+ fs.writeFileSync(resolved.file, out);
392
+ escalateHuman(engagementDir, { artifact, by: by.trim(), confidence: confVal, reasons, reasoning: reasoning.trim(), at });
393
+ return { ok: true, error: null, data: { artifact, verdict: 'escalate', approved: false, confidence: confVal, guardrails: checks, escalation_reasons: reasons } };
394
+ }
395
+
396
+ out = fm.set(out, 'approved', true);
397
+ out = fm.set(out, 'approved_by', by.trim());
398
+ out = fm.set(out, 'approved_at', at);
399
+ fs.writeFileSync(resolved.file, out);
400
+ return { ok: true, error: null, data: { artifact, verdict: 'approved', approved: true, approved_by: by.trim(), approved_at: at, confidence: confVal, guardrails: checks } };
401
+ }
402
+
403
+ module.exports = {
404
+ approve, isApproved, allApproved, approvalGate, autoApproveScope,
405
+ autoApprovePlans, autoApproveReport, autoRecord,
406
+ planIds, unapprovedPlans, approvedPlans, YOLO_PREAUTHORIZED_BY, AUTONOMOUS_MODE_BY,
407
+ aiApprove, AI_CONFIDENCE_FLOOR, floorFrom,
408
+ };