pi-braid 0.40.5 → 0.40.6

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 (85) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +116 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +89 -10
  13. package/dist/extensions/core/skills-tool/auto-inject.js +150 -21
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +47 -10
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +66 -23
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-POLICY.md +8 -0
  49. package/docs/LOCAL_DEV.md +0 -1
  50. package/docs/ROADMAP.md +5 -5
  51. package/docs/SETUP.md +19 -18
  52. package/package.json +1 -1
  53. package/skills/herdr-topology/SKILL.md +6 -1
  54. package/skills/research/SKILL.md +32 -0
  55. package/skills/subagent-orchestration/SKILL.md +2 -2
  56. package/src/extensions/core/agent-environment/index.ts +4 -3
  57. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  58. package/src/extensions/core/prompt-builder/index.ts +12 -7
  59. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  60. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  61. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  62. package/src/extensions/core/skills-tool/auto-inject.ts +196 -24
  63. package/src/extensions/core/skills-tool/index.ts +217 -15
  64. package/src/extensions/core/skills-tool/reach.ts +256 -0
  65. package/src/extensions/core/skills-tool/skill-triggers.ts +90 -20
  66. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  67. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  68. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  69. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  70. package/src/extensions/enforcement/resume-state.ts +127 -0
  71. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  72. package/src/extensions/enforcement/whisper.ts +21 -1
  73. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  74. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  75. package/src/extensions/memory/AGENTS.md +25 -1
  76. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  77. package/src/lib/config/braid-paths.ts +20 -0
  78. package/src/lib/config/braid-settings.ts +46 -0
  79. package/src/lib/detection/context-tiers.ts +186 -13
  80. package/src/lib/events/AGENTS.md +1 -0
  81. package/src/lib/events/turn-boundary.ts +115 -0
  82. package/src/lib/orchestrator/workers.ts +33 -12
  83. package/src/lib/state/global-state.ts +1 -0
  84. package/src/lib/utils/AGENTS.md +1 -1
  85. package/src/types/extension-context.d.ts +22 -79
@@ -1,14 +1,26 @@
1
1
  /**
2
- * Instance Composition: renders the full Instance block (Agent + pi-core
3
- * version, runtime paths, OS/PID, session, extension packages, other pi
4
- * instances) on demand via renderInstance (system_info tool); the prompt
5
- * carries only a compact one-line orientation (version | cwd | session).
6
- * Invariants: "Root" = pi-core's npm package folder; packages come from
7
- * the settings `packages` field (project / user-global, pi-core
8
- * precedence), never a sibling walk; pi-core version resolves from the
9
- * running pi binary; skills+memory live in memory-section.ts / the list_skills
10
- * tool; output
11
- * never contains internal module paths or "->".
2
+ * Instance Composition: two renders over the same gathered data.
3
+ *
4
+ * renderInstance is the full block (versions, runtime paths, OS/PID,
5
+ * session stats, extension packages, other pi instances) served on demand by
6
+ * the system_info tool. renderCompactInstance is the one-line orientation in
7
+ * the system prompt (braid version + install root, model, PID, session id,
8
+ * resource counts).
9
+ *
10
+ * Volatility rule: the system prompt is a cached prefix, so the compact line
11
+ * may carry only process-stable facts. A timestamp, elapsed time, turn count,
12
+ * tool average or context size would rewrite the prefix on every request and
13
+ * cost more than the field is worth; those facts stay in the system_info
14
+ * tool, which is a fresh turn by construction.
15
+ *
16
+ * Invariants: "Core" = pi-core's npm package folder, "braid root" = the
17
+ * loaded pi-braid package folder; packages come from the settings `packages`
18
+ * field (project / user-global, pi-core precedence), never a sibling walk;
19
+ * the pi-core version is pi-core's own `VERSION` export (the library braid is
20
+ * loaded into names the core that is running), with a filesystem walk as the
21
+ * fallback and as the source of the binary/package-folder fields; skills+memory
22
+ * live in memory-section.ts / the list_skills tool; output never contains
23
+ * internal module paths or "->".
12
24
  */
13
25
  import type { PromptSection } from "./section.js";
14
26
  import { type TopLevelExtension } from "./top-level-extensions.js";
@@ -24,6 +36,8 @@ export interface SkillEntry {
24
36
  description?: string;
25
37
  }
