pincer-workflow 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +7 -5
  2. package/bin/pincer.js +42 -5
  3. package/package.json +2 -2
  4. package/template/.agents/skills/pincer-code/SKILL.md +51 -4
  5. package/template/.agents/skills/pincer-evaluate/SKILL.md +29 -2
  6. package/template/.agents/skills/pincer-narrow/SKILL.md +11 -2
  7. package/template/.agents/skills/pincer-plan/SKILL.md +9 -1
  8. package/template/.agents/skills/pincer-release/SKILL.md +14 -3
  9. package/template/.agents/skills/pincer-status/SKILL.md +17 -2
  10. package/template/.claude/commands/pincer-code.md +51 -4
  11. package/template/.claude/commands/pincer-evaluate.md +29 -2
  12. package/template/.claude/commands/pincer-narrow.md +11 -2
  13. package/template/.claude/commands/pincer-plan.md +9 -1
  14. package/template/.claude/commands/pincer-release.md +14 -3
  15. package/template/.claude/commands/pincer-status.md +17 -2
  16. package/template/.claude/hooks/hook-policy.cjs +17 -3
  17. package/template/.claude/references/ticket-template.md +4 -0
  18. package/template/.codex/README.md +3 -2
  19. package/template/.github/prompts/pincer-code.prompt.md +51 -4
  20. package/template/.github/prompts/pincer-evaluate.prompt.md +29 -2
  21. package/template/.github/prompts/pincer-narrow.prompt.md +11 -2
  22. package/template/.github/prompts/pincer-plan.prompt.md +9 -1
  23. package/template/.github/prompts/pincer-release.prompt.md +14 -3
  24. package/template/.github/prompts/pincer-status.prompt.md +17 -2
  25. package/template/AGENTS.md +6 -0
  26. package/template/docs/dry-run-checklist.md +46 -3
  27. package/template/docs/release-checklist.md +2 -1
  28. package/template/docs/runtime-contracts.md +437 -0
  29. package/template/scripts/pincer-evidence.cjs +5 -223
  30. package/template/scripts/pincer-runtime/evidence.cjs +391 -0
  31. package/template/scripts/pincer-runtime/fsutil.cjs +37 -0
  32. package/template/scripts/pincer-runtime/identity.cjs +146 -0
  33. package/template/scripts/pincer-runtime/lifecycle.cjs +289 -0
  34. package/template/scripts/pincer-runtime/migrate.cjs +127 -0
  35. package/template/scripts/pincer-runtime/parse.cjs +297 -0
  36. package/template/scripts/pincer-runtime/readiness.cjs +89 -0
  37. package/template/scripts/pincer-runtime/runner.cjs +224 -0
  38. package/template/scripts/pincer-runtime/sanitize.cjs +63 -0
  39. package/template/scripts/pincer-runtime/source.cjs +129 -0
  40. package/template/scripts/pincer-runtime/state.cjs +292 -0
  41. package/template/scripts/pincer-runtime/status.cjs +358 -0
  42. package/template/scripts/pincer-runtime.cjs +350 -0
  43. package/template/scripts/pincer-status.sh +11 -162
  44. package/template/scripts/pincer-ticket.sh +19 -139
  45. package/template/scripts/pincer-ticket-lib.sh +0 -321
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
- // PINCER evidence — read-only validator for candidate evidence manifests
4
- // (evidence schema 1). Dependency-free; runs under `node` on any platform.
3
+ // PINCER evidence — read-only validator for candidate evidence manifests.
4
+ // Dependency-free; runs under `node` on any platform. The implementation lives
5
+ // in scripts/pincer-runtime/evidence.cjs (shared with status and release).
5
6
  //
6
7
  // node scripts/pincer-evidence.cjs validate .prd/evidence/prd-vN/<candidate>/manifest.json \
7
8
  // [--candidate <sha>] [--base <sha>] [--prd .prd/prd-vN.md] [--files]
@@ -20,226 +21,7 @@
20
21
  // application; that judgment stays with the reviewer.
21
22
  const fs = require('node:fs');
22
23
  const path = require('node:path');
