dsh-cross-memory 0.2.12 → 0.2.14

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 (43) hide show
  1. package/README.md +55 -16
  2. package/docs/DETAIL.md +13 -10
  3. package/docs/DETAIL.zh.md +13 -10
  4. package/lib/backfill.js +32 -1
  5. package/lib/client.js +3 -3
  6. package/lib/consolidate.js +41 -39
  7. package/lib/dense.js +47 -15
  8. package/lib/extract.js +39 -11
  9. package/lib/gate.js +35 -19
  10. package/lib/index.js +221 -131
  11. package/lib/mcp.js +330 -0
  12. package/lib/notify.js +10 -5
  13. package/lib/persona.js +99 -1
  14. package/lib/raw-recall.js +18 -7
  15. package/lib/reflection.js +10 -1
  16. package/lib/state.js +19 -7
  17. package/lib/storage.js +11 -1
  18. package/lib/sync.js +36 -14
  19. package/lib/test/archive.test.js +19 -0
  20. package/lib/test/consolidate.test.js +48 -10
  21. package/lib/test/extract.test.js +30 -1
  22. package/lib/test/loops.test.js +3 -2
  23. package/lib/test/mcp.test.js +103 -0
  24. package/lib/test/notices.test.js +67 -0
  25. package/lib/test/persona.test.js +40 -1
  26. package/lib/test/recall.test.js +54 -1
  27. package/lib/test/reflection.test.js +60 -1
  28. package/lib/test/subagent-contract.test.js +18 -12
  29. package/lib/test/sync.test.js +4 -0
  30. package/lib/tool.js +4 -3
  31. package/lib/types/backfill.d.ts +5 -0
  32. package/lib/types/consolidate.d.ts +34 -51
  33. package/lib/types/dense.d.ts +7 -2
  34. package/lib/types/extract.d.ts +14 -0
  35. package/lib/types/gate.d.ts +4 -0
  36. package/lib/types/index.d.ts +10 -0
  37. package/lib/types/mcp.d.ts +184 -0
  38. package/lib/types/notify.d.ts +3 -2
  39. package/lib/types/persona.d.ts +17 -0
  40. package/lib/types/raw-recall.d.ts +1 -0
  41. package/lib/types/sync.d.ts +7 -5
  42. package/lib/types/test/mcp.test.d.ts +1 -0
  43. package/package.json +14 -7
@@ -12,7 +12,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
12
12
  import { tmpdir } from 'node:os';
13
13
  import { join } from 'node:path';
14
14
  import test from 'node:test';
15
- import { REFLECTION_INTERVAL_MS, REFLECTION_MIN_ENTRIES, listReflections, parseReflection, replyStats, previousInsights, reflectionDue, renderReflectionFile, writeReflection, } from '../reflection.js';
15
+ import { REFLECTION_INTERVAL_MS, REFLECTION_MIN_ENTRIES, listReflections, parseReflection, replyStats, previousInsights, reflectionDue, renderReflectionFile, runReflection, writeReflection, } from '../reflection.js';
16
16
  const NOW = Date.parse('2026-10-24T03:00:00Z');
17
17
  const known = new Set(['mem-a', 'mem-b']);
