pi-braid 0.41.1 → 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.
@@ -88,6 +88,13 @@
88
88
  * and surfaces the state through skill_stats instead of mutating the
89
89
  * transcript.
90
90
  * 9. Best-effort: failures are non-fatal, logged at debug level.
91
+ * 10. Drift trigger: the visible catalog in the prompt is a snapshot of the
92
+ * work's directory, not of the session. When the path-taking tools
93
+ * accumulate entries in a new work area, one steer line re-points at the
94
+ * catalog (at most DRIFT_MAX_FIRES a session, DRIFT_WINDOW_CALLS apart,
95
+ * and never within that window of a suggestion or a SKILL.md read). The
96
+ * rule and its bounds live in loading-guidance.ts beside the floor text
97
+ * the line points at; this module only wires them to tool results.
91
98
  *
92
99
  * Structure matches the existing steer whisper pattern used by topic-drift,
93
100
  * turn-outcome, compaction-retry, context-lifecycle, and others.
@@ -114,6 +121,17 @@ import {
114
121
  } from "./session-records.js";
115
122
  import { triggerMatches } from "./skill-triggers.js";
116
123
  import type { TriggerSource } from "./skill-triggers.js";
124
+ import {
125
+ advanceDrift,
126
+ driftDirectoryFor,
127
+ driftPayload,
128
+ initialDrift,
129
+ noteDriftSurface,
130
+ recordDriftDrop,
131
+ recordDriftFire,
132
+ skillReadRoot,
133
+ } from "./loading-guidance.js";
134
+ import type { CatalogEntry, DriftTracker } from "./loading-guidance.js";
117
135
 
118
136
  const log = createLogger("skills-auto-inject");
119
137
 
@@ -265,6 +283,8 @@ interface AutoInjectState {
265
283
  currentTurn: number;
266
284
  /** True once the once-per-session profile hint whisper fired. */
267
285
  hintSent: boolean;
286
+ /** Where the work is going, for the drift trigger (loading-guidance.ts). */
287
+ drift: DriftTracker;
268
288
  }
269
289
 
270
290
  const STATE_KEY = "skills-auto-inject";
@@ -274,6 +294,7 @@ function getState(ctx: ExtensionContext): AutoInjectState {
274
294
  injected: [],
275
295
  currentTurn: 0,
276
296
  hintSent: false,
297
+ drift: initialDrift(),
277
298
  }));
278
299
  }
279
300
 
@@ -306,6 +327,18 @@ export function updateSkillCache(skills: CachedSkill[]): void {
306
327
  _skillsCache = skills;
307
328
  }
308
329
 
330
+ /**
331
+ * The visible catalog as the prompt floor renders it (see loading-guidance.ts):
332
+ * every cached skill model selection may route to, with the description and
333
+ * path the row needs. Read from this module because the cache lives here; the
334
+ * floor's read root is derived from the paths, never hardcoded.
335
+ */
336
+ export function getCachedVisibleSkills(): CatalogEntry[] {
337
+ return _skillsCache
338
+ .filter((s) => !s.disableModelInvocation)
339
+ .map((s) => ({ name: s.name, description: s.description, filePath: s.filePath }));
340
+ }
341
+
309
342
  // Keyword Extraction
310
343
 
