muse-crew 0.6.6 → 0.6.7

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.
@@ -30,30 +30,56 @@ const RESOLVED_WORKFLOW = inputs.resolved_workflow || null;
30
30
  const WORKFLOW_WAS_NULL = inputs.workflow_was_null === true;
31
31
  const CLAIM_WORKFLOW_PERSIST = (WORKFLOW_WAS_NULL && RESOLVED_WORKFLOW) ? ", \"workflow\": \"" + RESOLVED_WORKFLOW + "\"" : "";
32
32
 
33
+ // Visual verdict protocol availability — the workflow parks for parent-run
34
+ // baseline capture and visual verdict ONLY when the protocol is fully
35
+ // shipped. The protocol requires docs/visual-verdict.md in the release AND
36
+ // the parent-side capture tooling (task b309a97d, "QA owns the visual
37
+ // verdict"). Until both exist, the parks would deadlock waiting for a
38
+ // parent who cannot fulfill them.
39
+ // Effective value for this run, resolved by the dispatcher from the
40
+ // project's visual_protocol setting (null=inherits crew default=off).
41
+ // Manual launches without the arg default to off (previous behavior).
42
+ var VISUAL_PROTOCOL_AVAILABLE = inputs.visual_protocol === true;
43
+
33
44
  // Config from args — backward-compatible fallbacks for manual launches
34
- const DASHBOARD_SLUG = inputs.dashboardSlug || "orchestra-dashboard";
35
45
  const crewHome = inputs.crewHome || "~/workspace/.jarvis";
