@henryqw/pi-subagent 22.0.1 → 22.2.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/README.md CHANGED
@@ -21,15 +21,20 @@ pi install npm:pi-mcp-adapter
21
21
 
22
22
  ## Use
23
23
 
24
- ![Delegation mode routing and the checked changeset lifecycle through recovery, validation, and promotion](./docs/delegation-routing.svg)
24
+ ![Main, its coordinator extension, and a Herdr subagent through checked work, worker failure, and coordinator interruption](./docs/worker-lifecycle.svg)
25
+
26
+ The coordinator is extension code running in Main's Pi process, not another agent. It persists the request, launches the Herdr subagent, checks its committed work, and reports saved results; Main chooses what to stage and promote. If a worker fails, the coordinator reports attention after the wave settles, not necessarily immediately while siblings work. If Main's Pi process stops, no follow-up is guaranteed: restart and run `/subagent recover` in the canonical repository to classify orphaned interruptions and send Main one recovery report. Main then uses `subagent_status` for exact evidence and deliberate next actions. A stale `running` state does not prove a worker is still active; interrupted or ambiguous actions are never replayed automatically.
25
27
 
26
28
  Ask Main to delegate a bounded task, such as “Have a scout trace sign-in without editing files.” Main uses `delegate_task`; you receive progress and a result or an actionable failure while Main remains available.
27
29
 
28
30
  Commands are for you; tools and the packaged skill are for Main. You do not need to call agent tools or manage candidate identities yourself.
29
31
 
32
+ In the TUI, the compact widget uses one row per visible agent/task: `D` or `I` marks direct or isolated work, and `[S]` or `[I3]` identifies the Role initial (plus the isolated model class: `1` fast, `2` balanced, `3` frontier, `*` fav). Direct rows show the launched model, thinking level, elapsed time, and measured session tokens (`— tok` until usage is available). Isolated rows show the recorded task state and any retained workspace; their status glyphs use the active TUI theme, while the text still names the status without color. Herdr does not currently provide reliable live model, thinking, or token readings for those rows. Attention appears before ordinary work, with a `+N more` summary when direct rows overflow. A ready isolated candidate is **not promoted** to Main. Use `/subagent` or `subagent_status` for exact identities, failures, and recovery.
33
+
30
34
  | Surface | Type | Purpose |
31
35
  | --- | --- | --- |
32
- | `/subagent` | command | Pick direct or isolated work to inspect; send or edit pending instructions for a locally active isolated changeset. Requires interactive TUI or RPC. |
36
+ | `/subagent` | command | Browse work, launch isolated status inspection in a separate Herdr tab with the `fast` model, or send/edit pending instructions. Requires interactive TUI or RPC; inspection also requires a Herdr-managed pane and a read-only `scout` Role. |
37
+ | `/subagent recover` | command | Classify orphaned isolated work in the current canonical repository and send Main one follow-up with request IDs, blockers, and reported next actions. No UI or Herdr pane required. |
33
38
  | `delegate_task` | tool | Start read-only direct work or a durable isolated checked graph. |
34
39
  | `subagent_status` | tool | Read durable isolated state and the exact allowed continuation without replaying work. |
35
40
  | `subagent_resume` | tool | Perform the reported `retry`, `verify`, or `finalize` continuation; does not replace staging or integration. |
@@ -121,21 +126,23 @@ An isolated request has one durable ID, one goal, and 1–8 typed tasks:
121
126
 
122
127
  `dependsOn` controls scheduling. `contextFrom` may name completed text tasks and preserves the declared order. Changesets require focused task checks; a graph with changesets requires final checks. A canonical root `package.json` test script is required: the runner adds `pnpm test` to final checks if missing, and Main runs it on the combined integration checkout before promotion. Checks and judgments bind to exact Git identities; candidate drift, Main drift, mutation during validation, ambiguity, or conflicts stop promotion and retain evidence.
123
128
 
124
- `delegate_task` and `subagent_resume` return a durable request ID after its state is saved; productive work continues while Main is free. Pi delivers completion or attention as a follow-up message in the launching session. Use `subagent_status` if delivery is missed or you need current state.
129
+ `delegate_task`, `subagent_resume`, and `subagent_integrate advance` return a durable request ID after the wave is saved; productive work continues while Main is free. Pi sends a follow-up in the launching session whenever a checked worker becomes ready, and again when the wave finishes or needs attention. Use `subagent_status` if delivery is missed or you need current state.
125
130
 
126
- The worker produces a clean committed candidate, then runs focused preliminary checks and optional judgment. The runner records a ready candidate but **does not integrate it automatically**. Main inspects `subagent_status`, selects each exact candidate with `subagent_stage` in an owned integration worktree, and resolves conflicts there. `subagent_integrate` can advance dependent tasks from a staged snapshot, validate the combined tip with full root checks and optional final judgment, and promote it to Main only after exact validation. A definitive failed combined check/review allows one committed correction in the integration checkout followed by another validation. Main must explicitly promote; promotion and cleanup never silently discard retained work.
131
+ The worker produces a committed candidate without tracked or untracked changes, then runs focused preliminary checks and optional judgment. Ignored generated files do not block candidacy, but prevent automatic worktree cleanup; inspect them before deleting retained work. The runner records each ready candidate immediately but **does not integrate it automatically**. Main can inspect `subagent_status` and use `subagent_stage` to select the exact candidate in an owned integration worktree while siblings are still working; conflicts are resolved there. Stage and resolve are available during an active wave, but rejection and revision wait for the wave to settle. `subagent_integrate` can advance dependent tasks from a staged snapshot, validate the combined tip with full root checks and optional final judgment after the wave settles, and promote it to Main only after exact validation. A definitive failed combined check/review allows one committed correction in the integration checkout followed by another validation. Main must explicitly promote; promotion and cleanup never silently discard retained work.
127
132
 
