@ferris1225/pi-subagents 4.1.5 → 4.1.7
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 +39 -6
- package/agents/reviewer.md +2 -2
- package/agents/worker.md +4 -0
- package/package.json +1 -1
- package/src/dispatch.ts +8 -3
- package/src/fixloop.ts +25 -14
- package/src/monitor.ts +29 -6
- package/src/rpc-run.ts +26 -2
- package/src/thread-lifecycle.ts +85 -13
- package/src/tools.ts +49 -5
- package/src/widget.ts +35 -5
- package/src/worktree.ts +12 -0
package/README.md
CHANGED
|
@@ -119,7 +119,10 @@ The runtime deliberately keeps delegation conservative:
|
|
|
119
119
|
- `worker` and `cleaner` remain distinct write-capable entry roles. Each updates
|
|
120
120
|
existing README/docs/examples/comments directly affected by its change. After
|
|
121
121
|
success, one enabled independent `reviewer` gate runs, with the existing bounded
|
|
122
|
-
worker ↔ reviewer fix loop for `REVIEW_FAIL`.
|
|
122
|
+
worker ↔ reviewer fix loop for `REVIEW_FAIL`. Every gate finding carries a
|
|
123
|
+
concrete fix instruction; the worker implements those instructions or ships a
|
|
124
|
+
sounder fix with an explicit pushback, and re-review judges the resulting code —
|
|
125
|
+
only open findings and defects the fix itself introduced can continue the loop.
|
|
123
126
|
- When `documenter` is enabled, every managed reviewer gate is asked for a
|
|
124
127
|
standalone `DOCUMENTATION: CLEAN` or `DOCUMENTATION: NEEDED` line. Only
|
|
125
128
|
`REVIEW_PASS` can authorize the final sync: NEEDED includes
|
|
@@ -225,14 +228,19 @@ immediately, while NEEDED (or a missing marker on that passing gate) runs one
|
|
|
225
228
|
final docs sync. A failure uses the bounded loop:
|
|
226
229
|
|
|
227
230
|
```text
|
|
228
|
-
reviewer → worker
|
|
231
|
+
reviewer → worker applies each fix instruction (or rebuts with a sounder fix)
|
|
232
|
+
→ reviewer re-reviews the result → …
|
|
229
233
|
REVIEW_PASS ─┬─ CLEAN → deliver
|
|
230
234
|
└─ NEEDED/missing → documenter
|
|
231
235
|
```
|
|
232
236
|
|
|
233
237
|
Each step gets a fresh model context. The chain shares the same code state and
|
|
234
238
|
passes every full reviewer and worker report forward; it does not reuse one
|
|
235
|
-
context window.
|
|
239
|
+
context window. Re-review converges instead of re-auditing: it rules on every
|
|
240
|
+
previous finding once, judges the code as it now stands (a sound worker fix
|
|
241
|
+
counts even when it deviates from the instruction), and adds new findings only
|
|
242
|
+
for defects the fix round's own edits introduced or exposed — issues unrelated
|
|
243
|
+
to those edits belong to a fresh gate, not to the loop. Internal children bypass top-level lifecycle policy, so they
|
|
236
244
|
cannot recursively start another chain. Gate reviewers keep documentation drift
|
|
237
245
|
out of the code verdict while `documenter` is enabled by recording it under
|
|
238
246
|
`## Documentation notes`; with documenter disabled, drift is a normal finding.
|
|
@@ -380,16 +388,26 @@ worktree finalization to the same one-time lifecycle owner. `stop-all` interrupt
|
|
|
380
388
|
every lane holder before waiting for finalization, avoiding self-deadlock when an
|
|
381
389
|
isolated apply is queued behind shared work.
|
|
382
390
|
|
|
391
|
+
Every control operation is bounded: park, stop, resume, and fork never wait
|
|
392
|
+
indefinitely on a generation that is still settling (for example an isolated
|
|
393
|
+
apply queued behind the managed repository lane). Stop proceeds after a bounded
|
|
394
|
+
deadline once it owns the lifecycle, a still-running integration continues in the
|
|
395
|
+
background, and a durable recovery record is persisted pointing at the retained
|
|
396
|
+
worktree/patch so stopped work is never lost.
|
|
397
|
+
|
|
383
398
|
## Results and live status
|
|
384
399
|
|
|
385
400
|
The active TUI widget shows standalone runs normally and projects each managed
|
|
386
|
-
workflow as a compact timeline plus its current internal child
|
|
401
|
+
workflow as a compact timeline plus its current internal child. Every row leads
|
|
402
|
+
with its stable run id — the handle for `subagent_control`, `subagent_status`,
|
|
403
|
+
and `subagent_stop`:
|
|
387
404
|
|
|
388
405
|
```text
|
|
389
|
-
◆ worker workflow · src/cache.ts
|
|
406
|
+
◆ #12 worker workflow · src/cache.ts · wt:a91f3c · 42s
|
|
390
407
|
✓ implement ─ ● review ─ ○ docs
|
|
391
|
-
└ ● reviewer · final review · claude-sonnet-4-5/high · 10s
|
|
408
|
+
└ ● #15 reviewer · final review · claude-sonnet-4-5/high · 10s
|
|
392
409
|
git diff
|
|
410
|
+
○ #23 worker · queued · redirect to ripgrep crates · 5m02s
|
|
393
411
|
```
|
|
394
412
|
|
|
395
413
|
Success is green, the active stage uses the accent color and bold text, pending
|
|
@@ -398,6 +416,15 @@ error. Fix paths show their budget (`fix 1/2`, `re-review 1/2`). The timeline
|
|
|
398
416
|
contains only stages that ran or are currently planned; `DOCUMENTATION: CLEAN`
|
|
399
417
|
removes pending docs instead of pretending that stage ran.
|
|
400
418
|
|
|
419
|
+
Worktree-isolated runs carry a group badge on the row that owns the worktree:
|
|
420
|
+
`wt:<id>` while active, `wt:<id> applying` while the settled patch is being
|
|
421
|
+
applied to the original checkout, then `applied`/`clean`, or `retained` when
|
|
422
|
+
integration failed. The short id changes when a resumed generation creates a
|
|
423
|
+
continuation worktree, so a group boundary change is visible at a glance.
|
|
424
|
+
Nested stage rows inherit the group through the tree instead of repeating the
|
|
425
|
+
badge. Queued rows say `queued` and omit model/thinking — the route is
|
|
426
|
+
re-resolved when the run actually starts.
|
|
427
|
+
|
|
401
428
|
A managed root keeps its original top-level role and workflow-wide elapsed time,
|
|
402
429
|
but omits model/thinking because several model stages own it. The active nested
|
|
403
430
|
row shows the current role, relation, selected/fallback model, thinking, stage
|
|
@@ -436,6 +463,12 @@ session. Searches, reads, reasoning, and edits already completed are preserved.
|
|
|
436
463
|
Ordinary tool and test failures remain task failures and do not trigger a model
|
|
437
464
|
handoff.
|
|
438
465
|
|
|
466
|
+
Model changes apply immediately to work that has not started: a run still
|
|
467
|
+
waiting for a concurrency slot re-resolves its route when it actually starts,
|
|
468
|
+
and managed workflow stages (fix rounds, re-reviews, the conditional documenter)
|
|
469
|
+
re-read the config before each stage launches. Only an already-running child
|
|
470
|
+
keeps the model it started with.
|
|
471
|
+
|
|
439
472
|
Thinking defaults to **Auto**. pi-subagents starts from the role's preference and
|
|
440
473
|
chooses only a level the effective model actually supports. A fallback re-checks
|
|
441
474
|
the level for the main model. `documenter` deliberately ships with the same fast,
|
package/agents/reviewer.md
CHANGED
|
@@ -43,7 +43,7 @@ You are a senior, adversarial code reviewer. Find genuine defects and risks rath
|
|
|
43
43
|
- Return only the review result. Do not repeat the task brief, summarize the implementation, narrate inspection/tool chronology, or explain a root cause when no finding depends on it. Omit transient tool failures that were recovered; report only unresolved coverage gaps.
|
|
44
44
|
- Stay independent of `worker`, `cleaner`, and `documenter`; fix nothing yourself. When a final documenter is available, documentation drift is not a code-gate finding: record it in a short `## Documentation notes` section and carry it forward on re-review. When documenter is disabled, drift is a normal gate finding.
|
|
45
45
|
- Every gate (never an advisory review) must classify documentation on its own standalone machine line. Emit `DOCUMENTATION: NEEDED` and include `## Documentation notes` when a sync is needed; otherwise emit `DOCUMENTATION: CLEAN`. Runtime treats a missing marker conservatively as NEEDED. Do not emit this marker for advisory output.
|
|
46
|
-
- In a gate, every code/test finding enters auto-fix, with no severity tiers. A direct REVIEW_PASS is final for code: CLEAN delivers directly, while NEEDED/missing runs one conditional documentation sync without reopening the gate. On re-review,
|
|
46
|
+
- In a gate, every code/test finding enters auto-fix, with no severity tiers, and every gate finding must end with a concrete fix instruction — what to change, where, and how to verify the fix — because a worker implements exactly those instructions unless it can justify a sounder fix and push back. A direct REVIEW_PASS is final for code: CLEAN delivers directly, while NEEDED/missing runs one conditional documentation sync without reopening the gate. On re-review, judge the code as it now stands: a finding is resolved when the pending diff fixes it soundly, whether or not the worker followed your instruction. Rule on each open finding once, concretely adjudicate worker pushback, add only defects the fix introduced or exposed — never issues unrelated to this round's edits — and never re-open a verified resolution.
|
|
47
47
|
- Advisory findings never enter auto-fix; the caller decides whether to authorize later implementation or cleanup.
|
|
48
48
|
|
|
49
49
|
## Output
|
|
@@ -64,7 +64,7 @@ For a gate review:
|
|
|
64
64
|
## Files Reviewed
|
|
65
65
|
- path/to/file.ts
|
|
66
66
|
## Findings
|
|
67
|
-
- file.ts:42 — concrete issue and why it breaks
|
|
67
|
+
- file.ts:42 — concrete issue and why it breaks — Fix: the change to make and how to verify it
|
|
68
68
|
(Write "None" when no finding remains.)
|
|
69
69
|
## Documentation notes
|
|
70
70
|
- exact stale surface and required correction
|
package/agents/worker.md
CHANGED
|
@@ -34,6 +34,10 @@ Never commit, push, publish, tag, release, or bump a package version. The parent
|
|
|
34
34
|
- You cannot dispatch sub-agents (children are leaf processes with no `subagent` tool). When the
|
|
35
35
|
brief lacks context that needs broad code discovery, state concretely what an `explorer` should
|
|
36
36
|
retrieve for the caller — do not guess.
|
|
37
|
+
- In an auto-fix round, apply your own judgment to the reviewer's fix instructions: implement each
|
|
38
|
+
instruction when it is sound; when it is wrong, out of scope, or a sounder fix exists, implement
|
|
39
|
+
your fix and push back in your report — cite the finding, refute the instruction's reasoning,
|
|
40
|
+
and describe what you shipped instead. A deviation without reasoning will be re-opened.
|
|
37
41
|
- The parent runtime automatically runs one enabled `reviewer` gate after a successful top-level worker and preserves the bounded worker/reviewer fix loop. A final `documenter` runs only when that terminal review reports documentation drift or omits its marker (or when reviewer is disabled). Report a complete handoff, but do not ask the caller to duplicate downstream roles. Never treat your own verification as the final gate.
|
|
38
42
|
|
|
39
43
|
## Output format
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ferris1225/pi-subagents",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.7",
|
|
4
4
|
"description": "A managed sub-agent team for pi: specialized roles, pre-commit documentation sync, retained threads, auto-fix chains, model fallback, and Git worktree isolation.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/dispatch.ts
CHANGED
|
@@ -208,7 +208,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
208
208
|
if (!run) return; // already finished — stay idempotent
|
|
209
209
|
if (opts?.silent || !runtime.sessionActive) return;
|
|
210
210
|
const icon = status === "done" ? "✓" : "✗";
|
|
211
|
-
ctx.ui.notify(`${icon} ${monitor.summarize(run)}`, status === "done" ? "info" : "error");
|
|
211
|
+
ctx.ui.notify(`${icon} #${run.id} ${monitor.summarize(run)}`, status === "done" ? "info" : "error");
|
|
212
212
|
};
|
|
213
213
|
|
|
214
214
|
// Live sub-agent activity → concise one-line status ("thinking",
|
|
@@ -315,7 +315,11 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
315
315
|
const resolveLiveAgentTools = (candidate: AgentConfig): AgentConfig =>
|
|
316
316
|
resolveAgentTools({ ...candidate, tools: discoveredAgent.tools }, runtime.getActiveTools());
|
|
317
317
|
const agent = resolveLiveAgentTools(discoveredAgent);
|
|
318
|
-
|
|
318
|
+
// Workflow policy (fix-round caps, agents) stays fixed for the chain,
|
|
319
|
+
// but model/thinking routes are re-read per stage so config edits
|
|
320
|
+
// apply to stages that have not launched yet.
|
|
321
|
+
const stageConfig = await loadConfig(runtime.configPath).catch(() => request.config);
|
|
322
|
+
const resolvedRoute = resolveDispatchModelRoute(agent, stageConfig, request.ctx);
|
|
319
323
|
const route = request.isolation === "worktree"
|
|
320
324
|
? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
|
|
321
325
|
: resolvedRoute;
|
|
@@ -323,6 +327,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
323
327
|
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
324
328
|
...meta,
|
|
325
329
|
isolation: request.isolation,
|
|
330
|
+
...(request.worktreeId ? { worktreeId: request.worktreeId } : {}),
|
|
326
331
|
});
|
|
327
332
|
const onLive = makeLiveHandler(runId);
|
|
328
333
|
try {
|
|
@@ -339,7 +344,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
339
344
|
signal: request.signal,
|
|
340
345
|
onLive,
|
|
341
346
|
makeDetails: makeDetails("single", true),
|
|
342
|
-
idleTimeoutMs:
|
|
347
|
+
idleTimeoutMs: stageConfig.idleTimeoutSec * 1000,
|
|
343
348
|
},
|
|
344
349
|
route.mainFallbackRef,
|
|
345
350
|
);
|
package/src/fixloop.ts
CHANGED
|
@@ -3,6 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Successful top-level worker/cleaner runs continue through an independent
|
|
5
5
|
* code review gate; bounded worker → reviewer fix rounds close its findings.
|
|
6
|
+
* Gate findings carry concrete fix instructions that the worker implements
|
|
7
|
+
* unless it can justify a sounder fix and push back; re-review adjudicates on
|
|
8
|
+
* the resulting code (open findings plus fix-introduced defects only) so the
|
|
9
|
+
* rounds converge instead of re-auditing from scratch.
|
|
6
10
|
* Reviewers classify documentation drift explicitly, so the low-cost final
|
|
7
11
|
* documenter runs only when needed (or conservatively when an older/custom
|
|
8
12
|
* reviewer omits the marker). Direct passing/failing gates use the same policy.
|
|
@@ -139,8 +143,9 @@ export function getManagedWorkflowPlan(
|
|
|
139
143
|
|
|
140
144
|
/**
|
|
141
145
|
* Build the worker task brief for one fix round from a reviewer's findings.
|
|
142
|
-
* The worker gets the full review text
|
|
143
|
-
*
|
|
146
|
+
* The worker gets the full review text — findings plus their fix instructions
|
|
147
|
+
* — and closes every finding either by implementing the instruction or by
|
|
148
|
+
* shipping a sounder fix with an explicit per-finding pushback.
|
|
144
149
|
*/
|
|
145
150
|
export function buildFixTaskBrief(reviewerResult: SingleResult, round: number, maxRounds: number): string {
|
|
146
151
|
const review = getResultOutput(reviewerResult);
|
|
@@ -153,13 +158,15 @@ export function buildFixTaskBrief(reviewerResult: SingleResult, round: number, m
|
|
|
153
158
|
review,
|
|
154
159
|
`---`,
|
|
155
160
|
``,
|
|
156
|
-
`
|
|
157
|
-
`
|
|
161
|
+
`Each finding in the reviewer's report carries a fix instruction. Close EVERY finding — there is no severity triage; all of them get fixed.`,
|
|
162
|
+
`You own the fix: when an instruction is factually wrong, clearly out of scope, or a sounder fix exists, implement YOUR fix instead,`,
|
|
163
|
+
`then push back explicitly per finding — cite it, refute the instruction's reasoning, and state what you shipped instead.`,
|
|
164
|
+
`A pushback without a working alternative or concrete reasoning will be re-opened.`,
|
|
158
165
|
`Do NOT refactor unrelated code beyond what the findings require.`,
|
|
159
166
|
`Synchronize any existing README/docs/examples/comments directly affected by your fixes; do not broaden into standalone documentation maintenance.`,
|
|
160
167
|
`Do NOT commit, push, publish, tag, or release; do not bump versions. The parent chain still owns re-review and any conditional final documentation sync.`,
|
|
161
168
|
`After editing, run the project's format/build/tests when they exist and report`,
|
|
162
|
-
`exactly what you changed (paths + short rationale) so a reviewer can verify.`,
|
|
169
|
+
`exactly what you changed (paths + short rationale) plus any pushback, so a reviewer can verify.`,
|
|
163
170
|
remaining > 0
|
|
164
171
|
? `A reviewer will re-review your changes automatically after you finish.`
|
|
165
172
|
: `This is the last auto-fix round; the workflow conditionally runs any needed final documentation sync and then delivers.`,
|
|
@@ -304,6 +311,8 @@ export function buildFinalReviewBrief(
|
|
|
304
311
|
``,
|
|
305
312
|
`Run \`git status\` and \`git diff\` and inspect the actual pending code; the report is context, not proof.`,
|
|
306
313
|
`Remain read-only. Verify correctness, regressions, and tests.`,
|
|
314
|
+
`Attach a concrete fix instruction to EVERY gate finding: what to change, where, and how to verify the fix.`,
|
|
315
|
+
`A worker will implement your instructions unless it can justify a sounder fix and push back, so make each instruction specific enough to act on.`,
|
|
307
316
|
...(options.documenterPending
|
|
308
317
|
? [
|
|
309
318
|
`A conditional documentation sync is available AFTER this gate, so documentation drift is not a code-gate finding.`,
|
|
@@ -321,10 +330,11 @@ export function buildFinalReviewBrief(
|
|
|
321
330
|
|
|
322
331
|
/**
|
|
323
332
|
* The re-review brief handed to the reviewer after a worker fix round. Includes
|
|
324
|
-
* the prior review and worker report so the reviewer can adjudicate
|
|
333
|
+
* the prior review and worker report so the reviewer can adjudicate pushback
|
|
325
334
|
* instead of restating findings. The convergence contract keeps rounds from
|
|
326
|
-
* ping-ponging:
|
|
327
|
-
*
|
|
335
|
+
* ping-ponging: judge the resulting code (not instruction obedience), rule on
|
|
336
|
+
* the open findings once, add only defects this round's edits introduced,
|
|
337
|
+
* never re-open a verified resolution.
|
|
328
338
|
*/
|
|
329
339
|
export function buildReReviewBrief(
|
|
330
340
|
reviewerResult: SingleResult,
|
|
@@ -342,16 +352,17 @@ export function buildReReviewBrief(
|
|
|
342
352
|
review,
|
|
343
353
|
`---`,
|
|
344
354
|
``,
|
|
345
|
-
`The worker's report (what it changed, plus any
|
|
355
|
+
`The worker's report (what it changed, plus any pushback where it replaced your fix instruction with its own fix):`,
|
|
346
356
|
`---`,
|
|
347
357
|
workerReport,
|
|
348
358
|
`---`,
|
|
349
359
|
``,
|
|
350
|
-
`Rule on EVERY previous finding: resolved, or still open.
|
|
351
|
-
`
|
|
352
|
-
`
|
|
353
|
-
`
|
|
354
|
-
`
|
|
360
|
+
`Rule on EVERY previous finding: resolved, or still open. Judge the code as it now stands — a finding is`,
|
|
361
|
+
`resolved when the pending diff fixes it soundly, whether or not the worker followed your fix instruction.`,
|
|
362
|
+
`A finding the worker pushed back on must be adjudicated ONCE — accept the worker's fix unless you can`,
|
|
363
|
+
`concretely refute its reasoning; never simply restate the finding for another round.`,
|
|
364
|
+
`Run \`git diff\` to see what changed, then add NEW findings only for defects this round's edits introduced or exposed.`,
|
|
365
|
+
`Re-review never opens findings unrelated to this round's edits; issues the earlier review missed belong to a fresh gate.`,
|
|
355
366
|
`Do NOT re-open a finding you verified as resolved.`,
|
|
356
367
|
...(options.documenterPending
|
|
357
368
|
? [
|
package/src/monitor.ts
CHANGED
|
@@ -34,13 +34,18 @@ export function isRunActiveStatus(status: RunStatus): boolean {
|
|
|
34
34
|
return status === "queued" || status === "running" || status === "steering" || status === "interrupting";
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/** Durable integration projection of a worktree-isolated run: pending before
|
|
38
|
+
* settlement, finalizing while the patch is applied/cleaned up, then the
|
|
39
|
+
* terminal WorktreeFinalizationStatus. */
|
|
40
|
+
export type RunIntegrationStatus = "pending" | "finalizing" | WorktreeFinalizationStatus;
|
|
41
|
+
|
|
37
42
|
export interface RunView {
|
|
38
43
|
id: number;
|
|
39
44
|
agent: string;
|
|
40
45
|
task: string;
|
|
41
46
|
/** Short content label derived from the task (paths/symbols), shown next to
|
|
42
47
|
* the agent name so concurrent same-agent runs are told apart by what they
|
|
43
|
-
* are doing, not just their run id. */
|
|
48
|
+
* are doing, not just by their run id. */
|
|
44
49
|
label?: string;
|
|
45
50
|
model?: string;
|
|
46
51
|
/** Selected model ref when the run handed off to current main. */
|
|
@@ -48,7 +53,10 @@ export interface RunView {
|
|
|
48
53
|
/** Effective thinking strength this run was launched with (frontmatter/config/global). */
|
|
49
54
|
thinking?: string;
|
|
50
55
|
isolation?: IsolationMode;
|
|
51
|
-
integrationStatus?:
|
|
56
|
+
integrationStatus?: RunIntegrationStatus;
|
|
57
|
+
/** Short worktree-group identity (mkdtemp suffix) shared by every run inside
|
|
58
|
+
* one isolated worktree; changes when a continuation worktree is created. */
|
|
59
|
+
worktreeId?: string;
|
|
52
60
|
forkedFromRunId?: number;
|
|
53
61
|
forkChildRunIds?: number[];
|
|
54
62
|
status: RunStatus;
|
|
@@ -85,6 +93,7 @@ export interface RunChainMeta {
|
|
|
85
93
|
relationLabel?: string;
|
|
86
94
|
parentRunId?: number;
|
|
87
95
|
isolation?: IsolationMode;
|
|
96
|
+
worktreeId?: string;
|
|
88
97
|
forkedFromRunId?: number;
|
|
89
98
|
continuationKind?: ContinuationKind;
|
|
90
99
|
}
|
|
@@ -458,7 +467,7 @@ export class MonitorStore {
|
|
|
458
467
|
...(meta?.groupId ? { groupId: meta.groupId } : {}),
|
|
459
468
|
...(meta?.relationLabel ? { relationLabel: meta.relationLabel } : {}),
|
|
460
469
|
...(meta?.parentRunId !== undefined ? { parentRunId: meta.parentRunId } : {}),
|
|
461
|
-
...(meta?.isolation ? { isolation: meta.isolation, integrationStatus: meta.isolation === "worktree" ? "pending" : undefined } : {}),
|
|
470
|
+
...(meta?.isolation ? { isolation: meta.isolation, integrationStatus: meta.isolation === "worktree" ? "pending" : undefined, ...(meta.worktreeId ? { worktreeId: meta.worktreeId } : {}) } : {}),
|
|
462
471
|
...(meta?.forkedFromRunId !== undefined ? { forkedFromRunId: meta.forkedFromRunId } : {}),
|
|
463
472
|
...(meta?.continuationKind ? { continuationKind: meta.continuationKind } : {}),
|
|
464
473
|
});
|
|
@@ -559,11 +568,17 @@ export class MonitorStore {
|
|
|
559
568
|
this.notify();
|
|
560
569
|
}
|
|
561
570
|
|
|
562
|
-
setIsolation(
|
|
571
|
+
setIsolation(
|
|
572
|
+
id: number,
|
|
573
|
+
isolation: IsolationMode,
|
|
574
|
+
integrationStatus?: RunIntegrationStatus,
|
|
575
|
+
worktreeId?: string,
|
|
576
|
+
): void {
|
|
563
577
|
const run = this.find(id);
|
|
564
578
|
if (!run) return;
|
|
565
579
|
run.isolation = isolation;
|
|
566
580
|
run.integrationStatus = integrationStatus;
|
|
581
|
+
if (worktreeId) run.worktreeId = worktreeId;
|
|
567
582
|
this.notify();
|
|
568
583
|
}
|
|
569
584
|
|
|
@@ -608,7 +623,7 @@ export class MonitorStore {
|
|
|
608
623
|
model?: string,
|
|
609
624
|
thinking?: string,
|
|
610
625
|
isolation?: IsolationMode,
|
|
611
|
-
meta?: { elapsedMs?: number; continuationKind?: ContinuationKind },
|
|
626
|
+
meta?: { elapsedMs?: number; continuationKind?: ContinuationKind; worktreeId?: string },
|
|
612
627
|
): void {
|
|
613
628
|
const run = this.find(id);
|
|
614
629
|
if (!run) {
|
|
@@ -619,7 +634,13 @@ export class MonitorStore {
|
|
|
619
634
|
label: runLabel(task),
|
|
620
635
|
model,
|
|
621
636
|
thinking,
|
|
622
|
-
...(isolation
|
|
637
|
+
...(isolation
|
|
638
|
+
? {
|
|
639
|
+
isolation,
|
|
640
|
+
integrationStatus: isolation === "worktree" ? "pending" as const : undefined,
|
|
641
|
+
...(isolation === "worktree" && meta?.worktreeId ? { worktreeId: meta.worktreeId } : {}),
|
|
642
|
+
}
|
|
643
|
+
: {}),
|
|
623
644
|
status: "queued",
|
|
624
645
|
usage: emptyUsage(),
|
|
625
646
|
elapsedMs: meta?.elapsedMs ?? 0,
|
|
@@ -635,6 +656,8 @@ export class MonitorStore {
|
|
|
635
656
|
run.thinking = thinking;
|
|
636
657
|
if (isolation) run.isolation = isolation;
|
|
637
658
|
run.integrationStatus = isolation === "worktree" ? "pending" : undefined;
|
|
659
|
+
if (isolation === "worktree" && meta?.worktreeId) run.worktreeId = meta.worktreeId;
|
|
660
|
+
else if (isolation !== "worktree") run.worktreeId = undefined;
|
|
638
661
|
run.status = "queued";
|
|
639
662
|
run.usage = emptyUsage();
|
|
640
663
|
run.activity = undefined;
|
package/src/rpc-run.ts
CHANGED
|
@@ -788,8 +788,32 @@ export async function runRpcAgentAttempt(options: RunRpcAttemptOptions): Promise
|
|
|
788
788
|
if (!closed) await processClosed.promise;
|
|
789
789
|
return;
|
|
790
790
|
}
|
|
791
|
-
|
|
792
|
-
|
|
791
|
+
// Bound the abort settlement exactly like stop: a child that never
|
|
792
|
+
// settles after abort must not hold the control operation forever.
|
|
793
|
+
let parkTimer: ReturnType<typeof setTimeout> | undefined;
|
|
794
|
+
let parkTimedOut = false;
|
|
795
|
+
const parkDeadline = new Promise<boolean>((resolve) => {
|
|
796
|
+
parkTimer = setTimeout(() => {
|
|
797
|
+
parkTimedOut = true;
|
|
798
|
+
resolve(false);
|
|
799
|
+
}, RPC_ABORT_SETTLE_TIMEOUT_MS);
|
|
800
|
+
if (typeof parkTimer.unref === "function") parkTimer.unref();
|
|
801
|
+
});
|
|
802
|
+
let accepted: boolean;
|
|
803
|
+
try {
|
|
804
|
+
accepted = await Promise.race([abortAcceptedPrompt(), parkDeadline]);
|
|
805
|
+
} catch {
|
|
806
|
+
/* a rejected abort still parks; termination below is the bounded fallback */
|
|
807
|
+
accepted = false;
|
|
808
|
+
} finally {
|
|
809
|
+
if (parkTimer) clearTimeout(parkTimer);
|
|
810
|
+
}
|
|
811
|
+
if (abortSettlement) {
|
|
812
|
+
const stable = abortSettlement;
|
|
813
|
+
abortSettlement = undefined;
|
|
814
|
+
stable.resolve();
|
|
815
|
+
}
|
|
816
|
+
if (!accepted && !parkTimedOut && !closed) await processClosed.promise;
|
|
793
817
|
if (finished && accepted) throw new Error("Thread exited while parking.");
|
|
794
818
|
markParked();
|
|
795
819
|
setAttemptPhase("parked");
|
package/src/thread-lifecycle.ts
CHANGED
|
@@ -67,6 +67,7 @@ import {
|
|
|
67
67
|
} from "./spawn.ts";
|
|
68
68
|
import {
|
|
69
69
|
createWorktreeIsolation,
|
|
70
|
+
worktreeGroupId,
|
|
70
71
|
type IsolationMode,
|
|
71
72
|
type WorktreeFinalization,
|
|
72
73
|
type WorktreeIsolation,
|
|
@@ -75,6 +76,24 @@ import {
|
|
|
75
76
|
export const FORK_CONTINUATION_PROMPT =
|
|
76
77
|
"Continue from the retained context above. Review the prior work, then take the most useful next step toward completing the existing objective without repeating completed work.";
|
|
77
78
|
|
|
79
|
+
/** Control operations must never wait forever on a settling generation: the
|
|
80
|
+
* queue task can legitimately spend minutes in worktree finalization (bounded
|
|
81
|
+
* per-Git-command timeouts) or wait behind the managed repository lane. After
|
|
82
|
+
* this deadline the control path owns the lifecycle synchronously and proceeds
|
|
83
|
+
* while the stuck tail settles silently in the background. */
|
|
84
|
+
export const CONTROL_QUIESCE_TIMEOUT_MS = 20_000;
|
|
85
|
+
|
|
86
|
+
/** Resolve true when the promise settles, or false after the bounded deadline. */
|
|
87
|
+
export function quiesced(promise: Promise<unknown>, timeoutMs: number = CONTROL_QUIESCE_TIMEOUT_MS): Promise<boolean> {
|
|
88
|
+
return Promise.race([
|
|
89
|
+
promise.then(() => true, () => true),
|
|
90
|
+
new Promise<boolean>((resolve) => {
|
|
91
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
92
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
93
|
+
}),
|
|
94
|
+
]);
|
|
95
|
+
}
|
|
96
|
+
|
|
78
97
|
const WORKTREE_ISOLATION_INSTRUCTIONS =
|
|
79
98
|
"You are running in a temporary detached Git worktree. Work only in the current cwd; do not create another worktree or manually copy/apply changes to the original checkout. The parent dispatcher will integrate your tracked, deleted, and untracked changes when this thread finally settles.";
|
|
80
99
|
|
|
@@ -148,6 +167,8 @@ export interface ManagedWorkflowRequest extends DispatchEnvironment {
|
|
|
148
167
|
executionCwd: string;
|
|
149
168
|
projectCwd: string;
|
|
150
169
|
isolation: IsolationMode;
|
|
170
|
+
/** Short identity of the isolated worktree shared by every workflow stage. */
|
|
171
|
+
worktreeId?: string;
|
|
151
172
|
signal: AbortSignal;
|
|
152
173
|
rememberLatest: (result: SingleResult) => void;
|
|
153
174
|
}
|
|
@@ -294,6 +315,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
294
315
|
}
|
|
295
316
|
}
|
|
296
317
|
const executionCwd = worktree?.cwd ?? originalCwd;
|
|
318
|
+
const worktreeGroup = worktree ? worktreeGroupId(worktree) : undefined;
|
|
297
319
|
const resolvedRoute = resolveDispatchModelRoute(agent, runConfig, runCtx);
|
|
298
320
|
// Isolation is a persistent system-level invariant, not a one-shot task
|
|
299
321
|
// prefix: queued retargets, live retargets, resumes, and main-model
|
|
@@ -310,6 +332,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
310
332
|
}
|
|
311
333
|
const runId = existingThread?.id ?? monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
312
334
|
isolation,
|
|
335
|
+
...(worktreeGroup ? { worktreeId: worktreeGroup } : {}),
|
|
313
336
|
...(seed?.forkedFromRunId !== undefined ? { forkedFromRunId: seed.forkedFromRunId } : {}),
|
|
314
337
|
...(seed?.continuationKind ? { continuationKind: seed.continuationKind } : {}),
|
|
315
338
|
});
|
|
@@ -329,6 +352,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
329
352
|
monitor.restartRun(runId, agent.name, task, route.agent.model, thinkingLevel, isolation, {
|
|
330
353
|
elapsedMs: existingThread.elapsedMs,
|
|
331
354
|
continuationKind: appendedObjectiveOnResume ? "resume-appended" : "resume-retained",
|
|
355
|
+
...(worktreeGroup ? { worktreeId: worktreeGroup } : {}),
|
|
332
356
|
});
|
|
333
357
|
runtime.settledRuns.delete(runId);
|
|
334
358
|
}
|
|
@@ -426,12 +450,20 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
426
450
|
// All normal, destructive-stop, and shutdown owners converge here. Cache
|
|
427
451
|
// the lane-protected apply itself so superseding lifecycle paths can project
|
|
428
452
|
// the same finalization onto their own result without acquiring twice.
|
|
429
|
-
generationFinalization
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
453
|
+
if (!generationFinalization) {
|
|
454
|
+
monitor.setIsolation(
|
|
455
|
+
runId,
|
|
456
|
+
"worktree",
|
|
457
|
+
"finalizing",
|
|
458
|
+
worktreeGroupId(generationWorktree),
|
|
459
|
+
);
|
|
460
|
+
generationFinalization = runInManagedRepositoryLane(
|
|
461
|
+
generationWorktree.originalRoot,
|
|
462
|
+
() => generationWorktree.finalize(),
|
|
463
|
+
);
|
|
464
|
+
}
|
|
433
465
|
const finalization = await generationFinalization;
|
|
434
|
-
monitor.setIsolation(runId, "worktree", finalization.status);
|
|
466
|
+
monitor.setIsolation(runId, "worktree", finalization.status, worktreeGroupId(generationWorktree));
|
|
435
467
|
if (result) {
|
|
436
468
|
result.runId = runId;
|
|
437
469
|
result.isolation = "worktree";
|
|
@@ -565,7 +597,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
565
597
|
// control after that child settles, so cancel its queue owner explicitly.
|
|
566
598
|
if (phase === "settled") runtime.backgroundQueue.cancel(controller);
|
|
567
599
|
}
|
|
568
|
-
|
|
600
|
+
// The settling tail may be blocked on worktree finalization or the
|
|
601
|
+
// managed repository lane. Park already owns the lifecycle, so proceed
|
|
602
|
+
// after a bounded wait and let the tail finish silently in the background.
|
|
603
|
+
if (!(await quiesced(completion))) {
|
|
604
|
+
runtime.backgroundQueue.cancel(controller);
|
|
605
|
+
}
|
|
569
606
|
if (
|
|
570
607
|
thread.generation !== generation ||
|
|
571
608
|
thread.lifecycleVersion !== version ||
|
|
@@ -631,7 +668,15 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
631
668
|
let continuationWorktree: WorktreeIsolation | undefined;
|
|
632
669
|
let clonedSession: Awaited<ReturnType<typeof forkRetainedSession>> | undefined;
|
|
633
670
|
try {
|
|
634
|
-
|
|
671
|
+
// Never wait forever on a previous generation that is still settling
|
|
672
|
+
// (e.g. blocked behind the managed repository lane in finalization).
|
|
673
|
+
if (!(await quiesced(thread.generationCompletion))) {
|
|
674
|
+
return failedStartResult(
|
|
675
|
+
thread.agentName,
|
|
676
|
+
thread.task,
|
|
677
|
+
`Run #${runId}'s previous generation is still settling; retry the resume shortly.`,
|
|
678
|
+
);
|
|
679
|
+
}
|
|
635
680
|
if (!ownsResumeReservation(thread, reservation)) {
|
|
636
681
|
return failedStartResult(
|
|
637
682
|
thread.agentName,
|
|
@@ -811,7 +856,15 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
811
856
|
let childWorktree: WorktreeIsolation | undefined;
|
|
812
857
|
let forkedSession: Awaited<ReturnType<typeof forkRetainedSession>> | undefined;
|
|
813
858
|
try {
|
|
814
|
-
|
|
859
|
+
// Same bounded preflight as resume: a still-settling source generation
|
|
860
|
+
// must not block the control operation forever.
|
|
861
|
+
if (!(await quiesced(thread.generationCompletion))) {
|
|
862
|
+
return failedStartResult(
|
|
863
|
+
thread.agentName,
|
|
864
|
+
thread.task,
|
|
865
|
+
`Run #${runId}'s previous generation is still settling; retry the fork shortly.`,
|
|
866
|
+
);
|
|
867
|
+
}
|
|
815
868
|
if (!ownsFork()) {
|
|
816
869
|
return failedStartResult(thread.agentName, thread.task, `Run #${runId} changed while fork was preparing; no child was started.`);
|
|
817
870
|
}
|
|
@@ -911,23 +964,41 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
911
964
|
isolation === "shared" && canStartManagedWorkflow(agent, workflowAvailability);
|
|
912
965
|
const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
|
|
913
966
|
if (runtime.threads.get(runId)?.generation !== generation) return;
|
|
967
|
+
// Model/thinking config may have changed while this generation sat
|
|
968
|
+
// queued behind the concurrency limit. Re-resolve the route at actual
|
|
969
|
+
// start so /subagents-setup edits apply to not-yet-started runs.
|
|
970
|
+
let activeRoute = route;
|
|
971
|
+
let activeIdleTimeoutMs = runConfig.idleTimeoutSec * 1000;
|
|
972
|
+
try {
|
|
973
|
+
const startConfig = await loadConfig(runtime.configPath);
|
|
974
|
+
runtime.backgroundQueue.setConcurrency(startConfig.maxConcurrency);
|
|
975
|
+
const resolvedStart = resolveDispatchModelRoute(agent, startConfig, runCtx);
|
|
976
|
+
activeRoute = isolation === "worktree"
|
|
977
|
+
? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
|
|
978
|
+
: resolvedStart;
|
|
979
|
+
activeIdleTimeoutMs = startConfig.idleTimeoutSec * 1000;
|
|
980
|
+
monitor.setModel(runId, activeRoute.agent.model);
|
|
981
|
+
monitor.setThinking(runId, activeRoute.thinkingLevel);
|
|
982
|
+
} catch {
|
|
983
|
+
/* keep the dispatch-time route when fresh config is unavailable */
|
|
984
|
+
}
|
|
914
985
|
let result: SingleResult;
|
|
915
986
|
try {
|
|
916
987
|
result = await runSingleAgentWithMainFallback(
|
|
917
988
|
{
|
|
918
989
|
defaultCwd: executionCwd,
|
|
919
|
-
agent:
|
|
990
|
+
agent: activeRoute.agent,
|
|
920
991
|
resolveAgentForAttempt: resolveLiveAgentTools,
|
|
921
992
|
agentName,
|
|
922
993
|
task,
|
|
923
994
|
cwd: executionCwd,
|
|
924
|
-
thinkingLevel,
|
|
925
|
-
thinkingLevelForModel:
|
|
995
|
+
thinkingLevel: activeRoute.thinkingLevel,
|
|
996
|
+
thinkingLevelForModel: activeRoute.thinkingLevelForModel,
|
|
926
997
|
signal: backgroundSignal,
|
|
927
998
|
onLive,
|
|
928
999
|
control,
|
|
929
1000
|
makeDetails: makeDetails("single", true),
|
|
930
|
-
idleTimeoutMs:
|
|
1001
|
+
idleTimeoutMs: activeIdleTimeoutMs,
|
|
931
1002
|
...(priorSessionId && priorSessionDir
|
|
932
1003
|
? {
|
|
933
1004
|
sessionId: priorSessionId,
|
|
@@ -938,7 +1009,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
938
1009
|
}
|
|
939
1010
|
: {}),
|
|
940
1011
|
},
|
|
941
|
-
|
|
1012
|
+
activeRoute.mainFallbackRef,
|
|
942
1013
|
);
|
|
943
1014
|
} catch (error) {
|
|
944
1015
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
@@ -1013,6 +1084,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
1013
1084
|
executionCwd: thread.executionCwd,
|
|
1014
1085
|
projectCwd: originalCwd,
|
|
1015
1086
|
isolation,
|
|
1087
|
+
...(worktree ? { worktreeId: worktreeGroupId(worktree) } : {}),
|
|
1016
1088
|
signal: backgroundSignal,
|
|
1017
1089
|
ctx: runCtx,
|
|
1018
1090
|
config: runConfig,
|
package/src/tools.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
8
8
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
9
9
|
import { Text } from "@earendil-works/pi-tui";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
10
11
|
import { Type } from "typebox";
|
|
11
12
|
import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "./config.ts";
|
|
12
13
|
import { formatCompletionBlock, formatUsage, matchRunIds } from "./format.ts";
|
|
@@ -19,8 +20,11 @@ import {
|
|
|
19
20
|
statusLabel,
|
|
20
21
|
type RunStatus,
|
|
21
22
|
} from "./monitor.ts";
|
|
23
|
+
import { persistRecoveryRecords, recoveryRecordFromFinalization } from "./recovery.ts";
|
|
22
24
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
25
|
+
import { CONTROL_QUIESCE_TIMEOUT_MS, quiesced } from "./thread-lifecycle.ts";
|
|
23
26
|
import { getResultOutput, isFailedResult, type SingleResult } from "./spawn.ts";
|
|
27
|
+
import type { WorktreeFinalization } from "./worktree.ts";
|
|
24
28
|
|
|
25
29
|
/** In-turn result lookup. Dispatch already ended the turn and results arrive as
|
|
26
30
|
* wake-up messages, so the default must NOT block: a settled run returns its
|
|
@@ -648,6 +652,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
648
652
|
|
|
649
653
|
const stopped: string[] = [];
|
|
650
654
|
const retainedIntegration: string[] = [];
|
|
655
|
+
const pendingIntegration: string[] = [];
|
|
651
656
|
for (const [claimIndex, claim] of claimed.entries()) {
|
|
652
657
|
const {
|
|
653
658
|
runId,
|
|
@@ -663,8 +668,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
663
668
|
stopVersion,
|
|
664
669
|
stopMessage,
|
|
665
670
|
} = claim;
|
|
666
|
-
|
|
667
|
-
|
|
671
|
+
// Every wait here is bounded: the queue task can sit for minutes in
|
|
672
|
+
// worktree finalization or behind the managed repository lane, and an
|
|
673
|
+
// unkillable child can stall even the RPC-level stop. Stop owns the
|
|
674
|
+
// lifecycle synchronously, so a stuck tail settles silently after we
|
|
675
|
+
// proceed; none of its late paths can publish a second result.
|
|
676
|
+
await quiesced(interruptionPromises[claimIndex]);
|
|
677
|
+
if (!(await quiesced(completion))) runtime.backgroundQueue.cancel(controller);
|
|
668
678
|
if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
|
|
669
679
|
if (thread.queueController === controller) thread.queueController = undefined;
|
|
670
680
|
|
|
@@ -703,8 +713,42 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
703
713
|
runId,
|
|
704
714
|
isolation: thread.isolation,
|
|
705
715
|
};
|
|
706
|
-
const
|
|
707
|
-
|
|
716
|
+
const worktree = thread.worktree;
|
|
717
|
+
let finalization: WorktreeFinalization | undefined;
|
|
718
|
+
try {
|
|
719
|
+
finalization = await Promise.race([
|
|
720
|
+
thread.finalizeIsolation(generation, stoppedResult),
|
|
721
|
+
new Promise<undefined>((resolve) => {
|
|
722
|
+
const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
|
|
723
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
724
|
+
}),
|
|
725
|
+
]);
|
|
726
|
+
} catch {
|
|
727
|
+
/* an unexpected finalize rejection must not block the stop */
|
|
728
|
+
}
|
|
729
|
+
if (finalization === undefined) {
|
|
730
|
+
// Integration is still settling in the background. Point a
|
|
731
|
+
// durable recovery record at the artifacts so the isolated work
|
|
732
|
+
// stays findable even if the background tail later fails; a
|
|
733
|
+
// successful tail removes them and the record self-prunes.
|
|
734
|
+
if (thread.isolation === "worktree" && worktree) {
|
|
735
|
+
stoppedResult.integrationStatus = "pending";
|
|
736
|
+
stoppedResult.integrationWorktreePath = worktree.worktreePath;
|
|
737
|
+
await persistRecoveryRecords(runtime.configPath, [
|
|
738
|
+
recoveryRecordFromFinalization(runId, {
|
|
739
|
+
status: "retained",
|
|
740
|
+
integrated: false,
|
|
741
|
+
hadChanges: false,
|
|
742
|
+
...(existsSync(worktree.worktreePath) ? { worktreePath: worktree.worktreePath } : {}),
|
|
743
|
+
...(existsSync(worktree.patchPath) ? { patchPath: worktree.patchPath } : {}),
|
|
744
|
+
error: "subagent_stop timed out waiting for worktree integration; it continues in the background",
|
|
745
|
+
}),
|
|
746
|
+
]).catch(() => undefined);
|
|
747
|
+
}
|
|
748
|
+
pendingIntegration.push(`#${runId}`);
|
|
749
|
+
} else if (finalization.status === "retained") {
|
|
750
|
+
retainedIntegration.push(`#${runId}`);
|
|
751
|
+
}
|
|
708
752
|
runtime.registerRunResult(runId, stoppedResult);
|
|
709
753
|
thread.lastResult = stoppedResult;
|
|
710
754
|
}
|
|
@@ -730,7 +774,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
730
774
|
return {
|
|
731
775
|
content: [{
|
|
732
776
|
type: "text",
|
|
733
|
-
text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}`,
|
|
777
|
+
text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
|
|
734
778
|
}],
|
|
735
779
|
details: {},
|
|
736
780
|
};
|
package/src/widget.ts
CHANGED
|
@@ -39,6 +39,26 @@ function formatContinuationTask(label: string, task: string, width: number): str
|
|
|
39
39
|
return summary ? `${label}${separator}${summary}` : label;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/** Worktree-group badge shown on the row that owns the isolated worktree: the
|
|
43
|
+
* short group identity plus its integration state, so a workflow visibly moves
|
|
44
|
+
* through applying → applied (or retained) and a continuation worktree (new
|
|
45
|
+
* identity) is distinguishable from the original one. */
|
|
46
|
+
function worktreeBadge(run: RunView): string {
|
|
47
|
+
const id = run.worktreeId ?? "?";
|
|
48
|
+
switch (run.integrationStatus) {
|
|
49
|
+
case "finalizing":
|
|
50
|
+
return `wt:${id} applying`;
|
|
51
|
+
case "integrated":
|
|
52
|
+
return `wt:${id} applied`;
|
|
53
|
+
case "no_changes":
|
|
54
|
+
return `wt:${id} clean`;
|
|
55
|
+
case "retained":
|
|
56
|
+
return `wt:${id} retained`;
|
|
57
|
+
default:
|
|
58
|
+
return `wt:${id}`;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
42
62
|
/** One compact primary line per genuinely active run, plus an optional indented
|
|
43
63
|
* activity line. The primary line reserves stage model/thinking when present and
|
|
44
64
|
* elapsed width before truncating the task. Settled and parked threads never
|
|
@@ -49,6 +69,7 @@ function runPrimaryLine(
|
|
|
49
69
|
width: number,
|
|
50
70
|
now: number,
|
|
51
71
|
prefix: string,
|
|
72
|
+
isGroupOwner: boolean,
|
|
52
73
|
): string {
|
|
53
74
|
const dim = (text: string): string => theme.fg("dim", text);
|
|
54
75
|
const icon = run.managedWorkflow && run.status === "running"
|
|
@@ -56,18 +77,24 @@ function runPrimaryLine(
|
|
|
56
77
|
: statusIcon(run.status, theme);
|
|
57
78
|
const displayName = run.managedWorkflow ? `${run.agent} workflow` : run.agent;
|
|
58
79
|
const name = theme.fg("accent", theme.bold(displayName));
|
|
59
|
-
|
|
80
|
+
// The stable run id is the handle for subagent_control/subagent_status; a
|
|
81
|
+
// queued run has not started, which must be visible at a glance. Its model
|
|
82
|
+
// is omitted too: the route is re-resolved when the run actually starts.
|
|
83
|
+
const queued = run.status === "queued";
|
|
84
|
+
const queuedTag = queued ? ` ${dim("· queued")}` : "";
|
|
85
|
+
const identity = `${prefix}${icon} #${run.id} ${name}${queuedTag}`;
|
|
60
86
|
const elapsed = formatElapsed(run, now);
|
|
61
87
|
// Render only the resolved model id plus thinking level. Provider auth and
|
|
62
88
|
// other configuration never enter monitor state or this line.
|
|
63
89
|
const modelId = run.model?.split("/").at(-1);
|
|
64
|
-
const modelSource = run.managedWorkflow
|
|
90
|
+
const modelSource = run.managedWorkflow || queued
|
|
65
91
|
? ""
|
|
66
92
|
: formatTaskSummary(
|
|
67
93
|
modelId ? `${modelId}${run.thinking ? `/${run.thinking}` : ""}` : run.thinking ? `thinking:${run.thinking}` : "",
|
|
68
94
|
64,
|
|
69
95
|
false,
|
|
70
96
|
);
|
|
97
|
+
const badge = isGroupOwner && run.isolation === "worktree" ? worktreeBadge(run) : "";
|
|
71
98
|
// A chain child shows its role in the chain plus a task-derived label; the
|
|
72
99
|
// templated fix brief itself would only repeat the parent review's content.
|
|
73
100
|
const continuation = run.parentRunId === undefined
|
|
@@ -81,7 +108,7 @@ function runPrimaryLine(
|
|
|
81
108
|
const taskDesiredSource = [continuation, taskSource]
|
|
82
109
|
.filter((part): part is string => Boolean(part))
|
|
83
110
|
.join(" · ");
|
|
84
|
-
const primaryPartCount = 2 + (modelSource ? 1 : 0) + (elapsed ? 1 : 0);
|
|
111
|
+
const primaryPartCount = 2 + (modelSource ? 1 : 0) + (badge ? 1 : 0) + (elapsed ? 1 : 0);
|
|
85
112
|
const contentWidth = Math.max(
|
|
86
113
|
0,
|
|
87
114
|
width -
|
|
@@ -130,6 +157,7 @@ function runPrimaryLine(
|
|
|
130
157
|
identity,
|
|
131
158
|
task ? dim(task) : undefined,
|
|
132
159
|
modelThinking ? dim(modelThinking) : undefined,
|
|
160
|
+
badge ? dim(badge) : undefined,
|
|
133
161
|
].filter((part): part is string => Boolean(part)).join(" · ");
|
|
134
162
|
return compactLine(primaryLeft, elapsed ? dim(`· ${elapsed}`) : "", width);
|
|
135
163
|
}
|
|
@@ -211,7 +239,9 @@ export function formatActiveRunLines(
|
|
|
211
239
|
const lines: string[] = [];
|
|
212
240
|
for (const root of roots) {
|
|
213
241
|
const children = childrenOf.get(root.id) ?? [];
|
|
214
|
-
|
|
242
|
+
// Roots (including orphaned chain children whose parent row is gone) own
|
|
243
|
+
// their worktree group; nested children inherit the group via the tree.
|
|
244
|
+
lines.push(runPrimaryLine(root, theme, width, now, "", true));
|
|
215
245
|
const hasTimeline = Boolean(root.managedWorkflow && root.workflowStages?.length);
|
|
216
246
|
const timeline = hasTimeline ? workflowTimelineLine(root, theme, width) : undefined;
|
|
217
247
|
if (timeline) lines.push(timeline);
|
|
@@ -222,7 +252,7 @@ export function formatActiveRunLines(
|
|
|
222
252
|
}
|
|
223
253
|
children.forEach((child, index) => {
|
|
224
254
|
const connector = index === children.length - 1 ? "└ " : "├ ";
|
|
225
|
-
lines.push(runPrimaryLine(child, theme, width, now, theme.fg("dim", ` ${connector}`)));
|
|
255
|
+
lines.push(runPrimaryLine(child, theme, width, now, theme.fg("dim", ` ${connector}`), false));
|
|
226
256
|
lines.push(...runActivityLine(child, theme, width, " "));
|
|
227
257
|
});
|
|
228
258
|
}
|
package/src/worktree.ts
CHANGED
|
@@ -16,6 +16,18 @@ import { isAbsolute, join, relative, resolve } from "node:path";
|
|
|
16
16
|
|
|
17
17
|
export type IsolationMode = "shared" | "worktree";
|
|
18
18
|
|
|
19
|
+
const WORKTREE_TEMP_DIR_PREFIX = "pi-subagent-worktree-";
|
|
20
|
+
|
|
21
|
+
/** Short stable identity of one isolated worktree group (the mkdtemp suffix).
|
|
22
|
+
* Continuation/fork generations create a fresh worktree, so the identity
|
|
23
|
+
* visibly changes when the group's filesystem boundary changes. */
|
|
24
|
+
export function worktreeGroupId(worktree: Pick<WorktreeIsolation, "tempDir">): string {
|
|
25
|
+
const base = worktree.tempDir.split(/[\\/]/).filter(Boolean).pop() ?? worktree.tempDir;
|
|
26
|
+
return base.startsWith(WORKTREE_TEMP_DIR_PREFIX)
|
|
27
|
+
? base.slice(WORKTREE_TEMP_DIR_PREFIX.length)
|
|
28
|
+
: base;
|
|
29
|
+
}
|
|
30
|
+
|
|
19
31
|
export interface CommandRunOptions {
|
|
20
32
|
cwd: string;
|
|
21
33
|
input?: Buffer;
|