@a-t-h-i/bot-lobby 0.6.61 → 0.6.63

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 (101) hide show
  1. package/README.md +8 -8
  2. package/package.json +2 -1
  3. package/prompts/designer.md +25 -15
  4. package/prompts/master.md +284 -491
  5. package/prompts/panel.md +7 -0
  6. package/prompts/planner.md +15 -4
  7. package/prompts/qa.md +5 -1
  8. package/prompts/worker.md +0 -7
  9. package/scripts/builtin/affected_packages.mjs +106 -0
  10. package/scripts/builtin/check_changed.mjs +51 -0
  11. package/scripts/builtin/check_contract_breakage.mjs +118 -0
  12. package/scripts/builtin/circular_dependency_check.mjs +79 -0
  13. package/scripts/builtin/code_duplication_check.mjs +86 -0
  14. package/scripts/builtin/diff_summary.mjs +62 -0
  15. package/scripts/builtin/failure_digest.mjs +107 -0
  16. package/scripts/builtin/find_generated_files.mjs +79 -0
  17. package/scripts/builtin/find_symbol.mjs +81 -0
  18. package/scripts/builtin/find_test_fixtures.mjs +73 -0
  19. package/scripts/builtin/find_tests_for.mjs +12 -0
  20. package/scripts/builtin/lib/common.mjs +267 -0
  21. package/scripts/builtin/outline_file.mjs +77 -0
  22. package/scripts/builtin/project_commands.mjs +49 -0
  23. package/scripts/builtin/recent_changes.mjs +14 -0
  24. package/scripts/builtin/repo_map.mjs +65 -0
  25. package/scripts/builtin/run_changed_tests.mjs +48 -0
  26. package/src/delivery/transport.ts +1 -1
  27. package/src/desk/client-extension.ts +1 -31
  28. package/src/desk/ipc.ts +1 -11
  29. package/src/desk/session.ts +4 -101
  30. package/src/execution/agent-runner.ts +50 -8
  31. package/src/execution/assigned-session.ts +263 -0
  32. package/src/execution/assignment-discovery.ts +128 -0
  33. package/src/execution/assignment-policy.ts +46 -0
  34. package/src/execution/assignment.ts +175 -0
  35. package/src/execution/delegation.ts +9 -94
  36. package/src/execution/pi-runner.ts +99 -9
  37. package/src/harness/instructions.ts +1 -1
  38. package/src/index.ts +3 -0
  39. package/src/knowledge/design-record.ts +394 -0
  40. package/src/knowledge/file-notes.ts +36 -8
  41. package/src/lobby/ask.ts +6 -0
  42. package/src/lobby/exec.ts +28 -0
  43. package/src/lobby/host.ts +2 -11
  44. package/src/lobby/pi-commands.ts +83 -0
  45. package/src/lobby/planner.ts +50 -124
  46. package/src/lobby/prompts.ts +1 -7
  47. package/src/lobby/runtime.ts +2 -26
  48. package/src/lobby/service.ts +28 -27
  49. package/src/lobby/topics.ts +0 -2
  50. package/src/master/evidence-freshness.ts +96 -0
  51. package/src/master/master.ts +248 -74
  52. package/src/master/scout-cache.ts +1 -1
  53. package/src/master/scout-lock.ts +44 -0
  54. package/src/master/scout-prefetch.ts +78 -0
  55. package/src/pi/activity.ts +2 -0
  56. package/src/pi/assignment-guard.ts +157 -0
  57. package/src/pi/delegation.ts +2 -21
  58. package/src/pi/model-support.ts +0 -6
  59. package/src/pi/start-task.ts +18 -7
  60. package/src/pi/tools.ts +41 -8
  61. package/src/roles/scout.ts +3 -1
  62. package/src/roles/worker.ts +107 -5
  63. package/src/schemas/configuration.ts +11 -45
  64. package/src/schemas/findings.ts +3 -0
  65. package/src/schemas/task.ts +30 -12
  66. package/src/scripts/library.ts +31 -1
  67. package/src/scripts/pick.ts +31 -15
  68. package/src/state/archive.ts +10 -0
  69. package/src/state/checkpoint.ts +0 -1
  70. package/src/state/gitignore.ts +39 -0
  71. package/src/state/persistence.ts +56 -0
  72. package/src/state/recovery.ts +33 -1
  73. package/src/webui/api/index.ts +6 -35
  74. package/src/webui/api/retention.ts +44 -0
  75. package/src/webui/api/status.ts +5 -6
  76. package/src/webui/dev/fake-service.ts +8 -117
  77. package/src/webui/dev/fixtures.ts +2 -16
  78. package/src/webui/protocol.ts +3 -142
  79. package/src/workflow/draft-assignments.ts +118 -0
  80. package/src/workflow/workflow.ts +271 -214
  81. package/webui/dist/assets/{CodeSurface-BtzJOVyH.js → CodeSurface-CdyiJTYa.js} +1 -1
  82. package/webui/dist/assets/{TerminalView-Cz-KNWsq.js → TerminalView-D2nbR2J1.js} +1 -1
  83. package/webui/dist/assets/index-BTyu99rI.css +2 -0
  84. package/webui/dist/assets/index-BUGK22Z6.js +112 -0
  85. package/webui/dist/build.json +32 -68
  86. package/webui/dist/index.html +2 -2
  87. package/prompts/expert.md +0 -17
  88. package/prompts/goal-check.md +0 -44
  89. package/prompts/pr-review.md +0 -62
  90. package/prompts/splitter.md +0 -58
  91. package/src/execution/worker-trees.ts +0 -396
  92. package/src/lobby/issues.ts +0 -219
  93. package/src/lobby/pr-review.ts +0 -366
  94. package/src/lobby/pulls.ts +0 -250
  95. package/src/lobby/split.ts +0 -262
  96. package/src/master/goal-check.ts +0 -115
  97. package/src/webui/api/gh-error.ts +0 -17
  98. package/src/webui/api/git.ts +0 -98
  99. package/src/webui/api/issues.ts +0 -50
  100. package/webui/dist/assets/index-D5fvY8f8.js +0 -112
  101. package/webui/dist/assets/index-DFvk8ADr.css +0 -2
