@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
package/dist/store.d.ts CHANGED
@@ -1,5 +1,16 @@
1
1
  import type { Envelope, SessionSnapshot, SessionSpec } from '@anhlp/alp-runtime/index';
2
2
  import type { SessionError, SessionStatus } from '@anhlp/alp-protocol/session';
3
+ import type { TurnAttention } from '@anhlp/alp-protocol/events';
4
+ import type { ConversationBranch, ForkProvenance, NativeBase } from '@anhlp/alp-protocol/session';
5
+ /** A branch a rewind set aside (§12.7): its public description, the native conversation and where its timeline lies. */
6
+ export type StoredBranch = ConversationBranch & {
7
+ /** The native conversation the root continued before the rewind: never deleted, so the branch stays recoverable. */
8
+ threadId: string;
9
+ base?: NativeBase;
10
+ /** The first discarded cursor, and the rewind's marker cursor (the branch holds what lay between). */
11
+ cut: number;
12
+ marker: number;
13
+ };
3
14
  /**
4
15
  * alpd's durable state (plans/reference/ALPD.md §5, §66): one JSON record per session,
5
16
  * written atomically, one append-only JSONL timeline per tree, and one receipt per
@@ -20,6 +31,30 @@ export type SessionRecord = {
20
31
  title?: string;
21
32
  /** Set aside by the user: closed, and listed only when asked (ALPD §61). */
22
33
  archived?: boolean;
34
+ /** A root's last turn that ended unseen, until a client acknowledges it or another turn starts (Paseo's requiresAttention). */
35
+ attention?: TurnAttention;
36
+ /** Claude: the conversation `session.threadId` is made from on its first prompt, after a fork or rewind (§12.7). */
37
+ base?: NativeBase;
38
+ /** Where this root was forked from (§12.7). */
39
+ forkedFrom?: ForkProvenance;
40
+ /** Stable creation ownership; current native binding/title may change after a fork. */
41
+ forkAttempt?: {
42
+ key: string;
43
+ attemptId?: string;
44
+ createdAt: string;
45
+ fingerprint: string;
46
+ };
47
+ /** Branches rewinds set aside, oldest first (§12.7). */
48
+ branches?: StoredBranch[];
49
+ /** Atomic proof of completed conversation commits whose journal marker may be missing. */
50
+ lifecycleCommits?: Record<string, {
51
+ operation: string;
52
+ requestId: string;
53
+ createdAt: string;
54
+ fingerprint: string;
55
+ attemptId?: string;
56
+ result: any;
57
+ }>;
23
58
  createdAt: string;
24
59
  updatedAt: string;
25
60
  };
@@ -59,7 +94,11 @@ export type StoreHealth = {
59
94
  };
60
95
  };
61
96
  export type Store = ReturnType<typeof createStore>;
