@hmharness/cognitive 0.23.28 → 0.23.30
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.
- package/dist/credit-assignment.js +4 -0
- package/dist/learning-targets.d.ts +27 -2
- package/dist/learning-targets.js +93 -2
- package/dist/ledger.d.ts +12 -1
- package/dist/ledger.js +23 -0
- package/dist/skill-compiler.d.ts +33 -0
- package/dist/skill-compiler.js +24 -0
- package/package.json +2 -2
|
@@ -25,9 +25,11 @@
|
|
|
25
25
|
*/
|
|
26
26
|
import type { Candidate, EvalResult, LearningDataset, LearningPlan, LearningTarget } from './continual.js';
|
|
27
27
|
import type { CognitiveLedger } from './ledger.js';
|
|
28
|
-
import { type WorkflowCandidate } from './skill-compiler.js';
|
|
28
|
+
import { type WorkflowCandidate, type AntiPattern } from './skill-compiler.js';
|
|
29
29
|
export type TargetTrainer = (plan: LearningPlan, dataset: LearningDataset) => Promise<Candidate>;
|
|
30
|
-
|
|
30
|
+
/** train rides along: deterministic-rebuild evaluators (world_model) need
|
|
31
|
+
* the exact training set; evaluators that don't care ignore the 3rd arg. */
|
|
32
|
+
export type TargetEvaluator = (candidate: Candidate, holdout: LearningDataset, train: LearningDataset) => Promise<EvalResult>;
|
|
31
33
|
export type TargetRollback = (candidate: Candidate) => Promise<void>;
|
|
32
34
|
export interface PromotionPolicy {
|
|
33
35
|
/** minimum evidence metric before promotion is even considered */
|
|
@@ -90,3 +92,26 @@ export declare function registerSkillTarget(registry: LearningTargetRegistry, op
|
|
|
90
92
|
policy?: Partial<PromotionPolicy>;
|
|
91
93
|
lineageSource?: string;
|
|
92
94
|
}): void;
|
|
95
|
+
export interface AntiPatternCandidate extends Candidate {
|
|
96
|
+
patterns: AntiPattern[];
|
|
97
|
+
}
|
|
98
|
+
export declare function registerAntiPatternTarget(registry: LearningTargetRegistry, opts: {
|
|
99
|
+
holdout: () => Promise<LearningDataset>;
|
|
100
|
+
mining?: {
|
|
101
|
+
minFailures?: number;
|
|
102
|
+
nMax?: number;
|
|
103
|
+
};
|
|
104
|
+
policy?: Partial<PromotionPolicy>;
|
|
105
|
+
lineageSource?: string;
|
|
106
|
+
}): void;
|
|
107
|
+
export interface WorldModelCandidate extends Candidate {
|
|
108
|
+
environmentId: string;
|
|
109
|
+
beliefs: number;
|
|
110
|
+
corrections: number;
|
|
111
|
+
}
|
|
112
|
+
export declare function registerWorldModelTarget(registry: LearningTargetRegistry, opts: {
|
|
113
|
+
environmentId: string;
|
|
114
|
+
holdout: () => Promise<LearningDataset>;
|
|
115
|
+
policy?: Partial<PromotionPolicy>;
|
|
116
|
+
lineageSource?: string;
|
|
117
|
+
}): void;
|
package/dist/learning-targets.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { evidenceThreshold } from "./continual.js";
|
|
2
|
-
import { mineWorkflows } from "./skill-compiler.js";
|
|
2
|
+
import { mineWorkflows, mineAntiPatterns } from "./skill-compiler.js";
|
|
3
|
+
import { WorldModel } from "./world-model.js";
|
|
4
|
+
import { replayIntoWorldModel } from "./analysis.js";
|
|
3
5
|
const REQUIRED_FIELDS = ['trainer', 'evaluator', 'holdout', 'promotionPolicy', 'rollback', 'lineage'];
|
|
4
6
|
/** Only vocabulary kinds are mirrored - see the module doc. */
|
|
5
7
|
const LEDGER_MAP = {
|
|
@@ -52,7 +54,7 @@ export class LearningTargetRegistry {
|
|
|
52
54
|
let evalResult;
|
|
53
55
|
if (reg.promotionPolicy.requireHoldout) {
|
|
54
56
|
const hold = await reg.holdout();
|
|
55
|
-
evalResult = await reg.evaluator(candidate, hold);
|
|
57
|
+
evalResult = await reg.evaluator(candidate, hold, train);
|
|
56
58
|
candidate = { ...candidate, status: 'evaluated', evalResult };
|
|
57
59
|
}
|
|
58
60
|
const evidence = evalResult?.metrics.evidence ?? 0;
|
|
@@ -122,3 +124,92 @@ export function registerSkillTarget(registry, opts) {
|
|
|
122
124
|
lineage: { registeredAt: new Date().toISOString(), version: 1, source: opts.lineageSource ?? 'skill-compiler.mineWorkflows' },
|
|
123
125
|
});
|
|
124
126
|
}
|
|
127
|
+
export function registerAntiPatternTarget(registry, opts) {
|
|
128
|
+
registry.register({
|
|
129
|
+
target: 'tool',
|
|
130
|
+
trainer: async (plan, dataset) => ({
|
|
131
|
+
id: `anti-${plan.opportunityId}-${Math.random().toString(36).slice(2, 8)}`,
|
|
132
|
+
plan,
|
|
133
|
+
createdAt: new Date().toISOString(),
|
|
134
|
+
status: 'draft',
|
|
135
|
+
patterns: mineAntiPatterns(dataset.trajectories, opts.mining ?? {}),
|
|
136
|
+
}),
|
|
137
|
+
evaluator: async (candidate, holdout) => {
|
|
138
|
+
const top = candidate.patterns[0];
|
|
139
|
+
const failures = holdout.trajectories.filter((t) => !t.metrics.success);
|
|
140
|
+
const successes = holdout.trajectories.filter((t) => t.metrics.success);
|
|
141
|
+
if (!top) {
|
|
142
|
+
return { candidateId: candidate.id, pass: false, metrics: { evidence: 0, holdoutFailures: failures.length }, holdoutSize: holdout.trajectories.length };
|
|
143
|
+
}
|
|
144
|
+
const runIn = (t) => containsGram(t.steps.map((s) => s.action.type), top.pattern);
|
|
145
|
+
const detection = failures.length > 0 ? Number((failures.filter(runIn).length / failures.length).toFixed(3)) : 0;
|
|
146
|
+
const control = successes.length > 0 ? Number((successes.filter(runIn).length / successes.length).toFixed(3)) : 0;
|
|
147
|
+
const evidence = Number((detection - control).toFixed(3));
|
|
148
|
+
const pass = failures.length >= 2 && detection >= 0.5 && evidence > 0;
|
|
149
|
+
return {
|
|
150
|
+
candidateId: candidate.id,
|
|
151
|
+
pass,
|
|
152
|
+
metrics: { evidence, detection, control, holdoutFailures: failures.length, patternFailures: top.failures },
|
|
153
|
+
holdoutSize: holdout.trajectories.length,
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
holdout: opts.holdout,
|
|
157
|
+
promotionPolicy: { minEvidence: 0.5, requireHoldout: true, canaryShare: 0.2, ...opts.policy },
|
|
158
|
+
rollback: async () => undefined, // anti-pattern rollback = stop warning on it; the pattern history stays auditable
|
|
159
|
+
lineage: { registeredAt: new Date().toISOString(), version: 1, source: opts.lineageSource ?? 'skill-compiler.mineAntiPatterns' },
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function brierScoreOnly(wm, holdout, environmentId) {
|
|
163
|
+
let checked = 0;
|
|
164
|
+
let sum = 0;
|
|
165
|
+
for (const traj of holdout) {
|
|
166
|
+
if (traj.environment.id !== environmentId)
|
|
167
|
+
continue;
|
|
168
|
+
for (const step of traj.steps) {
|
|
169
|
+
const p = wm.predict({ action: step.action });
|
|
170
|
+
const binary = step.outcome === 'success' ? 1 : 0;
|
|
171
|
+
sum += (p.confidence - binary) ** 2;
|
|
172
|
+
checked++;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return { checked, brier: checked > 0 ? Number((sum / checked).toFixed(4)) : 0 };
|
|
176
|
+
}
|
|
177
|
+
export function registerWorldModelTarget(registry, opts) {
|
|
178
|
+
registry.register({
|
|
179
|
+
target: 'world_model',
|
|
180
|
+
trainer: async (plan, dataset) => {
|
|
181
|
+
const wm = replayIntoWorldModel(dataset.trajectories, opts.environmentId);
|
|
182
|
+
const st = wm.worldState;
|
|
183
|
+
const corrections = st.beliefs.reduce((s, b) => s + (b.corrections?.length ?? 0), 0);
|
|
184
|
+
return {
|
|
185
|
+
id: `wm-${plan.opportunityId}-${Math.random().toString(36).slice(2, 8)}`,
|
|
186
|
+
plan,
|
|
187
|
+
createdAt: new Date().toISOString(),
|
|
188
|
+
status: 'draft',
|
|
189
|
+
environmentId: opts.environmentId,
|
|
190
|
+
beliefs: st.beliefs.filter((b) => b.id.startsWith('act:')).length,
|
|
191
|
+
corrections,
|
|
192
|
+
};
|
|
193
|
+
},
|
|
194
|
+
evaluator: async (candidate, holdout, train) => {
|
|
195
|
+
// deterministic rebuild from the SAME train set the trainer used - the
|
|
196
|
+
// evaluator receives the train dataset by contract, so no smuggling
|
|
197
|
+
const trained = replayIntoWorldModel(train.trajectories, opts.environmentId);
|
|
198
|
+
const fresh = new WorldModel(opts.environmentId);
|
|
199
|
+
const t = brierScoreOnly(trained, holdout.trajectories, opts.environmentId);
|
|
200
|
+
const f = brierScoreOnly(fresh, holdout.trajectories, opts.environmentId);
|
|
201
|
+
const evidence = f.brier > 0 ? Number(((f.brier - t.brier) / f.brier).toFixed(3)) : 0;
|
|
202
|
+
const pass = t.checked >= 10 && t.brier < f.brier && evidence >= 0.5;
|
|
203
|
+
return {
|
|
204
|
+
candidateId: candidate.id,
|
|
205
|
+
pass,
|
|
206
|
+
metrics: { evidence, brierTrained: t.brier, brierFresh: f.brier, checked: t.checked },
|
|
207
|
+
holdoutSize: holdout.trajectories.length,
|
|
208
|
+
};
|
|
209
|
+
},
|
|
210
|
+
holdout: opts.holdout,
|
|
211
|
+
promotionPolicy: { minEvidence: 0.5, requireHoldout: true, canaryShare: 0.2, ...opts.policy },
|
|
212
|
+
rollback: async () => undefined, // world-model rollback = dropping the candidate model; the base model is never mutated in-place
|
|
213
|
+
lineage: { registeredAt: new Date().toISOString(), version: 1, source: opts.lineageSource ?? 'analysis.replayIntoWorldModel' },
|
|
214
|
+
});
|
|
215
|
+
}
|
package/dist/ledger.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
export type LedgerEventKind = 'belief.created' | 'belief.revised'
|
|
1
|
+
export type LedgerEventKind = 'belief.created' | 'belief.revised'
|
|
2
|
+
/** Ledger 2.0 (weekly pack 0.24 P0): the DAG vocabulary grows so the
|
|
3
|
+
* replayable cognitive graph can express supersession, contradiction,
|
|
4
|
+
* causal hypotheses, strategy changes and attribution results. */
|
|
5
|
+
| 'belief.superseded' | 'belief.contradicted' | 'causal.hypothesis' | 'strategy.changed' | 'credit.attribution' | 'prediction.made' | 'prediction.confirmed' | 'prediction.failed' | 'exploration.chosen' | 'observation.recorded' | 'skill.candidate' | 'skill.promoted' | 'skill.rejected' | 'memory.promoted' | 'memory.contradicted' | 'goal.revised' | 'model.routed' | 'capability.denied';
|
|
2
6
|
export interface LedgerEvent {
|
|
3
7
|
/** strictly monotonic per store; never reused */
|
|
4
8
|
readonly seq: number;
|
|
@@ -14,6 +18,8 @@ export interface LedgerEvent {
|
|
|
14
18
|
readonly confidence?: number;
|
|
15
19
|
/** the event this one answers or revises */
|
|
16
20
|
readonly parentSeq?: number;
|
|
21
|
+
/** Ledger 2.0: the version of the belief after this event (belief.* only) */
|
|
22
|
+
readonly beliefVersion?: number;
|
|
17
23
|
}
|
|
18
24
|
export interface LedgerSummary {
|
|
19
25
|
total: number;
|
|
@@ -28,6 +34,8 @@ export interface LedgerAppendInput {
|
|
|
28
34
|
taskId?: string;
|
|
29
35
|
confidence?: number;
|
|
30
36
|
parentSeq?: number;
|
|
37
|
+
/** Ledger 2.0: belief version after this event (belief.* kinds) */
|
|
38
|
+
beliefVersion?: number;
|
|
31
39
|
}
|
|
32
40
|
/** Pure in-memory append-only ledger. Rebuild from persistence with loadLedger. */
|
|
33
41
|
export declare class CognitiveLedger {
|
|
@@ -39,6 +47,9 @@ export declare class CognitiveLedger {
|
|
|
39
47
|
events(): readonly LedgerEvent[];
|
|
40
48
|
/** Lineage chain: the event with this seq plus every ancestor via parentSeq. */
|
|
41
49
|
chain(seq: number): LedgerEvent[];
|
|
50
|
+
/** Ledger 2.0: everything downstream of an event (the replay-from-cause
|
|
51
|
+
* query - what did this belief revision LEAD to?). Branches included. */
|
|
52
|
+
descendants(seq: number): LedgerEvent[];
|
|
42
53
|
summary(): LedgerSummary;
|
|
43
54
|
}
|
|
44
55
|
export declare function ledgerPath(home: string): string;
|
package/dist/ledger.js
CHANGED
|
@@ -38,6 +38,7 @@ export class CognitiveLedger {
|
|
|
38
38
|
...(input.taskId !== undefined ? { taskId: input.taskId } : {}),
|
|
39
39
|
...(input.confidence !== undefined ? { confidence: input.confidence } : {}),
|
|
40
40
|
...(input.parentSeq !== undefined ? { parentSeq: input.parentSeq } : {}),
|
|
41
|
+
...(input.beliefVersion !== undefined ? { beliefVersion: input.beliefVersion } : {}),
|
|
41
42
|
});
|
|
42
43
|
this.eventsBySeq.push(evt);
|
|
43
44
|
return evt;
|
|
@@ -76,6 +77,28 @@ export class CognitiveLedger {
|
|
|
76
77
|
}
|
|
77
78
|
return out;
|
|
78
79
|
}
|
|
80
|
+
/** Ledger 2.0: everything downstream of an event (the replay-from-cause
|
|
81
|
+
* query - what did this belief revision LEAD to?). Branches included. */
|
|
82
|
+
descendants(seq) {
|
|
83
|
+
const childrenOf = new Map();
|
|
84
|
+
for (const e of this.eventsBySeq) {
|
|
85
|
+
if (e.parentSeq === undefined)
|
|
86
|
+
continue;
|
|
87
|
+
const list = childrenOf.get(e.parentSeq) ?? [];
|
|
88
|
+
list.push(e);
|
|
89
|
+
childrenOf.set(e.parentSeq, list);
|
|
90
|
+
}
|
|
91
|
+
const out = [];
|
|
92
|
+
const queue = [seq];
|
|
93
|
+
while (queue.length) {
|
|
94
|
+
const cur = queue.shift();
|
|
95
|
+
for (const child of childrenOf.get(cur) ?? []) {
|
|
96
|
+
out.push(child);
|
|
97
|
+
queue.push(child.seq);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
79
102
|
summary() {
|
|
80
103
|
const byKind = {};
|
|
81
104
|
for (const e of this.eventsBySeq)
|
package/dist/skill-compiler.d.ts
CHANGED
|
@@ -54,6 +54,39 @@ export interface VerificationResult {
|
|
|
54
54
|
pass: boolean;
|
|
55
55
|
}>;
|
|
56
56
|
}
|
|
57
|
+
export interface SkillVariable {
|
|
58
|
+
name: string;
|
|
59
|
+
description?: string;
|
|
60
|
+
example?: string;
|
|
61
|
+
}
|
|
62
|
+
export interface SkillSpecV2 extends SkillSpec {
|
|
63
|
+
/** named variables the procedure binds (mined from args when available) */
|
|
64
|
+
variables?: SkillVariable[];
|
|
65
|
+
/** what the world should look like after a successful run */
|
|
66
|
+
expectedStateDelta?: Array<{
|
|
67
|
+
key: string;
|
|
68
|
+
change: string;
|
|
69
|
+
}>;
|
|
70
|
+
/** known counterexamples: situations where this skill MUST NOT fire */
|
|
71
|
+
counterexamples?: Array<{
|
|
72
|
+
description: string;
|
|
73
|
+
source: string;
|
|
74
|
+
}>;
|
|
75
|
+
/** where this skill came from - trajectory ids / miner + version */
|
|
76
|
+
provenance?: string;
|
|
77
|
+
/** miner-estimated confidence in [0,1] */
|
|
78
|
+
confidence?: number;
|
|
79
|
+
/** environments this skill is known to apply in */
|
|
80
|
+
environmentScope?: string[];
|
|
81
|
+
}
|
|
82
|
+
/** Honest adapter: a mined workflow becomes a V2 skill with EXACTLY the
|
|
83
|
+
* fields the data supports. Action-type n-grams cannot recover variable
|
|
84
|
+
* bindings or state deltas - those stay EMPTY (the Lab fills them when
|
|
85
|
+
* its analysis can), and empty is stated, never faked. */
|
|
86
|
+
export declare function toSkillSpecV2(candidate: WorkflowCandidate, opts?: {
|
|
87
|
+
provenance?: string;
|
|
88
|
+
environmentScope?: string[];
|
|
89
|
+
}): SkillSpecV2;
|
|
57
90
|
/** The benchmark surface the compiler verifies against — implemented by
|
|
58
91
|
* the environments/bench packages; kept as an interface for independence
|
|
59
92
|
* (evaluator independence rule: the compiler never grades its own work). */
|
package/dist/skill-compiler.js
CHANGED
|
@@ -10,6 +10,30 @@
|
|
|
10
10
|
* candidates.
|
|
11
11
|
*/
|
|
12
12
|
import { stableHash } from "./protocol.js";
|
|
13
|
+
/** Honest adapter: a mined workflow becomes a V2 skill with EXACTLY the
|
|
14
|
+
* fields the data supports. Action-type n-grams cannot recover variable
|
|
15
|
+
* bindings or state deltas - those stay EMPTY (the Lab fills them when
|
|
16
|
+
* its analysis can), and empty is stated, never faked. */
|
|
17
|
+
export function toSkillSpecV2(candidate, opts = {}) {
|
|
18
|
+
return {
|
|
19
|
+
id: `skill-${candidate.environmentId}-${candidate.steps.join('-').slice(0, 40)}`,
|
|
20
|
+
name: candidate.steps.slice(0, 3).join(' → '),
|
|
21
|
+
trigger: { environmentId: candidate.environmentId, actionTypes: candidate.steps },
|
|
22
|
+
preconditions: [],
|
|
23
|
+
procedure: candidate.steps.map((ref) => ({ kind: 'act', ref })),
|
|
24
|
+
verification: [],
|
|
25
|
+
evidence: candidate.trajectoryIds.map((id) => ({ trajectoryId: id, steps: 0, outcome: 'success' })),
|
|
26
|
+
version: '2.0.0',
|
|
27
|
+
status: 'candidate',
|
|
28
|
+
createdAt: new Date().toISOString(),
|
|
29
|
+
variables: [],
|
|
30
|
+
expectedStateDelta: [],
|
|
31
|
+
counterexamples: [],
|
|
32
|
+
provenance: opts.provenance ?? `mineWorkflows (support ${candidate.support})`,
|
|
33
|
+
confidence: Math.min(1, Number((candidate.support / 10).toFixed(2))),
|
|
34
|
+
environmentScope: opts.environmentScope ?? [candidate.environmentId],
|
|
35
|
+
};
|
|
36
|
+
}
|
|
13
37
|
export class SkillCompiler {
|
|
14
38
|
skills = new Map();
|
|
15
39
|
lastVerification = new Map();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hmharness/cognitive",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.30",
|
|
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.
|
|
29
|
+
"@hmharness/kernel": "0.23.30"
|
|
30
30
|
}
|
|
31
31
|
}
|