pi-braid 0.41.2 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,42 +1,151 @@
1
1
  /**
2
- * Skills-loading directive, owned by the skills-tool module.
2
+ * Skills floor, owned by the skills-tool module: the visible catalog section
3
+ * and the drift trigger that re-points at it.
3
4
  *
4
- * The skills-tool module owns the strategy text for using its own tool;
5
- * prompt-builder imports it and renders it as the "skills-loading" section
6
- * ONLY when both `read` and `list_skills` are active tools.
5
+ * prompt-builder imports the section text and renders it as the
6
+ * "skills-loading" section ONLY when both `read` and `list_skills` are active
7
+ * tools.
7
8
  *
8
- * Current rule: task-start list_skills puts the full catalog (name, path,
9
- * purpose) in view so the domain-match trigger is decidable; the catalog
10
- * one-liner is metadata, the SKILL.md path is the knowledge — no skill
11
- * content is injected into the prompt. The trigger has a mechanical form
12
- * (a tool call whose family word appears in a skill's name) because the
13
- * judgment form loses sessions that are inside a skill's domain by
14
- * construction. Decision logic lives in the prompt, mechanics in tool
15
- * descriptions (strategy-only contract; each fact in exactly one place).
9
+ * Why the catalog is rendered instead of described. A pointer the model has
10
+ * to redeem with a tool call is a probability, not a mechanism: the first
11
+ * prompt of a resumed session is thin ("let's pick up where we left off"),
12
+ * the catalog is one call away, and nothing in a thin prompt demands it.
13
+ * Rendering every visible skill as one `- name: description` row removes the
14
+ * redemption step, so a domain match needs only the task text in front of the
15
+ * model, not a decision to go look. The row is metadata; the file is still
16
+ * the knowledge, and the rule below says so.
17
+ *
18
+ * The read path is derived from the entries' own paths, never hardcoded: the
19
+ * same text renders for a checkout, an npm install tree, or a worktree. A
20
+ * catalog installed from more than one pack has no single root, so each
21
+ * directory heads its own group of rows instead of one root being named for
22
+ * all of them (a root that resolves for 22 rows and misdirects the other 5 is
23
+ * worse than no root at all).
16
24
  *
17
25
  * The mechanical trigger's worked examples are derived at assembly time from
18
- * the live tool and skill names (mechanicalTriggerExamples): a tool's family
19
- * token paired with an installed visible skill's dash-token. The text never
20
- * hardcodes a tool or skill name, so it cannot name a pair that does not
21
- * exist in the running session; when no pair computes, the sentence renders
22
- * without a parenthetical.
26
+ * the live tool and skill names: a tool's family token paired with an
27
+ * installed visible skill's dash-token. The text never hardcodes a tool or
28
+ * skill name, so it cannot name a pair that does not exist in the running
29
+ * session; when no pair computes, the sentence renders without a
30
+ * parenthetical.
31
+ *
32
+ * The same module owns the drift trigger (below): work that moves to a new
33
+ * directory is the moment a visible catalog stops matching the task text in
34
+ * view, and the trigger re-points at the catalog with one line. Its state is
35
+ * plain data and its decisions are pure functions, so the wiring lives in
36
+ * auto-inject.ts and the reasoning stays testable here.
23
37
  */
24
38
 
