@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
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - exploration engine (blueprint §5 / EXP-001..010)
|
|
3
|
+
*
|
|
4
|
+
* NOT random exploration: the policy ranks candidate actions by
|
|
5
|
+
* score = w_u*uncertaintyReduction + w_i*informationGain
|
|
6
|
+
* + w_g*goalRelevance - w_r*risk
|
|
7
|
+
* under a hard action/cost budget (EXP-008), and every exploration run is a
|
|
8
|
+
* hypothesis -> experiment -> observation -> belief update loop (EXP-005/006):
|
|
9
|
+
* a HypothesisRegistry tracks claims with expected evidence; outcomes resolve
|
|
10
|
+
* them into world-model belief updates or explicit refutations.
|
|
11
|
+
*/
|
|
12
|
+
import type { Action, ActionSpec, Observation } from './protocol.js';
|
|
13
|
+
import type { WorldModel } from './world-model.js';
|
|
14
|
+
export interface Hypothesis {
|
|
15
|
+
id: string;
|
|
16
|
+
claim: string;
|
|
17
|
+
/** what observation would support it */
|
|
18
|
+
expectedEvidence: string;
|
|
19
|
+
/** what observation would refute it */
|
|
20
|
+
refutingEvidence: string;
|
|
21
|
+
status: 'open' | 'supported' | 'refuted';
|
|
22
|
+
createdAt: string;
|
|
23
|
+
resolvedAt?: string;
|
|
24
|
+
note?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare class HypothesisRegistry {
|
|
27
|
+
private items;
|
|
28
|
+
private seq;
|
|
29
|
+
register(h: Omit<Hypothesis, 'id' | 'status' | 'createdAt'>): Hypothesis;
|
|
30
|
+
open(): Hypothesis[];
|
|
31
|
+
all(): readonly Hypothesis[];
|
|
32
|
+
resolve(id: string, status: 'supported' | 'refuted', note?: string): void;
|
|
33
|
+
}
|
|
34
|
+
export interface ExplorationContext {
|
|
35
|
+
observation: Observation;
|
|
36
|
+
worldModel: WorldModel;
|
|
37
|
+
goalKeywords?: string[];
|
|
38
|
+
hypotheses: HypothesisRegistry;
|
|
39
|
+
}
|
|
40
|
+
export interface ExplorationOutcome {
|
|
41
|
+
action: Action;
|
|
42
|
+
result: {
|
|
43
|
+
outcome: string;
|
|
44
|
+
};
|
|
45
|
+
hypothesisId?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface ExplorationRunOptions {
|
|
48
|
+
maxActions: number;
|
|
49
|
+
maxCost: number;
|
|
50
|
+
riskTolerance: number;
|
|
51
|
+
weights?: Partial<{
|
|
52
|
+
uncertainty: number;
|
|
53
|
+
information: number;
|
|
54
|
+
goal: number;
|
|
55
|
+
risk: number;
|
|
56
|
+
}>;
|
|
57
|
+
chooseAction?: (candidates: Array<{
|
|
58
|
+
spec: ActionSpec;
|
|
59
|
+
score: number;
|
|
60
|
+
}>) => ActionSpec | undefined;
|
|
61
|
+
}
|
|
62
|
+
export interface ExplorationResult {
|
|
63
|
+
actionsTaken: number;
|
|
64
|
+
costSpent: number;
|
|
65
|
+
hypothesesResolved: number;
|
|
66
|
+
unknownActionTypesBefore: number;
|
|
67
|
+
unknownActionTypesAfter: number;
|
|
68
|
+
aborted?: 'budget' | 'no-candidates' | 'risk';
|
|
69
|
+
}
|
|
70
|
+
export interface ExplorationPolicy {
|
|
71
|
+
selectAction(ctx: ExplorationContext, opts: ExplorationRunOptions): Promise<Action | undefined>;
|
|
72
|
+
informationGain(action: Action, state: {
|
|
73
|
+
uncertaintyByAction: Record<string, number>;
|
|
74
|
+
}): Promise<number>;
|
|
75
|
+
novelty(state: unknown, seenStates: unknown[]): number;
|
|
76
|
+
risk(action: Action): number;
|
|
77
|
+
}
|
|
78
|
+
/** EXP-002. Novelty = fraction of unseen structural features vs history. */
|
|
79
|
+
export declare function noveltyScore(state: unknown, seenStates: unknown[]): number;
|
|
80
|
+
export declare class UcbExplorationPolicy implements ExplorationPolicy {
|
|
81
|
+
private weights;
|
|
82
|
+
constructor(weights?: Required<NonNullable<ExplorationRunOptions['weights']>>);
|
|
83
|
+
informationGain(action: Action, state: {
|
|
84
|
+
uncertaintyByAction: Record<string, number>;
|
|
85
|
+
}): Promise<number>;
|
|
86
|
+
novelty(state: unknown, seenStates: unknown[]): number;
|
|
87
|
+
risk(action: Action): number;
|
|
88
|
+
selectAction(ctx: ExplorationContext, opts: ExplorationRunOptions): Promise<Action | undefined>;
|
|
89
|
+
private goalScore;
|
|
90
|
+
}
|
|
91
|
+
export declare class ExplorationEngine {
|
|
92
|
+
private policy;
|
|
93
|
+
private seenStates;
|
|
94
|
+
outcomeLog: ExplorationOutcome[];
|
|
95
|
+
constructor(policy?: ExplorationPolicy);
|
|
96
|
+
/** Run the explore loop against an act() callable. The caller owns the
|
|
97
|
+
* environment; the engine owns budgeting, hypothesis bookkeeping and
|
|
98
|
+
* novelty tracking. */
|
|
99
|
+
run(opts: ExplorationRunOptions & {
|
|
100
|
+
ctx: ExplorationContext;
|
|
101
|
+
act: (a: Action) => Promise<{
|
|
102
|
+
outcome: string;
|
|
103
|
+
}>;
|
|
104
|
+
}): Promise<ExplorationResult>;
|
|
105
|
+
updateFromOutcome(_outcome: ExplorationOutcome): void;
|
|
106
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
export class HypothesisRegistry {
|
|
2
|
+
items = [];
|
|
3
|
+
seq = 0;
|
|
4
|
+
register(h) {
|
|
5
|
+
const full = { ...h, id: `hyp-${++this.seq}`, status: 'open', createdAt: new Date().toISOString() };
|
|
6
|
+
this.items.push(full);
|
|
7
|
+
return full;
|
|
8
|
+
}
|
|
9
|
+
open() {
|
|
10
|
+
return this.items.filter((h) => h.status === 'open');
|
|
11
|
+
}
|
|
12
|
+
all() {
|
|
13
|
+
return this.items;
|
|
14
|
+
}
|
|
15
|
+
resolve(id, status, note) {
|
|
16
|
+
const h = this.items.find((x) => x.id === id);
|
|
17
|
+
if (h && h.status === 'open') {
|
|
18
|
+
h.status = status;
|
|
19
|
+
h.resolvedAt = new Date().toISOString();
|
|
20
|
+
h.note = note;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** EXP-002. Novelty = fraction of unseen structural features vs history. */
|
|
25
|
+
export function noveltyScore(state, seenStates) {
|
|
26
|
+
if (seenStates.length === 0)
|
|
27
|
+
return 1;
|
|
28
|
+
const features = stateFeatures(state);
|
|
29
|
+
const seen = new Set();
|
|
30
|
+
for (const s of seenStates)
|
|
31
|
+
for (const f of stateFeatures(s))
|
|
32
|
+
seen.add(f);
|
|
33
|
+
const unseen = [...features].filter((f) => !seen.has(f));
|
|
34
|
+
return features.length ? unseen.length / features.length : 0;
|
|
35
|
+
}
|
|
36
|
+
function stateFeatures(state, prefix = '') {
|
|
37
|
+
if (typeof state !== 'object' || state === null)
|
|
38
|
+
return [`${prefix}=${String(state)}`];
|
|
39
|
+
if (Array.isArray(state)) {
|
|
40
|
+
const out = [];
|
|
41
|
+
state.slice(0, 20).forEach((v, i) => out.push(...stateFeatures(v, `${prefix}[${i}]`)));
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
const out = [];
|
|
45
|
+
Object.entries(state).slice(0, 30).forEach(([k, v]) => {
|
|
46
|
+
out.push(...stateFeatures(v, prefix ? `${prefix}.${k}` : k));
|
|
47
|
+
});
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
export class UcbExplorationPolicy {
|
|
51
|
+
weights;
|
|
52
|
+
constructor(weights = {
|
|
53
|
+
uncertainty: 0.35,
|
|
54
|
+
information: 0.25,
|
|
55
|
+
goal: 0.25,
|
|
56
|
+
risk: 0.15,
|
|
57
|
+
}) {
|
|
58
|
+
this.weights = weights;
|
|
59
|
+
}
|
|
60
|
+
async informationGain(action, state) {
|
|
61
|
+
// actions of an uncertain type carry more information: resolving high
|
|
62
|
+
// uncertainty teaches more than re-confirming a known action
|
|
63
|
+
return state.uncertaintyByAction[action.type] ?? 1;
|
|
64
|
+
}
|
|
65
|
+
novelty(state, seenStates) {
|
|
66
|
+
return noveltyScore(state, seenStates);
|
|
67
|
+
}
|
|
68
|
+
risk(action) {
|
|
69
|
+
// structural risk: irreversible affordances and destructive verbs
|
|
70
|
+
const verbs = ['delete', 'remove', 'drop', 'publish', 'deploy', 'send', 'reset', 'format', 'kill'];
|
|
71
|
+
const hay = `${action.type} ${Object.keys(action.args).join(' ')}`.toLowerCase();
|
|
72
|
+
return verbs.some((v) => hay.includes(v)) ? 0.8 : 0.1;
|
|
73
|
+
}
|
|
74
|
+
async selectAction(ctx, opts) {
|
|
75
|
+
const wm = ctx.worldModel.worldState;
|
|
76
|
+
const seenStates = [];
|
|
77
|
+
const candidates = [];
|
|
78
|
+
for (const spec of ctx.observation.availableActions) {
|
|
79
|
+
const probe = { id: `explore-${spec.id}`, type: spec.type, args: {}, reason: 'exploration probe' };
|
|
80
|
+
const uncertainty = wm.uncertainty.byAction[spec.type] ?? 1;
|
|
81
|
+
const info = await this.informationGain(probe, { uncertaintyByAction: wm.uncertainty.byAction });
|
|
82
|
+
const goalRelevance = this.goalScore(spec, ctx.goalKeywords ?? []);
|
|
83
|
+
const risk = this.risk(probe) + (spec.irreversible ? 0.4 : 0);
|
|
84
|
+
if (risk > opts.riskTolerance)
|
|
85
|
+
continue; // EXP-007 safe exploration
|
|
86
|
+
const score = this.weights.uncertainty * uncertainty +
|
|
87
|
+
this.weights.information * info +
|
|
88
|
+
this.weights.goal * goalRelevance -
|
|
89
|
+
this.weights.risk * risk;
|
|
90
|
+
candidates.push({ spec, score });
|
|
91
|
+
}
|
|
92
|
+
if (candidates.length === 0)
|
|
93
|
+
return undefined;
|
|
94
|
+
candidates.sort((a, b) => b.score - a.score);
|
|
95
|
+
const chosen = opts.chooseAction ? opts.chooseAction(candidates) : candidates[0].spec;
|
|
96
|
+
if (!chosen)
|
|
97
|
+
return undefined;
|
|
98
|
+
seenStates.push(ctx.observation.state);
|
|
99
|
+
return { id: `explore-${chosen.id}`, type: chosen.type, args: defaultArgs(chosen), reason: `exploration: top-scored affordance (${chosen.id})` };
|
|
100
|
+
}
|
|
101
|
+
goalScore(spec, keywords) {
|
|
102
|
+
if (keywords.length === 0)
|
|
103
|
+
return 0.5;
|
|
104
|
+
const hay = `${spec.type} ${spec.description ?? ''} ${spec.id}`.toLowerCase();
|
|
105
|
+
const hits = keywords.filter((k) => hay.includes(k)).length;
|
|
106
|
+
return keywords.length ? hits / keywords.length : 0;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function defaultArgs(spec) {
|
|
110
|
+
const args = {};
|
|
111
|
+
const schema = spec.argsSchema ?? {};
|
|
112
|
+
for (const [k, v] of Object.entries(schema)) {
|
|
113
|
+
args[k] = typeof v === 'string' && v.includes('string') ? 'probe' : null;
|
|
114
|
+
}
|
|
115
|
+
return args;
|
|
116
|
+
}
|
|
117
|
+
export class ExplorationEngine {
|
|
118
|
+
policy;
|
|
119
|
+
seenStates = [];
|
|
120
|
+
outcomeLog = [];
|
|
121
|
+
constructor(policy) {
|
|
122
|
+
this.policy = policy ?? new UcbExplorationPolicy();
|
|
123
|
+
}
|
|
124
|
+
/** Run the explore loop against an act() callable. The caller owns the
|
|
125
|
+
* environment; the engine owns budgeting, hypothesis bookkeeping and
|
|
126
|
+
* novelty tracking. */
|
|
127
|
+
async run(opts) {
|
|
128
|
+
const unknownBefore = opts.ctx.worldModel.worldState.uncertainty.byAction;
|
|
129
|
+
let actions = 0;
|
|
130
|
+
let cost = 0;
|
|
131
|
+
let hypothesesResolved = 0;
|
|
132
|
+
let lastObs = opts.ctx.observation.state;
|
|
133
|
+
while (actions < opts.maxActions && cost < opts.maxCost) {
|
|
134
|
+
const action = await this.policy.selectAction(opts.ctx, opts);
|
|
135
|
+
if (!action) {
|
|
136
|
+
return { actionsTaken: actions, costSpent: cost, hypothesesResolved, unknownActionTypesBefore: countUnknown(unknownBefore), unknownActionTypesAfter: countUnknown(opts.ctx.worldModel.worldState.uncertainty.byAction), aborted: 'no-candidates' };
|
|
137
|
+
}
|
|
138
|
+
const spec = opts.ctx.observation.availableActions.find((s) => s.type === action.type);
|
|
139
|
+
const stepCost = spec?.cost ?? 1;
|
|
140
|
+
const risk = await Promise.resolve(this.policy.risk(action));
|
|
141
|
+
if (risk > opts.riskTolerance) {
|
|
142
|
+
return { actionsTaken: actions, costSpent: cost, hypothesesResolved, unknownActionTypesBefore: countUnknown(unknownBefore), unknownActionTypesAfter: countUnknown(opts.ctx.worldModel.worldState.uncertainty.byAction), aborted: 'risk' };
|
|
143
|
+
}
|
|
144
|
+
const result = await opts.act(action);
|
|
145
|
+
actions += 1;
|
|
146
|
+
cost += stepCost;
|
|
147
|
+
this.outcomeLog.push({ action, result });
|
|
148
|
+
this.seenStates.push(lastObs);
|
|
149
|
+
// belief update happens through the caller's worldModel.update in the
|
|
150
|
+
// act loop; here we only track novelty of the new state
|
|
151
|
+
lastObs = opts.ctx.observation.state;
|
|
152
|
+
const open = opts.ctx.hypotheses.open();
|
|
153
|
+
for (const h of open.slice(0, 3)) {
|
|
154
|
+
// resolve hypotheses whose expected/refuting evidence matches outcome
|
|
155
|
+
const successLike = result.outcome === 'success';
|
|
156
|
+
if (h.expectedEvidence.includes('succeeds') && successLike) {
|
|
157
|
+
opts.ctx.hypotheses.resolve(h.id, 'supported', `action ${action.type} succeeded`);
|
|
158
|
+
hypothesesResolved += 1;
|
|
159
|
+
}
|
|
160
|
+
else if (h.refutingEvidence.includes('fails') && !successLike) {
|
|
161
|
+
opts.ctx.hypotheses.resolve(h.id, 'refuted', `action ${action.type} -> ${result.outcome}`);
|
|
162
|
+
hypothesesResolved += 1;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
actionsTaken: actions,
|
|
168
|
+
costSpent: cost,
|
|
169
|
+
hypothesesResolved,
|
|
170
|
+
unknownActionTypesBefore: countUnknown(unknownBefore),
|
|
171
|
+
unknownActionTypesAfter: countUnknown(opts.ctx.worldModel.worldState.uncertainty.byAction),
|
|
172
|
+
aborted: actions >= opts.maxActions || cost >= opts.maxCost ? 'budget' : undefined,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
updateFromOutcome(_outcome) {
|
|
176
|
+
// policy currently stateless beyond novelty history; hook kept for
|
|
177
|
+
// learned-policies (EXP: updateFromOutcome contract in blueprint)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function countUnknown(map) {
|
|
181
|
+
return Object.values(map).filter((u) => u >= 0.95).length;
|
|
182
|
+
}
|
package/dist/goal.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - goal system (blueprint §4 / GOAL-001..010)
|
|
3
|
+
*
|
|
4
|
+
* Goals form a graph (parent/sub), each with executable success criteria.
|
|
5
|
+
* Safety rules from the blueprint, enforced structurally:
|
|
6
|
+
* - source "intrinsic" goals are ALWAYS proposals: adopt() refuses them
|
|
7
|
+
* unless approved=true (GOAL-008 gate lives here, not in a caller's good
|
|
8
|
+
* intentions)
|
|
9
|
+
* - goals declaring real-world side effects (sideEffects=true) require the
|
|
10
|
+
* same explicit approval
|
|
11
|
+
* - detectDrift compares the trajectory's outcomes against the goal's
|
|
12
|
+
* success criteria and returns a report the supervisor can pause on
|
|
13
|
+
*/
|
|
14
|
+
import type { Transition } from './world-model.js';
|
|
15
|
+
export interface Constraint {
|
|
16
|
+
kind: 'time' | 'budget' | 'capability' | 'safety';
|
|
17
|
+
expression: string;
|
|
18
|
+
}
|
|
19
|
+
/** GOAL-004 hooks: executable checks, injected by the host (CLI/web/agent).
|
|
20
|
+
* Returning false = criterion not (yet) met; throwing = check itself
|
|
21
|
+
* failed and counts as unknown, never as pass. */
|
|
22
|
+
export type CriterionCheck = (goal: Goal, context: GoalContext) => boolean | Promise<boolean>;
|
|
23
|
+
export interface SuccessCriterion {
|
|
24
|
+
id: string;
|
|
25
|
+
description: string;
|
|
26
|
+
/** structural predicate over the final world state / last observation */
|
|
27
|
+
check?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface Goal {
|
|
30
|
+
id: string;
|
|
31
|
+
description: string;
|
|
32
|
+
source: 'user' | 'environment' | 'intrinsic' | 'subagent';
|
|
33
|
+
priority: number;
|
|
34
|
+
constraints: Constraint[];
|
|
35
|
+
successCriteria: SuccessCriterion[];
|
|
36
|
+
deadline?: string;
|
|
37
|
+
parentGoalId?: string;
|
|
38
|
+
/** declared real-world side effects (deploys, sends, deletions) */
|
|
39
|
+
sideEffects?: string[];
|
|
40
|
+
/** lifecycle */
|
|
41
|
+
status: 'proposed' | 'active' | 'achieved' | 'abandoned' | 'blocked';
|
|
42
|
+
createdAt: string;
|
|
43
|
+
}
|
|
44
|
+
export interface GoalContext {
|
|
45
|
+
sessionId: string;
|
|
46
|
+
workspaceDir?: string;
|
|
47
|
+
/** host-provided criterion evaluators keyed by criterion check string */
|
|
48
|
+
evaluators?: Record<string, CriterionCheck>;
|
|
49
|
+
budgetMs?: number;
|
|
50
|
+
elapsedMs?: number;
|
|
51
|
+
actionsTaken?: number;
|
|
52
|
+
}
|
|
53
|
+
export interface GoalDriftReport {
|
|
54
|
+
goalId: string;
|
|
55
|
+
driftScore: number;
|
|
56
|
+
signals: string[];
|
|
57
|
+
recommendation: 'continue' | 'pause' | 'request-confirmation' | 'abandon';
|
|
58
|
+
}
|
|
59
|
+
export declare class GoalManager {
|
|
60
|
+
private goals;
|
|
61
|
+
list(): Goal[];
|
|
62
|
+
get(id: string): Goal | undefined;
|
|
63
|
+
/** GOAL-007. Intrinsic goals enter as proposals only. */
|
|
64
|
+
propose(goal: Omit<Goal, 'status' | 'createdAt'>): Goal;
|
|
65
|
+
/** GOAL-008. The approval gate. High-impact = intrinsic source OR declared
|
|
66
|
+
* side effects; those cannot be activated without explicit approval. */
|
|
67
|
+
adopt(goalId: string, opts?: {
|
|
68
|
+
approved?: boolean;
|
|
69
|
+
}): Promise<void>;
|
|
70
|
+
/** GOAL-003. Decomposition is host-injectable: the default splitter is a
|
|
71
|
+
* deterministic one-criterion-per-subgoal carve; LLM decomposition plugs
|
|
72
|
+
* in by passing a custom decomposer. Subgoals inherit constraints and
|
|
73
|
+
* reference the parent. */
|
|
74
|
+
decompose(goalId: string, decomposer?: (goal: Goal) => Array<{
|
|
75
|
+
description: string;
|
|
76
|
+
successCriteria: SuccessCriterion[];
|
|
77
|
+
}>): Promise<Goal[]>;
|
|
78
|
+
/** GOAL-004. Score = priority x progress(criteria) x urgency(deadline). */
|
|
79
|
+
score(goal: Goal, context: GoalContext): Promise<number>;
|
|
80
|
+
checkCriteria(goal: Goal, context: GoalContext): Promise<Array<{
|
|
81
|
+
criterion: SuccessCriterion;
|
|
82
|
+
met: boolean | 'unknown';
|
|
83
|
+
}>>;
|
|
84
|
+
/** GOAL-005. Drift = trajectory stops serving the goal's success criteria.
|
|
85
|
+
* Signals: low criterion coverage of recent actions, budget overrun with
|
|
86
|
+
* zero met criteria, repeated failures on unrelated action types. */
|
|
87
|
+
detectDrift(goal: Goal, trajectory: Transition[], context: GoalContext): GoalDriftReport;
|
|
88
|
+
/** GOAL-002. The graph view: parent -> children edges with statuses. */
|
|
89
|
+
graph(): {
|
|
90
|
+
nodes: Goal[];
|
|
91
|
+
edges: Array<{
|
|
92
|
+
from: string;
|
|
93
|
+
to: string;
|
|
94
|
+
}>;
|
|
95
|
+
};
|
|
96
|
+
mark(goalId: string, status: Goal['status']): void;
|
|
97
|
+
}
|
package/dist/goal.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
export class GoalManager {
|
|
2
|
+
goals = new Map();
|
|
3
|
+
list() {
|
|
4
|
+
return [...this.goals.values()];
|
|
5
|
+
}
|
|
6
|
+
get(id) {
|
|
7
|
+
return this.goals.get(id);
|
|
8
|
+
}
|
|
9
|
+
/** GOAL-007. Intrinsic goals enter as proposals only. */
|
|
10
|
+
propose(goal) {
|
|
11
|
+
const g = {
|
|
12
|
+
...goal,
|
|
13
|
+
status: goal.source === 'intrinsic' ? 'proposed' : 'proposed',
|
|
14
|
+
createdAt: new Date().toISOString(),
|
|
15
|
+
};
|
|
16
|
+
this.goals.set(g.id, g);
|
|
17
|
+
return g;
|
|
18
|
+
}
|
|
19
|
+
/** GOAL-008. The approval gate. High-impact = intrinsic source OR declared
|
|
20
|
+
* side effects; those cannot be activated without explicit approval. */
|
|
21
|
+
async adopt(goalId, opts) {
|
|
22
|
+
const g = this.goals.get(goalId);
|
|
23
|
+
if (!g)
|
|
24
|
+
throw new Error(`unknown goal ${goalId}`);
|
|
25
|
+
const highImpact = g.source === 'intrinsic' || (g.sideEffects ?? []).length > 0;
|
|
26
|
+
if (highImpact && !opts?.approved) {
|
|
27
|
+
throw new Error(`goal ${goalId} is high-impact (source=${g.source}, sideEffects=${(g.sideEffects ?? []).join(',') || 'none'}) and requires explicit approval`);
|
|
28
|
+
}
|
|
29
|
+
g.status = 'active';
|
|
30
|
+
}
|
|
31
|
+
/** GOAL-003. Decomposition is host-injectable: the default splitter is a
|
|
32
|
+
* deterministic one-criterion-per-subgoal carve; LLM decomposition plugs
|
|
33
|
+
* in by passing a custom decomposer. Subgoals inherit constraints and
|
|
34
|
+
* reference the parent. */
|
|
35
|
+
async decompose(goalId, decomposer) {
|
|
36
|
+
const parent = this.goals.get(goalId);
|
|
37
|
+
if (!parent)
|
|
38
|
+
throw new Error(`unknown goal ${goalId}`);
|
|
39
|
+
const parts = decomposer
|
|
40
|
+
? decomposer(parent)
|
|
41
|
+
: parent.successCriteria.map((c, i) => ({ description: `${parent.description} — criterion ${i + 1}: ${c.description}`, successCriteria: [c] }));
|
|
42
|
+
return parts.map((p, i) => {
|
|
43
|
+
const sub = {
|
|
44
|
+
id: `${parent.id}/sub-${i + 1}`,
|
|
45
|
+
description: p.description,
|
|
46
|
+
source: 'subagent',
|
|
47
|
+
priority: parent.priority,
|
|
48
|
+
constraints: parent.constraints,
|
|
49
|
+
successCriteria: p.successCriteria,
|
|
50
|
+
parentGoalId: parent.id,
|
|
51
|
+
status: 'active',
|
|
52
|
+
createdAt: new Date().toISOString(),
|
|
53
|
+
};
|
|
54
|
+
this.goals.set(sub.id, sub);
|
|
55
|
+
return sub;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** GOAL-004. Score = priority x progress(criteria) x urgency(deadline). */
|
|
59
|
+
async score(goal, context) {
|
|
60
|
+
const results = await this.checkCriteria(goal, context);
|
|
61
|
+
const met = results.filter((r) => r.met).length;
|
|
62
|
+
const progress = results.length ? met / results.length : 0;
|
|
63
|
+
let urgency = 1;
|
|
64
|
+
if (goal.deadline) {
|
|
65
|
+
const remainMs = new Date(goal.deadline).getTime() - Date.now();
|
|
66
|
+
urgency = remainMs < 0 ? 0.2 : remainMs < 3_600_000 ? 1.5 : 1;
|
|
67
|
+
}
|
|
68
|
+
const budgetPenalty = context.budgetMs && context.elapsedMs && context.elapsedMs > context.budgetMs ? 0.5 : 1;
|
|
69
|
+
return Number((goal.priority * progress * urgency * budgetPenalty).toFixed(4));
|
|
70
|
+
}
|
|
71
|
+
async checkCriteria(goal, context) {
|
|
72
|
+
const out = [];
|
|
73
|
+
for (const c of goal.successCriteria) {
|
|
74
|
+
const fn = c.check ? context.evaluators?.[c.check] : undefined;
|
|
75
|
+
if (!fn) {
|
|
76
|
+
out.push({ criterion: c, met: 'unknown' });
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
out.push({ criterion: c, met: await fn(goal, context) });
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
out.push({ criterion: c, met: 'unknown' });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
/** GOAL-005. Drift = trajectory stops serving the goal's success criteria.
|
|
89
|
+
* Signals: low criterion coverage of recent actions, budget overrun with
|
|
90
|
+
* zero met criteria, repeated failures on unrelated action types. */
|
|
91
|
+
detectDrift(goal, trajectory, context) {
|
|
92
|
+
const signals = [];
|
|
93
|
+
const keywords = extractKeywords(goal);
|
|
94
|
+
const recent = trajectory.slice(-20);
|
|
95
|
+
const relevant = recent.filter((t) => mentionsAny(t.action, keywords)).length;
|
|
96
|
+
const coverage = recent.length ? relevant / recent.length : 1;
|
|
97
|
+
// nearly-zero goal coverage is a STRONG signal on its own
|
|
98
|
+
const offCourse = recent.length >= 5 && coverage < 0.15;
|
|
99
|
+
if (recent.length >= 5 && coverage < 0.3)
|
|
100
|
+
signals.push(`only ${Math.round(coverage * 100)}% of recent actions reference goal keywords`);
|
|
101
|
+
const failures = recent.filter((t) => t.outcome === 'failure').length;
|
|
102
|
+
if (recent.length >= 5 && failures / recent.length > 0.7)
|
|
103
|
+
signals.push(`${failures}/${recent.length} recent transitions failed`);
|
|
104
|
+
if (context.budgetMs && (context.elapsedMs ?? 0) > context.budgetMs)
|
|
105
|
+
signals.push('budget exceeded');
|
|
106
|
+
const driftScore = Number(Math.min(1, signals.length * 0.35 + (1 - coverage) * 0.3).toFixed(3));
|
|
107
|
+
let recommendation = 'continue';
|
|
108
|
+
if (signals.length >= 2 || driftScore >= 0.7 || offCourse)
|
|
109
|
+
recommendation = goal.source === 'user' ? 'request-confirmation' : 'pause';
|
|
110
|
+
return { goalId: goal.id, driftScore, signals, recommendation };
|
|
111
|
+
}
|
|
112
|
+
/** GOAL-002. The graph view: parent -> children edges with statuses. */
|
|
113
|
+
graph() {
|
|
114
|
+
const nodes = [...this.goals.values()];
|
|
115
|
+
const edges = nodes.filter((n) => n.parentGoalId).map((n) => ({ from: n.parentGoalId, to: n.id }));
|
|
116
|
+
return { nodes, edges };
|
|
117
|
+
}
|
|
118
|
+
mark(goalId, status) {
|
|
119
|
+
const g = this.goals.get(goalId);
|
|
120
|
+
if (g)
|
|
121
|
+
g.status = status;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function extractKeywords(goal) {
|
|
125
|
+
return goal.description
|
|
126
|
+
.toLowerCase()
|
|
127
|
+
.split(/[^\p{L}\p{N}_-]+/u)
|
|
128
|
+
.filter((w) => w.length >= 3);
|
|
129
|
+
}
|
|
130
|
+
function mentionsAny(action, keywords) {
|
|
131
|
+
const hay = `${action.type} ${action.reason ?? ''} ${Object.keys(action.args).join(' ')}`.toLowerCase();
|
|
132
|
+
return keywords.some((k) => hay.includes(k));
|
|
133
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - the Cognitive OS core layer
|
|
3
|
+
*
|
|
4
|
+
* Blueprint: HMH Cognitive OS (2026-09). Kernel stays the source of truth;
|
|
5
|
+
* this layer owns cognitive STRATEGY: environment protocol, world model,
|
|
6
|
+
* goals, exploration, RLM, five-layer memory, skill compilation, continual
|
|
7
|
+
* learning control plane, evolution-2.0 governance, multi-agent topology,
|
|
8
|
+
* GeneralBench and the transfer lab. Nothing here touches approval/sandbox
|
|
9
|
+
* internals — governance composes them, never bypasses them.
|
|
10
|
+
*/
|
|
11
|
+
export * from './protocol.js';
|
|
12
|
+
export * from './registry.js';
|
|
13
|
+
export * from './trajectory.js';
|
|
14
|
+
export * from './world-model.js';
|
|
15
|
+
export * from './goal.js';
|
|
16
|
+
export * from './exploration.js';
|
|
17
|
+
export * from './rlm.js';
|
|
18
|
+
export * from './memory.js';
|
|
19
|
+
export * from './skill-compiler.js';
|
|
20
|
+
export * from './continual.js';
|
|
21
|
+
export * from './evolution2.js';
|
|
22
|
+
export * from './multi-agent.js';
|
|
23
|
+
export * from './benchmark.js';
|
|
24
|
+
export * from './status.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/cognitive - the Cognitive OS core layer
|
|
3
|
+
*
|
|
4
|
+
* Blueprint: HMH Cognitive OS (2026-09). Kernel stays the source of truth;
|
|
5
|
+
* this layer owns cognitive STRATEGY: environment protocol, world model,
|
|
6
|
+
* goals, exploration, RLM, five-layer memory, skill compilation, continual
|
|
7
|
+
* learning control plane, evolution-2.0 governance, multi-agent topology,
|
|
8
|
+
* GeneralBench and the transfer lab. Nothing here touches approval/sandbox
|
|
9
|
+
* internals — governance composes them, never bypasses them.
|
|
10
|
+
*/
|
|
11
|
+
export * from "./protocol.js";
|
|
12
|
+
export * from "./registry.js";
|
|
13
|
+
export * from "./trajectory.js";
|
|
14
|
+
export * from "./world-model.js";
|
|
15
|
+
export * from "./goal.js";
|
|
16
|
+
export * from "./exploration.js";
|
|
17
|
+
export * from "./rlm.js";
|
|
18
|
+
export * from "./memory.js";
|
|
19
|
+
export * from "./skill-compiler.js";
|
|
20
|
+
export * from "./continual.js";
|
|
21
|
+
export * from "./evolution2.js";
|
|
22
|
+
export * from "./multi-agent.js";
|
|
23
|
+
export * from "./benchmark.js";
|
|
24
|
+
export * from "./status.js";
|
package/dist/memory.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export type MemoryLayer = 'working' | 'episodic' | 'semantic' | 'procedural' | 'world';
|
|
2
|
+
export interface MemoryEntry {
|
|
3
|
+
id: string;
|
|
4
|
+
layer: MemoryLayer;
|
|
5
|
+
/** the claim / rule / ref itself */
|
|
6
|
+
content: string;
|
|
7
|
+
/** structured payload (skill ref, trajectory ref, belief snapshot…) */
|
|
8
|
+
payload?: unknown;
|
|
9
|
+
source: string;
|
|
10
|
+
provenance: string;
|
|
11
|
+
confidence: number;
|
|
12
|
+
timestamp: string;
|
|
13
|
+
environment: string;
|
|
14
|
+
session: string;
|
|
15
|
+
/** set when a newer entry superseded this one (append-only evolution) */
|
|
16
|
+
supersededBy?: string;
|
|
17
|
+
tags?: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface ContradictionReport {
|
|
20
|
+
key: string;
|
|
21
|
+
entries: Array<{
|
|
22
|
+
id: string;
|
|
23
|
+
content: string;
|
|
24
|
+
confidence: number;
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
export declare class CognitiveMemory {
|
|
28
|
+
private home;
|
|
29
|
+
private working;
|
|
30
|
+
private longTerm;
|
|
31
|
+
constructor(home: string);
|
|
32
|
+
private file;
|
|
33
|
+
setWorking(key: string, content: string, session: string): void;
|
|
34
|
+
getWorking(key: string): string | undefined;
|
|
35
|
+
clearWorking(): void;
|
|
36
|
+
write(entry: Omit<MemoryEntry, 'id' | 'timestamp'> & {
|
|
37
|
+
id?: string;
|
|
38
|
+
timestamp?: string;
|
|
39
|
+
}): Promise<MemoryEntry>;
|
|
40
|
+
/** MEM-006 hybrid retrieval: tag/keyword match + recency + confidence. */
|
|
41
|
+
retrieve(query: {
|
|
42
|
+
layer?: MemoryLayer;
|
|
43
|
+
tags?: string[];
|
|
44
|
+
text?: string;
|
|
45
|
+
environment?: string;
|
|
46
|
+
limit?: number;
|
|
47
|
+
}): MemoryEntry[];
|
|
48
|
+
/** MEM-008. Same subject, divergent claims. */
|
|
49
|
+
detectContradictions(): ContradictionReport[];
|
|
50
|
+
/** MEM-009. Merge duplicates, decay stale entries via supersededBy —
|
|
51
|
+
* originals stay in the file (append-only, blueprint §10). */
|
|
52
|
+
consolidate(opts?: {
|
|
53
|
+
staleDays?: number;
|
|
54
|
+
}): Promise<{
|
|
55
|
+
merged: number;
|
|
56
|
+
decayed: number;
|
|
57
|
+
}>;
|
|
58
|
+
load(): Promise<number>;
|
|
59
|
+
stats(): Record<MemoryLayer | 'total', number>;
|
|
60
|
+
private persist;
|
|
61
|
+
}
|
|
62
|
+
/** MEM-007 provenance validation: long-term entries without a real source
|
|
63
|
+
* are rejected at write time. */
|
|
64
|
+
export declare function validateEntry(e: MemoryEntry): string[];
|