omp-superagent 0.1.15 → 0.1.17

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.
@@ -0,0 +1,83 @@
1
+ import type { Inbound } from "../contracts";
2
+ import { matchesWrittenCommand, messengerCommandText } from "../messaging/messenger-commands";
3
+ import { record } from "./native-frames";
4
+
5
+ // Native command and branch journal contract from omp-superkit 12d19ec.
6
+ const selector = /^\s*(\/?superstack)(?=\s|$)/i;
7
+ export const headSuperstackTaskPrefix = "superstack\n\n";
8
+
9
+ type HeadSuperstackReceipt =
10
+ | { readonly kind: "enable" | "off" | "held" }
11
+ | { readonly kind: "task"; readonly start: number; readonly view: "written" | "telegram" };
12
+
13
+ // This runs only on original intake. For a task, pin an offset into one of
14
+ // the immutable source views rather than storing another copy of its text.
15
+ export function admitHeadSuperstack(input: Inbound, task: string): HeadSuperstackReceipt | undefined {
16
+ const match = selector.exec(task);
17
+ if (!match || !matchesWrittenCommand(input)) return;
18
+ const written = messengerCommandText(input);
19
+ if (!written.endsWith(task)) return;
20
+ const wrapperLength = written.length - task.length;
21
+ const start = wrapperLength + match[0].length;
22
+ const args = written.slice(start).trim();
23
+ const view = input.route.platform === "telegram" ? input.routingText : written;
24
+ const projected = view !== written;
25
+ if (projected) {
26
+ // An exposed second token on the same line cannot corroborate a masked
27
+ // first token. Telegram only attests the first written slash command.
28
+ const sameLine = /^[^\r\n]*/u.exec(written.slice(start))?.[0];
29
+ const attestedSlash = wrapperLength === 0 && match[1]?.startsWith("/") && input.telegramProtectedCommand === false;
30
+ if (view === undefined || !view.startsWith(written.slice(0, start)) || !/^(?:\s|$)/u.test(view.slice(start))
31
+ || (!attestedSlash && match[1] && sameLine?.includes(match[1]))) return { kind: "held" };
32
+ }
33
+ if (args === "" || args === "off")
34
+ return view?.slice(start).trim() === args ? { kind: args ? "off" : "enable" } : { kind: "held" };
35
+ if (!view?.slice(start).trim()) return { kind: "held" };
36
+ return { kind: "task", start, view: projected ? "telegram" : "written" };
37
+ }
38
+
39
+ export function recordedHeadSuperstack(value: string | null): HeadSuperstackReceipt | null {
40
+ if (value === null) return null;
41
+ const { kind, start, view } = record(JSON.parse(value));
42
+ if (kind === "task" && typeof start === "number" && Number.isSafeInteger(start) && start > 0
43
+ && (view === "written" || view === "telegram")) return { kind, start, view };
44
+ if (kind === "enable" || kind === "off") return { kind };
45
+ return { kind: "held" };
46
+ }
47
+
48
+ export function headSuperstackTaskText(input: Inbound, task: Extract<HeadSuperstackReceipt, { kind: "task" }>): string | undefined {
49
+ return (task.view === "telegram" ? input.routingText : messengerCommandText(input))?.slice(task.start).trim();
50
+ }
51
+
52
+ export function advertisesSuperstack(value: unknown): boolean {
53
+ const { commands } = record(value);
54
+ return Array.isArray(commands) && commands.map(record).some(command =>
55
+ command.name === "superstack" && command.source === "extension"
56
+ && command.description === "Enable branch-local skill routing for an optional task, or use off to disable it");
57
+ }
58
+
59
+ export function superstackBranchEnabled(value: unknown): boolean | undefined {
60
+ const { entries, leafId } = record(value);
61
+ if (!Array.isArray(entries) || (leafId !== null && typeof leafId !== "string")) return undefined;
62
+ const byId = new Map(entries.map(record).map(entry => [entry.id, entry]));
63
+ const visited = new Set<string>();
64
+ let id = leafId;
65
+ while (typeof id === "string" && !visited.has(id)) {
66
+ visited.add(id);
67
+ const entry = byId.get(id);
68
+ if (!entry) return undefined;
69
+ if (entry.type === "custom" && entry.customType === "omp-superstack:state")
70
+ return typeof entry.data === "boolean" ? entry.data : undefined;
71
+ if (entry.parentId !== null && typeof entry.parentId !== "string") return undefined;
72
+ id = entry.parentId;
73
+ }
74
+ return id === null ? false : undefined;
75
+ }
76
+
77
+ export function superstackControlOutcome(id: string, wanted: boolean, enabled: boolean | undefined) {
78
+ if (enabled === undefined) return { state: "uncertain",
79
+ text: `Superstack 설정을 확인하지 못했습니다. 명령을 다시 보내지 않았고 다음 HEAD 요청을 보류했습니다. 원래 세션을 확인하거나 /resolve ${id} 로 보류를 종료하세요.` } as const;
80
+ if (enabled !== wanted) return { state: "cancelled",
81
+ text: "HEAD 브랜치에 요청한 Superstack 설정이 적용되지 않았습니다. 모델 작업은 시작하지 않았습니다." } as const;
82
+ return { state: "done", text: `현재 HEAD 세션 브랜치의 Superstack 설정을 ${enabled ? "켰습니다" : "껐습니다"}. 모델 작업은 시작하지 않았습니다.` } as const;
83
+ }
@@ -5,6 +5,7 @@ import { getAgentDbPath } from "@oh-my-pi/pi-utils/dirs";
5
5
  import { authorizeRoute, type Config } from "../config/config";
