code60-transmission-server 0.1.0-staging.3 → 0.1.0-staging.6

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 (36) hide show
  1. package/README.engine.md +64 -2
  2. package/README.md +66 -5
  3. package/dist/src/broker/native/README.md +15 -0
  4. package/dist/src/broker/native/build.js +3 -0
  5. package/dist/src/broker/native/command-helper.c +93 -0
  6. package/dist/src/cli/configure.js +193 -0
  7. package/dist/src/cli/daemon.js +5 -1
  8. package/dist/src/cli/helpers.js +12 -4
  9. package/dist/src/cli/main.js +12 -3
  10. package/dist/src/cli/runtime-build.js +38 -0
  11. package/dist/src/config/coding-policy.js +4 -0
  12. package/dist/src/config/deployment.js +26 -10
  13. package/dist/src/config/workflow-schema.json +11 -0
  14. package/dist/src/engine/commands.js +35 -4
  15. package/dist/src/engine/workflow-engine.js +70 -15
  16. package/dist/src/main.js +4 -1
  17. package/dist/src/mcp/main.js +4 -2
  18. package/dist/src/mcp/server.js +37 -6
  19. package/dist/src/runtime/engine-driver.js +11 -2
  20. package/dist/src/runtime/provider-bridge.js +4 -2
  21. package/dist/src/runtime/provider-transport.js +7 -5
  22. package/dist/src/server/api-contract.json +530 -2
  23. package/dist/src/server/application.js +9 -3
  24. package/dist/src/server/coding.js +254 -0
  25. package/dist/src/server/deployment.js +18 -6
  26. package/dist/src/server/history-handlers.js +16 -2
  27. package/dist/src/server/workspace-handlers.js +1 -1
  28. package/dist/src/tools/checks.js +12 -1
  29. package/dist/src/tools/command-check.js +34 -0
  30. package/dist/src/tools/commands.js +310 -0
  31. package/dist/src/tools/developer.js +351 -0
  32. package/dist/src/tools/index.js +19 -2
  33. package/dist/src/workspaces/index.js +244 -22
  34. package/dist/src/workspaces/source.js +295 -0
  35. package/package.json +4 -2
  36. package/scripts/postinstall.mjs +2 -1
@@ -1,11 +1,12 @@
1
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";
2
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join } from "node:path";
4
4
  import { canonical, digest, jsonCopy } from "../broker/policy.js";
5
5
  import { NativeFilesystemRoot } from "../broker/filesystem.js";
6
6
  import { runSqlCommitHook } from "../engine/contracts.js";
7
7
  import { startupLockIdentity } from "../broker/startup-lock.js";
8
8
  import { WorkspaceError, WorkspaceGit } from "./git.js";
9
+ import { SourceBlobs, SourceRepository, DEFAULT_SOURCE_QUOTAS } from './source.js';
9
10
  export { WorkspaceError } from "./git.js";
