@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.10

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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +14 -2
  4. package/dist/THIRD-PARTY-NOTICES.txt +456 -0
  5. package/dist/alp-templates.d.ts +5 -0
  6. package/dist/alpd.js +64050 -0
  7. package/dist/attachments.d.ts +187 -0
  8. package/dist/attachments.js +856 -0
  9. package/dist/build-manifest.json +150 -0
  10. package/dist/conversation.d.ts +119 -0
  11. package/dist/conversation.js +688 -0
  12. package/dist/disk.d.ts +67 -0
  13. package/dist/disk.js +152 -0
  14. package/dist/files.d.ts +262 -0
  15. package/dist/files.js +674 -0
  16. package/dist/git.d.ts +98 -0
  17. package/dist/git.js +1246 -0
  18. package/dist/gitignore.d.ts +62 -0
  19. package/dist/gitignore.js +254 -0
  20. package/dist/history.d.ts +24 -0
  21. package/dist/history.js +149 -0
  22. package/dist/index.d.ts +11 -0
  23. package/dist/index.js +28 -0
  24. package/dist/lifecycle.d.ts +101 -0
  25. package/dist/lifecycle.js +239 -0
  26. package/dist/lock.d.ts +21 -0
  27. package/dist/lock.js +42 -0
  28. package/dist/main.d.ts +1 -0
  29. package/dist/main.js +363 -0
  30. package/dist/model-catalog.d.ts +2 -0
  31. package/dist/model-catalog.js +44 -0
  32. package/dist/native-entry.d.ts +2 -0
  33. package/dist/native-entry.js +3 -0
  34. package/dist/native-register.d.ts +1 -0
  35. package/dist/native-register.js +13 -0
  36. package/dist/native-terminal.d.ts +45 -0
  37. package/dist/native-terminal.js +201 -0
  38. package/dist/operations.d.ts +40 -0
  39. package/dist/operations.js +313 -0
  40. package/dist/registry.d.ts +89 -0
  41. package/dist/registry.js +343 -0
  42. package/dist/rpc-error.d.ts +6 -0
  43. package/dist/rpc-error.js +11 -0
  44. package/dist/scheduler.d.ts +96 -0
  45. package/dist/scheduler.js +298 -0
  46. package/dist/schedules.d.ts +70 -0
  47. package/dist/schedules.js +246 -0
  48. package/dist/server.d.ts +60 -0
  49. package/dist/server.js +1958 -0
  50. package/dist/store.d.ts +178 -0
  51. package/dist/store.js +386 -0
  52. package/dist/terminal-native/README.md +201 -0
  53. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  54. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  56. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  57. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  58. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  59. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  60. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  61. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  62. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  63. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  64. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  65. package/dist/terminal-native/terminal-owner.c +389 -0
  66. package/dist/terminal-screen.d.ts +24 -0
  67. package/dist/terminal-screen.js +99 -0
  68. package/dist/terminals.d.ts +203 -0
  69. package/dist/terminals.js +570 -0
  70. package/dist/windows-terminal.d.ts +32 -0
  71. package/dist/windows-terminal.js +79 -0
  72. package/dist/worktrees.d.ts +65 -0
  73. package/dist/worktrees.js +318 -0
  74. package/native/README.md +201 -0
  75. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  76. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  77. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  78. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  79. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  80. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  81. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  82. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  83. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  84. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  85. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  86. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  87. package/native/terminal-owner.c +389 -0
  88. package/package.json +163 -4
  89. package/src/alp-templates.d.ts +5 -0
  90. package/src/attachments.ts +908 -0
  91. package/src/conversation.ts +857 -0
  92. package/src/disk.ts +175 -0
  93. package/src/files.ts +884 -0
  94. package/src/git.ts +1220 -0
  95. package/src/gitignore.ts +277 -0
  96. package/src/history.ts +118 -0
  97. package/src/index.ts +12 -0
  98. package/src/lifecycle.ts +283 -0
  99. package/src/lock.ts +53 -0
  100. package/src/main.ts +381 -0
  101. package/src/model-catalog.ts +36 -0
  102. package/src/native-entry.ts +5 -0
  103. package/src/native-register.ts +21 -0
  104. package/src/native-terminal.ts +127 -0
  105. package/src/operations.ts +329 -0
  106. package/src/registry.ts +238 -0
  107. package/src/rpc-error.ts +4 -0
  108. package/src/scheduler.ts +438 -0
  109. package/src/schedules.ts +297 -0
  110. package/src/server.ts +2238 -0
  111. package/src/store.ts +449 -0
  112. package/src/terminal-screen.ts +74 -0
  113. package/src/terminals.ts +653 -0
  114. package/src/windows-terminal.ts +74 -0
  115. package/src/worktrees.ts +382 -0
