@hmharness/cognitive 0.23.21 → 0.23.22
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/code-world-model.d.ts +96 -0
- package/dist/code-world-model.js +127 -0
- package/dist/evalset.d.ts +98 -0
- package/dist/evalset.js +159 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/mea.d.ts +73 -0
- package/dist/mea.js +122 -0
- package/dist/rlm-sandbox.d.ts +7 -0
- package/dist/rlm-sandbox.js +23 -5
- package/dist/wm-causal.d.ts +48 -0
- package/dist/wm-causal.js +122 -0
- package/package.json +2 -2
|
@@ -0,0 +1,96 @@
|
|
|
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
|
+
export declare class CodeWorldModel {
|
|
52
|
+
private entities;
|
|
53
|
+
private relations;
|
|
54
|
+
/** latest diagnostics per uri (sensors push; overwrite per uri) */
|
|
55
|
+
private diagnostics;
|
|
56
|
+
private latestBuild;
|
|
57
|
+
private runtimeFacts;
|
|
58
|
+
private openPredictions;
|
|
59
|
+
/** Ingest sensors' output — idempotent per entity id; diagnostics replace per uri. */
|
|
60
|
+
ingest(input: {
|
|
61
|
+
entities?: CodeEntity[];
|
|
62
|
+
relations?: SymbolRelation[];
|
|
63
|
+
diagnostics?: CodeDiagnostic[];
|
|
64
|
+
build?: BuildFact;
|
|
65
|
+
runtime?: RuntimeFact;
|
|
66
|
+
}): void;
|
|
67
|
+
get entityCount(): number;
|
|
68
|
+
get relationCount(): number;
|
|
69
|
+
get diagnosticCount(): number;
|
|
70
|
+
get build(): BuildFact | null;
|
|
71
|
+
entity(id: string): CodeEntity | undefined;
|
|
72
|
+
relationsOf(entityId: string): SymbolRelation[];
|
|
73
|
+
diagnosticsFor(uri: string): CodeDiagnostic[];
|
|
74
|
+
/**
|
|
75
|
+
* PREDICT an edit's blast radius from the relation graph: renaming or
|
|
76
|
+
* deleting entity X touches X itself plus every relation that names X
|
|
77
|
+
* (callers, referrers, importers). newDiagnosticEstimate is the count of
|
|
78
|
+
* existing diagnostics on the touched files — the honest floor, not a
|
|
79
|
+
* guess about new ones.
|
|
80
|
+
*/
|
|
81
|
+
predictEditDelta(edit: {
|
|
82
|
+
editKind: 'rename' | 'delete' | 'modify';
|
|
83
|
+
target: string;
|
|
84
|
+
}): EditDelta;
|
|
85
|
+
/**
|
|
86
|
+
* Record what ACTUALLY happened and settle the open prediction. The
|
|
87
|
+
* actual may legally differ — surprise (missed) is exactly the signal
|
|
88
|
+
* that the graph is incomplete.
|
|
89
|
+
*/
|
|
90
|
+
recordEditDelta(target: string, actual: {
|
|
91
|
+
touchedEntities: string[];
|
|
92
|
+
touchedRelations: string[];
|
|
93
|
+
}): PredictionError | null;
|
|
94
|
+
/** Snapshot hash — for holdout discipline and drift detection. */
|
|
95
|
+
stateHash(): string;
|
|
96
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
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
|
+
/* ---------------- the model ---------------- */
|
|
18
|
+
export class CodeWorldModel {
|
|
19
|
+
entities = new Map();
|
|
20
|
+
relations = [];
|
|
21
|
+
/** latest diagnostics per uri (sensors push; overwrite per uri) */
|
|
22
|
+
diagnostics = new Map();
|
|
23
|
+
latestBuild = null;
|
|
24
|
+
runtimeFacts = [];
|
|
25
|
+
openPredictions = new Map();
|
|
26
|
+
/** Ingest sensors' output — idempotent per entity id; diagnostics replace per uri. */
|
|
27
|
+
ingest(input) {
|
|
28
|
+
for (const e of input.entities ?? [])
|
|
29
|
+
this.entities.set(e.id, e);
|
|
30
|
+
this.relations.push(...(input.relations ?? []));
|
|
31
|
+
for (const d of input.diagnostics ?? []) {
|
|
32
|
+
const cur = this.diagnostics.get(d.uri) ?? [];
|
|
33
|
+
const next = cur.filter((x) => x.message !== d.message || x.source !== d.source);
|
|
34
|
+
next.push(d);
|
|
35
|
+
this.diagnostics.set(d.uri, next);
|
|
36
|
+
}
|
|
37
|
+
if (input.build)
|
|
38
|
+
this.latestBuild = input.build;
|
|
39
|
+
if (input.runtime)
|
|
40
|
+
this.runtimeFacts.push(input.runtime);
|
|
41
|
+
}
|
|
42
|
+
get entityCount() {
|
|
43
|
+
return this.entities.size;
|
|
44
|
+
}
|
|
45
|
+
get relationCount() {
|
|
46
|
+
return this.relations.length;
|
|
47
|
+
}
|
|
48
|
+
get diagnosticCount() {
|
|
49
|
+
return [...this.diagnostics.values()].reduce((s, l) => s + l.length, 0);
|
|
50
|
+
}
|
|
51
|
+
get build() {
|
|
52
|
+
return this.latestBuild;
|
|
53
|
+
}
|
|
54
|
+
entity(id) {
|
|
55
|
+
return this.entities.get(id);
|
|
56
|
+
}
|
|
57
|
+
relationsOf(entityId) {
|
|
58
|
+
return this.relations.filter((r) => r.from === entityId || r.to === entityId);
|
|
59
|
+
}
|
|
60
|
+
diagnosticsFor(uri) {
|
|
61
|
+
return [...(this.diagnostics.get(uri) ?? [])];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* PREDICT an edit's blast radius from the relation graph: renaming or
|
|
65
|
+
* deleting entity X touches X itself plus every relation that names X
|
|
66
|
+
* (callers, referrers, importers). newDiagnosticEstimate is the count of
|
|
67
|
+
* existing diagnostics on the touched files — the honest floor, not a
|
|
68
|
+
* guess about new ones.
|
|
69
|
+
*/
|
|
70
|
+
predictEditDelta(edit) {
|
|
71
|
+
const touchedEntities = new Set([edit.target]);
|
|
72
|
+
const touchedRelations = new Set();
|
|
73
|
+
for (const r of this.relations) {
|
|
74
|
+
if (r.from === edit.target || r.to === edit.target) {
|
|
75
|
+
touchedRelations.add(`${r.from}->${r.to}:${r.kind}`);
|
|
76
|
+
touchedEntities.add(r.from);
|
|
77
|
+
touchedEntities.add(r.to);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const uris = new Set([...touchedEntities].map((id) => id.split('#')[0]));
|
|
81
|
+
let diagFloor = 0;
|
|
82
|
+
for (const uri of uris)
|
|
83
|
+
diagFloor += (this.diagnostics.get(uri) ?? []).length;
|
|
84
|
+
const predicted = {
|
|
85
|
+
editKind: edit.editKind,
|
|
86
|
+
target: edit.target,
|
|
87
|
+
touchedEntities: [...touchedEntities],
|
|
88
|
+
touchedRelations: [...touchedRelations],
|
|
89
|
+
newDiagnosticEstimate: diagFloor,
|
|
90
|
+
};
|
|
91
|
+
this.openPredictions.set(edit.target, { predicted, at: new Date().toISOString() });
|
|
92
|
+
return predicted;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Record what ACTUALLY happened and settle the open prediction. The
|
|
96
|
+
* actual may legally differ — surprise (missed) is exactly the signal
|
|
97
|
+
* that the graph is incomplete.
|
|
98
|
+
*/
|
|
99
|
+
recordEditDelta(target, actual) {
|
|
100
|
+
const open = this.openPredictions.get(target);
|
|
101
|
+
if (!open)
|
|
102
|
+
return null;
|
|
103
|
+
this.openPredictions.delete(target);
|
|
104
|
+
const p = new Set([...open.predicted.touchedEntities, ...open.predicted.touchedRelations]);
|
|
105
|
+
const a = new Set([...actual.touchedEntities, ...actual.touchedRelations]);
|
|
106
|
+
const union = new Set([...p, ...a]);
|
|
107
|
+
const inter = [...p].filter((x) => a.has(x));
|
|
108
|
+
const missed = [...a].filter((x) => !p.has(x));
|
|
109
|
+
const spurious = [...p].filter((x) => !a.has(x));
|
|
110
|
+
return {
|
|
111
|
+
jaccard: union.size ? Number((inter.length / union.size).toFixed(3)) : 1,
|
|
112
|
+
precision: a.size ? Number((inter.length / a.size).toFixed(3)) : 1,
|
|
113
|
+
recall: p.size ? Number((inter.length / p.size).toFixed(3)) : 1,
|
|
114
|
+
missed,
|
|
115
|
+
spurious,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Snapshot hash — for holdout discipline and drift detection. */
|
|
119
|
+
stateHash() {
|
|
120
|
+
return stableHash({
|
|
121
|
+
entities: [...this.entities.keys()].sort(),
|
|
122
|
+
relations: this.relations.map((r) => `${r.from}->${r.to}:${r.kind}`).sort(),
|
|
123
|
+
diagnosticUris: [...this.diagnostics.keys()].sort(),
|
|
124
|
+
build: this.latestBuild,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -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;
|
package/dist/evalset.js
ADDED
|
@@ -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
package/dist/index.js
CHANGED
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
|
+
}
|
package/dist/rlm-sandbox.d.ts
CHANGED
|
@@ -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. */
|
package/dist/rlm-sandbox.js
CHANGED
|
@@ -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
|
-
*
|
|
26
|
-
*
|
|
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
|
|
33
|
-
const
|
|
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.
|
|
3
|
+
"version": "0.23.22",
|
|
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.
|
|
29
|
+
"@hmharness/kernel": "0.23.22"
|
|
30
30
|
}
|
|
31
31
|
}
|