@xzzpig/pi-subagents 0.20.0 → 0.22.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/CHANGELOG.md +164 -0
- package/README.md +1 -1
- package/agents/oracle.md +8 -19
- package/agents/researcher.md +0 -3
- package/agents/reviewer.md +17 -61
- package/agents/scout.md +1 -4
- package/agents/worker.md +8 -25
- package/docs/agents.md +72 -7
- package/docs/configuration.md +58 -7
- package/docs/extension-api.md +36 -11
- package/docs/fork-extensions.md +1 -0
- package/docs/fork-supervisor-routing.md +77 -0
- package/docs/missions.md +34 -17
- package/docs/models.md +1 -1
- package/docs/observability.md +10 -5
- package/docs/tool-reference.md +117 -84
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +16 -7
- package/index.ts +5 -0
- package/package.json +6 -3
- package/prompts/council.md +1 -1
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +16 -16
- package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
- package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +9 -1
- package/src/agents/agent-management.ts +4 -0
- package/src/agents/agent-memory.ts +3 -3
- package/src/agents/agent-scope.ts +4 -0
- package/src/agents/agent-serializer.ts +8 -1
- package/src/agents/agents.ts +191 -145
- package/src/api/preflight.ts +8 -4
- package/src/api/supervisor-routing.ts +196 -0
- package/src/extension/config.ts +21 -2
- package/src/extension/context-injection.ts +6 -1
- package/src/extension/control-notices.ts +1 -9
- package/src/extension/declaration-pinning.ts +164 -0
- package/src/extension/doctor.ts +7 -10
- package/src/extension/fanout-child.ts +7 -8
- package/src/extension/index.ts +143 -134
- package/src/extension/reply-workflow-script.ts +20 -11
- package/src/extension/rpc.ts +11 -6
- package/src/extension/schemas.ts +34 -30
- package/src/extension/subagent-guide.ts +86 -6
- package/src/extension/subagent-options.ts +47 -0
- package/src/extension/tool-activation.ts +3 -2
- package/src/extension/tool-description.ts +51 -68
- package/src/inspectors/actions.ts +37 -11
- package/src/inspectors/plugins.ts +3 -2
- package/src/inspectors/tmux/actions.ts +204 -0
- package/src/inspectors/tmux/client.ts +85 -0
- package/src/inspectors/tmux/plugin.ts +21 -0
- package/src/integrations/herdr-status.ts +18 -49
- package/src/integrations/program-status.ts +215 -0
- package/src/intercom/fork-supervisor-routing.ts +533 -0
- package/src/intercom/native-supervisor-channel.ts +152 -13
- package/src/intercom/result-intercom.ts +3 -2
- package/src/intercom/supervisor-ui.ts +2 -174
- package/src/missions/store.ts +25 -5
- package/src/profiles/profiles.ts +24 -21
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +143 -38
- package/src/runs/background/async-job-tracker.ts +11 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +14 -9
- package/src/runs/background/binary-bootstrap.ts +2 -1
- package/src/runs/background/calendar-schedule.ts +90 -0
- package/src/runs/background/chain-root-attachment.ts +9 -5
- package/src/runs/background/fleet-view.ts +5 -5
- package/src/runs/background/notify.ts +185 -12
- package/src/runs/background/result-files.ts +116 -5
- package/src/runs/background/result-watcher.ts +99 -66
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/run-child-session.ts +16 -2
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-child-launch.ts +1 -0
- package/src/runs/background/runner-http-dispatcher.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +256 -61
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +32 -12
- package/src/runs/background/subagent-wait.ts +38 -19
- package/src/runs/background/terminal-run-index.ts +46 -1
- package/src/runs/background/wait-completions.ts +1 -0
- package/src/runs/background/wait-tool.ts +33 -23
- package/src/runs/background/workflow-terminal-proof.ts +39 -22
- package/src/runs/foreground/async-stop-action.ts +48 -22
- package/src/runs/foreground/execution.ts +94 -52
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +232 -77
- package/src/runs/shared/child-commands.ts +2 -1
- package/src/runs/shared/child-hooks.ts +4 -3
- package/src/runs/shared/child-launch.ts +3 -0
- package/src/runs/shared/child-session.ts +41 -24
- package/src/runs/shared/child-tool-plan.ts +13 -26
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/fork-command-result.ts +10 -0
- package/src/runs/shared/herdr-placed-run.ts +5 -4
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +30 -1
- package/src/runs/shared/nested-events.ts +5 -0
- package/src/runs/shared/parallel-handoff.ts +56 -8
- package/src/runs/shared/parallel-utils.ts +2 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/runner-launcher.ts +25 -0
- package/src/runs/shared/single-output.ts +53 -0
- package/src/runs/shared/structured-output.ts +14 -7
- package/src/runs/shared/subagent-control.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
- package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
- package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
- package/src/runs/shared/worktree-lock.ts +29 -0
- package/src/runs/shared/worktree.ts +12 -1
- package/src/shared/atomic-json.ts +4 -2
- package/src/shared/edit-distance.ts +33 -0
- package/src/shared/file-lease.ts +74 -0
- package/src/shared/formatters.ts +1 -5
- package/src/shared/model-info.ts +22 -0
- package/src/shared/package-version.ts +17 -0
- package/src/shared/parent-wake.ts +79 -0
- package/src/shared/pruned-fork.ts +7 -1
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +36 -2
- package/src/shared/utils.ts +8 -6
- package/src/slash/prompt-template-bridge.ts +21 -20
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagents-admin.ts +2 -1
- package/src/tui/fleet-native-transcript.ts +2 -0
- package/src/tui/fleet-transcript.ts +12 -3
- package/src/tui/fleet.ts +11 -8
- package/src/tui/render.ts +27 -19
- package/src/tui/subagent-messages.ts +305 -0
- package/src/watchdog/diff-tool.ts +2 -2
- package/src/watchdog/register-main.ts +2 -22
- package/src/watchdog/render.ts +2 -24
- package/src/watchdog/runtime.ts +6 -4
- package/src/watchdog/settings.ts +18 -13
- package/src/watchdog/tool-actions.ts +2 -2
- package/src/workflows/scripted-workflow.ts +20 -6
- package/src/workflows/workflow-resources.ts +11 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withHandoffWriteLock, withRepositoryWorktreeLock } from "./worktree-lock.ts";
|
|
1
2
|
import * as fs from "node:fs";
|
|
2
3
|
import * as path from "node:path";
|
|
3
4
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
@@ -20,7 +21,7 @@ import type {
|
|
|
20
21
|
WorktreeSetupProgress,
|
|
21
22
|
WorktreeCleanupIntent,
|
|
22
23
|
} from "./worktree.ts";
|
|
23
|
-
import { cleanupWorktrees } from "./worktree.ts";
|
|
24
|
+
import { cleanupWorktrees, withWorktreeTransaction } from "./worktree.ts";
|
|
24
25
|
import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "./lane-metadata.ts";
|
|
25
26
|
|
|
26
27
|
export interface ParallelHandoffResult {
|
|
@@ -159,6 +160,26 @@ function pathInside(root: string, candidate: string): boolean {
|
|
|
159
160
|
return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
160
161
|
}
|
|
161
162
|
|
|
163
|
+
export async function protectRetainedWorktreeForResume(manifestPath: string, runId: string, childIndex: number, signal?: AbortSignal): Promise<string> {
|
|
164
|
+
const original = readParallelHandoffManifest(manifestPath);
|
|
165
|
+
const group = original?.groups.find((item) => item.children.some((child) => child.index === childIndex));
|
|
166
|
+
if (!group) throw new Error("Retained worktree handoff disappeared before resume admission.");
|
|
167
|
+
return withWorktreeTransaction(() => withRepositoryWorktreeLock(group.repoRoot, () => withHandoffWriteLock(manifestPath, () => {
|
|
168
|
+
signal?.throwIfAborted();
|
|
169
|
+
const cwd = resolveRetainedWorktreeCwd(manifestPath, runId, childIndex);
|
|
170
|
+
if (!cwd) throw new Error("Retained worktree ownership disappeared before resume admission.");
|
|
171
|
+
const manifest = readParallelHandoffManifest(manifestPath)!;
|
|
172
|
+
const currentGroup = manifest.groups.find((item) => item.children.some((child) => child.index === childIndex))!;
|
|
173
|
+
const child = currentGroup.children.find((item) => item.index === childIndex)!;
|
|
174
|
+
const task = currentGroup.cleanup.tasks.find((item) => item.index === child.taskIndex)!;
|
|
175
|
+
task.preserved = true;
|
|
176
|
+
task.reason = "retained child resume requires managed worktree cwd";
|
|
177
|
+
manifest.updatedAt = Date.now();
|
|
178
|
+
writeAtomicJson(manifestPath, manifest);
|
|
179
|
+
return cwd;
|
|
180
|
+
}), { signal }));
|
|
181
|
+
}
|
|
182
|
+
|
|
162
183
|
export function resolveRetainedWorktreeCwd(manifestPath: string, runId: string, childIndex: number): string | undefined {
|
|
163
184
|
const manifest = readParallelHandoffManifest(manifestPath);
|
|
164
185
|
if (!manifest) return undefined;
|
|
@@ -405,7 +426,7 @@ function firstRepositoryRoot(manifest: ParallelHandoffManifest): string | undefi
|
|
|
405
426
|
|
|
406
427
|
function formatCleanupCommand(manifestPath: string, manifest: ParallelHandoffManifest): string | undefined {
|
|
407
428
|
const repoRoot = firstRepositoryRoot(manifest);
|
|
408
|
-
return repoRoot ? `subagent({ action: "worktree.cleanup", repo: ${JSON.stringify(repoRoot)}, handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" })` : undefined;
|
|
429
|
+
return repoRoot ? `subagent({ action: "worktree.cleanup", options: { repo: ${JSON.stringify(repoRoot)}, handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" } })` : undefined;
|
|
409
430
|
}
|
|
410
431
|
|
|
411
432
|
export function formatStoredParallelHandoffCleanup(manifestPath: string, manifest?: ParallelHandoffManifest): string {
|
|
@@ -417,7 +438,7 @@ export function formatStoredParallelHandoffCleanup(manifestPath: string, manifes
|
|
|
417
438
|
stored = undefined;
|
|
418
439
|
}
|
|
419
440
|
}
|
|
420
|
-
if (!stored) return ["Cleanup eligibility: unknown", "Reason: lane manifest is missing or invalid; removal is not safe.", `Plan command: subagent({ action: "worktree.cleanup", handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" })`].join("\n");
|
|
441
|
+
if (!stored) return ["Cleanup eligibility: unknown", "Reason: lane manifest is missing or invalid; removal is not safe.", `Plan command: subagent({ action: "worktree.cleanup", options: { handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" } })`].join("\n");
|
|
421
442
|
const eligibility = trustedStoredCleanupEligibility(stored);
|
|
422
443
|
const lines = [`Cleanup eligibility: ${eligibility.state}`];
|
|
423
444
|
if (eligibility.state === "terminal-blocked") lines.push(`Reason: ${eligibility.reason}`);
|
|
@@ -434,7 +455,11 @@ export interface ParallelHandoffEvidenceResult {
|
|
|
434
455
|
text: string;
|
|
435
456
|
}
|
|
436
457
|
|
|
437
|
-
export function recordParallelHandoffMerge(
|
|
458
|
+
export function recordParallelHandoffMerge(...args: Parameters<typeof recordParallelHandoffMergeUnlocked>): ReturnType<typeof recordParallelHandoffMergeUnlocked> {
|
|
459
|
+
return withHandoffWriteLock(args[0].manifestPath, () => recordParallelHandoffMergeUnlocked(...args));
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function recordParallelHandoffMergeUnlocked(input: { manifestPath: string; laneId: string; merge: unknown; now?: number }): ParallelHandoffEvidenceResult {
|
|
438
463
|
const manifest = readParallelHandoffManifest(input.manifestPath);
|
|
439
464
|
if (!manifest) throw new Error(`Parallel handoff manifest not found: ${input.manifestPath}`);
|
|
440
465
|
validateManifestForLaneEvidence(manifest, boundedString(input.laneId, "laneId", MAX_SUPERSESSION_ID_LENGTH));
|
|
@@ -452,7 +477,11 @@ export function recordParallelHandoffMerge(input: { manifestPath: string; laneId
|
|
|
452
477
|
return { manifest: updated, reference: referenceFor(input.manifestPath, updated), text: formatStoredParallelHandoffCleanup(input.manifestPath, updated) };
|
|
453
478
|
}
|
|
454
479
|
|
|
455
|
-
export function recordParallelHandoffSupersession(
|
|
480
|
+
export function recordParallelHandoffSupersession(...args: Parameters<typeof recordParallelHandoffSupersessionUnlocked>): ReturnType<typeof recordParallelHandoffSupersessionUnlocked> {
|
|
481
|
+
return withHandoffWriteLock(args[0].manifestPath, () => recordParallelHandoffSupersessionUnlocked(...args));
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function recordParallelHandoffSupersessionUnlocked(input: { manifestPath: string; laneId: string; supersession: unknown; now?: number }): ParallelHandoffEvidenceResult {
|
|
456
485
|
const manifest = readParallelHandoffManifest(input.manifestPath);
|
|
457
486
|
if (!manifest) throw new Error(`Parallel handoff manifest not found: ${input.manifestPath}`);
|
|
458
487
|
const laneId = boundedString(input.laneId, "laneId", MAX_SUPERSESSION_ID_LENGTH);
|
|
@@ -494,7 +523,11 @@ function missingDiff(input: { manifestPath: string; stepIndex: number; taskIndex
|
|
|
494
523
|
};
|
|
495
524
|
}
|
|
496
525
|
|
|
497
|
-
export function writeParallelHandoffGroup(
|
|
526
|
+
export function writeParallelHandoffGroup(...args: Parameters<typeof writeParallelHandoffGroupUnlocked>): ReturnType<typeof writeParallelHandoffGroupUnlocked> {
|
|
527
|
+
return withHandoffWriteLock(args[0].manifestPath, () => writeParallelHandoffGroupUnlocked(...args));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function writeParallelHandoffGroupUnlocked(input: {
|
|
498
531
|
manifestPath: string;
|
|
499
532
|
runId: string;
|
|
500
533
|
mode: "single" | "parallel" | "chain";
|
|
@@ -577,6 +610,7 @@ export function writeParallelHandoffGroup(input: {
|
|
|
577
610
|
branch: worktree.branch,
|
|
578
611
|
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
579
612
|
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
613
|
+
...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
|
|
580
614
|
worktreeRemoved: false,
|
|
581
615
|
branchRemoved: false,
|
|
582
616
|
preserved: true,
|
|
@@ -584,6 +618,15 @@ export function writeParallelHandoffGroup(input: {
|
|
|
584
618
|
})),
|
|
585
619
|
},
|
|
586
620
|
};
|
|
621
|
+
for (const task of group.cleanup.tasks) {
|
|
622
|
+
const previous = existing?.groups.flatMap((item) => item.cleanup.tasks).find((item) => item.path === task.path && item.branch === task.branch);
|
|
623
|
+
if (previous?.worktreeRemoved) task.worktreeRemoved = true;
|
|
624
|
+
if (previous?.branchRemoved) task.branchRemoved = true;
|
|
625
|
+
if (!task.worktreeRemoved && previous?.reason?.includes("retained child resume")) {
|
|
626
|
+
task.preserved = true;
|
|
627
|
+
task.reason = previous.reason;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
587
630
|
const groups = existing?.groups.filter((candidate) => candidate.stepIndex !== input.stepIndex) ?? [];
|
|
588
631
|
groups.push(group);
|
|
589
632
|
groups.sort((left, right) => left.stepIndex - right.stepIndex);
|
|
@@ -664,7 +707,7 @@ export function writeWorktreeSetupHandoff(input: Omit<Parameters<typeof writePar
|
|
|
664
707
|
const task = cleanup?.tasks.find((candidate) => candidate.index === worktree.index);
|
|
665
708
|
return task ? { ...task, reason: task.reason && diagnostic(task.reason), errors: task.errors?.map(diagnostic) } : {
|
|
666
709
|
index: worktree.index, path: worktree.path, branch: worktree.branch,
|
|
667
|
-
provider: worktree.provider, naming: worktree.naming,
|
|
710
|
+
provider: worktree.provider, naming: worktree.naming, recordedBaseDir: worktree.recordedBaseDir,
|
|
668
711
|
worktreeRemoved: false, branchRemoved: false, preserved: true,
|
|
669
712
|
reason: "setup pending durable handoff capture",
|
|
670
713
|
};
|
|
@@ -681,7 +724,11 @@ export function formatParallelHandoffError(error: unknown): string {
|
|
|
681
724
|
return `Worktree handoff unavailable: ${error instanceof Error ? error.message : String(error)}`;
|
|
682
725
|
}
|
|
683
726
|
|
|
684
|
-
export function discardPreservedWorktrees(
|
|
727
|
+
export function discardPreservedWorktrees(...args: Parameters<typeof discardPreservedWorktreesUnlocked>): ReturnType<typeof discardPreservedWorktreesUnlocked> {
|
|
728
|
+
return withHandoffWriteLock(args[0], () => discardPreservedWorktreesUnlocked(...args));
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function discardPreservedWorktreesUnlocked(
|
|
685
732
|
manifestPath: string,
|
|
686
733
|
authorization: Extract<WorktreeCleanupIntent, { kind: "discard" }>["authorization"],
|
|
687
734
|
): { manifest: ParallelHandoffManifest; text: string } {
|
|
@@ -702,6 +749,7 @@ export function discardPreservedWorktrees(
|
|
|
702
749
|
branch: task.branch,
|
|
703
750
|
...(task.provider ? { provider: task.provider } : {}),
|
|
704
751
|
...(task.naming ? { naming: task.naming } : {}),
|
|
752
|
+
...(task.recordedBaseDir ? { recordedBaseDir: task.recordedBaseDir } : {}),
|
|
705
753
|
index: task.index,
|
|
706
754
|
nodeModulesLinked: false,
|
|
707
755
|
syntheticPaths: [],
|
|
@@ -3,6 +3,8 @@ export type ResolvedRunnerConfig = import("../../shared/types.ts").AgentRunnerCo
|
|
|
3
3
|
export interface RunnerSubagentStep {
|
|
4
4
|
/** Session id of the direct parent session for permission-system ask forwarding. */
|
|
5
5
|
parentSessionId?: string;
|
|
6
|
+
/** Parent session file, recorded as the new child session's `parentSession` header. */
|
|
7
|
+
parentSessionFile?: string;
|
|
6
8
|
/** Resolved opt-in rules for native Pi child tool calls. */
|
|
7
9
|
permissionRules?: import("./permissions.ts").PermissionRules;
|
|
8
10
|
/** Parent-authoritative trust state for profile-aware project config merging. */
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unfinished assistant text recovered when a child ends abnormally.
|
|
3
|
+
*
|
|
4
|
+
* Final output is built from completed `message_end` messages, so text that was
|
|
5
|
+
* still streaming when a child timed out or its session threw is otherwise lost.
|
|
6
|
+
* The tracker keeps one in-memory reference to the latest unfinished assistant
|
|
7
|
+
* message. Nothing is persisted.
|
|
8
|
+
*/
|
|
9
|
+
import type { ChildSessionEvent } from "./child-session.ts";
|
|
10
|
+
import { extractTextFromContent } from "../../shared/utils.ts";
|
|
11
|
+
|
|
12
|
+
export type PartialOutputCause = "timeout" | "child error";
|
|
13
|
+
|
|
14
|
+
export interface PartialOutputTracker {
|
|
15
|
+
observe(event: ChildSessionEvent): void;
|
|
16
|
+
/** Latest unfinished assistant text that is newer than the last completed reply. */
|
|
17
|
+
text(): string | undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function isAssistant(message: unknown): boolean {
|
|
21
|
+
return !!message && typeof message === "object" && (message as { role?: unknown }).role === "assistant";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function isErroredAssistant(message: unknown): boolean {
|
|
25
|
+
const { stopReason, errorMessage } = message as { stopReason?: unknown; errorMessage?: unknown };
|
|
26
|
+
return stopReason === "error" || (typeof errorMessage === "string" && errorMessage.length > 0);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function createPartialOutputTracker(): PartialOutputTracker {
|
|
30
|
+
// Only a reference is kept per event; text is extracted once, when a child ends abnormally.
|
|
31
|
+
let latest: { content?: unknown } | undefined;
|
|
32
|
+
return {
|
|
33
|
+
observe(event) {
|
|
34
|
+
if ((event.type !== "message_update" && event.type !== "message_end") || !isAssistant(event.message)) return;
|
|
35
|
+
// A completed reply, including a tool-only one, is already part of the final output.
|
|
36
|
+
// A provider-error message is skipped there, so its text is the newest unfinished text.
|
|
37
|
+
latest = event.type === "message_update" || isErroredAssistant(event.message) ? event.message as { content?: unknown } : undefined;
|
|
38
|
+
},
|
|
39
|
+
text() {
|
|
40
|
+
const text = extractTextFromContent(latest?.content);
|
|
41
|
+
return text.trim() ? text : undefined;
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function formatPartialOutput(text: string, cause: PartialOutputCause): string {
|
|
47
|
+
return `Partial output before ${cause}:\n${text}`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AgentConfig } from "../../agents/agents.ts";
|
|
2
|
+
import type { RunnerLauncher } from "../../shared/types.ts";
|
|
3
|
+
|
|
4
|
+
/** Own-property lookup, so an inherited object key can never select a command. */
|
|
5
|
+
export function lookupRunnerLauncher(runnerLaunchers: Record<string, string[]> | undefined, name: string): RunnerLauncher | undefined {
|
|
6
|
+
const argv = runnerLaunchers && Object.hasOwn(runnerLaunchers, name) ? runnerLaunchers[name] : undefined;
|
|
7
|
+
return argv ? { name, argv: [...argv] } : undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** A launcher wraps the local Pi background runner, so it cannot combine with machine placement or an external runner. */
|
|
11
|
+
export function runnerLauncherPlacementError(agent: Pick<AgentConfig, "name" | "launcher" | "runner">, machine: string | undefined): string | undefined {
|
|
12
|
+
if (agent.launcher === undefined) return undefined;
|
|
13
|
+
const runnerType = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job" ? agent.runner.type : undefined;
|
|
14
|
+
if (!machine && !runnerType) return undefined;
|
|
15
|
+
return `Agent '${agent.name}' uses launcher '${agent.launcher}', which wraps the local Pi background runner, so it cannot run ${machine ? `on machine '${machine}'` : `with runner.type='${runnerType}'`}.`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The launcher an agent launch runs under, or the reason it cannot launch. */
|
|
19
|
+
export function resolveAgentRunnerLauncher(agent: Pick<AgentConfig, "name" | "launcher" | "runner">, runnerLaunchers: Record<string, string[]> | undefined, machine: string | undefined): { launcher?: RunnerLauncher; error?: string } {
|
|
20
|
+
if (agent.launcher === undefined) return {};
|
|
21
|
+
const placementError = runnerLauncherPlacementError(agent, machine);
|
|
22
|
+
if (placementError) return { error: placementError };
|
|
23
|
+
const launcher = lookupRunnerLauncher(runnerLaunchers, agent.launcher);
|
|
24
|
+
return launcher ? { launcher } : { error: `Agent '${agent.name}' uses launcher '${agent.launcher}', which is not defined in runnerLaunchers in the user subagent config.` };
|
|
25
|
+
}
|
|
@@ -174,6 +174,59 @@ export function formatSavedOutputReference(savedPath: string, fullOutput: string
|
|
|
174
174
|
};
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
const INLINE_OUTPUT_HEAD_CHARS = 2_000;
|
|
178
|
+
/** Larger files are not read to check a cap; the output then stays whole. */
|
|
179
|
+
const MAX_FULL_OUTPUT_FILE_BYTES = 50 * 1024 * 1024;
|
|
180
|
+
/** The line finalizeSingleOutput appends when inline output was also saved to an explicit output file. */
|
|
181
|
+
const SAVED_OUTPUT_LINE = /\n\nOutput saved to: (.+) \([^()\n]*\)\. Read this file if needed\.$/;
|
|
182
|
+
|
|
183
|
+
function readFullOutputFile(filePath: string): string | undefined {
|
|
184
|
+
try {
|
|
185
|
+
const stat = fs.statSync(filePath);
|
|
186
|
+
if (!stat.isFile() || stat.size > MAX_FULL_OUTPUT_FILE_BYTES) return undefined;
|
|
187
|
+
return fs.readFileSync(filePath, "utf-8");
|
|
188
|
+
} catch {
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Keeps at most INLINE_OUTPUT_HEAD_CHARS of a child's output inline and points to the file holding all of it.
|
|
195
|
+
* Files come only from run records, never from the child's text: a trailing `Output saved to:` line is kept as the
|
|
196
|
+
* pointer only when it names the run's recorded saved-output path, and that recorded path is what gets read.
|
|
197
|
+
* Output stays whole when it is short or no readable file contains it, so no text is lost.
|
|
198
|
+
*/
|
|
199
|
+
export function capInlineOutput(output: string, files: { artifactPath?: string; savedPath?: string }): string {
|
|
200
|
+
const match = files.savedPath ? output.match(SAVED_OUTPUT_LINE) : null;
|
|
201
|
+
const savedLine = match && files.savedPath && match[1] === path.resolve(files.savedPath) ? match : undefined;
|
|
202
|
+
const body = savedLine ? output.slice(0, savedLine.index) : output;
|
|
203
|
+
const filePath = savedLine ? files.savedPath : files.artifactPath;
|
|
204
|
+
if (body.length <= INLINE_OUTPUT_HEAD_CHARS || !filePath) return output;
|
|
205
|
+
const fullOutput = readFullOutputFile(filePath);
|
|
206
|
+
if (fullOutput === undefined || !fullOutput.includes(body)) return output;
|
|
207
|
+
const lineEnd = body.lastIndexOf("\n", INLINE_OUTPUT_HEAD_CHARS);
|
|
208
|
+
let end = lineEnd >= INLINE_OUTPUT_HEAD_CHARS - 200 ? lineEnd : INLINE_OUTPUT_HEAD_CHARS;
|
|
209
|
+
if (/[\uD800-\uDBFF]/.test(body[end - 1] ?? "")) end -= 1;
|
|
210
|
+
if (savedLine) return `${body.slice(0, end)}\n…${output.slice(body.length)}`;
|
|
211
|
+
const reference = formatSavedOutputReference(filePath, fullOutput);
|
|
212
|
+
return `${body.slice(0, end)}\n…\nFull output: ${reference.path} (${formatByteSize(reference.bytes)}, ${reference.lines} ${reference.lines === 1 ? "line" : "lines"}). Read it if needed.`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Applies capInlineOutput to each `agent:\noutput` section of a run summary whose child output is long. */
|
|
216
|
+
export function capSummaryOutputs(summary: string, results: ReadonlyArray<{ agent?: unknown; output?: unknown; artifactPaths?: { outputPath?: unknown }; artifactOutputSaveFailed?: unknown; savedOutputPath?: unknown }> | undefined): string {
|
|
217
|
+
let capped = summary;
|
|
218
|
+
for (const result of results ?? []) {
|
|
219
|
+
if (typeof result.agent !== "string" || typeof result.output !== "string" || result.output.length <= INLINE_OUTPUT_HEAD_CHARS) continue;
|
|
220
|
+
const artifactPath = result.artifactOutputSaveFailed === true || typeof result.artifactPaths?.outputPath !== "string" ? undefined : result.artifactPaths.outputPath;
|
|
221
|
+
const savedPath = typeof result.savedOutputPath === "string" && result.savedOutputPath ? result.savedOutputPath : undefined;
|
|
222
|
+
const section = `${result.agent}:\n${result.output}`;
|
|
223
|
+
const index = capped.indexOf(section);
|
|
224
|
+
if (index < 0) continue;
|
|
225
|
+
capped = `${capped.slice(0, index)}${result.agent}:\n${capInlineOutput(result.output, { artifactPath, savedPath })}${capped.slice(index + section.length)}`;
|
|
226
|
+
}
|
|
227
|
+
return capped;
|
|
228
|
+
}
|
|
229
|
+
|
|
177
230
|
export function validateFileOnlyOutputMode(outputMode: OutputMode | undefined, outputPath: string | undefined, context: string): string | undefined {
|
|
178
231
|
if (outputMode === "file-only" && !outputPath) {
|
|
179
232
|
return `${context} sets outputMode: "file-only" but does not configure an output file. Set output to a path or use outputMode: "inline".`;
|
|
@@ -5,6 +5,7 @@ import * as path from "node:path";
|
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import type { Message } from "@earendil-works/pi-ai";
|
|
7
7
|
import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
|
|
8
|
+
import { resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "./pi-spawn.ts";
|
|
8
9
|
import type { JsonSchemaObject } from "../../shared/types.ts";
|
|
9
10
|
import type { ResolvedAcceptanceReportMode } from "./acceptance.ts";
|
|
10
11
|
|
|
@@ -175,17 +176,23 @@ async function importCompile(): Promise<CompileJsonSchema> {
|
|
|
175
176
|
} catch (error) {
|
|
176
177
|
failures.push(`direct import failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
177
178
|
}
|
|
178
|
-
|
|
179
|
-
|
|
179
|
+
// Pi's extension loader imports this compiled file natively, so the lazy import above misses
|
|
180
|
+
// Pi's host-package aliases when TypeBox is installed only in Pi's own tree.
|
|
181
|
+
const envRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || undefined;
|
|
182
|
+
if (!envRoot) failures.push(`${PI_CODING_AGENT_PACKAGE_ROOT_ENV} is not set`);
|
|
183
|
+
const roots = new Map<string, string>();
|
|
184
|
+
for (const [label, root] of [[PI_CODING_AGENT_PACKAGE_ROOT_ENV, envRoot], ["running Pi package root", resolvePiPackageRoot()], ["installed Pi package root", resolveInstalledPiPackageRoot()]] as const) {
|
|
185
|
+
if (root && !roots.has(root)) roots.set(root, label);
|
|
186
|
+
}
|
|
187
|
+
if (roots.size === 0) failures.push("no Pi package root found");
|
|
188
|
+
for (const [root, label] of roots) {
|
|
180
189
|
try {
|
|
181
|
-
const compile = await resolveCompileFromPackageRoot(
|
|
190
|
+
const compile = await resolveCompileFromPackageRoot(root);
|
|
182
191
|
if (compile) return compile;
|
|
183
|
-
failures.push(
|
|
192
|
+
failures.push(`${label} ${root}: typebox/compile did not export a Compile function`);
|
|
184
193
|
} catch (error) {
|
|
185
|
-
failures.push(
|
|
194
|
+
failures.push(`${label} ${root}: ${error instanceof Error ? error.message : String(error)}`);
|
|
186
195
|
}
|
|
187
|
-
} else {
|
|
188
|
-
failures.push(`${PI_CODING_AGENT_PACKAGE_ROOT_ENV} is not set`);
|
|
189
196
|
}
|
|
190
197
|
throw new Error(`Cannot load typebox/compile for structured output validation (${failures.join("; ")})`);
|
|
191
198
|
}
|
|
@@ -227,7 +227,7 @@ export function formatControlNudge(event: ControlEvent): string {
|
|
|
227
227
|
export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string): string {
|
|
228
228
|
const runTarget = event.runId;
|
|
229
229
|
const nudgeMessage = formatControlNudge(event);
|
|
230
|
-
const steerCommand = `subagent({ action: "steer", id: "${runTarget}", ${event.index !== undefined ?
|
|
230
|
+
const steerCommand = `subagent({ action: "steer", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)}${event.index !== undefined ? `, options: { index: ${event.index} }` : ""} })`;
|
|
231
231
|
const nestedResumeCommand = `subagent({ action: "resume", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)} })`;
|
|
232
232
|
const facts = formatLongRunningFacts(event);
|
|
233
233
|
const head = (title: string) => [
|
|
@@ -251,14 +251,14 @@ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTar
|
|
|
251
251
|
}
|
|
252
252
|
|
|
253
253
|
if (event.reason === "tool_open_threshold" && event.currentTool === "bash") {
|
|
254
|
-
const command = (label: string, action: string) => `${label}: subagent(${JSON.stringify({ action, id: runTarget, ...(event.index !== undefined ? { index: event.index } : {}), toolCallId: event.toolCallId })})`;
|
|
254
|
+
const command = (label: string, action: string) => `${label}: subagent(${JSON.stringify({ action, id: runTarget, options: { ...(event.index !== undefined ? { index: event.index } : {}), toolCallId: event.toolCallId } })})`;
|
|
255
255
|
return lines([
|
|
256
256
|
...head("Subagent needs attention"),
|
|
257
257
|
"Hint: Inspect the running command and recent output before nudging. A queued steer does not cancel an in-flight bash call. A dev server or watch command may intentionally never return. Elapsed time alone does not prove the command is stuck.",
|
|
258
258
|
"Recovery: For a local Pi child explicitly granted subagent_command, yield a needed persistent command or cancel the exact incorrect command, then steer the child. Query command.status to confirm the result. If command controls are unavailable, inspect partial changes and interruption scope before interrupt/resume; interrupt is run-scoped and may affect siblings.",
|
|
259
259
|
...(event.toolCallId ? [command("Command", "command.status"), command("Yield", "command.yield"), command("Cancel", "command.cancel")] : []),
|
|
260
260
|
status,
|
|
261
|
-
`Transcript: subagent({ action: "status", id: "${runTarget}", view: "transcript"${event.index !== undefined ? `, index: ${event.index}` : ""} })`,
|
|
261
|
+
`Transcript: subagent({ action: "status", id: "${runTarget}", options: { view: "transcript"${event.index !== undefined ? `, index: ${event.index}` : ""} } })`,
|
|
262
262
|
]);
|
|
263
263
|
}
|
|
264
264
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
-
import type { BeforeProviderRequestEvent, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import type { BeforeAgentStartEvent, BeforeProviderRequestEvent, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { registerNativeSupervisorClient } from "../../intercom/native-supervisor-channel.ts";
|
|
6
6
|
import { permissionDecision } from "./permissions.ts";
|
|
7
7
|
import type { SteerRequest } from "../background/control-channel.ts";
|
|
@@ -198,16 +198,16 @@ export function stripSubagentOrchestrationSkill(prompt: string): string {
|
|
|
198
198
|
|
|
199
199
|
function stripChildBoundaryInstructions(prompt: string): string {
|
|
200
200
|
let rewritten = prompt;
|
|
201
|
-
for (const
|
|
202
|
-
rewritten = rewritten.split(
|
|
201
|
+
for (const instructions of [CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS, CHILD_FANOUT_BOUNDARY_INSTRUCTIONS, STRUCTURED_OUTPUT_INSTRUCTIONS]) {
|
|
202
|
+
rewritten = rewritten.split(`\n\n${instructions}`).join("").split(instructions).join("");
|
|
203
203
|
}
|
|
204
204
|
return rewritten.replace(/^(?:[ \t]*\r?\n)+/, "");
|
|
205
205
|
}
|
|
206
206
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
): string {
|
|
207
|
+
type InheritedPromptOptions = { inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean };
|
|
208
|
+
type ChildBoundaryOptions = { fanoutChild?: boolean; structuredOutput?: boolean };
|
|
209
|
+
|
|
210
|
+
function stripInheritedPromptText(prompt: string, options: InheritedPromptOptions): string {
|
|
211
211
|
let rewritten = prompt;
|
|
212
212
|
if (!options.inheritProjectContext) {
|
|
213
213
|
rewritten = stripProjectContext(rewritten);
|
|
@@ -218,11 +218,41 @@ export function rewriteSubagentPrompt(
|
|
|
218
218
|
if (!options.inheritSkills) {
|
|
219
219
|
rewritten = stripInheritedSkills(rewritten);
|
|
220
220
|
}
|
|
221
|
-
|
|
222
|
-
|
|
221
|
+
return stripChildBoundaryInstructions(stripSubagentOrchestrationSkill(rewritten));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function appendChildBoundary(prompt: string, options: ChildBoundaryOptions): string {
|
|
223
225
|
const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;
|
|
224
226
|
const structured = options.structuredOutput ? `\n\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : "";
|
|
225
|
-
|
|
227
|
+
// Pi's base prompt stays first so providers that recognize it by its opening still do.
|
|
228
|
+
return `${stripChildBoundaryInstructions(prompt)}\n\n${boundary}${structured}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function rewriteSubagentPrompt(prompt: string, options: InheritedPromptOptions & ChildBoundaryOptions): string {
|
|
232
|
+
return appendChildBoundary(stripInheritedPromptText(prompt, options), options);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** In place, so later handlers and the final render never see the removed context. */
|
|
236
|
+
function filterChildPromptOptions(options: BeforeAgentStartEvent["systemPromptOptions"], inherited: InheritedPromptOptions): void {
|
|
237
|
+
if (!inherited.inheritProjectContext) options.contextFiles = [];
|
|
238
|
+
else if (!inherited.inheritGlobalContext) options.contextFiles = options.contextFiles.filter((file) => !isGlobalContextFile(file.path));
|
|
239
|
+
options.skills = inherited.inheritSkills ? options.skills.filter((skill) => skill.name !== "pi-subagents") : [];
|
|
240
|
+
// Role prompts can embed context, skill catalogs, or an earlier child's boundary as text.
|
|
241
|
+
if (options.customPrompt) options.customPrompt = stripInheritedPromptText(options.customPrompt, inherited);
|
|
242
|
+
if (options.appendSystemPrompt) options.appendSystemPrompt = stripInheritedPromptText(options.appendSystemPrompt, inherited);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function rewritesChildPrompt(config: ChildRuntimeConfig): boolean {
|
|
246
|
+
return config.inheritProjectContext !== undefined || config.inheritGlobalContext !== undefined || config.inheritSkills !== undefined || Boolean(config.fanoutChild);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Installed after every other extension: a returned prompt freezes out sections added after it. */
|
|
250
|
+
export function registerSubagentPromptBoundary(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
251
|
+
if (!rewritesChildPrompt(config)) return;
|
|
252
|
+
pi.on("before_agent_start", (event) => {
|
|
253
|
+
const finalized = appendChildBoundary(event.systemPrompt, { fanoutChild: config.fanoutChild, structuredOutput: Boolean(config.structuredOutput) });
|
|
254
|
+
return finalized === event.systemPrompt ? undefined : { systemPrompt: finalized };
|
|
255
|
+
});
|
|
226
256
|
}
|
|
227
257
|
|
|
228
258
|
function isParentOnlySubagentMessage(message: unknown): boolean {
|
|
@@ -557,19 +587,12 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
|
|
|
557
587
|
pi.setSessionName(childSessionName);
|
|
558
588
|
}
|
|
559
589
|
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
inheritSkills: inheritSkills ?? true,
|
|
568
|
-
fanoutChild,
|
|
569
|
-
structuredOutput: Boolean(config.structuredOutput),
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
if (rewritten === event.systemPrompt) return;
|
|
573
|
-
return { systemPrompt: rewritten };
|
|
590
|
+
// Filter the inputs instead of returning a prompt; the boundary hook appends the boundary last.
|
|
591
|
+
if (!rewritesChildPrompt(config)) return;
|
|
592
|
+
filterChildPromptOptions((event as BeforeAgentStartEvent).systemPromptOptions, {
|
|
593
|
+
inheritProjectContext: config.inheritProjectContext ?? true,
|
|
594
|
+
inheritGlobalContext: config.inheritGlobalContext ?? true,
|
|
595
|
+
inheritSkills: config.inheritSkills ?? true,
|
|
596
|
+
});
|
|
574
597
|
});
|
|
575
598
|
}
|
|
@@ -13,6 +13,6 @@ export function workflowAsyncChildSteeringGuidance(status: AsyncStatus, state?:
|
|
|
13
13
|
if (ids.size === 0) return [];
|
|
14
14
|
return [
|
|
15
15
|
"Async children recorded as running; direct steering rechecks controls. Choose an exact child ID (queued does not mean consumed):",
|
|
16
|
-
...[...ids].map((id) => ` subagent({ action: "steer", id: "${id}",
|
|
16
|
+
...[...ids].map((id) => ` subagent({ action: "steer", id: "${id}", message: "...", options: { mode: "follow_up" } })`),
|
|
17
17
|
];
|
|
18
18
|
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
|
|
6
|
+
import { readParallelHandoffManifest } from "./parallel-handoff.ts";
|
|
7
|
+
import { buildWorktreeCleanupPlan, isRegisteredCleanupWorktree, resolveCleanupRepoRoot, samePath, worktreeCleanupContentPayload, worktreeCleanupPlanPath, WORKTREE_CLEANUP_PLAN_TTL_MS, type BuildWorktreeCleanupPlanInput, type WorktreeCleanupPlan, type WorktreeCleanupPlanEntry } from "./worktree-cleanup-plan.ts";
|
|
8
|
+
import { withHandoffWriteLock, withRepositoryWorktreeLock } from "./worktree-lock.ts";
|
|
9
|
+
import { withWorktreeTransaction } from "./worktree.ts";
|
|
10
|
+
|
|
11
|
+
export type CleanupReceipt = {
|
|
12
|
+
version: 1; planId: string; repoRoot: string; contentHash: string;
|
|
13
|
+
state: "applying" | "complete" | "partial";
|
|
14
|
+
startedAt: number; completedAt?: number; error?: string;
|
|
15
|
+
entries: Array<{ path: string; branch: string; state: "removing" | "removed" | "kept" | "failed"; reason: string }>;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function assertContainedRealPath(repoRoot: string, candidate: string, create = false): void {
|
|
19
|
+
const relative = path.relative(repoRoot, candidate);
|
|
20
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error("Cleanup evidence must be inside the selected repository.");
|
|
21
|
+
let current = repoRoot;
|
|
22
|
+
for (const segment of relative.split(path.sep)) {
|
|
23
|
+
current = path.join(current, segment);
|
|
24
|
+
if (!fs.existsSync(current) && create) fs.mkdirSync(current, { mode: 0o700 });
|
|
25
|
+
const stat = fs.lstatSync(current);
|
|
26
|
+
if (stat.isSymbolicLink()) throw new Error(`Cleanup evidence cannot use a symlink: ${current}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function loadReviewedCleanupPlan(repo: string, planId: string, now = Date.now()): WorktreeCleanupPlan {
|
|
31
|
+
const repoRoot = resolveCleanupRepoRoot(repo);
|
|
32
|
+
const file = worktreeCleanupPlanPath(repoRoot, planId);
|
|
33
|
+
assertContainedRealPath(repoRoot, file);
|
|
34
|
+
const stat = fs.statSync(file);
|
|
35
|
+
if (!stat.isFile() || stat.size > 2 * 1024 * 1024) throw new Error("Cleanup plan is not a bounded regular file.");
|
|
36
|
+
const plan = JSON.parse(fs.readFileSync(file, "utf-8")) as WorktreeCleanupPlan;
|
|
37
|
+
if (plan.version !== 1 || plan.planId !== planId || plan.repoRoot !== repoRoot || !Number.isFinite(plan.createdAt) || !Number.isFinite(plan.expiresAt) || plan.createdAt > now || (plan.expiresAt <= now && !fs.existsSync(file.replace(/\.json$/, ".claim"))) || plan.expiresAt - plan.createdAt !== WORKTREE_CLEANUP_PLAN_TTL_MS) throw new Error("Cleanup plan is invalid, expired, or belongs to another repository.");
|
|
38
|
+
if (!Array.isArray(plan.entries) || plan.entries.length > 512 || !Array.isArray(plan.baseDirs) || plan.baseDirs.length !== 1 || !plan.baseDirs.every((item) => typeof item === "string" && path.isAbsolute(item)) || !Array.isArray(plan.metadataPaths) || !plan.metadataPaths.every((item) => typeof item === "string" && path.isAbsolute(item)) || !Array.isArray(plan.pruneCandidates)) throw new Error("Cleanup plan has invalid inventory fields.");
|
|
39
|
+
const paths = new Set<string>();
|
|
40
|
+
for (const entry of plan.entries) {
|
|
41
|
+
if (!entry || typeof entry.path !== "string" || !path.isAbsolute(entry.path) || typeof entry.branch !== "string" || !["remove", "keep", "unknown"].includes(entry.decision) || !entry.preconditions || entry.preconditions.path !== entry.path || entry.preconditions.branch !== entry.branch || !Array.isArray(entry.reasons) || !entry.reasons.every((reason) => typeof reason === "string") || paths.has(entry.path)) throw new Error("Cleanup plan has invalid or duplicate entries.");
|
|
42
|
+
paths.add(entry.path);
|
|
43
|
+
}
|
|
44
|
+
const hash = createHash("sha256").update(JSON.stringify(worktreeCleanupContentPayload(plan))).digest("hex");
|
|
45
|
+
if (plan.contentHash !== hash) throw new Error("Cleanup plan content hash does not match; create and review a fresh plan.");
|
|
46
|
+
return plan;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function recordRemoval(entry: WorktreeCleanupPlanEntry): void {
|
|
50
|
+
const manifest = readParallelHandoffManifest(entry.handoffPath!);
|
|
51
|
+
if (!manifest || manifest.runId !== entry.runId) throw new Error("Handoff ownership changed before recording removal.");
|
|
52
|
+
const tasks = manifest.groups.flatMap((group) => group.cleanup.tasks).filter((task) => task.index === entry.taskIndex && samePath(path.resolve(path.dirname(entry.handoffPath!), task.path), entry.path) && task.branch === entry.branch);
|
|
53
|
+
if (tasks.length !== 1) throw new Error("Handoff task no longer identifies exactly one removed worktree.");
|
|
54
|
+
if (tasks[0]!.worktreeRemoved) return;
|
|
55
|
+
tasks[0]!.worktreeRemoved = true;
|
|
56
|
+
tasks[0]!.branchRemoved = false;
|
|
57
|
+
tasks[0]!.preserved = true;
|
|
58
|
+
tasks[0]!.reason = "reviewed cleanup removed worktree; local branch retained";
|
|
59
|
+
manifest.updatedAt = Date.now();
|
|
60
|
+
writePrivateAtomicJson(entry.handoffPath!, manifest);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function applyReviewedCleanupPlan(input: {
|
|
64
|
+
repo: string; planId: string; authorized: boolean; signal?: AbortSignal;
|
|
65
|
+
foregroundRunOwnership?: BuildWorktreeCleanupPlanInput["foregroundRunOwnership"];
|
|
66
|
+
/** Internal retention seam: shrink the reviewed batch while holding the repository lock. */
|
|
67
|
+
select?: (plan: WorktreeCleanupPlan) => Set<string>;
|
|
68
|
+
}): Promise<{ receipt: CleanupReceipt; receiptPath: string; reused: boolean }> {
|
|
69
|
+
if (!input.authorized) throw new Error("Worktree cleanup requires discardWorktree authorization.");
|
|
70
|
+
return withWorktreeTransaction(() => withRepositoryWorktreeLock(input.repo, async () => {
|
|
71
|
+
const plan = loadReviewedCleanupPlan(input.repo, input.planId);
|
|
72
|
+
const claimPath = worktreeCleanupPlanPath(plan.repoRoot, plan.planId).replace(/\.json$/, ".claim");
|
|
73
|
+
const receiptPath = path.join(claimPath, "receipt.json");
|
|
74
|
+
assertContainedRealPath(plan.repoRoot, path.dirname(claimPath));
|
|
75
|
+
try { fs.mkdirSync(claimPath, { mode: 0o700 }); }
|
|
76
|
+
catch (error) {
|
|
77
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
78
|
+
assertContainedRealPath(plan.repoRoot, receiptPath);
|
|
79
|
+
// A claimed plan is never destructively replayed, even after interruption.
|
|
80
|
+
const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf-8")) as CleanupReceipt;
|
|
81
|
+
if (receipt.version !== 1 || receipt.planId !== plan.planId || receipt.repoRoot !== plan.repoRoot || receipt.contentHash !== plan.contentHash || !Array.isArray(receipt.entries) || !["applying", "complete", "partial"].includes(receipt.state)) throw new Error("Claimed cleanup plan has an invalid receipt; inspect it before creating a fresh plan.");
|
|
82
|
+
// Reconcile only a journaled attempt whose directory and Git registration
|
|
83
|
+
// are both gone. A recreated path is never changed or removed on replay.
|
|
84
|
+
for (const entry of plan.entries.filter((entry) => receipt.state !== "complete" && entry.decision === "remove" && receipt.entries.some((item) => (item?.state === "removing" || item?.state === "removed") && item.path === entry.path && item.branch === entry.branch))) {
|
|
85
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
86
|
+
input.signal?.throwIfAborted();
|
|
87
|
+
try { fs.lstatSync(entry.path); continue; }
|
|
88
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
89
|
+
if (!isRegisteredCleanupWorktree(plan.repoRoot, entry.path) && entry.handoffPath) {
|
|
90
|
+
const item = receipt.entries.find((item) => item.path === entry.path && item.branch === entry.branch)!;
|
|
91
|
+
if (item.state === "removing") {
|
|
92
|
+
item.state = "removed";
|
|
93
|
+
item.reason = "interrupted removal reconciled; local branch retained";
|
|
94
|
+
writePrivateAtomicJson(receiptPath, receipt);
|
|
95
|
+
}
|
|
96
|
+
withHandoffWriteLock(entry.handoffPath, () => recordRemoval(entry));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { receipt, receiptPath, reused: true };
|
|
100
|
+
}
|
|
101
|
+
const receipt: CleanupReceipt = { version: 1, planId: plan.planId, repoRoot: plan.repoRoot, contentHash: plan.contentHash, state: "applying", startedAt: Date.now(), entries: [] };
|
|
102
|
+
writePrivateAtomicJson(receiptPath, receipt);
|
|
103
|
+
try {
|
|
104
|
+
const selected = input.select?.(plan);
|
|
105
|
+
for (const entry of plan.entries.filter((item) => item.decision === "remove")) {
|
|
106
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
107
|
+
input.signal?.throwIfAborted();
|
|
108
|
+
if (selected && !selected.has(entry.path)) {
|
|
109
|
+
receipt.entries.push({ path: entry.path, branch: entry.branch, state: "kept", reason: "outside the current retention excess" });
|
|
110
|
+
} else {
|
|
111
|
+
try {
|
|
112
|
+
if (!entry.handoffPath) throw new Error("Reviewed entry has no handoff ownership.");
|
|
113
|
+
withHandoffWriteLock(entry.handoffPath, () => {
|
|
114
|
+
const manifest = readParallelHandoffManifest(entry.handoffPath!);
|
|
115
|
+
if (!manifest || manifest.runId !== entry.runId) throw new Error("Handoff ownership changed before cleanup validation.");
|
|
116
|
+
const fresh = buildWorktreeCleanupPlan({ repo: plan.repoRoot, candidatePaths: [entry.path], handoffPaths: plan.metadataPaths, worktreeBaseDir: path.dirname(plan.baseDirs[0]!), foregroundRunOwnership: input.foregroundRunOwnership });
|
|
117
|
+
const candidate = fresh.entries.find((item) => item.path === entry.path);
|
|
118
|
+
if (fresh.warnings?.some((warning) => /capped|failed to inspect/.test(warning)) || !candidate || candidate.decision !== "remove" || candidate.handoffPath !== entry.handoffPath || candidate.runId !== entry.runId || candidate.taskIndex !== entry.taskIndex || candidate.patchPath !== entry.patchPath || JSON.stringify(candidate.preconditions) !== JSON.stringify(entry.preconditions)) {
|
|
119
|
+
receipt.entries.push({ path: entry.path, branch: entry.branch, state: "kept", reason: candidate?.reasons.join("; ") || "reviewed ownership or Git facts changed" });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
input.signal?.throwIfAborted();
|
|
123
|
+
const journalEntry: CleanupReceipt["entries"][number] = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
|
|
124
|
+
receipt.entries.push(journalEntry);
|
|
125
|
+
writePrivateAtomicJson(receiptPath, receipt); // Admit the attempt before Git can remove anything.
|
|
126
|
+
const removed = spawnSync("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
|
|
127
|
+
if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
|
|
128
|
+
journalEntry.state = "removed";
|
|
129
|
+
journalEntry.reason = "worktree removed; local branch retained";
|
|
130
|
+
writePrivateAtomicJson(receiptPath, receipt); // Evidence precedes secondary manifest bookkeeping.
|
|
131
|
+
recordRemoval(entry);
|
|
132
|
+
});
|
|
133
|
+
} catch (error) {
|
|
134
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
135
|
+
const removed = receipt.entries.find((item) => item.path === entry.path && item.state === "removed");
|
|
136
|
+
if (removed) { removed.reason += `; removal bookkeeping failed: ${reason}`; receipt.error = reason; }
|
|
137
|
+
else {
|
|
138
|
+
const pending = receipt.entries.find((item) => item.path === entry.path && item.state === "removing");
|
|
139
|
+
if (pending) { pending.reason += `; operation failed: ${reason}`; receipt.error = reason; }
|
|
140
|
+
else receipt.entries.push({ path: entry.path, branch: entry.branch, state: "failed", reason });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
writePrivateAtomicJson(receiptPath, receipt);
|
|
145
|
+
}
|
|
146
|
+
receipt.state = !receipt.error && receipt.entries.every((entry) => entry.state === "removed") ? "complete" : "partial";
|
|
147
|
+
} catch (error) {
|
|
148
|
+
receipt.state = "partial";
|
|
149
|
+
receipt.error = error instanceof Error ? error.message : String(error);
|
|
150
|
+
}
|
|
151
|
+
receipt.completedAt = Date.now();
|
|
152
|
+
writePrivateAtomicJson(receiptPath, receipt);
|
|
153
|
+
return { receipt, receiptPath, reused: false };
|
|
154
|
+
}, { signal: input.signal }));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function formatCleanupReceipt(result: { receipt: CleanupReceipt; receiptPath: string; reused: boolean }): string {
|
|
158
|
+
const { receipt } = result;
|
|
159
|
+
return [`Worktree cleanup ${receipt.planId}: ${receipt.state}${result.reused ? " (previous receipt; plan not replayed)" : ""}`, "Local branches retained.", ...receipt.entries.map((entry) => `- ${entry.path}: ${entry.state}; ${entry.reason}`), ...(receipt.error ? [receipt.error] : []), `Receipt: ${result.receiptPath}`].join("\n");
|
|
160
|
+
}
|