humemory 0.2.6 → 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.
Files changed (95) hide show
  1. package/AGENTS.md +49 -4
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +22 -10
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +89 -0
  9. package/dist/agent/maintenance-queue.js +245 -87
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +68 -17
  12. package/dist/agent/maintenance-state.d.ts +4 -0
  13. package/dist/agent/mcp-client-setup.d.ts +16 -0
  14. package/dist/agent/mcp-client-setup.js +108 -0
  15. package/dist/agent/opencode-import.d.ts +22 -0
  16. package/dist/agent/opencode-import.js +71 -0
  17. package/dist/agent/opencode-session-parser.d.ts +3 -0
  18. package/dist/agent/opencode-session-parser.js +35 -0
  19. package/dist/agent/session-parser.d.ts +8 -0
  20. package/dist/agent/session-parser.js +18 -0
  21. package/dist/agent/source-registry.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +164 -4
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/embeddings.d.ts +0 -10
  27. package/dist/core/embeddings.js +2 -1
  28. package/dist/core/llm-generator.d.ts +2 -10
  29. package/dist/core/paths.d.ts +5 -0
  30. package/dist/core/paths.js +27 -0
  31. package/dist/core/project-path.d.ts +3 -0
  32. package/dist/core/project-path.js +14 -0
  33. package/dist/core/search.d.ts +1 -1
  34. package/dist/core/search.js +7 -9
  35. package/dist/core/types.d.ts +13 -1
  36. package/dist/index.d.ts +5 -0
  37. package/dist/index.js +5 -0
  38. package/dist/store/sqlite.d.ts +37 -0
  39. package/dist/store/sqlite.js +94 -42
  40. package/package.json +4 -3
  41. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  42. package/public/app/index.html +1 -1
  43. package/scripts/consolidate.js +4 -4
  44. package/scripts/hook-post-commit.ts +2 -1
  45. package/scripts/hook-session-start.ts +2 -1
  46. package/scripts/hook-session.ts +2 -1
  47. package/src/agent/claude-hook.ts +126 -0
  48. package/src/agent/codex-import.ts +129 -0
  49. package/src/agent/codex-rollout-parser.ts +121 -0
  50. package/src/agent/commit-closer.ts +173 -0
  51. package/src/agent/kimi-import.ts +128 -0
  52. package/src/agent/kimi-session-parser.ts +127 -0
  53. package/src/agent/learning-extractor.ts +128 -0
  54. package/src/agent/maintenance-queue.ts +546 -0
  55. package/src/agent/maintenance-runner.ts +322 -0
  56. package/src/agent/maintenance-state.ts +168 -0
  57. package/src/agent/mcp-client-setup.ts +125 -0
  58. package/src/agent/opencode-import.ts +96 -0
  59. package/src/agent/opencode-session-parser.ts +53 -0
  60. package/src/agent/session-context.ts +302 -0
  61. package/src/agent/session-parser.ts +155 -0
  62. package/src/agent/source-registry.ts +135 -0
  63. package/src/api/cors.ts +42 -0
  64. package/src/api/dream-routes.ts +46 -0
  65. package/src/api/errors.ts +45 -0
  66. package/src/api/intentions-routes.ts +348 -0
  67. package/src/api/limits.ts +90 -0
  68. package/src/api/maintenance-routes.ts +73 -0
  69. package/src/api/memory-routes.ts +391 -0
  70. package/src/api/scripts-routes.ts +176 -0
  71. package/src/api/security-headers.ts +54 -0
  72. package/src/api/server.ts +292 -0
  73. package/src/cli/index.ts +1175 -0
  74. package/src/core/clock.ts +64 -0
  75. package/src/core/cue-arg.ts +79 -0
  76. package/src/core/cues.ts +511 -0
  77. package/src/core/decay.ts +198 -0
  78. package/src/core/dreamer.ts +494 -0
  79. package/src/core/embeddings.ts +157 -0
  80. package/src/core/event-bus.ts +100 -0
  81. package/src/core/hybrid.ts +78 -0
  82. package/src/core/llm-cli-client.ts +118 -0
  83. package/src/core/llm-generator.ts +90 -0
  84. package/src/core/paths.ts +28 -0
  85. package/src/core/project-path.ts +14 -0
  86. package/src/core/sanitize.ts +116 -0
  87. package/src/core/scripts.ts +112 -0
  88. package/src/core/search.ts +189 -0
  89. package/src/core/trust.ts +67 -0
  90. package/src/core/types.ts +393 -0
  91. package/src/core/vector-clusterer.ts +131 -0
  92. package/src/index.ts +40 -0
  93. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  94. package/src/mcp/server.ts +202 -0
  95. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Clock seam — lets tests drive time.
