@hmharness/cognitive 0.23.11 → 0.23.13
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 +20 -0
- package/dist/crowd.d.ts +78 -0
- package/dist/crowd.js +203 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/rlm-sandbox.d.ts +21 -0
- package/dist/rlm-sandbox.js +90 -0
- package/dist/rlm.d.ts +4 -2
- package/dist/rlm.js +24 -24
- package/package.json +2 -2
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)
|
package/dist/crowd.d.ts
ADDED
|
@@ -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
|
@@ -15,6 +15,8 @@ export * from './world-model.js';
|
|
|
15
15
|
export * from './goal.js';
|
|
16
16
|
export * from './exploration.js';
|
|
17
17
|
export * from './rlm.js';
|
|
18
|
+
export { runSandboxedEval } from './rlm-sandbox.js';
|
|
19
|
+
export type { SandboxResult, SandboxOptions } from './rlm-sandbox.js';
|
|
18
20
|
export * from './memory.js';
|
|
19
21
|
export * from './skill-compiler.js';
|
|
20
22
|
export * from './continual.js';
|
|
@@ -28,3 +30,4 @@ export * from './transfer-lab.js';
|
|
|
28
30
|
export * from './abstract-actions.js';
|
|
29
31
|
export * from './learning-loop.js';
|
|
30
32
|
export * from './governance.js';
|
|
33
|
+
export * from './crowd.js';
|
package/dist/index.js
CHANGED
|
@@ -15,6 +15,7 @@ export * from "./world-model.js";
|
|
|
15
15
|
export * from "./goal.js";
|
|
16
16
|
export * from "./exploration.js";
|
|
17
17
|
export * from "./rlm.js";
|
|
18
|
+
export { runSandboxedEval } from "./rlm-sandbox.js";
|
|
18
19
|
export * from "./memory.js";
|
|
19
20
|
export * from "./skill-compiler.js";
|
|
20
21
|
export * from "./continual.js";
|
|
@@ -28,3 +29,4 @@ export * from "./transfer-lab.js";
|
|
|
28
29
|
export * from "./abstract-actions.js";
|
|
29
30
|
export * from "./learning-loop.js";
|
|
30
31
|
export * from "./governance.js";
|
|
32
|
+
export * from "./crowd.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface SandboxResult {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
value?: unknown;
|
|
4
|
+
error?: {
|
|
5
|
+
code: string;
|
|
6
|
+
message: string;
|
|
7
|
+
};
|
|
8
|
+
durationMs: number;
|
|
9
|
+
terminated: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface SandboxOptions {
|
|
12
|
+
/** hard per-eval wall; the worker is terminated past it (default 15s) */
|
|
13
|
+
timeoutMs?: number;
|
|
14
|
+
/** worker heap caps (defaults below) */
|
|
15
|
+
maxOldGenerationSizeMb?: number;
|
|
16
|
+
maxYoungGenerationSizeMb?: number;
|
|
17
|
+
}
|
|
18
|
+
/** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
|
|
19
|
+
* are coarse-grained (composing workspace variables), so per-eval spawn
|
|
20
|
+
* overhead (~10-30ms) is acceptable for real isolation each time. */
|
|
21
|
+
export declare function runSandboxedEval(code: string, vars: Record<string, unknown>, meta: Record<string, unknown>, opts?: SandboxOptions): Promise<SandboxResult>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - RLM sandbox (review P0-1 / RLM-001..004, 2026-10-03)
|
|
3
|
+
*
|
|
4
|
+
* RLM eval code used to run through `new Function` in the MAIN process:
|
|
5
|
+
* full authority (globals, dynamic import, process), only budget-counted.
|
|
6
|
+
* This module moves eval into a worker_threads Worker with real walls:
|
|
7
|
+
*
|
|
8
|
+
* - crash containment: a throwing/OOM-ing eval cannot take the host down
|
|
9
|
+
* - termination: infinite loops are killed at the timeout (terminate())
|
|
10
|
+
* - secret isolation: the worker is created with `env: {}` — API keys in
|
|
11
|
+
* the host environment are NEVER inherited (RLM-002 security rule)
|
|
12
|
+
* - memory ceiling: resourceLimits cap the worker heap
|
|
13
|
+
* - shadowed surface: process/require are undefined inside the eval scope
|
|
14
|
+
*
|
|
15
|
+
* HONEST limits (documented, not hidden): a worker is a containment boundary,
|
|
16
|
+
* NOT a cryptographic sandbox — determined code may still reach Node
|
|
17
|
+
* internals. The walls above are real against the failure modes that
|
|
18
|
+
* actually happen (bugs, loops, leaks, secret inheritance); malicious
|
|
19
|
+
* capability escalation is the Capability OS layer's job, not this one.
|
|
20
|
+
*/
|
|
21
|
+
import { Worker } from 'node:worker_threads';
|
|
22
|
+
/** The worker bootstrap source. Runs as CommonJS, receives {code, vars, meta}
|
|
23
|
+
* through workerData (structured-cloned at spawn), executes the code as an
|
|
24
|
+
* async function body with a frozen ctx, and posts the result back.
|
|
25
|
+
* Shadows the dangerous globals at function-constructor scope so casual
|
|
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
|
+
})();
|
|
40
|
+
`;
|
|
41
|
+
/** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
|
|
42
|
+
* are coarse-grained (composing workspace variables), so per-eval spawn
|
|
43
|
+
* overhead (~10-30ms) is acceptable for real isolation each time. */
|
|
44
|
+
export function runSandboxedEval(code, vars, meta, opts = {}) {
|
|
45
|
+
const started = Date.now();
|
|
46
|
+
const timeoutMs = opts.timeoutMs ?? 15_000;
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
let settled = false;
|
|
49
|
+
let worker;
|
|
50
|
+
try {
|
|
51
|
+
worker = new Worker(WORKER_SOURCE, {
|
|
52
|
+
eval: true,
|
|
53
|
+
workerData: { code, vars, meta }, // structured-cloned at spawn — no message race
|
|
54
|
+
env: {}, // secrets never inherit (RLM-002)
|
|
55
|
+
stdout: true,
|
|
56
|
+
stderr: true,
|
|
57
|
+
resourceLimits: {
|
|
58
|
+
maxOldGenerationSizeMb: opts.maxOldGenerationSizeMb ?? 256,
|
|
59
|
+
maxYoungGenerationSizeMb: opts.maxYoungGenerationSizeMb ?? 64,
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
resolve({ ok: false, error: { code: 'E_SANDBOX_SPAWN', message: String(err).slice(0, 200) }, durationMs: Date.now() - started, terminated: false });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const finish = (r) => {
|
|
68
|
+
if (settled)
|
|
69
|
+
return;
|
|
70
|
+
settled = true;
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
worker.terminate().catch(() => undefined);
|
|
73
|
+
resolve(r);
|
|
74
|
+
};
|
|
75
|
+
const timer = setTimeout(() => {
|
|
76
|
+
finish({ ok: false, error: { code: 'E_SANDBOX_TIMEOUT', message: `eval exceeded ${timeoutMs}ms and was terminated` }, durationMs: Date.now() - started, terminated: true });
|
|
77
|
+
}, timeoutMs);
|
|
78
|
+
worker.on('message', (m) => {
|
|
79
|
+
finish({ ok: m.ok, value: m.value, error: m.error, durationMs: Date.now() - started, terminated: false });
|
|
80
|
+
});
|
|
81
|
+
worker.on('error', (err) => {
|
|
82
|
+
finish({ ok: false, error: { code: 'E_SANDBOX_CRASH', message: String(err.message || err).slice(0, 200) }, durationMs: Date.now() - started, terminated: false });
|
|
83
|
+
});
|
|
84
|
+
worker.on('exit', (code) => {
|
|
85
|
+
if (!settled) {
|
|
86
|
+
finish({ ok: false, error: { code: 'E_SANDBOX_EXIT', message: `worker exited early (code ${code})` }, durationMs: Date.now() - started, terminated: false });
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
}
|
package/dist/rlm.d.ts
CHANGED
|
@@ -71,8 +71,10 @@ export declare class RLMRuntime {
|
|
|
71
71
|
set(name: string, value: RLMValue): void;
|
|
72
72
|
get(name: string): RLMValue;
|
|
73
73
|
names(): string[];
|
|
74
|
-
/** RLM-003.
|
|
75
|
-
*
|
|
74
|
+
/** RLM-003 / review P0-1. Eval runs in a SANDBOXED WORKER per call: crash
|
|
75
|
+
* containment, timeout termination, secret-free env, memory caps (see
|
|
76
|
+
* rlm-sandbox.ts). Budget checks stay in the host; ctx is frozen inside
|
|
77
|
+
* the worker so governance state (meta) cannot be mutated from eval. */
|
|
76
78
|
eval(code: string, ctx?: Partial<RLMContext>): Promise<RLMResult>;
|
|
77
79
|
/** RLM-004/005. Checkpoint the whole workspace (vars + log + budget). */
|
|
78
80
|
checkpoint(label?: string): RLMCheckpoint;
|
package/dist/rlm.js
CHANGED
|
@@ -3,13 +3,15 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A programmable cognitive workbench: context, memory snippets, environment
|
|
5
5
|
* state, predictions, subagent handles and validators are ADDRESSABLE
|
|
6
|
-
* VARIABLES the (host) program composes.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* VARIABLES the (host) program composes. Eval code runs in a SANDBOXED
|
|
7
|
+
* WORKER (rlm-sandbox.ts, review P0-1 2026-10-03): crash containment,
|
|
8
|
+
* timeout termination, secret-free env, memory caps. The runtime provides
|
|
9
|
+
* budget accounting, checkpoints and forks; it does NOT allow hidden
|
|
10
|
+
* unsafe self-modification: eval code can only touch workspace variables,
|
|
11
|
+
* never the runtime's own governance state (RLM-008).
|
|
11
12
|
*/
|
|
12
13
|
import { stableHash } from "./protocol.js";
|
|
14
|
+
import { runSandboxedEval } from "./rlm-sandbox.js";
|
|
13
15
|
export class RLMRuntime {
|
|
14
16
|
budget;
|
|
15
17
|
host;
|
|
@@ -46,8 +48,10 @@ export class RLMRuntime {
|
|
|
46
48
|
names() {
|
|
47
49
|
return Object.keys(this.vars);
|
|
48
50
|
}
|
|
49
|
-
/** RLM-003.
|
|
50
|
-
*
|
|
51
|
+
/** RLM-003 / review P0-1. Eval runs in a SANDBOXED WORKER per call: crash
|
|
52
|
+
* containment, timeout termination, secret-free env, memory caps (see
|
|
53
|
+
* rlm-sandbox.ts). Budget checks stay in the host; ctx is frozen inside
|
|
54
|
+
* the worker so governance state (meta) cannot be mutated from eval. */
|
|
51
55
|
async eval(code, ctx) {
|
|
52
56
|
const started = Date.now();
|
|
53
57
|
const budget = this.materializeBudget();
|
|
@@ -58,24 +62,20 @@ export class RLMRuntime {
|
|
|
58
62
|
return { ok: false, error: { code: 'E_BUDGET_WALL', message: `wall-clock budget exhausted (${budget.maxWallMs}ms)` }, durationMs: 0, budget };
|
|
59
63
|
}
|
|
60
64
|
this._evals += 1;
|
|
61
|
-
const meta =
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
this.log.push(`eval ok (${Date.now() - started}ms)`);
|
|
68
|
-
return { ok: true, value: resolved, durationMs: Date.now() - started, budget: this.materializeBudget() };
|
|
69
|
-
}
|
|
70
|
-
catch (err) {
|
|
71
|
-
this.log.push(`eval fail: ${String(err).slice(0, 120)}`);
|
|
72
|
-
return {
|
|
73
|
-
ok: false,
|
|
74
|
-
error: { code: 'E_EVAL', message: err instanceof Error ? err.message : String(err) },
|
|
75
|
-
durationMs: Date.now() - started,
|
|
76
|
-
budget: this.materializeBudget(),
|
|
77
|
-
};
|
|
65
|
+
const meta = { evalsUsed: this._evals, subagentsUsed: this.subagents.length, checkpointCount: this.checkpoints.length };
|
|
66
|
+
const merged = ctx?.vars ? { ...ctx.vars } : { ...this.vars };
|
|
67
|
+
const r = await runSandboxedEval(code, merged, meta, { timeoutMs: Math.min(15_000, Math.max(1_000, budget.maxWallMs - budget.used.wallMs)) });
|
|
68
|
+
if (r.ok) {
|
|
69
|
+
this.log.push(`eval ok (${r.durationMs}ms)`);
|
|
70
|
+
return { ok: true, value: r.value, durationMs: Date.now() - started, budget: this.materializeBudget() };
|
|
78
71
|
}
|
|
72
|
+
this.log.push(`eval fail: ${r.error?.code} ${String(r.error?.message).slice(0, 80)}`);
|
|
73
|
+
return {
|
|
74
|
+
ok: false,
|
|
75
|
+
error: r.error ?? { code: 'E_EVAL', message: 'unknown sandbox failure' },
|
|
76
|
+
durationMs: Date.now() - started,
|
|
77
|
+
budget: this.materializeBudget(),
|
|
78
|
+
};
|
|
79
79
|
}
|
|
80
80
|
/** RLM-004/005. Checkpoint the whole workspace (vars + log + budget). */
|
|
81
81
|
checkpoint(label) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hmharness/cognitive",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.13",
|
|
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.13"
|
|
30
30
|
}
|
|
31
31
|
}
|