Skip to content

Commit 697254e

Browse files
author
ami3466
committed
log: ship a list, not 200 captures — and reject through the one brain
The Log list sent 4,000 characters of every capture plus up to a hundred cell diffs per row, ~half a megabyte to paint 200 rows the renderer draws as ONE line each (`text.split("\n",1)[0]`). Nearly all of it was thrown away on arrival. The list now carries a 200-char preview and the cell COUNT. The capture in full and the reviewable before→after diff move to GET /api/log?id=<id>, fetched for the one row a user actually opens, cached per id and dropped when the record version bumps — a row opened while pending, then structured, must not keep showing the empty diff it had. The refetch is quiet: the open row keeps its content and is refilled in place, no loading flag, nothing unmounts. list 2,599B for 7 rows vs 31,713B of details — measured in the e2e, not guessed REJECT WAS A SECOND COPY OF THE BRAIN. The route hand-rolled what cli-core's logReject already does and had drifted: it never called dropMergeRuleFor, so rejecting a column merge FROM THE UI left its rule in config and the next import silently redid the merge the user had just undone (the CLI, on the same brain, got this right). It also used bare refreshSyncCache, which no-ops when no cache exists, where logReject lands the sources it rewrote. The route keeps its HTTP shape — auth, 404, "already rejected" — and delegates the rest. The e2e was asserting a lie, and had been since d0d9730. Reject used to return `undo.applied.length`, a constant — "reverted: 2" even when it wrote no cells. d0d9730 made the undo CONDITIONAL (a cell holding a value someone typed after the merge is theirs, so it stays) and made `reverted` an honest count of cells actually moved. The assertion kept expecting the constant, so the suite failed on correct behavior — and, worse, never once exercised a working undo: both of its cells were edited before the reject, so zero was the right answer. reverted = 0 in that scenario, and 2026-07-01 rightly still holds the 1111 the user typed over it Replaced with checks that pin the real contract and would fail on a broken undo: nothing the capture wrote survives, the hand-typed cell does, and a SECOND capture nobody edits is rejected and must take back every cell it wrote, its column and dates with it, touching no other source. journal-edit gains the same at the lib level plus the rule this repo runs on — reject's patched cache is compared byte for byte against a full rebuild. edit:test · log:test (40 checks) · tsc --noEmit — all green Neither failure was reachable by CI: release.yml builds the image and runs verify:tree, and no e2e suite at all.
1 parent 61fc703 commit 697254e

5 files changed

Lines changed: 266 additions & 62 deletions

File tree

‎scripts/data-log-e2e.ts‎

