@seanhogg/builderforce-memory 2026.10.69 → 2026.10.71

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/dist/knowledge/build.d.ts +3 -1
  2. package/dist/knowledge/build.d.ts.map +1 -1
  3. package/dist/knowledge/build.js +5 -1
  4. package/dist/knowledge/build.js.map +1 -1
  5. package/dist/knowledge/coChange.d.ts +104 -0
  6. package/dist/knowledge/coChange.d.ts.map +1 -0
  7. package/dist/knowledge/coChange.js +297 -0
  8. package/dist/knowledge/coChange.js.map +1 -0
  9. package/dist/knowledge/communities.d.ts +2 -0
  10. package/dist/knowledge/communities.d.ts.map +1 -1
  11. package/dist/knowledge/communities.js +5 -1
  12. package/dist/knowledge/communities.js.map +1 -1
  13. package/dist/knowledge/comparability.d.ts +3 -1
  14. package/dist/knowledge/comparability.d.ts.map +1 -1
  15. package/dist/knowledge/comparability.js +2 -1
  16. package/dist/knowledge/comparability.js.map +1 -1
  17. package/dist/knowledge/index.d.ts +5 -1
  18. package/dist/knowledge/index.d.ts.map +1 -1
  19. package/dist/knowledge/index.js +3 -1
  20. package/dist/knowledge/index.js.map +1 -1
  21. package/dist/knowledge/outline.d.ts.map +1 -1
  22. package/dist/knowledge/outline.js +2 -0
  23. package/dist/knowledge/outline.js.map +1 -1
  24. package/dist/knowledge/refs.d.ts.map +1 -1
  25. package/dist/knowledge/refs.js +3 -1
  26. package/dist/knowledge/refs.js.map +1 -1
  27. package/dist/knowledge/sources.d.ts +1 -1
  28. package/dist/knowledge/sources.d.ts.map +1 -1
  29. package/dist/knowledge/sources.js +3 -1
  30. package/dist/knowledge/sources.js.map +1 -1
  31. package/dist/knowledge/transitions.d.ts +59 -0
  32. package/dist/knowledge/transitions.d.ts.map +1 -0
  33. package/dist/knowledge/transitions.js +90 -0
  34. package/dist/knowledge/transitions.js.map +1 -0
  35. package/dist/stats/distributions.d.ts +23 -1
  36. package/dist/stats/distributions.d.ts.map +1 -1
  37. package/dist/stats/distributions.js +102 -19
  38. package/dist/stats/distributions.js.map +1 -1
  39. package/dist/stats/index.d.ts +1 -1
  40. package/dist/stats/index.d.ts.map +1 -1
  41. package/dist/stats/index.js +1 -1
  42. package/dist/stats/index.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/contract/exports.snapshot.json +21 -0
  45. package/src/contract/regression.analysisTruncated.test.ts +32 -0
  46. package/src/contract/regression.assets.test.ts +4 -0
  47. package/src/contract/types.contract.test.ts +50 -1
  48. package/src/knowledge/build.ts +5 -1
  49. package/src/knowledge/coChange.test.ts +297 -0
  50. package/src/knowledge/coChange.ts +333 -0
  51. package/src/knowledge/communities.ts +6 -1
  52. package/src/knowledge/comparability.analysis.test.ts +16 -1
  53. package/src/knowledge/comparability.ts +4 -1
  54. package/src/knowledge/index.ts +8 -1
  55. package/src/knowledge/outline.ts +2 -0
  56. package/src/knowledge/refs.ts +4 -1
  57. package/src/knowledge/sources.ts +3 -1
  58. package/src/knowledge/transitions.test.ts +135 -0
  59. package/src/knowledge/transitions.ts +115 -0
  60. package/src/stats/distributions.ts +103 -20
  61. package/src/stats/index.ts +3 -0
  62. package/src/stats/stats.test.ts +89 -0
@@ -5,7 +5,7 @@
5
5
  * names/versions are restated below; the analyzer-RUNNING cases stay in agent-tools.
6
6
  */
7
7
 
8
- import { compareAnalysis, identityOfIssue, normalizeAnalysis, type CodeAnalysisSnapshot } from './comparability.js';
8
+ import { analysisMeta, compareAnalysis, identityOfIssue, normalizeAnalysis, type CodeAnalysisSnapshot } from './comparability.js';
9
9
 
10
10
  const ANALYZERS = [{ name: 'dependency-cruiser', version: '16.10.4' }, { name: 'jscpd', version: '4.0.5' }, { name: 'knip', version: '5.62.0' }];
11
11
 
@@ -71,3 +71,18 @@ describe('compareAnalysis delegates to comparable()', () => {
71
71
  expect(compareAnalysis(scoped, snapshot()).reasons).toEqual(['scope-changed']);
72
72
  });
73
73
  });
