pi-braid 0.40.2 → 0.40.5

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 (29) hide show
  1. package/build-info.json +4 -4
  2. package/dist/extensions/cognitive/metacognition/handlers/claim-verification.js +7 -1
  3. package/dist/extensions/cognitive/metacognition/handlers/finalize.js +20 -0
  4. package/dist/extensions/cognitive/topic-drift/index.js +19 -2
  5. package/dist/extensions/core/prompt-builder/top-level-extensions.d.ts +6 -5
  6. package/dist/extensions/core/prompt-builder/top-level-extensions.js +64 -29
  7. package/dist/extensions/core/skills-tool/auto-inject.d.ts +99 -17
  8. package/dist/extensions/core/skills-tool/auto-inject.js +129 -17
  9. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +37 -13
  10. package/dist/extensions/core/skills-tool/skill-triggers.js +54 -16
  11. package/dist/extensions/memory/context-manager/handlers/tools/context-inspect.js +7 -1
  12. package/dist/extensions/memory/memory-agent-bridge/explore-paths.d.ts +2 -24
  13. package/dist/extensions/memory/memory-agent-bridge/explore-paths.js +33 -2
  14. package/dist/extensions/scheduling/timer/index.js +9 -1
  15. package/dist/extensions/self/error-tracking/index.js +8 -1
  16. package/dist/extensions/self/health-maintenance/handlers/session-health-tool.js +9 -2
  17. package/package.json +2 -1
  18. package/src/extensions/cognitive/metacognition/handlers/claim-verification.ts +8 -1
  19. package/src/extensions/cognitive/metacognition/handlers/finalize.ts +21 -0
  20. package/src/extensions/cognitive/topic-drift/index.ts +20 -2
  21. package/src/extensions/core/prompt-builder/AGENTS.md +1 -1
  22. package/src/extensions/core/prompt-builder/top-level-extensions.ts +68 -29
  23. package/src/extensions/core/skills-tool/auto-inject.ts +170 -19
  24. package/src/extensions/core/skills-tool/skill-triggers.ts +53 -16
  25. package/src/extensions/memory/context-manager/handlers/tools/context-inspect.ts +8 -1
  26. package/src/extensions/memory/memory-agent-bridge/explore-paths.ts +37 -3
  27. package/src/extensions/scheduling/timer/index.ts +10 -1
  28. package/src/extensions/self/error-tracking/index.ts +9 -1
  29. package/src/extensions/self/health-maintenance/handlers/session-health-tool.ts +10 -2
@@ -8,13 +8,23 @@
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: 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.
23
+ * 1b. Ranking: equal scores compare by more distinct matched signals, then
24
+ * by rarer evidence (lower summed document frequency), then by name.
25
+ * Alphabetical order alone decided which of two equally-scored skills
26
+ * took a slot, which is how a broadly-matching skill outranked the one
27
+ * whose evidence was the prompt's actual subject.
18
28
  * 2. Session-scoped state: track which skills were injected on which turn.
19
29
  * Cooldown is per-skill on top of the global floor: an injected skill
20
30
  * cools down at least COOLDOWN_TURNS, and once it was actually loaded
@@ -130,6 +140,32 @@ export const MAX_EXCERPT_CHARS = 300;
130
140
  * and/or filePath keyword hits only). Name matches qualify at any score.
131
141
  */
132
142
  export const MIN_NON_NAME_SCORE = 2;
