@cogitator-ai/bridge 0.6.1 → 0.8.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 (84) hide show
  1. package/README.md +102 -19
  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/board.d.ts +76 -0
  7. package/dist/board.d.ts.map +1 -0
  8. package/dist/board.js +19 -0
  9. package/dist/board.js.map +1 -0
  10. package/dist/checks.d.ts +31 -0
  11. package/dist/checks.d.ts.map +1 -0
  12. package/dist/checks.js +202 -0
  13. package/dist/checks.js.map +1 -0
  14. package/dist/client.d.ts +17 -1
  15. package/dist/client.d.ts.map +1 -1
  16. package/dist/client.js +29 -0
  17. package/dist/client.js.map +1 -1
  18. package/dist/dispatcher.d.ts +187 -2
  19. package/dist/dispatcher.d.ts.map +1 -1
  20. package/dist/dispatcher.js +930 -18
  21. package/dist/dispatcher.js.map +1 -1
  22. package/dist/errors.d.ts +1 -1
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/errors.js.map +1 -1
  25. package/dist/handover.d.ts +72 -0
  26. package/dist/handover.d.ts.map +1 -0
  27. package/dist/handover.js +225 -0
  28. package/dist/handover.js.map +1 -0
  29. package/dist/host.d.ts +7 -0
  30. package/dist/host.d.ts.map +1 -1
  31. package/dist/host.js +1 -0
  32. package/dist/host.js.map +1 -1
  33. package/dist/index.d.ts +5 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +3 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/inputs.d.ts +166 -0
  38. package/dist/inputs.d.ts.map +1 -1
  39. package/dist/inputs.js +65 -0
  40. package/dist/inputs.js.map +1 -1
  41. package/dist/job-record.d.ts +42 -1
  42. package/dist/job-record.d.ts.map +1 -1
  43. package/dist/job-record.js +39 -1
  44. package/dist/job-record.js.map +1 -1
  45. package/dist/letters.d.ts +3 -1
  46. package/dist/letters.d.ts.map +1 -1
  47. package/dist/letters.js +38 -5
  48. package/dist/letters.js.map +1 -1
  49. package/dist/memory/index.d.ts +35 -0
  50. package/dist/memory/index.d.ts.map +1 -0
  51. package/dist/memory/index.js +192 -0
  52. package/dist/memory/index.js.map +1 -0
  53. package/dist/paths.d.ts +7 -0
  54. package/dist/paths.d.ts.map +1 -1
  55. package/dist/paths.js +9 -0
  56. package/dist/paths.js.map +1 -1
  57. package/dist/protocol.d.ts +6 -0
  58. package/dist/protocol.d.ts.map +1 -1
  59. package/dist/protocol.js +6 -0
  60. package/dist/protocol.js.map +1 -1
  61. package/dist/registry.d.ts +7 -2
  62. package/dist/registry.d.ts.map +1 -1
  63. package/dist/registry.js +8 -5
  64. package/dist/registry.js.map +1 -1
  65. package/dist/server.d.ts.map +1 -1
  66. package/dist/server.js +6 -0
  67. package/dist/server.js.map +1 -1
  68. package/dist/tools/guidance.d.ts.map +1 -1
  69. package/dist/tools/guidance.js +4 -0
  70. package/dist/tools/guidance.js.map +1 -1
  71. package/dist/tools/tools.d.ts.map +1 -1
  72. package/dist/tools/tools.js +292 -2
  73. package/dist/tools/tools.js.map +1 -1
  74. package/dist/types.d.ts +105 -5
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js +27 -2
  77. package/dist/types.js.map +1 -1
  78. package/dist/worktree.d.ts +131 -0
  79. package/dist/worktree.d.ts.map +1 -0
  80. package/dist/worktree.js +278 -0
  81. package/dist/worktree.js.map +1 -0
  82. package/fakes/claude.mjs +53 -3
  83. package/fakes/lib.mjs +24 -9
  84. package/package.json +11 -1
@@ -1,15 +1,100 @@
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 { MAX_RECALL_LIMIT } from './board.js';
6
+ import { runCheck, skippedCheck, summarizeChecks } from './checks.js';
4
7
  import { BridgeError } from './errors.js';
5
8
  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';
9
+ 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, ForgetInputSchema, RecallInputSchema, RejectInputSchema, RememberInputSchema, WaitInputSchema, WithdrawInputSchema, } from './inputs.js';
10
+ import { HANDOVER_GAP, buildHandover } from './handover.js';
7
11
  import { isFinishedJobState, jobOf, jobRecordOf } from './job-record.js';
8
12
  import { expectationOf, forHistory, newLetterId, normalizeBody, oneLine, quoted, renderLetter, repeats, titleOf, } from './letters.js';
9
- import { canonicalPath, findCheckoutRoot, findProjectRoot, isInside } from './paths.js';
13
+ import { canonicalPath, findCheckoutRoot, findProjectRoot, inCheckout, isInside } from './paths.js';
14
+ import { DISCARDED_REFS, GitError, addJobWorktree, branchTip, busyWith, changesOf, checkoutOf, conflictsOf, patchOf, pointRef, removeJobWorktree, shownPath, snapshotOf, squashInto, } from './worktree.js';
10
15
  import { allocateAgentName, resolveAddress } from './registry.js';
11
16
  import { BRIDGE_JOB_KEY, BRIDGE_SENDER, CallerIdentitySchema, DEFAULT_LIMITS, HarnessNameSchema, INBOX_DELIVERY, NO_CAPABILITIES, PERSON, } from './types.js';
12
17
  const ACTIVE_JOB_STATES = ['submitted', 'working', 'input-required'];
18
+ const FINISHED_JOB_STATES = ['completed', 'failed', 'canceled'];
19
+ /** How often the worktrees of finished jobs are looked at for those nobody came for, in ms. */
20
+ const WORKTREE_SWEEP_MS = 3_600_000;
21
+ /** How many changed files the record of a job names. */
22
+ const PATHS_KEPT = 50;
23
+ const ENDED = {
24
+ accepted: 'taken',
25
+ branch: 'left as a branch',
26
+ rejected: 'dropped',
27
+ discarded: 'put away',
28
+ };
29
+ /** What a job changed, as its record keeps it. */
30
+ function summaryOf(changes, at) {
31
+ return {
32
+ files: changes.files.length,
33
+ insertions: changes.insertions,
34
+ deletions: changes.deletions,
35
+ commits: changes.commits,
36
+ paths: changes.files.slice(0, PATHS_KEPT).map((file) => shownPath(file.path)),
37
+ at,
38
+ };
39
+ }
40
+ /** The folder a job is done in: the caller's, or the one it names from there. */
41
+ function jobFolder(from, named) {
42
+ if (!named)
43
+ return from.cwd;
44
+ return canonicalPath(isAbsolute(named) ? named : resolvePath(from.cwd, named));
45
+ }
46
+ /** How much of a job's text the board is asked about. */
47
+ const ABOUT_CHARS = 4_000;
48
+ /** How many notes of earlier jobs the handover of a job looks at. */
49
+ const EARLIER_NOTES = 6;
50
+ /**
51
+ * What earlier jobs like this one left on the board: the lessons and outcomes that fit its
52
+ * text, and the other lessons of the jobs those belong to, since a job is found by what it was
53
+ * about and its lessons are worded as they are. Lessons come before outcomes.
54
+ */
55
+ async function earlierLike(board, project, about) {
56
+ const fitting = await board.recall({
57
+ project,
58
+ text: about,
59
+ kinds: ['lesson', 'outcome'],
60
+ limit: EARLIER_NOTES,
61
+ });
62
+ const jobs = new Set(fitting.flatMap((note) => note.source.job ?? []));
63
+ const lessons = jobs.size === 0
64
+ ? []
65
+ : (await board.recall({ project, kinds: ['lesson'], limit: MAX_RECALL_LIMIT })).filter((note) => note.source.job !== undefined && jobs.has(note.source.job));
66
+ const seen = new Set();
67
+ return [...lessons, ...fitting]
68
+ .filter((note) => !seen.has(note.id) && seen.add(note.id))
69
+ .sort((a, b) => Number(a.kind === 'outcome') - Number(b.kind === 'outcome'))
70
+ .slice(0, EARLIER_NOTES);
71
+ }
72
+ /** How much of a report the note of a job's outcome repeats. */
73
+ const REPORT_NOTED = 300;
74
+ /** How a job ended, in one line for the board. */
75
+ function outcomeText(job, reported) {
76
+ const checked = job.verification
77
+ ? job.verification.verified
78
+ ? ', and its checks confirmed the result'
79
+ : ', but its checks did not confirm the result'
80
+ : '';
81
+ const how = job.state === 'completed'
82
+ ? `completed${checked}`
83
+ : `${job.state}${job.reason ? ` (${oneLine(job.reason)})` : ''}`;
84
+ const quote = (text) => oneLine(text).replaceAll('"', "'");
85
+ const said = reported ? quote(reported) : '';
86
+ const report = said
87
+ ? ` Its report began: "${said.length > REPORT_NOTED ? `${said.slice(0, REPORT_NOTED)}...` : said}"`
88
+ : '';
89
+ return `Job #${job.number} "${quote(job.title)}", done by ${job.to} for ${job.from}: ${how}.${report}`;
90
+ }
91
+ /** What git said when it refused, as an error an agent can act on. */
92
+ function gitRefusal(error, what) {
93
+ if (error instanceof BridgeError)
94
+ return error;
95
+ const said = error instanceof GitError ? error.said : asError(error).message;
96
+ return new BridgeError('invalid_input', `${what}: ${oneLine(said)}`);
97
+ }
13
98
  const UNREAD_STATES = ['queued', 'delivered'];
