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
@@ -1,22 +1,40 @@
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
 
16
29
  import { statSync, readFileSync } from "node:fs";
17
30
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
18
31
 
19
- /** Max trigger phrases read per skill — a longer list is an authoring bug, not a matcher input. */
32
+ /**
33
+ * Max trigger phrases read per skill — a longer list is an authoring bug, not a
34
+ * matcher input. Two authored lists reach the cap (braid-reference 16,
35
+ * pi-reference 15), so their tail phrases are not read: raising the cap needs
36
+ * the assertion in test-skill-decision.mjs changed with it.
37
+ */
20
38
  export const MAX_TRIGGERS = 12;
21
39
 
22
40
  /** Max characters of one trigger phrase. */
@@ -52,12 +70,11 @@ export function normalizeTriggers(value: unknown): string[] {
52
70
  }
53
71
 
54
72
  /**
55
- * Read a skill's trigger phrases: frontmatter `triggers:` first (canonical),
56
- * then the description's trailing "Triggers: …" segment — the pack's existing
57
- * convention (7 of 32 skills carry one) predates the frontmatter field, and
58
- * the matcher should honor what authors already wrote. Missing/unreadable
59
- * file or malformed YAML → no triggers (the matcher falls back to
60
- * name/description scoring alone). Memoized: unchanged files never re-read.
73
+ * Read a skill's trigger phrases: frontmatter (`trigger` or `triggers`) first,
74
+ * then a `## trigger:` body heading, then the description's trailing
75
+ * "Triggers: …" segment. Missing/unreadable file or malformed YAML → no
76
+ * triggers (the matcher falls back to name/description scoring alone).
77
+ * Memoized: unchanged files never re-read.
61
78
  */
62
79
  export function readSkillTriggers(filePath: string, description?: string): string[] {
63
80
  let st;
@@ -71,8 +88,11 @@ export function readSkillTriggers(filePath: string, description?: string): strin
71
88
  if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size) return cached.triggers;
72
89
  let triggers: string[];
73
90
  try {
74
- const { frontmatter } = parseFrontmatter(readFileSync(filePath, "utf-8"));
75
- triggers = normalizeTriggers((frontmatter as Record<string, unknown>).triggers);
91
+ const { frontmatter, body } = parseFrontmatter(readFileSync(filePath, "utf-8"));
92
+ const fm = frontmatter as Record<string, unknown>;
93
+ triggers = normalizeTriggers(fm.trigger);
94
+ if (!triggers.length) triggers = normalizeTriggers(fm.triggers);
95
+ if (!triggers.length) triggers = parseBodyTriggers(body);
76
96
  } catch {
77
97
  triggers = []; // malformed frontmatter — score on name/description only
78
98
  }
@@ -81,6 +101,22 @@ export function readSkillTriggers(filePath: string, description?: string): strin
81
101
  return triggers;
82
102
  }
83
103
 