143
+ /**
144
+ * A keyword present in this many skill documents or more is corpus-common: it
145
+ * appears in a large share of the catalog (5 of 22 skills = 23%), so it cannot
146
+ * distinguish one skill from another and contributes NOTHING to the weak legs
147
+ * (description, catalog path).
148
+ *
149
+ * The number is measured, not guessed. Two measurements, one threshold:
150
+ *
151
+ * Corpus mass. Over 400 recorded prompts against the 22-skill catalog, the
152
+ * weak-leg points awarded to words by document frequency are df1 17.0%,
153
+ * df2 22.4%, df3 20.9%, df4 13.3%, df5 7.8%, df6 4.1%, df7 9.1%, df9 0.4%,
154
+ * df22 5.1%. Words at df ≥ 5 carry 26.4% of every weak-leg point the matcher
155
+ * awards; df ≥ 4 carries 39.7%, df ≥ 6 carries 18.6%. The catalog's generic
156
+ * vocabulary starts here (skill, read, prompt, text, build, change, agent,
157
+ * line); below it the words still describe work types (review, check, test,
158
+ * edit, documentation).
159
+ *
160
+ * Labelled set. 26 recorded prompts, recall@2 by threshold: df ≥ 4 → 12/23,
161
+ * df ≥ 5 → 13/23, df ≥ 6 → 13/23, df ≥ 7 → 14/23, no gate at all → 12/23.
162
+ * Recall alone cannot choose the number: every step that weakens the gate
163
+ * admits more skills (45, 54, 67, 71, 106 admissions) and admitting more can
164
+ * only raise a top-2 recall figure. 5 is where the gate removes a quarter of
165
+ * the corpus-common mass without also deleting the work-type words that are
166
+ * sometimes a skill's only reachable evidence.
167
+ */
168
+ export const COMMON_KEYWORD_DF = 5;
133
169
  /**
134
170
  * Common English words to exclude from keyword matching.
135
171
  * Kept small — only the most frequent noise words that would
@@ -237,76 +273,146 @@ export function extractKeywords(text) {
237
273
  return [...new Set(words)];
238
274
  }
239
275
  // Relevance Scoring
276
+ /**
277
+ * The text a skill contributes to the corpus-frequency count: its description
278
+ * plus its own catalog path (`<dir>/skill.md`). Deliberately NOT the absolute
279
+ * path: a checkout root puts its own directory names ("private", "packages",
280
+ * a worktree name) in every one of the 22 documents — measured at df 22 for
281
+ * `private`, `package`, `pack` and `core`, and different on every machine the
282
+ * agent runs on. On description plus the skill's own directory those four
283
+ * measure df 0, 1, 1 and 2; `skill` and `kill` stay catalog-wide because the
284
+ * file itself is named SKILL.md, and the rarity gate is what removes them.
285
+ * Lowercased; the matcher tests substrings. Pure.
286
+ */
287
+ export function skillCorpusDocument(skill) {
288
+ const tail = skill.filePath.toLowerCase().split(/[\\/]/).filter(Boolean).slice(-2).join("/");
289
+ return `${skill.description.toLowerCase()} ${tail}`;
290
+ }
291
+ /**
292
+ * Document frequency of each keyword across the cached skills: how many skill
293
+ * documents contain it as a substring (the test every weak leg performs).
294
+ * Computed once per turn from the cache, for the prompt's keywords only. Pure
295
+ * given the cache.
296
+ */
297
+ export function corpusKeywordFrequency(keywords, skills) {
298
+ const docs = skills.map(skillCorpusDocument);
299
+ const freq = new Map();
300
+ for (const kw of keywords) {
301
+ let n = 0;
302
+ for (const doc of docs)
303
+ if (doc.includes(kw))
304
+ n++;
305
+ freq.set(kw, n);
306
+ }
307
+ return freq;
308
+ }
309
+ const NO_MATCH = { score: 0, signals: 0, evidenceDf: 0 };
240
310
  /**
241
311
  * Score a skill against a set of keywords.
242
312
  *
243
313
  * Scoring rules:
244
314
  * +3 skill name contains a keyword (exact match)
245
315
  * +2 skill name contains a keyword as substring
246
- * +2 a frontmatter trigger phrase occurs in the prompt (word-bounded)
316
+ * +2 a trigger phrase occurs in the prompt (word-bounded)
247
317
  * +1 skill description contains a keyword
248
- * +1 skill filePath contains a keyword (e.g. "research" in "research/SKILL.md")
318
+ * +1 the skill's own catalog path contains a keyword (e.g. "research" in
319
+ * "research/skill.md")
249
320
  *
250
321
  * A trigger hit counts as a name hit: the phrase is the skill author's own
251
322
  * relevance signal, so it qualifies the skill the same way a name match does.
252
323
  *
324
+ * `keywordDf` is the corpus document frequency of the prompt's keywords (see
325
+ * corpusKeywordFrequency). A keyword at COMMON_KEYWORD_DF or above scores
326
+ * nothing on the weak legs; passing no map scores every keyword at full weight
327
+ * (the pre-rarity behavior, which the unit fixtures pin).
328
+ *
253
329
  * Qualification bar: a skill whose match never touches its NAME (description
254
330
  * and/or filePath hits only) must reach a total score of at least
255
331
  * MIN_NON_NAME_SCORE — one description keyword is too weak a signal and
256
332
  * lets generic skills fire on almost any prompt. Name and trigger matches
257
333
  * always qualify.
258
334
  *
259
- * `promptText` (lowercased by the caller or raw — matching is case-insensitive
260
- * on our side) enables trigger matching; omit it where the raw prompt is not
335
+ * `promptText` enables trigger matching; omit it where the raw prompt is not
261
336
  * available and only keyword scoring should run.
262
337
  *
263
- * Returns 0 if the skill does not qualify.
338
+ * Returns the zero match if the skill does not qualify.
264
339
  */
