@vellumai/assistant 0.10.10-dev.202607211519.4a4e758 → 0.10.10-dev.202607211537.40f1959

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 (116) hide show
  1. package/docs/architecture/memory.md +101 -630
  2. package/openapi.yaml +3 -2
  3. package/package.json +1 -1
  4. package/src/__tests__/cli-memory-v2-reembed-skills.test.ts +1 -1
  5. package/src/__tests__/context-search-memory-v2-source.test.ts +5 -5
  6. package/src/__tests__/lifecycle-memory-v2-seed.test.ts +12 -8
  7. package/src/__tests__/managed-skill-lifecycle.test.ts +2 -2
  8. package/src/__tests__/plugin-import-boundary-guard.test.ts +11 -7
  9. package/src/__tests__/secret-routes-platform-proxy.test.ts +6 -3
  10. package/src/daemon/__tests__/embedding-reconcile.test.ts +2 -2
  11. package/src/daemon/embedding-reconcile.ts +4 -4
  12. package/src/daemon/skill-memory-refresh.ts +1 -1
  13. package/src/daemon/tool-side-effects.ts +3 -3
  14. package/src/daemon/trust-context.ts +1 -1
  15. package/src/persistence/jobs-store.ts +3 -0
  16. package/src/plugins/defaults/memory/__tests__/jobs-worker-v2-schedule.test.ts +72 -2
  17. package/src/plugins/defaults/memory/__tests__/memory-v2-concept-frequency.test.ts +1 -1
  18. package/src/plugins/defaults/memory/__tests__/tools-delete-memory-page.test.ts +1 -1
  19. package/src/plugins/defaults/memory/context-search/sources/memory-v2.ts +5 -5
  20. package/src/plugins/defaults/memory/fork-conversation-memory.ts +4 -4
  21. package/src/plugins/defaults/memory/graph/__tests__/conversation-graph-memory-v2-routing.test.ts +2 -1
  22. package/src/plugins/defaults/memory/graph/capability-seed.ts +1 -1
  23. package/src/plugins/defaults/memory/graph-topology/__tests__/build-memory-graph.test.ts +1 -1
  24. package/src/plugins/defaults/memory/graph-topology/build-memory-graph.ts +42 -4
  25. package/src/plugins/defaults/memory/graph-topology/pending-buffer.test.ts +146 -0
  26. package/src/plugins/defaults/memory/graph-topology/pending-buffer.ts +206 -0
  27. package/src/plugins/defaults/memory/injectors.ts +1 -1
  28. package/src/plugins/defaults/memory/job-handlers.ts +2 -2
  29. package/src/plugins/defaults/memory/jobs/__tests__/embed-concept-page.test.ts +2 -2
  30. package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +3 -3
  31. package/src/plugins/defaults/memory/jobs-worker.ts +42 -10
  32. package/src/plugins/defaults/memory/memory-retrospective-enqueue.ts +1 -1
  33. package/src/plugins/defaults/memory/memory-v2-concept-frequency.ts +1 -1
  34. package/src/plugins/defaults/memory/src/__tests__/memory-v2-routes.test.ts +2 -2
  35. package/src/plugins/defaults/memory/src/__tests__/memory-v2-simulate-route.test.ts +4 -3
  36. package/src/plugins/defaults/memory/src/memory-item-routes.test.ts +39 -4
  37. package/src/plugins/defaults/memory/src/memory-item-routes.ts +44 -4
  38. package/src/plugins/defaults/memory/src/memory-v2-routes.ts +10 -10
  39. package/src/plugins/defaults/memory/startup.ts +2 -2
  40. package/src/plugins/defaults/memory/tools.ts +1 -1
  41. package/src/plugins/defaults/memory/v2/__tests__/activation-store.test.ts +1 -1
  42. package/src/plugins/defaults/memory/v2/__tests__/activation.test.ts +4 -3
  43. package/src/plugins/defaults/memory/v2/__tests__/backfill-jobs.test.ts +1 -1
  44. package/src/plugins/defaults/memory/v2/__tests__/injection.test.ts +8 -7
  45. package/src/plugins/defaults/memory/v2/__tests__/reranker.test.ts +2 -2
  46. package/src/plugins/defaults/memory/v2/__tests__/router.test.ts +4 -3
  47. package/src/plugins/defaults/memory/v2/activation-store.ts +1 -1
  48. package/src/plugins/defaults/memory/v2/activation.ts +8 -5
  49. package/src/plugins/defaults/memory/v2/backfill-jobs.ts +2 -2
  50. package/src/plugins/defaults/memory/v2/harness/replay-input.ts +1 -1
  51. package/src/plugins/defaults/memory/v2/harness/retriever.ts +1 -1
  52. package/src/plugins/defaults/memory/v2/injection.ts +15 -9
  53. package/src/plugins/defaults/memory/v2/migration.ts +7 -2
  54. package/src/plugins/defaults/memory/v2/reranker.ts +1 -1
  55. package/src/plugins/defaults/memory/v2/router.ts +4 -4
  56. package/src/plugins/defaults/memory/v3/__tests__/candidate-match.test.ts +2 -2
  57. package/src/plugins/defaults/memory/v3/__tests__/carry-integration.test.ts +1 -1
  58. package/src/plugins/defaults/memory/v3/__tests__/edge.test.ts +1 -1
  59. package/src/plugins/defaults/memory/v3/__tests__/live-integration.test.ts +1 -1
  60. package/src/plugins/defaults/memory/v3/__tests__/maintain-job.test.ts +1 -1
  61. package/src/plugins/defaults/memory/v3/__tests__/orchestrate.test.ts +1 -1
  62. package/src/plugins/defaults/memory/v3/__tests__/shadow-integration.test.ts +1 -1
  63. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +7 -7
  64. package/src/plugins/defaults/memory/v3/candidate-match.ts +2 -2
  65. package/src/plugins/defaults/memory/v3/capabilities.ts +2 -2
  66. package/src/plugins/defaults/memory/v3/card.ts +1 -1
  67. package/src/plugins/defaults/memory/v3/edge.ts +1 -1
  68. package/src/plugins/defaults/memory/v3/maintain-job.ts +3 -3
  69. package/src/plugins/defaults/memory/v3/page-content.ts +2 -2
  70. package/src/plugins/defaults/memory/v3/prune.ts +4 -4
  71. package/src/plugins/defaults/memory/v3/selection-log-store.ts +1 -1
  72. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +2 -2
  73. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/cli-command-store.test.ts +4 -4
  74. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/consolidation-job.test.ts +6 -6
  75. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/frontmatter-sweep.test.ts +2 -2
  76. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/memory-v2-startup.test.ts +4 -4
  77. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/prompts-consolidation.test.ts +1 -1
  78. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/qdrant.test.ts +8 -5
  79. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/sim.test.ts +11 -8
  80. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/skill-content.test.ts +1 -1
  81. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/skill-store.test.ts +8 -8
  82. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/sparse-bm25.test.ts +1 -1
  83. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/static-context.test.ts +3 -3
  84. package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/sweep-job.test.ts +7 -5
  85. package/src/plugins/defaults/memory/{v2 → v3/substrate}/cli-command-store.ts +5 -5
  86. package/src/plugins/defaults/memory/{v2 → v3/substrate}/consolidation-job.ts +9 -9
  87. package/src/plugins/defaults/memory/{v2 → v3/substrate}/frontmatter-sweep.ts +4 -4
  88. package/src/plugins/defaults/memory/{v2 → v3/substrate}/memory-v2-startup.test.ts +4 -4
  89. package/src/plugins/defaults/memory/{v2 → v3/substrate}/memory-v2-startup.ts +9 -9
  90. package/src/plugins/defaults/memory/{v2 → v3/substrate}/page-index.ts +1 -1
  91. package/src/plugins/defaults/memory/{v2 → v3/substrate}/page-store.ts +1 -1
  92. package/src/plugins/defaults/memory/{v2 → v3/substrate}/prompts/consolidation.ts +3 -3
  93. package/src/plugins/defaults/memory/{v2 → v3/substrate}/qdrant.ts +5 -5
  94. package/src/plugins/defaults/memory/{v2 → v3/substrate}/sim.ts +5 -5
  95. package/src/plugins/defaults/memory/{v2 → v3/substrate}/skill-content.ts +1 -1
  96. package/src/plugins/defaults/memory/{v2 → v3/substrate}/skill-store.ts +5 -5
  97. package/src/plugins/defaults/memory/{v2 → v3/substrate}/sparse-bm25.ts +2 -2
  98. package/src/plugins/defaults/memory/{v2 → v3/substrate}/static-context.ts +5 -5
  99. package/src/plugins/defaults/memory/{v2 → v3/substrate}/sweep-job.ts +10 -10
  100. package/src/plugins/defaults/memory/v3-eval/eval-packets.ts +2 -2
  101. package/src/runtime/routes/consolidation-routes.ts +1 -1
  102. package/src/runtime/routes/conversation-query-routes.ts +1 -1
  103. package/src/runtime/routes/secret-routes.ts +1 -1
  104. package/src/workspace/migrations/__tests__/backfill-v3-leaves.test.ts +2 -2
  105. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/concept-page-frontmatter-schema.test.ts +0 -0
  106. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/consolidation-prompt-flag-gating-guard.test.ts +0 -0
  107. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/edge-index.test.ts +0 -0
  108. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/injected-block-slugs.test.ts +0 -0
  109. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/page-index.test.ts +0 -0
  110. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/__tests__/page-store.test.ts +0 -0
  111. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/cli-command-content.ts +0 -0
  112. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/constants.ts +0 -0
  113. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/edge-index.ts +0 -0
  114. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/injected-block-slugs.ts +0 -0
  115. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/prompts/sweep.ts +0 -0
  116. /package/src/plugins/defaults/memory/{v2 → v3/substrate}/types.ts +0 -0
