@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.5

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 (95) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +26 -1
  3. package/dist/alpd.js +29928 -14898
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +34 -1
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +154 -2
  12. package/dist/files.js +392 -68
  13. package/dist/git.d.ts +93 -0
  14. package/dist/git.js +1192 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +7 -1
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +43 -11
  24. package/dist/native-terminal.d.ts +45 -0
  25. package/dist/native-terminal.js +198 -0
  26. package/dist/operations.d.ts +8 -2
  27. package/dist/operations.js +20 -10
  28. package/dist/registry.d.ts +89 -0
  29. package/dist/registry.js +343 -0
  30. package/dist/scheduler.d.ts +96 -0
  31. package/dist/scheduler.js +296 -0
  32. package/dist/schedules.d.ts +70 -0
  33. package/dist/schedules.js +246 -0
  34. package/dist/server.d.ts +14 -2
  35. package/dist/server.js +836 -90
  36. package/dist/store.d.ts +72 -2
  37. package/dist/store.js +111 -4
  38. package/dist/terminal-native/README.md +201 -0
  39. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  40. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  41. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  42. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  43. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  44. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  45. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  46. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  48. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  51. package/dist/terminal-native/terminal-owner.c +389 -0
  52. package/dist/terminal-screen.d.ts +24 -0
  53. package/dist/terminal-screen.js +99 -0
  54. package/dist/terminals.d.ts +193 -0
  55. package/dist/terminals.js +570 -0
  56. package/dist/windows-terminal.d.ts +29 -0
  57. package/dist/windows-terminal.js +122 -0
  58. package/dist/worktrees.d.ts +65 -0
  59. package/dist/worktrees.js +318 -0
  60. package/native/README.md +201 -0
  61. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  62. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  63. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  64. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  65. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  66. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  67. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  68. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  69. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  70. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  71. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  72. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  73. package/native/terminal-owner.c +389 -0
  74. package/package.json +70 -7
  75. package/src/attachments.ts +908 -0
  76. package/src/conversation.ts +857 -0
  77. package/src/disk.ts +175 -0
  78. package/src/files.ts +528 -82
  79. package/src/git.ts +1140 -0
  80. package/src/gitignore.ts +10 -0
  81. package/src/history.ts +118 -0
  82. package/src/index.ts +7 -0
  83. package/src/lifecycle.ts +283 -0
  84. package/src/main.ts +37 -12
  85. package/src/native-terminal.ts +122 -0
  86. package/src/operations.ts +27 -11
  87. package/src/registry.ts +238 -0
  88. package/src/scheduler.ts +432 -0
  89. package/src/schedules.ts +297 -0
  90. package/src/server.ts +948 -102
  91. package/src/store.ts +117 -4
  92. package/src/terminal-screen.ts +74 -0
  93. package/src/terminals.ts +641 -0
  94. package/src/windows-terminal.ts +123 -0
  95. package/src/worktrees.ts +382 -0
