pi-legion 3.0.1 → 3.1.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.
@@ -74,9 +74,13 @@ import { provisionWorktree } from "./provision.ts";
74
74
 
75
75
  export interface BudgetRefusedEvent {
76
76
  type: "budget_refused";
77
- requestedMaxDepth: number;
78
- effectiveMaxDepth: number;
79
77
  reason: string;
78
+ /** Present for maxDepth hard-cap warnings. */
79
+ requestedMaxDepth?: number;
80
+ /** Present for maxDepth hard-cap warnings. */
81
+ effectiveMaxDepth?: number;
82
+ /** Role name when reason is `worktree_denied_non_centurion` (#214). */
83
+ agent?: string;
80
84
  }
81
85
 
82
86
  export interface OrchestratorLegionContext {
@@ -128,7 +132,15 @@ export interface CollectResult {
128
132
  }
129
133
 
130
134
  export const COLLECT_GRACE_EXTENSIONS = 2;
131
- /** Shown when the launch-time collect budget elapses and the child is still in-turn. */
135
+ /**
136
+ * Shown when this collect() call's budget elapses and the child is still in-turn.
137
+ *
138
+ * The "cumulative since launch" wording below is legacy: `collect()` starts its
139
+ * deadline from the moment it is called (`orchestrator.ts` `let deadline = ...`),
140
+ * not from launch. The literal is user-visible and asserted in integration tests,
141
+ * so D6 of `docs/contracts/vexillatio-nonblocking-launch-v1.md` deliberately left
142
+ * it untouched; do not read it as the actual budget origin.
143
+ */
132
144
  export const COLLECT_DEADLINE_REASON = "collect deadline (cumulative since launch) exceeded; child still alive";
133
145
  /** Shown when a live child's session ends on an OpenAI/GPT connection blip. */
134
146
  export const TRANSIENT_CONNECTION_REASON = "transient connection error; RPC child still alive";
@@ -257,6 +269,7 @@ export class Orchestrator {
257
269
  private readonly legion?: OrchestratorLegionContext;
258
270
  private readonly requestedDepthCap?: number;
259
271
  private depthWarningEmitted = false;
272
+ private worktreeDeniedWarningEmitted = false;
260
273
  private spawned = 0;
261
274
  private readonly children = new Map<string, ChildRecord>();
262
275
  private readonly nameCounter = new Map<string, number>();
@@ -524,6 +537,26 @@ export class Orchestrator {
524
537
  this.onBudgetRefused?.(event);
525
538
  }
526
539
 
540
+ /**
541
+ * #214: only `name === "centurion"` may hold worktree isolation.
542
+ * Non-centurion requests warn once per run (like warnDepthCap) and are
543
+ * forced to false — never thrown.
544
+ */
545
+ private warnWorktreeDenied(agentName: string): void {
546
+ if (this.worktreeDeniedWarningEmitted) return;
547
+ this.worktreeDeniedWarningEmitted = true;
548
+ const event: BudgetRefusedEvent = {
549
+ type: "budget_refused",
550
+ reason: "worktree_denied_non_centurion",
551
+ agent: agentName,
552
+ };
553
+ console.warn(
554
+ `[pi-legion] worktree denied for non-centurion role '${agentName}'; forced worktree: false. ` +
555
+ `Fix the role card (set worktree: false) or dispatch a centurion for isolated parallel writers.`,
556
+ );
557
+ this.onBudgetRefused?.(event);
558
+ }
559
+
527
560
  async launch(input: {
528
561
  agent: AgentConfig;
529
562
  task: string;
@@ -562,8 +595,18 @@ export class Orchestrator {
562
595
  let sessionFile = previous?.sessionFile ?? this.sessionFileFor(name);
563
596
  const tempDir = this.runDir;
564
597
  const parentRole = this.legion ? getNode(this.legion.db, this.legion.nodeId)?.role : undefined;
565
- const worktree = this.legion && input.agent.name === "centurion"
566
- ? true
598
+ const isCenturion = input.agent.name === "centurion";
599
+ // #214 D4: only centurion may hold worktree. Legion path still forces
600
+ // centurion→true and centurion-parent→member false; non-centurion
601
+ // requests from any source are demoted below (D1: warn, never throw).
602
+ let worktree = isCenturion
603
+ ? (this.legion
604
+ ? true
605
+ : resolveLaunchWorktree({
606
+ roleDefault: input.agent.worktree,
607
+ launch: input.worktree,
608
+ parentInWorktree: isInsideChildWorktree(this.cwd),
609
+ }))
567
610
  : this.legion && parentRole === "centurion"
568
611
  ? false
569
612
  : resolveLaunchWorktree({
@@ -571,6 +614,10 @@ export class Orchestrator {
571
614
  launch: input.worktree,
572
615
  parentInWorktree: isInsideChildWorktree(this.cwd),
573
616
  });
617
+ if (!isCenturion && worktree === true) {
618
+ this.warnWorktreeDenied(input.agent.name);
619
+ worktree = false;
620
+ }
574
621
  // Spawn-mode arbitration (contract D2). `resolveSpawnMode` only reports the
575
622
  // configured intent; the launch context decides whether an OMITTED mode can
576
623
  // actually run in-process. An omitted mode falls back to rpc when this
@@ -614,7 +661,7 @@ export class Orchestrator {
614
661
  // `launch({ worktree: false })` — that override now wins as it should.
615
662
  if (inProcess && worktree) {
616
663
  throw new SubagentError(
617
- `spawnMode "inprocess" cannot use worktree isolation for '${name}'`,
664
+ `spawnMode "inprocess" cannot use worktree isolation for '${name}'; set worktree: false`,
618
665
  ErrorCodes.INVALID_PARAMS,
619
666
  );
620
667
  }
@@ -656,7 +703,8 @@ export class Orchestrator {
656
703
  ? this.depth + 1
657
704
  : Math.min(this.maxDepthValue, this.depth + roleDepth, MAX_NESTED_PATH_ENTRIES),
658
705
  nodeId,
659
- herdr: { supervisor: "rpc", node_id: nodeId },
706
+ // #209: the run record carries the ARBITRATED backend, not a literal.
707
+ herdr: { supervisor: mode, node_id: nodeId },
660
708
  });
661
709
  createdRunId = run.runId;
662
710
  sessionFile = this.legion.runStore.sessionFileFor(run.runId, name);
@@ -740,6 +788,8 @@ export class Orchestrator {
740
788
  previous.acceptance = undefined;
741
789
  previous.outputFile = undefined;
742
790
  previous.model = startedModel;
791
+ // A resume re-arbitrates the backend; keep the record truthful (#209).
792
+ previous.spawnMode = mode;
743
793
  this.children.set(name, previous);
744
794
  }
745
795
  const child = previous ?? this.recordChild({
@@ -747,6 +797,7 @@ export class Orchestrator {
747
797
  ...(nodeId ? { nodeId } : {}),
748
798
  agent: input.agent,
749
799
  sessionFile: result.sessionFile,
800
+ spawnMode: mode,
750
801
  ...(startedModel ? { model: startedModel } : {}),
751
802
  ...(input.thinking !== undefined ? { thinking: input.thinking } : input.agent.thinking !== undefined ? { thinking: input.agent.thinking } : {}),
752
803
  ...(worktreePath ? { worktreePath } : {}),
@@ -762,6 +813,8 @@ export class Orchestrator {
762
813
  agent: input.agent.name,
763
814
  kind: input.agent.kind,
764
815
  child,
816
+ // #209: callers render this instead of assuming the RPC backend.
817
+ spawnMode: mode,
765
818
  };
766
819
  } catch (error) {
767
820
  if (spawned) await this.supervisor.retire(name).catch(() => {});
@@ -843,6 +896,8 @@ export class Orchestrator {
843
896
  nodeId?: string;
844
897
  agent: AgentConfig;
845
898
  sessionFile: string;
899
+ /** Arbitrated spawn backend (#209); persisted so later operators see the truth. */
900
+ spawnMode: SpawnMode;
846
901
  model?: string;
847
902
  thinking?: string | false;
848
903
  worktreePath?: string;
@@ -862,6 +917,7 @@ export class Orchestrator {
862
917
  ...(input.agent.completionGuard ? { completionGuard: true } : {}),
863
918
  ...(input.model ? { model: input.model } : {}),
864
919
  ...(input.thinking !== undefined ? { thinking: input.thinking } : {}),
920
+ spawnMode: input.spawnMode,
865
921
  ...(input.worktreePath ? { worktreePath: input.worktreePath } : {}),
866
922
  ...(input.worktreeBranch ? { worktreeBranch: input.worktreeBranch } : {}),
867
923
  };
@@ -954,9 +1010,23 @@ export class Orchestrator {
954
1010
  }
955
1011
  if (opts.signal?.aborted) return abortedSnapshot();
956
1012
  parsed = parseSessionFile(child.sessionFile);
1013
+ // #227 D5: a child whose process is gone cannot produce another message.
1014
+ // When its last turn already ended with a terminal assistant message there
1015
+ // is nothing left to wait for, so finish the completed turn here.
1016
+ //
1017
+ // This is defensive rather than an observable behaviour fix: the
1018
+ // collect-deadline branch below is already gated on `isAlive(name)`, so a
1019
+ // dead child never received the `running` snapshot. Keeping the guard makes
1020
+ // the intent explicit instead of relying on that coincidence — see D5 and
1021
+ // the disclosure in the #227 contract.
1022
+ if (wait === "timeout" && !this.supervisor.isAlive(name) && isLastTurnComplete(parsed)) {
1023
+ return this.finishCollect(child, parsed, deriveOutcome(parsed), deadline);
1024
+ }
957
1025
  let execution = deriveOutcome(parsed);
958
1026
  if (wait === "timeout" && this.supervisor.isAlive(name) && !isLastTurnComplete(parsed)) {
959
- // `timeoutMs` is the budget from launch, not the length of this status check.
1027
+ // `timeoutMs` is measured from THIS collect call, not from the launch (D6).
1028
+ // The constant's "cumulative since launch" wording is legacy; see its
1029
+ // docstring for why it was left as-is.
960
1030
  execution = { ...execution, status: "running", reason: COLLECT_DEADLINE_REASON };
961
1031
  } else if (wait === "gone" && parsed.turns.length === 0) {
962
1032
  execution = { status: "aborted", reason: "RPC child exited before writing session JSONL", model: child.model ?? null };
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Per-child git worktree isolation.
3
3
  *
4
- * Writer roles default to `worktree: true`. Each child gets its own branch
5
- * under the run directory (`git worktree add -b`) so concurrent parent Pis
6
- * do not share a dirty checkout. The child commits there and opens an MR;
7
- * retire leaves the tree on disk (same rationale as keeping the session file).
4
+ * Only the `centurion` role may hold `worktree: true` (#214 / contract §9).
5
+ * Squad members work in-place inside the centurion subtree (or parent cwd).
6
+ * When isolation is granted, the child gets its own branch under the run
7
+ * directory (`git worktree add -b`); retire leaves the tree on disk (same
8
+ * rationale as keeping the session file).
8
9
  */
9
10
 
10
11
  import { execFileSync } from "node:child_process";
@@ -37,7 +37,17 @@ function emptyUsage(): Usage {
37
37
 
38
38
  /** Mutable clock used while folding events; not part of ParsedSession. */
39
39
  export interface GenerationClock {
40
+ /** Nested Unix-ms timestamp of the message that opened this generation window. */
40
41
  awaitingSince?: number;
42
+ /**
43
+ * Same window edge expressed as the enclosing entry's write instant.
44
+ *
45
+ * Sessions may carry only the nested timestamp, only the entry ISO timestamp,
46
+ * or both. Measuring an end against a start from a different axis yields a
47
+ * nonsense span, so each window records both edges and `applyAssistant`
48
+ * pairs like with like.
49
+ */
50
+ awaitingWall?: number;
41
51
  }
42
52
 
43
53
  export function emptyParsedSession(): ParsedSession {
@@ -126,10 +136,13 @@ function accumulateUsage(
126
136
  }
127
137
 
128
138
  /**
129
- * Turn-boundary timestamps for the current-turn elapsed display.
139
+ * Turn-boundary timestamp for the current-turn elapsed display.
130
140
  *
131
- * The nested message `timestamp` is Unix ms (session-format.md); fall back to
132
- * the ISO 8601 entry timestamp for entries written without the nested value.
141
+ * Prefers the nested message `timestamp` (Unix ms, session-format.md) — for the
142
+ * elapsed display the moment generation began is exactly what we want — and
143
+ * falls back to the ISO 8601 entry timestamp for entries written without it.
144
+ * Generation *duration* is measured elsewhere (`applyAssistant`): the nested
145
+ * value marks a start, not a completion, and `durationMs` carries the length.
133
146
  */
134
147
  function messageTimestamp(
135
148
  event: Record<string, unknown>,
@@ -145,6 +158,19 @@ function messageTimestamp(
145
158
  return undefined;
146
159
  }
147
160
 
161
+ /**
162
+ * The instant a message was written, on the same Unix-ms axis as
163
+ * `message.timestamp`. Used for the generation clock so start and end share a
164
+ * basis; a session that only carries the entry ISO timestamp would otherwise
165
+ * mix a wall-clock instant into a Unix-ms subtraction.
166
+ */
167
+ function entryWrittenAt(event: Record<string, unknown>): number | undefined {
168
+ const outer = event.timestamp;
169
+ if (typeof outer !== "string") return undefined;
170
+ const ms = Date.parse(outer);
171
+ return Number.isFinite(ms) ? ms : undefined;
172
+ }
173
+
148
174
  /** Find (or create) the turn an assistant/toolResult message belongs to. */
149
175
  function currentTurn(parsed: ParsedSession): TurnRecord {
150
176
  const existing = parsed.turns.at(-1);
@@ -163,6 +189,7 @@ function applyAssistant(
163
189
  parsed: ParsedSession,
164
190
  message: Record<string, unknown>,
165
191
  timestamp: number | undefined,
192
+ wall: number | undefined,
166
193
  clock: GenerationClock,
167
194
  ): void {
168
195
  const turn = currentTurn(parsed);
@@ -181,7 +208,21 @@ function applyAssistant(
181
208
  });
182
209
  if (timestamp !== undefined) turn.endedAt = timestamp;
183
210
 
184
- if (
211
+ // Generation time spans the wait for the model plus the model call itself. Two
212
+ // strictly paired sources, never mixed:
213
+ // 1. `durationMs` — an exact length reported by the provider, axis-free.
214
+ // 2. entry-to-entry (`wall` − `awaitingWall`) — both edges are write instants,
215
+ // so a session that omits nested timestamps still measures correctly.
216
+ // Subtracting the nested `message.timestamp` is NOT the completion instant: it
217
+ // marks when generation began, so it captures only prompt→first-token latency
218
+ // (2-7ms on real sessions). It survives as a last resort for synthetic or
219
+ // legacy sessions that carry no entry timestamps at all.
220
+ const measured = message.durationMs;
221
+ if (typeof measured === "number" && Number.isFinite(measured) && measured >= 0) {
222
+ parsed.generationMs += measured;
223
+ } else if (wall !== undefined && clock.awaitingWall !== undefined && wall >= clock.awaitingWall) {
224
+ parsed.generationMs += wall - clock.awaitingWall;
225
+ } else if (
185
226
  timestamp !== undefined &&
186
227
  clock.awaitingSince !== undefined &&
187
228
  timestamp >= clock.awaitingSince
@@ -189,6 +230,7 @@ function applyAssistant(
189
230
  parsed.generationMs += timestamp - clock.awaitingSince;
190
231
  }
191
232
  clock.awaitingSince = undefined;
233
+ clock.awaitingWall = undefined;
192
234
 
193
235
  accumulateUsage(parsed.usage, message);
194
236
  if (typeof message.model === "string") parsed.model = message.model;
@@ -201,6 +243,7 @@ function applyToolResult(
201
243
  parsed: ParsedSession,
202
244
  message: Record<string, unknown>,
203
245
  timestamp: number | undefined,
246
+ wall: number | undefined,
204
247
  clock: GenerationClock,
205
248
  ): void {
206
249
  const turn = parsed.turns.at(-1);
@@ -212,6 +255,7 @@ function applyToolResult(
212
255
  }
213
256
  // Tool completion starts the next generation window (model resumes).
214
257
  if (timestamp !== undefined) clock.awaitingSince = timestamp;
258
+ if (wall !== undefined) clock.awaitingWall = wall;
215
259
  }
216
260
 
217
261
  /**
@@ -288,6 +332,9 @@ function applyEvent(
288
332
  const message = event.message as Record<string, unknown> | undefined;
289
333
  if (!message || typeof message !== "object") return;
290
334
  const ts = messageTimestamp(event, message);
335
+ // The entry write instant, on the same Unix-ms axis as `message.timestamp`.
336
+ // Generation timing uses it so both window edges share one basis.
337
+ const wall = entryWrittenAt(event);
291
338
 
292
339
  switch (message.role) {
293
340
  case "user":
@@ -300,13 +347,14 @@ function applyEvent(
300
347
  });
301
348
  // User prompt opens a generation window.
302
349
  if (ts !== undefined) clock.awaitingSince = ts;
350
+ if (wall !== undefined) clock.awaitingWall = wall;
303
351
  break;
304
352
  case "assistant":
305
- applyAssistant(parsed, message, ts, clock);
353
+ applyAssistant(parsed, message, ts, wall, clock);
306
354
  break;
307
355
  case "toolResult":
308
356
  case "tool":
309
- applyToolResult(parsed, message, ts, clock);
357
+ applyToolResult(parsed, message, ts, wall, clock);
310
358
  break;
311
359
  default:
312
360
  break;
@@ -529,6 +577,25 @@ export const NO_ASSISTANT_ABORT_REASON = "no assistant message for the last prom
529
577
  export const PARENT_SESSION_SHUTDOWN_ABORT_REASON =
530
578
  "parent session shutdown retired the child before it produced an assistant message";
531
579
 
580
+ /**
581
+ * The parent turn ended and the abort signal carried no reason (#227 D3b).
582
+ *
583
+ * Upstream writes a reason-less `AbortController` cancellation as
584
+ * `stopReason:"error"` with a bare `"This operation was aborted"` message, which
585
+ * used to be indistinguishable from a real provider failure. The status stays
586
+ * `aborted`; only the reason becomes self-describing.
587
+ */
588
+ export const ABORT_WITHOUT_REASON =
589
+ "parent turn ended (abort signal without a reason)";
590
+
591
+ /**
592
+ * The exact messages `AbortSignal`/`AbortController` produce with no reason.
593
+ * Anchored to the whole message so a longer, meaningful error (a provider
594
+ * message that merely mentions aborting) does not get rewritten.
595
+ */
596
+ const REASONLESS_ABORT_MESSAGE =
597
+ /^(this operation was aborted|the operation was aborted|operation aborted)$/i;
598
+
532
599
  /** True when the last turn (or the whole file) has no assistant message. */
533
600
  export function lastTurnHasNoAssistant(parsed: ParsedSession): boolean {
534
601
  const last = parsed.turns.at(-1);
@@ -631,11 +698,20 @@ function outcomeFromFinalMessage(
631
698
  // F29: a graceful interrupt surfaces as `error` with an abort-ish message.
632
699
  const msg = final.errorMessage ?? "";
633
700
  if (/abort/i.test(msg)) {
701
+ // #227 D3b: a reason-less AbortController cancellation reaches us as
702
+ // the bare engine message. Name it as the parent's abort instead of
703
+ // echoing text that reads like a provider failure. Anything carrying
704
+ // more (notably a `timeout`, or a longer provider sentence) keeps the
705
+ // original message — status is `aborted` either way.
706
+ const reason =
707
+ REASONLESS_ABORT_MESSAGE.test(msg.trim()) && !/timeout/i.test(msg)
708
+ ? ABORT_WITHOUT_REASON
709
+ : msg;
634
710
  return {
635
711
  status: "aborted",
636
712
  stopReason: "error",
637
713
  errorMessage: msg,
638
- reason: msg,
714
+ reason,
639
715
  ...base,
640
716
  };
641
717
  }
@@ -364,6 +364,13 @@ export interface ChildRecord {
364
364
  thinking?: string | false;
365
365
  /** Models that were requested but cannot be represented by the RPC child. */
366
366
  modelDropped?: string[];
367
+ /**
368
+ * Backend this child was actually spawned on, as arbitrated by
369
+ * `Orchestrator.launch` (#209). Optional because run.json records written
370
+ * before the field existed have no value — readers must render those as
371
+ * unknown, never guess a backend.
372
+ */
373
+ spawnMode?: SpawnMode;
367
374
  }
368
375
 
369
376
  export interface RunRecord {
@@ -373,8 +380,11 @@ export interface RunRecord {
373
380
  cwd: string;
374
381
 
375
382
  herdr: {
376
- /** Current transport marker under the historic run.json key. */
377
- supervisor?: "rpc";
383
+ /**
384
+ * Transport marker under the historic run.json key: the arbitrated backend
385
+ * of the run's own process (#209). Absent on legacy records.
386
+ */
387
+ supervisor?: SpawnMode;
378
388
  /** Reserved for M2 tree identity. */
379
389
  node_id?: string;
380
390
  };
@@ -482,6 +492,11 @@ export interface Handle {
482
492
  * silently defeated the ownership audit.
483
493
  */
484
494
  child: ChildRecord;
495
+ /**
496
+ * Backend the orchestrator actually chose for this launch (arbitration
497
+ * result, #209). Callers render this instead of assuming `rpc`.
498
+ */
499
+ spawnMode: SpawnMode;
485
500
  }
486
501
 
487
502
  // =============================================================================