14
99
  const NEEDS_ANSWER = ['question', 'permission'];
15
100
  const REMINDER_QUOTE_LENGTH = 500;
@@ -41,6 +126,7 @@ function fitting(items, sizeOf, budget = MAX_ANSWER_CHARS, orNone = false) {
41
126
  return taken;
42
127
  }
43
128
  const STATE_RANK = {
129
+ held: -1,
44
130
  queued: 0,
45
131
  delivered: 1,
46
132
  read: 2,
@@ -112,12 +198,24 @@ export class BridgeDispatcher extends EventEmitter {
112
198
  assertWritable;
113
199
  rights;
114
200
  person;
201
+ board;
115
202
  /** When each agent's other parties were last told it waits at its window, see `stuck` */
116
203
  stuckTold = new Map();
117
204
  /** Those waiting for the verdict of a permission request, by its id, see `verdict` */
118
205
  verdictWaiters = new Map();
119
206
  /** What the person route is told, one thing after another */
120
207
  personNews = Promise.resolve();
208
+ /** The checks that run or wait their turn, by job, each with what stops it */
209
+ checkRuns = new Map();
210
+ /** The checks of one job after those of another: they build and test, and memory is short */
211
+ checkQueue = Promise.resolve();
212
+ /** The last work on each checkout something is being brought into, see `oneAtATimeIn` */
213
+ checkouts = new Map();
214
+ /** Jobs whose worktree is being taken, dropped or put away right now */
215
+ taking = new Set();
216
+ /** Whether what a dispatcher before this one left unfinished was picked up */
217
+ recovered = false;
218
+ worktreesSweptAt = Number.NEGATIVE_INFINITY;
121
219
  queue = Promise.resolve();
122
220
  deliveries = new Map();
123
221
  background = new Set();
@@ -152,6 +250,7 @@ export class BridgeDispatcher extends EventEmitter {
152
250
  this.assertWritable = options.assertWritable;
153
251
  this.rights = options.rights;
154
252
  this.person = options.person;
253
+ this.board = options.board;
155
254
  for (const adapter of options.adapters ?? []) {
156
255
  const harness = parse(HarnessNameSchema, adapter.harness, 'Cannot use the adapter');
157
256
  if (this.adapters.has(harness)) {
@@ -256,12 +355,17 @@ export class BridgeDispatcher extends EventEmitter {
256
355
  async createJob(caller, input) {
257
356
  const request = parse(CreateJobInputSchema, input, 'Cannot create the job');
258
357
  this.checkBody(request.body);
358
+ const handover = await this.handoverFor(caller, request);
359
+ const withContext = handover ? `${request.body}${HANDOVER_GAP}${handover}` : request.body;
360
+ const body = withContext.length <= this.limits.maxBodyLength ? withContext : request.body;
259
361
  const outcome = await this.asCaller(caller, async (tx) => {
260
362
  const from = this.requireCaller(caller);
261
363
  if (request.letterId) {
262
364
  const sent = this.store.getLetter(request.letterId);
263
365
  if (sent) {
264
- if (sent.kind !== 'task' || sent.from !== from.name || sent.body !== request.body) {
366
+ if (sent.kind !== 'task' ||
367
+ sent.from !== from.name ||
368
+ this.taskText(sent) !== request.body) {
265
369
  throw new BridgeError('invalid_letter', `The letter id ${request.letterId} belongs to another letter. Give a new job a new id`, { letter: request.letterId });
266
370
  }
267
371
  return { job: this.requireJob(sent.job).job, letter: sent, duplicate: true };
@@ -272,6 +376,7 @@ export class BridgeDispatcher extends EventEmitter {
272
376
  caller: from.name,
273
377
  now: this.now(),
274
378
  canSpawn: (harness) => this.adapters.get(harness)?.createSession !== undefined,
379
+ fresh: request.worktree === true,
275
380
  });
276
381
  const carriedOut = this.store
277
382
  .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
@@ -305,12 +410,12 @@ export class BridgeDispatcher extends EventEmitter {
305
410
  return new Refusal(error);
306
411
  }
307
412
  const budget = resolveBudget(request.budget, this.limits);
308
- const cwd = request.cwd
309
- ? canonicalPath(isAbsolute(request.cwd) ? request.cwd : resolvePath(from.cwd, request.cwd))
310
- : from.cwd;
413
+ const cwd = jobFolder(from, request.cwd);
311
414
  if (!isInside(from.project, cwd) && !isInside(findCheckoutRoot(from.cwd), cwd)) {
312
415
  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
416
  }
417
+ if (request.worktree)
418
+ this.checkWorktreeAsked(from, resolution, cwd);
314
419
  const now = this.now();
315
420
  const refusal = this.handOverRefusal(from, resolution, request.body, cwd, now);
316
421
  if (refusal) {
@@ -354,6 +459,8 @@ export class BridgeDispatcher extends EventEmitter {
354
459
  to: to.name,
355
460
  project: from.project,
356
461
  cwd,
462
+ ...(body !== request.body && { taskLength: request.body.length }),
463
+ ...(request.worktree && { isolation: 'worktree' }),
357
464
  checks: request.checks ?? [],
358
465
  budget,
359
466
  lettersUsed: 1,
@@ -363,7 +470,7 @@ export class BridgeDispatcher extends EventEmitter {
363
470
  deadlineAt: this.iso(Math.min(now + budget.durationMs, parent ? Date.parse(parent.deadlineAt) : Infinity)),
364
471
  };
365
472
  const firstLetterId = request.letterId ?? this.letterId();
366
- const history = userMessage(forHistory(request.body, firstLetterId));
473
+ const history = userMessage(forHistory(body, firstLetterId));
367
474
  const task = await this.tasks.createTask(history, undefined, {
368
475
  agentName: to.name,
369
476
  metadata: { [BRIDGE_JOB_KEY]: record },
@@ -374,13 +481,13 @@ export class BridgeDispatcher extends EventEmitter {
374
481
  agent: from.name,
375
482
  data: { title: record.title, from: from.name, to: to.name, depth, cwd },
376
483
  });
377
- const letter = this.accept(tx, {
484
+ const letter = this.acceptLetter(tx, {
378
485
  id: firstLetterId,
379
486
  job: number,
380
487
  kind: 'task',
381
488
  from: from.name,
382
489
  to: to.name,
383
- body: request.body,
490
+ body,
384
491
  replyDueAt: this.iso(now + budget.replyTimeoutMs),
385
492
  });
386
493
  if (resolution.kind === 'spawn') {
@@ -411,6 +518,7 @@ export class BridgeDispatcher extends EventEmitter {
411
518
  const request = parse(SendLetterInputSchema, input, 'Cannot send the letter');
412
519
  this.checkBody(request.body);
413
520
  const rights = request.ask ? await this.rightsFor(request.job, request.ask) : undefined;
521
+ const changes = request.kind === 'report' ? await this.changesAtReport(request.job) : undefined;
414
522
  const outcome = await this.asCaller(caller, async (tx) => {
415
523
  const from = this.requireCaller(caller);
416
524
  if (request.id) {
@@ -507,7 +615,7 @@ export class BridgeDispatcher extends EventEmitter {
507
615
  : rights === 'ask' && !forPerson
508
616
  ? 'Only the person can allow this, and this bridge has no way to reach them, so it is refused'
509
617
  : undefined;
510
- const letter = this.accept(tx, {
618
+ const letter = this.acceptLetter(tx, {
511
619
  id: request.id ?? this.letterId(),
512
620
  job: job.number,
513
621
  kind: request.kind,
@@ -545,9 +653,32 @@ export class BridgeDispatcher extends EventEmitter {
545
653
  await this.transition(tx, job.number, state, forHistory(request.body, letter.id));
546
654
  if (state === 'failed')
547
655
  await this.patchRecord(job.taskId, { reason: `reported as failed by ${from.name}` });
656
+ if (changes && job.worktree && !job.worktree.end) {
657
+ await this.patchRecord(job.taskId, { changes });
658
+ }
659
+ if (state === 'completed' && job.checks.length > 0) {
660
+ this.store.updateLetter(letter.id, { state: 'held' });
661
+ await this.patchRecord(job.taskId, {
662
+ checking: { letter: letter.id, since: this.iso(now) },
663
+ });
664
+ tx.checks.push(job.number);
665
+ }
548
666
  this.closeLetters(tx, job.number, letter.id);
549
667
  await this.stopWaiting(job.number, now, false);
550
668
  await this.cancelChildren(tx, job);
669
+ if (this.board) {
670
+ for (const lesson of request.lessons ?? []) {
671
+ tx.notes.push({
672
+ kind: 'lesson',
673
+ text: lesson,
674
+ project: job.project,
675
+ source: { by: from.name, job: job.number, at: this.iso(now) },
676
+ });
677
+ }
678
+ if (!(state === 'completed' && job.checks.length > 0)) {
679
+ this.noteOutcome(tx, job.number, request.body);
680
+ }
681
+ }
551
682
  }
552
683
  else if (isAssignee && NEEDS_ANSWER.includes(request.kind)) {
553
684
  await this.transition(tx, job.number, 'input-required', forHistory(request.body, letter.id));
@@ -644,7 +775,7 @@ export class BridgeDispatcher extends EventEmitter {
644
775
  }
645
776
  const body = request.body ??
646
777
  (request.verdict === 'allow' ? 'Allowed by the person' : 'Refused by the person');
647
- const letter = this.accept(tx, {
778
+ const letter = this.acceptLetter(tx, {
648
779
  id: this.letterId(),
649
780
  job: job.number,
650
781
  kind: 'answer',
@@ -876,7 +1007,7 @@ export class BridgeDispatcher extends EventEmitter {
876
1007
  */
877
1008
  refuse(tx, request, reason) {
878
1009
  const settled = this.markHandled(tx, request);
879
- const answer = this.accept(tx, {
1010
+ const answer = this.acceptLetter(tx, {
880
1011
  id: this.letterId(),
881
1012
  job: request.job,
882
1013
  kind: 'answer',
@@ -1213,6 +1344,772 @@ export class BridgeDispatcher extends EventEmitter {
1213
1344
  return this.requireJob(number).job;
1214
1345
  });
1215
1346
  }
1347
+ /**
1348
+ * Refuses a job that asks for a worktree of its own and cannot have one: the folder is in no
1349
+ * git repository, the session that would carry it out is open somewhere else already, or the
1350
+ * project has as many such jobs in progress as it may.
1351
+ */
1352
+ checkWorktreeAsked(from, resolution, cwd) {
1353
+ if (!inCheckout(cwd)) {
1354
+ throw new BridgeError('no_worktree', `A worktree is a checkout of a git repository, and ${cwd} is in none`, { cwd });
1355
+ }
1356
+ if (canonicalPath(findProjectRoot(cwd)) !== canonicalPath(from.project)) {
1357
+ 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 });
1358
+ }
1359
+ if (resolution.kind === 'agent') {
1360
+ 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 });
1361
+ }
1362
+ const isolated = this.store
1363
+ .jobTasks({ states: ACTIVE_JOB_STATES, project: from.project })
1364
+ .flatMap((task) => jobOf(task) ?? [])
1365
+ .filter((job) => job.isolation === 'worktree');
1366
+ if (isolated.length >= this.limits.worktreesPerProject) {
1367
+ 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) });
1368
+ }
1369
+ }
1370
+ /**
1371
+ * Where a session that is about to be started for a job works: the worktree of the job, made
1372
+ * now, when the job asked for one. Resolves with the job as it is once it has its worktree and
1373
+ * with its first letter, which says so, and with nothing for a job that works where it was
1374
+ * handed over.
1375
+ *
1376
+ * @throws when git cannot make the worktree: the job then fails with what git said
1377
+ */
1378
+ async placeOf(agentName, job, letterId) {
1379
+ if (job.isolation !== 'worktree' || job.worktree)
1380
+ return undefined;
1381
+ let made;
1382
+ try {
1383
+ made = await addJobWorktree({
1384
+ project: job.project,
1385
+ from: job.cwd,
1386
+ number: job.number,
1387
+ title: job.title,
1388
+ });
1389
+ }
1390
+ catch (error) {
1391
+ throw new Error(`the worktree of the job could not be made: ${asError(error).message}`, {
1392
+ cause: error,
1393
+ });
1394
+ }
1395
+ const record = async (tx) => {
1396
+ await this.patchRecord(job.taskId, {
1397
+ worktree: { path: made.path, branch: made.branch, base: made.base },
1398
+ cwd: made.cwd,
1399
+ });
1400
+ const agent = this.store.getAgent(agentName);
1401
+ if (agent)
1402
+ this.store.putAgent({ ...agent, cwd: made.cwd });
1403
+ this.journal(tx, {
1404
+ type: 'job.worktree',
1405
+ job: job.number,
1406
+ agent: agentName,
1407
+ data: { path: made.path, branch: made.branch, base: made.base },
1408
+ });
1409
+ const fresh = this.requireJob(job.number).job;
1410
+ const letter = this.store.getLetter(letterId);
1411
+ if (!letter)
1412
+ throw new BridgeError('storage', `The first letter of job ${job.number} is lost`);
1413
+ return { job: fresh, letter: renderLetter(letter, fresh) };
1414
+ };
1415
+ try {
1416
+ return await this.mutate(record);
1417
+ }
1418
+ catch (error) {
1419
+ await removeJobWorktree(job.project, made.path, made.branch).catch(() => undefined);
1420
+ throw error;
1421
+ }
1422
+ }
1423
+ /** The worktree of a job while its work is still in it. */
1424
+ liveWorktree(job) {
1425
+ return job.worktree && !job.worktree.end ? job.worktree : undefined;
1426
+ }
1427
+ /**
1428
+ * What a job changed in its worktree, counted as its report comes in, for the report to say.
1429
+ * Nothing for a job without a worktree, and nothing when git cannot tell: the report goes
1430
+ * through all the same.
1431
+ */
1432
+ async changesAtReport(number) {
1433
+ const job = await this.enqueue(async () => this.jobIfAny(number));
1434
+ const worktree = job && this.liveWorktree(job);
1435
+ if (!worktree)
1436
+ return undefined;
1437
+ try {
1438
+ return summaryOf(await changesOf(worktree.path, worktree.base), this.iso());
1439
+ }
1440
+ catch (error) {
1441
+ this.onError(asError(error));
1442
+ return undefined;
1443
+ }
1444
+ }
1445
+ startChecks(number) {
1446
+ if (this.checkRuns.has(number))
1447
+ return;
1448
+ const stop = new AbortController();
1449
+ this.checkRuns.set(number, stop);
1450
+ const run = this.checkQueue
1451
+ .then(() => this.runChecks(number, stop.signal))
1452
+ .finally(() => this.checkRuns.delete(number));
1453
+ this.checkQueue = run.catch(() => undefined);
1454
+ this.track(run);
1455
+ }
1456
+ /**
1457
+ * Runs the checks of a job that was reported on, where the job was done, and hands its report
1458
+ * over with what they showed. The bridge runs a command itself, outside any sandbox, so it
1459
+ * runs only what the rules of whoever handed the job over allow without asking: the rest is
1460
+ * left out, and the result then does not count as verified. A dispatcher that closes in the
1461
+ * middle leaves the job as it is, and the next one runs its checks again.
1462
+ */
1463
+ async runChecks(number, signal) {
1464
+ const job = await this.enqueue(async () => this.jobIfAny(number));
1465
+ if (!job?.checking)
1466
+ return;
1467
+ const places = [job.project, findCheckoutRoot(job.cwd), this.liveWorktree(job)?.path];
1468
+ const results = [];
1469
+ for (const check of job.checks) {
1470
+ try {
1471
+ const cwd = check.cwd ? canonicalPath(resolvePath(job.cwd, check.cwd)) : job.cwd;
1472
+ if (!places.some((place) => place !== undefined && isInside(place, cwd))) {
1473
+ results.push(skippedCheck(check, `it would run in ${cwd}, outside the project`));
1474
+ continue;
1475
+ }
1476
+ const rights = await this.rightsFor(number, {
1477
+ tool: 'Bash',
1478
+ access: 'command',
1479
+ command: check.command,
1480
+ cwd,
1481
+ });
1482
+ if (rights !== 'allow') {
1483
+ results.push(skippedCheck(check, !this.rights
1484
+ ? 'this bridge has no rules to judge a command by, and runs none without them'
1485
+ : rights === 'deny'
1486
+ ? `the rules of ${job.from} forbid the command`
1487
+ : `the rules of ${job.from} do not allow the command without asking. Allow it in the settings of the project, or run it yourself`));
1488
+ continue;
1489
+ }
1490
+ results.push(await runCheck(check, {
1491
+ cwd,
1492
+ timeoutMs: check.timeoutMs ?? this.limits.checkTimeoutMs,
1493
+ signal,
1494
+ }));
1495
+ }
1496
+ catch (error) {
1497
+ this.onError(asError(error));
1498
+ results.push(skippedCheck(check, `the bridge failed to run it: ${asError(error).message}`));
1499
+ }
1500
+ if (signal.aborted)
1501
+ return;
1502
+ }
1503
+ if (this.closing)
1504
+ return;
1505
+ const { verified, summary } = summarizeChecks(results);
1506
+ await this.mutate(async (tx) => {
1507
+ const { job: fresh } = this.requireJob(number);
1508
+ if (!fresh.checking)
1509
+ return;
1510
+ await this.patchRecord(fresh.taskId, {
1511
+ verification: { verified, checkedAt: this.iso(), summary, checks: results },
1512
+ checking: undefined,
1513
+ });
1514
+ this.journal(tx, { type: 'job.verified', job: number, data: { verified, summary } });
1515
+ const report = this.store.getLetter(fresh.checking.letter);
1516
+ this.noteOutcome(tx, number, report?.body);
1517
+ if (report?.state === 'held') {
1518
+ this.store.updateLetter(report.id, { state: 'queued' });
1519
+ tx.wake.add(report.to);
1520
+ }
1521
+ });
1522
+ }
1523
+ /**
1524
+ * Picks up what a dispatcher before this one left in the middle: the checks of jobs that were
1525
+ * reported on and never got their verdict.
1526
+ */
1527
+ recover(tx) {
1528
+ if (this.recovered)
1529
+ return;
1530
+ this.recovered = true;
1531
+ for (const task of this.store.jobTasks({ states: ['completed'] })) {
1532
+ const job = jobOf(task);
1533
+ if (job?.checking)
1534
+ tx.checks.push(job.number);
1535
+ }
1536
+ }
1537
+ /**
1538
+ * What a job changed in its worktree so far: the files, how much, and the patch. For the two
1539
+ * agents of the job, while it runs and after, as long as its worktree is there.
1540
+ *
1541
+ * @throws BridgeError `unknown_job`, `not_a_party`, `no_worktree` for a job without a worktree
1542
+ * of its own or whose work was taken or dropped already
1543
+ */
1544
+ async diff(caller, input) {
1545
+ const request = parse(DiffInputSchema, input, 'Cannot show the changes');
1546
+ const { job, worktree } = await this.asCaller(caller, async () => {
1547
+ const agent = this.requireCaller(caller);
1548
+ const found = this.requireJob(request.job).job;
1549
+ if (agent.name !== found.from && agent.name !== found.to) {
1550
+ throw new BridgeError('not_a_party', `Job ${found.number} is between ${found.from} and ${found.to}`, { job: found.number });
1551
+ }
1552
+ return { job: found, worktree: this.requireWorktree(found) };
1553
+ });
1554
+ const changes = await this.readChanges(job, worktree);
1555
+ const { patch, truncated } = request.maxChars === 0
1556
+ ? { patch: '', truncated: changes.files.length > 0 }
1557
+ : await patchOf(worktree.path, worktree.base, changes.tree, {
1558
+ ...(request.paths && { paths: request.paths }),
1559
+ ...(request.maxChars !== undefined && { maxChars: request.maxChars }),
1560
+ });
1561
+ return {
1562
+ job: job.number,
1563
+ worktree: worktree.path,
1564
+ branch: worktree.branch,
1565
+ base: worktree.base,
1566
+ files: changes.files.map((file) => ({ ...file, path: shownPath(file.path) })),
1567
+ insertions: changes.insertions,
1568
+ deletions: changes.deletions,
1569
+ commits: changes.commits,
1570
+ patch,
1571
+ truncated,
1572
+ };
1573
+ }
1574
+ /**
1575
+ * Takes the work of a finished job out of its worktree, as the agent that handed the job over.
1576
+ * The changes, committed there or not, come into the checkout the caller works in as one
1577
+ * change that is staged and not committed: the commit is the caller's to make. With
1578
+ * `asBranch` they are left as a branch instead, for work that goes on as a pull request. The
1579
+ * worktree is removed either way. When the changes would leave files in conflict nothing is
1580
+ * touched, the answer names the files, and the worktree stays for another try. The bridge
1581
+ * never merges into a branch nobody is working on.
1582
+ *
1583
+ * @throws BridgeError `unknown_job`, `not_a_party` (only who handed the job over takes its
1584
+ * work), `invalid_input` (the job still runs, its checks do, the caller is in another
1585
+ * repository, or git refused), `no_worktree`
1586
+ */
1587
+ async accept(caller, input) {
1588
+ const request = parse(AcceptInputSchema, input, 'Cannot take the work');
1589
+ const { job, worktree, agent } = await this.asCaller(caller, async () => this.requireTaker(caller, request.job, 'take'));
1590
+ return this.whileTaking(job.number, async () => {
1591
+ const changes = await this.readChanges(job, worktree);
1592
+ if (changes.files.length === 0 && changes.commits === 0) {
1593
+ await removeJobWorktree(job.project, worktree.path, worktree.branch);
1594
+ const ended = await this.endWorktree(job.number, { how: 'accepted' }, 'job.accepted', {});
1595
+ return { state: 'nothing', job: ended };
1596
+ }
1597
+ const commit = await snapshotOf(worktree.path, changes, `job #${job.number}: ${job.title}`);
1598
+ if (request.asBranch) {
1599
+ const branch = request.asBranch === true ? worktree.branch : request.asBranch;
1600
+ await this.leaveBranch(job, worktree, branch, commit);
1601
+ const ended = await this.endWorktree(job.number, { how: 'branch', commit, ref: branch }, 'job.accepted', { branch, commit });
1602
+ return { state: 'branch', job: ended, branch, commit };
1603
+ }
1604
+ const into = await checkoutOf(agent.cwd);
1605
+ if (!into || canonicalPath(findProjectRoot(into)) !== canonicalPath(job.project)) {
1606
+ 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 });
1607
+ }
1608
+ const conflicts = await this.oneAtATimeIn(into, async () => {
1609
+ const busy = await busyWith(into).catch((error) => {
1610
+ throw gitRefusal(error, `Git could not look at ${into}`);
1611
+ });
1612
+ if (busy) {
1613
+ 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 });
1614
+ }
1615
+ const inConflict = await conflictsOf(into, commit).catch((error) => {
1616
+ throw gitRefusal(error, `Git could not tell whether job ${job.number} merges into ${into}`);
1617
+ });
1618
+ if (inConflict.length > 0)
1619
+ return inConflict;
1620
+ await squashInto(into, commit).catch((error) => {
1621
+ 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`);
1622
+ });
1623
+ return [];
1624
+ });
1625
+ if (conflicts.length > 0) {
1626
+ return { state: 'conflict', job, into, files: conflicts.map(shownPath) };
1627
+ }
1628
+ await removeJobWorktree(job.project, worktree.path, worktree.branch).catch((error) => this.onError(asError(error)));
1629
+ const ended = await this.endWorktree(job.number, { how: 'accepted', commit, into }, 'job.accepted', { into, commit, files: changes.files.length });
1630
+ return {
1631
+ state: 'accepted',
1632
+ job: ended,
1633
+ into,
1634
+ files: changes.files.length,
1635
+ insertions: changes.insertions,
1636
+ deletions: changes.deletions,
1637
+ };
1638
+ });
1639
+ }
1640
+ /**
1641
+ * Drops the work of a finished job, as the agent that handed the job over: its worktree and
1642
+ * the branch of it are removed with everything in them.
1643
+ *
1644
+ * @throws BridgeError `unknown_job`, `not_a_party`, `invalid_input` (the job still runs, or
1645
+ * its checks do), `no_worktree`
1646
+ */
1647
+ async reject(caller, input) {
1648
+ const request = parse(RejectInputSchema, input, 'Cannot drop the work');
1649
+ const { job, worktree } = await this.asCaller(caller, async () => this.requireTaker(caller, request.job, 'drop'));
1650
+ return this.whileTaking(job.number, async () => {
1651
+ await removeJobWorktree(job.project, worktree.path, worktree.branch);
1652
+ return this.endWorktree(job.number, { how: 'rejected' }, 'job.rejected', {
1653
+ ...(request.reason && { reason: request.reason }),
1654
+ });
1655
+ });
1656
+ }
1657
+ /**
1658
+ * Work on one checkout after the other work on it: looking whether it is free, merging into
1659
+ * it and taking a failed merge back are one step, and two jobs taken into the same checkout
1660
+ * at once would each undo what the other staged.
1661
+ */
1662
+ oneAtATimeIn(checkout, work) {
1663
+ const run = (this.checkouts.get(checkout) ?? Promise.resolve()).then(work, work);
1664
+ const settled = run
1665
+ .then(() => undefined, () => undefined)
1666
+ .finally(() => {
1667
+ if (this.checkouts.get(checkout) === settled)
1668
+ this.checkouts.delete(checkout);
1669
+ });
1670
+ this.checkouts.set(checkout, settled);
1671
+ return run;
1672
+ }
1673
+ /** The worktree of a job whose work is still in it, or why there is none. */
1674
+ requireWorktree(job) {
1675
+ const worktree = this.liveWorktree(job);
1676
+ if (worktree)
1677
+ return worktree;
1678
+ const end = job.worktree?.end;
1679
+ throw new BridgeError('no_worktree', end
1680
+ ? `The work of job ${job.number} was ${ENDED[end.how]}${end.ref ? ` (${end.ref})` : ''}${end.into ? ` into ${end.into}` : ''}, and its worktree is gone`
1681
+ : job.isolation === 'worktree'
1682
+ ? `Job ${job.number} has no worktree yet: its session has not started`
1683
+ : `Job ${job.number} was done in ${job.cwd}, not in a worktree of its own: what it changed is there`, { job: job.number });
1684
+ }
1685
+ /** The job, its worktree and the caller, for the one who may take or drop its work. */
1686
+ requireTaker(caller, number, what) {
1687
+ const agent = this.requireCaller(caller);
1688
+ const { job } = this.requireJob(number);
1689
+ if (agent.name !== job.from) {
1690
+ throw new BridgeError('not_a_party', `Only ${job.from}, who handed job ${job.number} over, can ${what} its work`, { job: job.number });
1691
+ }
1692
+ if (!isFinishedJobState(job.state)) {
1693
+ 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 });
1694
+ }
1695
+ if (job.checking) {
1696
+ throw new BridgeError('invalid_input', `The checks of job ${job.number} still run. Its report comes with what they show`, { job: job.number });
1697
+ }
1698
+ return { job, worktree: this.requireWorktree(job), agent };
1699
+ }
1700
+ /** One taking, dropping or putting away of a job's worktree at a time. */
1701
+ async whileTaking(number, work) {
1702
+ if (this.taking.has(number)) {
1703
+ throw new BridgeError('invalid_input', `The work of job ${number} is being taken or dropped right now`, { job: number });
1704
+ }
1705
+ this.taking.add(number);
1706
+ try {
1707
+ return await work();
1708
+ }
1709
+ finally {
1710
+ this.taking.delete(number);
1711
+ }
1712
+ }
1713
+ async readChanges(job, worktree) {
1714
+ try {
1715
+ return await changesOf(worktree.path, worktree.base);
1716
+ }
1717
+ catch (error) {
1718
+ throw gitRefusal(error, `Git could not read the worktree of job ${job.number}, ${worktree.path}`);
1719
+ }
1720
+ }
1721
+ /**
1722
+ * Leaves the work of a worktree as the branch `branch`, at `commit`, and removes the worktree.
1723
+ * The branch is set first: whatever goes wrong after that, the work is on it.
1724
+ */
1725
+ async leaveBranch(job, worktree, branch, commit) {
1726
+ try {
1727
+ const own = branch === worktree.branch;
1728
+ await pointRef(job.project, `refs/heads/${branch}`, commit, { fresh: !own });
1729
+ await removeJobWorktree(job.project, worktree.path, own ? undefined : worktree.branch);
1730
+ }
1731
+ catch (error) {
1732
+ throw gitRefusal(error, `Git could not leave the work of job ${job.number} as ${branch}`);
1733
+ }
1734
+ }
1735
+ /** Records how the work in a job's worktree ended. */
1736
+ async endWorktree(number, end, type, data) {
1737
+ return this.mutate(async (tx) => {
1738
+ const { job } = this.requireJob(number);
1739
+ if (job.worktree) {
1740
+ await this.patchRecord(job.taskId, {
1741
+ worktree: { ...job.worktree, end: { ...end, at: this.iso() } },
1742
+ });
1743
+ this.retireFrom(tx, job, job.worktree.path);
1744
+ }
1745
+ this.journal(tx, { type, job: number, data: { how: end.how, ...data } });
1746
+ return this.requireJob(number).job;
1747
+ });
1748
+ }
1749
+ /**
1750
+ * Takes the session that was started in a worktree for gone once the worktree is: the folder
1751
+ * it works in is not there any more, so it is no session to hand another job to.
1752
+ */
1753
+ retireFrom(tx, job, worktree) {
1754
+ const agent = this.store.getAgent(job.to);
1755
+ if (!agent || agent.status === 'gone' || !isInside(worktree, agent.cwd))
1756
+ return;
1757
+ this.store.putAgent({ ...agent, status: 'gone' });
1758
+ this.journal(tx, {
1759
+ type: 'agent.gone',
1760
+ agent: agent.name,
1761
+ data: { error: `the worktree of job #${job.number}, where it worked, was removed` },
1762
+ });
1763
+ }
1764
+ /**
1765
+ * Puts away the worktrees nobody came for: those of jobs that finished longer ago than
1766
+ * `limits.worktreeKeepMs`. What such a worktree holds is kept as a commit under a ref of its
1767
+ * own, the worktree and its branch are removed, and whoever handed the job over is told
1768
+ * where the work is. Looked at once an hour.
1769
+ */
1770
+ sweepWorktrees(now) {
1771
+ if (now - this.worktreesSweptAt < WORKTREE_SWEEP_MS)
1772
+ return;
1773
+ this.worktreesSweptAt = now;
1774
+ const left = this.store
1775
+ .jobTasks({ states: FINISHED_JOB_STATES })
1776
+ .flatMap((task) => jobOf(task) ?? [])
1777
+ .filter((job) => this.liveWorktree(job) !== undefined &&
1778
+ !job.checking &&
1779
+ now - Date.parse(job.endedAt ?? job.updatedAt) >= this.limits.worktreeKeepMs);
1780
+ for (const job of left) {
1781
+ if (this.taking.has(job.number))
1782
+ continue;
1783
+ this.track(this.whileTaking(job.number, () => this.putAway(job)));
1784
+ }
1785
+ }
1786
+ /**
1787
+ * Puts the worktree of a job away. Nothing is removed before its work is kept: when git
1788
+ * cannot read the worktree because its folder is gone, the commits on its branch are kept,
1789
+ * and when it cannot for another reason, the worktree stays and the next look tries again.
1790
+ */
1791
+ async putAway(job) {
1792
+ const worktree = this.liveWorktree(job);
1793
+ if (!worktree)
1794
+ return;
1795
+ const ref = `${DISCARDED_REFS}/job-${job.number}`;
1796
+ let kept;
1797
+ try {
1798
+ if (existsSync(worktree.path)) {
1799
+ const changes = await changesOf(worktree.path, worktree.base);
1800
+ if (changes.files.length > 0 || changes.commits > 0) {
1801
+ const commit = await snapshotOf(worktree.path, changes, `job #${job.number}: ${job.title}`);
1802
+ await pointRef(job.project, ref, commit);
1803
+ kept = { commit, ref };
1804
+ }
1805
+ }
1806
+ else {
1807
+ const tip = await branchTip(job.project, worktree.branch);
1808
+ if (tip && tip !== worktree.base) {
1809
+ await pointRef(job.project, ref, tip);
1810
+ kept = { commit: tip, ref };
1811
+ }
1812
+ }
1813
+ await removeJobWorktree(job.project, worktree.path, worktree.branch);
1814
+ }
1815
+ catch (error) {
1816
+ this.onError(new Error(`The worktree of job ${job.number}, ${worktree.path}, could not be put away and stays: ${asError(error).message}`, { cause: error }));
1817
+ return;
1818
+ }
1819
+ await this.mutate(async (tx) => {
1820
+ const { job: fresh } = this.requireJob(job.number);
1821
+ if (!fresh.worktree)
1822
+ return;
1823
+ await this.patchRecord(fresh.taskId, {
1824
+ worktree: { ...fresh.worktree, end: { how: 'discarded', at: this.iso(), ...kept } },
1825
+ });
1826
+ this.retireFrom(tx, fresh, fresh.worktree.path);
1827
+ this.journal(tx, {
1828
+ type: 'job.discarded',
1829
+ job: job.number,
1830
+ data: { how: 'discarded', ...kept },
1831
+ });
1832
+ if (kept) {
1833
+ 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}.`);
1834
+ }
1835
+ });
1836
+ }
1837
+ /** The board of this bridge, or the refusal of a bridge that was given none. */
1838
+ requireBoard() {
1839
+ if (this.board)
1840
+ return this.board;
1841
+ throw new BridgeError('no_board', 'This bridge keeps no notes: whoever runs it gave it no board to keep them on');
1842
+ }
1843
+ /** The project a call about the board is for: the caller's own, or the one the person names. */
1844
+ boardProject(agent, named) {
1845
+ if (agent)
1846
+ return agent.project;
1847
+ if (named)
1848
+ return canonicalPath(findProjectRoot(named));
1849
+ throw new BridgeError('invalid_input', 'Say which project the note is for');
1850
+ }
1851
+ /** The jobs whose own notes a caller may see: an agent's are those it is a party of. */
1852
+ jobsSeenBy(agent, project) {
1853
+ return this.store
1854
+ .jobTasks(agent ? { party: agent.name } : { project })
1855
+ .flatMap((task) => jobOf(task) ?? [])
1856
+ .filter((job) => job.project === project)
1857
+ .map((job) => job.number);
1858
+ }
1859
+ /**
1860
+ * Puts a note on the board of a project, for the agents that work there to find: a fact, or
1861
+ * what a job taught. The note carries who said it, on which job and when. `caller` is the
1862
+ * agent that says it, or `null` for the person, who names the project. A note kept to a job
1863
+ * (`jobOnly`) is seen by the two agents of that job only.
1864
+ *
1865
+ * @throws BridgeError `no_board`, `not_registered`, `unknown_job`, `not_a_party` (the job named
1866
+ * is not the caller's), `invalid_input`
1867
+ */
1868
+ async remember(caller, input) {
1869
+ const request = parse(RememberInputSchema, input, 'Cannot remember that');
1870
+ const board = this.requireBoard();
1871
+ const fact = await this.enqueue(async () => {
1872
+ const agent = caller === null ? undefined : this.requireCaller(caller);
1873
+ let project = this.boardProject(agent, request.project);
1874
+ let job = request.job;
1875
+ if (job !== undefined) {
1876
+ const found = this.requireJob(job).job;
1877
+ const party = agent ? agent.name === found.from || agent.name === found.to : undefined;
1878
+ if (party)
1879
+ project = found.project;
1880
+ if (found.project !== project || party === false) {
1881
+ throw new BridgeError('not_a_party', `Job ${found.number} is between ${found.from} and ${found.to}, so a note cannot be said on it from here`, { job: found.number });
1882
+ }
1883
+ }
1884
+ else if (agent) {
1885
+ const carried = this.store
1886
+ .jobTasks({ to: agent.name, states: ACTIVE_JOB_STATES })
1887
+ .flatMap((task) => jobOf(task) ?? []);
1888
+ if (carried.length === 1)
1889
+ job = carried[0].number;
1890
+ }
1891
+ return {
1892
+ kind: request.kind ?? 'fact',
1893
+ text: request.text,
1894
+ project,
1895
+ ...(request.jobOnly && job !== undefined && { job }),
1896
+ source: {
1897
+ by: agent?.name ?? PERSON,
1898
+ ...(job !== undefined && { job }),
1899
+ at: this.iso(),
1900
+ },
1901
+ };
1902
+ });
1903
+ const kept = await board.remember(fact);
1904
+ await this.journalNote(kept, fact.source.by);
1905
+ return kept;
1906
+ }
1907
+ /**
1908
+ * Writes down that a note went on the board, and who said it this time. Everybody can read
1909
+ * the journal, so the text of a note kept to one job is left out of it.
1910
+ */
1911
+ async journalNote(kept, by) {
1912
+ await this.mutate(async (tx) => {
1913
+ this.journal(tx, {
1914
+ type: 'fact.remembered',
1915
+ agent: by,
1916
+ ...(kept.source.job !== undefined && { job: kept.source.job }),
1917
+ data: {
1918
+ id: kept.id,
1919
+ kind: kept.kind,
1920
+ project: kept.project,
1921
+ ...(kept.job === undefined && { text: kept.text }),
1922
+ ...(kept.source.by !== by && { saidBefore: kept.source.by }),
1923
+ },
1924
+ });
1925
+ });
1926
+ }
1927
+ /**
1928
+ * Looks at the board of a project: the notes that fit `text` best, or the newest. An agent
1929
+ * sees the notes of its project and those kept to the jobs it is a party of, the person
1930
+ * (`caller` is `null`) every note of the project they name.
1931
+ *
1932
+ * @throws BridgeError `no_board`, `not_registered`, `invalid_input`
1933
+ */
1934
+ async recall(caller, input = {}) {
1935
+ const request = parse(RecallInputSchema, input, 'Cannot look at the board');
1936
+ const board = this.requireBoard();
1937
+ const query = await this.enqueue(async () => {
1938
+ const agent = caller === null ? undefined : this.requireCaller(caller);
1939
+ const project = this.boardProject(agent, request.project);
1940
+ return { project, jobs: this.jobsSeenBy(agent, project) };
1941
+ });
1942
+ return board.recall({
1943
+ ...query,
1944
+ ...(request.text && { text: request.text }),
1945
+ ...(request.kinds && { kinds: request.kinds }),
1946
+ ...(request.limit !== undefined && { limit: request.limit }),
1947
+ });
1948
+ }
1949
+ /**
1950
+ * Lets a note of the board go: it is found no more, and is not deleted. An agent lets go what
1951
+ * it said itself, the person (`caller` is `null`) any note of the project they name.
1952
+ *
1953
+ * @throws BridgeError `no_board`, `not_registered`, `invalid_input` (no such note there),
1954
+ * `not_a_party` (the note is another's)
1955
+ */
1956
+ async forget(caller, input) {
1957
+ const request = parse(ForgetInputSchema, input, 'Cannot forget that');
1958
+ const board = this.requireBoard();
1959
+ const { agent, project, jobs } = await this.enqueue(async () => {
1960
+ const found = caller === null ? undefined : this.requireCaller(caller);
1961
+ const where = this.boardProject(found, request.project);
1962
+ return { agent: found, project: where, jobs: this.jobsSeenBy(found, where) };
1963
+ });
1964
+ const fact = await board.find(request.id);
1965
+ const seen = fact?.project === project && (fact.job === undefined || jobs.includes(fact.job));
1966
+ if (!fact || !seen) {
1967
+ throw new BridgeError('invalid_input', `There is no note ${request.id} on the board of ${project}`, {
1968
+ id: request.id,
1969
+ });
1970
+ }
1971
+ if (agent && fact.source.by !== agent.name) {
1972
+ throw new BridgeError('not_a_party', `The note ${fact.id} is what ${fact.source.by === PERSON ? 'the person' : fact.source.by} said: only they, or the person, let it go`, { id: fact.id });
1973
+ }
1974
+ await board.forget(fact.id);
1975
+ await this.mutate(async (tx) => {
1976
+ this.journal(tx, {
1977
+ type: 'fact.forgotten',
1978
+ agent: agent?.name ?? PERSON,
1979
+ data: { id: fact.id, kind: fact.kind, project: fact.project, by: fact.source.by },
1980
+ });
1981
+ });
1982
+ return fact;
1983
+ }
1984
+ /** The text of a job as its caller wrote it: its first letter without what the bridge added. */
1985
+ taskText(first, job) {
1986
+ const length = (job ?? this.jobIfAny(first.job))?.taskLength;
1987
+ return length === undefined ? first.body : first.body.slice(0, length);
1988
+ }
1989
+ /**
1990
+ * Whether the rules of an agent let it read a file without asking: its own, and those of every
1991
+ * agent up the chain of the jobs it carries out. True on a bridge that was given no judge:
1992
+ * what an agent names in its own project it could read itself.
1993
+ */
1994
+ async mayRead(from, cwd, path) {
1995
+ if (!this.rights)
1996
+ return true;
1997
+ const ask = { tool: 'Read', access: 'read', paths: [path], cwd };
1998
+ try {
1999
+ const now = this.iso();
2000
+ const own = await this.rights({
2001
+ job: {
2002
+ number: 0,
2003
+ taskId: '',
2004
+ title: '',
2005
+ from: from.name,
2006
+ to: from.name,
2007
+ project: from.project,
2008
+ cwd,
2009
+ checks: [],
2010
+ budget: this.limits.budget,
2011
+ lettersUsed: 0,
2012
+ depth: 1,
2013
+ createdAt: now,
2014
+ deadlineAt: now,
2015
+ state: 'submitted',
2016
+ updatedAt: now,
2017
+ },
2018
+ delegator: from,
2019
+ ask,
2020
+ });
2021
+ if (own !== 'allow')
2022
+ return false;
2023
+ const carried = await this.enqueue(async () => this.store
2024
+ .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
2025
+ .flatMap((task) => jobOf(task) ?? []));
2026
+ for (const job of carried) {
2027
+ if ((await this.rightsFor(job.number, ask)) !== 'allow')
2028
+ return false;
2029
+ }
2030
+ return true;
2031
+ }
2032
+ catch (error) {
2033
+ this.onError(asError(error));
2034
+ return false;
2035
+ }
2036
+ }
2037
+ /**
2038
+ * The block the bridge puts under the text of a job, see `buildHandover`: what the caller
2039
+ * named, the lines of the files it pointed at, and the notes of the board that fit the job.
2040
+ * Undefined when there is nothing to add. It never fails the hand-over and never holds it up
2041
+ * for long: what cannot be read or found in time is left out, and the block is kept small
2042
+ * enough for the letter to take it.
2043
+ */
2044
+ async handoverFor(caller, request) {
2045
+ const from = await this.enqueue(async () => this.store.getAgent(caller));
2046
+ if (!from)
2047
+ return undefined;
2048
+ const room = Math.floor((this.limits.maxBodyLength - request.body.length - HANDOVER_GAP.length) / 4);
2049
+ const budget = Math.min(request.contextTokens ?? this.limits.contextTokens, room);
2050
+ if (budget <= 0)
2051
+ return undefined;
2052
+ const build = async () => {
2053
+ const about = `${request.title ?? ''}\n${request.body}`.slice(0, ABOUT_CHARS);
2054
+ const board = this.board;
2055
+ const [facts, earlier] = board
2056
+ ? await Promise.all([
2057
+ board.recall({ project: from.project, text: about, kinds: ['fact'], limit: 8 }),
2058
+ earlierLike(board, from.project, about),
2059
+ ])
2060
+ : [[], []];
2061
+ return buildHandover(request.context, {
2062
+ from: from.name,
2063
+ cwd: from.cwd,
2064
+ roots: [from.project, findCheckoutRoot(from.cwd)],
2065
+ top: findCheckoutRoot(from.cwd),
2066
+ mayRead: (path) => this.mayRead(from, from.cwd, path),
2067
+ facts,
2068
+ earlier,
2069
+ }, budget);
2070
+ };
2071
+ try {
2072
+ return await within(build(), this.limits.contextTimeoutMs, 'Putting the context of the job together');
2073
+ }
2074
+ catch (error) {
2075
+ this.onError(asError(error));
2076
+ return undefined;
2077
+ }
2078
+ }
2079
+ /**
2080
+ * Notes how a job ended on the board of its project, in the bridge's own name: who did it for
2081
+ * whom, how it ended, what its checks showed and the start of what was reported. A later job
2082
+ * like it finds the note in its handover.
2083
+ */
2084
+ noteOutcome(tx, number, reported) {
2085
+ if (!this.board)
2086
+ return;
2087
+ const { job } = this.requireJob(number);
2088
+ tx.notes.push({
2089
+ kind: 'outcome',
2090
+ text: outcomeText(job, reported),
2091
+ project: job.project,
2092
+ source: { by: BRIDGE_SENDER, job: job.number, at: this.iso() },
2093
+ });
2094
+ }
2095
+ /** Puts on the board what a call left for it, after the call is stored. */
2096
+ keepNotes(notes) {
2097
+ const board = this.board;
2098
+ if (!board || notes.length === 0)
2099
+ return;
2100
+ this.track((async () => {
2101
+ for (const note of notes) {
2102
+ try {
2103
+ const kept = await board.remember(note);
2104
+ if (kept.kind !== 'outcome')
2105
+ await this.journalNote(kept, note.source.by);
2106
+ }
2107
+ catch (error) {
2108
+ this.onError(asError(error));
2109
+ }
2110
+ }
2111
+ })());
2112
+ }
1216
2113
  /** @throws BridgeError `unknown_job` */
1217
2114
  async job(number) {
1218
2115
  return this.enqueue(async () => this.requireJob(number).job);
@@ -1273,6 +2170,8 @@ export class BridgeDispatcher extends EventEmitter {
1273
2170
  const now = this.now();
1274
2171
  const failed = [];
1275
2172
  const reminded = [];
2173
+ this.recover(tx);
2174
+ this.sweepWorktrees(now);
1276
2175
  const overdue = this.store
1277
2176
  .jobTasks({ states: ACTIVE_JOB_STATES, deadlineBy: now })
1278
2177
  .flatMap((task) => jobOf(task) ?? [])
@@ -1471,6 +2370,8 @@ export class BridgeDispatcher extends EventEmitter {
1471
2370
  */
1472
2371
  async close() {
1473
2372
  this.closing = true;
2373
+ for (const run of this.checkRuns.values())
2374
+ run.abort();
1474
2375
  for (const waiter of [...this.waiters.values()])
1475
2376
  waiter.end('closed');
1476
2377
  for (const letter of [...this.verdictWaiters.keys()])
@@ -1523,6 +2424,8 @@ export class BridgeDispatcher extends EventEmitter {
1523
2424
  settled: [],
1524
2425
  decided: new Set(),
1525
2426
  notices: [],
2427
+ checks: [],
2428
+ notes: [],
1526
2429
  };
1527
2430
  const result = await this.store.transaction(() => {
1528
2431
  this.assertWritable?.();
@@ -1544,6 +2447,10 @@ export class BridgeDispatcher extends EventEmitter {
1544
2447
  this.wake(agent);
1545
2448
  for (const letter of tx.decided)
1546
2449
  this.announce(letter);
2450
+ if (!this.closing)
2451
+ for (const number of tx.checks)
2452
+ this.startChecks(number);
2453
+ this.keepNotes(tx.notes);
1547
2454
  this.tellPerson(tx);
1548
2455
  return result;
1549
2456
  }
@@ -1670,6 +2577,8 @@ export class BridgeDispatcher extends EventEmitter {
1670
2577
  }
1671
2578
  if (job.state !== to) {
1672
2579
  this.journal(tx, { type: 'job.state', job: number, data: { from: job.state, to } });
2580
+ if (isFinishedJobState(to))
2581
+ await this.patchRecord(job.taskId, { endedAt: this.iso() });
1673
2582
  }
1674
2583
  }
1675
2584
  async pickUp(tx, job) {
@@ -1689,6 +2598,7 @@ export class BridgeDispatcher extends EventEmitter {
1689
2598
  await this.patchRecord(job.taskId, { reason });
1690
2599
  this.closeLetters(tx, number);
1691
2600
  await this.stopWaiting(number, this.now(), false);
2601
+ this.noteOutcome(tx, number);
1692
2602
  const text = `Job #${number} has failed: ${reason}.`;
1693
2603
  this.systemNote(tx, job, job.from, text);
1694
2604
  this.systemNote(tx, job, job.to, `${text} Stop working on it.`);
@@ -1702,6 +2612,7 @@ export class BridgeDispatcher extends EventEmitter {
1702
2612
  await this.patchRecord(job.taskId, { reason });
1703
2613
  this.closeLetters(tx, number);
1704
2614
  await this.stopWaiting(number, this.now(), false);
2615
+ this.noteOutcome(tx, number);
1705
2616
  this.systemNote(tx, job, job.to, note);
1706
2617
  await this.cancelChildren(tx, job);
1707
2618
  }
@@ -1734,7 +2645,7 @@ export class BridgeDispatcher extends EventEmitter {
1734
2645
  if (job.cwd !== cwd || !sameAgent(job))
1735
2646
  return false;
1736
2647
  const first = this.store.listLetters({ job: job.number, kinds: ['task'], limit: 1 })[0];
1737
- return first !== undefined && normalizeBody(first.body) === wanted;
2648
+ return first !== undefined && normalizeBody(this.taskText(first, job)) === wanted;
1738
2649
  });
1739
2650
  if (same) {
1740
2651
  return new BridgeError('loop_detected', `You already handed this job to ${same.to} as job #${same.number}, and it is still ${same.state}. Wait for its report, or cancel it first`, { job: same.number });
@@ -1770,7 +2681,7 @@ export class BridgeDispatcher extends EventEmitter {
1770
2681
  }
1771
2682
  }
1772
2683
  }
1773
- accept(tx, fields) {
2684
+ acceptLetter(tx, fields) {
1774
2685
  const letter = this.store.insertLetter({
1775
2686
  ...fields,
1776
2687
  state: 'queued',
@@ -1799,7 +2710,7 @@ export class BridgeDispatcher extends EventEmitter {
1799
2710
  }
1800
2711
  /** A letter the bridge writes itself. It costs the job nothing and is never held back as a repeat. */
1801
2712
  systemNote(tx, job, to, body) {
1802
- return this.accept(tx, {
2713
+ return this.acceptLetter(tx, {
1803
2714
  id: this.letterId(),
1804
2715
  job: job.number,
1805
2716
  kind: 'note',
@@ -2047,14 +2958,15 @@ export class BridgeDispatcher extends EventEmitter {
2047
2958
  return;
2048
2959
  let created;
2049
2960
  try {
2961
+ const place = await this.placeOf(agentName, request.job, letterId);
2050
2962
  created = await within(adapter.createSession({
2051
2963
  agentName,
2052
2964
  harness: request.agent.harness,
2053
2965
  project: request.agent.project,
2054
- cwd: request.agent.cwd,
2966
+ cwd: place?.job.cwd ?? request.agent.cwd,
2055
2967
  ...(request.agent.sessionName && { sessionName: request.agent.sessionName }),
2056
- job: request.job,
2057
- firstLetter: request.letter,
2968
+ job: place?.job ?? request.job,
2969
+ firstLetter: place?.letter ?? request.letter,
2058
2970
  }), this.limits.sessionStartTimeoutMs, `Starting a ${request.agent.harness} session`);
2059
2971
  if (!created.sessionId.trim())
2060
2972
  throw new Error('the adapter returned no session id');