@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/memory.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - five-layer memory (blueprint §7 / MEM-001..010)
|
|
3
|
+
*
|
|
4
|
+
* working : current-task context/drafts, minutes-lived, runtime only
|
|
5
|
+
* episodic : full trajectories/experiences, written at task end (the
|
|
6
|
+
* TrajectoryStore is the episodic substrate; this layer indexes
|
|
7
|
+
* it for retrieval)
|
|
8
|
+
* semantic : rules/facts/concepts, written ONLY by distill+verify
|
|
9
|
+
* procedural: skills/workflows/policies — versioned, owned by the skill
|
|
10
|
+
* compiler (this layer stores refs, not bodies)
|
|
11
|
+
* world : environment state/causal/prediction errors — owned by the
|
|
12
|
+
* world model (refs again)
|
|
13
|
+
*
|
|
14
|
+
* Blueprint rule (§8 of master prompt): EVERY long-term entry carries
|
|
15
|
+
* source/provenance/confidence/timestamp/environment/session — enforced by
|
|
16
|
+
* validateEntry, not by convention. Contradiction detection (MEM-008) flags
|
|
17
|
+
* same-key claims with divergent values; consolidation (MEM-009) merges
|
|
18
|
+
* duplicates and decays stale entries WITHOUT deleting originals
|
|
19
|
+
* (append-only: contradicted entries get supersededBy, never removed).
|
|
20
|
+
*/
|
|
21
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { stableHash } from "./protocol.js";
|
|
24
|
+
export class CognitiveMemory {
|
|
25
|
+
home;
|
|
26
|
+
working = new Map();
|
|
27
|
+
longTerm = [];
|
|
28
|
+
constructor(home) {
|
|
29
|
+
this.home = home;
|
|
30
|
+
}
|
|
31
|
+
file() {
|
|
32
|
+
return join(this.home, 'cognitive', 'memory', 'memory.jsonl');
|
|
33
|
+
}
|
|
34
|
+
/* ---- working layer (runtime, not persisted) ---- */
|
|
35
|
+
setWorking(key, content, session) {
|
|
36
|
+
this.working.set(key, {
|
|
37
|
+
id: `work-${stableHash(key + session).slice(0, 10)}`,
|
|
38
|
+
layer: 'working',
|
|
39
|
+
content,
|
|
40
|
+
source: 'runtime',
|
|
41
|
+
provenance: 'working-memory',
|
|
42
|
+
confidence: 1,
|
|
43
|
+
timestamp: new Date().toISOString(),
|
|
44
|
+
environment: 'runtime',
|
|
45
|
+
session,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
getWorking(key) {
|
|
49
|
+
return this.working.get(key)?.content;
|
|
50
|
+
}
|
|
51
|
+
clearWorking() {
|
|
52
|
+
this.working.clear();
|
|
53
|
+
}
|
|
54
|
+
/* ---- long-term layers ---- */
|
|
55
|
+
async write(entry) {
|
|
56
|
+
const full = {
|
|
57
|
+
...entry,
|
|
58
|
+
id: entry.id ?? `mem-${stableHash(entry.content + entry.layer + Date.now()).slice(0, 12)}`,
|
|
59
|
+
timestamp: entry.timestamp ?? new Date().toISOString(),
|
|
60
|
+
};
|
|
61
|
+
const errors = validateEntry(full);
|
|
62
|
+
if (errors.length)
|
|
63
|
+
throw new Error(`invalid memory entry: ${errors.join('; ')}`);
|
|
64
|
+
this.longTerm.push(full);
|
|
65
|
+
await this.persist();
|
|
66
|
+
return full;
|
|
67
|
+
}
|
|
68
|
+
/** MEM-006 hybrid retrieval: tag/keyword match + recency + confidence. */
|
|
69
|
+
retrieve(query) {
|
|
70
|
+
let pool = this.longTerm.filter((e) => !e.supersededBy);
|
|
71
|
+
if (query.layer)
|
|
72
|
+
pool = pool.filter((e) => e.layer === query.layer);
|
|
73
|
+
if (query.environment)
|
|
74
|
+
pool = pool.filter((e) => e.environment === query.environment);
|
|
75
|
+
if (query.tags?.length) {
|
|
76
|
+
const want = new Set(query.tags);
|
|
77
|
+
pool = pool.filter((e) => (e.tags ?? []).some((t) => want.has(t)));
|
|
78
|
+
}
|
|
79
|
+
if (query.text) {
|
|
80
|
+
const q = query.text.toLowerCase();
|
|
81
|
+
pool = pool.filter((e) => e.content.toLowerCase().includes(q));
|
|
82
|
+
}
|
|
83
|
+
const scored = pool.map((e) => ({
|
|
84
|
+
e,
|
|
85
|
+
score: e.confidence * 0.6 + recencyScore(e.timestamp) * 0.2 + (query.text && e.content.toLowerCase().includes(query.text.toLowerCase()) ? 0.2 : 0),
|
|
86
|
+
}));
|
|
87
|
+
scored.sort((a, b) => b.score - a.score);
|
|
88
|
+
return scored.slice(0, query.limit ?? 10).map((s) => s.e);
|
|
89
|
+
}
|
|
90
|
+
/** MEM-008. Same subject, divergent claims. */
|
|
91
|
+
detectContradictions() {
|
|
92
|
+
const active = this.longTerm.filter((e) => !e.supersededBy && e.layer === 'semantic');
|
|
93
|
+
const byKey = new Map();
|
|
94
|
+
for (const e of active) {
|
|
95
|
+
const key = subjectKey(e.content);
|
|
96
|
+
byKey.set(key, [...(byKey.get(key) ?? []), e]);
|
|
97
|
+
}
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const [key, entries] of byKey) {
|
|
100
|
+
if (entries.length < 2)
|
|
101
|
+
continue;
|
|
102
|
+
const normalized = new Set(entries.map((e) => normalizeClaim(e.content)));
|
|
103
|
+
if (normalized.size > 1) {
|
|
104
|
+
out.push({ key, entries: entries.map((e) => ({ id: e.id, content: e.content, confidence: e.confidence })) });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** MEM-009. Merge duplicates, decay stale entries via supersededBy —
|
|
110
|
+
* originals stay in the file (append-only, blueprint §10). */
|
|
111
|
+
async consolidate(opts) {
|
|
112
|
+
const staleDays = opts?.staleDays ?? 60;
|
|
113
|
+
let merged = 0;
|
|
114
|
+
let decayed = 0;
|
|
115
|
+
const active = this.longTerm.filter((e) => !e.supersededBy && (e.layer === 'semantic' || e.layer === 'episodic'));
|
|
116
|
+
const byKey = new Map();
|
|
117
|
+
for (const e of active) {
|
|
118
|
+
const key = `${e.layer}:${subjectKey(e.content)}`;
|
|
119
|
+
byKey.set(key, [...(byKey.get(key) ?? []), e]);
|
|
120
|
+
}
|
|
121
|
+
for (const group of byKey.values()) {
|
|
122
|
+
if (group.length < 2)
|
|
123
|
+
continue;
|
|
124
|
+
group.sort((a, b) => b.confidence - a.confidence || b.timestamp.localeCompare(a.timestamp));
|
|
125
|
+
const [best, ...rest] = group;
|
|
126
|
+
const sameClaim = rest.filter((r) => normalizeClaim(r.content) === normalizeClaim(best.content));
|
|
127
|
+
for (const r of sameClaim) {
|
|
128
|
+
r.supersededBy = best.id;
|
|
129
|
+
merged += 1;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const cutoff = Date.now() - staleDays * 86_400_000;
|
|
133
|
+
for (const e of this.longTerm) {
|
|
134
|
+
if (!e.supersededBy && e.layer === 'episodic' && new Date(e.timestamp).getTime() < cutoff && e.confidence < 0.5) {
|
|
135
|
+
e.supersededBy = 'consolidation:stale';
|
|
136
|
+
decayed += 1;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (merged || decayed)
|
|
140
|
+
await this.persist();
|
|
141
|
+
return { merged, decayed };
|
|
142
|
+
}
|
|
143
|
+
async load() {
|
|
144
|
+
try {
|
|
145
|
+
const text = await readFile(this.file(), 'utf8');
|
|
146
|
+
this.longTerm = text.split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
this.longTerm = [];
|
|
150
|
+
}
|
|
151
|
+
return this.longTerm.length;
|
|
152
|
+
}
|
|
153
|
+
stats() {
|
|
154
|
+
const out = { total: this.longTerm.length };
|
|
155
|
+
for (const l of ['working', 'episodic', 'semantic', 'procedural', 'world']) {
|
|
156
|
+
out[l] = this.longTerm.filter((e) => e.layer === l).length;
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
async persist() {
|
|
161
|
+
await mkdir(join(this.home, 'cognitive', 'memory'), { recursive: true });
|
|
162
|
+
await writeFile(this.file(), this.longTerm.map((e) => JSON.stringify(e)).join('\n') + '\n', 'utf8');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** MEM-007 provenance validation: long-term entries without a real source
|
|
166
|
+
* are rejected at write time. */
|
|
167
|
+
export function validateEntry(e) {
|
|
168
|
+
const errors = [];
|
|
169
|
+
if (!e.source)
|
|
170
|
+
errors.push('source required');
|
|
171
|
+
if (!e.provenance)
|
|
172
|
+
errors.push('provenance required');
|
|
173
|
+
if (typeof e.confidence !== 'number' || e.confidence < 0 || e.confidence > 1)
|
|
174
|
+
errors.push('confidence must be in [0,1]');
|
|
175
|
+
if (!e.timestamp)
|
|
176
|
+
errors.push('timestamp required');
|
|
177
|
+
if (!e.environment)
|
|
178
|
+
errors.push('environment required');
|
|
179
|
+
if (!e.session)
|
|
180
|
+
errors.push('session required');
|
|
181
|
+
if (!e.content)
|
|
182
|
+
errors.push('content required');
|
|
183
|
+
if (e.layer === 'working')
|
|
184
|
+
errors.push('working entries are runtime-only; do not persist them');
|
|
185
|
+
return errors;
|
|
186
|
+
}
|
|
187
|
+
function subjectKey(content) {
|
|
188
|
+
// crude subject extraction: the leading subject phrase, lowercased —
|
|
189
|
+
// short (2 tokens) so "X accepts Y" and "X does not accept Y" collide
|
|
190
|
+
// into one subject group for contradiction detection
|
|
191
|
+
return normalizeClaim(content).split(/\s+/).slice(0, 2).join(' ');
|
|
192
|
+
}
|
|
193
|
+
function normalizeClaim(content) {
|
|
194
|
+
return content.toLowerCase().replace(/[。.!!??,,、'"]/g, '').replace(/\s+/g, ' ').trim();
|
|
195
|
+
}
|
|
196
|
+
function recencyScore(timestamp) {
|
|
197
|
+
const age = Date.now() - new Date(timestamp).getTime();
|
|
198
|
+
const days = age / 86_400_000;
|
|
199
|
+
return Math.max(0, 1 - days / 90);
|
|
200
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - multi-agent 2.0 (blueprint §11 / MA-001..010)
|
|
3
|
+
*
|
|
4
|
+
* Roles, contracts, budgets, heartbeats and cancellation — the governance
|
|
5
|
+
* shell around the EXISTING agent/spawn + roles + topology machinery. This
|
|
6
|
+
* module does not re-implement spawning; it defines the topology contract
|
|
7
|
+
* the host bridges onto spawn_agent, with the shared blackboard the
|
|
8
|
+
* blueprint demands: goal graph, world model, evidence store, budget,
|
|
9
|
+
* approval policy, artifact store.
|
|
10
|
+
*/
|
|
11
|
+
import type { Goal } from './goal.js';
|
|
12
|
+
export type AgentRoleName = 'supervisor' | 'explorer' | 'planner' | 'implementer' | 'critic' | 'verifier' | 'researcher' | 'memory-curator';
|
|
13
|
+
export interface AgentContract {
|
|
14
|
+
role: AgentRoleName;
|
|
15
|
+
/** what this role consumes */
|
|
16
|
+
input: Record<string, string>;
|
|
17
|
+
/** what this role must produce */
|
|
18
|
+
output: Record<string, string>;
|
|
19
|
+
timeoutMs: number;
|
|
20
|
+
budget: {
|
|
21
|
+
maxActions: number;
|
|
22
|
+
maxCostUnits: number;
|
|
23
|
+
};
|
|
24
|
+
heartbeatIntervalMs: number;
|
|
25
|
+
}
|
|
26
|
+
export interface AgentNode {
|
|
27
|
+
id: string;
|
|
28
|
+
role: AgentRoleName;
|
|
29
|
+
status: 'pending' | 'running' | 'done' | 'failed' | 'cancelled';
|
|
30
|
+
contract: AgentContract;
|
|
31
|
+
lastHeartbeatAt?: string;
|
|
32
|
+
startedAt?: string;
|
|
33
|
+
endedAt?: string;
|
|
34
|
+
result?: unknown;
|
|
35
|
+
failure?: {
|
|
36
|
+
code: string;
|
|
37
|
+
message: string;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export interface SharedBlackboard {
|
|
41
|
+
goalGraph: {
|
|
42
|
+
nodes: Goal[];
|
|
43
|
+
edges: Array<{
|
|
44
|
+
from: string;
|
|
45
|
+
to: string;
|
|
46
|
+
}>;
|
|
47
|
+
};
|
|
48
|
+
/** world-model digest the agents read (belief table + uncertainty) */
|
|
49
|
+
worldDigest: {
|
|
50
|
+
beliefs: Array<{
|
|
51
|
+
claim: string;
|
|
52
|
+
confidence: number;
|
|
53
|
+
}>;
|
|
54
|
+
uncertainty: Record<string, number>;
|
|
55
|
+
};
|
|
56
|
+
evidence: string[];
|
|
57
|
+
budget: {
|
|
58
|
+
totalCostUnits: number;
|
|
59
|
+
spent: number;
|
|
60
|
+
};
|
|
61
|
+
approvals: string[];
|
|
62
|
+
artifacts: Array<{
|
|
63
|
+
id: string;
|
|
64
|
+
kind: string;
|
|
65
|
+
ref: string;
|
|
66
|
+
}>;
|
|
67
|
+
}
|
|
68
|
+
export interface TopologySpec {
|
|
69
|
+
/** roles that participate, in dependency order */
|
|
70
|
+
nodes: AgentContract[];
|
|
71
|
+
edges: Array<{
|
|
72
|
+
from: string;
|
|
73
|
+
to: string;
|
|
74
|
+
handoff: string;
|
|
75
|
+
}>;
|
|
76
|
+
}
|
|
77
|
+
export declare const ROLE_CONTRACTS: Record<AgentRoleName, AgentContract>;
|
|
78
|
+
/** MA-002/003. Compose a topology from roles with handoffs. */
|
|
79
|
+
export declare function defineTopology(roles: AgentRoleName[], handoffs?: Array<{
|
|
80
|
+
from: AgentRoleName;
|
|
81
|
+
to: AgentRoleName;
|
|
82
|
+
handoff: string;
|
|
83
|
+
}>): TopologySpec;
|
|
84
|
+
/** The supervisor-owned runtime state for one multi-agent run. */
|
|
85
|
+
export declare class AgentTopology {
|
|
86
|
+
spec: TopologySpec;
|
|
87
|
+
private nodes;
|
|
88
|
+
private blackboard;
|
|
89
|
+
private seq;
|
|
90
|
+
constructor(spec: TopologySpec, blackboard: SharedBlackboard);
|
|
91
|
+
view(): AgentNode[];
|
|
92
|
+
board(): SharedBlackboard;
|
|
93
|
+
start(id: string): void;
|
|
94
|
+
/** MA-007. Liveness signal; stale agents are visible to the supervisor. */
|
|
95
|
+
heartbeat(id: string): void;
|
|
96
|
+
/** MA-007 watchdog: running agents silent past 3x their interval. */
|
|
97
|
+
staleAgents(now?: number): AgentNode[];
|
|
98
|
+
finish(id: string, result: unknown): void;
|
|
99
|
+
fail(id: string, failure: {
|
|
100
|
+
code: string;
|
|
101
|
+
message: string;
|
|
102
|
+
}): void;
|
|
103
|
+
/** MA-008. Cancellation cascades downstream over the role handoff graph:
|
|
104
|
+
* agents whose inputs depend on a cancelled role cannot run. */
|
|
105
|
+
cancel(id: string): AgentRoleName[];
|
|
106
|
+
/** MA-009. Budget enforcement on the shared board. */
|
|
107
|
+
trySpend(costUnits: number): {
|
|
108
|
+
ok: boolean;
|
|
109
|
+
spent: number;
|
|
110
|
+
total: number;
|
|
111
|
+
};
|
|
112
|
+
addEvidence(ref: string): void;
|
|
113
|
+
addArtifact(artifact: {
|
|
114
|
+
id: string;
|
|
115
|
+
kind: string;
|
|
116
|
+
ref: string;
|
|
117
|
+
}): void;
|
|
118
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
export const ROLE_CONTRACTS = {
|
|
2
|
+
supervisor: { role: 'supervisor', input: { goal: 'the goal graph' }, output: { verdict: 'final verified result' }, timeoutMs: 30 * 60_000, budget: { maxActions: 200, maxCostUnits: 500 }, heartbeatIntervalMs: 60_000 },
|
|
3
|
+
explorer: { role: 'explorer', input: { observation: 'current environment affordances' }, output: { map: 'unknown-action report + hypotheses' }, timeoutMs: 10 * 60_000, budget: { maxActions: 30, maxCostUnits: 60 }, heartbeatIntervalMs: 30_000 },
|
|
4
|
+
planner: { role: 'planner', input: { goal: 'goal', world: 'belief table' }, output: { plan: 'ordered action proposal' }, timeoutMs: 5 * 60_000, budget: { maxActions: 15, maxCostUnits: 30 }, heartbeatIntervalMs: 30_000 },
|
|
5
|
+
implementer: { role: 'implementer', input: { plan: 'ordered actions' }, output: { changes: 'applied actions + artifacts' }, timeoutMs: 20 * 60_000, budget: { maxActions: 100, maxCostUnits: 200 }, heartbeatIntervalMs: 30_000 },
|
|
6
|
+
critic: { role: 'critic', input: { changes: 'applied changes' }, output: { review: 'risks + regressions found' }, timeoutMs: 5 * 60_000, budget: { maxActions: 10, maxCostUnits: 20 }, heartbeatIntervalMs: 30_000 },
|
|
7
|
+
verifier: { role: 'verifier', input: { changes: 'applied changes', criteria: 'success criteria' }, output: { verdict: 'pass/fail per criterion' }, timeoutMs: 10 * 60_000, budget: { maxActions: 40, maxCostUnits: 80 }, heartbeatIntervalMs: 30_000 },
|
|
8
|
+
researcher: { role: 'researcher', input: { question: 'open question' }, output: { findings: 'evidence-linked findings' }, timeoutMs: 10 * 60_000, budget: { maxActions: 30, maxCostUnits: 60 }, heartbeatIntervalMs: 30_000 },
|
|
9
|
+
'memory-curator': { role: 'memory-curator', input: { trajectory: 'finished trajectory' }, output: { memories: 'distilled entries with provenance' }, timeoutMs: 5 * 60_000, budget: { maxActions: 20, maxCostUnits: 40 }, heartbeatIntervalMs: 30_000 },
|
|
10
|
+
};
|
|
11
|
+
/** MA-002/003. Compose a topology from roles with handoffs. */
|
|
12
|
+
export function defineTopology(roles, handoffs) {
|
|
13
|
+
const seen = new Set();
|
|
14
|
+
const nodes = [];
|
|
15
|
+
for (const r of roles) {
|
|
16
|
+
if (seen.has(r))
|
|
17
|
+
continue;
|
|
18
|
+
seen.add(r);
|
|
19
|
+
nodes.push(ROLE_CONTRACTS[r]);
|
|
20
|
+
}
|
|
21
|
+
const edges = (handoffs ?? []).map((h) => ({ from: h.from, to: h.to, handoff: h.handoff }));
|
|
22
|
+
return { nodes, edges };
|
|
23
|
+
}
|
|
24
|
+
/** The supervisor-owned runtime state for one multi-agent run. */
|
|
25
|
+
export class AgentTopology {
|
|
26
|
+
spec;
|
|
27
|
+
nodes = new Map();
|
|
28
|
+
blackboard;
|
|
29
|
+
seq = 0;
|
|
30
|
+
constructor(spec, blackboard) {
|
|
31
|
+
this.spec = spec;
|
|
32
|
+
this.blackboard = blackboard;
|
|
33
|
+
for (const c of spec.nodes) {
|
|
34
|
+
const id = `${c.role}-${++this.seq}`;
|
|
35
|
+
this.nodes.set(id, { id, role: c.role, status: 'pending', contract: c });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
view() {
|
|
39
|
+
return [...this.nodes.values()];
|
|
40
|
+
}
|
|
41
|
+
board() {
|
|
42
|
+
return JSON.parse(JSON.stringify(this.blackboard));
|
|
43
|
+
}
|
|
44
|
+
start(id) {
|
|
45
|
+
const n = this.nodes.get(id);
|
|
46
|
+
if (n && n.status === 'pending') {
|
|
47
|
+
n.status = 'running';
|
|
48
|
+
n.startedAt = new Date().toISOString();
|
|
49
|
+
n.lastHeartbeatAt = n.startedAt;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** MA-007. Liveness signal; stale agents are visible to the supervisor. */
|
|
53
|
+
heartbeat(id) {
|
|
54
|
+
const n = this.nodes.get(id);
|
|
55
|
+
if (n)
|
|
56
|
+
n.lastHeartbeatAt = new Date().toISOString();
|
|
57
|
+
}
|
|
58
|
+
/** MA-007 watchdog: running agents silent past 3x their interval. */
|
|
59
|
+
staleAgents(now = Date.now()) {
|
|
60
|
+
return [...this.nodes.values()].filter((n) => n.status === 'running' && n.lastHeartbeatAt && now - new Date(n.lastHeartbeatAt).getTime() > 3 * n.contract.heartbeatIntervalMs);
|
|
61
|
+
}
|
|
62
|
+
finish(id, result) {
|
|
63
|
+
const n = this.nodes.get(id);
|
|
64
|
+
if (n && n.status === 'running') {
|
|
65
|
+
n.status = 'done';
|
|
66
|
+
n.endedAt = new Date().toISOString();
|
|
67
|
+
n.result = result;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
fail(id, failure) {
|
|
71
|
+
const n = this.nodes.get(id);
|
|
72
|
+
if (n && (n.status === 'running' || n.status === 'pending')) {
|
|
73
|
+
n.status = 'failed';
|
|
74
|
+
n.endedAt = new Date().toISOString();
|
|
75
|
+
n.failure = failure;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** MA-008. Cancellation cascades downstream over the role handoff graph:
|
|
79
|
+
* agents whose inputs depend on a cancelled role cannot run. */
|
|
80
|
+
cancel(id) {
|
|
81
|
+
const n = this.nodes.get(id);
|
|
82
|
+
if (!n)
|
|
83
|
+
return [];
|
|
84
|
+
n.status = 'cancelled';
|
|
85
|
+
n.endedAt = new Date().toISOString();
|
|
86
|
+
const cancelledRoles = new Set([n.contract.role]);
|
|
87
|
+
let expanded = true;
|
|
88
|
+
while (expanded) {
|
|
89
|
+
expanded = false;
|
|
90
|
+
for (const e of this.spec.edges) {
|
|
91
|
+
if (cancelledRoles.has(e.from) && !cancelledRoles.has(e.to)) {
|
|
92
|
+
cancelledRoles.add(e.to);
|
|
93
|
+
expanded = true;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
for (const node of this.nodes.values()) {
|
|
98
|
+
if (cancelledRoles.has(node.contract.role) && (node.status === 'pending' || node.status === 'running')) {
|
|
99
|
+
node.status = 'cancelled';
|
|
100
|
+
node.endedAt = new Date().toISOString();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return [...cancelledRoles];
|
|
104
|
+
}
|
|
105
|
+
/** MA-009. Budget enforcement on the shared board. */
|
|
106
|
+
trySpend(costUnits) {
|
|
107
|
+
const { totalCostUnits, spent } = this.blackboard.budget;
|
|
108
|
+
const ok = spent + costUnits <= totalCostUnits;
|
|
109
|
+
if (ok)
|
|
110
|
+
this.blackboard.budget.spent += costUnits;
|
|
111
|
+
return { ok, spent: this.blackboard.budget.spent, total: totalCostUnits };
|
|
112
|
+
}
|
|
113
|
+
addEvidence(ref) {
|
|
114
|
+
this.blackboard.evidence.push(ref);
|
|
115
|
+
}
|
|
116
|
+
addArtifact(artifact) {
|
|
117
|
+
this.blackboard.artifacts.push(artifact);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
/** ENV-002. What the agent sees of the world at one instant. */
|
|
21
|
+
export interface Observation {
|
|
22
|
+
environmentId: string;
|
|
23
|
+
timestamp: string;
|
|
24
|
+
/** environment-specific structured state (files, DOM, device tree…) */
|
|
25
|
+
state: unknown;
|
|
26
|
+
/** affordances the environment currently offers (ENV-003) */
|
|
27
|
+
availableActions: ActionSpec[];
|
|
28
|
+
/** optional raw payload (screenshot bytes ref, JSONL dump ref…) */
|
|
29
|
+
raw?: unknown;
|
|
30
|
+
}
|
|
31
|
+
/** ENV-003. Declarative affordance: what an action needs and returns. */
|
|
32
|
+
export interface ActionSpec {
|
|
33
|
+
id: string;
|
|
34
|
+
type: string;
|
|
35
|
+
description?: string;
|
|
36
|
+
argsSchema?: Record<string, unknown>;
|
|
37
|
+
/** declared cost used by exploration budgeting (arbitrary units) */
|
|
38
|
+
cost?: number;
|
|
39
|
+
/** true when the action cannot undo itself (delete, publish, deploy) */
|
|
40
|
+
irreversible?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/** ENV-003. What the agent does. `reason` is mandatory culture: decisions
|
|
43
|
+
* are observable (AHE decision observability, blueprint §10). */
|
|
44
|
+
export interface Action {
|
|
45
|
+
id: string;
|
|
46
|
+
type: string;
|
|
47
|
+
args: Record<string, unknown>;
|
|
48
|
+
reason?: string;
|
|
49
|
+
}
|
|
50
|
+
export interface ActionResult {
|
|
51
|
+
actionId: string;
|
|
52
|
+
outcome: 'success' | 'failure' | 'unknown';
|
|
53
|
+
/** structured error, never a bare string (blueprint coding discipline) */
|
|
54
|
+
error?: {
|
|
55
|
+
code: string;
|
|
56
|
+
message: string;
|
|
57
|
+
};
|
|
58
|
+
output?: unknown;
|
|
59
|
+
observationRef?: string;
|
|
60
|
+
durationMs?: number;
|
|
61
|
+
cost?: number;
|
|
62
|
+
}
|
|
63
|
+
export interface ResetOptions {
|
|
64
|
+
/** deterministic seed when the environment supports replay */
|
|
65
|
+
seed?: string;
|
|
66
|
+
/** scratch root for filesystem-backed environments */
|
|
67
|
+
workspaceDir?: string;
|
|
68
|
+
}
|
|
69
|
+
/** ENV-004. Restorable world state. stateHash detects divergence on restore. */
|
|
70
|
+
export interface Snapshot {
|
|
71
|
+
environmentId: string;
|
|
72
|
+
version: number;
|
|
73
|
+
takenAt: string;
|
|
74
|
+
stateHash: string;
|
|
75
|
+
payload: unknown;
|
|
76
|
+
}
|
|
77
|
+
/** The environment's self-assessment. Never the only promotion signal. */
|
|
78
|
+
export interface EnvironmentScore {
|
|
79
|
+
environmentId: string;
|
|
80
|
+
metrics: Record<string, number>;
|
|
81
|
+
details?: string;
|
|
82
|
+
}
|
|
83
|
+
/** ENV-001. The world contract. observe/act/reset/snapshot/restore/evaluate/close. */
|
|
84
|
+
export interface Environment {
|
|
85
|
+
id: string;
|
|
86
|
+
version: string;
|
|
87
|
+
capabilities(): Promise<Capability[]>;
|
|
88
|
+
reset(opts?: ResetOptions): Promise<Observation>;
|
|
89
|
+
observe(): Promise<Observation>;
|
|
90
|
+
act(action: Action): Promise<ActionResult>;
|
|
91
|
+
snapshot(): Promise<Snapshot>;
|
|
92
|
+
restore(snapshot: Snapshot): Promise<void>;
|
|
93
|
+
evaluate(): Promise<EnvironmentScore>;
|
|
94
|
+
close(): Promise<void>;
|
|
95
|
+
}
|
|
96
|
+
/** ENV-006. What an environment can do, discovered not assumed. */
|
|
97
|
+
export interface Capability {
|
|
98
|
+
kind: 'observe' | 'act' | 'evaluate' | 'snapshot' | 'restore' | 'network' | 'filesystem' | 'process' | 'display';
|
|
99
|
+
detail: string;
|
|
100
|
+
/** absent = fully available; present = degraded and why (honesty rule) */
|
|
101
|
+
limitation?: string;
|
|
102
|
+
}
|
|
103
|
+
export interface TrajectoryStep {
|
|
104
|
+
step: number;
|
|
105
|
+
observationRef?: string;
|
|
106
|
+
action: Action;
|
|
107
|
+
prediction?: {
|
|
108
|
+
claim: string;
|
|
109
|
+
confidence: number;
|
|
110
|
+
};
|
|
111
|
+
outcome: 'success' | 'failure' | 'unknown';
|
|
112
|
+
reward?: number;
|
|
113
|
+
evidence: string[];
|
|
114
|
+
toolCallId?: string;
|
|
115
|
+
durationMs?: number;
|
|
116
|
+
}
|
|
117
|
+
export interface TrajectoryMetrics {
|
|
118
|
+
success: boolean;
|
|
119
|
+
actions: number;
|
|
120
|
+
elapsedMs: number;
|
|
121
|
+
recoveryCount: number;
|
|
122
|
+
/** prediction calibration on this trajectory (Brier score, lower=better) */
|
|
123
|
+
brierScore?: number;
|
|
124
|
+
}
|
|
125
|
+
export interface CognitiveTrajectory {
|
|
126
|
+
id: string;
|
|
127
|
+
sessionId: string;
|
|
128
|
+
environment: {
|
|
129
|
+
id: string;
|
|
130
|
+
version: string;
|
|
131
|
+
};
|
|
132
|
+
goal?: {
|
|
133
|
+
id: string;
|
|
134
|
+
description: string;
|
|
135
|
+
};
|
|
136
|
+
steps: TrajectoryStep[];
|
|
137
|
+
metrics: TrajectoryMetrics;
|
|
138
|
+
startedAt: string;
|
|
139
|
+
endedAt?: string;
|
|
140
|
+
}
|
|
141
|
+
export declare const TRAJECTORY_SCHEMA_VERSION = 1;
|
|
142
|
+
export declare function validateAction(a: unknown): {
|
|
143
|
+
valid: boolean;
|
|
144
|
+
errors: string[];
|
|
145
|
+
};
|
|
146
|
+
export declare function validateObservation(o: unknown): {
|
|
147
|
+
valid: boolean;
|
|
148
|
+
errors: string[];
|
|
149
|
+
};
|
|
150
|
+
export declare function validateTrajectory(t: unknown): {
|
|
151
|
+
valid: boolean;
|
|
152
|
+
errors: string[];
|
|
153
|
+
};
|
|
154
|
+
/** Deterministic non-crypto hash for stateHash / replay divergence checks. */
|
|
155
|
+
export declare function stableHash(value: unknown): string;
|