memorix 1.2.3 → 1.2.5

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 (52) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +3 -3
  3. package/README.zh-CN.md +3 -3
  4. package/dist/cli/index.js +5273 -4730
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/index.js +506 -99
  7. package/dist/index.js.map +1 -1
  8. package/dist/maintenance-runner.js +176 -53
  9. package/dist/maintenance-runner.js.map +1 -1
  10. package/dist/memcode-runtime/CHANGELOG.md +33 -0
  11. package/dist/sdk.d.ts +4 -2
  12. package/dist/sdk.js +507 -99
  13. package/dist/sdk.js.map +1 -1
  14. package/dist/types.d.ts +8 -1
  15. package/dist/types.js.map +1 -1
  16. package/docs/1.2.4-PERSISTENT-MEMORY-DELIVERY.md +86 -0
  17. package/docs/1.2.5-RETRIEVAL-PERFORMANCE.md +85 -0
  18. package/docs/AGENT_OPERATOR_PLAYBOOK.md +13 -1
  19. package/docs/API_REFERENCE.md +13 -3
  20. package/docs/PERFORMANCE.md +22 -1
  21. package/docs/dev-log/progress.txt +73 -7
  22. package/package.json +2 -1
  23. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  24. package/src/cli/capability-map.ts +1 -1
  25. package/src/cli/command-guide.ts +4 -1
  26. package/src/cli/commands/agent-integrations.ts +5 -1
  27. package/src/cli/commands/codegraph.ts +1 -1
  28. package/src/cli/commands/context.ts +9 -1
  29. package/src/cli/commands/memory.ts +12 -3
  30. package/src/cli/commands/operator-shared.ts +74 -2
  31. package/src/cli/commands/resume.ts +31 -0
  32. package/src/cli/index.ts +5 -1
  33. package/src/codegraph/auto-context.ts +54 -1
  34. package/src/codegraph/task-lens.ts +29 -0
  35. package/src/compact/token-budget.ts +16 -1
  36. package/src/config/resolved-config.ts +29 -4
  37. package/src/config/toml-loader.ts +9 -5
  38. package/src/hooks/handler.ts +127 -66
  39. package/src/hooks/installers/index.ts +5 -4
  40. package/src/hooks/official-skills.ts +6 -4
  41. package/src/hooks/rules/memorix-agent-rules.md +9 -7
  42. package/src/knowledge/context-assembly.ts +4 -1
  43. package/src/knowledge/workset.ts +89 -1
  44. package/src/memory/session.ts +144 -10
  45. package/src/runtime/project-maintenance.ts +1 -14
  46. package/src/sdk.ts +4 -0
  47. package/src/server.ts +144 -25
  48. package/src/store/bun-sqlite-compat.ts +118 -15
  49. package/src/store/orama-store.ts +39 -18
  50. package/src/store/sqlite-db.ts +3 -3
  51. package/src/timeout.ts +23 -0
  52. package/src/types.ts +8 -0
@@ -22,6 +22,9 @@ import { detectBestPattern, patternToObservationType } from './pattern-detector.
22
22
  import { isSignificantKnowledge, isRetrievedResult, isTrivialCommand } from './significance-filter.js';
23
23
  import type { AgentName, HookEvent, HookOutput, NormalizedHookInput } from './types.js';
24
24
 
25
+ type HookInjectionMode = 'full' | 'minimal' | 'silent';
26
+ type HookContextTarget = 'hook-session-start' | 'hook-user-prompt';
27
+
25
28
  // ─── Constants ───
26
29
 
27
30
  /** Observation type → emoji mapping (single source of truth) */
