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.
Files changed (81) hide show
  1. package/.githooks/post-commit +22 -0
  2. package/AGENTS.md +328 -0
  3. package/CHANGELOG.md +198 -0
  4. package/LICENSE +21 -0
  5. package/README.md +488 -0
  6. package/bin/humemory.js +19 -0
  7. package/dist/agent/claude-hook.d.ts +15 -0
  8. package/dist/agent/claude-hook.js +38 -0
  9. package/dist/agent/commit-closer.d.ts +60 -0
  10. package/dist/agent/commit-closer.js +125 -0
  11. package/dist/agent/learning-extractor.d.ts +10 -0
  12. package/dist/agent/learning-extractor.js +75 -0
  13. package/dist/agent/session-context.d.ts +63 -0
  14. package/dist/agent/session-context.js +216 -0
  15. package/dist/agent/session-parser.d.ts +12 -0
  16. package/dist/agent/session-parser.js +85 -0
  17. package/dist/api/dream-routes.d.ts +7 -0
  18. package/dist/api/dream-routes.js +40 -0
  19. package/dist/api/intentions-routes.d.ts +23 -0
  20. package/dist/api/intentions-routes.js +252 -0
  21. package/dist/api/memory-routes.d.ts +10 -0
  22. package/dist/api/memory-routes.js +277 -0
  23. package/dist/api/scripts-routes.d.ts +13 -0
  24. package/dist/api/scripts-routes.js +129 -0
  25. package/dist/api/server.d.ts +33 -0
  26. package/dist/api/server.js +157 -0
  27. package/dist/cli/index.d.ts +2 -0
  28. package/dist/cli/index.js +798 -0
  29. package/dist/core/clock.d.ts +38 -0
  30. package/dist/core/clock.js +52 -0
  31. package/dist/core/cue-arg.d.ts +19 -0
  32. package/dist/core/cue-arg.js +72 -0
  33. package/dist/core/cues.d.ts +138 -0
  34. package/dist/core/cues.js +372 -0
  35. package/dist/core/decay.d.ts +49 -0
  36. package/dist/core/decay.js +157 -0
  37. package/dist/core/dreamer.d.ts +114 -0
  38. package/dist/core/dreamer.js +427 -0
  39. package/dist/core/embeddings.d.ts +79 -0
  40. package/dist/core/embeddings.js +133 -0
  41. package/dist/core/event-bus.d.ts +71 -0
  42. package/dist/core/event-bus.js +67 -0
  43. package/dist/core/hybrid.d.ts +33 -0
  44. package/dist/core/hybrid.js +63 -0
  45. package/dist/core/llm-generator.d.ts +18 -0
  46. package/dist/core/llm-generator.js +69 -0
  47. package/dist/core/sanitize.d.ts +57 -0
  48. package/dist/core/sanitize.js +87 -0
  49. package/dist/core/scripts.d.ts +55 -0
  50. package/dist/core/scripts.js +96 -0
  51. package/dist/core/search.d.ts +42 -0
  52. package/dist/core/search.js +173 -0
  53. package/dist/core/trust.d.ts +48 -0
  54. package/dist/core/trust.js +57 -0
  55. package/dist/core/types.d.ts +333 -0
  56. package/dist/core/types.js +1 -0
  57. package/dist/core/vector-clusterer.d.ts +53 -0
  58. package/dist/core/vector-clusterer.js +113 -0
  59. package/dist/index.d.ts +28 -0
  60. package/dist/index.js +18 -0
  61. package/dist/mcp/server.d.ts +22 -0
  62. package/dist/mcp/server.js +158 -0
  63. package/dist/store/sqlite.d.ts +240 -0
  64. package/dist/store/sqlite.js +1653 -0
  65. package/docs/TESTING.md +244 -0
  66. package/package.json +95 -0
  67. package/public/app/galaxy-f42190mq.js +10 -0
  68. package/public/app/index-2cf31xxn.css +1 -0
  69. package/public/app/index-epqg22cp.js +1 -0
  70. package/public/app/index-f9h80bzq.js +12 -0
  71. package/public/app/index-gbfwa9vq.js +2 -0
  72. package/public/app/index-kvhc17mz.js +2 -0
  73. package/public/app/index-pbd5t4dj.js +2 -0
  74. package/public/app/index.html +12 -0
  75. package/public/app/promenade-cnzzpm73.js +4111 -0
  76. package/public/app/river-tyawhh8w.js +13 -0
  77. package/public/session.html +659 -0
  78. package/scripts/consolidate.js +46 -0
  79. package/scripts/hook-post-commit.ts +80 -0
  80. package/scripts/hook-session-start.ts +92 -0
  81. package/scripts/hook-session.ts +60 -0