@@ -1,644 +1,115 @@
1
1
  # Memory Architecture
2
2
 
3
- Assistant memory and context-injection architecture details.
3
+ Assistant memory and context-injection architecture.
4
4
 
5
- ## Simplified Memory System (Default)
5
+ ## Tiers
6
6
 
7
- The simplified memory system replaces the legacy item/tier/staleness model with a two-layer architecture: a **brief** (time-relevant context + open loops) plus **archive recall** (observations, chunks, episodes). It is enabled by default via `memory.simplified.enabled: true`.
7
+ An assistant runs exactly one memory tier, derived by `memoryTier()` in
8
+ `src/config/memory-tier.ts`:
8
9
 
9
- ### Architecture Overview
10
+ | Tier | Selected when | Injection source |
11
+ | ----- | -------------------------------------------- | --------------------------------------------- |
12
+ | `off` | `memory.enabled === false` | none |
13
+ | `v3` | `memory.v3.live === true` | v3 lanes + card (`v3/injector.ts`) |
14
+ | `v2` | `memory.v2.enabled === true` and v3 not live | v2 activation/router engine (`v2/`) |
15
+ | `v1` | otherwise | PKB `<knowledge_base>` block (`pkb/`, legacy) |
10
16
 
11
- ```mermaid
12
- graph TB
13
- subgraph "Write Path (Simplified)"
14
- MSG["Incoming Message"] --> REDUCER["Memory Reducer<br/>(LLM-backed, delayed)"]
15
- REDUCER --> TC["time_contexts<br/>(brief state)"]
16
- REDUCER --> OL["open_loops<br/>(brief state)"]
17
- REDUCER --> OBS_R["Archive Observations<br/>(reducer output)"]
18
- REDUCER --> EP_R["Archive Episodes<br/>(reducer output)"]
19
-
20
- MSG --> INDEXER["Dual-Write Indexer"]
21
- INDEXER --> OBS["memory_observations"]
22
- INDEXER --> CHK["memory_chunks<br/>(content-hash deduped)"]
23
-
24
- COMPACT["Context Compaction"] --> EP["memory_episodes"]
25
- end
26
-
27
- subgraph "Read Path (Simplified)"
28
- TURN["User Turn"] --> BRIEF["Memory Brief Compiler"]
29
- BRIEF --> TC
30
- BRIEF --> OL
31
- BRIEF --> BRIEF_OUT["&lt;memory_brief&gt;<br/>Time contexts + Open loops"]
32
-
33
- TURN --> RECALL_GATE["Archive Recall Gate<br/>(keyword + pattern match)"]
34
- RECALL_GATE --> PREFETCH["Prefetch<br/>(episodes + observations)"]
35
- RECALL_GATE --> DEEP["Deeper Recall<br/>(episodes + observations + chunks)"]
36
- DEEP --> RECALL_OUT["&lt;supporting_recall&gt;<br/>Source-linked bullets"]
37
-
38
- BRIEF_OUT --> INJECT["Runtime Injection<br/>(prepend to user message)"]
39
- RECALL_OUT --> INJECT
40
- end
41
-
42
- subgraph "Memory Tools (Simplified)"
43
- SAVE["memory_save"] --> OBS
44
- RECALL_TOOL["memory_recall"] --> RECALL_GATE
45
- end
46
- ```
47
-
48
- ### Tables
49
-
50
- | Table | Purpose | Write source |
51
- | --------------------- | ----------------------------------------------- | ------------------------------------------------------- |
52
- | `time_contexts` | Bounded temporal windows for the brief | Reducer |
53
- | `open_loops` | Unresolved follow-up items for the brief | Reducer |
54
- | `memory_observations` | Raw factual statements from conversation turns | Indexer dual-write, reducer, memory_save tool, backfill |
55
- | `memory_chunks` | Deduplicated content units for embedding/recall | Derived from observations, content-hash deduped |
56
- | `memory_episodes` | Narrative summaries of interaction spans | Compaction, reducer, backfill |
57
-
58
- ### Reducer
59
-
60
- The memory reducer is a provider-backed (LLM) background process that analyzes unreduced conversation turns and produces structured CRUD operations for brief-state tables and archive candidates. It runs on a delay after conversation idle or switch, scheduled via the `reduce_conversation_memory` job. The reducer is side-effect-free; results are applied transactionally via `applyReducerResult`.
61
-
62
- ### Brief
63
-
64
- The memory brief is compiled fresh on every turn from active `time_contexts` and `open_loops`. It is rendered as `<memory_brief>` XML and injected as a text block prepended to the user message. Empty sections are omitted.
65
-
66
- ### Archive Recall
67
-
68
- Archive recall runs when the user's turn triggers a recall gate (past-reference language, analogy/debugging patterns, or strong prefetch hits). It queries episodes, observations, and chunks via keyword matching and returns up to 3 source-linked bullets in `<supporting_recall>`. No recall tag is emitted when results are empty.
69
-
70
- ### Backfill
71
-
72
- Existing users have legacy data in `memory_segments`, `memory_summaries`, and `memory_items`. The `backfill_simplified_memory` job migrates this data into the simplified tables:
73
-
74
- - `memory_segments` -> `memory_observations` + `memory_chunks`
75
- - `memory_summaries` -> `memory_episodes`
76
- - Active, high-confidence `memory_items` -> `memory_observations` + `memory_chunks`, with unambiguous items also mapped to `time_contexts` or `open_loops`
77
-
78
- The backfill is idempotent (content-hash dedup + checkpoint tracking), processes in batches of 200, and self-enqueues continuation jobs for large datasets.
79
-
80
- ### Rollback Posture
81
-
82
- The legacy memory system remains fully available as a short-lived rollback path:
83
-
84
- - **Legacy tables are preserved**: `memory_segments`, `memory_items`, `memory_summaries`, and `memory_item_sources` remain in the schema and continue to receive writes from the legacy indexer/extraction pipeline.
85
- - **Flag-gated**: Setting `memory.simplified.enabled: false` reverts to the legacy item/tier/staleness model for both read and write paths.
86
- - **Memory tools**: `memory_save` and `memory_recall` check the flag at call time and route to the appropriate path (simplified observations or legacy items).
87
- - **No data loss**: The backfill copies data without deleting legacy rows. Both systems can coexist.
88
-
89
- ### Key Files
90
-
91
- | File | Role |
92
- | ----------------------------------------------------------------- | ------------------------------------------------ |
93
- | `assistant/src/config/schemas/memory-simplified.ts` | Config schema with `enabled: true` default |
94
- | `assistant/src/memory/reducer.ts` | Provider-backed reducer (LLM call + parse) |
95
- | `assistant/src/memory/reducer-store.ts` | Transactional result application |
96
- | `assistant/src/memory/reducer-scheduler.ts` | Idle-delay and conversation-switch scheduling |
97
- | `assistant/src/memory/archive-store.ts` | Observation/chunk/episode write helpers |
98
- | `assistant/src/memory/archive-recall.ts` | Prefetch + deeper recall over archive tables |
99
- | `assistant/src/memory/brief.ts` | Brief composer (time contexts + open loops) |
100
- | `assistant/src/memory/job-handlers/backfill-simplified-memory.ts` | Legacy data migration handler |
101
- | `assistant/src/tools/memory/handlers.ts` | Memory tool handlers (simplified/legacy routing) |
102
- | `assistant/src/__tests__/simplified-memory-e2e.test.ts` | End-to-end test suite |
103
-
104
- ---
105
-
106
- ## Legacy Memory System — Daemon Data Flow
107
-
108
- > **Note**: The legacy system below is retained as rollback support. New installations use the simplified system by default.
109
-
110
- ## Memory System — Daemon Data Flow
111
-
112
- ```mermaid
113
- graph TB
114
- subgraph "Write Path"
115
- MSG_IN["Incoming Message<br/>(HTTP)"]
116
- STORE["ConversationStore.addMessage()<br/>Drizzle ORM → SQLite"]
117
- INDEX["Memory Indexer"]
118
- SEGMENT["Split into segments<br/>→ memory_segments"]
119
- EXTRACT_JOB["Enqueue extract_items job<br/>→ memory_jobs"]
120
- SUMMARY_JOB["Enqueue build_conversation_summary<br/>→ memory_jobs"]
121
- end
122
-
123
- subgraph "Background Worker (polls every 1.5s)"
124
- WORKER["MemoryJobsWorker"]
125
- EMBED_SEG["embed_segment<br/>→ Qdrant (dense + sparse)"]
126
- EMBED_ITEM["embed_item<br/>→ Qdrant (dense + sparse)"]
127
- EMBED_SUM["embed_summary<br/>→ Qdrant (dense + sparse)"]
128
- EXTRACT["extract_items<br/>→ memory_items +<br/>memory_item_sources<br/>(LLM-directed supersession)"]
129
- CLEAN_SUPERSEDED["cleanup_stale_superseded_items<br/>delete stale superseded items<br/>and Qdrant vectors"]
130
- BUILD_SUM["build_conversation_summary<br/>→ memory_summaries"]
131
- end
132
-
133
- subgraph "Embedding Provider Selection (selectEmbeddingBackend)"
134
- PROVIDER_SELECT["Provider Selection<br/>auto: local → OpenAI → Gemini → Ollama<br/>or explicit config override"]
135
- LOCAL_EMB["Local (ONNX)<br/>bge-small-en-v1.5"]
136
- OAI_EMB["OpenAI<br/>text-embedding-3-small"]
137
- GEM_EMB["Gemini<br/>gemini-embedding-001"]
138
- OLL_EMB["Ollama<br/>nomic-embed-text"]
139
- end
140
-
141
- subgraph "Sparse Embedding (in-process)"
142
- SPARSE_GEN["generateSparseEmbedding()<br/>TF-IDF, FNV-1a hashing<br/>(no external calls)"]
143
- end
144
-
145
- subgraph "Qdrant Vector Store"
146
- DENSE["Named vector: dense<br/>(cosine similarity)"]
147
- SPARSE["Named vector: sparse<br/>(TF-IDF based)"]
148
- RRF["Query API:<br/>Reciprocal Rank Fusion"]
149
- end
150
-
151
- subgraph "Read Path (Memory Recall)"
152
- NEEDS_MEM["needsMemory gate<br/>(skip short/empty/tool-result turns)"]
153
- QUERY["Recall Query Builder<br/>User request + compacted context summary"]
154
- BUDGET["Dynamic Recall Budget<br/>computeRecallBudget()<br/>from prompt headroom"]
155
- EMBED_Q["Generate dense + sparse<br/>query embeddings"]
156
- HYBRID["Hybrid Search<br/>dense + sparse RRF on Qdrant"]
157
- MERGE["Merge + Deduplicate<br/>weighted score combination"]
158
- TIER["Tier Classification<br/>score > 0.8 → tier 1<br/>score > 0.6 → tier 2<br/>below → dropped"]
159
- STALE["Staleness Computation<br/>kind-specific lifetimes<br/>+ reinforcement from<br/>source conversation count"]
160
- DEMOTE["Stale Demotion<br/>very_stale tier 1 → tier 2"]
161
- INJECT["Two-Layer XML Injection<br/>budget-aware rendering"]
162
- TELEMETRY["Emit memory_recalled<br/>tier counts + hybrid search ms +<br/>staleness stats"]
163
- end
164
-
165
- subgraph "Context Window Management"
166
- CTX["Session Context"]
167
- COMPACT["Compaction trigger<br/>(approaching token limit)"]
168
- GUARDS["Cooldown + early-exit guards<br/>with severe-pressure override"]
169
- SUMMARIZE["Summarize old messages<br/>→ context_summary on conversation"]
170
- REPLACE["Replace old messages<br/>with summary in context<br/>(originals stay in DB)"]
171
- end
172
-
173
- subgraph "Overflow Recovery (context-overflow-reducer.ts)"
174
- OVF_PRE["Preflight budget check<br/>estimate > maxInputTokens × (1 − safetyMarginRatio)"]
175
- OVF_T1["Tier 1: Forced compaction<br/>force=true, minKeepRecentUserTurns=0"]
176
- OVF_T2["Tier 2: Tool-result truncation<br/>4,000 chars per result"]
177
- OVF_T3["Tier 3: Media/file stubbing"]
178
- OVF_T4["Tier 4: Injection downgrade<br/>→ minimal mode"]
179
- OVF_LATEST["Auto-compress latest turn<br/>(force=true, minKeepRecentUserTurns=0)"]
180
- end
181
-
182
- MSG_IN --> STORE
183
- STORE --> INDEX
184
- INDEX --> SEGMENT
185
- INDEX --> EXTRACT_JOB
186
- INDEX --> SUMMARY_JOB
187
-
188
- WORKER --> EMBED_SEG
189
- WORKER --> EMBED_ITEM
190
- WORKER --> EMBED_SUM
191
- WORKER --> EXTRACT
192
- WORKER --> CLEAN_SUPERSEDED
193
- WORKER --> BUILD_SUM
194
-
195
- EMBED_SEG --> PROVIDER_SELECT
196
- EMBED_ITEM --> PROVIDER_SELECT
197
- EMBED_SUM --> PROVIDER_SELECT
198
- PROVIDER_SELECT --> LOCAL_EMB
199
- PROVIDER_SELECT --> OAI_EMB
200
- PROVIDER_SELECT --> GEM_EMB
201
- PROVIDER_SELECT --> OLL_EMB
202
- LOCAL_EMB --> DENSE
203
- OAI_EMB --> DENSE
204
- GEM_EMB --> DENSE
205
- OLL_EMB --> DENSE
206
- EMBED_SEG --> SPARSE_GEN
207
- EMBED_ITEM --> SPARSE_GEN
208
- EMBED_SUM --> SPARSE_GEN
209
- SPARSE_GEN --> SPARSE
210
-
211
- NEEDS_MEM --> QUERY
212
- QUERY --> EMBED_Q
213
- EMBED_Q --> PROVIDER_SELECT
214
- EMBED_Q --> SPARSE_GEN
215
- EMBED_Q --> HYBRID
216
- HYBRID --> RRF
217
- HYBRID --> MERGE
218
- MERGE --> TIER
219
- TIER --> STALE
220
- STALE --> DEMOTE
221
- BUDGET --> INJECT
222
- DEMOTE --> INJECT
223
- INJECT --> TELEMETRY
224
-
225
- CTX --> COMPACT
226
- COMPACT --> GUARDS
227
- GUARDS --> SUMMARIZE
228
- SUMMARIZE --> REPLACE
229
-
230
- %% Overflow recovery flow
231
- CTX --> OVF_PRE
232
- OVF_PRE --> OVF_T1
233
- OVF_T1 --> OVF_T2
234
- OVF_T2 --> OVF_T3
235
- OVF_T3 --> OVF_T4
236
- OVF_T4 --> OVF_LATEST
237
- OVF_LATEST -.->|"uses"| SUMMARIZE
238
- OVF_T1 -.->|"uses"| SUMMARIZE
239
- ```
240
-
241
- ### Context Compaction and Overflow Recovery Interaction
242
-
243
- Normal context compaction (the "Context Window Management" subgraph above) runs proactively as the conversation approaches the token limit, using cooldown guards and a severity-pressure override to balance compaction frequency against cost. This is the primary defense against context overflow.
244
-
245
- When compaction alone is insufficient — either because the conversation grew too fast between turns or because a single turn contains extremely large payloads — the overflow recovery pipeline takes over. The pipeline's first tier (forced compaction) reuses the same `maybeCompact()` summarization machinery but with emergency parameters: `force: true` bypasses cooldown guards and `minKeepRecentUserTurns: 0` allows summarizing even the most recent history. The reducer drives convergence toward a tighter budget by re-invoking each tier until the estimated tokens fall under its `targetTokens` ceiling. Subsequent tiers (tool-result truncation, media stubbing, injection downgrade) apply progressively more aggressive payload reduction without involving the summarizer.
246
-
247
- If all four reducer tiers are exhausted, the overflow policy resolver determines whether to compress the latest user turn. All sessions — interactive and non-interactive alike — auto-compress the latest turn without prompting. The only explicit opt-out is setting `contextWindow.overflowRecovery.interactiveLatestTurnCompression` (or `nonInteractiveLatestTurnCompression`) to `"drop"`, which short-circuits to a graceful failure instead. Disabling overflow recovery entirely (`contextWindow.overflowRecovery.enabled: false`) also yields a graceful failure.
248
-
249
- The key distinction: normal compaction is a cost-optimized background process that preserves conversational quality; overflow recovery is a convergence mechanism that prioritizes session survival over context richness. Both share the same summarization infrastructure but operate under different pressure thresholds and constraints.
250
-
251
- ### Memory Retrieval Config Knobs (Defaults)
252
-
253
- | Config key | Default | Purpose |
254
- | ----------------------------------------------------- | ------------------------: | -------------------------------------------------------------------- |
255
- | `memory.retrieval.dynamicBudget.enabled` | `true` | Toggle per-turn recall budget calculation from live prompt headroom. |
256
- | `memory.retrieval.dynamicBudget.minInjectTokens` | `2400` | Lower clamp for computed recall injection budget. |
257
- | `memory.retrieval.dynamicBudget.maxInjectTokens` | `16000` | Upper clamp for computed recall injection budget. |
258
- | `memory.retrieval.dynamicBudget.targetHeadroomTokens` | `10000` | Reserved headroom to keep free for response generation/tool traces. |
259
- | `memory.retrieval.maxInjectTokens` | `16000` | Static fallback when dynamic budget is disabled. |
260
- | `memory.retrieval.scopePolicy` | `'allow_global_fallback'` | Scope filtering strategy: `'strict'` or `'allow_global_fallback'`. |
261
-
262
- ### Memory Recall Debugging Playbook
263
-
264
- 1. Run a recall-heavy turn and inspect `memory_recalled` events in the client trace stream.
265
- 2. Validate baseline counters:
266
- - `semanticHits`
267
- - `tier1Count`, `tier2Count`
268
- - `hybridSearchLatencyMs`
269
- - `mergedCount`, `selectedCount`, `injectedTokens`, `latencyMs`
270
- 3. Cross-check context pressure with `context_compacted` events:
271
- - `previousEstimatedInputTokens` vs `estimatedInputTokens`
272
- - `summaryCalls`, `compactedMessages`
273
- 4. If dynamic budget is enabled, verify `injectedTokens` stays within the configured min/max clamps for `dynamicBudget`.
274
- 5. Inspect staleness distribution in debug logs:
275
- - `fresh`, `aging`, `stale`, `very_stale` counts
276
- - Check for unexpected tier demotions (very_stale tier 1 items demoted to tier 2)
277
- 6. Before tuning ranking settings, run:
278
- - `cd assistant && bun test src/__tests__/context-memory-e2e.test.ts`
279
- - `cd assistant && bun test src/__tests__/memory-context-benchmark.benchmark.test.ts`
280
- - `cd assistant && bun test src/__tests__/memory-recall-quality.test.ts`
281
- 7. After tuning, rerun the same suite and compare:
282
- - tier counts (coverage)
283
- - selected count / injected tokens (budget safety)
284
- - latency and ordering regressions via top candidate snapshots
285
-
286
- ### Write Path — Extraction and Supersession
287
-
288
- ```mermaid
289
- stateDiagram-v2
290
- [*] --> ActiveItem : extract_items\n(LLM or pattern-based)
291
- ActiveItem --> Superseded : explicit supersession\n(overrideConfidence = "explicit"\n+ supersedes = oldItemId)
292
- ActiveItem --> ActiveItem : tentative/inferred override\n(both items coexist)
293
- ActiveItem --> Superseded : subject-match fallback\n(same kind + subject,\nno LLM-directed supersession)
294
- Superseded --> Cleanup : cleanup_stale_superseded_items\n(delete from DB + Qdrant)
295
- ```
296
-
297
- **Item extraction** uses LLM-powered extraction (with pattern-based fallback) to identify memorable information from conversation messages. Each extracted item belongs to one of eight kinds:
298
-
299
- | Kind | Description | Base Lifetime |
300
- | ------------ | -------------------------------------------------------------------- | ------------- |
301
- | `identity` | Personal info, facts, relationships | 6 months |
302
- | `preference` | Likes, dislikes, preferred approaches/tools | 3 months |
303
- | `journal` | Experiential reflections, journal-style notes, forward-looking items | 3 months |
304
- | `constraint` | Rules, requirements, directives | 1 month |
305
- | `project` | Project details, repos, tech stacks, action items | 2 weeks |
306
- | `decision` | Choices made, approaches selected | 2 weeks |
307
- | `event` | Deadlines, milestones, meetings, dates | 3 days |
308
- | `capability` | Skill catalog entries (system-generated, not LLM-extracted) | never expires |
309
-
310
- **Supersession chains** replace the old conflict resolution system. When the LLM extracts a new item that updates an existing one, it sets `supersedes` to the old item's ID and `overrideConfidence` to one of three levels:
311
-
312
- - `explicit` — Clear override signal (e.g. "I changed my mind about X"). The old item is marked `superseded` and removed from Qdrant.
313
- - `tentative` — Ambiguous; both items coexist as active.
314
- - `inferred` — Weak signal; both items coexist (logged for observability).
315
-
316
- A fallback subject-match supersession also runs for items without LLM-directed supersession: same kind + same subject = old item superseded.
317
-
318
- **Semantic density gating** skips extraction for messages that are too short, consist of low-value filler (e.g. "ok", "thanks", "got it"), or have fewer than 3 words.
319
-
320
- ### Read Path — Hybrid Recall Pipeline
321
-
322
- The recall pipeline runs on every turn that passes the `needsMemory` gate (skips empty, very short, and tool-result-only turns). The pipeline is orchestrated by `buildMemoryRecall()` in `retriever.ts`:
323
-
324
- 1. **Query construction** (`query-builder.ts`): Combines the user request text (up to 2000 chars) with any in-context session summary (up to 1200 chars).
325
-
326
- 2. **Dense + sparse embedding generation**: The query is embedded using the configured embedding provider (auto-selection order: local → OpenAI → Gemini → Ollama). A TF-IDF sparse embedding is also generated in-process using FNV-1a hashing to a 30K vocabulary with sub-linear TF weighting and L2 normalization.
327
-
328
- 3. **Hybrid search on Qdrant**: When both dense and sparse vectors are available, the pipeline uses Qdrant's query API with two prefetch stages (dense and sparse, each fetching up to 40 candidates) fused via Reciprocal Rank Fusion (RRF). Falls back to dense-only search when sparse vectors are unavailable.
329
-
330
- 4. **Merge and deduplicate**: Hybrid candidates are deduplicated by key. A weighted final score is computed: `0.4 + importance * 0.25 + confidence * 0.15 + recency * 0.2`, where `recency` is a logarithmic time-decay score (ACT-R inspired) based on when the item was last seen.
331
-
332
- 5. **Tier classification** (`tier-classifier.ts`): Score-based, deterministic classification:
333
- - `finalScore > 0.8` → **tier 1** (high relevance)
334
- - `finalScore > 0.6` → **tier 2** (possibly relevant)
335
- - Below 0.6 → dropped
336
-
337
- 6. **Staleness computation** (`staleness.ts`): Each item candidate is annotated with a staleness level based on its age relative to a kind-specific base lifetime (see table above). The effective lifetime is extended by a reinforcement factor: `baseLifetime * (1 + 0.3 * (sourceConversationCount - 1))`, so items mentioned across multiple conversations age more slowly. Staleness levels:
338
- - `ratio < 0.5` → `fresh`
339
- - `ratio <= 1.0` → `aging`
340
- - `ratio <= 2.0` → `stale`
341
- - `ratio > 2.0` → `very_stale`
342
-
343
- 7. **Stale demotion**: `very_stale` tier 1 candidates are demoted to tier 2, preventing old information from occupying prime injection space.
344
-
345
- 8. **Two-layer XML injection** (`formatting.ts`): Budget-aware rendering into four XML sections:
346
-
347
- ```xml
348
- <memory_context __injected>
349
-
350
- <user_identity>
351
- <!-- identity-kind tier 1 items (plain statements) -->
352
- </user_identity>
353
-
354
- <relevant_context>
355
- <!-- tier 1 non-identity/non-preference items (episode-wrapped with source attribution) -->
356
- </relevant_context>
357
-
358
- <applicable_preferences>
359
- <!-- preference/constraint tier 1 items (plain statements) -->
360
- </applicable_preferences>
17
+ New workspaces are switched to `v3` at creation (workspace migration 105).
18
+ `v1` and the `v2` injection engine are in retirement; v3 is the target state.
361
19
 
362
- <possibly_relevant>
363
- <!-- tier 2 items (episode-wrapped with staleness annotations) -->
364
- </possibly_relevant>
20
+ ## The concept-page substrate (`v3/substrate/`)
365
21
 
366
- </memory_context>
367
- ```
22
+ The durable core shared by v2 and v3 is the **concept-page substrate**:
23
+ markdown articles under `memory/concepts/` (plus the aggregate views
24
+ `essentials.md`, `threads.md`, `recent.md` and the intake `buffer.md`), their
25
+ cached page index, and the concept-page Qdrant collection with dense + BM25
26
+ sparse vectors. It lives in
27
+ `src/plugins/defaults/memory/v3/substrate/` because it is memory-v3's
28
+ foundation — the v2 injection engine is just a second (transitional) consumer.
368
29
 
