@sjawhar/pi-legion 19.5.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({
@@ -11843,7 +11847,21 @@ var legionSlotView = object({
11843
11847
  });
11844
11848
  var legionWaitingLineView = object({
11845
11849
  place: number2().int().positive(),
11846
- length: number2().int().positive()
11850
+ length: number2().int().positive(),
11851
+ part: _enum(["returned", "starting"]).optional(),
11852
+ kind: _enum(["returning", "answered", "queued_root", "first_phase"]).optional(),
11853
+ partPlace: number2().int().positive().optional(),
11854
+ partLength: number2().int().positive().optional(),
11855
+ holdsSlot: boolean2().optional(),
11856
+ since: timestamp.optional(),
11857
+ rootRank: nonEmptyString2.optional(),
11858
+ ownRank: nonEmptyString2.optional(),
11859
+ rootKey: issueKey.optional(),
11860
+ reason: nonEmptyString2.optional()
11861
+ });
11862
+ var legionWhyView = object({
11863
+ state: _enum(["claim_stopped", "waiting", "blocked", "unlisted"]),
11864
+ reason: nonEmptyString2
11847
11865
  });
11848
11866
  var legionCheckWakeView = object({
11849
11867
  kind: nonEmptyString2,
@@ -11934,6 +11952,7 @@ var legionIssue = object({
11934
11952
  gatedSteps: array(legionGatedStepView).optional(),
11935
11953
  slot: legionSlotView.optional(),
11936
11954
  waitingLine: legionWaitingLineView.optional(),
11955
+ why: legionWhyView.optional(),
11937
11956
  waitingOn: legionWaitingOn.optional(),
11938
11957
  check: legionCheckView.optional(),
11939
11958
  memoryGroup: _enum(["memory", "none"]).optional(),
@@ -11982,6 +12001,7 @@ var legionCapabilityState = object({
11982
12001
  source: _enum(["configuration", "boot"]).optional()
11983
12002
  });
11984
12003
  var legionSettings = looseObject({
12004
+ review_round_cap: number2().int().positive(),
11985
12005
  worker_boot_timeout_seconds: number2().int().positive()
11986
12006
  });
11987
12007
  var legionCacheView = object({
@@ -12055,6 +12075,30 @@ var LegionReadyRequest = strictObject({
12055
12075
  generation: number2().int().positive(),
12056
12076
  capabilities: LegionCapabilityReport.optional()
12057
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
+ });
12058
12102
  var LegionReadyForUpdateRequest = strictObject({
12059
12103
  claimToken: nonEmptyString2,
12060
12104
  sessionId: nonEmptyString2,
@@ -12177,6 +12221,11 @@ var LegionOperatorClaimResponse = object({
12177
12221
  pluginContract: number2().int().nonnegative(),
12178
12222
  updateRound: nonEmptyString2.optional(),
12179
12223
  updateHead: nonEmptyString2.optional(),
12224
+ lastTurnStart: timestamp.optional(),
12225
+ lastTurnEnd: timestamp.optional(),
12226
+ lastDeathCause: nonEmptyString2.optional(),
12227
+ lastStartFailure: nonEmptyString2.optional(),
12228
+ lastReady: timestamp.optional(),
12180
12229
  step: legionStepView.optional(),
12181
12230
  failure: legionClaimFailureView.optional()
12182
12231
  });
@@ -12197,9 +12246,7 @@ var LegionGrantResponse = object({
12197
12246
  expiresAt: timestamp
12198
12247
  });
12199
12248
  var LegionEmptyResponse = object({});
12200
- var LegionHandoffCompleteResponse = object({
12201
- note: nonEmptyString2.optional()
12202
- });
12249
+ var LegionHandoffCompleteResponse = object({});
12203
12250
  var LegionWaveReleaseResponse = object({
12204
12251
  released: array(nonEmptyString2),
12205
12252
  started: array(issueKey),
@@ -12219,7 +12266,6 @@ var LegionHandoffCompleteRequest = strictObject({
12219
12266
  grantId: nonEmptyString2,
12220
12267
  summary: nonEmptyString2,
12221
12268
  verdict: string2(),
12222
- ready: boolean2(),
12223
12269
  commit: nonEmptyString2.optional(),
12224
12270
  handoffId: nonEmptyString2.optional(),
12225
12271
  handoffVersion: number2().int().positive().optional(),
@@ -12453,6 +12499,7 @@ function createLegionDaemonClient(baseUrl, fetchFn = fetch) {
12453
12499
  ready: (input, options) => acknowledge("/legion/v1/claims/ready", input, options?.signal),
12454
12500
  readyForUpdate: (input) => acknowledge("/legion/v1/claims/ready-for-update", input),
12455
12501
  exit: (input) => acknowledge("/legion/v1/claims/exit", input),
12502
+ turnOutcome: (input) => post("/legion/v1/claims/turn-outcome", LegionTurnOutcomeRequest, LegionTurnOutcomeResponse, input),
12456
12503
  activity: (input) => acknowledge("/legion/v1/claims/activity", input),
12457
12504
  releaseRecords: (input) => post("/legion/v1/claims/release-records", LegionReleaseRecordsRequest, LegionReleaseRecordsResponse, input),
12458
12505
  grant: (input) => post("/legion/v1/grants", LegionGrantRequest, LegionGrantResponse, input),
@@ -12927,6 +12974,8 @@ function stepPhaseStall(state, input) {
12927
12974
  return state.state === "closed" ? { state } : { state: { state: "open", count: 0 } };
12928
12975
  case "tool-call":
12929
12976
  return { state: { state: state.state, count: 0 } };
12977
+ case "refused":
12978
+ return { state };
12930
12979
  case "reminded":
12931
12980
  return state.state === "closed" ? { state } : { state: { state: "open", count: state.count + 1 } };
12932
12981
  case "settle": {
@@ -12967,6 +13016,18 @@ function assistantRanTool(message) {
12967
13016
  return false;
12968
13017
  return message.content.some((block) => typeof block === "object" && block !== null && ("type" in block) && (block.type === "toolCall" || block.type === "tool_use"));
12969
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
+ }
12970
13031
  function recordedPhaseStall(state) {
12971
13032
  return state === "awaiting-update" ? "waiting" : state;
12972
13033
  }
@@ -13114,6 +13175,14 @@ function createPhaseReminder(deps) {
13114
13175
  });
13115
13176
  return { reminds: false, record };
13116
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
+ }
13117
13186
  return { reminds: true, record };
13118
13187
  };
13119
13188
  const tellArchitect = async (record) => {
@@ -13236,17 +13305,20 @@ function createPhaseReminder(deps) {
13236
13305
  generation += 1;
13237
13306
  advance(input);
13238
13307
  },
13239
- settle: async (text, options) => {
13308
+ settle: async (turn) => {
13240
13309
  turnRunning = false;
13241
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;
13242
13318
  if (stall.state !== "closed")
13243
13319
  lastMessage = text.slice(0, LAST_MESSAGE_LIMIT);
13244
13320
  const before = stall.count;
13245
- const reminder = advance({
13246
- kind: "settle",
13247
- lastAssistantText: text,
13248
- backgroundWork: options?.backgroundWork
13249
- });
13321
+ const reminder = advance(turn);
13250
13322
  if (stall.state === "awaiting-update") {
13251
13323
  continued = false;
13252
13324
  return;
@@ -13260,7 +13332,7 @@ function createPhaseReminder(deps) {
13260
13332
  continued = false;
13261
13333
  return;
13262
13334
  }
13263
- if (before !== 0 || continued || options?.canContinue === false) {
13335
+ if (before !== 0 || continued) {
13264
13336
  continued = false;
13265
13337
  armReminder(reminder, deps.limits.reminderMs);
13266
13338
  return;
@@ -14379,12 +14451,12 @@ async function bootLegionClaim(host) {
14379
14451
  await host.afterRegister?.(claim);
14380
14452
  host.setCapability({
14381
14453
  sessionID: host.registration.sessionId,
14382
- claimToken: claim.claimToken,
14383
- generation: claim.generation,
14384
14454
  tree: claim.tree,
14385
14455
  issue: claim.issue,
14386
14456
  role: claim.role,
14387
14457
  secret: claim.secret,
14458
+ claimToken: claim.claimToken,
14459
+ generation: claim.generation,
14388
14460
  promptAgents: claim.promptAgents
14389
14461
  });
14390
14462
  const ready = {
@@ -14455,7 +14527,7 @@ import { logger as logger3 } from "@oh-my-pi/pi-utils";
14455
14527
  // package.json
14456
14528
  var package_default = {
14457
14529
  name: "@sjawhar/pi-legion",
14458
- version: "19.5.0",
14530
+ version: "19.7.0",
14459
14531
  license: "Apache-2.0",
14460
14532
  type: "module",
14461
14533
  omp: {
@@ -14467,7 +14539,7 @@ var package_default = {
14467
14539
  ]
14468
14540
  },
14469
14541
  legion: {
14470
- daemonApiVersion: 75
14542
+ daemonApiVersion: 86
14471
14543
  },
14472
14544
  repository: {
14473
14545
  type: "git",
@@ -15937,7 +16009,6 @@ var PhaseOpArguments = discriminatedUnion("op", [
15937
16009
  verdict: _enum(["pass", "pending", "fail"], {
15938
16010
  error: "handoff_complete's verdict is pass, pending or fail"
15939
16011
  }).optional(),
15940
- ready: boolean2({ error: "handoff_complete's ready is true or false" }).optional(),
15941
16012
  wake_at: nextLook.optional()
15942
16013
  }),
15943
16014
  operation("request_backward_move", {
@@ -15981,7 +16052,7 @@ var PHASE_OP_SENTENCES = {
15981
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. "
15982
16053
  };
15983
16054
  function legionToolDescription(host) {
15984
- 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}.`;
15985
16056
  }
15986
16057
  async function mintClaimGrant(daemon, claim) {
15987
16058
  const { grantId } = await daemon.grant({
@@ -16151,9 +16222,6 @@ async function completeHandoff(runtime, args) {
16151
16222
  if (args.verdict === undefined) {
16152
16223
  throw new Error("handoff_complete on a production check names a verdict of pass, pending or fail");
16153
16224
  }
16154
- if (args.ready === true) {
16155
- throw new Error("handoff_complete on a production check is no READY: leave ready out");
16156
- }
16157
16225
  if (claim.role !== check.role) {
16158
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`);
16159
16227
  }
@@ -16169,7 +16237,6 @@ async function completeHandoff(runtime, args) {
16169
16237
  grantId: await mintClaimGrant(daemon, claim),
16170
16238
  summary: args.summary,
16171
16239
  verdict: args.verdict ?? "",
16172
- ready: false,
16173
16240
  ...args.wake_at === undefined ? {} : { wakeAt: args.wake_at }
16174
16241
  });
16175
16242
  }
@@ -16184,7 +16251,6 @@ async function completeHandoff(runtime, args) {
16184
16251
  grantId: await mintClaimGrant(daemon, claim),
16185
16252
  summary: args.summary,
16186
16253
  verdict: args.verdict ?? "",
16187
- ready: args.ready ?? false,
16188
16254
  ...report
16189
16255
  });
16190
16256
  }
@@ -16230,33 +16296,123 @@ var OPERATION_FIELDS = {
16230
16296
  close_root: ["issue", "reason"],
16231
16297
  park_child: ["issue"],
16232
16298
  rerun_child: ["issue"],
16233
- read_state: [],
16299
+ read_state: ["issue", "issues", "phase", "settings"],
16234
16300
  set_status: ["issue", "status"],
16235
16301
  fresh_session: ["issue", "role"],
16236
16302
  compact: ["issue", "role"]
16237
16303
  };
16238
16304
  var ISSUE_STATUSES2 = ["todo", "backlog", "icebox"];
16239
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
+ }
16240
16395
  function toolSchema(pi) {
16241
16396
  const z = pi.zod;
16242
- const phase = phaseOpParameters(z);
16397
+ const phaseOp = phaseOpParameters(z);
16243
16398
  return z.object({
16244
16399
  op: z.enum([...OPERATIONS.architect, ...OPERATIONS.controller]),
16245
- issue: phase.issue,
16246
- since: phase.since,
16400
+ issue: phaseOp.issue,
16401
+ since: phaseOp.since,
16247
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(),
16248
16403
  version: z.number().optional(),
16249
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(),
16250
16405
  issues: z.array(z.string()).optional(),
16251
- to: phase.to,
16406
+ to: phaseOp.to,
16252
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(),
16253
16408
  decision: z.enum(["retry", "escalate"]).optional(),
16254
- summary: phase.summary,
16255
- verdict: phase.verdict,
16256
- ready: phase.ready,
16257
- wake_at: phase.wake_at,
16258
- round: phase.round,
16409
+ summary: phaseOp.summary,
16410
+ verdict: phaseOp.verdict,
16411
+ wake_at: phaseOp.wake_at,
16412
+ round: phaseOp.round,
16259
16413
  status: z.enum(ISSUE_STATUSES2).optional(),
16414
+ phase: z.enum([...LEGION_PHASES]).optional(),
16415
+ settings: z.boolean().optional(),
16260
16416
  role: z.enum(LEGION_ROLES).optional()
16261
16417
  });
16262
16418
  }
@@ -16296,7 +16452,7 @@ function createLegionTool(deps) {
16296
16452
  description: legionToolDescription({
16297
16453
  envoyPublish: "envoy_publish",
16298
16454
  before: PHASE_OP_SENTENCES.readRecord + PHASE_OP_SENTENCES.readReleaseRecords,
16299
- 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. "
16300
16456
  }),
16301
16457
  defaultInactive: true,
16302
16458
  parameters: toolSchema(pi),
@@ -16329,7 +16485,7 @@ function createLegionTool(deps) {
16329
16485
  const client = daemon();
16330
16486
  if (active.kind === "controller") {
16331
16487
  if (operation === "read_state")
16332
- return jsonSuccess(await client.state());
16488
+ return readState(await client.state(), parameters);
16333
16489
  const issue = requiredString2(parameters, operation, "issue");
16334
16490
  if (operation === "fresh_session" || operation === "compact") {
16335
16491
  const role = LEGION_ROLES.find((candidate) => candidate === parameters.role);
@@ -16434,6 +16590,54 @@ function createLegionTool(deps) {
16434
16590
  };
16435
16591
  }
16436
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
+
16437
16641
  // ../pi-shared/src/workspace-recreated.ts
16438
16642
  var WORKSPACE_RECREATED_VARIABLE = "LEGION_WORKSPACE_RECREATED";
16439
16643
  var WORKSPACE_RESTORED_VARIABLE = "LEGION_WORKSPACE_RESTORED";
@@ -16628,6 +16832,11 @@ function legionExtension(pi) {
16628
16832
  daemonClient ??= createLegionDaemonClient(requiredEnvironment(process.env, "LEGION_DAEMON_URL"));
16629
16833
  return daemonClient;
16630
16834
  };
16835
+ const turnOutcomes = createTurnOutcomeReporter({
16836
+ daemon: roleDaemon,
16837
+ claim: (sessionID) => claimSession.capability(sessionID),
16838
+ log: logger5
16839
+ });
16631
16840
  const claimSession = createClaimSession({
16632
16841
  daemon: roleDaemon,
16633
16842
  persistedTranscript,
@@ -16861,6 +17070,9 @@ function legionExtension(pi) {
16861
17070
  if (assistantRanTool(event.message))
16862
17071
  phaseReminder.apply({ kind: "tool-call" });
16863
17072
  });
17073
+ pi.on("agent_end", async (event, context) => {
17074
+ await turnOutcomes.report(context.sessionManager.getSessionId(), event);
17075
+ });
16864
17076
  pi.on("session_stop", async (event, context) => {
16865
17077
  if (event.signal.aborted)
16866
17078
  return;
@@ -16868,7 +17080,7 @@ function legionExtension(pi) {
16868
17080
  await reportActivity(context, { onlyWhenChanged: false });
16869
17081
  return;
16870
17082
  }
16871
- const reminder = await phaseReminder.settle(assistantText(event.last_assistant_message));
17083
+ const reminder = await phaseReminder.settle(turnEndOf(event.last_assistant_message));
16872
17084
  await reportActivity(context, { onlyWhenChanged: false });
16873
17085
  return reminder === undefined ? undefined : { continue: true, additionalContext: reminder };
16874
17086
  });
@@ -14,7 +14,7 @@ You own one issue tree from its first decision to the merge that closes it. The
14
14
  - Act on delivered wakes and the live artifacts they name; build no wait loop, since every wake reaches you.
15
15
  - Check each claim against the code as fetched now (the default branch your addressing line names, or the head under review), never the workspace as it was at admission, and tell every fresh reader you dispatch to do the same: the branch may have moved since.
16
16
  - Before you end a turn that waits on a human, open what they must answer: a decision block, a `dispatch ask` or `dispatch request-approval`. A turn that ends with nothing open asks nobody, and the tree stops. Open an ordinary ask on the root issue itself, never a child: only a question a session of this tree opens on the root starts a wait on a person, so an ask on a child starts no wait and leaves the tree standing still. Once you have handed a root question to the human, end your turn: when nothing else of the tree is at work — no other issue of the tree in a phase, the `legion` label still on, and no person or outside session holding the root's Dispatch claim — the root moves to `awaiting_person`, keeping its admission slot, while this session stays live. Read the human's comments and replies as they arrive. Their answer gives this live claim a task naming what answered and what is still with them. The same holds once you request approval and `register_gate` that version: the registration hands the spec to the human, so end your turn there too, and the human's review, or a newer version once Dispatch shows the request back on your turn, gives you that task.
17
- An answered root stands in the admission line until the pass that resumes it, and nothing is sent to you about that wait: your record's `waitingLine` gives the live place in the line and the line's length, your resume task says what answered the wait, and you act on neither, because that resume takes no further slot and the daemon starts you again by itself.
17
+ An answered root stands in the admission line until the pass that resumes it, and nothing is sent to you about that wait: your record's `waitingLine` gives the live place in the line and the line's length, with the line's own fields beside them — `part` (`returned` for an issue whose work came back, `starting` for one that has not started) and `kind`, `partPlace` of `partLength` inside that part, `holdsSlot`, which is true for your answered root because it has held its slot since its start, the key that placed it (`since` for a `returned` issue, `rootRank`, `ownRank` and `rootKey` for a `starting` one) and `reason`, the daemon's own sentence for that place — and `why` on any issue of your tree that is not working now gives the same answer in one word and one sentence (`claim_stopped`, a claim nothing will wake; `waiting`, this line; `blocked`, a link or an open child; `unlisted`, an issue no list places), your resume task says what answered the wait, and you act on neither your place nor your wait, because that resume takes no further slot and the daemon starts you again by itself.
18
18
  - Deliver every criterion of the root spec in this tree. Work leaves it only when a root splits, as a `dispatch ask` for the rest: work outside has no owner.
19
19
  - A problem outside the tree is a `dispatch ask`, never an issue you file, because a person decides whether it needs one (`skill://legion-worker/references/findings.md`). A clear defect is the exception. Fix one in code this tree touches or depends on in this tree's pull request. Send any other to the controller, which gives it to the tree that owns that code.
20
20
  - Before you write a spec or ask a person anything, read the repository's `STRATEGY.md` when it has one and the design principles where it states them (`AGENTS.md`, in this repository), then use a standard best-practice solution; ask only what neither settles, with one recommendation. A design that crosses a Boundary in `STRATEGY.md` goes to its owner before it is built. Find the standard with a web search and with how two or three well-regarded projects solve the problem. Cite them in a few lines of the spec's `Design`. A design far from the standard is a sign to fix the underlying problem, not to add a workaround.
@@ -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