@goah/cli 0.13.2 → 0.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,30 +2,27 @@ import { createRequire as __goahCreateRequire } from "node:module";
2
2
  const require = __goahCreateRequire(import.meta.url);
3
3
  import {
4
4
  runnerPlugin
5
- } from "./chunk-D2DVAH37.js";
5
+ } from "./chunk-R6GKCNTB.js";
6
6
  import {
7
7
  SQLITE_SCHEMA_VERSION,
8
8
  SqliteLedger
9
- } from "./chunk-YH6YJ2IB.js";
9
+ } from "./chunk-CDELLMIJ.js";
10
10
  import {
11
11
  RunnerRouter,
12
12
  Supervisor,
13
13
  deriveRecoveryViews
14
- } from "./chunk-QBD6EJ2Z.js";
14
+ } from "./chunk-SQJZ5OFH.js";
15
15
  import {
16
16
  ProcessRunner,
17
17
  piWorkerPath,
18
18
  resolveEnvSpec
19
- } from "./chunk-7E7V6OIU.js";
19
+ } from "./chunk-EK6BTCFG.js";
20
20
  import {
21
21
  createPiModel
22
22
  } from "./chunk-6M3OOCKO.js";
23
23
  import {
24
24
  replayTranscript
25
25
  } from "./chunk-R6I3VKME.js";
26
- import {
27
- normalizeAssistantText
28
- } from "./chunk-TJON22J4.js";
29
26
 
30
27
  // node_modules/.dist-original/index.js
31
28
  import { accessSync, chmodSync as chmodSync3, constants, existsSync as existsSync3, mkdirSync as mkdirSync2, openSync, closeSync, readFileSync as readFileSync3, renameSync, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
@@ -440,10 +437,7 @@ async function* turnFrames(turnId, ledger, isActive) {
440
437
  throw new Error("Turn disappeared");
441
438
  if (current.status !== "in_progress") {
442
439
  yield* drain();
443
- const answer = ledger.turnItems(turnId).filter((item) => item.type === "assistant_message").at(-1);
444
- const answerText = String(answer?.data?.text ?? "");
445
- const streamed = answerText !== "" && ledger.readStream(`turn:${turnId}`).some((event) => event.type === "response.committed" ? event.data.text === answerText : event.type === "message.assistant.completed" && assistantEventText(event.data) === answerText);
446
- yield { type: "result", value: { turn: { ...current, leaseToken: null }, ...answer && !streamed ? { response: { content: answerText } } : {} } };
440
+ yield { type: "result", value: { turn: { ...current, leaseToken: null } } };
447
441
  return;
448
442
  }
449
443
  await new Promise((resolve3) => setTimeout(resolve3, 50));
@@ -461,16 +455,6 @@ function requiredGoal(ledger, id) {
461
455
  throw new Error("goal not found");
462
456
  return goal;
463
457
  }
464
- function assistantEventText(value) {
465
- if (!value || typeof value !== "object" || Array.isArray(value) || !value.message || typeof value.message !== "object" || Array.isArray(value.message))
466
- return "";
467
- const content = value.message.content;
468
- if (typeof content === "string")
469
- return normalizeAssistantText(content);
470
- if (!Array.isArray(content))
471
- return "";
472
- return content.map((item) => item && typeof item === "object" && !Array.isArray(item) && item.type === "text" && typeof item.text === "string" ? normalizeAssistantText(item.text) : "").filter(Boolean).join("\n");
473
- }
474
458
  function isTurnPresentationEvent(type) {
475
459
  return type.startsWith("message.") || type.startsWith("tool.") || type.startsWith("item.") || type.startsWith("turn.") || type === "response.committed" || type === "handoff.recorded" || type === "transcript.interrupted" || type === "transcript.completed";
476
460
  }
@@ -751,9 +751,25 @@ var SqliteLedger = class {
751
751
  return this.#transaction(() => this.#repairOpenTurnItems(id, reason, now, actor));
752
752
  }
753
753
  finishTurn(id, status, error, now, actor, mailIds = []) {
754
+ if (status === "completed")
755
+ throw new Error("successful Turn completion requires commitTurnResponse or commitHandoff");
754
756
  const current = this.#requiredTurn(id);
755
757
  return this.#transaction(() => this.#finishTurn(current, status, error, now, actor, mailIds));
756
758
  }
759
+ commitTurnResponse(id, responseItemId, now, actor, mailIds = []) {
760
+ return this.#transaction(() => {
761
+ const current = this.#requiredTurn(id);
762
+ if (current.goalId !== null)
763
+ throw new Error("Goal-bound Turn response requires commitHandoff");
764
+ const responseItem = this.turnItems(id).find((item) => item.id === responseItemId);
765
+ const text = responseItem && responseItem.type === "assistant_message" && responseItem.status === "completed" ? normalizeAssistantText(String(responseItem.data.text ?? "")) : "";
766
+ if (!responseItem || !text)
767
+ throw new Error("Turn response does not match a readable Assistant Item");
768
+ const streamId = `turn:${id}`;
769
+ this.#insertEvent({ streamId, ts: now, actor, type: "response.committed", data: { messageItemId: responseItem.id, text } });
770
+ return this.#finishTurn(current, "completed", null, now, actor, mailIds);
771
+ });
772
+ }
757
773
  releaseTurnProcess(id, actor) {
758
774
  if (actor !== "supervisor")
759
775
  throw new Error("only supervisor may release Runner process ownership");
@@ -1451,25 +1467,36 @@ var SqliteLedger = class {
1451
1467
  } else {
1452
1468
  if (event.type !== `turn.${turn.status}` || turn.attempt !== current.attempt || turn.runnerPid !== current.runnerPid)
1453
1469
  throw new Error(`turn event ${event.seq} has an invalid terminal transition`);
1454
- if (turn.status === "completed" && turn.goalId !== null)
1455
- this.#assertReplayGoalCompletion(turn, event);
1470
+ if (turn.status === "completed") {
1471
+ if (turn.goalId !== null)
1472
+ this.#assertReplayGoalCompletion(turn, event);
1473
+ else
1474
+ this.#assertReplayResponseCompletion(turn, event);
1475
+ }
1456
1476
  }
1457
1477
  }
