pi-braid 0.43.5 → 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.
Files changed (26) hide show
  1. package/CHANGELOG.md +95 -7
  2. package/build-info.json +4 -4
  3. package/dist/extensions/core/prompt-builder/surface-discipline-section.d.ts +1 -1
  4. package/dist/extensions/core/prompt-builder/surface-discipline-section.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 +10 -0
  8. package/dist/extensions/core/skills-tool/auto-inject.js +216 -1
  9. package/dist/extensions/core/skills-tool/index.js +64 -3
  10. package/dist/extensions/core/skills-tool/loading-guidance.js +2 -1
  11. package/dist/extensions/core/skills-tool/session-records.d.ts +297 -8
  12. package/dist/extensions/core/skills-tool/session-records.js +509 -5
  13. package/dist/extensions/core/skills-tool/skill-families.d.ts +60 -0
  14. package/dist/extensions/core/skills-tool/skill-families.js +105 -0
  15. package/dist/extensions/orchestrator/index.js +11 -1
  16. package/docs/LOCAL_DEV.md +1 -1
  17. package/package.json +1 -1
  18. package/src/extensions/core/AGENTS.md +1 -0
  19. package/src/extensions/core/prompt-builder/surface-discipline-section.ts +1 -1
  20. package/src/extensions/core/skills-tool/applicability.ts +220 -0
  21. package/src/extensions/core/skills-tool/auto-inject.ts +274 -0
  22. package/src/extensions/core/skills-tool/index.ts +75 -2
  23. package/src/extensions/core/skills-tool/loading-guidance.ts +2 -1
  24. package/src/extensions/core/skills-tool/session-records.ts +740 -5
  25. package/src/extensions/core/skills-tool/skill-families.ts +112 -0
  26. package/src/extensions/orchestrator/index.ts +13 -1
@@ -112,8 +112,10 @@ import { getExtensionState } from "../../../lib/state/extension-state.js";
112
112
  import { BRAID_INJECTED, BRAID_SOURCE } from "../../../lib/constants/injection-details.js";
113
113
  import { getSkillsUsageFilePath } from "../../../lib/config/braid-paths.js";
114
114
  import { SESSION_COMPACT, AGENT_SETTLED } from "../../../lib/core/event-names.js";
115
- import { getSessionProfile, recordSessionSkillLoad, recordSessionStart, } from "./session-records.js";
115
+ import { getSessionProfile, recordApplicabilityCensus, recordApplicabilityVerdict, recordObligationLegs, recordSessionSkillLoad, recordSessionStart, } from "./session-records.js";
116
+ import { evaluateApplicability } from "./applicability.js";
116
117
  import { triggerMatches } from "./skill-triggers.js";
118
+ import { toolFamilyToken } from "./skill-families.js";
117
119
  import { advanceDrift, driftDirectoryFor, driftPayload, initialDrift, noteDriftSurface, recordDriftDrop, recordDriftFire, skillReadRoot, } from "./loading-guidance.js";
118
120
  const log = createLogger("skills-auto-inject");
119
121
  // Constants
@@ -238,6 +240,12 @@ const KEYWORD_STOP_WORDS = new Set([
238
240
  "need",
239
241
  "look",
240
242
  ]);
243
+ function initialObligations() {
244
+ return { legs: new Map(), called: new Set(), written: new Map() };
245
+ }
246
+ function initialApplicability() {
247
+ return { censusWritten: false, verdicts: new Map(), evaluated: 0, undeclared: [], taskChars: 0 };
248
+ }
241
249
  const STATE_KEY = "skills-auto-inject";
242
250
  function getState(ctx) {
243
251
  return getExtensionState(ctx, STATE_KEY, () => ({
@@ -245,6 +253,8 @@ function getState(ctx) {
245
253
  currentTurn: 0,
246
254
  hintSent: false,
247
255
  drift: initialDrift(),
256
+ applicability: initialApplicability(),
257
+ obligations: initialObligations(),
248
258
  }));
249
259
  }
250
260
  // Shared module-level variable rather than a per-module copy: the import
@@ -910,6 +920,159 @@ export function resolveDiscoveryMode(ctx) {
910
920
  }
911
921
  return state;
912
922
  }
