muse-crew 0.4.3 → 0.4.4

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