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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +8 -8
  2. package/package.json +2 -1
  3. package/prompts/designer.md +25 -15
  4. package/prompts/master.md +284 -491
  5. package/prompts/panel.md +7 -0
  6. package/prompts/planner.md +15 -4
  7. package/prompts/qa.md +5 -1
  8. package/prompts/worker.md +0 -7
  9. package/scripts/builtin/affected_packages.mjs +106 -0
  10. package/scripts/builtin/check_changed.mjs +51 -0
  11. package/scripts/builtin/check_contract_breakage.mjs +118 -0
  12. package/scripts/builtin/circular_dependency_check.mjs +79 -0
  13. package/scripts/builtin/code_duplication_check.mjs +86 -0
  14. package/scripts/builtin/diff_summary.mjs +62 -0
  15. package/scripts/builtin/failure_digest.mjs +107 -0
  16. package/scripts/builtin/find_generated_files.mjs +79 -0
  17. package/scripts/builtin/find_symbol.mjs +81 -0
  18. package/scripts/builtin/find_test_fixtures.mjs +73 -0
  19. package/scripts/builtin/find_tests_for.mjs +12 -0
  20. package/scripts/builtin/lib/common.mjs +267 -0
  21. package/scripts/builtin/outline_file.mjs +77 -0
  22. package/scripts/builtin/project_commands.mjs +49 -0
  23. package/scripts/builtin/recent_changes.mjs +14 -0
  24. package/scripts/builtin/repo_map.mjs +65 -0
  25. package/scripts/builtin/run_changed_tests.mjs +48 -0
  26. package/src/delivery/transport.ts +1 -1
  27. package/src/desk/client-extension.ts +1 -31
  28. package/src/desk/ipc.ts +1 -11
  29. package/src/desk/session.ts +4 -101
  30. package/src/execution/agent-runner.ts +50 -8
  31. package/src/execution/assigned-session.ts +263 -0
  32. package/src/execution/assignment-discovery.ts +128 -0
  33. package/src/execution/assignment-policy.ts +46 -0
  34. package/src/execution/assignment.ts +175 -0
  35. package/src/execution/delegation.ts +9 -94
  36. package/src/execution/pi-runner.ts +99 -9
  37. package/src/harness/instructions.ts +1 -1
  38. package/src/index.ts +3 -0
  39. package/src/knowledge/design-record.ts +394 -0
  40. package/src/knowledge/file-notes.ts +36 -8
  41. package/src/lobby/ask.ts +6 -0
  42. package/src/lobby/exec.ts +28 -0
  43. package/src/lobby/host.ts +2 -11
  44. package/src/lobby/pi-commands.ts +83 -0
  45. package/src/lobby/planner.ts +50 -124
  46. package/src/lobby/prompts.ts +1 -7
  47. package/src/lobby/runtime.ts +2 -26
  48. package/src/lobby/service.ts +28 -27
  49. package/src/lobby/topics.ts +0 -2
  50. package/src/master/evidence-freshness.ts +96 -0
  51. package/src/master/master.ts +248 -74
  52. package/src/master/scout-cache.ts +1 -1
  53. package/src/master/scout-lock.ts +44 -0
  54. package/src/master/scout-prefetch.ts +78 -0
  55. package/src/pi/activity.ts +2 -0
  56. package/src/pi/assignment-guard.ts +157 -0
  57. package/src/pi/delegation.ts +2 -21
  58. package/src/pi/model-support.ts +0 -6
  59. package/src/pi/start-task.ts +18 -7
  60. package/src/pi/tools.ts +41 -8
  61. package/src/roles/scout.ts +3 -1
  62. package/src/roles/worker.ts +107 -5
  63. package/src/schemas/configuration.ts +11 -45
  64. package/src/schemas/findings.ts +3 -0
  65. package/src/schemas/task.ts +30 -12
  66. package/src/scripts/library.ts +31 -1
  67. package/src/scripts/pick.ts +31 -15
  68. package/src/state/archive.ts +10 -0
  69. package/src/state/checkpoint.ts +0 -1
  70. package/src/state/gitignore.ts +39 -0
  71. package/src/state/persistence.ts +56 -0
  72. package/src/state/recovery.ts +33 -1
  73. package/src/webui/api/index.ts +6 -35
  74. package/src/webui/api/retention.ts +44 -0
  75. package/src/webui/api/status.ts +5 -6
  76. package/src/webui/dev/fake-service.ts +8 -117
  77. package/src/webui/dev/fixtures.ts +2 -16
  78. package/src/webui/protocol.ts +3 -142
  79. package/src/workflow/draft-assignments.ts +118 -0
  80. package/src/workflow/workflow.ts +271 -214
  81. package/webui/dist/assets/{CodeSurface-BtzJOVyH.js → CodeSurface-CdyiJTYa.js} +1 -1
  82. package/webui/dist/assets/{TerminalView-Cz-KNWsq.js → TerminalView-D2nbR2J1.js} +1 -1
  83. package/webui/dist/assets/index-BTyu99rI.css +2 -0
  84. package/webui/dist/assets/index-BUGK22Z6.js +112 -0
  85. package/webui/dist/build.json +32 -68
  86. package/webui/dist/index.html +2 -2
  87. package/prompts/expert.md +0 -17
  88. package/prompts/goal-check.md +0 -44
  89. package/prompts/pr-review.md +0 -62
  90. package/prompts/splitter.md +0 -58
  91. package/src/execution/worker-trees.ts +0 -396
  92. package/src/lobby/issues.ts +0 -219
  93. package/src/lobby/pr-review.ts +0 -366
  94. package/src/lobby/pulls.ts +0 -250
  95. package/src/lobby/split.ts +0 -262
  96. package/src/master/goal-check.ts +0 -115
  97. package/src/webui/api/gh-error.ts +0 -17
  98. package/src/webui/api/git.ts +0 -98
  99. package/src/webui/api/issues.ts +0 -50
  100. package/webui/dist/assets/index-D5fvY8f8.js +0 -112
  101. package/webui/dist/assets/index-DFvk8ADr.css +0 -2