1478
+ #assertReplayResponseCompletion(turn, event) {
1479
+ const responseRow = this.db.prepare("SELECT data FROM events WHERE stream_id=? AND type='response.committed' AND seq<? ORDER BY seq DESC LIMIT 1").get(`turn:${turn.id}`, event.seq);
1480
+ if (!responseRow)
1481
+ throw new Error(`turn event ${event.seq} completes without a committed response`);
1482
+ const response = JSON.parse(responseRow.data);
1483
+ const responseItem = this.turnItems(turn.id).find((item) => item.id === response.messageItemId && item.type === "assistant_message" && item.status === "completed");
1484
+ if (!responseItem || normalizeAssistantText(String(responseItem.data.text ?? "")) !== response.text)
1485
+ throw new Error(`turn event ${event.seq} has a mismatched committed response`);
1486
+ return responseItem;
1487
+ }
1458
1488
  #assertReplayGoalCompletion(turn, event) {
1459
1489
  if (turn.goalId === null || turn.goalRevision === null)
1460
1490
  throw new Error(`turn event ${event.seq} has no Goal commitment`);
1461
1491
  const items = this.turnItems(turn.id);
1462
- const responses = items.filter((item) => item.type === "assistant_message" && item.status === "completed" && typeof item.data.text === "string" && Boolean(item.data.text.trim()));
1492
+ this.#assertReplayResponseCompletion(turn, event);
1463
1493
  const handoffItem = items.findLast((item) => item.type === "handoff" && item.status === "completed");
1464
- const responseRow = this.db.prepare("SELECT data FROM events WHERE stream_id=? AND type='response.committed' AND seq<? ORDER BY seq DESC LIMIT 1").get(`turn:${turn.id}`, event.seq);
1465
1494
  const handoffRow = this.db.prepare("SELECT data FROM events WHERE stream_id=? AND type='handoff.recorded' AND seq<? ORDER BY seq DESC LIMIT 1").get(`turn:${turn.id}`, event.seq);
