@a-t-h-i/bot-lobby 0.6.80 → 0.7.1

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-v19_sKLO.js → CodeSurface-Bdkhh84z.js} +1 -1
  53. package/webui/dist/assets/{TerminalView-BW7Ik8CM.js → TerminalView-CsDNheS9.js} +1 -1
  54. package/webui/dist/assets/index-Bt0RLI3l.css +2 -0
  55. package/webui/dist/assets/{index-QvpDedq6.js → index-C3Bn07Vr.js} +45 -45
  56. package/webui/dist/build.json +58 -58
  57. package/webui/dist/index.html +2 -2
  58. package/webui/dist/assets/index-BKF36jpt.css +0 -2
@@ -35,7 +35,8 @@ import { stripStartFlags } from "../pi/start-flags.ts";
35
35
  import { checkThinking, modelRef, resolveChatProfile, resolveLobbyProfile, resolvePanelProfile, supportedThinking } from "../pi/model-support.ts";
36
36
  import { modelLookup } from "../pi/tools.ts";
37
37
  import { startPlannedTask, startTask } from "../pi/start-task.ts";
38
- import { deliverComments, setAuto } from "../pi/owner.ts";
38
+ import { deliverComments, pauseOwner, setAuto } from "../pi/owner.ts";
39
+ import { switchLanded, switchPending } from "../pi/switch-pending.ts";
39
40
  import { CHAT_MARK, chatFromEntries, chatMarkContent, CLEARED_NOTE, lobbyFeed, type ChatEntry, type ChatMarkDetails } from "./feed.ts";
40
41
  import { CHAT_AGENT_SOURCES, parseLobbyCommand, parseMention, type LobbyCommand } from "./prompts.ts";
41
42
  import type { ChatJob, ChatWorker } from "./chat-agents.ts";
@@ -123,11 +124,11 @@ function addComment(state: Runtime, taskId: string, text: string): string {
123
124
  function deliverComment(task: Task, sessionId: string): string {
124
125
  const taskId = task.id;
125
126
  if (task.ownerSessionId === sessionId) {
126
- if (deliverComments() === 0) return `comment saved — it reaches the oracle once ${taskId} is resumed or restored`;
127
- return `comment sent to the oracle — it will ${task.plan ? "amend the plan" : "revise the proposal"}`;
127
+ if (deliverComments() === 0) return `comment saved — it reaches the orchestrator once ${taskId} is resumed or restored`;
128
+ return `comment sent to the orchestrator — it will ${task.plan ? "amend the plan" : "revise the proposal"}`;
128
129
  }
129
130
  if (!task.ownerSessionId) return `comment saved — ${taskId} has no owning session; it is delivered once a session claims it`;
130
- return `comment saved — the session driving ${taskId} passes it to its oracle`;
131
+ return `comment saved — the session driving ${taskId} passes it to its orchestrator`;
131
132
  }
132
133
 
133
134
  /**
@@ -214,7 +215,7 @@ async function routeChat(state: Runtime, text: string): Promise<void> {
214
215
  return;
215
216
  }
216
217
  if (picked.route === "knowledge") {
217
- lobbyFeed.log("LOBBY", `a knowledge question (${picked.probability.toFixed(2)}): the oracle reads the project's knowledge`, "info");
218
+ lobbyFeed.log("LOBBY", `a knowledge question (${picked.probability.toFixed(2)}): the orchestrator reads the project's knowledge`, "info");
218
219
  state.pi.sendUserMessage(knowledgeQuestion(text, readDataRoots(state.root, state.configDir)), state.ctx.isIdle() ? undefined : { deliverAs: "followUp" });
219
220
  return;
220
221
  }
@@ -279,7 +280,7 @@ function lobbyCommand(state: Runtime, command: LobbyCommand, rest: string): Lobb
279
280
  startTask(state.pi, state.ctx, state.configDir, request)
280
281
  .then(() => lobbyTopics.bump("tasks"))
281
282
  .catch((error: Error) => failed(state, "could not start the task", error));
282
- return "starting a task — the oracle takes it from here";
283
+ return "starting a task — the orchestrator takes it from here";
283
284
  }
284
285
  if (state.planner?.busy) return "the panel is still thinking — wait for the round to finish";
285
286
  // A plan under way stays among the project's previous plans; this one starts afresh.
@@ -582,7 +583,7 @@ async function resumeTask(state: Runtime, taskId: string): Promise<{ notice: str
582
583
  try {
583
584
  sendToInbox(state.root, state.configDir, taskId, message, state.ctx.sessionManager.getSessionId());
584
585
  } catch (error) {
585
- return { notice: `unpaused ${taskId}, but could not tell its oracle — ${(error as Error).message}` };
586
+ return { notice: `unpaused ${taskId}, but could not tell its orchestrator — ${(error as Error).message}` };
586
587
  }
587
588
  lobbyFeed.log("LOBBY", `resumed ${taskId} in another terminal`, "success");
588
589
  return { notice: `resumed ${taskId} — the session driving it in another terminal carries on` };
@@ -624,7 +625,7 @@ function mutableTask(state: Runtime, taskId: string): Task {
624
625
 
625
626
  async function wakeTask(state: Runtime, task: Task, message: string): Promise<string> {
626
627
  if (!tellOracle(state, task, message)) return (await resumeTask(state, task.id)).notice;
627
- return "the owning oracle has been notified";
628
+ return "the owning orchestrator has been notified";
628
629
  }
629
630
 
630
631
  /**
@@ -673,7 +674,7 @@ async function acceptTask(state: Runtime, taskId: string): Promise<{ notice: str
673
674
  const asks = lastQaAsks(task);
674
675
  if (task.qaVerdict !== "pass" && !task.qaWaiver) waiveQa(task, asks, "from the Tasks screen");
675
676
  if (task.lint?.state === "failing") waiveLint(task, "from the Tasks screen");
676
- recordDecision(task, "The user accepted the work as it is from the Tasks screen; the oracle was asked to complete it.");
677
+ recordDecision(task, "The user accepted the work as it is from the Tasks screen; the orchestrator was asked to complete it.");
677
678
  saveTask(state.root, state.configDir, task);
678
679
  lobbyTopics.bump("tasks");
679
680
  const wake = await wakeTask(state, task, `The user accepted ${task.id}'s work as it is. Call orchestrate action=complete now with a short summary naming outstanding QA/lint asks: ${asks.join("; ") || "none recorded"}. Read the persisted gate waivers first. Do not merge automatically.`);
@@ -703,8 +704,8 @@ async function skipTaskStep(state: Runtime, taskId: string, step: number, text:
703
704
  lobbyTopics.bump("tasks");
704
705
  lobbyTopics.bump("lobby");
705
706
  const message = `The user skipped step ${step + 1} of ${task.id}'s plan: "${text}". Their reason: ${why}. Do not delegate, build or review that step; if an agent is on it now, let it stop there or tell it to. Carry on with the next open step.`;
706
- if (!tellOracle(state, task, message)) return { notice: `step ${step + 1} skipped; the oracle reads why when the task carries on` };
707
- return { notice: `step ${step + 1} skipped; the oracle has been told` };
707
+ if (!tellOracle(state, task, message)) return { notice: `step ${step + 1} skipped; the orchestrator reads why when the task carries on` };
708
+ return { notice: `step ${step + 1} skipped; the orchestrator has been told` };
708
709
  }
709
710
 
710
711
  async function resolveTaskApproval(state: Runtime, taskId: string, approvalId: string, decision: "approved" | "rejected", note?: string): Promise<{ notice: string }> {
@@ -728,8 +729,8 @@ function sendToTask(state: Runtime, taskId: string, text: string): string {
728
729
  } catch (error) {
729
730
  return (error as Error).message;
730
731
  }
731
- lobbyFeed.log("LOBBY", `message for ${taskId}'s oracle saved`, "info");
732
- return task.ownerSessionId ? `sent — the session driving ${taskId} passes it to its oracle` : `saved — ${taskId} has no owning session; its oracle gets it once a session claims it`;
732
+ lobbyFeed.log("LOBBY", `message for ${taskId}'s orchestrator saved`, "info");
733
+ return task.ownerSessionId ? `sent — the session driving ${taskId} passes it to its orchestrator` : `saved — ${taskId} has no owning session; its orchestrator gets it once a session claims it`;
733
734
  }
734
735
 
735
736
  /** Auto mode as the lobby last read it, per task: every frame asks, the file is read at most once a second. */
@@ -786,8 +787,8 @@ function sendToSession(state: Runtime, sessionId: string, text: string): string
786
787
  } catch (error) {
787
788
  return (error as Error).message;
788
789
  }
