@seanhogg/builderforce-memory 2026.10.74 → 2026.10.75

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.
@@ -25,6 +25,8 @@ export type { ChangePointResult, CusumResult } from "./timeSeries.js";
25
25
  export { ledoitWolfCovariance, psi } from "./multivariate.js";
26
26
  export type { CovarianceResult } from "./multivariate.js";
27
27
  export { entropyOfCounts, shannonEntropy } from "./information.js";
28
+ export { meanAndSd } from "./moments.js";
29
+ export type { MeanAndSd } from "./moments.js";
28
30
  export { chapmanEstimate, gammaPoissonPosterior, goelOkumotoMLE, kaplanMeier, lincolnPetersenEstimate, } from "./estimators.js";
29
31
  export type { InsufficientData, KaplanMeierResult } from "./estimators.js";
30
32
  export { brierScore, effortAwareRecall, expectedCalibrationError, ndcgAtK, popt, prAuc, } from "./scores.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/stats/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAClD,YAAY,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EACH,WAAW,EACX,aAAa,EACb,aAAa,EACb,sBAAsB,EACtB,gCAAgC,EAChC,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,yBAAyB,EACzB,0BAA0B,EAC1B,cAAc,GACjB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAEjF,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACjF,YAAY,EAAE,uBAAuB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEzE,OAAO,EACH,iBAAiB,EACjB,Y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wilcoxonSignedRank, } from "./tests.js
19
19
  export { bayesianOnlineChangePoint, cusum } from "./timeSeries.js";
20
20
  export { ledoitWolfCovariance, psi } from "./multivariate.js";
21
21
  export { entropyOfCounts, shannonEntropy } from "./information.js";
22
+ export { meanAndSd } from "./moments.js";
22
23
  export { chapmanEstimate, gammaPoissonPosterior, goelOkumotoMLE, kaplanMeier, lincolnPetersenEstimate, } from "./estimators.js";
23
24
  export { brierScore, effortAwareRecall, expectedCalibrationError, ndcgAtK, popt, prAuc, } from "./scores.js";
24
25
  export { thompsonRank, thompsonSample } from "./policies.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/stats/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAGlD,OAAO,EACH,WAAW,EACX,aAAa,EACb,aAAa,EACb,sBAAsB,EACtB,gCAAgC,EAChC,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,yBAAyB,EACzB,0BAA0B,EAC1B,cAAc,GACjB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAEjF,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAGjF,OAAO,EACH,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,GACrB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,yBAAyB,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAGnE,OAAO,EAAE,oBAAoB,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAG9D,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEnE,OAAO,EACH,eAAe,EACf,qBAAqB,EACrB,cAAc,EACd,WAAW,EACX,uBAAuB,GAC1B,MAAM,iBAAiB,C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AAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Sample moments for the stats module (PRD 41 Part D / D13): the ONE mean and
