pi-braid 0.41.2 → 0.42.1

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 (34) hide show
  1. package/CHANGELOG.md +1006 -0
  2. package/build-info.json +4 -4
  3. package/dist/extensions/cognitive/metacognition/handlers/think.js +9 -0
  4. package/dist/extensions/core/prompt-builder/index.js +10 -11
  5. package/dist/extensions/core/skills-tool/auto-inject.d.ts +17 -2
  6. package/dist/extensions/core/skills-tool/auto-inject.js +100 -24
  7. package/dist/extensions/core/skills-tool/index.js +47 -26
  8. package/dist/extensions/core/skills-tool/loading-guidance.d.ts +149 -28
  9. package/dist/extensions/core/skills-tool/loading-guidance.js +257 -29
  10. package/dist/extensions/manifest.js +6 -0
  11. package/dist/extensions/self/path-miss/detect.d.ts +30 -0
  12. package/dist/extensions/self/path-miss/detect.js +67 -0
  13. package/dist/extensions/self/path-miss/index.d.ts +33 -0
  14. package/dist/extensions/self/path-miss/index.js +118 -0
  15. package/dist/lib/core/event-names.d.ts +1 -0
  16. package/dist/lib/core/event-names.js +1 -0
  17. package/dist/lib/utils/argument-report.d.ts +41 -0
  18. package/dist/lib/utils/argument-report.js +95 -0
  19. package/package.json +4 -3
  20. package/src/extensions/cognitive/metacognition/handlers/think.ts +9 -0
  21. package/src/extensions/core/AGENTS.md +8 -6
  22. package/src/extensions/core/prompt-builder/AGENTS.md +2 -2
  23. package/src/extensions/core/prompt-builder/index.ts +10 -14
  24. package/src/extensions/core/skills-tool/auto-inject.ts +138 -26
  25. package/src/extensions/core/skills-tool/index.ts +60 -37
  26. package/src/extensions/core/skills-tool/loading-guidance.ts +303 -29
  27. package/src/extensions/manifest.ts +6 -0
  28. package/src/extensions/self/AGENTS.md +2 -1
  29. package/src/extensions/self/path-miss/AGENTS.md +39 -0
  30. package/src/extensions/self/path-miss/detect.ts +78 -0
  31. package/src/extensions/self/path-miss/index.ts +135 -0
  32. package/src/lib/core/event-names.ts +1 -0
  33. package/src/lib/utils/AGENTS.md +1 -0
  34. package/src/lib/utils/argument-report.ts +105 -0
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Tool-argument refusal text.
3
+ *
4
+ * pi validates a tool call against its schema and reports the failure in
5
+ * schema terms: an out-of-list value says "must be equal to one of the allowed
6
+ * values", a missing required field says "must have required properties
7
+ * decision". Neither names the values, so the model that guessed one learns
8
+ * nothing it can act on and guesses again.
9
+ *
10
+ * The accepted values, and the sentence explaining a required field, are
11
+ * already in the schema. This module reads them from there at the moment the
12
+ * refusal is built: no list is written twice, so no copy can drift from the
13
+ * one the validator enforces.
14
+ *
15
+ * Seat: a tool's `prepareArguments`. pi calls it first, inside the same
16
+ * guarded block as its own schema validation, so a throw here is what the
17
+ * model reads — and the schema stays exactly as strict as it was. The checks
18
+ * below are equivalences, not relaxations: a call refused here is one pi would
19
+ * have refused too, only with a message the model can use.
20
+ *
21
+ * Scope is the top level of the argument object. A nested list is left to pi
22
+ * rather than described from a guess about its parent.
23
+ */
24
+ function nodeOf(value) {
25
+ return value && typeof value === "object" ? value : undefined;
26
+ }
27
+ /**
28
+ * The values a schema node accepts, read from the node.
29
+ *
30
+ * A single-valued node (`const`, which is what `Type.Literal` builds) yields
31
+ * one value; an `enum` yields its list; a union of those yields all of them.
32
+ * A node that constrains nothing yields no values, and the caller then leaves
33
+ * the message to pi.
34
+ */
35
+ export function acceptedValues(node) {
36
+ const schema = nodeOf(node);
37
+ if (!schema)
38
+ return [];
39
+ if (typeof schema.const === "string")
40
+ return [schema.const];
41
+ if (Array.isArray(schema.enum) && schema.enum.every((v) => typeof v === "string")) {
42
+ return [...new Set(schema.enum)];
43
+ }
44
+ const branches = Array.isArray(schema.anyOf)
45
+ ? schema.anyOf
46
+ : Array.isArray(schema.oneOf)
47
+ ? schema.oneOf
48
+ : undefined;
49
+ if (!branches)
50
+ return [];
51
+ return [...new Set(branches.flatMap((branch) => acceptedValues(branch)))];
52
+ }
53
+ function quoted(value) {
54
+ return JSON.stringify(value);
55
+ }
56
+ /**
57
+ * Throw the refusal a model can act on, when this module can say more than the
58
+ * validator does. Returns silently otherwise, leaving pi's own message intact.
59
+ *
60
+ * `schema` is the same object the tool declares as its `parameters`, and
61
+ * `args` the arguments the call carried.
62
+ */
63
+ export function checkArgumentValues(toolName, schema, args) {
64
+ const root = nodeOf(schema);
65
+ const properties = nodeOf(root?.properties);
66
+ const input = nodeOf(args);
67
+ if (!root || !properties || !input)
68
+ return;
69
+ // A required field with a stated purpose: say both, once.
70
+ if (Array.isArray(root.required)) {
71
+ for (const key of root.required) {
72
+ if (typeof key !== "string")
73
+ continue;
74
+ const value = input[key];
75
+ if (value !== undefined && value !== null)
76
+ continue;
77
+ const purpose = nodeOf(properties[key])?.description;
78
+ if (typeof purpose !== "string" || purpose.length === 0)
79
+ continue;
80
+ throw new Error(`${toolName}: ${key} is required (${purpose})`);
81
+ }
82
+ }
83
+ // A value outside its declared list: name the list.
84
+ for (const [key, raw] of Object.entries(input)) {
85
+ if (typeof raw !== "string")
86
+ continue;
87
+ const values = acceptedValues(properties[key]);
88
+ if (values.length === 0 || values.includes(raw))
89
+ continue;
90
+ throw new Error(`${toolName}: ${key} ${quoted(raw)} is not accepted. Accepted: ${values
91
+ .map(quoted)
92
+ .join(", ")}`);
93
+ }
94
+ }
95
+ //# sourceMappingURL=argument-report.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.1",
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",
@@ -23,6 +23,7 @@
23
23
  "LICENSE",
