@hmharness/cognitive 0.19.0
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/benchmark.d.ts +80 -0
- package/dist/benchmark.js +85 -0
- package/dist/continual.d.ts +90 -0
- package/dist/continual.js +142 -0
- package/dist/evolution2.d.ts +93 -0
- package/dist/evolution2.js +181 -0
- package/dist/exploration.d.ts +106 -0
- package/dist/exploration.js +182 -0
- package/dist/goal.d.ts +97 -0
- package/dist/goal.js +133 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +24 -0
- package/dist/memory.d.ts +64 -0
- package/dist/memory.js +200 -0
- package/dist/multi-agent.d.ts +118 -0
- package/dist/multi-agent.js +119 -0
- package/dist/protocol.d.ts +155 -0
- package/dist/protocol.js +103 -0
- package/dist/registry.d.ts +75 -0
- package/dist/registry.js +195 -0
- package/dist/rlm.d.ts +88 -0
- package/dist/rlm.js +139 -0
- package/dist/skill-compiler.d.ts +81 -0
- package/dist/skill-compiler.js +124 -0
- package/dist/status.d.ts +20 -0
- package/dist/status.js +76 -0
- package/dist/trajectory.d.ts +54 -0
- package/dist/trajectory.js +112 -0
- package/dist/world-model.d.ts +146 -0
- package/dist/world-model.js +219 -0
- package/package.json +31 -0
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - protocol (blueprint §1 Environment API + §22 interfaces)
|
|
3
|
+
*
|
|
4
|
+
* THE contract everything else builds on. An environment is an observable,
|
|
5
|
+
* actionable, snapshotable, restorable, evaluable world. Protocol-first
|
|
6
|
+
* discipline: these types + validateAction/validateObservation ship and are
|
|
7
|
+
* tested BEFORE any concrete environment exists (master prompt rule: schema
|
|
8
|
+
* and runtime validation are separated, and no capability is declared that
|
|
9
|
+
* is not executable).
|
|
10
|
+
*
|
|
11
|
+
* Hard rules encoded here:
|
|
12
|
+
* - every Observation carries availableActions (the agent may only choose
|
|
13
|
+
* from what the environment declared — no invented affordances)
|
|
14
|
+
* - every ActionResult is success|failure|unknown with structured errors
|
|
15
|
+
* (blueprint: all errors must have a structured code)
|
|
16
|
+
* - Snapshot carries a stateHash so replay/restore can detect divergence
|
|
17
|
+
* - evaluate() is the environment's own voice, never the only judge
|
|
18
|
+
* (evaluator independence is enforced upstream in evolution2.ts)
|
|
19
|
+
*/
|
|
20
|
+
export const TRAJECTORY_SCHEMA_VERSION = 1;
|
|
21
|
+
/* ---- runtime validation (schema and runtime validation are separated) ---- */
|
|
22
|
+
export function validateAction(a) {
|
|
23
|
+
const errors = [];
|
|
24
|
+
if (typeof a !== 'object' || a === null)
|
|
25
|
+
return { valid: false, errors: ['action must be an object'] };
|
|
26
|
+
const o = a;
|
|
27
|
+
if (typeof o.id !== 'string' || !o.id)
|
|
28
|
+
errors.push('action.id must be a non-empty string');
|
|
29
|
+
if (typeof o.type !== 'string' || !o.type)
|
|
30
|
+
errors.push('action.type must be a non-empty string');
|
|
31
|
+
if (typeof o.args !== 'object' || o.args === null || Array.isArray(o.args))
|
|
32
|
+
errors.push('action.args must be an object');
|
|
33
|
+
if (o.reason !== undefined && typeof o.reason !== 'string')
|
|
34
|
+
errors.push('action.reason must be a string when present');
|
|
35
|
+
return { valid: errors.length === 0, errors };
|
|
36
|
+
}
|
|
37
|
+
export function validateObservation(o) {
|
|
38
|
+
const errors = [];
|
|
39
|
+
if (typeof o !== 'object' || o === null)
|
|
40
|
+
return { valid: false, errors: ['observation must be an object'] };
|
|
41
|
+
const v = o;
|
|
42
|
+
if (typeof v.environmentId !== 'string' || !v.environmentId)
|
|
43
|
+
errors.push('observation.environmentId must be a non-empty string');
|
|
44
|
+
if (typeof v.timestamp !== 'string' || !v.timestamp)
|
|
45
|
+
errors.push('observation.timestamp must be a non-empty string');
|
|
46
|
+
if (!('state' in v))
|
|
47
|
+
errors.push('observation.state is required (may be null)');
|
|
48
|
+
if (!Array.isArray(v.availableActions))
|
|
49
|
+
errors.push('observation.availableActions must be an array');
|
|
50
|
+
return { valid: errors.length === 0, errors };
|
|
51
|
+
}
|
|
52
|
+
export function validateTrajectory(t) {
|
|
53
|
+
const errors = [];
|
|
54
|
+
if (typeof t !== 'object' || t === null)
|
|
55
|
+
return { valid: false, errors: ['trajectory must be an object'] };
|
|
56
|
+
const v = t;
|
|
57
|
+
if (typeof v.id !== 'string' || !v.id)
|
|
58
|
+
errors.push('trajectory.id required');
|
|
59
|
+
if (typeof v.sessionId !== 'string' || !v.sessionId)
|
|
60
|
+
errors.push('trajectory.sessionId required');
|
|
61
|
+
if (typeof v.environment !== 'object' || v.environment === null)
|
|
62
|
+
errors.push('trajectory.environment required');
|
|
63
|
+
if (!Array.isArray(v.steps))
|
|
64
|
+
errors.push('trajectory.steps must be an array');
|
|
65
|
+
else {
|
|
66
|
+
v.steps.forEach((s, i) => {
|
|
67
|
+
const sv = s;
|
|
68
|
+
if (typeof sv.step !== 'number')
|
|
69
|
+
errors.push(`steps[${i}].step must be a number`);
|
|
70
|
+
if (!['success', 'failure', 'unknown'].includes(String(sv.outcome)))
|
|
71
|
+
errors.push(`steps[${i}].outcome invalid`);
|
|
72
|
+
if (sv.prediction !== undefined) {
|
|
73
|
+
const p = sv.prediction;
|
|
74
|
+
if (typeof p.confidence !== 'number' || p.confidence < 0 || p.confidence > 1) {
|
|
75
|
+
errors.push(`steps[${i}].prediction.confidence must be within [0,1]`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (typeof v.metrics !== 'object' || v.metrics === null)
|
|
81
|
+
errors.push('trajectory.metrics required');
|
|
82
|
+
return { valid: errors.length === 0, errors };
|
|
83
|
+
}
|
|
84
|
+
/** Deterministic non-crypto hash for stateHash / replay divergence checks. */
|
|
85
|
+
export function stableHash(value) {
|
|
86
|
+
const text = typeof value === 'string' ? value : JSON.stringify(sortKeys(value));
|
|
87
|
+
let h1 = 0x811c9dc5;
|
|
88
|
+
let h2 = 0x1000193;
|
|
89
|
+
for (let i = 0; i < text.length; i++) {
|
|
90
|
+
h1 = (h1 ^ text.charCodeAt(i)) >>> 0;
|
|
91
|
+
h1 = Math.imul(h1, 16777619) >>> 0;
|
|
92
|
+
h2 = (h2 + text.charCodeAt(i) * 31) >>> 0;
|
|
93
|
+
}
|
|
94
|
+
return (h1.toString(16).padStart(8, '0') + h2.toString(16).padStart(8, '0'));
|
|
95
|
+
}
|
|
96
|
+
function sortKeys(v) {
|
|
97
|
+
if (Array.isArray(v))
|
|
98
|
+
return v.map(sortKeys);
|
|
99
|
+
if (typeof v === 'object' && v !== null) {
|
|
100
|
+
return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
|
|
101
|
+
}
|
|
102
|
+
return v;
|
|
103
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - environment registry (ENV-005/007/008/010)
|
|
3
|
+
*
|
|
4
|
+
* Environments register themselves; the registry is the single lookup point
|
|
5
|
+
* for goal planning, exploration and the benchmark harness. It also owns:
|
|
6
|
+
* - health() : probe observe() under a timeout (ENV-007)
|
|
7
|
+
* - versioning : one id may hold multiple versions (ENV-008)
|
|
8
|
+
* - conformance() : the SAME contract test for every environment, so an
|
|
9
|
+
* adapter cannot quietly degrade into a fake (ENV-010)
|
|
10
|
+
*/
|
|
11
|
+
import type { Capability, Environment, Observation, ActionResult, EnvironmentScore } from './protocol.js';
|
|
12
|
+
export interface RegisteredEnvironment {
|
|
13
|
+
env: Environment;
|
|
14
|
+
registeredAt: string;
|
|
15
|
+
lastHealth?: {
|
|
16
|
+
ok: boolean;
|
|
17
|
+
checkedAt: string;
|
|
18
|
+
detail?: string;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export declare class EnvironmentRegistry {
|
|
22
|
+
private byId;
|
|
23
|
+
private byIdVersion;
|
|
24
|
+
register(env: Environment, opts?: {
|
|
25
|
+
replace?: boolean;
|
|
26
|
+
}): void;
|
|
27
|
+
list(): Array<{
|
|
28
|
+
id: string;
|
|
29
|
+
version: string;
|
|
30
|
+
registeredAt: string;
|
|
31
|
+
lastHealth?: RegisteredEnvironment['lastHealth'];
|
|
32
|
+
}>;
|
|
33
|
+
get(id: string): Environment | undefined;
|
|
34
|
+
getVersion(id: string, version: string): Environment | undefined;
|
|
35
|
+
/** ENV-007: observe() must answer within timeoutMs. */
|
|
36
|
+
health(id: string, timeoutMs?: number): Promise<{
|
|
37
|
+
ok: boolean;
|
|
38
|
+
checkedAt: string;
|
|
39
|
+
detail?: string;
|
|
40
|
+
}>;
|
|
41
|
+
/** ENV-010: the shared contract test. Every environment must pass it.
|
|
42
|
+
* Exercises the full protocol surface on a throwaway reset. */
|
|
43
|
+
conformance(env: Environment, timeoutMs?: number): Promise<{
|
|
44
|
+
pass: boolean;
|
|
45
|
+
failures: string[];
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
/** A minimal in-memory environment used by tests and as the reference
|
|
49
|
+
* implementation of the protocol (deterministic, replayable). */
|
|
50
|
+
export declare class MemoryEnvironment implements Environment {
|
|
51
|
+
id: string;
|
|
52
|
+
version: string;
|
|
53
|
+
private state;
|
|
54
|
+
private stepCount;
|
|
55
|
+
constructor(id?: string);
|
|
56
|
+
capabilities(): Promise<Capability[]>;
|
|
57
|
+
reset(): Promise<Observation>;
|
|
58
|
+
observe(): Promise<Observation>;
|
|
59
|
+
act(action: {
|
|
60
|
+
type: string;
|
|
61
|
+
args: Record<string, unknown>;
|
|
62
|
+
}): Promise<ActionResult>;
|
|
63
|
+
snapshot(): Promise<{
|
|
64
|
+
environmentId: string;
|
|
65
|
+
version: number;
|
|
66
|
+
takenAt: string;
|
|
67
|
+
stateHash: string;
|
|
68
|
+
payload: any;
|
|
69
|
+
}>;
|
|
70
|
+
restore(snapshot: {
|
|
71
|
+
payload: unknown;
|
|
72
|
+
}): Promise<void>;
|
|
73
|
+
evaluate(): Promise<EnvironmentScore>;
|
|
74
|
+
close(): Promise<void>;
|
|
75
|
+
}
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { validateObservation, stableHash } from "./protocol.js";
|
|
2
|
+
export class EnvironmentRegistry {
|
|
3
|
+
byId = new Map();
|
|
4
|
+
byIdVersion = new Map();
|
|
5
|
+
register(env, opts) {
|
|
6
|
+
const key = `${env.id}@${env.version}`;
|
|
7
|
+
if (this.byId.has(env.id) && !opts?.replace && this.byId.get(env.id).env.version !== env.version) {
|
|
8
|
+
// same id, different version: keep both, newest becomes default
|
|
9
|
+
}
|
|
10
|
+
else if (this.byId.has(env.id) && !opts?.replace) {
|
|
11
|
+
throw new Error(`environment ${env.id}@${env.version} already registered`);
|
|
12
|
+
}
|
|
13
|
+
this.byId.set(env.id, { env, registeredAt: new Date().toISOString() });
|
|
14
|
+
this.byIdVersion.set(key, env);
|
|
15
|
+
}
|
|
16
|
+
list() {
|
|
17
|
+
return [...this.byId.values()].map((r) => ({
|
|
18
|
+
id: r.env.id,
|
|
19
|
+
version: r.env.version,
|
|
20
|
+
registeredAt: r.registeredAt,
|
|
21
|
+
lastHealth: r.lastHealth,
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
get(id) {
|
|
25
|
+
return this.byId.get(id)?.env;
|
|
26
|
+
}
|
|
27
|
+
getVersion(id, version) {
|
|
28
|
+
return this.byIdVersion.get(`${id}@${version}`);
|
|
29
|
+
}
|
|
30
|
+
/** ENV-007: observe() must answer within timeoutMs. */
|
|
31
|
+
async health(id, timeoutMs = 5_000) {
|
|
32
|
+
const entry = this.byId.get(id);
|
|
33
|
+
if (!entry)
|
|
34
|
+
return { ok: false, checkedAt: new Date().toISOString(), detail: 'not registered' };
|
|
35
|
+
try {
|
|
36
|
+
const obs = await withTimeout(entry.env.observe(), timeoutMs, `health timeout after ${timeoutMs}ms`);
|
|
37
|
+
const v = validateObservation(obs);
|
|
38
|
+
entry.lastHealth = {
|
|
39
|
+
ok: v.valid,
|
|
40
|
+
checkedAt: new Date().toISOString(),
|
|
41
|
+
detail: v.valid ? undefined : v.errors.join('; '),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
entry.lastHealth = {
|
|
46
|
+
ok: false,
|
|
47
|
+
checkedAt: new Date().toISOString(),
|
|
48
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
return entry.lastHealth;
|
|
52
|
+
}
|
|
53
|
+
/** ENV-010: the shared contract test. Every environment must pass it.
|
|
54
|
+
* Exercises the full protocol surface on a throwaway reset. */
|
|
55
|
+
async conformance(env, timeoutMs = 15_000) {
|
|
56
|
+
const failures = [];
|
|
57
|
+
const step = async (name, fn) => {
|
|
58
|
+
try {
|
|
59
|
+
await withTimeout(fn(), timeoutMs, `${name} timed out`);
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
failures.push(`${name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
await step('capabilities', async () => {
|
|
66
|
+
const caps = await env.capabilities();
|
|
67
|
+
if (!Array.isArray(caps) || caps.length === 0)
|
|
68
|
+
throw new Error('no capabilities declared');
|
|
69
|
+
});
|
|
70
|
+
let obs;
|
|
71
|
+
await step('reset', async () => {
|
|
72
|
+
obs = await env.reset({});
|
|
73
|
+
const v = validateObservation(obs);
|
|
74
|
+
if (!v.valid)
|
|
75
|
+
throw new Error(v.errors.join('; '));
|
|
76
|
+
});
|
|
77
|
+
await step('observe', async () => {
|
|
78
|
+
const o = await env.observe();
|
|
79
|
+
const v = validateObservation(o);
|
|
80
|
+
if (!v.valid)
|
|
81
|
+
throw new Error(v.errors.join('; '));
|
|
82
|
+
if (o.environmentId !== env.id)
|
|
83
|
+
throw new Error(`environmentId mismatch: ${o.environmentId}`);
|
|
84
|
+
});
|
|
85
|
+
await step('act(noop)', async () => {
|
|
86
|
+
const noop = obs?.availableActions.find((a) => (a.cost ?? 0) === 0) ?? obs?.availableActions[0];
|
|
87
|
+
if (!noop)
|
|
88
|
+
throw new Error('no available action to probe');
|
|
89
|
+
const r = await env.act({ id: `conformance-${noop.id}`, type: noop.type, args: {}, reason: 'conformance probe' });
|
|
90
|
+
if (!['success', 'failure', 'unknown'].includes(r.outcome))
|
|
91
|
+
throw new Error('invalid outcome');
|
|
92
|
+
if (r.outcome === 'failure' && !r.error)
|
|
93
|
+
throw new Error('failure without structured error');
|
|
94
|
+
});
|
|
95
|
+
await step('snapshot+restore', async () => {
|
|
96
|
+
const snap = await env.snapshot();
|
|
97
|
+
if (typeof snap.stateHash !== 'string' || !snap.stateHash)
|
|
98
|
+
throw new Error('snapshot.stateHash required');
|
|
99
|
+
await env.restore(snap);
|
|
100
|
+
const after = await env.snapshot();
|
|
101
|
+
if (after.stateHash !== stableHash(snap.payload) && after.stateHash !== snap.stateHash) {
|
|
102
|
+
// hash drift after immediate restore means restore is not faithful
|
|
103
|
+
failures.push('snapshot/restore: stateHash diverged right after restore');
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
await step('evaluate', async () => {
|
|
107
|
+
const score = await env.evaluate();
|
|
108
|
+
if (typeof score.metrics !== 'object' || score.metrics === null)
|
|
109
|
+
throw new Error('evaluate must return metrics object');
|
|
110
|
+
});
|
|
111
|
+
await step('close', async () => {
|
|
112
|
+
await env.close();
|
|
113
|
+
});
|
|
114
|
+
return { pass: failures.length === 0, failures };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function withTimeout(p, ms, message) {
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
const timer = setTimeout(() => reject(new Error(message)), ms);
|
|
120
|
+
p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** A minimal in-memory environment used by tests and as the reference
|
|
124
|
+
* implementation of the protocol (deterministic, replayable). */
|
|
125
|
+
export class MemoryEnvironment {
|
|
126
|
+
id;
|
|
127
|
+
version = '1.0.0';
|
|
128
|
+
state = {};
|
|
129
|
+
stepCount = 0;
|
|
130
|
+
constructor(id = 'memory') {
|
|
131
|
+
this.id = id;
|
|
132
|
+
}
|
|
133
|
+
async capabilities() {
|
|
134
|
+
return [
|
|
135
|
+
{ kind: 'observe', detail: 'key-value state' },
|
|
136
|
+
{ kind: 'act', detail: 'set/delete keys' },
|
|
137
|
+
{ kind: 'snapshot', detail: 'full state clone' },
|
|
138
|
+
];
|
|
139
|
+
}
|
|
140
|
+
async reset() {
|
|
141
|
+
this.state = {};
|
|
142
|
+
this.stepCount = 0;
|
|
143
|
+
return this.observe();
|
|
144
|
+
}
|
|
145
|
+
async observe() {
|
|
146
|
+
return {
|
|
147
|
+
environmentId: this.id,
|
|
148
|
+
timestamp: new Date().toISOString(),
|
|
149
|
+
state: { ...this.state, stepCount: this.stepCount },
|
|
150
|
+
availableActions: [
|
|
151
|
+
{ id: 'set', type: 'set', description: 'set a key', argsSchema: { key: 'string', value: 'unknown' }, cost: 1 },
|
|
152
|
+
{ id: 'delete', type: 'delete', description: 'delete a key', argsSchema: { key: 'string' }, cost: 1, irreversible: true },
|
|
153
|
+
],
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
async act(action) {
|
|
157
|
+
this.stepCount += 1;
|
|
158
|
+
const started = Date.now();
|
|
159
|
+
if (action.type === 'set') {
|
|
160
|
+
const { key, value } = action.args;
|
|
161
|
+
if (typeof key !== 'string') {
|
|
162
|
+
return { actionId: 'anon', outcome: 'failure', error: { code: 'E_ARGS', message: 'key must be a string' }, durationMs: Date.now() - started };
|
|
163
|
+
}
|
|
164
|
+
this.state[key] = value ?? null;
|
|
165
|
+
return { actionId: 'anon', outcome: 'success', durationMs: Date.now() - started };
|
|
166
|
+
}
|
|
167
|
+
if (action.type === 'delete') {
|
|
168
|
+
const { key } = action.args;
|
|
169
|
+
if (typeof key !== 'string') {
|
|
170
|
+
return { actionId: 'anon', outcome: 'failure', error: { code: 'E_ARGS', message: 'key must be a string' }, durationMs: Date.now() - started };
|
|
171
|
+
}
|
|
172
|
+
delete this.state[key];
|
|
173
|
+
return { actionId: 'anon', outcome: 'success', durationMs: Date.now() - started };
|
|
174
|
+
}
|
|
175
|
+
return { actionId: 'anon', outcome: 'failure', error: { code: 'E_UNKNOWN_ACTION', message: `unknown action type ${action.type}` }, durationMs: Date.now() - started };
|
|
176
|
+
}
|
|
177
|
+
async snapshot() {
|
|
178
|
+
return {
|
|
179
|
+
environmentId: this.id,
|
|
180
|
+
version: 1,
|
|
181
|
+
takenAt: new Date().toISOString(),
|
|
182
|
+
stateHash: stableHash(this.state),
|
|
183
|
+
payload: JSON.parse(JSON.stringify(this.state)),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
async restore(snapshot) {
|
|
187
|
+
this.state = JSON.parse(JSON.stringify(snapshot.payload));
|
|
188
|
+
}
|
|
189
|
+
async evaluate() {
|
|
190
|
+
return { environmentId: this.id, metrics: { keys: Object.keys(this.state).length, steps: this.stepCount } };
|
|
191
|
+
}
|
|
192
|
+
async close() {
|
|
193
|
+
this.state = {};
|
|
194
|
+
}
|
|
195
|
+
}
|
package/dist/rlm.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export type RLMValue = unknown;
|
|
2
|
+
export interface RLMCheckpoint {
|
|
3
|
+
id: string;
|
|
4
|
+
label?: string;
|
|
5
|
+
createdAt: string;
|
|
6
|
+
stateHash: string;
|
|
7
|
+
snapshot: {
|
|
8
|
+
vars: Record<string, RLMValue>;
|
|
9
|
+
log: string[];
|
|
10
|
+
budget: ResourceBudget;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export interface ResourceBudget {
|
|
14
|
+
maxEvals: number;
|
|
15
|
+
maxWallMs: number;
|
|
16
|
+
maxSubagents: number;
|
|
17
|
+
used: {
|
|
18
|
+
evals: number;
|
|
19
|
+
wallMs: number;
|
|
20
|
+
subagents: number;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export interface SubagentSpec {
|
|
24
|
+
role: string;
|
|
25
|
+
task: string;
|
|
26
|
+
budgetMs?: number;
|
|
27
|
+
}
|
|
28
|
+
export interface AgentHandle {
|
|
29
|
+
id: string;
|
|
30
|
+
role: string;
|
|
31
|
+
/** host-bridged execution: resolves with the subagent's final message */
|
|
32
|
+
completion: Promise<string>;
|
|
33
|
+
cancel(): void;
|
|
34
|
+
}
|
|
35
|
+
export interface RLMContext {
|
|
36
|
+
vars: Record<string, RLMValue>;
|
|
37
|
+
/** read-only view of governance state (cannot be mutated from eval) */
|
|
38
|
+
readonly meta: {
|
|
39
|
+
evalsUsed: number;
|
|
40
|
+
subagentsUsed: number;
|
|
41
|
+
checkpointCount: number;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export interface RLMResult {
|
|
45
|
+
ok: boolean;
|
|
46
|
+
value?: unknown;
|
|
47
|
+
error?: {
|
|
48
|
+
code: string;
|
|
49
|
+
message: string;
|
|
50
|
+
};
|
|
51
|
+
durationMs: number;
|
|
52
|
+
budget: ResourceBudget;
|
|
53
|
+
}
|
|
54
|
+
export interface RLMHost {
|
|
55
|
+
/** host bridges subagent execution to the real spawn_agent machinery */
|
|
56
|
+
spawnSubagent(spec: SubagentSpec): Promise<AgentHandle>;
|
|
57
|
+
}
|
|
58
|
+
export declare class RLMRuntime {
|
|
59
|
+
private budget;
|
|
60
|
+
private host?;
|
|
61
|
+
private vars;
|
|
62
|
+
private log;
|
|
63
|
+
private checkpoints;
|
|
64
|
+
private subagents;
|
|
65
|
+
private t0;
|
|
66
|
+
constructor(budget?: Partial<ResourceBudget>, host?: RLMHost | undefined);
|
|
67
|
+
get fullBudget(): ResourceBudget;
|
|
68
|
+
private materializeBudget;
|
|
69
|
+
private _evals;
|
|
70
|
+
/** Addressable variables — the composable context surface (RLM-002). */
|
|
71
|
+
set(name: string, value: RLMValue): void;
|
|
72
|
+
get(name: string): RLMValue;
|
|
73
|
+
names(): string[];
|
|
74
|
+
/** RLM-003. Recursive call: eval code can spawn nested evals and read
|
|
75
|
+
* other variables, but through THIS runtime so accounting holds. */
|
|
76
|
+
eval(code: string, ctx?: Partial<RLMContext>): Promise<RLMResult>;
|
|
77
|
+
/** RLM-004/005. Checkpoint the whole workspace (vars + log + budget). */
|
|
78
|
+
checkpoint(label?: string): RLMCheckpoint;
|
|
79
|
+
restore(cp: RLMCheckpoint): void;
|
|
80
|
+
/** RLM-003. Fork = independent child workspace from a deep copy. */
|
|
81
|
+
fork(label?: string): Promise<RLMRuntime>;
|
|
82
|
+
/** RLM-007. Subagent lifecycle through the host bridge; counted, cancellable. */
|
|
83
|
+
spawn(spec: SubagentSpec): Promise<AgentHandle>;
|
|
84
|
+
cancelAll(): void;
|
|
85
|
+
/** RLM-009. Structured trace of the workspace history. */
|
|
86
|
+
trace(): string[];
|
|
87
|
+
private assertValidName;
|
|
88
|
+
}
|
package/dist/rlm.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - RLM runtime (blueprint §6 / RLM-001..010)
|
|
3
|
+
*
|
|
4
|
+
* A programmable cognitive workbench: context, memory snippets, environment
|
|
5
|
+
* state, predictions, subagent handles and validators are ADDRESSABLE
|
|
6
|
+
* VARIABLES the (host) program composes. `eval` runs host-supplied code
|
|
7
|
+
* against those variables — the runtime provides isolation walls, resource
|
|
8
|
+
* accounting, checkpoints and forks; it does NOT allow hidden unsafe
|
|
9
|
+
* self-modification: eval code can only touch workspace variables, never
|
|
10
|
+
* the runtime's own governance state (RLM-008).
|
|
11
|
+
*/
|
|
12
|
+
import { stableHash } from "./protocol.js";
|
|
13
|
+
export class RLMRuntime {
|
|
14
|
+
budget;
|
|
15
|
+
host;
|
|
16
|
+
vars = {};
|
|
17
|
+
log = [];
|
|
18
|
+
checkpoints = [];
|
|
19
|
+
subagents = [];
|
|
20
|
+
t0 = Date.now();
|
|
21
|
+
constructor(budget = {}, host) {
|
|
22
|
+
this.budget = budget;
|
|
23
|
+
this.host = host;
|
|
24
|
+
}
|
|
25
|
+
get fullBudget() {
|
|
26
|
+
return this.materializeBudget();
|
|
27
|
+
}
|
|
28
|
+
materializeBudget() {
|
|
29
|
+
return {
|
|
30
|
+
maxEvals: this.budget.maxEvals ?? 100,
|
|
31
|
+
maxWallMs: this.budget.maxWallMs ?? 10 * 60_000,
|
|
32
|
+
maxSubagents: this.budget.maxSubagents ?? 8,
|
|
33
|
+
used: { evals: this._evals, wallMs: Date.now() - this.t0, subagents: this.subagents.length },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
_evals = 0;
|
|
37
|
+
/** Addressable variables — the composable context surface (RLM-002). */
|
|
38
|
+
set(name, value) {
|
|
39
|
+
this.assertValidName(name);
|
|
40
|
+
this.vars[name] = value;
|
|
41
|
+
this.log.push(`set ${name}`);
|
|
42
|
+
}
|
|
43
|
+
get(name) {
|
|
44
|
+
return this.vars[name];
|
|
45
|
+
}
|
|
46
|
+
names() {
|
|
47
|
+
return Object.keys(this.vars);
|
|
48
|
+
}
|
|
49
|
+
/** RLM-003. Recursive call: eval code can spawn nested evals and read
|
|
50
|
+
* other variables, but through THIS runtime so accounting holds. */
|
|
51
|
+
async eval(code, ctx) {
|
|
52
|
+
const started = Date.now();
|
|
53
|
+
const budget = this.materializeBudget();
|
|
54
|
+
if (this._evals >= budget.maxEvals) {
|
|
55
|
+
return { ok: false, error: { code: 'E_BUDGET_EVALS', message: `eval budget exhausted (${budget.maxEvals})` }, durationMs: 0, budget };
|
|
56
|
+
}
|
|
57
|
+
if (budget.used.wallMs >= budget.maxWallMs) {
|
|
58
|
+
return { ok: false, error: { code: 'E_BUDGET_WALL', message: `wall-clock budget exhausted (${budget.maxWallMs}ms)` }, durationMs: 0, budget };
|
|
59
|
+
}
|
|
60
|
+
this._evals += 1;
|
|
61
|
+
const meta = Object.freeze({ evalsUsed: this._evals, subagentsUsed: this.subagents.length, checkpointCount: this.checkpoints.length });
|
|
62
|
+
const sandbox = Object.freeze({ vars: this.vars, meta, ...ctx });
|
|
63
|
+
try {
|
|
64
|
+
const fn = new Function('ctx', `"use strict";\n${code}`);
|
|
65
|
+
const value = fn(sandbox);
|
|
66
|
+
const resolved = value instanceof Promise ? await value : value;
|
|
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
|
+
};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** RLM-004/005. Checkpoint the whole workspace (vars + log + budget). */
|
|
81
|
+
checkpoint(label) {
|
|
82
|
+
const cp = {
|
|
83
|
+
id: `cp-${this.checkpoints.length + 1}`,
|
|
84
|
+
label,
|
|
85
|
+
createdAt: new Date().toISOString(),
|
|
86
|
+
stateHash: stableHash({ vars: this.vars, log: this.log }),
|
|
87
|
+
snapshot: {
|
|
88
|
+
vars: JSON.parse(JSON.stringify(this.vars)),
|
|
89
|
+
log: [...this.log],
|
|
90
|
+
budget: JSON.parse(JSON.stringify(this.materializeBudget())),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
this.checkpoints.push(cp);
|
|
94
|
+
return cp;
|
|
95
|
+
}
|
|
96
|
+
restore(cp) {
|
|
97
|
+
const existing = this.checkpoints.find((c) => c.id === cp.id) ?? cp;
|
|
98
|
+
this.vars = JSON.parse(JSON.stringify(existing.snapshot.vars));
|
|
99
|
+
this.log = [...existing.snapshot.log, `restored@${existing.id}`];
|
|
100
|
+
}
|
|
101
|
+
/** RLM-003. Fork = independent child workspace from a deep copy. */
|
|
102
|
+
async fork(label) {
|
|
103
|
+
const child = new RLMRuntime(this.budget, this.host);
|
|
104
|
+
child.vars = JSON.parse(JSON.stringify(this.vars));
|
|
105
|
+
child.log = [...this.log, `forked${label ? `(${label})` : ''}`];
|
|
106
|
+
child._evals = this._evals;
|
|
107
|
+
return child;
|
|
108
|
+
}
|
|
109
|
+
/** RLM-007. Subagent lifecycle through the host bridge; counted, cancellable. */
|
|
110
|
+
async spawn(spec) {
|
|
111
|
+
const budget = this.materializeBudget();
|
|
112
|
+
if (this.subagents.length >= budget.maxSubagents) {
|
|
113
|
+
throw new Error(`subagent budget exhausted (${budget.maxSubagents})`);
|
|
114
|
+
}
|
|
115
|
+
if (!this.host) {
|
|
116
|
+
throw new Error('no RLMHost bridge configured: spawn requires a host that connects to the real agent runtime');
|
|
117
|
+
}
|
|
118
|
+
const handle = await this.host.spawnSubagent(spec);
|
|
119
|
+
this.subagents.push(handle);
|
|
120
|
+
handle.completion.finally(() => {
|
|
121
|
+
this.log.push(`subagent ${handle.id} (${spec.role}) done`);
|
|
122
|
+
}).catch(() => undefined);
|
|
123
|
+
return handle;
|
|
124
|
+
}
|
|
125
|
+
cancelAll() {
|
|
126
|
+
for (const a of this.subagents)
|
|
127
|
+
a.cancel();
|
|
128
|
+
this.subagents = [];
|
|
129
|
+
}
|
|
130
|
+
/** RLM-009. Structured trace of the workspace history. */
|
|
131
|
+
trace() {
|
|
132
|
+
return [...this.log];
|
|
133
|
+
}
|
|
134
|
+
assertValidName(name) {
|
|
135
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
136
|
+
throw new Error(`invalid variable name ${name}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { CognitiveTrajectory } from './protocol.js';
|
|
2
|
+
export interface Trigger {
|
|
3
|
+
/** matched against goal text + observation affordances */
|
|
4
|
+
keywords?: string[];
|
|
5
|
+
environmentId?: string;
|
|
6
|
+
actionTypes?: string[];
|
|
7
|
+
}
|
|
8
|
+
export interface Condition {
|
|
9
|
+
description: string;
|
|
10
|
+
/** structural expression checked by the host, e.g. "fs:exists(package.json)" */
|
|
11
|
+
check: string;
|
|
12
|
+
}
|
|
13
|
+
export interface Step {
|
|
14
|
+
kind: 'act' | 'verify' | 'note';
|
|
15
|
+
/** for act: the action type to execute; for verify: the check id */
|
|
16
|
+
ref: string;
|
|
17
|
+
args?: Record<string, unknown>;
|
|
18
|
+
}
|
|
19
|
+
export interface VerificationSpec {
|
|
20
|
+
id: string;
|
|
21
|
+
/** host evaluator key, resolved by the benchmark runner */
|
|
22
|
+
evaluator: string;
|
|
23
|
+
expect: {
|
|
24
|
+
metric: string;
|
|
25
|
+
op: '>=' | '<=' | '==';
|
|
26
|
+
value: number;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface EvidenceRef {
|
|
30
|
+
trajectoryId: string;
|
|
31
|
+
steps: number;
|
|
32
|
+
outcome: 'success' | 'failure' | 'unknown';
|
|
33
|
+
}
|
|
34
|
+
export interface SkillSpec {
|
|
35
|
+
id: string;
|
|
36
|
+
name: string;
|
|
37
|
+
trigger: Trigger;
|
|
38
|
+
preconditions: Condition[];
|
|
39
|
+
procedure: Step[];
|
|
40
|
+
verification: VerificationSpec[];
|
|
41
|
+
evidence: EvidenceRef[];
|
|
42
|
+
version: string;
|
|
43
|
+
status: 'candidate' | 'active' | 'rolled-back';
|
|
44
|
+
createdAt: string;
|
|
45
|
+
}
|
|
46
|
+
export interface VerificationResult {
|
|
47
|
+
skillId: string;
|
|
48
|
+
pass: boolean;
|
|
49
|
+
checks: Array<{
|
|
50
|
+
id: string;
|
|
51
|
+
metric: string;
|
|
52
|
+
actual: number;
|
|
53
|
+
expected: string;
|
|
54
|
+
pass: boolean;
|
|
55
|
+
}>;
|
|
56
|
+
}
|
|
57
|
+
/** The benchmark surface the compiler verifies against — implemented by
|
|
58
|
+
* the environments/bench packages; kept as an interface for independence
|
|
59
|
+
* (evaluator independence rule: the compiler never grades its own work). */
|
|
60
|
+
export interface SkillBenchmark {
|
|
61
|
+
runSkill(skill: SkillSpec): Promise<Record<string, number>>;
|
|
62
|
+
}
|
|
63
|
+
export declare class SkillCompiler {
|
|
64
|
+
private skills;
|
|
65
|
+
private lastVerification;
|
|
66
|
+
list(): SkillSpec[];
|
|
67
|
+
get(id: string): SkillSpec | undefined;
|
|
68
|
+
/** SK-002. Mine successful trajectories for repeated action-type runs.
|
|
69
|
+
* A pattern must appear in >= minRepeat distinct successful episodes to
|
|
70
|
+
* become a candidate — one lucky run is folklore, not a skill. */
|
|
71
|
+
compile(experiences: CognitiveTrajectory[], opts?: {
|
|
72
|
+
minRepeat?: number;
|
|
73
|
+
}): Promise<SkillSpec[]>;
|
|
74
|
+
/** SK-004. Run the skill's verification specs against the benchmark. */
|
|
75
|
+
verify(skill: SkillSpec, benchmark: SkillBenchmark): Promise<VerificationResult>;
|
|
76
|
+
/** SK-007. Promote only candidates with a PASSING verification on record.
|
|
77
|
+
* No verification, no promotion — this is the whole point of the gate. */
|
|
78
|
+
promote(skillId: string): Promise<void>;
|
|
79
|
+
/** SK-008. Rollback is always allowed. */
|
|
80
|
+
rollback(skillId: string): Promise<void>;
|
|
81
|
+
}
|