humemory 0.2.7 → 0.2.9

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 (102) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +66 -12
  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 +2 -1
  9. package/dist/agent/maintenance-queue.js +36 -62
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/memory-routes.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +117 -6
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/doctor.d.ts +28 -0
  27. package/dist/core/doctor.js +320 -0
  28. package/dist/core/embeddings.d.ts +0 -10
  29. package/dist/core/embeddings.js +2 -1
  30. package/dist/core/hybrid.d.ts +7 -3
  31. package/dist/core/hybrid.js +7 -3
  32. package/dist/core/llm-generator.d.ts +2 -10
  33. package/dist/core/paths.d.ts +12 -0
  34. package/dist/core/paths.js +36 -0
  35. package/dist/core/project-path.d.ts +3 -0
  36. package/dist/core/project-path.js +14 -0
  37. package/dist/core/search.d.ts +1 -1
  38. package/dist/core/search.js +7 -9
  39. package/dist/core/types.d.ts +13 -1
  40. package/dist/index.d.ts +5 -0
  41. package/dist/index.js +5 -0
  42. package/dist/store/sqlite.d.ts +37 -0
  43. package/dist/store/sqlite.js +94 -42
  44. package/docs/PORTABILITY.md +84 -0
  45. package/package.json +5 -3
  46. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  47. package/public/app/index.html +1 -1
  48. package/scripts/consolidate.js +4 -4
  49. package/scripts/hook-post-commit.ts +2 -1
  50. package/scripts/hook-session-start.ts +2 -1
  51. package/scripts/hook-session.ts +2 -1
  52. package/scripts/maintenance-worker.ts +7 -2
  53. package/src/agent/claude-hook.ts +126 -0
  54. package/src/agent/codex-import.ts +129 -0
  55. package/src/agent/codex-rollout-parser.ts +121 -0
  56. package/src/agent/commit-closer.ts +173 -0
  57. package/src/agent/kimi-import.ts +128 -0
  58. package/src/agent/kimi-session-parser.ts +127 -0
  59. package/src/agent/learning-extractor.ts +128 -0
  60. package/src/agent/maintenance-queue.ts +544 -0
  61. package/src/agent/maintenance-runner.ts +322 -0
  62. package/src/agent/maintenance-state.ts +168 -0
  63. package/src/agent/mcp-client-setup.ts +125 -0
  64. package/src/agent/opencode-import.ts +96 -0
  65. package/src/agent/opencode-session-parser.ts +53 -0
  66. package/src/agent/session-context.ts +302 -0
  67. package/src/agent/session-parser.ts +155 -0
  68. package/src/agent/source-registry.ts +135 -0
  69. package/src/api/cors.ts +42 -0
  70. package/src/api/dream-routes.ts +46 -0
  71. package/src/api/errors.ts +45 -0
  72. package/src/api/intentions-routes.ts +348 -0
  73. package/src/api/limits.ts +90 -0
  74. package/src/api/maintenance-routes.ts +73 -0
  75. package/src/api/memory-routes.ts +391 -0
  76. package/src/api/scripts-routes.ts +176 -0
  77. package/src/api/security-headers.ts +54 -0
  78. package/src/api/server.ts +292 -0
  79. package/src/cli/index.ts +1195 -0
  80. package/src/core/clock.ts +64 -0
  81. package/src/core/cue-arg.ts +79 -0
  82. package/src/core/cues.ts +511 -0
  83. package/src/core/decay.ts +198 -0
  84. package/src/core/doctor.ts +362 -0
  85. package/src/core/dreamer.ts +494 -0
  86. package/src/core/embeddings.ts +157 -0
  87. package/src/core/event-bus.ts +100 -0
  88. package/src/core/hybrid.ts +82 -0
  89. package/src/core/llm-cli-client.ts +118 -0
  90. package/src/core/llm-generator.ts +90 -0
  91. package/src/core/paths.ts +38 -0
  92. package/src/core/project-path.ts +14 -0
  93. package/src/core/sanitize.ts +116 -0
  94. package/src/core/scripts.ts +112 -0
  95. package/src/core/search.ts +189 -0
  96. package/src/core/trust.ts +67 -0
  97. package/src/core/types.ts +393 -0
  98. package/src/core/vector-clusterer.ts +131 -0
  99. package/src/index.ts +40 -0
  100. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  101. package/src/mcp/server.ts +202 -0
  102. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,189 @@