128
- Open `/subagent` without arguments to pick work by label. The menu shows direct records on this session branch and isolated requests in the current canonical Git checkout (including requests launched in other sessions). Pick a task to inspect status and recovery in separate notices; retained paths and worker identities remain exact even when the request has many attempts or generations. Refresh or choose completed/history for older work. Invalid state IDs are warned about and preserved. Outside Git or when isolated inventory is unavailable, direct recovery still works. Browsing does not resume work or change resources.
133
+ Open `/subagent` without arguments to pick work by label. The menu shows direct records on this session branch and isolated requests in the current canonical Git checkout (including requests launched in other sessions). Pick an isolated request and **Inspect status and recovery** to launch a non-focused Herdr tab with a read-only `scout` Role on the configured `fast` route. Its prompt contains bounded saved status (including retained paths, but not raw launch environment or session transcripts); the analysis stays in that tab and does not queue a Main turn. The tab and session file are recorded for recovery even if launch becomes uncertain. The read-only `subagent_status` tool remains Main's authority for exact identities before any stage or recovery action. If Herdr or the read-only fast route is unavailable, inspection fails without changing the request; Main can use `subagent_status`. Refresh or choose completed/history for older work. Invalid state IDs are warned about and preserved. Outside Git or when isolated inventory is unavailable, direct recovery still works. Browsing does not resume work or change resources.
129
134
 
130
- For a locally active unsealed isolated changeset, choose **Send follow-up instructions** to open a native multiline editor; submission queues the instruction, not a completed revision. Choose **Edit queued instructions** to withdraw *all still-pending* instructions for that selected task before the editor opens. Their full text appears in FIFO order separated by blank lines. Explicit submission queues **one replacement** at the tail. Cancel leaves the withdrawn instructions removed; already-claimed instructions, initial prompts, and automatic corrections cannot be recalled. A worker may seal during editing: failed submission reopens the full submitted text for deliberate editing or copying, never automatically requeues it. Combined text above the single-instruction limit is preserved in the editor but rejected until shortened. Cancelling before withdrawal makes no change. Neither action touches Main's editor or Pi's global Option+Up queue shortcut. No-UI sessions must use the agent tools for inspection and recovery.
135
+ For a locally active unsealed isolated changeset, choose **Send follow-up instructions** to open a native multiline editor; submission queues the instruction, not a completed revision. Choose **Edit queued instructions** to withdraw *all still-pending* instructions for that selected task before the editor opens. Their full text appears in FIFO order separated by blank lines. Explicit submission queues **one replacement** at the tail. Cancel leaves the withdrawn instructions removed; already-claimed instructions, initial prompts, and automatic corrections cannot be recalled. A worker may seal during editing: failed submission reopens the full submitted text for deliberate editing or copying, never automatically requeues it. Combined text above the single-instruction limit is preserved in the editor but rejected until shortened. Cancelling before withdrawal makes no change. Neither action touches Main's editor or Pi's global Option+Up queue shortcut. No-UI sessions can run `/subagent recover` or use agent tools for individual inspection and recovery.
131
136
 
132
137
  A queued follow-up runs after the current turn settles and must produce a new clean commit that passes preliminary checks again. When no queued revision remains, the checked candidate seals immediately; there is no guaranteed post-completion editing window. Late follow-ups fail visibly.
133
138
 
134
139
  ### Isolated recovery
135
140
 
136
- Main uses the recovery tools in the interface table above. The following details describe their exact identity and retained-work requirements.
141
+ After a coordinator interruption, run `/subagent recover` once. It acquires the repository productive lease before changing any orphaned `pending` or `running` state, preserves unreadable state files and retained candidates, and reports blockers and existing continuations to Main without replaying prompts, merges, promotion, or cleanup. If another productive run holds the lease, it only reads status and reports the live owner; wait rather than taking over. Repeating the command is safe. Main uses `subagent_status` for exact identities and the recovery tools in the interface table above for deliberate decisions; the command never stages or promotes. Direct Herdr tab recovery remains in `/subagent`.
142
+
143
+ The following details describe exact identity and retained-work requirements.
137
144
 