26
38
  interface PiVersionInfo {
39
+ /** The running library's own `VERSION`; the package.json version found by
40
+ * the walk only when that export is unavailable. */
27
41
  version: string;
28
42
  root: string;
29
43
  /** Path to the resolved `pi` binary. */
@@ -53,8 +67,17 @@ export interface InstanceContext {
53
67
  /** Exported for system-info-tool — the full Instance data shape. */
54
68
  export interface InstanceData {
55
69
  braidVersion: string;
70
+ /** Folder of the running pi-braid package (where the loaded build lives).
71
+ * Empty when resolution failed. */
72
+ braidRoot: string;
56
73
  /** Resolved pi-core info (version + npm package folder). */
57
74
  pi: PiVersionInfo;
75
+ /** Session model as pi sees it (provider + model id); null when the
76
+ * runtime has no model selected. */
77
+ model: {
78
+ provider: string;
79
+ id: string;
80
+ } | null;
58
81
  /** Userland pi settings directory (~/.pi/agent or
59
82
  * PI_CODING_AGENT_DIR override). The agent uses this to find
60
83
  * its own settings, skills, memory, and session files. */
@@ -95,6 +118,24 @@ export interface InstanceData {
95
118
  */
96
119
  export declare function gatherInstanceData(_pi: ExtensionAPI, ctx: ExtensionContext, instanceCtx: InstanceContext): Promise<InstanceData>;
97
120
  export declare function instanceSection(_pi: ExtensionAPI, ctx: ExtensionContext, instanceCtx: InstanceContext): Promise<PromptSection>;
121
+ /**
122
+ * The compact Instance line for the system prompt.
123
+ *
124
+ * One field per question the agent would otherwise spend a tool call on:
125
+ *
126
+ * Agent which braid and pi-core build is answering?
127
+ * Root which pi-braid folder is loaded (stale local install vs global)?
128
+ * Model which provider/model will the next request go to?
129
+ * PID which OS process is this session, for ps/lock checks?
130
+ * Session which session file holds this transcript?
131
+ * Resources did the skill pack and memory stores load at all?
132
+ *
133
+ * A field answering only "nice to know" does not belong here, and neither
134
+ * does anything volatile: see the volatility rule in the module docstring.
135
+ * The block is process-stable by construction, so it renders byte-identical
136
+ * on every turn and the provider prefix cache holds across the session.
137
+ */
138
+ export declare function renderCompactInstance(d: InstanceData): string;
98
139
  /** Exported for system-info-tool — renders InstanceData to plain text. */
99
140
  export declare function renderInstance(d: InstanceData): Promise<string>;
100
141
  export {};
@@ -1,24 +1,62 @@
1
1
  /**
2
- * Instance Composition: renders the full Instance block (Agent + pi-core
3
- * version, runtime paths, OS/PID, session, extension packages, other pi
4
- * instances) on demand via renderInstance (system_info tool); the prompt
5
- * carries only a compact one-line orientation (version | cwd | session).
6
- * Invariants: "Root" = pi-core's npm package folder; packages come from
7
- * the settings `packages` field (project / user-global, pi-core
8
- * precedence), never a sibling walk; pi-core version resolves from the
9
- * running pi binary; skills+memory live in memory-section.ts / the list_skills
10
- * tool; output
11
- * never contains internal module paths or "->".
2
+ * Instance Composition: two renders over the same gathered data.
3
+ *
4
+ * renderInstance is the full block (versions, runtime paths, OS/PID,
5
+ * session stats, extension packages, other pi instances) served on demand by
6
+ * the system_info tool. renderCompactInstance is the one-line orientation in
7
+ * the system prompt (braid version + install root, model, PID, session id,
8
+ * resource counts).
9
+ *
10
+ * Volatility rule: the system prompt is a cached prefix, so the compact line
11
+ * may carry only process-stable facts. A timestamp, elapsed time, turn count,
12
+ * tool average or context size would rewrite the prefix on every request and
13
+ * cost more than the field is worth; those facts stay in the system_info
14
+ * tool, which is a fresh turn by construction.
15
+ *
16
+ * Invariants: "Core" = pi-core's npm package folder, "braid root" = the
17
+ * loaded pi-braid package folder; packages come from the settings `packages`
18
+ * field (project / user-global, pi-core precedence), never a sibling walk;
19
+ * the pi-core version is pi-core's own `VERSION` export (the library braid is
20
+ * loaded into names the core that is running), with a filesystem walk as the
21
+ * fallback and as the source of the binary/package-folder fields; skills+memory
22
+ * live in memory-section.ts / the list_skills tool; output never contains
23
+ * internal module paths or "->".
12
24
  */
13
25
  import { execSync, spawnSync } from "node:child_process";
14
26
  import { readFileSync, existsSync, realpathSync } from "node:fs";
15
27
  import { dirname, join } from "node:path";
16
28
  import { fileURLToPath } from "node:url";
17
29
  import * as os from "node:os";
18
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
30
+ import { getAgentDir, VERSION as PI_CORE_VERSION } from "@earendil-works/pi-coding-agent";
19
31
  import { discoverTopLevelExtensions } from "./top-level-extensions.js";
20
32
  import { gatherL1Environment } from "../agent-environment/index.js";
33
+ /**
34
+ * The pi-core version of the library braid is loaded into, read from pi-core's
35
+ * own `VERSION` export.
36
+ *
37
+ * Braid is loaded by the harness, so that constant names the core actually
38
+ * running. A filesystem walk cannot answer the same question: the managed
39
+ * install keeps the entrypoint as a regular shell shim at `bin/pi` (so
40
+ * `realpathSync` changes nothing) and the package in a sibling
41
+ * `install/releases/<version>/node_modules` subtree, which no ancestor of
42
+ * `bin/` contains. Null when the export is absent or is not a version, so the
43
+ * caller falls back to the walk.
44
+ */
45
+ function piCoreVersionFromLibrary() {
46
+ const value = typeof PI_CORE_VERSION === "string" ? PI_CORE_VERSION.trim() : "";
47
+ return /^\d+\.\d+\.\d+/.test(value) ? value : null;
48
+ }
49
+ /** The pi-core the current process is running over: the library's `VERSION`
50
+ * for the version, the filesystem walk for the binary and package folder. */
21
51
  function discoverRunningPi() {
52
+ const located = locateRunningPi();
53
+ const libraryVersion = piCoreVersionFromLibrary();
54
+ return libraryVersion ? { ...located, version: libraryVersion } : located;
55
+ }
56
+ /** Walk PATH and the filesystem for the running pi binary and its package
57
+ * folder. Supplies `root` and `binary`, and a version only as the fallback
58
+ * for a runtime where pi-core's `VERSION` export is missing. */
59
+ function locateRunningPi() {
22
60
  // 1. Find the actually-running `pi` binary. We DON'T just call
23
61
  // `which pi` because that follows PATH order and can return a
24
62
  // stale binary from a sibling repo's `node_modules/.bin` (e.g.
@@ -162,7 +200,10 @@ function readBraidVersion() {
162
200
  catch {
163
201
  // fall through
164
202
  }
165
- return { version: "unknown", root: process.cwd() };
203
+ // No cwd fallback: the compact line renders this path as the braid root,
204
+ // and a cwd there would read as a real install while duplicating the
205
+ // pi-injected <cwd>. An unresolved root is the honest value.
206
+ return { version: "unknown", root: "" };
166
207
  }
167
208
  const CACHE_TTL_MS = 5_000;
168
209
  let _otherPiCache = null;
@@ -283,7 +324,7 @@ function discoverOtherPiInstances() {
283
324
  */
284
325
  export async function gatherInstanceData(_pi, ctx, instanceCtx) {
285
326
  const pi = discoverRunningPi();
286
- const braid = readBraidVersion();
327
+ const { version: braidVersion, root: braidRoot } = readBraidVersion();
287
328
  const session = gatherL1Environment(_pi, ctx);
288
329
  const topLevelExtensions = discoverTopLevelExtensions();
289
330
  const osInfo = {
@@ -299,8 +340,10 @@ export async function gatherInstanceData(_pi, ctx, instanceCtx) {
299
340
  };
300
341
  const otherPiInstances = discoverOtherPiInstances();
301
342
  return {
302
- braidVersion: braid.version,
343
+ braidVersion,
344
+ braidRoot,
303
345
  pi,
346
+ model: ctx.model ? { provider: String(ctx.model.provider), id: ctx.model.id } : null,
304
347
  settingsDir: getAgentDir(),
305
348
  os: osInfo,
306
349
  cwd: process.cwd(),
@@ -323,6 +366,36 @@ export async function instanceSection(_pi, ctx, instanceCtx) {
323
366
  render: async () => renderInstance(data),
324
367
  };
325
368
  }
369
+ /**
370
+ * The compact Instance line for the system prompt.
371
+ *
372
+ * One field per question the agent would otherwise spend a tool call on:
373
+ *
374
+ * Agent which braid and pi-core build is answering?
375
+ * Root which pi-braid folder is loaded (stale local install vs global)?
376
+ * Model which provider/model will the next request go to?
377
+ * PID which OS process is this session, for ps/lock checks?
378
+ * Session which session file holds this transcript?
379
+ * Resources did the skill pack and memory stores load at all?
380
+ *
381
+ * A field answering only "nice to know" does not belong here, and neither
382
+ * does anything volatile: see the volatility rule in the module docstring.
383
+ * The block is process-stable by construction, so it renders byte-identical
384
+ * on every turn and the provider prefix cache holds across the session.
385
+ */
386
+ export function renderCompactInstance(d) {
387
+ const model = d.model ? `${d.model.provider}/${d.model.id}` : "(unset)";
388
+ const skills = `${d.skillCount} skill${d.skillCount === 1 ? "" : "s"}`;
389
+ const memories = `${d.memoryCount} memor${d.memoryCount === 1 ? "y" : "ies"}`;
390
+ return [
391
+ `Agent: Braid v${d.braidVersion} (over pi-core v${d.pi.version})`,
392
+ `Root: ${d.braidRoot || "(unknown)"}`,
393
+ `Model: ${model}`,
394
+ `PID: ${d.session.pid}`,
395
+ `Session: ${d.sessionId || "(unknown)"}`,
396
+ `Resources: ${skills}, ${memories}`,
397
+ ].join(" | ");
398
+ }
326
399
  /** Exported for system-info-tool — renders InstanceData to plain text. */
327
400
  export async function renderInstance(d) {
328
401
  const lines = [];
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Extracts the Instance section (Agent version, pi-core version, paths,
5
5
  * OS, session stats, extensions, other instances) from the system prompt
6
- * into a read-on-demand tool. The prompt keeps only a compact one-line
7
- * orientation (version | cwd | session) at the bottom; the full Instance
8
- * block lives here.
6
+ * into a read-on-demand tool. The prompt keeps only the compact one-line
7
+ * orientation (build + install root, model, PID, session, resource counts)
8
+ * at the bottom; the full Instance block lives here.
9
9
  *
10
10
  * This saves ~60-100+ tokens per prompt turn while keeping the data
11
11
  * available when the agent actually needs it.
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Extracts the Instance section (Agent version, pi-core version, paths,
5
5
  * OS, session stats, extensions, other instances) from the system prompt
6
- * into a read-on-demand tool. The prompt keeps only a compact one-line
7
- * orientation (version | cwd | session) at the bottom; the full Instance
8
- * block lives here.
6
+ * into a read-on-demand tool. The prompt keeps only the compact one-line
7
+ * orientation (build + install root, model, PID, session, resource counts)
8
+ * at the bottom; the full Instance block lives here.
9
9
  *
10
10
  * This saves ~60-100+ tokens per prompt turn while keeping the data
11
11
  * available when the agent actually needs it.
@@ -75,7 +75,7 @@ export const TOOL_GUIDELINES = {
75
75
  // ── context-management (alwaysOn) ──
76
76
  set_tool_profile: "when: task scope is known — focused profiles cut prompt noise and token cost; args: lean/research/debugging/browser/deep",
77
77
  // ── skills-tool (default-enabled) ──
78
- list_skills: "when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize; caveat: read the WHOLE SKILL.md before acting in the domain",
78
+ list_skills: "when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize/sectionsMax/rank; caveat: rows arrive ordered by relevance to the current task (rows with evidence carry relevance {score, reason}; the response carries ranking {tier, basis, policy}; rank: catalog for the plain order) and reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections) prices the read — read the WHOLE SKILL.md before acting in the domain",
79
79
  skill_stats: "when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json)",
80
80
  // ── topic-drift (default-enabled) ──
81
81
  topic_drift: "when: multi-part requests — check output against the original ask before responding; args: action check + output; caveat: reset re-anchors the topic",
@@ -15,11 +15,15 @@
15
15
  * a signal: it fires broad skills on almost any prompt.
16
16
  * Keywords are stemmed with one suffix rule (trailing s/es) so plural
17
17
  * prompts hit singular name tokens ("skills" → "skill").
18
- * Corpus-common words are gated out of the weak legs: a word present in
19
- * COMMON_KEYWORD_DF or more of the cached skills' documents cannot tell
20
- * skills apart, so description/path hits from it score nothing. Name and
21
- * trigger hits are never gated — the skill's own identity vocabulary is
22
- * what a prompt naming it looks like.
18
+ * Corpus-common words are gated out of the weak legs AND out of the
19
+ * name leg's prefix hits: a word present in COMMON_KEYWORD_DF or more of
20
+ * the cached skills' documents cannot tell skills apart, so
21
+ * description/path hits from it score nothing. A name hit is word-shaped
22
+ * by construction — a whole name token, or the start of one — so a word
23
+ * buried inside a coined token ("line" in placement-disc**line**) is not
24
+ * a name hit at all. A whole-name-token hit and a trigger hit are never
25
+ * gated: the skill's own identity vocabulary is what a prompt naming it
26
+ * looks like, and a curated phrase is the author's signal.
23
27
  * 1b. Ranking: equal scores compare by more distinct matched signals, then
24
28
  * by rarer evidence (lower summed document frequency), then by name.
25
29
  * Alphabetical order alone decided which of two equally-scored skills
@@ -94,6 +98,7 @@
94
98
  * before_agent_start handler.
95
99
  */
96
100
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
101
+ import type { TriggerSource } from "./skill-triggers.js";
97
102
  /**
98
103
  * Max skill suggestions holding a slot at any time.
99
104
  *
@@ -131,7 +136,8 @@ export declare const MIN_NON_NAME_SCORE = 2;
131
136
  * A keyword present in this many skill documents or more is corpus-common: it
132
137
  * appears in a large share of the catalog (5 of 22 skills = 23%), so it cannot
133
138
  * distinguish one skill from another and contributes NOTHING to the weak legs
134
- * (description, catalog path).
139
+ * (description, catalog path) — or to the name leg's token-prefix rule, the one
140
+ * name hit that can rest on a shared word.
135
141
  *
136
142
  * The number is measured, not guessed. Two measurements, one threshold:
137
143
  *
@@ -173,6 +179,8 @@ export interface CachedSkill {
173
179
  disableModelInvocation?: boolean;
174
180
  /** Frontmatter trigger phrases (setCachedSkills resolves them from SKILL.md). */
175
181
  triggers?: string[];
182
+ /** Which source authored each phrase (the row's evidence label). */
183
+ triggerSources?: Record<string, TriggerSource>;
176
184
  }
177
185
  /** Called by index.ts's setCachedSkills to keep the auto-inject cache in sync. */
178
186
  export declare function updateSkillCache(skills: CachedSkill[]): void;
@@ -219,13 +227,26 @@ export interface SkillMatch {
219
227
  signals: number;
220
228
  /** Summed document frequency of the matched keywords — lower is rarer. */
221
229
  evidenceDf: number;
230
+ /** Strongest evidence behind the score; null when the skill did not qualify. */
231
+ reason: RelevanceReason | null;
222
232
  }
233
+ /**
234
+ * What the strongest evidence for a row was. Short on purpose: a ranking row
235
+ * says "trigger", not a sentence — the reader is choosing a read, not reading
236
+ * an explanation.
237
+ *
238
+ * trigger — an authored phrase from frontmatter or the description tail
239
+ * heading — an authored phrase from a `## trigger:` body heading
240
+ * name — a keyword in the skill's own name
241
+ * description — a description or catalog-path keyword (the weak legs)
242
+ */
243
+ export type RelevanceReason = "trigger" | "heading" | "name" | "description";
223
244
  /**
224
245
  * Score a skill against a set of keywords.
225
246
  *
226
247
  * Scoring rules:
227
- * +3 skill name contains a keyword (exact match)
228
- * +2 skill name contains a keyword as substring
248
+ * +3 skill name carries a keyword as a whole token (exact match)
249
+ * +2 skill name starts a token with a keyword, below the frequency gate
229
250
  * +2 a trigger phrase occurs in the prompt (word-bounded)
230
251
  * +1 skill description contains a keyword
231
252
  * +1 the skill's own catalog path contains a keyword (e.g. "research" in
@@ -236,8 +257,11 @@ export interface SkillMatch {
236
257
  *
237
258
  * `keywordDf` is the corpus document frequency of the prompt's keywords (see
238
259
  * corpusKeywordFrequency). A keyword at COMMON_KEYWORD_DF or above scores
239
- * nothing on the weak legs; passing no map scores every keyword at full weight
240
- * (the pre-rarity behavior, which the unit fixtures pin).
260
+ * nothing on the weak legs, and nothing on the name leg's token-prefix rule:
261
+ * a common word that only starts a token ("line" in "line-counting") is
262
+ * vocabulary the catalog shares, not the skill's own. Passing no map scores
263
+ * every keyword at full weight (the pre-rarity behavior, which the unit
264
+ * fixtures pin).
241
265
  *
242
266
  * Qualification bar: a skill whose match never touches its NAME (description
243
267
  * and/or filePath hits only) must reach a total score of at least
@@ -266,6 +290,7 @@ export interface ScoredSkill {
266
290
  }
267
291
  /**
268
292
  * Decide which scored skills to suggest given the session injection state.
293
+ *
269
294
  * Pure — mirrors the handler's decision path so it can be unit-tested:
270
295
  * sort (score desc, distinct signals desc, evidence df asc, name asc) →
271
296
  * cooldown filter (global floor + per-skill loaded extension) → slot budget
@@ -281,6 +306,60 @@ export interface ScoredSkill {
281
306
  * caller is responsible for recording the picks in session state.
282
307
  */
283
308
  export declare function selectSuggestions(scored: ScoredSkill[], injected: InjectedSkill[], currentTurn: number): ScoredSkill[];
309
+ /**
310
+ * Declared margin: a gap smaller than this between the first and second
311
+ * qualified skill means the top is a coin flip, and the read says so
312
+ * (`thin-margin`) instead of presenting the order as a decision. The number is
313
+ * deliberate, not measured: one description keyword (+1) is exactly the
314
+ * distance the scorer says is too weak to qualify a skill on its own
315
+ * (MIN_NON_NAME_SCORE), so a lead that one extra weak hit could erase is not a
316
+ * lead.
317
+ */
318
+ export declare const RANK_MARGIN_THRESHOLD = 2;
319
+ /**
320
+ * A task text shorter than this cannot carry a ranking signal: a greeting or a
321
+ * two-word nudge names no domain, so the deterministic tier reports itself
322
+ * short rather than confidently wrong.
323
+ */
324
+ export declare const RANK_SHORT_TASK_CHARS = 24;
325
+ /** Why the deterministic tier answered the way it did. */
326
+ export type RankingBasis = "no-task" | "short-task" | "no-score" | "unambiguous" | "tie" | "thin-margin";
327
+ /** One skill as the ranking read consumes it: match evidence plus its label. */
328
+ export interface RankedSkill {
329
+ skill: CachedSkill;
330
+ score: number;
331
+ signals: number;
332
+ evidenceDf: number;
333
+ reason: RelevanceReason | null;
334
+ }
335
+ /** The deterministic tier's whole answer: an ordered list and a verdict on it. */
336
+ export interface DeterministicRanking {
337
+ /** Qualified skills only, best first (the order the whisper ranks by). */
338
+ ranked: RankedSkill[];
339
+ /** True when the list cannot separate its own top — the escalation trigger. */
340
+ ambiguous: boolean;
341
+ basis: RankingBasis;
342
+ }
343
+ /**
344
+ * Rank the catalog against a task text without a model. Pure given the cache.
345
+ *
346
+ * Ordering is the whisper's comparator (score, then distinct signals, then
347
+ * summed evidence df, then name) so the two surfaces can never disagree about
348
+ * which skill is better. `ambiguous` is the one thing the whisper does not
349
+ * need: it decides every turn with slots and cooldowns, while a catalog read
350
+ * shows the whole list and therefore must say when its own top is not decided
351
+ * (a tie or a thin margin) or when the task text could not inform it at all.
352
+ *
353
+ * The verdict:
354
+ * no-task — no task text at all; nothing to rank.
355
+ * short-task — the text carries no significant keyword, or is shorter than
356
+ * RANK_SHORT_TASK_CHARS: nothing here can rank a catalog.
357
+ * no-score — every skill scored zero: unambiguous (nothing applies).
358
+ * tie — the top two score the same: ambiguous.
359
+ * thin-margin — the top two sit closer than RANK_MARGIN_THRESHOLD: ambiguous.
360
+ * unambiguous — one skill leads the field by at least the margin.
361
+ */
362
+ export declare function rankSkillsDeterministic(skills: CachedSkill[], taskText: string): DeterministicRanking;
284
363
  /**
285
364
  * Strip YAML frontmatter from a SKILL.md body. Pure.
286
365
  *