@hmharness/cognitive 0.23.12 → 0.23.14
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/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/dist/slice.d.ts +71 -0
- package/dist/slice.js +126 -0
- package/package.json +31 -31
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';
|
|
@@ -29,3 +31,4 @@ export * from './abstract-actions.js';
|
|
|
29
31
|
export * from './learning-loop.js';
|
|
30
32
|
export * from './governance.js';
|
|
31
33
|
export * from './crowd.js';
|
|
34
|
+
export * from './slice.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";
|
|
@@ -29,3 +30,4 @@ export * from "./abstract-actions.js";
|
|
|
29
30
|
export * from "./learning-loop.js";
|
|
30
31
|
export * from "./governance.js";
|
|
31
32
|
export * from "./crowd.js";
|
|
33
|
+
export * from "./slice.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/dist/slice.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export interface SliceStage {
|
|
2
|
+
stage: 'observe' | 'goal' | 'plan' | 'act' | 'evaluate' | 'learn';
|
|
3
|
+
ok: boolean;
|
|
4
|
+
detail: string;
|
|
5
|
+
/** machine-checkable proof artifact per stage (ids, counts, hashes) */
|
|
6
|
+
evidence: Record<string, unknown>;
|
|
7
|
+
}
|
|
8
|
+
export interface SliceOptions {
|
|
9
|
+
home: string;
|
|
10
|
+
task: string;
|
|
11
|
+
cwd: string;
|
|
12
|
+
/** REAL execution: host bridges to the agent loop (runAgentTask). Must
|
|
13
|
+
* return the agent's own completion claim + the trajectory id it left. */
|
|
14
|
+
act: () => Promise<{
|
|
15
|
+
completed: boolean;
|
|
16
|
+
claim: string;
|
|
17
|
+
trajectoryId?: string;
|
|
18
|
+
turns?: number;
|
|
19
|
+
toolUses?: number;
|
|
20
|
+
}>;
|
|
21
|
+
/** INDEPENDENT evaluation (review P0-3): runs AFTER act, claim-blind.
|
|
22
|
+
* The contract below is the separation wall — see IndependentEvaluator. */
|
|
23
|
+
evaluate?: IndependentEvaluator;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Review P0-3: the evaluator must be structurally SEPARATE from the agent's
|
|
27
|
+
* self-assessment. This contract is the wall:
|
|
28
|
+
* - the evaluator receives the TASK and the WORKSPACE, never the agent's
|
|
29
|
+
* claim, turns or tool transcript (claim-blind by construction);
|
|
30
|
+
* - the verdict's `source` travels with every downstream artifact so a
|
|
31
|
+
* structural fallback can never masquerade as independent judgment;
|
|
32
|
+
* - agent self-reports are recorded (in the report) but CANNOT satisfy a
|
|
33
|
+
* SuccessCriterion — only an IndependentEvaluator (or a future holdout
|
|
34
|
+
* harness) can.
|
|
35
|
+
*/
|
|
36
|
+
export interface IndependentEvaluator {
|
|
37
|
+
readonly kind: 'independent-evaluator';
|
|
38
|
+
/** claim-blind by construction: inputs are task + workspace only */
|
|
39
|
+
run(task: string, cwd: string): Promise<{
|
|
40
|
+
pass: boolean;
|
|
41
|
+
reasons: string[];
|
|
42
|
+
}>;
|
|
43
|
+
}
|
|
44
|
+
/** Wrap a plain checker into the evaluator contract (asserts claim-blindness
|
|
45
|
+
* at the type level: the checker signature cannot even receive the claim). */
|
|
46
|
+
export declare function independentEvaluator(run: (task: string, cwd: string) => Promise<{
|
|
47
|
+
pass: boolean;
|
|
48
|
+
reasons: string[];
|
|
49
|
+
}>): IndependentEvaluator;
|
|
50
|
+
export interface SliceReport {
|
|
51
|
+
task: string;
|
|
52
|
+
startedAt: string;
|
|
53
|
+
stages: SliceStage[];
|
|
54
|
+
/** the independent verdict — this, not the agent claim, is what Learn keys on */
|
|
55
|
+
verdict: {
|
|
56
|
+
source: 'independent' | 'structural';
|
|
57
|
+
pass: boolean;
|
|
58
|
+
reasons: string[];
|
|
59
|
+
};
|
|
60
|
+
agentClaim: {
|
|
61
|
+
completed: boolean;
|
|
62
|
+
claim: string;
|
|
63
|
+
};
|
|
64
|
+
goalDrift?: {
|
|
65
|
+
score: number;
|
|
66
|
+
signals: string[];
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
export declare function runVerticalSlice(opts: SliceOptions): Promise<SliceReport>;
|
|
70
|
+
/** Format a slice report for the CLI (auditable, one line per stage). */
|
|
71
|
+
export declare function formatSliceReport(r: SliceReport): string;
|
package/dist/slice.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - vertical cognitive slice (review P0-2, 2026-10-03)
|
|
3
|
+
*
|
|
4
|
+
* The modules existed but as HORIZONTAL pieces; this file chains ONE real
|
|
5
|
+
* task through the full cognitive pipeline, every stage leaving evidence:
|
|
6
|
+
*
|
|
7
|
+
* Observe (environment/workspace) -> WorldModel view
|
|
8
|
+
* -> Goal (registered + decomposed from the task text)
|
|
9
|
+
* -> Plan (world-model digest = what the planner may trust)
|
|
10
|
+
* -> Act (host-bridged REAL execution — the agent loop, real tools)
|
|
11
|
+
* -> Evaluate (INDEPENDENT verdict: host checker or structural check;
|
|
12
|
+
* the agent's own claim is recorded as a CLAIM, never as evidence)
|
|
13
|
+
* -> Learn (WM replay from the trajectory, memory entry keyed to the
|
|
14
|
+
* INDEPENDENT verdict, diagnosis line for the next round)
|
|
15
|
+
*
|
|
16
|
+
* The slice REPORT is the audit unit: each stage names what it did and
|
|
17
|
+
* what evidence it produced. Nothing here promotes skills — learning
|
|
18
|
+
* outcomes flow into the existing gated pipelines (evaluator
|
|
19
|
+
* independence, blueprint §9 / review P0-3).
|
|
20
|
+
*/
|
|
21
|
+
import { join } from 'node:path';
|
|
22
|
+
import { readdir } from 'node:fs/promises';
|
|
23
|
+
import { CognitiveMemory } from "./memory.js";
|
|
24
|
+
import { buildContextDigest, loadTrajectories, replayIntoWorldModel, diagnoseOpportunities } from "./analysis.js";
|
|
25
|
+
import { loadCrowdPriors } from "./crowd.js";
|
|
26
|
+
/** Wrap a plain checker into the evaluator contract (asserts claim-blindness
|
|
27
|
+
* at the type level: the checker signature cannot even receive the claim). */
|
|
28
|
+
export function independentEvaluator(run) {
|
|
29
|
+
return { kind: 'independent-evaluator', run };
|
|
30
|
+
}
|
|
31
|
+
/** Workspace observation WITHOUT any environment adapter: files + sizes of
|
|
32
|
+
* the task cwd (first two levels) — a deterministic, cheap world fact the
|
|
33
|
+
* slice can diff after acting. Environment adapters plug in later via the
|
|
34
|
+
* same stage contract. */
|
|
35
|
+
async function observeWorkspace(cwd) {
|
|
36
|
+
const out = [];
|
|
37
|
+
try {
|
|
38
|
+
const entries = await readdir(cwd, { withFileTypes: true });
|
|
39
|
+
for (const e of entries.slice(0, 50)) {
|
|
40
|
+
out.push(e.isDirectory() ? e.name + '/' : e.name);
|
|
41
|
+
if (e.isDirectory() && out.length < 50) {
|
|
42
|
+
try {
|
|
43
|
+
const sub = await readdir(join(cwd, e.name), { withFileTypes: true });
|
|
44
|
+
for (const s of sub.slice(0, 10))
|
|
45
|
+
out.push(e.name + '/' + (s.isDirectory() ? s.name + '/' : s.name));
|
|
46
|
+
}
|
|
47
|
+
catch { /* unreadable subdir is a fact, not a failure */ }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch { /* unreadable cwd recorded as zero files */ }
|
|
52
|
+
return { files: out, topCount: out.filter((f) => !f.includes('/')).length };
|
|
53
|
+
}
|
|
54
|
+
export async function runVerticalSlice(opts) {
|
|
55
|
+
const stages = [];
|
|
56
|
+
const startedAt = new Date().toISOString();
|
|
57
|
+
// 1. OBSERVE — workspace facts (pre-act snapshot)
|
|
58
|
+
const before = await observeWorkspace(opts.cwd);
|
|
59
|
+
stages.push({ stage: 'observe', ok: true, detail: `${before.files.length} entries observed in cwd`, evidence: { topCount: before.topCount, sample: before.files.slice(0, 8) } });
|
|
60
|
+
// 2. GOAL — register the task as a goal (propose+adopt: user-sourced
|
|
61
|
+
// tasks are explicit, no approval ambiguity for slice goals)
|
|
62
|
+
const { GoalManager } = await import("./goal.js");
|
|
63
|
+
const gm = new GoalManager();
|
|
64
|
+
const goal = gm.propose({ id: `goal-slice-${startedAt}`, description: opts.task, source: 'user', priority: 2, constraints: [], successCriteria: [{ id: 'sc-independent', description: 'independent evaluation passes' }] });
|
|
65
|
+
await gm.adopt(goal.id, { approved: true });
|
|
66
|
+
stages.push({ stage: 'goal', ok: true, detail: 'goal registered from task text', evidence: { goalId: goal.id, criteria: 1 } });
|
|
67
|
+
// 3. PLAN — the world-model digest (trusted/flaky tools + crowd priors)
|
|
68
|
+
const digest = await buildContextDigest(opts.home).catch(() => '');
|
|
69
|
+
const priors = await loadCrowdPriors(opts.home).catch(() => null);
|
|
70
|
+
stages.push({ stage: 'plan', ok: digest.length > 0 || Boolean(priors?.sources.length), detail: digest ? 'world-model digest attached to the planning context' : (priors?.sources.length ? 'crowd priors present (digest empty: little local evidence yet)' : 'no digest yet (cold start) — plan proceeds without WM advice'), evidence: { digestChars: digest.length, crowdSources: priors?.sources.length ?? 0 } });
|
|
71
|
+
// 4. ACT — REAL execution through the host bridge
|
|
72
|
+
let actResult;
|
|
73
|
+
try {
|
|
74
|
+
actResult = await opts.act();
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
actResult = { completed: false, claim: 'act threw: ' + String(err).slice(0, 160) };
|
|
78
|
+
}
|
|
79
|
+
stages.push({ stage: 'act', ok: actResult.completed, detail: actResult.completed ? 'agent loop completed' : 'agent loop did not complete', evidence: { claim: actResult.claim.slice(0, 200), turns: actResult.turns ?? null, toolUses: actResult.toolUses ?? null, trajectoryId: actResult.trajectoryId ?? null } });
|
|
80
|
+
// 5. EVALUATE — INDEPENDENT of the agent (separate phase, claim-blind:
|
|
81
|
+
// the evaluator contract only receives task + cwd, never the claim)
|
|
82
|
+
let verdict;
|
|
83
|
+
if (opts.evaluate) {
|
|
84
|
+
const r = await opts.evaluate.run(opts.task, opts.cwd).catch((e) => ({ pass: false, reasons: ['evaluator threw: ' + String(e).slice(0, 120)] }));
|
|
85
|
+
verdict = { source: 'independent', pass: r.pass, reasons: r.reasons.slice(0, 5) };
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
// structural fallback: completion + (from the latest trajectory) no
|
|
89
|
+
// tool failures — explicitly labeled NOT a quality judgment
|
|
90
|
+
const trajectories = await loadTrajectories(opts.home, 1);
|
|
91
|
+
const last = trajectories[0];
|
|
92
|
+
const failed = last ? last.steps.filter((s) => s.outcome === 'failure').length : 0;
|
|
93
|
+
const pass = actResult.completed && failed === 0 && Boolean(last);
|
|
94
|
+
verdict = { source: 'structural', pass, reasons: [`completed=${actResult.completed}`, `toolFailures=${failed}`, `trajectory=${last?.id ?? 'none'}`] };
|
|
95
|
+
}
|
|
96
|
+
stages.push({ stage: 'evaluate', ok: verdict.pass, detail: `verdict (${verdict.source}): ${verdict.pass ? 'PASS' : 'FAIL'} — ${verdict.reasons.join('; ')}`, evidence: { source: verdict.source, reasons: verdict.reasons } });
|
|
97
|
+
// 6. LEARN — WM replay + memory keyed to the INDEPENDENT verdict
|
|
98
|
+
const trajectories = await loadTrajectories(opts.home, 50);
|
|
99
|
+
const latest = actResult.trajectoryId ? trajectories.find((t) => t.id === actResult.trajectoryId) ?? trajectories[0] : trajectories[0];
|
|
100
|
+
const wm = replayIntoWorldModel(trajectories, latest?.environment.id ?? 'terminal');
|
|
101
|
+
const mem = new CognitiveMemory(opts.home);
|
|
102
|
+
await mem.load();
|
|
103
|
+
const entry = await mem.write({
|
|
104
|
+
layer: 'episodic',
|
|
105
|
+
content: `SLICE ${verdict.pass ? 'PASS' : 'FAIL'}(${verdict.source}): ${opts.task.slice(0, 120)}`,
|
|
106
|
+
payload: { verdict, agentClaim: actResult.claim.slice(0, 200), trajectoryId: latest?.id ?? null, digestChars: digest.length },
|
|
107
|
+
source: 'vertical-slice',
|
|
108
|
+
provenance: `slice:${startedAt}`,
|
|
109
|
+
confidence: verdict.source === 'independent' ? (verdict.pass ? 0.9 : 0.85) : 0.6,
|
|
110
|
+
environment: latest?.environment.id ?? 'terminal',
|
|
111
|
+
session: 'vertical-slice',
|
|
112
|
+
tags: ['slice', verdict.source, verdict.pass ? 'pass' : 'fail'],
|
|
113
|
+
});
|
|
114
|
+
const { opportunities } = await diagnoseOpportunities(opts.home).catch(() => ({ opportunities: [] }));
|
|
115
|
+
stages.push({ stage: 'learn', ok: true, detail: `WM replayed (${wm.worldState.beliefs.length} beliefs); memory entry ${entry.id} keyed to the ${verdict.source} verdict`, evidence: { memoryId: entry.id, beliefs: wm.worldState.beliefs.length, opportunities: opportunities.length } });
|
|
116
|
+
return { task: opts.task, startedAt, stages, verdict, agentClaim: { completed: actResult.completed, claim: actResult.claim } };
|
|
117
|
+
}
|
|
118
|
+
/** Format a slice report for the CLI (auditable, one line per stage). */
|
|
119
|
+
export function formatSliceReport(r) {
|
|
120
|
+
const lines = [`认知纵切片 · ${r.task.slice(0, 60)}`];
|
|
121
|
+
for (const s of r.stages) {
|
|
122
|
+
lines.push(` ${s.ok ? '✓' : '✗'} ${s.stage.padEnd(9)} ${s.detail}`);
|
|
123
|
+
}
|
|
124
|
+
lines.push(` 裁决: ${r.verdict.pass ? 'PASS' : 'FAIL'} (${r.verdict.source}) — 学步以此为准,agent 自评仅作记录`);
|
|
125
|
+
return lines.join('\n');
|
|
126
|
+
}
|
package/package.json
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@hmharness/cognitive",
|
|
3
|
-
"version": "0.23.
|
|
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.
|
|
30
|
-
}
|
|
31
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@hmharness/cognitive",
|
|
3
|
+
"version": "0.23.14",
|
|
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.14"
|
|
30
|
+
}
|
|
31
|
+
}
|