789
- lobbyFeed.log("LOBBY", "message for another session's oracle saved", "info");
790
- return "sent — that session passes it to its oracle within a few seconds";
790
+ lobbyFeed.log("LOBBY", "message for another session's orchestrator saved", "info");
791
+ return "sent — that session passes it to its orchestrator within a few seconds";
791
792
  }
792
793
 
793
794
  /**
@@ -795,66 +796,102 @@ function sendToSession(state: Runtime, sessionId: string, text: string): string
795
796
  * runs with a command context (the only one that may replace the session).
796
797
  * A background session is stopped first, so one process writes its file; a
797
798
  * task no session owns is claimed instead.
799
+ *
800
+ * Nothing here waits for this window to go quiet: a turn at work, or a task
801
+ * this session drives, is handed to the background (see `handOffFor`), and
802
+ * pi's switch itself stops the turn and saves it before it opens the next
803
+ * session. The reply comes back at once; the stop and the switch run after it,
804
+ * the window's turn and a background target winding down side by side.
798
805
  */
799
806
  async function switchTo(state: Runtime, target: SwitchTarget): Promise<string> {
800
807
  if (target.claimTaskId) {
801
- if (!state.ctx.isIdle()) return "this window's oracle is working — stop it, then take the task over here";
808
+ if (!state.ctx.isIdle()) return "this window's orchestrator is working — stop it, then take the task over here";
802
809
  state.pi.sendUserMessage(`/bot-lobby claim ${target.claimTaskId}`, { expandPromptTemplates: true });
803
810
  return `taking ${target.claimTaskId} over in this window`;
804
811
  }
805
- // A window at work hands its session to the background (it carries on there) and then switches.
806
- const leaving = state.ctx.isIdle() ? undefined : await stepAside(state);
812
+ if (switching) return "a switch is already under way — wait a moment";
813
+ const leaving = handOffFor(state);
807
814
  if (typeof leaving === "string") return leaving;
808
- let file = target.background?.sessionFile;
809
- if (target.background) {
810
- target.background.stop();
811
- await target.background.whenExited();
812
- }
813
- file ??= target.sessionId ? await chats.locate(target.sessionId) : undefined;
814
- if (!file) {
815
- if (leaving) handOff = undefined;
816
- return `could not find ${target.name}'s session file — /resume lists every saved session`;
817
- }
818
- state.pi.sendUserMessage(`/bot-lobby switch ${file}`, { expandPromptTemplates: true });
815
+ switching = true;
816
+ const resumeOwner = pauseOwner();
817
+ // Start winding this window's turn down now, alongside the background target; pi's switch waits for it to settle.
818
+ if (!state.ctx.isIdle()) state.ctx.abort();
819
+ void runSwitch(state, target, resumeOwner).finally(() => {
820
+ switching = false;
821
+ });
819
822
  return leaving ? `${leaving.name} carries on in the background; switching this window to ${target.name}…` : `switching this window to ${target.name}…`;
820
823
  }