6
6
  import type { InputRecord, Route, StorePort } from "../contracts";
7
7
  import { messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
8
+ import { discordWorkThreadSource } from "../messaging/discord-work-thread";
8
9
  import { discardResultAttachment, isOriginalAttachmentMessage, pruneResultAttachments, readResultAttachmentIntent,
9
10
  readResultAttachmentStart, requestedResultPath, ResultAttachmentError, stageResultAttachment,
10
11
  type ResultAttachmentIntent, type ResultAttachmentPayload } from "../messaging/result-attachment";
@@ -56,7 +57,8 @@ export class ResultAttachments {
56
57
  if (route.authorityId !== this.config[route.platform]?.ownerId) {
57
58
  throw new ResultAttachmentError("Result attachments require the configured messenger owner");
58
59
  }
59
- if (!authorizeRoute(this.config, route)) throw new Error("Unauthorized messenger route");
60
+ if (!authorizeRoute(this.config, route) && !discordWorkThreadSource(this.config, this.store, route))
61
+ throw new Error("Unauthorized messenger route");
60
62
  }
61
63
 
62
64
  queue(run: AttachmentRun, intent: ResultAttachmentIntent, admission: {
@@ -36,6 +36,7 @@ import { compareMessageIds } from "../routing/message-order";
36
36
  import { storedWorkflowName, workflowChoice } from "../lane/workflow";
37
37
  import { laneWaitKey, type LaneReport } from "../lane/lane-report";
38
38
  import { laneWatchReplySource } from "../lane/lane-watch";
39
+ import { discordWorkThreadOwnerKey, recordedDiscordWorkThreadSource } from "../messaging/discord-work-thread";
39
40
  import { isResultAttachmentSnapshot } from "../messaging/result-attachment";
40
41
  import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
41
42
  import type { CronUpdate } from "../cron/cron-jobs";
@@ -467,9 +468,27 @@ export class Store implements StorePort {
467
468
  return { lane, failed, original };
468
469
  }
469
470
 
471
+ private scopedWorkSource(input: InputRecord): { sourceId: string; owner: InputRecord } | null {
472
+ const ownerId = this.getMeta(discordWorkThreadOwnerKey(input.id));
473
+ if (ownerId === null) return null;
474
+ const sourceId = this.getMeta(`handoff-source:${input.id}`);
475
+ const source = sourceId && this.ownerSource(sourceId);
476
+ const placement = recordedDiscordWorkThreadSource(this, input.route);
477
+ if (!sourceId || !source || source.id !== ownerId || !placement
478
+ || routeKey(physicalRoute(source.route)) !== routeKey(placement)
479
+ || !input.target || input.target === "main" || this.laneForRoute(input.route)?.id !== input.target
480
+ || (input.id !== `handoff:${sourceId}:lane` && input.id !== `handoff:${sourceId}:${input.target}`
481
+ && (input.id !== `resume:${sourceId}:${input.target}` || this.getMeta(`native-goal-resume-owner:${input.id}`) === null))) {
482
+ throw new Error(`Invalid scoped Discord work-thread binding: ${input.id}`);
483
+ }
484
+ return { sourceId, owner: source };
485
+ }
486
+
470
487
  reportApprovalSource(id: string): InputRecord | null {
471
488
  const input = this.input(id);
472
489
  if (!input || isRetiredScopeInput(id)) return null;
490
+ const scoped = this.scopedWorkSource(input);
491
+ if (scoped) return scoped.owner;
473
492
  const reportId = input.target === "main" ? id : this.getMeta(`handoff-source:${id}`);
474
493
  if (!reportId || isRetiredScopeInput(reportId) || this.input(reportId)?.target !== "main") return null;
475
494
  const sourceId = this.getMeta(`report-approval-source:${reportId}`);
@@ -945,7 +964,10 @@ export class Store implements StorePort {
945
964
  if (!this.receive(input, target, {
946
965
  [`handoff-source:${input.id}`]: sourceId,
947
966
  [`native-goal-resume-owner:${input.id}`]: JSON.stringify(owner),
948
- }) || !this.submit(input.id, owner.requestId, owner.generation)) throw new Error("Native goal resume was not admitted");
967
+ ...(owner.scopedWorkOwnerId === undefined ? {} : { [discordWorkThreadOwnerKey(input.id)]: owner.scopedWorkOwnerId }),
968
+ })) throw new Error("Native goal resume was not admitted");
969
+ if (owner.scopedWorkOwnerId !== undefined) this.scopedWorkSource(this.requireInput(input.id));
970
+ if (!this.submit(input.id, owner.requestId, owner.generation)) throw new Error("Native goal resume was not admitted");
949
971
  return this.requireInput(input.id);
950
972
  }).immediate();