74
+
75
+ describe('a truncated snapshot (PRD 41 B2, C9)', () => {
76
+ it('carries truncated into its meta only when set', () => {
77
+ expect(analysisMeta({ ...snapshot(), truncated: true })).toMatchObject({ truncated: true });
78
+ expect(analysisMeta(snapshot())).not.toHaveProperty('truncated');
79
+ });
80
+ it('is not comparable on either side, so it reports nothing added or resolved', () => {
81
+ const full = snapshot(); const cut = { ...snapshot(), truncated: true as const, issues: snapshot().issues.slice(1) };
82
+ for (const [current, baseline] of [[cut, full], [full, cut]] as const) {
83
+ const result = compareAnalysis(current, baseline);
84
+ expect(result).toMatchObject({ comparable: false, reasons: ['truncated'], added: [], resolved: [] });
85
+ }
86
+ expect(compareAnalysis(snapshot(), snapshot())).toMatchObject({ comparable: true, reasons: [] });
87
+ });
88
+ });
@@ -83,6 +83,8 @@ export interface CodeAnalysisSnapshot {
83
83
  nodes: string[];
84
84
  edges: Array<{ from: string; to: string; circular: boolean }>;
85
85
  issues: AnalysisIssue[];
86
+ /** Set when the analyzed scope was cut short (the host's file cap, or a listing that stopped early): the analysis is partial, so it is never comparable (reason `truncated`). */
87
+ truncated?: true;
86
88
  }
87
89
  export interface CodeAnalysisComparison { current: CodeAnalysisSnapshot; baseline?: CodeAnalysisSnapshot }
88
90
 
@@ -155,12 +157,13 @@ export function identityOfIssue(issue: AnalysisIssue): FindingIdentity {
155
157
  return { id: issue.id, anchor: issue.anchor ?? composeAnchor(issue.kind, ANALYSIS_ANCHOR_VERSION, anchorKind, anchorWithSnippet(primary, issue.snippet)), anchorKind, members };
156
158
  }
157
159
 
158
- /** A snapshot's comparability meta: source scope/repo/branch, tool versions, and every tool not `complete` as failed. */
160
+ /** A snapshot's comparability meta: source scope/repo/branch, tool versions, every tool not `complete` as failed, and `truncated` (only when set). */
159
161
  export function analysisMeta(snapshot: CodeAnalysisSnapshot): ComparabilityMeta {
160
162
  return {
161
163
  scope: snapshot.source.scope, repo: snapshot.source.repository, branch: snapshot.source.branch ?? undefined,
162
164
  tools: Object.fromEntries(snapshot.tools.map((t) => [t.name, t.version])),
163
165
  failed: snapshot.tools.filter((t) => t.status !== 'complete').map((t) => t.name),
166
+ ...(snapshot.truncated ? { truncated: true } : {}),
164
167
  };
165
168
  }
166
169
 
@@ -32,6 +32,13 @@ export {
32
32
  COMMUNITY_MAX_PASSES, COMMUNITY_MAX_ITERATIONS, COMMUNITY_LP_ITERATIONS,
33
33
  } from './communities.js';
34
34
  export type { CommunityMembership, CommunityMethod, CommunityResult, NodePlacement } from './communities.js';
35
+ export {
36
+ coChangePartners, encodeCoChange, decodeCoChange, coChangeRecallAtK, applyCoChangeHidden, COCHANGE_MIN_SUPPORT, COCHANGE_MIN_LIFT,
37
+ COCHANGE_MAX_COMMIT_FILES, COCHANGE_MAX_PARTNERS, COCHANGE_MAX_COMMITS, COCHANGE_BADGE, COCHANGE_HIDDEN_BADGE,
38
+ } from './coChange.js';
39
+ export type { CoChangeBadgeEntry, CoChangeCommit, CoChangeOptions, CoChangePartner, CoChangeRecall } from './coChange.js';
40
+ export { transitionsFromWeights, transitionsFromSequences, stationTransitions, transitionOf, mostLikelyWalk } from './transitions.js';
41
+ export type { StationTransition, TransitionRow, TransitionSource, TransitionTable } from './transitions.js';
35
42
  export { pageRank, byImportance, areaImportance, PAGERANK_DAMPING, PAGERANK_ITERATIONS } from './importance.js';
