@hmharness/cognitive 0.19.1 → 0.19.3

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,75 @@
1
+ import { WorldModel, type CognitiveTrajectory } from './index.js';
2
+ import { type LearningOpportunity } from './continual.js';
3
+ import { type UniformMetrics } from './benchmark.js';
4
+ export declare function loadTrajectories(home: string, limit?: number): Promise<CognitiveTrajectory[]>;
5
+ export interface WorldModelSummary {
6
+ environmentId: string;
7
+ beliefs: Array<{
8
+ actionType: string;
9
+ confidence: number;
10
+ evidenceCount: number;
11
+ claim: string;
12
+ }>;
13
+ plannerGate: {
14
+ trusted: string[];
15
+ untrusted: string[];
16
+ unknown: string[];
17
+ };
18
+ calibration: {
19
+ resolved: number;
20
+ meanError: number | undefined;
21
+ };
22
+ trajectoriesReplayed: number;
23
+ stepsReplayed: number;
24
+ }
25
+ /** Replay recorded trajectories through a fresh WorldModel. Every step is
26
+ * predicted BEFORE it is applied, so prediction-vs-actual calibration is
27
+ * measured on history the model never saw coming (no leakage). */
28
+ export declare function replayIntoWorldModel(trajectories: CognitiveTrajectory[], environmentId?: string): WorldModel;
29
+ export declare function summarizeWorldModel(wm: WorldModel, trajectoriesReplayed: number, stepsReplayed: number): WorldModelSummary;
30
+ /** Full pipeline for one home: load -> replay -> summarize. */
31
+ export declare function analyzeWorldModel(home: string, environmentId?: string): Promise<WorldModelSummary>;
32
+ /** CL-003 over live data: what kind of learning would pay off right now? */
33
+ export declare function diagnoseOpportunities(home: string): Promise<{
34
+ opportunities: LearningOpportunity[];
35
+ trajectories: number;
36
+ }>;
37
+ export interface BenchReport {
38
+ environmentId: string;
39
+ runs: number;
40
+ aggregate: UniformMetrics & {
41
+ successRate: number;
42
+ };
43
+ }
44
+ /** BENCH seed: uniform metrics aggregated over recorded runs (action budget
45
+ * = the run's own step count +1, so efficiency measures consistency, and
46
+ * honest runs with retries score below clean one-shot runs). */
47
+ export declare function benchFromTrajectories(home: string, environmentId?: string, limit?: number): Promise<BenchReport | null>;
48
+ /** Compact world-model digest for the SYSTEM PROMPT. The model sees which
49
+ * tool types history trusts, which keep failing, and what the diagnosis
50
+ * layer currently suggests — perception feeding action, capped hard so it
51
+ * can never bloat the prompt (max ~500 chars). */
52
+ export declare function buildContextDigest(home: string, maxChars?: number): Promise<string>;
53
+ export interface GoalDriftView {
54
+ trajectoryId: string;
55
+ goalDescription: string;
56
+ driftScore: number;
57
+ signals: string[];
58
+ recommendation: string;
59
+ }
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[]>;
63
+ export interface SkillCandidateView {
64
+ id: string;
65
+ name: string;
66
+ procedure: string[];
67
+ evidenceTrajectories: number;
68
+ status: string;
69
+ }
70
+ /** SK-002 on live data: mine repeated successful action runs from the
71
+ * trajectory store into skill CANDIDATES (promotion still requires the
72
+ * benchmark gate — this only surfaces what the history suggests). */
73
+ export declare function skillCandidatesFromHistory(home: string, opts?: {
74
+ minRepeat?: number;
75
+ }): Promise<SkillCandidateView[]>;
@@ -0,0 +1,199 @@
1
+ /**
2
+ * @hmharness/cognitive - analysis (blueprint M2/M8/M11: the data flywheel)
3
+ *
4
+ * Turns the trajectory store that the live runner has been filling into the
5
+ * three things the cognitive layers consume:
6
+ *
7
+ * - loadWorldModel: replay every recorded step THROUGH the world model
8
+ * (predict-then-update), so beliefs, calibration and planner gates are
9
+ * built from REAL run history, not synthetic examples
10
+ * - diagnoseOpportunities: LearningController.diagnose over the real
11
+ * trajectory dataset — failure clusters, calibration gaps, recovery and
12
+ * efficiency opportunities (CL-003 wired to live data)
13
+ * - benchFromTrajectories: GeneralBench uniform metrics aggregated over
14
+ * recorded runs per environment (BENCH seed on real samples)
15
+ */
16
+ import { readdir, readFile } from 'node:fs/promises';
17
+ import { join } from 'node:path';
18
+ import { WorldModel } from "./index.js";
19
+ import { LearningController } from "./continual.js";
20
+ import { uniformMetrics } from "./benchmark.js";
21
+ export async function loadTrajectories(home, limit = 500) {
22
+ const dir = join(home, 'cognitive', 'trajectories');
23
+ let files;
24
+ try {
25
+ files = (await readdir(dir)).filter((f) => f.endsWith('.jsonl'));
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ const out = [];
31
+ for (const f of files.slice(-limit)) {
32
+ try {
33
+ const text = await readFile(join(dir, f), 'utf8');
34
+ for (const line of text.split('\n')) {
35
+ if (!line.trim())
36
+ continue;
37
+ try {
38
+ out.push(JSON.parse(line));
39
+ }
40
+ catch { /* skip torn tail lines */ }
41
+ }
42
+ }
43
+ catch { /* unreadable file: skip */ }
44
+ }
45
+ return out;
46
+ }
47
+ /** Replay recorded trajectories through a fresh WorldModel. Every step is
48
+ * predicted BEFORE it is applied, so prediction-vs-actual calibration is
49
+ * measured on history the model never saw coming (no leakage). */
50
+ export function replayIntoWorldModel(trajectories, environmentId = 'terminal') {
51
+ const wm = new WorldModel(environmentId);
52
+ for (const traj of trajectories) {
53
+ if (traj.environment.id !== environmentId)
54
+ continue;
55
+ for (const step of traj.steps) {
56
+ const prediction = wm.predict({ action: step.action });
57
+ wm.update({
58
+ stateBefore: wm.worldState,
59
+ action: step.action,
60
+ observation: { environmentId, timestamp: traj.startedAt, state: null, availableActions: [] },
61
+ outcome: step.outcome,
62
+ predictionId: prediction.id,
63
+ });
64
+ }
65
+ }
66
+ return wm;
67
+ }
68
+ export function summarizeWorldModel(wm, trajectoriesReplayed, stepsReplayed) {
69
+ const state = wm.worldState;
70
+ return {
71
+ environmentId: state.environmentId,
72
+ beliefs: state.beliefs
73
+ .filter((b) => b.id.startsWith('act:'))
74
+ .map((b) => ({ actionType: b.id.slice(4), confidence: b.confidence, evidenceCount: b.evidenceCount, claim: b.claim }))
75
+ .sort((a, b) => b.evidenceCount - a.evidenceCount),
76
+ plannerGate: wm.plannerConfidence(0.6),
77
+ calibration: wm.calibration(),
78
+ trajectoriesReplayed,
79
+ stepsReplayed,
80
+ };
81
+ }
82
+ /** Full pipeline for one home: load -> replay -> summarize. */
83
+ export async function analyzeWorldModel(home, environmentId = 'terminal') {
84
+ const trajectories = await loadTrajectories(home);
85
+ const steps = trajectories.filter((t) => t.environment.id === environmentId).reduce((s, t) => s + t.steps.length, 0);
86
+ const wm = replayIntoWorldModel(trajectories, environmentId);
87
+ return summarizeWorldModel(wm, trajectories.length, steps);
88
+ }
89
+ /** CL-003 over live data: what kind of learning would pay off right now? */
90
+ export async function diagnoseOpportunities(home) {
91
+ const trajectories = await loadTrajectories(home);
92
+ const lc = new LearningController(); // diagnosis only: no trainer needed
93
+ for (const t of trajectories)
94
+ await lc.collect(t);
95
+ return { opportunities: await lc.diagnose(lc.dataset()), trajectories: trajectories.length };
96
+ }
97
+ /** BENCH seed: uniform metrics aggregated over recorded runs (action budget
98
+ * = the run's own step count +1, so efficiency measures consistency, and
99
+ * honest runs with retries score below clean one-shot runs). */
100
+ export async function benchFromTrajectories(home, environmentId = 'terminal', limit = 200) {
101
+ const trajectories = (await loadTrajectories(home, limit)).filter((t) => t.environment.id === environmentId);
102
+ if (trajectories.length === 0)
103
+ return null;
104
+ const metrics = trajectories.map((t) => uniformMetrics(t, t.metrics.actions + 1));
105
+ const avg = (pick) => Number((metrics.reduce((s, m) => s + pick(m), 0) / metrics.length).toFixed(3));
106
+ return {
107
+ environmentId,
108
+ runs: trajectories.length,
109
+ aggregate: {
110
+ success: avg((m) => m.success),
111
+ actionEfficiency: avg((m) => m.actionEfficiency),
112
+ recoveryRate: avg((m) => m.recoveryRate),
113
+ calibration: avg((m) => m.calibration),
114
+ predicted: metrics.some((m) => m.predicted),
115
+ costUnits: avg((m) => m.costUnits),
116
+ latencyMs: avg((m) => m.latencyMs),
117
+ successRate: avg((m) => m.success),
118
+ },
119
+ };
120
+ }
121
+ /* ---- context advisor (blueprint M3: the planner consumes the world model) ---- */
122
+ /** Compact world-model digest for the SYSTEM PROMPT. The model sees which
123
+ * tool types history trusts, which keep failing, and what the diagnosis
124
+ * layer currently suggests — perception feeding action, capped hard so it
125
+ * can never bloat the prompt (max ~500 chars). */
126
+ export async function buildContextDigest(home, maxChars = 500) {
127
+ try {
128
+ const wm = await analyzeWorldModel(home);
129
+ if (wm.stepsReplayed < 3)
130
+ return ''; // too little evidence to advise on
131
+ const lines = [];
132
+ const untrusted = wm.beliefs.filter((b) => b.confidence < 0.5 && b.evidenceCount >= 2);
133
+ if (untrusted.length > 0) {
134
+ lines.push(`Flaky tools historically (verify carefully when using): ${untrusted.slice(0, 3).map((b) => `${b.actionType}(${Math.round(b.confidence * 100)}%)`).join(', ')}.`);
135
+ }
136
+ const trusted = wm.beliefs.filter((b) => b.confidence >= 0.7 && b.evidenceCount >= 3);
137
+ if (trusted.length > 0) {
138
+ lines.push(`Reliable tools: ${trusted.slice(0, 3).map((b) => b.actionType).join(', ')}.`);
139
+ }
140
+ const { opportunities } = await diagnoseOpportunities(home);
141
+ const opp = opportunities[0];
142
+ if (opp)
143
+ lines.push(`Learning focus right now: ${opp.signal.slice(0, 120)}.`);
144
+ const text = lines.join(' ');
145
+ return text.length > maxChars ? text.slice(0, maxChars - 3) + '...' : text;
146
+ }
147
+ catch {
148
+ return ''; // advising is best-effort; never block context assembly
149
+ }
150
+ }
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) {
154
+ const { GoalManager } = await import("./goal.js");
155
+ const gm = new GoalManager();
156
+ const trajectories = (await loadTrajectories(home, limit)).filter((t) => t.goal?.description);
157
+ const out = [];
158
+ for (const traj of trajectories) {
159
+ const goal = gm.propose({
160
+ id: traj.goal.id,
161
+ description: traj.goal.description,
162
+ source: 'user',
163
+ priority: 1,
164
+ constraints: [],
165
+ successCriteria: [],
166
+ });
167
+ const transitions = traj.steps.map((s) => ({
168
+ stateBefore: {},
169
+ action: s.action,
170
+ observation: { environmentId: traj.environment.id, timestamp: traj.startedAt, state: null, availableActions: [] },
171
+ outcome: s.outcome,
172
+ }));
173
+ const report = gm.detectDrift(goal, transitions, { sessionId: traj.sessionId, actionsTaken: traj.steps.length });
174
+ out.push({
175
+ trajectoryId: traj.id,
176
+ goalDescription: traj.goal.description,
177
+ driftScore: report.driftScore,
178
+ signals: report.signals,
179
+ recommendation: report.recommendation,
180
+ });
181
+ }
182
+ return out.sort((a, b) => b.driftScore - a.driftScore);
183
+ }
184
+ /** SK-002 on live data: mine repeated successful action runs from the
185
+ * trajectory store into skill CANDIDATES (promotion still requires the
186
+ * benchmark gate — this only surfaces what the history suggests). */
187
+ export async function skillCandidatesFromHistory(home, opts) {
188
+ const { SkillCompiler } = await import("./skill-compiler.js");
189
+ const compiler = new SkillCompiler();
190
+ const trajectories = await loadTrajectories(home);
191
+ const candidates = await compiler.compile(trajectories, opts);
192
+ return candidates.map((c) => ({
193
+ id: c.id,
194
+ name: c.name,
195
+ procedure: c.procedure.map((s) => s.ref),
196
+ evidenceTrajectories: c.evidence.length,
197
+ status: c.status,
198
+ }));
199
+ }
package/dist/index.d.ts CHANGED
@@ -22,3 +22,4 @@ export * from './evolution2.js';
22
22
  export * from './multi-agent.js';
