dsh-layers-hippocampus 1.6.2 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/config.js CHANGED
@@ -70,7 +70,19 @@ export const TOOL_SUFFIXES = Object.freeze([
70
70
  export const CORE_TOOL_SUFFIXES = Object.freeze(['remember', 'recall', 'admin']);
71
71
 
72
72
  /** Every accepted top-level key (nested groups are validated separately). */
73
+ /**
74
+ * Schema version of the CONFIG OBJECT itself (not of the plugin).
75
+ *
76
+ * v1.6.3: introduced after the 1.6.2 incident — a profile written for an older
77
+ * schema (no `archiveAfterDays`) was validated against NEW defaults and threw
78
+ * MEM_E_CONFIG_OUT_OF_RANGE before the plugin could even register its routes.
79
+ * From now on the loader MIGRATES first and validates second.
80
+ */
81
+ export const CONFIG_SCHEMA_VERSION = 3;
82
+
73
83
  export const CONFIG_KEYS = Object.freeze([
84
+ 'configVersion',
85
+ 'strictStartup',
74
86
  'dataDir',
75
87
  'migrateFrom',
76
88
  'maintenanceCron',
@@ -129,6 +141,12 @@ export function defaultDataDir(env = process.env) {
129
141
  export const DEFAULT_CONFIG = Object.freeze({
130
142
  dataDir: null, // resolved below: <DSH_HOME>/memory
131
143
  migrateFrom: null,
144
+ // v1.6.3: schema version of the config object itself (see CONFIG_SCHEMA_VERSION).
145
+ configVersion: CONFIG_SCHEMA_VERSION,
146
+ // v1.6.3 startup safety net. `true` (default) = fail fast on a bad value;
147
+ // `false` = degrade to the safe default and keep the plugin registered, because
148
+ // a boot abort leaves every /api/hippocampus/* route missing (1.6.2 incident).
149
+ strictStartup: true,
132
150
  maintenanceCron: '0 */6 * * *',
133
151
  toolPrefix: 'memory',
134
152
  briefing: true,
@@ -180,19 +198,18 @@ export const DEFAULT_CONFIG = Object.freeze({
180
198
  threshold: 0.85,
181
199
  target: 0.7,
182
200
  injectPrompt: true,
183
- // v1.5.6: when a handoff becomes active the CLIENT half asks the Host client
184
- // service `uiWorkspace.startSession()` to open a fresh conversation (opt-out).
185
- autoNewSession: true,
186
- // v1.5.6: how the client half decides a new conversation is due. `interval`
187
- // polls /stats every `autoNewSessionIntervalSeconds`; `once` checks only once
188
- // per page load (no recurring traffic).
189
- autoNewSessionPoll: 'interval',
190
- autoNewSessionIntervalSeconds: 15,
201
+ // v1.6.3 REMOVED: `autoNewSession` / `autoNewSessionPoll` /
202
+ // `autoNewSessionIntervalSeconds`. Handing off is an in-conversation event; the
203
+ // host now CONTINUES the same conversation after the marker instead of opening a
204
+ // second one, so a client-side "start a fresh session" controller only spawned a
205
+ // useless empty conversation. Legacy keys are stripped by `migrateConfig`.
191
206
  // v1.6.0 cold-start injection switches (user request 2026-11-06):
192
- // - summary: inject the previous handoff/L3 summary so the first turn inherits context
193
- // - recentTurns: inject the last few verbatim-ish episodes (costs more start tokens)
207
+ // - summary: inject the previous handoff summary so the first turn inherits context
208
+ // - recentTurns: inject the last few turns of the handed-off conversation
209
+ // - recentTurns: inject the last few turns of the handed-off conversation
210
+ // (v1.6.3 default ON: a new conversation must not start "blind")
194
211
  coldStartInjectSummary: true,
195
- coldStartInjectRecentTurns: false,
212
+ coldStartInjectRecentTurns: true,
196
213
  // REMOVED in v1.5.3: `minInjectConfidence`. It never demonstrably saved tokens
197
214
  // (0.6 vs 0 produced byte-identical payloads) and every hit-shaping pass is a
198
215
  // permanent token tax; keeping a misleading knob is worse than having none.
@@ -255,7 +272,20 @@ export const DEFAULT_CONFIG = Object.freeze({
255
272
  // Two-phase delete: forget parks the event for this long before the pipeline runs.
256
273
  delete: Object.freeze({ graceHours: 24 }),
257
274
  // Spaced repetition schedule (days between reviews).
258
- review: Object.freeze({ enabled: true, intervals: [1, 2, 4, 7, 15, 30] }),
275
+ // v1.6.3: `autoConsume` makes maintenance actually CONSUME the due queue instead
276
+ // of only reporting it. Without it a fresh install accumulated hundreds of
277
+ // "due" rows that nobody ever cleared (every `lastAt` stayed null), so the queue
278
+ // grew monotonically and pinned decay anchors at creation time forever.
279
+ review: Object.freeze({
280
+ enabled: true,
281
+ intervals: [1, 2, 4, 7, 15, 30],
282
+ autoConsume: true,
283
+ // Bounded work per maintenance pass: batch size is the setImmediate yield point,
284
+ // maxPerRun is the total budget (a huge backlog drains over several passes
285
+ // instead of blocking one).
286
+ consumeBatchSize: 40,
287
+ consumeMaxPerRun: 200,
288
+ }),
259
289
  migration: Object.freeze({ timeoutMs: 600_000 }),
260
290
  // L1.5 lifecycle knobs are user-facing on purpose (charter v3.0): no silent
261
291
  // hard-coded half-lives. leafDecayFloor 0 keeps the strict forget-driven mode.
@@ -486,14 +516,175 @@ export function multiSpaceActive(config, hasOrchestrator) {
486
516
  return hasOrchestrator === true && config?.features?.multiSpace !== false;
487
517
  }
488
518
 
519
+ /**
520
+ * Migrate a config object from any older schema to the current one.
521
+ *
522
+ * This runs BEFORE `normaliseRaw`/strict validation on purpose: it is the only
523
+ * place allowed to invent values, and every invention is reported (warn + the
524
+ * returned `warnings` array). It never throws — an unknown/missing version is
525
+ * treated as "oldest", because refusing to boot is exactly the bug we are fixing.
526
+ *
527
+ * @param {object} raw caller/config-file values
528
+ * @param {{logger?: object}} [opts]
529
+ * @returns {{input: object, warnings: string[], migrated: boolean, fromVersion: number}}
530
+ */
531
+ export function migrateConfig(raw, { logger = console } = {}) {
532
+ if (!isPlainObject(raw)) return { input: raw, warnings: [], migrated: false, fromVersion: CONFIG_SCHEMA_VERSION };
533
+ const warnings = [];
534
+ const input = { ...raw };
535
+ // An EMPTY config carries no legacy shape: it is simply "use the defaults".
536
+ // Treating it as current keeps `resolveConfig({})` silent instead of warning on
537
+ // every internal call that has nothing to migrate.
538
+ const isEmpty = Object.keys(raw).length === 0;
539
+ const fromVersion = isEmpty
540
+ ? CONFIG_SCHEMA_VERSION
541
+ : Number.isInteger(raw.configVersion)
542
+ ? raw.configVersion
543
+ : 0;
544
+ let migrated = false;
545
+
546
+ const warn = (message) => {
547
+ warnings.push(message);
548
+ try {
549
+ logger?.warn?.(`hippocampus/config-migration: ${message}`);
550
+ } catch {
551
+ /* a broken logger must never block a boot */
552
+ }
553
+ };
554
+
555
+ if (fromVersion < CONFIG_SCHEMA_VERSION) {
556
+ input.configVersion = CONFIG_SCHEMA_VERSION;
557
+ if (fromVersion === 0) {
558
+ warn(`config.configVersion was missing; treated as legacy schema and migrated to ${CONFIG_SCHEMA_VERSION}`);
559
+ } else {
560
+ warn(`config.configVersion ${fromVersion} -> ${CONFIG_SCHEMA_VERSION}`);
561
+ }
562
+ migrated = true;
563
+ }
564
+
565
+ // The exact 1.6.2 breakage: `retentionDays` pinned by an old profile, while
566
+ // `archiveAfterDays` did not exist yet and its new default (90) exceeded it.
567
+ const rawGroup = isPlainObject(input.raw) ? { ...input.raw } : null;
568
+ if (rawGroup && rawGroup.archiveAfterDays === undefined) {
569
+ const retention = Number.isInteger(rawGroup.retentionDays) ? rawGroup.retentionDays : null;
570
+ if (retention !== null && retention <= DEFAULT_CONFIG.raw.archiveAfterDays) {
571
+ const derived = Math.max(1, retention - 1);
572
+ rawGroup.archiveAfterDays = derived;
573
+ input.raw = rawGroup;
574
+ warn(
575
+ `config.raw.archiveAfterDays was missing and retentionDays=${retention} is not above the new default ${DEFAULT_CONFIG.raw.archiveAfterDays}; derived archiveAfterDays=${derived}. Set raw.archiveAfterDays explicitly to silence this.`,
576
+ );
577
+ migrated = true;
578
+ }
579
+ }
580
+
581
+ // v1.6.3: the client-side "open a new conversation on handoff" controller is gone
582
+ // (a handoff now continues the SAME conversation). Strip the three legacy keys so a
583
+ // profile written by an older HA does not keep advertising a knob that no longer
584
+ // exists — otherwise the settings page would render a switch that does nothing.
585
+ const REMOVED_CONTEXT_KEYS = ['autoNewSession', 'autoNewSessionPoll', 'autoNewSessionIntervalSeconds'];
586
+ if (isPlainObject(input.context)) {
587
+ const legacy = REMOVED_CONTEXT_KEYS.filter((key) => input.context[key] !== undefined);
588
+ if (legacy.length > 0) {
589
+ const contextGroup = { ...input.context };
590
+ for (const key of legacy) delete contextGroup[key];
591
+ input.context = contextGroup;
592
+ warn(
593
+ `config.context.${legacy.join('/')} removed in 1.6.3 (a handoff continues the same conversation); the key(s) were dropped.`,
594
+ );
595
+ migrated = true;
596
+ }
597
+ }
598
+
599
+ // `strictStartup` did not exist before 1.6.3; default it explicitly so the
600
+ // resolved config always states the behaviour it will use.
601
+ if (input.strictStartup === undefined) {
602
+ input.strictStartup = DEFAULT_CONFIG.strictStartup;
603
+ }
604
+
605
+ return { input, warnings, migrated, fromVersion };
606
+ }
607
+
489
608
  /**
490
609
  * Validate and resolve. Throws `MemoryError` with a `MEM_E_CONFIG_*` code; never
491
610
  * clamps, never defaults a bad value.
492
611
  *
612
+ * v1.6.3 startup safety net: when `strictStartup: false`, an out-of-range value
613
+ * degrades to the safe default instead of aborting activation (the 1.6.2 incident
614
+ * left the whole plugin unregistered, so the UI polled 404 forever). The strict
615
+ * path remains the default and the ONLY path when `strictStartup` is unset/true.
616
+ *
493
617
  * @param {object} [raw] caller/config-file values
494
618
  * @param {{env?: object}} [opts]
495
619
  */
496
620
  export function resolveConfig(raw = {}, { env = process.env } = {}) {
621
+ const migration = migrateConfig(raw);
622
+ const input = migration.input;
623
+ const strictStartup = input?.strictStartup !== false;
624
+
625
+ try {
626
+ return attachConfigMeta(buildResolvedConfig(input, { env }), migration);
627
+ } catch (error) {
628
+ if (strictStartup || error?.code !== ErrorCodes.CONFIG_OUT_OF_RANGE) throw error;
629
+ // Degraded boot: drop the offending key (details.key is the dotted path) and
630
+ // retry once. Everything else — invalid types, unknown keys — still throws.
631
+ const offendingKey = error?.details?.key;
632
+ const relaxed = dropDottedKey(input, offendingKey);
633
+ const fallback = attachConfigMeta(buildResolvedConfig(relaxed, { env }), migration);
634
+ fallback.startup = {
635
+ ...fallback.startup,
636
+ degraded: true,
637
+ degradedReason: {
638
+ code: error.code,
639
+ key: offendingKey ?? null,
640
+ message: error.message,
641
+ },
642
+ };
643
+ fallback.warnings = [
644
+ ...fallback.warnings,
645
+ `strictStartup=false: ${error.message} — fell back to the safe default and continued starting.`,
646
+ ];
647
+ try {
648
+ console.warn(`hippocampus/config-degraded: ${error.message} — started anyway (strictStartup=false)`);
649
+ } catch {
650
+ /* ignore */
651
+ }
652
+ return fallback;
653
+ }
654
+ }
655
+
656
+ /** Copy the dotted key out of the input so the next pass validates cleanly. */
657
+ function dropDottedKey(input, dotted) {
658
+ if (!dotted || typeof dotted !== 'string') return input;
659
+ const parts = dotted.split('.');
660
+ const clone = { ...input };
661
+ let cursor = clone;
662
+ for (let index = 0; index < parts.length - 1; index += 1) {
663
+ const key = parts[index];
664
+ if (!isPlainObject(cursor[key])) return clone;
665
+ cursor[key] = { ...cursor[key] };
666
+ cursor = cursor[key];
667
+ }
668
+ delete cursor[parts[parts.length - 1]];
669
+ return clone;
670
+ }
671
+
672
+ /** Stable, non-frozen observability block for migrations/degradation. */
673
+ function attachConfigMeta(config, migration) {
674
+ return {
675
+ ...config,
676
+ configVersion: CONFIG_SCHEMA_VERSION,
677
+ startup: {
678
+ strict: config.strictStartup !== false,
679
+ degraded: false,
680
+ migrated: migration.migrated,
681
+ fromVersion: migration.fromVersion,
682
+ },
683
+ warnings: [...migration.warnings],
684
+ };
685
+ }
686
+
687
+ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
497
688
  const input = normaliseRaw(raw);
498
689
 
499
690
  for (const group of ['retrieval', 'context', 'index', 'temp', 'decay', 'activeSet', 'raw', 'delete', 'review', 'migration', 'identity', 'tools', 'dream', 'tagging', 'features', 'l2Merge']) {
@@ -513,6 +704,12 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
513
704
  input.maintenanceCron === undefined ? defaults.maintenanceCron : input.maintenanceCron,
514
705
  'maintenanceCron',
515
706
  );
707
+ // v1.6.3: validated like any other boolean; the degradation path lives in
708
+ // resolveConfig() and reads the RAW value before validation on purpose.
709
+ const strictStartup = requireBoolean(
710
+ input.strictStartup === undefined ? defaults.strictStartup : input.strictStartup,
711
+ 'strictStartup',
712
+ );
516
713
  // Parse + prove it can fire. The error carries MEM_E_CONFIG_INVALID_CRON.
517
714
  validateCron(maintenanceCron);
518
715
 
@@ -577,22 +774,6 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
577
774
  }
578
775
  const contextInjectPrompt =
579
776
  contextIn.injectPrompt === undefined ? defaults.context.injectPrompt : requireBoolean(contextIn.injectPrompt, 'context.injectPrompt');
580
- const contextAutoNewSession = requireBoolean(
581
- contextIn.autoNewSession === undefined ? defaults.context.autoNewSession : contextIn.autoNewSession,
582
- 'context.autoNewSession',
583
- );
584
- const contextAutoNewSessionPoll = requireEnum(
585
- contextIn.autoNewSessionPoll === undefined ? defaults.context.autoNewSessionPoll : contextIn.autoNewSessionPoll,
586
- 'context.autoNewSessionPoll',
587
- ['interval', 'once'],
588
- );
589
- const contextAutoNewSessionIntervalSeconds = requireInteger(
590
- contextIn.autoNewSessionIntervalSeconds === undefined
591
- ? defaults.context.autoNewSessionIntervalSeconds
592
- : contextIn.autoNewSessionIntervalSeconds,
593
- 'context.autoNewSessionIntervalSeconds',
594
- { min: 5, max: 3600 },
595
- );
596
777
  const contextColdStartInjectSummary = requireBoolean(
597
778
  contextIn.coldStartInjectSummary === undefined
598
779
  ? defaults.context.coldStartInjectSummary
@@ -812,6 +993,20 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
812
993
  reviewIn.intervals === undefined ? defaults.review.intervals : reviewIn.intervals,
813
994
  'review.intervals',
814
995
  );
996
+ const reviewAutoConsume = requireBoolean(
997
+ reviewIn.autoConsume === undefined ? defaults.review.autoConsume : reviewIn.autoConsume,
998
+ 'review.autoConsume',
999
+ );
1000
+ const reviewConsumeBatchSize = requireInteger(
1001
+ reviewIn.consumeBatchSize === undefined ? defaults.review.consumeBatchSize : reviewIn.consumeBatchSize,
1002
+ 'review.consumeBatchSize',
1003
+ { min: 1, max: 500 },
1004
+ );
1005
+ const reviewConsumeMaxPerRun = requireInteger(
1006
+ reviewIn.consumeMaxPerRun === undefined ? defaults.review.consumeMaxPerRun : reviewIn.consumeMaxPerRun,
1007
+ 'review.consumeMaxPerRun',
1008
+ { min: 1, max: 10_000 },
1009
+ );
815
1010
 
816
1011
  // ---- migration -----------------------------------------------------------
817
1012
  const migrationIn = input.migration ?? {};
@@ -1121,6 +1316,8 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
1121
1316
  const resolved = {
1122
1317
  dataDir,
1123
1318
  migrateFrom,
1319
+ configVersion: CONFIG_SCHEMA_VERSION,
1320
+ strictStartup,
1124
1321
  maintenanceCron,
1125
1322
  toolPrefix,
1126
1323
  briefing: requireBoolean(input.briefing === undefined ? defaults.briefing : input.briefing, 'briefing'),
@@ -1146,10 +1343,7 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
1146
1343
  threshold: contextThreshold,
1147
1344
  target: contextTarget,
1148
1345
  injectPrompt: contextInjectPrompt,
1149
- autoNewSession: contextAutoNewSession,
1150
- autoNewSessionPoll: contextAutoNewSessionPoll,
1151
- autoNewSessionIntervalSeconds: contextAutoNewSessionIntervalSeconds,
1152
- // v1.6.0 cold-start injection switches (independent booleans).
1346
+ // v1.6.3 cold-start injection switches (independent booleans).
1153
1347
  coldStartInjectSummary: contextColdStartInjectSummary,
1154
1348
  coldStartInjectRecentTurns: contextColdStartInjectRecentTurns,
1155
1349
  // v1.5.0 routing knobs below; v1.5.3 removed minInjectConfidence entirely.
@@ -1185,7 +1379,13 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
1185
1379
  maxResultTokens: rawMaxResultTokens,
1186
1380
  },
1187
1381
  delete: { graceHours: deleteGraceHours },
1188
- review: { enabled: reviewEnabled, intervals: reviewIntervals },
1382
+ review: {
1383
+ enabled: reviewEnabled,
1384
+ intervals: reviewIntervals,
1385
+ autoConsume: reviewAutoConsume,
1386
+ consumeBatchSize: reviewConsumeBatchSize,
1387
+ consumeMaxPerRun: reviewConsumeMaxPerRun,
1388
+ },
1189
1389
  migration: { timeoutMs: migrationTimeoutMs },
1190
1390
  tagTree: tagTreeConfig,
1191
1391
  identity: { eventTimePolicy },
@@ -1212,7 +1412,14 @@ export function toMemoryOptions(config) {
1212
1412
  policy.activeSet = { ...(policy.activeSet ?? {}), cap: config.activeSet.cap };
1213
1413
  // Two-phase delete + review schedule are policy values with config names.
1214
1414
  policy.delete = { ...(policy.delete ?? {}), graceHours: config.delete.graceHours };
1215
- policy.review = { ...(policy.review ?? {}), enabled: config.review.enabled, intervals: config.review.intervals };
1415
+ policy.review = {
1416
+ ...(policy.review ?? {}),
1417
+ enabled: config.review.enabled,
1418
+ intervals: config.review.intervals,
1419
+ autoConsume: config.review.autoConsume,
1420
+ consumeBatchSize: config.review.consumeBatchSize,
1421
+ consumeMaxPerRun: config.review.consumeMaxPerRun,
1422
+ };
1216
1423
  return {
1217
1424
  dataDir: config.dataDir,
1218
1425
  policy,
@@ -1237,6 +1444,12 @@ export function toMemoryOptions(config) {
1237
1444
  features: config.features,
1238
1445
  // v1.5.6: L2 multi-merge tunables (offline maintain phase).
1239
1446
  l2Merge: config.l2Merge,
1447
+ // v1.6.3: the engine's own `panel` is what /stats and memory_admin read, so the
1448
+ // config-load outcome must reach it — otherwise `panel.startup` reported the
1449
+ // "unknown" default while `capabilities.startup` reported the truth.
1450
+ configVersion: config.configVersion,
1451
+ startup: config.startup,
1452
+ warnings: config.warnings,
1240
1453
  },
1241
1454
  };
1242
1455
  }
package/src/memory.js CHANGED
@@ -169,6 +169,15 @@ export const SESSION_TRACK_LIMIT = 16;
169
169
  * proceed. Configurable per call for tests.
170
170
  */
171
171
  export const HANDOFF_TIMEOUT_MS = 5000;
172
+ /**
173
+ * v1.6.3 handoff tail: how many verbatim-ish turns travel with the marker, and how
174
+ * long each one may be. The marker is written to state/handoff.json AND re-injected
175
+ * into the next conversation's prompt, so both bounds are prompt-budget decisions,
176
+ * not storage decisions (raw keeps the full text).
177
+ */
178
+ export const HANDOFF_TAIL_TURNS = 5;
179
+ export const RECENT_TURN_LIMIT = 12;
180
+ export const RECENT_TURN_MAX_CHARS = 400;
172
181
  export const HANDOFF_STATES = Object.freeze({ ACTIVE: 'active', FAILED: 'failed', CONSUMED: 'consumed' });
173
182
  /** Any summary whose text starts with this is a handoff summary, never evidence. */
174
183
  export const HANDOFF_TEXT_PREFIX = '交接摘要';
@@ -495,6 +504,15 @@ export class Memory {
495
504
  */
496
505
  this._sessionTokens = new Map();
497
506
  this._currentSessionId = null;
507
+ /**
508
+ * v1.6.3: the last few surface turns of the CURRENT conversation, in order.
509
+ *
510
+ * A handoff used to record only the distilled summary, so a brand-new conversation
511
+ * could not see "what was actually just said". This ring buffer is in-memory (the
512
+ * raw log remains the durable truth) and is copied into the handoff marker so the
513
+ * cold-start block can replay the tail verbatim-ish.
514
+ */
515
+ this._recentTurns = [];
498
516
  /** Tags whose oversized hint has already been shown: the next recall is "insist". */
499
517
  this._oversizedHintTags = new Set();
500
518
  this._handoffInFlight = false;
@@ -1029,8 +1047,14 @@ export class Memory {
1029
1047
  return makeRestore({ eventId, target, reason, logTime });
1030
1048
  }
1031
1049
 
1032
- /** Reinforce existing episodes. The reinforcement log IS the anchor (no field). */
1033
- async reinforce({ eventIds, weight = 1, eventTime }) {
1050
+ /**
1051
+ * Reinforce existing episodes. The reinforcement log IS the anchor (no field).
1052
+ *
1053
+ * `advanceReviews:false` is for the maintenance backfill consumer, which batches the
1054
+ * schedule advance itself (`ReviewSchedule.advanceMany`) to keep one file write per
1055
+ * batch instead of one per event.
1056
+ */
1057
+ async reinforce({ eventIds, weight = 1, eventTime, advanceReviews = true }) {
1034
1058
  this.assertOpen();
1035
1059
  const ids = this.normaliseIds(eventIds);
1036
1060
  const snapshot = await this.logStore.snapshot();
@@ -1049,7 +1073,7 @@ export class Memory {
1049
1073
  await this.logStore.append(records);
1050
1074
  await this.indexManager.applyRecords(records);
1051
1075
  // A reinforcement IS a review: advance the spaced-repetition step.
1052
- for (const target of ids) this.reviews.advance(target, { now: this.clock.now() });
1076
+ if (advanceReviews) for (const target of ids) this.reviews.advance(target, { now: this.clock.now() });
1053
1077
  this._markBriefingDirty();
1054
1078
  return {
1055
1079
  reinforced: ids,
@@ -1058,6 +1082,70 @@ export class Memory {
1058
1082
  };
1059
1083
  }
1060
1084
 
1085
+ /**
1086
+ * Consume the due review queue (v1.6.3).
1087
+ *
1088
+ * Why this exists: `ReviewSchedule.tick()` was only ever REPORTED in maintenance —
1089
+ * nothing advanced the due rows, so on a fresh install every entry stayed at
1090
+ * `lastAt: null` and the queue grew monotonically (337 due on the reporter's
1091
+ * machine). Two consequences, both bad:
1092
+ * 1. a permanently "due" list makes the spaced-repetition panel useless;
1093
+ * 2. recall never got the reinforcement anchor, so the decay curve was computed
1094
+ * as if the memory had never been touched since it was written.
1095
+ *
1096
+ * A due item is by definition "scheduled for review now", so maintenance treats it
1097
+ * as reviewed: one batched `reinforce` (the log is the anchor — no field is
1098
+ * mutated) plus one batched schedule advance.
1099
+ *
1100
+ * Bounded on purpose: at most `consumeMaxPerRun` items per pass, `consumeBatchSize`
1101
+ * per chunk, and `setImmediate` between chunks so the event loop (HTTP routes,
1102
+ * prompt assembly) keeps running while a large backlog drains.
1103
+ */
1104
+ async _consumeDueReviews({ now = this.clock.now() } = {}) {
1105
+ // `config.review` arrives through `toMemoryOptions().config`; fall back to the
1106
+ // resolved policy when a bare `Memory.open({policy})` fixture is used.
1107
+ const policy = this.config?.review ?? this.policy?.review ?? {};
1108
+ if (policy.enabled === false) return { enabled: false, reason: 'review-disabled' };
1109
+ if (policy.autoConsume === false) return { enabled: false, reason: 'auto-consume-disabled' };
1110
+ const batchSize = Math.max(1, Number(policy.consumeBatchSize) || 40);
1111
+ const maxPerRun = Math.max(1, Number(policy.consumeMaxPerRun) || 200);
1112
+ const view = this.reviews.tick({ events: this.indexManager.snapshot()?.events ?? [], now });
1113
+ const dueIds = (view.due ?? []).map((row) => row.eventId).filter(Boolean).slice(0, maxPerRun);
1114
+ if (dueIds.length === 0) {
1115
+ return { enabled: true, consumed: 0, batches: 0, dueBefore: Array.isArray(view.due) ? view.due.length : 0, remaining: 0 };
1116
+ }
1117
+ const consumed = [];
1118
+ let batches = 0;
1119
+ for (let offset = 0; offset < dueIds.length; offset += batchSize) {
1120
+ const chunk = dueIds.slice(offset, offset + batchSize);
1121
+ try {
1122
+ await this.reinforce({ eventIds: chunk, weight: 1, eventTime: now, advanceReviews: false });
1123
+ this.reviews.advanceMany(chunk, { now });
1124
+ consumed.push(...chunk);
1125
+ } catch (error) {
1126
+ // A failed chunk must not abort the pass: the next maintenance retries the
1127
+ // same rows, because their `lastAt` stays null until they succeed.
1128
+ return {
1129
+ enabled: true,
1130
+ consumed: consumed.length,
1131
+ batches,
1132
+ dueBefore: view.due.length,
1133
+ remaining: dueIds.length - consumed.length,
1134
+ error: error instanceof Error ? error.message : String(error),
1135
+ };
1136
+ }
1137
+ batches += 1;
1138
+ if (offset + batchSize < dueIds.length) await new Promise((resolve) => setImmediate(resolve));
1139
+ }
1140
+ return {
1141
+ enabled: true,
1142
+ consumed: consumed.length,
1143
+ batches,
1144
+ dueBefore: view.due.length,
1145
+ remaining: Math.max(0, view.due.length - consumed.length),
1146
+ };
1147
+ }
1148
+
1061
1149
  /** Delete: two-phase by default (grace countdown), then the 4-phase pipeline. */
1062
1150
  async forget({ eventIds, mode = 'purge', reason = 'unspecified' }) {
1063
1151
  this.assertOpen();
@@ -1472,6 +1560,9 @@ export class Memory {
1472
1560
  // deliberately INDEPENDENT of the raw-retention gates below — the handoff must
1473
1561
  // still work when the black box is disabled or sampled.
1474
1562
  this.observeSessionTurn(session?.id ?? session?.sessionId ?? null, turn.text);
1563
+ // v1.6.3: keep the verbatim-ish tail so the handoff marker can carry "the last
1564
+ // few things said" into the next conversation (see _distillHandoffTail).
1565
+ this._recordRecentTurn(turn.role, turn.text);
1475
1566
  this._maybeAutoHandoff();
1476
1567
  }
1477
1568
  const raw = this.config?.raw ?? {};
@@ -1580,6 +1671,12 @@ export class Memory {
1580
1671
  const isSameKeyRestart =
1581
1672
  previousTokens !== null && tokens < previousTokens / 2 && previousTokens > this.context.nativeTokenLimit / 2;
1582
1673
  this._currentSessionId = key;
1674
+ if (isNewSession) {
1675
+ // v1.6.3: the tail belongs to ONE conversation; a new session id must not inherit
1676
+ // the previous conversation's last turns (they are replayed by the handoff marker
1677
+ // instead, exactly once).
1678
+ this._recentTurns = [];
1679
+ }
1583
1680
  if (isNewSession || isSameKeyRestart) {
1584
1681
  // CORE ANTI-DEADLOCK: the in-flight guard belongs to the OLD session only.
1585
1682
  this._handoffInFlight = false;
@@ -1591,9 +1688,34 @@ export class Memory {
1591
1688
  return this.sessionUsage();
1592
1689
  }
1593
1690
 
1691
+ /**
1692
+ * Remember ONE surface turn for the handoff tail (v1.6.3).
1693
+ *
1694
+ * Bounded and process-local by design: the raw log stays the durable source of
1695
+ * truth, and this buffer only exists to hand "what was just said" to the next
1696
+ * conversation. Text is normalised and truncated so a pasted file cannot bloat the
1697
+ * marker that is written to state/handoff.json.
1698
+ */
1699
+ _recordRecentTurn(role, text) {
1700
+ const clean = String(text ?? '').replace(/\s+/g, ' ').trim();
1701
+ if (clean.length === 0) return;
1702
+ this._recentTurns.push({
1703
+ role: role === 'assistant' ? 'assistant' : 'user',
1704
+ text: clean.slice(0, RECENT_TURN_MAX_CHARS),
1705
+ });
1706
+ if (this._recentTurns.length > RECENT_TURN_LIMIT) {
1707
+ this._recentTurns = this._recentTurns.slice(-RECENT_TURN_LIMIT);
1708
+ }
1709
+ }
1710
+
1711
+ /** The last `count` remembered turns (oldest first) for the handoff marker. */
1712
+ recentTurns(count = HANDOFF_TAIL_TURNS) {
1713
+ const limit = Math.max(0, Math.min(RECENT_TURN_LIMIT, Number(count) || 0));
1714
+ return this._recentTurns.slice(-limit).map((turn) => ({ role: turn.role, text: turn.text }));
1715
+ }
1716
+
1594
1717
  /** Add ONE turn's estimated tokens to its session (surface messages only). */
1595
- observeSessionTurn(sessionId, text) {
1596
- this.assertOpen();
1718
+ observeSessionTurn(sessionId, text) { this.assertOpen();
1597
1719
  const key = typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : DEFAULT_SESSION_KEY;
1598
1720
  const previous = this._sessionTokens.get(key) ?? 0;
1599
1721
  const tokens = previous + Math.max(1, Math.ceil(String(text ?? '').length / 4));
@@ -1785,6 +1907,9 @@ export class Memory {
1785
1907
  summaryEventId: distilled?.eventId ?? null,
1786
1908
  summaryStatus: distilled?.status ?? null,
1787
1909
  summaryError: failure,
1910
+ // v1.6.3: carry the last few turns verbatim so the next conversation can pick up
1911
+ // "what was actually just said" instead of only the compressed summary.
1912
+ tailTurns: this.recentTurns(HANDOFF_TAIL_TURNS),
1788
1913
  // v1.5.6: carry the working mode (Host agent preset) across the handoff so the
1789
1914
  // next conversation starts in the SAME mode instead of the profile default.
1790
1915
  agentPreset: this._handoffPreset(),
@@ -2108,6 +2233,13 @@ export class Memory {
2108
2233
  } catch (error) {
2109
2234
  report.reviewsError = error instanceof Error ? error.message : String(error);
2110
2235
  }
2236
+ // v1.6.3: actually CONSUME the due queue (batched + setImmediate) instead of only
2237
+ // reporting it. Kept in its own try so a backlog problem can never fail the pass.
2238
+ try {
2239
+ report.reviewConsume = await this._consumeDueReviews({ now: this.clock.now() });
2240
+ } catch (error) {
2241
+ report.reviewConsumeError = error instanceof Error ? error.message : String(error);
2242
+ }
2111
2243
  // L1.5 tag tree: a projection of the NOW-converged index (pending deletes may
2112
2244
  // have forced a nested rebuild above). Published to state/tag-tree.json with the
2113
2245
  // ghost metadata and the persisted prune queue, so a failure here is a side
@@ -2587,11 +2719,17 @@ export class Memory {
2587
2719
  tagTree: this.tagTree.status({ indexGeneration: index.generation ?? null }),
2588
2720
  // v1.4.0 surfaces: raw shards, review queue, pending deletes.
2589
2721
  raw: { ...this.raw.stats(), mode: this.config?.raw?.mode ?? 'salience' },
2590
- reviews: this.reviews.status({ now }),
2722
+ reviews: { ...this.reviews.status({ now }), autoConsume: this.config?.review?.autoConsume !== false },
2591
2723
  pendingDeletes: this.pendingDeletes.status(now),
2592
2724
  // v1.5.5: offline Dream circuit + last fallback, visible so a broken LLM is
2593
2725
  // never a silent degradation.
2594
2726
  dream: this.dreamStatus(),
2727
+ // v1.6.3: config-load outcome (migration / degraded startup) is part of the
2728
+ // status surface, because "started with different values than you wrote" is
2729
+ // exactly the kind of thing the 1.6.2 incident showed must never be silent.
2730
+ startup: this.config?.startup ?? { strict: true, degraded: false, migrated: false, fromVersion: null },
2731
+ configVersion: this.config?.configVersion ?? null,
2732
+ configWarnings: Array.isArray(this.config?.warnings) ? this.config.warnings.slice(0, 10) : [],
2595
2733
  // v1.5.6: pre-ingest tagging health (applied anchors / anchorless misses).
2596
2734
  autoTag: { ...this._autoTag },
2597
2735
  // v1.5.6: L2 multi-merge bookkeeping (merged sources / groups).
package/src/schedule.js CHANGED
@@ -115,6 +115,34 @@ export class ReviewSchedule {
115
115
  return { eventId, step: entry.step, dueAt: entry.dueAt };
116
116
  }
117
117
 
118
+ /**
119
+ * Advance MANY events in one load + one atomic write (v1.6.3).
120
+ *
121
+ * `advance()` re-reads and rewrites `state/reviews.json` per event, which is fine
122
+ * for a single manual reinforce but pathological for the backfill consumer: a
123
+ * 337-item backlog would mean 337 file reads and 337 fsync-style rewrites inside
124
+ * ONE maintenance pass. This is the batched form — same semantics, one write.
125
+ */
126
+ advanceMany(eventIds, { now = this.clock.now() } = {}) {
127
+ const ids = Array.isArray(eventIds) ? eventIds.filter((id) => typeof id === 'string' && id.length > 0) : [];
128
+ if (ids.length === 0) return [];
129
+ const state = this.load();
130
+ const intervals = this.intervals();
131
+ const advanced = [];
132
+ let changed = false;
133
+ for (const eventId of ids) {
134
+ const entry = state.items[eventId];
135
+ if (!entry) continue;
136
+ entry.step = Math.min((entry.step ?? 0) + 1, intervals.length - 1);
137
+ entry.lastAt = now;
138
+ entry.dueAt = now + intervals[entry.step] * DAY_MS;
139
+ advanced.push({ eventId, step: entry.step, dueAt: entry.dueAt });
140
+ changed = true;
141
+ }
142
+ if (changed) this.save(state);
143
+ return advanced;
144
+ }
145
+
118
146
  /** Read-only view for admin / panel. */
119
147
  status({ now = this.clock.now() } = {}) {
120
148
  const state = this.load();
package/src/webRoutes.js CHANGED
@@ -85,11 +85,10 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
85
85
  'features.multiSpace',
86
86
  'features.crossSpaceTransfer',
87
87
  'features.crossSpaceRecall',
88
- // v1.5.6: client half may open a fresh conversation when a handoff turns active.
89
- 'context.autoNewSession',
90
- 'context.autoNewSessionPoll',
91
- 'context.autoNewSessionIntervalSeconds',
92
- // v1.6.0 cold-start injection switches (independent; default summary on, turns off).
88
+ // v1.6.3: `context.autoNewSession*` was REMOVED (a handoff continues the same
89
+ // conversation; opening a second one wasted the user's context). The keys are no
90
+ // longer editable — a stale client sending them gets the normal unknown-key error.
91
+ // v1.6.0 cold-start injection switches (independent; both default on since 1.6.3).
93
92
  'context.coldStartInjectSummary',
94
93
  'context.coldStartInjectRecentTurns',
95
94
  // v1.5.6 L2 multi-merge tunables (offline maintain phase).
@@ -136,6 +135,12 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
136
135
  'raw.captureRatio',
137
136
  'delete.graceHours',
138
137
  'review.enabled',
138
+ // v1.6.3: maintenance CONSUMES due review rows (it used to only report them, so
139
+ // the queue grew forever). Batching is bounded on purpose; an operator with a huge
140
+ // backlog can shrink `consumeMaxPerRun` to spread the drain over more passes.
141
+ 'review.autoConsume',
142
+ 'review.consumeBatchSize',
143
+ 'review.consumeMaxPerRun',
139
144
  // L1.5 tag-tree lifecycle. Rebuildable derived state, so a change is applied by
140
145
  // the next maintenance pass, never by rewriting anything on the request path.
141
146
  'tagTree.midHalfLifeMultiplier',