311
344
  /**
@@ -1120,41 +1153,115 @@ export function resolveDiscoveryMode(ctx: ExtensionContext): DiscoveryState {
1120
1153
 
1121
1154
  // Main Handler
1122
1155
 
1156
+ /** The tool_result fields this module reads. */
1157
+ interface ToolResultEvent {
1158
+ toolName?: string;
1159
+ isError?: boolean;
1160
+ input?: { path?: string };
1161
+ content?: Array<{ text?: string }>;
1162
+ }
1163
+
1164
+ /**
1165
+ * Count a SKILL.md read (the list→read load path) and mark the matching
1166
+ * injection loaded (releases its slot and extends its cooldown: the skill is
1167
+ * in the agent's context now). Returns the skill name when the read was one,
1168
+ * so the caller can treat it as a skill surface.
1169
+ */
1170
+ function detectSkillLoad(
1171
+ ev: ToolResultEvent,
1172
+ ctx: ExtensionContext,
1173
+ state: AutoInjectState,
1174
+ ): string | undefined {
1175
+ if (ev?.toolName !== "read") return undefined;
1176
+ // A failed read returns the error text, not the file — counting it
1177
+ // inflated `loaded` with phantom loads (the read-detector never saw
1178
+ // the skill content, and no SKILL.md was opened).
1179
+ if (ev.isError) return undefined;
1180
+ const text = (ev.content ?? []).map((c) => c.text ?? "").join("\n");
1181
+ const name = skillNameFromRead(ev.input?.path, text);
1182
+ if (!name) return undefined;
1183
+ const held = state.injected.find((i) => i.name === name && i.loadedTurn === undefined);
1184
+ if (held) held.loadedTurn = state.currentTurn;
1185
+ recordSkillLoad(ctx, name);
1186
+ log.debug(`[skills-auto-inject] counted actual load of "${name}" via read`);
1187
+ return name;
1188
+ }
1189
+
1190
+ /**
1191
+ * Fire the drift line when the work has moved into a new work area (the rule
1192
+ * and its bounds live in loading-guidance.ts, beside the floor text the line
1193
+ * points at). The floor is the catalog against the prompt that was in view;
1194
+ * a session now reading and writing elsewhere has its catalog in the prompt
1195
+ * and its task text elsewhere, and one line re-points at it.
1196
+ *
1197
+ * Guarded like the floor section itself: without read and list_skills there is
1198
+ * no catalog in the prompt to point at, so nothing fires.
1199
+ */
1200
+ function stepDrift(
1201
+ pi: ExtensionAPI,
1202
+ ctx: ExtensionContext,
1203
+ state: AutoInjectState,
1204
+ ev: ToolResultEvent,
1205
+ ): void {
1206
+ const target = advanceDrift(
1207
+ state.drift,
1208
+ driftDirectoryFor(ev?.toolName, ev?.input?.path, ctx.cwd ?? ""),
1209
+ );
1210
+ if (!target) return;
1211
+ const toolNames = new Set(pi.getAllTools().map((t) => t.name));
1212
+ if (!toolNames.has("read") || !toolNames.has("list_skills")) {
1213
+ recordDriftDrop(state.drift);
1214
+ return;
1215
+ }
1216
+ const delivered = sendTrackedMessage(
1217
+ pi,
1218
+ {
1219
+ customType: "skills-drift",
1220
+ content: [{ type: "text" as const, text: driftPayload(target, skillReadRoot(_skillsCache)) }],
1221
+ display: true,
1222
+ details: {
1223
+ [BRAID_INJECTED]: true,
1224
+ [BRAID_SOURCE]: "skills-auto-inject",
1225
+ directory: target,
1226
+ },
1227
+ },
1228
+ { delivery: "park", deliverAs: "steer" },
1229
+ { type: "context", source: "skills-auto-inject" },
1230
+ // The module's own budget is the bound (DRIFT_MAX_FIRES a session,
1231
+ // DRIFT_WINDOW_CALLS between fires), so a suppression cap must not drop
1232
+ // the line in a busy turn: that is exactly when the work is moving and
1233
+ // the floor's snapshot goes stale.
1234
+ { bypassFloodCap: true },
1235
+ );
1236
+ if (!delivered) {
1237
+ recordDriftDrop(state.drift);
1238
+ return;
1239
+ }
1240
+ recordDriftFire(state.drift, target);
1241
+ log.info(
1242
+ `[skills-auto-inject] drift line for ${target} (fire ${state.drift.fires}, call ${state.drift.calls})`,
1243
+ );
1244
+ }
1245
+
1123
1246
  /**
1124
- * Register the auto-inject handler on before_agent_start plus the
1125
- * read-tool load detector on tool_result.
1247
+ * Register the auto-inject handler on before_agent_start, the read-tool load
1248
+ * detector and the drift trigger on tool_result.
1126
1249
  *
1127
1250
  * Call this from the skills-tool extension factory, after registering
1128
1251
  * the list_skills tool.
1129
1252
  */
1130
1253
  export function registerAutoInject(pi: ExtensionAPI): void {
1131
- // Count SKILL.md reads (the list→read load path) via the read tool, and
1132
- // per-skill: mark the matching injection as loaded (releases its slot and
1133
- // extends its cooldown — the skill is in the agent's context now).
1254
+ // Two jobs per tool result. The load detector runs first: a SKILL.md read
1255
+ // that just landed is a skill surface, and the drift guard must see it
1256
+ // before it decides whether to speak.
1134
1257
  pi.on("tool_result", (event: unknown, ctx: ExtensionContext) => {
1135
1258
  try {
1136
- const ev = event as {
1137
- toolName?: string;
1138
- isError?: boolean;
1139
- input?: { path?: string };
1140
- content?: Array<{ text?: string }>;
1141
- };
1142
- if (ev?.toolName !== "read") return;
1143
- // A failed read returns the error text, not the file — counting it
1144
- // inflated `loaded` with phantom loads (the read-detector never saw
1145
- // the skill content, and no SKILL.md was opened).
1146
- if (ev.isError) return;
1147
- const text = (ev.content ?? []).map((c) => c.text ?? "").join("\n");
1148
- const name = skillNameFromRead(ev.input?.path, text);
1149
- if (name) {
1150
- const state = getState(ctx);
1151
- const held = state.injected.find((i) => i.name === name && i.loadedTurn === undefined);
1152
- if (held) held.loadedTurn = state.currentTurn;
1153
- recordSkillLoad(ctx, name);
1154
- log.debug(`[skills-auto-inject] counted actual load of "${name}" via read`);
1155
- }
1259
+ const ev = event as ToolResultEvent;
1260
+ const state = getState(ctx);
1261
+ if (detectSkillLoad(ev, ctx, state)) noteDriftSurface(state.drift);
1262
+ stepDrift(pi, ctx, state, ev);
1156
1263
  } catch {
1157
- // best-effort — never break the tool loop over a counter
1264
+ // best-effort — never break the tool loop over a counter or a whisper
1158
1265
  }
1159
1266
  });
1160
1267
 
@@ -1300,6 +1407,11 @@ export function registerAutoInject(pi: ExtensionAPI): void {
1300
1407
  `(turn ${state.currentTurn}, keywords: ${keywords.slice(0, 5).join(", ")})`,
1301
1408
  );
1302
1409
 
1410
+ // A delivered suggestion is a skill surface: the drift trigger stays
1411
+ // quiet for its window, because the pointer the trigger exists to
1412
+ // supply has just landed.
1413
+ noteDriftSurface(state.drift);
1414
+
1303
1415
  for (const item of toInject) {
1304
1416
  state.injected.push({
1305
1417
  name: item.skill.name,
@@ -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
  }