23
23
  export * from './benchmark.js';
24
24
  export * from './status.js';
25
+ export * from './analysis.js';
package/dist/index.js CHANGED
@@ -22,3 +22,4 @@ export * from "./evolution2.js";
22
22
  export * from "./multi-agent.js";
23
23
  export * from "./benchmark.js";
24
24
  export * from "./status.js";
25
+ export * from "./analysis.js";
package/dist/status.d.ts CHANGED
@@ -14,6 +14,24 @@ export interface CognitiveStatus {
14
14
  trajectories: boolean;
15
15
  evolutionAudit: boolean;
16
16
  };
17
+ /** world-model digest replayed from recorded trajectories (blueprint M2) */
18
+ worldModel?: {
19
+ beliefs: Array<{
20
+ actionType: string;
21
+ confidence: number;
22
+ evidenceCount: number;
23
+ }>;
24
+ plannerGate: {
25
+ trusted: string[];
26
+ untrusted: string[];
27
+ unknown: string[];
28
+ };
29
+ calibration: {
30
+ resolved: number;
31
+ meanError: number | undefined;
32
+ };
33
+ stepsReplayed: number;
34
+ };
17
35
  }
18
36
  export declare function cognitiveStatus(home: string): Promise<CognitiveStatus>;
19
37
  /** Human-facing one-pager (zh) for the CLI. */