1466
- if (!responseRow || !handoffRow || !handoffItem)
1467
- throw new Error(`turn event ${event.seq} completes a Goal without response and Handoff`);
1468
- const response = JSON.parse(responseRow.data);
1495
+ if (!handoffRow || !handoffItem)
1496
+ throw new Error(`turn event ${event.seq} completes a Goal without Handoff`);
1469
1497
  const handoff = JSON.parse(handoffRow.data);
1470
- const responseItem = responses.find((item) => item.id === response.messageItemId);
1471
- if (!responseItem || responseItem.data.text !== response.text || !isDeepStrictEqual(handoffItem.data, handoff))
1472
- throw new Error(`turn event ${event.seq} has mismatched response or Handoff facts`);
1498
+ if (!isDeepStrictEqual(handoffItem.data, handoff))
1499
+ throw new Error(`turn event ${event.seq} has mismatched Handoff facts`);
1473
1500
  assertHandoff(handoff);
1474
1501
  const record = this.workRecord(turn.goalId);
1475
1502
  if (handoff.goalId !== turn.goalId || handoff.goalRevision !== turn.goalRevision || record?.recordRevision !== handoff.recordRevision)
@@ -124,18 +124,23 @@ var PiRunnerAdapter = class {
124
124
  }
125
125
  async #run(request) {
126
126
  const runnerSession = await this.driver.createRunnerSession(request);
