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
package/lib/index.js CHANGED
@@ -47,7 +47,7 @@ import { planRetention, retentionKey } from './retention.js';
47
47
  import { MemoryLog, createFileSink, createLogExporter, pluginLogger } from './log.js';
48
48
  import { collectExtractionWindow, collectWindow, resolveLlmRoute, runExtraction, selectKnownTitles } from './extract.js';
49
49
  import { collectExcerpts, collectRagExcerpts } from './raw-recall.js';
50
- import { decodeSessionLog, findSessionLogs, parseSessionLog, planWindows, zstdAvailable } from './backfill.js';
50
+ import { decodeSessionLogAsync, findSessionLogs, parseSessionLog, planWindows, zstdAvailable } from './backfill.js';
51
51
  import { backgroundDelayMs, cappedBackoffMs, extractionDelayMs, formatDelay, parsePeakHours, peakDelayMs } from './schedule.js';
52
52
  import { CONSOLIDATE_PRESET_ID, adjudicateDisputes, applyPlan, applyVerdicts, classifyPlan, clearPendingPlan, conflictDisputes, denyToolsFor, hasApplicableFragment, mergePendingPlan, pinExistingScopes, proposalIsFresh, readPendingPlan, runConsolidation, runConsolidationDirect, selectForConsolidation, writePendingPlan } from './consolidate.js';
53
53
  import { discardDraft, listDrafts, promote, writeDraft } from './skills.js';