package/dist/status.js CHANGED
@@ -40,6 +40,18 @@ export async function cognitiveStatus(home) {
40
40
  { id: 'arc3', version: '0.1.0' },
41
41
  ];
42
42
  void loaded;
43
+ let worldModel;
44
+ try {
45
+ const { analyzeWorldModel } = await import("./analysis.js");
46
+ const wm = await analyzeWorldModel(home);
47
+ worldModel = {
48
+ beliefs: wm.beliefs.slice(0, 10).map((b) => ({ actionType: b.actionType, confidence: b.confidence, evidenceCount: b.evidenceCount })),
49
+ plannerGate: wm.plannerGate,
50
+ calibration: wm.calibration,
51
+ stepsReplayed: wm.stepsReplayed,
52
+ };
53
+ }
54
+ catch { /* world model digest is best-effort */ }
43
55
  return {
44
56
  home,
45
57
  memory: mem.stats(),
@@ -53,6 +65,7 @@ export async function cognitiveStatus(home) {
53
65
  trajectories: trajectories > 0,
54
66
  evolutionAudit: auditEvents > 0,
55
67
  },
68
+ worldModel,
56
69
  };
57
70
  }
58
71
  /** Human-facing one-pager (zh) for the CLI. */
@@ -67,6 +80,11 @@ export function formatCognitiveStatus(s) {
67
80
  ` 进化审计 ${s.evolutionAuditEvents} 条事件${s.evolutionLastEvent ? `(最近: ${String(s.evolutionLastEvent.event)})` : ''}`,
68
81
  ` 环境注册表 ${s.environments.map((e) => e.id).join(' / ')}`,
69
82
  ];
83
+ if (s.worldModel && s.worldModel.beliefs.length > 0) {
84
+ const top = s.worldModel.beliefs.slice(0, 3).map((b) => `${b.actionType}≈${b.confidence.toFixed(1)}`).join(' ');
85
+ const cal = s.worldModel.calibration;
86
+ lines.push(` 世界模型 ${s.worldModel.stepsReplayed} 步回放,top 信念 ${top}${cal.meanError !== undefined ? `,校准误差 ${cal.meanError}` : ''}`);
87
+ }
70
88
  const notReady = Object.entries(s.ready).filter(([, v]) => !v).map(([k]) => k);
71
89
  if (notReady.length)
72
90
  lines.push(` 未激活 ${notReady.join(', ')}(对应能力尚未产生第一条数据)`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.19.1",
3
+ "version": "0.19.3",
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.1"
29
+ "@hmharness/kernel": "0.19.3"
30
30
  }
31
31
  }