pi-braid 0.43.6 → 0.43.8

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 (62) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/TOOLS.md +1 -1
  3. package/build-info.json +4 -4
  4. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  5. package/dist/extensions/core/skills-tool/applicability.d.ts +134 -0
  6. package/dist/extensions/core/skills-tool/applicability.js +161 -0
  7. package/dist/extensions/core/skills-tool/auto-inject.d.ts +31 -0
  8. package/dist/extensions/core/skills-tool/auto-inject.js +320 -1
  9. package/dist/extensions/core/skills-tool/index.js +83 -4
  10. package/dist/extensions/core/skills-tool/loading-guidance.d.ts +4 -1
  11. package/dist/extensions/core/skills-tool/loading-guidance.js +6 -2
  12. package/dist/extensions/core/skills-tool/session-records.d.ts +395 -8
  13. package/dist/extensions/core/skills-tool/session-records.js +645 -5
  14. package/dist/extensions/core/skills-tool/skill-families.d.ts +60 -0
  15. package/dist/extensions/core/skills-tool/skill-families.js +105 -0
  16. package/dist/extensions/enforcement/handlers/analysis/dreamer-handler.js +5 -1
  17. package/dist/extensions/enforcement/handlers/register-tool-call.js +5 -2
  18. package/dist/extensions/enforcement/verification-judge.d.ts +7 -0
  19. package/dist/extensions/enforcement/verification-judge.js +28 -21
  20. package/dist/extensions/memory/session-recall/ask.d.ts +95 -0
  21. package/dist/extensions/memory/session-recall/ask.js +376 -0
  22. package/dist/extensions/memory/session-recall/corpus-index.d.ts +200 -0
  23. package/dist/extensions/memory/session-recall/corpus-index.js +480 -0
  24. package/dist/extensions/memory/session-recall/index.js +173 -21
  25. package/dist/extensions/memory/session-recall/search.d.ts +29 -0
  26. package/dist/extensions/memory/session-recall/search.js +42 -9
  27. package/dist/lib/ai/payload-hygiene.d.ts +3 -0
  28. package/dist/lib/ai/payload-hygiene.js +34 -2
  29. package/dist/lib/config/braid-paths.d.ts +4 -0
  30. package/dist/lib/config/braid-paths.js +6 -0
  31. package/dist/lib/config/braid-settings.d.ts +22 -0
  32. package/dist/lib/config/braid-settings.js +15 -0
  33. package/dist/lib/detection/tool-loop-detector.d.ts +95 -46
  34. package/dist/lib/detection/tool-loop-detector.js +288 -180
  35. package/dist/lib/reasoning/dreamer.d.ts +2 -1
  36. package/dist/lib/reasoning/dreamer.js +12 -7
  37. package/docs/LOCAL_DEV.md +1 -1
  38. package/docs/SETUP.md +1 -0
  39. package/package.json +1 -1
  40. package/src/extensions/core/AGENTS.md +3 -1
  41. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  42. package/src/extensions/core/skills-tool/applicability.ts +220 -0
  43. package/src/extensions/core/skills-tool/auto-inject.ts +391 -0
  44. package/src/extensions/core/skills-tool/index.ts +96 -3
  45. package/src/extensions/core/skills-tool/loading-guidance.ts +6 -2
  46. package/src/extensions/core/skills-tool/session-records.ts +932 -5
  47. package/src/extensions/core/skills-tool/skill-families.ts +112 -0
  48. package/src/extensions/enforcement/handlers/analysis/dreamer-handler.ts +5 -1
  49. package/src/extensions/enforcement/handlers/register-tool-call.ts +5 -2
  50. package/src/extensions/enforcement/verification-judge.ts +32 -25
  51. package/src/extensions/memory/AGENTS.md +2 -2
  52. package/src/extensions/memory/session-recall/AGENTS.md +92 -18
  53. package/src/extensions/memory/session-recall/ask.ts +435 -0
  54. package/src/extensions/memory/session-recall/corpus-index.ts +609 -0
  55. package/src/extensions/memory/session-recall/index.ts +202 -21
  56. package/src/extensions/memory/session-recall/search.ts +61 -10
  57. package/src/lib/ai/payload-hygiene.ts +47 -3
  58. package/src/lib/config/braid-paths.ts +7 -0
  59. package/src/lib/config/braid-settings.ts +42 -3
  60. package/src/lib/detection/AGENTS.md +8 -7
  61. package/src/lib/detection/tool-loop-detector.ts +339 -195
  62. package/src/lib/reasoning/dreamer.ts +13 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.43.6",
