pi-braid 0.43.6 → 0.43.7

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.
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The tool families a skill declares it governs.
3
+ *
4
+ * A trigger phrase says WHEN to open a skill file; nothing in the file says
5
+ * what the file's advice is then used FOR. `governs:` closes that: the tool
6
+ * families whose calls the body is written to direct. A family is the tool
7
+ * name's first underscore-delimited segment (`search_documents` → `search`),
8
+ * the same token `loading-guidance.ts` pairs with a skill name in the
9
+ * mechanical trigger, so "before the first call in the family" in the prompt
10
+ * and "a call in a declared family" in the record cannot mean two things.
11
+ *
12
+ * The declaration is authored data in the skill's own frontmatter — pi's
13
+ * parser already returns it, and the pack's authoring contract already admits
14
+ * any YAML-valid extra key. No new file format and no new field parser is
15
+ * needed, which is why this module only reads.
16
+ *
17
+ * Most skills govern nothing: advice about prose, a palette or a checklist
18
+ * directs no tool, and a file without the key is read as declaring no family.
19
+ * The absence is a fact, not a gap — an obligation that names no family is
20
+ * satisfied by the read alone.
21
+ *
22
+ * A declared family may not be the detector's own tool (`read`): a call to it
23
+ * IS the read leg, so counting it as an applied call would let an obligation
24
+ * satisfy itself. The parser drops such an entry; the shipped pack's contract
25
+ * refuses it by name so an author sees the problem before a release.
26
+ *
27
+ * Nothing here names a skill, a package or a path. Reads are memoized by file
28
+ * mtime + size, so a turn pays one stat per skill file and a parse only when
29
+ * a file changed.
30
+ */
31
+ import { readFileSync, statSync } from "node:fs";
32
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
33
+ /**
34
+ * Max families read from one declaration. A body that directs more than four
35
+ * tool families is not one skill's job, and the record's per-session rows are
36
+ * bounded by the same number. The pack's contract mirrors this cap.
37
+ */
38
+ export const MAX_GOVERNED_FAMILIES = 4;
39
+ /** The token shape a declaration must use: a tool name's first segment. */
40
+ export const GOVERNED_FAMILY_SHAPE = /^[a-z][a-z0-9]*$/;
41
+ /**
42
+ * The tool whose call is the read leg itself. Never a declarable family: see
43
+ * the module header.
44
+ */
45
+ export const DETECTOR_TOOL = "read";
46
+ /** The family a tool name belongs to: its first underscore-delimited segment. */
47
+ export function toolFamilyToken(toolName) {
48
+ return (toolName ?? "").split("_")[0].toLowerCase();
49
+ }
50
+ /**
51
+ * Normalize a frontmatter `governs` value into family tokens. Accepts a YAML
52
+ * list or a comma-separated string, lowercases, drops malformed, detector, and
53
+ * surplus entries, and dedupes in authored order. Pure.
54
+ */
55
+ export function parseGovernedFamilies(value) {
56
+ const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
57
+ const families = [];
58
+ for (const item of raw) {
59
+ if (typeof item !== "string")
60
+ continue;
61
+ const family = item.trim().toLowerCase();
62
+ if (!GOVERNED_FAMILY_SHAPE.test(family) || family === DETECTOR_TOOL)
63
+ continue;
64
+ if (families.includes(family))
65
+ continue;
66
+ families.push(family);
67
+ if (families.length >= MAX_GOVERNED_FAMILIES)
68
+ break;
69
+ }
70
+ return families;
71
+ }
72
+ const cache = new Map();
73
+ /**
74
+ * Read the families a skill file declares. Missing or unreadable file, or
75
+ * malformed frontmatter, yields an empty list (a declaration that cannot be
76
+ * read is not a declaration). Memoized: an unchanged file never re-reads.
77
+ */
78
+ export function readGovernedFamilies(filePath) {
79
+ let st;
80
+ try {
81
+ st = statSync(filePath);
82
+ }
83
+ catch {
84
+ cache.delete(filePath);
85
+ return [];
86
+ }
87
+ const cached = cache.get(filePath);
88
+ if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size)
89
+ return cached.families;
90
+ let families = [];
91
+ try {
92
+ const { frontmatter } = parseFrontmatter(readFileSync(filePath, "utf-8"));
93
+ families = parseGovernedFamilies(frontmatter.governs);
94
+ }
95
+ catch {
96
+ // Unreadable or unparseable: no declared family, and no throw on a turn.
97
+ }
98
+ cache.set(filePath, { mtimeMs: st.mtimeMs, size: st.size, families });
99
+ return families;
100
+ }
101
+ /** Test seam: forget every memoized read. */
102
+ export function clearGovernedFamilyCache() {
103
+ cache.clear();
104
+ }
105
+ //# sourceMappingURL=skill-families.js.map
package/docs/LOCAL_DEV.md CHANGED
@@ -138,7 +138,7 @@ before and after a full run. A non-zero delta is the leak this rule prevents.
138
138
  ### New fixtures: use `node:test`
139
139
 
140
140
  A new fixture is written on `node:test`. The runner does not care which style a
141
- file uses - 88 of the core suite's 322 fixtures already use `node:test` - so the
141
+ file uses - 90 of the core suite's 324 fixtures already use `node:test` - so the
142
142
  reason is the failure the other style produces. A hand-rolled helper that calls
143
143
  `fn()` without awaiting it discards the case's promise, so an `async` case runs
144
144
  detached and the file can print its green tally before that case settles, with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-braid",
3
- "version": "0.43.6",
3
+ "version": "0.43.7",
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",
@@ -34,3 +34,4 @@ 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
+ - **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`/`read`/`applied` belong to the record that owns each skill's declared tool family; the verdict row joins it on the skill name.
@@ -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
+ }