@vellumai/assistant 0.11.3-dev.202608101923.ff319b9 → 0.11.3-dev.202608102016.71d1d5b
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/docs/architecture/memory.md +6 -1
- package/package.json +1 -1
- package/src/__tests__/conversation-fork-crud.test.ts +69 -0
- package/src/__tests__/conversation-fork-referential.test.ts +67 -0
- package/src/__tests__/conversation-fork-retrospective.test.ts +24 -0
- package/src/persistence/conversation-crud.ts +33 -4
- package/src/persistence/conversation-lineage.ts +9 -0
- package/src/persistence/delivery-crud.ts +7 -0
- package/src/plugins/defaults/memory/__tests__/buffer-format.test.ts +57 -3
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-accounting.test.ts +72 -0
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-job.test.ts +4 -1
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-provider-path.test.ts +4 -1
- package/src/plugins/defaults/memory/buffer-format.ts +24 -1
- package/src/plugins/defaults/memory/context-search/sources/conversations.ts +6 -0
- package/src/plugins/defaults/memory/graph-topology/pending-buffer.test.ts +20 -1
- package/src/plugins/defaults/memory/memory-retrospective-accounting.ts +19 -7
- package/src/plugins/defaults/memory/substrate/__tests__/consolidation-job.test.ts +33 -0
|
@@ -80,7 +80,12 @@ graph LR
|
|
|
80
80
|
uses. A fact may span several lines, so the entry and the line are different
|
|
81
81
|
units, and the readers below (consolidation's cutoff, the injected `<info>`
|
|
82
82
|
Buffer cap, the Memory tab's pending nodes) all recognize entries through
|
|
83
|
-
that one matcher rather than their own.
|
|
83
|
+
that one matcher rather than their own. An entry opens with a timestamped
|
|
84
|
+
bullet at column 0 and its body is indented under it, which is what makes the
|
|
85
|
+
format round-trip: the delimiter is the column-0 bullet shape, so nesting the
|
|
86
|
+
body keeps fact content from imitating one. Entries written before that
|
|
87
|
+
nesting existed still parse, since an unindented body line that is not itself
|
|
88
|
+
entry-shaped is read as a continuation.
|
|
84
89
|
- **Consolidation** (`substrate/consolidation-job.ts`) is a background
|
|
85
90
|
agent conversation that files buffer entries into concept pages, rewrites
|
|
86
91
|
the aggregate views, and trims the buffer. Scheduling
|
package/package.json
CHANGED
|
@@ -1794,3 +1794,72 @@ describe("forkConversation + memory_retrospective_state", () => {
|
|
|
1794
1794
|
expect(fork.slackContextCompactionWatermarkAt).toBe(compactedAt);
|
|
1795
1795
|
});
|
|
1796
1796
|
});
|
|
1797
|
+
|
|
1798
|
+
describe("forkConversation with unfinalized rows", () => {
|
|
1799
|
+
beforeEach(() => {
|
|
1800
|
+
resetTables();
|
|
1801
|
+
});
|
|
1802
|
+
|
|
1803
|
+
test("skips unfinalized rows and anchors the fork at the last finalized message", async () => {
|
|
1804
|
+
const source = createConversation("Mid-turn fork");
|
|
1805
|
+
await addMessage(source.id, "user", "question", { skipIndexing: true });
|
|
1806
|
+
const lastFinalized = await addMessage(
|
|
1807
|
+
source.id,
|
|
1808
|
+
"assistant",
|
|
1809
|
+
"completed reply",
|
|
1810
|
+
{ skipIndexing: true },
|
|
1811
|
+
);
|
|
1812
|
+
const streaming = await addMessage(
|
|
1813
|
+
source.id,
|
|
1814
|
+
"assistant",
|
|
1815
|
+
"partial reply still being written",
|
|
1816
|
+
{ skipIndexing: true },
|
|
1817
|
+
);
|
|
1818
|
+
rawRun(
|
|
1819
|
+
"test:markUnfinalized",
|
|
1820
|
+
"UPDATE messages SET finalized = 0 WHERE id = ?",
|
|
1821
|
+
streaming.id,
|
|
1822
|
+
);
|
|
1823
|
+
|
|
1824
|
+
const fork = forkConversation({ conversationId: source.id });
|
|
1825
|
+
const forkMessages = getMessages(fork.id);
|
|
1826
|
+
|
|
1827
|
+
// The invariant, not mere presence: exactly the finalized rows were
|
|
1828
|
+
// copied, every copy reads as finalized, no copy descends from the
|
|
1829
|
+
// unfinalized source row, and the lineage anchor is a row the fork
|
|
1830
|
+
// actually holds.
|
|
1831
|
+
expect(forkMessages).toHaveLength(2);
|
|
1832
|
+
expect(forkMessages.every((row) => row.finalized === 1)).toBe(true);
|
|
1833
|
+
const forkedFromIds = forkMessages.map(
|
|
1834
|
+
(row) =>
|
|
1835
|
+
(parseMetadata(row.metadata) as { forkSourceMessageId?: string })
|
|
1836
|
+
?.forkSourceMessageId,
|
|
1837
|
+
);
|
|
1838
|
+
expect(forkedFromIds).not.toContain(streaming.id);
|
|
1839
|
+
expect(fork.forkParentMessageId).toBe(lastFinalized.id);
|
|
1840
|
+
// The source still owns its in-flight row untouched.
|
|
1841
|
+
expect(getMessages(source.id)).toHaveLength(3);
|
|
1842
|
+
});
|
|
1843
|
+
|
|
1844
|
+
test("a stale mid-history unfinalized row is skipped without shifting the anchor", async () => {
|
|
1845
|
+
const source = createConversation("Stale row fork");
|
|
1846
|
+
await addMessage(source.id, "user", "first", { skipIndexing: true });
|
|
1847
|
+
const stale = await addMessage(source.id, "assistant", "orphaned partial", {
|
|
1848
|
+
skipIndexing: true,
|
|
1849
|
+
});
|
|
1850
|
+
const tail = await addMessage(source.id, "user", "latest", {
|
|
1851
|
+
skipIndexing: true,
|
|
1852
|
+
});
|
|
1853
|
+
rawRun(
|
|
1854
|
+
"test:markUnfinalized",
|
|
1855
|
+
"UPDATE messages SET finalized = 0 WHERE id = ?",
|
|
1856
|
+
stale.id,
|
|
1857
|
+
);
|
|
1858
|
+
|
|
1859
|
+
const fork = forkConversation({ conversationId: source.id });
|
|
1860
|
+
const forkMessages = getMessages(fork.id);
|
|
1861
|
+
|
|
1862
|
+
expect(forkMessages).toHaveLength(2);
|
|
1863
|
+
expect(fork.forkParentMessageId).toBe(tail.id);
|
|
1864
|
+
});
|
|
1865
|
+
});
|
|
@@ -350,3 +350,70 @@ describe("referential forking", () => {
|
|
|
350
350
|
expect(textOf(getMessages(source.id))).toHaveLength(4);
|
|
351
351
|
});
|
|
352
352
|
});
|
|
353
|
+
|
|
354
|
+
describe("referential forking with unfinalized rows", () => {
|
|
355
|
+
beforeEach(() => {
|
|
356
|
+
resetTables();
|
|
357
|
+
clearConfig();
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
test("ancestor rows are hidden while unfinalized and appear once finalized", async () => {
|
|
361
|
+
const source = await seedSource("Launch");
|
|
362
|
+
const midRow = getMessages(source.id)[1]!;
|
|
363
|
+
getDb()
|
|
364
|
+
.update(messages)
|
|
365
|
+
.set({ finalized: 0 })
|
|
366
|
+
.where(eq(messages.id, midRow.id))
|
|
367
|
+
.run();
|
|
368
|
+
|
|
369
|
+
setForkStrategy("reference");
|
|
370
|
+
const fork = await forkConversationForRetrospective({
|
|
371
|
+
conversationId: source.id,
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
// The fork's lineage read excludes the ancestor's in-flight row; the
|
|
375
|
+
// source's own read keeps it.
|
|
376
|
+
expect(textOf(getMessages(fork.id))).toEqual([
|
|
377
|
+
"draft a launch plan",
|
|
378
|
+
"tweak the timeline",
|
|
379
|
+
"updated",
|
|
380
|
+
]);
|
|
381
|
+
expect(getMessages(source.id)).toHaveLength(4);
|
|
382
|
+
|
|
383
|
+
getDb()
|
|
384
|
+
.update(messages)
|
|
385
|
+
.set({ finalized: 1 })
|
|
386
|
+
.where(eq(messages.id, midRow.id))
|
|
387
|
+
.run();
|
|
388
|
+
|
|
389
|
+
// Once the row finalizes it enters the inherited window on its own.
|
|
390
|
+
expect(textOf(getMessages(fork.id))).toEqual([
|
|
391
|
+
"draft a launch plan",
|
|
392
|
+
"here is a first pass",
|
|
393
|
+
"tweak the timeline",
|
|
394
|
+
"updated",
|
|
395
|
+
]);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
test("an unfinalized tail is not the fork anchor", async () => {
|
|
399
|
+
const source = await seedSource("Launch");
|
|
400
|
+
const tail = getMessages(source.id).at(-1)!;
|
|
401
|
+
getDb()
|
|
402
|
+
.update(messages)
|
|
403
|
+
.set({ finalized: 0 })
|
|
404
|
+
.where(eq(messages.id, tail.id))
|
|
405
|
+
.run();
|
|
406
|
+
|
|
407
|
+
setForkStrategy("reference");
|
|
408
|
+
const fork = await forkConversationForRetrospective({
|
|
409
|
+
conversationId: source.id,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
expect(fork.forkParentMessageId).not.toBe(tail.id);
|
|
413
|
+
expect(textOf(getMessages(fork.id))).toEqual([
|
|
414
|
+
"draft a launch plan",
|
|
415
|
+
"here is a first pass",
|
|
416
|
+
"tweak the timeline",
|
|
417
|
+
]);
|
|
418
|
+
});
|
|
419
|
+
});
|
|
@@ -723,3 +723,27 @@ describe("forkConversationForRetrospective — compacted source", () => {
|
|
|
723
723
|
});
|
|
724
724
|
});
|
|
725
725
|
});
|
|
726
|
+
|
|
727
|
+
describe("forkConversationForRetrospective with unfinalized rows", () => {
|
|
728
|
+
beforeEach(() => {
|
|
729
|
+
resetTables();
|
|
730
|
+
});
|
|
731
|
+
|
|
732
|
+
test("skips the unfinalized tail and anchors at the last finalized message", async () => {
|
|
733
|
+
const source = await seedSource("Mid-turn retro");
|
|
734
|
+
const tail = getMessages(source.id).at(-1)!;
|
|
735
|
+
const db = getDb();
|
|
736
|
+
db.run(`UPDATE messages SET finalized = 0 WHERE id = '${tail.id}'`);
|
|
737
|
+
|
|
738
|
+
const fork = await forkConversationForRetrospective({
|
|
739
|
+
conversationId: source.id,
|
|
740
|
+
});
|
|
741
|
+
const forkMessages = getMessages(fork.id);
|
|
742
|
+
|
|
743
|
+
// Invariant: only finalized rows are copied, and the lineage anchor is a
|
|
744
|
+
// row the fork actually holds.
|
|
745
|
+
expect(forkMessages).toHaveLength(3);
|
|
746
|
+
expect(forkMessages.every((row) => row.finalized === 1)).toBe(true);
|
|
747
|
+
expect(fork.forkParentMessageId).not.toBe(tail.id);
|
|
748
|
+
});
|
|
749
|
+
});
|
|
@@ -498,6 +498,25 @@ export function parseMessageMetadata(
|
|
|
498
498
|
}
|
|
499
499
|
}
|
|
500
500
|
|
|
501
|
+
/**
|
|
502
|
+
* Rows a fork may copy: finalized ones. A `finalized = 0` row is mid-write,
|
|
503
|
+
* its content a `{ ref }` into the source turn's in-flight delta file, which
|
|
504
|
+
* the source deletes when the turn completes. A copied row would point at a
|
|
505
|
+
* file another conversation is about to delete, leaving a permanently empty
|
|
506
|
+
* message that reads as final and is invisible to crash recovery (which scans
|
|
507
|
+
* `finalized = 0` only). Unfinalized is not "unsent": the message was sent
|
|
508
|
+
* and is still being written, so there is no completed content to copy. A
|
|
509
|
+
* fork reflects the conversation at a completed point.
|
|
510
|
+
*
|
|
511
|
+
* Callers apply this to `messagesToCopy` itself, upstream of the boundary
|
|
512
|
+
* timestamp, compaction inheritance, `forkParentMessageId`, and the id map,
|
|
513
|
+
* so every derivation describes the rows actually copied and the lineage
|
|
514
|
+
* anchor can never reference a row the fork does not hold.
|
|
515
|
+
*/
|
|
516
|
+
function dropUnfinalizedRows(rows: MessageRow[]): MessageRow[] {
|
|
517
|
+
return rows.filter((message) => message.finalized === 1);
|
|
518
|
+
}
|
|
519
|
+
|
|
501
520
|
function cloneForkMessageMetadata(
|
|
502
521
|
metadata: string | null,
|
|
503
522
|
sourceMessageId: string,
|
|
@@ -1336,7 +1355,7 @@ export function forkConversation(params: {
|
|
|
1336
1355
|
|
|
1337
1356
|
const messagesToCopy =
|
|
1338
1357
|
copyBoundaryIndex >= 0
|
|
1339
|
-
? sourceMessages.slice(0, copyBoundaryIndex + 1)
|
|
1358
|
+
? dropUnfinalizedRows(sourceMessages.slice(0, copyBoundaryIndex + 1))
|
|
1340
1359
|
: ([] as MessageRow[]);
|
|
1341
1360
|
|
|
1342
1361
|
// Inherit the history-strip marker only when the fork boundary is at-or-
|
|
@@ -1461,7 +1480,13 @@ export function forkConversation(params: {
|
|
|
1461
1480
|
messagesToCopy,
|
|
1462
1481
|
forkedMessageIds,
|
|
1463
1482
|
latestForkedAssistant,
|
|
1464
|
-
|
|
1483
|
+
// The wholesale memory-state carry requires the fork's window to equal
|
|
1484
|
+
// the source's rendered window; a boundary at the tip no longer
|
|
1485
|
+
// guarantees that when the unfinalized filter dropped rows from the
|
|
1486
|
+
// slice, so both conditions gate it.
|
|
1487
|
+
isFullHistoryFork:
|
|
1488
|
+
copyBoundaryIndex === sourceMessages.length - 1 &&
|
|
1489
|
+
messagesToCopy.length === copyBoundaryIndex + 1,
|
|
1465
1490
|
inheritedCompactedMessageCount:
|
|
1466
1491
|
inheritedCompaction?.compactedMessageCount ?? 0,
|
|
1467
1492
|
diskSyncQueue,
|
|
@@ -1772,7 +1797,7 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1772
1797
|
);
|
|
1773
1798
|
const messagesToCopy =
|
|
1774
1799
|
copyBoundaryIndex >= 0
|
|
1775
|
-
? sourceMessages.slice(0, copyBoundaryIndex + 1)
|
|
1800
|
+
? dropUnfinalizedRows(sourceMessages.slice(0, copyBoundaryIndex + 1))
|
|
1776
1801
|
: ([] as MessageRow[]);
|
|
1777
1802
|
|
|
1778
1803
|
const sourceHistoryStrippedAt = sourceConversation.historyStrippedAt ?? null;
|
|
@@ -1936,8 +1961,12 @@ export async function forkConversationForRetrospective(params: {
|
|
|
1936
1961
|
messagesToCopy: rowsToCopy,
|
|
1937
1962
|
forkedMessageIds,
|
|
1938
1963
|
latestForkedAssistant,
|
|
1964
|
+
// Both conditions, for the same reason as `forkConversation`:
|
|
1965
|
+
// a tip boundary no longer implies an equal window once the
|
|
1966
|
+
// unfinalized filter dropped rows from the slice.
|
|
1939
1967
|
isFullHistoryFork:
|
|
1940
|
-
copyBoundaryIndex === sourceMessages.length - 1
|
|
1968
|
+
copyBoundaryIndex === sourceMessages.length - 1 &&
|
|
1969
|
+
messagesToCopy.length === copyBoundaryIndex + 1,
|
|
1941
1970
|
// The copied range already starts at the visible window.
|
|
1942
1971
|
inheritedCompactedMessageCount: forkCompactedMessageCount,
|
|
1943
1972
|
skipCompactionLedgerCopy: inheritedCompaction != null,
|
|
@@ -184,6 +184,14 @@ export function isSingleSegmentLineage(segments: LineageSegment[]): boolean {
|
|
|
184
184
|
* strictly-earlier `createdAt`, or an equal `createdAt` with an id that does
|
|
185
185
|
* not sort after the bound. The fork message itself is included, because a
|
|
186
186
|
* fork is taken THROUGH that message.
|
|
187
|
+
*
|
|
188
|
+
* Ancestor segments additionally exclude unfinalized rows. An ancestor's
|
|
189
|
+
* `finalized = 0` row is a message its own live turn is still writing; a
|
|
190
|
+
* descendant reading it would see partial content that the ancestor rewrites
|
|
191
|
+
* inline when the turn completes. The row enters the window on its own once
|
|
192
|
+
* it finalizes. A segment with no bound is the conversation's own tail and
|
|
193
|
+
* keeps its unfinalized rows: a conversation always sees its own in-flight
|
|
194
|
+
* message.
|
|
187
195
|
*/
|
|
188
196
|
export function lineageMessageFilter(segments: LineageSegment[]): SQL {
|
|
189
197
|
const clauses = segments.map((segment) => {
|
|
@@ -194,6 +202,7 @@ export function lineageMessageFilter(segments: LineageSegment[]): SQL {
|
|
|
194
202
|
const { createdAt, id } = segment.through;
|
|
195
203
|
return and(
|
|
196
204
|
owner,
|
|
205
|
+
eq(messages.finalized, 1),
|
|
197
206
|
or(
|
|
198
207
|
lt(messages.createdAt, createdAt),
|
|
199
208
|
and(
|
|
@@ -236,6 +236,13 @@ export function findInboundConversationId(
|
|
|
236
236
|
/**
|
|
237
237
|
* Record an inbound channel event. Returns `duplicate: true` if this
|
|
238
238
|
* exact (channel, chat, message) combination was already seen.
|
|
239
|
+
*
|
|
240
|
+
* The dedup half of this is also implemented gateway-side, on the same
|
|
241
|
+
* triple, in `gateway/src/db/inbound-dedup-store.ts`. Deliberately, not by
|
|
242
|
+
* accident: the gateway claims a delivery before handing it over, so a
|
|
243
|
+
* vendor's retry costs no crossing, and this stays as the record that binds
|
|
244
|
+
* the conversation and tracks the reply. Both must key on the same three
|
|
245
|
+
* fields for either to mean anything.
|
|
239
246
|
*/
|
|
240
247
|
export function recordInbound(
|
|
241
248
|
sourceChannel: string,
|
|
@@ -48,9 +48,9 @@ describe("matchBufferEntryStart", () => {
|
|
|
48
48
|
});
|
|
49
49
|
|
|
50
50
|
test("an indented entry-shaped line is body text, not a new entry", () => {
|
|
51
|
-
// The writer
|
|
52
|
-
// part of the fact above it.
|
|
53
|
-
// fact into two nodes in the
|
|
51
|
+
// The writer puts only an entry's opening line at column 0 and nests the
|
|
52
|
+
// body under it, so anything indented is part of the fact above it.
|
|
53
|
+
// Reading it as an entry splits one fact into two nodes in the Memory tab.
|
|
54
54
|
expect(isBufferEntryStart(" - [Jan 1, 9:00 AM] indented")).toBe(false);
|
|
55
55
|
expect(isBufferEntryStart("\t- [Jan 1, 9:00 AM] tab-indented")).toBe(false);
|
|
56
56
|
});
|
|
@@ -97,6 +97,60 @@ describe("matchBufferEntryStart", () => {
|
|
|
97
97
|
});
|
|
98
98
|
});
|
|
99
99
|
|
|
100
|
+
describe("formatRememberEntry round trip", () => {
|
|
101
|
+
const WRITTEN_AT = new Date(2026, 0, 1, 9, 0);
|
|
102
|
+
|
|
103
|
+
test("a fact whose body is itself entry-shaped survives as one entry", () => {
|
|
104
|
+
const content = "plan:\n- [Jan 2, 9:00 AM] step";
|
|
105
|
+
const written = formatRememberEntry(content, WRITTEN_AT);
|
|
106
|
+
|
|
107
|
+
// The body is nested, so it cannot be mistaken for the next fact.
|
|
108
|
+
expect(written).toBe(
|
|
109
|
+
"- [Jan 1, 9:00 AM] plan:\n - [Jan 2, 9:00 AM] step\n",
|
|
110
|
+
);
|
|
111
|
+
expect(splitBufferEntries(written.trimEnd().split("\n"))).toHaveLength(1);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("any content round-trips to exactly one entry", () => {
|
|
115
|
+
// The delimiter is "canonical entry shape at column 0", so the property
|
|
116
|
+
// that matters is that no fact body can imitate one, whatever the user
|
|
117
|
+
// dictated.
|
|
118
|
+
const adversarial = [
|
|
119
|
+
"plan:\n- [Jan 2, 9:00 AM] step",
|
|
120
|
+
"plan:\n- [Jan 2, 9:00 AM] step\n- [Jan 3, 10:15 PM] another",
|
|
121
|
+
"- [Jan 2, 9:00 AM] body opens with an entry shape",
|
|
122
|
+
"top\n\n- [Dec 31, 12:05 PM] after a blank line",
|
|
123
|
+
"top\n - [Jan 2, 9:00 AM] already indented",
|
|
124
|
+
"top\n\t- [Jan 2, 9:00 AM] tab indented",
|
|
125
|
+
"top\n- [ ] checklist\n- [[wikilink]] doc\n- plain bullet",
|
|
126
|
+
"single line, no body",
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
for (const content of adversarial) {
|
|
130
|
+
const written = formatRememberEntry(content, WRITTEN_AT);
|
|
131
|
+
expect(splitBufferEntries(written.trimEnd().split("\n"))).toHaveLength(1);
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("the fact text a reader recovers is unchanged by nesting", () => {
|
|
136
|
+
const content = "plan:\n- [Jan 2, 9:00 AM] step";
|
|
137
|
+
const groups = splitBufferEntries(
|
|
138
|
+
formatRememberEntry(content, WRITTEN_AT).trimEnd().split("\n"),
|
|
139
|
+
);
|
|
140
|
+
// Opening clause on the entry, body carried verbatim under it.
|
|
141
|
+
expect(groups[0]!.start?.text).toBe("plan:");
|
|
142
|
+
expect(groups[0]!.lines).toEqual([
|
|
143
|
+
"- [Jan 1, 9:00 AM] plan:",
|
|
144
|
+
" - [Jan 2, 9:00 AM] step",
|
|
145
|
+
]);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test("blank body lines stay blank rather than becoming whitespace", () => {
|
|
149
|
+
const written = formatRememberEntry("a\n\nb", WRITTEN_AT);
|
|
150
|
+
expect(written).toBe("- [Jan 1, 9:00 AM] a\n\n b\n");
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
100
154
|
describe("splitBufferEntries", () => {
|
|
101
155
|
test("keeps a multiline fact's body with its opening line", () => {
|
|
102
156
|
const groups = splitBufferEntries([
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { beforeEach, describe, expect, test } from "bun:test";
|
|
2
2
|
|
|
3
|
+
import { eq } from "drizzle-orm";
|
|
4
|
+
|
|
3
5
|
import {
|
|
4
6
|
createConversation,
|
|
5
7
|
type MessageRow,
|
|
@@ -8,6 +10,7 @@ import { getDb } from "../../../../persistence/db-connection.js";
|
|
|
8
10
|
import { initializeDb } from "../../../../persistence/db-init.js";
|
|
9
11
|
import { messages } from "../../../../persistence/schema/index.js";
|
|
10
12
|
import {
|
|
13
|
+
getRetrospectiveMessagesAfter,
|
|
11
14
|
hasQualifyingUserMessageAfter,
|
|
12
15
|
messagesHaveUserActivity,
|
|
13
16
|
} from "../memory-retrospective-accounting.js";
|
|
@@ -197,3 +200,72 @@ describe("messagesHaveUserActivity", () => {
|
|
|
197
200
|
expect(messagesHaveUserActivity([])).toBe(false);
|
|
198
201
|
});
|
|
199
202
|
});
|
|
203
|
+
|
|
204
|
+
describe("getRetrospectiveMessagesAfter", () => {
|
|
205
|
+
beforeEach(() => {
|
|
206
|
+
const db = getDb();
|
|
207
|
+
db.run(`DELETE FROM messages`);
|
|
208
|
+
db.run(`DELETE FROM conversations`);
|
|
209
|
+
createConversation({ id: CONV });
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test("truncates at a stale mid-slice unfinalized row so the cursor never passes it", () => {
|
|
213
|
+
const first = insertRaw({ role: "user", content: TEXT, createdAt: 1_000 });
|
|
214
|
+
const stale = insertRaw({
|
|
215
|
+
role: "assistant",
|
|
216
|
+
content: TEXT,
|
|
217
|
+
createdAt: 2_000,
|
|
218
|
+
});
|
|
219
|
+
insertRaw({ role: "user", content: TEXT, createdAt: 3_000 });
|
|
220
|
+
insertRaw({ role: "assistant", content: TEXT, createdAt: 4_000 });
|
|
221
|
+
getDb()
|
|
222
|
+
.update(messages)
|
|
223
|
+
.set({ finalized: 0 })
|
|
224
|
+
.where(eq(messages.id, stale))
|
|
225
|
+
.run();
|
|
226
|
+
|
|
227
|
+
const slice = getRetrospectiveMessagesAfter(CONV, null);
|
|
228
|
+
|
|
229
|
+
// The slice stops BEFORE the stale row: taking the later finalized rows
|
|
230
|
+
// as the cutoff would advance the cursor past the stale row, and once it
|
|
231
|
+
// finalizes it would sit behind the cursor, unreviewed forever.
|
|
232
|
+
expect(slice.map((row) => row.id)).toEqual([first]);
|
|
233
|
+
|
|
234
|
+
getDb()
|
|
235
|
+
.update(messages)
|
|
236
|
+
.set({ finalized: 1 })
|
|
237
|
+
.where(eq(messages.id, stale))
|
|
238
|
+
.run();
|
|
239
|
+
|
|
240
|
+
// Once the row resolves, the slice continues past it.
|
|
241
|
+
expect(getRetrospectiveMessagesAfter(CONV, null)).toHaveLength(4);
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("excludes unfinalized rows so the cutoff stays on rows a fork holds", () => {
|
|
245
|
+
insertRaw({ role: "user", content: TEXT, createdAt: 1_000 });
|
|
246
|
+
const lastFinalized = insertRaw({
|
|
247
|
+
role: "assistant",
|
|
248
|
+
content: TEXT,
|
|
249
|
+
createdAt: 2_000,
|
|
250
|
+
});
|
|
251
|
+
const streaming = insertRaw({
|
|
252
|
+
role: "assistant",
|
|
253
|
+
content: TEXT,
|
|
254
|
+
createdAt: 3_000,
|
|
255
|
+
});
|
|
256
|
+
getDb()
|
|
257
|
+
.update(messages)
|
|
258
|
+
.set({ finalized: 0 })
|
|
259
|
+
.where(eq(messages.id, streaming))
|
|
260
|
+
.run();
|
|
261
|
+
|
|
262
|
+
const slice = getRetrospectiveMessagesAfter(CONV, null);
|
|
263
|
+
|
|
264
|
+
// The invariant: no slice member is unfinalized, and the cutoff the job
|
|
265
|
+
// would take (the last slice row) is a row the retrospective fork
|
|
266
|
+
// actually contains.
|
|
267
|
+
expect(slice.some((row) => row.finalized === 0)).toBe(false);
|
|
268
|
+
expect(slice.at(-1)?.id).toBe(lastFinalized);
|
|
269
|
+
expect(slice.map((row) => row.id)).not.toContain(streaming);
|
|
270
|
+
});
|
|
271
|
+
});
|
|
@@ -168,7 +168,10 @@ mock.module("../find-most-recent-retrospective-for.js", () => ({
|
|
|
168
168
|
mock.module("../../../../persistence/conversation-crud.js", () => ({
|
|
169
169
|
getMessagesAfter: (id: string, afterId: string | null) => {
|
|
170
170
|
messagesAfterCalls.push({ conversationId: id, afterId });
|
|
171
|
-
|
|
171
|
+
// Real rows always carry `finalized` (NOT NULL, default 1); the slice
|
|
172
|
+
// filter drops unfinalized rows, so mock rows default to finalized
|
|
173
|
+
// unless a test explicitly stages a streaming row.
|
|
174
|
+
return newMessages.map((row) => ({ finalized: 1, ...row }));
|
|
172
175
|
},
|
|
173
176
|
getMessages: (id: string) => {
|
|
174
177
|
if (messagesByConversationId[id]) {
|
|
@@ -96,7 +96,10 @@ mock.module("../find-most-recent-retrospective-for.js", () => ({
|
|
|
96
96
|
}));
|
|
97
97
|
|
|
98
98
|
mock.module("../../../../persistence/conversation-crud.js", () => ({
|
|
99
|
-
|
|
99
|
+
// Real rows always carry `finalized` (NOT NULL, default 1); the slice
|
|
100
|
+
// filter drops unfinalized rows, so mock rows default to finalized.
|
|
101
|
+
getMessagesAfter: (_id: string, _afterId: string | null) =>
|
|
102
|
+
newMessages.map((row) => ({ finalized: 1, ...row })),
|
|
100
103
|
getMessages: (id: string) => messageStores[id] ?? [],
|
|
101
104
|
// `defaultResolveTarget` in the REAL wake reads the FORK id's row for the
|
|
102
105
|
// archived check, so both rows carry archivedAt/createdAt. The fork's
|
|
@@ -89,6 +89,13 @@ export function formatBufferTimestamp(now: Date): string {
|
|
|
89
89
|
return `${month} ${day}, ${displayHour}:${minutes} ${ampm}`;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
/**
|
|
93
|
+
* Indent applied to a fact's continuation lines. Two spaces is the markdown
|
|
94
|
+
* convention for content nested under a `- ` bullet, so an entry stays
|
|
95
|
+
* readable as a list item.
|
|
96
|
+
*/
|
|
97
|
+
const CONTINUATION_INDENT = " ";
|
|
98
|
+
|
|
92
99
|
/**
|
|
93
100
|
* Build a timestamped bullet entry for `buffer.md` / `archive/<date>.md`.
|
|
94
101
|
*
|
|
@@ -96,11 +103,27 @@ export function formatBufferTimestamp(now: Date): string {
|
|
|
96
103
|
* human-readable and downstream consumers (sweep, consolidation, the graph
|
|
97
104
|
* view) can parse the same shape regardless of which path produced the entry.
|
|
98
105
|
*
|
|
106
|
+
* A fact's body is indented, which is what makes the format round-trip. The
|
|
107
|
+
* buffer is line-delimited and the delimiter is "canonical entry shape at
|
|
108
|
+
* column 0", so a body line carrying that exact shape would otherwise be
|
|
109
|
+
* indistinguishable from the start of the next fact and split one entry into
|
|
110
|
+
* two. Indenting moves every body line off column 0, so no fact content can
|
|
111
|
+
* imitate a delimiter no matter what the user dictated. Blank lines stay
|
|
112
|
+
* genuinely blank rather than becoming whitespace.
|
|
113
|
+
*
|
|
114
|
+
* Readers strip the indent: {@link matchBufferEntryStart} classifies on the
|
|
115
|
+
* raw line while `parseBufferEntries` trims continuation lines, so the fact
|
|
116
|
+
* text a caller gets back is unchanged by this.
|
|
117
|
+
*
|
|
99
118
|
* Exported so memory sweep / extractor jobs format their auto-remembered
|
|
100
119
|
* entries identically to user-facing `remember()` calls.
|
|
101
120
|
*/
|
|
102
121
|
export function formatRememberEntry(content: string, now: Date): string {
|
|
103
|
-
|
|
122
|
+
const [opening = "", ...body] = content.split("\n");
|
|
123
|
+
const nested = body.map((line) =>
|
|
124
|
+
line.trim().length === 0 ? "" : `${CONTINUATION_INDENT}${line}`,
|
|
125
|
+
);
|
|
126
|
+
return `- [${formatBufferTimestamp(now)}] ${[opening, ...nested].join("\n")}\n`;
|
|
104
127
|
}
|
|
105
128
|
|
|
106
129
|
/**
|
|
@@ -224,6 +224,12 @@ async function gatherCandidateRowsFromQdrant(
|
|
|
224
224
|
* the source/type/excluded-conversation predicates in SQL (Qdrant has no
|
|
225
225
|
* visibility filtering). The app-side scorer determines final ordering, so
|
|
226
226
|
* the SQL tie-break falls back to recency.
|
|
227
|
+
*
|
|
228
|
+
* No `finalized = 1` predicate, deliberately: every id in `messageIds` comes
|
|
229
|
+
* from the lexical or vector index, and indexing filters `finalized = 1` at
|
|
230
|
+
* index time (`message-lexical.ts`), so an unfinalized row can never be a
|
|
231
|
+
* candidate here. Do not copy this query shape to a reader whose id set has a
|
|
232
|
+
* different provenance; those need the filter themselves.
|
|
227
233
|
*/
|
|
228
234
|
function searchByIds(
|
|
229
235
|
messageIds: readonly string[],
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
2
|
|
|
3
|
+
import { formatRememberEntry } from "../buffer-format.js";
|
|
3
4
|
import {
|
|
4
5
|
buildPendingGraph,
|
|
5
6
|
findPendingEntryForContent,
|
|
@@ -42,8 +43,26 @@ describe("parseBufferEntries", () => {
|
|
|
42
43
|
expect(entries[1]!.text).toBe("separate fact");
|
|
43
44
|
});
|
|
44
45
|
|
|
46
|
+
test("a written fact stays one node even when its body is entry-shaped at column 0", () => {
|
|
47
|
+
// Round trip through the real writer. A user can dictate a fact whose body
|
|
48
|
+
// is itself a dated bullet, and without the writer nesting the body those
|
|
49
|
+
// lines are byte-identical to the start of the next fact, so one memory
|
|
50
|
+
// renders as several pending nodes in the Memory tab.
|
|
51
|
+
const entries = parseBufferEntries(
|
|
52
|
+
formatRememberEntry(
|
|
53
|
+
"Rollout plan:\n- [Jul 21, 9:00 AM] cutover window opens\n- [Jul 22, 9:00 AM] rollback deadline",
|
|
54
|
+
new Date(2026, 6, 20, 15, 15),
|
|
55
|
+
),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
expect(entries).toHaveLength(1);
|
|
59
|
+
expect(entries[0]!.text).toBe(
|
|
60
|
+
"Rollout plan:\n- [Jul 21, 9:00 AM] cutover window opens\n- [Jul 22, 9:00 AM] rollback deadline",
|
|
61
|
+
);
|
|
62
|
+
});
|
|
63
|
+
|
|
45
64
|
test("an indented entry-shaped line stays inside the fact above it", () => {
|
|
46
|
-
//
|
|
65
|
+
// Only an entry's opening line sits at column 0, so an indented bullet
|
|
47
66
|
// that happens to carry a timestamp is body text the user wrote. Reading
|
|
48
67
|
// it as an entry splits one fact into two nodes in the Memory tab.
|
|
49
68
|
const entries = parseBufferEntries(
|
|
@@ -52,18 +52,30 @@ export function isSkillCardMessage(row: { metadata: string | null }): boolean {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
/**
|
|
55
|
-
* `getMessagesAfter` minus skill-card
|
|
56
|
-
* new-message slice: a card-only tail yields an
|
|
57
|
-
* `no_new_messages` early return), and a mixed tail's
|
|
58
|
-
* last real message rather than the card.
|
|
55
|
+
* `getMessagesAfter` truncated at the first unfinalized row, minus skill-card
|
|
56
|
+
* rows. The retrospective job's new-message slice: a card-only tail yields an
|
|
57
|
+
* empty slice (the job's `no_new_messages` early return), and a mixed tail's
|
|
58
|
+
* cutoff lands on the last real message rather than the card.
|
|
59
|
+
*
|
|
60
|
+
* The slice STOPS BEFORE the first unfinalized row rather than filtering it
|
|
61
|
+
* out. The job's cutoff (and therefore `lastProcessedMessageId` on success)
|
|
62
|
+
* is chosen from this slice, while the fork the job reviews skips unfinalized
|
|
63
|
+
* rows, so the cursor must never move past one: filtering through a stale
|
|
64
|
+
* mid-slice `finalized = 0` row would advance the cursor beyond it, and once
|
|
65
|
+
* the row later finalizes its `(createdAt, id)` sits behind the cursor,
|
|
66
|
+
* unreviewed forever. Truncating parks the cursor before the unfinalized row;
|
|
67
|
+
* the rows behind it are reviewed by the retrospective that runs after the
|
|
68
|
+
* row resolves (finalizes, or is repaired away by crash recovery).
|
|
59
69
|
*/
|
|
60
70
|
export function getRetrospectiveMessagesAfter(
|
|
61
71
|
conversationId: string,
|
|
62
72
|
afterMessageId: string | null,
|
|
63
73
|
): MessageRow[] {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
74
|
+
const rows = getMessagesAfter(conversationId, afterMessageId);
|
|
75
|
+
const firstUnfinalized = rows.findIndex((row) => row.finalized !== 1);
|
|
76
|
+
const bounded =
|
|
77
|
+
firstUnfinalized === -1 ? rows : rows.slice(0, firstUnfinalized);
|
|
78
|
+
return bounded.filter((row) => !isSkillCardMessage(row));
|
|
67
79
|
}
|
|
68
80
|
|
|
69
81
|
/**
|
|
@@ -197,6 +197,7 @@ const { memoryV2ConsolidateJob, CONSOLIDATION_FAILURE_CHECKPOINT_KEY } =
|
|
|
197
197
|
const { CUTOFF_PLACEHOLDER, CONSOLIDATION_PROMPT } =
|
|
198
198
|
await import("../prompts/consolidation.js");
|
|
199
199
|
const { invalidatePageIndex } = await import("../page-index.js");
|
|
200
|
+
const { formatRememberEntry } = await import("../../buffer-format.js");
|
|
200
201
|
|
|
201
202
|
// The handler only reads `config.memory.enabled`, `config.memory.v2.enabled`,
|
|
202
203
|
// `config.memory.v2.consolidation_prompt_path`, and
|
|
@@ -437,6 +438,38 @@ describe("memoryV2ConsolidateJob — chunked cutoff (consolidation_max_entries_p
|
|
|
437
438
|
expect(outcome.cutoff).not.toBe("[meeting-notes]");
|
|
438
439
|
});
|
|
439
440
|
|
|
441
|
+
test("a fact whose body holds a canonical entry line counts once and never supplies the cutoff", async () => {
|
|
442
|
+
// Written through the real writer, so this covers the round trip rather
|
|
443
|
+
// than a hand-built buffer: the body line carries the exact shape an entry
|
|
444
|
+
// opening has. Counting it would both inflate the per-run budget and let
|
|
445
|
+
// the cutoff be drawn from inside a fact, deferring entries against a
|
|
446
|
+
// timestamp the user never filed anything at.
|
|
447
|
+
writeFileSync(
|
|
448
|
+
bufferPath(),
|
|
449
|
+
formatRememberEntry(
|
|
450
|
+
"Alice's rollout plan:\n- [Apr 28, 9:00 AM] cutover",
|
|
451
|
+
new Date(2026, 3, 27, 9, 0),
|
|
452
|
+
) +
|
|
453
|
+
formatRememberEntry(
|
|
454
|
+
"Bob takes his coffee black.",
|
|
455
|
+
new Date(2026, 3, 27, 9, 1),
|
|
456
|
+
),
|
|
457
|
+
);
|
|
458
|
+
|
|
459
|
+
const outcome = await memoryV2ConsolidateJob(
|
|
460
|
+
makeJob(),
|
|
461
|
+
configWithMaxEntries(2),
|
|
462
|
+
);
|
|
463
|
+
|
|
464
|
+
expect(outcome.kind).toBe("invoked");
|
|
465
|
+
if (outcome.kind !== "invoked") {
|
|
466
|
+
throw new Error("unreachable");
|
|
467
|
+
}
|
|
468
|
+
// Two facts, cap 2 → no chunking. Three would chunk and defer one.
|
|
469
|
+
expect(outcome.deferredEntries).toBe(0);
|
|
470
|
+
expect(outcome.cutoff).not.toBe("Apr 28, 9:00 AM");
|
|
471
|
+
});
|
|
472
|
+
|
|
440
473
|
test("multi-line entries under the cap → full-buffer cutoff even when raw line count exceeds it", async () => {
|
|
441
474
|
writeFileSync(
|
|
442
475
|
bufferPath(),
|