Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/restore-claude-activity-time.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-backend-claude": patch
---

Preserve original activity timestamps when restoring archived Claude conversations, so history reads do not move old chats to the top of the list or restart their inactivity period.
6 changes: 3 additions & 3 deletions docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ owner for typed chats created after it.)
**Built (#3229):** first-party native removal behind the optional
`historyRemoval` backend capability
([package contract](../integration-contract/package-api.md#native-history-removal-additive-3229)).
Claude (`removeClaudeSession`, `packages/ui-backend-claude/src/transcript-archive.ts:331-357`)
Claude (`removeClaudeSession`, `packages/ui-backend-claude/src/transcript-archive.ts:337-363`)
and Pi (`removePiSession`, `packages/ui-backend-pi/src/session-storage.ts:101-117`)
name their owned artifacts; the shared fence
(`createSessionRetirement`, `packages/ui-sdk/src/server/native-history-removal.ts:117-224`)
Expand Down Expand Up @@ -167,11 +167,11 @@ must be tested through their installed runtime, not inferred from directory name
archive manifests/index/staged or conflict copies can contain readable text.
History reads can restore archived files before reading the SDK transcript
(`createHistory`, `packages/ui-backend-claude/src/history.ts:45-103`;
`restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:179-207`).
`restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:180-213`).
The live/archive roots are resolved by the backend
(`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`).
Archive movement and crash recovery must join the same lifecycle fence
(`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:261-321`).
(`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:267-327`).
Delete all owned branches/subagents/copies, not just the displayed branch.
Unknown/unattributable archive remnants mean removal is incomplete.
- **Native Pi history.** SessionManager JSONL trees retain inactive branches and
Expand Down
14 changes: 14 additions & 0 deletions packages/ui-backend-claude/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -367,3 +367,17 @@ text-part index and exact original text before folding the transcript into UI
messages. Cold archival and resume continue to copy the runtime transcript as
written; display metadata never becomes provider input. Older transcripts keep
their existing bytes.

## Archived history and activity time

History reads and worker resumes restore cold transcripts with the archive's
recorded `lastActiveAt` on their files and subordinate directories. Reading an
old conversation therefore preserves its list position and idle eligibility;
the resumed CLI's next write advances activity normally. The next daily sweep
can archive a restored conversation again if it has received no new writes.

The server's scratch-pin refresh reads retained conversation histories before
pruning scratch artifacts, including archived conversations. Those reads need
the transcript to discover links and preserve referenced files. The archive
sweep itself restores only an interrupted restore marked `restoring`; a fresh
archive is otherwise left cold.
9 changes: 7 additions & 2 deletions packages/ui-backend-claude/src/transcript-archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,17 @@ export function restoreArchivedSession(id: string, options: ArchiveOptions): voi
archivedBytes(archive, id, file);
}
atomic(join(source, "restoring"), "1");
const activity = new Date(record.session.lastActiveAt);
const parents = new Set<string>();
for (const file of record.files) {
const target = join(live, file.path);
atomic(target, archivedBytes(archive, id, file));
const now = new Date(options.now?.() ?? Date.now());
utimesSync(target, now, now);
utimesSync(target, activity, activity);
for (let parent = dirname(target); parent !== live; parent = dirname(parent)) parents.add(parent);
}
// Publishing children changes their parents' mtimes too. The idle scan
// includes directories, so reset them after every file has been restored.
for (const parent of parents) utimesSync(parent, activity, activity);
options.checkpoint?.("restore");
index(archive, manifests(archive, options.log).filter(m => m.session.id !== id).map(m => m.session));
rmSync(source, { recursive: true }); syncDirectory(archive);
Expand Down
47 changes: 44 additions & 3 deletions packages/ui-backend-claude/tests/transcript-archive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,48 @@ test("idle sessions move to gzip with SDK metadata and round-trip byte-identical
expect(readFileSync(join(live, `${ID}.jsonl`))).toEqual(before);
expect(readFileSync(join(live, ID, "notes.bin"))).toEqual(Buffer.from([0, 255, 17]));
expect(readFileSync(join(live, ID, "subagents/agent.jsonl"), "utf8")).toBe("Athena\n");
expect(statSync(join(live, `${ID}.jsonl`)).mtimeMs).toBe(now);
expect(statSync(join(live, `${ID}.jsonl`)).mtimeMs).toBe(now - 31 * DAY);
expect(savedIndex()).toEqual([]); expect(existsSync(join(archive, ID))).toBe(false);
now += DAY; await archiveIdleSessions(options);
expect(existsSync(join(live, `${ID}.jsonl`))).toBe(true);
expect(existsSync(join(live, `${ID}.jsonl`))).toBe(false);
});
test("history restoration retains listed activity and a real append advances it", async () => {
session();
const activity = now - 31 * DAY;
const transcript = join(live, `${ID}.jsonl`);
// The SDK reads lastModified from the live transcript's stat. Keep that
// boundary real rather than returning the fixture's stale metadata.
const history = createHistory({ brainPath: brain, env: options.env,
listSessionsFn: async () => existsSync(transcript)
? [{ ...metadata[0]!, lastModified: statSync(transcript).mtimeMs }] : [],
getSessionMessagesFn: async () => {
expect(readFileSync(transcript)).toEqual(Buffer.from('Odysseus\n\u0000\u00ff'));
return [];
} });
expect((await history.listSessions())[0]!.lastActiveAt).toBe(activity);
await archiveIdleSessions(options);
now += DAY;
expect((await history.listSessions())[0]!.lastActiveAt).toBe(activity);
const restoreClock = spyOn(Date, "now").mockReturnValue(now);
try {
await history.getHistory(ID);
expect((await history.listSessions())[0]!.lastActiveAt, "RESTORE_RETAINS_ACTIVITY_TIME").toBe(activity);
} finally { restoreClock.mockRestore(); }
// Model the resumed CLI's own append; the filesystem supplies its new mtime.
fs.appendFileSync(transcript, "\nReturn to Ithaca\n");
const appendedAt = statSync(transcript).mtimeMs;
expect(appendedAt).toBeGreaterThan(activity);
expect((await history.listSessions())[0]!.lastActiveAt).toBe(appendedAt);
});
test("a history-only restore is archived by the next daily sweep without a new inactivity period", async () => {
session(); await archiveIdleSessions(options);
const history = createHistory({ brainPath: brain, env: options.env, getSessionMessagesFn: async () => [] });
await history.getHistory(ID);
now += DAY; await archiveIdleSessions(options);
expect(errors).toEqual([]);
expect(existsSync(join(live, `${ID}.jsonl`)), "RESTORE_DOES_NOT_RESET_IDLE_THRESHOLD").toBe(false);
expect(existsSync(join(live, ID))).toBe(false);
expect(listArchivedSessions(options)[0]!.lastActiveAt).toBe(now - 32 * DAY);
});
test("newest nested mtime protects a session; exactly 30 days is not idle enough", async () => {
session(); session(OTHER, 30);
Expand Down Expand Up @@ -123,7 +161,10 @@ test("interrupted restore is completed on the next sweep, never deleted as an ol
expect(() => restoreArchivedSession(ID, { ...options, checkpoint: () => { throw new Error("interrupted restore"); } })).toThrow("interrupted restore");
expect(existsSync(join(archive, ID, "restoring"))).toBe(true);
now += DAY; await archiveIdleSessions(options);
expect(errors).toEqual([]); expect(savedIndex()).toEqual([]);
expect(errors).toEqual([]);
expect(existsSync(join(archive, ID, "restoring"))).toBe(false);
restoreArchivedSession(ID, options);
expect(savedIndex()).toEqual([]);
expect(readFileSync(join(live, ID, "subagents/agent.jsonl"), "utf8")).toBe("Athena\n");
});
test("recovery never deletes changed source bytes or a running session", async () => {
Expand Down
Loading