821
824
 
822
- /** The session this window was working in when it switched away, started in the background once the switch lands. */
823
- let handOff: { file: string; name: string; message: string } | undefined;
825
+ /** A switch is under way (between the reply and pi opening the next session). */
826
+ let switching = false;
827
+
828
+ async function runSwitch(state: Runtime, target: SwitchTarget, resumeOwner: () => void): Promise<void> {
829
+ const failed = (why: string) => {
830
+ handOff = undefined;
831
+ resumeOwner();
832
+ lobbyFeed.log("LOBBY", why, "warning");
833
+ lobbyNotify(state, why, "warning");
834
+ };
835
+ try {
836
+ let file = target.background?.sessionFile;
837
+ if (target.background) {
838
+ // Stop its turn first so the process ends quickly instead of running out its grace period.
839
+ target.background.abort();
840
+ target.background.stop();
841
+ await target.background.whenExited();
842
+ }
843
+ file ??= target.sessionId ? await chats.locate(target.sessionId) : undefined;
844
+ if (!file) return failed(`could not find ${target.name}'s session file — /resume lists every saved session`);
845
+ // `/bot-lobby switch` undoes the hold and the hand-off itself should pi not switch after all.
846
+ switchPending(() => {
847
+ handOff = undefined;
848
+ resumeOwner();
849
+ });
850
+ state.pi.sendUserMessage(`/bot-lobby switch ${file}`, { expandPromptTemplates: true });
851
+ } catch (error) {
852
+ failed(`could not switch to ${target.name} — ${(error as Error).message}`);
853
+ }
854
+ }
824
855
 
825
- /** How long a stopped turn gets to wind down before the switch gives up. */
826
- const STEP_ASIDE_MS = 10_000;
856
+ /** The session this window was working in when it switched away, started in the background once the switch lands. */
857
+ let handOff: { file: string; name: string; message?: string; taskId?: string } | undefined;
827
858
 