25
- /** Paragraph 1: the discovery rule (pinned verbatim by test-prompt-budget.mjs). */
26
- export const SKILLS_DISCOVERY_RULE = `You discover skills on demand, not in advance: at the start of a task, call list_skills once to see the catalog (name, path, purpose). When the task enters a listed skill's domain, read the WHOLE SKILL.md before acting in that domain; never act from memory of a skill's contents.`;
39
+ import { isAbsolute, relative, resolve, sep } from "node:path";
40
+
41
+ /** One visible skill as the floor renders it. */
42
+ export interface CatalogEntry {
43
+ name: string;
44
+ description: string;
45
+ filePath: string;
46
+ }
47
+
48
+ /**
49
+ * Paragraph 1: what the catalog is, where the bodies live, and the obligation.
50
+ *
51
+ * `readRoot` is the single pack directory the rule can state; `grouped` says
52
+ * the rows are rendered under directory headings instead, so the rule points
53
+ * at the heading rather than at a root that does not exist. Neither given (a
54
+ * catalog whose bodies carry no pack) leaves the location unstated, which is
55
+ * the honest answer when the paths cannot be derived.
56
+ */
57
+ export function skillsCatalogRule(readRoot: string, grouped = false): string {
58
+ const readPath = readRoot
59
+ ? ` Each row's body is at \`${readRoot}/<name>/SKILL.md\`.`
60
+ : grouped
61
+ ? ` Each row's body is at \`<dir>/<name>/SKILL.md\`, where \`<dir>\` is the row's directory heading.`
62
+ : "";
63
+ return `This catalog is every installed skill: one row per skill, name and description.${readPath} When the task enters a listed skill's domain, read the WHOLE SKILL.md before acting in that domain; never act from memory of a skill's contents.`;
64
+ }
27
65
 
28
66
  /** Paragraph 2: the pointer rule (pinned verbatim by test-prompt-budget.mjs). */
29
- export const SKILLS_POINTER_RULE = `Pointer rule: the catalog one-liner is metadata, not content — the SKILL.md path is the knowledge. Mid-task, enter a domain absent from the visible catalog → call list_skills again (catalog is paginated). The prompt already covering the domain is the only reason to skip the read.`;
67
+ export const SKILLS_POINTER_RULE = `Pointer rule: the catalog one-liner is metadata, not content — the SKILL.md path is the knowledge. The prompt already covering the domain is the only reason to skip the read.`;
30
68
 
31
69
  const MECHANICAL_TRIGGER_LEAD = `Mechanical trigger, no judgment call: about to use a tool family whose word appears in a skill's name`;
32
70
  const MECHANICAL_TRIGGER_TAIL = `→ read that SKILL.md before the first call in the family.`;
33
71
 