138
- Pass the exact `generation`, candidate (`taskId`, `attempt`, `candidate`) and `expectedTip` identities reported by status to stage; pass the generation and combined `expectedTip` to integrate. If Main advances cleanly before promotion, call `subagent_integrate refresh` with the recorded `expectedMain`, old `expectedTip`, and new clean `newMain`. Main must restage selected immutable candidates into the new generation and rerun combined checks. Dirty or divergent Main blocks refresh. Stale identities fail. At most two integration worktrees may remain unreleased per request; a superseded generation is read-only. To release a superseded *clean* integration checkout, call `subagent_integrate` with `{ id, action: "release", generation, expectedTip }`, using that generation's last staged tip (or integration base when no stage completed). To release a rejected candidate after its worker has terminated and all generations using it are released, pass `{ id, action: "release", generation: <latest generation number, or 1>, taskId, attempt, expectedTip: <candidate tip> }`. Release persists each host/checkout/branch step, verifies ownership and cleanliness (including ignored files), and deletes the branch only if its ref still names the exact tip. Dirty, conflicted, changed, or uncertain resources remain for manual inspection; retry the same release after resolving the obstacle. Released checkouts free a retained slot; abort is available after every retained resource is released. Rejection can invalidate dependent work; if fresh dependent execution is impossible, start a new request instead of forcing promotion. Productive requests have no whole-run wall-clock deadline. Resume does not reset the recorded policy or correction count. Child limits, abort signals, process I/O, status inspection, exact termination, and cleanup retain finite safety bounds.
145
+ Pass the exact `generation`, candidate (`taskId`, `attempt`, `candidate`) and `expectedTip` identities reported by status to stage; pass the generation and combined `expectedTip` to integrate. If Main advances cleanly before promotion, call `subagent_integrate refresh` with the recorded `expectedMain`, old `expectedTip`, and new clean `newMain`. Main must restage selected immutable candidates into the new generation and rerun combined checks. Dirty or divergent Main blocks refresh. Stale identities fail. If integration allocation was uncertain, `subagent_stage resolve` first proves the owned checkout is still at its base before starting the selected merge; otherwise it retains the intent. At most two integration worktrees may remain unreleased per request; a superseded generation is read-only. To release a superseded *clean* integration checkout, call `subagent_integrate` with `{ id, action: "release", generation, expectedTip }`, using that generation's last staged tip (or integration base when no stage completed). To release a rejected candidate after its worker has terminated and all generations using it are released, pass `{ id, action: "release", generation: <latest generation number, or 1>, taskId, attempt, expectedTip: <candidate tip> }`. Release persists each host/checkout/branch step, verifies ownership and cleanliness (including ignored files), and deletes the branch only if its ref still names the exact tip. Dirty, conflicted, changed, or uncertain resources remain for manual inspection; retry the same release after resolving the obstacle. Released checkouts free a retained slot; abort is available after every retained resource is released. Rejection can invalidate dependent work; if fresh dependent execution is impossible, start a new request instead of forcing promotion. Productive requests have no whole-run wall-clock deadline. Resume does not reset the recorded policy or correction count. Child limits, abort signals, process I/O, status inspection, exact termination, and cleanup retain finite safety bounds.
139
146
 
140
147
  The extension never pushes, opens a pull request, publishes, deploys, force-cleans recoverable work, or silently falls back to Main.
141
148
 
@@ -8,9 +8,11 @@ export interface DirectHandle {
8
8
  sessionFile: string;
9
9
  prompt: string;
10
10
  answer(maxBytes: number): Promise<string>;
11
+ usageTokens(): Promise<number | undefined>;
11
12
  cancel(): Promise<void>;
12
13
  }
13
14
  export declare function exactDirectAnswer(jsonl: string, prompt: string, maxBytes?: number): string;
15
+ export declare function directSessionTokens(jsonl: string, prompt: string): number | undefined;
14
16
  export type DirectTab = Pick<DirectHandle, "name" | "tabId" | "paneId" | "sessionFile">;