104
+ /** First `## trigger:` / `## triggers:` heading; a heading-shaped line cannot come from frontmatter. */
105
+ const BODY_TRIGGER_HEADING = /^##\s*triggers?\s*:\s*(.*)$/i;
106
+
107
+ /**
108
+ * Trigger phrases from a body `## trigger: "a, b, c"` heading. The FIRST such
109
+ * heading is the whole input: a body with several is an authoring error, not
110
+ * extra matcher input. Quotes around the value are stripped. Pure.
111
+ */
112
+ export function parseBodyTriggers(body: string): string[] {
113
+ for (const line of body.split(/\r?\n/)) {
114
+ const match = BODY_TRIGGER_HEADING.exec(line);
115
+ if (match) return normalizeTriggers(match[1].trim().replace(/^["']|["']$/g, ""));
116
+ }
117
+ return [];
118
+ }
119
+
84
120
  /**
85
121
  * Trigger phrases from a description's trailing "Triggers: …" segment —
86
122
  * the contrib pack convention ("… Use when X. Triggers: meme, image macro.").
@@ -106,7 +142,8 @@ export function clearSkillTriggerCache(): void {
106
142
  /**
107
143
  * True when the phrase occurs in the prompt on word boundaries ("pane" does
108
144
  * not match "paneled"). Multi-word phrases match literally; hyphenated
109
- * prompt tokens count as boundaries.
145
+ * prompt tokens count as boundaries. Phrases are normalized to lowercase, so
146
+ * the prompt is folded to match: the boundary classes stay lowercase-only.
110
147
  */
111
148
  export function triggerMatches(phrase: string, promptText: string): boolean {
112
149
  let re = regexCache.get(phrase);
@@ -115,5 +152,5 @@ export function triggerMatches(phrase: string, promptText: string): boolean {
115
152
  re = new RegExp(`(?:^|[^a-z0-9])${escaped}(?:$|[^a-z0-9])`);
116
153
  regexCache.set(phrase, re);
117
154
  }
118
- return re.test(promptText);
155
+ return re.test(promptText.toLowerCase());
119
156
  }
@@ -21,6 +21,11 @@ import { formatTokensK } from "../../../../../lib/detection/context-usage.js";
21
21
  import { readExtensionState } from "../../../../../lib/state/extension-state.js";
22
22
  import { formatPendingCompactionsLine, readPendingCompactions } from "./context-compress.js";
23
23
 
24
+ /** A numeric selector read as absent when it names no positive count. */
25
+ function positiveNumber(v: unknown): number | undefined {
26
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
27
+ }
28
+
24
29
  export const contextInspectSchema = Type.Object({
25
30
  detail: Type.Optional(
26
31
  Type.String({
@@ -285,7 +290,9 @@ export function registerContextInspect(pi: ExtensionAPI): void {
285
290
 
286
291
  // PRUNE: Only prune candidates (like context_prune dry-run)
287
292
  if (detail === "prune") {
288
- const minAge = params.minAge ?? 5;
293
+ // "" converts to 0 before the handler, and `age >= 0` admits every
294
+ // candidate: the age filter disabled itself instead of applying 5.
295
+ const minAge = positiveNumber(params.minAge) ?? 5;
289
296
  let candidates = audit.candidates.filter((c: any) => c.age >= minAge);
290
297
  if (params.toolFilter?.length) {
291
298
  candidates = candidates.filter(
@@ -9,7 +9,7 @@ import { promisify } from "node:util";
9
9
  import * as path from "node:path";
10
10
  import * as url from "node:url";
11
11
  import { Type } from "typebox";
12
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import type { ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
13
13
  import { addEvidence } from "../../../lib/store/evidence-pool.js";
14
14
 
15
15
  const execFileAsync = promisify(execFile);
@@ -136,7 +136,10 @@ async function readFileHead(path: string, lines = 30): Promise<string> {
136
136
  }
137
137
  }
138
138
 
139
- export function createExplorePathsTool() {
139
+ // The two result shapes (a named refusal and a report) carry different
140
+ // details, so the tool declares its own type rather than letting the first
141
+ // return statement narrow every other branch.
142
+ export function createExplorePathsTool(): ToolDefinition<any, any, any> {
140
143
  return {
141
144
  name: "explore_paths",
142
145
  label: "Explore Paths",
@@ -178,11 +181,42 @@ export function createExplorePathsTool() {
178
181
  hypothesis_3?: string;
179
182
  searchRoot?: string;
180
183
  };
184
+
185
+ // A blank hypothesis names nothing to search. Both are schema-legal
186
+ // (`Type.String()` accepts ""), and the report that followed came back
187
+ // with "No useful keywords found" -- read as "no evidence", not as an
188
+ // unusable call.
189
+ const requiredHypotheses: Array<[string, unknown]> = [
190
+ ["hypothesis_1", hypothesis_1],
191
+ ["hypothesis_2", hypothesis_2],
192
+ ];
193
+ const blankRequired = requiredHypotheses
194
+ .filter(([, value]) => typeof value !== "string" || value.trim().length === 0)
195
+ .map(([name]) => name);
196
+ if (blankRequired.length > 0) {
197
+ const named = blankRequired.map((name) => `'${name}'`).join(" and ");
198
+ return {
199
+ details: { error: "missing_hypothesis", blank: blankRequired },
200
+ content: [
201
+ {
202
+ type: "text" as const,
203
+ 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".`,
204
+ },
205
+ ],
206
+ };
207
+ }
208
+
181
209
  const searchDir = resolveSearchRoot(searchRoot, ctx?.cwd);
182
210
 
183
211
  const results: string[] = [];
184
212
  const hypotheses = [hypothesis_1, hypothesis_2];
185
- if (hypothesis_3) hypotheses.push(hypothesis_3);
213
+ // An optional third hypothesis is absent when blank; a blank one used to
214
+ // become a report section with an empty title and an empty search.
215
+ const third =
216
+ typeof hypothesis_3 === "string" && hypothesis_3.trim().length > 0
217
+ ? hypothesis_3
218
+ : undefined;
219
+ if (third) hypotheses.push(third);
186
220
 
187
221
  const explorations = hypotheses.map(async (hyp, i) => {
188
222
  const localResults: string[] = [];
@@ -63,6 +63,11 @@ import {
63
63
  import { formatLocalTime } from "../../../lib/utils/local-time.js";
64
64
  import { describeFireTiming } from "./fire-timing.js";
65
65
 
66
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
67
+ function optionalString(v: unknown): string | undefined {
68
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
69
+ }
70
+
66
71
  type PersistedTimer = {
67
72
  id: string;
68
73
  sessionId: string;
@@ -880,7 +885,11 @@ function createTimerTool(sessionState: {
880
885
  }
881
886
  switch (params?.action) {
882
887
  case "set": {
883
- const { delay_seconds, reason, tag, interval_seconds, count, wake } = params;
888
+ const { delay_seconds, reason, interval_seconds, count, wake } = params;
889
+ // A blank tag is no tag: stored as "" it reads as [] in the list
890
+ // rendering instead of (untagged), and cancelTimersByTag("") would
891
+ // match every blank-tagged timer in the session.
892
+ const tag = optionalString(params.tag);
884
893
  if (tag && !/^[a-zA-Z0-9_-]+$/.test(tag)) {
885
894
  throw new Error(`Invalid tag "${tag}" - use alphanumeric + dash/underscore`);
886
895
  }
@@ -100,6 +100,11 @@ async function captureError(
100
100
  return entry;
101
101
  }
102
102
 
103
+ /** A numeric selector read as absent when it names no positive count. */
104
+ function positiveNumber(v: unknown): number | undefined {
105
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
106
+ }
107
+
103
108
  const errorSchema = Type.Object({
104
109
  action: Type.Union(
105
110
  [Type.Literal("list"), Type.Literal("get"), Type.Literal("clear"), Type.Literal("stats")],
@@ -161,7 +166,10 @@ export default function errorCaptureExtension(pi: ExtensionAPI): void {
161
166
  switch (params.action) {
162
167
  case "list": {
163
168
  const entries = await loadErrors();
164
- const limit = params.limit ?? 10;
169
+ // The framework converts "" to 0 before the handler (no `minimum`
170
+ // on the schema), and slice(-0) is slice(0): a blank limit returned
171
+ // every captured error, the opposite of the documented cap.
172
+ const limit = positiveNumber(params.limit) ?? 10;
165
173
  const source = params.source;
166
174
  const unhandledOnly = params.unhandledOnly ?? false;
167
175
 
@@ -28,6 +28,11 @@ import {
28
28
  type SessionHealthState,
29
29
  } from "../../../enforcement/session-health.js";
30
30
 
31
+ /** A blank string is "not provided": a client that emits every schema key sends "" for the unused ones. */
32
+ function optionalString(v: unknown): string | undefined {
33
+ return typeof v === "string" && v.trim().length > 0 ? v : undefined;
34
+ }
35
+
31
36
  const sessionHealthSchema = Type.Object({
32
37
  action: Type.Union([Type.Literal("get"), Type.Literal("diagnose"), Type.Literal("recover")], {
33
38
  description: "Action: get, diagnose (with history), or recover (force reset)",
@@ -143,7 +148,10 @@ export function registerSessionHealthTool(pi: ExtensionAPI): void {
143
148
  details,
144
149
  };
145
150
  }
146
- setSessionHealthMode(ctx, "healthy", params.reason);
151
+ // A blank reason is no reason: stored (and echoed) as "" it reads as
152
+ // an audit note the operator never wrote.
153
+ const reason = optionalString(params.reason);
154
+ setSessionHealthMode(ctx, "healthy", reason);
147
155
  const after = getSessionHealth(ctx);
148
156
  const details: SessionHealthToolDetails = {
149
157
  mode: after.mode,
@@ -155,7 +163,7 @@ export function registerSessionHealthTool(pi: ExtensionAPI): void {
155
163
  content: [
156
164
  {
157
165
  type: "text" as const,
158
- 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}` : ""}`,
166
+ 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}` : ""}`,
159
167
  },
160
168
  ],
161
169
  details,