72
+ /** Forward-slash form of a path, for segment arithmetic on either platform. */
73
+ function toSlashes(path: string): string {
74
+ return path.replace(/\\/g, "/");
75
+ }
76
+
77
+ /** Sorted by name, byte-comparison so the order never depends on the locale. */
78
+ function byName(a: string, b: string): number {
79
+ return a < b ? -1 : a > b ? 1 : 0;
80
+ }
81
+
82
+ /** One directory a catalog's bodies live in, with the skills filed under it. */
83
+ export interface CatalogGroup {
84
+ /** The pack directory itself, in forward-slash form. */
85
+ dir: string;
86
+ skills: CatalogEntry[];
87
+ }
88
+
89
+ /**
90
+ * The pack directory a skill's body sits in. pi's layout is
91
+ * `<pack>/<skill-name>/SKILL.md`, so the pack is two levels above the file;
92
+ * the row's stated path is `<pack>/<name>/SKILL.md`. A path too short to have
93
+ * a pack reports "", and its group renders without a heading.
94
+ */
95
+ function packOf(filePath: string): string {
96
+ const parts = toSlashes(filePath ?? "").split("/");
97
+ if (parts.length < 3) return "";
98
+ return parts.slice(0, -2).join("/");
99
+ }
100
+
101
+ /**
102
+ * File the entries by the pack their own SKILL.md lives in: the braid pack
103
+ * plus the user-global directory is two groups in one catalog. Groups and
104
+ * rows are sorted, so identical catalogs render byte-identical text in any
105
+ * cache order. Pure.
106
+ */
107
+ export function catalogGroups(skills: CatalogEntry[]): CatalogGroup[] {
108
+ const byDir = new Map<string, CatalogEntry[]>();
109
+ for (const skill of skills) {
110
+ const dir = packOf(skill.filePath ?? "");
111
+ const bucket = byDir.get(dir);
112
+ if (bucket) bucket.push(skill);
113
+ else byDir.set(dir, [skill]);
114
+ }
115
+ return [...byDir.keys()].sort(byName).map((dir) => ({ dir, skills: byDir.get(dir) ?? [] }));
116
+ }
117
+
118
+ /**
119
+ * The one directory every entry lives under, or "" when they do not share
120
+ * one: a single root is a fact a caller may state, and a common ancestor of
121
+ * two packs is not. Pure.
122
+ */
123
+ export function skillReadRoot(skills: CatalogEntry[]): string {
124
+ const groups = catalogGroups(skills);
125
+ return groups.length === 1 ? groups[0].dir : "";
126
+ }
127
+
128
+ /**
129
+ * One row per skill: `- name: description`, whitespace collapsed to a single
130
+ * line. Descriptions are NOT clipped: the row is the whole reason the floor
131
+ * works, and a clipped description is what a model would have to guess from.
132
+ * Pure.
133
+ */
134
+ export function catalogRows(skills: CatalogEntry[]): string[] {
135
+ return [...skills]
136
+ .sort((a, b) => byName(a.name, b.name))
137
+ .map((s) => {
138
+ const description = (s.description ?? "").replace(/\s+/g, " ").trim();
139
+ return description ? `- ${s.name}: ${description}` : `- ${s.name}`;
140
+ });
141
+ }
142
+
34
143
  /**
35
144
  * Worked examples for the mechanical trigger, derived from the live inputs.
36
145
  *
37
146
  * A pair exists when a tool's family token (the first underscore-delimited
38
- * token of the tool name: `herdr_layout` → `herdr`) equals a dash-delimited
39
- * token of a skill name (`herdr-topology` → `herdr`), case-insensitively.
147
+ * token of the tool name: `widget_open` → `widget`) equals a dash-delimited
148
+ * token of a skill name (`widget-map` → `widget`), case-insensitively.
40
149
  * One example renders per distinct family token: the trigger fires per
41
150
  * family ("before the first call in the family"), so enumerating every tool
42
151
  * in a family would restate one fact; the representative tool is the
@@ -74,16 +183,181 @@ export function mechanicalTriggerExamples(toolNames: string[], skillNames: strin
74
183
  }
75
184
 
76
185
  /**
77
- * The full skills-loading text: discovery rule, pointer rule, and the
78
- * mechanical trigger with only the pairs computed from the given tool and
79
- * skill names. prompt-builder feeds it the active tool names and the
80
- * skills-tool module's visible-catalog names.
186
+ * The full skills-loading section: catalog rule (with the derived read path),
187
+ * pointer rule, one row per visible skill, and the mechanical trigger with
188
+ * only the pairs computed from the given tool and skill names.
189
+ *
190
+ * prompt-builder feeds it the active tool names and the skills-tool module's
191
+ * visible catalog. An empty catalog renders no section: the floor is a
192
+ * catalog, and a section claiming to list every skill while listing none
193
+ * would be a lie the model has no way to check.
194
+ *
195
+ * One pack renders its root in the rule; several packs render a directory
196
+ * heading before each group of rows, because no single root describes them.
81
197
  */
