@cogitator-ai/bridge 0.6.0 → 0.7.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 (72) hide show
  1. package/README.md +43 -5
  2. package/dist/adapters/claude.d.ts +13 -0
  3. package/dist/adapters/claude.d.ts.map +1 -1
  4. package/dist/adapters/claude.js +11 -1
  5. package/dist/adapters/claude.js.map +1 -1
  6. package/dist/checks.d.ts +31 -0
  7. package/dist/checks.d.ts.map +1 -0
  8. package/dist/checks.js +202 -0
  9. package/dist/checks.js.map +1 -0
  10. package/dist/client.d.ts +7 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +14 -0
  13. package/dist/client.js.map +1 -1
  14. package/dist/dispatcher.d.ts +118 -2
  15. package/dist/dispatcher.d.ts.map +1 -1
  16. package/dist/dispatcher.js +570 -11
  17. package/dist/dispatcher.js.map +1 -1
  18. package/dist/errors.d.ts +1 -1
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js.map +1 -1
  21. package/dist/index.d.ts +3 -2
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/inputs.d.ts +89 -0
  26. package/dist/inputs.d.ts.map +1 -1
  27. package/dist/inputs.js +24 -0
  28. package/dist/inputs.js.map +1 -1
  29. package/dist/job-record.d.ts +41 -1
  30. package/dist/job-record.d.ts.map +1 -1
  31. package/dist/job-record.js +38 -1
  32. package/dist/job-record.js.map +1 -1
  33. package/dist/letters.d.ts +3 -1
  34. package/dist/letters.d.ts.map +1 -1
  35. package/dist/letters.js +38 -5
  36. package/dist/letters.js.map +1 -1
  37. package/dist/paths.d.ts +7 -0
  38. package/dist/paths.d.ts.map +1 -1
  39. package/dist/paths.js +9 -0
  40. package/dist/paths.js.map +1 -1
  41. package/dist/protocol.d.ts +3 -0
  42. package/dist/protocol.d.ts.map +1 -1
  43. package/dist/protocol.js +3 -0
  44. package/dist/protocol.js.map +1 -1
  45. package/dist/registry.d.ts +7 -2
  46. package/dist/registry.d.ts.map +1 -1
  47. package/dist/registry.js +8 -5
  48. package/dist/registry.js.map +1 -1
  49. package/dist/server.d.ts.map +1 -1
  50. package/dist/server.js +3 -0
  51. package/dist/server.js.map +1 -1
  52. package/dist/tools/guidance.d.ts.map +1 -1
  53. package/dist/tools/guidance.js +2 -0
  54. package/dist/tools/guidance.js.map +1 -1
  55. package/dist/tools/index.d.ts +1 -1
  56. package/dist/tools/index.js +1 -1
  57. package/dist/tools/tools.d.ts +1 -1
  58. package/dist/tools/tools.d.ts.map +1 -1
  59. package/dist/tools/tools.js +168 -4
  60. package/dist/tools/tools.js.map +1 -1
  61. package/dist/types.d.ts +90 -5
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/types.js +23 -2
  64. package/dist/types.js.map +1 -1
  65. package/dist/worktree.d.ts +131 -0
  66. package/dist/worktree.d.ts.map +1 -0
  67. package/dist/worktree.js +278 -0
  68. package/dist/worktree.js.map +1 -0
  69. package/fakes/claude.mjs +53 -3
  70. package/fakes/lib.mjs +24 -9
  71. package/fakes/mcp.mjs +3 -2
  72. package/package.json +4 -4
@@ -1,15 +1,47 @@
1
1
  import { EventEmitter } from 'node:events';
2
+ import { existsSync } from 'node:fs';
2
3
  import { isAbsolute, resolve as resolvePath } from 'node:path';
3
4
  import { TaskManager, textPart, toMessage } from '@cogitator-ai/a2a';
5
+ import { runCheck, skippedCheck, summarizeChecks } from './checks.js';
4
6
  import { BridgeError } from './errors.js';
5
7
  import { deliveryBackoff, exhaustedBudget, formatDuration, nextDepth, resolveBudget, resolveLimits, } from './guards.js';
6
- import { AgentsFilterSchema, CreateJobInputSchema, DEFAULT_INBOX_LIMIT, DEFAULT_LIST_LIMIT, DEFAULT_VERDICT_WAIT_MS, DEFAULT_WAIT_MS, DeliveredInputSchema, EscalateInputSchema, InboxInputSchema, JobsFilterSchema, JournalQuerySchema, LettersFilterSchema, PersonAnswerInputSchema, SendLetterInputSchema, StuckInputSchema, VerdictInputSchema, VerificationInputSchema, WaitInputSchema, WithdrawInputSchema, } from './inputs.js';
8
+ import { AgentsFilterSchema, CreateJobInputSchema, DEFAULT_INBOX_LIMIT, DEFAULT_LIST_LIMIT, DEFAULT_VERDICT_WAIT_MS, DEFAULT_WAIT_MS, DeliveredInputSchema, EscalateInputSchema, InboxInputSchema, JobsFilterSchema, JournalQuerySchema, LettersFilterSchema, PersonAnswerInputSchema, SendLetterInputSchema, StuckInputSchema, VerdictInputSchema, VerificationInputSchema, AcceptInputSchema, DiffInputSchema, RejectInputSchema, WaitInputSchema, WithdrawInputSchema, } from './inputs.js';
7
9
  import { isFinishedJobState, jobOf, jobRecordOf } from './job-record.js';
