code60-transmission-server 0.0.0-stage → 0.1.0

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 (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +287 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +176 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +163 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +103 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11078 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +163 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
@@ -0,0 +1,715 @@
1
+ import { randomUUID, createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, realpathSync } from "node:fs";
3
+ import { dirname, isAbsolute, join } from "node:path";
4
+ import { canonical, digest, jsonCopy } from "../broker/policy.js";
5
+ import { NativeFilesystemRoot } from "../broker/filesystem.js";
6
+ import { runSqlCommitHook } from "../engine/contracts.js";
7
+ import { startupLockIdentity } from "../broker/startup-lock.js";
8
+ import { WorkspaceError, WorkspaceGit } from "./git.js";
9
+ export { WorkspaceError } from "./git.js";
10
+ export const WORKSPACE_MIGRATION = { id: "workspaces-v1", sql: `
11
+ CREATE TABLE workspace_owner (singleton INTEGER PRIMARY KEY CHECK(singleton=1), owner TEXT NOT NULL);
12
+ CREATE TABLE workspace_records (id TEXT PRIMARY KEY, identity TEXT NOT NULL UNIQUE, body TEXT NOT NULL);
13
+ CREATE TABLE workspace_leases (id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, run_id TEXT NOT NULL UNIQUE, state TEXT NOT NULL, body TEXT NOT NULL);
14
+ CREATE UNIQUE INDEX workspace_active_lease ON workspace_leases(workspace_id) WHERE state!='released';
15
+ CREATE TABLE workspace_snapshots (id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, body TEXT NOT NULL);
16
+ CREATE TRIGGER workspace_snapshot_immutable_update BEFORE UPDATE ON workspace_snapshots BEGIN SELECT RAISE(ABORT,'immutable_snapshot'); END;
17
+ CREATE TRIGGER workspace_snapshot_immutable_delete BEFORE DELETE ON workspace_snapshots BEGIN SELECT RAISE(ABORT,'immutable_snapshot'); END;
18
+ CREATE TABLE workspace_baselines (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, revision_id TEXT NOT NULL, body TEXT NOT NULL);
19
+ CREATE TABLE workspace_conflicts (run_id TEXT PRIMARY KEY, body TEXT NOT NULL);
20
+ CREATE TABLE workspace_overwrites (digest TEXT PRIMARY KEY, run_id TEXT NOT NULL, consumed_by TEXT);
21
+ CREATE TABLE workspace_jobs (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, state TEXT NOT NULL, body TEXT NOT NULL);
22
+ ` };
23
+ const sha = (data) => createHash("sha256").update(data).digest("hex");
24
+ const fileMode = (entry) => Number(entry.identity.split("|f:").at(-1).split(":")[2]) & 0o777;
25
+ const sameFile = (a, b) => a.type === b.type && a.path === b.path && a.mode === b.mode && a.contentDigest === b.contentDigest;
26
+ const fdIdentity = (fd) => { const s = fstatSync(fd, { bigint: true }); return `${s.dev}:${s.ino}`; };
27
+ const openDirectory = (path) => openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
28
+ /** Engine-owned workspace effects and private immutable byte checkpoints.
29
+ * Public WorkspaceRevision remains an identity of the LIVE paused workspace.
30
+ * No registration, lease, snapshot, Git, restore, or effect method is agent RPC. */
31
+ export class WorkspaceService {
32
+ options;
33
+ coordinator;
34
+ owner = randomUUID();
35
+ now;
36
+ descriptors = new Map();
37
+ engineFds = [];
38
+ deploymentRoots;
39
+ quarantineFd;
40
+ closed = false;
41
+ constructor(options) {
42
+ this.options = options;
43
+ this.coordinator = options.coordinator;
44
+ this.now = options.now ?? Date.now;
45
+ this.coordinator.assertOutsideTransaction();
46
+ if (options.recover && options.startupLockFd === undefined)
47
+ throw new WorkspaceError("startup_writer_barrier_required", 422);
48
+ if (options.startupLockFd !== undefined)
49
+ startupLockIdentity(options.startupLockFd);
50
+ this.deploymentRoots = new Map(options.deploymentRoots ?? []);
51
+ for (const [id, fd] of this.deploymentRoots)
52
+ if (!id || id.length > 200 || !fstatSync(fd).isDirectory())
53
+ throw new WorkspaceError("invalid_deployment_root", 422);
54
+ if (!options.protectedRootFds.length)
55
+ throw new WorkspaceError("protected_roots_required", 422);
56
+ const snapshots = realpathSync(options.snapshotDirectory), s = lstatSync(snapshots);
57
+ if (!s.isDirectory() || s.uid !== process.geteuid?.() || (s.mode & 0o77))
58
+ throw new WorkspaceError("unsafe_snapshot_root", 422);
59
+ this.engineFds.push(openDirectory(snapshots));
60
+ for (const row of this.coordinator.db.prepare("PRAGMA database_list").all()) {
61
+ if (row.file)
62
+ this.engineFds.push(openDirectory(realpathSync(dirname(row.file))));
63
+ }
64
+ const quarantine = join(snapshots, "quarantine");
65
+ try {
66
+ mkdirSync(quarantine, { mode: 0o700 });
67
+ }
68
+ catch (error) {
69
+ if (error.code !== "EEXIST")
70
+ throw error;
71
+ }
72
+ this.quarantineFd = openDirectory(quarantine);
73
+ this.engineFds.push(this.quarantineFd);
74
+ if (fstatSync(this.quarantineFd).mode & 0o77)
75
+ throw new WorkspaceError("unsafe_quarantine_root", 422);
76
+ this.coordinator.atomic(() => {
77
+ const prior = this.row("SELECT owner FROM workspace_owner WHERE singleton=1");
78
+ if (prior?.owner && !options.recover)
79
+ throw new WorkspaceError("workspace_coordinator_already_owned");
80
+ this.coordinator.db.prepare("INSERT INTO workspace_owner VALUES (1,?) ON CONFLICT(singleton) DO UPDATE SET owner=excluded.owner").run(this.owner);
81
+ if (options.recover)
82
+ for (const row of this.rows("SELECT body FROM workspace_leases WHERE state!='released'")) {
83
+ const lease = JSON.parse(String(row.body));
84
+ lease.state = "uncertain";
85
+ this.saveLease(lease);
86
+ }
87
+ });
88
+ }
89
+ row(sql, ...args) {
90
+ return this.coordinator.db.prepare(sql).get(...args);
91
+ }
92
+ rows(sql, ...args) {
93
+ return this.coordinator.db.prepare(sql).all(...args);
94
+ }
95
+ owned() {
96
+ if (this.closed || this.row("SELECT owner FROM workspace_owner WHERE singleton=1")?.owner !== this.owner)
97
+ throw new WorkspaceError("workspace_coordinator_fenced");
98
+ }
99
+ entry() { this.coordinator.assertOutsideTransaction(); this.owned(); }
100
+ time() { return new Date(this.now()).toISOString(); }
101
+ record(id) {
102
+ const row = this.row("SELECT body FROM workspace_records WHERE id=?", id);
103
+ if (!row)
104
+ throw new WorkspaceError("workspace_not_found", 404);
105
+ return JSON.parse(String(row.body));
106
+ }
107
+ saveRecord(record) {
108
+ this.coordinator.db.prepare("UPDATE workspace_records SET body=? WHERE id=?").run(canonical(record), record.view.id);
109
+ }
110
+ get(id) { this.owned(); return jsonCopy(this.record(id).view); }
111
+ list() { this.owned(); return this.rows("SELECT body FROM workspace_records ORDER BY rowid").map(row => JSON.parse(String(row.body)).view); }
112
+ pin(root) {
113
+ let fd = this.descriptors.get(root.path);
114
+ if (fd === undefined) {
115
+ fd = openDirectory(root.path);
116
+ this.descriptors.set(root.path, fd);
117
+ }
118
+ const actual = lstatSync(root.path);
119
+ if (!actual.isDirectory() || actual.isSymbolicLink() || `${actual.dev}:${actual.ino}` !== root.identity || fdIdentity(fd) !== root.identity) {
120
+ throw new WorkspaceError("workspace_identity_changed");
121
+ }
122
+ return fd;
123
+ }
124
+ roots() {
125
+ return this.rows("SELECT body FROM workspace_records").flatMap(row => {
126
+ const record = JSON.parse(String(row.body));
127
+ return [record.root, ...record.scratch];
128
+ });
129
+ }
130
+ files(root, kind = "workspace", extra = []) {
131
+ return new NativeFilesystemRoot({ rootFd: this.pin(root), root: kind, helperPath: this.options.helperPath,
132
+ ...(this.options.startupLockFd === undefined ? {} : { startupLockFd: this.options.startupLockFd }),
133
+ quarantineFd: this.quarantineFd, protectedRootFds: [...this.options.protectedRootFds, ...this.engineFds,
134
+ ...this.deploymentRoots.values(),
135
+ ...this.roots().filter(other => other.identity !== root.identity).map(other => this.pin(other)), ...extra] });
136
+ }
137
+ git(record) {
138
+ return new WorkspaceGit({ rootFd: this.pin(record.root), repositoryPath: record.root.path,
139
+ ...(this.options.startupLockFd === undefined ? {} : { startupLockFd: this.options.startupLockFd }),
140
+ helperPath: this.options.gitHelperPath, expectedIdentity: record.gitIdentity });
141
+ }
142
+ root(path) {
143
+ if (!isAbsolute(path) || /[\0\r\n]/.test(path))
144
+ throw new WorkspaceError("invalid_workspace_path", 422);
145
+ const physical = realpathSync(path), fd = openDirectory(physical);
146
+ try {
147
+ return { path: physical, identity: fdIdentity(fd) };
148
+ }
149
+ finally {
150
+ closeSync(fd);
151
+ }
152
+ }
153
+ register(input, hooks = {}) {
154
+ this.entry();
155
+ if (!input.name?.trim() || !Array.isArray(input.scratchPaths))
156
+ throw new WorkspaceError("invalid_workspace", 422);
157
+ const root = this.root(input.repositoryPath), scratch = input.scratchPaths.map(path => this.root(path));
158
+ if (new Set([root, ...scratch].map(item => item.identity)).size !== 1 + scratch.length)
159
+ throw new WorkspaceError("workspace_root_alias", 422);
160
+ if ([root, ...scratch].some(candidate => this.roots().some(registered => registered.identity === candidate.identity))) {
161
+ throw new WorkspaceError("workspace_root_alias", 422);
162
+ }
163
+ const candidates = [root, ...scratch], temporary = candidates.map(item => openDirectory(item.path));
164
+ let registered = false;
165
+ try {
166
+ for (let i = 0; i < candidates.length; i++)
167
+ this.files(candidates[i], i === 0 ? "workspace" : "scratch", temporary.filter((_, j) => j !== i)).close();
168
+ if (this.row("SELECT id FROM workspace_records WHERE identity=?", root.identity))
169
+ throw new WorkspaceError("workspace_already_registered");
170
+ const git = new WorkspaceGit({ rootFd: this.pin(root), repositoryPath: root.path, helperPath: this.options.gitHelperPath });
171
+ const record = { root, scratch, gitIdentity: git.identity, view: { id: randomUUID(), name: input.name,
172
+ repositoryPath: root.path, scratchPaths: scratch.map(item => item.path), headCommit: git.head(), state: "available", version: 1, createdAt: this.time() } };
173
+ try {
174
+ this.assertClean(this.capture(record, "registration"), git);
175
+ }
176
+ catch (error) {
177
+ if (!(error instanceof WorkspaceError) || error.code !== "workspace_dirty")
178
+ throw error;
179
+ record.view.state = "needs_attention";
180
+ }
181
+ const value = this.coordinator.atomic(() => {
182
+ this.owned();
183
+ this.coordinator.db.prepare("INSERT INTO workspace_records VALUES (?,?,?)").run(record.view.id, root.identity, canonical(record));
184
+ runSqlCommitHook(hooks.onAdmittedSql, record.view);
185
+ return jsonCopy(record.view);
186
+ });
187
+ registered = true;
188
+ return value;
189
+ }
190
+ finally {
191
+ temporary.forEach(closeSync);
192
+ if (!registered)
193
+ for (const root of candidates) {
194
+ const fd = this.descriptors.get(root.path);
195
+ if (fd !== undefined) {
196
+ closeSync(fd);
197
+ this.descriptors.delete(root.path);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ metadata(record) {
203
+ const files = this.files(record.root);
204
+ try {
205
+ const git = this.git(record), configDigest = git.validateConfiguration(), index = git.index();
206
+ return { entries: files.inspectTree(), git, head: git.head(), ref: git.branch(), indexIdentity: index.identity, indexDigest: index.contentDigest, configDigest };
207
+ }
208
+ finally {
209
+ files.close();
210
+ }
211
+ }
212
+ capture(record, runId) {
213
+ const before = this.metadata(record), files = this.files(record.root);
214
+ try {
215
+ let bytes = 0;
216
+ const entries = before.entries.map(entry => {
217
+ if (entry.type === "directory")
218
+ return { ...entry, mode: fileMode(entry) };
219
+ const data = files.readBytes(entry.path, entry.identity);
220
+ bytes += data.length;
221
+ if (bytes > 16 * 1_048_576)
222
+ throw new WorkspaceError("workspace_snapshot_too_large", 422);
223
+ return { ...entry, mode: fileMode(entry), data: data.toString("base64"), contentDigest: sha(data) };
224
+ });
225
+ const after = this.metadata(record);
226
+ if (digest(before.entries) !== digest(after.entries) || before.head !== after.head || before.ref !== after.ref ||
227
+ before.indexDigest !== after.indexDigest || before.configDigest !== after.configDigest)
228
+ throw new WorkspaceError("workspace_changed_during_capture");
229
+ return this.snapshot(record, runId, entries, before);
230
+ }
231
+ finally {
232
+ files.close();
233
+ }
234
+ }
235
+ snapshot(record, runId, entries, metadata) {
236
+ const identity = { rootIdentity: record.root.identity, headCommit: metadata.head, headRef: metadata.ref,
237
+ indexDigest: metadata.indexDigest, configDigest: metadata.configDigest,
238
+ entries: entries.map(({ data: _data, ...entry }) => entry) };
239
+ return { revision: { id: randomUUID(), workspaceId: record.view.id, headCommit: metadata.head, contentDigest: digest(identity), capturedAt: this.time() },
240
+ runId, rootIdentity: record.root.identity, headRef: metadata.ref, indexIdentity: metadata.indexIdentity,
241
+ indexDigest: metadata.indexDigest, configDigest: metadata.configDigest, entries };
242
+ }
243
+ persist(snapshot) {
244
+ this.coordinator.db.prepare("INSERT INTO workspace_snapshots VALUES (?,?,?)").run(snapshot.revision.id, snapshot.revision.workspaceId, canonical(snapshot));
245
+ }
246
+ load(id) {
247
+ const row = this.row("SELECT body FROM workspace_snapshots WHERE id=?", id);
248
+ if (!row)
249
+ throw new WorkspaceError("workspace_revision_not_found", 404);
250
+ return JSON.parse(String(row.body));
251
+ }
252
+ revision(id) { this.owned(); return jsonCopy(this.load(id).revision); }
253
+ assertClean(snapshot, git) {
254
+ const tracked = git.tree(snapshot.revision.headCommit), actual = snapshot.entries.filter(entry => entry.type === "file");
255
+ if (tracked.length !== actual.length || tracked.some(file => {
256
+ const entry = actual.find(item => item.path === file.path);
257
+ if (!entry)
258
+ return true;
259
+ const bytes = Buffer.from(entry.data, "base64");
260
+ const object = createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
261
+ return object !== file.object || Boolean(entry.mode & 0o100) !== Boolean(file.mode & 0o100);
262
+ }))
263
+ throw new WorkspaceError("workspace_dirty");
264
+ const expected = tracked.map(file => `${file.mode.toString(8)} ${file.object} 0\t${file.path}`).sort();
265
+ if (canonical(git.indexEntries().sort()) !== canonical(expected))
266
+ throw new WorkspaceError("workspace_dirty");
267
+ }
268
+ lease(runId) {
269
+ const row = this.row("SELECT body FROM workspace_leases WHERE run_id=?", runId);
270
+ if (!row)
271
+ throw new WorkspaceError("workspace_lease_not_found", 404);
272
+ return JSON.parse(String(row.body));
273
+ }
274
+ saveLease(lease) {
275
+ this.coordinator.db.prepare("UPDATE workspace_leases SET state=?,body=? WHERE id=?").run(lease.state, canonical(lease), lease.id);
276
+ }
277
+ acquireLease(workspaceId, runId, hooks = {}) {
278
+ this.entry();
279
+ const record = this.record(workspaceId), snapshot = this.capture(record, runId);
280
+ this.assertClean(snapshot, this.git(record));
281
+ this.git(record).assertIdentity();
282
+ return this.coordinator.atomic(() => {
283
+ this.owned();
284
+ if (this.row("SELECT id FROM workspace_leases WHERE workspace_id=? AND state!='released'", workspaceId))
285
+ throw new WorkspaceError("workspace_leased");
286
+ const lease = { id: randomUUID(), workspaceId, runId, state: "active", knownRevisionId: snapshot.revision.id };
287
+ this.persist(snapshot);
288
+ this.coordinator.db.prepare("INSERT INTO workspace_leases VALUES (?,?,?,'active',?)").run(lease.id, workspaceId, runId, canonical(lease));
289
+ record.view.state = "leased";
290
+ record.view.activeRunId = runId;
291
+ record.view.version++;
292
+ this.saveRecord(record);
293
+ runSqlCommitHook(hooks.onAdmittedSql, lease);
294
+ return jsonCopy(lease);
295
+ });
296
+ }
297
+ assertContext(context) {
298
+ this.owned();
299
+ const lease = this.lease(context.binding.runId);
300
+ if (lease.id !== context.leaseId || lease.workspaceId !== context.workspaceId || lease.state !== "active")
301
+ throw new WorkspaceError("stale_workspace_lease");
302
+ this.pin(this.record(context.workspaceId).root);
303
+ }
304
+ toolRoot(context, kind = "workspace", scratchIndex = 0) {
305
+ this.entry();
306
+ this.assertContext(context);
307
+ const record = this.record(context.workspaceId), root = kind === "workspace" ? record.root : record.scratch[scratchIndex];
308
+ if (!root)
309
+ throw new WorkspaceError("scratch_not_registered", 422);
310
+ return this.files(root, kind);
311
+ }
312
+ deploymentRootIds() { return [...this.deploymentRoots.keys()]; }
313
+ toolDeploymentRoot(context, rootId) {
314
+ this.entry();
315
+ this.assertContext(context);
316
+ const fd = this.deploymentRoots.get(rootId);
317
+ if (fd === undefined)
318
+ throw new WorkspaceError("deployment_root_not_registered", 422);
319
+ return new NativeFilesystemRoot({ rootFd: fd, root: "deployment", rootId, helperPath: this.options.helperPath,
320
+ quarantineFd: this.quarantineFd, ...(this.options.startupLockFd === undefined ? {} : { startupLockFd: this.options.startupLockFd }),
321
+ protectedRootFds: [...this.options.protectedRootFds, ...this.engineFds, ...this.roots().map(root => this.pin(root)),
322
+ ...[...this.deploymentRoots].filter(([id]) => id !== rootId).map(([, descriptor]) => descriptor)] });
323
+ }
324
+ persistedFailure(mutate, error, hooks = {}) {
325
+ let preserve = false;
326
+ return this.coordinator.atomic(() => {
327
+ mutate();
328
+ preserve = true;
329
+ if (hooks.onCommittedErrorSql)
330
+ this.coordinator.savepoint(() => runSqlCommitHook(hooks.onCommittedErrorSql, error instanceof WorkspaceError ? { code: error.code, status: error.status } : { code: "workspace_operation_failed", status: 500 }));
331
+ throw error;
332
+ }, { commitOnError: () => preserve });
333
+ }
334
+ conflictData(known, observed) {
335
+ const paths = [...new Set([...known.entries.map(entry => entry.path), ...observed.entries.map(entry => entry.path)])]
336
+ .filter(path => canonical(known.entries.find(entry => entry.path === path) ?? null) !== canonical(observed.entries.find(entry => entry.path === path) ?? null));
337
+ if (known.revision.headCommit !== observed.revision.headCommit || known.headRef !== observed.headRef)
338
+ paths.push(".git/HEAD");
339
+ if (known.indexDigest !== observed.indexDigest)
340
+ paths.push(".git/index");
341
+ if (known.configDigest !== observed.configDigest)
342
+ paths.push(".git/config");
343
+ return { workspaceRevisionId: known.revision.id, paths: paths.sort(),
344
+ conflictDigest: digest({ expected: known.revision.contentDigest, observed: observed.revision.contentDigest, paths: paths.sort() }), detectedAt: this.time() };
345
+ }
346
+ conflict(lease, known, observed, failure) {
347
+ const conflict = this.conflictData(known, observed);
348
+ const mutate = () => {
349
+ this.coordinator.db.prepare("INSERT INTO workspace_conflicts VALUES (?,?) ON CONFLICT(run_id) DO UPDATE SET body=excluded.body").run(lease.runId, canonical(conflict));
350
+ const record = this.record(lease.workspaceId);
351
+ record.view.state = "needs_attention";
352
+ record.view.version++;
353
+ this.saveRecord(record);
354
+ };
355
+ if (failure)
356
+ this.persistedFailure(mutate, failure.error, failure.hooks);
357
+ this.coordinator.atomic(mutate);
358
+ return conflict;
359
+ }
360
+ getConflict(runId) {
361
+ const row = this.row("SELECT body FROM workspace_conflicts WHERE run_id=?", runId);
362
+ return row ? JSON.parse(String(row.body)) : undefined;
363
+ }
364
+ known(runId) {
365
+ const lease = this.lease(runId);
366
+ if (lease.state !== "active")
367
+ throw new WorkspaceError("stale_workspace_lease");
368
+ return { lease, record: this.record(lease.workspaceId), snapshot: this.load(lease.knownRevisionId) };
369
+ }
370
+ /** Snapshot bytes only. The caller owns the live-workspace assertKnown gate. */
371
+ instructionSources(runId) {
372
+ this.entry();
373
+ return this.known(runId).snapshot.entries.filter(entry => entry.type === "file")
374
+ .sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
375
+ .map(entry => ({ path: entry.path, content: Buffer.from(entry.data, "base64") }));
376
+ }
377
+ assertKnown(runId, hooks = {}) {
378
+ this.entry();
379
+ const { lease, record, snapshot } = this.known(runId), actual = this.metadata(record);
380
+ if (canonical(actual.entries) !== canonical(snapshot.entries.map(({ path, type, identity }) => ({ path, type, identity }))) ||
381
+ actual.head !== snapshot.revision.headCommit || actual.ref !== snapshot.headRef || actual.indexDigest !== snapshot.indexDigest || actual.configDigest !== snapshot.configDigest) {
382
+ this.conflict(lease, snapshot, this.capture(record, runId), { error: new WorkspaceError("external_workspace_change"), hooks });
383
+ throw new WorkspaceError("external_workspace_change");
384
+ }
385
+ }
386
+ /** Only the trusted file executor calls this after its broker grant. Record
387
+ * changed bytes from exact executable arguments/known source, never read
388
+ * unrelated file contents on behalf of a restricted model tool. */
389
+ applyMutation(context, mutation, effect) {
390
+ this.entry();
391
+ this.assertContext(context);
392
+ this.assertKnown(context.binding.runId);
393
+ const { lease, record, snapshot } = this.known(context.binding.runId);
394
+ const result = effect();
395
+ if (result && typeof result === "object" && "then" in result)
396
+ throw new WorkspaceError("async_workspace_mutation");
397
+ if (result && typeof result === "object" && "success" in result && result.success === false)
398
+ return result;
399
+ const actual = this.metadata(record), paths = new Set([mutation.path, ...(mutation.kind === "move" ? [mutation.destination] : [])]);
400
+ const permitted = (entry) => paths.has(entry.path) || (entry.type === "directory" &&
401
+ [...paths].some(path => entry.path === "." || path.startsWith(`${entry.path}/`)));
402
+ for (const path of new Set([...snapshot.entries.map(entry => entry.path), ...actual.entries.map(entry => entry.path)])) {
403
+ const before = snapshot.entries.find(entry => entry.path === path), after = actual.entries.find(entry => entry.path === path);
404
+ if (before?.identity !== after?.identity && !permitted(after ?? before)) {
405
+ this.conflict(lease, snapshot, this.capture(record, lease.runId));
406
+ throw new WorkspaceError("external_workspace_change");
407
+ }
408
+ }
409
+ const content = new Map(snapshot.entries.filter(entry => entry.type === "file").map(entry => [entry.path, entry]));
410
+ if (mutation.kind === "write")
411
+ content.set(mutation.path, { path: mutation.path, type: "file", identity: "", mode: 0,
412
+ data: mutation.content.toString("base64"), contentDigest: sha(mutation.content) });
413
+ if (mutation.kind === "delete")
414
+ content.delete(mutation.path);
415
+ if (mutation.kind === "move") {
416
+ const source = content.get(mutation.path);
417
+ if (!source)
418
+ throw new WorkspaceError("workspace_source_unknown");
419
+ content.delete(mutation.path);
420
+ content.set(mutation.destination, { ...source, path: mutation.destination });
421
+ }
422
+ const entries = actual.entries.map(entry => ({ ...entry, mode: fileMode(entry),
423
+ ...(entry.type === "file" ? { data: content.get(entry.path).data, contentDigest: content.get(entry.path).contentDigest } : {}) }));
424
+ const next = this.snapshot(record, lease.runId, entries, actual);
425
+ this.coordinator.atomic(() => { this.persist(next); lease.knownRevisionId = next.revision.id; this.saveLease(lease); });
426
+ return result;
427
+ }
428
+ captureRevision(runId, hooks = {}) {
429
+ this.entry();
430
+ if (this.options.assertNoProjectWriters)
431
+ this.options.assertNoProjectWriters(runId);
432
+ else
433
+ this.coordinator.assertQuiescent(runId);
434
+ this.assertKnown(runId, hooks);
435
+ const { lease, record } = this.known(runId), snapshot = this.capture(record, runId);
436
+ return this.coordinator.atomic(() => {
437
+ this.persist(snapshot);
438
+ lease.knownRevisionId = snapshot.revision.id;
439
+ this.saveLease(lease);
440
+ runSqlCommitHook(hooks.onAdmittedSql, snapshot.revision);
441
+ return jsonCopy(snapshot.revision);
442
+ });
443
+ }
444
+ assertRevision(runId, revisionId, hooks = {}) {
445
+ this.entry();
446
+ this.assertKnown(runId, hooks);
447
+ const { lease, snapshot } = this.known(runId), expected = this.load(revisionId);
448
+ if (expected.runId !== runId || expected.revision.workspaceId !== lease.workspaceId || expected.revision.contentDigest !== snapshot.revision.contentDigest) {
449
+ throw new WorkspaceError("workspace_revision_changed");
450
+ }
451
+ }
452
+ baseline(runId, scope, stepExecutionId, hooks = {}) {
453
+ this.entry();
454
+ this.coordinator.assertQuiescent(runId);
455
+ this.assertKnown(runId, hooks);
456
+ if (!["run_start", "step_start"].includes(scope) || (scope === "step_start" && !stepExecutionId))
457
+ throw new WorkspaceError("invalid_baseline", 422);
458
+ const { snapshot } = this.known(runId), baseline = { id: randomUUID(), runId, scope, commit: snapshot.revision.headCommit,
459
+ ...(stepExecutionId === undefined ? {} : { stepExecutionId }), createdAt: this.time() };
460
+ return this.coordinator.atomic(() => {
461
+ this.coordinator.db.prepare("INSERT INTO workspace_baselines VALUES (?,?,?,?)").run(baseline.id, runId, snapshot.revision.id, canonical(baseline));
462
+ runSqlCommitHook(hooks.onAdmittedSql, baseline);
463
+ return jsonCopy(baseline);
464
+ });
465
+ }
466
+ approveOverwrite(runId, conflictDigest) {
467
+ this.owned();
468
+ if (this.getConflict(runId)?.conflictDigest !== conflictDigest)
469
+ throw new WorkspaceError("stale_workspace_conflict");
470
+ this.coordinator.atomic(() => {
471
+ this.coordinator.db.prepare("INSERT OR IGNORE INTO workspace_overwrites(digest,run_id) VALUES (?,?)").run(conflictDigest, runId);
472
+ });
473
+ }
474
+ gate(runId) {
475
+ const exists = this.row("SELECT name FROM sqlite_master WHERE type='table' AND name='broker_runs'");
476
+ const row = exists && this.row("SELECT body FROM broker_runs WHERE id=?", runId);
477
+ if (row) {
478
+ const gate = JSON.parse(String(row.body));
479
+ if (gate.cancelled || gate.operatorPaused || (gate.deadlineAt !== null && gate.deadlineAt <= this.now()) ||
480
+ this.rows("SELECT body FROM broker_approvals WHERE run_id=?", runId).some(row => JSON.parse(String(row.body)).state === "pending")) {
481
+ throw new WorkspaceError("workspace_execution_gated");
482
+ }
483
+ }
484
+ }
485
+ saveJob(job) {
486
+ this.coordinator.db.prepare("INSERT INTO workspace_jobs VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state,body=excluded.body")
487
+ .run(job.id, job.runId, job.state, canonical(job));
488
+ }
489
+ activeWork(runId) {
490
+ return this.rows("SELECT body FROM workspace_jobs WHERE run_id=? AND state!='completed'", runId).map(row => JSON.parse(String(row.body)));
491
+ }
492
+ phase(job, state) {
493
+ job.state = state;
494
+ this.coordinator.atomic(() => this.saveJob(job));
495
+ this.options.fault?.(state, jsonCopy(job));
496
+ }
497
+ complete(job, snapshot, hooks) {
498
+ return this.coordinator.atomic(() => {
499
+ const lease = this.lease(job.runId), record = this.record(job.workspaceId);
500
+ this.persist(snapshot);
501
+ lease.state = "active";
502
+ lease.knownRevisionId = snapshot.revision.id;
503
+ this.saveLease(lease);
504
+ record.view.headCommit = snapshot.revision.headCommit;
505
+ record.view.state = "leased";
506
+ record.view.version++;
507
+ this.saveRecord(record);
508
+ job.state = "completed";
509
+ job.commit = snapshot.revision.headCommit;
510
+ this.saveJob(job);
511
+ this.coordinator.db.prepare("DELETE FROM workspace_conflicts WHERE run_id=?").run(job.runId);
512
+ runSqlCommitHook(hooks.onCompletedSql, job);
513
+ return jsonCopy(job);
514
+ });
515
+ }
516
+ uncertain(job) {
517
+ job.state = "uncertain";
518
+ this.saveJob(job);
519
+ const lease = this.lease(job.runId), record = this.record(job.workspaceId);
520
+ lease.state = "uncertain";
521
+ this.saveLease(lease);
522
+ record.view.state = "needs_attention";
523
+ record.view.version++;
524
+ this.saveRecord(record);
525
+ }
526
+ accept(input, hooks = {}) {
527
+ this.entry();
528
+ this.coordinator.assertQuiescent(input.runId);
529
+ this.gate(input.runId);
530
+ this.assertRevision(input.runId, input.revisionId, hooks);
531
+ const { lease, record } = this.known(input.runId), snapshot = this.load(input.revisionId), git = this.git(record);
532
+ if (git.head() !== input.expectedHead || snapshot.revision.headCommit !== input.expectedHead)
533
+ throw new WorkspaceError("git_expected_head_conflict");
534
+ const job = { id: randomUUID(), runId: input.runId, workspaceId: lease.workspaceId, kind: "accept",
535
+ state: "started", revisionId: snapshot.revision.id, expectedHead: input.expectedHead, headRef: snapshot.headRef, artifactId: input.artifactId };
536
+ this.coordinator.atomic(() => { this.saveJob(job); runSqlCommitHook(hooks.onAdmittedSql, job); });
537
+ try {
538
+ this.options.fault?.("started", jsonCopy(job));
539
+ const tree = git.makeTree(snapshot.entries.filter(entry => entry.type === "file")
540
+ .map(entry => ({ path: entry.path, bytes: Buffer.from(entry.data, "base64"), mode: entry.mode })));
541
+ job.candidate = git.commit(tree, input.expectedHead, `Code60 accepted step ${input.stepExecutionId}\nArtifact ${input.artifactId}\nJournal ${job.id}\n`);
542
+ this.phase(job, "candidate");
543
+ this.assertRevision(input.runId, input.revisionId);
544
+ git.updateRef(`refs/code60/candidates/${job.id}`, job.candidate, "0".repeat(40));
545
+ git.updateRef(job.headRef, job.candidate, job.expectedHead);
546
+ this.phase(job, "ref_applied");
547
+ git.installIndex(job.candidate, snapshot.indexIdentity);
548
+ this.options.fault?.("index_installed", jsonCopy(job));
549
+ const actual = this.capture(record, input.runId);
550
+ if (actual.revision.headCommit !== job.candidate || actual.headRef !== job.headRef ||
551
+ !this.sameContents(snapshot, actual))
552
+ throw new WorkspaceError("workspace_changed_during_acceptance");
553
+ return this.complete(job, actual, hooks);
554
+ }
555
+ catch (error) {
556
+ this.persistedFailure(() => this.uncertain(job), error, hooks);
557
+ }
558
+ }
559
+ sameContents(a, b) {
560
+ return a.entries.length === b.entries.length && a.entries.every(entry => {
561
+ const other = b.entries.find(item => item.path === entry.path);
562
+ return other !== undefined && sameFile(entry, other);
563
+ });
564
+ }
565
+ restore(input, hooks = {}) {
566
+ this.entry();
567
+ this.coordinator.assertQuiescent(input.runId);
568
+ this.gate(input.runId);
569
+ const { lease, record, snapshot: known } = this.known(input.runId);
570
+ const baseline = this.row("SELECT * FROM workspace_baselines WHERE id=? AND run_id=?", input.baselineId, input.runId);
571
+ if (!baseline)
572
+ throw new WorkspaceError("baseline_unavailable", 409);
573
+ const target = this.load(String(baseline.revision_id)), observed = this.capture(record, input.runId);
574
+ let conflict;
575
+ if (observed.revision.contentDigest !== known.revision.contentDigest) {
576
+ // Compute the exact conflict before selecting a grant. Failed permission
577
+ // checks and their public receipt share the conflict's root transaction.
578
+ const expected = this.conflictData(known, observed).conflictDigest;
579
+ const grant = this.row("SELECT consumed_by FROM workspace_overwrites WHERE digest=? AND run_id=?", expected, input.runId);
580
+ if (expected !== input.overwriteConflictDigest || !grant || grant.consumed_by) {
581
+ this.conflict(lease, known, observed, { error: new WorkspaceError(expected !== input.overwriteConflictDigest ?
582
+ "external_workspace_change" : "overwrite_permission_required"), hooks });
583
+ }
584
+ conflict = this.conflict(lease, known, observed);
585
+ }
586
+ const job = { id: randomUUID(), runId: input.runId, workspaceId: lease.workspaceId, kind: "restore",
587
+ state: "started", revisionId: observed.revision.id, expectedHead: observed.revision.headCommit, headRef: observed.headRef,
588
+ baselineId: input.baselineId, candidate: target.revision.headCommit };
589
+ this.coordinator.atomic(() => {
590
+ if (conflict) {
591
+ const grant = this.row("SELECT consumed_by FROM workspace_overwrites WHERE digest=? AND run_id=?", conflict.conflictDigest, input.runId);
592
+ if (!grant || grant.consumed_by)
593
+ throw new WorkspaceError("overwrite_permission_required");
594
+ this.coordinator.db.prepare("UPDATE workspace_overwrites SET consumed_by=? WHERE digest=? AND consumed_by IS NULL").run(job.id, conflict.conflictDigest);
595
+ }
596
+ this.persist(observed);
597
+ this.saveJob(job);
598
+ runSqlCommitHook(hooks.onAdmittedSql, job);
599
+ });
600
+ const files = this.files(record.root), git = this.git(record);
601
+ try {
602
+ this.options.fault?.("started", jsonCopy(job));
603
+ git.updateRef(`refs/code60/history/${job.id}`, job.expectedHead, "0".repeat(40));
604
+ for (const entry of observed.entries.filter(entry => entry.type === "file" && !target.entries.some(item => item.path === entry.path && item.type === "file"))) {
605
+ files.remove(entry.path, false, entry.identity);
606
+ }
607
+ for (const entry of observed.entries.filter(entry => entry.type === "directory" && entry.path !== "." &&
608
+ !target.entries.some(item => item.path === entry.path && item.type === "directory")).sort((a, b) => b.path.length - a.path.length)) {
609
+ const current = files.inspectTree().find(item => item.path === entry.path);
610
+ if (!current || current.type !== "directory" || current.identity.split("|f:").at(-1).split(":").slice(0, 3).join(":") !==
611
+ entry.identity.split("|f:").at(-1).split(":").slice(0, 3).join(":"))
612
+ throw new WorkspaceError("workspace_changed_during_restore");
613
+ files.remove(entry.path, true);
614
+ }
615
+ const current = new Map(files.inspectTree().map(entry => [entry.path, entry]));
616
+ for (const entry of target.entries.filter(entry => entry.type === "directory" && entry.path !== ".").sort((a, b) => a.path.length - b.path.length)) {
617
+ if (!current.has(entry.path)) {
618
+ files.makeDirectory(entry.path);
619
+ files.setMode(entry.path, entry.mode);
620
+ }
621
+ }
622
+ for (const entry of target.entries.filter(entry => entry.type === "file")) {
623
+ const before = observed.entries.find(item => item.path === entry.path && item.type === "file");
624
+ if (before && sameFile(before, entry))
625
+ continue;
626
+ const expected = before?.identity ?? files.absentIdentity(entry.path);
627
+ files.writeBytes(entry.path, Buffer.from(entry.data, "base64"), expected);
628
+ files.setMode(entry.path, entry.mode);
629
+ }
630
+ git.updateRef(job.headRef, target.revision.headCommit, job.expectedHead);
631
+ this.phase(job, "ref_applied");
632
+ git.installIndex(target.revision.headCommit, observed.indexIdentity);
633
+ this.options.fault?.("index_installed", jsonCopy(job));
634
+ const actual = this.capture(record, input.runId);
635
+ if (actual.revision.headCommit !== target.revision.headCommit || actual.headRef !== job.headRef || !this.sameContents(target, actual)) {
636
+ throw new WorkspaceError("workspace_changed_during_restore");
637
+ }
638
+ return this.complete(job, actual, hooks);
639
+ }
640
+ catch (error) {
641
+ this.persistedFailure(() => this.uncertain(job), error, hooks);
642
+ }
643
+ finally {
644
+ files.close();
645
+ }
646
+ }
647
+ /** Read/prove completion only. Never rerun Git or file effects after a crash.
648
+ * Incomplete/ambiguous journals keep the lease and require operator recovery. */
649
+ reconcile(runId, hooks = {}) {
650
+ this.entry();
651
+ this.coordinator.assertQuiescent(runId);
652
+ const lease = this.lease(runId), record = this.record(lease.workspaceId), actual = this.capture(record, runId), git = this.git(record);
653
+ const jobs = this.activeWork(runId);
654
+ return jobs.map(job => {
655
+ const expected = job.kind === "accept" ? this.load(job.revisionId) :
656
+ this.load(String(this.row("SELECT revision_id FROM workspace_baselines WHERE id=?", job.baselineId)?.revision_id));
657
+ try {
658
+ if (!job.candidate || actual.revision.headCommit !== job.candidate || actual.headRef !== job.headRef || !this.sameContents(expected, actual))
659
+ return job;
660
+ this.assertClean(actual, git);
661
+ }
662
+ catch {
663
+ return job;
664
+ }
665
+ return this.complete(job, actual, hooks);
666
+ });
667
+ }
668
+ releaseLease(runId, terminal, hooks = {}) {
669
+ this.entry();
670
+ this.coordinator.assertQuiescent(runId);
671
+ if (!terminal || this.activeWork(runId).length)
672
+ throw new WorkspaceError("workspace_writers_or_operations_unresolved");
673
+ return this.coordinator.atomic(() => {
674
+ const lease = this.lease(runId), record = this.record(lease.workspaceId);
675
+ lease.state = "released";
676
+ this.saveLease(lease);
677
+ record.view.state = "available";
678
+ delete record.view.activeRunId;
679
+ record.view.version++;
680
+ this.saveRecord(record);
681
+ runSqlCommitHook(hooks.onAdmittedSql, lease);
682
+ return lease;
683
+ });
684
+ }
685
+ activateLeaseForRecovery(runId) {
686
+ this.entry();
687
+ this.coordinator.assertQuiescent(runId);
688
+ if (this.activeWork(runId).length)
689
+ throw new WorkspaceError("workspace_operations_unreconciled");
690
+ return this.coordinator.atomic(() => {
691
+ const lease = this.lease(runId);
692
+ if (lease.state !== "uncertain")
693
+ throw new WorkspaceError("workspace_not_recovering");
694
+ lease.state = "active";
695
+ this.saveLease(lease);
696
+ return jsonCopy(lease);
697
+ });
698
+ }
699
+ close() {
700
+ if (this.closed)
701
+ return;
702
+ try {
703
+ this.coordinator.assertOutsideTransaction();
704
+ if (this.row("SELECT owner FROM workspace_owner WHERE singleton=1")?.owner === this.owner) {
705
+ this.coordinator.atomic(() => { this.coordinator.db.prepare("UPDATE workspace_owner SET owner='' WHERE owner=?").run(this.owner); });
706
+ }
707
+ }
708
+ finally {
709
+ this.closed = true;
710
+ for (const fd of [...this.descriptors.values(), ...this.engineFds])
711
+ closeSync(fd);
712
+ this.descriptors.clear();
713
+ }
714
+ }
715
+ }