omp-superagent 0.1.16 → 0.1.18

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 (47) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +119 -33
  4. package/docs/OPERATIONS.md +83 -23
  5. package/docs/design/execution.md +66 -17
  6. package/docs/design/messaging.md +134 -47
  7. package/docs/releases/0.1.17.md +10 -0
  8. package/docs/releases/0.1.18.md +10 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +2 -2
  19. package/skills/head/references/routing.md +17 -6
  20. package/src/config/config.ts +15 -0
  21. package/src/contracts.ts +49 -4
  22. package/src/cron/cron-jobs.ts +135 -92
  23. package/src/cron/cron-pr-intake.ts +18 -11
  24. package/src/extension.ts +15 -5
  25. package/src/gateway/gateway-client.ts +3 -1
  26. package/src/lane/workflow.ts +12 -6
  27. package/src/managed-super-probe.ts +21 -15
  28. package/src/messaging/messenger-command-catalog.json +1 -1
  29. package/src/messaging/messenger-commands.ts +8 -3
  30. package/src/messaging/slack-context.ts +50 -0
  31. package/src/omp/superkit-skills.ts +15 -2
  32. package/src/pr/pr-intake-order.ts +62 -0
  33. package/src/pr/pr-intake-review.ts +49 -31
  34. package/src/pr/pr-intake-work.ts +3 -2
  35. package/src/routing/message-order.ts +22 -1
  36. package/src/routing/topic-request.ts +41 -0
  37. package/src/runtime/controller.ts +515 -191
  38. package/src/runtime/deferred-routing.ts +12 -4
  39. package/src/runtime/dm-timeline.ts +3 -3
  40. package/src/storage/deferred-routing.ts +25 -4
  41. package/src/storage/store.ts +389 -60
  42. package/src/worker/worker-checkout.ts +38 -4
  43. package/src/worker/worker-host.ts +114 -24
  44. package/src/worker/worker-ledger.ts +28 -9
  45. package/src/worker/worker-repository.ts +13 -0
  46. package/src/worker/worker-service.ts +74 -17
  47. package/src/worker/worker-wire.ts +3 -1
@@ -1,7 +1,8 @@
1
1
  import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
- import { isAbsolute, join, relative, sep } from "node:path";
3
- import { gitWorkerRepository, workerRepositoryHead, workerRepositoryIdentity } from "./worker-repository";
2
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
3
+ import { gitWorkerRepository, workerIndexHasOrdinaryFiles, workerMemoryRepositoryMatches, workerRepositoryHead, workerRepositoryIdentity } from "./worker-repository";
4
4
  import { WorkerRefusal } from "./worker-request";
5
+ import { trustedWorkerPath } from "./worker-trust";
5
6
  import type { WorkerLaneRef, WorkerPolicy, WorkerRepo } from "./worker-wire";
6
7
 
7
8
  export function privateWorkerDirectory(directory: string, create = false): boolean {
@@ -37,10 +38,43 @@ export async function enrolledRepo(policy: WorkerPolicy, repo: WorkerRepo): Prom
37
38
  return gitPath;
38
39
  }
39
40
 
