@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
@@ -77,7 +77,6 @@ export function isGitIsolation(value: unknown): value is GitIsolation {
77
77
  export interface WorkflowConfig {
78
78
  maxReviewIterations: number;
79
79
  maxParallelScouts: number;
80
- requireApprovalForFeatures: boolean;
81
80
  requireApprovalForDependencies: boolean;
82
81
  requireApprovalForArchitectureChanges: boolean;
83
82
  /** Bounded retries for transient agent failures (crash/stall), §59. A cancel never retries. */
@@ -102,24 +101,12 @@ export interface WorkflowConfig {
102
101
  knowledgeRetrieval: boolean;
103
102
  /** A scout asked the same thing again for the same task, on a tree that has not changed, reuses its findings instead of running. */
104
103
  reuseScouts: boolean;
105
- /** How a parallel batch shares the repository: one checkout with the file desk (`desk`), or a worktree per worker whose changes are merged back when the batch ends (`worktrees`). */
106
- parallelMode: ParallelMode;
104
+ /** A new task on the full workflow starts one shared scout over the domains the classifier's triage names, while the oracle reads the request; its first scout call takes those findings. */
105
+ prefetchScout: boolean;
106
+ /** A structured assignment that only reads (reference files, no edit or write) runs on the scout's model and thinking instead of the worker's. */
107
+ readOnlyOnScoutModel: boolean;
107
108
  /** The QA gate reviews with a clean context: the request, plan, board contracts and diff, not the workers' own accounts of their work. */
108
109
  cleanReview: boolean;
109
- /** Before a task completes, one read-only agent checks the change against the user's original request (not the plan) and names any gap. */
110
- goalCheck: boolean;
111
- /** Workers may ask a stronger model for advice on a hard step (`ask_expert`), a couple of times per step. */
112
- consultExpert: boolean;
113
- /** The model `ask_expert` consults; empty uses the oracle's. */
114
- expertModel: string;
115
- }
116
-
117
- /** How workers in one parallel batch share the repository. */
118
- export const PARALLEL_MODES = ["desk", "worktrees"] as const;
119
- export type ParallelMode = (typeof PARALLEL_MODES)[number];
120
-
121
- export function isParallelMode(value: unknown): value is ParallelMode {
122
- return typeof value === "string" && (PARALLEL_MODES as readonly string[]).includes(value);
123
110
  }
124
111
 
125
112
  /**
@@ -179,8 +166,6 @@ export interface LobbyWebConfig {
179
166
  export interface LobbyConfig {
180
167
  /** Who sits on the planning panel next to the oracle, until toggled in the Plan tab. */
181
168
  planningPanel: PanelMember[];
182
- /** Show the GitHub Issues tab (off for now). */
183
- issues: boolean;
184
169
  /** Bot-lobby is on when pi starts; off (the default), pi starts as plain pi until ctrl+shift+m or /bot-lobby on. */
185
170
  startOn: boolean;
186
171
  /** Which panes the Lobby tab shows. */
@@ -192,11 +177,6 @@ export interface LobbyConfig {
192
177
  * round skips the seats and asks nothing; later replies only revise. 0 = unlimited.
193
178
  */
194
179
  maxPlanningRounds: number;
195
- /**
196
- * A plan with more steps than this is offered to be split into up to five
197
- * tasks when it is saved (the oracle proposes, the user decides); 0 = never.
198
- */
199
- splitPlanAbove: number;
200
180
  /** The loopback web UI (port, browser, where its questions are answered). */
201
181
  web: LobbyWebConfig;
202
182
  }
@@ -289,7 +269,6 @@ export const DEFAULT_CONFIG: BotLobbyConfig = {
289
269
  workflow: {
290
270
  maxReviewIterations: 2,
291
271
  maxParallelScouts: 3,
292
- requireApprovalForFeatures: true,
293
272
  requireApprovalForDependencies: true,
294
273
  requireApprovalForArchitectureChanges: true,
295
274
  maxAgentRetries: 1,
@@ -303,11 +282,9 @@ export const DEFAULT_CONFIG: BotLobbyConfig = {
303
282
  repoMap: true,
304
283
  knowledgeRetrieval: true,
305
284
  reuseScouts: true,
306
- parallelMode: "desk",
285
+ prefetchScout: true,
286
+ readOnlyOnScoutModel: true,
307
287
  cleanReview: true,
308
- goalCheck: true,
309
- consultExpert: true,
310
- expertModel: "",
311
288
  },
312
289
  lint: { mode: "advise", command: "", extensions: [], timeoutMs: 2 * 60 * 1000 },
313
290
  knowledge: {
@@ -318,12 +295,10 @@ export const DEFAULT_CONFIG: BotLobbyConfig = {
318
295
  },
319
296
  lobby: {
320
297
  planningPanel: [...PANEL_MEMBERS],
321
- issues: false,
322
298
  startOn: false,
323
299
  panels: { conversation: true, activity: true, thinking: true },
324
300
  keys: {},
325
301
  maxPlanningRounds: 5,
326
- splitPlanAbove: 8,
327
302
  web: { port: 7347, openBrowser: true },
328
303
  },
329
304
  classifier: {
@@ -429,7 +404,7 @@ function flag(value: unknown, fallback: boolean): boolean {
429
404
  }
430
405
 
431
406
  function normalizeLobby(value: unknown): LobbyConfig {
432
- const source = value as { planningPanel?: unknown; issues?: unknown; startOn?: unknown; panels?: unknown; keys?: unknown; maxPlanningRounds?: unknown; splitPlanAbove?: unknown; web?: unknown } | undefined;
407
+ const source = value as { planningPanel?: unknown; startOn?: unknown; panels?: unknown; keys?: unknown; maxPlanningRounds?: unknown; web?: unknown } | undefined;
433
408
  const defaults = DEFAULT_CONFIG.lobby;
434
409
  const panel = Array.isArray(source?.planningPanel)
435
410
  ? [...new Set(source.planningPanel.filter((entry): entry is PanelMember => typeof entry === "string" && isPanelMember(entry)))]
@@ -438,12 +413,10 @@ function normalizeLobby(value: unknown): LobbyConfig {
438
413
  const keys = source?.keys && typeof source.keys === "object" ? source.keys as Record<string, unknown> : {};
439
414
  return {
440
415
  planningPanel: PANEL_MEMBERS.filter((member) => panel.includes(member)),
441
- issues: flag(source?.issues, defaults.issues),
442
416
  startOn: flag(source?.startOn, defaults.startOn),
443
417
  panels: Object.fromEntries(LOBBY_PANELS.map((name) => [name, flag(panels[name], defaults.panels[name])])) as Record<LobbyPanel, boolean>,
444
418
  keys: Object.fromEntries(Object.entries(keys).filter((entry): entry is [string, string] => typeof entry[1] === "string" && entry[1].trim().length > 0)),
445
419
  maxPlanningRounds: roundLimit(source?.maxPlanningRounds, defaults.maxPlanningRounds),
446
- splitPlanAbove: roundLimit(source?.splitPlanAbove, defaults.splitPlanAbove),
447
420
  web: normalizeLobbyWeb(source?.web, defaults.web),
448
421
  };
449
422
  }
@@ -533,15 +506,14 @@ export function resolveConfig(partial: unknown): BotLobbyConfig {
533
506
  workflow.repoMap = workflow.repoMap !== false;
534
507
  workflow.knowledgeRetrieval = workflow.knowledgeRetrieval !== false;
535
508
  workflow.reuseScouts = workflow.reuseScouts !== false;
536
- workflow.parallelMode = isParallelMode(workflow.parallelMode) ? workflow.parallelMode : DEFAULT_CONFIG.workflow.parallelMode;
509
+ workflow.prefetchScout = workflow.prefetchScout !== false;
510
+ workflow.readOnlyOnScoutModel = workflow.readOnlyOnScoutModel !== false;
537
511
  workflow.cleanReview = workflow.cleanReview !== false;
538
- workflow.goalCheck = workflow.goalCheck !== false;
539
- workflow.consultExpert = workflow.consultExpert !== false;
540
- workflow.expertModel = typeof workflow.expertModel === "string" ? workflow.expertModel.trim() : "";
541
512
  workflow.gitIsolation = isGitIsolation(workflow.gitIsolation) ? workflow.gitIsolation : DEFAULT_CONFIG.workflow.gitIsolation;
542
513
  // Agent time limits are gone: a config file that still names them is cleaned on its next save.
543
514
  // So are quick fixes: the lobby chat does that work now.
544
- for (const key of ["agentTimeoutMs", "wrapUpAt", "taskBudgetMinutes", "routeQuickFixes"]) delete (workflow as unknown as Record<string, unknown>)[key];
515
+ // The goal check, expert consults, worktrees mode and the feature approval stop are gone too.
516
+ for (const key of ["agentTimeoutMs", "wrapUpAt", "taskBudgetMinutes", "routeQuickFixes", "goalCheck", "consultExpert", "expertModel", "parallelMode", "requireApprovalForFeatures"]) delete (workflow as unknown as Record<string, unknown>)[key];
545
517
  const knowledge = { ...DEFAULT_CONFIG.knowledge, ...(src.knowledge as Partial<KnowledgeConfig> | undefined) };
546
518
  const srcAgents = (src.agents ?? {}) as Partial<BotLobbyConfig["agents"]>;
547
519
  return {
@@ -650,12 +622,6 @@ export function panelMemberProfile(config: BotLobbyConfig, member: PanelMember):
650
622
  return { model: modelOf(entry.model), thinking: entry.thinking, instructions: entry.instructions, ...grantFields(entry), ...compactField(entry), ...harnessField(config, entry) };
651
623
  }
652
624
 
653
- /** The model and thinking a worker's `ask_expert` consults: the configured expert, or the oracle's model. */
654
- export function expertProfile(config: BotLobbyConfig): { model?: string; thinking: string } {
655
- const model = config.workflow.expertModel ? modelOf(config.workflow.expertModel) : modelOf(config.master.model);
656
- return { ...(model ? { model } : {}), thinking: "high" };
657
- }
658
-
659
625
  /** Resolves the model, thinking and grants one subagent run uses. */
660
626
  export type ProfileResolver = (domain: Domain, role: Role) => AgentProfile;
661
627
 
@@ -1,3 +1,4 @@
1
+ import type { AssignmentExpansionRequest } from "../execution/assignment.ts";
1
2
  import type { Domain, Role } from "./agent.ts";
2
3
  import type { Blocker, Verdict } from "./task.ts";
3
4
 
@@ -63,6 +64,8 @@ export interface WorkerResult {
63
64
  scriptProposals?: ScriptProposal[];
64
65
  dependencyNeeds: string[];
65
66
  architectureChanges: string[];
67
+ /** Validated requests only; requests never grant additional permissions. */
68
+ needs?: AssignmentExpansionRequest[];
66
69
  pushback?: Pushback;
67
70
  raw: string;
68
71
  }
@@ -1,3 +1,4 @@
1
+ import type { WorkerAssignment, AssignmentExpansionRequest } from "../execution/assignment.ts";
1
2
  import type { LintReport } from "./lint.ts";
2
3
  import type { Domain, Role } from "./agent.ts";
3
4
  import type { Delivery } from "../delivery/types.ts";
@@ -34,6 +35,7 @@ export interface Blocker {
34
35
  export interface Decision {
35
36
  domain: Domain | "master";
36
37
  text: string;
38
+ discoveryAllowance?: { assignmentId: string; revision: number; decisionId: string; reason: string; limit: number };
37
39
  createdAt: string;
38
40
  }
39
41
 
@@ -253,7 +255,35 @@ export interface PhaseTiming {
253
255
  blockingRequestIds: string[];
254
256
  }
255
257
 
258
+ /** Master-authored briefs, separate from runtime artifact access identities. */
259
+ export interface WorkerAssignmentRecord {
260
+ domain: Domain;
261
+ brief: WorkerAssignment;
262
+ revisions: WorkerAssignment[];
263
+ outcomes: {
264
+ revision: number;
265
+ runId: string;
266
+ status: WorkerRunRecord["status"];
267
+ completedWork: string[];
268
+ needs: AssignmentExpansionRequest[];
269
+ /** Absent on legacy outcomes; acceptance must require current evidence. */
270
+ issues?: string[];
271
+ verification?: string;
272
+ freshness?: {
273
+ assignmentId: string;
274
+ revision: number;
275
+ status: "unverified hints" | "verified" | "invalidated" | "superseded";
276
+ hintIds: string[];
277
+ hints?: { id: string; scope: "file" | "repository"; source: string; fingerprint: string }[];
278
+ pause?: true;
279
+ recheckCompletedWork?: boolean;
280
+ };
281
+ finishedAt?: string;
282
+ }[];
283
+ }
284
+
256
285
  export interface Task {
286
+ workerAssignments?: WorkerAssignmentRecord[];
257
287
  /** Advisory task-state checkpoint; external references require live revalidation. */
258
288
  checkpoint?: TaskCheckpoint;
259
289
  /** Canonical waits, including legacy tasks without a reliable clock. */
@@ -310,18 +340,6 @@ export interface Task {
310
340
  lintWaiver?: { at: string };
311
341
  /** Plan steps the user skipped, each with their reason; the oracle is told not to work on them. */
312
342
  skippedSteps?: SkippedStep[];
313
- /** The last goal check: the change (by its diff's hash) read against the user's request before completion. */
314
- goalCheck?: GoalCheckRecord;
315
- }
316
-
317
- export interface GoalCheckRecord {
318
- /** Hash of the diff it read: the same change is not checked twice. */
319
- key: string;
320
- verdict: "met" | "not_met";
321
- gaps: string[];
322
- at: string;
323
- /** When completion was refused for these gaps: only then can the oracle complete anyway with a reason. */
324
- refusedAt?: string;
325
343
  }
326
344
 
327
345
  export function createTask(
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
+ import { fileURLToPath } from "node:url";
15
16
 
16
17
  /** The languages a script may be written in: how it is run and how its header lines are commented. */
17
18
  export const SCRIPT_LANGUAGES = {
@@ -46,8 +47,17 @@ export interface ScriptEntry {
46
47
  purpose: string;
47
48
  /** How to run it, with its arguments; the runner and path when the header gives none. */
48
49
  usage: string;
50
+ /** Shipped with bot-lobby (`scripts/builtin/`), for every project; a project script of the same name wins. */
51
+ builtin?: boolean;
49
52
  }
50
53
 
54
+ /**
55
+ * The scripts bot-lobby ships for every project: read-only helpers for the
56
+ * jobs every task repeats (the tests and checks for what changed, where a
57
+ * symbol lives, a file's outline, the project's commands, a map of the repo).
58
+ */
59
+ export const BUILTIN_SCRIPTS_DIR = fileURLToPath(new URL("../../scripts/builtin/", import.meta.url));
60
+
51
61
  export function scriptsDir(dataRoot: string): string {
52
62
  return join(dataRoot, "scripts");
53
63
  }
@@ -95,7 +105,9 @@ function readEntry(dir: string, name: string): ScriptEntry | undefined {
95
105
  if (!statSync(path).isFile()) return undefined;
96
106
  const lines = readFileSync(path, "utf8").split("\n").slice(0, HEADER_LINES);
97
107
  const entry = { name, path, language: language(name) };
98
- return { ...entry, purpose: headerValue(lines, "purpose") ?? nameWords(name), usage: headerValue(lines, "usage") ?? runCommand(entry) };
108
+ // `{script}` in a usage line stands for the script's own path.
109
+ const usage = headerValue(lines, "usage")?.replaceAll("{script}", path) ?? runCommand(entry);
110
+ return { ...entry, purpose: headerValue(lines, "purpose") ?? nameWords(name), usage };
99
111
  } catch {
100
112
  return undefined;
101
113
  }
@@ -112,6 +124,24 @@ export function listScripts(dataRoot: string): ScriptEntry[] {
112
124
  .filter((entry): entry is ScriptEntry => entry !== undefined);
113
125
  }
114
126
 
127
+ /** The built-in scripts, by name. */
128
+ export function builtinScripts(dir = BUILTIN_SCRIPTS_DIR): ScriptEntry[] {
129
+ if (!existsSync(dir)) return [];
130
+ return readdirSync(dir)
131
+ .filter((name) => NAME.test(name))
132
+ .sort()
133
+ .map((name) => readEntry(dir, name))
134
+ .filter((entry): entry is ScriptEntry => entry !== undefined)
135
+ .map((entry) => ({ ...entry, builtin: true }));
136
+ }
137
+
138
+ /** The project's scripts, then the built-in ones it does not replace with its own of the same name. */
139
+ export function allScripts(dataRoot: string): ScriptEntry[] {
140
+ const own = listScripts(dataRoot);
141
+ const names = new Set(own.map((entry) => entry.name));
142
+ return [...own, ...builtinScripts().filter((entry) => !names.has(entry.name))];
143
+ }
144
+
115
145
  /** The body with any header lines of its own taken out, and a shebang it starts with kept apart. */
116
146
  function splitBody(body: string): { shebang?: string; rest: string } {
117
147
  const lines = body.replace(/\r\n/g, "\n").split("\n");
@@ -6,7 +6,7 @@
6
6
  * the library, so an agent can look for itself.
7
7
  */
8
8
  import { score, tokenize } from "../knowledge/selector.ts";
9
- import { listScripts, nameWords, scriptsDir, type ScriptEntry } from "./library.ts";
9
+ import { allScripts, BUILTIN_SCRIPTS_DIR, nameWords, scriptsDir, type ScriptEntry } from "./library.ts";
10
10
 
11
11
  /** Most scripts one prompt suggests. */
12
12
  export const MAX_SUGGESTED = 6;
@@ -36,38 +36,54 @@ function line(entry: ScriptEntry): string {
36
36
  return `- \`${entry.name}\` — ${entry.purpose}\n run: \`${entry.usage}\``;
37
37
  }
38
38
 
39
+ /** The built-ins not already suggested, by name, in one line: always in reach, never a long list. */
40
+ function builtinLine(entries: readonly ScriptEntry[], picked: readonly ScriptEntry[]): string {
41
+ const rest = entries.filter((entry) => entry.builtin && !picked.includes(entry));
42
+ if (rest.length === 0) return "";
43
+ return `Built-in scripts (read-only; \`node ${BUILTIN_SCRIPTS_DIR}<name>.mjs --help\` shows what each does and how to run it): ${rest.map((entry) => entry.name.replace(/\.mjs$/, "")).join(", ")}. Prefer them to working the same thing out by hand: find_symbol over rounds of grep, outline_file before reading a long file, run_changed_tests and check_changed over whole suites.`;
44
+ }
45
+
39
46
  /**
40
47
  * The Scripts layer of a worker's, scout's or QA agent's prompt: the scripts
41
- * that fit this step and how to run each, then where the rest are. "" while
42
- * the library is empty.
48
+ * that fit this step and how to run each, where the project's own are, and
49
+ * the built-ins. "" with no scripts at all.
43
50
  */
44
51
  export function scriptsBlock(dataRoot: string, entries: readonly ScriptEntry[], picked: readonly ScriptEntry[]): string {
45
52
  if (entries.length === 0) return "";
46
- const where = `The shared scripts library (${entries.length} script${entries.length === 1 ? "" : "s"}) is \`${scriptsDir(dataRoot)}\`; each file's first lines say what it does and how to run it.`;
47
- if (picked.length === 0) return `None of the shared scripts fits this step. ${where}`;
53
+ const own = entries.filter((entry) => !entry.builtin).length;
54
+ const where = own > 0 ? `The shared scripts library (${own} script${own === 1 ? "" : "s"}) is \`${scriptsDir(dataRoot)}\`; each file's first lines say what it does and how to run it.` : "";
55
+ const builtins = builtinLine(entries, picked);
56
+ if (picked.length === 0) return [`None of the shared scripts fits this step exactly.`, where, builtins].filter(Boolean).join(" ");
48
57
  return [
49
58
  "These shared scripts do part of this step: run one instead of doing its work by hand, and check its output as you would your own.",
50
59
  ...picked.map(line),
51
60
  where,
52
- ].join("\n");
61
+ builtins,
62
+ ].filter(Boolean).join("\n");
53
63
  }
54
64
 
55
- /** The oracle's view of the library: every script by name and purpose, so it can point a brief at one. */
56
- export function libraryBlock(dataRoot: string, entries: readonly ScriptEntry[] = listScripts(dataRoot)): string {
65
+ /** The oracle's view of the library: every project script by name and purpose, and the built-ins, so it can point a brief at one. */
66
+ export function libraryBlock(dataRoot: string, entries: readonly ScriptEntry[] = allScripts(dataRoot)): string {
57
67
  const dir = scriptsDir(dataRoot);
58
- if (entries.length === 0) return `The shared scripts library (\`${dir}\`) is empty.`;
59
- const shown = entries.slice(0, MAX_LISTED).map((entry) => `- \`${entry.name}\` — ${entry.purpose}`);
60
- const more = entries.length > MAX_LISTED ? [`…and ${entries.length - MAX_LISTED} more in \`${dir}\`.`] : [];
61
- return [`Shared scripts (\`${dir}\`):`, ...shown, ...more].join("\n");
68
+ const own = entries.filter((entry) => !entry.builtin);
69
+ const builtin = entries.filter((entry) => entry.builtin);
70
+ const shown = own.slice(0, MAX_LISTED).map((entry) => `- \`${entry.name}\` — ${entry.purpose}`);
71
+ const more = own.length > MAX_LISTED ? [`…and ${own.length - MAX_LISTED} more in \`${dir}\`.`] : [];
72
+ return [
73
+ own.length === 0 ? `The project's scripts library (\`${dir}\`) is empty.` : `Shared scripts (\`${dir}\`):`,
74
+ ...shown,
75
+ ...more,
76
+ ...(builtin.length > 0 ? [`Built-in scripts every agent can run (\`${BUILTIN_SCRIPTS_DIR}\`): ${builtin.map((entry) => entry.name).join(", ")}. Name one in a brief when it does part of the step.`] : []),
77
+ ].join("\n");
62
78
  }
63
79
 
64
80
  /**
65
- * The Scripts layer for one agent's step: the library read, the picker's
66
- * choice (shared words when it fails), and the block. "" with no scripts.
81
+ * The Scripts layer for one agent's step: the library read (built-ins
82
+ * included), the picker's choice (shared words when it fails), and the block.
67
83
  */
68
84
  export async function scriptsFor(dataRoot: string | undefined, step: string, picker: ScriptPicker = keywordPicker, signal?: AbortSignal): Promise<string> {
69
85
  if (!dataRoot) return "";
70
- const entries = listScripts(dataRoot);
86
+ const entries = allScripts(dataRoot);
71
87
  if (entries.length === 0) return "";
72
88
  let picked: ScriptEntry[];
73
89
  try {
@@ -12,6 +12,7 @@ import { taskDir, tasksRoot } from "../knowledge/paths.ts";
12
12
  import { transition } from "./task-state.ts";
13
13
  import { dataRoot, readDataRoots } from "./project.ts";
14
14
  import { forgetCachedUnder, readJsonCached } from "./file-cache.ts";
15
+ import { cleanupTaskAssignedSessions } from "../execution/assigned-session.ts";
15
16
 
16
17
  export function archiveRoot(root: string, configDir: string): string {
17
18
  return join(dataRoot(root, configDir), "archive", "tasks");
@@ -81,6 +82,7 @@ export function archiveTask(root: string, configDir: string, taskId: string, now
81
82
  }
82
83
  task.archivedAt = stamp;
83
84
  writeAt(from, task);
85
+ cleanupTaskAssignedSessions(from);
84
86
  mkdirSync(dirname(to), { recursive: true });
85
87
  renameSync(from, to);
86
88
  return task;
@@ -93,6 +95,7 @@ export function restoreTask(root: string, configDir: string, taskId: string): Ta
93
95
  if (!task) throw new Error(`${taskId} is not in the archive`);
94
96
  const to = taskDir(dataRoot(root, configDir), taskId);
95
97
  if (existsSync(to)) throw new Error(`a task ${taskId} is already on the list`);
98
+ if (TERMINAL_STATES.includes(task.state)) cleanupTaskAssignedSessions(from);
96
99
  delete task.archivedAt;
97
100
  writeAt(from, task);
98
101
  mkdirSync(tasksRoot(dataRoot(root, configDir)), { recursive: true });
@@ -104,5 +107,12 @@ export function restoreTask(root: string, configDir: string, taskId: string): Ta
104
107
  export function deleteTask(root: string, configDir: string, taskId: string, where: "list" | "archive" = "list"): void {
105
108
  const dir = where === "archive" ? archivedDir(root, configDir, taskId) : liveDir(root, configDir, checkId(taskId));
106
109
  if (!dir || !existsSync(dir)) throw new Error(where === "archive" ? `${taskId} is not in the archive` : `no task ${taskId}`);
110
+ const task = readAt(dir);
111
+ if (task && !TERMINAL_STATES.includes(task.state)) {
112
+ transition(task, "abandoned", new Date().toISOString());
113
+ writeAt(dir, task);
114
+ }
115
+ // Refuse deletion while an assignment owns a live lock; never erase a running conversation.
116
+ cleanupTaskAssignedSessions(dir);
107
117
  rmSync(dir, { recursive: true, force: true });
108
118
  }
@@ -128,7 +128,6 @@ function bookmarks(records: readonly BookmarkRecord[] = []): CheckpointList<Book
128
128
  function evidence(task: Task): CheckpointList<CheckpointTaskRef> {
129
129
  const records: CheckpointTaskRef[] = task.reviewRecords.slice(-8).map((record, i) => ({ ...taskRef(`task.reviewRecords[${Math.max(0, task.reviewRecords.length - 8) + i}]`, record), result: record.verdict }));
130
130
  if (task.lint) records.push({ ...taskRef("task.lint", task.lint), result: task.lint.state });
131
- if (task.goalCheck) records.push({ ...taskRef("task.goalCheck", task.goalCheck), result: task.goalCheck.verdict });
132
131
  return { ...list(records), omitted: Math.max(0, task.reviewRecords.length - 8) };
133
132
  }
134
133
 
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The managed `.gitignore` block for bot-lobby's per-project data. Off (the
3
+ * default) ignores all of `.pi/`; on ignores only its siblings and negates
4
+ * `.pi/bot-lobby/` back in, so the lobby's tasks, knowledge and scripts ride
5
+ * with the repo. Pure string handling: no fs, no git subprocesses.
6
+ */
7
+
8
+ const OFF_COMMENT = "# bot-lobby local task state, knowledge and config";
9
+ const ON_COMMENT = "# bot-lobby local task state and config (bot-lobby retained in git)";
10
+
11
+ /** Every line this module owns, wherever it appears in the file. */
12
+ const MANAGED = new Set([OFF_COMMENT, ON_COMMENT, ".pi/", ".pi/*", "!.pi/bot-lobby", "!.pi/bot-lobby/"]);
13
+
14
+ /** True iff content negates `.pi/bot-lobby` back into the repo. */
15
+ export function retentionEnabled(content: string): boolean {
16
+ return content.split("\n").some((line) => {
17
+ const trimmed = line.trim();
18
+ return trimmed === "!.pi/bot-lobby" || trimmed === "!.pi/bot-lobby/";
19
+ });
20
+ }
21
+
22
+ /** Rewrite content so the managed block matches `enabled`; pure and idempotent. */
23
+ export function withRetention(content: string, enabled: boolean): string {
24
+ const block = enabled ? [ON_COMMENT, ".pi/*", "!.pi/bot-lobby/"] : [OFF_COMMENT, ".pi/"];
25
+ const lines = content.split("\n");
26
+ if (lines.at(-1) === "") lines.pop();
27
+ const kept: string[] = [];
28
+ let at = -1;
29
+ for (const line of lines) {
30
+ if (MANAGED.has(line.trim())) {
31
+ if (at < 0) at = kept.length;
32
+ continue;
33
+ }
34
+ kept.push(line);
35
+ }
36
+ if (at < 0) return kept.length === 0 ? `${block.join("\n")}\n` : `${kept.join("\n")}\n\n${block.join("\n")}\n`;
37
+ kept.splice(at, 0, ...block);
38
+ return `${kept.join("\n")}\n`;
39
+ }
@@ -1,4 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import type { WorkerAssignment } from "../execution/assignment.ts";
2
4
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
3
5
  import { join, sep } from "node:path";
4
6
  import type { KnowledgeConfig } from "../schemas/configuration.ts";
@@ -193,6 +195,59 @@ function trimAssignments(records: AssignmentRecord[]): AssignmentRecord[] {
193
195
  return kept;
194
196
  }
195
197
 
198
+ /** Preflight a whole batch before any state mutation or worker dispatch. */
199
+ export function checkWorkerAssignments(task: Task, batch: { domain: Domain; assignment: WorkerAssignment }[]): void {
200
+ const ids = new Set<string>();
201
+ for (const { domain, assignment } of batch) {
202
+ if (ids.has(assignment.id)) throw new Error(`Duplicate worker assignment id ${assignment.id} in batch`);
203
+ ids.add(assignment.id);
204
+ const prior = task.workerAssignments?.find((entry) => entry.brief.id === assignment.id);
205
+ if (!prior) continue;
206
+ if (prior.domain !== domain) throw new Error(`Assignment ${assignment.id} belongs to ${prior.domain}; keep its domain stable`);
207
+ if (assignment.revision < prior.brief.revision) throw new Error(`Stale assignment ${assignment.id}; current revision is ${prior.brief.revision}`);
208
+ if (assignment.revision === prior.brief.revision && !isDeepStrictEqual(assignment, prior.brief)) throw new Error(`Conflicting assignment ${assignment.id} revision ${assignment.revision}; increase revision for changes`);
209
+ }
210
+ }
211
+
212
+ /** Inputs must first pass validateAssignment and workflow approval-ledger checks. */
213
+ export function recordWorkerAssignments(task: Task, batch: { domain: Domain; assignment: WorkerAssignment }[]): void {
214
+ checkWorkerAssignments(task, batch);
215
+ task.workerAssignments ??= [];
216
+ for (const { domain, assignment } of batch) {
217
+ const prior = task.workerAssignments.find((entry) => entry.brief.id === assignment.id);
218
+ if (!prior) task.workerAssignments.push({ domain, brief: structuredClone(assignment), revisions: [structuredClone(assignment)], outcomes: [] });
219
+ else if (assignment.revision > prior.brief.revision) {
220
+ prior.brief = structuredClone(assignment);
221
+ prior.revisions.push(structuredClone(assignment));
222
+ }
223
+ }
224
+ }
225
+
226
+ /** Preserve newer revisions and independently recorded outcomes during stale saves. */
227
+ function preserveWorkerAssignments(task: Task, latest: Task): void {
228
+ const merged = new Map((latest.workerAssignments ?? []).map((entry) => [entry.brief.id, structuredClone(entry)]));
229
+ for (const mine of task.workerAssignments ?? []) {
230
+ const prior = merged.get(mine.brief.id);
231
+ if (!prior) { merged.set(mine.brief.id, mine); continue; }
232
+ if (mine.domain !== prior.domain) throw new Error(`Conflicting assignment domain ${mine.brief.id}`);
233
+ for (const revision of mine.revisions) {
234
+ const existing = prior.revisions.find((entry) => entry.revision === revision.revision);
235
+ if (existing && !isDeepStrictEqual(existing, revision)) throw new Error(`Conflicting assignment ${revision.id} revision ${revision.revision}`);
236
+ if (!existing) prior.revisions.push(revision);
237
+ }
238
+ prior.revisions.sort((a, b) => a.revision - b.revision);
239
+ prior.brief = prior.revisions.at(-1)!;
240
+ for (const outcome of mine.outcomes) {
241
+ const existing = prior.outcomes.find((entry) => entry.runId === outcome.runId);
242
+ if (!existing) { prior.outcomes.push(outcome); continue; }
243
+ // Never let a stale save restore an invalidated evidence verdict.
244
+ if (outcome.freshness?.status === "invalidated") existing.freshness = structuredClone(outcome.freshness);
245
+ if (existing.issues || outcome.issues) existing.issues = [...new Set([...(existing.issues ?? []), ...(outcome.issues ?? [])])];
246
+ }
247
+ }
248
+ if (merged.size) task.workerAssignments = [...merged.values()];
249
+ }
250
+
196
251
  export function saveTask(root: string, configDir: string, task: Task): void {
197
252
  const latest = loadTask(root, configDir, task.id);
198
253
  // Abandonment is final: an in-flight action must not overwrite its audit or resurrect it.
@@ -205,6 +260,7 @@ export function saveTask(root: string, configDir: string, task: Task): void {
205
260
  preserveUserConstraints(task, latest);
206
261
  mergePhaseTiming(task, timingBaselines.get(task), latest);
207
262
  preserveAssignments(task, latest);
263
+ preserveWorkerAssignments(task, latest);
208
264
  }
209
265
  refreshCheckpoint(task, root, latest?.checkpoint);
210
266
  const path = join(taskDir(dataRoot(root, configDir), task.id), "state.json");
@@ -12,7 +12,10 @@
12
12
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
13
13
  import { join } from "node:path";
14
14
  import { randomBytes } from "node:crypto";
15
- import { dataRoot } from "./project.ts";
15
+ import { dataRoot, readDataRoots } from "./project.ts";
16
+ import { tasksRoot } from "../knowledge/paths.ts";
17
+ import { TERMINAL_STATES } from "../schemas/task.ts";
18
+ import { cleanupTaskAssignedSessions } from "../execution/assigned-session.ts";
16
19
  import { processAlive } from "./presence.ts";
17
20
 
18
21
  /** A background session a window drives, as the next window relaunches it. */
@@ -121,6 +124,7 @@ export function stoppedWindows(root: string, configDir: string, alive: (pid: num
121
124
  * the same work. Returns the records this process took.
122
125
  */
123
126
  export function claimStoppedWindows(root: string, configDir: string, alive: (pid: number) => boolean = processAlive): WindowRecord[] {
127
+ retryTerminalAssignedSessionCleanup(root, configDir);
124
128
  const claimed: WindowRecord[] = [];
125
129
  for (const record of stoppedWindows(root, configDir, alive)) {
126
130
  const path = windowPath(root, configDir, record.pid, record.token);
@@ -135,6 +139,34 @@ export function claimStoppedWindows(root: string, configDir: string, alive: (pid
135
139
  return claimed;
136
140
  }
137
141
 
142
+ /** Terminal cleanup is retried independently: one locked/corrupt task never prevents other recovery. */
143
+ export function retryTerminalAssignedSessionCleanup(root: string, configDir: string): { taskDir: string; error: string }[] {
144
+ const issues: { taskDir: string; error: string }[] = [];
145
+ for (const dr of readDataRoots(root, configDir)) {
146
+ for (const tree of [tasksRoot(dr), join(dr, "archive", "tasks")]) {
147
+ if (!existsSync(tree)) continue;
148
+ for (const entry of readdirSync(tree, { withFileTypes: true })) {
149
+ if (!entry.isDirectory()) continue;
150
+ const dir = join(tree, entry.name);
151
+ const task = readJson(join(dir, "state.json")) as { state?: unknown } | undefined;
152
+ if (!task || !TERMINAL_STATES.some(state => state === task.state)) continue;
153
+ retryTaskCleanup(dir, issues);
154
+ }
155
+ }
156
+ }
157
+ return issues;
158
+ }
159
+ function retryTaskCleanup(dir: string, issues: { taskDir: string; error: string }[]): void {
160
+ const issueFile = join(dir, "assigned-session-cleanup-issue.json");
161
+ try { cleanupTaskAssignedSessions(dir); rmSync(issueFile, { force: true }); }
162
+ catch (error) {
163
+ const issue = { taskDir: dir, error: error instanceof Error ? error.message : String(error) };
164
+ issues.push(issue);
165
+ try { writeAtomic(issueFile, issue); }
166
+ catch (failure) { issue.error += `; could not persist recovery issue: ${failure instanceof Error ? failure.message : String(failure)}`; }
167
+ }
168
+ }
169
+
138
170
  function statePath(root: string, configDir: string, kind: SessionStateKind, sessionId: string): string | undefined {
139
171
  const id = safe(sessionId);
140
172
  return id ? join(recoveryDir(root, configDir), `${kind}-${id}.json`) : undefined;