@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,814 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* clientlist.cjs — client checklist engine core (Phase 19, plan 19-01).
|
|
4
|
+
*
|
|
5
|
+
* The client's tracker is the contract: run it top to bottom, never fabricate
|
|
6
|
+
* coverage, never let scenario text drift silently. A client-provided csv is
|
|
7
|
+
* ingested natively; an xlsx runs through a python3+openpyxl lane-B host-tool
|
|
8
|
+
* bridge (probe-and-instruct when missing, mirroring lib/pdf.cjs) — the sdk
|
|
9
|
+
* itself stays zero-dependency.
|
|
10
|
+
*
|
|
11
|
+
* Storage (design decision 1):
|
|
12
|
+
* <engagement>/clientlist/<slug>.json the imported snapshot (below)
|
|
13
|
+
* <engagement>/clientlist/source/<file> pristine byte-copy of the
|
|
14
|
+
* ORIGINAL — import never mutates
|
|
15
|
+
* it, export re-reads it as the
|
|
16
|
+
* base for the updated copy.
|
|
17
|
+
*
|
|
18
|
+
* Snapshot schema (pensieve.clientlist/1):
|
|
19
|
+
* { schema, slug, imported_at,
|
|
20
|
+
* source: { file, format: csv|xlsx, sha256, bytes, copy },
|
|
21
|
+
* sheets: [ { index, name, columns: {row_number, scenario, verdict,
|
|
22
|
+
* evidence, notes}, rows: [ { id, row_number, scenario_text,
|
|
23
|
+
* scenario_sha256, verdict, evidence, notes, blocker_note } ] } ] }
|
|
24
|
+
*
|
|
25
|
+
* IDs (design decision 2): CR-<sheet-index>-<position>, 1-based position
|
|
26
|
+
* among DATA rows of the sheet. Real client sheets carry duplicate row
|
|
27
|
+
* numbers — the row number is recorded as DATA, never used as the key.
|
|
28
|
+
* A row is a DATA row iff its scenario cell is non-empty (blank filler rows
|
|
29
|
+
* are not tracked; the rule is deterministic so positions never shift).
|
|
30
|
+
*
|
|
31
|
+
* Verdicts (design decision 4) are validated STATES, not free text:
|
|
32
|
+
* no_done — No + what-was-done text (done, required)
|
|
33
|
+
* no_na — No + N/A reason (reason, required)
|
|
34
|
+
* yes — Yes + finding reference (finding_id, required)
|
|
35
|
+
* EMPTY — an explicitly written empty verdict REQUIRES a blocker note;
|
|
36
|
+
* an untouched row (verdict null, no blocker) stays untouched.
|
|
37
|
+
* Unknown tiers are refused. Coverage is never fabricated.
|
|
38
|
+
*
|
|
39
|
+
* Write/export touch ONLY verdict/evidence/notes(+blocker) fields; before
|
|
40
|
+
* each cell write export re-verifies the row's scenario hash against the
|
|
41
|
+
* PRISTINE copy and aborts the WHOLE export on drift (fail-closed, atomic
|
|
42
|
+
* temp+rename — no half-written exports).
|
|
43
|
+
*/
|
|
44
|
+
const fs = require('node:fs');
|
|
45
|
+
const os = require('node:os');
|
|
46
|
+
const path = require('node:path');
|
|
47
|
+
const crypto = require('node:crypto');
|
|
48
|
+
const { spawnSync } = require('node:child_process');
|
|
49
|
+
|
|
50
|
+
const state = require('./state.cjs');
|
|
51
|
+
|
|
52
|
+
const SCHEMA = 'pensieve.clientlist/1';
|
|
53
|
+
|
|
54
|
+
// ---- lane-B host-tool bridge (python3 + openpyxl), pdf.cjs pattern ----
|
|
55
|
+
//
|
|
56
|
+
// Ordered probe candidates: an explicit override, the system python3 (when it
|
|
57
|
+
// can import openpyxl), then the shared pensieve host venv (when it exists).
|
|
58
|
+
// The FIRST candidate that can import openpyxl wins; the sdk never installs
|
|
59
|
+
// anything and never crashes — a miss returns ok:false with exact setup
|
|
60
|
+
// instructions BEFORE any engagement state is touched.
|
|
61
|
+
|
|
62
|
+
const SETUP_INSTRUCTIONS = [
|
|
63
|
+
'clientlist xlsx import/export uses a lane-B host tool (ADR-014 pattern): python3 with openpyxl on the HOST.',
|
|
64
|
+
'The sdk is zero-dependency and will not install it for you. Setup:',
|
|
65
|
+
' python3 -m venv ~/.pensieve/venv',
|
|
66
|
+
' ~/.pensieve/venv/bin/pip install openpyxl',
|
|
67
|
+
'(the sdk probes python3 then ~/.pensieve/venv/bin/python automatically,',
|
|
68
|
+
' or pin one with PENSIEVE_CLIENTLIST_PYTHON — a pin is probed exclusively)',
|
|
69
|
+
].join('\n');
|
|
70
|
+
|
|
71
|
+
function bridgeCandidates() {
|
|
72
|
+
// An explicit PENSIEVE_CLIENTLIST_PYTHON pins the interpreter (same
|
|
73
|
+
// semantics as PENSIEVE_PDF_PYTHON in lib/pdf.cjs): it is the ONLY
|
|
74
|
+
// candidate probed, so a bad pin fails loudly instead of silently
|
|
75
|
+
// falling through to another python.
|
|
76
|
+
if (process.env.PENSIEVE_CLIENTLIST_PYTHON) return [process.env.PENSIEVE_CLIENTLIST_PYTHON];
|
|
77
|
+
const list = ['python3'];
|
|
78
|
+
const venv = path.join(os.homedir(), '.pensieve', 'venv', 'bin', 'python');
|
|
79
|
+
if (fs.existsSync(venv)) list.push(venv);
|
|
80
|
+
const legacy = path.join(os.homedir(), '.strike', 'venv', 'bin', 'python'); /* pre-rename venv */
|
|
81
|
+
if (fs.existsSync(legacy)) list.push(legacy);
|
|
82
|
+
return list;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** probe the ordered candidates for an importable openpyxl */
|
|
86
|
+
function probePython() {
|
|
87
|
+
const tried = [];
|
|
88
|
+
for (const py of bridgeCandidates()) {
|
|
89
|
+
tried.push(py);
|
|
90
|
+
let r;
|
|
91
|
+
try {
|
|
92
|
+
r = spawnSync(py, ['-c', 'import openpyxl'], { encoding: 'utf8' });
|
|
93
|
+
} catch (e) {
|
|
94
|
+
continue; // candidate could not start — try the next one
|
|
95
|
+
}
|
|
96
|
+
if (r.error) continue; // not found on this host — try the next one
|
|
97
|
+
if (r.status === 0) return { ok: true, python: py };
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
ok: false,
|
|
101
|
+
reason: `no probed python can import openpyxl (tried: ${tried.join(', ')})`,
|
|
102
|
+
instructions: SETUP_INSTRUCTIONS,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Generated python bridge scripts (design decision 3): the sdk writes the
|
|
107
|
+
// script to a temp file and passes the payload as JSON on stdin; the script
|
|
108
|
+
// answers with one JSON document on stdout. read phase = import + export
|
|
109
|
+
// drift verification base; write phase = apply allowed-cell ops to a copy.
|
|
110
|
+
const PY_READ = [
|
|
111
|
+
'import json, sys',
|
|
112
|
+
'from openpyxl import load_workbook',
|
|
113
|
+
'payload = json.load(sys.stdin)',
|
|
114
|
+
'wb = load_workbook(payload["file"], data_only=True)',
|
|
115
|
+
'sheets = []',
|
|
116
|
+
'for idx, name in enumerate(wb.sheetnames):',
|
|
117
|
+
' ws = wb[name]',
|
|
118
|
+
' rows = []',
|
|
119
|
+
' for cells in ws.iter_rows():',
|
|
120
|
+
' rows.append({',
|
|
121
|
+
' "excel_row": cells[0].row if cells else 1,',
|
|
122
|
+
' "fields": ["" if c.value is None else str(c.value) for c in cells],',
|
|
123
|
+
' })',
|
|
124
|
+
' sheets.append({"index": idx, "name": name, "rows": rows})',
|
|
125
|
+
'json.dump({"sheets": sheets}, sys.stdout)',
|
|
126
|
+
].join('\n');
|
|
127
|
+
|
|
128
|
+
const PY_WRITE = [
|
|
129
|
+
'import json, sys',
|
|
130
|
+
'from openpyxl import load_workbook',
|
|
131
|
+
'payload = json.load(sys.stdin)',
|
|
132
|
+
'wb = load_workbook(payload["source"])',
|
|
133
|
+
'for op in payload["ops"]:',
|
|
134
|
+
' ws = wb[op["sheet"]]',
|
|
135
|
+
' ws.cell(row=op["row"], column=op["col"]).value = op["value"]',
|
|
136
|
+
'wb.save(payload["out"])',
|
|
137
|
+
].join('\n');
|
|
138
|
+
|
|
139
|
+
function runBridge(python, script, payload) {
|
|
140
|
+
const tmp = path.join(os.tmpdir(), `pensieve-clientlist-bridge-${process.pid}-${Date.now()}.py`);
|
|
141
|
+
fs.writeFileSync(tmp, script, 'utf8');
|
|
142
|
+
try {
|
|
143
|
+
const r = spawnSync(python, [tmp], {
|
|
144
|
+
input: JSON.stringify(payload),
|
|
145
|
+
encoding: 'utf8',
|
|
146
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
147
|
+
});
|
|
148
|
+
if (r.error) throw new Error(`xlsx bridge could not start (${python}): ${r.error.message}`);
|
|
149
|
+
if (r.status !== 0) {
|
|
150
|
+
throw new Error(`xlsx bridge exited ${r.status}: ${(r.stderr || '').trim().slice(-500)}`);
|
|
151
|
+
}
|
|
152
|
+
return r.stdout && r.stdout.trim() ? JSON.parse(r.stdout) : null;
|
|
153
|
+
} finally {
|
|
154
|
+
try { fs.unlinkSync(tmp); } catch { /* best-effort temp cleanup */ }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---- helpers ----
|
|
159
|
+
|
|
160
|
+
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
|
|
161
|
+
|
|
162
|
+
function slugify(name) {
|
|
163
|
+
return String(name)
|
|
164
|
+
.toLowerCase()
|
|
165
|
+
.replace(/\.(csv|xlsx|xlsm)$/i, '')
|
|
166
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
167
|
+
.replace(/^-+|-+$/g, '') || 'checklist';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function refuse(gate, error, extra = {}) {
|
|
171
|
+
return { ok: false, gate, error, data: null, ...extra };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function requireEngagementDir(dir) {
|
|
175
|
+
if (!dir || !state.isEngagement(dir)) {
|
|
176
|
+
throw new Error(
|
|
177
|
+
'clientlist requires an engagement dir (no STATE.md with status frontmatter at the given path)'
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return path.resolve(dir);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function clientlistDir(dir) { return path.join(dir, 'clientlist'); }
|
|
184
|
+
function sourceDir(dir) { return path.join(clientlistDir(dir), 'source'); }
|
|
185
|
+
function snapshotFile(dir, slug) { return path.join(clientlistDir(dir), `${slug}.json`); }
|
|
186
|
+
|
|
187
|
+
function writeAtomic(file, content) {
|
|
188
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
189
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
190
|
+
fs.writeFileSync(tmp, content, 'utf8');
|
|
191
|
+
fs.renameSync(tmp, file);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function loadSnapshot(dir, slug) {
|
|
195
|
+
const file = snapshotFile(dir, slug);
|
|
196
|
+
if (!fs.existsSync(file)) {
|
|
197
|
+
const known = fs.existsSync(clientlistDir(dir))
|
|
198
|
+
? fs.readdirSync(clientlistDir(dir)).filter((f) => f.endsWith('.json')).map((f) => f.replace(/\.json$/, ''))
|
|
199
|
+
: [];
|
|
200
|
+
throw new Error(`clientlist snapshot "${slug}" not found (imported: ${known.join(', ') || 'none'})`);
|
|
201
|
+
}
|
|
202
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---- csv (native, quoted commas + CRLF tolerant) ----
|
|
206
|
+
//
|
|
207
|
+
// The parser keeps each field's RAW text (quotes exactly as they appeared)
|
|
208
|
+
// and each record's line ending, so a rebuilt export reproduces every
|
|
209
|
+
// untouched byte of the pristine copy and only the written cells change.
|
|
210
|
+
|
|
211
|
+
function parseCsv(text) {
|
|
212
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // UTF-8 BOM
|
|
213
|
+
const records = [];
|
|
214
|
+
let fields = [];
|
|
215
|
+
let raw = '';
|
|
216
|
+
let quoted = false;
|
|
217
|
+
let fieldStarted = false;
|
|
218
|
+
const pushField = () => { fields.push(raw); raw = ''; quoted = false; fieldStarted = false; };
|
|
219
|
+
const pushRecord = (eol) => {
|
|
220
|
+
pushField();
|
|
221
|
+
records.push({ fields, rawFields: fields.slice(), eol });
|
|
222
|
+
fields = [];
|
|
223
|
+
};
|
|
224
|
+
for (let i = 0; i < text.length; i++) {
|
|
225
|
+
const ch = text[i];
|
|
226
|
+
if (quoted) {
|
|
227
|
+
if (ch === '"') {
|
|
228
|
+
if (text[i + 1] === '"') { raw += '""'; i++; }
|
|
229
|
+
else { raw += '"'; quoted = false; }
|
|
230
|
+
} else raw += ch;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (!fieldStarted && ch === '"' && raw === '') {
|
|
234
|
+
quoted = true;
|
|
235
|
+
fieldStarted = true;
|
|
236
|
+
raw = '"';
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (ch === ',') { pushField(); continue; }
|
|
240
|
+
if (ch === '\r' || ch === '\n') {
|
|
241
|
+
const eol = ch === '\r' && text[i + 1] === '\n' ? (i++, '\r\n') : '\n';
|
|
242
|
+
pushRecord(eol);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
fieldStarted = true;
|
|
246
|
+
raw += ch;
|
|
247
|
+
}
|
|
248
|
+
if (raw !== '' || fields.length > 0) pushRecord('');
|
|
249
|
+
return records;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** raw field text -> value (strip outer quotes, unescape "" -> ") */
|
|
253
|
+
function csvValue(rawField) {
|
|
254
|
+
if (rawField.length >= 2 && rawField[0] === '"' && rawField[rawField.length - 1] === '"') {
|
|
255
|
+
return rawField.slice(1, -1).replace(/""/g, '"');
|
|
256
|
+
}
|
|
257
|
+
return rawField;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** value -> raw field text (quote only when necessary) */
|
|
261
|
+
function csvRaw(value) {
|
|
262
|
+
const v = String(value ?? '');
|
|
263
|
+
if (/[",\r\n]/.test(v)) return `"${v.replace(/"/g, '""')}"`;
|
|
264
|
+
return v;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---- column resolution (header = first row; scenario column REQUIRED) ----
|
|
268
|
+
|
|
269
|
+
const COLUMN_ALIASES = {
|
|
270
|
+
row_number: ['row', '#', 'no', 'no.', 'number', 'item', 'item no', 'item number', 'id', 'ref', 'sr', 's.no', 'sr no', 'sr. no', 'row number'],
|
|
271
|
+
scenario: ['scenario', 'scenario text', 'scenario description', 'test scenario', 'control', 'control description', 'check', 'check description', 'requirement', 'requirement description', 'description', 'test'],
|
|
272
|
+
verdict: ['verdict', 'result', 'status', 'answer', 'outcome', 'done'],
|
|
273
|
+
evidence: ['evidence', 'evidence id', 'evidence ids', 'proof', 'ref evidence'],
|
|
274
|
+
notes: ['notes', 'note', 'remarks', 'comments', 'comment', 'observations'],
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
function resolveColumns(headerFields, where) {
|
|
278
|
+
const cols = { row_number: null, scenario: null, verdict: null, evidence: null, notes: null };
|
|
279
|
+
for (const [key, aliases] of Object.entries(COLUMN_ALIASES)) {
|
|
280
|
+
const idx = headerFields.findIndex((h) => aliases.includes(h.trim().toLowerCase()));
|
|
281
|
+
if (idx !== -1) cols[key] = idx;
|
|
282
|
+
}
|
|
283
|
+
if (cols.scenario === null) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`clientlist: no scenario column found in ${where} `
|
|
286
|
+
+ '(looked for Scenario / Control / Check / Requirement / Description headers) '
|
|
287
|
+
+ '— cannot hash-freeze what cannot be identified'
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
return cols;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Shared sheet model builder: header record + data records ->
|
|
295
|
+
* { name, index, columns, rows } with position-keyed ids and frozen hashes.
|
|
296
|
+
* `records` items: { fields: [values] } (csv: decoded; xlsx: bridge strings).
|
|
297
|
+
*/
|
|
298
|
+
function buildSheet({ index, name, records, excelRows }) {
|
|
299
|
+
if (records.length === 0) {
|
|
300
|
+
throw new Error(`clientlist: sheet "${name}" is empty (no header row)`);
|
|
301
|
+
}
|
|
302
|
+
const columns = resolveColumns(records[0].fields, `sheet "${name}"`);
|
|
303
|
+
const rows = [];
|
|
304
|
+
for (let i = 1; i < records.length; i++) {
|
|
305
|
+
const fields = records[i].fields;
|
|
306
|
+
const scenario = String(fields[columns.scenario] ?? '').trim();
|
|
307
|
+
if (scenario === '') continue; // not a data row — positions never shift
|
|
308
|
+
rows.push({
|
|
309
|
+
id: `CR-${index}-${rows.length + 1}`,
|
|
310
|
+
row_number: columns.row_number !== null
|
|
311
|
+
? String(fields[columns.row_number] ?? '').trim() || null
|
|
312
|
+
: null,
|
|
313
|
+
scenario_text: scenario,
|
|
314
|
+
scenario_sha256: sha256(Buffer.from(scenario, 'utf8')),
|
|
315
|
+
verdict: null,
|
|
316
|
+
evidence: [],
|
|
317
|
+
notes: '',
|
|
318
|
+
blocker_note: null,
|
|
319
|
+
...(excelRows ? { sheet_row: excelRows[i] } : {}),
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
return { index, name, columns, rows };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ---- clientlist.importWorkbook ----
|
|
326
|
+
|
|
327
|
+
function importWorkbook(dir, { file, slug } = {}) {
|
|
328
|
+
const dirAbs = requireEngagementDir(dir);
|
|
329
|
+
if (!file) throw new Error('clientlist.import requires a --file <csv|xlsx>');
|
|
330
|
+
const src = path.resolve(file);
|
|
331
|
+
if (!fs.existsSync(src)) throw new Error(`clientlist.import: file not found: ${src}`);
|
|
332
|
+
|
|
333
|
+
const ext = path.extname(src).toLowerCase();
|
|
334
|
+
const bytes = fs.readFileSync(src);
|
|
335
|
+
const format = ext === '.csv' ? 'csv' : ext === '.xlsx' || ext === '.xlsm' ? 'xlsx' : null;
|
|
336
|
+
if (!format) throw new Error(`clientlist.import: unsupported format "${ext}" (csv or xlsx)`);
|
|
337
|
+
|
|
338
|
+
// Parse FIRST (fail-closed on bad content), probe the host tool for xlsx
|
|
339
|
+
// BEFORE any engagement state is touched (design decision 3).
|
|
340
|
+
let sheets;
|
|
341
|
+
let bridge = null;
|
|
342
|
+
if (format === 'csv') {
|
|
343
|
+
const records = parseCsv(bytes.toString('utf8'));
|
|
344
|
+
sheets = [buildSheet({
|
|
345
|
+
index: 0,
|
|
346
|
+
name: path.basename(src).replace(/\.[^.]+$/, ''),
|
|
347
|
+
records: records.map((r) => ({ fields: r.rawFields.map(csvValue) })),
|
|
348
|
+
})];
|
|
349
|
+
} else {
|
|
350
|
+
const probe = probePython();
|
|
351
|
+
if (!probe.ok) {
|
|
352
|
+
return refuse('clientlist-bridge', `${probe.reason}.\n${SETUP_INSTRUCTIONS}`,
|
|
353
|
+
{ instructions: SETUP_INSTRUCTIONS });
|
|
354
|
+
}
|
|
355
|
+
bridge = probe.python;
|
|
356
|
+
const out = runBridge(bridge, PY_READ, { file: src });
|
|
357
|
+
sheets = out.sheets.map((s) => buildSheet({
|
|
358
|
+
index: s.index,
|
|
359
|
+
name: s.name,
|
|
360
|
+
records: s.rows.map((r) => ({ fields: r.fields })),
|
|
361
|
+
excelRows: s.rows.map((r) => r.excel_row),
|
|
362
|
+
}));
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const useSlug = slug ? slugify(slug) : slugify(path.basename(src));
|
|
366
|
+
const snapFile = snapshotFile(dirAbs, useSlug);
|
|
367
|
+
if (fs.existsSync(snapFile)) {
|
|
368
|
+
return refuse('clientlist-import',
|
|
369
|
+
`clientlist snapshot "${useSlug}" already imported (${path.relative(dirAbs, snapFile)}) `
|
|
370
|
+
+ '— remove it to re-import; import never overwrites silently');
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// pristine byte-copy of the ORIGINAL (import never mutates it)
|
|
374
|
+
const copyPath = path.join(sourceDir(dirAbs), path.basename(src));
|
|
375
|
+
fs.mkdirSync(sourceDir(dirAbs), { recursive: true });
|
|
376
|
+
fs.copyFileSync(src, copyPath);
|
|
377
|
+
if (sha256(fs.readFileSync(copyPath)) !== sha256(bytes)) {
|
|
378
|
+
throw new Error('clientlist.import: pristine copy verification failed (hash mismatch after copy)');
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const snap = {
|
|
382
|
+
schema: SCHEMA,
|
|
383
|
+
slug: useSlug,
|
|
384
|
+
imported_at: new Date().toISOString(),
|
|
385
|
+
source: {
|
|
386
|
+
file: path.basename(src),
|
|
387
|
+
format,
|
|
388
|
+
sha256: sha256(bytes),
|
|
389
|
+
bytes: bytes.length,
|
|
390
|
+
copy: path.relative(dirAbs, copyPath),
|
|
391
|
+
},
|
|
392
|
+
sheets: sheets.map((s) => ({
|
|
393
|
+
index: s.index,
|
|
394
|
+
name: s.name,
|
|
395
|
+
columns: s.columns,
|
|
396
|
+
rows: s.rows,
|
|
397
|
+
})),
|
|
398
|
+
};
|
|
399
|
+
writeAtomic(snapFile, JSON.stringify(snap, null, 2) + '\n');
|
|
400
|
+
return {
|
|
401
|
+
ok: true,
|
|
402
|
+
slug: useSlug,
|
|
403
|
+
snapshot: path.relative(dirAbs, snapFile),
|
|
404
|
+
source_copy: path.relative(dirAbs, copyPath),
|
|
405
|
+
sha256: snap.source.sha256,
|
|
406
|
+
bridge: bridge ? path.basename(bridge) : 'native-csv',
|
|
407
|
+
sheets: snap.sheets.map((s) => ({ name: s.name, rows: s.rows.length })),
|
|
408
|
+
total_rows: snap.sheets.reduce((n, s) => n + s.rows.length, 0),
|
|
409
|
+
ids: snap.sheets.flatMap((s) => s.rows.map((r) => r.id)),
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// ---- verdict validation (design decision 4: in the SDK, not the prompt) ----
|
|
414
|
+
//
|
|
415
|
+
// The three tiers and the blocked-empty state are the ONLY states; coverage
|
|
416
|
+
// is never fabricated. Each tier carries exactly its required field.
|
|
417
|
+
|
|
418
|
+
const TIERS = ['no_done', 'no_na', 'yes'];
|
|
419
|
+
|
|
420
|
+
function validateVerdict(tier, { done, reason, finding_id } = {}) {
|
|
421
|
+
if (!TIERS.includes(tier)) {
|
|
422
|
+
throw new Error(
|
|
423
|
+
`unknown verdict tier "${tier}" (clientlist tiers: ${TIERS.join(', ')}, `
|
|
424
|
+
+ 'or an empty verdict with a blocker note)'
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
if (tier === 'no_done') {
|
|
428
|
+
if (!String(done ?? '').trim()) {
|
|
429
|
+
throw new Error('verdict no_done requires what-was-done text (--done)');
|
|
430
|
+
}
|
|
431
|
+
return { tier, done: String(done).trim() };
|
|
432
|
+
}
|
|
433
|
+
if (tier === 'no_na') {
|
|
434
|
+
if (!String(reason ?? '').trim()) {
|
|
435
|
+
throw new Error('verdict no_na requires an N/A reason (--reason)');
|
|
436
|
+
}
|
|
437
|
+
return { tier, reason: String(reason).trim() };
|
|
438
|
+
}
|
|
439
|
+
if (!String(finding_id ?? '').trim()) {
|
|
440
|
+
throw new Error('verdict yes requires a finding reference (--finding-id)');
|
|
441
|
+
}
|
|
442
|
+
return { tier, finding_id: String(finding_id).trim() };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** find a row (and its sheet) by position-keyed id across the snapshot */
|
|
446
|
+
function findRow(snap, id) {
|
|
447
|
+
for (const sheet of snap.sheets) {
|
|
448
|
+
for (const row of sheet.rows) {
|
|
449
|
+
if (row.id === id) return { sheet, row };
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
throw new Error(`clientlist: unknown row id "${id}" (not in snapshot "${snap.slug}")`);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// ---- clientlist.write ----
|
|
456
|
+
//
|
|
457
|
+
// Touches ONLY verdict/evidence/notes(+blocker) fields. The scenario text,
|
|
458
|
+
// its hash, the id and the row number are immutable by construction (they
|
|
459
|
+
// are not accepted as arguments at all). The snapshot write is atomic.
|
|
460
|
+
|
|
461
|
+
function write(dir, {
|
|
462
|
+
slug, id,
|
|
463
|
+
tier, verdict, done, reason, finding_id,
|
|
464
|
+
evidence, notes, blocker_note,
|
|
465
|
+
} = {}) {
|
|
466
|
+
const dirAbs = requireEngagementDir(dir);
|
|
467
|
+
if (!slug) throw new Error('clientlist.write requires --slug');
|
|
468
|
+
if (!id) throw new Error('clientlist.write requires --id <CR-...>');
|
|
469
|
+
const snap = loadSnapshot(dirAbs, slug);
|
|
470
|
+
const { row } = findRow(snap, id);
|
|
471
|
+
|
|
472
|
+
// verdict handling: `tier` given (or a verdict object) -> the verdict IS
|
|
473
|
+
// being set; tier null/'' with the write means EMPTY verdict, which is the
|
|
474
|
+
// blocked state and REQUIRES a blocker note (on this write or already on
|
|
475
|
+
// the row). No tier at all -> the verdict is not being touched.
|
|
476
|
+
let nextVerdict = row.verdict;
|
|
477
|
+
let nextBlocker = row.blocker_note;
|
|
478
|
+
if (verdict !== undefined || tier !== undefined) {
|
|
479
|
+
if (verdict && typeof verdict === 'object') {
|
|
480
|
+
nextVerdict = validateVerdict(verdict.tier, verdict);
|
|
481
|
+
} else if (tier === null || tier === '' || tier === undefined) {
|
|
482
|
+
nextBlocker = blocker_note !== undefined ? blocker_note : row.blocker_note;
|
|
483
|
+
if (!String(nextBlocker ?? '').trim()) {
|
|
484
|
+
throw new Error(
|
|
485
|
+
'an EMPTY verdict requires a blocker note (--blocker-note) — '
|
|
486
|
+
+ 'coverage is never fabricated, a blocked row must say why'
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
nextVerdict = null;
|
|
490
|
+
} else {
|
|
491
|
+
nextVerdict = validateVerdict(tier, { done, reason, finding_id });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (blocker_note !== undefined && (tier !== undefined || verdict !== undefined)) {
|
|
495
|
+
nextBlocker = blocker_note; // explicit --blocker-note alongside a verdict set
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
if (evidence !== undefined) {
|
|
499
|
+
row.evidence = (Array.isArray(evidence) ? evidence : String(evidence).split(','))
|
|
500
|
+
.map((s) => String(s).trim()).filter(Boolean);
|
|
501
|
+
}
|
|
502
|
+
if (notes !== undefined) row.notes = String(notes ?? '');
|
|
503
|
+
row.verdict = nextVerdict;
|
|
504
|
+
row.blocker_note = nextBlocker === undefined ? null : (nextBlocker || null);
|
|
505
|
+
|
|
506
|
+
writeAtomic(snapshotFile(dirAbs, slug), JSON.stringify(snap, null, 2) + '\n');
|
|
507
|
+
return {
|
|
508
|
+
id: row.id, row_number: row.row_number, scenario_sha256: row.scenario_sha256,
|
|
509
|
+
verdict: row.verdict, evidence: row.evidence, notes: row.notes,
|
|
510
|
+
blocker_note: row.blocker_note,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// ---- clientlist.list ----
|
|
515
|
+
|
|
516
|
+
function list(dir, { slug } = {}) {
|
|
517
|
+
const dirAbs = requireEngagementDir(dir);
|
|
518
|
+
if (!slug) throw new Error('clientlist.list requires --slug');
|
|
519
|
+
const snap = loadSnapshot(dirAbs, slug);
|
|
520
|
+
const rows = snap.sheets.flatMap((s) => s.rows.map((r) => ({ sheet: s.name, ...r })));
|
|
521
|
+
return {
|
|
522
|
+
slug: snap.slug,
|
|
523
|
+
source: snap.source,
|
|
524
|
+
imported_at: snap.imported_at,
|
|
525
|
+
sheets: snap.sheets.map((s) => ({ name: s.name, rows: s.rows.length })),
|
|
526
|
+
total: rows.length,
|
|
527
|
+
rows,
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// ---- clientlist.exportWorkbook ----
|
|
532
|
+
//
|
|
533
|
+
// Renders an UPDATED COPY of the client workbook (csv natively here; xlsx via
|
|
534
|
+
// the same bridge in the task-4 lane). Design decision 5: only the
|
|
535
|
+
// verdict/evidence/notes cells are written; BEFORE any write each row's
|
|
536
|
+
// scenario hash is re-verified against the PRISTINE copy and the WHOLE
|
|
537
|
+
// export aborts on drift. Atomic: temp file + rename, no half-written
|
|
538
|
+
// exports. The pristine copy itself is never modified.
|
|
539
|
+
|
|
540
|
+
/** client-facing text for a row's verdict state (never fabricates coverage) */
|
|
541
|
+
function verdictCellText(row) {
|
|
542
|
+
if (row.verdict && row.verdict.tier === 'no_done') return `No (done: ${row.verdict.done})`;
|
|
543
|
+
if (row.verdict && row.verdict.tier === 'no_na') return `No (N/A: ${row.verdict.reason})`;
|
|
544
|
+
if (row.verdict && row.verdict.tier === 'yes') return `Yes (finding: ${row.verdict.finding_id})`;
|
|
545
|
+
if (!row.verdict && row.blocker_note) return `Blocked: ${row.blocker_note}`;
|
|
546
|
+
return null; // untouched -> the original cell is left exactly as-is
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** per-row allowed-cell writes: {verdict, evidence, notes} cell text or null */
|
|
550
|
+
function rowCellWrites(row) {
|
|
551
|
+
const out = {};
|
|
552
|
+
const v = verdictCellText(row);
|
|
553
|
+
if (v !== null) out.verdict = v;
|
|
554
|
+
if (Array.isArray(row.evidence) && row.evidence.length > 0) out.evidence = row.evidence.join(', ');
|
|
555
|
+
if (row.notes) out.notes = row.notes;
|
|
556
|
+
return out;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Align pristine parsed records against snapshot data rows and re-verify the
|
|
561
|
+
* frozen scenario hashes. Returns {writes: Map<recordIndex, {verdict,evidence,notes}>}
|
|
562
|
+
* or throws a drift Error naming the first offending row id.
|
|
563
|
+
*/
|
|
564
|
+
function alignAndVerify(sheetSnap, dataRecords) {
|
|
565
|
+
if (dataRecords.length !== sheetSnap.rows.length) {
|
|
566
|
+
throw new Error(
|
|
567
|
+
`scenario drift in sheet "${sheetSnap.name}": expected ${sheetSnap.rows.length} data row(s), `
|
|
568
|
+
+ `pristine copy has ${dataRecords.length} — re-import before exporting`
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
const writes = new Map();
|
|
572
|
+
for (let i = 0; i < sheetSnap.rows.length; i++) {
|
|
573
|
+
const row = sheetSnap.rows[i];
|
|
574
|
+
const rec = dataRecords[i];
|
|
575
|
+
const scenario = String(rec.value(sheetSnap.columns.scenario) ?? '').trim();
|
|
576
|
+
if (sha256(Buffer.from(scenario, 'utf8')) !== row.scenario_sha256) {
|
|
577
|
+
throw new Error(
|
|
578
|
+
`scenario drift on ${row.id}: the pristine copy's scenario text no longer matches `
|
|
579
|
+
+ 'the hash frozen at import — re-import before exporting (fail-closed)'
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
const w = rowCellWrites(row);
|
|
583
|
+
if (Object.keys(w).length > 0) writes.set(rec.index, w);
|
|
584
|
+
}
|
|
585
|
+
return writes;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function exportWorkbook(dir, { slug, out } = {}) {
|
|
589
|
+
const dirAbs = requireEngagementDir(dir);
|
|
590
|
+
if (!slug) throw new Error('clientlist.export requires --slug');
|
|
591
|
+
const snap = loadSnapshot(dirAbs, slug);
|
|
592
|
+
const pristine = path.join(dirAbs, snap.source.copy);
|
|
593
|
+
if (!fs.existsSync(pristine)) {
|
|
594
|
+
return refuse('clientlist-source',
|
|
595
|
+
`pristine copy missing (${snap.source.copy}) — the export base must be the imported original`);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const stem = snap.source.file.replace(/\.[^.]+$/, '');
|
|
599
|
+
const ext = snap.source.format === 'xlsx' ? '.xlsx' : '.csv';
|
|
600
|
+
const outPath = out ? path.resolve(out) : path.join(clientlistDir(dirAbs), 'export', `${stem}-updated${ext}`);
|
|
601
|
+
|
|
602
|
+
let rowsWritten;
|
|
603
|
+
if (snap.source.format === 'csv') {
|
|
604
|
+
const r = exportCsv(snap, pristine, outPath);
|
|
605
|
+
if (r.ok === false) return r;
|
|
606
|
+
rowsWritten = r.rowsWritten;
|
|
607
|
+
} else {
|
|
608
|
+
const r = exportXlsx(snap, pristine, outPath);
|
|
609
|
+
if (r.ok === false) return r;
|
|
610
|
+
rowsWritten = r.rowsWritten;
|
|
611
|
+
}
|
|
612
|
+
return {
|
|
613
|
+
ok: true,
|
|
614
|
+
out: outPath,
|
|
615
|
+
rows_written: rowsWritten,
|
|
616
|
+
base: path.relative(dirAbs, pristine),
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function exportCsv(snap, pristine, outPath) {
|
|
621
|
+
if (snap.sheets.length !== 1) {
|
|
622
|
+
throw new Error('csv snapshots carry exactly one sheet (internal inconsistency)');
|
|
623
|
+
}
|
|
624
|
+
const sheet = snap.sheets[0];
|
|
625
|
+
let text = fs.readFileSync(pristine, 'utf8');
|
|
626
|
+
const hadBom = text.charCodeAt(0) === 0xfeff;
|
|
627
|
+
const records = parseCsv(text).map((r, index) => ({
|
|
628
|
+
index,
|
|
629
|
+
rawFields: r.rawFields,
|
|
630
|
+
eol: r.eol,
|
|
631
|
+
value: (col) => csvValue(r.rawFields[col] ?? ''),
|
|
632
|
+
}));
|
|
633
|
+
|
|
634
|
+
// allowed columns; missing ones are APPENDED (still verdict/evidence/notes
|
|
635
|
+
// fields only — the scenario and row-number columns are never touched)
|
|
636
|
+
const width = records.reduce((n, r) => Math.max(n, r.rawFields.length), 0);
|
|
637
|
+
let nextCol = width;
|
|
638
|
+
const append = (idx, label) => {
|
|
639
|
+
if (idx !== null) return idx;
|
|
640
|
+
for (let i = 0; i < records.length; i++) records[i].rawFields.push(i === 0 ? label : '');
|
|
641
|
+
return nextCol++; // 0-based index of the just-appended column
|
|
642
|
+
};
|
|
643
|
+
const colVerdict = append(sheet.columns.verdict, 'Result');
|
|
644
|
+
const colEvidence = append(sheet.columns.evidence, 'Evidence');
|
|
645
|
+
const colNotes = append(sheet.columns.notes, 'Notes');
|
|
646
|
+
|
|
647
|
+
// data rows = records after the header whose scenario cell is non-empty,
|
|
648
|
+
// aligned POSITIONALLY with the snapshot rows; hash re-verified per row.
|
|
649
|
+
const dataRecords = records.slice(1).filter((r) => String(r.value(sheet.columns.scenario) ?? '').trim() !== '');
|
|
650
|
+
let writes;
|
|
651
|
+
try {
|
|
652
|
+
writes = alignAndVerify(sheet, dataRecords);
|
|
653
|
+
} catch (e) {
|
|
654
|
+
return refuse('clientlist-drift', e.message);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// rebuild: raw fields preserved verbatim except the allowed cells
|
|
658
|
+
let rowsWritten = 0;
|
|
659
|
+
for (const [recordIndex, w] of writes) {
|
|
660
|
+
const rec = records[recordIndex];
|
|
661
|
+
if (w.verdict !== undefined) rec.rawFields[colVerdict] = csvRaw(w.verdict);
|
|
662
|
+
if (w.evidence !== undefined) rec.rawFields[colEvidence] = csvRaw(w.evidence);
|
|
663
|
+
if (w.notes !== undefined) rec.rawFields[colNotes] = csvRaw(w.notes);
|
|
664
|
+
rowsWritten++;
|
|
665
|
+
}
|
|
666
|
+
const rebuilt = (hadBom ? '\ufeff' : '') + records.map((r) => r.rawFields.join(',') + r.eol).join('');
|
|
667
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
668
|
+
writeAtomic(outPath, rebuilt);
|
|
669
|
+
return { ok: true, rowsWritten };
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// xlsx export lane — implemented with the task-4 bridge (probe + generated
|
|
673
|
+
// python). Same rules: align + verify hashes against the pristine copy
|
|
674
|
+
// FIRST, then apply only the allowed cell ops, atomically.
|
|
675
|
+
function exportXlsx(snap, pristine, outPath) {
|
|
676
|
+
const probe = probePython();
|
|
677
|
+
if (!probe.ok) {
|
|
678
|
+
return refuse('clientlist-bridge', `${probe.reason}.\n${SETUP_INSTRUCTIONS}`,
|
|
679
|
+
{ instructions: SETUP_INSTRUCTIONS });
|
|
680
|
+
}
|
|
681
|
+
const read = runBridge(probe.python, PY_READ, { file: pristine });
|
|
682
|
+
const byName = new Map(read.sheets.map((s) => [s.name, s]));
|
|
683
|
+
|
|
684
|
+
const ops = [];
|
|
685
|
+
let rowsWritten = 0;
|
|
686
|
+
for (const sheet of snap.sheets) {
|
|
687
|
+
const live = byName.get(sheet.name);
|
|
688
|
+
if (!live) {
|
|
689
|
+
return refuse('clientlist-drift',
|
|
690
|
+
`scenario drift: sheet "${sheet.name}" missing from the pristine copy — re-import before exporting`);
|
|
691
|
+
}
|
|
692
|
+
const width = live.rows.reduce((n, r) => Math.max(n, r.fields.length), 0);
|
|
693
|
+
const colVerdict = sheet.columns.verdict !== null ? sheet.columns.verdict : width;
|
|
694
|
+
const colEvidence = sheet.columns.evidence !== null ? sheet.columns.evidence : width + 1;
|
|
695
|
+
const colNotes = sheet.columns.notes !== null ? sheet.columns.notes : width + 2;
|
|
696
|
+
const headerRow = live.rows[0];
|
|
697
|
+
const hdr = (col, label) => {
|
|
698
|
+
if (col >= headerRow.fields.length) {
|
|
699
|
+
ops.push({ sheet: sheet.name, row: headerRow.excel_row, col: col + 1, value: label });
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
hdr(colVerdict, 'Result');
|
|
703
|
+
hdr(colEvidence, 'Evidence');
|
|
704
|
+
hdr(colNotes, 'Notes');
|
|
705
|
+
|
|
706
|
+
const dataRecords = live.rows.slice(1)
|
|
707
|
+
.map((r, i) => ({ index: i + 1, fields: r.fields, excel_row: r.excel_row, value: (c) => r.fields[c] ?? '' }))
|
|
708
|
+
.filter((r) => String(r.value(sheet.columns.scenario) ?? '').trim() !== '');
|
|
709
|
+
let writes;
|
|
710
|
+
try {
|
|
711
|
+
writes = alignAndVerify(sheet, dataRecords);
|
|
712
|
+
} catch (e) {
|
|
713
|
+
return refuse('clientlist-drift', e.message);
|
|
714
|
+
}
|
|
715
|
+
const byIndex = new Map(dataRecords.map((r) => [r.index, r]));
|
|
716
|
+
for (const [recIndex, w] of writes) {
|
|
717
|
+
const rec = byIndex.get(recIndex);
|
|
718
|
+
if (w.verdict !== undefined) ops.push({ sheet: sheet.name, row: rec.excel_row, col: colVerdict + 1, value: w.verdict });
|
|
719
|
+
if (w.evidence !== undefined) ops.push({ sheet: sheet.name, row: rec.excel_row, col: colEvidence + 1, value: w.evidence });
|
|
720
|
+
if (w.notes !== undefined) ops.push({ sheet: sheet.name, row: rec.excel_row, col: colNotes + 1, value: w.notes });
|
|
721
|
+
rowsWritten++;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
726
|
+
const tmp = `${outPath}.tmp-${process.pid}`;
|
|
727
|
+
try {
|
|
728
|
+
runBridge(probe.python, PY_WRITE, { source: pristine, out: tmp, ops });
|
|
729
|
+
fs.renameSync(tmp, outPath);
|
|
730
|
+
} catch (e) {
|
|
731
|
+
try { fs.unlinkSync(tmp); } catch { /* nothing to clean */ }
|
|
732
|
+
throw e;
|
|
733
|
+
}
|
|
734
|
+
return { ok: true, rowsWritten };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// ---- clientlist.status ----
|
|
738
|
+
//
|
|
739
|
+
// Per-sheet and overall counts. The five states are exhaustive and mutually
|
|
740
|
+
// exclusive: no_done / no_na / yes (the three verdict tiers), blocked
|
|
741
|
+
// (empty verdict + blocker note), untouched (everything else — never counted
|
|
742
|
+
// as covered; coverage is never fabricated).
|
|
743
|
+
|
|
744
|
+
function countRows(rows) {
|
|
745
|
+
const c = { total: rows.length, no_done: 0, no_na: 0, yes: 0, blocked: 0, untouched: 0 };
|
|
746
|
+
for (const row of rows) {
|
|
747
|
+
if (row.verdict && row.verdict.tier === 'no_done') c.no_done++;
|
|
748
|
+
else if (row.verdict && row.verdict.tier === 'no_na') c.no_na++;
|
|
749
|
+
else if (row.verdict && row.verdict.tier === 'yes') c.yes++;
|
|
750
|
+
else if (!row.verdict && row.blocker_note) c.blocked++;
|
|
751
|
+
else c.untouched++;
|
|
752
|
+
}
|
|
753
|
+
return c;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function status(dir, { slug } = {}) {
|
|
757
|
+
const dirAbs = requireEngagementDir(dir);
|
|
758
|
+
if (!slug) throw new Error('clientlist.status requires --slug');
|
|
759
|
+
const snap = loadSnapshot(dirAbs, slug);
|
|
760
|
+
|
|
761
|
+
const sheets = snap.sheets.map((s) => ({
|
|
762
|
+
name: s.name, index: s.index, counts: countRows(s.rows),
|
|
763
|
+
}));
|
|
764
|
+
const overall = countRows(snap.sheets.flatMap((s) => s.rows));
|
|
765
|
+
return { slug: snap.slug, sheets, overall };
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// ---- clientlist.progressDigest (Phase 19 19-02 / SC4) ----
|
|
769
|
+
//
|
|
770
|
+
// One-line answered-counts-per-tier summary of EVERY imported snapshot, for
|
|
771
|
+
// the STATE.md digest on status transitions (lib/state.cjs):
|
|
772
|
+
// "<slug> <answered>/<total> answered (no_done X, no_na Y, yes Z, blocked
|
|
773
|
+
// B, untouched U)" — one part per snapshot, '; '-joined.
|
|
774
|
+
// answered = no_done + no_na + yes (the three verdict tiers; blocked and
|
|
775
|
+
// untouched never count as answered — coverage is never fabricated).
|
|
776
|
+
// Returns null when the engagement carries no readable snapshot (the caller
|
|
777
|
+
// then leaves the digest untouched).
|
|
778
|
+
|
|
779
|
+
function progressDigest(dir) {
|
|
780
|
+
const dirAbs = path.resolve(dir);
|
|
781
|
+
const clDir = clientlistDir(dirAbs);
|
|
782
|
+
if (!fs.existsSync(clDir)) return null;
|
|
783
|
+
const slugs = fs.readdirSync(clDir).filter((f) => f.endsWith('.json')).sort();
|
|
784
|
+
const parts = [];
|
|
785
|
+
for (const f of slugs) {
|
|
786
|
+
let snap;
|
|
787
|
+
try {
|
|
788
|
+
snap = JSON.parse(fs.readFileSync(path.join(clDir, f), 'utf8'));
|
|
789
|
+
} catch {
|
|
790
|
+
continue; // unreadable snapshot contributes no digest part
|
|
791
|
+
}
|
|
792
|
+
if (!snap || !Array.isArray(snap.sheets)) continue;
|
|
793
|
+
const c = countRows(snap.sheets.flatMap((s) => s.rows || []));
|
|
794
|
+
const answered = c.no_done + c.no_na + c.yes;
|
|
795
|
+
parts.push(
|
|
796
|
+
`${snap.slug || f.replace(/\.json$/, '')} ${answered}/${c.total} answered `
|
|
797
|
+
+ `(no_done ${c.no_done}, no_na ${c.no_na}, yes ${c.yes}, blocked ${c.blocked}, untouched ${c.untouched})`
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
return parts.length > 0 ? parts.join('; ') : null;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
module.exports = {
|
|
804
|
+
importWorkbook,
|
|
805
|
+
write,
|
|
806
|
+
list,
|
|
807
|
+
exportWorkbook,
|
|
808
|
+
status,
|
|
809
|
+
progressDigest,
|
|
810
|
+
probePython,
|
|
811
|
+
SETUP_INSTRUCTIONS,
|
|
812
|
+
// exported for tests/export internals
|
|
813
|
+
_internals: { parseCsv, csvValue, csvRaw, resolveColumns, buildSheet, slugify },
|
|
814
|
+
};
|