memorix 1.1.7 → 1.1.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 (185) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/CLAUDE.md +6 -1
  3. package/README.md +21 -0
  4. package/README.zh-CN.md +21 -0
  5. package/TEAM.md +86 -86
  6. package/dist/cli/index.js +852 -214
  7. package/dist/cli/index.js.map +1 -1
  8. package/dist/dashboard/static/index.html +201 -201
  9. package/dist/dashboard/static/style.css +3584 -3584
  10. package/dist/index.js +129 -62
  11. package/dist/index.js.map +1 -1
  12. package/dist/memcode-runtime/CHANGELOG.md +22 -0
  13. package/dist/memcode-runtime/package.json +4 -4
  14. package/dist/sdk.js +129 -62
  15. package/dist/sdk.js.map +1 -1
  16. package/docs/AGENT_OPERATOR_PLAYBOOK.md +18 -0
  17. package/docs/API_REFERENCE.md +2 -0
  18. package/docs/CONFIGURATION.md +18 -0
  19. package/docs/DESIGN_DECISIONS.md +357 -357
  20. package/docs/SETUP.md +10 -0
  21. package/docs/dev-log/progress.txt +23 -30
  22. package/package.json +1 -1
  23. package/src/audit/index.ts +156 -156
  24. package/src/cli/commands/agent-integrations.ts +623 -0
  25. package/src/cli/commands/audit-list.ts +89 -89
  26. package/src/cli/commands/background.ts +659 -659
  27. package/src/cli/commands/cleanup.ts +255 -255
  28. package/src/cli/commands/codegraph.ts +4 -0
  29. package/src/cli/commands/config-get.ts +9 -2
  30. package/src/cli/commands/doctor.ts +26 -0
  31. package/src/cli/commands/formation.ts +48 -48
  32. package/src/cli/commands/git-hook-install.ts +111 -111
  33. package/src/cli/commands/handoff.ts +66 -66
  34. package/src/cli/commands/hooks-status.ts +63 -63
  35. package/src/cli/commands/ingest-commit.ts +153 -153
  36. package/src/cli/commands/ingest-image.ts +73 -73
  37. package/src/cli/commands/ingest-log.ts +180 -180
  38. package/src/cli/commands/ingest.ts +44 -44
  39. package/src/cli/commands/integrate-shared.ts +15 -15
  40. package/src/cli/commands/lock.ts +96 -96
  41. package/src/cli/commands/message.ts +121 -121
  42. package/src/cli/commands/poll.ts +70 -70
  43. package/src/cli/commands/purge-all-memory.ts +85 -85
  44. package/src/cli/commands/purge-project-memory.ts +83 -83
  45. package/src/cli/commands/reasoning.ts +132 -132
  46. package/src/cli/commands/repair.ts +60 -0
  47. package/src/cli/commands/retention.ts +108 -108
  48. package/src/cli/commands/serve-shared.ts +118 -118
  49. package/src/cli/commands/setup.ts +3 -3
  50. package/src/cli/commands/skills.ts +123 -123
  51. package/src/cli/commands/task.ts +192 -192
  52. package/src/cli/commands/transfer.ts +73 -73
  53. package/src/cli/commands/uninstall-project-artifacts.ts +85 -85
  54. package/src/cli/index.ts +3 -1
  55. package/src/cli/tui/ChatView.tsx +234 -234
  56. package/src/cli/tui/CommandBar.tsx +312 -312
  57. package/src/cli/tui/ContextRail.tsx +118 -118
  58. package/src/cli/tui/HeaderBar.tsx +72 -72
  59. package/src/cli/tui/LogoBanner.tsx +51 -51
  60. package/src/cli/tui/Panels.tsx +632 -632
  61. package/src/cli/tui/Sidebar.tsx +179 -179
  62. package/src/cli/tui/chat-service.ts +742 -742
  63. package/src/cli/tui/data.ts +547 -547
  64. package/src/cli/tui/index.ts +41 -41
  65. package/src/cli/tui/markdown-render.tsx +371 -371
  66. package/src/cli/tui/theme.ts +178 -178
  67. package/src/cli/tui/use-mouse.ts +157 -157
  68. package/src/cli/tui/useNavigation.ts +56 -56
  69. package/src/cli/update-checker.ts +211 -211
  70. package/src/cli/version.ts +7 -7
  71. package/src/cli/workbench.ts +1 -1
  72. package/src/codegraph/auto-context.ts +6 -0
  73. package/src/codegraph/context-pack.ts +7 -6
  74. package/src/codegraph/exclude.ts +47 -0
  75. package/src/codegraph/lite-provider.ts +5 -24
  76. package/src/codegraph/project-context.ts +13 -15
  77. package/src/compact/token-budget.ts +74 -74
  78. package/src/config/behavior.ts +59 -59
  79. package/src/config/resolved-config.ts +6 -0
  80. package/src/config/toml-loader.ts +4 -0
  81. package/src/config/yaml-loader.ts +7 -0
  82. package/src/dashboard/project-classification.ts +64 -64
  83. package/src/dashboard/static/index.html +201 -201
  84. package/src/dashboard/static/style.css +3584 -3584
  85. package/src/embedding/fastembed-provider.ts +142 -142
  86. package/src/embedding/transformers-provider.ts +111 -111
  87. package/src/git/extractor.ts +209 -209
  88. package/src/git/hooks-path.ts +85 -85
  89. package/src/git/noise-filter.ts +210 -210
  90. package/src/hooks/installers/index.ts +4 -4
  91. package/src/hooks/official-skills.ts +1 -1
  92. package/src/hooks/pattern-detector.ts +173 -173
  93. package/src/hooks/rules/memorix-agent-rules.md +2 -2
  94. package/src/hooks/significance-filter.ts +250 -250
  95. package/src/llm/memory-manager.ts +328 -328
  96. package/src/llm/provider.ts +885 -885
  97. package/src/llm/quality.ts +248 -248
  98. package/src/memory/attribution-guard.ts +249 -249
  99. package/src/memory/auto-relations.ts +107 -107
  100. package/src/memory/consolidation.ts +302 -302
  101. package/src/memory/disclosure-policy.ts +141 -141
  102. package/src/memory/entity-extractor.ts +197 -197
  103. package/src/memory/formation/evaluate.ts +217 -217
  104. package/src/memory/formation/extract.ts +361 -361
  105. package/src/memory/formation/index.ts +417 -417
  106. package/src/memory/formation/resolve.ts +344 -344
  107. package/src/memory/formation/types.ts +315 -315
  108. package/src/memory/freshness.ts +122 -122
  109. package/src/memory/graph.ts +197 -197
  110. package/src/memory/refs.ts +94 -94
  111. package/src/memory/retention.ts +433 -433
  112. package/src/memory/secret-filter.ts +79 -79
  113. package/src/memory/session.ts +523 -523
  114. package/src/multimodal/image-loader.ts +143 -143
  115. package/src/orchestrate/adapters/claude-stream.ts +192 -192
  116. package/src/orchestrate/adapters/claude.ts +111 -111
  117. package/src/orchestrate/adapters/codex-stream.ts +134 -134
  118. package/src/orchestrate/adapters/codex.ts +41 -41
  119. package/src/orchestrate/adapters/gemini-stream.ts +166 -166
  120. package/src/orchestrate/adapters/gemini.ts +42 -42
  121. package/src/orchestrate/adapters/index.ts +73 -73
  122. package/src/orchestrate/adapters/opencode-stream.ts +143 -143
  123. package/src/orchestrate/adapters/opencode.ts +47 -47
  124. package/src/orchestrate/adapters/spawn-helper.ts +286 -286
  125. package/src/orchestrate/adapters/types.ts +77 -77
  126. package/src/orchestrate/capability-router.ts +284 -284
  127. package/src/orchestrate/context-compact.ts +188 -188
  128. package/src/orchestrate/cost-tracker.ts +219 -219
  129. package/src/orchestrate/error-recovery.ts +191 -191
  130. package/src/orchestrate/evidence.ts +140 -140
  131. package/src/orchestrate/ledger.ts +110 -110
  132. package/src/orchestrate/memorix-bridge.ts +380 -380
  133. package/src/orchestrate/output-budget.ts +80 -80
  134. package/src/orchestrate/permission.ts +152 -152
  135. package/src/orchestrate/pipeline-trace.ts +131 -131
  136. package/src/orchestrate/prompt-builder.ts +155 -155
  137. package/src/orchestrate/ring-buffer.ts +37 -37
  138. package/src/orchestrate/task-graph.ts +389 -389
  139. package/src/orchestrate/verify-gate.ts +219 -219
  140. package/src/orchestrate/worktree.ts +232 -232
  141. package/src/project/aliases.ts +374 -374
  142. package/src/project/detector.ts +268 -268
  143. package/src/rules/adapters/claude-code.ts +99 -99
  144. package/src/rules/adapters/codex.ts +97 -97
  145. package/src/rules/adapters/copilot.ts +124 -124
  146. package/src/rules/adapters/cursor.ts +114 -114
  147. package/src/rules/adapters/kiro.ts +126 -126
  148. package/src/rules/adapters/trae.ts +56 -56
  149. package/src/rules/adapters/windsurf.ts +83 -83
  150. package/src/rules/syncer.ts +235 -235
  151. package/src/sdk.ts +327 -327
  152. package/src/search/intent-detector.ts +289 -289
  153. package/src/search/query-expansion.ts +52 -52
  154. package/src/server/formation-timeout.ts +27 -27
  155. package/src/server.ts +3 -0
  156. package/src/skills/mini-skills.ts +386 -386
  157. package/src/store/chat-store.ts +119 -119
  158. package/src/store/file-lock.ts +100 -100
  159. package/src/store/graph-store.ts +249 -249
  160. package/src/store/mini-skill-store.ts +349 -349
  161. package/src/store/obs-store.ts +255 -255
  162. package/src/store/orama-store.ts +15 -8
  163. package/src/store/persistence-json.ts +212 -212
  164. package/src/store/persistence.ts +291 -291
  165. package/src/store/project-affinity.ts +195 -195
  166. package/src/store/session-store.ts +259 -259
  167. package/src/store/sqlite-store.ts +339 -339
  168. package/src/team/event-bus.ts +76 -76
  169. package/src/team/file-locks.ts +173 -173
  170. package/src/team/handoff.ts +167 -167
  171. package/src/team/messages.ts +203 -203
  172. package/src/team/poll.ts +132 -132
  173. package/src/team/tasks.ts +211 -211
  174. package/src/wiki/generator.ts +237 -237
  175. package/src/wiki/knowledge-graph.ts +334 -334
  176. package/src/wiki/types.ts +85 -85
  177. package/src/workspace/mcp-adapters/codex.ts +191 -191
  178. package/src/workspace/mcp-adapters/copilot.ts +105 -105
  179. package/src/workspace/mcp-adapters/cursor.ts +53 -53
  180. package/src/workspace/mcp-adapters/kiro.ts +64 -64
  181. package/src/workspace/mcp-adapters/opencode.ts +123 -123
  182. package/src/workspace/mcp-adapters/trae.ts +134 -134
  183. package/src/workspace/mcp-adapters/windsurf.ts +91 -91
  184. package/src/workspace/sanitizer.ts +60 -60
  185. package/src/workspace/workflow-sync.ts +131 -131
