@hmharness/cognitive 0.23.11 → 0.23.12

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
@@ -271,6 +271,26 @@ export async function buildContextDigest(home, maxChars = 500) {
271
271
  if (trusted.length > 0) {
272
272
  lines.push(`Reliable tools: ${trusted.slice(0, 3).map((b) => b.actionType).join(', ')}.`);
273
273
  }
274
+ // crowd loop: for actions THIS machine has barely seen (<2 samples), the
275
+ // crowd prior is real information — a second user's win32/x64 experience
276
+ // with a tool beats a blind guess. Local evidence always dominates.
277
+ try {
278
+ const { loadCrowdPriors } = await import("./crowd.js");
279
+ const priors = await loadCrowdPriors(home);
280
+ if (priors.sources.length > 0) {
281
+ const localN = new Map(wm.beliefs.map((b) => [b.actionType, b.evidenceCount]));
282
+ const crowdKnown = Object.entries(priors.priors)
283
+ .filter(([key, p]) => key.endsWith('|' + key.split('|')[1]) && p.n >= 5)
284
+ .map(([key, p]) => ({ action: key.split('|')[1], n: p.n, rate: p.successRate }))
285
+ .filter((c) => (localN.get(c.action) ?? 0) < 2)
286
+ .sort((a, b) => b.n - a.n)
287
+ .slice(0, 3);
288
+ if (crowdKnown.length > 0) {
289
+ lines.push(`Crowd experience on similar machines: ${crowdKnown.map((c) => `${c.action} ~${Math.round(c.rate * 100)}%(n=${c.n})`).join(', ')}.`);
290
+ }
291
+ }
292
+ }
293
+ catch { /* crowd line is additive chrome */ }
274
294
  const { opportunities } = await diagnoseOpportunities(home);
275
295
  const opp = opportunities[0];
276
296
  if (opp)
@@ -0,0 +1,78 @@
1
+ export interface EnvironmentFingerprint {
2
+ os: string;
3
+ arch: string;
4
+ nodeMajor: number;
5
+ /** coarse shell family the agent's tools target (win: cmd, else unix) */
6
+ shell: 'cmd' | 'unix';
7
+ }
8
+ export declare function environmentFingerprint(): EnvironmentFingerprint;
9
+ /** two fingerprints are compatible when the load-bearing fields match:
10
+ * os+arch must be equal; release/node major may drift (tool behavior
11
+ * rarely flips on a Node minor). */
12
+ export declare function fingerprintCompatible(a: EnvironmentFingerprint, b: EnvironmentFingerprint): boolean;
13
+ export interface CrowdStat {
14
+ environmentId: string;
15
+ actionType: string;
16
+ n: number;
17
+ successRate: number;
18
+ meanDurationMs: number;
19
+ }
20
+ export interface CrowdSummary {
21
+ kind: 'hmharness-crowd-summary';
22
+ version: 1;
23
+ fingerprint: EnvironmentFingerprint;
24
+ generatedAt: string;
25
+ trajectoryCount: number;
26
+ stats: CrowdStat[];
27
+ }
28
+ /** Aggregate the local trajectory store into a content-free summary.
29
+ * Everything derived from step metadata ONLY (action type, outcome,
30
+ * duration) — a summary shared publicly cannot leak what you worked on. */
31
+ export declare function crowdSummary(home: string): Promise<CrowdSummary>;
32
+ /** Write the summary to a file (default: HMH_HOME/crowd-summary.json). */
33
+ export declare function writeCrowdSummary(home: string, outFile?: string): Promise<{
34
+ file: string;
35
+ summary: CrowdSummary;
36
+ }>;
37
+ export interface CrowdPriors {
38
+ kind: 'hmharness-crowd-priors';
39
+ version: 1;
40
+ /** sources absorbed so far (dedupe key: fingerprint + generatedAt) */
41
+ sources: Array<{
42
+ fingerprint: EnvironmentFingerprint;
43
+ generatedAt: string;
44
+ stats: number;
45
+ }>;
46
+ /** merged per (environment|action) prior; local evidence blends over it */
47
+ priors: Record<string, {
48
+ n: number;
49
+ successRate: number;
50
+ source: string;
51
+ }>;
52
+ }
53
+ /** Merge a crowd summary into the local prior store. Fingerprint-
54
+ * incompatible summaries are refused (return why) — a mismatched crowd
55
+ * would actively mislead this machine's world model. Re-absorbing the
56
+ * same source is a no-op (dedupe). */
57
+ export declare function absorbCrowdSummary(home: string, summaryFile: string): Promise<{
58
+ ok: boolean;
59
+ absorbed: number;
60
+ error?: string;
61
+ skipped?: string;
62
+ }>;
63
+ /** Load the local prior store for world-model seeding (used by the digest
64
+ * and explore runner). Returns {} when nothing was ever absorbed. */
65
+ export declare function loadCrowdPriors(home: string): Promise<CrowdPriors>;
66
+ /** Merge multiple crowd summaries into ONE pack for a fingerprint class
67
+ * (what a community publishes per environment, e.g. crowd/win32-x64.json):
68
+ * per-action stats are weighted by n, fingerprints must all be mutually
69
+ * compatible, and the pack carries the merged n so absorbers can weight it
70
+ * against their local evidence. The pack uses the summary format so
71
+ * `absorb` consumes it unchanged. */
72
+ export declare function mergeCrowdSummaries(summaries: CrowdSummary[]): {
73
+ ok: true;
74
+ pack: CrowdSummary;
75
+ } | {
76
+ ok: false;
77
+ error: string;
78
+ };
package/dist/crowd.js ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @hmharness/cognitive - crowd loop (federated-by-file first slice)
3
+ *
4
+ * The self-evolution loop is local-first: every user's world model, skills
5
+ * and calibration live in THEIR HMH_HOME and nothing phones home. This
6
+ * module is the privacy-safe bridge for users who WANT to contribute:
7
+ *
8
+ * crowdSummary(): an anonymous, content-free aggregate of the local
9
+ * trajectory store — per (environment × actionType) success rates and
10
+ * durations plus the machine's COARSE environment fingerprint
11
+ * (os/arch/node-major/shell-family). No task text, no paths, no args,
12
+ * no URLs — nothing that could identify the user or leak their work.
13
+ *
14
+ * absorbCrowdSummary(): the inverse — merge such a summary (shared by
15
+ * file, PR, or a future opt-in registry) into the local world model as
16
+ * PRIOR evidence, blended under local evidence so real experience on
17
+ * this machine always dominates. Priors only apply when the summary's
18
+ * fingerprint matches this machine's os+arch (a win32/x64 crowd stat
19
+ * must not steer a linux/arm64 user).
20
+ *
21
+ * Design rule: contribution is opt-in and offline by default — the file
22
+ * round-trip is the whole mechanism; there is no telemetry endpoint here.
23
+ */
24
+ import { readFile, writeFile } from 'node:fs/promises';
25
+ import { join } from 'node:path';
26
+ import { loadTrajectories } from "./analysis.js";
27
+ import { CognitiveMemory } from "./memory.js";
28
+ export function environmentFingerprint() {
29
+ return {
30
+ os: process.platform,
31
+ arch: process.arch,
32
+ nodeMajor: Number(process.versions.node.split('.')[0]) || 0,
33
+ shell: process.platform === 'win32' ? 'cmd' : 'unix',
34
+ };
35
+ }
36
+ /** two fingerprints are compatible when the load-bearing fields match:
37
+ * os+arch must be equal; release/node major may drift (tool behavior
38
+ * rarely flips on a Node minor). */
39
+ export function fingerprintCompatible(a, b) {
40
+ return a.os === b.os && a.arch === b.arch && a.shell === b.shell;
41
+ }
42
+ /** Aggregate the local trajectory store into a content-free summary.
43
+ * Everything derived from step metadata ONLY (action type, outcome,
44
+ * duration) — a summary shared publicly cannot leak what you worked on. */
45
+ export async function crowdSummary(home) {
46
+ const trajectories = await loadTrajectories(home, 10_000);
47
+ const table = new Map();
48
+ for (const traj of trajectories) {
49
+ for (const s of traj.steps) {
50
+ const key = `${traj.environment.id}|${s.action.type}`;
51
+ const agg = table.get(key) ?? { n: 0, ok: 0, ms: 0 };
52
+ agg.n += 1;
53
+ agg.ok += s.outcome === 'success' ? 1 : 0;
54
+ agg.ms += s.durationMs ?? 0;
55
+ table.set(key, agg);
56
+ }
57
+ }
58
+ const stats = [...table.entries()]
59
+ .map(([key, v]) => {
60
+ const [environmentId, actionType] = key.split('|');
61
+ return { environmentId, actionType, n: v.n, successRate: Number((v.ok / v.n).toFixed(3)), meanDurationMs: Math.round(v.ms / v.n) };
62
+ })
63
+ .sort((a, b) => b.n - a.n);
64
+ return {
65
+ kind: 'hmharness-crowd-summary',
66
+ version: 1,
67
+ fingerprint: environmentFingerprint(),
68
+ generatedAt: new Date().toISOString(),
69
+ trajectoryCount: trajectories.length,
70
+ stats,
71
+ };
72
+ }
73
+ /** Write the summary to a file (default: HMH_HOME/crowd-summary.json). */
74
+ export async function writeCrowdSummary(home, outFile) {
75
+ const summary = await crowdSummary(home);
76
+ const file = outFile ?? join(home, 'crowd-summary.json');
77
+ await writeFile(file, JSON.stringify(summary, null, 1), 'utf8');
78
+ return { file, summary };
79
+ }
80
+ async function readPriors(home) {
81
+ try {
82
+ const j = JSON.parse(await readFile(join(home, 'cognitive', 'crowd-priors.json'), 'utf8'));
83
+ if (j && j.kind === 'hmharness-crowd-priors' && j.priors && Array.isArray(j.sources))
84
+ return j;
85
+ }
86
+ catch { /* absent/corrupt = empty */ }
87
+ return { kind: 'hmharness-crowd-priors', version: 1, sources: [], priors: {} };
88
+ }
89
+ /** Merge a crowd summary into the local prior store. Fingerprint-
90
+ * incompatible summaries are refused (return why) — a mismatched crowd
91
+ * would actively mislead this machine's world model. Re-absorbing the
92
+ * same source is a no-op (dedupe). */
93
+ export async function absorbCrowdSummary(home, summaryFile) {
94
+ let summary;
95
+ try {
96
+ const raw = JSON.parse(await readFile(summaryFile, 'utf8'));
97
+ if (!raw || raw.kind !== 'hmharness-crowd-summary' || !Array.isArray(raw.stats) || !raw.fingerprint) {
98
+ return { ok: false, absorbed: 0, error: 'not a crowd summary (kind/version mismatch)' };
99
+ }
100
+ summary = raw;
101
+ }
102
+ catch (e) {
103
+ return { ok: false, absorbed: 0, error: 'unreadable file: ' + String(e).slice(0, 80) };
104
+ }
105
+ const mine = environmentFingerprint();
106
+ if (!fingerprintCompatible(mine, summary.fingerprint)) {
107
+ return { ok: false, absorbed: 0, skipped: `fingerprint mismatch: summary is ${summary.fingerprint.os}/${summary.fingerprint.arch}, this machine is ${mine.os}/${mine.arch}` };
108
+ }
109
+ const dedupeKey = `${summary.fingerprint.os}/${summary.fingerprint.arch}/n${summary.fingerprint.nodeMajor}@${summary.generatedAt}`;
110
+ const priors = await readPriors(home);
111
+ if (priors.sources.some((s) => `${s.fingerprint.os}/${s.fingerprint.arch}/n${s.fingerprint.nodeMajor}@${s.generatedAt}` === dedupeKey)) {
112
+ return { ok: true, absorbed: 0, skipped: 'source already absorbed (dedupe)' };
113
+ }
114
+ let absorbed = 0;
115
+ for (const st of summary.stats) {
116
+ const key = `${st.environmentId}|${st.actionType}`;
117
+ const prev = priors.priors[key];
118
+ if (!prev) {
119
+ priors.priors[key] = { n: st.n, successRate: st.successRate, source: dedupeKey };
120
+ }
121
+ else {
122
+ // weighted merge: bigger sample wins proportionally
123
+ const total = prev.n + st.n;
124
+ priors.priors[key] = {
125
+ n: total,
126
+ successRate: Number(((prev.successRate * prev.n + st.successRate * st.n) / total).toFixed(3)),
127
+ source: dedupeKey,
128
+ };
129
+ }
130
+ absorbed++;
131
+ }
132
+ priors.sources.push({ fingerprint: summary.fingerprint, generatedAt: summary.generatedAt, stats: summary.stats.length });
133
+ // best-effort dir + write
134
+ const { mkdir } = await import('node:fs/promises');
135
+ await mkdir(join(home, 'cognitive'), { recursive: true });
136
+ await writeFile(join(home, 'cognitive', 'crowd-priors.json'), JSON.stringify(priors, null, 1), 'utf8');
137
+ // episodic index entry so the contribution is auditable locally
138
+ const mem = new CognitiveMemory(home);
139
+ await mem.load();
140
+ await mem.write({
141
+ layer: 'semantic',
142
+ content: `CROWD-ABSORB ${absorbed} action stats from ${summary.fingerprint.os}/${summary.fingerprint.arch} (n=${summary.stats.reduce((s, x) => s + x.n, 0)} steps)`,
143
+ payload: { source: dedupeKey, stats: absorbed },
144
+ source: 'crowd-loop',
145
+ provenance: 'crowd-priors.json',
146
+ confidence: 0.6,
147
+ environment: 'terminal',
148
+ session: 'crowd',
149
+ tags: ['crowd', 'priors'],
150
+ }).catch(() => undefined);
151
+ return { ok: true, absorbed };
152
+ }
153
+ /** Load the local prior store for world-model seeding (used by the digest
154
+ * and explore runner). Returns {} when nothing was ever absorbed. */
155
+ export async function loadCrowdPriors(home) {
156
+ return readPriors(home);
157
+ }
158
+ /* ---------------- pack merging (community aggregation) ---------------- */
159
+ /** Merge multiple crowd summaries into ONE pack for a fingerprint class
160
+ * (what a community publishes per environment, e.g. crowd/win32-x64.json):
161
+ * per-action stats are weighted by n, fingerprints must all be mutually
162
+ * compatible, and the pack carries the merged n so absorbers can weight it
163
+ * against their local evidence. The pack uses the summary format so
164
+ * `absorb` consumes it unchanged. */
165
+ export function mergeCrowdSummaries(summaries) {
166
+ const valid = summaries.filter((s) => s && s.kind === 'hmharness-crowd-summary' && Array.isArray(s.stats) && s.fingerprint);
167
+ if (valid.length === 0)
168
+ return { ok: false, error: 'no valid crowd summaries to merge' };
169
+ const base = valid[0].fingerprint;
170
+ for (const s of valid) {
171
+ if (!fingerprintCompatible(base, s.fingerprint)) {
172
+ return { ok: false, error: `fingerprint class mismatch: refusing to mix ${s.fingerprint.os}/${s.fingerprint.arch} into ${base.os}/${base.arch} pack` };
173
+ }
174
+ }
175
+ const table = new Map();
176
+ for (const s of valid) {
177
+ for (const st of s.stats) {
178
+ const key = `${st.environmentId}|${st.actionType}`;
179
+ const agg = table.get(key) ?? { n: 0, ok: 0, ms: 0 };
180
+ agg.n += st.n;
181
+ agg.ok += st.successRate * st.n;
182
+ agg.ms += st.meanDurationMs * st.n;
183
+ table.set(key, agg);
184
+ }
185
+ }
186
+ const stats = [...table.entries()]
187
+ .map(([key, v]) => {
188
+ const [environmentId, actionType] = key.split('|');
189
+ return { environmentId, actionType, n: v.n, successRate: Number((v.ok / v.n).toFixed(3)), meanDurationMs: Math.round(v.ms / v.n) };
190
+ })
191
+ .sort((a, b) => b.n - a.n);
192
+ return {
193
+ ok: true,
194
+ pack: {
195
+ kind: 'hmharness-crowd-summary',
196
+ version: 1,
197
+ fingerprint: base,
198
+ generatedAt: `pack-${new Date().toISOString()}`,
199
+ trajectoryCount: valid.reduce((s, x) => s + x.trajectoryCount, 0),
200
+ stats,
201
+ },
202
+ };
203
+ }
package/dist/index.d.ts CHANGED
@@ -28,3 +28,4 @@ export * from './transfer-lab.js';
28
28
  export * from './abstract-actions.js';
29
29
  export * from './learning-loop.js';
30
30
  export * from './governance.js';
31
+ export * from './crowd.js';
package/dist/index.js CHANGED
@@ -28,3 +28,4 @@ export * from "./transfer-lab.js";
28
28
  export * from "./abstract-actions.js";
29
29
  export * from "./learning-loop.js";
30
30
  export * from "./governance.js";
31
+ export * from "./crowd.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cognitive",
3
- "version": "0.23.11",
3
+ "version": "0.23.12",
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.11"
29
+ "@hmharness/kernel": "0.23.12"
30
30
  }
31
31
  }