23
- const crypto = require('node:crypto');
24
- const { execFileSync } = require('node:child_process');
25
-
26
- const SCHEMA = 1;
27
- const HEX40 = /^[0-9a-f]{40}$/;
28
- const SHA256 = /^[0-9a-f]{64}$/;
29
- const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
30
- const PRD_REF = /^\.prd\/prd-v([1-9][0-9]{0,8})\.md$/;
31
- const MANIFEST_AT = /^\.prd\/evidence\/prd-v([1-9][0-9]{0,8})\/([0-9a-f]{40})\/manifest\.json$/;
32
- // Requirement IDs are the PRD's own: R-01 from the template, or a supplied PRD's
33
- // REQ-1 / AC-12 style, kept verbatim rather than renamed.
34
- const REQ_ID = /^[A-Z][A-Z0-9]{0,7}-[0-9]{1,6}$/;
35
- const TICKET_ID = /^T-[0-9]{2,6}$/;
36
- const CHECK_ID = /^C-[0-9]{2,6}$/;
37
- const IMAGE = /\.(png|jpe?g|webp)$/i;
38
- const MAX_TEXT = 2000; // guard against pasted environment dumps
39
- const TOP_KEYS = ['schema', 'prd', 'base', 'candidate', 'created', 'environment', 'coverage_review', 'requirements', 'checks', 'visual_review', 'artifacts'];
40
- const ENV_KEYS = ['os', 'node', 'tools', 'limitations'];
41
- const REQ_KEYS = ['id', 'disposition', 'tickets', 'checks', 'note', 'authorized_by'];
42
- const CHECK_KEYS = ['id', 'kind', 'required', 'result', 'command', 'timestamp', 'artifacts', 'scenario', 'viewport', 'observed', 'note'];
43
- const DISPOSITIONS = ['delivered', 'blocked', 'deferred'];
44
- const KINDS = ['command', 'visual', 'review'];
45
- const RESULTS = ['passed', 'failed', 'unverified'];
46
-
47
- const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v);
48
- const shortText = v => typeof v === 'string' && v.length <= MAX_TEXT;
49
- const nonempty = v => shortText(v) && v.trim() !== '';
50
- const toPosix = p => p.split(path.sep).join('/');
51
-
52
- function repoRoot() {
53
- if (process.env.CLAUDE_PROJECT_DIR) return path.resolve(process.env.CLAUDE_PROJECT_DIR);
54
- try {
55
- return execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
56
- } catch {
57
- return process.cwd();
58
- }
59
- }
60
-
61
- // Resolve through symlinks above the repository (macOS /var -> /private/var)
62
- // without requiring the leaf to exist yet.
63
- function realpathDeep(p) {
64
- try { return fs.realpathSync(p); } catch {
65
- const parent = path.dirname(p);
66
- return parent === p ? p : path.join(realpathDeep(parent), path.basename(p));
67
- }
68
- }
69
-
70
- function digestFile(file) {
71
- return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
72
- }
73
-
74
- // Why a repository-relative path is unsafe, or null when it is acceptable.
75
- function unsafePath(p) {
76
- if (p.startsWith('/')) return 'absolute paths are not allowed';
77
- if (/^[A-Za-z]:/.test(p)) return 'drive-letter paths are not allowed';
78
- if (p.includes('\\')) return 'backslashes are not allowed; use repository-relative POSIX paths';
79
- if (p.split('/').some(s => s === '' || s === '.' || s === '..')) return 'path must be normalized and repository-relative (no "..", "." or empty segments)';
80
- return null;
81
- }
82
-
83
- function validate(manifestArg, opts) {
84
- const root = realpathDeep(repoRoot());
85
- const abs = realpathDeep(path.resolve(manifestArg));
86
- const rel = toPosix(path.relative(root, abs));
87
- const at = rel.match(MANIFEST_AT);
88
- if (!at) return [`manifest must live at .prd/evidence/prd-vN/<candidate>/manifest.json inside the repository (got ${rel})`];
89
- const [, dirVersion, dirCandidate] = at;
90
- const dirRel = path.posix.dirname(rel);
91
-
92
- let raw;
93
- try { raw = fs.readFileSync(abs, 'utf8'); } catch { return ['missing — run /pincer-evaluate to write evidence for this candidate']; }
94
- let doc;
95
- try { doc = JSON.parse(raw); } catch (error) { return [`malformed JSON (${error.message})`]; }
96
- if (!isObject(doc)) return ['malformed: the manifest must be a JSON object'];
97
- if (doc.schema !== SCHEMA) return [`unknown evidence schema ${JSON.stringify(doc.schema)} — this runtime validates schema ${SCHEMA}`];
98
-
99
- const problems = [];
100
- const problem = message => problems.push(message);
101
- for (const key of Object.keys(doc)) if (!TOP_KEYS.includes(key)) problem(`unknown top-level key "${key}"`);
102
- for (const key of TOP_KEYS) if (!(key in doc)) problem(`missing "${key}"`);
103
-
104
- const prd = typeof doc.prd === 'string' ? doc.prd.match(PRD_REF) : null;
105
- if (!prd) problem('prd must be a reference of the form .prd/prd-vN.md');
106
- else if (prd[1] !== dirVersion) problem(`wrong PRD: manifest names ${doc.prd} but lives under prd-v${dirVersion}`);
107
- if (opts.prd && doc.prd !== opts.prd) problem(`wrong PRD: manifest is for ${doc.prd}, expected ${opts.prd}`);
108
-
109
- for (const key of ['base', 'candidate']) {
110
- if (typeof doc[key] !== 'string' || !HEX40.test(doc[key])) problem(`${key} must be a full 40-hex commit ID`);
111
- }
112
- if (typeof doc.candidate === 'string' && HEX40.test(doc.candidate) && doc.candidate !== dirCandidate) {
113
- problem(`wrong candidate: manifest names ${doc.candidate} but lives under ${dirCandidate}`);
114
- }
115
- if (opts.candidate && doc.candidate !== opts.candidate) problem(`wrong candidate: manifest is for ${doc.candidate}, expected ${opts.candidate}`);
116
- if (opts.base && doc.base !== opts.base) problem(`wrong base: manifest records ${doc.base}, expected ${opts.base}`);
117
- if (typeof doc.created !== 'string' || !ISO_UTC.test(doc.created)) problem('created must be an ISO-8601 UTC timestamp (YYYY-MM-DDTHH:MM:SSZ)');
118
-
119
- const env = doc.environment;
120
- if (!isObject(env)) problem('environment must be an object with os, node, tools and limitations');
121
- else {
122
- for (const key of ['os', 'node']) if (!nonempty(env[key])) problem(`environment.${key} must be a short nonempty string (redacted summary, not a dump)`);
123
- for (const key of ['tools', 'limitations']) {
124
- if (!Array.isArray(env[key]) || !env[key].every(nonempty)) problem(`environment.${key} must be an array of short strings`);
125
- }
126
- for (const key of Object.keys(env)) if (!ENV_KEYS.includes(key)) problem(`environment.${key} is not allowed — persist redacted summaries only`);
127
- }
128
- if (!nonempty(doc.coverage_review)) problem('coverage_review must be a nonempty string recording the reviewer judgment on requirement coverage');
129
-
130
- // Artifacts: repository-contained regular files with matching digests.
131
- const artifacts = new Map();
132
- if (!Array.isArray(doc.artifacts)) problem('artifacts must be an array of {path, sha256}');
133
- else doc.artifacts.forEach((entry, index) => {
134
- const label = `artifacts[${index}]`;
135
- if (!isObject(entry)) { problem(`${label} must be an object {path, sha256}`); return; }
136
- for (const key of Object.keys(entry)) if (!['path', 'sha256'].includes(key)) problem(`${label}.${key} is not allowed`);
137
- const p = entry.path;
138
- if (typeof p !== 'string' || p === '') { problem(`${label}.path must be a nonempty string`); return; }
139
- if (artifacts.has(p)) problem(`duplicate artifact path ${p}`);
140
- artifacts.set(p, false);
141
- const why = unsafePath(p);
142
- if (why) { problem(`artifact ${p}: ${why}`); return; }
143
- if (!p.startsWith(`${dirRel}/`)) { problem(`artifact ${p}: outside the evidence directory ${dirRel}/`); return; }
144
- const digestOk = typeof entry.sha256 === 'string' && SHA256.test(entry.sha256);
145
- if (!digestOk) problem(`artifact ${p}: sha256 must be a full 64-hex digest`);
146
- const segments = p.split('/');
147
- let current = root;
148
- for (let i = 0; i < segments.length; i++) {
149
- current = path.join(current, segments[i]);
150
- let stat;
151
- try { stat = fs.lstatSync(current); } catch { problem(`artifact ${p}: missing`); return; }
152
- const last = i === segments.length - 1;
153
- if (stat.isSymbolicLink()) {
154
- problem(last ? `artifact ${p}: is a symlink (only regular files inside the repository are accepted)` : `artifact ${p}: path component ${segments.slice(0, i + 1).join('/')} is a symlink`);
155
- return;
156
- }
157
- if (!last && !stat.isDirectory()) { problem(`artifact ${p}: ${segments.slice(0, i + 1).join('/')} is not a directory`); return; }
158
- if (last && !stat.isFile()) { problem(`artifact ${p}: not a regular file`); return; }
159
- }
160
- if (digestOk && digestFile(current) !== entry.sha256) problem(`artifact ${p}: digest mismatch — the file changed after the evidence was recorded`);
161
- });
162
-
163
- // Checks: what was run or judged, with results and artifact references.
164
- const checks = new Map();
165
- let visualChecks = 0;
166
- if (!Array.isArray(doc.checks)) problem('checks must be an array');
167
- else doc.checks.forEach((check, index) => {
168
- const label = `checks[${index}]`;
169
- if (!isObject(check)) { problem(`${label} must be an object`); return; }
170
- const id = typeof check.id === 'string' && CHECK_ID.test(check.id) ? check.id : null;
171
- if (!id) problem(`${label}.id must be a check ID such as C-01`);
172
- else if (checks.has(id)) problem(`duplicate check ID ${id}`);
173
- else checks.set(id, check);
174
- const name = id || label;
175
- for (const key of Object.keys(check)) if (!CHECK_KEYS.includes(key)) problem(`check ${name}: unknown key "${key}"`);
176
- if (!KINDS.includes(check.kind)) problem(`check ${name}: kind must be one of ${KINDS.join(', ')}`);
177
- if (typeof check.required !== 'boolean') problem(`check ${name}: required must be true or false`);
178
- if (!RESULTS.includes(check.result)) problem(`check ${name}: result must be one of ${RESULTS.join(', ')}`);
179
- if (typeof check.timestamp !== 'string' || !ISO_UTC.test(check.timestamp)) problem(`check ${name}: timestamp must be an ISO-8601 UTC timestamp`);
180
- if (check.kind === 'command' && !nonempty(check.command)) problem(`check ${name}: command kind requires the command that was run`);
181
- for (const key of ['command', 'scenario', 'viewport', 'observed', 'note']) {
182
- if (key in check && !shortText(check[key])) problem(`check ${name}: ${key} must be a short string`);
183
- }
184
- let images = 0;
185
- if (!Array.isArray(check.artifacts)) problem(`check ${name}: artifacts must be an array of repository-relative paths`);
186
- else for (const p of check.artifacts) {
187
- if (typeof p !== 'string') { problem(`check ${name}: artifact reference must be a string`); continue; }
188
- if (!artifacts.has(p)) problem(`check ${name}: references unlisted artifact ${p} (dangling reference)`);
189
- else artifacts.set(p, true);
190
- if (IMAGE.test(p)) images++;
191
- }
192
- if (check.kind === 'visual') {
193
- visualChecks++;
194
- for (const key of ['scenario', 'viewport', 'observed']) if (!nonempty(check[key])) problem(`check ${name}: visual check requires ${key}`);
195
- // A passed visual check must show its image; an unverified one (tool
196
- // unavailable) is recorded honestly without one and, when required, blocks.
197
- if (check.result === 'passed' && images === 0) problem(`check ${name}: a passed visual check requires a saved image artifact (.png, .jpg or .webp)`);
198
- }
199
- if (check.required === true && check.result !== 'passed') {
200
- problem(`required check ${name} is ${check.result} — readiness is blocked until it passes on a new candidate or the requirement is deferred with authorization`);
201
- }
202
- });
203
- for (const [p, referenced] of artifacts) if (!referenced) problem(`artifact ${p}: not referenced by any check`);
204
-
205
- // Requirements: every ID dispositioned; deferrals authorized; checks resolve.
206
- const requirements = new Set();
207
- if (!Array.isArray(doc.requirements) || doc.requirements.length === 0) problem('requirements must be a nonempty array — every PRD requirement needs a disposition');
208
- else doc.requirements.forEach((req, index) => {
209
- const label = `requirements[${index}]`;
210
- if (!isObject(req)) { problem(`${label} must be an object`); return; }
211
- const id = typeof req.id === 'string' && REQ_ID.test(req.id) ? req.id : null;
212
- if (!id) problem(`${label}.id must be a requirement ID such as R-01 or the PRD's own REQ-1 (uppercase prefix, dash, digits)`);
213
- else if (requirements.has(id)) problem(`duplicate requirement ID ${id}`);
214
- else requirements.add(id);
215
- const name = id || label;
216
- for (const key of Object.keys(req)) if (!REQ_KEYS.includes(key)) problem(`requirement ${name}: unknown key "${key}"`);
217
- if (!DISPOSITIONS.includes(req.disposition)) problem(`requirement ${name}: disposition must be one of ${DISPOSITIONS.join(', ')}`);
218
- if (!Array.isArray(req.tickets) || !req.tickets.every(t => typeof t === 'string' && TICKET_ID.test(t))) problem(`requirement ${name}: tickets must be an array of ticket IDs such as T-01`);
219
- if (!Array.isArray(req.checks)) problem(`requirement ${name}: checks must be an array of check IDs`);
220
- else for (const c of req.checks) {
221
- if (typeof c !== 'string' || !checks.has(c)) problem(`requirement ${name}: references unknown check ${JSON.stringify(c)} (dangling reference)`);
222
- }
223
- for (const key of ['note', 'authorized_by']) if (key in req && !shortText(req[key])) problem(`requirement ${name}: ${key} must be a short string`);
224
- if (req.disposition === 'deferred' && !nonempty(req.authorized_by)) problem(`requirement ${name}: deferred requires authorized_by naming the explicit user authorization`);
225
- if (req.disposition === 'delivered' && Array.isArray(req.checks) && req.checks.length === 0) problem(`requirement ${name}: delivered requires at least one check`);
226
- if (req.disposition === 'blocked') problem(`requirement ${name} is blocked — readiness is blocked until it is delivered on a new candidate or deferred with authorization`);
227
- });
228
-
229
- const visual = doc.visual_review;
230
- if (!isObject(visual) || typeof visual.applicable !== 'boolean') problem('visual_review must be {applicable: boolean, reason?: string}');
231
- else {
232
- for (const key of Object.keys(visual)) if (!['applicable', 'reason'].includes(key)) problem(`visual_review.${key} is not allowed`);
233
- if (visual.applicable === false && !nonempty(visual.reason)) problem('visual_review.reason is required when visual review is not applicable (say why)');
234
- if (visual.applicable === true && visualChecks === 0) problem('visual_review.applicable is true but no visual check is recorded');
235
- if ('reason' in visual && !shortText(visual.reason)) problem('visual_review.reason must be a short string');
236
- }
237
-
238
- if (problems.length === 0 && opts.files) {
239
- opts.list = [rel, ...doc.artifacts.map(a => a.path)];
240
- }
241
- return problems;
242
- }
24
+ const { HEX40, PRD_REF, validate, digestFile } = require('./pincer-runtime/evidence.cjs');
243
25
 
