humemory 0.2.7 → 0.2.8
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/AGENTS.md +8 -4
- package/CHANGELOG.md +6 -0
- package/README.md +22 -10
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +2 -0
- package/dist/agent/maintenance-queue.js +36 -61
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +45 -10
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +96 -4
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +5 -0
- package/dist/core/paths.js +27 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/package.json +4 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +546 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1175 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +78 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +28 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import type { Memory, DecayLevel } from './types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Decay configuration.
|
|
5
|
+
*/
|
|
6
|
+
export const DECAY_CONFIG = {
|
|
7
|
+
// Base time for each level, in hours
|
|
8
|
+
levelThresholds: [0, 24, 168, 720, 2160], // 0h, 1j, 1sem, 1mois, 3mois
|
|
9
|
+
|
|
10
|
+
// How much each recall slows decay
|
|
11
|
+
recallBonus: 0.3, // every recall adds 30% more time
|
|
12
|
+
|
|
13
|
+
// Salience threshold above which decay slows down
|
|
14
|
+
saillanceThreshold: 70,
|
|
15
|
+
|
|
16
|
+
// Phase 6.0.1 — verified traces age more slowly
|
|
17
|
+
verifiedMultiplier: 1.5,
|
|
18
|
+
|
|
19
|
+
// Phase 6.0.1 / Claude R3-B8 — cap on the PRODUCT of all slowdown
|
|
20
|
+
// multipliers (recall × salience × verified). Without this, the unbounded
|
|
21
|
+
// `1 + recallCount * recallBonus` term makes verified+salient+recalled
|
|
22
|
+
// traces effectively photographic — which is not forgetting.
|
|
23
|
+
maxTotalSlowdown: 2.5,
|
|
24
|
+
|
|
25
|
+
// Phase 6.0.2 — contradiction collapse (Kimi B9, accepted by Claude R3):
|
|
26
|
+
// first refutation divides saillance by `contradictionDivisor`, further ones
|
|
27
|
+
// by `refuteDivisor` (cap `refuteCap` refutations), never below the floor.
|
|
28
|
+
contradictionDivisor: 4,
|
|
29
|
+
refuteDivisor: 2,
|
|
30
|
+
refuteCap: 3,
|
|
31
|
+
contradictionFloor: 5,
|
|
32
|
+
|
|
33
|
+
// Decay cycle: how often the sweep runs, in hours
|
|
34
|
+
decayCycleHours: 24,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Current decay level of a trace.
|
|
39
|
+
*/
|
|
40
|
+
export function calculateDecayLevel(memory: Memory, now: Date = new Date()): DecayLevel {
|
|
41
|
+
if (memory.photographic) {
|
|
42
|
+
return 0; // Photographic mode — no decay
|
|
43
|
+
}
|
|
44
|
+
if (memory.currentLevel === 4 || memory.mergedIntoId) {
|
|
45
|
+
return 4; // already lost or merged
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const hoursSinceCreation = (now.getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60);
|
|
49
|
+
const hoursSinceRecall = memory.lastRecalled
|
|
50
|
+
? (now.getTime() - memory.lastRecalled.getTime()) / (1000 * 60 * 60)
|
|
51
|
+
: Infinity;
|
|
52
|
+
|
|
53
|
+
// Use whichever of the two is more recent
|
|
54
|
+
const effectiveAge = Math.min(hoursSinceCreation, hoursSinceRecall);
|
|
55
|
+
|
|
56
|
+
// Appliquer le bonus de rappel
|
|
57
|
+
const recallMultiplier = 1 + (memory.recallCount * DECAY_CONFIG.recallBonus);
|
|
58
|
+
|
|
59
|
+
// Appliquer le bonus de saillance
|
|
60
|
+
const saillanceMultiplier = memory.saillance >= DECAY_CONFIG.saillanceThreshold ? 1.5 : 1;
|
|
61
|
+
|
|
62
|
+
// Phase 6.0.1 — le bonus de vérification
|
|
63
|
+
const verifiedMultiplier = memory.verified ? DECAY_CONFIG.verifiedMultiplier : 1;
|
|
64
|
+
|
|
65
|
+
// Cap on the PRODUCT (R3/B8): the unbounded recall term counts toward it.
|
|
66
|
+
const totalSlowdown = Math.min(
|
|
67
|
+
recallMultiplier * saillanceMultiplier * verifiedMultiplier,
|
|
68
|
+
DECAY_CONFIG.maxTotalSlowdown
|
|
69
|
+
);
|
|
70
|
+
const finalAge = effectiveAge / totalSlowdown;
|
|
71
|
+
|
|
72
|
+
// Determine the level
|
|
73
|
+
for (let i = 3; i >= 0; i--) {
|
|
74
|
+
if (finalAge >= DECAY_CONFIG.levelThresholds[i]) {
|
|
75
|
+
return i as DecayLevel;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Salience score of a trace.
|
|
84
|
+
* Based on recent recalls, connections and emotional charge.
|
|
85
|
+
*/
|
|
86
|
+
export function calculateSaillance(memory: Memory, now: Date = new Date()): number {
|
|
87
|
+
let score = 50; // baseline
|
|
88
|
+
|
|
89
|
+
// Bonus for recent recalls (within 7 days)
|
|
90
|
+
if (memory.lastRecalled) {
|
|
91
|
+
const daysSinceRecall = (now.getTime() - memory.lastRecalled.getTime()) / (1000 * 60 * 60 * 24);
|
|
92
|
+
if (daysSinceRecall < 7) {
|
|
93
|
+
score += 20;
|
|
94
|
+
} else if (daysSinceRecall < 30) {
|
|
95
|
+
score += 10;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Bonus for how often it was recalled
|
|
100
|
+
score += Math.min(memory.recallCount * 5, 20);
|
|
101
|
+
|
|
102
|
+
// Bonus for keywords: more tags means better connected
|
|
103
|
+
score += Math.min(memory.keywords.length * 3, 15);
|
|
104
|
+
|
|
105
|
+
// Crude emotional-charge detection. The list stays bilingual on purpose: traces
|
|
106
|
+
// are written in whatever language the developer works in, and dropping the
|
|
107
|
+
// French markers would silently weaken salience on French content.
|
|
108
|
+
const emotionalWords = [
|
|
109
|
+
'important', 'urgent', 'critical', 'attention', 'wow', 'awesome', 'damn', 'problem', 'error', 'broken',
|
|
110
|
+
'génial', 'merde', 'problème', 'erreur', 'super',
|
|
111
|
+
];
|
|
112
|
+
const contentLower = memory.content.toLowerCase();
|
|
113
|
+
const hasEmotion = emotionalWords.some(word => contentLower.includes(word));
|
|
114
|
+
if (hasEmotion) {
|
|
115
|
+
score += 10;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return Math.min(score, 100);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Initial decay rate.
|
|
123
|
+
* 0.0 = very slow, 1.0 = very fast.
|
|
124
|
+
*/
|
|
125
|
+
export function calculateDecayRate(content: string, keywords: string[]): number {
|
|
126
|
+
// Base rate
|
|
127
|
+
let rate = 0.5;
|
|
128
|
+
|
|
129
|
+
// Long content decays more slowly: there is more detail worth keeping
|
|
130
|
+
if (content.length > 500) {
|
|
131
|
+
rate -= 0.1;
|
|
132
|
+
} else if (content.length < 100) {
|
|
133
|
+
rate += 0.1;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Many keywords means better connected, so slower decay
|
|
137
|
+
if (keywords.length > 5) {
|
|
138
|
+
rate -= 0.1;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return Math.max(0.1, Math.min(1.0, rate));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface DecayCurvePoint {
|
|
145
|
+
time: Date;
|
|
146
|
+
level: DecayLevel;
|
|
147
|
+
saillance: number;
|
|
148
|
+
hoursElapsed: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Projects a trace's forgetting curve over `daysAhead` days, one point every six
|
|
153
|
+
* hours.
|
|
154
|
+
*
|
|
155
|
+
* It lives here, next to the rules it samples, rather than in the visualisation
|
|
156
|
+
* code: a curve drawn from a diverging copy of the algorithm would tell a story
|
|
157
|
+
* the system does not actually live.
|
|
158
|
+
*/
|
|
159
|
+
export function projectDecayCurve(memory: Memory, daysAhead = 90): DecayCurvePoint[] {
|
|
160
|
+
const points: DecayCurvePoint[] = [];
|
|
161
|
+
const createdAt = new Date(memory.createdAt).getTime();
|
|
162
|
+
const totalMs = daysAhead * 24 * 3600_000;
|
|
163
|
+
const stepMs = 6 * 3600_000;
|
|
164
|
+
|
|
165
|
+
for (let t = 0; t <= totalMs; t += stepMs) {
|
|
166
|
+
const at = new Date(createdAt + t);
|
|
167
|
+
points.push({
|
|
168
|
+
time: at,
|
|
169
|
+
level: calculateDecayLevel(memory, at),
|
|
170
|
+
saillance: calculateSaillance(memory, at),
|
|
171
|
+
hoursElapsed: t / 3600_000,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return points;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Updates every trace in a collection.
|
|
180
|
+
*/
|
|
181
|
+
export function updateAllDecay(memories: Memory[], now: Date = new Date()): Memory[] {
|
|
182
|
+
return memories.map(memory => {
|
|
183
|
+
const newLevel = calculateDecayLevel(memory, now);
|
|
184
|
+
const newSaillance = calculateSaillance(memory, now);
|
|
185
|
+
|
|
186
|
+
// Mark as lost/merged once level 4 is reached
|
|
187
|
+
if (newLevel === 4 && memory.currentLevel !== 4) {
|
|
188
|
+
// TODO: merging logic still to implement
|
|
189
|
+
console.log(`Memory ${memory.id} marked as decayed (level 4)`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
...memory,
|
|
194
|
+
currentLevel: newLevel,
|
|
195
|
+
saillance: newSaillance,
|
|
196
|
+
};
|
|
197
|
+
});
|
|
198
|
+
}
|
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dreaming — Phase 6.1.
|
|
3
|
+
*
|
|
4
|
+
* A background consolidation pass that detects recurring patterns across
|
|
5
|
+
* sessions *and agents*, then proposes — never silently applies. The human
|
|
6
|
+
* gate is `pnpm cli dream review` / `approve` / `reject`.
|
|
7
|
+
*
|
|
8
|
+
* Invariants (asserted by tests):
|
|
9
|
+
* - The dreamer scores clusters on `base(source)` ONLY — verification informs
|
|
10
|
+
* recall ordering, recurrence informs clustering, they never feed each
|
|
11
|
+
* other (Claude R1, self-confirming loop).
|
|
12
|
+
* - The job is idempotent: `payload_hash` dedups proposals, and a rejected
|
|
13
|
+
* pattern is not resurrected on the next run (re-filing the same hash is an
|
|
14
|
+
* INSERT OR IGNORE no-op while the rejected row exists).
|
|
15
|
+
* - No network, no embeddings: the `Clusterer` is an interface so Phase 7 can
|
|
16
|
+
* swap in vectors without touching the pipeline (owner ruling).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { createHash } from 'crypto';
|
|
20
|
+
import type {
|
|
21
|
+
Memory, Intention, MemoryStore, IntentionStore, ScriptStore,
|
|
22
|
+
DreamKind, DreamProposal,
|
|
23
|
+
} from './types.js';
|
|
24
|
+
import { baseTrust } from './trust.js';
|
|
25
|
+
import { systemClock, type Clock } from './clock.js';
|
|
26
|
+
|
|
27
|
+
export const DREAM_CONFIG = {
|
|
28
|
+
/** Traces younger than this are considered. */
|
|
29
|
+
windowDays: 30,
|
|
30
|
+
/** A cluster qualifies at ≥ K traces from ≥ 2 sessions, or ≥ 2 agents. */
|
|
31
|
+
minClusterSize: 3,
|
|
32
|
+
minDistinctSessions: 2,
|
|
33
|
+
minDistinctAgents: 2,
|
|
34
|
+
/** Corroboration also requires distinct directories — agreement ≠ independence. */
|
|
35
|
+
minDistinctDirectories: 2,
|
|
36
|
+
/** Jaccard similarity threshold for the keyword clusterer. */
|
|
37
|
+
similarityThreshold: 0.34,
|
|
38
|
+
/**
|
|
39
|
+
* FALLBACK cluster threshold, used only for embedders without a calibrated
|
|
40
|
+
* per-model value (HashEmbedder in tests). Production models carry their
|
|
41
|
+
* own in CLUSTER_THRESHOLDS (embeddings.ts, 7.5 rounds 1–4): e5-small
|
|
42
|
+
* 0.855 / e5-base 0.825 / bge-m3 0.740 (best F1 0.89).
|
|
43
|
+
*
|
|
44
|
+
* vectorCorroborateThreshold 0.99 = SENTINEL, auto-corroboration DISABLED.
|
|
45
|
+
* Four calibration rounds (e5-small, e5-base ×2, bge-m3 — 52 labelled pairs
|
|
46
|
+
* incl. same-domain hard negatives) all failed to find a P=1.0 gate
|
|
47
|
+
* (best-case false max 0.908 > true min 0.691 with bge-m3). Re-enabling
|
|
48
|
+
* requires a stronger embedder or an LLM pairwise verifier, not more fixture.
|
|
49
|
+
*/
|
|
50
|
+
vectorClusterThreshold: 0.825,
|
|
51
|
+
vectorCorroborateThreshold: 0.99,
|
|
52
|
+
/** Proposal lifetime (owner-approved 14d expiry). */
|
|
53
|
+
proposalTtlDays: 14,
|
|
54
|
+
/** LLM drafting cap per run; skipped entirely without a client. */
|
|
55
|
+
maxDraftsPerRun: 10,
|
|
56
|
+
/** Loops open longer than this are stale-loop candidates. */
|
|
57
|
+
staleLoopDays: 30,
|
|
58
|
+
/** Max traces read per run. */
|
|
59
|
+
collectLimit: 500,
|
|
60
|
+
/**
|
|
61
|
+
* Phase 8.5 — script mining. A "correction" is a trace that WON an active
|
|
62
|
+
* contradiction: 6.0.2 already establishes that mechanism as evidence a
|
|
63
|
+
* prior trace was wrong, so reusing it avoids inventing a new "correction"
|
|
64
|
+
* tag with no producer anywhere in the codebase (Claude's Phase 8
|
|
65
|
+
* annotation flagged the alternative — tagging memoryType — as dead weight
|
|
66
|
+
* without one).
|
|
67
|
+
*/
|
|
68
|
+
scriptCandidateMinCluster: 2,
|
|
69
|
+
/** Draft steps are raw trace content, capped — no LLM drafting for this kind (out of scope, PHASE8_PLAN §Out of scope). */
|
|
70
|
+
scriptCandidateMaxSteps: 6,
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Phase 7 seam: swap this implementation for a vector clusterer. */
|
|
74
|
+
export interface Clusterer {
|
|
75
|
+
/** Async since Phase 7.1 — vector clusterers embed before grouping. */
|
|
76
|
+
cluster(memories: Memory[]): Promise<Memory[][]> | Memory[][];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Tokenize the strongest available retrieval text of a trace. */
|
|
80
|
+
function tokens(m: Memory): Set<string> {
|
|
81
|
+
const text = m.level3Keywords || m.keywords.join(' ') || m.level2Essential || m.content;
|
|
82
|
+
return new Set(
|
|
83
|
+
text
|
|
84
|
+
.toLowerCase()
|
|
85
|
+
.split(/[^a-z0-9àâäéèêëîïôöùûüç_-]+/i)
|
|
86
|
+
.filter((t) => t.length > 2)
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function jaccard(a: Set<string>, b: Set<string>): number {
|
|
91
|
+
if (!a.size || !b.size) return 0;
|
|
92
|
+
let inter = 0;
|
|
93
|
+
for (const t of a) if (b.has(t)) inter++;
|
|
94
|
+
return inter / (a.size + b.size - inter);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Keyword clusterer: union-find over pairwise Jaccard similarity. Deterministic
|
|
99
|
+
* (stable iteration order, ties broken by insertion order), local, dependency-free.
|
|
100
|
+
*/
|
|
101
|
+
export class KeywordClusterer implements Clusterer {
|
|
102
|
+
constructor(private threshold: number = DREAM_CONFIG.similarityThreshold) {}
|
|
103
|
+
|
|
104
|
+
cluster(memories: Memory[]): Memory[][] {
|
|
105
|
+
const parent = memories.map((_, i) => i);
|
|
106
|
+
const find = (i: number): number => {
|
|
107
|
+
while (parent[i] !== i) {
|
|
108
|
+
parent[i] = parent[parent[i]];
|
|
109
|
+
i = parent[i];
|
|
110
|
+
}
|
|
111
|
+
return i;
|
|
112
|
+
};
|
|
113
|
+
const tokenSets = memories.map(tokens);
|
|
114
|
+
for (let i = 0; i < memories.length; i++) {
|
|
115
|
+
for (let j = i + 1; j < memories.length; j++) {
|
|
116
|
+
if (jaccard(tokenSets[i], tokenSets[j]) >= this.threshold) {
|
|
117
|
+
const ri = find(i);
|
|
118
|
+
const rj = find(j);
|
|
119
|
+
if (ri !== rj) parent[rj] = ri;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const groups = new Map<number, Memory[]>();
|
|
124
|
+
memories.forEach((m, i) => {
|
|
125
|
+
const root = find(i);
|
|
126
|
+
if (!groups.has(root)) groups.set(root, []);
|
|
127
|
+
groups.get(root)!.push(m);
|
|
128
|
+
});
|
|
129
|
+
return [...groups.values()].filter((g) => g.length > 1);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface DreamReport {
|
|
134
|
+
considered: number;
|
|
135
|
+
clusters: number;
|
|
136
|
+
filed: number;
|
|
137
|
+
expired: number;
|
|
138
|
+
staleLoopCandidates: number;
|
|
139
|
+
draftsWritten: number;
|
|
140
|
+
/** Traces that earned `corroborated` verification during this run (6.0.1). */
|
|
141
|
+
corroborated: number;
|
|
142
|
+
/** `script_candidate` proposals filed this run (8.5). */
|
|
143
|
+
scriptCandidates: number;
|
|
144
|
+
proposals: DreamProposal[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function hashOf(kind: DreamKind, ids: string[]): string {
|
|
148
|
+
return createHash('sha1').update([kind, ...ids.slice().sort()].join('|')).digest('hex');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Confidence: cluster size saturates at 8, weighted by mean baseTrust. */
|
|
152
|
+
function confidenceOf(cluster: Memory[]): number {
|
|
153
|
+
const sizeScore = Math.min(cluster.length, 8) / 8;
|
|
154
|
+
const trustScoreAvg = cluster.reduce((s, m) => s + baseTrust(m), 0) / cluster.length / 100;
|
|
155
|
+
return Math.round(sizeScore * (0.4 + 0.6 * trustScoreAvg) * 100) / 100;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function qualifies(cluster: Memory[]): boolean {
|
|
159
|
+
const sessions = new Set(cluster.map((m) => m.sessionId));
|
|
160
|
+
const agents = new Set(cluster.map((m) => m.agent).filter(Boolean));
|
|
161
|
+
return (
|
|
162
|
+
(cluster.length >= DREAM_CONFIG.minClusterSize && sessions.size >= DREAM_CONFIG.minDistinctSessions) ||
|
|
163
|
+
agents.size >= DREAM_CONFIG.minDistinctAgents
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Does this cluster constitute *corroboration* — the first of the three
|
|
169
|
+
* evidence paths of 6.0.1, and the only one the dreamer can observe?
|
|
170
|
+
*
|
|
171
|
+
* Agreement is not independence (Claude R1, defect 1): three agents that read
|
|
172
|
+
* the same stale README are one source wearing three names. So distinct agent
|
|
173
|
+
* labels are necessary but not sufficient — the traces must also come from
|
|
174
|
+
* distinct sessions AND distinct directories, which is the cheapest available
|
|
175
|
+
* proxy for "these agents did not look at the same thing at the same time".
|
|
176
|
+
*
|
|
177
|
+
* Corroboration is deliberately the weakest bonus in TRUST_CONFIG (+8). It
|
|
178
|
+
* cannot feed the dreamer back: clustering scores on `baseTrust` only, so a
|
|
179
|
+
* cluster can never raise the trust that makes it qualify (R1, defect 2).
|
|
180
|
+
*/
|
|
181
|
+
function corroborates(cluster: Memory[]): boolean {
|
|
182
|
+
const agents = new Set(cluster.map((m) => m.agent).filter(Boolean));
|
|
183
|
+
if (agents.size < DREAM_CONFIG.minDistinctAgents) return false;
|
|
184
|
+
const sessions = new Set(cluster.map((m) => m.sessionId));
|
|
185
|
+
if (sessions.size < DREAM_CONFIG.minDistinctSessions) return false;
|
|
186
|
+
const directories = new Set(cluster.map((m) => m.directory));
|
|
187
|
+
return directories.size >= DREAM_CONFIG.minDistinctDirectories;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export interface DreamOptions {
|
|
191
|
+
store: MemoryStore & IntentionStore;
|
|
192
|
+
clusterer?: Clusterer;
|
|
193
|
+
clock?: Clock;
|
|
194
|
+
/**
|
|
195
|
+
* Optional LLM drafting of consolidated wording. Capped and skipped when
|
|
196
|
+
* absent — the job then files proposals with the raw cluster, never fails.
|
|
197
|
+
*/
|
|
198
|
+
draft?: (cluster: Memory[]) => Promise<string>;
|
|
199
|
+
/** Human identity for resolvedBy — `git config user.email`, fallback 'cli'. */
|
|
200
|
+
now?: never; // use clock
|
|
201
|
+
/** Override the 30-day collection window (validation / deep retrospectives). */
|
|
202
|
+
windowDays?: number;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function runDreamer(options: DreamOptions): Promise<DreamReport> {
|
|
206
|
+
const { store } = options;
|
|
207
|
+
const clock = options.clock ?? systemClock;
|
|
208
|
+
const clusterer = options.clusterer ?? new KeywordClusterer();
|
|
209
|
+
const now = clock.now();
|
|
210
|
+
const windowStart =
|
|
211
|
+
now.getTime() - (options.windowDays ?? DREAM_CONFIG.windowDays) * 24 * 3600_000;
|
|
212
|
+
|
|
213
|
+
// 0. Housekeeping: pending proposals past their TTL expire first.
|
|
214
|
+
const expired = (await store.expireDreamProposals?.()) ?? 0;
|
|
215
|
+
|
|
216
|
+
// 1. Collect — exclude contradicted losers and level-4/merged rows.
|
|
217
|
+
const contradicted = new Set(
|
|
218
|
+
((await store.listContradictions?.({ status: 'active' })) ?? []).map((ct) => ct.loserId)
|
|
219
|
+
);
|
|
220
|
+
const traces = (await store.list({ limit: DREAM_CONFIG.collectLimit })).filter(
|
|
221
|
+
(m) =>
|
|
222
|
+
m.createdAt.getTime() >= windowStart &&
|
|
223
|
+
m.currentLevel < 4 &&
|
|
224
|
+
!m.mergedIntoId &&
|
|
225
|
+
!contradicted.has(m.id)
|
|
226
|
+
);
|
|
227
|
+
|
|
228
|
+
// 2. Cluster. ScoredClusterer (Phase 7.3) also yields each cluster's
|
|
229
|
+
// weakest link — needed for the two-threshold rule (A1).
|
|
230
|
+
const { hasScores } = await import('./vector-clusterer.js');
|
|
231
|
+
const scored = hasScores(clusterer) ? await clusterer.clusterWithScores(traces) : null;
|
|
232
|
+
const clusters: { members: Memory[]; minPairwiseSimilarity: number | null }[] = scored
|
|
233
|
+
? scored.map((c) => ({ members: c.members, minPairwiseSimilarity: c.minPairwiseSimilarity }))
|
|
234
|
+
: (await clusterer.cluster(traces)).map((members) => ({ members, minPairwiseSimilarity: null }));
|
|
235
|
+
|
|
236
|
+
// 3-4. Qualify, then propose (idempotent via payload_hash).
|
|
237
|
+
let filed = 0;
|
|
238
|
+
let drafts = 0;
|
|
239
|
+
const proposals: DreamProposal[] = [];
|
|
240
|
+
const expiresAt = new Date(now.getTime() + DREAM_CONFIG.proposalTtlDays * 24 * 3600_000);
|
|
241
|
+
|
|
242
|
+
let corroborated = 0;
|
|
243
|
+
|
|
244
|
+
for (const cluster of clusters) {
|
|
245
|
+
if (!qualifies(cluster.members)) continue;
|
|
246
|
+
|
|
247
|
+
// Corroboration is evidence, not a proposal: 6.0.1 lists it as an
|
|
248
|
+
// automatic verification path, so it applies without the human gate.
|
|
249
|
+
// It touches no content — only the `verified` flag and its reason.
|
|
250
|
+
//
|
|
251
|
+
// A1 (two thresholds): when the clusterer scores its clusters, the weakest
|
|
252
|
+
// link must also clear the STRICTER corroborate threshold — grouping
|
|
253
|
+
// tolerates noise because a human reviews proposals; verification does
|
|
254
|
+
// not, because nobody reviews it. Clusterers without scores (keyword)
|
|
255
|
+
// keep the metadata-only rule.
|
|
256
|
+
const similarityOk =
|
|
257
|
+
cluster.minPairwiseSimilarity === null ||
|
|
258
|
+
cluster.minPairwiseSimilarity >= DREAM_CONFIG.vectorCorroborateThreshold;
|
|
259
|
+
if (similarityOk && corroborates(cluster.members) && store.verify) {
|
|
260
|
+
for (const m of cluster.members) {
|
|
261
|
+
if (m.verified) continue; // never downgrade an existing, stronger reason
|
|
262
|
+
await store.verify(m.id, 'corroborated');
|
|
263
|
+
corroborated++;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
let drafted: string | undefined;
|
|
268
|
+
if (options.draft && drafts < DREAM_CONFIG.maxDraftsPerRun) {
|
|
269
|
+
drafted = await options.draft(cluster.members);
|
|
270
|
+
drafts++;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const ids = cluster.members.map((m) => m.id);
|
|
274
|
+
const payload = JSON.stringify({
|
|
275
|
+
clusterIds: ids,
|
|
276
|
+
agents: [...new Set(cluster.members.map((m) => m.agent).filter(Boolean))],
|
|
277
|
+
sessions: new Set(cluster.members.map((m) => m.sessionId)).size,
|
|
278
|
+
samples: cluster.members.slice(0, 3).map((m) => (m.level2Essential ?? m.content).slice(0, 140)),
|
|
279
|
+
drafted,
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
const ok = (await store.fileDreamProposal?.({
|
|
283
|
+
kind: 'promote_semantic',
|
|
284
|
+
payload,
|
|
285
|
+
payloadHash: hashOf('promote_semantic', ids),
|
|
286
|
+
confidence: confidenceOf(cluster.members),
|
|
287
|
+
expiresAt,
|
|
288
|
+
})) ?? false;
|
|
289
|
+
if (ok) filed++;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// 5. Stale loops (intentions read-only): open past staleLoopDays whose linked
|
|
293
|
+
// trace has faded to L3+ — propose closing them.
|
|
294
|
+
let staleLoopCandidates = 0;
|
|
295
|
+
const armed = await store.listIntentions({ status: ['armed', 'fired'], limit: 500 });
|
|
296
|
+
for (const intention of armed) {
|
|
297
|
+
const ageMs = now.getTime() - intention.createdAt.getTime();
|
|
298
|
+
if (ageMs < DREAM_CONFIG.staleLoopDays * 24 * 3600_000) continue;
|
|
299
|
+
if (intention.relatedMemoryId) {
|
|
300
|
+
const linked = await store.getById(intention.relatedMemoryId);
|
|
301
|
+
if (linked && linked.currentLevel < 3) continue; // trace still alive → not stale
|
|
302
|
+
}
|
|
303
|
+
staleLoopCandidates++;
|
|
304
|
+
const ok = (await store.fileDreamProposal?.({
|
|
305
|
+
kind: 'close_stale_loop',
|
|
306
|
+
payload: JSON.stringify({ intentionId: intention.id, content: intention.content, ageDays: Math.floor(ageMs / 24 / 3600_000) }),
|
|
307
|
+
payloadHash: hashOf('close_stale_loop', [intention.id]),
|
|
308
|
+
confidence: 0.3,
|
|
309
|
+
expiresAt,
|
|
310
|
+
})) ?? false;
|
|
311
|
+
if (ok) filed++;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// 6. Script mining (8.5): a cluster of *corrections* — traces that WON an
|
|
315
|
+
// active contradiction — sharing a directory drafts a script. "11 of 15
|
|
316
|
+
// agents fail the same command, then fix it the same way" is a contradiction
|
|
317
|
+
// per winning trace; clustering the winners finds the repeated pattern.
|
|
318
|
+
let scriptCandidates = 0;
|
|
319
|
+
if (store.listContradictions) {
|
|
320
|
+
const activeContradictions = await store.listContradictions({ status: 'active' });
|
|
321
|
+
const inWindow = activeContradictions.filter((c) => c.createdAt.getTime() >= windowStart);
|
|
322
|
+
// A memory can win more than one contradiction; keep its earliest win —
|
|
323
|
+
// that is when it first established itself as the correction.
|
|
324
|
+
const wonAt = new Map<string, Date>();
|
|
325
|
+
for (const c of inWindow) {
|
|
326
|
+
const prior = wonAt.get(c.winnerId);
|
|
327
|
+
if (!prior || c.createdAt < prior) wonAt.set(c.winnerId, c.createdAt);
|
|
328
|
+
}
|
|
329
|
+
const winners = (
|
|
330
|
+
await Promise.all([...wonAt.keys()].map((id) => store.getById(id)))
|
|
331
|
+
).filter((m): m is Memory => m !== null && m.currentLevel < 4 && !m.mergedIntoId);
|
|
332
|
+
|
|
333
|
+
const byDirectory = new Map<string, Memory[]>();
|
|
334
|
+
for (const w of winners) {
|
|
335
|
+
const bucket = byDirectory.get(w.directory) ?? [];
|
|
336
|
+
bucket.push(w);
|
|
337
|
+
byDirectory.set(w.directory, bucket);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
for (const [directory, group] of byDirectory) {
|
|
341
|
+
if (group.length < DREAM_CONFIG.scriptCandidateMinCluster) continue;
|
|
342
|
+
// Cluster within the directory only — a script has one `directory`,
|
|
343
|
+
// mixing corrections from unrelated places would draft a drill nobody
|
|
344
|
+
// asked for. No verification is granted here (unlike step 4's
|
|
345
|
+
// corroboration): this path only ever produces a human-reviewed
|
|
346
|
+
// proposal, so the plain (unscored) grouping is enough.
|
|
347
|
+
const subclusters = await clusterer.cluster(group);
|
|
348
|
+
for (const cluster of subclusters) {
|
|
349
|
+
if (cluster.length < DREAM_CONFIG.scriptCandidateMinCluster) continue;
|
|
350
|
+
const ordered = [...cluster].sort(
|
|
351
|
+
(a, b) => (wonAt.get(a.id)!.getTime() - wonAt.get(b.id)!.getTime())
|
|
352
|
+
);
|
|
353
|
+
const steps = ordered
|
|
354
|
+
.slice(0, DREAM_CONFIG.scriptCandidateMaxSteps)
|
|
355
|
+
.map((m) => (m.level2Essential ?? m.content).slice(0, 200));
|
|
356
|
+
const keywordCounts = new Map<string, number>();
|
|
357
|
+
for (const m of cluster) for (const k of m.keywords) keywordCounts.set(k, (keywordCounts.get(k) ?? 0) + 1);
|
|
358
|
+
const topKeyword = [...keywordCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
|
|
359
|
+
const ids = cluster.map((m) => m.id);
|
|
360
|
+
const name = topKeyword ? `fix-${topKeyword}` : `correction-${hashOf('script_candidate', ids).slice(0, 6)}`;
|
|
361
|
+
|
|
362
|
+
const ok = (await store.fileDreamProposal?.({
|
|
363
|
+
kind: 'script_candidate',
|
|
364
|
+
payload: JSON.stringify({
|
|
365
|
+
directory,
|
|
366
|
+
name,
|
|
367
|
+
description: `Recurring correction across ${cluster.length} traces — steps drafted from what fixed it each time.`,
|
|
368
|
+
steps,
|
|
369
|
+
sourceMemoryIds: ids,
|
|
370
|
+
truncatedSteps: cluster.length > DREAM_CONFIG.scriptCandidateMaxSteps,
|
|
371
|
+
}),
|
|
372
|
+
payloadHash: hashOf('script_candidate', ids),
|
|
373
|
+
confidence: confidenceOf(cluster),
|
|
374
|
+
expiresAt,
|
|
375
|
+
})) ?? false;
|
|
376
|
+
if (ok) { filed++; scriptCandidates++; }
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const pending = (await store.listDreamProposals?.({ status: 'pending' })) ?? [];
|
|
382
|
+
proposals.push(...pending);
|
|
383
|
+
|
|
384
|
+
return {
|
|
385
|
+
considered: traces.length,
|
|
386
|
+
clusters: clusters.length,
|
|
387
|
+
filed,
|
|
388
|
+
expired,
|
|
389
|
+
staleLoopCandidates,
|
|
390
|
+
draftsWritten: drafts,
|
|
391
|
+
corroborated,
|
|
392
|
+
scriptCandidates,
|
|
393
|
+
proposals,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Applies an approved proposal. Returns a human-readable summary of the effect.
|
|
399
|
+
* `update_agents_md` never writes the file — it returns the suggested line for
|
|
400
|
+
* the human to paste (level-1 memory stays human-owned, permanently).
|
|
401
|
+
*/
|
|
402
|
+
export async function applyDreamProposal(
|
|
403
|
+
store: MemoryStore & IntentionStore & ScriptStore,
|
|
404
|
+
proposal: DreamProposal,
|
|
405
|
+
options?: { clock?: Clock }
|
|
406
|
+
): Promise<string> {
|
|
407
|
+
const payload = JSON.parse(proposal.payload);
|
|
408
|
+
|
|
409
|
+
switch (proposal.kind) {
|
|
410
|
+
case 'promote_semantic': {
|
|
411
|
+
const ids: string[] = payload.clusterIds;
|
|
412
|
+
const members = (await Promise.all(ids.map((id) => store.getById(id)))).filter(Boolean) as Memory[];
|
|
413
|
+
if (!members.length) return 'cluster vanished — nothing to promote';
|
|
414
|
+
const content = payload.drafted ??
|
|
415
|
+
`Recurring pattern across ${members.length} traces (${payload.sessions} sessions, agents: ${payload.agents.join(', ') || 'n/a'}):\n` +
|
|
416
|
+
members.map((m) => `- ${(m.level2Essential ?? m.content).slice(0, 200)}`).join('\n');
|
|
417
|
+
const created = await store.add({
|
|
418
|
+
content,
|
|
419
|
+
directory: members[0].directory,
|
|
420
|
+
day: (options?.clock ?? systemClock).now().toISOString().split('T')[0],
|
|
421
|
+
keywords: [...new Set(members.flatMap((m) => m.keywords))].slice(0, 8),
|
|
422
|
+
sessionId: 'dream',
|
|
423
|
+
memoryType: 'semantic',
|
|
424
|
+
source: 'dream_proposal',
|
|
425
|
+
verified: true,
|
|
426
|
+
// NOT 'human': `human` is the only reason that renders a trace *bare*,
|
|
427
|
+
// outside the untrusted markers, in the next session's context block
|
|
428
|
+
// (session-context.ts). This content is LLM-drafted or concatenated
|
|
429
|
+
// from agent traces — the human approved a proposal showing three
|
|
430
|
+
// 140-char samples, they did not read this text. `corroborated` is
|
|
431
|
+
// what the evidence actually supports, and it keeps the trace wrapped.
|
|
432
|
+
verificationReason: 'corroborated',
|
|
433
|
+
});
|
|
434
|
+
return `promoted to semantic memory ${created.id.slice(0, 8)}…`;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
case 'merge_cluster': {
|
|
438
|
+
const ids: string[] = payload.clusterIds;
|
|
439
|
+
if (ids.length < 2) return 'cluster too small to merge';
|
|
440
|
+
const [target, ...sources] = ids;
|
|
441
|
+
for (const src of sources) await store.merge(src, target, {});
|
|
442
|
+
return `merged ${sources.length} trace(s) into ${target.slice(0, 8)}…`;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
case 'contradiction': {
|
|
446
|
+
const r = await store.contradict!(payload.winnerId, payload.loserId, {
|
|
447
|
+
reason: payload.reason,
|
|
448
|
+
createdBy: 'human', // approved by the human gate
|
|
449
|
+
});
|
|
450
|
+
return r.contradiction
|
|
451
|
+
? `contradiction applied — loser at ${r.loser.saillance}/100`
|
|
452
|
+
: 'contradiction filed again as proposal';
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
case 'close_stale_loop': {
|
|
456
|
+
await store.updateIntentionStatus(payload.intentionId, 'closed', {});
|
|
457
|
+
return `stale loop ${payload.intentionId.slice(0, 8)}… closed`;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
case 'update_agents_md': {
|
|
461
|
+
return `suggested AGENTS.md addition (paste it yourself):\n${payload.drafted ?? payload.suggestion ?? ''}`;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
case 'script_candidate': {
|
|
465
|
+
// Lands as 'draft', never 'active' (8.5): the human reviewing the
|
|
466
|
+
// proposal saw a description and a confidence score, not necessarily
|
|
467
|
+
// every drafted step — same reasoning as promote_semantic not landing
|
|
468
|
+
// as `verificationReason: 'human'` (R1 discussion, Claude's reply).
|
|
469
|
+
// A human still runs `script activate` after reading the actual steps.
|
|
470
|
+
const script = await store.addScript({
|
|
471
|
+
name: payload.name,
|
|
472
|
+
description: payload.description,
|
|
473
|
+
steps: payload.steps,
|
|
474
|
+
directory: payload.directory,
|
|
475
|
+
source: 'dream_proposal',
|
|
476
|
+
status: 'draft',
|
|
477
|
+
pinned: false,
|
|
478
|
+
});
|
|
479
|
+
return `drafted script "${script.name}" (${script.id.slice(0, 8)}…) — ` +
|
|
480
|
+
`\`pnpm cli script activate ${script.id.slice(0, 8)}\` after reviewing the steps`;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
case 'script_archived': {
|
|
484
|
+
// Notice, not a request (PHASE8_PLAN.md §8.4): the archival already
|
|
485
|
+
// happened — in the disuse sweep, or immediately on a contradiction
|
|
486
|
+
// (`reason` distinguishes the two, both filed by the store). Nothing
|
|
487
|
+
// left to apply — resolving the proposal only acknowledges it.
|
|
488
|
+
return payload.reason === 'contradiction'
|
|
489
|
+
? `acknowledged: "${payload.name}" archived — contradicted by "${payload.winnerContent}"`
|
|
490
|
+
: `acknowledged: "${payload.name}" archived by disuse ` +
|
|
491
|
+
`(saillance ${payload.storedSaillance} → effective ${payload.effectiveSaillance})`;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|