@@ -1,10 +1,12 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { designRecordBlock, designStanding, withoutDesignRecord } from "../knowledge/design-record.ts";
3
+ import { validateAssignment, type WorkerAssignment } from "../execution/assignment.ts";
4
+ import { join, resolve } from "node:path";
3
5
  import { profileFor, type BotLobbyConfig, type ProfileResolver } from "../schemas/configuration.ts";
4
6
  import type { Domain } from "../schemas/agent.ts";
5
7
  import type { AgentRun, ReviewResult, ScoutResult, WorkerResult } from "../schemas/findings.ts";
6
8
  import { domainSpec } from "../agents/registry.ts";
7
- import { runAgent, runParallel, watchdogOptions, type AgentRequest } from "../execution/agent-runner.ts";
9
+ import { runAgent, watchdogOptions, type AgentRequest } from "../execution/agent-runner.ts";
8
10
  import { spawnPiProcess, type ProcessRunner, type RelayAsk } from "../execution/pi-runner.ts";
9
11
  import { knowledgeFilePath, readAgentKnowledge, writeFileEnsured } from "../knowledge/store.ts";
10
12
  import { taskDir } from "../knowledge/paths.ts";
@@ -22,8 +24,10 @@ import { truncate } from "../text.ts";
22
24
  import { isScoutResultUsable, parseScoutResult, validateScoutResult } from "../roles/scout.ts";
23
25
  import { treeState } from "../execution/git.ts";
24
26
  import { toolBudgetEnv, toolBudgetNote } from "../pi/tool-budget.ts";
25
- import { recordFileNotes } from "../knowledge/file-notes.ts";
27
+ import { fileNoteHints, recordFileNotes, treePath, type FileNoteHint } from "../knowledge/file-notes.ts";
28
+ import { EvidenceFreshness, verifyEvidenceHint, type EvidenceHint, type EvidenceStatus, type FreshnessInvalidation } from "./evidence-freshness.ts";
26
29
  import { readCachedScout, scoutKey, writeCachedScout } from "./scout-cache.ts";
30
+ import { acquireScoutLock } from "./scout-lock.ts";
27
31
  import { BOARD_ENV, BOARD_TOOLS, boardContext } from "../desk/board.ts";
28
32
  import { seedDelivery } from "../desk/delivery.ts";
29
33
  import type { FileHinter } from "../classifier/files.ts";
@@ -76,6 +80,17 @@ function scoutInstruction(request: ScoutRequest, domain: Domain): string {
76
80
  ].join("\n");
77
81
  }
78
82
 
83
+ function sharedScoutInstruction(request: ScoutRequest): string {
84
+ if (request.domains.length === 1) return scoutInstruction(request, request.domains[0]!);
85
+ return [
86
+ request.instruction,
87
+ "One shared read-only investigation covers all selected domains; inspect shared code only once.",
88
+ ...request.domains.map((domain) => `${domain}: ${domainSpec(domain).scoutFocus}.`),
89
+ "For each selected domain, emit `# Domain: <domain>` followed by the usual scout sections. Attribute evidence to that domain; do not omit domains.",
90
+ "Identify relevant files with line anchors and purposes, contracts, callers, tests and risks. Distinguish verified evidence from assumptions. Do not modify any file.",
91
+ ].join("\n\n");
92
+ }
93
+
79
94
  /** Where an agent's knowledge files are, for the note that says what a prompt left out. */
