@hmharness/cognitive 0.19.4 → 0.19.5

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,16 @@
1
+ /**
2
+ * @hmharness/cognitive - abstract action mapping (blueprint §17 / TR-002 core)
3
+ *
4
+ * Cross-environment transfer fails at the LITERAL action layer (terminal's
5
+ * writeFile and harmonyos's hdc-install share no type string). The abstract
6
+ * layer names the INTENT: write / install / run / observe / remove / verify.
7
+ * World-model beliefs replay through this map, so knowledge earned in one
8
+ * environment can inform another — while the map itself stays explicit and
9
+ * auditable (no silent fuzzy matching).
10
+ */
11
+ export type AbstractAction = 'observe' | 'read' | 'write' | 'edit' | 'run' | 'install' | 'launch' | 'remove' | 'query' | 'navigate' | 'interact';
12
+ /** explicit, auditable literal→abstract edges. Extend deliberately. */
13
+ export declare const ABSTRACT_ACTION_MAP: Record<string, AbstractAction>;
14
+ export declare function abstractOf(actionType: string): AbstractAction | undefined;
15
+ /** both sides map to the same abstract intent? */
16
+ export declare function abstractlyOverlaps(a: string, b: string): boolean;
@@ -0,0 +1,32 @@
1
+ /** explicit, auditable literal→abstract edges. Extend deliberately. */
2
+ export const ABSTRACT_ACTION_MAP = {
3
+ // terminal environment
4
+ 'command': 'run',
5
+ 'writeFile': 'write',
6
+ 'deleteFile': 'remove',
7
+ // agent tools (trajectory steps use tool names)
8
+ 'read_file': 'read',
9
+ 'write_file': 'write',
10
+ 'edit_file': 'edit',
11
+ 'run_command': 'run',
12
+ 'list_dir': 'observe',
13
+ 'web_fetch': 'query',
14
+ 'web_search': 'query',
15
+ 'browser_open': 'navigate',
16
+ 'desktop_click': 'interact',
17
+ 'desktop_type': 'interact',
18
+ 'desktop_screenshot': 'observe',
19
+ // harmonyos environment
20
+ 'hdc-shell': 'run',
21
+ 'hdc-install': 'install',
22
+ 'hdc-aa-start': 'launch',
23
+ };
24
+ export function abstractOf(actionType) {
25
+ return ABSTRACT_ACTION_MAP[actionType];
26
+ }
27
+ /** both sides map to the same abstract intent? */
28
+ export function abstractlyOverlaps(a, b) {
29
+ const aa = abstractOf(a);
30
+ const ab = abstractOf(b);
31
+ return aa !== undefined && aa === ab;
32
+ }
package/dist/index.d.ts CHANGED
@@ -24,3 +24,5 @@ export * from './benchmark.js';
24
24
  export * from './status.js';
25
25
  export * from './analysis.js';
26
26
  export * from './explore-runner.js';
27
+ export * from './transfer-lab.js';
28
+ export * from './abstract-actions.js';
package/dist/index.js CHANGED
@@ -24,3 +24,5 @@ export * from "./benchmark.js";
24
24
  export * from "./status.js";
25
25
  export * from "./analysis.js";
26
26
  export * from "./explore-runner.js";