62
- export declare function createStore(root: string): {
97
+ export declare function createStore(root: string, options?: {
98
+ onWriteError?: (error: unknown) => void;
99
+ }): {
100
+ /** The state directory this store keeps its files in. */
101
+ root: string;
63
102
  put(record: SessionRecord): Promise<void>;
64
103
  receipt(key: string): Promise<Receipt | UnreadableReceipt | undefined>;
65
104
  putReceipt(key: string, receipt: Receipt): Promise<void>;
@@ -79,8 +118,39 @@ export declare function createStore(root: string): {
79
118
  pruneReceipts(maxAgeMs: number, { temporaries }?: {
80
119
  temporaries?: boolean | undefined;
81
120
  }): Promise<void>;
121
+ /** Authoritative record after queued writes, including failed writes (which do not prove completion). */
122
+ get(id: string): Promise<SessionRecord | undefined>;
82
123
  list(): Promise<SessionRecord[]>;
83
124
  append(rootId: string, envelope: Envelope): Promise<void>;
125
+ history(rootId: string, sessionId: string, options?: {
126
+ before?: string;
127
+ limit?: number;
128
+ maxBytes?: number;
129
+ }): Promise<{
130
+ tipCursor: number;
131
+ olderCursor?: string | undefined;
132
+ generation: string;
133
+ items: import("./history.js").HistoryItem[];
134
+ hasOlder: boolean;
135
+ }>;
136
+ /**
137
+ * Rewinds a tree's timeline (§12.7), idempotently: the whole timeline moves to the branch file
138
+ * `<root>.branch-<id>.jsonl`, and the root's timeline becomes its lines before `cut`, the root's own
139
+ * session lifecycle lines after it (opened, updated, closed: not conversation), `marker`, and any line
140
+ * whose cursor follows the marker's, in cursor order. Runs in
141
+ * the tree's append queue, so no append lands in between. A crash leaves the old timeline, or the
142
+ * branch and the new one beside it (finished by the next call); the history index is rebuilt with a
143
+ * new generation, so every older history cursor is stale.
144
+ */
145
+ rewind(rootId: string, { cut, branchId, marker }: {
146
+ cut: number;
147
+ branchId: string;
148
+ marker: Envelope;
149
+ }): Promise<void>;
150
+ /** Writes a new tree's whole timeline at once (a fork's, §12.7); written again whole by a repeat. */
151
+ createTimeline(rootId: string, envelopes: Envelope[]): Promise<void>;
152
+ /** The timeline of a branch a rewind set aside; empty when it is not there. */
153
+ branchTimeline(rootId: string, branchId: string): Promise<Envelope[]>;
84
154
  timeline(rootId: string): Promise<Envelope[]>;
85
155
  /**
86
156
  * Waits for the queued writes of these records and timelines, and names those that
@@ -102,7 +172,7 @@ export declare function createStore(root: string): {
102
172
  /** How many records, receipts and timelines are failed now: a later successful write clears a record, a lost timeline line never clears. */
103
173
  failing(): number;
104
174
  health(): StoreHealth;
105
- /** Removes a whole tree: its records and its timeline. */
175
+ /** Removes a whole tree: its records, its timeline and the branches rewinds set aside. */
106
176
  remove(rootId: string, ids: string[]): Promise<void>;
107
177
  flush(): Promise<void>;
108
178
  };
package/dist/store.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // packages/daemon/src/store.ts
2
- import { appendFile, mkdir, open, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
2
+ import { createHistoryIndex } from "./history.js";
3
+ import { appendFile, mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
4
  import { replaceFile } from "./lock.js";
4
5
  import { randomBytes } from "node:crypto";
5
6
  import path from "node:path";
@@ -8,9 +9,10 @@ var log = createLogger({ component: "store" });
8
9
  var SAFE = /[^\w.:-]/g;
9
10
  var fileName = (id) => id.replace(SAFE, "_");
10
11
  var TAIL_CHUNK = 64 * 1024;
11
- function createStore(root) {
12
+ function createStore(root, options = {}) {
12
13
  const sessionsDir = path.join(root, "sessions");
13
14
  const timelineDir = path.join(root, "timeline");
15
+ const historyIndexes = /* @__PURE__ */ new Map();
14
16
  const receiptsDir = path.join(root, "receipts");
15
17
  const writes = /* @__PURE__ */ new Map();
16
18
  const appends = /* @__PURE__ */ new Map();
@@ -51,6 +53,7 @@ function createStore(root) {
51
53
  health.failures++;
52
54
  health.lastError = { at: (/* @__PURE__ */ new Date()).toISOString(), operation, message: error?.message ?? String(error) };
53
55
  log.error(`${operation} failed`, { code: "ALP_PERSISTENCE_WRITE_FAILED", operation, error, ...ids });
56
+ options.onWriteError?.(error);
54
57
  }
55
58
  );
56
59
  map.set(key, settled);
@@ -114,7 +117,10 @@ function createStore(root) {
114
117
  return envelopes;
115
118
  }
116
119
  const receiptFile = (key) => path.join(receiptsDir, `${fileName(key)}.json`);
120
+ const branchFile = (rootId, branchId) => path.join(timelineDir, `${fileName(rootId)}.branch-${fileName(branchId)}.jsonl`);
117
121
  return {
122
+ /** The state directory this store keeps its files in. */
123
+ root,
118
124
  put(record) {
119
125
  const file = path.join(sessionsDir, `${fileName(record.id)}.json`);
120
126
  const body = JSON.stringify(record);
@@ -185,6 +191,17 @@ function createStore(root) {
185
191
  }
186
192
  }
187
193
  },
194
+ /** Authoritative record after queued writes, including failed writes (which do not prove completion). */
195
+ async get(id) {
196
+ await writes.get(id)?.catch(() => {
197
+ });
198
+ try {
199
+ return JSON.parse(await readFile(path.join(sessionsDir, `${fileName(id)}.json`), "utf8"));
200
+ } catch (error) {
201
+ if (error?.code === "ENOENT") return void 0;
202
+ throw error;
203
+ }
204
+ },
188
205
  async list() {
189
206
  await prepare();
190
207
  const records = [];
@@ -212,6 +229,93 @@ function createStore(root) {
212
229
  await appendFile(file, line, { mode: 384 });
213
230
  }, true, { rootId });
214
231
  },
232
+ async history(rootId, sessionId, options2 = {}) {
233
+ await prepare();
234
+ await appends.get(rootId);
235
+ let index = historyIndexes.get(rootId);
236
+ if (!index) {
237
+ index = createHistoryIndex(path.join(timelineDir, `${fileName(rootId)}.jsonl`));
238
+ historyIndexes.set(rootId, index);
239
+ }
240
+ return index.page(sessionId, options2);
241
+ },
242
+ /**
243
+ * Rewinds a tree's timeline (§12.7), idempotently: the whole timeline moves to the branch file
244
+ * `<root>.branch-<id>.jsonl`, and the root's timeline becomes its lines before `cut`, the root's own
245
+ * session lifecycle lines after it (opened, updated, closed: not conversation), `marker`, and any line
246
+ * whose cursor follows the marker's, in cursor order. Runs in
247
+ * the tree's append queue, so no append lands in between. A crash leaves the old timeline, or the
248
+ * branch and the new one beside it (finished by the next call); the history index is rebuilt with a
249
+ * new generation, so every older history cursor is stale.
250
+ */
251
+ rewind(rootId, { cut, branchId, marker }) {
252
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
253
+ const branch = branchFile(rootId, branchId);
254
+ const temporary = `${file}.rewind-${fileName(branchId)}.tmp`;
255
+ return queue(appends, rootId, `timeline rewind ${rootId}`, async () => {
256
+ const exists = (target) => stat(target).then(() => true, (error) => {
257
+ if (error?.code === "ENOENT") return false;
258
+ throw error;
259
+ });
260
+ if (!await exists(branch)) {
261
+ if (!repaired.has(rootId)) {
262
+ await repairTail(file);
263
+ repaired.add(rootId);
264
+ }
265
+ const text = await readFile(file, "utf8").catch((error) => {
266
+ if (error?.code === "ENOENT") return "";
267
+ throw error;
268
+ });
269
+ const kept = [];
270
+ const markerCursor = marker.cursor ?? Number.MAX_SAFE_INTEGER;
271
+ let cursor = 0;
272
+ for (const line of text.split("\n")) {
273
+ if (!line) continue;
274
+ let envelope;
275
+ try {
276
+ envelope = JSON.parse(line);
277
+ } catch {
278
+ continue;
279
+ }
280
+ cursor = typeof envelope.cursor === "number" && envelope.cursor > cursor ? envelope.cursor : cursor + 1;
281
+ const lifecycle = envelope.sessionId === rootId && ["session.opened", "session.ready", "session.updated", "session.closed", "session.failed"].includes(envelope.event?.type);
282
+ if (cursor < cut) kept.push({ cursor, line });
283
+ else if (lifecycle || cursor > markerCursor) kept.push({ cursor, line: JSON.stringify({ ...envelope, cursor }) });
284
+ }
285
+ kept.push({ cursor: markerCursor, line: JSON.stringify(marker) });
286
+ kept.sort((a, b) => a.cursor - b.cursor);
287
+ await writeFile(temporary, `${kept.map((entry) => entry.line).join("\n")}
288
+ `, { mode: 384 });
289
+ if (await exists(file)) await rename(file, branch);
290
+ else await writeFile(branch, "", { mode: 384 });
291
+ }
292
+ if (await exists(temporary)) await rename(temporary, file);
293
+ await Promise.all([".jsonl.idx", ".jsonl.history.json"].map((suffix) => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })));
294
+ historyIndexes.delete(rootId);
295
+ repaired.add(rootId);
296
+ }, false, { rootId });
297
+ },
298
+ /** Writes a new tree's whole timeline at once (a fork's, §12.7); written again whole by a repeat. */
299
+ createTimeline(rootId, envelopes) {
300
+ const file = path.join(timelineDir, `${fileName(rootId)}.jsonl`);
301
+ return queue(appends, rootId, `timeline ${rootId}`, async () => {
302
+ await writeAtomic(file, envelopes.map((envelope) => `${JSON.stringify(envelope)}
303
+ `).join(""));
304
+ await Promise.all([".jsonl.idx", ".jsonl.history.json"].map((suffix) => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })));
305
+ historyIndexes.delete(rootId);
306
+ repaired.add(rootId);
307
+ }, false, { rootId });
308
+ },
309
+ /** The timeline of a branch a rewind set aside; empty when it is not there. */
310
+ async branchTimeline(rootId, branchId) {
311
+ await appends.get(rootId);
312
+ try {
313
+ return parseTimeline(await readFile(branchFile(rootId, branchId), "utf8"), path.basename(branchFile(rootId, branchId)));
314
+ } catch (error) {
315
+ if (error?.code === "ENOENT") return [];
316
+ throw error;
317
+ }
318
+ },
215
319
  async timeline(rootId) {
216
320
  await appends.get(rootId);
217
321
  const name = `${fileName(rootId)}.jsonl`;
@@ -258,15 +362,18 @@ function createStore(root) {
258
362
  health() {
259
363
  return { ...health, ...health.lastError ? { lastError: { ...health.lastError } } : {} };
260
364
  },
261
- /** Removes a whole tree: its records and its timeline. */
365
+ /** Removes a whole tree: its records, its timeline and the branches rewinds set aside. */
262
366
  async remove(rootId, ids) {
263
367
  await Promise.all([...ids.map((id) => writes.get(id)), appends.get(rootId)]);
368
+ const branches = (await readdir(timelineDir).catch(() => [])).filter((name) => name.startsWith(`${fileName(rootId)}.branch-`));
264
369
  await Promise.all([
265
370
  ...ids.map((id) => rm(path.join(sessionsDir, `${fileName(id)}.json`), { force: true })),
266
- rm(path.join(timelineDir, `${fileName(rootId)}.jsonl`), { force: true })
371
+ ...[".jsonl", ".jsonl.idx", ".jsonl.history.json"].map((suffix) => rm(path.join(timelineDir, `${fileName(rootId)}${suffix}`), { force: true })),
372
+ ...branches.map((name) => rm(path.join(timelineDir, name), { force: true }))
267
373
  ]);
268
374
  for (const id of ids) failed.delete(id);
269
375
  failed.delete(`timeline:${rootId}`);
376
+ historyIndexes.delete(rootId);
270
377
  repaired.delete(rootId);
271
378
  },
272
379
  async flush() {
@@ -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.
@@ -0,0 +1,11 @@
1
+ {
2
+ "protocol": 1,
3
+ "slot": "darwin-arm64",
4
+ "source": "d2fa72ce0b083e60cddbe76839365beaa80b891451b45987d968b805154d0636",
5
+ "sha256": "354f50aea9e8d5113fc9fb4fd90ccb417d8aad74b89473fdcb711c6d1253f367",
6
+ "buildHost": "v22.23.4",
7
+ "deploymentTarget": "11.0",
8
+ "executionChecked": true,
9
+ "executionProtection": "identity-bound",
10
+ "executionHost": "darwin-arm64"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "protocol": 1,
3
+ "slot": "darwin-x64",
4
+ "source": "d2fa72ce0b083e60cddbe76839365beaa80b891451b45987d968b805154d0636",
5
+ "sha256": "606a0bd9a0ae76550156d343c89efa69d97215b8bf95c6aadbf38b6468a041e5",
6
+ "buildHost": "v22.23.4",
7
+ "deploymentTarget": "11.0",
8
+ "executionChecked": true,
9
+ "executionProtection": "identity-bound",
10
+ "executionHost": "darwin-arm64"
11
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "protocol": 1,
3
+ "slot": "linux-arm64-glibc",
4
+ "source": "d2fa72ce0b083e60cddbe76839365beaa80b891451b45987d968b805154d0636",
5
+ "sha256": "fa6e8b66f8e449d6fa294518c7f7d107e0707d2048623cc4952031b9580c31e3",
6
+ "buildHost": "v22.23.4",
7
+ "executionChecked": true,
8
+ "executionProtection": "identity-bound",
9
+ "executionHost": "linux-arm64"
10
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "protocol": 1,
3
+ "slot": "linux-arm64-musl",
4
+ "source": "d2fa72ce0b083e60cddbe76839365beaa80b891451b45987d968b805154d0636",
5
+ "sha256": "e6935d27c14c626b3207ea8edecd4a56b6bf13c8634b97a7480928e4bd22e9d6",
6
+ "buildHost": "v20.15.1",
7
+ "executionChecked": true,
8
+ "executionProtection": "identity-bound",
9
+ "executionHost": "linux-arm64"
10
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "protocol": 1,
3
+ "slot": "linux-x64-glibc",
4
+ "source": "d2fa72ce0b083e60cddbe76839365beaa80b891451b45987d968b805154d0636",
5
+ "sha256": "4746db2e0b89ffd81f9ab14da871a8a8a59b39d219ab9612bb86faa8d8db35b7",
6
+ "buildHost": "v22.23.4",
7
+ "executionChecked": true,
8
+ "executionProtection": "identity-bound",
9
+ "executionHost": "linux-x64"
10
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "protocol": 1,
3
+ "slot": "linux-x64-musl",
4
+ "source": "d2fa72ce0b083e60cddbe76839365beaa80b891451b45987d968b805154d0636",
5
+ "sha256": "5d3e964057212ce231ab920426012ede944057138613712f0cf52a81f1397c2d",
6
+ "buildHost": "v20.15.1",
7
+ "executionChecked": true,
8
+ "executionProtection": "identity-bound",
9
+ "executionHost": "linux-x64"
10
+ }