@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
@@ -0,0 +1,394 @@
1
+ /**
2
+ * The design record: the visual choices a project has settled (spacing,
3
+ * radius, borders, shadows, hover and press, motion), kept in the Designer's
4
+ * `design-language.md` under `## Design record` so the user edits it in the
5
+ * Knowledge tab like any other entry. A choice is the user's (answered while
6
+ * planning), or an agent's (made during a task where nothing was recorded,
7
+ * for the user to overrule). What the code already settles (its tokens, or
8
+ * the utility classes it uses most) is read from the code each time, never
9
+ * copied in, so it cannot go stale. Planning asks only about the fields
10
+ * neither settles; tasks never ask.
11
+ */
12
+ import { readdirSync, readFileSync, statSync } from "node:fs";
13
+ import { join, relative } from "node:path";
14
+ import { knowledgeDir } from "./paths.ts";
15
+ import { DEFAULT_KNOWLEDGE_CONTENT, readFileOr, writeFileEnsured } from "./store.ts";
16
+
17
+ export type DesignField = "spacing" | "radius" | "borders" | "shadows" | "hover" | "motion";
18
+
19
+ interface FieldOption {
20
+ label: string;
21
+ description: string;
22
+ /** The preview's CSS for this option, applied to the shared sample. */
23
+ css: string;
24
+ }
25
+
26
+ interface FieldSpec {
27
+ label: string;
28
+ question: string;
29
+ options: FieldOption[];
30
+ }
31
+
32
+ /** Each field: how it reads in the record, the question planning asks, and its options. */
33
+ export const DESIGN_FIELDS: Record<DesignField, FieldSpec> = {
34
+ spacing: {
35
+ label: "Spacing and padding",
36
+ question: "How roomy should spacing and padding be?",
37
+ options: [
38
+ { label: "Compact", description: "tight padding (8px cards, 4px gaps), more on screen", css: ".card{padding:8px;gap:4px}.row{gap:6px}" },
39
+ { label: "Comfortable", description: "medium padding (16px cards, 8px gaps)", css: ".card{padding:16px;gap:8px}.row{gap:10px}" },
40
+ { label: "Roomy", description: "generous padding (24px cards, 16px gaps), calmer", css: ".card{padding:28px;gap:16px}.row{gap:14px}" },
41
+ ],
42
+ },
43
+ radius: {
44
+ label: "Corner radius",
45
+ question: "How rounded should corners be?",
46
+ options: [
47
+ { label: "Sharp", description: "0 to 2px corners", css: ".card,.btn,.field{border-radius:2px}" },
48
+ { label: "Soft", description: "6 to 8px corners", css: ".card{border-radius:10px}.btn,.field{border-radius:7px}" },
49
+ { label: "Round", description: "12 to 16px corners", css: ".card{border-radius:18px}.btn,.field{border-radius:12px}" },
50
+ { label: "Pill", description: "fully rounded buttons and fields, 16px cards", css: ".card{border-radius:18px}.btn,.field{border-radius:999px}" },
51
+ ],
52
+ },
53
+ borders: {
54
+ label: "Borders",
55
+ question: "How should surfaces be separated?",
56
+ options: [
57
+ { label: "No borders", description: "surfaces separated by background tone only", css: ".card,.field{border:0}.card{background:#f1f2f5}.field{background:#fff}" },
58
+ { label: "Hairline", description: "1px low-contrast borders", css: ".card,.field{border:1px solid #e3e5ea}" },
59
+ { label: "Visible", description: "1px clearly visible borders", css: ".card,.field{border:1px solid #9aa0ab}" },
60
+ ],
61
+ },
62
+ shadows: {
63
+ label: "Shadows and depth",
64
+ question: "How much depth should surfaces have?",
65
+ options: [
66
+ { label: "Flat", description: "no shadows", css: ".card{box-shadow:none}" },
67
+ { label: "Soft", description: "a faint shadow under raised surfaces", css: ".card{box-shadow:0 1px 3px rgba(20,24,40,.08),0 1px 2px rgba(20,24,40,.06)}" },
68
+ { label: "Elevated", description: "clear shadows that lift cards and pop-ups", css: ".card{box-shadow:0 10px 30px rgba(20,24,40,.16)}" },
69
+ ],
70
+ },
71
+ hover: {
72
+ label: "Hover and press effects",
73
+ question: "What should buttons and rows do on hover and press?",
74
+ options: [
75
+ { label: "Subtle tint", description: "background darkens slightly; press darkens more", css: ".btn:hover{filter:brightness(.94)}.btn:active{filter:brightness(.86)}" },
76
+ { label: "Lift", description: "rises 1px with a shadow; press sinks back", css: ".btn:hover{transform:translateY(-1px);box-shadow:0 4px 12px rgba(20,24,40,.18)}.btn:active{transform:translateY(0);box-shadow:none}" },
77
+ { label: "Springy", description: "grows a little on hover, squishes on press", css: ".btn{transition:transform .25s cubic-bezier(.34,1.56,.64,1)}.btn:hover{transform:scale(1.04)}.btn:active{transform:scale(.96)}" },
78
+ { label: "None", description: "no hover effect beyond the cursor", css: "" },
79
+ ],
80
+ },
81
+ motion: {
82
+ label: "Motion",
83
+ question: "How should things animate?",
84
+ options: [
85
+ { label: "No motion", description: "changes happen instantly", css: ".btn{transition:none}" },
86
+ { label: "Quick and calm", description: "short fades and slides, about 150ms", css: ".btn{transition:all .15s ease-out}" },
87
+ { label: "Playful springs", description: "springy, iOS-style motion, about 300ms", css: ".btn{transition:all .3s cubic-bezier(.34,1.56,.64,1)}" },
88
+ ],
89
+ },
90
+ };
91
+
92
+ export const DESIGN_FIELD_KEYS = Object.keys(DESIGN_FIELDS) as DesignField[];
93
+
94
+ export const RECORD_HEADING = "## Design record";
95
+ const RECORD_INTRO = "Settled visual choices. Agents follow these and never ask about them again; edit a line to change it.";
96
+
97
+ export interface DesignChoice {
98
+ field: DesignField;
99
+ value: string;
100
+ /** `you` (the user chose it) or `agent` (an agent chose it during a task, for you to overrule). */
101
+ by: "you" | "agent";
102
+ /** The task it was chosen in, for an agent's choice. */
103
+ taskId?: string;
104
+ date?: string;
105
+ }
106
+
107
+ export function designRecordPath(dataRoot: string): string {
108
+ return join(knowledgeDir(dataRoot, "designer"), "design-language.md");
109
+ }
110
+
111
+ export function isDesignField(value: string): value is DesignField {
112
+ return value in DESIGN_FIELDS;
113
+ }
114
+
115
+ /** The field a line names, by its label or key. */
116
+ function fieldOf(name: string): DesignField | undefined {
117
+ const plain = name.trim().toLowerCase();
118
+ return DESIGN_FIELD_KEYS.find((key) => key === plain || DESIGN_FIELDS[key].label.toLowerCase() === plain);
119
+ }
120
+
121
+ const LINE = /^-\s+\*\*(.+?):\*\*\s+(.+?)\s*$/;
122
+ const SOURCE = /\s+_\((you|agent)(?:,\s*([A-Za-z0-9-]+))?(?:,\s*(\d{4}-\d{2}-\d{2}))?\)_$/;
123
+
124
+ /** The section's lines: [start, end) of `design-language.md`, or undefined when it has none. */
125
+ function sectionRange(rows: readonly string[]): [number, number] | undefined {
126
+ const start = rows.findIndex((row) => row.trim() === RECORD_HEADING);
127
+ if (start < 0) return undefined;
128
+ let end = rows.findIndex((row, index) => index > start && /^#{1,2}\s/.test(row));
129
+ if (end < 0) end = rows.length;
130
+ return [start, end];
131
+ }
132
+
133
+ /** The choices recorded in `design-language.md`'s text; a line it cannot read is left out. */
134
+ export function parseDesignRecord(text: string): Map<DesignField, DesignChoice> {
135
+ const rows = text.split("\n");
136
+ const range = sectionRange(rows);
137
+ const choices = new Map<DesignField, DesignChoice>();
138
+ if (!range) return choices;
139
+ for (const row of rows.slice(range[0] + 1, range[1])) {
140
+ const line = LINE.exec(row.trim());
141
+ const field = line ? fieldOf(line[1]!) : undefined;
142
+ if (!line || !field) continue;
143
+ const source = SOURCE.exec(line[2]!);
144
+ const value = (source ? line[2]!.slice(0, source.index) : line[2]!).trim();
145
+ if (!value) continue;
146
+ choices.set(field, {
147
+ field, value, by: (source?.[1] as DesignChoice["by"] | undefined) ?? "you",
148
+ ...(source?.[2] ? { taskId: source[2] } : {}),
149
+ ...(source?.[3] ? { date: source[3] } : {}),
150
+ });
151
+ }
152
+ return choices;
153
+ }
154
+
155
+ function choiceLine(choice: DesignChoice): string {
156
+ const source = [choice.by, choice.taskId, choice.date].filter(Boolean).join(", ");
157
+ return `- **${DESIGN_FIELDS[choice.field].label}:** ${choice.value.replace(/\s*\n\s*/g, " ")} _(${source})_`;
158
+ }
159
+
160
+ /**
161
+ * `design-language.md`'s text with these choices set: a field already
162
+ * recorded is replaced in place, a new one is added in the fields' order, and
163
+ * the section is added at the end when the file has none. Everything
164
+ * else in the file stays as it is.
165
+ */
166
+ export function withDesignChoices(text: string, choices: readonly DesignChoice[]): string {
167
+ const rows = (text.trim() ? text : DEFAULT_KNOWLEDGE_CONTENT["design-language.md"]!).replace(/\n+$/, "").split("\n");
168
+ let range = sectionRange(rows);
169
+ if (!range) {
170
+ rows.push("", RECORD_HEADING, "", RECORD_INTRO);
171
+ range = sectionRange(rows)!;
172
+ }
173
+ const merged = parseDesignRecord(rows.join("\n"));
174
+ for (const choice of choices) merged.set(choice.field, choice);
175
+ const body = rows.slice(range[0] + 1, range[1]).filter((row) => {
176
+ const line = LINE.exec(row.trim());
177
+ return !(line && fieldOf(line[1]!));
178
+ });
179
+ while (body.length > 0 && body.at(-1)!.trim() === "") body.pop();
180
+ const lines = DESIGN_FIELD_KEYS.filter((field) => merged.has(field)).map((field) => choiceLine(merged.get(field)!));
181
+ const section = [RECORD_HEADING, ...(body.length > 0 ? body : ["", RECORD_INTRO]), "", ...lines, ""];
182
+ return [...rows.slice(0, range[0]), ...section, ...rows.slice(range[1])].join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
183
+ }
184
+
185
+ export function readDesignRecord(dataRoot: string): Map<DesignField, DesignChoice> {
186
+ return parseDesignRecord(readFileOr(designRecordPath(dataRoot)));
187
+ }
188
+
189
+ /** Record choices in the project's design record; returns the file written. */
190
+ export function recordDesignChoices(dataRoot: string, choices: readonly DesignChoice[]): string {
191
+ const path = designRecordPath(dataRoot);
192
+ if (choices.length > 0) writeFileEnsured(path, withDesignChoices(readFileOr(path), choices));
193
+ return path;
194
+ }
195
+
196
+ /** `design-language.md` without its record section: the rest of the Designer's standards. */
197
+ export function withoutDesignRecord(text: string): string {
198
+ const rows = text.split("\n");
199
+ const range = sectionRange(rows);
200
+ return range ? [...rows.slice(0, range[0]), ...rows.slice(range[1])].join("\n") : text;
201
+ }
202
+
203
+ /** The value a chosen option stands for: its label and what it means, or the user's own words. */
204
+ export function choiceValue(field: DesignField, answer: string): string {
205
+ const text = answer.trim();
206
+ const option = DESIGN_FIELDS[field].options.find((entry) => entry.label.toLowerCase() === text.toLowerCase());
207
+ return option ? `${option.label}: ${option.description}` : text;
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // What the code already settles
212
+ // ---------------------------------------------------------------------------
213
+
214
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "out", ".next", ".nuxt", "coverage", "vendor", ".pi", "target", ".venv", "venv", "__pycache__"]);
215
+ const MARKUP = /\.(tsx|jsx|vue|svelte|html|astro)$/;
216
+ const MAX_FILES = 600;
217
+ const MAX_FILE_BYTES = 200_000;
218
+ const MAX_DEPTH = 6;
219
+
220
+ /** Custom properties per field, as `--name: value` in a stylesheet. */
221
+ const TOKEN_PATTERNS: Record<DesignField, RegExp> = {
222
+ spacing: /--[\w-]*(?:spacing|space|gap|gutter|pad)[\w-]*/,
223
+ radius: /--[\w-]*radius[\w-]*/,
224
+ borders: /--[\w-]*border[\w-]*/,
225
+ shadows: /--[\w-]*shadow[\w-]*/,
226
+ hover: /--[\w-]*hover[\w-]*/,
227
+ motion: /--[\w-]*(?:duration|ease|easing|transition|motion|spring)[\w-]*/,
228
+ };
229
+
230
+ /** Utility classes per field, counted in markup (Tailwind and lookalikes). */
231
+ const CLASS_PATTERNS: Record<DesignField, RegExp> = {
232
+ spacing: /(?<![\w:-])(?:p[xytrbl]?|gap(?:-[xy])?|space-[xy])-(\d+(?:\.5)?)(?![\w-])/g,
233
+ radius: /(?<![\w:-])rounded(?:-(?:none|sm|md|lg|xl|2xl|3xl|full))?(?![\w-])/g,
234
+ borders: /(?<![\w:-])border(?:-(?:0|2|4|8))?(?![\w-])/g,
235
+ shadows: /(?<![\w:-])shadow(?:-(?:none|sm|md|lg|xl|2xl|inner))?(?![\w-])/g,
236
+ hover: /(?<![\w-])(?:hover|active):[\w/.[\]-]+/g,
237
+ motion: /(?<![\w:-])(?:transition(?:-[a-z]+)?|duration-\d+|animate-[a-z-]+)(?![\w-])/g,
238
+ };
239
+
240
+ interface CodeStyle {
241
+ /** Stylesheets with tokens, relative to the project. */
242
+ sheets: string[];
243
+ tokens: Map<DesignField, string[]>;
244
+ classes: Map<DesignField, Map<string, number>>;
245
+ hoverRules: number;
246
+ }
247
+
248
+ function walk(root: string, visit: (path: string) => void): void {
249
+ let seen = 0;
250
+ const step = (dir: string, depth: number) => {
251
+ if (depth > MAX_DEPTH || seen >= MAX_FILES) return;
252
+ let names: string[];
253
+ try {
254
+ names = readdirSync(dir).sort();
255
+ } catch {
256
+ return;
257
+ }
258
+ for (const name of names) {
259
+ if (seen >= MAX_FILES) return;
260
+ if (name.startsWith(".") && name !== ".storybook") continue;
261
+ const path = join(dir, name);
262
+ let stat;
263
+ try {
264
+ stat = statSync(path);
265
+ } catch {
266
+ continue;
267
+ }
268
+ if (stat.isDirectory()) {
269
+ if (!SKIP_DIRS.has(name)) step(path, depth + 1);
270
+ } else if ((name.endsWith(".css") || MARKUP.test(name)) && stat.size <= MAX_FILE_BYTES) {
271
+ seen += 1;
272
+ visit(path);
273
+ }
274
+ }
275
+ };
276
+ step(root, 0);
277
+ }
278
+
279
+ /** Read the project's stylesheets and markup for what they already settle. */
280
+ export function readCodeStyle(projectRoot: string): CodeStyle {
281
+ const style: CodeStyle = { sheets: [], tokens: new Map(), classes: new Map(), hoverRules: 0 };
282
+ walk(projectRoot, (path) => {
283
+ let text: string;
284
+ try {
285
+ text = readFileSync(path, "utf8");
286
+ } catch {
287
+ return;
288
+ }
289
+ if (path.endsWith(".css")) {
290
+ let found = false;
291
+ for (const match of text.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)(?=[;}])/g)) {
292
+ const [, name, value] = match;
293
+ const field = DESIGN_FIELD_KEYS.find((key) => TOKEN_PATTERNS[key].test(name!));
294
+ if (!field) continue;
295
+ const list = style.tokens.get(field) ?? [];
296
+ if (list.length < 6 && !list.some((entry) => entry.startsWith(`${name}:`))) list.push(`${name}: ${value!.trim().slice(0, 60)}`);
297
+ style.tokens.set(field, list);
298
+ found = true;
299
+ }
300
+ style.hoverRules += (text.match(/:hover\b/g) ?? []).length;
301
+ if (found && style.sheets.length < 6) style.sheets.push(relative(projectRoot, path));
302
+ return;
303
+ }
304
+ for (const field of DESIGN_FIELD_KEYS) {
305
+ const counts = style.classes.get(field) ?? new Map<string, number>();
306
+ for (const match of text.matchAll(CLASS_PATTERNS[field])) counts.set(match[0], (counts.get(match[0]) ?? 0) + 1);
307
+ style.classes.set(field, counts);
308
+ }
309
+ });
310
+ return style;
311
+ }
312
+
313
+ /** Fewer uses than this and the classes do not say what the project does. */
314
+ const MIN_CLASS_USES = 5;
315
+
316
+ /** What the code says about a field, in a line; undefined when it says nothing. */
317
+ function codeSays(style: CodeStyle, field: DesignField): string | undefined {
318
+ const tokens = style.tokens.get(field) ?? [];
319
+ const counts = [...(style.classes.get(field) ?? new Map<string, number>())].sort((a, b) => b[1] - a[1]);
320
+ const uses = counts.reduce((sum, [, count]) => sum + count, 0);
321
+ const parts: string[] = [];
322
+ if (tokens.length > 0) parts.push(`tokens ${tokens.join(", ")}`);
323
+ if (uses >= MIN_CLASS_USES) parts.push(`most used ${counts.slice(0, 4).map(([name, count]) => `${name} (${count}×)`).join(", ")}`);
324
+ if (field === "hover" && style.hoverRules >= 3) parts.push(`${style.hoverRules} :hover rules in the stylesheets`);
325
+ return parts.length > 0 ? parts.join("; ") : undefined;
326
+ }
327
+
328
+ export interface DesignStanding {
329
+ recorded: Map<DesignField, DesignChoice>;
330
+ /** What the code settles, per field it says something about. */
331
+ fromCode: Map<DesignField, string>;
332
+ sheets: string[];
333
+ /** Fields neither the record nor the code settles: the only ones planning may ask about. */
334
+ gaps: DesignField[];
335
+ }
336
+
337
+ export function designStanding(dataRoot: string, projectRoot: string): DesignStanding {
338
+ const recorded = readDesignRecord(dataRoot);
339
+ const style = readCodeStyle(projectRoot);
340
+ const fromCode = new Map<DesignField, string>();
341
+ for (const field of DESIGN_FIELD_KEYS) {
342
+ const says = codeSays(style, field);
343
+ if (says) fromCode.set(field, says);
344
+ }
345
+ return { recorded, fromCode, sheets: style.sheets, gaps: DESIGN_FIELD_KEYS.filter((field) => !recorded.has(field) && !fromCode.has(field)) };
346
+ }
347
+
348
+ /** The record as an agent reads it: the settled fields (yours first, then the code's) and the open ones. */
349
+ export function designRecordBlock(standing: DesignStanding, open: "planning" | "task"): string {
350
+ const lines = ["## Design record (settled visual choices: follow them, never ask about them)"];
351
+ for (const field of DESIGN_FIELD_KEYS) {
352
+ const choice = standing.recorded.get(field);
353
+ const code = standing.fromCode.get(field);
354
+ if (choice) lines.push(`- ${DESIGN_FIELDS[field].label}: ${choice.value} (${choice.by === "you" ? "the user chose this" : `an agent chose this${choice.taskId ? ` in ${choice.taskId}` : ""}; the user may overrule it`})`);
355
+ else if (code) lines.push(`- ${DESIGN_FIELDS[field].label}: follow the code — ${code}`);
356
+ }
357
+ if (lines.length === 1) lines.push("- (nothing settled yet)");
358
+ if (standing.sheets.length > 0) lines.push(`Global stylesheets: ${standing.sheets.join(", ")}.`);
359
+ if (standing.gaps.length === 0) return lines.join("\n");
360
+ const open_ = standing.gaps.map((field) => `${field} (${DESIGN_FIELDS[field].label.toLowerCase()})`).join(", ");
361
+ lines.push(open === "planning"
362
+ ? `Not settled yet: ${open_}. If this work changes what the user sees, list the ones it touches under ## Style (their keys, comma-separated); the user is asked those once with fixed options and the answers are recorded. Do not ask them under Questions.`
363
+ : `Not settled yet: ${open_}. Do not ask the user about them. Follow the closest pattern already in the code, and list each value you chose under "Design choices" in your report as \`- <key>: <value>\`, so it is recorded for the user to overrule.`);
364
+ return lines.join("\n");
365
+ }
366
+
367
+ // ---------------------------------------------------------------------------
368
+ // Planning's style questions
369
+ // ---------------------------------------------------------------------------
370
+
371
+ const SAMPLE_CSS = "body{margin:0;font:14px/1.45 system-ui,sans-serif;color:#1d2230;background:#fafbfc}.page{padding:24px;display:flex;justify-content:center;zoom:2.4}.card{display:flex;flex-direction:column;background:#fff;border:1px solid #e3e5ea;border-radius:10px;padding:16px;gap:8px;width:320px}.card h3{margin:0;font-size:15px}.card p{margin:0;color:#5b6170}.field{border:1px solid #d5d8de;border-radius:7px;padding:7px 10px;color:#8a909c;background:#fff}.row{display:flex;gap:10px;justify-content:flex-end}.btn{border:0;border-radius:7px;padding:7px 14px;font:inherit;font-weight:600;cursor:pointer;background:#3b5bdb;color:#fff;transition:all .15s ease-out}.btn.ghost{background:#eceef2;color:#1d2230}";
372
+ const SAMPLE_HTML = '<div class="page"><div class="card"><h3>Invite a teammate</h3><p>They get access to this project.</p><div class="field">name@company.com</div><div class="row"><button class="btn ghost">Cancel</button><button class="btn">Send invite</button></div></div></div>';
373
+
374
+ export interface StyleQuestion {
375
+ text: string;
376
+ record: DesignField;
377
+ options: Array<{ label: string; description: string; mockup: { html: string; css: string } }>;
378
+ }
379
+
380
+ /** The fixed questions for the fields asked about, each option drawn on the same small sample. */
381
+ export function styleQuestions(fields: readonly DesignField[]): StyleQuestion[] {
382
+ return fields.map((field) => ({
383
+ text: DESIGN_FIELDS[field].question,
384
+ record: field,
385
+ options: DESIGN_FIELDS[field].options.map((option) => ({ label: option.label, description: option.description, mockup: { html: SAMPLE_HTML, css: `${SAMPLE_CSS}${option.css}` } })),
386
+ }));
387
+ }
388
+
389
+ /** The field keys a seat listed under `## Style`, in the record's order. */
390
+ export function styleFields(text: string | undefined): DesignField[] {
391
+ if (!text) return [];
392
+ const named = new Set(text.toLowerCase().split(/[\s,;•*-]+/).map((word) => word.trim()).filter(Boolean));
393
+ return DESIGN_FIELD_KEYS.filter((field) => named.has(field));
394
+ }
@@ -8,8 +8,8 @@
8
8
  */