3
+ *
4
+ * humemory is time-driven: all decay (L0→L4) depends on the gap between
5
+ * `createdAt`/`lastRecalled` and "now". As long as that "now" is a `new Date()`
6
+ * buried in the store, a level transition can only be tested by actually waiting
7
+ * 24 hours. This module extracts the seam: production injects `systemClock`,
8
+ * tests inject a `FakeClock` they advance by hand.
9
+ *
10
+ * See docs/TESTING.md → pillar 2.
11
+ */
12
+
13
+ export interface Clock {
14
+ now(): Date;
15
+ }
16
+
17
+ /** Production clock — reads the system time. */
18
+ export const systemClock: Clock = {
19
+ now: () => new Date(),
20
+ };
21
+
22
+ /**
23
+ * Test clock — only moves when `advance()`/`set()` is called.
24
+ *
25
+ * ```ts
26
+ * const clock = new FakeClock(new Date('2026-01-01T00:00:00Z'));
27
+ * const store = new SQLiteStore(':memory:', { clock });
28
+ * clock.advance(25 * 3600_000); // +25h, L0 → L1
29
+ * ```
30
+ */
31
+ export class FakeClock implements Clock {
32
+ private t: Date;
33
+
34
+ constructor(start: Date | string | number = new Date('2026-01-01T00:00:00.000Z')) {
35
+ this.t = new Date(start);
36
+ }
37
+
38
+ now(): Date {
39
+ // Defensive copy: a caller mutating the result must not shift the clock.
40
+ return new Date(this.t.getTime());
41
+ }
42
+
43
+ /** Advances by `ms` milliseconds. */
44
+ advance(ms: number): this {
45
+ this.t = new Date(this.t.getTime() + ms);
46
+ return this;
47
+ }
48
+
49
+ /** Advances by `h` hours — decay thresholds are expressed in hours. */
50
+ advanceHours(h: number): this {
51
+ return this.advance(h * 3600_000);
52
+ }
53
+
54
+ /** Advances by `d` days. */
55
+ advanceDays(d: number): this {
56
+ return this.advance(d * 24 * 3600_000);
57
+ }
58
+
59
+ /** Moves the clock to an absolute date. */
60
+ set(t: Date | string | number): this {
61
+ this.t = new Date(t);
62
+ return this;
63
+ }
64
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Parsing of `--cue` command-line arguments.
3
+ *
4
+ * Accepted formats:
5
+ * time:2026-12-01 — one-shot deadline (ISO date or datetime)
6
+ * cron:0 9 * * 1 — recurrence
7
+ * event:file_open:src/auth/service.ts — file opened
8
+ * event:branch_switch:feature/x — branch changed
9
+ * event:error_pattern:SQLITE_(BUSY) — error pattern (may contain ':')
10
+ *
11
+ * It lives in core/ rather than cli/: the same format is typed on the command
12
+ * line and in the front-end form. One parser, tested once.
13
+ */
14
+
15
+ import type { TriggerSpec } from '../core/types.js';
16
+
17
+ export class CueArgError extends Error {}
18
+
19
+ const EVENT_TYPES = ['file_open', 'branch_switch', 'error_pattern'] as const;
20
+
21
+ export function parseCueArg(raw: string): TriggerSpec {
22
+ const input = raw.trim();
23
+ if (!input) throw new CueArgError('empty cue');
24
+
25
+ const [head, ...rest] = input.split(':');
26
+ const tail = rest.join(':'); // error patterns and ISO times contain ':'
27
+
28
+ switch (head) {
29
+ case 'time': {
30
+ if (!tail) throw new CueArgError('time: expects an ISO date — e.g. time:2026-12-01');
31
+ const date = new Date(tail);
32
+ if (Number.isNaN(date.getTime())) throw new CueArgError(`invalid date: ${tail}`);
33
+ return { kind: 'time', at: date.toISOString() };
34
+ }
35
+
36
+ case 'cron': {
37
+ if (!tail.trim()) throw new CueArgError('cron: expects an expression — e.g. "cron:0 9 * * 1"');
38
+ return { kind: 'time', cron: tail.trim() };
39
+ }
40
+
41
+ case 'event': {
42
+ const sep = tail.indexOf(':');
43
+ const type = sep === -1 ? tail : tail.slice(0, sep);
44
+ const value = sep === -1 ? '' : tail.slice(sep + 1);
45
+
46
+ if (!EVENT_TYPES.includes(type as any)) {
47
+ throw new CueArgError(`unknown event type: "${type}" (${EVENT_TYPES.join(' | ')})`);
48
+ }
49
+ if (!value) throw new CueArgError(`event:${type}: expects a value`);
50
+
51
+ switch (type) {
52
+ case 'file_open':
53
+ return { kind: 'event', type: 'file_open', path: value };
54
+ case 'branch_switch':
55
+ return { kind: 'event', type: 'branch_switch', branch: value };
56
+ default:
57
+ return { kind: 'event', type: 'error_pattern', pattern: value };
58
+ }
59
+ }
60
+
61
+ default:
62
+ throw new CueArgError(`unknown prefix: "${head}" (time | cron | event)`);
63
+ }
64
+ }
65
+
66
+ /** Renders a cue in its CLI form — the inverse of `parseCueArg`, for display. */
67
+ export function formatTriggerSpec(spec: TriggerSpec): string {
68
+ if (spec.kind === 'time') {
69
+ return spec.cron ? `cron:${spec.cron}` : `time:${spec.at}`;
70
+ }
71
+ switch (spec.type) {
72
+ case 'file_open':
73
+ return `event:file_open:${spec.path}`;
74
+ case 'branch_switch':
75
+ return `event:branch_switch:${spec.branch}`;
76
+ default:
77
+ return `event:error_pattern:${spec.pattern}`;
78
+ }
79
+ }
@@ -0,0 +1,511 @@
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
+
13
+ import { projectPath } from './project-path.js';
14
+ import type {
15
+ Cue,
16
+ Intention,
17
+ IntentionStore,
18
+ Script,
19
+ ScriptStore,
20
+ TimeTriggerSpec,
21
+ EventTriggerSpec,
22
+ } from './types.js';
23
+ import type { AppEvent, EventBus, Unsubscribe } from './event-bus.js';
24
+ import { systemClock, type Clock } from './clock.js';
25
+
26
+ export interface CueResolver {
27
+ /** Time cues due at `now` (not yet fired, or recurring and due again). */
28
+ resolveTimeCues(now?: Date): Promise<Cue[]>;
29
+ /** Event cues matching this event. */
30
+ resolveEventCues(event: AppEvent): Promise<Cue[]>;
31
+ /** Marks cue and intention as fired. Returns the woken intention. */
32
+ fire(cueId: string): Promise<Intention>;
33
+ /** Phase 8.1 — fires a script cue: the drill is surfaced, saillance bumped. */
34
+ fireScript(cueId: string): Promise<Script>;
35
+ /** Dispatches by target kind (8.1) — what bus wiring should call. */
36
+ fireAny(cueId: string): Promise<{ kind: 'intention'; intention: Intention } | { kind: 'script'; script: Script }>;
37
+ /** Expires intentions past their deadline. Returns how many. */
38
+ expireStale(now?: Date): Promise<number>;
39
+ }
40
+
41
+ // ─────────────────────────────────────────────────────────────────────────────
42
+ // Cron — minimal matcher, 5 fields (minute hour day-of-month month day-of-week)
43
+ // ─────────────────────────────────────────────────────────────────────────────
44
+
45
+ const CRON_RANGES: Array<[min: number, max: number]> = [
46
+ [0, 59], // minute
47
+ [0, 23], // heure
48
+ [1, 31], // jour du mois
49
+ [1, 12], // mois
50
+ [0, 6], // jour de la semaine, 0 = dimanche
51
+ ];
52
+
53
+ /** Expands a cron field (`*`, `5`, `1-5`, `*\/15`, `1-9/2`, lists) into a value set. */
54
+ function expandCronField(field: string, index: number): Set<number> | null {
55
+ const [min, max] = CRON_RANGES[index];
56
+ const values = new Set<number>();
57
+
58
+ for (const part of field.split(',')) {
59
+ const [rangePart, stepPart] = part.split('/');
60
+ const step = stepPart === undefined ? 1 : Number(stepPart);
61
+ if (!Number.isInteger(step) || step < 1) return null;
62
+
63
+ let lo: number;
64
+ let hi: number;
65
+
66
+ if (rangePart === '*') {
67
+ lo = min;
68
+ hi = max;
69
+ } else if (rangePart.includes('-')) {
70
+ const [a, b] = rangePart.split('-').map(Number);
71
+ if (!Number.isInteger(a) || !Number.isInteger(b)) return null;
72
+ lo = a;
73
+ hi = b;
74
+ } else {
75
+ const n = Number(rangePart);
76
+ if (!Number.isInteger(n)) return null;
77
+ lo = n;
78
+ hi = n;
79
+ }
80
+
81
+ if (lo < min || hi > max || lo > hi) return null;
82
+ for (let v = lo; v <= hi; v += step) values.add(v);
83
+ }
84
+
85
+ return values.size ? values : null;
86
+ }
87
+
88
+ interface ParsedCron {
89
+ minute: Set<number>;
90
+ hour: Set<number>;
91
+ dom: Set<number>;
92
+ month: Set<number>;
93
+ dow: Set<number>;
94
+ domRestricted: boolean;
95
+ dowRestricted: boolean;
96
+ }
97
+
98
+ /** Parses a 5-field cron expression. Returns null when it is invalid. */
99
+ export function parseCron(expr: string): ParsedCron | null {
100
+ const fields = expr.trim().split(/\s+/);
101
+ if (fields.length !== 5) return null;
102
+
103
+ const sets = fields.map((f, i) => expandCronField(f, i));
104
+ if (sets.some((s) => s === null)) return null;
105
+
106
+ const [minute, hour, dom, month, dow] = sets as Set<number>[];
107
+ return {
108
+ minute,
109
+ hour,
110
+ dom,
111
+ month,
112
+ dow,
113
+ domRestricted: fields[2] !== '*',
114
+ dowRestricted: fields[4] !== '*',
115
+ };
116
+ }
117
+
118
+ /**
119
+ * True when `date` (to the minute, in UTC) lands on a cron occurrence.
120
+ *
121
+ * When day-of-month and day-of-week are both restricted, standard cron combines
122
+ * them with OR, not AND — `0 9 1 * 1` means "the 1st of the month **or** on a
123
+ * Monday". That semantics is kept so nothing surprises anyone.
124
+ */
125
+ export function cronMatches(parsed: ParsedCron, date: Date): boolean {
126
+ if (!parsed.minute.has(date.getUTCMinutes())) return false;
127
+ if (!parsed.hour.has(date.getUTCHours())) return false;
128
+ if (!parsed.month.has(date.getUTCMonth() + 1)) return false;
129
+
130
+ const domHit = parsed.dom.has(date.getUTCDate());
131
+ const dowHit = parsed.dow.has(date.getUTCDay());
132
+
133
+ if (parsed.domRestricted && parsed.dowRestricted) return domHit || dowHit;
134
+ if (parsed.domRestricted) return domHit;
135
+ if (parsed.dowRestricted) return dowHit;
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * Cron catch-up window, in minutes (7 days).
141
+ *
142
+ * The resolver is not a daemon: it runs at SessionStart, so only now and then.
143
+ * Without catch-up, an occurrence falling between two sessions would be lost. So
144
+ * time is walked backwards minute by minute from `now` to the last known
145
+ * reference, capped by this window — beyond it, an occurrence is considered too
146
+ * old to be worth a wake-up.
147
+ */
148
+ export const CRON_CATCHUP_MINUTES = 7 * 24 * 60;
149
+
150
+ /** True when a cron occurrence exists in the half-open interval (since, now]. */
151
+ export function cronDueSince(expr: string, since: Date, now: Date): boolean {
152
+ const parsed = parseCron(expr);
153
+ if (!parsed) return false; // invalid expression: never due, never a crash
154
+
155
+ const MINUTE = 60_000;
156
+ const nowMin = Math.floor(now.getTime() / MINUTE);
157
+ const sinceMin = Math.floor(since.getTime() / MINUTE);
158
+ const floor = Math.max(sinceMin + 1, nowMin - CRON_CATCHUP_MINUTES);
159
+
160
+ for (let m = nowMin; m >= floor; m--) {
161
+ if (cronMatches(parsed, new Date(m * MINUTE))) return true;
162
+ }
163
+ return false;
164
+ }
165
+
166
+ // ─────────────────────────────────────────────────────────────────────────────
167
+ // Event matching
168
+ // ─────────────────────────────────────────────────────────────────────────────
169
+
170
+ /** Normalises separators so Windows and POSIX paths match alike. */
171
+ function normalizePath(p: string): string {
172
+ return p.replace(/\\/g, '/').replace(/^\.\//, '');
173
+ }
174
+
175
+ /**
176
+ * A cue is only eligible within its mental place: the event must come from the
177
+ * intention's `directory` or a subdirectory. Without this, a loop opened on one
178
+ * project would wake while working on another — the database is shared across
179
+ * projects.
180
+ */
181
+ function directoryMatches(intentionDir: string, eventDir: string | undefined): boolean {
182
+ if (!eventDir) return true; // event without context: no filtering
183
+ const a = projectPath(intentionDir);
184
+ const b = projectPath(eventDir);
185
+ return b === a || b.startsWith(`${a}/`) || a.startsWith(`${b}/`);
186
+ }
187
+
188
+ /**
189
+ * Hard caps on regex evaluation (SECURITY_AUDIT.md M-01). The pattern and the
190
+ * event text both come from unauthenticated callers, and the native RegExp engine
191
+ * backtracks: `^(a+)+$` against a long non-matching string pins the event loop.
192
+ * The engine cannot be given a deadline, so the inputs are bounded instead and
193
+ * the shapes that make catastrophic backtracking possible are refused outright.
194
+ */
195
+ export const MAX_PATTERN_LENGTH = 200;
196
+ export const MAX_MATCH_TEXT_LENGTH = 10_000;
197
+
198
+ /**
199
+ * Detects a quantifier applied to a group that itself contains a quantifier —
200
+ * the `(a+)+` / `(a*)*` / `(a+|b)*` family behind exponential backtracking.
201
+ * Conservative: it can reject a benign pattern, which only costs a fallback to
202
+ * literal search, never a hang.
203
+ */
204
+ export function isDangerousPattern(pattern: string): boolean {
205
+ if (pattern.length > MAX_PATTERN_LENGTH) return true;
206
+
207
+ // Walk the groups, tracking whether each holds an unescaped quantifier, and
208
+ // flag any group that is itself quantified on close.
209
+ const stack: boolean[] = [];
210
+ for (let i = 0; i < pattern.length; i++) {
211
+ const ch = pattern[i];
212
+ if (ch === '\\') {
213
+ i++; // escaped char: never a quantifier or a group delimiter
214
+ continue;
215
+ }
216
+ if (ch === '(') {
217
+ stack.push(false);
218
+ continue;
219
+ }
220
+ if (ch === ')') {
221
+ const innerHadQuantifier = stack.pop() ?? false;
222
+ const next = pattern[i + 1];
223
+ const outerQuantified = next === '+' || next === '*' || next === '{';
224
+ if (innerHadQuantifier && outerQuantified) return true;
225
+ continue;
226
+ }
227
+ if (ch === '+' || ch === '*' || ch === '{') {
228
+ if (stack.length > 0) stack[stack.length - 1] = true;
229
+ }
230
+ }
231
+ return false;
232
+ }
233
+
234
+ /**
235
+ * Tests an error pattern. A pattern that is invalid, oversized or shaped for
236
+ * catastrophic backtracking falls back to a literal, non-backtracking search.
237
+ */
238
+ function errorPatternMatches(pattern: string, text: string): boolean {
239
+ const bounded = text.length > MAX_MATCH_TEXT_LENGTH ? text.slice(0, MAX_MATCH_TEXT_LENGTH) : text;
240
+
241
+ if (isDangerousPattern(pattern)) {
242
+ return bounded.toLowerCase().includes(pattern.toLowerCase());
243
+ }
244
+ try {
245
+ return new RegExp(pattern, 'i').test(bounded);
246
+ } catch {
247
+ return bounded.toLowerCase().includes(pattern.toLowerCase());
248
+ }
249
+ }
250
+
251
+ /** True when this event trigger matches this event. */
252
+ export function eventTriggerMatches(spec: EventTriggerSpec, event: AppEvent): boolean {
253
+ switch (spec.type) {
254
+ case 'file_open': {
255
+ if (event.type !== 'file_open') return false;
256
+ const want = normalizePath(spec.path);
257
+ const got = normalizePath(event.path);
258
+ // Suffix accepted: a cue armed on 'src/auth/service.ts' must match an event
259
+ // carrying the absolute path of the same file.
260
+ return got === want || got.endsWith(`/${want}`);
261
+ }
262
+ case 'branch_switch':
263
+ return event.type === 'branch_switch' && event.branch === spec.branch;
264
+ case 'error_pattern':
265
+ return event.type === 'error_pattern' && errorPatternMatches(spec.pattern, event.text);
266
+ default:
267
+ return false;
268
+ }
269
+ }
270
+
271
+ // ─────────────────────────────────────────────────────────────────────────────
272
+ // Short loop identity
273
+ // ─────────────────────────────────────────────────────────────────────────────
274
+
275
+ /** Length of the UUID prefix used as a readable loop identifier. */
276
+ export const LOOP_ID_LENGTH = 8;
277
+
278
+ /**
279
+ * Short identifier shown to the agent: `loop-a1b2c3d4`. This is what a human
280
+ * retypes into a commit message (`Closes loop-a1b2c3d4`) — a full UUID would
281
+ * never be retyped by hand.
282
+ */
283
+ export function loopId(intentionId: string): string {
284
+ return `loop-${intentionId.slice(0, LOOP_ID_LENGTH)}`;
285
+ }
286
+
287
+ /** Extracts short loop ids mentioned in a text (a commit message). */
288
+ export function extractLoopIds(text: string): string[] {
289
+ const found = new Set<string>();
290
+ for (const m of text.matchAll(/\bloop-([0-9a-f]{4,36})\b/gi)) {
291
+ found.add(m[1].toLowerCase());
292
+ }
293
+ return [...found];
294
+ }
295
+
296
+ /** Finds the intention a short id points to, when it is unambiguous. */
297
+ export function matchIntentionByShortId(
298
+ intentions: Intention[],
299
+ shortId: string
300
+ ): Intention | null {
301
+ const needle = shortId.toLowerCase();
302
+ const hits = intentions.filter((i) => i.id.toLowerCase().startsWith(needle));
303
+ // An ambiguous prefix closes nothing: better to do nothing than close the wrong loop.
304
+ return hits.length === 1 ? hits[0] : null;
305
+ }
306
+
307
+ // ─────────────────────────────────────────────────────────────────────────────
308
+ // Decay rules for intentions
309
+ // ─────────────────────────────────────────────────────────────────────────────
310
+
311
+ /** Salience decline of a fired intention, in points per day (the Zeigarnik pull fading). */
312
+ export const INTENTION_FADE_PER_DAY = 10;
313
+
314
+ /**
315
+ * Current salience of an intention (PHASE5_PLAN.md § 5.2):
316
+ * - `armed` → pinned at 100: an open loop stays salient, it does not decay
317
+ * - `fired` and not `closed` → declines from `firedAt`: the Zeigarnik pull fades
318
+ * - `closed` → 0: archived, kept for history
319
+ * - `expired` → 0: soft-deleted
320
+ */
321
+ export function intentionSaillance(intention: Intention, now: Date): number {
322
+ switch (intention.status) {
323
+ case 'armed':
324
+ return 100;
325
+ case 'closed':
326
+ case 'expired':
327
+ return 0;
328
+ case 'fired': {
329
+ if (!intention.firedAt) return intention.saillance;
330
+ const days = (now.getTime() - intention.firedAt.getTime()) / 86_400_000;
331
+ return Math.max(0, Math.round(100 - days * INTENTION_FADE_PER_DAY));
332
+ }
333
+ }
334
+ }
335
+
336
+ // ─────────────────────────────────────────────────────────────────────────────
337
+ // Resolver
338
+ // ─────────────────────────────────────────────────────────────────────────────
339
+
340
+ export interface CueResolverOptions {
341
+ clock?: Clock;
342
+ }
343
+
344
+ export class SqliteCueResolver implements CueResolver {
345
+ private clock: Clock;
346
+
347
+ constructor(
348
+ private store: IntentionStore & Partial<ScriptStore>,
349
+ options: CueResolverOptions = {}
350
+ ) {
351
+ this.clock = options.clock ?? systemClock;
352
+ }
353
+
354
+ /**
355
+ * A cue only wakes while its target is live: an intention still `armed`, a
356
+ * script still `active` (8.1 — drafts never fire). Returns the target's
357
+ * directory for mental-place filtering, or null when the target is dead.
358
+ */
359
+ private async liveTargetDirectoryOf(cue: Cue): Promise<string | null> {
360
+ if (cue.targetKind === 'script') {
361
+ const script = this.store.getScript ? await this.store.getScript(cue.targetId) : null;
362
+ return script && script.status === 'active' ? script.directory : null;
363
+ }
364
+ const intention = await this.store.getIntention(cue.targetId);
365
+ const recurring = cue.triggerSpec.kind === 'time' && Boolean(cue.triggerSpec.cron);
366
+ return intention && (intention.status === 'armed' || (recurring && intention.status === 'fired'))
367
+ ? intention.directory : null;
368
+ }
369
+
370
+ async resolveTimeCues(now: Date = this.clock.now()): Promise<Cue[]> {
371
+ const due: Cue[] = [];
372
+
373
+ for await (const cue of this.armedCues('time')) {
374
+ const spec = cue.triggerSpec as TimeTriggerSpec;
375
+ if (spec.kind !== 'time') continue;
376
+
377
+ let isDue = false;
378
+ if (spec.at) {
379
+ const at = new Date(spec.at);
380
+ isDue = !Number.isNaN(at.getTime()) && at.getTime() <= now.getTime();
381
+ } else if (spec.cron) {
382
+ // Reference: the last known wake-up, otherwise the arming time.
383
+ isDue = cronDueSince(spec.cron, cue.firedAt ?? cue.armedAt, now);
384
+ }
385
+
386
+ if (!isDue) continue;
387
+ if (!(await this.liveTargetDirectoryOf(cue))) continue;
388
+ due.push(cue);
389
+ }
390
+
391
+ return due;
392
+ }
393
+
394
+ async resolveEventCues(event: AppEvent): Promise<Cue[]> {
395
+ // A commit does not wake an intention, it closes one — that is the
396
+ // post-commit hook's job (S5-03b), not this resolver's.
397
+ if (event.type === 'commit') return [];
398
+
399
+ const matched: Cue[] = [];
400
+
401
+ for await (const cue of this.armedCues('event')) {
402
+ const spec = cue.triggerSpec as EventTriggerSpec;
403
+ if (spec.kind !== 'event') continue;
404
+ if (!eventTriggerMatches(spec, event)) continue;
405
+
406
+ const directory = await this.liveTargetDirectoryOf(cue);
407
+ if (!directory) continue;
408
+ if (!directoryMatches(directory, (event as any).directory)) continue;
409
+
410
+ matched.push(cue);
411
+ }
412
+
413
+ return matched;
414
+ }
415
+
416
+ private async *armedCues(kind: 'time' | 'event'): AsyncGenerator<Cue> {
417
+ let afterId = '';
418
+ while (true) {
419
+ const page = await this.store.listCues({ status: 'armed', kind, limit: 500, afterId });
420
+ for (const cue of page) yield cue;
421
+ if (page.length < 500) return;
422
+ afterId = page[page.length - 1].id;
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Marks cue and intention as fired. A cron cue is re-armed after firing: a
428
+ * recurrence that does not re-arm is a one-shot in disguise.
429
+ */
430
+ async fire(cueId: string): Promise<Intention> {
431
+ const cue = await this.store.getCue(cueId);
432
+ if (!cue) throw new Error(`Cue ${cueId} not found`);
433
+ if (cue.targetKind !== 'intention') throw new Error(`Cue ${cueId} arms a script — use fireScript`);
434
+
435
+ const spec = cue.triggerSpec as TimeTriggerSpec;
436
+ const recurring = spec.kind === 'time' && Boolean(spec.cron);
437
+
438
+ await this.store.markCueFired(cueId, { rearm: recurring });
439
+ return this.store.updateIntentionStatus(cue.targetId, 'fired');
440
+ }
441
+
442
+ /** Script counterpart of fire(): same cue bookkeeping, script bumped (8.1). */
443
+ async fireScript(cueId: string): Promise<Script> {
444
+ const cue = await this.store.getCue(cueId);
445
+ if (!cue) throw new Error(`Cue ${cueId} not found`);
446
+ if (cue.targetKind !== 'script') throw new Error(`Cue ${cueId} arms an intention — use fire`);
447
+ if (!this.store.markScriptFired) throw new Error('Store has no ScriptStore support');
448
+
449
+ const spec = cue.triggerSpec as TimeTriggerSpec;
450
+ const recurring = spec.kind === 'time' && Boolean(spec.cron);
451
+
452
+ await this.store.markCueFired(cueId, { rearm: recurring });
453
+ return this.store.markScriptFired(cue.targetId);
454
+ }
455
+
456
+ async fireAny(
457
+ cueId: string
458
+ ): Promise<{ kind: 'intention'; intention: Intention } | { kind: 'script'; script: Script }> {
459
+ const cue = await this.store.getCue(cueId);
460
+ if (!cue) throw new Error(`Cue ${cueId} not found`);
461
+ if (cue.targetKind === 'script') return { kind: 'script', script: await this.fireScript(cueId) };
462
+ return { kind: 'intention', intention: await this.fire(cueId) };
463
+ }
464
+
465
+ /**
466
+ * Expires `armed` intentions whose `expiresAt` has passed and cancels their
467
+ * cues — a cue outliving its intention is a ghost wake-up.
468
+ */
469
+ async expireStale(now: Date = this.clock.now()): Promise<number> {
470
+ const armed = await this.store.listIntentions({ status: 'armed', limit: 500 });
471
+ let expired = 0;
472
+
473
+ for (const intention of armed) {
474
+ if (!intention.expiresAt || intention.expiresAt.getTime() > now.getTime()) continue;
475
+
476
+ await this.store.updateIntentionStatus(intention.id, 'expired');
477
+ for (const cue of await this.store.listCues({ intentionId: intention.id, status: 'armed' })) {
478
+ await this.store.updateCueStatus(cue.id, 'cancelled');
479
+ }
480
+ expired++;
481
+ }
482
+
483
+ return expired;
484
+ }
485
+ }
486
+
487
+ /**
488
+ * Wires a resolver onto an event bus: every published event wakes the cues that
489
+ * match. Returns the unsubscribe handle.
490
+ *
491
+ * ```ts
492
+ * const detach = attachResolverToBus(bus, resolver);
493
+ * await bus.publish({ type: 'branch_switch', branch: 'feature/x', directory: '/src' });
494
+ * ```
495
+ */
496
+ export function attachResolverToBus(
497
+ bus: EventBus,
498
+ resolver: CueResolver,
499
+ options: {
500
+ onFired?: (intention: Intention, cue: Cue) => void | Promise<void>;
501
+ onScriptFired?: (script: Script, cue: Cue) => void | Promise<void>;
502
+ } = {}
503
+ ): Unsubscribe {
504
+ return bus.subscribeAll(async (event) => {
505
+ for (const cue of await resolver.resolveEventCues(event)) {
506
+ const fired = await resolver.fireAny(cue.id);
507
+ if (fired.kind === 'script') await options.onScriptFired?.(fired.script, cue);
508
+ else await options.onFired?.(fired.intention, cue);
509
+ }
510
+ });
511
+ }