244
26
  function usage(message) {
245
27
  if (message) process.stderr.write(`pincer-evidence: ${message}\n`);
@@ -273,7 +55,7 @@ function main(argv) {
273
55
  process.exit(1);
274
56
  }
275
57
  const doc = JSON.parse(fs.readFileSync(path.resolve(manifest), 'utf8'));
276
- process.stdout.write(`ok ${doc.candidate}\n`);
58
+ process.stdout.write(`ok ${doc.candidate}${doc.schema === 2 ? ' schema 2' : ''}\n`);
277
59
  if (opts.files) for (const p of opts.list) process.stdout.write(`${p}\n`);
278
60
  return;
279
61
  }
@@ -0,0 +1,391 @@
1
+ 'use strict';
2
+ // PINCER runtime — candidate evidence (docs/runtime-contracts.md, "Evidence
3
+ // schema 2"). Schema 1 validation lives here unchanged from v0.4.1 so status,
4
+ // release and the pincer-evidence.cjs entry point share one implementation.
5
+ //
6
+ // What validation establishes: that the locally authored record is internally
7
+ // consistent — schema, references, candidate association, required results,
8
+ // artifact existence and digests, repository containment. It is NOT independent
9
+ // attestation that the recorded commands ran or that images depict the stated
10
+ // application; that judgment stays with the reviewer.
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+ const crypto = require('node:crypto');
14
+ const { execFileSync } = require('node:child_process');
15
+ const { validateAttempt, contextKey } = require('./state.cjs');
16
+
17
+ const SCHEMA = 1;
18
+ const HEX40 = /^[0-9a-f]{40}$/;
19
+ const SHA256 = /^[0-9a-f]{64}$/;
20
+ const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
21
+ const PRD_REF = /^\.prd\/prd-v([1-9][0-9]{0,8})\.md$/;
22
+ const MANIFEST_AT = /^\.prd\/evidence\/prd-v([1-9][0-9]{0,8})\/([0-9a-f]{40})\/manifest\.json$/;
23
+ // Requirement IDs are the PRD's own: R-01 from the template, or a supplied PRD's
24
+ // REQ-1 / AC-12 style, kept verbatim rather than renamed.
25
+ const REQ_ID = /^[A-Z][A-Z0-9]{0,7}-[0-9]{1,6}$/;
26
+ const TICKET_ID = /^T-[0-9]{2,6}$/;
27
+ const CHECK_ID = /^C-[0-9]{2,6}$/;
28
+ const IMAGE = /\.(png|jpe?g|webp)$/i;
29
+ const MAX_TEXT = 2000; // guard against pasted environment dumps
30
+ const TOP_KEYS = ['schema', 'prd', 'base', 'candidate', 'created', 'environment', 'coverage_review', 'requirements', 'checks', 'visual_review', 'artifacts'];
31
+ const ENV_KEYS = ['os', 'node', 'tools', 'limitations'];
32
+ const REQ_KEYS = ['id', 'disposition', 'tickets', 'checks', 'note', 'authorized_by'];
33
+ const CHECK_KEYS = ['id', 'kind', 'required', 'result', 'command', 'timestamp', 'artifacts', 'scenario', 'viewport', 'observed', 'note'];
34
+ const DISPOSITIONS = ['delivered', 'blocked', 'deferred'];
35
+ const KINDS = ['command', 'visual', 'review'];
36
+ const RESULTS = ['passed', 'failed', 'unverified'];
37
+ // Schema 2 (docs/runtime-contracts.md, "Evidence schema 2"): a change binding,
38
+ // provenance per check, and attempt provenance on runtime command checks.
39
+ const SCHEMAS = [1, 2];
40
+ const TOP_KEYS_2 = [...TOP_KEYS, 'change'];
41
+ const CHECK_KEYS_2 = [...CHECK_KEYS, 'provenance', 'attempt'];
42
+ const PROVENANCE = ['runtime', 'authored'];
43
+ const ATTEMPT_KEYS = ['id', 'sequence', 'outcome', 'exit_code', 'started', 'finished', 'source_before', 'source_after', 'check_digest', 'runner', 'cwd', 'log_sha256', 'truncated'];
44
+ const OUTCOMES = ['passed', 'failed', 'timed_out', 'interrupted', 'error'];
45
+ const CHANGE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
46
+ const resultFor = outcome => (outcome === 'passed' ? 'passed' : outcome === 'error' ? 'unverified' : 'failed');
47
+
48
+ const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v);
49
+ const shortText = v => typeof v === 'string' && v.length <= MAX_TEXT;
50
+ const nonempty = v => shortText(v) && v.trim() !== '';
51
+ const toPosix = p => p.split(path.sep).join('/');
52
+
53
+ function repoRoot() {
54
+ if (process.env.CLAUDE_PROJECT_DIR) return path.resolve(process.env.CLAUDE_PROJECT_DIR);
55
+ try {
56
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
57
+ } catch {
58
+ return process.cwd();
59
+ }
60
+ }
61
+
62
+ // Resolve through symlinks above the repository (macOS /var -> /private/var)
63
+ // without requiring the leaf to exist yet.
64
+ function realpathDeep(p) {
65
+ try { return fs.realpathSync(p); } catch {
66
+ const parent = path.dirname(p);
67
+ return parent === p ? p : path.join(realpathDeep(parent), path.basename(p));
68
+ }
69
+ }
70
+
71
+ function digestFile(file) {
72
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
73
+ }
74
+
75
+ // Why a repository-relative path is unsafe, or null when it is acceptable.
76
+ function unsafePath(p) {
77
+ if (p.startsWith('/')) return 'absolute paths are not allowed';
78
+ if (/^[A-Za-z]:/.test(p)) return 'drive-letter paths are not allowed';
79
+ if (p.includes('\\')) return 'backslashes are not allowed; use repository-relative POSIX paths';
80
+ if (p.split('/').some(s => s === '' || s === '.' || s === '..')) return 'path must be normalized and repository-relative (no "..", "." or empty segments)';
81
+ return null;
82
+ }
83
+
84
+ function validate(manifestArg, opts, rootArg) {
85
+ const root = realpathDeep(rootArg || repoRoot());
86
+ const abs = realpathDeep(path.resolve(manifestArg));
87
+ const rel = toPosix(path.relative(root, abs));
88
+ const at = rel.match(MANIFEST_AT);
89
+ if (!at) return [`manifest must live at .prd/evidence/prd-vN/<candidate>/manifest.json inside the repository (got ${rel})`];
90
+ const [, dirVersion, dirCandidate] = at;
91
+ const dirRel = path.posix.dirname(rel);
92
+
93
+ let raw;
94
+ try { raw = fs.readFileSync(abs, 'utf8'); } catch { return ['missing — run /pincer-evaluate to write evidence for this candidate']; }
95
+ let doc;
96
+ try { doc = JSON.parse(raw); } catch (error) { return [`malformed JSON (${error.message})`]; }
97
+ if (!isObject(doc)) return ['malformed: the manifest must be a JSON object'];
98
+ if (!SCHEMAS.includes(doc.schema)) return [`unknown evidence schema ${JSON.stringify(doc.schema)} — this runtime validates schemas ${SCHEMAS.join(' and ')}`];
99
+ const schema2 = doc.schema === 2;
100
+ const topKeys = schema2 ? TOP_KEYS_2 : TOP_KEYS;
101
+ const checkKeys = schema2 ? CHECK_KEYS_2 : CHECK_KEYS;
102
+
103
+ const problems = [];
104
+ const problem = message => problems.push(message);
105
+ for (const key of Object.keys(doc)) if (!topKeys.includes(key)) problem(`unknown top-level key "${key}"`);
106
+ for (const key of topKeys) if (!(key in doc)) problem(`missing "${key}"`);
107
+ if (schema2) {
108
+ const change = doc.change;
109
+ if (!isObject(change)) problem('change must be an object {id, prd_revision, base}');
110
+ else {
111
+ for (const key of Object.keys(change)) if (!['id', 'prd_revision', 'base'].includes(key)) problem(`change.${key} is not allowed`);
112
+ if (typeof change.id !== 'string' || !CHANGE_ID.test(change.id)) problem('change.id must be a change ID ([a-z0-9][a-z0-9-]{0,63})');
113
+ if (typeof change.prd_revision !== 'string' || !SHA256.test(change.prd_revision)) problem('change.prd_revision must be a 64-hex SHA-256 digest');
114
+ if (typeof change.base !== 'string' || !HEX40.test(change.base)) problem('change.base must be a full 40-hex commit ID');
115
+ }
116
+ }
117
+
118
+ const prd = typeof doc.prd === 'string' ? doc.prd.match(PRD_REF) : null;
119
+ if (!prd) problem('prd must be a reference of the form .prd/prd-vN.md');
120
+ else if (prd[1] !== dirVersion) problem(`wrong PRD: manifest names ${doc.prd} but lives under prd-v${dirVersion}`);
121
+ if (opts.prd && doc.prd !== opts.prd) problem(`wrong PRD: manifest is for ${doc.prd}, expected ${opts.prd}`);
122
+
123
+ for (const key of ['base', 'candidate']) {
124
+ if (typeof doc[key] !== 'string' || !HEX40.test(doc[key])) problem(`${key} must be a full 40-hex commit ID`);
125
+ }
126
+ if (typeof doc.candidate === 'string' && HEX40.test(doc.candidate) && doc.candidate !== dirCandidate) {
127
+ problem(`wrong candidate: manifest names ${doc.candidate} but lives under ${dirCandidate}`);
128
+ }
129
+ if (opts.candidate && doc.candidate !== opts.candidate) problem(`wrong candidate: manifest is for ${doc.candidate}, expected ${opts.candidate}`);
130
+ if (opts.base && doc.base !== opts.base) problem(`wrong base: manifest records ${doc.base}, expected ${opts.base}`);
131
+ if (typeof doc.created !== 'string' || !ISO_UTC.test(doc.created)) problem('created must be an ISO-8601 UTC timestamp (YYYY-MM-DDTHH:MM:SSZ)');
132
+
133
+ const env = doc.environment;
134
+ if (!isObject(env)) problem('environment must be an object with os, node, tools and limitations');
135
+ else {
136
+ for (const key of ['os', 'node']) if (!nonempty(env[key])) problem(`environment.${key} must be a short nonempty string (redacted summary, not a dump)`);
137
+ for (const key of ['tools', 'limitations']) {
138
+ if (!Array.isArray(env[key]) || !env[key].every(nonempty)) problem(`environment.${key} must be an array of short strings`);
139
+ }
140
+ for (const key of Object.keys(env)) if (!ENV_KEYS.includes(key)) problem(`environment.${key} is not allowed — persist redacted summaries only`);
141
+ }
142
+ if (!nonempty(doc.coverage_review)) problem('coverage_review must be a nonempty string recording the reviewer judgment on requirement coverage');
143
+
144
+ // Artifacts: repository-contained regular files with matching digests.
145
+ const artifacts = new Map();
146
+ if (!Array.isArray(doc.artifacts)) problem('artifacts must be an array of {path, sha256}');
147
+ else doc.artifacts.forEach((entry, index) => {
148
+ const label = `artifacts[${index}]`;
149
+ if (!isObject(entry)) { problem(`${label} must be an object {path, sha256}`); return; }
150
+ for (const key of Object.keys(entry)) if (!['path', 'sha256'].includes(key)) problem(`${label}.${key} is not allowed`);
151
+ const p = entry.path;
152
+ if (typeof p !== 'string' || p === '') { problem(`${label}.path must be a nonempty string`); return; }
153
+ if (artifacts.has(p)) problem(`duplicate artifact path ${p}`);
154
+ artifacts.set(p, false);
155
+ const why = unsafePath(p);
156
+ if (why) { problem(`artifact ${p}: ${why}`); return; }
157
+ if (!p.startsWith(`${dirRel}/`)) { problem(`artifact ${p}: outside the evidence directory ${dirRel}/`); return; }
158
+ const digestOk = typeof entry.sha256 === 'string' && SHA256.test(entry.sha256);
159
+ if (!digestOk) problem(`artifact ${p}: sha256 must be a full 64-hex digest`);
160
+ const segments = p.split('/');
161
+ let current = root;
162
+ for (let i = 0; i < segments.length; i++) {
163
+ current = path.join(current, segments[i]);
164
+ let stat;
165
+ try { stat = fs.lstatSync(current); } catch { problem(`artifact ${p}: missing`); return; }
166
+ const last = i === segments.length - 1;
167
+ if (stat.isSymbolicLink()) {
168
+ problem(last ? `artifact ${p}: is a symlink (only regular files inside the repository are accepted)` : `artifact ${p}: path component ${segments.slice(0, i + 1).join('/')} is a symlink`);
169
+ return;
170
+ }
171
+ if (!last && !stat.isDirectory()) { problem(`artifact ${p}: ${segments.slice(0, i + 1).join('/')} is not a directory`); return; }
172
+ if (last && !stat.isFile()) { problem(`artifact ${p}: not a regular file`); return; }
173
+ }
174
+ if (digestOk && digestFile(current) !== entry.sha256) problem(`artifact ${p}: digest mismatch — the file changed after the evidence was recorded`);
175
+ });
176
+
177
+ // Checks: what was run or judged, with results and artifact references.
178
+ const checks = new Map();
179
+ let visualChecks = 0;
180
+ if (!Array.isArray(doc.checks)) problem('checks must be an array');
181
+ else doc.checks.forEach((check, index) => {
182
+ const label = `checks[${index}]`;
183
+ if (!isObject(check)) { problem(`${label} must be an object`); return; }
184
+ const id = typeof check.id === 'string' && CHECK_ID.test(check.id) ? check.id : null;
185
+ if (!id) problem(`${label}.id must be a check ID such as C-01`);
186
+ else if (checks.has(id)) problem(`duplicate check ID ${id}`);
187
+ else checks.set(id, check);
188
+ const name = id || label;
189
+ for (const key of Object.keys(check)) if (!checkKeys.includes(key)) problem(`check ${name}: unknown key "${key}"`);
190
+ if (!KINDS.includes(check.kind)) problem(`check ${name}: kind must be one of ${KINDS.join(', ')}`);
191
+ if (schema2) validateProvenance(check, name, doc, problem);
192
+ if (typeof check.required !== 'boolean') problem(`check ${name}: required must be true or false`);
193
+ if (!RESULTS.includes(check.result)) problem(`check ${name}: result must be one of ${RESULTS.join(', ')}`);
194
+ if (typeof check.timestamp !== 'string' || !ISO_UTC.test(check.timestamp)) problem(`check ${name}: timestamp must be an ISO-8601 UTC timestamp`);
195
+ if (check.kind === 'command' && !nonempty(check.command)) problem(`check ${name}: command kind requires the command that was run`);
196
+ for (const key of ['command', 'scenario', 'viewport', 'observed', 'note']) {
197
+ if (key in check && !shortText(check[key])) problem(`check ${name}: ${key} must be a short string`);
198
+ }
199
+ let images = 0;
200
+ if (!Array.isArray(check.artifacts)) problem(`check ${name}: artifacts must be an array of repository-relative paths`);
201
+ else for (const p of check.artifacts) {
202
+ if (typeof p !== 'string') { problem(`check ${name}: artifact reference must be a string`); continue; }
203
+ if (!artifacts.has(p)) problem(`check ${name}: references unlisted artifact ${p} (dangling reference)`);
204
+ else artifacts.set(p, true);
205
+ if (IMAGE.test(p)) images++;
206
+ }
207
+ if (check.kind === 'visual') {
208
+ visualChecks++;
209
+ for (const key of ['scenario', 'viewport', 'observed']) if (!nonempty(check[key])) problem(`check ${name}: visual check requires ${key}`);
210
+ // A passed visual check must show its image; an unverified one (tool
211
+ // unavailable) is recorded honestly without one and, when required, blocks.
212
+ if (check.result === 'passed' && images === 0) problem(`check ${name}: a passed visual check requires a saved image artifact (.png, .jpg or .webp)`);
213
+ }
214
+ if (check.required === true && check.result !== 'passed') {
215
+ problem(`required check ${name} is ${check.result} — readiness is blocked until it passes on a new candidate or the requirement is deferred with authorization`);
216
+ }
217
+ });
218
+ for (const [p, referenced] of artifacts) if (!referenced) problem(`artifact ${p}: not referenced by any check`);
219
+
220
+ // Requirements: every ID dispositioned; deferrals authorized; checks resolve.
221
+ const requirements = new Set();
222
+ if (!Array.isArray(doc.requirements) || doc.requirements.length === 0) problem('requirements must be a nonempty array — every PRD requirement needs a disposition');
223
+ else doc.requirements.forEach((req, index) => {
224
+ const label = `requirements[${index}]`;
225
+ if (!isObject(req)) { problem(`${label} must be an object`); return; }
226
+ const id = typeof req.id === 'string' && REQ_ID.test(req.id) ? req.id : null;
227
+ if (!id) problem(`${label}.id must be a requirement ID such as R-01 or the PRD's own REQ-1 (uppercase prefix, dash, digits)`);
228
+ else if (requirements.has(id)) problem(`duplicate requirement ID ${id}`);
229
+ else requirements.add(id);
230
+ const name = id || label;
231
+ for (const key of Object.keys(req)) if (!REQ_KEYS.includes(key)) problem(`requirement ${name}: unknown key "${key}"`);
232
+ if (!DISPOSITIONS.includes(req.disposition)) problem(`requirement ${name}: disposition must be one of ${DISPOSITIONS.join(', ')}`);
233
+ if (!Array.isArray(req.tickets) || !req.tickets.every(t => typeof t === 'string' && TICKET_ID.test(t))) problem(`requirement ${name}: tickets must be an array of ticket IDs such as T-01`);
234
+ if (!Array.isArray(req.checks)) problem(`requirement ${name}: checks must be an array of check IDs`);
235
+ else for (const c of req.checks) {
236
+ if (typeof c !== 'string' || !checks.has(c)) problem(`requirement ${name}: references unknown check ${JSON.stringify(c)} (dangling reference)`);
237
+ }
238
+ for (const key of ['note', 'authorized_by']) if (key in req && !shortText(req[key])) problem(`requirement ${name}: ${key} must be a short string`);
239
+ if (req.disposition === 'deferred' && !nonempty(req.authorized_by)) problem(`requirement ${name}: deferred requires authorized_by naming the explicit user authorization`);
240
+ if (req.disposition === 'delivered' && Array.isArray(req.checks) && req.checks.length === 0) problem(`requirement ${name}: delivered requires at least one check`);
241
+ if (req.disposition === 'blocked') problem(`requirement ${name} is blocked — readiness is blocked until it is delivered on a new candidate or deferred with authorization`);
242
+ });
243
+
244
+ const visual = doc.visual_review;
245
+ if (!isObject(visual) || typeof visual.applicable !== 'boolean') problem('visual_review must be {applicable: boolean, reason?: string}');
246
+ else {
247
+ for (const key of Object.keys(visual)) if (!['applicable', 'reason'].includes(key)) problem(`visual_review.${key} is not allowed`);
248
+ if (visual.applicable === false && !nonempty(visual.reason)) problem('visual_review.reason is required when visual review is not applicable (say why)');
249
+ if (visual.applicable === true && visualChecks === 0) problem('visual_review.applicable is true but no visual check is recorded');
250
+ if ('reason' in visual && !shortText(visual.reason)) problem('visual_review.reason must be a short string');
251
+ }
252
+
253
+ if (problems.length === 0 && opts.files) {
254
+ opts.list = [rel, ...doc.artifacts.map(a => a.path)];
255
+ }
256
+ return problems;
257
+ }
258
+
259
+ // Schema 2: every check declares its provenance; a passed or failed command
260
+ // result exists only as a runtime attempt whose log digest the manifest carries.
261
+ function validateProvenance(check, name, doc, problem) {
262
+ if (!PROVENANCE.includes(check.provenance)) { problem(`check ${name}: provenance must be runtime or authored`); return; }
263
+ const artifactDigest = p => { const entry = Array.isArray(doc.artifacts) ? doc.artifacts.find(a => isObject(a) && a.path === p) : null; return entry ? entry.sha256 : null; };
264
+ if (check.provenance === 'authored') {
265
+ if ('attempt' in check) problem(`check ${name}: an authored check carries no attempt`);
266
+ if (check.kind === 'command' && ['passed', 'failed'].includes(check.result)) problem(`check ${name}: a ${check.result} command check must have runtime provenance (run it through pincer-runtime.cjs check)`);
267
+ return;
268
+ }
269
+ if (check.kind !== 'command') problem(`check ${name}: runtime provenance applies to command checks only`);
270
+ const a = check.attempt;
271
+ if (!isObject(a)) { problem(`check ${name}: runtime provenance requires an attempt object`); return; }
272
+ for (const key of Object.keys(a)) if (!ATTEMPT_KEYS.includes(key)) problem(`check ${name}: attempt.${key} is not allowed`);
273
+ for (const key of ATTEMPT_KEYS) if (!(key in a)) problem(`check ${name}: attempt.${key} is missing`);
274
+ if (!nonempty(a.id)) problem(`check ${name}: attempt.id must be a nonempty string`);
275
+ if (!Number.isInteger(a.sequence) || a.sequence < 1) problem(`check ${name}: attempt.sequence must be a positive integer`);
276
+ if (!OUTCOMES.includes(a.outcome)) problem(`check ${name}: attempt.outcome must be one of ${OUTCOMES.join(', ')}`);
277
+ else if (check.result !== resultFor(a.outcome)) problem(`check ${name}: result ${check.result} disagrees with attempt outcome ${a.outcome} (expected ${resultFor(a.outcome)})`);
278
+ if (a.exit_code !== null && !Number.isInteger(a.exit_code)) problem(`check ${name}: attempt.exit_code must be an integer or null`);
279
+ for (const key of ['started', 'finished']) if (typeof a[key] !== 'string' || !ISO_UTC.test(a[key])) problem(`check ${name}: attempt.${key} must be an ISO-8601 UTC timestamp`);
280
+ for (const key of ['source_before', 'source_after']) if (a[key] !== null && (typeof a[key] !== 'string' || !SHA256.test(a[key]))) problem(`check ${name}: attempt.${key} must be a 64-hex digest or null`);
281
+ if (typeof a.check_digest !== 'string' || !SHA256.test(a.check_digest)) problem(`check ${name}: attempt.check_digest must be a 64-hex digest`);
282
+ if (!isObject(a.runner) || !nonempty(a.runner.shell) || !Array.isArray(a.runner.args) || !nonempty(a.runner.version)) problem(`check ${name}: attempt.runner must be {shell, args, version}`);
283
+ if (!shortText(a.cwd)) problem(`check ${name}: attempt.cwd must be a short string`);
284
+ if (typeof a.truncated !== 'boolean') problem(`check ${name}: attempt.truncated must be true or false`);
285
+ if (typeof a.log_sha256 !== 'string' || !SHA256.test(a.log_sha256)) problem(`check ${name}: attempt.log_sha256 must be a 64-hex digest`);
286
+ else if (Array.isArray(check.artifacts)) {
287
+ const logs = check.artifacts.filter(p => typeof p === 'string' && /\.log$/.test(p));
288
+ if (logs.length !== 1) problem(`check ${name}: a runtime check references exactly one .log artifact`);
289
+ else if (artifactDigest(logs[0]) !== a.log_sha256) problem(`check ${name}: log artifact ${logs[0]} digest does not equal attempt.log_sha256`);
290
+ }
291
+ }
292
+
293
+ // --- Export (schema 2) ---------------------------------------------------------
294
+ // Build the candidate evidence set from a draft of authored fields and the
295
+ // runtime's attempts for the candidate. Never invents a review transcript and
296
+ // never converts a review judgment into a command result.
297
+ function exportEvidence(root, { candidate, base, prd, draft, binding, attemptsFor, environment, now, atomicWrite }) {
298
+ const version = prd.match(PRD_REF)[1];
299
+ const dirRel = `.prd/evidence/prd-v${version}/${candidate}`;
300
+ const dirAbs = path.join(root, dirRel);
301
+ const problems = [];
302
+ if (!isObject(draft)) return { problems: ['draft must be a JSON object'] };
303
+ const allowed = ['environment', 'coverage_review', 'requirements', 'checks', 'visual_review'];
304
+ for (const key of Object.keys(draft)) if (!allowed.includes(key)) problems.push(`draft: unknown key "${key}" (allowed: ${allowed.join(', ')})`);
305
+ if (!Array.isArray(draft.checks)) problems.push('draft.checks must be an array');
306
+ if (problems.length) return { problems };
307
+ const env = isObject(draft.environment) ? draft.environment : {};
308
+ const checks = [];
309
+ const artifactPaths = new Set();
310
+ for (const stub of draft.checks) {
311
+ if (!isObject(stub) || typeof stub.id !== 'string' || !CHECK_ID.test(stub.id)) { problems.push(`draft.checks entries must be objects with a check ID such as C-01 (got ${JSON.stringify(isObject(stub) ? stub.id : stub)})`); continue; }
312
+ // Authored artifact paths are validated before anything is written: no
313
+ // traversal, no absolute paths, and inside this candidate's evidence directory.
314
+ for (const p of Array.isArray(stub.artifacts) ? stub.artifacts : []) {
315
+ if (typeof p !== 'string') { problems.push(`draft check ${stub.id}: artifact references must be strings`); continue; }
316
+ const why = unsafePath(p);
317
+ if (why) problems.push(`draft check ${stub.id}: artifact ${p}: ${why}`);
318
+ else if (!p.startsWith(`${dirRel}/`)) problems.push(`draft check ${stub.id}: artifact ${p}: outside the evidence directory ${dirRel}/`);
319
+ }
320
+ const isStub = stub.kind === 'command' && !('result' in stub);
321
+ if (!isStub) {
322
+ if (stub.kind === 'command' && ['passed', 'failed'].includes(stub.result)) { problems.push(`draft check ${stub.id}: a ${stub.result} command result cannot be authored; omit result to populate it from the runtime attempt`); continue; }
323
+ const authored = { ...stub, provenance: 'authored' };
324
+ delete authored.attempt;
325
+ for (const p of authored.artifacts || []) artifactPaths.add(p);
326
+ checks.push(authored);
327
+ continue;
328
+ }
329
+ const { attempt, pointed } = attemptsFor(stub.id);
330
+ if (!attempt) { problems.push(`draft check ${stub.id}: no runtime attempt for candidate ${candidate}; run: node scripts/pincer-runtime.cjs check ${stub.id} --candidate ${candidate} -- <command>`); continue; }
331
+ // The record must be complete, written for this check, and its captured
332
+ // logs must still match the digests it recorded; anything else is refused.
333
+ const invalid = validateAttempt(attempt, contextKey({ kind: 'candidate', candidate, check: stub.id }), pointed || null);
334
+ if (invalid) { problems.push(`draft check ${stub.id}: attempt ${typeof attempt.id === 'string' ? attempt.id : '?'} ${invalid}; run the check again`); continue; }
335
+ if (attempt.outcome === 'running') { problems.push(`draft check ${stub.id}: attempt ${attempt.id} is still running`); continue; }
336
+ const logRel = `${dirRel}/checks/${stub.id}.log`;
337
+ const pieces = [`$ ${(attempt.check && attempt.check.display) || ''}`.replace(/\n$/, ''), ''];
338
+ let missing = false, altered = null;
339
+ for (const stream of ['stdout', 'stderr']) {
340
+ const info = attempt.artifacts[stream];
341
+ const file = path.join(root, info.path);
342
+ let text = '';
343
+ if (fs.existsSync(file)) {
344
+ const data = fs.readFileSync(file);
345
+ if (info.sha256 === null) { altered = altered || `captured ${stream} log ${info.path} has no recorded digest (the attempt was finalized by recover)`; }
346
+ else if (crypto.createHash('sha256').update(data).digest('hex') !== info.sha256) { altered = altered || `captured ${stream} log ${info.path} does not match the digest the attempt recorded`; }
347
+ text = data.toString('utf8');
348
+ } else { missing = true; text = '[pincer: captured log missing from local state]'; }
349
+ pieces.push(`--- ${stream}${info.truncated ? ' (truncated by the runtime)' : ''}${info.redactions ? ` (${info.redactions} redaction(s))` : ''} ---`);
350
+ pieces.push(text.replace(/\n$/, ''));
351
+ }
352
+ if (missing) { problems.push(`draft check ${stub.id}: attempt ${attempt.id} has no captured log; run the check again`); continue; }
353
+ if (altered) { problems.push(`draft check ${stub.id}: attempt ${attempt.id}: ${altered}; run the check again`); continue; }
354
+ pieces.push(`--- outcome ${attempt.outcome}${attempt.exit_code !== null && attempt.exit_code !== undefined ? ` (exit ${attempt.exit_code})` : ''} ---`);
355
+ const content = `${pieces.join('\n')}\n`;
356
+ atomicWrite(path.join(dirAbs, 'checks', `${stub.id}.log`), content);
357
+ artifactPaths.add(logRel);
358
+ checks.push({
359
+ id: stub.id, kind: 'command', required: Boolean(stub.required), result: resultFor(attempt.outcome),
360
+ command: (attempt.check && attempt.check.display || '').replace(/\n$/, ''), timestamp: attempt.finished || attempt.started,
361
+ artifacts: [logRel, ...(stub.artifacts || [])], provenance: 'runtime',
362
+ attempt: {
363
+ id: attempt.id, sequence: attempt.sequence, outcome: attempt.outcome, exit_code: attempt.exit_code ?? null,
364
+ started: attempt.started, finished: attempt.finished, source_before: attempt.source ? attempt.source.before : null, source_after: attempt.source ? attempt.source.after : null,
365
+ check_digest: attempt.check.digest, runner: attempt.runner, cwd: attempt.cwd || '.', log_sha256: crypto.createHash('sha256').update(content).digest('hex'), truncated: Boolean((attempt.artifacts.stdout && attempt.artifacts.stdout.truncated) || (attempt.artifacts.stderr && attempt.artifacts.stderr.truncated)),
366
+ },
367
+ ...(stub.note ? { note: stub.note } : {}), ...(attempt.outcome === 'error' ? { note: `${stub.note ? `${stub.note}; ` : ''}attempt error: ${attempt.error}` } : {}),
368
+ });
369
+ }
370
+ if (problems.length) return { problems };
371
+ const artifacts = [];
372
+ for (const p of [...artifactPaths].sort()) {
373
+ const abs = path.join(root, p);
374
+ if (!fs.existsSync(abs)) { problems.push(`artifact ${p}: missing (authored artifacts must be saved before export)`); continue; }
375
+ artifacts.push({ path: p, sha256: digestFile(abs) });
376
+ }
377
+ if (problems.length) return { problems };
378
+ const manifest = {
379
+ schema: 2, prd, base, candidate, created: now,
380
+ environment: { os: environment.os, node: environment.node, tools: env.tools || [], limitations: env.limitations || [] },
381
+ coverage_review: draft.coverage_review, requirements: draft.requirements, checks, visual_review: draft.visual_review, artifacts,
382
+ change: { id: binding.change, prd_revision: binding.prd_revision, base: binding.base },
383
+ };
384
+ const manifestRel = `${dirRel}/manifest.json`;
385
+ atomicWrite(path.join(root, manifestRel), `${JSON.stringify(manifest, null, 2)}\n`);
386
+ const validation = validate(path.join(root, manifestRel), { candidate, base, prd }, root);
387
+ return { manifest: manifestRel, problems: validation };
388
+ }
389
+
390
+
391
+ module.exports = { SCHEMA, SCHEMAS, HEX40, PRD_REF, CHECK_ID, validate, exportEvidence, resultFor, digestFile, repoRoot, realpathDeep, unsafePath };