@hmharness/cognitive 0.19.4 → 0.19.6

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
+ }
@@ -58,8 +58,10 @@ export interface GoalDriftView {
58
58
  recommendation: string;
59
59
  }
60
60
  /** GOAL-005 on live data: for every recorded trajectory that carried a goal,
61
- * compare its actions against the goal's keywords and report drift. */
62
- export declare function analyzeGoalDrift(home: string, limit?: number): Promise<GoalDriftView[]>;
61
+ * compare its actions against the goal's keywords and report drift.
62
+ * order='score' (default) ranks worst-first; order='time' is the timeline
63
+ * view (oldest→newest) the dashboard renders as a trend. */
64
+ export declare function analyzeGoalDrift(home: string, limit?: number, order?: 'score' | 'time'): Promise<GoalDriftView[]>;
63
65
  export interface SkillCandidateView {
64
66
  id: string;
65
67
  name: string;
package/dist/analysis.js CHANGED
@@ -149,8 +149,10 @@ export async function buildContextDigest(home, maxChars = 500) {
149
149
  }
150
150
  }
151
151
  /** GOAL-005 on live data: for every recorded trajectory that carried a goal,
152
- * compare its actions against the goal's keywords and report drift. */
153
- export async function analyzeGoalDrift(home, limit = 100) {
152
+ * compare its actions against the goal's keywords and report drift.
153
+ * order='score' (default) ranks worst-first; order='time' is the timeline
154
+ * view (oldest→newest) the dashboard renders as a trend. */
155
+ export async function analyzeGoalDrift(home, limit = 100, order = 'score') {
154
156
  const { GoalManager } = await import("./goal.js");
155
157
  const gm = new GoalManager();
156
158
  const trajectories = (await loadTrajectories(home, limit)).filter((t) => t.goal?.description);
@@ -177,9 +179,14 @@ export async function analyzeGoalDrift(home, limit = 100) {
177
179
  driftScore: report.driftScore,
178
180
  signals: report.signals,
179
181
  recommendation: report.recommendation,
182
+ startedAt: traj.startedAt,
180
183
  });
181
184
  }
182
- return out.sort((a, b) => b.driftScore - a.driftScore);
185
+ if (order === 'time')
186
+ out.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
187
+ else
188
+ out.sort((a, b) => b.driftScore - a.driftScore);
189
+ return out;
183
190
  }
