@vellumai/assistant 0.10.10-dev.202607201449.71ed188 → 0.10.10-dev.202607201635.61498a8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.10-dev.202607201449.71ed188",
3
+ "version": "0.10.10-dev.202607201635.61498a8",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -755,7 +755,9 @@ process imports the retrospective machinery and calls it in-process, so no
755
755
  running daemon is required.
756
756
 
757
757
  Examples:
758
- $ assistant memory retrospective run <conversationId>`,
758
+ $ assistant memory retrospective run <conversationId>
759
+ $ assistant memory retrospective list
760
+ $ assistant memory retrospective list --limit 20 --json`,
759
761
  subcommands: [
760
762
  {
761
763
  name: "run",
@@ -781,6 +783,33 @@ CLI process — no IPC round-trip to the daemon.
781
783
  Examples:
782
784
  $ assistant memory retrospective run abc123`,
783
785
  },
786
+ {
787
+ name: "list",
788
+ description: "List the most-recently-run retrospective state rows",
789
+ options: [
790
+ {
791
+ flags: "--limit <n>",
792
+ description: "Max rows to return (default 10, max 200)",
793
+ },
794
+ {
795
+ flags: "--json",
796
+ description: "Machine-readable compact JSON output",
797
+ },
798
+ ],
799
+ helpText: `
800
+ Reads the memory_retrospective_state table directly from the workspace SQLite
801
+ database and prints the most-recently-run state rows, newest first. No daemon
802
+ required. Each row shows the source conversation ID, when the retrospective last
803
+ ran, how many memory entries are currently retained in the dedup log (capped at
804
+ 100 entries / 8 KB — older entries are dropped as new ones arrive, so RETAINED
805
+ reflects the live dedup window, not a cumulative save count), and whether any
806
+ pass has yet succeeded (status "ok") or only failed attempts exist ("pending").
807
+
808
+ Examples:
809
+ $ assistant memory retrospective list
810
+ $ assistant memory retrospective list --limit 20
811
+ $ assistant memory retrospective list --json`,
812
+ },
784
813
  ],
785
814
  },
786
815
  {
@@ -8,7 +8,7 @@
8
8
  * Subcommands:
9
9
  *
10
10
  * - `run <conversationId>` — run a fork-based retrospective on a conversation.
11
- * - `list` — list the last five retrospectives (TODO).
11
+ * - `list` — list the most-recently-run retrospective state rows.
12
12
  */
13
13
 
14
14
  import type { Command } from "commander";
@@ -54,12 +54,79 @@ export function registerMemoryRetrospectiveCommand(memory: Command): void {
54
54
  renderOutcome(outcome);
55
55
  },
56
56
  );
57
+
58
+ // ── list ──────────────────────────────────────────────────────────────
59
+
60
+ subcommand(retro, "list")
61
+ .alias("ls")
62
+ .action(async (opts: { limit?: string; json?: boolean }, cmd: Command) => {
63
+ const limit = Math.min(
64
+ 200,
65
+ Math.max(1, opts.limit !== undefined ? parseInt(opts.limit, 10) : 10),
66
+ );
67
+ if (isNaN(limit)) {
68
+ log.error("--limit must be a number.");
69
+ process.exitCode = 1;
70
+ return;
71
+ }
72
+
73
+ const { listRetrospectiveStates } =
74
+ await import("../../../plugins/defaults/memory/memory-retrospective-state.js");
75
+ const rows = listRetrospectiveStates(limit);
76
+
77
+ if (opts.json) {
78
+ writeOutput(cmd, { rows, total: rows.length });
79
+ return;
80
+ }
81
+
82
+ renderList(rows);
83
+ });
57
84
  }
58
85
 
59
86
  // ---------------------------------------------------------------------------
60
87
  // Human-readable rendering
61
88
  // ---------------------------------------------------------------------------
62
89
 
90
+ interface RetrospectiveStateRow {
91
+ conversationId: string;
92
+ lastProcessedMessageId: string;
93
+ lastRunAt: number;
94
+ rememberedLog: string[];
95
+ }
96
+
97
+ function renderList(rows: RetrospectiveStateRow[]): void {
98
+ if (rows.length === 0) {
99
+ log.info("No retrospective state found. Run a retrospective first with:");
100
+ log.info(" assistant memory retrospective run <conversationId>");
101
+ return;
102
+ }
103
+
104
+ const DATE_WIDTH = 20;
105
+ const CONV_WIDTH = 12;
106
+ const MEM_WIDTH = 10;
107
+
108
+ console.log(
109
+ `${"CONVERSATION".padEnd(CONV_WIDTH)} ${"LAST RUN".padEnd(DATE_WIDTH)} ${"RETAINED".padEnd(MEM_WIDTH)} STATUS`,
110
+ );
111
+
112
+ for (const row of rows) {
113
+ const conv = row.conversationId.slice(0, CONV_WIDTH - 1).padEnd(CONV_WIDTH);
114
+ const runAt = new Date(row.lastRunAt).toLocaleString("en-US", {
115
+ month: "short",
116
+ day: "numeric",
117
+ year: "numeric",
118
+ hour: "numeric",
119
+ minute: "2-digit",
120
+ });
121
+ const retained = String(row.rememberedLog.length).padEnd(MEM_WIDTH);
122
+ const status =
123
+ row.lastProcessedMessageId === "" ? "pending (no success yet)" : "ok";
124
+ console.log(`${conv} ${runAt.padEnd(DATE_WIDTH)} ${retained} ${status}`);
125
+ }
126
+
127
+ console.log(`\n${rows.length} row${rows.length === 1 ? "" : "s"}`);
128
+ }
129
+
63
130
  function renderOutcome(outcome: MemoryRetrospectiveOutcome): void {
64
131
  switch (outcome.kind) {
65
132
  case "disabled":
@@ -73,6 +73,12 @@ const LOUD_CHUNK = pcm(8_000);
73
73
  // chunk trips barge-in. Must stay above that default.
74
74
  const SUSTAINED_LOUD_CHUNK = pcm(8_000, 7_200);
75
75
  const SILENT_CHUNK = pcm(0);
76
+ // A sub-threshold "ducked" chunk. While the assistant is audibly playing, the
77
+ // browser's half-duplex echo canceller attenuates the user's near-end voice, so
78
+ // the server classifies the post-AEC audio as below the speech-energy gate:
79
+ // a barge-in mid-playback arrives as loud runs split by these ducked gaps.
80
+ // 10 ms at 24 kHz, mean amplitude well under the 800 threshold.
81
+ const DUCKED_CHUNK = pcm(200);
76
82
 
77
83
  class MockStreamingTranscriber implements StreamingTranscriber {
78
84
  readonly providerId = "deepgram" as const;
@@ -2443,31 +2449,118 @@ describe("LiveVoiceSession sustained-speech barge-in guard", () => {
2443
2449
  await waitFor(() => abort.mock.calls.length === 1);
2444
2450
  });
2445
2451
 
2446
- test("a non-speech chunk resets the sustained-speech run", async () => {
2447
- const { frames, session, speakFirstReply } = createSpeakingTurnHarness({
2448
- bargeInMinSpeechMs: 60,
2449
- });
2452
+ test("a brief sub-threshold gap does not reset the sustained-speech run", async () => {
2453
+ const { frames, session, abort, speakFirstReply } =
2454
+ createSpeakingTurnHarness({ bargeInMinSpeechMs: 60 });
2450
2455
  await speakFirstReply();
2451
2456
 
2452
- // 50 ms of speech, a silence blip, then 50 ms more: neither run reaches
2453
- // the guard because the blip zeroes the accumulator.
2457
+ // 50 ms of speech, then one ducked gap: while the assistant is playing, the
2458
+ // half-duplex echo canceller attenuates the user's voice, so the server
2459
+ // sees a sub-threshold chunk mid-utterance. The gap (10 ms) is far shorter
2460
+ // than BARGE_IN_GAP_TOLERANCE_MS, so it must NOT zero the run.
2454
2461
  for (let index = 0; index < 5; index += 1) {
2455
2462
  await session.handleBinaryAudio(LOUD_CHUNK);
2456
2463
  }
2457
- await session.handleBinaryAudio(SILENT_CHUNK);
2464
+ await session.handleBinaryAudio(DUCKED_CHUNK);
2465
+ await flushAsyncCallbacks();
2466
+ expect(countType(frames, "turn_cancelled")).toBe(0);
2467
+
2468
+ // A single further speech chunk carries the retained 50 ms run across the
2469
+ // gap to the 60 ms guard and cancels: the gap left the accumulator intact,
2470
+ // so one more 10 ms chunk is enough rather than a fresh 60 ms run.
2471
+ await session.handleBinaryAudio(LOUD_CHUNK);
2472
+ await waitFor(() =>
2473
+ frames.some((frame) => frame.type === "turn_cancelled"),
2474
+ );
2475
+ expect(
2476
+ frames.find((frame) => frame.type === "turn_cancelled"),
2477
+ ).toMatchObject({ type: "turn_cancelled", turnId: "live-turn-1" });
2478
+ await waitFor(() => abort.mock.calls.length === 1);
2479
+ });
2480
+
2481
+ test("a gap longer than the tolerance resets the sustained-speech run", async () => {
2482
+ const { frames, session, abort, speakFirstReply } =
2483
+ createSpeakingTurnHarness({ bargeInMinSpeechMs: 60 });
2484
+ await speakFirstReply();
2485
+
2486
+ // 50 ms of speech, then a ducked gap longer than BARGE_IN_GAP_TOLERANCE_MS
2487
+ // (25 chunks = 250 ms): a real pause rather than a syllable boundary, so the
2488
+ // run resets. The harness silence threshold is 5 s, so the detector never
2489
+ // ends the utterance here — the reset is the gap-tolerance logic, not
2490
+ // utterance end.
2491
+ for (let index = 0; index < 5; index += 1) {
2492
+ await session.handleBinaryAudio(LOUD_CHUNK);
2493
+ }
2494
+ for (let index = 0; index < 25; index += 1) {
2495
+ await session.handleBinaryAudio(DUCKED_CHUNK);
2496
+ }
2497
+ // 50 ms more speech: because the run reset, this accumulates from zero and
2498
+ // stays under the 60 ms guard — the two stretches do not sum across the long
2499
+ // gap into a false barge-in.
2458
2500
  for (let index = 0; index < 5; index += 1) {
2459
2501
  await session.handleBinaryAudio(LOUD_CHUNK);
2460
2502
  }
2461
2503
  await flushAsyncCallbacks();
2462
2504
  expect(countType(frames, "turn_cancelled")).toBe(0);
2505
+ expect(abort).not.toHaveBeenCalled();
2463
2506
 
2464
- // A 6th consecutive speech chunk completes a full 60 ms run.
2507
+ // A 6th consecutive speech chunk (with the 5 above) completes a fresh 60 ms
2508
+ // run after the reset and cancels normally.
2465
2509
  await session.handleBinaryAudio(LOUD_CHUNK);
2466
2510
  await waitFor(() =>
2467
2511
  frames.some((frame) => frame.type === "turn_cancelled"),
2468
2512
  );
2469
2513
  });
2470
2514
 
2515
+ test("a gap of exactly the tolerance is tolerated and does not reset the run", async () => {
2516
+ const { frames, session, abort, speakFirstReply } =
2517
+ createSpeakingTurnHarness({ bargeInMinSpeechMs: 60 });
2518
+ await speakFirstReply();
2519
+
2520
+ // 50 ms of speech, then a ducked gap of exactly BARGE_IN_GAP_TOLERANCE_MS
2521
+ // (20 chunks = 200 ms). The tolerance is inclusive — the web client batches
2522
+ // PCM into 50 ms frames, so a ducked run lands on the boundary exactly — so
2523
+ // this gap does not reset the accumulated speech.
2524
+ for (let index = 0; index < 5; index += 1) {
2525
+ await session.handleBinaryAudio(LOUD_CHUNK);
2526
+ }
2527
+ for (let index = 0; index < 20; index += 1) {
2528
+ await session.handleBinaryAudio(DUCKED_CHUNK);
2529
+ }
2530
+ // One more speech chunk carries the retained 50 ms run to the 60 ms guard
2531
+ // and cancels — proof the exactly-200 ms gap left the accumulator intact.
2532
+ await session.handleBinaryAudio(LOUD_CHUNK);
2533
+ await waitFor(() =>
2534
+ frames.some((frame) => frame.type === "turn_cancelled"),
2535
+ );
2536
+ expect(
2537
+ frames.find((frame) => frame.type === "turn_cancelled"),
2538
+ ).toMatchObject({ type: "turn_cancelled", turnId: "live-turn-1" });
2539
+ await waitFor(() => abort.mock.calls.length === 1);
2540
+ });
2541
+
2542
+ test("sparse periodic blips separated by boundary gaps do not accumulate into a barge-in", async () => {
2543
+ const { frames, session, abort, speakFirstReply } =
2544
+ createSpeakingTurnHarness({ bargeInMinSpeechMs: 60 });
2545
+ await speakFirstReply();
2546
+
2547
+ // A 10 ms blip every 200 ms models residual echo/noise, not sustained
2548
+ // speech: each blip clears the consecutive-gap timer while the boundary gap
2549
+ // (20 chunks = 200 ms) escapes the per-gap reset. Enough cycles to reach the
2550
+ // 60 ms guard by pure blip-summing (6 blips) plus margin. The duty-cycle
2551
+ // ceiling (cumulative tolerated silence > bargeInMinSpeechMs * 4 = 240 ms)
2552
+ // resets the run every few cycles, so the blips never sum into a barge-in.
2553
+ for (let cycle = 0; cycle < 9; cycle += 1) {
2554
+ await session.handleBinaryAudio(LOUD_CHUNK);
2555
+ for (let index = 0; index < 20; index += 1) {
2556
+ await session.handleBinaryAudio(DUCKED_CHUNK);
2557
+ }
2558
+ }
2559
+ await flushAsyncCallbacks();
2560
+ expect(countType(frames, "turn_cancelled")).toBe(0);
2561
+ expect(abort).not.toHaveBeenCalled();
2562
+ });
2563
+
2471
2564
  test("bargeInMinSpeechMs 0 restores instant barge-in", async () => {
2472
2565
  const { frames, session, abort, speakFirstReply } =
2473
2566
  createSpeakingTurnHarness({ bargeInMinSpeechMs: 0 });
@@ -109,6 +109,24 @@ const FINALIZE_GRACE_MS = 1_000;
109
109
  // liveVoice.vad.bargeInMinSpeechMs schema default; 0 disables the guard for
110
110
  // instant barge-in.
111
111
  const DEFAULT_BARGE_IN_MIN_SPEECH_MS = 250;
112
+ // Longest continuous sub-threshold gap the sustained-speech barge-in run
113
+ // tolerates without resetting. A gap this short is a syllable boundary, or the
114
+ // choppy energy the browser's half-duplex echo canceller produces while the
115
+ // assistant is still playing (it ducks the user's near-end voice, so post-AEC
116
+ // user speech arrives as intermittent above-gate chunks) — so the run keeps
117
+ // accumulating across it and a barge-in during playback still lands. Only a
118
+ // longer continuous silence (a real end of speech, or an isolated cough) resets
119
+ // the run.
120
+ const BARGE_IN_GAP_TOLERANCE_MS = 200;
121
+ // Ceiling on cumulative sub-threshold time across a whole barge-in run, as a
122
+ // multiple of bargeInMinSpeechMs. Per-gap tolerance alone lets sparse isolated
123
+ // blips (e.g. a 10 ms echo spike every 200 ms) each clear the consecutive-gap
124
+ // timer while retaining prior speech, so they would sum to the guard over
125
+ // several seconds and fire a barge-in with no sustained user speech. Capping the
126
+ // run's total tolerated silence imposes a minimum above-gate duty cycle
127
+ // (1 / (1 + ratio) ≈ 20%): once the run is mostly silence it resets, so genuine
128
+ // choppy speech still lands but periodic noise cannot accumulate into one.
129
+ const BARGE_IN_MAX_TOLERATED_SILENCE_RATIO = 4;
112
130
  // At most this many TTS segment jobs are open (provider stream started,
113
131
  // frames not yet fully emitted) per turn: the emitting job plus one
114
132
  // prefetching job. The prefetch buffers its chunks in memory until promoted;
@@ -457,15 +475,25 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
457
475
  // sensitivity" live (see applyConfigUpdate).
458
476
  private bargeInMinSpeechMs: number;
459
477
  // Sustained-speech barge-in guard, armed at speech onset while the
460
- // assistant turn is audibly speaking: consecutive speech-chunk duration
478
+ // assistant turn is audibly speaking: above-gate speech-chunk duration
461
479
  // accumulates until it reaches bargeInMinSpeechMs, then the deferred
462
- // speech_started + barge-in fire (at most once per onset). A non-speech
463
- // chunk zeroes the run; the detector's utterance end discards the guard.
480
+ // speech_started + barge-in fire (at most once per onset). Brief sub-threshold
481
+ // gaps are tolerated (see BARGE_IN_GAP_TOLERANCE_MS); the run resets on a
482
+ // single longer continuous silence, or once cumulative tolerated silence
483
+ // exceeds the duty-cycle ceiling (see BARGE_IN_MAX_TOLERATED_SILENCE_RATIO).
484
+ // The detector's utterance end discards the guard.
464
485
  private pendingBargeIn: {
465
486
  // Null when guarding only the post-tts_done drain window (the turn is
466
487
  // already finalized but the client is still playing its tail).
467
488
  turn: ActiveAssistantTurn | null;
468
489
  speechMs: number;
490
+ // Consecutive sub-threshold (non-speech) time since the last speech chunk;
491
+ // resets speechMs once it exceeds BARGE_IN_GAP_TOLERANCE_MS.
492
+ silenceMs: number;
493
+ // Cumulative sub-threshold time over the whole run (not reset by speech
494
+ // chunks); resets speechMs once it exceeds the duty-cycle ceiling so sparse
495
+ // periodic blips cannot sum into a barge-in.
496
+ toleratedSilenceMs: number;
469
497
  } | null = null;
470
498
  // Estimated wall-clock ms until the client finishes draining the
471
499
  // assistant audio sent so far. The server clears the turn right after
@@ -1091,7 +1119,12 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1091
1119
  if ((bargeableTurn || drainingPlayback) && this.bargeInMinSpeechMs > 0) {
1092
1120
  // Onset audio keeps flowing into the cycle/pre-roll while the guard
1093
1121
  // accumulates (trackBargeInGuard), so no speech is lost either way.
1094
- this.pendingBargeIn = { turn: bargeableTurn, speechMs: 0 };
1122
+ this.pendingBargeIn = {
1123
+ turn: bargeableTurn,
1124
+ speechMs: 0,
1125
+ silenceMs: 0,
1126
+ toleratedSilenceMs: 0,
1127
+ };
1095
1128
  return;
1096
1129
  }
1097
1130
 
@@ -1104,22 +1137,42 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1104
1137
  }
1105
1138
 
1106
1139
  // Advances the sustained-speech barge-in guard by one server-VAD chunk:
1107
- // consecutive speech accumulates toward bargeInMinSpeechMs (a non-speech
1108
- // chunk zeroes the run) and, once met, the deferred speech_started +
1109
- // barge-in fire.
1140
+ // above-gate speech accumulates toward bargeInMinSpeechMs while brief
1141
+ // sub-threshold gaps are tolerated (a single continuous silence longer than
1142
+ // BARGE_IN_GAP_TOLERANCE_MS, or cumulative tolerated silence past the
1143
+ // duty-cycle ceiling, zeroes the run), and once met the deferred
1144
+ // speech_started + barge-in fire.
1110
1145
  private trackBargeInGuard(hasSpeech: boolean, chunk: Buffer): void {
1111
1146
  const guard = this.pendingBargeIn;
1112
1147
  if (!guard) {
1113
1148
  return;
1114
1149
  }
1115
- if (!hasSpeech) {
1116
- guard.speechMs = 0;
1117
- return;
1118
- }
1119
- guard.speechMs += pcm16DurationMs(
1150
+ const chunkMs = pcm16DurationMs(
1120
1151
  chunk.byteLength,
1121
1152
  this.context.startFrame.audio.sampleRate,
1122
1153
  );
1154
+ if (!hasSpeech) {
1155
+ guard.silenceMs += chunkMs;
1156
+ guard.toleratedSilenceMs += chunkMs;
1157
+ // Strictly greater on the per-gap check: a gap of exactly
1158
+ // BARGE_IN_GAP_TOLERANCE_MS is still tolerated. The web client batches PCM
1159
+ // into 50 ms frames, so a run of ducked frames lands on the boundary
1160
+ // exactly (e.g. four frames = 200 ms). The run also resets once its total
1161
+ // tolerated silence outweighs the speech by the duty-cycle ceiling, so
1162
+ // sparse periodic blips can never sum to the guard.
1163
+ if (
1164
+ guard.silenceMs > BARGE_IN_GAP_TOLERANCE_MS ||
1165
+ guard.toleratedSilenceMs >
1166
+ this.bargeInMinSpeechMs * BARGE_IN_MAX_TOLERATED_SILENCE_RATIO
1167
+ ) {
1168
+ guard.speechMs = 0;
1169
+ guard.silenceMs = 0;
1170
+ guard.toleratedSilenceMs = 0;
1171
+ }
1172
+ return;
1173
+ }
1174
+ guard.silenceMs = 0;
1175
+ guard.speechMs += chunkMs;
1123
1176
  if (guard.speechMs < this.bargeInMinSpeechMs) {
1124
1177
  return;
1125
1178
  }
@@ -1,6 +1,11 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
 
3
- import { parseExtractionResponse } from "./extraction.js";
3
+ import type { DeferredEdge } from "./extraction.js";
4
+ import {
5
+ applySupersessionDurability,
6
+ parseExtractionResponse,
7
+ } from "./extraction.js";
8
+ import type { MemoryDiff, MemoryNode, NewNode } from "./types.js";
4
9
 
5
10
  // ---------------------------------------------------------------------------
6
11
  // Helpers
@@ -1219,3 +1224,323 @@ describe("parseExtractionResponse — robustness", () => {
1219
1224
  expect(diff.reinforceNodeIds).toEqual([]);
1220
1225
  });
1221
1226
  });
1227
+
1228
+ // ---------------------------------------------------------------------------
1229
+ // applySupersessionDurability
1230
+ // ---------------------------------------------------------------------------
1231
+
1232
+ function mockNode(overrides: Partial<MemoryNode> = {}): MemoryNode {
1233
+ return {
1234
+ id: "node-x",
1235
+ content: "Some fact.",
1236
+ type: "semantic",
1237
+ created: NOW,
1238
+ lastAccessed: NOW,
1239
+ lastConsolidated: NOW,
1240
+ eventDate: null,
1241
+ emotionalCharge: {
1242
+ valence: 0,
1243
+ intensity: 0,
1244
+ decayCurve: "linear",
1245
+ decayRate: 0.05,
1246
+ originalIntensity: 0,
1247
+ },
1248
+ fidelity: "vivid",
1249
+ confidence: 0.8,
1250
+ significance: 0.5,
1251
+ stability: 14,
1252
+ reinforcementCount: 0,
1253
+ lastReinforced: NOW,
1254
+ sourceConversations: [CONV_ID],
1255
+ sourceType: "direct",
1256
+ narrativeRole: null,
1257
+ partOfStory: null,
1258
+ imageRefs: null,
1259
+ ...overrides,
1260
+ };
1261
+ }
1262
+
1263
+ function emptyDiff(): MemoryDiff {
1264
+ return {
1265
+ createNodes: [],
1266
+ updateNodes: [],
1267
+ deleteNodeIds: [],
1268
+ createEdges: [],
1269
+ deleteEdgeIds: [],
1270
+ createTriggers: [],
1271
+ deleteTriggerIds: [],
1272
+ reinforceNodeIds: [],
1273
+ };
1274
+ }
1275
+
1276
+ function newNodeStub(overrides: Partial<NewNode> = {}): NewNode {
1277
+ return {
1278
+ content: "New fact.",
1279
+ type: "semantic",
1280
+ created: NOW,
1281
+ lastAccessed: NOW,
1282
+ lastConsolidated: NOW,
1283
+ eventDate: null,
1284
+ emotionalCharge: {
1285
+ valence: 0,
1286
+ intensity: 0,
1287
+ decayCurve: "linear",
1288
+ decayRate: 0.05,
1289
+ originalIntensity: 0,
1290
+ },
1291
+ fidelity: "vivid",
1292
+ confidence: 0.8,
1293
+ significance: 0.5,
1294
+ stability: 14,
1295
+ reinforcementCount: 0,
1296
+ lastReinforced: NOW,
1297
+ sourceConversations: [CONV_ID],
1298
+ sourceType: "direct",
1299
+ narrativeRole: null,
1300
+ partOfStory: null,
1301
+ imageRefs: null,
1302
+ ...overrides,
1303
+ };
1304
+ }
1305
+
1306
+ describe("applySupersessionDurability — new→existing", () => {
1307
+ test("new node inherits stability from superseded node when old is higher", () => {
1308
+ const diff = emptyDiff();
1309
+ diff.createNodes.push(newNodeStub({ stability: 14 }));
1310
+
1311
+ const deferredEdges: DeferredEdge[] = [
1312
+ {
1313
+ source: { kind: "new", newNodeIndex: 0 },
1314
+ target: { kind: "existing", nodeId: "old-1" },
1315
+ relationship: "supersedes",
1316
+ weight: 1,
1317
+ },
1318
+ ];
1319
+
1320
+ const nodeMap = new Map([
1321
+ ["old-1", mockNode({ id: "old-1", stability: 45 })],
1322
+ ]);
1323
+
1324
+ applySupersessionDurability(diff, deferredEdges, nodeMap);
1325
+
1326
+ expect(diff.createNodes[0].stability).toBe(45);
1327
+ });
1328
+
1329
+ test("new node keeps its own higher stability when it exceeds old node", () => {
1330
+ const diff = emptyDiff();
1331
+ diff.createNodes.push(newNodeStub({ stability: 60 }));
1332
+
1333
+ const deferredEdges: DeferredEdge[] = [
1334
+ {
1335
+ source: { kind: "new", newNodeIndex: 0 },
1336
+ target: { kind: "existing", nodeId: "old-1" },
1337
+ relationship: "supersedes",
1338
+ weight: 1,
1339
+ },
1340
+ ];
1341
+
1342
+ const nodeMap = new Map([
1343
+ ["old-1", mockNode({ id: "old-1", stability: 30 })],
1344
+ ]);
1345
+
1346
+ applySupersessionDurability(diff, deferredEdges, nodeMap);
1347
+
1348
+ expect(diff.createNodes[0].stability).toBe(60);
1349
+ });
1350
+
1351
+ test("new node inherits reinforcementCount from superseded node", () => {
1352
+ const diff = emptyDiff();
1353
+ diff.createNodes.push(newNodeStub({ reinforcementCount: 0 }));
1354
+
1355
+ const deferredEdges: DeferredEdge[] = [
1356
+ {
1357
+ source: { kind: "new", newNodeIndex: 0 },
1358
+ target: { kind: "existing", nodeId: "old-1" },
1359
+ relationship: "supersedes",
1360
+ weight: 1,
1361
+ },
1362
+ ];
1363
+
1364
+ const nodeMap = new Map([
1365
+ ["old-1", mockNode({ id: "old-1", reinforcementCount: 3 })],
1366
+ ]);
1367
+
1368
+ applySupersessionDurability(diff, deferredEdges, nodeMap);
1369
+
1370
+ expect(diff.createNodes[0].reinforcementCount).toBe(3);
1371
+ });
1372
+
1373
+ test("new node significance becomes max of new and old", () => {
1374
+ const diff = emptyDiff();
1375
+ diff.createNodes.push(newNodeStub({ significance: 0.4 }));
1376
+
1377
+ const deferredEdges: DeferredEdge[] = [
1378
+ {
1379
+ source: { kind: "new", newNodeIndex: 0 },
1380
+ target: { kind: "existing", nodeId: "old-1" },
1381
+ relationship: "supersedes",
1382
+ weight: 1,
1383
+ },
1384
+ ];
1385
+
1386
+ const nodeMap = new Map([
1387
+ ["old-1", mockNode({ id: "old-1", significance: 0.8 })],
1388
+ ]);
1389
+
1390
+ applySupersessionDurability(diff, deferredEdges, nodeMap);
1391
+
1392
+ expect(diff.createNodes[0].significance).toBe(0.8);
1393
+ });
1394
+
1395
+ test("non-supersedes edges are not touched", () => {
1396
+ const diff = emptyDiff();
1397
+ diff.createNodes.push(
1398
+ newNodeStub({ stability: 14, reinforcementCount: 0 }),
1399
+ );
1400
+
1401
+ const deferredEdges: DeferredEdge[] = [
1402
+ {
1403
+ source: { kind: "new", newNodeIndex: 0 },
1404
+ target: { kind: "existing", nodeId: "old-1" },
1405
+ relationship: "caused-by",
1406
+ weight: 1,
1407
+ },
1408
+ ];
1409
+
1410
+ const nodeMap = new Map([
1411
+ [
1412
+ "old-1",
1413
+ mockNode({ id: "old-1", stability: 50, reinforcementCount: 5 }),
1414
+ ],
1415
+ ]);
1416
+
1417
+ applySupersessionDurability(diff, deferredEdges, nodeMap);
1418
+
1419
+ expect(diff.createNodes[0].stability).toBe(14);
1420
+ expect(diff.createNodes[0].reinforcementCount).toBe(0);
1421
+ });
1422
+
1423
+ test("skips gracefully when target not in candidate map", () => {
1424
+ const diff = emptyDiff();
1425
+ diff.createNodes.push(newNodeStub({ stability: 14 }));
1426
+
1427
+ const deferredEdges: DeferredEdge[] = [
1428
+ {
1429
+ source: { kind: "new", newNodeIndex: 0 },
1430
+ target: { kind: "existing", nodeId: "ghost-id" },
1431
+ relationship: "supersedes",
1432
+ weight: 1,
1433
+ },
1434
+ ];
1435
+
1436
+ applySupersessionDurability(diff, deferredEdges, new Map());
1437
+
1438
+ expect(diff.createNodes[0].stability).toBe(14);
1439
+ });
1440
+ });
1441
+
1442
+ describe("applySupersessionDurability — existing→existing", () => {
1443
+ test("adds updateNode entry for superseding existing node", () => {
1444
+ const diff = emptyDiff();
1445
+ diff.createEdges.push({
1446
+ sourceNodeId: "new-fact",
1447
+ targetNodeId: "old-fact",
1448
+ relationship: "supersedes",
1449
+ weight: 1,
1450
+ created: NOW,
1451
+ });
1452
+
1453
+ const nodeMap = new Map([
1454
+ [
1455
+ "new-fact",
1456
+ mockNode({
1457
+ id: "new-fact",
1458
+ stability: 14,
1459
+ reinforcementCount: 0,
1460
+ significance: 0.5,
1461
+ }),
1462
+ ],
1463
+ [
1464
+ "old-fact",
1465
+ mockNode({
1466
+ id: "old-fact",
1467
+ stability: 40,
1468
+ reinforcementCount: 2,
1469
+ significance: 0.7,
1470
+ }),
1471
+ ],
1472
+ ]);
1473
+
1474
+ applySupersessionDurability(diff, [], nodeMap);
1475
+
1476
+ expect(diff.updateNodes).toHaveLength(1);
1477
+ const update = diff.updateNodes[0];
1478
+ expect(update.id).toBe("new-fact");
1479
+ expect(update.changes.stability).toBe(40);
1480
+ expect(update.changes.reinforcementCount).toBe(2);
1481
+ expect(update.changes.significance).toBe(0.7);
1482
+ });
1483
+
1484
+ test("merges into existing updateNode rather than adding a duplicate", () => {
1485
+ const diff = emptyDiff();
1486
+ diff.updateNodes.push({
1487
+ id: "new-fact",
1488
+ changes: { content: "Corrected content.", significance: 0.9 },
1489
+ });
1490
+ diff.createEdges.push({
1491
+ sourceNodeId: "new-fact",
1492
+ targetNodeId: "old-fact",
1493
+ relationship: "supersedes",
1494
+ weight: 1,
1495
+ created: NOW,
1496
+ });
1497
+
1498
+ const nodeMap = new Map([
1499
+ [
1500
+ "new-fact",
1501
+ mockNode({
1502
+ id: "new-fact",
1503
+ stability: 14,
1504
+ reinforcementCount: 0,
1505
+ significance: 0.6,
1506
+ }),
1507
+ ],
1508
+ [
1509
+ "old-fact",
1510
+ mockNode({
1511
+ id: "old-fact",
1512
+ stability: 35,
1513
+ reinforcementCount: 4,
1514
+ significance: 0.7,
1515
+ }),
1516
+ ],
1517
+ ]);
1518
+
1519
+ applySupersessionDurability(diff, [], nodeMap);
1520
+
1521
+ expect(diff.updateNodes).toHaveLength(1);
1522
+ const update = diff.updateNodes[0];
1523
+ expect(update.changes.content).toBe("Corrected content.");
1524
+ expect(update.changes.stability).toBe(35);
1525
+ expect(update.changes.reinforcementCount).toBe(4);
1526
+ // LLM said 0.9, old had 0.7 — max wins
1527
+ expect(update.changes.significance).toBe(0.9);
1528
+ });
1529
+
1530
+ test("skips gracefully when target not in candidate map", () => {
1531
+ const diff = emptyDiff();
1532
+ diff.createEdges.push({
1533
+ sourceNodeId: "new-fact",
1534
+ targetNodeId: "ghost",
1535
+ relationship: "supersedes",
1536
+ weight: 1,
1537
+ created: NOW,
1538
+ });
1539
+
1540
+ const nodeMap = new Map([["new-fact", mockNode({ id: "new-fact" })]]);
1541
+
1542
+ applySupersessionDurability(diff, [], nodeMap);
1543
+
1544
+ expect(diff.updateNodes).toHaveLength(0);
1545
+ });
1546
+ });
@@ -38,6 +38,7 @@ import type {
38
38
  Fidelity,
39
39
  ImageRef,
40
40
  MemoryDiff,
41
+ MemoryNode,
41
42
  MemoryType,
42
43
  NewEdge,
43
44
  NewNode,
@@ -582,6 +583,109 @@ export interface DeferredEdge {
582
583
  weight: number;
583
584
  }
584
585
 
586
+ /**
587
+ * Inherit durability from the superseded (old) node into the superseding
588
+ * (new/updated) node. Called after parsing the LLM diff but before applying
589
+ * it to the store.
590
+ *
591
+ * Without this, a superseding node starts with zero reinforcement history and
592
+ * decays faster than the stale fact it was meant to retire — the old memory
593
+ * wins the next significance race even though it has been explicitly replaced.
594
+ *
595
+ * Two cases handled:
596
+ * 1. existing→existing edge in diff.createEdges: the source (superseding)
597
+ * existing node gets an updateNode entry that carries over stability,
598
+ * reinforcementCount, and significance (taking the max of both nodes so
599
+ * the superseding node is never downgraded).
600
+ * 2. new→existing edge in deferredEdges: the new node in diff.createNodes is
601
+ * mutated in place before applyDiff runs.
602
+ */
603
+ export function applySupersessionDurability(
604
+ diff: MemoryDiff,
605
+ deferredEdges: DeferredEdge[],
606
+ candidateNodeMap: Map<string, MemoryNode>,
607
+ ): void {
608
+ // Case 1: existing→existing supersession (both endpoints in candidateNodes)
609
+ for (const edge of diff.createEdges) {
610
+ if (edge.relationship !== "supersedes") {
611
+ continue;
612
+ }
613
+ const target = candidateNodeMap.get(edge.targetNodeId);
614
+ if (!target) {
615
+ continue;
616
+ }
617
+ const source = candidateNodeMap.get(edge.sourceNodeId);
618
+
619
+ const inheritedStability = Math.max(
620
+ source?.stability ?? 14,
621
+ target.stability,
622
+ );
623
+ const inheritedCount = Math.max(
624
+ source?.reinforcementCount ?? 0,
625
+ target.reinforcementCount,
626
+ );
627
+ const inheritedSignificance = Math.max(
628
+ source?.significance ?? 0,
629
+ target.significance,
630
+ );
631
+
632
+ const existing = diff.updateNodes.find((u) => u.id === edge.sourceNodeId);
633
+ if (existing) {
634
+ existing.changes.stability = Math.max(
635
+ (existing.changes.stability as number | undefined) ??
636
+ source?.stability ??
637
+ 14,
638
+ inheritedStability,
639
+ );
640
+ existing.changes.reinforcementCount = Math.max(
641
+ (existing.changes.reinforcementCount as number | undefined) ??
642
+ source?.reinforcementCount ??
643
+ 0,
644
+ inheritedCount,
645
+ );
646
+ existing.changes.significance = Math.max(
647
+ (existing.changes.significance as number | undefined) ??
648
+ source?.significance ??
649
+ 0,
650
+ inheritedSignificance,
651
+ );
652
+ } else {
653
+ diff.updateNodes.push({
654
+ id: edge.sourceNodeId,
655
+ changes: {
656
+ stability: inheritedStability,
657
+ reinforcementCount: inheritedCount,
658
+ significance: inheritedSignificance,
659
+ },
660
+ });
661
+ }
662
+ }
663
+
664
+ // Case 2: new→existing supersession (the typical case from extraction)
665
+ for (const de of deferredEdges) {
666
+ if (de.relationship !== "supersedes") {
667
+ continue;
668
+ }
669
+ if (de.source.kind !== "new" || de.target.kind !== "existing") {
670
+ continue;
671
+ }
672
+ const target = candidateNodeMap.get(de.target.nodeId);
673
+ if (!target) {
674
+ continue;
675
+ }
676
+ const newNode = diff.createNodes[de.source.newNodeIndex];
677
+ if (!newNode) {
678
+ continue;
679
+ }
680
+ newNode.stability = Math.max(newNode.stability, target.stability);
681
+ newNode.reinforcementCount = Math.max(
682
+ newNode.reinforcementCount,
683
+ target.reinforcementCount,
684
+ );
685
+ newNode.significance = Math.max(newNode.significance, target.significance);
686
+ }
687
+ }
688
+
585
689
  export function parseExtractionResponse(
586
690
  input: Record<string, unknown>,
587
691
  conversationId: string,
@@ -1140,21 +1244,9 @@ export async function runGraphExtraction(
1140
1244
  conversationTimestamp,
1141
1245
  );
1142
1246
 
1143
- // 7. Handle supersession (inherit durability before applying diff)
1144
- // TODO: full supersession is not yet implemented. When it lands, iterate
1145
- // BOTH `diff.createEdges` (existing → existing) AND `deferredEdges`
1146
- // (new → existing, the typical supersession case).
1147
- // Tracked by https://github.com/vellum-ai/vellum-assistant/pull/27057 (Devin).
1148
- for (const edge of diff.createEdges) {
1149
- if (edge.relationship === "supersedes") {
1150
- // Placeholder — see TODO above.
1151
- }
1152
- }
1153
- for (const de of deferredEdges) {
1154
- if (de.relationship === "supersedes") {
1155
- // Placeholder — see TODO above.
1156
- }
1157
- }
1247
+ // 7. Inherit durability from superseded nodes before applying the diff.
1248
+ const candidateNodeMap = new Map(candidateNodes.map((n) => [n.id, n]));
1249
+ applySupersessionDurability(diff, deferredEdges, candidateNodeMap);
1158
1250
 
1159
1251
  // 8. Apply the diff
1160
1252
  const result = applyDiff(diff, { conversationId });
@@ -681,6 +681,8 @@ export function applyDiff(
681
681
  if (c.confidence !== undefined) updates.confidence = c.confidence;
682
682
  if (c.significance !== undefined) updates.significance = c.significance;
683
683
  if (c.stability !== undefined) updates.stability = c.stability;
684
+ if (c.reinforcementCount !== undefined)
685
+ updates.reinforcementCount = c.reinforcementCount;
684
686
  if (c.narrativeRole !== undefined)
685
687
  updates.narrativeRole = c.narrativeRole;
686
688
  if (c.partOfStory !== undefined) updates.partOfStory = c.partOfStory;
@@ -23,7 +23,7 @@
23
23
  // The schema enforces the foreign key with ON DELETE CASCADE, so deleting a
24
24
  // conversation collects its state row automatically.
25
25
 
26
- import { eq } from "drizzle-orm";
26
+ import { desc, eq } from "drizzle-orm";
27
27
 
28
28
  import { type DrizzleDb, getDb } from "../../../persistence/db-connection.js";
29
29
  import { memoryRetrospectiveState } from "../../../persistence/schema/index.js";
@@ -88,6 +88,26 @@ function serializeRememberedLog(log: string[]): string | null {
88
88
  return log.length === 0 ? null : JSON.stringify(log);
89
89
  }
90
90
 
91
+ /**
92
+ * Return the `limit` most-recently-run retrospective state rows, newest first.
93
+ */
94
+ export function listRetrospectiveStates(
95
+ limit: number,
96
+ ): MemoryRetrospectiveState[] {
97
+ const rows = getDb()
98
+ .select()
99
+ .from(memoryRetrospectiveState)
100
+ .orderBy(desc(memoryRetrospectiveState.lastRunAt))
101
+ .limit(limit)
102
+ .all();
103
+ return rows.map((row) => ({
104
+ conversationId: row.conversationId,
105
+ lastProcessedMessageId: row.lastProcessedMessageId,
106
+ lastRunAt: row.lastRunAt,
107
+ rememberedLog: parseRememberedLog(row.rememberedLog),
108
+ }));
109
+ }
110
+
91
111
  /**
92
112
  * Load the state row for a conversation, or `null` if no row exists.
93
113
  */