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
@@ -1,8 +1,18 @@
1
1
  /**
2
- * Durable per-session skill-adoption records + monthly adoption rollup.
2
+ * Durable per-session skill records + the monthly adoption rollup.
3
3
  *
4
- * Every session that reaches an agent turn gets ONE logical record:
5
- * { sessionId, role, month, hadSkillLoad, updatedAt }
4
+ * The store is one append-only JSONL file with three record kinds, told apart
5
+ * by `kind`:
6
+ *
7
+ * (absent) an ADOPTION record, the older shape:
8
+ * { sessionId, role, month, hadSkillLoad, updatedAt }
9
+ * "applicability" an APPLICABILITY record: the session's skill verdicts
10
+ * (see ApplicabilityRecord)
11
+ * "obligation" an OBLIGATION record: one skill's legs in one session
12
+ * (see ObligationLegRecord)
13
+ *
14
+ * An adoption record exists for every session that reaches an agent turn, so
15
+ * every such session gets ONE logical record (the rollup denominator);
6
16
  * `role` carries the session's profile name from the braid config (see
7
17
  * lib/config/session-profiles.ts), or the neutral default when no profile
8
18
  * matches; `month` is the local-time "YYYY-MM" of the write, and
@@ -22,6 +32,13 @@
22
32
  * filesystems; the tolerant reader skips unparseable lines, the window is
23
33
  * a single small write, and this is accepted as best-effort telemetry.
24
34
  *
35
+ * Each reader reads its own kind and ignores the others. The adoption reader
36
+ * is fail-closed on an unknown `kind`, so a record type added later cannot
37
+ * enter the adoption numbers by looking enough like one; and a build that
38
+ * predates the applicability kind reads those lines as adoption records of
39
+ * the same session, which folds to the same numbers because it carries no
40
+ * new sessions and never sets `hadSkillLoad`.
41
+ *
25
42
  * Back-compat: records written before profiles existed carry a role from
26
43
  * the retired fixed set; those values pass the profile-name gate
27
44
  * unchanged, so older buckets keep folding under their original names.
@@ -34,6 +51,7 @@ import { createLogger } from "../../../lib/core/logger.js";
34
51
  import { getExtensionState } from "../../../lib/state/extension-state.js";
35
52
  import { getSkillsSessionsFilePath } from "../../../lib/config/braid-paths.js";
36
53
  import { NEUTRAL_SESSION_PROFILE, normalizeProfileName, resolveSessionProfileForCwd, } from "../../../lib/config/session-profiles.js";
54
+ import { MAX_APPLICABILITY_EVIDENCE } from "./applicability.js";
37
55
  const log = createLogger("skills-tool");
38
56
  /** Local-time calendar month of a date, "YYYY-MM". */