828
- /** Stop this window's turn and keep its session to carry on in the background; the hand-off, or why not. */
829
- async function stepAside(state: Runtime): Promise<{ name: string } | string> {
830
- const file = state.ctx.sessionManager.getSessionFile?.();
831
- if (!file) return "this window's session is not saved yet — stop the oracle, then switch";
832
- const name = state.pi.getSessionName() ?? "this window's session";
859
+ /**
860
+ * Whether this window's session carries on in the background after the
861
+ * switch: when its orchestrator is at work (its cut-off turn is picked back up) or
862
+ * it drives a task that is not finished (auto mode, messages and questions
863
+ * keep reaching it there). Returns the hand-off, nothing to hand off, or why
864
+ * the switch cannot happen.
865
+ */
866
+ function handOffFor(state: Runtime): { name: string } | string | undefined {
867
+ const working = !state.ctx.isIdle();
833
868
  const task = ownedTask(state.root, state.configDir, state.ctx.sessionManager.getSessionId());
834
- state.ctx.abort();
835
- const deadline = Date.now() + STEP_ASIDE_MS;
836
- while (!state.ctx.isIdle()) {
837
- if (Date.now() > deadline) return "the oracle did not stop in time — try the switch again";
838
- await new Promise((resolve) => setTimeout(resolve, 50));
839
- }
840
- const message = task && !TERMINAL_STATES.includes(task.state) && !task.paused
841
- ? `bot-lobby: you were moved to the background while you worked on ${task.id}; your last turn was cut off. Read where the task stands with the orchestrate tool (action=status), run again any step that was cut off, and carry on.`
842
- : "bot-lobby: you were moved to the background while you worked, and your last turn was cut off. Carry on where you left off.";
843
- handOff = { file, name, message };
869
+ const driving = Boolean(task && !TERMINAL_STATES.includes(task.state));
870
+ if (!working && !driving) return undefined;
871
+ const file = state.ctx.sessionManager.getSessionFile?.();
872
+ if (!file) return working ? "this window's session is not saved yet — stop the orchestrator, then switch" : undefined;
873
+ const name = state.pi.getSessionName() ?? (task ? task.title : "this window's session");
874
+ const message = !working
875
+ ? undefined
876
+ : task && driving && !task.paused
877
+ ? `bot-lobby: you were moved to the background while you worked on ${task.id}; your last turn was cut off. Read where the task stands with the orchestrate tool (action=status), run again any step that was cut off, and carry on.`
878
+ : "bot-lobby: you were moved to the background while you worked, and your last turn was cut off. Carry on where you left off.";
879
+ handOff = { file, name, ...(message ? { message } : {}), ...(task && driving ? { taskId: task.id } : {}) };
844
880
  return { name };
845
881
  }
846
882
 
847
- /** Once this window runs its new session, carry the one it left on in the background (see `stepAside`). */
883
+ /** Once this window runs its new session, carry the one it left on in the background (see `handOffFor`). */
848
884
  export function carryHandOff(state: Runtime): void {
885
+ switchLanded();
849
886
  const pending = handOff;
850
887
  handOff = undefined;
851
888
  if (!pending) return;
852
889
  if (state.ctx.sessionManager.getSessionFile?.() === pending.file) {
853
- lobbyFeed.log("LOBBY", "the switch did not happen; the oracle was stopped — send a message to carry on", "warning");
890
+ lobbyFeed.log("LOBBY", "the switch did not happen; the orchestrator was stopped — send a message to carry on", "warning");
854
891
  return;
855
892
  }
856
893
  try {
857
- sessionRegistry().start(state.ctx.cwd, { name: pending.name, projectRoot: state.root, onDialog: dialogTracker(state), ask: askForSession, sessionFile: pending.file, message: pending.message });
894
+ sessionRegistry().start(state.ctx.cwd, { name: pending.name, projectRoot: state.root, onDialog: dialogTracker(state), ask: askForSession, sessionFile: pending.file, ...(pending.message ? { message: pending.message } : {}), ...(pending.taskId ? { taskId: pending.taskId } : {}) });
858
895
  lobbyFeed.log("LOBBY", `${pending.name} carries on in the background`, "success");
859
896
  } catch (error) {
860
897
  lobbyFeed.log("LOBBY", `could not carry ${pending.name} on in the background — ${(error as Error).message}; /resume finds it`, "warning");
@@ -1,6 +1,8 @@
1
1
  import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
2
4
  import { designRecordBlock, designStanding, withoutDesignRecord } from "../knowledge/design-record.ts";
3
- import { validateAssignment, type WorkerAssignment } from "../execution/assignment.ts";
5
+ import { validateAssignment, type ContextPack, type ContextPackFile, CONTEXT_SNIPPET_MAX_CHARS, type WorkerAssignment } from "../execution/assignment.ts";
4
6
  import { join, resolve } from "node:path";
5
7
  import { profileFor, type BotLobbyConfig, type ProfileResolver } from "../schemas/configuration.ts";
6
8
  import type { Domain } from "../schemas/agent.ts";
@@ -15,10 +17,10 @@ import { appendPost, assignmentId } from "../desk/board.ts";
15
17
  import { refreshCatalogue } from "../knowledge/catalogue.ts";
16
18
  import { notesFor } from "../knowledge/retrieval.ts";
17
19
  import { assignmentKey, applySelection, bookmarkBlock, BOOKMARK_DEADLINE_MS, BOOKMARKS_VERSION, deliverBookmarks, fitHints, lexicalBookmarks, type BookmarkState, type Selection } from "../knowledge/bookmarks.ts";
18
- import { KNOWLEDGE_BUDGET_CHARS, type BookmarkPick, type BookmarkSelectorInput, type KnowledgePaths, type KnowledgePicker } from "../classifier/knowledge.ts";
20
+ import { KNOWLEDGE_BUDGET_CHARS, applyStartupBudget, STARTUP_KNOWLEDGE_BUDGET_CHARS, type BookmarkPick, type BookmarkSelectorInput, type KnowledgePaths, type KnowledgePicker } from "../classifier/knowledge.ts";
19
21
  import { scriptsFor } from "../scripts/pick.ts";
20
22
  import { summarizeOutcomes } from "./synthesis.ts";
21
- import { parseWorkerResult, validateWorkerResult } from "../roles/worker.ts";
23
+ import { parseWorkerResult, validateWorkerResult, contextPackBlock } from "../roles/worker.ts";
22
24
  import { parseReviewResult, readVerdict, validateReviewResult } from "../roles/reviewer.ts";
23
25
  import { truncate } from "../text.ts";
24
26
  import { isScoutResultUsable, parseScoutResult, validateScoutResult } from "../roles/scout.ts";
@@ -32,6 +34,7 @@ import { BOARD_ENV, BOARD_TOOLS, boardContext } from "../desk/board.ts";
32
34
  import { seedDelivery } from "../desk/delivery.ts";
33
35
  import type { FileHinter } from "../classifier/files.ts";
34
36
  import { fellShort, profileLabel, routeLabel, type EffortRoute, type EffortRouter } from "../classifier/effort.ts";
37
+ import { noteRunContextChars } from "../state/metrics.ts";
35
38
 
36
39
  export interface ScoutOutcome {
37
40
  result: ScoutResult;
@@ -97,6 +100,25 @@ function knowledgePaths(dataRoots: readonly string[], agent: Domain): KnowledgeP
97
100
  return root ? { knowledge: knowledgeFilePath(root, agent, "knowledge"), standards: knowledgeFilePath(root, agent, "standard"), decisions: knowledgeFilePath(root, agent, "decision") } : {};
98
101
  }
99
102
 
103
+ /** What one subagent prompt carries of its knowledge after the combined startup budget: sections, bookmarks and visible diagnostics. */
104
+ function budgetKnowledge(request: { config?: BotLobbyConfig; dataRoots: readonly string[] }, agent: Domain, selected: KnowledgeSelection, bookmarks: string): { selected: KnowledgeSelection; bookmarks: string; notes: string[] } {
105
+ const paths = knowledgePaths(request.dataRoots, agent);
106
+ const budgeted = applyStartupBudget([
107
+ { name: "standards", content: selected.standards ?? "", path: paths.standards },
108
+ { name: "knowledge", content: selected.knowledge ?? "", path: paths.knowledge },
109
+ { name: "decisions", content: selected.decisions ?? "", path: paths.decisions },
110
+ { name: "bookmarks", content: bookmarks },
111
+ { name: "scripts", content: selected.scripts ?? "" },
112
+ ], request.config?.workflow.knowledgeStartupBudget ?? STARTUP_KNOWLEDGE_BUDGET_CHARS);
113
+ const by = (name: string) => budgeted.sections.find((section) => section.name === name)?.content ?? "";
114
+ const scripts = by("scripts");
115
+ return {
116
+ selected: { knowledge: by("knowledge"), standards: by("standards"), decisions: by("decisions"), ...(scripts ? { scripts } : {}) },
117
+ bookmarks: by("bookmarks"),
118
+ notes: budgeted.diagnostics,
119
+ };
120
+ }
121
+
100
122
  /**
101
123
  * What an agent's prompt carries of its knowledge for a step: Jev's picks from
102
124
  * the files that are too long when a picker is given, the keyword selection
@@ -219,12 +241,13 @@ function bookmarkState(
219
241
  }
220
242
 
221
243
  function scoutContext(request: ScoutRequest, domain: Domain, selected: KnowledgeSelection, likely = "", bookmarks = ""): AgentRequest["context"] {
244
+ const budgeted = budgetKnowledge(request, domain, selected, bookmarks);
222
245
  return {
223
246
  task: request.taskText,
224
- ...selected,
225
- ...(bookmarks ? { bookmarks } : {}),
247
+ ...budgeted.selected,
248
+ ...(budgeted.bookmarks ? { bookmarks: budgeted.bookmarks } : {}),
226
249
  instructions: request.config.agents[domain].instructions,
227
- workflowContext: [`Task state: scouting. Domain: ${domain}. Read-only reconnaissance; no implementation.`, toolBudgetNote(request.config.scout.maxToolCalls), likely].filter(Boolean).join("\n\n"),
250
+ workflowContext: [`Task state: scouting. Domain: ${domain}. Read-only reconnaissance; no implementation.`, toolBudgetNote(request.config.scout.maxToolCalls), likely, ...budgeted.notes].filter(Boolean).join("\n\n"),
228
251
  };
229
252
  }
230
253
 
@@ -475,7 +498,7 @@ function alongsideGuidance(request: WorkerRequest): string {
475
498
  /** What a worker that may ask the user is told about it. */
476
499
  function askGuidance(previews: string): string {
477
500
  return [
478
- "You can ask the user with ask_user_question: the oracle relays it, and your clock stops while they answer.",
501
+ "You can ask the user with ask_user_question: the orchestrator relays it, and your clock stops while they answer.",
479
502
  "Ask when a design decision is genuinely theirs (a visual direction, a layout, a style), once, with all such questions together, before you build it; decide everything else yourself.",
480
503
  "Show each option. Give it a `preview`: a Markdown wireframe (a fenced block drawn with box characters) or a short snippet of the component.",
481
504
  `When you can render an option (a screenshot from the project's own tooling, a rendered mockup), save it as a PNG under ${previews} (never in the repository) and give its path as the option's \`image\`.`,
@@ -549,6 +572,52 @@ export function readOnlyAssignment(assignment: WorkerAssignment): boolean {
549
572
  return assignment.files.every((file) => file.access === "reference") && !assignment.tools.some((tool) => tool.name === "edit" || tool.name === "write");
550
573
  }
551
574
 
575
+ /** A cheap content fingerprint: 16 hex characters of the file's bytes at pack time. */
576
+ export function packFingerprint(content: string): string {
577
+ return createHash("sha1").update(content).digest("hex").slice(0, 16);
578
+ }
579
+
580
+ /** A stale entry's refreshed form: new fingerprint, re-read snippet for its range, ranges clamped into the file as it is. */
581
+ function refreshedEntry(file: ContextPackFile, content: string): ContextPackFile {
582
+ const lines = content.replace(/\r?\n$/, "").split("\n");
583
+ const clamp = (value: number): number => Math.min(Math.max(1, value), Math.max(1, lines.length));
584
+ const ranges = file.ranges?.map(([start, end]): [number, number] => { const from = clamp(start); const to = clamp(end); return from <= to ? [from, to] : [to, from]; });
585
+ const [start, end] = ranges?.[0] ?? [1, Math.min(lines.length, 60)];
586
+ const snippet = file.snippet === undefined && !ranges?.length ? undefined : lines.slice(Math.max(0, start - 1), Math.max(0, end)).join("\n").slice(0, CONTEXT_SNIPPET_MAX_CHARS);
587
+ return { ...file, ...(ranges ? { ranges } : {}), fingerprint: packFingerprint(content), ...(snippet !== undefined ? { snippet } : {}) };
588
+ }
589
+
590
+ /**
591
+ * Stale-context refresh at dispatch. A fingerprint that no longer matches
592
+ * the file refreshes that entry (new fingerprint plus a re-read snippet and
593
+ * clamped range); a path that no longer exists drops its entry. The pack is
594
+ * never delivered silently stale, and the returned notes say exactly what
595
+ * changed so the worker knows which entries are newer than the rest.
596
+ */
597
+ export async function refreshContextPack(pack: ContextPack, root: string): Promise<string[]> {
598
+ const notes: string[] = [];
599
+ const files: ContextPackFile[] = [];
600
+ for (const file of pack.files) {
601
+ if (!file.fingerprint) {
602
+ files.push(file);
603
+ continue;
604
+ }
605
+ const content = await readFile(join(root, file.path), "utf8").catch(() => undefined);
606
+ if (content === undefined) {
607
+ notes.push(`dropped ${file.path} (the file no longer exists)`);
608
+ continue;
609
+ }
610
+ const fingerprint = packFingerprint(content);
611
+ if (fingerprint === file.fingerprint) files.push(file);
612
+ else {
613
+ files.push(refreshedEntry(file, content));
614
+ notes.push(`refreshed ${file.path} (content had changed; new fingerprint ${fingerprint})`);
615
+ }
616
+ }
617
+ pack.files = files;
618
+ return notes;
619
+ }
620
+
552
621
  /**
553
622
  * The worker's model, thinking and grants. A read-only assignment needs no
554
623
  * builder: it runs on the scout's model and thinking (keeping the worker's grants,
@@ -579,6 +648,7 @@ export async function runWorker(
579
648
  prepareBookmarks(request, request.domain, `${request.instruction}\n\n${request.taskText}`),
580
649
  ]);
581
650
  const hints = fitHints(bookmarked, likely);
651
+ const budgeted = budgetKnowledge(request, request.domain, selected, hints.bookmarks);
582
652
  const hintTools = request.hints?.tools() ?? [];
583
653
  const boardFrom = request.boardFrom ?? assignmentId(request.domain);
584
654
  const extraTools = [...(request.agent?.extraTools ?? []), ...hintTools, ...(request.board ? BOARD_TOOLS : [])];
@@ -594,10 +664,10 @@ export async function runWorker(
594
664
  instruction: request.instruction,
595
665
  context: {
596
666
  task: request.taskText,
597
- ...selected,
598
- ...(hints.bookmarks ? { bookmarks: hints.bookmarks } : {}),
667
+ ...budgeted.selected,
668
+ ...(budgeted.bookmarks ? { bookmarks: budgeted.bookmarks } : {}),
599
669
  instructions: request.config.agents[request.domain].instructions,
600
- workflowContext: workerWorkflowContext(request, boardFrom, hints.likely),
670
+ workflowContext: [workerWorkflowContext(request, boardFrom, hints.likely), ...budgeted.notes].filter(Boolean).join("\n\n"),
601
671
  },
602
672
  ...configured,
603
673
  cwd: request.cwd,
@@ -642,10 +712,12 @@ async function runFreshWorker(request: WorkerRequest, assignment: WorkerAssignme
642
712
  checking = state.checks.start({ assignmentId: assignment.id, revision: assignment.revision, hints }).catch((error: unknown) => { checkError = error; });
643
713
  if (assignment.completedWork.length) state.checks.completed(assignment.id, assignment.revision);
644
714
  reportFreshness(request, reader, status());
645
- const instruction = [base.instruction, freshnessHints(hints)].filter(Boolean).join("\n\n");
715
+ const refresh = assignment.contextPack ? await refreshContextPack(assignment.contextPack, request.cwd) : [];
716
+ const instruction = [base.instruction, freshnessHints(hints), refresh.length ? `Context pack refresh at dispatch: ${refresh.join("; ")}.` : ""].filter(Boolean).join("\n\n");
646
717
  // Assignment-local navigation hints belong in user content, not the shared system prefix.
647
718
  // Start actual dispatch now, before awaiting any source-file hashes.
648
719
  const outcome = await dispatchFreshWorker({ ...base, instruction }, request, assignment, route, state.checks, run);
720
+ if (assignment.contextPack) noteRunContextChars(outcome.run.runId, contextPackBlock(assignment.contextPack).length);
649
721
  state.checks.completed(assignment.id, assignment.revision);
650
722
  await checking;
651
723
  const freshness = status();
@@ -761,6 +833,7 @@ function isRetryableReviewRun(run: AgentRun): boolean {
761
833
  }
762
834
 
763
835
  function reviewerAgentRequest(request: ReviewerRequest, selected: KnowledgeSelection, bookmarks = ""): AgentRequest {
836
+ const budgeted = budgetKnowledge(request, request.domain, selected, bookmarks);
764
837
  return {
765
838
  taskId: request.taskId,
766
839
  domain: request.domain,
@@ -771,10 +844,10 @@ function reviewerAgentRequest(request: ReviewerRequest, selected: KnowledgeSelec
771
844
  "Review the current repository changes against the approved requirements and plan.",
772
845
  context: {
773
846
  task: request.taskText,
774
- ...selected,
775
- ...(bookmarks ? { bookmarks } : {}),
847
+ ...budgeted.selected,
848
+ ...(budgeted.bookmarks ? { bookmarks: budgeted.bookmarks } : {}),
776
849
  instructions: request.config.agents[request.domain].instructions,
777
- workflowContext: reviewerContext(request),
850
+ workflowContext: [reviewerContext(request), ...budgeted.notes].filter(Boolean).join("\n\n"),
778
851
  },
779
852
  ...profileFields(request.config, request.profile, request.domain, "reviewer"),
780
853
  cwd: request.cwd,
@@ -9,7 +9,9 @@
9
9
  */
10
10
  import type { Domain } from "../schemas/agent.ts";
11
11
  import type { AgentRun } from "../schemas/findings.ts";
12
- import type { TaskTriage } from "../schemas/task.ts";
12
+ import type { Task, TaskTriage } from "../schemas/task.ts";
13
+ import { appendMetrics, avoidedLaunchRecord } from "../state/metrics.ts";
14
+ import { singleWorker } from "../workflow/track.ts";
13
15
  import type { ScoutOutcome } from "./master.ts";
14
16
 
15
17
  interface Prefetch {
@@ -32,6 +34,17 @@ const prefetches = new Map<string, Prefetch>();
32
34
  const BUILD_DOMAIN_AT = 0.35;
33
35
  const QA_DOMAIN_AT = 0.5;
34
36
 
37
+ /**
38
+ * The opening scout a single-worker fast-path task never starts: its one
39
+ * worker reads what it needs itself, so the launch is refused before any
40
+ * process runs, and the avoided launch is recorded. False for every other task.
41
+ */
42
+ export function skipSingleWorkerPrefetch(task: Task, metrics: { root: string; configDir: string }): boolean {
43
+ if (!singleWorker(task)) return false;
44
+ appendMetrics(metrics.root, metrics.configDir, [avoidedLaunchRecord(task.id, "scout prefetch: single-worker fast path")]);
45
+ return true;
46
+ }
47
+
35
48
  /** The domains worth scouting before the oracle asks, from the triage; none without one. */
36
49
  export function prefetchDomains(triage: TaskTriage | undefined): Domain[] {
37
50
  if (!triage) return [];
@@ -25,6 +25,7 @@ import { classifierSummary } from "./model-settings.ts";
25
25
  import { keyStatus } from "../classifier/instance.ts";
26
26
  import { kickoff, startPlannedTask, startTask } from "./start-task.ts";
27
27
  import { setAuto, toggleOwnAuto } from "./owner.ts";
28
+ import { switchFailed } from "./switch-pending.ts";
28
29
  import { registerWebServer, webCommand } from "../webui/command.ts";
29
30
  import { modelRef, thinkingMismatches } from "./model-support.ts";
30
31
  import { describeRun, runFromLog } from "./run-summary.ts";
@@ -46,15 +47,15 @@ const HELP = [
46
47
  "/bot-lobby pause|resume Pause or resume the active task",
47
48
  "/bot-lobby cancel [taskId] Abandon a task",
48
49
  "/bot-lobby approve|amend <text>|decline Answer the current proposal",
49
- "/bot-lobby accept [taskId] Accept a task's work as it is, without a QA pass; the oracle then completes it",
50
+ "/bot-lobby accept [taskId] Accept a task's work as it is, without a QA pass; the orchestrator then completes it",
50
51
  "/bot-lobby knowledge Show persistent knowledge files",
51
52
  "/bot-lobby runs [taskId] Recent subagent runs: time, turns, tokens, cost, model",
52
53
  "/bot-lobby settings Open the web lobby's Settings: per-agent model, effort and instructions",
53
54
  "/bot-lobby config Show effective configuration",
54
55
  "/bot-lobby on|off Turn bot-lobby on or off for this session (ctrl+shift+m); a new session starts off",
55
56
  "/bot-lobby claim <taskId> Take ownership of an orphaned task",
56
- "/bot-lobby carry-on <taskId> Take over a task no running session drives, unpause it and have the oracle carry it on (the Tasks screen's Resume)",
57
- "/bot-lobby auto [on|off] Auto mode: the oracle drives this session's task without asking (alt+g)",
57
+ "/bot-lobby carry-on <taskId> Take over a task no running session drives, unpause it and have the orchestrator carry it on (the Tasks screen's Resume)",
58
+ "/bot-lobby auto [on|off] Auto mode: the orchestrator drives this session's task without asking (alt+g)",
58
59
  "/bot-lobby start-plan PLAN-… [auto] Start a planned task here; its agreed plan needs no approval",
59
60
  "/bot-lobby switch <session.jsonl> Run a saved session in this window (the web lobby's session browser uses it)",
60
61
  "/bot-lobby web [stop|link|reset] Open the browser UI (it starts with pi, on this machine only), or stop it, print its link, reset its link",
@@ -200,7 +201,7 @@ function claimTaskCommand(ctx: ExtensionCommandContext, configDir: string, taskI
200
201
  /**
201
202
  * `/bot-lobby carry-on <taskId>`: take over a task no running session drives
202
203
  * (or this session's own, when it is started again from its file), unpause it
203
- * and have the oracle carry it on. A background session resumed from the
204
+ * and have the orchestrator carry it on. A background session resumed from the
204
205
  * Tasks screen runs it as its first message.
205
206
  */
206
207
  function carryOnCommand(pi: ExtensionAPI, ctx: ExtensionCommandContext, configDir: string, taskId?: string): void {
@@ -266,7 +267,7 @@ function acceptWork(pi: ExtensionAPI, ctx: ExtensionCommandContext, configDir: s
266
267
  if (task.lint?.state === "failing") waiveLint(task, "with /bot-lobby accept");
267
268
  saveTask(root, configDir, task);
268
269
  applyStatus(ctx, root, configDir);
269
- ctx.ui.notify(`bot-lobby: ${task.id} accepted as it is; the oracle will complete it.`, "info");
270
+ ctx.ui.notify(`bot-lobby: ${task.id} accepted as it is; the orchestrator will complete it.`, "info");
270
271
  const waived = [task.qaWaiver ? "the QA gate" : "", task.lintWaiver ? "the lint gate" : ""].filter(Boolean);
271
272
  const message = `The user accepted ${task.id}'s work as it is${waived.length ? ` (${waived.join(" and ")} ${waived.length === 1 ? "is" : "are"} waived)` : ""}. Call orchestrate action=complete now with a short summary that names anything QA or lint still asked for.`;
272
273
  pi.sendUserMessage(message, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
@@ -303,13 +304,30 @@ function showConfig(ctx: ExtensionCommandContext): void {
303
304
  * `/bot-lobby switch <file>`: run a saved session in this window. Only a
304
305
  * command context may replace the session, so the lobby's browser asks for a
305
306
  * switch through this command. The context is stale once the switch starts.
307
+ * The command never touches the stale context after a switch that landed.
306
308
  */
307
309
  async function switchCommand(ctx: ExtensionCommandContext, path: string): Promise<void> {
308
- if (!existsSync(path)) return ctx.ui.notify(`bot-lobby: no session file at ${path}`, "warning");
309
- if (ctx.sessionManager.getSessionFile() === path) return ctx.ui.notify("bot-lobby: this window already runs that session", "info");
310
- if (!ctx.isIdle()) return ctx.ui.notify("bot-lobby: the oracle is working — stop it, then switch", "warning");
311
- const result = await ctx.switchSession(path);
312
- if (result.cancelled) ctx.ui.notify("bot-lobby: the switch was cancelled", "warning");
310
+ if (!existsSync(path)) {
311
+ switchFailed();
312
+ return ctx.ui.notify(`bot-lobby: no session file at ${path}`, "warning");
313
+ }
314
+ if (ctx.sessionManager.getSessionFile() === path) {
315
+ switchFailed();
316
+ return ctx.ui.notify("bot-lobby: this window already runs that session", "info");
317
+ }
318
+ // A turn at work is no reason to refuse: pi's switch stops it and saves it first, and the lobby has handed
319
+ // the session to the background (see switchTo in src/lobby/service.ts).
320
+ let result: { cancelled: boolean };
321
+ try {
322
+ result = await ctx.switchSession(path);
323
+ } catch (error) {
324
+ switchFailed();
325
+ throw error;
326
+ }
327
+ if (result.cancelled) {
328
+ switchFailed();
329
+ ctx.ui.notify("bot-lobby: the switch was cancelled", "warning");
330
+ }
313
331
  }
314
332
 
315
333
  /** `/bot-lobby auto [on|off]`: switch (or set) auto mode for this session's task. */
package/src/pi/events.ts CHANGED
@@ -2,12 +2,12 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { activeTask } from "../state/persistence.ts";
3
3
  import { detectProjectRoot, loadConfig, readDataRoots } from "../state/project.ts";
4
4
  import { compilePrompt } from "../prompts/compiler.ts";
5
- import { readAgentKnowledge } from "../knowledge/store.ts";
5
+ import { knowledgeFilePath, readAgentKnowledge } from "../knowledge/store.ts";
6
6
  import { selectKnowledge, selectRelevant } from "../knowledge/selector.ts";
7
7
  import { applySelection, assignmentKey, bookmarkBlock, lexicalBookmarks } from "../knowledge/bookmarks.ts";
8
8
  import { refreshCatalogue } from "../knowledge/catalogue.ts";
9
9
  import { readNotes } from "../knowledge/notes.ts";
10
- import { KNOWLEDGE_BUDGET_CHARS } from "../classifier/knowledge.ts";
10
+ import { applyStartupBudget, KNOWLEDGE_BUDGET_CHARS } from "../classifier/knowledge.ts";
11
11
  import { libraryBlock } from "../scripts/pick.ts";
12
12
  import { cancelAllRuns } from "../execution/agent-runner.ts";
13
13
  import { describeTask } from "../workflow/workflow.ts";
@@ -162,20 +162,31 @@ export function registerLifecycle(pi: ExtensionAPI, configDir: string): void {
162
162
  const dataRoots = readDataRoots(root, configDir);
163
163
  const slices = readAgentKnowledge(dataRoots, "master");
164
164
  const query = `${taskRequest(task)} ${task.proposal ?? ""}`;
165
- const retrieval = loadConfig().workflow.knowledgeRetrieval;
165
+ const config = loadConfig();
166
+ const retrieval = config.workflow.knowledgeRetrieval;
166
167
  const selected = retrieval
167
168
  ? { knowledge: "", decisions: "", standards: selectRelevant(query, slices.standards ?? "", KNOWLEDGE_BUDGET_CHARS) }
168
169
  : selectKnowledge(query, slices);
170
+ const first = dataRoots[0];
171
+ // One combined budget across every injected knowledge section; historical decisions and completed-task logs stay retrieval-on-demand (bookmarks), never injected.
172
+ const budgeted = applyStartupBudget([
173
+ { name: "standards", content: selected.standards, path: first ? knowledgeFilePath(first, "master", "standard") : undefined },
174
+ { name: "knowledge", content: selected.knowledge, path: first ? knowledgeFilePath(first, "master", "knowledge") : undefined },
175
+ { name: "decisions", content: selected.decisions, path: first ? knowledgeFilePath(first, "master", "decision") : undefined },
176
+ { name: "bookmarks", content: retrieval ? masterBookmarks(root, configDir, dataRoots, task.id, query) : "" },
177
+ { name: "scripts", content: first ? libraryBlock(first) : "" },
178
+ ], config.workflow.knowledgeStartupBudget);
179
+ const section = (name: string) => budgeted.sections.find((entry) => entry.name === name)?.content ?? "";
169
180
  event.systemPromptOptions.sections["bot-lobby"] = compilePrompt({
170
181
  domain: "master",
171
182
  task: masterTaskContext(task, readPlanComments(root, configDir, task.id), isAutoMode(root, configDir, task.id)),
172
- standards: selected.standards,
173
- knowledge: selected.knowledge,
174
- decisions: selected.decisions,
175
- bookmarks: retrieval ? masterBookmarks(root, configDir, dataRoots, task.id, query) : "",
176
- scripts: dataRoots[0] ? libraryBlock(dataRoots[0]) : "",
177
- workflowContext: masterWorkflowContext(task),
178
- instructions: loadConfig().master.instructions,
183
+ standards: section("standards"),
184
+ knowledge: section("knowledge"),
185
+ decisions: section("decisions"),
186
+ bookmarks: section("bookmarks"),
187
+ scripts: section("scripts"),
188
+ workflowContext: [masterWorkflowContext(task), ...budgeted.diagnostics].filter(Boolean).join("\n\n"),
189
+ instructions: config.master.instructions,
179
190
  });
180
191
  });
181
192
  }