pi-braid 0.40.3 → 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 +178 -17
  13. package/dist/extensions/core/skills-tool/auto-inject.js +264 -23
  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 +74 -13
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +105 -24
  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 +2 -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 +350 -27
  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 +130 -23
  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",
@@ -8,13 +8,27 @@
8
8
  *
9
9
  * Design:
10
10
  * 1. Relevance detection: keyword match of skill name/description plus
11
- * frontmatter trigger phrases against the user's current prompt.
11
+ * curated trigger phrases against the user's current prompt.
12
12
  * Qualification bar: a skill whose match never touches its NAME (name
13
13
  * token or trigger phrase) must reach a score of at least
14
14
  * MIN_NON_NAME_SCORE — a lone description/path keyword hit is too weak
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 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.
27
+ * 1b. Ranking: equal scores compare by more distinct matched signals, then
28
+ * by rarer evidence (lower summed document frequency), then by name.
29
+ * Alphabetical order alone decided which of two equally-scored skills
30
+ * took a slot, which is how a broadly-matching skill outranked the one
31
+ * whose evidence was the prompt's actual subject.
18
32
  * 2. Session-scoped state: track which skills were injected on which turn.
19
33
  * Cooldown is per-skill on top of the global floor: an injected skill
20
34
  * cools down at least COOLDOWN_TURNS, and once it was actually loaded
@@ -84,6 +98,7 @@
84
98
  * before_agent_start handler.
85
99
  */
86
100
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
101
+ import type { TriggerSource } from "./skill-triggers.js";
87
102
  /**
88
103
  * Max skill suggestions holding a slot at any time.
89
104
  *
@@ -117,6 +132,33 @@ export declare const MAX_EXCERPT_CHARS = 300;
117
132
  * and/or filePath keyword hits only). Name matches qualify at any score.
118
133
  */
119
134
  export declare const MIN_NON_NAME_SCORE = 2;
