@hmharness/cognitive 0.23.15 → 0.23.17
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/analysis.d.ts +6 -0
- package/dist/analysis.js +22 -6
- package/dist/memory.d.ts +5 -1
- package/dist/memory.js +19 -6
- package/dist/rlm-sandbox.js +13 -13
- package/dist/skill-compiler.d.ts +34 -0
- package/dist/skill-compiler.js +65 -0
- package/dist/slice.js +2 -1
- package/dist/world-model.d.ts +44 -0
- package/dist/world-model.js +74 -0
- package/package.json +31 -31
package/dist/analysis.d.ts
CHANGED
|
@@ -19,6 +19,12 @@ export interface WorldModelSummary {
|
|
|
19
19
|
resolved: number;
|
|
20
20
|
meanError: number | undefined;
|
|
21
21
|
};
|
|
22
|
+
/** WM 2.0: structured delta-prediction accuracy (shape predictions) */
|
|
23
|
+
deltaAccuracy: {
|
|
24
|
+
checked: number;
|
|
25
|
+
hits: number;
|
|
26
|
+
accuracy: number | undefined;
|
|
27
|
+
};
|
|
22
28
|
trajectoriesReplayed: number;
|
|
23
29
|
stepsReplayed: number;
|
|
24
30
|
}
|
package/dist/analysis.js
CHANGED
|
@@ -75,6 +75,7 @@ export function summarizeWorldModel(wm, trajectoriesReplayed, stepsReplayed) {
|
|
|
75
75
|
.sort((a, b) => b.evidenceCount - a.evidenceCount),
|
|
76
76
|
plannerGate: wm.plannerConfidence(0.6),
|
|
77
77
|
calibration: wm.calibration(),
|
|
78
|
+
deltaAccuracy: wm.deltaAccuracy(),
|
|
78
79
|
trajectoriesReplayed,
|
|
79
80
|
stepsReplayed,
|
|
80
81
|
};
|
|
@@ -350,11 +351,26 @@ export async function skillCandidatesFromHistory(home, opts) {
|
|
|
350
351
|
const compiler = new SkillCompiler();
|
|
351
352
|
const trajectories = await loadTrajectories(home);
|
|
352
353
|
const candidates = await compiler.compile(trajectories, opts);
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
354
|
+
// W10 wiring: n-gram workflow candidates join the SAME pool — they flow
|
|
355
|
+
// into the evolve bench pipeline (promotion gates) like any candidate;
|
|
356
|
+
// nothing here promotes anything (evaluator independence)
|
|
357
|
+
const { mineWorkflows } = await import("./skill-compiler.js");
|
|
358
|
+
const workflows = mineWorkflows(trajectories, { minSupport: opts?.minRepeat ?? 2 });
|
|
359
|
+
const fromWorkflows = workflows.map((w) => ({
|
|
360
|
+
id: `wf-${w.steps.join('_')}`,
|
|
361
|
+
name: `workflow: ${w.steps.join(' → ')} (${w.environmentId})`,
|
|
362
|
+
procedure: w.steps,
|
|
363
|
+
evidenceTrajectories: w.support,
|
|
364
|
+
status: 'candidate',
|
|
359
365
|
}));
|
|
366
|
+
return [
|
|
367
|
+
...candidates.map((c) => ({
|
|
368
|
+
id: c.id,
|
|
369
|
+
name: c.name,
|
|
370
|
+
procedure: c.procedure.map((s) => s.ref),
|
|
371
|
+
evidenceTrajectories: c.evidence.length,
|
|
372
|
+
status: c.status,
|
|
373
|
+
})),
|
|
374
|
+
...fromWorkflows,
|
|
375
|
+
];
|
|
360
376
|
}
|
package/dist/memory.d.ts
CHANGED
|
@@ -37,7 +37,11 @@ export declare class CognitiveMemory {
|
|
|
37
37
|
id?: string;
|
|
38
38
|
timestamp?: string;
|
|
39
39
|
}): Promise<MemoryEntry>;
|
|
40
|
-
/** MEM-006 hybrid retrieval
|
|
40
|
+
/** MEM-006 hybrid retrieval (Memory 2.0: scored lexical match): query
|
|
41
|
+
* terms score individually over content+tags (partial credit, no hard
|
|
42
|
+
* AND-substring wall — "hvigor build fail" must surface "hvigor 构建失败"
|
|
43
|
+
* and a note that only mentions build), combined with confidence and
|
|
44
|
+
* recency. Hard filters stay hard: layer/environment/tags. */
|
|
41
45
|
retrieve(query: {
|
|
42
46
|
layer?: MemoryLayer;
|
|
43
47
|
tags?: string[];
|
package/dist/memory.js
CHANGED
|
@@ -65,7 +65,11 @@ export class CognitiveMemory {
|
|
|
65
65
|
await this.persist();
|
|
66
66
|
return full;
|
|
67
67
|
}
|
|
68
|
-
/** MEM-006 hybrid retrieval
|
|
68
|
+
/** MEM-006 hybrid retrieval (Memory 2.0: scored lexical match): query
|
|
69
|
+
* terms score individually over content+tags (partial credit, no hard
|
|
70
|
+
* AND-substring wall — "hvigor build fail" must surface "hvigor 构建失败"
|
|
71
|
+
* and a note that only mentions build), combined with confidence and
|
|
72
|
+
* recency. Hard filters stay hard: layer/environment/tags. */
|
|
69
73
|
retrieve(query) {
|
|
70
74
|
let pool = this.longTerm.filter((e) => !e.supersededBy);
|
|
71
75
|
if (query.layer)
|
|
@@ -76,13 +80,22 @@ export class CognitiveMemory {
|
|
|
76
80
|
const want = new Set(query.tags);
|
|
77
81
|
pool = pool.filter((e) => (e.tags ?? []).some((t) => want.has(t)));
|
|
78
82
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
+
const terms = (query.text ?? '').toLowerCase().split(/[\s,,;;]+/).filter((t) => t.length >= 2);
|
|
84
|
+
const lexicalScore = (e) => {
|
|
85
|
+
if (terms.length === 0)
|
|
86
|
+
return 0;
|
|
87
|
+
const hay = (e.content + ' ' + (e.tags ?? []).join(' ')).toLowerCase();
|
|
88
|
+
let hits = 0;
|
|
89
|
+
for (const t of terms)
|
|
90
|
+
if (hay.includes(t))
|
|
91
|
+
hits += 1;
|
|
92
|
+
return hits / terms.length;
|
|
93
|
+
};
|
|
94
|
+
if (terms.length > 0)
|
|
95
|
+
pool = pool.filter((e) => lexicalScore(e) > 0);
|
|
83
96
|
const scored = pool.map((e) => ({
|
|
84
97
|
e,
|
|
85
|
-
score: e.confidence * 0.
|
|
98
|
+
score: e.confidence * 0.4 + recencyScore(e.timestamp) * 0.2 + lexicalScore(e) * 0.4,
|
|
86
99
|
}));
|
|
87
100
|
scored.sort((a, b) => b.score - a.score);
|
|
88
101
|
return scored.slice(0, query.limit ?? 10).map((s) => s.e);
|
package/dist/rlm-sandbox.js
CHANGED
|
@@ -24,19 +24,19 @@ import { Worker } from 'node:worker_threads';
|
|
|
24
24
|
* async function body with a frozen ctx, and posts the result back.
|
|
25
25
|
* Shadows the dangerous globals at function-constructor scope so casual
|
|
26
26
|
* access fails loudly. */
|
|
27
|
-
const WORKER_SOURCE = `
|
|
28
|
-
const { parentPort, workerData } = require('node:worker_threads');
|
|
29
|
-
(async () => {
|
|
30
|
-
const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
|
|
31
|
-
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);
|
|
35
|
-
parentPort.postMessage({ ok: true, value });
|
|
36
|
-
} catch (err) {
|
|
37
|
-
parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
|
|
38
|
-
}
|
|
39
|
-
})();
|
|
27
|
+
const WORKER_SOURCE = `
|
|
28
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
29
|
+
(async () => {
|
|
30
|
+
const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
|
|
31
|
+
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);
|
|
35
|
+
parentPort.postMessage({ ok: true, value });
|
|
36
|
+
} catch (err) {
|
|
37
|
+
parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
40
|
`;
|
|
41
41
|
/** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
|
|
42
42
|
* are coarse-grained (composing workspace variables), so per-eval spawn
|
package/dist/skill-compiler.d.ts
CHANGED
|
@@ -79,3 +79,37 @@ export declare class SkillCompiler {
|
|
|
79
79
|
/** SK-008. Rollback is always allowed. */
|
|
80
80
|
rollback(skillId: string): Promise<void>;
|
|
81
81
|
}
|
|
82
|
+
export interface WorkflowCandidate {
|
|
83
|
+
/** the consecutive action-type n-gram (the workflow body) */
|
|
84
|
+
steps: string[];
|
|
85
|
+
/** distinct successful trajectories containing the n-gram */
|
|
86
|
+
support: number;
|
|
87
|
+
trajectoryIds: string[];
|
|
88
|
+
/** environment of the supporting episodes */
|
|
89
|
+
environmentId: string;
|
|
90
|
+
}
|
|
91
|
+
/** Mine frequent consecutive action n-grams (n within [nMin,nMax]) across
|
|
92
|
+
* SUCCESSFUL trajectories, keeping only MAXIMAL ones (an n-gram fully
|
|
93
|
+
* contained in a longer supported n-gram of the same episodes adds nothing).
|
|
94
|
+
* This generalizes compile()'s exact full-sequence matching: a workflow
|
|
95
|
+
* survives when one episode has an extra step somewhere. */
|
|
96
|
+
export declare function mineWorkflows(experiences: CognitiveTrajectory[], opts?: {
|
|
97
|
+
minSupport?: number;
|
|
98
|
+
nMin?: number;
|
|
99
|
+
nMax?: number;
|
|
100
|
+
}): WorkflowCandidate[];
|
|
101
|
+
export interface AntiPattern {
|
|
102
|
+
/** the action-type sequence that reliably PRECEDES failure */
|
|
103
|
+
pattern: string[];
|
|
104
|
+
/** failed trajectories ending right after this sequence */
|
|
105
|
+
failures: number;
|
|
106
|
+
trajectoryIds: string[];
|
|
107
|
+
warning: string;
|
|
108
|
+
}
|
|
109
|
+
/** Mine failure anti-patterns: consecutive action runs that immediately
|
|
110
|
+
* precede the END of FAILED trajectories. These become warnings attached to
|
|
111
|
+
* skills (knowledge about what NOT to do), never procedures. */
|
|
112
|
+
export declare function mineAntiPatterns(experiences: CognitiveTrajectory[], opts?: {
|
|
113
|
+
minFailures?: number;
|
|
114
|
+
nMax?: number;
|
|
115
|
+
}): AntiPattern[];
|
package/dist/skill-compiler.js
CHANGED
|
@@ -100,6 +100,71 @@ export class SkillCompiler {
|
|
|
100
100
|
s.status = 'rolled-back';
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
+
/** Mine frequent consecutive action n-grams (n within [nMin,nMax]) across
|
|
104
|
+
* SUCCESSFUL trajectories, keeping only MAXIMAL ones (an n-gram fully
|
|
105
|
+
* contained in a longer supported n-gram of the same episodes adds nothing).
|
|
106
|
+
* This generalizes compile()'s exact full-sequence matching: a workflow
|
|
107
|
+
* survives when one episode has an extra step somewhere. */
|
|
108
|
+
export function mineWorkflows(experiences, opts = {}) {
|
|
109
|
+
const minSupport = opts.minSupport ?? 2;
|
|
110
|
+
const nMin = opts.nMin ?? 2;
|
|
111
|
+
const nMax = opts.nMax ?? 4;
|
|
112
|
+
const table = new Map();
|
|
113
|
+
for (const traj of experiences) {
|
|
114
|
+
if (!traj.metrics.success)
|
|
115
|
+
continue;
|
|
116
|
+
const seq = traj.steps.filter((s) => s.outcome === 'success').map((s) => s.action.type);
|
|
117
|
+
for (let n = nMin; n <= Math.min(nMax, seq.length); n++) {
|
|
118
|
+
for (let i = 0; i + n <= seq.length; i++) {
|
|
119
|
+
const gram = seq.slice(i, i + n);
|
|
120
|
+
const key = gram.join('|');
|
|
121
|
+
const agg = table.get(key) ?? { steps: gram, trajs: new Set(), env: traj.environment.id };
|
|
122
|
+
agg.trajs.add(traj.id);
|
|
123
|
+
table.set(key, agg);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const supported = [...table.entries()]
|
|
128
|
+
.filter(([, v]) => v.trajs.size >= minSupport)
|
|
129
|
+
.map(([key, v]) => ({ key, steps: v.steps, support: v.trajs.size, trajectoryIds: [...v.trajs], environmentId: v.env }));
|
|
130
|
+
// maximality: drop grams whose key is a contiguous substring of a longer
|
|
131
|
+
// supported gram with support from a superset of episodes
|
|
132
|
+
const kept = supported.filter((c) => {
|
|
133
|
+
return !supported.some((d) => d !== c && d.steps.length > c.steps.length && d.key.includes(c.key) && d.support >= c.support);
|
|
134
|
+
});
|
|
135
|
+
return kept.sort((a, b) => b.steps.length - a.steps.length || b.support - a.support);
|
|
136
|
+
}
|
|
137
|
+
/** Mine failure anti-patterns: consecutive action runs that immediately
|
|
138
|
+
* precede the END of FAILED trajectories. These become warnings attached to
|
|
139
|
+
* skills (knowledge about what NOT to do), never procedures. */
|
|
140
|
+
export function mineAntiPatterns(experiences, opts = {}) {
|
|
141
|
+
const minFailures = opts.minFailures ?? 2;
|
|
142
|
+
const nMax = opts.nMax ?? 3;
|
|
143
|
+
const table = new Map();
|
|
144
|
+
for (const traj of experiences) {
|
|
145
|
+
if (traj.metrics.success)
|
|
146
|
+
continue;
|
|
147
|
+
const seq = traj.steps.map((s) => s.action.type);
|
|
148
|
+
if (seq.length === 0)
|
|
149
|
+
continue;
|
|
150
|
+
for (let n = 1; n <= Math.min(nMax, seq.length); n++) {
|
|
151
|
+
const gram = seq.slice(seq.length - n);
|
|
152
|
+
const key = gram.join('|');
|
|
153
|
+
const agg = table.get(key) ?? { steps: gram, trajs: new Set() };
|
|
154
|
+
agg.trajs.add(traj.id);
|
|
155
|
+
table.set(key, agg);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const all = [...table.entries()]
|
|
159
|
+
.filter(([, v]) => v.trajs.size >= minFailures)
|
|
160
|
+
.map(([key, v]) => ({ key, steps: v.steps, failures: v.trajs.size, trajectoryIds: [...v.trajs] }));
|
|
161
|
+
// maximality (same rule as workflows): drop a gram fully contained in a
|
|
162
|
+
// longer supported gram — the longer one carries the actionable context
|
|
163
|
+
const kept = all.filter((c) => !all.some((d) => d !== c && d.steps.length > c.steps.length && d.key.endsWith(c.key) && d.failures >= c.failures));
|
|
164
|
+
return kept
|
|
165
|
+
.map((c) => ({ pattern: c.steps, failures: c.failures, trajectoryIds: c.trajectoryIds, warning: `avoid ${c.key}: preceded the failure end in ${c.failures} failed runs` }))
|
|
166
|
+
.sort((a, b) => b.failures - a.failures || b.pattern.length - a.pattern.length);
|
|
167
|
+
}
|
|
103
168
|
function longestSuccessfulRun(traj) {
|
|
104
169
|
let best = [];
|
|
105
170
|
let cur = [];
|
package/dist/slice.js
CHANGED
|
@@ -112,7 +112,8 @@ export async function runVerticalSlice(opts) {
|
|
|
112
112
|
tags: ['slice', verdict.source, verdict.pass ? 'pass' : 'fail'],
|
|
113
113
|
});
|
|
114
114
|
const { opportunities } = await diagnoseOpportunities(opts.home).catch(() => ({ opportunities: [] }));
|
|
115
|
-
|
|
115
|
+
const deltaAcc = wm.deltaAccuracy();
|
|
116
|
+
stages.push({ stage: 'learn', ok: true, detail: `WM replayed (${wm.worldState.beliefs.length} beliefs; delta-shape accuracy ${deltaAcc.accuracy !== undefined ? Math.round(deltaAcc.accuracy * 100) + '%' : 'n/a'} over ${deltaAcc.checked}); memory entry ${entry.id} keyed to the ${verdict.source} verdict`, evidence: { memoryId: entry.id, beliefs: wm.worldState.beliefs.length, deltaAccuracy: deltaAcc, opportunities: opportunities.length } });
|
|
116
117
|
return { task: opts.task, startedAt, stages, verdict, agentClaim: { completed: actResult.completed, claim: actResult.claim } };
|
|
117
118
|
}
|
|
118
119
|
/** Format a slice report for the CLI (auditable, one line per stage). */
|
package/dist/world-model.d.ts
CHANGED
|
@@ -98,6 +98,36 @@ export interface PredictionQuery {
|
|
|
98
98
|
action: Action;
|
|
99
99
|
currentState?: WorldState;
|
|
100
100
|
}
|
|
101
|
+
export interface StateDelta {
|
|
102
|
+
/** top-level state keys added / removed / changed by a transition */
|
|
103
|
+
added: string[];
|
|
104
|
+
removed: string[];
|
|
105
|
+
changed: Array<{
|
|
106
|
+
key: string;
|
|
107
|
+
from: unknown;
|
|
108
|
+
to: unknown;
|
|
109
|
+
}>;
|
|
110
|
+
/** stable shape id: which keys this action tends to touch, sorted */
|
|
111
|
+
shape: string;
|
|
112
|
+
}
|
|
113
|
+
/** Structural diff of two observation states (top level + one nested
|
|
114
|
+
* level; deeper structure is hashed into the changed value). Deterministic
|
|
115
|
+
* and content-agnostic — it works on ANY environment's state object. */
|
|
116
|
+
export declare function stateDiff(before: unknown, after: unknown): StateDelta;
|
|
117
|
+
export interface DeltaPrediction {
|
|
118
|
+
actionType: string;
|
|
119
|
+
/** most frequent historical delta shape for this action type */
|
|
120
|
+
predictedShape: string | null;
|
|
121
|
+
/** fraction of historical transitions of this type that matched the mode shape */
|
|
122
|
+
confidence: number;
|
|
123
|
+
n: number;
|
|
124
|
+
}
|
|
125
|
+
export interface DeltaAccuracy {
|
|
126
|
+
checked: number;
|
|
127
|
+
/** predictions whose predicted shape matched the actual shape */
|
|
128
|
+
hits: number;
|
|
129
|
+
accuracy: number | undefined;
|
|
130
|
+
}
|
|
101
131
|
/** WM-002. Transition journal with retrieval by action type / outcome. */
|
|
102
132
|
export declare class TransitionStore {
|
|
103
133
|
private items;
|
|
@@ -113,6 +143,13 @@ export declare class WorldModel {
|
|
|
113
143
|
private transitions;
|
|
114
144
|
private predictions;
|
|
115
145
|
private seq;
|
|
146
|
+
/** WM 2.0: per-actionType delta shape history + prediction-accuracy
|
|
147
|
+
* bookkeeping (structured predictions are scored like outcome ones) */
|
|
148
|
+
private deltaShapes;
|
|
149
|
+
private deltaChecked;
|
|
150
|
+
private deltaHits;
|
|
151
|
+
/** open structured predictions: predictionId -> expected shape (resolved on update) */
|
|
152
|
+
private openDeltaPredictions;
|
|
116
153
|
constructor(environmentId: string);
|
|
117
154
|
get worldState(): WorldState;
|
|
118
155
|
/** WM-001/006. Apply a transition: update variables/entities, per-action
|
|
@@ -123,6 +160,13 @@ export declare class WorldModel {
|
|
|
123
160
|
* confidence 0 and knownUnknown=true — planners MUST treat that as a
|
|
124
161
|
* signal to explore, not as 0% success. */
|
|
125
162
|
predict(query: PredictionQuery): Prediction;
|
|
163
|
+
/** WM 2.0: predict the STRUCTURAL effect of an action — which state keys
|
|
164
|
+
* it tends to touch — from the delta-shape history. Ties into the same
|
|
165
|
+
* predictionId resolution as outcome predictions: passing the id here
|
|
166
|
+
* scores the shape prediction when the transition lands. */
|
|
167
|
+
predictDelta(actionType: string, predictionId?: string): DeltaPrediction;
|
|
168
|
+
/** WM 2.0: rolling accuracy of structured shape predictions. */
|
|
169
|
+
deltaAccuracy(): DeltaAccuracy;
|
|
126
170
|
/** planner gate: which action types are reliable enough to plan with */
|
|
127
171
|
plannerConfidence(threshold?: number): {
|
|
128
172
|
trusted: string[];
|
package/dist/world-model.js
CHANGED
|
@@ -1,4 +1,28 @@
|
|
|
1
1
|
import { stableHash } from "./protocol.js";
|
|
2
|
+
/** Structural diff of two observation states (top level + one nested
|
|
3
|
+
* level; deeper structure is hashed into the changed value). Deterministic
|
|
4
|
+
* and content-agnostic — it works on ANY environment's state object. */
|
|
5
|
+
export function stateDiff(before, after) {
|
|
6
|
+
const added = [];
|
|
7
|
+
const removed = [];
|
|
8
|
+
const changed = [];
|
|
9
|
+
const norm = (v) => (v !== null && typeof v === 'object' ? stableHash(v) : v);
|
|
10
|
+
const keysOf = (o) => (o && typeof o === 'object' ? Object.keys(o) : []);
|
|
11
|
+
const b = (before ?? {});
|
|
12
|
+
const a = (after ?? {});
|
|
13
|
+
for (const k of new Set([...keysOf(before), ...keysOf(after)])) {
|
|
14
|
+
const inB = k in b;
|
|
15
|
+
const inA = k in a;
|
|
16
|
+
if (inB && !inA)
|
|
17
|
+
removed.push(k);
|
|
18
|
+
else if (!inB && inA)
|
|
19
|
+
added.push(k);
|
|
20
|
+
else if (JSON.stringify(norm(b[k])) !== JSON.stringify(norm(a[k])))
|
|
21
|
+
changed.push({ key: k, from: norm(b[k]), to: norm(a[k]) });
|
|
22
|
+
}
|
|
23
|
+
const shape = [...added, ...removed, ...changed.map((c) => c.key)].sort().join(',');
|
|
24
|
+
return { added: added.sort(), removed: removed.sort(), changed, shape };
|
|
25
|
+
}
|
|
2
26
|
/** WM-002. Transition journal with retrieval by action type / outcome. */
|
|
3
27
|
export class TransitionStore {
|
|
4
28
|
items = [];
|
|
@@ -26,6 +50,13 @@ export class WorldModel {
|
|
|
26
50
|
transitions = new TransitionStore();
|
|
27
51
|
predictions = new Map();
|
|
28
52
|
seq = 0;
|
|
53
|
+
/** WM 2.0: per-actionType delta shape history + prediction-accuracy
|
|
54
|
+
* bookkeeping (structured predictions are scored like outcome ones) */
|
|
55
|
+
deltaShapes = new Map();
|
|
56
|
+
deltaChecked = 0;
|
|
57
|
+
deltaHits = 0;
|
|
58
|
+
/** open structured predictions: predictionId -> expected shape (resolved on update) */
|
|
59
|
+
openDeltaPredictions = new Map();
|
|
29
60
|
constructor(environmentId) {
|
|
30
61
|
this.state = {
|
|
31
62
|
environmentId,
|
|
@@ -71,6 +102,23 @@ export class WorldModel {
|
|
|
71
102
|
}
|
|
72
103
|
this.state.uncertainty.byAction[key] = Number((1 - (this.state.beliefs.find((b) => b.id === `act:${key}`)?.confidence ?? 0)).toFixed(4));
|
|
73
104
|
this.state.version += 1;
|
|
105
|
+
// WM 2.0: structured delta — diff the before/after state, learn the
|
|
106
|
+
// shape per action type, and score any open delta prediction
|
|
107
|
+
const actualDelta = stateDiff(input.stateBefore.variables ?? input.stateBefore, after ? (after.variables ?? after) : input.observation.state);
|
|
108
|
+
const shapes = this.deltaShapes.get(key) ?? [];
|
|
109
|
+
shapes.push(actualDelta.shape);
|
|
110
|
+
if (shapes.length > 50)
|
|
111
|
+
shapes.splice(0, shapes.length - 50);
|
|
112
|
+
this.deltaShapes.set(key, shapes);
|
|
113
|
+
if (input.predictionId) {
|
|
114
|
+
const expected = this.openDeltaPredictions.get(input.predictionId);
|
|
115
|
+
if (expected !== undefined) {
|
|
116
|
+
this.openDeltaPredictions.delete(input.predictionId);
|
|
117
|
+
this.deltaChecked += 1;
|
|
118
|
+
if (expected === actualDelta.shape)
|
|
119
|
+
this.deltaHits += 1;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
74
122
|
// WM-005: resolve the prediction bound to this action, if any
|
|
75
123
|
if (input.predictionId) {
|
|
76
124
|
const p = this.predictions.get(input.predictionId);
|
|
@@ -102,6 +150,32 @@ export class WorldModel {
|
|
|
102
150
|
this.predictions.set(id, prediction);
|
|
103
151
|
return prediction;
|
|
104
152
|
}
|
|
153
|
+
/** WM 2.0: predict the STRUCTURAL effect of an action — which state keys
|
|
154
|
+
* it tends to touch — from the delta-shape history. Ties into the same
|
|
155
|
+
* predictionId resolution as outcome predictions: passing the id here
|
|
156
|
+
* scores the shape prediction when the transition lands. */
|
|
157
|
+
predictDelta(actionType, predictionId) {
|
|
158
|
+
const shapes = this.deltaShapes.get(actionType) ?? [];
|
|
159
|
+
const counts = new Map();
|
|
160
|
+
for (const s of shapes)
|
|
161
|
+
counts.set(s, (counts.get(s) ?? 0) + 1);
|
|
162
|
+
let mode = null;
|
|
163
|
+
let modeN = 0;
|
|
164
|
+
for (const [s, c] of counts)
|
|
165
|
+
if (c > modeN) {
|
|
166
|
+
mode = s;
|
|
167
|
+
modeN = c;
|
|
168
|
+
}
|
|
169
|
+
if (mode !== null && predictionId)
|
|
170
|
+
this.openDeltaPredictions.set(predictionId, mode);
|
|
171
|
+
return { actionType, predictedShape: mode, confidence: shapes.length > 0 ? Number((modeN / shapes.length).toFixed(3)) : 0, n: shapes.length };
|
|
172
|
+
}
|
|
173
|
+
/** WM 2.0: rolling accuracy of structured shape predictions. */
|
|
174
|
+
deltaAccuracy() {
|
|
175
|
+
if (this.deltaChecked === 0)
|
|
176
|
+
return { checked: 0, hits: 0, accuracy: undefined };
|
|
177
|
+
return { checked: this.deltaChecked, hits: this.deltaHits, accuracy: Number((this.deltaHits / this.deltaChecked).toFixed(3)) };
|
|
178
|
+
}
|
|
105
179
|
/** planner gate: which action types are reliable enough to plan with */
|
|
106
180
|
plannerConfidence(threshold = 0.6) {
|
|
107
181
|
const trusted = [];
|
package/package.json
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@hmharness/cognitive",
|
|
3
|
-
"version": "0.23.
|
|
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
|
-
"type": "module",
|
|
6
|
-
"main": "dist/index.js",
|
|
7
|
-
"exports": {
|
|
8
|
-
".": {
|
|
9
|
-
"types": "./dist/index.d.ts",
|
|
10
|
-
"default": "./dist/index.js"
|
|
11
|
-
}
|
|
12
|
-
},
|
|
13
|
-
"types": "dist/index.d.ts",
|
|
14
|
-
"scripts": {
|
|
15
|
-
"build": "tsc -p tsconfig.build.json"
|
|
16
|
-
},
|
|
17
|
-
"files": [
|
|
18
|
-
"dist"
|
|
19
|
-
],
|
|
20
|
-
"license": "MIT",
|
|
21
|
-
"repository": {
|
|
22
|
-
"type": "git",
|
|
23
|
-
"url": "git+https://github.com/swsgbl/hmharness.git"
|
|
24
|
-
},
|
|
25
|
-
"engines": {
|
|
26
|
-
"node": ">=22"
|
|
27
|
-
},
|
|
28
|
-
"dependencies": {
|
|
29
|
-
"@hmharness/kernel": "0.23.
|
|
30
|
-
}
|
|
31
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@hmharness/cognitive",
|
|
3
|
+
"version": "0.23.17",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"types": "dist/index.d.ts",
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc -p tsconfig.build.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/swsgbl/hmharness.git"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@hmharness/kernel": "0.23.17"
|
|
30
|
+
}
|
|
31
|
+
}
|