@hmharness/cognitive 0.23.13 → 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 CHANGED
@@ -31,3 +31,4 @@ export * from './abstract-actions.js';
31
31
  export * from './learning-loop.js';
32
32
  export * from './governance.js';
33
33
  export * from './crowd.js';
34
+ export * from './slice.js';
package/dist/index.js CHANGED
@@ -30,3 +30,4 @@ export * from "./abstract-actions.js";
30
30
  export * from "./learning-loop.js";
31
31
  export * from "./governance.js";
32
32
  export * from "./crowd.js";
33
+ export * from "./slice.js";
@@ -24,19 +24,19 @@ import { Worker } from 'node:worker_threads';
24
24
  * async function body with a frozen ctx, and posts the result back.
25
25
  * Shadows the dangerous globals at function-constructor scope so casual
26
26
  * access fails loudly. */
27
- const WORKER_SOURCE = `
28
- const { parentPort, workerData } = require('node:worker_threads');
29
- (async () => {
30
- const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
31
- try {
32
- const process = undefined, require = undefined;
33
- const fn = new Function('ctx', 'process', 'require', '"use strict";return (async()=>{' + workerData.code + '})();');
34
- const value = await fn(ctx, undefined, undefined);
35
- parentPort.postMessage({ ok: true, value });
36
- } catch (err) {
37
- parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
38
- }
39
- })();
27
+ const WORKER_SOURCE = `
28
+ const { parentPort, workerData } = require('node:worker_threads');
29
+ (async () => {
30
+ const ctx = Object.freeze({ vars: Object.freeze({ ...workerData.vars }), meta: Object.freeze({ ...workerData.meta }) });
31
+ try {
32
+ const process = undefined, require = undefined;
33
+ const fn = new Function('ctx', 'process', 'require', '"use strict";return (async()=>{' + workerData.code + '})();');
34
+ const value = await fn(ctx, undefined, undefined);
35
+ parentPort.postMessage({ ok: true, value });
36
+ } catch (err) {
37
+ parentPort.postMessage({ ok: false, error: { code: 'E_EVAL', message: err && err.message ? String(err.message).slice(0, 500) : String(err).slice(0, 500) } });
38
+ }
39
+ })();
40
40
  `;
41
41
  /** Run RLM eval code inside a fresh worker. One worker per eval — RLM evals
42
42
  * are coarse-grained (composing workspace variables), so per-eval spawn
@@ -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.13",
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.13"
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
+ }