127
+ let messageSequence = 0;
127
128
  try {
128
129
  while (true) {
129
130
  const step = await runnerSession.step();
130
131
  for (const trace of step.trace ?? [])
131
132
  request.emit(trace);
132
- if (step.response)
133
- return { outcome: "completed", response: step.response };
133
+ if (step.response) {
134
+ const finalMessageId = `adapter:${request.execution.id}:attempt:${request.execution.attempt}:message:${++messageSequence}`;
135
+ request.emit({ type: "message.assistant.completed", data: { message: { id: finalMessageId, role: "assistant", content: [{ type: "text", text: step.response.content }] }, commitState: "committed" } });
136
+ return { outcome: "completed", finalMessageId };
137
+ }
134
138
  if (step.handoff) {
135
- const validation = await request.rpc?.("goal.handoff.validate", { handoff: step.handoff.handoff, candidateMessage: step.handoff.response.content });
139
+ const messageItemId = `adapter:${request.execution.id}:attempt:${request.execution.attempt}:message:${++messageSequence}`;
140
+ const validation = await request.rpc?.("goal.handoff.validate", { handoff: step.handoff.handoff, candidateMessageId: messageItemId, candidateMessage: step.handoff.response.content });
136
141
  if (!validation)
137
142
  return { outcome: "abnormal", reason: "Handoff validation is unavailable" };
138
- request.emit({ type: "message.assistant.completed", data: { message: { id: `adapter:${request.execution.id}:handoff:${validation.attemptId}`, role: "assistant", content: [{ type: "text", text: step.handoff.response.content }], stopReason: "toolUse" }, commitState: "provisional" } });
143
+ request.emit({ type: "message.assistant.completed", data: { message: { id: messageItemId, role: "assistant", content: [{ type: "text", text: step.handoff.response.content }], stopReason: "toolUse" }, commitState: "provisional" } });
139
144
  if (!validation.accepted) {
140
145
  if (validation.fatal)
141
146
  return { outcome: "abnormal", reason: validation.issues.map((issue) => issue.message).join("; ") };
@@ -143,9 +148,11 @@ var PiRunnerAdapter = class {
143
148
  request.emit({ type: "runner.handoff_rejected", data: { attemptId: validation.attemptId, issues: validation.issues } });
144
149
  continue;
145
150
  }
151
+ if (validation.messageItemId !== messageItemId)
152
+ return { outcome: "abnormal", reason: "Handoff validation returned a different assistant message identity" };
146
153
  const output = { validationAttemptId: validation.attemptId, validationToken: validation.token, handoff: step.handoff.handoff };
147
154
  assertTurnOutput(output);
148
- return { outcome: "completed", response: step.handoff.response, handoff: output };
155
+ return { outcome: "completed", finalMessageId: messageItemId, handoff: output };
149
156
  }
150
157
  if (step.stopped)
151
158
  return { outcome: "abnormal", reason: request.turn.goalCommitment ? "runner stopped without a readable response and valid handoff" : "runner stopped without a response" };
@@ -3,7 +3,7 @@ const require = __goahCreateRequire(import.meta.url);
3
3
  import {
4
4
  createPiProcessRunner,
5
5
  piRunnerConfigurator
6
- } from "./chunk-7E7V6OIU.js";
6
+ } from "./chunk-EK6BTCFG.js";
7
7
 
8
8
  // node_modules/.dist-original/runner-registry.js
9
9
  var plugins = /* @__PURE__ */ new Map([
@@ -92,14 +92,20 @@ function field(value, key) {
92
92
 
93
93
  // node_modules/goah-supervisor/dist/roles.js
94
94
  var prompts = {
95
- child: "Own the assigned Child Goal. Follow its observation method, verify completion with its verification method, inspect shared Work Records, cite Ledger evidence, update this Goal's Work Record every Turn, and hand off an explicit outcome. Handoff is declarative: use mail.send to notify or escalate, setting its typed goalId route to the parent Goal when it should wake the parent's next committed Turn; use schedule.set to request future motion and send a completion_proposed Mail when the parent should review completion. You are not a task-only worker and cannot redefine or complete your own Goal.",
96
- ceo: `You are the user's sole operating interface and the durable CEO identity for this Goal tree. You organize work; you do not impersonate child execution.
95
+ child: `Own the assigned Child Goal. A Wake starts a work session; it is not a request for one short status update. Follow the observation method, verify completion with the verification method, inspect shared Work Records, cite Ledger evidence, and continue working while any safe, useful action can be executed now with current tools and authority. Use the Work Record as a durable checkpoint whenever the semantic state changes; updating it does not end the Turn. Planning, partial progress, or scheduling a future Wake are not by themselves reasons to stop. Before Handoff, ask whether another useful action can be completed without new authority, unavailable data, another Agent's result, or the passage of time; if yes, do it now.
96
+
97
+ Handoff is declarative and ends this Turn. Use outcome progress only after meaningful work when the current actionable frontier is exhausted; waiting only for an explicit external condition; blocked only for a real obstacle; and completion_proposed only when the verification material is ready for parent review. Use mail.send to notify or escalate, setting its typed goalId route to the parent Goal when it should wake the parent's next committed Turn; use schedule.set for genuinely time-dependent future observation and send a completion_proposed Mail when the parent should review completion. You are not a task-only worker and cannot redefine or complete your own Goal.`,
98
+ ceo: `You are the user's sole operating interface and the durable CEO identity for this Goal tree. You organize work and execute directly wherever work is not delegated. You are the executor of last resort when no suitable Child Agent profile exists.
97
99
 
98
100
  On the first wake for a root with no observation method, operationalize the goal before claiming measurable progress: inspect the current directory with read/edit/write/bash; read project documentation, configuration, code, scripts, local CLIs, and existing ledger evidence; clarify the objective, constraints, baseline, and meaning of success; identify the data source or qualitative inspection protocol; define freshness, cadence, time zone, sustain window, and missing-data behavior when relevant; list the exact access required; then propose a textual observation method to the human. Ask only for facts or permissions that cannot be discovered locally. Continue safe reversible exploration while waiting. Never invent a baseline, data source, permission, success criterion, or observation result.
99
101
 
100
- On every wake: (1) orient from the root and descendants, each current observation method and revision, Team motion, incoming mail, handoffs, blockers, unknown Tool Calls, and recovery facts; (2) diagnose every active child's motion, ownership, and adherence to its authoritative observation method; (3) decide whether to keep, delegate, revise the objective/method pair, reassign, pause, resume, complete, or escalate; (4) apply organization changes only through the high-level atomic tools; (5) repair every idle_unplanned child and every child missing an observation method before handoff; (6) close with active child motion plus a CEO review, an explicit wait/blocker, a human request, or a completion recommendation carrying evidence produced under the current method.
102
+ During every Goal Turn: (1) orient from the root and descendants, each current observation method and revision, Team motion, incoming mail, handoffs, blockers, unknown Tool Calls, and recovery facts; (2) diagnose every active child's motion, ownership, and adherence to its authoritative observation method; (3) decide whether to keep, delegate, revise the objective/method pair, reassign, pause, resume, complete, or escalate; (4) apply organization changes only through the high-level atomic tools; (5) repair every idle_unplanned child and every child missing an observation method; (6) execute the current work frontier instead of stopping at planning; (7) before ending, leave active child motion plus a CEO review, an explicit wait/blocker, a human request, or a completion recommendation carrying evidence produced under the current method.
103
+
104
+ Use goal.delegate rather than separate goal/mail/schedule calls. Execute ambiguous or exploratory work yourself until a stream has a bounded objective, independent observation and verification methods, and a reviewable result; only then create a distinct Goal-owning Agent. If no suitable Child Agent profile exists, continue executing the work yourself rather than stopping after decomposition. Use team.list as the roster source of truth.
105
+
106
+ A Wake starts a work session; it does not imply that the Turn should be short. Continue while any safe, useful action can be executed now with current tools and authority. Use the bound Goal's Work Record as a durable checkpoint whenever semantic state changes; updating it does not end the Turn. Planning, partial progress, decomposition, or scheduling a future Wake are not by themselves reasons to stop. Before Handoff, ask whether another useful action can be completed without new authority, unavailable data, another Agent's result, or the passage of time; if yes, do it now. Use outcome progress only when meaningful work is complete and the current actionable frontier is exhausted. Use waiting for an explicit external condition, blocked for a real obstacle, and completion_proposed only when verification material is ready for review.
101
107
 
102
- Use goal.delegate rather than separate goal/mail/schedule calls. Execute ambiguous or exploratory work yourself until a stream has a bounded objective, independent observation and verification methods, and a reviewable result; only then create a distinct Goal-owning Agent. Use team.list as the roster source of truth. Read the shared Work Record index, update the bound Goal's Work Record every Turn, and treat it as the durable semantic timeline. Handoff is declarative: use mail.send for explicit organization communication, schedule.set for future motion, and human.request when Human authority is required. Never claim authority to confirm Root methods, complete, or materially change a Root Goal: request the Human instead.`,
108
+ Handoff is declarative and ends the Turn: use mail.send for explicit organization communication, schedule.set only for genuinely time-dependent future motion, and human.request when Human authority is required. Never claim authority to confirm Root methods, complete, or materially change a Root Goal: request the Human instead.`,
103
109
  verifier: "Verify one Turn's handoff claims against its trace and runner facts. Do not trust self-report. Persist concise findings with exact evidence sequences.",
104
110
  audit: "Independently reconstruct outcomes from durable facts and external observations. Persist independent audit judgment with memory_append; it never substitutes for fresh evidence."
105
111
  };
@@ -550,27 +556,18 @@ var Supervisor = class {
550
556
  this.#scheduleTurnRecovery(sourceWake, sourceWakeTriggers, current.id, agent);
551
557
  return;
552
558
  }
553
- const response = normalizeAssistantText(result.response.content);
554
- if (!response)
555
- throw new Error("completed Turn requires a readable assistant response");
559
+ const responseItem = this.#finalAssistantItem(current.id, result.finalMessageId);
556
560
  if (turnContext.goalCommitment) {
557
561
  if (!result.handoff)
558
562
  throw new Error("committed Turn requires Handoff");
559
- this.#commitTurnGoalWork(current.id, agent, turnContext, response, result.handoff, sourceWake?.id ?? null, deliveredMailIds, recordRevisionAtStart);
563
+ this.#commitTurnGoalWork(current.id, agent, turnContext, responseItem, result.handoff, sourceWake?.id ?? null, deliveredMailIds, recordRevisionAtStart);
560
564
  return;
561
565
  }
562
566
  if (result.handoff)
563
567
  throw new Error("uncommitted Turn cannot finish with Handoff");
564
- const latestMessage = this.ledger.turnItems(current.id).findLast((item) => item.type === "assistant_message" && item.status === "completed");
565
- if (latestMessage) {
566
- const traced = normalizeAssistantText(String(latestMessage.data.text ?? ""));
567
- if (traced !== response)
568
- throw new Error("completed Turn response does not match its latest assistant trace");
569
- if (this.#assistantCommitState(current.id, traced) !== "committed")
570
- throw new Error("uncommitted Turn requires a committed assistant trace");
571
- } else
572
- this.#appendTurnItem(current.id, "assistant_message", { text: response }, agent);
573
- this.ledger.finishTurn(current.id, "completed", null, this.#now(), "supervisor", deliveredMailIds);
568
+ if (this.#assistantCommitState(current.id, responseItem.id) !== "committed")
569
+ throw new Error("uncommitted Turn requires a committed assistant trace");
570
+ this.ledger.commitTurnResponse(current.id, responseItem.id, this.#now(), "supervisor", deliveredMailIds);
574
571
  return;
575
572
  } catch (error) {
576
573
  if (renewal)
@@ -727,19 +724,32 @@ ${history}` } : {} };
727
724
  const facts = this.ledger.readStream(`turn:${turnId}`).filter((event) => event.type === "turn.retry_started").map((event) => `${event.type}: ${JSON.stringify(event.data)}`);
728
725
  return [...items, ...facts].join("\n");
729
726
  }
730
- #assistantCommitState(turnId, text) {
731
- const canonical = normalizeAssistantText(text);
732
- const event = this.ledger.readStream(`turn:${turnId}`).findLast((candidate) => {
727
+ #assistantMessageEvent(turnId, messageItemId) {
728
+ return this.ledger.readStream(`turn:${turnId}`).findLast((candidate) => {
733
729
  if (candidate.type !== "message.assistant.completed" || !candidate.data || typeof candidate.data !== "object" || Array.isArray(candidate.data))
734
730
  return false;
735
731
  const message = candidate.data.message;
736
- return messageTextContent(message?.content) === canonical;
732
+ return message?.id === messageItemId;
737
733
  });
734
+ }
735
+ #assistantCommitState(turnId, messageItemId) {
736
+ const event = this.#assistantMessageEvent(turnId, messageItemId);
738
737
  if (!event || !event.data || typeof event.data !== "object" || Array.isArray(event.data))
739
738
  return null;
740
739
  const state = event.data.commitState;
741
740
  return state === "committed" || state === "provisional" ? state : null;
742
741
  }
742
+ #finalAssistantItem(turnId, messageItemId) {
743
+ const id = messageItemId.trim();
744
+ const item = id ? this.ledger.turnItems(turnId).find((candidate) => candidate.id === id) : void 0;
745
+ const text = item && item.type === "assistant_message" && item.status === "completed" ? normalizeAssistantText(String(item.data.text ?? "")) : "";
746
+ const event = id ? this.#assistantMessageEvent(turnId, id) : void 0;
747
+ const turn = this.ledger.turn(turnId);
748
+ const retryStart = turn && turn.attempt > 1 ? this.ledger.readStream(`turn:${turnId}`).findLast((candidate) => candidate.type === "turn.retry_started" && candidate.data.attempt === turn.attempt) : void 0;
749
+ if (!item || !text || !event || retryStart && event.seq <= retryStart.seq)
750
+ throw new Error("completed Turn finalMessageId must reference a readable Assistant Item from the current attempt");
751
+ return item;
752
+ }
743
753
  #failTurn(turnId, reason) {
744
754
  const current = this.ledger.turn(turnId);
745
755
  if (!current || current.status !== "in_progress")
@@ -826,8 +836,12 @@ ${history}` } : {} };
826
836
  if (type === "message.assistant.completed") {
827
837
  const value = data;
828
838
  const text = messageTextContent(value.message?.content);
829
- if (text)
830
- this.#appendTurnItem(turnId, "assistant_message", { text }, actor);
839
+ if (text) {
840
+ const id = typeof value.message?.id === "string" ? value.message.id.trim() : "";
841
+ if (!id)
842
+ throw new Error("Runner assistant completion is missing a message Item id");
843
+ this.#appendTurnItem(turnId, "assistant_message", { text }, actor, id);
844
+ }
831
845
  } else if (type === "plan.updated")
832
846
  this.#appendTurnItem(turnId, "plan", data, actor);
833
847
  else if (type === "message.assistant.delta") {
@@ -1195,7 +1209,7 @@ ${history}` } : {} };
1195
1209
  return agent === "ceo" && role === "ceo";
