dsh-layers-hippocampus 1.6.2 → 1.6.4

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/index.js CHANGED
@@ -41,6 +41,7 @@ import { HostBridge } from './src/hostBridge.js';
41
41
  import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.js';
42
42
  import { DreamTimer } from './src/dreamTimer.js';
43
43
  import { probeCompression, resolveEngine } from './src/compression.js';
44
+ import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
44
45
  import { MEMORY_API, registerMemoryRoutes } from './src/webRoutes.js';
45
46
 
46
47
  export const name = 'memory';
@@ -61,7 +62,7 @@ export { resolveConfig, DEFAULT_CONFIG };
61
62
  * of letting a raw 404 reach the user.
62
63
  */
63
64
  export const CAPABILITIES = Object.freeze({
64
- version: '1.6.2',
65
+ version: '1.6.4',
65
66
  spaces: true,
66
67
  memories: true,
67
68
  transferConsent: true,
@@ -190,6 +191,30 @@ function defineTool(definition) {
190
191
  * because it owns the plugin's lifecycle contracts; the store itself is src/.
191
192
  */
192
193
  export function createRuntime({ ctx = null, config, options, clock, raw = null, orchestrator = null, timers = null }) {
194
+ // v1.6.3: the HOST is the authority on the model window and on measured prompt
195
+ // pressure. The engine probes are SYNCHRONOUS (they are called while computing a
196
+ // status/decide value), so these hold the most recent HOST-observed numbers; the
197
+ // `agent/request` middleware refreshes them before every call.
198
+ const hostProbes = {
199
+ /** @type {{ provider: string, model: string, window: number } | null} */
200
+ window: null,
201
+ /** Prompt tokens the host measured for the live request (pressure, no output). */
202
+ usedTokens: null,
203
+ /** Completion tokens the pending request reserves (its max_tokens). */
204
+ reservedTokens: null,
205
+ updatedAt: null,
206
+ lastError: null,
207
+ };
208
+ const withHostProbes = (targetOptions) => ({
209
+ ...targetOptions,
210
+ config: {
211
+ ...targetOptions.config,
212
+ getHostWindow: () => hostProbes.window?.window ?? null,
213
+ getHostUsedTokens: () => hostProbes.usedTokens,
214
+ getReservedTokens: () => hostProbes.reservedTokens,
215
+ },
216
+ });
217
+ options = withHostProbes(options);
193
218
  // v1.5.6 physical split: multi-space lives in dsh-orchestrator. `orchestrator` is a
194
219
  // test/embedding override; the Host supplies the real service through `ctx.get`.
195
220
  const orchestratorService = () => orchestrator ?? ctx?.get?.('orchestrator') ?? null;
@@ -398,8 +423,25 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
398
423
  * made the model look like it was rereading the same page.
399
424
  */
400
425
  runtime.injection = { sessionId: null, ids: new Set(), tags: new Set(), handoffAt: null };
401
- // v1.6.0: set on agent/created(startup), consumed by the FIRST prompt assembly.
402
- runtime.coldStartPending = false;
426
+ /**
427
+ * v1.6.3 cold-start state (replaces the v1.6.0 boolean `coldStartPending`).
428
+ *
429
+ * The boolean was consumed by the FIRST prompt assembly of the whole process, so
430
+ * any other agent that assembled a prompt first (a delegated sub-agent, a title
431
+ * generator, a background fibre) swallowed the injection and the user's brand-new
432
+ * conversation started blind — exactly the reported bug.
433
+ *
434
+ * Now a *pending injection* is armed per conversation start (a new session id from
435
+ * `session/event`, or `agent/created(source=startup)`) and is keyed by
436
+ * `session|handoffEpoch`. `injected` records what has already been delivered, so:
437
+ * - one conversation is injected at most once per handoff epoch;
438
+ * - a different agent cannot consume someone else's injection silently: the new
439
+ * conversation arms its own pending entry on its first captured turn.
440
+ */
441
+ runtime.coldStart = { pending: new Map(), injected: new Set(), lastSessionId: null };
442
+ const COLD_START_INJECTED_LIMIT = 64;
443
+ const COLD_START_PENDING_LIMIT = 8;
444
+ const COLD_START_PENDING_TTL_MS = 5 * 60_000;
403
445
  runtime.lastHintTags = [];
404
446
  runtime.resetInjection = (sessionId = runtime.injection.sessionId) => {
405
447
  runtime.injection = { sessionId, ids: new Set(), tags: new Set(), handoffAt: null };
@@ -455,20 +497,114 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
455
497
  };
456
498
 
457
499
  /**
458
- * v1.6.0: one-shot cold-start block for a brand-new conversation.
500
+ * v1.6.3: arm a cold-start injection for the conversation that is about to run.
501
+ *
502
+ * Two independent hosts signal "a conversation started": `agent/created` (a new
503
+ * agent, `source: startup`) and the first `session/event` of a session id we have
504
+ * not seen. Either one arms the SAME per-conversation entry, so a host that does
505
+ * not deliver one of them still gets the behaviour (and the second signal for the
506
+ * same conversation is a no-op, not a second injection).
507
+ *
508
+ * A MAP of pendings, not a single slot: a title generator or a delegated sub-agent
509
+ * may be created right after the user's conversation and arm its own entry. With a
510
+ * single slot that later arm would OVERWRITE — and then consume — the user's entry,
511
+ * which is exactly the bug being fixed.
459
512
  *
460
- * Two independent switches (user request 2026-11-06):
461
- * - `context.coldStartInjectSummary` → `[Cold-Start Summary]` (handoff summary
462
- * event, else the top L3 semantic summaries);
463
- * - `context.coldStartInjectRecentTurns` → `[Previous Context Tail]` (last ≤5
464
- * episodes, 200 chars each).
465
- * Both off → an empty string, and the static anti-customer-service policy still
466
- * keeps the model from the "how may I help you" opener.
513
+ * Nothing is armed when there is nothing to inject: no handoff summary and no L3
514
+ * summaries means a brand-new install, where a cold-start block would be noise.
467
515
  */
468
- runtime.coldStartText = () => {
469
- if (runtime.phase !== 'ready' || runtime.coldStartPending !== true) return '';
516
+ runtime.noteColdStart = ({ sessionId = null, agentId = null, source = 'session' } = {}) => {
517
+ if (runtime.phase !== 'ready') return null;
518
+ const handoff = memory.handoffState();
519
+ const hasSummaryEvent = typeof handoff?.summaryEventId === 'string' && handoff.summaryEventId.length > 0;
520
+ if (!hasSummaryEvent) return null;
521
+ const epoch = `${handoff.at ?? 0}:${handoff.summaryEventId}`;
522
+ const key = `${sessionId ?? agentId ?? 'unknown'}|${epoch}`;
523
+ if (runtime.coldStart.injected.has(key)) return null;
524
+ const pendings = runtime.coldStart.pending;
525
+ runtime.pruneColdStartPendings();
526
+ const existing = pendings.get(key);
527
+ if (existing) {
528
+ // Same conversation re-armed (created + first turn): merge identifiers and keep
529
+ // the FIRST arming time instead of restarting the TTL.
530
+ existing.sessionId = existing.sessionId ?? sessionId;
531
+ existing.agentId = existing.agentId ?? agentId;
532
+ return existing;
533
+ }
534
+ const entry = {
535
+ key,
536
+ sessionId,
537
+ agentId,
538
+ source,
539
+ at: memory.clock.now(),
540
+ epoch,
541
+ summaryEventId: handoff.summaryEventId,
542
+ };
543
+ pendings.set(key, entry);
544
+ // Bounded: the oldest armed entry is dropped, so a long-lived process cannot grow
545
+ // this map without limit (each conversation adds at most a couple of entries).
546
+ while (pendings.size > COLD_START_PENDING_LIMIT) {
547
+ pendings.delete(pendings.keys().next().value);
548
+ }
549
+ return entry;
550
+ };
551
+
552
+ /** Drop pendings that were never consumed (a conversation that never assembled). */
553
+ runtime.pruneColdStartPendings = () => {
554
+ const pendings = runtime.coldStart.pending;
555
+ if (pendings.size === 0) return 0;
556
+ const now = memory.clock.now();
557
+ let dropped = 0;
558
+ for (const [key, entry] of pendings) {
559
+ if (now - (Number(entry.at) || 0) > COLD_START_PENDING_TTL_MS) {
560
+ pendings.delete(key);
561
+ dropped += 1;
562
+ }
563
+ }
564
+ return dropped;
565
+ };
566
+
567
+ /** True when an armed entry belongs to the conversation currently assembling. */
568
+ const coldStartMatches = (pending, sessionId, agentId) => {
569
+ if (!pending) return false;
570
+ if (pending.sessionId && sessionId && pending.sessionId === sessionId) return true;
571
+ if (pending.agentId && agentId && pending.agentId === agentId) return true;
572
+ // Neither side known (older host without session/agent identity): the entry is
573
+ // still this process's ONLY armed injection, so let it through once.
574
+ return !pending.sessionId && !pending.agentId && !sessionId && !agentId;
575
+ };
576
+
577
+ /**
578
+ * v1.6.0 / v1.6.3: one-shot cold-start block for a conversation that just started
579
+ * after a handoff.
580
+ *
581
+ * Two independent switches:
582
+ * - `context.coldStartInjectSummary` → `[Cold-Start Summary]` (the handoff
583
+ * summary event; falls back to the top L3 semantic summaries);
584
+ * - `context.coldStartInjectRecentTurns` → `[Previous Context Tail]` (the last ≤5
585
+ * turns captured at handoff time, else the newest episodes).
586
+ * Both off → empty string; the static anti-customer-service policy still ships in
587
+ * `memory:policy`, so the model never falls back to a canned opener.
588
+ */
589
+ runtime.coldStartText = ({ sessionId = null, agentId = null } = {}) => {
590
+ if (runtime.phase !== 'ready') return '';
591
+ runtime.pruneColdStartPendings();
592
+ const pendings = runtime.coldStart.pending;
593
+ let pending = null;
594
+ for (const entry of pendings.values()) {
595
+ if (coldStartMatches(entry, sessionId, agentId)) {
596
+ pending = entry;
597
+ break;
598
+ }
599
+ }
600
+ if (!pending) return '';
601
+ // Consume on the FIRST matching assembly, even when both switches are off: the
602
+ // entry must not linger and fire later on an unrelated conversation.
603
+ pendings.delete(pending.key);
470
604
  const contextConfig = runtime.config?.context ?? {};
471
- if (contextConfig.coldStartInjectSummary !== true && contextConfig.coldStartInjectRecentTurns !== true) return '';
605
+ const wantSummary = contextConfig.coldStartInjectSummary === true;
606
+ const wantTurns = contextConfig.coldStartInjectRecentTurns === true;
607
+ if (!wantSummary && !wantTurns) return '';
472
608
  try {
473
609
  const view = memory.indexManager.snapshot();
474
610
  const allEvents = Array.isArray(view?.events) ? [...view.events] : [];
@@ -483,11 +619,15 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
483
619
  const spaces = memory.spaces.status();
484
620
  const activeSpace = spaces?.current ?? 'default';
485
621
  const lines = ['', `[Cold-Start Detected: Active Space=${activeSpace}, Recent Topic=${latestTopic}]`];
486
- if (contextConfig.coldStartInjectSummary === true) {
622
+ const handoff = memory.handoffState();
623
+ if (wantSummary) {
487
624
  let summaryText = '';
488
- const handoff = memory.handoffState();
489
625
  if (handoff?.summaryEventId) {
490
- const summaryEvent = events.find((event) => event.eventId === handoff.summaryEventId);
626
+ // The summary event carries a business tag (`folded_summary`), but be
627
+ // defensive: search ALL events so a bookkeeping-tag rewrite cannot hide it.
628
+ const summaryEvent =
629
+ allEvents.find((event) => event.eventId === handoff.summaryEventId) ??
630
+ events.find((event) => event.eventId === handoff.summaryEventId);
491
631
  if (summaryEvent?.content) summaryText = String(summaryEvent.content);
492
632
  }
493
633
  if (!summaryText) {
@@ -502,20 +642,34 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
502
642
  lines.push('[Cold-Start Summary]', summaryText.replace(/\s+/g, ' ').trim().slice(0, 800));
503
643
  }
504
644
  }
505
- if (contextConfig.coldStartInjectRecentTurns === true && events.length > 0) {
506
- const recent = events
507
- .slice(0, 5)
508
- .map((event) => `- ${String(event.content ?? '').replace(/\s+/g, ' ').trim().slice(0, 200)}`)
509
- .filter((line) => line.length > 2);
645
+ if (wantTurns) {
646
+ // Prefer the turns captured AT the handoff (verbatim roles, exactly "the last
647
+ // few things said"); episodes are distilled text and lose the dialogue shape.
648
+ const tail = Array.isArray(handoff?.tailTurns) ? handoff.tailTurns : [];
649
+ const recent = tail.length > 0
650
+ ? tail
651
+ .slice(-5)
652
+ .map((turn) => `- ${turn.role === 'assistant' ? 'assistant' : 'user'}: ${String(turn.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 200)}`)
653
+ .filter((line) => line.length > 10)
654
+ : events
655
+ .slice(0, 5)
656
+ .map((event) => `- ${String(event.content ?? '').replace(/\s+/g, ' ').trim().slice(0, 200)}`)
657
+ .filter((line) => line.length > 2);
510
658
  if (recent.length > 0) lines.push('[Previous Context Tail]', ...recent);
511
659
  }
512
- return lines.join('\n');
660
+ const text = lines.join('\n');
661
+ runtime.coldStart.injected.add(pending.key);
662
+ if (runtime.coldStart.injected.size > COLD_START_INJECTED_LIMIT) {
663
+ const oldest = runtime.coldStart.injected.values().next().value;
664
+ runtime.coldStart.injected.delete(oldest);
665
+ }
666
+ return text;
513
667
  } catch {
514
668
  return '';
515
669
  }
516
670
  };
517
671
 
518
- runtime.promptState = () => {
672
+ runtime.promptState = (assemblyContext = null) => {
519
673
  // Opportunistic mode tracking: prompt assembly is inside the agent turn, so the
520
674
  // current preset is readable here even when no change event ever fired.
521
675
  runtime.syncAgentPreset();
@@ -577,9 +731,12 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
577
731
  .join('\n')
578
732
  : '';
579
733
  // v1.6.0 cold-start block: volatile tail (after the cacheable prefix), injected
580
- // exactly once on the first assembly of a brand-new conversation.
581
- const coldStart = runtime.coldStartText();
582
- if (runtime.coldStartPending === true) runtime.coldStartPending = false;
734
+ // at most once per conversation (v1.6.3: keyed by session|handoff-epoch, so a
735
+ // sibling agent assembling first can no longer swallow the user's injection).
736
+ const coldStart = runtime.coldStartText({
737
+ sessionId: usage?.sessionId ?? null,
738
+ agentId: assemblyContext?.agent?.id ?? null,
739
+ });
583
740
  return (
584
741
  composePrompt({ rules: PROMPT_STATE_RULES, activeTask: activeTaskBlock, blocks, hints }) +
585
742
  marker +
@@ -590,6 +747,148 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
590
747
  return `Memory state: ${runtime.phase}${error} (not ready: memory tools answer MEM_E_NOT_READY).`;
591
748
  };
592
749
 
750
+ /**
751
+ * v1.6.3 — the per-request gate. Runs BEFORE the provider call (the `agent/request`
752
+ * listener above) and does three things, in this order:
753
+ *
754
+ * 1. **Live Compact**: one oversized `tool/result` is pointerized (head + tail kept,
755
+ * middle replaced by a pointer carrying the durable raw coordinates). This is the
756
+ * only defence against a SINGLE turn that adds hundreds of thousands of tokens —
757
+ * no threshold-based maintenance tick can react fast enough.
758
+ * 2. **Refresh the host probes** so the engine's denominator (real model window) and
759
+ * numerator (host-measured pressure) stop being guesses.
760
+ * 3. **Fail fast** when `used + reserved` already exceeds the model window. The API
761
+ * would reject the same request a moment later, after the tokens were spent and
762
+ * without telling the state machine anything; a handoff is attempted first so the
763
+ * next turn starts from a distilled tail instead of the same brick wall.
764
+ *
765
+ * Everything here is best-effort EXCEPT the deliberate `MEM_E_CONTEXT_EXCEEDED`.
766
+ *
767
+ * @param {{ agent?: object, config?: object, signal?: object }} input
768
+ */
769
+ runtime.guardRequest = async ({ agent = null, config: requestConfig = null, signal = null } = {}) => {
770
+ const session = agent?.session ?? null;
771
+ // ---- 1. Live Compact ---------------------------------------------------
772
+ const liveConfig = runtime.config?.context?.liveCompact ?? {};
773
+ if (liveConfig.enabled !== false && session) {
774
+ // The HOST owns the canonical pruner (`tool-result-pruner`, replay-safe, wired
775
+ // into the ptc preset). Delegate when present; only fall back to our own
776
+ // surface surgery when the host has no pruner at all.
777
+ const hostPruner = (() => {
778
+ try {
779
+ return ctx?.get?.('toolResultPruner') ?? null;
780
+ } catch {
781
+ return null;
782
+ }
783
+ })();
784
+ if (hostPruner && typeof hostPruner.pruneSession === 'function') {
785
+ try {
786
+ await hostPruner.pruneSession(session);
787
+ runtime.lastLiveCompact = { source: 'host', at: memory.clock.now() };
788
+ } catch (error) {
789
+ runtime.logger?.warn?.(`hippocampus: host live-compact failed: ${asMemoryError(error).code}`);
790
+ }
791
+ } else {
792
+ runtime.lastLiveCompact = {
793
+ source: 'hippocampus',
794
+ at: memory.clock.now(),
795
+ ...liveCompactSession(session, {
796
+ thresholdChars: liveConfig.thresholdChars ?? LIVE_COMPACT_DEFAULTS.thresholdChars,
797
+ headChars: liveConfig.headChars ?? LIVE_COMPACT_DEFAULTS.headChars,
798
+ tailChars: liveConfig.tailChars ?? LIVE_COMPACT_DEFAULTS.tailChars,
799
+ maxNodesPerRequest: liveConfig.maxNodesPerRequest ?? LIVE_COMPACT_DEFAULTS.maxNodesPerRequest,
800
+ logger: runtime.logger,
801
+ }),
802
+ };
803
+ }
804
+ }
805
+
806
+ // ---- 2. refresh the probes --------------------------------------------
807
+ const provider = requestConfig?.provider ?? null;
808
+ const model = requestConfig?.model ?? null;
809
+ const reserved = Number.isFinite(requestConfig?.maxTokens) ? requestConfig.maxTokens : null;
810
+ if (provider && model) {
811
+ const llm = (() => {
812
+ try {
813
+ return ctx?.get?.('llm') ?? null;
814
+ } catch {
815
+ return null;
816
+ }
817
+ })();
818
+ if (llm && typeof llm.resolveModelInfo === 'function') {
819
+ try {
820
+ const info = await llm.resolveModelInfo(provider, model, signal ?? undefined);
821
+ const window = info?.context?.contextWindow ?? null;
822
+ if (Number.isFinite(window) && window > 0) {
823
+ hostProbes.window = { provider, model, window: Math.round(window) };
824
+ }
825
+ if (Number.isFinite(info?.defaultMaxTokens)) {
826
+ // The adapter's own default is what an unspecified request asks for.
827
+ hostProbes.reservedTokens = reserved ?? info.defaultMaxTokens;
828
+ }
829
+ } catch (error) {
830
+ hostProbes.lastError = asMemoryError(error).code;
831
+ }
832
+ }
833
+ }
834
+ if (reserved !== null) hostProbes.reservedTokens = reserved;
835
+ const tokenMeter = (() => {
836
+ try {
837
+ return ctx?.get?.('tokenMeter') ?? null;
838
+ } catch {
839
+ return null;
840
+ }
841
+ })();
842
+ if (tokenMeter && session && typeof tokenMeter.contextPressure === 'function') {
843
+ try {
844
+ const pressure = tokenMeter.contextPressure(session) ?? {};
845
+ // `pressureTokens` is input + cache read/write; `projectedTokens` may already
846
+ // include the pending completion. Prefer the larger — under-reporting is what
847
+ // let 854k tokens look small.
848
+ const candidates = [pressure.pressureTokens, pressure.projectedTokens].filter((value) => Number.isFinite(value));
849
+ if (candidates.length > 0) hostProbes.usedTokens = Math.max(...candidates);
850
+ if (Number.isFinite(pressure.contextWindow) && pressure.contextWindow > 0 && !hostProbes.window) {
851
+ hostProbes.window = { provider: provider ?? 'host', model: model ?? 'host', window: Math.round(pressure.contextWindow) };
852
+ }
853
+ } catch (error) {
854
+ hostProbes.lastError = asMemoryError(error).code;
855
+ }
856
+ }
857
+ hostProbes.updatedAt = memory.clock.now();
858
+
859
+ // ---- 3. fail fast on a request that CANNOT fit -------------------------
860
+ const state = memory.context.nativeState({
861
+ usedTokens: hostProbes.usedTokens ?? undefined,
862
+ reservedTokens: hostProbes.reservedTokens ?? undefined,
863
+ });
864
+ if (!state.hardExceeded) return state;
865
+ // Try to hand off first: even though it cannot shrink THIS request, it leaves a
866
+ // distilled tail for the next one instead of repeating the same failure.
867
+ let handoff = null;
868
+ try {
869
+ handoff = await memory.checkHandoff({ now: memory.clock.now() });
870
+ } catch {
871
+ /* the fail-fast below is the contract; a failed handoff only degrades recovery */
872
+ }
873
+ throw new MemoryError(
874
+ ErrorCodes.CONTEXT_EXCEEDED,
875
+ `request does not fit the model window: ${state.projectedTokens} tokens (prompt ${state.tokens} + reserved ${state.reservedTokens}) ` +
876
+ `>= ${state.nativeTokenLimit} (window source: ${state.windowSource}). ` +
877
+ 'Nothing was sent to the provider. Compact the conversation (host compaction) or start a new one; ' +
878
+ 'the handoff summary for the tail is available for the next conversation.',
879
+ {
880
+ usedTokens: state.tokens,
881
+ reservedTokens: state.reservedTokens,
882
+ projectedTokens: state.projectedTokens,
883
+ window: state.nativeTokenLimit,
884
+ windowSource: state.windowSource,
885
+ ratio: state.ratio,
886
+ handoff: handoff?.handoff?.summaryEventId ?? null,
887
+ liveCompact: runtime.lastLiveCompact ?? null,
888
+ },
889
+ );
890
+ };
891
+
593
892
  /**
594
893
  * The ONE maintenance entry point. Concurrency is refused, not queued: two
595
894
  * rebuilds racing would publish out of order, and a queue would silently run a
@@ -853,6 +1152,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
853
1152
  dreamQueue: memory.dreamQueue(),
854
1153
  dreamTimer: runtime.dreamTimer?.status() ?? null,
855
1154
  handoff: runtime.handoffView(),
1155
+ // v1.6.3: cold-start injection observability. Without it the only way to tell
1156
+ // "armed but never assembled" from "already injected" is to read the prompt.
1157
+ coldStart: runtime.coldStartView?.() ?? null,
856
1158
  panel: { ...status.panel, migration: runtime.migrationStatus() },
857
1159
  briefing: memory.briefing(),
858
1160
  config: uiConfig(runtime.config),
@@ -904,6 +1206,25 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
904
1206
  : ['default']
905
1207
  : [];
906
1208
 
1209
+ /**
1210
+ * v1.6.3: cold-start injection observability for /stats.
1211
+ *
1212
+ * `pending` = armed but not yet assembled (a conversation that has not run its
1213
+ * first turn), `injected` = delivered keys (bounded), `lastSessionId` = the most
1214
+ * recent conversation this process captured a turn for.
1215
+ */
1216
+ runtime.coldStartView = () => ({
1217
+ pending: [...runtime.coldStart.pending.values()].map((entry) => ({
1218
+ key: entry.key,
1219
+ sessionId: entry.sessionId,
1220
+ agentId: entry.agentId,
1221
+ source: entry.source,
1222
+ at: entry.at,
1223
+ })),
1224
+ injected: runtime.coldStart.injected.size,
1225
+ lastSessionId: runtime.coldStart.lastSessionId,
1226
+ });
1227
+
907
1228
  /**
908
1229
  * True only when a multi-space adapter (dsh-orchestrator) is present AND the
909
1230
  * profile has not turned the capability off. The core alone is single-space.
@@ -929,8 +1250,11 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
929
1250
  // but no spacesDelete, so the client hides the delete button instead of sending an
930
1251
  // action the old server would misread as CREATE ("空间已存在").
931
1252
  spacesDelete: runtime.multiSpaceAvailable() && typeof memory.spaces?.deleteSpace === 'function',
932
- // v1.5.6: the client half may open a fresh conversation on an active handoff.
933
- autoNewSession: runtime.config.context.autoNewSession === true,
1253
+ // v1.6.3: `autoNewSession` was REMOVED — a handoff continues the same conversation,
1254
+ // so there is no client-side "open another one" capability to advertise.
1255
+ // v1.6.3: how the config was loaded — a degraded boot must be visible, not silent.
1256
+ startup: runtime.config.startup ?? { strict: true, degraded: false, migrated: false, fromVersion: null },
1257
+ configVersion: runtime.config.configVersion ?? null,
934
1258
  // v1.6.1: cold-archive compression engines available in THIS Node runtime.
935
1259
  compression: (() => {
936
1260
  const probe = probeCompression();
@@ -946,15 +1270,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
946
1270
  })(),
947
1271
  });
948
1272
 
949
- /** v1.5.6: handoff observability for the client-side auto-new-session controller. */
950
- runtime.handoffView = () => {
1273
+ /** v1.5.6: handoff observability (the client shows the marker + summary link). */ runtime.handoffView = () => {
951
1274
  const handoff = memory.handoffState();
952
1275
  return {
953
1276
  active: handoff?.active === true,
954
1277
  at: handoff?.at ?? null,
955
1278
  summaryEventId: handoff?.summaryEventId ?? null,
956
1279
  agentPreset: runtime.agentPreset ?? null,
957
- autoNewSession: runtime.config.context.autoNewSession === true,
958
1280
  };
959
1281
  };
960
1282
 
@@ -1328,9 +1650,13 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1328
1650
  runtime.agentPresetSessionId = sessionId ?? null;
1329
1651
  },
1330
1652
  onAgentCreated: async (payload) => {
1331
- // v1.6.0: a brand-new conversation needs one cold-start injection on its first
1332
- // prompt assembly (summary and/or previous turns, each behind its own flag).
1333
- if (payload?.source === 'startup') runtime.coldStartPending = true;
1653
+ // v1.6.3: arm a cold-start injection for the new agent. The host reports
1654
+ // `source: 'startup'` for a user-created conversation, and there is no separate
1655
+ // "user pressed +" signal, so we do NOT gate on source here: the real gate is
1656
+ // "a handoff summary exists and this conversation has not seen it yet"
1657
+ // (inside noteColdStart). A delegated sub-agent also lands here — it merely
1658
+ // arms its OWN entry, and the user's conversation arms its own on first turn.
1659
+ runtime.noteColdStart({ agentId: payload?.agent?.id ?? null, source: 'agent-created' });
1334
1660
  // Track the mode this session actually runs in (a session may be created with
1335
1661
  // a preset without emitting a change event).
1336
1662
  try {
@@ -1503,9 +1829,19 @@ export async function discoverLegacyDataDir({ existsSync, dataDir }) {
1503
1829
  * @param {object} [rawConfig] plugin config from cordis.patch.yml / Config panel
1504
1830
  */
1505
1831
  export async function apply(ctx, rawConfig = {}) {
1506
- // Fail-fast: an invalid config must abort activation, never fall back to defaults.
1832
+ // v1.6.3: migrate-then-validate. `resolveConfig` migrates older config schemas
1833
+ // BEFORE strict validation, and with `strictStartup: false` degrades an
1834
+ // out-of-range value instead of aborting activation — a boot abort is what left
1835
+ // the whole plugin unregistered in 1.6.2 (UI polled /stats → 404 forever).
1507
1836
  const config = resolveConfig(rawConfig);
1508
1837
  const options = toMemoryOptions(config);
1838
+ const startupWarnings = Array.isArray(config.warnings) ? config.warnings : [];
1839
+ for (const warning of startupWarnings) ctx?.logger?.warn?.(`hippocampus/config: ${warning}`);
1840
+ if (config.startup?.degraded) {
1841
+ ctx?.logger?.warn?.(
1842
+ `hippocampus/config: STARTED DEGRADED (strictStartup=false) — ${config.startup.degradedReason?.message ?? 'config value out of range'}`,
1843
+ );
1844
+ }
1509
1845
 
1510
1846
  const runtime = createRuntime({ ctx, config, options, raw: rawConfig });
1511
1847
  // Internal handle, kept OFF the context: `ctx.memory` is a provided service name
@@ -1609,6 +1945,15 @@ export async function apply(ctx, rawConfig = {}) {
1609
1945
  // raw store's own gating/budgets still decide what lands on disk.
1610
1946
  const captureListener = (session, event) => {
1611
1947
  if (!runtime.memory || runtime.phase !== 'ready') return;
1948
+ // v1.6.3: a NEW conversation id is the reliable "the user started a conversation"
1949
+ // signal on every host (a user-created and a resumed session both arrive here).
1950
+ // Arming on the first captured turn also beats any sibling agent assembling a
1951
+ // prompt, because this conversation's assembly happens after its own turn.
1952
+ const sessionId = typeof session?.id === 'string' && session.id.length > 0 ? session.id : null;
1953
+ if (sessionId && sessionId !== runtime.coldStart.lastSessionId) {
1954
+ runtime.coldStart.lastSessionId = sessionId;
1955
+ runtime.noteColdStart({ sessionId, source: 'session-switch' });
1956
+ }
1612
1957
  // v1.5.6: remember the latest USER turn as the relevance input for
1613
1958
  // `[Memory Hints]`. This is the only place the current input is available:
1614
1959
  // prompt assembly receives no message text.
@@ -1633,6 +1978,27 @@ export async function apply(ctx, rawConfig = {}) {
1633
1978
  disposers.push(() => bus.off?.('session/event', captureListener));
1634
1979
  }
1635
1980
 
1981
+ // ---- v1.6.3: the request gate (Live Compact + fail-fast) ----------------
1982
+ // Runs as a plain (non-prepend) listener so it observes the FINAL routed config:
1983
+ // `await next()` returns `{provider, model, maxTokens}` for THIS call, and the
1984
+ // provider call happens after the chain resolves — throwing here aborts the
1985
+ // request instead of letting it be rejected by the API after the tokens are spent.
1986
+ const requestGuard = async ({ agent, signal }, next) => {
1987
+ const requestConfig = await next();
1988
+ if (!requestConfig || signal?.aborted) return requestConfig;
1989
+ try {
1990
+ await runtime.guardRequest({ agent, config: requestConfig, signal });
1991
+ } catch (error) {
1992
+ if (error instanceof MemoryError) throw error;
1993
+ runtime.logger?.warn?.(`hippocampus: request guard skipped: ${asMemoryError(error).code}: ${error?.message ?? error}`);
1994
+ }
1995
+ return requestConfig;
1996
+ };
1997
+ if (typeof bus.on === 'function') {
1998
+ bus.on('agent/request', requestGuard);
1999
+ disposers.push(() => bus.off?.('agent/request', requestGuard));
2000
+ }
2001
+
1636
2002
  const guard = (operation) => {
1637
2003
  if (runtime.phase === 'ready') return null;
1638
2004
  if (operation === 'recall' && runtime.legacy) return null; // served from legacy
@@ -2195,11 +2561,13 @@ export async function apply(ctx, rawConfig = {}) {
2195
2561
  }),
2196
2562
  );
2197
2563
  // On-demand: this function runs at assemble time and reads the live window.
2564
+ // v1.6.3: the assembly context carries `agent`, which lets the cold-start
2565
+ // injection be matched to the conversation that is actually assembling.
2198
2566
  disposers.push(
2199
2567
  ctx.systemPrompt.context({
2200
2568
  name: 'memory-state',
2201
2569
  order: 220,
2202
- text: () => runtime.promptState(),
2570
+ text: (assemblyContext) => runtime.promptState(assemblyContext),
2203
2571
  }),
2204
2572
  );
2205
2573
  if (config.enableReflection) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.6.2",
3
+ "version": "1.6.4",
4
4
  "private": false,
5
5
  "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
6
  "type": "module",