265
- export function scoreSkill(skill, keywords, promptText) {
340
+ export function matchSkill(skill, keywords, promptText, keywordDf) {
266
341
  let score = 0;
342
+ let signals = 0;
343
+ let evidenceDf = 0;
267
344
  let nameHit = false;
268
345
  const name = skill.name.toLowerCase();
269
346
  const desc = skill.description.toLowerCase();
270
- const path = skill.filePath.toLowerCase();
347
+ const path = skill.filePath.toLowerCase().split(/[\\/]/).filter(Boolean).slice(-2).join("/");
348
+ const dfOf = (kw) => keywordDf?.get(kw) ?? 0;
271
349
  for (const trig of skill.triggers ?? []) {
272
350
  if (triggerMatches(trig, promptText ?? "")) {
273
351
  score += 2;
352
+ signals++;
274
353
  nameHit = true;
354
+ // A curated phrase is the rarest evidence a skill can offer: df 0.
275
355
  }
276
356
  }
277
357
  for (const kw of keywords) {
358
+ const df = dfOf(kw);
278
359
  // Exact token match in name
279
360
  if (name.split(/[^a-z0-9]+/).includes(kw)) {
280
361
  score += 3;
362
+ signals++;
281
363
  nameHit = true;
364
+ evidenceDf += df;
282
365
  continue;
283
366
  }
284
367
  // Substring match in name (catches compound names like "code-search")
285
368
  if (name.includes(kw)) {
286
369
  score += 2;
370
+ signals++;
287
371
  nameHit = true;
372
+ evidenceDf += df;
288
373
  continue;
289
374
  }
290
- // Description contains keyword
375
+ // Corpus-common keyword: the weak legs score nothing for it, so a prompt
376
+ // full of generic vocabulary cannot buy a slot.
377
+ if (df >= COMMON_KEYWORD_DF)
378
+ continue;
379
+ let weakHit = false;
291
380
  if (desc.includes(kw)) {
292
381
  score += 1;
293
- continue;
382
+ weakHit = true;
294
383
  }
295
384
  // File path matches (e.g. "research" in "research/SKILL.md")
296
385
  if (path.includes(kw)) {
297
386
  score += 1;
387
+ weakHit = true;
388
+ }
389
+ // One signal per distinct keyword: a word present in both the description
390
+ // and the path is one piece of evidence, not two.
391
+ if (weakHit) {
392
+ signals++;
393
+ evidenceDf += df;
298
394
  }
299
395
  }
300
396
  if (!nameHit && score < MIN_NON_NAME_SCORE)
301
- return 0;
302
- return score;
397
+ return NO_MATCH;
398
+ return { score, signals, evidenceDf };
399
+ }
400
+ /** The score alone (see matchSkill for the rules and the rarity gate). */
401
+ export function scoreSkill(skill, keywords, promptText, keywordDf) {
402
+ return matchSkill(skill, keywords, promptText, keywordDf).score;
303
403
  }
304
404
  /**
305
405
  * Decide which scored skills to suggest given the session injection state.
306
406
  * Pure — mirrors the handler's decision path so it can be unit-tested:
307
- * sort (score desc, name asc) → cooldown filter (global floor + per-skill
308
- * loaded extension) → slot budget over ACTIVE held slots (a loaded skill
309
- * released its slot) → top-N slice.
407
+ * sort (score desc, distinct signals desc, evidence df asc, name asc) →
408
+ * cooldown filter (global floor + per-skill loaded extension) → slot budget
409
+ * over ACTIVE held slots (a loaded skill released its slot) → top-N slice.
410
+ *
411
+ * The rank order is the fix for alphabetical slot allocation: two skills with
412
+ * equal points used to be ordered by name, so a broadly-matching skill took
413
+ * the slot from one whose evidence was the prompt's actual subject. Distinct
414
+ * signals separate breadth of match; evidence df separates a match on the
415
+ * prompt's distinctive words from one on its filler.
310
416
  *
311
417
  * Returns the chosen scored items (empty when nothing qualifies). The
312
418
  * caller is responsible for recording the picks in session state.
@@ -314,7 +420,10 @@ export function scoreSkill(skill, keywords, promptText) {
314
420
  export function selectSuggestions(scored, injected, currentTurn) {
315
421
  if (!scored.length)
316
422
  return [];
317
- const sorted = [...scored].sort((a, b) => b.score - a.score || a.skill.name.localeCompare(b.skill.name));
423
+ const sorted = [...scored].sort((a, b) => b.score - a.score ||
424
+ (b.signals ?? 0) - (a.signals ?? 0) ||
425
+ (a.evidenceDf ?? 0) - (b.evidenceDf ?? 0) ||
426
+ a.skill.name.localeCompare(b.skill.name));
318
427
  const available = sorted.filter((s) => !onCooldown(s.skill.name, injected, currentTurn));
319
428
  if (!available.length)
320
429
  return [];
@@ -762,9 +871,12 @@ export function registerAutoInject(pi) {
762
871
  if (!keywords.length) {
763
872
  return; // No significant keywords to match
764
873
  }
874
+ // Corpus-common words cannot tell skills apart. Their document frequency
875
+ // is measured once per turn from the same cache the scorer reads.
876
+ const keywordDf = corpusKeywordFrequency(keywords, skills);
765
877
  // Score each skill. The raw prompt rides along for trigger matching.
766
878
  const scored = skills
767
- .map((s) => ({ skill: s, score: scoreSkill(s, keywords, prompt) }))
879
+ .map((s) => ({ skill: s, ...matchSkill(s, keywords, prompt, keywordDf) }))
768
880
  .filter((s) => s.score > 0);
769
881
  if (!scored.length) {
770
882
  return; // No relevant skills found
@@ -1,18 +1,36 @@
1
1
  /**
2
- * Frontmatter `triggers:` phrases for the suggestion matcher.
2
+ * Curated trigger phrases for the suggestion matcher.
3
3
  *
4
4
  * pi's skill objects carry a fixed shape (name, description, path, source),
5
5
  * so curated trigger phrases never reach braid through the prompt-builder
6
- * cache — read them from the SKILL.md frontmatter directly. Reads are
7
- * memoized by file mtime + size: repeated turns stat, only changed or
8
- * first-seen files parse.
6
+ * cache — read them from the SKILL.md itself. Reads are memoized by file
7
+ * mtime + size: repeated turns stat, only changed or first-seen files parse.
8
+ *
9
+ * Authors wrote the phrases in three places, and all three are read:
10
+ * 1. frontmatter, under `trigger:` (a comma-separated string) or
11
+ * `triggers:` (a YAML list) — the canonical field;
12
+ * 2. a `## trigger:` body heading, quoted or bare (9 of core's 22 skills
13
+ * carry the phrases here and nowhere else);
14
+ * 3. the description's trailing "Triggers: …" segment, the pack's older
15
+ * convention.
16
+ * A file may use any of them; the first source that yields phrases wins, so
17
+ * the frontmatter stays authoritative and a body heading never silently
18
+ * overrides it.
9
19
  *
10
20
  * A trigger hit scores like a name hit and qualifies a skill whose
11
21
  * description alone would stay under the qualification bar — the phrase is
12
22
  * the author's own signal of when the skill applies, sharper than any
13
- * description keyword.
23
+ * description keyword. Matching is case-insensitive: prompts arrive
24
+ * capitalized ("MASTERSHIP TRANSFER: …"), and a phrase that only matched
25
+ * lowercase text would be dead in production while a lowercase-only unit
26
+ * fixture kept the suite green.
27
+ */
28
+ /**
29
+ * Max trigger phrases read per skill — a longer list is an authoring bug, not a
30
+ * matcher input. Two authored lists reach the cap (braid-reference 16,
31
+ * pi-reference 15), so their tail phrases are not read: raising the cap needs
32
+ * the assertion in test-skill-decision.mjs changed with it.
14
33
  */
15
- /** Max trigger phrases read per skill — a longer list is an authoring bug, not a matcher input. */
16
34
  export declare const MAX_TRIGGERS = 12;
17
35
  /** Max characters of one trigger phrase. */
18
36
  export declare const MAX_TRIGGER_CHARS = 64;
@@ -23,14 +41,19 @@ export declare const MAX_TRIGGER_CHARS = 64;
23
41
  */
24
42
  export declare function normalizeTriggers(value: unknown): string[];
25
43
  /**
26
- * Read a skill's trigger phrases: frontmatter `triggers:` first (canonical),
27
- * then the description's trailing "Triggers: …" segment — the pack's existing
28
- * convention (7 of 32 skills carry one) predates the frontmatter field, and
29
- * the matcher should honor what authors already wrote. Missing/unreadable
30
- * file or malformed YAML → no triggers (the matcher falls back to
31
- * name/description scoring alone). Memoized: unchanged files never re-read.
44
+ * Read a skill's trigger phrases: frontmatter (`trigger` or `triggers`) first,
45
+ * then a `## trigger:` body heading, then the description's trailing
46
+ * "Triggers: …" segment. Missing/unreadable file or malformed YAML → no
47
+ * triggers (the matcher falls back to name/description scoring alone).
48
+ * Memoized: unchanged files never re-read.
32
49
  */
33
50
  export declare function readSkillTriggers(filePath: string, description?: string): string[];
51
+ /**
52
+ * Trigger phrases from a body `## trigger: "a, b, c"` heading. The FIRST such
53
+ * heading is the whole input: a body with several is an authoring error, not
54
+ * extra matcher input. Quotes around the value are stripped. Pure.
55
+ */
56
+ export declare function parseBodyTriggers(body: string): string[];
34
57
  /**
35
58
  * Trigger phrases from a description's trailing "Triggers: …" segment —
36
59
  * the contrib pack convention ("… Use when X. Triggers: meme, image macro.").
@@ -42,7 +65,8 @@ export declare function clearSkillTriggerCache(): void;
42
65
  /**
43
66
  * True when the phrase occurs in the prompt on word boundaries ("pane" does
44
67
  * not match "paneled"). Multi-word phrases match literally; hyphenated
45
- * prompt tokens count as boundaries.
68
+ * prompt tokens count as boundaries. Phrases are normalized to lowercase, so
69
+ * the prompt is folded to match: the boundary classes stay lowercase-only.
46
70
  */
47
71
  export declare function triggerMatches(phrase: string, promptText: string): boolean;
48
72
  //# sourceMappingURL=skill-triggers.d.ts.map
@@ -1,20 +1,38 @@
1
1
  /**
2
- * Frontmatter `triggers:` phrases for the suggestion matcher.
2
+ * Curated trigger phrases for the suggestion matcher.
3
3
  *
4
4
  * pi's skill objects carry a fixed shape (name, description, path, source),
5
5
  * so curated trigger phrases never reach braid through the prompt-builder
6
- * cache — read them from the SKILL.md frontmatter directly. Reads are
7
- * memoized by file mtime + size: repeated turns stat, only changed or
8
- * first-seen files parse.
6
+ * cache — read them from the SKILL.md itself. Reads are memoized by file
7
+ * mtime + size: repeated turns stat, only changed or first-seen files parse.
8
+ *
9
+ * Authors wrote the phrases in three places, and all three are read:
10
+ * 1. frontmatter, under `trigger:` (a comma-separated string) or
11
+ * `triggers:` (a YAML list) — the canonical field;
12
+ * 2. a `## trigger:` body heading, quoted or bare (9 of core's 22 skills
13
+ * carry the phrases here and nowhere else);
14
+ * 3. the description's trailing "Triggers: …" segment, the pack's older
15
+ * convention.
16
+ * A file may use any of them; the first source that yields phrases wins, so
17
+ * the frontmatter stays authoritative and a body heading never silently
18
+ * overrides it.
9
19
  *
10
20
  * A trigger hit scores like a name hit and qualifies a skill whose
11
21
  * description alone would stay under the qualification bar — the phrase is
12
22
  * the author's own signal of when the skill applies, sharper than any
13
- * description keyword.
23
+ * description keyword. Matching is case-insensitive: prompts arrive
24
+ * capitalized ("MASTERSHIP TRANSFER: …"), and a phrase that only matched
25
+ * lowercase text would be dead in production while a lowercase-only unit
26
+ * fixture kept the suite green.
14
27
  */
15
28
  import { statSync, readFileSync } from "node:fs";
16
29
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
17
- /** Max trigger phrases read per skill — a longer list is an authoring bug, not a matcher input. */
30
+ /**
31
+ * Max trigger phrases read per skill — a longer list is an authoring bug, not a
32
+ * matcher input. Two authored lists reach the cap (braid-reference 16,
33
+ * pi-reference 15), so their tail phrases are not read: raising the cap needs
34
+ * the assertion in test-skill-decision.mjs changed with it.
35
+ */
18
36
  export const MAX_TRIGGERS = 12;
19
37
  /** Max characters of one trigger phrase. */
20
38
  export const MAX_TRIGGER_CHARS = 64;
@@ -42,12 +60,11 @@ export function normalizeTriggers(value) {
42
60
  return cleaned;
43
61
  }
44
62
  /**
45
- * Read a skill's trigger phrases: frontmatter `triggers:` first (canonical),
46
- * then the description's trailing "Triggers: …" segment — the pack's existing
47
- * convention (7 of 32 skills carry one) predates the frontmatter field, and
48
- * the matcher should honor what authors already wrote. Missing/unreadable
49
- * file or malformed YAML → no triggers (the matcher falls back to
50
- * name/description scoring alone). Memoized: unchanged files never re-read.
63
+ * Read a skill's trigger phrases: frontmatter (`trigger` or `triggers`) first,
64
+ * then a `## trigger:` body heading, then the description's trailing
65
+ * "Triggers: …" segment. Missing/unreadable file or malformed YAML → no
66
+ * triggers (the matcher falls back to name/description scoring alone).
67
+ * Memoized: unchanged files never re-read.
51
68
  */
52
69
  export function readSkillTriggers(filePath, description) {
53
70
  let st;
@@ -63,8 +80,13 @@ export function readSkillTriggers(filePath, description) {
63
80
  return cached.triggers;
64
81
  let triggers;
65
82
  try {
66
- const { frontmatter } = parseFrontmatter(readFileSync(filePath, "utf-8"));
67
- triggers = normalizeTriggers(frontmatter.triggers);
83
+ const { frontmatter, body } = parseFrontmatter(readFileSync(filePath, "utf-8"));
84
+ const fm = frontmatter;
85
+ triggers = normalizeTriggers(fm.trigger);
86
+ if (!triggers.length)
87
+ triggers = normalizeTriggers(fm.triggers);
88
+ if (!triggers.length)
89
+ triggers = parseBodyTriggers(body);
68
90
  }
69
91
  catch {
70
92
  triggers = []; // malformed frontmatter — score on name/description only
@@ -74,6 +96,21 @@ export function readSkillTriggers(filePath, description) {
74
96
  cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, triggers });
75
97
  return triggers;
76
98
  }
99
+ /** First `## trigger:` / `## triggers:` heading; a heading-shaped line cannot come from frontmatter. */
100
+ const BODY_TRIGGER_HEADING = /^##\s*triggers?\s*:\s*(.*)$/i;
101
+ /**
102
+ * Trigger phrases from a body `## trigger: "a, b, c"` heading. The FIRST such
103
+ * heading is the whole input: a body with several is an authoring error, not
104
+ * extra matcher input. Quotes around the value are stripped. Pure.
105
+ */
106
+ export function parseBodyTriggers(body) {
107
+ for (const line of body.split(/\r?\n/)) {
108
+ const match = BODY_TRIGGER_HEADING.exec(line);
109
+ if (match)
110
+ return normalizeTriggers(match[1].trim().replace(/^["']|["']$/g, ""));
111
+ }
112
+ return [];
113
+ }
77
114
  /**
78
115
  * Trigger phrases from a description's trailing "Triggers: …" segment —
79
116
  * the contrib pack convention ("… Use when X. Triggers: meme, image macro.").
@@ -99,7 +136,8 @@ export function clearSkillTriggerCache() {
99
136
  /**
100
137
  * True when the phrase occurs in the prompt on word boundaries ("pane" does
101
138
  * not match "paneled"). Multi-word phrases match literally; hyphenated
102
- * prompt tokens count as boundaries.
139
+ * prompt tokens count as boundaries. Phrases are normalized to lowercase, so
140
+ * the prompt is folded to match: the boundary classes stay lowercase-only.
103
141
  */
104
142
  export function triggerMatches(phrase, promptText) {
105
143
  let re = regexCache.get(phrase);
@@ -108,6 +146,6 @@ export function triggerMatches(phrase, promptText) {
108
146
  re = new RegExp(`(?:^|[^a-z0-9])${escaped}(?:$|[^a-z0-9])`);
109
147
  regexCache.set(phrase, re);
110
148
  }
111
- return re.test(promptText);
149
+ return re.test(promptText.toLowerCase());
112
150
  }
113
151
  //# sourceMappingURL=skill-triggers.js.map
@@ -12,6 +12,10 @@ import { CONTEXT_COMPACT_REFUSE_PERCENT } from "../../../../../lib/detection/con
12
12
  import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
13
13
  import { readExtensionState } from "../../../../../lib/state/extension-state.js";
14
14
  import { formatPendingCompactionsLine, readPendingCompactions } from "./context-compress.js";
15
+ /** A numeric selector read as absent when it names no positive count. */
16
+ function positiveNumber(v) {
17
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
18
+ }
15
19
  export const contextInspectSchema = Type.Object({
16
20
  detail: Type.Optional(Type.String({
17
21
  enum: ["quick", "detailed", "full", "prune"],
@@ -226,7 +230,9 @@ export function registerContextInspect(pi) {
226
230
  }
227
231
  // PRUNE: Only prune candidates (like context_prune dry-run)
228
232
  if (detail === "prune") {
229
- const minAge = params.minAge ?? 5;
233
+ // "" converts to 0 before the handler, and `age >= 0` admits every
234
+ // candidate: the age filter disabled itself instead of applying 5.
235
+ const minAge = positiveNumber(params.minAge) ?? 5;
230
236
  let candidates = audit.candidates.filter((c) => c.age >= minAge);
231
237
  if (params.toolFilter?.length) {
232
238
  candidates = candidates.filter((c) => c.toolName && params.toolFilter.includes(c.toolName));
@@ -3,28 +3,6 @@
3
3
  *
4
4
  * Self-contained: file-finding helpers + the explore_paths tool.
5
5
  */
6
- import { Type } from "typebox";
7
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- export declare function createExplorePathsTool(): {
9
- name: string;
10
- label: string;
11
- promptSnippet: string;
12
- description: string;
13
- parameters: Type.TObject<{
14
- hypothesis_1: Type.TString;
15
- hypothesis_2: Type.TString;
16
- hypothesis_3: Type.TOptional<Type.TString>;
17
- searchRoot: Type.TOptional<Type.TString>;
18
- }>;
19
- execute: (_toolCallId: string, params: unknown, _signal: unknown, _onUpdate: unknown, ctx: ExtensionContext) => Promise<{
20
- details: {
21
- hypotheses: number;
22
- projectRoot: string;
23
- };
24
- content: {
25
- type: "text";
26
- text: string;
27
- }[];
28
- }>;
29
- };
6
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
7
+ export declare function createExplorePathsTool(): ToolDefinition<any, any, any>;
30
8
  //# sourceMappingURL=explore-paths.d.ts.map
@@ -120,6 +120,9 @@ async function readFileHead(path, lines = 30) {
120
120
  return "(could not read)";
121
121
  }
122
122
  }
123
+ // The two result shapes (a named refusal and a report) carry different
124
+ // details, so the tool declares its own type rather than letting the first
125
+ // return statement narrow every other branch.
123
126
  export function createExplorePathsTool() {
124
127
  return {
125
128
  name: "explore_paths",
@@ -142,11 +145,39 @@ export function createExplorePathsTool() {
142
145
  }),
143
146
  execute: async (_toolCallId, params, _signal, _onUpdate, ctx) => {
144
147
  const { hypothesis_1, hypothesis_2, hypothesis_3, searchRoot } = params;
148
+ // A blank hypothesis names nothing to search. Both are schema-legal
149
+ // (`Type.String()` accepts ""), and the report that followed came back
150
+ // with "No useful keywords found" -- read as "no evidence", not as an
151
+ // unusable call.
152
+ const requiredHypotheses = [
153
+ ["hypothesis_1", hypothesis_1],
154
+ ["hypothesis_2", hypothesis_2],
155
+ ];
156
+ const blankRequired = requiredHypotheses
157
+ .filter(([, value]) => typeof value !== "string" || value.trim().length === 0)
158
+ .map(([name]) => name);
159
+ if (blankRequired.length > 0) {
160
+ const named = blankRequired.map((name) => `'${name}'`).join(" and ");
161
+ return {
162
+ details: { error: "missing_hypothesis", blank: blankRequired },
163
+ content: [
164
+ {
165
+ type: "text",
166
+ text: `explore_paths requires a non-empty ${named}: name a file and a reason, e.g. "The bug might be in src/parser.ts because the offset is never clamped".`,
167
+ },
168
+ ],
169
+ };
170
+ }
145
171
  const searchDir = resolveSearchRoot(searchRoot, ctx?.cwd);
146
172
  const results = [];
147
173
  const hypotheses = [hypothesis_1, hypothesis_2];
148
- if (hypothesis_3)
149
- hypotheses.push(hypothesis_3);
174
+ // An optional third hypothesis is absent when blank; a blank one used to
175
+ // become a report section with an empty title and an empty search.
176
+ const third = typeof hypothesis_3 === "string" && hypothesis_3.trim().length > 0
177
+ ? hypothesis_3
178
+ : undefined;
179
+ if (third)
180
+ hypotheses.push(third);
150
181
  const explorations = hypotheses.map(async (hyp, i) => {
151
182
  const localResults = [];
152
183
  localResults.push(`### Hypothesis ${i + 1}: ${hyp.substring(0, 120)}`);
@@ -51,6 +51,10 @@ import { getTerminalBreakerConfig, getWakeDeliveryAlertConfig, } from "../../../
51
51
  import { getWatchdogWakeDeliveryFeed, setWatchdogWakeDueProvider, } from "../../../lib/state/global-state.js";
52
52
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
53
53
  import { describeFireTiming } from "./fire-timing.js";
54
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
55
+ function optionalString(v) {
56
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
57
+ }
54
58
  /** Get the timer file path for the current process CWD.
55
59
  * Each project CWD has its own timer file for independent timer pools. */
56
60
  function timerFilePath() {
@@ -720,7 +724,11 @@ function createTimerTool(sessionState) {
720
724
  }
721
725
  switch (params?.action) {
722
726
  case "set": {
723
- const { delay_seconds, reason, tag, interval_seconds, count, wake } = params;
727
+ const { delay_seconds, reason, interval_seconds, count, wake } = params;
728
+ // A blank tag is no tag: stored as "" it reads as [] in the list
729
+ // rendering instead of (untagged), and cancelTimersByTag("") would
730
+ // match every blank-tagged timer in the session.
731
+ const tag = optionalString(params.tag);
724
732
  if (tag && !/^[a-zA-Z0-9_-]+$/.test(tag)) {
725
733
  throw new Error(`Invalid tag "${tag}" - use alphanumeric + dash/underscore`);
726
734
  }
@@ -69,6 +69,10 @@ async function captureError(source, message, stack, context) {
69
69
  await saveError(entry);
70
70
  return entry;
71
71
  }
72
+ /** A numeric selector read as absent when it names no positive count. */
73
+ function positiveNumber(v) {
74
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
75
+ }
72
76
  const errorSchema = Type.Object({
73
77
  action: Type.Union([Type.Literal("list"), Type.Literal("get"), Type.Literal("clear"), Type.Literal("stats")], { description: "Action: list | get | clear | stats" }),
74
78
  // list-only
@@ -121,7 +125,10 @@ export default function errorCaptureExtension(pi) {
121
125
  switch (params.action) {
122
126
  case "list": {
123
127
  const entries = await loadErrors();
124
- const limit = params.limit ?? 10;
128
+ // The framework converts "" to 0 before the handler (no `minimum`
129
+ // on the schema), and slice(-0) is slice(0): a blank limit returned
130
+ // every captured error, the opposite of the documented cap.
131
+ const limit = positiveNumber(params.limit) ?? 10;
125
132
  const source = params.source;
126
133
  const unhandledOnly = params.unhandledOnly ?? false;
127
134
  let filtered = entries;
@@ -20,6 +20,10 @@
20
20
  */
21
21
  import { Type } from "typebox";
22
22
  import { getSessionHealth, setSessionHealthMode, } from "../../../enforcement/session-health.js";
23
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
24
+ function optionalString(v) {
25
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
26
+ }
23
27
  const sessionHealthSchema = Type.Object({
24
28
  action: Type.Union([Type.Literal("get"), Type.Literal("diagnose"), Type.Literal("recover")], {
25
29
  description: "Action: get, diagnose (with history), or recover (force reset)",
@@ -119,7 +123,10 @@ export function registerSessionHealthTool(pi) {
119
123
  details,
120
124
  };
121
125
  }
122
- setSessionHealthMode(ctx, "healthy", params.reason);
126
+ // A blank reason is no reason: stored (and echoed) as "" it reads as
127
+ // an audit note the operator never wrote.
128
+ const reason = optionalString(params.reason);
129
+ setSessionHealthMode(ctx, "healthy", reason);
123
130
  const after = getSessionHealth(ctx);
124
131
  const details = {
125
132
  mode: after.mode,
@@ -131,7 +138,7 @@ export function registerSessionHealthTool(pi) {
131
138
  content: [
132
139
  {
133
140
  type: "text",
134
- text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${params.reason ? `\n\nReason: ${params.reason}` : ""}`,
141
+ text: `Session health reset to ${after.mode}.\n\nThe next LLM call will either succeed (staying healthy) or fail (re-entering the appropriate mode).${reason ? `\n\nReason: ${reason}` : ""}`,
135
142
  },
136
143
  ],
137
144
  details,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.40.2",
3
+ "version": "0.40.5",
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",
@@ -86,6 +86,7 @@
86
86
  "pi-package",
87
87
  "pi",
88
88
  "pi-extension",
89
+ "pi-coding-agent",
89
90
  "llm-agent",
90
91
  "cognitive-systems",
91
92
  "enforcement",