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,393 @@
1
+ /**
2
+ * Memory decay levels.
3
+ * 0 = full detail (fresh)
4
+ * 1 = summary (days)
5
+ * 2 = gist (weeks)
6
+ * 3 = keywords (months)
7
+ * 4 = lost / merged
8
+ */
9
+ export type DecayLevel = 0 | 1 | 2 | 3 | 4;
10
+
11
+ /** Injection contract shared with browser-safe store interfaces. */
12
+ export interface LLMClient {
13
+ messages: {
14
+ create(params: any): Promise<{ content: Array<{ type: string; text?: string }> }>;
15
+ };
16
+ }
17
+
18
+ /**
19
+ * Memory types (cognitive neuroscience).
20
+ * - Episodic: lived events, with their temporal and spatial context
21
+ * - Semantic: facts and concepts
22
+ * - Procedural: know-how, gestures, routines
23
+ */
24
+ export type MemoryType = 'episodic' | 'semantic' | 'procedural';
25
+
26
+ export interface Memory {
27
+ id: string;
28
+ content: string; // Level 0 (full detail)
29
+ level1Summary?: string; // Level 1 (summary)
30
+ level2Essential?: string; // Level 2 (gist)
31
+ level3Keywords?: string; // Level 3 (keywords for BM25)
32
+
33
+ // Lightweight metadata
34
+ directory: string; // Project / source
35
+ day: string; // YYYY-MM-DD
36
+ keywords: string[]; // Tagged keywords
37
+ sessionId: string; // Working session
38
+ memoryType: MemoryType; // Memory type
39
+
40
+ // Lifecycle
41
+ createdAt: Date;
42
+ lastRecalled?: Date;
43
+ recallCount: number; // How many times it was recalled
44
+
45
+ // Decay
46
+ decayRate: number; // 0.0 (slow) to 1.0 (fast)
47
+ currentLevel: DecayLevel; // Current decay level
48
+ saillance: number; // Score 0-100
49
+
50
+ // Merging
51
+ mergedIntoId?: string; // Id of the trace it was merged into (level 4)
52
+
53
+ // Photographic mode — disables decay
54
+ photographic?: boolean;
55
+
56
+ // ── Phase 6 trust layer (populated from 6.0.1 onward) ──
57
+ source?: TraceSource; // who wrote it; undefined on pre-Phase-6 rows
58
+ agent?: string; // claude | codex | kimi | opencode | unknown
59
+ verified?: boolean;
60
+ verificationReason?: VerificationReason;
61
+ device?: string; // encoding device (localization now, sync later)
62
+ refutedCount?: number;
63
+ }
64
+
65
+ export type TraceSource = 'human' | 'agent' | 'hook' | 'llm_generated' | 'dream_proposal';
66
+
67
+ export type VerificationReason = 'corroborated' | 'grounded' | 'reused' | 'human';
68
+
69
+ export interface SearchQuery {
70
+ query: string;
71
+ directory?: string;
72
+ sessionId?: string;
73
+ maxLevel?: DecayLevel; // Highest decay level to include
74
+ limit?: number;
75
+ // Enriched filters
76
+ memoryType?: MemoryType;
77
+ dateFrom?: Date; // Filter: createdAt >= dateFrom
78
+ dateTo?: Date; // Filter: createdAt <= dateTo
79
+ minSaillance?: number; // Filter: saillance >= minSaillance
80
+ minRecalls?: number; // Filter: recallCount >= minRecalls
81
+ }
82
+
83
+ export interface SearchResult {
84
+ memory: Memory;
85
+ matchLevel: DecayLevel; // Level at which the match was found
86
+ score: number; // Relevance score
87
+ }
88
+
89
+ export interface MergeResult {
90
+ source: Memory;
91
+ target: Memory;
92
+ mergedContent?: string;
93
+ }
94
+
95
+ // ─────────────────────────────────────────────────────────────────────────────
96
+ // Trust layer (Phase 6.0.2) — contradictions
97
+ //
98
+ // A contradiction collapses the loser's saillance and excludes it from the
99
+ // SessionStart block, but never deletes it: human forgetting keeps the
100
+ // "ghosted" memory; humemory should too.
101
+ // ─────────────────────────────────────────────────────────────────────────────
102
+
103
+ export interface Contradiction {
104
+ id: string;
105
+ winnerId: string;
106
+ loserId: string;
107
+ /**
108
+ * Phase 8 — the loser can be a script as well as a memory ("correction
109
+ * kills the script", PHASE8_PLAN.md §8.4). The winner is always a memory:
110
+ * nothing in the domain corrects a fact *into* becoming a script, only the
111
+ * other way round. Absent on rows written before this field existed —
112
+ * treat as `'memory'`.
113
+ */
114
+ loserKind?: 'memory' | 'script';
115
+ reason?: string;
116
+ createdAt: Date;
117
+ createdBy: 'agent' | 'human' | 'dreamer';
118
+ agent?: string;
119
+ status: 'active' | 'revoked';
120
+ }
121
+
122
+ export interface ContradictResult {
123
+ contradiction?: Contradiction;
124
+ /** Set when authority was asymmetric: a proposal was filed instead. */
125
+ proposalFiled?: boolean;
126
+ /** Set when the loser was already merged — the collapse hit the merge target. */
127
+ retargetedTo?: string;
128
+ loser: Memory | Script;
129
+ }
130
+
131
+ // ─────────────────────────────────────────────────────────────────────────────
132
+ // Dreaming (Phase 6.1) — cross-session consolidation
133
+ //
134
+ // The dreamer detects recurring patterns across sessions and agents, then
135
+ // *proposes*. Nothing touches `memories` or AGENTS.md without explicit human
136
+ // approval.
137
+ // ─────────────────────────────────────────────────────────────────────────────
138
+
139
+ export type DreamKind =
140
+ | 'promote_semantic'
141
+ | 'merge_cluster'
142
+ | 'update_agents_md'
143
+ | 'contradiction'
144
+ | 'close_stale_loop'
145
+ | 'script_archived'
146
+ | 'script_candidate';
147
+
148
+ export type DreamStatus = 'pending' | 'approved' | 'rejected' | 'expired';
149
+
150
+ export interface DreamProposal {
151
+ id: string;
152
+ kind: DreamKind;
153
+ payload: string; // JSON: cluster ids, drafted consolidated content
154
+ payloadHash: string; // stable hash of sorted cluster ids + kind → idempotent
155
+ status: DreamStatus;
156
+ confidence: number; // 0..1, cluster size × mean baseTrust
157
+ createdAt: Date;
158
+ expiresAt?: Date;
159
+ resolvedAt?: Date;
160
+ resolvedBy?: string;
161
+ }
162
+
163
+ // ─────────────────────────────────────────────────────────────────────────────
164
+ // Prospective memory (Phase 5) — intentions and cues
165
+ //
166
+ // An `Intention` is an open loop: "tomorrow, refactor fn X". You do not search
167
+ // for it, it comes back — carried by one or more `Cue`s armed on time or on an
168
+ // event. Zeigarnik effect: while `armed` its salience stays pinned at 100; once
169
+ // `fired` and not `closed`, it starts declining like an ordinary trace.
170
+ // See PHASE5_PLAN.md § 5.1.
171
+ // ─────────────────────────────────────────────────────────────────────────────
172
+
173
+ /** armed = waiting · fired = surfaced to the agent · closed = done · expired = past its deadline. */
174
+ export type IntentionStatus = 'armed' | 'fired' | 'closed' | 'expired';
175
+
176
+ export type CueStatus = 'armed' | 'fired' | 'cancelled';
177
+
178
+ export type CueKind = 'time' | 'event';
179
+
180
+ /** Time trigger: either a one-shot date (`at`) or a recurrence (`cron`). */
181
+ export interface TimeTriggerSpec {
182
+ kind: 'time';
183
+ at?: string; // ISO datetime
184
+ cron?: string; // expression cron 5 champs
185
+ }
186
+
187
+ /**
188
+ * Event trigger. No `commit` variant here, on purpose: a commit does not wake an
189
+ * intention, it *closes* one — that is the post-commit hook's job (S5-03b), not
190
+ * the cue resolver's.
191
+ */
192
+ export type EventTriggerSpec =
193
+ | { kind: 'event'; type: 'file_open'; path: string }
194
+ | { kind: 'event'; type: 'branch_switch'; branch: string }
195
+ | { kind: 'event'; type: 'error_pattern'; pattern: string };
196
+
197
+ export type TriggerSpec = TimeTriggerSpec | EventTriggerSpec;
198
+
199
+ export interface Intention {
200
+ id: string;
201
+ content: string;
202
+ directory: string; // mental place
203
+ createdAt: Date;
204
+ expiresAt?: Date; // an intention without a deadline is undefined
205
+ status: IntentionStatus;
206
+ firedAt?: Date;
207
+ closedAt?: Date;
208
+ closedByCommit?: string; // SHA of the commit that closed the loop
209
+ saillance: number; // pinned at 100 while armed
210
+ relatedMemoryId?: string; // optional link to a retrospective trace
211
+
212
+ // ── Phase 6 trust layer (gap 8: loops carry provenance too) ──
213
+ source?: TraceSource;
214
+ agent?: string;
215
+ verified?: boolean;
216
+ verificationReason?: VerificationReason;
217
+ device?: string;
218
+ }
219
+
220
+ export interface Cue {
221
+ id: string;
222
+ /** Phase 8: a cue can arm an intention OR a script. */
223
+ targetKind: CueTargetKind;
224
+ /** Id of the target (intention or script) this cue arms. */
225
+ targetId: string;
226
+ /**
227
+ * @deprecated Compat alias for Phase 5 consumers — equals `targetId`.
228
+ * Intention-only consumers must check `targetKind === 'intention'` first.
229
+ */
230
+ intentionId: string;
231
+ kind: CueKind;
232
+ triggerSpec: TriggerSpec;
233
+ status: CueStatus;
234
+ armedAt: Date;
235
+ firedAt?: Date;
236
+ }
237
+
238
+ export type CueTargetKind = 'intention' | 'script';
239
+
240
+ /** Write shape for an intention: the store sets id/createdAt/status/saillance. */
241
+ export type NewIntention = Omit<
242
+ Intention,
243
+ 'id' | 'createdAt' | 'status' | 'saillance' | 'firedAt' | 'closedAt' | 'closedByCommit'
244
+ > & {
245
+ status?: IntentionStatus;
246
+ saillance?: number;
247
+ };
248
+
249
+ /** Write shape for a cue: the store sets id/armedAt/status and derives `kind` from the spec. */
250
+ export type NewCue = {
251
+ intentionId: string;
252
+ triggerSpec: TriggerSpec;
253
+ status?: CueStatus;
254
+ };
255
+
256
+ export interface IntentionStore {
257
+ addIntention(intention: NewIntention, cues?: TriggerSpec[]): Promise<Intention>;
258
+ getIntention(id: string): Promise<Intention | null>;
259
+ listIntentions(options?: {
260
+ status?: IntentionStatus | IntentionStatus[];
261
+ directory?: string;
262
+ limit?: number;
263
+ }): Promise<Intention[]>;
264
+ updateIntentionStatus(
265
+ id: string,
266
+ status: IntentionStatus,
267
+ options?: { closedByCommit?: string }
268
+ ): Promise<Intention>;
269
+ deleteIntention(id: string): Promise<void>;
270
+
271
+ addCue(cue: NewCue): Promise<Cue>;
272
+ getCue(id: string): Promise<Cue | null>;
273
+ listCues(options?: {
274
+ afterId?: string;
275
+ intentionId?: string;
276
+ targetKind?: CueTargetKind;
277
+ targetId?: string;
278
+ status?: CueStatus | CueStatus[];
279
+ kind?: CueKind;
280
+ limit?: number;
281
+ }): Promise<Cue[]>;
282
+ updateCueStatus(id: string, status: CueStatus): Promise<Cue>;
283
+ /** Records a firing. `rearm` keeps the cue `armed` (recurring cues). */
284
+ markCueFired(id: string, options?: { rearm?: boolean }): Promise<Cue>;
285
+ }
286
+
287
+ // ─────────────────────────────────────────────────────────────────────────────
288
+ // Phase 8.1 — Cognitive scripts (Schank & Abelson drills). A script is not an
289
+ // intention: an intention is ONE marker ("pense à X"), a script is an ORDERED
290
+ // procedure ("fais A, puis B, vérifie C") that fires on a cue and decays on
291
+ // DISUSE — the inverse Zeigarnik (PHASE8_PLAN.md § 8.4).
292
+ // ─────────────────────────────────────────────────────────────────────────────
293
+
294
+ /** draft = proposed, never fires · active = resolves through cues · archived = searchable only. */
295
+ export type ScriptStatus = 'draft' | 'active' | 'archived';
296
+
297
+ export interface Script {
298
+ id: string;
299
+ name: string; // 'release-check', unique per directory
300
+ description: string; // one line, shown in the context block header
301
+ steps: string[]; // ordered drill steps — plain strings, execution stays with the agent
302
+ directory: string; // mental place, same cue filtering as intentions
303
+ status: ScriptStatus;
304
+ /** Fire-bumped saillance; effective value deducts disuse decay (8.4 sweep). */
305
+ saillance: number;
306
+ fireCount: number;
307
+ lastFiredAt?: Date;
308
+ /** Pinned = photographic equivalent: exempt from disuse decay. */
309
+ pinned: boolean;
310
+ // ── Trust layer (8.3): same provenance shape as intentions (6.0.1) ──
311
+ source?: TraceSource;
312
+ agent?: string;
313
+ device?: string;
314
+ createdAt: Date;
315
+ updatedAt: Date;
316
+ }
317
+
318
+ /** Write shape for a script: the store sets id/status/saillance/fireCount/timestamps. */
319
+ export type NewScript = Omit<
320
+ Script,
321
+ 'id' | 'status' | 'saillance' | 'fireCount' | 'lastFiredAt' | 'createdAt' | 'updatedAt'
322
+ > & {
323
+ status?: ScriptStatus;
324
+ saillance?: number;
325
+ };
326
+
327
+ export interface ScriptStore {
328
+ addScript(script: NewScript, cues?: TriggerSpec[]): Promise<Script>;
329
+ getScript(id: string): Promise<Script | null>;
330
+ /** Name lookup, unique per directory — the CLI and the dreamer both address drills by name. */
331
+ getScriptByName(name: string, directory: string): Promise<Script | null>;
332
+ listScripts(options?: {
333
+ status?: ScriptStatus | ScriptStatus[];
334
+ directory?: string;
335
+ limit?: number;
336
+ }): Promise<Script[]>;
337
+ updateScriptStatus(id: string, status: ScriptStatus): Promise<Script>;
338
+ updateScript(
339
+ id: string,
340
+ patch: { name?: string; description?: string; steps?: string[]; pinned?: boolean }
341
+ ): Promise<Script>;
342
+ /** Firing bumps fireCount, lastFiredAt and saillance (+5, capped 100). */
343
+ markScriptFired(id: string): Promise<Script>;
344
+ deleteScript(id: string): Promise<void>; // also cancels its armed cues
345
+ }
346
+
347
+ export interface MemoryStore {
348
+ add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'>, options?: { autoGenerate?: boolean }): Promise<Memory>;
349
+ getById(id: string): Promise<Memory | null>;
350
+ search(query: SearchQuery): Promise<SearchResult[]>;
351
+ /**
352
+ * `agent` (Phase 6.0.1): who is recalling. A recall by a *different* agent
353
+ * than the writer earns the trace the `reused` verification.
354
+ */
355
+ /**
356
+ * Reinforce a trace. `agent` is attribution; `identityTrusted` says whether
357
+ * that attribution is a process-level fact (MCP stdio, CLI) or a request
358
+ * claiming one (HTTP header). Only the former can earn `reused` verification.
359
+ */
360
+ recall(id: string, agent?: string, options?: { identityTrusted?: boolean }): Promise<Memory>;
361
+ updateDecay(): Promise<void>;
362
+ delete(id: string): Promise<void>;
363
+ list(options?: {
364
+ limit?: number;
365
+ level?: DecayLevel;
366
+ levels?: DecayLevel[];
367
+ type?: MemoryType;
368
+ directory?: string;
369
+ minSaillance?: number;
370
+ }): Promise<Memory[]>;
371
+ findSimilar(id: string, options?: { limit?: number; threshold?: number }): Promise<SearchResult[]>;
372
+ merge(sourceId: string, targetId: string, options?: { autoMergeContent?: boolean; client?: LLMClient }): Promise<MergeResult>;
373
+ setPhotographic(id: string, value: boolean): Promise<Memory>;
374
+ /** Phase 6.0.1 — human override verification; automatic paths set the flag directly. */
375
+ verify?(id: string, by?: string): Promise<Memory>;
376
+ /** Phase 6.0.1 — negative signal: refuted_count +1 and verification revoked. */
377
+ refute?(id: string, reason?: string): Promise<Memory>;
378
+ /** Phase 6.0.4 — revert a merge: resurrect the source, restore the target's revised levels. */
379
+ unmerge?(sourceId: string): Promise<{ source: Memory; target: Memory }>;
380
+ /** Phase 6.0.2 — `id` contradicts `otherId`. Tiered authority keyed on verification_reason. */
381
+ contradict?(winnerId: string, loserId: string, options?: { reason?: string; createdBy?: 'agent' | 'human' | 'dreamer'; agent?: string }): Promise<ContradictResult>;
382
+ /** Phase 6.0.2 — revoke: the loser's saillance is recomputed, not literally restored. */
383
+ revokeContradiction?(id: string): Promise<Contradiction>;
384
+ /** Phase 6.0.2 — active (or all) contradictions, for the context block and audits. */
385
+ listContradictions?(options?: { loserId?: string; status?: 'active' | 'revoked' }): Promise<Contradiction[]>;
386
+ /** Phase 6.1 — dream proposals: list (default pending, non-expired) and resolve. */
387
+ listDreamProposals?(options?: { status?: DreamStatus; includeExpired?: boolean }): Promise<DreamProposal[]>;
388
+ resolveDreamProposal?(id: string, status: 'approved' | 'rejected', resolvedBy?: string): Promise<DreamProposal>;
389
+ /** Phase 6.1 — insert a proposal, deduped by (kind, payload_hash). Returns false if it already existed. */
390
+ fileDreamProposal?(p: { kind: DreamKind; payload: string; payloadHash: string; confidence?: number; expiresAt?: Date }): Promise<boolean>;
391
+ /** Phase 6.1 — mark pending proposals past their expires_at as expired. Returns the count. */
392
+ expireDreamProposals?(): Promise<number>;
393
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * VectorClusterer — Phase 7.3.
3
+ *
4
+ * Same union-find shape as KeywordClusterer, on cosine similarity over stored
5
+ * embeddings instead of Jaccard over tokens. Missing embeddings are embedded
6
+ * on the spot BY THE BATCH JOB (A3 — this class only ever runs inside
7
+ * `pnpm dream` / backfill, never on the add() path).
8
+ *
9
+ * Implements `ScoredClusterer`: the dreamer needs the cluster's minimum
10
+ * pairwise similarity to gate `corroborated` verification on the STRICTER
11
+ * threshold (A1). Grouping tolerates noise — a human reviews proposals;
12
+ * verification does not — nobody reviews it.
13
+ */
14
+
15
+ import type { Memory } from './types.js';
16
+ import { DREAM_CONFIG, type Clusterer } from './dreamer.js';
17
+ import { cosine, embeddableText, type Embedder } from './embeddings.js';
18
+
19
+ export interface ScoredCluster {
20
+ members: Memory[];
21
+ /** Weakest link that holds the cluster together. */
22
+ minPairwiseSimilarity: number;
23
+ }
24
+
25
+ export interface ScoredClusterer extends Clusterer {
26
+ clusterWithScores(memories: Memory[]): Promise<ScoredCluster[]>;
27
+ }
28
+
29
+ /** Type guard — the dreamer uses scores when the clusterer provides them. */
30
+ export function hasScores(c: Clusterer): c is ScoredClusterer {
31
+ return typeof (c as ScoredClusterer).clusterWithScores === 'function';
32
+ }
33
+
34
+ export interface EmbeddingStore {
35
+ getEmbedding(memoryId: string): Promise<{ modelId: string; embedding: Float32Array } | null>;
36
+ setEmbedding(memoryId: string, modelId: string, embedding: Float32Array): Promise<void>;
37
+ }
38
+
39
+ export class VectorClusterer implements ScoredClusterer {
40
+ constructor(
41
+ private embedder: Embedder,
42
+ private store: EmbeddingStore,
43
+ /**
44
+ * Default: the embedder's calibrated per-model threshold
45
+ * (OnnxEmbedder.suggestedClusterThreshold — 7.5 round 4), falling back to
46
+ * DREAM_CONFIG for embedders without calibration (e.g. HashEmbedder in tests).
47
+ */
48
+ private threshold: number = (embedder as { suggestedClusterThreshold?: number })
49
+ .suggestedClusterThreshold ?? DREAM_CONFIG.vectorClusterThreshold
50
+ ) {}
51
+
52
+ private async embeddingsFor(memories: Memory[]): Promise<Float32Array[]> {
53
+ const missing: { index: number; text: string }[] = [];
54
+ const out: (Float32Array | null)[] = [];
55
+
56
+ for (let i = 0; i < memories.length; i++) {
57
+ const row = await this.store.getEmbedding(memories[i].id);
58
+ if (row && row.modelId === this.embedder.modelId) {
59
+ out.push(row.embedding);
60
+ } else {
61
+ out.push(null);
62
+ missing.push({ index: i, text: embeddableText(memories[i]) });
63
+ }
64
+ }
65
+
66
+ if (missing.length) {
67
+ // One batched model call for everything missing (A3: we are in a batch job).
68
+ const fresh = await this.embedder.embed(missing.map((m) => m.text));
69
+ for (let k = 0; k < missing.length; k++) {
70
+ out[missing[k].index] = fresh[k];
71
+ await this.store.setEmbedding(memories[missing[k].index].id, this.embedder.modelId, fresh[k]);
72
+ }
73
+ }
74
+
75
+ return out as Float32Array[];
76
+ }
77
+
78
+ async clusterWithScores(memories: Memory[]): Promise<ScoredCluster[]> {
79
+ if (memories.length < 2) return [];
80
+ const vectors = await this.embeddingsFor(memories);
81
+
82
+ const parent = memories.map((_, i) => i);
83
+ const find = (i: number): number => {
84
+ while (parent[i] !== i) {
85
+ parent[i] = parent[parent[i]];
86
+ i = parent[i];
87
+ }
88
+ return i;
89
+ };
90
+ // Track the weakest accepted link per union — that is the cluster's
91
+ // minPairwiseSimilarity once grouping settles.
92
+ const sims = new Map<string, number>();
93
+ for (let i = 0; i < memories.length; i++) {
94
+ for (let j = i + 1; j < memories.length; j++) {
95
+ const s = cosine(vectors[i], vectors[j]);
96
+ if (s >= this.threshold) {
97
+ sims.set(`${i}:${j}`, s);
98
+ const ri = find(i);
99
+ const rj = find(j);
100
+ if (ri !== rj) parent[rj] = ri;
101
+ }
102
+ }
103
+ }
104
+
105
+ const groups = new Map<number, number[]>();
106
+ memories.forEach((_, i) => {
107
+ const root = find(i);
108
+ if (!groups.has(root)) groups.set(root, []);
109
+ groups.get(root)!.push(i);
110
+ });
111
+
112
+ const clusters: ScoredCluster[] = [];
113
+ for (const idxs of groups.values()) {
114
+ if (idxs.length < 2) continue;
115
+ let min = 1;
116
+ for (let a = 0; a < idxs.length; a++) {
117
+ for (let b = a + 1; b < idxs.length; b++) {
118
+ const key = `${Math.min(idxs[a], idxs[b])}:${Math.max(idxs[a], idxs[b])}`;
119
+ const s = sims.get(key) ?? cosine(vectors[idxs[a]], vectors[idxs[b]]);
120
+ if (s < min) min = s;
121
+ }
122
+ }
123
+ clusters.push({ members: idxs.map((i) => memories[i]), minPairwiseSimilarity: min });
124
+ }
125
+ return clusters;
126
+ }
127
+
128
+ async cluster(memories: Memory[]): Promise<Memory[][]> {
129
+ return (await this.clusterWithScores(memories)).map((c) => c.members);
130
+ }
131
+ }
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * humemory — Human-like memory system
3
+ *
4
+ * Stores memories with progressive decay and inverse search
5
+ * (degraded layers first, escalating to full detail)
6
+ */
7
+
8
+ export { SQLiteStore } from './store/sqlite.js';
9
+ export { InverseSearchEngine } from './core/search.js';
10
+ export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
11
+ export { generateMemoryLevels, generateMemoryLevelsDeterministic, setLLMClient } from './core/llm-generator.js';
12
+ export { systemClock, FakeClock } from './core/clock.js';
13
+ export { InMemoryEventBus } from './core/event-bus.js';
14
+ export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
15
+ export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
16
+ export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
17
+ export { processSession } from './agent/claude-hook.js';
18
+ export { parseClaudeHookPayload } from './agent/session-parser.js';
19
+ export { parseKimiSession } from './agent/kimi-session-parser.js';
20
+ export { importKimiSessions, defaultKimiHome, KIMI_SOURCE } from './agent/kimi-import.js';
21
+ export { parseOpenCodeExport } from './agent/opencode-session-parser.js';
22
+ export { importOpenCodeSessions, defaultOpenCodeCommand, OPENCODE_SOURCE } from './agent/opencode-import.js';
23
+ export { setupHumemoryMcpClients } from './agent/mcp-client-setup.js';
24
+ export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
25
+ export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
26
+ export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
27
+ export type { Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MergeResult,
28
+ Intention, Cue, IntentionStatus, CueStatus, CueKind, TriggerSpec, TimeTriggerSpec, EventTriggerSpec,
29
+ NewIntention, NewCue, IntentionStore } from './core/types.js';
30
+ export type { StoreOptions } from './store/sqlite.js';
31
+ export type { Clock } from './core/clock.js';
32
+ export type { CueResolver, CueResolverOptions } from './core/cues.js';
33
+ export type { SessionContext, SessionContextOptions } from './agent/session-context.js';
34
+ export type { AppEvent, AppEventType, AppEventOf, EventBus, EventHandler, Unsubscribe } from './core/event-bus.js';
35
+ export type { GeneratedLevels, LLMClient } from './core/llm-generator.js';
36
+ export type { ParsedSession, SessionMessage } from './agent/session-parser.js';
37
+ export type { ExtractedLearning } from './agent/learning-extractor.js';
38
+ export type { HookOptions, HookResult } from './agent/claude-hook.js';
39
+ export type { MaintenanceJob, EnqueueOptions, QueueResult, WorkerOptions, WorkerResult } from './agent/maintenance-queue.js';
40
+ export type { AgentSourceDefinition, AgentSourceId, DiscoveredAgentSource, DiscoveryOptions } from './agent/source-registry.js';