@ferris1225/pi-subagents 6.0.4 → 7.0.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.
@@ -3,9 +3,8 @@
3
3
  *
4
4
  * The process transport lives in cli-run.ts: each attempt runs Pi's own CLI in
5
5
  * `--mode rpc` with a session retained after settlement, and settles on
6
- * `agent_settled`. This module owns selected-to-main model handoff,
7
- * capability-clamped thinking, accounting, and result formatting around those
8
- * attempts.
6
+ * `agent_settled`. This module owns retained sessions and result handling.
7
+ * Worker failures return to main without starting a more expensive model.
9
8
  */
10
9
 
11
10
  import { createHash, randomUUID } from "node:crypto";
@@ -61,29 +60,6 @@ function getFinalOutput(messages: Message[]): string {
61
60
  return "";
62
61
  }
63
62
 
64
- export const RESULT_LINE_MAX = 200;
65
-
66
- export interface TruncatedOutput {
67
- text: string;
68
- truncated: boolean;
69
- shownLines: number;
70
- totalLines: number;
71
- widthClipped: boolean;
72
- }
73
-
74
- export function truncateResultOutput(output: string, maxLines: number): TruncatedOutput {
75
- const lines = output.split("\n");
76
- const totalLines = lines.length;
77
- const widthClipped = lines.some((line) => line.length > RESULT_LINE_MAX);
78
- if (totalLines <= maxLines && !widthClipped) {
79
- return { text: output, truncated: false, shownLines: totalLines, totalLines, widthClipped: false };
80
- }
81
- const kept = lines.slice(0, maxLines).map((line) =>
82
- line.length > RESULT_LINE_MAX ? `${line.slice(0, RESULT_LINE_MAX)}…` : line,
83
- );
84
- return { text: kept.join("\n"), truncated: true, shownLines: kept.length, totalLines, widthClipped };
85
- }
86
-
87
63
  const RESULT_ARTIFACT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
88
64
  const RESULT_ARTIFACT_MAX_FILES_PER_PROJECT = 50;
89
65
  // Explicit current prefix plus the strict timestamp/token convention used by 1.1.0.
@@ -253,7 +229,7 @@ export function getResultOutput(result: SingleResult): string {
253
229
  return error || output || "(no output)";
254
230
  }
255
231
 
256
- /** Model handoff preserves useful history, but main or siblings may have edited
232
+ /** A continuation preserves useful history, but main or siblings may have edited
257
233
  * the workspace since the selected model last read it. */
258
234
  const RESUME_CONTINUATION_RULES =
259
235
  "Use the earlier session history as evidence. The current objective below takes precedence over earlier task requests; preserve earlier constraints unless it changes them. Reuse relevant completed work and checks. The workspace may have changed while this thread was inactive: before editing a file, re-read it unless you read it during this continuation. The current cwd is authoritative; do not reuse paths to an earlier temporary worktree. Finish with the result-only handoff your role requires.";
@@ -274,12 +250,6 @@ async function createSessionDir(root: string): Promise<string> {
274
250
  return dir;
275
251
  }
276
252
 