36
43
  export {
37
44
  loadPartitions, partitionOf, partitionOrder, verdictOf, globToRegExp, matchGlob, TOP_LEVEL_FOLDER,
@@ -89,7 +96,7 @@ export {
89
96
  DEFAULT_REVIEW_MODEL_CALLS, DEFAULT_REVIEW_JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE,
90
97
  } from './judge.js';
91
98
  export {
92
- composePacks, ignoreMatcher, ignoreSourcesOf, isAssetPath, isBinaryPath, isBinaryText, isDocumentPath, mediaTypeOfPath,
99
+ composePacks, ignoreMatcher, ignoreSourcesOf, isAssetPath, isBinaryBytes, isBinaryPath, isBinaryText, isDocumentPath, mediaTypeOfPath,
93
100
  resolveDocument, resolveRelativePath,
94
101
  DEFAULT_MAX_FILE_BYTES, EXTRACTOR_VERSION, filesManifestKey, extractorManifestKey, judgedManifestKey, compareManifestKey,
95
102
  } from './sources.js';
@@ -19,6 +19,8 @@ export const OUTLINE_BADGE_KEYS: readonly string[] = [
19
19
  'complexity', 'maxComplexity', 'coverage', 'churn', 'owner', 'patterns', 'cloneGroup', 'unused', 'unusedExports',
20
20
  'entry', 'layerRule', 'unusedDependencies', 'externals', 'added', 'removed', 'changed', 'status',
21
21
  'communityId', 'communityConfidence',
22
+ // PRD 38 P4 (coChange.ts): the encoded co-change partners (read with decodeCoChange) and how many no reference explains.
23
+ 'coChange', 'coChangeHidden',
22
24
  // An asset file (assetFile.ts): a binary file the review stores as a node, never read.
23
25
  'asset', 'mediaType', 'size', 'oversized',
24
26
  ];
@@ -106,9 +106,12 @@ export function basenameOf(path: string): string {
106
106
  return i < 0 ? path : path.slice(i + 1);
107
107
  }
108
108
 
109
+ /** Bound once: a bare `Math.round` is a global lookup per call, ~1 µs inside a vm context (jest) on hot paths. */
110
+ const mathRound = Math.round;
111
+
109
112
  /** Rounds to 6 decimals so floating noise never reaches the JSON. */
110
113
  export function round6(n: number): number {
111
- return Math.round(n * 1e6) / 1e6;
114
+ return mathRound(n * 1e6) / 1e6;
112
115
  }
113
116
 
114
117
  /** JSON with object keys sorted and `undefined` members dropped — the canonical form for digests. */
@@ -22,7 +22,9 @@ export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
22
22
  * owedFiles.ts for how an unfinished one is carried to the next review).
23
23
  */
24
24
  // 5 (2026-11-10, PRD 43 P0b): the code pack's file nodes carry the file→file rollup of the symbol-level edge kinds.