3
+ * standard deviation for predicted measures, so callers stop hand-rolling them.
4
+ */
5
+ /** Result of {@link meanAndSd}. */
6
+ export interface MeanAndSd {
7
+ /** Number of finite values actually used. */
8
+ n: number;
9
+ /** Arithmetic mean of the finite values; NaN when `n` is 0. */
10
+ mean: number;
11
+ /** Sample standard deviation (n − 1 denominator); 0 when `n` < 2. */
12
+ sd: number;
13
+ /**
14
+ * Values that were not finite (NaN or ±Infinity) and were skipped, the same
15
+ * convention as `WilcoxonResult.nonFinite`.
16
+ */
17
+ nonFinite: number;
18
+ }
19
+ /**
20
+ * Mean and SAMPLE standard deviation by Welford's online algorithm, which stays
21
+ * accurate where the naive Σx² − (Σx)²/n form cancels catastrophically (values
22
+ * with a large common offset).
23
+ *
24
+ * - Non-finite values (NaN, ±Infinity) are skipped and counted in `nonFinite`;
25
+ * `n` is the count of values used.
26
+ * - `n` = 0: `mean` is NaN and `sd` is 0. One result shape is kept rather than the
27
+ * estimators' `InsufficientData` union, so callers branch on `n`.
28
+ * - `n` = 1: `mean` is the value and `sd` is 0 (a sample sd needs two values).
29
+ * - A z-score consumer must guard `n >= 2 && sd > 0`: sd is 0 (not NaN) for one
30
+ * value or all-equal data, so an unguarded division yields ±Infinity.
31
+ *
32
+ * Pure and deterministic: one pass in input order, no allocation beyond the result.
33
+ */
34
+ export declare function meanAndSd(values: readonly number[]): MeanAndSd;
35
+ //# sourceMappingURL=moments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"moments.d.ts","sourceRoot":"","sources":["../../src/stats/moments.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,mCAAmC;AACnC,MAAM,WAAW,SAAS;IACtB,6CAA6C;IAC7C,CAAC,EAAE,MAAM,CAAC;IACV,+DAA+D;IAC/D,IAAI,EAAE,MAAM,CAAC;IACb,qEAAqE;IACrE,EAAE,EAAE,MAAM,CAAC;IACX;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAkB9D"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Sample moments for the stats module (PRD 41 Part D / D13): the ONE mean and
3
+ * standard deviation for predicted measures, so callers stop hand-rolling them.
4
+ */
5
+ /**
6
+ * Mean and SAMPLE standard deviation by Welford's online algorithm, which stays
7
+ * accurate where the naive Σx² − (Σx)²/n form cancels catastrophically (values
8
+ * with a large common offset).
9
+ *
10
+ * - Non-finite values (NaN, ±Infinity) are skipped and counted in `nonFinite`;
11
+ * `n` is the count of values used.
12
+ * - `n` = 0: `mean` is NaN and `sd` is 0. One result shape is kept rather than the
13
+ * estimators' `InsufficientData` union, so callers branch on `n`.
14
+ * - `n` = 1: `mean` is the value and `sd` is 0 (a sample sd needs two values).
15
+ * - A z-score consumer must guard `n >= 2 && sd > 0`: sd is 0 (not NaN) for one
16
+ * value or all-equal data, so an unguarded division yields ±Infinity.
17
+ *
18
+ * Pure and deterministic: one pass in input order, no allocation beyond the result.
19
+ */
20
+ export function meanAndSd(values) {
21
+ let n = 0;
22
+ let nonFinite = 0;
23
+ let mean = 0;
24
+ let m2 = 0;
25
+ for (const x of values) {
26
+ if (!Number.isFinite(x)) {
27
+ nonFinite++;
28
+ continue;
29
+ }
30
+ n++;
31
+ const delta = x - mean;
32
+ mean += delta / n;
33
+ m2 += delta * (x - mean);
34
+ }
35
+ if (n === 0)
36
+ return { n: 0, mean: Number.NaN, sd: 0, nonFinite };
37
+ const sd = n < 2 ? 0 : Math.sqrt(Math.max(0, m2) / (n - 1));
38
+ return { n, mean, sd, nonFinite };
39
+ }
40
+ //# sourceMappingURL=moments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"moments.js","sourceRoot":"","sources":["../../src/stats/moments.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAiBH;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,SAAS,CAAC,MAAyB;IAC/C,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,EAAE,GAAG,CAAC,CAAC;IACX,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;YACtB,SAAS,EAAE,CAAC;YACZ,SAAS;QACb,CAAC;QACD,CAAC,EAAE,CAAC;QACJ,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,CAAC;QACvB,IAAI,IAAI,KAAK,GAAG,CAAC,CAAC;QAClB,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7B,CAAC;IACD,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC;IACjE,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC5D,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC;AACtC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seanhogg/builderforce-memory",
3
- "version": "2026.10.74",
3
+ "version": "2026.10.75",
4
4
  "description": "BuilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, persistent agent memory, and token-saving agent-run memory (code maps, a prompt-cache-safe working memory, chunked transcript windowing) for BuilderForce.ai agents.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -636,6 +636,7 @@
636
636
  "ledoitWolfCovariance",
637
637
  "lincolnPetersenEstimate",
638
638
  "logisticProbability",
639
+ "meanAndSd",
639
640
  "ndcgAtK",
640
641
  "normalDraw",
641
642
  "onlineLogisticStep",
