@hmharness/cognitive 0.23.22 → 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.
@@ -48,15 +48,29 @@ export interface PredictionError {
48
48
  /** predicted but untouched (overprediction) */
49
49
  spurious: string[];
50
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
+ }
51
60
  export declare class CodeWorldModel {
52
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). */
53
66
  private relations;
54
67
  /** latest diagnostics per uri (sensors push; overwrite per uri) */
55
68
  private diagnostics;
56
69
  private latestBuild;
57
70
  private runtimeFacts;
58
71
  private openPredictions;
59
- /** Ingest sensors' output — idempotent per entity id; diagnostics replace per uri. */
72
+ /** Ingest sensors' output — idempotent per entity id AND per relation
73
+ * edge; diagnostics replace per uri. */
60
74
  ingest(input: {
61
75
  entities?: CodeEntity[];
62
76
  relations?: SymbolRelation[];
@@ -64,10 +78,19 @@ export declare class CodeWorldModel {
64
78
  build?: BuildFact;
65
79
  runtime?: RuntimeFact;
66
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;
67
86
  get entityCount(): number;
68
87
  get relationCount(): number;
69
88
  get diagnosticCount(): number;
70
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[];
71
94
  entity(id: string): CodeEntity | undefined;
72
95
  relationsOf(entityId: string): SymbolRelation[];
73
96
  diagnosticsFor(uri: string): CodeDiagnostic[];
@@ -91,6 +114,12 @@ export declare class CodeWorldModel {
91
114
  touchedEntities: string[];
92
115
  touchedRelations: string[];
93
116
  }): PredictionError | null;
94
- /** Snapshot hash — for holdout discipline and drift detection. */
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). */
95
124
  stateHash(): string;
96
125
  }
@@ -14,20 +14,25 @@
14
14
  * predict-before/actual-after/error scoring the environment world has.
15
15
  */
16
16
  import { stableHash } from "./protocol.js";
17
- /* ---------------- the model ---------------- */
18
17
  export class CodeWorldModel {
19
18
  entities = new Map();
20
- relations = [];
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();
21
24
  /** latest diagnostics per uri (sensors push; overwrite per uri) */
22
25
  diagnostics = new Map();
23
26
  latestBuild = null;
24
27
  runtimeFacts = [];
25
28
  openPredictions = new Map();
26
- /** Ingest sensors' output — idempotent per entity id; diagnostics replace per uri. */
29
+ /** Ingest sensors' output — idempotent per entity id AND per relation
30
+ * edge; diagnostics replace per uri. */
27
31
  ingest(input) {
28
32
  for (const e of input.entities ?? [])
29
33
  this.entities.set(e.id, e);
30
- this.relations.push(...(input.relations ?? []));
34
+ for (const r of input.relations ?? [])
35
+ this.relations.set(`${r.from}->${r.to}:${r.kind}`, r);
31
36
  for (const d of input.diagnostics ?? []) {
32
37
  const cur = this.diagnostics.get(d.uri) ?? [];
33
38
  const next = cur.filter((x) => x.message !== d.message || x.source !== d.source);
@@ -39,11 +44,40 @@ export class CodeWorldModel {
39
44
  if (input.runtime)
40
45
  this.runtimeFacts.push(input.runtime);
41
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
+ }
42
76
  get entityCount() {
43
77
  return this.entities.size;
44
78
  }
45
79
  get relationCount() {
46
- return this.relations.length;
80
+ return this.relations.size;
47
81
  }
48
82
  get diagnosticCount() {
49
83
  return [...this.diagnostics.values()].reduce((s, l) => s + l.length, 0);
@@ -51,11 +85,17 @@ export class CodeWorldModel {
51
85
  get build() {
52
86
  return this.latestBuild;
53
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
+ }
54
94
  entity(id) {
55
95
  return this.entities.get(id);
56
96
  }
57
97
  relationsOf(entityId) {
58
- return this.relations.filter((r) => r.from === entityId || r.to === entityId);
98
+ return [...this.relations.values()].filter((r) => r.from === entityId || r.to === entityId);
59
99
  }
60
100
  diagnosticsFor(uri) {
61
101
  return [...(this.diagnostics.get(uri) ?? [])];
@@ -70,7 +110,7 @@ export class CodeWorldModel {
70
110
  predictEditDelta(edit) {
71
111
  const touchedEntities = new Set([edit.target]);
72
112
  const touchedRelations = new Set();
73
- for (const r of this.relations) {
113
+ for (const r of this.relations.values()) {
74
114
  if (r.from === edit.target || r.to === edit.target) {
75
115
  touchedRelations.add(`${r.from}->${r.to}:${r.kind}`);
76
116
  touchedEntities.add(r.from);
@@ -115,12 +155,20 @@ export class CodeWorldModel {
115
155
  spurious,
116
156
  };
117
157
  }
118
- /** Snapshot hash — for holdout discipline and drift detection. */
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). */
119
165
  stateHash() {
120
166
  return stableHash({
121
167
  entities: [...this.entities.keys()].sort(),
122
- relations: this.relations.map((r) => `${r.from}->${r.to}:${r.kind}`).sort(),
123
- diagnosticUris: [...this.diagnostics.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(),
124
172
  build: this.latestBuild,
125
173
  });
126
174
  }
@@ -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
+ }
package/dist/index.d.ts CHANGED
@@ -35,3 +35,4 @@ export * from './slice.js';
35
35
  export * from './mea.js';
36
36
  export * from './evalset.js';
37
37
  export * from './code-world-model.js';
38
+ export * from './code-world-store.js';
package/dist/index.js CHANGED
@@ -34,3 +34,4 @@ export * from "./slice.js";
34
34
  export * from "./mea.js";
35
35
  export * from "./evalset.js";
36
36
  export * from "./code-world-model.js";
37
+ export * from "./code-world-store.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.23.22",
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.22"
29
+ "@hmharness/kernel": "0.23.23"
30
30
  }
31
31
  }