@@ -282,16 +285,117 @@ function buildObservation(
282
285
 
283
286
  // ─── Session Start Handler ───
284
287
 
288
+ async function getHookInjectionMode(input: NormalizedHookInput): Promise<HookInjectionMode> {
289
+ try {
290
+ const { getBehaviorConfig } = await import('../config/behavior.js');
291
+ return getBehaviorConfig({ projectRoot: input.cwd || undefined }).sessionInject;
292
+ } catch {
293
+ return 'minimal';
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Assemble the one bounded project brief shared by hook delivery points.
299
+ * Hooks never retrieve a transcript: this returns only the normal Workset.
300
+ */
301
+ async function buildHookProjectContext(
302
+ input: NormalizedHookInput,
303
+ task: string,
304
+ target: HookContextTarget,
305
+ ): Promise<{ prompt: string; hasContinuation: boolean } | null> {
306
+ try {
307
+ const { detectProject } = await import('../project/detector.js');
308
+ const { getProjectDataDir } = await import('../store/persistence.js');
309
+ const { initObservationStore, getObservationStore: getStore } = await import('../store/obs-store.js');
310
+ const { initMiniSkillStore } = await import('../store/mini-skill-store.js');
311
+ const { initSessionStore } = await import('../store/session-store.js');
312
+ const { initAliasRegistry, registerAlias } = await import('../project/aliases.js');
313
+ const { MaintenanceTargetStore } = await import('../runtime/maintenance-targets.js');
314
+ const { buildAutoProjectContext, formatAutoProjectContextPrompt } = await import('../codegraph/auto-context.js');
315
+ const { filterReadableObservations } = await import('../memory/visibility.js');
316
+
317
+ const rawProject = detectProject(input.cwd || process.cwd());
318
+ if (!rawProject) return null;
319
+ const dataDir = await getProjectDataDir(rawProject.id);
320
+
321
+ initAliasRegistry(dataDir);
322
+ const canonicalId = await registerAlias(rawProject);
323
+ new MaintenanceTargetStore(dataDir).register({
324
+ projectId: canonicalId,
325
+ projectRoot: rawProject.rootPath,
326
+ dataDir,
327
+ });
328
+ await initObservationStore(dataDir);
329
+ await initMiniSkillStore(dataDir);
330
+ await initSessionStore(dataDir);
331
+ const activeObservations = filterReadableObservations(
332
+ await getStore().loadByProject(canonicalId, { status: 'active' }),
333
+ { projectId: canonicalId },
334
+ );
335
+ const context = await buildAutoProjectContext({
336
+ project: { ...rawProject, id: canonicalId },
337
+ dataDir,
338
+ observations: activeObservations,
339
+ task,
340
+ refresh: 'auto',
341
+ reader: { projectId: canonicalId },
342
+ continuation: 'always',
343
+ enqueueRefresh: () => import('../runtime/lifecycle.js').then(({ enqueueCodegraphRefresh }) => {
344
+ enqueueCodegraphRefresh({
345
+ dataDir,
346
+ projectId: canonicalId,
347
+ source: target === 'hook-user-prompt' ? 'hook-user-prompt' : 'hook-session-start',
348
+ maxFiles: 5_000,
349
+ });
350
+ }),
351
+ deliveryTarget: target,
352
+ });
353
+
354
+ return {
355
+ prompt: formatAutoProjectContextPrompt(context),
356
+ hasContinuation: Boolean(
357
+ context.continuation?.previousSession || (context.continuation?.memories.length ?? 0) > 0,
358
+ ),
359
+ };
360
+ } catch (error) {
361
+ // A context hint must never interrupt the host's turn. The structured
362
+ // error is intentionally kept in stderr for hook diagnostics.
363
+ console.error('[memorix] hook context failed:', (error as Error)?.message ?? error);
364
+ return null;
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Claude Code ignores SessionStart systemMessage as model context. Its official
370
+ * UserPromptSubmit output accepts additionalContext, so explicit continuation
371
+ * requests are delivered there instead of relying on a rules-file suggestion.
372
+ */
373
+ async function buildClaudeContinuationPromptContext(input: NormalizedHookInput): Promise<string | undefined> {
374
+ if (input.agent !== 'claude' || input.event !== 'user_prompt' || !input.userPrompt?.trim()) {
375
+ return undefined;
376
+ }
377
+
378
+ const { isContinuationTask } = await import('../codegraph/task-lens.js');
379
+ if (!isContinuationTask(input.userPrompt)) return undefined;
380
+
381
+ if (await getHookInjectionMode(input) === 'silent') return undefined;
382
+
383
+ const context = await buildHookProjectContext(input, input.userPrompt, 'hook-user-prompt');
384
+ if (!context?.hasContinuation) return undefined;
385
+
386
+ return [
387
+ 'Memorix prepared a bounded prior-work brief for this explicit continuation request.',
388
+ 'Treat it as background context; current code wins. Use it before broad Git or file-history archaeology.',
389
+ '',
390
+ context.prompt,
391
+ ].join('\n');
392
+ }
393
+
285
394
  async function handleSessionStart(input: NormalizedHookInput): Promise<{
286
395
  observation: ReturnType<typeof buildObservation> | null;
287
396
  output: HookOutput;
288
397
  }> {
289
- // Check behavior config for session injection level
290
- let injectMode: 'full' | 'minimal' | 'silent' = 'minimal';
291
- try {
292
- const { getBehaviorConfig } = await import('../config/behavior.js');
293
- injectMode = getBehaviorConfig().sessionInject;
294
- } catch { /* default to minimal */ }
398
+ const injectMode = await getHookInjectionMode(input);
295
399
 
296
400
  if (injectMode === 'silent') {
297
401
  return { observation: null, output: { continue: true } };
@@ -299,55 +403,8 @@ async function handleSessionStart(input: NormalizedHookInput): Promise<{
299
403
 
300
404
  let contextSummary = '';
301
405
  if (injectMode === 'full') {
302
- try {
303
- const { detectProject } = await import('../project/detector.js');
304
- const { getProjectDataDir } = await import('../store/persistence.js');
305
- const { initObservationStore, getObservationStore: getStore } = await import('../store/obs-store.js');
306
- const { initMiniSkillStore } = await import('../store/mini-skill-store.js');
307
- const { initSessionStore } = await import('../store/session-store.js');
308
- const { initAliasRegistry, registerAlias } = await import('../project/aliases.js');
309
- const { MaintenanceTargetStore } = await import('../runtime/maintenance-targets.js');
310
- const { buildAutoProjectContext, formatAutoProjectContextPrompt } = await import('../codegraph/auto-context.js');
311
- const { filterReadableObservations } = await import('../memory/visibility.js');
312
-
313
- const rawProject = detectProject(input.cwd || process.cwd());
314
- if (!rawProject) throw new Error('No .git found');
315
- const dataDir = await getProjectDataDir(rawProject.id);
316
-
317
- initAliasRegistry(dataDir);
318
- const canonicalId = await registerAlias(rawProject);
319
- new MaintenanceTargetStore(dataDir).register({
320
- projectId: canonicalId,
321
- projectRoot: rawProject.rootPath,
322
- dataDir,
323
- });
324
- await initObservationStore(dataDir);
325
- await initMiniSkillStore(dataDir);
326
- await initSessionStore(dataDir);
327
- const activeObservations = filterReadableObservations(
328
- await getStore().loadByProject(canonicalId, { status: 'active' }),
329
- { projectId: canonicalId },
330
- );
331
- const context = await buildAutoProjectContext({
332
- project: { ...rawProject, id: canonicalId },
333
- dataDir,
334
- observations: activeObservations,
335
- refresh: 'auto',
336
- enqueueRefresh: () => import('../runtime/lifecycle.js').then(({ enqueueCodegraphRefresh }) => {
337
- enqueueCodegraphRefresh({
338
- dataDir,
339
- projectId: canonicalId,
340
- source: 'hook-session-start',
341
- maxFiles: 5_000,
342
- });
343
- }),
344
- deliveryTarget: 'hook-session-start',
345
- });
346
- contextSummary = `\n\n${formatAutoProjectContextPrompt(context)}`;
347
- } catch (sessErr) {
348
- // Diagnostic log — session start context injection failed
349
- console.error('[memorix] session start context failed:', (sessErr as Error)?.message ?? sessErr);
350
- }
406
+ const context = await buildHookProjectContext(input, 'Continue the current task.', 'hook-session-start');
407
+ if (context) contextSummary = `\n\n${context.prompt}`;
351
408
  }
352
409
 
353
410
  // Build system message based on inject mode
@@ -378,6 +435,10 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
378
435
  output: HookOutput;
379
436
  }> {
380
437
  const defaultOutput: HookOutput = { continue: true };
438
+ const continuationMessage = await buildClaudeContinuationPromptContext(input);
439
+ const output = continuationMessage
440
+ ? { ...defaultOutput, systemMessage: continuationMessage }
441
+ : defaultOutput;
381
442
 
382
443
  // ─── Session lifecycle (special handling) ───
383
444
  if (input.event === 'session_start') {
@@ -386,7 +447,7 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
386
447
  if (input.event === 'session_end') {
387
448
  const endContent = extractContent(input);
388
449
  if (endContent.length < 50) {
389
- return { observation: null, output: defaultOutput };
450
+ return { observation: null, output };
390
451
  }
391
452
  const draft = buildObservation(input, endContent, 'unknown');
392
453
  const admission = assessHookAdmission({
@@ -399,13 +460,13 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
399
460
  observation: admission.action === 'store'
400
461
  ? buildObservation(input, endContent, 'unknown', admission)
401
462
  : null,
402
- output: defaultOutput,
463
+ output,
403
464
  };
404
465
  }
405
466
  if (input.event === 'post_compact') {
406
467
  // Post-compaction: acknowledge the event, no observation needed.
407
468
  // The real value is the side-effect (runHook pipe) already handled by the plugin.
408
- return { observation: null, output: defaultOutput };
469
+ return { observation: null, output };
409
470
  }
410
471
 
411
472
  // ─── Classify & extract ───
@@ -415,7 +476,7 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
415
476
 
416
477
  // Never-store category (memorix's own tools)
417
478
  if (policy.store === 'never') {
418
- return { observation: null, output: defaultOutput };
479
+ return { observation: null, output };
419
480
  }
420
481
 
421
482
  // ─── Significance Filter (Cipher-style noise rejection) ───
@@ -423,13 +484,13 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
423
484
  if (category === 'command' && input.command) {
424
485
  const realCmd = extractRealCommand(input.command);
425
486
  if (isTrivialCommand(realCmd)) {
426
- return { observation: null, output: defaultOutput };
487
+ return { observation: null, output };
427
488
  }
428
489
  }
429
490
 
430
491
  // Skip retrieved/search results (prevent memory pollution)
431
492
  if (isRetrievedResult(content)) {
432
- return { observation: null, output: defaultOutput };
493
+ return { observation: null, output };
433
494
  }
434
495
 
435
496
  // Minimum length gate
@@ -437,7 +498,7 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
437
498
  ? MIN_PROMPT_LENGTH
438
499
  : policy.minLength;
439
500
  if (content.length < minLen) {
440
- return { observation: null, output: defaultOutput };
501
+ return { observation: null, output };
441
502
  }
442
503
 
443
504
  // User prompts & AI responses are direct interaction — check significance
@@ -450,7 +511,7 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
450
511
  if (effectiveStore !== 'always') {
451
512
  const significance = isSignificantKnowledge(content);
452
513
  if (!significance.isSignificant) {
453
- return { observation: null, output: defaultOutput };
514
+ return { observation: null, output };
454
515
  }
455
516
  }
456
517
 
@@ -459,14 +520,14 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
459
520
  const pattern = detectBestPattern(content);
460
521
  const significance = isSignificantKnowledge(content);
461
522
  if (!pattern && content.length < 200 && !significance.isSignificant) {
462
- return { observation: null, output: defaultOutput };
523
+ return { observation: null, output };
463
524
  }
464
525
  }
465
526
 
466
527
  // Cooldown (per-file or per-command, not per-tool-category)
467
528
  const cooldownKey = buildCooldownKey(input, content);
468
529
  if (isInCooldown(cooldownKey)) {
469
- return { observation: null, output: defaultOutput };
530
+ return { observation: null, output };
470
531
  }
471
532
  markTriggered(cooldownKey);
472
533
 
@@ -481,7 +542,7 @@ async function handleHookEventCore(input: NormalizedHookInput): Promise<{
481
542
  observation: admission.action === 'store'
482
543
  ? buildObservation(input, content, category, admission)
483
544
  : null,
484
- output: defaultOutput,
545
+ output,
485
546
  };
486
547
  }
487
548
 
@@ -1210,17 +1210,18 @@ function getAgentRulesContent(agent?: AgentName, scope: 'project' | 'global' = '
1210
1210
  '',
1211
1211
  '## Start with Memory Autopilot',
1212
1212
  '',
1213
- `Default first step for non-trivial coding work: call \x60memorix_project_context\x60 with the user's actual task before progress files, dev-log reads, ad-hoc file reads, or git archaeology. Memorix will choose a task-lensed brief (bugfix, feature, release, onboarding, refactor, docs, test, or general). Treat its "Start here" files as the first ${contextNoun} files to inspect.`,
1213
+ `Default first step for non-trivial coding work: call \x60memorix_project_context\x60 with the user's actual task before progress files, dev-log reads, ad-hoc file reads, or git archaeology. Memorix will choose a task-lensed brief (bugfix, feature, release, onboarding, refactor, docs, test, or general). When the task is continuing prior work, the same brief also includes a bounded prior-work projection. Treat its "Start here" files as the first ${contextNoun} files to inspect.`,
1214
1214
  '',
1215
- 'If the MCP tool is not visible yet but the client supports tool discovery or dynamic loading, search/select \x60memorix_project_context\x60 first. Run \x60memorix context --task "<task>"\x60 only after MCP is unavailable, disabled, or not discoverable, and pass the user\'s real task text. Do not skip memory, wait indefinitely on MCP startup, or hand-write tool-call syntax.',
1215
+ 'If the MCP tool is not visible yet but the client supports tool discovery or dynamic loading, search/select \x60memorix_project_context\x60 first. Continuation fallback is mandatory: when the user asks to continue, resume, take over, or explain prior work and MCP cannot be called in this turn, run exactly one CLI brief with the user\'s real task before inspecting files, Git history, progress notes, or guessing: \x60memorix resume "<task>" --json\x60. For a new task, use \x60memorix context "<task>" --json\x60 instead. The absence of \x60.memorix\x60 or visible memory files never proves project memory is empty. If that one command fails, report it and proceed normally. Do not probe help, enumerate commands, chain broad searches, wait indefinitely on MCP startup, or hand-write tool-call syntax.',
1216
1216
  '',
1217
- 'Use \x60memorix_context_pack\x60 when you need structured refs and freshness for code-bound memories.',
1217
+ 'After a successful \x60memorix_project_context\x60 result, the brief is the default retrieval boundary. Do not call more Memorix retrieval tools after a complete brief. Use \x60memorix_context_pack\x60, \x60memorix_search\x60, or \x60memorix_detail\x60 only when the brief lacks a specific reference, freshness field, or fact needed for the task, or when the user explicitly asks for deeper history. In MCP, name that missing fact in \x60purpose\x60 when intentionally expanding beyond the brief. Do not retrieve the same decision twice just to confirm an already-complete brief.',
1218
+ 'If the user asks for read-only work or says not to modify files, do not call \x60memorix_store\x60 just to record an assessment. Store only when the user explicitly asks to preserve it.',
1218
1219
  '',
1219
1220
  '## When to search memory',
1220
1221
  '',
1221
1222
  'Use \x60memorix_graph_context\x60 for explicit memory graph questions or broad graph overview after the autopilot brief is not enough.',
1222
1223
  '',
1223
- `Use \x60memorix_search\x60 when prior ${contextNoun} context would help — for example:`,
1224
+ `Use \x60memorix_search\x60 when prior ${contextNoun} context would help and the Autopilot brief did not already answer the question — for example:`,
1224
1225
  '- The user asks about a past decision, bug, or change',
1225
1226
  '- You need to understand why something was designed a certain way',
1226
1227
  "- You're continuing work that started in a previous session",
@@ -31,7 +31,8 @@ export const OFFICIAL_MEMORIX_SKILLS: OfficialMemorixSkill[] = [
31
31
  '',
32
32
  '| Situation | Prefer | CLI fallback |',
33
33
  '|---|---|---|',
34
- '| Starting or continuing a coding task and needing the best task-lensed project map | `memorix_project_context` with the user\'s task | `memorix context --task "<task>"` |',
34
+ '| Starting a coding task and needing the best task-lensed project map | `memorix_project_context` with the user\'s task | `memorix context "<task>" --json` |',
35
+ '| Continuing prior project work | `memorix_project_context` with the user\'s task | `memorix resume "<task>" --json` |',
35
36
  '| Need structured refs/freshness for code-bound memories | `memorix_context_pack` | `memorix codegraph context-pack --task "<topic>"` |',
36
37
  '| Explicit memory graph question | `memorix_graph_context` | `memorix memory graph-context --query "<topic>"` |',
37
38
  '| Specific past decision, bug, file, or change | `memorix_search` | `memorix memory search --query "<topic>"` |',
@@ -44,9 +45,10 @@ export const OFFICIAL_MEMORIX_SKILLS: OfficialMemorixSkill[] = [
44
45
  '',
45
46
  '- Default first step for non-trivial coding work: call `memorix_project_context` before progress files, dev-log reads, ad-hoc file reads, or git archaeology. Pass the user\'s actual task so Memorix can choose a bugfix, feature, release, onboarding, refactor, docs, test, or general brief. Start by reading its suggested files.',
46
47
  '- In Claude Code headless/print-mode, an initial MCP `pending` status is not a failure by itself. Prefer MCP first: use the client\'s tool discovery/dynamic loading to find `memorix_project_context` when it is not in the first visible tool list.',
47
- '- Run `memorix context --task "<task>"` from the shell only after MCP is unavailable, disabled, or not discoverable, and pass the user\'s real task text. Do not skip memory, wait indefinitely on `pending`, or hand-write tool-call syntax.',
48
- '- Use `memorix_search` for a specific decision, bug, file, or prior change that the project context did not answer.',
49
- '- Fetch detail before relying on a specific memory.',
48
+ '- Continuation fallback is mandatory: when the user asks to continue, resume, take over, or explain prior work and MCP cannot be called in this turn, run `memorix resume "<task>" --json` exactly once before inspecting files, Git history, progress notes, or guessing. The absence of `.memorix` or visible memory files never proves project memory is empty. For a new task, use `memorix context "<task>" --json` instead. If that one command fails, report it and proceed normally; do not probe help, enumerate commands, or chain broad searches.',
49
+ '- After a successful `memorix_project_context`, the brief is the default retrieval boundary. Do not call more Memorix retrieval tools after a complete brief. Use Context Pack, search, or detail only when the brief lacks a specific reference, freshness field, or fact needed for the task, or when the user explicitly asks for deeper history. In MCP, name that missing fact in `purpose` when intentionally expanding beyond the brief. Do not retrieve the same decision twice just to confirm an already-complete brief.',
50
+ '- If the user asks for read-only work or says not to modify files, do not call `memorix_store` just to record an assessment. Store only when the user explicitly asks to preserve it.',
51
+ '- Use `memorix_search` for a specific decision, bug, file, or prior change that the project context did not answer. Fetch detail only for a result you still need after the brief.',
50
52
  '- Treat current code-bound memory as a map. Treat stale, suspect, or unbound memory as a lead that must be verified against the current code.',
51
53
  '- Skip memory lookup for greetings, tiny one-off edits, or questions fully answered by the current file.',
52
54
  '- If a fresh project has no memories, proceed normally and do not repeat the same empty search in the same turn.',
@@ -7,13 +7,15 @@ You have access to Memorix memory tools. Follow these rules to maintain persiste
7
7
  At the beginning of non-trivial coding work, use Memorix Memory Autopilot before local progress notes or broad file exploration. A session bind is not required for every conversation.
8
8
 
9
9
  1. Default first step for non-trivial coding work: call `memorix_project_context` with the user's actual task before progress files, dev-log reads, ad-hoc file reads, or git archaeology. Memorix will choose a task-lensed brief (bugfix, feature, release, onboarding, refactor, docs, test, or general). Treat its "Start here" files as the first code or docs to inspect.
10
- 2. If the MCP tool is not visible yet but the client supports tool discovery or dynamic loading, search/select `memorix_project_context` first. Run `memorix context --task "<task>"` only after MCP is unavailable, disabled, or not discoverable, and pass the user's real task text. Do not skip memory, wait indefinitely on MCP startup, or hand-write tool-call syntax.
11
- 3. Use `memorix_context_pack` when you need structured refs and freshness for code-bound memories.
12
- 4. For broad memory graph questions, call `memorix_graph_context` to get a compact background packet.
13
- 5. For specific past decisions, bugs, files, or changes, call `memorix_search` with a focused query.
14
- 6. If search results are found, use `memorix_detail` only for the few refs you actually need.
15
- 7. Call `memorix_session_start` only when explicit session semantics are useful: handoff, long-running work, orchestration coordination, restoring prior session context, or HTTP project binding.
16
- 8. Reference relevant memories naturally in your response; do not just list them.
10
+ 2. If the MCP tool is not visible yet but the client supports tool discovery or dynamic loading, search/select `memorix_project_context` first. Continuation fallback is mandatory: when the user asks to continue, resume, take over, or explain prior work and MCP cannot be called in this turn, run exactly one CLI brief with the user's real task before inspecting files, Git history, progress notes, or guessing: use `memorix resume "<task>" --json`. For a new task, use `memorix context "<task>" --json` instead. The absence of `.memorix` or visible memory files never proves project memory is empty. If that one command fails, report it and proceed normally. Do not probe help, enumerate commands, chain broad searches, wait indefinitely on MCP startup, or hand-write tool-call syntax.
11
+ 3. After a successful `memorix_project_context` result, the brief is the default retrieval boundary. Do not call more Memorix retrieval tools after a complete brief. Use `memorix_context_pack`, `memorix_search`, or `memorix_detail` only when the brief lacks a specific reference, freshness field, or fact needed for the task, or when the user explicitly asks for deeper history. In MCP, name that missing fact in `purpose` when intentionally expanding beyond the brief. Do not retrieve the same decision twice just to confirm an already-complete brief.
12
+ If the user asks for read-only work or says not to modify files, do not call `memorix_store` just to record an assessment. Store only when the user explicitly asks to preserve it.
13
+ 4. Use `memorix_context_pack` when you need structured refs and freshness for code-bound memories.
14
+ 5. For broad memory graph questions, call `memorix_graph_context` to get a compact background packet after the Autopilot brief is not enough.
15
+ 6. For a specific past decision, bug, file, or change that the brief did not answer, call `memorix_search` with a focused query.
16
+ 7. If search results are found, use `memorix_detail` only for the few refs you actually need.
17
+ 8. Call `memorix_session_start` only when explicit session semantics are useful: handoff, long-running work, orchestration coordination, restoring prior session context, or HTTP project binding.
18
+ 9. Reference relevant memories naturally in your response; do not just list them.
17
19
 
18
20
  If `memorix_search` says this is a fresh project with no Memorix memories yet, treat that as a successful cold-start signal. Do not repeat `memorix_search` again in the same turn unless the user explicitly asks for history/context, or new memories were written during the turn.
19
21
 
@@ -7,10 +7,12 @@ export type ContextDeliveryTarget =
7
7
  | 'project-context'
8
8
  | 'context-pack'
9
9
  | 'hook-session-start'
10
+ | 'hook-user-prompt'
10
11
  | 'session-handoff';
11
12
 
12
13
  export type ContextCandidateKind =
13
14
  | 'task'
15
+ | 'continuation'
14
16
  | 'current-fact'
15
17
  | 'code-state'
16
18
  | 'semantic-code'
@@ -41,7 +43,7 @@ export interface ContextReceiptOmission {
41
43
  }
42
44
 
43
45
  export interface ContextReceipt {
44
- version: '1.2.2';
46
+ version: '1.2.4';
45
47
  target: ContextDeliveryTarget;
46
48
  elapsedMs: number;
47
49
  budget: {
@@ -58,6 +60,7 @@ function displayTarget(target: ContextDeliveryTarget): string {
58
60
  case 'project-context': return 'Project Context';
59
61
  case 'context-pack': return 'Context Pack';
60
62
  case 'hook-session-start': return 'SessionStart hook';
63
+ case 'hook-user-prompt': return 'UserPromptSubmit hook';
61
64
  case 'session-handoff': return 'session handoff';
62
65
  }
63
66
  }
@@ -77,11 +77,28 @@ export interface WorksetMemorySource {
77
77
  reason?: string;
78
78
  }
79
79
 
80
+ /** Prior-work evidence selected only for an explicit or inferred continuation. */
81
+ export interface WorksetContinuation {
82
+ previousSession?: {
83
+ id: string;
84
+ agent?: string;
85
+ endedAt?: string;
86
+ summary: string;
87
+ };
88
+ memories: Array<{
89
+ id: number;
90
+ title: string;
91
+ type: string;
92
+ detail?: string;
93
+ }>;
94
+ }
95
+
80
96
  export interface TaskWorkset {
81
97
  version: '1.2';
82
98
  task: string;
83
99
  lens: string;
84
100
  currentFacts: string[];
101
+ continuation?: WorksetContinuation;
85
102
  codeState?: string;
86
103
  startHere: string[];
87
104
  /** Bounded task-specific relations from a validated local semantic graph. */
@@ -117,6 +134,7 @@ export interface BuildTaskWorksetInput {
117
134
  task?: string;
118
135
  lens: string;
119
136
  currentFacts?: string[];
137
+ continuation?: WorksetContinuation;
120
138
  codeState?: string;
121
139
  startHere: string[];
122
140
  semanticCode?: ExternalCodeGraphOutline;
@@ -151,6 +169,11 @@ function short(text: string, budget = 28): string {
151
169
  return countTextTokens(safe) <= budget ? safe : truncateToTokenBudget(safe, budget);
152
170
  }
153
171
 
172
+ // A continuation anchor often contains the exact flag, path, or command that
173
+ // makes the handoff actionable. Preserve a little more of it than generic
174
+ // display detail; the enclosing Workset budget still decides whether it fits.
175
+ const CONTINUATION_DETAIL_TOKEN_BUDGET = 20;
176
+
154
177
  function claimAssertion(claim: KnowledgeClaim): string {
155
178
  return short([claim.subject, claim.predicate, claim.objectValue].join(' '));
156
179
  }
@@ -259,6 +282,7 @@ function freshnessForMemory(status: WorksetMemorySource['status']): ContextCandi
259
282
  }
260
283
 
261
284
  function receiptOmissionKind(raw: string): ContextCandidateKind | undefined {
285
+ if (raw.includes('continuation')) return 'continuation';
262
286
  if (raw.includes('task')) return 'task';
263
287
  if (raw.includes('fact')) return 'current-fact';
264
288
  if (raw.includes('state')) return 'code-state';
@@ -328,6 +352,51 @@ export function renderTaskWorksetPrompt(input: Omit<TaskWorkset, 'prompt' | 'bud
328
352
  });
329
353
  appendLine(lines, 'Task lens: ' + input.lens, maxTokens, omitted, 'lens');
330
354
 
355
+ const hasContinuation = Boolean(
356
+ input.continuation?.previousSession || (input.continuation?.memories.length ?? 0) > 0,
357
+ );
358
+ if (hasContinuation && input.continuation) {
359
+ appendLine(lines, '', maxTokens, omitted, 'continuation-heading');
360
+ appendLine(lines, 'Resume from prior work', maxTokens, omitted, 'continuation-heading');
361
+ if (input.continuation.previousSession) {
362
+ const session = input.continuation.previousSession;
363
+ const source = [session.agent, session.endedAt ? session.endedAt.slice(0, 10) : undefined]
364
+ .filter(Boolean)
365
+ .join(', ');
366
+ appendLine(
367
+ lines,
368
+ '- Previous session' + (source ? ` (${source})` : '') + ': ' + short(session.summary, 44),
369
+ maxTokens,
370
+ omitted,
371
+ 'continuation-session',
372
+ selected,
373
+ {
374
+ kind: 'continuation',
375
+ id: 'session:' + session.id,
376
+ reason: 'latest meaningful project session summary',
377
+ trust: 'historical',
378
+ },
379
+ );
380
+ }
381
+ for (const memory of input.continuation.memories.slice(0, 3)) {
382
+ const detail = memory.detail ? ': ' + short(memory.detail, CONTINUATION_DETAIL_TOKEN_BUDGET) : '';
383
+ appendLine(
384
+ lines,
385
+ '- #' + memory.id + ' ' + memory.type + ': ' + short(memory.title, 18) + detail,
386
+ maxTokens,
387
+ omitted,
388
+ 'continuation-memory',
389
+ selected,
390
+ {
391
+ kind: 'continuation',
392
+ id: 'memory:' + memory.id,
393
+ reason: 'durable prior-work memory',
394
+ trust: 'historical',
395
+ },
396
+ );
397
+ }
398
+ }
399
+
331
400
  if (input.cautions.length > 0 || input.cautionMemory.length > 0) {
332
401
  appendLine(lines, '', maxTokens, omitted, 'caution-heading');
333
402
  appendLine(lines, 'Cautions', maxTokens, omitted, 'caution-heading');
@@ -629,6 +698,24 @@ export async function buildTaskWorkset(input: BuildTaskWorksetInput): Promise<Ta
629
698
  const normalizedCautions = unique(cautions.map(caution => caution.kind))
630
699
  .map(kind => cautions.find(caution => caution.kind === kind)!)
631
700
  .slice(0, 6);
701
+ const continuation = input.continuation
702
+ && (input.continuation.previousSession || input.continuation.memories.length > 0)
703
+ ? {
704
+ ...(input.continuation.previousSession
705
+ ? {
706
+ previousSession: {
707
+ ...input.continuation.previousSession,
708
+ summary: short(input.continuation.previousSession.summary, 52),
709
+ },
710
+ }
711
+ : {}),
712
+ memories: input.continuation.memories.slice(0, 3).map((memory) => ({
713
+ ...memory,
714
+ title: short(memory.title, 20),
715
+ ...(memory.detail ? { detail: short(memory.detail, CONTINUATION_DETAIL_TOKEN_BUDGET) } : {}),
716
+ })),
717
+ }
718
+ : undefined;
632
719
  const base = {
633
720
  version: '1.2' as const,
634
721
  task,
@@ -636,6 +723,7 @@ export async function buildTaskWorkset(input: BuildTaskWorksetInput): Promise<Ta
636
723
  currentFacts: input.currentFacts?.map(fact => fact.startsWith('Historical note:')
637
724
  ? short(fact, 48)
638
725
  : short(fact, 28)).slice(0, 4) ?? [],
726
+ ...(continuation ? { continuation } : {}),
639
727
  ...(input.codeState ? { codeState: short(input.codeState, 28) } : {}),
640
728
  startHere: unique(input.startHere).slice(0, 5),
641
729
  ...(input.semanticCode ? { semanticCode: input.semanticCode } : {}),
@@ -660,7 +748,7 @@ export async function buildTaskWorkset(input: BuildTaskWorksetInput): Promise<Ta
660
748
  budget: { maxTokens },
661
749
  });
662
750
  const receipt: ContextReceipt = {
663
- version: '1.2.2',
751
+ version: '1.2.4',
664
752
  target: input.deliveryTarget ?? 'project-context',
665
753
  elapsedMs: Math.max(0, Date.now() - startedAt),
666
754
  budget: {