pi-better-server 0.6.0 → 0.7.1

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.
Files changed (142) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -0,0 +1,551 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import {
4
+ closeSync,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ mkdtempSync,
9
+ openSync,
10
+ readFileSync,
11
+ readdirSync,
12
+ realpathSync,
13
+ renameSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
18
+ import { inspectGitWorkspace, isIgnoredGitSubdirectory, syncGitRemotes } from "./git-workspace.ts";
19
+ import { restoreTree, snapshotTree, verifyTree, type SavedEntry } from "./workspace-files.ts";
20
+ import { durableSubagentRoot } from "./session-store.ts";
21
+ import { taskWorkspaceDir } from "./registry.ts";
22
+
23
+ export type WorkspaceMode = "clone" | "worktree";
24
+ export interface IsolatedWorkspace {
25
+ owner: string;
26
+ root: string;
27
+ mode: WorkspaceMode;
28
+ source: string;
29
+ base: string;
30
+ subdir: string;
31
+ }
32
+
33
+ // Every mutating git command uses an argv array. Restoring a checkout cannot run a post-checkout hook.
34
+ function git(cwd: string, args: string[], input?: number): Buffer {
35
+ return execFileSync("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", ...args], {
36
+ cwd,
37
+ maxBuffer: 64 * 1024 * 1024,
38
+ stdio: [input ?? "pipe", "pipe", "pipe"],
39
+ env: {
40
+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
41
+ GIT_TERMINAL_PROMPT: "0",
42
+ GIT_OPTIONAL_LOCKS: "0",
43
+ GIT_NO_LAZY_FETCH: "1",
44
+ },
45
+ });
46
+ }
47
+ const value = (cwd: string, args: string[]) => git(cwd, args).toString().trim();
48
+ const recoveryRoot = () => join(durableSubagentRoot(), "workspaces");
49
+ function paths(w: IsolatedWorkspace) {
50
+ const currentRoot = taskWorkspaceDir(w.owner);
51
+ const record = join(recoveryRoot(), w.owner);
52
+ const root = w.root ?? currentRoot;
53
+ if (
54
+ !isAbsolute(root) ||
55
+ root !== resolve(root) ||
56
+ basename(root) !== w.owner ||
57
+ basename(dirname(root)) !== "pi-better-subagent-workspaces"
58
+ )
59
+ throw new Error("Invalid owned workspace location");
60
+ if (root !== currentRoot && readFileSync(join(record, "root"), "utf8") !== root)
61
+ throw new Error("Recorded workspace location changed");
62
+ if (resolve(root, w.subdir) !== root && !resolve(root, w.subdir).startsWith(root + sep))
63
+ throw new Error("Invalid workspace subdirectory");
64
+ return { root, record, store: join(recoveryRoot(), "blobs") };
65
+ }
66
+
67
+ export function workspaceChoice(
68
+ source: string,
69
+ owner: string,
70
+ mode: WorkspaceMode,
71
+ tools: string,
72
+ exclude: string,
73
+ ): IsolatedWorkspace | undefined {
74
+ const disabled = new Set(exclude.split(",").map((s) => s.trim()));
75
+ if (
76
+ !tools
77
+ .split(",")
78
+ .some((t) => ["write", "edit", "apply_patch", "multi_edit"].includes(t.trim()) && !disabled.has(t.trim()))
79
+ )
80
+ return;
81
+ if (!existsSync(source)) return; // The normal launcher reports a missing cwd.
82
+ let ancestor = realpathSync(source);
83
+ while (!existsSync(join(ancestor, ".git"))) {
84
+ const parent = dirname(ancestor);
85
+ if (ancestor === parent) return;
86
+ ancestor = parent;
87
+ }
88
+ let info;
89
+ try {
90
+ info = inspectGitWorkspace(source);
91
+ } catch (error) {
92
+ if (String(error).includes("not a git repository")) return;
93
+ throw error;
94
+ }
95
+ const subdir = relative(info.repoRoot, realpathSync(source));
96
+ if (isIgnoredGitSubdirectory(info.repoRoot, subdir)) return;
97
+ let base: string;
98
+ try {
99
+ base = value(source, ["rev-parse", "--verify", "HEAD"]);
100
+ } catch {
101
+ throw new Error(
102
+ "An isolated Git workspace requires a base commit. Commit the initial files or use isolation:false at " +
103
+ source,
104
+ );
105
+ }
106
+ return { owner, root: taskWorkspaceDir(owner), mode, source: info.repoRoot, subdir, base };
107
+ }
108
+
109
+ function addLinked(source: string, root: string, commit: string): void {
110
+ git(source, ["worktree", "add", "--detach", root, commit]);
111
+ }
112
+ export function createIsolatedWorkspace(w: IsolatedWorkspace, reserved = false): string {
113
+ const { root } = paths(w);
114
+ mkdirSync(dirname(root), { recursive: true });
115
+ if (!reserved && existsSync(root)) throw new Error("Isolated workspace already exists: " + root);
116
+ if (w.mode === "worktree") addLinked(w.source, root, w.base);
117
+ else {
118
+ // Local source preserves unpublished commits and works offline. Separate objects protect the source from worker writes.
119
+ git(w.source, ["clone", "--local", "--no-hardlinks", "--no-checkout", "--", w.source, root]);
120
+ git(root, ["checkout", "--detach", w.base]);
121
+ syncGitRemotes(w.source, root);
122
+ for (const key of ["user.name", "user.email", "user.signingkey"]) {
123
+ let setting;
124
+ try {
125
+ setting = value(w.source, ["config", "--local", "--get", key]);
126
+ } catch {
127
+ continue;
128
+ }
129
+ git(root, ["config", "--local", key, setting]);
130
+ }
131
+ }
132
+ const cwd = join(root, w.subdir);
133
+ if (!existsSync(cwd))
134
+ throw new Error(
135
+ "Directory is missing from the selected Git commit. Use isolation:false for uncommitted inputs at " +
136
+ join(w.source, w.subdir),
137
+ );
138
+ if (!realpathSync(cwd).startsWith(realpathSync(root) + sep) && realpathSync(cwd) !== realpathSync(root))
139
+ throw new Error("Invalid workspace directory: " + cwd);
140
+ return cwd;
141
+ }
142
+
143
+ // Move the intact checkout out of the canonical path before recursively removing it.
144
+ // After a crash, admission and cleanup finish the same registered move and can restore
145
+ // the verified copy without ever mistaking half a checkout for a live workspace.
146
+ function finishRetirement(w: IsolatedWorkspace) {
147
+ const retired = paths(w).root + "-retired";
148
+ if (!existsSync(retired)) return;
149
+ if (w.mode === "worktree") git(w.source, ["worktree", "remove", "--force", retired]);
150
+ else rmSync(retired, { recursive: true, force: true });
151
+ }
152
+
153
+ function removeOwned(w: IsolatedWorkspace): void {
154
+ const { root } = paths(w);
155
+ finishRetirement(w);
156
+ if (!existsSync(root)) return;
157
+ if (w.mode === "worktree") git(w.source, ["worktree", "move", root, root + "-retired"]);
158
+ else renameSync(root, root + "-retired");
159
+ finishRetirement(w);
160
+ }
161
+
162
+ export function discardWorkspace(w: IsolatedWorkspace): void {
163
+ if (w.mode === "worktree" && existsSync(join(paths(w).root, ".git")))
164
+ git(w.source, ["worktree", "remove", "--force", paths(w).root]);
165
+ else rmSync(paths(w).root, { recursive: true, force: true });
166
+ }
167
+
168
+ interface Checkpoint {
169
+ workspace: IsolatedWorkspace;
170
+ files: SavedEntry[];
171
+ git: SavedEntry[];
172
+ // Per-worktree HEAD, index, logs and operation state are distinct from the shared object store.
173
+ privateGit?: SavedEntry[];
174
+ head: string;
175
+ branch: string;
176
+ }
177
+
178
+ const withoutGit = new Set([".git"]);
179
+ const worktreePointers = new Set(["commondir", "gitdir"]);
180
+ const sharedGitEntries = new Set(["config", "objects", "packed-refs", "refs", "logs", "info", "shallow", "hooks"]);
181
+ const pendingOperation = [
182
+ "rebase-merge",
183
+ "rebase-apply",
184
+ "MERGE_HEAD",
185
+ "CHERRY_PICK_HEAD",
186
+ "REVERT_HEAD",
187
+ "sequencer",
188
+ ];
189
+
190
+ function atomicText(path: string, content: string): void {
191
+ const tmp = path + "-" + randomUUID();
192
+ try {
193
+ writeFileSync(tmp, content, { mode: 0o600 });
194
+ renameSync(tmp, path);
195
+ } finally {
196
+ rmSync(tmp, { force: true });
197
+ }
198
+ }
199
+
200
+ function attemptFile(record: string, id: string): string {
201
+ if (!/^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id)) throw new Error("Invalid workspace attempt");
202
+ return join(record, "attempt-" + id);
203
+ }
204
+
205
+ function checkpointDir(w: IsolatedWorkspace, attempt?: string): string {
206
+ const { record } = paths(w);
207
+ const generation = readFileSync(attempt ? attemptFile(record, attempt) : join(record, "current"), "utf8");
208
+ if (!/^save-[a-zA-Z0-9]+$/.test(generation)) throw new Error("Invalid workspace checkpoint");
209
+ return join(record, generation);
210
+ }
211
+
212
+ function readCheckpoint(w: IsolatedWorkspace, attempt?: string): { dir: string; cp: Checkpoint } {
213
+ const dir = checkpointDir(w, attempt);
214
+ const cp = JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8")) as Checkpoint;
215
+ if (cp.workspace.owner !== w.owner || cp.workspace.source !== w.source || cp.workspace.base !== w.base)
216
+ throw new Error("Workspace checkpoint identity changed");
217
+ return { dir, cp };
218
+ }
219
+
220
+ export function hasWorkspaceCheckpoint(w: IsolatedWorkspace): boolean {
221
+ try {
222
+ readCheckpoint(w);
223
+ return true;
224
+ } catch {
225
+ return false;
226
+ }
227
+ }
228
+
229
+ function currentWorkspace(w: IsolatedWorkspace): IsolatedWorkspace {
230
+ const { root, record } = paths(w);
231
+ if (!existsSync(join(record, "handoff"))) return w;
232
+ readCheckpoint(w);
233
+ // The marker precedes removal. A crash can leave the verified original in place.
234
+ if (existsSync(root) && lstatSync(join(root, ".git")).isFile()) return { ...w, mode: "worktree" };
235
+ return { ...w, mode: "clone" };
236
+ }
237
+
238
+ function inspectOwned(w: IsolatedWorkspace) {
239
+ const { root } = paths(w);
240
+ const info = inspectGitWorkspace(root);
241
+ if (lstatSync(root).isSymbolicLink() || info.repoRoot !== root || info.isLinkedWorktree !== (w.mode === "worktree"))
242
+ throw new Error("Workspace ownership changed at " + root);
243
+ if (w.mode === "clone" && (info.gitDir !== join(root, ".git") || info.commonGitDir !== info.gitDir))
244
+ throw new Error("Clone metadata moved outside " + root);
245
+ if (
246
+ w.mode === "worktree" &&
247
+ (info.commonGitDir !== inspectGitWorkspace(w.source).commonGitDir ||
248
+ !info.gitDir.startsWith(join(info.commonGitDir, "worktrees") + sep) ||
249
+ realpathSync(readFileSync(join(info.gitDir, "gitdir"), "utf8").trim()) !== join(root, ".git"))
250
+ )
251
+ throw new Error("Worktree registration changed at " + root);
252
+ return info;
253
+ }
254
+
255
+ function materializeClone(target: string, cp: Checkpoint, store: string): void {
256
+ restoreTree(target, store, cp.files);
257
+ verifyTree(target, cp.files);
258
+ const gitDir = join(target, ".git");
259
+ if (cp.privateGit) {
260
+ // The linked checkout has its own HEAD and index. Prefer its per-worktree
261
+ // records over similarly named entries in the main worktree.
262
+ const merged = new Map(cp.git.map((entry) => [entry.name, entry]));
263
+ for (const entry of cp.privateGit) merged.set(entry.name, entry);
264
+ const entries = [...merged.values()].sort((a, b) => Buffer.compare(Buffer.from(a.name), Buffer.from(b.name)));
265
+ restoreTree(gitDir, store, entries);
266
+ // verifyTree compares depth-first order. Verify the two inventories by name.
267
+ const actual = snapshotTree(gitDir).sort((a, b) => Buffer.compare(Buffer.from(a.name), Buffer.from(b.name)));
268
+ if (JSON.stringify(actual) !== JSON.stringify(entries))
269
+ throw new Error("Recovered Git metadata failed verification");
270
+ // A linked checkout may belong to a bare parent. The exported checkout owns its new working directory.
271
+ git(target, ["config", "--file", join(gitDir, "config"), "core.bare", "false"]);
272
+ } else {
273
+ restoreTree(gitDir, store, cp.git);
274
+ verifyTree(gitDir, cp.git);
275
+ }
276
+ const info = inspectGitWorkspace(target);
277
+ if (info.repoRoot !== realpathSync(target) || info.gitDir !== realpathSync(gitDir))
278
+ throw new Error("Recovered checkout refers to external Git metadata");
279
+ }
280
+
281
+ function checkIndependentHistory(proof: string, head: string, packPath?: string): void {
282
+ // Only inspect Git's object graph. Repository config, hooks and global config
283
+ // are not inputs to verification and must not run helpers on the worker's behalf.
284
+ const config = join(proof, ".git", "config"),
285
+ original = join(dirname(proof), "verification-config");
286
+ renameSync(config, original);
287
+ try {
288
+ const format =
289
+ head.length === 64
290
+ ? "[core]\nrepositoryformatversion=1\n[extensions]\nobjectformat=sha256\n"
291
+ : "[core]\nrepositoryformatversion=0\n";
292
+ writeFileSync(config, format, { mode: 0o600 });
293
+ const args = ["--git-dir", join(proof, ".git"), "--work-tree", proof];
294
+ const options = {
295
+ cwd: proof,
296
+ stdio: ["ignore", "pipe", "pipe"] as ["ignore", "pipe", "pipe"],
297
+ env: {
298
+ PATH: process.env.PATH,
299
+ GIT_CONFIG_NOSYSTEM: "1",
300
+ GIT_CONFIG_GLOBAL: "/dev/null",
301
+ GIT_NO_LAZY_FETCH: "1",
302
+ GIT_ALLOW_PROTOCOL: "",
303
+ GIT_NO_REPLACE_OBJECTS: "1",
304
+ },
305
+ };
306
+ if (
307
+ execFileSync("git", [...args, "rev-parse", "HEAD"], options)
308
+ .toString()
309
+ .trim() !== head
310
+ )
311
+ throw new Error("Saved HEAD failed verification");
312
+ execFileSync(
313
+ "git",
314
+ [...args, "fsck", "--cache", "--connectivity-only", "--no-dangling", "--no-reflogs", head],
315
+ options,
316
+ );
317
+ if (packPath) {
318
+ const output = openSync(packPath, "wx", 0o600);
319
+ try {
320
+ execFileSync("git", [...args, "pack-objects", "--stdout", "--revs", "--indexed-objects"], {
321
+ ...options, input: head + "\n", stdio: ["pipe", output, "pipe"],
322
+ });
323
+ } finally {
324
+ closeSync(output);
325
+ }
326
+ }
327
+ } finally {
328
+ renameSync(original, config);
329
+ }
330
+ }
331
+
332
+ function discardUnpublishedGenerations(record: string): void {
333
+ const names = readdirSync(record);
334
+ const referenced = new Set(
335
+ names
336
+ .filter((name) => name === "current" || /^attempt-sa_[a-z0-9]+_[a-z0-9]+$/i.test(name))
337
+ .map((name) => readFileSync(join(record, name), "utf8")),
338
+ );
339
+ for (const name of names)
340
+ if (/^save-[a-zA-Z0-9]+$/.test(name) && !referenced.has(name))
341
+ rmSync(join(record, name), { recursive: true, force: true });
342
+ }
343
+
344
+ function checkpoint(w: IsolatedWorkspace, attempt: string) {
345
+ const { root, record, store } = paths(w);
346
+ const info = inspectOwned(w);
347
+ const linked = w.mode === "worktree";
348
+ const indexLock = join(info.gitDir, "index.lock");
349
+ if (existsSync(indexLock)) {
350
+ throw new Error(`Git index lock blocks workspace recovery at ${indexLock}. Original checkout retained at ${root}.`);
351
+ }
352
+ if (
353
+ pendingOperation.some((name) => existsSync(join(info.gitDir, name))) ||
354
+ existsSync(join(info.commonGitDir, "objects/info/alternates")) ||
355
+ (existsSync(join(info.commonGitDir, "worktrees")) && !linked)
356
+ ) {
357
+ throw new Error("Git operation or dependent checkout requires the original checkout retained at " + root);
358
+ }
359
+ const head = value(root, ["rev-parse", "--verify", "HEAD"]);
360
+ const branch = value(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
361
+ const files = snapshotTree(root, store, withoutGit);
362
+ if (files.some((e) => e.name.endsWith("/.git") && e.type !== "directory"))
363
+ throw new Error("Nested worktree requires retaining " + root);
364
+ // Never archive another checkout's index, HEAD, in-progress operation, or registration.
365
+ const commonGit = linked
366
+ ? new Set([...readdirSync(info.commonGitDir).filter((name) => !sharedGitEntries.has(name)), "logs/HEAD"])
367
+ : undefined;
368
+ const cp: Checkpoint = {
369
+ workspace: w,
370
+ head,
371
+ branch: branch === "HEAD" ? "" : branch,
372
+ files,
373
+ git: snapshotTree(info.commonGitDir, store, commonGit),
374
+ };
375
+ if (cp.git.some((e) => e.type === "symlink")) throw new Error("External Git storage requires retaining " + root);
376
+ if (linked) cp.privateGit = snapshotTree(info.gitDir, store, worktreePointers);
377
+ if (cp.privateGit?.some((e) => e.type === "symlink"))
378
+ throw new Error("External worktree metadata requires retaining " + root);
379
+ mkdirSync(record, { recursive: true, mode: 0o700 });
380
+ atomicText(join(record, "root"), root);
381
+ discardUnpublishedGenerations(record);
382
+ const dir = mkdtempSync(join(record, "save-")),
383
+ proof = join(dir, "proof");
384
+ try {
385
+ materializeClone(proof, cp, store);
386
+ checkIndependentHistory(proof, head);
387
+ verifyTree(root, files, withoutGit);
388
+ if (value(root, ["rev-parse", "HEAD"]) !== head) throw new Error("Workspace HEAD changed while saving " + root);
389
+ if (linked) verifyTree(info.gitDir, cp.privateGit!, worktreePointers);
390
+ else verifyTree(info.gitDir, cp.git);
391
+ rmSync(proof, { recursive: true, force: true });
392
+ const manifest = JSON.stringify(cp);
393
+ const pointer = attemptFile(record, attempt);
394
+ if (existsSync(pointer)) {
395
+ const prior = readCheckpoint(w, attempt);
396
+ if (readFileSync(join(prior.dir, "manifest.json"), "utf8") === manifest) {
397
+ rmSync(dir, { recursive: true, force: true });
398
+ atomicText(join(record, "current"), prior.dir.slice(record.length + 1));
399
+ return prior;
400
+ }
401
+ }
402
+ writeFileSync(join(dir, "manifest.json"), manifest, { mode: 0o600 });
403
+ const generation = dir.slice(record.length + 1);
404
+ atomicText(attemptFile(record, attempt), generation);
405
+ atomicText(join(record, "current"), generation);
406
+ return { dir, cp };
407
+ } catch (error) {
408
+ rmSync(dir, { recursive: true, force: true });
409
+ throw error;
410
+ }
411
+ }
412
+
413
+ export function reclaimWorkspace(original: IsolatedWorkspace, attempt = original.owner): void {
414
+ finishPendingRestore(original);
415
+ if (existsSync(paths(original).root + "-retired")) finishRetirement(readCheckpoint(original).cp.workspace);
416
+ const w = currentWorkspace(original);
417
+ const { root, record } = paths(w);
418
+ // A continuation froze the previous attempt before accepting the next writer.
419
+ // Only an attempt without such a frozen result can own the remaining checkout.
420
+ if (existsSync(attemptFile(record, attempt))) {
421
+ readCheckpoint(w, attempt);
422
+ if (!existsSync(root)) return;
423
+ if (existsSync(join(record, "writer")) && readFileSync(join(record, "writer"), "utf8") !== attempt) return;
424
+ }
425
+ if (!existsSync(root)) {
426
+ readCheckpoint(w, attempt);
427
+ return;
428
+ }
429
+ checkpoint(w, attempt);
430
+ removeOwned(w);
431
+ }
432
+
433
+ export function markWorkspaceWriter(w: IsolatedWorkspace, id: string): void {
434
+ const { record } = paths(w);
435
+ mkdirSync(record, { recursive: true, mode: 0o700 });
436
+ atomicText(join(record, "root"), paths(w).root);
437
+ atomicText(join(record, "writer"), id);
438
+ }
439
+
440
+ function finishPendingRestore(w: IsolatedWorkspace): void {
441
+ const { root, record } = paths(w);
442
+ const marker = join(record, "restoring");
443
+ if (!existsSync(marker)) return;
444
+ readCheckpoint(w);
445
+ const staging = readFileSync(marker, "utf8");
446
+ if (dirname(staging) !== dirname(root) || !basename(staging).startsWith(basename(root) + "-restore-"))
447
+ throw new Error("Invalid pending restore");
448
+ const target = join(staging, "checkout");
449
+ if (existsSync(join(target, ".git")) && lstatSync(join(target, ".git")).isFile())
450
+ git(w.source, ["worktree", "remove", "--force", target]);
451
+ rmSync(staging, { recursive: true, force: true });
452
+ rmSync(marker);
453
+ }
454
+
455
+ // Called under the conversation lease, after confirming that the previous writer is gone.
456
+ export function restoreWorkspace(
457
+ original: IsolatedWorkspace,
458
+ inClone = false,
459
+ prior = original.owner,
460
+ ): IsolatedWorkspace {
461
+ finishPendingRestore(original);
462
+ if (existsSync(paths(original).root + "-retired")) finishRetirement(readCheckpoint(original).cp.workspace);
463
+ const w = currentWorkspace(original);
464
+ const { root, record, store } = paths(w);
465
+ const exists = existsSync(root);
466
+ if (exists) inspectOwned(w);
467
+ const { cp } = exists ? checkpoint(w, prior) : readCheckpoint(w, prior);
468
+ const after = { ...w, mode: inClone ? ("clone" as const) : w.mode };
469
+ if (exists && after.mode === w.mode) return w;
470
+ mkdirSync(dirname(root), { recursive: true });
471
+ const staging = mkdtempSync(root + "-restore-"),
472
+ target = join(staging, "checkout");
473
+ atomicText(join(record, "restoring"), staging);
474
+ try {
475
+ if (after.mode === "clone") {
476
+ materializeClone(target, cp, store);
477
+ if (inClone) atomicText(join(record, "handoff"), "clone");
478
+ if (exists) removeOwned(w);
479
+ renameSync(target, root);
480
+ } else {
481
+ // Let Git enforce branch occupancy. The saved private HEAD and index replace the temporary checkout.
482
+ if (cp.branch && value(w.source, ["rev-parse", "--verify", "refs/heads/" + cp.branch]) !== cp.head)
483
+ throw new Error("Worktree branch moved. The saved checkout is available in Clone.");
484
+ git(w.source, [
485
+ "worktree",
486
+ "add",
487
+ "--no-checkout",
488
+ ...(cp.branch ? [] : ["--detach"]),
489
+ target,
490
+ cp.branch || "HEAD",
491
+ ]);
492
+ const admin = inspectGitWorkspace(target).gitDir;
493
+ for (const name of readdirSync(admin))
494
+ if (!worktreePointers.has(name)) rmSync(join(admin, name), { recursive: true, force: true });
495
+ restoreTree(admin, store, cp.privateGit!);
496
+ restoreTree(target, store, cp.files);
497
+ verifyTree(target, cp.files, withoutGit);
498
+ verifyTree(admin, cp.privateGit!, worktreePointers);
499
+ const verify = ["fsck", "--cache", "--connectivity-only", "--no-dangling", "--no-reflogs", cp.head];
500
+ try {
501
+ git(target, verify);
502
+ } catch {
503
+ // A detached commit or staged blob can be pruned while its checkout is reclaimed.
504
+ // Reintroduce its verified objects without updating any source branch or Git configuration.
505
+ const proof = join(staging, "proof");
506
+ const packPath = join(staging, "saved.pack");
507
+ materializeClone(proof, cp, store);
508
+ checkIndependentHistory(proof, cp.head, packPath);
509
+ const input = openSync(packPath, "r");
510
+ try {
511
+ git(w.source, ["unpack-objects", "-q"], input);
512
+ } finally {
513
+ closeSync(input);
514
+ }
515
+ git(target, verify);
516
+ }
517
+ git(w.source, ["worktree", "move", target, root]);
518
+ }
519
+ return after;
520
+ } finally {
521
+ finishPendingRestore(w);
522
+ }
523
+ }
524
+
525
+ export function workspaceDelivery(w: IsolatedWorkspace, cwd: string, confined: boolean, attempt = w.owner): string {
526
+ const { record } = paths(w);
527
+ let location = cwd;
528
+ if (existsSync(attemptFile(record, attempt))) {
529
+ const manifest = join(checkpointDir(w, attempt), "manifest.json");
530
+ location = `${manifest} (restore a copy with pi-subagents-recover ${attempt} <new-directory>)`;
531
+ }
532
+ const guidance =
533
+ w.mode === "worktree" && confined
534
+ ? " If Git metadata writes are denied, review the saved changes or continue with recover_in_clone:true."
535
+ : "";
536
+ return `Git workspace (${w.mode}): ${location}. Base: ${w.base}.${guidance}`;
537
+ }
538
+
539
+ export function exportWorkspace(w: IsolatedWorkspace, attempt: string, destination: string): void {
540
+ const dest = resolve(destination);
541
+ if (existsSync(dest)) throw new Error("Choose a new destination directory.");
542
+ const { cp } = readCheckpoint(w, attempt);
543
+ // Reserve the destination exclusively. A failed export has no effect on the saved copy.
544
+ mkdirSync(dest, { mode: 0o700 });
545
+ try {
546
+ materializeClone(dest, cp, paths(w).store);
547
+ } catch (error) {
548
+ rmSync(dest, { recursive: true, force: true });
549
+ throw error;
550
+ }
551
+ }
@@ -3,7 +3,7 @@ import { assignmentFor, assignmentDiagnostic } from "./assignment-projection.mjs
3
3
  import { describeTiming } from "./timing.domain.mjs";
4
4
  import { fmtElapsed } from "./widget.mjs";
5
5
  import { formatListHealthSuffix } from "./health-surface.mjs";
6
- import { isWithinWorkspace, normalizeWorkspacePath } from "./workspace-scope.domain.mjs";
6
+ import { discoveryWorkspace, isWithinWorkspace, normalizeWorkspacePath } from "./workspace-scope.domain.mjs";
7
7
  export const SUBAGENT_LIST_DEFAULT_LIMIT = 10;
8
8
  export const SUBAGENT_LIST_MAX_LIMIT = 100;
9
9
  /** Effective + durable supervision statuses accepted by subagent_list filters. */
@@ -107,7 +107,7 @@ export function collectSubagentList(p) {
107
107
  const statusOf = p.statusOf ?? ((meta) => meta.status);
108
108
  const healthById = p.healthById ?? (() => undefined);
109
109
  const failureById = p.failureById ?? (() => "");
110
- const inScope = p.inScope ?? ((meta) => options.all || isWithinWorkspace(meta.cwd, cwd));
110
+ const inScope = p.inScope ?? ((meta) => options.all || isWithinWorkspace(discoveryWorkspace(meta), cwd));
111
111
  const offset = Math.max(0, Math.floor(Number(p.offset) || 0));
112
112
  const scoped = (p.metas ?? [])
113
113
  .filter((meta) => inScope(meta, options))
@@ -9,18 +9,20 @@ import { ownerBindingFromContext, getWorkerOperationService, resolveProductionSc
9
9
  import { processStartToken } from "./registry.domain.mjs";
10
10
  import { connectWorkClient } from "./shared-work-client.mjs";
11
11
  import { catalogHostAuthority } from "./catalog-host-admission.domain.mjs";
12
- import { openSharedCatalog } from "./shared-catalog.domain.mjs";
12
+ import { openSharedCatalog, waitForCatalogSetup } from "./shared-catalog.domain.mjs";
13
13
  import { SANDBOX_POLICY_CHANNEL } from "./permission-policy.domain.mjs";
14
14
  import { canonicalJson } from "./operation-bridge-types.domain.mjs";
15
15
  import { activeChildProviders } from "./config.domain.mjs";
16
16
  import { captureLaunchContext } from "./launch-context.domain.mjs";
17
17
  /** The fixed Pi host issues execution grants. Catalog registration grants no execution. */
18
- export async function submitManagedLaunch(pi, ctx, key, tool, params) {
18
+ export async function submitManagedLaunch(pi, ctx, key, tool, params, signal) {
19
+ signal?.throwIfAborted();
19
20
  ctx = captureLaunchContext(ctx);
20
21
  mkdirSync(getAgentDir(), { recursive: true });
21
22
  const root = realpathSync(getAgentDir());
22
- const catalog = await openSharedCatalog(ctx.cwd, root);
23
+ const catalog = await openSharedCatalog(ctx.cwd, root, undefined, undefined, signal);
23
24
  catalog.close();
25
+ signal?.throwIfAborted();
24
26
  const registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
25
27
  if (registration.agentDir !== root || registration.version !== 1)
26
28
  throw new Error("Invalid runtime registration");
@@ -29,12 +31,22 @@ export async function submitManagedLaunch(pi, ctx, key, tool, params) {
29
31
  const stat = lstatSync(directory);
30
32
  if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
31
33
  throw new Error("Unsafe launch admission directory");
32
- const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-subagent-launch-v1"]);
34
+ const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-subagent-launch-v1"], { signal });
33
35
  const id = randomUUID(), secret = randomBytes(32).toString("hex"), path = join(directory, `${id}.json`);
34
36
  let unsubscribe;
37
+ const cancel = () => {
38
+ try {
39
+ rmSync(path, { force: true });
40
+ }
41
+ catch { /* Finally retries cleanup. */ }
42
+ client.close();
43
+ };
44
+ signal?.addEventListener("abort", cancel, { once: true });
35
45
  try {
46
+ signal?.throwIfAborted();
36
47
  const hello = await client.ready;
37
- const catalogAuthority = await catalogHostAuthority(root, ctx.cwd, join(registration.serverDir, "pi-server.sock"));
48
+ const catalogAuthority = await waitForCatalogSetup(catalogHostAuthority(root, ctx.cwd, join(registration.serverDir, "pi-server.sock")), signal);
49
+ signal?.throwIfAborted();
38
50
  const owner = ownerBindingFromContext(ctx);
39
51
  if (!owner.sessionId)
40
52
  throw new Error("Launch requires a registered parent session");
@@ -66,7 +78,12 @@ export async function submitManagedLaunch(pi, ctx, key, tool, params) {
66
78
  });
67
79
  return await client.request("runtime_launch_subagent", { authority: { id, secret } });
68
80
  }
81
+ catch (error) {
82
+ signal?.throwIfAborted();
83
+ throw error;
84
+ }
69
85
  finally {
86
+ signal?.removeEventListener("abort", cancel);
70
87
  if (typeof unsubscribe === "function")
71
88
  unsubscribe();
72
89
  client.close();