39
57
  export function monthOf(date) {
@@ -45,6 +63,10 @@ function normalizeRecord(raw) {
45
63
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
46
64
  return undefined;
47
65
  const r = raw;
66
+ // One file, several record kinds: the adoption reader accepts its own kind
67
+ // (no `kind`, or an explicit "adoption") and refuses anything else.
68
+ if (r.kind !== undefined && r.kind !== "adoption")
69
+ return undefined;
48
70
  if (typeof r.sessionId !== "string" || !r.sessionId)
49
71
  return undefined;
50
72
  if (typeof r.month !== "string" || !/^\d{4}-\d{2}$/.test(r.month))
@@ -108,11 +130,11 @@ export function readSessionRecords(storePath) {
108
130
  return out;
109
131
  }
110
132
  /**
111
- * Append one record. Best-effort: every error is swallowed (this runs on
133
+ * Append one record line. Best-effort: every error is swallowed (this runs on
112
134
  * the agent-loop and tool-result paths — a telemetry failure must never
113
135
  * break a turn). Returns true when the line landed on disk.
114
136
  */
115
- export function appendSessionRecord(record, storePath) {
137
+ function appendLine(record, storePath) {
116
138
  try {
117
139
  mkdirSync(dirname(storePath), { recursive: true });
118
140
  appendFileSync(storePath, `${JSON.stringify(record)}\n`, "utf-8");
@@ -123,6 +145,10 @@ export function appendSessionRecord(record, storePath) {
123
145
  return false;
124
146
  }
125
147
  }
148
+ /** Append one adoption record (see appendLine for the failure contract). */
149
+ export function appendSessionRecord(record, storePath) {
150
+ return appendLine(record, storePath);
151
+ }
126
152
  /** Warned once per process about a refused adoption-record append. */
127
153
  let _warnedRecordFailure = false;
128
154
  function reportRecordFailure(err) {
@@ -206,6 +232,620 @@ export function recordSessionSkillLoad(ctx, storePath) {
206
232
  reportRecordFailure(err);
207
233
  }
208
234
  }
235
+ /** One evidence row, normalizing an unknown source to "no source recorded". */
236
+ function normalizeEvidence(raw) {
237
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
238
+ return undefined;
239
+ const e = raw;
240
+ if (typeof e.phrase !== "string" || !e.phrase)
241
+ return undefined;
242
+ return e.source === "frontmatter" || e.source === "heading" || e.source === "description"
243
+ ? { phrase: e.phrase, source: e.source }
244
+ : { phrase: e.phrase };
245
+ }
246
+ /**
247
+ * Normalize one raw applicability line; undefined when the line is not one.
248
+ * Field junk is coerced to a safe default rather than trusted, matching the
249
+ * adoption reader's posture.
250
+ */
251
+ function normalizeApplicabilityRecord(raw) {
252
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
253
+ return undefined;
254
+ const r = raw;
255
+ if (r.kind !== "applicability")
256
+ return undefined;
257
+ if (typeof r.sessionId !== "string" || !r.sessionId)
258
+ return undefined;
259
+ if (typeof r.month !== "string" || !/^\d{4}-\d{2}$/.test(r.month))
260
+ return undefined;
261
+ const base = {
262
+ kind: "applicability",
263
+ sessionId: r.sessionId,
264
+ role: normalizeProfileName(r.role) ?? NEUTRAL_SESSION_PROFILE,
265
+ month: r.month,
266
+ updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "",
267
+ };
268
+ if (typeof r.skill === "string" && r.skill) {
269
+ if (r.applicability !== "read" && r.applicability !== "ignored")
270
+ return undefined;
271
+ const evidence = [];
272
+ for (const item of Array.isArray(r.evidence) ? r.evidence : []) {
273
+ const normalized = normalizeEvidence(item);
274
+ if (normalized)
275
+ evidence.push(normalized);
276
+ }
277
+ return { ...base, skill: r.skill, applicability: r.applicability, evidence };
278
+ }
279
+ const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
280
+ return {
281
+ ...base,
282
+ taskChars: count(r.taskChars),
283
+ evaluated: count(r.evaluated),
284
+ undeclared: (Array.isArray(r.undeclared) ? r.undeclared : []).filter((name) => typeof name === "string" && name !== ""),
285
+ };
286
+ }
287
+ /**
288
+ * Read the applicability records from the store. Missing or unreadable file →
289
+ * empty (never throws); non-applicability and corrupt lines are skipped.
290
+ */
291
+ export function readApplicabilityRecords(storePath) {
292
+ let text;
293
+ try {
294
+ text = readFileSync(storePath, "utf-8");
295
+ }
296
+ catch {
297
+ return []; // missing or unreadable → no records
298
+ }
299
+ const out = [];
300
+ for (const line of text.split("\n")) {
301
+ const trimmed = line.trim();
302
+ if (!trimmed)
303
+ continue;
304
+ try {
305
+ const rec = normalizeApplicabilityRecord(JSON.parse(trimmed));
306
+ if (rec)
307
+ out.push(rec);
308
+ }
309
+ catch {
310
+ // torn or corrupt line — skip
311
+ }
312
+ }
313
+ return out;
314
+ }
315
+ /**
316
+ * Merge two verdicts for the same skill: `read` beats `ignored` (a read is
317
+ * evidence the skill's content reached the session, whatever the turn order
318
+ * was), and the evidence unions by (phrase, source), bounded like every other
319
+ * evidence surface. Pure.
320
+ */
321
+ function mergeVerdict(current, next) {
322
+ if (!current)
323
+ return next;
324
+ const byPhrase = new Map();
325
+ for (const evidence of [...current.evidence, ...next.evidence]) {
326
+ const key = `${evidence.phrase}\u0000${evidence.source ?? ""}`;
327
+ if (!byPhrase.has(key) && byPhrase.size < MAX_APPLICABILITY_EVIDENCE) {
328
+ byPhrase.set(key, evidence);
329
+ }
330
+ }
331
+ return {
332
+ name: next.name,
333
+ verdict: current.verdict === "read" || next.verdict === "read" ? "read" : "ignored",
334
+ evidence: [...byPhrase.values()],
335
+ };
336
+ }
337
+ /**
338
+ * Fold the store into one logical record per sessionId: the newest census wins
339
+ * the session facts, verdict rows union across writes with `read` beating
340
+ * `ignored`. Pure. The fold is what makes a torn, duplicated or out-of-order
341
+ * append harmless: the record set, not the line order, decides a verdict.
342
+ */
343
+ export function foldApplicabilityRecords(records) {
344
+ const byId = new Map();
345
+ const empty = (rec) => ({
346
+ sessionId: rec.sessionId,
347
+ role: rec.role,
348
+ month: rec.month,
349
+ updatedAt: rec.updatedAt,
350
+ taskChars: 0,
351
+ evaluated: 0,
352
+ undeclared: [],
353
+ verdicts: [],
354
+ classes: { read: 0, ignored: 0, notApplicable: 0 },
355
+ });
356
+ for (const rec of records) {
357
+ const prev = byId.get(rec.sessionId) ?? empty(rec);
358
+ // Session facts come from the newest CENSUS row; verdict rows carry no
359
+ // census of their own and must not erase it.
360
+ const newer = rec.updatedAt >= prev.updatedAt;
361
+ const verdicts = new Map(prev.verdicts.map((v) => [v.name, v]));
362
+ if ("skill" in rec) {
363
+ verdicts.set(rec.skill, mergeVerdict(verdicts.get(rec.skill), {
364
+ name: rec.skill,
365
+ verdict: rec.applicability,
366
+ evidence: rec.evidence,
367
+ }));
368
+ }
369
+ const census = "evaluated" in rec ? (newer ? rec : undefined) : undefined;
370
+ byId.set(rec.sessionId, {
371
+ sessionId: rec.sessionId,
372
+ role: newer ? rec.role : prev.role,
373
+ month: newer ? rec.month : prev.month,
374
+ updatedAt: newer ? rec.updatedAt : prev.updatedAt,
375
+ taskChars: census ? census.taskChars : prev.taskChars,
376
+ evaluated: census ? census.evaluated : prev.evaluated,
377
+ undeclared: census ? census.undeclared : prev.undeclared,
378
+ verdicts: [...verdicts.values()],
379
+ classes: { read: 0, ignored: 0, notApplicable: 0 },
380
+ });
381
+ }
382
+ for (const rec of byId.values()) {
383
+ const read = rec.verdicts.filter((v) => v.verdict === "read").length;
384
+ const ignored = rec.verdicts.length - read;
385
+ rec.classes = { read, ignored, notApplicable: Math.max(0, rec.evaluated - read - ignored) };
386
+ }
387
+ return [...byId.values()];
388
+ }
389
+ /** Resolve the session identity a record needs, or undefined for a fake ctx. */
390
+ function applicabilityBase(ctx) {
391
+ const sess = resolveSession(ctx);
392
+ if (!sess)
393
+ return undefined;
394
+ return {
395
+ sessionId: sess.sessionId,
396
+ role: getSessionProfile(ctx).name,
397
+ month: monthOf(new Date()),
398
+ updatedAt: new Date().toISOString(),
399
+ };
400
+ }
401
+ /**
402
+ * Append the session's census row. Best-effort like every other writer here: a
403
+ * false return means the line did not land, never a thrown turn.
404
+ */
405
+ export function recordApplicabilityCensus(ctx, census, storePath) {
406
+ try {
407
+ const base = applicabilityBase(ctx);
408
+ if (!base)
409
+ return false;
410
+ return appendLine({ kind: "applicability", ...base, ...census }, storePath ?? getSkillsSessionsFilePath());
411
+ }
412
+ catch (err) {
413
+ reportRecordFailure(err);
414
+ return false;
415
+ }
416
+ }
417
+ /**
418
+ * Append one skill's verdict row. The same function writes the `read` upgrade:
419
+ * the fold decides, so no line is ever rewritten.
420
+ */
421
+ export function recordApplicabilityVerdict(ctx, verdict, storePath) {
422
+ try {
423
+ const base = applicabilityBase(ctx);
424
+ if (!base)
425
+ return false;
426
+ return appendLine({ kind: "applicability", ...base, ...verdict }, storePath ?? getSkillsSessionsFilePath());
427
+ }
428
+ catch (err) {
429
+ reportRecordFailure(err);
430
+ return false;
431
+ }
432
+ }
433
+ /**
434
+ * The folded applicability record for the context's own session, or undefined
435
+ * when the session wrote none. Reader: a refused path or a torn store is a
436
+ * miss, not a throw.
437
+ */
438
+ export function getSessionApplicability(ctx, options = {}) {
439
+ try {
440
+ const sess = resolveSession(ctx);
441
+ if (!sess)
442
+ return undefined;
443
+ const storePath = options.storePath ?? getSkillsSessionsFilePath();
444
+ return foldApplicabilityRecords(readApplicabilityRecords(storePath)).find((rec) => rec.sessionId === sess.sessionId);
445
+ }
446
+ catch (err) {
447
+ reportRecordFailure(err);
448
+ return undefined;
449
+ }
450
+ }
451
+ /** Normalize a parsed JSON line into an obligation record, or null. */
452
+ export function normalizeObligationRecord(raw) {
453
+ if (!raw || typeof raw !== "object")
454
+ return null;
455
+ const r = raw;
456
+ if (r.kind !== "obligation")
457
+ return null;
458
+ if (typeof r.sessionId !== "string" || typeof r.skill !== "string" || !r.skill.trim()) {
459
+ return null;
460
+ }
461
+ return {
462
+ kind: "obligation",
463
+ sessionId: r.sessionId,
464
+ role: typeof r.role === "string" ? r.role : NEUTRAL_SESSION_PROFILE,
465
+ month: typeof r.month === "string" ? r.month : "",
466
+ updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "",
467
+ skill: r.skill,
468
+ suggested: r.suggested === true,
469
+ listed: r.listed === true,
470
+ informed: r.informed === true,
471
+ read: r.read === true,
472
+ called: r.called === true,
473
+ applied: r.applied === true,
474
+ };
475
+ }
476
+ /**
477
+ * Read the obligation records from the store. Missing or unreadable file →
478
+ * empty (never throws); other kinds and corrupt lines are skipped.
479
+ */
480
+ export function readObligationRecords(storePath = getSkillsSessionsFilePath()) {
481
+ let text;
482
+ try {
483
+ text = readFileSync(storePath, "utf-8");
484
+ }
485
+ catch {
486
+ return []; // missing or unreadable → no records
487
+ }
488
+ const out = [];
489
+ for (const line of text.split("\n")) {
490
+ const trimmed = line.trim();
491
+ if (!trimmed)
492
+ continue;
493
+ try {
494
+ const rec = normalizeObligationRecord(JSON.parse(trimmed));
495
+ if (rec)
496
+ out.push(rec);
497
+ }
498
+ catch {
499
+ // torn or corrupt line — skip
500
+ }
501
+ }
502
+ return out;
503
+ }
504
+ /**
505
+ * Fold a session's obligation rows into one record: the legs OR across every
506
+ * row, so a row that saw one leg never erases a leg a later row did not have.
507
+ * `called`/`applied` are written once per skill, so the OR is exact rather
508
+ * than convenient. A torn or duplicated row folds; a malformed one is dropped
509
+ * at normalize, before this sees it.
510
+ */
511
+ export function foldObligationRecords(records) {
512
+ const bySession = new Map();
513
+ for (const rec of records) {
514
+ let session = bySession.get(rec.sessionId);
515
+ if (!session) {
516
+ session = {
517
+ sessionId: rec.sessionId,
518
+ role: rec.role,
519
+ month: rec.month,
520
+ updatedAt: rec.updatedAt,
521
+ skills: [],
522
+ };
523
+ bySession.set(rec.sessionId, session);
524
+ }
525
+ else if (rec.updatedAt >= session.updatedAt) {
526
+ session.role = rec.role;
527
+ session.month = rec.month;
528
+ session.updatedAt = rec.updatedAt;
529
+ }
530
+ const held = session.skills.find((legs) => legs.skill === rec.skill);
531
+ if (!held) {
532
+ session.skills.push({
533
+ skill: rec.skill,
534
+ suggested: rec.suggested,
535
+ listed: rec.listed,
536
+ informed: rec.informed,
537
+ read: rec.read,
538
+ called: rec.called,
539
+ applied: rec.applied,
540
+ });
541
+ continue;
542
+ }
543
+ held.suggested = held.suggested || rec.suggested;
544
+ held.listed = held.listed || rec.listed;
545
+ held.informed = held.informed || rec.informed;
546
+ held.read = held.read || rec.read;
547
+ held.called = held.called || rec.called;
548
+ held.applied = held.applied || rec.applied;
549
+ }
550
+ return [...bySession.values()];
551
+ }
552
+ /**
553
+ * Append one skill's legs. Best-effort like the sibling writer: a refused or
554
+ * missing store returns false so the caller can retry on a later turn.
555
+ */
556
+ export function recordObligationLegs(ctx, legs, storePath) {
557
+ try {
558
+ const base = applicabilityBase(ctx);
559
+ if (!base)
560
+ return false;
561
+ const record = {
562
+ kind: "obligation",
563
+ ...base,
564
+ skill: legs.skill,
565
+ suggested: legs.suggested,
566
+ listed: legs.listed,
567
+ informed: legs.informed,
568
+ read: legs.read,
569
+ called: legs.called,
570
+ applied: legs.applied,
571
+ };
572
+ return appendLine(record, storePath ?? getSkillsSessionsFilePath());
573
+ }
574
+ catch (err) {
575
+ reportRecordFailure(err);
576
+ return false;
577
+ }
578
+ }
579
+ /** The current session's obligation rows, folded. Missing store → undefined. */
580
+ export function getSessionObligation(ctx, options = {}) {
581
+ try {
582
+ const sess = resolveSession(ctx);
583
+ if (!sess)
584
+ return undefined;
585
+ const storePath = options.storePath ?? getSkillsSessionsFilePath();
586
+ return foldObligationRecords(readObligationRecords(storePath)).find((rec) => rec.sessionId === sess.sessionId);
587
+ }
588
+ catch (err) {
589
+ reportRecordFailure(err);
590
+ return undefined;
591
+ }
592
+ }
593
+ /**
594
+ * An obligation is satisfied when the body was read AND, if the session ever
595
+ * called into a family the skill declares, that the first call came after the
596
+ * read. Without a declared family the second clause is vacuous: reading the
597
+ * body is the whole obligation.
598
+ */
599
+ export function obligationSatisfied(legs) {
600
+ return legs.read && (!legs.called || legs.applied);
601
+ }
602
+ /**
603
+ * Judge one session against its obligation rows. Pure.
604
+ *
605
+ * A skill is an obligation when the applicability fold carries a verdict for
606
+ * it: the previous record's question was whether the skill applied, and this
607
+ * one takes that answer as given. An obligation is decided by this record's
608
+ * legs alone, which is why the two kinds can be folded independently and
609
+ * joined on (sessionId, skill) without either re-reading the other.
610
+ */
611
+ export function judgeSessionObligations(applicable, obligation) {
612
+ if (!applicable)
613
+ return undefined;
614
+ const applied = new Set(applicable.verdicts.map((verdict) => verdict.name));
615
+ const skills = (obligation?.skills ?? []).map((legs) => ({
616
+ ...legs,
617
+ satisfied: applied.has(legs.skill) ? obligationSatisfied(legs) : null,
618
+ }));
619
+ // An applicable skill with no leg row still owes the read: a session that was
620
+ // never offered, listed, or read the body it owed is the ignored population,
621
+ // and dropping it from the denominator would report only the sessions that
622
+ // happened to be instrumented.
623
+ const seen = new Set(skills.map((legs) => legs.skill));
624
+ for (const skill of applied) {
625
+ if (seen.has(skill))
626
+ continue;
627
+ skills.push({
628
+ skill,
629
+ suggested: false,
630
+ listed: false,
631
+ informed: false,
632
+ read: false,
633
+ called: false,
634
+ applied: false,
635
+ satisfied: false,
636
+ });
637
+ }
638
+ if (!applicable.verdicts.length) {
639
+ return { skills, allSatisfied: false, obligations: 0 };
640
+ }
641
+ const obligations = skills.filter((legs) => legs.satisfied !== null);
642
+ return {
643
+ skills,
644
+ obligations: obligations.length,
645
+ allSatisfied: obligations.every((legs) => legs.satisfied === true),
646
+ };
647
+ }
648
+ /**
649
+ * The design's own decision rule: a gap this small makes the rate a duplicate
650
+ * of the read rate, and a duplicate should be deleted rather than shipped.
651
+ */
652
+ export const FALSIFIER_GAP_POINTS = 5;
653
+ /** Compute both rates over one store's folds. Pure. */
654
+ export function computeObligationRate(sessions, obligations) {
655
+ const bySession = new Map(obligations.map((rec) => [rec.sessionId, rec]));
656
+ let population = 0;
657
+ let allSatisfied = 0;
658
+ let withRead = 0;
659
+ let obligationsSeen = 0;
660
+ let unsatisfied = 0;
661
+ let uninstrumented = 0;
662
+ for (const session of sessions) {
663
+ if (!session.verdicts.length)
664
+ continue;
665
+ const legs = bySession.get(session.sessionId);
666
+ if (!legs || !legs.skills.length) {
667
+ uninstrumented++;
668
+ continue;
669
+ }
670
+ const judgement = judgeSessionObligations(session, legs);
671
+ if (!judgement)
672
+ continue;
673
+ population++;
674
+ obligationsSeen += judgement.obligations;
675
+ if (judgement.allSatisfied)
676
+ allSatisfied++;
677
+ if (legs.skills.some((row) => row.read))
678
+ withRead++;
679
+ unsatisfied += judgement.skills.filter((row) => row.satisfied === false).length;
680
+ }
681
+ const allSatisfiedRate = population ? round4(allSatisfied / population) : 0;
682
+ const readRate = population ? round4(withRead / population) : 0;
683
+ const gapPoints = Math.round((allSatisfiedRate - readRate) * 10000) / 100;
684
+ return {
685
+ sessions: population,
686
+ allSatisfied,
687
+ allSatisfiedRate,
688
+ withRead,
689
+ readRate,
690
+ gapPoints,
691
+ obligations: obligationsSeen,
692
+ unsatisfied,
693
+ discriminating: Math.abs(gapPoints) >= FALSIFIER_GAP_POINTS,
694
+ uninstrumented,
695
+ };
696
+ }
697
+ function round4(n) {
698
+ return Math.round(n * 10000) / 10000;
699
+ }
700
+ /**
701
+ * The store-wide rate, or undefined when the store carries no obligation row
702
+ * at all. Undefined is the absent record: a reader of a store this build has
703
+ * not written to sees the payload it always saw, byte for byte.
704
+ */
705
+ export function getObligationRate(options = {}) {
706
+ try {
707
+ const storePath = options.storePath ?? getSkillsSessionsFilePath();
708
+ const obligationRecords = readObligationRecords(storePath);
709
+ if (!obligationRecords.length)
710
+ return undefined;
711
+ return computeObligationRate(foldApplicabilityRecords(readApplicabilityRecords(storePath)), foldObligationRecords(obligationRecords));
712
+ }
713
+ catch (err) {
714
+ reportRecordFailure(err);
715
+ return undefined;
716
+ }
717
+ }
718
+ // The at-use inform, measured against the suggestion channel
719
+ /**
720
+ * The suggestion channel's pair conversion as published from session-file
721
+ * mining: 95 read-followed pairs out of 506 delivered ones, Wilson 15.6-22.4.
722
+ *
723
+ * It is a measurement constant, not a target: it stands in as the comparison
724
+ * arm only while the same store carries too few suggested pairs of its own to
725
+ * stand on its own (see INFORM_DECISION_MIN_PAIRS). A two-pair store arm that
726
+ * happens to have converted nothing is not a baseline; it is a sample. The
727
+ * moment the store holds the floor of suggested pairs, their own fold answers
728
+ * and this number is not read.
729
+ */
730
+ export const CHANNEL_PUBLISHED_CONVERSION = 0.188;
731
+ /** Wilson 95% bounds for that published figure, as proportions. */
732
+ export const CHANNEL_PUBLISHED_INTERVAL = { lower: 0.156, upper: 0.224 };
733
+ /**
734
+ * Informs needed before the comparison decides anything. Below this the
735
+ * answer is "undecided": a verdict from a handful of pairs would be a verdict
736
+ * about the sample, and the report's decision rule says so in writing before
737
+ * the first inform lands. The same floor governs the comparison arm: a store
738
+ * carrying fewer suggested pairs than this is not a baseline to beat.
739
+ */
740
+ export const INFORM_DECISION_MIN_PAIRS = 20;
741
+ /**
742
+ * Wilson score interval for k successes in n trials (95% by default). Chosen
743
+ * over the normal approximation because the inform population is small and a
744
+ * small-sample interval is the only one that can say "undecided" honestly.
745
+ * Returns zeros for n = 0. Pure.
746
+ */
747
+ export function wilsonInterval(successes, total, z = 1.959963985) {
748
+ if (!total || total < 0)
749
+ return { lower: 0, upper: 0 };
750
+ const p = Math.min(1, Math.max(0, successes / total));
751
+ const denominator = 1 + (z * z) / total;
752
+ const centre = (p + (z * z) / (2 * total)) / denominator;
753
+ const half = (z * Math.sqrt((p * (1 - p)) / total + (z * z) / (4 * total * total))) / denominator;
754
+ return {
755
+ lower: round4(Math.max(0, centre - half)),
756
+ upper: round4(Math.min(1, centre + half)),
757
+ };
758
+ }
759
+ /**
760
+ * Fold the obligation rows into the at-use rate and the channel arm beside it.
761
+ * Pure.
762
+ *
763
+ * The rule, applied literally: fewer than the floor is undecided; at the floor
764
+ * the inform beats the channel only when its point estimate is above the
765
+ * channel's AND its lower Wilson bound is above it too. Anything else at the
766
+ * floor is noise, which is the falsifier firing rather than a neutral result.
767
+ */
768
+ export function computeInformRate(obligations) {
769
+ let informs = 0;
770
+ let informRead = 0;
771
+ let channelPairs = 0;
772
+ let channelRead = 0;
773
+ const bySkill = new Map();
774
+ for (const session of obligations) {
775
+ for (const legs of session.skills) {
776
+ if (legs.suggested) {
777
+ channelPairs++;
778
+ if (legs.read)
779
+ channelRead++;
780
+ }
781
+ if (!legs.informed)
782
+ continue;
783
+ informs++;
784
+ if (legs.read)
785
+ informRead++;
786
+ let row = bySkill.get(legs.skill);
787
+ if (!row) {
788
+ row = { skill: legs.skill, informs: 0, readFollowed: 0 };
789
+ bySkill.set(legs.skill, row);
790
+ }
791
+ row.informs++;
792
+ if (legs.read)
793
+ row.readFollowed++;
794
+ }
795
+ }
796
+ const conversion = informs ? round4(informRead / informs) : 0;
797
+ const channel = channelPairs >= INFORM_DECISION_MIN_PAIRS
798
+ ? {
799
+ pairs: channelPairs,
800
+ readFollowed: channelRead,
801
+ conversion: round4(channelRead / channelPairs),
802
+ ci: wilsonInterval(channelRead, channelPairs),
803
+ source: "store",
804
+ }
805
+ : {
806
+ pairs: channelPairs,
807
+ readFollowed: channelRead,
808
+ conversion: CHANNEL_PUBLISHED_CONVERSION,
809
+ ci: CHANNEL_PUBLISHED_INTERVAL,
810
+ source: "published",
811
+ };
812
+ const ci = wilsonInterval(informRead, informs);
813
+ const decidable = informs >= INFORM_DECISION_MIN_PAIRS;
814
+ const verdict = !decidable
815
+ ? "undecided"
816
+ : conversion > channel.conversion && ci.lower > channel.conversion
817
+ ? "beats"
818
+ : "noise";
819
+ return {
820
+ informs,
821
+ readFollowed: informRead,
822
+ conversion,
823
+ ci,
824
+ skills: [...bySkill.values()],
825
+ channel,
826
+ gapPoints: Math.round((conversion - channel.conversion) * 10000) / 100,
827
+ decidable,
828
+ verdict,
829
+ };
830
+ }
831
+ /**
832
+ * The store-wide at-use rate, or undefined when the store carries no inform row
833
+ * at all. Undefined keeps every existing `skill_stats` payload byte-identical
834
+ * for a build or an install that never emitted one.
835
+ */
836
+ export function getInformRate(options = {}) {
837
+ try {
838
+ const storePath = options.storePath ?? getSkillsSessionsFilePath();
839
+ const records = readObligationRecords(storePath);
840
+ if (!records.some((rec) => rec.informed))
841
+ return undefined;
842
+ return computeInformRate(foldObligationRecords(records));
843
+ }
844
+ catch (err) {
845
+ reportRecordFailure(err);
846
+ return undefined;
847
+ }
848
+ }
209
849
  /**
210
850
  * Compute the monthly adoption rollup for the current + previous 2
211
851
  * months, keyed by session profile name. Pure (given records + now).