muse-crew 0.4.3 → 0.4.5

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