@hmharness/cognitive 0.23.16 → 0.23.18

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
  }
package/dist/crowd.d.ts CHANGED
@@ -60,6 +60,20 @@ export declare function absorbCrowdSummary(home: string, summaryFile: string): P
60
60
  error?: string;
61
61
  skipped?: string;
62
62
  }>;
63
+ /** Absorb a crowd pack from an https URL (e.g. the repo's crowd/ directory
64
+ * on raw.githubusercontent). Guards: https-only, 10s timeout, 2MB size cap,
65
+ * and the SAME content-free validation as local files — a fetched body is
66
+ * untrusted input exactly like a shared file. Opt-in by construction: this
67
+ * only runs when the user names the URL.
68
+ * Transport fallback: Node's global fetch fails on some networks where curl
69
+ * works (DNS resolution differences); on fetch failure we retry once via
70
+ * the system curl with the SAME https-only URL. */
71
+ export declare function absorbCrowdUrl(home: string, url: string): Promise<{
72
+ ok: boolean;
73
+ absorbed: number;
74
+ error?: string;
75
+ skipped?: string;
76
+ }>;
63
77
  /** Load the local prior store for world-model seeding (used by the digest
64
78
  * and explore runner). Returns {} when nothing was ever absorbed. */
65
79
  export declare function loadCrowdPriors(home: string): Promise<CrowdPriors>;
package/dist/crowd.js CHANGED
@@ -102,6 +102,10 @@ export async function absorbCrowdSummary(home, summaryFile) {
102
102
  catch (e) {
103
103
  return { ok: false, absorbed: 0, error: 'unreadable file: ' + String(e).slice(0, 80) };
104
104
  }
105
+ return absorbParsedSummary(home, summary);
106
+ }
107
+ /** Shared absorb path for file- and URL-sourced summaries. */
108
+ async function absorbParsedSummary(home, summary) {
105
109
  const mine = environmentFingerprint();
106
110
  if (!fingerprintCompatible(mine, summary.fingerprint)) {
107
111
  return { ok: false, absorbed: 0, skipped: `fingerprint mismatch: summary is ${summary.fingerprint.os}/${summary.fingerprint.arch}, this machine is ${mine.os}/${mine.arch}` };
@@ -150,6 +154,69 @@ export async function absorbCrowdSummary(home, summaryFile) {
150
154
  }).catch(() => undefined);
151
155
  return { ok: true, absorbed };
152
156
  }
157
+ /** Absorb a crowd pack from an https URL (e.g. the repo's crowd/ directory
158
+ * on raw.githubusercontent). Guards: https-only, 10s timeout, 2MB size cap,
159
+ * and the SAME content-free validation as local files — a fetched body is
160
+ * untrusted input exactly like a shared file. Opt-in by construction: this
161
+ * only runs when the user names the URL.
162
+ * Transport fallback: Node's global fetch fails on some networks where curl
163
+ * works (DNS resolution differences); on fetch failure we retry once via
164
+ * the system curl with the SAME https-only URL. */
165
+ export async function absorbCrowdUrl(home, url) {
166
+ let parsed;
167
+ try {
168
+ parsed = new URL(url);
169
+ }
170
+ catch {
171
+ return { ok: false, absorbed: 0, error: 'invalid URL' };
172
+ }
173
+ if (parsed.protocol !== 'https:') {
174
+ return { ok: false, absorbed: 0, error: 'https URLs only (no plain http, no file://)' };
175
+ }
176
+ let text = null;
177
+ let lastError = '';
178
+ try {
179
+ const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
180
+ if (!res.ok)
181
+ return { ok: false, absorbed: 0, error: `HTTP ${res.status}` };
182
+ const len = Number(res.headers.get('content-length') ?? '0');
183
+ if (len > 2_000_000)
184
+ return { ok: false, absorbed: 0, error: `pack too large (${len} bytes > 2MB cap)` };
185
+ text = await res.text();
186
+ }
187
+ catch (e) {
188
+ lastError = String(e).slice(0, 80);
189
+ }
190
+ if (text === null) {
191
+ // curl fallback (same https-only url; curl is stock on Win10+/Unix and
192
+ // resolves some networks' DNS differently than undici)
193
+ try {
194
+ const { spawnSync } = await import('node:child_process');
195
+ const r = spawnSync('curl', ['-s', '--max-time', '10', url], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
196
+ if (r.status === 0 && r.stdout)
197
+ text = r.stdout;
198
+ else
199
+ lastError = `fetch failed (${lastError}); curl fallback failed (exit ${r.status})`;
200
+ }
201
+ catch (e) {
202
+ lastError = `fetch failed (${lastError}); curl fallback unavailable: ${String(e).slice(0, 60)}`;
203
+ }
204
+ }
205
+ if (text === null)
206
+ return { ok: false, absorbed: 0, error: 'fetch failed: ' + lastError };
207
+ if (text.length > 2_000_000)
208
+ return { ok: false, absorbed: 0, error: 'pack too large (>2MB cap)' };
209
+ try {
210
+ const raw = JSON.parse(text);
211
+ if (!raw || raw.kind !== 'hmharness-crowd-summary' || !Array.isArray(raw.stats) || !raw.fingerprint) {
212
+ return { ok: false, absorbed: 0, error: 'not a crowd summary (kind/version mismatch)' };
213
+ }
214
+ return await absorbParsedSummary(home, raw);
215
+ }
216
+ catch (e) {
217
+ return { ok: false, absorbed: 0, error: 'unparseable body: ' + String(e).slice(0, 80) };
218
+ }
219
+ }
153
220
  /** Load the local prior store for world-model seeding (used by the digest
154
221
  * and explore runner). Returns {} when nothing was ever absorbed. */
155
222
  export async function loadCrowdPriors(home) {
@@ -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.18",
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.18"
30
+ }
31
+ }