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,38 +1,129 @@
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.
37
+ */
38
+ import { isAbsolute, relative, resolve, sep } from "node:path";
39
+ /**
40
+ * Paragraph 1: what the catalog is, where the bodies live, and the obligation.
41
+ *
42
+ * `readRoot` is the single pack directory the rule can state; `grouped` says
43
+ * the rows are rendered under directory headings instead, so the rule points
44
+ * at the heading rather than at a root that does not exist. Neither given (a
45
+ * catalog whose bodies carry no pack) leaves the location unstated, which is
46
+ * the honest answer when the paths cannot be derived.
23
47
  */
24
- /** Paragraph 1: the discovery rule (pinned verbatim by test-prompt-budget.mjs). */
25
- 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.`;
48
+ export function skillsCatalogRule(readRoot, grouped = false) {
49
+ const readPath = readRoot
50
+ ? ` Each row's body is at \`${readRoot}/<name>/SKILL.md\`.`
51
+ : grouped
52
+ ? ` Each row's body is at \`<dir>/<name>/SKILL.md\`, where \`<dir>\` is the row's directory heading.`
53
+ : "";
54
+ 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.`;
55
+ }
26
56
  /** Paragraph 2: the pointer rule (pinned verbatim by test-prompt-budget.mjs). */
27
- 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.`;
57
+ 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.`;
28
58
  const MECHANICAL_TRIGGER_LEAD = `Mechanical trigger, no judgment call: about to use a tool family whose word appears in a skill's name`;
29
59
  const MECHANICAL_TRIGGER_TAIL = `→ read that SKILL.md before the first call in the family.`;
60
+ /** Forward-slash form of a path, for segment arithmetic on either platform. */
61
+ function toSlashes(path) {
62
+ return path.replace(/\\/g, "/");
63
+ }
64
+ /** Sorted by name, byte-comparison so the order never depends on the locale. */
65
+ function byName(a, b) {
66
+ return a < b ? -1 : a > b ? 1 : 0;
67
+ }
68
+ /**
69
+ * The pack directory a skill's body sits in. pi's layout is
70
+ * `<pack>/<skill-name>/SKILL.md`, so the pack is two levels above the file;
71
+ * the row's stated path is `<pack>/<name>/SKILL.md`. A path too short to have
72
+ * a pack reports "", and its group renders without a heading.
73
+ */
74
+ function packOf(filePath) {
75
+ const parts = toSlashes(filePath ?? "").split("/");
76
+ if (parts.length < 3)
77
+ return "";
78
+ return parts.slice(0, -2).join("/");
79
+ }
80
+ /**
81
+ * File the entries by the pack their own SKILL.md lives in: the braid pack
82
+ * plus the user-global directory is two groups in one catalog. Groups and
83
+ * rows are sorted, so identical catalogs render byte-identical text in any
84
+ * cache order. Pure.
85
+ */
86
+ export function catalogGroups(skills) {
87
+ const byDir = new Map();
88
+ for (const skill of skills) {
89
+ const dir = packOf(skill.filePath ?? "");
90
+ const bucket = byDir.get(dir);
91
+ if (bucket)
92
+ bucket.push(skill);
93
+ else
94
+ byDir.set(dir, [skill]);
95
+ }
96
+ return [...byDir.keys()].sort(byName).map((dir) => ({ dir, skills: byDir.get(dir) ?? [] }));
97
+ }
98
+ /**
99
+ * The one directory every entry lives under, or "" when they do not share
100
+ * one: a single root is a fact a caller may state, and a common ancestor of
101
+ * two packs is not. Pure.
102
+ */
103
+ export function skillReadRoot(skills) {
104
+ const groups = catalogGroups(skills);
105
+ return groups.length === 1 ? groups[0].dir : "";
106
+ }
107
+ /**
108
+ * One row per skill: `- name: description`, whitespace collapsed to a single
109
+ * line. Descriptions are NOT clipped: the row is the whole reason the floor
110
+ * works, and a clipped description is what a model would have to guess from.
111
+ * Pure.
112
+ */
113
+ export function catalogRows(skills) {
114
+ return [...skills]
115
+ .sort((a, b) => byName(a.name, b.name))
116
+ .map((s) => {
117
+ const description = (s.description ?? "").replace(/\s+/g, " ").trim();
118
+ return description ? `- ${s.name}: ${description}` : `- ${s.name}`;
119
+ });
120
+ }
30
121
  /**
31
122
  * Worked examples for the mechanical trigger, derived from the live inputs.
32
123
  *
33
124
  * A pair exists when a tool's family token (the first underscore-delimited
34
- * token of the tool name: `herdr_layout` → `herdr`) equals a dash-delimited
35
- * token of a skill name (`herdr-topology` → `herdr`), case-insensitively.
125
+ * token of the tool name: `widget_open` → `widget`) equals a dash-delimited
126
+ * token of a skill name (`widget-map` → `widget`), case-insensitively.
36
127
  * One example renders per distinct family token: the trigger fires per
37
128
  * family ("before the first call in the family"), so enumerating every tool
38
129
  * in a family would restate one fact; the representative tool is the
@@ -72,16 +163,153 @@ export function mechanicalTriggerExamples(toolNames, skillNames) {
72
163
  .map(([family, { casing }]) => `\`${familyTool.get(family)}\` → ${casing}`);
73
164
  }
74
165
  /**
75
- * The full skills-loading text: discovery rule, pointer rule, and the
76
- * mechanical trigger with only the pairs computed from the given tool and
77
- * skill names. prompt-builder feeds it the active tool names and the
78
- * skills-tool module's visible-catalog names.
166
+ * The full skills-loading section: catalog rule (with the derived read path),
167
+ * pointer rule, one row per visible skill, and the mechanical trigger with
168
+ * only the pairs computed from the given tool and skill names.
169
+ *
170
+ * prompt-builder feeds it the active tool names and the skills-tool module's
171
+ * visible catalog. An empty catalog renders no section: the floor is a
172
+ * catalog, and a section claiming to list every skill while listing none
173
+ * would be a lie the model has no way to check.
174
+ *
175
+ * One pack renders its root in the rule; several packs render a directory
176
+ * heading before each group of rows, because no single root describes them.
79
177
  */
