@yeison.restrepo.r/code-conductor 1.48.0 → 1.50.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.
- package/README.md +6 -6
- package/package.json +1 -1
- package/project-template/.claude/agents/audit.md +2 -2
- package/project-template/.claude/agents/code.md +1 -1
- package/project-template/.claude/agents/define-review.md +1 -1
- package/project-template/.claude/agents/plan.md +2 -2
- package/project-template/.claude/agents/qa.md +3 -3
- package/project-template/.claude/agents/security.md +13 -8
- package/project-template/.claude/agents/spec.md +2 -2
- package/project-template/.claude/commands/cc-orchestrate.md +8 -5
- package/project-template/.claude/commands/cc-plan.md +18 -0
- package/project-template/.claude/commands/cc-review.md +20 -0
- package/project-template/.claude/commands/cc-spec.md +18 -0
- package/project-template/.claude/commands/cc-test.md +22 -1
- package/project-template/.claude/hooks/pre-tool-use.mjs +12 -1
- package/scripts/orchestrate.mjs +378 -55
- package/scripts/security-scan.mjs +152 -31
package/scripts/orchestrate.mjs
CHANGED
|
@@ -23,6 +23,8 @@ export const WRITE_SURFACE = [RUN_FILE, ENVELOPE_FILE, '.claude/memory/session-s
|
|
|
23
23
|
// Where /cc-orchestrate writes each agent's final message for `handback` to read: inside
|
|
24
24
|
// the surface, and cleared with the run so file names never collide across runs.
|
|
25
25
|
export const HANDBACK_DIR = '.conductor/handback';
|
|
26
|
+
// FEAT-059 C5, C7: owner-only; outside the hand-back directory so it outlives end.
|
|
27
|
+
const OWNER_FILE = '.conductor/security-pre-existing.txt';
|
|
26
28
|
// FEAT-041: the Define review loop's reports, cleared with the run like the hand-backs.
|
|
27
29
|
export const REVIEW_DIR = '.conductor/review';
|
|
28
30
|
// Three reviewer passes, so at most two revisions, each re-reviewed (FEAT-041 (d)).
|
|
@@ -30,6 +32,7 @@ export const REVIEW_CAP = 3;
|
|
|
30
32
|
// FEAT-057: fix rounds per run, fixed at start so the orchestrator's prompt cannot change the cap.
|
|
31
33
|
export const AUDIT_ROUNDS_DEFAULT = 2;
|
|
32
34
|
const AUDIT_ROUNDS_MAX = 5;
|
|
35
|
+
const SNAP_STORE_MAX_BYTES = 64 * 1024;
|
|
33
36
|
const isAuditRounds = (n) => Number.isInteger(n) && n >= 0 && n <= AUDIT_ROUNDS_MAX;
|
|
34
37
|
// Every outcome a closed loop can carry; only the skip is the orchestrator's to record (FEAT-058).
|
|
35
38
|
const REVIEW_OUTCOME = /^(clean|cap|unchanged|skipped:[a-z][a-z0-9-]{0,39})$/;
|
|
@@ -66,7 +69,7 @@ const DEPENDENCY_STATES = ['audit', 'not-covered', 'disabled'];
|
|
|
66
69
|
const OBJECT_NAME = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
|
|
67
70
|
export const SECURITY_NOT_CONFIGURED = 'not-configured (run predates FEAT-034)';
|
|
68
71
|
|
|
69
|
-
// A halt stops the run and is recorded in it (D12). A refusal is a misuse of the CLI:
|
|
72
|
+
// A halt stops the run and is recorded in it (D12); resume clears it from the last gate whose record still validates (FEAT-055). A refusal is a misuse of the CLI:
|
|
70
73
|
// nothing is written and nothing is recorded.
|
|
71
74
|
export class Halt extends Error {
|
|
72
75
|
constructor(code, reason) { super(`${code}: ${reason}`); this.code = code; this.reason = reason; }
|
|
@@ -103,7 +106,8 @@ function isSecurity(s) {
|
|
|
103
106
|
if (s.audit_command !== null && !hasAudit) return false;
|
|
104
107
|
if (hasAudit !== (s.dependency === 'audit')) return false;
|
|
105
108
|
if (s.base !== null && !OBJECT_NAME.test(s.base ?? '')) return false;
|
|
106
|
-
|
|
109
|
+
// FEAT-059 C16: a scan command without the threshold suffix was written by FEAT-034, whose entries carry no verdict.
|
|
110
|
+
return typeof s.scan_command === 'string' && s.scan_command.endsWith(` ${s.threshold}`);
|
|
107
111
|
}
|
|
108
112
|
|
|
109
113
|
// FEAT-057: a present audit_rounds that is not 0-5 would let a hand-edited run buy fix rounds without limit.
|
|
@@ -128,14 +132,14 @@ function readRun(root) {
|
|
|
128
132
|
|
|
129
133
|
const saveRun = (root, run) => writeAtomic(join(root, RUN_FILE), JSON.stringify(run, null, 2) + '\n');
|
|
130
134
|
|
|
131
|
-
// Every verb but start and end drives a run that must exist, be this session's, and not be halted.
|
|
135
|
+
// Every verb but start, resume and end drives a run that must exist, be this session's, and not be halted.
|
|
132
136
|
function liveRun(root, sessionId) {
|
|
133
137
|
const run = readRun(root);
|
|
134
138
|
if (!run) throw new Refusal(`no run file at ${join(root, RUN_FILE)}; start one first`);
|
|
135
139
|
if (run.session_id !== sessionId) {
|
|
136
140
|
throw new Refusal(`run ${run.item} belongs to another session; end it, or start to replace it`);
|
|
137
141
|
}
|
|
138
|
-
if (run.halt) throw new Refusal(`run ${run.item} halted with ${run.halt.code}; recover with
|
|
142
|
+
if (run.halt) throw new Refusal(`run ${run.item} halted with ${run.halt.code}; recover with resume, or end then start (D12, FEAT-055)`);
|
|
139
143
|
return run;
|
|
140
144
|
}
|
|
141
145
|
|
|
@@ -155,8 +159,8 @@ export function nextStep(run) {
|
|
|
155
159
|
if (fix) return { role: 'code', fix: fix.round };
|
|
156
160
|
const last = run.handbacks.at(-1)?.role;
|
|
157
161
|
if (last === 'audit') return { role: isPlainObject(run.security) ? 'security' : 'qa' };
|
|
158
|
-
//
|
|
159
|
-
if (last === 'security') return run.handbacks.at(-1).security?.
|
|
162
|
+
// Only an approving verdict routes to qa (FEAT-059); a blocked or failed seat never does, and the halt already names end (FEAT-034).
|
|
163
|
+
if (last === 'security') return run.handbacks.at(-1).security?.verdict === 'APPROVE' ? { role: 'qa' } : { end: true };
|
|
160
164
|
if (last === 'qa') return { end: true };
|
|
161
165
|
return { role: 'audit' };
|
|
162
166
|
}
|
|
@@ -327,11 +331,11 @@ const scanRef = (root) => relative(root, join(HERE, 'security-scan.mjs')).split(
|
|
|
327
331
|
|
|
328
332
|
// FEAT-034: what the security seat will run, fixed at start so Guard 7 and the router read one record.
|
|
329
333
|
function resolveSecurity(root, stack, { threshold, dependencyAudit }) {
|
|
330
|
-
const
|
|
331
|
-
const base = OBJECT_NAME.test(head) ? head : null;
|
|
334
|
+
const base = headObject(root);
|
|
332
335
|
const auditCommand = dependencyAudit ? PM_AUDIT_COMMAND[stack.packageManager] ?? null : null;
|
|
333
336
|
const dependency = !dependencyAudit ? 'disabled' : auditCommand ? 'audit' : 'not-covered';
|
|
334
|
-
|
|
337
|
+
// C14: the scanner writes complete lines, severity included; 'none' keeps a fixed arity outside git (plan decisions).
|
|
338
|
+
const scanCommand = `node ${scanRef(root)} ${base ?? 'none'} ${threshold}`;
|
|
335
339
|
if (auditCommand) checkSecurityCommand(auditCommand);
|
|
336
340
|
checkSecurityCommand(scanCommand);
|
|
337
341
|
return { threshold, dependency, base, audit_command: auditCommand, scan_command: scanCommand };
|
|
@@ -360,6 +364,14 @@ function gitValue(root, args, fallback) {
|
|
|
360
364
|
return (r.status === 0 && r.stdout.trim()) || fallback;
|
|
361
365
|
}
|
|
362
366
|
|
|
367
|
+
const headCommit = (root) => {
|
|
368
|
+
const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
|
|
369
|
+
return /^[0-9a-f]{7,40}$/.test(head) ? head : '0000000';
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
// A full object name or null: what an approval and the security seat anchor to (FEAT-055, FEAT-034).
|
|
373
|
+
const headObject = (root) => { const head = gitValue(root, ['rev-parse', 'HEAD'], ''); return OBJECT_NAME.test(head) ? head : null; };
|
|
374
|
+
|
|
363
375
|
// A fix step's files come from the record, re-checked against the plan because the run file is writable.
|
|
364
376
|
function codeScope(root, run, step) {
|
|
365
377
|
if (step.fix !== undefined) { const { files } = fixDue(run); return fixScope(root, run, Array.isArray(files) ? files : [], step.fix); }
|
|
@@ -368,10 +380,9 @@ function codeScope(root, run, step) {
|
|
|
368
380
|
}
|
|
369
381
|
|
|
370
382
|
function envelopeFields(run, root, step) {
|
|
371
|
-
const head = gitValue(root, ['rev-parse', 'HEAD'], '0000000').toLowerCase();
|
|
372
383
|
const { tk, scope } = ROLE_ARTIFACTS[step.role];
|
|
373
384
|
const fields = {
|
|
374
|
-
ph: PHASE[step.role], c:
|
|
385
|
+
ph: PHASE[step.role], c: headCommit(root), s: run.item,
|
|
375
386
|
// A fix re-enters Build, so it carries Build's entry gate, the one --to code checks (D6).
|
|
376
387
|
n: [], f: [], d: [], x: [], role: step.role, tk, gate: step.fix === undefined ? run.gate : expectedGate('code'),
|
|
377
388
|
};
|
|
@@ -394,15 +405,21 @@ function envelopeFields(run, root, step) {
|
|
|
394
405
|
const currentHash = (root, kind, rel) => { try { return documentHash(kind, readFileSync(join(root, rel))); } catch { return null; } };
|
|
395
406
|
|
|
396
407
|
// FEAT-056: after define_approved, a changed spec or plan means the run would execute text nobody approved.
|
|
408
|
+
// FEAT-055: returned, not thrown, so resume refuses with the same text where install halts.
|
|
409
|
+
function approvedDocHalt(root, run, kind) {
|
|
410
|
+
const { path, sha256 } = run.approvals[kind] ?? {};
|
|
411
|
+
if (typeof path !== 'string' || typeof sha256 !== 'string') {
|
|
412
|
+
return new Halt('ORCH_APPROVAL_UNHASHED', `run ${run.item} records an approval without a document hash (started before FEAT-056); run end, then start`);
|
|
413
|
+
}
|
|
414
|
+
const now = currentHash(root, kind, path);
|
|
415
|
+
if (now === sha256) return null;
|
|
416
|
+
return new Halt('ORCH_APPROVED_DOC_CHANGED', `${kind} ${path} was approved at sha256 ${sha256} and ${now ? `now hashes ${now}` : 'can no longer be read'}`);
|
|
417
|
+
}
|
|
418
|
+
|
|
397
419
|
function checkApprovedDocs(root, run) {
|
|
398
420
|
for (const kind of ['spec', 'plan']) {
|
|
399
|
-
const
|
|
400
|
-
if (
|
|
401
|
-
throw new Halt('ORCH_APPROVAL_UNHASHED', `run ${run.item} records an approval without a document hash (started before FEAT-056); run end, then start`);
|
|
402
|
-
}
|
|
403
|
-
const now = currentHash(root, kind, path);
|
|
404
|
-
if (now === sha256) continue;
|
|
405
|
-
throw new Halt('ORCH_APPROVED_DOC_CHANGED', `${kind} ${path} was approved at sha256 ${sha256} and ${now ? `now hashes ${now}` : 'can no longer be read'}`);
|
|
421
|
+
const failure = approvedDocHalt(root, run, kind);
|
|
422
|
+
if (failure) throw failure;
|
|
406
423
|
}
|
|
407
424
|
}
|
|
408
425
|
|
|
@@ -434,8 +451,8 @@ function withholdUnlessApproved(run) {
|
|
|
434
451
|
const verdict = run.handbacks.findLast((h) => h.role === 'audit')?.verdict;
|
|
435
452
|
if (verdict !== 'APPROVE') throw new Halt('ORCH_GATE_WITHHELD', `qa may not forward verify_pass: the audit verdict is ${verdict ?? 'absent'}`);
|
|
436
453
|
if (!isPlainObject(run.security)) return;
|
|
437
|
-
const
|
|
438
|
-
if (
|
|
454
|
+
const seatVerdict = run.handbacks.findLast((h) => h.role === 'security')?.security?.verdict;
|
|
455
|
+
if (seatVerdict !== 'APPROVE') throw new Halt('ORCH_GATE_WITHHELD', `qa may not forward verify_pass: the security verdict is ${seatVerdict ?? 'absent'}`);
|
|
439
456
|
}
|
|
440
457
|
|
|
441
458
|
// FEAT-057: a fix re-enters Build with no task, so it never advances tasks.done; audits carry their round.
|
|
@@ -457,15 +474,20 @@ export function recordHandback(run, role, gate, verdict, extra = {}) {
|
|
|
457
474
|
return { ...run, role: null, gate: forwardGate(run, role, gate), tasks, handbacks: [...run.handbacks, entry] };
|
|
458
475
|
}
|
|
459
476
|
|
|
477
|
+
// FEAT-055: the validated text is returned too, so resume can validate the same bytes again.
|
|
460
478
|
function parseHandback(text) {
|
|
461
479
|
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith('SNAP_HANDBACK '));
|
|
462
480
|
if (lines.length !== 1) throw new Halt('ORCH_HANDBACK_MISSING', `expected exactly one SNAP_HANDBACK line, found ${lines.length}`);
|
|
463
481
|
const json = lines[0].slice('SNAP_HANDBACK '.length).trim();
|
|
482
|
+
// The SNAP is stored in the run file, which the hooks stop reading past their envelope cap (Guard 6 would go from deny to warn).
|
|
483
|
+
if (Buffer.byteLength(json) > SNAP_STORE_MAX_BYTES) {
|
|
484
|
+
throw new Halt('ORCH_HANDBACK_INVALID', `the hand-back SNAP is larger than ${SNAP_STORE_MAX_BYTES} bytes`);
|
|
485
|
+
}
|
|
464
486
|
const error = validate(json + '\n');
|
|
465
487
|
if (error) throw new Halt('ORCH_HANDBACK_INVALID', error);
|
|
466
488
|
const env = JSON.parse(json);
|
|
467
489
|
if (env.v !== 3 && env.v !== 4) throw new Halt('ORCH_HANDBACK_INVALID', `a hand-back must be a v3 or v4 envelope, got v${env.v}`);
|
|
468
|
-
return env;
|
|
490
|
+
return { env, snap: json };
|
|
469
491
|
}
|
|
470
492
|
|
|
471
493
|
function auditStop({ verdict, blockers }, round, cap) {
|
|
@@ -506,10 +528,11 @@ function checkConsistent(verdict, blockers, paths) {
|
|
|
506
528
|
return { verdict, blockers, paths };
|
|
507
529
|
}
|
|
508
530
|
|
|
509
|
-
|
|
531
|
+
// FEAT-059 C10: one parser for both Verify roles; the role only names the report in the missing-line reason.
|
|
532
|
+
export function parseVerdict(text, role = 'audit') {
|
|
510
533
|
const lines = text.split(/\r?\n/).map((l) => l.trim());
|
|
511
534
|
const candidates = lines.filter((l) => VERDICT_CANDIDATE.test(l));
|
|
512
|
-
if (candidates.length === 0) throw new Halt('ORCH_VERDICT_MISSING',
|
|
535
|
+
if (candidates.length === 0) throw new Halt('ORCH_VERDICT_MISSING', `the ${role} report has no VERDICT: APPROVE | RETURN | ESCALATE line`);
|
|
513
536
|
if (candidates.length > 1) throw new Halt('ORCH_VERDICT_INVALID', `expected exactly one VERDICT line, found ${candidates.length}`);
|
|
514
537
|
const match = VERDICT_LINE.exec(candidates[0]);
|
|
515
538
|
if (!match) throw new Halt('ORCH_VERDICT_INVALID', `${JSON.stringify(candidates[0].slice(0, QUOTE_CAP))} is not VERDICT: APPROVE | RETURN | ESCALATE`);
|
|
@@ -521,12 +544,20 @@ export function parseVerdict(text) {
|
|
|
521
544
|
}
|
|
522
545
|
|
|
523
546
|
// FEAT-034: the security report. The orchestrator copies what the agent wrote; the script reads it.
|
|
547
|
+
// FEAT-059: it ends in the audit's verdict line, and findings the change did not introduce sit in an owner-only block.
|
|
524
548
|
const SCANS_CANDIDATE = /^scans\s*:/i;
|
|
525
549
|
const SCANS_LINE = /^SCANS: dependency=(ran|not-covered|disabled|failed) secrets=(ran|failed) scripts=(ran|failed)$/;
|
|
526
|
-
const SECURITY_FINDING = /^- \[(critical|high|moderate|low)
|
|
550
|
+
const SECURITY_FINDING = /^- \[(blocker|major|minor)\] (\S+:\d+) — (critical|high|moderate|low) (dependency|secret|script): \S/;
|
|
551
|
+
const FINDING_FORM = '- [<blocker|minor>] <path>:<line> — <critical|high|moderate|low> <dependency|secret|script>: <text>';
|
|
527
552
|
const SECURITY_CANDIDATE = /^- \[/;
|
|
553
|
+
const OWNER_OPEN = 'PRE-EXISTING (owner only):';
|
|
554
|
+
const OWNER_CLOSE = 'END PRE-EXISTING';
|
|
555
|
+
const REPORT_FILE = `${HANDBACK_DIR}/security.txt`;
|
|
556
|
+
const reportAt = (n) => `${REPORT_FILE}:${n}`;
|
|
528
557
|
const quote = (line) => JSON.stringify(line.slice(0, QUOTE_CAP));
|
|
529
558
|
const invalid = (reason) => new Halt('ORCH_SECURITY_REPORT_INVALID', reason);
|
|
559
|
+
// C1: recomputed here from the run file, never read from the report.
|
|
560
|
+
const severityFor = (level, threshold) => (SECURITY_LEVELS.indexOf(level) >= SECURITY_LEVELS.indexOf(threshold) ? 'blocker' : 'minor');
|
|
530
561
|
|
|
531
562
|
function checkDependency(scans, findings, security) {
|
|
532
563
|
const wanted = security.dependency === 'audit' ? ['ran', 'failed'] : [security.dependency];
|
|
@@ -544,21 +575,75 @@ function scansLine(lines) {
|
|
|
544
575
|
if (!match) throw invalid(`${quote(candidates[0])} is not SCANS: dependency=<ran|not-covered|disabled|failed> secrets=<ran|failed> scripts=<ran|failed>`);
|
|
545
576
|
const at = lines.findIndex((l) => l.startsWith('SNAP_HANDBACK '));
|
|
546
577
|
const before = lines.slice(0, Math.max(at, 0)).filter(Boolean);
|
|
547
|
-
|
|
578
|
+
// C11: parseVerdict has already placed the verdict last, so the SCANS line sits just before it.
|
|
579
|
+
if (at === -1 || before.at(-2) !== candidates[0]) throw invalid('the SCANS line must immediately precede the VERDICT line');
|
|
548
580
|
return { dependency: match[1], secrets: match[2], scripts: match[3] };
|
|
549
581
|
}
|
|
550
582
|
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
const
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
583
|
+
// C12: wide candidates, so a near-miss marker halts by name instead of letting an owner line fall into the public part.
|
|
584
|
+
function ownerMarkers(lines) {
|
|
585
|
+
const candidates = lines.map(({ line, n }, index) => ({ line, n, index }))
|
|
586
|
+
.filter(({ line }) => /^(end )?pre-existing/i.test(line));
|
|
587
|
+
if (candidates.length === 0) return null;
|
|
588
|
+
const odd = candidates.find(({ line }) => line !== OWNER_OPEN && line !== OWNER_CLOSE);
|
|
589
|
+
if (odd) throw invalid(`the owner-only marker at ${reportAt(odd.n)} is malformed`);
|
|
590
|
+
const [open, close] = candidates;
|
|
591
|
+
if (candidates.length !== 2 || open.line !== OWNER_OPEN || close.line !== OWNER_CLOSE) {
|
|
592
|
+
throw invalid(`the owner-only block at ${reportAt(candidates[0].n)} is repeated, unclosed or misplaced`);
|
|
559
593
|
}
|
|
594
|
+
return { open: open.index, close: close.index };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export function splitReport(text) {
|
|
598
|
+
const lines = text.split(/\r?\n/).map((l, i) => ({ line: l.trim(), n: i + 1 }));
|
|
599
|
+
const marks = ownerMarkers(lines);
|
|
600
|
+
if (!marks) return { publicLines: lines, owner: [] };
|
|
601
|
+
const early = lines.slice(0, marks.open).findIndex(({ line }) => SECURITY_CANDIDATE.test(line));
|
|
602
|
+
if (early !== -1) throw invalid(`the owner-only block at ${reportAt(marks.open + 1)} must come before the first finding line`);
|
|
603
|
+
const inside = lines.slice(marks.open + 1, marks.close).filter(({ line }) => line !== '');
|
|
604
|
+
const prose = inside.find(({ line }) => !SECURITY_CANDIDATE.test(line));
|
|
605
|
+
if (prose) throw invalid(`the line at ${reportAt(prose.n)} inside the owner-only block is not a finding line`);
|
|
606
|
+
return { publicLines: [...lines.slice(0, marks.open), ...lines.slice(marks.close + 1)], owner: inside };
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function securityFinding({ line, n }, part, threshold) {
|
|
610
|
+
const m = SECURITY_FINDING.exec(line);
|
|
611
|
+
const name = part === 'public' ? quote(line) : `the line at ${reportAt(n)}`;
|
|
612
|
+
if (!m) throw invalid(`${name} is not a security finding line: ${FINDING_FORM}`);
|
|
613
|
+
const [, bracket, location, level, source] = m;
|
|
614
|
+
const expected = severityFor(level, threshold);
|
|
615
|
+
if (bracket !== expected) {
|
|
616
|
+
throw invalid(part === 'public'
|
|
617
|
+
? `${quote(line)} must carry [${expected}]: ${level} against the run's threshold ${threshold}`
|
|
618
|
+
: `the line at ${reportAt(n)} carries the wrong severity for the run's threshold`);
|
|
619
|
+
}
|
|
620
|
+
return { part, n, line, severity: bracket, location, level, source };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// C8: a failed scan can hide findings, so only ESCALATE may follow one.
|
|
624
|
+
function checkFailedEscalates(scans, verdict) {
|
|
625
|
+
const failed = ['dependency', 'secrets', 'scripts'].find((k) => scans[k] === 'failed');
|
|
626
|
+
if (failed && verdict !== 'ESCALATE') {
|
|
627
|
+
throw new Halt('ORCH_VERDICT_INCONSISTENT', `VERDICT: ${verdict} with the ${failed} scan failed; a failed scan requires VERDICT: ESCALATE`);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
export function parseSecurityReport(text, security) {
|
|
632
|
+
const { publicLines, owner } = splitReport(text);
|
|
633
|
+
const { verdict } = parseVerdict(publicLines.map((x) => x.line).join('\n'), 'security');
|
|
634
|
+
const scans = scansLine(publicLines.map((x) => x.line));
|
|
635
|
+
// Defense in depth: the verdict check reads only the lines before SNAP_HANDBACK, so nothing may follow it.
|
|
636
|
+
const handbackAt = publicLines.findIndex((x) => x.line.startsWith('SNAP_HANDBACK '));
|
|
637
|
+
const late = publicLines.slice(handbackAt + 1).find((x) => SECURITY_CANDIDATE.test(x.line));
|
|
638
|
+
if (late) throw invalid(`the finding line at ${reportAt(late.n)} comes after SNAP_HANDBACK`);
|
|
639
|
+
const findings = [
|
|
640
|
+
...publicLines.filter((x) => SECURITY_CANDIDATE.test(x.line)).map((x) => securityFinding(x, 'public', security.threshold)),
|
|
641
|
+
...owner.map((x) => securityFinding(x, 'owner', security.threshold)),
|
|
642
|
+
];
|
|
560
643
|
checkDependency(scans, findings, security);
|
|
561
|
-
|
|
644
|
+
checkConsistent(verdict, findings.filter((f) => f.part === 'public' && f.severity === 'blocker').length, []);
|
|
645
|
+
checkFailedEscalates(scans, verdict);
|
|
646
|
+
return { verdict, scans, findings };
|
|
562
647
|
}
|
|
563
648
|
|
|
564
649
|
const scanFailed = (reason) => new Halt('ORCH_SECURITY_SCAN_FAILED', `the local scans cannot be re-run: ${reason}`);
|
|
@@ -566,52 +651,102 @@ const scanFailed = (reason) => new Halt('ORCH_SECURITY_SCAN_FAILED', `the local
|
|
|
566
651
|
// The diff under scan can change the work-tree scanner, so the re-run loads the base commit's copy (C17).
|
|
567
652
|
async function baseScan(root, security) {
|
|
568
653
|
if (security.base === null) throw scanFailed('the run recorded no base commit');
|
|
569
|
-
const path = security.scan_command.replace(/^node /, '').replace(/
|
|
654
|
+
const path = security.scan_command.replace(/^node /, '').replace(/ \S+ \S+$/, '');
|
|
570
655
|
const shown = spawnSync('git', ['show', `${security.base}:./${path}`], { cwd: root });
|
|
571
656
|
if (shown.status !== 0) throw scanFailed(`${path} is not committed at the base`);
|
|
572
657
|
const dir = mkdtempSync(join(tmpdir(), 'cc-security-base-'));
|
|
573
658
|
try {
|
|
574
659
|
const file = join(dir, 'security-scan.mjs');
|
|
575
660
|
writeFileSync(file, shown.stdout);
|
|
576
|
-
const
|
|
577
|
-
|
|
661
|
+
const scanner = await import(pathToFileURL(file).href);
|
|
662
|
+
// C15: the normal upgrade path of a 1.48.0 project until its update is committed.
|
|
663
|
+
if (scanner.SCAN_CONTRACT !== 2) throw scanFailed(`the base commit's ${path} predates FEAT-059 (an install or update that is not committed); end this run, commit the updated ${path}, then start again`);
|
|
664
|
+
return scanner.scanChanges(root, security.base, security.threshold);
|
|
578
665
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
579
666
|
}
|
|
580
667
|
|
|
668
|
+
const DEPENDENCY_PACKAGE = /— (?:critical|high|moderate|low) dependency: ((?:@[^@\s/]+\/)?[^@\s]+)@/;
|
|
669
|
+
|
|
670
|
+
function lineCount(root, rel) {
|
|
671
|
+
const file = join(root, rel);
|
|
672
|
+
if (!existsSync(file)) return 0;
|
|
673
|
+
const text = readFileSync(file, 'utf8');
|
|
674
|
+
return text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// C3-C4, C13: the reason names neither the direction nor the package.
|
|
678
|
+
function checkOrigin(root, findings, local) {
|
|
679
|
+
const changed = local.changed === 'all' || local.changed === 'failed' ? 'all' : local.changed;
|
|
680
|
+
for (const f of findings.filter((x) => x.source === 'dependency')) {
|
|
681
|
+
const path = f.location.replace(/:\d+$/, '');
|
|
682
|
+
const n = Number(f.location.slice(path.length + 1));
|
|
683
|
+
if (path !== local.lockfile || n < 1 || n > lineCount(root, path)) {
|
|
684
|
+
throw invalid(`the dependency finding at ${reportAt(f.n)} does not name a line of the run's lockfile`);
|
|
685
|
+
}
|
|
686
|
+
const pkg = DEPENDENCY_PACKAGE.exec(f.line)?.[1];
|
|
687
|
+
const preExisting = Boolean(pkg) && changed !== 'all' && !changed.includes(pkg);
|
|
688
|
+
if ((f.part === 'owner') !== preExisting) throw invalid(`the dependency finding at ${reportAt(f.n)} is filed in the wrong part`);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
581
692
|
function checkComplete(report, local) {
|
|
582
693
|
for (const scan of ['secrets', 'scripts']) {
|
|
583
694
|
if (report.scans[scan] !== local[scan]) throw new Halt('ORCH_SECURITY_REPORT_INCOMPLETE', `the report says ${scan}=${report.scans[scan]}; the local re-run says ${local[scan]}`);
|
|
584
695
|
}
|
|
585
|
-
const reported =
|
|
586
|
-
const
|
|
587
|
-
|
|
696
|
+
const reported = report.findings.filter((f) => f.source !== 'dependency');
|
|
697
|
+
const partOf = (line) => reported.filter((f) => f.line === line);
|
|
698
|
+
for (const [lines, part] of [[local.introduced, 'public'], [local.preExisting, 'owner']]) {
|
|
699
|
+
for (const line of lines) {
|
|
700
|
+
const found = partOf(line);
|
|
701
|
+
if (found.some((f) => f.part === part)) continue;
|
|
702
|
+
if (found.length > 0) throw new Halt('ORCH_SECURITY_REPORT_INCOMPLETE', `the local finding at ${reportAt(found[0].n)} is filed in the wrong part`);
|
|
703
|
+
throw new Halt('ORCH_SECURITY_REPORT_INCOMPLETE', "the report does not match the base scanner's local findings");
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
// An owner-only line copied into the public part would leak a pre-existing finding.
|
|
707
|
+
for (const line of local.preExisting) {
|
|
708
|
+
const leaked = reported.find((f) => f.line === line && f.part === 'public');
|
|
709
|
+
if (leaked) throw new Halt('ORCH_SECURITY_REPORT_INCOMPLETE', `the local finding at ${reportAt(leaked.n)} is filed in the wrong part`);
|
|
710
|
+
}
|
|
588
711
|
}
|
|
589
712
|
|
|
590
713
|
function securitySummary(report, threshold) {
|
|
714
|
+
const publicFindings = report.findings.filter((f) => f.part === 'public');
|
|
591
715
|
const counts = { critical: 0, high: 0, moderate: 0, low: 0 };
|
|
592
|
-
for (const f of
|
|
716
|
+
for (const f of publicFindings) counts[f.level] += 1;
|
|
593
717
|
const failed = ['dependency', 'secrets', 'scripts'].find((k) => report.scans[k] === 'failed');
|
|
594
|
-
const blocking =
|
|
595
|
-
|
|
596
|
-
|
|
718
|
+
const blocking = publicFindings.filter((f) => f.severity === 'blocker');
|
|
719
|
+
// C6: nothing from the owner-only block reaches the run file.
|
|
720
|
+
const entry = { scans: report.scans, counts, threshold, verdict: report.verdict, blocked: report.verdict !== 'APPROVE' };
|
|
721
|
+
return { entry, failed, blocking, total: publicFindings.length };
|
|
597
722
|
}
|
|
598
723
|
|
|
599
|
-
function securityStop({ failed, blocking }, threshold) {
|
|
600
|
-
if (
|
|
601
|
-
if (
|
|
602
|
-
return new Halt('
|
|
724
|
+
function securityStop({ entry, failed, blocking }, threshold) {
|
|
725
|
+
if (entry.verdict === 'APPROVE' && blocking.length === 0) return null;
|
|
726
|
+
if (entry.verdict !== 'ESCALATE') return new Halt('ORCH_SECURITY_BLOCKED', `security found ${blocking.length} finding(s) at or above ${threshold}; first: ${blocking[0].line.slice(0, QUOTE_CAP)}`);
|
|
727
|
+
if (failed) return new Halt('ORCH_SECURITY_SCAN_FAILED', `the ${failed} scan did not complete; scans clean is the Verify exit, see ${REPORT_FILE}`);
|
|
728
|
+
return new Halt('ORCH_SECURITY_ESCALATE', `security escalated a decision only the owner takes; see ${REPORT_FILE}`);
|
|
603
729
|
}
|
|
604
730
|
|
|
731
|
+
const ownerText = (report) => {
|
|
732
|
+
const lines = report.findings.filter((f) => f.part === 'owner').map((f) => f.line);
|
|
733
|
+
return `${lines.length ? lines.join('\n') : 'none'}\n`;
|
|
734
|
+
};
|
|
735
|
+
|
|
605
736
|
async function securityHandback(root, run, gate, text) {
|
|
606
737
|
const report = parseSecurityReport(text, run.security);
|
|
607
|
-
|
|
738
|
+
const local = await baseScan(root, run.security);
|
|
739
|
+
checkOrigin(root, report.findings, local);
|
|
740
|
+
checkComplete(report, local);
|
|
741
|
+
writeAtomic(join(root, OWNER_FILE), ownerText(report));
|
|
608
742
|
const { threshold } = run.security;
|
|
609
743
|
const summary = securitySummary(report, threshold);
|
|
610
744
|
// Saved first, so the halt cli records lands on top of the entry.
|
|
611
745
|
saveRun(root, recordHandback(run, 'security', gate, null, { security: summary.entry }));
|
|
612
746
|
const stop = securityStop(summary, threshold);
|
|
613
747
|
if (stop) throw stop;
|
|
614
|
-
|
|
748
|
+
// C6: the success text is fixed whatever the owner-only block held.
|
|
749
|
+
return `security handed back ${gate}; VERDICT: APPROVE; ${summary.total} finding(s) below ${threshold} recorded; dependency=${report.scans.dependency}; pre-existing findings, if any, are in ${OWNER_FILE} (owner only)`;
|
|
615
750
|
}
|
|
616
751
|
|
|
617
752
|
async function handback(root, sessionId, role, bytes) {
|
|
@@ -622,14 +757,14 @@ async function handback(root, sessionId, role, bytes) {
|
|
|
622
757
|
throw new Halt('ORCH_HANDBACK_CONFLICT', `${role} already handed back for this position; a second report is not routed`);
|
|
623
758
|
}
|
|
624
759
|
if (!run.role || run.role !== role) throw new Refusal(`handback ${role}: the dispatched role is ${run.role ?? 'none'}`);
|
|
625
|
-
const env = parseHandback(text);
|
|
760
|
+
const { env, snap } = parseHandback(text);
|
|
626
761
|
if (env.sys.role !== role) throw new Halt('ORCH_HANDBACK_ROLE_MISMATCH', `dispatched ${role}, the hand-back names ${env.sys.role}`);
|
|
627
762
|
if (!MAY_HAND_BACK[role].includes(env.ops.gate)) {
|
|
628
763
|
throw new Halt('ORCH_GATE_UNEARNED', `${role} may hand back ${MAY_HAND_BACK[role].join('|')}, not ${env.ops.gate}`);
|
|
629
764
|
}
|
|
630
765
|
if (role === 'security') return securityHandback(root, run, env.ops.gate, text);
|
|
631
766
|
const verdict = role === 'audit' ? parseVerdict(text) : null;
|
|
632
|
-
const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict);
|
|
767
|
+
const recorded = recordHandback(run, role, env.ops.gate, verdict?.verdict, { snap });
|
|
633
768
|
saveRun(root, recorded);
|
|
634
769
|
// Saved first, so the halt cli records lands on top of the audit entry (FEAT-060, FEAT-057).
|
|
635
770
|
if (verdict && verdict.verdict !== 'APPROVE') return auditFix(root, recorded, verdict, bytes);
|
|
@@ -638,6 +773,7 @@ async function handback(root, sessionId, role, bytes) {
|
|
|
638
773
|
}
|
|
639
774
|
|
|
640
775
|
// Two human approvals, one gate write (A4): only an approved plan writes define_approved.
|
|
776
|
+
// FEAT-055: and HEAD at that moment, so resume can tell whether history still holds it.
|
|
641
777
|
// FEAT-056: each approval binds the bytes the owner was shown; a stale hash writes nothing.
|
|
642
778
|
function approve(root, sessionId, what, rel, shown) {
|
|
643
779
|
const run = liveRun(root, sessionId);
|
|
@@ -650,7 +786,7 @@ function approve(root, sessionId, what, rel, shown) {
|
|
|
650
786
|
if (sha256 !== shown.toLowerCase()) {
|
|
651
787
|
throw new Refusal(`ORCH_DOC_HASH_STALE: ${what} ${rel} hashes ${sha256}, not the ${shown} that was shown; show the document again`);
|
|
652
788
|
}
|
|
653
|
-
const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256 };
|
|
789
|
+
const approval = { at: new Date().toISOString(), by: gitValue(root, ['config', 'user.name'], 'unknown'), path: rel, sha256, commit: headObject(root) };
|
|
654
790
|
if (what === 'plan') return approvePlan(root, run, content.toString('utf8'), approval);
|
|
655
791
|
saveRun(root, { ...run, approvals: { ...run.approvals, spec: approval } });
|
|
656
792
|
return `spec approved: sha256 ${sha256}`;
|
|
@@ -675,6 +811,105 @@ function checkLoopClosed(run, what) {
|
|
|
675
811
|
throw new Refusal(`ORCH_REVIEW_OPEN: review ${what} is ${state}; close it before the approval`);
|
|
676
812
|
}
|
|
677
813
|
|
|
814
|
+
const RESUME_USAGE = 'usage: orchestrate.mjs resume';
|
|
815
|
+
const RESTART = 'recover with end, then start';
|
|
816
|
+
const RECORD_KINDS = ['spec', 'plan'];
|
|
817
|
+
|
|
818
|
+
// FEAT-055: every failure is a refusal, so a failed resume leaves the halt it was asked to clear as it was.
|
|
819
|
+
function haltedRun(root, sessionId, args) {
|
|
820
|
+
if (args.length > 0) throw new Refusal(RESUME_USAGE);
|
|
821
|
+
let run = null;
|
|
822
|
+
try { run = readRun(root); } catch { /* an invalid run file is judged below */ }
|
|
823
|
+
if (!run) throw new Refusal(`ORCH_RESUME_NO_RUN: no valid run file at ${join(root, RUN_FILE)}`);
|
|
824
|
+
if (!run.halt) throw new Refusal(`ORCH_RESUME_NOT_HALTED: run ${run.item} is not halted; continue with ${describeStep(nextStep(run))}`);
|
|
825
|
+
if (!sessionId) throw new Refusal('ORCH_NO_SESSION_ID: CLAUDE_CODE_SESSION_ID is absent or empty, so Guard 6 could never bind this run');
|
|
826
|
+
if (!run.approvals.spec) throw new Refusal(`ORCH_RESUME_NO_GATE: run ${run.item} records no spec approval, so no gate is left to resume from; ${RESTART}`);
|
|
827
|
+
return run;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// 0: HEAD descends from commit; 1: it does not; anything else: git cannot answer. A non-hex name never reaches git as an option.
|
|
831
|
+
function ancestry(root, commit) {
|
|
832
|
+
if (typeof commit !== 'string' || !/^[0-9a-f]{7,64}$/.test(commit)) return null;
|
|
833
|
+
return spawnSync('git', ['merge-base', '--is-ancestor', commit, 'HEAD'], { cwd: root, encoding: 'utf8' }).status;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
const unanchored = (kind, reason) => new Refusal(`ORCH_RESUME_UNANCHORED: the ${kind} approval ${reason}; ${RESTART}`);
|
|
837
|
+
|
|
838
|
+
// An approval is the owner's act, which the run cannot redo, so a failing one refuses the whole resume.
|
|
839
|
+
function checkApproval(root, run, kind) {
|
|
840
|
+
const failure = approvedDocHalt(root, run, kind);
|
|
841
|
+
if (failure?.code === 'ORCH_APPROVAL_UNHASHED') throw new Refusal(failure.message);
|
|
842
|
+
const { commit } = run.approvals[kind];
|
|
843
|
+
if (commit === undefined) throw unanchored(kind, 'records no commit (approved before FEAT-055)');
|
|
844
|
+
if (commit === null) throw unanchored(kind, 'records a null commit (approved outside a git repository or before its first commit)');
|
|
845
|
+
if (failure) throw new Refusal(`${failure.message}; ${RESTART}`);
|
|
846
|
+
const answer = ancestry(root, commit);
|
|
847
|
+
if (answer === 1) {
|
|
848
|
+
throw new Refusal(`ORCH_RESUME_HISTORY_REWRITTEN: HEAD ${gitValue(root, ['rev-parse', 'HEAD'], 'unknown')} does not descend from the ${kind} approval's commit ${commit}; ${RESTART}`);
|
|
849
|
+
}
|
|
850
|
+
if (answer !== 0) throw unanchored(kind, `commit ${String(commit)} cannot be checked against HEAD`);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// The conflict's last entry is ambiguous, except a spec or plan entry whose approval already stands.
|
|
854
|
+
function candidateEntries(run) {
|
|
855
|
+
const last = run.handbacks.at(-1);
|
|
856
|
+
if (run.halt.code !== 'ORCH_HANDBACK_CONFLICT' || !last) return run.handbacks;
|
|
857
|
+
return RECORD_KINDS.includes(last.role) && run.approvals[last.role] ? run.handbacks : run.handbacks.slice(0, -1);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// A task entry still describes the repository: its position, its SNAP and its commit all hold.
|
|
861
|
+
function taskEntryHolds(root, entry, taskId) {
|
|
862
|
+
if (entry.task !== taskId || typeof entry.snap !== 'string' || validate(`${entry.snap}\n`) !== '') return false;
|
|
863
|
+
let env = null;
|
|
864
|
+
try { env = JSON.parse(entry.snap); } catch { return false; }
|
|
865
|
+
return env?.sys?.role === 'code' && ancestry(root, env.sys.c) === 0;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Each approved document's entry, then Build's task entries up to the first that fails; Verify is always redone.
|
|
869
|
+
function keptEntries(root, run) {
|
|
870
|
+
const entries = candidateEntries(run);
|
|
871
|
+
const approved = RECORD_KINDS.filter((k) => run.approvals[k]).map((k) => entries.find((h) => h.role === k)).filter(Boolean);
|
|
872
|
+
if (!run.approvals.plan) return { kept: approved, tasks: 0 };
|
|
873
|
+
const tasks = entries.filter((h) => h.role === 'code' && !('fix' in h));
|
|
874
|
+
let n = 0;
|
|
875
|
+
while (n < tasks.length && n < run.tasks.ids.length && taskEntryHolds(root, tasks[n], run.tasks.ids[n])) n += 1;
|
|
876
|
+
return { kept: [...approved, ...tasks.slice(0, n)], tasks: n };
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// Only approvePlan writes define_approved, and only the last task's hand-back forwards build_executed.
|
|
880
|
+
const resumedGate = (run, tasks) => (!run.approvals.plan ? 'boundary_routed' : tasks < run.tasks.ids.length ? 'define_approved' : 'build_executed');
|
|
881
|
+
|
|
882
|
+
// A dropped document's loop is cleared with it, so the redone document gets a fresh review loop.
|
|
883
|
+
const resumedReview = (run, kept) => (isPlainObject(run.review)
|
|
884
|
+
? Object.fromEntries(Object.entries(run.review).filter(([k]) => kept.some((h) => h.role === k))) : run.review);
|
|
885
|
+
|
|
886
|
+
function nextLine(run) {
|
|
887
|
+
const step = nextStep(run);
|
|
888
|
+
return step.task ? `${describeStep(step)} (task ${run.tasks.done + 1} of ${run.tasks.ids.length})` : describeStep(step);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// FEAT-055: back to the last gate whose record still validates; every record after it is dropped and redone.
|
|
892
|
+
function resume(root, sessionId, args) {
|
|
893
|
+
const run = haltedRun(root, sessionId, args);
|
|
894
|
+
const approvals = RECORD_KINDS.filter((k) => run.approvals[k]);
|
|
895
|
+
for (const kind of approvals) checkApproval(root, run, kind);
|
|
896
|
+
const { kept, tasks } = keptEntries(root, run);
|
|
897
|
+
const records = kept.length + approvals.length;
|
|
898
|
+
const dropped = run.handbacks.length - kept.length;
|
|
899
|
+
const { code, reason, at } = run.halt;
|
|
900
|
+
const resumes = [...(Array.isArray(run.resumes) ? run.resumes : []), { at: new Date().toISOString(), halt: { code, reason, at }, kept: records, dropped }];
|
|
901
|
+
const next = {
|
|
902
|
+
...run, session_id: sessionId, role: null, halt: null, gate: resumedGate(run, tasks),
|
|
903
|
+
handbacks: kept, tasks: { ...run.tasks, done: tasks }, review: resumedReview(run, kept), resumes,
|
|
904
|
+
};
|
|
905
|
+
// Computed before the write: resume records no halt, so a throw after saveRun would leave a changed run behind a failed exit.
|
|
906
|
+
const line = `run ${run.item} resumed after ${code} from ${next.gate}: kept ${records} record(s), dropped ${dropped}; next: ${nextLine(next)}`;
|
|
907
|
+
saveRun(root, next);
|
|
908
|
+
// The halted agent's envelope; the hand-back and review files stay for the owner and are overwritten on re-dispatch.
|
|
909
|
+
rmSync(join(root, ENVELOPE_FILE), { force: true });
|
|
910
|
+
return line;
|
|
911
|
+
}
|
|
912
|
+
|
|
678
913
|
const reviewWellFormed = (flag, arg, extra) => extra === undefined
|
|
679
914
|
&& (flag === '--round' ? arg !== undefined : flag === '--record' ? arg === undefined : flag === '--close' && SKIP_OUTCOME.test(arg ?? ''));
|
|
680
915
|
|
|
@@ -790,6 +1025,8 @@ function start(root, sessionId, args) {
|
|
|
790
1025
|
const security = resolveSecurity(root, stack(), { threshold, dependencyAudit });
|
|
791
1026
|
const bound = ticket === undefined ? null : ticketIntake(root, item, ticket);
|
|
792
1027
|
if (old) clearRunFiles(root);
|
|
1028
|
+
// C7: a previous run's owner file must not be read as this run's; end keeps it for the closing report.
|
|
1029
|
+
rmSync(join(root, OWNER_FILE), { force: true });
|
|
793
1030
|
if (bound) writeSnapshot(root, bound.path, bound.text);
|
|
794
1031
|
saveRun(root, {
|
|
795
1032
|
v: 1, session_id: sessionId, item, mode: auto ? 'auto' : 'step', started: new Date().toISOString(),
|
|
@@ -823,6 +1060,89 @@ function recordHalt(root, halt) {
|
|
|
823
1060
|
} catch { /* an unreadable run file cannot carry its own halt */ }
|
|
824
1061
|
}
|
|
825
1062
|
|
|
1063
|
+
// FEAT-061: a phase command dispatches its role outside a run. With a run file present, even a foreign or broken one, the verb writes nothing: the envelope path is the run's.
|
|
1064
|
+
const ENVELOPE_ROLES = ['spec', 'plan', 'audit', 'qa'];
|
|
1065
|
+
const ENVELOPE_USAGE = 'usage: orchestrate.mjs envelope <spec|plan|audit|qa> [--item <label>] | --clear';
|
|
1066
|
+
const LABEL = /^[a-zA-Z0-9._-]+$/; // The sys.s pattern snap-validate enforces.
|
|
1067
|
+
|
|
1068
|
+
function parseEnvelopeArgs(args) {
|
|
1069
|
+
if (args.length === 1 && args[0] === '--clear') return { clear: true };
|
|
1070
|
+
const [role, flag, label] = args;
|
|
1071
|
+
if (!ENVELOPE_ROLES.includes(role)) throw new Refusal(ENVELOPE_USAGE);
|
|
1072
|
+
if (args.length === 1) return { role, label: 'adhoc' };
|
|
1073
|
+
if (args.length === 3 && flag === '--item' && LABEL.test(label)) return { role, label };
|
|
1074
|
+
throw new Refusal(ENVELOPE_USAGE);
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// Read without throwing: an unreadable run file is another owner's to clear, never this verb's halt.
|
|
1078
|
+
function runState(root, sessionId) {
|
|
1079
|
+
const path = join(root, RUN_FILE);
|
|
1080
|
+
if (!existsSync(path)) return { state: 'N' };
|
|
1081
|
+
let run = null;
|
|
1082
|
+
try { run = JSON.parse(readFileSync(path, 'utf8')); } catch { /* judged below */ }
|
|
1083
|
+
if (isValidRun(run) && sessionId && run.session_id === sessionId) return { state: 'L', run, path };
|
|
1084
|
+
return { state: 'O', path };
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
function withRunFile(root, role, st) {
|
|
1088
|
+
const live = st.state === 'L';
|
|
1089
|
+
if (role === 'audit') {
|
|
1090
|
+
const who = live ? `live run ${st.run.item}` : `a run file at ${st.path} belongs to another session or is unreadable`;
|
|
1091
|
+
return `not-installed: ${who}; audit has no write tool and no shell, so it needs no envelope`;
|
|
1092
|
+
}
|
|
1093
|
+
if (role === 'qa' && live) {
|
|
1094
|
+
const command = st.run.test_command;
|
|
1095
|
+
if (typeof command !== 'string' || command === '') {
|
|
1096
|
+
throw new Refusal(`envelope qa: run ${st.run.item} records no test command, so Guard 7 grants qa no shell; end it, then start`);
|
|
1097
|
+
}
|
|
1098
|
+
return `not-installed: live run ${st.run.item}; qa runs ${command}`;
|
|
1099
|
+
}
|
|
1100
|
+
if (live) {
|
|
1101
|
+
throw new Refusal(`envelope ${role}: run ${st.run.item} is live in this session and its Define band writes this document; continue with /cc-orchestrate, or end the run`);
|
|
1102
|
+
}
|
|
1103
|
+
throw new Refusal(`envelope ${role}: a run file at ${st.path} belongs to another session or is unreadable; clear it with: node ${scriptRef(root)} end`);
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
function adhocFields(root, role, label) {
|
|
1107
|
+
const fields = {
|
|
1108
|
+
ph: PHASE[role], c: headCommit(root), s: label, n: [], f: [], d: [], x: [], role, tk: ROLE_ARTIFACTS[role].tk, gate: expectedGate(role),
|
|
1109
|
+
};
|
|
1110
|
+
if (role === 'spec' || role === 'plan') fields.scope = resolveDocs(root, label).scopes[role];
|
|
1111
|
+
if (role === 'qa') fields.p = { test_command: checkTestCommand(resolveTestCommand(root)) };
|
|
1112
|
+
return fields;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
function installAdhoc(root, role, label) {
|
|
1116
|
+
if (!findAgent(role, root)) {
|
|
1117
|
+
throw new Halt('ORCH_AGENT_MISSING', `no agent definition named ${role} in .claude/agents/ or ~/.claude/agents/`);
|
|
1118
|
+
}
|
|
1119
|
+
const built = runScript('snap-build.mjs', [], JSON.stringify(adhocFields(root, role, label)));
|
|
1120
|
+
if (built.status !== 0) throw new Halt('SNAP_ERROR', built.err);
|
|
1121
|
+
const error = validate(built.out, role);
|
|
1122
|
+
if (error) throw new Halt('SNAP_ERROR', error);
|
|
1123
|
+
writeAtomic(join(root, ENVELOPE_FILE), built.out);
|
|
1124
|
+
return `installed: ${role} envelope at ${ENVELOPE_FILE}\n${built.out.trim()}`;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
function clearAdhoc(root, st) {
|
|
1128
|
+
if (st.state !== 'N') throw new Refusal(`envelope --clear: a run file exists at ${st.path}; the envelope belongs to that run`);
|
|
1129
|
+
const path = join(root, ENVELOPE_FILE);
|
|
1130
|
+
if (!existsSync(path)) return 'no envelope';
|
|
1131
|
+
rmSync(path, { force: true });
|
|
1132
|
+
return 'cleared';
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
function envelopeVerb(root, sessionId, args) {
|
|
1136
|
+
const parsed = parseEnvelopeArgs(args);
|
|
1137
|
+
const st = runState(root, sessionId);
|
|
1138
|
+
if (parsed.clear) return clearAdhoc(root, st);
|
|
1139
|
+
if (st.state !== 'N') return withRunFile(root, parsed.role, st);
|
|
1140
|
+
// Every failure is a Refusal, so no halt is ever recorded in a run this verb does not own.
|
|
1141
|
+
try { return installAdhoc(root, parsed.role, parsed.label); } catch (e) {
|
|
1142
|
+
throw e instanceof Halt ? new Refusal(e.message) : e;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
826
1146
|
export async function cli(argv, env, cwd = process.cwd()) {
|
|
827
1147
|
const [verb, a, b, c] = argv;
|
|
828
1148
|
const root = findRunRoot(cwd);
|
|
@@ -834,16 +1154,19 @@ export async function cli(argv, env, cwd = process.cwd()) {
|
|
|
834
1154
|
approve: () => approve(root, sid, a, b, c),
|
|
835
1155
|
hash: () => hashDoc(root, a, b),
|
|
836
1156
|
review: () => review(root, sid, argv.slice(1)),
|
|
1157
|
+
resume: () => resume(root, sid, argv.slice(1)),
|
|
1158
|
+
envelope: () => envelopeVerb(root, sid, argv.slice(1)),
|
|
837
1159
|
end: () => end(root),
|
|
838
1160
|
};
|
|
839
1161
|
try {
|
|
840
|
-
if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|end');
|
|
1162
|
+
if (!verbs[verb]) throw new Refusal('usage: orchestrate.mjs start|install|handback|approve|hash|review|resume|envelope|end');
|
|
841
1163
|
process.stdout.write((await verbs[verb]()) + '\n');
|
|
842
1164
|
return 0;
|
|
843
1165
|
} catch (e) {
|
|
844
1166
|
if (e instanceof Refusal) { process.stderr.write(`orchestrate: ${e.message}\n`); return 2; }
|
|
845
1167
|
if (!(e instanceof Halt)) throw e;
|
|
846
|
-
|
|
1168
|
+
// resume never records a halt: one thrown by a helper it reuses must not overwrite the halt it was resuming (FEAT-055).
|
|
1169
|
+
if (!['start', 'envelope', 'resume'].includes(verb)) recordHalt(root, e);
|
|
847
1170
|
process.stderr.write(`${e.code}: ${e.reason}\n`);
|
|
848
1171
|
return 1;
|
|
849
1172
|
}
|