9
9
  import { createHash } from "node:crypto";
10
10
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
- import { readFile, stat } from "node:fs/promises";
12
- import { dirname, isAbsolute, join, relative } from "node:path";
11
+ import { readFile, realpath, stat } from "node:fs/promises";
12
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
13
13
  import type { Domain } from "../schemas/agent.ts";
14
14
  import type { RelevantFile } from "../schemas/findings.ts";
15
15
  import { tempName, withFileLock } from "../desk/lock.ts";
@@ -22,6 +22,8 @@ export interface FileNote {
22
22
  hash: string;
23
23
  domain: Domain;
24
24
  at: string;
25
+ /** File-local provenance, never evidence of callers or repository-wide behavior. */
26
+ provenance?: { kind: "scout"; scope: "file"; usage: "navigation-only" };
25
27
  }
26
28
 
27
29
  interface NotesFile {
@@ -42,7 +44,10 @@ export function fileNotesPath(dataDir: string): string {
42
44
  export function readFileNotes(dataDir: string): Record<string, FileNote> {
43
45
  try {
44
46
  const parsed = JSON.parse(readFileSync(fileNotesPath(dataDir), "utf8")) as Partial<NotesFile>;
45
- return parsed.version === 1 && parsed.files && typeof parsed.files === "object" ? parsed.files : {};
47
+ if (parsed.version !== 1 || !parsed.files || typeof parsed.files !== "object") return {};
48
+ return Object.fromEntries(Object.entries(parsed.files).filter(([, note]) =>
49
+ note && typeof note.note === "string" && typeof note.hash === "string" && typeof note.at === "string",
50
+ ));
46
51
  } catch {
47
52
  return {};
48
53
  }
@@ -63,7 +68,11 @@ function writeFileNotes(dataDir: string, files: Record<string, FileNote>): void
63
68
  /** A file's content hash, or undefined when it is missing, not a file or too large. */
64
69
  export async function contentHash(cwd: string, path: string): Promise<string | undefined> {
65
70
  try {
66
- const full = join(cwd, path);
71
+ const local = treePath(cwd, path);
72
+ if (!local) return undefined;
73
+ const root = await realpath(cwd);
74
+ const full = await realpath(join(root, local));
75
+ if (!treePath(root, full)) return undefined;
67
76
  const info = await stat(full);
68
77
  if (!info.isFile() || info.size > MAX_HASHED_BYTES) return undefined;
69
78
  return createHash("sha1").update(await readFile(full)).digest("hex");
@@ -76,8 +85,8 @@ export async function contentHash(cwd: string, path: string): Promise<string | u
76
85
  export function treePath(cwd: string, path: string): string | undefined {
77
86
  const plain = path.trim().replace(/^\.\//, "");
78
87
  if (!plain) return undefined;
79
- const rel = isAbsolute(plain) ? relative(cwd, plain) : plain;
80
- return !rel || rel.startsWith("..") || isAbsolute(rel) ? undefined : rel.split("\\").join("/");
88
+ const rel = relative(resolve(cwd), resolve(cwd, plain));
89
+ return !rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(rel) ? undefined : rel.split("\\").join("/");
81
90
  }
82
91
 
83
92
  /** Record a scout's Relevant Files as notes, each with its file's current hash; files that are not there are skipped. */
@@ -87,7 +96,7 @@ export async function recordFileNotes(dataDir: string, cwd: string, domain: Doma
87
96
  const hash = path ? await contentHash(cwd, path) : undefined;
88
97
  if (!path || !hash) return undefined;
89
98
  const note = file.reason.trim().replace(/\s+/g, " ").slice(0, MAX_NOTE_CHARS);
90
- return [path, { note, ...(file.lines ? { lines: file.lines } : {}), hash, domain, at: now.toISOString() }];
99
+ return [path, { note, ...(file.lines ? { lines: file.lines } : {}), hash, domain, at: now.toISOString(), provenance: { kind: "scout", scope: "file", usage: "navigation-only" } }];
91
100
  }));
92
101
  const fresh = entries.filter((entry): entry is [string, FileNote] => entry !== undefined);
93
102
  if (fresh.length === 0) return 0;
@@ -105,7 +114,26 @@ export async function recordFileNotes(dataDir: string, cwd: string, domain: Doma
105
114
  }
106
115
  }
107
116
 
108
- /** The notes for `paths` whose file is unchanged since the note was taken. */
117
+ export interface FileNoteHint {
118
+ id: string;
119
+ scope: "file";
120
+ source: string;
121
+ fingerprint: string;
122
+ usage: "navigation-only";
123
+ status: "unverified hints";
124
+ note: FileNote;
125
+ }
126
+
127
+ /** Relevant notes only; callers must validate their source before relying on them. */
128
+ export function fileNoteHints(dataDir: string, paths: readonly string[]): FileNoteHint[] {
129
+ const notes = readFileNotes(dataDir);
130
+ return [...new Set(paths)].flatMap((path) => notes[path] ? [{
131
+ id: `file-note:${path}`, scope: "file" as const, source: path, fingerprint: notes[path]!.hash,
132
+ usage: "navigation-only" as const, status: "unverified hints" as const, note: notes[path]!,
133
+ }] : []);
134
+ }
135
+
136
+ /** The notes for `paths` whose source is unchanged; navigation only, not broad claims. */
109
137
  export async function currentNotes(dataDir: string, cwd: string, paths: readonly string[]): Promise<Map<string, FileNote>> {
110
138
  const notes = readFileNotes(dataDir);
111
139
  const wanted = paths.filter((path) => notes[path]);
package/src/lobby/ask.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * answers become the user's turn for the next round.
8
8
  */
9
9
  import type { PanelQuestion, SettledQuestion } from "./planner.ts";
10
+ import type { DesignField } from "../knowledge/design-record.ts";
10
11
  import { MAX_HEADER, MAX_LABEL, MAX_OPTIONS, MAX_QUESTIONS, MIN_OPTIONS, RESERVED, type AskAnswer, type AskOption, type AskQuestion, type AskResult, type Asker } from "../ask/types.ts";
11
12
 
12
13
  export { MAX_QUESTIONS, MIN_OPTIONS, MAX_OPTIONS, type AskAnswer, type AskOption, type AskQuestion, type AskResult, type Asker };
@@ -93,6 +94,11 @@ export function settledQuestions(questions: readonly PanelQuestion[], results: r
93
94
  return answered(questions, results).map(({ question, text }) => ({ from: question.from, question: question.text.replace(/\s+/g, " ").trim(), ...(text ? { answer: text } : {}) }));
94
95
  }
95
96
 
97
+ /** The style questions the user answered, with the design record field each one settles. */
98
+ export function styleAnswers(questions: readonly PanelQuestion[], results: readonly AskResult[]): Array<{ field: DesignField; answer: string }> {
99
+ return answered(questions, results).flatMap(({ question, text }) => (question.record && text ? [{ field: question.record, answer: text }] : []));
100
+ }
101
+
96
102
  /**
97
103
  * The user's turn for the next round: every question with who asked it and
98
104
  * the answer (`→ …`), their notes, and what they left unanswered. Undefined
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Running a command without a shell (git, gh): the real `execFile`, or a fake
3
+ * in tests.
4
+ */
5
+ import { execFile } from "node:child_process";
6
+
7
+ export interface ExecResult {
8
+ stdout: string;
9
+ stderr: string;
10
+ code: number;
11
+ }
12
+
13
+ /** Runs a command without a shell; `execCommand` in the extension, a fake in tests. */
14
+ export type Exec = (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<ExecResult>;
15
+
16
+ /**
17
+ * `execFile` as an `Exec`: a non-zero exit resolves with its code and output,
18
+ * while a missing binary rejects with the spawn error (`ENOENT`), so a caller
19
+ * can say "gh is not installed" rather than "exited with code 1".
20
+ */
21
+ export const execCommand: Exec = (command, args, options) =>
22
+ new Promise((resolve, reject) => {
23
+ execFile(command, args, { cwd: options?.cwd, timeout: options?.timeout, maxBuffer: 10 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
24
+ if (error && typeof (error as NodeJS.ErrnoException).code === "string") return reject(error);
25
+ const code = error ? (typeof (error as { code?: unknown }).code === "number" ? (error as { code: number }).code : 1) : 0;
26
+ resolve({ stdout: String(stdout), stderr: String(stderr), code });
27
+ });
28
+ });
package/src/lobby/host.ts CHANGED
@@ -13,13 +13,10 @@ import type { ChatEntry, LobbyFeed } from "./feed.ts";
13
13
  import type { BackgroundSession } from "./sessions.ts";
14
14
  import type { PlannerSeed, PlanningSession } from "./planner.ts";
15
15
  import type { PlanRecord, PlanSummary } from "../state/plan-history.ts";
16
- import type { IssuesState } from "./issues.ts";
17
- import type { PullsState } from "./pulls.ts";
18
- import type { PullReviews } from "./pr-review.ts";
19
16
  import type { KnowledgeBook } from "./knowledge.ts";
20
17
  import type { WorkspaceInfo } from "../execution/workspace.ts";
21
18
 
22
- export { TAB_IDS, TAB_LABELS, visibleTabs } from "./prompts.ts";
19
+ export { TAB_IDS, TAB_LABELS } from "./prompts.ts";
23
20
  export type { TabId } from "./prompts.ts";
24
21
 
25
22
  /**
@@ -106,6 +103,7 @@ export interface LobbyService {
106
103
  * to open when it moved somewhere else.
107
104
  */
108
105
  toOracle(text: string): string | { notice: string; open: "plan" } | undefined;
106
+ commands?(): import("./pi-commands.ts").LobbySlashCommand[];
109
107
  /** Answer a project question and learn from the codebase, without creating a task. */
110
108
  askKnowledge(text: string): void;
111
109
  comment(taskId: string, text: string): string;
@@ -137,11 +135,6 @@ export interface LobbyService {
137
135
  planningRounds?(): number;
138
136
  /** `model · thinking` a panel seat runs on. */
139
137
  seatLabel(member: PanelMember): string;
140
- issues: IssuesState;
141
- /** The Git tab's pull requests, read through `gh`. */
142
- pulls: PullsState;
143
- /** Reviews of pull requests by an agent, and Jev's reads of them. */
144
- reviews: PullReviews;
145
138
  /** Every agent's knowledge files: read, edited, commented on. */
146
139
  knowledge: KnowledgeBook;
147
140
  /** The effective config, never a secret; the web settings page reads it. */
@@ -160,8 +153,6 @@ export interface LobbyService {
160
153
  classifierModels?(): Array<{ id: string; label: string }>;
161
154
  /** The model this window's session runs on (`provider/id`), when it has one. */
162
155
  sessionModel?(): string | undefined;
163
- /** Git's Issues view is switched on (`lobby.issues`). */
164
- issuesEnabled(): boolean;
165
156
  /** What this window carried on from one that stopped unexpectedly, when it did. */
166
157
  recovered?(): { at: number; text: string } | undefined;
167
158
  /** This window's pi session name, when it has one. */
@@ -0,0 +1,83 @@
1
+ import type { ExtensionAPI, ExtensionContext, SlashCommandInfo } from "@earendil-works/pi-coding-agent";
2
+ import { pushNotice } from "../webui/notices.ts";
3
+
4
+ export interface LobbySlashCommand {
5
+ name: string;
6
+ description: string;
7
+ terminal?: boolean;
8
+ }
9
+
10
+ // Pi 1.4's native commands are not exported by its public API; getCommands lists only resources.
11
+ const NATIVE_COMMANDS = [
12
+ ["settings", "Open Pi settings"],
13
+ ["model", "Select model"],
14
+ ["tree", "Navigate the session tree"],
15
+ ["thinking", "Set thinking level"],
16
+ ["scoped-models", "Choose models for cycling"],
17
+ ["export", "Export the session as HTML or JSONL"],
18
+ ["import", "Import a JSONL session"],
19
+ ["share", "Share the session"],
20
+ ["bug", "Report a bug to Pi developers"],
21
+ ["copy", "Copy the last agent message"],
22
+ ["name", "Set the session name"],
23
+ ["session", "Show session info and usage"],
24
+ ["changelog", "Show Pi changelog"],
25
+ ["hotkeys", "Show Pi keyboard shortcuts"],
26
+ ["fork", "Fork from a previous message"],
27
+ ["clone", "Duplicate the current session"],
28
+ ["trust", "Save the project trust decision"],
29
+ ["login", "Configure provider authentication"],
30
+ ["logout", "Remove provider authentication"],
31
+ ["new", "Start a new session"],
32
+ ["compact", "Compact the session context"],
33
+ ["resume", "Resume a saved session"],
34
+ ["reload", "Reload extensions, skills, prompts and settings"],
35
+ ["quit", "Quit Pi"],
36
+ ] as const;
37
+
38
+ function resources(pi?: ExtensionAPI): SlashCommandInfo[] {
39
+ try {
40
+ return pi?.getCommands?.() ?? [];
41
+ } catch {
42
+ return [];
43
+ }
44
+ }
45
+
46
+ export function piCommands(pi?: ExtensionAPI): LobbySlashCommand[] {
47
+ const commands = new Map<string, LobbySlashCommand>(NATIVE_COMMANDS.map(([name, description]) => [
48
+ name, { name, description, ...(name === "compact" ? {} : { terminal: true }) },
49
+ ]));
50
+ for (const command of resources(pi)) {
51
+ if (!commands.has(command.name)) commands.set(command.name, { name: command.name, description: command.description ?? "" });
52
+ }
53
+ return [...commands.values()];
54
+ }
55
+
56
+ function compact(ctx: ExtensionContext, instructions: string): string {
57
+ if (!ctx.isIdle()) return "the oracle is working — stop it before compacting";
58
+ ctx.compact({
59
+ ...(instructions ? { customInstructions: instructions } : {}),
60
+ onComplete: () => pushNotice("Session context compacted", "success"),
61
+ onError: (error) => pushNotice(`Context compaction failed — ${error.message}`, "error"),
62
+ });
63
+ return "compacting the session context…";
64
+ }
65
+
66
+ function handoff(ctx: ExtensionContext, text: string): string {
67
+ if (ctx.mode !== "tui") return `${text.split(/\s+/)[0]} requires Pi's terminal UI; this session has no terminal`;
68
+ const draft = ctx.ui.getEditorText();
69
+ if (draft.trim() && draft !== text) return "Pi's terminal has an unfinished draft — clear it before handing off this command";
70
+ ctx.ui.setEditorText(text);
71
+ return `prepared ${text.split(/\s+/)[0]} in Pi — press Enter in Pi's terminal to run it`;
72
+ }
73
+
74
+ export function sendPiCommand(pi: ExtensionAPI, ctx: ExtensionContext, text: string): string {
75
+ const input = text.trim();
76
+ const name = input.slice(1).split(/\s+/)[0]!;
77
+ if (name === "compact") return compact(ctx, input.slice(name.length + 1).trim());
78
+ const command = piCommands(pi).find((entry) => entry.name === name);
79
+ if (command?.terminal) return handoff(ctx, input);
80
+ if (!command && !/^skill:[^\s/]+$/.test(name)) return `unknown Pi command /${name}`;
81
+ pi.sendUserMessage(input, { expandPromptTemplates: true, ...(!ctx.isIdle() ? { deliverAs: "followUp" as const } : {}) });
82
+ return `sent /${name} to pi`;
83
+ }