46
+ // Crew API: the workflow calls the crew-owned CLI, not the dashboard.
47
+ // The CLI implements the API.md contract against $CREW_HOME/crew-state.db.
48
+ const CREW_API = crewHome + "/current/lib/crew-api.js";
49
+ // Build a shell command invoking the CLI. Args are JSON-encoded and
50
+ // single-quote-wrapped for safe shell passing. The agent runs this and
51
+ // returns the stdout verbatim (the CLI emits JSON on stdout).
52
+ function crewCmd(command, args) {
53
+ var json = JSON.stringify(args || {}).replace(/'/g, "'\\''");
54
+ return "node " + CREW_API + " --crew-home " + crewHome + " " + command + " --json '" + json + "'";
55
+ }
36
56
  const ORCH_PATH = crewHome + "/.orchestration";
37
57
  // Pin lifecycle scripts to this run
38
58
  const LIFECYCLE_SRC = crewHome + "/lib/worktree-lifecycle.sh";
39
59
  const MERGE_LOCK_SRC = crewHome + "/lib/merge-lock.sh";
40
- const RUN_LIB = crewHome + "/.pins/" + taskId; // persistent disk, NOT /tmp (tmpfs wiped by cell reboots — canary b5efd1b1); stale pins reaped by orphan-sweep
60
+ const RUN_LIB = crewHome + "/.pins/" + taskId; // persistent disk, NOT /tmp (tmpfs wiped by cell reboots — canary b5efd1b1)
41
61
  const LIFECYCLE = RUN_LIB + "/worktree-lifecycle.sh";
42
62
  const MERGE_LOCK = RUN_LIB + "/merge-lock.sh";
43
63
  const PUBLISH_NPM_SRC = crewHome + "/lib/publish-npm.sh";
44
64
  const PUBLISH_NPM = RUN_LIB + "/publish-npm.sh";
45
- const ORPHAN_SWEEP_SRC = crewHome + "/lib/orphan-sweep.sh";
46
- const ORPHAN_SWEEP = RUN_LIB + "/orphan-sweep.sh";
47
65
  // The four basenames the pin step must materialize — asserted mechanically
48
66
  // by workflow code from the verbatim listing, never from agent prose.
49
- const PIN_BASENAMES = [LIFECYCLE, MERGE_LOCK, PUBLISH_NPM, ORPHAN_SWEEP].map(function (p) { return p.split("/").pop(); });
67
+ const PIN_BASENAMES = [LIFECYCLE, MERGE_LOCK, PUBLISH_NPM].map(function (p) { return p.split("/").pop(); });
50
68
 
51
69
  // Project config — passed by dispatcher, falls back to dashboard defaults
52
70
  const projectConfig = inputs.project_config || {};
53
71
  // Project this run was dispatched for — the mid-run project-change guard
54
72
  // compares the task's live project against this on every phase boundary.
55
73
  const LAUNCH_PROJECT_ID = inputs.project_id || "";
56
- const REPO_PATH = projectConfig.repo_path || "~/workspace/ts-spaces/orchestra-dashboard";
74
+ // Fail closed on a missing repo_path never silently fall back to
75
+ // another checkout (the canary's wrong-repo Build, 2026-09-11: prepare
76
+ // failed in the npm package and the builder freelanced into a dashboard
77
+ // clone). The dispatcher skips unconfigured projects; this is the
78
+ // backstop for direct launches.
79
+ const REPO_PATH = projectConfig.repo_path || "";
80
+ if (!REPO_PATH) {
81
+ throw new Error("Project '" + (inputs.project_id || "unknown") + "' has no repo_path configured — set it via updateproject before dispatching tasks.");
82
+ }
57
83
 
58
84
  // Worktree layout: the task's worktree lives at
59
85
  // <repo>/.worktrees/<task_id> on branch task/<task_id>. The lifecycle
@@ -61,7 +87,7 @@ const REPO_PATH = projectConfig.repo_path || "~/workspace/ts-spaces/orchestra-da
61
87
  // registry at <repo>/.worktrees/.registry/<task_id> is the source of
62
88
  // truth for task→branch/path.
63
89
  // Env prefix baked into every lifecycle invocation the agents run.
64
- const LIFECYCLE_ENV = "CREW_REPO=" + REPO_PATH + " ";
90
+ const LIFECYCLE_ENV = "CREW_HOME=" + crewHome + " CREW_REPO=" + REPO_PATH + " ";
65
91
  // The task branch is always task/<task_id>.
66
92
  const TASK_BRANCH = "task/" + taskId;
67
93
  // Where the agent works.
@@ -70,7 +96,7 @@ const WORKTREE_HINT = REPO_PATH + "/.worktrees/" + taskId;
70
96
  const WORKTREE_PRESERVED_HINT = ".worktrees/" + taskId;
71
97
 
72
98
  const PUBLISH_TYPE = projectConfig.deploy_type || "";
73
- const PUBLISH_SLUG = projectConfig.deploy_slug || DASHBOARD_SLUG;
99
+ const PUBLISH_SLUG = projectConfig.deploy_slug || "";
74
100
  const PROJECT_DESC = projectConfig.description || "React + TypeScript web dashboard (client/src/, server/src/, drizzle/)";
75
101
  const RELEASE_SCRIPT = crewHome + "/crew-release.sh";
76
102
 
@@ -192,7 +218,7 @@ function attemptKey(base, reworkCount) {
192
218
  function pinLifecycle(key) {
193
219
  return agent(
194
220
  "Snapshot lifecycle scripts for version pinning.\n" +
195
- "Run: mkdir -p " + RUN_LIB + " && cp " + LIFECYCLE_SRC + " " + LIFECYCLE + " && cp " + MERGE_LOCK_SRC + " " + MERGE_LOCK + " && cp " + PUBLISH_NPM_SRC + " " + PUBLISH_NPM + " && cp " + ORPHAN_SWEEP_SRC + " " + ORPHAN_SWEEP + " && chmod +x " + LIFECYCLE + " " + MERGE_LOCK + " " + PUBLISH_NPM + " " + ORPHAN_SWEEP + " && ls -1 " + RUN_LIB + "\n" +
221
+ "Run: mkdir -p " + RUN_LIB + " && cp " + LIFECYCLE_SRC + " " + LIFECYCLE + " && cp " + MERGE_LOCK_SRC + " " + MERGE_LOCK + " && cp " + PUBLISH_NPM_SRC + " " + PUBLISH_NPM + " && chmod +x " + LIFECYCLE + " " + MERGE_LOCK + " " + PUBLISH_NPM + " && ls -1 " + RUN_LIB + "\n" +
196
222
  "Return the verbatim output of the ls -1 command as { \"listing\": \"<verbatim output>\" } and nothing else.",
197
223
  { key: key, label: "Pinning lifecycle scripts",
198
224
  schema: { type: "object", properties: { listing: { type: "string" } }, required: ["listing"] } }
@@ -204,19 +230,65 @@ function pinLifecycle(key) {
204
230
  function parsePinListing(result) {
205
231
  return (result && result.listing ? result.listing : "").split("\n").map(function (s) { return s.trim(); }).filter(function (s) { return s.length > 0; });
206
232
  }
233
+ // TOOL_CHECK_PREAMBLE - every work agent runs this first. The artifact tool
234
+ // namespace is deferred for workflow children: present but invisible until
235
+ // the child loads it via tool_search.load_tool_namespace (bug 3472bf36 root
236
+ // cause, verified 2026-09-11 by direct probe: 5/5 children self-loaded it;
237
+ // the "non-deterministic platform flake" was children never being told to
238
+ // load it). The two signal lines are the ONLY machine-read tool-availability
239
+ // evidence - the workflow never guesses from English prose.
240
+ // Byte-identical across standard/bugfix/chore/docs - pinned by
241
+ // tests/artifact-tools.test.js.
242
+ var TOOL_CHECK_PREAMBLE =
243
+ "TOOL CHECK (do this first, before any other work):\n" +
244
+ "1. Call tool_search.load_tool_namespace with paths [\"artifact\"].\n" +
245
+ "2. Write exactly one line: artifact_tools: ok - or artifact_tools: missing if the call failed or the tool does not exist.\n" +
246
+ "3. Run the shell command: echo tool-probe-ok - then write exactly one line: shell_transport: ok - or shell_transport: unavailable if you cannot run shell commands.\n" +
247
+ "Then do the assignment below.\n\n";
248
+ // ARTIFACT_LOAD_PREAMBLE - the one-line load instruction that precedes every
249
+ // special-purpose prompt calling artifact tools (rebuild trigger, provenance
250
+ // stamp, publish verification). The artifact tool namespace is deferred for
251
+ // workflow children: present but invisible until the child loads it via
252
+ // tool_search.load_tool_namespace (bug 3472bf36 root cause). Byte-identical
253
+ // across standard/bugfix/chore - pinned by tests/artifact-tools.test.js.
254
+ var ARTIFACT_LOAD_PREAMBLE =
255
+ "First call tool_search.load_tool_namespace with paths [\"artifact\"] - the artifact tool namespace is deferred and invisible until loaded.\n";
207
256
  function buildTransportRetryTrailer(stepName, repoPath, taskId, attempt, reason) {
208
- // reason: "discarded" (the runtime threw the output away it could not be
209
- // machine-read) or "empty" (agent() returned without throwing but produced
210
- // nothing usable). The trailer tells the retry what to expect, not just to
211
- // try again.
257
+ // reason: "discarded" (the runtime threw the output away - it could not be
258
+ // machine-read), "empty" (agent() returned without throwing but produced
259
+ // nothing usable), "no-tools" (the worker's TOOL CHECK reported
260
+ // artifact_tools: missing), or "no-transport" (the worker's TOOL CHECK
261
+ // reported shell_transport: unavailable).
262
+ // The trailer tells the retry what to expect, not just to try again.
212
263
  var why = reason === "empty"
213
264
  ? "your previous attempt returned no usable output"
265
+ : reason === "no-tools"
266
+ ? "your previous attempt's TOOL CHECK reported artifact_tools: missing (this is a fresh launch, so run the TOOL CHECK's load step again before the work)"
267
+ : reason === "no-transport"
268
+ ? "your previous attempt's TOOL CHECK reported shell_transport: unavailable (this is a fresh launch, so run the TOOL CHECK's shell probe again before the work)"
214
269
  : "your previous attempt's output could not be machine-read as JSON and was discarded";
215
270
  return "\n\nTRANSPORT RETRY (attempt " + attempt + " of 2): " + why + ". " +
216
- "First check existing state (worktree/branch at " + repoPath + "/.worktrees/" + taskId + ", the task branch, dashboard sessions for this task) " +
271
+ "First check existing state (worktree/branch at " + repoPath + "/.worktrees/" + taskId + ", the task branch, dashboard sessions for this task) - " +
217
272
  "if the " + stepName + " work is already complete, report on what was done rather than duplicating side effects. " +
218
273
  "Then return your report as JSON in exactly the shape specified above.";
219
274
  }
275
+ // parseToolSignals - bug 3472bf36. The work agent's TOOL CHECK emits two
276
+ // exact signal lines: artifact_tools: ok|missing and
277
+ // shell_transport: ok|unavailable. The workflow reads ONLY these lines.
278
+ // It never guesses tool availability from English prose: the old regex
279
+ // misclassified ordinary inability-prose (e.g. a Map agent describing what
280
+ // it could not inspect) and burned all three attempts on useless retries.
281
+ // Byte-identical across standard/bugfix/chore/docs - pinned by
282
+ // tests/artifact-tools.test.js.
283
+ function parseToolSignals(text) {
284
+ var t = String(text || "");
285
+ var out = { artifactTools: "unknown", shellTransport: "unknown" };
286
+ var am = t.match(/^artifact_tools:\s*(ok|missing)\s*$/m);
287
+ if (am) out.artifactTools = am[1];
288
+ var sm = t.match(/^shell_transport:\s*(ok|unavailable)\s*$/m);
289
+ if (sm) out.shellTransport = sm[1];
290
+ return out;
291
+ }
220
292
  function describeWorkAgentFailure(stepName, identity, attempts) {
221
293
  // Honest classification of a work-agent call that yielded no usable
222
294
  // report, with the per-attempt evidence preserved in the session notes.
@@ -270,6 +342,259 @@ function extractReleaseDecision(workerText) {
270
342
  if (rel === "yes" && !b) return null;
271
343
  return { release: rel, version_bump: b ? b[1].toLowerCase() : null };
272
344
  }
345
+ // Merge-record helpers (merge-lease fix, 2026-09-12): the integrate step
346
+ // records the exact merged commit in $CREW_HOME/.merge-records/<task_id>,
347
+ // so a re-dispatched run can verify a landed merge and publish it even
348
+ // after the branch was reclaimed under an expired lease. All pure — no I/O,
349
+ // no clock. Byte-identical in standard.js, bugfix.js, chore.js.
350
+ function parseMergeRecord(text) {
351
+ var t = (text || "").trim();
352
+ if (!t || t === "NO_RECORD") return null;
353
+ // Append-only record; last occurrence of each key wins.
354
+ function lastVal(prefix) {
355
+ var v = null, found = false;
356
+ var lines = t.split("\n");
357
+ for (var i = 0; i < lines.length; i++) {
358
+ var line = lines[i].trim();
359
+ if (line.indexOf(prefix) === 0) { v = line.slice(prefix.length).trim(); found = true; }
360
+ }
361
+ return found ? v : null;
362
+ }
363
+ var commit = lastVal("merge_commit=");
364
+ var release = lastVal("release=");
365
+ var bump = lastVal("version_bump=");
366
+ var malformed = false;
367
+ if (commit === null || !/^[0-9a-f]{40}$/.test(commit)) malformed = true;
368
+ if (release !== null && !/^(yes|no|unknown)$/.test(release)) malformed = true;
369
+ if (bump !== null && !/^(patch|minor|major|none)$/.test(bump)) malformed = true;
370
+ if (malformed) return { malformed: true };
371
+ return { merge_commit: commit, merged_at: lastVal("merged_at="), release: release, version_bump: bump };
372
+ }
373
+ // Publish lock decision table: what the merge record + lock state say about
374
+ // the publish window. Pure — pinned by tests/merge-record.test.js.
375
+ function decidePublishLockPath(o) {
376
+ var rec = o.rec, ancestor = !!o.ancestor, lockHeld = !!o.lockHeld;
377
+ if (rec === null) return lockHeld ? "refresh" : "skip";
378
+ if (rec.malformed) return "park";
379
+ if (!ancestor) return "park";
380
+ return lockHeld ? "refresh" : "reacquire";
381
+ }
382
+ // Integrate retry decision: a landed merge must route to Publish, not
383
+ // re-integrate (the branch may be gone — reclaimed under an expired lease).
384
+ // Pure — pinned by tests/merge-record.test.js.
385
+ function decideIntegrateRetry(o) {
386
+ var rec = o.rec, ancestor = !!o.ancestor;
387
+ if (rec === null) return "proceed";
388
+ if (rec.malformed) return "park";
389
+ return ancestor ? "skip-to-publish" : "proceed";
390
+ }
391
+ // On a dispatcher retry resumed at Integrate, the run-local releaseDecision
392
+ // is null (Build doesn't re-run). Hydrate it from the merge record so the
393
+ // npm Publish gate doesn't park a publishable merge. Pure — pinned by
394
+ // tests/merge-record.test.js.
395
+ function hydrateReleaseDecision(rec) {
396
+ if (rec && (rec.release === "yes" || rec.release === "no")) {
397
+ return { release: rec.release, version_bump: rec.version_bump === "none" ? null : rec.version_bump };
398
+ }
399
+ return null;
400
+ }
401
+
402
+ // Publish diff transport: parse a unified diff into per-file {path, added,
403
+ // removed} line lists. Pure function — no I/O, no clock. Used by Publish to
404
+ // verify the artifact builder applied the carried change (canary run 4,
405
+ // 2026-09-11: the builder's source tree was stale and disconnected from the
406
+ // crew's repo; "rebuild from current source" rebuilt stale code and the
407
+ // workflow stamped the new commit hash on it — provenance fiction).
408
+ function parseUnifiedDiff(diffText) {
409
+ var files = [];
410
+ var current = null;
411
+ var lines = (diffText || "").split("\n");
412
+ for (var i = 0; i < lines.length; i++) {
413
+ var line = lines[i];
414
+ var m = /^diff --git a\/(.*) b\/(.*)$/.exec(line);
415
+ if (m) {
416
+ current = { path: m[2], added: [], removed: [] };
417
+ files.push(current);
418
+ continue;
419
+ }
420
+ if (!current) continue;
421
+ if (/^--- /.test(line) || /^\+\+\+ /.test(line)) continue;
422
+ if (/^@@ /.test(line)) continue;
423
+ if (line.charAt(0) === "+") {
424
+ current.added.push(line.slice(1));
425
+ } else if (line.charAt(0) === "-") {
426
+ current.removed.push(line.slice(1));
427
+ }
428
+ }
429
+ return files;
430
+ }
431
+
432
+ // Compare the artifact builder's reported applied-changes against the diff's
433
+ // expected changes. Every added/removed line must match exactly per path,
434
+ // and the file counts must match — the builder applies exactly the carried
435
+ // change, nothing more, nothing less. Pure function — no I/O, no clock.
436
+ // OBSERVATION INPUT ONLY (2026-09-12, task 23ca8f3f): the applied report
437
+ // has a demonstrated false-negative mode (applied:[] for a diff the builder
438
+ // had actually applied), and it is derived from the carried diff, so a match
439
+ // certifies nothing either. A mismatch is logged as observation; it never
440
+ // parks and never blocks the stamp. The verification is the independent
441
+ // read-back (docs/publish-verification.md).
442
+ function verifyAppliedChanges(expected, applied) {
443
+ if (!Array.isArray(applied)) {
444
+ return { ok: false, reason: "builder returned no applied-changes list" };
445
+ }
446
+ function sorted(a) { return (a || []).slice().sort(); }
447
+ function eq(a, b) {
448
+ a = sorted(a); b = sorted(b);
449
+ if (a.length !== b.length) return false;
450
+ for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
451
+ return true;
452
+ }
453
+ for (var i = 0; i < expected.length; i++) {
454
+ var exp = expected[i];
455
+ var got = null;
456
+ for (var j = 0; j < applied.length; j++) {
457
+ if (applied[j] && applied[j].path === exp.path) { got = applied[j]; break; }
458
+ }
459
+ if (!got) {
460
+ return { ok: false, reason: "builder did not report changing '" + exp.path + "'" };
461
+ }
462
+ if (!eq(exp.added, got.added)) {
463
+ return { ok: false, reason: "added lines for '" + exp.path + "' do not match the carried diff" };
464
+ }
465
+ if (!eq(exp.removed, got.removed)) {
466
+ return { ok: false, reason: "removed lines for '" + exp.path + "' do not match the carried diff" };
467
+ }
468
+ }
469
+ if (applied.length !== expected.length) {
470
+ return { ok: false, reason: "builder reported changing " + applied.length + " file(s), diff carries " + expected.length };
471
+ }
472
+ return { ok: true };
473
+ }
474
+
475
+ // Publish read-back request builder: the verbatim_request the workflow hands
476
+ // to artifact_inspect (via a child) after the artifact build lands. Pure
477
+ // function — no I/O, no clock. The request carries the merged diff as the
478
+ // expected change and asks for an independent read of the artifact's actual
479
+ // source: for each file, the exact current text of the changed regions plus
480
+ // a per-line present/absent finding. The parent (docs/publish-verification.md)
481
+ // compares these findings against the diff mechanically and stamps provenance
482
+ // only on a match. This breaks the circularity that hollowed canary run 8
483
+ // (2026-09-11): verifyAppliedChanges compares the builder's applied-report
484
+ // against the diff the report was derived from — a fabricated report passes
485
+ // by construction. Independent read-back cannot be fabricated from the diff;
486
+ // it must match the artifact's real content.
487
+ function buildPublishReadbackRequest(taskId, commit, diff, buildAgentId) {
488
+ // Build-ID correlation (2026-09-12): buildAgentId is the build.agent_id the
489
+ // workflow observed for the publish attempt (the artifact system's durable
490
+ // build identifier). The read-back request carries it so the parent can
491
+ // prove the read-back inspected the live build of THIS attempt — not a
492
+ // different build's output. Null/empty means the edit was accepted but
493
+ // never correlated to a builder run. Pure function of inputs — no I/O,
494
+ // no clock.
495
+ var buildIdLine = (typeof buildAgentId === "string" && buildAgentId.length > 0)
496
+ ? "Expected builder build agent_id: " + buildAgentId + " (the artifact system's in-flight correlation ID for this publish attempt — not a durable post-completion identifier).\n"
497
+ : "No build agent_id was observed for this publish attempt (the edit was accepted but never correlated to a builder run) — say so explicitly in your report.\n";
498
+ return (
499
+ "Publish content read-back for task " + taskId + ", merge commit " + commit + ".\n" +
500
+ "The unified diff below was supposed to be applied to this artifact's source tree and deployed. Do NOT modify anything.\n" +
501
+ "Do NOT rely on the builder's applied-changes report — it is derived from this same diff, so it cannot confirm the content. Read the artifact's CURRENT source directly.\n" +
502
+ "\n" +
503
+ buildIdLine +
504
+ "Report the live build's agent_id as seen in artifact_status (or state explicitly that no build/agent_id is visible). If an expected agent_id is given above and the live one differs, say so exactly — the read-back may be inspecting a different build's output.\n" +
505
+ "\n" +
506
+ "UNIFIED DIFF (expected change):\n" +
507
+ "```diff\n" + diff + "\n```\n" +
508
+ "\n" +
509
+ "For each file in the diff:\n" +
510
+ "1. Read the file's CURRENT content in the artifact source tree.\n" +
511
+ "2. Quote the exact current text of the regions around the changed lines.\n" +
512
+ "3. For every added (+) line in the diff, state whether that exact line is PRESENT in the current source.\n" +
513
+ "4. For every removed (-) line in the diff, state whether that exact line is ABSENT from the current source.\n" +
514
+ "5. Report build/deploy health and the console error count.\n" +
515
+ "\n" +
516
+ "Return the per-file present/absent findings with the quoted observed lines. Do not modify anything.\n" +
517
+ "This read-back feeds the parent content-verification protocol (docs/publish-verification.md): the parent stamps provenance only when every added line is present and every removed line is absent."
518
+ );
519
+ }
520
+
521
+ // Pre-publish base observation (diagnostic, 2026-09-12): instruction fragment
522
+ // for the builder's edit request, asking it to report the sha256 of each
523
+ // touched file's CURRENT content BEFORE applying the diff. Pure function —
524
+ // no I/O, no clock.
525
+ //
526
+ // Why: the builder applies the carried diff to its own source tree, whose
527
+ // base state is unrecorded. The post-hoc read-back only checks the changed
528
+ // regions AFTER the edit; it cannot tell us what base the diff landed on.
529
+ // If the tree was dirty or drifted before the edit, the read-back still
530
+ // passes (the diff's lines are present) while the artifact silently carries
531
+ // uncommitted content — the production validateRepoPath incident
532
+ // (2026-09-12), where the live artifact contained code absent from every git
533
+ // ref. These pre-hashes, compared against the workflow-computed expected
534
+ // base hashes (merge parent), reveal what the publish actually read.
535
+ // Observation only — the workflow logs mismatches but never parks on them.
536
+ function buildPreHashInstruction(files) {
537
+ var paths = files.map(function(f) { return f.path; }).join(", ");
538
+ return (
539
+ "- BEFORE applying anything, compute the sha256 hash of each file below as it CURRENTLY exists in your source tree (before your changes). Use the exact bytes of the current file content.\n" +
540
+ "- Report these hashes in the \"pre_hashes\" field of your return JSON, as { \"<path>\": \"<sha256 hex>\" }.\n" +
541
+ "- If a file does not exist in your tree, report its hash as the string \"MISSING\".\n" +
542
+ "- Do this BEFORE applying the diff — the hashes must reflect the pre-edit state.\n" +
543
+ " Files: " + paths + "\n"
544
+ );
545
+ }
546
+
547
+ // Durable publish-attempt ledger (2026-09-12): every artifact publish
548
+ // attempt is recorded append-only at $CREW_HOME/.publish-ledger/<slug>.jsonl
549
+ // on persistent disk (NOT /tmp). The ledger is the correlation record for
550
+ // publish attempts whose outcome is UNKNOWN. When the rebuild trigger's
551
+ // child returns prose instead of JSON (structured-output failure), the edit
552
+ // may already have been accepted as pending_init — and artifact_status
553
+ // cannot see pending_init (diagnostic canary 2026-09-12: an edit accepted
554
+ // as pending_init was immediately followed by an all-false status check,
555
+ // and the old retry issued a DUPLICATE edit). "No build visible" is NOT
556
+ // evidence the edit did not go through, so the workflow never blind-retries
557
+ // on an unknown outcome: it records the attempt and parks fail-closed. A
558
+ // human or a later run correlates the accepted edit via the ledger (commit
559
+ // hash + attempt key + the artifact build's agent_id when one was observed)
560
+ // instead of guessing from a blind status poll.
561
+ // Best-effort observability: a failed write is logged loudly but never
562
+ // throws — the caller's park/proceed decision never depends on the ledger.
563
+ // Byte-identical across standard/bugfix/chore — pinned by
564
+ // tests/publish-ledger.test.js.
565
+ async function recordPublishLedger(entry, rework) {
566
+ try {
567
+ var ledgerDir = crewHome + "/.publish-ledger";
568
+ var line = JSON.stringify({
569
+ ts: "@LEDGER_TS@",
570
+ task_id: taskId,
571
+ workflow: RESOLVED_WORKFLOW || "unknown",
572
+ slug: PUBLISH_SLUG,
573
+ commit: entry.commit || null,
574
+ attempt: entry.attempt || null,
575
+ agent_id: entry.agent_id || null,
576
+ applied_report: entry.applied_report || null,
577
+ outcome: entry.outcome,
578
+ detail: entry.detail || ""
579
+ });
580
+ var sq = function(s) { return "'" + String(s).split("'").join("'\\''") + "'"; };
581
+ var res = await agent(
582
+ "Append one line to the publish-attempt ledger (best-effort observability, not a gate).\n" +
583
+ "Run: mkdir -p " + sq(ledgerDir) + " && printf '%s\n' " + sq(line) +
584
+ " | sed \"s/@LEDGER_TS@/$(date -u +%Y-%m-%dT%H:%M:%SZ)/\" >> " + sq(ledgerDir + "/" + PUBLISH_SLUG + ".jsonl") + " && echo LEDGER_OK\n" +
585
+ "Return JSON { \"result\": \"<verbatim output>\" } and nothing else.",
586
+ { key: attemptKey("publish-ledger-" + taskId + "-" + entry.outcome, rework),
587
+ label: "Recording publish attempt in ledger",
588
+ schema: { type: "object", properties: { result: { type: "string" } }, required: ["result"] } }
589
+ );
590
+ var ok = !!(res && res.result && res.result.indexOf("LEDGER_OK") !== -1);
591
+ log("Publish ledger: outcome '" + entry.outcome + "' for task " + taskId +
592
+ (ok ? " recorded." : " NOT confirmed (" + ((res && res.result) || "no output") + ")"));
593
+ } catch (e) {
594
+ log("Publish ledger: write failed for task " + taskId + " (non-fatal, observability only): " + (e && e.message ? e.message : e));
595
+ }
596
+ }
597
+
273
598
  // Marker line preservation: machine-readable lines (repo_diff:, release:,
274
599
  // version_bump:, VERDICT:, TARGET_VERSION=, published:) are extracted from
275
600
  // the full worker report and appended after the summary slice, so a long
@@ -279,13 +604,37 @@ function extractMarkerLines(workerText) {
279
604
  var markers = [];
280
605
  for (var i = 0; i < lines.length; i++) {
281
606
  var line = lines[i].trim();
282
- if (/^(repo_diff:|release:|version_bump:|VERDICT:|TARGET_VERSION=|published:|experiential:|capture_targets:)/i.test(line)) {
607
+ if (/^(repo_diff:|release:|version_bump:|VERDICT:|TARGET_VERSION=|published:|experiential:|capture_targets:|worktree:)/i.test(line)) {
283
608
  markers.push(line);
284
609
  }
285
610
  }
286
611
  return markers.join("\n");
287
612
  }
288
613
 
614
+ // Worktree confinement: the Build agent must declare the exact worktree
615
+ // path it built in on a `worktree:` marker line. The workflow compares it
616
+ // against WORKTREE_HINT mechanically (exact string match) — never by
617
+ // reading agent prose. This closes the hole where a builder whose prepare
618
+ // failed freelanced into a different checkout (canary, 2026-09-11): the
619
+ // honest-but-confused case fails here, and a fabricated path is caught one
620
+ // phase later when Review's inspect finds no commits in the configured repo.
621
+ function extractWorktree(workerText) {
622
+ var lines = (workerText || "").split("\n");
623
+ var found = null;
624
+ for (var i = 0; i < lines.length; i++) {
625
+ var line = lines[i].trim();
626
+ var m = /^worktree:\s*(\S.*)$/i.exec(line);
627
+ if (m) found = m[1].trim();
628
+ }
629
+ if (!found) return { ok: false };
630
+ // Normalize trailing slashes: ".../<task_id>/" and ".../<task_id>"
631
+ // name the same directory. Compare locations, not spellings — a
632
+ // builder that emits the trailing slash still worked in the right
633
+ // place. (Canary 2026-09-11: an exact comparison rejected a correct
634
+ // declaration over one trailing slash.)
635
+ return { ok: true, path: found.replace(/\/+$/, "") };
636
+ }
637
+
289
638
  // Visual verdict shared functions: byte-identical across standard.js,
290
639
  // bugfix.js, and chore.js (pinned by tests/visual-verdict.test.js — same
291
640
  // contract as buildTransportRetryTrailer).
@@ -334,8 +683,8 @@ async function resolveExperiential() {
334
683
  var expCheck = null;
335
684
  try {
336
685
  expCheck = await agent(
337
- "Find this task's Triage step session notes from the dashboard.\n" +
338
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getstate\", args: { \"events_limit\": 1 }.\n" +
686
+ "Find this task's Triage step session notes from the crew API.\n" +
687
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("get-state", { events_limit: 1 }) + "\n" +
339
688
  "Find the session with task_id \"" + taskId + "\" and step \"Triage\" (status completed) in the returned sessions array and read its notes field.\n" +
340
689
  "Return JSON { \"experiential_line\": \"<the exact text of the experiential: marker line from the notes, or empty string if absent>\" } and nothing else.",
341
690
  {
@@ -357,10 +706,12 @@ async function resolveExperiential() {
357
706
  }
358
707
  // Baseline evidence status: reads the task's note events for the exact
359
708
  // protocol prefixes (explicit state, never English matching). Returns
360
- // { baseline_found, baseline_kind, baseline_refs, requested_count }.
709
+ // { baseline_found, baseline_kind, baseline_refs, requested_count, evidence_count }.
361
710
  // found = any note starting exactly "baseline: captured" or "baseline:
362
711
  // none" (kind/refs come from the LATEST such message); requested_count =
363
- // the number of notes starting exactly "baseline: requested". Each call
712
+ // the number of notes starting exactly "baseline: requested";
713
+ // evidence_count = the number of notes starting exactly "baseline: captured" or
714
+ // "baseline: none" (the per-attempt evidence chain; state-derived, no wall clock). Each call
364
715
  // uses a fresh key: the evidence changes between calls (the parent logs
365
716
  // the capture while this run is parked), so a cached replay would lie.
366
717
  let baselineStatusCallCount = 0;
@@ -368,10 +719,10 @@ async function baselineStatus() {
368
719
  baselineStatusCallCount++;
369
720
  try {
370
721
  var ev = await agent(
371
- "Read this task's note events from the dashboard.\n" +
372
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getevents\", args: { \"task_id\": \"" + taskId + "\" }.\n" +
722
+ "Read this task's note events from the crew API.\n" +
723
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("get-events", { task_id: taskId }) + "\n" +
373
724
  "Consider only events with type \"note\". For each message, check whether it starts exactly with \"baseline: captured\", \"baseline: none\", or \"baseline: requested\" (exact prefix, case-sensitive).\n" +
374
- "Return JSON { \"baseline_found\": <true if any message starts exactly with \"baseline: captured\" or \"baseline: none\">, \"baseline_kind\": \"<\"captured\" or \"none\", from the LATEST such message, or empty string if none>\", \"baseline_refs\": \"<the text after the prefix in that latest message, or empty string>\", \"requested_count\": <count of messages starting exactly with \"baseline: requested\"> } and nothing else.",
725
+ "Return JSON { \"baseline_found\": <true if any message starts exactly with \"baseline: captured\" or \"baseline: none\">, \"baseline_kind\": \"<\"captured\" or \"none\", from the LATEST such message, or empty string if none>\", \"baseline_refs\": \"<the text after the prefix in that latest message, or empty string>\", \"requested_count\": <count of messages starting exactly with \"baseline: requested\">, \"evidence_count\": <count of messages starting exactly with \"baseline: captured\" or \"baseline: none\"> } and nothing else.",
375
726
  {
376
727
  key: "baseline-status-" + taskId + "-" + baselineStatusCallCount,
377
728
  label: "Reading baseline evidence status",
@@ -381,9 +732,10 @@ async function baselineStatus() {
381
732
  baseline_found: { type: "boolean" },
382
733
  baseline_kind: { type: "string" },
383
734
  baseline_refs: { type: "string" },
384
- requested_count: { type: "number" }
735
+ requested_count: { type: "number" },
736
+ evidence_count: { type: "number" }
385
737
  },
386
- required: ["baseline_found", "baseline_kind", "baseline_refs", "requested_count"]
738
+ required: ["baseline_found", "baseline_kind", "baseline_refs", "requested_count", "evidence_count"]
387
739
  }
388
740
  }
389
741
  );
@@ -391,11 +743,12 @@ async function baselineStatus() {
391
743
  baseline_found: !!(ev && ev.baseline_found),
392
744
  baseline_kind: (ev && ev.baseline_kind) || "",
393
745
  baseline_refs: (ev && ev.baseline_refs) || "",
394
- requested_count: (ev && ev.requested_count) || 0
746
+ requested_count: (ev && ev.requested_count) || 0,
747
+ evidence_count: (ev && ev.evidence_count) || 0
395
748
  };
396
749
  } catch (e) {
397
750
  log("baselineStatus: agent call failed (" + (e && e.message ? e.message : e) + ") — treating as no evidence");
398
- return { baseline_found: false, baseline_kind: "", baseline_refs: "", requested_count: 0 };
751
+ return { baseline_found: false, baseline_kind: "", baseline_refs: "", requested_count: 0, evidence_count: 0 };
399
752
  }
400
753
  }
401
754
  // Visual verdict status: the parent records the visual verdict as a note
@@ -409,10 +762,10 @@ async function visualVerdictStatus() {
409
762
  visualVerdictCallCount++;
410
763
  try {
411
764
  var vv = await agent(
412
- "Read this task's QA session and note events from the dashboard.\n" +
413
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getstate\", args: { \"events_limit\": 1 }.\n" +
765
+ "Read this task's QA session and note events from the crew API.\n" +
766
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("get-state", { events_limit: 1 }) + "\n" +
414
767
  "Find the LATEST session with task_id \"" + taskId + "\" and step \"QA\" in the returned sessions array and note its started_at timestamp (call it QA_START; use empty string if there is no QA session).\n" +
415
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getevents\", args: { \"task_id\": \"" + taskId + "\" }.\n" +
768
+ "Then run in shell and return the stdout verbatim:\n" + crewCmd("get-events", { task_id: taskId }) + "\n" +
416
769
  "Consider only events with type \"note\" whose timestamp is newer than QA_START. Among them, find messages starting exactly with \"visual_verdict: PASS\" or \"visual_verdict: FAIL\" (exact prefix, case-sensitive); use the latest such message.\n" +
417
770
  "Return JSON { \"found\": <true if such a message exists>, \"verdict\": \"<\"PASS\" or \"FAIL\" from that message, or empty string>\", \"detail\": \"<the text after the prefix in that message, or empty string>\" } and nothing else.",
418
771
  {
@@ -498,21 +851,44 @@ function releaseDecisionText() {
498
851
  // envelope the launcher sees. If the park call itself fails, the run
499
852
  // reports "failed" (retryable) so the next tick re-attempts the park —
500
853
  // a lost park is never reported as parked.
854
+ // Terminal cleanup: the run's last act at every park/fail boundary. A run
855
+ // that parks or fails must not leak its worktree, branch, or merge lock.
856
+ // The lifecycle's terminal-cleanup releases the lock unconditionally and
857
+ // reclaims the worktree+branch ONLY when the task branch is fully merged
858
+ // into main (then it is redundant); unmerged work is preserved for the
859
+ // human by design. Fire-and-forget with one bounded retry — the merge-lock
860
+ // lease expiry and the orphan sweep are the backstop for a dead transport.
861
+ async function terminalCleanup() {
862
+ for (var attempt = 1; attempt <= 2; attempt++) {
863
+ try {
864
+ await agent(
865
+ "Run in shell and return the stdout verbatim:\n" + LIFECYCLE_ENV + " terminal-cleanup " + taskId,
866
+ { key: "terminal-cleanup" + (attempt > 1 ? "-retry" : ""),
867
+ label: "Terminal cleanup (merged-branch reclamation)" + (attempt > 1 ? " (retry)" : "") }
868
+ );
869
+ return;
870
+ } catch (cleanupErr) {
871
+ log("Terminal cleanup attempt " + attempt + " failed for task " + taskId + ": " + (cleanupErr && cleanupErr.message ? cleanupErr.message : cleanupErr));
872
+ }
873
+ }
874
+ log("Terminal cleanup exhausted for task " + taskId + " — merge-lock lease expiry and orphan sweep are the backstop");
875
+ }
501
876
  async function parkTask(reason) {
502
877
  log("Parking task " + taskId + " for human attention: " + reason);
503
878
  var parkMessage = ("Parked: " + reason).slice(0, 1000);
504
879
  try {
505
880
  await agent(
506
881
  "Park this task for human attention.\n" +
507
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"parktask\", args: " +
508
- JSON.stringify({ task_id: taskId, message: parkMessage }) + ".\n" +
882
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("park-task", { task_id: taskId, message: parkMessage }) + "\n" +
509
883
  "The parked state is the human-attention signal — the dispatcher skips parked tasks.",
510
- { key: "park-task", label: "Parking task for human attention", schema: { type: "object" } }
884
+ { key: "park-task", label: "Parking task for human attention" }
511
885
  );
512
886
  } catch (parkErr) {
513
887
  log("PARK FAILED for task " + taskId + ": " + (parkErr && parkErr.message ? parkErr.message : parkErr) + " — park did not land, reporting failed so the next tick retries");
888
+ await terminalCleanup();
514
889
  return { status: "failed", task_id: taskId, reason: "park failed: " + reason, park_failed: true };
515
890
  }
891
+ await terminalCleanup();
516
892
  return { status: "parked", task_id: taskId, reason: reason };
517
893
  }
518
894
  let i = startStepIndex;
@@ -550,8 +926,8 @@ while (i < STEPS.length) {
550
926
  // re-launches the step with the new project's config.
551
927
  if (LAUNCH_PROJECT_ID) {
552
928
  const projectCheck = await agent(
553
- "Read this task's current project from the dashboard.\n" +
554
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getstate\", args: { \"events_limit\": 1 }.\n" +
929
+ "Read this task's current project from the crew API.\n" +
930
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("get-state", { events_limit: 1 }) + "\n" +
555
931
  "Find the task with id \"" + taskId + "\" in the returned tasks array.\n" +
556
932
  "Return exactly { \"project\": \"<the task's project field, or empty string if absent>\" } and nothing else.",
557
933
  {
@@ -566,14 +942,15 @@ while (i < STEPS.length) {
566
942
  log(abortMessage);
567
943
  await agent(
568
944
  "Abort the stale run and remove its worktree from the old project's repo.\n" +
569
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
570
- "{ \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + REWORK_STEP + "\", \"status\": \"failed\", " +
571
- "\"notes\": " + JSON.stringify(abortMessage + " Rebuild from the Map session notes in the task's event history.") + " }.\n" +
572
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
573
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"identity\": \"" + step.identity + "\", \"message\": " + JSON.stringify(abortMessage) + " }.\n" +
945
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
946
+ task_id: taskId,
947
+ session: { task_id: taskId, identity: step.identity, step: REWORK_STEP, status: "failed",
948
+ notes: abortMessage + " Rebuild from the Map session notes in the task's event history." },
949
+ event: { task_id: taskId, type: "failed", identity: step.identity, message: abortMessage }
950
+ }) + "\n" +
574
951
  "Then run: "+ LIFECYCLE_ENV + " cleanup " + taskId + "\n" +
575
952
  "The cleanup output should contain CLEANUP.",
576
- { key: "abort-project-change", label: "Aborting stale run (project changed)", schema: { type: "object" } }
953
+ { key: "abort-project-change", label: "Aborting stale run (project changed)" }
577
954
  );
578
955
  return { status: "failed", task_id: taskId, reason: abortMessage };
579
956
  }
@@ -614,7 +991,7 @@ while (i < STEPS.length) {
614
991
  "Release the merge lock and clean up without publishing.\n" +
615
992
  "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
616
993
  "If the output contains DEPLOYED, the lock is released and the worktree is cleaned up.",
617
- { key: attemptKey("publish-skip-cleanup", totalReworkCount), label: "Skipping Publish (no target)", schema: { type: "object" } }
994
+ { key: attemptKey("publish-skip-cleanup", totalReworkCount), label: "Skipping Publish (no target)" }
618
995
  );
619
996
  i++;
620
997
  continue;
@@ -639,7 +1016,7 @@ while (i < STEPS.length) {
639
1016
  "Release the merge lock and clean up without publishing.\n" +
640
1017
  "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
641
1018
  "If the output contains DEPLOYED, the lock is released and the worktree is cleaned up.",
642
- { key: attemptKey("publish-skip-release-no", totalReworkCount), label: "Skipping Publish (release: no)", schema: { type: "object" } }
1019
+ { key: attemptKey("publish-skip-release-no", totalReworkCount), label: "Skipping Publish (release: no)" }
643
1020
  );
644
1021
  i++;
645
1022
  continue;
@@ -677,11 +1054,12 @@ while (i < STEPS.length) {
677
1054
  // claimed:false and this run stands down as a duplicate.
678
1055
  let activeSessionId;
679
1056
  if (isFirstClaim) {
1057
+ var firstClaimUpdateArgs = { id: taskId, state: "in_progress" };
1058
+ if (WORKFLOW_WAS_NULL && RESOLVED_WORKFLOW) firstClaimUpdateArgs.workflow = RESOLVED_WORKFLOW;
680
1059
  const claimResult = await agent(
681
1060
  "Claim this task for the " + step.name + " step.\n" +
682
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"updatetask\", args: { \"id\": \"" + taskId + "\", \"state\": \"in_progress\"" + CLAIM_WORKFLOW_PERSIST + " }.\n" +
683
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"claimtask\", args:\n" +
684
- "{ \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"notes\": \"" + step.name + " step started\" }.\n" +
1061
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("update-task", firstClaimUpdateArgs) + "\n" +
1062
+ "Then run in shell and return the stdout verbatim:\n" + crewCmd("claim-task", { task_id: taskId, identity: step.identity, step: step.name, notes: step.name + " step started" }) + "\n" +
685
1063
  "Do not interpret the claim response. It already contains an explicit \"claimed\" field — copy it verbatim.\n" +
686
1064
  "Return { claimed: <verbatim>, session_id: \"<...>\" }. If claimed is false there is no session_id; return { claimed: false, session_id: \"\" }.",
687
1065
  {
@@ -702,8 +1080,8 @@ while (i < STEPS.length) {
702
1080
  } else {
703
1081
  const claimResult = await agent(
704
1082
  "Claim a session for this task step.\n" +
705
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"claimtask\", args:\n" +
706
- "{ \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"notes\": \"" + step.name + " step started" + (totalReworkCount > 0 ? " (rework #" + totalReworkCount + ")" : "") + "\" }.\n" +
1083
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("claim-task", { task_id: taskId, identity: step.identity, step: step.name,
1084
+ notes: step.name + " step started" + (totalReworkCount > 0 ? " (rework #" + totalReworkCount + ")" : "") }) + "\n" +
707
1085
  "Return the session_id from the response.",
708
1086
  {
709
1087
  key: "claim-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : "") + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""),
@@ -740,25 +1118,41 @@ while (i < STEPS.length) {
740
1118
  log("Capture skipped for task " + taskId + " — " + (capExp !== "yes" ? "not experiential" : "publish target is not artifact"));
741
1119
  await agent(
742
1120
  "Update the session and log the event.\n" +
743
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
744
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"completed\", \"notes\": \"Capture skipped — not an experiential artifact task\" }.\n" +
745
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
746
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"identity\": \"" + step.identity + "\", \"message\": \"Capture completed by " + step.identity + "\" }.",
747
- { key: "record-Capture" + bounceSuffix, label: "Recording Capture result", schema: { type: "object" } }
1121
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
1122
+ task_id: taskId,
1123
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name, status: "completed", notes: "Capture skipped — not an experiential artifact task" },
1124
+ event: { task_id: taskId, type: "completed", identity: step.identity, message: "Capture completed by " + step.identity }
1125
+ }),
1126
+ { key: "record-Capture" + bounceSuffix, label: "Recording Capture result" }
748
1127
  );
749
1128
  i++;
750
1129
  continue;
751
1130
  }
752
1131
  var capStatus = await baselineStatus();
753
- if (capStatus.baseline_found) {
754
- log("Capture: baseline evidence already recorded for task " + taskId + " (" + capStatus.baseline_kind + ")");
1132
+ // Stale-decision guard: a "baseline: none (visual protocol unavailable)"
1133
+ // note is only durable while the protocol is unavailable. When
1134
+ // VISUAL_PROTOCOL_AVAILABLE is true, that old decision no longer
1135
+ // stands — fall through to the request path for a fresh capture
1136
+ // attempt. Exact-string trim comparison against the workflow's own
1137
+ // written message (explicit state, never English matching).
1138
+ var baselineLatestMessage = ("baseline: " + capStatus.baseline_kind + capStatus.baseline_refs).trim();
1139
+ var baselineStale = VISUAL_PROTOCOL_AVAILABLE && baselineLatestMessage === "baseline: none (visual protocol unavailable)";
1140
+ if (capStatus.baseline_found && !baselineStale) {
1141
+ var evidenceN = capStatus.evidence_count + 1;
1142
+ var carryNote = "baseline: " + capStatus.baseline_kind + " (#" + evidenceN + " carries forward prior:" + capStatus.baseline_refs + ")";
1143
+ log("Capture: baseline evidence already recorded for task " + taskId + " (" + capStatus.baseline_kind + ") — logging per-attempt carry-forward note (evidence #" + evidenceN + ")");
755
1144
  await agent(
756
- "Update the session and log the event.\n" +
757
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
758
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"completed\", \"notes\": " + JSON.stringify("Baseline evidence already recorded: " + capStatus.baseline_kind + " " + capStatus.baseline_refs) + " }.\n" +
759
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
760
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"identity\": \"" + step.identity + "\", \"message\": \"Capture completed by " + step.identity + "\" }.",
761
- { key: "record-Capture" + bounceSuffix, label: "Recording Capture result", schema: { type: "object" } }
1145
+ "Log the per-attempt baseline carry-forward note, then record the phase.\n" +
1146
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("log-event", {
1147
+ task_id: taskId, type: "note", identity: step.identity, message: carryNote
1148
+ }) + "\n" +
1149
+ "Then run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
1150
+ task_id: taskId,
1151
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name, status: "completed",
1152
+ notes: "Baseline evidence already recorded: " + capStatus.baseline_kind + " " + capStatus.baseline_refs + " (evidence #" + evidenceN + ")" },
1153
+ event: { task_id: taskId, type: "completed", identity: step.identity, message: "Capture completed by " + step.identity }
1154
+ }),
1155
+ { key: "record-Capture" + bounceSuffix, label: "Recording Capture result" }
762
1156
  );
763
1157
  i++;
764
1158
  continue;
@@ -768,13 +1162,18 @@ while (i < STEPS.length) {
768
1162
  log("Capture: baseline capture unavailable after 2 requests for task " + taskId + " — recording baseline:none");
769
1163
  await agent(
770
1164
  "Record that no baseline was capturable.\n" +
771
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
772
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"note\", \"identity\": \"" + step.identity + "\", \"message\": \"baseline: none (capture unavailable after 2 attempts)\" }.\n" +
773
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
774
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"completed\", \"notes\": \"baseline: none — final QA judges on rubric alone\" }.\n" +
775
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
776
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"identity\": \"" + step.identity + "\", \"message\": \"Capture completed by " + step.identity + "\" }.",
777
- { key: "record-Capture-none" + bounceSuffix, label: "Recording baseline: none", schema: { type: "object" } }
1165
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("log-event", {
1166
+ task_id: taskId, type: "note", identity: step.identity,
1167
+ message: "baseline: none (capture unavailable after 2 attempts)"
1168
+ }) + "\n" +
1169
+ "Then run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
1170
+ task_id: taskId,
1171
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
1172
+ status: "completed", notes: "baseline: none — final QA judges on rubric alone" },
1173
+ event: { task_id: taskId, type: "completed", identity: step.identity,
1174
+ message: "Capture completed by " + step.identity }
1175
+ }),
1176
+ { key: "record-Capture-none" + bounceSuffix, label: "Recording baseline: none" }
778
1177
  );
779
1178
  i++;
780
1179
  continue;
@@ -782,12 +1181,36 @@ while (i < STEPS.length) {
782
1181
  log("Capture: requesting baseline capture (attempt " + attemptN + ") for task " + taskId);
783
1182
  await agent(
784
1183
  "Request the baseline capture and record the request.\n" +
785
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
786
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"note\", \"identity\": \"" + step.identity + "\", \"message\": \"baseline: requested (attempt " + attemptN + ")\" }.\n" +
787
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
788
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"failed\", \"notes\": " + JSON.stringify("Baseline capture requested (attempt " + attemptN + ") — parent protocol: run the baseline capture protocol in docs/visual-verdict.md, then re-queue the task at Map. The Capture step re-checks baseline evidence when re-run.") + " }.",
789
- { key: "record-Capture-request" + bounceSuffix, label: "Recording baseline capture request", schema: { type: "object" } }
1184
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("log-event", {
1185
+ task_id: taskId, type: "note", identity: step.identity,
1186
+ message: "baseline: requested (attempt " + attemptN + ")"
1187
+ }) + "\n" +
1188
+ "Then run in shell and return the stdout verbatim:\n" + crewCmd("upsert-session", {
1189
+ id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name, status: "failed",
1190
+ notes: "Baseline capture requested (attempt " + attemptN + ") — parent protocol: run the baseline capture protocol in docs/visual-verdict.md, then re-queue the task at Map. The Capture step re-checks baseline evidence when re-run."
1191
+ }),
1192
+ { key: "record-Capture-request" + bounceSuffix, label: "Recording baseline capture request" }
790
1193
  );
1194
+ if (!VISUAL_PROTOCOL_AVAILABLE) {
1195
+ log("Capture: visual protocol not available (VISUAL_PROTOCOL_AVAILABLE=false) — recording baseline:none instead of parking for task " + taskId);
1196
+ await agent(
1197
+ "Record that baseline capture was skipped (protocol unavailable).\\n" +
1198
+ "Run in shell and return the stdout verbatim:\\n" + crewCmd("log-event", {
1199
+ task_id: taskId, type: "note", identity: step.identity,
1200
+ message: "baseline: none (visual protocol unavailable)"
1201
+ }) + "\\n" +
1202
+ "Then run in shell and return the stdout verbatim:\\n" + crewCmd("record-phase", {
1203
+ task_id: taskId,
1204
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
1205
+ status: "completed", notes: "baseline: none — visual protocol unavailable, final QA judges on rubric alone" },
1206
+ event: { task_id: taskId, type: "completed", identity: step.identity,
1207
+ message: "Capture completed by " + step.identity }
1208
+ }),
1209
+ { key: "record-Capture-none-protocol" + bounceSuffix, label: "Recording baseline: none (protocol unavailable)" }
1210
+ );
1211
+ i++;
1212
+ continue;
1213
+ }
791
1214
  return await parkTask("Baseline capture requested (attempt " + attemptN + ") — parent: run the baseline capture protocol in docs/visual-verdict.md, then re-queue the task at Map");
792
1215
  }
793
1216
 
@@ -803,11 +1226,14 @@ while (i < STEPS.length) {
803
1226
  log("Map gate: no baseline evidence for experiential task " + taskId + " — bouncing to Capture");
804
1227
  await agent(
805
1228
  "Record the Map gate bounce.\n" +
806
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
807
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"failed\", \"notes\": \"Map gate bounce: no baseline evidence recorded for this experiential task — no spec was written. Baseline evidence must be captured before the spec.\" }.\n" +
808
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
809
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"identity\": \"" + step.identity + "\", \"message\": \"Map gate bounce baseline evidence missing, returning to Capture\" }.",
810
- { key: "record-Map-bounce" + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""), label: "Recording Map gate bounce", schema: { type: "object" } }
1229
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
1230
+ task_id: taskId,
1231
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
1232
+ status: "failed", notes: "Map gate bounce: no baseline evidence recorded for this experiential task no spec was written. Baseline evidence must be captured before the spec." },
1233
+ event: { task_id: taskId, type: "failed", identity: step.identity,
1234
+ message: "Map gate bounce — baseline evidence missing, returning to Capture" }
1235
+ }),
1236
+ { key: "record-Map-bounce" + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""), label: "Recording Map gate bounce" }
811
1237
  );
812
1238
  mapGateBounceCount++;
813
1239
  i = CAPTURE_INDEX;
@@ -837,9 +1263,10 @@ while (i < STEPS.length) {
837
1263
 
838
1264
  } else if (step.name === "Reproduce") {
839
1265
  instructions = "Reproduce the bug from a user's perspective. You are CODE-BLIND — do NOT read source code.\n" +
840
- "To investigate, use artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\" with action \"getstate\" (args {}) to read current sessions, events, and tasks.\n" +
1266
+ "To investigate, run in shell and read the stdout JSON:\n" + crewCmd("get-state", {}) + "\n" +
1267
+ "This returns current sessions, events, and tasks.\n" +
841
1268
  "Look at session notes in the returned data — check whether multiline content has newlines preserved or runs together.\n" +
842
- "You can also check specific sessions with the getevents action for evidence.\n" +
1269
+ "You can also check a specific task's events with: node " + CREW_API + " --crew-home " + crewHome + " get-events --json '{\"task_id\":\"<the task id>\"}'.\n" +
843
1270
  "Do NOT use artifact_inspect — it is async and will not return results inline.\n" +
844
1271
  "Capture concrete evidence from the data you retrieve.\n" +
845
1272
  "Report your reproduction evidence and steps as plain prose.\n" +
@@ -861,6 +1288,9 @@ while (i < STEPS.length) {
861
1288
  instructions = "STEP 1: Prepare your worktree.\n" +
862
1289
  "Run: "+ LIFECYCLE_ENV + " prepare " + taskId + "\n" +
863
1290
  "If the output says CREATED or REUSED, proceed. If it says ERROR, stop and report the failure clearly.\n\n" +
1291
+ "HEARTBEAT: Start a background heartbeat loop NOW (before STEP 2) to signal you are still alive during this build. Run this once:\n" +
1292
+ "(while node " + CREW_API + " --crew-home " + crewHome + " heartbeat-session --json '{\"id\": \"" + activeSessionId + "\"}' >/dev/null 2>&1; do sleep 900; done) &\n" +
1293
+ "The loop heartbeats every 15 minutes and exits on its own when the session ends. This prevents the dispatcher from mistaking a long build for a dead session and launching a duplicate.\n\n" +
864
1294
  "STEP 2: Edit source files to implement the mapper's spec below.\n" +
865
1295
  (mapperSpec ? "MAPPER'S SPEC (implement exactly this):\n" + mapperSpec + "\n\n" : "") +
866
1296
  "Your working directory: " + WORKTREE_HINT + "/\n" +
@@ -879,7 +1309,7 @@ while (i < STEPS.length) {
879
1309
  "If the task's deliverable is runtime state (a cron definition, scheduler change, or dashboard/config state created outside the repo) and the repository genuinely needs no change, do NOT fabricate a commit: leave the branch with no commits ahead of main and declare `repo_diff: none` in your report, naming the runtime-state deliverable. Otherwise commit your changes normally.\n\n" +
880
1310
  (rejectionNotes ? "This is REWORK after rejection. Address these specific issues:\n" + rejectionNotes + "\n\n" : "") +
881
1311
  "Report back in plain prose: what you built and the outcome." +
882
- (PUBLISH_TYPE === "npm" ? " End your report with the release: and version_bump: lines exactly as specified above — keep them on their own lines, lowercase, unrephrased — then a final line with exactly: VERDICT: PASS if the build is complete, VERDICT: FAIL if it is not." : " End your report with exactly one line: VERDICT: PASS if the build is complete, VERDICT: FAIL if it is not.");
1312
+ (PUBLISH_TYPE === "npm" ? " End your report with the release: and version_bump: lines exactly as specified above — keep them on their own lines, lowercase, unrephrased — then a line `worktree: ` followed by the exact working directory path from above (copy it verbatim \u2014 it must match character-for-character), then a final line with exactly: VERDICT: PASS if the build is complete, VERDICT: FAIL if it is not." : " End your report with a line `worktree: ` followed by the exact working directory path from above (copy it verbatim \u2014 it must match character-for-character), then exactly one line: VERDICT: PASS if the build is complete, VERDICT: FAIL if it is not.");
883
1313
 
884
1314
  } else if (step.name === "Review") {
885
1315
  instructions = "Review independently and cold. You have NOT seen any reasoning from the builder.\nDo NOT access the task dashboard, event log, or any comments. Your review is based solely on the spec and the code.\n\n" +
@@ -915,14 +1345,19 @@ while (i < STEPS.length) {
915
1345
  "R4. Commit the resolution on resolve/" + taskId + ": git add -A && git commit -m \"resolve conflicts: " + taskId + "\".\n" +
916
1346
  "R5. Back in " + REPO_PATH + ": git checkout main && git merge --ff-only resolve/" + taskId + ". This fast-forwards — main has not moved while the lock was held. Then STEP 2 applies: git push origin main. Report the merged commit hash.\n" +
917
1347
  "R6. Clean up: cd " + REPO_PATH + " && git worktree remove --force /tmp/crew-resolve-" + taskId + " && git branch -D resolve/" + taskId + ".\n" +
918
- "ESCALATE — report 'conflict needs human resolution', then end your report with exactly this line: VERDICT: FAIL — when: 3 attempts are exhausted; the conflict touches generated files, migrations, or public API contracts; or 'looks right + checks pass' is not sufficient for any other reason. On escalation, RELEASE THE LOCK so the task can be reworked later: run CREW_REPO=" + REPO_PATH + " " + MERGE_LOCK + " release " + taskId + " (release is keyed on task id; no PID needed). Do NOT run post-deploy on escalation — it would delete the untouched task branch the human still needs.\n" +
1348
+ "ESCALATE — report 'conflict needs human resolution', then end your report with exactly this line: VERDICT: FAIL — when: 3 attempts are exhausted; the conflict touches generated files, migrations, or public API contracts; or 'looks right + checks pass' is not sufficient for any other reason. On escalation, RELEASE THE LOCK so the task can be reworked later: run CREW_HOME=" + crewHome + " CREW_REPO=" + REPO_PATH + " " + MERGE_LOCK + " release " + taskId + " (release is keyed on task id; no PID needed). Do NOT run post-deploy on escalation — it would delete the untouched task branch the human still needs.\n" +
919
1349
  "- If it contains ERROR, something else failed. Report the error, then end your report with exactly this line: VERDICT: FAIL.\n\n" +
920
1350
  "\n" +
921
1351
  "STEP 2: Push the merged main to the remote repository.\n" +
1352
+ "First, refresh the merge lock — a slow push must not let the 600s lease expire under you: " + LIFECYCLE_ENV + LIFECYCLE + " refresh-lock " + taskId + ". If the refresh fails, report 'merge lock lost before push' and end your report with exactly this line: VERDICT: FAIL. Do not push without the lock.\n" +
922
1353
  "Run: cd " + REPO_PATH + " && git push origin main\n" +
923
1354
  "- If the push succeeds, report the merged commit hash.\n" +
924
1355
  "- If the push is rejected as non-fast-forward (the remote has commits not present locally),\n" +
925
- " NEVER force-push. Do not run any --force variant. Report 'git push origin main rejected as non-fast-forward remote main has diverged; manual resolution required' in your notes, then end your report with exactly this line: VERDICT: FAIL.\n\n" +
1356
+ " NEVER force-push. Do not run any --force variant. The lifecycle's `integrate` already reconciled origin/main under the merge lock, so a rejection means the remote advanced after that reconcile recover mechanically while you still hold the lock:\n" +
1357
+ " 1. Run: cd " + REPO_PATH + " && git fetch origin main && git merge --no-edit origin/main -m \"merge: push-time reconcile (" + taskId + ")\".\n" +
1358
+ " 2. If the merge conflicts, abort it (git merge --abort), report 'push-time reconcile conflicted — manual resolution required', then end your report with exactly this line: VERDICT: FAIL.\n" +
1359
+ " 3. If it merges cleanly, retry the push exactly once: git push origin main. If the second push still rejects, report 'push rejected twice as non-fast-forward', then end your report with exactly this line: VERDICT: FAIL.\n" +
1360
+ " 4. If the retry succeeds, report the merged commit hash.\n\n" +
926
1361
  "Report back in plain prose — what happened at each step — and end your report with exactly one line: VERDICT: PASS or VERDICT: FAIL.";
927
1362
 
928
1363
  } else if (step.name === "Publish") {
@@ -956,15 +1391,22 @@ while (i < STEPS.length) {
956
1391
  // provenance was stamped — prose-trusted side effects, the same failure
957
1392
  // class as the npm double-skip (bb739316). The npm path already runs one
958
1393
  // deterministic script; the artifact path now has the same shape. Lock
959
- // refresh, rebuild trigger, build-completion poll, provenance stamp, and
960
- // post-deploy are narrow schema'd bookkeeping calls owned by the
961
- // workflow — the work agent reports on the mechanical outcome and
962
- // cannot skip what it never owned. Any step failing parks with an
963
- // honest, step-specific reason (fail-closed). The post-hoc
964
- // getprovenance-vs-HEAD verification below stays as the final gate.
1394
+ // refresh, rebuild trigger, build-completion poll, and post-deploy are
1395
+ // narrow schema'd bookkeeping calls owned by the workflow — the work
1396
+ // agent reports on the mechanical outcome and cannot skip what it never
1397
+ // owned. Any step failing parks with an honest, step-specific reason
1398
+ // (fail-closed). There is deliberately NO workflow-side provenance
1399
+ // stamp: the builder's applied-report is circular (canary run 8,
1400
+ // 2026-09-11), so the stamp moved to the parent — after the build
1401
+ // lands, the workflow triggers an independent artifact_inspect
1402
+ // read-back, records the session completed, and parks with
1403
+ // "publish: verification-requested". The parent stamps provenance only
1404
+ // after the read-back confirms the content (docs/publish-verification.md);
1405
+ // QA's provenance check enforces the stamp mechanically.
965
1406
  var artifactPublish = null;
966
1407
  var publishLockRefreshed = false;
967
1408
  var publishSkippedNoLock = false;
1409
+ var publishBuildLanded = false; // true once the artifact build poll completes: content exists to verify; the provenance stamp is deferred to the parent (docs/publish-verification.md)
968
1410
  try {
969
1411
  // STEP 0 (mechanical): read the merge-lock state explicitly — never
970
1412
  // infer it from prose. An empty-diff Integrate (MERGED_EMPTY)
@@ -987,31 +1429,297 @@ while (i < STEPS.length) {
987
1429
  }
988
1430
  publishLockRefreshed = true;
989
1431
  }
990
- // STEP 1 (mechanical): trigger the rebuild with one narrow call.
1432
+ // STEP 1 (mechanical): carry the merged change to the artifact
1433
+ // builder. The builder's source tree is NOT the crew's repo —
1434
+ // canary run 4 (2026-09-11) proved it: Publish asked for "rebuild
1435
+ // from current source. Do not modify any source files" and the
1436
+ // builder rebuilt a stale copy predating the canary's changes, then
1437
+ // the workflow stamped the new commit hash on the stale build.
1438
+ // Provenance fiction; all eight phases passed. The merge diff is
1439
+ // embedded in the edit request; the builder applies it to its own
1440
+ // tree and reports the applied changes; the workflow verifies the
1441
+ // report matches the diff BEFORE stamping provenance. A mismatch
1442
+ // parks without stamping — the stamp must never certify a build
1443
+ // whose content was not verified.
991
1444
  // Skipped entirely when no lock was held — nothing merged, nothing
992
1445
  // to ship.
993
1446
  if (!publishSkippedNoLock) {
994
- // (below) the rebuild trigger, bounded poll, and provenance stamp
995
- // agent only makes the artifact_edit call and reports whether it was
996
- // accepted no prose claim to trust. If the artifact tool namespace
1447
+ // (below) the diff computation, rebuild trigger, application
1448
+ // verification, bounded poll, and provenance stamp. The builder
1449
+ // only makes the artifact_edit call and reports the applied
1450
+ // changes — no prose claim to trust. If the artifact tool namespace
997
1451
  // is missing from this child it reports honestly and the workflow
998
1452
  // retries once with a fresh key (bounded); anything else parks.
1453
+ var diffResult = await agent(
1454
+ "Run: cd " + REPO_PATH + " && git rev-parse HEAD && echo '---PARENT---' && git rev-parse HEAD^1 && echo '---DIFF---' && git diff HEAD^1 HEAD && echo '---NAMES---' && git diff-tree --no-commit-id --name-only -r HEAD\n" +
1455
+ "Return JSON { \"commit\": \"<HEAD trimmed>\", \"parent\": \"<HEAD^1 trimmed>\", \"diff\": \"<raw unified diff, may be multi-line>\", \"files\": \"<newline-separated paths>\" } and nothing else.",
1456
+ { key: attemptKey("publish-artifact-diff-" + taskId, totalReworkCount), label: "Computing merged diff for publish",
1457
+ schema: { type: "object", properties: { commit: { type: "string" }, parent: { type: "string" }, diff: { type: "string" }, files: { type: "string" } }, required: ["commit", "diff"] } }
1458
+ );
1459
+ var mergeCommitForPublish = (diffResult.commit || "").trim();
1460
+ var mergeParentForPublish = (diffResult.parent || "").trim();
1461
+ var mergeDiff = diffResult.diff || "";
1462
+ if (!mergeDiff.trim()) {
1463
+ return await parkTask("Publish diff is empty for commit " + (mergeCommitForPublish || "unknown") + " — a merge lock was held but there is no change to carry. Human attention needed.");
1464
+ }
1465
+ if (/^Binary files /m.test(mergeDiff)) {
1466
+ return await parkTask("Publish diff contains binary files — the text diff transport cannot carry them. Human attention needed.");
1467
+ }
1468
+ if (/^rename from /m.test(mergeDiff)) {
1469
+ return await parkTask("Publish diff contains a rename — the diff transport cannot carry renames. Human attention needed.");
1470
+ }
1471
+ var mergeDiffLines = mergeDiff.split("\n").length;
1472
+ if (mergeDiffLines > 200) {
1473
+ return await parkTask("Publish diff is " + mergeDiffLines + " lines (budget 200) — too large for the diff transport. Human attention needed.");
1474
+ }
1475
+ var expectedChanges = parseUnifiedDiff(mergeDiff);
1476
+ if (expectedChanges.length === 0) {
1477
+ return await parkTask("Publish diff parsed to zero files for commit " + (mergeCommitForPublish || "unknown") + " — cannot verify application. Human attention needed.");
1478
+ }
1479
+ // Pre-publish base observation (diagnostic, 2026-09-12): the builder
1480
+ // applies the diff to its own source tree, whose base state is
1481
+ // unrecorded. Compute the trustworthy expected base — the sha256 of
1482
+ // each touched file at the merge parent commit — so the builder's
1483
+ // self-reported pre-edit hashes (see buildPreHashInstruction) can be
1484
+ // compared against it. Observation only: a mismatch is logged loudly
1485
+ // but never parks. The observation tells us what the publish actually
1486
+ // reads, so the subsequent fix can require the right base.
1487
+ var expectedBaseHashes = {};
1488
+ try {
1489
+ // Shell-quote helper (no regex-with-quote: the test parser does not
1490
+ // understand regex literals containing quotes).
1491
+ var sq = function(s) { return "'" + String(s).split("'").join("'\\''") + "'"; };
1492
+ var baseHashResult = await agent(
1493
+ "Run: cd " + REPO_PATH + " && parent=" + sq(mergeParentForPublish) + " && for f in " + expectedChanges.map(function(f) { return sq(f.path); }).join(" ") + "; do printf '%s:' \"$f\"; git show \"$parent:$f\" 2>/dev/null | sha256sum | cut -d' ' -f1; done\n" +
1494
+ "Return JSON { \"hashes\": \"<newline-separated <path>:<sha256> lines, empty hash means the file is new in this diff>\" } and nothing else.",
1495
+ { key: attemptKey("publish-base-hashes-" + taskId, totalReworkCount), label: "Computing expected base content hashes",
1496
+ schema: { type: "object", properties: { hashes: { type: "string" } }, required: ["hashes"] } }
1497
+ );
1498
+ (baseHashResult.hashes || "").split("\n").forEach(function(line) {
1499
+ var m = /^([^:]+):([0-9a-f]*)$/.exec(line.trim());
1500
+ if (m) expectedBaseHashes[m[1]] = m[2] || "NEW-FILE";
1501
+ });
1502
+ log("Publish expected base hashes for task " + taskId + " (merge parent " + (mergeParentForPublish || "unknown").slice(0, 12) + "): " + JSON.stringify(expectedBaseHashes));
1503
+ } catch (e) {
1504
+ log("Publish expected base hash computation failed for task " + taskId + " (non-fatal, observation degraded): " + (e && e.message ? e.message : e));
1505
+ }
999
1506
  var rebuildPrompt =
1000
1507
  "Call artifact_edit with slug \"" + PUBLISH_SLUG + "\" and verbatim_request:\n" +
1001
- "'Rebuild the application from current source. Do not modify any source files just rebuild and deploy what is on disk.'\n" +
1002
- "If the artifact_edit tool is not available in this session, do NOT improvise — return { \"edit_started\": false, \"error\": \"artifact_edit unavailable\" }.\n" +
1003
- "Make no other calls. Return JSON { \"edit_started\": <true if the edit was accepted, false otherwise>, \"error\": \"<details or empty string>\" } and nothing else.";
1508
+ "'Apply the following change to your source tree, then rebuild and deploy.\n" +
1509
+ "\n" +
1510
+ "UNIFIED DIFF (relative to your source tree):\n" +
1511
+ "```diff\n" + mergeDiff + "\n```\n" +
1512
+ "\n" +
1513
+ "Rules:\n" +
1514
+ "- For each file in the diff, apply its hunks to the same path in your source tree (use git apply or equivalent).\n" +
1515
+ "- For a new file (--- /dev/null), create it with the added (+) lines as its full content.\n" +
1516
+ "- For a deleted file (+++ /dev/null), delete it.\n" +
1517
+ "- If any hunk does not apply cleanly, STOP and report the failure — do not improvise or skip hunks.\n" +
1518
+ "- Do not make any other source changes.\n" +
1519
+ "- After applying, rebuild and deploy.\n" +
1520
+ "- Report, for each file you changed: its path, the exact lines you added, and the exact lines you removed.\n" +
1521
+ buildPreHashInstruction(expectedChanges) + "'\n" +
1522
+ ARTIFACT_LOAD_PREAMBLE +
1523
+ "If artifact_edit is still not available after the load, do NOT improvise — return { \"edit_started\": false, \"error\": \"artifact_tools missing after load\", \"applied\": [] }.\n" +
1524
+ "Make no other calls. Return JSON { \"edit_started\": <true if the edit was accepted, false otherwise>, \"error\": \"<details or empty string>\", \"applied\": [{\"path\": \"<file path>\", \"added\": [\"<added lines>\"], \"removed\": [\"<removed lines>\"]}], \"pre_hashes\": {\"<file path>\": \"<sha256 of that file's content BEFORE you applied the diff, or \"MISSING\">\"} } and nothing else.";
1004
1525
  var rebuildSchema =
1005
- { type: "object", properties: { edit_started: { type: "boolean" }, error: { type: "string" } }, required: ["edit_started"] };
1006
- var rebuildTrigger = await agent(rebuildPrompt,
1007
- { key: attemptKey("publish-artifact-rebuild-" + taskId, totalReworkCount), label: "Triggering artifact rebuild", schema: rebuildSchema });
1008
- if (!rebuildTrigger.edit_started && rebuildTrigger.error === "artifact_edit unavailable") {
1009
- log("Publish rebuild trigger: artifact_edit unavailable — one bounded retry with a fresh key");
1526
+ { type: "object",
1527
+ properties: {
1528
+ edit_started: { type: "boolean" },
1529
+ error: { type: "string" },
1530
+ applied: {
1531
+ type: "array",
1532
+ items: {
1533
+ type: "object",
1534
+ properties: {
1535
+ path: { type: "string" },
1536
+ added: { type: "array", items: { type: "string" } },
1537
+ removed: { type: "array", items: { type: "string" } }
1538
+ },
1539
+ required: ["path", "added", "removed"]
1540
+ }
1541
+ },
1542
+ pre_hashes: {
1543
+ type: "object",
1544
+ description: "Diagnostic (2026-09-12): sha256 of each touched file's content BEFORE the builder applied the diff, as reported by the builder. Compared against the workflow-computed expected base hashes (merge parent) — observation only, never gating."
1545
+ }
1546
+ },
1547
+ required: ["edit_started", "applied"] };
1548
+ var rebuildTrigger = null;
1549
+ var rebuildReportMissing = false; // true if the edit went through but the agent returned no applied report (structured-output failure) — the smoke-check is skipped; the parent's independent read-back is the verification
1550
+ // The trigger key of the attempt that last ran, for the publish ledger.
1551
+ // Minted once here (not re-minted per use site) so the ledger always
1552
+ // records the exact key that was issued — and so a re-minted duplicate
1553
+ // can never drift from it.
1554
+ var rebuildAttemptKey = attemptKey("publish-artifact-rebuild-" + taskId, totalReworkCount);
1555
+ // The artifact build's agent_id, captured from artifact_status when the
1556
+ // trigger's outcome is ambiguous (structured-output failure). The
1557
+ // agent_id is the artifact system's in-flight correlation ID (not durable post-completion)
1558
+ // (research 2026-09-12): artifact.edit returns pending_init with NO
1559
+ // agent_id, but artifact_status exposes build.agent_id immediately
1560
+ // after acceptance, stable across polls. Recorded in the ledger so an
1561
+ // ambiguous attempt correlates to the exact builder run; null when no
1562
+ // build was ever observed.
1563
+ var rebuildAgentId = null;
1564
+ // The builder's applied-report is an observation, not a gate
1565
+ // (2026-09-12, task 23ca8f3f): computed once the trigger outcome is
1566
+ // known, logged loudly, never a park.
1567
+ var publishAppliedObservation = null; // "match" | "mismatch: <reason>" | "missing-report" — observation only, never a park
1568
+ try {
1010
1569
  rebuildTrigger = await agent(rebuildPrompt,
1011
- { key: attemptKey("publish-artifact-rebuild-" + taskId + "-retry1", totalReworkCount), label: "Triggering artifact rebuild (retry)", schema: rebuildSchema });
1570
+ { key: rebuildAttemptKey, label: "Triggering artifact rebuild", schema: rebuildSchema });
1571
+ } catch (rebuildErr) {
1572
+ // Structured-output failure (canary run 9, 2026-09-11): the agent
1573
+ // called artifact_edit (tool_call_count > 0) but returned prose
1574
+ // instead of JSON. The side effect may have happened — the outcome
1575
+ // is UNKNOWN, not "did not go through". The old code asked a child
1576
+ // for derived booleans and retried on all-false; that check issued
1577
+ // the DUPLICATE artifact_edit on 2026-09-12.
1578
+ //
1579
+ // Build-ID research (2026-09-12) corrected the model: artifact.edit
1580
+ // returns pending_init with NO agent_id, but artifact_status exposes
1581
+ // the build's agent_id (the artifact system's durable build
1582
+ // identifier, stable across polls) immediately after acceptance.
1583
+ // So the recovery no longer asks the child to derive booleans —
1584
+ // the layer where the 2026-09-12 signal was lost. It reads the RAW
1585
+ // build object and extracts build.agent_id mechanically in the
1586
+ // workflow script. An observed agent_id is positive evidence the
1587
+ // edit went through; no build after a bounded poll is still
1588
+ // inconclusive (unknown), never proof the edit failed. Mechanical
1589
+ // rule: never blind-retry on unknown — record the attempt and park
1590
+ // fail-closed; correlate via the ledger, never by re-issuing.
1591
+ log("Publish rebuild trigger: structured-output failure (" + (rebuildErr && rebuildErr.message ? rebuildErr.message : rebuildErr) + ") — checking build state before deciding; outcome unknown until state confirms it");
1592
+ var buildState = null;
1593
+ var buildStateFailed = false;
1594
+ try {
1595
+ buildState = await agent(
1596
+ ARTIFACT_LOAD_PREAMBLE +
1597
+ "Call artifact_status with slug \"" + PUBLISH_SLUG + "\".\n" +
1598
+ "Poll up to 3 times, about 20 seconds apart, until the response shows a build (the \"build\" value is an object, not null). " +
1599
+ "Return the raw \"build\" value verbatim as JSON — the build object exactly as returned, with its agent_id, operation, status, and any other fields untouched. " +
1600
+ "Do not summarize, interpret, or derive booleans from it. " +
1601
+ "If no build appears after 3 polls, return null. " +
1602
+ "Return JSON { \"build\": <the raw build object or null> } and nothing else.",
1603
+ { key: attemptKey("publish-artifact-buildcheck-" + taskId, totalReworkCount), label: "Reading artifact build state after trigger failure",
1604
+ schema: { type: "object", properties: { build: { type: ["object", "null"] } }, required: ["build"] } }
1605
+ );
1606
+ } catch (buildCheckErr) {
1607
+ buildStateFailed = true;
1608
+ log("Publish rebuild trigger: build-state check itself failed (" + (buildCheckErr && buildCheckErr.message ? buildCheckErr.message : buildCheckErr) + ") — treating the outcome as unknown");
1609
+ }
1610
+ var acceptedAgentId = (buildState && buildState.build && typeof buildState.build.agent_id === "string" && buildState.build.agent_id) || null;
1611
+ if (!buildStateFailed && acceptedAgentId) {
1612
+ // The edit went through — the agent just failed to return JSON.
1613
+ // The build's agent_id is positive evidence: it appears in
1614
+ // artifact_status immediately after our accepted edit (pending_init
1615
+ // acceptance is followed by a visible build with a stable agent_id,
1616
+ // per the 2026-09-12 research). No applied report to smoke-check;
1617
+ // the parent's independent read-back (docs/publish-verification.md)
1618
+ // is the real verification, not the circular applied-report. The
1619
+ // agent_id is recorded in the ledger so this attempt correlates to
1620
+ // the exact builder run, not just commit + attempt key.
1621
+ log("Publish rebuild trigger: artifact_status shows build " + acceptedAgentId + " for slug " + PUBLISH_SLUG + " — the edit went through despite the structured-output failure. Skipping applied-report smoke-check; parent read-back is the verification.");
1622
+ rebuildTrigger = { edit_started: true, error: "", applied: null };
1623
+ rebuildReportMissing = true;
1624
+ rebuildAgentId = acceptedAgentId;
1625
+ } else {
1626
+ // No build observed — but that proves nothing (a fast-completing
1627
+ // build can finish between polls, or the check itself failed). The
1628
+ // outcome is UNKNOWN. No retry: re-issuing the edit here duplicated
1629
+ // it on 2026-09-12. Record the attempt durably and park fail-closed;
1630
+ // correlate via the ledger, never by guessing from a blind poll.
1631
+ log("Publish rebuild trigger: no build observed after structured-output failure — outcome UNKNOWN. Recording the attempt and parking fail-closed; no blind retry.");
1632
+ await recordPublishLedger({
1633
+ commit: mergeCommitForPublish,
1634
+ attempt: rebuildAttemptKey,
1635
+ agent_id: null,
1636
+ applied_report: null,
1637
+ outcome: "unknown",
1638
+ detail: "structured-output failure on rebuild trigger; build-state poll saw no build (or the check itself failed); edit may have been accepted as pending_init"
1639
+ }, totalReworkCount);
1640
+ return await parkTask("Publish outcome unknown: the rebuild trigger's child did not return JSON, and the follow-up build-state poll could not observe a build for slug " + PUBLISH_SLUG + ". The edit may have been accepted as pending_init, so no retry was issued — a blind retry duplicated the edit on 2026-09-12. The attempt is recorded in the publish ledger at " + crewHome + "/.publish-ledger/" + PUBLISH_SLUG + ".jsonl (commit " + String(mergeCommitForPublish || "unknown").slice(0, 12) + "). Correlate the accepted edit via the ledger and the builder's eventual completion before re-driving Publish. Fail-closed.");
1641
+ }
1642
+ }
1643
+ if (!rebuildReportMissing && !rebuildTrigger.edit_started && rebuildTrigger.error === "artifact_tools missing after load") {
1644
+ log("Publish rebuild trigger: artifact_tools missing after load — one bounded retry with a fresh key");
1645
+ rebuildTrigger = await agent(rebuildPrompt,
1646
+ { key: attemptKey("publish-artifact-rebuild-" + taskId + "-retry2", totalReworkCount), label: "Triggering artifact rebuild (retry)", schema: rebuildSchema });
1647
+ rebuildAttemptKey = attemptKey("publish-artifact-rebuild-" + taskId + "-retry2", totalReworkCount);
1648
+ }
1649
+ // Durable publish-attempt ledger: record the trigger outcome while the
1650
+ // attempt key and commit are in scope. Every attempt lands here with
1651
+ // its outcome — submitted, rejected, or unknown (unknown is recorded
1652
+ // at the park site above). A later run or human matches commit hash +
1653
+ // attempt key against the builder's eventual completion.
1654
+ if (rebuildTrigger && rebuildTrigger.edit_started) {
1655
+ // Applied-report observation (2026-09-12, task 23ca8f3f): the
1656
+ // builder's applied-report is logged as observation only — it
1657
+ // never parks. The report is derived from the carried diff, so a
1658
+ // "match" certifies nothing (canary run 8); and it has a
1659
+ // demonstrated false-negative mode (applied:[] for a diff the
1660
+ // builder had actually applied). The independent read-back below
1661
+ // plus the parent protocol (docs/publish-verification.md) are the
1662
+ // verification — this block always proceeds to them.
1663
+ publishAppliedObservation = rebuildReportMissing
1664
+ ? "missing-report"
1665
+ : (function () { var c = verifyAppliedChanges(expectedChanges, rebuildTrigger.applied); return c.ok ? "match" : "mismatch: " + c.reason; })();
1666
+ log("Publish applied-report observation for task " + taskId + ": " + publishAppliedObservation + " — observation only, never a park: the applied report is derived from the carried diff and proved unreliable in the false-negative direction (task 23ca8f3f, 2026-09-12: applied:[] for a diff the builder had applied). The independent read-back below plus the parent protocol are the verification.");
1667
+ await recordPublishLedger({
1668
+ commit: mergeCommitForPublish,
1669
+ attempt: rebuildAttemptKey,
1670
+ agent_id: rebuildAgentId,
1671
+ applied_report: publishAppliedObservation,
1672
+ outcome: "submitted",
1673
+ detail: rebuildReportMissing
1674
+ ? "edit confirmed via build-state poll after structured-output failure (build " + (rebuildAgentId || "agent_id unknown") + "); builder applied-report missing"
1675
+ : "edit accepted; builder applied-report received"
1676
+ }, totalReworkCount);
1677
+ } else if (rebuildTrigger) {
1678
+ await recordPublishLedger({
1679
+ commit: mergeCommitForPublish,
1680
+ attempt: rebuildAttemptKey,
1681
+ applied_report: null,
1682
+ outcome: "rejected",
1683
+ detail: "edit not accepted: " + (rebuildTrigger.error || "no error detail")
1684
+ }, totalReworkCount);
1012
1685
  }
1013
1686
  var publishFailure = null;
1014
1687
  if (rebuildTrigger.edit_started) {
1688
+ // STEP 1b (observation only): publishAppliedObservation was
1689
+ // computed and logged above, inside the ledger block — the
1690
+ // builder's applied-report never parks and never blocks the stamp.
1691
+ // Task 23ca8f3f (2026-09-12) proved its false-negative mode:
1692
+ // applied:[] for a diff the builder had actually applied, which
1693
+ // parked a successful publish as unverified. A "match" certifies
1694
+ // nothing either — the report is derived from the carried diff
1695
+ // (canary run 8). The flow proceeds to the build poll and the
1696
+ // independent read-back trigger regardless of what the report
1697
+ // claimed; real verification is the parent's read-back
1698
+ // (docs/publish-verification.md) before the provenance stamp.
1699
+ // Pre-publish base observation (diagnostic, 2026-09-12): compare
1700
+ // the builder's self-reported pre-edit hashes against the
1701
+ // workflow-computed expected base (merge parent). This tells us
1702
+ // what base state the publish actually read. OBSERVATION ONLY —
1703
+ // a mismatch is logged loudly but never parks and never blocks
1704
+ // the stamp. If the tree was dirty or drifted, the evidence is
1705
+ // here; the fix (requiring the right base) comes after we see it.
1706
+ try {
1707
+ var preHashes = (rebuildTrigger && rebuildTrigger.pre_hashes) || {};
1708
+ var baseLines = expectedChanges.map(function(f) {
1709
+ var expected = expectedBaseHashes[f.path];
1710
+ var actual = preHashes[f.path];
1711
+ var expShort = (expected || "UNKNOWN").slice(0, 12);
1712
+ var actShort = String(actual || "NOT-REPORTED").slice(0, 12);
1713
+ var match = (expected !== undefined && actual !== undefined) ? (expected === actual) : "unknown";
1714
+ return " " + f.path + ": expected_base=" + expShort + " builder_pre=" + actShort + " match=" + match;
1715
+ });
1716
+ var anyMismatch = expectedChanges.some(function(f) {
1717
+ return expectedBaseHashes[f.path] !== undefined && preHashes[f.path] !== undefined && expectedBaseHashes[f.path] !== preHashes[f.path];
1718
+ });
1719
+ log("Publish pre-tree base observation for task " + taskId + (anyMismatch ? " — BASE MISMATCH DETECTED (tree was not at the expected merge-parent state when the diff was applied):" : " — base matches expected merge-parent state:") + "\n" + baseLines.join("\n"));
1720
+ } catch (e) {
1721
+ log("Publish pre-tree base observation failed for task " + taskId + " (non-fatal): " + (e && e.message ? e.message : e));
1722
+ }
1015
1723
  // STEP 1b (mechanical): bounded poll for build completion, chunked so
1016
1724
  // the merge-lock lease is refreshed before it can expire. The 600s
1017
1725
  // lease is shorter than the worst-case 10-minute build poll, so the
@@ -1041,7 +1749,7 @@ while (i < STEPS.length) {
1041
1749
  ? attemptKey("publish-artifact-poll-" + taskId, totalReworkCount)
1042
1750
  : attemptKey("publish-artifact-poll-" + taskId + "-c" + chunk, totalReworkCount);
1043
1751
  buildPoll = await agent(
1044
- "Poll artifact_status for slug \"" + PUBLISH_SLUG + "\" until no build is running. Check every 30 seconds, up to 7 checks (3.5 minutes max).\n" +
1752
+ "First call tool_search.load_tool_namespace with paths [\"artifact\"]. Then poll artifact_status for slug \"" + PUBLISH_SLUG + "\" until no build is running. Check every 30 seconds, up to 7 checks (3.5 minutes max).\n" +
1045
1753
  "Return JSON { \"build_done\": <true if no build is running within budget, false on timeout>, \"status\": \"<final status or timeout note>\" } and nothing else.",
1046
1754
  { key: pollKey, label: "Waiting for artifact build to complete (chunk " + chunk + " of 3)",
1047
1755
  schema: { type: "object", properties: { build_done: { type: "boolean" }, status: { type: "string" } }, required: ["build_done"] },
@@ -1053,22 +1761,20 @@ while (i < STEPS.length) {
1053
1761
  buildPoll = { build_done: false, status: (buildPoll && buildPoll.status) || "build still running after the 10.5-minute bounded poll" };
1054
1762
  }
1055
1763
  if (buildPoll.build_done) {
1056
- // STEP 1c (mechanical): stamp provenance from workflow-computed values.
1057
- var provStamp = await agent(
1058
- "Run: cd " + REPO_PATH + " && git rev-parse HEAD — call this SRC.\n" +
1059
- "Run: basename $(readlink " + crewHome + "/current) call this REL.\n" +
1060
- "Run: date -u +%Y-%m-%dT%H:%M:%SZ call this TS.\n" +
1061
- "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"setprovenance\", args:\n" +
1062
- "{ \"source_commit\": \"<SRC trimmed>\", \"crew_release\": \"<REL trimmed>\", \"published_at\": \"<TS trimmed>\", \"task_id\": \"" + taskId + "\" }.\n" +
1063
- "Return JSON { \"stamped\": <true if the setprovenance response contains ok: true, false otherwise>, \"source_commit\": \"<SRC trimmed>\", \"crew_release\": \"<REL trimmed>\", \"published_at\": \"<TS trimmed>\" } and nothing else.",
1064
- { key: attemptKey("publish-artifact-stamp-" + taskId, totalReworkCount), label: "Stamping artifact provenance",
1065
- schema: { type: "object", properties: { stamped: { type: "boolean" }, source_commit: { type: "string" }, crew_release: { type: "string" }, published_at: { type: "string" } }, required: ["stamped", "source_commit", "crew_release", "published_at"] } }
1066
- );
1067
- if (provStamp.stamped) {
1068
- artifactPublish = { source_commit: provStamp.source_commit, crew_release: provStamp.crew_release, published_at: provStamp.published_at };
1069
- } else {
1070
- publishFailure = "Provenance stamp failed after a completed build (source_commit " + (provStamp.source_commit || "unknown") + "). The build landed but is unstamped — fail-closed.";
1071
- }
1764
+ // STEP 1c (mechanical): NO provenance stamp here. Canary run 8
1765
+ // (2026-09-11) proved the stamp cannot certify content: the
1766
+ // builder's applied-report is derived from the carried diff, so
1767
+ // verifyAppliedChanges above is circulara fabricated report
1768
+ // passes by construction, and every phase went green on a hollow
1769
+ // build. The stamp moves to the parent (docs/publish-verification.md):
1770
+ // after an independent artifact_inspect read-back confirms the
1771
+ // artifact's actual content matches the merged diff, the parent
1772
+ // stamps provenance and re-queues; QA's provenance check then
1773
+ // enforces the stamp mechanically, so an unverified publish fails
1774
+ // loudly in QA instead of passing silently here.
1775
+ publishBuildLanded = true;
1776
+ artifactPublish = { source_commit: mergeCommitForPublish, pending_parent_verification: true };
1777
+ log("Publish build landed for task " + taskId + " — provenance stamp deferred to parent content verification");
1072
1778
  } else {
1073
1779
  publishFailure = "Artifact build did not complete within budget: " + (buildPoll.status || "timeout") + ". The publish may or may not have landed — provenance was not stamped.";
1074
1780
  }
@@ -1099,9 +1805,9 @@ while (i < STEPS.length) {
1099
1805
  : " Post-deploy also failed (" + (postDeploy.output || "no output") + ") — worktree and lock state unknown."));
1100
1806
  }
1101
1807
  if (!postDeploy.deployed) {
1102
- return await parkTask("Post-deploy failed after a stamped publish: " + (postDeploy.output || "no output") + ". The publish landed but worktree cleanup and lock release are unknown — human attention needed.");
1808
+ return await parkTask("Post-deploy failed after the artifact build landed: " + (postDeploy.output || "no output") + ". The build may have landed but worktree cleanup and lock release are unknown — human attention needed.");
1103
1809
  }
1104
- log("Deterministic artifact publish completed for task " + taskId + ": provenance at " + artifactPublish.source_commit);
1810
+ log("Deterministic artifact publish completed for task " + taskId + ": build at " + artifactPublish.source_commit + ", provenance PENDING parent content verification");
1105
1811
  }
1106
1812
  } catch (pubErr) {
1107
1813
  // Best-effort cleanup: if the lock was refreshed, try to release it
@@ -1111,8 +1817,7 @@ while (i < STEPS.length) {
1111
1817
  await agent(
1112
1818
  "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
1113
1819
  "Return JSON { \"deployed\": <true if the output contains DEPLOYED, false otherwise> } and nothing else.",
1114
- { key: attemptKey("publish-postdeploy-cleanup-" + taskId, totalReworkCount), label: "Releasing lock after publish failure",
1115
- schema: { type: "object", properties: { deployed: { type: "boolean" } }, required: ["deployed"] } }
1820
+ { key: attemptKey("publish-postdeploy-cleanup-" + taskId, totalReworkCount), label: "Releasing lock after publish failure" }
1116
1821
  );
1117
1822
  } catch (cleanupErr) {
1118
1823
  log("Publish cleanup post-deploy also failed: " + (cleanupErr && cleanupErr.message ? cleanupErr.message : cleanupErr));
@@ -1132,10 +1837,10 @@ while (i < STEPS.length) {
1132
1837
  instructions = "Publish the merged code to the live artifact.\n\n" +
1133
1838
  "The publish was performed deterministically by the workflow before your step — do NOT call artifact_edit, artifact_status, setprovenance, or post-deploy yourself; doing so would trigger a duplicate build or disturb the finalized state. You perform no publish actions.\n\n" +
1134
1839
  "For the change summary, run: cd " + REPO_PATH + " && git log -1 --stat\n\n" +
1135
- "Mechanical outcome (every step succeeded and was verified by the workflow):\n" +
1840
+ "Mechanical outcome (the workflow's mechanical steps; content verification is the parent's, still pending):\n" +
1136
1841
  "- merge lock refreshed: yes\n" +
1137
1842
  "- artifact rebuild triggered and completed: yes\n" +
1138
- "- provenance stamped: yessource_commit " + artifactPublish.source_commit + ", crew_release " + artifactPublish.crew_release + ", published_at " + artifactPublish.published_at + "\n" +
1843
+ "- provenance stamped: NOnot yet, and you must NOT stamp it. The stamp moved to the parent, which stamps it only after an independent content read-back confirms the artifact actually contains the merged change (docs/publish-verification.md). A stamped-but-hollow build is exactly how canary run 8 (2026-09-11) went green on stale content.\n" +
1139
1844
  "- post-deploy finalized: yes (worktree removed, merge lock released)\n\n" +
1140
1845
  "POLICY: The live artifact is rebuilt only in this phase, from the repo. Never use artifact_edit to change the artifact directly — fixes go through the repo and the loop. A source fix is not done until the artifact is rebuilt from it here.\n\n" +
1141
1846
  "The repo push already happened in Integrate — do NOT push to git in this phase.\n\n" +
@@ -1153,7 +1858,7 @@ while (i < STEPS.length) {
1153
1858
  // declared release: yes, QA verifies the registry actually moved. A silent
1154
1859
  // publish skip becomes a loud QA failure with evidence, not a pass.
1155
1860
  var npmPublishCheck = (PUBLISH_TYPE === "npm" && releaseDecision && releaseDecision.release === "yes")
1156
- ? "NPM PUBLISH CHECK: the accepted Build report declared release: yes, so this run's Publish phase must have published — UNLESS it was skipped deterministically on an empty-diff Integrate. Find this task's recorded Publish result: call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getstate\", args: { \"events_limit\": 1 }, then find the session for this task_id with step \"Publish\" (status completed) in the returned sessions array and read its session notes (the Publish agent's summary — event history does NOT carry it).\n" +
1861
+ ? "NPM PUBLISH CHECK: the accepted Build report declared release: yes, so this run's Publish phase must have published — UNLESS it was skipped deterministically on an empty-diff Integrate. Find this task's recorded Publish result: run in shell and return the stdout verbatim:\n" + crewCmd("get-state", { events_limit: 1 }) + "\n, then find the session for this task_id with step \"Publish\" (status completed) in the returned sessions array and read its session notes (the Publish agent's summary — event history does NOT carry it).\n" +
1157
1862
  "CHECK THE SKIP PATH FIRST: if the notes contain a line matching skipped: no-lock-held, Publish was skipped deterministically — Integrate reported MERGED_EMPTY (no commits ahead of main), so no merge lock was taken and there was nothing to ship. Verify the notes contain that skip-marker line and do NOT contain a line matching published: muse-crew@. Do NOT run npm view and do NOT demand registry movement — nothing was supposed to ship. Report 'npm publish check: Publish skipped deterministically (empty-diff Integrate — nothing to ship)' and PASS this check.\n" +
1158
1863
  "Only when the notes contain no skip marker must the publish have landed — run the full verification below.\n" +
1159
1864
  "Extract the line matching TARGET_VERSION=<new-version> computed as <base> + <scope> → <new-version> (the workflow appends it to the Publish notes, so it is always present). If the line is missing, report 'npm publish verification failed: Publish notes did not carry the computed target version', then end your report with exactly this line: VERDICT: FAIL.\n" +
@@ -1163,11 +1868,11 @@ while (i < STEPS.length) {
1163
1868
  instructions = "Final QA testing. You are CODE-BLIND — do NOT read source code.\n" +
1164
1869
  "Public docs (API.md, README, published action schemas) are NOT source code — read them freely, exactly as a user would.\n" +
1165
1870
  "DOCS GATE: If the fix is public-affecting (it alters anything a user or consumer can observe: API actions, parameters, behavior, or errors), verify the public docs describe it. If public docs are missing or stale, report 'public docs missing/stale for [the change]', then end your report with exactly this line: VERDICT: FAIL. QA always fails when public-affecting changes lack public docs. Guide/tutorial gaps are lower priority — file a follow-up task for those instead of failing.\n" +
1166
- "To test, use artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\" with action \"getstate\" (args {}) to read current sessions, events, and tasks.\n" +
1871
+ "To test, run in shell and read the stdout JSON:\n" + crewCmd("get-state", {}) + "\nThis returns current sessions, events, and tasks.\n" +
1167
1872
  "Verify the fix by checking that session notes in the returned data now handle newlines correctly.\n" +
1168
- "You can also check specific data with the getevents action.\n" +
1873
+ "You can also check specific data with: node " + CREW_API + " --crew-home " + crewHome + " get-events --json '{\"task_id\":\"<the task id>\"}'.\n" +
1169
1874
  "Do NOT use artifact_inspect — it is async and will not return results inline.\n" +
1170
- "File follow-up tasks via artifact_invoke_action createtask on slug \"" + DASHBOARD_SLUG + "\" for related issues.\n" +
1875
+ "File follow-up tasks by running in shell:\n" + crewCmd("create-task", { title: "<short title>", description: "<details>", project: "<project id>", workflow: "bugfix", filed_by: "hazel" }) + "\n(substitute the real values for the placeholders).\n" +
1171
1876
  npmPublishCheck +
1172
1877
  "Report your test results as plain prose.\n" +
1173
1878
  "End your report with exactly one line: VERDICT: PASS if testing passes, VERDICT: FAIL if it fails.";
@@ -1182,23 +1887,24 @@ while (i < STEPS.length) {
1182
1887
  "Your VERDICT below covers the MECHANICAL CHECKS only. Do NOT call artifact_inspect.\n\n" +
1183
1888
  "MECHANICAL CHECKS:\n" +
1184
1889
  "DOCS GATE: If the fix is public-affecting (it alters anything a user or consumer can observe: API actions, parameters, behavior, or errors), verify the public docs describe it. If public docs are missing or stale, report 'public docs missing/stale for [the change]', then end your report with exactly this line: VERDICT: FAIL. QA always fails when public-affecting changes lack public docs. Guide/tutorial gaps are lower priority — file a follow-up task for those instead of failing.\n" +
1185
- "To test, use artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\" with action \"getstate\" (args {}) to read current sessions, events, and tasks.\n" +
1890
+ "To test, run in shell and read the stdout JSON:\n" + crewCmd("get-state", {}) + "\nThis returns current sessions, events, and tasks.\n" +
1186
1891
  "Verify the fix by checking that session notes in the returned data now handle newlines correctly.\n" +
1187
- "You can also check specific data with the getevents action.\n" +
1892
+ "You can also check specific data with: node " + CREW_API + " --crew-home " + crewHome + " get-events --json '{\"task_id\":\"<the task id>\"}'.\n" +
1188
1893
  npmPublishCheck +
1189
- "File follow-up tasks via artifact_invoke_action createtask on slug \"" + DASHBOARD_SLUG + "\" for related issues.\n\n" +
1894
+ "File follow-up tasks by running in shell:\n" + crewCmd("create-task", { title: "<short title>", description: "<details>", project: "<project id>", workflow: "bugfix", filed_by: "hazel" }) + "\n(substitute the real values for the placeholders).\n\n" +
1190
1895
  "BASELINE SANITY: in the event history you fetched, the task's note events must contain a message starting with `baseline: captured` or `baseline: none`. If no message starts with either prefix, report 'baseline evidence missing at QA — the Map gate was bypassed', then end your report with exactly this line: VERDICT: FAIL.\n\n" +
1191
1896
  "Report your test results as plain prose.\n" +
1192
1897
  "End your report with exactly one line: VERDICT: PASS if testing passes, VERDICT: FAIL if it fails on the mechanical checks.";
1193
1898
  }
1194
1899
  if (PUBLISH_TYPE === "artifact") {
1195
1900
  instructions = "PROVENANCE CHECK (this project publishes to a dashboard artifact).\n" +
1196
- "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"getprovenance\", args: {}.\n" +
1197
- "If provenance is null, report 'provenance missing publish did not stamp', then end your report with exactly this line: VERDICT: FAIL.\n" +
1901
+ "Provenance is crew-owned state: read it from the Crew API, never from the artifact's own getprovenance action (a different, non-authoritative store).\n" +
1902
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("get-provenance", {}) + "\n" +
1903
+ "If provenance is null, report 'provenance missing — publish did not stamp source/crew release', then end your report with exactly this line: VERDICT: FAIL.\n" +
1198
1904
  "Run: cd " + REPO_PATH + " && git rev-parse HEAD — call this LIVE_HEAD.\n" +
1199
- "Run: test -d " + crewHome + "/releases/<provenance.crew_release> (substitute the real stamped hash; do not run the literal placeholder). If the directory does not exist, report 'provenance mismatch: crew_release [value from getprovenance] not found in release registry', then end your report with exactly this line: VERDICT: FAIL.\n" +
1905
+ "Run: test -d " + crewHome + "/releases/<provenance.crew_release> (substitute the real stamped hash; do not run the literal placeholder). If the directory does not exist, report 'provenance mismatch: crew_release [value from get-provenance] not found in release registry', then end your report with exactly this line: VERDICT: FAIL.\n" +
1200
1906
  "If provenance.source_commit equals LIVE_HEAD, the source check passes.\n" +
1201
- "Otherwise the check is NOT failed yet: post-deploy commits an artifact-builder staging commit (\"rebuild: <task_id>\") AFTER the stamp, so LIVE_HEAD may sit ahead of the stamped commit ONLY IF every commit in between is such a rebuild marker. Verify exactly:\n" +
1907
+ "Otherwise the check is NOT failed yet: the parent stamps provenance AFTER post-deploy (docs/publish-verification.md), and post-deploy may commit an artifact-builder staging commit (\"rebuild: <task_id>\"), so LIVE_HEAD may sit ahead of the stamped commit ONLY IF every commit in between is such a rebuild marker. Verify exactly:\n" +
1202
1908
  "1. Run: cd " + REPO_PATH + " && git merge-base --is-ancestor <provenance.source_commit> LIVE_HEAD && echo ANCESTOR_OK (substitute the real stamped hash and LIVE_HEAD; do not run the literal placeholders). If this command fails, report 'provenance mismatch: stamped source_commit is not an ancestor of live HEAD', then end your report with exactly this line: VERDICT: FAIL.\n" +
1203
1909
  "2. Run: cd " + REPO_PATH + " && git log --format=%s <provenance.source_commit>..LIVE_HEAD (substitute real values). Every subject line MUST start with \"rebuild: \". If any line does not, report 'provenance mismatch: live HEAD moved past the stamped commit with non-rebuild source commits: [paste the offending subject lines]', then end your report with exactly this line: VERDICT: FAIL.\n\n" +
1204
1910
  instructions;
@@ -1212,7 +1918,7 @@ while (i < STEPS.length) {
1212
1918
  var eventPreamble = "";
1213
1919
  if (step.name !== "Review" && step.name !== "Publish") {
1214
1920
  eventPreamble = "CONTEXT: First, fetch this task's event history for background.\n" +
1215
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getevents\", args: { \"task_id\": \"" + taskId + "\" }.\n" +
1921
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("get-events", { task_id: taskId }) + "\n" +
1216
1922
  "The returned events are filtered to this task. They contain notes and decisions from prior phases.\n\n";
1217
1923
  }
1218
1924
 
@@ -1223,13 +1929,14 @@ while (i < STEPS.length) {
1223
1929
  // string. The verdict is still extracted deterministically from the report
1224
1930
  // text by extractVerdict below — never by an agent.
1225
1931
  var workPromptBase =
1932
+ TOOL_CHECK_PREAMBLE +
1226
1933
  "Read the identity file at " + ORCH_PATH + "/identities/" + step.identity + ".md using the read tool, and embody that character fully.\n\n" +
1227
1934
  "## Your Assignment\n\n" +
1228
1935
  "Task: " + taskTitle + "\n" +
1229
1936
  "Task ID: " + taskId + "\n" +
1230
1937
  "Description: " + taskDescription + "\n" +
1231
1938
  "Step: " + step.name + "\n" +
1232
- (step.name !== "Review" ? "Dashboard slug: " + DASHBOARD_SLUG + "\n" : "") +
1939
+ (step.name !== "Review" ? "Crew API: " + CREW_API + "\n" : "") +
1233
1940
  "\n## Instructions\n\n" + eventPreamble + instructions + "\n\n" +
1234
1941
  "CONSTRAINT: Do NOT call logevent or upsertagentsession — the workflow handles all phase tracking after your step completes.\n\n" +
1235
1942
  "Stay in character. Do the work thoroughly.\n\n" +
@@ -1240,7 +1947,8 @@ while (i < STEPS.length) {
1240
1947
  var workAttempts = [];
1241
1948
  for (var workAttempt = 0; workAttempt <= 2; workAttempt++) {
1242
1949
  var workKey = workAttempt === 0 ? workKeyBase : workRetryKey(step.name, (totalReworkCount > 0 ? "-r" + totalReworkCount : ""), workAttempt);
1243
- var retryReason = workAttempt === 0 ? null : (workAttempts[workAttempt - 1].threw ? "discarded" : "empty");
1950
+ var prevAttempt = workAttempt === 0 ? null : workAttempts[workAttempt - 1];
1951
+ var retryReason = workAttempt === 0 ? null : (prevAttempt.threw ? "discarded" : (prevAttempt.outcome === "missing-artifact-tools" ? "no-tools" : (prevAttempt.outcome === "unavailable-shell-transport" ? "no-transport" : "empty")));
1244
1952
  try {
1245
1953
  workerResult = await agent(
1246
1954
  workPromptBase + (workAttempt === 0 ? "" : buildTransportRetryTrailer(step.name, REPO_PATH, taskId, workAttempt, retryReason)),
@@ -1255,6 +1963,22 @@ while (i < STEPS.length) {
1255
1963
  // always fails (regression shipped in ecef136 when Date.now() was
1256
1964
  // removed from this loop).
1257
1965
  if (typeof workerResult === "string" && workerResult.trim()) {
1966
+ // Bug 3472bf36: a worker whose TOOL CHECK reports artifact_tools: missing
1967
+ // (or shell_transport: unavailable) gets a fresh launch - the load is
1968
+ // per-launch - instead of a useless report.
1969
+ var toolSignals = parseToolSignals(workerResult);
1970
+ if (toolSignals.artifactTools === "missing") {
1971
+ workAttempts.push({ threw: false, error: "", outcome: "missing-artifact-tools" });
1972
+ log(step.name + " work agent attempt " + (workAttempt + 1) + " of 3 reported artifact_tools: missing — retrying with a fresh launch");
1973
+ workerResult = null;
1974
+ continue;
1975
+ }
1976
+ if (toolSignals.shellTransport === "unavailable") {
1977
+ workAttempts.push({ threw: false, error: "", outcome: "unavailable-shell-transport" });
1978
+ log(step.name + " work agent attempt " + (workAttempt + 1) + " of 3 reported shell_transport: unavailable — retrying with a fresh launch");
1979
+ workerResult = null;
1980
+ continue;
1981
+ }
1258
1982
  if (workAttempt > 0) log(step.name + " work agent transport retry " + workAttempt + " returned a machine-readable report");
1259
1983
  break;
1260
1984
  }
@@ -1277,11 +2001,13 @@ while (i < STEPS.length) {
1277
2001
  log(step.name + " " + workFailure.notes + " — marking failed for retry");
1278
2002
  await agent(
1279
2003
  "Record work failure.\n" +
1280
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
1281
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"failed\", \"notes\": \"" + workFailure.notes + "\" }.\n" +
1282
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
1283
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"message\": \"" + workFailure.eventMessage + "\" }.",
1284
- { key: "record-block-" + step.name, label: "Recording work failure", schema: { type: "object" } }
2004
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
2005
+ task_id: taskId,
2006
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
2007
+ status: "failed", notes: workFailure.notes },
2008
+ event: { task_id: taskId, type: "failed", message: workFailure.eventMessage }
2009
+ }),
2010
+ { key: "record-block-" + step.name, label: "Recording work failure" }
1285
2011
  );
1286
2012
  return {
1287
2013
  __hatchWorkflowControl: "blocked",
@@ -1315,11 +2041,14 @@ while (i < STEPS.length) {
1315
2041
  log(step.name + " verdict re-ask exhausted — marking failed for retry");
1316
2042
  await agent(
1317
2043
  "Record verdict failure.\n" +
1318
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
1319
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"failed\", \"notes\": \"Worker report had no single unambiguous VERDICT: PASS/FAIL line (bounded re-ask exhausted)\" }.\n" +
1320
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
1321
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"message\": \"" + step.name + " verdict line missing or ambiguous, re-ask exhausted — phase failed, dispatcher will retry\" }.",
1322
- { key: "record-block-" + step.name, label: "Recording verdict failure", schema: { type: "object" } }
2044
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
2045
+ task_id: taskId,
2046
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
2047
+ status: "failed", notes: "Worker report had no single unambiguous VERDICT: PASS/FAIL line (bounded re-ask exhausted)" },
2048
+ event: { task_id: taskId, type: "failed",
2049
+ message: step.name + " verdict line missing or ambiguous, re-ask exhausted — phase failed, dispatcher will retry" }
2050
+ }),
2051
+ { key: "record-block-" + step.name, label: "Recording verdict failure" }
1323
2052
  );
1324
2053
  return {
1325
2054
  __hatchWorkflowControl: "blocked",
@@ -1333,6 +2062,39 @@ while (i < STEPS.length) {
1333
2062
  verdictPassed = verdict.passed;
1334
2063
  }
1335
2064
 
2065
+
2066
+ // Worktree confinement (Build only): the declared worktree path must
2067
+ // match WORKTREE_HINT exactly. A builder that worked in any other
2068
+ // checkout fails the phase here — the dispatcher retries Build under
2069
+ // its consecutive-failure cap, and the retry re-runs prepare against
2070
+ // the configured repo. Missing or mismatched lines fail closed.
2071
+ if (step.name === "Build" && verdictPassed === true) {
2072
+ var wt = extractWorktree(workerText);
2073
+ if (!wt.ok || wt.path !== WORKTREE_HINT) {
2074
+ log("Build worktree confinement failed — declared: " + (wt.ok ? wt.path : "<none>") + ", expected: " + WORKTREE_HINT + " — marking failed for retry");
2075
+ await agent(
2076
+ "Record worktree confinement failure.\n" +
2077
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
2078
+ task_id: taskId,
2079
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
2080
+ status: "failed", notes: "Build declared worktree " + (wt.ok ? wt.path : "<none>") + " — expected " + WORKTREE_HINT + ". The builder worked outside the configured repo checkout; phase failed for retry" },
2081
+ event: { task_id: taskId, type: "failed",
2082
+ message: "Build worktree confinement failed — builder worked outside " + WORKTREE_HINT + ", phase failed, dispatcher will retry" }
2083
+ }),
2084
+ { key: "record-worktree-fail-" + step.name, label: "Recording worktree confinement failure" }
2085
+ );
2086
+ return {
2087
+ __hatchWorkflowControl: "blocked",
2088
+ result: {
2089
+ blocked_reason: "Build worked outside the configured repo checkout",
2090
+ message: "The builder declared worktree " + (wt.ok ? wt.path : "<none>") + " but the task's worktree is " + WORKTREE_HINT + ". The phase is marked failed; the dispatcher will retry Build against the configured repo.",
2091
+ task_id: taskId
2092
+ }
2093
+ };
2094
+ }
2095
+ log("Build worktree confinement passed: " + wt.path);
2096
+ }
2097
+
1336
2098
  // Deterministic closeout: no formatter agent. The verdict is mechanical
1337
2099
  // (extractVerdict above); the summary is the worker's report truncated.
1338
2100
  // For verdict steps passed comes from the verdict; for non-verdict steps
@@ -1427,13 +2189,13 @@ while (i < STEPS.length) {
1427
2189
  // dashboard QA source check).
1428
2190
  try {
1429
2191
  var provRefresh = await agent(
1430
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getprovenance\", args: {}. " +
2192
+ "Run in shell and read the stdout JSON:\n" + crewCmd("get-provenance", {}) + "\n" +
1431
2193
  "If the response has no provenance (null), return JSON { \"refreshed\": false, \"reason\": \"no-record\" } and stop. " +
1432
2194
  "Otherwise run: basename $(readlink " + crewHome + "/current) — call this REL; " +
1433
2195
  "run: date -u +%Y-%m-%dT%H:%M:%SZ — call this TS. " +
1434
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"setprovenance\", args: " +
1435
- "{ \"source_commit\": \"<existing provenance.source_commit>\", \"crew_release\": \"<REL trimmed>\", \"published_at\": \"<TS trimmed>\", \"task_id\": \"" + taskId + "\" }. " +
1436
- "Return JSON { \"refreshed\": <true if the setprovenance response contains ok: true, false otherwise>, \"crew_release\": \"<REL trimmed>\", \"published_at\": \"<TS trimmed>\" } and nothing else.",
2196
+ "Then run in shell: node " + CREW_API + " --crew-home " + crewHome + " set-provenance --json '{\"source_commit\":\"<the existing provenance.source_commit value>\",\"crew_release\":\"<REL>\",\"published_at\":\"<TS>\",\"task_id\":\"" + taskId + "\"}' " +
2197
+ "(substitute the real values; the JSON must be single-quote-wrapped for the shell). " +
2198
+ "Return JSON { \"refreshed\": <true if the set-provenance stdout contains ok: true, false otherwise>, \"crew_release\": \"<REL trimmed>\", \"published_at\": \"<TS trimmed>\" } and nothing else.",
1437
2199
  { key: attemptKey("publish-provenance-refresh-" + taskId, totalReworkCount), label: "Refreshing dashboard provenance after crew release",
1438
2200
  schema: { type: "object", properties: { refreshed: { type: "boolean" }, reason: { type: "string" }, crew_release: { type: "string" }, published_at: { type: "string" } }, required: ["refreshed"] } }
1439
2201
  );
@@ -1454,43 +2216,51 @@ while (i < STEPS.length) {
1454
2216
  } // end: !npmPublishSkipped — a skipped publish has nothing to verify
1455
2217
  }
1456
2218
 
1457
- // Artifact publish verification: the worker cannot self-certify a deploy.
1458
- // The workflow reads the artifact's provenance and confirms it points at the
1459
- // integrated commit. A stale or missing provenance means the publish did not
1460
- // land fail closed, do not trust the worker's prose.
2219
+ // Publish content verification parent-owned (docs/publish-verification.md).
2220
+ // The old block read back the workflow's OWN provenance stamp and compared
2221
+ // it to HEAD: that verifies the stamp, not the content. Canary run 8
2222
+ // (2026-09-11) passed it with a hollow build the stamp was honest, the
2223
+ // artifact was stale, all eight phases green. The stamp now moves to the
2224
+ // parent: trigger an independent artifact_inspect read-back of the changed
2225
+ // regions here; the parent stamps provenance only after mechanically
2226
+ // confirming the artifact's actual content matches the merged diff. QA's
2227
+ // provenance check enforces the stamp — an unverified publish fails loudly
2228
+ // there instead of passing silently here.
2229
+ // Skip-aware (park 2026-09-11): an empty-diff Integrate takes no merge
2230
+ // lock, and the deterministic publish path skips rebuild/stamp entirely —
2231
+ // there is no new content to verify, so verification is vacuous.
2232
+ // publishSkippedNoLock is workflow-computed state from the explicit
2233
+ // lock-status read in STEP 0, not agent prose.
2234
+ var publishVerifyInspect = { triggered: false, inspection_id: "", error: "" };
1461
2235
  if (step.name === "Publish" && PUBLISH_TYPE === "artifact" && PUBLISH_SLUG) {
1462
- // Skip-aware (park 2026-09-11): an empty-diff Integrate takes no merge
1463
- // lock, and the deterministic publish path skips rebuild/stamp entirely —
1464
- // there is no new provenance to compare against HEAD, so verification is
1465
- // vacuous. publishSkippedNoLock is workflow-computed state from the
1466
- // explicit lock-status read in STEP 0, not agent prose.
1467
2236
  if (publishSkippedNoLock) {
1468
- log("Publish skipped for task " + taskId + " (no merge lock held — empty-diff Integrate): artifact verification vacuous, nothing was shipped");
2237
+ log("Publish skipped for task " + taskId + " (no merge lock held — empty-diff Integrate): content verification vacuous, nothing was shipped");
2238
+ } else if (!publishBuildLanded) {
2239
+ log("Publish build did not land for task " + taskId + " — no content to verify (the failure park above already fired)");
1469
2240
  } else {
1470
2241
  try {
1471
- var headResult = await agent(
1472
- "Run: cd " + REPO_PATH + " && git rev-parse HEAD. Return JSON { \"head\": \"<output trimmed>\" } and nothing else.",
1473
- { key: attemptKey("verify-publish-head-" + taskId, totalReworkCount), label: "Reading integrated commit",
1474
- schema: { type: "object", properties: { head: { type: "string" } }, required: ["head"] } }
1475
- );
1476
- var expectedCommit = (headResult.head || "").trim();
1477
- var provResult = await agent(
1478
- "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"getprovenance\", args: {}. " +
1479
- "Return JSON { \"source_commit\": \"<provenance.source_commit>\", \"published_at\": \"<provenance.published_at>\" } and nothing else.",
1480
- { key: attemptKey("verify-publish-prov-" + taskId, totalReworkCount), label: "Verifying artifact provenance",
1481
- schema: { type: "object", properties: { source_commit: { type: "string" }, published_at: { type: "string" } }, required: ["source_commit"] } }
2242
+ var inspectResult = await agent(
2243
+ ARTIFACT_LOAD_PREAMBLE +
2244
+ "Call artifact_inspect with slug \"" + PUBLISH_SLUG + "\", repair_authorized false, and verbatim_request exactly as follows:\n" +
2245
+ "<<<READBACK_REQUEST\n" + buildPublishReadbackRequest(taskId, mergeCommitForPublish, mergeDiff, rebuildAgentId) + "\nREADBACK_REQUEST\n" +
2246
+ "If artifact_inspect is still not available after the load, do NOT improvise — return { \"triggered\": false, \"inspection_id\": \"\", \"error\": \"artifact_tools missing after load\" } and nothing else.\n" +
2247
+ "Return JSON { \"triggered\": <true if the inspection started, false otherwise>, \"inspection_id\": \"<the inspection id, or empty string>\", \"error\": \"<details or empty string>\" } and nothing else.",
2248
+ { key: attemptKey("publish-verify-inspect-" + taskId, totalReworkCount), label: "Triggering publish content read-back",
2249
+ schema: { type: "object", properties: { triggered: { type: "boolean" }, inspection_id: { type: "string" }, error: { type: "string" } }, required: ["triggered"] } }
1482
2250
  );
1483
- var provCommit = (provResult.source_commit || "").trim();
1484
- if (!provCommit || provCommit !== expectedCommit) {
1485
- return await parkTask("Publish verification failed: artifact provenance shows source_commit '" + provCommit +
1486
- "' but the integrated HEAD is '" + expectedCommit + "'. The publish did not land or provenance was not stamped.");
2251
+ publishVerifyInspect.triggered = !!(inspectResult && inspectResult.triggered);
2252
+ publishVerifyInspect.inspection_id = (inspectResult && inspectResult.inspection_id) || "";
2253
+ publishVerifyInspect.error = (inspectResult && inspectResult.error) || "";
2254
+ if (publishVerifyInspect.triggered) {
2255
+ log("Publish content read-back inspection triggered for task " + taskId + ": " + publishVerifyInspect.inspection_id);
2256
+ } else {
2257
+ log("Publish content read-back inspect trigger failed for task " + taskId + ": " + (publishVerifyInspect.error || "not started") + " — the park below asks the parent to trigger it manually");
1487
2258
  }
1488
- log("Publish verified for task " + taskId + ": artifact provenance at " + provCommit);
1489
- publishVerified = true;
1490
2259
  } catch (e) {
1491
- return await parkTask("Publish verification failed: could not read artifact provenance (" + (e && e.message ? e.message : e) + "). Fail-closed.");
2260
+ publishVerifyInspect.error = (e && e.message ? e.message : String(e)).slice(0, 200);
2261
+ log("Publish content read-back inspect trigger threw for task " + taskId + ": " + publishVerifyInspect.error + " — the park below asks the parent to trigger it manually");
1492
2262
  }
1493
- } // end: !publishSkippedNoLock — a skipped publish has nothing to verify
2263
+ } // end: !publishSkippedNoLock && publishBuildLanded — a skipped or failed publish has nothing to verify
1494
2264
  }
1495
2265
 
1496
2266
  // Session notes. Machine-readable marker lines are extracted from the full
@@ -1541,14 +2311,16 @@ while (i < STEPS.length) {
1541
2311
 
1542
2312
  await agent(
1543
2313
  "Update the session and log the event.\n" +
1544
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
1545
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"" + status + "\", \"notes\": " + JSON.stringify(summary) + " }.\n" +
1546
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
1547
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"" + status + "\", \"identity\": \"" + step.identity + "\", \"message\": \"" + step.name + " " + status + " by " + step.identity + "\" }.",
2314
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("record-phase", {
2315
+ task_id: taskId,
2316
+ session: { id: activeSessionId, task_id: taskId, identity: step.identity, step: step.name,
2317
+ status: status, notes: summary },
2318
+ event: { task_id: taskId, type: status, identity: step.identity,
2319
+ message: step.name + " " + status + " by " + step.identity }
2320
+ }),
1548
2321
  {
1549
2322
  key: "record-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : "") + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""),
1550
- label: "Recording " + step.name + " result",
1551
- schema: { type: "object" }
2323
+ label: "Recording " + step.name + " result"
1552
2324
  }
1553
2325
  );
1554
2326
 
@@ -1587,7 +2359,11 @@ while (i < STEPS.length) {
1587
2359
  log("Visual verdict FAIL — bouncing to Build (rework #" + totalReworkCount + " of " + MAX_TOTAL_REWORK + ")");
1588
2360
  continue;
1589
2361
  } else {
1590
- return await parkTask("Visual verdict pending — parent: run the post-change capture + visual verdict protocol in docs/visual-verdict.md (capture plan is in the QA session notes)");
2362
+ if (!VISUAL_PROTOCOL_AVAILABLE) {
2363
+ log("Visual verdict protocol not available (VISUAL_PROTOCOL_AVAILABLE=false) for task " + taskId + " — skipping visual gate, QA mechanical checks already passed");
2364
+ } else {
2365
+ return await parkTask("Visual verdict pending — parent: run the post-change capture + visual verdict protocol in docs/visual-verdict.md (capture plan is in the QA session notes)");
2366
+ }
1591
2367
  }
1592
2368
  }
1593
2369
 
@@ -1619,17 +2395,35 @@ while (i < STEPS.length) {
1619
2395
  return { status: "failed", task_id: taskId, reason: "Publish failed: " + summary };
1620
2396
  }
1621
2397
 
2398
+ // Publish verification park: the build landed and post-deploy finalized,
2399
+ // but provenance is UNSTAMPED until the parent's independent read-back
2400
+ // (docs/publish-verification.md) confirms the artifact's actual content
2401
+ // matches the merged diff. The parent stamps provenance, then re-queues;
2402
+ // the dispatcher resumes at QA, whose provenance check enforces the stamp
2403
+ // mechanically. A failed Publish never reaches this park — it returned
2404
+ // failed above and retries under the dispatcher's cap. The merge lock is
2405
+ // already released (post-deploy), so the parked task holds no resources.
2406
+ if (passed && step.name === "Publish" && PUBLISH_TYPE === "artifact" && PUBLISH_SLUG && !publishSkippedNoLock && publishBuildLanded) {
2407
+ return await parkTask("publish: verification-requested " + mergeCommitForPublish +
2408
+ " (build " + (rebuildAgentId || "agent_id unobserved") + ")" +
2409
+ " — artifact build landed, post-deploy finalized, provenance NOT stamped. Parent: run docs/publish-verification.md" +
2410
+ (publishVerifyInspect.triggered
2411
+ ? " (content read-back inspection " + publishVerifyInspect.inspection_id + " already triggered)."
2412
+ : " (read-back inspect trigger failed: " + (publishVerifyInspect.error || "not started") + " — parent: trigger artifact_inspect manually)."));
2413
+ }
2414
+
1622
2415
  i++;
1623
2416
  }
1624
2417
 
1625
2418
  await agent(
1626
2419
  "Mark this task as done.\n" +
1627
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"updatetask\", args: { \"id\": \"" + taskId + "\", \"state\": \"done\" }.\n" +
1628
- "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
1629
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"message\": \"All bugfix workflow steps complete.\" }.",
1630
- { key: "task-done", label: "Completing task: " + taskTitle, schema: { type: "object" } }
2420
+ "Run in shell and return the stdout verbatim:\n" + crewCmd("update-task", { id: taskId, state: "done" }) + "\n" +
2421
+ "Then run in shell and return the stdout verbatim:\n" + crewCmd("log-event", {
2422
+ task_id: taskId, type: "completed", message: "All bugfix workflow steps complete."
2423
+ }),
2424
+ { key: "task-done", label: "Completing task: " + taskTitle }
1631
2425
  );
1632
2426
 
1633
2427
  log("Bugfix workflow complete for task " + taskId);
1634
- await agent("Clean up pinned lifecycle scripts: rm -rf " + RUN_LIB, { key: "cleanup-pins", label: "Cleaning pinned scripts", schema: { type: "object" } });
2428
+ await agent("Clean up pinned lifecycle scripts: rm -rf " + RUN_LIB, { key: "cleanup-pins", label: "Cleaning pinned scripts" });
1635
2429
  return { status: "ok", task_id: taskId, message: "Bugfix workflow complete for " + taskTitle };