@a-t-h-i/bot-lobby 0.6.79 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/THIRD_PARTY_NOTICES.md +0 -1
  2. package/package.json +1 -1
  3. package/prompts/lobby-chat.md +1 -1
  4. package/prompts/master.md +15 -2
  5. package/prompts/panel.md +4 -4
  6. package/prompts/planner.md +2 -2
  7. package/prompts/worker.md +6 -1
  8. package/src/ask/tool.ts +1 -1
  9. package/src/classifier/effort.ts +5 -0
  10. package/src/classifier/files.ts +7 -0
  11. package/src/classifier/knowledge.ts +88 -0
  12. package/src/classifier/lobby.ts +1 -1
  13. package/src/desk/board-client.ts +1 -1
  14. package/src/desk/board.ts +1 -1
  15. package/src/execution/assignment.ts +77 -1
  16. package/src/execution/delegation.ts +80 -27
  17. package/src/execution/verification.ts +216 -0
  18. package/src/knowledge/catalog-tools.ts +1 -1
  19. package/src/knowledge/catalogue.ts +21 -6
  20. package/src/knowledge/compactor.ts +212 -5
  21. package/src/knowledge/oracle-digest.ts +2 -2
  22. package/src/knowledge/paths.ts +9 -0
  23. package/src/knowledge/repo-map.ts +1 -0
  24. package/src/knowledge/retrieval.ts +8 -2
  25. package/src/knowledge/store.ts +68 -14
  26. package/src/lobby/chat-agents.ts +57 -8
  27. package/src/lobby/feed.ts +2 -2
  28. package/src/lobby/knowledge.ts +3 -3
  29. package/src/lobby/pi-commands.ts +1 -1
  30. package/src/lobby/planner.ts +6 -6
  31. package/src/lobby/prompts.ts +2 -2
  32. package/src/lobby/runtime.ts +4 -4
  33. package/src/lobby/service.ts +88 -51
  34. package/src/master/master.ts +87 -14
  35. package/src/master/scout-prefetch.ts +14 -1
  36. package/src/pi/commands.ts +28 -10
  37. package/src/pi/events.ts +21 -10
  38. package/src/pi/owner.ts +21 -3
  39. package/src/pi/start-task.ts +9 -6
  40. package/src/pi/switch-pending.ts +24 -0
  41. package/src/pi/tools.ts +14 -0
  42. package/src/roles/worker.ts +33 -3
  43. package/src/schemas/configuration.ts +9 -0
  44. package/src/schemas/task.ts +18 -0
  45. package/src/schemas/verification.ts +38 -0
  46. package/src/state/metrics.ts +32 -2
  47. package/src/webui/api/knowledge.ts +1 -1
  48. package/src/webui/api/tasks.ts +1 -1
  49. package/src/webui/dev/fake-service.ts +7 -7
  50. package/src/workflow/track.ts +65 -3
  51. package/src/workflow/workflow.ts +142 -17
  52. package/webui/dist/assets/{CodeSurface-DZdLN-w3.js → CodeSurface-FHm02AXI.js} +1 -1
  53. package/webui/dist/assets/{TerminalView-CRwPTCho.js → TerminalView-Be3q2ej_.js} +1 -1
  54. package/webui/dist/assets/{index-CiUnrnfa.js → index-B_7Iioqo.js} +45 -45
  55. package/webui/dist/assets/index-DPP8sEwW.css +2 -0
  56. package/webui/dist/build.json +59 -59
  57. package/webui/dist/index.html +2 -2
  58. package/webui/dist/assets/index-CTNZ-wc_.css +0 -2
@@ -20,7 +20,6 @@ naming the file it came from.
20
20
  | `webui/src/components/ui/button.tsx` | `apps/web/src/components/ui/button.tsx` |
21
21
  | `webui/src/components/ui/input.tsx` | `apps/web/src/components/ui/input.tsx` |
22
22
  | `webui/src/components/ui/textarea.tsx` | `apps/web/src/components/ui/textarea.tsx` |
23
- | `webui/src/components/ui/tooltip.tsx` | `apps/web/src/components/ui/tooltip.tsx` |
24
23
  | `webui/src/components/ui/kbd.tsx` | `apps/web/src/components/ui/kbd.tsx` |
25
24
  | `webui/src/components/ui/checkbox.tsx` | `apps/web/src/components/ui/checkbox.tsx` |
26
25
  | `webui/src/components/ui/switch.tsx` | `apps/web/src/components/ui/switch.tsx` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-t-h-i/bot-lobby",
3
- "version": "0.6.79",
3
+ "version": "0.7.0",
4
4
  "description": "Structured multi-agent software engineering orchestrator for Pi",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -4,7 +4,7 @@ You are answering the user directly in Bot Lobby's chat. There is no task,
4
4
  brief, plan or review round here: the user talks to the team the way they
5
5
  would talk to a colleague, and this message was given to you because it is
6
6
  yours to answer (they named you with an @ mention, or the classifier judged
7
- it your area). The Master (the oracle) and the other agents share this chat
7
+ it your area). The Master (the orchestrator) and the other agents share this chat
8
8
  and read your reply.
9
9
 
10
10
  ## How to work