@@ -181,6 +181,12 @@ export function isCatchAllDirectory(root, dshHome) {
181
181
  export const inject = ['tools', 'commands'];
182
182
  /** Job key of the single global consolidation job. */
183
183
  const CONSOLIDATE_JOB = 'global';
184
+ /** Whether a session is a subagent rather than an interactive top-level session. */
185
+ export function isSubagentSession(session) {
186
+ if (session.header.origin === 'subagent')
187
+ return true;
188
+ return session.header.delegationDepth !== undefined && session.header.delegationDepth > 0;
189
+ }
184
190
  /**
185
191
  * The memory runtime: one instance per plugin mount, shared by the tool, the
186
192
  * injector, the extractor, and the command handler.
@@ -236,6 +242,8 @@ export class MemoriesRuntime {
236
242
  injected = new WeakSet();
237
243
  /** Recall deltas already injected into each conversation. */
238
244
  recallCounts = new WeakMap();
245
+ /** Latest human user turn id/seq whose full-history RAG excerpts were already injected. */
246
+ lastRagTurn = new WeakMap();
239
247
  /** Late memory blocks already injected into each conversation. */
240
248
  deltaCounts = new WeakMap();
241
249
  /** The user-turn number at which each conversation last emitted a rotation block. */
@@ -374,6 +382,10 @@ export class MemoriesRuntime {
374
382
  dispose() {
375
383
  this.stopPeriodicExtraction();
376
384
  this.storeSync.stop();
385
+ if (this.exitFlushInstalled) {
386
+ process.off('beforeExit', this.exitFlush);
387
+ this.exitFlushInstalled = false;
388
+ }
377
389
  this.lifecycle.abort(new Error('dsh-cross-memory disposed'));
378
390
  this.state.close();
379
391
  }
@@ -1144,11 +1156,8 @@ export class MemoriesRuntime {
1144
1156
  openingQuery(session) {
1145
1157
  try {
1146
1158
  for (const message of session.deriveMessages()) {
1147
- if (message.role !== 'user')
1159
+ if (message.role !== 'user' || message.source.kind !== 'user')
1148
1160
  continue;
1149
- // 0.2.0 起 MessageSource 只剩 'user' | 'model' | 'tool' | 'system-prompt',
1150
- // 不再有 'plugin'(dsh-llm/lib/types/message.d.ts:19/23/28/103)。原先那句
1151
- // `source.kind === 'plugin'` 已成为不可能的窄化,TS2367 报错,故删除。
1152
1161
  const blocks = message.content;
1153
1162
  const text = blocks
1154
1163
  .filter((block) => block.type === 'text' && typeof block.text === 'string')
@@ -1170,6 +1179,7 @@ export class MemoriesRuntime {
1170
1179
  resetInjection(session) {
1171
1180
  this.injected.delete(session);
1172
1181
  this.recallCounts.delete(session);
1182
+ this.lastRagTurn.delete(session);
1173
1183
  this.deltaCounts.delete(session);
1174
1184
  this.rotationAt.delete(session);
1175
1185
  this.surfacedIds.delete(session);
@@ -1327,17 +1337,20 @@ export class MemoriesRuntime {
1327
1337
  return undefined;
1328
1338
  if (this.sessionOff(session))
1329
1339
  return undefined;
1330
- const query = this.latestUserText(session);
1331
- // The full-history channel is computed before the eligibility gate: a turn
1332
- // with no matching memory still has its original conversation in the logs,
1333
- // and the gate returning nothing must not hide that.
1334
- const ragExcerpts = query !== undefined && this.settings.ragRecall && this.settings.ragRecallBytes > 0
1335
- ? await this.ragExcerpts(query, session.id)
1336
- : [];
1340
+ const latestTurn = this.latestUserTurn(session);
1341
+ if (latestTurn === undefined)
1342
+ return undefined;
1343
+ const query = latestTurn.text;
1337
1344
  // A one-word acknowledgement has nothing a memory could be about; skipping it
1338
- // also avoids a full store scan on every "好" the user types.
1339
- if (query === undefined || !isSubstantiveTurn(query))
1345
+ // before scanning session logs also avoids wasted work on every "好".
1346
+ if (!isSubstantiveTurn(query))
1340
1347
  return undefined;
1348
+ // Per-turn dedup for full-history RAG: tool-call steps within the same turn
1349
+ // or a host-runner continuation turn must not re-inject the same 12 KB RAG block.
1350
+ const ragAlreadyInjected = this.lastRagTurn.get(session) === latestTurn.key;
1351
+ const ragExcerpts = !ragAlreadyInjected && this.settings.ragRecall && this.settings.ragRecallBytes > 0
1352
+ ? await this.ragExcerpts(query, session.id)
1353
+ : [];
1341
1354
  const seen = this.seenIds(session);
1342
1355
  const states = await this.allScopes(session);
1343
1356
  // Resolved once for the turn: this loop scores every entry in the store.
@@ -1405,6 +1418,7 @@ export class MemoriesRuntime {
1405
1418
  const text = renderRecall([], this.settings.recallMaxBytes + this.settings.ragRecallBytes, [], ragExcerpts);
1406
1419
  if (text !== undefined) {
1407
1420
  this.recallCounts.set(session, used + 1);
1421
+ this.lastRagTurn.set(session, latestTurn.key);
1408
1422
  this.log.info('dsh-cross-memory: session %s recalled no memory, used %d raw excerpt(s) from the full history', session.id, ragExcerpts.length);
1409
1423
  return createUserMessage({
1410
1424
  content: [{ type: 'text', text }],
@@ -1520,17 +1534,19 @@ export class MemoriesRuntime {
1520
1534
  // still decides what may be recalled, so this cannot admit an entry the
1521
1535
  // lexical gate refused. When the service is unreachable, `denseScores`
1522
1536
  // returns an empty map and the lexical order stands.
1537
+ let rerankedByDense = false;
1523
1538
  if (this.settings.denseEnabled && eligible.length > 1) {
1524
- const dense = await denseScores(states.flatMap((state) => state.entries), query, { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
1539
+ const dense = await denseScores(eligible.map((item) => item.entry), query, { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
1525
1540
  if (dense.size > 0) {
1526
1541
  const lexical = [...eligible].sort(byStrength).map((item) => item.entry.id);
1527
1542
  const semantic = [...dense.entries()].sort((left, right) => right[1] - left[1]).map(([id]) => id);
1528
1543
  const fused = rrf([lexical, semantic]);
1529
1544
  eligible.sort((left, right) => (fused.get(right.entry.id) ?? 0) - (fused.get(left.entry.id) ?? 0));
1545
+ rerankedByDense = true;
1530
1546
  this.log.info('dsh-cross-memory: session %s recall re-ranked by the dense channel (%d candidates)', session.id, eligible.length);
1531
1547
  }
1532
1548
  }
1533
- else {
1549
+ if (!rerankedByDense) {
1534
1550
  eligible.sort(byStrength);
1535
1551
  }
1536
1552
  // The one-hop neighbours go in after the seeds and carry no lexical
@@ -1538,25 +1554,23 @@ export class MemoriesRuntime {
1538
1554
  // case this exists for is a turn that names one fragment of something the
1539
1555
  // store filed in several.
1540
1556
  const related = relatedHits(this.groups(states), eligible.slice(0, EXPAND_SEEDS).map((item) => ({ entry: item.entry, score: item.score })), { exclude: new Set([...seen, ...eligible.map((item) => item.entry.id)]), limit: remaining });
1541
- for (const hit of related) {
1542
- eligible.push({
1543
- entry: hit.entry,
1544
- about: true,
1545
- distinctive: false,
1546
- credited: false,
1547
- relevance: 0,
1548
- score: hit.score,
1549
- best: '',
1550
- bm25: 0,
1551
- evidence: { strongTerms: 0, phrase: false },
1552
- });
1553
- }
1557
+ const relatedCandidates = related.map((hit) => ({
1558
+ entry: hit.entry,
1559
+ about: true,
1560
+ distinctive: false,
1561
+ credited: false,
1562
+ relevance: 0,
1563
+ score: hit.score,
1564
+ best: '',
1565
+ bm25: 0,
1566
+ evidence: { strongTerms: 0, phrase: false },
1567
+ }));
1568
+ relatedCandidates.sort(byStrength);
1569
+ // Append neighbors AFTER direct hits so their relevance-0 ordering never
1570
+ // overwrites the dense RRF ranking of the direct hits.
1571
+ eligible.push(...relatedCandidates);
1554
1572
  /** Which of the candidates arrived over a hop, and from which seed, for the log line below. */
1555
1573
  const relatedVia = new Map(related.map((hit) => [hit.entry.id, hit.via ?? '']));
1556
- // The neighbours carry relevance 0, so this second sort is what keeps them
1557
- // behind every memory the turn actually matched without relying on the order
1558
- // `relatedHits` happened to return.
1559
- eligible.sort(byStrength);
1560
1574
  const picked = [];
1561
1575
  for (const candidate of eligible) {
1562
1576
  if (picked.length >= remaining)
@@ -1601,10 +1615,15 @@ export class MemoriesRuntime {
1601
1615
  const extras = `${window === undefined ? '' : `, window ${window.label}`}`
1602
1616
  + `${hopped.length === 0 ? '' : `, +${hopped.length} related via ${[...new Set(hopped.map((item) => relatedVia.get(item.entry.id)))].join(',')}`}`
1603
1617
  + `${excerpts.length === 0 ? '' : `, raw +${excerpts.length}`}`;
1604
- this.log.info('dsh-cross-memory: session %s recalled %s (relevance %s, score %s%s, via %s)', session.id, picked.map((item) => item.entry.id).join(', '), picked[0].relevance.toFixed(1), picked[0].score.toFixed(1), extras, JSON.stringify((picked[0].best ?? '').slice(0, 80)));
1605
- this.recallCounts.set(session, used + picked.length);
1606
- await this.markSurfaced(session, picked.map((item) => item.entry));
1607
- this.recordInjection(session, picked.map((item) => item.entry.id));
1618
+ const top = picked[0];
1619
+ this.log.info('dsh-cross-memory: session %s recalled %s (relevance %s, score %s%s, via %s)', session.id, picked.length > 0 ? picked.map((item) => item.entry.id).join(', ') : '(raw-only)', top !== undefined ? top.relevance.toFixed(1) : '0.0', top !== undefined ? top.score.toFixed(1) : '0.0', extras, JSON.stringify((top?.best ?? '').slice(0, 80)));
1620
+ this.recallCounts.set(session, used + Math.max(picked.length, ragExcerpts.length > 0 ? 1 : 0));
1621
+ if (ragExcerpts.length > 0)
1622
+ this.lastRagTurn.set(session, latestTurn.key);
1623
+ if (picked.length > 0) {
1624
+ await this.markSurfaced(session, picked.map((item) => item.entry));
1625
+ this.recordInjection(session, picked.map((item) => item.entry.id));
1626
+ }
1608
1627
  return createUserMessage({
1609
1628
  content: [{ type: 'text', text }],
1610
1629
  // The same form as the summary block; `carriesRecall` tells them apart by
@@ -1901,7 +1920,7 @@ export class MemoriesRuntime {
1901
1920
  * @param session - session to read.
1902
1921
  * @returns the text, or `undefined` when no user message is on the surface.
1903
1922
  */
1904
- latestUserText(session) {
1923
+ latestUserTurn(session) {
1905
1924
  try {
1906
1925
  const messages = session.deriveMessages();
1907
1926
  for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -1918,8 +1937,10 @@ export class MemoriesRuntime {
1918
1937
  .trim();
1919
1938
  if (text.length < this.settings.recallMinQueryChars)
1920
1939
  return undefined;
1921
- if (text.length > 0)
1922
- return text.slice(0, 2_000);
1940
+ if (text.length > 0) {
1941
+ const key = typeof message.id === 'string' && message.id.length > 0 ? message.id : index;
1942
+ return { key, text: text.slice(0, 2_000) };
1943
+ }
1923
1944
  }
1924
1945
  }
1925
1946
  catch {
@@ -1927,6 +1948,13 @@ export class MemoriesRuntime {
1927
1948
  }
1928
1949
  return undefined;
1929
1950
  }
1951
+ latestUserText(session) {
1952
+ return this.latestUserTurn(session)?.text;
1953
+ }
1954
+ /** Clean up per-session maps when an agent disposes. */
1955
+ forgetSession(sessionId) {
1956
+ this.capped.delete(sessionId);
1957
+ }
1930
1958
  /** Whether memory is switched off for one session. */
1931
1959
  sessionOff(session) {
1932
1960
  return this.state.getSessionMode(session.id) === 'off';
@@ -2048,11 +2076,15 @@ export class MemoriesRuntime {
2048
2076
  * @param delayMs - how long to wait.
2049
2077
  */
2050
2078
  armTimer(agent, delayMs) {
2079
+ if (this.lifecycle.signal.aborted)
2080
+ return;
2051
2081
  const existing = this.idleTimers.get(agent);
2052
2082
  if (existing !== undefined)
2053
2083
  clearTimeout(existing);
2054
2084
  const timer = setTimeout(() => {
2055
2085
  this.idleTimers.delete(agent);
2086
+ if (this.lifecycle.signal.aborted)
2087
+ return;
2056
2088
  // Still inside a peak window? Wait for it to end rather than spending now —
2057
2089
  // the settle clock keeps running, so the pass runs as soon as it is cheap.
2058
2090
  const penalty = peakDelayMs(this.settings.peakHours, new Date());
@@ -2117,10 +2149,14 @@ export class MemoriesRuntime {
2117
2149
  // tick. Skipped under the test runner, which tears its temp dirs down faster
2118
2150
  // than this delayed write would fire.
2119
2151
  if (process.env['NODE_TEST_CONTEXT'] === undefined) {
2152
+ if (this.bootNoticeTimer !== undefined)
2153
+ clearTimeout(this.bootNoticeTimer);
2120
2154
  const boot = setTimeout(() => {
2155
+ this.bootNoticeTimer = undefined;
2121
2156
  void this.pumpNotices().catch(() => undefined);
2122
2157
  }, 15_000);
2123
2158
  boot.unref?.();
2159
+ this.bootNoticeTimer = boot;
2124
2160
  }
2125
2161
  const minutes = this.settings.extractIntervalMinutes;
2126
2162
  if (!(minutes > 0))
@@ -2138,6 +2174,9 @@ export class MemoriesRuntime {
2138
2174
  }
2139
2175
  /** Stop the periodic check, if one is running. */
2140
2176
  stopPeriodicExtraction() {
2177
+ if (this.bootNoticeTimer !== undefined)
2178
+ clearTimeout(this.bootNoticeTimer);
2179
+ this.bootNoticeTimer = undefined;
2141
2180
  if (this.periodicTimer !== undefined)
2142
2181
  clearInterval(this.periodicTimer);
2143
2182
  this.periodicTimer = undefined;
@@ -2154,6 +2193,8 @@ export class MemoriesRuntime {
2154
2193
  markStoreChanged() {
2155
2194
  this.storeSync.markChanged();
2156
2195
  }
2196
+ /** The boot notice check's timer, when one is armed. */
2197
+ bootNoticeTimer;
2157
2198
  /** The periodic check's timer, when one is armed. */
2158
2199
  periodicTimer;
2159
2200
  /** The store's git transport; see {@link StoreSyncService}. */
@@ -2459,8 +2500,12 @@ export class MemoriesRuntime {
2459
2500
  this.idleSince.delete(agent);
2460
2501
  }
2461
2502
  /** Remember an agent so a process exit can still mine it. */
2503
+ trackedAgents = new WeakSet();
2462
2504
  track(agent) {
2463
- this.tracked.add(new WeakRef(agent));
2505
+ if (!this.trackedAgents.has(agent)) {
2506
+ this.trackedAgents.add(agent);
2507
+ this.tracked.add(new WeakRef(agent));
2508
+ }
2464
2509
  this.installExitFlush();
2465
2510
  }
2466
2511
  /**
@@ -2670,6 +2715,13 @@ export class MemoriesRuntime {
2670
2715
  window,
2671
2716
  projectLabel,
2672
2717
  ...knownTitles.length === 0 ? {} : { knownTitles },
2718
+ ...await readLoops(this.store.memoriesDir).then((ledger) => {
2719
+ const open = ledger.loops
2720
+ .filter((loop) => loop.state === 'open')
2721
+ .slice(-25)
2722
+ .map((loop) => ({ id: loop.id, text: loop.text }));
2723
+ return open.length === 0 ? {} : { openLoops: open };
2724
+ }).catch(() => ({})),
2673
2725
  ...this.settings.extractProvider.length > 0 && this.settings.extractModel.length > 0
2674
2726
  ? { provider: this.settings.extractProvider, model: this.settings.extractModel }
2675
2727
  : {},
@@ -2734,7 +2786,7 @@ export class MemoriesRuntime {
2734
2786
  }).catch((error) => {
2735
2787
  this.log.warn('dsh-cross-memory: could not write the evidence note for session %s: %o', key, error);
2736
2788
  });
2737
- await this.recordLoops(key, outcome.loops);
2789
+ await this.recordLoops(key, outcome.loops, outcome.closedLoops);
2738
2790
  this.log.info('dsh-cross-memory: stored %d memories from session %s (%s)%s%s', outcome.drafts.length, key, stored.join(', '), spend, outcome.truncated === true ? ` — the reply hit the ${this.settings.extractMaxOutputTokens}-token cap and was salvaged; raise extractMaxOutputTokens to keep the rest` : '');
2739
2791
  // A pass that always lands on the cap is a pass whose ceiling is the
2740
2792
  // binding constraint. Saying so is the only way anybody can tell that
@@ -2837,7 +2889,7 @@ export class MemoriesRuntime {
2837
2889
  let log;
2838
2890
  try {
2839
2891
  const buffer = await readFile(entry.file);
2840
- log = parseSessionLog(decodeSessionLog(buffer), entry.file, entry.modifiedAt);
2892
+ log = parseSessionLog(await decodeSessionLogAsync(buffer), entry.file, entry.modifiedAt);
2841
2893
  }
2842
2894
  catch (error) {
2843
2895
  skippedEmpty += 1;
@@ -3060,6 +3112,8 @@ export class MemoriesRuntime {
3060
3112
  // A paused account skips the pass and leaves the job in place: the cooldown
3061
3113
  // is the right place to retry, not this turn.
3062
3114
  if (this.backgroundPaused()) {
3115
+ const { lease: _lease, ...unleased } = job;
3116
+ this.state.putJob({ ...unleased, leaseUntil: 0 });
3063
3117
  this.consolidateSkip = 'background passes are paused by a provider quota cooldown';
3064
3118
  return undefined;
3065
3119
  }
@@ -3210,10 +3264,10 @@ export class MemoriesRuntime {
3210
3264
  this.noteLimitRefusal(error);
3211
3265
  this.log.warn('dsh-cross-memory: consolidation failed for session %s: %s', parent.session.id, message);
3212
3266
  // The failure is a plain TypeError from a field access, and its message
3213
- // alone ("reading 'id'") names no call site. Record the stack once at
3214
- // decision level so the next occurrence is locatable without a rebuild.
3267
+ // alone ("reading 'id'") names no call site. Record the top stack frames
3268
+ // at warn level so it persists under default `logLevel: 'info'`.
3215
3269
  if (error instanceof Error && typeof error.stack === 'string' && error.stack.length > 0) {
3216
- this.log.decision('dsh-cross-memory: consolidation failure stack: %s', error.stack);
3270
+ this.log.warn('dsh-cross-memory: consolidation failure stack: %s', error.stack.split('\n').slice(0, 6).join(' | '));
3217
3271
  }
3218
3272
  // The command reports `consolidateSkipReason`; without this the failure
3219
3273
  // surfaced as "Nothing to consolidate: unknown reason".
@@ -3272,6 +3326,7 @@ export class MemoriesRuntime {
3272
3326
  const now = Date.now();
3273
3327
  try {
3274
3328
  let queue = pruneNotices(await readNotices(dir), now);
3329
+ const before = JSON.stringify(queue);
3275
3330
  const policy = {
3276
3331
  now,
3277
3332
  quietHours: this.settings.noticeQuietHours,
@@ -3304,7 +3359,7 @@ export class MemoriesRuntime {
3304
3359
  // 2. Open loops whose deadline has passed. This is the trigger that makes
3305
3360
  // the assistant pro-active rather than reactive: it needs no question to
3306
3361
  // answer, only a promise the user made and has not closed.
3307
- const loopNow = pruneLoops(await readLoops(dir), now);
3362
+ let loopNow = pruneLoops(await readLoops(dir), now);
3308
3363
  const raised = [];
3309
3364
  for (const loop of dueLoops(loopNow, now)) {
3310
3365
  const admitted = admitNotice(queue, {
@@ -3334,12 +3389,13 @@ export class MemoriesRuntime {
3334
3389
  ledger = withLoop(ledger, id, { remindedAt: now, remindCount: (loop.remindCount ?? 0) + 1 });
3335
3390
  }
3336
3391
  await writeLoops(dir, ledger);
3392
+ loopNow = ledger;
3337
3393
  }
3338
3394
  // 4. Judgement notices: a note with no deadline that has been sitting for
3339
3395
  // days. There is no rule that says it is worth an interruption, so the
3340
3396
  // gate decides — and its default is silence. Without a session there is no
3341
3397
  // route to ask through, and silence is the right failure.
3342
- if (this.settings.noticeGate) {
3398
+ if (this.settings.noticeGate && session !== undefined && !this.backgroundPaused()) {
3343
3399
  const staleAfter = 3 * 86_400_000;
3344
3400
  const candidates = loopNow.loops.filter((loop) => loop.state === 'open'
3345
3401
  && loop.dueAt === undefined
@@ -3347,54 +3403,65 @@ export class MemoriesRuntime {
3347
3403
  && (loop.remindCount ?? 0) < 3
3348
3404
  && (loop.remindedAt === undefined || now - loop.remindedAt >= 86_400_000));
3349
3405
  if (candidates.length > 0) {
3350
- const gate = await gateNotices({
3351
- llm: this.llm,
3352
- session,
3353
- candidates: candidates.map((loop) => ({
3354
- id: loop.id,
3355
- title: `还挂着:${loop.text}`,
3356
- detail: `说了 ${Math.round((now - loop.openedAt) / 86_400_000)} 天,没有截止日期,已提醒 ${loop.remindCount ?? 0} 次`,
3357
- })),
3358
- ...await readPersona(dir).then((text) => text === undefined ? {} : { persona: text }),
3359
- provider: this.settings.extractProvider,
3360
- model: this.settings.extractModel,
3361
- timeoutMs: 20_000,
3362
- signal: this.lifecycle.signal,
3363
- });
3364
- this.log.info('dsh-cross-memory: notice gate: %d candidate(s), %d allowed (%s)', candidates.length, gate.deliver.size, gate.reason);
3365
- let ledger = loopNow;
3366
- for (const candidate of candidates) {
3367
- if (!gate.deliver.has(candidate.id))
3368
- continue;
3369
- const admitted = admitNotice(queue, {
3370
- kind: 'loop',
3371
- createdAt: now,
3372
- dueAt: now,
3373
- title: `还挂着:${candidate.text}`,
3374
- body: candidate.text,
3375
- evidence: [candidate.id],
3376
- dedupeKey: `loop:${candidate.id}`,
3377
- }, policy);
3378
- if (!admitted.ok)
3379
- continue;
3380
- queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
3381
- ledger = withLoop(ledger, candidate.id, { remindedAt: now, remindCount: (candidate.remindCount ?? 0) + 1 });
3406
+ const GATE_COOLDOWN_MS = 6 * 3_600_000;
3407
+ const fingerprint = candidates.map((loop) => `${loop.id}:${loop.remindCount ?? 0}`).sort().join(',');
3408
+ const lastAt = Number(this.state.getMeta('noticeGate:lastAt') ?? '0');
3409
+ const lastFingerprint = this.state.getMeta('noticeGate:lastFingerprint') ?? '';
3410
+ if (lastAt > 0 && now - lastAt < GATE_COOLDOWN_MS && lastFingerprint === fingerprint) {
3411
+ this.log.decision('dsh-cross-memory: notice gate skipped (%d candidate(s) unchanged within 6h cooldown)', candidates.length);
3412
+ }
3413
+ else {
3414
+ this.state.putMeta('noticeGate:lastAt', String(now));
3415
+ this.state.putMeta('noticeGate:lastFingerprint', fingerprint);
3416
+ const gate = await gateNotices({
3417
+ llm: this.llm,
3418
+ session,
3419
+ candidates: candidates.map((loop) => ({
3420
+ id: loop.id,
3421
+ title: `还挂着:${loop.text}`,
3422
+ detail: `说了 ${Math.round((now - loop.openedAt) / 86_400_000)} 天,没有截止日期,已提醒 ${loop.remindCount ?? 0} 次`,
3423
+ })),
3424
+ ...await readPersona(dir).then((text) => text === undefined ? {} : { persona: text }),
3425
+ ...this.settings.extractProvider.length > 0 && this.settings.extractModel.length > 0
3426
+ ? { provider: this.settings.extractProvider, model: this.settings.extractModel }
3427
+ : {},
3428
+ timeoutMs: 20_000,
3429
+ signal: this.lifecycle.signal,
3430
+ });
3431
+ this.log.info('dsh-cross-memory: notice gate: %d candidate(s), %d allowed (%s)', candidates.length, gate.deliver.size, gate.reason);
3432
+ let ledger = loopNow;
3433
+ for (const candidate of candidates) {
3434
+ if (!gate.deliver.has(candidate.id))
3435
+ continue;
3436
+ const admitted = admitNotice(queue, {
3437
+ kind: 'loop',
3438
+ createdAt: now,
3439
+ dueAt: now,
3440
+ title: `还挂着:${candidate.text}`,
3441
+ body: candidate.text,
3442
+ evidence: [candidate.id],
3443
+ dedupeKey: `loop:${candidate.id}`,
3444
+ }, policy);
3445
+ if (!admitted.ok)
3446
+ continue;
3447
+ queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
3448
+ ledger = withLoop(ledger, candidate.id, { remindedAt: now, remindCount: (candidate.remindCount ?? 0) + 1 });
3449
+ }
3450
+ if (ledger !== loopNow)
3451
+ await writeLoops(dir, ledger);
3382
3452
  }
3383
- if (ledger !== loopNow)
3384
- await writeLoops(dir, ledger);
3385
3453
  }
3386
3454
  }
3387
- else if (loopNow.loops.some((loop) => loop.state === 'open' && loop.dueAt === undefined)) {
3455
+ else if (!this.settings.noticeGate && loopNow.loops.some((loop) => loop.state === 'open' && loop.dueAt === undefined)) {
3388
3456
  this.log.decision('dsh-cross-memory: notice gate is off, undated loops stay silent');
3389
3457
  }
3390
- const before = JSON.stringify(queue);
3391
3458
  // 5. Deliver what is due. The only channel is the operating system's
3392
3459
  // notification: this plugin used to hand the sentence to a desktop pet, and
3393
3460
  // that dependency is gone — a notice is worth having only if it arrives
3394
3461
  // without a second plugin being installed and configured correctly.
3395
3462
  let next = queue;
3396
3463
  for (const notice of dueNotices(queue, now)) {
3397
- if (systemNotification('dsh-cross-memory', notice.title)) {
3464
+ if (await systemNotification('dsh-cross-memory', notice.title)) {
3398
3465
  next = withNotice(next, { ...notice, state: 'delivered', deliveredAt: now });
3399
3466
  this.log.info('dsh-cross-memory: notice delivered via system notification: %s', notice.title);
3400
3467
  }
@@ -3416,16 +3483,24 @@ export class MemoriesRuntime {
3416
3483
  * lifecycle and a deadline, it is never recalled by retrieval, and its id must
3417
3484
  * stay stable across rewrites so one promise cannot become three reminders.
3418
3485
  */
3419
- async recordLoops(sessionKey, candidates) {
3420
- if (candidates.length === 0)
3486
+ async recordLoops(sessionKey, candidates, closedIds = []) {
3487
+ if (candidates.length === 0 && closedIds.length === 0)
3421
3488
  return;
3422
3489
  try {
3423
3490
  const dir = this.store.memoriesDir;
3424
3491
  const now = Date.now();
3425
- const current = pruneLoops(await readLoops(dir), now);
3426
- const next = mergeLoops(current, candidates, now, sessionKey);
3492
+ let current = pruneLoops(await readLoops(dir), now);
3493
+ let closed = 0;
3494
+ for (const id of closedIds) {
3495
+ const outcome = closeLoop(current, id);
3496
+ if (outcome.closed !== undefined) {
3497
+ current = outcome.store;
3498
+ closed += 1;
3499
+ }
3500
+ }
3501
+ const next = candidates.length > 0 ? mergeLoops(current, candidates, now, sessionKey) : current;
3427
3502
  await writeLoops(dir, next);
3428
- this.log.info('dsh-cross-memory: open loops now %d (from %d candidate(s))', next.loops.filter((loop) => loop.state === 'open').length, candidates.length);
3503
+ this.log.info('dsh-cross-memory: open loops now %d (from %d candidate(s), %d closed)', next.loops.filter((loop) => loop.state === 'open').length, candidates.length, closed);
3429
3504
  }
3430
3505
  catch (error) {
3431
3506
  this.log.warn('dsh-cross-memory: could not record open loops: %s', error instanceof Error ? error.message : String(error));
@@ -3471,8 +3546,9 @@ export class MemoriesRuntime {
3471
3546
  entries,
3472
3547
  ...await readPersona(dir).then((text) => text === undefined ? {} : { persona: text }),
3473
3548
  previous: previousInsights(files),
3474
- provider: this.settings.extractProvider,
3475
- model: this.settings.extractModel,
3549
+ ...this.settings.extractProvider.length > 0 && this.settings.extractModel.length > 0
3550
+ ? { provider: this.settings.extractProvider, model: this.settings.extractModel }
3551
+ : {},
3476
3552
  timeoutMs: 60_000,
3477
3553
  signal: this.lifecycle.signal,
3478
3554
  });
@@ -3495,7 +3571,7 @@ export class MemoriesRuntime {
3495
3571
  * @returns whether the operating system accepted it.
3496
3572
  */
3497
3573
  async probeNotification() {
3498
- const sent = systemNotification('dsh-cross-memory', '测试通知:看到这条说明通知通道正常。');
3574
+ const sent = await systemNotification('dsh-cross-memory', '测试通知:看到这条说明通知通道正常。');
3499
3575
  return sent ? { ok: true } : { ok: false, reason: 'osascript was rejected or unavailable' };
3500
3576
  }
3501
3577
  /** The notice queue as one short block, for the command. */
@@ -3617,7 +3693,7 @@ export class MemoriesRuntime {
3617
3693
  const verdict = byId.get(dispute.id);
3618
3694
  if (verdict === undefined)
3619
3695
  continue;
3620
- this.log.info('dsh-cross-memory: auto-decide %s %s/%s (confidence %.2f): %s', verdict.accept ? 'accepted' : 'rejected', dispute.scope, dispute.id, verdict.confidence, verdict.reason);
3696
+ this.log.info('dsh-cross-memory: auto-decide %s %s/%s (confidence %s): %s', verdict.accept ? 'accepted' : 'rejected', dispute.scope, dispute.id, verdict.confidence.toFixed(2), verdict.reason);
3621
3697
  }
3622
3698
  if (remaining.length > 0) {
3623
3699
  this.log.info('dsh-cross-memory: %d decision(s) still need a person after auto-decide', remaining.length);
@@ -3632,6 +3708,7 @@ export class MemoriesRuntime {
3632
3708
  // The profile as it stands, so the pass refines it instead of re-inventing
3633
3709
  // one every six hours. Read before the call: the pass writes it back.
3634
3710
  ...await readPersona(this.store.memoriesDir).then((text) => text === undefined ? {} : { persona: text }),
3711
+ ...await listDrafts(this.store.memoriesDir, this.deployment.dshHome).then((drafts) => drafts.length === 0 ? {} : { existingSkills: drafts.map((d) => ({ name: d.name, description: d.description })) }).catch(() => ({})),
3635
3712
  projectLabel: root === undefined ? NO_PROJECT_LABEL : this.store.target('project', root).label,
3636
3713
  maxUpserts: this.settings.consolidateMaxEntries,
3637
3714
  // The deny list only reaches the pre-0.2.1 seam, whose request still
@@ -4384,12 +4461,17 @@ export function apply(ctx, config = {}) {
4384
4461
  * actually fails.
4385
4462
  */
4386
4463
  let runtime;
4464
+ let pendingLogSinkError;
4387
4465
  const sink = createFileSink(deployment.logFile, undefined, (reason) => {
4388
4466
  // A failed write is the one failure the log file cannot report about itself:
4389
4467
  // the very channel is broken. Record it on the runtime so `/memories stats`
4390
4468
  // (and the settings card, which reads the same field) can say the file is
4391
4469
  // stale instead of leaving a user to trust something that stopped growing.
4392
- runtime.logSinkError = `write failed: ${reason}`;
4470
+ const message = `write failed: ${reason}`;
4471
+ if (runtime !== undefined)
4472
+ runtime.logSinkError = message;
4473
+ else
4474
+ pendingLogSinkError = message;
4393
4475
  });
4394
4476
  if (sink !== undefined) {
4395
4477
  ctx.logger.exporter(createLogExporter(sink, () => current.logLevel));
@@ -4398,7 +4480,7 @@ export function apply(ctx, config = {}) {
4398
4480
  // Recorded on the runtime rather than only logged: this very message cannot
4399
4481
  // reach the file that failed to open, and the host's own sink is a ring
4400
4482
  // buffer that a stock profile never reads. `stats` is where a user looks.
4401
- runtime.logSinkError = `unwritable: ${deployment.logFile}`;
4483
+ pendingLogSinkError = `unwritable: ${deployment.logFile}`;
4402
4484
  log.warn('dsh-cross-memory: could not open the log file %s', deployment.logFile);
4403
4485
  }
4404
4486
  // The Memories page is this plugin's own, so the settings domain is asked not
@@ -4416,8 +4498,11 @@ export function apply(ctx, config = {}) {
4416
4498
  liveRegistrations();
4417
4499
  onSettingsCommit();
4418
4500
  });
4419
- runtime = new MemoriesRuntime(ctx, config, read);
4420
- ctx.effect(() => () => runtime.dispose(), 'dsh-cross-memory.lifecycle');
4501
+ const activeRuntime = new MemoriesRuntime(ctx, config, read);
4502
+ runtime = activeRuntime;
4503
+ if (pendingLogSinkError !== undefined)
4504
+ activeRuntime.logSinkError = pendingLogSinkError;
4505
+ ctx.effect(() => () => activeRuntime.dispose(), 'dsh-cross-memory.lifecycle');
4421
4506
  // A staged consolidation proposal can also wait as an answer-embedded action
4422
4507
  // card: the model offers it from its skill, and the buttons apply or discard
4423
4508
  // the whole batch. Both services are optional, and an older action-card
@@ -4434,16 +4519,16 @@ export function apply(ctx, config = {}) {
4434
4519
  }
4435
4520
  const seam = {
4436
4521
  pending: async () => {
4437
- const pending = await readPendingPlan(runtime.store.memoriesDir).catch(() => undefined);
4522
+ const pending = await readPendingPlan(activeRuntime.store.memoriesDir).catch(() => undefined);
4438
4523
  return pending === undefined
4439
4524
  ? undefined
4440
4525
  : { label: pending.label, count: pending.disputes.length, stagedAt: pending.at };
4441
4526
  },
4442
4527
  apply: async (agent) => {
4443
- const result = await runtime.applyPendingPlan(agent);
4528
+ const result = await activeRuntime.applyPendingPlan(agent);
4444
4529
  return result === undefined ? undefined : { written: result.written, retired: result.retired };
4445
4530
  },
4446
- reject: () => runtime.rejectPendingPlan(),
4531
+ reject: () => activeRuntime.rejectPendingPlan(),
4447
4532
  };
4448
4533
  child.effect(() => registerProposalCard(actionCards, skills, seam), 'dsh-cross-memory.proposalCard');
4449
4534
  });
@@ -4467,7 +4552,7 @@ export function apply(ctx, config = {}) {
4467
4552
  description: '合并与重整记忆时使用的子代理组成:不含任何工具,只能返回 JSON 方案。',
4468
4553
  plugins: [],
4469
4554
  }).then((unregister) => {
4470
- runtime.markConsolidatePresetReady(true);
4555
+ activeRuntime.markConsolidatePresetReady(true);
4471
4556
  child.effect(() => () => { void unregister(); }, 'dsh-cross-memory.consolidatePreset');
4472
4557
  log.info('dsh-cross-memory: registered the tool-free preset %s for the consolidation child', CONSOLIDATE_PRESET_ID);
4473
4558
  }, (error) => {
@@ -4475,13 +4560,13 @@ export function apply(ctx, config = {}) {
4475
4560
  });
4476
4561
  });
4477
4562
  onSettingsCommit = () => {
4478
- runtime.startPeriodicExtraction();
4479
- runtime.startPeriodicSync();
4480
- runtime.reportSettingsIssues();
4563
+ activeRuntime.startPeriodicExtraction();
4564
+ activeRuntime.startPeriodicSync();
4565
+ activeRuntime.reportSettingsIssues();
4481
4566
  };
4482
- runtime.startPeriodicExtraction();
4483
- runtime.startPeriodicSync();
4484
- runtime.reportSettingsIssues();
4567
+ activeRuntime.startPeriodicExtraction();
4568
+ activeRuntime.startPeriodicSync();
4569
+ activeRuntime.reportSettingsIssues();
4485
4570
  // The Memories page reads and edits memories through the Typert gateway, so
4486
4571
  // registering the invocation manifest and providing the `memories` service
4487
4572
  // are what make `ctx.remote.memories.*` callable from the browser. Both are
@@ -4500,10 +4585,10 @@ export function apply(ctx, config = {}) {
4500
4585
  const withdraw = typert.register(REMOTE_CONTRIBUTION);
4501
4586
  child.effect(() => withdraw, 'dsh-cross-memory.remoteContribution');
4502
4587
  const service = createRemoteService({
4503
- store: runtime.store,
4588
+ store: activeRuntime.store,
4504
4589
  dshHome: deployment.dshHome,
4505
- disputes: () => runtime.disputes(),
4506
- resolveDispute: (id, decision) => runtime.resolveDispute(id, decision),
4590
+ disputes: () => activeRuntime.disputes(),
4591
+ resolveDispute: (id, decision) => activeRuntime.resolveDispute(id, decision),
4507
4592
  });
4508
4593
  // Provided on the plugin's own context, not the child's: the gateway is a
4509
4594
  // sibling scope and resolves the service as a peer.
@@ -4518,7 +4603,7 @@ export function apply(ctx, config = {}) {
4518
4603
  });
4519
4604
  // Import (and remove) a pre-SQLite watermark file once, so upgrading does not
4520
4605
  // re-mine conversations that were already processed.
4521
- void importLegacyState(runtime.state, runtime.store.memoriesDir).then((imported) => {
4606
+ void importLegacyState(activeRuntime.state, activeRuntime.store.memoriesDir).then((imported) => {
4522
4607
  if (imported === undefined)
4523
4608
  return;
4524
4609
  log.info('dsh-cross-memory: imported %d watermarks from the legacy state file', imported);
@@ -4528,18 +4613,18 @@ export function apply(ctx, config = {}) {
4528
4613
  // The first sweep runs here rather than waiting for a session to settle: a
4529
4614
  // process that starts and stops (a script, a one-shot task) then still gets
4530
4615
  // the periodic cleanup it would otherwise never reach.
4531
- void runtime.sweepIfDue().catch((error) => {
4616
+ void activeRuntime.sweepIfDue().catch((error) => {
4532
4617
  log.warn('dsh-cross-memory: startup sweep failed: %o', error);
4533
4618
  });
4534
4619
  // Activation facts belong at `debug`, not at the file's default verbosity: a
4535
4620
  // hot reload writes this line on every edit, and measured over nine days it
4536
4621
  // was a quarter of the whole log while saying nothing a reader could act on.
4537
4622
  // `/memories stats` reports the same facts on demand.
4538
- log.debug('dsh-cross-memory: store at %s autoExtract=%s idle=%d log=%s', runtime.store.memoriesDir, String(runtime.settings.autoExtract), runtime.settings.autoExtractIdleMs, deployment.logFile.length > 0 ? `${deployment.logFile} (${runtime.settings.logLevel})` : 'off');
4623
+ log.debug('dsh-cross-memory: store at %s autoExtract=%s idle=%d log=%s', activeRuntime.store.memoriesDir, String(activeRuntime.settings.autoExtract), activeRuntime.settings.autoExtractIdleMs, deployment.logFile.length > 0 ? `${deployment.logFile} (${activeRuntime.settings.logLevel})` : 'off');
4539
4624
  // `enableTool`/`enableCommand` are live: each registration is torn down and
4540
4625
  // re-created when the toggle flips, so the model's catalog follows the entry
4541
4626
  // config without a restart.
4542
- const registerTool = () => registerMemoryTool(ctx, runtime);
4627
+ const registerTool = () => registerMemoryTool(ctx, activeRuntime);
4543
4628
  const registerCommand = () => ctx.commands.register({
4544
4629
  name: 'memories',
4545
4630
  description: 'Inspect and manage cross-session memories',
@@ -4550,11 +4635,11 @@ export function apply(ctx, config = {}) {
4550
4635
  // Every failure inside this plugin becomes an error RESULT instead.
4551
4636
  handler: async (invocation) => {
4552
4637
  try {
4553
- return await handleCommand(runtime, invocation);
4638
+ return await handleCommand(activeRuntime, invocation);
4554
4639
  }
4555
4640
  catch (error) {
4556
4641
  const message = error instanceof Error ? error.message : String(error);
4557
- runtime.noteCommandFailure(invocation.rawInput.trim().split(/\s+/u)[0] ?? 'memories', error);
4642
+ activeRuntime.noteCommandFailure(invocation.rawInput.trim().split(/\s+/u)[0] ?? 'memories', error);
4558
4643
  return { kind: 'error', text: `dsh-cross-memory: ${message}` };
4559
4644
  }
4560
4645
  },
@@ -4562,14 +4647,14 @@ export function apply(ctx, config = {}) {
4562
4647
  let toolDisposer;
4563
4648
  let commandDisposer;
4564
4649
  const syncRegistrations = () => {
4565
- const wantTool = runtime.settings.enableTool;
4650
+ const wantTool = activeRuntime.settings.enableTool;
4566
4651
  if (wantTool && toolDisposer === undefined)
4567
4652
  toolDisposer = registerTool();
4568
4653
  else if (!wantTool && toolDisposer !== undefined) {
4569
4654
  toolDisposer();
4570
4655
  toolDisposer = undefined;
4571
4656
  }
4572
- const wantCommand = runtime.settings.enableCommand;
4657
+ const wantCommand = activeRuntime.settings.enableCommand;
4573
4658
  if (wantCommand && commandDisposer === undefined)
4574
4659
  commandDisposer = registerCommand();
4575
4660
  else if (!wantCommand && commandDisposer !== undefined) {
@@ -4584,24 +4669,27 @@ export function apply(ctx, config = {}) {
4584
4669
  commandDisposer?.();
4585
4670
  }, 'dsh-cross-memory.registrations');
4586
4671
  ctx.on('agent/status', ({ agent, status }) => {
4672
+ if (isSubagentSession(agent.session))
4673
+ return;
4587
4674
  if (status === 'idle')
4588
- runtime.scheduleExtraction(agent);
4675
+ activeRuntime.scheduleExtraction(agent);
4589
4676
  else
4590
- runtime.cancelExtraction(agent);
4677
+ activeRuntime.cancelExtraction(agent);
4591
4678
  // Record real activity on every transition, so `maxAgeDays` judges a
4592
4679
  // session by when it was last USED rather than by when it was last mined —
4593
4680
  // a session that is never mined would otherwise look infinitely young.
4594
- runtime.recordActivity(agent.session);
4681
+ activeRuntime.recordActivity(agent.session);
4595
4682
  });
4596
4683
  ctx.on('agent/disposed', ({ agent }) => {
4597
- runtime.cancelExtraction(agent);
4684
+ activeRuntime.cancelExtraction(agent);
4685
+ activeRuntime.forgetSession(agent.session.id);
4598
4686
  // A short-lived process may exit before the idle timer ever fires; the
4599
4687
  // disposal boundary is the last moment an extraction can still run.
4600
4688
  // `flushExit` is declared async, but the registry wraps every listener and
4601
4689
  // reports anything it throws as "agent/disposed listener threw". Normalise
4602
4690
  // the return value first: a `.catch` on a non-promise is exactly the failure
4603
4691
  // the host logged in 2026-11-22..26, and disposal must never be the raiser.
4604
- Promise.resolve(runtime.flushExit()).catch(() => undefined);
4692
+ Promise.resolve(activeRuntime.flushExit()).catch(() => undefined);
4605
4693
  });
4606
4694
  // 0.1.7-rc.1 起宿主把 `agent/session-start` 改名为 `agent/created`(公告见 v0.1.7-rc.1
4607
4695
  // release notes)。payload 形状不变,仍是 `{ agent, source }`,`source` 取值同为
@@ -4613,7 +4701,7 @@ export function apply(ctx, config = {}) {
4613
4701
  // is gone: forget it and let the next pre-step re-inject. Fresh and resumed
4614
4702
  // sessions need no work here — the first step of the first turn injects.
4615
4703
  if (source === 'clear' || source === 'compact')
4616
- runtime.resetInjection(agent.session);
4704
+ activeRuntime.resetInjection(agent.session);
4617
4705
  // 返回 undefined(而不是 void):0.2.0 的 'agent/created' 监听器签名要求
4618
4706
  // `Promise<undefined> | undefined`,隐式 void 会报 TS2345。
4619
4707
  return undefined;
@@ -4622,33 +4710,35 @@ export function apply(ctx, config = {}) {
4622
4710
  const decision = await next();
4623
4711
  if (decision.kind === 'reject')
4624
4712
  return decision;
4713
+ if (isSubagentSession(agent.session))
4714
+ return decision;
4625
4715
  // Memory is an enhancement, never a precondition: this seam runs on every
4626
4716
  // step of every turn, and an exception here fails the user's turn. Contain
4627
4717
  // everything and fall through to the unmodified decision instead.
4628
4718
  try {
4629
4719
  const addition = [];
4630
- const summary = await runtime.injectionFor(agent);
4720
+ const summary = await activeRuntime.injectionFor(agent);
4631
4721
  if (summary !== undefined)
4632
4722
  addition.push(summary);
4633
4723
  // Titles of what the summary had no room for: one small block per
4634
4724
  // conversation, so the store becomes discoverable instead of only the
4635
4725
  // same dozen entries ever being shown.
4636
- const rotation = await runtime.rotationFor(agent);
4726
+ const rotation = await activeRuntime.rotationFor(agent);
4637
4727
  if (rotation !== undefined)
4638
4728
  addition.push(rotation);
4639
4729
  // Credit the memories the block already handed over and this turn is now
4640
4730
  // actually about. Without it the only "demand" signal the ranking has is a
4641
4731
  // search hit, which measures lookup-style knowledge and misses the memory
4642
4732
  // that was injected and used.
4643
- await runtime.creditInjectedUse(agent);
4733
+ await activeRuntime.creditInjectedUse(agent);
4644
4734
  // The on-demand delta is a second, independent decision: a conversation can
4645
4735
  // already carry the summary and still meet a memory that only matters now.
4646
- const delta = await runtime.recallFor(agent);
4736
+ const delta = await activeRuntime.recallFor(agent);
4647
4737
  if (delta !== undefined)
4648
4738
  addition.push(delta);
4649
4739
  // A third, independent decision: the conversation already carries the
4650
4740
  // summary and may still have had memories written after it.
4651
- const late = await runtime.deltaFor(agent);
4741
+ const late = await activeRuntime.deltaFor(agent);
4652
4742
  if (late !== undefined)
4653
4743
  addition.push(late);
4654
4744
  const fresh = addition.filter((message) => !decision.messages.some((existing) => existing.id === message.id));
@@ -4662,7 +4752,7 @@ export function apply(ctx, config = {}) {
4662
4752
  return { ...decision, messages: [...decision.messages, ...fresh] };
4663
4753
  }
4664
4754
  catch (error) {
4665
- runtime.notePreStepFailure(agent.session.id, error);
4755
+ activeRuntime.notePreStepFailure(agent.session.id, error);
4666
4756
  return decision;
4667
4757
  }
4668
4758
  });