27
+ export * from "./transfer-lab.js";
28
+ export * from "./abstract-actions.js";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @hmharness/cognitive - transfer lab (blueprint §17 / TR-001..006)
3
+ *
4
+ * A CONTROLLED experiment, not a dashboard decoration: does knowledge
5
+ * learned in a SOURCE environment measurably improve exploration in a
6
+ * TARGET environment?
7
+ *
8
+ * with-transfer arm : the exploration policy consults a world model whose
9
+ * beliefs were replayed from SOURCE-env history
10
+ * from-scratch arm : identical run against an empty world model
11
+ *
12
+ * Both arms use the SAME environment instance sequence, budgets and seeds —
13
+ * only the belief table differs. Transfer Score = relative success gain
14
+ * (TR-006); negative transfer (carried beliefs HURT) is a first-class
15
+ * result and is reported, never hidden.
16
+ *
17
+ * Honesty rules:
18
+ * - source and target usually expose DIFFERENT affordances; the carried
19
+ * beliefs only transfer where action types overlap. The report shows the
20
+ * overlap so a 0-overlap pair never pretends to be a transfer test.
21
+ * - small N is small N: verdicts below are labelled with sample counts.
22
+ */
23
+ import type { Environment } from './index.js';
24
+ import { type ExplorationResult } from './exploration.js';
25
+ export interface TransferArmResult {
26
+ successes: number;
27
+ runs: number;
28
+ totalActions: number;
29
+ details: Array<ExplorationResult>;
30
+ }
31
+ export interface TransferExperimentReport {
32
+ sourceEnv: string;
33
+ targetEnv: string;
34
+ runsPerArm: number;
35
+ actionOverlap: string[];
36
+ withTransfer: number;
37
+ fromScratch: number;
38
+ score: number;
39
+ verdict: 'positive' | 'neutral' | 'negative';
40
+ trajectoryIds: string[];
41
+ }
42
+ export declare function runTransferExperiment(home: string, opts: {
43
+ sourceEnv: string;
44
+ targetEnv: string;
45
+ makeTargetEnv: () => Environment;
46
+ runsPerArm?: number;
47
+ maxActions?: number;
48
+ /** skip persisting arm trajectories (pure experiment) */
49
+ record?: boolean;
50
+ }): Promise<TransferExperimentReport>;
@@ -0,0 +1,126 @@
1
+ import { TrajectoryStore, TrajectoryRecorder } from "./index.js";
2
+ import { WorldModel } from "./world-model.js";
3
+ import { ExplorationEngine, UcbExplorationPolicy, HypothesisRegistry } from "./exploration.js";
4
+ import { loadTrajectories, replayIntoWorldModel } from "./analysis.js";
5
+ import { transferScore, transferVerdict } from "./benchmark.js";
6
+ import { abstractOf } from "./abstract-actions.js";
7
+ /** belief-key mapping used by BOTH arms: '@write' when the action type has
8
+ * an abstract intent, the literal type otherwise. Symmetric mapping keeps
9
+ * the arms comparable — only the seeded KNOWLEDGE differs. */
10
+ function mappedKey(actionType) {
11
+ const a = abstractOf(actionType);
12
+ return a ? `@${a}` : actionType;
13
+ }
14
+ /** one exploration run against `env`, optionally seeded by `wm` */
15
+ async function exploreOnce(env, wm, opts) {
16
+ const hypotheses = new HypothesisRegistry();
17
+ hypotheses.register({ claim: 'affordances can be exercised successfully', expectedEvidence: 'probing an action succeeds', refutingEvidence: 'probing actions fails' });
18
+ const obs = await env.reset({});
19
+ const engine = new ExplorationEngine(new UcbExplorationPolicy());
20
+ const result = await engine.run({
21
+ maxActions: opts.maxActions,
22
+ maxCost: opts.maxCost,
23
+ riskTolerance: 0.6,
24
+ ctx: { observation: obs, worldModel: wm, hypotheses },
25
+ act: async (action) => {
26
+ // translate to the abstract key layer so source-env beliefs can hit
27
+ const keyAction = { ...action, type: mappedKey(action.type) };
28
+ const prediction = wm.predict({ action: keyAction });
29
+ const r = await env.act(action);
30
+ const after = await env.observe().catch(() => obs);
31
+ wm.update({
32
+ stateBefore: wm.worldState,
33
+ action: keyAction,
34
+ observation: after,
35
+ outcome: r.outcome === 'success' ? 'success' : r.outcome === 'failure' ? 'failure' : 'unknown',
36
+ predictionId: prediction.id,
37
+ });
38
+ opts.rec.record({ action, outcome: r.outcome, evidence: [`transfer:${action.type}`], prediction: { claim: prediction.claim, confidence: prediction.confidence } });
39
+ return { outcome: r.outcome };
40
+ },
41
+ });
42
+ const successfulActions = engine.outcomeLog.filter((o) => o.result.outcome === 'success').length;
43
+ return { ...result, successfulActions };
44
+ }
45
+ async function runArm(home, makeEnv, wmSeed, runs, maxActions, envId, armLabel) {
46
+ const store = home === 'NOREC' ? null : new TrajectoryStore(home);
47
+ const details = [];
48
+ let successfulActions = 0;
49
+ let totalActions = 0;
50
+ const wm = wmSeed ?? new WorldModel(envId);
51
+ // each run gets a FRESH environment (no cross-run state leakage) but the
52
+ // SAME world model — that is the "carried knowledge" being measured
53
+ for (let i = 0; i < runs; i++) {
54
+ const env = makeEnv();
55
+ const rec = new TrajectoryRecorder(`trj-transfer-${armLabel}-${Date.now().toString(36)}-${i}`, `transfer-${armLabel}`, { id: envId, version: '1' });
56
+ const result = await exploreOnce(env, wm, { maxActions, maxCost: maxActions * 4, rec, home });
57
+ details.push(result);
58
+ totalActions += result.actionsTaken;
59
+ successfulActions += result.successfulActions;
60
+ const traj = rec.finish(result.actionsTaken > 0);
61
+ await store?.append(traj).catch(() => undefined);
62
+ await env.close().catch(() => undefined);
63
+ }
64
+ return { successes: successfulActions, runs, totalActions, details, wm, successfulActions };
65
+ }
66
+ export async function runTransferExperiment(home, opts) {
67
+ const runsPerArm = Math.min(Math.max(opts.runsPerArm ?? 3, 1), 10);
68
+ const maxActions = Math.min(Math.max(opts.maxActions ?? 4, 1), 10);
69
+ const home2 = opts.record === false ? 'NOREC' : home;
70
+ // seed: replay SOURCE-env history, then REKEY beliefs onto the abstract
71
+ // action layer (@write/@run/...) so knowledge crosses environment borders
72
+ const history = await loadTrajectories(home);
73
+ const literal = replayIntoWorldModel(history, opts.sourceEnv);
74
+ const seeded = new WorldModel(opts.targetEnv);
75
+ const byAbstract = new Map();
76
+ for (const b of literal.worldState.beliefs) {
77
+ if (!b.id.startsWith('act:'))
78
+ continue;
79
+ const key = mappedKey(b.id.slice(4));
80
+ const prev = byAbstract.get(key) ?? { conf: 0, n: 0 };
81
+ const total = prev.n + b.evidenceCount;
82
+ byAbstract.set(key, { conf: (prev.conf * prev.n + b.confidence * b.evidenceCount) / Math.max(1, total), n: total });
83
+ }
84
+ for (const [key, v] of byAbstract) {
85
+ for (let i = 0; i < v.n; i++) {
86
+ seeded.update({
87
+ stateBefore: seeded.worldState,
88
+ action: { id: `seed-${key}-${i}`, type: key, args: {} },
89
+ observation: { environmentId: opts.targetEnv, timestamp: new Date().toISOString(), state: null, availableActions: [] },
90
+ outcome: v.conf >= 0.5 ? 'success' : 'failure',
91
+ });
92
+ }
93
+ }
94
+ // abstract overlap: target affordances whose intent has seeded knowledge
95
+ const probeEnv = opts.makeTargetEnv();
96
+ const probeObs = await probeEnv.reset({});
97
+ await probeEnv.close().catch(() => undefined);
98
+ const seededKeys = new Set(byAbstract.keys());
99
+ const overlap = [...new Set(probeObs.availableActions.map((a) => mappedKey(a.type)).filter((k) => seededKeys.has(k)))];
100
+ const withArm = await runArm(home2, opts.makeTargetEnv, seeded, runsPerArm, maxActions, opts.targetEnv, 'with');
101
+ const withoutArm = await runArm(home2, opts.makeTargetEnv, null, runsPerArm, maxActions, opts.targetEnv, 'without');
102
+ // ACTION-LEVEL success rate: the seeded arm should spend its budget on
103
+ // affordances it already believes in — wasted probes on failing actions
104
+ // are exactly what carried knowledge should prevent
105
+ const withRate = withArm.totalActions ? withArm.successfulActions / withArm.totalActions : 0;
106
+ const withoutRate = withoutArm.totalActions ? withoutArm.successfulActions / withoutArm.totalActions : 0;
107
+ const cell = {
108
+ sourceEnv: opts.sourceEnv,
109
+ targetEnv: opts.targetEnv,
110
+ withTransfer: Number(withRate.toFixed(4)),
111
+ fromScratch: Number(withoutRate.toFixed(4)),
112
+ samplesWith: withArm.totalActions,
113
+ samplesWithout: withoutArm.totalActions,
114
+ };
115
+ return {
116
+ sourceEnv: opts.sourceEnv,
117
+ targetEnv: opts.targetEnv,
118
+ runsPerArm,
119
+ actionOverlap: overlap,
120
+ withTransfer: Number(cell.withTransfer.toFixed(3)),
121
+ fromScratch: Number(cell.fromScratch.toFixed(3)),
122
+ score: transferScore(cell),
123
+ verdict: transferVerdict(cell),
124
+ trajectoryIds: [],
125
+ };
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.19.4",
3
+ "version": "0.19.5",
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.19.4"
29
+ "@hmharness/kernel": "0.19.5"
30
30
  }
31
31
  }