10
11
  export const WORKSPACE_MIGRATION = { id: "workspaces-v1", sql: `
11
12
  CREATE TABLE workspace_owner (singleton INTEGER PRIMARY KEY CHECK(singleton=1), owner TEXT NOT NULL);
@@ -20,8 +21,9 @@ export const WORKSPACE_MIGRATION = { id: "workspaces-v1", sql: `
20
21
  CREATE TABLE workspace_overwrites (digest TEXT PRIMARY KEY, run_id TEXT NOT NULL, consumed_by TEXT);
21
22
  CREATE TABLE workspace_jobs (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, state TEXT NOT NULL, body TEXT NOT NULL);
22
23
  ` };
24
+ export const WORKSPACE_SOURCE_MIGRATION = { id: 'workspace-source.v1', sql: `CREATE TABLE workspace_source_blobs (run_id TEXT NOT NULL, blob TEXT NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY(run_id,blob));` };
23
25
  const sha = (data) => createHash("sha256").update(data).digest("hex");
24
- const fileMode = (entry) => Number(entry.identity.split("|f:").at(-1).split(":")[2]) & 0o777;
26
+ const fileMode = (entry) => entry.mode ?? (Number(entry.identity.split("|f:").at(-1).split(":")[2]) & 0o777);
25
27
  const sameFile = (a, b) => a.type === b.type && a.path === b.path && a.mode === b.mode && a.contentDigest === b.contentDigest;
26
28
  const fdIdentity = (fd) => { const s = fstatSync(fd, { bigint: true }); return `${s.dev}:${s.ino}`; };
27
29
  const openDirectory = (path) => openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
@@ -30,6 +32,10 @@ const openDirectory = (path) => openSync(path, constants.O_RDONLY | constants.O_
30
32
  * No registration, lease, snapshot, Git, restore, or effect method is agent RPC. */
31
33
  export class WorkspaceService {
32
34
  options;
35
+ sourceQuotas;
36
+ blobs;
37
+ commandWriters = new Set();
38
+ commandReaders = new Map();
33
39
  coordinator;
34
40
  owner = randomUUID();
35
41
  now;
@@ -42,6 +48,7 @@ export class WorkspaceService {
42
48
  this.options = options;
43
49
  this.coordinator = options.coordinator;
44
50
  this.now = options.now ?? Date.now;
51
+ this.sourceQuotas = { ...DEFAULT_SOURCE_QUOTAS, ...options.sourceQuotas };
45
52
  this.coordinator.assertOutsideTransaction();
46
53
  if (options.recover && options.startupLockFd === undefined)
47
54
  throw new WorkspaceError("startup_writer_barrier_required", 422);
@@ -56,6 +63,7 @@ export class WorkspaceService {
56
63
  const snapshots = realpathSync(options.snapshotDirectory), s = lstatSync(snapshots);
57
64
  if (!s.isDirectory() || s.uid !== process.geteuid?.() || (s.mode & 0o77))
58
65
  throw new WorkspaceError("unsafe_snapshot_root", 422);
66
+ this.blobs = new SourceBlobs(snapshots);
59
67
  this.engineFds.push(openDirectory(snapshots));
60
68
  for (const row of this.coordinator.db.prepare("PRAGMA database_list").all()) {
61
69
  if (row.file)
@@ -135,6 +143,8 @@ export class WorkspaceService {
135
143
  ...this.roots().filter(other => other.identity !== root.identity).map(other => this.pin(other)), ...extra] });
136
144
  }
137
145
  git(record) {
146
+ if (record.sourceTracking)
147
+ return new SourceRepository(record.root.path, record.gitIdentity, record.generatedPaths ?? [], this.options.startupLockFd);
138
148
  return new WorkspaceGit({ rootFd: this.pin(record.root), repositoryPath: record.root.path,
139
149
  ...(this.options.startupLockFd === undefined ? {} : { startupLockFd: this.options.startupLockFd }),
140
150
  helperPath: this.options.gitHelperPath, expectedIdentity: record.gitIdentity });
@@ -167,8 +177,10 @@ export class WorkspaceService {
167
177
  this.files(candidates[i], i === 0 ? "workspace" : "scratch", temporary.filter((_, j) => j !== i)).close();
168
178
  if (this.row("SELECT id FROM workspace_records WHERE identity=?", root.identity))
169
179
  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,
180
+ const git = input.sourceTracking ? new SourceRepository(root.path, undefined, this.options.generatedPaths ?? [], this.options.startupLockFd) : new WorkspaceGit({ rootFd: this.pin(root), repositoryPath: root.path, helperPath: this.options.gitHelperPath });
181
+ if (this.rows('SELECT body FROM workspace_records').some(row => JSON.parse(String(row.body)).gitIdentity === git.identity))
182
+ throw new WorkspaceError('workspace_git_alias', 422);
183
+ const record = { root, scratch, gitIdentity: git.identity, ...(input.sourceTracking ? { sourceTracking: true, generatedPaths: [...this.options.generatedPaths ?? []] } : {}), view: { id: randomUUID(), name: input.name,
172
184
  repositoryPath: root.path, scratchPaths: scratch.map(item => item.path), headCommit: git.head(), state: "available", version: 1, createdAt: this.time() } };
173
185
  try {
174
186
  this.assertClean(this.capture(record, "registration"), git);
@@ -199,17 +211,52 @@ export class WorkspaceService {
199
211
  }
200
212
  }
201
213
  }
214
+ enableSourceTracking(workspaceId) {
215
+ this.entry();
216
+ const record = this.record(workspaceId);
217
+ if (record.view.activeRunId || this.row("SELECT id FROM workspace_leases WHERE workspace_id=? AND state!='released'", workspaceId))
218
+ throw new WorkspaceError('workspace_leased');
219
+ if (record.sourceTracking && canonical(record.generatedPaths ?? []) === canonical(this.options.generatedPaths ?? []))
220
+ return;
221
+ if (!record.sourceTracking)
222
+ this.git(record); // Prove the legacy identity before upgrading its format.
223
+ const git = new SourceRepository(record.root.path, record.sourceTracking ? record.gitIdentity : undefined, this.options.generatedPaths ?? [], this.options.startupLockFd);
224
+ record.sourceTracking = true;
225
+ record.generatedPaths = [...this.options.generatedPaths ?? []];
226
+ record.gitIdentity = git.identity;
227
+ this.capture(record, 'registration');
228
+ record.view.version++;
229
+ record.view.state = 'available';
230
+ this.coordinator.atomic(() => this.saveRecord(record));
231
+ }
232
+ get commandHelperPath() { return join(dirname(this.options.helperPath), 'command-helper'); }
202
233
  metadata(record) {
203
234
  const files = this.files(record.root);
204
235
  try {
205
236
  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 };
237
+ return { entries: git instanceof SourceRepository ? git.sourceEntries() : files.inspectTree(), git, head: git.head(), ref: git.branch(), indexIdentity: index.identity, indexDigest: index.contentDigest, configDigest };
207
238
  }
208
239
  finally {
209
240
  files.close();
210
241
  }
211
242
  }
212
243
  capture(record, runId) {
244
+ if (record.sourceTracking) {
245
+ const before = this.metadata(record), git = before.git;
246
+ const entries = git.capture(this.blobs, this.sourceQuotas), after = this.metadata(record);
247
+ if (canonical(before.entries) !== canonical(after.entries) || before.head !== after.head || before.indexDigest !== after.indexDigest || before.configDigest !== after.configDigest)
248
+ throw new WorkspaceError('workspace_changed_during_capture');
249
+ if (runId !== 'registration')
250
+ this.coordinator.atomic(() => {
251
+ for (const entry of entries)
252
+ if (entry.blob)
253
+ this.coordinator.db.prepare('INSERT OR IGNORE INTO workspace_source_blobs VALUES (?,?,?)').run(runId, entry.blob, entry.size ?? 0);
254
+ const usage = this.row('SELECT COALESCE(SUM(bytes),0) AS bytes FROM workspace_source_blobs WHERE run_id=?', runId);
255
+ if (Number(usage?.bytes ?? 0) > this.sourceQuotas.totalBytes)
256
+ throw new WorkspaceError('source_total_quota', 422);
257
+ });
258
+ return { ...this.snapshot(record, runId, entries, before), indexBlob: this.blobs.put(git.index().bytes) };
259
+ }
213
260
  const before = this.metadata(record), files = this.files(record.root);
214
261
  try {
215
262
  let bytes = 0;
@@ -241,7 +288,13 @@ export class WorkspaceService {
241
288
  indexDigest: metadata.indexDigest, configDigest: metadata.configDigest, entries };
242
289
  }
243
290
  persist(snapshot) {
244
- this.coordinator.db.prepare("INSERT INTO workspace_snapshots VALUES (?,?,?)").run(snapshot.revision.id, snapshot.revision.workspaceId, canonical(snapshot));
291
+ const body = canonical(snapshot), prior = this.row('SELECT body FROM workspace_snapshots WHERE id=?', snapshot.revision.id);
292
+ if (prior) {
293
+ if (prior.body !== body)
294
+ throw new WorkspaceError('immutable_snapshot');
295
+ return;
296
+ }
297
+ this.coordinator.db.prepare("INSERT INTO workspace_snapshots VALUES (?,?,?)").run(snapshot.revision.id, snapshot.revision.workspaceId, body);
245
298
  }
246
299
  load(id) {
247
300
  const row = this.row("SELECT body FROM workspace_snapshots WHERE id=?", id);
@@ -251,14 +304,14 @@ export class WorkspaceService {
251
304
  }
252
305
  revision(id) { this.owned(); return jsonCopy(this.load(id).revision); }
253
306
  assertClean(snapshot, git) {
254
- const tracked = git.tree(snapshot.revision.headCommit), actual = snapshot.entries.filter(entry => entry.type === "file");
307
+ const tracked = git.tree(snapshot.revision.headCommit), actual = snapshot.entries.filter(entry => entry.type !== "directory");
255
308
  if (tracked.length !== actual.length || tracked.some(file => {
256
309
  const entry = actual.find(item => item.path === file.path);
257
310
  if (!entry)
258
311
  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);
312
+ const bytes = entry.gitObject ? undefined : this.blobs.bytes(entry);
313
+ const object = entry.gitObject ?? createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
314
+ return object !== file.object || (entry.type === 'symlink' ? file.mode !== 0o120000 : Boolean(entry.mode & 0o100) !== Boolean(file.mode & 0o100));
262
315
  }))
263
316
  throw new WorkspaceError("workspace_dirty");
264
317
  const expected = tracked.map(file => `${file.mode.toString(8)} ${file.object} 0\t${file.path}`).sort();
@@ -274,11 +327,15 @@ export class WorkspaceService {
274
327
  saveLease(lease) {
275
328
  this.coordinator.db.prepare("UPDATE workspace_leases SET state=?,body=? WHERE id=?").run(lease.state, canonical(lease), lease.id);
276
329
  }
277
- acquireLease(workspaceId, runId, hooks = {}) {
330
+ acquireLease(workspaceId, runId, hooks = {}, resultMode = 'commit') {
278
331
  this.entry();
279
332
  const record = this.record(workspaceId), snapshot = this.capture(record, runId);
280
- this.assertClean(snapshot, this.git(record));
281
- this.git(record).assertIdentity();
333
+ if (resultMode === 'commit') {
334
+ this.assertClean(snapshot, this.git(record));
335
+ if (!snapshot.headRef.startsWith('refs/heads/'))
336
+ throw new WorkspaceError('unsupported_git_head');
337
+ this.git(record).assertIdentity();
338
+ }
282
339
  return this.coordinator.atomic(() => {
283
340
  this.owned();
284
341
  if (this.row("SELECT id FROM workspace_leases WHERE workspace_id=? AND state!='released'", workspaceId))
@@ -301,6 +358,131 @@ export class WorkspaceService {
301
358
  throw new WorkspaceError("stale_workspace_lease");
302
359
  this.pin(this.record(context.workspaceId).root);
303
360
  }
361
+ sourceRepository(runId) {
362
+ this.entry();
363
+ const { record } = this.known(runId);
364
+ return record.sourceTracking ? this.git(record) : undefined;
365
+ }
366
+ assertWritable(runId) { if (this.commandWriters.has(runId) || this.commandReaders.get(runId))
367
+ throw new WorkspaceError('workspace_command_active', 409, 'Stop or await active commands before editing source.'); }
368
+ beginCommand(runId, writing) {
369
+ this.entry();
370
+ if (writing)
371
+ this.assertWritable(runId);
372
+ else if (this.commandWriters.has(runId))
373
+ throw new WorkspaceError('workspace_command_active');
374
+ this.assertKnown(runId);
375
+ if (!this.sourceRepository(runId))
376
+ throw new WorkspaceError('source_tracking_required', 422);
377
+ if (writing)
378
+ this.commandWriters.add(runId);
379
+ else
380
+ this.commandReaders.set(runId, (this.commandReaders.get(runId) ?? 0) + 1);
381
+ return this.revision(this.lease(runId).knownRevisionId);
382
+ }
383
+ settleCommand(runId, writing, before) {
384
+ this.entry();
385
+ const { lease, record } = this.known(runId), previous = this.load(before);
386
+ try {
387
+ const next = this.capture(record, runId);
388
+ if (next.revision.headCommit !== previous.revision.headCommit || next.indexDigest !== previous.indexDigest || next.configDigest !== previous.configDigest ||
389
+ (!writing && !this.sameContents(previous, next)))
390
+ throw new WorkspaceError('command_changed_protected_source');
391
+ if (!writing)
392
+ return previous.revision;
393
+ this.coordinator.atomic(() => { this.persist(next); lease.knownRevisionId = next.revision.id; this.saveLease(lease); });
394
+ return next.revision;
395
+ }
396
+ catch (error) {
397
+ lease.state = 'uncertain';
398
+ this.saveLease(lease);
399
+ throw error;
400
+ }
401
+ finally {
402
+ if (writing)
403
+ this.commandWriters.delete(runId);
404
+ else
405
+ this.commandReaders.set(runId, Math.max(0, (this.commandReaders.get(runId) ?? 1) - 1));
406
+ }
407
+ }
408
+ sourceMutation(context, effect) {
409
+ this.entry();
410
+ this.assertContext(context);
411
+ this.assertWritable(context.binding.runId);
412
+ this.assertKnown(context.binding.runId);
413
+ const { lease, record } = this.known(context.binding.runId), repository = this.sourceRepository(lease.runId);
414
+ if (!repository)
415
+ throw new WorkspaceError('source_tracking_required', 422);
416
+ try {
417
+ const result = effect(repository), next = this.capture(record, lease.runId);
418
+ this.coordinator.atomic(() => { this.persist(next); lease.knownRevisionId = next.revision.id; this.saveLease(lease); });
419
+ return result;
420
+ }
421
+ catch (error) {
422
+ try {
423
+ this.assertKnown(lease.runId);
424
+ }
425
+ catch {
426
+ lease.state = 'uncertain';
427
+ this.saveLease(lease);
428
+ }
429
+ throw error;
430
+ }
431
+ }
432
+ recoveryPreview(runId) {
433
+ this.entry();
434
+ const lease = this.lease(runId), snapshot = this.capture(this.record(lease.workspaceId), runId);
435
+ this.persist(snapshot);
436
+ return { sourceDigest: snapshot.revision.contentDigest, revisionId: snapshot.revision.id };
437
+ }
438
+ resolveStoppedCommand(runId, beforeRevisionId, resolution) {
439
+ this.entry();
440
+ const lease = this.lease(runId), record = this.record(lease.workspaceId), before = this.load(beforeRevisionId), observed = this.capture(record, runId), git = this.git(record);
441
+ if (!(git instanceof SourceRepository) || observed.revision.contentDigest !== resolution.sourceDigest)
442
+ throw new WorkspaceError('command_recovery_digest_changed');
443
+ if (observed.indexDigest !== before.indexDigest || observed.configDigest !== before.configDigest || observed.revision.headCommit !== before.revision.headCommit)
444
+ throw new WorkspaceError('command_recovery_git_conflict');
445
+ if (resolution.action === 'rollback')
446
+ git.restore(before.entries, observed.entries, this.blobs);
447
+ const next = resolution.action === 'rollback' ? this.capture(record, runId) : observed;
448
+ this.coordinator.atomic(() => { this.persist(next); lease.knownRevisionId = next.revision.id; this.saveLease(lease); });
449
+ this.commandWriters.delete(runId);
450
+ this.commandReaders.delete(runId);
451
+ }
452
+ sourceResult(runId, revisionId) {
453
+ this.entry();
454
+ const lease = this.lease(runId), record = this.record(lease.workspaceId);
455
+ if (lease.state === 'active')
456
+ this.assertKnown(runId);
457
+ const resultFile = join(this.options.snapshotDirectory, `result-${revisionId ?? lease.knownRevisionId}.json`);
458
+ if (existsSync(resultFile))
459
+ return JSON.parse(readFileSync(resultFile, 'utf8'));
460
+ const repository = record.sourceTracking ? this.git(record) : undefined;
461
+ if (!repository)
462
+ throw new WorkspaceError('source_tracking_required', 422);
463
+ const row = this.row("SELECT revision_id FROM workspace_baselines WHERE run_id=? AND json_extract(body,'$.scope')='run_start' ORDER BY rowid LIMIT 1", runId);
464
+ if (!row)
465
+ throw new WorkspaceError('baseline_unavailable');
466
+ const before = this.load(String(row.revision_id)), after = this.load(revisionId ?? lease.knownRevisionId);
467
+ if (after.runId !== runId || after.revision.workspaceId !== record.view.id)
468
+ throw new WorkspaceError('revision_scope_mismatch');
469
+ const paths = [...new Set([...before.entries, ...after.entries].filter(e => e.type !== 'directory').map(e => e.path))].sort();
470
+ const files = paths.flatMap(path => {
471
+ const a = before.entries.find(e => e.path === path), b = after.entries.find(e => e.path === path);
472
+ return a && b && sameFile(a, b) ? [] : [{ path, status: !a ? 'added' : !b ? 'deleted' : 'modified' }];
473
+ });
474
+ const patchPath = join(this.options.snapshotDirectory, `result-${after.revision.id}.patch`);
475
+ const fd = openSync(patchPath, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, 0o600);
476
+ try {
477
+ repository.git(['diff-tree', '--no-commit-id', '-r', '-p', '--binary', '--no-ext-diff', '--no-textconv', repository.sourceTree(before.entries, this.blobs), repository.sourceTree(after.entries, this.blobs)], undefined, fd);
478
+ }
479
+ finally {
480
+ closeSync(fd);
481
+ }
482
+ const result = { baselineRevisionId: before.revision.id, workspaceRevisionId: after.revision.id, files, patchPath };
483
+ writeFileSync(resultFile, JSON.stringify(result), { mode: 0o600 });
484
+ return result;
485
+ }
304
486
  toolRoot(context, kind = "workspace", scratchIndex = 0) {
305
487
  this.entry();
306
488
  this.assertContext(context);
@@ -370,14 +552,22 @@ export class WorkspaceService {
370
552
  /** Snapshot bytes only. The caller owns the live-workspace assertKnown gate. */
371
553
  instructionSources(runId) {
372
554
  this.entry();
373
- return this.known(runId).snapshot.entries.filter(entry => entry.type === "file")
555
+ const { snapshot, record } = this.known(runId);
556
+ return snapshot.entries.filter(entry => entry.type === "file" && (entry.size ?? 0) <= 1_048_576 && (!record.sourceTracking || ['AGENTS.md', 'AGENTS.override.md'].includes(basename(entry.path))))
374
557
  .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") }));
558
+ .map(entry => ({ path: entry.path, content: this.blobs.bytes(entry) }));
559
+ }
560
+ instructionSource(runId, path) {
561
+ this.entry();
562
+ const entry = this.known(runId).snapshot.entries.find(entry => entry.path === path && entry.type === 'file');
563
+ if (!entry || (entry.size ?? 0) > 1_048_576)
564
+ throw new WorkspaceError('instruction_source_unavailable', 422);
565
+ return this.blobs.bytes(entry);
376
566
  }
377
567
  assertKnown(runId, hooks = {}) {
378
568
  this.entry();
379
569
  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 }))) ||
570
+ if (canonical(actual.entries.map(({ path, type, identity }) => ({ path, type, identity }))) !== canonical(snapshot.entries.map(({ path, type, identity }) => ({ path, type, identity }))) ||
381
571
  actual.head !== snapshot.revision.headCommit || actual.ref !== snapshot.headRef || actual.indexDigest !== snapshot.indexDigest || actual.configDigest !== snapshot.configDigest) {
382
572
  this.conflict(lease, snapshot, this.capture(record, runId), { error: new WorkspaceError("external_workspace_change"), hooks });
383
573
  throw new WorkspaceError("external_workspace_change");
@@ -387,6 +577,7 @@ export class WorkspaceService {
387
577
  * changed bytes from exact executable arguments/known source, never read
388
578
  * unrelated file contents on behalf of a restricted model tool. */
389
579
  applyMutation(context, mutation, effect) {
580
+ this.assertWritable(context.binding.runId);
390
581
  this.entry();
391
582
  this.assertContext(context);
392
583
  this.assertKnown(context.binding.runId);
@@ -406,6 +597,11 @@ export class WorkspaceService {
406
597
  throw new WorkspaceError("external_workspace_change");
407
598
  }
408
599
  }
600
+ if (record.sourceTracking) {
601
+ const next = this.capture(record, lease.runId);
602
+ this.coordinator.atomic(() => { this.persist(next); lease.knownRevisionId = next.revision.id; this.saveLease(lease); });
603
+ return result;
604
+ }
409
605
  const content = new Map(snapshot.entries.filter(entry => entry.type === "file").map(entry => [entry.path, entry]));
410
606
  if (mutation.kind === "write")
411
607
  content.set(mutation.path, { path: mutation.path, type: "file", identity: "", mode: 0,
@@ -506,7 +702,8 @@ export class WorkspaceService {
506
702
  record.view.version++;
507
703
  this.saveRecord(record);
508
704
  job.state = "completed";
509
- job.commit = snapshot.revision.headCommit;
705
+ if (job.resultMode !== 'working_tree')
706
+ job.commit = snapshot.revision.headCommit;
510
707
  this.saveJob(job);
511
708
  this.coordinator.db.prepare("DELETE FROM workspace_conflicts WHERE run_id=?").run(job.runId);
512
709
  runSqlCommitHook(hooks.onCompletedSql, job);
@@ -532,12 +729,18 @@ export class WorkspaceService {
532
729
  if (git.head() !== input.expectedHead || snapshot.revision.headCommit !== input.expectedHead)
533
730
  throw new WorkspaceError("git_expected_head_conflict");
534
731
  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 };
732
+ state: "started", revisionId: snapshot.revision.id, expectedHead: input.expectedHead, headRef: snapshot.headRef, artifactId: input.artifactId, ...(input.resultMode ? { resultMode: input.resultMode } : {}), ...(input.resultMode === 'working_tree' ? { candidate: input.expectedHead } : {}) };
536
733
  this.coordinator.atomic(() => { this.saveJob(job); runSqlCommitHook(hooks.onAdmittedSql, job); });
537
734
  try {
538
735
  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 })));
736
+ if (input.resultMode === 'working_tree') {
737
+ job.resultMode = 'working_tree';
738
+ job.candidate = input.expectedHead;
739
+ this.sourceResult(input.runId, input.revisionId);
740
+ return this.complete(job, snapshot, hooks);
741
+ }
742
+ const tree = git instanceof SourceRepository ? git.sourceTree(snapshot.entries, this.blobs) : git.makeTree(snapshot.entries.filter(entry => entry.type === "file")
743
+ .map(entry => ({ path: entry.path, bytes: this.blobs.bytes(entry), mode: entry.mode })));
541
744
  job.candidate = git.commit(tree, input.expectedHead, `Code60 accepted step ${input.stepExecutionId}\nArtifact ${input.artifactId}\nJournal ${job.id}\n`);
542
745
  this.phase(job, "candidate");
543
746
  this.assertRevision(input.runId, input.revisionId);
@@ -600,6 +803,18 @@ export class WorkspaceService {
600
803
  const files = this.files(record.root), git = this.git(record);
601
804
  try {
602
805
  this.options.fault?.("started", jsonCopy(job));
806
+ if (git instanceof SourceRepository) {
807
+ git.restore(target.entries, observed.entries, this.blobs);
808
+ if (git.head() !== target.revision.headCommit)
809
+ git.updateRef(job.headRef, target.revision.headCommit, job.expectedHead);
810
+ if (target.indexBlob)
811
+ git.restoreIndex(this.blobs.bytes({ path: 'index', type: 'file', mode: 0o600, identity: '', blob: target.indexBlob }));
812
+ this.phase(job, 'ref_applied');
813
+ const actual = this.capture(record, input.runId);
814
+ if (!this.sameContents(target, actual) || actual.indexDigest !== target.indexDigest)
815
+ throw new WorkspaceError('workspace_changed_during_restore');
816
+ return this.complete(job, actual, hooks);
817
+ }
603
818
  git.updateRef(`refs/code60/history/${job.id}`, job.expectedHead, "0".repeat(40));
604
819
  for (const entry of observed.entries.filter(entry => entry.type === "file" && !target.entries.some(item => item.path === entry.path && item.type === "file"))) {
605
820
  files.remove(entry.path, false, entry.identity);
@@ -657,7 +872,14 @@ export class WorkspaceService {
657
872
  try {
658
873
  if (!job.candidate || actual.revision.headCommit !== job.candidate || actual.headRef !== job.headRef || !this.sameContents(expected, actual))
659
874
  return job;
660
- this.assertClean(actual, git);
875
+ if (job.resultMode === 'working_tree' || record.sourceTracking && job.kind === 'restore') {
876
+ if (actual.indexDigest !== expected.indexDigest || actual.configDigest !== expected.configDigest)
877
+ return job;
878
+ if (job.resultMode === 'working_tree')
879
+ this.sourceResult(runId, job.revisionId);
880
+ }
881
+ else
882
+ this.assertClean(actual, git);
661
883
  }
662
884
  catch {
663
885
  return job;