8
10
  import { expectationOf, forHistory, newLetterId, normalizeBody, oneLine, quoted, renderLetter, repeats, titleOf, } from './letters.js';
9
- import { canonicalPath, findCheckoutRoot, findProjectRoot, isInside } from './paths.js';
11
+ import { canonicalPath, findCheckoutRoot, findProjectRoot, inCheckout, isInside } from './paths.js';
12
+ import { DISCARDED_REFS, GitError, addJobWorktree, branchTip, busyWith, changesOf, checkoutOf, conflictsOf, patchOf, pointRef, removeJobWorktree, shownPath, snapshotOf, squashInto, } from './worktree.js';
10
13
  import { allocateAgentName, resolveAddress } from './registry.js';
11
14
  import { BRIDGE_JOB_KEY, BRIDGE_SENDER, CallerIdentitySchema, DEFAULT_LIMITS, HarnessNameSchema, INBOX_DELIVERY, NO_CAPABILITIES, PERSON, } from './types.js';
12
15
  const ACTIVE_JOB_STATES = ['submitted', 'working', 'input-required'];
16
+ const FINISHED_JOB_STATES = ['completed', 'failed', 'canceled'];
17
+ /** How often the worktrees of finished jobs are looked at for those nobody came for, in ms. */
18
+ const WORKTREE_SWEEP_MS = 3_600_000;
19
+ /** How many changed files the record of a job names. */
20
+ const PATHS_KEPT = 50;
21
+ const ENDED = {
22
+ accepted: 'taken',
23
+ branch: 'left as a branch',
24
+ rejected: 'dropped',
25
+ discarded: 'put away',
26
+ };
27
+ /** What a job changed, as its record keeps it. */
28
+ function summaryOf(changes, at) {
29
+ return {
30
+ files: changes.files.length,
31
+ insertions: changes.insertions,
32
+ deletions: changes.deletions,
33
+ commits: changes.commits,
34
+ paths: changes.files.slice(0, PATHS_KEPT).map((file) => shownPath(file.path)),
35
+ at,
36
+ };
37
+ }
38
+ /** What git said when it refused, as an error an agent can act on. */
39
+ function gitRefusal(error, what) {
40
+ if (error instanceof BridgeError)
41
+ return error;
42
+ const said = error instanceof GitError ? error.said : asError(error).message;
43
+ return new BridgeError('invalid_input', `${what}: ${oneLine(said)}`);
44
+ }
13
45
  const UNREAD_STATES = ['queued', 'delivered'];
14
46
  const NEEDS_ANSWER = ['question', 'permission'];
15
47
  const REMINDER_QUOTE_LENGTH = 500;
@@ -41,6 +73,7 @@ function fitting(items, sizeOf, budget = MAX_ANSWER_CHARS, orNone = false) {
41
73
  return taken;
42
74
  }