1196
1210
  return role === "verifier" || role === "audit";
1197
1211
  }
1198
- #commitTurnGoalWork(turnId, agent, turn, response, raw, sourceWakeId, mailIds, revisionAtStart) {
1212
+ #commitTurnGoalWork(turnId, agent, turn, responseItem, raw, sourceWakeId, mailIds, revisionAtStart) {
1199
1213
  const binding = turn.goalCommitment;
1200
1214
  const goal = this.#goal(binding.goalId);
1201
1215
  if (goal.revision !== binding.goalRevision)
@@ -1206,11 +1220,9 @@ ${history}` } : {} };
1206
1220
  assertTurnOutput(raw);
1207
1221
  const validation = this.#handoffValidations.get(raw.validationToken);
1208
1222
  const execution = this.ledger.turn(turnId);
1209
- if (!validation || !execution || validation.turnId !== turnId || validation.attemptId !== raw.validationAttemptId || this.#handoffAttemptSeq.get(turnId) !== raw.validationAttemptId || validation.agent !== agent || validation.attempt !== execution.attempt || validation.leaseToken !== execution.leaseToken || validation.goalId !== goal.id || validation.goalRevision !== goal.revision || validation.message !== response || validation.handoff.outcome !== raw.handoff.outcome || !isSameNumbers(validation.handoff.evidence, raw.handoff.evidence))
1223
+ const response = normalizeAssistantText(String(responseItem.data.text ?? ""));
1224
+ if (!validation || !execution || validation.turnId !== turnId || validation.attemptId !== raw.validationAttemptId || this.#handoffAttemptSeq.get(turnId) !== raw.validationAttemptId || validation.agent !== agent || validation.attempt !== execution.attempt || validation.leaseToken !== execution.leaseToken || validation.goalId !== goal.id || validation.goalRevision !== goal.revision || validation.messageItemId !== responseItem.id || validation.message !== response || validation.handoff.outcome !== raw.handoff.outcome || !isSameNumbers(validation.handoff.evidence, raw.handoff.evidence))
1210
1225
  throw new Error("Handoff validation token is stale or does not match this Turn result");
1211
- const responseItem = [...this.ledger.turnItems(turnId)].reverse().find((item2) => item2.type === "assistant_message" && item2.status === "completed" && item2.data.text === validation.message);
1212
- if (!responseItem)
1213
- throw new Error("accepted Handoff response was not recorded in the Turn");
1214
1226
  const output = this.#committedTurnOutput(raw, binding);
1215
1227
  assertHandoff(output.handoff);
1216
1228
  const now = this.#now();
@@ -1341,7 +1353,8 @@ ${workText}`, activeGoal: turn.activeGoal, goalCommitment: turn.goalCommitment,
1341
1353
  const input = asRecord(params);
