@agimon-ai/po-git 0.0.0-alpha.20 → 0.0.0-alpha.201

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 (36) hide show
  1. package/LICENSE +97 -8
  2. package/README.md +91 -21
  3. package/dist/apiContracts.cjs +78 -12
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +78 -12
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +2255 -544
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +1553 -508
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts.map +1 -1
  14. package/dist/extensions/server.mjs +1512 -467
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +1747 -1374
  17. package/dist/extensions/web.mjs.map +1 -1
  18. package/dist/gitDependencies-D8bKxZSc.cjs +2690 -0
  19. package/dist/gitDependencies-D8bKxZSc.cjs.map +1 -0
  20. package/dist/gitDependencies-Delu4xip.mjs +2432 -0
  21. package/dist/gitDependencies-Delu4xip.mjs.map +1 -0
  22. package/dist/index.cjs +13 -22
  23. package/dist/index.d.mts +266 -14
  24. package/dist/index.d.mts.map +1 -1
  25. package/dist/index.mjs +3 -22
  26. package/dist/po-runtime-identity.json +1 -0
  27. package/llms.txt +3 -3
  28. package/package.json +99 -21
  29. package/src/prompts/codemode-how-to-git/SKILL.md +137 -0
  30. package/dist/index.cjs.map +0 -1
  31. package/dist/index.mjs.map +0 -1
  32. package/dist/worktreeOperations-Cd8Q12L4.mjs +0 -1064
  33. package/dist/worktreeOperations-Cd8Q12L4.mjs.map +0 -1
  34. package/dist/worktreeOperations-Dxs3txKL.cjs +0 -1220
  35. package/dist/worktreeOperations-Dxs3txKL.cjs.map +0 -1
  36. package/src/prompts/po-use-git/SKILL.md +0 -87