923
+ // Applicability verdict (recorded, never enforced)
924
+ /**
925
+ * Classify the catalog against this turn's task text and record what changed.
926
+ *
927
+ * Two writes, both append-only:
928
+ * - the session's census row, once, retried until it lands. It is what makes
929
+ * "not-applicable" derivable (evaluated minus the verdict rows) and what
930
+ * names the skills whose files state no condition at all.
931
+ * - one verdict row per skill whose declared condition held, and never twice
932
+ * for the same (session, skill): the set only grows because the verdict is
933
+ * per-session — a skill whose condition held on any turn applied to the
934
+ * session.
935
+ *
936
+ * The row shape is the joint the sibling compliance record expects: it joins on
937
+ * (sessionId, skill) and adds its own `suggested`/`listed`/`read`/`applied`
938
+ * beside this verdict, so `ignored / (read + ignored)` becomes computable. This
939
+ * module writes no `applied` leg: a tool belong to a skill's family only once
940
+ * the skill declares that family, and no skill does yet.
941
+ *
942
+ * Reads only — it never touches `injected`, a counter or a send. That is the
943
+ * whole point of the ordering in before_agent_start: this step cannot move the
944
+ * suggestion, and the suggestion cannot move the verdict.
945
+ */
946
+ function stepApplicability(ctx, state, skills, prompt) {
947
+ const evaluation = evaluateApplicability(skills, prompt);
948
+ const app = state.applicability;
949
+ const fresh = evaluation.applicable.filter((verdict) => !app.verdicts.has(verdict.name));
950
+ for (const verdict of fresh)
951
+ app.verdicts.set(verdict.name, verdict);
952
+ app.evaluated = evaluation.evaluated;
953
+ app.undeclared = evaluation.undeclared;
954
+ app.taskChars = prompt.length;
955
+ if (!app.censusWritten) {
956
+ const wrote = recordApplicabilityCensus(ctx, {
957
+ taskChars: app.taskChars,
958
+ evaluated: app.evaluated,
959
+ undeclared: app.undeclared,
960
+ });
961
+ // A session without an id, or a refused store: retry on the next turn.
962
+ if (wrote)
963
+ app.censusWritten = true;
964
+ }
965
+ if (!fresh.length)
966
+ return;
967
+ log.debug(`[skills-auto-inject] applicability: ${fresh.length} newly applicable, ` +
968
+ `${evaluation.evaluated} evaluated, ${evaluation.undeclared.length} undeclared`);
969
+ for (const verdict of fresh) {
970
+ recordApplicabilityVerdict(ctx, {
971
+ skill: verdict.name,
972
+ applicability: verdict.verdict,
973
+ evidence: verdict.evidence,
974
+ });
975
+ // The obligation row lands with the verdict, not with the first leg: a
976
+ // session that is merely told which body it owes, and then does nothing,
977
+ // is the population the rate exists to count. Without this row that
978
+ // session would be mistaken for one the instrument never saw.
979
+ legsFor(state, verdict.name);
980
+ appendObligationRow(ctx, state, verdict.name);
981
+ }
982
+ }
983
+ /**
984
+ * Upgrade an applicable skill to `read` and append its verdict row. A read of a
985
+ * skill whose declared condition never held gets no row: the three classes are
986
+ * about skills that applied, and a read is not a fourth one.
987
+ */
988
+ function markApplicabilityRead(ctx, state, name) {
989
+ const app = state.applicability;
990
+ const held = app.verdicts.get(name);
991
+ if (!held || held.verdict === "read")
992
+ return;
993
+ app.verdicts.set(name, { ...held, verdict: "read" });
994
+ recordApplicabilityVerdict(ctx, {
995
+ skill: name,
996
+ applicability: "read",
997
+ evidence: held.evidence,
998
+ });
999
+ }
1000
+ // Obligation rows (the applied leg)
1001
+ /**
1002
+ * The session's legs for one skill, created on first sight. The object is the
1003
+ * snapshot every row carries, so a row states all five legs as of the moment
1004
+ * the leg changed rather than the single delta that triggered the write.
1005
+ */
1006
+ function legsFor(state, name) {
1007
+ let legs = state.obligations.legs.get(name);
1008
+ if (!legs) {
1009
+ legs = {
1010
+ skill: name,
1011
+ suggested: false,
1012
+ listed: false,
1013
+ read: false,
1014
+ called: false,
1015
+ applied: false,
1016
+ };
1017
+ state.obligations.legs.set(name, legs);
1018
+ }
1019
+ return legs;
1020
+ }
1021
+ /**
1022
+ * Append the skill's legs when they changed since the last row. One row per
1023
+ * distinct state rather than one per event: a session that reads the same body
1024
+ * three times, or lists it on every turn, writes one line. A refused write
1025
+ * leaves the signature unset, so the next leg change retries.
1026
+ */
1027
+ function appendObligationRow(ctx, state, name) {
1028
+ const legs = state.obligations.legs.get(name);
1029
+ if (!legs)
1030
+ return;
1031
+ const signature = [legs.suggested, legs.listed, legs.read, legs.called, legs.applied]
1032
+ .map((flag) => (flag ? "1" : "0"))
1033
+ .join("");
1034
+ if (state.obligations.written.get(name) === signature)
1035
+ return;
1036
+ if (!recordObligationLegs(ctx, legs))
1037
+ return;
1038
+ state.obligations.written.set(name, signature);
1039
+ }
1040
+ /** Note one observed leg for a skill and record the row it changed. */
1041
+ function noteObligationLeg(ctx, state, name, leg) {
1042
+ if (!name)
1043
+ return;
1044
+ const legs = legsFor(state, name);
1045
+ if (legs[leg])
1046
+ return;
1047
+ legs[leg] = true;
1048
+ appendObligationRow(ctx, state, name);
1049
+ }
1050
+ /**
1051
+ * Record the skills a delivered suggestion offered this session. Called only
1052
+ * after the send was accepted, so the row counts arrivals like the `suggested`
1053
+ * counter does. Never throws: a record is not worth a broken turn.
1054
+ */
1055
+ export function noteObligationSuggested(ctx, names) {
1056
+ try {
1057
+ const state = getState(ctx);
1058
+ for (const name of names)
1059
+ noteObligationLeg(ctx, state, name, "suggested");
1060
+ }
1061
+ catch (err) {
1062
+ log.debug(`[skills-auto-inject] obligation suggested leg failed (best-effort): ${err}`);
1063
+ }
1064
+ }
1065
+ /** Record the skills a catalog page listed (called from the list_skills tool). */
1066
+ export function noteObligationListed(ctx, names) {
1067
+ try {
1068
+ const state = getState(ctx);
1069
+ for (const name of names)
1070
+ noteObligationLeg(ctx, state, name, "listed");
1071
+ }
1072
+ catch (err) {
1073
+ log.debug(`[skills-auto-inject] obligation listed leg failed (best-effort): ${err}`);
1074
+ }
1075
+ }
913
1076
  /**
914
1077
  * Count a SKILL.md read (the list→read load path) and mark the matching
915
1078
  * injection loaded (releases its slot and extends its cooldown: the skill is
@@ -932,9 +1095,44 @@ function detectSkillLoad(ev, ctx, state) {
932
1095
  if (held)
933
1096
  held.loadedTurn = state.currentTurn;
934
1097
  recordSkillLoad(ctx, name);
1098
+ // The load counters say a read happened; this says whether the session was
1099
+ // one where the skill applied. Independent writes, independent failures.
1100
+ markApplicabilityRead(ctx, state, name);
1101
+ noteObligationLeg(ctx, state, name, "read");
935
1102
  log.debug(`[skills-auto-inject] counted actual load of "${name}" via read`);
936
1103
  return name;
937
1104
  }
1105
+ /**
1106
+ * Record a call into a declared family (the applied leg).
1107
+ *
1108
+ * The FIRST call per (session, skill) decides it: a read already on record
1109
+ * means the body came first and the call applies what it says; no read means
1110
+ * the call came first, and no later read can turn that into satisfaction — the
1111
+ * ordering is a fact about what happened, not a state that improves.
1112
+ *
1113
+ * A failed call still counts: a refusal would fire before the tool ran and
1114
+ * could not know the outcome. Skills that declare no family are never reached
1115
+ * here, which is most of them.
1116
+ */
1117
+ function stepFamilyCalls(ctx, state, event) {
1118
+ const toolName = event?.toolName;
1119
+ if (!toolName)
1120
+ return;
1121
+ const family = toolFamilyToken(toolName);
1122
+ if (!family)
1123
+ return;
1124
+ for (const skill of _skillsCache) {
1125
+ if (!skill.families?.length || !skill.families.includes(family))
1126
+ continue;
1127
+ if (state.obligations.called.has(skill.name))
1128
+ continue;
1129
+ const legs = legsFor(state, skill.name);
1130
+ state.obligations.called.add(skill.name);
1131
+ legs.called = true;
1132
+ legs.applied = legs.read;
1133
+ appendObligationRow(ctx, state, skill.name);
1134
+ }
1135
+ }
938
1136
  /**
939
1137
  * Fire the drift line when the work has moved into a new work area (the rule
940
1138
  * and its bounds live in loading-guidance.ts, beside the floor text the line
@@ -993,6 +1191,10 @@ export function registerAutoInject(pi) {
993
1191
  const state = getState(ctx);
994
1192
  if (detectSkillLoad(ev, ctx, state))
995
1193
  noteDriftSurface(state.drift);
1194
+ // A call in a declared family is the applied leg. It runs after the load
1195
+ // detector so a SKILL.md read of the very tool call in flight is already
1196
+ // on record when the family is looked up.
1197
+ stepFamilyCalls(ctx, state, ev);
996
1198
  stepDrift(pi, ctx, state, ev);
997
1199
  }
998
1200
  catch {
@@ -1044,6 +1246,17 @@ export function registerAutoInject(pi) {
1044
1246
  if (!prompt.trim()) {
1045
1247
  return; // No user input to match against
1046
1248
  }
1249
+ // Applicability is recorded BEFORE every scoring early-return below.
1250
+ // Most sessions match no skill, and those are exactly the sessions the
1251
+ // adoption counters cannot explain: the returns would erase them. The
1252
+ // step reads the catalog and the prompt only, so the suggestion decision
1253
+ // below is untouched by it (and its failure cannot cost a suggestion).
1254
+ try {
1255
+ stepApplicability(ctx, state, skills, prompt);
1256
+ }
1257
+ catch (err) {
1258
+ log.debug(`[skills-auto-inject] applicability step failed (best-effort): ${err}`);
1259
+ }
1047
1260
  // One-shot profile hint: the first non-empty prompt of a session whose
1048
1261
  // configured profile carries a hint gets exactly one steer — the hint
1049
1262
  // text itself, byte-for-byte. Profiles without a hint and sessions
@@ -1125,6 +1338,8 @@ export function registerAutoInject(pi) {
1125
1338
  (i.loadedTurn !== undefined && state.currentTurn - i.loadedTurn < LOADED_COOLDOWN_TURNS));
1126
1339
  // E3: per-skill suggestion counter — counts deliveries, not intent.
1127
1340
  recordSkillSuggestion(ctx, skillsToInject.map((s) => s.name));
1341
+ // The same delivery is an obligation leg: the body was offered here.
1342
+ noteObligationSuggested(ctx, skillsToInject.map((s) => s.name));
1128
1343
  }
1129
1344
  catch (err) {
1130
1345
  log.debug(`[skills-auto-inject] Error in before_agent_start: ${err}`);
@@ -34,10 +34,11 @@
34
34
  import { Type } from "typebox";
35
35
  import { createLogger } from "../../../lib/core/logger.js";
36
36
  import { getSkillsRankingMode } from "../../../lib/config/braid-settings.js";
37
- import { registerAutoInject, updateSkillCache, getSkillStats, getDurableSkillStats, resolveDiscoveryMode, rankSkillsDeterministic, } from "./auto-inject.js";
37
+ import { registerAutoInject, updateSkillCache, getSkillStats, getDurableSkillStats, noteObligationListed, resolveDiscoveryMode, rankSkillsDeterministic, } from "./auto-inject.js";
38
38
  import { readSkillTriggerEntries } from "./skill-triggers.js";
39
+ import { readGovernedFamilies } from "./skill-families.js";
39
40
  import { clampSectionsMax, DEFAULT_SECTIONS_MAX, SECTIONS_MAX_LIMIT, readSkillReach, } from "./reach.js";
40
- import { getMonthlyAdoptionRollup } from "./session-records.js";
41
+ import { getMonthlyAdoptionRollup, getObligationRate, getSessionApplicability, getSessionObligation, judgeSessionObligations, } from "./session-records.js";
41
42
  import { checkArgumentValues } from "../../../lib/utils/argument-report.js";
42
43
  const log = createLogger("skills-tool");
43
44
  let cachedSkills = [];
@@ -53,7 +54,15 @@ export function setCachedSkills(skills) {
53
54
  const triggerSources = {};
54
55
  for (const entry of entries)
55
56
  triggerSources[entry.phrase] = entry.source;
56
- return { ...s, triggers: entries.map((entry) => entry.phrase), triggerSources };
57
+ return {
58
+ ...s,
59
+ triggers: entries.map((entry) => entry.phrase),
60
+ triggerSources,
61
+ // The families the file says its advice directs, resolved from the same
62
+ // frontmatter read the phrases come from (one extra parse per file per
63
+ // process). An empty list is a declaration of no family, not a miss.
64
+ families: readGovernedFamilies(s.filePath),
65
+ };
57
66
  });
58
67
  // Sync with auto-inject subsystem (enriched cache — triggers ride along)
59
68
  updateSkillCache(cachedSkills);
@@ -245,6 +254,10 @@ export default function skillsToolExtension(pi) {
245
254
  // the empty object carried no information the absence does not.
246
255
  ...(answer.relevance.has(s.name) ? { relevance: answer.relevance.get(s.name) } : {}),
247
256
  }));
257
+ // A listed row is one of the session's obligation legs: the catalog is
258
+ // where a body becomes findable without a whisper. Recorded before the
259
+ // response is built so the row and the page describe the same read.
260
+ noteObligationListed(ctx, skills.map((s) => s.name));
248
261
  return {
249
262
  content: [
250
263
  {
@@ -310,6 +323,41 @@ export default function skillsToolExtension(pi) {
310
323
  }
311
324
  const monthly = getMonthlyAdoptionRollup();
312
325
  const discovery = resolveDiscoveryMode(ctx);
326
+ // The session's skill verdicts (read | ignored, plus the not-applicable
327
+ // remainder of the census) from the durable record, never from memory:
328
+ // the point of the record is that it outlives the turn that saw it.
329
+ // Absent when the session wrote none — an older store, or a session that
330
+ // never reached a task text — so an exhausted reader of the old counters
331
+ // keeps byte-identical output. Only the verdict classes are summarized in
332
+ // details; the full evidence stays in the text payload.
333
+ const recorded = getSessionApplicability(ctx);
334
+ const applicability = recorded
335
+ ? {
336
+ taskChars: recorded.taskChars,
337
+ evaluated: recorded.evaluated,
338
+ undeclared: recorded.undeclared,
339
+ classes: recorded.classes,
340
+ verdicts: recorded.verdicts,
341
+ updatedAt: recorded.updatedAt,
342
+ }
343
+ : undefined;
344
+ // The session's obligation legs and its boolean: what the session did
345
+ // with the bodies whose conditions held. Absent when the session has no
346
+ // leg row, so a store this build never wrote to reads byte for byte as
347
+ // it did before (the same rule the applicability block above follows).
348
+ const legRecord = getSessionObligation(ctx);
349
+ const judgement = judgeSessionObligations(recorded, legRecord);
350
+ const obligations = judgement && legRecord && legRecord.skills.length
351
+ ? {
352
+ allSatisfied: judgement.allSatisfied,
353
+ obligations: judgement.obligations,
354
+ skills: judgement.skills,
355
+ }
356
+ : undefined;
357
+ // Both rates over one population, or absent while the store carries no
358
+ // obligation row at all: a build that predates the leg reads the same
359
+ // sessions and must see the same payload.
360
+ const obligationRate = getObligationRate();
313
361
  return {
314
362
  content: [
315
363
  {
@@ -329,6 +377,9 @@ export default function skillsToolExtension(pi) {
329
377
  suggestedEpoch: suggestedMixed === 0 ? "delivered" : "mixed",
330
378
  },
331
379
  monthly,
380
+ ...(applicability ? { applicability } : {}),
381
+ ...(obligations ? { obligations } : {}),
382
+ ...(obligationRate ? { obligationRate } : {}),
332
383
  discovery: {
333
384
  // Whether the stock skill catalog sits in the persisted
334
385
  // transcript (it re-enters via pi's post-compaction
@@ -347,6 +398,16 @@ export default function skillsToolExtension(pi) {
347
398
  allTimeSkills: Object.keys(allTime).length,
348
399
  allTimeTotals: { ...totals, suggestedDelivered, suggestedMixed },
349
400
  monthly,
401
+ ...(applicability ? { applicability: applicability.classes } : {}),
402
+ ...(obligations
403
+ ? {
404
+ obligations: {
405
+ allSatisfied: obligations.allSatisfied,
406
+ count: obligations.obligations,
407
+ },
408
+ }
409
+ : {}),
410
+ ...(obligationRate ? { obligationRate } : {}),
350
411
  },
351
412
  };
352
413
  },
@@ -36,6 +36,7 @@
36
36
  * auto-inject.ts and the reasoning stays testable here.
37
37
  */
38
38
  import { isAbsolute, relative, resolve, sep } from "node:path";
39
+ import { toolFamilyToken } from "./skill-families.js";
39
40
  /**
40
41
  * Paragraph 1: what the catalog is, where the bodies live, and the obligation.
41
42
  *
@@ -136,7 +137,7 @@ export function mechanicalTriggerExamples(toolNames, skillNames) {
136
137
  // Family token (lowercased) -> lexicographically smallest active tool name.
137
138
  const familyTool = new Map();
138
139
  for (const tool of toolNames) {
139
- const family = tool.split("_")[0].toLowerCase();
140
+ const family = toolFamilyToken(tool);
140
141
  const incumbent = familyTool.get(family);
141
142
  if (incumbent === undefined || tool < incumbent)
142
143
  familyTool.set(family, tool);