@@ -36,6 +36,7 @@ import type {
36
36
  NodeRef, StationTransition, TransitionRow, TransitionSource, TransitionTable,
37
37
  } from '../knowledge/index.js';
38
38
  import type { betaMoments, logisticProbability, onlineLogisticStep, rateInterval, sigmoid, wilsonInterval } from '../stats/index.js';
39
+ import type { meanAndSd, MeanAndSd } from '../stats/index.js';
39
40
  import type {
40
41
  CallFact, CapabilityImportFact, DerivedRows, EntryPointFact, EntryPointKind, ExportFact, ExtractorStamp, FactChange, FactGraph, FactGraphOptions,
41
42
  FactGraphUpdate, FactKind, FactRule, FileFacts, RuleEvaluation, RuleScope, RuleWorld, TestCaseFact, TestFacts,
@@ -323,6 +324,9 @@ export type wilsonInterval_signature = Expect<Equal<
323
324
  typeof wilsonInterval, (successes: number, n: number, z?: number) => { low: number; high: number }
324
325
  >>;
325
326
  export type betaMoments_signature = Expect<Equal<typeof betaMoments, (alpha: number, beta: number) => { mean: number; variance: number }>>;
327
+ // PRD 41 D13: the one mean / sample sd (Welford) for predicted measures; run-delta's naturalness model migrates onto it.
328
+ export type meanAndSd_signature = Expect<Equal<typeof meanAndSd, (values: readonly number[]) => MeanAndSd>>;
329
+ export type MeanAndSd_fields = Expect<Equal<MeanAndSd, { n: number; mean: number; sd: number; nonFinite: number }>>;
326
330
  // PRD 38 P7: station transitions (the view groups stations; memory owns the formula). Reference rows carry no interval.
327
331
  export type TransitionSource_values = Expect<Equal<TransitionSource, 'traces' | 'references'>>;
328
332
  export type StationTransition_fields = Expect<Equal<StationTransition, { to: string; p: number; k: number; n: number; low?: number; high?: number }>>;
@@ -50,6 +50,9 @@ export type { CovarianceResult } from "./multivariate.js";
50
50
 
51
51
  export { entropyOfCounts, shannonEntropy } from "./information.js";
52
52
 
53
+ export { meanAndSd } from "./moments.js";
54
+ export type { MeanAndSd } from "./moments.js";
55
+
53
56
  export {
54
57
  chapmanEstimate,
55
58
  gammaPoissonPosterior,
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The PRD 41 D13 mean / sample sd primitive (`meanAndSd`): the one mean and standard
3
+ * deviation for predicted measures (Builderforce run-delta's naturalness model).
4
+ */
5
+
6
+ import { describe, expect, it } from "@jest/globals";
7
+ import { meanAndSd } from "./index.js";
8
+
9
+ describe("meanAndSd", () => {
10
+ it("gives the textbook mean and sample sd", () => {
11
+ // 2,4,4,4,5,5,7,9: mean 5, Σ(x−5)² = 32, sample variance 32/7.
12
+ const r = meanAndSd([2, 4, 4, 4, 5, 5, 7, 9]);
13
+ expect(r.n).toBe(8);
14
+ expect(r.nonFinite).toBe(0);
15
+ expect(r.mean).toBe(5);
16
+ expect(r.sd).toBeCloseTo(Math.sqrt(32 / 7), 14);
17
+ const s = meanAndSd([1, 2, 3, 4]);
18
+ expect(s.mean).toBe(2.5);
19
+ expect(s.sd).toBeCloseTo(Math.sqrt(5 / 3), 14);
20
+ });
21
+
22
+ it("survives catastrophic cancellation (large common offset)", () => {
23
+ const r = meanAndSd([1e9 + 4, 1e9 + 7, 1e9 + 13, 1e9 + 16]);
24
+ expect(r.n).toBe(4);
25
+ expect(r.mean).toBe(1e9 + 10);
26
+ expect(r.sd * r.sd).toBeCloseTo(30, 9);
27
+ });
28
+
29
+ it("n = 0: mean NaN, sd 0", () => {
30
+ expect(meanAndSd([])).toEqual({ n: 0, mean: Number.NaN, sd: 0, nonFinite: 0 });
31
+ });
32
+
33
+ it("n = 1: mean is the value, sd 0", () => {
34
+ expect(meanAndSd([3.25])).toEqual({ n: 1, mean: 3.25, sd: 0, nonFinite: 0 });
35
+ });
36
+
37
+ it("all-equal input has sd exactly 0", () => {
38
+ const r = meanAndSd([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]);
39
+ expect(r.n).toBe(7);
40
+ expect(r.mean).toBeCloseTo(0.1, 15);
41
+ expect(r.sd).toBe(0);
42
+ });
43
+
44
+ it("skips NaN and ±Infinity, counting them in nonFinite", () => {
45
+ const r = meanAndSd([1, Number.NaN, 2, Number.POSITIVE_INFINITY, 3, Number.NEGATIVE_INFINITY, 4]);
46
+ expect(r.n).toBe(4);
47
+ expect(r.nonFinite).toBe(3);
48
+ expect(r.mean).toBe(2.5);
49
+ expect(r.sd).toBeCloseTo(Math.sqrt(5 / 3), 14);
50
+ expect(meanAndSd([Number.NaN, Number.NaN])).toEqual({ n: 0, mean: Number.NaN, sd: 0, nonFinite: 2 });
51
+ });
52
+
53
+ it("is deterministic and does not mutate its input", () => {
54
+ const input = Object.freeze([5, 1, 9, 3, 7]);
55
+ expect(meanAndSd(input)).toEqual(meanAndSd(input));
56
+ expect(input).toEqual([5, 1, 9, 3, 7]);
57
+ });
58
+ });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Sample moments for the stats module (PRD 41 Part D / D13): the ONE mean and
3
+ * standard deviation for predicted measures, so callers stop hand-rolling them.
4
+ */
5
+
6
+ /** Result of {@link meanAndSd}. */
7
+ export interface MeanAndSd {
8
+ /** Number of finite values actually used. */
9
+ n: number;
10
+ /** Arithmetic mean of the finite values; NaN when `n` is 0. */
11
+ mean: number;
12
+ /** Sample standard deviation (n − 1 denominator); 0 when `n` < 2. */
13
+ sd: number;
14
+ /**
15
+ * Values that were not finite (NaN or ±Infinity) and were skipped, the same
16
+ * convention as `WilcoxonResult.nonFinite`.
17
+ */
18
+ nonFinite: number;
19
+ }
20
+
21
+ /**
22
+ * Mean and SAMPLE standard deviation by Welford's online algorithm, which stays
23
+ * accurate where the naive Σx² − (Σx)²/n form cancels catastrophically (values
24
+ * with a large common offset).
25
+ *
26
+ * - Non-finite values (NaN, ±Infinity) are skipped and counted in `nonFinite`;
27
+ * `n` is the count of values used.
28
+ * - `n` = 0: `mean` is NaN and `sd` is 0. One result shape is kept rather than the
29
+ * estimators' `InsufficientData` union, so callers branch on `n`.
30
+ * - `n` = 1: `mean` is the value and `sd` is 0 (a sample sd needs two values).
31
+ * - A z-score consumer must guard `n >= 2 && sd > 0`: sd is 0 (not NaN) for one
32
+ * value or all-equal data, so an unguarded division yields ±Infinity.
33
+ *
34
+ * Pure and deterministic: one pass in input order, no allocation beyond the result.
35
+ */
36
+ export function meanAndSd(values: readonly number[]): MeanAndSd {
37
+ let n = 0;
38
+ let nonFinite = 0;
39
+ let mean = 0;
40
+ let m2 = 0;
41
+ for (const x of values) {
42
+ if (!Number.isFinite(x)) {
43
+ nonFinite++;
44
+ continue;
45
+ }
46
+ n++;
47
+ const delta = x - mean;
48
+ mean += delta / n;
49
+ m2 += delta * (x - mean);
50
+ }
51
+ if (n === 0) return { n: 0, mean: Number.NaN, sd: 0, nonFinite };
52
+ const sd = n < 2 ? 0 : Math.sqrt(Math.max(0, m2) / (n - 1));
53
+ return { n, mean, sd, nonFinite };
54
+ }