@hmharness/cognitive 0.19.0

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,124 @@
1
+ /**
2
+ * @hmharness/cognitive - skill compiler (blueprint §8 / SK-001..010)
3
+ *
4
+ * Skills are EXECUTABLE, VERIFIABLE objects — not prose. A SkillSpec carries
5
+ * trigger, preconditions, procedure (typed steps), verification specs and
6
+ * evidence refs, versioned. Compilation mines episodic trajectories for
7
+ * repeated action patterns that ended in success; every candidate MUST pass
8
+ * its verification suite on a benchmark before promotion, and promotion is
9
+ * reversible (SK-007/008) through the same governance path as evolution
10
+ * candidates.
11
+ */
12
+ import { stableHash } from "./protocol.js";
13
+ export class SkillCompiler {
14
+ skills = new Map();
15
+ lastVerification = new Map();
16
+ list() {
17
+ return [...this.skills.values()];
18
+ }
19
+ get(id) {
20
+ return this.skills.get(id);
21
+ }
22
+ /** SK-002. Mine successful trajectories for repeated action-type runs.
23
+ * A pattern must appear in >= minRepeat distinct successful episodes to
24
+ * become a candidate — one lucky run is folklore, not a skill. */
25
+ async compile(experiences, opts) {
26
+ const minRepeat = opts?.minRepeat ?? 2;
27
+ const patterns = new Map();
28
+ for (const traj of experiences) {
29
+ if (!traj.metrics.success)
30
+ continue;
31
+ const run = longestSuccessfulRun(traj);
32
+ if (run.length < 2)
33
+ continue;
34
+ const key = run.join('|');
35
+ const p = patterns.get(key) ?? { actionTypes: run, trajectories: [] };
36
+ p.trajectories.push(traj);
37
+ patterns.set(key, p);
38
+ }
39
+ const out = [];
40
+ for (const [key, p] of patterns) {
41
+ if (p.trajectories.length < minRepeat)
42
+ continue;
43
+ const envId = p.trajectories[0].environment.id;
44
+ const skill = {
45
+ id: `skill-${stableHash(key).slice(0, 10)}`,
46
+ name: `${p.actionTypes.join(' → ')} (${envId})`,
47
+ trigger: { environmentId: envId, actionTypes: p.actionTypes },
48
+ preconditions: [
49
+ { description: `environment is ${envId}`, check: `env:id=${envId}` },
50
+ ],
51
+ procedure: p.actionTypes.map((t) => ({ kind: 'act', ref: t })),
52
+ verification: [
53
+ { id: 'success-rate', evaluator: 'bench:run', expect: { metric: 'successRate', op: '>=', value: 0.8 } },
54
+ { id: 'action-efficiency', evaluator: 'bench:run', expect: { metric: 'actionsPerSuccess', op: '<=', value: 1.5 * avgActions(p.trajectories) } },
55
+ ],
56
+ evidence: p.trajectories.map((t) => ({ trajectoryId: t.id, steps: t.metrics.actions, outcome: 'success' })),
57
+ version: '0.1.0',
58
+ status: 'candidate',
59
+ createdAt: new Date().toISOString(),
60
+ };
61
+ this.skills.set(skill.id, skill);
62
+ out.push(skill);
63
+ }
64
+ return out;
65
+ }
66
+ /** SK-004. Run the skill's verification specs against the benchmark. */
67
+ async verify(skill, benchmark) {
68
+ const metrics = await benchmark.runSkill(skill);
69
+ const checks = skill.verification.map((v) => {
70
+ const actual = metrics[v.expect.metric] ?? Number.NaN;
71
+ const pass = v.expect.op === '>=' ? actual >= v.expect.value
72
+ : v.expect.op === '<=' ? actual <= v.expect.value
73
+ : actual === v.expect.value;
74
+ return { id: v.id, metric: v.expect.metric, actual, expected: `${v.expect.op} ${v.expect.value}`, pass: Number.isFinite(actual) && pass };
75
+ });
76
+ const result = { skillId: skill.id, pass: checks.every((c) => c.pass), checks };
77
+ this.lastVerification.set(skill.id, result);
78
+ return result;
79
+ }
80
+ /** SK-007. Promote only candidates with a PASSING verification on record.
81
+ * No verification, no promotion — this is the whole point of the gate. */
82
+ async promote(skillId) {
83
+ const s = this.skills.get(skillId);
84
+ if (!s)
85
+ throw new Error(`unknown skill ${skillId}`);
86
+ const verification = this.lastVerification.get(skillId);
87
+ if (!verification?.pass) {
88
+ throw new Error(`skill ${skillId} has no passing verification on record: run verify() against a benchmark first`);
89
+ }
90
+ if (s.status === 'active')
91
+ return;
92
+ s.status = 'active';
93
+ s.version = bump(s.version);
94
+ }
95
+ /** SK-008. Rollback is always allowed. */
96
+ async rollback(skillId) {
97
+ const s = this.skills.get(skillId);
98
+ if (!s)
99
+ throw new Error(`unknown skill ${skillId}`);
100
+ s.status = 'rolled-back';
101
+ }
102
+ }
103
+ function longestSuccessfulRun(traj) {
104
+ let best = [];
105
+ let cur = [];
106
+ for (const s of traj.steps) {
107
+ if (s.outcome === 'success') {
108
+ cur.push(s.action.type);
109
+ if (cur.length > best.length)
110
+ best = cur;
111
+ }
112
+ else {
113
+ cur = [];
114
+ }
115
+ }
116
+ return best;
117
+ }
118
+ function avgActions(trajs) {
119
+ return trajs.reduce((s, t) => s + t.metrics.actions, 0) / trajs.length;
120
+ }
121
+ function bump(version) {
122
+ const [maj, min, patch] = version.split('.').map((n) => Number(n) || 0);
123
+ return `${maj}.${min}.${patch + 1}`;
124
+ }
@@ -0,0 +1,20 @@
1
+ export interface CognitiveStatus {
2
+ home: string;
3
+ memory: Record<string, number>;
4
+ memoryContradictions: number;
5
+ trajectories: number;
6
+ evolutionAuditEvents: number;
7
+ evolutionLastEvent?: Record<string, unknown>;
8
+ environments: Array<{
9
+ id: string;
10
+ version: string;
11
+ }>;
12
+ ready: {
13
+ memory: boolean;
14
+ trajectories: boolean;
15
+ evolutionAudit: boolean;
16
+ };
17
+ }
18
+ export declare function cognitiveStatus(home: string): Promise<CognitiveStatus>;
19
+ /** Human-facing one-pager (zh) for the CLI. */
20
+ export declare function formatCognitiveStatus(s: CognitiveStatus): string;
package/dist/status.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @hmharness/cognitive - status snapshot for CLI (`hmh cognitive status`)
3
+ * and the web research dashboard (`/api/cognitive`).
4
+ *
5
+ * RD-001..008 seed: one call gathers registry state, memory layer stats,
6
+ * evolution audit tail and bench/transfer readiness. Read-only, cheap,
7
+ * honest — absent subsystems report absent, never zeros-that-lie.
8
+ */
9
+ import { readdir, readFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { CognitiveMemory, TrajectoryStore } from "./index.js";
12
+ export async function cognitiveStatus(home) {
13
+ const mem = new CognitiveMemory(home);
14
+ const loaded = await mem.load();
15
+ const contradictions = mem.detectContradictions().length;
16
+ let trajectories = 0;
17
+ try {
18
+ const files = await readdir(join(home, 'cognitive', 'trajectories')).catch(() => []);
19
+ trajectories = files.filter((f) => f.endsWith('.jsonl')).length;
20
+ }
21
+ catch {
22
+ trajectories = 0;
23
+ }
24
+ void new TrajectoryStore(home); // store is instantiated per-write; count files instead
25
+ let auditEvents = 0;
26
+ let evolutionLastEvent;
27
+ try {
28
+ const text = await readFile(join(home, 'cognitive', 'evolution', 'audit.jsonl'), 'utf8');
29
+ const lines = text.split('\n').filter((l) => l.trim());
30
+ auditEvents = lines.length;
31
+ if (lines.length)
32
+ evolutionLastEvent = JSON.parse(lines[lines.length - 1]);
33
+ }
34
+ catch { /* no audit yet */ }
35
+ const environments = [
36
+ { id: 'terminal', version: '1.0.0' },
37
+ { id: 'harmonyos', version: '1.0.0' },
38
+ { id: 'browser', version: '1.0.0' },
39
+ { id: 'desktop', version: '1.0.0' },
40
+ { id: 'arc3', version: '0.1.0' },
41
+ ];
42
+ void loaded;
43
+ return {
44
+ home,
45
+ memory: mem.stats(),
46
+ memoryContradictions: contradictions,
47
+ trajectories,
48
+ evolutionAuditEvents: auditEvents,
49
+ evolutionLastEvent,
50
+ environments,
51
+ ready: {
52
+ memory: loaded > 0,
53
+ trajectories: trajectories > 0,
54
+ evolutionAudit: auditEvents > 0,
55
+ },
56
+ };
57
+ }
58
+ /** Human-facing one-pager (zh) for the CLI. */
59
+ export function formatCognitiveStatus(s) {
60
+ const layers = ['working', 'episodic', 'semantic', 'procedural', 'world']
61
+ .map((l) => `${l}:${s.memory[l] ?? 0}`)
62
+ .join(' ');
63
+ const lines = [
64
+ 'HMH Cognitive OS 状态',
65
+ ` 记忆五层 ${layers}(矛盾待审 ${s.memoryContradictions})`,
66
+ ` 轨迹库 ${s.trajectories} 条 episodic 记录`,
67
+ ` 进化审计 ${s.evolutionAuditEvents} 条事件${s.evolutionLastEvent ? `(最近: ${String(s.evolutionLastEvent.event)})` : ''}`,
68
+ ` 环境注册表 ${s.environments.map((e) => e.id).join(' / ')}`,
69
+ ];
70
+ const notReady = Object.entries(s.ready).filter(([, v]) => !v).map(([k]) => k);
71
+ if (notReady.length)
72
+ lines.push(` 未激活 ${notReady.join(', ')}(对应能力尚未产生第一条数据)`);
73
+ else
74
+ lines.push(' 全部子系统已产生数据');
75
+ return lines.join('\n');
76
+ }
@@ -0,0 +1,54 @@
1
+ import { type CognitiveTrajectory, type TrajectoryStep } from './protocol.js';
2
+ export declare class TrajectoryStore {
3
+ private home;
4
+ constructor(home: string);
5
+ private dir;
6
+ append(traj: CognitiveTrajectory): Promise<{
7
+ ok: boolean;
8
+ errors: string[];
9
+ file: string;
10
+ }>;
11
+ load(id: string): Promise<CognitiveTrajectory[]>;
12
+ }
13
+ /** In-memory builder so callers never hand-assemble step arrays. */
14
+ export declare class TrajectoryRecorder {
15
+ readonly id: string;
16
+ readonly sessionId: string;
17
+ readonly environment: {
18
+ id: string;
19
+ version: string;
20
+ };
21
+ private goal?;
22
+ private steps;
23
+ private startedAt;
24
+ private recoveries;
25
+ private t0;
26
+ constructor(id: string, sessionId: string, environment: {
27
+ id: string;
28
+ version: string;
29
+ }, goal?: {
30
+ id: string;
31
+ description: string;
32
+ } | undefined);
33
+ record(step: Omit<TrajectoryStep, 'step'>): void;
34
+ finish(success: boolean): CognitiveTrajectory;
35
+ }
36
+ /** Brier score over predicted steps: mean((confidence - outcome)^2).
37
+ * Lower is better; undefined when no predictions were made — an agent that
38
+ * never predicts cannot be scored on calibration (that absence is itself
39
+ * reported by the dashboard, not silently zeroed). */
40
+ export declare function brierScore(steps: TrajectoryStep[]): number | undefined;
41
+ /** Deterministic replay check: re-run recorded actions against a fresh
42
+ * environment and report divergence. Used by WM-009 and BENCH tracks. */
43
+ export declare function replay(traj: CognitiveTrajectory, fresh: {
44
+ act(a: TrajectoryStep['action']): Promise<{
45
+ outcome: string;
46
+ }>;
47
+ }): Promise<{
48
+ divergedAt: number | null;
49
+ mismatches: Array<{
50
+ step: number;
51
+ recorded: string;
52
+ replayed: string;
53
+ }>;
54
+ }>;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @hmharness/cognitive - trajectory store (blueprint §23 + CL-001)
3
+ *
4
+ * Every cognitive run appends ONE JSONL trajectory: observation refs, actions
5
+ * WITH reasons, optional pre-action predictions (confidence), outcomes,
6
+ * rewards and evidence refs. Raw records are append-only — distillation
7
+ * happens in other layers, never by rewriting here (blueprint §10: 精炼层
8
+ * 不可覆盖原始记录).
9
+ */
10
+ import { mkdir, readFile, appendFile } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import { validateTrajectory } from "./protocol.js";
13
+ export class TrajectoryStore {
14
+ home;
15
+ constructor(home) {
16
+ this.home = home;
17
+ }
18
+ dir() {
19
+ return join(this.home, 'cognitive', 'trajectories');
20
+ }
21
+ async append(traj) {
22
+ const v = validateTrajectory(traj);
23
+ if (!v.valid)
24
+ return { ok: false, errors: v.errors, file: '' };
25
+ await mkdir(this.dir(), { recursive: true });
26
+ const file = join(this.dir(), `${traj.id}.jsonl`);
27
+ await appendFile(file, JSON.stringify(traj) + '\n', 'utf8');
28
+ return { ok: true, errors: [], file };
29
+ }
30
+ async load(id) {
31
+ let text;
32
+ try {
33
+ text = await readFile(join(this.dir(), `${id}.jsonl`), 'utf8');
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ return text.split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l));
39
+ }
40
+ }
41
+ /** In-memory builder so callers never hand-assemble step arrays. */
42
+ export class TrajectoryRecorder {
43
+ id;
44
+ sessionId;
45
+ environment;
46
+ goal;
47
+ steps = [];
48
+ startedAt = new Date().toISOString();
49
+ recoveries = 0;
50
+ t0 = Date.now();
51
+ constructor(id, sessionId, environment, goal) {
52
+ this.id = id;
53
+ this.sessionId = sessionId;
54
+ this.environment = environment;
55
+ this.goal = goal;
56
+ }
57
+ record(step) {
58
+ if (this.steps.length > 0 && this.steps[this.steps.length - 1].outcome === 'failure' && step.outcome === 'success') {
59
+ this.recoveries += 1;
60
+ }
61
+ this.steps.push({ ...step, step: this.steps.length + 1 });
62
+ }
63
+ finish(success) {
64
+ return {
65
+ id: this.id,
66
+ sessionId: this.sessionId,
67
+ environment: this.environment,
68
+ goal: this.goal,
69
+ steps: this.steps,
70
+ metrics: {
71
+ success,
72
+ actions: this.steps.length,
73
+ elapsedMs: Date.now() - this.t0,
74
+ recoveryCount: this.recoveries,
75
+ brierScore: brierScore(this.steps),
76
+ },
77
+ startedAt: this.startedAt,
78
+ endedAt: new Date().toISOString(),
79
+ };
80
+ }
81
+ }
82
+ /** Brier score over predicted steps: mean((confidence - outcome)^2).
83
+ * Lower is better; undefined when no predictions were made — an agent that
84
+ * never predicts cannot be scored on calibration (that absence is itself
85
+ * reported by the dashboard, not silently zeroed). */
86
+ export function brierScore(steps) {
87
+ const predicted = steps.filter((s) => s.prediction);
88
+ if (predicted.length === 0)
89
+ return undefined;
90
+ let sum = 0;
91
+ for (const s of predicted) {
92
+ const actual = s.outcome === 'success' ? 1 : 0;
93
+ const c = Math.min(1, Math.max(0, s.prediction.confidence));
94
+ sum += (c - actual) ** 2;
95
+ }
96
+ return Number((sum / predicted.length).toFixed(4));
97
+ }
98
+ /** Deterministic replay check: re-run recorded actions against a fresh
99
+ * environment and report divergence. Used by WM-009 and BENCH tracks. */
100
+ export async function replay(traj, fresh) {
101
+ const mismatches = [];
102
+ let divergedAt = null;
103
+ for (const s of traj.steps) {
104
+ const r = await fresh.act(s.action);
105
+ if (r.outcome !== s.outcome) {
106
+ mismatches.push({ step: s.step, recorded: s.outcome, replayed: r.outcome });
107
+ if (divergedAt === null)
108
+ divergedAt = s.step;
109
+ }
110
+ }
111
+ return { divergedAt, mismatches };
112
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @hmharness/cognitive - world model (blueprint §3 / WM-001..010)
3
+ *
4
+ * The agent's_belief about an environment, updated from transitions and used
5
+ * to predict action outcomes. Blueprint hard rules encoded:
6
+ * - 不允许假装确定: every prediction carries confidence; low-confidence
7
+ * predictions are flagged and MAY NOT silently feed a planner
8
+ * (plannerConfidence gate below)
9
+ * - prediction vs actual 自动比较 (WM-005): every resolved prediction is
10
+ * scored, rolling calibration is maintained
11
+ * - 错误聚类 (WM-005): misses cluster by (actionType, errorBucket) so the
12
+ * diagnosis layer sees WHERE the model is wrong, not just how often
13
+ * - replay (WM-009): transitions are the unit of replay/revision evidence
14
+ * - episodic retrieval + semantic rule extraction (WM-008): transitions are
15
+ * retrievable; `revise` turns recurring error clusters into explicit
16
+ * correction rules (never silently rewritten beliefs)
17
+ */
18
+ import type { Action, Observation } from './protocol.js';
19
+ export interface Belief {
20
+ id: string;
21
+ claim: string;
22
+ confidence: number;
23
+ evidenceCount: number;
24
+ lastConfirmedAt?: string;
25
+ /** correction rules extracted from error clusters (WM-008) */
26
+ corrections?: Array<{
27
+ pattern: string;
28
+ rule: string;
29
+ fromCluster: string;
30
+ }>;
31
+ }
32
+ export interface UncertaintyMap {
33
+ /** actionType -> uncertainty in [0,1]; absent = never observed */
34
+ byAction: Record<string, number>;
35
+ }
36
+ export interface WorldState {
37
+ environmentId: string;
38
+ version: number;
39
+ entities: Array<{
40
+ id: string;
41
+ kind: string;
42
+ props?: Record<string, unknown>;
43
+ }>;
44
+ variables: Record<string, unknown>;
45
+ beliefs: Belief[];
46
+ uncertainty: UncertaintyMap;
47
+ }
48
+ export interface Transition {
49
+ stateBefore: WorldState;
50
+ action: Action;
51
+ observation: Observation;
52
+ stateAfter?: WorldState;
53
+ reward?: number;
54
+ outcome: 'success' | 'failure' | 'unknown';
55
+ predictionId?: string;
56
+ }
57
+ export interface Prediction {
58
+ id: string;
59
+ claim: string;
60
+ confidence: number;
61
+ actionType: string;
62
+ createdAt: string;
63
+ resolvedAt?: string;
64
+ actual?: 'success' | 'failure' | 'unknown';
65
+ /** |confidence - actual| on resolution */
66
+ error?: number;
67
+ }
68
+ export interface PredictionEvidence {
69
+ predictionId: string;
70
+ claim: string;
71
+ confidence: number;
72
+ actual?: string;
73
+ error?: number;
74
+ supportingTransitions: number;
75
+ cluster?: string;
76
+ }
77
+ export interface ModelRevision {
78
+ id: string;
79
+ createdAt: string;
80
+ clustersAddressed: string[];
81
+ rulesAdded: Array<{
82
+ pattern: string;
83
+ rule: string;
84
+ }>;
85
+ beliefsAdjusted: number;
86
+ }
87
+ export interface ModelEvidence {
88
+ cluster: string;
89
+ misses: number;
90
+ total: number;
91
+ sampleErrors: Array<{
92
+ claim: string;
93
+ actual: string;
94
+ confidence: number;
95
+ }>;
96
+ }
97
+ export interface PredictionQuery {
98
+ action: Action;
99
+ currentState?: WorldState;
100
+ }
101
+ /** WM-002. Transition journal with retrieval by action type / outcome. */
102
+ export declare class TransitionStore {
103
+ private items;
104
+ append(t: Transition): void;
105
+ all(): readonly Transition[];
106
+ byActionType(type: string): Transition[];
107
+ byOutcome(outcome: Transition['outcome']): Transition[];
108
+ /** rough episodic retrieval: most recent N transitions of same action type */
109
+ similar(actionType: string, n?: number): Transition[];
110
+ }
111
+ export declare class WorldModel {
112
+ private state;
113
+ private transitions;
114
+ private predictions;
115
+ private seq;
116
+ constructor(environmentId: string);
117
+ get worldState(): WorldState;
118
+ /** WM-001/006. Apply a transition: update variables/entities, per-action
119
+ * success-rate beliefs, and resolve any prediction bound to the action. */
120
+ update(input: Transition): WorldState;
121
+ /** WM-003/004. Predict the outcome of an action from the belief table.
122
+ * The model is allowed to say "I don't know": unseen action types return
123
+ * confidence 0 and knownUnknown=true — planners MUST treat that as a
124
+ * signal to explore, not as 0% success. */
125
+ predict(query: PredictionQuery): Prediction;
126
+ /** planner gate: which action types are reliable enough to plan with */
127
+ plannerConfidence(threshold?: number): {
128
+ trusted: string[];
129
+ untrusted: string[];
130
+ unknown: string[];
131
+ };
132
+ explainPrediction(id: string): PredictionEvidence;
133
+ /** WM-005. Cluster resolved-but-wrong predictions by action type. */
134
+ errorClusters(): ModelEvidence[];
135
+ /** WM-007/008. Turn error clusters into explicit correction rules.
136
+ * Beliefs are NOT silently rewritten — rules are attached as corrections
137
+ * so provenance survives (blueprint: 可解释修订). */
138
+ revise(evidence: ModelEvidence[]): ModelRevision;
139
+ confidence(stateOrPredictionId: string): number;
140
+ /** rolling calibration for the dashboard (mean |error| over resolved) */
141
+ calibration(): {
142
+ resolved: number;
143
+ meanError: number | undefined;
144
+ };
145
+ get transitionsStore(): TransitionStore;
146
+ }