3
+ "version": "0.43.8",
4
4
  "description": "🥨 Braid - Metacognitive extension suite for pi coding agent: Adds memory, plan tracking, structured cognitive signals and completion checks on top of pi core loop, so long sessions keep their context and stop claiming unfinished work.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,7 +26,7 @@ environmental awareness, and system prompt assembly.
26
26
 
27
27
  ## Skills adoption contract
28
28
 
29
- The auto-inject whisper in `skills-tool/` is the only channel that surfaces a matching skill to the agent, so the rules about whether it arrived live in one place, here, and nowhere else:
29
+ Two surfaces in `skills-tool/` put a skill body in front of the agent: the auto-inject whisper, before the prompt is answered, and the at-use line, after a call in a family a file's `governs:` declaration names has already run. The rules about whether either arrived live in one place, here, and nowhere else:
30
30
 
31
31
  - **Delivery is observable.** `sendTrackedMessage` returns a boolean: `true` when the message was handed to `pi.sendMessage` (immediately or on the deferred triggerTurn macrotask), `false` when a suppression path dropped it (cognitive nudges disabled, per-turn/per-source flood cap, reprime cooldown). A suggestion is delivered with the park class (`delivery: "park", deliverAs: "steer"`) at source `skills-auto-inject`, which pi-core appends to the session stream - immediately when the session is idle, at the turn's end when a run is active. Both land in the session JSONL; a suppression upstream of `pi.sendMessage` reaches no stream at all.
32
32
  - **Counters move after delivery.** `recordSkillSuggestion` runs only on a `true` return, and the cooldown/LRU bookkeeping runs after the send too, so `suggested` counts arrivals and an undelivered suggestion consumes no slot. The suggestion bypasses the per-turn whisper cap (`bypassFloodCap: true`) because prompt-builder's once-per-session hygiene whisper fires earlier in the same `before_agent_start` at the same priority and would otherwise spend the only advisory slot; the module's own budget (cooldown turns, max active suggestions, one send per turn) is the bound that keeps the whisper a whisper.
@@ -34,3 +34,5 @@ The auto-inject whisper in `skills-tool/` is the only channel that surfaces a ma
34
34
  - **The trigger has a mechanical form.** `skills-tool/loading-guidance.ts` carries both the judgment form (the task entered a listed skill's domain) and the mechanical form (about to call a tool family whose word appears in a skill's name). `prompt-builder` renders that text through the `skillsLoadingText` builder as the `skills-loading` section and holds no copy of the rules; the trigger's worked examples are derived at assembly from the live tool and skill names, so the text names no pair that the running session does not have. The identity's skills prose stays one sentence.
35
35
  - **The catalog is in the prompt.** The same section renders every visible skill as one `- name: description` row, with the read path derived from the skills' own file paths (one root for a single pack, a directory heading per pack when a catalog is installed from several). A tool call is no longer the way the agent learns which skills exist: the floor exists because the prompt that opens a resumed session carries no domain vocabulary for a matcher to rank against. `list_skills` remains the price tool (reach, headings, ranking) rather than the catalog.
36
36
  - **Drift re-points at the floor.** When the session's own path-taking calls (`read`/`edit`/`write`) accumulate entries in a work area the floor was not rendered against, one steer line names that area and points back at the catalog. The rule and its bounds (two entries, one fire per twelve calls, three per session, quiet for the same window after any skill surface) live in `loading-guidance.ts` beside the floor text; the wiring is the `tool_result` handler in `auto-inject.ts`. Bounds are the whole design: the line is only worth its noise if it stays rare.