80
95
  function knowledgePaths(dataRoots: readonly string[], agent: Domain): KnowledgePaths {
81
96
  const root = dataRoots[0];
@@ -92,13 +107,26 @@ function retrievalMode(request: { config?: BotLobbyConfig }): boolean {
92
107
  return request.config?.workflow.knowledgeRetrieval !== false && request.config !== undefined;
93
108
  }
94
109
 
95
- async function pickKnowledge(request: { config?: BotLobbyConfig; knowledge?: KnowledgePicker; dataRoots: readonly string[]; signal?: AbortSignal }, agent: Domain, query: string): Promise<KnowledgeSelection> {
110
+ async function pickKnowledge(request: { config?: BotLobbyConfig; knowledge?: KnowledgePicker; dataRoots: readonly string[]; signal?: AbortSignal; cwd?: string }, agent: Domain, query: string): Promise<KnowledgeSelection> {
96
111
  const [selected, scripts] = await Promise.all([pickFiles(request, agent, query), scriptsFor(request.dataRoots[0], query, request.knowledge?.scripts, request.signal)]);
97
112
  return scripts ? { ...selected, scripts } : selected;
98
113
  }
99
114
 
100
- async function pickFiles(request: { config?: BotLobbyConfig; knowledge?: KnowledgePicker; dataRoots: readonly string[]; signal?: AbortSignal }, agent: Domain, query: string): Promise<KnowledgeSelection> {
101
- const slices = readAgentKnowledge(request.dataRoots, agent);
115
+ /**
116
+ * The designer always gets the whole design record (it is short, and a value
117
+ * left out would be asked about or guessed); the rest of its standards are
118
+ * selected as usual.
119
+ */
120
+ async function pickFiles(request: { config?: BotLobbyConfig; knowledge?: KnowledgePicker; dataRoots: readonly string[]; signal?: AbortSignal; cwd?: string }, agent: Domain, query: string): Promise<KnowledgeSelection> {
121
+ if (agent !== "designer" || !request.dataRoots[0]) return selectFiles(request, agent, query);
122
+ const selected = await selectFiles(request, agent, query, withoutDesignRecord);
123
+ const record = designRecordBlock(designStanding(request.dataRoots[0], request.cwd ?? ""), "task");
124
+ return { ...selected, standards: [record, selected.standards].filter(Boolean).join("\n\n") };
125
+ }
126
+
127
+ async function selectFiles(request: { config?: BotLobbyConfig; knowledge?: KnowledgePicker; dataRoots: readonly string[]; signal?: AbortSignal }, agent: Domain, query: string, standards: (text: string) => string = (text) => text): Promise<KnowledgeSelection> {
128
+ const read = readAgentKnowledge(request.dataRoots, agent);
129
+ const slices = { ...read, standards: standards(read.standards) };
102
130
  if (retrievalMode(request)) {
103
131
  return { knowledge: "", decisions: "", standards: selectRelevant(query, slices.standards ?? "", KNOWLEDGE_BUDGET_CHARS) };
104
132
  }
@@ -238,21 +266,27 @@ function toOutcome(run: AgentRun, domain: Domain): ScoutOutcome {
238
266
  return { result, run, issues: validateScoutResult(result), usable: isScoutResultUsable(result) };
239
267
  }
240
268
 
241
- /**
242
- * Run the selected domain scouts concurrently and persist their findings. A
243
- * domain asked the same thing before on an unchanged tree reuses its earlier
244
- * findings (`workflow.reuseScouts`); every new finding's Relevant Files are
245
- * kept as file notes for the repository map.
246
- */
269
+ /** One preparation/execution per task, including targeted followups. No cache miss implicitly invokes this API. */
247
270
  export async function runScouts(request: ScoutRequest, run: ProcessRunner = spawnPiProcess): Promise<ScoutOutcome[]> {
271
+ const release = acquireScoutLock(request.taskDir);
272
+ try {
273
+ return await prepareScouts({ ...request, domains: [...new Set(request.domains)] }, run);
274
+ } finally {
275
+ release();
276
+ }
277
+ }
278
+
279
+ async function prepareScouts(request: ScoutRequest, run: ProcessRunner): Promise<ScoutOutcome[]> {
280
+ if (request.domains.length === 0) return [];
281
+ request.signal?.throwIfAborted();
248
282
  const dataDir = request.dataRoots[0];
249
283
  const tree = dataDir && request.config.workflow.reuseScouts ? await treeState(request.cwd, request.dataRoots) : undefined;
250
- const keys = request.domains.map((domain) => scoutKey(domain, scoutInstruction(request, domain), request.taskText));
284
+ const instruction = sharedScoutInstruction(request);
285
+ const keys = request.domains.map((domain) => scoutKey(domain, instruction, request.taskText));
251
286
  const cached = keys.map((key) => (dataDir && tree ? readCachedScout(dataDir, key, tree) : undefined));
252
- const fresh = request.domains.filter((_domain, index) => !cached[index]);
253
- const ran = fresh.length > 0 ? await scoutDomains({ ...request, domains: fresh }, run) : [];
254
- let next = 0;
255
- const outcomes = request.domains.map((_domain, index) => cached[index] ?? ran[next++]!);
287
+ // Never mix execution identities from a partially cached preparation.
288
+ const outcomes = cached.every((outcome) => outcome !== undefined && outcome.run.runId === cached[0]?.run.runId)
289
+ ? cached as ScoutOutcome[] : await scoutDomains(request, run);
256
290
  saveScoutResults(request.taskDir, outcomes);
257
291
  if (dataDir) await remember(dataDir, request, outcomes, keys, tree);
258
292
  return outcomes;
@@ -270,47 +304,59 @@ async function remember(dataDir: string, request: ScoutRequest, outcomes: readon
270
304
  }
271
305
 
272
306
  async function scoutDomains(request: ScoutRequest, run: ProcessRunner): Promise<ScoutOutcome[]> {
273
- // Each scout gets the files most likely to answer its own instruction and focus, and its assignment's bookmarks.
274
- const [likely, selected, bookmarked] = await Promise.all([
275
- Promise.all(request.domains.map((domain) => likelyFor(request.hints, `${request.instruction}\n${domainSpec(domain).scoutFocus}`, request.signal, request.taskText))),
276
- Promise.all(request.domains.map((domain) => pickKnowledge(request, domain, `${request.instruction}\n${domainSpec(domain).scoutFocus}\n\n${request.taskText}`))),
277
- Promise.all(request.domains.map((domain) => prepareBookmarks(request, domain, `${request.instruction}\n${domainSpec(domain).scoutFocus}\n\n${request.taskText}`))),
307
+ const entry = await sharedScoutRequest(request);
308
+ const route = entry.harness ? undefined : await routeFor(request.effort, entry.instruction, { ...(entry.model ? { model: entry.model } : {}), thinking: entry.thinking ?? "low" }, { thinkingFixed: true, context: request.taskText, ...(request.signal ? { signal: request.signal } : {}) });
309
+ let agentRun = await runAgent(route ? { ...entry, ...routedFields(route) } : entry, run);
310
+ let outcomes = sharedScoutOutcomes(agentRun, request.domains);
311
+ if (route && outcomes.some((outcome) => !outcome.usable) && agentRun.status !== "cancelled" && !request.signal?.aborted) {
312
+ agentRun = await runAgent(entry, run);
313
+ outcomes = sharedScoutOutcomes(agentRun, request.domains);
314
+ }
315
+ return outcomes;
316
+ }
317
+
318
+ async function sharedScoutRequest(request: ScoutRequest): Promise<AgentRequest> {
319
+ const domain = request.domains[0]!;
320
+ const instruction = sharedScoutInstruction(request);
321
+ const query = `${instruction}\n\n${request.taskText}`;
322
+ const [likely, selections, bookmarked] = await Promise.all([
323
+ likelyFor(request.hints, instruction, request.signal, request.taskText),
324
+ Promise.all(request.domains.map((selected) => pickKnowledge(request, selected, query))),
325
+ prepareBookmarks(request, request.domains.length === 1 ? domain : `scout:${request.domains.join("+")}`, query),
278
326
  ]);
279
- const extraTools = request.hints?.tools() ?? [];
280
- const requests: AgentRequest[] = request.domains.map((domain, index) => {
281
- const hints = fitHints(bookmarked[index] ?? "", likely[index] ?? "");
282
- return {
283
- delegationQuota: { used: 0 },
284
- effort: request.effort,
285
- taskId: request.taskId,
286
- domain,
287
- role: "scout",
288
- instruction: scoutInstruction(request, domain),
289
- context: scoutContext(request, domain, selected[index]!, hints.likely, hints.bookmarks),
290
- ...(extraTools.length > 0 ? { extraTools } : {}),
291
- env: toolBudgetEnv(request.config.scout.maxToolCalls),
327
+ const hints = fitHints(bookmarked, likely);
328
+ return {
329
+ delegationQuota: { used: 0 }, effort: request.effort, taskId: request.taskId, domain, role: "scout",
330
+ instruction, context: sharedScoutContext(request, selections, hints), extraTools: request.hints?.tools() ?? [], env: toolBudgetEnv(request.config.scout.maxToolCalls),
292
331
  ...profileFields(request.config, request.profile, domain, "scout"),
293
- cwd: request.cwd,
294
- signal: request.signal,
295
- onUpdate: request.onUpdate,
296
- ...watchdogOptions(request.config.workflow),
297
- };
332
+ cwd: request.cwd, signal: request.signal, onUpdate: request.onUpdate, ...watchdogOptions(request.config.workflow),
333
+ };
334
+ }
335
+
336
+ function sharedScoutContext(request: ScoutRequest, selections: KnowledgeSelection[], hints: { likely: string; bookmarks: string }): AgentRequest["context"] {
337
+ const selected = mergeScoutKnowledge(request.domains, selections);
338
+ const context = scoutContext(request, request.domains[0]!, selected, hints.likely, hints.bookmarks);
339
+ context.instructions = request.domains.map((domain) => request.config.agents[domain].instructions ? `${domain}: ${request.config.agents[domain].instructions}` : "").filter(Boolean).join("\n\n");
340
+ context.workflowContext += `\nSelected domains: ${request.domains.join(", ")}. One shared scout; keep evidence attributed to each domain.`;
341
+ return context;
342
+ }
343
+
344
+ function mergeScoutKnowledge(domains: Domain[], selections: KnowledgeSelection[]): KnowledgeSelection {
345
+ if (selections.length === 1) return selections[0]!;
346
+ const merge = (key: keyof KnowledgeSelection) => selections.map((selected, index) => selected[key] ? `### ${domains[index]}\n${selected[key]}` : "").filter(Boolean).join("\n\n");
347
+ return { knowledge: merge("knowledge"), standards: merge("standards"), decisions: merge("decisions"), scripts: merge("scripts") };
348
+ }
349
+
350
+ /** Domain projections retain the original execution object: usage/work events are emitted only once. */
351
+ function sharedScoutOutcomes(run: AgentRun, domains: Domain[]): ScoutOutcome[] {
352
+ if (domains.length === 1) return [toOutcome(run, domains[0]!)];
353
+ const sections = run.output.split(/^# Domain: (designer|backend|qa)\s*$/m);
354
+ return domains.map((domain) => {
355
+ const index = sections.findIndex((value, index) => index % 2 === 1 && value === domain);
356
+ const raw = index < 0 ? "" : sections[index + 1] ?? "";
357
+ const outcome = toOutcome({ ...run, output: raw }, domain);
358
+ return { ...outcome, run, issues: index < 0 ? [...outcome.issues, `missing shared scout section for ${domain}`] : outcome.issues };
298
359
  });
299
- // Scouts think at a fixed level; a trivial one may move to the cheaper model (a pi model, so not on another harness).
300
- const routes = await Promise.all(requests.map((entry) => entry.harness ? undefined : routeFor(request.effort, entry.instruction, { ...(entry.model ? { model: entry.model } : {}), thinking: entry.thinking ?? "low" }, { thinkingFixed: true, context: request.taskText, ...(request.signal ? { signal: request.signal } : {}) })));
301
- const first = requests.map((entry, index) => (routes[index] ? { ...entry, ...routedFields(routes[index]!) } : entry));
302
- const runs = await runParallel(first, request.config.workflow.maxParallelScouts, run);
303
- let outcomes = runs.map((agentRun) => toOutcome(agentRun, agentRun.domain));
304
- // A routed scout that came back unusable runs again on its configured model.
305
- const again = outcomes.map((outcome, index) => (routes[index] && !outcome.usable && outcome.run.status !== "cancelled" && !request.signal?.aborted ? index : -1)).filter((index) => index >= 0);
306
- if (again.length > 0) {
307
- const reruns = await runParallel(again.map((index) => requests[index]!), request.config.workflow.maxParallelScouts, run);
308
- outcomes = outcomes.map((outcome, index) => {
309
- const position = again.indexOf(index);
310
- return position >= 0 ? toOutcome(reruns[position]!, reruns[position]!.domain) : outcome;
311
- });
312
- }
313
- return outcomes;
314
360
  }
315
361
  export function scoutResultPath(taskDir: string, domain: Domain): string {
316
362
  return join(taskDir, `scout-${domain}.json`);
@@ -346,13 +392,28 @@ function readScoutArtifact(dirs: readonly string[], domain: Domain): ScoutOutcom
346
392
  return undefined;
347
393
  }
348
394
 
395
+ export interface WorkerFreshness {
396
+ assignmentId: string;
397
+ revision: number;
398
+ status: EvidenceStatus;
399
+ hintIds: string[];
400
+ hints?: EvidenceHint[];
401
+ pause?: true;
402
+ recheckCompletedWork?: boolean;
403
+ }
404
+
349
405
  export interface WorkerOutcome {
350
406
  result: WorkerResult;
351
407
  run: AgentRun;
352
408
  issues: string[];
409
+ freshness?: WorkerFreshness;
353
410
  }
354
411
 
355
412
  export interface WorkerRequest {
413
+ /** Optional until the installed runtime supports fail-closed revised loadouts. */
414
+ assignment?: WorkerAssignment;
415
+ /** Existing task status can expose background hint verification without a preparation gate. */
416
+ onFreshness?: (status: WorkerFreshness) => void;
356
417
  /** Extra run wiring for parallel batches: the file desk's env, tools and hooks. */
357
418
  agent?: Pick<AgentRequest, "env" | "extraTools" | "onStart" | "onAttemptEnd">;
358
419
  taskId: string;
@@ -385,10 +446,6 @@ export interface WorkerRequest {
385
446
  boardFrom?: string;
386
447
  /** Domains working at the same time as this one, in a parallel batch. */
387
448
  alongside?: readonly Domain[];
388
- /** The worker has a worktree of its own for the batch; its change is applied back when the batch ends. */
389
- ownCheckout?: boolean;
390
- /** The model ask_expert consults on. */
391
- expert?: { model?: string; thinking: string };
392
449
  }
393
450
 
394
451
  /** How a worker uses the task board, and what it already says for its role. */
@@ -407,13 +464,10 @@ function alongsideGuidance(request: WorkerRequest): string {
407
464
  const others = (request.alongside ?? []).filter((domain) => domain !== request.domain);
408
465
  if (others.length === 0) return "";
409
466
  const names = others.map((domain) => ({ backend: "DEV", designer: "DESIGN", qa: "QA" })[domain]).join(" and ");
410
- const peers = `You work at the same time as ${names}. When you need a fact about their part (a name, a shape, a route), ask them with \`ask_peer\` instead of guessing; answer their questions with \`answer_peer\`. Questions only: neither of you takes work from the other.`;
411
- const checkout = request.ownCheckout
412
- ? " You work in a checkout of your own (no file claims needed): edit only the files your brief names, because when the batch ends your change is applied onto the others', and overlapping lines will not apply."
413
- : "";
414
- if (request.domain !== "qa") return `${peers}${checkout}`;
467
+ const peers = `You work at the same time as ${names}. Settle what they build against through the board's \`contract\` posts, and read theirs before you guess.`;
468
+ if (request.domain !== "qa") return peers;
415
469
  return [
416
- `${peers}${checkout}`,
470
+ peers,
417
471
  "You write the tests while the others build, so nobody waits for the build to finish first: work from the approved plan's contracts and acceptance criteria and the board's `contract` posts, not from their code. Write and claim test files only. When a builder posts `done` for a piece (or before you report), run your tests against what is there; a failing test against finished work is a finding for its owner, never a production fix of yours.",
418
472
  ].join(" ");
419
473
  }
@@ -439,7 +493,7 @@ function workerWorkflowContext(request: WorkerRequest, boardFrom: string, likely
439
493
  `Domain boundary: ${spec.boundary}`,
440
494
  "Dependency policy: never add a dependency or make a significant architectural change yourself; list them under the matching output section and stop that part of the work.",
441
495
  own.length > 0
442
- ? `Scout findings for your domain:\n${summarizeOutcomes(own, 1500)}`
496
+ ? `${request.assignment ? "Unverified broad scout navigation hints only; repository freshness is not established. Re-read current assigned files and verify callers/tests rather than relying on these findings." : "Scout findings for your domain:"}\n${summarizeOutcomes(own, 1500)}`
443
497
  : "No scout findings were collected for your domain; verify the repository yourself.",
444
498
  likely,
445
499
  request.risk ?? "",
@@ -451,15 +505,76 @@ function workerWorkflowContext(request: WorkerRequest, boardFrom: string, likely
451
505
  ].filter(Boolean).join("\n\n");
452
506
  }
453
507
 
508
+ interface TaskFreshness {
509
+ checks: EvidenceFreshness;
510
+ listeners: Map<string, (event: FreshnessInvalidation) => void>;
511
+ }
512
+
513
+ // Only overlapping dispatches share checks; no persistent evidence verdict cache.
514
+ const workerFreshness = new Map<string, TaskFreshness>();
515
+
516
+ function taskFreshness(key: string, request: WorkerRequest): TaskFreshness {
517
+ const existing = workerFreshness.get(key);
518
+ if (existing) return existing;
519
+ const listeners = new Map<string, (event: FreshnessInvalidation) => void>();
520
+ const checks = new EvidenceFreshness(
521
+ (hint) => verifyEvidenceHint(request.cwd, hint, () => treeState(request.cwd, request.dataRoots)),
522
+ (event) => listeners.get(JSON.stringify([event.assignmentId, event.revision]))?.(event),
523
+ );
524
+ const state = { checks, listeners };
525
+ workerFreshness.set(key, state);
526
+ return state;
527
+ }
528
+
529
+ function freshnessHints(hints: readonly FileNoteHint[]): string {
530
+ if (!hints.length) return "";
531
+ return [
532
+ "Unverified hints (file-local navigation only; not current callers, tests or repository behavior). Read assigned files now; checks run alongside this work.",
533
+ ...hints.map((hint) => `${hint.id}: ${hint.source} — ${hint.note.note}`),
534
+ "If a hint is invalidated, pause only work depending on it, continue independent assigned work, and request corrected evidence/revision. Completed dependent work must be rechecked before acceptance.",
535
+ ].join("\n");
536
+ }
537
+
538
+ function reportFreshness(request: WorkerRequest, reader: string, status: WorkerFreshness): void {
539
+ request.onFreshness?.(status);
540
+ if (!request.board) return;
541
+ appendPost(request.board, {
542
+ from: "oracle", kind: status.pause ? "blocker" : "note", to: ["oracle", reader],
543
+ text: `Assignment ${status.assignmentId} revision ${status.revision}: ${status.status}. Hints: ${status.hintIds.join(", ") || "none"}.${status.pause ? " Pause only dependent work; continue independent assigned work. Recheck completed dependent work before acceptance; request corrected evidence in a new revision." : " File-local navigation only; use current assigned-file reads."}`,
544
+ });
545
+ }
546
+
547
+ /** True when an assignment only reads: every file is reference and no edit or write tool is selected. */
548
+ export function readOnlyAssignment(assignment: WorkerAssignment): boolean {
549
+ return assignment.files.every((file) => file.access === "reference") && !assignment.tools.some((tool) => tool.name === "edit" || tool.name === "write");
550
+ }
551
+
552
+ /**
553
+ * The worker's model, thinking and grants. A read-only assignment needs no
554
+ * builder: it runs on the scout's model and thinking (keeping the worker's grants,
555
+ * which its tool selection was checked against), unless the scout is on a harness.
556
+ */
557
+ function workerProfile(request: WorkerRequest, assignment: WorkerAssignment | undefined) {
558
+ const worker = profileFields(request.config, request.profile, request.domain, "worker");
559
+ if (!assignment || !request.config.workflow.readOnlyOnScoutModel || !readOnlyAssignment(assignment)) return worker;
560
+ const scout = profileFields(request.config, request.profile, request.domain, "scout");
561
+ if (scout.harness || worker.harness) return worker;
562
+ // A scout that inherits the session's model would make this run dearer: keep the worker's model, at the scout's thinking.
563
+ const model = scout.model && scout.model !== "inherit" ? scout.model : worker.model;
564
+ return { ...worker, model, thinking: scout.thinking };
565
+ }
566
+
454
567
  /** Delegate one implementation step to a domain worker. */
455
568
  export async function runWorker(
456
569
  request: WorkerRequest,
457
570
  run: ProcessRunner = spawnPiProcess,
458
571
  ): Promise<WorkerOutcome> {
459
- const configured = profileFields(request.config, request.profile, request.domain, "worker");
572
+ const assignment = request.assignment !== undefined ? await validateAssignment(request.assignment, request.cwd) : undefined;
573
+ if (assignment && !request.dataRoots[0]) throw new Error("Assigned worker requires host-owned task storage in dataRoots.");
574
+ const configured = workerProfile(request, assignment);
460
575
  const [selected, likely, route, bookmarked] = await Promise.all([
461
576
  pickKnowledge(request, request.domain, `${request.instruction}\n\n${request.taskText}`),
462
- likelyFor(request.hints, request.instruction, request.signal, request.taskText),
577
+ assignment ? Promise.resolve("") : likelyFor(request.hints, request.instruction, request.signal, request.taskText),
463
578
  routeFor(request.effort, request.instruction, { ...(configured.model ? { model: configured.model } : {}), thinking: configured.thinking }, { context: request.taskText, ...(request.signal ? { signal: request.signal } : {}) }),
464
579
  prepareBookmarks(request, request.domain, `${request.instruction}\n\n${request.taskText}`),
465
580
  ]);
@@ -470,7 +585,7 @@ export async function runWorker(
470
585
  const env = request.board ? { ...request.agent?.env, [BOARD_ENV]: request.board, BOT_LOBBY_BOARD_FROM: boardFrom } : request.agent?.env;
471
586
  const base: AgentRequest = {
472
587
  delegationQuota: { used: 0 },
473
- ...(request.expert ? { expert: request.expert } : {}),
588
+ ...(assignment ? { assignment: { brief: assignment, taskDir: taskDir(request.dataRoots[0]!, request.taskId) } } : {}),
474
589
  effort: request.effort,
475
590
  effortProfile: configured,
476
591
  taskId: request.taskId,
@@ -494,11 +609,12 @@ export async function runWorker(
494
609
  ...(extraTools.length > 0 ? { extraTools } : {}),
495
610
  ...(request.ask ? { onAsk: request.ask.onAsk } : {}),
496
611
  };
497
- let outcome = workerOutcome(request.domain, await runAgent(route ? { ...base, ...routedFields(route) } : base, run));
612
+ if (assignment) return runFreshWorker(request, assignment, base, route, boardFrom, run);
613
+ let outcome = workerOutcome(request.domain, await runAgent(route ? { ...base, ...routedFields(route) } : base, run), request.cwd, assignment);
498
614
  // A routed step that fell short runs again at the configured model and thinking.
499
615
  if (route && fellShort(outcome.run, outcome.issues) && !request.signal?.aborted) {
500
616
  const routed = outcome.run.edited ?? [];
501
- outcome = workerOutcome(request.domain, await runAgent(base, run));
617
+ outcome = workerOutcome(request.domain, await runAgent(base, run), request.cwd, assignment);
502
618
  // The step owns what the routed attempt edited too.
503
619
  const edited = [...new Set([...routed, ...(outcome.run.edited ?? [])])];
504
620
  if (edited.length > 0) outcome = { ...outcome, run: { ...outcome.run, edited } };
@@ -506,12 +622,67 @@ export async function runWorker(
506
622
  return outcome;
507
623
  }
508
624
 
509
- function workerOutcome(domain: Domain, agentRun: AgentRun): WorkerOutcome {
625
+ async function runFreshWorker(request: WorkerRequest, assignment: WorkerAssignment, base: AgentRequest, route: EffortRoute | undefined, reader: string, run: ProcessRunner): Promise<WorkerOutcome> {
626
+ const key = JSON.stringify([request.cwd, taskDir(request.dataRoots[0]!, request.taskId)]);
627
+ const state = taskFreshness(key, request);
628
+ const listenerKey = JSON.stringify([assignment.id, assignment.revision]);
629
+ if (state.listeners.has(listenerKey)) throw new Error("Assignment revision is already checking freshness; wait for its dispatch to finish.");
630
+ const hints = fileNoteHints(request.dataRoots[0]!, assignment.files.flatMap((file) => {
631
+ const path = treePath(request.cwd, file.path);
632
+ return path ? [path] : [];
633
+ }));
634
+ const status = (): WorkerFreshness => {
635
+ const current = state.checks.status(assignment.id, assignment.revision);
636
+ return { assignmentId: assignment.id, revision: assignment.revision, status: current, hintIds: hints.map((hint) => hint.id), hints: hints.map(({ id, scope, source, fingerprint }) => ({ id, scope, source, fingerprint })), ...(current === "invalidated" ? { pause: true as const, recheckCompletedWork: true } : {}) };
637
+ };
638
+ state.listeners.set(listenerKey, (event) => reportFreshness(request, reader, { ...status(), ...event }));
639
+ let checkError: unknown;
640
+ let checking: Promise<void> | undefined;
641
+ try {
642
+ checking = state.checks.start({ assignmentId: assignment.id, revision: assignment.revision, hints }).catch((error: unknown) => { checkError = error; });
643
+ if (assignment.completedWork.length) state.checks.completed(assignment.id, assignment.revision);
644
+ reportFreshness(request, reader, status());
645
+ const instruction = [base.instruction, freshnessHints(hints)].filter(Boolean).join("\n\n");
646
+ // Assignment-local navigation hints belong in user content, not the shared system prefix.
647
+ // Start actual dispatch now, before awaiting any source-file hashes.
648
+ const outcome = await dispatchFreshWorker({ ...base, instruction }, request, assignment, route, state.checks, run);
649
+ state.checks.completed(assignment.id, assignment.revision);
650
+ await checking;
651
+ const freshness = status();
652
+ if (freshness.status !== "superseded") reportFreshness(request, reader, freshness);
653
+ const issues = state.checks.canAccept(assignment.id, assignment.revision) && !checkError ? outcome.issues : [...outcome.issues, `Assignment evidence ${freshness.status}; acceptance requires current verified hints and rechecked dependent work.${checkError ? " Freshness notification failed; restore task status/board delivery before retrying." : ""}`];
654
+ return { ...outcome, issues, freshness };
655
+ } finally {
656
+ await checking;
657
+ state.checks.completed(assignment.id, assignment.revision);
658
+ state.listeners.delete(listenerKey);
659
+ if (!state.listeners.size) workerFreshness.delete(key);
660
+ }
661
+ }
662
+
663
+ async function dispatchFreshWorker(base: AgentRequest, request: WorkerRequest, assignment: WorkerAssignment, route: EffortRoute | undefined, checks: EvidenceFreshness, run: ProcessRunner): Promise<WorkerOutcome> {
664
+ const outcome = workerOutcome(request.domain, await runAgent(route ? { ...base, ...routedFields(route) } : base, run), request.cwd, assignment);
665
+ if (!route || !fellShort(outcome.run, outcome.issues) || request.signal?.aborted || ["invalidated", "superseded"].includes(checks.status(assignment.id, assignment.revision))) return outcome;
666
+ const edited = outcome.run.edited ?? [];
667
+ const retry = await runAgent(base, run);
668
+ const combined = [...new Set([...edited, ...(retry.edited ?? [])])];
669
+ return workerOutcome(request.domain, { ...retry, edited: combined }, request.cwd, assignment);
670
+ }
671
+
672
+ function workerOutcome(domain: Domain, agentRun: AgentRun, cwd: string, assignment?: WorkerAssignment): WorkerOutcome {
510
673
  const result = parseWorkerResult(domain, agentRun.output);
511
674
  const issues =
512
675
  agentRun.status === "success"
513
- ? validateWorkerResult(result)
676
+ ? validateWorkerResult(result, assignment)
514
677
  : [`worker ${agentRun.status}: ${agentRun.error ?? "no detail"}`];
678
+ if (assignment && agentRun.edited?.length) {
679
+ const root = realpathSync(cwd);
680
+ const writable = new Set(assignment.files.filter((file) => file.access !== "reference").map((file) => resolve(root, file.path)));
681
+ for (const path of agentRun.edited) {
682
+ if (!writable.has(resolve(root, path))) issues.push(`observed edit outside assignment edit/create paths: ${path}`);
683
+ }
684
+ if (!result.verification.trim() && !issues.includes("changed files without verification")) issues.push("changed files without verification");
685
+ }
515
686
  return { result, run: agentRun, issues };
516
687
  }
517
688
 
@@ -539,6 +710,8 @@ export interface ReviewerRequest {
539
710
  risk?: string;
540
711
  /** The task board's contracts, decisions, blockers and finished pieces, as posted by the task's agents. */
541
712
  board?: string;
713
+ /** The assignments behind the change: the files each could change and its verification commands, for QA to start from. */
714
+ assignmentChecks?: string;
542
715
  /** Review with a clean context: no worker summaries or scout findings, only the request, plan, board and diff. */
543
716
  clean?: boolean;
544
717
  instruction?: string;
@@ -570,6 +743,7 @@ function reviewerContext(request: ReviewerRequest): string {
570
743
  request.provenance ? `Who changed each file (bot-lobby's record of every agent's edit and write calls; judge each as your role's Change provenance says):\n${request.provenance}` : "",
571
744
  request.lint ?? "",
572
745
  request.board ?? "",
746
+ request.assignmentChecks ?? "",
573
747
  `Repository changes:\n${request.diff}`,
574
748
  ]
575
749
  .filter((line) => line.length > 0)
@@ -35,7 +35,7 @@ export function scoutKey(domain: Domain, instruction: string, taskText: string):
35
35
  export function readCachedScout(dataDir: string, key: string, tree: string): ScoutOutcome | undefined {
36
36
  try {
37
37
  const cached = JSON.parse(readFileSync(join(scoutCacheDir(dataDir), `${key}.json`), "utf8")) as Partial<CachedScout>;
38
- if (cached.version !== 1 || cached.tree !== tree || !cached.outcome?.usable || !cached.at) return undefined;
38
+ if (cached.version !== 1 || cached.tree !== tree || !cached.outcome?.usable || !cached.outcome.run?.runId || !cached.at) return undefined;
39
39
  return { ...cached.outcome, reused: cached.at };
40
40
  } catch {
41
41
  return undefined;
@@ -0,0 +1,44 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ /** True only when the lock's owner is shown to be gone: same host, and its process no longer exists. */
7
+ function ownerGone(path: string): boolean {
8
+ try {
9
+ const owner = JSON.parse(readFileSync(path, "utf8")) as { pid?: unknown; host?: unknown };
10
+ if (typeof owner.pid !== "number" || (owner.host !== undefined && owner.host !== hostname())) return false;
11
+ try { process.kill(owner.pid, 0); return false; }
12
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
13
+ } catch { return false; }
14
+ }
15
+
16
+ function create(path: string, token: string): void {
17
+ const fd = openSync(path, "wx", 0o600);
18
+ try { writeFileSync(fd, JSON.stringify({ token, pid: process.pid, host: hostname() })); }
19
+ finally { closeSync(fd); }
20
+ }
21
+
22
+ /**
23
+ * Initial reconnaissance and targeted followups share the same task-local lock.
24
+ * A lock left by a process that died (a crash, a killed window) is taken over;
25
+ * one held by a live or unknown owner refuses the second scout.
26
+ */
27
+ export function acquireScoutLock(taskDir: string): () => void {
28
+ mkdirSync(taskDir, { recursive: true });
29
+ const path = join(taskDir, "scout.lock");
30
+ const token = randomUUID();
31
+ try {
32
+ create(path, token);
33
+ } catch (error) {
34
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
35
+ if (!ownerGone(path)) throw new Error(`A scout is already running for this task (${path}). Wait for its findings instead of starting another.`);
36
+ unlinkSync(path);
37
+ create(path, token);
38
+ }
39
+ return () => {
40
+ const owner = JSON.parse(readFileSync(path, "utf8")) as { token?: string };
41
+ if (owner.token !== token) throw new Error(`Scout lock ownership changed: ${path}`);
42
+ unlinkSync(path);
43
+ };
44
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The scout a task starts with: launched when the task is created, over the
3
+ * domains the classifier's triage names, so its findings are ready (or nearly)
4
+ * by the time the oracle has read the request and asks for a scout. The
5
+ * oracle's first scout call takes it; nothing else waits on it. One per task,
6
+ * held in this process only: a restarted window simply scouts as before. The
7
+ * runs it spent are handed to whichever action ends it, so they are accounted
8
+ * once in the task's run log like any scout's.
9
+ */
10
+ import type { Domain } from "../schemas/agent.ts";
11
+ import type { AgentRun } from "../schemas/findings.ts";
12
+ import type { TaskTriage } from "../schemas/task.ts";
13
+ import type { ScoutOutcome } from "./master.ts";
14
+
15
+ interface Prefetch {
16
+ domains: Domain[];
17
+ outcomes: Promise<ScoutOutcome[] | undefined>;
18
+ runs: Map<string, AgentRun>;
19
+ cancel: () => void;
20
+ }
21
+
22
+ export interface PrefetchTaken {
23
+ /** The findings, when they cover the ask with usable reconnaissance. */
24
+ outcomes?: ScoutOutcome[];
25
+ /** The finished runs the prefetch spent, used or not. */
26
+ runs: AgentRun[];
27
+ }
28
+
29
+ const prefetches = new Map<string, Prefetch>();
30
+
31
+ /** Domains at least this likely in the triage are scouted up front; QA only when it clearly takes part. */
32
+ const BUILD_DOMAIN_AT = 0.35;
33
+ const QA_DOMAIN_AT = 0.5;
34
+
35
+ /** The domains worth scouting before the oracle asks, from the triage; none without one. */
36
+ export function prefetchDomains(triage: TaskTriage | undefined): Domain[] {
37
+ if (!triage) return [];
38
+ const build = (["backend", "designer"] as const).filter((domain) => (triage.domains[domain] ?? 0) >= BUILD_DOMAIN_AT);
39
+ return [...build, ...((triage.domains.qa ?? 0) >= QA_DOMAIN_AT ? ["qa" as const] : [])];
40
+ }
41
+
42
+ /**
43
+ * Start the task's opening scout. `start` gets the signal to stop it by and the
44
+ * callback that records its runs. One per task; false when it did not start.
45
+ */
46
+ export function startScoutPrefetch(taskId: string, domains: Domain[], start: (signal: AbortSignal, onRun: (run: AgentRun) => void) => Promise<ScoutOutcome[]>): boolean {
47
+ if (domains.length === 0 || prefetches.has(taskId)) return false;
48
+ const controller = new AbortController();
49
+ const runs = new Map<string, AgentRun>();
50
+ const onRun = (run: AgentRun) => { if (run.status !== "running") runs.set(run.runId, run); };
51
+ // A failed or cancelled prefetch is just a miss: the oracle's scout runs as it would have.
52
+ const outcomes = start(controller.signal, onRun).catch(() => undefined);
53
+ prefetches.set(taskId, { domains, outcomes, runs, cancel: () => controller.abort() });
54
+ return true;
55
+ }
56
+
57
+ /**
58
+ * End the task's opening scout for an ask over `domains`. When it covers them
59
+ * all with usable findings it waits for them and returns them; otherwise it is
60
+ * stopped at once, so the oracle's own scout (which needs the task's scout lock)
61
+ * can start. Undefined when there was none.
62
+ */
63
+ export async function takeScoutPrefetch(taskId: string, domains: readonly Domain[]): Promise<PrefetchTaken | undefined> {
64
+ const prefetch = prefetches.get(taskId);
65
+ if (!prefetch) return undefined;
66
+ prefetches.delete(taskId);
67
+ const covers = domains.length > 0 && domains.every((domain) => prefetch.domains.includes(domain));
68
+ if (!covers) prefetch.cancel();
69
+ const outcomes = await prefetch.outcomes;
70
+ const runs = [...prefetch.runs.values()];
71
+ const wanted = covers ? outcomes?.filter((outcome) => domains.includes(outcome.result.domain)) : undefined;
72
+ return wanted && wanted.length === domains.length && wanted.every((outcome) => outcome.usable) ? { outcomes: wanted, runs } : { runs };
73
+ }
74
+
75
+ /** Stop a task's opening scout and wait until it has let go of the task's scout lock. */
76
+ export function stopScoutPrefetch(taskId: string): Promise<PrefetchTaken | undefined> {
77
+ return takeScoutPrefetch(taskId, []);
78
+ }
@@ -122,6 +122,8 @@ function orchestrateStep(args: unknown): string {
122
122
  return `compacting ${text("file") ?? "knowledge"}`;
123
123
  case "script":
124
124
  return `saving the shared script ${text("name") ?? ""}`.trimEnd();
125
+ case "design":
126
+ return `recording the design choice ${text("name") ?? ""}`.trimEnd();
125
127
  case "resolve_approval":
126
128
  return `${text("decision") === "rejected" ? "rejecting" : "approving"} ${text("approvalId") ?? "a request"}`;
127
129
  case "complete":