40
- export async function boundWorkspace(repo: WorkerRepo, ref: Pick<WorkerLaneRef, "revision" | "subdir">): Promise<string> {
41
+ /** Durable identity of the enrolled physical checkout, not its mutable documents. */
42
+ export function workerCheckoutIdentity(repoRoot: string, gitDir: string, cwd: string): string | null {
43
+ const uid = process.getuid?.();
44
+ if (uid === undefined || !within(repoRoot, cwd)) return null;
45
+ try {
46
+ trustedWorkerPath(repoRoot, [], "directory");
47
+ for (let dir = cwd; dir !== repoRoot; dir = dirname(dir)) {
48
+ const stat = lstatSync(dir, { throwIfNoEntry: false });
49
+ if (!stat?.isDirectory() || stat.uid !== uid || (stat.mode & 0o022) !== 0) return null;
50
+ }
51
+ const identities = [repoRoot, gitDir, cwd].map(path => {
52
+ const stat = lstatSync(path, { bigint: true, throwIfNoEntry: false });
53
+ return stat?.isDirectory() && stat.uid === BigInt(uid) && (stat.mode & 0o022n) === 0n
54
+ && realpathSync(path) === path ? `${stat.dev}:${stat.ino}` : null;
55
+ });
56
+ return identities.includes(null) ? null : identities.join("/");
57
+ } catch (error) {
58
+ if (error instanceof WorkerRefusal || error instanceof Error && "code" in error
59
+ && ["ENOENT", "ENOTDIR", "EACCES", "ELOOP"].includes(String(error.code))) return null;
60
+ throw error;
61
+ }
62
+ }
63
+
64
+ export async function boundWorkspace(repo: WorkerRepo, ref: Pick<WorkerLaneRef, "revision" | "subdir">,
65
+ continuation?: { readonly gitDir: string; readonly checkoutIdentity: string }): Promise<string> {
41
66
  const cwd = join(repo.cwd, ref.subdir);
42
67
  if (!lstatSync(cwd, { throwIfNoEntry: false })?.isDirectory() || realpathSync(cwd) !== cwd || !within(repo.cwd, cwd))
43
68
  throw new WorkerRefusal("Worker subdirectory is not a canonical directory inside its enrolled checkout");
69
+ if (continuation) {
70
+ const { gitDir, checkoutIdentity } = continuation;
71
+ const unchanged = () => workerCheckoutIdentity(repo.cwd, gitDir, cwd) === checkoutIdentity;
72
+ // Like the clean preflight, check the exact Git binding after the asynchronous index scan.
73
+ if (!unchanged() || !await workerIndexHasOrdinaryFiles(repo.cwd, gitDir)
74
+ || !await workerMemoryRepositoryMatches(cwd, { ...ref, repoId: repo.id, repoRoot: repo.cwd, gitDir }) || !unchanged())
75
+ throw new WorkerRefusal("Worker continuation no longer matches the original checkout and Git revision");
76
+ return cwd;
77
+ }
44
78
  const observed = await workerRepositoryHead(cwd);
45
79
  if (!observed || observed.repoId !== repo.id || observed.revision !== ref.revision || observed.subdir !== ref.subdir)
46
80
  throw new WorkerRefusal("Worker checkout must be clean at the exact requested Git revision and subdirectory");
@@ -65,7 +99,7 @@ function readClaim(gitDir: string) {
65
99
  } finally { closeSync(fd); }
66
100
  }
67
101
 
68
- function syncDirectory(path: string): void {
102
+ export function syncDirectory(path: string): void {
69
103
  const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
70
104
  try { fsyncSync(fd); } finally { closeSync(fd); }
71
105
  }
@@ -1,11 +1,12 @@
1
- import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync, type Stats } from "node:fs";
1
+ import { constants, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readSync, unlinkSync, type Stats } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { Value } from "@sinclair/typebox/value";
4
4
  import { HostConnection } from "../omp/host";
5
5
  import { NativeJournalFormatError, readNativeSessionId } from "../omp/native-journal";
6
- import { ownsCheckout, privateWorkerDirectory } from "./worker-checkout";
7
- import { workerExit, type WorkerIdentity, type WorkerLedger, type WorkerReceipt } from "./worker-ledger";
6
+ import { ownsCheckout, privateWorkerDirectory, syncDirectory } from "./worker-checkout";
7
+ import { workerExit, workerReaped, type WorkerIdentity, type WorkerJournalDirectory, type WorkerLedger, type WorkerReceipt } from "./worker-ledger";
8
8
  import { WorkerRefusal } from "./worker-request";
9
+ import { trustedWorkerPath } from "./worker-trust";
9
10
  import { remoteLanePaths, type WorkerPolicy, type WorkerProbe } from "./worker-wire";
10
11
 
11
12
  export const WORKER_ATTEMPT_ENV = "OMP_SUPERAGENT_WORKER_ATTEMPT";
@@ -14,18 +15,51 @@ export const WORKER_SESSION_ENV = "OMP_SUPERAGENT_WORKER_EXPECTED_SESSION";
14
15
  export function workerPaths(policy: WorkerPolicy, laneId: string) {
15
16
  const { socketPath, sessionFile } = remoteLanePaths(policy, laneId);
16
17
  if (Buffer.byteLength(socketPath) > 100) throw new WorkerRefusal("Worker socket path exceeds 100 bytes");
17
- return { socketPath, sessionFile, exitPath: `${socketPath}.exit.json`, logPath: join(dirname(socketPath), `${laneId}.log`) };
18
+ return { socketPath, sessionFile, exitPath: `${socketPath}.exit.json`, reapedPath: `${socketPath}.reaped.json`,
19
+ logPath: join(dirname(socketPath), `${laneId}.log`) };
18
20
  }
19
21
  type WorkerPaths = ReturnType<typeof workerPaths>;
20
22
  type WorkerFiles = Awaited<ReturnType<typeof readWorkerFiles>>;
21
23
 
22
- function checkedFile(path: string): Stats | undefined {
24
+ function checkedFile(path: string, privateJournal = false): Stats | undefined {
23
25
  const stat = lstatSync(path, { throwIfNoEntry: false });
24
- if (stat && (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0))
26
+ if (stat && (!stat.isFile() || stat.uid !== process.getuid?.()
27
+ || (privateJournal ? stat.nlink !== 1 || (stat.mode & 0o7111) !== 0 : (stat.mode & 0o022) !== 0)))
25
28
  throw new WorkerRefusal("Worker session or exit record is not an owned regular file");
26
29
  return stat;
27
30
  }
28
31
 
32
+ function checkedJournalDirectory(path: string, expected?: WorkerJournalDirectory): WorkerJournalDirectory {
33
+ if (!privateWorkerDirectory(path)) throw new WorkerRefusal("Private worker journal directory is missing");
34
+ trustedWorkerPath(path, [], "directory");
35
+ const { dev, ino } = lstatSync(path, { bigint: true });
36
+ const actual = { dev: dev.toString(), ino: ino.toString() };
37
+ if (expected && (actual.dev !== expected.dev || actual.ino !== expected.ino))
38
+ throw new WorkerRefusal("Private worker journal directory changed");
39
+ return actual;
40
+ }
41
+
42
+ /** An existing directory is not proof that the worker exclusively created it. */
43
+ export function prepareWorkerJournalDirectory(paths: WorkerPaths, expected?: WorkerJournalDirectory): WorkerJournalDirectory | undefined {
44
+ const path = dirname(paths.sessionFile);
45
+ if (expected) return checkedJournalDirectory(path, expected);
46
+ trustedWorkerPath(dirname(path), [], "directory");
47
+ try { mkdirSync(path, { mode: 0o700 }); }
48
+ catch (error) {
49
+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;
50
+ if (!privateWorkerDirectory(path)) throw new WorkerRefusal("Worker journal directory changed during preparation");
51
+ return undefined; // Keep legacy file-permission checks; never adopt the namespace.
52
+ }
53
+ const directory = checkedJournalDirectory(path);
54
+ syncDirectory(dirname(path)); // Persist the new namespace before the ledger can attest it.
55
+ return directory;
56
+ }
57
+
58
+ function checkedJournal(paths: WorkerPaths, directory?: WorkerJournalDirectory): Stats | undefined {
59
+ if (directory) checkedJournalDirectory(dirname(paths.sessionFile), directory);
60
+ return checkedFile(paths.sessionFile, directory !== undefined);
61
+ }
62
+
29
63
  function checkedSocket(path: string): Stats | undefined {
30
64
  const stat = lstatSync(path, { throwIfNoEntry: false });
31
65
  if (stat && (!stat.isSocket() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600))
@@ -37,6 +71,10 @@ function sameFile(expected: Pick<Stats, "dev" | "ino">, observed: Stats | undefi
37
71
  return observed !== undefined && expected.dev === observed.dev && expected.ino === observed.ino;
38
72
  }
39
73
 
74
+ function permissionDenied(error: unknown): boolean {
75
+ return error instanceof Error && "code" in error && (error.code === "EACCES" || error.code === "EPERM");
76
+ }
77
+
40
78
  function pidAlive(pid: number): boolean {
41
79
  try { process.kill(pid, 0); return true; }
42
80
  catch (error) {
@@ -46,45 +84,89 @@ function pidAlive(pid: number): boolean {
46
84
  }
47
85
  }
48
86
 
49
- export async function readWorkerFiles(paths: WorkerPaths) {
87
+ export async function readWorkerFiles(paths: WorkerPaths, directory?: WorkerJournalDirectory) {
50
88
  privateWorkerDirectory(dirname(paths.socketPath));
51
89
  privateWorkerDirectory(dirname(dirname(paths.sessionFile)));
52
90
  privateWorkerDirectory(dirname(paths.sessionFile));
53
91
  const socket = checkedSocket(paths.socketPath);
54
92
  const exit = checkedFile(paths.exitPath);
55
- const session = checkedFile(paths.sessionFile);
93
+ const session = checkedJournal(paths, directory);
56
94
  let sessionId: string | null = null;
57
95
  if (session) {
58
96
  try { sessionId = await readNativeSessionId(paths.sessionFile, session) ?? null; }
59
97
  catch (error) {
60
- if (!(error instanceof NativeJournalFormatError)) throw error;
61
98
  // A present but unrecognized journal is not an absent native session.
99
+ if (error instanceof NativeJournalFormatError) sessionId = null;
100
+ else if (permissionDenied(error))
101
+ throw new WorkerRefusal("Worker native journal cannot be read", { cause: error });
102
+ else throw error;
62
103
  }
63
- if (!sameFile(session, checkedFile(paths.sessionFile))) throw new WorkerRefusal("Worker journal changed while reading its identity");
104
+ if (!sameFile(session, checkedJournal(paths, directory))) throw new WorkerRefusal("Worker journal changed while reading its identity");
64
105
  }
65
106
  return { socket, exit, session, sessionId };
66
107
  }
67
108
 
68
- function provenExit(paths: WorkerPaths, files: WorkerFiles, receipt: WorkerReceipt) {
69
- if (!files.exit || !files.sessionId || files.exit.size > 4096 || (files.exit.mode & 0o077) !== 0) return null;
70
- const fd = openSync(paths.exitPath, constants.O_RDONLY | constants.O_NOFOLLOW);
109
+ function readExitRecord(path: string, expected: Stats | undefined): unknown {
110
+ if (!expected || expected.size > 4096 || (expected.mode & 0o477) !== 0o400) return null;
111
+ let fd: number;
112
+ try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
113
+ catch (error) {
114
+ if (permissionDenied(error)) return null;
115
+ throw error;
116
+ }
71
117
  try {
72
118
  const stat = fstatSync(fd);
73
- if (!sameFile(files.exit, stat) || stat.size !== files.exit.size) return null;
74
- let exit: unknown;
75
- try { exit = JSON.parse(readFileSync(fd, "utf8")); }
119
+ if (!sameFile(expected, stat) || stat.size !== expected.size || stat.mode !== expected.mode) return null;
120
+ const bytes = Buffer.alloc(stat.size);
121
+ if (readSync(fd, bytes) !== bytes.length) return null;
122
+ const after = fstatSync(fd);
123
+ if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs || after.ctimeMs !== stat.ctimeMs) return null;
124
+ try { return JSON.parse(bytes.toString("utf8")); }
76
125
  catch (error) {
77
126
  if (error instanceof SyntaxError) return null;
78
127
  throw error;
79
128
  }
80
- if (!Value.Check(workerExit, exit) || exit.workerAttempt !== receipt.attempt || exit.sessionFile !== paths.sessionFile
81
- || exit.sessionId !== files.sessionId || receipt.sessionId !== null && exit.sessionId !== receipt.sessionId
82
- || receipt.phase === "live" && (exit.pid !== receipt.identity.pid || exit.ownerPid !== receipt.identity.ownerPid)
83
- || exit.pid === exit.ownerPid) return null;
84
- return exit;
85
129
  } finally { closeSync(fd); }
86
130
  }
87
131
 
132
+ function matchesExit(paths: WorkerPaths, receipt: WorkerReceipt, proof: {
133
+ readonly workerAttempt: string; readonly sessionFile: string; readonly pid: number; readonly ownerPid: number;
134
+ }): boolean {
135
+ return proof.workerAttempt === receipt.attempt && proof.sessionFile === paths.sessionFile && proof.pid !== proof.ownerPid
136
+ && (receipt.phase !== "live" || (proof.pid === receipt.identity.pid && proof.ownerPid === receipt.identity.ownerPid));
137
+ }
138
+
139
+ function readVerifiedExit(paths: WorkerPaths, receipt: WorkerReceipt, stat: Stats | undefined) {
140
+ const exit = readExitRecord(paths.exitPath, stat);
141
+ return Value.Check(workerExit, exit) && matchesExit(paths, receipt, exit)
142
+ && (receipt.sessionId === null || exit.sessionId === receipt.sessionId) ? exit : null;
143
+ }
144
+
145
+ function journalHeld() {
146
+ return new WorkerRefusal("Worker checkout was released after verified process exit; the original journal remains unverified and cannot reopen");
147
+ }
148
+
149
+ /** The private owner's receipt, not the damaged journal, decides checkout-only retirement. */
150
+ function retireWithoutJournal(ledger: WorkerLedger, paths: WorkerPaths, receipt: WorkerReceipt): boolean {
151
+ if (receipt.phase !== "launching" && receipt.phase !== "live") return false;
152
+ const proof = () => {
153
+ if (!privateWorkerDirectory(dirname(paths.socketPath)) || lstatSync(paths.socketPath, { throwIfNoEntry: false })) return null;
154
+ const reaped = readExitRecord(paths.reapedPath, checkedFile(paths.reapedPath));
155
+ if (Value.Check(workerReaped, reaped) && matchesExit(paths, receipt, reaped)
156
+ && (receipt.phase === "launching" || reaped.settledSessionId === receipt.identity.sessionId)) return reaped;
157
+ // Before attachment, no managed work could have been submitted. An old
158
+ // exit receipt proves process exit, but not settlement of an attached lane.
159
+ return receipt.phase === "launching" ? readVerifiedExit(paths, receipt, checkedFile(paths.exitPath)) : null;
160
+ };
161
+ const before = proof();
162
+ if (!before || pidAlive(before.pid) || pidAlive(before.ownerPid)) return false;
163
+ return ledger.retire(receipt, { journalHeld: true, cleanup: () => {
164
+ const current = proof();
165
+ if (!current || JSON.stringify(current) !== JSON.stringify(before) || pidAlive(before.pid) || pidAlive(before.ownerPid))
166
+ throw new WorkerRefusal("Worker process exit evidence changed before checkout retirement");
167
+ } });
168
+ }
169
+
88
170
  export function absentWorkerHost(files: WorkerFiles, receipt: WorkerReceipt | null): WorkerProbe {
89
171
  const expected = receipt?.sessionId ?? null;
90
172
  const uncertain = !!files.socket || files.sessionId !== expected || !!files.session !== (expected !== null)
@@ -111,7 +193,13 @@ export async function attestWorkerHost(paths: WorkerPaths, files: WorkerFiles, r
111
193
  }
112
194
 
113
195
  export async function inspectWorkerHost(ledger: WorkerLedger, paths: WorkerPaths, receipt: WorkerReceipt | null, attest = true): Promise<WorkerProbe> {
114
- const files = await readWorkerFiles(paths);
196
+ if (receipt?.phase === "checkout-released") throw journalHeld();
197
+ let files: WorkerFiles;
198
+ try { files = await readWorkerFiles(paths, receipt?.journalDirectory); }
199
+ catch (error) {
200
+ if (error instanceof WorkerRefusal && receipt && retireWithoutJournal(ledger, paths, receipt)) throw journalHeld();
201
+ throw error;
202
+ }
115
203
  if (!receipt || receipt.phase === "released") return absentWorkerHost(files, receipt);
116
204
  if (receipt.phase === "reserved") {
117
205
  const untouched = absentWorkerHost(files, receipt);
@@ -119,14 +207,15 @@ export async function inspectWorkerHost(ledger: WorkerLedger, paths: WorkerPaths
119
207
  return untouched;
120
208
  return { ...untouched, uncertain: true };
121
209
  }
122
- const exit = provenExit(paths, files, receipt);
210
+ const recorded = readVerifiedExit(paths, receipt, files.exit);
211
+ const exit = recorded && recorded.sessionId === files.sessionId ? recorded : null;
123
212
  const pid = receipt.phase === "live" ? receipt.identity.pid : exit?.pid ?? null;
124
213
  const owner = receipt.phase === "live" ? receipt.identity.ownerPid : exit?.ownerPid ?? null;
125
214
  const nativeAlive = pid !== null && pidAlive(pid);
126
215
  const ownerAlive = owner !== null && pidAlive(owner);
127
216
  if (exit && !nativeAlive && !ownerAlive && (!files.socket || receipt.phase === "live" && sameFile(receipt.identity, files.socket))) {
128
217
  const cleanup = () => {
129
- if (!files.session || !sameFile(files.session, checkedFile(paths.sessionFile))
218
+ if (!files.session || !sameFile(files.session, checkedJournal(paths, receipt.journalDirectory))
130
219
  || !files.exit || !sameFile(files.exit, checkedFile(paths.exitPath))
131
220
  || pidAlive(exit.pid) || pidAlive(exit.ownerPid)) throw new WorkerRefusal("Worker native exit evidence changed");
132
221
  const socket = checkedSocket(paths.socketPath);
@@ -139,6 +228,7 @@ export async function inspectWorkerHost(ledger: WorkerLedger, paths: WorkerPaths
139
228
  return { socket: false, sessionFile: true, sessionId: exit.sessionId, pid: null, pidAlive: false, ownerAlive: false,
140
229
  uncertain: false, ...(clean ? { exitGeneration: receipt.generation } : {}) };
141
230
  }
231
+ if (!exit && !files.socket && retireWithoutJournal(ledger, paths, receipt)) throw journalHeld();
142
232
  if (attest && files.socket && !exit) {
143
233
  try {
144
234
  const identity = await attestWorkerHost(paths, files, receipt);
@@ -30,6 +30,13 @@ export const workerExit = Type.Object({
30
30
  persisted: Type.Literal(true),
31
31
  observationsFlushed: Type.Literal(true),
32
32
  });
33
+ export const workerReaped = Type.Object({
34
+ pid: workerPid, ownerPid: workerPid, sessionFile: identityFields.sessionFile,
35
+ workerAttempt: Type.String(), settledSessionId: Type.Optional(sessionId),
36
+ });
37
+
38
+ const journalDirectory = Type.Object({ dev: Type.String({ pattern: "^[0-9]+$" }), ino: Type.String({ pattern: "^[0-9]+$" }) });
39
+ export type WorkerJournalDirectory = Readonly<Static<typeof journalDirectory>>;
33
40
  const receiptFields = {
34
41
  laneId: Type.String(),
35
42
  generation: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
@@ -42,6 +49,8 @@ const receiptFields = {
42
49
  attempt: Type.String({ pattern: "^[0-9a-f-]{36}$" }),
43
50
  launcherPid: workerPid,
44
51
  sessionId: Type.Union([sessionId, Type.Null()]),
52
+ journalDirectory: Type.Optional(journalDirectory),
53
+ checkoutIdentity: Type.Optional(Type.String({ pattern: "^[0-9]+:[0-9]+/[0-9]+:[0-9]+/[0-9]+:[0-9]+$" })),
45
54
  memory: Type.Optional(workerMemoryBinding),
46
55
  privateMemoryPrepared: Type.Optional(Type.Literal(true)),
47
56
  };
@@ -50,11 +59,15 @@ const receipt = Type.Union([
50
59
  Type.Object({ ...receiptFields, phase: Type.Literal("launching") }),
51
60
  Type.Object({ ...receiptFields, phase: Type.Literal("live"), identity }),
52
61
  Type.Object({ ...receiptFields, phase: Type.Literal("released"), exitVerified: Type.Optional(Type.Literal(true)) }),
62
+ Type.Object({ ...receiptFields, phase: Type.Literal("checkout-released") }),
53
63
  ]);
54
64
  export type WorkerReceipt = Readonly<Static<typeof receipt>>;
55
65
  export type WorkerIdentity = Readonly<Static<typeof identity>>;
56
66
  type ReservedReceipt = Extract<WorkerReceipt, { phase: "reserved" }>;
67
+ type Retirement = { readonly sessionId: string; readonly clean: boolean; readonly cleanup: () => void }
68
+ | { readonly journalHeld: true; readonly cleanup: () => void };
57
69
  type WorkerSeal = Pick<WorkerLaneRef, "generation" | "repoId" | "revision" | "subdir"> & { readonly repoRoot: string };
70
+ const occupied = "phase NOT IN ('released', 'checkout-released')";
58
71
 
59
72
  function decode(row: { readonly data: string } | null): WorkerReceipt | null {
60
73
  if (!row) return null;
@@ -113,7 +126,7 @@ export class WorkerLedger {
113
126
  }
114
127
 
115
128
  active(): WorkerReceipt[] {
116
- return this.#db.query<{ data: string }, []>("SELECT data FROM worker_lanes WHERE phase != 'released'")
129
+ return this.#db.query<{ data: string }, []>(`SELECT data FROM worker_lanes WHERE ${occupied}`)
117
130
  .all().flatMap(row => decode(row) ?? []);
118
131
  }
119
132
 
@@ -161,10 +174,12 @@ export class WorkerLedger {
161
174
  if (current && (current.phase !== "released" || current.generation >= ref.generation)
162
175
  || current?.attempt !== previous?.attempt || current?.phase !== previous?.phase)
163
176
  throw new WorkerRefusal("Worker lane generation is already reserved or no longer current");
164
- const active = this.#db.query<{ count: number }, []>("SELECT count(*) AS count FROM worker_lanes WHERE phase != 'released'").get();
177
+ const active = this.#db.query<{ count: number }, []>(`SELECT count(*) AS count FROM worker_lanes WHERE ${occupied}`).get();
165
178
  if (!active || active.count >= this.#capacity) throw new WorkerRefusal("Worker Host capacity is occupied");
166
179
  const value: ReservedReceipt = { ...ref, ...binding, attempt: crypto.randomUUID(), launcherPid: process.pid,
167
- phase: "reserved", sessionId: current?.sessionId ?? null };
180
+ phase: "reserved", sessionId: current?.sessionId ?? null,
181
+ ...(current?.journalDirectory && { journalDirectory: current.journalDirectory }),
182
+ ...(current?.checkoutIdentity && { checkoutIdentity: current.checkoutIdentity }) };
168
183
  this.#write(value);
169
184
  return value;
170
185
  }).immediate();
@@ -183,15 +198,19 @@ export class WorkerLedger {
183
198
  return this.#replaceCurrent(current, () => next);
184
199
  }
185
200
 
186
- retire(current: WorkerReceipt, exit?: { readonly sessionId: string; readonly clean: boolean; readonly cleanup: () => void }): boolean {
201
+ retire(current: WorkerReceipt, exit?: Retirement): boolean {
187
202
  return this.#replaceCurrent(current, () => {
188
203
  exit?.cleanup();
189
204
  releaseCheckout(current);
190
- const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest, memory } = current;
191
- const sessionId = exit?.sessionId ?? current.sessionId;
192
- return { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
193
- phase: "released", sessionId, ...(sessionId !== null && memory ? { memory } : {}),
194
- ...(exit?.clean && { exitVerified: true }) };
205
+ const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
206
+ journalDirectory, checkoutIdentity, memory } = current;
207
+ const verified = exit && "sessionId" in exit ? exit : undefined;
208
+ const sessionId = verified?.sessionId ?? current.sessionId;
209
+ const binding = { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
210
+ sessionId, ...(journalDirectory && { journalDirectory }), ...(checkoutIdentity && { checkoutIdentity }),
211
+ ...(sessionId !== null && memory ? { memory } : {}) };
212
+ if (exit && "journalHeld" in exit) return { ...binding, phase: "checkout-released" };
213
+ return { ...binding, phase: "released", ...(verified?.clean && { exitVerified: true }) };
195
214
  });
196
215
  }
197
216
  }
@@ -272,6 +272,19 @@ async function* gitRecords(root: string, args: readonly string[]): AsyncGenerato
272
272
  }
273
273
  }
274
274
 
275
+ /** Keep the existing non-submodule boundary without comparing worktree or index contents to HEAD. */
276
+ export async function workerIndexHasOrdinaryFiles(root: string, gitDir: string): Promise<boolean> {
277
+ const records = gitRecords(root, [`--git-dir=${gitDir}`, `--work-tree=${root}`, "ls-files", "--stage", "-z"]);
278
+ try {
279
+ for (;;) {
280
+ const record = await records.next();
281
+ if (record.done) return record.value;
282
+ const tab = record.value.indexOf(9);
283
+ if (tab < 0 || !/^(100644|100755|120000) [0-9a-f]+ [0-3]$/.test(record.value.toString("latin1", 0, tab))) return false;
284
+ }
285
+ } finally { await records.return(false); }
286
+ }
287
+
275
288
  async function matchesCommit(root: string, gitArgs: readonly string[], revision: string): Promise<boolean> {
276
289
  const index = gitRecords(root, [...gitArgs, "ls-files", "--stage", "-v", "-z"]);
277
290
  const tree = gitRecords(root, [...gitArgs, "ls-tree", "-r", "-z", revision]);
@@ -1,12 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { lstatSync, type Stats } from "node:fs";
3
- import { dirname } from "node:path";
3
+ import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { startHost } from "../omp/host";
6
- import { boundWorkspace, enrolledRepo, privateWorkerDirectory, reserveCheckout } from "./worker-checkout";
7
- import { absentWorkerHost, attestWorkerHost, inspectWorkerHost, readWorkerFiles,
6
+ import { boundWorkspace, enrolledRepo, privateWorkerDirectory, reserveCheckout, workerCheckoutIdentity } from "./worker-checkout";
7
+ import { absentWorkerHost, attestWorkerHost, inspectWorkerHost, prepareWorkerJournalDirectory, readWorkerFiles,
8
8
  WORKER_ATTEMPT_ENV, WORKER_SESSION_ENV, workerPaths } from "./worker-host";
9
- import { WorkerLedger, type WorkerReceipt } from "./worker-ledger";
9
+ import { WorkerLedger, type WorkerJournalDirectory, type WorkerReceipt } from "./worker-ledger";
10
10
  import { WORKER_MEMORY_WIRE_ENV } from "./worker-memory-storage";
11
11
  import { assertWorkerGitStartup, requireWorkerStartupFlags, workerLaunchProfile, workerManagedUlwPath } from "./worker-profile";
12
12
  import { parseWorkerPolicy, parseWorkerRequest, WorkerRefusal } from "./worker-request";
@@ -25,6 +25,7 @@ type AttachPermit = {
25
25
  readonly pid: number; readonly ownerPid: number;
26
26
  readonly socket: { readonly dev: string; readonly ino: string };
27
27
  readonly journal: { readonly dev: string; readonly ino: string };
28
+ readonly journalDirectory?: WorkerJournalDirectory;
28
29
  };
29
30
  type WorkerReply = { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly error: string };
30
31
  type WorkerPreparation = { readonly kind: "reply"; readonly reply: WorkerReply } | ({ readonly kind: "attach" } & AttachPermit);
@@ -52,9 +53,19 @@ async function describeWorker(policy: WorkerPolicy, workspace?: Workspace): Prom
52
53
  const platform = process.platform;
53
54
  if (platform !== "linux" && platform !== "darwin") throw new WorkerRefusal("Unsupported worker platform");
54
55
  const { workerId, stateDir, repos, capacity } = policy;
55
- // Keep process/Git subprocess counts bounded even when the policy lists many repos.
56
- for (const repo of repos) await enrolledRepo(policy, repo);
57
- if (workspace) await boundWorkspace(findRepo(policy, workspace.repoId), workspace);
56
+ if (workspace) {
57
+ const repo = findRepo(policy, workspace.repoId);
58
+ const gitDir = await enrolledRepo(policy, repo);
59
+ await boundWorkspace(repo, workspace);
60
+ if (lstatSync(join(stateDir, "worker.sqlite"), { throwIfNoEntry: false })) {
61
+ const service = new WorkerService(policy);
62
+ try { await service.reap({ repoId: repo.id, repoRoot: repo.cwd, gitDir }); }
63
+ finally { service.close(); }
64
+ }
65
+ } else {
66
+ // Enrollment-wide inventory still validates all its registered checkouts.
67
+ for (const repo of repos) await enrolledRepo(policy, repo);
68
+ }
58
69
  return { workerId, platform, stateDir, repos, capacity, active: WorkerLedger.count(policy) };
59
70
  }
60
71
 
@@ -82,13 +93,15 @@ class WorkerService {
82
93
  return current;
83
94
  }
84
95
 
85
- async #reap(): Promise<void> {
96
+ async reap(scope?: Pick<WorkerReceipt, "repoId" | "repoRoot" | "gitDir">): Promise<void> {
86
97
  for (const receipt of this.#ledger.active()) {
98
+ if (scope && (scope.repoId !== receipt.repoId || scope.repoRoot !== receipt.repoRoot || scope.gitDir !== receipt.gitDir)) continue;
87
99
  if (!this.#policy.repos.some(repo => repo.id === receipt.repoId && repo.cwd === receipt.repoRoot)) continue;
88
100
  try { await inspectWorkerHost(this.#ledger, workerPaths(this.#policy, receipt.laneId), receipt, false); }
89
101
  catch (error) {
90
102
  if (!(error instanceof Error)) throw error;
91
- // Damaged or unobservable evidence still consumes capacity.
103
+ // A refused inspection does not free an unverified reservation.
104
+ // Checkout-only retirement may already have committed before refusal.
92
105
  }
93
106
  }
94
107
  }
@@ -104,9 +117,30 @@ class WorkerService {
104
117
  return { ...probe, uncertain: true, pid: null, sessionId: null };
105
118
  const absent = !probe.uncertain && !probe.socket && !probe.pidAlive && !probe.ownerAlive && probe.pid === null;
106
119
  const sealed = absent && this.#ledger.confirmRelease(ref, lane.repo.cwd, { observed, reconcile });
120
+ let reopenActive: number | undefined;
121
+ const released = this.#receipt(lane);
122
+ // Released with an exact readable session is also valid after an attempt
123
+ // that reached no Host. It does not manufacture an exitGeneration for it.
124
+ if (sealed && released?.phase === "released" && released.attempt === observed?.attempt
125
+ && probe.sessionId && released.sessionId === probe.sessionId
126
+ && released.checkoutIdentity) {
127
+ try {
128
+ if (await enrolledRepo(this.#policy, lane.repo) === released.gitDir) {
129
+ await boundWorkspace(lane.repo, ref, { gitDir: released.gitDir, checkoutIdentity: released.checkoutIdentity });
130
+ const current = this.#receipt(lane);
131
+ const active = this.#ledger.active().length;
132
+ if (current?.attempt === released.attempt && current.phase === "released" && active < this.#policy.capacity)
133
+ reopenActive = active;
134
+ }
135
+ } catch (error) {
136
+ if (!(error instanceof WorkerRefusal)) throw error;
137
+ // Exit is independent of checkout readiness; keep its proof intact.
138
+ }
139
+ }
107
140
  const memoryLaunch = process.env[WORKER_MEMORY_WIRE_ENV] === "1" && absent && !probe.sessionFile && !sealed;
108
141
  return { ...probe, ...(sealed && { sealedGeneration: ref.generation }),
109
142
  ...(sealed && exitGeneration === ref.generation && { exitGeneration }),
143
+ ...(reopenActive !== undefined && { reopenActive }),
110
144
  ...(memoryLaunch && { memoryLaunchVersion: 1 }),
111
145
  ...(!probe.uncertain && probe.socket && observed?.generation === ref.generation
112
146
  && observed.privateMemoryPrepared && observed.memory?.proof && { memoryPreparedVersion: 1 }),
@@ -128,15 +162,17 @@ class WorkerService {
128
162
  return { pid: probe.pid };
129
163
  throw new WorkerRefusal("Worker lane generation has no verified live Host; it cannot reopen");
130
164
  }
131
- await this.#reap();
165
+ await this.reap();
132
166
  const previous = this.#receipt(lane);
167
+ if (previous?.phase === "checkout-released")
168
+ throw new WorkerRefusal("Worker checkout was released, but the original journal remains unverified and cannot reopen");
133
169
  if (observed?.attempt !== previous?.attempt || (previous && previous.phase !== "released"))
134
170
  throw new WorkerRefusal("Worker lane has a resident or uncertain launch");
135
171
  if (previous && ref.generation <= previous.generation)
136
172
  throw new WorkerRefusal("Worker does not reopen a previous lane generation");
137
173
  const gitDir = await enrolledRepo(this.#policy, lane.repo);
138
174
  if (previous && previous.gitDir !== gitDir) throw new WorkerRefusal("Worker checkout metadata directory changed");
139
- const initial = await readWorkerFiles(lane.paths);
175
+ const initial = await readWorkerFiles(lane.paths, previous?.journalDirectory);
140
176
  if (absentWorkerHost(initial, previous).uncertain) throw new WorkerRefusal("Worker lane has an unverified socket or journal");
141
177
  if (launch.memorySync && process.env[WORKER_MEMORY_WIRE_ENV] !== "1")
142
178
  throw new WorkerRefusal("Worker memory is not supported by this transport");
@@ -145,23 +181,43 @@ class WorkerService {
145
181
  const memoryKey = previous?.memory?.key ?? (launch.memorySync ? crypto.randomUUID() : undefined);
146
182
  // Commit admission before reserving the checkout, publishing any session
147
183
  // artifacts, or starting the stock OMP process.
148
- const reservation = this.#ledger.reserve(ref, { repoRoot: lane.repo.cwd, gitDir, launchDigest,
184
+ let reservation = this.#ledger.reserve(ref, { repoRoot: lane.repo.cwd, gitDir, launchDigest,
149
185
  ...(previous?.memory && { memory: previous.memory }) }, previous);
186
+ const continuation = previous?.phase === "released" && previous.sessionId && previous.checkoutIdentity
187
+ ? { gitDir, checkoutIdentity: previous.checkoutIdentity } : undefined;
188
+ const selected = join(lane.repo.cwd, ref.subdir);
150
189
  let cwd: string;
151
190
  let target: ReturnType<typeof workerLaunchProfile>;
152
191
  let managedUlwPath: string;
153
192
  try {
154
193
  reserveCheckout(reservation);
155
- cwd = await boundWorkspace(lane.repo, ref);
194
+ const checkoutIdentity = workerCheckoutIdentity(lane.repo.cwd, gitDir, selected);
195
+ if (previous?.checkoutIdentity && previous.checkoutIdentity !== checkoutIdentity)
196
+ throw new WorkerRefusal("Worker continuation no longer matches the original checkout directories");
197
+ cwd = await boundWorkspace(lane.repo, ref, continuation);
156
198
  await assertWorkerGitStartup(lane.repo);
157
199
  target = workerLaunchProfile(this.#policy, cwd);
158
200
  managedUlwPath = await workerManagedUlwPath(this.#policy.repos);
159
201
  await requireWorkerStartupFlags(target.executable, this.#policy.stateDir, target.env);
160
- if (absentWorkerHost(await readWorkerFiles(lane.paths), reservation).uncertain)
202
+ if (absentWorkerHost(await readWorkerFiles(lane.paths, reservation.journalDirectory), reservation).uncertain)
161
203
  throw new WorkerRefusal("Worker socket or journal changed before launch");
162
204
  privateWorkerDirectory(dirname(lane.paths.socketPath), true);
163
205
  privateWorkerDirectory(dirname(dirname(lane.paths.sessionFile)), true);
164
- privateWorkerDirectory(dirname(lane.paths.sessionFile), true);
206
+ // Authorize stock-created modes only after establishing custody of a
207
+ // new private namespace, before either SDK preparation or OMP opens it.
208
+ const directory = prepareWorkerJournalDirectory(lane.paths, reservation.journalDirectory);
209
+ if (continuation) {
210
+ await assertWorkerGitStartup(lane.repo);
211
+ await boundWorkspace(lane.repo, ref, continuation);
212
+ }
213
+ const pin = checkoutIdentity && workerCheckoutIdentity(lane.repo.cwd, gitDir, cwd) === checkoutIdentity ? checkoutIdentity : null;
214
+ if (previous?.checkoutIdentity && pin !== previous.checkoutIdentity)
215
+ throw new WorkerRefusal("Worker checkout directories changed before launch");
216
+ if ((pin && pin !== reservation.checkoutIdentity) || (directory && !reservation.journalDirectory)) {
217
+ const prepared = { ...reservation, ...(pin && { checkoutIdentity: pin }), ...(directory && { journalDirectory: directory }) };
218
+ if (!this.#ledger.transition(reservation, prepared)) throw new WorkerRefusal("Worker launch reservation is no longer current");
219
+ reservation = prepared;
220
+ }
165
221
  } catch (error) {
166
222
  this.#ledger.retire(reservation);
167
223
  throw error;
@@ -209,7 +265,7 @@ class WorkerService {
209
265
  if (receipt?.attempt !== observed.attempt || receipt.phase !== "live" ||
210
266
  !probe.socket || !probe.pidAlive || !probe.ownerAlive)
211
267
  throw new WorkerRefusal("Worker lane does not have an attachable native Host");
212
- const files = await readWorkerFiles(lane.paths);
268
+ const files = await readWorkerFiles(lane.paths, receipt.journalDirectory);
213
269
  if (!files.session) throw new WorkerRefusal("No owned worker socket/journal/checkout");
214
270
  const { pid, ownerPid, sessionId, sessionFile, ...identity } = await attestWorkerHost(lane.paths, files, receipt);
215
271
  const { socketPath } = lane.paths;
@@ -219,7 +275,8 @@ class WorkerService {
219
275
  if (current?.phase !== "live" || current.generation !== ref.generation || current.attempt !== receipt.attempt)
220
276
  throw new WorkerRefusal("Worker lane changed before attach");
221
277
  return { generation: receipt.generation, workerAttempt: receipt.attempt,
222
- socketPath, sessionFile, sessionId, pid, ownerPid, socket, journal };
278
+ socketPath, sessionFile, sessionId, pid, ownerPid, socket, journal,
279
+ ...(receipt.journalDirectory && { journalDirectory: receipt.journalDirectory }) };
223
280
  }
224
281
  }
225
282
 
@@ -39,6 +39,8 @@ export interface WorkerProbe {
39
39
  readonly sealedGeneration?: number;
40
40
  /** Exact generation whose persisted native exit the worker verified. */
41
41
  readonly exitGeneration?: number;
42
+ /** An exact exited session can reopen in its original checkout; reported occupancy is read-only. */
43
+ readonly reopenActive?: number;
42
44
  /** The wire accepts opt-in on a fresh, absent, unsealed worker lane. */
43
45
  readonly memoryLaunchVersion?: 1;
44
46
  /** Private storage was prepared for this attempt; readiness can be checked after native init. */
@@ -62,7 +64,7 @@ export const WorkerDescriptionSchema = Type.Object({
62
64
  const probe = Type.Object({
63
65
  socket: Type.Boolean(), sessionFile: Type.Boolean(), pidAlive: Type.Boolean(), ownerAlive: Type.Boolean(),
64
66
  uncertain: Type.Boolean(), pid: Type.Union([positive, Type.Null()]), sessionId: Type.Union([text, Type.Null()]),
65
- sealedGeneration: Type.Optional(positive), exitGeneration: Type.Optional(positive),
67
+ sealedGeneration: Type.Optional(positive), exitGeneration: Type.Optional(positive), reopenActive: Type.Optional(natural),
66
68
  memoryLaunchVersion: Type.Optional(Type.Literal(1)), memoryPreparedVersion: Type.Optional(Type.Literal(1)),
67
69
  memorySyncVersion: Type.Optional(Type.Literal(1)),
68
70
  });