82
- export function skillsLoadingText(toolNames: string[], skillNames: string[]): string {
83
- const examples = mechanicalTriggerExamples(toolNames, skillNames);
198
+ export function skillsLoadingText(toolNames: string[], skills: CatalogEntry[]): string {
199
+ if (!skills.length) return "";
200
+ const examples = mechanicalTriggerExamples(
201
+ toolNames,
202
+ skills.map((s) => s.name),
203
+ );
84
204
  const trigger =
85
205
  examples.length > 0
86
206
  ? `${MECHANICAL_TRIGGER_LEAD} (${examples.join(", ")}) ${MECHANICAL_TRIGGER_TAIL}`
87
207
  : `${MECHANICAL_TRIGGER_LEAD} ${MECHANICAL_TRIGGER_TAIL}`;
88
- return `${SKILLS_DISCOVERY_RULE}\n\n${SKILLS_POINTER_RULE}\n\n${trigger}\n`;
208
+ const groups = catalogGroups(skills);
209
+ const grouped = groups.length > 1;
210
+ const rows = grouped
211
+ ? groups
212
+ .map((g) =>
213
+ g.dir
214
+ ? `${g.dir}\n${catalogRows(g.skills).join("\n")}`
215
+ : catalogRows(g.skills).join("\n"),
216
+ )
217
+ .join("\n\n")
218
+ : catalogRows(groups[0].skills).join("\n");
219
+ return `${skillsCatalogRule(skillReadRoot(skills), grouped)}\n\n${SKILLS_POINTER_RULE}\n\n${rows}\n\n${trigger}\n`;
220
+ }
221
+
222
+ // Drift trigger
223
+ //
224
+ // The floor is a snapshot: the catalog does not change mid-session, but the
225
+ // work does. A session that starts in one directory and moves to another has
226
+ // its catalog in view and its task text elsewhere, which is the same silent
227
+ // prompt the floor exists for. The trigger watches where the path-taking
228
+ // tools actually write and reads, and when a new directory accumulates
229
+ // entries it says so in one line, pointing back at the catalog.
230
+ //
231
+ // Bounds, all deliberate:
232
+ // - two entries in one directory before it counts: a single stray read is
233
+ // not where the work is.
234
+ // - at most one fire per DRIFT_WINDOW_CALLS tool calls, and quiet for the
235
+ // same window after any skill surface (a suggestion or a SKILL.md read),
236
+ // because a surface that just landed is the pointer the trigger exists to
237
+ // supply.
238
+ // - at most DRIFT_MAX_FIRES per session, so the line stays a signal.
239
+ // - a directory is announced once; the entry counts restart after a fire,
240
+ // so the budget is spent on directories the session has not been told
241
+ // about.
242
+ // - paths with fewer than two directory segments are ignored: repo-root
243
+ // files and top-level directories are where a session starts, not where
244
+ // it moved to.
245
+
246
+ /** The path-taking tools whose calls describe where the work is. */
247
+ export const DRIFT_PATH_TOOLS = ["read", "edit", "write"] as const;
248
+
249
+ /** Tool calls that must pass between fires, and after any skill surface. */
250
+ export const DRIFT_WINDOW_CALLS = 12;
251
+
252
+ /** Fires per session. */
253
+ export const DRIFT_MAX_FIRES = 3;
254
+
255
+ /** Entries in one directory before it counts as where the work is. */
256
+ export const DRIFT_ENTRIES = 2;
257
+
258
+ /** Directory segments a path must carry before it can name a work area. */
259
+ export const DRIFT_MIN_SEGMENTS = 2;
260
+
261
+ /** Drift state, session-scoped plain data (see auto-inject.ts for the holder). */
262
+ export interface DriftTracker {
263
+ /** Tool results seen this session: the clock both window guards read. */
264
+ calls: number;
265
+ /** Call index of the last fire; null before the first. */
266
+ lastFire: number | null;
267
+ /** Fires this session. */
268
+ fires: number;
269
+ /** Call index of the last skill surface; null before the first. */
270
+ lastSurface: number | null;
271
+ /** Directory -> entries seen since the last fire. */
272
+ entries: Record<string, number>;
273
+ /** Directories already announced (each is announced once). */
274
+ announced: string[];
275
+ }
276
+
277
+ /** Fresh drift state for a session. */
278
+ export function initialDrift(): DriftTracker {
279
+ return { calls: 0, lastFire: null, fires: 0, lastSurface: null, entries: {}, announced: [] };
280
+ }
281
+
282
+ /**
283
+ * The work area a finished tool call touched: the first two directory
284
+ * segments of its path, relative to the session's project root. Undefined for
285
+ * a tool that takes no path, a path outside the project, and a path with
286
+ * fewer than DRIFT_MIN_SEGMENTS directories. Pure.
287
+ */
288
+ export function driftDirectoryFor(
289
+ toolName: string | undefined,
290
+ inputPath: string | undefined,
291
+ cwd: string,
292
+ ): string | undefined {
293
+ if (!toolName || !(DRIFT_PATH_TOOLS as readonly string[]).includes(toolName)) return undefined;
294
+ if (!inputPath || !cwd) return undefined;
295
+ const root = resolve(cwd);
296
+ const absolute = isAbsolute(inputPath) ? resolve(inputPath) : resolve(root, inputPath);
297
+ const inside = relative(root, absolute);
298
+ const segments = inside.split(sep).filter(Boolean);
299
+ if (!segments.length || segments[0] === "..") return undefined;
300
+ const directories = segments.slice(0, -1);
301
+ if (directories.length < DRIFT_MIN_SEGMENTS) return undefined;
302
+ return directories.slice(0, DRIFT_MIN_SEGMENTS).join("/");
303
+ }
304
+
305
+ /**
306
+ * Count one finished tool call and answer whether it is a fire.
307
+ *
308
+ * Returns the work area to announce, or null. The caller fires the line and
309
+ * then calls recordDriftFire (on delivery) or recordDriftDrop (when the
310
+ * whisper was suppressed), so a dropped line never spends the budget. The
311
+ * tracker is the session's own mutable state; the answer is a pure function
312
+ * of its contents.
313
+ */
314
+ export function advanceDrift(tracker: DriftTracker, directory: string | undefined): string | null {
315
+ tracker.calls++;
316
+ if (!directory) return null;
317
+ if (tracker.fires >= DRIFT_MAX_FIRES) return null;
318
+ const entries = (tracker.entries[directory] ?? 0) + 1;
319
+ tracker.entries[directory] = entries;
320
+ if (entries < DRIFT_ENTRIES) return null;
321
+ if (tracker.announced.includes(directory)) return null;
322
+ if (tracker.lastFire !== null && tracker.calls - tracker.lastFire < DRIFT_WINDOW_CALLS)
323
+ return null;
324
+ if (tracker.lastSurface !== null && tracker.calls - tracker.lastSurface < DRIFT_WINDOW_CALLS) {
325
+ return null;
326
+ }
327
+ return directory;
328
+ }
329
+
330
+ /** Mark a fire at the current call: spends one fire, announces, restarts counts. */
331
+ export function recordDriftFire(tracker: DriftTracker, directory: string): void {
332
+ tracker.fires++;
333
+ tracker.lastFire = tracker.calls;
334
+ if (!tracker.announced.includes(directory)) tracker.announced.push(directory);
335
+ tracker.entries = {};
336
+ }
337
+
338
+ /**
339
+ * Mark a fire attempt whose whisper was suppressed: no fire is spent and the
340
+ * directory is not announced, but the counts restart and the window opens, so
341
+ * a suppressed line is retried only after the session has done more work.
342
+ */
343
+ export function recordDriftDrop(tracker: DriftTracker): void {
344
+ tracker.lastFire = tracker.calls;
345
+ tracker.entries = {};
346
+ }
347
+
348
+ /** Note that a skill surface (a suggestion or a SKILL.md read) just landed. */
349
+ export function noteDriftSurface(tracker: DriftTracker): void {
350
+ tracker.lastSurface = tracker.calls;
351
+ }
352
+
353
+ /**
354
+ * The one-line steer: the work area and a pointer back at the catalog in the
355
+ * prompt. `readRoot` empty (several packs, see skillReadRoot) drops the path
356
+ * clause instead of naming a path that may not resolve.
357
+ */
358
+ export function driftPayload(directory: string, readRoot: string): string {
359
+ const pointer = readRoot
360
+ ? `read \`${readRoot}/<name>/SKILL.md\``
361
+ : `read the matching skill's SKILL.md`;
362
+ return `[SKILL INDEX] work is in ${directory}. Catalog above; ${pointer}.`;
89
363
  }