@@ -0,0 +1,122 @@
1
+ // packages/daemon/src/windows-terminal.ts
2
+ import { existsSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ function packagedNodePty() {
6
+ const assets = globalThis[Symbol.for("alp.packaged")]?.assetDir?.();
7
+ const entry = assets ? path.join(assets, "node-pty", "lib", "index.js") : void 0;
8
+ return entry && existsSync(entry) ? entry : void 0;
9
+ }
10
+ var loaded;
11
+ function loadNodePty() {
12
+ if (loaded === void 0) {
13
+ try {
14
+ loaded = createRequire(import.meta.url)(packagedNodePty() ?? "node-pty");
15
+ } catch {
16
+ loaded = null;
17
+ }
18
+ }
19
+ return loaded ?? void 0;
20
+ }
21
+ function windowsTerminalCapability() {
22
+ return loadNodePty() ? { available: true, protection: "none" } : { available: false, reason: "node_pty_unavailable" };
23
+ }
24
+ function windowsShell(env = process.env) {
25
+ const candidate = env.ComSpec ?? env.COMSPEC;
26
+ return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : "cmd.exe";
27
+ }
28
+ var windowsPtySpawn = (file, args, options) => {
29
+ if (options.signal?.aborted) throw new Error("Terminal startup cancelled");
30
+ const pty = loadNodePty();
31
+ if (!pty) throw new Error("node-pty is unavailable on this host");
32
+ const spawnOptions = { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true, ...packagedNodePty() ? { useConptyDll: true } : {} };
33
+ const child = typeof process.versions.bun === "string" ? spawnUnderBun(pty, file, args, spawnOptions) : pty.spawn(file, args, spawnOptions);
34
+ let killed = false;
35
+ return {
36
+ pid: child.pid,
37
+ write(data) {
38
+ if (!killed) child.write(data);
39
+ },
40
+ resize(cols, rows) {
41
+ if (!killed) try {
42
+ child.resize(cols, rows);
43
+ } catch {
44
+ }
45
+ },
46
+ // Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
47
+ kill() {
48
+ if (killed) return;
49
+ killed = true;
50
+ try {
51
+ child.kill();
52
+ } catch {
53
+ }
54
+ },
55
+ onData: (listener) => child.onData(listener),
56
+ onExit: (listener) => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal }))
57
+ };
58
+ };
59
+ function spawnUnderBun(pty, file, args, options) {
60
+ const load = createRequire(import.meta.url);
61
+ const fs = load("node:fs");
62
+ const net = load("node:net");
63
+ const Socket = net.Socket;
64
+ function InputSocket(...rest) {
65
+ const [opts] = rest;
66
+ if (opts && typeof opts.fd === "number" && opts.writable === true && opts.readable === false) return fdWriter(fs, opts.fd);
67
+ return new Socket(...rest);
68
+ }
69
+ InputSocket.prototype = Socket.prototype;
70
+ net.Socket = InputSocket;
71
+ try {
72
+ return pty.spawn(file, args, options);
73
+ } finally {
74
+ net.Socket = Socket;
75
+ }
76
+ }
77
+ function fdWriter(fs, fd) {
78
+ let queue = Promise.resolve();
79
+ let closed = false;
80
+ let failed = false;
81
+ const writer = {
82
+ readable: false,
83
+ writable: true,
84
+ setEncoding() {
85
+ return writer;
86
+ },
87
+ write(data) {
88
+ if (closed || failed) return false;
89
+ const bytes = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
90
+ queue = queue.then(() => new Promise((resolve) => {
91
+ const rest = (offset) => {
92
+ if (closed || failed || offset >= bytes.length) return resolve();
93
+ fs.write(fd, bytes, offset, bytes.length - offset, null, (error, written) => {
94
+ if (error) {
95
+ failed = true;
96
+ writer.writable = false;
97
+ return resolve();
98
+ }
99
+ rest(offset + written);
100
+ });
101
+ };
102
+ rest(0);
103
+ }));
104
+ return true;
105
+ },
106
+ destroy() {
107
+ if (closed) return writer;
108
+ closed = true;
109
+ writer.writable = false;
110
+ void queue.then(() => fs.close(fd, () => {
111
+ }));
112
+ return writer;
113
+ }
114
+ };
115
+ return writer;
116
+ }
117
+ export {
118
+ loadNodePty,
119
+ windowsPtySpawn,
120
+ windowsShell,
121
+ windowsTerminalCapability
122
+ };
@@ -0,0 +1,65 @@
1
+ import { type RegistryService, type WorkspaceRecord } from './registry.js';
2
+ type Mapping = {
3
+ id: string;
4
+ source: string;
5
+ commonDir: string;
6
+ parent: string;
7
+ };
8
+ type Context = {
9
+ principalId?: string;
10
+ principalEpoch?: string;
11
+ mappingIds?: string[];
12
+ authorizedRoots?: string[];
13
+ };
14
+ /** What the owner confirms before a legacy managed worktree is adopted (t-c1ba), each proven from Git and the filesystem. */
15
+ export type AdoptionFacts = {
16
+ workspaceId: string;
17
+ directory: string;
18
+ source: string;
19
+ commonDir: string;
20
+ gitDir: string;
21
+ branch: string;
22
+ head: string;
23
+ };
24
+ /** Owner-only file; neither an RPC parameter nor repository configuration can approve a destination. */
25
+ export declare function worktreeMappings(home: string): Promise<Mapping[]>;
26
+ export declare function createWorkspaceWorktrees(home: string, registry: RegistryService, guard: <T>(directory: string, run: () => Promise<T>) => Promise<T>, register: (directory: string) => Promise<void>, adoptWorkspace?: (directory: string, verify: (canonical: string) => Promise<void>) => Promise<void>): {
27
+ describe(w: WorkspaceRecord): Promise<{
28
+ managedWorktree?: boolean | undefined;
29
+ branch: string | null;
30
+ id: string;
31
+ projectId: string;
32
+ directory: string;
33
+ canonical?: string;
34
+ title?: string | null;
35
+ pinnedAt?: string | null;
36
+ labels: string[];
37
+ createdAt: string;
38
+ archivedAt?: string | null;
39
+ idempotencyKey?: string;
40
+ }>;
41
+ /** What adopting this legacy managed worktree would certify (t-c1ba); it changes nothing. */
42
+ adoption(workspaceId: string, context?: Context): Promise<AdoptionFacts>;
43
+ /**
44
+ * Certifies a managed worktree that predates birth certification, once the owner confirmed the
45
+ * facts `adoption` showed. The facts are proven again under the runtime's removal guard, which
46
+ * also refuses any checkout an assignment, claim, lease or session still owns. Removal stays a
47
+ * separate request with all of its own checks.
48
+ */
49
+ adopt(p: {
50
+ workspaceId: string;
51
+ confirm: AdoptionFacts;
52
+ }, context?: Context): Promise<{
53
+ adopted: AdoptionFacts;
54
+ }>;
55
+ assertAvailable(directory: string): Promise<void>;
56
+ grants(context?: Context): Promise<{
57
+ mappings: {
58
+ id: string;
59
+ source: string;
60
+ }[];
61
+ workspaces: WorkspaceRecord[];
62
+ }>;
63
+ mutate(method: "create" | "remove", p: any, context?: Context): Promise<any>;
64
+ };
65
+ export {};
@@ -0,0 +1,318 @@
1
+ // packages/daemon/src/worktrees.ts
2
+ import { randomBytes } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { lstat, mkdir, open, readFile, realpath, stat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { user_worktree } from "@anhlp/alp-core";
7
+ import { RegistryError } from "./registry.js";
8
+ var fail = (reason, message, code = 1004) => {
9
+ throw new RegistryError(code, message, { reason });
10
+ };
11
+ var git = user_worktree.userWorktreeGit;
12
+ async function worktreeMappings(home) {
13
+ const file = path.join(home, "worktree-destinations.json");
14
+ const info = await lstat(file).catch((e) => {
15
+ if (e.code === "ENOENT") return void 0;
16
+ throw e;
17
+ });
18
+ if (!info) return [];
19
+ if (!info.isFile() || process.platform !== "win32" && (info.uid !== process.getuid?.() || info.mode & 63))
20
+ fail("mapping_invalid", "Worktree destination configuration must be private", 1005);
21
+ const value = JSON.parse(await readFile(file, "utf8"));
22
+ if (value?.version !== 1 || !Array.isArray(value.mappings))
23
+ fail("mapping_invalid", "Invalid worktree destination configuration", 1005);
24
+ const ids = /* @__PURE__ */ new Set();
25
+ for (const m of value.mappings) {
26
+ if (!m || typeof m.id !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(m.id) || ids.has(m.id))
27
+ fail("mapping_invalid", "Invalid mapping identity", 1005);
28
+ ids.add(m.id);
29
+ for (const k of ["source", "commonDir", "parent"]) {
30
+ if (typeof m[k] !== "string" || !path.isAbsolute(m[k]) || await realpath(m[k]) !== m[k] || !(await stat(m[k])).isDirectory())
31
+ fail("mapping_invalid", "Mapping paths must be existing canonical directories", 1005);
32
+ }
33
+ const parentInfo = await stat(m.parent);
34
+ if (process.platform !== "win32" && (parentInfo.uid !== process.getuid?.() || parentInfo.mode & 63))
35
+ fail("mapping_invalid", "Destination parent must be owner-private", 1005);
36
+ for (const reserved of [path.join(home, "worktrees"), path.join(home, "copies"), m.commonDir])
37
+ if (m.parent === reserved || m.parent.startsWith(reserved + path.sep) || reserved.startsWith(m.parent + path.sep))
38
+ fail("mapping_invalid", "Destination overlaps protected assignment or Git storage", 1005);
39
+ if (m.parent === m.source || m.parent.startsWith(m.source + path.sep) || m.source.startsWith(m.parent + path.sep))
40
+ fail("mapping_invalid", "Destination parent must be separate from source", 1005);
41
+ }
42
+ return value.mappings;
43
+ }
44
+ function createWorkspaceWorktrees(home, registry, guard, register, adoptWorkspace) {
45
+ const adapter = git();
46
+ async function approved(context, source, mappingId, native = true) {
47
+ const m = (await worktreeMappings(home)).find((m2) => m2.id === mappingId && m2.source === source);
48
+ if (!m) return fail("outside_workspace", "Mapping unavailable", 1003);
49
+ if (context.mappingIds && !context.mappingIds.includes(m.id) || context.authorizedRoots && !context.authorizedRoots.includes(source))
50
+ fail("outside_workspace", "Worktree mapping is not approved for this credential", 1003);
51
+ if ((await (native ? adapter.facts(source) : user_worktree.repositoryIdentity(source))).commonDir !== m.commonDir)
52
+ fail("identity_changed", "Source repository identity changed", 1003);
53
+ return m;
54
+ }
55
+ const workspace = (r, id) => r.workspaces.find((w) => w.id === id) ?? fail("not_found", "No workspace", 1001);
56
+ async function sourceOf(r, id) {
57
+ const w = workspace(r, id);
58
+ if (w.archivedAt || w.worktree?.removedAt || r.projects.find((p) => p.id === w.projectId)?.removedAt)
59
+ fail("not_found", "Workspace unavailable", 1001);
60
+ if (await realpath(w.directory) !== (w.canonical ?? w.directory))
61
+ fail("identity_changed", "Source identity changed", 1003);
62
+ return w;
63
+ }
64
+ async function adoptionFacts(r, id) {
65
+ const w = workspace(r, id);
66
+ const meta = w.worktree;
67
+ if (!meta || meta.kind !== "user" || meta.removedAt || w.archivedAt)
68
+ return fail("not_managed", "Only a present managed user worktree can be adopted", 1003);
69
+ if (Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === w.id))
70
+ fail("reconciliation_required", "Workspace is pending reconciliation");
71
+ const mapping = (await worktreeMappings(home)).find(
72
+ (m) => m.id === meta.mappingId && m.source === meta.source && m.commonDir === meta.commonDir
73
+ );
74
+ if (!mapping) return fail("outside_workspace", "The host does not approve its destination mapping now", 1003);
75
+ const directory = path.join(mapping.parent, w.id);
76
+ const branch = `alp/workspace/${w.id}`;
77
+ if (!/^wks_[0-9a-f]{16}$/.test(w.id) || w.directory !== directory || (w.canonical ?? w.directory) !== directory || meta.branch !== branch)
78
+ fail("identity_changed", "Not a generated managed worktree", 1003);
79
+ const info = await lstat(directory).catch(() => void 0);
80
+ if (!info?.isDirectory() || await realpath(directory).catch(() => void 0) !== directory)
81
+ fail("identity_changed", "Managed worktree path is missing or not canonical", 1003);
82
+ const origin = await adapter.facts(mapping.source).catch(() => void 0);
83
+ if (origin?.commonDir !== mapping.commonDir) fail("identity_changed", "Source repository identity changed", 1003);
84
+ const row = await adapter.inspect(mapping.source, directory, branch).catch(() => void 0);
85
+ const target = row ? await adapter.facts(directory).catch(() => void 0) : void 0;
86
+ if (!row || !target || target.commonDir !== mapping.commonDir || target.gitDir === target.commonDir || target.gitDir !== meta.gitDir || target.branch !== branch || row.HEAD !== target.head)
87
+ return fail("identity_changed", "Git does not list it as this managed worktree", 1003);
88
+ return { workspaceId: w.id, directory, source: mapping.source, commonDir: mapping.commonDir, gitDir: target.gitDir, branch, head: target.head };
89
+ }
90
+ const owner = (context) => {
91
+ if ((context.principalId ?? "owner") !== "owner" || (context.principalEpoch ?? "owner") !== "owner" || context.mappingIds || context.authorizedRoots)
92
+ fail("owner_only", "Only the host owner adopts a workspace", 1003);
93
+ };
94
+ async function audit(entry) {
95
+ const file = path.join(home, "state", "workspace-adoptions.jsonl");
96
+ await mkdir(path.dirname(file), { recursive: true, mode: 448 });
97
+ const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 384);
98
+ try {
99
+ await handle.writeFile(JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry }) + "\n");
100
+ } finally {
101
+ await handle.close();
102
+ }
103
+ }
104
+ async function clean(source, target, branch, head) {
105
+ if (!await adapter.inspect(source, target, branch))
106
+ fail("outcome_unknown", "Worktree creation needs owner reconciliation", 1005);
107
+ if ((await adapter.facts(target)).head !== head) fail("outcome_unknown", "Prepared worktree HEAD changed", 1005);
108
+ await adapter.assertClean(target);
109
+ }
110
+ return {
111
+ async describe(w) {
112
+ const { worktree, ...row } = w;
113
+ let branch = null;
114
+ try {
115
+ const canonical = await realpath(w.directory);
116
+ if (canonical === (w.canonical ?? w.directory))
117
+ branch = (await user_worktree.repositoryIdentity(canonical)).branch;
118
+ } catch {
119
+ }
120
+ return { ...row, branch, ...worktree ? { managedWorktree: true } : {} };
121
+ },
122
+ /** What adopting this legacy managed worktree would certify (t-c1ba); it changes nothing. */
123
+ async adoption(workspaceId, context = {}) {
124
+ owner(context);
125
+ return adoptionFacts(await registry.snapshot(), workspaceId);
126
+ },
127
+ /**
128
+ * Certifies a managed worktree that predates birth certification, once the owner confirmed the
129
+ * facts `adoption` showed. The facts are proven again under the runtime's removal guard, which
130
+ * also refuses any checkout an assignment, claim, lease or session still owns. Removal stays a
131
+ * separate request with all of its own checks.
132
+ */
133
+ async adopt(p, context = {}) {
134
+ owner(context);
135
+ if (!adoptWorkspace) return fail("guard_unavailable", "Runtime cannot prove safe adoption", 1005);
136
+ const confirmed = (facts2) => !!p.confirm && typeof p.confirm === "object" && Object.keys(p.confirm).length === Object.keys(facts2).length && Object.keys(facts2).every((k) => p.confirm[k] === facts2[k]);
137
+ const facts = await adoptionFacts(await registry.snapshot(), p.workspaceId);
138
+ if (!confirmed(facts)) fail("confirmation_mismatch", "The workspace differs from what was confirmed; review it and confirm again", 1003);
139
+ await audit({ event: "adoption.requested", actor: "owner", ...facts });
140
+ try {
141
+ await adoptWorkspace(facts.directory, async () => {
142
+ if (!confirmed(await adoptionFacts(await registry.snapshot(), p.workspaceId)))
143
+ fail("confirmation_mismatch", "The workspace changed after it was confirmed; review it and confirm again", 1003);
144
+ });
145
+ } catch (error) {
146
+ await audit({ event: "adoption.refused", actor: "owner", workspaceId: facts.workspaceId, reason: error?.data?.reason ?? "failed", error: error?.message ?? String(error) }).catch(() => {
147
+ });
148
+ throw error;
149
+ }
150
+ await audit({ event: "adoption.certified", actor: "owner", workspaceId: facts.workspaceId, directory: facts.directory });
151
+ return { adopted: facts };
152
+ },
153
+ async assertAvailable(directory) {
154
+ const r = await registry.snapshot();
155
+ const canonical = await realpath(directory).catch(() => path.resolve(directory));
156
+ if (Object.values(r.worktreeJournal ?? {}).some(
157
+ (j) => canonical === j.intent.directory || canonical.startsWith(j.intent.directory + path.sep)
158
+ ))
159
+ fail("reconciliation_required", "Workspace is pending reconciliation");
160
+ },
161
+ async grants(context = {}) {
162
+ const r = await registry.snapshot();
163
+ const mappings = [];
164
+ for (const m of await worktreeMappings(home)) {
165
+ try {
166
+ await approved(context, m.source, m.id, false);
167
+ mappings.push(m);
168
+ } catch {
169
+ }
170
+ }
171
+ const workspaces = [];
172
+ for (const w of r.workspaces) {
173
+ const m = w.worktree;
174
+ if (!m || m.principalId !== (context.principalId ?? "owner") || m.grantEpoch !== (context.principalEpoch ?? "owner") || !mappings.some((a) => a.id === m.mappingId && a.source === m.source && a.commonDir === m.commonDir))
175
+ continue;
176
+ const expected = path.join(mappings.find((a) => a.id === m.mappingId).parent, w.id);
177
+ if (w.directory !== expected || w.canonical !== expected) continue;
178
+ const pending = Object.values(r.worktreeJournal ?? {}).find((j) => j.intent.id === w.id);
179
+ if (!m.removedAt && !pending) {
180
+ try {
181
+ const identity = await user_worktree.repositoryIdentity(w.directory);
182
+ if (identity.gitDir !== m.gitDir || identity.commonDir !== m.commonDir || identity.branch !== m.branch || await lstat(path.join(identity.gitDir, "locked")).catch((e) => {
183
+ if (e.code === "ENOENT") return void 0;
184
+ throw e;
185
+ }))
186
+ continue;
187
+ } catch {
188
+ continue;
189
+ }
190
+ }
191
+ workspaces.push(
192
+ Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === w.id) ? { ...w, archivedAt: w.archivedAt ?? "pending" } : w
193
+ );
194
+ }
195
+ return { mappings: mappings.map((m) => ({ id: m.id, source: m.source })), workspaces };
196
+ },
197
+ async mutate(method, p, context = {}) {
198
+ const actor = context.principalId ?? "owner";
199
+ const r = await registry.snapshot();
200
+ const w = workspace(r, p.workspaceId);
201
+ const origin = method === "create" ? await sourceOf(r, w.id) : w;
202
+ const meta = w.worktree;
203
+ if (method === "remove" && (!meta || meta.kind !== "user" || meta.principalId !== actor || meta.grantEpoch !== (context.principalEpoch ?? "owner")))
204
+ fail("not_managed", "Only your managed user worktrees can be removed", 1003);
205
+ const source = method === "create" ? await realpath(origin.directory) : meta.source;
206
+ const mappingId = method === "create" ? p.mappingId : meta.mappingId;
207
+ const mapping = await approved(context, source, mappingId);
208
+ return registry.nativeMutation(
209
+ "workspace.worktree." + method,
210
+ { workspaceId: p.workspaceId, ...method === "create" ? { mappingId: p.mappingId } : {} },
211
+ { actor: actor + ":" + (context.principalEpoch ?? "owner"), requestId: p.requestId, ifRevision: p.ifRevision },
212
+ async (draft) => {
213
+ if (method === "create") {
214
+ const id = "wks_" + randomBytes(8).toString("hex");
215
+ const facts = await adapter.facts(source);
216
+ return {
217
+ method,
218
+ id,
219
+ requestId: p.requestId,
220
+ ifRevision: p.ifRevision,
221
+ directory: path.join(mapping.parent, id),
222
+ projectId: origin.projectId,
223
+ sourceWorkspaceId: origin.id,
224
+ source,
225
+ commonDir: mapping.commonDir,
226
+ mappingId,
227
+ principalId: actor,
228
+ grantEpoch: context.principalEpoch ?? "owner",
229
+ branch: `alp/workspace/${id}`,
230
+ head: facts.head
231
+ };
232
+ }
233
+ if (w.directory !== path.join(mapping.parent, w.id) || w.canonical !== w.directory)
234
+ fail("identity_changed", "Managed worktree path changed", 1003);
235
+ await guard(w.directory, async () => {
236
+ if (Object.values(draft.sessions).includes(w.id))
237
+ fail(
238
+ "workspace_history",
239
+ "Saved sessions reference this checkout; retain its files. This operation does not delete history."
240
+ );
241
+ try {
242
+ await adapter.assertClean(w.directory);
243
+ } catch {
244
+ fail(
245
+ "workspace_dirty",
246
+ "Worktree has dirty, ignored, hidden-index or submodule data; preserve it before removal"
247
+ );
248
+ }
249
+ });
250
+ return { method, id: w.id, directory: w.directory, ...meta };
251
+ },
252
+ async (intent, draft) => {
253
+ await approved(context, intent.source, intent.mappingId);
254
+ if (intent.principalId !== actor || intent.grantEpoch !== (context.principalEpoch ?? "owner") || intent.directory !== path.join(mapping.parent, intent.id) || intent.commonDir !== mapping.commonDir)
255
+ fail("identity_changed", "Worktree journal identity changed", 1003);
256
+ if (method === "create") {
257
+ const row = await adapter.inspect(intent.source, intent.directory, intent.branch);
258
+ if (!row) await adapter.create(intent.source, mapping.parent, intent.id, intent.branch, intent.head);
259
+ await clean(intent.source, intent.directory, intent.branch, intent.head);
260
+ await register(intent.directory);
261
+ const created = {
262
+ id: intent.id,
263
+ projectId: intent.projectId,
264
+ directory: intent.directory,
265
+ canonical: intent.directory,
266
+ labels: [],
267
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
268
+ worktree: {
269
+ kind: "user",
270
+ sourceWorkspaceId: intent.sourceWorkspaceId,
271
+ source: intent.source,
272
+ commonDir: intent.commonDir,
273
+ gitDir: (await user_worktree.repositoryIdentity(intent.directory)).gitDir,
274
+ requestId: intent.requestId,
275
+ ifRevision: intent.ifRevision,
276
+ mappingId: intent.mappingId,
277
+ principalId: actor,
278
+ grantEpoch: context.principalEpoch ?? "owner",
279
+ branch: intent.branch,
280
+ head: intent.head
281
+ }
282
+ };
283
+ draft.workspaces.push(created);
284
+ return { workspace: created };
285
+ }
286
+ const finish = async () => {
287
+ if (Object.values(draft.sessions).includes(intent.id))
288
+ fail(
289
+ "workspace_history",
290
+ "Saved sessions reference this checkout; retain its files. This operation does not delete history."
291
+ );
292
+ const present2 = await lstat(intent.directory).catch((e) => {
293
+ if (e.code === "ENOENT") return void 0;
294
+ throw e;
295
+ });
296
+ if (present2) await adapter.remove(intent.source, intent.directory, intent.branch);
297
+ else if (await adapter.inspect(intent.source, intent.directory, intent.branch))
298
+ fail("outcome_unknown", "Worktree removal needs reconciliation", 1005);
299
+ const removed = workspace(draft, intent.id);
300
+ removed.archivedAt = (/* @__PURE__ */ new Date()).toISOString();
301
+ removed.pinnedAt = null;
302
+ removed.worktree.removedAt = removed.archivedAt;
303
+ return { workspace: removed, filesRemoved: true, branchRetained: true };
304
+ };
305
+ const present = await lstat(intent.directory).catch((e) => {
306
+ if (e.code === "ENOENT") return void 0;
307
+ throw e;
308
+ });
309
+ return present ? guard(intent.directory, finish) : finish();
310
+ }
311
+ );
312
+ }
313
+ };
314
+ }
315
+ export {
316
+ createWorkspaceWorktrees,
317
+ worktreeMappings
318
+ };