1342
1354
  if (method === "goal.handoff.validate") {
1343
1355
  const candidate = String(input.candidateMessage ?? "");
1344
- this.ledger.appendEvent({ streamId: `turn:${turnId}`, ts: this.#now(), actor: agent, type: "rpc.goal.handoff.validate", data: { attemptId: handoffAttemptId, handoff: input.handoff ?? null, candidateMessagePresent: Boolean(candidate.trim()), candidateMessageChars: candidate.length }, ignorable: true });
1356
+ const candidateMessageId = String(input.candidateMessageId ?? "");
1357
+ this.ledger.appendEvent({ streamId: `turn:${turnId}`, ts: this.#now(), actor: agent, type: "rpc.goal.handoff.validate", data: { attemptId: handoffAttemptId, handoff: input.handoff ?? null, candidateMessageId, candidateMessagePresent: Boolean(candidate.trim()), candidateMessageChars: candidate.length }, ignorable: true });
1345
1358
  return this.#validateHandoffDraft(turnId, handoffAttemptId, agent, execution, context, input);
1346
1359
  }
1347
1360
  const profile = this.#profiles.get(agent) ?? { agent, role: "child" };
@@ -1480,17 +1493,19 @@ ${workText}`, activeGoal: turn.activeGoal, goalCommitment: turn.goalCommitment,
1480
1493
  #validateHandoffDraft(turnId, attemptId, agent, execution, context, input) {
1481
1494
  if (!context.goalCommitment || execution.goalId === null)
1482
1495
  return { accepted: false, fatal: true, attemptId, issues: [{ code: "turn_not_committed", message: "This Turn no longer has a Goal commitment." }] };
1483
- const request = { handoff: input.handoff ?? null, candidateMessage: String(input.candidateMessage ?? "") };
1496
+ const request = { handoff: input.handoff ?? null, candidateMessageId: String(input.candidateMessageId ?? "").trim(), candidateMessage: String(input.candidateMessage ?? "") };
1484
1497
  const issues = [];
1485
1498
  try {
1486
1499
  assertAgentHandoff(request.handoff);
1487
1500
  } catch {
1488
1501
  issues.push({ code: "handoff_invalid", message: "Handoff requires a valid outcome and at least one evidence event." });
1489
1502
  }
1490
- const existingMessage = [...this.ledger.turnItems(turnId)].reverse().find((item) => item.type === "assistant_message" && item.status === "completed" && typeof item.data.text === "string" && Boolean(item.data.text.trim()));
1491
- const message = normalizeAssistantText(request.candidateMessage) || normalizeAssistantText(String(existingMessage?.data?.text ?? ""));
1492
- if (!message)
1493
- issues.push({ code: "message_missing", message: "This committed Turn needs a readable assistant message before it can finish." });
1503
+ const message = normalizeAssistantText(request.candidateMessage);
1504
+ const existingMessage = request.candidateMessageId ? this.ledger.turnItems(turnId).find((item) => item.id === request.candidateMessageId) : void 0;
1505
+ if (!request.candidateMessageId || !message)
1506
+ issues.push({ code: "message_missing", message: "This committed Turn needs a readable assistant message Item before it can finish." });
1507
+ else if (existingMessage && (existingMessage.type !== "assistant_message" || existingMessage.status !== "completed" || normalizeAssistantText(String(existingMessage.data.text ?? "")) !== message))
1508
+ issues.push({ code: "message_mismatch", message: "Handoff message identity does not match its assistant Item." });
1494
1509
  const goal = this.ledger.goal(context.goalCommitment.goalId);
1495
1510
  if (!goal || goal.phase !== "active" || goal.owner !== agent || goal.revision !== context.goalCommitment.goalRevision)
1496
1511
  return { accepted: false, fatal: true, attemptId, issues: [{ code: "goal_fence_changed", message: "Goal ownership, phase, or revision changed; this Turn can no longer finish against the old commitment." }] };
@@ -1504,8 +1519,8 @@ ${workText}`, activeGoal: turn.activeGoal, goalCommitment: turn.goalCommitment,
1504
1519
  if (issues.length)
1505
1520
  return { accepted: false, fatal: false, attemptId, issues };
1506
1521
  const token = randomUUID();
1507
- this.#handoffValidations.set(token, { turnId, attemptId, agent, attempt: execution.attempt, leaseToken: execution.leaseToken, goalId: goal.id, goalRevision: goal.revision, message, handoff: { outcome: request.handoff.outcome, evidence: [...request.handoff.evidence] } });
1508
- return { accepted: true, fatal: false, attemptId, token, goalId: goal.id, goalRevision: goal.revision };
1522
+ this.#handoffValidations.set(token, { turnId, attemptId, agent, attempt: execution.attempt, leaseToken: execution.leaseToken, goalId: goal.id, goalRevision: goal.revision, messageItemId: request.candidateMessageId, message, handoff: { outcome: request.handoff.outcome, evidence: [...request.handoff.evidence] } });
1523
+ return { accepted: true, fatal: false, attemptId, token, goalId: goal.id, goalRevision: goal.revision, messageItemId: request.candidateMessageId };
1509
1524
  }
1510
1525
  #beginHandoffAttempt(turnId) {
1511
1526
  this.#invalidateHandoffTokens(turnId);