muse-crew 0.4.3 → 0.4.5

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.
@@ -1,9 +1,10 @@
1
1
  export const meta = {
2
2
  name: "crew-bugfix",
3
- description: "Bugfix workflow: Triage → Reproduce → Map → Build → Review → Integrate → Publish → QA",
4
- phases: ["Triage", "Reproduce", "Map", "Build", "Review", "Integrate", "Publish", "QA"],
3
+ description: "Bugfix workflow: Triage → Capture → Reproduce → Map → Build → Review → Integrate → Publish → QA",
4
+ phases: ["Triage", "Capture", "Reproduce", "Map", "Build", "Review", "Integrate", "Publish", "QA"],
5
5
  steps: [
6
6
  { name: "Triage", identity: "sage" },
7
+ { name: "Capture", identity: "hazel" },
7
8
  { name: "Reproduce", identity: "hazel" },
8
9
  { name: "Map", identity: "mara" },
9
10
  { name: "Build", identity: "wren" },
@@ -19,7 +20,6 @@ const inputs = args ?? {};
19
20
  const taskId = inputs.task_id;
20
21
  const taskTitle = inputs.task_title || "";
21
22
  const taskDescription = inputs.task_description || "";
22
- const firstSessionId = inputs.session_id || null;
23
23
  const startStepIndex = inputs.start_step_index || 0;
24
24
 
25
25
  // Config from args — backward-compatible fallbacks for manual launches
@@ -29,13 +29,16 @@ const ORCH_PATH = crewHome + "/.orchestration";
29
29
  // Pin lifecycle scripts to this run
30
30
  const LIFECYCLE_SRC = crewHome + "/lib/worktree-lifecycle.sh";
31
31
  const MERGE_LOCK_SRC = crewHome + "/lib/merge-lock.sh";
32
- const RUN_LIB = "/tmp/crew-lib-" + taskId;
32
+ const RUN_LIB = crewHome + "/.pins/" + taskId; // persistent disk, NOT /tmp (tmpfs wiped by cell reboots — canary b5efd1b1); stale pins reaped by orphan-sweep
33
33
  const LIFECYCLE = RUN_LIB + "/worktree-lifecycle.sh";
34
34
  const MERGE_LOCK = RUN_LIB + "/merge-lock.sh";
35
35
  const PUBLISH_NPM_SRC = crewHome + "/lib/publish-npm.sh";
36
36
  const PUBLISH_NPM = RUN_LIB + "/publish-npm.sh";
37
37
  const ORPHAN_SWEEP_SRC = crewHome + "/lib/orphan-sweep.sh";
38
38
  const ORPHAN_SWEEP = RUN_LIB + "/orphan-sweep.sh";
39
+ // The four basenames the pin step must materialize — asserted mechanically
40
+ // by workflow code from the verbatim listing, never from agent prose.
41
+ const PIN_BASENAMES = [LIFECYCLE, MERGE_LOCK, PUBLISH_NPM, ORPHAN_SWEEP].map(function (p) { return p.split("/").pop(); });
39
42
 
40
43
  // Project config — passed by dispatcher, falls back to dashboard defaults
41
44
  const projectConfig = inputs.project_config || {};
@@ -43,6 +46,21 @@ const projectConfig = inputs.project_config || {};
43
46
  // compares the task's live project against this on every phase boundary.
44
47
  const LAUNCH_PROJECT_ID = inputs.project_id || "";
45
48
  const REPO_PATH = projectConfig.repo_path || "~/workspace/ts-spaces/orchestra-dashboard";
49
+
50
+ // Worktree layout: the task's worktree lives at
51
+ // <repo>/.worktrees/<task_id> on branch task/<task_id>. The lifecycle
52
+ // manager (lib/worktree-lifecycle.sh) owns creation and removal; the
53
+ // registry at <repo>/.worktrees/.registry/<task_id> is the source of
54
+ // truth for task→branch/path.
55
+ // Env prefix baked into every lifecycle invocation the agents run.
56
+ const LIFECYCLE_ENV = "CREW_REPO=" + REPO_PATH + " ";
57
+ // The task branch is always task/<task_id>.
58
+ const TASK_BRANCH = "task/" + taskId;
59
+ // Where the agent works.
60
+ const WORKTREE_HINT = REPO_PATH + "/.worktrees/" + taskId;
61
+ // Where preserved work lives when the rework budget is exhausted.
62
+ const WORKTREE_PRESERVED_HINT = ".worktrees/" + taskId;
63
+
46
64
  const PUBLISH_TYPE = projectConfig.deploy_type || "";
47
65
  const PUBLISH_SLUG = projectConfig.deploy_slug || DASHBOARD_SLUG;
48
66
  const PROJECT_DESC = projectConfig.description || "React + TypeScript web dashboard (client/src/, server/src/, drizzle/)";
@@ -52,17 +70,360 @@ if (!taskId) {
52
70
  throw new Error("task_id is required in args");
53
71
  }
54
72
 
55
- // Work-agent result schema. Runtime retries on non-JSON (structured outputs).
56
- // Workflow wraps in try/catch so exhausted retries block instead of crashing.
57
- const WORK_SCHEMA = {
58
- type: "object",
59
- properties: { passed: { type: "boolean" }, summary: { type: "string" } },
60
- required: ["passed", "summary"]
61
- };
73
+ // Closeout is deterministic: the work agent returns the runtime's native
74
+ // transport envelope {"status": "ok", "result": "<prose report>"} with no
75
+ // schema, so the workflow receives the report as a plain string. There is no
76
+ // {"report"} wrapper: that invented shape invited agents to improvise sibling
77
+ // keys (notably "status"), which the runtime duck-types as its own envelope
78
+ // and fatally misparses. The envelope is the runtime's own documented shape
79
+ // — not a demand for machine-structured reasoning.
80
+ // The verdict is extracted mechanically by extractVerdict below — never by an
81
+ // agent. The summary is the worker's report truncated. The release decision
82
+ // comes from extractReleaseDecision. No formatter agent: it added a failure
83
+ // mode while contributing nothing the workflow doesn't compute itself.
84
+ // Steps whose passed=false drives a control-flow branch (rework bounce,
85
+ // block) declare their verdict explicitly on a VERDICT: line. The verdict is
86
+ // extracted DETERMINISTICALLY by workflow code (extractVerdict) — never by
87
+ // an agent. Missing, malformed, or contradictory lines fail the phase (never silently pass).
88
+ const VERDICT_STEPS = ["Build", "Review", "QA", "Reproduce", "Integrate", "Publish"];
89
+ function extractVerdict(workerText) {
90
+ // The verdict is the LAST VERDICT: PASS/FAIL in the report (contract: end
91
+ // your report with the verdict). This ignores literal VERDICT strings echoed
92
+ // from the worker's instructions (which contain quoted examples). Fail
93
+ // closed if: no verdict found, the last verdict is not in the trailing 100
94
+ // chars (verdict must be at the end), or conflicting verdicts appear in the
95
+ // trailing 200 chars. Word boundary prevents "PASSING" matching as PASS.
96
+ var text = workerText || "";
97
+ var regex = /VERDICT:\s*(PASS|FAIL)\b/gi;
98
+ var matches = [];
99
+ var m;
100
+ while ((m = regex.exec(text)) !== null) {
101
+ matches.push({ value: /FAIL/i.test(m[0]) ? "FAIL" : "PASS", index: m.index });
102
+ }
103
+ if (matches.length === 0) return { ok: false, count: 0 };
104
+ var last = matches[matches.length - 1];
105
+ if (last.index < text.length - 100) return { ok: false, count: matches.length };
106
+ var trailing = matches.filter(function (x) { return x.index >= text.length - 200; });
107
+ var uniq = trailing.map(function (x) { return x.value; }).filter(function (v, i, a) { return a.indexOf(v) === i; });
108
+ if (uniq.length !== 1) return { ok: false, count: matches.length };
109
+ return { ok: true, passed: last.value === "PASS" };
110
+ }
111
+ // Verdict re-ask (bug cd18ccc2): a verdict-step report that fails
112
+ // extractVerdict is not failed immediately. Stochastic verdict-line
113
+ // non-compliance (the agent did the work but omitted or garbled the VERDICT
114
+ // line) gets up to two bounded follow-up agent() calls whose only job is to
115
+ // read the preserved report and emit exactly one VERDICT line. The verdict
116
+ // is still extracted mechanically by extractVerdict — the re-ask agent
117
+ // transcribes, never decides the phase outcome. Each attempt uses a fresh
118
+ // stable-key suffix so a cached failure can never replay deterministically.
119
+ // Exhaustion keeps the existing fail-closed behavior. This is structure, not
120
+ // prompt hardening: no instruction text was stern-ified to get here.
121
+ function verdictReaskKey(stepName, reworkSuffix, attempt) {
122
+ return "verdict-reask-" + stepName + reworkSuffix + "-a" + attempt;
123
+ }
124
+ function buildVerdictReaskPrompt(stepName, workerText) {
125
+ return "Mechanical transcription task. Read the work report below and emit its verdict.\n\n" +
126
+ "WORK REPORT (verbatim):\n" + workerText + "\n\n" +
127
+ "Decide from the report's own content whether the " + stepName + " step clearly describes successful completion: " +
128
+ "if it does, the verdict is PASS; otherwise — failure, error, unfinished work, or unclear — the verdict is FAIL. " +
129
+ "Do NOT copy any VERDICT line from the report — decide from the content.\n\n" +
130
+ "Return your work as JSON in exactly this shape: {\"status\": \"ok\", \"result\": \"your verdict line here\"}. " +
131
+ "The result must be exactly one line and nothing else: VERDICT: PASS or VERDICT: FAIL.";
132
+ }
133
+ async function reaskVerdict(stepName, reworkSuffix, workerText) {
134
+ var verdict = { ok: false, count: 0 };
135
+ for (var attempt = 1; attempt <= 2; attempt++) {
136
+ var reaskResult = null;
137
+ try {
138
+ reaskResult = await agent(buildVerdictReaskPrompt(stepName, workerText), {
139
+ key: verdictReaskKey(stepName, reworkSuffix, attempt),
140
+ label: "Verdict re-ask: " + stepName + " (attempt " + attempt + " of 2)",
141
+ timeoutMs: 180000
142
+ });
143
+ } catch (e) {
144
+ log(stepName + " verdict re-ask attempt " + attempt + " errored: " + ((e && e.message ? e.message : String(e)) || "").slice(0, 200));
145
+ continue;
146
+ }
147
+ var reaskText = (typeof reaskResult === "string") ? reaskResult : "";
148
+ verdict = extractVerdict(reaskText);
149
+ if (verdict.ok) {
150
+ log(stepName + " verdict re-ask attempt " + attempt + " recovered verdict: " + (verdict.passed ? "PASS" : "FAIL"));
151
+ return verdict;
152
+ }
153
+ log(stepName + " verdict re-ask attempt " + attempt + " produced no readable verdict (" + verdict.count + " trailing-window matches)");
154
+ }
155
+ return verdict;
156
+ }
157
+ // Transport retry: the work-agent agent() call can throw even when the agent
158
+ // did the work. Stochastic envelope non-compliance (bare prose instead of
159
+ // the native {"status":"ok","result":"..."} envelope) trips the runtime's
160
+ // JSON-candidate heuristic when the prose contains a {...}-looking
161
+ // substring — canary 39457ee9's QA report quoted the change's own
162
+ // {/* ... */} JSX comment, the runtime tried to parse it as JSON, threw,
163
+ // and the workflow discarded a complete VERDICT: PASS report as "no output".
164
+ // The verdict re-ask covers an unreadable verdict inside a RECEIVED report;
165
+ // this covers the report never arriving. The assignment is retried boundedly
166
+ // with fresh keys (never a cached replay) before failing closed. Re-entry is
167
+ // safe: lifecycle scripts answer REUSED for existing worktrees/branches, the
168
+ // retry trailer tells the agent to check existing state first and report
169
+ // rather than duplicate completed side effects, and the rework path already
170
+ // re-runs Build after rejection — Build re-entry is an established pattern.
171
+ function workRetryKey(stepName, reworkSuffix, attempt) {
172
+ return "work-" + stepName + reworkSuffix + "-t" + attempt;
173
+ }
174
+ // replay-key scoping for bug 1b8bb875 — runtime keys agent() calls by explicit key per workflow process; on in-process rework a re-executed phase must mint fresh keys; uses the same -r<N> suffix as the phase loop; pure function of inputs, no clock, no randomness (determinism contract). The count is a parameter because chore.js names the counter reworkCount while standard.js/bugfix.js name it totalReworkCount.
175
+ function attemptKey(base, reworkCount) {
176
+ return base + (reworkCount > 0 ? "-r" + reworkCount : "");
177
+ }
178
+ // pinLifecycle(key) — snapshot the lifecycle scripts into RUN_LIB and return
179
+ // the verbatim `ls -1` listing so WORKFLOW CODE asserts the four pinned
180
+ // basenames; the agent cannot self-certify. (The pin step was the one place
181
+ // the workflows trusted agent prose: task 24be1cd6 walked to Publish on an
182
+ // empty pin dir.) Byte-identical across standard/bugfix/chore — pinned by
183
+ // tests/pin-location.test.js.
184
+ function pinLifecycle(key) {
185
+ return agent(
186
+ "Snapshot lifecycle scripts for version pinning.\n" +
187
+ "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" +
188
+ "Return the verbatim output of the ls -1 command as { \"listing\": \"<verbatim output>\" } and nothing else.",
189
+ { key: key, label: "Pinning lifecycle scripts",
190
+ schema: { type: "object", properties: { listing: { type: "string" } }, required: ["listing"] } }
191
+ );
192
+ }
193
+ // parsePinListing(result) — basenames from a pin/verify listing.
194
+ // Byte-identical across standard/bugfix/chore — pinned by
195
+ // tests/pin-location.test.js.
196
+ function parsePinListing(result) {
197
+ return (result && result.listing ? result.listing : "").split("\n").map(function (s) { return s.trim(); }).filter(function (s) { return s.length > 0; });
198
+ }
199
+ function buildTransportRetryTrailer(stepName, repoPath, taskId, attempt, reason) {
200
+ // reason: "discarded" (the runtime threw the output away — it could not be
201
+ // machine-read) or "empty" (agent() returned without throwing but produced
202
+ // nothing usable). The trailer tells the retry what to expect, not just to
203
+ // try again.
204
+ var why = reason === "empty"
205
+ ? "your previous attempt returned no usable output"
206
+ : "your previous attempt's output could not be machine-read as JSON and was discarded";
207
+ return "\n\nTRANSPORT RETRY (attempt " + attempt + " of 2): " + why + ". " +
208
+ "First check existing state (worktree/branch at " + repoPath + "/.worktrees/" + taskId + ", the task branch, dashboard sessions for this task) — " +
209
+ "if the " + stepName + " work is already complete, report on what was done rather than duplicating side effects. " +
210
+ "Then return your report as JSON in exactly the shape specified above.";
211
+ }
212
+ function describeWorkAgentFailure(stepName, identity, attempts) {
213
+ // Honest classification of a work-agent call that yielded no usable
214
+ // report, with the per-attempt evidence preserved in the session notes.
215
+ // Two distinct cases:
216
+ // - agent() THREW: the runtime discarded output it could not machine-read
217
+ // (e.g. prose tripping the JSON-candidate heuristic). The raw output is
218
+ // gone — the workflow never received it — so the surviving error text is
219
+ // recorded here instead. (An earlier comment claimed the raw output was
220
+ // "preserved in the run record"; that was false — nothing preserved it —
221
+ // and the claim is removed.)
222
+ // - agent() RETURNED EMPTY without throwing: the child produced nothing
223
+ // usable. Each attempt's outcome is the evidence.
224
+ // attempts: [{threw, error, outcome}, ...], in order.
225
+ var parts = [];
226
+ for (var i = 0; i < attempts.length; i++) {
227
+ var a = attempts[i];
228
+ parts.push("attempt " + (i + 1) + "/" + attempts.length + ": " +
229
+ (a.threw ? "threw '" + a.error + "'" : "returned " + a.outcome));
230
+ }
231
+ var detail = parts.join("; ").replace(/"/g, "'").slice(0, 400);
232
+ var anyThrow = false;
233
+ for (var j = 0; j < attempts.length; j++) {
234
+ if (attempts[j].threw) { anyThrow = true; break; }
235
+ }
236
+ if (anyThrow) {
237
+ return {
238
+ notes: "Work agent produced no machine-readable report after " + attempts.length + " attempts; runtime discarded the output (" + detail + ")",
239
+ eventMessage: stepName + " work agent produced no machine-readable report after " + attempts.length + " attempts — phase failed, dispatcher will retry",
240
+ blockedReason: stepName + " work agent produced no machine-readable report after " + attempts.length + " attempts",
241
+ message: "The " + identity + " agent's output could not be machine-read (" + attempts.length + " attempts exhausted); the runtime discarded the raw output before the workflow could see it. Surviving evidence: " + detail
242
+ };
243
+ }
244
+ return {
245
+ notes: "Work agent returned no usable output after " + attempts.length + " attempts (" + detail + ")",
246
+ eventMessage: stepName + " work agent returned no usable output after " + attempts.length + " attempts — phase failed, dispatcher will retry",
247
+ blockedReason: stepName + " work agent returned no usable output",
248
+ message: "The " + identity + " agent returned no usable output after " + attempts.length + " attempts (" + detail + ")."
249
+ };
250
+ }
251
+
252
+ // Release declaration extraction: deterministic. The Build worker declares
253
+ // release:/version_bump: in its report; workflow code reads them directly
254
+ // from the full worker report. A missing or malformed declaration fails
255
+ // closed to null (Review then rejects).
256
+ function extractReleaseDecision(workerText) {
257
+ var t = workerText || "";
258
+ var r = /release:\s*(yes|no)\b/i.exec(t);
259
+ if (!r) return null;
260
+ var b = /version_bump:\s*(patch|minor|major)\b/i.exec(t);
261
+ var rel = r[1].toLowerCase();
262
+ if (rel === "yes" && !b) return null;
263
+ return { release: rel, version_bump: b ? b[1].toLowerCase() : null };
264
+ }
265
+ // Marker line preservation: machine-readable lines (repo_diff:, release:,
266
+ // version_bump:, VERDICT:, TARGET_VERSION=, published:) are extracted from
267
+ // the full worker report and appended after the summary slice, so a long
268
+ // report can never amputate them. Later phases read these from session notes.
269
+ function extractMarkerLines(workerText) {
270
+ var lines = (workerText || "").split("\n");
271
+ var markers = [];
272
+ for (var i = 0; i < lines.length; i++) {
273
+ var line = lines[i].trim();
274
+ if (/^(repo_diff:|release:|version_bump:|VERDICT:|TARGET_VERSION=|published:|experiential:|capture_targets:)/i.test(line)) {
275
+ markers.push(line);
276
+ }
277
+ }
278
+ return markers.join("\n");
279
+ }
280
+
281
+ // Visual verdict shared functions: byte-identical across standard.js,
282
+ // bugfix.js, and chore.js (pinned by tests/visual-verdict.test.js — same
283
+ // contract as buildTransportRetryTrailer).
284
+ function extractExperiential(workerText) {
285
+ // Reads Sage's experiential: yes|no marker line. Missing or malformed
286
+ // fails closed to null — the flag is opt-in; null is treated as
287
+ // non-experiential (never silently parks a task on a garbled line).
288
+ var t = workerText || "";
289
+ var r = /experiential:\s*(yes|no)\b/i.exec(t);
290
+ if (!r) return null;
291
+ return r[1].toLowerCase() === "yes";
292
+ }
293
+ function buildVisualCapturePlan(taskTitle, taskDescription, kind, captureTargets) {
294
+ // Deterministic visual-capture frame. kind: "baseline" | "postchange".
295
+ // This string IS the capture script: fixed viewport matrix, scroll
296
+ // positions, and interaction states — the inspection agent executes it
297
+ // verbatim, nothing is improvised. Task-specific targets fill the slots.
298
+ var title = String(taskTitle || "").replace(/"/g, "'").slice(0, 120);
299
+ var targets = String(captureTargets || "").trim() ||
300
+ String(taskDescription || "").replace(/"/g, "'").slice(0, 300);
301
+ return "VISUAL CAPTURE — " + kind.toUpperCase() + " — task: " + title + ". " +
302
+ "Target views/controls: " + targets + ". " +
303
+ "For EACH target, capture exactly: " +
304
+ "(1) desktop 1440x900, full view, scrolled to top; " +
305
+ "(2) desktop 1440x900, scrolled so the target is vertically centered; " +
306
+ "(3) mobile 390x844, scrolled so the target is vertically centered; " +
307
+ "(4) desktop 1440x900, hover state on the target control; " +
308
+ "(5) desktop 1440x900, keyboard-focus state on the target control; " +
309
+ "(6) desktop 1440x900, active/pressed state if the target is a button or control. " +
310
+ "Also record: console error count, the ARIA tree of the target region, any horizontal overflow. " +
311
+ "Name captures " + kind + "-<n>-<viewport>-<state>. Return the captures, not a summary.";
312
+ }
313
+ // Experiential flag resolution: the task is experiential when Sage's Triage
314
+ // report ends with the machine-read marker "experiential: yes". The flag is
315
+ // opt-in — a missing or garbled line degrades to "unknown", which callers
316
+ // treat as non-experiential. The task is never parked on a garbled line.
317
+ async function resolveExperiential() {
318
+ if (isExperiential === true) return "yes";
319
+ if (isExperiential === false) return "no";
320
+ var expCheck = null;
321
+ try {
322
+ expCheck = await agent(
323
+ "Find this task's Triage step session notes from the dashboard.\n" +
324
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getstate\", args: { \"events_limit\": 1 }.\n" +
325
+ "Find the session with task_id \"" + taskId + "\" and step \"Triage\" (status completed) in the returned sessions array and read its notes field.\n" +
326
+ "Return JSON { \"experiential_line\": \"<the exact text of the experiential: marker line from the notes, or empty string if absent>\" } and nothing else.",
327
+ {
328
+ key: "resolve-experiential-" + taskId,
329
+ label: "Resolving experiential flag from Triage notes",
330
+ schema: { type: "object", properties: { experiential_line: { type: "string" } }, required: ["experiential_line"] }
331
+ }
332
+ );
333
+ } catch (e) {
334
+ log("resolveExperiential: agent call failed (" + (e && e.message ? e.message : e) + ") — treating as unknown");
335
+ return "unknown";
336
+ }
337
+ var marker = extractExperiential(expCheck && expCheck.experiential_line ? expCheck.experiential_line : "");
338
+ if (marker === true) return "yes";
339
+ if (marker === false) return "no";
340
+ return "unknown";
341
+ }
342
+ // Baseline evidence status: reads the task's note events for the exact
343
+ // protocol prefixes (explicit state, never English matching). Returns
344
+ // { baseline_found, baseline_kind, baseline_refs, requested_count }.
345
+ // found = any note starting exactly "baseline: captured" or "baseline:
346
+ // none" (kind/refs come from the LATEST such message); requested_count =
347
+ // the number of notes starting exactly "baseline: requested". Each call
348
+ // uses a fresh key: the evidence changes between calls (the parent logs
349
+ // the capture while this run is parked), so a cached replay would lie.
350
+ let baselineStatusCallCount = 0;
351
+ async function baselineStatus() {
352
+ baselineStatusCallCount++;
353
+ try {
354
+ var ev = await agent(
355
+ "Read this task's note events from the dashboard.\n" +
356
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getevents\", args: { \"task_id\": \"" + taskId + "\" }.\n" +
357
+ "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" +
358
+ "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.",
359
+ {
360
+ key: "baseline-status-" + taskId + "-" + baselineStatusCallCount,
361
+ label: "Reading baseline evidence status",
362
+ schema: {
363
+ type: "object",
364
+ properties: {
365
+ baseline_found: { type: "boolean" },
366
+ baseline_kind: { type: "string" },
367
+ baseline_refs: { type: "string" },
368
+ requested_count: { type: "number" }
369
+ },
370
+ required: ["baseline_found", "baseline_kind", "baseline_refs", "requested_count"]
371
+ }
372
+ }
373
+ );
374
+ return {
375
+ baseline_found: !!(ev && ev.baseline_found),
376
+ baseline_kind: (ev && ev.baseline_kind) || "",
377
+ baseline_refs: (ev && ev.baseline_refs) || "",
378
+ requested_count: (ev && ev.requested_count) || 0
379
+ };
380
+ } catch (e) {
381
+ log("baselineStatus: agent call failed (" + (e && e.message ? e.message : e) + ") — treating as no evidence");
382
+ return { baseline_found: false, baseline_kind: "", baseline_refs: "", requested_count: 0 };
383
+ }
384
+ }
385
+ // Visual verdict status: the parent records the visual verdict as a note
386
+ // event after the rendered post-change inspection results arrive. Finds the
387
+ // latest step "QA" session's started_at, then note events NEWER than it
388
+ // whose message starts exactly "visual_verdict: PASS" / "visual_verdict:
389
+ // FAIL". Returns { found, verdict, detail }. A fresh key per call: the
390
+ // verdict lands while this run is parked.
391
+ let visualVerdictCallCount = 0;
392
+ async function visualVerdictStatus() {
393
+ visualVerdictCallCount++;
394
+ try {
395
+ var vv = await agent(
396
+ "Read this task's QA session and note events from the dashboard.\n" +
397
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getstate\", args: { \"events_limit\": 1 }.\n" +
398
+ "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" +
399
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"getevents\", args: { \"task_id\": \"" + taskId + "\" }.\n" +
400
+ "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" +
401
+ "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.",
402
+ {
403
+ key: "visual-verdict-status-" + taskId + "-" + visualVerdictCallCount,
404
+ label: "Reading visual verdict status",
405
+ schema: {
406
+ type: "object",
407
+ properties: {
408
+ found: { type: "boolean" },
409
+ verdict: { type: "string" },
410
+ detail: { type: "string" }
411
+ },
412
+ required: ["found", "verdict", "detail"]
413
+ }
414
+ }
415
+ );
416
+ return { found: !!(vv && vv.found), verdict: (vv && vv.verdict) || "", detail: (vv && vv.detail) || "" };
417
+ } catch (e) {
418
+ log("visualVerdictStatus: agent call failed (" + (e && e.message ? e.message : e) + ") — treating as not found");
419
+ return { found: false, verdict: "", detail: "" };
420
+ }
421
+ }
62
422
 
63
423
  // STEPS inline — export const meta is parsed as metadata, not a runtime binding
64
424
  const STEPS = [
65
425
  { name: "Triage", identity: "sage" },
426
+ { name: "Capture", identity: "hazel" },
66
427
  { name: "Reproduce", identity: "hazel" },
67
428
  { name: "Map", identity: "mara" },
68
429
  { name: "Build", identity: "wren" },
@@ -73,6 +434,8 @@ const STEPS = [
73
434
  ];
74
435
  const BUILD_INDEX = STEPS.findIndex(s => s.name === 'Build');
75
436
  if (BUILD_INDEX < 0) throw new Error("STEPS missing 'Build' step");
437
+ const CAPTURE_INDEX = STEPS.findIndex(s => s.name === 'Capture');
438
+ if (CAPTURE_INDEX < 0) throw new Error("STEPS missing 'Capture' step");
76
439
  const REWORK_STEP = STEPS[BUILD_INDEX].name;
77
440
  // Shared rework budget: Review and QA rejections draw from the SAME pool of 2.
78
441
  // E.g. 2 Review bounces + 1 QA bounce = 3 total > budget -> task blocks.
@@ -80,8 +443,15 @@ const MAX_TOTAL_REWORK = 2;
80
443
  let totalReworkCount = 0;
81
444
  let rejectionNotes = inputs.rejection_notes || "";
82
445
  let mapperSpec = "";
446
+ // Visual verdict state: Sage's experiential flag (true/false/null until the
447
+ // Triage report is read), Mara's capture targets for the post-change capture
448
+ // plan, and the Map-gate bounce counter (keeps agent stable-keys unique when
449
+ // a Map-gate bounce re-runs Capture/Map in the same run).
450
+ let isExperiential = null;
451
+ let captureTargets = "";
452
+ let mapGateBounceCount = 0;
83
453
  // Merge-time versioning: the release decision is extracted deterministically
84
- // from the accepted Build summary (extractReleaseDecision) so the Publish
454
+ // from the accepted Build worker report (extractReleaseDecision) so the Publish
85
455
  // agent never decides whether to publish. Two consecutive Publish runs
86
456
  // rationalized a skip against explicit instruction text — text alone did not
87
457
  // hold, so the decision now lives in workflow code, not agent judgment.
@@ -95,26 +465,50 @@ function bumpVersion(base, scope) {
95
465
  if (scope === "minor") return p[0] + "." + (p[1] + 1) + ".0";
96
466
  return p[0] + "." + p[1] + "." + (p[2] + 1); // patch (default)
97
467
  }
98
- function extractReleaseDecision(text) {
99
- const t = text || "";
100
- const r = /^release:\s*(yes|no)\s*$/im.exec(t);
101
- if (!r) return null;
102
- const b = /^version_bump:\s*(patch|minor|major)\s*$/im.exec(t);
103
- if (r[1].toLowerCase() === "yes" && !b) return null;
104
- return { release: r[1].toLowerCase(), version_bump: b ? b[1].toLowerCase() : null };
105
- }
106
468
  function releaseDecisionText() {
107
- if (!releaseDecision) return "no parseable release:/version_bump: decision";
469
+ if (!releaseDecision) return "no machine-readable release decision from the Build report";
108
470
  return "release: " + releaseDecision.release + (releaseDecision.version_bump ? ", version_bump: " + releaseDecision.version_bump : " (no version_bump line)");
109
471
  }
472
+ // Park the task for human attention and end the run. "blocked" is never
473
+ // manually authored — the dashboard derives it mechanically from unmet
474
+ // dependencies — so a workflow outcome that needs a human parks the task
475
+ // instead. Parking is one atomic dashboard action (parktask): the parked
476
+ // state and the explanatory note land in one transaction, never half.
477
+ // The dispatcher skips parked tasks; a human moving parked→todo
478
+ // mechanically resets the retry counters. Returns the workflow result
479
+ // envelope the launcher sees. If the park call itself fails, the run
480
+ // reports "failed" (retryable) so the next tick re-attempts the park —
481
+ // a lost park is never reported as parked.
482
+ async function parkTask(reason) {
483
+ log("Parking task " + taskId + " for human attention: " + reason);
484
+ var parkMessage = ("Parked: " + reason).slice(0, 1000);
485
+ try {
486
+ await agent(
487
+ "Park this task for human attention.\n" +
488
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"parktask\", args: " +
489
+ JSON.stringify({ task_id: taskId, message: parkMessage }) + ".\n" +
490
+ "The parked state is the human-attention signal — the dispatcher skips parked tasks.",
491
+ { key: "park-task", label: "Parking task for human attention", schema: { type: "object" } }
492
+ );
493
+ } catch (parkErr) {
494
+ log("PARK FAILED for task " + taskId + ": " + (parkErr && parkErr.message ? parkErr.message : parkErr) + " — park did not land, reporting failed so the next tick retries");
495
+ return { status: "failed", task_id: taskId, reason: "park failed: " + reason, park_failed: true };
496
+ }
497
+ return { status: "parked", task_id: taskId, reason: reason };
498
+ }
110
499
  let i = startStepIndex;
111
500
 
112
- // Pin lifecycle scripts
113
- await agent(
114
- "Snapshot lifecycle scripts for version pinning.\n" +
115
- "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,
116
- { key: "pin-lifecycle", label: "Pinning lifecycle scripts", schema: { type: "object" } }
117
- );
501
+ // ── Pin lifecycle scripts ────────────────────────────────────────────
502
+ // Copy lifecycle scripts into a per-task temp dir so this run is immune
503
+ // to upgrades that land while it's in flight. Verified mechanically:
504
+ // workflow code asserts the four basenames from the verbatim listing
505
+ // the agent cannot self-certify. Any miss parks the task before Triage.
506
+ const initialPins = parsePinListing(await pinLifecycle("pin-lifecycle"));
507
+ const missingInitialPins = PIN_BASENAMES.filter(function (b) { return initialPins.indexOf(b) === -1; });
508
+ if (missingInitialPins.length > 0) {
509
+ return await parkTask("Lifecycle pin incomplete before Triage — missing " + missingInitialPins.join(", ") + " in " + RUN_LIB + ".");
510
+ }
511
+ log("Lifecycle scripts pinned to " + RUN_LIB);
118
512
 
119
513
  while (i < STEPS.length) {
120
514
  const step = STEPS[i];
@@ -145,15 +539,14 @@ while (i < STEPS.length) {
145
539
  if (currentProject !== LAUNCH_PROJECT_ID) {
146
540
  const abortMessage = "Task project changed mid-run from '" + LAUNCH_PROJECT_ID + "' to '" + currentProject + "' — aborting stale run. The dispatcher will re-launch from " + REWORK_STEP + " with the new project context.";
147
541
  log(abortMessage);
148
- const abortSessionPatch = (isFirstClaim && firstSessionId) ? "\"id\": \"" + firstSessionId + "\", " : "";
149
542
  await agent(
150
543
  "Abort the stale run and remove its worktree from the old project's repo.\n" +
151
544
  "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
152
- "{ \"task_id\": \"" + taskId + "\", " + abortSessionPatch + "\"identity\": \"" + step.identity + "\", \"step\": \"" + REWORK_STEP + "\", \"status\": \"failed\", " +
545
+ "{ \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + REWORK_STEP + "\", \"status\": \"failed\", " +
153
546
  "\"notes\": " + JSON.stringify(abortMessage + " Rebuild from the Map session notes in the task's event history.") + " }.\n" +
154
547
  "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
155
548
  "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"identity\": \"" + step.identity + "\", \"message\": " + JSON.stringify(abortMessage) + " }.\n" +
156
- "Then run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " cleanup " + taskId + "\n" +
549
+ "Then run: "+ LIFECYCLE_ENV + " cleanup " + taskId + "\n" +
157
550
  "The cleanup output should contain CLEANUP.",
158
551
  { key: "abort-project-change", label: "Aborting stale run (project changed)", schema: { type: "object" } }
159
552
  );
@@ -161,22 +554,49 @@ while (i < STEPS.length) {
161
554
  }
162
555
  }
163
556
 
557
+ // ── Pre-Publish pin guard ──────────────────────────────────────────
558
+ // Verify the pinned lifecycle scripts still exist on every Publish
559
+ // pass (first pass and rework passes): the pin step trusted agent
560
+ // prose instead of a mechanical check, so task 24be1cd6 walked to
561
+ // Publish on an empty pin dir. One re-pin and re-verify on a miss;
562
+ // still missing parks the task. Keys are attemptKey-scoped so a
563
+ // rework Publish never re-mints a first-pass key.
564
+ if (step.name === "Publish") {
565
+ let publishPins = parsePinListing(await agent(
566
+ "Verify the pinned lifecycle scripts are present.\n" +
567
+ "Run: ls -1 " + RUN_LIB + " 2>/dev/null || echo PIN_DIR_MISSING\n" +
568
+ "Return the verbatim output as { \"listing\": \"<verbatim output>\" } and nothing else.",
569
+ { key: attemptKey("pins-verify-publish", totalReworkCount), label: "Verifying pinned lifecycle scripts",
570
+ schema: { type: "object", properties: { listing: { type: "string" } }, required: ["listing"] } }
571
+ ));
572
+ let missingAtPublish = PIN_BASENAMES.filter(function (b) { return publishPins.indexOf(b) === -1; });
573
+ if (missingAtPublish.length > 0) {
574
+ log("Pin guard at Publish: missing " + missingAtPublish.join(", ") + " — re-pinning once");
575
+ publishPins = parsePinListing(await pinLifecycle(attemptKey("pin-lifecycle-republish", totalReworkCount)));
576
+ missingAtPublish = PIN_BASENAMES.filter(function (b) { return publishPins.indexOf(b) === -1; });
577
+ }
578
+ if (missingAtPublish.length > 0) {
579
+ return await parkTask("Pinned lifecycle scripts missing at Publish even after re-pin: " + missingAtPublish.join(", ") + " in " + RUN_LIB + ".");
580
+ }
581
+ log("Pin guard: all four lifecycle scripts present at Publish");
582
+ }
583
+
164
584
  // Publish is optional and target-based. Empty target = prototyping project: skip the phase.
165
585
  // Unknown target (incl. legacy "repo") = config error: block.
166
586
  if (step.name === "Publish" && !PUBLISH_TYPE) {
167
587
  log("Publish skipped for task " + taskId + " — no publish target configured (deploy_type empty)");
168
588
  await agent(
169
589
  "Release the merge lock and clean up without publishing.\n" +
170
- "Run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " post-deploy " + taskId + "\n" +
590
+ "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
171
591
  "If the output contains DEPLOYED, the lock is released and the worktree is cleaned up.",
172
- { key: "publish-skip-cleanup", label: "Skipping Publish (no target)", schema: { type: "object" } }
592
+ { key: attemptKey("publish-skip-cleanup", totalReworkCount), label: "Skipping Publish (no target)", schema: { type: "object" } }
173
593
  );
174
594
  i++;
175
595
  continue;
176
596
  }
177
597
  if (step.name === "Publish" && PUBLISH_TYPE !== "npm" && PUBLISH_TYPE !== "artifact" && PUBLISH_TYPE !== "vercel") {
178
598
  log("Unknown publish target for task " + taskId + ": " + PUBLISH_TYPE);
179
- return { status: "blocked", task_id: taskId, reason: "Unknown publish target '" + PUBLISH_TYPE + "' — expected 'npm', 'artifact', 'vercel', or empty (skip publish)." };
599
+ return await parkTask("Unknown publish target '" + PUBLISH_TYPE + "' — expected 'npm', 'artifact', 'vercel', or empty (skip publish).");
180
600
  }
181
601
 
182
602
  // Merge-time versioning, decided deterministically: the release decision was
@@ -186,15 +606,15 @@ while (i < STEPS.length) {
186
606
  // therefore has no decision point to rationalize into a skip.
187
607
  if (step.name === "Publish" && PUBLISH_TYPE === "npm") {
188
608
  if (!releaseDecision) {
189
- return { status: "blocked", task_id: taskId, reason: "Build summary has no parseable release:/version_bump: lines — cannot assign version at publish time." };
609
+ return await parkTask("Build report has no machine-readable release:/version_bump: declaration — cannot assign version at publish time.");
190
610
  }
191
611
  if (releaseDecision.release === "no") {
192
- log("Publish skipped for task " + taskId + " — accepted Build summary declared release: no");
612
+ log("Publish skipped for task " + taskId + " — accepted Build report declared release: no");
193
613
  await agent(
194
614
  "Release the merge lock and clean up without publishing.\n" +
195
- "Run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " post-deploy " + taskId + "\n" +
615
+ "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
196
616
  "If the output contains DEPLOYED, the lock is released and the worktree is cleaned up.",
197
- { key: "publish-skip-release-no", label: "Skipping Publish (release: no)", schema: { type: "object" } }
617
+ { key: attemptKey("publish-skip-release-no", totalReworkCount), label: "Skipping Publish (release: no)", schema: { type: "object" } }
198
618
  );
199
619
  i++;
200
620
  continue;
@@ -210,27 +630,50 @@ while (i < STEPS.length) {
210
630
  "Run: npm view muse-crew version 2>/dev/null || echo NOT_FOUND\n" +
211
631
  "If the output is NOT_FOUND, run: node -p \"require('" + REPO_PATH + "/package.json').version\"\n" +
212
632
  "Return JSON { \"base\": \"<the version string, trimmed>\" } and nothing else.",
213
- { key: "publish-base-" + taskId, label: "Reading registry base version",
633
+ { key: attemptKey("publish-base-" + taskId, totalReworkCount), label: "Reading registry base version",
214
634
  schema: { type: "object", properties: { base: { type: "string" } }, required: ["base"] } }
215
635
  );
216
636
  var pubScope = releaseDecision.version_bump || "patch";
217
637
  var pubBase = (baseResult.base || "").trim();
218
638
  if (!/^\d+\.\d+\.\d+$/.test(pubBase)) {
219
- return { status: "blocked", task_id: taskId,
220
- reason: "Publish base version unreadable: '" + pubBase + "'. Fail-closed." };
639
+ return await parkTask("Publish base version unreadable: '" + pubBase + "'. Fail-closed.");
221
640
  }
222
641
  publishTarget = { base: pubBase, scope: pubScope, target: bumpVersion(pubBase, pubScope) };
223
642
  log("Publish target for task " + taskId + ": " + pubBase + " + " + pubScope + " -> " + publishTarget.target);
224
643
  } catch (e) {
225
- return { status: "blocked", task_id: taskId,
226
- reason: "Deterministic pre-publish failed: " + (e && e.message ? e.message : e) + ". Fail-closed." };
644
+ return await parkTask("Deterministic pre-publish failed: " + (e && e.message ? e.message : e) + ". Fail-closed.");
227
645
  }
228
646
  }
229
647
 
230
- // Claim session
648
+ // Self-claim — the dispatcher only recommends; the launched workflow claims
649
+ // the task as its first action, so a claim can never exist without a launched
650
+ // agent behind it. If another run claimed the task first (two poll ticks
651
+ // raced in the window before this run's claim), claimtask returns
652
+ // claimed:false and this run stands down as a duplicate.
231
653
  let activeSessionId;
232
- if (isFirstClaim && firstSessionId) {
233
- activeSessionId = firstSessionId;
654
+ if (isFirstClaim) {
655
+ const claimResult = await agent(
656
+ "Claim this task for the " + step.name + " step.\n" +
657
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"updatetask\", args: { \"id\": \"" + taskId + "\", \"state\": \"in_progress\" }.\n" +
658
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"claimtask\", args:\n" +
659
+ "{ \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"notes\": \"" + step.name + " step started\" }.\n" +
660
+ "Do not interpret the claim response. It already contains an explicit \"claimed\" field — copy it verbatim.\n" +
661
+ "Return { claimed: <verbatim>, session_id: \"<...>\" }. If claimed is false there is no session_id; return { claimed: false, session_id: \"\" }.",
662
+ {
663
+ key: "claim-" + step.name + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""),
664
+ label: "Claiming " + step.name,
665
+ schema: {
666
+ type: "object",
667
+ properties: { claimed: { type: "boolean" }, session_id: { type: "string" } },
668
+ required: ["claimed", "session_id"]
669
+ }
670
+ }
671
+ );
672
+ if (!claimResult.claimed) {
673
+ log("Standing down — task " + taskId + " was already claimed by another run");
674
+ return { status: "duplicate", task_id: taskId, reason: "task already claimed by another run" };
675
+ }
676
+ activeSessionId = claimResult.session_id;
234
677
  } else {
235
678
  const claimResult = await agent(
236
679
  "Claim a session for this task step.\n" +
@@ -238,7 +681,7 @@ while (i < STEPS.length) {
238
681
  "{ \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"notes\": \"" + step.name + " step started" + (totalReworkCount > 0 ? " (rework #" + totalReworkCount + ")" : "") + "\" }.\n" +
239
682
  "Return the session_id from the response.",
240
683
  {
241
- key: "claim-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : ""),
684
+ key: "claim-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : "") + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""),
242
685
  label: "Claiming " + step.name,
243
686
  schema: {
244
687
  type: "object",
@@ -250,11 +693,115 @@ while (i < STEPS.length) {
250
693
  activeSessionId = claimResult.session_id;
251
694
  }
252
695
 
696
+ // ── Capture: baseline evidence for experiential tasks ─────────────
697
+ // Hazel's QA capture pass runs right after Triage, before Map, for tasks
698
+ // Sage flagged experiential. The capture itself is parent-driven (the
699
+ // inspection handoff arrives at the root agent, outside this script), so
700
+ // when no baseline evidence is recorded yet the script logs a note event
701
+ // and parks with the exact parent protocol + resume path. Never fails the
702
+ // task over missing evidence: after two requests, baseline:none is
703
+ // recorded and final QA judges on the rubric alone.
704
+ if (step.name === "Capture") {
705
+ var capExp = await resolveExperiential();
706
+ var bounceSuffix = (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : "");
707
+ if (capExp !== "yes" || PUBLISH_TYPE !== "artifact") {
708
+ log("Capture skipped for task " + taskId + " — " + (capExp !== "yes" ? "not experiential" : "publish target is not artifact"));
709
+ await agent(
710
+ "Update the session and log the event.\n" +
711
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
712
+ "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"completed\", \"notes\": \"Capture skipped — not an experiential artifact task\" }.\n" +
713
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
714
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"identity\": \"" + step.identity + "\", \"message\": \"Capture completed by " + step.identity + "\" }.",
715
+ { key: "record-Capture" + bounceSuffix, label: "Recording Capture result", schema: { type: "object" } }
716
+ );
717
+ i++;
718
+ continue;
719
+ }
720
+ var capStatus = await baselineStatus();
721
+ if (capStatus.baseline_found) {
722
+ log("Capture: baseline evidence already recorded for task " + taskId + " (" + capStatus.baseline_kind + ")");
723
+ await agent(
724
+ "Update the session and log the event.\n" +
725
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
726
+ "{ \"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" +
727
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
728
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"identity\": \"" + step.identity + "\", \"message\": \"Capture completed by " + step.identity + "\" }.",
729
+ { key: "record-Capture" + bounceSuffix, label: "Recording Capture result", schema: { type: "object" } }
730
+ );
731
+ i++;
732
+ continue;
733
+ }
734
+ var attemptN = capStatus.requested_count + 1;
735
+ if (capStatus.requested_count >= 2) {
736
+ log("Capture: baseline capture unavailable after 2 requests for task " + taskId + " — recording baseline:none");
737
+ await agent(
738
+ "Record that no baseline was capturable.\n" +
739
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
740
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"note\", \"identity\": \"" + step.identity + "\", \"message\": \"baseline: none (capture unavailable after 2 attempts)\" }.\n" +
741
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
742
+ "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"completed\", \"notes\": \"baseline: none — final QA judges on rubric alone\" }.\n" +
743
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
744
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"completed\", \"identity\": \"" + step.identity + "\", \"message\": \"Capture completed by " + step.identity + "\" }.",
745
+ { key: "record-Capture-none" + bounceSuffix, label: "Recording baseline: none", schema: { type: "object" } }
746
+ );
747
+ i++;
748
+ continue;
749
+ }
750
+ log("Capture: requesting baseline capture (attempt " + attemptN + ") for task " + taskId);
751
+ await agent(
752
+ "Request the baseline capture and record the request.\n" +
753
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
754
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"note\", \"identity\": \"" + step.identity + "\", \"message\": \"baseline: requested (attempt " + attemptN + ")\" }.\n" +
755
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
756
+ "{ \"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.") + " }.",
757
+ { key: "record-Capture-request" + bounceSuffix, label: "Recording baseline capture request", schema: { type: "object" } }
758
+ );
759
+ 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");
760
+ }
761
+
762
+ // ── Map gate: experiential tasks need baseline evidence ────────────
763
+ // Mara must verify baseline evidence exists before writing the spec. If
764
+ // missing, bounce back to Capture — never to Build, never a task failure.
765
+ var mapBaselineRefs = "";
766
+ var mapBaselineNone = false;
767
+ if (step.name === "Map") {
768
+ if ((await resolveExperiential()) === "yes") {
769
+ var gateStatus = await baselineStatus();
770
+ if (!gateStatus.baseline_found) {
771
+ log("Map gate: no baseline evidence for experiential task " + taskId + " — bouncing to Capture");
772
+ await agent(
773
+ "Record the Map gate bounce.\n" +
774
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
775
+ "{ \"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" +
776
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
777
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"identity\": \"" + step.identity + "\", \"message\": \"Map gate bounce — baseline evidence missing, returning to Capture\" }.",
778
+ { key: "record-Map-bounce" + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""), label: "Recording Map gate bounce", schema: { type: "object" } }
779
+ );
780
+ mapGateBounceCount++;
781
+ i = CAPTURE_INDEX;
782
+ continue;
783
+ }
784
+ mapBaselineRefs = gateStatus.baseline_refs;
785
+ mapBaselineNone = (gateStatus.baseline_kind === "none");
786
+ }
787
+ }
788
+
789
+ // Visual verdict routing: experiential artifact tasks get their visual
790
+ // verdict from the parent AFTER the rendered post-change inspection
791
+ // results arrive (this script cannot receive the async handoff). The QA
792
+ // work agent covers mechanical checks only; the visual-verdict gate below
793
+ // parks for the parent protocol when no visual_verdict: note event exists
794
+ // yet.
795
+ var qaVisual = false;
796
+ if (step.name === "QA") {
797
+ qaVisual = (await resolveExperiential()) === "yes" && PUBLISH_TYPE === "artifact";
798
+ }
799
+
253
800
  var safeTitle = taskTitle.replace(/"/g, "'").replace(/\\/g, "\\\\").replace(/`/g, "'");
254
801
  var instructions = "";
255
802
 
256
803
  if (step.name === "Triage") {
257
- instructions = "Validate the task, check clarity, note dependencies, confirm the bugfix workflow assignment.\nIf the task needs decomposition, note that in your assessment.\nYour final response MUST be valid JSON and nothing else: { \"summary\": \"your assessment\", \"passed\": true }. No prose, no markdown, just the JSON object.";
804
+ instructions = "Validate the task, check clarity, note dependencies, confirm the bugfix workflow assignment.\nIf the task needs decomposition, note that in your assessment.\nReport back in plain prose what you found.\nEXPERIENTIAL FLAG: does this task change anything rendered and visible in the project's user-facing artifact (pages, components, styles, layout, copy, visual states)? If yes it is experiential and gets baseline captures (plus a visual verdict where the workflow has a QA phase). End your report with exactly one line on its own, lowercase, unrephrased: experiential: yes — or experiential: no. This line is machine-read.";
258
805
 
259
806
  } else if (step.name === "Reproduce") {
260
807
  instructions = "Reproduce the bug from a user's perspective. You are CODE-BLIND — do NOT read source code.\n" +
@@ -263,82 +810,88 @@ while (i < STEPS.length) {
263
810
  "You can also check specific sessions with the getevents action for evidence.\n" +
264
811
  "Do NOT use artifact_inspect — it is async and will not return results inline.\n" +
265
812
  "Capture concrete evidence from the data you retrieve.\n" +
266
- "If reproduction succeeds, your final response MUST be valid JSON and nothing else: { \"passed\": true, \"summary\": \"reproduction evidence and steps\" }.\n" +
267
- "If reproduction fails, your final response MUST be valid JSON and nothing else: { \"passed\": false, \"summary\": \"what you tried and why reproduction failed\" }.\n" +
268
- "No prose, no markdown, just the JSON object.";
813
+ "Report your reproduction evidence and steps as plain prose.\n" +
814
+ "End your report with exactly one line: VERDICT: PASS if reproduction succeeded, VERDICT: FAIL if it failed.";
269
815
 
270
816
  } else if (step.name === "Map") {
271
- instructions = "Update the task with a solution-oriented spec. Research options, pick the shortest path.\nThe builder will edit source files in a git worktree.\nProject: " + PROJECT_DESC + "\nWrite it clearly enough that the builder does not need to ask questions.\nYour final response MUST be valid JSON and nothing else: { \"summary\": \"what you specified\", \"passed\": true }. No prose, no markdown, just the JSON object.";
817
+ var mapGatePara = "";
818
+ if (mapBaselineRefs || mapBaselineNone) {
819
+ mapGatePara = "\nBASELINE GATE (experiential task): " +
820
+ (mapBaselineNone
821
+ ? "no baseline was capturable (baseline: none recorded) — write the spec without baseline comparison and note it."
822
+ : "pre-change baseline captures: " + mapBaselineRefs + " — consult the affected views when writing the spec.") +
823
+ " If the baseline evidence is missing with no baseline:none recorded, do not write the spec — report 'baseline evidence missing — Map gate bounce required' and stop.\n" +
824
+ "Declare capture targets for the post-change visual capture: end your report with a line `capture_targets: <comma-separated views/controls this change affects>` (optional; falls back to the task description).";
825
+ }
826
+ instructions = "Update the task with a solution-oriented spec. Research options, pick the shortest path.\nThe builder will edit source files in a git worktree.\nProject: " + PROJECT_DESC + "\nWrite it clearly enough that the builder does not need to ask questions.\nReport back in plain prose — what you specified." + mapGatePara;
272
827
 
273
828
  } else if (step.name === "Build") {
274
829
  instructions = "STEP 1: Prepare your worktree.\n" +
275
- "Run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " prepare " + taskId + "\n" +
276
- "If the output says CREATED or REUSED, proceed. If it says ERROR, stop and set passed to false.\n\n" +
830
+ "Run: "+ LIFECYCLE_ENV + " prepare " + taskId + "\n" +
831
+ "If the output says CREATED or REUSED, proceed. If it says ERROR, stop and report the failure clearly.\n\n" +
277
832
  "STEP 2: Edit source files to implement the mapper's spec below.\n" +
278
833
  (mapperSpec ? "MAPPER'S SPEC (implement exactly this):\n" + mapperSpec + "\n\n" : "") +
279
- "Your working directory: " + REPO_PATH + "/.worktrees/" + taskId + "/\n" +
834
+ "Your working directory: " + WORKTREE_HINT + "/\n" +
280
835
  "This is the project source: " + PROJECT_DESC + "\n" +
281
836
  "Edit the TypeScript source files directly. Do NOT use artifact_edit — that happens in the Publish phase.\n" +
282
837
  "Do not add unrequested features. Build exactly what the spec calls for.\n" +
283
838
  "PUBLIC DOCS: If your change is public-affecting (it alters anything a user or consumer can observe: API actions, parameters, behavior, or errors), update the public docs in the same commit — API.md for API changes. Documentation and implementation ship together.\n\n" +
284
- (PUBLISH_TYPE === "npm" ? "PACKAGE VERSION: this project publishes to the npm registry. Versions are assigned at PUBLISH time — never in your branch. Do NOT touch the `version` field in package.json (or package-lock). Instead, end your summary with exactly these two lines:\n" +
839
+ (PUBLISH_TYPE === "npm" ? "PACKAGE VERSION: this project publishes to the npm registry. Versions are assigned at PUBLISH time — never in your branch. Do NOT touch the `version` field in package.json (or package-lock). Instead, end your report with exactly these two lines:\n" +
285
840
  "release: yes|no — 'yes' if this change warrants a published release (anything a consumer can observe: workflow behavior, phase lists, identities, published docs, API); 'no' if internal-only.\n" +
286
841
  "version_bump: patch|minor|major — patch for fixes (default), minor for new behavior, major for breaking changes. Omit this line only when release is no.\n" +
287
842
  "Example: release: yes\\nversion_bump: minor\n\n" : "") +
288
843
  "STEP 3: Commit your changes.\n" +
289
- "cd " + REPO_PATH + "/.worktrees/" + taskId + "\n" +
844
+ "cd " + WORKTREE_HINT + "\n" +
290
845
  "git add -A\n" +
291
846
  "git commit -m \"fix: " + safeTitle + "\"\n\n" +
292
- "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 summary, naming the runtime-state deliverable. Otherwise commit your changes normally.\n\n" +
847
+ "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" +
293
848
  (rejectionNotes ? "This is REWORK after rejection. Address these specific issues:\n" + rejectionNotes + "\n\n" : "") +
294
- "Your final response MUST be valid JSON and nothing else: { \"summary\": \"what you built\", \"passed\": true }. No prose, no markdown, just the JSON object.";
849
+ "Report back in plain prose: what you built and the outcome." +
850
+ (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.");
295
851
 
296
852
  } else if (step.name === "Review") {
297
853
  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" +
298
854
  (mapperSpec ? "MAPPER'S SPEC (the builder was asked to implement exactly this):\n" + mapperSpec + "\n\n" : "Read the spec (from the task description or spec files under " + crewHome + "/).\n\n") +
299
855
  "Examine the code changes by running:\n" +
300
- "CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " inspect " + taskId + "\n\n" +
856
+ LIFECYCLE_ENV + LIFECYCLE + " inspect " + taskId + "\n\n" +
301
857
  "The inspect output is authoritative: it prints the task branch's actual tip commit (TIP) and every commit ahead of main. Base your review ONLY on this output — do NOT run git log yourself to pick commits, and do NOT discuss commit hashes from any other source (they may come from stale rework rounds or a different repo).\n\n" +
302
858
  "You can also read specific files in the worktree at:\n" +
303
- REPO_PATH + "/.worktrees/" + taskId + "/\n\n" +
859
+ WORKTREE_HINT + "/\n\n" +
304
860
  "Check quality, correctness, and spec compliance.\n" +
305
- "Check that public-affecting changes have matching public doc updates (API.md or the published API contract). If the docs are missing or inaccurate, reject with notes on what is stale.\n" +
306
- "If the branch has no commits ahead of main (inspect shows an empty commit log), approve ONLY if the Build summary declares `repo_diff: none` with a plausible runtime-state deliverable (e.g. a cron created via the cron tool). Otherwise reject: 'no commits ahead of main and no repo_diff: none declaration — the builder likely forgot to commit'.\n" +
861
+ "Check that public-affecting changes have matching public doc updates (API.md or the published API contract). If the docs are missing or inaccurate, report what is stale, then end your report with exactly this line: VERDICT: FAIL.\n" +
862
+ "If the branch has no commits ahead of main (inspect shows an empty commit log), approve ONLY if the Build summary declares `repo_diff: none` with a plausible runtime-state deliverable (e.g. a cron created via the cron tool). Otherwise report 'no commits ahead of main and no repo_diff: none declaration — the builder likely forgot to commit', then end your report with exactly this line: VERDICT: FAIL.\n" +
307
863
  (PUBLISH_TYPE === "npm" ? "PACKAGE VERSION: this project publishes to the npm registry, and versions are assigned at publish time — never in branches. Two checks:\n" +
308
- "(a) The task branch must NOT have changed package.json's `version` field. Check: cd " + REPO_PATH + " && git diff main...task/" + taskId + " -- package.json. If the branch touched `version` in any way, REJECT with notes: 'versions are assigned at publish time, never in branches — remove the version change'.\n" +
309
- "(b) The accepted Build summary declares: " + releaseDecisionText() + ". " +
864
+ "(a) The task branch must NOT have changed package.json's `version` field. Check: cd " + REPO_PATH + " && git diff main..." + TASK_BRANCH + " -- package.json. If the branch touched `version` in any way, report 'versions are assigned at publish time, never in branches — remove the version change' in your notes, then end your report with exactly this line: VERDICT: FAIL.\n" +
865
+ "(b) The accepted Build report declares: " + releaseDecisionText() + ". " +
310
866
  (releaseDecision
311
- ? "Validate this decision against the change: release must be 'yes' when the change is consumer-observable and 'no' when internal-only; the version_bump scope must fit the change (patch for fixes, minor for new behavior, major for breaking changes). If the decision is wrong or mis-scoped, reject with notes."
312
- : "The decision is missing or malformed — REJECT with notes: 'Build summary must end with release: yes|no and (when release is yes) version_bump: patch|minor|major lines'.") + "\n" : "") +
313
- "If the work passes review, your final response MUST be valid JSON and nothing else: { \"passed\": true, \"summary\": \"approval notes\" }.\n" +
314
- "If the work fails review, your final response MUST be valid JSON and nothing else: { \"passed\": false, \"summary\": \"rejection notes explaining what needs to change\" }.\n" +
315
- "No prose, no markdown, just the JSON object.";
867
+ ? "Validate this decision against the change: release must be 'yes' when the change is consumer-observable and 'no' when internal-only; the version_bump scope must fit the change (patch for fixes, minor for new behavior, major for breaking changes). If the decision is wrong or mis-scoped, report your notes, then end with exactly this line: VERDICT: FAIL."
868
+ : "The decision is missing or malformed — report 'Build report must end with release: yes|no and (when release is yes) version_bump: patch|minor|major lines', then end with exactly this line: VERDICT: FAIL.") + "\n" : "") +
869
+ "Write your review as plain prose — findings, then decision. End your report with exactly one line: VERDICT: PASS if the work passes, VERDICT: FAIL if it fails.";
316
870
 
317
871
  } else if (step.name === "Integrate") {
318
872
  instructions = "Merge the approved task branch into main.\n\n" +
319
- "Run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " integrate " + taskId + " \"merge: fix: " + safeTitle + "\"\n\n" +
873
+ "Run: "+ LIFECYCLE_ENV + " integrate " + taskId + " \"merge: fix: " + safeTitle + "\"\n\n" +
320
874
  "Read the output:\n" +
321
875
  "- If it contains MERGED, integration succeeded. Report the merged commit hash.\n" +
322
- "- If it contains MERGED_EMPTY, the branch had no commits ahead of main (a runtime-state deliverable, declared by Build as repo_diff: none). Integration succeeded vacuously: the merge lock was NOT taken and there is no new commit. Set passed to true with summary 'merged empty: no repo changes — deliverable was runtime state'. SKIP STEP 2 (push): there is no new commit to push.\n" +
323
- "- If it contains LOCK_HELD, another task holds the merge lock (mid Integrate/Publish). Set passed to false.\n" +
876
+ "- If it contains MERGED_EMPTY, the branch had no commits ahead of main (a runtime-state deliverable, declared by Build as repo_diff: none). Integration succeeded vacuously: the merge lock was NOT taken and there is no new commit. Report 'merged empty: no repo changes — deliverable was runtime state', then end your report with exactly this line: VERDICT: PASS. SKIP STEP 2 (push): there is no new commit to push.\n" +
877
+ "- If it contains LOCK_HELD, another task holds the merge lock (mid Integrate/Publish). Report 'merge lock held', then end your report with exactly this line: VERDICT: FAIL.\n" +
324
878
  "- If it contains CONFLICT, the plain merge failed — the merge was aborted, main is clean, and your task still holds the merge lock. Do NOT fail yet. Resolve it:\n" +
325
879
  "RESOLUTION:\n" +
326
- "R1. Refresh the merge lock FIRST (a long resolution must not silently lose the lock to the orphan sweep): CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " refresh-lock " + taskId + ". Create a scratch worktree WITH A NEW BRANCH (main is already checked out in the repo checkout, so git forbids checking it out a second time): cd " + REPO_PATH + " && git worktree add -b resolve/" + taskId + " /tmp/crew-resolve-" + taskId + " main. Reproduce the conflict in the scratch worktree: cd /tmp/crew-resolve-" + taskId + " && git merge task/" + taskId + ". This reproduces the exact conflict (main has not moved — the lock was held throughout). The task branch task/" + taskId + " is never modified.\n" +
880
+ "R1. Refresh the merge lock FIRST (a long resolution must not silently lose the lock to the orphan sweep): "+ LIFECYCLE_ENV + " refresh-lock " + taskId + ". Create a scratch worktree WITH A NEW BRANCH (main is already checked out in the repo checkout, so git forbids checking it out a second time): cd " + REPO_PATH + " && git worktree add -b resolve/" + taskId + " /tmp/crew-resolve-" + taskId + " main. Reproduce the conflict in the scratch worktree: cd /tmp/crew-resolve-" + taskId + " && git merge " + TASK_BRANCH + ". This reproduces the exact conflict (main has not moved — the lock was held throughout). The task branch " + TASK_BRANCH + " is never modified.\n" +
327
881
  "R2. For each conflicted file, read the three sides: git show :1:<file> (base), git show :2:<file> (ours = main), git show :3:<file> (theirs = task branch). Resolve each hunk by keeping both sides' changes when they do not semantically overlap. Version-only hunks resolve to the higher semver (safety net). Never invent new behavior. Leave no markers.\n" +
328
- "R3. Verify in the scratch worktree, in this order: (a) git diff --check is clean; (b) git grep -n '^<<<<<<<' -- . returns nothing; (c) node --check every changed .js file (conflicted files plus everything listed by git diff --name-only). If any check fails, refresh the merge lock (CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " refresh-lock " + taskId + "), then retry the resolution using the failure output as context — max 3 attempts total.\n" +
882
+ "R3. Verify in the scratch worktree, in this order: (a) git diff --check is clean; (b) git grep -n '^<<<<<<<' -- . returns nothing; (c) node --check every changed .js file (conflicted files plus everything listed by git diff --name-only). If any check fails, refresh the merge lock ("+ LIFECYCLE_ENV + " refresh-lock " + taskId + "), then retry the resolution using the failure output as context — max 3 attempts total.\n" +
329
883
  "R4. Commit the resolution on resolve/" + taskId + ": git add -A && git commit -m \"resolve conflicts: " + taskId + "\".\n" +
330
884
  "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" +
331
885
  "R6. Clean up: cd " + REPO_PATH + " && git worktree remove --force /tmp/crew-resolve-" + taskId + " && git branch -D resolve/" + taskId + ".\n" +
332
- "ESCALATE — return {\"passed\": false, \"summary\": \"conflict needs human resolution\"} — 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" +
333
- "- If it contains ERROR, something else failed. Set passed to false.\n\n" +
886
+ "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" +
887
+ "- If it contains ERROR, something else failed. Report the error, then end your report with exactly this line: VERDICT: FAIL.\n\n" +
334
888
  "\n" +
335
889
  "STEP 2: Push the merged main to the remote repository.\n" +
336
890
  "Run: cd " + REPO_PATH + " && git push origin main\n" +
337
891
  "- If the push succeeds, report the merged commit hash.\n" +
338
892
  "- If the push is rejected as non-fast-forward (the remote has commits not present locally),\n" +
339
- " NEVER force-push. Do not run any --force variant. Set passed to false with summary:\n" +
340
- " 'git push origin main rejected as non-fast-forwardremote main has diverged; manual resolution required'.\n\n" +
341
- "Your final response MUST be valid JSON and nothing else: { \"summary\": \"result\", \"passed\": true/false }. No prose, no markdown, just the JSON object.";
893
+ " 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" +
894
+ "Report back in plain prose what happened at each step and end your report with exactly one line: VERDICT: PASS or VERDICT: FAIL.";
342
895
 
343
896
  } else if (step.name === "Publish") {
344
897
  if (PUBLISH_TYPE === "npm") {
@@ -356,74 +909,199 @@ while (i < STEPS.length) {
356
909
  " CREW_HOME=" + crewHome + " LIFECYCLE=" + LIFECYCLE + " RELEASE_SCRIPT=" + RELEASE_SCRIPT +
357
910
  " bash " + PUBLISH_NPM + "\n\n" +
358
911
  "Do NOT run npm, npm pack, npm publish, or the python publish script yourself. Do NOT compare local and registry versions. Do NOT decide whether to publish.\n\n" +
359
- "If the command exits nonzero, set passed to false and put the script's PUBLISH_FAILED line in your summary.\n" +
360
- "If it exits zero, paste the script's COMPLETE marker block verbatim into your summary, then end your summary with exactly these two lines, in this order — lowercase, no trailing period, do not rephrase (the QA backstop extracts them by pattern):\n" +
912
+ "If the command exits nonzero, put the script's PUBLISH_FAILED line in your report, then end your report with exactly this line: VERDICT: FAIL.\n" +
913
+ "If it exits zero, paste the script's COMPLETE marker block verbatim into your report, then end your report with exactly these three lines, in this order — lowercase, no trailing period, do not rephrase:\n" +
361
914
  "TARGET_VERSION=" + publishTarget.target + " computed as " + publishTarget.base + " + " + publishTarget.scope + " → " + publishTarget.target + "\n" +
362
- "published: muse-crew@" + publishTarget.target + "\n\n" +
363
- "Your final response MUST be valid JSON and nothing else: { \"summary\": \"result\", \"passed\": true }.\n" +
364
- "No prose, no markdown, just the JSON object.";
365
- } else if (PUBLISH_TYPE === "artifact") {
366
- // Artifact projects: rebuild the live artifact via artifact_edit, then finalize
915
+ "published: muse-crew@" + publishTarget.target + "\n" +
916
+ "VERDICT: PASS\n\n";
917
+ } else if (PUBLISH_TYPE === "artifact") {
918
+ // Deterministic artifact publish (canary b5efd1b1, 2026-09-10): the work
919
+ // agent claimed "Rebuilt and deployed" while no build ran and no
920
+ // provenance was stamped — prose-trusted side effects, the same failure
921
+ // class as the npm double-skip (bb739316). The npm path already runs one
922
+ // deterministic script; the artifact path now has the same shape. Lock
923
+ // refresh, rebuild trigger, build-completion poll, provenance stamp, and
924
+ // post-deploy are narrow schema'd bookkeeping calls owned by the
925
+ // workflow — the work agent reports on the mechanical outcome and
926
+ // cannot skip what it never owned. Any step failing parks with an
927
+ // honest, step-specific reason (fail-closed). The post-hoc
928
+ // getprovenance-vs-HEAD verification below stays as the final gate.
929
+ var artifactPublish = null;
930
+ var publishLockRefreshed = false;
931
+ try {
932
+ // STEP 0 (mechanical): refresh the merge lock so a long build cannot
933
+ // go stale mid-publish.
934
+ var lockRefresh = await agent(
935
+ "Run: "+ LIFECYCLE_ENV + " refresh-lock " + taskId + "\n" +
936
+ "Return JSON { \"refreshed\": <true if the command exited zero, false otherwise>, \"output\": \"<trimmed stdout>\" } and nothing else.",
937
+ { key: attemptKey("publish-lock-refresh-" + taskId, totalReworkCount), label: "Refreshing merge lock for publish",
938
+ schema: { type: "object", properties: { refreshed: { type: "boolean" }, output: { type: "string" } }, required: ["refreshed"] } }
939
+ );
940
+ if (!lockRefresh.refreshed) {
941
+ return await parkTask("Publish lock refresh failed: " + (lockRefresh.output || "no output") + ". Fail-closed — lock state unknown.");
942
+ }
943
+ publishLockRefreshed = true;
944
+ // STEP 1 (mechanical): trigger the rebuild with one narrow call. The
945
+ // agent only makes the artifact_edit call and reports whether it was
946
+ // accepted — no prose claim to trust. If the artifact tool namespace
947
+ // is missing from this child it reports honestly and the workflow
948
+ // retries once with a fresh key (bounded); anything else parks.
949
+ var rebuildPrompt =
950
+ "Call artifact_edit with slug \"" + PUBLISH_SLUG + "\" and verbatim_request:\n" +
951
+ "'Rebuild the application from current source. Do not modify any source files — just rebuild and deploy what is on disk.'\n" +
952
+ "If the artifact_edit tool is not available in this session, do NOT improvise — return { \"edit_started\": false, \"error\": \"artifact_edit unavailable\" }.\n" +
953
+ "Make no other calls. Return JSON { \"edit_started\": <true if the edit was accepted, false otherwise>, \"error\": \"<details or empty string>\" } and nothing else.";
954
+ var rebuildSchema =
955
+ { type: "object", properties: { edit_started: { type: "boolean" }, error: { type: "string" } }, required: ["edit_started"] };
956
+ var rebuildTrigger = await agent(rebuildPrompt,
957
+ { key: attemptKey("publish-artifact-rebuild-" + taskId, totalReworkCount), label: "Triggering artifact rebuild", schema: rebuildSchema });
958
+ if (!rebuildTrigger.edit_started && rebuildTrigger.error === "artifact_edit unavailable") {
959
+ log("Publish rebuild trigger: artifact_edit unavailable — one bounded retry with a fresh key");
960
+ rebuildTrigger = await agent(rebuildPrompt,
961
+ { key: attemptKey("publish-artifact-rebuild-" + taskId + "-retry1", totalReworkCount), label: "Triggering artifact rebuild (retry)", schema: rebuildSchema });
962
+ }
963
+ var publishFailure = null;
964
+ if (rebuildTrigger.edit_started) {
965
+ // STEP 1b (mechanical): bounded poll for build completion.
966
+ var buildPoll = await agent(
967
+ "Poll artifact_status for slug \"" + PUBLISH_SLUG + "\" until no build is running. Check every 30 seconds, up to 20 checks (10 minutes max).\n" +
968
+ "Return JSON { \"build_done\": <true if no build is running within budget, false on timeout>, \"status\": \"<final status or timeout note>\" } and nothing else.",
969
+ { key: attemptKey("publish-artifact-poll-" + taskId, totalReworkCount), label: "Waiting for artifact build to complete",
970
+ schema: { type: "object", properties: { build_done: { type: "boolean" }, status: { type: "string" } }, required: ["build_done"] },
971
+ timeoutMs: 660000 }
972
+ );
973
+ if (buildPoll.build_done) {
974
+ // STEP 1c (mechanical): stamp provenance from workflow-computed values.
975
+ var provStamp = await agent(
976
+ "Run: cd " + REPO_PATH + " && git rev-parse HEAD — call this SRC.\n" +
977
+ "Run: basename $(readlink " + crewHome + "/current) — call this REL.\n" +
978
+ "Run: date -u +%Y-%m-%dT%H:%M:%SZ — call this TS.\n" +
979
+ "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"setprovenance\", args:\n" +
980
+ "{ \"source_commit\": \"<SRC trimmed>\", \"crew_release\": \"<REL trimmed>\", \"published_at\": \"<TS trimmed>\", \"task_id\": \"" + taskId + "\" }.\n" +
981
+ "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.",
982
+ { key: attemptKey("publish-artifact-stamp-" + taskId, totalReworkCount), label: "Stamping artifact provenance",
983
+ 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"] } }
984
+ );
985
+ if (provStamp.stamped) {
986
+ artifactPublish = { source_commit: provStamp.source_commit, crew_release: provStamp.crew_release, published_at: provStamp.published_at };
987
+ } else {
988
+ publishFailure = "Provenance stamp failed after a completed build (source_commit " + (provStamp.source_commit || "unknown") + "). The build landed but is unstamped — fail-closed.";
989
+ }
990
+ } else {
991
+ publishFailure = "Artifact build did not complete within budget: " + (buildPoll.status || "timeout") + ". The publish may or may not have landed — provenance was not stamped.";
992
+ }
993
+ } else {
994
+ publishFailure = "Artifact rebuild trigger failed: " + (rebuildTrigger.error || "artifact_edit not accepted") + ". The publish did not land.";
995
+ }
996
+ // STEP 2 (mechanical, always once the lock was refreshed): post-deploy
997
+ // commits builder leftovers if any, removes the worktree, and releases
998
+ // the merge lock — even when the publish itself failed, so a skipped
999
+ // or failed publish can never leave the lock held (canary b5efd1b1).
1000
+ var postDeploy = await agent(
1001
+ "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
1002
+ "Return JSON { \"deployed\": <true if the output contains DEPLOYED, false otherwise>, \"output\": \"<trimmed output>\" } and nothing else.",
1003
+ { key: attemptKey("publish-postdeploy-" + taskId, totalReworkCount), label: "Finalizing publish (post-deploy)",
1004
+ schema: { type: "object", properties: { deployed: { type: "boolean" }, output: { type: "string" } }, required: ["deployed"] } }
1005
+ );
1006
+ if (publishFailure) {
1007
+ return await parkTask(publishFailure + (postDeploy.deployed
1008
+ ? " Post-deploy finalized cleanup."
1009
+ : " Post-deploy also failed (" + (postDeploy.output || "no output") + ") — worktree and lock state unknown."));
1010
+ }
1011
+ if (!postDeploy.deployed) {
1012
+ 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.");
1013
+ }
1014
+ log("Deterministic artifact publish completed for task " + taskId + ": provenance at " + artifactPublish.source_commit);
1015
+ } catch (pubErr) {
1016
+ // Best-effort cleanup: if the lock was refreshed, try to release it
1017
+ // before parking so the failure cannot wedge the next run.
1018
+ if (publishLockRefreshed) {
1019
+ try {
1020
+ await agent(
1021
+ "Run: "+ LIFECYCLE_ENV + " post-deploy " + taskId + "\n" +
1022
+ "Return JSON { \"deployed\": <true if the output contains DEPLOYED, false otherwise> } and nothing else.",
1023
+ { key: attemptKey("publish-postdeploy-cleanup-" + taskId, totalReworkCount), label: "Releasing lock after publish failure",
1024
+ schema: { type: "object", properties: { deployed: { type: "boolean" } }, required: ["deployed"] } }
1025
+ );
1026
+ } catch (cleanupErr) {
1027
+ log("Publish cleanup post-deploy also failed: " + (cleanupErr && cleanupErr.message ? cleanupErr.message : cleanupErr));
1028
+ }
1029
+ }
1030
+ return await parkTask("Deterministic artifact publish failed: " + (pubErr && pubErr.message ? pubErr.message : pubErr) + ". Fail-closed.");
1031
+ }
1032
+ // The work agent no longer performs the publish — it reports on the
1033
+ // mechanical outcome above. It must not rebuild or re-stamp: a second
1034
+ // artifact_edit would trigger a duplicate build.
367
1035
  instructions = "Publish the merged code to the live artifact.\n\n" +
1036
+ "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" +
1037
+ "For the change summary, run: cd " + REPO_PATH + " && git log -1 --stat\n\n" +
1038
+ "Mechanical outcome (every step succeeded and was verified by the workflow):\n" +
1039
+ "- merge lock refreshed: yes\n" +
1040
+ "- artifact rebuild triggered and completed: yes\n" +
1041
+ "- provenance stamped: yes — source_commit " + artifactPublish.source_commit + ", crew_release " + artifactPublish.crew_release + ", published_at " + artifactPublish.published_at + "\n" +
1042
+ "- post-deploy finalized: yes (worktree removed, merge lock released)\n\n" +
368
1043
  "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" +
369
1044
  "The repo push already happened in Integrate — do NOT push to git in this phase.\n\n" +
370
- "STEP 0: Refresh the merge lock to prevent stale-lock breaking during publish.\n" +
371
- "Run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " refresh-lock " + taskId + "\n\n" +
372
- "STEP 1: Publish to the live artifact.\n" +
373
- "Get the change summary: cd " + REPO_PATH + " && git log -1 --stat\n" +
374
- "Then call artifact_edit with slug \"" + PUBLISH_SLUG + "\" and verbatim_request:\n" +
375
- "'Rebuild the application from current source. Do not modify any source files — just rebuild and deploy what is on disk.'\n" +
376
- "Wait for the build to complete by polling artifact_status until it is no longer running.\n\n" +
377
- "STEP 1B: Stamp publication provenance.\n" +
378
- "Run: cd " + REPO_PATH + " && git rev-parse HEAD\n" +
379
- "Run: basename $(readlink " + crewHome + "/current)\n" +
380
- "Run: date -u +%Y-%m-%dT%H:%M:%SZ\n" +
381
- "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"setprovenance\", args:\n" +
382
- "{ \"source_commit\": \"<rev-parse output>\", \"crew_release\": \"<basename output>\", \"published_at\": \"<date output>\", \"task_id\": \"" + taskId + "\" }.\n" +
383
- "Confirm the response contains ok: true. If setprovenance fails, report it in your summary but still run post-deploy to release the lock.\n\n" +
384
- "STEP 2: Finalize.\n" +
385
- "Run: CREW_REPO=" + REPO_PATH + " " + LIFECYCLE + " post-deploy " + taskId + "\n" +
386
- "If the output contains DEPLOYED, publishing is complete.\n\n" +
387
- "If artifact_edit failed, still run post-deploy to release the merge lock and clean up.\n" +
388
- "Report the failure: { \"passed\": false, \"summary\": \"artifact publish failed: [details]\" }.\n\n" +
389
- "Your final response MUST be valid JSON and nothing else: { \"summary\": \"published changes\", \"passed\": true }.\n" +
390
- "No prose, no markdown, just the JSON object.";
391
- } else if (PUBLISH_TYPE === "vercel") {
1045
+ "Write plain prose describing what was published, then on its own line: VERDICT: PASS\n" +
1046
+ "The VERDICT line must be the last line of your report.";
1047
+ } else if (PUBLISH_TYPE === "vercel") {
392
1048
  // vercel publish is not yet implemented — block without inventing behavior
393
1049
  instructions = "The project's publish target is \"vercel\", which is not yet implemented.\n" +
394
1050
  "Do NOT invent publish behavior — do not guess CLI commands, APIs, or deployment steps.\n" +
395
- "Your final response MUST be valid JSON and nothing else: { \"passed\": false, \"summary\": \"vercel publish not yet implemented\" }.\n" +
396
- "No prose, no markdown, just the JSON object.";
1051
+ "Report the situation in prose, then end your report with exactly this line: VERDICT: FAIL.";
397
1052
  }
398
1053
  } else if (step.name === "QA") {
399
1054
  // Backstop for merge-time versioning: when the accepted Build summary
400
1055
  // declared release: yes, QA verifies the registry actually moved. A silent
401
1056
  // publish skip becomes a loud QA failure with evidence, not a pass.
402
1057
  var npmPublishCheck = (PUBLISH_TYPE === "npm" && releaseDecision && releaseDecision.release === "yes")
403
- ? "NPM PUBLISH CHECK: the accepted Build summary declared release: yes, so this run's Publish phase must have published. 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" +
404
- "Extract the line matching TARGET_VERSION=<new-version> computed as <base> + <scope> → <new-version>. If the line is missing, FAIL with { \"passed\": false, \"summary\": \"npm publish verification failed: Publish summary did not echo its computed target version (STEP 3B)\" }.\n" +
405
- "Verify the bump SCOPE: the <scope> in that line MUST equal the accepted version_bump scope \"" + releaseDecision.version_bump + "\" — if the Publish agent applied a different scope, FAIL. Verify the ARITHMETIC: <base> + <scope> must equal <new-version> (patch increments the last segment only, e.g. 0.3.0 + patch → 0.3.1; minor increments the middle and resets the last to 0; major increments the first and resets the rest to 0) — if the math is wrong, FAIL.\n" +
406
- "Extract the published version from the notes line matching published: muse-crew@<version> (match case-insensitively and ignore any trailing period — agents sometimes rephrase it). It MUST equal <new-version> from the TARGET_VERSION line. Then run: npm view muse-crew version. The registry version MUST equal <new-version>. If any of these checks fails, FAIL with { \"passed\": false, \"summary\": \"npm publish verification failed: [details]\" }.\n"
1058
+ ? "NPM PUBLISH CHECK: the accepted Build report declared release: yes, so this run's Publish phase must have published. 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" +
1059
+ "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" +
1060
+ "Verify the bump SCOPE: the <scope> in that line MUST equal the accepted version_bump scope \"" + releaseDecision.version_bump + "\" — if it differs, report the mismatch, then end your report with exactly this line: VERDICT: FAIL. Verify the ARITHMETIC: <base> + <scope> must equal <new-version> (patch increments the last segment only, e.g. 0.3.0 + patch → 0.3.1; minor increments the middle and resets the last to 0; major increments the first and resets the rest to 0) — if the math is wrong, report it, then end your report with exactly this line: VERDICT: FAIL.\n" +
1061
+ "Extract the published version from the notes line matching published: muse-crew@<version>. It MUST equal <new-version> from the TARGET_VERSION line. Then run: npm view muse-crew version. The registry version MUST equal <new-version>. If any of these checks fails, report 'npm publish verification failed: [details]', then end your report with exactly this line: VERDICT: FAIL.\n"
407
1062
  : "";
408
1063
  instructions = "Final QA testing. You are CODE-BLIND — do NOT read source code.\n" +
409
1064
  "Public docs (API.md, README, published action schemas) are NOT source code — read them freely, exactly as a user would.\n" +
410
- "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, FAIL with { \"passed\": false, \"summary\": \"public docs missing/stale for [the change]\" }. 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" +
1065
+ "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" +
411
1066
  "To test, use artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\" with action \"getstate\" (args {}) to read current sessions, events, and tasks.\n" +
412
1067
  "Verify the fix by checking that session notes in the returned data now handle newlines correctly.\n" +
413
1068
  "You can also check specific data with the getevents action.\n" +
414
1069
  "Do NOT use artifact_inspect — it is async and will not return results inline.\n" +
415
1070
  "File follow-up tasks via artifact_invoke_action createtask on slug \"" + DASHBOARD_SLUG + "\" for related issues.\n" +
416
1071
  npmPublishCheck +
417
- "If testing passes, your final response MUST be valid JSON and nothing else: { \"passed\": true, \"summary\": \"test results\" }.\n" +
418
- "If testing fails, your final response MUST be valid JSON and nothing else: { \"passed\": false, \"summary\": \"failure details\" }.\n" +
419
- "No prose, no markdown, just the JSON object.";
1072
+ "Report your test results as plain prose.\n" +
1073
+ "End your report with exactly one line: VERDICT: PASS if testing passes, VERDICT: FAIL if it fails.";
1074
+ // Visual verdict ownership (experiential artifact tasks only): the QA
1075
+ // work agent covers the MECHANICAL CHECKS below — it does not call
1076
+ // artifact_inspect (async; the parent triggers the post-change capture
1077
+ // after this step). The visual verdict is produced by the parent after
1078
+ // the rendered post-change inspection results arrive.
1079
+ if (qaVisual) {
1080
+ instructions = "You are code-blind QA. You NEVER read source files. Public docs are not source — read them as a user would.\n" +
1081
+ "VISUAL VERDICT OWNERSHIP: this task is experiential. The visual verdict is NOT yours to issue — it is produced after the rendered post-change inspection results arrive, by Hazel with the baseline and post-change evidence in hand.\n" +
1082
+ "Your VERDICT below covers the MECHANICAL CHECKS only. Do NOT call artifact_inspect.\n\n" +
1083
+ "MECHANICAL CHECKS:\n" +
1084
+ "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" +
1085
+ "To test, use artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\" with action \"getstate\" (args {}) to read current sessions, events, and tasks.\n" +
1086
+ "Verify the fix by checking that session notes in the returned data now handle newlines correctly.\n" +
1087
+ "You can also check specific data with the getevents action.\n" +
1088
+ npmPublishCheck +
1089
+ "File follow-up tasks via artifact_invoke_action createtask on slug \"" + DASHBOARD_SLUG + "\" for related issues.\n\n" +
1090
+ "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" +
1091
+ "Report your test results as plain prose.\n" +
1092
+ "End your report with exactly one line: VERDICT: PASS if testing passes, VERDICT: FAIL if it fails on the mechanical checks.";
1093
+ }
420
1094
  if (PUBLISH_TYPE === "artifact") {
421
1095
  instructions = "PROVENANCE CHECK (this project publishes to a dashboard artifact).\n" +
422
1096
  "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"getprovenance\", args: {}.\n" +
423
- "If provenance is null, FAIL: { \"passed\": false, \"summary\": \"provenance missing — publish did not stamp\" }.\n" +
424
- "Run: cd " + REPO_PATH + " && git rev-parse HEAD\n" +
425
- "Run: basename $(readlink " + crewHome + "/current)\n" +
426
- "If either hash mismatches, FAIL: { \"passed\": false, \"summary\": \"provenance mismatch: [details]\" }.\n\n" +
1097
+ "If provenance is null, report 'provenance missing — publish did not stamp', then end your report with exactly this line: VERDICT: FAIL.\n" +
1098
+ "Run: cd " + REPO_PATH + " && git rev-parse HEAD — call this LIVE_HEAD.\n" +
1099
+ "Run: basename $(readlink " + crewHome + "/current) — call this LIVE_CREW.\n" +
1100
+ "If provenance.crew_release does not equal LIVE_CREW, report 'provenance mismatch: crew_release [value from getprovenance] != [LIVE_CREW]', then end your report with exactly this line: VERDICT: FAIL.\n" +
1101
+ "If provenance.source_commit equals LIVE_HEAD, the source check passes.\n" +
1102
+ "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" +
1103
+ "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" +
1104
+ "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" +
427
1105
  instructions;
428
1106
  }
429
1107
  }
@@ -439,9 +1117,13 @@ while (i < STEPS.length) {
439
1117
  "The returned events are filtered to this task. They contain notes and decisions from prior phases.\n\n";
440
1118
  }
441
1119
 
442
- var stepResult;
443
- try {
444
- stepResult = await agent(
1120
+ // Work agent returns the runtime's native envelope {"status": "ok",
1121
+ // "result": "<prose>"} with no schema. The runtime requires JSON output;
1122
+ // the envelope is its own documented shape, so there is nothing for the
1123
+ // agent to improvise. The workflow receives the prose report as a plain
1124
+ // string. The verdict is still extracted deterministically from the report
1125
+ // text by extractVerdict below — never by an agent.
1126
+ var workPromptBase =
445
1127
  "Read the identity file at " + ORCH_PATH + "/identities/" + step.identity + ".md using the read tool, and embody that character fully.\n\n" +
446
1128
  "## Your Assignment\n\n" +
447
1129
  "Task: " + taskTitle + "\n" +
@@ -451,75 +1133,213 @@ while (i < STEPS.length) {
451
1133
  (step.name !== "Review" ? "Dashboard slug: " + DASHBOARD_SLUG + "\n" : "") +
452
1134
  "\n## Instructions\n\n" + eventPreamble + instructions + "\n\n" +
453
1135
  "CONSTRAINT: Do NOT call logevent or upsertagentsession — the workflow handles all phase tracking after your step completes.\n\n" +
454
- "Stay in character. Do the work thoroughly.",
455
- {
456
- key: "work-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : ""),
457
- label: step.identity + ": " + step.name + " on \"" + taskTitle + "\"",
458
- timeoutMs: 3600000,
459
- schema: WORK_SCHEMA
1136
+ "Stay in character. Do the work thoroughly.\n\n" +
1137
+ "Return your work as JSON in exactly this shape: {\"status\": \"ok\", \"result\": \"your report here\"}. " +
1138
+ "The result is plain prose describing what you did and found. For verdict steps, end the report with exactly one line: VERDICT: PASS or VERDICT: FAIL.";
1139
+ var workKeyBase = "work-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : "");
1140
+ var workerResult = null;
1141
+ var workAttempts = [];
1142
+ for (var workAttempt = 0; workAttempt <= 2; workAttempt++) {
1143
+ var workKey = workAttempt === 0 ? workKeyBase : workRetryKey(step.name, (totalReworkCount > 0 ? "-r" + totalReworkCount : ""), workAttempt);
1144
+ var retryReason = workAttempt === 0 ? null : (workAttempts[workAttempt - 1].threw ? "discarded" : "empty");
1145
+ try {
1146
+ workerResult = await agent(
1147
+ workPromptBase + (workAttempt === 0 ? "" : buildTransportRetryTrailer(step.name, REPO_PATH, taskId, workAttempt, retryReason)),
1148
+ {
1149
+ key: workKey,
1150
+ label: step.identity + ": " + step.name + " on \"" + taskTitle + "\"" + (workAttempt === 0 ? "" : " (transport retry " + workAttempt + " of 2)"),
1151
+ timeoutMs: 3600000
1152
+ }
1153
+ );
1154
+ // Success path: a non-blank string report is usable — keep it and stop
1155
+ // retrying. Without this branch every attempt is discarded and the phase
1156
+ // always fails (regression shipped in ecef136 when Date.now() was
1157
+ // removed from this loop).
1158
+ if (typeof workerResult === "string" && workerResult.trim()) {
1159
+ if (workAttempt > 0) log(step.name + " work agent transport retry " + workAttempt + " returned a machine-readable report");
1160
+ break;
1161
+ }
1162
+ var emptyOutcome = workerResult === null ? "null" : (typeof workerResult === "string" ? "blank string" : typeof workerResult);
1163
+ workAttempts.push({ threw: false, error: "", outcome: emptyOutcome });
1164
+ log(step.name + " work agent attempt " + (workAttempt + 1) + " of 3 returned no usable output (" + emptyOutcome + ") — retrying with a fresh key");
1165
+ workerResult = null;
1166
+ } catch (e) {
1167
+ var attemptErr = (e && e.message ? e.message : String(e)).replace(/"/g, "'").slice(0, 160);
1168
+ workAttempts.push({ threw: true, error: attemptErr, outcome: "" });
1169
+ log(step.name + " work agent attempt " + (workAttempt + 1) + " of 3 threw: " + attemptErr);
1170
+ workerResult = null;
460
1171
  }
461
- );
462
- } catch (e) {
463
- log(step.name + " agent failed: " + (e.message || String(e)).slice(0, 500));
464
- stepResult = null;
465
1172
  }
1173
+ // The report arrives as a plain string — the runtime unwraps the envelope.
1174
+ var workerText = (typeof workerResult === "string") ? workerResult : null;
466
1175
 
467
- // If schema retries were exhausted, block gracefully
468
- if (!stepResult || typeof stepResult.summary !== "string") {
469
- log(step.name + " closeout unrecoverableblocking");
1176
+ if (typeof workerText !== "string" || !workerText.trim()) {
1177
+ var workFailure = describeWorkAgentFailure(step.name, step.identity, workAttempts);
1178
+ log(step.name + " " + workFailure.notes + " marking failed for retry");
470
1179
  await agent(
471
- "Record closeout failure.\n" +
1180
+ "Record work failure.\n" +
472
1181
  "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
473
- "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"blocked\", \"notes\": \"Agent failed to return structured result after retries\" }.\n" +
1182
+ "{ \"id\": \"" + activeSessionId + "\", \"task_id\": \"" + taskId + "\", \"identity\": \"" + step.identity + "\", \"step\": \"" + step.name + "\", \"status\": \"failed\", \"notes\": \"" + workFailure.notes + "\" }.\n" +
474
1183
  "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
475
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"blocked\", \"message\": \"" + step.name + " agent failed after retries — workflow blocked\" }.",
476
- { key: "record-block-" + step.name, label: "Recording closeout failure", schema: { type: "object" } }
1184
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"message\": \"" + workFailure.eventMessage + "\" }.",
1185
+ { key: "record-block-" + step.name, label: "Recording work failure", schema: { type: "object" } }
477
1186
  );
478
1187
  return {
479
1188
  __hatchWorkflowControl: "blocked",
480
1189
  result: {
481
- blocked_reason: step.name + " agent failed after retries",
482
- message: "The " + step.identity + " agent's work may be valid — structured output failed.",
1190
+ blocked_reason: workFailure.blockedReason,
1191
+ message: workFailure.message,
483
1192
  task_id: taskId
484
1193
  }
485
1194
  };
486
1195
  }
1196
+ // Verdict derivation (deterministic): for VERDICT_STEPS the workflow owns
1197
+ // the verdict — extracted by regex from the trailing window from the worker's own report.
1198
+ // A missing, malformed, or contradictory VERDICT line first gets a bounded
1199
+ // mechanical re-ask (reaskVerdict); only if that is exhausted does the phase
1200
+ // fail closed (blocked):
1201
+ // On verdict failure the session is marked "failed", NOT "blocked":
1202
+ // the dispatcher retries failed sessions at the same step, while a
1203
+ // "blocked" session is never picked up again (blocked is reserved for
1204
+ // unmet dependencies). The __hatchWorkflowControl: "blocked" return below
1205
+ // stays — that is the runtime's halt-the-run signal, a separate vocabulary.
1206
+ var verdictPassed = null;
1207
+ if (VERDICT_STEPS.indexOf(step.name) >= 0) {
1208
+ var verdict = extractVerdict(workerText);
1209
+ if (!verdict.ok) {
1210
+ // Bounded mechanical re-ask before failing the phase: the report may
1211
+ // be valid with a stochastically omitted or garbled verdict line.
1212
+ log(step.name + " verdict line missing or ambiguous (" + verdict.count + " trailing-window matches) — attempting bounded re-ask");
1213
+ verdict = await reaskVerdict(step.name, (totalReworkCount > 0 ? "-r" + totalReworkCount : ""), workerText);
1214
+ }
1215
+ if (!verdict.ok) {
1216
+ log(step.name + " verdict re-ask exhausted — marking failed for retry");
1217
+ await agent(
1218
+ "Record verdict failure.\n" +
1219
+ "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"upsertagentsession\", args:\n" +
1220
+ "{ \"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" +
1221
+ "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
1222
+ "{ \"task_id\": \"" + taskId + "\", \"type\": \"failed\", \"message\": \"" + step.name + " verdict line missing or ambiguous, re-ask exhausted — phase failed, dispatcher will retry\" }.",
1223
+ { key: "record-block-" + step.name, label: "Recording verdict failure", schema: { type: "object" } }
1224
+ );
1225
+ return {
1226
+ __hatchWorkflowControl: "blocked",
1227
+ result: {
1228
+ blocked_reason: step.name + " worker report had no single unambiguous VERDICT: PASS/FAIL line (bounded re-ask exhausted)",
1229
+ message: "The " + step.identity + " agent's work may be valid — its report did not declare a verdict the workflow could read, and two bounded re-ask attempts could not transcribe one. The report is preserved in the workflow log.",
1230
+ task_id: taskId
1231
+ }
1232
+ };
1233
+ }
1234
+ verdictPassed = verdict.passed;
1235
+ }
487
1236
 
488
- const summary = (stepResult.summary || "Step completed").slice(0, 2000);
489
- const passed = stepResult.passed !== false;
490
- const status = passed ? "completed" : "rejected";
1237
+ // Deterministic closeout: no formatter agent. The verdict is mechanical
1238
+ // (extractVerdict above); the summary is the worker's report truncated.
1239
+ // For verdict steps passed comes from the verdict; for non-verdict steps
1240
+ // the worker producing output means the step passed.
1241
+ var stepResult = {
1242
+ passed: verdictPassed !== null ? verdictPassed : true,
1243
+ summary: workerText
1244
+ };
1245
+ const passed = stepResult.passed === true;
1246
+ // "rejected" is an explicit phase verdict routed through rework (Review/QA,
1247
+ // and the Build/Reproduce reports that feed them). Integrate/Publish work
1248
+ // that did not finish is operational — "failed", retryable under the
1249
+ // dispatcher's consecutive-failure cap.
1250
+ const status = passed ? "completed" : (step.name === "Integrate" || step.name === "Publish" ? "failed" : "rejected");
491
1251
 
492
1252
  // Deterministic publish verification: the agent cannot self-certify a publish.
1253
+ var publishVerified = false;
493
1254
  if (step.name === "Publish" && PUBLISH_TYPE === "npm" && publishTarget) {
494
1255
  try {
495
1256
  var verifyResult = await agent(
496
1257
  "Run: npm view muse-crew version 2>/dev/null. Return JSON { \"registry_version\": \"<output trimmed>\" } and nothing else.",
497
- { key: "verify-publish-" + taskId, label: "Verifying published version",
1258
+ { key: attemptKey("verify-publish-" + taskId, totalReworkCount), label: "Verifying published version",
498
1259
  schema: { type: "object", properties: { registry_version: { type: "string" } }, required: ["registry_version"] } }
499
1260
  );
500
1261
  var regVer = (verifyResult.registry_version || "").trim();
501
1262
  if (regVer !== publishTarget.target) {
502
- return { status: "blocked", task_id: taskId,
503
- reason: "Publish verification failed: registry shows " + regVer + " but the release decision required " +
504
- publishTarget.target + " (" + publishTarget.base + " + " + publishTarget.scope + "). The publish did not land." };
1263
+ return await parkTask("Publish verification failed: registry shows " + regVer + " but the release decision required " +
1264
+ publishTarget.target + " (" + publishTarget.base + " + " + publishTarget.scope + "). The publish did not land.");
505
1265
  }
506
1266
  log("Publish verified for task " + taskId + ": registry at " + regVer);
1267
+ publishVerified = true;
507
1268
  } catch (e) {
508
- return { status: "blocked", task_id: taskId,
509
- reason: "Publish verification failed: could not read the registry version (" + (e && e.message ? e.message : e) + "). Fail-closed." };
1269
+ return await parkTask("Publish verification failed: could not read the registry version (" + (e && e.message ? e.message : e) + "). Fail-closed.");
510
1270
  }
511
1271
  }
512
1272
 
1273
+ // Artifact publish verification: the worker cannot self-certify a deploy.
1274
+ // The workflow reads the artifact's provenance and confirms it points at the
1275
+ // integrated commit. A stale or missing provenance means the publish did not
1276
+ // land — fail closed, do not trust the worker's prose.
1277
+ if (step.name === "Publish" && PUBLISH_TYPE === "artifact" && PUBLISH_SLUG) {
1278
+ try {
1279
+ var headResult = await agent(
1280
+ "Run: cd " + REPO_PATH + " && git rev-parse HEAD. Return JSON { \"head\": \"<output trimmed>\" } and nothing else.",
1281
+ { key: attemptKey("verify-publish-head-" + taskId, totalReworkCount), label: "Reading integrated commit",
1282
+ schema: { type: "object", properties: { head: { type: "string" } }, required: ["head"] } }
1283
+ );
1284
+ var expectedCommit = (headResult.head || "").trim();
1285
+ var provResult = await agent(
1286
+ "Call artifact_invoke_action on slug \"" + PUBLISH_SLUG + "\", action \"getprovenance\", args: {}. " +
1287
+ "Return JSON { \"source_commit\": \"<provenance.source_commit>\", \"published_at\": \"<provenance.published_at>\" } and nothing else.",
1288
+ { key: attemptKey("verify-publish-prov-" + taskId, totalReworkCount), label: "Verifying artifact provenance",
1289
+ schema: { type: "object", properties: { source_commit: { type: "string" }, published_at: { type: "string" } }, required: ["source_commit"] } }
1290
+ );
1291
+ var provCommit = (provResult.source_commit || "").trim();
1292
+ if (!provCommit || provCommit !== expectedCommit) {
1293
+ return await parkTask("Publish verification failed: artifact provenance shows source_commit '" + provCommit +
1294
+ "' but the integrated HEAD is '" + expectedCommit + "'. The publish did not land or provenance was not stamped.");
1295
+ }
1296
+ log("Publish verified for task " + taskId + ": artifact provenance at " + provCommit);
1297
+ publishVerified = true;
1298
+ } catch (e) {
1299
+ return await parkTask("Publish verification failed: could not read artifact provenance (" + (e && e.message ? e.message : e) + "). Fail-closed.");
1300
+ }
1301
+ }
1302
+
1303
+ // Session notes. Machine-readable marker lines are extracted from the full
1304
+ // worker report and appended AFTER the slice so a long report can never
1305
+ // amputate them; later phases (Review reading repo_diff:, QA backstop
1306
+ // reading TARGET_VERSION=) depend on them.
1307
+ let summary;
1308
+ var workerMarkers = extractMarkerLines(workerText);
1309
+ if (step.name === "Publish" && PUBLISH_TYPE === "npm" && publishTarget && publishVerified) {
1310
+ const markerLines = "TARGET_VERSION=" + publishTarget.target + " computed as " + publishTarget.base + " + " + publishTarget.scope + " → " + publishTarget.target + "\n" +
1311
+ "published: muse-crew@" + publishTarget.target;
1312
+ summary = (stepResult.summary || "Step completed").slice(0, 2000 - markerLines.length - workerMarkers.length - 2) + "\n" + markerLines + (workerMarkers ? "\n" + workerMarkers : "");
1313
+ } else {
1314
+ summary = (stepResult.summary || "Step completed").slice(0, 2000 - workerMarkers.length - 1) + (workerMarkers ? "\n" + workerMarkers : "");
1315
+ }
1316
+
1317
+ // Visual verdict evidence: for experiential artifact tasks, append the
1318
+ // deterministic post-change capture plan to the QA session notes. The
1319
+ // parent protocol (docs/visual-verdict.md) triggers the inspection with
1320
+ // this plan; "visual: pending" marks the owed verdict.
1321
+ if (step.name === "QA" && passed && qaVisual) {
1322
+ summary = (summary + "\nvisual: pending\ncapture_plan: " +
1323
+ buildVisualCapturePlan(taskTitle, taskDescription, "postchange", captureTargets).replace(/\s+/g, " ")).slice(0, 2900);
1324
+ }
1325
+
513
1326
  // Capture mapper's spec for Build and Review
514
1327
  if (step.name === "Map" && passed) {
515
1328
  mapperSpec = summary;
1329
+ var ctm = /capture_targets:\s*(.+)/i.exec(workerText);
1330
+ captureTargets = ctm ? ctm[1].trim().slice(0, 300) : "";
516
1331
  }
517
1332
 
518
- // Capture the accepted Build summary's machine-readable release decision.
519
- // Parsed from the RAW summary (before the 2000-char slice above) — the
520
- // release:/version_bump: lines sit at the very end and must survive truncation.
1333
+ // Capture Sage's experiential flag (machine-read marker line).
1334
+ if (step.name === "Triage" && passed) {
1335
+ isExperiential = extractExperiential(workerText);
1336
+ }
1337
+
1338
+ // Capture the accepted Build report's machine-readable release decision.
1339
+ // Deterministic extraction from the full worker report. A missing or
1340
+ // malformed declaration fails closed to null and Review rejects.
521
1341
  if (step.name === "Build" && passed) {
522
- releaseDecision = extractReleaseDecision(stepResult.summary || "");
1342
+ releaseDecision = extractReleaseDecision(workerText);
523
1343
  }
524
1344
 
525
1345
  await agent(
@@ -529,30 +1349,57 @@ while (i < STEPS.length) {
529
1349
  "Then call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
530
1350
  "{ \"task_id\": \"" + taskId + "\", \"type\": \"" + status + "\", \"identity\": \"" + step.identity + "\", \"message\": \"" + step.name + " " + status + " by " + step.identity + "\" }.",
531
1351
  {
532
- key: "record-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : ""),
1352
+ key: "record-" + step.name + (totalReworkCount > 0 ? "-r" + totalReworkCount : "") + (mapGateBounceCount > 0 ? "-g" + mapGateBounceCount : ""),
533
1353
  label: "Recording " + step.name + " result",
534
1354
  schema: { type: "object" }
535
1355
  }
536
1356
  );
537
1357
 
538
- // Reproduce failure blocks the task
1358
+ // Reproduce failure needs a human (PM attention): park the task. The
1359
+ // "blocked" event type is not used — blocked is mechanically derived from
1360
+ // unmet dependencies, never manually authored.
539
1361
  if (!passed && step.name === "Reproduce") {
540
- log("Reproduction failed for task " + taskId + " — blocking");
541
- await agent(
542
- "Mark this task as blocked because reproduction failed.\n" +
543
- "Call artifact_invoke_action on slug \"" + DASHBOARD_SLUG + "\", action \"logevent\", args:\n" +
544
- "{ \"task_id\": \"" + taskId + "\", \"type\": \"blocked\", \"message\": \"Reproduction failed needs PM attention\" }.",
545
- { key: "block-repro", label: "Blocking: reproduction failed", schema: { type: "object" } }
546
- );
547
- return { status: "blocked", task_id: taskId, reason: "Reproduction failed" };
1362
+ log("Reproduction failed for task " + taskId + " — parking for PM attention");
1363
+ return await parkTask("Reproduction failed — needs PM attention");
1364
+ }
1365
+
1366
+ // Visual-verdict gate: for experiential artifact tasks the task is done
1367
+ // only when the parent has recorded a visual_verdict: note event. The QA
1368
+ // work agent above covered the mechanical checks only. No recorded
1369
+ // verdict park for the parent protocol (never mark done on a pending
1370
+ // visual verdict). A recorded FAIL with budget left → rework at Build.
1371
+ if (step.name === "QA" && passed && qaVisual) {
1372
+ var vvStatus = await visualVerdictStatus();
1373
+ if (vvStatus.found && vvStatus.verdict === "PASS") {
1374
+ log("Visual verdict PASS recorded for task " + taskId + (vvStatus.detail ? " — " + vvStatus.detail : ""));
1375
+ } else if (vvStatus.found && vvStatus.verdict === "FAIL") {
1376
+ // A FAIL whose reason begins exactly "rendering impossible:" is not
1377
+ // reworkable — there is no rendered evidence to fix against. Park for
1378
+ // human attention instead of bouncing to Build.
1379
+ if (vvStatus.detail.indexOf("rendering impossible:") === 0) {
1380
+ log("Visual verdict FAIL (rendering impossible) for task " + taskId + " — parking for human attention");
1381
+ return await parkTask("Visual verdict FAIL — rendering impossible, human attention required: " + vvStatus.detail);
1382
+ }
1383
+ totalReworkCount++;
1384
+ if (totalReworkCount > MAX_TOTAL_REWORK) {
1385
+ log("Shared rework budget exhausted for task " + taskId + " — parking after visual verdict FAIL");
1386
+ return await parkTask("Exceeded shared rework budget (" + MAX_TOTAL_REWORK + " total rework attempts across Review and QA) after visual verdict FAIL: " + vvStatus.detail);
1387
+ }
1388
+ rejectionNotes = "Visual verdict FAIL: " + vvStatus.detail;
1389
+ i = BUILD_INDEX;
1390
+ log("Visual verdict FAIL — bouncing to Build (rework #" + totalReworkCount + " of " + MAX_TOTAL_REWORK + ")");
1391
+ continue;
1392
+ } else {
1393
+ 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)");
1394
+ }
548
1395
  }
549
1396
 
550
1397
  // Review/QA rejection bounces to Build
551
1398
  if (!passed && (step.name === "Review" || step.name === "QA")) {
552
1399
  totalReworkCount++;
553
1400
  if (totalReworkCount > MAX_TOTAL_REWORK) {
554
- log("Shared rework budget exhausted for task " + taskId + " — worktree preserved at .worktrees/" + taskId + " for manual inspection");
555
- return { status: "blocked", task_id: taskId, reason: "Exceeded shared rework budget (" + MAX_TOTAL_REWORK + " total rework attempts across Review and QA) after " + step.name + " rejection. Worktree preserved." };
1401
+ log("Shared rework budget exhausted for task " + taskId + " — worktree preserved at " + WORKTREE_PRESERVED_HINT + " for manual inspection");
1402
+ return await parkTask("Exceeded shared rework budget (" + MAX_TOTAL_REWORK + " total rework attempts across Review and QA) after " + step.name + " rejection. Worktree preserved.");
556
1403
  }
557
1404
  rejectionNotes = summary;
558
1405
  i = BUILD_INDEX;
@@ -560,16 +1407,19 @@ while (i < STEPS.length) {
560
1407
  continue;
561
1408
  }
562
1409
 
563
- // Integrate failure blocks the task
1410
+ // Integrate failure is operational (the merge did not finish), not a verdict:
1411
+ // the session above is recorded "failed" and the dispatcher retries the
1412
+ // phase under its consecutive-failure cap, parking after the cap.
564
1413
  if (!passed && step.name === "Integrate") {
565
1414
  log("Integration failed for task " + taskId + ": " + summary);
566
- return { status: "blocked", task_id: taskId, reason: "Integration failed: " + summary };
1415
+ return { status: "failed", task_id: taskId, reason: "Integration failed: " + summary };
567
1416
  }
568
1417
 
569
- // Publish failure blocks the task
1418
+ // Publish failure is operational (the publish did not finish), not a
1419
+ // verdict: recorded "failed" above, retried under the dispatcher's cap.
570
1420
  if (!passed && step.name === "Publish") {
571
1421
  log("Publish failed for task " + taskId + ": " + summary);
572
- return { status: "blocked", task_id: taskId, reason: "Publish failed: " + summary };
1422
+ return { status: "failed", task_id: taskId, reason: "Publish failed: " + summary };
573
1423
  }
574
1424
 
575
1425
  i++;