@@ -0,0 +1,2432 @@
1
+ import { createRequire } from "node:module";
2
+ import { BACKGROUND_CONTEXT, PO_FS_SERVICE, getOrThrow, requirePoFs, withAbortSignal } from "@agimon-ai/po-core/platform";
3
+ import { readPoWorkspaceRegistry } from "@agimon-ai/po-core/workspaceRegistry";
4
+ import { ConeFolder, PO_GIT_ENGINE_SERVICE, ProfileName, SparoError, SparsePolicy, profilePath } from "@agimon-ai/po-sparo";
5
+ import { defineServiceContract } from "@agimon-ai/po-core/serverPlugin";
6
+ import { execFile, spawn } from "node:child_process";
7
+ import fs from "node:fs/promises";
8
+ import { loadAll } from "js-yaml";
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import path from "node:path";
11
+ import os from "node:os";
12
+ import { isDeepStrictEqual } from "node:util";
13
+ import { poHomeDirectory } from "@agimon-ai/po-core/piSettings";
14
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
15
+ import { Check } from "typebox/value";
16
+ import { defineApiContract, jsonApiResponses } from "@agimon-ai/po-core/apiContracts";
17
+ import { Type } from "typebox";
18
+ import { PoWorkflowDefinitionRefSchema, PoWorkflowRunRefSchema } from "@agimon-ai/po-core/workflow";
19
+ //#region src/services/extensionService/index.ts
20
+ var DefaultGitExtensionService = class {
21
+ async execute() {
22
+ return {
23
+ message: "Show git worktrees owned by this session",
24
+ level: "info"
25
+ };
26
+ }
27
+ };
28
+ //#endregion
29
+ //#region src/schemas/gitEngine.ts
30
+ const GIT_ENGINE_CONTRACT = defineServiceContract(PO_GIT_ENGINE_SERVICE, { scope: "workspace" });
31
+ //#endregion
32
+ //#region src/services/gitCli/index.ts
33
+ /**
34
+ * Git, as this package needs it.
35
+ *
36
+ * The timeouts are not uniform because the operations are not comparable. A
37
+ * read answers in milliseconds; `worktree add` copies an entire checkout and
38
+ * `worktree remove` deletes one, both bounded by the filesystem rather than by
39
+ * git, and both minutes rather than seconds on a large repository or on
40
+ * Windows. A single timeout would either fail honest work or hang on a wedged
41
+ * one.
42
+ */
43
+ const READ_TIMEOUT_MS = 3e4;
44
+ const ADD_TIMEOUT_MS = 3e5;
45
+ const REMOVE_TIMEOUT_MS$1 = 3e5;
46
+ const PRUNE_TIMEOUT_MS = 15e3;
47
+ /** fetch and push: bounded by the network, so long enough for a slow link, short enough to notice a dead one. */
48
+ const NETWORK_TIMEOUT_MS = 12e4;
49
+ /** A rebase replays commits locally; a large branch on a slow disk takes minutes, never hours. */
50
+ const REBASE_TIMEOUT_MS = 3e5;
51
+ const MAX_OUTPUT_BYTES = 1e6;
52
+ /** Enough for any branch picker; a repository with more refs lists its most recent ones. */
53
+ const MAX_LISTED_REFS = 2e3;
54
+ const LOCAL_PREFIX = "refs/heads/";
55
+ const REMOTE_PREFIX = "refs/remotes/";
56
+ const HEAD_SUFFIX = "/HEAD";
57
+ /**
58
+ * Runs git and reports the outcome without ever throwing on a non-zero exit.
59
+ *
60
+ * LC_ALL is pinned because callers decide what to do by matching git's own
61
+ * wording, and a translated message would silently turn a recognised
62
+ * condition into an unrecognised failure.
63
+ *
64
+ * `env` replaces the environment for this child only. That is how remote auth
65
+ * reaches fetch and push without ever touching the hub's own process.env,
66
+ * which every session started afterwards would inherit.
67
+ */
68
+ function runGit(cwd, args, options) {
69
+ return new Promise((resolve) => {
70
+ execFile("git", [...args], {
71
+ cwd,
72
+ ...options.signal === void 0 ? {} : { signal: options.signal },
73
+ timeout: options.timeout,
74
+ maxBuffer: options.maxBuffer ?? MAX_OUTPUT_BYTES,
75
+ env: {
76
+ ...options.env ?? process.env,
77
+ LC_ALL: "C"
78
+ }
79
+ }, (error, stdout, stderr) => {
80
+ const failure = error;
81
+ resolve({
82
+ code: failure && typeof failure.code === "number" ? failure.code : failure ? 1 : 0,
83
+ stdout: String(stdout),
84
+ stderr: String(stderr),
85
+ timedOut: failure?.killed === true && failure.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
86
+ overflow: failure?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
87
+ });
88
+ });
89
+ });
90
+ }
91
+ /** Resolve a commit or configured profile blob without reading the working cone. */
92
+ async function revision(cwd, ref, options = {}) {
93
+ const result = await runGit(cwd, [
94
+ "rev-parse",
95
+ "--verify",
96
+ ref
97
+ ], {
98
+ ...options,
99
+ timeout: READ_TIMEOUT_MS
100
+ });
101
+ options.signal?.throwIfAborted();
102
+ if (result.code !== 0) throw failure("rev-parse", result);
103
+ return result.stdout.trim();
104
+ }
105
+ /** A sparse remote-only checkout creates its tracking branch in the engine. */
106
+ async function trackBranch(cwd, branch, upstream, options) {
107
+ const result = await runGit(cwd, [
108
+ "branch",
109
+ `--set-upstream-to=${upstream}`,
110
+ branch
111
+ ], {
112
+ ...options,
113
+ timeout: READ_TIMEOUT_MS
114
+ });
115
+ options.signal?.throwIfAborted();
116
+ if (result.code !== 0) throw failure("branch --set-upstream-to", result);
117
+ }
118
+ /** Read only the exact named remote branch, never a stale local tracking ref. */
119
+ async function remoteBranchHead(cwd, remote, branch, options) {
120
+ options.signal.throwIfAborted();
121
+ const configured = await runGit(cwd, [
122
+ "remote",
123
+ "get-url",
124
+ "--",
125
+ remote
126
+ ], {
127
+ ...options,
128
+ timeout: READ_TIMEOUT_MS
129
+ });
130
+ options.signal.throwIfAborted();
131
+ if (configured.code !== 0) return void 0;
132
+ const ref = `refs/heads/${branch}`;
133
+ const result = await runGit(cwd, [
134
+ "ls-remote",
135
+ "--exit-code",
136
+ "--refs",
137
+ "--",
138
+ remote,
139
+ ref
140
+ ], {
141
+ ...options,
142
+ timeout: NETWORK_TIMEOUT_MS
143
+ });
144
+ options.signal.throwIfAborted();
145
+ if (result.code !== 0) return void 0;
146
+ return result.stdout.split("\n").map((line) => line.split(" ")).find((line) => line[1] === ref)?.[0];
147
+ }
148
+ function git(cwd, args, timeout) {
149
+ return runGit(cwd, args, { timeout });
150
+ }
151
+ /**
152
+ * The message a failed git call is allowed to surface.
153
+ *
154
+ * Raw stderr never travels: it can carry a remote URL with a token in it, and
155
+ * this text ends up in a tool result the model reads and may repeat.
156
+ */
157
+ function failure(operation, result) {
158
+ return /* @__PURE__ */ new Error(`git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`);
159
+ }
160
+ /** Git's own words for "that worktree is not there any more". */
161
+ function missingWorktree(stderr) {
162
+ const normalized = stderr.toLowerCase();
163
+ return normalized.includes("is not a working tree") || normalized.includes("cannot remove working tree");
164
+ }
165
+ function createWorktreeGit() {
166
+ const prune = async (repositoryRoot) => {
167
+ await git(repositoryRoot, ["worktree", "prune"], PRUNE_TIMEOUT_MS);
168
+ };
169
+ return {
170
+ async addWorktree({ repositoryRoot, path, branch, baseRef }) {
171
+ const result = await git(repositoryRoot, [
172
+ "worktree",
173
+ "add",
174
+ "-b",
175
+ branch,
176
+ path,
177
+ baseRef
178
+ ], ADD_TIMEOUT_MS);
179
+ if (result.code !== 0) throw failure("worktree add", result);
180
+ },
181
+ async addExistingWorktree({ repositoryRoot, path, branch, remote }) {
182
+ const result = await git(repositoryRoot, remote === void 0 ? [
183
+ "worktree",
184
+ "add",
185
+ path,
186
+ branch
187
+ ] : [
188
+ "worktree",
189
+ "add",
190
+ "--track",
191
+ "-b",
192
+ branch,
193
+ path,
194
+ `${remote}/${branch}`
195
+ ], ADD_TIMEOUT_MS);
196
+ if (result.code !== 0) throw failure("worktree add", result);
197
+ },
198
+ async listBranches(repositoryRoot) {
199
+ const refs = await git(repositoryRoot, [
200
+ "for-each-ref",
201
+ "--sort=-committerdate",
202
+ `--count=${String(MAX_LISTED_REFS)}`,
203
+ "--format=%(refname)%09%(worktreepath)%09%(symref)",
204
+ "refs/heads",
205
+ "refs/remotes"
206
+ ], READ_TIMEOUT_MS);
207
+ if (refs.code !== 0) throw failure("for-each-ref", refs);
208
+ const local = [];
209
+ const remotes = [];
210
+ for (const line of refs.stdout.split("\n")) {
211
+ const [ref = "", worktreePath = "", symref = ""] = line.split(" ");
212
+ if (ref === "" || symref !== "") continue;
213
+ if (ref.startsWith(LOCAL_PREFIX)) {
214
+ const name = ref.slice(11);
215
+ local.push(worktreePath === "" ? { name } : {
216
+ name,
217
+ checkedOutAt: worktreePath
218
+ });
219
+ } else if (ref.startsWith(REMOTE_PREFIX) && !ref.endsWith(HEAD_SUFFIX)) {
220
+ const rest = ref.slice(13);
221
+ const separator = rest.indexOf("/");
222
+ if (separator > 0) remotes.push({
223
+ remote: rest.slice(0, separator),
224
+ name: rest.slice(separator + 1)
225
+ });
226
+ }
227
+ }
228
+ const localNames = new Set(local.map((branch) => branch.name));
229
+ const head = await git(repositoryRoot, [
230
+ "symbolic-ref",
231
+ "--quiet",
232
+ "--short",
233
+ "HEAD"
234
+ ], READ_TIMEOUT_MS);
235
+ const current = head.code === 0 && head.stdout.trim() !== "" ? head.stdout.trim() : void 0;
236
+ const origin = await git(repositoryRoot, [
237
+ "symbolic-ref",
238
+ "--quiet",
239
+ "--short",
240
+ "refs/remotes/origin/HEAD"
241
+ ], READ_TIMEOUT_MS);
242
+ const defaultBase = origin.code === 0 && origin.stdout.trim() !== "" ? origin.stdout.trim() : current;
243
+ return {
244
+ ...current === void 0 ? {} : { current },
245
+ ...defaultBase === void 0 ? {} : { defaultBase },
246
+ local,
247
+ remote: remotes.filter((branch) => !localNames.has(branch.name))
248
+ };
249
+ },
250
+ async removeWorktree({ repositoryRoot, path, force }) {
251
+ const result = await git(repositoryRoot, [
252
+ "worktree",
253
+ "remove",
254
+ ...force ? ["--force"] : [],
255
+ path
256
+ ], REMOVE_TIMEOUT_MS$1);
257
+ if (result.code === 0) return;
258
+ if (missingWorktree(result.stderr) && !await fs.access(path).then(() => true, () => false)) {
259
+ await prune(repositoryRoot);
260
+ return;
261
+ }
262
+ throw failure("worktree remove", result);
263
+ },
264
+ async deleteBranch({ repositoryRoot, branch }) {
265
+ return (await git(repositoryRoot, [
266
+ "branch",
267
+ "-d",
268
+ branch
269
+ ], READ_TIMEOUT_MS)).code === 0;
270
+ },
271
+ pruneWorktrees: prune,
272
+ async listWorktreePaths(repositoryRoot) {
273
+ const result = await git(repositoryRoot, [
274
+ "worktree",
275
+ "list",
276
+ "--porcelain"
277
+ ], READ_TIMEOUT_MS);
278
+ if (result.code !== 0) return [];
279
+ return result.stdout.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice(9).trim()).filter((line) => line !== "");
280
+ },
281
+ async dirtyFiles(path) {
282
+ const result = await git(path, ["status", "--porcelain"], READ_TIMEOUT_MS);
283
+ if (result.code !== 0) return [];
284
+ return result.stdout.split("\n").map((line) => line.slice(3).trim()).filter((line) => line !== "");
285
+ },
286
+ async repositoryRoot(cwd) {
287
+ const result = await git(cwd, ["rev-parse", "--show-toplevel"], READ_TIMEOUT_MS);
288
+ if (result.code !== 0) return void 0;
289
+ const root = result.stdout.trim();
290
+ return root === "" ? void 0 : root;
291
+ },
292
+ async currentBranch(cwd) {
293
+ const result = await git(cwd, [
294
+ "rev-parse",
295
+ "--abbrev-ref",
296
+ "HEAD"
297
+ ], READ_TIMEOUT_MS);
298
+ if (result.code !== 0) return void 0;
299
+ const branch = result.stdout.trim();
300
+ return branch === "" ? void 0 : branch;
301
+ },
302
+ async remoteBaseRef(cwd) {
303
+ const upstream = await git(cwd, [
304
+ "rev-parse",
305
+ "--abbrev-ref",
306
+ "--symbolic-full-name",
307
+ "@{upstream}"
308
+ ], READ_TIMEOUT_MS);
309
+ if (upstream.code === 0) {
310
+ const branch = upstream.stdout.trim();
311
+ if (branch !== "") return branch;
312
+ }
313
+ const origin = await git(cwd, [
314
+ "symbolic-ref",
315
+ "--quiet",
316
+ "--short",
317
+ "refs/remotes/origin/HEAD"
318
+ ], READ_TIMEOUT_MS);
319
+ if (origin.code === 0) {
320
+ const branch = origin.stdout.trim();
321
+ if (branch !== "") return branch;
322
+ }
323
+ const defaults = await git(cwd, [
324
+ "for-each-ref",
325
+ "--format=%(symref:short)",
326
+ "refs/remotes"
327
+ ], READ_TIMEOUT_MS);
328
+ if (defaults.code !== 0) return void 0;
329
+ return defaults.stdout.split("\n").map((line) => line.trim()).find((line) => line !== "");
330
+ },
331
+ async mergeBranch({ repositoryRoot, branch, message }) {
332
+ const result = await git(repositoryRoot, [
333
+ "merge",
334
+ "--no-ff",
335
+ ...message === void 0 ? [] : ["-m", message],
336
+ branch
337
+ ], READ_TIMEOUT_MS);
338
+ if (result.code === 0) return;
339
+ throw failure("merge", result);
340
+ }
341
+ };
342
+ }
343
+ //#endregion
344
+ //#region src/constants/git.ts
345
+ /** Workspace-mounted routes behind the new-session dialog. */
346
+ const GIT_BRANCHES_PATH = "/branches";
347
+ const GIT_SESSIONS_PATH = "/sessions";
348
+ /** Workspace-mounted: that workspace's remote auth for manual pull, push and rebase. */
349
+ const GIT_AUTH_PATH = "/auth";
350
+ /** Session-mounted: the session's change against its base, and one file's hunks. */
351
+ const GIT_REVIEW_PATH = "/review";
352
+ const GIT_REVIEW_FILE_PATH = "/review/file";
353
+ /** Repository file, relative to the checkout root, whose `setup` commands run in every new worktree. */
354
+ const WORKTREE_CONFIG_FILE = ".po/worktree.yaml";
355
+ /** Trusted same-host setup handoff, consumed before starting the child session's runner. */
356
+ const WORKTREE_SETUP_EVENT = "git_worktree_setup";
357
+ const WORKTREE_SETUP_RUNNER = "worktree-setup";
358
+ /** A missing or slow receiver is unconfirmed, never permission to retry a shell command. */
359
+ const WORKTREE_SETUP_TIMEOUT_MS = 3e3;
360
+ /** Installs the rift CLI. Shown to the person to copy, and named in the error an agent reads. */
361
+ const RIFT_INSTALL_COMMAND = "npm install -g rift-snapshot";
362
+ //#endregion
363
+ //#region src/services/errors/index.ts
364
+ var PoGitExpectedError = class extends Error {
365
+ code;
366
+ retryable;
367
+ recovery;
368
+ constructor(code, message, retryable, recovery) {
369
+ super(`[${code}] ${message}\nRecovery: ${recovery}`);
370
+ this.code = code;
371
+ this.retryable = retryable;
372
+ this.recovery = recovery;
373
+ this.name = "PoGitExpectedError";
374
+ }
375
+ };
376
+ /** Raised when a worktree action needs the canonical hub but it is not injected. */
377
+ var HubUnavailableError = class extends Error {
378
+ constructor(message) {
379
+ super(message);
380
+ this.name = "HubUnavailableError";
381
+ }
382
+ };
383
+ function invalidRequest(message, recovery) {
384
+ return new PoGitExpectedError("invalid_request", message, false, recovery);
385
+ }
386
+ //#endregion
387
+ //#region src/services/worktreeConfig/index.ts
388
+ function object(value) {
389
+ return typeof value === "object" && value !== null && !Array.isArray(value);
390
+ }
391
+ function invalid(field) {
392
+ throw invalidRequest(`${field} is not valid.`, "Fix the worktree configuration and try again.");
393
+ }
394
+ /** Sparse checkout names are separate from the launcher's selection.profile. */
395
+ function validSparseProfile(value) {
396
+ return ProfileName.safeParse(value).success;
397
+ }
398
+ /** Only this plugin's supplied fields are consumed; unrelated workspace metadata is left alone. */
399
+ function readWorktreeSparseDefaults(metadata) {
400
+ if (metadata === void 0) return {};
401
+ if (!object(metadata)) return invalid("Workspace metadata");
402
+ const field = Object.hasOwn(metadata, "git") ? "git" : Object.hasOwn(metadata, "sparo") ? "sparo" : void 0;
403
+ if (field === void 0) return {};
404
+ const value = metadata[field];
405
+ if (!object(value)) return invalid(`metadata.${field}`);
406
+ const profileKey = field === "sparo" ? "profile" : "sparseProfile";
407
+ if (Object.hasOwn(value, profileKey) && !validSparseProfile(value[profileKey])) return invalid(`metadata.${field}.${profileKey}`);
408
+ if (Object.hasOwn(value, "extraFolders") && (!Array.isArray(value.extraFolders) || !value.extraFolders.every((folder) => ConeFolder.safeParse(folder).success))) return invalid(`metadata.${field}.extraFolders`);
409
+ return {
410
+ ...value[profileKey] === void 0 ? {} : { sparseProfile: value[profileKey] },
411
+ ...value.extraFolders === void 0 ? {} : { extraFolders: [...value.extraFolders] }
412
+ };
413
+ }
414
+ /** Parse setup and sparse policy together, without repository-specific defaults. */
415
+ function parseWorktreeConfig(text) {
416
+ let value;
417
+ try {
418
+ const documents = loadAll(text);
419
+ if (documents.length > 1) return invalid(WORKTREE_CONFIG_FILE);
420
+ value = documents[0];
421
+ } catch {
422
+ return invalid(WORKTREE_CONFIG_FILE);
423
+ }
424
+ if (value === void 0 || value === null) return {};
425
+ if (!object(value)) return invalid(WORKTREE_CONFIG_FILE);
426
+ const result = {};
427
+ if (Object.hasOwn(value, "setup")) {
428
+ const commands = Array.isArray(value.setup) ? value.setup : [value.setup];
429
+ if (!commands.every((command) => typeof command === "string")) return invalid(`${WORKTREE_CONFIG_FILE} setup`);
430
+ const setup = commands.filter((command) => command.trim() !== "").join(" && ");
431
+ if (setup !== "") result.setup = setup;
432
+ }
433
+ if (Object.hasOwn(value, "sparse")) {
434
+ const sparse = SparsePolicy.safeParse(value.sparse);
435
+ if (!sparse.success) return invalid(`${WORKTREE_CONFIG_FILE} sparse`);
436
+ result.sparse = sparse.data;
437
+ }
438
+ return result;
439
+ }
440
+ /** One snapshot per repository in this composition, including missing or invalid files. */
441
+ function createWorktreeConfigReader(input) {
442
+ const snapshots = /* @__PURE__ */ new Map();
443
+ return (root) => {
444
+ let snapshot = snapshots.get(root);
445
+ if (snapshot === void 0) {
446
+ snapshot = (async () => {
447
+ const defaults = readWorktreeSparseDefaults(await input.readMetadata?.());
448
+ let text;
449
+ try {
450
+ text = await input.readTextFile(`${root.replace(/\/$/u, "")}/${WORKTREE_CONFIG_FILE}`);
451
+ } catch (error) {
452
+ if (error instanceof Error && "code" in error && (error.code === "not_found" || error.code === "ENOENT")) return Object.keys(defaults).length === 0 ? {} : { defaults };
453
+ throw error;
454
+ }
455
+ const config = parseWorktreeConfig(text);
456
+ return Object.keys(defaults).length === 0 ? config : {
457
+ ...config,
458
+ defaults
459
+ };
460
+ })();
461
+ snapshots.set(root, snapshot);
462
+ }
463
+ return snapshot;
464
+ };
465
+ }
466
+ //#endregion
467
+ //#region src/services/worktreeEvents/index.ts
468
+ const GIT_WORKTREE_LIFECYCLE_EVENT = "git_worktree_lifecycle";
469
+ const GIT_WORKTREE_MESSAGE_EVENT = "git_worktree_message";
470
+ /**
471
+ * A session's checkout may have changed: a tool call ended, or the agent
472
+ * settled. Carries nothing but its version; the '# diff' channel recomputes.
473
+ */
474
+ const GIT_SESSION_CHANGED_EVENT = "git_session_changed";
475
+ const MAX_WORKTREE_MESSAGE_BYTES = 65536;
476
+ function isMessageParty(value) {
477
+ return value === "parent" || value === "child";
478
+ }
479
+ function parseMessage(value) {
480
+ if (typeof value !== "object" || value === null) return void 0;
481
+ const record = value;
482
+ if (record.version !== 1) return void 0;
483
+ if (typeof record.worktreeId !== "string" || record.worktreeId === "") return void 0;
484
+ if (typeof record.fromSessionId !== "string" || record.fromSessionId === "") return void 0;
485
+ if (!isMessageParty(record.from)) return void 0;
486
+ if (typeof record.text !== "string" || record.text === "") return void 0;
487
+ if (Buffer.byteLength(record.text, "utf8") > 65536) return void 0;
488
+ if (typeof record.sentAt !== "string" || record.sentAt === "") return void 0;
489
+ return record;
490
+ }
491
+ function createWorktreeMessageInbox(directEvents, sessionId) {
492
+ if (sessionId === "") throw new Error("The Git message service requires a session identity.");
493
+ const messages = /* @__PURE__ */ new Map();
494
+ const unsubscribe = directEvents.subscribe(GIT_WORKTREE_MESSAGE_EVENT, sessionId, (payload) => {
495
+ const message = parseMessage(payload);
496
+ if (message === void 0) return;
497
+ const inbox = messages.get(message.worktreeId) ?? [];
498
+ if (inbox.length >= 100) inbox.shift();
499
+ inbox.push(message);
500
+ messages.set(message.worktreeId, inbox);
501
+ });
502
+ let closed = false;
503
+ return {
504
+ send(targetSessionId, message) {
505
+ if (closed) throw new Error("The Git message service is closed.");
506
+ directEvents.publish(GIT_WORKTREE_MESSAGE_EVENT, targetSessionId, message);
507
+ },
508
+ receive(worktreeId) {
509
+ if (closed) return [];
510
+ const inbox = messages.get(worktreeId);
511
+ if (inbox === void 0) return [];
512
+ messages.delete(worktreeId);
513
+ return inbox;
514
+ },
515
+ close() {
516
+ if (closed) return;
517
+ closed = true;
518
+ unsubscribe();
519
+ messages.clear();
520
+ }
521
+ };
522
+ }
523
+ function isWorktreeLifecycleEvent(value) {
524
+ if (typeof value !== "object" || value === null) return false;
525
+ const record = value;
526
+ return record.version === 1 && typeof record.repositoryRoot === "string" && record.repositoryRoot !== "";
527
+ }
528
+ /**
529
+ * One bounded issue/receipt on the trusted host bus. Timeout and cancellation
530
+ * overwrite the retained request so a late receiver cannot run abandoned setup.
531
+ * There are deliberately no retries: a lost receipt can mean the runner exists.
532
+ */
533
+ function startWorktreeSetup(directEvents, sessionId, command, signal) {
534
+ if (signal?.aborted) return Promise.resolve("unconfirmed");
535
+ const requestId = randomUUID();
536
+ return new Promise((resolve) => {
537
+ let settled = false;
538
+ const finish = (stage) => {
539
+ if (settled) return;
540
+ settled = true;
541
+ clearTimeout(timer);
542
+ unsubscribe();
543
+ signal?.removeEventListener("abort", abort);
544
+ if (stage === "unconfirmed") directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
545
+ version: 1,
546
+ kind: "cancel",
547
+ requestId
548
+ });
549
+ resolve(stage);
550
+ };
551
+ const abort = () => finish("unconfirmed");
552
+ const unsubscribe = directEvents.subscribe(WORKTREE_SETUP_EVENT, sessionId, (value) => {
553
+ if (!value || typeof value !== "object") return;
554
+ const receipt = value;
555
+ if (receipt.version !== 1 || receipt.kind !== "receipt" || receipt.requestId !== requestId) return;
556
+ if (receipt.stage === "started" || receipt.stage === "failed" || receipt.stage === "unconfirmed") finish(receipt.stage);
557
+ });
558
+ const timer = setTimeout(() => finish("unconfirmed"), WORKTREE_SETUP_TIMEOUT_MS);
559
+ signal?.addEventListener("abort", abort, { once: true });
560
+ if (signal?.aborted) abort();
561
+ if (!settled) directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
562
+ version: 1,
563
+ kind: "request",
564
+ requestId,
565
+ command
566
+ });
567
+ });
568
+ }
569
+ /**
570
+ * Runs only under the child's runner service injection. This receiver never
571
+ * reads the registry: the parent can hold its transaction through the receipt.
572
+ * Consuming retained requests synchronously prevents a remount replaying setup.
573
+ */
574
+ function receiveWorktreeSetup(directEvents, sessionId, cwd, runner, signal) {
575
+ const pending = /* @__PURE__ */ new Map();
576
+ const seen = /* @__PURE__ */ new Set();
577
+ let closed = false;
578
+ let unsubscribe = () => {};
579
+ const receipt = (requestId, stage) => directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
580
+ version: 1,
581
+ kind: "receipt",
582
+ requestId,
583
+ stage
584
+ });
585
+ const close = () => {
586
+ if (closed) return;
587
+ closed = true;
588
+ unsubscribe();
589
+ signal?.removeEventListener("abort", close);
590
+ for (const [requestId, controller] of pending) {
591
+ controller.abort();
592
+ receipt(requestId, "unconfirmed");
593
+ }
594
+ pending.clear();
595
+ };
596
+ if (signal?.aborted) return close;
597
+ unsubscribe = directEvents.subscribe(WORKTREE_SETUP_EVENT, sessionId, (value) => {
598
+ if (closed || !value || typeof value !== "object") return;
599
+ const event = value;
600
+ if (event.version !== 1 || typeof event.requestId !== "string" || !event.requestId) return;
601
+ const requestId = event.requestId;
602
+ if (event.kind === "cancel") {
603
+ pending.get(requestId)?.abort();
604
+ return;
605
+ }
606
+ if (event.kind !== "request" || typeof event.command !== "string" || !event.command.trim() || seen.has(requestId)) return;
607
+ seen.add(requestId);
608
+ const command = event.command;
609
+ const controller = new AbortController();
610
+ pending.set(requestId, controller);
611
+ directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, {
612
+ version: 1,
613
+ kind: "consumed",
614
+ requestId
615
+ });
616
+ Promise.resolve().then(async () => {
617
+ controller.signal.throwIfAborted();
618
+ await runner.start({
619
+ name: WORKTREE_SETUP_RUNNER,
620
+ command: [command],
621
+ cwd,
622
+ wakeOnExit: true
623
+ }, controller.signal);
624
+ if (!controller.signal.aborted && !closed) receipt(requestId, "started");
625
+ }).catch(() => {
626
+ if (!closed) receipt(requestId, controller.signal.aborted ? "unconfirmed" : "failed");
627
+ }).finally(() => pending.delete(requestId));
628
+ }, { replayLatest: true });
629
+ signal?.addEventListener("abort", close, { once: true });
630
+ if (signal?.aborted) close();
631
+ return close;
632
+ }
633
+ function isSessionChangedEvent(value) {
634
+ return typeof value === "object" && value !== null && value.version === 1;
635
+ }
636
+ //#endregion
637
+ //#region src/services/atomicJson/index.ts
638
+ const OWNER_ONLY_FILE = 384;
639
+ /**
640
+ * Writes JSON so a reader never sees a half-written file.
641
+ *
642
+ * The registry is read by the same process that writes it, and by a later
643
+ * process after a crash. A plain write can be interrupted between the truncate
644
+ * and the last byte, which leaves a file that parses as nothing and loses every
645
+ * record in it. Writing beside the target and renaming makes the swap atomic on
646
+ * the same filesystem, so a reader sees either the old file or the new one.
647
+ */
648
+ async function writeJsonAtomic(file, value) {
649
+ const directory = path.dirname(file);
650
+ await fs.mkdir(directory, { recursive: true });
651
+ const temporary = path.join(directory, `.${path.basename(file)}.${randomUUID()}.tmp`);
652
+ await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: OWNER_ONLY_FILE });
653
+ await fs.rename(temporary, file);
654
+ }
655
+ /**
656
+ * Reads JSON, treating every failure as absent.
657
+ *
658
+ * A missing file and an unparseable one mean the same thing to every caller
659
+ * here: there is nothing to act on. Distinguishing them would only offer a
660
+ * choice no caller wants to make.
661
+ */
662
+ async function readJson(file) {
663
+ try {
664
+ return JSON.parse(await fs.readFile(file, "utf8"));
665
+ } catch {
666
+ return;
667
+ }
668
+ }
669
+ //#endregion
670
+ //#region src/services/repositoryIdentity/index.ts
671
+ const ID_LENGTH = 12;
672
+ const MAX_LABEL_LENGTH = 32;
673
+ /**
674
+ * The git directory shared by a repository and all of its worktrees.
675
+ *
676
+ * A normal checkout has a `.git` directory. A linked worktree has a `.git`
677
+ * FILE pointing at `<common>/worktrees/<name>`, whose `commondir` points back
678
+ * at the shared directory. Following that chain is what makes every worktree of
679
+ * one repository agree on the repository's identity, which matters here because
680
+ * the registry is per repository and must be found from inside a worktree too.
681
+ * A session may run in a subdirectory, so the nearest enclosing checkout is used.
682
+ */
683
+ async function gitCommonDirectory(directory) {
684
+ let root = path.resolve(directory);
685
+ let marker = path.join(root, ".git");
686
+ let stat;
687
+ for (;;) try {
688
+ stat = await fs.stat(marker);
689
+ break;
690
+ } catch {
691
+ const parent = path.dirname(root);
692
+ if (parent === root) return void 0;
693
+ root = parent;
694
+ marker = path.join(root, ".git");
695
+ }
696
+ if (stat.isDirectory()) return marker;
697
+ let pointer;
698
+ try {
699
+ pointer = (await fs.readFile(marker, "utf8")).trim();
700
+ } catch {
701
+ return;
702
+ }
703
+ if (!pointer.startsWith("gitdir:")) return void 0;
704
+ const gitDir = path.resolve(root, pointer.slice(7).trim());
705
+ try {
706
+ const common = (await fs.readFile(path.join(gitDir, "commondir"), "utf8")).trim();
707
+ return path.resolve(gitDir, common);
708
+ } catch {
709
+ return gitDir;
710
+ }
711
+ }
712
+ /** A directory name that is recognisable to a person and safe on a filesystem. */
713
+ function repositoryLabel(root) {
714
+ const label = path.basename(root).toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, MAX_LABEL_LENGTH);
715
+ return label === "" ? "repository" : label;
716
+ }
717
+ /**
718
+ * A stable id for the repository a directory belongs to.
719
+ *
720
+ * Keyed on the common git directory rather than the given path, so the main
721
+ * checkout and every worktree of it resolve to one id and therefore to one
722
+ * registry. Falling back to the path keeps a non-repository directory usable
723
+ * instead of failing, though nothing here should reach that case.
724
+ */
725
+ async function repositoryId(root) {
726
+ const common = await gitCommonDirectory(root);
727
+ const token = common === void 0 ? `root:${path.resolve(root)}` : `git:${common}`;
728
+ return createHash("sha256").update(token).digest("hex").slice(0, ID_LENGTH);
729
+ }
730
+ /** A short, collision-resistant suffix for one worktree directory. */
731
+ function shortId(seed) {
732
+ return createHash("sha256").update(seed).digest("hex").slice(0, 8);
733
+ }
734
+ //#endregion
735
+ //#region src/schemas/apiContracts.ts
736
+ const S = Type.String();
737
+ const B = Type.Boolean();
738
+ const O$1 = Type.Optional;
739
+ const SparseProfileSchema = Type.String({ pattern: "^[A-Za-z0-9][A-Za-z0-9_-]*$" });
740
+ const SelectionSchema = Type.Object({ profile: Type.Union([S, Type.Null()]) });
741
+ const literals = (values) => Type.Union(values.map((value) => Type.Literal(value)));
742
+ const WorktreeRecordSchema = Type.Object({
743
+ version: Type.Literal(2),
744
+ id: S,
745
+ branch: S,
746
+ baseRef: S,
747
+ path: S,
748
+ repositoryRoot: S,
749
+ sessionId: S,
750
+ parentSessionId: Type.Optional(S),
751
+ status: literals([
752
+ "spawning",
753
+ "running",
754
+ "closing",
755
+ "orphaned"
756
+ ]),
757
+ setupStage: O$1(literals([
758
+ "none",
759
+ "started",
760
+ "failed",
761
+ "unconfirmed"
762
+ ])),
763
+ backend: O$1(Type.Literal("rift")),
764
+ sparseProfile: O$1(SparseProfileSchema),
765
+ extraFolders: O$1(Type.Array(S)),
766
+ sparseFingerprint: O$1(S),
767
+ baseCommit: O$1(S),
768
+ workflow: O$1(Type.Object({
769
+ attemptId: S,
770
+ fingerprint: S,
771
+ state: literals([
772
+ "spawned",
773
+ "admitted",
774
+ "retained"
775
+ ]),
776
+ admissionId: O$1(S),
777
+ runId: O$1(S),
778
+ reason: O$1(S)
779
+ })),
780
+ createdAt: S
781
+ });
782
+ const ErrorTargetSchema = Type.Union([Type.Object({
783
+ action: Type.Literal("create"),
784
+ riftMissing: O$1(Type.Literal(true))
785
+ }), Type.Object({
786
+ action: Type.Literal("close"),
787
+ id: S
788
+ })]);
789
+ const WorktreesPayloadSchema = Type.Object({
790
+ worktrees: Type.Array(Type.Object({
791
+ id: S,
792
+ branch: S,
793
+ path: S,
794
+ sessionId: Type.Union([S, Type.Null()]),
795
+ orphaned: B,
796
+ unowned: B
797
+ })),
798
+ pending: O$1(S),
799
+ error: O$1(S),
800
+ errorTarget: O$1(ErrorTargetSchema)
801
+ });
802
+ const WorktreesCommandSchema = Type.Union([Type.Object({
803
+ action: Type.Literal("create"),
804
+ branch: S,
805
+ baseRef: O$1(S),
806
+ reservationId: O$1(Type.String({
807
+ minLength: 1,
808
+ pattern: "^[A-Za-z0-9_-]+$"
809
+ }))
810
+ }), Type.Object({
811
+ action: Type.Literal("close"),
812
+ id: S,
813
+ force: O$1(B)
814
+ })]);
815
+ const N = Type.Integer({ minimum: 0 });
816
+ const ChangesSchema = Type.Object({
817
+ branch: O$1(S),
818
+ base: O$1(S),
819
+ added: N,
820
+ removed: N,
821
+ files: N,
822
+ truncated: O$1(B),
823
+ upstream: O$1(Type.Object({
824
+ ref: S,
825
+ ahead: N,
826
+ behind: N
827
+ })),
828
+ rebase: O$1(Type.Object({ conflicts: Type.Array(S) }))
829
+ });
830
+ const SyncErrorTargetSchema = Type.Union([Type.Object({ action: literals([
831
+ "pull",
832
+ "rebase",
833
+ "abort-rebase"
834
+ ]) }), Type.Object({
835
+ action: Type.Literal("push"),
836
+ forceRequired: O$1(Type.Literal(true))
837
+ })]);
838
+ const GitChangesPayloadSchema = Type.Object({
839
+ changes: O$1(ChangesSchema),
840
+ pending: O$1(S),
841
+ error: O$1(S),
842
+ errorTarget: O$1(SyncErrorTargetSchema)
843
+ });
844
+ const GitChangesCommandSchema = Type.Union([Type.Object({ action: literals([
845
+ "pull",
846
+ "rebase",
847
+ "abort-rebase"
848
+ ]) }), Type.Object({
849
+ action: Type.Literal("push"),
850
+ force: O$1(Type.Literal(true))
851
+ })]);
852
+ const AuthViewSchema = Type.Object({
853
+ method: literals([
854
+ "none",
855
+ "ssh",
856
+ "https"
857
+ ]),
858
+ ssh: O$1(Type.Object({ keyPath: O$1(S) })),
859
+ https: O$1(Type.Object({
860
+ host: S,
861
+ username: S,
862
+ hasToken: B
863
+ }))
864
+ });
865
+ const AuthSaveSchema = Type.Union([
866
+ Type.Object({ method: Type.Literal("none") }),
867
+ Type.Object({
868
+ method: Type.Literal("ssh"),
869
+ keyPath: O$1(S)
870
+ }),
871
+ Type.Object({
872
+ method: Type.Literal("https"),
873
+ host: S,
874
+ username: S,
875
+ token: O$1(Type.String({ writeOnly: true }))
876
+ })
877
+ ]);
878
+ const DiffRowSchema = Type.Object({
879
+ marker: literals([
880
+ "+",
881
+ "-",
882
+ " "
883
+ ]),
884
+ line: N,
885
+ content: S
886
+ });
887
+ const ReviewSummarySchema = Type.Object({
888
+ repository: B,
889
+ branch: O$1(S),
890
+ base: O$1(S),
891
+ mergeBase: O$1(S),
892
+ truncated: O$1(B),
893
+ files: Type.Array(Type.Object({
894
+ path: S,
895
+ status: literals([
896
+ "added",
897
+ "modified",
898
+ "deleted",
899
+ "untracked",
900
+ "conflicted"
901
+ ]),
902
+ added: N,
903
+ removed: N,
904
+ binary: O$1(B)
905
+ }))
906
+ });
907
+ const ReviewFileSchema = Type.Object({
908
+ path: S,
909
+ hunks: Type.Array(Type.Object({
910
+ start: N,
911
+ rows: Type.Array(DiffRowSchema)
912
+ })),
913
+ binary: O$1(Type.Literal(true)),
914
+ tooLarge: O$1(Type.Literal(true))
915
+ });
916
+ const query = [{
917
+ name: "repositoryId",
918
+ in: "query",
919
+ required: true,
920
+ schema: S
921
+ }, {
922
+ name: "sessionId",
923
+ in: "query",
924
+ required: true,
925
+ schema: S
926
+ }];
927
+ defineApiContract({
928
+ version: 1,
929
+ dynamic: [],
930
+ http: ["host", "workspace"].flatMap((scope) => [
931
+ {
932
+ id: "git.list",
933
+ scope,
934
+ basePath: "git",
935
+ path: "/worktrees",
936
+ method: "GET",
937
+ authentication: "owner",
938
+ description: "List admitted repository worktrees.",
939
+ parameters: query.map((item) => ({
940
+ ...item,
941
+ required: item.name === "repositoryId"
942
+ })),
943
+ responses: jsonApiResponses(Type.Object({ worktrees: Type.Array(WorktreeRecordSchema) }))
944
+ },
945
+ {
946
+ id: "git.create",
947
+ scope,
948
+ basePath: "git",
949
+ path: "/worktrees",
950
+ method: "POST",
951
+ authentication: "owner",
952
+ description: "Create a worktree and session.",
953
+ parameters: query,
954
+ body: {
955
+ required: true,
956
+ contentType: "application/json",
957
+ schema: Type.Object({
958
+ branch: Type.String({ minLength: 1 }),
959
+ baseRef: O$1(S),
960
+ name: O$1(S),
961
+ sparseProfile: O$1(SparseProfileSchema),
962
+ selection: O$1(SelectionSchema)
963
+ })
964
+ },
965
+ responses: jsonApiResponses(Type.Object({ worktree: WorktreeRecordSchema }), 201)
966
+ },
967
+ {
968
+ id: "git.close",
969
+ scope,
970
+ basePath: "git",
971
+ path: "/worktrees/{id}",
972
+ method: "DELETE",
973
+ authentication: "owner",
974
+ description: "Close a worktree.",
975
+ parameters: [...query, {
976
+ name: "force",
977
+ in: "query",
978
+ required: false,
979
+ schema: B
980
+ }],
981
+ responses: jsonApiResponses(Type.Object({ worktree: WorktreeRecordSchema }))
982
+ },
983
+ ...scope === "workspace" ? [
984
+ {
985
+ id: "git.auth.read",
986
+ scope,
987
+ basePath: "git",
988
+ path: "/auth",
989
+ method: "GET",
990
+ authentication: "owner",
991
+ description: "Read a workspace's remote auth for manual sync. The token is never returned.",
992
+ parameters: [{
993
+ name: "repositoryId",
994
+ in: "query",
995
+ required: true,
996
+ schema: S
997
+ }],
998
+ responses: jsonApiResponses(AuthViewSchema)
999
+ },
1000
+ {
1001
+ id: "git.auth.save",
1002
+ scope,
1003
+ basePath: "git",
1004
+ path: "/auth",
1005
+ method: "PUT",
1006
+ authentication: "owner",
1007
+ description: "Replace a workspace's remote auth. Passkey step-up gated for remote devices.",
1008
+ parameters: [{
1009
+ name: "repositoryId",
1010
+ in: "query",
1011
+ required: true,
1012
+ schema: S
1013
+ }],
1014
+ body: {
1015
+ required: true,
1016
+ contentType: "application/json",
1017
+ schema: AuthSaveSchema
1018
+ },
1019
+ responses: jsonApiResponses(AuthViewSchema)
1020
+ },
1021
+ {
1022
+ id: "git.branches",
1023
+ scope,
1024
+ basePath: "git",
1025
+ path: "/branches",
1026
+ method: "GET",
1027
+ authentication: "owner",
1028
+ description: "List the workspace branches for the new-session dialog.",
1029
+ responses: jsonApiResponses(Type.Object({
1030
+ repository: B,
1031
+ current: O$1(S),
1032
+ defaultBase: O$1(S),
1033
+ sparseProfiles: O$1(Type.Array(S)),
1034
+ defaultSparseProfile: O$1(S),
1035
+ local: Type.Array(Type.Object({
1036
+ name: S,
1037
+ checkedOutAt: O$1(S)
1038
+ })),
1039
+ remote: Type.Array(Type.Object({
1040
+ remote: S,
1041
+ name: S
1042
+ }))
1043
+ }))
1044
+ },
1045
+ {
1046
+ id: "git.branches.delete",
1047
+ scope,
1048
+ basePath: "git",
1049
+ path: "/branches",
1050
+ method: "DELETE",
1051
+ authentication: "owner",
1052
+ description: "Safely delete a local branch that is not checked out. Never force-deletes unmerged work.",
1053
+ body: {
1054
+ required: true,
1055
+ contentType: "application/json",
1056
+ schema: Type.Object({ branch: S })
1057
+ },
1058
+ responses: jsonApiResponses(Type.Object({ deleted: B }))
1059
+ },
1060
+ {
1061
+ id: "git.branches.open",
1062
+ scope,
1063
+ basePath: "git",
1064
+ path: "/branches/open",
1065
+ method: "POST",
1066
+ authentication: "owner",
1067
+ description: "Open the branch checkout in Finder. Local callers only, no client-supplied path.",
1068
+ body: {
1069
+ required: true,
1070
+ contentType: "application/json",
1071
+ schema: Type.Object({ branch: S })
1072
+ },
1073
+ responses: jsonApiResponses(Type.Object({ opened: B }))
1074
+ },
1075
+ {
1076
+ id: "git.sessions.create",
1077
+ scope,
1078
+ basePath: "git",
1079
+ path: "/sessions",
1080
+ method: "POST",
1081
+ authentication: "owner",
1082
+ description: "Start a top-level worktree session on an existing or new branch.",
1083
+ body: {
1084
+ required: true,
1085
+ contentType: "application/json",
1086
+ schema: Type.Union([Type.Object({
1087
+ mode: Type.Literal("existing-branch"),
1088
+ branch: S,
1089
+ remote: O$1(S),
1090
+ name: O$1(S),
1091
+ sparseProfile: O$1(SparseProfileSchema),
1092
+ selection: O$1(SelectionSchema)
1093
+ }), Type.Object({
1094
+ mode: Type.Literal("new-branch"),
1095
+ branch: S,
1096
+ baseRef: O$1(S),
1097
+ name: O$1(S),
1098
+ sparseProfile: O$1(SparseProfileSchema),
1099
+ selection: O$1(SelectionSchema)
1100
+ })])
1101
+ },
1102
+ responses: jsonApiResponses(Type.Object({
1103
+ sessionId: S,
1104
+ worktreeId: S
1105
+ }), 201)
1106
+ }
1107
+ ] : [],
1108
+ ...scope === "host" ? [{
1109
+ id: "git.review.summary",
1110
+ scope: "session",
1111
+ basePath: "git",
1112
+ path: "/review",
1113
+ method: "GET",
1114
+ authentication: "owner",
1115
+ description: "List the files the session's checkout changed against its base.",
1116
+ responses: jsonApiResponses(ReviewSummarySchema)
1117
+ }, {
1118
+ id: "git.review.file",
1119
+ scope: "session",
1120
+ basePath: "git",
1121
+ path: "/review/file",
1122
+ method: "GET",
1123
+ authentication: "owner",
1124
+ description: "One changed file's hunks; the path must be in the session's change set.",
1125
+ parameters: [{
1126
+ name: "path",
1127
+ in: "query",
1128
+ required: true,
1129
+ schema: Type.String({ minLength: 1 })
1130
+ }],
1131
+ responses: jsonApiResponses(ReviewFileSchema)
1132
+ }] : []
1133
+ ]),
1134
+ sockets: ["host", "workspace"].flatMap((scope) => [
1135
+ {
1136
+ id: "git.changes.channel",
1137
+ scope,
1138
+ service: "po.hub",
1139
+ member: "git_changes",
1140
+ kind: "channel",
1141
+ direction: "server-to-client",
1142
+ description: "The session's change against its base, and manual sync state.",
1143
+ input: GitChangesPayloadSchema
1144
+ },
1145
+ {
1146
+ id: "git.changes.command",
1147
+ scope,
1148
+ service: "po.hub",
1149
+ member: "git_changes",
1150
+ kind: "channel",
1151
+ direction: "client-to-server",
1152
+ description: "Manual pull, push, rebase or abort-rebase for the session.",
1153
+ input: GitChangesCommandSchema
1154
+ },
1155
+ {
1156
+ id: "git.channel",
1157
+ scope,
1158
+ service: "po.hub",
1159
+ member: "git_worktrees",
1160
+ kind: "channel",
1161
+ direction: "server-to-client",
1162
+ description: "Worktree channel payload.",
1163
+ input: WorktreesPayloadSchema
1164
+ },
1165
+ {
1166
+ id: "git.command",
1167
+ scope,
1168
+ service: "po.hub",
1169
+ member: "git_worktrees",
1170
+ kind: "channel",
1171
+ direction: "client-to-server",
1172
+ description: "Worktree channel command payload.",
1173
+ input: WorktreesCommandSchema
1174
+ }
1175
+ ])
1176
+ });
1177
+ //#endregion
1178
+ //#region src/schemas/worktreeWorkflows.ts
1179
+ const PO_GIT_WORKFLOWS_SERVICE = "po/git-workflows";
1180
+ const GIT_WORKFLOWS_CONTRACT = defineServiceContract(PO_GIT_WORKFLOWS_SERVICE, { scope: "session" });
1181
+ const Text = Type.String({ minLength: 1 });
1182
+ const O = Type.Optional;
1183
+ const Binding = O(Type.Unknown());
1184
+ const WorktreeWorkflowAttemptSchema = Type.Object({
1185
+ attemptId: Text,
1186
+ fingerprint: Text,
1187
+ launcherSessionId: Text,
1188
+ branch: Text,
1189
+ definition: O(PoWorkflowDefinitionRefSchema),
1190
+ createdAt: Text,
1191
+ state: Type.Union([
1192
+ "reserved",
1193
+ "spawned",
1194
+ "admitting",
1195
+ "admitted",
1196
+ "retained",
1197
+ "closed",
1198
+ "rejected"
1199
+ ].map((state) => Type.Literal(state))),
1200
+ worktreeId: O(Text),
1201
+ sessionId: O(Text),
1202
+ admission: O(Type.Union([
1203
+ Type.Object({
1204
+ attemptId: Text,
1205
+ admissionId: Text,
1206
+ state: Type.Literal("pending"),
1207
+ binding: Binding
1208
+ }),
1209
+ Type.Object({
1210
+ attemptId: Text,
1211
+ admissionId: Text,
1212
+ state: Type.Literal("rejected"),
1213
+ errors: Type.Array(Text)
1214
+ }),
1215
+ Type.Object({
1216
+ attemptId: Text,
1217
+ admissionId: Text,
1218
+ state: Type.Literal("registered"),
1219
+ run: PoWorkflowRunRefSchema,
1220
+ binding: Binding
1221
+ })
1222
+ ]))
1223
+ });
1224
+ /** Model-facing repository launch only. Trusted overrides and allocation never cross this boundary. */
1225
+ const StartWorktreeWorkflowSchema = Type.Object({
1226
+ key: Text,
1227
+ attemptId: O(Text),
1228
+ branch: O(Text),
1229
+ sparseProfile: O(Text),
1230
+ inputs: O(Type.Record(Type.String(), Type.String()))
1231
+ }, { additionalProperties: false });
1232
+ //#endregion
1233
+ //#region src/services/worktreeRegistry/index.ts
1234
+ const LOCK_WAIT_MS = 5e3;
1235
+ const LOCK_RETRY_MS = 25;
1236
+ function malformedRegistry() {
1237
+ throw new PoGitExpectedError("registry_read_failed", "The worktree registry is unreadable or malformed.", false, "Inspect and repair the registry before retrying. It has not been replaced.");
1238
+ }
1239
+ /** Explicit v1/v2 read compatibility. Nothing is rewritten until a caller replaces the file. */
1240
+ function parseWorktreeRegistry(value) {
1241
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return malformedRegistry();
1242
+ const file = value;
1243
+ if (file.version !== 1 && file.version !== 2 || !Array.isArray(file.entries)) return malformedRegistry();
1244
+ if (Object.hasOwn(file, "workflowAttempts")) {
1245
+ if (file.version !== 2 || !Array.isArray(file.workflowAttempts)) return malformedRegistry();
1246
+ const keys = /* @__PURE__ */ new Set();
1247
+ for (const attempt of file.workflowAttempts) {
1248
+ if (!Check(WorktreeWorkflowAttemptSchema, attempt)) return malformedRegistry();
1249
+ const key = JSON.stringify([attempt.launcherSessionId, attempt.attemptId]);
1250
+ if (keys.has(key)) return malformedRegistry();
1251
+ keys.add(key);
1252
+ if (attempt.admission && attempt.admission.attemptId !== attempt.attemptId) return malformedRegistry();
1253
+ if (attempt.admission?.state === "registered" && attempt.admission.run.ownerSessionId !== attempt.sessionId) return malformedRegistry();
1254
+ }
1255
+ }
1256
+ if (Object.hasOwn(file, "sparoImport")) {
1257
+ const marker = file.sparoImport;
1258
+ if (file.version !== 2 || !marker || typeof marker !== "object" || Array.isArray(marker) || typeof marker.source !== "string" || !path.isAbsolute(marker.source) || typeof marker.sourceDigest !== "string" || !/^[a-f0-9]{64}$/u.test(marker.sourceDigest) || typeof marker.completedAt !== "string" || !Number.isFinite(Date.parse(marker.completedAt)) || !Array.isArray(marker.recordIds) || !marker.recordIds.every((id) => typeof id === "string" && id !== "")) return malformedRegistry();
1259
+ }
1260
+ return file.entries.map((value) => {
1261
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return malformedRegistry();
1262
+ const record = value;
1263
+ if (record.version !== file.version) return malformedRegistry();
1264
+ if (file.version === 1 && [
1265
+ "sparseProfile",
1266
+ "extraFolders",
1267
+ "sparseFingerprint"
1268
+ ].some((key) => Object.hasOwn(record, key))) return malformedRegistry();
1269
+ const normalized = {
1270
+ ...record,
1271
+ version: 2
1272
+ };
1273
+ if (!Check(WorktreeRecordSchema, normalized) || normalized.id === "") return malformedRegistry();
1274
+ if (Object.hasOwn(record, "sparseProfile") && !ProfileName.safeParse(record.sparseProfile).success) return malformedRegistry();
1275
+ if (Object.hasOwn(record, "extraFolders") && (!Array.isArray(record.extraFolders) || !record.extraFolders.every((folder) => ConeFolder.safeParse(folder).success))) return malformedRegistry();
1276
+ return normalized;
1277
+ });
1278
+ }
1279
+ /** Read metadata and records together, with the same fail-closed validation. */
1280
+ async function readWorktreeRegistryFile(file) {
1281
+ let text;
1282
+ try {
1283
+ text = await fs.readFile(file, "utf8");
1284
+ } catch (error) {
1285
+ if (error.code === "ENOENT") return {
1286
+ version: 2,
1287
+ entries: []
1288
+ };
1289
+ return malformedRegistry();
1290
+ }
1291
+ let parsed;
1292
+ try {
1293
+ parsed = JSON.parse(text);
1294
+ } catch {
1295
+ return malformedRegistry();
1296
+ }
1297
+ const entries = parseWorktreeRegistry(parsed);
1298
+ const { sparoImport } = parsed;
1299
+ const workflowAttempts = [...parsed.workflowAttempts ?? []];
1300
+ for (const record of entries) {
1301
+ if (!record.workflow || !record.parentSessionId || workflowAttempts.some((attempt) => attempt.launcherSessionId === record.parentSessionId && attempt.attemptId === record.workflow.attemptId)) continue;
1302
+ workflowAttempts.push({
1303
+ attemptId: record.workflow.attemptId,
1304
+ fingerprint: record.workflow.fingerprint,
1305
+ launcherSessionId: record.parentSessionId,
1306
+ branch: record.branch,
1307
+ createdAt: record.createdAt,
1308
+ state: record.workflow.state,
1309
+ worktreeId: record.id,
1310
+ sessionId: record.sessionId
1311
+ });
1312
+ }
1313
+ return {
1314
+ version: 2,
1315
+ entries,
1316
+ ...sparoImport ? { sparoImport } : {},
1317
+ ...workflowAttempts.length ? { workflowAttempts } : {}
1318
+ };
1319
+ }
1320
+ /**
1321
+ * Repository mutations hold an exclusive directory lock from the read through
1322
+ * the final commit. This works across independently loaded packages and hosts.
1323
+ * A crashed owner leaves a visible lock, never a lease another writer may steal.
1324
+ */
1325
+ function createWorktreeRegistry(file, options = {}) {
1326
+ return {
1327
+ async list() {
1328
+ return [...(await readWorktreeRegistryFile(file)).entries];
1329
+ },
1330
+ async workflowAttempts() {
1331
+ return [...(await readWorktreeRegistryFile(file)).workflowAttempts ?? []];
1332
+ },
1333
+ async replaceWorkflowAttempts(workflowAttempts) {
1334
+ const value = {
1335
+ ...await readWorktreeRegistryFile(file),
1336
+ workflowAttempts
1337
+ };
1338
+ parseWorktreeRegistry(value);
1339
+ await writeJsonAtomic(file, value);
1340
+ },
1341
+ async replace(entries) {
1342
+ const previous = await readWorktreeRegistryFile(file);
1343
+ const value = {
1344
+ version: 2,
1345
+ entries,
1346
+ ...previous.sparoImport ? { sparoImport: previous.sparoImport } : {},
1347
+ ...previous.workflowAttempts ? { workflowAttempts: previous.workflowAttempts } : {}
1348
+ };
1349
+ parseWorktreeRegistry(value);
1350
+ await writeJsonAtomic(file, value);
1351
+ },
1352
+ async transaction(operation, signal) {
1353
+ const lock = `${file}.lock`;
1354
+ if (options.createDirectory !== false) await fs.mkdir(path.dirname(file), { recursive: true });
1355
+ const deadline = Date.now() + LOCK_WAIT_MS;
1356
+ for (;;) {
1357
+ signal?.throwIfAborted();
1358
+ try {
1359
+ await fs.mkdir(lock, { mode: 448 });
1360
+ break;
1361
+ } catch (error) {
1362
+ if (error.code !== "EEXIST") throw error;
1363
+ if (Date.now() >= deadline) throw new PoGitExpectedError("registry_busy", "Another worktree operation holds the repository registry.", true, "Retry after it finishes. After a host crash, inspect and remove the abandoned worktrees.json.lock directory.");
1364
+ await setTimeout$1(LOCK_RETRY_MS, void 0, { signal });
1365
+ }
1366
+ }
1367
+ try {
1368
+ await fs.writeFile(path.join(lock, "owner.json"), JSON.stringify({
1369
+ pid: process.pid,
1370
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1371
+ }), { mode: 384 });
1372
+ signal?.throwIfAborted();
1373
+ return await operation();
1374
+ } finally {
1375
+ await fs.rm(lock, { recursive: true });
1376
+ }
1377
+ }
1378
+ };
1379
+ }
1380
+ //#endregion
1381
+ //#region src/services/sparoRegistryImport/index.ts
1382
+ function refuse(reason) {
1383
+ throw new Error(`Sparo registry import refused: ${reason}. No import was committed.`);
1384
+ }
1385
+ function sourceEntries(text) {
1386
+ let value;
1387
+ try {
1388
+ value = JSON.parse(text);
1389
+ } catch {
1390
+ return refuse("malformed source JSON");
1391
+ }
1392
+ if (!value || typeof value !== "object" || Array.isArray(value)) return refuse("malformed source registry");
1393
+ const file = value;
1394
+ if (file.version !== 2 || !Array.isArray(file.entries)) return refuse("expected Sparo v2 records");
1395
+ return parseWorktreeRegistry({
1396
+ version: 2,
1397
+ entries: file.entries.map((value) => {
1398
+ if (!value || typeof value !== "object" || Array.isArray(value)) return refuse("malformed source record");
1399
+ const record = value;
1400
+ if (record.version !== 2 || record.provider !== "po-sparo" || record.backend !== void 0) return refuse("unsupported source provider or backend");
1401
+ if (["sparseProfile", "sparseFingerprint"].some((key) => Object.hasOwn(record, key))) return refuse("source contains destination-only sparse fields");
1402
+ for (const key of [
1403
+ "baseCommit",
1404
+ "fingerprint",
1405
+ "reservationId"
1406
+ ]) if (Object.hasOwn(record, key) && (typeof record[key] !== "string" || record[key] === "")) return refuse(`invalid ${key}`);
1407
+ if (Object.hasOwn(record, "setupStage") && ![
1408
+ "none",
1409
+ "started",
1410
+ "failed"
1411
+ ].includes(String(record.setupStage))) return refuse("invalid setup stage");
1412
+ if (Object.hasOwn(record, "workflow")) {
1413
+ const workflow = record.workflow;
1414
+ if (!workflow || typeof workflow !== "object" || Array.isArray(workflow)) return refuse("invalid workflow");
1415
+ const evidence = workflow;
1416
+ for (const key of ["attemptId", "fingerprint"]) if (typeof evidence[key] !== "string" || evidence[key] === "") return refuse(`invalid workflow ${key}`);
1417
+ if (![
1418
+ "spawned",
1419
+ "admitted",
1420
+ "retained"
1421
+ ].includes(String(evidence.state))) return refuse("invalid workflow state");
1422
+ for (const key of [
1423
+ "admissionId",
1424
+ "runId",
1425
+ "reason"
1426
+ ]) if (Object.hasOwn(evidence, key) && typeof evidence[key] !== "string") return refuse(`invalid workflow ${key}`);
1427
+ }
1428
+ const { profile, fingerprint, ...preserved } = record;
1429
+ return {
1430
+ ...preserved,
1431
+ provider: "po-git",
1432
+ ...Object.hasOwn(record, "profile") ? { sparseProfile: profile } : {},
1433
+ ...Object.hasOwn(record, "fingerprint") ? { sparseFingerprint: fingerprint } : {}
1434
+ };
1435
+ })
1436
+ });
1437
+ }
1438
+ /**
1439
+ * The caller has stopped po-sparo. Destination lock is outermost; the source's
1440
+ * actual directory-lock protocol excludes a racing old writer through publish.
1441
+ * Only that transient source sidecar is touched, never its records or checkouts.
1442
+ */
1443
+ async function importSparoRegistry(options, source, destination, managedRoot) {
1444
+ const files = options.fs;
1445
+ const context = options.signal ? withAbortSignal(options.signal, BACKGROUND_CONTEXT) : BACKGROUND_CONTEXT;
1446
+ const canonical = async (file) => getOrThrow(await files.canonicalPath(file, context));
1447
+ const readText = async (file) => getOrThrow(await files.readTextFile(file, context));
1448
+ const inside = (root, candidate) => {
1449
+ const relative = path.relative(root, candidate);
1450
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1451
+ };
1452
+ if (options.sourceProviderStopped !== true) return refuse("stop the source provider before cutover");
1453
+ const result = {
1454
+ source,
1455
+ destination,
1456
+ imported: 0,
1457
+ duplicates: 0
1458
+ };
1459
+ return createWorktreeRegistry(destination).transaction(async () => {
1460
+ const current = await readWorktreeRegistryFile(destination);
1461
+ if (current.sparoImport) {
1462
+ if (current.sparoImport.source !== source) return refuse("completion belongs to a different source");
1463
+ return {
1464
+ ...result,
1465
+ status: "already-imported"
1466
+ };
1467
+ }
1468
+ const sourceInfo = await files.fileInfo(source, context);
1469
+ if (!sourceInfo.ok && sourceInfo.error.code === "not_found") return {
1470
+ ...result,
1471
+ status: "source-absent"
1472
+ };
1473
+ getOrThrow(sourceInfo);
1474
+ return createWorktreeRegistry(source, { createDirectory: false }).transaction(async () => {
1475
+ const snapshot = await readText(source);
1476
+ const imported = sourceEntries(snapshot);
1477
+ const common = await gitCommonDirectory(options.repositoryRoot);
1478
+ if (!common) return refuse("destination is not a Git repository");
1479
+ const identity = await canonical(common);
1480
+ const canonicalManagedRoot = imported.length ? await canonical(managedRoot) : managedRoot;
1481
+ const listed = await Promise.all((await options.git.listWorktreePaths(options.repositoryRoot)).map(async (entry) => {
1482
+ const resolved = await files.canonicalPath(entry, context);
1483
+ return !resolved.ok && resolved.error.code === "not_found" ? void 0 : getOrThrow(resolved);
1484
+ }));
1485
+ const membership = new Set(listed.filter((entry) => entry !== void 0));
1486
+ const combined = [...current.entries];
1487
+ for (const entry of imported) {
1488
+ options.signal?.throwIfAborted();
1489
+ if (!path.isAbsolute(entry.path) || !path.isAbsolute(entry.repositoryRoot)) return refuse("non-absolute path");
1490
+ const entryCommon = await gitCommonDirectory(entry.repositoryRoot);
1491
+ const checkoutCommon = await gitCommonDirectory(entry.path);
1492
+ if (!entryCommon || !checkoutCommon || await canonical(entryCommon) !== identity || await canonical(checkoutCommon) !== identity) return refuse(`wrong repository for '${entry.id}'`);
1493
+ const realPath = await canonical(entry.path);
1494
+ if (!inside(managedRoot, path.resolve(entry.path)) || !inside(canonicalManagedRoot, realPath)) return refuse(`'${entry.id}' is outside the admitted Sparo worktrees root`);
1495
+ if (getOrThrow(await files.fileInfo(path.join(realPath, ".git"), context)).kind !== "file") return refuse(`'${entry.id}' is not a linked worktree`);
1496
+ if (!membership.has(realPath)) return refuse(`Git does not list '${entry.id}'`);
1497
+ if (await options.git.currentBranch(entry.path) !== entry.branch) return refuse(`branch mismatch for '${entry.id}'`);
1498
+ if (!entry.sessionId || !Number.isFinite(Date.parse(entry.createdAt))) return refuse(`invalid ownership or timestamp for '${entry.id}'`);
1499
+ const collisions = [];
1500
+ for (const existing of combined) {
1501
+ const resolved = await files.canonicalPath(existing.path, context);
1502
+ const existingPath = !resolved.ok && resolved.error.code === "not_found" ? path.resolve(existing.path) : getOrThrow(resolved);
1503
+ if (existing.id === entry.id || existingPath === realPath || existing.sessionId === entry.sessionId || "reservationId" in entry && "reservationId" in existing && entry.reservationId === existing.reservationId) collisions.push(existing);
1504
+ }
1505
+ if (collisions.length) {
1506
+ if (collisions.length !== 1 || !isDeepStrictEqual(collisions[0], entry)) return refuse(`conflicting id, path or owner for '${entry.id}'`);
1507
+ result.duplicates++;
1508
+ } else {
1509
+ combined.push(entry);
1510
+ result.imported++;
1511
+ }
1512
+ }
1513
+ if (await readText(source) !== snapshot) return refuse("source changed during import");
1514
+ options.signal?.throwIfAborted();
1515
+ const value = {
1516
+ version: 2,
1517
+ entries: combined,
1518
+ ...current.workflowAttempts ? { workflowAttempts: current.workflowAttempts } : {},
1519
+ sparoImport: {
1520
+ source,
1521
+ sourceDigest: createHash("sha256").update(snapshot).digest("hex"),
1522
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
1523
+ recordIds: imported.map((entry) => entry.id)
1524
+ }
1525
+ };
1526
+ parseWorktreeRegistry(value);
1527
+ await writeJsonAtomic(destination, value);
1528
+ return {
1529
+ ...result,
1530
+ status: "imported"
1531
+ };
1532
+ }, options.signal);
1533
+ }, options.signal);
1534
+ }
1535
+ //#endregion
1536
+ //#region src/services/paths/index.ts
1537
+ /**
1538
+ * Where this package keeps its own state.
1539
+ *
1540
+ * Outside the repository on purpose. A worktree directory inside the checkout
1541
+ * would be found by every glob the repository's own tooling runs, and would
1542
+ * resolve workspace imports against the parent checkout rather than the
1543
+ * worktree, so a session there would build the wrong source while appearing to
1544
+ * work.
1545
+ */
1546
+ function poGitRoot(homeDir = os.homedir(), environment = {}) {
1547
+ return path.join(poHomeDirectory(homeDir, environment), "git");
1548
+ }
1549
+ /**
1550
+ * Deliberate operator cutover, never called by normal registry discovery.
1551
+ * Stop po-sparo first and pass admitted home/environment and Git capabilities.
1552
+ * Label migration completes first; the import then owns the canonical transaction,
1553
+ * even when the canonical registry already existed. No checkout is moved.
1554
+ */
1555
+ async function importSparoWorktrees(options) {
1556
+ if (!path.isAbsolute(options.homeDirectory) || !path.isAbsolute(options.repositoryRoot)) throw new Error("Sparo cutover requires explicit absolute home and repository roots.");
1557
+ if (!options.fs) throw new Error("Sparo cutover requires the admitted host filesystem.");
1558
+ if (!options.environment || options.sourceProviderStopped !== true) throw new Error("Sparo cutover requires an admitted environment and a stopped source provider.");
1559
+ const destination = await registryFile(options.repositoryRoot, options.homeDirectory, options.environment);
1560
+ return importSparoRegistry(options, path.join(poHomeDirectory(options.homeDirectory, options.environment), "sparo", "registry", await repositoryId(options.repositoryRoot), "worktrees.json"), destination, path.join(poHomeDirectory(options.homeDirectory, options.environment), "sparo", "worktrees"));
1561
+ }
1562
+ /** The directory every worktree for every repository is created under. */
1563
+ function worktreesRoot(homeDir = os.homedir(), environment = {}) {
1564
+ return path.join(poGitRoot(homeDir, environment), "worktrees");
1565
+ }
1566
+ /**
1567
+ * Remote auth for every workspace, one entry per workspace root.
1568
+ *
1569
+ * Outside every repository, so a token can never be committed, and readable
1570
+ * only by the owner. It holds secrets, which no other file here does.
1571
+ */
1572
+ function credentialsFile(homeDir = os.homedir(), environment = {}) {
1573
+ return path.join(poGitRoot(homeDir, environment), "credentials.json");
1574
+ }
1575
+ /** One registry file per repository, keyed by the shared git directory. */
1576
+ async function registryFile(repositoryRoot, homeDir = os.homedir(), environment = {}) {
1577
+ const id = await repositoryId(repositoryRoot);
1578
+ const root = path.join(poGitRoot(homeDir, environment), "registry");
1579
+ const canonical = path.join(root, id, "worktrees.json");
1580
+ if (await fs.access(canonical).then(() => true, () => false)) return canonical;
1581
+ let names;
1582
+ try {
1583
+ names = await fs.readdir(root);
1584
+ } catch {
1585
+ return canonical;
1586
+ }
1587
+ const legacyFiles = [];
1588
+ for (const entry of names.filter((name) => name.endsWith(`--${id}`)).sort()) {
1589
+ const file = path.join(root, entry, "worktrees.json");
1590
+ if (await fs.access(file).then(() => true, () => false)) legacyFiles.push(file);
1591
+ }
1592
+ if (legacyFiles.length === 0) return canonical;
1593
+ const entries = /* @__PURE__ */ new Map();
1594
+ const workflowAttempts = /* @__PURE__ */ new Map();
1595
+ for (const file of legacyFiles) {
1596
+ const snapshot = await readWorktreeRegistryFile(file);
1597
+ for (const attempt of snapshot.workflowAttempts ?? []) {
1598
+ const key = JSON.stringify([attempt.launcherSessionId, attempt.attemptId]);
1599
+ const previous = workflowAttempts.get(key);
1600
+ if (previous && !isDeepStrictEqual(previous, attempt)) throw new Error("Conflicting legacy workflow attempt metadata.");
1601
+ workflowAttempts.set(key, attempt);
1602
+ }
1603
+ for (const entry of snapshot.entries) {
1604
+ const existing = entries.get(entry.id);
1605
+ if (existing !== void 0 && !isDeepStrictEqual(existing, entry)) throw new Error(`Conflicting legacy worktree registry entries for '${entry.id}'.`);
1606
+ entries.set(entry.id, entry);
1607
+ }
1608
+ }
1609
+ const temporary = `${canonical}.${randomUUID()}.migration`;
1610
+ await writeJsonAtomic(temporary, {
1611
+ version: 2,
1612
+ entries: [...entries.values()],
1613
+ ...workflowAttempts.size ? { workflowAttempts: [...workflowAttempts.values()] } : {}
1614
+ });
1615
+ try {
1616
+ await fs.link(temporary, canonical);
1617
+ } catch (error) {
1618
+ if (error.code !== "EEXIST") throw error;
1619
+ } finally {
1620
+ await fs.rm(temporary);
1621
+ }
1622
+ return canonical;
1623
+ }
1624
+ //#endregion
1625
+ //#region src/services/riftCli/index.ts
1626
+ /** Present at a repository root, it makes worktrees Rift copy-on-write workspaces instead of git worktrees. */
1627
+ const RIFT_CONFIG_FILE = ".rift.toml";
1628
+ /** Rift's identity marker; a root without it was never `rift init`ed. */
1629
+ const RIFT_MARKER = ".rift";
1630
+ /** Cloning is instant, but `.rift.toml` hooks such as an install run inside create. */
1631
+ const CREATE_TIMEOUT_MS = 6e5;
1632
+ const REMOVE_TIMEOUT_MS = 3e5;
1633
+ /**
1634
+ * Runs the rift CLI. Stderr is dropped rather than piped: hooks inherit it and may keep it open
1635
+ * after rift exits (a `docker compose up -d`), and raw output never reaches a tool result anyway.
1636
+ */
1637
+ function rift(cwd, args, timeout) {
1638
+ return new Promise((resolve, reject) => {
1639
+ const child = spawn("rift", [...args], {
1640
+ cwd,
1641
+ stdio: [
1642
+ "ignore",
1643
+ "pipe",
1644
+ "ignore"
1645
+ ],
1646
+ timeout
1647
+ });
1648
+ let stdout = "";
1649
+ child.stdout.on("data", (chunk) => stdout += String(chunk));
1650
+ child.on("error", (error) => reject(error.code === "ENOENT" ? new PoGitExpectedError("rift_missing", `This repository has ${RIFT_CONFIG_FILE}, but the rift CLI is not installed.`, false, `Install it with \`${RIFT_INSTALL_COMMAND}\`, run \`rift init\` in the repository root, then try again. An agent asks the person with ask_user_question before installing. Removing ${RIFT_CONFIG_FILE} falls back to git worktrees.`) : error));
1651
+ child.on("exit", (code) => resolve({
1652
+ code: code ?? 1,
1653
+ stdout
1654
+ }));
1655
+ });
1656
+ }
1657
+ const exists = (file) => fs.access(file).then(() => true, () => false);
1658
+ function createWorktreeRift() {
1659
+ const remove = async (target) => {
1660
+ if (!await exists(target)) return;
1661
+ const result = await rift(path.dirname(target), ["remove", target], REMOVE_TIMEOUT_MS);
1662
+ if (result.code !== 0) throw new Error(`rift remove failed (exit ${String(result.code)})`);
1663
+ };
1664
+ return {
1665
+ enabled: (repositoryRoot) => exists(path.join(repositoryRoot, RIFT_CONFIG_FILE)),
1666
+ async create({ repositoryRoot, path: target, branch, baseRef, existing, remote }) {
1667
+ if (!await exists(path.join(repositoryRoot, RIFT_MARKER))) {
1668
+ await rift(repositoryRoot, ["--help"], READ_TIMEOUT_MS);
1669
+ throw new PoGitExpectedError("invalid_request", `This repository has ${RIFT_CONFIG_FILE}, but Rift is not initialized for ${repositoryRoot}.`, false, "Run `rift init` in the repository root (not inside a git worktree), then try again.");
1670
+ }
1671
+ if (await exists(target)) throw new Error(`The worktree path ${target} already exists.`);
1672
+ await fs.mkdir(path.dirname(target), { recursive: true });
1673
+ const created = await rift(repositoryRoot, [
1674
+ "create",
1675
+ repositoryRoot,
1676
+ "--into",
1677
+ path.dirname(target),
1678
+ "--name",
1679
+ path.basename(target),
1680
+ "--copy-all"
1681
+ ], CREATE_TIMEOUT_MS);
1682
+ if (created.code !== 0) {
1683
+ await remove(target).catch(() => void 0);
1684
+ throw new Error(`rift create failed (exit ${String(created.code)})`);
1685
+ }
1686
+ const switchArgs = existing ? remote === void 0 ? [
1687
+ "switch",
1688
+ "--discard-changes",
1689
+ branch
1690
+ ] : [
1691
+ "switch",
1692
+ "--discard-changes",
1693
+ "--track",
1694
+ "-c",
1695
+ branch,
1696
+ `${remote}/${branch}`
1697
+ ] : [
1698
+ "switch",
1699
+ "--discard-changes",
1700
+ "-c",
1701
+ branch,
1702
+ baseRef
1703
+ ];
1704
+ for (const args of [switchArgs, ["clean", "-fd"]]) {
1705
+ const result = await runGit(target, args, { timeout: READ_TIMEOUT_MS });
1706
+ if (result.code !== 0) {
1707
+ await remove(target).catch(() => void 0);
1708
+ throw new Error(`git ${String(args[0])} in the rift failed (exit ${String(result.code)})`);
1709
+ }
1710
+ }
1711
+ },
1712
+ remove,
1713
+ async fetchBranch({ repositoryRoot, path: source, branch }) {
1714
+ const result = await runGit(repositoryRoot, [
1715
+ "fetch",
1716
+ source,
1717
+ `refs/heads/${branch}:refs/heads/${branch}`
1718
+ ], { timeout: READ_TIMEOUT_MS });
1719
+ if (result.code !== 0) throw new Error(`git fetch from the rift failed (exit ${String(result.code)})`);
1720
+ }
1721
+ };
1722
+ }
1723
+ //#endregion
1724
+ //#region src/services/worktreeNaming/index.ts
1725
+ const MAX_SLUG_LENGTH = 64;
1726
+ /** Anything git forbids in a ref, plus a leading `-` that `worktree add` would read as an option. */
1727
+ const INVALID_REF = /(^[-/.])|[\s~^:?*[\\]|\.\.|@\{|\/\/|\/\.|\.lock$|\/$|\.$/u;
1728
+ const MAX_REF_LENGTH = 255;
1729
+ const FIRST_PRINTABLE = 32;
1730
+ const DELETE = 127;
1731
+ /**
1732
+ * A branch name reduced to one safe path segment.
1733
+ *
1734
+ * Slashes are the point: `wt/fix-auth` is a perfectly good branch and a
1735
+ * terrible directory name, because the nested directory it implies is not the
1736
+ * one the worktree lives in.
1737
+ */
1738
+ function branchSlug(branch) {
1739
+ const slug = branch.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, MAX_SLUG_LENGTH).replace(/-+$/gu, "");
1740
+ return slug === "" ? "worktree" : slug;
1741
+ }
1742
+ /**
1743
+ * The directory for one worktree.
1744
+ *
1745
+ * The short id disambiguates two branches whose slugs collide, such as
1746
+ * `feature/x` and `feature_x`, which would otherwise want the same directory.
1747
+ */
1748
+ function worktreeDirectory(input) {
1749
+ const repository = `${input.repositoryLabel}--${input.repositoryId}`;
1750
+ return `${input.worktreesRoot}/${repository}/${branchSlug(input.branch)}--${input.shortId}`;
1751
+ }
1752
+ /** Why a worktree cannot be created, or undefined when it can. */
1753
+ function refuseSpawn(input) {
1754
+ if (input.branch.trim() === "") return "A branch name is required.";
1755
+ const live = input.existing.find((record) => record.branch === input.branch && record.status !== "orphaned");
1756
+ if (live) return `Branch ${input.branch} already has a worktree (${live.id}).`;
1757
+ }
1758
+ /** Why a worktree cannot be closed, or undefined when it can. */
1759
+ function refuseClose(input) {
1760
+ if (!input.record) return "No worktree with that id. Call list to see the current ids.";
1761
+ if (input.dirtyFiles.length === 0 || input.force) return void 0;
1762
+ const names = input.dirtyFiles.slice(0, 10).join(", ");
1763
+ const more = input.dirtyFiles.length > 10 ? `, and ${String(input.dirtyFiles.length - 10)} more` : "";
1764
+ return `${String(input.dirtyFiles.length)} uncommitted file(s): ${names}${more}. Pass force: true to discard them.`;
1765
+ }
1766
+ /**
1767
+ * Marks records whose process or directory is gone as orphaned.
1768
+ *
1769
+ * Nothing is deleted here. A po-git orphan owns a directory that may hold
1770
+ * uncommitted work, so losing the record would lose the only pointer to it.
1771
+ * Deletion is always a separate, named decision.
1772
+ */
1773
+ async function reconcile(records, probe) {
1774
+ const changed = [];
1775
+ const next = [];
1776
+ for (const record of records) {
1777
+ if (record.status === "orphaned" || await probe.exists(record.path) && probe.alive(record)) {
1778
+ next.push(record);
1779
+ continue;
1780
+ }
1781
+ changed.push(record.id);
1782
+ next.push({
1783
+ ...record,
1784
+ status: "orphaned"
1785
+ });
1786
+ }
1787
+ return {
1788
+ records: next,
1789
+ changed
1790
+ };
1791
+ }
1792
+ /**
1793
+ * What a prune would do, decided before anything is destroyed.
1794
+ *
1795
+ * Separating the plan from the execution is what makes dryRun honest and lets
1796
+ * the destructive half be reviewed on its own.
1797
+ */
1798
+ function planPrune(input) {
1799
+ const plan = {
1800
+ remove: [],
1801
+ forget: [],
1802
+ untracked: [],
1803
+ keptDirty: [],
1804
+ keptBranches: []
1805
+ };
1806
+ const known = new Set(input.records.map((record) => record.path));
1807
+ const listed = new Set(input.gitPaths);
1808
+ for (const record of input.records) {
1809
+ if (record.status !== "orphaned") continue;
1810
+ if (!listed.has(record.path)) {
1811
+ plan.forget.push(record);
1812
+ continue;
1813
+ }
1814
+ if ((input.dirtyByPath.get(record.path) ?? []).length > 0) {
1815
+ plan.keptDirty.push(record);
1816
+ continue;
1817
+ }
1818
+ plan.remove.push(record);
1819
+ }
1820
+ for (const path of input.gitPaths) if (path.startsWith(`${input.worktreesRoot}/`) && !known.has(path)) plan.untracked.push(path);
1821
+ return plan;
1822
+ }
1823
+ /** Whether a user-supplied branch or base ref is safe to hand to git as a positional argument. */
1824
+ function validRefName(name) {
1825
+ if (name === "" || name === "@" || name.length > MAX_REF_LENGTH || INVALID_REF.test(name)) return false;
1826
+ for (const character of name) {
1827
+ const code = character.charCodeAt(0);
1828
+ if (code < FIRST_PRINTABLE || code === DELETE) return false;
1829
+ }
1830
+ return true;
1831
+ }
1832
+ //#endregion
1833
+ //#region src/services/worktreeOperations/index.ts
1834
+ const GIT_WORKTREE_DELEGATION_KIND = "git.worktree.delegation";
1835
+ const GIT_WORKTREE_MESSAGE_KIND = "git.worktree.message";
1836
+ const GIT_WORKTREE_REPORT_KIND = "git.worktree.report";
1837
+ function createWorktreeOperations(deps) {
1838
+ const { git } = deps;
1839
+ const readConfig = deps.worktreeConfig ?? createWorktreeConfigReader({ readTextFile: (file) => fs.readFile(file, "utf8") });
1840
+ const rift = deps.rift ?? createWorktreeRift();
1841
+ const sessionService = deps.sessionService;
1842
+ const now = deps.now ?? (() => /* @__PURE__ */ new Date());
1843
+ const requireSessionService = () => {
1844
+ if (sessionService === void 0) throw new HubUnavailableError("The cockpit session service is unavailable. Start the cockpit and try again.");
1845
+ return sessionService;
1846
+ };
1847
+ const requireMessageInbox = () => {
1848
+ if (deps.messageInbox === void 0) throw new HubUnavailableError("The Git message service is unavailable. Start the cockpit and try again.");
1849
+ return deps.messageInbox;
1850
+ };
1851
+ const readSessionDelivery = () => deps.sessionDelivery?.();
1852
+ const requireSessionDelivery = () => {
1853
+ const delivery = readSessionDelivery();
1854
+ if (delivery === void 0) throw new HubUnavailableError("The Session delivery service is unavailable. Start the cockpit and try again.");
1855
+ return delivery;
1856
+ };
1857
+ const probe = {
1858
+ alive: (record) => requireSessionService().isLive(record.sessionId),
1859
+ exists: (path) => fs.access(path).then(() => true, () => false)
1860
+ };
1861
+ /** What git lists as worktrees, plus Rift workspaces, which git cannot see. */
1862
+ const listedPaths = async (root, records) => {
1863
+ const rifts = records.filter((record) => record.backend === "rift");
1864
+ const present = await Promise.all(rifts.map((record) => probe.exists(record.path)));
1865
+ return [...await git.listWorktreePaths(root), ...rifts.filter((_, index) => present[index]).map((r) => r.path)];
1866
+ };
1867
+ const removeCheckout = (root, record, force) => record.backend === "rift" ? rift.remove(record.path) : git.removeWorktree({
1868
+ repositoryRoot: root,
1869
+ path: record.path,
1870
+ force
1871
+ });
1872
+ /**
1873
+ * Everything an action needs about the repository it is acting on.
1874
+ *
1875
+ * Resolved per call rather than cached: a session's cwd is stable, but the
1876
+ * worktree registry is shared and another process may have written it since
1877
+ * the last call.
1878
+ */
1879
+ const resolve = async (context) => {
1880
+ const root = await git.repositoryRoot(context.cwd);
1881
+ if (root === void 0) throw new PoGitExpectedError("not_a_repository", `${context.cwd} is not inside a git repository.`, false, "Run this from a repository checkout.");
1882
+ const store = createWorktreeRegistry(await registryFile(root, deps.homeDir, deps.environment));
1883
+ return {
1884
+ root,
1885
+ store,
1886
+ records: await store.list()
1887
+ };
1888
+ };
1889
+ const require = (records, id) => {
1890
+ const record = records.find((entry) => entry.id === id);
1891
+ if (record === void 0) throw new PoGitExpectedError("worktree_not_found", `No worktree with id ${id}.`, false, "Call list to see the current ids.");
1892
+ return record;
1893
+ };
1894
+ /**
1895
+ * Refuses to destroy or merge a worktree another live session is using.
1896
+ *
1897
+ * `parentSessionId` records who asked for the worktree. Two sessions in one
1898
+ * checkout share this registry, so without the check either could close the
1899
+ * other's work in progress by id.
1900
+ *
1901
+ * Once that session is gone there is no owner left to protect, and refusing
1902
+ * would strand the worktree: nothing else could ever close it.
1903
+ */
1904
+ const requireOwner = (context, record, action) => {
1905
+ if (record.parentSessionId === context.sessionId) return;
1906
+ if (record.parentSessionId === void 0 || !requireSessionService().isLive(record.parentSessionId)) return;
1907
+ throw new PoGitExpectedError("worktree_not_owned", `Worktree ${record.id} belongs to another session.`, false, `Ask the session that created it to ${action} it, or close that session first.`);
1908
+ };
1909
+ const peerFor = (context, record) => {
1910
+ if (record.parentSessionId === void 0) throw new PoGitExpectedError("worktree_peer_unavailable", `Worktree ${record.id} was opened on its own and has no parent session to message.`, false, "Message a worktree this session created.");
1911
+ if (context.sessionId === record.parentSessionId) return {
1912
+ sessionId: record.sessionId,
1913
+ party: "parent"
1914
+ };
1915
+ if (context.sessionId === record.sessionId) return {
1916
+ sessionId: record.parentSessionId,
1917
+ party: "child"
1918
+ };
1919
+ throw new PoGitExpectedError("worktree_not_owned", `Worktree ${record.id} belongs to another session.`, false, "Use a worktree owned by this session.");
1920
+ };
1921
+ const requirePeerLive = (peerSessionId) => {
1922
+ if (!requireSessionService().isLive(peerSessionId)) throw new PoGitExpectedError("worktree_peer_unavailable", "The other worktree session is no longer live.", false, "Start a new worktree session before sending a message.");
1923
+ };
1924
+ const operation = (options) => ({
1925
+ environment: deps.environment ?? {},
1926
+ signal: AbortSignal.any([...deps.signal ? [deps.signal] : [], ...options?.signal ? [options.signal] : []])
1927
+ });
1928
+ const engine = () => {
1929
+ const service = deps.gitEngine?.();
1930
+ if (!service) throw new PoGitExpectedError("invalid_request", "Sparse checkout requires po/git-engine.", false, "Enable the Git engine workspace service.");
1931
+ return service;
1932
+ };
1933
+ const fingerprint = async (root, config, ref, options) => {
1934
+ const policy = config.sparse;
1935
+ const request = operation(options);
1936
+ const names = await engine().profiles(root, policy, request, ref);
1937
+ const blobs = await Promise.all(names.filter((name) => name !== "full").map(async (name) => [profilePath(name, policy), await revision(root, `${ref}:${profilePath(name, policy)}`, {
1938
+ env: request.environment,
1939
+ signal: request.signal
1940
+ })]));
1941
+ return createHash("sha256").update(JSON.stringify([policy, blobs])).digest("hex");
1942
+ };
1943
+ const sparseMutation = async (context, id, folders, options) => {
1944
+ const { store, records } = await resolve(context);
1945
+ const record = require(records, id);
1946
+ if (context.sessionId !== record.sessionId) requireOwner(context, record, folders ? "expand" : "reapply");
1947
+ if (!record.sparseProfile) throw new PoGitExpectedError("invalid_request", "This worktree has no sparse profile.", false, "Choose a sparse worktree.");
1948
+ const config = await readConfig(record.repositoryRoot);
1949
+ if (!config.sparse) throw new PoGitExpectedError("invalid_request", "Sparse policy is not configured.", false, "Restore the worktree sparse configuration.");
1950
+ const result = folders ? await engine().expand(record.path, folders, config.sparse, operation(options)) : await engine().reapply(record.path, config.sparse, operation(options));
1951
+ const updated = {
1952
+ ...record,
1953
+ extraFolders: [.../* @__PURE__ */ new Set([...record.extraFolders ?? [], ...folders ?? []])].sort(),
1954
+ sparseFingerprint: await fingerprint(record.path, config, "HEAD", options)
1955
+ };
1956
+ await store.replace(records.map((entry) => entry.id === id ? updated : entry));
1957
+ return {
1958
+ ...updated,
1959
+ coneFolders: result.coneFolders
1960
+ };
1961
+ };
1962
+ const operations = {
1963
+ async profiles(context, baseRef, options) {
1964
+ if (baseRef !== void 0 && !validRefName(baseRef)) throw new PoGitExpectedError("invalid_request", "The profile base ref is invalid.", false, "Use a valid Git ref.");
1965
+ const { root } = await resolve(context);
1966
+ const config = await readConfig(root);
1967
+ if (!config.sparse) return {};
1968
+ const ref = baseRef ?? await git.remoteBaseRef(root) ?? "HEAD";
1969
+ return {
1970
+ sparseProfiles: await engine().profiles(root, config.sparse, operation(options), ref),
1971
+ ...config.defaults?.sparseProfile ? { defaultSparseProfile: config.defaults.sparseProfile } : {}
1972
+ };
1973
+ },
1974
+ expand: (context, id, folders, options) => sparseMutation(context, id, folders, options),
1975
+ reapply: (context, id, options) => sparseMutation(context, id, void 0, options),
1976
+ async spawn(context, request, options) {
1977
+ const parentSessionId = context.sessionId;
1978
+ const parented = parentSessionId === void 0 ? {} : { parentSessionId };
1979
+ const { root, store, records } = await resolve(context);
1980
+ const reservations = request.reservationId === void 0 ? void 0 : requireSessionService().reservations;
1981
+ if (request.reservationId !== void 0 && (!reservations || request.task !== void 0)) throw new PoGitExpectedError("invalid_request", "Reserved worktree sessions require host setup and cannot start a task.", false, "Create the session from its pending setup card.");
1982
+ const reserved = request.reservationId === void 0 ? void 0 : reservations.read(request.reservationId, parentSessionId);
1983
+ const existing = reserved === void 0 ? void 0 : records.find((record) => record.sessionId === reserved.sessionId);
1984
+ if (existing) {
1985
+ const expectedPath = worktreeDirectory({
1986
+ worktreesRoot: worktreesRoot(deps.homeDir, deps.environment),
1987
+ repositoryLabel: repositoryLabel(root),
1988
+ repositoryId: await repositoryId(root),
1989
+ branch: request.branch,
1990
+ shortId: shortId(reserved.sessionId)
1991
+ });
1992
+ if (existing.parentSessionId !== parentSessionId || existing.repositoryRoot !== root || existing.branch !== request.branch || existing.path !== expectedPath || existing.path !== reserved?.cwd || request.baseRef !== void 0 && existing.baseRef !== request.baseRef || !await probe.exists(existing.path) || !(await listedPaths(root, records)).includes(existing.path) || await git.repositoryRoot(existing.path) !== existing.path || await git.currentBranch(existing.path) !== request.branch) throw new PoGitExpectedError("invalid_request", "The reserved checkout no longer matches this setup.", false, "Inspect the existing branch and checkout; they will not be replaced.");
1993
+ if (!requireSessionService().isLive(existing.sessionId)) {
1994
+ if ((await requireSessionService().create({
1995
+ cwd: existing.path,
1996
+ name: request.name ?? request.branch,
1997
+ parentSessionId,
1998
+ sessionProvenance: "worktree",
1999
+ reservationId: request.reservationId,
2000
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
2001
+ })).sessionId !== existing.sessionId) throw new Error("The host did not use the reserved session identity.");
2002
+ }
2003
+ await reservations.complete(request.reservationId, parentSessionId);
2004
+ return existing;
2005
+ }
2006
+ const refusal = refuseSpawn({
2007
+ branch: request.branch,
2008
+ existing: records
2009
+ });
2010
+ if (refusal !== void 0) throw new PoGitExpectedError("worktree_exists", refusal, false, "Pick another branch name, or close it.");
2011
+ const taskDelivery = request.task === void 0 ? void 0 : requireSessionDelivery();
2012
+ const config = await readConfig(root);
2013
+ const setup = options?.workflow ? void 0 : config.setup;
2014
+ const sparseProfile = config.sparse ? config.defaults?.sparseProfile ?? request.sparseProfile : void 0;
2015
+ if (request.sparseProfile !== void 0 && (!config.sparse || config.defaults?.sparseProfile !== void 0 && request.sparseProfile !== config.defaults.sparseProfile)) throw new PoGitExpectedError("invalid_request", "The sparse profile does not match the workspace configuration.", false, "Use the workspace sparse default.");
2016
+ let setupCommand = setup;
2017
+ if (setup !== void 0 && sparseProfile !== void 0) {
2018
+ const cli = deps.sparoCliPath?.();
2019
+ if (!cli || !path.isAbsolute(cli) || cli.includes("\0")) throw new PoGitExpectedError("invalid_request", "The installed Sparo setup CLI is unavailable.", false, "Repair the plugin installation before creating this checkout.");
2020
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
2021
+ const policy = JSON.stringify(SparsePolicy.parse(config.sparse));
2022
+ setupCommand = `${quote(cli)} --policy-json ${quote(policy)} install . && ${setup}`;
2023
+ }
2024
+ const useRift = sparseProfile === void 0 && await rift.enabled(root);
2025
+ const existingBranch = request.checkout === "existing";
2026
+ const id = shortId(reserved?.sessionId ?? randomUUID());
2027
+ let path$1 = worktreeDirectory({
2028
+ worktreesRoot: worktreesRoot(deps.homeDir, deps.environment),
2029
+ repositoryLabel: repositoryLabel(root),
2030
+ repositoryId: await repositoryId(root),
2031
+ branch: request.branch,
2032
+ shortId: id
2033
+ });
2034
+ if (request.reservationId !== void 0) path$1 = (await reservations.prepare(request.reservationId, parentSessionId, path$1)).cwd;
2035
+ const recovering = reserved?.cwd !== void 0 && await probe.exists(path$1);
2036
+ if (recovering && (!(useRift ? await git.repositoryRoot(path$1) === path$1 : (await git.listWorktreePaths(root)).includes(path$1)) || await git.currentBranch(path$1) !== request.branch)) throw new PoGitExpectedError("invalid_request", "The reserved checkout no longer matches this setup.", false, "Inspect the existing directory; it will not be replaced.");
2037
+ if (!recovering) {
2038
+ if (existingBranch) {
2039
+ const branches = await git.listBranches(root);
2040
+ const local = branches.local.find((branch) => branch.name === request.branch);
2041
+ if (!(request.remote === void 0 ? local !== void 0 && local.checkedOutAt === void 0 : local === void 0 && branches.remote.some((branch) => branch.remote === request.remote && branch.name === request.branch))) throw new PoGitExpectedError("invalid_request", local?.checkedOutAt === void 0 ? `The branch ${request.branch} is not available to check out.` : `The branch ${request.branch} is already checked out at ${local.checkedOutAt}.`, false, "Pick another branch, or create a new one.");
2042
+ } else if ((await git.listBranches(root)).local.some((branch) => branch.name === request.branch)) throw new PoGitExpectedError("invalid_request", `The branch ${request.branch} already exists.`, false, "Pick another name, or open it as an existing branch.");
2043
+ }
2044
+ const baseRef = existingBranch ? request.remote === void 0 ? request.branch : `${request.remote}/${request.branch}` : request.baseRef ?? await git.remoteBaseRef(root);
2045
+ if (baseRef === void 0) throw new PoGitExpectedError("git_failed", "No remote base branch is available for this repository.", false, "Fetch a remote branch or pass an explicit baseRef.");
2046
+ const cancelled = () => options?.signal?.aborted === true;
2047
+ const rollback = async () => {
2048
+ if (reserved) return ` The reserved checkout at ${path$1} was retained for recovery.`;
2049
+ await removeCheckout(root, {
2050
+ path: path$1,
2051
+ ...useRift ? { backend: "rift" } : {}
2052
+ }, true).catch(() => void 0);
2053
+ if (useRift) return "";
2054
+ if (existingBranch && request.remote === void 0) return "";
2055
+ return await git.deleteBranch({
2056
+ repositoryRoot: root,
2057
+ branch: request.branch
2058
+ }).catch(() => false) ? "" : ` The branch ${request.branch} has work on it and was kept.`;
2059
+ };
2060
+ const workflowBaseCommit = options?.workflow ? await revision(root, baseRef, {
2061
+ env: deps.environment ?? {},
2062
+ signal: operation(options).signal
2063
+ }) : void 0;
2064
+ options?.onProgress?.(`creating branch ${request.branch}\u2026`);
2065
+ let coneFolders;
2066
+ let sparseFingerprint;
2067
+ if (!recovering) {
2068
+ if (sparseProfile !== void 0) {
2069
+ sparseFingerprint = await fingerprint(root, config, baseRef, options);
2070
+ try {
2071
+ coneFolders = (await engine().create({
2072
+ repoRoot: root,
2073
+ path: path$1,
2074
+ branch: request.branch,
2075
+ base: baseRef,
2076
+ profile: sparseProfile,
2077
+ extraFolders: config.defaults?.extraFolders ?? [],
2078
+ install: false
2079
+ }, config.sparse, operation(options))).coneFolders;
2080
+ if (existingBranch && request.remote !== void 0) await trackBranch(path$1, request.branch, baseRef, {
2081
+ env: deps.environment ?? {},
2082
+ signal: operation(options).signal
2083
+ });
2084
+ } catch (error) {
2085
+ await rollback();
2086
+ throw error;
2087
+ }
2088
+ } else if (useRift) await rift.create({
2089
+ repositoryRoot: root,
2090
+ path: path$1,
2091
+ branch: request.branch,
2092
+ baseRef,
2093
+ existing: existingBranch,
2094
+ ...request.remote === void 0 ? {} : { remote: request.remote }
2095
+ });
2096
+ else if (existingBranch) await git.addExistingWorktree({
2097
+ repositoryRoot: root,
2098
+ path: path$1,
2099
+ branch: request.branch,
2100
+ ...request.remote === void 0 ? {} : { remote: request.remote }
2101
+ });
2102
+ else await git.addWorktree({
2103
+ repositoryRoot: root,
2104
+ path: path$1,
2105
+ branch: request.branch,
2106
+ baseRef
2107
+ });
2108
+ }
2109
+ if (cancelled()) throw new PoGitExpectedError("spawn_cancelled", `Cancelled before the session started.${await rollback()}`, false, reserved ? "Retry setup with the same branch to recover the reserved checkout." : "The worktree was removed; run it again when you are ready.");
2110
+ options?.onProgress?.("starting session…");
2111
+ let sessionId;
2112
+ try {
2113
+ sessionId = (await requireSessionService().create({
2114
+ cwd: path$1,
2115
+ name: request.name ?? request.branch,
2116
+ ...parented,
2117
+ sessionProvenance: "worktree",
2118
+ ...options?.preset === void 0 ? request.selection === void 0 ? {} : { selection: request.selection } : { selection: { preset: options.preset } },
2119
+ ...options?.signal === void 0 ? {} : { signal: options.signal },
2120
+ ...request.reservationId === void 0 ? {} : { reservationId: request.reservationId }
2121
+ })).sessionId;
2122
+ if (reserved && sessionId !== reserved.sessionId) throw new Error("The host did not use the reserved session identity.");
2123
+ } catch (error) {
2124
+ const kept = await rollback();
2125
+ if (cancelled()) throw new PoGitExpectedError("spawn_cancelled", `Cancelled while the session was starting.${kept}`, false, reserved ? "Retry setup with the same branch to recover the reserved checkout." : "The worktree was removed; run it again when you are ready.");
2126
+ if (error instanceof HubUnavailableError) throw new PoGitExpectedError("hub_unavailable", `${error.message}${kept}`, true, "Start the cockpit and try again.");
2127
+ throw error;
2128
+ }
2129
+ const record = {
2130
+ version: 2,
2131
+ id,
2132
+ branch: request.branch,
2133
+ baseRef,
2134
+ path: path$1,
2135
+ repositoryRoot: root,
2136
+ sessionId,
2137
+ ...parented,
2138
+ status: "running",
2139
+ setupStage: setup === void 0 ? "none" : "unconfirmed",
2140
+ ...sparseProfile === void 0 ? {} : {
2141
+ sparseProfile,
2142
+ extraFolders: config.defaults?.extraFolders ?? [],
2143
+ sparseFingerprint
2144
+ },
2145
+ ...useRift ? { backend: "rift" } : {},
2146
+ createdAt: now().toISOString(),
2147
+ ...options?.workflow ? {
2148
+ baseCommit: workflowBaseCommit,
2149
+ workflow: {
2150
+ ...options.workflow,
2151
+ state: "spawned"
2152
+ }
2153
+ } : {}
2154
+ };
2155
+ try {
2156
+ await store.replace([...records, record]);
2157
+ } catch (error) {
2158
+ await requireSessionService().close(sessionId).catch(() => void 0);
2159
+ const kept = await rollback();
2160
+ throw new PoGitExpectedError("registry_write_failed", `The worktree was created but the registry could not be written (${error.message}).${kept}`, true, "Check the registry file for permissions or free space, then try again.");
2161
+ }
2162
+ if (setupCommand !== void 0) {
2163
+ try {
2164
+ const stage = await deps.startSetup?.(sessionId, setupCommand, operation(options).signal);
2165
+ record.setupStage = stage === "started" || stage === "failed" ? stage : "unconfirmed";
2166
+ } catch {
2167
+ record.setupStage = operation(options).signal.aborted ? "unconfirmed" : "failed";
2168
+ }
2169
+ await store.replace([...records, record]);
2170
+ if (record.setupStage !== "started") options?.onProgress?.(`worktree setup ${record.setupStage}; inspect worktree-setup before deciding whether to retry. Do not retry automatically.`);
2171
+ }
2172
+ const setupStarted = record.setupStage === "started";
2173
+ if (request.task !== void 0 && taskDelivery !== void 0) try {
2174
+ const receipt = await taskDelivery.deliver({
2175
+ recipientKey: sessionId,
2176
+ kind: GIT_WORKTREE_DELEGATION_KIND,
2177
+ prompt: setupStarted ? `${request.task}\n\nThe worktree setup (${setup}) is running as the runner "worktree-setup". Check it with po-runner before relying on installed dependencies or builds.` : setup === void 0 ? request.task : `${request.task}\n\nThe worktree setup handoff is ${record.setupStage}. Inspect the runner "worktree-setup" before relying on dependencies or deciding whether to retry. Do not retry automatically.`,
2178
+ metadata: {
2179
+ worktreeId: record.id,
2180
+ fromRole: "parent",
2181
+ text: request.task,
2182
+ sentAt: record.createdAt
2183
+ }
2184
+ });
2185
+ const admission = await taskDelivery.waitForAdmission(receipt.deliveryId);
2186
+ if (admission !== "admitted") throw new PoGitExpectedError("task_delivery_failed", `Worktree ${record.id} was created and task delivery ${receipt.deliveryId} was persisted, but admission ${admission === "recovery_required" ? "requires recovery" : "was not confirmed before the timeout"}.`, true, admission === "recovery_required" ? `Call messages from worktree ${record.id} to recover the task in the recipient session. Do not resend it automatically.` : `Check delivery ${receipt.deliveryId} in the sender outbox or call messages from worktree ${record.id} in the recipient session before deciding whether to resend.`);
2187
+ } catch (error) {
2188
+ if (error instanceof PoGitExpectedError) throw error;
2189
+ throw new PoGitExpectedError("task_delivery_failed", `Worktree ${record.id} was created, but task delivery failed (${String(error)}).`, true, `Inspect worktree ${record.id} and the sender outbox before using send to deliver the task. Do not recreate the worktree.`);
2190
+ }
2191
+ if (request.reservationId !== void 0) await reservations.complete(request.reservationId, parentSessionId);
2192
+ return coneFolders === void 0 ? record : {
2193
+ ...record,
2194
+ coneFolders
2195
+ };
2196
+ },
2197
+ async linkWorkflow(context, id, workflow) {
2198
+ const { store, records } = await resolve(context);
2199
+ const record = require(records, id);
2200
+ if (record.parentSessionId !== context.sessionId || record.workflow?.attemptId !== workflow.attemptId || record.workflow.fingerprint !== workflow.fingerprint) throw new PoGitExpectedError("invalid_request", "The workflow does not own this checkout.", false, "Inspect the recorded workflow owner.");
2201
+ if (record.workflow.admissionId && record.workflow.admissionId !== workflow.admissionId || record.workflow.runId && record.workflow.runId !== workflow.runId || record.workflow.state === "retained" && workflow.state !== "retained") throw new PoGitExpectedError("invalid_request", "The workflow admission or terminal identity changed.", false, "Keep and inspect the recorded workflow.");
2202
+ const updated = {
2203
+ ...record,
2204
+ workflow
2205
+ };
2206
+ await store.replace(records.map((entry) => entry.id === id ? updated : entry));
2207
+ return updated;
2208
+ },
2209
+ async close(context, id, force, expectedWorkflow) {
2210
+ const { root, store, records } = await resolve(context);
2211
+ const record = require(records, id);
2212
+ requireOwner(context, record, "close");
2213
+ if (expectedWorkflow && (record.status !== "running" || record.workflow?.state !== "admitted" || record.sessionId !== expectedWorkflow.sessionId || record.path !== expectedWorkflow.path || await revision(record.path, "HEAD", {
2214
+ env: deps.environment ?? {},
2215
+ signal: operation().signal
2216
+ }) !== expectedWorkflow.head || record.parentSessionId !== context.sessionId || [
2217
+ "attemptId",
2218
+ "fingerprint",
2219
+ "admissionId",
2220
+ "runId"
2221
+ ].some((key) => record.workflow?.[key] !== expectedWorkflow[key]))) throw new PoGitExpectedError("invalid_request", "The workflow checkout evidence changed.", false, "Keep and inspect this checkout.");
2222
+ const refusal = refuseClose({
2223
+ record,
2224
+ dirtyFiles: await probe.exists(record.path) ? await git.dirtyFiles(record.path) : [],
2225
+ force
2226
+ });
2227
+ if (refusal !== void 0) throw new PoGitExpectedError("worktree_dirty", refusal, false, "Commit the work, or pass force: true.");
2228
+ await requireSessionService().close(record.sessionId);
2229
+ await removeCheckout(root, record, force);
2230
+ await store.replace(records.filter((entry) => entry.id !== id));
2231
+ return record;
2232
+ },
2233
+ async list(context) {
2234
+ const { store, records } = await resolve(context);
2235
+ const outcome = await reconcile(records, probe);
2236
+ if (outcome.changed.length > 0) await store.replace(outcome.records);
2237
+ return outcome.records;
2238
+ },
2239
+ async status(context, id) {
2240
+ const { records } = await resolve(context);
2241
+ const record = require(records, id);
2242
+ return {
2243
+ record,
2244
+ dirtyFiles: await probe.exists(record.path) ? await git.dirtyFiles(record.path) : []
2245
+ };
2246
+ },
2247
+ async merge(context, id, message) {
2248
+ const { root, records } = await resolve(context);
2249
+ const record = require(records, id);
2250
+ requireOwner(context, record, "merge");
2251
+ const parentDirty = await git.dirtyFiles(root);
2252
+ if (parentDirty.length > 0) throw new PoGitExpectedError("worktree_dirty", `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(", ")}.`, false, "Commit or stash the parent checkout first.");
2253
+ if (record.backend === "rift") await rift.fetchBranch({
2254
+ repositoryRoot: root,
2255
+ path: record.path,
2256
+ branch: record.branch
2257
+ });
2258
+ await git.mergeBranch({
2259
+ repositoryRoot: root,
2260
+ branch: record.branch,
2261
+ ...message === void 0 ? {} : { message }
2262
+ });
2263
+ return record;
2264
+ },
2265
+ /** Sends only between the parent session and its own worktree session. */
2266
+ async send(context, id, message) {
2267
+ if (Buffer.byteLength(message, "utf8") > 65536) throw new PoGitExpectedError("message_too_large", `A message may not exceed ${String(MAX_WORKTREE_MESSAGE_BYTES)} bytes.`, false, "Send a shorter message.");
2268
+ const { records } = await resolve(context);
2269
+ const record = require(records, id);
2270
+ const peer = peerFor(context, record);
2271
+ requirePeerLive(peer.sessionId);
2272
+ const sentAt = (/* @__PURE__ */ new Date()).toISOString();
2273
+ const delivery = readSessionDelivery();
2274
+ if (delivery !== void 0) {
2275
+ const kind = peer.party === "parent" ? GIT_WORKTREE_MESSAGE_KIND : GIT_WORKTREE_REPORT_KIND;
2276
+ const receipt = await delivery.deliver({
2277
+ recipientKey: peer.sessionId,
2278
+ kind,
2279
+ prompt: peer.party === "parent" ? `Parent message for worktree ${record.id}:\n\n${message}` : `Report from worktree ${record.id}:\n\n${message}`,
2280
+ metadata: {
2281
+ worktreeId: record.id,
2282
+ fromRole: peer.party,
2283
+ text: message,
2284
+ sentAt
2285
+ }
2286
+ });
2287
+ const admission = await delivery.waitForAdmission(receipt.deliveryId);
2288
+ if (admission !== "admitted") throw new PoGitExpectedError("message_delivery_failed", `Worktree ${record.id} persisted message delivery ${receipt.deliveryId}, but admission ${admission === "recovery_required" ? "requires recovery" : "was not confirmed before the timeout"}.`, true, admission === "recovery_required" ? `Call messages from the recipient session to recover delivery ${receipt.deliveryId}. Do not resend it automatically.` : `Check delivery ${receipt.deliveryId} in the sender outbox or call messages from the recipient session before deciding whether to resend.`);
2289
+ return;
2290
+ }
2291
+ requireMessageInbox().send(peer.sessionId, {
2292
+ version: 1,
2293
+ worktreeId: record.id,
2294
+ fromSessionId: context.sessionId,
2295
+ from: peer.party,
2296
+ text: message,
2297
+ sentAt
2298
+ });
2299
+ },
2300
+ async messages(context, id) {
2301
+ const { records } = await resolve(context);
2302
+ const record = require(records, id);
2303
+ const peer = peerFor(context, record);
2304
+ const delivery = readSessionDelivery();
2305
+ if (delivery === void 0) return requireMessageInbox().receive(record.id);
2306
+ const entries = (await delivery.inbox({
2307
+ consumed: false,
2308
+ metadata: { worktreeId: record.id }
2309
+ })).filter((entry) => entry.senderKey === peer.sessionId && (entry.state === "admitted" || entry.state === "recovery_required") && (peer.party === "parent" ? entry.kind === GIT_WORKTREE_REPORT_KIND : entry.kind === GIT_WORKTREE_MESSAGE_KIND || entry.kind === GIT_WORKTREE_DELEGATION_KIND));
2310
+ for (const entry of entries) await delivery.consume(entry.deliveryId);
2311
+ return entries.map((entry) => ({
2312
+ version: 1,
2313
+ worktreeId: record.id,
2314
+ fromSessionId: entry.senderKey,
2315
+ from: peer.party === "parent" ? "child" : "parent",
2316
+ text: entry.state === "recovery_required" ? `[Recovery required: prompt admission was not confirmed] ${entry.metadata.text ?? entry.prompt}` : entry.metadata.text ?? entry.prompt,
2317
+ sentAt: entry.metadata.sentAt ?? ""
2318
+ }));
2319
+ },
2320
+ async prune(context, dryRun) {
2321
+ const { root, store, records } = await resolve(context);
2322
+ const reconciled = await reconcile(records, probe);
2323
+ const gitPaths = await listedPaths(root, reconciled.records);
2324
+ const dirtyByPath = /* @__PURE__ */ new Map();
2325
+ for (const record of reconciled.records) if (record.status === "orphaned" && await probe.exists(record.path)) dirtyByPath.set(record.path, await git.dirtyFiles(record.path));
2326
+ const plan = planPrune({
2327
+ records: reconciled.records,
2328
+ gitPaths,
2329
+ worktreesRoot: worktreesRoot(deps.homeDir, deps.environment),
2330
+ dirtyByPath
2331
+ });
2332
+ if (dryRun) {
2333
+ await store.replace(reconciled.records);
2334
+ return plan;
2335
+ }
2336
+ for (const record of plan.remove) await removeCheckout(root, record, false);
2337
+ for (const record of [...plan.remove, ...plan.forget]) if (!await git.deleteBranch({
2338
+ repositoryRoot: root,
2339
+ branch: record.branch
2340
+ }).catch(() => false) && record.backend !== "rift") plan.keptBranches.push(record.branch);
2341
+ const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));
2342
+ await store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));
2343
+ return plan;
2344
+ }
2345
+ };
2346
+ const locked = async (context, operation, signal) => {
2347
+ try {
2348
+ const { store } = await resolve(context);
2349
+ return await store.transaction(operation, signal);
2350
+ } catch (error) {
2351
+ if (signal?.aborted && !(error instanceof PoGitExpectedError)) throw new PoGitExpectedError("spawn_cancelled", "The worktree operation was cancelled.", false, "Inspect its recorded state before retrying.");
2352
+ if (error instanceof SparoError && error.code !== "COMMAND_FAILED") throw new PoGitExpectedError("invalid_request", error.message, false, "Run sparo init explicitly before sparse checkout, or fix the configured profile.");
2353
+ if ([
2354
+ "ENOTDIR",
2355
+ "EACCES",
2356
+ "EROFS",
2357
+ "ENOSPC"
2358
+ ].includes(String(error.code))) throw new PoGitExpectedError("registry_write_failed", "The worktree registry is not writable.", true, "Check permissions and free space before retrying.");
2359
+ throw error;
2360
+ }
2361
+ };
2362
+ return {
2363
+ ...operations,
2364
+ spawn: (context, request, options) => {
2365
+ if (sessionService === void 0) return Promise.reject(new PoGitExpectedError("hub_unavailable", "The cockpit session service is unavailable.", true, "Use the cockpit worktree tool after its Git server plugin is available."));
2366
+ if (request.sparseProfile !== void 0 && !validSparseProfile(request.sparseProfile) || !validRefName(request.branch) || request.baseRef !== void 0 && !validRefName(request.baseRef)) return Promise.reject(new PoGitExpectedError("invalid_request", "That is not a valid branch name.", false, "Pick another name."));
2367
+ if (request.reservationId !== void 0 && context.sessionId === void 0) return Promise.reject(new PoGitExpectedError("invalid_request", "A reserved worktree session requires its owning parent.", false, "Create the session from its pending setup card."));
2368
+ return locked(context, () => operations.spawn(context, request, options), options?.signal);
2369
+ },
2370
+ expand: (context, id, folders, options) => {
2371
+ if (!Array.isArray(folders) || folders.length === 0 || !folders.every((folder) => ConeFolder.safeParse(folder).success)) return Promise.reject(new PoGitExpectedError("invalid_request", "Pass nonempty relative cone folders.", false, "Use repository-relative folders."));
2372
+ return locked(context, () => operations.expand(context, id, folders, options), options?.signal);
2373
+ },
2374
+ reapply: (context, id, options) => locked(context, () => operations.reapply(context, id, options), options?.signal),
2375
+ linkWorkflow: (context, id, workflow) => locked(context, () => operations.linkWorkflow(context, id, workflow)),
2376
+ close: (context, id, force, expectedWorkflow) => locked(context, () => operations.close(context, id, force, expectedWorkflow)),
2377
+ list: (context) => locked(context, () => operations.list(context)),
2378
+ merge: (context, id, message) => locked(context, () => operations.merge(context, id, message)),
2379
+ prune: (context, dryRun) => locked(context, () => operations.prune(context, dryRun))
2380
+ };
2381
+ }
2382
+ //#endregion
2383
+ //#region src/services/gitDependencies/index.ts
2384
+ function createGitDependencies(overrides = {}) {
2385
+ return {
2386
+ service: overrides.service ?? new DefaultGitExtensionService(),
2387
+ operations: overrides.operations ?? createWorktreeOperations({ git: createWorktreeGit() })
2388
+ };
2389
+ }
2390
+ /** One admitted environment and config snapshot per session or API composition. */
2391
+ function createGitOperationDependencies({ context, host, signal }, scope = host.context) {
2392
+ let files;
2393
+ let gitEngine;
2394
+ context.inject([PO_FS_SERVICE], (child) => {
2395
+ files = requirePoFs(child);
2396
+ return () => {
2397
+ files = void 0;
2398
+ };
2399
+ });
2400
+ context.inject([PO_GIT_ENGINE_SERVICE], (child) => {
2401
+ gitEngine = child.get(PO_GIT_ENGINE_SERVICE);
2402
+ return () => {
2403
+ gitEngine = void 0;
2404
+ };
2405
+ });
2406
+ return {
2407
+ gitEngine: () => gitEngine,
2408
+ sparoCliPath: () => createRequire(import.meta.url).resolve("@agimon-ai/po-sparo/bin/cli"),
2409
+ startSetup: (sessionId, command, setupSignal) => host.context.directEvents ? startWorktreeSetup(host.context.directEvents, sessionId, command, setupSignal) : Promise.resolve("unconfirmed"),
2410
+ environment: scope.environment ?? {},
2411
+ homeDir: host.context.homeDirectory,
2412
+ signal,
2413
+ worktreeConfig: createWorktreeConfigReader({
2414
+ async readTextFile(file) {
2415
+ if (!files) throw new Error("The Git host filesystem is unavailable.");
2416
+ const result = await files.readTextFile(file, withAbortSignal(signal, BACKGROUND_CONTEXT));
2417
+ if (!result.ok) throw result.error;
2418
+ return result.value;
2419
+ },
2420
+ async readMetadata() {
2421
+ const registry = readPoWorkspaceRegistry(context);
2422
+ if (!scope.workspaceId || !registry) return void 0;
2423
+ const result = await registry.resolve({ id: scope.workspaceId });
2424
+ return result.status === "found" ? result.workspace.metadata : void 0;
2425
+ }
2426
+ })
2427
+ };
2428
+ }
2429
+ //#endregion
2430
+ export { NETWORK_TIMEOUT_MS as A, PoGitExpectedError as C, GIT_REVIEW_FILE_PATH as D, GIT_BRANCHES_PATH as E, revision as F, runGit as I, GIT_ENGINE_CONTRACT as L, REBASE_TIMEOUT_MS as M, createWorktreeGit as N, GIT_REVIEW_PATH as O, remoteBranchHead as P, DefaultGitExtensionService as R, HubUnavailableError as S, GIT_AUTH_PATH as T, createWorktreeMessageInbox as _, credentialsFile as a, receiveWorktreeSetup as b, registryFile as c, PO_GIT_WORKFLOWS_SERVICE as d, StartWorktreeWorkflowSchema as f, GIT_WORKTREE_LIFECYCLE_EVENT as g, GIT_SESSION_CHANGED_EVENT as h, validRefName as i, READ_TIMEOUT_MS as j, GIT_SESSIONS_PATH as k, createWorktreeRegistry as l, writeJsonAtomic as m, createGitOperationDependencies as n, importSparoWorktrees as o, readJson as p, createWorktreeOperations as r, poGitRoot as s, createGitDependencies as t, GIT_WORKFLOWS_CONTRACT as u, isSessionChangedEvent as v, invalidRequest as w, validSparseProfile as x, isWorktreeLifecycleEvent as y };
2431
+
2432
+ //# sourceMappingURL=gitDependencies-Delu4xip.mjs.map