184
191
  /** SK-002 on live data: mine repeated successful action runs from the
185
192
  * trajectory store into skill CANDIDATES (promotion still requires the
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,57 @@
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
+ /** calibration: mean Brier per arm (lower = better predicted). The seeded
42
+ * arm should predict overlapping actions better than the empty arm even
43
+ * when success rates tie — that is real carried knowledge. */
44
+ brierWith?: number;
45
+ brierWithout?: number;
46
+ /** positive = seeded arm better calibrated (its Brier is lower) */
47
+ calibrationDelta?: number;
48
+ }
49
+ export declare function runTransferExperiment(home: string, opts: {
50
+ sourceEnv: string;
51
+ targetEnv: string;
52
+ makeTargetEnv: () => Environment;
53
+ runsPerArm?: number;
54
+ maxActions?: number;
55
+ /** skip persisting arm trajectories (pure experiment) */
56
+ record?: boolean;
57
+ }): Promise<TransferExperimentReport>;
@@ -0,0 +1,133 @@
1
+ import { TrajectoryStore, TrajectoryRecorder, brierScore } 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 allSteps = [];
51
+ const wm = wmSeed ?? new WorldModel(envId);
52
+ // each run gets a FRESH environment (no cross-run state leakage) but the
53
+ // SAME world model — that is the "carried knowledge" being measured
54
+ for (let i = 0; i < runs; i++) {
55
+ const env = makeEnv();
56
+ const rec = new TrajectoryRecorder(`trj-transfer-${armLabel}-${Date.now().toString(36)}-${i}`, `transfer-${armLabel}`, { id: envId, version: '1' });
57
+ const result = await exploreOnce(env, wm, { maxActions, maxCost: maxActions * 4, rec, home });
58
+ details.push(result);
59
+ totalActions += result.actionsTaken;
60
+ successfulActions += result.successfulActions;
61
+ const traj = rec.finish(result.actionsTaken > 0);
62
+ allSteps.push(...traj.steps);
63
+ await store?.append(traj).catch(() => undefined);
64
+ await env.close().catch(() => undefined);
65
+ }
66
+ return { successes: successfulActions, runs, totalActions, details, wm, successfulActions, meanBrier: brierScore(allSteps) };
67
+ }
68
+ export async function runTransferExperiment(home, opts) {
69
+ const runsPerArm = Math.min(Math.max(opts.runsPerArm ?? 3, 1), 10);
70
+ const maxActions = Math.min(Math.max(opts.maxActions ?? 4, 1), 10);
71
+ const home2 = opts.record === false ? 'NOREC' : home;
72
+ // seed: replay SOURCE-env history, then REKEY beliefs onto the abstract
73
+ // action layer (@write/@run/...) so knowledge crosses environment borders
74
+ const history = await loadTrajectories(home);
75
+ const literal = replayIntoWorldModel(history, opts.sourceEnv);
76
+ const seeded = new WorldModel(opts.targetEnv);
77
+ const byAbstract = new Map();
78
+ for (const b of literal.worldState.beliefs) {
79
+ if (!b.id.startsWith('act:'))
80
+ continue;
81
+ const key = mappedKey(b.id.slice(4));
82
+ const prev = byAbstract.get(key) ?? { conf: 0, n: 0 };
83
+ const total = prev.n + b.evidenceCount;
84
+ byAbstract.set(key, { conf: (prev.conf * prev.n + b.confidence * b.evidenceCount) / Math.max(1, total), n: total });
85
+ }
86
+ for (const [key, v] of byAbstract) {
87
+ for (let i = 0; i < v.n; i++) {
88
+ seeded.update({
89
+ stateBefore: seeded.worldState,
90
+ action: { id: `seed-${key}-${i}`, type: key, args: {} },
91
+ observation: { environmentId: opts.targetEnv, timestamp: new Date().toISOString(), state: null, availableActions: [] },
92
+ outcome: v.conf >= 0.5 ? 'success' : 'failure',
93
+ });
94
+ }
95
+ }
96
+ // abstract overlap: target affordances whose intent has seeded knowledge
97
+ const probeEnv = opts.makeTargetEnv();
98
+ const probeObs = await probeEnv.reset({});
99
+ await probeEnv.close().catch(() => undefined);
100
+ const seededKeys = new Set(byAbstract.keys());
101
+ const overlap = [...new Set(probeObs.availableActions.map((a) => mappedKey(a.type)).filter((k) => seededKeys.has(k)))];
102
+ const withArm = await runArm(home2, opts.makeTargetEnv, seeded, runsPerArm, maxActions, opts.targetEnv, 'with');
103
+ const withoutArm = await runArm(home2, opts.makeTargetEnv, null, runsPerArm, maxActions, opts.targetEnv, 'without');
104
+ // ACTION-LEVEL success rate: the seeded arm should spend its budget on
105
+ // affordances it already believes in — wasted probes on failing actions
106
+ // are exactly what carried knowledge should prevent
107
+ const withRate = withArm.totalActions ? withArm.successfulActions / withArm.totalActions : 0;
108
+ const withoutRate = withoutArm.totalActions ? withoutArm.successfulActions / withoutArm.totalActions : 0;
109
+ const cell = {
110
+ sourceEnv: opts.sourceEnv,
111
+ targetEnv: opts.targetEnv,
112
+ withTransfer: Number(withRate.toFixed(4)),
113
+ fromScratch: Number(withoutRate.toFixed(4)),
114
+ samplesWith: withArm.totalActions,
115
+ samplesWithout: withoutArm.totalActions,
116
+ };
117
+ return {
118
+ sourceEnv: opts.sourceEnv,
119
+ targetEnv: opts.targetEnv,
120
+ runsPerArm,
121
+ actionOverlap: overlap,
122
+ withTransfer: Number(cell.withTransfer.toFixed(3)),
123
+ fromScratch: Number(cell.fromScratch.toFixed(3)),
124
+ score: transferScore(cell),
125
+ verdict: transferVerdict(cell),
126
+ trajectoryIds: [],
127
+ brierWith: withArm.meanBrier,
128
+ brierWithout: withoutArm.meanBrier,
129
+ calibrationDelta: withArm.meanBrier !== undefined && withoutArm.meanBrier !== undefined
130
+ ? Number((withoutArm.meanBrier - withArm.meanBrier).toFixed(4))
131
+ : undefined,
132
+ };
133
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.19.4",
3
+ "version": "0.19.6",
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.6"
30
30
  }
31
31
  }