dsh-cross-memory 0.2.10 → 0.2.11

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.
package/lib/index.js CHANGED
@@ -59,6 +59,16 @@ import { REMOTE_CONTRIBUTION, REMOTE_NAMESPACE, REMOTE_SERVICE, createRemoteServ
59
59
  export const name = 'memories';
60
60
  /** Budget for the extraction a shutdown is allowed to wait for. */
61
61
  const EXIT_FLUSH_TIMEOUT_MS = 8_000;
62
+ /**
63
+ * Let the host event loop breathe between two bounded slices of background work.
64
+ *
65
+ * The periodic pass walks every open session and the whole store on the main
66
+ * thread; measured on 29 live sessions, one uninterrupted walk held the loop for
67
+ * 5.6-8.3 s every 30 minutes (the host reported `Host event loop stalled` each
68
+ * time). Yielding between slices keeps the same work but caps one slice at a few
69
+ * milliseconds, so an interactive turn is never parked behind the pass.
70
+ */
71
+ const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
62
72
  /**
63
73
  * How often a periodic pass that changed nothing still reports at info level.
64
74
  *
@@ -2204,7 +2214,9 @@ export class MemoriesRuntime {
2204
2214
  const limit = this.settings.maxSessionsPerPass;
2205
2215
  const ordered = [...candidates.values()].sort((left, right) => this.activityOf(right) - this.activityOf(left));
2206
2216
  let mined = 0;
2207
- for (const agent of ordered) {
2217
+ for (const [index, agent] of ordered.entries()) {
2218
+ if (index > 0 && index % 4 === 0)
2219
+ await yieldToEventLoop();
2208
2220
  if (this.lifecycle.signal.aborted)
2209
2221
  return;
2210
2222
  counts.tracked += 1;
@@ -2558,6 +2570,15 @@ export class MemoriesRuntime {
2558
2570
  */
2559
2571
  hasNothingNew(session) {
2560
2572
  const after = this.state.getSession(session.id)?.lastSeq ?? 0;
2573
+ // Cheap gate before the window walk. A live process keeps every settled
2574
+ // session in `candidates`, and on a caught-up session the walk still pays a
2575
+ // full pass over the surface graph for nothing. The surface nodes are kept
2576
+ // in seq order, so a last node at or below the watermark means no message
2577
+ // can be newer than it — no window can exist, and no string is built.
2578
+ const nodes = session.surface.nodes;
2579
+ const newest = nodes[nodes.length - 1];
2580
+ if (newest !== undefined && newest <= after)
2581
+ return true;
2561
2582
  const window = collectWindow(session, after, this.settings.extractWindowMessages, this.settings.extractMaxInputChars);
2562
2583
  return window.lastSeq === undefined || window.text.trim().length === 0;
2563
2584
  }
@@ -2582,7 +2603,7 @@ export class MemoriesRuntime {
2582
2603
  }
2583
2604
  /** Bound `beforeExit` handler. */
2584
2605
  exitFlush = () => {
2585
- void this.flushExit().catch(() => undefined);
2606
+ Promise.resolve(this.flushExit()).catch(() => undefined);
2586
2607
  };
2587
2608
  /**
2588
2609
  * Mine one session's transcript tail and store what it yields.
@@ -3061,7 +3082,18 @@ export class MemoriesRuntime {
3061
3082
  this.consolidateSkip = `only ${entries.length} memories are eligible for a pass`;
3062
3083
  return undefined;
3063
3084
  }
3064
- const proposed = await this.runConsolidationPass(parent, entries, root);
3085
+ const proposedRaw = await this.runConsolidationPass(parent, entries, root);
3086
+ // Two routes feed this plan (the subagent seam and the direct model call),
3087
+ // and a malformed element in any array reaches `item.id` in the classifier
3088
+ // as a TypeError whose message names no field. Drop holes here, once, so a
3089
+ // bad reply costs one skipped row instead of the whole pass.
3090
+ const proposed = proposedRaw === undefined ? undefined : {
3091
+ ...proposedRaw,
3092
+ upserts: proposedRaw.upserts.filter((item) => item !== null && item !== undefined),
3093
+ ...proposedRaw.conflicts === undefined ? {} : {
3094
+ conflicts: proposedRaw.conflicts.filter((conflict) => conflict !== null && conflict !== undefined),
3095
+ },
3096
+ };
3065
3097
  if (proposed === undefined) {
3066
3098
  this.state.deleteJob(CONSOLIDATE_JOB);
3067
3099
  // `onSkip` records the concrete reason; this is the fallback for a
@@ -3177,6 +3209,12 @@ export class MemoriesRuntime {
3177
3209
  });
3178
3210
  this.noteLimitRefusal(error);
3179
3211
  this.log.warn('dsh-cross-memory: consolidation failed for session %s: %s', parent.session.id, message);
3212
+ // 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.
3215
+ 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);
3217
+ }
3180
3218
  // The command reports `consolidateSkipReason`; without this the failure
3181
3219
  // surfaced as "Nothing to consolidate: unknown reason".
3182
3220
  this.consolidateSkip = `the pass failed: ${message}`;
@@ -3707,6 +3745,11 @@ export class MemoriesRuntime {
3707
3745
  }
3708
3746
  scopes += 1;
3709
3747
  archived += await this.retain('project', descriptor.root, now);
3748
+ // The sweep walks every known workspace on the main thread; on a store
3749
+ // with 40 scopes that is one long tick. Yield between scopes so the pass
3750
+ // never holds the loop beyond a slice.
3751
+ if (scopes % 4 === 0)
3752
+ await yieldToEventLoop();
3710
3753
  }
3711
3754
  const rehomed = await this.store.adoptMisnamedProjects().catch(() => []);
3712
3755
  for (const move of rehomed) {
@@ -3937,10 +3980,14 @@ export class MemoriesRuntime {
3937
3980
  now,
3938
3981
  });
3939
3982
  let archived = 0;
3983
+ let examined = 0;
3940
3984
  for (const decision of expired) {
3941
3985
  this.log.decision('dsh-cross-memory: archiving %s/%s, unused for %d days', decision.scope, decision.id, Math.round(decision.ageDays));
3942
3986
  if (await this.store.archive(scope, root, decision.id, now, 'retention'))
3943
3987
  archived += 1;
3988
+ examined += 1;
3989
+ if (examined % 25 === 0)
3990
+ await yieldToEventLoop();
3944
3991
  }
3945
3992
  return archived;
3946
3993
  }
@@ -4550,7 +4597,11 @@ export function apply(ctx, config = {}) {
4550
4597
  runtime.cancelExtraction(agent);
4551
4598
  // A short-lived process may exit before the idle timer ever fires; the
4552
4599
  // disposal boundary is the last moment an extraction can still run.
4553
- void runtime.flushExit().catch(() => undefined);
4600
+ // `flushExit` is declared async, but the registry wraps every listener and
4601
+ // reports anything it throws as "agent/disposed listener threw". Normalise
4602
+ // the return value first: a `.catch` on a non-promise is exactly the failure
4603
+ // the host logged in 2026-11-22..26, and disposal must never be the raiser.
4604
+ Promise.resolve(runtime.flushExit()).catch(() => undefined);
4554
4605
  });
4555
4606
  // 0.1.7-rc.1 起宿主把 `agent/session-start` 改名为 `agent/created`(公告见 v0.1.7-rc.1
4556
4607
  // release notes)。payload 形状不变,仍是 `{ agent, source }`,`source` 取值同为
package/lib/sync.js CHANGED
@@ -598,6 +598,9 @@ export class MemorySync {
598
598
  // cycle cheaply and let the next timer retry once the writes settle; the
599
599
  // --autostash shortcut is not used because a concurrent edit to a file the
600
600
  // upstream commit also rewrites would resurface as conflict markers.
601
+ // A "commit then retry once" variant was tried on 2026-11-27 and reverted: a
602
+ // local edit that conflicts with the upstream commit turns the retry into a
603
+ // live rebase, which is exactly the state this branch exists to avoid.
601
604
  if (!this.rebaseInProgress()) {
602
605
  this.options.log.warn('dsh-cross-memory: 记忆库 rebase 没能启动(工作区仍有未提交改动),本轮跳过同步');
603
606
  return { ...nothing, pulled: 0, stoppedBy: 'rebase-not-started' };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The periodic pass must not walk a caught-up session's surface.
3
+ *
4
+ * `hasNothingNew` runs once per open session every `extractIntervalMinutes`
5
+ * tick. Before the cheap gate it built a full extraction window (a pass over
6
+ * every surface node, one `eventAt` call per seq) just to discover that the
7
+ * watermark was already at the tail; measured with 29 live sessions on the
8
+ * host, that walk held the event loop for 5.6-8.3 s every 30 minutes and the
9
+ * host logged `Host event loop stalled` each time.
10
+ *
11
+ * What the gate must not do is change the answer. This file pins both sides:
12
+ * a last node at or below the watermark is "nothing new" without one `eventAt`
13
+ * call, and anything newer still goes through the window walk.
14
+ *
15
+ * @module dsh-cross-memory/test/caught-up.test
16
+ */
17
+ import assert from 'node:assert/strict';
18
+ import { mkdtemp, rm } from 'node:fs/promises';
19
+ import { tmpdir } from 'node:os';
20
+ import { join } from 'node:path';
21
+ import test from 'node:test';
22
+ import { MemoriesRuntime } from '../index.js';
23
+ /** A context stand-in. */
24
+ const stubContext = {
25
+ get: () => undefined,
26
+ logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
27
+ };
28
+ /** A runtime over a temp store, disposed after the test. */
29
+ async function fixture(t) {
30
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-caught-up-'));
31
+ const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: true });
32
+ t.after(() => {
33
+ runtime.dispose();
34
+ return rm(dir, { recursive: true, force: true });
35
+ });
36
+ return { runtime };
37
+ }
38
+ /** A session whose surface is the given seqs and whose events are all probes. */
39
+ function stubSession(id, nodes, probes) {
40
+ return {
41
+ id,
42
+ header: { version: 0, id, createdAt: 0, cwd: process.cwd(), isSeeded: false },
43
+ surface: { nodes },
44
+ eventAt: (seq) => {
45
+ probes.push(seq);
46
+ return undefined;
47
+ },
48
+ };
49
+ }
50
+ /** The runtime method under test, at its private face. */
51
+ const gate = (runtime) => runtime;
52
+ test('a session whose last surface node is at the watermark skips the walk', async (t) => {
53
+ const { runtime } = await fixture(t);
54
+ runtime.state.putSession('caught-up', { lastSeq: 7, at: 0 });
55
+ const probes = [];
56
+ const session = stubSession('caught-up', [1, 2, 7], probes);
57
+ assert.equal(gate(runtime).hasNothingNew(session), true);
58
+ assert.deepEqual(probes, [], 'the gate answered without one eventAt call');
59
+ });
60
+ test('the gate opens for any node past the watermark', async (t) => {
61
+ const { runtime } = await fixture(t);
62
+ runtime.state.putSession('behind', { lastSeq: 6, at: 0 });
63
+ const probes = [];
64
+ const session = stubSession('behind', [1, 2, 7], probes);
65
+ // The walk runs (it can see node 7) and still reports "nothing new" because
66
+ // the probe yields no message — which is the behaviour the gate must keep.
67
+ assert.equal(gate(runtime).hasNothingNew(session), true);
68
+ assert.deepEqual(probes, [7], 'the walk started at the first node past the floor');
69
+ });
70
+ test('an empty surface still takes the window path', async (t) => {
71
+ const { runtime } = await fixture(t);
72
+ runtime.state.putSession('empty', { lastSeq: 0, at: 0 });
73
+ const probes = [];
74
+ const session = stubSession('empty', [], probes);
75
+ assert.equal(gate(runtime).hasNothingNew(session), true);
76
+ assert.deepEqual(probes, []);
77
+ });
78
+ test('a session with no recorded watermark is walked, not short-circuited', async (t) => {
79
+ const { runtime } = await fixture(t);
80
+ const probes = [];
81
+ const session = stubSession('fresh', [1, 2], probes);
82
+ assert.equal(gate(runtime).hasNothingNew(session), true);
83
+ assert.deepEqual(probes, [1, 2], 'with no watermark every node is newer');
84
+ });
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-cross-memory",
3
3
  "description": "Cross-session memory for the DeepSeek Harness: project-scoped and global memories with an explicit memory tool, idle-time background extraction, consolidation, and layered summary injection",
4
- "version": "0.2.10",
4
+ "version": "0.2.11",
5
5
  "private": false,
6
6
  "publishConfig": {
7
7
  "access": "public"