277
- function buildFallbackResumeReason(fromModel?: string): string {
278
- return fromModel
279
- ? `the selected model (${fromModel}) failed at the model/provider level, so the current main model is continuing`
280
- : "the selected model failed at the model/provider level, so the current main model is continuing";
281
- }
282
-
283
253
  export interface RunSingleOptions {
284
254
  defaultCwd: string;
285
255
  agent: AgentConfig;
@@ -287,8 +257,6 @@ export interface RunSingleOptions {
287
257
  task: string;
288
258
  cwd?: string;
289
259
  thinkingLevel?: ThinkingLevel;
290
- /** Resolve the effective level for each runtime model candidate. */
291
- thinkingLevelForModel?: (modelRef?: string) => ThinkingLevel;
292
260
  idleTimeoutMs?: number;
293
261
  sessionDir?: string;
294
262
  sessionId?: string;
@@ -299,13 +267,12 @@ export interface RunSingleOptions {
299
267
  scratchRoot: string;
300
268
  /** Plain-text prompt passed to Pi over stdin. */
301
269
  stdinText?: string;
302
- /** Refresh parent-derived tools immediately before every selected model and
303
- * selected-to-main fallback process is spawned. */
304
- resolveAgentForAttempt?: (agent: AgentConfig) => AgentConfig;
270
+ /** Refresh parent-derived tools immediately before the worker is spawned. */
271
+ resolveAgentBeforeLaunch?: (agent: AgentConfig) => AgentConfig;
305
272
  signal?: AbortSignal;
306
273
  onLive?: (event: SubagentLiveEvent) => void;
307
274
  env?: NodeJS.ProcessEnv;
308
- /** Stable logical-generation controller shared across model attempts. */
275
+ /** Stable logical-generation controller for startup, steering, and cancellation. */
309
276
  control?: RunControl;
310
277
  startupTimeoutMs?: number;
311
278
  }
@@ -367,18 +334,8 @@ async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult>
367
334
  return result;
368
335
  }
369
336
 
370
- /**
371
- * Run one logical generation on the selected model, then hand directly to the
372
- * current main model after any model/provider-level failure. A launch failure is returned to main without replaying an ambiguous prompt.
373
- * Both attempts resume the same retained Pi session.
374
- */
375
- export async function runSingleAgentWithMainFallback(
376
- options: RunSingleOptions,
377
- mainFallbackRef?: string,
378
- ): Promise<SingleResult> {
379
- const agent = options.agent;
380
- const launchedRef = agent?.model;
381
-
337
+ /** Run one generation on the chosen worker, preserving its session for follow-ups. */
338
+ export async function runWorker(options: RunSingleOptions): Promise<SingleResult> {
382
339
  const sessionId = options.sessionId ?? randomUUID();
383
340
  const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
384
341
  const baseOptions: RunSingleOptions = {
@@ -387,146 +344,37 @@ export async function runSingleAgentWithMainFallback(
387
344
  ? { stdinText: buildResumePrompt(options.task, "a follow-up was requested") }
388
345
  : {}),
389
346
  };
390
- if (!options.sessionDir) {
391
- // Surface the fresh session immediately so the dispatching thread can
392
- // persist a durable checkpoint before the child settles.
393
- try {
394
- options.onLive?.({ kind: "session", sessionId, sessionDir });
395
- } catch {
396
- /* never throw from event handling */
397
- }
347
+ try {
348
+ if (!options.sessionDir) options.onLive?.({ kind: "session", sessionId, sessionDir });
349
+ options.onLive?.({ kind: "model", model: options.agent.model, thinking: options.thinkingLevel });
350
+ } catch {
351
+ /* never throw from event handling */
398
352
  }
399
-
400
- const dispatchFailure = async (error: unknown): Promise<SingleResult> => {
353
+ let result: SingleResult;
354
+ try {
355
+ result = controlledDisposition(baseOptions) ?? await runSingleAgent({
356
+ ...baseOptions,
357
+ agent: options.resolveAgentBeforeLaunch?.(options.agent) ?? options.agent,
358
+ });
359
+ } catch (error) {
401
360
  const errorMessage = error instanceof Error ? error.message : String(error);
402
- const hasSession = sessionExists(sessionDir, sessionId);
403
- if (!hasSession && !options.sessionDir) {
404
- await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
405
- }
406
- return {
407
- agent: options.agentName,
408
- task: options.control?.getObjective() ?? options.task,
409
- exitCode: 1,
410
- messages: [],
411
- stderr: errorMessage,
412
- usage: emptyUsage(),
413
- model: options.agent.model,
414
- thinking: options.thinkingLevel,
415
- stopReason: "error",
416
- errorMessage,
417
- dispatchFailed: true,
418
- ...(hasSession || options.sessionDir ? { sessionId, sessionDir } : {}),
361
+ result = {
362
+ agent: options.agentName, task: options.task, exitCode: 1,
363
+ messages: [], stderr: errorMessage, usage: emptyUsage(),
364
+ model: options.agent.model, thinking: options.thinkingLevel,
365
+ stopReason: "error", errorMessage, dispatchFailed: true,
419
366
  };
420
- };
421
-
422
- const runAttempt = async (opts: RunSingleOptions): Promise<SingleResult> => {
423
- const immediate = controlledDisposition(opts);
424
- if (immediate) return immediate;
425
- try {
426
- const attemptOptions = opts.resolveAgentForAttempt ? { ...opts, agent: opts.resolveAgentForAttempt(opts.agent) } : opts;
427
- const result = await runSingleAgent(attemptOptions);
428
- return controlledDisposition(opts, result) ?? result;
429
- } catch (error) {
430
- const failed = await dispatchFailure(error);
431
- return controlledDisposition(opts, failed) ?? failed;
432
- }
433
- };
434
-
435
- const selectedRef = launchedRef?.trim() || undefined;
436
- const normalizedMainRef = mainFallbackRef?.trim() || undefined;
437
- const candidates: Array<{ agent: AgentConfig; ref?: string }> = [
438
- { agent, ref: selectedRef },
439
- ];
440
- if (normalizedMainRef && normalizedMainRef !== selectedRef) {
441
- candidates.push({ agent: { ...agent, model: normalizedMainRef }, ref: normalizedMainRef });
442
367
  }
443
-
444
- let fallbackUsed = false;
445
- let result: SingleResult | undefined;
446
- const priorFailedTools: NonNullable<SingleResult["failedTools"]> = [];
447
- const priorUsage = emptyUsage();
448
-
449
- const retainAttemptDiagnostics = (attempt: SingleResult): void => {
450
- priorFailedTools.push(...(attempt.failedTools ?? []));
451
- priorUsage.input += attempt.usage.input;
452
- priorUsage.output += attempt.usage.output;
453
- priorUsage.cacheRead += attempt.usage.cacheRead;
454
- priorUsage.cacheWrite += attempt.usage.cacheWrite;
455
- priorUsage.cost += attempt.usage.cost;
456
- priorUsage.turns += attempt.usage.turns;
457
- priorUsage.contextTokens = attempt.usage.contextTokens || priorUsage.contextTokens;
458
- };
459
-
460
- const finish = async (settled: SingleResult): Promise<SingleResult> => {
461
- if (priorFailedTools.length > 0) {
462
- settled.failedTools = [...priorFailedTools, ...(settled.failedTools ?? [])];
463
- }
464
- if (
465
- priorUsage.turns || priorUsage.input || priorUsage.output || priorUsage.cacheRead ||
466
- priorUsage.cacheWrite || priorUsage.cost || priorUsage.contextTokens
467
- ) {
468
- settled.usage = {
469
- input: priorUsage.input + settled.usage.input,
470
- output: priorUsage.output + settled.usage.output,
471
- cacheRead: priorUsage.cacheRead + settled.usage.cacheRead,
472
- cacheWrite: priorUsage.cacheWrite + settled.usage.cacheWrite,
473
- cost: priorUsage.cost + settled.usage.cost,
474
- turns: priorUsage.turns + settled.usage.turns,
475
- contextTokens: settled.usage.contextTokens || priorUsage.contextTokens,
476
- };
477
- }
478
- const persistedSession = sessionExists(sessionDir, sessionId);
479
- if (!settled.dispatchFailed || persistedSession || options.sessionDir) {
480
- settled.sessionId ??= sessionId;
481
- settled.sessionDir ??= sessionDir;
482
- } else {
483
- await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
484
- settled.sessionId = undefined;
485
- settled.sessionDir = undefined;
486
- }
487
- settled.task = options.control?.getObjective() ?? settled.task;
488
- if (fallbackUsed && launchedRef) settled.modelFallbackFrom = launchedRef;
489
- options.control?.markSettled();
490
- return settled;
491
- };
492
-
493
- for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
494
- const candidate = candidates[candidateIndex];
495
- fallbackUsed ||= candidateIndex > 0;
496
- const previousModel = result?.model ?? candidates[candidateIndex - 1]?.ref;
497
- const candidateThinking = options.thinkingLevelForModel?.(candidate.ref) ?? options.thinkingLevel;
498
- const candidateOptions: RunSingleOptions = {
499
- ...baseOptions,
500
- agent: candidate.agent,
501
- thinkingLevel: candidateThinking,
502
- ...(candidateIndex > 0
503
- ? {
504
- stdinText: buildResumePrompt(
505
- options.control?.getObjective() ?? options.task,
506
- buildFallbackResumeReason(previousModel),
507
- ),
508
- }
509
- : {}),
510
- };
511
- try {
512
- options.onLive?.({
513
- kind: "model",
514
- model: candidate.ref,
515
- thinking: candidateThinking,
516
- ...(candidateIndex > 0 && launchedRef ? { fallbackFrom: launchedRef } : {}),
517
- });
518
- } catch {
519
- /* never throw from event handling */
520
- }
521
-
522
- result = await runAttempt(candidateOptions);
523
- if (result.stopReason === "aborted") return finish(result);
524
- if (!isModelLevelFailure(result)) return finish(result);
525
- // Any model-level failure advances immediately to the sole fallback (the
526
- // current main model). Retain selected-attempt tool diagnostics and usage;
527
- // ordinary task/tool failures returned above without a handoff.
528
- if (candidateIndex < candidates.length - 1) retainAttemptDiagnostics(result);
368
+ result = controlledDisposition(baseOptions, result) ?? result;
369
+ if (!result.dispatchFailed || sessionExists(sessionDir, sessionId) || options.sessionDir) {
370
+ result.sessionId ??= sessionId;
371
+ result.sessionDir ??= sessionDir;
372
+ } else {
373
+ await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
374
+ result.sessionId = undefined;
375
+ result.sessionDir = undefined;
529
376
  }
530
-
531
- return finish(result!);
377
+ result.task = options.control?.getObjective() ?? result.task;
378
+ options.control?.markSettled();
379
+ return result;
532
380
  }
@@ -108,10 +108,6 @@ export interface WorktreeIsolation {
108
108
  getContinuationCheckpoint(): WorktreeCheckpoint | undefined;
109
109
  /** Remove an unused worktree whose dispatch was cancelled. */
110
110
  discard(): Promise<void>;
111
- /** Whether anything is pending against the integration base — the same
112
- * question finalization answers as `hadChanges`, asked before settlement so
113
- * policy can tell a run that produced a diff from one that produced none. */
114
- hasPendingChanges(): Promise<boolean>;
115
111
  /** Idempotent across stale generations and repeated stop/shutdown paths. */
116
112
  finalize(): Promise<WorktreeFinalization>;
117
113
  }
@@ -387,16 +383,6 @@ class GitWorktreeIsolation implements WorktreeIsolation {
387
383
  return this.discardPromise;
388
384
  }
389
385
 
390
- async hasPendingChanges(): Promise<boolean> {
391
- // A settled worktree already recorded the answer; asking Git again after
392
- // removal would fail. Diffing the integration base (not HEAD) excludes
393
- // previously integrated work from the recovered run's pending changes.
394
- if (this.currentState === "no_changes") return false;
395
- if (this.currentState !== "active" || !existsSync(this.worktreePath)) return true;
396
- const diff = await this.collectChanges(this.integrationBaseHead);
397
- return diff.stdout.length > 0;
398
- }
399
-
400
386
  finalize(): Promise<WorktreeFinalization> {
401
387
  if (this.finalization) return this.finalization;
402
388
  this.currentState = "finalizing";
@@ -7,34 +7,16 @@
7
7
  * failure directly so it is never delayed.
8
8
  */
9
9
 
10
- import { formatUsageTokens, sumUsage, type RunWaitReason } from "../presentation/monitor.ts";
10
+ import { formatUsageTokens, sumUsage } from "../presentation/monitor.ts";
11
11
  import type { UsageStats } from "../execution/run-control.ts";
12
- export interface CompletionBatchTimings {
13
- debounceMs: number;
14
- maxWaitMs: number;
15
- }
16
12
 
17
- const DEFAULT_COMPLETION_BATCH_TIMINGS: CompletionBatchTimings = {
18
- debounceMs: 150,
19
- maxWaitMs: 1_000,
20
- };
13
+ const COMPLETION_DEBOUNCE_MS = 150;
14
+ const COMPLETION_MAX_WAIT_MS = 1_000;
21
15
 
22
16
  type TimerHandle = ReturnType<typeof setTimeout>;
23
17
 
24
- function unrefHandle(handle: TimerHandle): void {
25
- if (
26
- handle &&
27
- typeof handle === "object" &&
28
- "unref" in handle &&
29
- typeof (handle as { unref: unknown }).unref === "function"
30
- ) {
31
- (handle as { unref: () => void }).unref();
32
- }
33
- }
34
-
35
18
  export interface CompletionBatcherOptions<T> {
36
19
  emit: (items: T[]) => void;
37
- timings?: Partial<CompletionBatchTimings>;
38
20
  }
39
21
 
40
22
  export interface CompletionBatcher<T> {
@@ -47,7 +29,6 @@ export interface CompletionBatcher<T> {
47
29
  }
48
30
 
49
31
  export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>): CompletionBatcher<T> {
50
- const timings = { ...DEFAULT_COMPLETION_BATCH_TIMINGS, ...options.timings };
51
32
  let pending: T[] = [];
52
33
  let debounceTimer: TimerHandle | null = null;
53
34
  let maxWaitTimer: TimerHandle | null = null;
@@ -76,12 +57,12 @@ export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>)
76
57
  pending.push(item);
77
58
 
78
59
  if (debounceTimer !== null) clearTimeout(debounceTimer);
79
- debounceTimer = setTimeout(emitGroup, timings.debounceMs);
80
- unrefHandle(debounceTimer);
60
+ debounceTimer = setTimeout(emitGroup, COMPLETION_DEBOUNCE_MS);
61
+ debounceTimer.unref();
81
62
 
82
63
  if (maxWaitTimer === null) {
83
- maxWaitTimer = setTimeout(emitGroup, timings.maxWaitMs);
84
- unrefHandle(maxWaitTimer);
64
+ maxWaitTimer = setTimeout(emitGroup, COMPLETION_MAX_WAIT_MS);
65
+ maxWaitTimer.unref();
85
66
  }
86
67
  },
87
68
  flush: emitGroup,
@@ -97,7 +78,7 @@ export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>)
97
78
  export interface CompletionMessageItem {
98
79
  agent: string;
99
80
  block: string;
100
- /** Final usage of the underlying run (or chain); aggregated into the group totals. */
81
+ /** Final usage of the underlying run; aggregated into the group totals. */
101
82
  usage?: UsageStats;
102
83
  /** Model ref that produced this run's usage; group totals stay per model
103
84
  * instead of summing different models' spend into one number. */
@@ -143,12 +124,8 @@ export interface ActiveRunFoot {
143
124
  agent: string;
144
125
  /** Optional content label (task-derived) shown next to the agent name. */
145
126
  label?: string;
146
- /** Startup state before a child emits activity. */
147
- wait?: RunWaitReason;
148
- }
149
-
150
- function activeRunWaitTag(wait: RunWaitReason | undefined): string {
151
- return wait ? " (starting)" : "";
127
+ /** The child process is still starting. */
128
+ starting?: boolean;
152
129
  }
153
130
 
154
131
  /**
@@ -163,7 +140,7 @@ export function formatActiveRunsFooter(runs: readonly ActiveRunFoot[], maxListed
163
140
  if (runs.length === 0) return "";
164
141
  const listed = runs.slice(0, maxListed);
165
142
  const items = listed
166
- .map((run) => `#${run.id} ${run.agent}${run.label ? `·${run.label}` : ""}${activeRunWaitTag(run.wait)}`)
143
+ .map((run) => `#${run.id} ${run.agent}${run.label ? `·${run.label}` : ""}${run.starting ? " (starting)" : ""}`)
167
144
  .join(", ");
168
145
  const more = runs.length > listed.length ? `, +${runs.length - listed.length} more` : "";
169
146
  return `\n\n⚠ ${runs.length} other run${runs.length === 1 ? "" : "s"} still active: ${items}${more}. Do not conclude the overall task yet — their results wake you automatically.`;
@@ -1,11 +1,11 @@
1
1
  /**
2
- * Shared background-dispatch machinery used by both delegation tools.
2
+ * Shared background-dispatch machinery for fresh runs and completed-run
3
+ * follow-ups.
3
4
  *
4
- * The `subagent` tool and the workflow runner start children through the same
5
- * dispatcher, live-activity projection, terminal-notification path, and tool-card
6
- * details builder. Keeping them here means a workflow node is an ordinary
7
- * managed run: same lifecycle ownership, isolation, admission, durable checkpointing,
8
- * and completion accounting.
5
+ * `subagent` and `subagent_message` start children through the same
6
+ * dispatcher, live-activity projection, terminal-notification path, and
7
+ * tool-card details builder, so every run shares lifecycle ownership,
8
+ * isolation, admission, durable checkpointing, and completion accounting.
9
9
  */
10
10
 
11
11
  import { createBackgroundDispatcher } from "./thread-lifecycle.ts";
@@ -90,7 +90,7 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
90
90
  }
91
91
  break;
92
92
  case "model":
93
- monitor.setModel(runId, e.model, e.fallbackFrom);
93
+ monitor.setModel(runId, e.model);
94
94
  monitor.setThinking(runId, e.thinking);
95
95
  break;
96
96
  case "usage":
@@ -20,7 +20,6 @@ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
20
20
  import { uptime } from "node:os";
21
21
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
22
22
  import type { UsageStats } from "../execution/run-control.ts";
23
- import { migrateStoredRecordRoles } from "../configuration/role-migration.ts";
24
23
  import type { SubagentThread } from "./runtime.ts";
25
24
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
26
25
  import { isManagedSessionDir, isManagedWorktreeLayout, samePath } from "../isolation/managed-paths.ts";
@@ -84,8 +83,6 @@ export interface ThreadRecord {
84
83
  executionCwd: string;
85
84
  /** Resolved (clamped) level of the last generation. */
86
85
  thinkingLevel?: string;
87
- /** Originally requested level, retained with the recovery metadata. */
88
- requestedThinkingLevel?: string;
89
86
  isolation: IsolationMode;
90
87
  state: "parked" | "completed" | "failed";
91
88
  elapsedMs: number;
@@ -182,9 +179,6 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
182
179
  cwd: raw.cwd,
183
180
  executionCwd: typeof raw.executionCwd === "string" && raw.executionCwd ? raw.executionCwd : raw.cwd,
184
181
  ...(typeof raw.thinkingLevel === "string" && raw.thinkingLevel ? { thinkingLevel: raw.thinkingLevel } : {}),
185
- ...(typeof raw.requestedThinkingLevel === "string" && raw.requestedThinkingLevel
186
- ? { requestedThinkingLevel: raw.requestedThinkingLevel }
187
- : {}),
188
182
  isolation: raw.isolation,
189
183
  state: raw.state,
190
184
  elapsedMs: typeof raw.elapsedMs === "number" && Number.isFinite(raw.elapsedMs) ? Math.max(0, raw.elapsedMs) : 0,
@@ -201,7 +195,6 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
201
195
  }
202
196
 
203
197
  interface ThreadManifestRead {
204
- rolesMigrated?: boolean;
205
198
  sourceCount: number;
206
199
  records: ThreadRecord[];
207
200
  }
@@ -210,10 +203,7 @@ async function readManifest(path: string): Promise<ThreadManifestRead> {
210
203
  try {
211
204
  const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
212
205
  if (!Array.isArray(parsed?.records)) throw new Error(`Invalid thread manifest: ${path}`);
213
- let rolesMigrated = false;
214
- for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
215
206
  return {
216
- rolesMigrated,
217
207
  sourceCount: parsed.records.length,
218
208
  records: parsed.records.flatMap((record) => {
219
209
  const normalized = normalizeRecord(record);
@@ -330,7 +320,7 @@ export async function readThreadRecords(configPath: string): Promise<ThreadRecor
330
320
  .map((path) => withManifestMutation(path, async () => {
331
321
  const manifest = await readManifest(path);
332
322
  const validated = await validatedManifestRecords(configPath, path, manifest.records);
333
- if (manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
323
+ if (validated.length !== manifest.sourceCount) await writeManifest(path, validated);
334
324
  return validated;
335
325
  })),
336
326
  );
@@ -403,19 +393,19 @@ function summarizeResult(result: SingleResult): ThreadResultSummary | undefined
403
393
 
404
394
  /** Project a live thread into its durable record. Only handles whose
405
395
  * filesystem is still meaningful are persisted; finalized-and-removed
406
- * worktrees keep their checkpoint commit as recovery evidence. */
396
+ * worktrees keep their checkpoint commit as recovery evidence. An upsert keeps
397
+ * the stored record's creation time. */
407
398
  export function threadRecordFromThread(
408
399
  thread: SubagentThread,
409
400
  state: "parked" | "completed" | "failed",
410
- previous?: ThreadRecord,
411
- now = Date.now(),
412
401
  ): ThreadRecord {
402
+ const now = Date.now();
413
403
  const worktree = thread.worktree ? worktreeSnapshot(thread.worktree) : undefined;
414
- thread.durableId ??= previous ? threadRecordIdentity(previous) : randomUUID();
404
+ thread.durableId ??= randomUUID();
415
405
  return {
416
406
  durableId: thread.durableId,
417
407
  runId: thread.id,
418
- createdAt: previous?.createdAt ?? now,
408
+ createdAt: now,
419
409
  updatedAt: now,
420
410
  generation: thread.generation,
421
411
  agentName: thread.agentName,
@@ -423,7 +413,6 @@ export function threadRecordFromThread(
423
413
  cwd: thread.cwd,
424
414
  executionCwd: thread.executionCwd,
425
415
  ...(thread.thinkingLevel ? { thinkingLevel: thread.thinkingLevel } : {}),
426
- ...(thread.requestedThinkingLevel ? { requestedThinkingLevel: thread.requestedThinkingLevel } : {}),
427
416
  isolation: thread.isolation,
428
417
  state,
429
418
  elapsedMs: thread.elapsedMs,
@@ -487,7 +476,7 @@ export async function pruneThreadRecords(
487
476
  const records = manifest.records;
488
477
  if (manifest.sourceCount === 0) return;
489
478
  const validity = await Promise.all(records.map((record) => validateThreadRecord(configPath, path, record)));
490
- let changed = Boolean(manifest.rolesMigrated) || manifest.sourceCount !== records.length || validity.some((valid) => !valid);
479
+ let changed = manifest.sourceCount !== records.length || validity.some((valid) => !valid);
491
480
  const kept: ThreadRecord[] = [];
492
481
  for (const [index, record] of records.entries()) {
493
482
  if (!validity[index]) continue;
@@ -41,7 +41,6 @@ export interface SubagentThread {
41
41
  /** Actual child cwd (the equivalent path inside an isolated worktree). */
42
42
  executionCwd: string;
43
43
  thinkingLevel?: ThinkingLevel;
44
- requestedThinkingLevel?: ThinkingLevel;
45
44
  isolation: IsolationMode;
46
45
  worktree?: WorktreeIsolation;
47
46
  /** Original durable evidence retained when its worktree handle is unavailable. */
@@ -61,8 +60,7 @@ export interface SubagentThread {
61
60
  elapsedMs: number;
62
61
  /** Terminal or interrupted partial result; independent of the transient monitor row. */
63
62
  lastResult?: SingleResult;
64
- /** A destructive stop retires context even if the active child settles later. */
65
- retireOnSettle?: boolean;
63
+ /** Retired by a destructive stop: its session is deleted and it cannot be continued. */
66
64
  retired?: boolean;
67
65
  /** All owners finalize under the same original-repository lane. */
68
66
  finalizeIsolation: (generation: number, result?: SingleResult) => Promise<WorktreeFinalization | undefined>;
@@ -182,7 +180,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
182
180
  id: run.id,
183
181
  agent: run.agent,
184
182
  label: run.label,
185
- ...(run.status === "queued" && run.waitReason ? { wait: run.waitReason } : {}),
183
+ ...(run.status === "queued" ? { starting: true } : {}),
186
184
  }));
187
185
  const message = {
188
186
  customType: "subagent-result",
@@ -271,10 +269,9 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
271
269
  continue;
272
270
  }
273
271
  if (thread.lifecycleOperation === "settle") continue;
272
+ // Unlike subagent_stop, shutdown interrupts to the last checkpoint and
273
+ // preserves session/worktree artifacts for manual recovery.
274
274
  thread.lifecycleOperation = "stop";
275
- // Deliberately NOT retireOnSettle: shutdown interrupts to the last
276
- // checkpoint and preserves session/worktree artifacts for manual recovery.
277
- thread.retireOnSettle = false;
278
275
  if (liveStates.has(thread.state)) thread.state = "stopped";
279
276
  }
280
277
  runtime.completionBatcher.dispose();
@@ -35,7 +35,6 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
35
35
  const stopVersion = ++thread.lifecycleVersion;
36
36
  thread.lifecycleOperation = "stop";
37
37
  thread.retired = true;
38
- thread.retireOnSettle = true;
39
38
  thread.state = "stopped";
40
39
  const completion = thread.generationCompletion;
41
40
  let releaseQuiescence!: () => void;
@@ -60,7 +59,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
60
59
  // Interrupt every claimed generation before awaiting any one of them.
61
60
  // An isolated stop may need the repository lane for final integration;
62
61
  // cancelling all holders first prevents stop-all from waiting behind a
63
- // later shared workflow that this same operation has not interrupted yet.
62
+ // later run that this same operation has not interrupted yet.
64
63
  const interruptionPromises = claimed.map(({ thread, stopMessage, controller }) => {
65
64
  const stopping = thread.control.stop(stopMessage).catch(() => undefined);
66
65
  runtime.backgroundQueue.cancel(controller);