80
- export function skillsLoadingText(toolNames, skillNames) {
81
- const examples = mechanicalTriggerExamples(toolNames, skillNames);
178
+ export function skillsLoadingText(toolNames, skills) {
179
+ if (!skills.length)
180
+ return "";
181
+ const examples = mechanicalTriggerExamples(toolNames, skills.map((s) => s.name));
82
182
  const trigger = examples.length > 0
83
183
  ? `${MECHANICAL_TRIGGER_LEAD} (${examples.join(", ")}) ${MECHANICAL_TRIGGER_TAIL}`
84
184
  : `${MECHANICAL_TRIGGER_LEAD} ${MECHANICAL_TRIGGER_TAIL}`;
85
- return `${SKILLS_DISCOVERY_RULE}\n\n${SKILLS_POINTER_RULE}\n\n${trigger}\n`;
185
+ const groups = catalogGroups(skills);
186
+ const grouped = groups.length > 1;
187
+ const rows = grouped
188
+ ? groups
189
+ .map((g) => g.dir
190
+ ? `${g.dir}\n${catalogRows(g.skills).join("\n")}`
191
+ : catalogRows(g.skills).join("\n"))
192
+ .join("\n\n")
193
+ : catalogRows(groups[0].skills).join("\n");
194
+ return `${skillsCatalogRule(skillReadRoot(skills), grouped)}\n\n${SKILLS_POINTER_RULE}\n\n${rows}\n\n${trigger}\n`;
195
+ }
196
+ // Drift trigger
197
+ //
198
+ // The floor is a snapshot: the catalog does not change mid-session, but the
199
+ // work does. A session that starts in one directory and moves to another has
200
+ // its catalog in view and its task text elsewhere, which is the same silent
201
+ // prompt the floor exists for. The trigger watches where the path-taking
202
+ // tools actually write and reads, and when a new directory accumulates
203
+ // entries it says so in one line, pointing back at the catalog.
204
+ //
205
+ // Bounds, all deliberate:
206
+ // - two entries in one directory before it counts: a single stray read is
207
+ // not where the work is.
208
+ // - at most one fire per DRIFT_WINDOW_CALLS tool calls, and quiet for the
209
+ // same window after any skill surface (a suggestion or a SKILL.md read),
210
+ // because a surface that just landed is the pointer the trigger exists to
211
+ // supply.
212
+ // - at most DRIFT_MAX_FIRES per session, so the line stays a signal.
213
+ // - a directory is announced once; the entry counts restart after a fire,
214
+ // so the budget is spent on directories the session has not been told
215
+ // about.
216
+ // - paths with fewer than two directory segments are ignored: repo-root
217
+ // files and top-level directories are where a session starts, not where
218
+ // it moved to.
219
+ /** The path-taking tools whose calls describe where the work is. */
220
+ export const DRIFT_PATH_TOOLS = ["read", "edit", "write"];
221
+ /** Tool calls that must pass between fires, and after any skill surface. */
222
+ export const DRIFT_WINDOW_CALLS = 12;
223
+ /** Fires per session. */
224
+ export const DRIFT_MAX_FIRES = 3;
225
+ /** Entries in one directory before it counts as where the work is. */
226
+ export const DRIFT_ENTRIES = 2;
227
+ /** Directory segments a path must carry before it can name a work area. */
228
+ export const DRIFT_MIN_SEGMENTS = 2;
229
+ /** Fresh drift state for a session. */
230
+ export function initialDrift() {
231
+ return { calls: 0, lastFire: null, fires: 0, lastSurface: null, entries: {}, announced: [] };
232
+ }
233
+ /**
234
+ * The work area a finished tool call touched: the first two directory
235
+ * segments of its path, relative to the session's project root. Undefined for
236
+ * a tool that takes no path, a path outside the project, and a path with
237
+ * fewer than DRIFT_MIN_SEGMENTS directories. Pure.
238
+ */
239
+ export function driftDirectoryFor(toolName, inputPath, cwd) {
240
+ if (!toolName || !DRIFT_PATH_TOOLS.includes(toolName))
241
+ return undefined;
242
+ if (!inputPath || !cwd)
243
+ return undefined;
244
+ const root = resolve(cwd);
245
+ const absolute = isAbsolute(inputPath) ? resolve(inputPath) : resolve(root, inputPath);
246
+ const inside = relative(root, absolute);
247
+ const segments = inside.split(sep).filter(Boolean);
248
+ if (!segments.length || segments[0] === "..")
249
+ return undefined;
250
+ const directories = segments.slice(0, -1);
251
+ if (directories.length < DRIFT_MIN_SEGMENTS)
252
+ return undefined;
253
+ return directories.slice(0, DRIFT_MIN_SEGMENTS).join("/");
254
+ }
255
+ /**
256
+ * Count one finished tool call and answer whether it is a fire.
257
+ *
258
+ * Returns the work area to announce, or null. The caller fires the line and
259
+ * then calls recordDriftFire (on delivery) or recordDriftDrop (when the
260
+ * whisper was suppressed), so a dropped line never spends the budget. The
261
+ * tracker is the session's own mutable state; the answer is a pure function
262
+ * of its contents.
263
+ */
264
+ export function advanceDrift(tracker, directory) {
265
+ tracker.calls++;
266
+ if (!directory)
267
+ return null;
268
+ if (tracker.fires >= DRIFT_MAX_FIRES)
269
+ return null;
270
+ const entries = (tracker.entries[directory] ?? 0) + 1;
271
+ tracker.entries[directory] = entries;
272
+ if (entries < DRIFT_ENTRIES)
273
+ return null;
274
+ if (tracker.announced.includes(directory))
275
+ return null;
276
+ if (tracker.lastFire !== null && tracker.calls - tracker.lastFire < DRIFT_WINDOW_CALLS)
277
+ return null;
278
+ if (tracker.lastSurface !== null && tracker.calls - tracker.lastSurface < DRIFT_WINDOW_CALLS) {
279
+ return null;
280
+ }
281
+ return directory;
282
+ }
283
+ /** Mark a fire at the current call: spends one fire, announces, restarts counts. */
284
+ export function recordDriftFire(tracker, directory) {
285
+ tracker.fires++;
286
+ tracker.lastFire = tracker.calls;
287
+ if (!tracker.announced.includes(directory))
288
+ tracker.announced.push(directory);
289
+ tracker.entries = {};
290
+ }
291
+ /**
292
+ * Mark a fire attempt whose whisper was suppressed: no fire is spent and the
293
+ * directory is not announced, but the counts restart and the window opens, so
294
+ * a suppressed line is retried only after the session has done more work.
295
+ */
296
+ export function recordDriftDrop(tracker) {
297
+ tracker.lastFire = tracker.calls;
298
+ tracker.entries = {};
299
+ }
300
+ /** Note that a skill surface (a suggestion or a SKILL.md read) just landed. */
301
+ export function noteDriftSurface(tracker) {
302
+ tracker.lastSurface = tracker.calls;
303
+ }
304
+ /**
305
+ * The one-line steer: the work area and a pointer back at the catalog in the
306
+ * prompt. `readRoot` empty (several packs, see skillReadRoot) drops the path
307
+ * clause instead of naming a path that may not resolve.
308
+ */
309
+ export function driftPayload(directory, readRoot) {
310
+ const pointer = readRoot
311
+ ? `read \`${readRoot}/<name>/SKILL.md\``
312
+ : `read the matching skill's SKILL.md`;
313
+ return `[SKILL INDEX] work is in ${directory}. Catalog above; ${pointer}.`;
86
314
  }
87
315
  //# sourceMappingURL=loading-guidance.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.41.2",
3
+ "version": "0.42.0",
4
4
  "description": "Metacognitive extension suite for pi-coding-agent: enforcement, memory, reasoning, self-improvement, and structured cognitive signals.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -7,12 +7,12 @@ environmental awareness, and system prompt assembly.
7
7
 
8
8
  ## Sub-extensions
9
9
 
10
- | Path | Purpose | Depended on by |
11
- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
12
- | `polyfill/` | Polyfills for missing pi core features. | (foundation) |
13
- | `agent-environment/` | L1 environmental awareness: working dir, time, machine info. | `prompt-builder` |
14
- | `prompt-builder/` | Builds the agent's system prompt. Composes sections; orchestrates once-per-session whisper deliveries from `memory/` and `cognitive/`. | (final assembly) |
15
- | `skills-tool/` | On-demand skill discovery: `list_skills` catalog + `skill_stats` counters, the auto-inject whisper, and the skills-loading directive text rendered by `prompt-builder`. | (tool surface) |
10
+ | Path | Purpose | Depended on by |
11
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
12
+ | `polyfill/` | Polyfills for missing pi core features. | (foundation) |
13
+ | `agent-environment/` | L1 environmental awareness: working dir, time, machine info. | `prompt-builder` |
14
+ | `prompt-builder/` | Builds the agent's system prompt. Composes sections; orchestrates once-per-session whisper deliveries from `memory/` and `cognitive/`. | (final assembly) |
15
+ | `skills-tool/` | Skill surface: `list_skills` catalog (on-demand reach and ranking) + `skill_stats` counters, the auto-inject whisper, the skills floor (visible catalog) and drift trigger text rendered by `prompt-builder`. | (tool surface) |
16
16
 
17
17
  ## Local Contracts
18
18
 
@@ -32,3 +32,5 @@ The auto-inject whisper in `skills-tool/` is the only channel that surfaces a ma
32
32
  - **Counters move after delivery.** `recordSkillSuggestion` runs only on a `true` return, and the cooldown/LRU bookkeeping runs after the send too, so `suggested` counts arrivals and an undelivered suggestion consumes no slot. The suggestion bypasses the per-turn whisper cap (`bypassFloodCap: true`) because prompt-builder's once-per-session hygiene whisper fires earlier in the same `before_agent_start` at the same priority and would otherwise spend the only advisory slot; the module's own budget (cooldown turns, max active suggestions, one send per turn) is the bound that keeps the whisper a whisper.
33
33
  - **Conversion is a detected read.** The whisper asks the agent to open the SKILL.md; the conversion signal is the `read` tool_result (`actual`), which is also what sets `hadSkillLoad` in the durable session record. The retired LOADED/SKIP reply is no longer solicited; `claimed` keeps its historical honor-system meaning and stays monotone.
34
34
  - **The trigger has a mechanical form.** `skills-tool/loading-guidance.ts` carries both the judgment form (the task entered a listed skill's domain) and the mechanical form (about to call a tool family whose word appears in a skill's name). `prompt-builder` renders that text through the `skillsLoadingText` builder as the `skills-loading` section and holds no copy of the rules; the trigger's worked examples are derived at assembly from the live tool and skill names, so the text names no pair that the running session does not have. The identity's skills prose stays one sentence.
35
+ - **The catalog is in the prompt.** The same section renders every visible skill as one `- name: description` row, with the read path derived from the skills' own file paths (one root for a single pack, a directory heading per pack when a catalog is installed from several). A tool call is no longer the way the agent learns which skills exist: the floor exists because the prompt that opens a resumed session carries no domain vocabulary for a matcher to rank against. `list_skills` remains the price tool (reach, headings, ranking) rather than the catalog.
36
+ - **Drift re-points at the floor.** When the session's own path-taking calls (`read`/`edit`/`write`) accumulate entries in a work area the floor was not rendered against, one steer line names that area and points back at the catalog. The rule and its bounds (two entries, one fire per twelve calls, three per session, quiet for the same window after any skill surface) live in `loading-guidance.ts` beside the floor text; the wiring is the `tool_result` handler in `auto-inject.ts`. Bounds are the whole design: the line is only worth its noise if it stays rare.
@@ -1,5 +1,5 @@
1
1
  <!-- status: current -->
2
- <!-- Status note: identity compressed + PHILOSOPHY block added after EPISTEMIC_STANCE; the placement-discipline block and the PHILOSOPHY senior-craft line were reverted after the prompt re-probe failed its keep rule, REPAIR_DISCIPLINE stays; Resources section deleted; context guidelines reduced to the two policy sentences; pipelines cover 2 domains; tool guideline lines trimmed. Skills no longer render in the prompt: discovery is served by the list_skills tool, and the pi docs seat is a pointer to the pi-reference skill (the native `<docs>` region is not re-emitted). Policy relocation: the skills-loading directive lives in the skills-tool module; SURFACE_DISCIPLINE is its own section file; REPAIR_DISCIPLINE and SELF_AUDIT are identity blocks. The multi-agent message-contract constant is removed: the `[agent:…]` tag contract named a message format with no producer in any shipped mechanism, so the standing prompt asserted a channel that does not exist. The skills-loading section's mechanical trigger now derives its worked examples at assembly from the live tool and skill names (`skillsLoadingText` in skills-tool/loading-guidance.ts); no tool or skill name is hardcoded in prompt text. -->
2
+ <!-- Status note: identity compressed + PHILOSOPHY block added after EPISTEMIC_STANCE; the placement-discipline block and the PHILOSOPHY senior-craft line were reverted after the prompt re-probe failed its keep rule, REPAIR_DISCIPLINE stays; Resources section deleted; context guidelines reduced to the two policy sentences; pipelines cover 2 domains; tool guideline lines trimmed. Skills render in the prompt as the skills floor: every visible skill is one `- name: description` row, with the read path derived from the skills' own file paths (one root for a single pack, a directory heading per pack for several) and the mechanical trigger last; `list_skills` stays the price tool (reach, headings, ranking). The pi docs seat is a pointer to the pi-reference skill (the native `<docs>` region is not re-emitted). Policy relocation: the skills floor text and its drift trigger live in the skills-tool module (`loading-guidance.ts`); SURFACE_DISCIPLINE is its own section file; REPAIR_DISCIPLINE and SELF_AUDIT are identity blocks. The multi-agent message-contract constant is removed: the `[agent:…]` tag contract named a message format with no producer in any shipped mechanism, so the standing prompt asserted a channel that does not exist. The floor's rows and the trigger's worked examples are derived at assembly from the live cache, tool names and skill names (`skillsLoadingText` in skills-tool/loading-guidance.ts); no tool, skill or install path is hardcoded in prompt text. -->
3
3
 
4
4
  # src/extensions/core/prompt-builder/ - System Prompt Composition
5
5
 
@@ -20,7 +20,7 @@ Every file in this folder either:
20
20
 
21
21
  | File | Purpose |
22
22
  | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
23
- | `index.ts` | Main handler. Wires `before_agent_start`, calls the 4 `deliver*` functions, composes the final prompt. |
23
+ | `index.ts` | Main handler. Wires `before_agent_start`, calls the 4 `deliver*` functions, composes the final prompt. Renders the skills floor as its own guarded section (`skillsLoadingText` over the live visible catalog), after the identity seats and before the guidelines. |
24
24
  | `section.ts` | The `PromptSection` primitive + `composeSections` joiner + `simpleSection`, `linesSection`, `headingSection` builders. |
25
25
  | `identity.ts` | Framing constants: `IDENTITY_INTRO` (generalist identity), `DISCOVERY` (D1 guarded exploration stance), `WORK_ETHIC` (methodical precision, signal-not-noise), `REPAIR_DISCIPLINE` (root cause named falsifiably before repair; re-derivation of claims that are not yours; weighted repair decisions), `SELF_MANAGEMENT` (memory workspace, evidence-carrying done items, known-open-check done gate), `COMMUNICATION` (conclusion-first, output style), `EPISTEMIC_STANCE` (identity-core: claim gate, self-state gate, retrieved-context preference), `SELF_AUDIT` (symmetric doubt; handoff ends with the unverified), `PHILOSOPHY` (character-level stance - silence, calm strategist, precise self-irony). |
26
26
  | `surface-discipline-section.ts` | `SURFACE_DISCIPLINE` (signal discipline across code, commits, tests, docs, reports, logs) + `surfaceDisciplineSection()` - its own section, rendered between the identity and identity-core blocks. Text pinned verbatim by test-prompt-budget.mjs. |
@@ -38,7 +38,8 @@ import {
38
38
  reconstructProjectDocsSection,
39
39
  resetProjectDocsSectionCache,
40
40
  } from "./project-docs-section.js";
41
- import { setCachedSkills, getCachedVisibleSkillNames } from "../skills-tool/index.js";
41
+ import { setCachedSkills } from "../skills-tool/index.js";
42
+ import { getCachedVisibleSkills } from "../skills-tool/auto-inject.js";
42
43
  import { reconstructMemorySection, resetMemorySectionCache } from "./memory-section.js";
43
44
  import { gatherInstanceData, renderCompactInstance } from "./instance-composition.js";
44
45
  import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
@@ -523,21 +524,16 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
523
524
  surfaceDisciplineSection(),
524
525
  simpleSection("identity-core", [EPISTEMIC_STANCE, SELF_AUDIT, PHILOSOPHY].join("\n\n")),
525
526
 
526
- // 2. Skills-loading directive (before guidelines, before tools).
527
+ // 2. Skills floor (before guidelines, before tools).
527
528
  // Owned by the skills-tool module (loading-guidance.ts) and rendered
528
- // here. Guarded by read AND list_skills availability — the directive
529
- // instructs list_skills discovery + full-file read, so both tools
530
- // must be present. The trigger's worked examples are derived here
531
- // from the active tool names and the visible skill catalog (the
532
- // cache setCachedSkills populated above is the catalog's source of
533
- // truth); the text itself never hardcodes a tool or skill name.
529
+ // here: the visible catalog itself, one row per skill, plus the
530
+ // read rule and the mechanical trigger. Guarded by read AND
531
+ // list_skills availability — the rule instructs a full-file read and
532
+ // the trigger names the catalog, so both tools must be present. The
533
+ // rows and the read root come from the live cache (setCachedSkills
534
+ // above); an empty catalog renders no section at all.
534
535
  ...(hasRead && hasListSkills
535
- ? [
536
- simpleSection(
537
- "skills-loading",
538
- skillsLoadingText(toolNames, getCachedVisibleSkillNames()),
539
- ),
540
- ]
536
+ ? [simpleSection("skills-loading", skillsLoadingText(toolNames, getCachedVisibleSkills()))]
541
537
  : []),
542
538
 
543
539
  // 3. Guidelines (before tools, pi-core native pattern).
@@ -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,