package/prompts/master.md CHANGED
@@ -139,6 +139,16 @@ structured assignment there, so send that step as a prose `task`. Fields:
139
139
  requested}]`: open expansion requests; requests grant nothing.
140
140
  - Optional `discoveryLimit` (default two, never reset by a retry or
141
141
  revision; raising it needs an explicit allowance decision).
142
+ - Optional `contextPack`: the exact context the worker needs on turn one —
143
+ `{version: 1, files: [{path, ranges: [[start, end]], fingerprint,
144
+ snippet}], invariants, priorWork, verification}`. Give exact paths with
145
+ line ranges, bounded snippets (at most 2,000 characters each; 24,000 for
146
+ the whole pack), content fingerprints from your own reads, the invariants
147
+ that must hold, prior work already landed, and the verification you expect.
148
+ The engine validates the pack before launch and refreshes stale
149
+ fingerprints at dispatch, so the worker never re-discovers what you already
150
+ know. Batch it instead of sending a scout or making the worker re-read
151
+ everything.
142
152
 
143
153
  The engine validates every brief before a batch starts; fix a rejected one,
144
154
  never retry with prose alone. Reads of assigned files and verification are
@@ -159,6 +169,8 @@ self-contained, in this order:
159
169
  the step number(s).
160
170
  2. **Files**: exact paths to change and to leave alone, with line anchors
161
171
  from the scouts' Relevant Files (`src/auth.ts:40-62`) where you have them.
172
+ When you already hold the exact context, put it in the assignment's
173
+ `contextPack` instead of briefing the worker to re-discover it.
162
174
  3. **What to do**: numbered, concrete actions with exact names, signatures,
163
175
  shapes, strings and values. "Use X", never "a suitable X".
164
176
  4. **Contracts**: everything shared with another domain or step, in full in
@@ -199,8 +211,9 @@ Every delegation costs a full agent run:
199
211
  acceptance criteria; it follows `done` posts.
200
212
  - Scout all touched domains in one `scout` call with pointed questions. A
201
213
  scout over the triage's domains may have started with the task: your first
202
- scout call returns its findings. Skip scouting when the evidence is enough;
203
- a reused result is fresh. Target-verify one claim rather than re-scout.
214
+ scout call returns its findings. Skip scouting when the evidence is enough
215
+ (a reused result is fresh, or your own reads fill the `contextPack`);
216
+ target-verify one claim rather than re-scout.
204
217
  - After a worker returns, check `git diff --stat` and the report; leave deep
205
218
  verification to the QA gate. Make independent reads in one turn.
206
219
  - Use fewer agents with fuller briefs: one worker for one domain or any
package/prompts/panel.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Planning Panel Member
2
2
 
3
3
  You sit on the planning panel for a task that has not started yet. The panel
4
- is the oracle plus one member per domain — DEV, DESIGN, QA and RESEARCH — and
4
+ is the orchestrator plus one member per domain — DEV, DESIGN, QA and RESEARCH — and
5
5
  the user answers everyone's questions in one conversation, so every agent that
6
6
  later works on the task starts from the same decisions.
7
7
 
@@ -13,7 +13,7 @@ conversation ends with **Likely files**, read those first; `find_relevant_files`
13
13
  ## Each round
14
14
 
15
15
  You receive the conversation so far, including every panel member's earlier
16
- questions and the user's answers, and the oracle's current draft plan.
16
+ questions and the user's answers, and the orchestrator's current draft plan.
17
17
 
18
18
  - Ask only what your seat owns (below), and only what would change how the
19
19
  task is built or verified. Never repeat a question that has been answered,
@@ -23,7 +23,7 @@ questions and the user's answers, and the oracle's current draft plan.
23
23
  rephrased. If an answer looks wrong or thin, say so under Notes; do not
24
24
  ask it a second time.
25
25
  - Ask at most two questions, the most important first. They go to the
26
- oracle, who picks at most four for the user each round across the whole
26
+ orchestrator, who picks at most four for the user each round across the whole
27
27
  panel and decides the rest with your recommendation, so make each one
28
28
  short, plain and specific, and give it two to four options in a neutral
29
29
  order. Do not recommend one: the user should think the decision through.
@@ -40,7 +40,7 @@ questions and the user's answers, and the oracle's current draft plan.
40
40
  decided, not grey boxes. The user sees each as a
41
41
  thumbnail beside the question and expands them to scroll through the
42
42
  options side by side. DESIGN draws for every visual question; any seat may.
43
- - Read the draft's Assumptions: if one the oracle made for your seat is
43
+ - Read the draft's Assumptions: if one the orchestrator made for your seat is
44
44
  wrong, say so under Notes and ask about it again.
45
45
  - If an answer from the user is vague or conflicts with what you see in the
46
46
  repository, say so and ask again.
@@ -1,6 +1,6 @@
1
1
  # Task Planner
2
2
 
3
- You are the oracle chairing a planning panel: you help the user turn an idea
3
+ You are the orchestrator chairing a planning panel: you help the user turn an idea
4
4
  (or a GitHub issue) into a task plan that the team of agents can execute
5
5
  without guessing. The panel's domain members — DEV, DESIGN, QA and RESEARCH —
6
6
  bring you their questions in the first round; after that you plan alone and
@@ -27,7 +27,7 @@ below.
27
27
  what the repository or an earlier answer already settles, and keep only the
28
28
  ones whose answer changes what gets built. Put the most important first and
29
29
  start each with the seat it serves — `[DEV]`, `[DESIGN]`, `[QA]`,
30
- `[RESEARCH]`, or `[ORACLE]` for your own. When members disagree, make that
30
+ `[RESEARCH]`, or `[ORCHESTRATOR]` for your own. When members disagree, make that
31
31
  one of the questions.
32
32
  - Keep each question short and plain: one line the user can answer at a
33
33
  glance. Give it two to four options — labels of one to five words and a
package/prompts/worker.md CHANGED
@@ -12,6 +12,11 @@ domain-specific responsibility.
12
12
  - When the `find_relevant_files` tool is available, describe what you need in
13
13
  plain words before walking the tree.
14
14
  - Identify relevant tests.
15
+ - When your brief carries a context pack, trust it: its paths, line ranges,
16
+ fingerprints and snippets were current at dispatch, and what dispatch
17
+ refreshed is named with the pack. Re-read a packed file only when you will
18
+ edit it, reading just the needed line range, and make independent reads in
19
+ one batch instead of sequential re-discovery.
15
20
 
16
21
  You may disagree with Scout findings when repository evidence contradicts
17
22
  them.
@@ -100,7 +105,7 @@ repository at the same time, and files are checked out like physical documents:
100
105
  nothing else.
101
106
  - Verify tests.
102
107
  - Update the temporary task scratchpad.
103
- - Do not commit, stage or stash: the oracle commits the task's work.
108
+ - Do not commit, stage or stash: the orchestrator commits the task's work.
104
109
  - Report concise results.
105
110
 
106
111
  ## Pushback
package/src/ask/tool.ts CHANGED
@@ -51,7 +51,7 @@ const DESCRIPTION = [
51
51
  "Do not use it for yes/no confirmations of what you were already told to do, or for questions the conversation already answers.",
52
52
  ].join(" ");
53
53
 
54
- const RELAYED = "Your questions reach the user through the oracle, and your clock stops while they answer. Ask only what is theirs to decide (a visual direction, a layout, a trade-off they care about), all at once; decide the rest yourself.";
54
+ const RELAYED = "Your questions reach the user through the orchestrator, and your clock stops while they answer. Ask only what is theirs to decide (a visual direction, a layout, a trade-off they care about), all at once; decide the rest yourself.";
55
55
 
56
56
  /** Why a set of questions cannot be asked as given, or undefined when it can. */
57
57
  export function invalidQuestions(questions: readonly AskQuestion[]): string | undefined {
@@ -107,6 +107,11 @@ export interface EffortScore {
107
107
  confidence: number;
108
108
  }
109
109
 
110
+ /** The effort reading as one line of a fast path's basis: `effort: simple (0.88)`. */
111
+ export function effortBasis(scored: EffortScore | undefined): string | undefined {
112
+ return scored ? `effort: ${scored.level} (${scored.confidence.toFixed(2)})` : undefined;
113
+ }
114
+
110
115
  /** Lowers the model or thinking of a step the classifier judges simple or trivial. */
111
116
  export interface EffortRouter {
112
117
  /** Children may raise reasoning for complex work, using the parent's configured model. */
@@ -489,6 +489,8 @@ export function likelyFilesBlock(result: LikelyFiles | undefined): string {
489
489
  export interface FileHinter {
490
490
  /** The Likely files block for a step, or "" (off, nothing stands out, out of time). */
491
491
  block(query: string, signal?: AbortSignal, context?: string): Promise<string>;
492
+ /** The same call's likely paths, newest first, or [] — so a caller can build a fingerprinted context pack from them. */
493
+ paths?(query: string, signal?: AbortSignal): Promise<string[]>;
492
494
  /** Tools to add to a subagent's allowlist: `find_relevant_files` while file hints are on. */
493
495
  tools(): readonly string[];
494
496
  }
@@ -502,6 +504,11 @@ export function fileHinter(classifier: Classifier, scope: FileScope, log?: (text
502
504
  if (result) log?.(block ? `likely files: ${result.files.map((file) => `${file.path} (${file.relevance.toFixed(2)})`).join(", ")} · ${result.ms} ms` : `no file stands out (${result.anyRelevant.toFixed(2)}) · ${result.ms} ms`);
503
505
  return block;
504
506
  },
507
+ async paths(query, signal) {
508
+ if (!classifier.enabled("files")) return [];
509
+ const result = await likelyFiles(classifier, scope, query, { ...(signal ? { signal } : {}), budgetMs: classifier.config.fileHints.budgetMs });
510
+ return result?.files.map((file) => file.path) ?? [];
511
+ },
505
512
  tools: () => (classifier.enabled("files") ? [FIND_FILES_TOOL] : []),
506
513
  };
507
514
  }
@@ -23,6 +23,8 @@ import type { ScriptPicker } from "../scripts/pick.ts";
23
23
 
24
24
  /** How many characters of each knowledge file a prompt has room for. */
25
25
  export const KNOWLEDGE_BUDGET_CHARS = 4000;
26
+ /** One combined budget across everything a prompt injects as knowledge (standards, knowledge, decisions, bookmarks, scripts): 8,000 characters per role by default. */
27
+ export const STARTUP_KNOWLEDGE_BUDGET_CHARS = 8000;
26
28
  /** A section is judged on its first characters; the whole section is kept when it stays. */
27
29
  export const SECTION_EXCERPT_CHARS = 700;
28
30
  /** Sections judged per file; a longer file is narrowed by keywords first. */
@@ -104,6 +106,92 @@ export function leftOutNote(kept: Kept, name: string, path?: string): string {
104
106
  : `_Kept ${kept.kept} of ${kept.total} sections of ${name} for this step.${where}_`;
105
107
  }
106
108
 
109
+ /** One knowledge section a prompt may inject, before the combined startup budget applies. */
110
+ export interface StartupSection {
111
+ name: string;
112
+ content: string;
113
+ /** Pinned rules or user annotations: never truncated, whatever the budget says. */
114
+ protected?: boolean;
115
+ /** Where the whole content lives, for the left-out notes. */
116
+ path?: string;
117
+ }
118
+
119
+ /** The marker `pinFirst` puts above a slice that carries pinned rules. */
120
+ const PINNED_MARKER = "## Pinned";
121
+
122
+ /** A section that carries pinned rules (the pin block) is protected content. */
123
+ export function isProtectedKnowledge(content: string): boolean {
124
+ return content.includes(PINNED_MARKER);
125
+ }
126
+
127
+ /** `(1.2k chars)` — the size note each injected section header carries. */
128
+ export function sectionSizeNote(chars: number): string {
129
+ return chars >= 1000 ? `${(Math.round(chars / 100) / 10).toFixed(1)}k chars` : `${chars} chars`;
130
+ }
131
+
132
+ function withSize(content: string): string {
133
+ return `*(${sectionSizeNote(content.length)})*\n\n${content}`;
134
+ }
135
+
136
+ /** Whitespace-normalized equality is exact enough to drop a repeated section. */
137
+ function normalizedKey(content: string): string {
138
+ return content.replace(/\s+/g, " ").trim().toLowerCase();
139
+ }
140
+
141
+ export interface StartupBudgetResult {
142
+ sections: StartupSection[];
143
+ /** Visible diagnostics: protected content kept whole over budget, duplicates dropped, sections left out. */
144
+ diagnostics: string[];
145
+ }
146
+
147
+ /**
148
+ * One combined budget across every injected knowledge section of a prompt.
149
+ * Protected content (pinned rules, user annotations) is never truncated: when
150
+ * it alone exceeds the budget it is kept whole and a diagnostic names the
151
+ * file and its size. Anything else is kept whole while it fits, clipped once,
152
+ * then left out with a note saying where the whole content is. The same
153
+ * history or decision content is never injected twice: an exact duplicate of
154
+ * an earlier section is dropped with a diagnostic. Every kept section records
155
+ * its size under its header as `(1.2k chars)`.
156
+ */
157
+ export function applyStartupBudget(sections: readonly StartupSection[], budget: number = STARTUP_KNOWLEDGE_BUDGET_CHARS): StartupBudgetResult {
158
+ const diagnostics: string[] = [];
159
+ const seen = new Set<string>();
160
+ const marked: StartupSection[] = sections.map((section) => {
161
+ if (!section.content.trim()) return { ...section, content: "" };
162
+ const key = normalizedKey(section.content);
163
+ if (seen.has(key)) {
164
+ diagnostics.push(`${section.name}: duplicate of content already injected above; not repeated.`);
165
+ return { ...section, content: "" };
166
+ }
167
+ seen.add(key);
168
+ return { ...section, protected: section.protected ?? isProtectedKnowledge(section.content) };
169
+ });
170
+ const guarded = marked.filter((section) => section.protected && section.content);
171
+ const guardedChars = guarded.reduce((total, section) => total + section.content.length, 0);
172
+ if (guardedChars > budget) {
173
+ for (const section of guarded) {
174
+ diagnostics.push(`Protected content in ${section.path ?? section.name} (${sectionSizeNote(section.content.length)}) alone exceeds the startup knowledge budget (${sectionSizeNote(budget)}); kept whole, not truncated.`);
175
+ }
176
+ }
177
+ let remaining = Math.max(0, budget - guardedChars);
178
+ const budgeted = marked.map((section): StartupSection => {
179
+ if (!section.content) return section;
180
+ if (section.protected) return { ...section, content: withSize(section.content) };
181
+ if (remaining <= 0) {
182
+ return { ...section, content: `_Left out to hold the startup knowledge budget; the whole content is ${section.path ?? `in ${section.name}`}._` };
183
+ }
184
+ if (section.content.length <= remaining) {
185
+ remaining -= section.content.length;
186
+ return { ...section, content: withSize(section.content) };
187
+ }
188
+ const clipped = clip(section.content, remaining).trimEnd();
189
+ remaining = 0;
190
+ return { ...section, content: `${withSize(clipped)}\n\n_Trimmed to hold the startup knowledge budget; the whole content is ${section.path ?? `in ${section.name}`}._` };
191
+ });
192
+ return { sections: budgeted, diagnostics };
193
+ }
194
+
107
195
  /** Picks what an agent's prompt carries of its knowledge files, and of the shared scripts. */
108
196
  export interface KnowledgePicker {
109
197
  select(task: string, files: KnowledgeInput, options?: { signal?: AbortSignal; paths?: KnowledgePaths }): Promise<KnowledgeSelection>;
@@ -15,7 +15,7 @@ import { clip } from "./limits.ts";
15
15
  export type ChatRoute = ChatAgent | "knowledge";
16
16
 
17
17
  const ROUTES: Record<ChatRoute, string> = {
18
- master: "The Master (the oracle): general conversation, the team's tasks and plans, anything across several areas of the project, or anything no single agent below clearly owns",
18
+ master: "The Master (the orchestrator): general conversation, the team's tasks and plans, anything across several areas of the project, or anything no single agent below clearly owns",
19
19
  designer: "DESIGN: the frontend, meaning pages, components, styling, layout, UX, on-screen copy and browser code, whether a question about it or a change to it",
20
20
  backend: "DEV: backend code, meaning APIs, data and databases, server logic, integrations, scripts, build and tooling, whether a question about it or a change to it",
21
21
  qa: "QA: tests, meaning writing, running or fixing them, test strategy, how to verify a change, or checking work for bugs",
@@ -46,7 +46,7 @@ export function registerBoardClient(pi: ExtensionAPI, env: NodeJS.ProcessEnv = p
46
46
  name: "post_board",
47
47
  label: "Post to the task board",
48
48
  description:
49
- "Post a short, typed entry on the task board that every agent on this task can read: `contract` (an interface others build against: a route, a payload shape, a type, an event name, file location), `decision` (a choice others should follow), `blocker` (something stopping you that someone else must change), `question` (open, for the oracle), `done` (a piece is finished and ready to test), `note`. Unaddressed contracts and blockers reach the other running workers at once; `to` (worker ids: backend, designer, qa, a child id) or `files` narrows who is pushed it. Post facts, not progress chatter.",
49
+ "Post a short, typed entry on the task board that every agent on this task can read: `contract` (an interface others build against: a route, a payload shape, a type, an event name, file location), `decision` (a choice others should follow), `blocker` (something stopping you that someone else must change), `question` (open, for the orchestrator), `done` (a piece is finished and ready to test), `note`. Unaddressed contracts and blockers reach the other running workers at once; `to` (worker ids: backend, designer, qa, a child id) or `files` narrows who is pushed it. Post facts, not progress chatter.",
50
50
  parameters: Type.Object({
51
51
  kind: Type.Union(POST_KINDS.map((kind) => Type.Literal(kind))),
52
52
  text: Type.String({ description: "The post: the exact facts, at most a short paragraph" }),
package/src/desk/board.ts CHANGED
@@ -184,7 +184,7 @@ export function filterPosts(posts: readonly BoardPost[], filter: BoardFilter): B
184
184
  return filter.limit && matching.length > filter.limit ? matching.slice(-filter.limit) : matching;
185
185
  }
186
186
 
187
- const NAMES: Record<string, string> = { backend: "DEV", designer: "DESIGN", qa: "QA", oracle: "ORACLE" };
187
+ const NAMES: Record<string, string> = { backend: "DEV", designer: "DESIGN", qa: "QA", oracle: "ORCHESTRATOR" };
188
188
 
189
189
  export function posterName(from: string): string {
190
190
  const role = roleOf(from);
@@ -13,6 +13,30 @@ export interface AssignmentExpansionRequest {
13
13
  requested: string[];
14
14
  }
15
15
 
16
+ /** One file of a context pack: an exact path with optional line ranges, a content fingerprint and a bounded snippet. */
17
+ export interface ContextPackFile {
18
+ path: string;
19
+ /** Line ranges as [start, end] with 1 <= start <= end. */
20
+ ranges?: Array<[number, number]>;
21
+ /** Cheap content hash at pack-build time; dispatch refreshes entries whose fingerprint no longer matches. */
22
+ fingerprint?: string;
23
+ /** At most 2,000 characters of the file, current at pack-build time. */
24
+ snippet?: string;
25
+ }
26
+
27
+ /** Versioned, validated worker context: exact paths, bounded snippets, invariants, prior work and verification, rendered once into the initial worker prompt. */
28
+ export interface ContextPack {
29
+ version: 1;
30
+ files: ContextPackFile[];
31
+ invariants?: string[];
32
+ priorWork?: string[];
33
+ verification: string[];
34
+ }
35
+
36
+ /** Total pack size, serialized, and the largest a single snippet may be. */
37
+ export const CONTEXT_PACK_MAX_CHARS = 24_000;
38
+ export const CONTEXT_SNIPPET_MAX_CHARS = 2_000;
39
+
16
40
  export interface WorkerAssignment {
17
41
  id: string;
18
42
  revision: number;
@@ -29,6 +53,8 @@ export interface WorkerAssignment {
29
53
  needs: AssignmentExpansionRequest[];
30
54
  /** Total allowance, not a fresh allowance on retry or revision. */
31
55
  discoveryLimit?: number;
56
+ /** Reusable context rendered once into the initial worker prompt; validated before dispatch. */
57
+ contextPack?: ContextPack;
32
58
  }
33
59
 
34
60
  export class AssignmentValidationError extends Error {
@@ -64,11 +90,12 @@ function texts(value: unknown, label: string, required = false): void {
64
90
  }
65
91
 
66
92
  function validateShape(input: unknown): WorkerAssignment {
67
- const a = object(input, ["id", "revision", "objective", "actions", "files", "contracts", "constraints", "exclusions", "tools", "verification", "evidence", "completedWork", "needs", "discoveryLimit"], "assignment");
93
+ const a = object(input, ["id", "revision", "objective", "actions", "files", "contracts", "constraints", "exclusions", "tools", "verification", "evidence", "completedWork", "needs", "discoveryLimit", "contextPack"], "assignment");
68
94
  text(a.id, "id");
69
95
  text(a.objective, "objective");
70
96
  requireValue(Number.isSafeInteger(a.revision) && Number(a.revision) > 0, "revision must be a positive integer");
71
97
  requireValue(a.discoveryLimit === undefined || (Number.isSafeInteger(a.discoveryLimit) && Number(a.discoveryLimit) >= 0), "discoveryLimit must be a non-negative integer");
98
+ validateContextPackShape(a.contextPack);
72
99
  validateActions(a.actions);
73
100
  validateFiles(a.files);
74
101
  validateTools(a.tools);
@@ -112,6 +139,33 @@ function validateNeeds(value: unknown): void {
112
139
  });
113
140
  }
114
141
 
142
+ /** Shape-only pack checks; path scope is checked against the project root in validateAssignment. */
143
+ function validateContextPackShape(value: unknown): void {
144
+ if (value === undefined) return;
145
+ const pack = object(value, ["version", "files", "invariants", "priorWork", "verification"], "contextPack");
146
+ requireValue(pack.version === 1, "contextPack.version must be 1");
147
+ const total = JSON.stringify(pack).length;
148
+ requireValue(total <= CONTEXT_PACK_MAX_CHARS, `contextPack is ${total} characters; at most ${CONTEXT_PACK_MAX_CHARS} are allowed: trim snippets, ranges or arrays`);
149
+ list(pack.files, "contextPack.files").forEach((entry, i) => {
150
+ const file = object(entry, ["path", "ranges", "fingerprint", "snippet"], `contextPack.files[${i}]`);
151
+ text(file.path, `contextPack.files[${i}].path`);
152
+ requireValue(!/[\0*?\[\]{}]/.test(file.path), `contextPack.files[${i}].path must be an exact path, not a pattern`);
153
+ if (file.ranges !== undefined) list(file.ranges, `contextPack.files[${i}].ranges`).forEach((range, r) => {
154
+ requireValue(Array.isArray(range) && range.length === 2 && range.every((bound) => Number.isSafeInteger(bound)), `contextPack.files[${i}].ranges[${r}] must be [start, end] integers`);
155
+ const [start, end] = range as [number, number];
156
+ requireValue(start >= 1 && start <= end, `contextPack.files[${i}].ranges[${r}] must satisfy 1 <= start <= end (got ${start}-${end})`);
157
+ });
158
+ if (file.fingerprint !== undefined) text(file.fingerprint, `contextPack.files[${i}].fingerprint`);
159
+ if (file.snippet !== undefined) {
160
+ requireValue(typeof file.snippet === "string", `contextPack.files[${i}].snippet must be text`);
161
+ requireValue(file.snippet.length <= CONTEXT_SNIPPET_MAX_CHARS, `contextPack.files[${i}].snippet is ${file.snippet.length} characters; at most ${CONTEXT_SNIPPET_MAX_CHARS} are allowed (${file.path})`);
162
+ }
163
+ });
164
+ if (pack.invariants !== undefined) texts(pack.invariants, "contextPack.invariants");
165
+ if (pack.priorWork !== undefined) texts(pack.priorWork, "contextPack.priorWork");
166
+ texts(pack.verification, "contextPack.verification", true);
167
+ }
168
+
115
169
  function inside(root: string, path: string): boolean {
116
170
  const rel = relative(root, path);
117
171
  return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
@@ -165,11 +219,33 @@ async function validateFile(file: AssignmentFile, root: string, seen: Set<string
165
219
  }
166
220
  }
167
221
 
222
+ /** Pack paths resolve exactly like assigned reference paths: inside project scope, an existing file, no aliases. */
223
+ async function validatePackFile(file: ContextPackFile, root: string, seen: Set<string>, index: number): Promise<void> {
224
+ const label = `contextPack.files[${index}].path`;
225
+ const path = resolve(root, file.path);
226
+ requireValue(inside(root, path), `${label} ${file.path} is outside project scope ${root}`);
227
+ try {
228
+ const target = await resolvedPath(path, false);
229
+ requireValue(inside(root, target), `${label} ${file.path} resolves outside project scope ${root}`);
230
+ const entry = await stat(target);
231
+ requireValue(entry.isFile(), `${label} ${file.path} must identify a file, not a directory`);
232
+ requireValue(!seen.has(target), `${label} ${file.path} duplicates another pack path`);
233
+ seen.add(target);
234
+ } catch (error) {
235
+ if (error instanceof AssignmentValidationError) throw error;
236
+ throw new AssignmentValidationError(`${label} ${file.path}: ${error instanceof Error ? error.message : String(error)}; correct the path or refresh the pack`);
237
+ }
238
+ }
239
+
168
240
  /** Validate before dispatch; failure must never fall back to an unrestricted run. */
169
241
  export async function validateAssignment(input: unknown, projectRoot: string): Promise<WorkerAssignment> {
170
242
  const assignment = validateShape(input);
171
243
  const root = await realpath(projectRoot);
172
244
  const seen = new Set<string>();
173
245
  for (const file of assignment.files) await validateFile(file, root, seen);
246
+ if (assignment.contextPack) {
247
+ const packSeen = new Set<string>();
248
+ for (const [index, file] of assignment.contextPack.files.entries()) await validatePackFile(file, root, packSeen, index);
249
+ }
174
250
  return { ...assignment, discoveryLimit: assignment.discoveryLimit ?? 2 };
175
251
  }
@@ -1,4 +1,4 @@
1
- import { appendMetrics, metricFromRun } from "../state/metrics.ts";
1
+ import { appendMetrics, avoidedLaunchRecord, metricFromRun } from "../state/metrics.ts";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { mkdirSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
@@ -7,6 +7,7 @@ import type { AgentRun } from "../schemas/findings.ts";
7
7
  import type { Domain, Role } from "../schemas/agent.ts";
8
8
  import { effortFor } from "../classifier/instance.ts";
9
9
  import { fellShort, profileLabel, routeLabel } from "../classifier/effort.ts";
10
+ import { singleWorker } from "../workflow/track.ts";
10
11
  import { agentProfile } from "../schemas/configuration.ts";
11
12
  import { dataRoot, detectProjectRoot, loadConfig } from "../state/project.ts";
12
13
  import { EditLog } from "../state/changes.ts";
@@ -27,6 +28,25 @@ export const DURABLE_OUTPUT_TOOL = "read_durable_output_artifacts";
27
28
  export const AGENT_ENV = "BOT_LOBBY_AGENT_POLICY";
28
29
  export const DELEGATION_ENV = "BOT_LOBBY_DELEGATION";
29
30
 
31
+ /** The stages of a delegate launch, in launch order. */
32
+ export type LaunchStage = "briefs-validation" | "desk-open" | "delegation-server" | "child-identity" | "child-spawn" | "child-run";
33
+
34
+ /** Every delegate launch failure's exact shape: which stage failed, whether a worker started, and why. */
35
+ export function launchStageError(stage: LaunchStage, cause: unknown, childRunId?: string): Error {
36
+ const started = childRunId ? `worker ${childRunId} started` : "no worker started";
37
+ const message = cause instanceof Error ? cause.message : String(cause);
38
+ return new Error(`delegate failed at stage "${stage}" (${started}): ${message}`);
39
+ }
40
+
41
+ /** Run one launch stage, naming it in the error when it fails. */
42
+ async function launchStage<T>(stage: LaunchStage, work: () => Promise<T>, childRunId?: string): Promise<T> {
43
+ try {
44
+ return await work();
45
+ } catch (cause) {
46
+ throw launchStageError(stage, cause, childRunId);
47
+ }
48
+ }
49
+
30
50
  /** Only DESIGN/DEV workers and the QA gate may spawn children. */
31
51
  export function canDelegate(agent: { role: Role; domain: Domain; depth?: number }, quotaUsed: number): boolean {
32
52
  if ((agent.depth ?? 1) !== 1 || quotaUsed >= MAX_CHILDREN) return false;
@@ -228,11 +248,11 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
228
248
 
229
249
  const address = options.env?.[DESK_ENV.address];
230
250
  let desk = address ? deskSessionAt(address) : undefined;
231
- if (address && !desk) throw new Error("The inherited file desk is unavailable.");
251
+ if (address && !desk) throw launchStageError("desk-open", new Error("The inherited file desk is unavailable."));
232
252
  const board = options.env?.[BOARD_ENV];
233
253
  // A worker without a batch desk still needs claims among its children.
234
254
  const ownedDesk = editable && !desk ? new DeskSession({ cwd: options.cwd, ...(board ? { boardPath: board } : {}) }) : undefined;
235
- if (ownedDesk) await ownedDesk.open();
255
+ if (ownedDesk) await launchStage("desk-open", () => ownedDesk.open());
236
256
  // Children claim files among themselves; the parent keeps the batch desk when it has one.
237
257
  const childDesk = ownedDesk ?? desk;
238
258
  desk ??= ownedDesk;
@@ -263,7 +283,12 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
263
283
  // The child's board and desk identity carries its parent's role, so a post addressed to the role reaches every worker of it while the child keeps its own cursors.
264
284
  const childWorker = `${agent.domain}:${childId}`;
265
285
  // Each child runs under its own assignment identity, issued within the parent's live scope.
266
- const childAccess = options.runtimeAccess?.issueChild({ taskId: agent.taskId, ownerSessionId: options.runtimeAccess.ownerSessionId, runId: id, worktree: options.cwd }, { runId: childId, domain: agent.domain, role: agent.role, worktree: options.cwd });
286
+ let childAccess: RuntimeAccess | undefined;
287
+ try {
288
+ childAccess = options.runtimeAccess?.issueChild({ taskId: agent.taskId, ownerSessionId: options.runtimeAccess.ownerSessionId, runId: id, worktree: options.cwd }, { runId: childId, domain: agent.domain, role: agent.role, worktree: options.cwd });
289
+ } catch (cause) {
290
+ throw launchStageError("child-identity", cause, childId);
291
+ }
267
292
  const base: AgentRun = { runId: childId, parentRunId: id, depth: 2, taskId: agent.taskId, domain: agent.domain, role: agent.role, instruction: brief, stepInstruction: options.task, status: "running", output: "", attempts: 1, startedAt: new Date().toISOString(), ...(options.thinking ? { thinking: options.thinking } : {}) };
268
293
  const edits = new EditLog(options.cwd);
269
294
  const live = createLiveRun(base, { onUpdate: update }, edits);
@@ -273,26 +298,36 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
273
298
  const effort = options.effort ?? effortFor();
274
299
  const route = await effort.childRoute?.(brief, configured, { context: options.task, signal }).catch(() => undefined);
275
300
  const attempt = async (model: string | undefined, thinking: string) => {
301
+ let started = false;
276
302
  signal.throwIfAborted();
277
303
  const routed = route && model === route.model && thinking === route.thinking;
278
304
  live.annotate({ model, thinking, route: routed ? routeLabel(route) : undefined, routedFrom: routed ? profileLabel(route.from) : undefined, note: routed ? routeLabel(route) : undefined, noteKind: "info" });
279
- return runPiAgent({
280
- ...options,
281
- agent: { ...agent, runId: childId, depth: 2 },
282
- task: brief,
283
- model,
284
- thinking,
285
- tools: [...new Set([...tools.filter((tool) => tool !== DELEGATE_TOOL && (tool !== DURABLE_OUTPUT_TOOL || !!childAccess)), ...(childDesk ? childDesk.tools() : [])])],
286
- mcpTools,
287
- ...(childAccess ? { runtimeAccess: childAccess } : {}),
288
- signal,
289
- delegationQuota: undefined,
290
- onChildRun: undefined,
291
- onEvent: live.onEvent,
292
- // A child keeps the board but under its own identity, so its reads, pushes and acknowledgements never collide with its parent's or a same-role sibling's.
293
- env: { ...options.env, ...(board ? { BOT_LOBBY_BOARD_FROM: childWorker } : {}), ...(childDesk ? childDesk.env(childWorker) : {}) },
294
- onStart: (handle) => childDesk?.attach(childWorker, { runId: childId, steer: handle.steer, annotate: live.annotate }),
295
- }, run);
305
+ try {
306
+ return await runPiAgent({
307
+ ...options,
308
+ agent: { ...agent, runId: childId, depth: 2 },
309
+ task: brief,
310
+ model,
311
+ thinking,
312
+ tools: [...new Set([...tools.filter((tool) => tool !== DELEGATE_TOOL && (tool !== DURABLE_OUTPUT_TOOL || !!childAccess)), ...(childDesk ? childDesk.tools() : [])])],
313
+ mcpTools,
314
+ ...(childAccess ? { runtimeAccess: childAccess } : {}),
315
+ signal,
316
+ delegationQuota: undefined,
317
+ onChildRun: undefined,
318
+ onEvent: live.onEvent,
319
+ // A child keeps the board but under its own identity, so its reads, pushes and acknowledgements never collide with its parent's or a same-role sibling's.
320
+ env: { ...options.env, ...(board ? { BOT_LOBBY_BOARD_FROM: childWorker } : {}), ...(childDesk ? childDesk.env(childWorker) : {}) },
321
+ onStart: (handle) => {
322
+ started = true;
323
+ childDesk?.attach(childWorker, { runId: childId, steer: handle.steer, annotate: live.annotate });
324
+ },
325
+ }, run);
326
+ } catch (cause) {
327
+ // A cancellation is not a launch failure: it settles as a cancelled run.
328
+ if (signal.aborted) throw cause;
329
+ throw launchStageError("child-spawn", cause, started ? childId : undefined);
330
+ }
296
331
  };
297
332
  let result = await attempt(route?.model ?? configured.model, route?.thinking ?? configured.thinking);
298
333
  let retried = false;
@@ -300,15 +335,20 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
300
335
  retried = true;
301
336
  result = await attempt(configured.model, configured.thinking);
302
337
  }
303
- const final: AgentRun = { ...live.current(), ...result, thinking: retried ? configured.thinking : route?.thinking ?? configured.thinking, attempts: retried ? 2 : 1, ...(route && !retried ? { route: routeLabel(route), routedFrom: profileLabel(route.from) } : {}), edited: edits.list(), finishedAt: new Date().toISOString(), note: undefined, noteKind: undefined };
338
+ // A run that started and then failed names its stage: the launcher tells failed-start from failed-work.
339
+ const failed = result.error ? { error: launchStageError("child-run", new Error(result.error), childId).message } : {};
340
+ const final: AgentRun = { ...live.current(), ...result, thinking: retried ? configured.thinking : route?.thinking ?? configured.thinking, attempts: retried ? 2 : 1, ...(route && !retried ? { route: routeLabel(route), routedFrom: profileLabel(route.from) } : {}), ...failed, edited: edits.list(), finishedAt: new Date().toISOString(), note: undefined, noteKind: undefined };
304
341
  update(final);
305
342
  return final;
306
343
  } catch (error) {
307
- const final: AgentRun = { ...live.current(), edited: edits.list(), status: signal.aborted ? "cancelled" : "failed", error: (error as Error).message, finishedAt: new Date().toISOString(), note: undefined, noteKind: undefined };
344
+ const cause = error instanceof Error ? error.message : String(error);
345
+ // A failure after the child's identity exists names its launch stage; a cancellation is not a launch failure.
346
+ const failure = signal.aborted || cause.startsWith('delegate failed at stage "') ? cause : launchStageError("child-run", error, childId).message;
347
+ const final: AgentRun = { ...live.current(), edited: edits.list(), status: signal.aborted ? "cancelled" : "failed", error: failure, finishedAt: new Date().toISOString(), note: undefined, noteKind: undefined };
308
348
  update(final);
309
349
  return final;
310
350
  } finally {
311
- childDesk?.release(childId, () => "Child finished; re-read the file and check its report before continuing.");
351
+ childDesk?.release(childWorker, () => "Child finished; re-read the file and check its report before continuing.");
312
352
  }
313
353
  };
314
354
 
@@ -320,7 +360,20 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
320
360
  if (request.op !== "delegate") return { ok: false, text: "Unknown delegation operation." };
321
361
  const signal = childSignal();
322
362
  signal.throwIfAborted();
323
- const briefs = reserveChildren(quota, request.briefs);
363
+ // The single-worker fast path is one implementation worker end to end: its worker cannot hand work down. A pure read, before any side effect.
364
+ const projectRoot = detectProjectRoot(options.cwd, CONFIG_DIR_NAME);
365
+ const registry = loadTask(projectRoot, CONFIG_DIR_NAME, agent.taskId);
366
+ if (registry && singleWorker(registry)) {
367
+ appendMetrics(projectRoot, CONFIG_DIR_NAME, [avoidedLaunchRecord(registry.id, "nested delegation: single-worker fast path")]);
368
+ return { ok: false, text: `Task ${registry.id} is on the single-worker fast path: one implementation worker carries it end to end, and sub-delegation would bypass that. Do the work yourself; if it genuinely needs more workers, ask the orchestrator to promote the task (action=track track=full, with the reason).` };
369
+ }
370
+ // Briefs validate before any side effect: no claim release, no pool use, no child spawn.
371
+ let briefs: string[];
372
+ try {
373
+ briefs = reserveChildren(quota, request.briefs);
374
+ } catch (cause) {
375
+ throw launchStageError("briefs-validation", cause);
376
+ }
324
377
  // A coordinating parent must release claims before waiting for children that may need them.
325
378
  for (const held of new Set([desk, childDesk])) held?.releaseFiles(parentDeskId, () => "Delegating this work; re-read before editing.");
326
379
  const runs = briefs.map((brief) => {
@@ -331,11 +384,11 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
331
384
  });
332
385
  const results = await Promise.all(runs);
333
386
  return { ok: true, text: JSON.stringify(results.map((child) => ({ runId: child.runId, status: child.status, report: child.output.slice(0, 12_000), reportPath: join(dataRoot(detectProjectRoot(options.cwd, CONFIG_DIR_NAME), CONFIG_DIR_NAME), "delegations", `${child.runId}.json`), error: child.error, usage: child.usage }))) };
334
- }, () => controller.abort()).catch(async (error) => {
387
+ }, () => controller.abort()).catch(async (cause) => {
335
388
  if (ownedDesk) await ownedDesk.close();
336
389
  pool.users -= 1;
337
390
  if (pool.users === 0) pools.delete(key);
338
- throw error;
391
+ throw launchStageError("delegation-server", cause);
339
392
  });
340
393
 
341
394
  let closed = false;