951
973
  }
@@ -981,7 +1003,7 @@ export class Store implements StorePort {
981
1003
  }
982
1004
 
983
1005
  private laneReportSources(receiptId: string, input: InputRecord, source: InputRecord): Readonly<Record<string, string>> {
984
- const approvalSource = this.getMeta(`handoff-reply:${input.id}`) !== null ? source : this.reportApprovalSource(input.id);
1006
+ const approvalSource = this.parentThreadReply(input, source) ? source : this.reportApprovalSource(input.id);
985
1007
  return {
986
1008
  [`activity-source:${receiptId}`]: source.id,
987
1009
  // Redirect the mediated report, not native approvals raised during review.
@@ -1382,21 +1404,38 @@ export class Store implements StorePort {
1382
1404
  }
1383
1405
 
1384
1406
  laneReplyRoute(input: InputRecord, source: InputRecord): Route {
1407
+ const scoped = this.scopedWorkSource(input);
1408
+ if (scoped) {
1409
+ if (scoped.sourceId !== source.id) throw new Error(`Invalid scoped Discord reply source: ${input.id}`);
1410
+ return input.route;
1411
+ }
1412
+ const parentReply = this.parentThreadReply(input, source);
1413
+ if (parentReply) return parentReply;
1414
+ const pinned = this.getMeta(`steering-topic-reply:${input.id}`);
1415
+ return pinned ? JSON.parse(pinned) : this.deliveryRoute(source);
1416
+ }
1417
+
1418
+ parentThreadReply(input: InputRecord, source: InputRecord): Route | null {
1385
1419
  const handoffReply = this.getMeta(`handoff-reply:${input.id}`);
1420
+ const kickoffId = `${source.id}:kickoff`;
1421
+ // Native thread creation has its own delivery binding; do not reinterpret
1422
+ // its approval routing as existing-thread placement.
1423
+ const opening = input.id === `handoff:${source.id}:lane` && this.getMeta(`kickoff-output:${input.id}`) === kickoffId
1424
+ && this.getMeta(`handoff-native:${source.id}`) !== "true";
1425
+ if (handoffReply === null && !opening) return null;
1426
+ const { route } = input;
1427
+ const fromExactParent = input.target && source.target === "main" && !source.pickerSelection
1428
+ && this.getMeta(`handoff-source:${input.id}`) === source.id && this.getMeta(`user-source:${source.id}`) === "true"
1429
+ && route.platform === "discord" && route.guildId && route.threadId && route.topicId === undefined
1430
+ && routeKey({ ...route, threadId: null }) === routeKey(source.route) && this.laneForRoute(route)?.id === input.target;
1386
1431
  if (handoffReply !== null) {
1387
- const { route } = input;
1388
- if (!input.target || input.id !== `handoff:${source.id}:${input.target}`
1389
- || this.getMeta(`handoff-source:${input.id}`) !== source.id
1390
- || source.target !== "main" || source.pickerSelection || this.getMeta(`user-source:${source.id}`) !== "true"
1391
- || route.platform !== "discord" || !route.guildId || !route.threadId || route.topicId !== undefined
1392
- || routeKey(route) !== handoffReply || routeKey({ ...route, threadId: null }) !== routeKey(source.route)
1393
- || this.laneForRoute(route)?.id !== input.target) {
1432
+ if (!fromExactParent || input.id !== `handoff:${source.id}:${input.target}` || routeKey(route) !== handoffReply)
1394
1433
  throw new Error(`Invalid existing-thread delivery binding: ${input.id}`);
1395
- }
1396
1434
  return route;
1397
1435
  }
1398
- const pinned = this.getMeta(`steering-topic-reply:${input.id}`);
1399
- return pinned ? JSON.parse(pinned) : this.deliveryRoute(source);
1436
+ if (!fromExactParent) return null;
1437
+ const kickoff = this.output(kickoffId);
1438
+ return kickoff?.state === "sent" && kickoff.sourceId === input.id && routeKey(kickoff.route) === routeKey(route) ? route : null;
1400
1439
  }
1401
1440
 
1402
1441
  private deliveryRoute(source: InputRecord, expectedLane?: string | null): Route {
@@ -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]);