369
- Empty sections are omitted. Each section has a per-item token budget (150 tokens for tier 1, 100 for tier 2). Tier 1 sections consume budget first; tier 2 uses the remainder.
30
+ Substrate activation is a single predicate, `usesConceptPageMemory()` in
31
+ `src/config/memory-v3-gate.ts`: memory on AND (`memory.v3.live` OR
32
+ `memory.v2.enabled`). Every substrate gate — the write path, consolidation
33
+ scheduling, boot-time maintenance, capability seeding, the static `<info>`
34
+ memory block, and the v1-machinery suppressions — keys on it. When the v2
35
+ engine is removed, the predicate collapses to `memory.enabled`.
370
36
 
371
- 9. **Injection strategy**: The rendered `<memory_context __injected>` block is prepended as a text content block to the last user message (`injectMemoryRecallAsUserBlock`), following the same pattern as workspace, temporal, and other runtime injections. Stripping is handled by the generic `stripUserTextBlocksByPrefix` mechanism matching the `<memory_context __injected>` prefix (with a backward-compat entry for the legacy `<memory_context>` prefix from older history). This avoids synthetic message pairs and preserves prompt prefix caching between turns.
372
-
373
- ### Internal-Only Trust Gating
374
-
375
- **Provenance-aware pipeline**: Every persisted message carries provenance metadata (`provenanceTrustClass`, `provenanceSourceChannel`, etc.) derived from the `TrustContext` resolved by `trust-context-resolver.ts`.
376
-
377
- Two trust gates enforce trust-class-based access control over the memory pipeline:
378
-
379
- - **Write gate** (`indexer.ts`): The `extract_items` job only runs for messages from trusted actors (guardian or undefined provenance). Messages from untrusted actors (`trusted_contact`, `unknown`) are still segmented and embedded — so they appear in conversation context — but no item extraction is triggered. This prevents untrusted channels from injecting or mutating long-term memory items.
380
-
381
- - **Read gate** (`conversation-memory.ts`): When the current session's actor is untrusted, the memory recall pipeline returns a no-op context — no recall injection. This ensures untrusted actors cannot surface or exploit previously extracted memory.
382
-
383
- Trust policy is **cross-channel and trust-class-based**: decisions use `trustContext.trustClass`, not the channel string. Desktop sessions default to `trustClass: 'guardian'`. External channels (Telegram, WhatsApp, phone) provide explicit trust context via the resolver. Messages without provenance metadata are treated as trusted (guardian); all new messages carry provenance.
384
-
385
- ### Embedding Backend Selection
386
-
387
- The embedding backend is selected based on `memory.embeddings.provider` config:
388
-
389
- - `auto` (default): Tries local → OpenAI → Gemini → Ollama, using the first available.
390
- - `local`: ONNX-based local model (bge-small-en-v1.5). Lazy-loaded to avoid crashing in compiled binaries where onnxruntime-node is unavailable.
391
- - `openai`: OpenAI text-embedding-3-small. Requires an OpenAI API key in secure storage.
392
- - `gemini`: Gemini gemini-embedding-001. Requires a Gemini API key in secure storage. Only backend supporting multimodal embeddings (images, audio, video).
393
- - `ollama`: Ollama nomic-embed-text. Requires Ollama to be configured.
394
-
395
- An in-memory LRU vector cache (32 MB cap, keyed by `sha256(provider + model + content)`) avoids redundant embedding calls for identical content. Sparse embeddings are generated in-process (no external calls).
396
-
397
- ### Graceful Degradation
398
-
399
- When the embedding backend or Qdrant is unavailable:
400
-
401
- - A **circuit breaker** on Qdrant (`qdrant-circuit-breaker.ts`) tracks consecutive failures and short-circuits search calls when the breaker is open.
402
- - If embedding generation fails and `memory.embeddings.required` is `true`, recall returns an empty result with a degradation status (`embedding_generation_failed` or `embedding_provider_down`).
403
- - If embeddings are optional (default), the pipeline returns empty results (no fallback search path exists without Qdrant).
404
- - Degradation status is reported to clients via `memory_status` events.
405
-
406
- ### Embedding Dimension Reconciliation
407
-
408
- The embedding dimension is a **committed property of the Qdrant collection**, derived from the dimension of whichever embedding backend built it. It is not a free-standing config value the user picks: `memory.qdrant.vectorSize` records the dimension the collections were created at, and reconciliation keeps that record consistent with the reachable backend.
409
-
410
- `reconcileEmbeddingIdentity` (`assistant/src/daemon/embedding-reconcile.ts`) runs once at daemon startup. It reads the committed collection dimension and probes the configured backend in parallel, then routes both observations through the pure `decideEmbeddingReconcile` (`assistant/src/persistence/embeddings/reconcile-decision.ts`) and executes the resulting action. A transient backend outage **degrades** (recall returns empty results, surfaced via `memory_worker_status`'s `embedding.degraded` flag) — it never destroys the collection.
411
-
412
- #### Decision table
413
-
414
- | Probe | Committed dim | Provider | Action | Effect |
415
- | --------------------------- | ------------- | ----------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
416
- | down (no reachable backend) | — | — | `defer-degraded` | No write, no destructive call. Warn and leave the collection untouched. |
417
- | up | none | — | `commit-fresh` | Adopt the probed dimension: commit it, ensure the collections exist at it (create-if-absent), enqueue a reembed. |
418
- | up | matches probe | — | `noop` | No writes. |
419
- | up | mismatch | explicit (`openai` / `gemini` / `ollama`) | `migrate` | Deliberate intent, confirmed by a successful probe: commit the new dim, destroy + recreate the collections, enqueue a reembed. The only destructive path. |
420
- | up | mismatch | `auto` | `noop` | No thrash. Under `auto` the reachable backend can flip between a small local model (384) and a large managed model (3072) on transient availability, so a per-boot mismatch is not allowed to recreate the collection. |
421
-
422
- Confirm-before-destroy: a destructive recreate runs only on a `migrate` action, and only after a non-null backend probe. This makes the dimension change depend on the backend being reachable rather than on a config flag written before the backend is known to answer.
423
-
424
- #### Platform intent is a fill-only deployment default
425
-
426
- Platform deployments express an embedding-provider preference through `getDeploymentContextDefaults` in `assistant/src/config/loader.ts`: when `IS_PLATFORM` is set, the loader **fills** `memory.embeddings.provider: "gemini"` as an in-memory default. This default is layered at config-load time and is **not persisted** to `config.json`, and it does **not** set `memory.qdrant.vectorSize` or `geminiModel`. The dimension stays derived from the live probe; the explicit provider only lifts a genuine upgrade from `noop` (auto) to `migrate` (explicit) in the decision table above. There is no config migration that writes a provider or dimension to disk.
427
-
428
- #### Lazy ensure vs. startup reconcile
429
-
430
- The lazy `ensureCollection` paths (`ensureConceptPageCollection` in `assistant/src/memory/v2/qdrant.ts`, `ensureSectionCollection` for v3) **create-if-absent only** for the committed dimension. They never perform a dimension migration — destructive dimension change is owned solely by the startup reconcile's `migrate` action. The lazy paths still recreate on **schema drift**: a collection missing a required named vector (e.g. an unnamed-vector layout, or one lacking `summary_dense` / `summary_sparse`) is rebuilt and signalled via `{ migrated: true }` so callers enqueue a backfill.
431
-
432
- ---
433
-
434
- ## Workspace Context Injection — Directory Awareness
435
-
436
- The session injects a `<workspace>` directory listing into the first user message and after compaction, giving the model awareness of the sandbox filesystem structure. The block persists in conversation history (old-format `<workspace_top_level>` blocks from pre-change history are stripped for backward compatibility).
437
-
438
- ### Lifecycle
439
-
440
- ```mermaid
441
- graph TB
442
- subgraph "Per-Turn Flow"
443
- CHECK{"workspaceTopLevelDirty<br/>OR first turn?"}
444
- SCAN["scanTopLevelDirectories(workingDir)<br/>→ TopLevelSnapshot"]
445
- RENDER["renderWorkspaceTopLevelContext(snapshot)<br/>→ XML text block"]
446
- CACHE["Cache rendered text<br/>workspaceTopLevelDirty = false"]
447
- INJECT["applyRuntimeInjections<br/>prepend workspace block<br/>to user message"]
448
- AGENT["AgentLoop.run(runMessages)"]
449
- end
450
-
451
- subgraph "Dirty Triggers (tool_result handler)"
452
- FILE_EDIT["file_edit (success)"]
453
- FILE_WRITE["file_write (success)"]
454
- BASH["bash (success)"]
455
- DIRTY["markWorkspaceTopLevelDirty()"]
456
- end
457
-
458
- CHECK -->|dirty or null| SCAN
459
- CHECK -->|clean| INJECT
460
- SCAN --> RENDER
461
- RENDER --> CACHE
462
- CACHE --> INJECT
463
- INJECT --> AGENT
464
-
465
- FILE_EDIT --> DIRTY
466
- FILE_WRITE --> DIRTY
467
- BASH --> DIRTY
468
- ```
469
-
470
- ### Key design decisions
471
-
472
- - **Scope**: Sandbox workspace only (`$VELLUM_WORKSPACE_DIR`). Non-recursive — only top-level directories.
473
- - **Bounded**: Maximum 120 directory entries (`MAX_TOP_LEVEL_ENTRIES`). Excess is truncated with a note.
474
- - **Prepend, not append**: The workspace block is prepended to the user message content so that Anthropic cache breakpoints continue to land on the trailing user text block, preserving prompt cache efficiency.
475
- - **Persists in history**: The injected `<workspace>` block persists in conversation history, giving the model workspace grounding across turns. Legacy `<workspace_top_level>` blocks from pre-change history are stripped for backward compatibility.
476
- - **Dirty-refresh**: The scanner runs once on the first turn, then only re-runs after a successful mutation tool (`file_edit`, `file_write`, `bash`). Failed tool results do not trigger a refresh.
477
- - **Injection ordering**: Workspace context is injected after other runtime injections (active surface, etc.) via `applyRuntimeInjections`, but because it is **prepended** to content blocks, it appears first in the final message.
478
-
479
- ### Cache compatibility
480
-
481
- The Anthropic provider places `cache_control: { type: 'ephemeral' }` on the **last content block** of the last two user turns. Since workspace context is prepended (first block), the cache breakpoint correctly lands on the trailing user text block. This is validated by dedicated cache-compatibility tests.
482
-
483
- ### Key files
484
-
485
- | File | Role |
486
- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
487
- | `assistant/src/workspace/top-level-scanner.ts` | Synchronous directory scanner with `MAX_TOP_LEVEL_ENTRIES` cap |
488
- | `assistant/src/workspace/top-level-renderer.ts` | Renders `TopLevelSnapshot` to `<workspace>` XML block |
489
- | `assistant/src/daemon/conversation-runtime-assembly.ts` | Runtime injections and legacy-block strip helpers (`<workspace>`, `<turn_context>`, `<channel_onboarding_playbook>`, `<onboarding_mode>`) |
490
- | `assistant/src/onboarding/onboarding-orchestrator.ts` | Builds assistant-owned onboarding runtime guidance from channel playbook + transport metadata |
491
- | `assistant/src/daemon/conversation-agent-loop.ts` | Agent loop orchestration, runtime injection wiring, legacy-block strip chain |
492
-
493
- ---
494
-
495
- ## Turn Context Injection — Date & Actor Grounding
496
-
497
- The session injects a unified `<turn_context>` block into every user message, giving the model awareness of the current timestamp (with timezone), interface, channel, and actor identity. This replaces the former separate `<temporal_context>`, `<inbound_actor_context>`, and per-channel turn context blocks. The unified block persists in conversation history so the assistant retains temporal and actor grounding across turns. Legacy blocks from pre-change history are stripped for backward compatibility.
498
-
499
- The `current_time:` field format is: `2026-04-02 (Wednesday) 14:30:00 -05:00 (America/Chicago)` — date, weekday name, local time, UTC offset, and IANA timezone name. The timestamp is grounded in the user's effective timezone, not UTC, so a message sent at 10pm local time is represented as 10pm for date/time reasoning.
500
-
501
- ### Per-turn flow
37
+ ### Write path
502
38
 
503
39
  ```mermaid
504
- graph TB
505
- subgraph "Per-Turn Flow"
506
- BUILD["buildUnifiedTurnContextBlock()<br/>→ unified XML block with timestamp,<br/>actor context, channel context"]
507
- INJECT["applyRuntimeInjections<br/>prepend turn_context block<br/>to user message"]
508
- AGENT["AgentLoop.run(runMessages)"]
509
- end
510
-
511
- BUILD --> INJECT
512
- INJECT --> AGENT
40
+ graph LR
41
+ REM["remember tool /<br/>POST /v1/memory/remember"] --> BUF["memory/buffer.md<br/>+ archive/&lt;date&gt;.md"]
42
+ SWEEP["idle sweep (opt-in)"] --> BUF
43
+ BUF --> CONS["memory_v2_consolidate job<br/>(background agent run)"]
44
+ CONS --> PAGES["concept pages<br/>memory/concepts/**"]
45
+ CONS --> VIEWS["essentials / threads / recent"]
46
+ CONS --> REEMBED["memory_v2_reembed →<br/>concept-page Qdrant collection"]
47
+ CONS --> MAINT["memory_v3_maintain<br/>(v3-live follow-up)"]
513
48
  ```
514
49
 
515
- ### Key design decisions
516
-
517
- - **Fresh each turn**: `buildUnifiedTurnContextBlock()` is called at the start of every agent loop invocation, ensuring the model always sees the current timestamp even in long-running conversations.
518
- - **Clock source invariant**: Absolute time (`now`) always comes from the assistant host clock (`Date.now()`), never from channel/client clocks.
519
- - **Timezone precedence**: Turn context resolves the effective timezone in this order: explicit runtime override for tests/legacy callers, manual `ui.userTimezone`, current turn `clientTimezone`, persisted `ui.detectedTimezone`, then assistant host timezone. The host clock still supplies the absolute instant; this cascade only selects the local timezone used to render `current_time`.
520
- - **Manual override semantics**: `ui.userTimezone` is a historical config path, but it is runtime-affecting, not purely presentational. When set, it is authoritative for `current_time` across all clients until the user clears or changes it.
521
- - **Device timezone semantics**: `clientTimezone` is the timezone reported with the active message for this turn. `ui.detectedTimezone` is the last device-detected timezone persisted by a client and is only used when there is no manual override and the current message does not carry a client timezone.
522
- - **Timezone mismatch guidance**: When `ui.userTimezone` differs from the current device timezone (`clientTimezone`, or `ui.detectedTimezone` when no current client value exists), `<turn_context>` also includes `configured_user_timezone`, `client_device_timezone`, and `timezone_update_available`. The last line tells the assistant that, after explicit user confirmation, it can persist the device timezone with `assistant config set ui.userTimezone "<IANA zone>"`. This gives the assistant a natural-language path to fix stale manual overrides without adding a dedicated tool.
523
- - **Timezone-aware**: Uses `Intl.DateTimeFormat` APIs for DST-safe date arithmetic and timezone validation/canonicalization.
524
- - **Persists in history**: The `<turn_context>` block persists in conversation history. Legacy `<temporal_context>`, `<inbound_actor_context>`, and separate channel context blocks from pre-change history are stripped for backward compatibility.
525
- - **Retry paths**: Turn context is included in all `applyRuntimeInjections` call sites (main path, compact retry, media-trim retry).
526
-
527
- ### Key files
528
-
529
- | File | Role |
530
- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
531
- | `assistant/src/daemon/date-context.ts` | `formatTurnTimestamp()` — generates the timestamp string used in `<turn_context>` |
532
- | `assistant/src/daemon/conversation-runtime-assembly.ts` | `buildUnifiedTurnContextBlock()` — constructs the unified `<turn_context>` block; legacy block strip helpers |
533
- | `assistant/src/daemon/conversation-agent-loop.ts` | Wiring: builds turn context, passes to `applyRuntimeInjections` |
534
-
535
- ---
536
-
537
- ## Workspace Git Tracking — Change Management
538
-
539
- The workspace sandbox (`$VELLUM_WORKSPACE_DIR`) is automatically tracked by a per-workspace git repository. Every file change made by the assistant is captured in structured commits, providing a full audit trail and natural undo/history exploration via standard git commands.
540
-
541
- ### Architecture overview
542
-
543
- ```mermaid
544
- graph TB
545
- subgraph "Turn-boundary commits (primary)"
546
- SESSION["Session.processMessage()"]
547
- TURN_COMMIT["commitTurnChanges()<br/>awaited, timeout-protected"]
548
- MSG_PROVIDER["CommitMessageProvider<br/>buildImmediateMessage()"]
549
- GIT_SERVICE["WorkspaceGitService<br/>mutex + circuit breaker"]
550
- end
551
-
552
- subgraph "Heartbeat safety net (secondary)"
553
- HEARTBEAT["HeartbeatService<br/>setInterval every 5 min"]
554
- CHECK["check(): age > 5 min<br/>OR files > 20"]
555
- end
556
-
557
- subgraph "Post-commit enrichment (async)"
558
- ENRICHMENT["CommitEnrichmentService<br/>bounded queue, fire-and-forget"]
559
- GIT_NOTES["git notes --ref=vellum<br/>JSON metadata"]
560
- end
561
-
562
- subgraph "Lifecycle"
563
- STARTUP["Daemon startup<br/>lifecycle.ts"]
564
- SHUTDOWN["Graceful shutdown<br/>commitAllPending()"]
565
- end
566
-
567
- SESSION -->|"await + timeout"| TURN_COMMIT
568
- TURN_COMMIT --> MSG_PROVIDER
569
- MSG_PROVIDER --> GIT_SERVICE
570
- TURN_COMMIT -->|"fire-and-forget"| ENRICHMENT
571
- HEARTBEAT --> CHECK
572
- CHECK --> MSG_PROVIDER
573
- CHECK -->|"fire-and-forget"| ENRICHMENT
574
- ENRICHMENT --> GIT_NOTES
575
- STARTUP --> HEARTBEAT
576
- SHUTDOWN -->|"await"| HEARTBEAT
577
- SHUTDOWN -->|"drain in-flight"| ENRICHMENT
578
- ```
579
-
580
- ### How it works
581
-
582
- 1. **Lazy initialization**: The git repository is created on first use, not at workspace creation. When `ensureInitialized()` is called, it checks for a `.git` directory. If absent, it runs `git init`, creates a `.gitignore` (excluding `data/`, `logs/`, `*.log`, `*.sock`, `*.pid`, `session-token`), sets the git identity to "Vellum Assistant", and creates an initial baseline commit capturing any pre-existing files. The baseline commit is intentional — it makes `git log`, `git diff`, and `git revert` work cleanly from the start. Both new and existing workspaces get the same treatment. For existing repos (e.g. created by older versions or external tools), `.gitignore` rules and git identity are set idempotently on each init, ensuring proper configuration regardless of how the repo was originally created.
583
-
584
- 2. **Turn-boundary commits**: After each conversation turn (user message + assistant response cycle), `conversation.ts` commits workspace changes via `commitTurnChanges(workspaceDir, sessionId, turnNumber)`. The commit runs in the `finally` block of `runAgentLoop`, guarded by a `turnStarted` flag that is set once the agent loop begins executing. This guarantees a commit attempt even when post-processing (e.g. `resolveAssistantAttachments`) throws, or when the user cancels mid-turn. The commit is raced against a configurable timeout (`workspaceGit.turnCommitMaxWaitMs`, default 4s) via `Promise.race`. If the commit exceeds the timeout, the turn proceeds immediately while the commit continues in the background. Note: the background commit is NOT awaited before the next turn starts, so brief cross-turn file attribution windows are possible but accepted as a tradeoff for responsiveness. Commit outcomes are logged with structured fields (`sessionId`, `turnNumber`, `filesChanged`, `durationMs`) for observability.
585
-
586
- 3. **Heartbeat safety net**: A `HeartbeatService` runs on a 5-minute interval, checking all tracked workspaces for uncommitted changes. It auto-commits when changes exceed either an age threshold (5 minutes since first detected) or a file count threshold (20+ files). This catches changes from long-running bash scripts, background processes, or crashed sessions that miss turn-boundary commits.
587
-
588
- 4. **Shutdown safety net**: During graceful daemon shutdown, `commitAllPending()` is called twice: once before `server.stop()` (pre-stop) and once after (post-stop). The pre-stop sweep captures any pending workspace changes. The post-stop sweep catches writes that occurred during server shutdown (e.g. in-flight tool executions completing during drain). Both calls are wrapped in try/catch to prevent commit failures from deadlocking shutdown.
589
-
590
- 5. **Corrupted repo recovery**: If a `.git` directory exists but is corrupted (e.g. missing HEAD), the service detects this via `git rev-parse --git-dir`, removes the corrupted directory, and reinitializes cleanly.
591
-
592
- 6. **Commit message provider abstraction**: All commit message construction is handled by a `CommitMessageProvider` interface (`commit-message-provider.ts`). The `DefaultCommitMessageProvider` produces deterministic messages based on trigger type (turn, heartbeat, shutdown). Both `turn-commit.ts` and `heartbeat-service.ts` accept an optional custom provider, creating a seam for future LLM-powered enrichment without changing the synchronous commit path.
593
-
594
- 7. **Circuit breaker with exponential backoff**: `WorkspaceGitService` tracks consecutive commit failures and backs off exponentially (2s, 4s, 8s... up to 60s configurable max). When the breaker is open, `commitIfDirty()` short-circuits without attempting git operations. On success, the breaker resets. State transitions are logged at info/warn level with structured fields (`consecutiveFailures`, `backoffMs`).
595
-
596
- 8. **Turn-commit timeout protection**: The turn-boundary commit in `conversation.ts` uses `Promise.race` with a configurable timeout (`workspaceGit.turnCommitMaxWaitMs`, default 4s). If the commit exceeds the timeout, the turn proceeds immediately (the commit continues in the background). This prevents slow git operations from blocking the conversation loop.
597
-
598
- 9. **Non-blocking enrichment queue**: After each successful commit, a `CommitEnrichmentService` runs async enrichment fire-and-forget. The queue has configurable max size (default 50), concurrency (default 1), per-job timeout (default 30s), and retry count (default 2 with exponential backoff). On queue overflow, the oldest job is dropped with a warning log. On graceful shutdown, in-flight jobs drain while pending jobs are discarded. Currently writes placeholder JSON metadata to git notes (`refs/notes/vellum`) as a scaffold for future LLM enrichment.
599
-
600
- 10. **Provider-aware commit message generation (optional)**: When `workspaceGit.commitMessageLLM.enabled` is `true`, turn-boundary commits attempt to generate a descriptive commit message using the configured LLM provider before falling back to deterministic messages. The feature ships disabled by default and is designed to never degrade turn completion guarantees.
601
-
602
- **Commit message LLM fallback chain**: The generator runs a sequence of pre-flight checks before calling the LLM. Each check that fails produces a machine-readable `llmFallbackReason` in the structured log output and immediately returns a deterministic message. The checks, in order:
603
- 1. `disabled` — `commitMessageLLM.enabled` is `false` or `useConfiguredProvider` is `false`
604
- 2. `missing_provider_api_key` — the configured provider's API key is not found in secure storage (skipped for keyless providers like Ollama that run without an API key)
605
- 3. `breaker_open` — the generator's internal circuit breaker is open after consecutive LLM failures (exponential backoff)
606
- 4. `insufficient_budget` — the remaining turn budget (`deadlineMs - Date.now()`) is below `minRemainingTurnBudgetMs`
607
- 5. `missing_fast_model` — no fast model could be resolved for the configured provider (see below); the provider is **not** called
608
- 6. `provider_not_initialized` — the configured provider is not registered/bootstrapped (e.g., `getProvider()` throws)
609
- 7. `timeout` — the LLM call exceeded `timeoutMs` (AbortController fires)
610
- 8. `provider_error` — the provider threw an exception during the LLM call
611
- 9. `invalid_output` — the LLM returned empty text, the literal string "FALLBACK", or total output > 500 chars
612
- - **Subject line capping**: If the LLM subject line exceeds 72 chars it is deterministically truncated to 72 chars. This is NOT treated as a failure (no breaker penalty, no deterministic fallback).
613
-
614
- **Fast model resolution**: The LLM call uses a small/fast model to minimize latency and cost. The model is resolved **before** any provider call as a pre-flight check:
615
- - If `commitMessageLLM.providerFastModelOverrides[provider]` is set, that model is used.
616
- - Otherwise, a built-in default is used: `anthropic` -> `claude-haiku-4-5-20251001`, `openai` -> `gpt-4o-mini`, `gemini` -> `gemini-2.0-flash`.
617
- - If the configured provider has no override and no built-in default (e.g., `ollama`, `fireworks`, `openrouter`), the generator returns a deterministic fallback with reason `missing_fast_model` and the provider is never called. To enable LLM commit messages for such providers, set `providerFastModelOverrides[provider]` to the desired model.
618
-
619
- **Pre-mutex LLM attempt**: The LLM generation runs BEFORE entering `commitIfDirty()` (outside the git mutex). Changed files are captured from a read-only `getStatus()` call (the "pre-status") outside the mutex. This avoids holding the mutex during network calls. The `commitIfDirty` callback uses its own mutex-protected status for the actual commit, so the file list used for commit and for the LLM prompt may differ slightly if files change between the two status calls — this is accepted as a tradeoff for not blocking concurrent git operations on LLM latency.
620
-
621
- ### Design decisions
622
-
623
- - **Commit at turn boundaries, not per-tool-call**: A single commit per turn captures all file mutations from that turn atomically. This avoids noisy per-file commits and keeps the history meaningful.
624
- - **Lazy init with baseline commit**: The repo is created on first use, not at daemon startup. Existing workspaces get their files captured in an "Initial commit: migrated existing workspace" on first use, rather than requiring an explicit migration step. The baseline commit ensures `git log`, `git diff`, and `git revert` work cleanly from the start.
625
- - **Mutex serialization**: All git operations go through a per-workspace `Mutex` to prevent concurrent `git add`/`git commit` from corrupting the index. The mutex uses a FIFO wait queue.
626
- - **Finally-block commit guarantee in conversation-agent-loop.ts**: Turn commits run in the `finally` block of `runAgentLoop`, ensuring they execute even when post-processing throws or the user cancels. The `turnStarted` flag prevents commits for turns that were blocked before the agent loop started. All errors are caught and logged as warnings. The commit is raced against a timeout (`turnCommitMaxWaitMs`, default 4s); if it exceeds the timeout the turn proceeds and the commit continues in the background without synchronization. Brief cross-turn file attribution is accepted as a tradeoff for keeping the conversation loop responsive.
627
- - **Branch enforcement at init time**: `ensureOnMainLocked()` is called during initialization to ensure the workspace is on the `main` branch. If the workspace is on the wrong branch or in a detached HEAD state, it auto-corrects to `main` with a warning log. Per-commit enforcement is unnecessary since nothing in the codebase switches branches.
628
- - **We intentionally don't provide custom history APIs** -- assistants should use git commands naturally via Bash (e.g. `git log`, `git diff`, `git show`). The workspace git repo is a standard git repository that any tool can interact with.
629
-
630
- ### Key files
631
-
632
- | File | Role |
633
- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
634
- | `assistant/src/workspace/git-service.ts` | `WorkspaceGitService`: lazy init, mutex, circuit breaker, `commitIfDirty()`, `getHeadHash()`, `writeNote()`, singleton registry |
635
- | `assistant/src/workspace/commit-message-provider.ts` | `CommitMessageProvider` interface, `DefaultCommitMessageProvider`, `CommitContext`/`CommitMessageResult` types |
636
- | `assistant/src/workspace/commit-message-enrichment-service.ts` | `CommitEnrichmentService`: bounded async queue, fire-and-forget enrichment, git notes output |
637
- | `assistant/src/workspace/turn-commit.ts` | `commitTurnChanges()`: turn-boundary commit with structured metadata + enrichment enqueue |
638
- | `assistant/src/workspace/provider-commit-message-generator.ts` | `ProviderCommitMessageGenerator`: LLM-based commit message generation with circuit breaker and deterministic fallback |
639
- | `assistant/src/workspace/heartbeat-service.ts` | `HeartbeatService`: periodic safety-net auto-commits, shutdown commits, enrichment enqueue |
640
- | `assistant/src/daemon/conversation-agent-loop.ts` | Integration: turn-boundary commit with `raceWithTimeout` protection in `runAgentLoop` finally block |
641
- | `assistant/src/daemon/lifecycle.ts` | Integration: `HeartbeatService` start/stop and shutdown commit |
642
- | `assistant/src/config/schema.ts` | `WorkspaceGitConfigSchema`: timeout, backoff, and enrichment queue configuration |
643
-
644
- ---
50
+ - `handleRemember` (`graph/tool-handlers.ts`) appends timestamped bullets to
51
+ `memory/buffer.md` + the daily archive whenever memory is enabled. Facts may
52
+ carry `[[slug]]` page hints that consolidation reads first when filing.
53
+ - **Consolidation** (`v3/substrate/consolidation-job.ts`) is a background
54
+ agent conversation that files buffer entries into concept pages, rewrites
55
+ the aggregate views, and trims the buffer. Scheduling
56
+ (`maybeEnqueueGraphMaintenanceJobs` in `jobs-worker.ts`):
57
+ - interval-based (`memory.v2.consolidation_interval_hours`, default 8h),
58
+ skipped below `MIN_BUFFER_LINES_FOR_CONSOLIDATION` (10) **unless** the
59
+ non-empty buffer has sat unwritten for a full interval (staleness
60
+ override — a small buffer can never sit unconsolidated forever);
61
+ - size-triggered at `consolidation_max_buffer_lines` (default 100);
62
+ - nudged by the create-memory route after a user-authored save (deduped,
63
+ failure-backoff-respecting);
64
+ - manual "Run now" via `POST /v1/consolidation/run-now`.
65
+ Failed runs enter an exponential backoff (transient vs billing curves).
66
+
67
+ ### Read paths
68
+
69
+ - **v3 (live)**: per-turn lane selection over concept pages — dense/sparse
70
+ retrieval (`v3/substrate/sim.ts` over the concept-page collection),
71
+ learned edges, entity/hot/fresh/core sets — rendered as the `<memory>`
72
+ card by `v3/injector.ts`. The static `<info>` block
73
+ (`v3/substrate/static-context.ts`: essentials/threads/recent/buffer) also
74
+ injects whenever the substrate is active.
75
+ - **v2 (transitional)**: activation/router engine in `v2/`
76
+ (`activation.ts`, `router.ts`, `reranker.ts`, `injection.ts`) selects
77
+ concept pages per turn. Suppressed at assembly when v3 is live. Gated on
78
+ `memory.v2.enabled` and deleted with it.
79
+ - **v1 (legacy)**: PKB retrieval over the v1 Qdrant collection. All v1
80
+ machinery (graph extraction, summarization, PKB indexing/filing, PKB
81
+ injection) is suppressed while the substrate is active.
82
+
83
+ ### Boot-time maintenance
84
+
85
+ `v3/substrate/memory-v2-startup.ts`, invoked from the memory plugin's
86
+ startup path: skill + CLI-command capability seeding into the concept-page
87
+ collection, BM25 corpus-stats rebuild, and collection schema
88
+ reconcile/reembed. All gated on `usesConceptPageMemory()`.
89
+
90
+ ## Memory graph (visualization)
91
+
92
+ `GET /v1/memory-graph` (`graph-topology/build-memory-graph.ts`) renders the
93
+ substrate as a backend-agnostic node/edge graph for the web Memory tab:
94
+ concept pages as nodes, authored links + learned co-selection associations as
95
+ edges, and `memory/buffer.md` entries as `pending` nodes
96
+ (`graph-topology/pending-buffer.ts`) so a just-saved fact appears before
97
+ consolidation files it. Gated on the `memory-concept-graph` feature flag +
98
+ `memory.v3.live`. `GET /v1/memory-graph-node` serves node detail, including
99
+ `buffer:` ids for pending entries.
100
+
101
+ ## Capture beyond `remember`
102
+
103
+ - **Retrospective** (`memory-retrospective-*.ts`): periodic per-conversation
104
+ review pass that saves what wasn't captured in the moment (and, on v3-live
105
+ assistants, authors procedural skills).
106
+ - **Sweep** (`v3/substrate/sweep-job.ts`, `memory.v2.sweep_enabled`, default
107
+ off): idle-debounced extraction of recent messages into the buffer.
108
+
109
+ ## Config namespaces
110
+
111
+ Substrate tuning still lives under the historical `memory.v2.*` keys
112
+ (consolidation intervals/limits, embedding + retrieval weights) and v3 lane
113
+ tuning under `memory.v3.*`. The `memory.v2.enabled` flag gates only the v2
114
+ injection engine's turn-time selection; the substrate runs whenever
115
+ `usesConceptPageMemory()` holds.