@hmharness/cognitive 0.23.29 → 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.
@@ -1,6 +1,10 @@
1
1
  export const CONTRIBUTOR_KINDS = [
2
2
  'belief.created',
3
3
  'belief.revised',
4
+ 'belief.superseded',
5
+ 'belief.contradicted',
6
+ 'causal.hypothesis',
7
+ 'strategy.changed',
4
8
  'exploration.chosen',
5
9
  'skill.candidate',
6
10
  'skill.promoted',
@@ -25,7 +25,7 @@
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
31
  * the exact training set; evaluators that don't care ignore the 3rd arg. */
@@ -92,6 +92,18 @@ export declare function registerSkillTarget(registry: LearningTargetRegistry, op
92
92
  policy?: Partial<PromotionPolicy>;
93
93
  lineageSource?: string;
94
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;
95
107
  export interface WorldModelCandidate extends Candidate {
96
108
  environmentId: string;
97
109
  beliefs: number;
@@ -1,5 +1,5 @@
1
1
  import { evidenceThreshold } from "./continual.js";
2
- import { mineWorkflows } from "./skill-compiler.js";
2
+ import { mineWorkflows, mineAntiPatterns } from "./skill-compiler.js";
3
3
  import { WorldModel } from "./world-model.js";
4
4
  import { replayIntoWorldModel } from "./analysis.js";
5
5
  const REQUIRED_FIELDS = ['trainer', 'evaluator', 'holdout', 'promotionPolicy', 'rollback', 'lineage'];
@@ -124,6 +124,41 @@ export function registerSkillTarget(registry, opts) {
124
124
  lineage: { registeredAt: new Date().toISOString(), version: 1, source: opts.lineageSource ?? 'skill-compiler.mineWorkflows' },
125
125
  });
126
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
+ }
127
162
  function brierScoreOnly(wm, holdout, environmentId) {
128
163
  let checked = 0;
129
164
  let sum = 0;
package/dist/ledger.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- export type LedgerEventKind = 'belief.created' | 'belief.revised' | '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';
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)
@@ -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). */
@@ -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.29",
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"
29
+ "@hmharness/kernel": "0.23.30"
30
30
  }
31
31
  }