15
17
  export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: string, idleMs: number): {
16
18
  start(launch: ResolvedRoleLaunch, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void): Promise<DirectHandle>;
@@ -70,6 +70,43 @@ export function exactDirectAnswer(jsonl, prompt, maxBytes = ANSWER_LIMIT) {
70
70
  throw new Error(`Pi final answer exceeds the ${maxBytes}-byte workflow limit; read the private session file for recovery.`);
71
71
  return text;
72
72
  }
73
+ // Ignore a partial trailing JSONL entry while the child is writing it.
74
+ export function directSessionTokens(jsonl, prompt) {
75
+ let active = false;
76
+ let total = 0;
77
+ let observed = false;
78
+ for (const line of jsonl.split("\n")) {
79
+ if (!line.trim())
80
+ continue;
81
+ let entry;
82
+ try {
83
+ entry = JSON.parse(line);
84
+ }
85
+ catch {
86
+ break;
87
+ }
88
+ if (entry.type !== "message" || !entry.message || typeof entry.message !== "object")
89
+ continue;
90
+ const message = entry.message;
91
+ if (message.role === "user") {
92
+ active = Array.isArray(message.content) && message.content.length === 1
93
+ && message.content[0]?.text === prompt;
94
+ if (active) {
95
+ total = 0;
96
+ observed = false;
97
+ }
98
+ }
99
+ else if (active && message.role === "assistant" && message.usage && typeof message.usage === "object") {
100
+ const usage = message.usage;
101
+ const values = [usage.input, usage.output, usage.cacheRead, usage.cacheWrite];
102
+ if (values.every((value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
103
+ total += values.reduce((sum, value) => sum + value, 0);
104
+ observed = true;
105
+ }
106
+ }
107
+ }
108
+ return observed ? total : undefined;
109
+ }
73
110
  export function createDirectHerdr(pi, cwd, idleMs) {
74
111
  if (process.env.HERDR_ENV !== "1")
75
112
  throw new Error("Direct delegation requires a Herdr-managed Pi pane (HERDR_ENV=1).");
@@ -131,8 +168,20 @@ export function createDirectHerdr(pi, cwd, idleMs) {
131
168
  const state = inspect(accepted, "agent_prompted", name, paneId, tabId);
132
169
  if (state === "blocked" || state === "unknown")
133
170
  throw new Error(`Herdr agent became ${state}; inspect it before retrying.`);
171
+ let lastUsageSize = -1;
172
+ let lastTokens;
134
173
  return {
135
174
  name, tabId, paneId, sessionFile, prompt,
175
+ async usageTokens() {
176
+ const info = await stat(sessionFile);
177
+ if (info.size > SESSION_LIMIT)
178
+ return undefined;
179
+ if (info.size !== lastUsageSize) {
180
+ lastTokens = directSessionTokens(await readFile(sessionFile, "utf8"), prompt);
181
+ lastUsageSize = info.size;
182
+ }
183
+ return lastTokens;
184
+ },
136
185
  async answer(maxBytes) {
137
186
  const readAnswer = async () => {
138
187
  const info = await stat(sessionFile);
@@ -321,10 +321,8 @@ export class CheckedGitRuntime {
321
321
  if (!await this.isAncestor(requiredBase, identity.head, worktree.cwd, context)) {
322
322
  throw new Error(`Task ${task.id} tip does not descend from its recorded base ${requiredBase}.`);
323
323
  }
324
- if (requireChange) {
325
- const count = Number.parseInt(oneLine(await this.requireGit(["rev-list", "--count", `${requiredBase}..${identity.head}`], worktree.cwd, context), "task commit count"), 10);
326
- if (!Number.isSafeInteger(count) || count < 1)
327
- throw new Error(`Task ${task.id} has no committed change from its recorded base.`);
324
+ if (requireChange && identity.head === requiredBase) {
325
+ throw new Error(`Task ${task.id} has no committed change from its recorded base.`);
328
326
  }
329
327
  return identity;
330
328
  }
@@ -341,24 +339,27 @@ export class CheckedGitRuntime {
341
339
  return worktree;
342
340
  }
343
341
  async inspectInFlightWorkspace(cwd, context) {
344
- const branch = oneLine(await this.requireGit(["symbolic-ref", "--quiet", "HEAD"], cwd, context), "branch reference");
345
- const head = oid(await this.requireGit(["rev-parse", "--verify", "HEAD^{commit}"], cwd, context), "HEAD");
346
- const hadGitlinks = await this.hasGitlinks(cwd, context);
347
- const inspection = await inspectWorktreeDirty(cwd, this.gitRunner(context));
348
- if (inspection.failure)
349
- throw new Error(`Worktree inspection failed: ${inspection.failure}`);
350
- const index = oid(await this.requireGit(["write-tree"], cwd, context), "index tree");
351
- const tree = oid(await this.requireGit(["rev-parse", "--verify", "HEAD^{tree}"], cwd, context), "HEAD tree");
352
- const hasGitlinks = hadGitlinks || await this.hasGitlinks(cwd, context);
353
- const finalBranch = oneLine(await this.requireGit(["symbolic-ref", "--quiet", "HEAD"], cwd, context), "branch reference");
354
- const finalHead = oid(await this.requireGit(["rev-parse", "--verify", "HEAD^{commit}"], cwd, context), "HEAD");
355
- if (branch !== finalBranch || head !== finalHead)
356
- throw new Error("Git workspace changed during in-flight identity inspection.");
357
- return {
358
- candidate: { branch, head, index, tree },
359
- clean: !inspection.dirty,
360
- supported: !hasGitlinks,
361
- };
342
+ for (let attempt = 0; attempt < 2; attempt++) {
343
+ const branch = oneLine(await this.requireGit(["symbolic-ref", "--quiet", "HEAD"], cwd, context), "branch reference");
344
+ const head = oid(await this.requireGit(["rev-parse", "--verify", "HEAD^{commit}"], cwd, context), "HEAD");
345
+ const hadGitlinks = await this.hasGitlinks(cwd, context);
346
+ const inspection = await inspectWorktreeDirty(cwd, this.gitRunner(context), false);
347
+ if (inspection.failure)
348
+ throw new Error(`Worktree inspection failed: ${inspection.failure}`);
349
+ const index = oid(await this.requireGit(["write-tree"], cwd, context), "index tree");
350
+ const tree = oid(await this.requireGit(["rev-parse", "--verify", "HEAD^{tree}"], cwd, context), "HEAD tree");
351
+ const hasGitlinks = hadGitlinks || await this.hasGitlinks(cwd, context);
352
+ const finalBranch = oneLine(await this.requireGit(["symbolic-ref", "--quiet", "HEAD"], cwd, context), "branch reference");
353
+ const finalHead = oid(await this.requireGit(["rev-parse", "--verify", "HEAD^{commit}"], cwd, context), "HEAD");
354
+ if (branch !== finalBranch || head !== finalHead)
355
+ continue;
356
+ return {
357
+ candidate: { branch, head, index, tree },
358
+ clean: !inspection.dirty,
359
+ supported: !hasGitlinks,
360
+ };
361
+ }
362
+ throw new Error("Git workspace changed during in-flight identity inspection.");
362
363
  }
363
364
  async inspectWorkspace(cwd, strictIgnored, context) {
364
365
  const branch = oneLine(await this.requireGit(["symbolic-ref", "--quiet", "HEAD"], cwd, context), "branch reference");
package/dist/index.d.ts CHANGED
@@ -9,6 +9,7 @@ export { captureWorkingCheckoutBaseline, captureWorkingCheckoutState, prepareWor
9
9
  export declare const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
10
10
  export declare const ROLE_MCP_POLICY_FLAG = "pi-subagent-role-mcps";
11
11
  export declare const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
12
+ export declare const EXECUTION_BUDGET_FLAG = "pi-subagent-execution-budget";
12
13
  export declare const CHILD_EXCLUDED_TOOL_NAMES: readonly ["delegate_task", "ask_question", "subagent_status", "subagent_resume", "subagent_stage", "subagent_abort"];
13
14
  export declare const CHILD_EXCLUDED_TOOLS: string;
14
15
  export declare const DELEGATE_TASK: {
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ const ROLE_TOOLS_EXTENSION = fileURLToPath(new URL("../extensions/role-tools.ts"
19
19
  export const PI_SUBAGENT_PROCESS_LEASE = "PI_SUBAGENT_PROCESS_LEASE";
20
20
  export const ROLE_MCP_POLICY_FLAG = "pi-subagent-role-mcps";
21
21
  export const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
22
+ export const EXECUTION_BUDGET_FLAG = "pi-subagent-execution-budget";
22
23
  export const CHILD_EXCLUDED_TOOL_NAMES = [
23
24
  "delegate_task",
24
25
  "ask_question",
@@ -45,10 +45,12 @@ async function sharedHistory(base, tip, cwd, signal) {
45
45
  /** Check helper-derived names even after a safely removed checkout is no longer present. */
46
46
  async function ownershipMetadata(root, info, signal) {
47
47
  const canonical = await realpath(root);
48
+ const first = (await requireGit(["worktree", "list", "--porcelain", "-z"], root, signal)).split("\0")[0];
49
+ const primary = first.startsWith("worktree ") ? await realpath(first.slice("worktree ".length)) : "";
48
50
  if (await realpath(await requireGit(["rev-parse", "--show-toplevel"], root, signal)) !== canonical
49
- || info.repoRoot !== canonical || info.cwd !== info.path
51
+ || info.repoRoot !== primary || info.cwd !== info.path
50
52
  || !/^pi-subagent\/subagent-[0-9a-f]{24}$/.test(info.branch)
51
- || info.path !== join(canonical, ".worktrees", basename(info.branch))) {
53
+ || info.path !== join(primary, ".worktrees", basename(info.branch))) {
52
54
  throw new Error("Git worktree is not an exact owned checkout of Main.");
53
55
  }
54
56
  }
@@ -1,5 +1,5 @@
1
1
  import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { type EphemeralSubagentExecutionBudget } from "./ephemeral.ts";
2
+ import type { EphemeralSubagentExecutionBudget } from "./ephemeral.ts";
3
3
  import type { CoordinatorRuntime, OperationContext, TransientLaunchHandle, VerifiedLaunch } from "./runner.ts";
4
4
  import { type ExecuteRequest, type ModelClass, type WorkspaceIdentity } from "./schema.ts";
5
5
  export declare const ISOLATED_MODEL_TASK: {
@@ -3,8 +3,7 @@ import { constants } from "node:fs";
3
3
  import { chmod, lstat, mkdtemp, open, realpath, rmdir, unlink } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { isAbsolute, join, normalize, relative, sep } from "node:path";
6
- import { resolveConfiguredRoleLaunch } from "./index.js";
7
- import { EXECUTION_BUDGET_ENV } from "./ephemeral.js";
6
+ import { EXECUTION_BUDGET_FLAG, resolveConfiguredRoleLaunch } from "./index.js";
8
7
  import { registerModelTask } from "@henryqw/pi-task-models";
9
8
  const PROMPT_FLAG = "--append-system-prompt";
10
9
  const DIRECTORY_MODE = 0o700;
@@ -138,13 +137,14 @@ export class RoleLaunchRuntime {
138
137
  modelClass,
139
138
  model: `${prepared.model.provider}/${prepared.model.id}`,
140
139
  thinkingLevel: prepared.thinkingLevel,
141
- args: Object.freeze([...prepared.args]),
142
- env: Object.freeze({
143
- ...prepared.env,
144
- ...(executionBudget === undefined ? {} : {
145
- [EXECUTION_BUDGET_ENV]: JSON.stringify({ ...executionBudget, startedAt: this.now() }),
146
- }),
147
- }),
140
+ args: Object.freeze([
141
+ ...prepared.args,
142
+ ...(executionBudget === undefined ? [] : [
143
+ `--${EXECUTION_BUDGET_FLAG}`,
144
+ JSON.stringify({ ...executionBudget, startedAt: this.now() }),
145
+ ]),
146
+ ]),
147
+ env: Object.freeze({ ...prepared.env }),
148
148
  tools: Object.freeze([...prepared.tools]),
149
149
  }),
150
150
  prompt: prepared.systemPrompt,
@@ -157,7 +157,7 @@ export class RoleLaunchRuntime {
157
157
  if (typeof resolvedRoot !== "string" || !isAbsolute(resolvedRoot) || resolvedRoot.includes("\0")) {
158
158
  throw new Error("Pi Subagent root resolver must return an absolute canonical path.");
159
159
  }
160
- const root = normalize(await realpath(resolvedRoot));
160
+ const root = await realpath(resolvedRoot);
161
161
  if (root !== resolvedRoot)
162
162
  throw new Error("Pi Subagent root resolver returned a non-canonical path.");
163
163
  const rootInfo = await lstat(root);
package/dist/runner.d.ts CHANGED
@@ -303,6 +303,13 @@ export declare class IsolatedRunner {
303
303
  }>;
304
304
  invalidIds: string[];
305
305
  }>;
306
+ /** Classify orphaned work under the same repository lease as productive execution.
307
+ * Status remains read-only; Main alone chooses any subsequent action. */
308
+ recoverRepository(root: string): Promise<{
309
+ requests: RunResponse[];
310
+ invalidIds: string[];
311
+ leaseBusy: boolean;
312
+ }>;
306
313
  canFollowup(root: string, requestId: string, taskId: string): boolean;
307
314
  drainFollowups(root: string, requestId: string, taskId: string): string[];
308
315
  queueFollowup(root: string, requestId: string, taskId: string, instruction: string): string;
package/dist/runner.js CHANGED
@@ -2,7 +2,7 @@ import { readFileSync, realpathSync } from "node:fs";
2
2
  import { createChildWorktree, finalizeChildWorktree } from "./worktree.js";
3
3
  import { IntegrationGit } from "./integration-git.js";
4
4
  import { checkBatchPasses, CLEANUP_KINDS, isCleanCommitted, MAX_PERSISTED_RUNTIME_TEXT_BYTES, MAX_POSSIBLE_RESOURCES, parseExecuteRequest, parseIntegrationAction, integrationGenerationPasses, parseResumeRequest, parseStageRequest, reviewEvidencePasses, sameIdentity, RUN_STATE_VERSION, } from "./schema.js";
5
- import { FileRunStore } from "./store.js";
5
+ import { FileRunStore, ProductiveRunLeaseBusyError } from "./store.js";
6
6
  const TRUNCATION_MARKER = "\n[truncated]";
7
7
  const TEXT_TASK_PROMPT_MAX_BYTES = 64 * 1024;
8
8
  const CHANGESET_TASK_PROMPT_MAX_BYTES = 96 * 1024;
@@ -533,6 +533,39 @@ export class IsolatedRunner {
533
533
  })),
534
534
  })) };
535
535
  }
536
+ /** Classify orphaned work under the same repository lease as productive execution.
537
+ * Status remains read-only; Main alone chooses any subsequent action. */
538
+ async recoverRepository(root) {
539
+ root = realpathSync.native(root);
540
+ let leaseBusy = false;
541
+ let inventory;
542
+ try {
543
+ inventory = await this.withProductiveRun(root, async (lifecycle) => await this.store.withLock(root, async () => {
544
+ const listed = await this.listRequests(root);
545
+ for (const request of listed.requests) {
546
+ if (request.status !== "pending" && request.status !== "running")
547
+ continue;
548
+ const handle = await this.store.load(root, request.id);
549
+ if (this.recoverInterrupted(handle.state))
550
+ await handle.save();
551
+ }
552
+ return listed;
553
+ }, { productiveRunLease: lifecycle.lease }));
554
+ }
555
+ catch (error) {
556
+ if (!(error instanceof ProductiveRunLeaseBusyError))
557
+ throw error;
558
+ leaseBusy = true;
559
+ inventory = await this.listRequests(root);
560
+ }
561
+ const requests = [];
562
+ for (const request of inventory.requests) {
563
+ if (["pending", "running", "needs_attention", "completed · retained"].includes(request.status)) {
564
+ requests.push(await this.status(request.id, root));
565
+ }
566
+ }
567
+ return { requests, invalidIds: inventory.invalidIds, leaseBusy };
568
+ }
536
569
  canFollowup(root, requestId, taskId) {
537
570
  const active = this.activeControl(realpathSync.native(root), requestId, taskId);
538
571
  return active !== undefined && active.task.status === "working" && !active.control.isSealed;
@@ -564,12 +597,13 @@ export class IsolatedRunner {
564
597
  if (this.productiveLifecycles.has(root)) {
565
598
  throw new Error("Another Pi Subagent productive request is active in this runner.");
566
599
  }
567
- const lifecycle = { lease, stopped: false };
600
+ const lifecycle = { lease, stages: new Set(), stopped: false };
568
601
  this.productiveLifecycles.set(root, lifecycle);
569
602
  try {
570
603
  return await operation(lifecycle);
571
604
  }
572
605
  finally {
606
+ await Promise.allSettled(lifecycle.stages);
573
607
  this.productiveLifecycles.delete(root);
574
608
  }
575
609
  });
@@ -756,10 +790,11 @@ export class IsolatedRunner {
756
790
  async stage(value, root, outerSignal) {
757
791
  const action = parseStageRequest(value);
758
792
  root = realpathSync.native(root);
759
- return await this.withProductiveRun(root, async (lifecycle) => {
760
- const handle = await this.store.withLock(root, async () => await this.store.load(root, action.id), { productiveRunLease: lifecycle.lease });
793
+ const stageSelected = async (handle, duringWave) => {
761
794
  const state = handle.state;
762
- if (terminal(state) || state.status !== "needs_attention" || (state.integration.refresh && state.integration.refresh.status !== "ready")) {
795
+ if (terminal(state) || (state.status !== "needs_attention"
796
+ && !(duringWave && state.status === "running" && (action.action === "stage" || action.action === "resolve")))
797
+ || (state.integration.refresh && state.integration.refresh.status !== "ready")) {
763
798
  throw new Error("Request is not waiting for Main staging or refresh allocation remains uncertain.");
764
799
  }
765
800
  const candidate = state.integration.candidates.find((item) => item.taskId === action.taskId && item.attempt === action.attempt
@@ -912,7 +947,7 @@ export class IsolatedRunner {
912
947
  }
913
948
  if (action.action === "resolve") {
914
949
  const pending = generation?.stages.at(-1);
915
- if (!pending || !["staging", "conflict"].includes(pending.status)
950
+ if (!pending || !["pending", "staging", "conflict"].includes(pending.status)
916
951
  || pending.taskId !== action.taskId || pending.attempt !== action.attempt
917
952
  || !sameIdentity(pending.source, action.candidate)
918
953
  || !sameIdentity(pending.onto, action.expectedTip))
@@ -983,9 +1018,15 @@ export class IsolatedRunner {
983
1018
  }
984
1019
  await this.saveProductive(handle); // Exact candidate and previous tip before merge.
985
1020
  }
986
- const outcome = await scope.call((context) => action.action === "stage"
1021
+ let outcome = await scope.call((context) => action.action === "stage"
987
1022
  ? this.integrationGit.stage(root, worktree, state.main, receipts, worker, candidate.tip, context.signal)
988
1023
  : this.integrationGit.reconcileStage(root, worktree, state.main, receipts, worker, candidate.tip, context.signal));
1024
+ if (action.action === "resolve" && stage.status === "pending"
1025
+ && outcome.outcome === "ready" && outcome.value === "not_started") {
1026
+ stage.status = "staging";
1027
+ await this.saveProductive(handle); // Read-only proof before Main's explicit merge request.
1028
+ outcome = await scope.call((context) => this.integrationGit.stage(root, worktree, state.main, receipts, worker, candidate.tip, context.signal));
1029
+ }
989
1030
  if (outcome.outcome === "ready" && outcome.value !== "not_started") {
990
1031
  stage.status = "staged";
991
1032
  stage.tip = outcome.value.tip;
@@ -1008,6 +1049,28 @@ export class IsolatedRunner {
1008
1049
  // Unproved outcomes keep the intent; never replay a merge automatically.
1009
1050
  await this.saveProductive(handle);
1010
1051
  return this.response(state);
1052
+ };
1053
+ const active = this.productiveLifecycles.get(root);
1054
+ if (active?.handle?.state.request.id === action.id) {
1055
+ if (active.stopped)
1056
+ throw new DurableRunStopped(active.handle.state);
1057
+ if (action.action !== "stage" && action.action !== "resolve") {
1058
+ throw new Error("Wait for active workers before revising or rejecting a candidate.");
1059
+ }
1060
+ if (active.stages.size)
1061
+ throw new Error("Another stage or resolution is active; retry after it finishes.");
1062
+ const stage = stageSelected(active.handle, true);
1063
+ active.stages.add(stage);
1064
+ try {
1065
+ return await stage;
1066
+ }
1067
+ finally {
1068
+ active.stages.delete(stage);
1069
+ }
1070
+ }
1071
+ return await this.withProductiveRun(root, async (lifecycle) => {
1072
+ const handle = await this.store.withLock(root, async () => await this.store.load(root, action.id), { productiveRunLease: lifecycle.lease });
1073
+ return await stageSelected(handle, false);
1011
1074
  });
1012
1075
  }
1013
1076
  stageReceipts(generation) {
@@ -1581,6 +1644,8 @@ export class IsolatedRunner {
1581
1644
  }
1582
1645
  async run(handle, scope, forceTextTaskId, stagedSnapshot) {
1583
1646
  const state = handle.state;
1647
+ const lifecycle = this.productiveLifecycles.get(state.root);
1648
+ lifecycle.handle = handle;
1584
1649
  let saveOnExit = true;
1585
1650
  state.status = "running";
1586
1651
  state.updatedAt = this.coordinatorRuntime.now();
@@ -1653,6 +1718,10 @@ export class IsolatedRunner {
1653
1718
  const dispatched = await Promise.allSettled(ready.map(async (task) => {
1654
1719
  try {
1655
1720
  await this.dispatchTask(handle, task, scope);
1721
+ if (task.kind === "changeset" && task.status === "ready_to_integrate") {
1722
+ this.retainCandidate(state, task);
1723
+ await this.saveProductive(handle);
1724
+ }
1656
1725
  }
1657
1726
  catch (error) {
1658
1727
  this.rethrowStopped(error);
@@ -1681,9 +1750,6 @@ export class IsolatedRunner {
1681
1750
  forceTextTaskId = undefined;
1682
1751
  continue;
1683
1752
  }
1684
- for (const task of ready)
1685
- if (task.kind === "changeset")
1686
- this.retainCandidate(state, task);
1687
1753
  wave.status = "needs_attention";
1688
1754
  state.status = "needs_attention";
1689
1755
  await this.saveProductive(handle);
@@ -1712,9 +1778,15 @@ export class IsolatedRunner {
1712
1778
  }
1713
1779
  finally {
1714
1780
  this.closeRequestControls(state.root, state.request.id);
1715
- if (saveOnExit) {
1716
- state.updatedAt = this.coordinatorRuntime.now();
1717
- await this.saveProductive(handle);
1781
+ try {
1782
+ if (saveOnExit) {
1783
+ state.updatedAt = this.coordinatorRuntime.now();
1784
+ await this.saveProductive(handle);
1785
+ }
1786
+ }
1787
+ finally {
1788
+ if (lifecycle.handle === handle)
1789
+ delete lifecycle.handle;
1718
1790
  }
1719
1791
  }
1720
1792
  }
@@ -2279,6 +2351,8 @@ export class IsolatedRunner {
2279
2351
  tip: attempt.candidate, checks: attempt.preliminaryChecks,
2280
2352
  ...(request.judgment ? { review: attempt.preliminaryReview } : {}), worker: "retained",
2281
2353
  });
2354
+ state.integration.candidates.sort((a, b) => state.tasks.findIndex((item) => item.taskId === a.taskId)
2355
+ - state.tasks.findIndex((item) => item.taskId === b.taskId));
2282
2356
  }
2283
2357
  async verifyRetainedTask(handle, task, scope) {
2284
2358
  const attempt = latestAttempt(task);
package/dist/store.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { type RunState } from "./schema.ts";
2
2
  declare const productiveRunLeaseBrand: unique symbol;
3
+ export declare class ProductiveRunLeaseBusyError extends Error {
4
+ constructor();
5
+ }
3
6
  export interface ProductiveRunLease {
4
7
  readonly [productiveRunLeaseBrand]: true;
5
8
  }
package/dist/store.js CHANGED
@@ -24,6 +24,11 @@ const LIFECYCLE_LOCK_OPTIONS = {
24
24
  retries: { forever: true, factor: 1, minTimeout: 25, maxTimeout: 25 },
25
25
  };
26
26
  const productiveRunLeaseBrand = Symbol("productiveRunLease");
27
+ export class ProductiveRunLeaseBusyError extends Error {
28
+ constructor() {
29
+ super("Another Pi Subagent productive request is active in this repository.");
30
+ }
31
+ }
27
32
  function isMissing(error) {
28
33
  return Boolean(error && typeof error === "object" && error.code === "ENOENT");
29
34
  }
@@ -127,7 +132,7 @@ export class FileRunStore {
127
132
  }
128
133
  catch (error) {
129
134
  if (isLocked(error)) {
130
- throw new Error("Another Pi Subagent productive request is active in this repository.");
135
+ throw new ProductiveRunLeaseBusyError();
131
136
  }
132
137
  throw error;
133
138
  }
@@ -189,7 +194,7 @@ export class FileRunStore {
189
194
  throw new Error(`Pi Subagent request ${state.request.id} already exists.`);
190
195
  throw error;
191
196
  }
192
- const saved = parseRunState(structuredClone(state));
197
+ const saved = JSON.parse(contents);
193
198
  this.onStateSaved?.(structuredClone(saved));
194
199
  return this.handle(saved, path);
195
200
  }
@@ -282,7 +287,7 @@ export class FileRunStore {
282
287
  return new RunStateHandle(state, path, async (contents) => {
283
288
  await this.assertSafeDestination(state.root, path);
284
289
  await writePrivateTextFileAtomically(path, contents);
285
- this.onStateSaved?.(parseRunState(JSON.parse(contents)));
290
+ this.onStateSaved?.(JSON.parse(contents));
286
291
  });
287
292
  }
288
293
  }
@@ -47,7 +47,7 @@ export declare function inspectIndexFlags(cwd: string, run?: GitRunner, signal?:
47
47
  failure?: string;
48
48
  }>;
49
49
  /** Proves a worktree has no tracked, untracked, ignored, index-hidden, or nested submodule work. */
50
- export declare function inspectWorktreeDirty(cwd: string, run?: GitRunner): Promise<WorktreeDirtyInspection>;
50
+ export declare function inspectWorktreeDirty(cwd: string, run?: GitRunner, includeIgnored?: boolean): Promise<WorktreeDirtyInspection>;
51
51
  /**
52
52
  * Inspects and possibly prunes a child worktree after it finishes. Commit count
53
53
  * reads the dedicated branch and refuses to prune when checkout HEAD no longer
package/dist/worktree.js CHANGED
@@ -170,12 +170,12 @@ export async function inspectIndexFlags(cwd, run = runGit, signal) {
170
170
  return { hidden: false, failure: `ls-files exit ${flags.code}: ${flags.stderr.trim().slice(0, 200)}` };
171
171
  return { hidden: flags.stdout.split("\0").some((entry) => /^(?:[a-z]|S) /.test(entry)) };
172
172
  }
173
- async function inspectDirty(run, cwd) {
173
+ async function inspectDirty(run, cwd, includeIgnored = true) {
174
174
  const refreshed = await run(["update-index", "--really-refresh"], cwd);
175
175
  if (refreshed.code !== 0 && refreshed.code !== 1) {
176
176
  return { dirty: false, failure: `update-index exit ${refreshed.code}: ${refreshed.stderr.trim().slice(0, 200)}` };
177
177
  }
178
- const status = await run(["status", "--porcelain", "--untracked-files=all", "--ignored=matching", "--ignore-submodules=none"], cwd);
178
+ const status = await run(["status", "--porcelain", "--untracked-files=all", ...(includeIgnored ? ["--ignored=matching"] : []), "--ignore-submodules=none"], cwd);
179
179
  if (status.code !== 0)
180
180
  return { dirty: false, failure: `status exit ${status.code}: ${status.stderr.trim().slice(0, 200)}` };
181
181
  if (refreshed.code === 1 || status.stdout.trim())
@@ -188,8 +188,8 @@ async function inspectDirty(run, cwd) {
188
188
  return { dirty: false };
189
189
  }
190
190
  /** Proves a worktree has no tracked, untracked, ignored, index-hidden, or nested submodule work. */
191
- export async function inspectWorktreeDirty(cwd, run = runGit) {
192
- const root = await inspectDirty(run, cwd);
191
+ export async function inspectWorktreeDirty(cwd, run = runGit, includeIgnored = true) {
192
+ const root = await inspectDirty(run, cwd, includeIgnored);
193
193
  if (root.dirty || root.failure)
194
194
  return root;
195
195
  const modules = await run(["submodule", "status", "--recursive"], cwd);
@@ -204,14 +204,14 @@ export async function inspectWorktreeDirty(cwd, run = runGit) {
204
204
  if (!paths.length)
205
205
  return { dirty: false, failure: "initialized submodule paths unavailable" };
206
206
  for (const path of paths) {
207
- const nested = await inspectDirty(run, path);
207
+ const nested = await inspectDirty(run, path, includeIgnored);
208
208
  if (nested.failure)
209
209
  return { dirty: false, failure: `submodule ${path}: ${nested.failure}` };
210
210
  if (nested.dirty)
211
211
  return { dirty: true };
212
212
  }
213
213
  }
214
- const rechecked = await inspectDirty(run, cwd);
214
+ const rechecked = await inspectDirty(run, cwd, includeIgnored);
215
215
  return initializedSubmodules ? { ...rechecked, initializedSubmodules } : rechecked;
216
216
  }
217
217
  /**