@hmharness/cognitive 0.23.16 → 0.23.17

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/analysis.js CHANGED
@@ -351,11 +351,26 @@ export async function skillCandidatesFromHistory(home, opts) {
351
351
  const compiler = new SkillCompiler();
352
352
  const trajectories = await loadTrajectories(home);
353
353
  const candidates = await compiler.compile(trajectories, opts);
354
- return candidates.map((c) => ({
355
- id: c.id,
356
- name: c.name,
357
- procedure: c.procedure.map((s) => s.ref),
358
- evidenceTrajectories: c.evidence.length,
359
- status: c.status,
354
+ // W10 wiring: n-gram workflow candidates join the SAME pool — they flow
355
+ // into the evolve bench pipeline (promotion gates) like any candidate;
356
+ // nothing here promotes anything (evaluator independence)
357
+ const { mineWorkflows } = await import("./skill-compiler.js");
358
+ const workflows = mineWorkflows(trajectories, { minSupport: opts?.minRepeat ?? 2 });
359
+ const fromWorkflows = workflows.map((w) => ({
360
+ id: `wf-${w.steps.join('_')}`,
361
+ name: `workflow: ${w.steps.join(' → ')} (${w.environmentId})`,
362
+ procedure: w.steps,
363
+ evidenceTrajectories: w.support,
364
+ status: 'candidate',
360
365
  }));
366
+ return [
367
+ ...candidates.map((c) => ({
368
+ id: c.id,
369
+ name: c.name,
370
+ procedure: c.procedure.map((s) => s.ref),
371
+ evidenceTrajectories: c.evidence.length,
372
+ status: c.status,
373
+ })),
374
+ ...fromWorkflows,
375
+ ];
361
376
  }
@@ -24,19 +24,19 @@ import { Worker } from 'node:worker_threads';
24
24
  * async function body with a frozen ctx, and posts the result back.
25
25
  * Shadows the dangerous globals at function-constructor scope so casual
26
26
  * access fails loudly. */
27
- const WORKER_SOURCE = `
28
- const { parentPort, workerData } = require('node:worker_threads');
29
- (async () => {
30
- const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
31
- try {
32
- const process = undefined, require = undefined;
33
- const fn = new Function('ctx', 'process', 'require', '"use strict";return (async()=>{' + workerData.code + '})();');
34
- const value = await fn(ctx, undefined, undefined);
35
- parentPort.postMessage({ ok: true, value });
36
- } catch (err) {
37
- parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
38
- }
39
- })();
27
+ const WORKER_SOURCE = `
28
+ const { parentPort, workerData } = require('node:worker_threads');
29
+ (async () => {
30
+ const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
31
+ try {
32
+ const process = undefined, require = undefined;
33
+ const fn = new Function('ctx', 'process', 'require', '"use strict";return (async()=>{' + workerData.code + '})();');
34
+ const value = await fn(ctx, undefined, undefined);
35
+ parentPort.postMessage({ ok: true, value });
36
+ } catch (err) {
37
+ parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
38
+ }
39
+ })();
40
40
  `;
41
41
  /** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
42
42
  * are coarse-grained (composing workspace variables), so per-eval spawn
@@ -79,3 +79,37 @@ export declare class SkillCompiler {
79
79
  /** SK-008. Rollback is always allowed. */
80
80
  rollback(skillId: string): Promise<void>;
81
81
  }
82
+ export interface WorkflowCandidate {
83
+ /** the consecutive action-type n-gram (the workflow body) */
84
+ steps: string[];
85
+ /** distinct successful trajectories containing the n-gram */
86
+ support: number;
87
+ trajectoryIds: string[];
88
+ /** environment of the supporting episodes */
89
+ environmentId: string;
90
+ }
91
+ /** Mine frequent consecutive action n-grams (n within [nMin,nMax]) across
92
+ * SUCCESSFUL trajectories, keeping only MAXIMAL ones (an n-gram fully
93
+ * contained in a longer supported n-gram of the same episodes adds nothing).
94
+ * This generalizes compile()'s exact full-sequence matching: a workflow
95
+ * survives when one episode has an extra step somewhere. */
96
+ export declare function mineWorkflows(experiences: CognitiveTrajectory[], opts?: {
97
+ minSupport?: number;
98
+ nMin?: number;
99
+ nMax?: number;
100
+ }): WorkflowCandidate[];
101
+ export interface AntiPattern {
102
+ /** the action-type sequence that reliably PRECEDES failure */
103
+ pattern: string[];
104
+ /** failed trajectories ending right after this sequence */
105
+ failures: number;
106
+ trajectoryIds: string[];
107
+ warning: string;
108
+ }
109
+ /** Mine failure anti-patterns: consecutive action runs that immediately
110
+ * precede the END of FAILED trajectories. These become warnings attached to
111
+ * skills (knowledge about what NOT to do), never procedures. */
112
+ export declare function mineAntiPatterns(experiences: CognitiveTrajectory[], opts?: {
113
+ minFailures?: number;
114
+ nMax?: number;
115
+ }): AntiPattern[];
@@ -100,6 +100,71 @@ export class SkillCompiler {
100
100
  s.status = 'rolled-back';
101
101
  }
102
102
  }
103
+ /** Mine frequent consecutive action n-grams (n within [nMin,nMax]) across
104
+ * SUCCESSFUL trajectories, keeping only MAXIMAL ones (an n-gram fully
105
+ * contained in a longer supported n-gram of the same episodes adds nothing).
106
+ * This generalizes compile()'s exact full-sequence matching: a workflow
107
+ * survives when one episode has an extra step somewhere. */
108
+ export function mineWorkflows(experiences, opts = {}) {
109
+ const minSupport = opts.minSupport ?? 2;
110
+ const nMin = opts.nMin ?? 2;
111
+ const nMax = opts.nMax ?? 4;
112
+ const table = new Map();
113
+ for (const traj of experiences) {
114
+ if (!traj.metrics.success)
115
+ continue;
116
+ const seq = traj.steps.filter((s) => s.outcome === 'success').map((s) => s.action.type);
117
+ for (let n = nMin; n <= Math.min(nMax, seq.length); n++) {
118
+ for (let i = 0; i + n <= seq.length; i++) {
119
+ const gram = seq.slice(i, i + n);
120
+ const key = gram.join('|');
121
+ const agg = table.get(key) ?? { steps: gram, trajs: new Set(), env: traj.environment.id };
122
+ agg.trajs.add(traj.id);
123
+ table.set(key, agg);
124
+ }
125
+ }
126
+ }
127
+ const supported = [...table.entries()]
128
+ .filter(([, v]) => v.trajs.size >= minSupport)
129
+ .map(([key, v]) => ({ key, steps: v.steps, support: v.trajs.size, trajectoryIds: [...v.trajs], environmentId: v.env }));
130
+ // maximality: drop grams whose key is a contiguous substring of a longer
131
+ // supported gram with support from a superset of episodes
132
+ const kept = supported.filter((c) => {
133
+ return !supported.some((d) => d !== c && d.steps.length > c.steps.length && d.key.includes(c.key) && d.support >= c.support);
134
+ });
135
+ return kept.sort((a, b) => b.steps.length - a.steps.length || b.support - a.support);
136
+ }
137
+ /** Mine failure anti-patterns: consecutive action runs that immediately
138
+ * precede the END of FAILED trajectories. These become warnings attached to
139
+ * skills (knowledge about what NOT to do), never procedures. */
140
+ export function mineAntiPatterns(experiences, opts = {}) {
141
+ const minFailures = opts.minFailures ?? 2;
142
+ const nMax = opts.nMax ?? 3;
143
+ const table = new Map();
144
+ for (const traj of experiences) {
145
+ if (traj.metrics.success)
146
+ continue;
147
+ const seq = traj.steps.map((s) => s.action.type);
148
+ if (seq.length === 0)
149
+ continue;
150
+ for (let n = 1; n <= Math.min(nMax, seq.length); n++) {
151
+ const gram = seq.slice(seq.length - n);
152
+ const key = gram.join('|');
153
+ const agg = table.get(key) ?? { steps: gram, trajs: new Set() };
154
+ agg.trajs.add(traj.id);
155
+ table.set(key, agg);
156
+ }
157
+ }
158
+ const all = [...table.entries()]
159
+ .filter(([, v]) => v.trajs.size >= minFailures)
160
+ .map(([key, v]) => ({ key, steps: v.steps, failures: v.trajs.size, trajectoryIds: [...v.trajs] }));
161
+ // maximality (same rule as workflows): drop a gram fully contained in a
162
+ // longer supported gram — the longer one carries the actionable context
163
+ const kept = all.filter((c) => !all.some((d) => d !== c && d.steps.length > c.steps.length && d.key.endsWith(c.key) && d.failures >= c.failures));
164
+ return kept
165
+ .map((c) => ({ pattern: c.steps, failures: c.failures, trajectoryIds: c.trajectoryIds, warning: `avoid ${c.key}: preceded the failure end in ${c.failures} failed runs` }))
166
+ .sort((a, b) => b.failures - a.failures || b.pattern.length - a.pattern.length);
167
+ }
103
168
  function longestSuccessfulRun(traj) {
104
169
  let best = [];
105
170
  let cur = [];
package/package.json CHANGED
@@ -1,31 +1,31 @@
1
- {
2
- "name": "@hmharness/cognitive",
3
- "version": "0.23.16",
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
- "type": "module",
6
- "main": "dist/index.js",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "default": "./dist/index.js"
11
- }
12
- },
13
- "types": "dist/index.d.ts",
14
- "scripts": {
15
- "build": "tsc -p tsconfig.build.json"
16
- },
17
- "files": [
18
- "dist"
19
- ],
20
- "license": "MIT",
21
- "repository": {
22
- "type": "git",
23
- "url": "git+https://github.com/swsgbl/hmharness.git"
24
- },
25
- "engines": {
26
- "node": ">=22"
27
- },
28
- "dependencies": {
29
- "@hmharness/kernel": "0.23.16"
30
- }
31
- }
1
+ {
2
+ "name": "@hmharness/cognitive",
3
+ "version": "0.23.17",
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
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "types": "dist/index.d.ts",
14
+ "scripts": {
15
+ "build": "tsc -p tsconfig.build.json"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/swsgbl/hmharness.git"
24
+ },
25
+ "engines": {
26
+ "node": ">=22"
27
+ },
28
+ "dependencies": {
29
+ "@hmharness/kernel": "0.23.17"
30
+ }
31
+ }