@@ -1,262 +0,0 @@
1
- /**
2
- * Splitting a long plan into tasks. When the user saves a plan with many
3
- * steps, the oracle proposes how to cut it into two to five tasks, the user
4
- * decides (keep it whole, take the split, or say what to change), and each part
5
- * is saved as a pending task that knows its siblings.
6
- *
7
- * The oracle decides where the lines go; the engine enforces the rest: at
8
- * most `MAX_SPLIT_TASKS` tasks, every step of the plan in exactly one of them,
9
- * and a task only ever building on earlier ones. A proposal that breaks a rule
10
- * is sent back once with the problems, and never reaches the user. Each part's
11
- * brief is composed here from the plan as written (its objective, decisions,
12
- * assumptions and risks stay whole, its steps section holds only that part's
13
- * steps), so nothing the user agreed can be lost in a model's retelling.
14
- */
15
- import { loadPrompt } from "../prompts/loader.ts";
16
- import { planStepBlocks } from "../pi/plan-checklist.ts";
17
- import type { SplitInfo } from "../state/backlog.ts";
18
- import type { AskQuestion } from "../ask/types.ts";
19
-
20
- /** The most tasks a plan is split into. */
21
- export const MAX_SPLIT_TASKS = 5;
22
- /** Times the user may ask the oracle to change a split before it is final. */
23
- export const MAX_SPLIT_REVISIONS = 3;
24
-
25
- export interface SplitTask {
26
- title: string;
27
- goal: string;
28
- /** The plan's steps (numbered from 1) this task does. */
29
- covers: number[];
30
- /** Earlier tasks (numbered from 1) it builds on. */
31
- after: number[];
32
- done: string[];
33
- }
34
-
35
- export interface SplitProposal {
36
- tasks: SplitTask[];
37
- /** What the oracle tells the user about the split. */
38
- note?: string;
39
- }
40
-
41
- export function splitPrompt(instructions?: string): string {
42
- const custom = instructions?.trim();
43
- return custom ? `${loadPrompt("splitter.md")}\n\n## Custom Instructions\n\n${custom}` : loadPrompt("splitter.md");
44
- }
45
-
46
- /** `3, 5-6` as [3, 5, 6]; `none` (or nothing) as []. Ranges are bounded, so a stray `1-999999` cannot fill memory. */
47
- export function parseNumbers(text: string): number[] {
48
- const found = new Set<number>();
49
- for (const match of text.matchAll(/(\d+)(?:\s*[-–—]\s*(\d+))?/g)) {
50
- const first = Number(match[1]);
51
- const last = match[2] ? Number(match[2]) : first;
52
- for (let number = first; number <= Math.min(last, first + 200); number += 1) found.add(number);
53
- }
54
- return [...found].sort((a, b) => a - b);
55
- }
56
-
57
- /** Read the oracle's reply into a proposal; throws a one-line reason when it has no tasks at all. */
58
- export function parseSplit(text: string): SplitProposal {
59
- const [head = "", ...after] = text.split(/^##\s+Note\s*$/im);
60
- const note = after.join("\n").trim().replace(/\s+/g, " ") || undefined;
61
- const parts = head.split(/^###\s+\d+[.):]?\s*/m).slice(1);
62
- if (parts.length === 0) throw new Error("no tasks found: write each as `### 1. Title` with Goal, Covers, After and Done when");
63
- const tasks = parts.map((part): SplitTask => {
64
- const lines = part.split("\n");
65
- const title = (lines[0] ?? "").replace(/[*_`#]/g, "").trim();
66
- const value = (key: string) => new RegExp(`^\\s*[-*]?\\s*\\**${key}\\**\\s*:\\**\\s*(.*)$`, "im").exec(part)?.[1]?.trim() ?? "";
67
- const doneAt = lines.findIndex((line) => /^\s*\**done when\**\s*:/i.test(line));
68
- const inline = doneAt < 0 ? undefined : /:\**\s*(\S.*)$/.exec(lines[doneAt]!)?.[1];
69
- const bullets = doneAt < 0 ? [] : lines.slice(doneAt + 1).filter((line) => /^\s*[-*]\s+\S/.test(line)).map((line) => line.replace(/^\s*[-*]\s+/, "").trim());
70
- const done = [...(inline ? [inline] : []), ...bullets];
71
- return { title, goal: value("goal"), covers: parseNumbers(value("covers")), after: parseNumbers(value("after")), done };
72
- });
73
- return { tasks, ...(note ? { note } : {}) };
74
- }
75
-
76
- /** Every rule a proposal breaks, in words the oracle can act on; empty when it is sound. */
77
- export function splitProblems(proposal: SplitProposal, stepCount: number, max = MAX_SPLIT_TASKS): string[] {
78
- const problems: string[] = [];
79
- const { tasks } = proposal;
80
- if (tasks.length < 2) problems.push("a split needs at least 2 tasks");
81
- if (tasks.length > max) problems.push(`a plan is split into at most ${max} tasks, not ${tasks.length}`);
82
- const owner = new Map<number, number>();
83
- tasks.forEach((task, index) => {
84
- const number = index + 1;
85
- if (!task.title) problems.push(`task ${number} has no title`);
86
- if (task.covers.length === 0) problems.push(`task ${number} covers no steps`);
87
- for (const step of task.covers) {
88
- if (step < 1 || step > stepCount) problems.push(`task ${number} covers step ${step}, but the plan has steps 1 to ${stepCount}`);
89
- else if (owner.has(step)) problems.push(`step ${step} is in both task ${owner.get(step)} and task ${number}`);
90
- else owner.set(step, number);
91
- }
92
- for (const earlier of task.after) if (earlier >= number || earlier < 1) problems.push(`task ${number} cannot come after task ${earlier}: list the tasks in the order they can be done, each building only on earlier ones`);
93
- });
94
- const missing = Array.from({ length: stepCount }, (_, index) => index + 1).filter((step) => !owner.has(step));
95
- if (missing.length > 0) problems.push(`step${missing.length === 1 ? "" : "s"} ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} in no task: every step belongs to exactly one`);
96
- return [...new Set(problems)];
97
- }
98
-
99
- /** `1-3, 5` for step numbers. */
100
- export function rangeWords(numbers: readonly number[]): string {
101
- const parts: string[] = [];
102
- for (let index = 0; index < numbers.length; ) {
103
- let end = index;
104
- while (end + 1 < numbers.length && numbers[end + 1] === numbers[end]! + 1) end += 1;
105
- parts.push(end > index ? `${numbers[index]}-${numbers[end]}` : String(numbers[index]));
106
- index = end + 1;
107
- }
108
- return parts.join(", ");
109
- }
110
-
111
- /** What the oracle is asked: the plan, its steps as numbered here, and, on a revision, the split so far with what the user wants changed. */
112
- export function splitRequest(input: { title: string; plan: string; steps: readonly string[]; max?: number; revision?: { previous: SplitProposal; words: string }; rejected?: readonly string[] }): string {
113
- const max = input.max ?? MAX_SPLIT_TASKS;
114
- const lines = [
115
- `Split this plan into 2 to ${max} tasks: ${input.title}`,
116
- "",
117
- `The plan has ${input.steps.length} steps. They are numbered here in the order of its Steps section; use these numbers in Covers.`,
118
- ...input.steps.map((step, index) => `${index + 1}. ${step.replace(/\s+/g, " ").trim()}`),
119
- "",
120
- "## The plan",
121
- "",
122
- input.plan.trim(),
123
- ];
124
- if (input.revision) {
125
- lines.push("", "## The split so far", "", proposalText(input.revision.previous), "", `## What the user wants changed`, "", input.revision.words.trim(), "", "Apply exactly that and keep the rest of the split as it is.");
126
- }
127
- if (input.rejected && input.rejected.length > 0) {
128
- lines.push("", "## Your last split was rejected", "", ...input.rejected.map((problem) => `- ${problem}`), "", "Answer again in the required format with a split that breaks none of these.");
129
- }
130
- return lines.join("\n");
131
- }
132
-
133
- /** A proposal as the oracle's own format, so a revision starts from what it (and the user) saw. */
134
- export function proposalText(proposal: SplitProposal): string {
135
- return [
136
- "## Tasks",
137
- ...proposal.tasks.flatMap((task, index) => [
138
- `### ${index + 1}. ${task.title}`,
139
- `Goal: ${task.goal}`,
140
- `Covers: ${rangeWords(task.covers)}`,
141
- `After: ${task.after.length > 0 ? rangeWords(task.after) : "none"}`,
142
- ...(task.done.length > 0 ? ["Done when:", ...task.done.map((point) => `- ${point}`)] : []),
143
- "",
144
- ]),
145
- ...(proposal.note ? ["## Note", proposal.note] : []),
146
- ].join("\n").trimEnd();
147
- }
148
-
149
- /** Markdown for the questionnaire's preview: each task with the steps it takes. */
150
- export function splitPreview(proposal: SplitProposal, steps: readonly string[]): string {
151
- const clip = (text: string) => {
152
- const flat = text.replace(/\s+/g, " ").trim();
153
- return flat.length > 110 ? `${flat.slice(0, 109)}…` : flat;
154
- };
155
- return proposal.tasks.map((task, index) => [
156
- `**${index + 1}. ${task.title}** · step${task.covers.length === 1 ? "" : "s"} ${rangeWords(task.covers)}${task.after.length > 0 ? ` · after ${rangeWords(task.after)}` : ""}`,
157
- ...(task.goal ? [`_${clip(task.goal)}_`] : []),
158
- ...task.covers.map((step) => `- ${step}. ${clip(steps[step - 1] ?? "")}`),
159
- ].join("\n")).join("\n\n");
160
- }
161
-
162
- /** The question the user answers: take the split, keep the plan whole, or write what to change. */
163
- export function splitQuestion(input: { stepCount: number; proposal: SplitProposal; steps: readonly string[]; revisions: number }): AskQuestion {
164
- const count = input.proposal.tasks.length;
165
- const last = input.revisions >= MAX_SPLIT_REVISIONS;
166
- return {
167
- header: "Split plan",
168
- question: [
169
- `This plan has **${input.stepCount} steps**. The oracle suggests splitting it into **${count} tasks**, each finished and reviewed on its own.`,
170
- ...(input.proposal.note ? [input.proposal.note] : []),
171
- last ? "This is the last revision: take it, or keep the plan whole." : "Type what to change (for example *merge 2 and 3*) to revise it.",
172
- ].join("\n\n"),
173
- options: [
174
- { label: splitLabel(count), description: "Each part is saved as its own pending task, in order, knowing the others.", preview: splitPreview(input.proposal, input.steps) },
175
- { label: "Keep it as one task", description: `One task with all ${input.stepCount} steps.` },
176
- ],
177
- };
178
- }
179
-
180
- export const KEEP_WHOLE = "Keep it as one task";
181
-
182
- export function splitLabel(count: number): string {
183
- return `Split into ${count} tasks`;
184
- }
185
-
186
- /** Ask whether to save a plan as one task after the oracle could not split it. */
187
- export function splitFailedQuestion(reason: string): AskQuestion {
188
- return {
189
- header: "Split plan",
190
- question: `The oracle could not split this plan (${reason.replace(/\s+/g, " ").trim()}). Save it as one task?`,
191
- options: [
192
- { label: "Save it as one task", description: "All the steps in one pending task." },
193
- { label: "Not now", description: "Save nothing; ctrl+s asks again." },
194
- ],
195
- };
196
- }
197
-
198
- /** The original plan with its Steps section holding only `covers` (renumbered); undefined when the plan's steps are not a list. */
199
- function planWithSteps(plan: string, covers: readonly number[], stepCount: number): string | undefined {
200
- const found = planStepBlocks(plan);
201
- if (!found || found.blocks.length !== stepCount) return undefined;
202
- const lines = plan.split("\n");
203
- const kept = covers.map((step, index) => found.blocks[step - 1]!.replace(/^(\s*)\d+([.)])/, (_all, indent: string, mark: string) => `${indent}${index + 1}${mark}`));
204
- const spacer = found.to > found.from && !(lines[found.to - 1] ?? "").trim() ? [""] : [];
205
- return [...lines.slice(0, found.from), ...kept.flatMap((block) => block.split("\n")), ...spacer, ...stepDetails(lines.slice(found.to), covers)].join("\n");
206
- }
207
-
208
- /** `### Step 3: …` (or `**Step 3 — …**`): the heading of one step's detail. */
209
- const DETAIL_HEADING = /^(\s*(?:#{1,6}\s+)?(?:\*\*)?\s*step\s+#?)(\d+)(?!\d)/i;
210
- const ANY_HEADING = /^\s*(?:(#{1,6})\s+\S.*|\*\*[^*]+\*\*.*)$/;
211
-
212
- /** A heading's depth: `#` is 1, a bold line deeper than any `#`. */
213
- const depth = (line: string): number => ANY_HEADING.exec(line)?.[1]?.length ?? 7;
214
-
215
- /**
216
- * The lines after a plan's steps list with only the detail of the steps in `covers`, renumbered as
217
- * the list was: a step's detail runs from its `Step N` heading to the next heading as deep or deeper.
218
- */
219
- function stepDetails(lines: readonly string[], covers: readonly number[]): string[] {
220
- const out: string[] = [];
221
- let skipping: number | undefined;
222
- for (const line of lines) {
223
- const heading = ANY_HEADING.test(line) ? depth(line) : undefined;
224
- if (skipping !== undefined && heading !== undefined && heading <= skipping) skipping = undefined;
225
- const detail = heading !== undefined ? DETAIL_HEADING.exec(line) : null;
226
- if (detail) {
227
- const at = covers.indexOf(Number(detail[2]));
228
- if (at < 0) {
229
- skipping = heading;
230
- continue;
231
- }
232
- out.push(line.replace(DETAIL_HEADING, (_all, lead: string) => `${lead}${at + 1}`));
233
- continue;
234
- }
235
- if (skipping === undefined) out.push(line);
236
- }
237
- return out;
238
- }
239
-
240
- /** One part's brief: where it sits, what it delivers, then the plan as written with only its own steps. */
241
- export function partBrief(input: { plan: string; steps: readonly string[]; proposal: SplitProposal; index: number }): string {
242
- const { proposal, index } = input;
243
- const task = proposal.tasks[index]!;
244
- const of = proposal.tasks.length;
245
- const head = [
246
- `### Part ${index + 1} of ${of} — ${task.title}`,
247
- ...(task.goal ? [`**Goal of this part:** ${task.goal}`] : []),
248
- ...(task.after.length > 0 ? [`**Builds on:** ${task.after.map((part) => `part ${part} — ${proposal.tasks[part - 1]?.title ?? ""}`).join("; ")} (finish that first).`] : []),
249
- ...(task.done.length > 0 ? ["**Done when:**", ...task.done.map((point) => `- ${point}`)] : []),
250
- ].join("\n");
251
- const own = planWithSteps(input.plan, task.covers, input.steps.length);
252
- if (own) return `${head}\n\n${own.trim()}`;
253
- // Steps that are not a list: the whole plan, with this part's steps named on top.
254
- const named = task.covers.map((step, position) => `${position + 1}. ${(input.steps[step - 1] ?? "").replace(/\s+/g, " ").trim()}`);
255
- return `${head}\n\n**Steps of this part (do only these; the plan below is the whole plan, for context):**\n${named.join("\n")}\n\n${input.plan.trim()}`;
256
- }
257
-
258
- /** What each saved part knows of the others. */
259
- export function partInfo(proposal: SplitProposal, index: number, group: string): SplitInfo {
260
- const task = proposal.tasks[index]!;
261
- return { group, part: index + 1, of: proposal.tasks.length, titles: proposal.tasks.map((entry) => entry.title), after: [...task.after] };
262
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * The goal check: before a task is called done, one read-only agent with a
3
- * clean context compares the change with what the user actually asked for
4
- * (the request and its amendments, not the plan) and names any requirement
5
- * the change does not meet. Plans drift and agents can finish every step and
6
- * still miss the point; this catches it at the one moment it is cheap to fix.
7
- */
8
- import type { AgentRun } from "../schemas/findings.ts";
9
- import type { BotLobbyConfig, ProfileResolver } from "../schemas/configuration.ts";
10
- import { profileFor } from "../schemas/configuration.ts";
11
- import { runAgent, watchdogOptions } from "../execution/agent-runner.ts";
12
- import { spawnPiProcess, type ProcessRunner } from "../execution/pi-runner.ts";
13
- import { loadPrompt } from "../prompts/loader.ts";
14
- import { truncate } from "../text.ts";
15
-
16
- export type GoalVerdict = "met" | "not_met" | "unread";
17
-
18
- export interface GoalCheckResult {
19
- verdict: GoalVerdict;
20
- /** Requirements the change does not meet, one line each. */
21
- gaps: string[];
22
- run: AgentRun;
23
- }
24
-
25
- export interface GoalCheckRequest {
26
- taskId: string;
27
- /** The user's request as they wrote it. */
28
- request: string;
29
- amendments: readonly string[];
30
- diff: string;
31
- cwd: string;
32
- config: BotLobbyConfig;
33
- profile?: ProfileResolver;
34
- signal?: AbortSignal;
35
- onUpdate?: (run: AgentRun) => void;
36
- }
37
-
38
- /** Most of the change it reads; a longer diff is cut, and the check reads the files it needs. */
39
- export const GOAL_DIFF_CHARS = 60_000;
40
-
41
- function section(text: string, title: string): string {
42
- const match = new RegExp(`^#{1,3}\\s+${title}\\s*:?\\s*$([\\s\\S]*?)(?=^#{1,3}\\s|(?![\\s\\S]))`, "im").exec(text);
43
- return match?.[1]?.trim() ?? "";
44
- }
45
-
46
- /** The verdict as written: on the heading line (`## Verdict: MET`, `**Verdict:** MET`) or the first line under it. */
47
- function verdictLine(text: string): string {
48
- const inline = /^\s*(?:#{1,3}\s*)?\**verdict\**\s*:\**\s*(\S.*)$/im.exec(text);
49
- if (inline?.[1]) return inline[1];
50
- return section(text, "Verdict").split("\n").find((line) => line.trim()) ?? "";
51
- }
52
-
53
- /** Words that make a verdict anything but a plain MET. */
54
- const QUALIFIED = /\b(NOT|UNMET|PARTIAL(LY)?|MOSTLY|LARGELY|EXCEPT|BUT|SOME|INCOMPLETE|FAIL(ED|S)?)\b/;
55
-
56
- /**
57
- * The verdict and gaps from a goal check's report; `unread` when it has no
58
- * verdict. Only a plain MET is met: a qualified one (`NOT MET`, `NOT-MET`,
59
- * `PARTIALLY MET`, `MET except …`) is not, and neither is a MET with gaps listed.
60
- */
61
- export function parseGoalCheck(output: string): { verdict: GoalVerdict; gaps: string[] } {
62
- const said = verdictLine(output).toUpperCase().replace(/[*_`]/g, " ").replace(/\s+/g, " ").trim();
63
- const gaps = section(output, "Gaps")
64
- .split("\n")
65
- .map((line) => line.replace(/^\s*[-*]\s*/, "").trim())
66
- .filter((line) => line.length > 0 && !/^\(?none\b[^a-z]*$/i.test(line) && !/^no gaps\.?$/i.test(line));
67
- // The format line copied back (`MET or NOT MET`) says nothing.
68
- if (/\bOR\b/.test(said)) return { verdict: "unread", gaps: [] };
69
- let verdict: GoalVerdict = QUALIFIED.test(said) || /NOT[-_ ]?MET|UNMET/.test(said) ? "not_met" : /^MET\b/.test(said) ? "met" : "unread";
70
- if (verdict === "met" && gaps.length > 0) verdict = "not_met";
71
- // A NOT MET without any gap named is still a gap: point at the requirements list.
72
- if (verdict === "not_met" && gaps.length === 0) {
73
- const unmet = section(output, "Requirements").split("\n").filter((line) => /—\s*(not|partly|partially) met\s*—/i.test(line)).map((line) => line.replace(/^\s*[-*]\s*/, "").trim());
74
- return { verdict, gaps: unmet.length > 0 ? unmet : [`the goal check found the request not fully met (${truncate(said, 120)}) but named no gap`] };
75
- }
76
- return { verdict, gaps: verdict === "met" ? [] : gaps };
77
- }
78
-
79
- export function goalCheckInstruction(request: GoalCheckRequest): string {
80
- return [
81
- "Check this change against what the user asked for.",
82
- `## The user's request\n\n${request.request.trim()}`,
83
- request.amendments.length > 0 ? `## The user's amendments\n\n${request.amendments.map((entry) => `- ${entry}`).join("\n")}` : "",
84
- `## The change\n\n${truncate(request.diff, GOAL_DIFF_CHARS)}`,
85
- ].filter(Boolean).join("\n\n");
86
- }
87
-
88
- /** The goal check's prompt, with the QA settings' own instructions when the user gave any. */
89
- export function goalCheckPrompt(instructions?: string): string {
90
- const custom = instructions?.trim();
91
- return custom ? `${loadPrompt("goal-check.md")}\n\n## Custom Instructions\n\n${custom}` : loadPrompt("goal-check.md");
92
- }
93
-
94
- export async function runGoalCheck(request: GoalCheckRequest, run: ProcessRunner = spawnPiProcess): Promise<GoalCheckResult> {
95
- // The QA settings' model reads the change: the same reader the gate trusts, on a much smaller job.
96
- const profile = profileFor(request.config, request.profile, "qa", "reviewer");
97
- const agentRun = await runAgent({
98
- taskId: request.taskId,
99
- domain: "qa",
100
- role: "reviewer",
101
- instruction: goalCheckInstruction(request),
102
- context: { task: request.request },
103
- systemPrompt: goalCheckPrompt(profile.instructions),
104
- mcpTools: profile.mcpTools,
105
- ...(profile.model ? { model: profile.model } : {}),
106
- thinking: profile.thinking,
107
- cwd: request.cwd,
108
- ...(request.signal ? { signal: request.signal } : {}),
109
- ...(request.onUpdate ? { onUpdate: (update: AgentRun) => request.onUpdate!({ ...update, note: update.note ?? "goal check" }) } : {}),
110
- ...watchdogOptions(request.config.workflow),
111
- retries: 0,
112
- }, run);
113
- if (agentRun.status !== "success") return { verdict: "unread", gaps: [], run: agentRun };
114
- return { ...parseGoalCheck(agentRun.output), run: agentRun };
115
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * A failed `gh` read as an HTTP refusal. `gh` owns authentication and the
3
- * repository, and its failures arrive as one readable line (`ghError`): a
4
- * number it cannot find is 404, anything else (not installed, not signed in,
5
- * no GitHub remote, a timeout) is a 500 carrying that line. No token or
6
- * command line is ever in the message.
7
- */
8
- import { fail } from "./index.ts";
9
-
10
- const UNKNOWN_NUMBER = /could not resolve|no (pull request|issue)s? found|not found/i;
11
-
12
- /** Refuse with `gh`'s own words (`what` names the read when it left none). */
13
- export function ghRefusal(message: string | undefined, what: string): never {
14
- const text = message ?? `could not read ${what}`;
15
- if (UNKNOWN_NUMBER.test(text)) fail(404, "not_found", text);
16
- fail(500, "failed", text);
17
- }
@@ -1,98 +0,0 @@
1
- /**
2
- * The Git tab over HTTP: the open pull requests with their checks, size and
3
- * review marks; one pull request with its files and discussion, our review
4
- * and Jev's read; starting and stopping a review; asking Jev. Everything goes
5
- * through the lobby's `PullsState` and `PullReviews`, so the terminal and the
6
- * page see one set of reviews. Nothing is ever posted to GitHub.
7
- *
8
- * Only types come from `src/lobby/pulls.ts` and `pr-review.ts` (erased at
9
- * compile time): the review module loads the agent runner, and the server
10
- * needs none of it.
11
- */
12
- import type { PullDetail, PullSummary } from "../../lobby/pulls.ts";
13
- import type { PullReadState, PullReview } from "../../lobby/pr-review.ts";
14
- import type { GitPull, GitPulls, PullInfo, PullReadInfo, PullReviewInfo, PullReviewMark } from "../protocol.ts";
15
- import type { ApiContext } from "./index.ts";
16
- import { ghRefusal } from "./gh-error.ts";
17
-
18
- /** The pull request has commits the review did not see (mirrors `isStale`). */
19
- function staleOf(review: PullReview, headSha: string | undefined): boolean {
20
- return Boolean(review.headSha && headSha && review.headSha !== headSha);
21
- }
22
-
23
- function markOf(review: PullReview | undefined, headSha: string | undefined): PullReviewMark | undefined {
24
- if (!review) return undefined;
25
- return { status: review.status, ...(review.verdict ? { verdict: review.verdict } : {}), stale: staleOf(review, headSha) };
26
- }
27
-
28
- function pullInfo(pull: PullSummary, review: PullReview | undefined): PullInfo {
29
- const { headSha, ...rest } = pull;
30
- const mark = markOf(review, headSha);
31
- return { ...rest, labels: [...rest.labels], ...(mark ? { review: mark } : {}) };
32
- }
33
-
34
- function reviewInfo(review: PullReview, headSha: string | undefined): PullReviewInfo {
35
- const { headSha: _seen, ...rest } = review;
36
- return { ...rest, steps: [...rest.steps], stale: staleOf(review, headSha) };
37
- }
38
-
39
- function readInfo(state: PullReadState): PullReadInfo {
40
- return { ...state, ...(state.read ? { read: { ...state.read } } : {}) };
41
- }
42
-
43
- /** The open pull requests; read from `gh` the first time or when `refresh` asks (a failure is not retried until asked). */
44
- export async function gitPulls(body: { refresh?: boolean }, ctx: ApiContext): Promise<GitPulls> {
45
- const state = ctx.service.pulls;
46
- if (body.refresh || (!state.loaded && !state.error)) {
47
- state.forget();
48
- await state.refresh();
49
- }
50
- const pulls = state.pulls.map((pull) => pullInfo(pull, ctx.service.reviews.review(pull.number)));
51
- return { pulls, loading: state.loading, loaded: state.loaded, ...(state.error ? { error: state.error } : {}) };
52
- }
53
-
54
- /** One pull request with its files, description, reviews and comments, our review and Jev's read. */
55
- export async function gitPull(body: { number: number }, ctx: ApiContext): Promise<GitPull> {
56
- const detail: PullDetail | undefined = await ctx.service.pulls.detail(body.number);
57
- if (!detail) ghRefusal(ctx.service.pulls.error, `#${body.number}`);
58
- const { body: text, state, mergeable, files, notes, ...summary } = detail!;
59
- const review = ctx.service.reviews.review(body.number);
60
- const read = ctx.service.reviews.reads.get(body.number);
61
- return {
62
- pull: {
63
- ...pullInfo(summary, review),
64
- body: text,
65
- ...(state ? { state } : {}),
66
- ...(mergeable ? { mergeable } : {}),
67
- files: files.map((file) => ({ ...file })),
68
- notes: notes.map((note) => ({ ...note })),
69
- },
70
- ...(review ? { review: reviewInfo(review, detail!.headSha) } : {}),
71
- ...(read ? { read: readInfo(read) } : {}),
72
- };
73
- }
74
-
75
- /** Start a review by a read-only agent; it runs on, streaming into the activity log. */
76
- export function gitReview(body: { number: number; focus?: string }, ctx: ApiContext): { notice: string } {
77
- const { reviews, pulls } = ctx.service;
78
- const number = body.number;
79
- if (reviews.running(number)) return { notice: `already reviewing #${number}` };
80
- const focus = body.focus?.trim();
81
- const detail = pulls.details.get(number);
82
- reviews.start(number, { ...(focus ? { focus } : {}), ...(detail ? { detail } : {}) }).catch(() => undefined);
83
- return { notice: `reviewing #${number}${focus ? ` — looking at: ${focus.length > 40 ? `${focus.slice(0, 39)}…` : focus}` : ""} — it streams into the activity log` };
84
- }
85
-
86
- /** Stop a running review. */
87
- export function gitCancelReview(body: { number: number }, ctx: ApiContext): { notice: string } {
88
- const stopped = ctx.service.reviews.cancel(body.number);
89
- return { notice: stopped ? `stopping the review of #${body.number}` : `no review of #${body.number} is running` };
90
- }
91
-
92
- /** Ask Jev for a quick read; the answer arrives with `git.pull`. */
93
- export function gitJev(body: { number: number }, ctx: ApiContext): { notice: string } {
94
- const { reviews, pulls } = ctx.service;
95
- if (reviews.reads.get(body.number)?.status === "running") return { notice: `Jev is already reading #${body.number}` };
96
- reviews.readWithJev(body.number, pulls.details.get(body.number)).catch(() => undefined);
97
- return { notice: `asking Jev to read #${body.number}…` };
98
- }
@@ -1,50 +0,0 @@
1
- /**
2
- * The Issues tab over HTTP: the open issues, one issue with its comments, and
3
- * filing a new one, all through the lobby's `IssuesState` (so `gh` owns
4
- * authentication and the repository). With `lobby.issues` off every call is
5
- * a 404, like the tab being absent from the terminal.
6
- */
7
- import type { IssueDetailInfo, IssueInfo, IssuesList } from "../protocol.ts";
8
- import type { ApiContext } from "./index.ts";
9
- import { fail } from "./index.ts";
10
- import { ghRefusal } from "./gh-error.ts";
11
-
12
- function requireIssues(ctx: ApiContext): void {
13
- if (!ctx.service.issuesEnabled()) fail(404, "not_found", "issues are off (lobby.issues)");
14
- }
15
-
16
- function issueInfo(issue: IssueInfo): IssueInfo {
17
- return { ...issue, labels: [...issue.labels] };
18
- }
19
-
20
- /** The open issues; read from `gh` the first time or when `refresh` asks (a failure is not retried until asked). */
21
- export async function issuesList(body: { refresh?: boolean }, ctx: ApiContext): Promise<IssuesList> {
22
- requireIssues(ctx);
23
- const state = ctx.service.issues;
24
- if (body.refresh || (!state.loaded && !state.error)) {
25
- state.details.clear();
26
- await state.refresh();
27
- }
28
- return { issues: state.issues.map(issueInfo), loading: state.loading, loaded: state.loaded, ...(state.error ? { error: state.error } : {}) };
29
- }
30
-
31
- /** One issue with its description and comments. */
32
- export async function issuesGet(body: { number: number }, ctx: ApiContext): Promise<{ issue: IssueDetailInfo }> {
33
- requireIssues(ctx);
34
- const detail = await ctx.service.issues.detail(body.number);
35
- if (!detail) ghRefusal(ctx.service.issues.error, `issue #${body.number}`);
36
- const found = detail!;
37
- return { issue: { ...issueInfo(found), body: found.body, ...(found.state ? { state: found.state } : {}), comments: found.comments.map((comment) => ({ ...comment })) } };
38
- }
39
-
40
- /** File an issue: the first line is the title, the rest the body. */
41
- export async function issuesCreate(body: { text: string }, ctx: ApiContext): Promise<{ notice: string }> {
42
- requireIssues(ctx);
43
- if (!body.text.trim()) return { notice: "type something first" };
44
- const state = ctx.service.issues;
45
- state.notice = undefined;
46
- state.error = undefined;
47
- await state.create(body.text);
48
- if (!state.notice) fail(500, "failed", state.error ?? "could not file the issue");
49
- return { notice: state.notice! };
50
- }