dsh-layers-hippocampus 0.0.0-stage → 1.6.1

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 (68) hide show
  1. package/CHANGELOG.md +1381 -0
  2. package/LICENSE +21 -0
  3. package/README.md +231 -2
  4. package/assets/icon-180.png +0 -0
  5. package/assets/screenshot-graph.png +0 -0
  6. package/assets/screenshot-panel.png +0 -0
  7. package/assets/screenshot-settings.png +0 -0
  8. package/cordis.patch.yml +20 -0
  9. package/docs/ARCHITECTURE.zh.md +745 -0
  10. package/docs/PUBLISHING.md +82 -0
  11. package/icon.svg +8 -0
  12. package/index.js +2434 -0
  13. package/locale/en.json +11 -0
  14. package/locale/zh.json +11 -0
  15. package/market/SUBMISSION.md +58 -0
  16. package/market/data/plugins/382quaii__dsh-Layers-Hippocampus.yml +7 -0
  17. package/package.json +73 -4
  18. package/screenshots.json +5 -0
  19. package/src/clock.js +64 -0
  20. package/src/compression.js +65 -0
  21. package/src/config.js +1181 -0
  22. package/src/context/contextEngine.js +355 -0
  23. package/src/cron.js +157 -0
  24. package/src/decay.js +57 -0
  25. package/src/deletePipeline.js +283 -0
  26. package/src/dream.js +547 -0
  27. package/src/dreamTimer.js +121 -0
  28. package/src/errors.js +172 -0
  29. package/src/eventLoop.js +85 -0
  30. package/src/graph.js +224 -0
  31. package/src/hostBridge.js +221 -0
  32. package/src/identity.js +328 -0
  33. package/src/index/buildIndex.js +531 -0
  34. package/src/index/indexManager.js +292 -0
  35. package/src/index/indexStore.js +182 -0
  36. package/src/l2Merge.js +246 -0
  37. package/src/log/identityLedger.js +263 -0
  38. package/src/log/ingest.js +107 -0
  39. package/src/log/logStore.js +427 -0
  40. package/src/log/records.js +284 -0
  41. package/src/maintenance.js +204 -0
  42. package/src/memory.js +2788 -0
  43. package/src/migration.js +225 -0
  44. package/src/migrationRunner.js +258 -0
  45. package/src/pendingDelete.js +98 -0
  46. package/src/policy.js +352 -0
  47. package/src/priceWindow.js +78 -0
  48. package/src/rawArchive.js +226 -0
  49. package/src/rawIndex.js +134 -0
  50. package/src/rawStore.js +901 -0
  51. package/src/retrieval.js +766 -0
  52. package/src/schedule.js +130 -0
  53. package/src/scheduler.js +121 -0
  54. package/src/semantic/semanticStore.js +213 -0
  55. package/src/semantic/tempSemantic.js +450 -0
  56. package/src/spaces/singleSpace.js +129 -0
  57. package/src/tagTreeCache.js +333 -0
  58. package/src/tagTreeRebuild.js +261 -0
  59. package/src/tagging.js +92 -0
  60. package/src/util.js +205 -0
  61. package/src/utils/RegexExtractor.js +81 -0
  62. package/src/utils/ToolOutputSlimmer.js +49 -0
  63. package/src/utils/WriteQueue.js +84 -0
  64. package/src/utils/memoryHints.js +75 -0
  65. package/src/utils/promptLayout.js +48 -0
  66. package/src/utils/reservedTags.js +24 -0
  67. package/src/webRoutes.js +650 -0
  68. package/ui/client.js +4053 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,1381 @@