Lines changed: 132 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
*
55
* MAIN: over the deployed URL — drop a CSV capture (POST /api/inbox),
66
* Structure it (POST /api/structure), see it in the Log with revert armed
7-
* (GET /api/log), hand-edit the daily table (POST /api/journal/edit: set a
7+
* (GET /api/log), open the row for its full text + cell diff
8+
* (GET /api/log?id=), hand-edit the daily table (POST /api/journal/edit: set a
89
* cell, add a manual column, delete a row), then Reject the capture
910
* (POST /api/log/reject) and assert the cells it wrote are gone while the
1011
* manual column survives.
@@ -112,11 +113,12 @@ async function main() {
112113
// 1. Drop a CSV capture, exactly like the Dropzone does. Structuring it is a
113114
// real import — it must wipe every trace of the demo record first.
114115
console.log("\nDrop → Structure");
116+
const csv = "date,steps\n2026-07-01,1000\n2026-07-02,2000";
115117
const drop = await fetch(`${base}/api/inbox`, {
116118
method: "POST",
117119
headers: json,
118120
body: JSON.stringify({
119-
text: "date,steps\n2026-07-01,1000\n2026-07-02,2000",
121+
text: csv,
120122
source: "drop",
121123
kind: "csv",
122124
meta: { filename: "steps.csv" },
@@ -132,20 +134,47 @@ async function main() {
132134
const sBody = (await structure.json()) as { structured: number };
133135
check("structured via the free CSV path", structure.ok && sBody.structured === 1);
134136

135-
// 2. The Log shows the capture with what it became, revert armed.
137+
// 2. The Log shows the capture with what it became, revert armed. The list is
138+
// a LIST: a short preview per row and the cell COUNT — the capture in full
139+
// and the cell diff itself belong to the expanded row (GET /api/log?id=).
136140
console.log("\nLog");
137141
const log1 = (await (await fetch(`${base}/api/log`, { headers: { cookie } })).json()) as {
138-
items: Array<{ id: string; status: string; filename: string | null; structured: { source: string | null; cells: number | null; canRevert: boolean; applied: Array<{ d: string; m: string; before: string | null; after: string }> } | null }>;
142+
items: Array<{ id: string; status: string; filename: string | null; text: string; textLength: number; structured: { source: string | null; cells: number | null; canRevert: boolean; appliedCount: number; applied?: unknown } | null }>;
139143
};
140144
const item = log1.items[0];
141145
check("demo wiped on real import — log holds only the real capture", log1.items.length === 1 && item.filename === "steps.csv");
142146
check("log shows structured → steps, 2 cells, revert armed",
143147
item.status === "structured" && item.structured?.source === "steps" && item.structured?.cells === 2 && item.structured?.canRevert === true);
144-
const diff = item.structured?.applied ?? [];
145-
check("log carries the reviewable diff (before → after per cell)",
148+
check("list row carries the preview and the true length, not the cell diff",
149+
item.text === csv && item.textLength === csv.length && item.structured?.applied === undefined);
150+
check("list row still counts the cells it wrote", item.structured?.appliedCount === 2);
151+
152+
// 2b. The expanded row: the capture in full plus the reviewable diff, fetched
153+
// on demand for the ONE row the user opened.
154+
console.log("\nLog detail");
155+
type Detail = {
156+
id: string;
157+
text: string;
158+
textLength: number;
159+
applied: Array<{ d: string; m: string; before: string | null; after: string }>;
160+
appliedTruncated: boolean;
161+
};
162+
const detailRes = await fetch(`${base}/api/log?id=${encodeURIComponent(item.id)}`, { headers: { cookie } });
163+
const detail = (await detailRes.json()) as Detail;
164+
check("detail returns the capture in full",
165+
detailRes.ok && detail.id === item.id && detail.text === csv && detail.textLength === csv.length);
166+
const diff = detail.applied ?? [];
167+
check("detail carries the reviewable diff (before → after per cell)",
146168
diff.length === 2 &&
147169
diff.some((c) => c.d === "2026-07-01" && c.m === "steps" && c.before === null && c.after === "1000") &&
148170
diff.some((c) => c.d === "2026-07-02" && c.m === "steps" && c.before === null && c.after === "2000"));
171+
check("the move lost nothing — as many cells as the list counts, none dropped",
172+
diff.length === item.structured?.appliedCount && detail.appliedTruncated === false);
173+
174+
const bogus = await fetch(`${base}/api/log?id=no-such-capture`, { headers: { cookie } });
175+
const bogusBody = (await bogus.json()) as Detail;
176+
check("an unknown id is an empty detail, not an error",
177+
bogus.ok && bogusBody.text === "" && bogusBody.textLength === 0 && bogusBody.applied.length === 0);
149178

150179
// 3. Edit the table: change a cell, add a manual column, delete a row.
151180
console.log("\nJournal edit");
@@ -170,27 +199,121 @@ async function main() {
170199
check("manual column written", day1?.values["manual.mood"]?.text === "good");
171200
check("row deleted", !eBody.journal.days.some((d) => d.date === "2026-07-02"));
172201

173-
// 4. Reject the capture: its cells go, the manual column stays.
202+
// 4. Reject the capture: nothing it wrote is left in the table, and the hand
203+
// edits stand. Both its cells were changed AFTER the merge (07-01 retyped
204+
// as 1111, 07-02's row deleted), so the undo is conditional and takes back
205+
// neither: a value the user typed is theirs, not the capture's. `reverted`
206+
// counts cells this reject actually moved — 0, honestly.
174207
console.log("\nReject");
175208
const reject = await fetch(`${base}/api/log/reject`, {
176209
method: "POST",
177210
headers: json,
178211
body: JSON.stringify({ id: item.id }),
179212
});
180213
const rBody = (await reject.json()) as { reverted: number };
181-
check("reject reverted the merge's cells", reject.ok && rBody.reverted === 2);
214+
check("reject counts only the cells it actually moved", reject.ok && rBody.reverted === 0);
182215

183216
const journal = (await (await fetch(`${base}/api/journal`, { headers: { cookie } })).json()) as {
184217
metrics: Array<{ key: string }>;
185218
days: Array<{ date: string; values: Record<string, { text: string }> }>;
186219
};
187-
check("rejected capture's column is gone", !journal.metrics.some((m) => m.key === "steps.steps"));
220+
check("no value the capture wrote is left in the table",
221+
journal.days.find((d) => d.date === "2026-07-01")?.values["steps.steps"]?.text !== "1000" &&
222+
!journal.days.some((d) => d.date === "2026-07-02"));
223+
check("the hand-typed cell stood through the undo",
224+
journal.days.find((d) => d.date === "2026-07-01")?.values["steps.steps"]?.text === "1111");
188225
check("manual edit survived the reject", journal.days.find((d) => d.date === "2026-07-01")?.values["manual.mood"]?.text === "good");
189226

190227
const log2 = (await (await fetch(`${base}/api/log`, { headers: { cookie } })).json()) as {
191228
items: Array<{ status: string; rejectedAt: string | null }>;
192229
};
193230
check("log marks it rejected", log2.items[0]?.status === "discarded" && Boolean(log2.items[0]?.rejectedAt));
231+
232+
// 4b. The undo itself, on cells nobody touched: a second capture, rejected
233+
// straight away, must take back every cell it wrote — its column with
234+
// them — report that true count, and leave the other sources alone.
235+
console.log("\nReject (untouched cells)");
236+
const drop2 = await fetch(`${base}/api/inbox`, {
237+
method: "POST",
238+
headers: json,
239+
body: JSON.stringify({
240+
text: "date,sleep\n2026-07-03,7\n2026-07-04,8",
241+
source: "drop",
242+
kind: "csv",
243+
meta: { filename: "sleep.csv" },
244+
}),
245+
});
246+
const structure2 = await fetch(`${base}/api/structure`, {
247+
method: "POST",
248+
headers: json,
249+
body: JSON.stringify({ all: true }),
250+
});
251+
const s2Body = (await structure2.json()) as { structured: number };
252+
check("second capture structured", drop2.ok && structure2.ok && s2Body.structured === 1);
253+
254+
const log3 = (await (await fetch(`${base}/api/log`, { headers: { cookie } })).json()) as {
255+
items: Array<{ id: string; filename: string | null; structured: { source: string | null } | null }>;
256+
};
257+
const fresh = log3.items.find((i) => i.filename === "sleep.csv");
258+
const sleepKey = `${fresh?.structured?.source}.sleep`;
259+
const mid = (await (await fetch(`${base}/api/journal`, { headers: { cookie } })).json()) as {
260+
metrics: Array<{ key: string }>;
261+
};
262+
check("the untouched capture's column landed", Boolean(fresh) && mid.metrics.some((m) => m.key === sleepKey));
263+
264+
const reject2 = await fetch(`${base}/api/log/reject`, {
265+
method: "POST",
266+
headers: json,
267+
body: JSON.stringify({ id: fresh?.id }),
268+
});
269+
const r2Body = (await reject2.json()) as { reverted: number };
270+
check("reject took back every cell it wrote", reject2.ok && r2Body.reverted === 2);
271+
272+
const after = (await (await fetch(`${base}/api/journal`, { headers: { cookie } })).json()) as {
273+
metrics: Array<{ key: string }>;
274+
days: Array<{ date: string; values: Record<string, { text: string }> }>;
275+
};
276+
check("rejected capture's column is gone", !after.metrics.some((m) => m.key === sleepKey));
277+
check("its dates are gone with it",
278+
!after.days.some((d) => d.date === "2026-07-03" || d.date === "2026-07-04"));
279+
check("the undo took its own cells and nothing else",
280+
after.days.find((d) => d.date === "2026-07-01")?.values["manual.mood"]?.text === "good" &&
281+
after.days.find((d) => d.date === "2026-07-01")?.values["steps.steps"]?.text === "1111");
282+
283+
// 5. The point of the split, in bytes: the list ships one short line per row,
284+
// the details ship the captures — and only for the row someone opened.
285+
console.log("\nPayload");
286+
const filler = "a long capture line the list has no reason to ship.".repeat(120);
287+
for (let n = 0; n < 5; n++) {
288+
const landed = await fetch(`${base}/api/inbox`, {
289+
method: "POST",
290+
headers: json,
291+
body: JSON.stringify({ text: `memo ${n}\n${filler}`, source: "memo", kind: "note" }),
292+
});
293+
if (!landed.ok) check(`long memo ${n} landed`, false, await landed.text());
294+
}
295+
const listRaw = await (await fetch(`${base}/api/log`, { headers: { cookie } })).text();
296+
const listBytes = Buffer.byteLength(listRaw);
297+
const list = JSON.parse(listRaw) as { items: Array<{ id: string; text: string; textLength: number }> };
298+
299+
let detailBytes = 0;
300+
for (const row of list.items) {
301+
const r = await fetch(`${base}/api/log?id=${encodeURIComponent(row.id)}`, { headers: { cookie } });
302+
detailBytes += Buffer.byteLength(await r.text());
303+
}
304+
check("the list costs a fraction of the details it stopped shipping",
305+
listBytes * 4 < detailBytes, `list ${listBytes}B for ${list.items.length} rows vs ${detailBytes}B of details`);
306+
307+
const big = list.items.find((i) => i.text.startsWith("memo 0"));
308+
check("the long memos reached the log", Boolean(big));
309+
if (big) {
310+
check("a long capture is a short preview in the list, with its true length",
311+
big.text.length <= 200 && big.textLength === `memo 0\n${filler}`.length,
312+
`preview ${big.text.length} chars of ${big.textLength}`);
313+
const bigDetail = (await (await fetch(`${base}/api/log?id=${encodeURIComponent(big.id)}`, { headers: { cookie } })).json()) as Detail;
314+
check("the detail hands back the whole capture the list truncated",
315+
bigDetail.text === `memo 0\n${filler}` && bigDetail.textLength === big.textLength);
316+
}
194317
} finally {
195318
server.kill();
196319
fs.rmSync(root, { recursive: true, force: true });

‎scripts/journal-edit.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,11 @@ import {
1919
mergeDailyCsv,
2020
readInboxFromRecord,
2121
rebuild,
22+
updateInboxItems,
2223
type DailyEdit,
2324
} from "../src/lib/record";
2425
import { dbPath } from "../src/lib/paths";
25-
import { inboxResolve, journalEdit, query } from "../src/lib/cli-core";
26+
import { inboxResolve, journalEdit, logReject, query } from "../src/lib/cli-core";
2627

2728
let failures = 0;
2829
function check(label: string, cond: boolean, extra = "") {
@@ -165,6 +166,38 @@ check("patched cache is byte-identical to a full rebuild", JSON.stringify(afterP
165166
delete process.env.AGENTQS_DATA_DIR;
166167
fs.rmSync(dataDir3, { recursive: true, force: true });
167168

169+
// ---- 8. logReject: conditional undo, and its cache patch equals a rebuild ----
170+
console.log("\nlogReject undoes only the cells that still hold what it wrote");
171+
const dataDir4 = fs.mkdtempSync(path.join(os.tmpdir(), "agentqs-reject-"));
172+
process.env.AGENTQS_DATA_DIR = dataDir4;
173+
const rDir4 = path.join(dataDir4, "record");
174+
const merged = mergeDailyCsv(rDir4, "steps", {
175+
header: ["date", "steps"],
176+
rows: [["2026-07-01", "1000"], ["2026-07-02", "2000"]],
177+
});
178+
const capture = appendInboxItem({ text: "date,steps\n2026-07-01,1000\n2026-07-02,2000" }, { recordDir: rDir4 });
179+
updateInboxItems(
180+
[{ id: capture.id, status: "structured", meta: { source: "steps", applied: merged.applied } }],
181+
{ recordDir: rDir4 },
182+
);
183+
rebuild({ recordDir: rDir4, dbPath: dbPath() });
184+
// The user retypes one of the merged cells — that value is now theirs.
185+
journalEdit([{ op: "set", source: "steps", metric: "steps", date: "2026-07-01", value: "1111" }]);
186+
const rej = logReject(capture.id);
187+
check("reverted counts only the untouched cell it actually cleared", rej.reverted === 1, JSON.stringify(rej));
188+
const cells = query("SELECT date,value_num FROM daily WHERE source='steps' AND metric='steps' ORDER BY date");
189+
check("the hand-typed cell survived, the untouched one is gone",
190+
cells.rows.length === 1 && cells.rows[0]?.date === "2026-07-01" && Number(cells.rows[0]?.value_num) === 1111,
191+
JSON.stringify(cells.rows));
192+
check("the item is discarded", readInboxFromRecord(rDir4).find((i) => i.id === capture.id)?.status === "discarded");
193+
const rejPatch = query("SELECT date,source,metric,value_num,value_text FROM daily ORDER BY source,metric,date");
194+
rebuild({ recordDir: rDir4, dbPath: dbPath() });
195+
const rejRebuild = query("SELECT date,source,metric,value_num,value_text FROM daily ORDER BY source,metric,date");
196+
check("reject's patched cache is byte-identical to a full rebuild",
197+
JSON.stringify(rejPatch.rows) === JSON.stringify(rejRebuild.rows));
198+
delete process.env.AGENTQS_DATA_DIR;
199+
fs.rmSync(dataDir4, { recursive: true, force: true });
200+
168201
fs.rmSync(rDir, { recursive: true, force: true });
169202
console.log(failures ? `\n${failures} check(s) FAILED` : "\nAll checks passed");
170203
process.exit(failures ? 1 : 0);

‎src/app/api/log/reject/route.ts‎

Lines changed: 10 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
import { NextResponse } from "next/server";
22
import { getCurrentUser } from "@/lib/session";
33
import { recordDir } from "@/lib/paths";
4-
import {
5-
applyDailyEdits,
6-
landInboxCaptures,
7-
readInboxFromRecord,
8-
refreshSyncCache,
9-
revertEditsFromAppliedMeta,
10-
updateInboxItems,
11-
} from "@/lib/record";
4+
import { logReject } from "@/lib/cli-core";
5+
import { readInboxFromRecord } from "@/lib/record";
126

137
export const runtime = "nodejs";
148
export const dynamic = "force-dynamic";
159

1610
/** Reject a Log item: undo what it wrote to the daily table (when the exact
17-
* cells were recorded at structure time) and mark it discarded. Pending items
11+
* cells were recorded at structure time) and mark it discarded. The undo is
12+
* conditional — a cell someone has changed since the merge holds THEIR value,
13+
* not the capture's, so it stays and `reverted` doesn't count it. Pending items
1814
* are simply discarded. `{ id }`. */
1915
export async function POST(req: Request) {
2016
if (!getCurrentUser()) {
@@ -37,31 +33,11 @@ export async function POST(req: Request) {
3733
return NextResponse.json({ error: "Already rejected." }, { status: 400 });
3834
}
3935

40-
// Undo the merge: replay the recorded cell changes in reverse (restore the
41-
// prior value; clear cells that didn't exist before).
42-
let reverted = 0;
43-
let touched: string[] = [];
44-
if (item.status === "structured") {
45-
const edits = revertEditsFromAppliedMeta(item.meta);
46-
const result = applyDailyEdits(edits, { recordDir: rDir });
47-
reverted = result.sets + result.clears;
48-
touched = result.sources;
49-
}
50-
51-
const rejected = {
52-
...item,
53-
status: "discarded",
54-
meta: {
55-
...(item.meta && typeof item.meta === "object" ? item.meta : {}),
56-
rejectedAt: new Date().toISOString(),
57-
},
58-
};
59-
updateInboxItems([{ id, status: rejected.status, meta: rejected.meta }], { recordDir: rDir });
60-
// Patch the cells this reject touched, then the one inbox row — a full rebuild
61-
// re-derives every event in the record (minutes of frozen server) to undo one
62-
// merge. landInboxCaptures falls back to that rebuild only when no cache exists.
63-
refreshSyncCache({ sources: touched }, { recordDir: rDir });
64-
landInboxCaptures([rejected], { recordDir: rDir });
36+
// One brain: the same core the CLI and MCP reject through. It replays the
37+
// recorded cells in reverse, forgets a rejected column-merge's rule (or the
38+
// next import would silently redo what this just undid), and patches only the
39+
// sources it rewrote plus the one inbox row — never a full rebuild.
40+
const { reverted } = logReject(id);
6541

6642
return NextResponse.json({ ok: true, reverted });
6743
}

0 commit comments

Comments
 (0)