@seanhogg/builderforce-memory 2026.10.71 → 2026.10.72
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.
- package/dist/knowledge/coChange.d.ts +3 -1
- package/dist/knowledge/coChange.d.ts.map +1 -1
- package/dist/knowledge/coChange.js +24 -12
- package/dist/knowledge/coChange.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +10 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +16 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +18 -1
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +10 -4
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/facts/extractorVersion.d.ts +45 -0
- package/dist/knowledge/facts/extractorVersion.d.ts.map +1 -0
- package/dist/knowledge/facts/extractorVersion.js +56 -0
- package/dist/knowledge/facts/extractorVersion.js.map +1 -0
- package/dist/knowledge/facts/fileFacts.d.ts +166 -0
- package/dist/knowledge/facts/fileFacts.d.ts.map +1 -0
- package/dist/knowledge/facts/fileFacts.js +156 -0
- package/dist/knowledge/facts/fileFacts.js.map +1 -0
- package/dist/knowledge/findings.d.ts +17 -14
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +29 -129
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/index.d.ts +13 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +8 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/model.d.ts +6 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +14 -4
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js +30 -8
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/plan.d.ts +10 -1
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +9 -4
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/review.js +1 -0
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewContext.d.ts.map +1 -1
- package/dist/knowledge/reviewContext.js +5 -2
- package/dist/knowledge/reviewContext.js.map +1 -1
- package/dist/knowledge/reviewFinish.d.ts.map +1 -1
- package/dist/knowledge/reviewFinish.js +3 -1
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +12 -0
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +2 -0
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +1 -0
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/rules/cloneGroup.d.ts +10 -0
- package/dist/knowledge/rules/cloneGroup.d.ts.map +1 -0
- package/dist/knowledge/rules/cloneGroup.js +46 -0
- package/dist/knowledge/rules/cloneGroup.js.map +1 -0
- package/dist/knowledge/rules/components.d.ts +8 -0
- package/dist/knowledge/rules/components.d.ts.map +1 -0
- package/dist/knowledge/rules/components.js +34 -0
- package/dist/knowledge/rules/components.js.map +1 -0
- package/dist/knowledge/rules/cycle.d.ts +7 -0
- package/dist/knowledge/rules/cycle.d.ts.map +1 -0
- package/dist/knowledge/rules/cycle.js +18 -0
- package/dist/knowledge/rules/cycle.js.map +1 -0
- package/dist/knowledge/rules/duplicateCopy.d.ts +7 -0
- package/dist/knowledge/rules/duplicateCopy.d.ts.map +1 -0
- package/dist/knowledge/rules/duplicateCopy.js +18 -0
- package/dist/knowledge/rules/duplicateCopy.js.map +1 -0
- package/dist/knowledge/rules/evaluateRules.d.ts +60 -0
- package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -0
- package/dist/knowledge/rules/evaluateRules.js +164 -0
- package/dist/knowledge/rules/evaluateRules.js.map +1 -0
- package/dist/knowledge/rules/factGraph.d.ts +51 -0
- package/dist/knowledge/rules/factGraph.d.ts.map +1 -0
- package/dist/knowledge/rules/factGraph.js +77 -0
- package/dist/knowledge/rules/factGraph.js.map +1 -0
- package/dist/knowledge/rules/factRule.d.ts +56 -0
- package/dist/knowledge/rules/factRule.d.ts.map +1 -0
- package/dist/knowledge/rules/factRule.js +46 -0
- package/dist/knowledge/rules/factRule.js.map +1 -0
- package/dist/knowledge/rules/godModule.d.ts +8 -0
- package/dist/knowledge/rules/godModule.d.ts.map +1 -0
- package/dist/knowledge/rules/godModule.js +16 -0
- package/dist/knowledge/rules/godModule.js.map +1 -0
- package/dist/knowledge/rules/knowledgeInput.d.ts +35 -0
- package/dist/knowledge/rules/knowledgeInput.d.ts.map +1 -0
- package/dist/knowledge/rules/knowledgeInput.js +33 -0
- package/dist/knowledge/rules/knowledgeInput.js.map +1 -0
- package/dist/knowledge/rules/nearDuplicate.d.ts +7 -0
- package/dist/knowledge/rules/nearDuplicate.d.ts.map +1 -0
- package/dist/knowledge/rules/nearDuplicate.js +20 -0
- package/dist/knowledge/rules/nearDuplicate.js.map +1 -0
- package/dist/knowledge/rules/partitionViolation.d.ts +10 -0
- package/dist/knowledge/rules/partitionViolation.d.ts.map +1 -0
- package/dist/knowledge/rules/partitionViolation.js +27 -0
- package/dist/knowledge/rules/partitionViolation.js.map +1 -0
- package/dist/knowledge/rules/possibleSame.d.ts +7 -0
- package/dist/knowledge/rules/possibleSame.d.ts.map +1 -0
- package/dist/knowledge/rules/possibleSame.js +15 -0
- package/dist/knowledge/rules/possibleSame.js.map +1 -0
- package/dist/knowledge/rules/stale.d.ts +7 -0
- package/dist/knowledge/rules/stale.d.ts.map +1 -0
- package/dist/knowledge/rules/stale.js +28 -0
- package/dist/knowledge/rules/stale.js.map +1 -0
- package/dist/knowledge/rules/unpartitioned.d.ts +7 -0
- package/dist/knowledge/rules/unpartitioned.d.ts.map +1 -0
- package/dist/knowledge/rules/unpartitioned.js +26 -0
- package/dist/knowledge/rules/unpartitioned.js.map +1 -0
- package/dist/knowledge/sources.d.ts +13 -0
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +14 -0
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/sha256.js +2 -2
- package/dist/retrieval/knowledge-index/sha256.js.map +1 -1
- package/dist/stats/distributions.d.ts +17 -1
- package/dist/stats/distributions.d.ts.map +1 -1
- package/dist/stats/distributions.js +26 -1
- package/dist/stats/distributions.js.map +1 -1
- package/dist/stats/fitting.d.ts.map +1 -1
- package/dist/stats/fitting.js +1 -6
- package/dist/stats/fitting.js.map +1 -1
- package/dist/stats/index.d.ts +10 -3
- package/dist/stats/index.d.ts.map +1 -1
- package/dist/stats/index.js +10 -3
- package/dist/stats/index.js.map +1 -1
- package/dist/stats/logistic.d.ts +30 -0
- package/dist/stats/logistic.d.ts.map +1 -0
- package/dist/stats/logistic.js +43 -0
- package/dist/stats/logistic.js.map +1 -0
- package/dist/stats/multivariate.d.ts +8 -13
- package/dist/stats/multivariate.d.ts.map +1 -1
- package/dist/stats/multivariate.js +7 -53
- package/dist/stats/multivariate.js.map +1 -1
- package/dist/stats/policies.d.ts.map +1 -1
- package/dist/stats/policies.js +4 -22
- package/dist/stats/policies.js.map +1 -1
- package/package.json +4 -3
- package/src/contract/exports.snapshot.json +37 -1
- package/src/contract/regression.extractorKey.test.ts +202 -0
- package/src/contract/regression.statsEngineFree.test.ts +70 -0
- package/src/contract/regression.thompsonDeterminism.test.ts +23 -0
- package/src/contract/types.contract.test.ts +59 -2
- package/src/knowledge/coChange.test.ts +15 -2
- package/src/knowledge/coChange.ts +22 -10
- package/src/knowledge/extractFile.ts +27 -5
- package/src/knowledge/extractJob.ts +24 -5
- package/src/knowledge/facts/extractorVersion.ts +73 -0
- package/src/knowledge/facts/fileFacts.test.ts +157 -0
- package/src/knowledge/facts/fileFacts.ts +305 -0
- package/src/knowledge/findings.ts +30 -127
- package/src/knowledge/index.ts +19 -0
- package/src/knowledge/model.ts +6 -0
- package/src/knowledge/owedFiles.ts +36 -8
- package/src/knowledge/plan.ts +16 -4
- package/src/knowledge/review.ts +1 -0
- package/src/knowledge/reviewContext.ts +5 -2
- package/src/knowledge/reviewFinish.ts +3 -1
- package/src/knowledge/reviewModel.ts +12 -0
- package/src/knowledge/reviewPrefetch.ts +3 -0
- package/src/knowledge/rules/cloneGroup.ts +45 -0
- package/src/knowledge/rules/components.ts +31 -0
- package/src/knowledge/rules/cycle.ts +20 -0
- package/src/knowledge/rules/duplicateCopy.ts +22 -0
- package/src/knowledge/rules/evaluateRules.test.ts +172 -0
- package/src/knowledge/rules/evaluateRules.ts +186 -0
- package/src/knowledge/rules/factGraph.oracle.test.ts +174 -0
- package/src/knowledge/rules/factGraph.ts +107 -0
- package/src/knowledge/rules/factRule.ts +74 -0
- package/src/knowledge/rules/godModule.ts +18 -0
- package/src/knowledge/rules/knowledgeInput.ts +60 -0
- package/src/knowledge/rules/knowledgeRules.test.ts +78 -0
- package/src/knowledge/rules/nearDuplicate.ts +22 -0
- package/src/knowledge/rules/partitionViolation.ts +31 -0
- package/src/knowledge/rules/possibleSame.ts +17 -0
- package/src/knowledge/rules/rules.testkit.test-util.ts +78 -0
- package/src/knowledge/rules/stale.ts +31 -0
- package/src/knowledge/rules/unpartitioned.ts +27 -0
- package/src/knowledge/sources.ts +16 -0
- package/src/retrieval/knowledge-index/sha256.test.ts +25 -0
- package/src/retrieval/knowledge-index/sha256.ts +2 -1
- package/src/stats/distributions.ts +29 -2
- package/src/stats/fitting.ts +1 -6
- package/src/stats/index.ts +12 -2
- package/src/stats/logistic.test.ts +89 -0
- package/src/stats/logistic.ts +49 -0
- package/src/stats/multivariate.ts +8 -59
- package/src/stats/policies.ts +4 -24
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/rules/rules.testkit.test-util.ts — fixture facts and fixture rules for the evaluator's trace
|
|
3
|
+
* tests and the determinism oracle. The rules mirror real ones by what they READ: `io-in-loop` (body, file),
|
|
4
|
+
* `export-count` (structure, file), `unresolved-import` (structure, neighbourhood), `route-guard` (structure,
|
|
5
|
+
* neighbourhood, hops 2 + guard chain), `content-tag` (content, file), `mutual-import` (structure, global),
|
|
6
|
+
* `call-total` (body, global).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Finding } from '../findingModel.js';
|
|
10
|
+
import { FACTS_EXTRACTOR_VERSION, factsExtractorTag } from '../facts/extractorVersion.js';
|
|
11
|
+
import type { FileFacts } from '../facts/fileFacts.js';
|
|
12
|
+
import { compareStr } from '../refs.js';
|
|
13
|
+
import { defineRule, type FactRule } from './factRule.js';
|
|
14
|
+
|
|
15
|
+
export const TAG = factsExtractorTag({ family: 'regex' }, 'fixture');
|
|
16
|
+
|
|
17
|
+
export const emptyFacts = (contentHash: string): FileFacts => ({
|
|
18
|
+
factsVersion: FACTS_EXTRACTOR_VERSION, extractor: TAG, language: 'fixture', contentHash,
|
|
19
|
+
symbols: [], imports: [], exports: [], entryPoints: [], calls: [], complexity: [], capabilityImports: [],
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const f = (rule: string, key: string, params: Finding['params'] = {}): Finding => ({
|
|
23
|
+
id: `${rule}:${key}`, kind: rule, pack: 'fixture', nodes: [], severity: 'warn', params,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export const ioInLoop = defineRule({
|
|
27
|
+
id: 'io-in-loop', version: 1, reads: ['body'], scope: 'file',
|
|
28
|
+
derive: ({ focus, files }) => files.get(focus!)!.calls.filter((c) => c.inLoop && c.awaited).map((c) => f('io-in-loop', `${focus}#${c.enclosing}#${c.callee}`)),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export const exportCount = defineRule({
|
|
32
|
+
id: 'export-count', version: 1, reads: ['structure'], scope: 'file',
|
|
33
|
+
derive: ({ focus, files }) => {
|
|
34
|
+
const n = files.get(focus!)!.exports.length;
|
|
35
|
+
return n > 2 ? [f('export-count', focus!, { exports: n })] : [];
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
export const contentTag = defineRule({
|
|
40
|
+
id: 'content-tag', version: 1, reads: ['content'], scope: 'file',
|
|
41
|
+
derive: ({ focus, files }) => [f('content-tag', focus!, { hash: files.get(focus!)!.contentHash.slice(0, 8) })],
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/** An import whose resolved target is not among the files the neighbourhood sees. */
|
|
45
|
+
export const unresolvedImport = defineRule({
|
|
46
|
+
id: 'unresolved-import', version: 1, reads: ['structure'], scope: 'neighbourhood',
|
|
47
|
+
derive: ({ focus, files }) => files.get(focus!)!.imports
|
|
48
|
+
.filter((i) => i.resolved !== undefined && !files.has(i.resolved))
|
|
49
|
+
.map((i) => f('unresolved-import', `${focus}->${i.resolved}`)),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** A route whose guard chain holds no file exporting `requireAuth`. */
|
|
53
|
+
export const routeGuard = defineRule({
|
|
54
|
+
id: 'route-guard', version: 1, reads: ['structure'], scope: 'neighbourhood', hops: 2, readsGuardChain: true,
|
|
55
|
+
derive: ({ focus, files }) => files.get(focus!)!.entryPoints
|
|
56
|
+
.filter((e) => !e.chain.some((c) => files.get(c)?.exports.some((x) => x.name === 'requireAuth')))
|
|
57
|
+
.map((e) => f('route-guard', `${focus}#${e.key}`)),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
export const mutualImport = defineRule({
|
|
61
|
+
id: 'mutual-import', version: 1, reads: ['structure'], scope: 'global',
|
|
62
|
+
derive: ({ files }) => {
|
|
63
|
+
const out: Finding[] = [];
|
|
64
|
+
for (const [a, fa] of files) for (const i of fa.imports) {
|
|
65
|
+
const b = i.resolved;
|
|
66
|
+
if (b === undefined || compareStr(a, b) >= 0) continue;
|
|
67
|
+
if (files.get(b)?.imports.some((j) => j.resolved === a)) out.push(f('mutual-import', `${a}<->${b}`));
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
export const callTotal = defineRule({
|
|
74
|
+
id: 'call-total', version: 1, reads: ['body'], scope: 'global',
|
|
75
|
+
derive: ({ files }) => [f('call-total', 'all', { calls: [...files.values()].reduce((s, x) => s + x.calls.reduce((t, c) => t + c.count, 0), 0) })],
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
export const FIXTURE_RULES: readonly FactRule[] = [ioInLoop, exportCount, contentTag, unresolvedImport, routeGuard, mutualImport, callTotal];
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/stale.ts — `stale`: one finding per source whose stored knowledge went stale (an
|
|
3
|
+
* unanchored stale node counts as its own source). Anchor (PRD 41 §C3): the stale source.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { finding, refAnchor } from '../findingBuilder.js';
|
|
7
|
+
import type { NodeRef } from '../model.js';
|
|
8
|
+
import { aboutTargets, FALLBACK_PACK_ID } from '../refs.js';
|
|
9
|
+
import { defineRule } from './factRule.js';
|
|
10
|
+
import type { KnowledgeRuleExtra } from './knowledgeInput.js';
|
|
11
|
+
|
|
12
|
+
export const staleRule = defineRule<KnowledgeRuleExtra>({
|
|
13
|
+
id: 'stale',
|
|
14
|
+
version: 1,
|
|
15
|
+
reads: [], // the knowledge graph only (stale flags)
|
|
16
|
+
scope: 'global',
|
|
17
|
+
extraInputs: ['knowledge'],
|
|
18
|
+
derive: ({ extra: { knowledge: k } }) => {
|
|
19
|
+
const about = aboutTargets(k.graph.edges);
|
|
20
|
+
const bySource = new Map<NodeRef, NodeRef[]>();
|
|
21
|
+
for (const n of k.graph.nodes) {
|
|
22
|
+
if (!n.stale) continue;
|
|
23
|
+
const target = about.get(n.ref) ?? n.ref;
|
|
24
|
+
const list = bySource.get(target) ?? [];
|
|
25
|
+
list.push(n.ref);
|
|
26
|
+
bySource.set(target, list);
|
|
27
|
+
}
|
|
28
|
+
return [...bySource].map(([source, refs]) =>
|
|
29
|
+
finding('stale', k.byRef.get(source)?.pack ?? FALLBACK_PACK_ID, [source, ...refs], 'warn', { count: refs.length }, undefined, refAnchor(source)));
|
|
30
|
+
},
|
|
31
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/unpartitioned.ts — `unpartitioned`: per pack with an `allow` registry, the share of its
|
|
3
|
+
* files no partition matched. Anchor (PRD 41 §C3): the pack.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { finding } from '../findingBuilder.js';
|
|
7
|
+
import { compareStr } from '../refs.js';
|
|
8
|
+
import { defineRule } from './factRule.js';
|
|
9
|
+
import type { KnowledgeRuleExtra } from './knowledgeInput.js';
|
|
10
|
+
|
|
11
|
+
export const unpartitionedRule = defineRule<KnowledgeRuleExtra>({
|
|
12
|
+
id: 'unpartitioned',
|
|
13
|
+
version: 1,
|
|
14
|
+
reads: [], // the knowledge graph and partition registries only
|
|
15
|
+
scope: 'global',
|
|
16
|
+
extraInputs: ['knowledge'],
|
|
17
|
+
derive: ({ extra: { knowledge: k } }) =>
|
|
18
|
+
[...k.registries].sort((a, b) => compareStr(a[0], b[0])).flatMap(([pack, reg]) => {
|
|
19
|
+
if (!reg.allow) return [];
|
|
20
|
+
const files = k.graph.nodes.filter((n) => n.pack === pack && n.kind === 'file');
|
|
21
|
+
const loose = files.filter((n) => n.partition === undefined).map((n) => n.ref);
|
|
22
|
+
if (loose.length === 0) return [];
|
|
23
|
+
return [finding('unpartitioned', pack, loose, 'info', {
|
|
24
|
+
count: loose.length, total: files.length, share: Math.round((loose.length / files.length) * 100),
|
|
25
|
+
}, undefined, { anchor: `pack:${pack}`, anchorKind: 'group' })];
|
|
26
|
+
}),
|
|
27
|
+
});
|
package/src/knowledge/sources.ts
CHANGED
|
@@ -25,6 +25,22 @@ export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
|
25
25
|
// 6 (2026-11-10, PRD 43 P0c): the agent-tools code pack resolves tsconfig path aliases, names callback-owner symbols,
|
|
26
26
|
// emits `new X().m()` call edges and reads JSX renders as calls, so cached code extracts re-run.
|
|
27
27
|
export const EXTRACTOR_VERSION = 6;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* THE test of "this extract (or this root's extractor entry) was made by today's extractor": today's
|
|
31
|
+
* {@link EXTRACTOR_VERSION}, and the same caller-supplied extractor key (`extractorKey`: an input the host's extractors
|
|
32
|
+
* read besides the file's bytes, e.g. a digest of the tsconfig path aliases). An absent or empty key equals only an
|
|
33
|
+
* absent or empty key, so a caller that passes none behaves as before keys existed and old records still match it.
|
|
34
|
+
* The extract cache (extractFile.ts) and the owed state (owedFiles.ts) both decide by this one comparison.
|
|
35
|
+
*/
|
|
36
|
+
export function isCurrentExtractor(recorded: { version: number | undefined; key: string | undefined }, keyNow: string | undefined): boolean {
|
|
37
|
+
return recorded.version === EXTRACTOR_VERSION && sameExtractorKey(recorded.key, keyNow);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** THE key comparison (inside {@link isCurrentExtractor}; the owed estimate also needs it alone): absent and '' both mean "no key". */
|
|
41
|
+
export function sameExtractorKey(a: string | undefined, b: string | undefined): boolean {
|
|
42
|
+
return (a || undefined) === (b || undefined);
|
|
43
|
+
}
|
|
28
44
|
/**
|
|
29
45
|
* Always ignored: VCS internals, installed dependencies, builderforce config, and lockfiles (`yarn.lock`, `Cargo.lock` …): generated,
|
|
30
46
|
* huge, and plain text — extracted they would cost judgement calls for nothing; they were never stored (once skipped as binary).
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/retrieval/knowledge-index/sha256.test.ts — the portable SHA-256 equals node:crypto for every padding
|
|
3
|
+
* case (input lengths 0..200 cover a message ending before, at and after the 56-byte length boundary), and
|
|
4
|
+
* incremental updates equal one update.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { Sha256, sha256Hex } from './sha256.js';
|
|
9
|
+
|
|
10
|
+
const bytesOf = (n: number) => Uint8Array.from({ length: n }, (_, i) => (i * 31 + 7) & 0xff);
|
|
11
|
+
const reference = (b: Uint8Array) => createHash('sha256').update(b).digest('hex');
|
|
12
|
+
|
|
13
|
+
describe('sha256', () => {
|
|
14
|
+
it('matches node:crypto for every length 0..200', () => {
|
|
15
|
+
for (let n = 0; n <= 200; n++) expect({ n, h: sha256Hex(bytesOf(n)) }).toEqual({ n, h: reference(bytesOf(n)) });
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('incremental updates equal one update', () => {
|
|
19
|
+
const b = bytesOf(300);
|
|
20
|
+
const h = new Sha256();
|
|
21
|
+
for (let i = 0; i < b.length; i += 7) h.update(b.subarray(i, i + 7));
|
|
22
|
+
expect(h.hex()).toBe(reference(b));
|
|
23
|
+
expect(sha256Hex('héllo')).toBe(createHash('sha256').update('héllo', 'utf8').digest('hex'));
|
|
24
|
+
});
|
|
25
|
+
});
|
|
@@ -57,7 +57,8 @@ export class Sha256 {
|
|
|
57
57
|
const bitsHi = Math.floor(this._bytes / 0x20000000);
|
|
58
58
|
const bitsLo = (this._bytes * 8) >>> 0;
|
|
59
59
|
this.update(new Uint8Array([0x80]));
|
|
60
|
-
|
|
60
|
+
// Zero-pad to 56 mod 64 in ONE update (byte-at-a-time padding cost ~55 calls per digest).
|
|
61
|
+
this.update(new Uint8Array((120 - this._blockLen) % 64));
|
|
61
62
|
const len = new Uint8Array(8);
|
|
62
63
|
const view = new DataView(len.buffer);
|
|
63
64
|
view.setUint32(0, bitsHi);
|
|
@@ -146,25 +146,52 @@ export function inverseRegularizedIncompleteBeta(p: number, a: number, b: number
|
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
/** Posterior Beta(α₀ + k, β₀ + n − k): mean and credible quantiles. */
|
|
149
|
+
/** Posterior Beta(α₀ + k, β₀ + n − k): mean, variance and credible quantiles. */
|
|
150
150
|
export interface BetaPosterior {
|
|
151
151
|
alpha: number;
|
|
152
152
|
beta: number;
|
|
153
153
|
mean: number;
|
|
154
|
+
variance: number;
|
|
154
155
|
quantile(p: number): number;
|
|
155
156
|
}
|
|
156
157
|
|
|
158
|
+
/** Mean α/(α+β) and variance αβ/((α+β)²(α+β+1)) of Beta(α, β). */
|
|
159
|
+
export function betaMoments(alpha: number, beta: number): { mean: number; variance: number } {
|
|
160
|
+
const total = alpha + beta;
|
|
161
|
+
return { mean: alpha / total, variance: (alpha * beta) / (total * total * (total + 1)) };
|
|
162
|
+
}
|
|
163
|
+
|
|
157
164
|
export function betaPosterior(alpha0: number, beta0: number, k: number, n: number): BetaPosterior {
|
|
158
165
|
const alpha = alpha0 + k;
|
|
159
166
|
const beta = beta0 + (n - k);
|
|
160
167
|
return {
|
|
161
168
|
alpha,
|
|
162
169
|
beta,
|
|
163
|
-
|
|
170
|
+
...betaMoments(alpha, beta),
|
|
164
171
|
quantile: (p) => inverseRegularizedIncompleteBeta(p, alpha, beta),
|
|
165
172
|
};
|
|
166
173
|
}
|
|
167
174
|
|
|
175
|
+
/** Two-sided 95% standard-normal critical value. */
|
|
176
|
+
const Z_95 = 1.96;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Wilson score interval of `successes / n` at critical value `z` (default 95%): stays
|
|
180
|
+
* inside [0, 1] and keeps a non-zero width at 0 or n successes, where the Wald interval
|
|
181
|
+
* collapses. `n` not > 0 (including NaN) or a non-finite `successes` is no evidence:
|
|
182
|
+
* [0, 1]. A `z` that is not a finite positive number is a caller error and throws.
|
|
183
|
+
*/
|
|
184
|
+
export function wilsonInterval(successes: number, n: number, z: number = Z_95): { low: number; high: number } {
|
|
185
|
+
if (!(z > 0) || !isFiniteNumber(z)) throw new RangeError(`wilsonInterval: z must be a finite positive number, got ${z}`);
|
|
186
|
+
if (!(n > 0) || !isFiniteNumber(successes)) return { low: 0, high: 1 };
|
|
187
|
+
const p = min(1, max(0, successes / n));
|
|
188
|
+
const z2 = z * z;
|
|
189
|
+
const denom = 1 + z2 / n;
|
|
190
|
+
const centre = (p + z2 / (2 * n)) / denom;
|
|
191
|
+
const half = (z * sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / denom;
|
|
192
|
+
return { low: max(0, centre - half), high: min(1, centre + half) };
|
|
193
|
+
}
|
|
194
|
+
|
|
168
195
|
function gammaQ(a: number, x: number): number {
|
|
169
196
|
// Regularized upper incomplete gamma Q(a, x) via continued fraction.
|
|
170
197
|
let b = x + 1 - a;
|
package/src/stats/fitting.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* calibration shapes the classical catalog does not carry.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import { sigmoid } from "./logistic.js";
|
|
8
9
|
import { createRng, normalDraw, type Rng } from "./prng.js";
|
|
9
10
|
|
|
10
11
|
export interface LaplaceApproximation {
|
|
@@ -12,12 +13,6 @@ export interface LaplaceApproximation {
|
|
|
12
13
|
covariance: number[][];
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
function sigmoid(x: number): number {
|
|
16
|
-
if (x >= 0) return 1 / (1 + Math.exp(-x));
|
|
17
|
-
const e = Math.exp(x);
|
|
18
|
-
return e / (1 + e);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
16
|
function invert2x2(m: number[][]): number[][] {
|
|
22
17
|
const det = m[0]![0]! * m[1]![1]! - m[0]![1]! * m[1]![0]!;
|
|
23
18
|
if (Math.abs(det) < 1e-12) {
|
package/src/stats/index.ts
CHANGED
|
@@ -2,14 +2,21 @@
|
|
|
2
2
|
* The stats module (PRD 41 Part D / D13): the ONE home for the predicted-measure
|
|
3
3
|
* maths. Pure and deterministic — seeded PRNG, fixed iteration caps, quantized
|
|
4
4
|
* outputs. It holds only what the memory-engine `ml/classical` catalog lacks and
|
|
5
|
-
* imports (never re-implements) those primitives; EWMA and the
|
|
6
|
-
* stay in `ml/classical
|
|
5
|
+
* imports (never re-implements) those primitives; EWMA, Ledoit–Wolf and the
|
|
6
|
+
* classical models stay in `ml/classical` (Ledoit–Wolf is re-exported here).
|
|
7
|
+
*
|
|
8
|
+
* One deliberate exception: the BINARY logistic head (`logistic.ts` — `sigmoid`,
|
|
9
|
+
* `logisticProbability`, `onlineLogisticStep`) is float64 and engine-free, not the
|
|
10
|
+
* engine's softmax `LogisticModel` (Float32 weights, batch fits). Device code scores a
|
|
11
|
+
* stored head and folds in one outcome at a time; batch fitting (gradient descent or
|
|
12
|
+
* IRLS) stays in the engine.
|
|
7
13
|
*/
|
|
8
14
|
|
|
9
15
|
export { createRng, normalDraw } from "./prng.js";
|
|
10
16
|
export type { Rng } from "./prng.js";
|
|
11
17
|
|
|
12
18
|
export {
|
|
19
|
+
betaMoments,
|
|
13
20
|
betaPosterior,
|
|
14
21
|
gammaQuantile,
|
|
15
22
|
garwoodPoissonInterval,
|
|
@@ -19,9 +26,12 @@ export {
|
|
|
19
26
|
rateInterval,
|
|
20
27
|
regularizedIncompleteBeta,
|
|
21
28
|
regularizedIncompleteGamma,
|
|
29
|
+
wilsonInterval,
|
|
22
30
|
} from "./distributions.js";
|
|
23
31
|
export type { BetaPosterior } from "./distributions.js";
|
|
24
32
|
|
|
33
|
+
export { logisticProbability, onlineLogisticStep, sigmoid } from "./logistic.js";
|
|
34
|
+
|
|
25
35
|
export { fitBayesianLogistic, fitIsotonic, fitPlattScaling } from "./fitting.js";
|
|
26
36
|
export type { BayesianLogisticOptions, IsotonicFit } from "./fitting.js";
|
|
27
37
|
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The PRD 41 D13 consolidation primitives: the ONE stable sigmoid and logistic head
|
|
3
|
+
* (prefetch's online calibration, the difficulty head, the pipeline router), the Wilson
|
|
4
|
+
* interval (replay impact and issue clusters, the canvas proportion card) and the Beta
|
|
5
|
+
* moments (the learned-routing Thompson draw).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, expect, it } from "@jest/globals";
|
|
9
|
+
import {
|
|
10
|
+
betaMoments,
|
|
11
|
+
betaPosterior,
|
|
12
|
+
logisticProbability,
|
|
13
|
+
onlineLogisticStep,
|
|
14
|
+
sigmoid,
|
|
15
|
+
wilsonInterval,
|
|
16
|
+
} from "./index.js";
|
|
17
|
+
|
|
18
|
+
describe("sigmoid", () => {
|
|
19
|
+
it("is ½ at 0, symmetric, and finite in both tails", () => {
|
|
20
|
+
expect(sigmoid(0)).toBe(0.5);
|
|
21
|
+
for (const z of [0.3, 2, 9]) expect(sigmoid(-z)).toBeCloseTo(1 - sigmoid(z), 12);
|
|
22
|
+
expect(sigmoid(-800)).toBe(0);
|
|
23
|
+
expect(sigmoid(800)).toBe(1);
|
|
24
|
+
expect(Number.isNaN(sigmoid(-1e308))).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe("logistic head", () => {
|
|
29
|
+
it("scores σ(b + w·x)", () => {
|
|
30
|
+
expect(logisticProbability([6, 2, 2], -5, [1, 0, 0])).toBeCloseTo(sigmoid(1), 15);
|
|
31
|
+
expect(logisticProbability([1, -1], 0.5, [2, 3])).toBeCloseTo(sigmoid(-0.5), 15);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("one SGD step moves toward the label and leaves its input untouched", () => {
|
|
35
|
+
const weights = [0, 0];
|
|
36
|
+
const x = [1, 0.5];
|
|
37
|
+
const before = logisticProbability(weights, 0, x);
|
|
38
|
+
const up = onlineLogisticStep(weights, 0, x, 1, 0.1);
|
|
39
|
+
expect(logisticProbability(up.weights, up.bias, x)).toBeGreaterThan(before);
|
|
40
|
+
expect(up.weights).toEqual([0.05, 0.025]);
|
|
41
|
+
expect(up.bias).toBeCloseTo(0.05, 15);
|
|
42
|
+
const down = onlineLogisticStep(weights, 0, x, 0, 0.1);
|
|
43
|
+
expect(logisticProbability(down.weights, down.bias, x)).toBeLessThan(before);
|
|
44
|
+
expect(weights).toEqual([0, 0]);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe("wilsonInterval", () => {
|
|
49
|
+
it("matches the textbook 95% interval", () => {
|
|
50
|
+
const { low, high } = wilsonInterval(50, 1_000);
|
|
51
|
+
expect(low).toBeCloseTo(0.0381, 4);
|
|
52
|
+
expect(high).toBeCloseTo(0.0653, 4);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("keeps a width at the boundary and stays in [0, 1]", () => {
|
|
56
|
+
const none = wilsonInterval(0, 40);
|
|
57
|
+
expect(none.low).toBeCloseTo(0, 12);
|
|
58
|
+
expect(none.high).toBeGreaterThan(0.05);
|
|
59
|
+
expect(wilsonInterval(10, 10).high).toBeCloseTo(1, 12);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("no evidence (n ≤ 0 or NaN, or non-finite successes) is [0, 1]", () => {
|
|
63
|
+
expect(wilsonInterval(0, 0)).toEqual({ low: 0, high: 1 });
|
|
64
|
+
expect(wilsonInterval(3, Number.NaN)).toEqual({ low: 0, high: 1 });
|
|
65
|
+
expect(wilsonInterval(Number.NaN, 10)).toEqual({ low: 0, high: 1 });
|
|
66
|
+
expect(wilsonInterval(Number.POSITIVE_INFINITY, 10)).toEqual({ low: 0, high: 1 });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("a z that is not a finite positive number throws", () => {
|
|
70
|
+
for (const z of [0, -1.96, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
71
|
+
expect(() => wilsonInterval(3, 10, z)).toThrow(RangeError);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("a wider z gives a wider interval", () => {
|
|
76
|
+
const a = wilsonInterval(30, 100);
|
|
77
|
+
const b = wilsonInterval(30, 100, 2.576);
|
|
78
|
+
expect(b.high - b.low).toBeGreaterThan(a.high - a.low);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe("betaMoments", () => {
|
|
83
|
+
it("gives the Beta mean and variance, and the posterior carries them", () => {
|
|
84
|
+
expect(betaMoments(2, 3)).toEqual({ mean: 0.4, variance: 0.04 });
|
|
85
|
+
const post = betaPosterior(1, 1, 1, 3);
|
|
86
|
+
expect(post.mean).toBe(betaMoments(2, 3).mean);
|
|
87
|
+
expect(post.variance).toBe(betaMoments(2, 3).variance);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The binary logistic head for the stats module (PRD 41 Part D / D13): the ONE
|
|
3
|
+
* numerically stable sigmoid, the probability of a stored head `σ(w·x + b)`, and one
|
|
4
|
+
* online SGD step on the log-loss. Pure: every function returns new values and never
|
|
5
|
+
* mutates its input.
|
|
6
|
+
*
|
|
7
|
+
* Batch fitting stays in memory-engine `ml/classical/logistic.ts` (gradient descent or
|
|
8
|
+
* IRLS, L2, sample and class weights) and the Laplace/Platt fits in `fitting.ts`; this
|
|
9
|
+
* is what a device needs to SCORE a fitted head and fold in one outcome at a time.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* σ(z) = 1 / (1 + e^−z), evaluated so neither tail overflows. The engine's training
|
|
14
|
+
* kernels keep their own (`memory-engine/src/training/cpu_ops.ts` `sigmoid`).
|
|
15
|
+
*/
|
|
16
|
+
export function sigmoid(z: number): number {
|
|
17
|
+
if (z >= 0) return 1 / (1 + Math.exp(-z));
|
|
18
|
+
const e = Math.exp(z);
|
|
19
|
+
return e / (1 + e);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* σ(b + Σᵢ wᵢ·xᵢ) over the features of `x` (accumulated in index order from the bias).
|
|
24
|
+
* The caller owns the shape check: a head whose weights do not match its features has
|
|
25
|
+
* no meaningful probability, and what to return then (0, ½, …) is the caller's policy.
|
|
26
|
+
*/
|
|
27
|
+
export function logisticProbability(weights: readonly number[], bias: number, x: readonly number[]): number {
|
|
28
|
+
let z = bias;
|
|
29
|
+
for (let i = 0; i < x.length; i++) z += weights[i]! * x[i]!;
|
|
30
|
+
return sigmoid(z);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* One online SGD step on the log-loss for a single labelled example:
|
|
35
|
+
* err = y − σ(w·x + b); wᵢ ← wᵢ + η·err·xᵢ; b ← b + η·err. Returns the new head.
|
|
36
|
+
*/
|
|
37
|
+
export function onlineLogisticStep(
|
|
38
|
+
weights: readonly number[],
|
|
39
|
+
bias: number,
|
|
40
|
+
x: readonly number[],
|
|
41
|
+
label: 0 | 1,
|
|
42
|
+
learningRate: number,
|
|
43
|
+
): { weights: number[]; bias: number } {
|
|
44
|
+
const err = label - logisticProbability(weights, bias, x);
|
|
45
|
+
return {
|
|
46
|
+
weights: weights.map((w, i) => w + learningRate * err * x[i]!),
|
|
47
|
+
bias: bias + learningRate * err,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -2,67 +2,16 @@
|
|
|
2
2
|
* Multivariate summaries for the stats module (PRD 41 Part D / D13): Ledoit–Wolf
|
|
3
3
|
* shrinkage covariance and the population stability index (PSI). Pure and
|
|
4
4
|
* deterministic.
|
|
5
|
+
*
|
|
6
|
+
* Ledoit–Wolf lives in memory-engine `ml/classical/covariance.ts` (the anomaly
|
|
7
|
+
* composite's Mahalanobis term fits on it) and is re-exported here, never copied. It
|
|
8
|
+
* comes through the engine's light `./ml/classical` subpath, NEVER the engine root:
|
|
9
|
+
* browser bundles import `./stats`, and the root carries WebGPU kernels and training
|
|
10
|
+
* (`src/contract/regression.statsEngineFree.test.ts` holds this).
|
|
5
11
|
*/
|
|
6
12
|
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
means: number[];
|
|
10
|
-
covariance: number[][];
|
|
11
|
-
/** Shrinkage intensity in [0, 1]. */
|
|
12
|
-
shrinkage: number;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Ledoit–Wolf shrunk covariance estimator. `data` is an n×d matrix (rows are
|
|
17
|
-
* observations). The optimal shrinkage intensity follows the Ledoit–Wolf formula
|
|
18
|
-
* toward the scaled-identity target (tr(S)/d)·I.
|
|
19
|
-
*/
|
|
20
|
-
export function ledoitWolfCovariance(data: readonly (readonly number[])[]): CovarianceResult {
|
|
21
|
-
const n = data.length;
|
|
22
|
-
const d = data[0]?.length ?? 0;
|
|
23
|
-
if (n === 0 || d === 0) return { means: new Array(d).fill(0), covariance: [], shrinkage: 0 };
|
|
24
|
-
const means = new Array<number>(d).fill(0);
|
|
25
|
-
for (const row of data) for (let j = 0; j < d; j++) means[j]! += row[j]! / n;
|
|
26
|
-
const center = data.map((row) => row.map((v, j) => v - means[j]!));
|
|
27
|
-
const scale = 1 / n; // MLE denominator, matching the LW derivation
|
|
28
|
-
const s: number[][] = [];
|
|
29
|
-
for (let i = 0; i < d; i++) {
|
|
30
|
-
s.push(new Array<number>(d).fill(0));
|
|
31
|
-
for (let j = 0; j < d; j++) {
|
|
32
|
-
let acc = 0;
|
|
33
|
-
for (let r = 0; r < n; r++) acc += center[r]![i]! * center[r]![j]!;
|
|
34
|
-
s[i]![j] = acc * scale;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
const trace = s.reduce((acc, row, i) => acc + row[i]!, 0);
|
|
38
|
-
const mu = trace / d;
|
|
39
|
-
// Sum of asymptotic variances of the off-diagonal (and diagonal) entries.
|
|
40
|
-
let deltaSum = 0;
|
|
41
|
-
for (let i = 0; i < d; i++) {
|
|
42
|
-
for (let j = 0; j < d; j++) {
|
|
43
|
-
let acc = 0;
|
|
44
|
-
for (let r = 0; r < n; r++) {
|
|
45
|
-
acc += (center[r]![i]! * center[r]![j]! - (i === j ? s[i]![i]! : s[i]![j]!)) ** 2;
|
|
46
|
-
}
|
|
47
|
-
deltaSum += acc / n;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
deltaSum *= scale * scale;
|
|
51
|
-
// Squared distance from S to the target.
|
|
52
|
-
let targetDist = 0;
|
|
53
|
-
for (let i = 0; i < d; i++) {
|
|
54
|
-
for (let j = 0; j < d; j++) {
|
|
55
|
-
const target = i === j ? mu : 0;
|
|
56
|
-
targetDist += (s[i]![j]! - target) ** 2;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
const beta = Math.min(deltaSum, targetDist);
|
|
60
|
-
const shrinkage = targetDist > 0 ? beta / targetDist : 0;
|
|
61
|
-
const covariance = s.map((row, i) =>
|
|
62
|
-
row.map((v, j) => (1 - shrinkage) * v + (i === j ? shrinkage * mu : 0)),
|
|
63
|
-
);
|
|
64
|
-
return { means, covariance, shrinkage };
|
|
65
|
-
}
|
|
13
|
+
export { ledoitWolfCovariance } from "@seanhogg/builderforce-memory-engine/ml/classical";
|
|
14
|
+
export type { CovarianceResult } from "@seanhogg/builderforce-memory-engine/ml/classical";
|
|
66
15
|
|
|
67
16
|
/**
|
|
68
17
|
* Population stability index, Σ (aᵢ − eᵢ) ln(aᵢ / eᵢ), over `bins` equal-width bins
|
package/src/stats/policies.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* source of randomness.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { type Rng } from "./prng.js";
|
|
8
|
+
import { normalDraw, type Rng } from "./prng.js";
|
|
9
9
|
|
|
10
10
|
export interface BetaArm {
|
|
11
11
|
alpha: number;
|
|
@@ -28,7 +28,9 @@ function gammaDraw(shape: number, rng: Rng): number {
|
|
|
28
28
|
const d = shape - 1 / 3;
|
|
29
29
|
const c = 1 / Math.sqrt(9 * d);
|
|
30
30
|
for (;;) {
|
|
31
|
-
|
|
31
|
+
// The module's ONE normal (prng.ts), stateless: a spare cached across calls would
|
|
32
|
+
// leak one caller's draw into the next, and the same seed would not give the same pick.
|
|
33
|
+
const z = normalDraw(rng);
|
|
32
34
|
const v = Math.pow(1 + c * z, 3);
|
|
33
35
|
if (v <= 0) continue;
|
|
34
36
|
const u = rng();
|
|
@@ -36,28 +38,6 @@ function gammaDraw(shape: number, rng: Rng): number {
|
|
|
36
38
|
}
|
|
37
39
|
}
|
|
38
40
|
|
|
39
|
-
/** Standard-normal draw via the polar form of Box–Muller (caches its spare). */
|
|
40
|
-
function makeNormalZ() {
|
|
41
|
-
let spare: number | null = null;
|
|
42
|
-
return (rng: Rng): number => {
|
|
43
|
-
if (spare !== null) {
|
|
44
|
-
const z = spare;
|
|
45
|
-
spare = null;
|
|
46
|
-
return z;
|
|
47
|
-
}
|
|
48
|
-
let u: number, v: number, s: number;
|
|
49
|
-
do {
|
|
50
|
-
u = rng() * 2 - 1;
|
|
51
|
-
v = rng() * 2 - 1;
|
|
52
|
-
s = u * u + v * v;
|
|
53
|
-
} while (s >= 1 || s === 0);
|
|
54
|
-
const mul = Math.sqrt((-2 * Math.log(s)) / s);
|
|
55
|
-
spare = v * mul;
|
|
56
|
-
return u * mul;
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
const normalZ = makeNormalZ();
|
|
60
|
-
|
|
61
41
|
/**
|
|
62
42
|
* Sample one arm index by Thompson sampling: draw θᵢ ~ Beta(αᵢ, βᵢ) per arm and
|
|
63
43
|
* return the argmax. Deterministic under the supplied `rng`.
|