@@ -1,523 +1,523 @@
1
- /**
2
- * Session Lifecycle Manager
3
- *
4
- * Tracks coding sessions across agents and provides context injection
5
- * for new sessions. Inspired by Engram's session management pattern.
6
- *
7
- * Key features:
8
- * - Start/end session tracking
9
- * - Structured session summaries (Goal/Discoveries/Accomplished/Files)
10
- * - Auto-inject previous session context on session start
11
- * - Cross-agent session awareness (all agents share session data)
12
- */
13
-
14
- import type { Observation, Session } from '../types.js';
15
- import { classifyLayer } from './disclosure-policy.js';
16
- import { resolveAliases } from '../project/aliases.js';
17
- import { getObservationStore } from '../store/obs-store.js';
18
- import { getSessionStore } from '../store/session-store.js';
19
- import { KnowledgeGraphManager } from './graph.js';
20
- import { redactCredentials, sanitizeCredentials } from './secret-filter.js';
21
-
22
- const PRIORITY_TYPES = new Set(['gotcha', 'decision', 'problem-solution', 'trade-off', 'discovery']);
23
- const TYPE_EMOJI: Record<string, string> = {
24
- 'gotcha': '[DISCOVERY]',
25
- 'decision': '[WHY]',
26
- 'problem-solution': '[FIX]',
27
- 'trade-off': '[TRADEOFF]',
28
- 'discovery': '[DISCOVERY]',
29
- 'how-it-works': '[INFO]',
30
- 'what-changed': '[CHANGE]',
31
- 'why-it-exists': '[DECISION]',
32
- 'session-request': '[SESSION]',
33
- 'probe': '[PROBE]',
34
- };
35
- const TYPE_WEIGHTS: Record<string, number> = {
36
- 'gotcha': 6,
37
- 'decision': 5.5,
38
- 'problem-solution': 5.25,
39
- 'trade-off': 4.75,
40
- 'discovery': 4.25,
41
- };
42
- const NOISE_PATTERNS = [
43
- /\[测试\]/i,
44
- /\[test\]/i,
45
- /验证/i,
46
- /兼容/i,
47
- /\bcompat(?:ibility)?\b/i,
48
- /\bdemo\b/i,
49
- /展示/i,
50
- /全能力/i,
51
- /handoff/i,
52
- /交接/i,
53
- /for_memmcp_test/i,
54
- /\bbenchmark\b/i,
55
- /\bsandbox\b/i,
56
- /\bplayground\b/i,
57
- ];
58
-
59
- // Command-trace observations (debug commands, shell output) are low-value noise
60
- // in session context. They may have been stored by hooks but shouldn't surface.
61
- const COMMAND_TRACE_PATTERNS = [
62
- /^Ran:\s/i,
63
- /^Command:\s/i,
64
- /^Executed:\s/i,
65
- /\b2>&1\b/,
66
- /\bSelect-String\b/i,
67
- /\bGet-Content\b/i,
68
- /\bnpx\s+vitest\b/i,
69
- /\bnpx\s+tsc\b/i,
70
- ];
71
-
72
- // Observations about Memorix itself (its tools, internals, runtime modes) should almost
73
- // never be injected into unrelated projects. These get a much heavier penalty.
74
- const SYSTEM_SELF_PATTERNS = [
75
- /memorix.demo/i,
76
- /memorix.*全能力/i,
77
- /memorix.*工具.*能力/i,
78
- /memorix.*runtime.*mode/i,
79
- /memorix.*运行模式/i,
80
- /memorix.*control.plane/i,
81
- /session.*inject(?:ion)?/i,
82
- /注入.*逻辑/i,
83
- /\b22\s*(?:个|tools?).*(?:工具|能力|capabilit)/i,
84
- /memorix.*(?:v\d|版本|version)/i,
85
- /memorix.*(?:兼容|compat)/i,
86
- /memorix.*(?:测试|test)/i,
87
- /memmcp/i,
88
- ];
89
-
90
- /**
91
- * Resolve a projectId into a Set of all known aliases.
92
- * Ensures sessions stored under any alias are found regardless of which IDE stored them.
93
- */
94
- async function resolveProjectIds(projectId: string): Promise<Set<string>> {
95
- try {
96
- const aliases = await resolveAliases(projectId);
97
- return new Set(aliases);
98
- } catch {
99
- return new Set([projectId]);
100
- }
101
- }
102
-
103
- /**
104
- * Generate a unique session ID.
105
- */
106
- function generateSessionId(): string {
107
- const ts = Date.now().toString(36);
108
- const rand = Math.random().toString(36).slice(2, 8);
109
- return `sess-${ts}-${rand}`;
110
- }
111
-
112
- function tokenizeProjectId(projectId: string): string[] {
113
- const leaf = projectId.split('/').at(-1) ?? projectId;
114
- return Array.from(
115
- new Set(
116
- leaf
117
- .toLowerCase()
118
- .split(/[^a-z0-9]+/i)
119
- .map((token) => token.trim())
120
- .filter((token) => token.length >= 2),
121
- ),
122
- );
123
- }
124
-
125
- function stringifyObservation(obs: Observation, includeFiles: boolean = true): string {
126
- const parts = [
127
- obs.title,
128
- obs.narrative,
129
- obs.entityName,
130
- ...(obs.facts ?? []),
131
- ...(obs.concepts ?? []),
132
- ];
133
-
134
- if (includeFiles) {
135
- parts.push(...(obs.filesModified ?? []));
136
- }
137
-
138
- return parts
139
- .filter(Boolean)
140
- .join('\n')
141
- .toLowerCase();
142
- }
143
-
144
- function isCommandTrace(obs: Observation): boolean {
145
- const title = obs.title ?? '';
146
- return COMMAND_TRACE_PATTERNS.some((pattern) => pattern.test(title));
147
- }
148
-
149
- function isNoiseObservation(obs: Observation): boolean {
150
- const text = stringifyObservation(obs, false);
151
- return NOISE_PATTERNS.some((pattern) => pattern.test(text)) || isCommandTrace(obs);
152
- }
153
-
154
- function isSystemSelfObservation(obs: Observation): boolean {
155
- const text = stringifyObservation(obs, false);
156
- return SYSTEM_SELF_PATTERNS.some((pattern) => pattern.test(text));
157
- }
158
-
159
- export function scoreObservationForSessionContext(obs: Observation, projectTokens: string[], now = Date.now()): number {
160
- let score = TYPE_WEIGHTS[obs.type] ?? 1;
161
- const text = stringifyObservation(obs);
162
- const ageDays = Math.max(0, (now - new Date(obs.createdAt).getTime()) / (1000 * 60 * 60 * 24));
163
-
164
- // Recency still matters, but should not dominate everything.
165
- score += Math.max(0.2, 2.5 - Math.min(ageDays, 45) * 0.05);
166
-
167
- // Prefer observations that mention the current project name or touch its paths.
168
- if (projectTokens.length > 0) {
169
- const matchingTokens = projectTokens.filter((token) => text.includes(token));
170
- if (matchingTokens.length > 0) {
171
- score += 2 + matchingTokens.length * 0.6;
172
- } else if ((obs.filesModified?.length ?? 0) > 0) {
173
- score -= 1.25;
174
- }
175
- }
176
-
177
- // Avoid injecting obviously stale or completed memories back into new sessions.
178
- if (obs.status === 'resolved' || obs.status === 'archived') {
179
- score -= 100;
180
- }
181
-
182
- // Downrank demos, tests, migrations, and handoff records.
183
- if (isNoiseObservation(obs)) {
184
- score -= 8;
185
- }
186
-
187
- // Heavy penalty for observations about Memorix itself (system self-reference).
188
- // These should almost never surface in unrelated project sessions.
189
- if (isSystemSelfObservation(obs)) {
190
- score -= 15;
191
- }
192
-
193
- // Source-aware adjustments (neutral when sourceDetail/valueCategory absent — backward-compatible)
194
- if (obs.sourceDetail === 'hook') {
195
- // Hook auto-captures are L1 routing signals, not L2 working context
196
- score -= 3;
197
- if (obs.valueCategory === 'ephemeral') {
198
- // Hook + ephemeral = high-noise auto-capture with no lasting value
199
- score -= 5;
200
- }
201
- }
202
- if (obs.valueCategory === 'core') {
203
- // Formation-classified core memory: high-value, prefer in working context
204
- score += 2;
205
- }
206
-
207
- // Probe observations are operational heartbeats — never surface as priority session context
208
- if (obs.type === 'probe') {
209
- score -= 100;
210
- }
211
-
212
- return score;
213
- }
214
-
215
- /**
216
- * Start a new coding session.
217
- *
218
- * Creates a session record and returns context from previous sessions
219
- * so the agent can resume work without re-explaining everything.
220
- */
221
- export async function startSession(
222
- projectDir: string,
223
- projectId: string,
224
- opts?: { sessionId?: string; agent?: string },
225
- ): Promise<{ session: Session; previousContext: string }> {
226
- const sessionId = opts?.sessionId || generateSessionId();
227
- const now = new Date().toISOString();
228
-
229
- const session: Session = {
230
- id: sessionId,
231
- projectId,
232
- startedAt: now,
233
- status: 'active',
234
- agent: opts?.agent,
235
- };
236
-
237
- // Load previous context before creating new session
238
- const previousContext = await getSessionContext(projectDir, projectId);
239
-
240
- // Atomic rollover: complete all active sessions for this project's aliases
241
- // and insert the new session in a single SQLite transaction.
242
- // Prevents concurrent startSession() from leaving multiple active sessions.
243
- const sessionStore = getSessionStore();
244
- const aliasSet = await resolveProjectIds(projectId);
245
- await sessionStore.atomicRolloverInsert(session, [...aliasSet], now);
246
-
247
- return { session, previousContext };
248
- }
249
-
250
- /**
251
- * End a coding session with an optional structured summary.
252
- *
253
- * Summary format (following Engram's convention):
254
- * ## Goal
255
- * ## Discoveries
256
- * ## Accomplished
257
- * ## Relevant Files
258
- */
259
- export async function endSession(
260
- projectDir: string,
261
- sessionId: string,
262
- summary?: string,
263
- ): Promise<Session | null> {
264
- const sessionStore = getSessionStore();
265
- const sessions = await sessionStore.loadAll();
266
- const session = sessions.find((entry) => entry.id === sessionId);
267
-
268
- if (!session) return null;
269
-
270
- session.status = 'completed';
271
- session.endedAt = new Date().toISOString();
272
- if (summary) {
273
- session.summary = sanitizeCredentials(summary);
274
- }
275
-
276
- await sessionStore.update(session);
277
- return session;
278
- }
279
-
280
- /**
281
- * Get formatted context from previous sessions for injection into a new session.
282
- *
283
- * Returns a layered context packet:
284
- * L1 Routing — recent hook signals + search guidance
285
- * Recent Handoff — last session summary (L2)
286
- * Key Memories — durable explicit working context (L2)
287
- * Session History— orientation log
288
- * L3 Evidence — pointers to git-memory and hook traces (on-demand)
289
- */
290
- export async function getSessionContext(
291
- projectDir: string,
292
- projectId: string,
293
- limit: number = 3,
294
- ): Promise<string> {
295
- const sessions = await getSessionStore().loadAll();
296
- const allObs = await getObservationStore().loadAll();
297
-
298
- const aliasSet = await resolveProjectIds(projectId);
299
- /** Check if a session summary contains noise/system-self content */
300
- const isNoisySummary = (summary: string | undefined): boolean => {
301
- if (!summary) return false;
302
- return NOISE_PATTERNS.some((p) => p.test(summary)) || SYSTEM_SELF_PATTERNS.some((p) => p.test(summary));
303
- };
304
-
305
- const projectSessions = sessions
306
- .filter((session) => aliasSet.has(session.projectId) && session.status === 'completed')
307
- .filter((session) => !isNoisySummary(session.summary))
308
- .sort((a, b) => new Date(b.endedAt || b.startedAt).getTime() - new Date(a.endedAt || a.startedAt).getTime())
309
- .slice(0, limit);
310
-
311
- if (projectSessions.length === 0 && allObs.length === 0) {
312
- return '';
313
- }
314
-
315
- const lines: string[] = [];
316
- const projectTokens = tokenizeProjectId(projectId);
317
-
318
- // ── Partition project observations by disclosure layer ─────────────
319
- const projectObs = allObs
320
- .filter((obs) => aliasSet.has(obs.projectId) && (obs.status ?? 'active') === 'active')
321
- .filter((obs) => !isNoiseObservation(obs) && !isSystemSelfObservation(obs));
322
-
323
- // L2: durable working context (explicit/undefined/core), priority types only
324
- const l2Scored = projectObs
325
- .filter((obs) => PRIORITY_TYPES.has(obs.type) && classifyLayer(obs) === 'L2')
326
- .map((obs) => ({ obs, score: scoreObservationForSessionContext(obs, projectTokens) }))
327
- .sort((a, b) => {
328
- if (b.score !== a.score) return b.score - a.score;
329
- return new Date(b.obs.createdAt).getTime() - new Date(a.obs.createdAt).getTime();
330
- });
331
-
332
- // Per-entity cap: only when multiple distinct entities are present.
333
- // Prevents one workstream from monopolizing session context.
334
- // When all candidates belong to a single entity, skip the cap — no pollution risk.
335
- const distinctL2Entities = new Set(l2Scored.map(({ obs }) => obs.entityName).filter(Boolean)).size;
336
- const l2Obs = (distinctL2Entities > 1
337
- ? (() => {
338
- const entityCount = new Map<string, number>();
339
- const ENTITY_CAP = 3;
340
- return l2Scored.filter(({ obs }) => {
341
- const key = obs.entityName ?? '';
342
- const count = entityCount.get(key) ?? 0;
343
- if (count >= ENTITY_CAP) return false;
344
- entityCount.set(key, count + 1);
345
- return true;
346
- });
347
- })()
348
- : l2Scored
349
- ).slice(0, 5).map(({ obs }) => obs);
350
-
351
- // L1: recent hook activity signals (titles only, most recent first)
352
- const l1HookObs = projectObs
353
- .filter((obs) => classifyLayer(obs) === 'L1')
354
- .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
355
- .slice(0, 3);
356
-
357
- // L3: git-ingest evidence count (pointer only, not injected)
358
- const l3GitCount = projectObs.filter((obs) => classifyLayer(obs) === 'L3').length;
359
- const totalHookCount = projectObs.filter((obs) => classifyLayer(obs) === 'L1').length;
360
-
361
- // Active entities: unique entity names from top-scored L2 memories.
362
- // Surfaced in L1 Routing as next-hop search guidance — not working context.
363
- // Capped at 5, derived from the same l2Obs already scored above.
364
- const activeEntities = [
365
- ...new Set(l2Obs.map((o) => o.entityName).filter((n): n is string => !!n && n.trim().length > 0)),
366
- ].slice(0, 5);
367
-
368
- // ── L1 Routing ─────────────────────────────────────────────────────
369
- // L1 Routing requires actual L1/L3 signals (hooks or git evidence).
370
- // Active entities enrich the section when it is shown but do not open it alone.
371
- const hasL1Content = l1HookObs.length > 0 || l3GitCount > 0;
372
- if (hasL1Content) {
373
- // Graph neighbor routing hint: 1-hop neighbors of activeEntities from the
374
- // knowledge graph. Routing only — no query expansion, no rerank, no 2-hop
375
- // traversal. Silently skipped if graph is absent, empty, or throws.
376
- let graphNeighbors: string[] = [];
377
- if (activeEntities.length > 0) {
378
- try {
379
- const graphMgr = new KnowledgeGraphManager(projectDir);
380
- await graphMgr.init();
381
- const { relations } = await graphMgr.readGraph();
382
- const activeSet = new Set(activeEntities.map((n) => n.toLowerCase()));
383
- const neighborSet = new Set<string>();
384
- for (const rel of relations) {
385
- const fromLower = rel.from.toLowerCase();
386
- const toLower = rel.to.toLowerCase();
387
- if (activeSet.has(fromLower) && !activeSet.has(toLower)) neighborSet.add(rel.to);
388
- if (activeSet.has(toLower) && !activeSet.has(fromLower)) neighborSet.add(rel.from);
389
- }
390
- graphNeighbors = [...neighborSet].slice(0, 5);
391
- } catch {
392
- // Graph unavailable or empty — silently skip
393
- }
394
- }
395
-
396
- lines.push('## L1 Routing');
397
- lines.push('*Recent activity signals and search guidance for this session.*');
398
-
399
- if (l1HookObs.length > 0) {
400
- for (const obs of l1HookObs) {
401
- lines.push(`[HOOK] ${redactCredentials(obs.title)}`);
402
- }
403
- lines.push('');
404
- }
405
-
406
- const hints: string[] = [];
407
- if (activeEntities.length > 0) {
408
- hints.push(`Active entities: ${activeEntities.join(', ')}`);
409
- }
410
- if (graphNeighbors.length > 0) {
411
- hints.push(`Graph neighbors: ${graphNeighbors.join(', ')}`);
412
- }
413
- if (l3GitCount > 0) {
414
- hints.push(`${l3GitCount} git-memory item(s) available — search \`what-changed\` or by entity/commit`);
415
- }
416
- if (totalHookCount > 0) {
417
- hints.push(`${totalHookCount} hook trace(s) available — use \`memorix_timeline\` for activity expansion`);
418
- }
419
- for (const hint of hints) {
420
- lines.push(`[TIP] ${hint}`);
421
- }
422
- lines.push('');
423
- }
424
-
425
- // ── L2 Recent Handoff ──────────────────────────────────────────────
426
- if (projectSessions.length > 0) {
427
- // Walk back to find the most recent session with a real summary.
428
- let handoff = projectSessions[0];
429
- for (const s of projectSessions) {
430
- if (s.summary && s.summary !== '(session ended implicitly by new session start)') {
431
- handoff = s;
432
- break;
433
- }
434
- }
435
- lines.push('## Recent Handoff');
436
- lines.push('*Last session with a recorded summary — pick up where it left off.*');
437
- if (handoff.agent) {
438
- lines.push(`Agent: ${handoff.agent}`);
439
- }
440
- lines.push(`Ended: ${handoff.endedAt || handoff.startedAt}`);
441
- if (handoff.summary && handoff.summary !== '(session ended implicitly by new session start)') {
442
- lines.push('', redactCredentials(handoff.summary));
443
- }
444
- lines.push('');
445
- }
446
-
447
- // ── L2 Key Project Memories ────────────────────────────────────────
448
- if (l2Obs.length > 0) {
449
- lines.push('## Key Project Memories');
450
- lines.push('*Durable working context — explicit decisions, gotchas, and discoveries.*');
451
- for (const obs of l2Obs) {
452
- const emoji = TYPE_EMOJI[obs.type] ?? '[PIN]';
453
- const fact = obs.facts?.[0] ? ` — ${redactCredentials(obs.facts[0])}` : '';
454
- lines.push(`${emoji} ${redactCredentials(obs.title)}${fact}`);
455
- }
456
- lines.push('');
457
- }
458
-
459
- // ── Session History ────────────────────────────────────────────────
460
- if (projectSessions.length > 1) {
461
- lines.push(`## Recent Session History (last ${projectSessions.length})`);
462
- lines.push('*Chronological session log — for orientation, not action.*');
463
- for (const session of projectSessions) {
464
- const date = (session.endedAt || session.startedAt).slice(0, 10);
465
- const agent = session.agent ? ` [${session.agent}]` : '';
466
- const rawSummary = session.summary && session.summary !== '(session ended implicitly by new session start)'
467
- ? session.summary : null;
468
- const summary = rawSummary
469
- ? ` — ${redactCredentials(rawSummary.split('\n')[0].replace(/^#+\s*/, '')).slice(0, 80)}`
470
- : '';
471
- lines.push(`- ${date}${agent}${summary}`);
472
- }
473
- lines.push('');
474
- }
475
-
476
- // ── L3 Evidence Hints ─────────────────────────────────────────────
477
- const l3Lines: string[] = [];
478
- if (l3GitCount > 0) {
479
- l3Lines.push(`[PIN] ${l3GitCount} git-memory item(s) — use \`memorix_search\` to retrieve repository evidence`);
480
- }
481
- if (totalHookCount > 0) {
482
- l3Lines.push(`[HOOK] ${totalHookCount} hook trace(s) — use \`memorix_timeline\` for full activity expansion`);
483
- }
484
- if (l3Lines.length > 0) {
485
- lines.push('## L3 Evidence');
486
- lines.push('*Deeper context available on demand — kept out of working context to stay compact.*');
487
- for (const l of l3Lines) {
488
- lines.push(l);
489
- }
490
- lines.push('');
491
- }
492
-
493
- return lines.join('\n');
494
- }
495
-
496
- /**
497
- * List all sessions for a project.
498
- */
499
- export async function listSessions(
500
- projectDir: string,
501
- projectId?: string,
502
- ): Promise<Session[]> {
503
- const sessionStore = getSessionStore();
504
- if (projectId) {
505
- const aliasSet = await resolveProjectIds(projectId);
506
- const all = await sessionStore.loadAll();
507
- return all.filter((session) => aliasSet.has(session.projectId));
508
- }
509
- return sessionStore.loadAll();
510
- }
511
-
512
- /**
513
- * Get the currently active session for a project (if any).
514
- */
515
- export async function getActiveSession(
516
- projectDir: string,
517
- projectId: string,
518
- ): Promise<Session | null> {
519
- const sessionStore = getSessionStore();
520
- const sessions = await sessionStore.loadAll();
521
- const aliasSet = await resolveProjectIds(projectId);
522
- return sessions.find((session) => aliasSet.has(session.projectId) && session.status === 'active') || null;
523
- }
1
+ /**
2
+ * Session Lifecycle Manager
3
+ *
4
+ * Tracks coding sessions across agents and provides context injection
5
+ * for new sessions. Inspired by Engram's session management pattern.
6
+ *
7
+ * Key features:
8
+ * - Start/end session tracking
9
+ * - Structured session summaries (Goal/Discoveries/Accomplished/Files)
10
+ * - Auto-inject previous session context on session start
11
+ * - Cross-agent session awareness (all agents share session data)
12
+ */
13
+
14
+ import type { Observation, Session } from '../types.js';
15
+ import { classifyLayer } from './disclosure-policy.js';
16
+ import { resolveAliases } from '../project/aliases.js';
17
+ import { getObservationStore } from '../store/obs-store.js';
18
+ import { getSessionStore } from '../store/session-store.js';
19
+ import { KnowledgeGraphManager } from './graph.js';
20
+ import { redactCredentials, sanitizeCredentials } from './secret-filter.js';
21
+
22
+ const PRIORITY_TYPES = new Set(['gotcha', 'decision', 'problem-solution', 'trade-off', 'discovery']);
23
+ const TYPE_EMOJI: Record<string, string> = {
24
+ 'gotcha': '[DISCOVERY]',
25
+ 'decision': '[WHY]',
26
+ 'problem-solution': '[FIX]',
27
+ 'trade-off': '[TRADEOFF]',
28
+ 'discovery': '[DISCOVERY]',
29
+ 'how-it-works': '[INFO]',
30
+ 'what-changed': '[CHANGE]',
31
+ 'why-it-exists': '[DECISION]',
32
+ 'session-request': '[SESSION]',
33
+ 'probe': '[PROBE]',
34
+ };
35
+ const TYPE_WEIGHTS: Record<string, number> = {
36
+ 'gotcha': 6,
37
+ 'decision': 5.5,
38
+ 'problem-solution': 5.25,
39
+ 'trade-off': 4.75,
40
+ 'discovery': 4.25,
41
+ };
42
+ const NOISE_PATTERNS = [
43
+ /\[测试\]/i,
44
+ /\[test\]/i,
45
+ /验证/i,
46
+ /兼容/i,
47
+ /\bcompat(?:ibility)?\b/i,
48
+ /\bdemo\b/i,
49
+ /展示/i,
50
+ /全能力/i,
51
+ /handoff/i,
52
+ /交接/i,
53
+ /for_memmcp_test/i,
54
+ /\bbenchmark\b/i,
55
+ /\bsandbox\b/i,
56
+ /\bplayground\b/i,
57
+ ];
58
+
59
+ // Command-trace observations (debug commands, shell output) are low-value noise
60
+ // in session context. They may have been stored by hooks but shouldn't surface.
61
+ const COMMAND_TRACE_PATTERNS = [
62
+ /^Ran:\s/i,
63
+ /^Command:\s/i,
64
+ /^Executed:\s/i,
65
+ /\b2>&1\b/,
66
+ /\bSelect-String\b/i,
67
+ /\bGet-Content\b/i,
68
+ /\bnpx\s+vitest\b/i,
69
+ /\bnpx\s+tsc\b/i,
70
+ ];
71
+
72
+ // Observations about Memorix itself (its tools, internals, runtime modes) should almost
73
+ // never be injected into unrelated projects. These get a much heavier penalty.
74
+ const SYSTEM_SELF_PATTERNS = [
75
+ /memorix.demo/i,
76
+ /memorix.*全能力/i,
77
+ /memorix.*工具.*能力/i,
78
+ /memorix.*runtime.*mode/i,
79
+ /memorix.*运行模式/i,
80
+ /memorix.*control.plane/i,
81
+ /session.*inject(?:ion)?/i,
82
+ /注入.*逻辑/i,
83
+ /\b22\s*(?:个|tools?).*(?:工具|能力|capabilit)/i,
84
+ /memorix.*(?:v\d|版本|version)/i,
85
+ /memorix.*(?:兼容|compat)/i,
86
+ /memorix.*(?:测试|test)/i,
87
+ /memmcp/i,
88
+ ];
89
+
90
+ /**
91
+ * Resolve a projectId into a Set of all known aliases.
92
+ * Ensures sessions stored under any alias are found regardless of which IDE stored them.
93
+ */
94
+ async function resolveProjectIds(projectId: string): Promise<Set<string>> {
95
+ try {
96
+ const aliases = await resolveAliases(projectId);
97
+ return new Set(aliases);
98
+ } catch {
99
+ return new Set([projectId]);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Generate a unique session ID.
105
+ */
106
+ function generateSessionId(): string {
107
+ const ts = Date.now().toString(36);
108
+ const rand = Math.random().toString(36).slice(2, 8);
109
+ return `sess-${ts}-${rand}`;
110
+ }
111
+
112
+ function tokenizeProjectId(projectId: string): string[] {
113
+ const leaf = projectId.split('/').at(-1) ?? projectId;
114
+ return Array.from(
115
+ new Set(
116
+ leaf
117
+ .toLowerCase()
118
+ .split(/[^a-z0-9]+/i)
119
+ .map((token) => token.trim())
120
+ .filter((token) => token.length >= 2),
121
+ ),
122
+ );
123
+ }
124
+
125
+ function stringifyObservation(obs: Observation, includeFiles: boolean = true): string {
126
+ const parts = [
127
+ obs.title,
128
+ obs.narrative,
129
+ obs.entityName,
130
+ ...(obs.facts ?? []),
131
+ ...(obs.concepts ?? []),
132
+ ];
133
+
134
+ if (includeFiles) {
135
+ parts.push(...(obs.filesModified ?? []));
136
+ }
137
+
138
+ return parts
139
+ .filter(Boolean)
140
+ .join('\n')
141
+ .toLowerCase();
142
+ }
143
+
144
+ function isCommandTrace(obs: Observation): boolean {
145
+ const title = obs.title ?? '';
146
+ return COMMAND_TRACE_PATTERNS.some((pattern) => pattern.test(title));
147
+ }
148
+
149
+ function isNoiseObservation(obs: Observation): boolean {
150
+ const text = stringifyObservation(obs, false);
151
+ return NOISE_PATTERNS.some((pattern) => pattern.test(text)) || isCommandTrace(obs);
152
+ }
153
+
154
+ function isSystemSelfObservation(obs: Observation): boolean {
155
+ const text = stringifyObservation(obs, false);
156
+ return SYSTEM_SELF_PATTERNS.some((pattern) => pattern.test(text));
157
+ }
158
+
159
+ export function scoreObservationForSessionContext(obs: Observation, projectTokens: string[], now = Date.now()): number {
160
+ let score = TYPE_WEIGHTS[obs.type] ?? 1;
161
+ const text = stringifyObservation(obs);
162
+ const ageDays = Math.max(0, (now - new Date(obs.createdAt).getTime()) / (1000 * 60 * 60 * 24));
163
+
164
+ // Recency still matters, but should not dominate everything.
165
+ score += Math.max(0.2, 2.5 - Math.min(ageDays, 45) * 0.05);
166
+
167
+ // Prefer observations that mention the current project name or touch its paths.
168
+ if (projectTokens.length > 0) {
169
+ const matchingTokens = projectTokens.filter((token) => text.includes(token));
170
+ if (matchingTokens.length > 0) {
171
+ score += 2 + matchingTokens.length * 0.6;
172
+ } else if ((obs.filesModified?.length ?? 0) > 0) {
173
+ score -= 1.25;
174
+ }
175
+ }
176
+
177
+ // Avoid injecting obviously stale or completed memories back into new sessions.
178
+ if (obs.status === 'resolved' || obs.status === 'archived') {
179
+ score -= 100;
180
+ }
181
+
182
+ // Downrank demos, tests, migrations, and handoff records.
183
+ if (isNoiseObservation(obs)) {
184
+ score -= 8;
185
+ }
186
+
187
+ // Heavy penalty for observations about Memorix itself (system self-reference).
188
+ // These should almost never surface in unrelated project sessions.
189
+ if (isSystemSelfObservation(obs)) {
190
+ score -= 15;
191
+ }
192
+
193
+ // Source-aware adjustments (neutral when sourceDetail/valueCategory absent — backward-compatible)
194
+ if (obs.sourceDetail === 'hook') {
195
+ // Hook auto-captures are L1 routing signals, not L2 working context
196
+ score -= 3;
197
+ if (obs.valueCategory === 'ephemeral') {
198
+ // Hook + ephemeral = high-noise auto-capture with no lasting value
199
+ score -= 5;
200
+ }
201
+ }
202
+ if (obs.valueCategory === 'core') {
203
+ // Formation-classified core memory: high-value, prefer in working context
204
+ score += 2;
205
+ }
206
+
207
+ // Probe observations are operational heartbeats — never surface as priority session context
208
+ if (obs.type === 'probe') {
209
+ score -= 100;
210
+ }
211
+
212
+ return score;
213
+ }
214
+
215
+ /**
216
+ * Start a new coding session.
217
+ *
218
+ * Creates a session record and returns context from previous sessions
219
+ * so the agent can resume work without re-explaining everything.
220
+ */
221
+ export async function startSession(
222
+ projectDir: string,
223
+ projectId: string,
224
+ opts?: { sessionId?: string; agent?: string },
225
+ ): Promise<{ session: Session; previousContext: string }> {
226
+ const sessionId = opts?.sessionId || generateSessionId();
227
+ const now = new Date().toISOString();
228
+
229
+ const session: Session = {
230
+ id: sessionId,
231
+ projectId,
232
+ startedAt: now,
233
+ status: 'active',
234
+ agent: opts?.agent,
235
+ };
236
+
237
+ // Load previous context before creating new session
238
+ const previousContext = await getSessionContext(projectDir, projectId);
239
+
240
+ // Atomic rollover: complete all active sessions for this project's aliases
241
+ // and insert the new session in a single SQLite transaction.
242
+ // Prevents concurrent startSession() from leaving multiple active sessions.
243
+ const sessionStore = getSessionStore();
244
+ const aliasSet = await resolveProjectIds(projectId);
245
+ await sessionStore.atomicRolloverInsert(session, [...aliasSet], now);
246
+
247
+ return { session, previousContext };
248
+ }
249
+
250
+ /**
251
+ * End a coding session with an optional structured summary.
252
+ *
253
+ * Summary format (following Engram's convention):
254
+ * ## Goal
255
+ * ## Discoveries
256
+ * ## Accomplished
257
+ * ## Relevant Files
258
+ */
259
+ export async function endSession(
260
+ projectDir: string,
261
+ sessionId: string,
262
+ summary?: string,
263
+ ): Promise<Session | null> {
264
+ const sessionStore = getSessionStore();
265
+ const sessions = await sessionStore.loadAll();
266
+ const session = sessions.find((entry) => entry.id === sessionId);
267
+
268
+ if (!session) return null;
269
+
270
+ session.status = 'completed';
271
+ session.endedAt = new Date().toISOString();
272
+ if (summary) {
273
+ session.summary = sanitizeCredentials(summary);
274
+ }
275
+
276
+ await sessionStore.update(session);
277
+ return session;
278
+ }
279
+
280
+ /**
281
+ * Get formatted context from previous sessions for injection into a new session.
282
+ *
283
+ * Returns a layered context packet:
284
+ * L1 Routing — recent hook signals + search guidance
285
+ * Recent Handoff — last session summary (L2)
286
+ * Key Memories — durable explicit working context (L2)
287
+ * Session History— orientation log
288
+ * L3 Evidence — pointers to git-memory and hook traces (on-demand)
289
+ */
290
+ export async function getSessionContext(
291
+ projectDir: string,
292
+ projectId: string,
293
+ limit: number = 3,
294
+ ): Promise<string> {
295
+ const sessions = await getSessionStore().loadAll();
296
+ const allObs = await getObservationStore().loadAll();
297
+
298
+ const aliasSet = await resolveProjectIds(projectId);
299
+ /** Check if a session summary contains noise/system-self content */
300
+ const isNoisySummary = (summary: string | undefined): boolean => {
301
+ if (!summary) return false;
302
+ return NOISE_PATTERNS.some((p) => p.test(summary)) || SYSTEM_SELF_PATTERNS.some((p) => p.test(summary));
303
+ };
304
+
305
+ const projectSessions = sessions
306
+ .filter((session) => aliasSet.has(session.projectId) && session.status === 'completed')
307
+ .filter((session) => !isNoisySummary(session.summary))
308
+ .sort((a, b) => new Date(b.endedAt || b.startedAt).getTime() - new Date(a.endedAt || a.startedAt).getTime())
309
+ .slice(0, limit);
310
+
311
+ if (projectSessions.length === 0 && allObs.length === 0) {
312
+ return '';
313
+ }
314
+
315
+ const lines: string[] = [];
316
+ const projectTokens = tokenizeProjectId(projectId);
317
+
318
+ // ── Partition project observations by disclosure layer ─────────────
319
+ const projectObs = allObs
320
+ .filter((obs) => aliasSet.has(obs.projectId) && (obs.status ?? 'active') === 'active')
321
+ .filter((obs) => !isNoiseObservation(obs) && !isSystemSelfObservation(obs));
322
+
323
+ // L2: durable working context (explicit/undefined/core), priority types only
324
+ const l2Scored = projectObs
325
+ .filter((obs) => PRIORITY_TYPES.has(obs.type) && classifyLayer(obs) === 'L2')
326
+ .map((obs) => ({ obs, score: scoreObservationForSessionContext(obs, projectTokens) }))
327
+ .sort((a, b) => {
328
+ if (b.score !== a.score) return b.score - a.score;
329
+ return new Date(b.obs.createdAt).getTime() - new Date(a.obs.createdAt).getTime();
330
+ });
331
+
332
+ // Per-entity cap: only when multiple distinct entities are present.
333
+ // Prevents one workstream from monopolizing session context.
334
+ // When all candidates belong to a single entity, skip the cap — no pollution risk.
335
+ const distinctL2Entities = new Set(l2Scored.map(({ obs }) => obs.entityName).filter(Boolean)).size;
336
+ const l2Obs = (distinctL2Entities > 1
337
+ ? (() => {
338
+ const entityCount = new Map<string, number>();
339
+ const ENTITY_CAP = 3;
340
+ return l2Scored.filter(({ obs }) => {
341
+ const key = obs.entityName ?? '';
342
+ const count = entityCount.get(key) ?? 0;
343
+ if (count >= ENTITY_CAP) return false;
344
+ entityCount.set(key, count + 1);
345
+ return true;
346
+ });
347
+ })()
348
+ : l2Scored
349
+ ).slice(0, 5).map(({ obs }) => obs);
350
+
351
+ // L1: recent hook activity signals (titles only, most recent first)
352
+ const l1HookObs = projectObs
353
+ .filter((obs) => classifyLayer(obs) === 'L1')
354
+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
355
+ .slice(0, 3);
356
+
357
+ // L3: git-ingest evidence count (pointer only, not injected)
358
+ const l3GitCount = projectObs.filter((obs) => classifyLayer(obs) === 'L3').length;
359
+ const totalHookCount = projectObs.filter((obs) => classifyLayer(obs) === 'L1').length;
360
+
361
+ // Active entities: unique entity names from top-scored L2 memories.
362
+ // Surfaced in L1 Routing as next-hop search guidance — not working context.
363
+ // Capped at 5, derived from the same l2Obs already scored above.
364
+ const activeEntities = [
365
+ ...new Set(l2Obs.map((o) => o.entityName).filter((n): n is string => !!n && n.trim().length > 0)),
366
+ ].slice(0, 5);
367
+
368
+ // ── L1 Routing ─────────────────────────────────────────────────────
369
+ // L1 Routing requires actual L1/L3 signals (hooks or git evidence).
370
+ // Active entities enrich the section when it is shown but do not open it alone.
371
+ const hasL1Content = l1HookObs.length > 0 || l3GitCount > 0;
372
+ if (hasL1Content) {
373
+ // Graph neighbor routing hint: 1-hop neighbors of activeEntities from the
374
+ // knowledge graph. Routing only — no query expansion, no rerank, no 2-hop
375
+ // traversal. Silently skipped if graph is absent, empty, or throws.
376
+ let graphNeighbors: string[] = [];
377
+ if (activeEntities.length > 0) {
378
+ try {
379
+ const graphMgr = new KnowledgeGraphManager(projectDir);
380
+ await graphMgr.init();
381
+ const { relations } = await graphMgr.readGraph();
382
+ const activeSet = new Set(activeEntities.map((n) => n.toLowerCase()));
383
+ const neighborSet = new Set<string>();
384
+ for (const rel of relations) {
385
+ const fromLower = rel.from.toLowerCase();
386
+ const toLower = rel.to.toLowerCase();
387
+ if (activeSet.has(fromLower) && !activeSet.has(toLower)) neighborSet.add(rel.to);
388
+ if (activeSet.has(toLower) && !activeSet.has(fromLower)) neighborSet.add(rel.from);
389
+ }
390
+ graphNeighbors = [...neighborSet].slice(0, 5);
391
+ } catch {
392
+ // Graph unavailable or empty — silently skip
393
+ }
394
+ }
395
+
396
+ lines.push('## L1 Routing');
397
+ lines.push('*Recent activity signals and search guidance for this session.*');
398
+
399
+ if (l1HookObs.length > 0) {
400
+ for (const obs of l1HookObs) {
401
+ lines.push(`[HOOK] ${redactCredentials(obs.title)}`);
402
+ }
403
+ lines.push('');
404
+ }
405
+
406
+ const hints: string[] = [];
407
+ if (activeEntities.length > 0) {
408
+ hints.push(`Active entities: ${activeEntities.join(', ')}`);
409
+ }
410
+ if (graphNeighbors.length > 0) {
411
+ hints.push(`Graph neighbors: ${graphNeighbors.join(', ')}`);
412
+ }
413
+ if (l3GitCount > 0) {
414
+ hints.push(`${l3GitCount} git-memory item(s) available — search \`what-changed\` or by entity/commit`);
415
+ }
416
+ if (totalHookCount > 0) {
417
+ hints.push(`${totalHookCount} hook trace(s) available — use \`memorix_timeline\` for activity expansion`);
418
+ }
419
+ for (const hint of hints) {
420
+ lines.push(`[TIP] ${hint}`);
421
+ }
422
+ lines.push('');
423
+ }
424
+
425
+ // ── L2 Recent Handoff ──────────────────────────────────────────────
426
+ if (projectSessions.length > 0) {
427
+ // Walk back to find the most recent session with a real summary.
428
+ let handoff = projectSessions[0];
429
+ for (const s of projectSessions) {
430
+ if (s.summary && s.summary !== '(session ended implicitly by new session start)') {
431
+ handoff = s;
432
+ break;
433
+ }
434
+ }
435
+ lines.push('## Recent Handoff');
436
+ lines.push('*Last session with a recorded summary — pick up where it left off.*');
437
+ if (handoff.agent) {
438
+ lines.push(`Agent: ${handoff.agent}`);
439
+ }
440
+ lines.push(`Ended: ${handoff.endedAt || handoff.startedAt}`);
441
+ if (handoff.summary && handoff.summary !== '(session ended implicitly by new session start)') {
442
+ lines.push('', redactCredentials(handoff.summary));
443
+ }
444
+ lines.push('');
445
+ }
446
+
447
+ // ── L2 Key Project Memories ────────────────────────────────────────
448
+ if (l2Obs.length > 0) {
449
+ lines.push('## Key Project Memories');
450
+ lines.push('*Durable working context — explicit decisions, gotchas, and discoveries.*');
451
+ for (const obs of l2Obs) {
452
+ const emoji = TYPE_EMOJI[obs.type] ?? '[PIN]';
453
+ const fact = obs.facts?.[0] ? ` — ${redactCredentials(obs.facts[0])}` : '';
454
+ lines.push(`${emoji} ${redactCredentials(obs.title)}${fact}`);
455
+ }
456
+ lines.push('');
457
+ }
458
+
459
+ // ── Session History ────────────────────────────────────────────────
460
+ if (projectSessions.length > 1) {
461
+ lines.push(`## Recent Session History (last ${projectSessions.length})`);
462
+ lines.push('*Chronological session log — for orientation, not action.*');
463
+ for (const session of projectSessions) {
464
+ const date = (session.endedAt || session.startedAt).slice(0, 10);
465
+ const agent = session.agent ? ` [${session.agent}]` : '';
466
+ const rawSummary = session.summary && session.summary !== '(session ended implicitly by new session start)'
467
+ ? session.summary : null;
468
+ const summary = rawSummary
469
+ ? ` — ${redactCredentials(rawSummary.split('\n')[0].replace(/^#+\s*/, '')).slice(0, 80)}`
470
+ : '';
471
+ lines.push(`- ${date}${agent}${summary}`);
472
+ }
473
+ lines.push('');
474
+ }
475
+
476
+ // ── L3 Evidence Hints ─────────────────────────────────────────────
477
+ const l3Lines: string[] = [];
478
+ if (l3GitCount > 0) {
479
+ l3Lines.push(`[PIN] ${l3GitCount} git-memory item(s) — use \`memorix_search\` to retrieve repository evidence`);
480
+ }
481
+ if (totalHookCount > 0) {
482
+ l3Lines.push(`[HOOK] ${totalHookCount} hook trace(s) — use \`memorix_timeline\` for full activity expansion`);
483
+ }
484
+ if (l3Lines.length > 0) {
485
+ lines.push('## L3 Evidence');
486
+ lines.push('*Deeper context available on demand — kept out of working context to stay compact.*');
487
+ for (const l of l3Lines) {
488
+ lines.push(l);
489
+ }
490
+ lines.push('');
491
+ }
492
+
493
+ return lines.join('\n');
494
+ }
495
+
496
+ /**
497
+ * List all sessions for a project.
498
+ */
499
+ export async function listSessions(
500
+ projectDir: string,
501
+ projectId?: string,
502
+ ): Promise<Session[]> {
503
+ const sessionStore = getSessionStore();
504
+ if (projectId) {
505
+ const aliasSet = await resolveProjectIds(projectId);
506
+ const all = await sessionStore.loadAll();
507
+ return all.filter((session) => aliasSet.has(session.projectId));
508
+ }
509
+ return sessionStore.loadAll();
510
+ }
511
+
512
+ /**
513
+ * Get the currently active session for a project (if any).
514
+ */
515
+ export async function getActiveSession(
516
+ projectDir: string,
517
+ projectId: string,
518
+ ): Promise<Session | null> {
519
+ const sessionStore = getSessionStore();
520
+ const sessions = await sessionStore.loadAll();
521
+ const aliasSet = await resolveProjectIds(projectId);
522
+ return sessions.find((session) => aliasSet.has(session.projectId) && session.status === 'active') || null;
523
+ }