dsh-layers-hippocampus 1.9.9 → 1.9.21

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/package.json CHANGED
@@ -1,75 +1,75 @@
1
- {
2
- "name": "dsh-layers-hippocampus",
3
- "version": "1.9.9",
4
- "private": false,
5
- "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
- "type": "module",
7
- "main": "index.js",
8
- "license": "MIT",
9
- "author": "382quaii",
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/382quaii/dsh-Layers-Hippocampus.git"
13
- },
14
- "homepage": "https://github.com/382quaii/dsh-Layers-Hippocampus#readme",
15
- "bugs": {
16
- "url": "https://github.com/382quaii/dsh-Layers-Hippocampus/issues"
17
- },
18
- "keywords": [
19
- "deepseek",
20
- "harness",
21
- "dsh",
22
- "dsh-plugin",
23
- "memory",
24
- "long-term-memory",
25
- "knowledge-graph",
26
- "ai-agent"
27
- ],
28
- "engines": {
29
- "node": ">=22"
30
- },
31
- "publishConfig": {
32
- "registry": "https://registry.npmjs.org/",
33
- "access": "public"
34
- },
35
- "exports": {
36
- ".": "./index.js",
37
- "./package.json": "./package.json",
38
- "./client": "./ui/client.js",
39
- "./cordis.patch.yml": "./cordis.patch.yml",
40
- "./locale/*.json": "./locale/*.json",
41
- "./icon": "./icon.svg",
42
- "./src/*": "./src/*"
43
- },
44
- "files": [
45
- "index.js",
46
- "src/**/*.js",
47
- "ui/**/*.js",
48
- "cordis.patch.yml",
49
- "locale/*.json",
50
- "icon.svg",
51
- "screenshots.json",
52
- "assets/*.png",
53
- "README.md",
54
- "LICENSE",
55
- "CHANGELOG.md",
56
- "docs/ARCHITECTURE.zh.md",
57
- "docs/PUBLISHING.md",
58
- "market/**/*.yml",
59
- "market/*.md"
60
- ],
61
- "scripts": {
62
- "test": "node test/run.mjs",
63
- "bench": "node scripts/bench-protocol.mjs",
64
- "repair-handoff": "node scripts/repair-handoff.mjs",
65
- "check": "node --check index.js && node --check ui/client.js && node test/run.mjs"
66
- },
67
- "dsh": {
68
- "bundle": {
69
- "patch": "./cordis.patch.yml"
70
- },
71
- "client": {
72
- "platform": "web"
73
- }
74
- }
75
- }
1
+ {
2
+ "name": "dsh-layers-hippocampus",
3
+ "version": "1.9.21",
4
+ "private": false,
5
+ "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "license": "MIT",
9
+ "author": "382quaii",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/382quaii/dsh-Layers-Hippocampus.git"
13
+ },
14
+ "homepage": "https://github.com/382quaii/dsh-Layers-Hippocampus#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/382quaii/dsh-Layers-Hippocampus/issues"
17
+ },
18
+ "keywords": [
19
+ "deepseek",
20
+ "harness",
21
+ "dsh",
22
+ "dsh-plugin",
23
+ "memory",
24
+ "long-term-memory",
25
+ "knowledge-graph",
26
+ "ai-agent"
27
+ ],
28
+ "engines": {
29
+ "node": ">=22"
30
+ },
31
+ "publishConfig": {
32
+ "registry": "https://registry.npmjs.org/",
33
+ "access": "public"
34
+ },
35
+ "exports": {
36
+ ".": "./index.js",
37
+ "./package.json": "./package.json",
38
+ "./client": "./ui/client.js",
39
+ "./cordis.patch.yml": "./cordis.patch.yml",
40
+ "./locale/*.json": "./locale/*.json",
41
+ "./icon": "./icon.svg",
42
+ "./src/*": "./src/*"
43
+ },
44
+ "files": [
45
+ "index.js",
46
+ "src/**/*.js",
47
+ "ui/**/*.js",
48
+ "cordis.patch.yml",
49
+ "locale/*.json",
50
+ "icon.svg",
51
+ "screenshots.json",
52
+ "assets/*.png",
53
+ "README.md",
54
+ "LICENSE",
55
+ "CHANGELOG.md",
56
+ "docs/ARCHITECTURE.zh.md",
57
+ "docs/PUBLISHING.md",
58
+ "market/**/*.yml",
59
+ "market/*.md"
60
+ ],
61
+ "scripts": {
62
+ "test": "node test/run.mjs",
63
+ "bench": "node scripts/bench-protocol.mjs",
64
+ "repair-handoff": "node scripts/repair-handoff.mjs",
65
+ "check": "node --check index.js && node --check ui/client.js && node test/run.mjs"
66
+ },
67
+ "dsh": {
68
+ "bundle": {
69
+ "patch": "./cordis.patch.yml"
70
+ },
71
+ "client": {
72
+ "platform": "web"
73
+ }
74
+ }
75
+ }
package/src/config.js CHANGED
@@ -133,6 +133,9 @@ export const CONFIG_KEYS = Object.freeze([
133
133
  'features',
134
134
  // L2 multi-merge (v1.5.6): offline condensation of duplicate same-tag episodes.
135
135
  'l2Merge',
136
+ // v1.9.13: handoff coordinator budgets. A top-level group of its own because it
137
+ // bounds ONE mechanism (the handoff), not the memory model.
138
+ 'handoff',
136
139
  'policy',
137
140
  ]);