25
- export const EXTRACTOR_VERSION = 5;
25
+ // 6 (2026-11-10, PRD 43 P0c): the agent-tools code pack resolves tsconfig path aliases, names callback-owner symbols,
26
+ // emits `new X().m()` call edges and reads JSX renders as calls, so cached code extracts re-run.
27
+ export const EXTRACTOR_VERSION = 6;
26
28
  /**
27
29
  * Always ignored: VCS internals, installed dependencies, builderforce config, and lockfiles (`yarn.lock`, `Cargo.lock` …): generated,
28
30
  * huge, and plain text — extracted they would cost judgement calls for nothing; they were never stored (once skipped as binary).
@@ -0,0 +1,135 @@
1
+ /**
2
+ * src/knowledge/transitions.test.ts
3
+ * PRD 38 P7: station transition probabilities — row normalisation, dropped self-loops, the per-row choice of traces over
4
+ * reference weights, intervals only on observed (trace) rows, and the greedy most-likely walk.
5
+ */
6
+
7
+ import {
8
+ mostLikelyWalk, stationTransitions, transitionOf, transitionsFromSequences, transitionsFromWeights,
9
+ } from './transitions.js';
10
+
11
+ const W = (from: string, to: string, weight: number) => ({ from, to, weight });
12
+ const same = (a: unknown, b: unknown) => expect(JSON.stringify(a)).toBe(JSON.stringify(b));
13
+ /** A trace history with `k` hops A → B and `n − k` hops A → C. */
14
+ const traces = (k: number, n: number) => [...Array.from({ length: k }, () => ['A', 'B']), ...Array.from({ length: n - k }, () => ['A', 'C'])];
15
+
16
+ describe('transitionsFromWeights', () => {
17
+ const t = transitionsFromWeights([W('A', 'B', 2), W('A', 'C', 1), W('A', 'B', 1), W('A', 'A', 5), W('B', 'A', 2), W('C', 'B', 0)]);
18
+
19
+ it('sums duplicate edges, drops self-loops and non-positive weights, and row-normalises', () => {
20
+ expect([...t.keys()]).toEqual(['A', 'B']);
21
+ expect(t.get('A')!.transitions.map((h) => [h.to, h.p, h.k, h.n])).toEqual([['B', 0.75, 3, 4], ['C', 0.25, 1, 4]]);
22
+ expect(t.get('B')!.transitions.map((h) => [h.to, h.p])).toEqual([['A', 1]]);
23
+ for (const row of t.values()) expect(row.transitions.reduce((s, h) => s + h.p, 0)).toBeCloseTo(1, 6);
24
+ });
25
+
26
+ it('reference rows are not observations: they say so and carry no interval', () => {
27
+ for (const row of t.values()) {
28
+ expect(row.source).toBe('references');
29
+ for (const h of row.transitions) expect('low' in h || 'high' in h).toBe(false);
30
+ }
31
+ });
32
+
33
+ it('rows sort p desc, then `to` asc, and shuffled input gives the same table', () => {
34
+ const edges = [W('S', 'z', 1), W('S', 'b', 1), W('S', 'm', 2)];
35
+ const a = transitionsFromWeights(edges);
36
+ expect(a.get('S')!.transitions.map((h) => h.to)).toEqual(['m', 'b', 'z']);
37
+ same([...transitionsFromWeights([...edges].reverse())], [...a]);
38
+ });
39
+ });
40
+
41
+ describe('transitionsFromSequences', () => {
42
+ it('counts first-order hops of the traces; a repeated station is not a hop', () => {
43
+ const t = transitionsFromSequences([['A', 'B', 'C'], ['A', 'A', 'B'], ['A', 'C']]);
44
+ expect(t.get('A')!.transitions.map((h) => [h.to, h.k, h.n, h.p])).toEqual([['B', 2, 3, 0.666667], ['C', 1, 3, 0.333333]]);
45
+ expect(t.get('B')!.transitions.map((h) => [h.to, h.p])).toEqual([['C', 1]]);
46
+ expect(t.get('A')!.source).toBe('traces');
47
+ expect(t.has('C')).toBe(false);
48
+ });
49
+
50
+ it('a trace hop carries the 90% Jeffreys interval: pinned at 3 of 4', () => {
51
+ const h = transitionOf(transitionsFromSequences(traces(3, 4)), 'A', 'B')!;
52
+ expect([h.p, h.low, h.high]).toEqual([0.75, 0.349293, 0.953993]);
53
+ });
54
+
55
+ it('the interval holds p (upper end 1 when every hop goes one way) and narrows with n', () => {
56
+ const all = transitionOf(transitionsFromSequences(traces(2, 2)), 'A', 'B')!;
57
+ expect([all.p, all.high]).toEqual([1, 1]);
58
+ expect(all.low).toBeLessThan(1);
59
+ const width = (k: number, n: number) => {
60
+ const h = transitionOf(transitionsFromSequences(traces(k, n)), 'A', 'B')!;
61
+ expect(h.low!).toBeLessThanOrEqual(h.p);
62
+ expect(h.high!).toBeGreaterThanOrEqual(h.p);
63
+ return h.high! - h.low!;
64
+ };
65
+ expect(width(30, 40)).toBeLessThan(width(3, 4));
66
+ expect(width(300, 400)).toBeLessThan(width(30, 40));
67
+ });
68
+ });
69
+
70
+ describe('stationTransitions', () => {
71
+ it('takes a station\'s trace row over its reference row', () => {
72
+ const t = stationTransitions({ sequences: [['A', 'C']], weights: [W('A', 'B', 10)] });
73
+ expect(t.get('A')!.source).toBe('traces');
74
+ expect(transitionOf(t, 'A', 'C')!.p).toBe(1);
75
+ expect(transitionOf(t, 'A', 'B')).toBeUndefined();
76
+ });
77
+
78
+ it('falls back per row: a station with no trace hop keeps its reference row', () => {
79
+ const t = stationTransitions({ sequences: [['A', 'B']], weights: [W('A', 'C', 5), W('B', 'C', 1), W('B', 'A', 3)] });
80
+ expect([...t].map(([from, row]) => [from, row.source])).toEqual([['A', 'traces'], ['B', 'references']]);
81
+ expect(t.get('B')!.transitions.map((h) => [h.to, h.p])).toEqual([['A', 0.75], ['C', 0.25]]);
82
+ expect(transitionOf(t, 'B', 'A')!.low).toBeUndefined();
83
+ expect(transitionOf(t, 'A', 'B')!.low).toBeDefined();
84
+ });
85
+
86
+ it.each([
87
+ ['no sequences', undefined], ['empty sequences', []], ['one-stop traces', [['A']]], ['traces that never move', [['A', 'A']]],
88
+ ])('is all references with %s', (_name, sequences) => {
89
+ const t = stationTransitions({ ...(sequences ? { sequences } : {}), weights: [W('A', 'B', 10)] });
90
+ expect(t.get('A')!.source).toBe('references');
91
+ expect(transitionOf(t, 'A', 'B')!.p).toBe(1);
92
+ });
93
+ });
94
+
95
+ describe('mostLikelyWalk', () => {
96
+ // A → B and A → C tie at 0.5 (B wins on `to`); B → A is likelier but visited, so B goes to D; D has no successor.
97
+ const table = transitionsFromWeights([W('A', 'C', 1), W('A', 'B', 1), W('B', 'A', 9), W('B', 'D', 1), W('C', 'E', 1)]);
98
+
99
+ it('follows the per-hop argmax, breaks ties by `to`, never revisits, and stops at a dead end', () => {
100
+ const w = mostLikelyWalk(table, 'A', 10);
101
+ expect(w.stops).toEqual(['A', 'B', 'D']);
102
+ expect(w.hops.map((h) => [h.to, h.p])).toEqual([['B', 0.5], ['D', 0.1]]);
103
+ });
104
+
105
+ it('stops after maxHops', () => {
106
+ expect(mostLikelyWalk(table, 'A', 1).stops).toEqual(['A', 'B']);
107
+ expect(mostLikelyWalk(table, 'A', 0)).toEqual({ stops: ['A'], hops: [] });
108
+ });
109
+
110
+ it('a start with no row is a walk of one stop', () => {
111
+ expect(mostLikelyWalk(table, 'Z', 5)).toEqual({ stops: ['Z'], hops: [] });
112
+ });
113
+
114
+ it('over a mixed table: trace hops carry their interval, reference hops do not', () => {
115
+ // A and B have trace rows (A → B → C); C has none, so its reference row (C → D) continues the walk.
116
+ const mixed = stationTransitions({ sequences: [['A', 'B', 'C']], weights: [W('A', 'Z', 9), W('C', 'D', 1), W('C', 'A', 0)] });
117
+ const w = mostLikelyWalk(mixed, 'A', 10);
118
+ expect(w.stops).toEqual(['A', 'B', 'C', 'D']);
119
+ expect(w.hops.map((h) => [h.to, h.low !== undefined, h.high !== undefined])).toEqual([['B', true, true], ['C', true, true], ['D', false, false]]);
120
+ expect(w.hops[0]).toMatchObject({ p: 1, high: 1 });
121
+ expect('low' in w.hops[2]! || 'high' in w.hops[2]!).toBe(false);
122
+ });
123
+
124
+ it('a trace row that leads only to visited stations ends the walk; its reference row is not consulted', () => {
125
+ // B's traces only go back to A (visited); B's reference row would offer C, but the trace row wins for B.
126
+ const t = stationTransitions({ sequences: [['A', 'B', 'A']], weights: [W('B', 'C', 5)] });
127
+ expect(t.get('B')!.source).toBe('traces');
128
+ expect(mostLikelyWalk(t, 'A', 10).stops).toEqual(['A', 'B']);
129
+ });
130
+
131
+ it('is deterministic under shuffled input', () => {
132
+ const shuffled = transitionsFromWeights([W('C', 'E', 1), W('B', 'D', 1), W('B', 'A', 9), W('A', 'B', 1), W('A', 'C', 1)]);
133
+ same(mostLikelyWalk(shuffled, 'A', 10), mostLikelyWalk(table, 'A', 10));
134
+ });
135
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * knowledge/transitions.ts — station transition probabilities (PRD 38 P7: Simulate, "Run to end", path-strip hops).
3
+ *
4
+ * A first-order Markov chain over stations: P(j|i) = k / n, where k is the count (or weight) of i → j and n the total out
5
+ * of i. A station's row comes from recorded run traces when the traces have a hop out of it, otherwise from the reference
6
+ * weights between stations; each row says which (`source`). Self-loops are dropped (staying put is not a hop), as are
7
+ * non-positive weights.
8
+ *
9
+ * A trace row is an observation, so every hop carries its credible interval (`rateInterval`, ../stats). A reference row is
10
+ * not one, so its hops carry no interval (`low` / `high` are absent).
11
+ *
12
+ * Stations are a view concept: memory holds the formula, the view applies it to its station grouping.
13
+ * Deterministic: rows in station order, each row p desc then `to` asc; weights summed in ascending order.
14
+ */
15
+
16
+ import { rateInterval } from '../stats/index.js';
17
+ import { compareStr, round6 } from './refs.js';
18
+
19
+ export type TransitionSource = 'traces' | 'references';
20
+
21
+ export interface StationTransition {
22
+ to: string;
23
+ /** k / n, round6. */
24
+ p: number;
25
+ /** Count (traces) or weight (references) of this hop. */
26
+ k: number;
27
+ /** Total count or weight out of the row's station. */
28
+ n: number;
29
+ /** Credible interval of p (`rateInterval(k, n)`), round6. Only on a trace row. */
30
+ low?: number;
31
+ high?: number;
32
+ }
33
+
34
+ export interface TransitionRow {
35
+ source: TransitionSource;
36
+ transitions: readonly StationTransition[];
37
+ }
38
+
39
+ export type TransitionTable = ReadonlyMap<string, TransitionRow>;
40
+
41
+ type Weighted = ReadonlyArray<{ from: string; to: string; weight: number }>;
42
+
43
+ function tableOf(edges: Weighted, source: TransitionSource): Map<string, TransitionRow> {
44
+ const rows = new Map<string, Map<string, number[]>>();
45
+ for (const e of edges) {
46
+ if (e.from === e.to || !(e.weight > 0) || !Number.isFinite(e.weight)) continue;
47
+ const row = rows.get(e.from) ?? new Map<string, number[]>();
48
+ const ws = row.get(e.to) ?? [];
49
+ ws.push(e.weight);
50
+ row.set(e.to, ws);
51
+ rows.set(e.from, row);
52
+ }
53
+ const sum = (ws: number[]) => [...ws].sort((a, b) => a - b).reduce((s, w) => s + w, 0);
54
+ const table = new Map<string, TransitionRow>();
55
+ for (const from of [...rows.keys()].sort(compareStr)) {
56
+ const hops = [...rows.get(from)!].map(([to, ws]) => ({ to, k: sum(ws) }));
57
+ const n = sum(hops.map((h) => h.k));
58
+ const transitions = hops.map(({ to, k }): StationTransition => {
59
+ const hop = { to, p: round6(k / n), k: round6(k), n: round6(n) };
60
+ if (source === 'references') return hop;
61
+ const { low, high } = rateInterval(k, n);
62
+ return { ...hop, low: round6(low), high: round6(high) };
63
+ }).sort((a, b) => b.p - a.p || compareStr(a.to, b.to));
64
+ table.set(from, { source, transitions });
65
+ }
66
+ return table;
67
+ }
68
+
69
+ /** Directed reference weights, row-normalised; rows are `references` and carry no interval. */
70
+ export function transitionsFromWeights(edges: Weighted): TransitionTable {
71
+ return tableOf(edges, 'references');
72
+ }
73
+
74
+ /** First-order Markov counts of observed station sequences (run traces); a repeated station is not a hop. */
75
+ export function transitionsFromSequences(sequences: ReadonlyArray<readonly string[]>): TransitionTable {
76
+ const hops: Array<{ from: string; to: string; weight: number }> = [];
77
+ for (const s of sequences) for (let i = 1; i < s.length; i++) hops.push({ from: s[i - 1]!, to: s[i]!, weight: 1 });
78
+ return tableOf(hops, 'traces');
79
+ }
80
+
81
+ /** Per station: its trace row when the traces have a hop out of it, else its reference row. */
82
+ export function stationTransitions(input: { sequences?: ReadonlyArray<readonly string[]>; weights: Weighted }): TransitionTable {
83
+ const traced = transitionsFromSequences(input.sequences ?? []);
84
+ const referenced = transitionsFromWeights(input.weights);
85
+ const table = new Map<string, TransitionRow>();
86
+ for (const from of [...new Set([...traced.keys(), ...referenced.keys()])].sort(compareStr)) {
87
+ table.set(from, traced.get(from) ?? referenced.get(from)!);
88
+ }
89
+ return table;
90
+ }
91
+
92
+ /** The hop from → to, if the table has it. */
93
+ export function transitionOf(table: TransitionTable, from: string, to: string): StationTransition | undefined {
94
+ return table.get(from)?.transitions.find((t) => t.to === to);
95
+ }
96
+
97
+ /**
98
+ * A greedy walk from `start`: at each hop the likeliest unvisited successor (ties by `to` asc), at most `maxHops`, stopping
99
+ * when no unvisited successor is left. Per-hop argmax, NOT the most likely whole path (no Viterbi search).
100
+ * A station whose trace row leads only to stations already visited ends the walk; it does not fall back to its reference row.
101
+ */
102
+ export function mostLikelyWalk(table: TransitionTable, start: string, maxHops: number): { stops: string[]; hops: StationTransition[] } {
103
+ const stops = [start];
104
+ const hops: StationTransition[] = [];
105
+ const seen = new Set(stops);
106
+ for (let cur = start; hops.length < maxHops;) {
107
+ const next = table.get(cur)?.transitions.find((t) => !seen.has(t.to));
108
+ if (!next) break;
109
+ hops.push(next);
110
+ stops.push(next.to);
111
+ seen.add(next.to);
112
+ cur = next.to;
113
+ }
114
+ return { stops, hops };
115
+ }
@@ -6,6 +6,11 @@
6
6
  * shape ranges Part D uses (posterior counts and sample sizes).
7
7
  */
8
8
 
9
+ // Bound once at module scope: a bare `Math.x` is a global lookup on every call, which inside a vm context (the jest
10
+ // runner) costs ~1 µs each and made the inverse beta ~100× slower there; a module binding is free everywhere.
11
+ const { abs, exp, log, max, min, pow, sin, sqrt, PI } = Math;
12
+ const isFiniteNumber = Number.isFinite;
13
+
9
14
  const MAX_ITER = 200;
10
15
  const EPS = 3e-14;
11
16
  const FPMIN = 1e-300;
@@ -17,13 +22,13 @@ function logGamma(x: number): number {
17
22
  12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
18
23
  ];
19
24
  if (x < 0.5) {
20
- return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
25
+ return log(PI / sin(PI * x)) - logGamma(1 - x);
21
26
  }
22
27
  const z = x - 1;
23
28
  let sum = 0.99999999999980993;
24
29
  for (let i = 0; i < p.length; i++) sum += p[i]! / (z + i + 1);
25
30
  const t = z + p.length - 0.5;
26
- return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(sum);
31
+ return 0.5 * log(2 * PI) + (z + 0.5) * log(t) - t + log(sum);
27
32
  }
28
33
 
29
34
  function betaCf(a: number, b: number, x: number): number {
@@ -32,27 +37,27 @@ function betaCf(a: number, b: number, x: number): number {
32
37
  const qam = a - 1;
33
38
  let c = 1;
34
39
  let d = 1 - (qab * x) / qap;
35
- if (Math.abs(d) < FPMIN) d = FPMIN;
40
+ if (abs(d) < FPMIN) d = FPMIN;
36
41
  d = 1 / d;
37
42
  let h = d;
38
43
  for (let m = 1; m <= MAX_ITER; m++) {
39
44
  const m2 = 2 * m;
40
45
  let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
41
46
  d = 1 + aa * d;
42
- if (Math.abs(d) < FPMIN) d = FPMIN;
47
+ if (abs(d) < FPMIN) d = FPMIN;
43
48
  c = 1 + aa / c;
44
- if (Math.abs(c) < FPMIN) c = FPMIN;
49
+ if (abs(c) < FPMIN) c = FPMIN;
45
50
  d = 1 / d;
46
51
  h *= d * c;
47
52
  aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
48
53
  d = 1 + aa * d;
49
- if (Math.abs(d) < FPMIN) d = FPMIN;
54
+ if (abs(d) < FPMIN) d = FPMIN;
50
55
  c = 1 + aa / c;
51
- if (Math.abs(c) < FPMIN) c = FPMIN;
56
+ if (abs(c) < FPMIN) c = FPMIN;
52
57
  d = 1 / d;
53
58
  const del = d * c;
54
59
  h *= del;
55
- if (Math.abs(del - 1) < EPS) break;
60
+ if (abs(del - 1) < EPS) break;
56
61
  }
57
62
  return h;
58
63
  }
@@ -61,25 +66,84 @@ function betaCf(a: number, b: number, x: number): number {
61
66
  export function regularizedIncompleteBeta(x: number, a: number, b: number): number {
62
67
  if (x <= 0) return 0;
63
68
  if (x >= 1) return 1;
64
- const bt = Math.exp(
65
- logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x),
69
+ const bt = exp(
70
+ logGamma(a + b) - logGamma(a) - logGamma(b) + a * log(x) + b * log(1 - x),
66
71
  );
67
72
  if (x < (a + 1) / (a + b + 2)) return (bt * betaCf(a, b, x)) / a;
68
73
  return 1 - (bt * betaCf(b, a, 1 - x)) / b;
69
74
  }
70
75
 
71
- /** Inverse of the regularized incomplete beta, by bisection. Deterministic. */
76
+ /** The inverse stops when its Newton step is below this RELATIVE to the nearer end's distance, min(x, 1 − x). */
77
+ const INVERSE_BETA_TOL = 1e-10;
78
+ /** Hard cap on the inverse's steps (each costs one I_x evaluation). */
79
+ const INVERSE_BETA_MAX_STEPS = 100;
80
+
81
+ /** Starting point of the inverse (Numerical Recipes 3e §6.14 `invbetai`): a normal approximation, or the tail power law below a, b = 1. */
82
+ function inverseBetaGuess(p: number, a: number, b: number): number {
83
+ if (a >= 1 && b >= 1) {
84
+ const pp = p < 0.5 ? p : 1 - p;
85
+ const t = sqrt(-2 * log(pp));
86
+ let x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
87
+ if (p < 0.5) x = -x;
88
+ const al = (x * x - 3) / 6;
89
+ const h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
90
+ const w = (x * sqrt(al + h)) / h - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * (al + 5 / 6 - 2 / (3 * h));
91
+ return a / (a + b * exp(2 * w));
92
+ }
93
+ const lna = log(a / (a + b));
94
+ const lnb = log(b / (a + b));
95
+ const t = exp(a * lna) / a;
96
+ const u = exp(b * lnb) / b;
97
+ const w = t + u;
98
+ return p < t / w ? pow(a * w * p, 1 / a) : 1 - pow(b * w * (1 - p), 1 / b);
99
+ }
100
+
101
+ /** The scale a tolerance is relative to: the distance to the nearer end of (0, 1), so both tails keep their digits. */
102
+ const nearEnd = (x: number): number => max(min(x, 1 - x), 1e-300);
103
+
104
+ /**
105
+ * Inverse of the regularized incomplete beta: Halley steps on I_x(a, b) − p, kept inside a shrinking bracket [lo, hi].
106
+ * - Converged when the Newton step |f / density| is below INVERSE_BETA_TOL · min(x, 1 − x) (relative, so a quantile near 0
107
+ * or 1 keeps its accuracy); the step is then applied and clamped to the bracket. The test runs on the RAW step, before any
108
+ * bracket fallback, and a step landing exactly on a bracket end is converged too (a step under 1 ulp).
109
+ * - A step that leaves the bracket, or a degenerate density, falls back to the bracket's midpoint.
110
+ * - If INVERSE_BETA_MAX_STEPS pass without converging, plain bisection finishes the bracket to tolerance (or to the last
111
+ * representable midpoint): an unconverged x is never returned.
112
+ * Deterministic: a fixed start and a fixed sequence of steps.
113
+ */
72
114
  export function inverseRegularizedIncompleteBeta(p: number, a: number, b: number): number {
73
115
  if (p <= 0) return 0;
74
116
  if (p >= 1) return 1;
117
+ const lnBeta = logGamma(a) + logGamma(b) - logGamma(a + b);
75
118
  let lo = 0;
76
119
  let hi = 1;
77
- for (let i = 0; i < 100; i++) {
120
+ const guess = inverseBetaGuess(p, a, b);
121
+ let x = guess > 0 && guess < 1 ? guess : 0.5;
122
+ for (let i = 0; i < INVERSE_BETA_MAX_STEPS; i++) {
123
+ const f = regularizedIncompleteBeta(x, a, b) - p;
124
+ if (f === 0) return x;
125
+ if (f < 0) lo = x;
126
+ else hi = x;
127
+ const density = exp((a - 1) * log(x) + (b - 1) * log(1 - x) - lnBeta);
128
+ let next = -1; // outside every bracket: falls back to bisection
129
+ if (density > 0 && isFiniteNumber(density)) {
130
+ const newton = f / density;
131
+ next = x - newton / (1 - 0.5 * min(1, newton * ((a - 1) / x - (b - 1) / (1 - x))));
132
+ // Converged: judged on the undamped Newton distance (a Halley damping can shrink a far step), before any fallback.
133
+ if (abs(newton) < INVERSE_BETA_TOL * nearEnd(x) || next === lo || next === hi) {
134
+ return min(max(next, lo), hi);
135
+ }
136
+ }
137
+ if (!(next > lo && next < hi)) next = (lo + hi) / 2;
138
+ x = next;
139
+ }
140
+ // Step cap hit: bisect the bracket to tolerance.
141
+ for (;;) {
78
142
  const mid = (lo + hi) / 2;
143
+ if (mid <= lo || mid >= hi || hi - lo < INVERSE_BETA_TOL * nearEnd(mid)) return mid;
79
144
  if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
80
145
  else hi = mid;
81
146
  }
82
- return (lo + hi) / 2;
83
147
  }
84
148
 
85
149
  /** Posterior Beta(α₀ + k, β₀ + n − k): mean and credible quantiles. */
@@ -111,15 +175,15 @@ function gammaQ(a: number, x: number): number {
111
175
  const an = -i * (i - a);
112
176
  b += 2;
113
177
  d = an * d + b;
114
- if (Math.abs(d) < FPMIN) d = FPMIN;
178
+ if (abs(d) < FPMIN) d = FPMIN;
115
179
  c = b + an / c;
116
- if (Math.abs(c) < FPMIN) c = FPMIN;
180
+ if (abs(c) < FPMIN) c = FPMIN;
117
181
  d = 1 / d;
118
182
  const del = d * c;
119
183
  h *= del;
120
- if (Math.abs(del - 1) < EPS) break;
184
+ if (abs(del - 1) < EPS) break;
121
185
  }
122
- return Math.exp(-x + a * Math.log(x) - logGamma(a)) * h;
186
+ return exp(-x + a * log(x) - logGamma(a)) * h;
123
187
  }
124
188
 
125
189
  /** Regularized lower incomplete gamma P(a, x). */
@@ -132,9 +196,9 @@ export function regularizedIncompleteGamma(a: number, x: number): number {
132
196
  for (let n = 1; n <= MAX_ITER; n++) {
133
197
  term *= x / (a + n);
134
198
  sum += term;
135
- if (Math.abs(term) < Math.abs(sum) * EPS) break;
199
+ if (abs(term) < abs(sum) * EPS) break;
136
200
  }
137
- return Math.exp(-x + a * Math.log(x) - logGamma(a)) * sum;
201
+ return exp(-x + a * log(x) - logGamma(a)) * sum;
138
202
  }
139
203
  return 1 - gammaQ(a, x);
140
204
  }
@@ -144,7 +208,7 @@ export function gammaQuantile(p: number, shape: number, scale = 1): number {
144
208
  if (p <= 0) return 0;
145
209
  if (p >= 1) return Infinity;
146
210
  let lo = 0;
147
- let hi = Math.max(shape * scale * 2, scale, 1e-9);
211
+ let hi = max(shape * scale * 2, scale, 1e-9);
148
212
  while (regularizedIncompleteGamma(shape, hi / scale) < p) {
149
213
  hi *= 2;
150
214
  if (hi > 1e12) break;
@@ -178,3 +242,22 @@ export function garwoodPoissonInterval(
178
242
  rateHigh: high / (2 * exposure),
179
243
  };
180
244
  }
245
+
246
+ /** The Jeffreys prior Beta(½, ½) of {@link rateInterval}. */
247
+ export const RATE_PRIOR = 0.5;
248
+ /** Mass of {@link rateInterval}: an equal-tailed 90% interval. */
249
+ export const RATE_CREDIBLE_MASS = 0.9;
250
+
251
+ /**
252
+ * The credible interval of an observed rate k of n: the equal-tailed RATE_CREDIBLE_MASS interval of the Jeffreys
253
+ * posterior Beta(½ + k, ½ + n − k), with Brown–Cai–DasGupta's boundary rule (low = 0 at k = 0, high = 1 at k = n) so
254
+ * the interval always holds k/n. THE interval of every rate a graph badge or a hop shows (PRD 38, PRD 41 D3).
255
+ */
256
+ export function rateInterval(k: number, n: number): { low: number; high: number } {
257
+ const post = betaPosterior(RATE_PRIOR, RATE_PRIOR, k, n);
258
+ const tail = (1 - RATE_CREDIBLE_MASS) / 2;
259
+ return {
260
+ low: k <= 0 ? 0 : post.quantile(tail),
261
+ high: k >= n ? 1 : post.quantile(1 - tail),
262
+ };
263
+ }
@@ -14,6 +14,9 @@ export {
14
14
  gammaQuantile,
15
15
  garwoodPoissonInterval,
16
16
  inverseRegularizedIncompleteBeta,
17
+ RATE_CREDIBLE_MASS,
18
+ RATE_PRIOR,
19
+ rateInterval,
17
20
  regularizedIncompleteBeta,
18
21
  regularizedIncompleteGamma,
19
22
  } from "./distributions.js";