24
24
  "AGENTS.md",
25
25
  "CONTRIBUTING.md",
26
+ "CHANGELOG.md",
26
27
  "TOOLS.md",
27
28
  "build-info.json"
28
29
  ],
@@ -66,8 +67,8 @@
66
67
  "release:local": "node scripts/publish-local.mjs",
67
68
  "publish:local": "node scripts/publish-local.mjs",
68
69
  "dev:link": "npm link && cd ~/.pi/agent/local-packages && npm link pi-braid",
69
- "prepack": "npm run build && node scripts/pack-provenance.mjs write",
70
- "postpack": "node scripts/pack-provenance.mjs remove"
70
+ "prepack": "npm run build && node scripts/stage-changelog.mjs write && node scripts/pack-provenance.mjs write",
71
+ "postpack": "node scripts/pack-provenance.mjs remove && node scripts/stage-changelog.mjs remove"
71
72
  },
72
73
  "devDependencies": {
73
74
  "@eslint/js": "10.0.1",
@@ -16,6 +16,7 @@ import {
16
16
  DEPTH_LEVELS,
17
17
  } from "./think-budget.js";
18
18
  import { criticGate } from "../../../../lib/ai/critic-gate.js";
19
+ import { checkArgumentValues } from "../../../../lib/utils/argument-report.js";
19
20
  import { getExtensionState } from "../../../../lib/state/extension-state.js";
20
21
  import { createLogger } from "../../../../lib/core/logger.js";
21
22
 
@@ -213,6 +214,14 @@ export function createThinkTool(): ToolDefinition<any, any, any> {
213
214
  description: "Think deeply with structured reasoning before making high-stakes decisions.",
214
215
  promptSnippet: "Think deeply with structured reasoning before decisions",
215
216
  parameters: thinkSchema,
217
+ // pi validates arguments before `execute` is reached, and its own refusal
218
+ // for a guessed enum or a missing field names neither. This hook runs
219
+ // first, inside the same guarded block, and refuses with the values the
220
+ // schema above already declares.
221
+ prepareArguments: (args: unknown) => {
222
+ checkArgumentValues("think", thinkSchema, args);
223
+ return args;
224
+ },
216
225
  execute: async (
217
226
  _toolCallId: string,
218
227
  params: any,
@@ -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,
@@ -34,6 +34,7 @@
34
34
 
35
35
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
36
36
  import { Type } from "typebox";
37
+ import type { Static } from "typebox";
37
38
  import { createLogger } from "../../../lib/core/logger.js";
38
39
  import { getSkillsRankingMode } from "../../../lib/config/braid-settings.js";
39
40
  import type { SkillsRankingMode } from "../../../lib/config/braid-settings.js";
@@ -55,6 +56,7 @@ import {
55
56
  readSkillReach,
56
57
  } from "./reach.js";
57
58
  import { getMonthlyAdoptionRollup } from "./session-records.js";
59
+ import { checkArgumentValues } from "../../../lib/utils/argument-report.js";
58
60
 
59
61
  const log = createLogger("skills-tool");
60
62
 
@@ -252,6 +254,52 @@ function rowOf(row: RankedSkill): RowRelevance {
252
254
 
253
255
  // Extension factory:
254
256
 
257
+ /**
258
+ * `list_skills` arguments: one action, one page of the catalog.
259
+ *
260
+ * The action is named here rather than inferred, because a pager call and a
261
+ * full-catalog call are the same call and the schema is what the model reads
262
+ * before choosing. The tool fills it when the call omits it (`prepareArguments`
263
+ * below), so a bare pager call behaves as the listing it obviously is while an
264
+ * unknown action is still refused.
265
+ */
266
+ const listSkillsSchema = Type.Object({
267
+ action: Type.Literal("list", {
268
+ description:
269
+ "list = paginated catalog with per-skill reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections)",
270
+ }),
271
+ page: Type.Optional(
272
+ Type.Number({
273
+ minimum: 1,
274
+ default: 1,
275
+ description: "Page number for list (1-based)",
276
+ }),
277
+ ),
278
+ pageSize: Type.Optional(
279
+ Type.Number({
280
+ minimum: 1,
281
+ maximum: 50,
282
+ default: 10,
283
+ description: "Entries per page for list",
284
+ }),
285
+ ),
286
+ sectionsMax: Type.Optional(
287
+ Type.Number({
288
+ minimum: 0,
289
+ maximum: SECTIONS_MAX_LIMIT,
290
+ default: DEFAULT_SECTIONS_MAX,
291
+ description: "Headings reported per skill; 0 omits the section list and keeps sectionCount",
292
+ }),
293
+ ),
294
+ rank: Type.Optional(
295
+ Type.Union([Type.Literal("relevance"), Type.Literal("catalog")], {
296
+ default: "relevance",
297
+ description:
298
+ "relevance (default) = order by fit to the current task; catalog = the plain catalog order, with no ranking fields",
299
+ }),
300
+ ),
301
+ });
302
+
255
303
  export default function skillsToolExtension(pi: ExtensionAPI): void {
256
304
  registerAutoInject(pi);
257
305
 
@@ -260,43 +308,18 @@ export default function skillsToolExtension(pi: ExtensionAPI): void {
260
308
  label: "List Skills",
261
309
  description:
262
310
  "Discover skills on demand: paginated catalog (name, filePath, description, source) plus each skill's reach (reachable, lines, bytes, chars, estTokens, sectionCount, section headings with line numbers), so the price of a read is visible before the read. Rows are ordered by relevance to the current task; a row with match evidence carries relevance {score, reason}, and the response carries ranking {tier, basis, policy}. Pass rank: 'catalog' for the plain catalog order. `read` a SKILL.md to load it.",
263
- parameters: Type.Object({
264
- action: Type.Literal("list", {
265
- description:
266
- "list = paginated catalog with per-skill reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections)",
267
- }),
268
- page: Type.Optional(
269
- Type.Number({
270
- minimum: 1,
271
- default: 1,
272
- description: "Page number for list (1-based)",
273
- }),
274
- ),
275
- pageSize: Type.Optional(
276
- Type.Number({
277
- minimum: 1,
278
- maximum: 50,
279
- default: 10,
280
- description: "Entries per page for list",
281
- }),
282
- ),
283
- sectionsMax: Type.Optional(
284
- Type.Number({
285
- minimum: 0,
286
- maximum: SECTIONS_MAX_LIMIT,
287
- default: DEFAULT_SECTIONS_MAX,
288
- description:
289
- "Headings reported per skill; 0 omits the section list and keeps sectionCount",
290
- }),
291
- ),
292
- rank: Type.Optional(
293
- Type.Union([Type.Literal("relevance"), Type.Literal("catalog")], {
294
- default: "relevance",
295
- description:
296
- "relevance (default) = order by fit to the current task; catalog = the plain catalog order, with no ranking fields",
297
- }),
298
- ),
299
- }),
311
+ parameters: listSkillsSchema,
312
+ // Paging without an action is a listing call: fill the action the call
313
+ // implies before pi validates, and refuse a guessed value with the accepted
314
+ // one named. The schema above stays the only description of the contract.
315
+ prepareArguments: (args: unknown) => {
316
+ const prepared =
317
+ args && typeof args === "object" && (args as { action?: unknown }).action == null
318
+ ? { ...args, action: "list" }
319
+ : args;
320
+ checkArgumentValues("list_skills", listSkillsSchema, prepared);
321
+ return prepared as Static<typeof listSkillsSchema>;
322
+ },
300
323
  execute: async (_id, params, signal, _onUpdate, ctx) => {
301
324
  const page = (params.page as number) ?? 1;
302
325
  const pageSize = (params.pageSize as number) ?? 10;