1
+ import { createRequire } from 'module';
2
+ const require = createRequire(import.meta.url);
3
+ const flexsearch = require('flexsearch');
4
+ const { Document } = flexsearch;
5
+
6
+ import type { Memory, SearchQuery, SearchResult, DecayLevel } from './types.js';
7
+ import { systemClock, type Clock } from './clock.js';
8
+ import { projectPath } from './project-path.js';
9
+
10
+ /**
11
+ * Inverse search engine, FlexSearch candidates with heuristic ranking.
12
+ * Queries the degraded layers first (level 3), then escalates.
13
+ */
14
+ export class InverseSearchEngine {
15
+ private index: any;
16
+ private memories: Map<string, Memory> = new Map();
17
+ private clock: Clock;
18
+
19
+ constructor(options: { clock?: Clock } = {}) {
20
+ // The recency bonus depends on "now" — injectable so scoring is deterministic
21
+ // in tests (docs/TESTING.md → pillar 2).
22
+ this.clock = options.clock ?? systemClock;
23
+ // FlexSearch index tuned for keywords
24
+ this.index = new Document({
25
+ tokenize: 'forward',
26
+ charset: 'latin:advanced',
27
+ optimize: true,
28
+ document: {
29
+ id: 'id',
30
+ index: ['level3Keywords', 'level2Essential', 'level1Summary', 'content'],
31
+ },
32
+ });
33
+ }
34
+
35
+ /**
36
+ * Adds a memory to the index
37
+ */
38
+ add(memory: Memory): void {
39
+ this.memories.set(memory.id, memory);
40
+
41
+ this.index.add({
42
+ id: memory.id,
43
+ level3Keywords: memory.level3Keywords || '',
44
+ level2Essential: memory.level2Essential || '',
45
+ level1Summary: memory.level1Summary || '',
46
+ content: memory.content,
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Updates a memory in the index
52
+ */
53
+ update(memory: Memory): void {
54
+ this.index.remove(memory.id);
55
+ this.add(memory);
56
+ }
57
+
58
+ /**
59
+ * Supprime un souvenir de l'index
60
+ */
61
+ remove(id: string): void {
62
+ this.index.remove(id);
63
+ this.memories.delete(id);
64
+ }
65
+
66
+ /**
67
+ * Inverse search: starts at level 3 and escalates when needed
68
+ */
69
+ search(query: SearchQuery): SearchResult[] {
70
+ const results: SearchResult[] = [];
71
+ const { query: searchQuery, maxLevel = 3, limit = 10 } = query;
72
+
73
+ // Level-by-level strategy, from most degraded to most detailed
74
+ const searchOrder: { field: string; level: DecayLevel }[] = [
75
+ { field: 'level3Keywords', level: 3 },
76
+ { field: 'level2Essential', level: 2 },
77
+ { field: 'level1Summary', level: 1 },
78
+ { field: 'content', level: 0 },
79
+ ];
80
+
81
+ const seenIds = new Set<string>();
82
+
83
+ for (const { field, level } of searchOrder) {
84
+ // Skip once past the caller's maximum level
85
+ if (level > maxLevel) continue;
86
+
87
+ // Recherche sur ce niveau
88
+ const matches = this.index.search({
89
+ query: searchQuery,
90
+ field,
91
+ limit: Math.max(1, this.memories.size), // rank all candidates after filtering
92
+ });
93
+
94
+ // FlexSearch retourne [{field, result: [ids]}]
95
+ // Collect ids from every matched field
96
+ const ids: string[] = [];
97
+ for (const match of matches) {
98
+ if (match && typeof match === 'object' && 'result' in match) {
99
+ ids.push(...(match.result as string[]));
100
+ } else if (typeof match === 'string') {
101
+ ids.push(match);
102
+ }
103
+ }
104
+
105
+ // Process the results
106
+ for (const id of ids) {
107
+ if (seenIds.has(id)) continue;
108
+ seenIds.add(id);
109
+
110
+ const memory = this.memories.get(id);
111
+ if (!memory) continue;
112
+
113
+ // Filtres optionnels
114
+ if (query.directory && projectPath(memory.directory) !== projectPath(query.directory)) continue;
115
+ if (query.sessionId && memory.sessionId !== query.sessionId) continue;
116
+ if (query.memoryType && memory.memoryType !== query.memoryType) continue;
117
+ if (query.dateFrom && new Date(memory.day) < query.dateFrom) continue;
118
+ if (query.dateTo && new Date(memory.day) > query.dateTo) continue;
119
+ if (query.minSaillance !== undefined && memory.saillance < query.minSaillance) continue;
120
+ if (query.minRecalls !== undefined && memory.recallCount < query.minRecalls) continue;
121
+
122
+ results.push({
123
+ memory,
124
+ matchLevel: level,
125
+ score: this.calculateScore(memory, searchQuery, level),
126
+ });
127
+
128
+ }
129
+ }
130
+
131
+ return results.sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id)).slice(0, Math.max(0, limit));
132
+ }
133
+
134
+ /**
135
+ * Calcule un score de pertinence
136
+ */
137
+ private calculateScore(memory: Memory, query: string, matchLevel: DecayLevel): number {
138
+ let score = 100;
139
+
140
+ // Bonus for matching on a degraded level: cheaper to reach, more useful
141
+ const levelBonus = matchLevel * 10;
142
+ score += levelBonus;
143
+
144
+ // Recency bonus
145
+ const daysSinceCreation =
146
+ (this.clock.now().getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60 * 24);
147
+ if (daysSinceCreation < 7) {
148
+ score += 20;
149
+ } else if (daysSinceCreation < 30) {
150
+ score += 10;
151
+ }
152
+
153
+ // Bonus for frequent recalls
154
+ score += memory.recallCount * 5;
155
+
156
+ // Bonus pour saillance
157
+ score += memory.saillance * 0.2;
158
+
159
+ // Penalty for very long content: less precise
160
+ if (memory.content.length > 1000) {
161
+ score -= 10;
162
+ }
163
+
164
+ return score;
165
+ }
166
+
167
+ /**
168
+ * Retourne tous les souvenirs (pour debug/sync)
169
+ */
170
+ getAll(): Memory[] {
171
+ return Array.from(this.memories.values());
172
+ }
173
+
174
+ /**
175
+ * Clear l'index
176
+ */
177
+ clear(): void {
178
+ this.index = new Document({
179
+ tokenize: 'forward',
180
+ charset: 'latin:advanced',
181
+ optimize: true,
182
+ document: {
183
+ id: 'id',
184
+ index: ['level3Keywords', 'level2Essential', 'level1Summary', 'content'],
185
+ },
186
+ });
187
+ this.memories.clear();
188
+ }
189
+ }
@@ -0,0 +1,67 @@
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
+
13
+ import type { Memory, TraceSource, VerificationReason } from './types.js';
14
+
15
+ export const TRUST_CONFIG = {
16
+ /** Base trust by provenance. */
17
+ base: {
18
+ human: 60,
19
+ hook: 45,
20
+ agent: 35,
21
+ llm_generated: 25,
22
+ dream_proposal: 20,
23
+ } satisfies Record<TraceSource, number>,
24
+
25
+ /**
26
+ * Bonus by verification reason — tiered, not flat (Claude R1). `corroborated`
27
+ * is deliberately weakest: two agents agreeing is the cheapest signal to
28
+ * manufacture and the easiest to obtain by accident.
29
+ */
30
+ bonus: {
31
+ human: 25,
32
+ grounded: 20,
33
+ reused: 15,
34
+ corroborated: 8,
35
+ } satisfies Record<VerificationReason, number>,
36
+
37
+ /** Each refutation costs this much, capped at `refutedCap` refutations. */
38
+ refutedPenalty: 15,
39
+ refutedCap: 3,
40
+ };
41
+
42
+ /**
43
+ * Trust of a trace, clamped to 0..100.
44
+ * Pre-Phase-6 rows (no `source`) default to the `agent` base — silence is not
45
+ * endorsement, but it is not suspicion either.
46
+ */
47
+ export function trustScore(memory: Memory): number {
48
+ const source = memory.source ?? 'agent';
49
+ let score = TRUST_CONFIG.base[source];
50
+
51
+ if (memory.verified && memory.verificationReason) {
52
+ score += TRUST_CONFIG.bonus[memory.verificationReason];
53
+ }
54
+
55
+ score -= TRUST_CONFIG.refutedPenalty * Math.min(memory.refutedCount ?? 0, TRUST_CONFIG.refutedCap);
56
+
57
+ return Math.max(0, Math.min(100, score));
58
+ }
59
+
60
+ /**
61
+ * Base-only trust, for dreamer clustering (Claude R1 invariant): verification
62
+ * informs recall ordering, recurrence informs clustering — they never feed
63
+ * each other.
64
+ */
65
+ export function baseTrust(memory: Memory): number {
66
+ return TRUST_CONFIG.base[memory.source ?? 'agent'];
67
+ }
@@ -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 the lexical index)
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
+ }