@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,133 @@
1
+ 'use strict';
2
+ /**
3
+ * close.cjs — engagement close-out (ADR-021, M3).
4
+ *
5
+ * Close is a gated archival step, not "stop touching it": requires a
6
+ * delivered|retesting status and an intact evidence chain, brings the
7
+ * engagement stack down (idempotent), writes the RETROSPECTIVE skeleton
8
+ * (whose "learnings → pack candidates" section feeds pack updates), stamps
9
+ * the registry, and moves STATE to closed.
10
+ */
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+ const state = require('./state.cjs');
15
+ const evidence = require('./evidence.cjs');
16
+ const findings = require('./findings.cjs');
17
+ const env = require('./env.cjs');
18
+ const paths = require('./paths.cjs');
19
+ const liveness = require('./liveness.cjs');
20
+
21
+ // REACH-03 (v1.1): early close reasons. `completed` keeps the delivered|retesting
22
+ // gate byte-identical; the early reasons close from ANY status but are
23
+ // owner-gated (--by, --note) and `unreachable` additionally requires an
24
+ // evidence-backed recon/LIVENESS.md verdict — the risk_accepted precedent
25
+ // (owner-gated terminal transitions carry their authority on the verb).
26
+ const EARLY_REASONS = new Set(['unreachable', 'withdrawn', 'owner-abort']);
27
+
28
+ function close(dir, { note = '', reason = 'completed', by = '' } = {}) {
29
+ const status = state.readStatus(dir);
30
+ if (status === 'closed') {
31
+ throw new Error('engagement is already closed');
32
+ }
33
+ let closeReason = 'completed';
34
+ if (reason === 'completed') {
35
+ if (!['delivered', 'retesting'].includes(status)) {
36
+ throw new Error(
37
+ `close requires status delivered|retesting (current: ${status}) — finish the loop first, `
38
+ + 'or close early with --reason unreachable|withdrawn|owner-abort --by <name>'
39
+ );
40
+ }
41
+ } else {
42
+ if (!EARLY_REASONS.has(reason)) {
43
+ throw new Error(`unknown close reason: ${reason} (accepted: completed, unreachable, withdrawn, owner-abort)`);
44
+ }
45
+ if (!String(by || '').trim()) {
46
+ throw new Error(`early close (reason: ${reason}) is owner-gated — pass --by <name> (and --note <why>)`);
47
+ }
48
+ if (reason === 'unreachable') {
49
+ const liv = liveness.readLiveness(dir);
50
+ if (liv.verdict !== 'unreachable') {
51
+ throw new Error(
52
+ `close --reason unreachable refused: recon/LIVENESS.md verdict is '${liv.verdict}' — the target answered; `
53
+ + 'use the normal loop or a different reason'
54
+ );
55
+ }
56
+ for (const eid of liv.evidence) {
57
+ const v = evidence.verify(dir, eid);
58
+ if (!v.ok) {
59
+ throw new Error(`liveness evidence ${eid} does not verify (${v.reason}) — refusing unreachable close`);
60
+ }
61
+ }
62
+ }
63
+ closeReason = reason;
64
+ }
65
+ const chain = evidence.verifyChain(dir);
66
+ if (!chain.ok) {
67
+ throw new Error(`evidence chain broken — close refused (ADR-016): ${chain.reason || `broken at seq ${chain.broken_at}`}`);
68
+ }
69
+ try { env.down(dir); } catch { /* stack already down or never up — close must not fail on it */ }
70
+
71
+ const id = path.basename(dir);
72
+ const g = findings.gate(dir);
73
+ const rows = findings.list(dir);
74
+ const retested = rows.filter((r) => r.status.startsWith('retested'));
75
+ const file = paths.retrospectiveFile(dir);
76
+ fs.writeFileSync(file, [
77
+ `# Retrospective — ${id}`,
78
+ '',
79
+ `Closed: ${new Date().toISOString()}`,
80
+ `Findings: ${g.validated.length} validated, ${g.rejected.length} rejected, ${retested.length} retested (${retested.filter((r) => r.status === 'retested_pass').length} fix-verified)`,
81
+ closeReason !== 'completed' ? `Close reason: ${closeReason} (early close — by ${by})` : '',
82
+ note ? `Close note: ${note}` : '',
83
+ '',
84
+ '## Objectives — met?',
85
+ '',
86
+ '_TODO: human/agent — one paragraph vs PROJECT.md objectives._',
87
+ '',
88
+ '## What worked',
89
+ '',
90
+ '_TODO_',
91
+ '',
92
+ '## What did not (incl. live findings / tooling defects)',
93
+ '',
94
+ '_TODO_',
95
+ '',
96
+ '## Learnings → pack candidates',
97
+ '',
98
+ '_TODO: TTPs/checklist rows worth folding back into packs (M4 learnings',
99
+ 'loop input — write them as pack-ready candidate items, not prose)._',
100
+ '',
101
+ ].filter((l) => l !== '').join('\n'));
102
+
103
+ // registry stamp
104
+ const regFile = path.join(state.pensieveHome(), 'engagements.json');
105
+ let reg = {};
106
+ try { reg = JSON.parse(fs.readFileSync(regFile, 'utf8')); } catch { /* empty */ }
107
+ reg[id] = {
108
+ ...(reg[id] || { id, path: dir }),
109
+ closed_at: new Date().toISOString(),
110
+ findings: { validated: g.validated.length, rejected: g.rejected.length, retested: retested.length },
111
+ ...(closeReason !== 'completed' ? { close_reason: closeReason } : {}),
112
+ };
113
+ fs.mkdirSync(state.pensieveHome(), { recursive: true });
114
+ fs.writeFileSync(regFile, JSON.stringify(reg, null, 2) + '\n');
115
+
116
+ state.setStatus(dir, 'closed', { closeReason });
117
+ if (String(by || '').trim()) {
118
+ const sf = paths.stateFile(dir);
119
+ let st = fs.readFileSync(sf, 'utf8');
120
+ st = fmSet(st, 'closed_by', by.trim());
121
+ if (note) st = fmSet(st, 'close_note', note);
122
+ fs.writeFileSync(sf, st);
123
+ }
124
+ return { closed: id, retrospective: file, findings: reg[id].findings, ...(closeReason !== 'completed' ? { close_reason: closeReason } : {}) };
125
+ }
126
+
127
+ // frontmatter helper (avoids a require cycle: frontmatter.cjs is state-free)
128
+ const fmSet = (text, key, value) => {
129
+ const { parse, set } = require('./frontmatter.cjs');
130
+ return set(text, key, value);
131
+ };
132
+
133
+ module.exports = { close };
@@ -0,0 +1,156 @@
1
+ 'use strict';
2
+ /**
3
+ * config.cjs — engagement config: defaults < config.yaml (engagement root) < PENSIEVE_* env.
4
+ * Unknown keys are ignored with warnings; invalid values fall back to defaults.
5
+ */
6
+
7
+ const fs = require('node:fs');
8
+ const { parseYaml } = require('./frontmatter.cjs');
9
+ const paths = require('./paths.cjs');
10
+
11
+ const SCHEMA = {
12
+ // engagement methodology (web/api/…) — real metadata asked at
13
+ // /pensieve-new-engagement; free-form (the question suggests web/api, but a
14
+ // network or hybrid engagement names its own). Written by init into both
15
+ // config.yaml and STATE.md frontmatter (v0.6 03-01, VIZ-05 / brief 3.5).
16
+ methodology: { def: 'web' },
17
+ methodology_tier: { def: 'DEFAULT', valid: ['CORE', 'DEFAULT', 'DEEP'] },
18
+ model_tier: { def: 'DEFAULT', valid: ['FAST', 'DEFAULT', 'DEEP'] },
19
+ cvss_version: { def: '4.0', valid: ['3.1', '4.0'] },
20
+ proxy: { def: 'http://egress:3128' },
21
+ toolbox_image: { def: 'pensieve-toolbox:local' },
22
+ report_language: { def: 'en' },
23
+ // NPX-05 (v1.2): the autonomy dial, replacing the ADR-009 vocabulary
24
+ // (interactive|semi|yolo — read-side aliased in load()). supervised =
25
+ // every checkpoint is explicit (human or AI-approver) — the old default.
26
+ // semi-autonomous = plan approvals go through the AI approver
27
+ // (ai-approve); scope + report stay human. autonomous = FULL WALK-AWAY
28
+ // (owner decision 2026-12-04, reversing the old non-goal): scope + plans
29
+ // + report checkpoints are auto-RECORDED with provenance
30
+ // approved_by: autonomous-mode — recorded, never skipped — while
31
+ // mechanical gates (evidence chain, report.verify, containment,
32
+ // liveness, close reasons) and blockers (missing creds, WAF,
33
+ // unreachable) still stop and surface. Autonomy is not silence.
34
+ autonomy: { def: 'supervised', valid: ['supervised', 'semi-autonomous', 'autonomous'] },
35
+ // ADR-024 AI-as-approver: the confidence floor for ai-approve. A verdict at
36
+ // or above this is auto-accepted (inside the guardrails); below it the
37
+ // checkpoint escalates to the human (HUMAN-NEEDED.md). Range 0..1; validated
38
+ // in approvals.floorFrom (numeric, so no `valid` list here).
39
+ ai_confidence_floor: { def: 0.8 },
40
+ // v0.6 01-04 (brief 1.11): report.pdf per-engagement overrides. The neutral
41
+ // Pensieve defaults live in assets/branding/config.json; these keys let an
42
+ // engagement rebrand / reclassify the formal PDF without touching code.
43
+ // null brand overrides = "fall back to assets/branding/config.json".
44
+ pdf_classification: { def: 'CONFIDENTIAL' },
45
+ pdf_tlp: { def: 'AMBER' },
46
+ pdf_brand_org: { def: null },
47
+ pdf_brand_accent: { def: null },
48
+ pdf_brand_footer: { def: null },
49
+ // Phase 05 (BOX-01): engagement box level, set by the scoper at scope time.
50
+ // def null = un-scoped; config.load falls back to null on a missing OR invalid
51
+ // value, so the plan-02 scoped->recon gate blocks until a valid box is set.
52
+ box: { def: null, valid: ['white', 'gray', 'black'] },
53
+ // Explicit operator waivers the prerequisite gate (plan 02) reads.
54
+ box_source_waiver: { def: false },
55
+ box_credentials_waiver: { def: null, valid: ['self-provision', 'unauthenticated-only'] },
56
+ // Per-engagement methodology pack switches (pack.enable/disable). First-class
57
+ // so load() surfaces it (and stops the "unknown config key ignored" warning),
58
+ // but `list: true` keeps it OUT of defaults() — it is an additive key present
59
+ // only once a pack is enabled, never a defaulted scalar (SEED-002).
60
+ enabled_packs: { def: [], list: true },
61
+ // Phase 16 (CFG-01): test-swarm wave sizing. max_parallel_items = desired
62
+ // parallel tester workers per wave; test_intensity = the ROE tier whose ceiling
63
+ // CLAMPS it. Numeric max_parallel_items has no `valid` list — it is range-guarded
64
+ // and clamped in maxParallelItems(cfg) (like ai_confidence_floor), never by load.
65
+ max_parallel_items: { def: 3 },
66
+ test_intensity: { def: 'normal', valid: ['low', 'normal', 'high'] },
67
+ };
68
+
69
+ function defaults() {
70
+ const d = {};
71
+ for (const [k, s] of Object.entries(SCHEMA)) {
72
+ if (s.list) continue; // additive list keys (enabled_packs) are not defaulted into cfg
73
+ d[k] = s.def;
74
+ }
75
+ return d;
76
+ }
77
+
78
+ const ENV_MAP = {
79
+ PENSIEVE_PROXY: 'proxy',
80
+ PENSIEVE_CVSS_VERSION: 'cvss_version',
81
+ PENSIEVE_TOOLBOX_IMAGE: 'toolbox_image',
82
+ PENSIEVE_METHODOLOGY_TIER: 'methodology_tier',
83
+ PENSIEVE_AI_CONFIDENCE_FLOOR: 'ai_confidence_floor',
84
+ };
85
+
86
+ function load(engagementDir) {
87
+ const cfg = defaults();
88
+ const warnings = [];
89
+ const file = paths.configFile(engagementDir);
90
+
91
+ // NPX-05 (v1.2): pre-v1.2 autonomy vocabulary, read-side aliased so old
92
+ // engagements load with the semantics their owner picked. yolo -> autonomous
93
+ // is an EXPANSION (full walk-away) — the warning says so, loudly.
94
+ const LEGACY_AUTONOMY = { interactive: 'supervised', semi: 'semi-autonomous', yolo: 'autonomous' };
95
+
96
+ if (fs.existsSync(file)) {
97
+ let parsed = {};
98
+ try {
99
+ parsed = parseYaml(fs.readFileSync(file, 'utf8'));
100
+ } catch (e) {
101
+ warnings.push(`config.yaml unparseable, using defaults (${e.message})`);
102
+ }
103
+ for (const [k, v] of Object.entries(parsed || {})) {
104
+ if (!(k in SCHEMA)) { warnings.push(`unknown config key ignored: ${k}`); continue; }
105
+ const s = SCHEMA[k];
106
+ if (k === 'autonomy' && v !== null && LEGACY_AUTONOMY[v]) {
107
+ const alias = LEGACY_AUTONOMY[v];
108
+ warnings.push(
109
+ `autonomy=${v} is the pre-v1.2 vocabulary — read as ${alias}`
110
+ + (v === 'yolo' ? ' (NOTE: autonomous is now FULL WALK-AWAY — plans AND report are auto-recorded, not scope-only)' : '')
111
+ + '; update config.yaml to supervised | semi-autonomous | autonomous'
112
+ );
113
+ cfg.autonomy = alias;
114
+ continue;
115
+ }
116
+ // null is the legitimate "unset" sentinel (e.g. box def null = un-scoped
117
+ // => gate blocks). Let it fall through to the default silently; only a
118
+ // non-null value outside the valid list is a real invalid-value warning.
119
+ if (v !== null && s.valid && !s.valid.includes(String(v))) {
120
+ warnings.push(`invalid ${k}=${JSON.stringify(v)} (valid: ${s.valid.join('|')}); using default ${s.def}`);
121
+ continue;
122
+ }
123
+ cfg[k] = v === null ? s.def : v;
124
+ }
125
+ }
126
+
127
+ for (const [env, key] of Object.entries(ENV_MAP)) {
128
+ if (process.env[env]) {
129
+ const s = SCHEMA[key];
130
+ if (s.valid && !s.valid.includes(process.env[env])) {
131
+ warnings.push(`invalid env ${env}=${process.env[env]} ignored`);
132
+ continue;
133
+ }
134
+ cfg[key] = process.env[env];
135
+ }
136
+ }
137
+
138
+ return { cfg, warnings };
139
+ }
140
+
141
+ // maxParallelItems(cfg) — CFG-01 ROE no-DoS wave cap. The engagement's desired
142
+ // max_parallel_items CLAMPED by the test_intensity tier ceiling (low->1, normal->3,
143
+ // high->5). Returns min(wanted, tierCap); a hand-edited value above the ceiling is
144
+ // silently capped, never raised (owner-LOCKED 2026-10-11). This is the ONLY reader
145
+ // of cfg.max_parallel_items — the swarm workflow must call this helper, never the
146
+ // raw key, so a hand-edit cannot bypass the cap (Pitfall 2).
147
+ const TIER_CAP = { low: 1, normal: 3, high: 5 };
148
+ function maxParallelItems(cfg) {
149
+ const tier = (cfg && cfg.test_intensity) || 'normal';
150
+ const cap = TIER_CAP[tier] !== undefined ? TIER_CAP[tier] : TIER_CAP.normal;
151
+ const n = parseInt(cfg && cfg.max_parallel_items, 10);
152
+ const wanted = (!Number.isNaN(n) && n >= 1) ? n : 3;
153
+ return Math.min(wanted, cap);
154
+ }
155
+
156
+ module.exports = { defaults, load, SCHEMA, maxParallelItems };
@@ -0,0 +1,91 @@
1
+ 'use strict';
2
+ /**
3
+ * cvss.cjs — deterministic CVSS scoring (ADR-011).
4
+ * The LLM proposes the VECTOR; this module computes score + band. Never LLM math.
5
+ * 3.1: direct spec implementation. 4.0: vendored official calculator
6
+ * (lib/vendor/cvss40.js — FIRST.ORG/Red Hat, BSD-2-Clause, license in repo).
7
+ */
8
+
9
+ const { CVSS40 } = require('./vendor/cvss40.js');
10
+
11
+ function severityBand(score) {
12
+ if (score === 0) return 'None';
13
+ if (score < 4.0) return 'Low';
14
+ if (score < 7.0) return 'Medium';
15
+ if (score < 9.0) return 'High';
16
+ return 'Critical';
17
+ }
18
+
19
+ /* ---------------- CVSS 3.1 ---------------- */
20
+
21
+ const V31 = {
22
+ AV: { N: 0.85, A: 0.62, L: 0.55, P: 0.2 },
23
+ AC: { L: 0.77, H: 0.44 },
24
+ PR: { N: 0.85, L: { U: 0.62, C: 0.68 }, H: { U: 0.27, C: 0.5 } },
25
+ UI: { N: 0.85, R: 0.62 },
26
+ CIA: { H: 0.56, L: 0.22, N: 0 },
27
+ };
28
+
29
+ function roundup31(x) {
30
+ // official roundup: integer arithmetic to avoid float drift
31
+ const i = Math.round(x * 100000);
32
+ if (i % 10000 === 0) return i / 100000;
33
+ return (Math.floor(i / 10000) + 1) / 10;
34
+ }
35
+
36
+ function score31(vector) {
37
+ const parts = vector.split('/');
38
+ if (parts[0] !== 'CVSS:3.1') throw new Error(`invalid CVSS 3.1 vector: ${vector}`);
39
+ const m = {};
40
+ for (const kv of parts.slice(1)) {
41
+ const [k, v] = kv.split(':');
42
+ m[k] = v;
43
+ }
44
+ for (const req of ['AV', 'AC', 'PR', 'UI', 'S', 'C', 'I', 'A']) {
45
+ if (!(req in m)) throw new Error(`CVSS 3.1 vector missing metric ${req}`);
46
+ }
47
+ const scope = m.S;
48
+ if (!['U', 'C'].includes(scope)) throw new Error(`invalid S value: ${m.S}`);
49
+ const pr = V31.PR[m.PR];
50
+ const prVal = typeof pr === 'object' ? pr[scope] : pr;
51
+ if (prVal === undefined) throw new Error(`invalid PR value: ${m.PR}`);
52
+
53
+ const c = V31.CIA[m.C], i = V31.CIA[m.I], a = V31.CIA[m.A];
54
+ if ([c, i, a].some((v) => v === undefined)) throw new Error('invalid C/I/A value');
55
+
56
+ const iss = 1 - (1 - c) * (1 - i) * (1 - a);
57
+ const impact = scope === 'U'
58
+ ? 6.42 * iss
59
+ : 7.52 * (iss - 0.029) - 3.25 * Math.pow(iss - 0.02, 15);
60
+ const exploitability = 8.22 * V31.AV[m.AV] * V31.AC[m.AC] * prVal * V31.UI[m.UI];
61
+
62
+ if (impact <= 0) return 0.0;
63
+ const base = scope === 'U'
64
+ ? roundup31(Math.min(impact + exploitability, 10))
65
+ : roundup31(Math.min(1.08 * (impact + exploitability), 10));
66
+ return base;
67
+ }
68
+
69
+ /* ---------------- CVSS 4.0 ---------------- */
70
+
71
+ function score40(vector) {
72
+ try {
73
+ return new CVSS40(vector).calculateScore();
74
+ } catch (e) {
75
+ throw new Error(`invalid CVSS 4.0 vector: ${e.message}`);
76
+ }
77
+ }
78
+
79
+ /* ---------------- dispatch ---------------- */
80
+
81
+ function score(vector) {
82
+ const v = String(vector || '').trim();
83
+ let version, base;
84
+ if (v.startsWith('CVSS:3.1/')) { version = '3.1'; base = score31(v); }
85
+ else if (v.startsWith('CVSS:4.0/')) { version = '4.0'; base = score40(v); }
86
+ else throw new Error(`unsupported or invalid CVSS vector: ${v || '(empty)'}`);
87
+ const rounded = Math.round(base * 10) / 10;
88
+ return { version, score: rounded, severity: severityBand(rounded) };
89
+ }
90
+
91
+ module.exports = { score, severityBand };
@@ -0,0 +1,272 @@
1
+ 'use strict';
2
+ /**
3
+ * env.cjs — engagement environment: compose rendering, allowlist, proxy env (ADR-003).
4
+ * Topology is the spike-002-validated one: internal pensieve-net (no route out),
5
+ * dual-homed squid egress, toolbox attached to the internal net only.
6
+ * up/down/status shell out to docker compose (integration-tested at M0 exit).
7
+ */
8
+
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { execFileSync } = require('node:child_process');
12
+ const scope = require('./scope.cjs');
13
+ const config = require('./config.cjs');
14
+ const paths = require('./paths.cjs');
15
+ const ids = require('./ids.cjs');
16
+
17
+ function readScopeAst(dir) {
18
+ return scope.parse(fs.readFileSync(paths.scopeFile(dir), 'utf8'));
19
+ }
20
+
21
+ function renderAllowlist(dir) {
22
+ return scope.egressConf(readScopeAst(dir));
23
+ }
24
+
25
+ function renderCompose(dir) {
26
+ const { cfg } = config.load(dir);
27
+ // single shared derivation (ids.composeProjectName, brief 1.8): bin
28
+ // findContainer matches containers by the same name, so the stack can
29
+ // never come up under a name the sdk can't find again.
30
+ const project = ids.composeProjectName(dir);
31
+ return `name: ${project}\n# generated by pensieve-sdk env.render — topology validated in spikes/002-pensieve-net
32
+ services:
33
+ egress:
34
+ image: ubuntu/squid:latest
35
+ entrypoint: ["squid", "-N", "-f", "/etc/squid/squid.conf"]
36
+ volumes:
37
+ - ${path.join(paths.envDir(dir), 'squid.conf')}:/etc/squid/squid.conf:ro
38
+ - ${path.join(paths.envDir(dir), 'allowlist.txt')}:/etc/squid/allowlist.txt
39
+ - ${path.join(paths.envDir(dir), 'provision.txt')}:/etc/squid/provision.txt
40
+ # NOTE: allowlist.txt (target lane) + provision.txt (ADR-014 provisioning lane)
41
+ # mounted rw (not :ro) so a window can widen provision.txt; squid.conf stays :ro
42
+ # (BLOCKER-1: ports can never be widened at runtime, only the rw dstdomain files)
43
+ networks:
44
+ - pensieve-net
45
+ - outbound
46
+ toolbox:
47
+ image: ${cfg.toolbox_image}
48
+ entrypoint: ["sleep", "infinity"]
49
+ # M2 hardening (ADR-015): non-root uid; ALL caps dropped — NET_RAW included,
50
+ # so raw-socket lanes fail CLOSED (spike 002e: they are out of the container
51
+ # model); no-new-privileges; resource ceilings. Provisioning (ADR-014) is the
52
+ # only privileged lane and runs via explicit 'docker exec -u 0' inside the
53
+ # approved window.
54
+ user: "1000:1000"
55
+ security_opt: ["no-new-privileges:true"]
56
+ cap_drop: ["ALL"]
57
+ mem_limit: 4g
58
+ cpus: 2.0
59
+ pids_limit: 512
60
+ networks:
61
+ - pensieve-net
62
+ environment:
63
+ HOME: /tmp
64
+ http_proxy: ${cfg.proxy}
65
+ https_proxy: ${cfg.proxy}
66
+ HTTP_PROXY: ${cfg.proxy}
67
+ HTTPS_PROXY: ${cfg.proxy}
68
+ networks:
69
+ pensieve-net:
70
+ internal: true
71
+ outbound: {}
72
+ `;
73
+ }
74
+
75
+ // BLOCKER-1 (13-CONTEXT, owner-locked 2026-10-08): two-lane egress ACL.
76
+ // TARGET lane — allowlist.txt reachable ONLY on the scope's asset ports.
77
+ // PROVISIONING lane — provision.txt (EMPTY at rest) reachable on 80/443; an
78
+ // ADR-014 window fills it with registry domains, close empties it.
79
+ // 80/443 are NEVER on target_ports (unless they ARE the scoped ports), so at rest
80
+ // nothing reaches the target on 80/443. squid.conf stays :ro — the only runtime-
81
+ // widenable surface is the rw provision.txt dstdomain file.
82
+ function renderSquidConf(dir) {
83
+ const ast = readScopeAst(dir);
84
+ const targetPorts = [...new Set(ast.assets.flatMap((a) => a.ports))].sort((a, b) => a - b);
85
+ // SSL_ports clears the CONNECT-method deny ONLY; domain+port authorization still
86
+ // requires an allow rule to match, so a port here never grants reachability by
87
+ // itself. = scoped target ports ∪ {443}: 443 for the provisioning CONNECT to the
88
+ // registries; a scoped HTTPS target on a non-standard port still gets to tunnel.
89
+ const sslPorts = [...new Set([...targetPorts, 443])].sort((a, b) => a - b);
90
+
91
+ const lines = [
92
+ '# PENSIEVE egress proxy — generated by pensieve-sdk',
93
+ 'http_port 3128',
94
+ 'acl allowed_sites dstdomain "/etc/squid/allowlist.txt"',
95
+ ];
96
+ // ponytail: no scoped ports -> emit no target lane; the target stays unreachable
97
+ // (default-deny). We NEVER inject 80/443 into target_ports to keep it reachable.
98
+ if (targetPorts.length) lines.push(`acl target_ports port ${targetPorts.join(' ')}`);
99
+ lines.push(
100
+ 'acl provision_sites dstdomain "/etc/squid/provision.txt"',
101
+ 'acl provision_ports port 80 443',
102
+ `acl SSL_ports port ${sslPorts.join(' ')}`,
103
+ 'acl CONNECT method CONNECT',
104
+ 'http_access deny CONNECT !SSL_ports'
105
+ );
106
+ if (targetPorts.length) lines.push('http_access allow allowed_sites target_ports');
107
+ lines.push(
108
+ 'http_access allow provision_sites provision_ports',
109
+ 'http_access deny all',
110
+ 'cache deny all',
111
+ 'visible_hostname pensieve-egress'
112
+ );
113
+ return lines.join('\n') + '\n';
114
+ }
115
+
116
+ function renderEnvFiles(dir) {
117
+ const envDir = paths.envDir(dir);
118
+ fs.mkdirSync(envDir, { recursive: true });
119
+ fs.writeFileSync(path.join(envDir, 'squid.conf'), renderSquidConf(dir));
120
+ fs.writeFileSync(path.join(envDir, 'allowlist.txt'), renderAllowlist(dir));
121
+ // provisioning lane: EMPTY at rest -> nothing reachable on 80/443 until a window
122
+ // (ADR-014) fills it; close empties it again.
123
+ fs.writeFileSync(path.join(envDir, 'provision.txt'), '');
124
+ fs.writeFileSync(path.join(envDir, 'compose.pensieve-net.yml'), renderCompose(dir));
125
+ return envDir;
126
+ }
127
+
128
+ function proxyEnv(dir) {
129
+ const { cfg } = config.load(dir);
130
+ return {
131
+ http_proxy: cfg.proxy,
132
+ https_proxy: cfg.proxy,
133
+ HTTP_PROXY: cfg.proxy,
134
+ HTTPS_PROXY: cfg.proxy,
135
+ no_proxy: 'localhost,127.0.0.1',
136
+ NO_PROXY: 'localhost,127.0.0.1',
137
+ };
138
+ }
139
+
140
+ function compose(dir, args) {
141
+ const envDir = paths.envDir(dir);
142
+ if (!fs.existsSync(path.join(envDir, 'compose.pensieve-net.yml'))) renderEnvFiles(dir);
143
+ return execFileSync('docker', ['compose', '-f', path.join(envDir, 'compose.pensieve-net.yml'), ...args], { stdio: 'pipe', encoding: 'utf8' });
144
+ }
145
+
146
+ function up(dir) { renderEnvFiles(dir); return compose(dir, ['up', '-d']); }
147
+ function down(dir) { return compose(dir, ['down']); }
148
+ function status(dir) {
149
+ let out = '';
150
+ try {
151
+ out = compose(dir, ['ps', '--format', 'json']);
152
+ } catch (e) {
153
+ // A missing/unhappy docker is NOT a crash — egress just isn't running
154
+ // (or the egress container was never brought up). Report empty output
155
+ // rather than failing the whole command, so the caller can still inspect
156
+ // the provisioning-window state.
157
+ out = '';
158
+ }
159
+ return { out, warnings: windowWarnings(dir) };
160
+ }
161
+
162
+ function windowWarnings(dir) {
163
+ const w = windowWarning(dir);
164
+ return w ? [w] : [];
165
+ }
166
+
167
+ // ── ADR-014 provisioning-window crash safety (v0.6 01-02, brief 1.7) ─────────
168
+ // While a tools.install provisioning window is open, the PROVISION lane
169
+ // (provision.txt) is WIDENED with the package-registry domains (13-CONTEXT:
170
+ // retargeted off the target allowlist.txt, which a window never touches now). If
171
+ // the process crashes mid-window, provision.txt stays widened. To be crash-safe we
172
+ // record, on the HOST (outside the container): (1) a byte-for-byte pre-window backup
173
+ // of provision.txt, and (2) a marker file naming the install pid. env.status/
174
+ // monitor.scan then warn while the marker is open with no live install pid. On a
175
+ // clean close the marker (and its pid) disappears and provision.txt is emptied.
176
+
177
+ function windowMarkerPath(dir) {
178
+ return path.join(paths.envDir(dir), 'provisioning-window.open');
179
+ }
180
+ function windowBackupPath(dir) {
181
+ return path.join(paths.envDir(dir), 'provision.pre-provision.bak');
182
+ }
183
+
184
+ function openProvisioningWindow(dir, hosts = []) {
185
+ const envDir = paths.envDir(dir);
186
+ const provision = path.join(envDir, 'provision.txt');
187
+ const marker = windowMarkerPath(dir);
188
+ const backup = windowBackupPath(dir);
189
+ if (!fs.existsSync(provision)) {
190
+ throw new Error(
191
+ `provisioning window: ${path.basename(provision)} is missing — run env.render/env.up first (flat layout: ${provision})`
192
+ );
193
+ }
194
+ fs.mkdirSync(envDir, { recursive: true });
195
+ fs.copyFileSync(provision, backup);
196
+ // widen the PROVISION lane only — the target allowlist.txt is never touched.
197
+ fs.writeFileSync(provision, hosts.length ? hosts.join('\n') + '\n' : '');
198
+ fs.writeFileSync(
199
+ marker,
200
+ JSON.stringify({ opened_at: new Date().toISOString(), pid: process.pid }, null, 2)
201
+ );
202
+ return { marker, backup };
203
+ }
204
+
205
+ function closeProvisioningWindow(dir) {
206
+ const marker = windowMarkerPath(dir);
207
+ if (fs.existsSync(marker)) fs.rmSync(marker);
208
+ // restore the provision lane to empty -> 80/443 unreachable again.
209
+ const provision = path.join(paths.envDir(dir), 'provision.txt');
210
+ if (fs.existsSync(provision)) fs.writeFileSync(provision, '');
211
+ return { marker };
212
+ }
213
+
214
+ // Liveness of a numeric pid, without sending any real signal (SIGUSR... 0 =
215
+ // "does this process exist and may I signal it?" — for signal 0, true iff
216
+ // the process exists AND we can signal it; false otherwise, never throws).
217
+ function isPidAlive(pid) {
218
+ if (!Number.isInteger(pid) || pid <= 0) return false;
219
+ try {
220
+ return process.kill(pid, 0) === true;
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+
226
+ function windowStatus(dir) {
227
+ // { open: boolean } — the marker is the source of truth: present = window
228
+ // legitimately in flight (or stale); absent = closed. The test asserts
229
+ // windowStatus(dir).open, so this returns the boolean, not a bare string.
230
+ const open = fs.existsSync(windowMarkerPath(dir));
231
+ return { open, status: open ? 'open' : 'closed' };
232
+ }
233
+
234
+ /**
235
+ * Return a human-readable WARN string when a provisioning window is OPEN but
236
+ * no install process is running (the window is stale — likely a crash).
237
+ * Names the pre-window backup path for restore. Returns null when there is no
238
+ * window to warn about (clean / closed).
239
+ */
240
+ function windowWarning(dir) {
241
+ const markerPath = windowMarkerPath(dir);
242
+ if (!fs.existsSync(markerPath)) return null;
243
+ let marker = { pid: undefined };
244
+ try {
245
+ marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
246
+ } catch {
247
+ /* marker unreadable/corrupt — treat as stale */
248
+ }
249
+ if (isPidAlive(marker.pid)) {
250
+ return null; // an install is still running — the window is legitimately open
251
+ }
252
+ const backupPath = windowBackupPath(dir);
253
+ return (
254
+ `[WARN] provisioning window left open in this engagement (no install running). ` +
255
+ `Restore the pre-window provision list from: ${backupPath} (re-run env.render to re-derive, or copy the backup back to provision.txt, then env.up)`
256
+ );
257
+ }
258
+
259
+ module.exports = {
260
+ renderCompose,
261
+ renderAllowlist,
262
+ renderSquidConf,
263
+ renderEnvFiles,
264
+ proxyEnv,
265
+ up,
266
+ down,
267
+ status,
268
+ windowStatus,
269
+ openProvisioningWindow,
270
+ closeProvisioningWindow,
271
+ windowWarning,
272
+ };