@cogitator-ai/bridge 0.7.0 → 0.9.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 (91) hide show
  1. package/README.md +161 -33
  2. package/dist/adapter.d.ts +28 -2
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapters/codex.d.ts.map +1 -1
  5. package/dist/adapters/codex.js +4 -0
  6. package/dist/adapters/codex.js.map +1 -1
  7. package/dist/board.d.ts +76 -0
  8. package/dist/board.d.ts.map +1 -0
  9. package/dist/board.js +19 -0
  10. package/dist/board.js.map +1 -0
  11. package/dist/client.d.ts +11 -1
  12. package/dist/client.d.ts.map +1 -1
  13. package/dist/client.js +15 -0
  14. package/dist/client.js.map +1 -1
  15. package/dist/dispatcher.d.ts +144 -12
  16. package/dist/dispatcher.d.ts.map +1 -1
  17. package/dist/dispatcher.js +597 -40
  18. package/dist/dispatcher.js.map +1 -1
  19. package/dist/errors.d.ts +1 -1
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js.map +1 -1
  22. package/dist/findings.d.ts +59 -0
  23. package/dist/findings.d.ts.map +1 -0
  24. package/dist/findings.js +117 -0
  25. package/dist/findings.js.map +1 -0
  26. package/dist/handover.d.ts +72 -0
  27. package/dist/handover.d.ts.map +1 -0
  28. package/dist/handover.js +225 -0
  29. package/dist/handover.js.map +1 -0
  30. package/dist/host.d.ts +7 -0
  31. package/dist/host.d.ts.map +1 -1
  32. package/dist/host.js +1 -0
  33. package/dist/host.js.map +1 -1
  34. package/dist/index.d.ts +6 -3
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +4 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/inputs.d.ts +104 -1
  39. package/dist/inputs.d.ts.map +1 -1
  40. package/dist/inputs.js +73 -1
  41. package/dist/inputs.js.map +1 -1
  42. package/dist/job-record.d.ts +16 -0
  43. package/dist/job-record.d.ts.map +1 -1
  44. package/dist/job-record.js +4 -0
  45. package/dist/job-record.js.map +1 -1
  46. package/dist/letters.d.ts +1 -1
  47. package/dist/letters.d.ts.map +1 -1
  48. package/dist/letters.js +6 -0
  49. package/dist/letters.js.map +1 -1
  50. package/dist/memory/index.d.ts +35 -0
  51. package/dist/memory/index.d.ts.map +1 -0
  52. package/dist/memory/index.js +192 -0
  53. package/dist/memory/index.js.map +1 -0
  54. package/dist/protocol.d.ts +3 -0
  55. package/dist/protocol.d.ts.map +1 -1
  56. package/dist/protocol.js +3 -0
  57. package/dist/protocol.js.map +1 -1
  58. package/dist/recipes/built-in.d.ts +35 -0
  59. package/dist/recipes/built-in.d.ts.map +1 -0
  60. package/dist/recipes/built-in.js +439 -0
  61. package/dist/recipes/built-in.js.map +1 -0
  62. package/dist/recipes/conductor.d.ts +61 -0
  63. package/dist/recipes/conductor.d.ts.map +1 -0
  64. package/dist/recipes/conductor.js +581 -0
  65. package/dist/recipes/conductor.js.map +1 -0
  66. package/dist/recipes/index.d.ts +5 -0
  67. package/dist/recipes/index.d.ts.map +1 -0
  68. package/dist/recipes/index.js +5 -0
  69. package/dist/recipes/index.js.map +1 -0
  70. package/dist/recipes/recipe.d.ts +128 -0
  71. package/dist/recipes/recipe.d.ts.map +1 -0
  72. package/dist/recipes/recipe.js +54 -0
  73. package/dist/recipes/recipe.js.map +1 -0
  74. package/dist/registry.d.ts +5 -0
  75. package/dist/registry.d.ts.map +1 -1
  76. package/dist/registry.js +5 -0
  77. package/dist/registry.js.map +1 -1
  78. package/dist/server.d.ts.map +1 -1
  79. package/dist/server.js +3 -0
  80. package/dist/server.js.map +1 -1
  81. package/dist/tools/guidance.d.ts.map +1 -1
  82. package/dist/tools/guidance.js +3 -0
  83. package/dist/tools/guidance.js.map +1 -1
  84. package/dist/tools/tools.d.ts.map +1 -1
  85. package/dist/tools/tools.js +252 -1
  86. package/dist/tools/tools.js.map +1 -1
  87. package/dist/types.d.ts +35 -1
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/types.js +4 -0
  90. package/dist/types.js.map +1 -1
  91. package/package.json +21 -1
@@ -2,10 +2,12 @@ import { EventEmitter } from 'node:events';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { isAbsolute, resolve as resolvePath } from 'node:path';
4
4
  import { TaskManager, textPart, toMessage } from '@cogitator-ai/a2a';
5
+ import { MAX_RECALL_LIMIT } from './board.js';
5
6
  import { runCheck, skippedCheck, summarizeChecks } from './checks.js';
6
7
  import { BridgeError } from './errors.js';
7
8
  import { deliveryBackoff, exhaustedBudget, formatDuration, nextDepth, resolveBudget, resolveLimits, } from './guards.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';
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';
9
11
  import { isFinishedJobState, jobOf, jobRecordOf } from './job-record.js';
10
12
  import { expectationOf, forHistory, newLetterId, normalizeBody, oneLine, quoted, renderLetter, repeats, titleOf, } from './letters.js';
11
13
  import { canonicalPath, findCheckoutRoot, findProjectRoot, inCheckout, isInside } from './paths.js';
@@ -35,6 +37,57 @@ function summaryOf(changes, at) {
35
37
  at,
36
38
  };
37
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
+ }
38
91
  /** What git said when it refused, as an error an agent can act on. */