@@ -0,0 +1,79 @@
1
+ // packages/daemon/src/windows-terminal.ts
2
+ import { createRequire } from "node:module";
3
+ var loaded;
4
+ function loadNodePty() {
5
+ if (loaded === void 0) {
6
+ try {
7
+ loaded = createRequire(import.meta.url)("node-pty");
8
+ } catch {
9
+ loaded = null;
10
+ }
11
+ }
12
+ return loaded ?? void 0;
13
+ }
14
+ function windowsTerminalCapability(load = loadNodePty) {
15
+ return load() ? { available: true, protection: "none" } : { available: false, reason: "node_pty_unavailable" };
16
+ }
17
+ function windowsShell(env = process.env) {
18
+ const candidate = env.ComSpec ?? env.COMSPEC;
19
+ return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : "cmd.exe";
20
+ }
21
+ var createWindowsPtySpawn = (load = loadNodePty) => (file, args, options) => {
22
+ if (options.signal?.aborted) throw new Error("Terminal startup cancelled");
23
+ const pty = load();
24
+ if (!pty) throw new Error("node-pty is unavailable on this host");
25
+ const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
26
+ let killed = false;
27
+ let exit = false;
28
+ const exited = new Promise((resolve) => {
29
+ child.onExit(() => {
30
+ exit = true;
31
+ resolve();
32
+ });
33
+ });
34
+ return {
35
+ // node-pty reports the ConPTY shell's pid only once its output worker connects (0 until then), so
36
+ // the pid is read live rather than copied at spawn.
37
+ get pid() {
38
+ return child.pid;
39
+ },
40
+ write(data) {
41
+ if (!killed) child.write(data);
42
+ },
43
+ resize(cols, rows) {
44
+ if (!killed) try {
45
+ child.resize(cols, rows);
46
+ } catch {
47
+ }
48
+ },
49
+ // Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
50
+ kill() {
51
+ if (killed) return;
52
+ killed = true;
53
+ try {
54
+ child.kill();
55
+ } catch {
56
+ }
57
+ },
58
+ // Bounded: node-pty defers a kill until the terminal is ready (its first output) and may never report
59
+ // an exit (a terminal that never becomes ready, a lost callback); that does not hold up close.
60
+ async exited(ms) {
61
+ if (exit) return;
62
+ let timer;
63
+ await Promise.race([exited, new Promise((resolve) => {
64
+ timer = setTimeout(resolve, ms);
65
+ })]);
66
+ clearTimeout(timer);
67
+ },
68
+ onData: (listener) => child.onData(listener),
69
+ onExit: (listener) => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal }))
70
+ };
71
+ };
72
+ var windowsPtySpawn = createWindowsPtySpawn();
73
+ export {
74
+ createWindowsPtySpawn,
75
+ loadNodePty,
76
+ windowsPtySpawn,
77
+ windowsShell,
78
+ windowsTerminalCapability
79
+ };
@@ -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
+ };
@@ -0,0 +1,201 @@
1
+ # Terminal native owner — candidate, platform matrix incomplete
2
+
3
+ Task t-d71b. Production `src/terminals.ts` now uses this identity-bound owner,
4
+ with no node-pty fallback on macOS or Linux. Linux may use the best-effort root-only mode described below;
5
+ Windows has no protection helper and uses node-pty (ConPTY), best-effort (see "Windows" below). This candidate is NOT accepted for release:
6
+ actual Linux (beyond CI capability checks) and Windows evidence remain missing. Missing or
7
+ unverifiable backends refuse terminal capability explicitly (no plain-PTY fallback on Linux); on Linux a verified helper without full protection (any reason) offers root-only compatibility (best-effort, user decision 2026-10-29). No end-user compiler
8
+ is required. Existing session authentication and host/Paseo opt-ins still apply.
9
+
10
+ ## Protocol and lifetime
11
+
12
+ One standalone C process owns forkpty, the startup gate, every signal and root
13
+ wait/reap. JS sends terminal input on stdin and resize (`R cols rows\n`) / cleanup
14
+ (`C\n`) on fd4. PTY output is stdout; fd3 contains bounded JSON ready, root-exit,
15
+ and cleanup records. Input/output queues and identity storage are bounded. Resizes coalesce behind
16
+ writable backpressure; cleanup closes the control pipe immediately. Native startup
17
+ polls the handshake/control descriptors with a 3s deadline; failure closes the
18
+ gate and attempts only identity-bound cleanup with a bounded nonblocking reap.
19
+
20
+ The child reports `getsid(0)==getpid()` before the parent releases its startup
21
+ gate. The owner acquires root identity before release, has default SIGCHLD and no
22
+ other reaper, and uses waitid(WNOWAIT) to observe natural exit. It retains the
23
+ root's live process or zombie until all discovery/signaling ends. This reserves
24
+ the root PID and prevents unrelated sessions reusing that session number. Only
25
+ processes proven to belong to that reserved session can be discovered. Observed
26
+ identities remain authorized if they subsequently leave the session. On the full-protection path there is no
27
+ marker, environment, age, PPid, parentuniqueid, TTY, numeric PID signal or numeric
28
+ group signal fallback. Never-observed children that immediately detach can be
29
+ missed (the approved g3 limit).
30
+
31
+ Linux opens a proc TGID directory with O_RDONLY|O_DIRECTORY (not O_PATH), reads
32
+ stat relative to that SAME descriptor, and uses pidfd_send_signal on that fd with
33
+ flags0/infoNULL. Capability probing checks kernel procfs and that /proc/self PID
34
+ and SID match the caller's namespace coordinates, and requires /proc/self/status
35
+ NSpid to have exactly one field equal to getpid() (proves the procfs PID namespace
36
+ is our active one without reading PID1, so it works for non-root users; missing
37
+ NSpid denies). A mount-privileged actor remounting /proc is outside this guarantee;
38
+ failure denies capability. Linux source has NOT been
39
+ compiled or executed here; permission/race/namespace/minimum-kernel evidence is
40
+ still required.
41
+
42
+ Darwin validates the complete private flavor17 56-byte struct and audit-token
43
+ version at runtime. Discovery uses U_before → reserved getsid → audit token →
44
+ U_after, requiring equal uniqueids and a matching token pidversion. Signals
45
+ refresh only a previously known uniqueid and use proc_signal_with_audittoken.
46
+ Unknown/changed identity never authorizes a numeric signal. Cleanup reports
47
+ observed/live/uncertain separately; it does not claim universal containment.
48
+
49
+ ## Accepted finite-generation Darwin limit
50
+
51
+ The Darwin final syscall compares PID + **32-bit global pidversion**, not the
52
+ 64-bit private uniqueid. Fork AND exec increment this global generation. If the
53
+ helper is suspended after its last identity check, enough global allocations can
54
+ wrap that generation and a recycled target PID can collide. Keeping a task-name
55
+ port or checking uniqueid again does not atomically bind the eventual syscall.
56
+ This is a source-derived limitation, not an executed 2^32-operation exploit.
57
+ The user explicitly accepted ONLY this residual in g4 (2026-10-29); ordinary PID
58
+ reuse protection, all native checks, packaging, platform tests and independent
59
+ review remain required. No blanket no-wrong-process waiver is inferred.
60
+
61
+ Kernel proof anchors (oracle 275c5e36, advice only; not implementation review):
62
+
63
+ - [XNU PID/zombie/session reservation and fork generations](https://github.com/apple-oss-distributions/xnu/blob/xnu-11215.1.10/bsd/kern/kern_fork.c#L877)
64
+ - [XNU WNOWAIT and reap hash removal](https://github.com/apple-oss-distributions/xnu/blob/xnu-11215.1.10/bsd/kern/kern_exit.c#L2457)
65
+ - [XNU setsid and cross-session restrictions](https://github.com/apple-oss-distributions/xnu/blob/xnu-11215.1.10/bsd/kern/kern_prot.c#L245)
66
+ - [XNU identity-info and final audit signal comparison](https://github.com/apple-oss-distributions/xnu/blob/xnu-11215.1.10/bsd/kern/proc_info.c#L3290)
67
+ - [XNU exec increments generation](https://github.com/apple-oss-distributions/xnu/blob/xnu-11215.1.10/bsd/kern/kern_exec.c#L6475)
68
+ - [Private ABI layout](https://github.com/apple-oss-distributions/xnu/blob/xnu-12377.1.9/bsd/sys/proc_info_private.h#L41)
69
+ - [Linux stored proc-directory identity](https://github.com/torvalds/linux/blob/v6.12/fs/proc/base.c#L3244)
70
+ - [Linux procdirfd signal dispatch](https://github.com/torvalds/linux/blob/v6.12/kernel/signal.c#L3647)
71
+ - [Linux stat session coordinates](https://github.com/torvalds/linux/blob/v6.12/fs/proc/array.c#L505)
72
+
73
+ ## Build, distribution and remaining platform evidence
74
+
75
+ `node scripts/build-terminal-native.mjs` is an EXPLICIT developer build, never
76
+ terminal startup or postinstall. Darwin also accepts `--arch=x64`/`--arch=arm64`
77
+ using the existing Apple compiler and ad-hoc codesign; capability execution must
78
+ succeed before a manifest is written. Hashes bind protocol, source and binary.
79
+ `node scripts/terminal-native-assets.mjs --require-matrix` and release pack-check
80
+ FAIL until all six slots exist: Darwin arm64/x64, Linux arm64/x64 × glibc/musl.
81
+ Builds copy only verified prebuilt assets beside root, daemon, CLI and Paseo bundles;
82
+ source-package daemon consumers also carry native source/hash manifests. They do
83
+ not invoke a compiler. A rebuild replaces the generated asset directory wholesale.
84
+
85
+ ### Committed prebuilts and the rebuild procedure (t-08cf)
86
+
87
+ All six slots are committed under `prebuilt/<slot>/` (binary with its exec bit, plus
88
+ `manifest.json` binding protocol, `terminal-owner.c` SHA-256 and binary SHA-256), so a
89
+ clean checkout passes `--require-matrix`, pack-check and the release clean-tree gate.
90
+ CI and releases ship the committed binaries; nothing is compiled during build or release.
91
+
92
+ The four Linux slots come from `.github/workflows/terminal-native.yml` (glibc on the
93
+ manylinux_2_28 floor image, musl on Alpine 3.20, each executed non-root in its own libc;
94
+ glibc also in fresh/ancestor PID namespaces). On every CI run that job rebuilds each slot
95
+ from the checked-out source, then requires the COMMITTED slot's manifest to record the
96
+ same source hash as the fresh build, its binary to match its manifest hash, and the
97
+ committed binary to pass the same execution checks. Builds are not byte-reproducible, so
98
+ binary hashes are NOT compared across builds: CI enforces source binding and execution,
99
+ not bit-for-bit provenance.
100
+
101
+ When `terminal-owner.c` changes, rebuild ALL six slots in the same commit:
102
+
103
+ 1. Darwin: on macOS, `node scripts/build-terminal-native.mjs --arch=arm64` and
104
+ `--arch=x64` (x64 capability executes through Rosetta).
105
+ 2. Linux: push the source change; the terminal-native jobs fail as stale but still upload
106
+ `terminal-native-<slot>` artifacts built from that exact revision. Download them into
107
+ an empty directory (`gh run download <run-id> -p 'terminal-native-*' -D <dir>`; each
108
+ lands as `<dir>/terminal-native-<slot>/<slot>.tar`) and extract each with
109
+ `tar -C packages/daemon/native/prebuilt -xpf <tar>` (tar keeps the exec bit).
110
+ 3. `node scripts/terminal-native-assets.mjs --require-matrix`, commit all six slots, and
111
+ check the next CI run is green.
112
+
113
+ Current artifacts: Darwin arm64 executed on macOS27, Darwin x64 capability executed
114
+ through existing Rosetta on that same host. Both target macOS11.0 (LC_BUILD_VERSION),
115
+ matching [Node22's macOS floor](https://github.com/nodejs/node/blob/v22.23.0/BUILDING.md#platform-list).
116
+ This deployment target is NOT proof of runtime compatibility on macOS11 or physical
117
+ x64 hardware. Private-ABI capability validation still fails closed. Linux builds
118
+ must retain the existing libc support baseline (Node22 glibc2.28). The committed Linux
119
+ artifacts were built and capability-executed by CI run 40857935251 (GitHub-hosted
120
+ Ubuntu 24.04 kernels); minimum-kernel execution has not been proved. pidfd_send_signal (Linux5.1 syscall baseline) selects full protection. Without it
121
+ Linux runs the best-effort root-only mode described below, disclosed with a non-blocking notice.
122
+ No permission denial or artifact failure silently selects compatibility.
123
+
124
+ Async startup reserves request IDs and quota before native readiness. Revoke,
125
+ shutdown and host optout cancel startup and await native cleanup before returning;
126
+ late readiness cannot publish an orphan terminal. Root exit is delivered after
127
+ stdio drains. The helper reads the PTY to EOF and advances partial output writes
128
+ for up to one further second; an undrained tail reports explicit uncertainty. Cleanup reports observed/live/uncertain, and uncertain/live results
129
+ refuse success and stop further terminal admission. The existing real PTY cleanup
130
+ scenarios now execute through the native owner (including exec, same-session
131
+ orphans and a late child). Never-observed immediate-setsid escapes remain the
132
+ approved g3 discovery limit. Actual Linux/Windows browser keyboard and Linux
133
+ namespace/proc permissions/races remain NOT_CHECKED.
134
+
135
+ Explicit developer regressions (require a local C compiler, not end-user startup):
136
+ `node --test packages/daemon/native/tests/lifecycle.mjs` exercises delayed native
137
+ startup and a real stalled control reader. `ALP_NATIVE_BASELINE=8ed11fd` runs the
138
+ same checks against the committed pre-correction C/TS in isolated scratch space.
139
+ This mode does not change the checkout. Both cases fail on that baseline and pass
140
+ on the correction. Ordinary lifecycle tests run separately from daemon/tests.
141
+
142
+ ## Linux root-only compatibility candidate (g5)
143
+
144
+ Linux is best-effort (user decision 2026-10-29; only macOS is guaranteed). A verified
145
+ helper that fails full protection for ANY reason (ENOSYS, EPERM/EACCES, procfs or
146
+ PID-namespace mismatch) advertises `alp-terminal-owner:1:root-only`; root-only mode
147
+ only signals the unreaped session root and, after the startup capability probe, does not use procfs or pidfd, so
148
+ background jobs may survive close. A corrupt/missing binary or manifest, timeout,
149
+ crash or malformed record still refuses capability (no unverified code runs).
150
+ The owner revalidates immediately before fork; a mode change refuses before shell
151
+ launch, and alpd probes the helper again for the next create.
152
+
153
+ Root-only terminals open directly: no acknowledgment is required (user decision
154
+ 2026-10-29, Linux and Windows are best-effort like Orca/Paseo). The deprecated
155
+ `protectionAcknowledgment: "linux-root-only-v1"` parameter is still accepted on
156
+ `terminal.create`/`terminal.attach` for compatibility and ignored. Terminal records
157
+ carry `protection: "root-only"`, so clients disclose the limit: ALP Web shows one
158
+ non-blocking notice ("Limited protection on this Linux host: closing the terminal may
159
+ not stop background processes."), and the terminal stays usable. Paseo's terminal
160
+ protocol has no notice field, so the ALP bridge writes the same notice once as a
161
+ dim line into each Paseo client's view of the terminal (never into alpd's output).
162
+
163
+ Compatibility never scans or explicitly signals descendants or process groups.
164
+ Only its own direct root is signaled, before final reap, with SIGCHLD explicitly
165
+ SIG_DFL and SA_NOCLDWAIT cleared by checked sigaction. A living child or WNOWAIT
166
+ zombie continuously reserves its PID; an unexpected ECHILD permanently retires
167
+ numeric authority. Final reap is checked. This is spawn ownership, not a snapshot
168
+ or a numeric PID-reuse heuristic; helper compromise invalidates that premise.
169
+ Kernel PTY hangup and line-discipline signals may naturally affect foreground jobs.
170
+
171
+ Known reduced coverage is `coverage: "root-only"`; successful cleanup establishes
172
+ only the shell's exit. Unmanaged jobs can survive close/revoke/optout/shutdown and
173
+ keep the PTY open (`outputOpen: true` after bounded draining). This accepted known
174
+ coverage limit alone does not lock admission. Root live/lost ownership, queued
175
+ bytes not delivered, protocol loss or sticky adapter failure remain uncertainty
176
+ and retain the admission lock. No delayed signals occur after root reap.
177
+
178
+ Advice/source proof: oracle18a20d0e examined [Linux5.1 wait/ptrace reap](https://github.com/torvalds/linux/blob/v5.1/kernel/exit.c)
179
+ and [original procdirfd signal dispatch](https://github.com/torvalds/linux/blob/v5.1/kernel/signal.c).
180
+ Actual Linux compilation/execution (old and supported kernel, namespace/permission,
181
+ ptrace/exec/reuse/race) remains NOT_CHECKED here; the four shipped Linux artifacts are committed and CI capability-checked.
182
+ Darwin author regressions validate the unchanged full path only; no seam/mock or
183
+ Rosetta execution is claimed as Linux or physical-x64/minimum-macOS proof.
184
+
185
+ ## Windows (best-effort, no protection helper)
186
+
187
+ There is no Windows native owner and pack-check requires no Windows slot. On win32,
188
+ `src/terminals.ts` spawns the shell (`%ComSpec%`, else `cmd.exe`) through node-pty
189
+ (ConPTY), the same platform PTY Paseo uses; node-pty is an optional dependency, and
190
+ when it cannot load, terminals refuse with `terminal_unsupported`. Terminals report
191
+ `protection: "none"`, and clients show a "not guaranteed on Windows" notice. Closing,
192
+ revoking or turning off terminals calls node-pty `kill()` (best-effort): the shell
193
+ ends, but processes it started may keep running. This is the only production use of
194
+ node-pty. Windows behavior has NOT been executed here; only injected-owner unit tests ran.
195
+
196
+ ## Termination signals
197
+
198
+ SIGTERM, SIGINT and SIGHUP sent to the owner (for example to the daemon's process group)
199
+ start the same bound cleanup as closing its control pipe, on every platform including
200
+ macOS (deliberate: previously such a signal killed the owner before cleanup). The shell
201
+ child resets them to default before exec.