humemory 0.2.1
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/.githooks/post-commit +22 -0
- package/AGENTS.md +328 -0
- package/CHANGELOG.md +198 -0
- package/LICENSE +21 -0
- package/README.md +488 -0
- package/bin/humemory.js +19 -0
- package/dist/agent/claude-hook.d.ts +15 -0
- package/dist/agent/claude-hook.js +38 -0
- package/dist/agent/commit-closer.d.ts +60 -0
- package/dist/agent/commit-closer.js +125 -0
- package/dist/agent/learning-extractor.d.ts +10 -0
- package/dist/agent/learning-extractor.js +75 -0
- package/dist/agent/session-context.d.ts +63 -0
- package/dist/agent/session-context.js +216 -0
- package/dist/agent/session-parser.d.ts +12 -0
- package/dist/agent/session-parser.js +85 -0
- package/dist/api/dream-routes.d.ts +7 -0
- package/dist/api/dream-routes.js +40 -0
- package/dist/api/intentions-routes.d.ts +23 -0
- package/dist/api/intentions-routes.js +252 -0
- package/dist/api/memory-routes.d.ts +10 -0
- package/dist/api/memory-routes.js +277 -0
- package/dist/api/scripts-routes.d.ts +13 -0
- package/dist/api/scripts-routes.js +129 -0
- package/dist/api/server.d.ts +33 -0
- package/dist/api/server.js +157 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +798 -0
- package/dist/core/clock.d.ts +38 -0
- package/dist/core/clock.js +52 -0
- package/dist/core/cue-arg.d.ts +19 -0
- package/dist/core/cue-arg.js +72 -0
- package/dist/core/cues.d.ts +138 -0
- package/dist/core/cues.js +372 -0
- package/dist/core/decay.d.ts +49 -0
- package/dist/core/decay.js +157 -0
- package/dist/core/dreamer.d.ts +114 -0
- package/dist/core/dreamer.js +427 -0
- package/dist/core/embeddings.d.ts +79 -0
- package/dist/core/embeddings.js +133 -0
- package/dist/core/event-bus.d.ts +71 -0
- package/dist/core/event-bus.js +67 -0
- package/dist/core/hybrid.d.ts +33 -0
- package/dist/core/hybrid.js +63 -0
- package/dist/core/llm-generator.d.ts +18 -0
- package/dist/core/llm-generator.js +69 -0
- package/dist/core/sanitize.d.ts +57 -0
- package/dist/core/sanitize.js +87 -0
- package/dist/core/scripts.d.ts +55 -0
- package/dist/core/scripts.js +96 -0
- package/dist/core/search.d.ts +42 -0
- package/dist/core/search.js +173 -0
- package/dist/core/trust.d.ts +48 -0
- package/dist/core/trust.js +57 -0
- package/dist/core/types.d.ts +333 -0
- package/dist/core/types.js +1 -0
- package/dist/core/vector-clusterer.d.ts +53 -0
- package/dist/core/vector-clusterer.js +113 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +18 -0
- package/dist/mcp/server.d.ts +22 -0
- package/dist/mcp/server.js +158 -0
- package/dist/store/sqlite.d.ts +240 -0
- package/dist/store/sqlite.js +1653 -0
- package/docs/TESTING.md +244 -0
- package/package.json +95 -0
- package/public/app/galaxy-f42190mq.js +10 -0
- package/public/app/index-2cf31xxn.css +1 -0
- package/public/app/index-epqg22cp.js +1 -0
- package/public/app/index-f9h80bzq.js +12 -0
- package/public/app/index-gbfwa9vq.js +2 -0
- package/public/app/index-kvhc17mz.js +2 -0
- package/public/app/index-pbd5t4dj.js +2 -0
- package/public/app/index.html +12 -0
- package/public/app/promenade-cnzzpm73.js +4111 -0
- package/public/app/river-tyawhh8w.js +13 -0
- package/public/session.html +659 -0
- package/scripts/consolidate.js +46 -0
- package/scripts/hook-post-commit.ts +80 -0
- package/scripts/hook-session-start.ts +92 -0
- package/scripts/hook-session.ts +60 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cue resolver — Phase 5.2.
|
|
3
|
+
*
|
|
4
|
+
* You do not search for an intention: it comes back. This module decides *when*.
|
|
5
|
+
* It reads the armed cues and answers two questions, one temporal
|
|
6
|
+
* (`resolveTimeCues`), one event-driven (`resolveEventCues`); then `fire()` marks
|
|
7
|
+
* both cue and intention as surfaced to the agent.
|
|
8
|
+
*
|
|
9
|
+
* The data layer (tables, CRUD) is Phase 5.1, in `src/store/sqlite.ts`; there is
|
|
10
|
+
* nothing but decisions here. See PHASE5_PLAN.md § 5.2.
|
|
11
|
+
*/
|
|
12
|
+
import { systemClock } from './clock.js';
|
|
13
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
14
|
+
// Cron — minimal matcher, 5 fields (minute hour day-of-month month day-of-week)
|
|
15
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
16
|
+
const CRON_RANGES = [
|
|
17
|
+
[0, 59], // minute
|
|
18
|
+
[0, 23], // heure
|
|
19
|
+
[1, 31], // jour du mois
|
|
20
|
+
[1, 12], // mois
|
|
21
|
+
[0, 6], // jour de la semaine, 0 = dimanche
|
|
22
|
+
];
|
|
23
|
+
/** Expands a cron field (`*`, `5`, `1-5`, `*\/15`, `1-9/2`, lists) into a value set. */
|
|
24
|
+
function expandCronField(field, index) {
|
|
25
|
+
const [min, max] = CRON_RANGES[index];
|
|
26
|
+
const values = new Set();
|
|
27
|
+
for (const part of field.split(',')) {
|
|
28
|
+
const [rangePart, stepPart] = part.split('/');
|
|
29
|
+
const step = stepPart === undefined ? 1 : Number(stepPart);
|
|
30
|
+
if (!Number.isInteger(step) || step < 1)
|
|
31
|
+
return null;
|
|
32
|
+
let lo;
|
|
33
|
+
let hi;
|
|
34
|
+
if (rangePart === '*') {
|
|
35
|
+
lo = min;
|
|
36
|
+
hi = max;
|
|
37
|
+
}
|
|
38
|
+
else if (rangePart.includes('-')) {
|
|
39
|
+
const [a, b] = rangePart.split('-').map(Number);
|
|
40
|
+
if (!Number.isInteger(a) || !Number.isInteger(b))
|
|
41
|
+
return null;
|
|
42
|
+
lo = a;
|
|
43
|
+
hi = b;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
const n = Number(rangePart);
|
|
47
|
+
if (!Number.isInteger(n))
|
|
48
|
+
return null;
|
|
49
|
+
lo = n;
|
|
50
|
+
hi = n;
|
|
51
|
+
}
|
|
52
|
+
if (lo < min || hi > max || lo > hi)
|
|
53
|
+
return null;
|
|
54
|
+
for (let v = lo; v <= hi; v += step)
|
|
55
|
+
values.add(v);
|
|
56
|
+
}
|
|
57
|
+
return values.size ? values : null;
|
|
58
|
+
}
|
|
59
|
+
/** Parses a 5-field cron expression. Returns null when it is invalid. */
|
|
60
|
+
export function parseCron(expr) {
|
|
61
|
+
const fields = expr.trim().split(/\s+/);
|
|
62
|
+
if (fields.length !== 5)
|
|
63
|
+
return null;
|
|
64
|
+
const sets = fields.map((f, i) => expandCronField(f, i));
|
|
65
|
+
if (sets.some((s) => s === null))
|
|
66
|
+
return null;
|
|
67
|
+
const [minute, hour, dom, month, dow] = sets;
|
|
68
|
+
return {
|
|
69
|
+
minute,
|
|
70
|
+
hour,
|
|
71
|
+
dom,
|
|
72
|
+
month,
|
|
73
|
+
dow,
|
|
74
|
+
domRestricted: fields[2] !== '*',
|
|
75
|
+
dowRestricted: fields[4] !== '*',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* True when `date` (to the minute, in UTC) lands on a cron occurrence.
|
|
80
|
+
*
|
|
81
|
+
* When day-of-month and day-of-week are both restricted, standard cron combines
|
|
82
|
+
* them with OR, not AND — `0 9 1 * 1` means "the 1st of the month **or** on a
|
|
83
|
+
* Monday". That semantics is kept so nothing surprises anyone.
|
|
84
|
+
*/
|
|
85
|
+
export function cronMatches(parsed, date) {
|
|
86
|
+
if (!parsed.minute.has(date.getUTCMinutes()))
|
|
87
|
+
return false;
|
|
88
|
+
if (!parsed.hour.has(date.getUTCHours()))
|
|
89
|
+
return false;
|
|
90
|
+
if (!parsed.month.has(date.getUTCMonth() + 1))
|
|
91
|
+
return false;
|
|
92
|
+
const domHit = parsed.dom.has(date.getUTCDate());
|
|
93
|
+
const dowHit = parsed.dow.has(date.getUTCDay());
|
|
94
|
+
if (parsed.domRestricted && parsed.dowRestricted)
|
|
95
|
+
return domHit || dowHit;
|
|
96
|
+
if (parsed.domRestricted)
|
|
97
|
+
return domHit;
|
|
98
|
+
if (parsed.dowRestricted)
|
|
99
|
+
return dowHit;
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Cron catch-up window, in minutes (7 days).
|
|
104
|
+
*
|
|
105
|
+
* The resolver is not a daemon: it runs at SessionStart, so only now and then.
|
|
106
|
+
* Without catch-up, an occurrence falling between two sessions would be lost. So
|
|
107
|
+
* time is walked backwards minute by minute from `now` to the last known
|
|
108
|
+
* reference, capped by this window — beyond it, an occurrence is considered too
|
|
109
|
+
* old to be worth a wake-up.
|
|
110
|
+
*/
|
|
111
|
+
export const CRON_CATCHUP_MINUTES = 7 * 24 * 60;
|
|
112
|
+
/** True when a cron occurrence exists in the half-open interval (since, now]. */
|
|
113
|
+
export function cronDueSince(expr, since, now) {
|
|
114
|
+
const parsed = parseCron(expr);
|
|
115
|
+
if (!parsed)
|
|
116
|
+
return false; // invalid expression: never due, never a crash
|
|
117
|
+
const MINUTE = 60_000;
|
|
118
|
+
const nowMin = Math.floor(now.getTime() / MINUTE);
|
|
119
|
+
const sinceMin = Math.floor(since.getTime() / MINUTE);
|
|
120
|
+
const floor = Math.max(sinceMin + 1, nowMin - CRON_CATCHUP_MINUTES);
|
|
121
|
+
for (let m = nowMin; m >= floor; m--) {
|
|
122
|
+
if (cronMatches(parsed, new Date(m * MINUTE)))
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
128
|
+
// Event matching
|
|
129
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
130
|
+
/** Normalises separators so Windows and POSIX paths match alike. */
|
|
131
|
+
function normalizePath(p) {
|
|
132
|
+
return p.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* A cue is only eligible within its mental place: the event must come from the
|
|
136
|
+
* intention's `directory` or a subdirectory. Without this, a loop opened on one
|
|
137
|
+
* project would wake while working on another — the database is shared across
|
|
138
|
+
* projects.
|
|
139
|
+
*/
|
|
140
|
+
function directoryMatches(intentionDir, eventDir) {
|
|
141
|
+
if (!eventDir)
|
|
142
|
+
return true; // event without context: no filtering
|
|
143
|
+
const a = normalizePath(intentionDir).replace(/\/$/, '');
|
|
144
|
+
const b = normalizePath(eventDir).replace(/\/$/, '');
|
|
145
|
+
return b === a || b.startsWith(`${a}/`) || a.startsWith(`${b}/`);
|
|
146
|
+
}
|
|
147
|
+
/** Tests an error pattern. An invalid regex falls back to a literal search. */
|
|
148
|
+
function errorPatternMatches(pattern, text) {
|
|
149
|
+
try {
|
|
150
|
+
return new RegExp(pattern, 'i').test(text);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return text.toLowerCase().includes(pattern.toLowerCase());
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** True when this event trigger matches this event. */
|
|
157
|
+
export function eventTriggerMatches(spec, event) {
|
|
158
|
+
switch (spec.type) {
|
|
159
|
+
case 'file_open': {
|
|
160
|
+
if (event.type !== 'file_open')
|
|
161
|
+
return false;
|
|
162
|
+
const want = normalizePath(spec.path);
|
|
163
|
+
const got = normalizePath(event.path);
|
|
164
|
+
// Suffix accepted: a cue armed on 'src/auth/service.ts' must match an event
|
|
165
|
+
// carrying the absolute path of the same file.
|
|
166
|
+
return got === want || got.endsWith(`/${want}`);
|
|
167
|
+
}
|
|
168
|
+
case 'branch_switch':
|
|
169
|
+
return event.type === 'branch_switch' && event.branch === spec.branch;
|
|
170
|
+
case 'error_pattern':
|
|
171
|
+
return event.type === 'error_pattern' && errorPatternMatches(spec.pattern, event.text);
|
|
172
|
+
default:
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
177
|
+
// Short loop identity
|
|
178
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
179
|
+
/** Length of the UUID prefix used as a readable loop identifier. */
|
|
180
|
+
export const LOOP_ID_LENGTH = 8;
|
|
181
|
+
/**
|
|
182
|
+
* Short identifier shown to the agent: `loop-a1b2c3d4`. This is what a human
|
|
183
|
+
* retypes into a commit message (`Closes loop-a1b2c3d4`) — a full UUID would
|
|
184
|
+
* never be retyped by hand.
|
|
185
|
+
*/
|
|
186
|
+
export function loopId(intentionId) {
|
|
187
|
+
return `loop-${intentionId.slice(0, LOOP_ID_LENGTH)}`;
|
|
188
|
+
}
|
|
189
|
+
/** Extracts short loop ids mentioned in a text (a commit message). */
|
|
190
|
+
export function extractLoopIds(text) {
|
|
191
|
+
const found = new Set();
|
|
192
|
+
for (const m of text.matchAll(/\bloop-([0-9a-f]{4,36})\b/gi)) {
|
|
193
|
+
found.add(m[1].toLowerCase());
|
|
194
|
+
}
|
|
195
|
+
return [...found];
|
|
196
|
+
}
|
|
197
|
+
/** Finds the intention a short id points to, when it is unambiguous. */
|
|
198
|
+
export function matchIntentionByShortId(intentions, shortId) {
|
|
199
|
+
const needle = shortId.toLowerCase();
|
|
200
|
+
const hits = intentions.filter((i) => i.id.toLowerCase().startsWith(needle));
|
|
201
|
+
// An ambiguous prefix closes nothing: better to do nothing than close the wrong loop.
|
|
202
|
+
return hits.length === 1 ? hits[0] : null;
|
|
203
|
+
}
|
|
204
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
205
|
+
// Decay rules for intentions
|
|
206
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
207
|
+
/** Salience decline of a fired intention, in points per day (the Zeigarnik pull fading). */
|
|
208
|
+
export const INTENTION_FADE_PER_DAY = 10;
|
|
209
|
+
/**
|
|
210
|
+
* Current salience of an intention (PHASE5_PLAN.md § 5.2):
|
|
211
|
+
* - `armed` → pinned at 100: an open loop stays salient, it does not decay
|
|
212
|
+
* - `fired` and not `closed` → declines from `firedAt`: the Zeigarnik pull fades
|
|
213
|
+
* - `closed` → 0: archived, kept for history
|
|
214
|
+
* - `expired` → 0: soft-deleted
|
|
215
|
+
*/
|
|
216
|
+
export function intentionSaillance(intention, now) {
|
|
217
|
+
switch (intention.status) {
|
|
218
|
+
case 'armed':
|
|
219
|
+
return 100;
|
|
220
|
+
case 'closed':
|
|
221
|
+
case 'expired':
|
|
222
|
+
return 0;
|
|
223
|
+
case 'fired': {
|
|
224
|
+
if (!intention.firedAt)
|
|
225
|
+
return intention.saillance;
|
|
226
|
+
const days = (now.getTime() - intention.firedAt.getTime()) / 86_400_000;
|
|
227
|
+
return Math.max(0, Math.round(100 - days * INTENTION_FADE_PER_DAY));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
export class SqliteCueResolver {
|
|
232
|
+
store;
|
|
233
|
+
clock;
|
|
234
|
+
constructor(store, options = {}) {
|
|
235
|
+
this.store = store;
|
|
236
|
+
this.clock = options.clock ?? systemClock;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* A cue only wakes while its target is live: an intention still `armed`, a
|
|
240
|
+
* script still `active` (8.1 — drafts never fire). Returns the target's
|
|
241
|
+
* directory for mental-place filtering, or null when the target is dead.
|
|
242
|
+
*/
|
|
243
|
+
async liveTargetDirectoryOf(cue) {
|
|
244
|
+
if (cue.targetKind === 'script') {
|
|
245
|
+
const script = this.store.getScript ? await this.store.getScript(cue.targetId) : null;
|
|
246
|
+
return script && script.status === 'active' ? script.directory : null;
|
|
247
|
+
}
|
|
248
|
+
const intention = await this.store.getIntention(cue.targetId);
|
|
249
|
+
return intention && intention.status === 'armed' ? intention.directory : null;
|
|
250
|
+
}
|
|
251
|
+
async resolveTimeCues(now = this.clock.now()) {
|
|
252
|
+
const cues = await this.store.listCues({ status: 'armed', kind: 'time', limit: 500 });
|
|
253
|
+
const due = [];
|
|
254
|
+
for (const cue of cues) {
|
|
255
|
+
const spec = cue.triggerSpec;
|
|
256
|
+
if (spec.kind !== 'time')
|
|
257
|
+
continue;
|
|
258
|
+
let isDue = false;
|
|
259
|
+
if (spec.at) {
|
|
260
|
+
const at = new Date(spec.at);
|
|
261
|
+
isDue = !Number.isNaN(at.getTime()) && at.getTime() <= now.getTime();
|
|
262
|
+
}
|
|
263
|
+
else if (spec.cron) {
|
|
264
|
+
// Reference: the last known wake-up, otherwise the arming time.
|
|
265
|
+
isDue = cronDueSince(spec.cron, cue.firedAt ?? cue.armedAt, now);
|
|
266
|
+
}
|
|
267
|
+
if (!isDue)
|
|
268
|
+
continue;
|
|
269
|
+
if (!(await this.liveTargetDirectoryOf(cue)))
|
|
270
|
+
continue;
|
|
271
|
+
due.push(cue);
|
|
272
|
+
}
|
|
273
|
+
return due;
|
|
274
|
+
}
|
|
275
|
+
async resolveEventCues(event) {
|
|
276
|
+
// A commit does not wake an intention, it closes one — that is the
|
|
277
|
+
// post-commit hook's job (S5-03b), not this resolver's.
|
|
278
|
+
if (event.type === 'commit')
|
|
279
|
+
return [];
|
|
280
|
+
const cues = await this.store.listCues({ status: 'armed', kind: 'event', limit: 500 });
|
|
281
|
+
const matched = [];
|
|
282
|
+
for (const cue of cues) {
|
|
283
|
+
const spec = cue.triggerSpec;
|
|
284
|
+
if (spec.kind !== 'event')
|
|
285
|
+
continue;
|
|
286
|
+
if (!eventTriggerMatches(spec, event))
|
|
287
|
+
continue;
|
|
288
|
+
const directory = await this.liveTargetDirectoryOf(cue);
|
|
289
|
+
if (!directory)
|
|
290
|
+
continue;
|
|
291
|
+
if (!directoryMatches(directory, event.directory))
|
|
292
|
+
continue;
|
|
293
|
+
matched.push(cue);
|
|
294
|
+
}
|
|
295
|
+
return matched;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Marks cue and intention as fired. A cron cue is re-armed after firing: a
|
|
299
|
+
* recurrence that does not re-arm is a one-shot in disguise.
|
|
300
|
+
*/
|
|
301
|
+
async fire(cueId) {
|
|
302
|
+
const cue = await this.store.getCue(cueId);
|
|
303
|
+
if (!cue)
|
|
304
|
+
throw new Error(`Cue ${cueId} not found`);
|
|
305
|
+
if (cue.targetKind !== 'intention')
|
|
306
|
+
throw new Error(`Cue ${cueId} arms a script — use fireScript`);
|
|
307
|
+
const spec = cue.triggerSpec;
|
|
308
|
+
const recurring = spec.kind === 'time' && Boolean(spec.cron);
|
|
309
|
+
await this.store.markCueFired(cueId, { rearm: recurring });
|
|
310
|
+
return this.store.updateIntentionStatus(cue.targetId, 'fired');
|
|
311
|
+
}
|
|
312
|
+
/** Script counterpart of fire(): same cue bookkeeping, script bumped (8.1). */
|
|
313
|
+
async fireScript(cueId) {
|
|
314
|
+
const cue = await this.store.getCue(cueId);
|
|
315
|
+
if (!cue)
|
|
316
|
+
throw new Error(`Cue ${cueId} not found`);
|
|
317
|
+
if (cue.targetKind !== 'script')
|
|
318
|
+
throw new Error(`Cue ${cueId} arms an intention — use fire`);
|
|
319
|
+
if (!this.store.markScriptFired)
|
|
320
|
+
throw new Error('Store has no ScriptStore support');
|
|
321
|
+
const spec = cue.triggerSpec;
|
|
322
|
+
const recurring = spec.kind === 'time' && Boolean(spec.cron);
|
|
323
|
+
await this.store.markCueFired(cueId, { rearm: recurring });
|
|
324
|
+
return this.store.markScriptFired(cue.targetId);
|
|
325
|
+
}
|
|
326
|
+
async fireAny(cueId) {
|
|
327
|
+
const cue = await this.store.getCue(cueId);
|
|
328
|
+
if (!cue)
|
|
329
|
+
throw new Error(`Cue ${cueId} not found`);
|
|
330
|
+
if (cue.targetKind === 'script')
|
|
331
|
+
return { kind: 'script', script: await this.fireScript(cueId) };
|
|
332
|
+
return { kind: 'intention', intention: await this.fire(cueId) };
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Expires `armed` intentions whose `expiresAt` has passed and cancels their
|
|
336
|
+
* cues — a cue outliving its intention is a ghost wake-up.
|
|
337
|
+
*/
|
|
338
|
+
async expireStale(now = this.clock.now()) {
|
|
339
|
+
const armed = await this.store.listIntentions({ status: 'armed', limit: 500 });
|
|
340
|
+
let expired = 0;
|
|
341
|
+
for (const intention of armed) {
|
|
342
|
+
if (!intention.expiresAt || intention.expiresAt.getTime() > now.getTime())
|
|
343
|
+
continue;
|
|
344
|
+
await this.store.updateIntentionStatus(intention.id, 'expired');
|
|
345
|
+
for (const cue of await this.store.listCues({ intentionId: intention.id, status: 'armed' })) {
|
|
346
|
+
await this.store.updateCueStatus(cue.id, 'cancelled');
|
|
347
|
+
}
|
|
348
|
+
expired++;
|
|
349
|
+
}
|
|
350
|
+
return expired;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Wires a resolver onto an event bus: every published event wakes the cues that
|
|
355
|
+
* match. Returns the unsubscribe handle.
|
|
356
|
+
*
|
|
357
|
+
* ```ts
|
|
358
|
+
* const detach = attachResolverToBus(bus, resolver);
|
|
359
|
+
* await bus.publish({ type: 'branch_switch', branch: 'feature/x', directory: '/src' });
|
|
360
|
+
* ```
|
|
361
|
+
*/
|
|
362
|
+
export function attachResolverToBus(bus, resolver, options = {}) {
|
|
363
|
+
return bus.subscribeAll(async (event) => {
|
|
364
|
+
for (const cue of await resolver.resolveEventCues(event)) {
|
|
365
|
+
const fired = await resolver.fireAny(cue.id);
|
|
366
|
+
if (fired.kind === 'script')
|
|
367
|
+
await options.onScriptFired?.(fired.script, cue);
|
|
368
|
+
else
|
|
369
|
+
await options.onFired?.(fired.intention, cue);
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Memory, DecayLevel } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Decay configuration.
|
|
4
|
+
*/
|
|
5
|
+
export declare const DECAY_CONFIG: {
|
|
6
|
+
levelThresholds: number[];
|
|
7
|
+
recallBonus: number;
|
|
8
|
+
saillanceThreshold: number;
|
|
9
|
+
verifiedMultiplier: number;
|
|
10
|
+
maxTotalSlowdown: number;
|
|
11
|
+
contradictionDivisor: number;
|
|
12
|
+
refuteDivisor: number;
|
|
13
|
+
refuteCap: number;
|
|
14
|
+
contradictionFloor: number;
|
|
15
|
+
decayCycleHours: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Current decay level of a trace.
|
|
19
|
+
*/
|
|
20
|
+
export declare function calculateDecayLevel(memory: Memory, now?: Date): DecayLevel;
|
|
21
|
+
/**
|
|
22
|
+
* Salience score of a trace.
|
|
23
|
+
* Based on recent recalls, connections and emotional charge.
|
|
24
|
+
*/
|
|
25
|
+
export declare function calculateSaillance(memory: Memory, now?: Date): number;
|
|
26
|
+
/**
|
|
27
|
+
* Initial decay rate.
|
|
28
|
+
* 0.0 = very slow, 1.0 = very fast.
|
|
29
|
+
*/
|
|
30
|
+
export declare function calculateDecayRate(content: string, keywords: string[]): number;
|
|
31
|
+
export interface DecayCurvePoint {
|
|
32
|
+
time: Date;
|
|
33
|
+
level: DecayLevel;
|
|
34
|
+
saillance: number;
|
|
35
|
+
hoursElapsed: number;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Projects a trace's forgetting curve over `daysAhead` days, one point every six
|
|
39
|
+
* hours.
|
|
40
|
+
*
|
|
41
|
+
* It lives here, next to the rules it samples, rather than in the visualisation
|
|
42
|
+
* code: a curve drawn from a diverging copy of the algorithm would tell a story
|
|
43
|
+
* the system does not actually live.
|
|
44
|
+
*/
|
|
45
|
+
export declare function projectDecayCurve(memory: Memory, daysAhead?: number): DecayCurvePoint[];
|
|
46
|
+
/**
|
|
47
|
+
* Updates every trace in a collection.
|
|
48
|
+
*/
|
|
49
|
+
export declare function updateAllDecay(memories: Memory[], now?: Date): Memory[];
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decay configuration.
|
|
3
|
+
*/
|
|
4
|
+
export const DECAY_CONFIG = {
|
|
5
|
+
// Base time for each level, in hours
|
|
6
|
+
levelThresholds: [0, 24, 168, 720, 2160], // 0h, 1j, 1sem, 1mois, 3mois
|
|
7
|
+
// How much each recall slows decay
|
|
8
|
+
recallBonus: 0.3, // every recall adds 30% more time
|
|
9
|
+
// Salience threshold above which decay slows down
|
|
10
|
+
saillanceThreshold: 70,
|
|
11
|
+
// Phase 6.0.1 — verified traces age more slowly
|
|
12
|
+
verifiedMultiplier: 1.5,
|
|
13
|
+
// Phase 6.0.1 / Claude R3-B8 — cap on the PRODUCT of all slowdown
|
|
14
|
+
// multipliers (recall × salience × verified). Without this, the unbounded
|
|
15
|
+
// `1 + recallCount * recallBonus` term makes verified+salient+recalled
|
|
16
|
+
// traces effectively photographic — which is not forgetting.
|
|
17
|
+
maxTotalSlowdown: 2.5,
|
|
18
|
+
// Phase 6.0.2 — contradiction collapse (Kimi B9, accepted by Claude R3):
|
|
19
|
+
// first refutation divides saillance by `contradictionDivisor`, further ones
|
|
20
|
+
// by `refuteDivisor` (cap `refuteCap` refutations), never below the floor.
|
|
21
|
+
contradictionDivisor: 4,
|
|
22
|
+
refuteDivisor: 2,
|
|
23
|
+
refuteCap: 3,
|
|
24
|
+
contradictionFloor: 5,
|
|
25
|
+
// Decay cycle: how often the sweep runs, in hours
|
|
26
|
+
decayCycleHours: 24,
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Current decay level of a trace.
|
|
30
|
+
*/
|
|
31
|
+
export function calculateDecayLevel(memory, now = new Date()) {
|
|
32
|
+
if (memory.photographic) {
|
|
33
|
+
return 0; // Photographic mode — no decay
|
|
34
|
+
}
|
|
35
|
+
if (memory.currentLevel === 4 || memory.mergedIntoId) {
|
|
36
|
+
return 4; // already lost or merged
|
|
37
|
+
}
|
|
38
|
+
const hoursSinceCreation = (now.getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60);
|
|
39
|
+
const hoursSinceRecall = memory.lastRecalled
|
|
40
|
+
? (now.getTime() - memory.lastRecalled.getTime()) / (1000 * 60 * 60)
|
|
41
|
+
: Infinity;
|
|
42
|
+
// Use whichever of the two is more recent
|
|
43
|
+
const effectiveAge = Math.min(hoursSinceCreation, hoursSinceRecall);
|
|
44
|
+
// Appliquer le bonus de rappel
|
|
45
|
+
const recallMultiplier = 1 + (memory.recallCount * DECAY_CONFIG.recallBonus);
|
|
46
|
+
// Appliquer le bonus de saillance
|
|
47
|
+
const saillanceMultiplier = memory.saillance >= DECAY_CONFIG.saillanceThreshold ? 1.5 : 1;
|
|
48
|
+
// Phase 6.0.1 — le bonus de vérification
|
|
49
|
+
const verifiedMultiplier = memory.verified ? DECAY_CONFIG.verifiedMultiplier : 1;
|
|
50
|
+
// Cap on the PRODUCT (R3/B8): the unbounded recall term counts toward it.
|
|
51
|
+
const totalSlowdown = Math.min(recallMultiplier * saillanceMultiplier * verifiedMultiplier, DECAY_CONFIG.maxTotalSlowdown);
|
|
52
|
+
const finalAge = effectiveAge / totalSlowdown;
|
|
53
|
+
// Determine the level
|
|
54
|
+
for (let i = 3; i >= 0; i--) {
|
|
55
|
+
if (finalAge >= DECAY_CONFIG.levelThresholds[i]) {
|
|
56
|
+
return i;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Salience score of a trace.
|
|
63
|
+
* Based on recent recalls, connections and emotional charge.
|
|
64
|
+
*/
|
|
65
|
+
export function calculateSaillance(memory, now = new Date()) {
|
|
66
|
+
let score = 50; // baseline
|
|
67
|
+
// Bonus for recent recalls (within 7 days)
|
|
68
|
+
if (memory.lastRecalled) {
|
|
69
|
+
const daysSinceRecall = (now.getTime() - memory.lastRecalled.getTime()) / (1000 * 60 * 60 * 24);
|
|
70
|
+
if (daysSinceRecall < 7) {
|
|
71
|
+
score += 20;
|
|
72
|
+
}
|
|
73
|
+
else if (daysSinceRecall < 30) {
|
|
74
|
+
score += 10;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Bonus for how often it was recalled
|
|
78
|
+
score += Math.min(memory.recallCount * 5, 20);
|
|
79
|
+
// Bonus for keywords: more tags means better connected
|
|
80
|
+
score += Math.min(memory.keywords.length * 3, 15);
|
|
81
|
+
// Crude emotional-charge detection. The list stays bilingual on purpose: traces
|
|
82
|
+
// are written in whatever language the developer works in, and dropping the
|
|
83
|
+
// French markers would silently weaken salience on French content.
|
|
84
|
+
const emotionalWords = [
|
|
85
|
+
'important', 'urgent', 'critical', 'attention', 'wow', 'awesome', 'damn', 'problem', 'error', 'broken',
|
|
86
|
+
'génial', 'merde', 'problème', 'erreur', 'super',
|
|
87
|
+
];
|
|
88
|
+
const contentLower = memory.content.toLowerCase();
|
|
89
|
+
const hasEmotion = emotionalWords.some(word => contentLower.includes(word));
|
|
90
|
+
if (hasEmotion) {
|
|
91
|
+
score += 10;
|
|
92
|
+
}
|
|
93
|
+
return Math.min(score, 100);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Initial decay rate.
|
|
97
|
+
* 0.0 = very slow, 1.0 = very fast.
|
|
98
|
+
*/
|
|
99
|
+
export function calculateDecayRate(content, keywords) {
|
|
100
|
+
// Base rate
|
|
101
|
+
let rate = 0.5;
|
|
102
|
+
// Long content decays more slowly: there is more detail worth keeping
|
|
103
|
+
if (content.length > 500) {
|
|
104
|
+
rate -= 0.1;
|
|
105
|
+
}
|
|
106
|
+
else if (content.length < 100) {
|
|
107
|
+
rate += 0.1;
|
|
108
|
+
}
|
|
109
|
+
// Many keywords means better connected, so slower decay
|
|
110
|
+
if (keywords.length > 5) {
|
|
111
|
+
rate -= 0.1;
|
|
112
|
+
}
|
|
113
|
+
return Math.max(0.1, Math.min(1.0, rate));
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Projects a trace's forgetting curve over `daysAhead` days, one point every six
|
|
117
|
+
* hours.
|
|
118
|
+
*
|
|
119
|
+
* It lives here, next to the rules it samples, rather than in the visualisation
|
|
120
|
+
* code: a curve drawn from a diverging copy of the algorithm would tell a story
|
|
121
|
+
* the system does not actually live.
|
|
122
|
+
*/
|
|
123
|
+
export function projectDecayCurve(memory, daysAhead = 90) {
|
|
124
|
+
const points = [];
|
|
125
|
+
const createdAt = new Date(memory.createdAt).getTime();
|
|
126
|
+
const totalMs = daysAhead * 24 * 3600_000;
|
|
127
|
+
const stepMs = 6 * 3600_000;
|
|
128
|
+
for (let t = 0; t <= totalMs; t += stepMs) {
|
|
129
|
+
const at = new Date(createdAt + t);
|
|
130
|
+
points.push({
|
|
131
|
+
time: at,
|
|
132
|
+
level: calculateDecayLevel(memory, at),
|
|
133
|
+
saillance: calculateSaillance(memory, at),
|
|
134
|
+
hoursElapsed: t / 3600_000,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return points;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Updates every trace in a collection.
|
|
141
|
+
*/
|
|
142
|
+
export function updateAllDecay(memories, now = new Date()) {
|
|
143
|
+
return memories.map(memory => {
|
|
144
|
+
const newLevel = calculateDecayLevel(memory, now);
|
|
145
|
+
const newSaillance = calculateSaillance(memory, now);
|
|
146
|
+
// Mark as lost/merged once level 4 is reached
|
|
147
|
+
if (newLevel === 4 && memory.currentLevel !== 4) {
|
|
148
|
+
// TODO: merging logic still to implement
|
|
149
|
+
console.log(`Memory ${memory.id} marked as decayed (level 4)`);
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
...memory,
|
|
153
|
+
currentLevel: newLevel,
|
|
154
|
+
saillance: newSaillance,
|
|
155
|
+
};
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
import type { Memory, MemoryStore, IntentionStore, ScriptStore, DreamProposal } from './types.js';
|
|
19
|
+
import { type Clock } from './clock.js';
|
|
20
|
+
export declare const DREAM_CONFIG: {
|
|
21
|
+
/** Traces younger than this are considered. */
|
|
22
|
+
windowDays: number;
|
|
23
|
+
/** A cluster qualifies at ≥ K traces from ≥ 2 sessions, or ≥ 2 agents. */
|
|
24
|
+
minClusterSize: number;
|
|
25
|
+
minDistinctSessions: number;
|
|
26
|
+
minDistinctAgents: number;
|
|
27
|
+
/** Corroboration also requires distinct directories — agreement ≠ independence. */
|
|
28
|
+
minDistinctDirectories: number;
|
|
29
|
+
/** Jaccard similarity threshold for the keyword clusterer. */
|
|
30
|
+
similarityThreshold: number;
|
|
31
|
+
/**
|
|
32
|
+
* FALLBACK cluster threshold, used only for embedders without a calibrated
|
|
33
|
+
* per-model value (HashEmbedder in tests). Production models carry their
|
|
34
|
+
* own in CLUSTER_THRESHOLDS (embeddings.ts, 7.5 rounds 1–4): e5-small
|
|
35
|
+
* 0.855 / e5-base 0.825 / bge-m3 0.740 (best F1 0.89).
|
|
36
|
+
*
|
|
37
|
+
* vectorCorroborateThreshold 0.99 = SENTINEL, auto-corroboration DISABLED.
|
|
38
|
+
* Four calibration rounds (e5-small, e5-base ×2, bge-m3 — 52 labelled pairs
|
|
39
|
+
* incl. same-domain hard negatives) all failed to find a P=1.0 gate
|
|
40
|
+
* (best-case false max 0.908 > true min 0.691 with bge-m3). Re-enabling
|
|
41
|
+
* requires a stronger embedder or an LLM pairwise verifier, not more fixture.
|
|
42
|
+
*/
|
|
43
|
+
vectorClusterThreshold: number;
|
|
44
|
+
vectorCorroborateThreshold: number;
|
|
45
|
+
/** Proposal lifetime (owner-approved 14d expiry). */
|
|
46
|
+
proposalTtlDays: number;
|
|
47
|
+
/** LLM drafting cap per run; skipped entirely without a client. */
|
|
48
|
+
maxDraftsPerRun: number;
|
|
49
|
+
/** Loops open longer than this are stale-loop candidates. */
|
|
50
|
+
staleLoopDays: number;
|
|
51
|
+
/** Max traces read per run. */
|
|
52
|
+
collectLimit: number;
|
|
53
|
+
/**
|
|
54
|
+
* Phase 8.5 — script mining. A "correction" is a trace that WON an active
|
|
55
|
+
* contradiction: 6.0.2 already establishes that mechanism as evidence a
|
|
56
|
+
* prior trace was wrong, so reusing it avoids inventing a new "correction"
|
|
57
|
+
* tag with no producer anywhere in the codebase (Claude's Phase 8
|
|
58
|
+
* annotation flagged the alternative — tagging memoryType — as dead weight
|
|
59
|
+
* without one).
|
|
60
|
+
*/
|
|
61
|
+
scriptCandidateMinCluster: number;
|
|
62
|
+
/** Draft steps are raw trace content, capped — no LLM drafting for this kind (out of scope, PHASE8_PLAN §Out of scope). */
|
|
63
|
+
scriptCandidateMaxSteps: number;
|
|
64
|
+
};
|
|
65
|
+
/** Phase 7 seam: swap this implementation for a vector clusterer. */
|
|
66
|
+
export interface Clusterer {
|
|
67
|
+
/** Async since Phase 7.1 — vector clusterers embed before grouping. */
|
|
68
|
+
cluster(memories: Memory[]): Promise<Memory[][]> | Memory[][];
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Keyword clusterer: union-find over pairwise Jaccard similarity. Deterministic
|
|
72
|
+
* (stable iteration order, ties broken by insertion order), local, dependency-free.
|
|
73
|
+
*/
|
|
74
|
+
export declare class KeywordClusterer implements Clusterer {
|
|
75
|
+
private threshold;
|
|
76
|
+
constructor(threshold?: number);
|
|
77
|
+
cluster(memories: Memory[]): Memory[][];
|
|
78
|
+
}
|
|
79
|
+
export interface DreamReport {
|
|
80
|
+
considered: number;
|
|
81
|
+
clusters: number;
|
|
82
|
+
filed: number;
|
|
83
|
+
expired: number;
|
|
84
|
+
staleLoopCandidates: number;
|
|
85
|
+
draftsWritten: number;
|
|
86
|
+
/** Traces that earned `corroborated` verification during this run (6.0.1). */
|
|
87
|
+
corroborated: number;
|
|
88
|
+
/** `script_candidate` proposals filed this run (8.5). */
|
|
89
|
+
scriptCandidates: number;
|
|
90
|
+
proposals: DreamProposal[];
|
|
91
|
+
}
|
|
92
|
+
export interface DreamOptions {
|
|
93
|
+
store: MemoryStore & IntentionStore;
|
|
94
|
+
clusterer?: Clusterer;
|
|
95
|
+
clock?: Clock;
|
|
96
|
+
/**
|
|
97
|
+
* Optional LLM drafting of consolidated wording. Capped and skipped when
|
|
98
|
+
* absent — the job then files proposals with the raw cluster, never fails.
|
|
99
|
+
*/
|
|
100
|
+
draft?: (cluster: Memory[]) => Promise<string>;
|
|
101
|
+
/** Human identity for resolvedBy — `git config user.email`, fallback 'cli'. */
|
|
102
|
+
now?: never;
|
|
103
|
+
/** Override the 30-day collection window (validation / deep retrospectives). */
|
|
104
|
+
windowDays?: number;
|
|
105
|
+
}
|
|
106
|
+
export declare function runDreamer(options: DreamOptions): Promise<DreamReport>;
|
|
107
|
+
/**
|
|
108
|
+
* Applies an approved proposal. Returns a human-readable summary of the effect.
|
|
109
|
+
* `update_agents_md` never writes the file — it returns the suggested line for
|
|
110
|
+
* the human to paste (level-1 memory stays human-owned, permanently).
|
|
111
|
+
*/
|
|
112
|
+
export declare function applyDreamProposal(store: MemoryStore & IntentionStore & ScriptStore, proposal: DreamProposal, options?: {
|
|
113
|
+
clock?: Clock;
|
|
114
|
+
}): Promise<string>;
|