37
+ - **The at-use line is observed, never enforced.** With `braid.skills.inform` set to `inform` (default `off`), a `tool_result` whose call **succeeded**, whose tool name yields a family token some visible cached skill declares with `governs:`, and whose obligation row carries no `read` leg emits one steer line naming the file path and the family. It runs after the result exists, returns no replacement, and refuses, delays and rewrites nothing: any gating change can only make it quieter, which is the property that separates it from a refusal gate. The payload is derived from the declaration and the catalogue entry only (the skill's own `filePath`, the token the call's name yields), so no skill name is invented in code and no tool argument is echoed. Once per session per skill, suppressed by the same obligation record the legs write (its `informed` leg), silenced by a read at any point, and hidden skills are never named. `skill_stats` reports it as `inform` from the store: `undecided` below twenty informs, `beats` only when the lower Wilson bound clears the suggestion channel's 18.8% pair conversion, `noise` otherwise.
38
+ - **Applicability is recorded, never enforced.** The counters cannot tell a skill that applied and was ignored from one that never applied, and the sessions that read nothing are mostly sessions no phrase matches. `skills-tool/applicability.ts` decides that difference from the skill's own declaration (the trigger phrases its file carries: frontmatter `trigger:`/`triggers:`, a `## trigger:` body heading, a description `Triggers:` tail), never from the ranking heuristic, with the injector's occurrence boundary and a clause-scoped negation read, so a phrase inside "do not research this" is not a condition met. The verdict is `read` (condition held and a detected read followed), `ignored` (condition held and no read followed), or `not-applicable` (derived: the census's `evaluated` minus the verdict rows); a skill whose file declares no phrase is named `undeclared` rather than judged either way. It reaches disk as `kind: "applicability"` rows in the per-session store (one verdict row per applicable skill keyed on `sessionId` + `skill`, one census row per session) and out through `skill_stats`. It is an observer: it writes no delivery, slot, cooldown, counter or prompt, and it owns no compliance leg. `suggested`/`listed`/`informed`/`read`/`applied` belong to the record that owns each skill's declared tool family; the verdict row joins it on the skill name.
@@ -128,7 +128,7 @@ export const TOOL_GUIDELINES: Record<string, string> = {
128
128
 
129
129
  // ── session-recall (default-enabled) ──
130
130
  session:
131
- "when: prior-work context needed across sessions (search/query/analyze/stats); args: action + query/sessionPath; caveat: project-scoped by default",
131
+ "when: prior-work context needed across sessions (search/query/analyze/stats), or a question about what was said or decided earlier (ask, which cites project, session, line and time); args: action + query/sessionPath; caveat: project-scoped by default, and ask refuses when the corpus index cannot answer",
132
132
 
133
133
  // ── error-tracking (opt-in) ──
134
134
  error:
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Skill applicability — did a skill's own declared condition hold for the task?
3
+ *
4
+ * The suggestion whisper, the catalog ranking and the adoption counters all
5
+ * answer "might this skill help?". None answers the question the counters
6
+ * cannot: of the sessions that read nothing, which of them had a skill whose
7
+ * stated condition the task text actually met? A suggestion that was ignored
8
+ * and a skill that never applied looked identical in `suggested`/`loaded`.
9
+ * This module decides that difference and keeps its evidence.
10
+ *
11
+ * The condition is the skill's OWN declaration, never a heuristic invented
12
+ * here: the trigger phrases its file declares — frontmatter `trigger:` /
13
+ * `triggers:`, a `## trigger:` body heading, the description's `Triggers:`
14
+ * tail — the same entries `skill-triggers.ts` reads and the same provenance
15
+ * labels it records. The shipped pack's contract already treats that list as
16
+ * the machine-readable form of applicability ("a description that cannot fire
17
+ * is indistinguishable from one that fires"), so a skill file needs no new
18
+ * field for this module to see it. A file that declares no phrase yields no
19
+ * verdict at all; the caller reports it as undeclared rather than asserting
20
+ * "does not apply" on no evidence.
21
+ *
22
+ * Matching mirrors the injector on purpose. The occurrence boundary is the one
23
+ * `triggerMatches` uses (a phrase occurs where neither neighbour is a letter or
24
+ * digit, so "pane" is not an occurrence in "paneled"), because a verdict that
25
+ * disagreed with the whisper would be worse than no verdict: the suite pins
26
+ * the two answers equal over the installed catalog. What this module adds is
27
+ * polarity — a phrase inside a negated clause ("do not research this") is not
28
+ * the author's condition holding, so the clause is read and the phrase is
29
+ * dropped as evidence.
30
+ *
31
+ * What this module does NOT do: it decides nothing about delivery, slots,
32
+ * cooldowns, counters or ranking. It returns a classification and the caller
33
+ * records it. Nothing here reads the session, writes a file or sends a
34
+ * message.
35
+ *
36
+ * Cost: one pass over the task text per phrase of the cached catalog, with the
37
+ * native substring scan as the cheap reject before any boundary work. The
38
+ * caller holds the prompt in memory already (the injector matches against the
39
+ * same string), so no I/O is added per turn.
40
+ */
41
+
42
+ import type { TriggerSource } from "./skill-triggers.js";
43
+
44
+ /**
45
+ * A skill as the applicability read consumes it: its name and the phrase list
46
+ * the cache resolved from its file. `triggers` and `triggerSources` are the
47
+ * fields `setCachedSkills` fills, so this read never touches the disk — the
48
+ * phrases and their provenance are the ones the injector matched against.
49
+ */
50
+ export interface ConditionalSkill {
51
+ name: string;
52
+ /** Authored phrases (lowercased, deduped, capped) — empty when the file declares none. */
53
+ triggers?: string[];
54
+ /** Which authored source declared each phrase. */
55
+ triggerSources?: Record<string, TriggerSource>;
56
+ }
57
+
58
+ /** One authored phrase that matched, with the place in the file that declares it. */
59
+ export interface ApplicabilityEvidence {
60
+ /** The authored phrase, as the reader normalized it. */
61
+ phrase: string;
62
+ /**
63
+ * frontmatter | heading | description — absent only when the cached skill
64
+ * carried no provenance map (an unenriched cache, never a production one).
65
+ */
66
+ source?: TriggerSource;
67
+ }
68
+
69
+ /**
70
+ * One skill's verdict for a session.
71
+ *
72
+ * `ignored` is the evaluation's answer: the declared condition held and no
73
+ * detected read followed. `read` is the read-detector's upgrade of the same
74
+ * row. The third class, not-applicable, is never a row — it is a skill that
75
+ * declared a condition and did not meet the task text, so a reader derives it
76
+ * from the record's census (`evaluated` minus the verdict rows).
77
+ */
78
+ export interface SkillApplicabilityVerdict {
79
+ name: string;
80
+ verdict: "read" | "ignored";
81
+ evidence: ApplicabilityEvidence[];
82
+ }
83
+
84
+ /** Max evidence rows carried per skill: enough to review, bounded like every other surface. */
85
+ export const MAX_APPLICABILITY_EVIDENCE = 4;
86
+
87
+ /**
88
+ * Word tokens a negation cue may sit before the phrase and still negate it.
89
+ * "do not research this" (0) and "no need to research" (2) are negated;
90
+ * "do not stop, then research it later" puts the cue past the clauseless
91
+ * distance and reads as the assertion it is. Four is the smallest window that
92
+ * covers the "no need to"/"there is no reason to" shapes without reaching
93
+ * across a clause.
94
+ */
95
+ export const NEGATION_GAP_TOKENS = 4;
96
+
97
+ /**
98
+ * Negation cues, matched in the clause text BEFORE a phrase. The `-n't`
99
+ * alternative is spelled out rather than listed per verb so a contraction the
100
+ * list forgot ("won't", "shouldn't") still counts.
101
+ */
102
+ const NEGATION_CUE =
103
+ /\b(?:not|never|no|nor|without|avoid|avoiding|skip|skipping)\b|\b[a-z]+n['\u2019]t\b/gi;
104
+
105
+ /** True when `char` continues a word (the boundary rule `triggerMatches` uses). */
106
+ function isWordChar(char: string | undefined): boolean {
107
+ return char !== undefined && /[a-z0-9]/.test(char);
108
+ }
109
+
110
+ /**
111
+ * Every index in `lowered` where `phrase` occurs as a whole phrase, using the
112
+ * matcher's boundary rule: neither neighbour may be a letter or digit. Phrase
113
+ * must already be lowercase. Pure.
114
+ */
115
+ export function phraseOccurrences(phrase: string, lowered: string): number[] {
116
+ if (!phrase) return [];
117
+ const out: number[] = [];
118
+ let from = 0;
119
+ for (;;) {
120
+ const at = lowered.indexOf(phrase, from);
121
+ if (at < 0) break;
122
+ if (!isWordChar(lowered[at - 1]) && !isWordChar(lowered[at + phrase.length])) out.push(at);
123
+ from = at + 1;
124
+ }
125
+ return out;
126
+ }
127
+
128
+ /**
129
+ * Index where the clause containing `at` begins: after the nearest sentence
130
+ * terminator. A clause boundary is what stops a negation in one statement from
131
+ * reaching a phrase in the next ("do not use the catalog; research the topic"
132
+ * asserts research). Pure.
133
+ */
134
+ export function clauseStart(lowered: string, at: number): number {
135
+ for (let i = at - 1; i >= 0; i--) {
136
+ const char = lowered[i];
137
+ if (char === "." || char === "!" || char === "?" || char === ";" || char === "\n") return i + 1;
138
+ }
139
+ return 0;
140
+ }
141
+
142
+ /**
143
+ * True when the clause text preceding a phrase carries a negation cue close
144
+ * enough to negate it. The LAST cue decides, so "not only did we not ask" is
145
+ * read by its nearest cue rather than its first. Pure.
146
+ */
147
+ export function isNegatedPrefix(prefix: string): boolean {
148
+ const cue = new RegExp(NEGATION_CUE.source, "gi");
149
+ let last: RegExpExecArray | null = null;
150
+ let match: RegExpExecArray | null;
151
+ while ((match = cue.exec(prefix))) last = match;
152
+ if (!last) return false;
153
+ const gap = prefix.slice(last.index + last[0].length);
154
+ return (gap.match(/[a-z0-9]+/g) ?? []).length <= NEGATION_GAP_TOKENS;
155
+ }
156
+
157
+ /**
158
+ * The evidence for one skill's declared condition holding on `taskText`.
159
+ *
160
+ * A phrase is evidence when at least one of its occurrences is asserted:
161
+ * negating one occurrence does not erase another ("do not skip research" and
162
+ * "research this" in the same text both count). Phrases are evidence at most
163
+ * MAX_APPLICABILITY_EVIDENCE times per skill, in authored order. An empty
164
+ * return means the condition did not hold. Pure.
165
+ */
166
+ export function skillApplicability(
167
+ skill: ConditionalSkill,
168
+ taskText: string,
169
+ ): ApplicabilityEvidence[] {
170
+ const lowered = taskText.toLowerCase();
171
+ const evidence: ApplicabilityEvidence[] = [];
172
+ for (const authored of skill.triggers ?? []) {
173
+ if (evidence.length >= MAX_APPLICABILITY_EVIDENCE) break;
174
+ const phrase = authored.toLowerCase();
175
+ // Cheap reject first: most phrases are absent from most prompts.
176
+ if (!phrase || !lowered.includes(phrase)) continue;
177
+ const asserted = phraseOccurrences(phrase, lowered).some(
178
+ (at) => !isNegatedPrefix(lowered.slice(clauseStart(lowered, at), at)),
179
+ );
180
+ if (!asserted) continue;
181
+ const source = skill.triggerSources?.[authored] ?? skill.triggerSources?.[phrase];
182
+ evidence.push(source ? { phrase, source } : { phrase });
183
+ }
184
+ return evidence;
185
+ }
186
+
187
+ /** The whole catalog's answer for one task text. */
188
+ export interface ApplicabilityEvaluation {
189
+ /** Skills whose declared condition held, each still an `ignored` verdict. */
190
+ applicable: SkillApplicabilityVerdict[];
191
+ /** Installed skills that declare at least one condition phrase. */
192
+ evaluated: number;
193
+ /** Installed skills that declare none — no condition, so no verdict either way. */
194
+ undeclared: string[];
195
+ }
196
+
197
+ /**
198
+ * Classify every installed skill against one task text. Pure: the catalog
199
+ * arrives as the cache already resolved it, and the text is the prompt the
200
+ * injector matched against.
201
+ */
202
+ export function evaluateApplicability(
203
+ skills: ConditionalSkill[],
204
+ taskText: string,
205
+ ): ApplicabilityEvaluation {
206
+ const applicable: SkillApplicabilityVerdict[] = [];
207
+ const undeclared: string[] = [];
208
+ let evaluated = 0;
209
+ const text = taskText ?? "";
210
+ for (const skill of skills) {
211
+ if (!skill.triggers?.length) {
212
+ undeclared.push(skill.name);
213
+ continue;
214
+ }
215
+ evaluated++;
216
+ const evidence = skillApplicability(skill, text);
217
+ if (evidence.length) applicable.push({ name: skill.name, verdict: "ignored", evidence });
218
+ }
219
+ return { applicable, evaluated, undeclared };
220
+ }