43
75
  const STATE_RANK = {
76
+ held: -1,
44
77
  queued: 0,
45
78
  delivered: 1,
46
79
  read: 2,
@@ -118,6 +151,17 @@ export class BridgeDispatcher extends EventEmitter {
118
151
  verdictWaiters = new Map();
119
152
  /** What the person route is told, one thing after another */
120
153
  personNews = Promise.resolve();
154
+ /** The checks that run or wait their turn, by job, each with what stops it */
155
+ checkRuns = new Map();
156
+ /** The checks of one job after those of another: they build and test, and memory is short */
157
+ checkQueue = Promise.resolve();
158
+ /** The last work on each checkout something is being brought into, see `oneAtATimeIn` */
159
+ checkouts = new Map();
160
+ /** Jobs whose worktree is being taken, dropped or put away right now */
161
+ taking = new Set();
162
+ /** Whether what a dispatcher before this one left unfinished was picked up */
163
+ recovered = false;
164
+ worktreesSweptAt = Number.NEGATIVE_INFINITY;
121
165
  queue = Promise.resolve();
122
166
  deliveries = new Map();
123
167
  background = new Set();
@@ -272,6 +316,7 @@ export class BridgeDispatcher extends EventEmitter {
272
316
  caller: from.name,
273
317
  now: this.now(),
274
318
  canSpawn: (harness) => this.adapters.get(harness)?.createSession !== undefined,
319
+ fresh: request.worktree === true,
275
320
  });
276
321
  const carriedOut = this.store
277
322
  .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
@@ -311,6 +356,8 @@ export class BridgeDispatcher extends EventEmitter {
311
356
  if (!isInside(from.project, cwd) && !isInside(findCheckoutRoot(from.cwd), cwd)) {
312
357
  throw new BridgeError('invalid_input', `A job is done inside the project it is handed over in (${from.project}) or the checkout you work in, and ${cwd} is outside both`, { cwd, project: from.project });
313
358
  }
359
+ if (request.worktree)
360
+ this.checkWorktreeAsked(from, resolution, cwd);
314
361
  const now = this.now();
315
362
  const refusal = this.handOverRefusal(from, resolution, request.body, cwd, now);
316
363
  if (refusal) {
@@ -354,6 +401,7 @@ export class BridgeDispatcher extends EventEmitter {
354
401
  to: to.name,
355
402
  project: from.project,
356
403
  cwd,
404
+ ...(request.worktree && { isolation: 'worktree' }),
357
405
  checks: request.checks ?? [],
358
406
  budget,
359
407
  lettersUsed: 1,
@@ -374,7 +422,7 @@ export class BridgeDispatcher extends EventEmitter {
374
422
  agent: from.name,
375
423
  data: { title: record.title, from: from.name, to: to.name, depth, cwd },
376
424
  });
377
- const letter = this.accept(tx, {
425
+ const letter = this.acceptLetter(tx, {
378
426
  id: firstLetterId,
379
427
  job: number,
380
428
  kind: 'task',
@@ -411,6 +459,7 @@ export class BridgeDispatcher extends EventEmitter {
411
459
  const request = parse(SendLetterInputSchema, input, 'Cannot send the letter');
412
460
  this.checkBody(request.body);
413
461
  const rights = request.ask ? await this.rightsFor(request.job, request.ask) : undefined;
462
+ const changes = request.kind === 'report' ? await this.changesAtReport(request.job) : undefined;
414
463
  const outcome = await this.asCaller(caller, async (tx) => {
415
464
  const from = this.requireCaller(caller);
416
465
  if (request.id) {
@@ -507,7 +556,7 @@ export class BridgeDispatcher extends EventEmitter {
507
556
  : rights === 'ask' && !forPerson
508
557
  ? 'Only the person can allow this, and this bridge has no way to reach them, so it is refused'
509
558
  : undefined;
510
- const letter = this.accept(tx, {
559
+ const letter = this.acceptLetter(tx, {
511
560
  id: request.id ?? this.letterId(),
512
561
  job: job.number,
513
562
  kind: request.kind,
@@ -545,6 +594,16 @@ export class BridgeDispatcher extends EventEmitter {
545
594
  await this.transition(tx, job.number, state, forHistory(request.body, letter.id));
546
595
  if (state === 'failed')
547
596
  await this.patchRecord(job.taskId, { reason: `reported as failed by ${from.name}` });
597
+ if (changes && job.worktree && !job.worktree.end) {
598
+ await this.patchRecord(job.taskId, { changes });
599
+ }
600
+ if (state === 'completed' && job.checks.length > 0) {
601
+ this.store.updateLetter(letter.id, { state: 'held' });
602
+ await this.patchRecord(job.taskId, {
603
+ checking: { letter: letter.id, since: this.iso(now) },
604
+ });
605
+ tx.checks.push(job.number);
606
+ }
548
607
  this.closeLetters(tx, job.number, letter.id);
549
608
  await this.stopWaiting(job.number, now, false);
550
609
  await this.cancelChildren(tx, job);
@@ -644,7 +703,7 @@ export class BridgeDispatcher extends EventEmitter {
644
703
  }
645
704
  const body = request.body ??
646
705
  (request.verdict === 'allow' ? 'Allowed by the person' : 'Refused by the person');
647
- const letter = this.accept(tx, {
706
+ const letter = this.acceptLetter(tx, {
648
707
  id: this.letterId(),
649
708
  job: job.number,
650
709
  kind: 'answer',
@@ -876,7 +935,7 @@ export class BridgeDispatcher extends EventEmitter {
876
935
  */
877
936
  refuse(tx, request, reason) {
878
937
  const settled = this.markHandled(tx, request);
879
- const answer = this.accept(tx, {
938
+ const answer = this.acceptLetter(tx, {
880
939
  id: this.letterId(),
881
940
  job: request.job,
882
941
  kind: 'answer',
@@ -1213,6 +1272,495 @@ export class BridgeDispatcher extends EventEmitter {
1213
1272
  return this.requireJob(number).job;
1214
1273
  });
1215
1274
  }
1275
+ /**
1276
+ * Refuses a job that asks for a worktree of its own and cannot have one: the folder is in no
1277
+ * git repository, the session that would carry it out is open somewhere else already, or the
1278
+ * project has as many such jobs in progress as it may.
1279
+ */
1280
+ checkWorktreeAsked(from, resolution, cwd) {
1281
+ if (!inCheckout(cwd)) {
1282
+ throw new BridgeError('no_worktree', `A worktree is a checkout of a git repository, and ${cwd} is in none`, { cwd });
1283
+ }
1284
+ if (canonicalPath(findProjectRoot(cwd)) !== canonicalPath(from.project)) {
1285
+ throw new BridgeError('no_worktree', `${cwd} is in a repository of its own inside the project, such as a submodule, and the bridge makes worktrees of the project only`, { cwd });
1286
+ }
1287
+ if (resolution.kind === 'agent') {
1288
+ throw new BridgeError('no_worktree', `A job in a worktree of its own is done by a session started for it, and ${resolution.agent.name} is open somewhere else already. Hand the job to a harness and it gets a fresh session`, { agent: resolution.agent.name });
1289
+ }
1290
+ const isolated = this.store
1291
+ .jobTasks({ states: ACTIVE_JOB_STATES, project: from.project })
1292
+ .flatMap((task) => jobOf(task) ?? [])
1293
+ .filter((job) => job.isolation === 'worktree');
1294
+ if (isolated.length >= this.limits.worktreesPerProject) {
1295
+ throw new BridgeError('worktree_limit', `${isolated.length} jobs of this project are in progress in worktrees of their own (${isolated.map((job) => `#${job.number}`).join(', ')}), the most there may be: each builds and tests next to the others. Wait for one to report, or hand this job over without a worktree`, { jobs: isolated.map((job) => job.number) });
1296
+ }
1297
+ }
1298
+ /**
1299
+ * Where a session that is about to be started for a job works: the worktree of the job, made
1300
+ * now, when the job asked for one. Resolves with the job as it is once it has its worktree and
1301
+ * with its first letter, which says so, and with nothing for a job that works where it was
1302
+ * handed over.
1303
+ *
1304
+ * @throws when git cannot make the worktree: the job then fails with what git said
1305
+ */
1306
+ async placeOf(agentName, job, letterId) {
1307
+ if (job.isolation !== 'worktree' || job.worktree)
1308
+ return undefined;
1309
+ let made;
1310
+ try {
1311
+ made = await addJobWorktree({
1312
+ project: job.project,
1313
+ from: job.cwd,
1314
+ number: job.number,
1315
+ title: job.title,
1316
+ });
1317
+ }
1318
+ catch (error) {
1319
+ throw new Error(`the worktree of the job could not be made: ${asError(error).message}`, {
1320
+ cause: error,
1321
+ });
1322
+ }
1323
+ const record = async (tx) => {
1324
+ await this.patchRecord(job.taskId, {
1325
+ worktree: { path: made.path, branch: made.branch, base: made.base },
1326
+ cwd: made.cwd,
1327
+ });
1328
+ const agent = this.store.getAgent(agentName);
1329
+ if (agent)
1330
+ this.store.putAgent({ ...agent, cwd: made.cwd });
1331
+ this.journal(tx, {
1332
+ type: 'job.worktree',
1333
+ job: job.number,
1334
+ agent: agentName,
1335
+ data: { path: made.path, branch: made.branch, base: made.base },
1336
+ });
1337
+ const fresh = this.requireJob(job.number).job;
1338
+ const letter = this.store.getLetter(letterId);
1339
+ if (!letter)
1340
+ throw new BridgeError('storage', `The first letter of job ${job.number} is lost`);
1341
+ return { job: fresh, letter: renderLetter(letter, fresh) };
1342
+ };
1343
+ try {
1344
+ return await this.mutate(record);
1345
+ }
1346
+ catch (error) {
1347
+ await removeJobWorktree(job.project, made.path, made.branch).catch(() => undefined);
1348
+ throw error;
1349
+ }
1350
+ }
1351
+ /** The worktree of a job while its work is still in it. */
1352
+ liveWorktree(job) {
1353
+ return job.worktree && !job.worktree.end ? job.worktree : undefined;
1354
+ }
1355
+ /**
1356
+ * What a job changed in its worktree, counted as its report comes in, for the report to say.
1357
+ * Nothing for a job without a worktree, and nothing when git cannot tell: the report goes
1358
+ * through all the same.
1359
+ */
1360
+ async changesAtReport(number) {
1361
+ const job = await this.enqueue(async () => this.jobIfAny(number));
1362
+ const worktree = job && this.liveWorktree(job);
1363
+ if (!worktree)
1364
+ return undefined;
1365
+ try {
1366
+ return summaryOf(await changesOf(worktree.path, worktree.base), this.iso());
1367
+ }
1368
+ catch (error) {
1369
+ this.onError(asError(error));
1370
+ return undefined;
1371
+ }
1372
+ }
1373
+ startChecks(number) {
1374
+ if (this.checkRuns.has(number))
1375
+ return;
1376
+ const stop = new AbortController();
1377
+ this.checkRuns.set(number, stop);
1378
+ const run = this.checkQueue
1379
+ .then(() => this.runChecks(number, stop.signal))
1380
+ .finally(() => this.checkRuns.delete(number));
1381
+ this.checkQueue = run.catch(() => undefined);
1382
+ this.track(run);
1383
+ }
1384
+ /**
1385
+ * Runs the checks of a job that was reported on, where the job was done, and hands its report
1386
+ * over with what they showed. The bridge runs a command itself, outside any sandbox, so it
1387
+ * runs only what the rules of whoever handed the job over allow without asking: the rest is
1388
+ * left out, and the result then does not count as verified. A dispatcher that closes in the
1389
+ * middle leaves the job as it is, and the next one runs its checks again.
1390
+ */
1391
+ async runChecks(number, signal) {
1392
+ const job = await this.enqueue(async () => this.jobIfAny(number));
1393
+ if (!job?.checking)
1394
+ return;
1395
+ const places = [job.project, findCheckoutRoot(job.cwd), this.liveWorktree(job)?.path];
1396
+ const results = [];
1397
+ for (const check of job.checks) {
1398
+ try {
1399
+ const cwd = check.cwd ? canonicalPath(resolvePath(job.cwd, check.cwd)) : job.cwd;
1400
+ if (!places.some((place) => place !== undefined && isInside(place, cwd))) {
1401
+ results.push(skippedCheck(check, `it would run in ${cwd}, outside the project`));
1402
+ continue;
1403
+ }
1404
+ const rights = await this.rightsFor(number, {
1405
+ tool: 'Bash',
1406
+ access: 'command',
1407
+ command: check.command,
1408
+ cwd,
1409
+ });
1410
+ if (rights !== 'allow') {
1411
+ results.push(skippedCheck(check, !this.rights
1412
+ ? 'this bridge has no rules to judge a command by, and runs none without them'
1413
+ : rights === 'deny'
1414
+ ? `the rules of ${job.from} forbid the command`
1415
+ : `the rules of ${job.from} do not allow the command without asking. Allow it in the settings of the project, or run it yourself`));
1416
+ continue;
1417
+ }
1418
+ results.push(await runCheck(check, {
1419
+ cwd,
1420
+ timeoutMs: check.timeoutMs ?? this.limits.checkTimeoutMs,
1421
+ signal,
1422
+ }));
1423
+ }
1424
+ catch (error) {
1425
+ this.onError(asError(error));
1426
+ results.push(skippedCheck(check, `the bridge failed to run it: ${asError(error).message}`));
1427
+ }
1428
+ if (signal.aborted)
1429
+ return;
1430
+ }
1431
+ if (this.closing)
1432
+ return;
1433
+ const { verified, summary } = summarizeChecks(results);
1434
+ await this.mutate(async (tx) => {
1435
+ const { job: fresh } = this.requireJob(number);
1436
+ if (!fresh.checking)
1437
+ return;
1438
+ await this.patchRecord(fresh.taskId, {
1439
+ verification: { verified, checkedAt: this.iso(), summary, checks: results },
1440
+ checking: undefined,
1441
+ });
1442
+ this.journal(tx, { type: 'job.verified', job: number, data: { verified, summary } });
1443
+ const report = this.store.getLetter(fresh.checking.letter);
1444
+ if (report?.state === 'held') {
1445
+ this.store.updateLetter(report.id, { state: 'queued' });
1446
+ tx.wake.add(report.to);
1447
+ }
1448
+ });
1449
+ }
1450
+ /**
1451
+ * Picks up what a dispatcher before this one left in the middle: the checks of jobs that were
1452
+ * reported on and never got their verdict.
1453
+ */
1454
+ recover(tx) {
1455
+ if (this.recovered)
1456
+ return;
1457
+ this.recovered = true;
1458
+ for (const task of this.store.jobTasks({ states: ['completed'] })) {
1459
+ const job = jobOf(task);
1460
+ if (job?.checking)
1461
+ tx.checks.push(job.number);
1462
+ }
1463
+ }
1464
+ /**
1465
+ * What a job changed in its worktree so far: the files, how much, and the patch. For the two
1466
+ * agents of the job, while it runs and after, as long as its worktree is there.
1467
+ *
1468
+ * @throws BridgeError `unknown_job`, `not_a_party`, `no_worktree` for a job without a worktree
1469
+ * of its own or whose work was taken or dropped already
1470
+ */
1471
+ async diff(caller, input) {
1472
+ const request = parse(DiffInputSchema, input, 'Cannot show the changes');
1473
+ const { job, worktree } = await this.asCaller(caller, async () => {
1474
+ const agent = this.requireCaller(caller);
1475
+ const found = this.requireJob(request.job).job;
1476
+ if (agent.name !== found.from && agent.name !== found.to) {
1477
+ throw new BridgeError('not_a_party', `Job ${found.number} is between ${found.from} and ${found.to}`, { job: found.number });
1478
+ }
1479
+ return { job: found, worktree: this.requireWorktree(found) };
1480
+ });
1481
+ const changes = await this.readChanges(job, worktree);
1482
+ const { patch, truncated } = request.maxChars === 0
1483
+ ? { patch: '', truncated: changes.files.length > 0 }
1484
+ : await patchOf(worktree.path, worktree.base, changes.tree, {
1485
+ ...(request.paths && { paths: request.paths }),
1486
+ ...(request.maxChars !== undefined && { maxChars: request.maxChars }),
1487
+ });
1488
+ return {
1489
+ job: job.number,
1490
+ worktree: worktree.path,
1491
+ branch: worktree.branch,
1492
+ base: worktree.base,
1493
+ files: changes.files.map((file) => ({ ...file, path: shownPath(file.path) })),
1494
+ insertions: changes.insertions,
1495
+ deletions: changes.deletions,
1496
+ commits: changes.commits,
1497
+ patch,
1498
+ truncated,
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Takes the work of a finished job out of its worktree, as the agent that handed the job over.
1503
+ * The changes, committed there or not, come into the checkout the caller works in as one
1504
+ * change that is staged and not committed: the commit is the caller's to make. With
1505
+ * `asBranch` they are left as a branch instead, for work that goes on as a pull request. The
1506
+ * worktree is removed either way. When the changes would leave files in conflict nothing is
1507
+ * touched, the answer names the files, and the worktree stays for another try. The bridge
1508
+ * never merges into a branch nobody is working on.
1509
+ *
1510
+ * @throws BridgeError `unknown_job`, `not_a_party` (only who handed the job over takes its
1511
+ * work), `invalid_input` (the job still runs, its checks do, the caller is in another
1512
+ * repository, or git refused), `no_worktree`
1513
+ */
1514
+ async accept(caller, input) {
1515
+ const request = parse(AcceptInputSchema, input, 'Cannot take the work');
1516
+ const { job, worktree, agent } = await this.asCaller(caller, async () => this.requireTaker(caller, request.job, 'take'));
1517
+ return this.whileTaking(job.number, async () => {
1518
+ const changes = await this.readChanges(job, worktree);
1519
+ if (changes.files.length === 0 && changes.commits === 0) {
1520
+ await removeJobWorktree(job.project, worktree.path, worktree.branch);
1521
+ const ended = await this.endWorktree(job.number, { how: 'accepted' }, 'job.accepted', {});
1522
+ return { state: 'nothing', job: ended };
1523
+ }
1524
+ const commit = await snapshotOf(worktree.path, changes, `job #${job.number}: ${job.title}`);
1525
+ if (request.asBranch) {
1526
+ const branch = request.asBranch === true ? worktree.branch : request.asBranch;
1527
+ await this.leaveBranch(job, worktree, branch, commit);
1528
+ const ended = await this.endWorktree(job.number, { how: 'branch', commit, ref: branch }, 'job.accepted', { branch, commit });
1529
+ return { state: 'branch', job: ended, branch, commit };
1530
+ }
1531
+ const into = await checkoutOf(agent.cwd);
1532
+ if (!into || canonicalPath(findProjectRoot(into)) !== canonicalPath(job.project)) {
1533
+ throw new BridgeError('invalid_input', `The work of job ${job.number} belongs to ${job.project}, and you work in ${agent.cwd}, which is not a checkout of it. Take it as a branch instead`, { job: job.number, cwd: agent.cwd });
1534
+ }
1535
+ const conflicts = await this.oneAtATimeIn(into, async () => {
1536
+ const busy = await busyWith(into).catch((error) => {
1537
+ throw gitRefusal(error, `Git could not look at ${into}`);
1538
+ });
1539
+ if (busy) {
1540
+ throw new BridgeError('invalid_input', `Nothing can be brought into ${into} right now: ${busy}. Taking the work of a job stages it, so commit or stash what is there first, then take the work again`, { job: job.number, into });
1541
+ }
1542
+ const inConflict = await conflictsOf(into, commit).catch((error) => {
1543
+ throw gitRefusal(error, `Git could not tell whether job ${job.number} merges into ${into}`);
1544
+ });
1545
+ if (inConflict.length > 0)
1546
+ return inConflict;
1547
+ await squashInto(into, commit).catch((error) => {
1548
+ throw gitRefusal(error, `Git refused to bring the changes of job ${job.number} into ${into}, which is as it was. Commit or stash what is in the way there, then take the work again`);
1549
+ });
1550
+ return [];
1551
+ });
1552
+ if (conflicts.length > 0) {
1553
+ return { state: 'conflict', job, into, files: conflicts.map(shownPath) };
1554
+ }
1555
+ await removeJobWorktree(job.project, worktree.path, worktree.branch).catch((error) => this.onError(asError(error)));
1556
+ const ended = await this.endWorktree(job.number, { how: 'accepted', commit, into }, 'job.accepted', { into, commit, files: changes.files.length });
1557
+ return {
1558
+ state: 'accepted',
1559
+ job: ended,
1560
+ into,
1561
+ files: changes.files.length,
1562
+ insertions: changes.insertions,
1563
+ deletions: changes.deletions,
1564
+ };
1565
+ });
1566
+ }
1567
+ /**
1568
+ * Drops the work of a finished job, as the agent that handed the job over: its worktree and
1569
+ * the branch of it are removed with everything in them.
1570
+ *
1571
+ * @throws BridgeError `unknown_job`, `not_a_party`, `invalid_input` (the job still runs, or
1572
+ * its checks do), `no_worktree`
1573
+ */
1574
+ async reject(caller, input) {
1575
+ const request = parse(RejectInputSchema, input, 'Cannot drop the work');
1576
+ const { job, worktree } = await this.asCaller(caller, async () => this.requireTaker(caller, request.job, 'drop'));
1577
+ return this.whileTaking(job.number, async () => {
1578
+ await removeJobWorktree(job.project, worktree.path, worktree.branch);
1579
+ return this.endWorktree(job.number, { how: 'rejected' }, 'job.rejected', {
1580
+ ...(request.reason && { reason: request.reason }),
1581
+ });
1582
+ });
1583
+ }
1584
+ /**
1585
+ * Work on one checkout after the other work on it: looking whether it is free, merging into
1586
+ * it and taking a failed merge back are one step, and two jobs taken into the same checkout
1587
+ * at once would each undo what the other staged.
1588
+ */
1589
+ oneAtATimeIn(checkout, work) {
1590
+ const run = (this.checkouts.get(checkout) ?? Promise.resolve()).then(work, work);
1591
+ const settled = run
1592
+ .then(() => undefined, () => undefined)
1593
+ .finally(() => {
1594
+ if (this.checkouts.get(checkout) === settled)
1595
+ this.checkouts.delete(checkout);
1596
+ });
1597
+ this.checkouts.set(checkout, settled);
1598
+ return run;
1599
+ }
1600
+ /** The worktree of a job whose work is still in it, or why there is none. */
1601
+ requireWorktree(job) {
1602
+ const worktree = this.liveWorktree(job);
1603
+ if (worktree)
1604
+ return worktree;
1605
+ const end = job.worktree?.end;
1606
+ throw new BridgeError('no_worktree', end
1607
+ ? `The work of job ${job.number} was ${ENDED[end.how]}${end.ref ? ` (${end.ref})` : ''}${end.into ? ` into ${end.into}` : ''}, and its worktree is gone`
1608
+ : job.isolation === 'worktree'
1609
+ ? `Job ${job.number} has no worktree yet: its session has not started`
1610
+ : `Job ${job.number} was done in ${job.cwd}, not in a worktree of its own: what it changed is there`, { job: job.number });
1611
+ }
1612
+ /** The job, its worktree and the caller, for the one who may take or drop its work. */
1613
+ requireTaker(caller, number, what) {
1614
+ const agent = this.requireCaller(caller);
1615
+ const { job } = this.requireJob(number);
1616
+ if (agent.name !== job.from) {
1617
+ throw new BridgeError('not_a_party', `Only ${job.from}, who handed job ${job.number} over, can ${what} its work`, { job: job.number });
1618
+ }
1619
+ if (!isFinishedJobState(job.state)) {
1620
+ throw new BridgeError('invalid_input', `Job ${job.number} is still ${job.state}. Wait for its report, or cancel it first`, { job: job.number, state: job.state });
1621
+ }
1622
+ if (job.checking) {
1623
+ throw new BridgeError('invalid_input', `The checks of job ${job.number} still run. Its report comes with what they show`, { job: job.number });
1624
+ }
1625
+ return { job, worktree: this.requireWorktree(job), agent };
1626
+ }
1627
+ /** One taking, dropping or putting away of a job's worktree at a time. */
1628
+ async whileTaking(number, work) {
1629
+ if (this.taking.has(number)) {
1630
+ throw new BridgeError('invalid_input', `The work of job ${number} is being taken or dropped right now`, { job: number });
1631
+ }
1632
+ this.taking.add(number);
1633
+ try {
1634
+ return await work();
1635
+ }
1636
+ finally {
1637
+ this.taking.delete(number);
1638
+ }
1639
+ }
1640
+ async readChanges(job, worktree) {
1641
+ try {
1642
+ return await changesOf(worktree.path, worktree.base);
1643
+ }
1644
+ catch (error) {
1645
+ throw gitRefusal(error, `Git could not read the worktree of job ${job.number}, ${worktree.path}`);
1646
+ }
1647
+ }
1648
+ /**
1649
+ * Leaves the work of a worktree as the branch `branch`, at `commit`, and removes the worktree.
1650
+ * The branch is set first: whatever goes wrong after that, the work is on it.
1651
+ */
1652
+ async leaveBranch(job, worktree, branch, commit) {
1653
+ try {
1654
+ const own = branch === worktree.branch;
1655
+ await pointRef(job.project, `refs/heads/${branch}`, commit, { fresh: !own });
1656
+ await removeJobWorktree(job.project, worktree.path, own ? undefined : worktree.branch);
1657
+ }
1658
+ catch (error) {
1659
+ throw gitRefusal(error, `Git could not leave the work of job ${job.number} as ${branch}`);
1660
+ }
1661
+ }
1662
+ /** Records how the work in a job's worktree ended. */
1663
+ async endWorktree(number, end, type, data) {
1664
+ return this.mutate(async (tx) => {
1665
+ const { job } = this.requireJob(number);
1666
+ if (job.worktree) {
1667
+ await this.patchRecord(job.taskId, {
1668
+ worktree: { ...job.worktree, end: { ...end, at: this.iso() } },
1669
+ });
1670
+ this.retireFrom(tx, job, job.worktree.path);
1671
+ }
1672
+ this.journal(tx, { type, job: number, data: { how: end.how, ...data } });
1673
+ return this.requireJob(number).job;
1674
+ });
1675
+ }
1676
+ /**
1677
+ * Takes the session that was started in a worktree for gone once the worktree is: the folder
1678
+ * it works in is not there any more, so it is no session to hand another job to.
1679
+ */
1680
+ retireFrom(tx, job, worktree) {
1681
+ const agent = this.store.getAgent(job.to);
1682
+ if (!agent || agent.status === 'gone' || !isInside(worktree, agent.cwd))
1683
+ return;
1684
+ this.store.putAgent({ ...agent, status: 'gone' });
1685
+ this.journal(tx, {
1686
+ type: 'agent.gone',
1687
+ agent: agent.name,
1688
+ data: { error: `the worktree of job #${job.number}, where it worked, was removed` },
1689
+ });
1690
+ }
1691
+ /**
1692
+ * Puts away the worktrees nobody came for: those of jobs that finished longer ago than
1693
+ * `limits.worktreeKeepMs`. What such a worktree holds is kept as a commit under a ref of its
1694
+ * own, the worktree and its branch are removed, and whoever handed the job over is told
1695
+ * where the work is. Looked at once an hour.
1696
+ */
1697
+ sweepWorktrees(now) {
1698
+ if (now - this.worktreesSweptAt < WORKTREE_SWEEP_MS)
1699
+ return;
1700
+ this.worktreesSweptAt = now;
1701
+ const left = this.store
1702
+ .jobTasks({ states: FINISHED_JOB_STATES })
1703
+ .flatMap((task) => jobOf(task) ?? [])
1704
+ .filter((job) => this.liveWorktree(job) !== undefined &&
1705
+ !job.checking &&
1706
+ now - Date.parse(job.endedAt ?? job.updatedAt) >= this.limits.worktreeKeepMs);
1707
+ for (const job of left) {
1708
+ if (this.taking.has(job.number))
1709
+ continue;
1710
+ this.track(this.whileTaking(job.number, () => this.putAway(job)));
1711
+ }
1712
+ }
1713
+ /**
1714
+ * Puts the worktree of a job away. Nothing is removed before its work is kept: when git
1715
+ * cannot read the worktree because its folder is gone, the commits on its branch are kept,
1716
+ * and when it cannot for another reason, the worktree stays and the next look tries again.
1717
+ */
1718
+ async putAway(job) {
1719
+ const worktree = this.liveWorktree(job);
1720
+ if (!worktree)
1721
+ return;
1722
+ const ref = `${DISCARDED_REFS}/job-${job.number}`;
1723
+ let kept;
1724
+ try {
1725
+ if (existsSync(worktree.path)) {
1726
+ const changes = await changesOf(worktree.path, worktree.base);
1727
+ if (changes.files.length > 0 || changes.commits > 0) {
1728
+ const commit = await snapshotOf(worktree.path, changes, `job #${job.number}: ${job.title}`);
1729
+ await pointRef(job.project, ref, commit);
1730
+ kept = { commit, ref };
1731
+ }
1732
+ }
1733
+ else {
1734
+ const tip = await branchTip(job.project, worktree.branch);
1735
+ if (tip && tip !== worktree.base) {
1736
+ await pointRef(job.project, ref, tip);
1737
+ kept = { commit: tip, ref };
1738
+ }
1739
+ }
1740
+ await removeJobWorktree(job.project, worktree.path, worktree.branch);
1741
+ }
1742
+ catch (error) {
1743
+ this.onError(new Error(`The worktree of job ${job.number}, ${worktree.path}, could not be put away and stays: ${asError(error).message}`, { cause: error }));
1744
+ return;
1745
+ }
1746
+ await this.mutate(async (tx) => {
1747
+ const { job: fresh } = this.requireJob(job.number);
1748
+ if (!fresh.worktree)
1749
+ return;
1750
+ await this.patchRecord(fresh.taskId, {
1751
+ worktree: { ...fresh.worktree, end: { how: 'discarded', at: this.iso(), ...kept } },
1752
+ });
1753
+ this.retireFrom(tx, fresh, fresh.worktree.path);
1754
+ this.journal(tx, {
1755
+ type: 'job.discarded',
1756
+ job: job.number,
1757
+ data: { how: 'discarded', ...kept },
1758
+ });
1759
+ if (kept) {
1760
+ this.systemNote(tx, fresh, fresh.from, `Nobody took or dropped the work of job #${job.number} for ${formatDuration(this.limits.worktreeKeepMs)}, so its worktree was removed. What it held is kept as commit ${kept.commit.slice(0, 10)} under ${kept.ref}: look at it with git show ${kept.ref}.`);
1761
+ }
1762
+ });
1763
+ }
1216
1764
  /** @throws BridgeError `unknown_job` */
1217
1765
  async job(number) {
1218
1766
  return this.enqueue(async () => this.requireJob(number).job);
@@ -1273,6 +1821,8 @@ export class BridgeDispatcher extends EventEmitter {
1273
1821
  const now = this.now();
1274
1822
  const failed = [];
1275
1823
  const reminded = [];
1824
+ this.recover(tx);
1825
+ this.sweepWorktrees(now);
1276
1826
  const overdue = this.store
1277
1827
  .jobTasks({ states: ACTIVE_JOB_STATES, deadlineBy: now })
1278
1828
  .flatMap((task) => jobOf(task) ?? [])
@@ -1471,6 +2021,8 @@ export class BridgeDispatcher extends EventEmitter {
1471
2021
  */
1472
2022
  async close() {
1473
2023
  this.closing = true;
2024
+ for (const run of this.checkRuns.values())
2025
+ run.abort();
1474
2026
  for (const waiter of [...this.waiters.values()])
1475
2027
  waiter.end('closed');
1476
2028
  for (const letter of [...this.verdictWaiters.keys()])
@@ -1523,6 +2075,7 @@ export class BridgeDispatcher extends EventEmitter {
1523
2075
  settled: [],
1524
2076
  decided: new Set(),
1525
2077
  notices: [],
2078
+ checks: [],
1526
2079
  };
1527
2080
  const result = await this.store.transaction(() => {
1528
2081
  this.assertWritable?.();
@@ -1544,6 +2097,9 @@ export class BridgeDispatcher extends EventEmitter {
1544
2097
  this.wake(agent);
1545
2098
  for (const letter of tx.decided)
1546
2099
  this.announce(letter);
2100
+ if (!this.closing)
2101
+ for (const number of tx.checks)
2102
+ this.startChecks(number);
1547
2103
  this.tellPerson(tx);
1548
2104
  return result;
1549
2105
  }
@@ -1670,6 +2226,8 @@ export class BridgeDispatcher extends EventEmitter {
1670
2226
  }
1671
2227
  if (job.state !== to) {
1672
2228
  this.journal(tx, { type: 'job.state', job: number, data: { from: job.state, to } });
2229
+ if (isFinishedJobState(to))
2230
+ await this.patchRecord(job.taskId, { endedAt: this.iso() });
1673
2231
  }
1674
2232
  }
1675
2233
  async pickUp(tx, job) {
@@ -1770,7 +2328,7 @@ export class BridgeDispatcher extends EventEmitter {
1770
2328
  }
1771
2329
  }
1772
2330
  }
1773
- accept(tx, fields) {
2331
+ acceptLetter(tx, fields) {
1774
2332
  const letter = this.store.insertLetter({
1775
2333
  ...fields,
1776
2334
  state: 'queued',
@@ -1799,7 +2357,7 @@ export class BridgeDispatcher extends EventEmitter {
1799
2357
  }
1800
2358
  /** A letter the bridge writes itself. It costs the job nothing and is never held back as a repeat. */
1801
2359
  systemNote(tx, job, to, body) {
1802
- return this.accept(tx, {
2360
+ return this.acceptLetter(tx, {
1803
2361
  id: this.letterId(),
1804
2362
  job: job.number,
1805
2363
  kind: 'note',
@@ -2047,14 +2605,15 @@ export class BridgeDispatcher extends EventEmitter {
2047
2605
  return;
2048
2606
  let created;
2049
2607
  try {
2608
+ const place = await this.placeOf(agentName, request.job, letterId);
2050
2609
  created = await within(adapter.createSession({
2051
2610
  agentName,
2052
2611
  harness: request.agent.harness,
2053
2612
  project: request.agent.project,
2054
- cwd: request.agent.cwd,
2613
+ cwd: place?.job.cwd ?? request.agent.cwd,
2055
2614
  ...(request.agent.sessionName && { sessionName: request.agent.sessionName }),
2056
- job: request.job,
2057
- firstLetter: request.letter,
2615
+ job: place?.job ?? request.job,
2616
+ firstLetter: place?.letter ?? request.letter,
2058
2617
  }), this.limits.sessionStartTimeoutMs, `Starting a ${request.agent.harness} session`);
2059
2618
  if (!created.sessionId.trim())
2060
2619
  throw new Error('the adapter returned no session id');