@hmharness/cognitive 0.23.21 → 0.23.23

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.
@@ -0,0 +1,125 @@
1
+ export interface CodeEntity {
2
+ /** stable id: `${uri}#${name}` */
3
+ id: string;
4
+ kind: 'file' | 'module' | 'function' | 'class' | 'method' | 'field';
5
+ name: string;
6
+ uri: string;
7
+ range?: {
8
+ startLine: number;
9
+ endLine: number;
10
+ };
11
+ }
12
+ export type RelationKind = 'defines' | 'calls' | 'references' | 'imports' | 'implements';
13
+ export interface SymbolRelation {
14
+ from: string;
15
+ to: string;
16
+ kind: RelationKind;
17
+ }
18
+ export interface CodeDiagnostic {
19
+ uri: string;
20
+ severity: 1 | 2 | 3 | 4;
21
+ message: string;
22
+ source: 'lsp' | 'build' | 'runtime';
23
+ }
24
+ export interface BuildFact {
25
+ ok: boolean;
26
+ outputDigest?: string;
27
+ at: string;
28
+ }
29
+ export interface RuntimeFact {
30
+ kind: string;
31
+ detail: string;
32
+ at: string;
33
+ }
34
+ export interface EditDelta {
35
+ editKind: 'rename' | 'delete' | 'modify';
36
+ target: string;
37
+ touchedEntities: string[];
38
+ touchedRelations: string[];
39
+ newDiagnosticEstimate: number;
40
+ }
41
+ export interface PredictionError {
42
+ /** Jaccard over the union of touched entities+relations */
43
+ jaccard: number;
44
+ precision: number;
45
+ recall: number;
46
+ /** entities/relations the edit touched that prediction missed (surprise) */
47
+ missed: string[];
48
+ /** predicted but untouched (overprediction) */
49
+ spurious: string[];
50
+ }
51
+ /** Data-only export shape — the persistence layer (code-world-store.ts)
52
+ * adds the kind/version envelope. fromSnapshot() is its inverse. */
53
+ export interface CodeWorldData {
54
+ entities: CodeEntity[];
55
+ relations: SymbolRelation[];
56
+ diagnostics: CodeDiagnostic[];
57
+ build: BuildFact | null;
58
+ runtime: RuntimeFact[];
59
+ }
60
+ export declare class CodeWorldModel {
61
+ private entities;
62
+ /** keyed `${from}->${to}:${kind}` — round 38 made relation ingest
63
+ * IDEMPOTENT like entities: a sensor re-observing the same edge is the
64
+ * same fact, not a new one. Append-only storage would grow without
65
+ * bound once persistence landed (every save→load cycle re-syncs). */
66
+ private relations;
67
+ /** latest diagnostics per uri (sensors push; overwrite per uri) */
68
+ private diagnostics;
69
+ private latestBuild;
70
+ private runtimeFacts;
71
+ private openPredictions;
72
+ /** Ingest sensors' output — idempotent per entity id AND per relation
73
+ * edge; diagnostics replace per uri. */
74
+ ingest(input: {
75
+ entities?: CodeEntity[];
76
+ relations?: SymbolRelation[];
77
+ diagnostics?: CodeDiagnostic[];
78
+ build?: BuildFact;
79
+ runtime?: RuntimeFact;
80
+ }): void;
81
+ /** Full data export (entities, deduped relations, diagnostics, build,
82
+ * runtime) — the store's save path; stateHash stays the cheap path. */
83
+ snapshot(): CodeWorldData;
84
+ /** Restore from a snapshot (load path) — a fresh model, one bulk set. */
85
+ static fromSnapshot(data: Partial<CodeWorldData>): CodeWorldModel;
86
+ get entityCount(): number;
87
+ get relationCount(): number;
88
+ get diagnosticCount(): number;
89
+ get build(): BuildFact | null;
90
+ /** Runtime observations (sensor-pushed), oldest first. Deliberately NOT
91
+ * part of stateHash: runtime history is evidence, not code state —
92
+ * holdout/drift hashing must not change because the agent browsed. */
93
+ get runtime(): RuntimeFact[];
94
+ entity(id: string): CodeEntity | undefined;
95
+ relationsOf(entityId: string): SymbolRelation[];
96
+ diagnosticsFor(uri: string): CodeDiagnostic[];
97
+ /**
98
+ * PREDICT an edit's blast radius from the relation graph: renaming or
99
+ * deleting entity X touches X itself plus every relation that names X
100
+ * (callers, referrers, importers). newDiagnosticEstimate is the count of
101
+ * existing diagnostics on the touched files — the honest floor, not a
102
+ * guess about new ones.
103
+ */
104
+ predictEditDelta(edit: {
105
+ editKind: 'rename' | 'delete' | 'modify';
106
+ target: string;
107
+ }): EditDelta;
108
+ /**
109
+ * Record what ACTUALLY happened and settle the open prediction. The
110
+ * actual may legally differ — surprise (missed) is exactly the signal
111
+ * that the graph is incomplete.
112
+ */
113
+ recordEditDelta(target: string, actual: {
114
+ touchedEntities: string[];
115
+ touchedRelations: string[];
116
+ }): PredictionError | null;
117
+ /** Snapshot hash — for holdout discipline and drift detection.
118
+ * Content-sensitive on diagnostics too (round 38): hashing only the uri
119
+ * list made "a new diagnostic on a known file" invisible to drift
120
+ * detection — a round-35 test assertion had been passing for the WRONG
121
+ * reason (duplicate relation edges from re-syncs), exposed by relation
122
+ * idempotence. Canonical: sorted, order-independent. Runtime history
123
+ * stays OUT (evidence, not code state). */
124
+ stateHash(): string;
125
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * @hmharness/cognitive - Code World Model (2026-10-04 audit line B / W7)
3
+ *
4
+ * "LSP + API KG + build/runtime facts 统一成 CodeEntity/Relation/
5
+ * Diagnostic/BuildFact/RuntimeFact" — one typed store for the code world,
6
+ * fed by sensors the host wires (LSP symbols/diagnostics, API KG, build
7
+ * runs, runtime probes). Cognitive keeps zero dependency on the lsp
8
+ * package: facts arrive as plain data, the model owns the ontology.
9
+ *
10
+ * The WM-2 discipline applies verbatim: an edit is PREDICTED before it
11
+ * happens (which entities, relations and diagnostics it should touch,
12
+ * derived from the relation graph), the ACTUAL delta is recorded after,
13
+ * and the prediction error is computed — the code world gets the same
14
+ * predict-before/actual-after/error scoring the environment world has.
15
+ */
16
+ import { stableHash } from "./protocol.js";
17
+ export class CodeWorldModel {
18
+ entities = new Map();
19
+ /** keyed `${from}->${to}:${kind}` — round 38 made relation ingest
20
+ * IDEMPOTENT like entities: a sensor re-observing the same edge is the
21
+ * same fact, not a new one. Append-only storage would grow without
22
+ * bound once persistence landed (every save→load cycle re-syncs). */
23
+ relations = new Map();
24
+ /** latest diagnostics per uri (sensors push; overwrite per uri) */
25
+ diagnostics = new Map();
26
+ latestBuild = null;
27
+ runtimeFacts = [];
28
+ openPredictions = new Map();
29
+ /** Ingest sensors' output — idempotent per entity id AND per relation
30
+ * edge; diagnostics replace per uri. */
31
+ ingest(input) {
32
+ for (const e of input.entities ?? [])
33
+ this.entities.set(e.id, e);
34
+ for (const r of input.relations ?? [])
35
+ this.relations.set(`${r.from}->${r.to}:${r.kind}`, r);
36
+ for (const d of input.diagnostics ?? []) {
37
+ const cur = this.diagnostics.get(d.uri) ?? [];
38
+ const next = cur.filter((x) => x.message !== d.message || x.source !== d.source);
39
+ next.push(d);
40
+ this.diagnostics.set(d.uri, next);
41
+ }
42
+ if (input.build)
43
+ this.latestBuild = input.build;
44
+ if (input.runtime)
45
+ this.runtimeFacts.push(input.runtime);
46
+ }
47
+ /** Full data export (entities, deduped relations, diagnostics, build,
48
+ * runtime) — the store's save path; stateHash stays the cheap path. */
49
+ snapshot() {
50
+ return {
51
+ entities: [...this.entities.values()],
52
+ relations: [...this.relations.values()],
53
+ diagnostics: [...this.diagnostics.values()].flat(),
54
+ build: this.latestBuild,
55
+ runtime: [...this.runtimeFacts],
56
+ };
57
+ }
58
+ /** Restore from a snapshot (load path) — a fresh model, one bulk set. */
59
+ static fromSnapshot(data) {
60
+ const m = new CodeWorldModel();
61
+ for (const e of data.entities ?? [])
62
+ m.entities.set(e.id, e);
63
+ for (const r of data.relations ?? [])
64
+ m.relations.set(`${r.from}->${r.to}:${r.kind}`, r);
65
+ for (const d of data.diagnostics ?? []) {
66
+ const cur = m.diagnostics.get(d.uri) ?? [];
67
+ const next = cur.filter((x) => x.message !== d.message || x.source !== d.source);
68
+ next.push(d);
69
+ m.diagnostics.set(d.uri, next);
70
+ }
71
+ if (data.build)
72
+ m.latestBuild = data.build;
73
+ m.runtimeFacts.push(...(data.runtime ?? []));
74
+ return m;
75
+ }
76
+ get entityCount() {
77
+ return this.entities.size;
78
+ }
79
+ get relationCount() {
80
+ return this.relations.size;
81
+ }
82
+ get diagnosticCount() {
83
+ return [...this.diagnostics.values()].reduce((s, l) => s + l.length, 0);
84
+ }
85
+ get build() {
86
+ return this.latestBuild;
87
+ }
88
+ /** Runtime observations (sensor-pushed), oldest first. Deliberately NOT
89
+ * part of stateHash: runtime history is evidence, not code state —
90
+ * holdout/drift hashing must not change because the agent browsed. */
91
+ get runtime() {
92
+ return [...this.runtimeFacts];
93
+ }
94
+ entity(id) {
95
+ return this.entities.get(id);
96
+ }
97
+ relationsOf(entityId) {
98
+ return [...this.relations.values()].filter((r) => r.from === entityId || r.to === entityId);
99
+ }
100
+ diagnosticsFor(uri) {
101
+ return [...(this.diagnostics.get(uri) ?? [])];
102
+ }
103
+ /**
104
+ * PREDICT an edit's blast radius from the relation graph: renaming or
105
+ * deleting entity X touches X itself plus every relation that names X
106
+ * (callers, referrers, importers). newDiagnosticEstimate is the count of
107
+ * existing diagnostics on the touched files — the honest floor, not a
108
+ * guess about new ones.
109
+ */
110
+ predictEditDelta(edit) {
111
+ const touchedEntities = new Set([edit.target]);
112
+ const touchedRelations = new Set();
113
+ for (const r of this.relations.values()) {
114
+ if (r.from === edit.target || r.to === edit.target) {
115
+ touchedRelations.add(`${r.from}->${r.to}:${r.kind}`);
116
+ touchedEntities.add(r.from);
117
+ touchedEntities.add(r.to);
118
+ }
119
+ }
120
+ const uris = new Set([...touchedEntities].map((id) => id.split('#')[0]));
121
+ let diagFloor = 0;
122
+ for (const uri of uris)
123
+ diagFloor += (this.diagnostics.get(uri) ?? []).length;
124
+ const predicted = {
125
+ editKind: edit.editKind,
126
+ target: edit.target,
127
+ touchedEntities: [...touchedEntities],
128
+ touchedRelations: [...touchedRelations],
129
+ newDiagnosticEstimate: diagFloor,
130
+ };
131
+ this.openPredictions.set(edit.target, { predicted, at: new Date().toISOString() });
132
+ return predicted;
133
+ }
134
+ /**
135
+ * Record what ACTUALLY happened and settle the open prediction. The
136
+ * actual may legally differ — surprise (missed) is exactly the signal
137
+ * that the graph is incomplete.
138
+ */
139
+ recordEditDelta(target, actual) {
140
+ const open = this.openPredictions.get(target);
141
+ if (!open)
142
+ return null;
143
+ this.openPredictions.delete(target);
144
+ const p = new Set([...open.predicted.touchedEntities, ...open.predicted.touchedRelations]);
145
+ const a = new Set([...actual.touchedEntities, ...actual.touchedRelations]);
146
+ const union = new Set([...p, ...a]);
147
+ const inter = [...p].filter((x) => a.has(x));
148
+ const missed = [...a].filter((x) => !p.has(x));
149
+ const spurious = [...p].filter((x) => !a.has(x));
150
+ return {
151
+ jaccard: union.size ? Number((inter.length / union.size).toFixed(3)) : 1,
152
+ precision: a.size ? Number((inter.length / a.size).toFixed(3)) : 1,
153
+ recall: p.size ? Number((inter.length / p.size).toFixed(3)) : 1,
154
+ missed,
155
+ spurious,
156
+ };
157
+ }
158
+ /** Snapshot hash — for holdout discipline and drift detection.
159
+ * Content-sensitive on diagnostics too (round 38): hashing only the uri
160
+ * list made "a new diagnostic on a known file" invisible to drift
161
+ * detection — a round-35 test assertion had been passing for the WRONG
162
+ * reason (duplicate relation edges from re-syncs), exposed by relation
163
+ * idempotence. Canonical: sorted, order-independent. Runtime history
164
+ * stays OUT (evidence, not code state). */
165
+ stateHash() {
166
+ return stableHash({
167
+ entities: [...this.entities.keys()].sort(),
168
+ relations: [...this.relations.keys()].sort(),
169
+ diagnostics: [...this.diagnostics.entries()]
170
+ .map(([uri, list]) => `${uri}::${list.map((d) => `${d.source ?? ''}|${d.severity}|${d.message}`).sort().join(';')}`)
171
+ .sort(),
172
+ build: this.latestBuild,
173
+ });
174
+ }
175
+ }
@@ -0,0 +1,14 @@
1
+ import { CodeWorldModel, type CodeWorldData } from './code-world-model.js';
2
+ /** Runtime evidence retained on disk. Browsing-heavy sessions can push
3
+ * thousands of facts; the LAST 500 carry the recent-context signal. */
4
+ export declare const RUNTIME_FACT_CAP = 500;
5
+ export interface CodeWorldFile extends CodeWorldData {
6
+ kind: 'hmharness-code-world';
7
+ version: 1;
8
+ savedAt: string;
9
+ }
10
+ export declare function codeWorldModelPath(home: string): string;
11
+ /** Load the persisted model (fresh when absent/corrupt/foreign-shaped). */
12
+ export declare function loadCodeWorldModel(home: string): Promise<CodeWorldModel>;
13
+ /** Persist the model (runtime facts trimmed to the newest cap). */
14
+ export declare function saveCodeWorldModel(home: string, cwm: CodeWorldModel): Promise<void>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @hmharness/cognitive - Code World Model persistence
3
+ *
4
+ * The model is in-memory by design (round 34); sensors were library-first
5
+ * (round 35 LSP, round 37 extension). Round 38 gives the model a HOME:
6
+ * one JSON file under HMH_HOME/cognitive/, load→mutate→save round-trips
7
+ * through snapshot()/fromSnapshot(), and the only unbounded kind —
8
+ * runtime facts (the agent browses; code size bounds the rest) — is
9
+ * trimmed to the most recent RUNTIME_FACT_CAP at SAVE time, never inside
10
+ * the model (the in-memory view keeps everything the process observed).
11
+ *
12
+ * File shape: plain JSON, user-inspectable, kind-stamped like every other
13
+ * trust/state file under cognitive/. Corrupt/absent = fresh model, never
14
+ * a crash (same discipline as the trust stores).
15
+ */
16
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
17
+ import { join } from 'node:path';
18
+ import { CodeWorldModel } from "./code-world-model.js";
19
+ /** Runtime evidence retained on disk. Browsing-heavy sessions can push
20
+ * thousands of facts; the LAST 500 carry the recent-context signal. */
21
+ export const RUNTIME_FACT_CAP = 500;
22
+ export function codeWorldModelPath(home) {
23
+ return join(home, 'cognitive', 'code-world-model.json');
24
+ }
25
+ /** Load the persisted model (fresh when absent/corrupt/foreign-shaped). */
26
+ export async function loadCodeWorldModel(home) {
27
+ try {
28
+ const j = JSON.parse(await readFile(codeWorldModelPath(home), 'utf8'));
29
+ if (j && j.kind === 'hmharness-code-world')
30
+ return CodeWorldModel.fromSnapshot(j);
31
+ }
32
+ catch { /* absent/corrupt = fresh model */ }
33
+ return new CodeWorldModel();
34
+ }
35
+ /** Persist the model (runtime facts trimmed to the newest cap). */
36
+ export async function saveCodeWorldModel(home, cwm) {
37
+ const data = cwm.snapshot();
38
+ const file = {
39
+ kind: 'hmharness-code-world',
40
+ version: 1,
41
+ savedAt: new Date().toISOString(),
42
+ ...data,
43
+ runtime: data.runtime.slice(-RUNTIME_FACT_CAP),
44
+ };
45
+ await mkdir(join(home, 'cognitive'), { recursive: true });
46
+ await writeFile(codeWorldModelPath(home), JSON.stringify(file), 'utf8');
47
+ }
@@ -0,0 +1,98 @@
1
+ export interface EvalTask {
2
+ id: string;
3
+ prompt: string;
4
+ /** assertion spec resolved by the host evaluator (expect-exact/regex/none/any) */
5
+ assertion: {
6
+ kind: 'expect-exact' | 'expect-regex' | 'expect-none' | 'expect-any';
7
+ expect: string;
8
+ };
9
+ /** true = holdout: promotion gates may never train on it */
10
+ holdout?: boolean;
11
+ }
12
+ export interface EvalTaskSet {
13
+ kind: 'hmharness-eval-taskset';
14
+ version: 1;
15
+ /** stable set id (e.g. 'generALBench-core'); content changes bump revision */
16
+ id: string;
17
+ revision: number;
18
+ createdAt: string;
19
+ tasks: EvalTask[];
20
+ }
21
+ /** Canonical JSON: tasks sorted by id, key order fixed — the hash basis. */
22
+ export declare function canonicalTaskSet(set: Omit<EvalTaskSet, 'createdAt'> & {
23
+ createdAt?: string;
24
+ }): string;
25
+ /** sha256 over the canonical form — order-independent, content-sensitive. */
26
+ export declare function datasetHash(set: Omit<EvalTaskSet, 'createdAt'> & {
27
+ createdAt?: string;
28
+ }): string;
29
+ /** Zero-dep PRNG (mulberry32) — same seed, same sequence, everywhere. */
30
+ export declare function seededRandom(seed: number): () => number;
31
+ /** Deterministic shuffle: same (tasks, seed) -> same order. */
32
+ export declare function seededOrder<T>(items: T[], seed: number): T[];
33
+ /** Stable seed from a string (dataset id + explicit seed material). */
34
+ export declare function seedFromString(s: string): number;
35
+ export interface EvalSplit {
36
+ train: EvalTask[];
37
+ holdout: EvalTask[];
38
+ }
39
+ export declare function splitSet(set: EvalTaskSet): EvalSplit;
40
+ /** The discipline gate: a train-side arm must contain ZERO holdout task ids. */
41
+ export declare function holdoutDisciplineOK(armTaskIds: string[], split: EvalSplit): {
42
+ ok: boolean;
43
+ violations: string[];
44
+ };
45
+ export interface EvalRunReport {
46
+ kind: 'hmharness-eval-run';
47
+ version: 1;
48
+ datasetHash: string;
49
+ setId: string;
50
+ revision: number;
51
+ seed: number;
52
+ split: 'train' | 'holdout';
53
+ arm: string;
54
+ perTask: Array<{
55
+ id: string;
56
+ pass: boolean;
57
+ }>;
58
+ passed: number;
59
+ total: number;
60
+ finishedAt: string;
61
+ }
62
+ /** Two reports are comparable ONLY when datasetHash + seed + split match. */
63
+ export declare function reportsComparable(a: EvalRunReport, b: EvalRunReport): boolean;
64
+ /** Build a report from a run (the host provides per-task pass flags). */
65
+ export declare function buildRunReport(set: EvalTaskSet, opts: {
66
+ seed: number;
67
+ split: 'train' | 'holdout';
68
+ arm: string;
69
+ perTask: Array<{
70
+ id: string;
71
+ pass: boolean;
72
+ }>;
73
+ }): EvalRunReport;
74
+ export interface SignificanceVerdict {
75
+ /** comparable precondition failed? then NOTHING else is filled */
76
+ comparable: boolean;
77
+ refusalReason?: string;
78
+ /** discordant pairs: only tasks where the two arms DISAGREE carry signal */
79
+ discordant: {
80
+ armOnlyPassed: number;
81
+ armBPassed: number;
82
+ agreed: number;
83
+ };
84
+ /** exact McNemar two-sided p-value over the discordant pairs */
85
+ pValue?: number;
86
+ significant?: boolean;
87
+ /** the audit discipline: a fixed alpha, stated on every verdict */
88
+ alpha: 0.05;
89
+ }
90
+ /**
91
+ * McNemar exact test for two PAIRED arms on the same task set. Refuses
92
+ * non-comparable reports outright (datasetHash+seed+split must all match);
93
+ * significance = discordant pairs are lopsided enough that a fair coin
94
+ * would rarely produce them (exact binomial, no normal approximation —
95
+ * eval sets are small). This is the 统计检验 the audit demanded so a
96
+ * "7/10 vs 5/10" delta can never again be read as an effect.
97
+ */
98
+ export declare function pairedSignificance(a: EvalRunReport, b: EvalRunReport): SignificanceVerdict;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @hmharness/cognitive - versioned eval task sets (2026-10-04 audit EVAL-IND)
3
+ *
4
+ * The audit's verdict on benchmarks: "framework, not corpus" — runs could
5
+ * not pin WHICH tasks they ran, in what order, or which were holdout.
6
+ * This module is the missing discipline:
7
+ *
8
+ * EvalTaskSet a versioned, hash-pinned task set. The dataset hash is
9
+ * sha256 over the CANONICAL form (tasks sorted by id), so
10
+ * set identity is order-independent and content-sensitive.
11
+ * seededOrder deterministic task order from an explicit seed — the same
12
+ * seed always produces the same order (zero-dep PRNG).
13
+ * holdout gate holdout tasks may never appear in a train-side arm
14
+ * report; reports carry the split they used.
15
+ * EvalRunReport an evaluation run that NAMES its datasetHash + seed +
16
+ * split — two reports are comparable ONLY when all three
17
+ * match (comparing across datasets is the classic
18
+ * apples-to-oranges self-evaluation failure).
19
+ */
20
+ import { createHash } from 'node:crypto';
21
+ /** Canonical JSON: tasks sorted by id, key order fixed — the hash basis. */
22
+ export function canonicalTaskSet(set) {
23
+ const tasks = [...set.tasks].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
24
+ return JSON.stringify({ kind: set.kind, version: set.version, id: set.id, revision: set.revision, tasks: tasks.map((t) => ({ id: t.id, prompt: t.prompt, assertion: t.assertion, holdout: t.holdout === true })) });
25
+ }
26
+ /** sha256 over the canonical form — order-independent, content-sensitive. */
27
+ export function datasetHash(set) {
28
+ return createHash('sha256').update(canonicalTaskSet(set)).digest('hex');
29
+ }
30
+ /* ---------------- deterministic order ---------------- */
31
+ /** Zero-dep PRNG (mulberry32) — same seed, same sequence, everywhere. */
32
+ export function seededRandom(seed) {
33
+ let a = seed >>> 0;
34
+ return () => {
35
+ a = (a + 0x6d2b79f5) | 0;
36
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
37
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
38
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
39
+ };
40
+ }
41
+ /** Deterministic shuffle: same (tasks, seed) -> same order. */
42
+ export function seededOrder(items, seed) {
43
+ const rand = seededRandom(seed);
44
+ const arr = [...items];
45
+ for (let i = arr.length - 1; i > 0; i--) {
46
+ const j = Math.floor(rand() * (i + 1));
47
+ [arr[i], arr[j]] = [arr[j], arr[i]];
48
+ }
49
+ return arr;
50
+ }
51
+ /** Stable seed from a string (dataset id + explicit seed material). */
52
+ export function seedFromString(s) {
53
+ const h = createHash('sha256').update(s).digest();
54
+ return h.readUInt32BE(0);
55
+ }
56
+ export function splitSet(set) {
57
+ return {
58
+ train: set.tasks.filter((t) => !t.holdout),
59
+ holdout: set.tasks.filter((t) => t.holdout === true),
60
+ };
61
+ }
62
+ /** The discipline gate: a train-side arm must contain ZERO holdout task ids. */
63
+ export function holdoutDisciplineOK(armTaskIds, split) {
64
+ const holdoutIds = new Set(split.holdout.map((t) => t.id));
65
+ const violations = armTaskIds.filter((id) => holdoutIds.has(id));
66
+ return { ok: violations.length === 0, violations };
67
+ }
68
+ /** Two reports are comparable ONLY when datasetHash + seed + split match. */
69
+ export function reportsComparable(a, b) {
70
+ return a.datasetHash === b.datasetHash && a.seed === b.seed && a.split === b.split;
71
+ }
72
+ /** Build a report from a run (the host provides per-task pass flags). */
73
+ export function buildRunReport(set, opts) {
74
+ const split = splitSet(set);
75
+ const allowed = opts.split === 'train' ? split.train : split.holdout;
76
+ const allowedIds = new Set(allowed.map((t) => t.id));
77
+ // a report may ONLY contain tasks from its declared split
78
+ const perTask = opts.perTask.filter((r) => allowedIds.has(r.id));
79
+ if (perTask.length !== opts.perTask.length) {
80
+ throw new Error(`report contains ${opts.perTask.length - perTask.length} task(s) outside the declared '${opts.split}' split — refuse to build a mislabeled report`);
81
+ }
82
+ return {
83
+ kind: 'hmharness-eval-run',
84
+ version: 1,
85
+ datasetHash: datasetHash(set),
86
+ setId: set.id,
87
+ revision: set.revision,
88
+ seed: opts.seed,
89
+ split: opts.split,
90
+ arm: opts.arm,
91
+ perTask,
92
+ passed: perTask.filter((r) => r.pass).length,
93
+ total: perTask.length,
94
+ finishedAt: new Date().toISOString(),
95
+ };
96
+ }
97
+ /* ---------------- paired statistical test (the audit's 统计检验) ---------------- */
98
+ /** exact two-sided binomial p-value: P(X <= k) + P(X >= n-k) mirrored, n small */
99
+ function binomTwoSidedP(n, k, p = 0.5) {
100
+ const logChoose = (a, b) => {
101
+ let s = 0;
102
+ for (let i = 1; i <= b; i++)
103
+ s += Math.log(a - b + i) - Math.log(i);
104
+ return s;
105
+ };
106
+ const pmf = (i) => Math.exp(logChoose(n, i) + i * Math.log(p) + (n - i) * Math.log(1 - p));
107
+ // observed tail + opposite tail at least as extreme (classic exact method)
108
+ const pk = pmf(k);
109
+ let sum = 0;
110
+ for (let i = 0; i <= n; i++)
111
+ if (pmf(i) <= pk + 1e-12)
112
+ sum += pmf(i);
113
+ return Math.min(1, Number(sum.toFixed(6)));
114
+ }
115
+ /**
116
+ * McNemar exact test for two PAIRED arms on the same task set. Refuses
117
+ * non-comparable reports outright (datasetHash+seed+split must all match);
118
+ * significance = discordant pairs are lopsided enough that a fair coin
119
+ * would rarely produce them (exact binomial, no normal approximation —
120
+ * eval sets are small). This is the 统计检验 the audit demanded so a
121
+ * "7/10 vs 5/10" delta can never again be read as an effect.
122
+ */
123
+ export function pairedSignificance(a, b) {
124
+ if (!reportsComparable(a, b)) {
125
+ return {
126
+ comparable: false,
127
+ refusalReason: `reports are not comparable (datasetHash/seed/split must all match; got ${a.setId}@r${a.revision} seed ${a.seed} ${a.split} vs ${b.setId}@r${b.revision} seed ${b.seed} ${b.split})`,
128
+ discordant: { armOnlyPassed: 0, armBPassed: 0, agreed: 0 },
129
+ alpha: 0.05,
130
+ };
131
+ }
132
+ const bBy = new Map(b.perTask.map((r) => [r.id, r.pass]));
133
+ let armOnlyPassed = 0;
134
+ let armBPassed = 0;
135
+ let agreed = 0;
136
+ for (const t of a.perTask) {
137
+ const other = bBy.get(t.id);
138
+ if (other === undefined)
139
+ continue; // unpaired task carries no signal
140
+ if (t.pass && !other)
141
+ armOnlyPassed += 1;
142
+ else if (!t.pass && other)
143
+ armBPassed += 1;
144
+ else
145
+ agreed += 1;
146
+ }
147
+ const n = armOnlyPassed + armBPassed;
148
+ if (n === 0) {
149
+ return { comparable: true, discordant: { armOnlyPassed, armBPassed, agreed }, pValue: 1, significant: false, alpha: 0.05 };
150
+ }
151
+ const pValue = binomTwoSidedP(n, Math.min(armOnlyPassed, armBPassed));
152
+ return {
153
+ comparable: true,
154
+ discordant: { armOnlyPassed, armBPassed, agreed },
155
+ pValue,
156
+ significant: pValue < 0.05,
157
+ alpha: 0.05,
158
+ };
159
+ }
package/dist/index.d.ts CHANGED
@@ -32,3 +32,7 @@ export * from './learning-loop.js';
32
32
  export * from './governance.js';
33
33
  export * from './crowd.js';
34
34
  export * from './slice.js';
35
+ export * from './mea.js';
36
+ export * from './evalset.js';
37
+ export * from './code-world-model.js';
38
+ export * from './code-world-store.js';
package/dist/index.js CHANGED
@@ -31,3 +31,7 @@ export * from "./learning-loop.js";
31
31
  export * from "./governance.js";
32
32
  export * from "./crowd.js";
33
33
  export * from "./slice.js";
34
+ export * from "./mea.js";
35
+ export * from "./evalset.js";
36
+ export * from "./code-world-model.js";
37
+ export * from "./code-world-store.js";
package/dist/mea.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ export interface MeaStep {
2
+ id: string;
3
+ description: string;
4
+ /** structural acceptance criteria the AUDITOR checks (claim-blind) */
5
+ acceptance: string;
6
+ status: 'pending' | 'running' | 'passed' | 'failed' | 'skipped';
7
+ attempts: number;
8
+ }
9
+ export interface ManagerState {
10
+ task: string;
11
+ steps: MeaStep[];
12
+ replansUsed: number;
13
+ budget: {
14
+ maxSteps: number;
15
+ maxReplans: number;
16
+ maxAttemptsPerStep: number;
17
+ };
18
+ history: MeaHistoryEntry[];
19
+ }
20
+ export interface MeaHistoryEntry {
21
+ at: string;
22
+ kind: 'decompose' | 'execute' | 'audit' | 'replan' | 'learn';
23
+ stepId?: string;
24
+ detail: string;
25
+ /** audit verdicts carry the evidence; executor claims never do */
26
+ evidence?: {
27
+ source: 'auditor' | 'manager' | 'learner';
28
+ pass?: boolean;
29
+ reasons?: string[];
30
+ };
31
+ }
32
+ /** Fresh executor bridge: receives ONLY the step + digest (no prior transcripts). */
33
+ export type FreshExecutor = (step: MeaStep, digest: {
34
+ done: string[];
35
+ remaining: string[];
36
+ }) => Promise<{
37
+ completed: boolean;
38
+ claim: string;
39
+ }>;
40
+ /** Read-only auditor bridge: claim-blind by construction (step + criteria + workspace). */
41
+ export type ReadOnlyAuditor = (step: MeaStep) => Promise<{
42
+ pass: boolean;
43
+ reasons: string[];
44
+ }>;
45
+ /** Manager decomposition bridge: task -> steps (each with acceptance criteria). */
46
+ export type ManagerDecomposer = (task: string) => Promise<MeaStep[]>;
47
+ export interface MeaReport {
48
+ task: string;
49
+ startedAt: string;
50
+ finishedAt: string;
51
+ stepsPassed: number;
52
+ stepsFailed: number;
53
+ replansUsed: number;
54
+ verdict: 'complete' | 'partial' | 'budget-exhausted';
55
+ history: MeaHistoryEntry[];
56
+ memoryEntries: string[];
57
+ }
58
+ export interface MeaOptions {
59
+ home: string;
60
+ task: string;
61
+ decompose: ManagerDecomposer;
62
+ execute: FreshExecutor;
63
+ audit: ReadOnlyAuditor;
64
+ budget?: Partial<ManagerState['budget']>;
65
+ /** digest source for the fresh executor (defaults to steps' own states) */
66
+ digest?: () => {
67
+ done: string[];
68
+ remaining: string[];
69
+ };
70
+ }
71
+ export declare function runMeaLoop(opts: MeaOptions): Promise<MeaReport>;
72
+ /** Format for CLI display. */
73
+ export declare function formatMeaReport(r: MeaReport): string;
package/dist/mea.js ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @hmharness/cognitive - MEA long-task loop (2026-10-04 audit COG-MEA / W3)
3
+ *
4
+ * The audit's 下一核心: instead of adding MORE agent roles horizontally,
5
+ * chain the existing ones into a long-task closed loop:
6
+ *
7
+ * Manager decomposes the task into steps with acceptance criteria,
8
+ * tracks progress, adapts on failures (bounded replans)
9
+ * Fresh Executor executes ONE step with a FRESH context — it sees the
10
+ * step + a blackboard digest, never previous steps'
11
+ * transcripts (no contamination across steps)
12
+ * Read-only audits each step CLAIM-BLIND (step + criteria + workspace
13
+ * Auditor only — the executor's claim is recorded but can never
14
+ * satisfy a criterion; same wall as slice's evaluator)
15
+ * Learner after the loop, distills into memory keyed to AUDIT
16
+ * verdicts (never executor claims) + replays the WM
17
+ *
18
+ * Every role is a host bridge (testable with fakes; the CLI/agent wires
19
+ * real execution). The loop is evidence-first: each step leaves an audit
20
+ * trail entry with the auditor's verdict and replan decisions.
21
+ */
22
+ import { CognitiveMemory } from "./memory.js";
23
+ import { loadTrajectories, replayIntoWorldModel } from "./analysis.js";
24
+ /* ---------------- the loop ---------------- */
25
+ export async function runMeaLoop(opts) {
26
+ const startedAt = new Date().toISOString();
27
+ const state = {
28
+ task: opts.task,
29
+ steps: [],
30
+ replansUsed: 0,
31
+ budget: {
32
+ maxSteps: opts.budget?.maxSteps ?? 10,
33
+ maxReplans: opts.budget?.maxReplans ?? 2,
34
+ maxAttemptsPerStep: opts.budget?.maxAttemptsPerStep ?? 2,
35
+ },
36
+ history: [],
37
+ };
38
+ // 1. MANAGER: decompose
39
+ state.steps = (await opts.decompose(opts.task)).slice(0, state.budget.maxSteps);
40
+ state.history.push({ at: new Date().toISOString(), kind: 'decompose', detail: `${state.steps.length} steps decomposed (cap ${state.budget.maxSteps})`, evidence: { source: 'manager' } });
41
+ const digest = opts.digest ?? (() => ({
42
+ done: state.steps.filter((s) => s.status === 'passed').map((s) => s.description),
43
+ remaining: state.steps.filter((s) => s.status === 'pending').map((s) => s.description),
44
+ }));
45
+ // 2. STEP LOOP: fresh executor -> read-only auditor per step
46
+ for (const step of state.steps) {
47
+ if (step.status !== 'pending')
48
+ continue;
49
+ step.status = 'running';
50
+ while (step.attempts < state.budget.maxAttemptsPerStep) {
51
+ step.attempts += 1;
52
+ // FRESH EXECUTOR: fresh context — only this step + digest
53
+ const exec = await opts.execute(step, digest()).catch((e) => ({ completed: false, claim: 'executor threw: ' + String(e).slice(0, 100) }));
54
+ state.history.push({ at: new Date().toISOString(), kind: 'execute', stepId: step.id, detail: `attempt ${step.attempts}: claim="${exec.claim.slice(0, 120)}"` });
55
+ // READ-ONLY AUDITOR: claim-blind — the claim is NOT passed in
56
+ const verdict = await opts.audit(step).catch((e) => ({ pass: false, reasons: ['auditor threw: ' + String(e).slice(0, 80)] }));
57
+ state.history.push({ at: new Date().toISOString(), kind: 'audit', stepId: step.id, detail: verdict.pass ? 'PASS' : `FAIL: ${verdict.reasons.join('; ').slice(0, 120)}`, evidence: { source: 'auditor', pass: verdict.pass, reasons: verdict.reasons } });
58
+ if (verdict.pass) {
59
+ step.status = 'passed';
60
+ break;
61
+ }
62
+ }
63
+ if (step.status === 'running') {
64
+ step.status = 'failed';
65
+ // MANAGER ADAPTATION: bounded replan — retry the failed step once as a
66
+ // revised child step before giving up (real managers re-decompose; the
67
+ // contract here is the BOUND, hosts may implement smarter adaptation)
68
+ if (state.replansUsed < state.budget.maxReplans) {
69
+ state.replansUsed += 1;
70
+ const revised = { id: `${step.id}-r${state.replansUsed}`, description: `revise: ${step.description}`, acceptance: step.acceptance, status: 'pending', attempts: 0 };
71
+ state.steps.splice(state.steps.indexOf(step) + 1, 0, revised);
72
+ state.history.push({ at: new Date().toISOString(), kind: 'replan', stepId: step.id, detail: `replan #${state.replansUsed}: revised step ${revised.id} inserted`, evidence: { source: 'manager' } });
73
+ }
74
+ }
75
+ }
76
+ const passed = state.steps.filter((s) => s.status === 'passed').length;
77
+ const failed = state.steps.filter((s) => s.status === 'failed').length;
78
+ const verdict = failed === 0 ? 'complete' : passed > 0 ? 'partial' : 'budget-exhausted';
79
+ // 3. LEARNER: memory keyed to AUDIT verdicts (never executor claims)
80
+ const mem = new CognitiveMemory(opts.home);
81
+ await mem.load();
82
+ const memoryEntries = [];
83
+ const entry = await mem.write({
84
+ layer: 'episodic',
85
+ content: `MEA ${verdict}: ${opts.task.slice(0, 100)} — ${passed} passed / ${failed} failed / ${state.replansUsed} replans`,
86
+ payload: { verdict, passed, failed, replans: state.replansUsed, history: state.history.filter((h) => h.kind === 'audit').map((h) => ({ step: h.stepId, pass: h.evidence?.pass })) },
87
+ source: 'mea-loop',
88
+ provenance: `mea:${startedAt}`,
89
+ confidence: verdict === 'complete' ? 0.9 : 0.6,
90
+ environment: 'terminal',
91
+ session: 'mea',
92
+ tags: ['mea', verdict],
93
+ });
94
+ memoryEntries.push(entry.id);
95
+ state.history.push({ at: new Date().toISOString(), kind: 'learn', detail: `memory entry ${entry.id} keyed to ${verdict} (audit verdicts, not claims)`, evidence: { source: 'learner' } });
96
+ // WM replay from whatever trajectories the executors left
97
+ const trajectories = await loadTrajectories(opts.home, 50);
98
+ const wm = replayIntoWorldModel(trajectories, 'terminal');
99
+ return {
100
+ task: opts.task,
101
+ startedAt,
102
+ finishedAt: new Date().toISOString(),
103
+ stepsPassed: passed,
104
+ stepsFailed: failed,
105
+ replansUsed: state.replansUsed,
106
+ verdict,
107
+ history: state.history,
108
+ memoryEntries,
109
+ };
110
+ }
111
+ /** Format for CLI display. */
112
+ export function formatMeaReport(r) {
113
+ const lines = [`MEA 闭环 · ${r.task.slice(0, 60)}`, ` 裁决: ${r.verdict}(${r.stepsPassed} 过 / ${r.stepsFailed} 败 / ${r.replansUsed} 重规划)`];
114
+ for (const h of r.history) {
115
+ if (h.kind === 'audit')
116
+ lines.push(` ${h.evidence?.pass ? '✓' : '✗'} ${h.kind.padEnd(9)} ${h.stepId ?? ''} ${h.detail.slice(0, 80)}`);
117
+ else if (h.kind !== 'execute')
118
+ lines.push(` · ${h.kind.padEnd(9)} ${h.detail.slice(0, 90)}`);
119
+ }
120
+ lines.push(` 学步键定审计裁决(executor 自评仅记录); WM 重放完成`);
121
+ return lines.join('\n');
122
+ }
@@ -15,6 +15,13 @@ export interface SandboxOptions {
15
15
  maxOldGenerationSizeMb?: number;
16
16
  maxYoungGenerationSizeMb?: number;
17
17
  }
18
+ /**
19
+ * HONEST threat model: escape vectors the worker CANNOT block today (they
20
+ * need a per-worker permission model, which Node does not offer per
21
+ * worker). The red-team test asserts every still-escaping probe is on this
22
+ * list, and every vector NOT on it is blocked — a new silent hole fails CI.
23
+ */
24
+ export declare const SANDBOX_BYPASS_VECTORS: readonly string[];
18
25
  /** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
19
26
  * are coarse-grained (composing workspace variables), so per-eval spawn
20
27
  * overhead (~10-30ms) is acceptable for real isolation each time. */
@@ -22,22 +22,40 @@ import { Worker } from 'node:worker_threads';
22
22
  /** The worker bootstrap source. Runs as CommonJS, receives {code, vars, meta}
23
23
  * through workerData (structured-cloned at spawn), executes the code as an
24
24
  * async function body with a frozen ctx, and posts the result back.
25
- * Shadows the dangerous globals at function-constructor scope so casual
26
- * access fails loudly. */
25
+ * RED-TEAM HARDENING (round 32, executable-payload driven): after the
26
+ * bootstrap captures parentPort, the escape-reachable globals are STRIPPED
27
+ * from the worker's globalThis — globalThis.process (kills the R1/R4
28
+ * reach-and-kill vectors), Worker/fetch/WebSocket (network + thread
29
+ * spawn). What remains impossible to block without a per-worker
30
+ * permission model is declared in SANDBOX_BYPASS_VECTORS below — pinned
31
+ * by the red-team test so a silent hole can never masquerade as covered. */
27
32
  const WORKER_SOURCE = `
28
33
  const { parentPort, workerData } = require('node:worker_threads');
29
34
  (async () => {
35
+ // hardening pass: strip escape globals BEFORE evaluating any user code
36
+ try { delete globalThis.process; } catch { /* non-configurable: shadow instead below */ }
37
+ try { globalThis.Worker = undefined; } catch { }
38
+ try { globalThis.fetch = undefined; } catch { }
39
+ try { globalThis.WebSocket = undefined; } catch { }
30
40
  const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
31
41
  try {
32
- const process = undefined, require = undefined;
33
- const fn = new Function('ctx', 'process', 'require', '"use strict";return (async()=>{' + workerData.code + '})();');
34
- const value = await fn(ctx, undefined, undefined);
42
+ const fn = new Function('ctx', 'process', 'require', 'fetch', 'Worker', 'WebSocket', '"use strict";return (async()=>{' + workerData.code + '})();');
43
+ const value = await fn(ctx, undefined, undefined, undefined, undefined, undefined);
35
44
  parentPort.postMessage({ ok: true, value });
36
45
  } catch (err) {
37
46
  parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
38
47
  }
39
48
  })();
40
49
  `;
50
+ /**
51
+ * HONEST threat model: escape vectors the worker CANNOT block today (they
52
+ * need a per-worker permission model, which Node does not offer per
53
+ * worker). The red-team test asserts every still-escaping probe is on this
54
+ * list, and every vector NOT on it is blocked — a new silent hole fails CI.
55
+ */
56
+ export const SANDBOX_BYPASS_VECTORS = [
57
+ 'dynamic-import', // import('node:*') inside eval code reaches Node modules
58
+ ];
41
59
  /** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
42
60
  * are coarse-grained (composing workspace variables), so per-eval spawn
43
61
  * overhead (~10-30ms) is acceptable for real isolation each time. */
@@ -0,0 +1,48 @@
1
+ import { type Transition } from './world-model.js';
2
+ export interface CausalLink {
3
+ actionType: string;
4
+ stateKey: string;
5
+ /** observational lift: P(delta on key | action) − P(delta on key | no action) */
6
+ lift: number;
7
+ /** transitions where the action ran and the key changed (within lag) */
8
+ support: number;
9
+ /** measured lag in steps (0 = same transition, 1 = next transition) */
10
+ lag: 0 | 1;
11
+ /** "observational" — stamped on every link: no intervention was performed */
12
+ evidence: 'observational';
13
+ }
14
+ /**
15
+ * Mine causal candidates from the transition journal. Bookkeeping is
16
+ * class-conditional: for every (actionType, stateKey, lag) we count
17
+ * P(key changes | action ran) against P(key changes | action did NOT run)
18
+ * over the same lag window — a link survives only with positive lift and
19
+ * enough support. Temporal precedence is structural: the delta window
20
+ * starts AT the action (lag 0) or one step after (lag 1).
21
+ */
22
+ export declare function mineCausalLinks(transitions: Transition[], opts?: {
23
+ minSupport?: number;
24
+ minLift?: number;
25
+ }): CausalLink[];
26
+ export interface CounterfactualReport {
27
+ /** the intervention: replay WITHOUT this action type */
28
+ withoutActionType: string;
29
+ /** honest epistemic label — this is what the BELIEF TABLE would have learned */
30
+ nature: 'model-based-extrapolation';
31
+ /** beliefs present in reality but ABSENT in the counterfactual world */
32
+ lostBeliefs: Array<{
33
+ actionType: string;
34
+ confidence: number;
35
+ }>;
36
+ /** the real vs counterfactual belief counts */
37
+ realBeliefs: number;
38
+ counterfactualBeliefs: number;
39
+ /** transitions that carried the action (excluded from the replay) */
40
+ excludedTransitions: number;
41
+ }
42
+ /**
43
+ * Replay the history WITHOUT one action type and diff the learned world
44
+ * against reality. NOT an environment claim: it answers "what would the
45
+ * harness have believed" — the honest scope of observational
46
+ * counterfactuals. Interventions on the environment belong to exploration.
47
+ */
48
+ export declare function counterfactualWithout(transitions: Transition[], withoutActionType: string, environmentId?: string): CounterfactualReport;
@@ -0,0 +1,122 @@
1
+ import { stateDiff, WorldModel } from "./world-model.js";
2
+ function deltaKeys(t) {
3
+ const before = t.stateBefore.variables ?? t.stateBefore;
4
+ const after = t.stateAfter ? (t.stateAfter.variables ?? t.stateAfter) : t.observation.state;
5
+ const d = stateDiff(before, after);
6
+ return [...d.added, ...d.removed, ...d.changed.map((c) => c.key)];
7
+ }
8
+ /**
9
+ * Mine causal candidates from the transition journal. Bookkeeping is
10
+ * class-conditional: for every (actionType, stateKey, lag) we count
11
+ * P(key changes | action ran) against P(key changes | action did NOT run)
12
+ * over the same lag window — a link survives only with positive lift and
13
+ * enough support. Temporal precedence is structural: the delta window
14
+ * starts AT the action (lag 0) or one step after (lag 1).
15
+ */
16
+ export function mineCausalLinks(transitions, opts = {}) {
17
+ const minSupport = opts.minSupport ?? 2;
18
+ const minLift = opts.minLift ?? 0.2;
19
+ const chronological = [...transitions].sort((a, b) => String(a.observation.timestamp).localeCompare(String(b.observation.timestamp)));
20
+ // runs per action type
21
+ const runs = new Map();
22
+ for (const t of chronological)
23
+ runs.set(t.action.type, (runs.get(t.action.type) ?? 0) + 1);
24
+ // key-change counters per lag window
25
+ // with: key changed in the window of a transition whose ACTION is `type`
26
+ // total: key changed in that window regardless of action
27
+ const withAction = new Map(); // `${type}|${key}|${lag}`
28
+ const totalAtLag = new Map(); // `${key}|${lag}`
29
+ const windows = [];
30
+ for (let i = 0; i < chronological.length; i++) {
31
+ const t = chronological[i];
32
+ windows.push({ keys: deltaKeys(t), lag: 0, type: t.action.type });
33
+ const next = chronological[i + 1];
34
+ if (next)
35
+ windows.push({ keys: deltaKeys(next), lag: 1, type: t.action.type });
36
+ }
37
+ for (const w of windows) {
38
+ for (const key of new Set(w.keys)) {
39
+ const wk = `${w.type}|${key}|${w.lag}`;
40
+ withAction.set(wk, (withAction.get(wk) ?? 0) + 1);
41
+ const tk = `${key}|${w.lag}`;
42
+ totalAtLag.set(tk, (totalAtLag.get(tk) ?? 0) + 1);
43
+ }
44
+ }
45
+ // Occam suppression for lag-1 links: when the immediate successor action
46
+ // explains the same key at lag 0 with a rate >= this link's lag-1 rate,
47
+ // the shorter path wins (the bystander must not harvest the successor's
48
+ // work — caught by the red-team-style test where login preceded deploy).
49
+ const pWithOf = (type, key, lag) => {
50
+ const w = withAction.get(`${type}|${key}|${lag}`) ?? 0;
51
+ return w / Math.max(1, runs.get(type) ?? 1);
52
+ };
53
+ const links = [];
54
+ for (const [wk, withCount] of withAction) {
55
+ const [type, key, lagStr] = wk.split('|');
56
+ const lag = Number(lagStr);
57
+ const typeRuns = runs.get(type) ?? 0;
58
+ const windowCount = lag === 0 ? chronological.length : Math.max(0, chronological.length - 1);
59
+ const pWith = withCount / Math.max(1, typeRuns);
60
+ const withoutCount = Math.max(0, (totalAtLag.get(`${key}|${lag}`) ?? 0) - withCount);
61
+ const noActionWindows = Math.max(1, windowCount - typeRuns);
62
+ const pWithout = withoutCount / noActionWindows;
63
+ const lift = Number((pWith - pWithout).toFixed(3));
64
+ if (withCount < minSupport || lift < minLift)
65
+ continue;
66
+ if (lag === 1) {
67
+ let suppressed = false;
68
+ for (const [sk, sw] of withAction) {
69
+ const [sType, sKey, sLagStr] = sk.split('|');
70
+ if (sLagStr !== '0' || sKey !== key)
71
+ continue;
72
+ const sP = sw / Math.max(1, runs.get(sType) ?? 1);
73
+ if (sP >= pWith) {
74
+ suppressed = true;
75
+ break;
76
+ }
77
+ }
78
+ if (suppressed)
79
+ continue;
80
+ }
81
+ // same (type,key) may appear at both lags — keep the stronger one
82
+ const prev = links.find((l) => l.actionType === type && l.stateKey === key);
83
+ if (prev) {
84
+ if (lift > prev.lift) {
85
+ prev.lift = lift;
86
+ prev.support = withCount;
87
+ prev.lag = lag;
88
+ }
89
+ continue;
90
+ }
91
+ void pWithOf;
92
+ links.push({ actionType: type, stateKey: key, lift, support: withCount, lag, evidence: 'observational' });
93
+ }
94
+ return links.sort((a, b) => b.lift - a.lift || b.support - a.support);
95
+ }
96
+ /**
97
+ * Replay the history WITHOUT one action type and diff the learned world
98
+ * against reality. NOT an environment claim: it answers "what would the
99
+ * harness have believed" — the honest scope of observational
100
+ * counterfactuals. Interventions on the environment belong to exploration.
101
+ */
102
+ export function counterfactualWithout(transitions, withoutActionType, environmentId = 'terminal') {
103
+ const real = new WorldModel(environmentId);
104
+ for (const t of transitions)
105
+ real.update(t);
106
+ const kept = transitions.filter((t) => t.action.type !== withoutActionType);
107
+ const cf = new WorldModel(environmentId);
108
+ for (const t of kept)
109
+ cf.update(t);
110
+ const cfTypes = new Set(cf.worldState.beliefs.filter((b) => b.id.startsWith('act:')).map((b) => b.id.slice(4)));
111
+ const lostBeliefs = real.worldState.beliefs
112
+ .filter((b) => b.id.startsWith('act:') && !cfTypes.has(b.id.slice(4)))
113
+ .map((b) => ({ actionType: b.id.slice(4), confidence: b.confidence }));
114
+ return {
115
+ withoutActionType,
116
+ nature: 'model-based-extrapolation',
117
+ lostBeliefs,
118
+ realBeliefs: real.worldState.beliefs.filter((b) => b.id.startsWith('act:')).length,
119
+ counterfactualBeliefs: cf.worldState.beliefs.filter((b) => b.id.startsWith('act:')).length,
120
+ excludedTransitions: transitions.filter((t) => t.action.type === withoutActionType).length,
121
+ };
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.23.21",
3
+ "version": "0.23.23",
4
4
  "description": "hmharness Cognitive OS core: Environment protocol, World Model, Goal system, Exploration, RLM runtime, five-layer memory, Skill Compiler, Continual Learning control plane, Evolution 2.0 governance, Multi-Agent topology, Transfer lab and GeneralBench schema. Cognitive strategy layer per the HMH Cognitive OS blueprint (2026-09).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -26,6 +26,6 @@
26
26
  "node": ">=22"
27
27
  },
28
28
  "dependencies": {
29
- "@hmharness/kernel": "0.23.21"
29
+ "@hmharness/kernel": "0.23.23"
30
30
  }
31
31
  }