@@ -0,0 +1,173 @@
1
+ import { createRequire } from 'module';
2
+ const require = createRequire(import.meta.url);
3
+ const flexsearch = require('flexsearch');
4
+ const { Document } = flexsearch;
5
+ import { systemClock } from './clock.js';
6
+ /**
7
+ * Inverse search engine, BM25-backed.
8
+ * Queries the degraded layers first (level 3), then escalates.
9
+ */
10
+ export class InverseSearchEngine {
11
+ index;
12
+ memories = new Map();
13
+ clock;
14
+ constructor(options = {}) {
15
+ // The recency bonus depends on "now" — injectable so scoring is deterministic
16
+ // in tests (docs/TESTING.md → pillar 2).
17
+ this.clock = options.clock ?? systemClock;
18
+ // FlexSearch index tuned for keywords
19
+ this.index = new Document({
20
+ tokenize: 'forward',
21
+ charset: 'latin:advanced',
22
+ optimize: true,
23
+ document: {
24
+ id: 'id',
25
+ index: ['level3Keywords', 'level2Essential', 'level1Summary', 'content'],
26
+ },
27
+ });
28
+ }
29
+ /**
30
+ * Adds a memory to the index
31
+ */
32
+ add(memory) {
33
+ this.memories.set(memory.id, memory);
34
+ this.index.add({
35
+ id: memory.id,
36
+ level3Keywords: memory.level3Keywords || '',
37
+ level2Essential: memory.level2Essential || '',
38
+ level1Summary: memory.level1Summary || '',
39
+ content: memory.content,
40
+ });
41
+ }
42
+ /**
43
+ * Updates a memory in the index
44
+ */
45
+ update(memory) {
46
+ this.index.remove(memory.id);
47
+ this.add(memory);
48
+ }
49
+ /**
50
+ * Supprime un souvenir de l'index
51
+ */
52
+ remove(id) {
53
+ this.index.remove(id);
54
+ this.memories.delete(id);
55
+ }
56
+ /**
57
+ * Inverse search: starts at level 3 and escalates when needed
58
+ */
59
+ search(query) {
60
+ const results = [];
61
+ const { query: searchQuery, maxLevel = 3, limit = 10 } = query;
62
+ // Level-by-level strategy, from most degraded to most detailed
63
+ const searchOrder = [
64
+ { field: 'level3Keywords', level: 3 },
65
+ { field: 'level2Essential', level: 2 },
66
+ { field: 'level1Summary', level: 1 },
67
+ { field: 'content', level: 0 },
68
+ ];
69
+ const seenIds = new Set();
70
+ for (const { field, level } of searchOrder) {
71
+ // Skip once past the caller's maximum level
72
+ if (level > maxLevel)
73
+ continue;
74
+ // Recherche sur ce niveau
75
+ const matches = this.index.search({
76
+ query: searchQuery,
77
+ field,
78
+ limit: limit * 2, // over-fetch, filtering happens below
79
+ });
80
+ // FlexSearch retourne [{field, result: [ids]}]
81
+ // Collect ids from every matched field
82
+ const ids = [];
83
+ for (const match of matches) {
84
+ if (match && typeof match === 'object' && 'result' in match) {
85
+ ids.push(...match.result);
86
+ }
87
+ else if (typeof match === 'string') {
88
+ ids.push(match);
89
+ }
90
+ }
91
+ // Process the results
92
+ for (const id of ids) {
93
+ if (seenIds.has(id))
94
+ continue;
95
+ seenIds.add(id);
96
+ const memory = this.memories.get(id);
97
+ if (!memory)
98
+ continue;
99
+ // Filtres optionnels
100
+ if (query.directory && memory.directory !== query.directory)
101
+ continue;
102
+ if (query.sessionId && memory.sessionId !== query.sessionId)
103
+ continue;
104
+ if (query.memoryType && memory.memoryType !== query.memoryType)
105
+ continue;
106
+ if (query.dateFrom && new Date(memory.day) < query.dateFrom)
107
+ continue;
108
+ if (query.dateTo && new Date(memory.day) > query.dateTo)
109
+ continue;
110
+ if (query.minSaillance !== undefined && memory.saillance < query.minSaillance)
111
+ continue;
112
+ if (query.minRecalls !== undefined && memory.recallCount < query.minRecalls)
113
+ continue;
114
+ results.push({
115
+ memory,
116
+ matchLevel: level,
117
+ score: this.calculateScore(memory, searchQuery, level),
118
+ });
119
+ if (results.length >= limit) {
120
+ return results.sort((a, b) => b.score - a.score);
121
+ }
122
+ }
123
+ }
124
+ return results.sort((a, b) => b.score - a.score);
125
+ }
126
+ /**
127
+ * Calcule un score de pertinence
128
+ */
129
+ calculateScore(memory, query, matchLevel) {
130
+ let score = 100;
131
+ // Bonus for matching on a degraded level: cheaper to reach, more useful
132
+ const levelBonus = (4 - matchLevel) * 10;
133
+ score += levelBonus;
134
+ // Recency bonus
135
+ const daysSinceCreation = (this.clock.now().getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60 * 24);
136
+ if (daysSinceCreation < 7) {
137
+ score += 20;
138
+ }
139
+ else if (daysSinceCreation < 30) {
140
+ score += 10;
141
+ }
142
+ // Bonus for frequent recalls
143
+ score += memory.recallCount * 5;
144
+ // Bonus pour saillance
145
+ score += memory.saillance * 0.2;
146
+ // Penalty for very long content: less precise
147
+ if (memory.content.length > 1000) {
148
+ score -= 10;
149
+ }
150
+ return Math.min(100, score);
151
+ }
152
+ /**
153
+ * Retourne tous les souvenirs (pour debug/sync)
154
+ */
155
+ getAll() {
156
+ return Array.from(this.memories.values());
157
+ }
158
+ /**
159
+ * Clear l'index
160
+ */
161
+ clear() {
162
+ this.index = new Document({
163
+ tokenize: 'forward',
164
+ charset: 'latin:advanced',
165
+ optimize: true,
166
+ document: {
167
+ id: 'id',
168
+ index: ['level3Keywords', 'level2Essential', 'level1Summary', 'content'],
169
+ },
170
+ });
171
+ this.memories.clear();
172
+ }
173
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Trust score — Phase 6.0.1.
3
+ *
4
+ * Deliberately separate from `saillance`: salience is *how loud* a trace is,
5
+ * trust is *whether to believe it*. Conflating them produces confident
6
+ * nonsense.
7
+ *
8
+ * The weights are calibration outputs (Kimi B7, accepted by Claude R3): they
9
+ * live in TRUST_CONFIG next to DECAY_CONFIG and are frozen against the labeled
10
+ * fixtures in tests/fixtures/trust/ — not guessed inline.
11
+ */
12
+ import type { Memory } from './types.js';
13
+ export declare const TRUST_CONFIG: {
14
+ /** Base trust by provenance. */
15
+ base: {
16
+ human: number;
17
+ hook: number;
18
+ agent: number;
19
+ llm_generated: number;
20
+ dream_proposal: number;
21
+ };
22
+ /**
23
+ * Bonus by verification reason — tiered, not flat (Claude R1). `corroborated`
24
+ * is deliberately weakest: two agents agreeing is the cheapest signal to
25
+ * manufacture and the easiest to obtain by accident.
26
+ */
27
+ bonus: {
28
+ human: number;
29
+ grounded: number;
30
+ reused: number;
31
+ corroborated: number;
32
+ };
33
+ /** Each refutation costs this much, capped at `refutedCap` refutations. */
34
+ refutedPenalty: number;
35
+ refutedCap: number;
36
+ };
37
+ /**
38
+ * Trust of a trace, clamped to 0..100.
39
+ * Pre-Phase-6 rows (no `source`) default to the `agent` base — silence is not
40
+ * endorsement, but it is not suspicion either.
41
+ */
42
+ export declare function trustScore(memory: Memory): number;
43
+ /**
44
+ * Base-only trust, for dreamer clustering (Claude R1 invariant): verification
45
+ * informs recall ordering, recurrence informs clustering — they never feed
46
+ * each other.
47
+ */
48
+ export declare function baseTrust(memory: Memory): number;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Trust score — Phase 6.0.1.
3
+ *
4
+ * Deliberately separate from `saillance`: salience is *how loud* a trace is,
5
+ * trust is *whether to believe it*. Conflating them produces confident
6
+ * nonsense.
7
+ *
8
+ * The weights are calibration outputs (Kimi B7, accepted by Claude R3): they
9
+ * live in TRUST_CONFIG next to DECAY_CONFIG and are frozen against the labeled
10
+ * fixtures in tests/fixtures/trust/ — not guessed inline.
11
+ */
12
+ export const TRUST_CONFIG = {
13
+ /** Base trust by provenance. */
14
+ base: {
15
+ human: 60,
16
+ hook: 45,
17
+ agent: 35,
18
+ llm_generated: 25,
19
+ dream_proposal: 20,
20
+ },
21
+ /**
22
+ * Bonus by verification reason — tiered, not flat (Claude R1). `corroborated`
23
+ * is deliberately weakest: two agents agreeing is the cheapest signal to
24
+ * manufacture and the easiest to obtain by accident.
25
+ */
26
+ bonus: {
27
+ human: 25,
28
+ grounded: 20,
29
+ reused: 15,
30
+ corroborated: 8,
31
+ },
32
+ /** Each refutation costs this much, capped at `refutedCap` refutations. */
33
+ refutedPenalty: 15,
34
+ refutedCap: 3,
35
+ };
36
+ /**
37
+ * Trust of a trace, clamped to 0..100.
38
+ * Pre-Phase-6 rows (no `source`) default to the `agent` base — silence is not
39
+ * endorsement, but it is not suspicion either.
40
+ */
41
+ export function trustScore(memory) {
42
+ const source = memory.source ?? 'agent';
43
+ let score = TRUST_CONFIG.base[source];
44
+ if (memory.verified && memory.verificationReason) {
45
+ score += TRUST_CONFIG.bonus[memory.verificationReason];
46
+ }
47
+ score -= TRUST_CONFIG.refutedPenalty * Math.min(memory.refutedCount ?? 0, TRUST_CONFIG.refutedCap);
48
+ return Math.max(0, Math.min(100, score));
49
+ }
50
+ /**
51
+ * Base-only trust, for dreamer clustering (Claude R1 invariant): verification
52
+ * informs recall ordering, recurrence informs clustering — they never feed
53
+ * each other.
54
+ */
55
+ export function baseTrust(memory) {
56
+ return TRUST_CONFIG.base[memory.source ?? 'agent'];
57
+ }
@@ -0,0 +1,333 @@
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
+ * Memory types (cognitive neuroscience).
12
+ * - Episodic: lived events, with their temporal and spatial context
13
+ * - Semantic: facts and concepts
14
+ * - Procedural: know-how, gestures, routines
15
+ */
16
+ export type MemoryType = 'episodic' | 'semantic' | 'procedural';
17
+ export interface Memory {
18
+ id: string;
19
+ content: string;
20
+ level1Summary?: string;
21
+ level2Essential?: string;
22
+ level3Keywords?: string;
23
+ directory: string;
24
+ day: string;
25
+ keywords: string[];
26
+ sessionId: string;
27
+ memoryType: MemoryType;
28
+ createdAt: Date;
29
+ lastRecalled?: Date;
30
+ recallCount: number;
31
+ decayRate: number;
32
+ currentLevel: DecayLevel;
33
+ saillance: number;
34
+ mergedIntoId?: string;
35
+ photographic?: boolean;
36
+ source?: TraceSource;
37
+ agent?: string;
38
+ verified?: boolean;
39
+ verificationReason?: VerificationReason;
40
+ device?: string;
41
+ refutedCount?: number;
42
+ }
43
+ export type TraceSource = 'human' | 'agent' | 'hook' | 'llm_generated' | 'dream_proposal';
44
+ export type VerificationReason = 'corroborated' | 'grounded' | 'reused' | 'human';
45
+ export interface SearchQuery {
46
+ query: string;
47
+ directory?: string;
48
+ sessionId?: string;
49
+ maxLevel?: DecayLevel;
50
+ limit?: number;
51
+ memoryType?: MemoryType;
52
+ dateFrom?: Date;
53
+ dateTo?: Date;
54
+ minSaillance?: number;
55
+ minRecalls?: number;
56
+ }
57
+ export interface SearchResult {
58
+ memory: Memory;
59
+ matchLevel: DecayLevel;
60
+ score: number;
61
+ }
62
+ export interface MergeResult {
63
+ source: Memory;
64
+ target: Memory;
65
+ mergedContent?: string;
66
+ }
67
+ export interface Contradiction {
68
+ id: string;
69
+ winnerId: string;
70
+ loserId: string;
71
+ /**
72
+ * Phase 8 — the loser can be a script as well as a memory ("correction
73
+ * kills the script", PHASE8_PLAN.md §8.4). The winner is always a memory:
74
+ * nothing in the domain corrects a fact *into* becoming a script, only the
75
+ * other way round. Absent on rows written before this field existed —
76
+ * treat as `'memory'`.
77
+ */
78
+ loserKind?: 'memory' | 'script';
79
+ reason?: string;
80
+ createdAt: Date;
81
+ createdBy: 'agent' | 'human' | 'dreamer';
82
+ agent?: string;
83
+ status: 'active' | 'revoked';
84
+ }
85
+ export interface ContradictResult {
86
+ contradiction?: Contradiction;
87
+ /** Set when authority was asymmetric: a proposal was filed instead. */
88
+ proposalFiled?: boolean;
89
+ /** Set when the loser was already merged — the collapse hit the merge target. */
90
+ retargetedTo?: string;
91
+ loser: Memory | Script;
92
+ }
93
+ export type DreamKind = 'promote_semantic' | 'merge_cluster' | 'update_agents_md' | 'contradiction' | 'close_stale_loop' | 'script_archived' | 'script_candidate';
94
+ export type DreamStatus = 'pending' | 'approved' | 'rejected' | 'expired';
95
+ export interface DreamProposal {
96
+ id: string;
97
+ kind: DreamKind;
98
+ payload: string;
99
+ payloadHash: string;
100
+ status: DreamStatus;
101
+ confidence: number;
102
+ createdAt: Date;
103
+ expiresAt?: Date;
104
+ resolvedAt?: Date;
105
+ resolvedBy?: string;
106
+ }
107
+ /** armed = waiting · fired = surfaced to the agent · closed = done · expired = past its deadline. */
108
+ export type IntentionStatus = 'armed' | 'fired' | 'closed' | 'expired';
109
+ export type CueStatus = 'armed' | 'fired' | 'cancelled';
110
+ export type CueKind = 'time' | 'event';
111
+ /** Time trigger: either a one-shot date (`at`) or a recurrence (`cron`). */
112
+ export interface TimeTriggerSpec {
113
+ kind: 'time';
114
+ at?: string;
115
+ cron?: string;
116
+ }
117
+ /**
118
+ * Event trigger. No `commit` variant here, on purpose: a commit does not wake an
119
+ * intention, it *closes* one — that is the post-commit hook's job (S5-03b), not
120
+ * the cue resolver's.
121
+ */
122
+ export type EventTriggerSpec = {
123
+ kind: 'event';
124
+ type: 'file_open';
125
+ path: string;
126
+ } | {
127
+ kind: 'event';
128
+ type: 'branch_switch';
129
+ branch: string;
130
+ } | {
131
+ kind: 'event';
132
+ type: 'error_pattern';
133
+ pattern: string;
134
+ };
135
+ export type TriggerSpec = TimeTriggerSpec | EventTriggerSpec;
136
+ export interface Intention {
137
+ id: string;
138
+ content: string;
139
+ directory: string;
140
+ createdAt: Date;
141
+ expiresAt?: Date;
142
+ status: IntentionStatus;
143
+ firedAt?: Date;
144
+ closedAt?: Date;
145
+ closedByCommit?: string;
146
+ saillance: number;
147
+ relatedMemoryId?: string;
148
+ source?: TraceSource;
149
+ agent?: string;
150
+ verified?: boolean;
151
+ verificationReason?: VerificationReason;
152
+ device?: string;
153
+ }
154
+ export interface Cue {
155
+ id: string;
156
+ /** Phase 8: a cue can arm an intention OR a script. */
157
+ targetKind: CueTargetKind;
158
+ /** Id of the target (intention or script) this cue arms. */
159
+ targetId: string;
160
+ /**
161
+ * @deprecated Compat alias for Phase 5 consumers — equals `targetId`.
162
+ * Intention-only consumers must check `targetKind === 'intention'` first.
163
+ */
164
+ intentionId: string;
165
+ kind: CueKind;
166
+ triggerSpec: TriggerSpec;
167
+ status: CueStatus;
168
+ armedAt: Date;
169
+ firedAt?: Date;
170
+ }
171
+ export type CueTargetKind = 'intention' | 'script';
172
+ /** Write shape for an intention: the store sets id/createdAt/status/saillance. */
173
+ export type NewIntention = Omit<Intention, 'id' | 'createdAt' | 'status' | 'saillance' | 'firedAt' | 'closedAt' | 'closedByCommit'> & {
174
+ status?: IntentionStatus;
175
+ saillance?: number;
176
+ };
177
+ /** Write shape for a cue: the store sets id/armedAt/status and derives `kind` from the spec. */
178
+ export type NewCue = {
179
+ intentionId: string;
180
+ triggerSpec: TriggerSpec;
181
+ status?: CueStatus;
182
+ };
183
+ export interface IntentionStore {
184
+ addIntention(intention: NewIntention, cues?: TriggerSpec[]): Promise<Intention>;
185
+ getIntention(id: string): Promise<Intention | null>;
186
+ listIntentions(options?: {
187
+ status?: IntentionStatus | IntentionStatus[];
188
+ directory?: string;
189
+ limit?: number;
190
+ }): Promise<Intention[]>;
191
+ updateIntentionStatus(id: string, status: IntentionStatus, options?: {
192
+ closedByCommit?: string;
193
+ }): Promise<Intention>;
194
+ deleteIntention(id: string): Promise<void>;
195
+ addCue(cue: NewCue): Promise<Cue>;
196
+ getCue(id: string): Promise<Cue | null>;
197
+ listCues(options?: {
198
+ intentionId?: string;
199
+ targetKind?: CueTargetKind;
200
+ targetId?: string;
201
+ status?: CueStatus | CueStatus[];
202
+ kind?: CueKind;
203
+ limit?: number;
204
+ }): Promise<Cue[]>;
205
+ updateCueStatus(id: string, status: CueStatus): Promise<Cue>;
206
+ /** Records a firing. `rearm` keeps the cue `armed` (recurring cues). */
207
+ markCueFired(id: string, options?: {
208
+ rearm?: boolean;
209
+ }): Promise<Cue>;
210
+ }
211
+ /** draft = proposed, never fires · active = resolves through cues · archived = searchable only. */
212
+ export type ScriptStatus = 'draft' | 'active' | 'archived';
213
+ export interface Script {
214
+ id: string;
215
+ name: string;
216
+ description: string;
217
+ steps: string[];
218
+ directory: string;
219
+ status: ScriptStatus;
220
+ /** Fire-bumped saillance; effective value deducts disuse decay (8.4 sweep). */
221
+ saillance: number;
222
+ fireCount: number;
223
+ lastFiredAt?: Date;
224
+ /** Pinned = photographic equivalent: exempt from disuse decay. */
225
+ pinned: boolean;
226
+ source?: TraceSource;
227
+ agent?: string;
228
+ device?: string;
229
+ createdAt: Date;
230
+ updatedAt: Date;
231
+ }
232
+ /** Write shape for a script: the store sets id/status/saillance/fireCount/timestamps. */
233
+ export type NewScript = Omit<Script, 'id' | 'status' | 'saillance' | 'fireCount' | 'lastFiredAt' | 'createdAt' | 'updatedAt'> & {
234
+ status?: ScriptStatus;
235
+ saillance?: number;
236
+ };
237
+ export interface ScriptStore {
238
+ addScript(script: NewScript, cues?: TriggerSpec[]): Promise<Script>;
239
+ getScript(id: string): Promise<Script | null>;
240
+ /** Name lookup, unique per directory — the CLI and the dreamer both address drills by name. */
241
+ getScriptByName(name: string, directory: string): Promise<Script | null>;
242
+ listScripts(options?: {
243
+ status?: ScriptStatus | ScriptStatus[];
244
+ directory?: string;
245
+ limit?: number;
246
+ }): Promise<Script[]>;
247
+ updateScriptStatus(id: string, status: ScriptStatus): Promise<Script>;
248
+ updateScript(id: string, patch: {
249
+ name?: string;
250
+ description?: string;
251
+ steps?: string[];
252
+ pinned?: boolean;
253
+ }): Promise<Script>;
254
+ /** Firing bumps fireCount, lastFiredAt and saillance (+5, capped 100). */
255
+ markScriptFired(id: string): Promise<Script>;
256
+ deleteScript(id: string): Promise<void>;
257
+ }
258
+ export interface MemoryStore {
259
+ add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'>, options?: {
260
+ autoGenerate?: boolean;
261
+ }): Promise<Memory>;
262
+ getById(id: string): Promise<Memory | null>;
263
+ search(query: SearchQuery): Promise<SearchResult[]>;
264
+ /**
265
+ * `agent` (Phase 6.0.1): who is recalling. A recall by a *different* agent
266
+ * than the writer earns the trace the `reused` verification.
267
+ */
268
+ /**
269
+ * Reinforce a trace. `agent` is attribution; `identityTrusted` says whether
270
+ * that attribution is a process-level fact (MCP stdio, CLI) or a request
271
+ * claiming one (HTTP header). Only the former can earn `reused` verification.
272
+ */
273
+ recall(id: string, agent?: string, options?: {
274
+ identityTrusted?: boolean;
275
+ }): Promise<Memory>;
276
+ updateDecay(): Promise<void>;
277
+ delete(id: string): Promise<void>;
278
+ list(options?: {
279
+ limit?: number;
280
+ level?: DecayLevel;
281
+ levels?: DecayLevel[];
282
+ type?: MemoryType;
283
+ directory?: string;
284
+ minSaillance?: number;
285
+ }): Promise<Memory[]>;
286
+ findSimilar(id: string, options?: {
287
+ limit?: number;
288
+ threshold?: number;
289
+ }): Promise<SearchResult[]>;
290
+ merge(sourceId: string, targetId: string, options?: {
291
+ autoMergeContent?: boolean;
292
+ client?: import('./llm-generator.js').LLMClient;
293
+ }): Promise<MergeResult>;
294
+ setPhotographic(id: string, value: boolean): Promise<Memory>;
295
+ /** Phase 6.0.1 — human override verification; automatic paths set the flag directly. */
296
+ verify?(id: string, by?: string): Promise<Memory>;
297
+ /** Phase 6.0.1 — negative signal: refuted_count +1 and verification revoked. */
298
+ refute?(id: string, reason?: string): Promise<Memory>;
299
+ /** Phase 6.0.4 — revert a merge: resurrect the source, restore the target's revised levels. */
300
+ unmerge?(sourceId: string): Promise<{
301
+ source: Memory;
302
+ target: Memory;
303
+ }>;
304
+ /** Phase 6.0.2 — `id` contradicts `otherId`. Tiered authority keyed on verification_reason. */
305
+ contradict?(winnerId: string, loserId: string, options?: {
306
+ reason?: string;
307
+ createdBy?: 'agent' | 'human' | 'dreamer';
308
+ agent?: string;
309
+ }): Promise<ContradictResult>;
310
+ /** Phase 6.0.2 — revoke: the loser's saillance is recomputed, not literally restored. */
311
+ revokeContradiction?(id: string): Promise<Contradiction>;
312
+ /** Phase 6.0.2 — active (or all) contradictions, for the context block and audits. */
313
+ listContradictions?(options?: {
314
+ loserId?: string;
315
+ status?: 'active' | 'revoked';
316
+ }): Promise<Contradiction[]>;
317
+ /** Phase 6.1 — dream proposals: list (default pending, non-expired) and resolve. */
318
+ listDreamProposals?(options?: {
319
+ status?: DreamStatus;
320
+ includeExpired?: boolean;
321
+ }): Promise<DreamProposal[]>;
322
+ resolveDreamProposal?(id: string, status: 'approved' | 'rejected', resolvedBy?: string): Promise<DreamProposal>;
323
+ /** Phase 6.1 — insert a proposal, deduped by (kind, payload_hash). Returns false if it already existed. */
324
+ fileDreamProposal?(p: {
325
+ kind: DreamKind;
326
+ payload: string;
327
+ payloadHash: string;
328
+ confidence?: number;
329
+ expiresAt?: Date;
330
+ }): Promise<boolean>;
331
+ /** Phase 6.1 — mark pending proposals past their expires_at as expired. Returns the count. */
332
+ expireDreamProposals?(): Promise<number>;
333
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
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
+ import type { Memory } from './types.js';
15
+ import { type Clusterer } from './dreamer.js';
16
+ import { type Embedder } from './embeddings.js';
17
+ export interface ScoredCluster {
18
+ members: Memory[];
19
+ /** Weakest link that holds the cluster together. */
20
+ minPairwiseSimilarity: number;
21
+ }
22
+ export interface ScoredClusterer extends Clusterer {
23
+ clusterWithScores(memories: Memory[]): Promise<ScoredCluster[]>;
24
+ }
25
+ /** Type guard — the dreamer uses scores when the clusterer provides them. */
26
+ export declare function hasScores(c: Clusterer): c is ScoredClusterer;
27
+ export interface EmbeddingStore {
28
+ getEmbedding(memoryId: string): Promise<{
29
+ modelId: string;
30
+ embedding: Float32Array;
31
+ } | null>;
32
+ setEmbedding(memoryId: string, modelId: string, embedding: Float32Array): Promise<void>;
33
+ }
34
+ export declare class VectorClusterer implements ScoredClusterer {
35
+ private embedder;
36
+ private store;
37
+ /**
38
+ * Default: the embedder's calibrated per-model threshold
39
+ * (OnnxEmbedder.suggestedClusterThreshold — 7.5 round 4), falling back to
40
+ * DREAM_CONFIG for embedders without calibration (e.g. HashEmbedder in tests).
41
+ */
42
+ private threshold;
43
+ constructor(embedder: Embedder, store: EmbeddingStore,
44
+ /**
45
+ * Default: the embedder's calibrated per-model threshold
46
+ * (OnnxEmbedder.suggestedClusterThreshold — 7.5 round 4), falling back to
47
+ * DREAM_CONFIG for embedders without calibration (e.g. HashEmbedder in tests).
48
+ */
49
+ threshold?: number);
50
+ private embeddingsFor;
51
+ clusterWithScores(memories: Memory[]): Promise<ScoredCluster[]>;
52
+ cluster(memories: Memory[]): Promise<Memory[][]>;
53
+ }