1
+ # Changelog
2
+
3
+ All notable changes to `dsh-layers-hippocampus` are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and the project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [1.6.1] — 2026-11-07
8
+
9
+ **Version fully un-frozen (user directive 2026-11-07): normal semantic versioning
10
+ resumes; 1.6.1 is the current release (patch on top of 1.6.0).**
11
+
12
+ - **Archive month detail UI**: the panel's raw section now shows `indexedShards` /
13
+ `archiveCount` StatCards plus a **collapsible month table** (月份 / 引擎 / 归档大小 /
14
+ 归档时间, month-DESC, collapsed by default). `panel.raw` carries `archivedBytes`,
15
+ `totalBytes`, `engines:{gzip,zstd}`, `savedBytes`, `compressionRatio` (null when
16
+ unmeasured) and `archiveMonths[]` with `at`/`bytesBefore`/`bytesAfter`; older hosts
17
+ degrade to “—” instead of breaking the panel.
18
+ - **Segment-token audit** (`docs/AUDIT-2026-11-07-segment-token.md`): no P0
19
+ same-segment re-injection exists; the six injection surfaces are documented with
20
+ their dedup mechanisms. Its two P3 items are now IMPLEMENTED:
21
+ - **P3-1** the `[Active Task]` event id also joins the block dedup pool, so one
22
+ event can never be injected both as Active Task and as a recall block;
23
+ - **P3-2** `[Persona & Traits]` is memoized by the L3 shape (`summaryId` +
24
+ `updatedAt` + count); unchanged L3 costs one signature, not a re-render.
25
+ - **Raw cold-tier archiving (zero external deps)**: on `maintain()`, daily shards
26
+ older than `raw.archiveAfterDays` (default **7**) are merged per calendar month
27
+ into one `raw-archive-YYYY-MM.jsonl.gz` via Node's built-in `zlib`, then the
28
+ plaintext shard is removed. Archiving runs at most once per month and SKIPS any
29
+ shard that is recently read (`state/raw-access.json`), `pinned`,
30
+ `status:handoff`, or carries a hot active-set tag. `deep_raw` and hash restore
31
+ stream the archive with `createGunzip()` line-by-line (no full read), report
32
+ `archiveErrors`/`notes: archive-corrupt:<name>` for a corrupt archive, and keep
33
+ plaintext `.jsonl` reads unchanged. `raw.retentionDays` default moves **30 → 90**
34
+ and must stay strictly above `archiveAfterDays` (fail-fast otherwise).
35
+ - **`/stats` panel: archive + index visualization**: `panel.raw` now reports
36
+ `archiveCount`, `archivedBytes`, `totalBytes`, `archiveMonths`, `engines`
37
+ (`{gzip,zstd}`), `savedBytes` (sum of bytesBefore−bytesAfter), `compressionRatio`
38
+ (null when no measured archive) and `indexedShards`. Each archive records
39
+ `bytesBefore`/`bytesAfter` in `state/raw-archive.json`, so the ratio and saved
40
+ bytes are real measurements, not estimates. The panel gains two StatCards
41
+ (“raw 索引覆盖”, “raw 冷归档”) with graceful “—” for an older host, plus a
42
+ collapsible **archive month table** (月份 / 引擎 / 归档大小 / 归档时间, month-DESC,
43
+ collapsed by default); `archiveMonths` rows carry `at`/`bytesBefore`/`bytesAfter`.
44
+ 4 cases in `test/v161.stats.test.js` + 2 UI contract cases.
45
+ - **Sparse line index for raw shards** (performance audit item C): one
46
+ `<day>.jsonl.idx.json` per shard, sampled every 64 lines with
47
+ `{line, offset, timestamp}` plus `bytes/mtimeMs/lineCount/minTs/maxTs/sorted`.
48
+ `deep_raw` uses it to SKIP a shard whose time range cannot overlap the window
49
+ (without opening the file) and to reuse `lineCount` for absolute `hit.line`
50
+ numbers (no second pass). Built offline by `maintain()` (50 shards/round,
51
+ progressive), deleted with its shard by `prune()`, and silently bypassed when
52
+ missing, stale (bytes/mtime mismatch), corrupt, or non-monotonic. `stats()`
53
+ reports `indexedShards`. 6 cases in `test/v161.rawIndex.test.js`.
54
+ - **Compression-engine selection (zero install)**: `raw.compressionEngine`
55
+ (`gzip` default | `zstd`) + a settings-page engine picker with an
56
+ enable/disable button. Zstd uses Node's BUILT-IN `node:zlib` zstd — nothing is
57
+ downloaded and there is no package to uninstall; "停用" switches back to gzip.
58
+ Archives are `raw-archive-YYYY-MM.jsonl.gz` / `.jsonl.zst`, dispatch is by
59
+ extension, and a legacy gzip archive stays readable after switching to zstd.
60
+ When the runtime lacks zstd the config silently falls back to gzip and
61
+ `capabilities.compression` reports `{engine, fallback, zstd, node}` for the UI.
62
+ - **Raw retention tiers documented**: the raw layer exposes exactly three modes —
63
+ `off` (keep nothing), `salience` (default: high-value turns/code/stack/errors only),
64
+ `all` (bounded by `maxTurnKb`/`maxBytesPerDay`/`maxTotalMb`) — plus
65
+ `retentionDays` (default 90) and `pinned` never pruned. README/ARCHITECTURE now
66
+ describe these implemented tiers only.
67
+ - **Fixed — settings page rendered blank**: the compression-engine card referenced a
68
+ bare `payload` that only exists in other components' scopes; it now uses the local
69
+ `statsPayload` and the shared `Select` component (not a fake `type:'select'` on
70
+ `Field`). `test/v161.ui.test.js` pins the scope rule so the whole settings page
71
+ cannot be taken down by one card again.
72
+
73
+ - **Recall bound-based early exit** (performance audit item A): every score is
74
+ `salience × decay × tagAffinity(≤3) × lexicalBoost(≤1) × association(≤1) ×
75
+ timeBoost(≤1.3) × handoff(≤1)`, so `salience × 3.9` is a hard upper bound.
76
+ Candidates are visited salience-DESC and scoring stops as soon as that bound
77
+ cannot beat the current k-th score. `pinned` hits bypass the cut, the best-k
78
+ window keeps the bound exact (ties still visited), and the result reports
79
+ `pruned` + `notes: pruned:<n>`. Complexity unchanged in the worst case
80
+ (`O(K log K)` ordering) but the per-candidate decay/similarity work is skipped
81
+ for the long low-salience tail.
82
+ - Regression: pinned decay stays exactly 1 (bypass path), monthly memos unchanged.
83
+ - **447 tests green** (64 files).
84
+
85
+ ## [1.6.0] — 2026-11-06
86
+
87
+ > Version note: 1.6.0 was the FIRST release after the temporary 1.5.7 freeze; the
88
+ > 2026-11-07 directive removed all freeze language and resumed normal versioning.
89
+ Cold-start wake-up + user-controlled cold-start injection:
90
+
91
+ - **Anti-"customer service" wake-up** (static `memory:policy` prefix): the model is
92
+ told it has continuous long-term memory, must not open with "how may I help you",
93
+ and should recall the recent topic before replying.
94
+ - **`context.coldStartInjectSummary`** (default **true**): on the first prompt
95
+ assembly of a brand-new conversation, inject `[Cold-Start Summary]` — the handoff
96
+ summary event when present, else the top-3 L3 semantic summaries (≤800 chars).
97
+ - **`context.coldStartInjectRecentTurns`** (default **false**): inject
98
+ `[Previous Context Tail]` with the last ≤5 business episodes (200 chars each).
99
+ - **`[Cold-Start Detected: Active Space=…, Recent Topic=…]`** header when either
100
+ switch is on; the block is volatile-tail only (prompt-cache prefix untouched) and
101
+ is consumed exactly once per new conversation.
102
+ - Both switches off → no historical blocks; the static wake-up policy still ships.
103
+ - UI: two independent toggles in the settings page's session group; HTTP-editable.
104
+ - **416 tests green** (64 files).
105
+
106
+ ## [1.5.7] — 2026-11-04
107
+
108
+ > Historical note: 1.5.7 shipped under a temporary version freeze; the 2026-11-07
109
+ > directive removed ALL freeze language and resumed normal semantic versioning
110
+ > (current version: 1.6.1). The sentence below is the historical 1.5.7 statement.
111
+
112
+ **Version freeze (historical, superseded): 1.5.7 was the shipped release.**
113
+ This release folds in everything added after the 1.5.6 draft — Orchestrator
114
+ federation/dedupe wiring, read-time merge, cross-space recall aggregation (opt-in
115
+ `features.crossSpaceRecall`), durable Orchestrator state, the settings-page GitHub
116
+ installer, the verified automatic new-conversation handoff (with configurable
117
+ once/interval detection), low-valley Dream Phase 2, space deletion, graph
118
+ interaction, and the rest of the 1.5.6 section below. Annotations of the form
119
+ `v1.5.6:` below record the version in which a feature was introduced; they are
120
+ history, not the current version. **411 tests green** (64 files).
121
+
122
+ ## [1.5.6] — 2026-11-03
123
+
124
+ **`deep_raw` now scans by line cursor: a huge day shard is never loaded whole.**
125
+ The black box is read newest-first in fixed chunks; peak memory is one chunk plus
126
+ one partial line (test-locked), not the file size. `hit.line` keeps its absolute
127
+ 1-based semantics. **411 tests green** (was 303).
128
+
129
+ ### Changed — raw scan / restore (zero-dependency, O(chunk) memory)
130
+
131
+ - **`readLinesReverse(file, {chunkSize, onBuffer})`** (`src/rawStore.js`): reads a
132
+ file backwards in 64 KiB chunks, yielding one line at a time; the trailing
133
+ newline does not produce a phantom empty line. `onBuffer` reports the live
134
+ buffer size for tests.
135
+ - **`deep_raw` scan** rewrote the whole-shard `readFileSync + split` path:
136
+ newest-first, one `JSON.parse` per line, line bytes counted as they are read,
137
+ hit results collected per shard. `hit.line` is computed from the shard's line
138
+ count via ONE extra bounded streaming pass, paid only when that shard produced
139
+ a hit (so a miss costs no counting pass).
140
+ - **`restoreByHash`** streams forward via `readline`; **`_loadTombstones`** streams
141
+ synchronously with a `StringDecoder` (multi-byte boundaries preserved);
142
+ **`_hashesFor`** streams asynchronously (so `RawStore.capture()` is now async —
143
+ only internal callers exist; the public `captureRaw()` contract is unchanged).
144
+ - **Engine-side result ceiling**: `MAX_SCAN_RESULTS = 500` caps one scan even if an
145
+ embedder passes `limit: 5000`; `budget.maxHits` is reported, `truncated` is true
146
+ when the cap is reached.
147
+ - **Observability**: `scanned.peakBufferBytes` exposes the largest buffer the
148
+ scanner ever held (proves the memory bound).
149
+
150
+ ### Added — stability hardening (same 1.5.6, no extra version bump)
151
+
152
+ - **Recall response cap**: `context.maxInjectTokens` (default 4000, 256–100 000,
153
+ fail-fast) bounds the JSON one recall returns. `Memory.applyPayloadBudget()`
154
+ keeps hits in rank order (the first is always kept), then semantic/temp summaries;
155
+ a cut is loud: `truncated: true`, `payload: {maxTokens, estimatedTokens, dropped}`
156
+ and a `payload-budget` note. Editable over HTTP and rendered in the settings page
157
+ with a tooltip.
158
+ - **`Memory.close()` releases resources**: `RawStore.close()` clears the flush timer
159
+ and synchronously persists queued turns before the log closes; `Memory.close()`
160
+ then detaches the scheduler, clears oversized-tag hints and calls
161
+ `IndexManager.release()` to drop the A/B views. Idempotent.
162
+ - **Event-loop lag monitoring**: `src/eventLoop.js` (`createLagMonitor`) wraps
163
+ `perf_hooks.monitorEventLoopDelay`; `maintain()` yields 50ms between phases and
164
+ `IndexManager.rebuild` yields between read/build/catch-up/swap once the measured
165
+ max delay crosses 100ms. The report carries
166
+ `eventLoop: {maxMs, p99Ms, meanMs, yields, thresholdMs}`. Honest boundary: a
167
+ synchronous builder cannot be preempted, so the granularity is phase-level and the
168
+ numbers expose an oversized phase.
169
+
170
+ ### Added — pre-ingest tagging (same 1.5.6, no extra version bump)
171
+
172
+ - **`src/tagging.js` / `extractTags()`**: deterministic anchors derived from content
173
+ shape — named error types (`error:typeerror`), Node errno codes
174
+ (`error:econnrefused`), fenced-code language (`lang:python`), HTTP status
175
+ (`http:500`), file path basename (`file:index.js`) and explicit task statements
176
+ (`task:…`). No LLM, no dependencies, stable ordering.
177
+ - **Write gate** (`Memory.stage`): model-provided tags always win; only an untagged
178
+ write runs the heuristic. Tags are deduplicated and capped by `tagging.maxTags`
179
+ (1–5, default 2). Inferred anchors are recorded on `meta.auto_tagged` /
180
+ `meta.auto_tags` (provenance, not a silent rewrite of what the caller asserted).
181
+ - **raw stays pure**: the black box still receives exactly
182
+ `{turn_id, timestamp, role, content}` — the test locks the four-field shape.
183
+ - **Miss is a warning**: `MEM_E_AUTO_TAG_MISS` goes to the Host log via
184
+ `Memory.setWarnHook` (wired in `index.js`) and increments
185
+ `panel.autoTag.misses`; the write proceeds untagged.
186
+ - **Config**: `tagging.autoTag` (default true) and `tagging.maxTags` (1–5), both
187
+ fail-fast, HTTP-editable and rendered in the settings page.
188
+
189
+ ### Added — pinned memory (same 1.5.6, no extra version bump)
190
+
191
+ - **`remember({ pinned: true })`**: a lesson/experience that must survive time.
192
+ It stores `meta.pinned = true` (provenance included in `content_hash`) and is
193
+ refused with **`MEM_E_PINNED_TAG_REQUIRED`** unless the caller supplies at least
194
+ one tag — an untriggerable lesson would be dead memory.
195
+ - **Never decays**: `projectEpisode` exposes `pinned`; `deriveTagTable` gives a
196
+ pinned event `decay = 1`, keeps its tag un-archived, and protected from the
197
+ `maxPostingsPerTag` drop; `deriveActiveSet` admits pinned tags regardless of
198
+ score or the cap.
199
+ - **Ranks first**: recall gives every matching pinned record `decay = 1`, exempts
200
+ it from `minScore`, and orders pinned hits ahead of all others
201
+ (`pinned-first:N` note).
202
+ - **Observability**: `panel.global.pinned` counts pinned records.
203
+ - Tool surface: `memory_remember.pinned` (boolean) is documented and passed
204
+ through; `bulk_ingest` items accept the same field.
205
+
206
+ ### Changed — relevance-first prompt hints (same 1.5.6, no extra version bump)
207
+
208
+ - **Global "most active tags" map removed from the prompt.** `runtime.promptState()`
209
+ now renders only tags that lexically overlap the CURRENT user turn (max 5), via
210
+ `src/utils/memoryHints.js` (`selectRelevantTags` / `renderMemoryHints`).
211
+ Internal bookkeeping tags (`status:*`, `month:*`, `context:*`, `active_task`)
212
+ are never hinted; no match means the section is simply absent (no padding).
213
+ - **Cache-safe placement**: `[Memory Hints]` is rendered AFTER `[Memory Blocks]`,
214
+ so a per-turn hint never disturbs the cacheable prefix (rules only).
215
+ - **Input source**: prompt assembly receives no message text, so the plugin tracks
216
+ the last `user/message` from `session/event` (`runtime.lastUserText`); other
217
+ surface events never overwrite it.
218
+ - The legacy `renderMemoryMap` / `composePrompt({map})` API remains for callers
219
+ and is still unit-tested, but the plugin no longer injects the map.
220
+
221
+ ### Added — capability flags & microkernel boundary (same 1.5.6, no extra version bump)
222
+
223
+ - **`features.multiSpace` (default true)** and **`features.crossSpaceTransfer`**
224
+ (default mirrors multiSpace). Both are fail-fast, HTTP-editable and rendered in
225
+ the settings page; turning multiSpace off implies crossSpaceTransfer off, and the
226
+ explicit contradictory combination is refused.
227
+ - **Strict single-space mode**: with multiSpace off, every routed read/write whose
228
+ `targetSpaceId` is not `default` answers **`MEM_E_FEATURE_DISABLED`** (before any
229
+ I/O); `createSpace` / `ensureSpace` / `warmup` refuse too, and the `/spaces` route
230
+ reports `['default']` with `capabilities.spaces=false` so the client hides
231
+ create/selector affordances instead of 404-ing.
232
+ - **Tools follow the flags**: `space_transfer` / `transfer_to_global` are neither
233
+ registered nor advertised in the prompt section when the capability is off.
234
+ - **`Memory.open('/abs/dir')`** is now the single-space form (the Orchestrator owns
235
+ the multi-space walk); the options-object form stays supported.
236
+ - **`Memory.warmup({targetSpaceId?, dataDir?})`**: lazy, read-only index warm-up for
237
+ the UI / Orchestrator — no maintenance, no writes; unknown/relative dataDir fails
238
+ fast.
239
+
240
+ ### Added — host lifecycle: compensating Dream (same 1.5.6, no extra version bump)
241
+
242
+ - **`src/hostBridge.js`** subscribes to the Host's process-local events
243
+ `agent/created` and `session/created` (the "session start" signals) through a plain
244
+ `{on, off}` bus seam, plus `agent/disposed` for teardown.
245
+ - **Compensation rule**: on a session start, if no Dream ran for
246
+ `dream.compensateAfterHours` (default 24, 1–720, fail-fast) AND the price window
247
+ permits, run exactly ONE compensating Dream through the shared
248
+ `runtime.runMaintenance('compensate')` gate — never a second concurrent run, never
249
+ a queue.
250
+ - **Price is injected, never guessed**: `setPriceProbe(fn)` / `DSH_DREAM_PRICE=low|high`.
251
+ Unknown price + an LLM-backed Dream ⇒ skip (`price-unknown`); unknown + local-only
252
+ Dream ⇒ allowed. A known peak ⇒ skip (`peak`).
253
+ - **Observability**: `runtime.hostStatus()` and `/stats`'s top-level `host` report
254
+ `sessionStarts / compensations / skipped / lastSkipReason / dreamDue / lowValley`.
255
+ - `enableDream:false` disables compensation; `agent/created`/`session/created` do not
256
+ otherwise affect memory writes (raw capture remains on `session/event`).
257
+
258
+ ### Added — Dream tunables in the settings page (same 1.5.6, no extra version bump)
259
+
260
+ - The **safe** Dream subset is now exposed to `/stats` + `/config` and rendered in
261
+ the settings page: `useLlm`, `minGroupSize`, `maxGroupsPerRun`, `maxSummaryChars`,
262
+ `maxSourceChars`, `maxEventsPerGroup`, `llmTimeoutMs`, `failureThreshold`,
263
+ `cooldownMinutes`, `compensateAfterHours` (all fail-fast validated).
264
+ - **Credentials stay private**: `dream.llm.{baseUrl,model,apiKey}` is neither exposed
265
+ by the routes nor editable over HTTP nor rendered in the form; it comes only from
266
+ the profile or `DSH_DREAM_LLM_*` env. A test asserts the key never appears in the
267
+ `/stats` payload.
268
+
269
+ ### Added — L2 multi-merge (`merged_into`, same 1.5.6, no extra version bump)
270
+
271
+ - **`src/l2Merge.js`** condenses duplicate same-tag L2 episodes into ONE durable
272
+ record, offline at the end of `maintain()` (after monthly memos; a failure never
273
+ fails maintenance).
274
+ - **Pinned and ordinary groups are strictly separated** — pinned merges only with
275
+ pinned; ordinary only with ordinary. A pinned merge keeps `pinned: true` and
276
+ inherits every tag.
277
+ - **Text**: earliest/latest time + deduplicated core text (each source capped), the
278
+ whole line capped by `l2Merge.maxSummaryChars` (ASCII ellipsis so identity
279
+ canonicalisation cannot make it longer).
280
+ - **Federated metadata**: `meta.global_tags` is copied into the merged record's
281
+ `meta` and **never becomes a tag**, so it cannot enter the sub-space inverted index;
282
+ `projectEpisode` exposes it as `event.globalTags` for the merge layer only.
283
+ - **Append-only marking**: sources are recorded as merged in
284
+ `state/l2-merge.json` (`mergedSourceIds`); the log is untouched and originals stay
285
+ recoverable. A second pass merges nothing (idempotent) and `status().panel.l2Merge`
286
+ reports the bookkeeping.
287
+ - **Config `l2Merge`**: `enabled` (default true), `minGroupSize` (2–20, default 2),
288
+ `maxGroupsPerRun` (1–50, default 5), `maxSummaryChars` (100–2000, default 400);
289
+ fail-fast, HTTP-editable and rendered in the settings page.
290
+
291
+ ### Added — L3 semantic tag invariant (same 1.5.6, no extra version bump)
292
+
293
+ - **`SemanticStore.upsert` is strict**: an L3 summary with zero usable tags is
294
+ refused with **`MEM_E_SEMANTIC_TAG_REQUIRED`** — such a summary could never be
295
+ reached by tag-driven retrieval (dead knowledge).
296
+ - **Offline paths degrade instead of failing**: delete-consolidation and trend
297
+ promotion derive tags from content heuristics (`extractTags`) and, if even that
298
+ yields nothing, write an explicit provenance anchor (`origin:unlabelled-episode` /
299
+ `origin:unlabelled-trend`). Maintenance and the two-phase delete pipeline therefore
300
+ never break on historical untagged events.
301
+ - **Historical data is read-only degraded**: summaries written before the invariant
302
+ remain readable and are marked `degraded: true` in `list()` /
303
+ `semanticSummaries()`; nothing is silently rewritten.
304
+
305
+ ### Added — working mode survives a handoff (same 1.5.6, no extra version bump)
306
+
307
+ - **Handoff marker carries the Host agent preset** (the UI's “工作模式”): the marker
308
+ written at rollover now records `agentPreset`, fed by the live adapter through
309
+ `memory.setHandoffPresetProvider()`.
310
+ - **A new conversation restores it before its first turn**: `agent/created` is a
311
+ serial Host event, so the bridge awaits `agentPresets.select(agent, preset)` for
312
+ `source === 'startup'` from a different session. `resume`, the marker-owner session
313
+ and markers without a preset are never overridden.
314
+ - **Never breaks agent creation**: a failed `select` is reported in
315
+ `runtime.lastPresetInherit` and the log, then creation proceeds.
316
+ - **Tracking**: `agent-preset/selected` updates the mode; tool boundaries and prompt
317
+ assembly opportunistically read `agents.currentInitiator()` + `agentPresets
318
+ .composedPreset()` and **backfill an older marker** that predates this feature.
319
+ - **Observability**: `/stats` exposes `agentPreset` + `presetInherit`, and
320
+ `hostStatus().presetSelections` counts observed selections.
321
+
322
+ ### Changed — physical split: multi-space engine moved out (same 1.5.6)
323
+
324
+ - **`src/spaces/spaceRouter.js` and `src/spaces/transfer.js` are GONE from this
325
+ package.** The full multi-space router (per-space FIFO chains, lazy child stores,
326
+ `MEM_E_*` validation) and the cross-space transfer engine now live in
327
+ `dsh-orchestrator` (`src/spaceRouter.js`, `src/transfer.js`).
328
+ - The core compiles only `src/spaces/singleSpace.js`: the `default` space is the
329
+ owner handle; every named-space operation answers **`MEM_E_FEATURE_DISABLED`** with
330
+ an explicit "install dsh-orchestrator" hint. No silent fallback to `default`.
331
+ - **Adapter injection is the wiring seam**: the Host's optional `orchestrator`
332
+ service supplies `createSpaceAdapter({owner, dataDir, openChild})` and `transfer`;
333
+ `Memory.open({spaces|spacesFactory, transfer})` accepts the same seam for embedders.
334
+ Without the service the plugin advertises `capabilities.spaces=false`, registers
335
+ only the eight single-space tools, and `/spaces` reports `default` only.
336
+ - A profile with `features.multiSpace:true` but no Orchestrator logs a loud warning
337
+ and runs the strict single-space core (visible in `/stats.capabilities`), instead
338
+ of pretending the capability exists.
339
+
340
+ ### Added — first batch: orchestrator service + 3 experience fixes (same 1.5.6)
341
+
342
+ - **Orchestrator service registration**: `apply()` now installs a real Host service
343
+ (`ctx.provide('orchestrator', …)` inside `ctx.effect`, so unloading removes it).
344
+ It exposes `createSpaceAdapter`, `transfer`, `dirFor`, `status`, `federation`,
345
+ `dedupe`, `consent` and `router`. The core decides the capability through
346
+ `config.multiSpaceActive(config, hasOrchestrator)`.
347
+ - **Reserved system tags isolated from display**: `status:*`, `folded-summary` and
348
+ `active_task` are filtered out of the knowledge graph (`buildGraph` + defensive
349
+ `view`) and the L1.5 tag tree (`rebuildTree` + persisted-tree/ghost filtering).
350
+ The inverted index still keeps them (handoff/recall internals need them).
351
+ - **`[Active Task]` injection**: prompt assembly prefers the active handoff summary,
352
+ otherwise the newest event carrying a `task:` tag, and renders it as an
353
+ unconditional top block (`[Active Task]`) once per session.
354
+ - **Fallback hints**: `selectRelevantTags` accepts `fallbackTags`; when the current
355
+ input has no lexical overlap (e.g. “继续”), the previous turn's matched tags (max 2)
356
+ are carried into `[Memory Hints]`.
357
+ - **Session-scoped injection dedup**: `runtime.injection` keeps per-session `ids` and
358
+ `tags`; hints, `[Active Task]` and recall blocks already injected are filtered on
359
+ later turns. SessionStart and rollover reset the pool, so the next session receives
360
+ the handoff content again.
361
+ - **Space deletion (UI + engine)**: `SpaceRouter.deleteSpace(id, {confirm})` closes
362
+ the child handle, evicts its queues/caches and removes the directory (refusing
363
+ `default` and requiring `confirm:true`). `Memory.deleteSpace` / `runtime.deleteSpace`
364
+ gate the same rules (named space only; `MEM_E_FEATURE_DISABLED` in the strict
365
+ single-space core). The HTTP route reuses `POST /spaces` with
366
+ `{action:'delete', space_id, confirm:true}`; an **unknown action is a 400** and
367
+ never falls through to CREATE. The SpaceSelector renders `🗑 删除空间` only for a
368
+ named space AND only when the new **`capabilities.spacesDelete`** handshake is
369
+ true — an old/pre-delete host therefore hides the button instead of answering the
370
+ misleading “空间已存在”. When `capabilities.spaces` is false the entire space UI
371
+ (selector, create/delete, current-space chip) disappears silently.
372
+
373
+ ### Added — local low-valley Dream scheduling (same 1.5.6)
374
+
375
+ - **No external price plugin required**: `src/priceWindow.js` computes Beijing-time
376
+ peak/valley locally (weekday 09–12 / 14–18 peak; lunch, nights and weekends low).
377
+ Chinese holidays are NOT modelled (the calendar moves yearly); `DSH_DREAM_PRICE=low|high`
378
+ or a Host price probe still override it.
379
+ - **The Host bridge gets a default probe** from `isLowValley()`, so a compensating
380
+ Dream skips peaks (`reason:'peak'`) and runs locally in the valley.
381
+ - **Idle LLM Dream defers instead of spending at peak**: `runtime.tick()` writes a
382
+ durable `state/dream-queue.json` (`pending, dueAt, reason:'peak-hour'`), emits
383
+ `dream-deferred`, and runs the queued Dream as soon as the valley opens — the queue
384
+ survives a restart, so a missed window is not lost.
385
+ - **Config `dream.onlyLowValley`** (default true; fail-fast, HTTP-editable, settings
386
+ toggle). A local-only Dream (no LLM) is never gated by price.
387
+ - `/stats` exposes `dreamWindow` (low/reason/nextLowAt), `dreamQueue` and `dreamTimer`.
388
+ - **Phase 2 — wake timer + sleep correction**: `src/dreamTimer.js` arms ONE wake-up
389
+ at the queued due time / next valley (injectable timers, `unref`ed). On fire it
390
+ re-reads the CLOCK and the WINDOW: a late wake after an OS sleep is reported
391
+ (`lateMs`, `catchUp`) and runs; a wake that lands in a peak re-arms for the next
392
+ valley instead of spending. Boot arms from the persisted queue, so a queue left by
393
+ a previous run catches up with delay 0. Disposal cancels the timer.
394
+ `dreamTimer` status (arms/wakes/lateWakes/reschedules/runs) is exposed on `/stats`.
395
+
396
+ ### Added — Federation / cross-space dedupe wiring (same 1.5.6)
397
+
398
+ - **Federation on write**: after a successful write the engine reports the record's
399
+ BUSINESS tags (never `status:*` / `month:*` / `active_task`) to the Orchestrator's
400
+ global `FederationMap` with the space id; a tag seen in two spaces becomes ONE
401
+ global node listing both. A missing/broken service can never fail the write.
402
+ - **Dedupe on monthly memos**: `generateMonthlyMemos()` claims `sha256(content)` in
403
+ the Orchestrator's `ContentRegistry` as `monthly:<spaceId>`; a sibling space with
404
+ the identical monthly workload skips its copy and reports
405
+ `monthly.skipped`/`skippedEntries` (owner traceable). Same-space reruns are
406
+ idempotent.
407
+ - Services arrive through the existing `orchestrator` adapter extras; spaces carry
408
+ their own `spaceId` (`path.basename(childDir)`), the default space is `default`.
409
+ - **Read-time merge on recall**: monthly memos now persist `meta.source_event_ids`,
410
+ and `projectEpisode` exposes `sourceEventIds`. `Memory.mergeRecallHits()` feeds the
411
+ recalled hits through `ContentRegistry.mergeForRead()`: a memo wins over the events
412
+ it owns, duplicate `contentHash` collapses monthly-first, and the payload reports
413
+ `merge: {space,monthly,droppedOwnedByMonthly,droppedDuplicateContent,total}`. Only
414
+ when the Orchestrator dedupe service is present; the pure core payload shape is
415
+ unchanged.
416
+ - **Cross-space recall aggregation**: `Memory.recallAcrossSpaces()` queries every open
417
+ space under its own lock, tags each hit with `spaceId`, and folds the union through
418
+ the same `mergeForRead()` (raw hits are requested with `mergeRecall:false` so the
419
+ aggregation sees owned events before the memo hides them). It is **opt-in**:
420
+ `features.crossSpaceRecall` defaults to **false**, is fail-fast (true without
421
+ multiSpace is a contradiction), HTTP-editable and rendered in the settings page.
422
+ Only when `crossSpaceRecall:true` does `runtime.recall()` use this path; otherwise
423
+ the single-space payload is unchanged (`mode` is never `cross-space`).
424
+ `mode:'cross-space'`, `spaces`, `merge` and per-hit `spaceId` are reported.
425
+
426
+ ### Tests
427
+
428
+ - New `test/v156.rawscan.test.js` (5 cases): newest-first + absolute line number
429
+ (5000-line shard), turn-budget truncation without reading the head, engine result
430
+ ceiling, `readLinesReverse` peak buffer ≤ chunk + one line over a 20k-line file,
431
+ and `restoreByHash` over the streaming path.
432
+ - New `test/v156.hardening.test.js` (5 cases): recall payload truncation and
433
+ under-budget pass-through, `maxInjectTokens` fail-fast, `close()` resource release
434
+ and idempotency, lag monitor yield after a 120ms block, maintenance `eventLoop`.
435
+ - New `test/v156.tagging.test.js` (7 cases): extraction matrix, untagged write gets
436
+ an anchor and becomes recallable, raw purity (four fields), manual tags win +
437
+ dedupe, miss warning + panel counter, `autoTag:false`, config fail-fast.
438
+ - New `test/v156.pinned.test.js` (3 cases): pinned without tags refused and no
439
+ write, one-year decay still `decay=1` + index/tag flags + pinned-first ranking,
440
+ pinned tag stays in the active set after a 400-day maintenance.
441
+ - New `test/v156.hints.test.js` (4 cases): selector matrix (match/unrelated/internal/
442
+ empty), hint rendering, prompt tail contains only matching tags after the block
443
+ marker with a stable prefix, `session/event` user turn tracking.
444
+ - New `test/v156.features.test.js` (5 cases): flag fail-fast + implied transfer-off,
445
+ strict single-space engine + capabilities/tools absent, transfer-only-off,
446
+ defaults unchanged, `Memory.open(string)` + lazy `warmup()`.
447
+ - New `test/v156.host.test.js` (6 cases): price normalisation; session start runs one
448
+ compensating Dream; unknown price + LLM skipped; peak skipped; not-due / disabled /
449
+ in-flight refused; MockHostEnvironment integration through `apply()` + `hostStatus`
450
+ surfaced on `/stats`; `dream.compensateAfterHours` fail-fast.
451
+ - New `test/v156.dreamui.test.js` (3 cases): safe Dream subset exposed / credentials
452
+ absent from the payload; tunables editable over HTTP while `dream.llm.*` is not;
453
+ settings page renders the section and offers no credential field.
454
+ - New `test/v156.l2merge.test.js` (4 cases): pinned/ordinary strict separation with
455
+ global-tag metadata preserved as meta (never a tag); a lone ordinary record is not
456
+ dragged into the pinned group; `maxSummaryChars` cap + `enabled:false`; config
457
+ fail-fast. Older fixtures disable `l2Merge` so their exact index-count assertions
458
+ stay deterministic.
459
+ - New `test/v156.l3tag.test.js` (4 cases): strict upsert refusal; delete-consolidation
460
+ derives `error:typeerror` / `origin:unlabelled-episode` instead of dead knowledge;
461
+ trend promotion derives tags before writing L3; historical untagged summaries are
462
+ readable but `degraded`.
463
+ - New `test/v156.preset.test.js` (6 cases): marker records the working mode; a new
464
+ conversation restores it through `agentPresets.select`; older markers are
465
+ backfilled from the live agent; resume / same-session / marker-without-preset never
466
+ override; a failed select does not fail creation; `agent-preset/selected` keeps the
467
+ tracked mode current.
468
+ - New `test/v156.singleSpace.test.js` (3 cases): the core works for `default` and
469
+ refuses named read/write/create/ensure/transfer; without the Orchestrator the plugin
470
+ advertises `spaces:false`, registers eight tools and never advertises a dead tool in
471
+ the prompt; injecting the adapter restores ten tools and `spaces:true`.
472
+ - Updated: manifest 1.5.5 → 1.5.6; settings page gains `context.maxInjectTokens`,
473
+ the pre-ingest tagging section, Dream tunables and the L2-merge section; editable
474
+ contract gains `tagging`, `features`, `dream` and `l2Merge`; panel contract gains
475
+ `global.pinned`, `autoTag` and `l2Merge`; `plugin.test` prompt contract now asserts
476
+ relevance hints instead of the removed global map.
477
+ - New `test/v156.firstBatch.test.js` (5 cases): reserved status tags never reach the
478
+ graph/tag tree; `[Active Task]` from the handoff summary and from a `task:` event;
479
+ fallback hints reuse the previous turn's tags; session dedup blocks the second
480
+ injection and resets on a new session.
481
+ - New `test/v156.spaceDelete.test.js` (5 cases): engine deletion with confirm/default/
482
+ missing rules; strict single-space refusal; **`capabilities.spacesDelete` versioned
483
+ handshake** (an old host hides the button, so a delete request can never be
484
+ misread as CREATE); `POST /spaces {action:'delete'}` removes the store and returns
485
+ the refreshed list; unknown actions answer 400 instead of falling through to
486
+ CREATE; the UI source carries the capability guard, the button, the human confirm
487
+ and the default-space guard.
488
+ - **Graph interaction layer** (`test/v156.graph.test.js`, 4 cases): Ctrl/Cmd+drag
489
+ pans the canvas (plain drag still moves a node), Ctrl/Cmd+wheel zooms around the
490
+ cursor via a non-passive native listener (plain wheel keeps page scroll),
491
+ double-click on blank space resets the view, and the frozen initial layout runs
492
+ through `separateOverlaps()` so nodes never start piled on top of each other.
493
+ The header/footer advertise the interaction.
494
+ - New `test/v156.lowValley.test.js` (4 cases): Beijing peak/valley boundaries and
495
+ next-low computation; `dream.onlyLowValley` fail-fast + editable; a peak-hour idle
496
+ Dream is deferred durably and runs at the valley; the Host bridge probe follows the
497
+ window while `DSH_DREAM_PRICE` remains an override.
498
+ - New `test/v156.federation.test.js` (2 cases): business tags federate into one
499
+ global node across spaces while internal tags are skipped; the first space claims a
500
+ cross-space monthly memo and the sibling reports `skipped` with the owner.
501
+ - New `test/v156.lowValley2.test.js` (4 cases): peak wake re-arms (never runs); a
502
+ sleep-delayed wake reports `lateMs`/`catchUp`; a past-due queue in the valley arms
503
+ delay 0; runtime integration: peak deferral -> timer fire -> queue cleared and
504
+ `dreamTimer.runs === 1`.
505
+ - New `test/v156.readMerge.test.js` (2 cases): a recalled monthly memo drops the
506
+ events it owns and reports merge stats; without the dedupe service the recall
507
+ payload is unchanged.
508
+ - New `test/v156.crossSpaceRecall.test.js` (2 cases): a recall returns hits from every
509
+ open space with provenance; a monthly memo hides its owned event even when recorder
510
+ in another space, while the other space still contributes.
511
+ - New `test/v156.crossSpaceRecallFlag.test.js` (3 cases): default false + fail-fast
512
+ (`true` without multiSpace is a contradiction, non-boolean rejected); flag true
513
+ aggregates open spaces; flag false keeps the single-space payload.
514
+ - **Settings-page GitHub installer**: new `POST /api/hippocampus/orchestrator/install`
515
+ (requires `{confirm:true}`) delegates to the Host's
516
+ `pluginManager.installBundle('git+https://github.com/382quaii/dsh-Layers-Orchestrator.git', {enabled:true})`,
517
+ short-circuits when the service is already present, and reports
518
+ `applied | restart-required | manual | failed`. The settings page ships a
519
+ “从 GitHub 安装 dsh-orchestrator” button (human confirm dialog) plus the repo link;
520
+ without `pluginManager` it shows the exact manual steps instead of failing silently.
521
+ - **Automatic new conversation on handoff (verified feasible)**: the Host exposes
522
+ `agents.create/resume` and, decisively, the CLIENT service
523
+ `uiWorkspace.startSession()` — the same action the “+” button uses. A client-half
524
+ controller polls `/stats`, and when `handoff.active && handoff.autoNewSession` it
525
+ calls `uiWorkspace.startSession(undefined, {agentPreset})` once per handoff marker
526
+ (sessionStorage guard, lifecycle-owned interval, capability-guarded no-op on old
527
+ hosts). New config `context.autoNewSession` (default **true**, fail-fast,
528
+ HTTP-editable, settings toggle), plus `context.autoNewSessionPoll`
529
+ (`interval` | `once`, default `interval`) and
530
+ `context.autoNewSessionIntervalSeconds` (5–3600, default 15): the settings page
531
+ now exposes a “按间隔轮询 / 只检查一次” select and an interval slider; the client
532
+ configures its timer from the FIRST stats response (`once` clears the recurring
533
+ timer). The workspace-file handoff scheme is no longer needed and stays documented
534
+ only as a fallback.
535
+ - **Fixed — new-conversation failure `tool "subagent" is already registered`**:
536
+ handoff preset inheritance no longer calls `agentPresets.select()` when the new
537
+ session is ALREADY composed with the marker's preset. A redundant recompose
538
+ re-mounted the preset's `@deepseek-ai/dsh-tool-subagent` row and aborted session
539
+ creation; the skip is recorded as `presetInherit.reason='already-composed'` and
540
+ locked by a regression test in `test/v156.preset.test.js`.
541
+ - **Persona section + generic custom decay (v1.5.7)**:
542
+ - `[Persona & Traits]` is its own prompt section (`name:'persona'`, **order 100**),
543
+ rendering the ≤10 highest-confidence L3 semantic summaries (live store read, not
544
+ the recall cache). The memory block/policy/reflection sections keep 2450/2455/2460.
545
+ - `service.remember()` accepts **`customDecayRate`** (finite, 0 < rate ≤ 10) OR
546
+ **`customHalfLifeDays`** (integer 1–36500), never both. The value is normalised to
547
+ `meta.decay_rate`, projected as `decayRate`, and applied as
548
+ `effectiveHalfLife = policyHalfLife / decayRate` for THAT record only. No
549
+ tag-prefix logic exists anywhere in the engine — an emotion plugin decides the
550
+ semantics by passing the parameter.
551
+ - **Cross-plugin `ctx.provide('hippocampus', service)`** (user decision 2026-11-05:
552
+ in-process service only, NO HTTP write surface): `apiVersion=1`, `ready()`,
553
+ `capabilities()` (declares `l3Traits:10` plus per-method support), `remember()`
554
+ (L2-only; non-L2 layers are redirected with a warning; returns
555
+ `{status,eventId,eventTime,duplicate}`), `recall()`, `runMaintenance(source)`
556
+ (never queues: a running pass answers `MEM_E_MAINTENANCE_RUNNING`; manual passes
557
+ are rate-limited to 30 s while `cron` bypasses), `stats()/handoffView()/
558
+ promptState()` read-only snapshots and `onDispose()` hooks. The service disappears
559
+ with its plugin fiber; later calls answer `MEM_E_SERVICE_DISPOSED`. New codes
560
+ `MEM_E_MAINTENANCE_RUNNING`, `MEM_E_SERVICE_DISPOSED`, `MEM_E_FEDERATION_FAILED`
561
+ are registered append-only (8 cases in `test/v157.service.test.js`).
562
+ - **Durable Orchestrator state**: `<root>/state/orchestrator.json` now persists the
563
+ global federation map and the monthly-memo claims (atomic tmp+rename on every
564
+ mutation); it is loaded before the services become observable, and a corrupt file
565
+ is treated as empty instead of failing activation — a restart no longer forgets
566
+ cross-space dedupe.
567
+ - Full suite: **411 tests / 411 pass / 0 fail**, 64 test files. Orchestrator:
568
+ **31/31** (`service` + `spaces` deletion + `persistence` round-trip/corrupt state).
569
+ **Installed locally**: desktop profile gets a `link:` dependency + an ordered patch
570
+ insert BEFORE the hippocampus entries, so the service exists at activation. Two
571
+ Cordis constraints were fixed on the way: `apply()` must return **undefined**
572
+ (the return value is treated as an effect → `TypeError: Invalid effect`), and the
573
+ service is registered directly with `ctx.provide` (itself an effect). The market
574
+ catalog still does **not** list it: that needs an npm publish / catalog submission.
575
+ - Added `docs/RELEASE-1.5.6.md`: release notes + the exact push/tag/npm/market
576
+ commands that require the operator's credentials (none executed here).
577
+
578
+ ## [1.5.5] — 2026-11-03
579
+
580
+ **Offline Dream distillation: an optional LLM pass that can never take Dream down.**
581
+ Same-tag L2 records are distilled into one durable, provenance-carrying record.
582
+ The LLM leg uses **Node's built-in `fetch` only** (charter v2.0 #1: still zero
583
+ dependencies); endpoint / model / key are injected through config or
584
+ `DSH_DREAM_LLM_*` env and are never hard-coded, logged, or returned by HTTP.
585
+ Every failure — no config, network down, timeout, non-JSON — silently degrades to
586
+ the deterministic local merge and records `MEM_E_DREAM_LLM_FALLBACK`. **303 tests
587
+ green** (was 295).
588
+
589
+ ### Added — Dream LLM distillation (`src/dream.js`, `Memory.executeDream`)
590
+
591
+ - **Structured output**: the model must answer JSON `{"summary","confidence"}`;
592
+ `summary` is capped at `dream.maxSummaryChars` (default 200). Fenced code,
593
+ non-JSON, missing fields and over-long summaries are all treated as LLM failure.
594
+ - **Zero-dependency transport**: Node's global `fetch` against an
595
+ OpenAI-compatible `/chat/completions`; `Authorization: Bearer` only when a key is
596
+ configured. No SDK, no `node-fetch`, no new `package.json` dependency (test-locked).
597
+ - **Absolute timeout**: `AbortController` + `Promise.race` under
598
+ `dream.llmTimeoutMs` (default 15s); the timer is always cleared in `finally`.
599
+ - **Local fallback**: earliest/latest time + deduplicated core text, capped to
600
+ `maxSummaryChars`. Degradation warns `MEM_E_DREAM_LLM_FALLBACK` and is visible in
601
+ `status().panel.dream.lastFallback`.
602
+ - **Provenance**: the distilled record always carries
603
+ `meta.source_event_ids` (deduped, sorted) and `meta.distilled_by` (`llm|local`);
604
+ a re-run never merges the same source twice (`state/dream.json` bookkeeping).
605
+ - **Circuit breaker**: `failureThreshold` (default 3) consecutive failures open the
606
+ breaker for `cooldownMinutes` (default 60); afterwards a half-open state allows
607
+ exactly one probe — success closes it, failure re-opens. Exposed as
608
+ `panel.dream.circuit`.
609
+ - **Single-flight + serial**: a concurrent `executeDream()` is refused
610
+ (`dream-in-flight`); within one run groups are processed strictly serially, so a
611
+ slow provider can never exhaust connections or accumulate queued work.
612
+ - **Offline only**: `executeDream()` is called exclusively from the `dream` branch
613
+ of the maintenance gate, after `maintain()` converged; the online
614
+ `recall`/`remember` paths never touch the network.
615
+
616
+ ### Config
617
+
618
+ - New `dream` group (fail-fast validated): `useLlm`, `minGroupSize` (2–50),
619
+ `maxGroupsPerRun` (1–50), `maxSummaryChars` (40–2000), `maxSourceChars`
620
+ (80–4000), `maxEventsPerGroup` (2–50), `llmTimeoutMs` (500–120000),
621
+ `failureThreshold` (1–20), `cooldownMinutes` (1–1440), and
622
+ `llm.{baseUrl,model,apiKey}`. The `llm` block is deliberately **not** part of the
623
+ UI/HTTP config projection, so a credential can never leak through the panel.
624
+
625
+ ### Tests
626
+
627
+ - New `test/v155.dream.test.js` (8 cases): no-config local fallback with full
628
+ provenance; LLM success (URL/header/body/JSON parse); non-JSON degradation;
629
+ fetch timeout degradation; single-flight refusal; circuit open → no fetch →
630
+ half-open single probe → close; `dream` config fail-fast matrix; `package.json`
631
+ dependency red line.
632
+ - Updated: status-panel contract gains `dream`; manifest 1.5.4 → 1.5.5.
633
+ - Full suite: **303 tests / 303 pass / 0 fail**, 41 test files.
634
+
635
+ ## [1.5.4] — 2026-11-02
636
+
637
+ **Hotfix: the automatic handoff state machine can no longer wedge a session, and
638
+ recursive handoff summaries are cut off at the source.** Incident: recursive
639
+ `交接摘要` generations inflated the ratio past the native window and a handoff that
640
+ failed could leave the machine stuck, blocking new sessions. **295 tests green**
641
+ (was 286).
642
+
643
+ ### Fixed — state machine (no deadlock, Fail-Fast with graceful degradation)
644
+
645
+ - **`checkHandoff()` never rejects**: a distillation error, a timeout (default 5s,
646
+ injectable per call) or a marker-write failure degrade to a `state:"failed"`
647
+ marker carrying `summaryError` and return immediately. The next session starts
648
+ regardless.
649
+ - **New-session transition resets everything**: `observeSessionTokens()` always
650
+ establishes the new session's own baseline, consumes a marker belonging to a
651
+ different session, and **releases `_handoffInFlight`**, so a hung handoff guard
652
+ can never own the next session. A same-key restart (estimate halved after reset)
653
+ is treated as a new baseline too.
654
+ - **Stale marker consumption happens before early returns**, so a fresh session
655
+ cannot inherit "handoff active" forever.
656
+ - **Outer watchdog in `_maybeAutoHandoff()`** in addition to the inner one: even if
657
+ `checkHandoff` itself hangs, the in-flight flag is released in `finally`.
658
+
659
+ ### Fixed — recursion
660
+
661
+ - **`_distillHandoffTail()` refuses handoff content** by tag (`status:handoff`) and
662
+ by the `交接摘要` text prefix, in both the live-context path and the indexed
663
+ fallback. Output is hard-capped at 1200 characters; the idempotency key includes
664
+ the timestamp so distinct epochs never collide. (No more summary-of-summary.)
665
+ - **`status:handoff` is internal**: 2% weight in normal recall and excluded from the
666
+ recent-memory list, so real facts always outrank handoff bookkeeping.
667
+
668
+ ### Added — escape hatches and cleanup
669
+
670
+ - **`Memory.resetSessionState()` / `memory_admin action=reset_session` /
671
+ `POST /api/hippocampus/session/reset` / settings-page 「强制重置交接状态(逃生舱)」**:
672
+ clears the live token baseline, the in-flight guard and the active marker. It
673
+ rewrites only `state/`; durable memories are untouched.
674
+ - **`Memory.repairHandoffSummaries()` + `scripts/repair-handoff.mjs`
675
+ (`npm run repair-handoff`)**: finds recursive/excess handoff generations
676
+ (recursive = >=2 `交接摘要` markers) and parks them in the two-phase
677
+ `pending_delete` queue. Dry-run by default; `--reset-marker` consumes a stuck
678
+ marker.
679
+ - Panel session status now exposes `handoffState` / `handoffDegraded` /
680
+ `handoffErrorCode`; a degraded handoff is visible in the status bar instead of
681
+ silently locking.
682
+ - New error code **`MEM_E_HANDOFF_FAILED`**.
683
+
684
+ ### Tests
685
+
686
+ - New `test/v156.handoff.test.js` (9 tests): recursion refused by tag/prefix and
687
+ fallback path; throwing/hanging distillation degrades without rejecting; new
688
+ session resets ratio and releases the stuck guard; handoff summary ranking and
689
+ list isolation; `resetSessionState` preserves memories; repair dry-run + pending
690
+ delete; admin tool + HTTP escape hatch (route table 8).
691
+ - Route contract 7 → 8, manifest 1.5.4.
692
+ - Full suite: **295 tests / 295 pass / 0 fail**, 40 test files.
693
+
694
+ ## [1.5.3] — 2026-11-02
695
+
696
+ **Hotfix: space creation no longer exposes a raw `MEM_E_SPACES: HTTP 404`, and
697
+ invalid/conflicting space names are rejected by the ENGINE with
698
+ `MEM_E_SPACE_INVALID`.** Incident: a new client bundle called
699
+ `/api/hippocampus/spaces` against a host process that predated the route (the same
700
+ process also 404s `/memories`). Fixed on three layers plus a route-drift test.
701
+ **286 tests green** (was 270).
702
+
703
+ ### Added — release hygiene
704
+
705
+ - **Benchmark Protocol v1 (`scripts/bench-protocol.mjs`, `npm run bench`)**: the only
706
+ sanctioned way to publish a throughput number. Each measured run gets a fresh
707
+ `os.tmpdir()` store, one discarded same-process warmup precedes 5 measured runs,
708
+ and the report carries MEDIAN + min/max/spread. It makes no speed assertions
709
+ (a shared/AV-scanned machine must report, not fail), so single-run noise cannot
710
+ become an architecture conclusion again. Replaces the deleted single-run
711
+ `scripts/confidence-ab.mjs`.
712
+ - **Multi-space fixed-overhead coverage (`test/v154.release.test.js`)**: N=10
713
+ physical spaces — bounded per-space boot (<500ms median), lazy root boot
714
+ (`spaces.open=[]`, children never eagerly opened), uniform per-space storage
715
+ (max/min ≤1.35), linear total bytes (≤1.3×N), per-space fixed overhead <256KB.
716
+ - **Dead config removal**: `context.minInjectConfidence` is gone end-to-end
717
+ (default/validation/projection, HTTP-editable key,
718
+ `applyConfidence`/`MIN_INJECT_CONFIDENCE` retrieval pass, recall
719
+ `confidence`/`lowConfidence` annotations and low-confidence notes, obsolete A/B
720
+ script). Supplying the old key fails fast with `MEM_E_CONFIG_UNKNOWN_KEY`
721
+ (`details.removedIn = "1.5.3"`), so a profile cannot keep believing it works.
722
+ - Test watchdog default 30s → 60s (the in-process suite boots real stores/spaces and
723
+ legitimately takes ~15–25s; the watchdog now only fires on real hangs).
724
+
725
+ ### Added — tool schema pruning
726
+
727
+ - **`tools.disabled` config (default `[]`)**: every registered tool definition costs its
728
+ JSON schema in prompt tokens on EVERY turn (~1.1–1.2k tokens of baseline tax). A
729
+ closed suffix vocabulary (`remember/checkpoint/recall/capture/bulk_ingest/reinforce/forget/space_transfer/transfer_to_global/admin`)
730
+ lets an operator prune low-frequency tools; `remember`/`recall`/`admin` are CORE
731
+ and cannot be disabled. A typo/prefix/full name, a core tool, or a duplicate aborts
732
+ config resolution with **`MEM_E_INVALID_TOOL_NAME`** (fail-fast, never silently
733
+ ignored). The register wrapper skips disabled suffixes AND the `memory` prompt
734
+ section stops advertising them, so the schema prune cannot lie to the model.
735
+ Editable over HTTP (`tools.disabled`) and rendered in the settings page as a
736
+ checkbox catalog with core-不可关闭 / low-frequency tooltips. Takes effect on the
737
+ next host start/reload (tool registration happens at activation).
738
+
739
+ ### Fixed
740
+
741
+ - **Route-drift lock**: a new test parses the client `API` constant table and
742
+ proves every path equals the backend `MEMORY_API` value verbatim, and that the
743
+ registered route table contains them all. Adding a route on one side without the
744
+ other now fails CI instead of 404-ing in production.
745
+ - **Capability handshake**: `/stats` (ready AND booting) and `GET /spaces` now carry
746
+ `capabilities: { version, spaces, memories, transferConsent, multiSpace }`.
747
+ The client checks `capabilities.spaces` BEFORE calling `POST /spaces`; if the
748
+ host is older it shows a version hint and disables the action instead of firing a
749
+ request that 404s. `memories` is gated the same way (old host → "当前宿主版本不
750
+ 支持记忆列表", not `MEM_E_MEMORIES`).
751
+ - **Human error copy**: every space-create failure now renders a complete sentence.
752
+ 404 / route-missing / network → `创建失败:底层引擎未响应,请检查版本或联系架构师`;
753
+ invalid name → `创建失败:空间名称无效——需以小写字母/数字开头,只能含 a-z 0-9 . _ -(最长 64)`;
754
+ duplicate → `创建失败:空间「33」已存在,请换一个名称`; reserved → `创建失败:该名称是
755
+ 系统保留名,请换一个`. The `MEM_E_SPACES: HTTP 404` template is gone from the bundle.
756
+ - **`MEM_E_SPACE_INVALID` (400)**: `validateNewSpaceId` + `Memory.createSpace` reject,
757
+ before any directory/JSONL write: empty/whitespace, wrong charset (`Bad`, `bad id!`,
758
+ path separators, `..`, `.`), >64 chars, trailing dot (Windows alias), Windows
759
+ device names (`con`, `nul`, `com1`, …), `default` (always exists), an existing
760
+ space (conflict), and a non-directory path collision. Creation returns `201`,
761
+ conflicts/invalid ids `400 MEM_E_SPACE_INVALID`.
762
+ - Fresh spaces are created from `POST /spaces` with a strict non-idempotent
763
+ `runtime.createSpace`; the lazy `ensureSpace` used by transfer keeps its
764
+ idempotent semantics.
765
+
766
+ ### Tests
767
+
768
+ - New `test/v153.spaces.test.js` (7 tests): client↔backend route-path equality
769
+ (the anti-404 lock), a real dispatch through the CLIENT path against the
770
+ registered host route table (handler answers 201, never a router 404),
771
+ invalid/reserved matrix, engine conflict-before-write, HTTP 201/400 + capability
772
+ handshake, human-copy mapper (no raw 404), capability gating for old hosts.
773
+ - Updated: `POST /spaces` assertions 200 → 201 strict creation; manifest 1.5.3.
774
+ - Full suite: **286 tests / 286 pass / 0 fail**, 39 test files (includes
775
+ `v154.release.test.js`).
776
+ - **Note (deployment)**: the live host process observed during the incident still
777
+ 404s `/spaces` and `/memories` — it must be restarted/reloaded for the new routes
778
+ to serve; until then the new client degrades with the version hint above instead
779
+ of a naked 404.
780
+
781
+ ## [1.5.2] — 2026-11-02
782
+
783
+ **Architecture correction: physical storage migration vs. business-data transfer
784
+ are now physically decoupled, and the UI has a real global SpaceSelector.** The
785
+ v1.5.0/v1.5.1 UI mixed two unrelated concerns and let the user type
786
+ `target_space_id`/`event_ids` by hand. Fixed and locked by tests. **270 tests
787
+ green** (was 263).
788
+
789
+ ### Changed — UI (module decoupling)
790
+
791
+ - **Physical dataDir migration extracted** into `StorageMigratorUI`, a SYSTEM/DATA
792
+ MANAGEMENT section at the bottom of the settings page. It owns only the A/B
793
+ double-buffer state machine: `POST { dataDir }` → `202 state=migrating` → copy →
794
+ verify → swap, old directory kept as a backup. No event ids, no spaces.
795
+ - **Business cross-space transfer removed from the settings form**: the manual
796
+ `event_ids` / `target_space_id` text inputs, the copy/cut buttons and the
797
+ inline confirmation are gone. Business transfer now exists ONLY in the panel's
798
+ regulated flow (below).
799
+ - **Global `SpaceSelector`** in the panel header: a dropdown of the physical spaces
800
+ (friendly labels: 默认空间 / 工作空间 / 私人空间 / 全局空间, unknown ids verbatim)
801
+ with `+ 新建空间` (creates an EMPTY space — never a copy). The selection is
802
+ app-global (`spaceStore` + `space-changed` bus event), so the panel and the
803
+ settings page follow it.
804
+ - **Every UI read follows the selected space**: `useMemoryStats`, `useGraph` and
805
+ `useRecentMemories` append `?space=<id>`; the backend routes `stats`, `graph` and
806
+ `memories` to that physical store. Memory list, graph, L1 log/index counts, L2.5
807
+ quarantine, L3 semantic count, L1.5 tag tree and the session status bar are all
808
+ that space's only — switching spaces cannot blend views or contexts.
809
+ - **Regulated cross-space flow (UI_TASK_3)**: check memories in the current space →
810
+ `移动到…` → dialog step 1 states `即将向 [目标空间] 发起迁移请求` → step 2 is the
811
+ SECOND explicit consent (`二次确认 · 安全红线`, with the cut warning when 剪切) →
812
+ only then is `user_approved: true` sent. Target is a dropdown of known spaces,
813
+ never a free-text id.
814
+ - `h(StorageMigratorUI)` is a separate component, so the two state machines can no
815
+ longer share draft state or validation.
816
+
817
+ ### Added — backend routing
818
+
819
+ - **`GET/POST /api/hippocampus/spaces`**: list the router's spaces / create an empty
820
+ one (`space_id`). The selector and `+ 新建空间` use it.
821
+ - **`?space=<id>` on `/api/hippocampus/stats` and `/api/hippocampus/graph`**:
822
+ `runtime.uiPayload(spaceId)` / `runtime.graphPayload(spaceId)` return that space's
823
+ panel/graph via `Memory.status({ targetSpaceId })` and
824
+ `Memory.graphForSpace({ targetSpaceId })`; a new space reports zeros (empty), so a
825
+ switched view is never a fallback to the default store.
826
+ - `Memory.ensureSpace()` (root router) and `runtime.spaceList()`.
827
+ - Panel status `panel.spaces.current` now reports the SELECTED space (was always
828
+ `default`), and `stats`/`graph` responses carry a top-level `spaceId`.
829
+
830
+ ### Security (unchanged red line, stricter transport)
831
+
832
+ - The HTTP transfer route no longer fabricates consent: it forwards
833
+ `user_approved` from the request and the ENGINE gate rejects a request that lacks
834
+ it with `MEM_E_REQUIRE_USER_CONSENT`. The UI only sets the flag after step 2. An
835
+ agent tool call and a raw POST that "bypasses the UI" therefore hit the same
836
+ wall.
837
+ - `dataDir` migration Fail-Fast strengthened: `validateMigrationPaths` now also
838
+ rejects an existing non-empty target (`MEM_E_MIGRATION_TARGET_BUSY`) and a
839
+ non-directory target (`MEM_E_MIGRATION_PATH`) synchronously, before a 202/job.
840
+ The old store remains authoritative on any rejection.
841
+
842
+ ### Tests
843
+
844
+ - New `test/v152.refactor.test.js` (7 tests): dataDir validation matrix
845
+ (missing/relative/same/inside/root/non-empty/non-dir) + `startMigration`
846
+ fail-fast with the old dir intact; space isolation for stats/graph/memories/
847
+ session/recall with `?space=`; `ensureSpace` empty space + spaces route;
848
+ unauthorized transfer blocked at engine AND HTTP, authorized passes; UI wiring
849
+ (SpaceSelector header mount, checkbox flow, no manual inputs, isolated
850
+ StorageMigratorUI).
851
+ - Updated contract assertions: HTTP routes 6 → 7 (spaces), transfer route requires
852
+ explicit `user_approved`, settings order now context → space/session → system
853
+ storage, cut second-confirmation now lives in the panel dialog, manifest 1.5.2.
854
+ - Full suite: **270 tests, 270 pass, 0 fail**.
855
+
856
+ ## [1.5.1] — 2026-11-02
857
+
858
+ **Security patch: cross-space transfer now requires EXPLICIT user consent.** Moving
859
+ memories between spaces is a data-egress action, not a memory optimisation. Two
860
+ independent locks (prompt + engine), plus a human-only UI path. **263 tests green**
861
+ (was 254).
862
+
863
+ ### Added
864
+
865
+ - **Prompt red line (`memory:policy`)**: a static `【🚨最高安全红线】` block forbids
866
+ the model from calling `memory_space_transfer` / `memory_transfer_to_global` on
867
+ its own judgement, sympathy, or "better cross-device sharing". The only allowed
868
+ trigger is a direct user command in the current conversation; when unsure the
869
+ model must ask `您需要我把这条信息同步到其他空间吗?`. It also documents the
870
+ `user_approved: true` retry protocol for `MEM_E_REQUIRE_USER_CONSENT` and states
871
+ that the intercept is never a one-off obstacle to bypass.
872
+ - **`memory_transfer_to_global` tool**: copy/move memories from a space into the
873
+ canonical `global` space, with the same privacy screen, raw_turn stripping, fresh
874
+ target ids and consent gate as `memory_space_transfer`. Both tool schemas expose
875
+ `user_approved` and their descriptions carry the security warning.
876
+ - **`context.requireExplicitConsentForTransfer`** (default **true**, validated
877
+ boolean, HTTP-editable and exposed in the settings page): the operator's master
878
+ switch for the engine gate. The settings toggle explains the risk.
879
+ - **`GET /api/hippocampus/memories`** (`limit`, `space`): bounded recent-memory
880
+ projection (`eventId`, `day`, `tags`, `snippet`) used by the panel's per-memory
881
+ detail rows. `Memory.recentMemories()` is read-only and index-snapshot based.
882
+ - **UI per-memory 分享/转移 button**: the panel now lists the 20 most recent
883
+ memories with a human-initiated transfer dialog (target space, copy/cut toggle,
884
+ second confirmation for cut). It calls the transfer route directly — **bypassing
885
+ the model entirely** — and the browser request is the consenting human.
886
+
887
+ ### Fixed / Security
888
+
889
+ - `Memory.transferEvents()` now throws
890
+ **`MEM_E_REQUIRE_USER_CONSENT`** with the fixed message
891
+ `[系统拦截] 跨空间传递需要用户明确授权。请向用户确认后再试。` when
892
+ `context.requireExplicitConsentForTransfer` is true and the call does not carry
893
+ `userApproved === true`. The gate runs **before** space ids are validated, before
894
+ any store is opened, before content is read and before any pending-delete record
895
+ is written, so a refused call is provably side-effect free.
896
+ - `POST /api/hippocampus/transfer` is documented and implemented as the **human
897
+ channel**: it marks `userApproved: true` itself (same-origin authenticated
898
+ browser request). The agent half cannot reach HTTP routes, so a UI click needs no
899
+ model involvement and a model call still hits the gate.
900
+ - The consent gate is strict: `userApproved` must be the boolean `true`; the
901
+ config value must be a boolean (a string like `"yes"` fails fast).
902
+
903
+ ### Tests
904
+
905
+ - New `test/v151.consent.test.js` (9 tests): default-on config + fail-fast type
906
+ check; engine gate fires before validation/IO (invalid target still answers
907
+ CONSENT, nothing parked, source untouched); agent tool blocked then succeeds only
908
+ with `user_approved: true`; `memory_transfer_to_global` same contract; explicit
909
+ config opt-out; engine-level facade contract; prompt red-line markers; HTTP route
910
+ marks consent; UI 分享/转移 + direct-API contract.
911
+ - Intentional contract growth updates: tools 9 → 10, HTTP routes 5 → 6, v150 UI
912
+ route/transfer assertions extended with `userApproved`, manifest 1.5.1.
913
+ - Full suite: **263 tests, 263 pass, 0 fail**.
914
+
915
+ ## [1.5.0] — 2026-11-02
916
+
917
+ Tag-explosion defence, physical multi-space routing, session handoff and the
918
+ cross-space transfer API. The plugin stays deliberately permission-free: the
919
+ complex permission choreography belongs to the future Orchestrator plugin, while
920
+ this engine owns only physical memory. **253 tests green** (was 200).
921
+
922
+ ### Added — module 1: tag-explosion defence (P0)
923
+
924
+ - **`index.maxPostingsPerTag` (default 500, 1–100000)**: derives the inverted index
925
+ with a hard physical cap per tag. When a tag exceeds it, the retained pointers are
926
+ chosen by `salience desc -> eventTime desc -> eventId asc` and re-sorted for
927
+ retrieval (`eventTime desc`, then id). `eventCount`, `mass` and `lastSeen` are
928
+ still aggregated over **all** events, so the counts the degradation layer reports
929
+ are honest; only the in-memory posting pointers are dropped (the JSONL log is
930
+ untouched and rebuildable). Tags expose `postingsLimit` / `postingsTruncated` /
931
+ `postingsDropped`; index stats expose `postingsTruncated` / `postingsDropped`.
932
+ - **Recall degradation for oversized tags**: an EXPLICIT query tag holding more than
933
+ 50 memories (`TAG_OVERFLOW_THRESHOLD`) is not expanded into the candidate pool.
934
+ The response carries `oversizedTagHints: [{ tag, total, code:
935
+ 'MEM_E_TAG_OVERFLOW', hint: '[系统提示] 发现关于 [tag] 的记忆共 N 条,数据量过大。
936
+ 请提供更精确的 startTime/endTime 或使用 deep_raw 查阅。', window }]` and the
937
+ course-block fallback is suppressed so the flood cannot re-enter through the back
938
+ door. If the caller insists (a second recall on the same tag), only the **3 most
939
+ recent** summaries are returned (`oversizedRecent: true`,
940
+ `oversized-tag-recent:3`). Graph neighbours of an oversized tag are never woken.
941
+ - **`deep_raw` super-tag gate**: a query touching a tag with more than 500
942
+ associations (`SUPER_TAG_THRESHOLD`) without `start_time`/`end_time` now throws
943
+ **`MEM_E_TIME_RANGE_REQUIRED`** (narrow queries keep the old
944
+ `MEM_E_INVALID_INPUT` contract). One authority decides: the tool no longer
945
+ pre-validates the window.
946
+
947
+ ### Added — module 2: multi-space routing & session handoff (physical layer)
948
+
949
+ - **Config** `context.autoSpaceFollow` (false), `context.autoRolloverEnabled`
950
+ (true), `context.autoRolloverThreshold` (0.85, 0.5–0.99),
951
+ `context.nativeTokenLimit` (8000, 512–1000000) — validated fail-fast, editable
952
+ over HTTP and in the UI.
953
+ - **`SpaceRouter`** (`src/spaces/spaceRouter.js`): `targetSpaceId` on
954
+ `remember`/`recall` routes to an isolated physical store
955
+ (`<dataDir>/spaces/<id>`, `default` = the existing store, so every old path is
956
+ byte-identical). One FIFO promise chain **per space**: same-space operations are
957
+ serialised, different spaces run concurrently (a single global lock would
958
+ reintroduce the cross-space stalls spaces exist to remove). Ids become directory
959
+ names, so `^[a-z0-9][a-z0-9._-]{0,63}$` is enforced and a typo fails with
960
+ `MEM_E_INVALID_INPUT` instead of silently writing into the default space.
961
+ `runMany` acquires in sorted order (no ABBA deadlock).
962
+ - **Qwen native fidelity**: `ContextEngine.nativeState()` reports
963
+ `mode: 'native' | 'layered'`; below `nativeTokenLimit` nothing is folded (folding
964
+ is a layered-mode operation), above it the L1.5 layered fold runs. The legacy
965
+ `maxTokens` paging threshold is untouched.
966
+ - **Automatic handoff (转生)**: when the session reaches
967
+ `autoRolloverThreshold x nativeTokenLimit`, the tail is distilled into ONE durable
968
+ L1.5 summary (`status:handoff`), `state/handoff.json` is marked active and the
969
+ `memory-state` prompt appends `[交接标记] … 本插件不能保证一个会话永生不死,只能
970
+ 保证人格不死。`. A new session consumes the marker. Handoffs are idempotent (one
971
+ summary per handoff) and self-trigger from the `session/event` stream and from
972
+ tool boundaries. With `autoRolloverEnabled: false` no marker is written and
973
+ ContextEngine force-evicts at 95% (`reason: 'native-force'`, down to
974
+ `target x nativeTokenLimit`).
975
+ - **Panel/status**: `panel.session` (`mode`, `tokens`, `nativeTokenLimit`,
976
+ `threshold`, `remainingTokens`, `rolloverEnabled`, `handoffActive`, …) and
977
+ `panel.spaces` (`current`, `ids`, `open`) are part of the UI contract.
978
+
979
+ ### Added — module 3: atomic cross-space transfer
980
+
981
+ - **`memory_space_transfer` tool** (`event_ids`, `target_space_id`,
982
+ `transfer_mode: 'copy' | 'move'` default copy, optional `source_space_id`) and
983
+ `Memory.transferEvents()`.
984
+ - **Safety rails enforced by the engine, not the caller**: privacy screening aborts
985
+ the whole batch with **`MEM_E_PRIVACY_BLOCKED`** (ID cards, CN phones, bank cards,
986
+ emails, credential assignments, PEM private keys; matched bytes never leave the
987
+ scanner) before any write; `raw_turn` / `rawTurn` / `raw_*` pointers are stripped
988
+ from meta at every depth; the TARGET space regenerates `event_id`s
989
+ (`dedupe:false`, never reuses the source identity) and tags copies
990
+ `transferred:from:<source>` + `transferred:to:<target>`.
991
+ - **State difference**: `copy` leaves the source untouched (`state: 'retained'`);
992
+ `move` parks the source ids in the **two-phase pending_delete queue**
993
+ (`state: 'pending_delete'`, `dueAt`, cancellable with `restore`) only after every
994
+ target write succeeded — never a direct physical delete, and a partial target
995
+ failure leaves the source untouched.
996
+ - **HTTP**: `POST /api/hippocampus/transfer` (same-origin, validated body) for the
997
+ UI migration button.
998
+
999
+ ### Added — module 4: UI
1000
+
1001
+ - **Space panel**: soft-follow toggle (`context.autoSpaceFollow`), auto-rollover
1002
+ toggle, trigger-ratio slider, native-window field, single-tag index cap control,
1003
+ and a live status bar: `[当前: 原生模式 | 剩余 X Tokens 触发交接]` (also
1004
+ `分层折叠` / `已交接` variants).
1005
+ - **Migration interaction**: copy/cut (复制/剪切) toggle next to the transfer button;
1006
+ choosing 剪切 requires a **second confirmation warning** before any request is
1007
+ sent.
1008
+ - **Philosophy footer** (bold, bottom of the settings page): **本插件不能保证一个
1009
+ 会话永生不死,只能保证人格不死。**
1010
+ - **Subtraction**: the tag search box uses the host-native Enter key only — no
1011
+ debounce, no timer, no effect. `filterGraphByQuery` is pure and testable; the
1012
+ force layout is not re-run by filtering.
1013
+
1014
+ ### Changed
1015
+
1016
+ - `uiConfig` exposes `index`; `Memory.applyLiveConfig()` projects a validated config
1017
+ onto the facade **and every open child space**, including the context engine's
1018
+ native/rollover overrides.
1019
+ - `Memory` opens child spaces lazily with the same policy input; `close()` closes
1020
+ children first; a child failure never blocks the rest.
1021
+ - The `memory-state` prompt only gains the handoff block when a marker is active,
1022
+ so the cache-stable prefix is unchanged in the common case.
1023
+
1024
+ ### Tests
1025
+
1026
+ - New files: `v150.index.test.js` (truncation/degradation/super-tag gate),
1027
+ `v150.space.test.js` (per-space concurrency, native boundary, forced eviction),
1028
+ `v150.transfer.test.js` (copy/move state difference, privacy, raw_turn strip,
1029
+ fresh ids), `v150.ui.test.js` (bundle contract, helpers, no debounce, footer,
1030
+ transfer route), `v150.lifecycle.test.js` (Qwen mode, threshold handoff, marker
1031
+ consumption, `targetSpaceId` isolation, ninth tool surface),
1032
+ `v150.config.test.js` (new groups, ranges, HTTP editability).
1033
+ - Intentional contract updates in old tests: 8 -> 9 tools, 4 -> 5 routes,
1034
+ `panel.session`/`panel.spaces` added to the panel snapshot, manifest 1.5.0.
1035
+ - Full suite: **253 tests, 253 pass, 0 fail** (old 200 cases included unchanged).
1036
+
1037
+ ## [1.4.3] — 2026-11-02
1038
+
1039
+ Two measured blockers from the 2026-11-02 handoff, both fixed and locked by tests.
1040
+
1041
+ ### Added
1042
+
1043
+ - **`raw.maxScanTurns` config (500–50000, default 5000)**: `deep_raw`'s scan budget
1044
+ was a hidden constant and is now a validated, UI-editable knob (`raw.maxScanTurns`).
1045
+ - **`stage()` / `commitMany()`**: remember is now a `stage -> commitMany` composition.
1046
+ `stage()` validates and builds a record (identity + idempotency, no log/index I/O);
1047
+ `commitMany()` performs ONE durable append, ONE ledger checkpoint and ONE index
1048
+ delta for a whole batch. `bulkIngest` uses it, so a 50-item chunk is one write
1049
+ instead of 50.
1050
+ - **`memory-state` prompt is now composed** via `composePrompt`: stable rules →
1051
+ `[Memory Map]` (active tags + counts) → `[Memory Blocks]` (the only per-turn
1052
+ volatile tail). The old single-line `briefing()` is no longer the prompt body
1053
+ (it changed on every write and broke the prefix cache). Full-chain tests lock the
1054
+ prefix to be byte-identical before/after a recall injects a block.
1055
+ - **`scripts/confidence-ab.mjs`**: local A/B benchmark for `context.minInjectConfidence`
1056
+ (100 noise + 10/3 relevant; characters, hits, low-confidence hints, mis-degraded
1057
+ relevant memories). Run it with `node scripts/confidence-ab.mjs`.
1058
+ - **Crash-restart test**: kills the process inside the 200ms checkpoint window
1059
+ (cancelled timer, no `close()`), reopens the same directory, and asserts the fresh
1060
+ instance reports `stale` (`unflushed-bytes`), rebuilds the index and can recall the
1061
+ unflushed tail.
1062
+
1063
+ ### Fixed
1064
+
1065
+ - **`injectRecall()` crashed on any L3 semantic hit**: it used `summary.id` while
1066
+ `rankSemantic()` returns `summaryId`, so a recall with a distilled summary and
1067
+ `context.injectPrompt` failed with `MEM_E_IO: ContextEngine.inject requires an id`.
1068
+ Now it uses `summaryId ?? id` and skips invalid summaries. Found by the new
1069
+ prompt/tag-tree full-chain test.
1070
+ - `logStore.status()` now exposes `unflushedBytes` (shard size minus manifest bytes)
1071
+ so an unclean shutdown cannot hide the uncheckpointed tail behind equal counters.
1072
+
1073
+ ### Changed
1074
+
1075
+ - **`deep_raw` scans NEWEST-FIRST** (per shard, tail to head). The old head-first
1076
+ scan burned its whole budget on the oldest 5000 turns of a day file — in a 10k
1077
+ shard the newest turn could never be found. A hit beyond the window now returns
1078
+ `truncated: true` with a note instead of pretending the turn does not exist.
1079
+ - **Buffered log append**: the hot path keeps one append handle without fsync +
1080
+ manifest rewrite per record. A 200ms checkpoint (and `close()`, and any
1081
+ rewrite/compaction) fsyncs and publishes the manifest; `status().unflushedBytes`
1082
+ plus the boot check make a mid-burst crash visible as stale instead of silently
1083
+ "up to date".
1084
+ - **Identity ledger checkpoint is debounced** (500ms / `close()`): it is a derived
1085
+ startup hint rebuilt from the log, so rewriting it per append was pure O(n²) cost.
1086
+ - **Index appends are lazy**: `applyRecords` records the delta and marks the view
1087
+ dirty; the next `snapshot()` folds it once. N writes cost one index build, and
1088
+ read-your-writes still holds because the fold happens on the read path.
1089
+ - **Briefing is dirty-driven**: a write marks the prompt-state line stale; the next
1090
+ `briefing()` / panel poll rebuilds it once instead of every append.
1091
+
1092
+ ### Measured
1093
+
1094
+ - Sequential `memory.remember` x1000: **119/s -> 9104/s** (8.4s -> 110ms).
1095
+ - 10,000-line raw shard, newest query: **0 hits -> 1 hit** (`deep_raw` now starts at
1096
+ the tail; hash restore and redaction regression-guarded).
1097
+ - **`deep_raw` tail-scan bias documented**: beyond `raw.maxScanTurns` (default 5000)
1098
+ per shard, only the newest N turns are covered; older history needs a larger budget
1099
+ or time-window pagination (`end_time` moved backwards). `truncated: true` + notes
1100
+ always say so.
1101
+ - **Confidence A/B (measured)**: `minInjectConfidence=0.6` cuts the tool payload by
1102
+ **49.7%** (10 relevant / 100 noise) and **75.8%** (3 relevant / 100 noise), with
1103
+ **0 relevant hits mis-degraded**; the prompt window only shrinks when the top-8
1104
+ contains noise (0% vs 59.7% in the two scenarios), so the honest claim is
1105
+ "long-tail payload + anti-hallucination", not "always fewer prompt tokens".
1106
+ - 197 tests green (was 189); after the prompt/tag-tree full-chain wiring and the
1107
+ crash-restart test: **200**.
1108
+
1109
+ ## [1.4.2] — 2026-11-01
1110
+
1111
+ ### Added
1112
+
1113
+ - **L1.5 标签层级树**: hierarchical tags (`tech/frontend/vue3`) now have a
1114
+ three-level lifecycle — immortal roots, leaves that die when their reference
1115
+ count reaches zero, and mids that enter a grace window when they lose their last
1116
+ child. A mid inside that window is a **ghost**: it can be revived by a new leaf,
1117
+ and it is what the UI's history view shows. The tree is a **derived cache**
1118
+ (`state/tag-tree.json`) built by `maintain()` from the converged index; the
1119
+ previous cache is carried forward (`refCount = 0`, orphans dropped) so the
1120
+ lifecycle is observable across maintenance runs. Deleting the file loses only
1121
+ ghost history.
1122
+ - **Bounded prune queue**: dead leaves are queued and consumed one
1123
+ `tagTree.pruneBatchSize` batch per maintenance run; the remaining queue is
1124
+ persisted in the same atomic write, so a 10k-leaf storm drains across runs
1125
+ instead of causing a maintenance storm.
1126
+ - **Anti-hallucination recall degradation**: a `memory_recall` hit reached only
1127
+ through a fading mid is **removed from `hits` entirely** (body, snippet and score
1128
+ never reach the model or the prompt window) and replaced by one metadata hint per
1129
+ mid: path, count, remaining grace days and the exact `deep_raw` time window. A
1130
+ query that names a fading mid with no live episode returns a `count: 0` hint
1131
+ instead of silence.
1132
+ - **`panel.tagTree`**: node/root/mid/leaf/ghost/queue counts for the Web panel, and
1133
+ `GET /api/hippocampus/graph` now returns `tagTree.ghosts` in the same response as
1134
+ the cached graph.
1135
+ - **UI**: `tagTree.*` sliders with numeric boxes and hover tooltips in the settings
1136
+ section; ghost nodes rendered in the force graph as translucent dashed circles
1137
+ hanging under their parent root, with a `仅活跃 / 历史全貌` toggle that cross-fades
1138
+ them via CSS opacity (the force layout does not re-run when toggling).
1139
+ - **Config `tagTree` group** (fail-fast, editable over HTTP and in the UI):
1140
+ `midHalfLifeMultiplier` (1–10), `midGracePeriodDays` (7–180),
1141
+ `pruneBatchSize` (10–500), `leafDecayFloor` (0–1). `midHalfLifeMultiplier` is the
1142
+ only source of the mid half-life — no silent hard-coded lifetime.
1143
+
1144
+ ### Changed
1145
+
1146
+ - `maintain()` now rebuilds/prunes/persists the tag tree after the index
1147
+ generation converges; a tag-tree failure is reported as `report.tagTreeError`
1148
+ and can never fail maintenance or block recall.
1149
+ - `applyConfig` now projects the validated config onto the running `Memory` facade,
1150
+ so live UI edits (raw limits, tagTree lifetimes, …) actually reach the running
1151
+ objects instead of waiting for a reload.
1152
+ - `pruneBatch` re-derives decay against the pass's `now` (a frozen build-time score
1153
+ made grace windows meaningless), rejects `O(mids × nodes)` rescans, and keeps
1154
+ parent child counts truthful when a mid dies.
1155
+
1156
+ ## [1.4.1] — 2026-11-01
1157
+
1158
+ ### Added
1159
+
1160
+ - **Prompt discipline (soft interception)**: a static `memory:policy` section tells
1161
+ the model to prefer `memory_recall` for history/files/system facts, and to treat
1162
+ a `[Slimmed]` response as an invitation to answer from the summary unless the
1163
+ `recovery_hash` must be dereferenced.
1164
+ - **Own-tool output slimming**: `memory_recall`/`memory_admin` responses over the
1165
+ budget (default 2000 tokens) are captured to raw first, then returned as
1166
+ `{slimmed, summary, topics, key_entities, recovery_hash, hint}`; the hint points
1167
+ at `memory_recall(mode="deep_raw", hash=…)`, which restores the exact payload.
1168
+ - **Retrieval confidence**: hits below `context.minInjectConfidence` (default 0.6)
1169
+ carry a short hint instead of their full body, plus a `low-confidence-hints:N` note.
1170
+ - **Write flood guard**: writes above 80% of `storageBudgetMb` throw
1171
+ `MEM_E_WRITE_FLOOD`; `memory.bulkIngest` chunks 50 items per await and ships as
1172
+ `memory_bulk_ingest`.
1173
+ - **raw.captureRatio** (0 | 0.5 | 1): deterministic sampling by content hash;
1174
+ ratio 0 disables capture and `deep_raw` returns an explicit warning.
1175
+
1176
+ ### Changed
1177
+
1178
+ - `memory_recall` gains `hash` (exact raw restore) and confidence fields; deep_raw
1179
+ results honour the token budget before returning.
1180
+ - `promptLayout` composes stable rules → memory map → `[Memory Blocks]` tail.
1181
+
1182
+ ## [1.4.0] — 2026-10-31
1183
+
1184
+ ### Added
1185
+
1186
+ - **Raw-turn forensics (`memory_capture`, `memory_recall mode:"deep_raw"`)**: a
1187
+ separate day-sharded JSONL store (`raw/`) that is never indexed, never loaded at
1188
+ boot, and never touched by normal recall. Gated by `raw.mode` (default
1189
+ `salience`: high-salience, code, stack traces, tool output, or `force`), deduped
1190
+ by content hash, secret-redacted, and capped by `maxTurnKb` (head+tail
1191
+ truncation), `maxBytesPerDay`, `maxTotalMb`, and `retentionDays` (pruned by
1192
+ maintenance; code shards keep 90 days). `deep_raw` scans newest→oldest under a
1193
+ byte/turn budget and reports `truncated: true` instead of pretending it saw
1194
+ everything.
1195
+ - **Spaced repetition**: engine-owned schedule (`1,2,4,7,15,30` days) persisted in
1196
+ `state/reviews.json`; `maintain()` reconciles due items and `reinforce` advances
1197
+ the step. Exposed as `memory_admin action="reviews"`.
1198
+ - **Two-phase delete**: `forget` parks the event for `delete.graceHours`
1199
+ (default 24) in `pending_deletes`; `restore` cancels it, and `maintain()`
1200
+ promotes expired requests into the 4-phase pipeline. Unknown ids now fail
1201
+ immediately, before parking.
1202
+ - **UI data-dir migration**: `dataDir` is editable in the settings page. Saving it
1203
+ takes `.migration.lock`, returns HTTP 202 with `state=migrating`, copies with
1204
+ `fs.promises.cp` in the background, verifies `recordCount` on both sides, and
1205
+ only then switches and reloads the store. A mismatch removes the target and
1206
+ keeps the old store authoritative; the source is never deleted.
1207
+ - New config groups: `raw.*`, `delete.graceHours`, `review.enabled`,
1208
+ `migration.timeoutMs` (all fail-fast validators, UI tooltips included).
1209
+ - **Raw-turn black box (minimal schema)**: each line is exactly
1210
+ `{turn_id, timestamp, role, content}` — no tags, salience, decay, event ids,
1211
+ graph links, session ids or metadata. Addressing is by `(day file, line number)`;
1212
+ append-only keeps lines stable (the one lawful line-pointer exception).
1213
+ Writes are queued and flushed in batches (10 records / 1s), never sync.
1214
+ - **Read-side redaction**: the shard keeps 100% plaintext (forensic integrity);
1215
+ secrets are redacted when `deep_raw` returns snippets, before any text reaches a
1216
+ model prompt. README states local storage is plaintext.
1217
+ - **Tombstones**: a committed purge appends `raw_tombstone {hash, timestamp}`;
1218
+ scans skip tombstoned content hashes (no resurrection).
1219
+ - **deep_raw constraints**: `start_time` and `end_time` are mandatory (missing →
1220
+ `MEM_E_INVALID_INPUT`), results are capped by `raw.maxResultTokens` (default
1221
+ 1000) and carry the truncation notice when cut.
1222
+ - **TTL**: maintenance deletes whole day files strictly older than
1223
+ `today - raw.retentionDays`; today's shard is never touched. Raw bytes are
1224
+ surfaced as `panel.storage.rawBytes` and counted in the dashboard ring.
1225
+ - **Automatic raw capture**: the plugin subscribes to `dsh-session`'s
1226
+ `session/event` and stores every user/assistant surface message verbatim
1227
+ (`raw.autoCapture: true`). The Host-injected `Current runtime context.` block is
1228
+ stripped out of `content` and kept (truncated) in `metadata.runtimeContext`, so
1229
+ `deep_raw` stays signal-clean. Tool output is opt-in (`raw.captureTools: false`),
1230
+ **except failed tool results** (`isError`), which are always captured as
1231
+ `kind: "error"`. Budgets, dedupe and retention still apply.
1232
+
1233
+ ### Changed
1234
+
1235
+ - Panel adds `raw`, `reviews`, and `pendingDeletes`; the settings page renders a
1236
+ migration progress card while `state=migrating`.
1237
+ - `Memory._scheduler` cron now reads `runtime.config` per tick, so a hot config
1238
+ update changes the schedule without a restart.
1239
+
1240
+ ## [1.3.1] — 2026-10-30
1241
+
1242
+ ### Fixed
1243
+
1244
+ - **Cold-start 404 (root cause)**: `webServer` is provided by the web-app row, which
1245
+ activates *after* this plugin's `apply()`. The old code called
1246
+ `ctx.get('webServer')` once and silently skipped registration when it was
1247
+ absent — every cold start had no routes, while a warm reload worked. Route
1248
+ registration now lives in `ctx.inject(['webServer'], child => …)`, so the child
1249
+ fiber activates the moment the service appears and the routes are always
1250
+ mounted. Verified live (404 → 200) and covered by a deferred-inject test.
1251
+ - **Front-end death spiral**: a bodiless 404 used to be synthesized into a JSON
1252
+ error, which the old retry counter treated as a protocol failure and gave up
1253
+ after six attempts. `getJson` now keeps "no JSON" distinct, and the pure
1254
+ `decideRetry` policy retries bodiless 404s with exponential backoff (capped at
1255
+ 5s) for up to 10 minutes before surfacing `MEM_E_BOOT_TIMEOUT` with a manual
1256
+ reconnect button.
1257
+ - **Diagnostics**: `apply()` prints `[Hippocampus] Route registered at <iso>
1258
+ (<paths>) phase=<phase>` when the routes are mounted, and
1259
+ `[Hippocampus] Route registration FAILED: <reason>` if the service never
1260
+ provides one.
1261
+
1262
+ ## [1.3.0] — 2026-10-30
1263
+
1264
+ ### Added
1265
+
1266
+ - **Context folding (推币机)**: blocks evicted from the context window are no longer
1267
+ dropped. A light rule folds the most recent batch into one `folded_summary`
1268
+ episode tagged `status:folded` — extracting names, task statements and core
1269
+ conclusions — and writes it back to the L1 log.
1270
+ - **Graph association (在线联想)**: when a query touches a tag, retrieval reads the
1271
+ cached graph and pulls that tag's three strongest neighbours into the candidate
1272
+ pool with an explicit `penalty: 0.5`; such hits are marked `association.via` and
1273
+ can never outrank a direct hit.
1274
+ - **Monthly memos (月记)**: `maintain()` condenses a finished natural month into one
1275
+ `status:monthly` episode. Memos do not decay (`decay = 1`) and are pulled in
1276
+ first for fuzzy historical queries ("上个月", "2023-10", "去年" …).
1277
+
1278
+ ### Changed
1279
+
1280
+ - HTTP routes are now registered **before** tools, prompts and scheduling inside
1281
+ `apply()`, so a page that wins the boot race hits a live handler answering
1282
+ `state=pending` instead of a 404. The Host-side assumption is documented in the
1283
+ code: `apply()` awaits nothing, and route service is expected once it returns.
1284
+
1285
+ ## [1.2.0] — 2026-10-30
1286
+
1287
+ ### Added
1288
+
1289
+ - **`memory_checkpoint`** (`task_id`, `progress`, `updated_at`): exactly one active
1290
+ heavy task. A new checkpoint demotes the previous one, one not refreshed for
1291
+ seven days is demoted by `maintain()`, and `memory_admin action="active_task"`
1292
+ reads it straight from the index — the active-set cap of 200 does not apply.
1293
+ - **Multimodal pointers**: `memory_remember` accepts `media_url` (absolute path or
1294
+ http(s) URL) plus `media_type` (`image|video|document|audio`). Inline base64 in
1295
+ `content` is rejected with `MEM_E_INVALID_MEDIA` from 256 consecutive base64
1296
+ characters; 200 characters is still ordinary text.
1297
+ - **`decay.halfLifeDays`** (default 30, 7–365) and **`activeSet.cap`** (default 200,
1298
+ 100–1000): both declared in `DEFAULT_CONFIG`, validated fail-fast by
1299
+ `resolveConfig`, projected into `policy`, and editable from the settings page.
1300
+ - **State handshake**: every route response now carries `state`
1301
+ (`pending|in_progress|ready|failed`), and the UI retries on `state` rather than
1302
+ on the HTTP status. A bodiless 404 during boot is treated as `pending` for a
1303
+ 120s grace window (the routes are only mounted once the Host runs `apply()`).
1304
+
1305
+ ### Changed
1306
+
1307
+ - Writes before READY are refused loudly: `POST /api/hippocampus/config` answers
1308
+ `409` with `MEM_E_NOT_READY` and the current state; tools already answered
1309
+ `MEM_E_NOT_READY`, and their error details now include `state` and `retryable`.
1310
+ - The settings page covers the full editable surface (18 keys), with the documented
1311
+ hints for `storageBudgetMb`, `context.maxTokens`, `decay.halfLifeDays` and
1312
+ `activeSet.cap`; saving before READY is disabled in the UI and rejected by the API.
1313
+
1314
+ ## [1.1.0] — 2026-10-29
1315
+
1316
+ ### Added
1317
+
1318
+ - **Graph dragging**: nodes are movable with pointer events. The dragged node is
1319
+ pinned for the duration, coordinates are mutated in a ref and painted straight
1320
+ to the DOM (no `setState` per frame), and release unpins it and runs a short
1321
+ alpha relaxation over its 1-hop neighbourhood. A pointer travel under 4px is
1322
+ still a click, so selecting a label can never move the node by accident.
1323
+ - **`storageBudgetMb`** (integer, default 50, range 10–1000): the storage ring's
1324
+ budget is now configurable instead of hard-coded, and the ring recomputes the
1325
+ moment the value is saved.
1326
+ - **Full settings UI**: every editable config key is in the settings section —
1327
+ switches for booleans, bounded number inputs, a select for
1328
+ `identity.eventTimePolicy`, and a text field for the maintenance cron. Saving
1329
+ posts one dotted-path patch through the same fail-fast validator as startup;
1330
+ a rejected value shows a red banner with the `MEM_E_CONFIG_*` code and nothing
1331
+ is applied. A successful save broadcasts `config-changed` so the panel
1332
+ refetches stats and graph immediately.
1333
+
1334
+ ### Fixed
1335
+
1336
+ - Dotted config paths deeper than one level (`identity.eventTimePolicy`,
1337
+ `retrieval.topK`) now nest correctly instead of producing a literal key.
1338
+
1339
+ ## [1.0.0] — 2026-10-29
1340
+
1341
+ First public release. The package was previously developed under the working
1342
+ names `@local/dsh-memory` / `Layers-Hippocampus`; the data directory is
1343
+ unchanged and legacy folders are migrated automatically.
1344
+
1345
+ ### Added
1346
+
1347
+ - **Layers**: append-only event log, rebuildable tag index (A/B generations),
1348
+ day diaries, independent semantic layer, L2.5 trend quarantine with promotion
1349
+ and burst detection.
1350
+ - **Identity discipline**: canonical `content_hash`, `event_id =
1351
+ hash(content_hash + event_time + occurrence_index)`, separate idempotency
1352
+ index, tombstones that survive log compaction.
1353
+ - **Context paging**: token budget, eviction thresholds, cumulative saved-token
1354
+ accounting persisted in `state/context.json`.
1355
+ - **Maintenance**: one gate for cron and Dream (`runtime.runMaintenance`), no
1356
+ queueing and no backfill; a missed window is skipped, not replayed.
1357
+ - **Config fail-fast**: `enableDream`, `dreamIdleMinutes`, `enableReflection`,
1358
+ `graphMaxEdges` (100–2000, default 500), cron, context and temp ranges are
1359
+ validated by `resolveConfig`; HTTP hot updates go through the same validator.
1360
+ - **Async startup state machine** `pending → in_progress → ready | failed`, with
1361
+ `POST /api/hippocampus/retry` and a UI retry banner.
1362
+ - **Offline knowledge graph**: built at the end of `maintain()` from the index
1363
+ (log minus tombstones), per-node Top-N neighbours, global weight order, cached
1364
+ at `state/graph.json`, hard cap 2000 edges.
1365
+ - **Web UI**: sidebar icon, main panel (SVG storage ring, stats, force-directed
1366
+ graph with progressive reveal), and a settings section.
1367
+ - **HTTP API** (same-origin, behind the Host's browser auth):
1368
+ `GET /api/hippocampus/stats`, `GET|POST /api/hippocampus/config`,
1369
+ `GET /api/hippocampus/graph`, `POST /api/hippocampus/retry`.
1370
+ - **Tests**: 106 in-process cases (Node `node:test`) covering identity,
1371
+ retrieval, L2.5, maintenance, migration, routes, graph and the client bundle
1372
+ contract.
1373
+
1374
+ ### Security
1375
+
1376
+ - The UI never receives credentials and never calls agent tools; every number is
1377
+ read through the Host's authenticated JSON routes.
1378
+ - The graph route returns at most `graphMaxEdges` edges from a cached file — no
1379
+ query language, no path input.
1380
+
1381
+ [1.0.0]: https://github.com/382quaii/dsh-Layers-Hippocampus/releases/tag/v1.0.0