138
141
 
@@ -599,7 +602,7 @@ function normaliseRaw(raw) {
599
602
  }
600
603
 
601
604
  const out = { ...nested };
602
- for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge', 'ui']) {
605
+ for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge', 'ui', 'handoff']) {
603
606
  if (isPlainObject(nested[group])) out[group] = { ...nested[group] };
604
607
  }
605
608
  for (const [alias, path] of Object.entries(FLAT_ALIASES)) {
@@ -830,7 +833,7 @@ function attachConfigMeta(config, migration) {
830
833
  function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
831
834
  const input = normaliseRaw(raw);
832
835
 
833
- for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge', 'ui']) {
836
+ for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge', 'ui', 'handoff']) {
834
837
  if (group in input && input[group] !== undefined && !isPlainObject(input[group])) {
835
838
  throw configError(ErrorCodes.CONFIG_INVALID_TYPE, `config.${group} must be an object`, { key: group });
836
839
  }
@@ -1062,8 +1065,45 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1062
1065
  'context.liveCompact.maxNodesPerRequest',
1063
1066
  { min: 1, max: 64 },
1064
1067
  );
1065
- // Security red line (v1.5.1): default TRUE. Only an explicit operator choice may
1066
- // disable the consent gate; a malformed value is a config error, never "false".
1068
+ // v1.9.13: folding ownership is a CONTRACT choice (who may fold this surface), so it
1069
+ // is an enum with three named answers — a typo must fail fast instead of silently
1070
+ // picking `auto` and yielding folding the user did not ask to yield.
1071
+ const contextOwnership = requireEnum(
1072
+ contextIn.ownership === undefined ? 'auto' : contextIn.ownership,
1073
+ 'context.ownership',
1074
+ ['auto', 'lone', 'shared'],
1075
+ );
1076
+ // v1.9.13: the handoff coordinator's budgets. They used to live as constants inside
1077
+ // src/handoff/coordinator.js; the settings page may edit them now, so `resolveConfig`
1078
+ // MUST produce them — a saved value the resolver ignores is the exact "silently does
1079
+ // nothing" failure this batch exists to prevent.
1080
+ const handoffIn = input.handoff ?? {};
1081
+ const handoffMinIntervalMs = requireInteger(
1082
+ handoffIn.minIntervalMs === undefined ? 0 : handoffIn.minIntervalMs,
1083
+ 'handoff.minIntervalMs',
1084
+ { min: 0, max: 600_000 },
1085
+ );
1086
+ const handoffRequestBudgetMs = requireInteger(
1087
+ handoffIn.requestBudgetMs === undefined ? 1500 : handoffIn.requestBudgetMs,
1088
+ 'handoff.requestBudgetMs',
1089
+ { min: 200, max: 30_000 },
1090
+ );
1091
+ const handoffFailFastBudgetMs = requireInteger(
1092
+ handoffIn.failFastBudgetMs === undefined ? 800 : handoffIn.failFastBudgetMs,
1093
+ 'handoff.failFastBudgetMs',
1094
+ { min: 100, max: 5_000 },
1095
+ );
1096
+ const handoffCommandBudgetMs = requireInteger(
1097
+ handoffIn.commandBudgetMs === undefined ? 10_000 : handoffIn.commandBudgetMs,
1098
+ 'handoff.commandBudgetMs',
1099
+ { min: 500, max: 120_000 },
1100
+ );
1101
+ const handoffMaxRunMs = requireInteger(
1102
+ handoffIn.maxRunMs === undefined ? 15_000 : handoffIn.maxRunMs,
1103
+ 'handoff.maxRunMs',
1104
+ { min: 1_000, max: 300_000 },
1105
+ );
1106
+
1067
1107
  const contextRequireExplicitConsentForTransfer = requireBoolean(
1068
1108
  contextIn.requireExplicitConsentForTransfer === undefined
1069
1109
  ? defaults.context.requireExplicitConsentForTransfer
@@ -1692,6 +1732,8 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1692
1732
  retrieval: { topK: retrievalTopK },
1693
1733
  index: { maxPostingsPerTag: indexMaxPostingsPerTag },
1694
1734
  context: {
1735
+ // v1.9.13: who may fold. Resolved here so a settings-page save is not ignored.
1736
+ ownership: contextOwnership,
1695
1737
  maxTokens: contextMaxTokens,
1696
1738
  maxInjectTokens: contextMaxInjectTokens,
1697
1739
  threshold: contextThreshold,
@@ -1771,6 +1813,15 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1771
1813
  },
1772
1814
  migration: { timeoutMs: migrationTimeoutMs },
1773
1815
  tagTree: tagTreeConfig,
1816
+ // v1.9.13: coordinator budgets are settings now, so they must exist on the resolved
1817
+ // config the runtime reads. Defaults match DEFAULT_HANDOFF_POLICY.
1818
+ handoff: {
1819
+ minIntervalMs: handoffMinIntervalMs,
1820
+ requestBudgetMs: handoffRequestBudgetMs,
1821
+ failFastBudgetMs: handoffFailFastBudgetMs,
1822
+ commandBudgetMs: handoffCommandBudgetMs,
1823
+ maxRunMs: handoffMaxRunMs,
1824
+ },
1774
1825
  identity: { eventTimePolicy },
1775
1826
  tools: toolsConfig,
1776
1827
  tagging: taggingConfig,
@@ -84,6 +84,33 @@ function positive(value) {
84
84
  return Number.isFinite(value) && value > 0 ? Math.round(value) : null;
85
85
  }
86
86
 
87
+ /**
88
+ * v1.9.21: the host has SEVERAL window surfaces, and they can disagree.
89
+ *
90
+ * 2026-12-01: `llm.resolveModelInfo()` advertised 1,048,576 for the live model while
91
+ * the provider's own request guard refused the same request at 262,144
92
+ * ("request does not fit the model window … window source: host"). The plugin
93
+ * measured 418k / 1,048,576 = 40% and never handed over; every turn was rejected.
94
+ *
95
+ * The rule is therefore: never assume more room than the SMALLEST number any host
96
+ * surface reports. `resolveWindow` still names the winner; this picks the numbers.
97
+ *
98
+ * @param {Array<{source?: string, provider?: string|null, model?: string|null, window?: number}>} candidates
99
+ * @returns {{source?: string, provider?: string|null, model?: string|null, window: number}|null}
100
+ */
101
+ export function pickWindow(candidates) {
102
+ const valid = (Array.isArray(candidates) ? candidates : [])
103
+ .map((entry) => ({
104
+ source: entry?.source ?? 'host',
105
+ provider: entry?.provider ?? null,
106
+ model: entry?.model ?? null,
107
+ window: positive(entry?.window),
108
+ }))
109
+ .filter((entry) => entry.window !== null);
110
+ if (valid.length === 0) return null;
111
+ return valid.reduce((best, entry) => (entry.window < best.window ? entry : best), valid[0]);
112
+ }
113
+
87
114
  function clampCount(value) {
88
115
  return Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
89
116
  }
@@ -114,7 +114,7 @@ function normalizeForce(force) {
114
114
  * @param {() => object|null} [deps.probe] current pressure/marker snapshot
115
115
  * @param {(input: { force: string, reason: string, runId: number, context: object|null }) => Promise<object>} deps.run
116
116
  */
117
- export function createHandoffCoordinator({ clock, logger = null, policy = () => ({}), probe = null, run } = {}) {
117
+ export function createHandoffCoordinator({ clock, logger = null, policy = () => ({}), probe = null, run, onStart = null, onSettle = null } = {}) {
118
118
  if (typeof run !== 'function') throw new TypeError('createHandoffCoordinator requires a run() executor');
119
119
 
120
120
  const now = () => {
@@ -146,6 +146,22 @@ export function createHandoffCoordinator({ clock, logger = null, policy = () =>
146
146
  }
147
147
  };
148
148
 
149
+ /**
150
+ * v1.9.10: the two visibility seams. `onStart` fires SYNCHRONOUSLY before the runner
151
+ * is invoked (so a notice explaining "this may take a moment" is already in the
152
+ * conversation before the blocking part), and `onSettle` fires when the run really
153
+ * finishes — including after the caller's budget expired, which is the only way the
154
+ * person can still learn that the memory was written. Both are best-effort.
155
+ */
156
+ const fireHook = (hook, payload) => {
157
+ if (typeof hook !== 'function') return;
158
+ try {
159
+ hook(payload);
160
+ } catch (error) {
161
+ warn(`hook failed: ${error?.message ?? error}`);
162
+ }
163
+ };
164
+
149
165
  function snapshotContext(context) {
150
166
  if (context && typeof context === 'object') return context;
151
167
  try {
@@ -253,6 +269,9 @@ export function createHandoffCoordinator({ clock, logger = null, policy = () =>
253
269
  }
254
270
  lastStartedAt = startedAt;
255
271
 
272
+ // v1.9.10: the notice must exist BEFORE the blocking distillation starts.
273
+ fireHook(onStart, { source: request.source, context, force: request.force, runId });
274
+
256
275
  const execute = Promise.resolve().then(() =>
257
276
  run({ force: request.force, reason: request.source, runId, context }),
258
277
  );
@@ -267,6 +286,7 @@ export function createHandoffCoordinator({ clock, logger = null, policy = () =>
267
286
  releaseRun(runId);
268
287
  const outcome = buildOutcome({ status: HANDOFF_STATUS.WATCHDOG, runId, source: request.source, decision, waitedMs: now() - startedAt });
269
288
  lastResult = outcome;
289
+ fireHook(onSettle, { source: request.source, context, outcome });
270
290
  pumpPending();
271
291
  }, activePolicy.maxRunMs);
272
292
  watchdog.unref?.();
@@ -285,6 +305,7 @@ export function createHandoffCoordinator({ clock, logger = null, policy = () =>
285
305
  waitedMs: now() - startedAt,
286
306
  });
287
307
  lastResult = outcome;
308
+ fireHook(onSettle, { source: request.source, context, outcome });
288
309
  pumpPending();
289
310
  return outcome;
290
311
  },
@@ -301,6 +322,7 @@ export function createHandoffCoordinator({ clock, logger = null, policy = () =>
301
322
  });
302
323
  lastResult = outcome;
303
324
  warn(`failed (${request.source}): ${outcome.error.code}`);
325
+ fireHook(onSettle, { source: request.source, context, outcome });
304
326
  pumpPending();
305
327
  return outcome;
306
328
  },
@@ -0,0 +1,97 @@
1
+ /**
2
+ * v1.9.11 — the handoff notice, built from the INSTALLED Agent contract.
3
+ *
4
+ * 1.9.10 guessed the `agent.inject()` signature and mis-read its delivery semantics.
5
+ * The installed sources settle both:
6
+ *
7
+ * - `inject(message: UserMessage)` — ONE parameter, and it is a message OBJECT
8
+ * (`@deepseek-ai/dsh-agent/src/runtime-types.ts`, "Queue model-facing context for
9
+ * the next pre-step without waking the driver"). A bare string is not that shape;
10
+ * the ContentBlock[] fallback 1.9.10 tried is the LLM layer's shape, not the Agent's.
11
+ * - an IDLE driver never claims injected context: "idle drivers leave it pending
12
+ * until follow-up or steering wakes them". So "injected" does NOT mean "delivered",
13
+ * and treating the two as one signal produced the false `channel: 'none'`.
14
+ *
15
+ * The delivery rule that follows:
16
+ * running -> inject() (claimed at the next step boundary, no extra turn)
17
+ * idle -> steer() ("an idle driver starts a turn" — the message is delivered)
18
+ * unknown -> inject() (never summon a turn on a guess)
19
+ *
20
+ * Every outcome reports THREE independent facts instead of one: whether the call threw
21
+ * (`injectThrew` + `error`), which method actually carried it (`channel`), and whether a
22
+ * claim was observed (`claimed`, null until `agent/inbox/claimed` says otherwise).
23
+ */
24
+
25
+ /** How long a notice may sit in the inbox before we call it "not observed". */
26
+ export const NOTICE_ID_PREFIX = 'hippocampus_notice_';
27
+
28
+ let noticeCounter = 0;
29
+
30
+ /**
31
+ * Build the one message shape the Agent inbox accepts. Mirrors the shape the installed
32
+ * `dsh-interaction-hub` hands to `agent.followup()` — built literally, no host import.
33
+ *
34
+ * @param {string} text
35
+ * @param {{ id?: string, now?: number }} [options]
36
+ */
37
+ export function buildNoticeMessage(text, { id = null, now = null } = {}) {
38
+ noticeCounter += 1;
39
+ const stamp = Number.isFinite(now) ? now : Date.now();
40
+ const messageId = typeof id === 'string' && id.length > 0 ? id : `${NOTICE_ID_PREFIX}${stamp}_${noticeCounter}`;
41
+ return {
42
+ id: messageId,
43
+ role: 'user',
44
+ content: [{ type: 'text', text: String(text ?? '') }],
45
+ source: { kind: 'user' },
46
+ };
47
+ }
48
+
49
+ function statusOf(agent) {
50
+ try {
51
+ const status = agent?.status;
52
+ return status === 'running' || status === 'idle' ? status : 'unknown';
53
+ } catch {
54
+ return 'unknown';
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Deliver one notice and report what actually happened.
60
+ *
61
+ * Never throws: a notice is best-effort narration, and a failed narration must not
62
+ * fail the handoff that produced it.
63
+ *
64
+ * @param {object|null} agent
65
+ * @param {string} text
66
+ * @param {{ now?: number, id?: string }} [options]
67
+ * @returns {{ sent: boolean, channel: 'inject'|'steer'|'none', injectThrew: boolean,
68
+ * error: string|null, messageId: string|null, method: string|null, status: string }}
69
+ */
70
+ export function deliverNotice(agent, text, { now = null, id = null } = {}) {
71
+ const message = buildNoticeMessage(text, { id, now });
72
+ const status = statusOf(agent);
73
+ const canInject = typeof agent?.inject === 'function';
74
+ const canSteer = typeof agent?.steer === 'function';
75
+
76
+ // Order matters: injecting into an idle driver leaves the message unclaimed forever.
77
+ const preferred = status === 'idle' && canSteer ? 'steer' : canInject ? 'inject' : canSteer ? 'steer' : null;
78
+ const order = preferred === 'inject' ? ['inject', 'steer'] : preferred === 'steer' ? ['steer', 'inject'] : [];
79
+
80
+ let injectThrew = false;
81
+ let error = null;
82
+ for (const method of order) {
83
+ if (typeof agent?.[method] !== 'function') continue;
84
+ try {
85
+ agent[method](message);
86
+ return { sent: true, channel: method, injectThrew, error, messageId: message.id, method, status };
87
+ } catch (caught) {
88
+ // Only the throw that a caller can act on is reported; a missing method is not a throw.
89
+ if (method === preferred) {
90
+ injectThrew = true;
91
+ error = `${caught?.name ?? 'Error'}: ${caught?.message ?? String(caught)}`.slice(0, 200);
92
+ }
93
+ }
94
+ }
95
+
96
+ return { sent: false, channel: 'none', injectThrew, error, messageId: message.id, method: null, status };
97
+ }
package/src/hostBridge.js CHANGED
@@ -32,6 +32,13 @@ export const HOST_EVENT_NAMES = Object.freeze({
32
32
  sessionCreated: 'session/created',
33
33
  agentDisposed: 'agent/disposed',
34
34
  agentPresetSelected: 'agent-preset/selected',
35
+ /**
36
+ * v1.9.11: the only honest proof that an injected notice was READ. The installed
37
+ * contract says an injected message is claimed at the next step boundary and is NOT
38
+ * re-emitted as a user/message, so watching `user/message` can never see it.
39
+ * (`@deepseek-ai/dsh-agent/src/runtime-types.ts`, "agent/inbox/claimed".)
40
+ */
41
+ inboxClaimed: 'agent/inbox/claimed',
35
42
  });
36
43
 
37
44
  export const DEFAULT_COMPENSATE_AFTER_HOURS = 24;
@@ -57,11 +64,13 @@ export class HostBridge {
57
64
  onDream = null,
58
65
  onAgentCreated = null,
59
66
  onAgentPresetSelected = null,
67
+ onNoticeClaimed = null,
60
68
  env = process.env,
61
69
  } = {}) {
62
70
  this.bus = bus;
63
71
  this.clock = clock;
64
72
  this.logger = logger;
73
+ this.onNoticeClaimed = onNoticeClaimed;
65
74
  this.getConfig = getConfig;
66
75
  this.getLastDreamAt = getLastDreamAt;
67
76
  this.onDream = typeof onDream === 'function' ? onDream : null;
@@ -122,22 +131,34 @@ export class HostBridge {
122
131
  }
123
132
  };
124
133
  const onDisposed = () => {};
134
+ // v1.9.11: an injected notice is CLAIMED here, never re-emitted as user/message.
135
+ const onClaimed = (payload) => {
136
+ this.stats.noticeClaims = (this.stats.noticeClaims ?? 0) + 1;
137
+ this.stats.lastNoticeClaimAt = this.clock();
138
+ try {
139
+ this.onNoticeClaimed?.(payload);
140
+ } catch (error) {
141
+ this.logger?.warn?.(`hippocampus: notice claim handler failed: ${error?.message ?? error}`);
142
+ }
143
+ };
125
144
  bus.on(HOST_EVENT_NAMES.agentCreated, onStart);
126
145
  bus.on(HOST_EVENT_NAMES.sessionCreated, onStart);
127
146
  bus.on(HOST_EVENT_NAMES.agentPresetSelected, onPreset);
128
147
  bus.on(HOST_EVENT_NAMES.agentDisposed, onDisposed);
129
- this._bound = { bus, onStart, onPreset, onDisposed };
148
+ bus.on(HOST_EVENT_NAMES.inboxClaimed, onClaimed);
149
+ this._bound = { bus, onStart, onPreset, onDisposed, onClaimed };
130
150
  return () => this.detach();
131
151
  }
132
152
 
133
153
  detach() {
134
154
  if (!this._bound) return;
135
- const { bus, onStart, onPreset, onDisposed } = this._bound;
155
+ const { bus, onStart, onPreset, onDisposed, onClaimed } = this._bound;
136
156
  try {
137
157
  bus.off?.(HOST_EVENT_NAMES.agentCreated, onStart);
138
158
  bus.off?.(HOST_EVENT_NAMES.sessionCreated, onStart);
139
159
  bus.off?.(HOST_EVENT_NAMES.agentPresetSelected, onPreset);
140
160
  bus.off?.(HOST_EVENT_NAMES.agentDisposed, onDisposed);
161
+ bus.off?.(HOST_EVENT_NAMES.inboxClaimed, onClaimed);
141
162
  } catch {
142
163
  /* a dying bus must not throw during disposal */
143
164
  }
package/src/memory.js CHANGED
@@ -163,8 +163,16 @@ export const FOLD_BATCH = 5;
163
163
  export const FOLDED_TAG = 'status:folded';
164
164
  /** Tag written on a monthly memo. */
165
165
  export const MONTHLY_TAG = 'status:monthly';
166
- /** Snapshot shape for state/handoff.json (v1.5.0 session rollover). */
167
- export const HANDOFF_SCHEMA = 1;
166
+ /**
167
+ * Snapshot shape for state/handoff.json (v1.5.0 session rollover).
168
+ *
169
+ * v1.9.10 -> 2: the marker now states whether the conversation is EXPECTED to move to a
170
+ * new session (`nextSessionRequired`), which pressure band it belongs to
171
+ * (`handoffEpoch`) and whether the person was actually told (`visibleNotice`). A v1
172
+ * marker is still readable — `handoffState()` defaults the missing fields instead of
173
+ * letting every caller invent a meaning for `undefined`.
174
+ */
175
+ export const HANDOFF_SCHEMA = 2;
168
176
  /** Tag written on the L1.5 tail summary produced by an automatic handoff. */
169
177
  export const HANDOFF_TAG = 'status:handoff';
170
178
  /** Session-key used when the host does not publish a session id. */
@@ -2024,7 +2032,38 @@ export class Memory {
2024
2032
  }
2025
2033
  // Keep provenance even after consumption (consumedBy/consumedAt are how the
2026
2034
  // next boot can tell "handed off" from "never handed off").
2027
- return { ...marker, active: marker.active === true };
2035
+ return {
2036
+ ...marker,
2037
+ active: marker.active === true,
2038
+ // v1.9.10 (marker v2): a v1 marker carries none of these. Defaulting here keeps
2039
+ // every reader honest — `undefined` would let a caller treat "unknown" as "true".
2040
+ nextSessionRequired: marker.nextSessionRequired === true,
2041
+ handoffEpoch: typeof marker.handoffEpoch === 'string' ? marker.handoffEpoch : null,
2042
+ reason: typeof marker.reason === 'string' ? marker.reason : null,
2043
+ visibleNotice: marker.visibleNotice && typeof marker.visibleNotice === 'object' ? marker.visibleNotice : null,
2044
+ };
2045
+ }
2046
+
2047
+ /**
2048
+ * v1.9.11: patch the delivered-notice outcome inside the durable marker.
2049
+ *
2050
+ * The claim arrives AFTER the marker is written (the driver takes the message at its
2051
+ * next step boundary), so "was this ever read?" cannot be answered at write time.
2052
+ * Rather than leave a permanently unknown field, the claim patches it in place.
2053
+ * Best-effort: a failed patch only costs the panel one stale field.
2054
+ */
2055
+ updateHandoffVisibleNotice(patch = {}) {
2056
+ const marker = this.handoffState();
2057
+ if (!marker || marker.active !== true || !marker.visibleNotice) return null;
2058
+ const next = { ...marker, visibleNotice: { ...marker.visibleNotice, ...patch } };
2059
+ try {
2060
+ ensureDir(this.paths.state);
2061
+ writeJsonAtomic(this.handoffPath(), next);
2062
+ this._markBriefingDirty();
2063
+ return next;
2064
+ } catch {
2065
+ return null;
2066
+ }
2028
2067
  }
2029
2068
 
2030
2069
  /**
@@ -2248,7 +2287,7 @@ export class Memory {
2248
2287
  };
2249
2288
  }
2250
2289
 
2251
- async checkHandoff({ now = this.clock.now(), distill = true, timeoutMs = HANDOFF_TIMEOUT_MS, force = false } = {}) {
2290
+ async checkHandoff({ now = this.clock.now(), distill = true, timeoutMs = HANDOFF_TIMEOUT_MS, force = false, reason = 'threshold', visibleNotice = null } = {}) {
2252
2291
  this.assertOpen();
2253
2292
  const usage = this.sessionUsage();
2254
2293
  const native = this.context.nativeState({ now, sessionTokens: usage.tokens });
@@ -2323,6 +2362,37 @@ export class Memory {
2323
2362
  state: failure ? HANDOFF_STATES.FAILED : HANDOFF_STATES.ACTIVE,
2324
2363
  degraded: Boolean(failure),
2325
2364
  at: now,
2365
+ // v1.9.10 (marker v2) — three facts the next conversation needs:
2366
+ // - `nextSessionRequired`: this handoff SUCCEEDED, so the conversation is
2367
+ // expected to continue in a new session. A FAILED distillation must never
2368
+ // claim that: the summary does not exist, so staying here is correct.
2369
+ // - `handoffEpoch`: session + pressure band. It is the same pair the coordinator
2370
+ // dedupes on, so "did this band already hand off?" has one answer everywhere.
2371
+ // - `visibleNotice`: whether the person was actually told (C3). A silent handoff
2372
+ // is indistinguishable from a hang, which is how 2026-12-01 was misdiagnosed.
2373
+ nextSessionRequired: !failure,
2374
+ handoffEpoch: `${usage.sessionId ?? 'ctx'}:${Math.round((Number(native.projectedRatio) || 0) * 100)}`,
2375
+ reason: String(reason ?? 'threshold').slice(0, 40),
2376
+ visibleNotice:
2377
+ visibleNotice && typeof visibleNotice === 'object'
2378
+ ? {
2379
+ // v1.9.11: three INDEPENDENT facts. Conflating them is what made 1.9.10
2380
+ // report `channel:'none'` for a call that had actually succeeded.
2381
+ sent: visibleNotice.sent === true,
2382
+ channel: String(visibleNotice.channel ?? 'none').slice(0, 16),
2383
+ injectThrew: visibleNotice.injectThrew === true,
2384
+ error: typeof visibleNotice.error === 'string' ? visibleNotice.error.slice(0, 200) : null,
2385
+ // null = not observed (yet). The claim arrives at the next step boundary,
2386
+ // which is after this marker is written; `updateHandoffVisibleNotice()`
2387
+ // patches it when it does.
2388
+ claimed: visibleNotice.claimed === true ? true : null,
2389
+ claimedAt: Number(visibleNotice.claimedAt) || null,
2390
+ // v1.9.11: the inbox message id is the ONLY way to match a later
2391
+ // `agent/inbox/claimed` back to this marker.
2392
+ messageId: typeof visibleNotice.messageId === 'string' ? visibleNotice.messageId.slice(0, 80) : null,
2393
+ at: Number(visibleNotice.at) || now,
2394
+ }
2395
+ : null,
2326
2396
  // Provenance matters: a context-window fallback is not a session measurement.
2327
2397
  tokenSource: usage.sessionId === null ? 'context-window' : 'session',
2328
2398
  sessionId: usage.sessionId,