@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,7 +1,15 @@
1
+ import { validateAssignment, type WorkerAssignment, type AssignmentExpansionRequest } from "../execution/assignment.ts";
2
+ import { DESIGN_FIELD_KEYS, isDesignField, recordDesignChoices } from "../knowledge/design-record.ts";
3
+ import { verifyEvidenceHint } from "../master/evidence-freshness.ts";
4
+ import { approveAssignmentDiscovery, prepareAssignmentDiscovery, readAssignmentDiscovery } from "../execution/assignment-discovery.ts";
5
+ import { cleanupTaskAssignedSessions } from "../execution/assigned-session.ts";
6
+ import { checkWorkerAssignments, recordWorkerAssignments } from "../state/persistence.ts";
1
7
  import { existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
2
8
  import { checkpointSummary, settledDecisions } from "../state/checkpoint.ts";
9
+ import { draftAssignments, draftAssignmentsNote } from "./draft-assignments.ts";
10
+ import { prefetchDomains, startScoutPrefetch, stopScoutPrefetch, takeScoutPrefetch } from "../master/scout-prefetch.ts";
3
11
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
- import type { BotLobbyConfig, ProfileResolver } from "../schemas/configuration.ts";
12
+ import { profileFor, type BotLobbyConfig, type ProfileResolver } from "../schemas/configuration.ts";
5
13
  import type { AgentRun, Pushback, ResearchResult, ReviewResult } from "../schemas/findings.ts";
6
14
  import {
7
15
  MAX_RUN_LOG,
@@ -14,6 +22,7 @@ import {
14
22
  type Task,
15
23
  type TaskState,
16
24
  type WorkerRunRecord,
25
+ type WorkerAssignmentRecord,
17
26
  } from "../schemas/task.ts";
18
27
  import { isDomain, type Domain } from "../schemas/agent.ts";
19
28
  import { transition } from "../state/task-state.ts";
@@ -33,9 +42,8 @@ import { mapConcurrent } from "../execution/agent-runner.ts";
33
42
  import { taskExecution } from "../execution/task-cancellation.ts";
34
43
  import { parseWorkerResult } from "../roles/worker.ts";
35
44
  import { autoNote, DeskSession } from "../desk/session.ts";
36
- import { closeWorkerTrees, mapToTop, mergeWorkerTrees, openWorkerTrees, type MergeOutcome } from "../execution/worker-trees.ts";
37
45
  import type { Handover } from "../desk/desk.ts";
38
- import { changedFiles, commitBefore, commitFiles, commitMessage, headCommit, readRepositoryDiff, uncommitted } from "../execution/git.ts";
46
+ import { treeState, changedFiles, commitBefore, commitFiles, commitMessage, headCommit, readRepositoryDiff, uncommitted } from "../execution/git.ts";
39
47
  import { appendChange, explainChanges, provenanceLines, provenanceSummary, readChanges, type FileProvenance } from "../state/changes.ts";
40
48
  import {
41
49
  loadScoutResults,
@@ -44,6 +52,7 @@ import {
44
52
  runWorker,
45
53
  type ReviewerRequest,
46
54
  type ScoutOutcome,
55
+ type ScoutRequest,
47
56
  type WorkerOutcome,
48
57
  type WorkerRequest,
49
58
  } from "../master/master.ts";
@@ -52,8 +61,6 @@ import { assessReconnaissance, completionBlockers, decideReviewLoop, recordDecis
52
61
  import { detectSharedFiles, summarizeOutcomes } from "../master/synthesis.ts";
53
62
  import { assignmentId, boardContext, boardPath, filterPosts, formatPosts, readBoard, roleOf } from "../desk/board.ts";
54
63
  import { seedDelivery } from "../desk/delivery.ts";
55
- import { runGoalCheck } from "../master/goal-check.ts";
56
- import { createHash } from "node:crypto";
57
64
  import { tail, truncate } from "../text.ts";
58
65
  import { isAutoMode } from "../state/auto.ts";
59
66
  import { briefRejection } from "./brief.ts";
@@ -77,10 +84,10 @@ import { missingWorktree, taskCwd } from "../execution/workspace.ts";
77
84
  import { completionReview, deferReview, refreshReview } from "../delivery/review.ts";
78
85
  import { deliver } from "../delivery/operations.ts";
79
86
  import { deliveryStore } from "../delivery/store.ts";
80
- import { execCommand, type Exec } from "../lobby/issues.ts";
87
+ import { execCommand, type Exec } from "../lobby/exec.ts";
81
88
  import type { LintExec } from "../execution/lint.ts";
82
89
  import type { LintReport } from "../schemas/lint.ts";
83
- import { lintBrief, lintContext, lintHolds, lintNote, lintRefusal, lintSummary, runLintGate } from "./lint.ts";
90
+ import { lintBrief, lintContext, lintHolds, lintRefusal, lintSummary, runLintGate } from "./lint.ts";
84
91
  import { assessQaRisk, DEPTHS, qaRiskBrief, qaRiskLine, unreadRisk } from "../classifier/qa-risk.ts";
85
92
  import type { QaRiskAssessment, TrackMember } from "../schemas/task.ts";
86
93
 
@@ -97,6 +104,7 @@ export const ORCHESTRATE_ACTIONS = [
97
104
  "bookmark",
98
105
  "compact",
99
106
  "script",
107
+ "design",
100
108
  "complete",
101
109
  "block",
102
110
  "resume",
@@ -126,7 +134,9 @@ export interface OrchestrateParams {
126
134
  /** implement: the concrete instruction for the worker. */
127
135
  task?: string;
128
136
  /** implement: several domains at once, run in parallel through the file desk. */
129
- assignments?: Array<{ domain: string; task: string }>;
137
+ workerAssignment?: WorkerAssignment;
138
+ assignments?: Array<{ domain: string; task?: string; workerAssignment?: WorkerAssignment }>;
139
+ discoveryAllowance?: { assignmentId: string; revision: number; decisionId: string; reason: string; limit: number };
130
140
  /** knowledge: which persistent file the text belongs to. */
131
141
  kind?: KnowledgeKind;
132
142
  /** bookmark: the operation on the task's bookmark list. */
@@ -163,8 +173,6 @@ export interface WorkflowDeps {
163
173
  config: BotLobbyConfig;
164
174
  /** Per-run model/thinking/time limit, clamped to each model; plain settings when absent. */
165
175
  profile?: ProfileResolver;
166
- /** The model and thinking ask_expert consults on, resolved like the profiles; the settings' own when absent. */
167
- expert?: { model?: string; thinking: string };
168
176
  signal?: AbortSignal;
169
177
  onUpdate?: (run: AgentRun) => void;
170
178
  ask: (question: string) => Promise<string | undefined>;
@@ -264,6 +272,7 @@ export function describeTask(task: Task): string {
264
272
  ? `Pending approvals: ${pendingApprovals(task).map((a) => `${a.id} ${a.kind} for ${a.domain}: ${truncate(a.detail, 120)}`).join("; ")}`
265
273
  : "",
266
274
  task.blockers.length > 0 ? `Blockers: ${task.blockers.map((b) => b.reason).join("; ")}` : "",
275
+ ...(task.workerAssignments ?? []).map(assignmentStatus),
267
276
  skippedStepsNote(task.plan, task.skippedSteps),
268
277
  settledDecisions(task),
269
278
  checkpointSummary(task),
@@ -272,6 +281,11 @@ export function describeTask(task: Task): string {
272
281
  return lines.filter((line) => line.length > 0).join("\n");
273
282
  }
274
283
 
284
+ function assignmentStatus(entry: WorkerAssignmentRecord): string {
285
+ const outcome = entry.outcomes.filter((outcome) => outcome.revision === entry.brief.revision).at(-1);
286
+ return `Assignment ${entry.brief.id} r${entry.brief.revision} (${entry.domain}): ${outcome?.status ?? "prepared"}; freshness=${outcome?.freshness?.status ?? "unverified hints"}; issues=${JSON.stringify(outcome?.issues ?? [])}; verification=${JSON.stringify(outcome?.verification ?? "")}; completedWork=${JSON.stringify(outcome?.completedWork ?? entry.brief.completedWork)}; needs=${JSON.stringify(outcome?.needs ?? entry.brief.needs)}`;
287
+ }
288
+
275
289
  /** Knowledge files past the compaction threshold, for status reporting. */
276
290
  export function describeOversizedKnowledge(dataRoots: readonly string[], threshold: number): string[] {
277
291
  return overThreshold(dataRoots, threshold).map((entry) => `${entry.agent}/${entry.file} (${entry.chars} chars)`);
@@ -364,37 +378,62 @@ async function clarifyByClassifier(task: Task, question: string, options: readon
364
378
  }
365
379
  }
366
380
 
381
+ /** The scout request for a task, as the oracle's scout action and the task's opening scout both make it. */
382
+ function scoutRequestFor(task: Task, deps: WorkflowDeps, instruction: string, domains: Domain[], signal = deps.signal): ScoutRequest {
383
+ return {
384
+ taskId: task.id,
385
+ taskText: taskRequest(task),
386
+ instruction,
387
+ domains,
388
+ cwd: deps.cwd,
389
+ dataRoots: readDataRoots(deps.root, deps.configDir),
390
+ taskDir: taskDirFor(deps.root, deps.configDir, task.id),
391
+ config: deps.config,
392
+ profile: deps.profile,
393
+ signal,
394
+ onUpdate: deps.onUpdate,
395
+ ...(deps.hints ? { hints: deps.hints } : {}),
396
+ ...(deps.knowledge ? { knowledge: deps.knowledge } : {}),
397
+ ...(deps.effort ? { effort: deps.effort } : {}),
398
+ };
399
+ }
400
+
401
+ const DEFAULT_SCOUT_INSTRUCTION = "Investigate this request and report findings the Master needs.";
402
+
403
+ /**
404
+ * Start the task's opening scout while the oracle reads the request: the full
405
+ * workflow only (the fast track and an agreed plan skip scouting), over the
406
+ * domains the triage names. Returns the domains it scouts; none when it did not start.
407
+ */
408
+ export function prefetchScouts(task: Task, config: BotLobbyConfig, makeDeps: () => WorkflowDeps): Domain[] {
409
+ if (!config.workflow.prefetchScout || task.approvedPlan || task.track?.path === "fast") return [];
410
+ const domains = prefetchDomains(task.triage);
411
+ if (domains.length === 0) return [];
412
+ const deps = makeDeps();
413
+ const cwd = taskCwd(task, deps.cwd);
414
+ const started = startScoutPrefetch(task.id, domains, (signal, onRun) => runScouts({ ...scoutRequestFor(task, { ...deps, cwd }, DEFAULT_SCOUT_INSTRUCTION, domains, signal), onUpdate: onRun }, deps.runProcess ?? spawnPiProcess));
415
+ return started ? domains : [];
416
+ }
417
+
367
418
  async function handleScout(task: Task, params: OrchestrateParams, deps: WorkflowDeps): Promise<string> {
368
419
  requireState(task, ["created", "clarifying", "scouting", "synthesizing"]);
369
420
  const domains = deriveDomains(params.domains);
370
421
  if (task.state === "created") transition(task, "clarifying");
371
422
  if (task.state === "clarifying") transition(task, "scouting");
372
423
  const verifying = task.state === "synthesizing";
373
- const instruction = params.instruction?.trim() || "Investigate this request and report findings the Master needs.";
374
- const outcomes = await runScouts(
375
- {
376
- taskId: task.id,
377
- taskText: taskRequest(task),
378
- instruction,
379
- domains,
380
- cwd: deps.cwd,
381
- dataRoots: readDataRoots(deps.root, deps.configDir),
382
- taskDir: taskDirFor(deps.root, deps.configDir, task.id),
383
- config: deps.config,
384
- profile: deps.profile,
385
- signal: deps.signal,
386
- onUpdate: deps.onUpdate,
387
- ...(deps.hints ? { hints: deps.hints } : {}),
388
- ...(deps.knowledge ? { knowledge: deps.knowledge } : {}),
389
- ...(deps.effort ? { effort: deps.effort } : {}),
390
- },
391
- deps.runProcess ?? spawnPiProcess,
392
- );
424
+ const instruction = params.instruction?.trim() || DEFAULT_SCOUT_INSTRUCTION;
425
+ // The scout that started with the task answers the first ask it covers; a pointed follow-up runs on its own.
426
+ const prefetch = verifying ? await stopScoutPrefetch(task.id) : await takeScoutPrefetch(task.id, domains);
427
+ // Its runs are this action's too, used or not, so the task's run log and costs count them once.
428
+ for (const run of prefetch?.runs ?? []) deps.onUpdate?.(run);
429
+ const early = prefetch?.outcomes;
430
+ const outcomes = early ?? await runScouts(scoutRequestFor(task, deps, instruction, domains), deps.runProcess ?? spawnPiProcess);
393
431
  if (!verifying) transition(task, "synthesizing");
394
432
  const involved = outcomes.filter((outcome) => outcome.usable).map((outcome) => outcome.result.domain);
395
433
  task.domains = [...new Set([...task.domains, ...involved])];
396
434
  recordAdvisoryPushbacks(task, outcomes.map((outcome) => ({ pushback: outcome.result.pushback, who: outcome.result.domain })));
397
- return scoutReport(outcomes, verifying);
435
+ const report = scoutReport(outcomes, verifying);
436
+ return early ? `${report}\n\nThese findings come from the scout that started with the task (it investigated the request as a whole). For a specific gap, scout again with a pointed instruction.` : report;
398
437
  }
399
438
 
400
439
  /** Research is evidence gathering, so it is legal in every non-terminal state. */
@@ -515,31 +554,8 @@ async function handlePropose(task: Task, params: OrchestrateParams, deps: Workfl
515
554
  if (!task.plan) addressComments(task, deps);
516
555
  for (const concern of params.concerns ?? []) recordDecision(task, `Concern: ${concern}`);
517
556
  transition(task, "awaiting_approval");
518
- if (!deps.config.workflow.requireApprovalForFeatures) return applyApprovalChoice(task, "approve");
519
- const unattended = unattendedReason(task, isAutoMode(deps.root, deps.configDir, task.id));
520
- if (unattended) {
521
- recordDecision(task, `Proposal approved without asking (${unattended}).`);
522
- return `${applyApprovalChoice(task, "approve")} (No approval needed: ${unattended === "auto mode" ? "auto mode is on" : `the user agreed this plan in the planning panel (${task.approvedPlan})`}.)`;
523
- }
524
- const choice = await deps.choose(`Approve this proposal?\n\n${truncate(proposal, 2000)}`, APPROVAL_OPTIONS);
525
- if (!choice) return `Awaiting approval. Present the proposal to the user and continue after they respond.\n\n${proposal}`;
526
- const lower = choice.toLowerCase();
527
- if (lower.startsWith("approve")) return applyApprovalChoice(task, "approve");
528
- if (lower.startsWith("decline")) return applyApprovalChoice(task, "decline");
529
- const result = applyApprovalChoice(task, "amend", await deps.ask("What should change?"));
530
- await retriage(task, deps);
531
- return result;
532
- }
533
-
534
- /** After an amendment, the classifier reads the request again, so the Master's hints follow the change. */
535
- async function retriage(task: Task, deps: WorkflowDeps): Promise<void> {
536
- if (!deps.triage || !task.triage) return;
537
- try {
538
- const next = await deps.triage([taskRequest(task), ...task.amendments.map((text) => `Amendment: ${text}`)].join("\n\n"), deps.signal);
539
- if (next) task.triage = next;
540
- } catch {
541
- // Hints only: the old triage stays.
542
- }
557
+ // The request already says what the user wants: a proposal goes straight on. Only new dependencies and architecture changes stop for the user.
558
+ return applyApprovalChoice(task, "approve");
543
559
  }
544
560
 
545
561
  /** States in which `plan` replaces an approved plan instead of recording the first one. */
@@ -577,7 +593,8 @@ function handlePlan(task: Task, params: OrchestrateParams, deps: WorkflowDeps):
577
593
  recordDecision(task, `Plan amended${addressed > 0 ? ` for ${addressed} user comment${addressed === 1 ? "" : "s"}` : ""}.`);
578
594
  return `Plan amended.${commentsNote(addressed)} Next: continue with action=implement for the next open step (or action=qa when the work is complete).`;
579
595
  }
580
- return `Plan recorded.${commentsNote(addressed)} Next: call action=implement with domain and task for the first step.`;
596
+ const drafts = draftAssignmentsNote(draftAssignments(plan, deps.cwd));
597
+ return [`Plan recorded.${commentsNote(addressed)} Next: call action=implement with domain and workerAssignment for the first step.`, drafts].filter(Boolean).join("\n\n");
581
598
  }
582
599
 
583
600
  /** Record approvals a worker asked for; auto-approve when config allows it. */
@@ -650,6 +667,7 @@ function workerReport(outcome: WorkerOutcome, approvals: Approval[], pushback?:
650
667
  result.scriptProposals?.length
651
668
  ? `Script proposals (save with action=script name purpose usage file=<draft>, when the job will come back; or ignore): ${result.scriptProposals.map((proposal) => `${proposal.name}${proposal.purpose ? ` — ${truncate(proposal.purpose, 120)}` : ""}${proposal.draft ? ` (draft: ${proposal.draft})` : ""}`).join("; ")}`
652
669
  : "",
670
+ workerNeeds(outcome).length > 0 ? `Expansion requests: ${JSON.stringify(workerNeeds(outcome))}` : "",
653
671
  issues.length > 0 ? `Issues: ${issues.join("; ")}` : "",
654
672
  pushback && objection
655
673
  ? `Pushback recorded (${pushback.id}): ${truncate(objection.reason, 240)}. Resolve with action=resolve_approval before re-delegating ${result.domain}.`
@@ -728,9 +746,15 @@ function boardNews(deps: WorkflowDeps, task: Task, after: number): string {
728
746
  return posts.length > 0 ? `Task board, new posts:\n${formatPosts(posts)}` : "";
729
747
  }
730
748
 
731
- function workerRequest(deps: WorkflowDeps, task: Task, domain: Domain, instruction: string, alongside?: readonly Domain[], boardFrom?: string): WorkerRequest {
749
+ function workerRequest(deps: WorkflowDeps, task: Task, domain: Domain, instruction: string, alongside?: readonly Domain[], boardFrom?: string, assignment?: WorkerAssignment): WorkerRequest {
732
750
  const ask = askRelay(task, deps, domain);
733
751
  return {
752
+ ...(assignment ? {
753
+ assignment,
754
+ onFreshness: (freshness) => {
755
+ deps.notify(`Assignment ${freshness.assignmentId} r${freshness.revision}: ${freshness.status}${freshness.pause ? "; pause dependent work and recheck it" : ""}.`, freshness.pause ? "warning" : "info");
756
+ },
757
+ } : {}),
734
758
  board: taskBoard(deps, task),
735
759
  boardFrom: boardFrom ?? assignmentId(domain),
736
760
  ...(alongside && alongside.length > 1 ? { alongside } : {}),
@@ -746,7 +770,6 @@ function workerRequest(deps: WorkflowDeps, task: Task, domain: Domain, instructi
746
770
  dataRoots: readDataRoots(deps.root, deps.configDir),
747
771
  config: deps.config,
748
772
  profile: deps.profile,
749
- ...(deps.expert ? { expert: deps.expert } : {}),
750
773
  signal: deps.signal,
751
774
  onUpdate: deps.onUpdate,
752
775
  ...(deps.hints ? { hints: deps.hints } : {}),
@@ -824,24 +847,93 @@ function recordWorkerRun(task: Task, run: AgentRun): void {
824
847
  interface Assignment {
825
848
  domain: Domain;
826
849
  instruction: string;
850
+ assignment?: WorkerAssignment;
827
851
  }
828
852
 
829
853
  /** The delegation as a list: `assignments` for a parallel batch, otherwise the single domain/task. */
830
- function parseAssignments(params: OrchestrateParams): Assignment[] {
831
- if (params.assignments && params.assignments.length > 0) {
832
- const list = params.assignments.map((entry) => {
833
- const instruction = entry.task?.trim();
834
- if (!instruction) throw new Error("every assignment needs a task (what to implement)");
835
- return { domain: parseDomain(entry.domain, "implement"), instruction };
836
- });
837
- const domains = list.map((entry) => entry.domain);
838
- if (new Set(domains).size !== domains.length) throw new Error("parallel assignments need distinct domains (one worker per domain)");
839
- return list;
854
+ async function parseAssignments(params: OrchestrateParams, cwd: string): Promise<Assignment[]> {
855
+ if (params.assignments !== undefined && (params.workerAssignment !== undefined || params.domain !== undefined || params.task !== undefined)) throw new Error("Use either assignments or a single domain/workerAssignment, not both");
856
+ const entries = params.assignments ?? [{ domain: params.domain, task: params.task, workerAssignment: params.workerAssignment }];
857
+ if (!Array.isArray(entries) || entries.length === 0) throw new Error("implement assignments must not be empty");
858
+ const list: Assignment[] = [];
859
+ for (const entry of entries) {
860
+ const domain = parseDomain(entry.domain, "implement");
861
+ if (entry.workerAssignment === undefined) {
862
+ if (!entry.task?.trim()) throw new Error("implement requires task or workerAssignment");
863
+ list.push({ domain, instruction: entry.task.trim() });
864
+ } else {
865
+ const assignment = await validateAssignment(entry.workerAssignment, cwd);
866
+ list.push({ domain, instruction: entry.task?.trim() || assignment.objective, assignment });
867
+ }
868
+ }
869
+ if (new Set(list.map((entry) => entry.domain)).size !== list.length) throw new Error("parallel assignments need distinct domains (one worker per domain)");
870
+ return list;
871
+ }
872
+
873
+ async function checkDiscoveryAllowances(task: Task, batch: { assignment: WorkerAssignment }[], deps: WorkflowDeps): Promise<void> {
874
+ for (const { assignment } of batch) {
875
+ if ((assignment.discoveryLimit ?? 2) <= 2) continue;
876
+ const prior = task.workerAssignments?.find((entry) => entry.brief.id === assignment.id);
877
+ if (!prior) throw new Error(`Assignment ${assignment.id}: persist a brief with the default discovery allowance before requesting a master decision`);
878
+ const ledger = await readAssignmentDiscovery(taskDirFor(deps.root, deps.configDir, task.id), assignment.id, prior.brief.revision);
879
+ if ((assignment.discoveryLimit ?? 2) > ledger.limit) throw new Error(`Assignment ${assignment.id}: discovery limit requires an explicit master allowance decision`);
880
+ }
881
+ }
882
+
883
+ async function decideDiscoveryAllowance(task: Task, params: OrchestrateParams, deps: WorkflowDeps): Promise<string> {
884
+ if (params.domain !== undefined && params.domain !== "master") throw new Error("discoveryAllowance is master-only");
885
+ const allowance = params.discoveryAllowance!;
886
+ const keys = ["assignmentId", "revision", "decisionId", "reason", "limit"];
887
+ if (!allowance || Object.keys(allowance).some((key) => !keys.includes(key)) || typeof allowance.assignmentId !== "string" || typeof allowance.decisionId !== "string" || !allowance.decisionId.trim() || typeof allowance.reason !== "string" || !allowance.reason.trim() || !Number.isSafeInteger(allowance.limit) || allowance.limit < 0) throw new Error("discoveryAllowance requires exactly assignmentId, revision, decisionId, reason and a non-negative integer limit");
888
+ const record = task.workerAssignments?.find((entry) => entry.brief.id === allowance.assignmentId);
889
+ if (!record || record.brief.revision !== allowance.revision) throw new Error("discoveryAllowance must identify the current persisted assignment revision");
890
+ const dir = taskDirFor(deps.root, deps.configDir, task.id);
891
+ let ledger;
892
+ try {
893
+ ledger = await readAssignmentDiscovery(dir, allowance.assignmentId, allowance.revision);
894
+ } catch (error) {
895
+ const message = error instanceof Error ? error.message : String(error);
896
+ if (!message.includes("ledger missing;") && !message.includes("is not prepared; current revision is")) throw error;
897
+ ledger = await prepareAssignmentDiscovery(dir, allowance.assignmentId, allowance.revision, Math.min(record.brief.discoveryLimit ?? 2, 2));
898
+ }
899
+ const existing = ledger.decisions.find((entry) => entry.decisionId === allowance.decisionId);
900
+ if (existing && (existing.reason !== allowance.reason || existing.limit !== allowance.limit)) throw new Error("discoveryAllowance decisionId already records different content");
901
+ if (!existing && allowance.limit <= ledger.limit) throw new Error("discoveryAllowance must increase the approved total");
902
+ // Durable audit first: a crash may leave a decision awaiting application, never an unaudited increase.
903
+ const text = `Discovery allowance: ${JSON.stringify(allowance)}`;
904
+ if (!task.decisions.some((entry) => entry.domain === "master" && entry.text === text)) {
905
+ recordDecision(task, text, "master");
906
+ task.decisions.at(-1)!.discoveryAllowance = structuredClone(allowance);
907
+ }
908
+ saveTask(deps.root, deps.configDir, task);
909
+ await approveAssignmentDiscovery(dir, allowance.assignmentId, allowance.revision, allowance);
910
+ return `Discovery allowance recorded (${allowance.assignmentId} r${allowance.revision}, limit ${allowance.limit}). Revise the brief to use the approved limit.`;
911
+ }
912
+
913
+ async function refreshAssignmentEvidence(task: Task, deps: WorkflowDeps): Promise<void> {
914
+ for (const entry of task.workerAssignments ?? []) {
915
+ const outcome = entry.outcomes.filter((item) => item.revision === entry.brief.revision).at(-1);
916
+ const freshness = outcome?.freshness;
917
+ if (!freshness || freshness.status !== "verified") continue;
918
+ // Legacy metadata without source snapshots cannot establish current evidence.
919
+ const checks = await Promise.all((freshness.hints ?? []).map((hint) => verifyEvidenceHint(deps.cwd, hint, () => treeState(deps.cwd, readDataRoots(deps.root, deps.configDir)))));
920
+ if (freshness.hints && checks.every(Boolean)) continue;
921
+ freshness.status = "invalidated";
922
+ freshness.pause = true;
923
+ freshness.recheckCompletedWork = true;
924
+ outcome!.issues = [...(outcome!.issues ?? []), "Evidence changed or source snapshots are missing; recheck dependent work in a new assignment revision"];
925
+ deps.notify(`Assignment ${entry.brief.id} r${entry.brief.revision}: evidence invalidated; recheck dependent work.`, "warning");
840
926
  }
841
- const domain = parseDomain(params.domain, "implement");
842
- const instruction = params.task?.trim();
843
- if (!instruction) throw new Error("implement requires task (what to implement)");
844
- return [{ domain, instruction }];
927
+ }
928
+
929
+ export function workerAssignmentHolds(task: Task): string[] {
930
+ return (task.workerAssignments ?? []).flatMap(({ brief, outcomes }) => {
931
+ const latest = outcomes.filter((outcome) => outcome.revision === brief.revision).at(-1);
932
+ const fresh = latest?.freshness;
933
+ const verified = latest?.verification?.trim();
934
+ if (latest?.status === "success" && Array.isArray(latest.issues) && latest.issues.length === 0 && latest.needs.length === 0 && fresh?.assignmentId === brief.id && fresh.revision === brief.revision && fresh.status === "verified" && (brief.files.every((file) => file.access === "reference") || verified)) return [];
935
+ return [`Assignment ${brief.id} r${brief.revision} needs a successful issue-free latest outcome, resolved needs, current verified evidence and verification for edits`];
936
+ });
845
937
  }
846
938
 
847
939
  /**
@@ -895,11 +987,6 @@ async function changeState(deps: WorkflowDeps, task: Task, base?: string): Promi
895
987
  return { top: tree.top, files: explainChanges(task, tree.files, tree.top, readChanges(deps.root, deps.configDir, task.createdAt)) };
896
988
  }
897
989
 
898
- /** Who touched each file, as the oracle names them (`DEV`, `DESIGN/DEV`). */
899
- function ownersOf(files: readonly FileProvenance[] | undefined): Map<string, string> {
900
- return new Map((files ?? []).filter((file) => file.domains?.length).map((file) => [file.path, file.domains!.map((domain) => AGENT_LABELS[domain]).join("/")]));
901
- }
902
-
903
990
  /**
904
991
  * The lint gate (see lint.ts): lint the files this task's agents touched, as
905
992
  * they stand, record the report on the task and tell the lobby when it is
@@ -941,7 +1028,8 @@ function provenanceNote(files: readonly FileProvenance[] | undefined): string {
941
1028
  }
942
1029
 
943
1030
  /** Record one worker's outcome on the task and return its report for the Master. */
944
- function absorbWorkerOutcome(task: Task, deps: WorkflowDeps, outcome: WorkerOutcome): string {
1031
+ function absorbWorkerOutcome(task: Task, deps: WorkflowDeps, outcome: WorkerOutcome, assignment?: WorkerAssignment): string {
1032
+ if (assignment) recordAssignmentOutcome(task, outcome, assignment);
945
1033
  const domain = outcome.result.domain;
946
1034
  recordWorkerRun(task, outcome.run);
947
1035
  appendChange(deps.root, deps.configDir, {
@@ -965,6 +1053,26 @@ function absorbWorkerOutcome(task: Task, deps: WorkflowDeps, outcome: WorkerOutc
965
1053
  return [report, grown].filter(Boolean).join("\n");
966
1054
  }
967
1055
 
1056
+ function recordAssignmentOutcome(task: Task, outcome: WorkerOutcome, assignment: WorkerAssignment): void {
1057
+ const record = task.workerAssignments?.find((entry) => entry.brief.id === assignment.id);
1058
+ if (!record) throw new Error(`Missing persisted worker assignment ${assignment.id}`);
1059
+ record.outcomes.push({
1060
+ revision: assignment.revision,
1061
+ runId: outcome.run.runId,
1062
+ status: outcome.run.status,
1063
+ issues: [...outcome.issues],
1064
+ verification: outcome.result.verification,
1065
+ ...(outcome.freshness ? { freshness: structuredClone(outcome.freshness) } : {}),
1066
+ completedWork: [...new Set([...assignment.completedWork, ...(outcome.result.completed ? [outcome.result.completed] : [])])],
1067
+ needs: structuredClone([...assignment.needs, ...workerNeeds(outcome)]),
1068
+ ...(outcome.run.finishedAt ? { finishedAt: outcome.run.finishedAt } : {}),
1069
+ });
1070
+ }
1071
+
1072
+ function workerNeeds(outcome: WorkerOutcome): AssignmentExpansionRequest[] {
1073
+ return (outcome.result as typeof outcome.result & { needs?: AssignmentExpansionRequest[] }).needs ?? [];
1074
+ }
1075
+
968
1076
  /** Reports longer than this are kept whole in a file and the oracle gets the path. */
969
1077
  const LONG_REPORT = 2400;
970
1078
 
@@ -1042,12 +1150,21 @@ async function handleImplement(task: Task, params: OrchestrateParams, deps: Work
1042
1150
  throw new Error(`action not allowed in state "${task.state}": on the full workflow the user approves a proposal first (a small, clear change can take the fast track: action=track track=fast)`);
1043
1151
  }
1044
1152
  if (!starting) requireState(task, ["planning", "implementing", "reviewing"]);
1045
- const assignments = parseAssignments(params);
1153
+ const assignments = await parseAssignments(params, deps.cwd);
1154
+ const structured = assignments.flatMap(({ domain, assignment }) => assignment ? [{ domain, assignment }] : []);
1155
+ checkWorkerAssignments(task, structured);
1156
+ // A harness cannot keep a sanitized conversation or attest its tools: refuse here, before anything is recorded.
1157
+ const harnessed = structured.filter(({ domain }) => profileFor(deps.config, deps.profile, domain, "worker").harness).map(({ domain }) => domain);
1158
+ if (harnessed.length > 0) throw new Error(`${harnessed.join(", ")} runs on a third-party harness, which cannot run a structured workerAssignment; send that step as a prose task instead.`);
1159
+ await checkDiscoveryAllowances(task, structured, deps);
1046
1160
  const benched = assignments.map((entry) => benchedRefusal(task, entry.domain)).filter(Boolean);
1047
1161
  if (benched.length > 0) throw new Error(benched.join("\n"));
1048
- const short = !deps.config.workflow.briefCheck ? [] : assignments.map((entry) => briefRejection(task.id, entry.domain, entry.instruction)).filter(Boolean);
1162
+ const short = !deps.config.workflow.briefCheck ? [] : assignments.filter((entry) => !entry.assignment).map((entry) => briefRejection(task.id, entry.domain, entry.instruction)).filter(Boolean);
1049
1163
  if (short.length > 0) throw new Error(short.join("\n"));
1050
1164
  for (const { domain } of assignments) assertNoPendingApprovals(task, domain);
1165
+ if (structured.length) recordWorkerAssignments(task, structured);
1166
+ saveTask(deps.root, deps.configDir, task);
1167
+ checkWorkerAssignments(task, structured);
1051
1168
  for (const { domain } of assignments) if (!task.domains.includes(domain)) task.domains.push(domain);
1052
1169
  if (task.track && onFastTrack(task)) task.track.roster = parseRoster([...task.track.roster, ...assignments.map((entry) => entry.domain)]);
1053
1170
  if (starting) startFast(task);
@@ -1059,13 +1176,13 @@ async function handleImplement(task: Task, params: OrchestrateParams, deps: Work
1059
1176
  const boardBefore = readBoard(taskBoard(deps, task)).at(-1)?.seq ?? 0;
1060
1177
  let report: string;
1061
1178
  if (assignments.length === 1) {
1062
- const { domain, instruction } = assignments[0]!;
1063
- const outcome = await runWorker(workerRequest(deps, task, domain, instruction), deps.runProcess ?? spawnPiProcess);
1064
- report = absorbWorkerOutcome(task, deps, outcome);
1179
+ const { domain, instruction, assignment } = assignments[0]!;
1180
+ const outcome = await runWorker(workerRequest(deps, task, domain, instruction, undefined, undefined, assignment), deps.runProcess ?? spawnPiProcess);
1181
+ report = absorbWorkerOutcome(task, deps, outcome, assignment);
1065
1182
  } else report = await runParallelWorkers(task, deps, assignments);
1066
1183
  const tree = await changeState(deps, task, task.baseline?.head);
1067
- const lint = lintNote(await lintTask(task, deps, tree), deps.config.lint.mode, ownersOf(tree?.files));
1068
- return [report, boardNews(deps, task, boardBefore), provenanceNote(tree?.files), lint].filter(Boolean).join("\n\n");
1184
+ // Lint runs once the work is in: before QA and at completion, not after every step.
1185
+ return [report, boardNews(deps, task, boardBefore), provenanceNote(tree?.files)].filter(Boolean).join("\n\n");
1069
1186
  }
1070
1187
 
1071
1188
  /**
@@ -1165,63 +1282,37 @@ function stepLine(instruction: string): string {
1165
1282
  * Several domains at once. The workers share one file desk: each claims a file
1166
1283
  * before editing it, queues for a busy one, and hands it over with a note; a
1167
1284
  * worker that finishes hands over whatever it still holds automatically.
1168
- * In `worktrees` mode each worker has a checkout of its own instead (no
1169
- * claims, no queues), and their changes are applied back when the batch ends.
1170
- * Either way the desk carries the board and the workers' questions to each other.
1285
+ * The desk also carries the task board to them.
1171
1286
  */
1172
1287
  async function runParallelWorkers(task: Task, deps: WorkflowDeps, assignments: Assignment[]): Promise<string> {
1173
1288
  const batch = assignments.map((entry) => entry.domain);
1174
- const runs = assignments.map((entry) => ({ domain: entry.domain, instruction: entry.instruction, worker: assignmentId(entry.domain) }));
1175
- const opened = deps.config.workflow.parallelMode === "worktrees" ? await openWorkerTrees(deps.cwd, batch) : undefined;
1176
- const trees = opened && typeof opened !== "string" ? opened : undefined;
1177
- const session = new DeskSession({ cwd: deps.cwd, boardPath: taskBoard(deps, task), peers: true, ...(trees ? { claims: false } : {}) });
1289
+ const runs = assignments.map((entry) => ({ ...entry, worker: assignmentId(entry.domain) }));
1290
+ const session = new DeskSession({ cwd: deps.cwd, boardPath: taskBoard(deps, task) });
1178
1291
  await session.open();
1179
1292
  let outcomes: WorkerOutcome[];
1180
1293
  let unenforced: Domain[];
1181
- let merged = "";
1182
1294
  try {
1183
- try {
1184
- outcomes = await mapConcurrent(runs, deps.config.workflow.maxParallelWorkers, ({ domain, instruction, worker }) => {
1185
- const request = workerRequest(deps, task, domain, instruction, batch, worker);
1186
- const tree = trees?.trees.get(domain);
1187
- if (tree) {
1188
- request.cwd = tree.cwd;
1189
- request.ownCheckout = true;
1190
- }
1191
- request.agent = {
1192
- env: session.env(worker),
1193
- extraTools: session.tools(),
1194
- onStart: (handle) => session.attach(worker, handle),
1195
- onAttemptEnd: (run) => {
1196
- const result = parseWorkerResult(domain, run.output);
1197
- session.release(worker, (path, next) => autoNote(domain, path, next, result.filesChanged, result.completed));
1198
- },
1199
- };
1200
- return runWorker(request, deps.runProcess ?? spawnPiProcess);
1201
- });
1202
- unenforced = trees ? [] : runs.filter((run) => !session.greetedBy(run.worker)).map((run) => run.domain);
1203
- } finally {
1204
- await session.close();
1205
- }
1206
- if (trees) {
1207
- const results = await mergeWorkerTrees(trees, batch, join(taskDirFor(deps.root, deps.configDir, task.id), "patches")).catch((error: unknown) => {
1208
- // Keep every worktree: nothing is lost while the oracle sorts it out.
1209
- for (const tree of trees.trees.values()) tree.keep = true;
1210
- return batch.map((worker): MergeOutcome => ({ worker, status: "conflict", patch: "", saved: trees.trees.get(worker)?.dir ?? "", reason: `merging back failed (${(error as Error).message}); the worktree is kept as it was` }));
1211
- });
1212
- // The edits were made in the worktrees: the task's record names the same files in its own tree.
1213
- outcomes = outcomes.map((outcome) => (outcome.run.edited?.length ? { ...outcome, run: { ...outcome.run, edited: outcome.run.edited.map((path) => mapToTop(trees, outcome.result.domain, path)) } } : outcome));
1214
- merged = mergeReport(results);
1215
- }
1295
+ outcomes = await mapConcurrent(runs, deps.config.workflow.maxParallelWorkers, ({ domain, instruction, worker, assignment }) => {
1296
+ const request = workerRequest(deps, task, domain, instruction, batch, worker, assignment);
1297
+ request.agent = {
1298
+ env: session.env(worker),
1299
+ extraTools: session.tools(),
1300
+ onStart: (handle) => session.attach(worker, handle),
1301
+ onAttemptEnd: (run) => {
1302
+ const result = parseWorkerResult(domain, run.output);
1303
+ session.release(worker, (path, next) => autoNote(domain, path, next, result.filesChanged, result.completed));
1304
+ },
1305
+ };
1306
+ return runWorker(request, deps.runProcess ?? spawnPiProcess);
1307
+ });
1308
+ unenforced = runs.filter((run) => !session.greetedBy(run.worker)).map((run) => run.domain);
1216
1309
  } finally {
1217
- if (trees) await closeWorkerTrees(trees);
1310
+ await session.close();
1218
1311
  }
1219
- const reports = outcomes.map((outcome) => absorbWorkerOutcome(task, deps, outcome));
1312
+ const reports = outcomes.map((outcome) => absorbWorkerOutcome(task, deps, outcome, assignments.find((entry) => entry.domain === outcome.result.domain)!.assignment));
1220
1313
  return [
1221
- `Parallel batch: ${batch.join(", ")}${trees ? " (a worktree each)" : ""}.`,
1222
- typeof opened === "string" ? `Worktrees were not used (${opened}); the workers shared the file desk.` : "",
1314
+ `Parallel batch: ${batch.join(", ")}.`,
1223
1315
  ...reports,
1224
- merged,
1225
1316
  handoverLog(session.handovers()),
1226
1317
  unenforced.length > 0
1227
1318
  ? `File checkout was not enforced for ${unenforced.join(", ")} (bot-lobby did not load in those workers); inspect the diff for overlapping edits.`
@@ -1231,24 +1322,6 @@ async function runParallelWorkers(task: Task, deps: WorkflowDeps, assignments: A
1231
1322
  .join("\n\n");
1232
1323
  }
1233
1324
 
1234
- /** What came of applying each worker's worktree back to the task's tree. */
1235
- function mergeReport(results: readonly MergeOutcome[]): string {
1236
- const label = (worker: string): string => AGENT_LABELS[(roleOf(worker) ?? worker) as Domain] ?? worker;
1237
- const applied = results.filter((entry) => entry.status === "applied").map((entry) => label(entry.worker));
1238
- const kept = results.filter((entry): entry is Extract<MergeOutcome, { status: "conflict" | "partial" }> => entry.status === "conflict" || entry.status === "partial");
1239
- return [
1240
- applied.length > 0 ? `Worktrees merged back: ${applied.join(", ")}.` : "",
1241
- ...kept.map((entry) => {
1242
- const where = [entry.patch ? `patch ${entry.patch}` : "", entry.saved.startsWith("refs/") ? `git ref ${entry.saved}` : entry.saved ? `worktree ${entry.saved}` : ""].filter(Boolean).join(", ");
1243
- const state =
1244
- entry.status === "partial"
1245
- ? `, and applying it failed part way: these files are left changed and need checking: ${(entry.leftChanged ?? []).slice(0, 10).join(", ")}`
1246
- : ", so none of it is in the tree";
1247
- return `${label(entry.worker)}'s change did not apply (${truncate(entry.reason, 300)})${state}.${where ? ` It is saved (${where}): delegate a fix step to ${label(entry.worker)} to bring it onto the current files (\`git apply --3way\` on the patch, or \`git diff <ref>^ <ref>\`), reconciling it with the others' changes.` : ""}`;
1248
- }),
1249
- ].filter(Boolean).join("\n");
1250
- }
1251
-
1252
1325
  function handoverLog(handovers: readonly Handover[]): string {
1253
1326
  if (handovers.length === 0) return "";
1254
1327
  const lines = handovers.map((entry) => `- ${entry.path}: ${workerLabel(entry.from)} → ${workerLabel(entry.to)}${entry.auto ? " (on finish)" : ""} — ${truncate(entry.note, 200)}`);
@@ -1347,6 +1420,7 @@ function qaRequest(deps: WorkflowDeps, task: Task, diff: string, risk: QaRiskAss
1347
1420
  board: seedAndReadBoard(taskBoard(deps, task), "qa"),
1348
1421
  ...(provenance && provenance.length > 0 ? { provenance: provenanceLines(provenance) } : {}),
1349
1422
  ...(lint ? { lint: lintContext(lint, deps.config.lint.mode) } : {}),
1423
+ ...(assignmentChecks(task, deps.config.workflow.cleanReview) ? { assignmentChecks: assignmentChecks(task, deps.config.workflow.cleanReview) } : {}),
1350
1424
  instruction: instruction?.trim() || qaInstruction(risk),
1351
1425
  cwd: deps.cwd,
1352
1426
  dataRoots: readDataRoots(deps.root, deps.configDir),
@@ -1358,6 +1432,22 @@ function qaRequest(deps: WorkflowDeps, task: Task, diff: string, risk: QaRiskAss
1358
1432
  };
1359
1433
  }
1360
1434
 
1435
+ /**
1436
+ * What the assignments already settle for QA: the files each one was allowed to
1437
+ * change, and the verification it was briefed with (and, outside a clean review,
1438
+ * what the worker reported). QA starts there,
1439
+ * runs those commands first and widens only where the diff reaches further.
1440
+ */
1441
+ export function assignmentChecks(task: Task, clean = false): string {
1442
+ const lines = (task.workerAssignments ?? []).flatMap(({ domain, brief, outcomes }) => {
1443
+ const latest = outcomes.filter((outcome) => outcome.revision === brief.revision).at(-1);
1444
+ if (!latest || latest.status !== "success") return [];
1445
+ const changed = brief.files.filter((file) => file.access !== "reference").map((file) => file.path);
1446
+ return [`- ${brief.id} r${brief.revision} (${domain}): ${changed.length ? `may change ${changed.join(", ")}` : "read only"}; verify with ${brief.verification.map((entry) => JSON.stringify(entry)).join(", ")}${!clean && latest.verification?.trim() ? `; the worker reported: ${truncate(latest.verification.trim().replace(/\s+/g, " "), 300)}` : ""}`];
1447
+ });
1448
+ return lines.length ? ["Assignments behind this change. Check these files first and run these verification commands before anything broader; widen only where the diff or a failure reaches other code:", ...lines].join("\n") : "";
1449
+ }
1450
+
1361
1451
  /** What the loop does after a QA round: finish, fix and review again, stop, or (the user's call) accept the work as it is. */
1362
1452
  type LoopDecision = "accept" | "iterate" | "blocked" | "waived";
1363
1453
 
@@ -1580,6 +1670,24 @@ function handleKnowledge(task: Task | undefined, params: OrchestrateParams, deps
1580
1670
  return `Recorded ${kind} for ${agent} in ${outcome.path}.`;
1581
1671
  }
1582
1672
 
1673
+ /**
1674
+ * The oracle records a visual choice in the project's design record: one a
1675
+ * designer made during a task where nothing was recorded (the user may
1676
+ * overrule it in Knowledge), or one the user stated in chat. `name` is the
1677
+ * field, `text` the value.
1678
+ */
1679
+ function handleDesign(task: Task | undefined, params: OrchestrateParams, deps: WorkflowDeps): string {
1680
+ const field = params.name?.trim().toLowerCase() ?? "";
1681
+ if (!isDesignField(field)) throw new Error(`design requires name: one of ${DESIGN_FIELD_KEYS.join(", ")}`);
1682
+ const value = params.text?.trim();
1683
+ if (!value) throw new Error("design requires text: the value chosen");
1684
+ const by = params.note?.trim().toLowerCase() === "user" ? "you" : "agent";
1685
+ const path = recordDesignChoices(dataRoot(deps.root, deps.configDir), [{ field, value, by, ...(task && by === "agent" ? { taskId: task.id } : {}), date: new Date().toISOString().slice(0, 10) }]);
1686
+ if (task) recordDecision(task, `Design record: ${field} = ${truncate(value, 120)} (${by === "you" ? "the user" : "agent"})`);
1687
+ lobbyTopics.bump("knowledge");
1688
+ return `Recorded ${field} in the design record (${path}).`;
1689
+ }
1690
+
1583
1691
  /**
1584
1692
  * The oracle manages the task's assignment bookmarks through its own tool:
1585
1693
  * add, remove, pin, unpin or exclude catalogue references for a recipient
@@ -1654,6 +1762,9 @@ function handleCompact(task: Task | undefined, params: OrchestrateParams, deps:
1654
1762
  async function handleComplete(task: Task, params: OrchestrateParams, deps: WorkflowDeps): Promise<string> {
1655
1763
  // The fast track (and a plan QA sat out) completes straight from its work; the full workflow from review.
1656
1764
  requireState(task, onFastTrack(task) || !qaRequired(task) ? ["implementing", "reviewing", "blocked"] : ["reviewing", "blocked"]);
1765
+ await refreshAssignmentEvidence(task, deps);
1766
+ const assignmentHolds = workerAssignmentHolds(task);
1767
+ if (assignmentHolds.length) throw new Error(`cannot complete: ${assignmentHolds.join("; ")}`);
1657
1768
  const joined = await qaJoinsRiskyFastTask(task, deps);
1658
1769
  if (joined) throw new Error(joined);
1659
1770
  // Without QA's part (where the track asks for it) only the user can let the task finish: they are asked, never overruled.
@@ -1664,12 +1775,6 @@ async function handleComplete(task: Task, params: OrchestrateParams, deps: Workf
1664
1775
  // New lint errors in what the task touched hold it in block mode, unless the user accepted the work as it is.
1665
1776
  const lint = await lintTask(task, deps);
1666
1777
  if (lint && lintHolds(lint, deps.config.lint.mode, Boolean(task.lintWaiver))) throw new Error(`cannot complete: ${lintRefusal(lint)}`);
1667
- const goal = await checkGoal(task, params, deps);
1668
- if (goal.refusal) {
1669
- // The refusal is recorded, so a reason on the next complete is an answer to it.
1670
- saveTask(deps.root, deps.configDir, task);
1671
- throw new Error(goal.refusal);
1672
- }
1673
1778
  // The gate refuses before any side effect, so a refusal leaves the task untouched.
1674
1779
  const oversized = overThreshold(readDataRoots(deps.root, deps.configDir), deps.config.knowledge.compactionThreshold);
1675
1780
  if (oversized.length > 0) throw new Error(`cannot complete: knowledge files over the compaction threshold: ${oversized.map((entry) => `${entry.agent}/${entry.file} (${entry.chars})`).join(", ")}. First record domain-relevant facts where they belong with action=knowledge (domain=designer|backend|qa), then rewrite each oversized file with action=compact, then call complete again.`);
@@ -1692,61 +1797,7 @@ async function handleComplete(task: Task, params: OrchestrateParams, deps: Workf
1692
1797
  flushDecisions(deps, task);
1693
1798
  const delivery = await offerDelivery(task, deps);
1694
1799
  const left = lint?.state === "failing" ? ` ${task.lintWaiver ? "Accepted by the user with lint errors" : "Lint (advisory)"}: ${lintSummary(lint)} Tell the user.` : "";
1695
- return `Task ${task.id} completed.${committed} History recorded and temporary scratchpads removed. ${delivery}${left}${goal.note ?? ""}`;
1696
- }
1697
-
1698
- /**
1699
- * The goal check before completion: one read-only agent compares the change
1700
- * with the user's own request (not the plan). Gaps refuse completion once;
1701
- * the oracle fixes them, or completes again with a `reason` when they are
1702
- * deliberate (the user agreed). The same change is never checked twice, and
1703
- * an unreadable check holds nothing.
1704
- */
1705
- /** Enough of the change to tell one from another; the check itself reads a shorter cut. */
1706
- const GOAL_HASH_CHARS = 4_000_000;
1707
-
1708
- async function checkGoal(task: Task, params: OrchestrateParams, deps: WorkflowDeps): Promise<{ refusal?: string; note?: string }> {
1709
- if (!deps.config.workflow.goalCheck || !builtSomething(task) || task.qaWaiver) return {};
1710
- const base = await reviewBase(task, deps);
1711
- // The whole change is hashed, so an edit past what the check reads still counts as a new change.
1712
- const diff = await readRepositoryDiff(deps.cwd, { ...(base ? { base } : {}), exclude: ownRecords(deps), limitChars: GOAL_HASH_CHARS });
1713
- if (!diff.trim() || /^Unable to read git state/.test(diff)) return {};
1714
- const key = createHash("sha256").update(diff).digest("hex").slice(0, 16);
1715
- if (task.goalCheck?.key !== key) {
1716
- let result: Awaited<ReturnType<typeof runGoalCheck>> | undefined;
1717
- // One more read when the first could not be read: a lost verdict should not let a gap through unseen.
1718
- for (let attempt = 0; attempt < 2 && result?.verdict !== "met" && result?.verdict !== "not_met"; attempt++) {
1719
- deps.signal?.throwIfAborted();
1720
- result = await runGoalCheck({
1721
- taskId: task.id,
1722
- request: taskRequest(task),
1723
- amendments: task.amendments,
1724
- diff,
1725
- cwd: deps.cwd,
1726
- config: deps.config,
1727
- ...(deps.profile ? { profile: deps.profile } : {}),
1728
- ...(deps.signal ? { signal: deps.signal } : {}),
1729
- ...(deps.onUpdate ? { onUpdate: deps.onUpdate } : {}),
1730
- }, deps.runProcess ?? spawnPiProcess);
1731
- }
1732
- deps.signal?.throwIfAborted();
1733
- if (!result || result.verdict === "unread") {
1734
- // Not recorded, so the next complete checks again.
1735
- const why = result?.run.error ? `: ${truncate(result.run.error, 160)}` : "";
1736
- return { note: ` The goal check could not be read (twice${why}), so the change was not checked against the request; tell the user.` };
1737
- }
1738
- task.goalCheck = { key, verdict: result.verdict, gaps: result.gaps, at: new Date().toISOString() };
1739
- }
1740
- const check = task.goalCheck!;
1741
- if (check.verdict !== "not_met") return {};
1742
- const gaps = check.gaps.slice(0, 12).map((gap) => `- ${truncate(gap, 300)}`).join("\n");
1743
- // A reason answers a refusal the oracle has seen; given up front, it is not an answer to anything yet.
1744
- if (params.reason?.trim() && check.refusedAt) {
1745
- recordDecision(task, `Completed although the goal check named gaps (${check.gaps.map((gap) => truncate(gap, 120)).join("; ")}): ${params.reason.trim()}`);
1746
- return { note: ` Completed with the goal check's gaps left open, because: ${truncate(params.reason.trim(), 300)}. Tell the user which parts of their request are not done:\n${gaps}` };
1747
- }
1748
- check.refusedAt = new Date().toISOString();
1749
- return { refusal: `cannot complete: the goal check read the change against the user's request and found it does not meet all of it:\n${gaps}\nDelegate a fix step for each gap and complete again (the next check reads the new change). If a gap is deliberate (the user agreed to leave it out, or it is out of scope), call complete again with reason saying so; tell the user.` };
1800
+ return `Task ${task.id} completed.${committed} History recorded and temporary scratchpads removed. ${delivery}${left}`;
1750
1801
  }
1751
1802
 
1752
1803
  /** The files a task's own workers changed: not one that held changes before they started, nor another task's. */
@@ -1927,7 +1978,8 @@ async function handleTrack(task: Task, params: OrchestrateParams, deps: Workflow
1927
1978
  return `Full workflow: ${rosterWords(roster)}. Scout what the request touches, then propose a short bullet list for approval.`;
1928
1979
  }
1929
1980
 
1930
- function handleDecide(task: Task, params: OrchestrateParams): string {
1981
+ async function handleDecide(task: Task, params: OrchestrateParams, deps: WorkflowDeps): Promise<string> {
1982
+ if (params.discoveryAllowance !== undefined) return decideDiscoveryAllowance(task, params, deps);
1931
1983
  const text = params.text?.trim();
1932
1984
  if (!text) throw new Error("decide requires text");
1933
1985
  const domain = params.domain && isDomain(params.domain) ? params.domain : "master";
@@ -1971,6 +2023,7 @@ const HANDLERS: Record<OrchestrateAction, (task: Task, params: OrchestrateParams
1971
2023
  knowledge: handleKnowledge,
1972
2024
  bookmark: handleBookmark,
1973
2025
  script: handleScript,
2026
+ design: handleDesign,
1974
2027
  compact: handleCompact,
1975
2028
  complete: handleComplete,
1976
2029
  block: handleBlock,
@@ -1987,9 +2040,9 @@ const HANDLERS: Record<OrchestrateAction, (task: Task, params: OrchestrateParams
1987
2040
  */
1988
2041
  export async function runWorkflowAction(params: OrchestrateParams, deps: WorkflowDeps): Promise<WorkflowResult> {
1989
2042
  // Project knowledge can be learned without starting or changing a task.
1990
- if ((params.action === "knowledge" || params.action === "compact" || params.action === "script") && !params.taskId) {
2043
+ if ((params.action === "knowledge" || params.action === "compact" || params.action === "script" || params.action === "design") && !params.taskId) {
1991
2044
  try {
1992
- const message = params.action === "knowledge" ? handleKnowledge(undefined, params, deps) : params.action === "script" ? handleScript(undefined, params, deps) : handleCompact(undefined, params, deps);
2045
+ const message = params.action === "knowledge" ? handleKnowledge(undefined, params, deps) : params.action === "script" ? handleScript(undefined, params, deps) : params.action === "design" ? handleDesign(undefined, params, deps) : handleCompact(undefined, params, deps);
1993
2046
  return { ok: true, taskId: "", state: "created", message };
1994
2047
  } catch (error) {
1995
2048
  return { ok: false, taskId: "", state: "created", message: `Rejected: ${(error as Error).message}` };
@@ -2061,6 +2114,10 @@ export async function runWorkflowAction(params: OrchestrateParams, deps: Workflo
2061
2114
  execution.signal.throwIfAborted();
2062
2115
  const runs = recordRunLog(task, finished, deps);
2063
2116
  saveTask(deps.root, deps.configDir, task);
2117
+ if (TERMINAL_STATES.includes(task.state)) {
2118
+ cleanupTaskAssignedSessions(taskDirFor(deps.root, deps.configDir, task.id));
2119
+ void stopScoutPrefetch(task.id);
2120
+ }
2064
2121
  return { ok: true, taskId: task.id, state: task.state, message: `${message}${runsFooter(runs)}`, runs };
2065
2122
  } catch (error) {
2066
2123
  const runs = recordRunLog(task, finished, deps);