39
92
  function gitRefusal(error, what) {
40
93
  if (error instanceof BridgeError)
@@ -100,6 +153,9 @@ function userMessage(text) {
100
153
  function asError(error) {
101
154
  return error instanceof Error ? error : new Error(String(error));
102
155
  }
156
+ /** The ids the conductor of a recipe gives the letters it writes. */
157
+ const RECIPE_LETTER_ID = /^(recipe|relay)-/;
158
+ const NO_CONDUCTOR = 'This bridge carries out no recipes: its host gave it no conductor (recipeAdapter of @cogitator-ai/bridge/recipes)';
103
159
  /** `work`, or a rejection when it takes longer than `ms`. */
104
160
  function within(work, ms, what) {
105
161
  return new Promise((resolve, reject) => {
@@ -145,6 +201,7 @@ export class BridgeDispatcher extends EventEmitter {
145
201
  assertWritable;
146
202
  rights;
147
203
  person;
204
+ board;
148
205
  /** When each agent's other parties were last told it waits at its window, see `stuck` */
149
206
  stuckTold = new Map();
150
207
  /** Those waiting for the verdict of a permission request, by its id, see `verdict` */
@@ -196,6 +253,7 @@ export class BridgeDispatcher extends EventEmitter {
196
253
  this.assertWritable = options.assertWritable;
197
254
  this.rights = options.rights;
198
255
  this.person = options.person;
256
+ this.board = options.board;
199
257
  for (const adapter of options.adapters ?? []) {
200
258
  const harness = parse(HarnessNameSchema, adapter.harness, 'Cannot use the adapter');
201
259
  if (this.adapters.has(harness)) {
@@ -300,24 +358,37 @@ export class BridgeDispatcher extends EventEmitter {
300
358
  async createJob(caller, input) {
301
359
  const request = parse(CreateJobInputSchema, input, 'Cannot create the job');
302
360
  this.checkBody(request.body);
361
+ const handover = request.recipe ? undefined : await this.handoverFor(caller, request);
362
+ const withContext = handover ? `${request.body}${HANDOVER_GAP}${handover}` : request.body;
363
+ const body = withContext.length <= this.limits.maxBodyLength ? withContext : request.body;
303
364
  const outcome = await this.asCaller(caller, async (tx) => {
304
365
  const from = this.requireCaller(caller);
366
+ this.checkOwnId(request.letterId, from);
305
367
  if (request.letterId) {
306
368
  const sent = this.store.getLetter(request.letterId);
307
369
  if (sent) {
308
- if (sent.kind !== 'task' || sent.from !== from.name || sent.body !== request.body) {
370
+ if (sent.kind !== 'task' ||
371
+ sent.from !== from.name ||
372
+ this.taskText(sent) !== request.body) {
309
373
  throw new BridgeError('invalid_letter', `The letter id ${request.letterId} belongs to another letter. Give a new job a new id`, { letter: request.letterId });
310
374
  }
311
375
  return { job: this.requireJob(sent.job).job, letter: sent, duplicate: true };
312
376
  }
313
377
  }
378
+ if (request.recipe && this.conductors().length === 0) {
379
+ throw new BridgeError('invalid_input', NO_CONDUCTOR, { recipe: request.recipe.name });
380
+ }
314
381
  const resolution = resolveAddress(this.store, request.to, {
315
382
  project: from.project,
316
383
  caller: from.name,
317
384
  now: this.now(),
318
385
  canSpawn: (harness) => this.adapters.get(harness)?.createSession !== undefined,
319
- fresh: request.worktree === true,
386
+ fresh: request.worktree === true || request.recipe !== undefined,
320
387
  });
388
+ this.checkRecipeAsked(resolution, request.recipe);
389
+ if (this.closing && resolution.kind === 'spawn') {
390
+ throw new BridgeError('not_running', 'The bridge dispatcher is closing and starts no session now. Hand the job over again when it runs');
391
+ }
321
392
  const carriedOut = this.store
322
393
  .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
323
394
  .flatMap((task) => jobOf(task) ?? []);
@@ -334,6 +405,8 @@ export class BridgeDispatcher extends EventEmitter {
334
405
  let depth;
335
406
  try {
336
407
  depth = nextDepth(parent?.depth, this.limits);
408
+ if (request.recipe)
409
+ nextDepth(depth, this.limits);
337
410
  }
338
411
  catch (error) {
339
412
  if (!(error instanceof BridgeError))
@@ -350,9 +423,7 @@ export class BridgeDispatcher extends EventEmitter {
350
423
  return new Refusal(error);
351
424
  }
352
425
  const budget = resolveBudget(request.budget, this.limits);
353
- const cwd = request.cwd
354
- ? canonicalPath(isAbsolute(request.cwd) ? request.cwd : resolvePath(from.cwd, request.cwd))
355
- : from.cwd;
426
+ const cwd = jobFolder(from, request.cwd);
356
427
  if (!isInside(from.project, cwd) && !isInside(findCheckoutRoot(from.cwd), cwd)) {
357
428
  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 });
358
429
  }
@@ -401,6 +472,8 @@ export class BridgeDispatcher extends EventEmitter {
401
472
  to: to.name,
402
473
  project: from.project,
403
474
  cwd,
475
+ ...(body !== request.body && { taskLength: request.body.length }),
476
+ ...(request.recipe && { recipe: request.recipe }),
404
477
  ...(request.worktree && { isolation: 'worktree' }),
405
478
  checks: request.checks ?? [],
406
479
  budget,
@@ -411,7 +484,7 @@ export class BridgeDispatcher extends EventEmitter {
411
484
  deadlineAt: this.iso(Math.min(now + budget.durationMs, parent ? Date.parse(parent.deadlineAt) : Infinity)),
412
485
  };
413
486
  const firstLetterId = request.letterId ?? this.letterId();
414
- const history = userMessage(forHistory(request.body, firstLetterId));
487
+ const history = userMessage(forHistory(body, firstLetterId));
415
488
  const task = await this.tasks.createTask(history, undefined, {
416
489
  agentName: to.name,
417
490
  metadata: { [BRIDGE_JOB_KEY]: record },
@@ -428,7 +501,7 @@ export class BridgeDispatcher extends EventEmitter {
428
501
  kind: 'task',
429
502
  from: from.name,
430
503
  to: to.name,
431
- body: request.body,
504
+ body,
432
505
  replyDueAt: this.iso(now + budget.replyTimeoutMs),
433
506
  });
434
507
  if (resolution.kind === 'spawn') {
@@ -462,6 +535,7 @@ export class BridgeDispatcher extends EventEmitter {
462
535
  const changes = request.kind === 'report' ? await this.changesAtReport(request.job) : undefined;
463
536
  const outcome = await this.asCaller(caller, async (tx) => {
464
537
  const from = this.requireCaller(caller);
538
+ this.checkOwnId(request.id, from);
465
539
  if (request.id) {
466
540
  const sent = this.store.getLetter(request.id);
467
541
  if (sent) {
@@ -552,7 +626,7 @@ export class BridgeDispatcher extends EventEmitter {
552
626
  await this.pickUp(tx, job);
553
627
  const forPerson = rights === 'ask' && this.person !== undefined;
554
628
  const refused = rights === 'deny'
555
- ? `The rules of ${job.from} forbid this, so it is refused`
629
+ ? `The rules of ${this.ruledBy(job)} forbid this, so it is refused`
556
630
  : rights === 'ask' && !forPerson
557
631
  ? 'Only the person can allow this, and this bridge has no way to reach them, so it is refused'
558
632
  : undefined;
@@ -569,7 +643,8 @@ export class BridgeDispatcher extends EventEmitter {
569
643
  ...(request.verdict && { verdict: request.verdict }),
570
644
  ...(forPerson && { needsPerson: true, personAskedAt: this.iso(now) }),
571
645
  ...(expectationOf(request.kind) === 'reply' &&
572
- !refused && {
646
+ !refused &&
647
+ !this.conducts(this.store.getAgent(to)) && {
573
648
  replyDueAt: this.iso(now + (forPerson ? this.limits.personReplyTimeoutMs : job.budget.replyTimeoutMs)),
574
649
  }),
575
650
  });
@@ -597,6 +672,8 @@ export class BridgeDispatcher extends EventEmitter {
597
672
  if (changes && job.worktree && !job.worktree.end) {
598
673
  await this.patchRecord(job.taskId, { changes });
599
674
  }
675
+ if (request.findings)
676
+ await this.patchRecord(job.taskId, { findings: request.findings });
600
677
  if (state === 'completed' && job.checks.length > 0) {
601
678
  this.store.updateLetter(letter.id, { state: 'held' });
602
679
  await this.patchRecord(job.taskId, {
@@ -607,6 +684,19 @@ export class BridgeDispatcher extends EventEmitter {
607
684
  this.closeLetters(tx, job.number, letter.id);
608
685
  await this.stopWaiting(job.number, now, false);
609
686
  await this.cancelChildren(tx, job);
687
+ if (this.board) {
688
+ for (const lesson of request.lessons ?? []) {
689
+ tx.notes.push({
690
+ kind: 'lesson',
691
+ text: lesson,
692
+ project: job.project,
693
+ source: { by: from.name, job: job.number, at: this.iso(now) },
694
+ });
695
+ }
696
+ if (!(state === 'completed' && job.checks.length > 0)) {
697
+ this.noteOutcome(tx, job.number, request.body);
698
+ }
699
+ }
610
700
  }
611
701
  else if (isAssignee && NEEDS_ANSWER.includes(request.kind)) {
612
702
  await this.transition(tx, job.number, 'input-required', forHistory(request.body, letter.id));
@@ -892,8 +982,10 @@ export class BridgeDispatcher extends EventEmitter {
892
982
  /**
893
983
  * What the rules of the agent that handed a job over make of a call. A job handed over from
894
984
  * inside a job is bound by every agent up the chain: the call is theirs to allow only when it
895
- * is each one's, and forbidden when any of them may not make it. A judge that throws, and a
896
- * bridge without one, leave the call to the person: nothing is allowed by accident.
985
+ * is each one's, and forbidden when any of them may not make it. The conductor of a recipe has
986
+ * no rules of its own: a job it handed out is judged by the rules of whoever started the
987
+ * recipe, and on up. A judge that throws, and a bridge without one, leave the call to the
988
+ * person: nothing is allowed by accident.
897
989
  */
898
990
  async rightsFor(number, ask) {
899
991
  if (!this.rights)
@@ -904,12 +996,18 @@ export class BridgeDispatcher extends EventEmitter {
904
996
  const job = this.jobIfAny(at);
905
997
  if (!job)
906
998
  return 'ask';
907
- const said = await this.rights({ job, delegator: this.store.getAgent(job.from), ask });
999
+ const delegator = this.store.getAgent(job.from);
1000
+ at = job.parent;
1001
+ if (this.conducts(delegator)) {
1002
+ if (at === undefined)
1003
+ return 'ask';
1004
+ continue;
1005
+ }
1006
+ const said = await this.rights({ job, delegator, ask });
908
1007
  if (said === 'deny')
909
1008
  return 'deny';
910
1009
  if (said === 'ask')
911
1010
  rights = 'ask';
912
- at = job.parent;
913
1011
  }
914
1012
  }
915
1013
  catch (error) {
@@ -953,17 +1051,51 @@ export class BridgeDispatcher extends EventEmitter {
953
1051
  * from inside it waits for them.
954
1052
  */
955
1053
  waitsForPerson(number) {
956
- const own = this.store.countLetters({
957
- job: number,
958
- needsPerson: true,
959
- states: ['queued', 'delivered', 'read'],
960
- });
961
- if (own > 0)
1054
+ if (this.asksPerson(number))
962
1055
  return true;
963
- return this.store.jobTasks({ parent: number, states: ACTIVE_JOB_STATES }).some((task) => {
1056
+ const below = this.store
1057
+ .jobTasks({ parent: number, states: ACTIVE_JOB_STATES })
1058
+ .some((task) => {
964
1059
  const child = jobOf(task);
965
1060
  return child !== undefined && this.waitsForPerson(child.number);
966
1061
  });
1062
+ if (below)
1063
+ return true;
1064
+ const recipe = this.recipeAbove(number);
1065
+ return recipe !== undefined && this.asksPerson(recipe.number);
1066
+ }
1067
+ /** Whether a letter of the job itself waits for the person. */
1068
+ asksPerson(number) {
1069
+ return (this.store.countLetters({
1070
+ job: number,
1071
+ needsPerson: true,
1072
+ states: ['queued', 'delivered', 'read'],
1073
+ }) > 0);
1074
+ }
1075
+ /**
1076
+ * The recipe a job is a step of, while it runs. A question of a step reaches the person as a
1077
+ * letter of the recipe's job, which the conductor passed on, so a step waits with its recipe.
1078
+ */
1079
+ recipeAbove(number) {
1080
+ const job = this.jobIfAny(number);
1081
+ const parent = job?.parent === undefined ? undefined : this.jobIfAny(job.parent);
1082
+ if (!parent || isFinishedJobState(parent.state))
1083
+ return undefined;
1084
+ return this.conducts(this.store.getAgent(parent.to)) ? parent : undefined;
1085
+ }
1086
+ /**
1087
+ * The jobs that wait for the person with a job: those it is part of, and for the job of a
1088
+ * recipe its steps that run.
1089
+ */
1090
+ waitingWith(number) {
1091
+ const chain = this.chainOf(number);
1092
+ const own = chain.find((job) => job.number === number);
1093
+ if (!own || !this.conducts(this.store.getAgent(own.to)))
1094
+ return chain;
1095
+ const steps = this.store
1096
+ .jobTasks({ parent: number, states: ACTIVE_JOB_STATES })
1097
+ .flatMap((task) => jobOf(task) ?? []);
1098
+ return [...chain, ...steps];
967
1099
  }
968
1100
  /** A job and the jobs it was handed over from inside of, the nearest first, while they run. */
969
1101
  chainOf(number) {
@@ -983,7 +1115,7 @@ export class BridgeDispatcher extends EventEmitter {
983
1115
  * of them is failed by its deadline while the wait lasts.
984
1116
  */
985
1117
  async startWaiting(number, now) {
986
- for (const job of this.chainOf(number)) {
1118
+ for (const job of this.waitingWith(number)) {
987
1119
  if (!job.personWaitSince) {
988
1120
  await this.patchRecord(job.taskId, { personWaitSince: this.iso(now) });
989
1121
  }
@@ -998,7 +1130,7 @@ export class BridgeDispatcher extends EventEmitter {
998
1130
  * that still waits for another letter goes on waiting.
999
1131
  */
1000
1132
  async stopWaiting(number, now, answered) {
1001
- for (const job of this.chainOf(number)) {
1133
+ for (const job of this.waitingWith(number)) {
1002
1134
  if (!job.personWaitSince)
1003
1135
  continue;
1004
1136
  const waited = Math.max(0, now - Date.parse(job.personWaitSince));
@@ -1295,6 +1427,44 @@ export class BridgeDispatcher extends EventEmitter {
1295
1427
  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
1428
  }
1297
1429
  }
1430
+ /**
1431
+ * Refuses a letter id of the kind the conductor names its own letters by, from anybody else:
1432
+ * a recipe finds the job of a step again by that id, so nobody else may take one.
1433
+ */
1434
+ checkOwnId(id, from) {
1435
+ if (id === undefined || !RECIPE_LETTER_ID.test(id) || this.conducts(from))
1436
+ return;
1437
+ throw new BridgeError('invalid_letter', 'Letter ids that start with "recipe-" or "relay-" are kept for the recipes of the bridge. Give the letter another id', { letter: id });
1438
+ }
1439
+ /** The harness words of the adapters that carry jobs out by recipes. */
1440
+ conductors() {
1441
+ return [...this.adapters.values()]
1442
+ .filter((adapter) => adapter.recipeProblem !== undefined)
1443
+ .map((adapter) => adapter.harness);
1444
+ }
1445
+ /**
1446
+ * Refuses a recipe the conductor cannot start, and a job for the conductor that names none.
1447
+ * Every recipe gets a conductor of its own, so a recipe is addressed by the harness word of
1448
+ * the conductor, never by the name of one that runs.
1449
+ */
1450
+ checkRecipeAsked(resolution, recipe) {
1451
+ const harness = resolution.kind === 'agent' ? resolution.agent.harness : resolution.harness;
1452
+ const adapter = this.adapters.get(harness);
1453
+ if (!recipe) {
1454
+ if (!adapter?.recipeProblem)
1455
+ return;
1456
+ throw new BridgeError('invalid_input', `${harness} carries out recipes only: name the recipe to start`, { harness });
1457
+ }
1458
+ if (!adapter?.recipeProblem || resolution.kind === 'agent') {
1459
+ const conductors = this.conductors();
1460
+ throw new BridgeError('invalid_input', conductors.length > 0
1461
+ ? `A recipe is started by handing its job to the conductor of the bridge: address it to ${conductors.join(' or ')}`
1462
+ : NO_CONDUCTOR, { recipe: recipe.name });
1463
+ }
1464
+ const problem = adapter.recipeProblem(recipe);
1465
+ if (problem)
1466
+ throw new BridgeError('invalid_input', problem, { recipe: recipe.name });
1467
+ }
1298
1468
  /**
1299
1469
  * Where a session that is about to be started for a job works: the worktree of the job, made
1300
1470
  * now, when the job asked for one. Resolves with the job as it is once it has its worktree and
@@ -1411,8 +1581,8 @@ export class BridgeDispatcher extends EventEmitter {
1411
1581
  results.push(skippedCheck(check, !this.rights
1412
1582
  ? 'this bridge has no rules to judge a command by, and runs none without them'
1413
1583
  : 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`));
1584
+ ? `the rules of ${this.ruledBy(job)} forbid the command`
1585
+ : `the rules of ${this.ruledBy(job)} do not allow the command without asking. Allow it in the settings of the project, or run it yourself`));
1416
1586
  continue;
1417
1587
  }
1418
1588
  results.push(await runCheck(check, {
@@ -1441,6 +1611,7 @@ export class BridgeDispatcher extends EventEmitter {
1441
1611
  });
1442
1612
  this.journal(tx, { type: 'job.verified', job: number, data: { verified, summary } });
1443
1613
  const report = this.store.getLetter(fresh.checking.letter);
1614
+ this.noteOutcome(tx, number, report?.body);
1444
1615
  if (report?.state === 'held') {
1445
1616
  this.store.updateLetter(report.id, { state: 'queued' });
1446
1617
  tx.wake.add(report.to);
@@ -1463,7 +1634,8 @@ export class BridgeDispatcher extends EventEmitter {
1463
1634
  }
1464
1635
  /**
1465
1636
  * 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.
1637
+ * agents of the job, and for whoever started the recipe it is a step of, while it runs and
1638
+ * after, as long as its worktree is there.
1467
1639
  *
1468
1640
  * @throws BridgeError `unknown_job`, `not_a_party`, `no_worktree` for a job without a worktree
1469
1641
  * of its own or whose work was taken or dropped already
@@ -1473,7 +1645,7 @@ export class BridgeDispatcher extends EventEmitter {
1473
1645
  const { job, worktree } = await this.asCaller(caller, async () => {
1474
1646
  const agent = this.requireCaller(caller);
1475
1647
  const found = this.requireJob(request.job).job;
1476
- if (agent.name !== found.from && agent.name !== found.to) {
1648
+ if (agent.name !== found.to && !this.handedOver(agent.name, found)) {
1477
1649
  throw new BridgeError('not_a_party', `Job ${found.number} is between ${found.from} and ${found.to}`, { job: found.number });
1478
1650
  }
1479
1651
  return { job: found, worktree: this.requireWorktree(found) };
@@ -1499,8 +1671,8 @@ export class BridgeDispatcher extends EventEmitter {
1499
1671
  };
1500
1672
  }
1501
1673
  /**
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
1674
+ * Takes the work of a finished job out of its worktree, as the agent that handed the job over,
1675
+ * or that started the recipe the job is a step of, once the recipe has reported. The changes, committed there or not, come into the checkout the caller works in as one
1504
1676
  * change that is staged and not committed: the commit is the caller's to make. With
1505
1677
  * `asBranch` they are left as a branch instead, for work that goes on as a pull request. The
1506
1678
  * worktree is removed either way. When the changes would leave files in conflict nothing is
@@ -1508,8 +1680,8 @@ export class BridgeDispatcher extends EventEmitter {
1508
1680
  * never merges into a branch nobody is working on.
1509
1681
  *
1510
1682
  * @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`
1683
+ * work), `invalid_input` (the job still runs, its checks do, the recipe it is a step of does,
1684
+ * the caller is in another repository, or git refused), `no_worktree`
1513
1685
  */
1514
1686
  async accept(caller, input) {
1515
1687
  const request = parse(AcceptInputSchema, input, 'Cannot take the work');
@@ -1565,11 +1737,12 @@ export class BridgeDispatcher extends EventEmitter {
1565
1737
  });
1566
1738
  }
1567
1739
  /**
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.
1740
+ * Drops the work of a finished job, as the agent that handed the job over, or that started the
1741
+ * recipe the job is a step of: its worktree and the branch of it are removed with everything
1742
+ * in them.
1570
1743
  *
1571
- * @throws BridgeError `unknown_job`, `not_a_party`, `invalid_input` (the job still runs, or
1572
- * its checks do), `no_worktree`
1744
+ * @throws BridgeError `unknown_job`, `not_a_party`, `invalid_input` (the job still runs, its
1745
+ * checks do, or the recipe it is a step of does), `no_worktree`
1573
1746
  */
1574
1747
  async reject(caller, input) {
1575
1748
  const request = parse(RejectInputSchema, input, 'Cannot drop the work');
@@ -1613,8 +1786,8 @@ export class BridgeDispatcher extends EventEmitter {
1613
1786
  requireTaker(caller, number, what) {
1614
1787
  const agent = this.requireCaller(caller);
1615
1788
  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 });
1789
+ if (!this.handedOver(agent.name, job)) {
1790
+ throw new BridgeError('not_a_party', `Only ${job.from}, who handed job ${job.number} over, or whoever handed over a job it is part of, can ${what} its work`, { job: job.number });
1618
1791
  }
1619
1792
  if (!isFinishedJobState(job.state)) {
1620
1793
  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 });
@@ -1622,8 +1795,66 @@ export class BridgeDispatcher extends EventEmitter {
1622
1795
  if (job.checking) {
1623
1796
  throw new BridgeError('invalid_input', `The checks of job ${job.number} still run. Its report comes with what they show`, { job: job.number });
1624
1797
  }
1798
+ const recipe = job.parent !== undefined && this.conducts(this.store.getAgent(job.from))
1799
+ ? this.jobIfAny(job.parent)
1800
+ : undefined;
1801
+ if (recipe && !isFinishedJobState(recipe.state)) {
1802
+ throw new BridgeError('invalid_input', `Job ${job.number} is a step of the recipe of job ${recipe.number}, which still runs: later steps may work in the same worktree. Wait for the report of job ${recipe.number}, or cancel it first`, { job: job.number, recipe: recipe.number });
1803
+ }
1804
+ const user = this.workingOn(job);
1805
+ if (user) {
1806
+ throw new BridgeError('invalid_input', `Job ${user.number} still works on what job ${job.number} left in its worktree. Wait for its report, or cancel it first`, { job: job.number, by: user.number });
1807
+ }
1625
1808
  return { job, worktree: this.requireWorktree(job), agent };
1626
1809
  }
1810
+ /**
1811
+ * A job in progress that works on what another job left in its worktree: one that is done in
1812
+ * that worktree, such as the review of the work or its fixes, and a recipe whose input names
1813
+ * the job as the one it works on. The worktree stays while there is one.
1814
+ */
1815
+ workingOn(job) {
1816
+ const worktree = this.liveWorktree(job);
1817
+ return this.store
1818
+ .jobTasks({ states: ACTIVE_JOB_STATES, project: job.project })
1819
+ .flatMap((task) => jobOf(task) ?? [])
1820
+ .find((other) => {
1821
+ if (other.number === job.number)
1822
+ return false;
1823
+ if (worktree && isInside(worktree.path, other.cwd))
1824
+ return true;
1825
+ const input = other.recipe?.input;
1826
+ return (typeof input === 'object' &&
1827
+ input !== null &&
1828
+ input.job === job.number);
1829
+ });
1830
+ }
1831
+ /**
1832
+ * Whether an agent handed a job over, or started the recipe the job is a step of: a job the
1833
+ * conductor hands out for an agent is that agent's to look at and take, as the recipe is its
1834
+ * own. A job another agent handed over from inside a job is that agent's alone.
1835
+ */
1836
+ handedOver(agent, job) {
1837
+ for (let at = job; at;) {
1838
+ if (at.from === agent)
1839
+ return true;
1840
+ if (at.parent === undefined || !this.conducts(this.store.getAgent(at.from)))
1841
+ return false;
1842
+ at = this.jobIfAny(at.parent);
1843
+ }
1844
+ return false;
1845
+ }
1846
+ /**
1847
+ * The agent whose rules bind a job: whoever handed it over, and for a step of a recipe
1848
+ * whoever started the recipe, since the conductor has no rules of its own.
1849
+ */
1850
+ ruledBy(job) {
1851
+ for (let at = job; at;) {
1852
+ if (at.parent === undefined || !this.conducts(this.store.getAgent(at.from)))
1853
+ return at.from;
1854
+ at = this.jobIfAny(at.parent);
1855
+ }
1856
+ return job.from;
1857
+ }
1627
1858
  /** One taking, dropping or putting away of a job's worktree at a time. */
1628
1859
  async whileTaking(number, work) {
1629
1860
  if (this.taking.has(number)) {
@@ -1703,7 +1934,8 @@ export class BridgeDispatcher extends EventEmitter {
1703
1934
  .flatMap((task) => jobOf(task) ?? [])
1704
1935
  .filter((job) => this.liveWorktree(job) !== undefined &&
1705
1936
  !job.checking &&
1706
- now - Date.parse(job.endedAt ?? job.updatedAt) >= this.limits.worktreeKeepMs);
1937
+ now - Date.parse(job.endedAt ?? job.updatedAt) >= this.limits.worktreeKeepMs &&
1938
+ this.workingOn(job) === undefined);
1707
1939
  for (const job of left) {
1708
1940
  if (this.taking.has(job.number))
1709
1941
  continue;
@@ -1761,6 +1993,287 @@ export class BridgeDispatcher extends EventEmitter {
1761
1993
  }
1762
1994
  });
1763
1995
  }
1996
+ /** The board of this bridge, or the refusal of a bridge that was given none. */
1997
+ requireBoard() {
1998
+ if (this.board)
1999
+ return this.board;
2000
+ throw new BridgeError('no_board', 'This bridge keeps no notes: whoever runs it gave it no board to keep them on');
2001
+ }
2002
+ /** The project a call about the board is for: the caller's own, or the one the person names. */
2003
+ boardProject(agent, named) {
2004
+ if (agent)
2005
+ return agent.project;
2006
+ if (named)
2007
+ return canonicalPath(findProjectRoot(named));
2008
+ throw new BridgeError('invalid_input', 'Say which project the note is for');
2009
+ }
2010
+ /** The jobs whose own notes a caller may see: an agent's are those it is a party of. */
2011
+ jobsSeenBy(agent, project) {
2012
+ return this.store
2013
+ .jobTasks(agent ? { party: agent.name } : { project })
2014
+ .flatMap((task) => jobOf(task) ?? [])
2015
+ .filter((job) => job.project === project)
2016
+ .map((job) => job.number);
2017
+ }
2018
+ /**
2019
+ * Puts a note on the board of a project, for the agents that work there to find: a fact, or
2020
+ * what a job taught. The note carries who said it, on which job and when. `caller` is the
2021
+ * agent that says it, or `null` for the person, who names the project. A note kept to a job
2022
+ * (`jobOnly`) is seen by the two agents of that job only.
2023
+ *
2024
+ * @throws BridgeError `no_board`, `not_registered`, `unknown_job`, `not_a_party` (the job named
2025
+ * is not the caller's), `invalid_input`
2026
+ */
2027
+ async remember(caller, input) {
2028
+ const request = parse(RememberInputSchema, input, 'Cannot remember that');
2029
+ const board = this.requireBoard();
2030
+ const fact = await this.enqueue(async () => {
2031
+ const agent = caller === null ? undefined : this.requireCaller(caller);
2032
+ let project = this.boardProject(agent, request.project);
2033
+ let job = request.job;
2034
+ if (job !== undefined) {
2035
+ const found = this.requireJob(job).job;
2036
+ const party = agent ? agent.name === found.from || agent.name === found.to : undefined;
2037
+ if (party)
2038
+ project = found.project;
2039
+ if (found.project !== project || party === false) {
2040
+ 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 });
2041
+ }
2042
+ }
2043
+ else if (agent) {
2044
+ const carried = this.store
2045
+ .jobTasks({ to: agent.name, states: ACTIVE_JOB_STATES })
2046
+ .flatMap((task) => jobOf(task) ?? []);
2047
+ if (carried.length === 1)
2048
+ job = carried[0].number;
2049
+ }
2050
+ return {
2051
+ kind: request.kind ?? 'fact',
2052
+ text: request.text,
2053
+ project,
2054
+ ...(request.jobOnly && job !== undefined && { job }),
2055
+ source: {
2056
+ by: agent?.name ?? PERSON,
2057
+ ...(job !== undefined && { job }),
2058
+ at: this.iso(),
2059
+ },
2060
+ };
2061
+ });
2062
+ const kept = await board.remember(fact);
2063
+ await this.journalNote(kept, fact.source.by);
2064
+ return kept;
2065
+ }
2066
+ /**
2067
+ * Writes down that a note went on the board, and who said it this time. Everybody can read
2068
+ * the journal, so the text of a note kept to one job is left out of it.
2069
+ */
2070
+ async journalNote(kept, by) {
2071
+ await this.mutate(async (tx) => {
2072
+ this.journal(tx, {
2073
+ type: 'fact.remembered',
2074
+ agent: by,
2075
+ ...(kept.source.job !== undefined && { job: kept.source.job }),
2076
+ data: {
2077
+ id: kept.id,
2078
+ kind: kept.kind,
2079
+ project: kept.project,
2080
+ ...(kept.job === undefined && { text: kept.text }),
2081
+ ...(kept.source.by !== by && { saidBefore: kept.source.by }),
2082
+ },
2083
+ });
2084
+ });
2085
+ }
2086
+ /**
2087
+ * Looks at the board of a project: the notes that fit `text` best, or the newest. An agent
2088
+ * sees the notes of its project and those kept to the jobs it is a party of, the person
2089
+ * (`caller` is `null`) every note of the project they name.
2090
+ *
2091
+ * @throws BridgeError `no_board`, `not_registered`, `invalid_input`
2092
+ */
2093
+ async recall(caller, input = {}) {
2094
+ const request = parse(RecallInputSchema, input, 'Cannot look at the board');
2095
+ const board = this.requireBoard();
2096
+ const query = await this.enqueue(async () => {
2097
+ const agent = caller === null ? undefined : this.requireCaller(caller);
2098
+ const project = this.boardProject(agent, request.project);
2099
+ return { project, jobs: this.jobsSeenBy(agent, project) };
2100
+ });
2101
+ return board.recall({
2102
+ ...query,
2103
+ ...(request.text && { text: request.text }),
2104
+ ...(request.kinds && { kinds: request.kinds }),
2105
+ ...(request.limit !== undefined && { limit: request.limit }),
2106
+ });
2107
+ }
2108
+ /**
2109
+ * Lets a note of the board go: it is found no more, and is not deleted. An agent lets go what
2110
+ * it said itself, the person (`caller` is `null`) any note of the project they name.
2111
+ *
2112
+ * @throws BridgeError `no_board`, `not_registered`, `invalid_input` (no such note there),
2113
+ * `not_a_party` (the note is another's)
2114
+ */
2115
+ async forget(caller, input) {
2116
+ const request = parse(ForgetInputSchema, input, 'Cannot forget that');
2117
+ const board = this.requireBoard();
2118
+ const { agent, project, jobs } = await this.enqueue(async () => {
2119
+ const found = caller === null ? undefined : this.requireCaller(caller);
2120
+ const where = this.boardProject(found, request.project);
2121
+ return { agent: found, project: where, jobs: this.jobsSeenBy(found, where) };
2122
+ });
2123
+ const fact = await board.find(request.id);
2124
+ const seen = fact?.project === project && (fact.job === undefined || jobs.includes(fact.job));
2125
+ if (!fact || !seen) {
2126
+ throw new BridgeError('invalid_input', `There is no note ${request.id} on the board of ${project}`, {
2127
+ id: request.id,
2128
+ });
2129
+ }
2130
+ if (agent && fact.source.by !== agent.name) {
2131
+ 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 });
2132
+ }
2133
+ await board.forget(fact.id);
2134
+ await this.mutate(async (tx) => {
2135
+ this.journal(tx, {
2136
+ type: 'fact.forgotten',
2137
+ agent: agent?.name ?? PERSON,
2138
+ data: { id: fact.id, kind: fact.kind, project: fact.project, by: fact.source.by },
2139
+ });
2140
+ });
2141
+ return fact;
2142
+ }
2143
+ /** The text of a job as its caller wrote it: its first letter without what the bridge added. */
2144
+ taskText(first, job) {
2145
+ const length = (job ?? this.jobIfAny(first.job))?.taskLength;
2146
+ return length === undefined ? first.body : first.body.slice(0, length);
2147
+ }
2148
+ /**
2149
+ * Whether the rules of an agent let it read a file without asking: its own, and those of every
2150
+ * agent up the chain of the jobs it carries out. The conductor of a recipe reads what whoever
2151
+ * started the recipe may. True on a bridge that was given no judge: what an agent names in its
2152
+ * own project it could read itself.
2153
+ */
2154
+ async mayRead(from, cwd, path) {
2155
+ if (!this.rights)
2156
+ return true;
2157
+ const ask = { tool: 'Read', access: 'read', paths: [path], cwd };
2158
+ try {
2159
+ const now = this.iso();
2160
+ const own = this.conducts(from)
2161
+ ? 'allow'
2162
+ : await this.rights({
2163
+ job: {
2164
+ number: 0,
2165
+ taskId: '',
2166
+ title: '',
2167
+ from: from.name,
2168
+ to: from.name,
2169
+ project: from.project,
2170
+ cwd,
2171
+ checks: [],
2172
+ budget: this.limits.budget,
2173
+ lettersUsed: 0,
2174
+ depth: 1,
2175
+ createdAt: now,
2176
+ deadlineAt: now,
2177
+ state: 'submitted',
2178
+ updatedAt: now,
2179
+ },
2180
+ delegator: from,
2181
+ ask,
2182
+ });
2183
+ if (own !== 'allow')
2184
+ return false;
2185
+ const carried = await this.enqueue(async () => this.store
2186
+ .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
2187
+ .flatMap((task) => jobOf(task) ?? []));
2188
+ if (this.conducts(from) && carried.length === 0)
2189
+ return false;
2190
+ for (const job of carried) {
2191
+ if ((await this.rightsFor(job.number, ask)) !== 'allow')
2192
+ return false;
2193
+ }
2194
+ return true;
2195
+ }
2196
+ catch (error) {
2197
+ this.onError(asError(error));
2198
+ return false;
2199
+ }
2200
+ }
2201
+ /**
2202
+ * The block the bridge puts under the text of a job, see `buildHandover`: what the caller
2203
+ * named, the lines of the files it pointed at, and the notes of the board that fit the job.
2204
+ * Undefined when there is nothing to add. It never fails the hand-over and never holds it up
2205
+ * for long: what cannot be read or found in time is left out, and the block is kept small
2206
+ * enough for the letter to take it.
2207
+ */
2208
+ async handoverFor(caller, request) {
2209
+ const from = await this.enqueue(async () => this.store.getAgent(caller));
2210
+ if (!from)
2211
+ return undefined;
2212
+ const room = Math.floor((this.limits.maxBodyLength - request.body.length - HANDOVER_GAP.length) / 4);
2213
+ const budget = Math.min(request.contextTokens ?? this.limits.contextTokens, room);
2214
+ if (budget <= 0)
2215
+ return undefined;
2216
+ const build = async () => {
2217
+ const about = `${request.title ?? ''}\n${request.body}`.slice(0, ABOUT_CHARS);
2218
+ const board = this.board;
2219
+ const [facts, earlier] = board
2220
+ ? await Promise.all([
2221
+ board.recall({ project: from.project, text: about, kinds: ['fact'], limit: 8 }),
2222
+ earlierLike(board, from.project, about),
2223
+ ])
2224
+ : [[], []];
2225
+ return buildHandover(request.context, {
2226
+ from: from.name,
2227
+ cwd: from.cwd,
2228
+ roots: [from.project, findCheckoutRoot(from.cwd)],
2229
+ top: findCheckoutRoot(from.cwd),
2230
+ mayRead: (path) => this.mayRead(from, from.cwd, path),
2231
+ facts,
2232
+ earlier,
2233
+ }, budget);
2234
+ };
2235
+ try {
2236
+ return await within(build(), this.limits.contextTimeoutMs, 'Putting the context of the job together');
2237
+ }
2238
+ catch (error) {
2239
+ this.onError(asError(error));
2240
+ return undefined;
2241
+ }
2242
+ }
2243
+ /**
2244
+ * Notes how a job ended on the board of its project, in the bridge's own name: who did it for
2245
+ * whom, how it ended, what its checks showed and the start of what was reported. A later job
2246
+ * like it finds the note in its handover.
2247
+ */
2248
+ noteOutcome(tx, number, reported) {
2249
+ if (!this.board)
2250
+ return;
2251
+ const { job } = this.requireJob(number);
2252
+ tx.notes.push({
2253
+ kind: 'outcome',
2254
+ text: outcomeText(job, reported),
2255
+ project: job.project,
2256
+ source: { by: BRIDGE_SENDER, job: job.number, at: this.iso() },
2257
+ });
2258
+ }
2259
+ /** Puts on the board what a call left for it, after the call is stored. */
2260
+ keepNotes(notes) {
2261
+ const board = this.board;
2262
+ if (!board || notes.length === 0)
2263
+ return;
2264
+ this.track((async () => {
2265
+ for (const note of notes) {
2266
+ try {
2267
+ const kept = await board.remember(note);
2268
+ if (kept.kind !== 'outcome')
2269
+ await this.journalNote(kept, note.source.by);
2270
+ }
2271
+ catch (error) {
2272
+ this.onError(asError(error));
2273
+ }
2274
+ }
2275
+ })());
2276
+ }
1764
2277
  /** @throws BridgeError `unknown_job` */
1765
2278
  async job(number) {
1766
2279
  return this.enqueue(async () => this.requireJob(number).job);
@@ -1799,6 +2312,46 @@ export class BridgeDispatcher extends EventEmitter {
1799
2312
  return fitting(this.store.readJournal({ ...request, limit: request.limit ?? DEFAULT_LIST_LIMIT }), size);
1800
2313
  });
1801
2314
  }
2315
+ /**
2316
+ * The harnesses the bridge can start a session of for a job. The conductor of recipes is none
2317
+ * of them: it takes a recipe, not a job.
2318
+ */
2319
+ async startable() {
2320
+ return [...this.adapters.values()]
2321
+ .filter((adapter) => adapter.createSession !== undefined && !adapter.recipeProblem)
2322
+ .map((adapter) => adapter.harness);
2323
+ }
2324
+ /**
2325
+ * Whether an agent takes a letter by itself right now: it waits for its mail, or its harness
2326
+ * hands the letter over and wakes the session for it.
2327
+ */
2328
+ async wakes(name) {
2329
+ const agent = await this.enqueue(async () => this.store.getAgent(name));
2330
+ if (agent?.status !== 'active')
2331
+ return false;
2332
+ if (this.waiters.has(agent.name))
2333
+ return true;
2334
+ const adapter = this.adapters.get(agent.harness);
2335
+ if (!adapter?.deliver || !adapter.capabilities.push)
2336
+ return false;
2337
+ if (!adapter.wakesFor)
2338
+ return true;
2339
+ try {
2340
+ return await within(adapter.wakesFor(agent), this.limits.deliveryTimeoutMs, `Asking whether ${agent.name} wakes for a letter`);
2341
+ }
2342
+ catch (error) {
2343
+ this.onError(asError(error));
2344
+ return false;
2345
+ }
2346
+ }
2347
+ /**
2348
+ * Whether an agent is a conductor: a session of an adapter that carries jobs out by recipes.
2349
+ * It has no rules of its own, and the jobs it hands out are bound by those of whoever started
2350
+ * its recipe.
2351
+ */
2352
+ conducts(agent) {
2353
+ return agent !== undefined && this.adapters.get(agent.harness)?.recipeProblem !== undefined;
2354
+ }
1802
2355
  async status() {
1803
2356
  return this.enqueue(async () => ({
1804
2357
  agents: this.store.listAgents({ statuses: ['active', 'starting'] }).length,
@@ -1806,7 +2359,7 @@ export class BridgeDispatcher extends EventEmitter {
1806
2359
  queuedLetters: this.store.countLetters({ states: ['queued'] }),
1807
2360
  adapters: [...this.adapters.keys()],
1808
2361
  startable: [...this.adapters.values()]
1809
- .filter((adapter) => adapter.createSession !== undefined)
2362
+ .filter((adapter) => adapter.createSession !== undefined && !adapter.recipeProblem)
1810
2363
  .map((adapter) => adapter.harness),
1811
2364
  waiting: [...this.waiters.keys()].sort(),
1812
2365
  }));
@@ -2076,6 +2629,7 @@ export class BridgeDispatcher extends EventEmitter {
2076
2629
  decided: new Set(),
2077
2630
  notices: [],
2078
2631
  checks: [],
2632
+ notes: [],
2079
2633
  };
2080
2634
  const result = await this.store.transaction(() => {
2081
2635
  this.assertWritable?.();
@@ -2100,6 +2654,7 @@ export class BridgeDispatcher extends EventEmitter {
2100
2654
  if (!this.closing)
2101
2655
  for (const number of tx.checks)
2102
2656
  this.startChecks(number);
2657
+ this.keepNotes(tx.notes);
2103
2658
  this.tellPerson(tx);
2104
2659
  return result;
2105
2660
  }
@@ -2247,6 +2802,7 @@ export class BridgeDispatcher extends EventEmitter {
2247
2802
  await this.patchRecord(job.taskId, { reason });
2248
2803
  this.closeLetters(tx, number);
2249
2804
  await this.stopWaiting(number, this.now(), false);
2805
+ this.noteOutcome(tx, number);
2250
2806
  const text = `Job #${number} has failed: ${reason}.`;
2251
2807
  this.systemNote(tx, job, job.from, text);
2252
2808
  this.systemNote(tx, job, job.to, `${text} Stop working on it.`);
@@ -2260,6 +2816,7 @@ export class BridgeDispatcher extends EventEmitter {
2260
2816
  await this.patchRecord(job.taskId, { reason });
2261
2817
  this.closeLetters(tx, number);
2262
2818
  await this.stopWaiting(number, this.now(), false);
2819
+ this.noteOutcome(tx, number);
2263
2820
  this.systemNote(tx, job, job.to, note);
2264
2821
  await this.cancelChildren(tx, job);
2265
2822
  }
@@ -2292,7 +2849,7 @@ export class BridgeDispatcher extends EventEmitter {
2292
2849
  if (job.cwd !== cwd || !sameAgent(job))
2293
2850
  return false;
2294
2851
  const first = this.store.listLetters({ job: job.number, kinds: ['task'], limit: 1 })[0];
2295
- return first !== undefined && normalizeBody(first.body) === wanted;
2852
+ return first !== undefined && normalizeBody(this.taskText(first, job)) === wanted;
2296
2853
  });
2297
2854
  if (same) {
2298
2855
  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 });