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