135
+ /**
136
+ * A keyword present in this many skill documents or more is corpus-common: it
137
+ * appears in a large share of the catalog (5 of 22 skills = 23%), so it cannot
138
+ * distinguish one skill from another and contributes NOTHING to the weak legs
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.
141
+ *
142
+ * The number is measured, not guessed. Two measurements, one threshold:
143
+ *
144
+ * Corpus mass. Over 400 recorded prompts against the 22-skill catalog, the
145
+ * weak-leg points awarded to words by document frequency are df1 17.0%,
146
+ * df2 22.4%, df3 20.9%, df4 13.3%, df5 7.8%, df6 4.1%, df7 9.1%, df9 0.4%,
147
+ * df22 5.1%. Words at df ≥ 5 carry 26.4% of every weak-leg point the matcher
148
+ * awards; df ≥ 4 carries 39.7%, df ≥ 6 carries 18.6%. The catalog's generic
149
+ * vocabulary starts here (skill, read, prompt, text, build, change, agent,
150
+ * line); below it the words still describe work types (review, check, test,
151
+ * edit, documentation).
152
+ *
153
+ * Labelled set. 26 recorded prompts, recall@2 by threshold: df ≥ 4 → 12/23,
154
+ * df ≥ 5 → 13/23, df ≥ 6 → 13/23, df ≥ 7 → 14/23, no gate at all → 12/23.
155
+ * Recall alone cannot choose the number: every step that weakens the gate
156
+ * admits more skills (45, 54, 67, 71, 106 admissions) and admitting more can
157
+ * only raise a top-2 recall figure. 5 is where the gate removes a quarter of
158
+ * the corpus-common mass without also deleting the work-type words that are
159
+ * sometimes a skill's only reachable evidence.
160
+ */
161
+ export declare const COMMON_KEYWORD_DF = 5;
120
162
  export interface InjectedSkill {
121
163
  name: string;
122
164
  turnNumber: number;
@@ -137,6 +179,8 @@ export interface CachedSkill {
137
179
  disableModelInvocation?: boolean;
138
180
  /** Frontmatter trigger phrases (setCachedSkills resolves them from SKILL.md). */
139
181
  triggers?: string[];
182
+ /** Which source authored each phrase (the row's evidence label). */
183
+ triggerSources?: Record<string, TriggerSource>;
140
184
  }
141
185
  /** Called by index.ts's setCachedSkills to keep the auto-inject cache in sync. */
142
186
  export declare function updateSkillCache(skills: CachedSkill[]): void;
@@ -156,49 +200,166 @@ export declare function stemKeyword(word: string): string;
156
200
  * bar (stemming "tasks" lands on the noise word "task", which stays out).
157
201
  */
158
202
  export declare function extractKeywords(text: string): string[];
203
+ /**
204
+ * The text a skill contributes to the corpus-frequency count: its description
205
+ * plus its own catalog path (`<dir>/skill.md`). Deliberately NOT the absolute
206
+ * path: a checkout root puts its own directory names ("private", "packages",
207
+ * a worktree name) in every one of the 22 documents — measured at df 22 for
208
+ * `private`, `package`, `pack` and `core`, and different on every machine the
209
+ * agent runs on. On description plus the skill's own directory those four
210
+ * measure df 0, 1, 1 and 2; `skill` and `kill` stay catalog-wide because the
211
+ * file itself is named SKILL.md, and the rarity gate is what removes them.
212
+ * Lowercased; the matcher tests substrings. Pure.
213
+ */
214
+ export declare function skillCorpusDocument(skill: CachedSkill): string;
215
+ /**
216
+ * Document frequency of each keyword across the cached skills: how many skill
217
+ * documents contain it as a substring (the test every weak leg performs).
218
+ * Computed once per turn from the cache, for the prompt's keywords only. Pure
219
+ * given the cache.
220
+ */
221
+ export declare function corpusKeywordFrequency(keywords: string[], skills: CachedSkill[]): Map<string, number>;
222
+ /** One skill's match against a prompt: points, distinct signals, evidence rarity. */
223
+ export interface SkillMatch {
224
+ /** Score the qualification bar and the ranking read (same scale as before). */
225
+ score: number;
226
+ /** Distinct matched signals: each trigger phrase, each distinct keyword. */
227
+ signals: number;
228
+ /** Summed document frequency of the matched keywords — lower is rarer. */
229
+ evidenceDf: number;
230
+ /** Strongest evidence behind the score; null when the skill did not qualify. */
231
+ reason: RelevanceReason | null;
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";
159
244
  /**
160
245
  * Score a skill against a set of keywords.
161
246
  *
162
247
  * Scoring rules:
163
- * +3 skill name contains a keyword (exact match)
164
- * +2 skill name contains a keyword as substring
165
- * +2 a frontmatter trigger phrase occurs in the prompt (word-bounded)
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
250
+ * +2 a trigger phrase occurs in the prompt (word-bounded)
166
251
  * +1 skill description contains a keyword
167
- * +1 skill filePath contains a keyword (e.g. "research" in "research/SKILL.md")
252
+ * +1 the skill's own catalog path contains a keyword (e.g. "research" in
253
+ * "research/skill.md")
168
254
  *
169
255
  * A trigger hit counts as a name hit: the phrase is the skill author's own
170
256
  * relevance signal, so it qualifies the skill the same way a name match does.
171
257
  *
258
+ * `keywordDf` is the corpus document frequency of the prompt's keywords (see
259
+ * corpusKeywordFrequency). A keyword at COMMON_KEYWORD_DF or above scores
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).
265
+ *
172
266
  * Qualification bar: a skill whose match never touches its NAME (description
173
267
  * and/or filePath hits only) must reach a total score of at least
174
268
  * MIN_NON_NAME_SCORE — one description keyword is too weak a signal and
175
269
  * lets generic skills fire on almost any prompt. Name and trigger matches
176
270
  * always qualify.
177
271
  *
178
- * `promptText` (lowercased by the caller or raw — matching is case-insensitive
179
- * on our side) enables trigger matching; omit it where the raw prompt is not
272
+ * `promptText` enables trigger matching; omit it where the raw prompt is not
180
273
  * available and only keyword scoring should run.
181
274
  *
182
- * Returns 0 if the skill does not qualify.
275
+ * Returns the zero match if the skill does not qualify.
276
+ */
277
+ export declare function matchSkill(skill: CachedSkill, keywords: string[], promptText?: string, keywordDf?: ReadonlyMap<string, number>): SkillMatch;
278
+ /** The score alone (see matchSkill for the rules and the rarity gate). */
279
+ export declare function scoreSkill(skill: CachedSkill, keywords: string[], promptText?: string, keywordDf?: ReadonlyMap<string, number>): number;
280
+ /**
281
+ * A skill with its match evidence, as the selection step consumes it. The
282
+ * evidence fields are optional so a caller holding only a score still selects;
283
+ * they then default to zero and the name stays the tie-breaker.
183
284
  */
184
- export declare function scoreSkill(skill: CachedSkill, keywords: string[], promptText?: string): number;
285
+ export interface ScoredSkill {
286
+ skill: CachedSkill;
287
+ score: number;
288
+ signals?: number;
289
+ evidenceDf?: number;
290
+ }
185
291
  /**
186
292
  * Decide which scored skills to suggest given the session injection state.
293
+ *
187
294
  * Pure — mirrors the handler's decision path so it can be unit-tested:
188
- * sort (score desc, name asc) → cooldown filter (global floor + per-skill
189
- * loaded extension) → slot budget over ACTIVE held slots (a loaded skill
190
- * released its slot) → top-N slice.
295
+ * sort (score desc, distinct signals desc, evidence df asc, name asc) →
296
+ * cooldown filter (global floor + per-skill loaded extension) → slot budget
297
+ * over ACTIVE held slots (a loaded skill released its slot) → top-N slice.
298
+ *
299
+ * The rank order is the fix for alphabetical slot allocation: two skills with
300
+ * equal points used to be ordered by name, so a broadly-matching skill took
301
+ * the slot from one whose evidence was the prompt's actual subject. Distinct
302
+ * signals separate breadth of match; evidence df separates a match on the
303
+ * prompt's distinctive words from one on its filler.
191
304
  *
192
305
  * Returns the chosen scored items (empty when nothing qualifies). The
193
306
  * caller is responsible for recording the picks in session state.
194
307
  */
195
- export declare function selectSuggestions(scored: Array<{
196
- skill: CachedSkill;
197
- score: number;
198
- }>, injected: InjectedSkill[], currentTurn: number): Array<{
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 {
199
329
  skill: CachedSkill;
200
330
  score: number;
201
- }>;
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;
202
363
  /**
203
364
  * Strip YAML frontmatter from a SKILL.md body. Pure.
204
365
  *