omp-superagent 0.1.18 → 0.1.19
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.
- package/docs/OPERATIONS.en.md +127 -30
- package/docs/OPERATIONS.md +114 -27
- package/docs/design/execution.md +90 -23
- package/docs/design/messaging.md +34 -2
- package/docs/releases/0.1.19.md +10 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +1 -1
- package/skills/head/SKILL.md +4 -3
- package/skills/head/references/model-selection.md +8 -22
- package/skills/head/references/routing.md +19 -11
- package/skills/lane/SKILL.md +24 -76
- package/skills/lane/references/workflow.md +7 -94
- package/src/cli.ts +36 -16
- package/src/config/config.ts +6 -2
- package/src/contracts.ts +20 -4
- package/src/extension.ts +10 -5
- package/src/host-extension.ts +76 -8
- package/src/lane/lane-report.ts +1 -1
- package/src/lane/lane-rows.ts +2 -1
- package/src/lane-extension.ts +4 -21
- package/src/messaging/result-attachment.ts +77 -19
- package/src/messaging/written-directives.ts +56 -0
- package/src/omp/exit-record.ts +27 -0
- package/src/omp/host-protocol.ts +20 -0
- package/src/omp/host.ts +73 -20
- package/src/omp/installed-omp.ts +15 -12
- package/src/omp/managed-super.ts +135 -65
- package/src/routing/topic-request.ts +7 -4
- package/src/runtime/controller.ts +512 -165
- package/src/runtime/inbound-attachments.ts +70 -0
- package/src/runtime/local-host-fence.ts +85 -0
- package/src/runtime/model-journal.ts +14 -9
- package/src/runtime/native-frames.ts +5 -1
- package/src/runtime/result-attachments.ts +151 -24
- package/src/runtime/worker-result-download.ts +36 -0
- package/src/storage/store.ts +79 -26
- package/src/worker/worker-checkout.ts +89 -9
- package/src/worker/worker-destination.ts +8 -7
- package/src/worker/worker-doctor.ts +29 -9
- package/src/worker/worker-enrollment.ts +44 -12
- package/src/worker/worker-git-startup.ts +157 -0
- package/src/worker/worker-host.ts +16 -26
- package/src/worker/worker-ledger.ts +42 -18
- package/src/worker/worker-placement-intent.ts +13 -0
- package/src/worker/worker-placement.ts +204 -28
- package/src/worker/worker-profile.ts +18 -65
- package/src/worker/worker-project-startup.ts +106 -0
- package/src/worker/worker-registration.ts +85 -30
- package/src/worker/worker-repository.ts +55 -6
- package/src/worker/worker-request.ts +13 -6
- package/src/worker/worker-result-attachments.ts +185 -0
- package/src/worker/worker-result-wire.ts +12 -0
- package/src/worker/worker-service.ts +51 -23
- package/src/worker/worker-trust.ts +19 -4
- package/src/worker/worker-wire.ts +47 -14
- package/upstream/super.json +2 -3
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { lstatSync, readdirSync, realpathSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { checkWorkerFile, readWorkerFile } from "./worker-registration";
|
|
4
|
+
import { gitWorkerRepository, workerIndexHasOrdinaryFiles } from "./worker-repository";
|
|
5
|
+
import { WorkerRefusal } from "./worker-request";
|
|
6
|
+
import { trustedWorkerPath } from "./worker-trust";
|
|
7
|
+
import type { WorkerRepo } from "./worker-wire";
|
|
8
|
+
|
|
9
|
+
const gitSettings = [
|
|
10
|
+
/^core\.(repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks|autocrlf|eol|safecrlf)$/,
|
|
11
|
+
/^extensions\.objectformat$/,
|
|
12
|
+
/^remote\.[A-Za-z0-9._/-]+\.(url|pushurl|fetch|push|tagopt|prune|prunetags|mirror|followremotehead)$/,
|
|
13
|
+
/^branch\.[A-Za-z0-9._/-]+\.(remote|merge|rebase|pushremote|description)$/,
|
|
14
|
+
/^user\.(name|email|useconfigonly)$/,
|
|
15
|
+
];
|
|
16
|
+
// These preferences choose behavior for explicit Git operations, not startup executables.
|
|
17
|
+
const trustedGitPreferences = /^(?:fetch\.prune|pull\.(?:ff|rebase)|push\.default)$/u;
|
|
18
|
+
const filterKey = /^filter\.[A-Za-z0-9._/-]+\.(clean|smudge|process|required)$/u;
|
|
19
|
+
const moduleKey = /^submodule\.(.+)\.(path|url|update|branch|ignore|active|fetchrecursesubmodules|shallow)$/u;
|
|
20
|
+
const moduleUpdates = new Set(["checkout", "rebase", "merge", "none"]);
|
|
21
|
+
const controls = /[\u0000-\u001f\u007f\\]/u;
|
|
22
|
+
|
|
23
|
+
type ConfigEntry = readonly [key: string, value: string];
|
|
24
|
+
type GitCheckout = { readonly cwd: string; readonly gitDir: string; readonly submodule?: true };
|
|
25
|
+
|
|
26
|
+
function safeRelative(path: string): boolean {
|
|
27
|
+
return !!path && !isAbsolute(path) && !controls.test(path) &&
|
|
28
|
+
path.split("/").every(part => part && part !== "." && part !== ".." && part.toLowerCase() !== ".git");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function moduleValue(key: string, value: string): boolean {
|
|
32
|
+
if (key === "update") return moduleUpdates.has(value);
|
|
33
|
+
if (key !== "url") return true;
|
|
34
|
+
// Known Git network protocols, scp-style SSH and ordinary local/relative paths.
|
|
35
|
+
// No external remote-helper transport selectors (name::payload).
|
|
36
|
+
return !!value && !controls.test(value) && !value.startsWith("-") && !value.includes("::") &&
|
|
37
|
+
(!value.includes("://") || /^(?:https?|ssh|git|file):\/\//u.test(value));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function configEntries(cwd: string, path: string): Promise<ConfigEntry[]> {
|
|
41
|
+
const values = await gitWorkerRepository(cwd, ["config", "--file", path, "--no-includes", "--null", "--list"]);
|
|
42
|
+
if (values === "") return [];
|
|
43
|
+
if (!values?.endsWith("\0")) throw new WorkerRefusal("Worker startup could not read bounded local Git configuration");
|
|
44
|
+
return values.slice(0, -1).split("\0").map(entry => {
|
|
45
|
+
const newline = entry.indexOf("\n");
|
|
46
|
+
return newline < 0 ? [entry, ""] : [entry.slice(0, newline), entry.slice(newline + 1)];
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function assertConfig(checkout: GitCheckout, trusted: boolean): Promise<void> {
|
|
51
|
+
const { cwd, gitDir, submodule } = checkout;
|
|
52
|
+
const configFile = join(gitDir, "config");
|
|
53
|
+
try {
|
|
54
|
+
checkWorkerFile(lstatSync(configFile), 0o644);
|
|
55
|
+
if (lstatSync(join(gitDir, "config.worktree"), { throwIfNoEntry: false })) throw new Error();
|
|
56
|
+
} catch {
|
|
57
|
+
throw new WorkerRefusal("Worker startup requires an owned regular Git config without worktree overrides");
|
|
58
|
+
}
|
|
59
|
+
const values = await configEntries(cwd, configFile);
|
|
60
|
+
const worktrees = values.filter(([key]) => key === "core.worktree");
|
|
61
|
+
if (values.some(([key, value]) => {
|
|
62
|
+
if (gitSettings.some(allowed => allowed.test(key)))
|
|
63
|
+
return trusted && /^remote\..+\.(url|pushurl)$/u.test(key) && !moduleValue("url", value);
|
|
64
|
+
if (!trusted) return true;
|
|
65
|
+
if (trustedGitPreferences.test(key) || filterKey.test(key) || key === "submodule.active") return false;
|
|
66
|
+
if (submodule && key === "core.worktree")
|
|
67
|
+
return worktrees.length !== 1 || !value || controls.test(value) || resolve(gitDir, value) !== cwd;
|
|
68
|
+
const [, name, field] = moduleKey.exec(key) ?? [];
|
|
69
|
+
return !name || !field || !safeRelative(name) || field === "path" || !moduleValue(field, value);
|
|
70
|
+
})) throw new WorkerRefusal("Worker startup refuses nonstandard local Git configuration (including hooks and includes; filters require checkout opt-in)");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Read-only Git plumbing does not run configured filters or inspect submodules. */
|
|
74
|
+
export async function assertWorkerGitRead(cwd: string, gitDir: string): Promise<void> {
|
|
75
|
+
if (lstatSync(join(gitDir, "commondir"), { throwIfNoEntry: false }))
|
|
76
|
+
throw new WorkerRefusal("Worker-current checkout cannot use a shared Git metadata directory");
|
|
77
|
+
await assertConfig({ cwd, gitDir }, true);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function moduleNames(cwd: string): Promise<Map<string, string>> {
|
|
81
|
+
const path = join(cwd, ".gitmodules");
|
|
82
|
+
const modules = new Map<string, string>();
|
|
83
|
+
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
84
|
+
if (!info) return modules;
|
|
85
|
+
checkWorkerFile(info, 0o644);
|
|
86
|
+
const names = new Set<string>();
|
|
87
|
+
for (const [key, value] of await configEntries(cwd, path)) {
|
|
88
|
+
const [, name, field] = moduleKey.exec(key) ?? [];
|
|
89
|
+
if (!name || !field || !safeRelative(name) || !moduleValue(field, value))
|
|
90
|
+
throw new WorkerRefusal("Worker startup refuses nonstandard submodule declarations");
|
|
91
|
+
if (field !== "path") continue;
|
|
92
|
+
if (!safeRelative(value) || names.has(name) || modules.has(value))
|
|
93
|
+
throw new WorkerRefusal("Worker startup requires uniquely bound submodule paths");
|
|
94
|
+
names.add(name);
|
|
95
|
+
modules.set(value, name);
|
|
96
|
+
}
|
|
97
|
+
return modules;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function initializedModule(parent: GitCheckout, path: string, name: string): GitCheckout | undefined {
|
|
101
|
+
const cwd = join(parent.cwd, path);
|
|
102
|
+
const info = lstatSync(cwd, { throwIfNoEntry: false });
|
|
103
|
+
if (!info) return;
|
|
104
|
+
trustedWorkerPath(cwd, [], "directory");
|
|
105
|
+
const marker = join(cwd, ".git");
|
|
106
|
+
const metadata = lstatSync(marker, { throwIfNoEntry: false });
|
|
107
|
+
if (!metadata) {
|
|
108
|
+
if (readdirSync(cwd).length) throw new WorkerRefusal("Worker submodule has no verified Git metadata");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
let gitDir = marker;
|
|
112
|
+
if (!metadata.isDirectory()) {
|
|
113
|
+
const text = readWorkerFile(marker, 0o644)?.toString("utf8");
|
|
114
|
+
const gitfile = /^gitdir: ([^\r\n]+)\r?\n?$/u.exec(text ?? "")?.[1];
|
|
115
|
+
if (!gitfile || controls.test(gitfile)) throw new WorkerRefusal("Worker submodule has an invalid Git marker");
|
|
116
|
+
gitDir = resolve(cwd, gitfile);
|
|
117
|
+
if (gitDir !== join(parent.gitDir, "modules", name))
|
|
118
|
+
throw new WorkerRefusal("Worker submodule Git metadata is outside its parent checkout binding");
|
|
119
|
+
}
|
|
120
|
+
trustedWorkerPath(gitDir, [], "directory");
|
|
121
|
+
if (realpathSync(gitDir) !== gitDir || lstatSync(join(gitDir, "commondir"), { throwIfNoEntry: false }))
|
|
122
|
+
throw new WorkerRefusal("Worker submodule does not have independent local Git metadata");
|
|
123
|
+
return { cwd, gitDir, submodule: true };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function assertTrustedModules(checkout: GitCheckout, budget: { left: number }, depth: number): Promise<void> {
|
|
127
|
+
const names = await moduleNames(checkout.cwd);
|
|
128
|
+
if (!await workerIndexHasOrdinaryFiles(checkout.cwd, checkout.gitDir, async path => {
|
|
129
|
+
const name = names.get(path);
|
|
130
|
+
if (!name || depth >= 8 || --budget.left < 0) return false;
|
|
131
|
+
const module = initializedModule(checkout, path, name);
|
|
132
|
+
if (module) {
|
|
133
|
+
await assertConfig(module, true);
|
|
134
|
+
const layout = await gitWorkerRepository(module.cwd, ["rev-parse", "--path-format=absolute",
|
|
135
|
+
"--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
|
|
136
|
+
if (layout !== `${module.cwd}\n${module.gitDir}\n${module.gitDir}\n`)
|
|
137
|
+
throw new WorkerRefusal("Worker submodule layout no longer matches its validated Git metadata");
|
|
138
|
+
await assertTrustedModules(module, budget, depth + 1);
|
|
139
|
+
}
|
|
140
|
+
return true;
|
|
141
|
+
})) throw new WorkerRefusal("Worker startup could not verify the enrolled submodule layout");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The admission helpers use Git plumbing only. Explicit native lane work may use enrolled local filters. */
|
|
145
|
+
export async function assertWorkerGitStartup(repo: WorkerRepo): Promise<void> {
|
|
146
|
+
const checkout: GitCheckout = { cwd: repo.cwd, gitDir: join(repo.cwd, ".git") };
|
|
147
|
+
await assertConfig(checkout, repo.trustedCheckout === true);
|
|
148
|
+
if (!repo.trustedCheckout) return;
|
|
149
|
+
try {
|
|
150
|
+
trustedWorkerPath(checkout.cwd, [], "directory");
|
|
151
|
+
trustedWorkerPath(checkout.gitDir, [], "directory");
|
|
152
|
+
await assertTrustedModules(checkout, { left: 128 }, 0);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error instanceof WorkerRefusal) throw error;
|
|
155
|
+
throw new WorkerRefusal("Worker startup could not verify local submodule configuration");
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { lstatSync, mkdirSync, 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
|
+
import { readExitRecord } from "../omp/exit-record";
|
|
5
6
|
import { NativeJournalFormatError, readNativeSessionId } from "../omp/native-journal";
|
|
6
|
-
import { ownsCheckout, privateWorkerDirectory, syncDirectory
|
|
7
|
+
import { matchesWorkerCheckoutDirectory, ownsCheckout, privateWorkerDirectory, syncDirectory,
|
|
8
|
+
type WorkerCheckoutPin } from "./worker-checkout";
|
|
7
9
|
import { workerExit, workerReaped, type WorkerIdentity, type WorkerJournalDirectory, type WorkerLedger, type WorkerReceipt } from "./worker-ledger";
|
|
8
10
|
import { WorkerRefusal } from "./worker-request";
|
|
9
11
|
import { trustedWorkerPath } from "./worker-trust";
|
|
@@ -106,29 +108,6 @@ export async function readWorkerFiles(paths: WorkerPaths, directory?: WorkerJour
|
|
|
106
108
|
return { socket, exit, session, sessionId };
|
|
107
109
|
}
|
|
108
110
|
|
|
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
|
-
}
|
|
117
|
-
try {
|
|
118
|
-
const stat = fstatSync(fd);
|
|
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")); }
|
|
125
|
-
catch (error) {
|
|
126
|
-
if (error instanceof SyntaxError) return null;
|
|
127
|
-
throw error;
|
|
128
|
-
}
|
|
129
|
-
} finally { closeSync(fd); }
|
|
130
|
-
}
|
|
131
|
-
|
|
132
111
|
function matchesExit(paths: WorkerPaths, receipt: WorkerReceipt, proof: {
|
|
133
112
|
readonly workerAttempt: string; readonly sessionFile: string; readonly pid: number; readonly ownerPid: number;
|
|
134
113
|
}): boolean {
|
|
@@ -143,7 +122,7 @@ function readVerifiedExit(paths: WorkerPaths, receipt: WorkerReceipt, stat: Stat
|
|
|
143
122
|
}
|
|
144
123
|
|
|
145
124
|
function journalHeld() {
|
|
146
|
-
return new WorkerRefusal("Worker checkout was released
|
|
125
|
+
return new WorkerRefusal("Worker checkout was released; the original journal remains unverified and cannot reopen");
|
|
147
126
|
}
|
|
148
127
|
|
|
149
128
|
/** The private owner's receipt, not the damaged journal, decides checkout-only retirement. */
|
|
@@ -176,11 +155,22 @@ export function absentWorkerHost(files: WorkerFiles, receipt: WorkerReceipt | nu
|
|
|
176
155
|
...(!uncertain && receipt?.phase === "released" && receipt.exitVerified && { exitGeneration: receipt.generation }) };
|
|
177
156
|
}
|
|
178
157
|
|
|
158
|
+
export function workerCheckoutPin(receipt: WorkerReceipt): WorkerCheckoutPin | undefined {
|
|
159
|
+
const { workerCheckout, checkoutIdentity, repoRoot, gitDir, subdir, repoId, revision } = receipt;
|
|
160
|
+
if (!workerCheckout) return;
|
|
161
|
+
if (workerCheckout !== checkoutIdentity) throw new WorkerRefusal("Worker-current launch has no verified checkout pin");
|
|
162
|
+
return { checkoutIdentity, repoRoot, gitDir, subdir, repoId, revision };
|
|
163
|
+
}
|
|
164
|
+
|
|
179
165
|
export async function attestWorkerHost(paths: WorkerPaths, files: WorkerFiles, receipt: WorkerReceipt): Promise<WorkerIdentity> {
|
|
180
166
|
if (!files.socket || !files.sessionId || !ownsCheckout(receipt)) throw new WorkerRefusal("No owned worker socket/journal/checkout");
|
|
167
|
+
const checkoutPin = workerCheckoutPin(receipt);
|
|
181
168
|
const { connection, identity, state } = await HostConnection.open(paths.socketPath);
|
|
182
169
|
try {
|
|
183
170
|
if (!("workerAttempt" in state) || state.workerAttempt !== receipt.attempt ||
|
|
171
|
+
checkoutPin && (state.workerCheckoutProof?.checkoutIdentity !== checkoutPin.checkoutIdentity ||
|
|
172
|
+
state.workerCheckoutProof.revision !== checkoutPin.revision ||
|
|
173
|
+
!matchesWorkerCheckoutDirectory(join(checkoutPin.repoRoot, checkoutPin.subdir), checkoutPin)) ||
|
|
184
174
|
typeof state.loadedSuperkitPath !== "string" || !state.loadedSuperkitPath.startsWith("/") || identity.pid === identity.ownerPid ||
|
|
185
175
|
identity.sessionFile !== paths.sessionFile || identity.sessionId !== files.sessionId ||
|
|
186
176
|
receipt.sessionId !== null && identity.sessionId !== receipt.sessionId || !sameFile(identity, files.socket) ||
|
|
@@ -3,10 +3,11 @@ import { closeSync, constants, fstatSync, lstatSync, openSync } from "node:fs";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { Type, type Static } from "@sinclair/typebox/type";
|
|
5
5
|
import { Value } from "@sinclair/typebox/value";
|
|
6
|
+
import { workerOwnerWasNotSpawned } from "../omp/host";
|
|
6
7
|
import { releaseCheckout } from "./worker-checkout";
|
|
7
8
|
import { workerMemoryBinding, type WorkerMemoryBinding } from "./worker-memory-storage";
|
|
8
9
|
import { WorkerRefusal } from "./worker-request";
|
|
9
|
-
import type
|
|
10
|
+
import { workerCheckoutSchema, type WorkerLaneRef, type WorkerPolicy } from "./worker-wire";
|
|
10
11
|
|
|
11
12
|
export const workerPid = Type.Integer({ minimum: 1, maximum: 0x7fffffff });
|
|
12
13
|
const sessionId = Type.String({ minLength: 1, maxLength: 512 });
|
|
@@ -43,6 +44,7 @@ const receiptFields = {
|
|
|
43
44
|
repoId: Type.String(),
|
|
44
45
|
revision: Type.String(),
|
|
45
46
|
subdir: Type.String(),
|
|
47
|
+
workerCheckout: Type.Optional(workerCheckoutSchema),
|
|
46
48
|
repoRoot: Type.String(),
|
|
47
49
|
gitDir: Type.String(),
|
|
48
50
|
launchDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
|
|
@@ -65,8 +67,11 @@ export type WorkerReceipt = Readonly<Static<typeof receipt>>;
|
|
|
65
67
|
export type WorkerIdentity = Readonly<Static<typeof identity>>;
|
|
66
68
|
type ReservedReceipt = Extract<WorkerReceipt, { phase: "reserved" }>;
|
|
67
69
|
type Retirement = { readonly sessionId: string; readonly clean: boolean; readonly cleanup: () => void }
|
|
68
|
-
| { readonly journalHeld: true; readonly cleanup: () => void }
|
|
69
|
-
|
|
70
|
+
| { readonly journalHeld: true; readonly cleanup: () => void }
|
|
71
|
+
| { readonly unspawnedError: unknown };
|
|
72
|
+
type WorkerSeal = Pick<WorkerLaneRef, "generation" | "repoId" | "revision" | "subdir"> & {
|
|
73
|
+
readonly repoRoot: string; readonly workerCheckout: string | null;
|
|
74
|
+
};
|
|
70
75
|
const occupied = "phase NOT IN ('released', 'checkout-released')";
|
|
71
76
|
|
|
72
77
|
function decode(row: { readonly data: string } | null): WorkerReceipt | null {
|
|
@@ -81,9 +86,16 @@ export class WorkerLedger {
|
|
|
81
86
|
readonly #capacity: number;
|
|
82
87
|
|
|
83
88
|
static count(policy: WorkerPolicy): number {
|
|
84
|
-
|
|
89
|
+
return WorkerLedger.occupancy(policy).length;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static occupancy(policy: WorkerPolicy): readonly WorkerLaneRef[] {
|
|
93
|
+
if (!lstatSync(join(policy.stateDir, "worker.sqlite"), { throwIfNoEntry: false })) return [];
|
|
85
94
|
const ledger = new WorkerLedger(policy, "read");
|
|
86
|
-
try {
|
|
95
|
+
try {
|
|
96
|
+
return ledger.active().map(({ laneId, generation, repoId, revision, subdir, workerCheckout }) =>
|
|
97
|
+
({ laneId, generation, repoId, revision, subdir, ...(workerCheckout && { workerCheckout }) }));
|
|
98
|
+
} finally { ledger.close(); }
|
|
87
99
|
}
|
|
88
100
|
|
|
89
101
|
constructor(policy: WorkerPolicy, mode: "read" | "write" = "write") {
|
|
@@ -105,11 +117,13 @@ export class WorkerLedger {
|
|
|
105
117
|
CREATE TABLE IF NOT EXISTS worker_lanes (id TEXT PRIMARY KEY, phase TEXT NOT NULL, data TEXT NOT NULL);
|
|
106
118
|
CREATE TABLE IF NOT EXISTS worker_seals (
|
|
107
119
|
id TEXT PRIMARY KEY, generation INTEGER NOT NULL, repoId TEXT NOT NULL,
|
|
108
|
-
revision TEXT NOT NULL, subdir TEXT NOT NULL, repoRoot TEXT NOT NULL
|
|
120
|
+
revision TEXT NOT NULL, subdir TEXT NOT NULL, repoRoot TEXT NOT NULL, workerCheckout TEXT
|
|
109
121
|
);
|
|
110
122
|
`);
|
|
111
123
|
if (mode === "write") this.#db.transaction(() => {
|
|
112
124
|
this.#db.query("INSERT OR IGNORE INTO worker_identity VALUES (1, ?)").run(policy.workerId);
|
|
125
|
+
if (!this.#db.query<{ name: string }, []>("PRAGMA table_info(worker_seals)").all().some(col => col.name === "workerCheckout"))
|
|
126
|
+
this.#db.exec("ALTER TABLE worker_seals ADD COLUMN workerCheckout TEXT");
|
|
113
127
|
}).immediate();
|
|
114
128
|
const row = this.#db.query<{ worker_id: string }, []>("SELECT worker_id FROM worker_identity WHERE singleton = 1").get();
|
|
115
129
|
if (row?.worker_id !== policy.workerId) throw new WorkerRefusal("Worker storage belongs to a different enrollment");
|
|
@@ -137,8 +151,9 @@ export class WorkerLedger {
|
|
|
137
151
|
|
|
138
152
|
#sealedGeneration(ref: WorkerLaneRef, repoRoot: string): number | undefined {
|
|
139
153
|
const seal = this.#db.query<WorkerSeal, [string]>(
|
|
140
|
-
"SELECT generation, repoId, revision, subdir, repoRoot FROM worker_seals WHERE id = ?").get(ref.laneId);
|
|
141
|
-
if (seal && (seal.repoId !== ref.repoId || seal.revision !== ref.revision || seal.subdir !== ref.subdir
|
|
154
|
+
"SELECT generation, repoId, revision, subdir, repoRoot, workerCheckout FROM worker_seals WHERE id = ?").get(ref.laneId);
|
|
155
|
+
if (seal && (seal.repoId !== ref.repoId || seal.revision !== ref.revision || seal.subdir !== ref.subdir
|
|
156
|
+
|| seal.repoRoot !== repoRoot || seal.workerCheckout !== (ref.workerCheckout ?? null)))
|
|
142
157
|
throw new WorkerRefusal("Worker lane has a different durable checkout binding");
|
|
143
158
|
return seal?.generation;
|
|
144
159
|
}
|
|
@@ -157,8 +172,8 @@ export class WorkerLedger {
|
|
|
157
172
|
// Keep any previous exit/session receipt intact. Reserve and seal use the
|
|
158
173
|
// same immediate transaction: either a launch is already admitted, or
|
|
159
174
|
// even an open request that arrives after this reply must refuse.
|
|
160
|
-
this.#db.query("INSERT OR REPLACE INTO worker_seals VALUES (?, ?, ?, ?, ?, ?)")
|
|
161
|
-
.run(ref.laneId, ref.generation, ref.repoId, ref.revision, ref.subdir, repoRoot);
|
|
175
|
+
this.#db.query("INSERT OR REPLACE INTO worker_seals (id, generation, repoId, revision, subdir, repoRoot, workerCheckout) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
176
|
+
.run(ref.laneId, ref.generation, ref.repoId, ref.revision, ref.subdir, repoRoot, ref.workerCheckout ?? null);
|
|
162
177
|
return true;
|
|
163
178
|
});
|
|
164
179
|
return options.reconcile ? confirm.immediate() : confirm();
|
|
@@ -185,11 +200,13 @@ export class WorkerLedger {
|
|
|
185
200
|
}).immediate();
|
|
186
201
|
}
|
|
187
202
|
|
|
188
|
-
#replaceCurrent(current: WorkerReceipt, replacement: () => WorkerReceipt): boolean {
|
|
203
|
+
#replaceCurrent(current: WorkerReceipt, replacement: (actual: WorkerReceipt) => WorkerReceipt | null): boolean {
|
|
189
204
|
return this.#db.transaction(() => {
|
|
190
205
|
const actual = this.get(current.laneId);
|
|
191
206
|
if (actual?.attempt !== current.attempt || actual.phase !== current.phase) return false;
|
|
192
|
-
|
|
207
|
+
const next = replacement(actual);
|
|
208
|
+
if (!next) return false;
|
|
209
|
+
this.#write(next);
|
|
193
210
|
return true;
|
|
194
211
|
}).immediate();
|
|
195
212
|
}
|
|
@@ -198,18 +215,25 @@ export class WorkerLedger {
|
|
|
198
215
|
return this.#replaceCurrent(current, () => next);
|
|
199
216
|
}
|
|
200
217
|
|
|
201
|
-
retire(
|
|
202
|
-
return this.#replaceCurrent(
|
|
203
|
-
|
|
218
|
+
retire(observed: WorkerReceipt, retirement?: Retirement): boolean {
|
|
219
|
+
return this.#replaceCurrent(observed, current => {
|
|
220
|
+
// No-owner proof is valid only in the live producer of this exact
|
|
221
|
+
// launch. It says nothing about the journal the SDK was allowed to prepare.
|
|
222
|
+
if (retirement && "unspawnedError" in retirement && (current.phase !== "launching"
|
|
223
|
+
|| current.launcherPid !== process.pid || !current.checkoutIdentity
|
|
224
|
+
|| !workerOwnerWasNotSpawned(retirement.unspawnedError, current.attempt)))
|
|
225
|
+
return null;
|
|
226
|
+
if (retirement && "cleanup" in retirement) retirement.cleanup();
|
|
204
227
|
releaseCheckout(current);
|
|
205
|
-
const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
|
|
228
|
+
const { laneId, generation, repoId, revision, subdir, workerCheckout, repoRoot, gitDir, attempt, launcherPid, launchDigest,
|
|
206
229
|
journalDirectory, checkoutIdentity, memory } = current;
|
|
207
|
-
const verified =
|
|
230
|
+
const verified = retirement && "sessionId" in retirement ? retirement : undefined;
|
|
208
231
|
const sessionId = verified?.sessionId ?? current.sessionId;
|
|
209
232
|
const binding = { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
|
|
233
|
+
...(workerCheckout && { workerCheckout }),
|
|
210
234
|
sessionId, ...(journalDirectory && { journalDirectory }), ...(checkoutIdentity && { checkoutIdentity }),
|
|
211
235
|
...(sessionId !== null && memory ? { memory } : {}) };
|
|
212
|
-
if (
|
|
236
|
+
if (retirement && !verified) return { ...binding, phase: "checkout-released" };
|
|
213
237
|
return { ...binding, phase: "released", ...(verified?.clean && { exitVerified: true }) };
|
|
214
238
|
});
|
|
215
239
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { RemotePlacement } from "./worker-wire";
|
|
2
|
+
|
|
3
|
+
export interface WorkerCurrentIntent {
|
|
4
|
+
readonly worker: string;
|
|
5
|
+
readonly repoId: string;
|
|
6
|
+
readonly subdir: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** The same promised workspace must own both the work and any result nominated there. */
|
|
10
|
+
export function matchesWorkerCurrentPlacement(intent: WorkerCurrentIntent, remote: RemotePlacement | null | undefined): boolean {
|
|
11
|
+
return !!remote?.workerCheckout && remote.workerId === intent.worker && remote.repoId === intent.repoId
|
|
12
|
+
&& remote.subdir === intent.subdir;
|
|
13
|
+
}
|