@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.
- package/LICENSE +684 -0
- package/README.md +180 -2
- package/VERSION +1 -0
- package/agents/README.md +16 -0
- package/agents/pensieve-code-auditor.md +58 -0
- package/agents/pensieve-mapper.md +46 -0
- package/agents/pensieve-planner.md +67 -0
- package/agents/pensieve-reconner.md +76 -0
- package/agents/pensieve-reporter.md +61 -0
- package/agents/pensieve-roe-checker.md +46 -0
- package/agents/pensieve-scoper.md +77 -0
- package/agents/pensieve-tester.md +83 -0
- package/agents/pensieve-validator.md +62 -0
- package/bin/pensieve +452 -0
- package/bin/pensieve-installer.cjs +5 -0
- package/commands/pensieve-close.md +6 -0
- package/commands/pensieve-map.md +6 -0
- package/commands/pensieve-new-engagement.md +6 -0
- package/commands/pensieve-pause.md +15 -0
- package/commands/pensieve-plan.md +6 -0
- package/commands/pensieve-progress.md +34 -0
- package/commands/pensieve-quick.md +8 -0
- package/commands/pensieve-recon.md +6 -0
- package/commands/pensieve-report.md +6 -0
- package/commands/pensieve-resume.md +6 -0
- package/commands/pensieve-retest.md +10 -0
- package/commands/pensieve-scope.md +49 -0
- package/commands/pensieve-surface.md +8 -0
- package/commands/pensieve-test.md +6 -0
- package/commands/pensieve-validate.md +6 -0
- package/docker/Dockerfile.pensieve-toolbox +75 -0
- package/docker/compose.pensieve-net.yml +37 -0
- package/docker/squid.conf.template +21 -0
- package/package.json +39 -4
- package/packs/ad/ad-killchain/checklist.md +64 -0
- package/packs/ad/ad-killchain/pack.yaml +19 -0
- package/packs/cloud/cloud-cis/checklist.md +66 -0
- package/packs/cloud/cloud-cis/pack.yaml +20 -0
- package/packs/fintech/practice-core/checklist.md +33 -0
- package/packs/fintech/practice-core/learnings.md +5 -0
- package/packs/fintech/practice-core/pack.yaml +18 -0
- package/packs/infra/ptes-infra/checklist.md +22 -0
- package/packs/infra/ptes-infra/pack.yaml +19 -0
- package/packs/mobile/owasp-masvs/checklist.md +80 -0
- package/packs/mobile/owasp-masvs/pack.yaml +20 -0
- package/packs/owasp-api-v4/checklist.md +85 -0
- package/packs/owasp-api-v4/learnings.md +6 -0
- package/packs/owasp-api-v4/pack.yaml +23 -0
- package/packs/owasp-api-v4/runbooks/API1/SKILL.md +66 -0
- package/packs/owasp-api-v4/runbooks/API10/SKILL.md +67 -0
- package/packs/owasp-api-v4/runbooks/API2/SKILL.md +129 -0
- package/packs/owasp-api-v4/runbooks/API3/SKILL.md +55 -0
- package/packs/owasp-api-v4/runbooks/API4/SKILL.md +59 -0
- package/packs/owasp-api-v4/runbooks/API5/SKILL.md +60 -0
- package/packs/owasp-api-v4/runbooks/API6/SKILL.md +63 -0
- package/packs/owasp-api-v4/runbooks/API7/SKILL.md +70 -0
- package/packs/owasp-api-v4/runbooks/API8/SKILL.md +72 -0
- package/packs/owasp-api-v4/runbooks/API9/SKILL.md +66 -0
- package/packs/thickclient/thickclient-core/checklist.md +60 -0
- package/packs/thickclient/thickclient-core/pack.yaml +24 -0
- package/packs/web/asvs-l2/checklist.md +50 -0
- package/packs/web/asvs-l2/learnings.md +6 -0
- package/packs/web/asvs-l2/pack.yaml +19 -0
- package/packs/web/asvs-l2/runbooks/V2-AUTH-ENUM/SKILL.md +75 -0
- package/packs/web/asvs-l2/runbooks/V2-AUTH-LIVE/SKILL.md +78 -0
- package/packs/web/asvs-l2/runbooks/V2-AUTH-MFA/SKILL.md +76 -0
- package/packs/web/asvs-l2/runbooks/V2-AUTH-RATE/SKILL.md +72 -0
- package/packs/web/owasp-testing-checklist/checklist.md +52 -0
- package/packs/web/owasp-testing-checklist/learnings.md +47 -0
- package/packs/web/owasp-testing-checklist/pack.yaml +21 -0
- package/packs/web/unauth-perimeter/checklist.md +72 -0
- package/packs/web/unauth-perimeter/pack.yaml +18 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-01/SKILL.md +60 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-02/SKILL.md +63 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-03/SKILL.md +62 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-04/SKILL.md +75 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-05/SKILL.md +66 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-06/SKILL.md +59 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-07/SKILL.md +56 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-08/SKILL.md +57 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-09/SKILL.md +62 -0
- package/packs/web/unauth-perimeter/runbooks/PERIM-10/SKILL.md +60 -0
- package/packs/whitebox/code-audit-core/checklist.md +36 -0
- package/packs/whitebox/code-audit-core/learnings.md +6 -0
- package/packs/whitebox/code-audit-core/pack.yaml +14 -0
- package/prompts/orchestrator-core.md +52 -0
- package/reference/attack-playbooks.md +57 -0
- package/reference/otp-relay.md +98 -0
- package/reference/param-profiles.md +48 -0
- package/reference/templates/FINDING.md +97 -0
- package/reference/tool-selection.md +64 -0
- package/reference/vulnerability-finding-standard.md +80 -0
- package/runtimes/hermes/hooks/injection-scan.py +290 -0
- package/runtimes/hermes/hooks/scope-guard.py +136 -0
- package/skills/pensieve/SKILL.md +134 -0
- package/skills/pensieve-close/SKILL.md +31 -0
- package/skills/pensieve-map/SKILL.md +25 -0
- package/skills/pensieve-new-engagement/SKILL.md +28 -0
- package/skills/pensieve-pause/SKILL.md +22 -0
- package/skills/pensieve-plan/SKILL.md +39 -0
- package/skills/pensieve-progress/SKILL.md +35 -0
- package/skills/pensieve-quick/SKILL.md +47 -0
- package/skills/pensieve-recon/SKILL.md +30 -0
- package/skills/pensieve-report/SKILL.md +46 -0
- package/skills/pensieve-resume/SKILL.md +33 -0
- package/skills/pensieve-retest/SKILL.md +35 -0
- package/skills/pensieve-scope/SKILL.md +35 -0
- package/skills/pensieve-surface/SKILL.md +36 -0
- package/skills/pensieve-test/SKILL.md +35 -0
- package/skills/pensieve-validate/SKILL.md +28 -0
- package/skills/pensieve-wiki/SKILL.md +39 -0
- package/src/installer/cli.cjs +209 -0
- package/src/installer/home.cjs +155 -0
- package/src/installer/runtimes.cjs +276 -0
- package/src/installer/uninstall.cjs +342 -0
- package/src/pensieve-sdk/bin/pensieve-sdk.cjs +1045 -0
- package/src/pensieve-sdk/lib/agent-translate.cjs +50 -0
- package/src/pensieve-sdk/lib/approvals.cjs +408 -0
- package/src/pensieve-sdk/lib/audit.cjs +290 -0
- package/src/pensieve-sdk/lib/checklist.cjs +337 -0
- package/src/pensieve-sdk/lib/clientlist.cjs +814 -0
- package/src/pensieve-sdk/lib/close.cjs +133 -0
- package/src/pensieve-sdk/lib/config.cjs +156 -0
- package/src/pensieve-sdk/lib/cvss.cjs +91 -0
- package/src/pensieve-sdk/lib/env.cjs +272 -0
- package/src/pensieve-sdk/lib/evidence.cjs +217 -0
- package/src/pensieve-sdk/lib/findings.cjs +1096 -0
- package/src/pensieve-sdk/lib/frontmatter.cjs +178 -0
- package/src/pensieve-sdk/lib/graph.cjs +607 -0
- package/src/pensieve-sdk/lib/ids.cjs +63 -0
- package/src/pensieve-sdk/lib/init.cjs +79 -0
- package/src/pensieve-sdk/lib/liveness.cjs +176 -0
- package/src/pensieve-sdk/lib/loop.cjs +619 -0
- package/src/pensieve-sdk/lib/migrate.cjs +57 -0
- package/src/pensieve-sdk/lib/monitor.cjs +69 -0
- package/src/pensieve-sdk/lib/pack.cjs +607 -0
- package/src/pensieve-sdk/lib/paths.cjs +73 -0
- package/src/pensieve-sdk/lib/pdf.cjs +291 -0
- package/src/pensieve-sdk/lib/recon.cjs +296 -0
- package/src/pensieve-sdk/lib/renderers/__pycache__/formal_report.cpython-314.pyc +0 -0
- package/src/pensieve-sdk/lib/renderers/formal_report.py +608 -0
- package/src/pensieve-sdk/lib/report.cjs +1135 -0
- package/src/pensieve-sdk/lib/runbook.cjs +124 -0
- package/src/pensieve-sdk/lib/sarif.cjs +154 -0
- package/src/pensieve-sdk/lib/scope.cjs +621 -0
- package/src/pensieve-sdk/lib/security.cjs +61 -0
- package/src/pensieve-sdk/lib/skills.cjs +193 -0
- package/src/pensieve-sdk/lib/state.cjs +610 -0
- package/src/pensieve-sdk/lib/subagent.cjs +658 -0
- package/src/pensieve-sdk/lib/target.cjs +149 -0
- package/src/pensieve-sdk/lib/tools.cjs +66 -0
- package/src/pensieve-sdk/lib/vault.cjs +122 -0
- package/src/pensieve-sdk/lib/vendor/cvss40.LICENSE +22 -0
- package/src/pensieve-sdk/lib/vendor/cvss40.js +1208 -0
- package/src/pensieve-sdk/package.json +11 -0
- package/templates/ACCOUNTS.md +35 -0
- package/templates/ATTACK-SURFACE.md +30 -0
- package/templates/FINDING.md +43 -0
- package/templates/PLAN.md +33 -0
- package/templates/PROJECT.md +29 -0
- package/templates/ROE.md +50 -0
- package/templates/RUN-LOG.md +19 -0
- package/templates/SCOPE.md +32 -0
- package/templates/VALIDATION.md +62 -0
- package/templates/report/REPORT.md +49 -0
- package/workflows/close.md +34 -0
- package/workflows/map.md +39 -0
- package/workflows/new-engagement.md +37 -0
- package/workflows/plan.md +45 -0
- package/workflows/progress.md +28 -0
- package/workflows/quick.md +67 -0
- package/workflows/recon.md +87 -0
- package/workflows/report.md +51 -0
- package/workflows/resume.md +26 -0
- package/workflows/retest.md +53 -0
- package/workflows/scope.md +47 -0
- package/workflows/surface.md +29 -0
- package/workflows/test.md +95 -0
- package/workflows/validate.md +34 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* monitor.cjs — WAF / rate-limit detection at the egress choke point (M2, ADR-017).
|
|
4
|
+
* Squid sees every response the engagement produces; agents and tools cannot
|
|
5
|
+
* bypass it. Parsing the proxy access log gives tool-agnostic detection:
|
|
6
|
+
* no agent cooperation required, no per-tool plugins.
|
|
7
|
+
*
|
|
8
|
+
* Signals per origin host (status = origin status after '/' in squid code):
|
|
9
|
+
* - any 429 -> rate_limited
|
|
10
|
+
* - >=50% 403 over a window of >=10 requests -> waf_blocking
|
|
11
|
+
* - 503 bursts (>=3) -> origin_overload (soft)
|
|
12
|
+
* scanAccessLog returns per-host stats; detectAlerts turns stats into
|
|
13
|
+
* actionable alerts. CLI writes them to env/waf-alerts.log (engagement root).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const WINDOW_MIN_FOR_RATIO = 10;
|
|
17
|
+
|
|
18
|
+
/** parse one squid access.log line -> {host, status} | null */
|
|
19
|
+
function parseLine(line) {
|
|
20
|
+
// squid native format: ts elapsed client code/status bytes method URL ident hierarchy type
|
|
21
|
+
const m = /^\s*\d+\.\d+\s+\d+\s+\S+\s+([A-Z_]+)\/(\d{3})\s+\d+\s+\S+\s+(\S+)/.exec(line);
|
|
22
|
+
if (!m) return null;
|
|
23
|
+
const status = parseInt(m[2], 10);
|
|
24
|
+
let host = null;
|
|
25
|
+
try { host = new URL(m[3]).hostname || null; } catch { /* not a URL form */ }
|
|
26
|
+
if (!host) {
|
|
27
|
+
// CONNECT lines carry host:port instead of a URL
|
|
28
|
+
const cm = /^([^:/]+)/.exec(m[3]);
|
|
29
|
+
host = cm ? cm[1] : null;
|
|
30
|
+
}
|
|
31
|
+
return host ? { host, status } : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function scanAccessLog(text) {
|
|
35
|
+
const stats = new Map();
|
|
36
|
+
for (const line of String(text).split('\n')) {
|
|
37
|
+
const r = parseLine(line);
|
|
38
|
+
if (!r) continue;
|
|
39
|
+
const s = stats.get(r.host) || { host: r.host, total: 0, statuses: {} };
|
|
40
|
+
s.total++;
|
|
41
|
+
s.statuses[r.status] = (s.statuses[r.status] || 0) + 1;
|
|
42
|
+
stats.set(r.host, s);
|
|
43
|
+
}
|
|
44
|
+
return [...stats.values()];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function detectAlerts(stats) {
|
|
48
|
+
const alerts = [];
|
|
49
|
+
for (const s of stats) {
|
|
50
|
+
const c429 = s.statuses['429'] || 0;
|
|
51
|
+
const c403 = s.statuses['403'] || 0;
|
|
52
|
+
const c503 = s.statuses['503'] || 0;
|
|
53
|
+
if (c429 >= 1) {
|
|
54
|
+
alerts.push({ host: s.host, signal: 'rate_limited', count: c429,
|
|
55
|
+
detail: `${c429}x HTTP 429 from ${s.host} — back off (reduce concurrency, add delay); continuing risks IP burn` });
|
|
56
|
+
}
|
|
57
|
+
if (s.total >= WINDOW_MIN_FOR_RATIO && c403 / s.total >= 0.5) {
|
|
58
|
+
alerts.push({ host: s.host, signal: 'waf_blocking', count: c403,
|
|
59
|
+
detail: `${c403}/${s.total} responses are 403 from ${s.host} — WAF/signature block likely; change approach or pause` });
|
|
60
|
+
}
|
|
61
|
+
if (c503 >= 3) {
|
|
62
|
+
alerts.push({ host: s.host, signal: 'origin_overload', count: c503,
|
|
63
|
+
detail: `${c503}x HTTP 503 from ${s.host} — target may be rate-shedding or falling over; slow down` });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return alerts;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = { scanAccessLog, detectAlerts, parseLine };
|
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* pack.cjs — methodology packs (ADR-002).
|
|
4
|
+
* Pack dir: packs/<area>/<slug>/ with pack.yaml + checklist.md.
|
|
5
|
+
* checklist.md: status table (agents mark it) + per-item "- test:" sections.
|
|
6
|
+
* ingest: copy a user source (dir) into packs/custom/<slug>/ with validation.
|
|
7
|
+
*
|
|
8
|
+
* MULTI-ROOT (31-01 / SCOP-03): pack resolution MERGES the built-in repo
|
|
9
|
+
* `packs/` tree with the USER root `$PENSIEVE_HOME/packs/` (PENSIEVE_HOME env
|
|
10
|
+
* override respected via paths.pensieveHome(); default ~/.pensieve/packs — a
|
|
11
|
+
* user-made pack survives reinstalls). ONE resolver, everywhere: every
|
|
12
|
+
* consumer (load/list/enable/ingest/learnings, checklist.list/coverage/gate,
|
|
13
|
+
* runbook lint/find, subagent briefs) resolves a slug through roots()/
|
|
14
|
+
* resolveDir() below — identical behavior from either root.
|
|
15
|
+
*
|
|
16
|
+
* Fail-closed collision: a user-root slug that collides with a BUILT-IN repo
|
|
17
|
+
* slug is REFUSED with BOTH filesystem paths named — never silently shadowed.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const fs = require('node:fs');
|
|
21
|
+
const path = require('node:path');
|
|
22
|
+
const fm = require('./frontmatter.cjs');
|
|
23
|
+
const paths = require('./paths.cjs');
|
|
24
|
+
const { parseYaml } = fm;
|
|
25
|
+
|
|
26
|
+
// ---- the ONE multi-root resolver (31-01 / SCOP-03) ---------------------------
|
|
27
|
+
|
|
28
|
+
/** built-in repo packs root: explicit primary (tests/consumers pass their
|
|
29
|
+
* packsRoot), else PENSIEVE_PACKS_DIR, else <repo>/packs — the same default
|
|
30
|
+
* the CLI and checklist.gate use. */
|
|
31
|
+
function repoRoot(primary) {
|
|
32
|
+
return primary ? path.resolve(primary)
|
|
33
|
+
: (process.env.PENSIEVE_PACKS_DIR || path.resolve(__dirname, '../../../packs'));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** user pack root: $PENSIEVE_HOME/packs (env override via paths.pensieveHome) */
|
|
37
|
+
function userRoot() {
|
|
38
|
+
return path.join(paths.pensieveHome(), 'packs');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** resolution order: built-in root first, then the user root (deduped) */
|
|
42
|
+
function roots(primary) {
|
|
43
|
+
const repo = repoRoot(primary);
|
|
44
|
+
const user = userRoot();
|
|
45
|
+
return repo === user ? [repo] : [repo, user];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** every root that carries this slug (the slug DIRECTORY exists), repo first.
|
|
49
|
+
* Identity is the directory — pack.yaml is load()'s validation, and runbook
|
|
50
|
+
* trees (skills/brief/lint) resolve by presence exactly as they did
|
|
51
|
+
* single-root. A slug dir in BOTH roots is a collision (fail-closed).
|
|
52
|
+
* Traversal-safe: a slug that escapes its root resolves to nothing. */
|
|
53
|
+
function resolveDirs(primary, slug) {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const r of roots(primary)) {
|
|
56
|
+
const dir = path.join(r, slug);
|
|
57
|
+
// confinement: the slug must resolve INSIDE the root it came from
|
|
58
|
+
if (dir !== r && !dir.startsWith(r + path.sep)) continue;
|
|
59
|
+
if (fs.existsSync(dir)) out.push(dir);
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** collision refusal: names BOTH filesystem paths; `.collision` carries them
|
|
65
|
+
* machine-readably (the CLI passes them through unsanitized — the two paths
|
|
66
|
+
* ARE the remedy, and security.sanitizeError would redact both to [path]). */
|
|
67
|
+
function collisionError(slug, dirs) {
|
|
68
|
+
const e = new Error(
|
|
69
|
+
`pack slug collision: "${slug}" exists in BOTH pack roots — ${dirs[0]} and ${dirs[1]} `
|
|
70
|
+
+ '— rename or remove one (a user pack never shadows built-in methodology)'
|
|
71
|
+
);
|
|
72
|
+
e.collision = { slug, paths: dirs };
|
|
73
|
+
return e;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** resolve ONE slug to ONE dir: 0 hits -> not found; ambiguity -> collision
|
|
77
|
+
* refusal (fail-closed); else the single dir, whichever root it lives in. */
|
|
78
|
+
function resolveDir(primary, slug) {
|
|
79
|
+
const dirs = resolveDirs(primary, slug);
|
|
80
|
+
// message carries BOTH legacy phrasings (load's "pack not found" and the
|
|
81
|
+
// learnings lane's "unknown pack") plus the roots actually searched
|
|
82
|
+
if (dirs.length === 0) {
|
|
83
|
+
throw new Error(`pack not found (unknown pack): ${slug} — searched: ${roots(primary).join(', ')}`);
|
|
84
|
+
}
|
|
85
|
+
if (dirs.length > 1) throw collisionError(slug, dirs);
|
|
86
|
+
return dirs[0];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function load(root, slug) {
|
|
90
|
+
const dir = resolveDir(root, slug);
|
|
91
|
+
const metaFile = path.join(dir, 'pack.yaml');
|
|
92
|
+
if (!fs.existsSync(metaFile)) throw new Error(`pack not found: ${slug} (no pack.yaml in ${dir})`);
|
|
93
|
+
const meta = parseYaml(fs.readFileSync(metaFile, 'utf8'));
|
|
94
|
+
const clFile = path.join(dir, meta.checklist || 'checklist.md');
|
|
95
|
+
const checklist = fs.existsSync(clFile) ? parseChecklist(fs.readFileSync(clFile, 'utf8')) : [];
|
|
96
|
+
return { slug, meta, checklist };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parseChecklist(text) {
|
|
100
|
+
const items = [];
|
|
101
|
+
const byId = new Map();
|
|
102
|
+
let cur = null;
|
|
103
|
+
const HEADER = new Set(['test', 'title', 'category', 'control', 'check', 'description', 'name']);
|
|
104
|
+
for (const line of String(text).split('\n')) {
|
|
105
|
+
const h = /^##\s+([A-Z][A-Za-z0-9._-]*)\s*[—–-]\s*(.+)$/.exec(line);
|
|
106
|
+
if (h) {
|
|
107
|
+
// heading sections carry execution detail; if a table row already
|
|
108
|
+
// registered this id, enrich it instead of duplicating
|
|
109
|
+
const existing = byId.get(h[1]);
|
|
110
|
+
cur = existing || { id: h[1], title: h[2].trim(), tests: [] };
|
|
111
|
+
if (!existing) { items.push(cur); byId.set(h[1], cur); }
|
|
112
|
+
if (h[2].trim()) cur.title = h[2].trim();
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const t = /^-\s+test:\s*(.+)$/.exec(line.trim());
|
|
116
|
+
if (t && cur) { cur.tests.push(t[1].trim()); continue; }
|
|
117
|
+
// table-format rows: | ID | title | status… | — SAMA-style user checklists
|
|
118
|
+
const row = /^\|\s*([A-Z][A-Za-z0-9._-]*(?:-[A-Za-z0-9._-]+)*)\s*\|\s*([^|]+?)\s*\|/.exec(line.trim());
|
|
119
|
+
if (row && row[1] !== 'ID' && !HEADER.has(row[2].trim().toLowerCase()) && !byId.has(row[1])) {
|
|
120
|
+
cur = { id: row[1], title: row[2].trim(), tests: [] };
|
|
121
|
+
items.push(cur);
|
|
122
|
+
byId.set(row[1], cur);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return items;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function walk(root, prefix = '') {
|
|
129
|
+
const out = [];
|
|
130
|
+
for (const entry of fs.readdirSync(path.join(root, prefix), { withFileTypes: true })) {
|
|
131
|
+
if (entry.name.startsWith('.') || entry.name === 'README.md') continue;
|
|
132
|
+
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
133
|
+
if (entry.isDirectory()) {
|
|
134
|
+
if (fs.existsSync(path.join(root, rel, 'pack.yaml'))) out.push(rel);
|
|
135
|
+
else out.push(...walk(root, rel));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** parse a pack's meta straight from ONE dir (no root resolution) — list() uses
|
|
142
|
+
* this so a colliding slug can still be LISTED (marked, both paths named)
|
|
143
|
+
* instead of load()'s refusal. */
|
|
144
|
+
function loadMetaFrom(dir) {
|
|
145
|
+
return parseYaml(fs.readFileSync(path.join(dir, 'pack.yaml'), 'utf8'));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function list(primary) {
|
|
149
|
+
const rootList = roots(primary);
|
|
150
|
+
const out = [];
|
|
151
|
+
const seen = new Map(); // slug -> row (repo-first; user rows merge in)
|
|
152
|
+
for (let i = 0; i < rootList.length; i++) {
|
|
153
|
+
const root = rootList[i];
|
|
154
|
+
const label = i === 0 ? 'repo' : 'user';
|
|
155
|
+
if (!fs.existsSync(root)) continue;
|
|
156
|
+
for (const slug of walk(root)) {
|
|
157
|
+
const dir = path.join(root, slug);
|
|
158
|
+
const existing = seen.get(slug);
|
|
159
|
+
if (existing) {
|
|
160
|
+
// fail-closed collision, made visible (never silently shadowed):
|
|
161
|
+
// one row, both paths named, unenablable (enable/load refuse).
|
|
162
|
+
existing.collision = true;
|
|
163
|
+
existing.paths = [existing.path, dir];
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const meta = loadMetaFrom(dir);
|
|
167
|
+
seen.set(slug, { ...meta, slug, root: label, path: dir }); // path is authoritative; pack.yaml's slug is display-only
|
|
168
|
+
out.push(seen.get(slug));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
175
|
+
|
|
176
|
+
function ingest(root, sourceDir, slug) {
|
|
177
|
+
if (!SLUG_RE.test(slug)) throw new Error(`invalid pack slug: ${slug}`);
|
|
178
|
+
if (!fs.existsSync(path.join(sourceDir, 'pack.yaml'))) {
|
|
179
|
+
throw new Error(`source has no pack.yaml: ${sourceDir}`);
|
|
180
|
+
}
|
|
181
|
+
const dest = path.join(root, 'custom', slug);
|
|
182
|
+
if (fs.existsSync(dest)) throw new Error(`pack already exists: custom/${slug}`);
|
|
183
|
+
// multi-root (31-01): refuse to MINT a collision — the same slug living in
|
|
184
|
+
// the other root would be ambiguous forever after (fail-closed, both named).
|
|
185
|
+
const others = resolveDirs(root, `custom/${slug}`).filter((d) => d !== dest);
|
|
186
|
+
if (others.length > 0) throw collisionError(`custom/${slug}`, [dest, ...others]);
|
|
187
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
188
|
+
for (const entry of fs.readdirSync(sourceDir)) {
|
|
189
|
+
fs.copyFileSync(path.join(sourceDir, entry), path.join(dest, entry));
|
|
190
|
+
}
|
|
191
|
+
// validate it loads
|
|
192
|
+
load(root, `custom/${slug}`);
|
|
193
|
+
return { slug: `custom/${slug}`, path: dest };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---- scaffold (31-02 / SCOP-02): the authoring half --------------------------
|
|
197
|
+
|
|
198
|
+
/** scaffold slug shape: exactly `<area>/<name>` — the PACK-FORMAT v1.0 path
|
|
199
|
+
* convention (packs/<area>/<slug>/). Each segment mints the same safe
|
|
200
|
+
* charset ingest uses; it is an ALLOWLIST, so traversal (`..`), extra
|
|
201
|
+
* separators, dotfiles, whitespace and shell metacharacters all fail by
|
|
202
|
+
* construction. */
|
|
203
|
+
const SLUG_SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
204
|
+
|
|
205
|
+
function parseScaffoldSlug(slug) {
|
|
206
|
+
const parts = String(slug).split('/');
|
|
207
|
+
if (parts.length !== 2) {
|
|
208
|
+
throw new Error(`invalid pack slug: ${slug} — expected the area/name shape (e.g. custom/my-checks)`);
|
|
209
|
+
}
|
|
210
|
+
for (const p of parts) {
|
|
211
|
+
if (!SLUG_SEGMENT_RE.test(p)) {
|
|
212
|
+
throw new Error(`invalid pack slug: ${slug} — segment "${p}" must be [a-z0-9-] (unsafe path characters refused)`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { area: parts[0], name: parts[1] };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** pack.yaml skeleton — PACK-FORMAT v1.0 (FROZEN) EXACTLY: the ten spec
|
|
219
|
+
* fields, in spec order, no additions. TODO guidance lives in comments
|
|
220
|
+
* (prose), never in a machine-parsed value: the UNTOUCHED file must load,
|
|
221
|
+
* list and lint as-is. */
|
|
222
|
+
function scaffoldYaml(slug, leaf) {
|
|
223
|
+
return `# Scaffolded by \`pensieve-sdk pack.scaffold\` — a valid PACK-FORMAT v1.0 skeleton.
|
|
224
|
+
# TODO(you): fill in real methodology. The skeleton is VALID AS-IS (it loads,
|
|
225
|
+
# lists, lints and enumerates untouched), so you edit content, never format.
|
|
226
|
+
# docs/PACK-FORMAT.md is the frozen contract.
|
|
227
|
+
|
|
228
|
+
# TODO(you): a real human title (display-only).
|
|
229
|
+
name: ${leaf} (scaffolded — replace with a real human title)
|
|
230
|
+
|
|
231
|
+
# THE PATH IS THE SLUG — packs/<area>/<slug>/ is the identifier everywhere
|
|
232
|
+
# (pack.enable, config.yaml enabled_packs, tools.check). pack.cjs treats the
|
|
233
|
+
# path as authoritative; this field must equal the pack's path under packs/
|
|
234
|
+
# and is display/documentation-only.
|
|
235
|
+
slug: ${slug}
|
|
236
|
+
|
|
237
|
+
version: "1.0"
|
|
238
|
+
|
|
239
|
+
# DEFAULT applies by default to matching surfaces; DEEP is enabled explicitly
|
|
240
|
+
# (regulated engagements).
|
|
241
|
+
tier: DEFAULT
|
|
242
|
+
|
|
243
|
+
# TODO(you): your surface signals — any of api, web, gray, black, white,
|
|
244
|
+
# mobile, infra, cloud (from recon). Omit applies_to entirely for a
|
|
245
|
+
# surface-agnostic pack.
|
|
246
|
+
applies_to:
|
|
247
|
+
- web
|
|
248
|
+
|
|
249
|
+
# TODO(you): where the methodology comes from (URL or note).
|
|
250
|
+
source: internal — scaffolded skeleton, replace with the methodology source
|
|
251
|
+
|
|
252
|
+
# TODO(you): license of the source material (matters when adapting
|
|
253
|
+
# third-party checklists).
|
|
254
|
+
license: internal — original content
|
|
255
|
+
|
|
256
|
+
# TODO(you): the tools this pack needs, one row per tool —
|
|
257
|
+
# name|lane|kind|spec — lane A = toolbox (in the container), B = host
|
|
258
|
+
# exception (ADR-013); kind = builtin | apt | pip | host-manual; spec =
|
|
259
|
+
# binary or package name. The two rows below are safe examples.
|
|
260
|
+
tools:
|
|
261
|
+
- curl|A|builtin|curl
|
|
262
|
+
- jq|A|builtin|jq
|
|
263
|
+
|
|
264
|
+
checklist: checklist.md
|
|
265
|
+
|
|
266
|
+
# TODO(you): one-line usage guidance for agents.
|
|
267
|
+
notes: Scaffolded skeleton for ${slug} — replace the example items with real checks before use.
|
|
268
|
+
`;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** checklist.md skeleton — the two parsed layers (table + per-ID `- test:`
|
|
272
|
+
* sections) with 2-3 obviously-placeholder example rows (ITEM-01..03) in the
|
|
273
|
+
* exact table syntax consumers parse. */
|
|
274
|
+
function scaffoldChecklist(slug, leaf) {
|
|
275
|
+
return `# ${leaf} — engagement checklist (SCAFFOLD)
|
|
276
|
+
|
|
277
|
+
TODO(you): replace this intro and the three EXAMPLE items below with your
|
|
278
|
+
real methodology. The skeleton is valid as-is — \`pensieve-sdk checklist.list
|
|
279
|
+
--pack ${slug}\` already enumerates ITEM-01..03; rename the IDs to your scheme
|
|
280
|
+
(e.g. PERIM-01), keep one \`## <ID> — <title>\` section per table row, and make
|
|
281
|
+
every \`- test:\` row a verifiable check (name the expected evidence when it
|
|
282
|
+
helps). docs/PACK-FORMAT.md is the frozen contract.
|
|
283
|
+
|
|
284
|
+
| ID | Category | Status | Finding |
|
|
285
|
+
|----|----------|--------|---------|
|
|
286
|
+
| ITEM-01 | Example check lane — replace with a real category | | |
|
|
287
|
+
| ITEM-02 | Second example lane — delete or rename me | | |
|
|
288
|
+
| ITEM-03 | Third example lane — delete or rename me | | |
|
|
289
|
+
|
|
290
|
+
## ITEM-01 — Example check lane (replace with a real title)
|
|
291
|
+
|
|
292
|
+
TODO(you): write the atomic tests for this item — each row is one verifiable
|
|
293
|
+
check an agent runs and marks.
|
|
294
|
+
|
|
295
|
+
- test: curl -skI "https://$TARGET/" and record the security-relevant response header lines (example — replace with your real check)
|
|
296
|
+
- test: jq-parse the body of one deep route and record its shape (example — replace with your real check)
|
|
297
|
+
|
|
298
|
+
## ITEM-02 — Second example lane (replace with a real title)
|
|
299
|
+
|
|
300
|
+
- test: capture one baseline request/response pair through the engagement proxy and record what normal looks like (example — replace)
|
|
301
|
+
|
|
302
|
+
## ITEM-03 — Third example lane (replace with a real title)
|
|
303
|
+
|
|
304
|
+
- test: diff the baseline against one variant request and record any observable state change (example — replace)
|
|
305
|
+
`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** runbooks/ITEM-01/SKILL.md stub — RUNBOOK-FORMAT.md required frontmatter
|
|
309
|
+
* keys + all four body sections, so the UNTOUCHED skeleton lints clean.
|
|
310
|
+
* TODO guidance stays in body prose, never in a parsed field. */
|
|
311
|
+
function scaffoldRunbook(slug) {
|
|
312
|
+
return `---
|
|
313
|
+
name: ITEM-01 — Example check lane (replace with a real title)
|
|
314
|
+
item: ITEM-01
|
|
315
|
+
description: Example runbook stub — replace with a one-line summary of what this item verifies on the target.
|
|
316
|
+
agents: [pensieve-tester]
|
|
317
|
+
pack: ${slug}
|
|
318
|
+
---
|
|
319
|
+
|
|
320
|
+
## Tools
|
|
321
|
+
|
|
322
|
+
curl, jq
|
|
323
|
+
|
|
324
|
+
## Steps
|
|
325
|
+
|
|
326
|
+
TODO(you): concrete, copy-pasteable commands — real flags, placeholder targets
|
|
327
|
+
only ($TARGET, $TOKEN_A, $TOKEN_B; never a real client host). Not prose hints.
|
|
328
|
+
|
|
329
|
+
\`\`\`sh
|
|
330
|
+
export PROXY=http://127.0.0.1:8080 # engagement proxy from PROJECT.md
|
|
331
|
+
export TS=$(date -u +%Y%m%dT%H%M%SZ)
|
|
332
|
+
|
|
333
|
+
# 1. Example probe — replace with the real procedure for ITEM-01.
|
|
334
|
+
curl -sk -x "$PROXY" -D "item01-headers-$TS.txt" -o /dev/null "https://$TARGET/"
|
|
335
|
+
\`\`\`
|
|
336
|
+
|
|
337
|
+
## Expected Evidence
|
|
338
|
+
|
|
339
|
+
TODO(you): the artifact that proves the step ran and lands in the evidence
|
|
340
|
+
ledger — e.g. the saved item01-headers capture plus the header lines judged.
|
|
341
|
+
|
|
342
|
+
## Pass/Fail
|
|
343
|
+
|
|
344
|
+
TODO(you): an explicit, decidable rule — e.g. FINDING if a protective control
|
|
345
|
+
is absent on the captured lines; PASS if it is present on every probe.
|
|
346
|
+
`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** learnings.md skeleton (OPTIONAL file) — the ADR-022 candidate-pool header
|
|
350
|
+
* pack.learn expects, primed so the learning loop works out of the box. */
|
|
351
|
+
function scaffoldLearnings(slug) {
|
|
352
|
+
return `# Engagement learnings — candidate pool
|
|
353
|
+
|
|
354
|
+
TODO(you): optional file. Engagement-retrospective TTPs land here via
|
|
355
|
+
\`pensieve-sdk pack.learn ${slug} --item "..."\` (ADR-022); a candidate
|
|
356
|
+
confirmed in enough independent engagements promotes itself into the
|
|
357
|
+
checklist (pack.revert is the human veto). Delete this file if you don't
|
|
358
|
+
want the loop.
|
|
359
|
+
|
|
360
|
+
_appended by pensieve-sdk pack.learn; promoted into the checklist by the pack author (ADR-022)_
|
|
361
|
+
`;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* scaffold(primary, slug, { repo }) — generate a COMPLETE, valid-as-is pack
|
|
366
|
+
* skeleton (31-02 / SCOP-02): pack.yaml (PACK-FORMAT v1.0 frozen, exactly) +
|
|
367
|
+
* checklist.md (header + example item rows) + runbooks/ITEM-01/SKILL.md
|
|
368
|
+
* (lint-clean RUNBOOK-FORMAT stub) + learnings.md (optional, primed).
|
|
369
|
+
*
|
|
370
|
+
* Default target: the USER root ($PENSIEVE_HOME/packs/<area>/<name>/) — a
|
|
371
|
+
* user-made pack survives reinstalls. `repo: true` contributes into the repo
|
|
372
|
+
* tree instead: an EXISTING top-level area, or custom/ (the sanctioned
|
|
373
|
+
* contributor area) — never a new top-level area.
|
|
374
|
+
*
|
|
375
|
+
* Fail-closed BEFORE any write: a slug existing in EITHER root is refused
|
|
376
|
+
* (both paths named when both — 31-01 collision semantics); the slug must
|
|
377
|
+
* match the area/name shape with safe segments. HARD ACCEPTANCE, enforced at
|
|
378
|
+
* mint time: the UNTOUCHED skeleton loads through the ONE resolver.
|
|
379
|
+
*/
|
|
380
|
+
function scaffold(primary, slug, { repo = false } = {}) {
|
|
381
|
+
const { area, name } = parseScaffoldSlug(slug); // shape FIRST, fail-closed
|
|
382
|
+
const repoDir = repoRoot(primary);
|
|
383
|
+
|
|
384
|
+
if (repo && area !== 'custom') {
|
|
385
|
+
const areaDir = path.join(repoDir, area);
|
|
386
|
+
if (!fs.existsSync(areaDir) || !fs.statSync(areaDir).isDirectory()) {
|
|
387
|
+
throw new Error(
|
|
388
|
+
`--repo refuses to invent a new top-level pack area: "${area}" does not exist under ${repoDir} `
|
|
389
|
+
+ `— scaffold under custom/ (pack.scaffold custom/${name} --repo) or an existing area`
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// existing slug in EITHER root -> refuse (both paths named when both);
|
|
395
|
+
// scaffold never overwrites, never mints a cross-root collision.
|
|
396
|
+
const dirs = resolveDirs(primary, slug);
|
|
397
|
+
if (dirs.length > 1) throw collisionError(slug, dirs);
|
|
398
|
+
if (dirs.length === 1) {
|
|
399
|
+
const e = new Error(`pack already exists: ${slug} — ${dirs[0]} (scaffold never overwrites)`);
|
|
400
|
+
e.existing = { slug, path: dirs[0] };
|
|
401
|
+
throw e;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const dir = path.join(repo ? repoDir : userRoot(), area, name);
|
|
405
|
+
const files = {
|
|
406
|
+
'pack.yaml': scaffoldYaml(slug, name),
|
|
407
|
+
'checklist.md': scaffoldChecklist(slug, name),
|
|
408
|
+
'runbooks/ITEM-01/SKILL.md': scaffoldRunbook(slug),
|
|
409
|
+
'learnings.md': scaffoldLearnings(slug),
|
|
410
|
+
};
|
|
411
|
+
fs.mkdirSync(path.dirname(path.join(dir, 'runbooks/ITEM-01/SKILL.md')), { recursive: true });
|
|
412
|
+
for (const [rel, content] of Object.entries(files)) {
|
|
413
|
+
fs.writeFileSync(path.join(dir, rel), content);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// the untouched skeleton MUST load through the ONE resolver — a scaffold
|
|
417
|
+
// that ever emits an unloadable pack is a bug, not a user problem.
|
|
418
|
+
load(primary, slug);
|
|
419
|
+
return { slug, path: dir, root: repo ? 'repo' : 'user', files: Object.keys(files) };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// per-engagement pack switches (config.yaml: enabled_packs list)
|
|
423
|
+
function enabled(dir) {
|
|
424
|
+
const cfg = paths.configFile(dir);
|
|
425
|
+
const text = fs.existsSync(cfg) ? fs.readFileSync(cfg, 'utf8') : '';
|
|
426
|
+
// Format-aware read (mirrors skills.readAgentSkillsMap): flat is canonical, but
|
|
427
|
+
// a fenced config.yaml still occurs when an agent_skills map was written via
|
|
428
|
+
// frontmatter.set. Read either shape; writeEnabled always re-emits flat (SEED-002).
|
|
429
|
+
const fenced = /^---\s*$/.test(text.split('\n')[0]);
|
|
430
|
+
try {
|
|
431
|
+
const list = fenced ? fm.get(text, 'enabled_packs') : (parseYaml(text) || {}).enabled_packs;
|
|
432
|
+
return list || [];
|
|
433
|
+
} catch {
|
|
434
|
+
return [];
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function enable(dir, slug, { packsRoot } = {}) {
|
|
439
|
+
// fail-closed collision (31-01 / SCOP-03): enabling an ambiguous slug is
|
|
440
|
+
// refused with BOTH filesystem paths named — a user pack never silently
|
|
441
|
+
// shadows built-in methodology. Refusal is not a write: enabled_packs is
|
|
442
|
+
// untouched when this throws. (Unknown slugs stay permitted as before —
|
|
443
|
+
// existence is load's fail-closed check, not enable's.)
|
|
444
|
+
const dirs = resolveDirs(packsRoot, slug);
|
|
445
|
+
if (dirs.length > 1) throw collisionError(slug, dirs);
|
|
446
|
+
const list = enabled(dir);
|
|
447
|
+
if (!list.includes(slug)) list.push(slug);
|
|
448
|
+
writeEnabled(dir, list);
|
|
449
|
+
return list;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function disable(dir, slug) {
|
|
453
|
+
const list = enabled(dir).filter((s) => s !== slug);
|
|
454
|
+
writeEnabled(dir, list);
|
|
455
|
+
return list;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function writeEnabled(dir, list) {
|
|
459
|
+
const cfg = paths.configFile(dir);
|
|
460
|
+
const text = fs.existsSync(cfg) ? fs.readFileSync(cfg, 'utf8') : '';
|
|
461
|
+
const obj = parseYaml(text) || {}; // flat: preserve every existing key, never fence
|
|
462
|
+
obj.enabled_packs = list;
|
|
463
|
+
fs.writeFileSync(cfg, fm.emitYaml(obj, 0, []).join('\n') + '\n');
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Learnings loop (ADR-022, M4): engagement-retrospective TTPs land in a
|
|
468
|
+
* pack's candidate pool with provenance. v0.6 05-03 makes promotion
|
|
469
|
+
* AUTONOMOUS: a candidate that is confirmed in enough independent engagements
|
|
470
|
+
* (AUTO_PROMOTE_AFTER) promotes itself into the checklist — no human pick.
|
|
471
|
+
* The human keeps a veto: pack.revert demotes a promoted learning and pulls
|
|
472
|
+
* its checklist row back out. Packs are still methodology — the only auto-edit
|
|
473
|
+
* is the narrow, confirmed, revertible promotion of a proven learning.
|
|
474
|
+
*/
|
|
475
|
+
// A candidate auto-promotes after this many independent confirmations.
|
|
476
|
+
const AUTO_PROMOTE_AFTER = 2;
|
|
477
|
+
|
|
478
|
+
function learningsFile(root, slug) { return path.join(resolveDir(root, slug), 'learnings.md'); }
|
|
479
|
+
|
|
480
|
+
function learn(root, slug, { item, source = '' } = {}) {
|
|
481
|
+
const dir = resolveDir(root, slug); // multi-root: user-root packs learn too (31-01)
|
|
482
|
+
if (!item || !String(item).trim()) throw new Error('learning requires an item (--item "text")');
|
|
483
|
+
const file = learningsFile(root, slug);
|
|
484
|
+
const lines = fs.existsSync(file)
|
|
485
|
+
? fs.readFileSync(file, 'utf8').split('\n')
|
|
486
|
+
: ['# Engagement learnings — candidate pool', '', '_appended by pensieve-sdk pack.learn; promoted into the checklist by the pack author (ADR-022)_', ''];
|
|
487
|
+
const n = lines.filter((l) => /^- L-\d+/.test(l)).length + 1;
|
|
488
|
+
const id = `L-${String(n).padStart(3, '0')}`;
|
|
489
|
+
lines.push(`- ${id} [candidate] (${new Date().toISOString().slice(0, 10)}${source ? `, ${source}` : ''}) ${String(item).trim()}`);
|
|
490
|
+
fs.writeFileSync(file, lines.join('\n'));
|
|
491
|
+
return { id, status: 'candidate', pack: slug };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function learnings(root, slug) {
|
|
495
|
+
const file = learningsFile(root, slug);
|
|
496
|
+
if (!fs.existsSync(file)) return [];
|
|
497
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
498
|
+
const out = [];
|
|
499
|
+
let cur = null;
|
|
500
|
+
for (const l of lines) {
|
|
501
|
+
const m = l.match(/^- (L-\d+) \[(candidate|promoted|rejected)\] \(([^)]*)\) (.*)$/);
|
|
502
|
+
if (m) {
|
|
503
|
+
cur = { id: m[1], status: m[2], meta: m[3], item: m[4], confirmations: [] };
|
|
504
|
+
out.push(cur);
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
if (/^- L-\d+/.test(l)) { cur = { raw: l }; out.push(cur); continue; }
|
|
508
|
+
// confirmation sub-bullet under a learning: " - confirmed by <eng> on <date>"
|
|
509
|
+
const c = l.match(/^\s+- confirmed by (\S+) on (\S+)/);
|
|
510
|
+
if (c && cur && !cur.raw) cur.confirmations.push({ by: c[1], on: c[2] });
|
|
511
|
+
}
|
|
512
|
+
return out;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function promote(root, slug, id) {
|
|
516
|
+
const learning = learnings(root, slug).find((x) => x.id === id && !x.raw);
|
|
517
|
+
if (!learning) throw new Error(`learning not found: ${id}`);
|
|
518
|
+
if (learning.status !== 'candidate') throw new Error(`only candidates can be promoted (${id} is ${learning.status})`);
|
|
519
|
+
const checklist = path.join(resolveDir(root, slug), 'checklist.md');
|
|
520
|
+
if (!fs.existsSync(checklist)) throw new Error(`checklist missing for ${slug}`);
|
|
521
|
+
let text = fs.readFileSync(checklist, 'utf8');
|
|
522
|
+
const heading = '## Engagement learnings';
|
|
523
|
+
const row = `- test: ${learning.item}`;
|
|
524
|
+
if (text.includes(heading)) {
|
|
525
|
+
// append after the last existing test row in the section (chronological)
|
|
526
|
+
const lines = text.split('\n');
|
|
527
|
+
const start = lines.indexOf(heading);
|
|
528
|
+
let last = start;
|
|
529
|
+
for (let i = start + 1; i < lines.length && i < start + 60; i++) {
|
|
530
|
+
if (lines[i].startsWith('- test:')) last = i;
|
|
531
|
+
else if (lines[i].startsWith('## ')) break;
|
|
532
|
+
}
|
|
533
|
+
lines.splice(last + 1, 0, row);
|
|
534
|
+
text = lines.join('\n');
|
|
535
|
+
} else {
|
|
536
|
+
text = text.replace(/\s*$/, '\n') + `\n${heading}\n\n${row}\n`;
|
|
537
|
+
}
|
|
538
|
+
fs.writeFileSync(checklist, text);
|
|
539
|
+
const file = learningsFile(root, slug);
|
|
540
|
+
fs.writeFileSync(file, fs.readFileSync(file, 'utf8').split('\n')
|
|
541
|
+
.map((ln) => (ln.startsWith(`- ${id} [candidate]`) ? ln.replace(`- ${id} [candidate]`, `- ${id} [promoted]`) : ln))
|
|
542
|
+
.join('\n'));
|
|
543
|
+
return { id, status: 'promoted', slug };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* confirm(root, slug, id, {by, note}) — the autonomous half of the loop. The
|
|
548
|
+
* agent calls this when it has APPLIED a candidate learning in an engagement
|
|
549
|
+
* and it worked (validated). Each call records provenance as a sub-bullet under
|
|
550
|
+
* the learning. When independent confirmations reach AUTO_PROMOTE_AFTER the
|
|
551
|
+
* candidate promotes itself (reuses promote's checklist injection) — no human
|
|
552
|
+
* pick. The human veto (revert) is always available afterwards.
|
|
553
|
+
*/
|
|
554
|
+
function confirm(root, slug, id, { by = '', note = '' } = {}) {
|
|
555
|
+
const file = learningsFile(root, slug);
|
|
556
|
+
if (!fs.existsSync(file)) throw new Error(`no learnings for ${slug}`);
|
|
557
|
+
const learning = learnings(root, slug).find((x) => x.id === id && !x.raw);
|
|
558
|
+
if (!learning) throw new Error(`learning not found: ${id}`);
|
|
559
|
+
if (learning.status !== 'candidate') throw new Error(`only candidates accrue confirmations (${id} is ${learning.status})`);
|
|
560
|
+
const when = new Date().toISOString().slice(0, 10);
|
|
561
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
562
|
+
const idx = lines.findIndex((l) => l.startsWith(`- ${id} [`));
|
|
563
|
+
if (idx === -1) throw new Error(`learning line not found: ${id}`);
|
|
564
|
+
// insert after the learning line and any existing confirmation sub-bullets
|
|
565
|
+
let insertAt = idx + 1;
|
|
566
|
+
while (insertAt < lines.length && /^\s+- /.test(lines[insertAt])) insertAt++;
|
|
567
|
+
lines.splice(insertAt, 0, ` - confirmed by ${by || 'engagement'} on ${when}${note ? ` — ${note}` : ''}`);
|
|
568
|
+
fs.writeFileSync(file, lines.join('\n'));
|
|
569
|
+
|
|
570
|
+
const confirmations = (learning.confirmations || []).length + 1;
|
|
571
|
+
if (confirmations >= AUTO_PROMOTE_AFTER) {
|
|
572
|
+
const r = promote(root, slug, id); // reuse the existing checklist injection
|
|
573
|
+
return { id, status: 'promoted', slug, confirmations, auto: true, threshold: AUTO_PROMOTE_AFTER };
|
|
574
|
+
}
|
|
575
|
+
return { id, status: 'candidate', slug, confirmations, auto: false, needed: AUTO_PROMOTE_AFTER };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* revert(root, slug, id) — the human veto. Demotes a promoted learning back to
|
|
580
|
+
* a candidate and removes the checklist row that promote/auto-promotion added.
|
|
581
|
+
* Deliberately the ONLY way to undo a promotion (keeps packs methodology-safe).
|
|
582
|
+
*/
|
|
583
|
+
function revert(root, slug, id) {
|
|
584
|
+
const learning = learnings(root, slug).find((x) => x.id === id && !x.raw);
|
|
585
|
+
if (!learning) throw new Error(`learning not found: ${id}`);
|
|
586
|
+
if (learning.status !== 'promoted') throw new Error(`only promoted learnings can be reverted (${id} is ${learning.status})`);
|
|
587
|
+
const checklist = path.join(resolveDir(root, slug), 'checklist.md');
|
|
588
|
+
if (fs.existsSync(checklist)) {
|
|
589
|
+
const row = `- test: ${learning.item}`;
|
|
590
|
+
const kept = fs.readFileSync(checklist, 'utf8').split('\n').filter((l) => l.trim() !== row.trim());
|
|
591
|
+
fs.writeFileSync(checklist, kept.join('\n'));
|
|
592
|
+
}
|
|
593
|
+
const file = learningsFile(root, slug);
|
|
594
|
+
fs.writeFileSync(file, fs.readFileSync(file, 'utf8').split('\n')
|
|
595
|
+
.map((ln) => (ln.startsWith(`- ${id} [promoted]`) ? ln.replace(`- ${id} [promoted]`, `- ${id} [candidate]`) : ln))
|
|
596
|
+
.join('\n'));
|
|
597
|
+
return { id, status: 'candidate', slug, veto: true };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
module.exports = {
|
|
601
|
+
// the ONE multi-root resolver (31-01 / SCOP-03) — every consumer routes here
|
|
602
|
+
roots, repoRoot, userRoot, resolveDirs, resolveDir, collisionError,
|
|
603
|
+
load, list, ingest, parseChecklist, enabled, enable, disable,
|
|
604
|
+
learn, learnings, promote, confirm, revert, AUTO_PROMOTE_AFTER,
|
|
605
|
+
// authoring half (31-02 / SCOP-02): skeleton generation, valid as-is
|
|
606
|
+
scaffold,
|
|
607
|
+
};
|