18
18
  test('an observation that cannot cite the store is dropped', () => {
@@ -62,3 +62,62 @@ test('a zero result reports whether the reply was empty or merely uncited', () =
62
62
  assert.equal(replyStats('not json', known), undefined);
63
63
  assert.deepEqual(replyStats('{"insights":"nope"}', known), { raw: 0, cited: 0 });
64
64
  });
65
+ test('runReflection falls back on empty provider/model and reports stream finish errors', async () => {
66
+ const entries = Array.from({ length: REFLECTION_MIN_ENTRIES }, (_, index) => ({
67
+ id: index === 0 ? 'mem-a' : `mem-${index}`,
68
+ scope: 'global',
69
+ kind: 'fact',
70
+ title: `title ${index}`,
71
+ body: `body ${index}`,
72
+ tags: [],
73
+ keys: [],
74
+ createdAt: NOW,
75
+ updatedAt: NOW,
76
+ uses: 0,
77
+ lastUsedAt: 0,
78
+ lastSurfacedAt: 0,
79
+ source: 'auto',
80
+ }));
81
+ const session = {
82
+ id: 'reflect-session',
83
+ requestHeader: () => ({ config: { provider: 'deepseek-account', model: 'deepseek-flash' } }),
84
+ };
85
+ const seen = {};
86
+ const okLlm = {
87
+ stream: (options) => {
88
+ seen.provider = options.provider;
89
+ seen.model = options.model;
90
+ return (async function* () {
91
+ yield { type: 'text-delta', index: 0, text: JSON.stringify({ insights: [{ text: '他总是在同一个项目上先写测试再改实现', evidence: ['mem-a'] }] }) };
92
+ yield { type: 'finish', reason: { kind: 'stop' } };
93
+ })();
94
+ },
95
+ };
96
+ const outcome = await runReflection({
97
+ llm: okLlm,
98
+ session,
99
+ entries,
100
+ provider: '',
101
+ model: '',
102
+ timeoutMs: 1000,
103
+ signal: new AbortController().signal,
104
+ });
105
+ assert.equal(seen.provider, 'deepseek-account');
106
+ assert.equal(seen.model, 'deepseek-flash');
107
+ assert.equal(outcome.insights.length, 1);
108
+ const errLlm = {
109
+ stream: () => (async function* () {
110
+ yield { type: 'finish', reason: { kind: 'error', failure: { message: 'empty route', code: 'BAD_ROUTE' } } };
111
+ })(),
112
+ };
113
+ const errOutcome = await runReflection({
114
+ llm: errLlm,
115
+ session,
116
+ entries,
117
+ timeoutMs: 1000,
118
+ signal: new AbortController().signal,
119
+ });
120
+ assert.equal(errOutcome.insights.length, 0);
121
+ assert.equal(errOutcome.skipped, 'failed');
122
+ assert.match(errOutcome.reason, /reflection call error: empty route/u);
123
+ });
@@ -75,7 +75,7 @@ function descriptorOf(spec) {
75
75
  /** A request naming a route and a preset, i.e. the common production case. */
76
76
  function routedRequest() {
77
77
  return {
78
- parent: {},
78
+ parent: { id: 'agent-1' },
79
79
  provider: 'test-provider',
80
80
  model: 'test-model',
81
81
  agentPreset: 'memories-consolidator',
@@ -91,7 +91,7 @@ function routedRequest() {
91
91
  /** A request with no route and no preset: both optionals must be absent, not undefined. */
92
92
  function bareRequest() {
93
93
  return {
94
- parent: {},
94
+ parent: { id: 'agent-1' },
95
95
  entries: [],
96
96
  projectLabel: 'demo',
97
97
  maxUpserts: 3,
@@ -113,10 +113,11 @@ test('the label is a non-empty string, so the kernel never sees undefined', () =
113
113
  });
114
114
  test('a bare request omits optional fields instead of setting them to undefined', () => {
115
115
  const spec = buildActivationSpec(bareRequest(), PROMPT, AbortSignal.timeout(1000));
116
- assert.ok(!('agentOptions' in spec.request));
117
- assert.ok(!('agentPreset' in spec.request));
118
- for (const [key, value] of Object.entries(spec.request)) {
119
- assert.ok(value !== undefined, `request.${key} is present but undefined`);
116
+ assert.ok(!('agentOptions' in spec));
117
+ assert.ok(!('agentPreset' in spec));
118
+ assert.ok(!('request' in spec), 'the kernel takes a flat SubagentActivationSpec, never a nested request');
119
+ for (const [key, value] of Object.entries(spec)) {
120
+ assert.ok(value !== undefined, `spec.${key} is present but undefined`);
120
121
  }
121
122
  assert.doesNotThrow(() => assertLossless(descriptorOf(spec)));
122
123
  });
@@ -133,15 +134,20 @@ test("the child's result is delivered to the caller, not announced to the parent
133
134
  const spec = buildActivationSpec(routedRequest(), PROMPT, AbortSignal.timeout(1_000));
134
135
  assert.equal(spec.delivery, 'caller');
135
136
  });
136
- test('the spec carries the signal at the top level, where the kernel reads it', () => {
137
- // The kernel's continuable path calls `spec.signal.throwIfAborted()` and passes
138
- // `spec.signal` into prepareContinuable; it never looks at `spec.request.signal`.
139
- // A spec with the signal only inside the request reserved the child and then
140
- // crashed with "Cannot read properties of undefined (reading 'throwIfAborted')".
137
+ test('the spec carries the flattened SubagentActivationSpec fields at the top level', () => {
138
+ // The kernel reads `spec.signal`, `spec.parent.id`, `spec.prompt`,
139
+ // `spec.agentPreset`, `spec.outputSchema`, and `spec.maxDepth` at the top level.
140
+ // Nesting them under `spec.request` caused `Cannot read properties of undefined (reading 'id')`
141
+ // inside `startActivation` at `spec.parent.id`.
141
142
  const timeout = AbortSignal.timeout(1_000);
142
143
  const spec = buildActivationSpec(routedRequest(), PROMPT, timeout);
143
144
  assert.equal(spec.signal, timeout, 'the top-level signal is the one the caller passed');
144
- assert.equal(spec.request.signal, timeout, 'and the request kept its own copy');
145
+ assert.equal(spec.parent.id, 'agent-1', 'spec.parent must be readable at the top level');
146
+ assert.deepEqual(spec.prompt, PROMPT);
147
+ assert.equal(spec.agentPreset, 'memories-consolidator');
148
+ assert.equal(spec.maxDepth, 1);
149
+ assert.ok(spec.outputSchema !== undefined);
150
+ assert.equal('request' in spec, false);
145
151
  assert.equal(typeof spec.signal.throwIfAborted, 'function');
146
152
  assert.doesNotThrow(() => spec.signal.throwIfAborted());
147
153
  });
@@ -76,6 +76,8 @@ test('machine state is kept out of the repository', async () => {
76
76
  await mkdir(join(base, 'entries'), { recursive: true });
77
77
  await writeFile(join(base, 'state.db'), 'binary');
78
78
  await writeFile(join(base, 'index.json'), '{}');
79
+ await mkdir(join(base, 'cache'), { recursive: true });
80
+ await writeFile(join(base, 'cache', 'dense-test.json'), '{}');
79
81
  await writeFile(join(base, 'entries', 'one.md'), entryText('one', 'kept', '2026-02-01T00:00:00.000Z'));
80
82
  const sync = new MemorySync({ memoriesDir: base, remote: '', intervalMs: 0, debounceMs: 0, gitTimeoutMs: 20_000, networkTimeoutMs: 20_000, log: quietLog, host: 'test' });
81
83
  await sync.init();
@@ -83,6 +85,8 @@ test('machine state is kept out of the repository', async () => {
83
85
  assert.ok(tracked.includes('entries/one.md'), 'an entry is tracked');
84
86
  assert.ok(!tracked.includes('state.db'), 'the database is not tracked');
85
87
  assert.ok(!tracked.includes('index.json'), 'the index cache is not tracked');
88
+ assert.ok(!tracked.includes('cache/dense-test.json'), 'the dense cache is not tracked');
89
+ assert.ok(STORE_GITIGNORE.includes('cache/'));
86
90
  assert.equal(await readFile(join(base, '.gitignore'), 'utf8'), STORE_GITIGNORE);
87
91
  });
88
92
  test('only entry paths are auto-resolved, and the newer revision wins without a resolver', () => {
package/lib/tool.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * @module dsh-cross-memory/tool
9
9
  */
10
10
  import { defineTool } from '@deepseek-ai/dsh-tools';
11
+ import { redactSecrets } from './extract.js';
11
12
  import { renderEntry, renderEvidence, renderHit } from './render.js';
12
13
  /** The scopes the model may name. */
13
14
  const SCOPES = ['global', 'project'];
@@ -166,12 +167,12 @@ export function registerMemoryTool(ctx, runtime) {
166
167
  }
167
168
  const result = await runtime.write(session, {
168
169
  scope: args.scope,
169
- title: title.slice(0, 120),
170
- body,
170
+ title: redactSecrets(title).slice(0, 120),
171
+ body: redactSecrets(body),
171
172
  tags: args.tags ?? [],
172
173
  ...args.kind === undefined ? {} : { kind: args.kind },
173
174
  ...args.keys === undefined ? {} : { keys: args.keys },
174
- ...args.appliesTo === undefined ? {} : { appliesTo: args.appliesTo },
175
+ ...args.appliesTo === undefined ? {} : { appliesTo: redactSecrets(args.appliesTo) },
175
176
  ...args.durability === undefined ? {} : { durability: args.durability },
176
177
  ...asOf === undefined ? {} : { asOf },
177
178
  ...args.pinned === undefined ? {} : { pinned: args.pinned },
@@ -59,6 +59,11 @@ export declare function zstdAvailable(): boolean;
59
59
  * @throws when the Node build has no zstd support.
60
60
  */
61
61
  export declare function decodeSessionLog(buffer: Buffer): string;
62
+ /**
63
+ * Async variant of {@link decodeSessionLog}: decompresses frames on libuv's
64
+ * worker pool so large persisted logs never stall the Host event loop.
65
+ */
66
+ export declare function decodeSessionLogAsync(buffer: Buffer): Promise<string>;
62
67
  /**
63
68
  * Parse one decoded session log.
64
69
  *
@@ -194,7 +194,10 @@ export interface ConsolidationPlan {
194
194
  readonly persona?: string;
195
195
  }
196
196
  /** Render the input document handed to the consolidation agent. */
197
- export declare function renderConsolidationInput(entries: readonly MemoryEntry[], projectLabel: string, currentPersona?: string): string;
197
+ export declare function renderConsolidationInput(entries: readonly MemoryEntry[], projectLabel: string, currentPersona?: string, existingSkills?: readonly {
198
+ readonly name: string;
199
+ readonly description: string;
200
+ }[]): string;
198
201
  /** Parse and validate the agent's JSON reply into a plan. */
199
202
  export declare function parsePlan(text: string, knownIds: ReadonlySet<string>, maxUpserts: number): ConsolidationPlan | undefined;
200
203
  /**
@@ -237,6 +240,11 @@ export interface ConsolidateRequest {
237
240
  readonly entries: readonly MemoryEntry[];
238
241
  /** The profile as it stands, so the pass refines it rather than re-inventing it. */
239
242
  readonly persona?: string;
243
+ /** Existing skill drafts so the pass reuses names instead of creating duplicates. */
244
+ readonly existingSkills?: readonly {
245
+ readonly name: string;
246
+ readonly description: string;
247
+ }[];
240
248
  /** Model-facing project label. */
241
249
  readonly projectLabel: string;
242
250
  /** Cap on returned memories. */
@@ -269,10 +277,10 @@ export interface ConsolidateRequest {
269
277
  *
270
278
  * Two kernel shapes live here, because the seam changed under this plugin:
271
279
  *
272
- * - `startActivation` is the 0.2.1-rc.2 shape. The provider is named, the
273
- * request is nested under it, and the child's tool set comes from an Agent
274
- * Preset named in the request — `toolFilter` and `persona` are gone from the
275
- * start request (the model-facing subagent tool rejects both outright).
280
+ * - `startActivation` is the current flattened `SubagentActivationSpec` shape.
281
+ * `provider`, `label`, `signal`, `delivery`, `prompt`, `parent`,
282
+ * `agentOptions`, `outputSchema`, `maxDepth`, and `agentPreset` all live at
283
+ * the top level (`toolFilter` and `persona` are gone).
276
284
  * - `start` is the pre-0.2.1 shape: a name-addressed call whose request carries
277
285
  * `toolFilter` and `persona`.
278
286
  *
@@ -290,55 +298,30 @@ export interface ActivationSpec {
290
298
  * descriptor with `snapshotJsonValue`, which rejects `undefined`. Omitting
291
299
  * it therefore does not mean "no label" — it means "this descriptor cannot be
292
300
  * serialized", and the pass dies with `subagent descriptor is not losslessly
293
- * JSON-serializable`. Every consolidation attempt failed that way from
294
- * 2026-10-20 until this field was declared here.
301
+ * JSON-serializable`.
295
302
  */
296
303
  label: string;
297
- /**
298
- * Cancellation for the whole activation.
299
- *
300
- * Top-level, NOT inside `request`: the kernel reads `spec.signal` directly
301
- * (`spec.signal.throwIfAborted()`, and `prepareContinuable({ signal })`), so a
302
- * spec that carries the signal only in its request throws
303
- * `Cannot read properties of undefined (reading 'throwIfAborted')` — after the
304
- * child has already been reserved, which is why it reads as a crash rather than
305
- * a refusal.
306
- *
307
- * The kernel's continuable path reads exactly these top-level fields —
308
- * `provider`, `label`, `signal`, `childId`, `delivery`, `request` — and these
309
- * on the request: `prompt`, `parent`, `maxDepth`, `outputSchema`,
310
- * `agentOptions`, `agentPreset`, `cwd`. Anything omitted here fails at the
311
- * kernel boundary, not at this module's type boundary.
312
- */
304
+ /** Cancellation for the whole activation. */
313
305
  signal: AbortSignal;
314
306
  /**
315
307
  * Where the child's settlement notice goes.
316
308
  *
317
309
  * `caller` is right for this pass: the plugin consumes `run.result` itself, so
318
- * a settlement message pushed into the parent's inbox is noise. That noise was
319
- * actively misleading — the kernel marks a child that answers in plain text
320
- * instead of calling `structured_output` as `error`, so the parent was told
321
- * "Background subagent ... failed before it finished" while the plan had in fact
322
- * arrived intact (2026-11-06). The kernel's own plugin-creator starts its
323
- * children the same way.
310
+ * a settlement message pushed into the parent's inbox is noise.
324
311
  */
325
312
  delivery?: 'caller' | 'parent';
326
- request: {
327
- prompt: {
328
- type: 'text';
329
- text: string;
330
- }[];
331
- parent: Agent;
332
- /** Kept for the request contract even though the kernel reads the top-level one. */
333
- signal: AbortSignal;
334
- agentOptions?: {
335
- provider?: string;
336
- model?: string;
337
- };
338
- outputSchema?: unknown;
339
- maxDepth?: number;
340
- agentPreset?: string;
313
+ prompt: {
314
+ type: 'text';
315
+ text: string;
316
+ }[];
317
+ parent: Agent;
318
+ agentOptions?: {
319
+ provider?: string;
320
+ model?: string;
341
321
  };
322
+ outputSchema?: unknown;
323
+ maxDepth?: number;
324
+ agentPreset?: string;
342
325
  }
343
326
  /**
344
327
  * One finished child run, as the seam reports it.
@@ -358,6 +341,7 @@ export interface ChildRunResult {
358
341
  export interface SubagentSeam {
359
342
  startActivation?: (spec: ActivationSpec) => Promise<{
360
343
  result: Promise<ChildRunResult>;
344
+ dispose?: () => Promise<void>;
361
345
  }>;
362
346
  start?: (name: string, request: {
363
347
  prompt: {
@@ -429,18 +413,17 @@ export declare function denyToolsFor(available: ReadonlySet<string>): string[];
429
413
  */
430
414
  export declare function runConsolidation(seam: SubagentSeam, request: ConsolidateRequest): Promise<ConsolidationPlan | undefined>;
431
415
  /**
432
- * Build the spec the 0.2.1-rc.2 seam takes.
416
+ * Build the flattened `SubagentActivationSpec` the kernel seam takes.
433
417
  *
434
- * Extracted so a test can inspect it without a kernel: the one bug this shape
435
- * can carry — a missing `label` — is invisible from the seam's type unless the
436
- * type declares the field, and the failure it causes happens inside the
437
- * kernel's descriptor validator, three calls away from here. See
438
- * {@link ActivationSpec.label}.
418
+ * Extracted so a test can inspect it without a kernel: the kernel reads
419
+ * `provider`, `label`, `signal`, `delivery`, `prompt`, `parent`, `maxDepth`,
420
+ * `outputSchema`, `agentOptions`, and `agentPreset` at the top level.
439
421
  *
440
422
  * @param request - route, preset and lineage parent.
441
423
  * @param prompt - the child's single user message.
442
424
  * @param timeout - the child's deadline.
443
- * @returns the spec, with every optional field absent rather than `undefined`.
425
+ * @param outputSchema - JSON schema for structured output.
426
+ * @returns the flattened spec, with optional fields omitted rather than `undefined`.
444
427
  */
445
428
  export declare function buildActivationSpec(request: ConsolidateRequest, prompt: {
446
429
  type: 'text';
@@ -11,18 +11,23 @@ export interface DenseOptions {
11
11
  readonly model: string;
12
12
  /** Directory holding the JSON vector cache. */
13
13
  readonly cacheDir: string;
14
+ /** Optional HTTP request timeout in milliseconds (default 5000). */
15
+ readonly timeoutMs?: number;
14
16
  }
15
17
  /**
16
18
  * Embed texts, reusing the on-disk cache.
17
19
  *
18
20
  * Failures propagate: the caller decides whether to fall back. The cache is
19
- * written only after every batch succeeded, so a partial run never poisons it.
21
+ * written atomically only after every batch succeeded, so a partial run never
22
+ * poisons it. Ephemeral texts (like one-off queries) can pass `persistCount`
23
+ * to avoid bloating the on-disk cache with unshared query vectors.
20
24
  *
21
25
  * @param texts - texts to embed, in order.
22
26
  * @param options - service location, model, and cache directory.
27
+ * @param persistCount - how many leading items belong in the persistent cache (defaults to all).
23
28
  * @returns one unit vector per text.
24
29
  */
25
- export declare function embed(texts: readonly string[], options: DenseOptions): Promise<Float32Array[]>;
30
+ export declare function embed(texts: readonly string[], options: DenseOptions, persistCount?: number): Promise<Float32Array[]>;
26
31
  /**
27
32
  * Cosine similarity of two unit vectors (a dot product).
28
33
  * @param left - one vector.
@@ -167,6 +167,12 @@ export declare const EXTRACT_JSON_SCHEMA: {
167
167
  };
168
168
  };
169
169
  };
170
+ readonly closedLoops: {
171
+ readonly type: 'array';
172
+ readonly items: {
173
+ readonly type: 'string';
174
+ };
175
+ };
170
176
  readonly summary: {
171
177
  readonly type: 'string';
172
178
  };
@@ -255,6 +261,7 @@ export declare function parseExtraction(text: string, maxMemories: number, sessi
255
261
  text: string;
256
262
  dueAt?: number;
257
263
  }[];
264
+ closedLoops: string[];
258
265
  summary: string;
259
266
  dropped: number;
260
267
  };
@@ -352,6 +359,11 @@ export interface ExtractionRequest {
352
359
  * the title differently and ids come from titles.
353
360
  */
354
361
  readonly knownTitles?: readonly string[];
362
+ /** Open loops currently tracked, so the extractor can close completed ones. */
363
+ readonly openLoops?: readonly {
364
+ readonly id: string;
365
+ readonly text: string;
366
+ }[];
355
367
  /** Explicit route override. */
356
368
  readonly provider?: string;
357
369
  readonly model?: string;
@@ -403,6 +415,8 @@ export type ExtractionOutcome = {
403
415
  text: string;
404
416
  dueAt?: number;
405
417
  }[];
418
+ /** Ids of previously open loops that this transcript shows are now done. */
419
+ readonly closedLoops?: readonly string[];
406
420
  /** What the session was about, stored as the evidence behind the drafts. */
407
421
  readonly summary: string;
408
422
  /** Usable drafts the reply offered beyond `maxMemories`, reported to the caller. */
@@ -37,6 +37,8 @@ export declare const GATE_JSON_SCHEMA: {
37
37
  };
38
38
  };
39
39
  };
40
+ /** Output token cap for one gate call (leaves room for reasoning tokens). */
41
+ export declare const DEFAULT_GATE_MAX_OUTPUT_TOKENS = 2048;
40
42
  /** Everything one gate call needs. */
41
43
  export interface GateRequest {
42
44
  /** LLM runtime. */
@@ -50,6 +52,8 @@ export interface GateRequest {
50
52
  /** Explicit route override. */
51
53
  readonly provider?: string;
52
54
  readonly model?: string;
55
+ /** Output token cap for the gate call. */
56
+ readonly maxOutputTokens?: number;
53
57
  /** Deadline for the call. */
54
58
  readonly timeoutMs: number;
55
59
  /** Plugin lifecycle signal. */
@@ -49,6 +49,8 @@ interface ScopeState {
49
49
  readonly heading: string;
50
50
  readonly entries: readonly MemoryEntry[];
51
51
  }
52
+ /** Whether a session is a subagent rather than an interactive top-level session. */
53
+ export declare function isSubagentSession(session: Session): boolean;
52
54
  /**
53
55
  * The memory runtime: one instance per plugin mount, shared by the tool, the
54
56
  * injector, the extractor, and the command handler.
@@ -104,6 +106,8 @@ export declare class MemoriesRuntime {
104
106
  private readonly injected;
105
107
  /** Recall deltas already injected into each conversation. */
106
108
  private readonly recallCounts;
109
+ /** Latest human user turn id/seq whose full-history RAG excerpts were already injected. */
110
+ private readonly lastRagTurn;
107
111
  /** Late memory blocks already injected into each conversation. */
108
112
  private readonly deltaCounts;
109
113
  /** The user-turn number at which each conversation last emitted a rotation block. */
@@ -603,7 +607,10 @@ export declare class MemoriesRuntime {
603
607
  * @param session - session to read.
604
608
  * @returns the text, or `undefined` when no user message is on the surface.
605
609
  */
610
+ private latestUserTurn;
606
611
  private latestUserText;
612
+ /** Clean up per-session maps when an agent disposes. */
613
+ forgetSession(sessionId: string): void;
607
614
  /** Whether memory is switched off for one session. */
608
615
  private sessionOff;
609
616
  /** Entry ids already shown to one conversation, created on first use. */
@@ -698,6 +705,8 @@ export declare class MemoriesRuntime {
698
705
  stopPeriodicSync(): void;
699
706
  /** Record that a memory changed; the commit and the network happen later. */
700
707
  private markStoreChanged;
708
+ /** The boot notice check's timer, when one is armed. */
709
+ private bootNoticeTimer;
701
710
  /** The periodic check's timer, when one is armed. */
702
711
  private periodicTimer;
703
712
  /** The store's git transport; see {@link StoreSyncService}. */
@@ -779,6 +788,7 @@ export declare class MemoriesRuntime {
779
788
  /** Cancel a pending extraction timer. */
780
789
  cancelExtraction(agent: Agent): void;
781
790
  /** Remember an agent so a process exit can still mine it. */
791
+ private readonly trackedAgents;
782
792
  private track;
783
793
  /**
784
794
  * Mine every tracked agent once, right now.
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env node
2
+ import { MemoryStore } from './storage.js';
3
+ /** Runtime options for the MCP server. */
4
+ export interface McpServerOptions {
5
+ readonly memoriesDir: string;
6
+ readonly cacheDir?: string;
7
+ readonly denseEnabled: boolean;
8
+ readonly denseUrl: string;
9
+ readonly denseModel: string;
10
+ }
11
+ /** One incoming JSON-RPC 2.0 request or notification. */
12
+ export interface JsonRpcRequest {
13
+ readonly jsonrpc?: string;
14
+ readonly id?: string | number | null;
15
+ readonly method: string;
16
+ readonly params?: Record<string, unknown>;
17
+ }
18
+ /** One outgoing JSON-RPC 2.0 response. */
19
+ export interface JsonRpcResponse {
20
+ readonly jsonrpc: '2.0';
21
+ readonly id: string | number | null;
22
+ readonly result?: unknown;
23
+ readonly error?: {
24
+ readonly code: number;
25
+ readonly message: string;
26
+ };
27
+ }
28
+ /** Tool definitions exposed to MCP clients (compact on purpose). */
29
+ export declare const MCP_TOOLS: readonly [{
30
+ readonly name: 'memory_persona';
31
+ readonly description: 'Read the user profile (persona/human.md): who the user is, their working conventions, standards, environment, and communication preferences. Call this early in a new session when user preferences matter.';
32
+ readonly inputSchema: {
33
+ readonly type: 'object';
34
+ readonly properties: {};
35
+ readonly additionalProperties: false;
36
+ };
37
+ }, {
38
+ readonly name: 'memory_search';
39
+ readonly description: 'Search durable cross-session memories (global and/or one project workspace) using BM25 + optional local embedding hybrid ranking. Omit query to browse recent entries.';
40
+ readonly inputSchema: {
41
+ readonly type: 'object';
42
+ readonly properties: {
43
+ readonly query: {
44
+ readonly type: 'string';
45
+ readonly description: 'Search query (Chinese or English). Empty lists most recent entries.';
46
+ };
47
+ readonly scope: {
48
+ readonly type: 'string';
49
+ readonly enum: readonly ['global', 'project', 'all'];
50
+ readonly description: 'Target scope; defaults to all (project + global when projectRoot/projectSlug is given, otherwise global).';
51
+ };
52
+ readonly projectRoot: {
53
+ readonly type: 'string';
54
+ readonly description: 'Absolute path of the current workspace root (used to resolve project scope).';
55
+ };
56
+ readonly projectSlug: {
57
+ readonly type: 'string';
58
+ readonly description: 'Explicit project directory slug under memories/projects/ (alternative to projectRoot).';
59
+ };
60
+ readonly kind: {
61
+ readonly type: 'string';
62
+ readonly enum: readonly ['fact', 'preference', 'knowledge', 'failure', 'procedure'];
63
+ readonly description: 'Filter by memory kind.';
64
+ };
65
+ readonly tags: {
66
+ readonly type: 'array';
67
+ readonly items: {
68
+ readonly type: 'string';
69
+ };
70
+ readonly description: 'Optional lowercase tag filters.';
71
+ };
72
+ readonly limit: {
73
+ readonly type: 'integer';
74
+ readonly minimum: 1;
75
+ readonly maximum: 25;
76
+ readonly description: 'Maximum hits to return (default 8, max 25).';
77
+ };
78
+ };
79
+ readonly additionalProperties: false;
80
+ };
81
+ }, {
82
+ readonly name: 'memory_read';
83
+ readonly description: 'Read the full body and metadata of one memory entry by id.';
84
+ readonly inputSchema: {
85
+ readonly type: 'object';
86
+ readonly properties: {
87
+ readonly id: {
88
+ readonly type: 'string';
89
+ readonly description: 'Entry id returned by memory_search.';
90
+ };
91
+ readonly scope: {
92
+ readonly type: 'string';
93
+ readonly enum: readonly ['global', 'project'];
94
+ readonly description: 'Scope to read from (defaults to project then global).';
95
+ };
96
+ readonly projectRoot: {
97
+ readonly type: 'string';
98
+ readonly description: 'Workspace root for project scope.';
99
+ };
100
+ readonly projectSlug: {
101
+ readonly type: 'string';
102
+ readonly description: 'Explicit project slug for project scope.';
103
+ };
104
+ };
105
+ readonly required: readonly ['id'];
106
+ readonly additionalProperties: false;
107
+ };
108
+ }, {
109
+ readonly name: 'memory_write';
110
+ readonly description: 'Write or update a durable memory entry. Title is the identity (same title updates in place). Credentials and passwords are automatically redacted before persistence.';
111
+ readonly inputSchema: {
112
+ readonly type: 'object';
113
+ readonly properties: {
114
+ readonly scope: {
115
+ readonly type: 'string';
116
+ readonly enum: readonly ['global', 'project'];
117
+ readonly description: 'global for cross-project facts/preferences, project for one workspace.';
118
+ };
119
+ readonly title: {
120
+ readonly type: 'string';
121
+ readonly description: 'Short imperative heading (max 120 chars).';
122
+ };
123
+ readonly body: {
124
+ readonly type: 'string';
125
+ readonly description: 'Self-contained fact, 1-4 sentences.';
126
+ };
127
+ readonly kind: {
128
+ readonly type: 'string';
129
+ readonly enum: readonly ['fact', 'preference', 'knowledge', 'failure', 'procedure'];
130
+ };
131
+ readonly tags: {
132
+ readonly type: 'array';
133
+ readonly items: {
134
+ readonly type: 'string';
135
+ };
136
+ };
137
+ readonly keys: {
138
+ readonly type: 'array';
139
+ readonly items: {
140
+ readonly type: 'string';
141
+ };
142
+ readonly description: 'Aliases and bilingual search keywords.';
143
+ };
144
+ readonly appliesTo: {
145
+ readonly type: 'string';
146
+ readonly description: 'Short phrase saying when this memory matters.';
147
+ };
148
+ readonly durability: {
149
+ readonly type: 'string';
150
+ readonly enum: readonly ['durable', 'snapshot'];
151
+ };
152
+ readonly pinned: {
153
+ readonly type: 'boolean';
154
+ };
155
+ readonly permanent: {
156
+ readonly type: 'boolean';
157
+ };
158
+ readonly projectRoot: {
159
+ readonly type: 'string';
160
+ readonly description: 'Workspace root (required when scope=project unless projectSlug is given).';
161
+ };
162
+ readonly projectSlug: {
163
+ readonly type: 'string';
164
+ readonly description: 'Explicit project slug (alternative to projectRoot).';
165
+ };
166
+ };
167
+ readonly required: readonly ['scope', 'title', 'body'];
168
+ readonly additionalProperties: false;
169
+ };
170
+ }, {
171
+ readonly name: 'memory_projects';
172
+ readonly description: 'List known project memory scopes with their slugs, recorded workspace roots, and entry counts.';
173
+ readonly inputSchema: {
174
+ readonly type: 'object';
175
+ readonly properties: {};
176
+ readonly additionalProperties: false;
177
+ };
178
+ }];
179
+ /** Resolve default options from environment variables. */
180
+ export declare function defaultMcpOptions(env?: NodeJS.ProcessEnv): McpServerOptions;
181
+ /** Handle one JSON-RPC 2.0 request. Returns `undefined` for notifications. */
182
+ export declare function handleMcpRequest(request: JsonRpcRequest, options: McpServerOptions, store?: MemoryStore): Promise<JsonRpcResponse | undefined>;
183
+ /** Run the newline-delimited JSON-RPC 2.0 stdio loop. */
184
+ export declare function startStdioServer(options?: McpServerOptions): void;
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Post a macOS notification.
2
+ * Post a macOS notification asynchronously so the Host event loop is never
3
+ * blocked waiting on AppleScript.
3
4
  *
4
5
  * Deliberately the quiet kind: no sound, no focus steal. The point is that a
5
6
  * notice is not lost, not that it interrupts. Never throws — a notification
@@ -9,4 +10,4 @@
9
10
  * @param message - notification body.
10
11
  * @returns whether `osascript` accepted it.
11
12
  */
12
- export declare function systemNotification(title: string, message: string): boolean;
13
+ export declare function systemNotification(title: string, message: string): Promise<boolean>;