@sjawhar/pi-legion 19.6.0 → 19.7.0

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.
package/dist/legion.js CHANGED
@@ -11692,7 +11692,6 @@ var LEGION_WORKFLOW_PHASES = [
11692
11692
  "accepting",
11693
11693
  "retro",
11694
11694
  "merging",
11695
- "awaiting_merge",
11696
11695
  "integrating",
11697
11696
  "done",
11698
11697
  "held"
@@ -11706,7 +11705,6 @@ var LEGION_PHASE_BACKWARD_TARGETS = [
11706
11705
  "accepting",
11707
11706
  "retro",
11708
11707
  "merging",
11709
- "awaiting_merge",
11710
11708
  "done",
11711
11709
  "held"
11712
11710
  ];
@@ -11799,6 +11797,11 @@ var legionClaimView = object({
11799
11797
  updateReasons: nonEmptyString2.optional(),
11800
11798
  providerErrorRun: number2().int().positive().optional(),
11801
11799
  pendingTask: legionPendingTaskView.optional(),
11800
+ lastTurnStart: timestamp.optional(),
11801
+ lastTurnEnd: timestamp.optional(),
11802
+ lastDeathCause: nonEmptyString2.optional(),
11803
+ lastStartFailure: nonEmptyString2.optional(),
11804
+ lastReady: timestamp.optional(),
11802
11805
  step: legionStepView.optional(),
11803
11806
  failure: legionClaimFailureView.optional(),
11804
11807
  pendingCause: legionFailureCause.optional()
@@ -11811,6 +11814,7 @@ var legionPhaseView = object({
11811
11814
  claim: legionClaimView,
11812
11815
  handoffCommit: nonEmptyString2.optional(),
11813
11816
  handoffRecord: legionHandoffRecordView.optional(),
11817
+ pass: number2().int().nonnegative(),
11814
11818
  rounds: number2().int().nonnegative(),
11815
11819
  backwardMoves: record(string2(), number2().int().positive()).optional()
11816
11820
  });
@@ -11819,7 +11823,7 @@ var legionPullRequestView = object({
11819
11823
  number: number2().int().positive(),
11820
11824
  head: nonEmptyString2,
11821
11825
  state: _enum(["open", "merged", "closed"]),
11822
- checksVerdict: nonEmptyString2.optional(),
11826
+ mergeState: _enum(["clean", "unstable", "has_hooks", "blocked", "dirty", "behind", "draft", "unknown"]).optional(),
11823
11827
  reviewDecision: nonEmptyString2.optional()
11824
11828
  });
11825
11829
  var legionGateView = object({
@@ -11997,6 +12001,7 @@ var legionCapabilityState = object({
11997
12001
  source: _enum(["configuration", "boot"]).optional()
11998
12002
  });
11999
12003
  var legionSettings = looseObject({
12004
+ review_round_cap: number2().int().positive(),
12000
12005
  worker_boot_timeout_seconds: number2().int().positive()
12001
12006
  });
12002
12007
  var legionCacheView = object({
@@ -12070,6 +12075,30 @@ var LegionReadyRequest = strictObject({
12070
12075
  generation: number2().int().positive(),
12071
12076
  capabilities: LegionCapabilityReport.optional()
12072
12077
  });
12078
+ var turnOutcomeFields = {
12079
+ generation: number2().int().positive(),
12080
+ sequence: number2().int().positive(),
12081
+ outcome: _enum(["clean", "refused"]),
12082
+ message: string2().optional()
12083
+ };
12084
+ var LegionTurnOutcomeAgentRequest = strictObject({
12085
+ claimToken: nonEmptyString2,
12086
+ sessionId: nonEmptyString2,
12087
+ secret: nonEmptyString2,
12088
+ ...turnOutcomeFields
12089
+ });
12090
+ var LegionTurnOutcomeBootRequest = strictObject({
12091
+ bootToken: nonEmptyString2,
12092
+ ...turnOutcomeFields
12093
+ });
12094
+ var LegionTurnOutcomeRequest = union([
12095
+ LegionTurnOutcomeAgentRequest,
12096
+ LegionTurnOutcomeBootRequest
12097
+ ]);
12098
+ var LegionTurnOutcomeResponse = object({
12099
+ refusedRun: number2().int().nonnegative(),
12100
+ failed: boolean2()
12101
+ });
12073
12102
  var LegionReadyForUpdateRequest = strictObject({
12074
12103
  claimToken: nonEmptyString2,
12075
12104
  sessionId: nonEmptyString2,
@@ -12192,6 +12221,11 @@ var LegionOperatorClaimResponse = object({
12192
12221
  pluginContract: number2().int().nonnegative(),
12193
12222
  updateRound: nonEmptyString2.optional(),
12194
12223
  updateHead: nonEmptyString2.optional(),
12224
+ lastTurnStart: timestamp.optional(),
12225
+ lastTurnEnd: timestamp.optional(),
12226
+ lastDeathCause: nonEmptyString2.optional(),
12227
+ lastStartFailure: nonEmptyString2.optional(),
12228
+ lastReady: timestamp.optional(),
12195
12229
  step: legionStepView.optional(),
12196
12230
  failure: legionClaimFailureView.optional()
12197
12231
  });
@@ -12212,9 +12246,7 @@ var LegionGrantResponse = object({
12212
12246
  expiresAt: timestamp
12213
12247
  });
12214
12248
  var LegionEmptyResponse = object({});
12215
- var LegionHandoffCompleteResponse = object({
12216
- note: nonEmptyString2.optional()
12217
- });
12249
+ var LegionHandoffCompleteResponse = object({});
12218
12250
  var LegionWaveReleaseResponse = object({
12219
12251
  released: array(nonEmptyString2),
12220
12252
  started: array(issueKey),
@@ -12234,7 +12266,6 @@ var LegionHandoffCompleteRequest = strictObject({
12234
12266
  grantId: nonEmptyString2,
12235
12267
  summary: nonEmptyString2,
12236
12268
  verdict: string2(),
12237
- ready: boolean2(),
12238
12269
  commit: nonEmptyString2.optional(),
12239
12270
  handoffId: nonEmptyString2.optional(),
12240
12271
  handoffVersion: number2().int().positive().optional(),
@@ -12468,6 +12499,7 @@ function createLegionDaemonClient(baseUrl, fetchFn = fetch) {
12468
12499
  ready: (input, options) => acknowledge("/legion/v1/claims/ready", input, options?.signal),
12469
12500
  readyForUpdate: (input) => acknowledge("/legion/v1/claims/ready-for-update", input),
12470
12501
  exit: (input) => acknowledge("/legion/v1/claims/exit", input),
12502
+ turnOutcome: (input) => post("/legion/v1/claims/turn-outcome", LegionTurnOutcomeRequest, LegionTurnOutcomeResponse, input),
12471
12503
  activity: (input) => acknowledge("/legion/v1/claims/activity", input),
12472
12504
  releaseRecords: (input) => post("/legion/v1/claims/release-records", LegionReleaseRecordsRequest, LegionReleaseRecordsResponse, input),
12473
12505
  grant: (input) => post("/legion/v1/grants", LegionGrantRequest, LegionGrantResponse, input),
@@ -12942,6 +12974,8 @@ function stepPhaseStall(state, input) {
12942
12974
  return state.state === "closed" ? { state } : { state: { state: "open", count: 0 } };
12943
12975
  case "tool-call":
12944
12976
  return { state: { state: state.state, count: 0 } };
12977
+ case "refused":
12978
+ return { state };
12945
12979
  case "reminded":
12946
12980
  return state.state === "closed" ? { state } : { state: { state: "open", count: state.count + 1 } };
12947
12981
  case "settle": {
@@ -12982,6 +13016,18 @@ function assistantRanTool(message) {
12982
13016
  return false;
12983
13017
  return message.content.some((block) => typeof block === "object" && block !== null && ("type" in block) && (block.type === "toolCall" || block.type === "tool_use"));
12984
13018
  }
13019
+ function assistantRefusal(message) {
13020
+ if (typeof message !== "object" || message === null)
13021
+ return;
13022
+ if (!("stopReason" in message) || message.stopReason !== "error")
13023
+ return;
13024
+ const worded = "errorMessage" in message && typeof message.errorMessage === "string" ? message.errorMessage : "";
13025
+ return worded === "" ? "error" : worded;
13026
+ }
13027
+ function turnEndOf(message) {
13028
+ const refusal = assistantRefusal(message);
13029
+ return refusal === undefined ? { kind: "settle", lastAssistantText: assistantText(message) } : { kind: "refused", message: refusal };
13030
+ }
12985
13031
  function recordedPhaseStall(state) {
12986
13032
  return state === "awaiting-update" ? "waiting" : state;
12987
13033
  }
@@ -13129,6 +13175,14 @@ function createPhaseReminder(deps) {
13129
13175
  });
13130
13176
  return { reminds: false, record };
13131
13177
  }
13178
+ const state = record.workers[claim.role]?.claim.state;
13179
+ if (state === "failed") {
13180
+ deps.log.debug("legion: the daemon has failed this claim; no reminder is sent", {
13181
+ issue: claim.issue,
13182
+ role: claim.role
13183
+ });
13184
+ return { reminds: false, record };
13185
+ }
13132
13186
  return { reminds: true, record };
13133
13187
  };
13134
13188
  const tellArchitect = async (record) => {
@@ -13251,17 +13305,20 @@ function createPhaseReminder(deps) {
13251
13305
  generation += 1;
13252
13306
  advance(input);
13253
13307
  },
13254
- settle: async (text, options) => {
13308
+ settle: async (turn) => {
13255
13309
  turnRunning = false;
13256
13310
  generation += 1;
13311
+ if (turn.kind === "refused") {
13312
+ advance(turn);
13313
+ continued = false;
13314
+ armReminder(reminderText(""), deps.limits.reminderMs);
13315
+ return;
13316
+ }
13317
+ const text = turn.lastAssistantText;
13257
13318
  if (stall.state !== "closed")
13258
13319
  lastMessage = text.slice(0, LAST_MESSAGE_LIMIT);
13259
13320
  const before = stall.count;
13260
- const reminder = advance({
13261
- kind: "settle",
13262
- lastAssistantText: text,
13263
- backgroundWork: options?.backgroundWork
13264
- });
13321
+ const reminder = advance(turn);
13265
13322
  if (stall.state === "awaiting-update") {
13266
13323
  continued = false;
13267
13324
  return;
@@ -13275,7 +13332,7 @@ function createPhaseReminder(deps) {
13275
13332
  continued = false;
13276
13333
  return;
13277
13334
  }
13278
- if (before !== 0 || continued || options?.canContinue === false) {
13335
+ if (before !== 0 || continued) {
13279
13336
  continued = false;
13280
13337
  armReminder(reminder, deps.limits.reminderMs);
13281
13338
  return;
@@ -14394,12 +14451,12 @@ async function bootLegionClaim(host) {
14394
14451
  await host.afterRegister?.(claim);
14395
14452
  host.setCapability({
14396
14453
  sessionID: host.registration.sessionId,
14397
- claimToken: claim.claimToken,
14398
- generation: claim.generation,
14399
14454
  tree: claim.tree,
14400
14455
  issue: claim.issue,
14401
14456
  role: claim.role,
14402
14457
  secret: claim.secret,
14458
+ claimToken: claim.claimToken,
14459
+ generation: claim.generation,
14403
14460
  promptAgents: claim.promptAgents
14404
14461
  });
14405
14462
  const ready = {
@@ -14470,7 +14527,7 @@ import { logger as logger3 } from "@oh-my-pi/pi-utils";
14470
14527
  // package.json
14471
14528
  var package_default = {
14472
14529
  name: "@sjawhar/pi-legion",
14473
- version: "19.6.0",
14530
+ version: "19.7.0",
14474
14531
  license: "Apache-2.0",
14475
14532
  type: "module",
14476
14533
  omp: {
@@ -14482,7 +14539,7 @@ var package_default = {
14482
14539
  ]
14483
14540
  },
14484
14541
  legion: {
14485
- daemonApiVersion: 85
14542
+ daemonApiVersion: 86
14486
14543
  },
14487
14544
  repository: {
14488
14545
  type: "git",
@@ -15952,7 +16009,6 @@ var PhaseOpArguments = discriminatedUnion("op", [
15952
16009
  verdict: _enum(["pass", "pending", "fail"], {
15953
16010
  error: "handoff_complete's verdict is pass, pending or fail"
15954
16011
  }).optional(),
15955
- ready: boolean2({ error: "handoff_complete's ready is true or false" }).optional(),
15956
16012
  wake_at: nextLook.optional()
15957
16013
  }),
15958
16014
  operation("request_backward_move", {
@@ -15996,7 +16052,7 @@ var PHASE_OP_SENTENCES = {
15996
16052
  requestBackwardMove: "request_backward_move returns an issue to an earlier phase (`to`, `reason`): a phase worker moves its own issue; " + "the tree's architect moves an issue in accepting, named by `issue`, back to implementing or testing, which counts a review round. "
15997
16053
  };
15998
16054
  function legionToolDescription(host) {
15999
- return "Perform the workflow operation the Legion daemon assigned this role. The daemon advances phases; this tool cannot spawn workers. " + (host.before ?? "") + "handoff_complete (phase workers and sub-architects; the daemon accepts a completion only from the role working the issue's current phase, " + "and the checking role's report on a look of its closed issue's production check) reports this phase complete: `summary` (two sentences for " + "the architect, or the merger's READY packet), `verdict` pass|fail from the tester alone on a phase completion (the daemon refuses a verdict " + "from any other role there) and pass|pending|fail on a production check report (pending: production does not carry the merge " + "yet), `ready: true` for the merger's READY. A planning, implementing, testing or reviewing phase ends with a handoff record on the " + "Dispatch issue: write it with `dispatch handoff-write --issue <issue> --phase <plan|implement|test|review> --body-file <file>` before " + "calling. This call reads the phase's newest record from Dispatch and reports it; the implementer's round also reports the commit " + "`legion/<issue>@origin` names, so push the branch first; retro and the merger's READY report the commit the workspace stands on. It " + "refuses, posting nothing, a phase with no record, a Dispatch that does not answer, or an implementer's `@-` not yet on " + "`legion/<issue>@origin`, each naming the remedy. A production check report " + "(the task whose first line is `Production check of <KEY>`, handed once the merge closed the issue to the role the check records) needs no " + "handoff and no commit: it carries its verdict and summary alone. A pending report also names `wake_at`, an RFC 3339 time: when you want the " + "next look. A pass, a fail, and a pending on the check's last look end the check, so none of them carries `wake_at` " + "(CHECK_WAKE_UNEXPECTED), and a pending on any other look is refused without one (CHECK_WAKE_REQUIRED). A report on an issue whose check is " + "closed or never opened is refused (CHECK_NOT_OPEN), and so is one from a role the check does not record (CHECK_ROLE_MISMATCH). " + "The daemon refuses " + "HANDOFF_SESSION_MISMATCH (another session wrote the record), HANDOFF_NOT_NEW (the record is the one you named for your previous phase: " + "write this phase's handoff), " + "HANDOFF_STALE_ASSIGNMENT (the issue left your phase and came back while your turn ran, so this completion is of the assignment before the one " + "the phase hands you now: end the turn without completing; the task of the assignment it hands you now is work of its own, so do that work and " + "complete it with a handoff of its own, never this record or verdict again), the implementer's completion of implementing with no open " + "pull request on `legion/<issue>` and none recorded " + "merged (HANDOFF_NO_PULL_REQUEST: open it; one naming a closed pull request is the architect's to decide) and, for READY, each " + "refusal the merger's role names; a refused completion changed nothing, so fix what it names and complete again. An accepted READY whose `note` " + "begins MANUAL_MERGE_REQUIRED: is one a person merges: arm nothing. " + "ready_for_update answers the daemon's update task on this issue's pod: `round` is the round id that task names, and the " + "daemon takes your answer for that round alone. Push every commit you want kept to the issue branch " + "first, because the pod and its disk are replaced after every worker of the pod has answered. The call ends no phase. The " + "daemon holds your next task until your process comes back on the new pod, in this same session. " + (host.after ?? "") + `What a later phase needs goes in your handoff; a question for another live role goes to its role topic with ${host.envoyPublish}.`;
16055
+ return "Perform the workflow operation the Legion daemon assigned this role. The daemon advances phases; this tool cannot spawn workers. " + (host.before ?? "") + "handoff_complete (phase workers and sub-architects; the daemon accepts a completion only from the role working the issue's current phase, " + "and the checking role's report on a look of its closed issue's production check) reports this phase complete: `summary` (two sentences for the " + "architect), `verdict` pass|fail from the tester alone on a phase completion (the daemon refuses a verdict from " + "any other role there) and pass|pending|fail on a production check report (pending: production does not carry the merge " + "yet). A planning, implementing, testing or reviewing phase ends with a handoff record on the " + "Dispatch issue: write it with `dispatch handoff-write --issue <issue> --phase <plan|implement|test|review> --body-file <file>` before " + "calling. This call reads the phase's newest record from Dispatch and reports it; the implementer's round also reports the commit " + "`legion/<issue>@origin` names, so push the branch first; retro and the merger's completion report the commit the workspace stands on. It " + "refuses, posting nothing, a phase with no record, a Dispatch that does not answer, or an implementer's `@-` not yet on " + "`legion/<issue>@origin`, each naming the remedy. A production check report " + "(the task whose first line is `Production check of <KEY>`, handed once the merge closed the issue to the role the check records) needs no " + "handoff and no commit: it carries its verdict and summary alone. A pending report also names `wake_at`, an RFC 3339 time: when you want the " + "next look. A pass, a fail, and a pending on the check's last look end the check, so none of them carries `wake_at` " + "(CHECK_WAKE_UNEXPECTED), and a pending on any other look is refused without one (CHECK_WAKE_REQUIRED). A report on an issue whose check is " + "closed or never opened is refused (CHECK_NOT_OPEN), and so is one from a role the check does not record (CHECK_ROLE_MISMATCH). " + "The daemon refuses " + "HANDOFF_SESSION_MISMATCH (another session wrote the record), HANDOFF_NOT_NEW (the record is the one you named for your previous phase: " + "write this phase's handoff), " + "HANDOFF_STALE_ASSIGNMENT (the issue left your phase and came back while your turn ran, so this completion is of the assignment before the one " + "the phase hands you now: end the turn without completing; the task of the assignment it hands you now is work of its own, so do that work and " + "complete it with a handoff of its own, never this record or verdict again), the implementer's completion of implementing with no open " + "pull request on `legion/<issue>` and none recorded " + "merged (HANDOFF_NO_PULL_REQUEST: open it; one naming a closed pull request is the architect's to decide); a refused completion changed " + "nothing, so fix what it names and complete again. " + "ready_for_update answers the daemon's update task on this issue's pod: `round` is the round id that task names, and the " + "daemon takes your answer for that round alone. Push every commit you want kept to the issue branch " + "first, because the pod and its disk are replaced after every worker of the pod has answered. The call ends no phase. The " + "daemon holds your next task until your process comes back on the new pod, in this same session. " + (host.after ?? "") + `What a later phase needs goes in your handoff; a question for another live role goes to its role topic with ${host.envoyPublish}.`;
16000
16056
  }
16001
16057
  async function mintClaimGrant(daemon, claim) {
16002
16058
  const { grantId } = await daemon.grant({
@@ -16166,9 +16222,6 @@ async function completeHandoff(runtime, args) {
16166
16222
  if (args.verdict === undefined) {
16167
16223
  throw new Error("handoff_complete on a production check names a verdict of pass, pending or fail");
16168
16224
  }
16169
- if (args.ready === true) {
16170
- throw new Error("handoff_complete on a production check is no READY: leave ready out");
16171
- }
16172
16225
  if (claim.role !== check.role) {
16173
16226
  throw new Error(`${claim.issue}'s production check is the ${check.role}'s, and this session is the ${claim.role}'s: only the role the check records reports on it`);
16174
16227
  }
@@ -16184,7 +16237,6 @@ async function completeHandoff(runtime, args) {
16184
16237
  grantId: await mintClaimGrant(daemon, claim),
16185
16238
  summary: args.summary,
16186
16239
  verdict: args.verdict ?? "",
16187
- ready: false,
16188
16240
  ...args.wake_at === undefined ? {} : { wakeAt: args.wake_at }
16189
16241
  });
16190
16242
  }
@@ -16199,7 +16251,6 @@ async function completeHandoff(runtime, args) {
16199
16251
  grantId: await mintClaimGrant(daemon, claim),
16200
16252
  summary: args.summary,
16201
16253
  verdict: args.verdict ?? "",
16202
- ready: args.ready ?? false,
16203
16254
  ...report
16204
16255
  });
16205
16256
  }
@@ -16245,33 +16296,123 @@ var OPERATION_FIELDS = {
16245
16296
  close_root: ["issue", "reason"],
16246
16297
  park_child: ["issue"],
16247
16298
  rerun_child: ["issue"],
16248
- read_state: [],
16299
+ read_state: ["issue", "issues", "phase", "settings"],
16249
16300
  set_status: ["issue", "status"],
16250
16301
  fresh_session: ["issue", "role"],
16251
16302
  compact: ["issue", "role"]
16252
16303
  };
16253
16304
  var ISSUE_STATUSES2 = ["todo", "backlog", "icebox"];
16254
16305
  var jsonSuccess = (details) => toolSuccess(JSON.stringify(details), details);
16306
+ var STATE_FILTERS = ["issue", "issues", "phase", "settings"];
16307
+ var SUMMARY_LEGEND = "legion state summary. Lines: project; admission cap; active/waiting/blocked; " + "capability <name> <status> [detail] [config <legion.yaml line>]; issues <count>; then " + "<KEY> <phase> <status> for every issue the daemon records, and under each issue Legion still " + "runs its slot, hold, gate <current> approved <version|none> and <role> <claim state> " + "<last turn start> <last turn end> lines, - for a value the daemon has none for. " + "read_state with issue, issues, phase or settings returns the full records it names.";
16308
+ function stateSummary(state) {
16309
+ const { admission, daemon } = state;
16310
+ const lines = [
16311
+ SUMMARY_LEGEND,
16312
+ `project ${daemon.project} boots ${daemon.boots} started ${daemon.startedAt}`,
16313
+ `admission cap ${admission.cap}${admission.free === undefined ? "" : ` free ${admission.free}`}`,
16314
+ `active ${admission.active.join(" ") || "(none)"}`,
16315
+ `waiting ${admission.waiting.join(" ") || "(none)"}`
16316
+ ];
16317
+ for (const blocked of admission.blocked) {
16318
+ lines.push(`blocked ${blocked.issue} on ${blocked.blockedBy.join(" ")}`);
16319
+ }
16320
+ for (const capability of state.capabilities) {
16321
+ const detail = capability.status === "present" ? "" : ` ${capability.detail}`;
16322
+ const config = capability.configLine === undefined ? "" : ` config ${capability.configLine}`;
16323
+ lines.push(`capability ${capability.name} ${capability.status}${detail}${config}`);
16324
+ }
16325
+ const keys = Object.keys(state.issues).sort();
16326
+ lines.push(`issues ${keys.length}`);
16327
+ for (const key of keys) {
16328
+ const issue = state.issues[key];
16329
+ if (issue === undefined)
16330
+ continue;
16331
+ lines.push(`${key} ${issue.phase} ${issue.status}`);
16332
+ if (issue.phase === "done" || issue.phase === "unrecorded")
16333
+ continue;
16334
+ if (issue.slot !== undefined) {
16335
+ const lent = issue.slot.lentTo === undefined ? "" : ` lent ${issue.slot.lentTo}`;
16336
+ lines.push(` slot ${issue.slot.index} since ${issue.slot.admittedAt}${lent}`);
16337
+ }
16338
+ if (issue.holdReason !== undefined)
16339
+ lines.push(` hold ${issue.holdReason}`);
16340
+ if (issue.designGate !== undefined) {
16341
+ const gate = issue.designGate;
16342
+ lines.push(` gate ${gate.currentVersion} approved ${gate.approvedVersion ?? "none"}`);
16343
+ }
16344
+ const claims = [];
16345
+ if (issue.architect !== undefined)
16346
+ claims.push(["architect", issue.architect]);
16347
+ for (const role of LEGION_ROLES) {
16348
+ const worker = issue.workers[role];
16349
+ if (worker !== undefined)
16350
+ claims.push([role, worker.claim]);
16351
+ }
16352
+ for (const [role, claim] of claims) {
16353
+ lines.push(` ${role} ${claim.state} ${claim.lastTurnStart ?? "-"} ${claim.lastTurnEnd ?? "-"}`);
16354
+ }
16355
+ }
16356
+ return lines.join(`
16357
+ `);
16358
+ }
16359
+ function readState(state, parameters) {
16360
+ const named = STATE_FILTERS.filter((filter) => parameters[filter] !== undefined);
16361
+ if (named.length === 0)
16362
+ return toolSuccess(stateSummary(state));
16363
+ if (named.length > 1) {
16364
+ throw new Error(`read_state takes one of ${STATE_FILTERS.join(", ")}, not ${named.join(" and ")}`);
16365
+ }
16366
+ if (named[0] === "settings") {
16367
+ if (parameters.settings !== true)
16368
+ throw new Error("read_state's settings is true");
16369
+ return jsonSuccess({ settings: state.settings });
16370
+ }
16371
+ if (named[0] === "phase") {
16372
+ const phase = LEGION_PHASES.find((candidate) => candidate === parameters.phase);
16373
+ if (phase === undefined) {
16374
+ throw new Error(`read_state's phase is one of ${LEGION_PHASES.join(", ")}`);
16375
+ }
16376
+ const selected = Object.entries(state.issues).filter(([, issue]) => issue.phase === phase);
16377
+ return jsonSuccess({ issues: Object.fromEntries(selected) });
16378
+ }
16379
+ let keys;
16380
+ if (named[0] === "issue")
16381
+ keys = [requiredString2(parameters, "read_state", "issue")];
16382
+ else {
16383
+ const issues = parameters.issues;
16384
+ if (!Array.isArray(issues) || !issues.every((issue) => typeof issue === "string")) {
16385
+ throw new Error("read_state's issues is a list of issue keys");
16386
+ }
16387
+ keys = issues;
16388
+ }
16389
+ const missing = keys.filter((key) => state.issues[key] === undefined);
16390
+ if (missing.length > 0)
16391
+ throw new Error(`The daemon has no record for ${missing.join(", ")}`);
16392
+ const records = keys.map((key) => [key, state.issues[key]]);
16393
+ return jsonSuccess({ issues: Object.fromEntries(records) });
16394
+ }
16255
16395
  function toolSchema(pi) {
16256
16396
  const z = pi.zod;
16257
- const phase = phaseOpParameters(z);
16397
+ const phaseOp = phaseOpParameters(z);
16258
16398
  return z.object({
16259
16399
  op: z.enum([...OPERATIONS.architect, ...OPERATIONS.controller]),
16260
- issue: phase.issue,
16261
- since: phase.since,
16400
+ issue: phaseOp.issue,
16401
+ since: phaseOp.since,
16262
16402
  artifactId: z.string().describe("register_gate's document for the step it registers: its artifact id, slug, or filename, as a dispatch command's --artifact takes it").optional(),
16263
16403
  version: z.number().optional(),
16264
16404
  step: z.enum(GATED_STEPS).describe("register_gate's design-gate step: decisions for the issue's decisions document, criteria for its Verification document, spec for its primary document. A deployment that gates one step takes the registration without it").optional(),
16265
16405
  issues: z.array(z.string()).optional(),
16266
- to: phase.to,
16406
+ to: phaseOp.to,
16267
16407
  reason: z.string().describe("close_root's and request_backward_move's why; no other operation takes it. park_child and rerun_child take only issue: say why you park a child in a dispatch comment on it").optional(),
16268
16408
  decision: z.enum(["retry", "escalate"]).optional(),
16269
- summary: phase.summary,
16270
- verdict: phase.verdict,
16271
- ready: phase.ready,
16272
- wake_at: phase.wake_at,
16273
- round: phase.round,
16409
+ summary: phaseOp.summary,
16410
+ verdict: phaseOp.verdict,
16411
+ wake_at: phaseOp.wake_at,
16412
+ round: phaseOp.round,
16274
16413
  status: z.enum(ISSUE_STATUSES2).optional(),
16414
+ phase: z.enum([...LEGION_PHASES]).optional(),
16415
+ settings: z.boolean().optional(),
16275
16416
  role: z.enum(LEGION_ROLES).optional()
16276
16417
  });
16277
16418
  }
@@ -16311,7 +16452,7 @@ function createLegionTool(deps) {
16311
16452
  description: legionToolDescription({
16312
16453
  envoyPublish: "envoy_publish",
16313
16454
  before: PHASE_OP_SENTENCES.readRecord + PHASE_OP_SENTENCES.readReleaseRecords,
16314
- after: PHASE_OP_SENTENCES.requestBackwardMove + "retry_or_escalate decides an issue the daemon holds after its worker failed (issue, decision): retry puts the issue " + "back in the phase it was held from and starts that phase's worker again, escalate leaves it held for the controller, " + "and an optional reason says why you decided as you did: a retry writes it into the restarted worker's task and the " + "daemon's own log line for the release, and an escalation sends it to the controller with the hold. " + "sign_off is the architect's acceptance of an issue in accepting, moving it to retro; the daemon refuses it in every " + "other phase (SIGNOFF_OUTSIDE_ACCEPTING) and while an issue beneath it is still in the workflow " + "(SIGNOFF_CHILD_IN_WORKFLOW, naming each one), since a parent's head proves its children's merged work: take each one " + "to done, or out of the workflow with park_child, and sign off again. close_root is refused the same way and with the " + "same code while an issue beneath the root is still in the workflow, since closing it would stop that work mid-turn. " + "release_children and rerun_child are refused for a child whose ancestor is in retro, merging or awaiting_merge " + "(CHILD_UNDER_ACCEPTED_PARENT, naming the ancestor), since that ancestor's approved head cannot carry work released " + "under it now: wait for the ancestor to close, then release it. " + "The controller's read_state returns the daemon's whole state and set_status moves an issue to todo, backlog or icebox. " + "fresh_session (issue, role) has one claim leave the session it runs in behind and start again in a new one: the daemon " + "stops the agent if it runs, forgets the session, and starts the claim, which loses everything that session held. A " + "phase worker that comes back owing no task is started through its issue's current phase, so it has that phase's work. " + "The answer is empty when the claim came back and nothing else is to be said, and names why nothing restarted the " + "phase (phaseNotRestarted) when the claim came back owing no task and the workflow refused that restart: the claim is " + "running, and no work was handed to it. " + "The daemon refuses it for a claim it records as working, which may be in a turn " + "(CLAIM_IN_A_TURN), for a claim left working over a process the daemon's last report " + "of it found gone, where no turn is running (CLAIM_IN_A_TURN as well), for a claim a " + "suspension is held over, in whatever state the hold found it (CLAIM_IN_A_TURN where " + "the claim is working, CLAIM_UNSETTLED where it is not), for a claim between states \u2014 " + "one queued, one whose launch is in flight, and one left working under a relaunch the " + "wake pacing parked (CLAIM_UNSETTLED) \u2014 and for role controller. " + "compact (issue, role) shortens one claim's session instead: the daemon has Oh My Pi write a text summary of the " + "session so far, and the claim keeps its session, its workspace and everything it knows of its issue and is sent " + "whatever task it owes again. Try compact before fresh_session for a claim that stays stuck. The answer says " + "whether the session was compacted and, when it was not, why; the claim is back either way. The daemon refuses " + "it for a claim that is suspended, failed or retired (CLAIM_NOT_RUNNING: fresh_session " + "reaches that one), for a claim it records as working, which may be in a turn " + "(CLAIM_IN_A_TURN), for a claim left working over a process the daemon's last report " + "of it found gone, where no turn is running (CLAIM_IN_A_TURN), for a claim a " + "suspension is held over (CLAIM_IN_A_TURN where the claim is working, CLAIM_UNSETTLED " + "where it is not), for a claim between states \u2014 one queued, one whose launch is in " + "flight, one whose agent has registered and is not ready yet, which fresh_session " + "reaches, and one left working under a relaunch the wake pacing parked " + "(CLAIM_UNSETTLED) \u2014 for a claim whose role runs on Claude Code (CLAIM_NOT_ON_OMP) " + "and for role controller. " + "Each refusal says what the claim does now and which operation reaches each state. It " + "names no moment to come back at: ask again later, and read the claim's state in " + "read_state. "
16455
+ after: PHASE_OP_SENTENCES.requestBackwardMove + "retry_or_escalate decides an issue the daemon holds after its worker failed (issue, decision): retry puts the issue " + "back in the phase it was held from and starts that phase's worker again, escalate leaves it held for the controller, " + "and an optional reason says why you decided as you did: a retry writes it into the restarted worker's task and the " + "daemon's own log line for the release, and an escalation sends it to the controller with the hold. " + "sign_off is the architect's acceptance of an issue in accepting, moving it to retro; the daemon refuses it in every " + "other phase (SIGNOFF_OUTSIDE_ACCEPTING) and while an issue beneath it is still in the workflow " + "(SIGNOFF_CHILD_IN_WORKFLOW, naming each one), since a parent's head proves its children's merged work: take each one " + "to done, or out of the workflow with park_child, and sign off again. close_root is refused the same way and with the " + "same code while an issue beneath the root is still in the workflow, since closing it would stop that work mid-turn. " + "release_children and rerun_child are refused for a child whose ancestor is in retro or merging " + "(CHILD_UNDER_ACCEPTED_PARENT, naming the ancestor), since that ancestor's approved head cannot carry work released " + "under it now: wait for the ancestor to close, then release it. " + "The controller's read_state with no field returns a summary of the daemon's whole state \u2014 the project, admission, each " + "capability, one line per recorded issue, and under each issue Legion still runs its slot, hold, gate and each claim's " + "state with its last turn times \u2014 and with issue, issues, phase or settings returns the full records it names; " + "set_status moves an issue to todo, backlog or icebox. " + "fresh_session (issue, role) has one claim leave the session it runs in behind and start again in a new one: the daemon " + "stops the agent if it runs, forgets the session, and starts the claim, which loses everything that session held. A " + "phase worker that comes back owing no task is started through its issue's current phase, so it has that phase's work. " + "The answer is empty when the claim came back and nothing else is to be said, and names why nothing restarted the " + "phase (phaseNotRestarted) when the claim came back owing no task and the workflow refused that restart: the claim is " + "running, and no work was handed to it. " + "The daemon refuses it for a claim it records as working, which may be in a turn " + "(CLAIM_IN_A_TURN), for a claim left working over a process the daemon's last report " + "of it found gone, where no turn is running (CLAIM_IN_A_TURN as well), for a claim a " + "suspension is held over, in whatever state the hold found it (CLAIM_IN_A_TURN where " + "the claim is working, CLAIM_UNSETTLED where it is not), for a claim between states \u2014 " + "one queued, one whose launch is in flight, and one left working under a relaunch the " + "wake pacing parked (CLAIM_UNSETTLED) \u2014 and for role controller. " + "compact (issue, role) shortens one claim's session instead: the daemon has Oh My Pi write a text summary of the " + "session so far, and the claim keeps its session, its workspace and everything it knows of its issue and is sent " + "whatever task it owes again. Try compact before fresh_session for a claim that stays stuck. The answer says " + "whether the session was compacted and, when it was not, why; the claim is back either way. The daemon refuses " + "it for a claim that is suspended, failed or retired (CLAIM_NOT_RUNNING: fresh_session " + "reaches that one), for a claim it records as working, which may be in a turn " + "(CLAIM_IN_A_TURN), for a claim left working over a process the daemon's last report " + "of it found gone, where no turn is running (CLAIM_IN_A_TURN), for a claim a " + "suspension is held over (CLAIM_IN_A_TURN where the claim is working, CLAIM_UNSETTLED " + "where it is not), for a claim between states \u2014 one queued, one whose launch is in " + "flight, one whose agent has registered and is not ready yet, which fresh_session " + "reaches, and one left working under a relaunch the wake pacing parked " + "(CLAIM_UNSETTLED) \u2014 for a claim whose role runs on Claude Code (CLAIM_NOT_ON_OMP) " + "and for role controller. " + "Each refusal says what the claim does now and which operation reaches each state. It " + "names no moment to come back at: ask again later, and read the claim's state in " + "read_state. "
16315
16456
  }),
16316
16457
  defaultInactive: true,
16317
16458
  parameters: toolSchema(pi),
@@ -16344,7 +16485,7 @@ function createLegionTool(deps) {
16344
16485
  const client = daemon();
16345
16486
  if (active.kind === "controller") {
16346
16487
  if (operation === "read_state")
16347
- return jsonSuccess(await client.state());
16488
+ return readState(await client.state(), parameters);
16348
16489
  const issue = requiredString2(parameters, operation, "issue");
16349
16490
  if (operation === "fresh_session" || operation === "compact") {
16350
16491
  const role = LEGION_ROLES.find((candidate) => candidate === parameters.role);
@@ -16449,6 +16590,54 @@ function createLegionTool(deps) {
16449
16590
  };
16450
16591
  }
16451
16592
 
16593
+ // src/turn-outcome.ts
16594
+ function createTurnOutcomeReporter(deps) {
16595
+ let counting;
16596
+ let sequence = 0;
16597
+ return {
16598
+ report: async (sessionID, event) => {
16599
+ const claim = deps.claim(sessionID);
16600
+ if (claim === undefined)
16601
+ return;
16602
+ if (claim.generation !== counting) {
16603
+ counting = claim.generation;
16604
+ sequence = 0;
16605
+ }
16606
+ sequence += 1;
16607
+ const mine = sequence;
16608
+ const refusal = assistantRefusal(event.messages?.findLast((message) => message.role === "assistant"));
16609
+ const request = {
16610
+ claimToken: claim.claimToken,
16611
+ sessionId: claim.sessionID,
16612
+ secret: claim.secret,
16613
+ generation: claim.generation,
16614
+ sequence: mine,
16615
+ outcome: refusal === undefined ? "clean" : "refused",
16616
+ ...refusal === undefined ? {} : { message: refusal }
16617
+ };
16618
+ try {
16619
+ const outcome = await retryWhileDaemonRestarts("claims/turn-outcome", () => deps.daemon().turnOutcome(request));
16620
+ deps.log.debug("legion: reported a turn's outcome", {
16621
+ issue: claim.issue,
16622
+ role: claim.role,
16623
+ sequence: mine,
16624
+ outcome: request.outcome,
16625
+ refusedRun: outcome.refusedRun,
16626
+ failed: outcome.failed
16627
+ });
16628
+ } catch (error) {
16629
+ deps.log.warn("legion: a turn's outcome did not reach the daemon", {
16630
+ issue: claim.issue,
16631
+ role: claim.role,
16632
+ sequence: mine,
16633
+ outcome: request.outcome,
16634
+ error: messageFor(error)
16635
+ });
16636
+ }
16637
+ }
16638
+ };
16639
+ }
16640
+
16452
16641
  // ../pi-shared/src/workspace-recreated.ts
16453
16642
  var WORKSPACE_RECREATED_VARIABLE = "LEGION_WORKSPACE_RECREATED";
16454
16643
  var WORKSPACE_RESTORED_VARIABLE = "LEGION_WORKSPACE_RESTORED";
@@ -16643,6 +16832,11 @@ function legionExtension(pi) {
16643
16832
  daemonClient ??= createLegionDaemonClient(requiredEnvironment(process.env, "LEGION_DAEMON_URL"));
16644
16833
  return daemonClient;
16645
16834
  };
16835
+ const turnOutcomes = createTurnOutcomeReporter({
16836
+ daemon: roleDaemon,
16837
+ claim: (sessionID) => claimSession.capability(sessionID),
16838
+ log: logger5
16839
+ });
16646
16840
  const claimSession = createClaimSession({
16647
16841
  daemon: roleDaemon,
16648
16842
  persistedTranscript,
@@ -16876,6 +17070,9 @@ function legionExtension(pi) {
16876
17070
  if (assistantRanTool(event.message))
16877
17071
  phaseReminder.apply({ kind: "tool-call" });
16878
17072
  });
17073
+ pi.on("agent_end", async (event, context) => {
17074
+ await turnOutcomes.report(context.sessionManager.getSessionId(), event);
17075
+ });
16879
17076
  pi.on("session_stop", async (event, context) => {
16880
17077
  if (event.signal.aborted)
16881
17078
  return;
@@ -16883,7 +17080,7 @@ function legionExtension(pi) {
16883
17080
  await reportActivity(context, { onlyWhenChanged: false });
16884
17081
  return;
16885
17082
  }
16886
- const reminder = await phaseReminder.settle(assistantText(event.last_assistant_message));
17083
+ const reminder = await phaseReminder.settle(turnEndOf(event.last_assistant_message));
16887
17084
  await reportActivity(context, { onlyWhenChanged: false });
16888
17085
  return reminder === undefined ? undefined : { continue: true, additionalContext: reminder };
16889
17086
  });
@@ -44,7 +44,7 @@ An answered root stands in the admission line until the pass that resumes it, an
44
44
  - Release every child as soon as it is filed, each with `--blocked-by` the issues it waits on, and never hold a release back for a close: a released child, held or running, keeps the root's close waiting, but once the root's own pull request has merged the root closes the moment its last released child leaves, and a child released after that finds no live tree and runs as an orphan root of its own.
45
45
  - On each `child-closed`, read the child's handoff. Edit the spec of each open child the result changes, and take out each child it makes unneeded with `park_child` and say why with `dispatch comment`.
46
46
  - Before you park a child for good (one made unneeded, or parked so its tree can finish), set the `--blocked-by` list of each sibling that waits on it again without it (one call with the rest of its list, or `--clear-blocked-by` when it was the only one), or park that sibling too: a parked child is stopped, not done, and its dependents stay held with no notice. A park followed by `rerun_child` keeps its dependents' links: they wait through the rerun and start when the rerun's merge closes the child.
47
- - A released child takes an admission slot of its own when the daemon starts its first phase and keeps it until it is done, leaves the workflow or waits only for its merge, and it waits in the admission line until the daemon starts it, so a tree of four started issues holds four of the cap's issues. It never becomes a root while your tree is live.
47
+ - A released child takes an admission slot of its own when the daemon starts its first phase and keeps it until it is done or leaves the workflow, and it waits in the admission line until the daemon starts it, so a tree of four started issues holds four of the cap's issues. It never becomes a root while your tree is live.
48
48
 
49
49
  ## 3. Children complete
50
50