From 17efe163981416b2db11eff22eee3b93971cbd57 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 04:37:24 +0000 Subject: [PATCH 1/2] Make the library's trash visible, with Put back Removed pulls already kept their files until "Empty trash", but nothing showed what was in the trash, and the button was the only way in. The Library now has a Trash button with a count that opens a list of removed pulls, each with Put back, and Empty trash asks first and says what goes and what stays. Putting a pull back makes it current again unless a newer pull of its section was saved since; then it comes back as an earlier version. Prune history no longer empties the user's trash: it deletes only the versions it drops. A new column records when a pull was removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T34mysav6y1nxUtCUc5Yrf --- CLAUDE.md | 4 + README.md | 10 +- docs/architecture.md | 5 + docs/user-guide.md | 26 ++++- src/db/migrations/0010_trash.sql | 4 + src/db/store.ts | 89 +++++++++++++++--- src/main/library.ts | 51 ++++++---- src/main/workspace.ts | 19 +++- src/shared/bridge.ts | 21 ++++- src/ui/format.ts | 9 +- src/ui/library.tsx | 151 +++++++++++++++++++++++++----- src/ui/styles.css | 6 ++ test/library.test.ts | 59 ++++++++++++ test/review-renderer.electron.cjs | 48 ++++++++-- test/ui-format.test.ts | 19 +++- 15 files changed, 442 insertions(+), 79 deletions(-) create mode 100644 src/db/migrations/0010_trash.sql diff --git a/CLAUDE.md b/CLAUDE.md index cd45769..d2261d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -96,6 +96,10 @@ original plan and any signed-in notes stay out of the repository (see `.gitignor - **What the user types is checked for credentials before it is stored**, not only before it is sent: `Runtime.start` and `answer`, and `Workspace.savePlan` and `approve`. A new place that stores typed text needs the same check (`holdsSecret`). +- **Removing a pull is not deleting it.** `Store.deletePull` moves it to the trash: a removed pull + that still has `artifacts` rows can be put back (`Store.putBack`). Only the user's **Empty trash** + deletes every removed pull's files; anything else that deletes files names its own pulls + (`Library.emptyTrash(ids)`, as `prune` does). - **A capture far shorter than the saved pull is refused in `Library.commit`** (`ShorterCapture`). Only a capture by hand passes `byHand`. Do not add another bypass. - **A folder written and then renamed uses `renameRetrying`** (`src/main/replace.ts`). On Windows diff --git a/README.md b/README.md index ebcdf11..fb87c73 100644 --- a/README.md +++ b/README.md @@ -450,10 +450,16 @@ only some parts (with your reason, which is recorded), or remove it. can be found. - **Removing the current pull of a section** makes the earlier version current again, if one is kept: the library lists it and new requests reuse it. The app says so when it happens. +- **Removed pulls go to the trash.** **Remove** takes a pull out of the library, but its PDF and Word + files stay on disk. The Library's **Trash** button shows how many pulls are in it and opens a list of + them, with when each was removed. **Put back** returns one to the library: it is current again + unless a newer pull of its section was saved since, in which case it comes back as an earlier + version. **Empty trash…** asks first, then deletes the files of the pulls in the trash; it never + touches the pulls in the library or files you exported, and once emptied, a pull cannot be put back. **Export index** writes a spreadsheet of what you hold: code, edition, jurisdiction, section, date and -account. It contains no code text. **Prune history** drops old versions beyond the number you keep. -Removed pulls go to a trash you empty yourself. +account. It contains no code text. **Prune history** deletes old versions beyond the number you keep; +it leaves the trash alone. ### Combine pulls into one PDF diff --git a/docs/architecture.md b/docs/architecture.md index 858a1ac..1ec5dde 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -137,6 +137,11 @@ The hard rules are tested by name. Search the tests for `rule_R` to see each one page. The queue does not ask Claude to look at such a page, and `save_pull` reports the stop. - **Removing the current pull** (`Store.deletePull`) makes the revision it replaced active again in the same transaction, so the library and reuse fall back to it. + - **The trash** is the removed pulls that still have `artifacts` rows (`Store.trash`); `removed_at` + orders it. `Store.putBack` returns one to the library: active again when it is newer than the + key's active pull, or the key has none, otherwise superseded. `Library.emptyTrash` deletes the + document folders and `artifacts` and `reissues` rows of removed pulls, every one or only those + named; `Library.prune` names only the revisions it drops, so it never empties the user's trash. - **Every save records the same things.** `Library.publish` takes the adapter version and the adopting-agency table setting, so a capture by hand and one found on a screenshot are saved as a queued pull is. diff --git a/docs/user-guide.md b/docs/user-guide.md index bb6bdeb..64fee5f 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -260,8 +260,9 @@ that comes out unchanged is kept as it was; one that changed replaces it, and th as an earlier version. It also repairs: a PDF or Word file that was changed or deleted in the library folder is put back as it was verified, after which exports work again. -**Remove** takes a pull out of the library. If it was the current pull of its section and an earlier -version is kept, that version is current again and the app tells you. +**Remove** moves a pull to the trash (see [The trash](#the-trash)). If it was the current pull of its +section and an earlier version is kept, that version is current again and the app tells you. Nothing is +deleted until you empty the trash, so a pull removed by mistake can be put back. ## Plan a project @@ -481,8 +482,25 @@ at the top stays until you choose **Resume**. - **Search** looks in code names, section numbers and the text itself. - **Filters** narrow by jurisdiction and by status. - **Export index** saves a spreadsheet of what you hold. It has no code text in it. -- **Prune history** removes earlier versions beyond the number set in Settings. -- **Empty trash** deletes the files of pulls you removed. +- **Prune history** deletes earlier versions beyond the number set in Settings. The current version + of every section stays, and the trash is left as it is. +- **Trash** shows the pulls you removed. The button shows how many there are, as in **Trash (2)**. + +### The trash + +When you remove a pull, it leaves the library but its PDF and Word files stay on disk. It waits in the +trash. Open **Trash** in the Library to see each removed pull with its section, jurisdiction, pull date +and the time you removed it. + +- **Put back** returns a pull to the library with its documents as they were. It is the current pull of + its section again, unless a newer pull of the same section has been saved since; then it comes back as + an earlier version, and the app tells you so. +- **Empty trash…** asks first, then deletes the PDF and Word files of every pull in the trash. After + that they cannot be put back; pull the section again if you need it. Emptying the trash never touches + the pulls in your library or files you exported to your own folders, and removed pulls stay readable + in plans and history. + +If you have never removed a pull, the trash is empty and there is nothing to delete. ### Combine pulls into one PDF diff --git a/src/db/migrations/0010_trash.sql b/src/db/migrations/0010_trash.sql new file mode 100644 index 0000000..9f144bd --- /dev/null +++ b/src/db/migrations/0010_trash.sql @@ -0,0 +1,4 @@ +-- When a pull was removed from the library. The trash lists the removed pulls whose documents are +-- still on disk, the one removed last first, and the user can put one back until the trash is +-- emptied. Pulls removed before this column have no time and are listed after the others. +ALTER TABLE pulls ADD COLUMN removed_at TEXT; diff --git a/src/db/store.ts b/src/db/store.ts index a9a6417..162cb96 100644 --- a/src/db/store.ts +++ b/src/db/store.ts @@ -14,6 +14,7 @@ import type { PullReview, Settings, Target, + TrashedPull, } from '../shared/bridge'; import { HISTORY_PULLS } from '../shared/claude-cost'; import { completedPullDetail } from '../shared/pull-status'; @@ -99,6 +100,22 @@ export interface StoredResult { appVersion: string; } const active = "status='active' AND verify_status IN ('verified','verified_with_warnings')"; +/** What a list of pulls reads of each row (`Store.summary`). */ +const listed = `id, pulled_at, needs_review, reviewed_at, jurisdiction, code_id, edition, + target_canonical, scope_kind, custom_scope_json, text_basis, code_title, header_line, source_url, + account_label, is_sample, is_model_text, verify_status, text_changed, dismissed_at, + coalesce(json_extract(verify_report_json, '$.stats.gaps'), 0) AS gap_count`; +/** The columns that make a pull's exact key (rule 7), and the condition that matches one. */ +const keyColumns = [ + 'site_id', + 'jurisdiction', + 'code_id', + 'edition', + 'target_canonical', + 'scope_kind', + 'scope_hash', +] as const; +const sameKey = keyColumns.map((c) => c + '=?').join(' AND '); function readPullReview(r: Row, id: string): PullReview { return { id, @@ -643,11 +660,7 @@ export class Store { } pulls(query = '') { const words = [...new Set(query.match(/[\p{L}\p{N}]+/gu))]; - const select = `SELECT id, pulled_at, needs_review, reviewed_at, jurisdiction, code_id, edition, - target_canonical, scope_kind, custom_scope_json, text_basis, code_title, header_line, source_url, - account_label, is_sample, is_model_text, verify_status, text_changed, dismissed_at, - coalesce(json_extract(verify_report_json, '$.stats.gaps'), 0) AS gap_count - FROM pulls WHERE ${active}`; + const select = `SELECT ${listed} FROM pulls WHERE ${active}`; return ( words.length ? this.all( @@ -784,23 +797,18 @@ export class Store { * Remove a pull from the library. When it was the current revision of its exact key, the newest * earlier revision of that key that is still kept becomes current again, in the same step: the * library and reuse fall back to it instead of holding nothing. Resolves to that revision's ID. + * The pull's documents stay on disk, in the trash, until the user empties it. */ deletePull(id: string): string | undefined { return this.tx(() => { const row = this.pullRow(id); - this.run("UPDATE pulls SET status='deleted' WHERE id=?", id); + this.run("UPDATE pulls SET status='deleted',removed_at=? WHERE id=?", now(), id); if (row.status !== 'active') return undefined; const earlier = this.one( `SELECT id FROM pulls WHERE status='superseded' AND verify_status IN ('verified','verified_with_warnings') - AND site_id=? AND jurisdiction=? AND code_id=? AND edition=? AND target_canonical=? AND scope_kind=? AND scope_hash=? + AND ${sameKey} ORDER BY (superseded_by IS ?) DESC, pulled_at DESC LIMIT 1`, - str(row, 'site_id'), - str(row, 'jurisdiction'), - str(row, 'code_id'), - str(row, 'edition'), - str(row, 'target_canonical'), - str(row, 'scope_kind'), - str(row, 'scope_hash'), + ...keyColumns.map((c) => str(row, c)), // The revision this one replaced comes first; otherwise the newest that is left. id, ); @@ -809,6 +817,59 @@ export class Store { return str(earlier, 'id'); }); } + /** + * The trash: pulls removed from the library whose documents are still on disk, the one removed + * last first. Emptying the trash deletes those documents (`Library.emptyTrash`); until then each + * can be put back (`putBack`). + */ + trash(): TrashedPull[] { + return this.all( + `SELECT ${listed}, removed_at FROM pulls p WHERE status='deleted' + AND EXISTS (SELECT 1 FROM artifacts a WHERE a.pull_id=p.id) + ORDER BY removed_at IS NULL, removed_at DESC, pulled_at DESC`, + ).map((r) => ({ + ...this.summary(r), + removedAt: r.removed_at ? str(r, 'removed_at') : undefined, + })); + } + /** + * Put a pull from the trash back in the library. It is the current pull of its section again + * when it is newer than the one that is current now, or when the section has none; the one it + * takes over from becomes an earlier version, as when a newer pull is saved. Otherwise it comes + * back as an earlier version. Its documents were never touched, so nothing is made again. + */ + putBack(id: string): { current: boolean } { + return this.tx(() => { + const row = this.one("SELECT * FROM pulls WHERE id=? AND status='deleted'", id); + if (!row) throw Error('This pull is not in the trash.'); + if (!this.one('SELECT 1 FROM artifacts WHERE pull_id=?', id)) + throw Error( + 'The documents of this pull were deleted when the trash was emptied. Pull the section again.', + ); + const current = this.one( + `SELECT id, pulled_at FROM pulls WHERE status='active' AND ${sameKey}`, + ...keyColumns.map((c) => str(row, c)), + ); + const verified = ['verified', 'verified_with_warnings'].includes(str(row, 'verify_status')); + if (verified && (!current || str(row, 'pulled_at') > str(current, 'pulled_at'))) { + // Exactly one pull of a key is current: the one it takes over from steps down first. + if (current) + this.run( + "UPDATE pulls SET status='superseded',superseded_by=? WHERE id=?", + id, + str(current, 'id'), + ); + this.run("UPDATE pulls SET status='active',superseded_by=NULL,removed_at=NULL WHERE id=?", id); + return { current: true }; + } + this.run( + "UPDATE pulls SET status='superseded',superseded_by=coalesce(superseded_by,?),removed_at=NULL WHERE id=?", + current ? str(current, 'id') : null, + id, + ); + return { current: false }; + }); + } artifact(id: string, kind: string) { const r = this.one('SELECT path FROM artifacts WHERE pull_id=? AND kind=?', id, kind); if (!r) throw Error('Artifact unavailable.'); diff --git a/src/main/library.ts b/src/main/library.ts index c9b7242..913b7a8 100644 --- a/src/main/library.ts +++ b/src/main/library.ts @@ -429,28 +429,39 @@ export class Library { seen.set(key, count); if (count > keep) drop.push(String(r.id)); } - for (const id of drop) this.store.run("UPDATE pulls SET status='deleted' WHERE id=?", id); - await this.emptyTrash(); + for (const id of drop) + this.store.run("UPDATE pulls SET status='deleted',removed_at=? WHERE id=?", now(), id); + // Only the versions dropped here: pulls the user removed stay in the trash until they empty it. + await this.emptyTrash(drop); return drop.length; } - /** Delete the documents of removed pulls. Their rows stay so plans and history remain readable. */ - async emptyTrash() { - const rows = this.store.all( - "SELECT a.path FROM artifacts a JOIN pulls p ON p.id=a.pull_id WHERE p.status='deleted' " + - "UNION SELECT r.old_path FROM reissues r JOIN pulls p ON p.id=r.pull_id WHERE p.status='deleted'", - ); - const folders = new Set(); - for (const r of rows) folders.add(path.dirname(path.join(this.root, String(r.path)))); - for (const folder of folders) - if (path.resolve(folder).startsWith(path.resolve(this.root) + path.sep)) - await fs.rm(folder, { recursive: true, force: true }).catch(() => {}); - this.store.run( - "DELETE FROM artifacts WHERE pull_id IN (SELECT id FROM pulls WHERE status='deleted')", - ); - this.store.run( - "DELETE FROM reissues WHERE pull_id IN (SELECT id FROM pulls WHERE status='deleted')", - ); - return folders.size; + /** + * Delete the documents of removed pulls: every pull in the trash, or only those named. Their rows + * stay so plans and history remain readable; with no documents, they leave the trash and can no + * longer be put back. Resolves to the number of pulls whose documents were deleted. + */ + async emptyTrash(only?: string[]) { + const ids = this.store + .all("SELECT id FROM pulls WHERE status='deleted'") + .map((r) => String(r.id)) + .filter((id) => !only || only.includes(id)); + let emptied = 0; + for (const id of ids) { + const rows = this.store.all( + 'SELECT path FROM artifacts WHERE pull_id=? UNION SELECT old_path FROM reissues WHERE pull_id=?', + id, + id, + ); + if (!rows.length) continue; + const folders = new Set(rows.map((r) => path.dirname(path.join(this.root, String(r.path))))); + for (const folder of folders) + if (path.resolve(folder).startsWith(path.resolve(this.root) + path.sep)) + await fs.rm(folder, { recursive: true, force: true }).catch(() => {}); + this.store.run('DELETE FROM artifacts WHERE pull_id=?', id); + this.store.run('DELETE FROM reissues WHERE pull_id=?', id); + emptied++; + } + return emptied; } detail(id: string): PullDetail { const r = this.store.pullRow(id), diff --git a/src/main/workspace.ts b/src/main/workspace.ts index 75beea6..131163d 100644 --- a/src/main/workspace.ts +++ b/src/main/workspace.ts @@ -651,6 +651,7 @@ export class Workspace implements Omit { jobs: this.store.jobs(new Date(this.clock.now()).toISOString()), plans: this.store.plans(), pulls: this.store.pulls(), + trash: this.store.trash(), settings, paused: this.store.get('paused', false), models, @@ -1567,7 +1568,23 @@ export class Workspace implements Omit { action: Parameters[0], pullId: string, ): Promise { - z.enum(['review', 'delete', 'refresh', 'reveal', 'rerender', 'prune', 'emptyTrash']).parse(action); + z.enum([ + 'review', + 'delete', + 'putBack', + 'refresh', + 'reveal', + 'rerender', + 'prune', + 'emptyTrash', + ]).parse(action); + if (action === 'putBack') { + // A pull in the trash is not in the library, so it is looked up apart from the others. + const { current } = this.store.putBack(id.parse(pullId)); + this.log('library', 'pull.put_back', { current }, { pullId }); + this.changed(); + return { putBack: current ? 'current' : 'earlier' }; + } if (action === 'prune') { await this.libraryService.prune(this.store.settings().keepVersions); this.changed(); diff --git a/src/shared/bridge.ts b/src/shared/bridge.ts index c127439..d55b67f 100644 --- a/src/shared/bridge.ts +++ b/src/shared/bridge.ts @@ -183,10 +183,20 @@ export interface Pull extends PullReview { /** Taken off the home screen's recent list by the user. It stays in the library. */ dismissed: boolean; } +/** A pull removed from the library whose documents are still on disk, in the trash. */ +export interface TrashedPull extends Pull { + /** When it was removed. Pulls removed before the trash recorded a time have none. */ + removedAt?: string; +} /** What a library action did, when there is something to tell the user. */ export interface LibraryOutcome { /** Removing the current pull made this earlier revision of the same section current again. */ restoredPullId?: string; + /** + * A pull put back from the trash: `current` when it is the section's current pull again, + * `earlier` when a newer pull of the section is current and it came back as an earlier version. + */ + putBack?: 'current' | 'earlier'; } export interface Check { id: string; @@ -363,6 +373,8 @@ export interface State { plans: Plan[]; jobs: Job[]; pulls: Pull[]; + /** Removed pulls whose documents are still on disk: the trash. */ + trash: TrashedPull[]; settings: Settings; paused: boolean; hasKey: boolean; @@ -478,11 +490,14 @@ export interface Bridge { importSample(): Promise; pull(id: string): Promise; /** - * `delete` removes a pull from the library. When it was the current revision of its section and - * an earlier revision is kept, that one becomes current again and the answer names it. + * `delete` moves a pull to the trash. When it was the current revision of its section and an + * earlier revision is kept, that one becomes current again and the answer names it. `putBack` + * returns a pull from the trash to the library and says whether it is current again. + * `emptyTrash` deletes the documents of every pull in the trash; `prune` deletes those of + * earlier versions beyond the number kept, and leaves the trash alone. */ library( - action: 'review' | 'delete' | 'refresh' | 'reveal' | 'rerender' | 'prune' | 'emptyTrash', + action: 'review' | 'delete' | 'putBack' | 'refresh' | 'reveal' | 'rerender' | 'prune' | 'emptyTrash', id: string, ): Promise; exportPull(id: string, format: 'pdf' | 'docx'): Promise; diff --git a/src/ui/format.ts b/src/ui/format.ts index f3c1b2f..5e23d88 100644 --- a/src/ui/format.ts +++ b/src/ui/format.ts @@ -223,8 +223,13 @@ export function runToShow(runs: readonly AgentRun[], chosen: string): AgentRun | */ export const removedNotice = (outcome: LibraryOutcome | void) => outcome?.restoredPullId - ? 'Pull removed. The earlier version of this section is current again.' - : 'Pull removed from the library.'; + ? 'Pull moved to the trash. The earlier version of this section is current again.' + : 'Pull moved to the trash. You can put it back from the Library’s Trash.'; +/** What putting a pull back from the trash did. */ +export const putBackNotice = (outcome: LibraryOutcome | void) => + outcome?.putBack === 'earlier' + ? 'Pull put back as an earlier version. A newer pull of this section is current.' + : 'Pull put back in the library.'; /** How far a set of jobs has got. Cancelled jobs are left out of the total. */ export function progress(jobs: Job[]) { diff --git a/src/ui/library.tsx b/src/ui/library.tsx index ac1a1cf..91aa077 100644 --- a/src/ui/library.tsx +++ b/src/ui/library.tsx @@ -21,10 +21,11 @@ import { Search, ShieldCheck, Trash2, + Undo2, X, } from 'lucide-react'; import { useEffect, useRef, useState, type MouseEvent } from 'react'; -import type { Check, Pull, PullDetail, Target } from '../shared/bridge'; +import type { Check, Pull, PullDetail, Target, TrashedPull } from '../shared/bridge'; import { codeOrder, containedIn, @@ -38,6 +39,7 @@ import { isOpen, jobStatus, plural, + putBackNotice, readable, removedNotice, sameTarget, @@ -99,7 +101,8 @@ export function LibraryPage() { const [resultQuery, setResultQuery] = useState(''); const [filter, setFilter] = useState(''); const [jurisdiction, setJurisdiction] = useState(''); - const [confirm, setConfirm] = useState<'prune' | 'emptyTrash' | null>(null); + const [confirm, setConfirm] = useState<'prune' | null>(null); + const [showTrash, setShowTrash] = useState(false); // Ticked pulls, in the order they were ticked. They stay ticked through searches and filters. const [picked, setPicked] = useState([]); const lastTicked = useRef(''); @@ -201,9 +204,14 @@ export function LibraryPage() { Prune history - } @@ -428,26 +436,123 @@ export function LibraryPage() { > For each section, CodePull keeps the newest {state.settings.keepVersions} earlier{' '} {state.settings.keepVersions === 1 ? 'version' : 'versions'} and deletes the documents of older - ones. The current version of every section stays. This cannot be undone. - - )} - {confirm === 'emptyTrash' && ( - setConfirm(null)} - action={async () => { - await window.codepull.library('emptyTrash', ''); - notify('Trash emptied.'); - }} - > - This deletes the documents of pulls you removed from the library. Their entries stay readable - in plans and history. This cannot be undone. + ones. The current version of every section stays, and the trash is left as it is. This cannot + be undone. )} + {showTrash && setShowTrash(false)} />} ); } +/** + * The trash: pulls the user removed from the library, with their documents still on disk. Each can + * be put back. Emptying it deletes those documents and nothing else. + */ +function TrashDialog({ close }: { close: () => void }) { + const { state, busy, run, notify } = useWorkspace(); + const [emptying, setEmptying] = useState(false); + const [problem, setProblem] = useState(''); + const trash = state.trash; + const name = (p: TrashedPull) => (p.title || p.target.codeId) + ' ' + sectionLabel(p.target); + const putBack = (p: TrashedPull) => + void run('Putting the pull back…', async () => { + setProblem(''); + try { + notify(putBackNotice(await window.codepull.library('putBack', p.id))); + } catch (e) { + setProblem(readable(e)); + } + }); + if (emptying) + return ( + setEmptying(false)} + action={async () => { + await window.codepull.library('emptyTrash', ''); + notify('Trash emptied.'); + }} + > + This deletes the PDF and Word files of the {plural(trash.length, 'pull')} in the trash, and they + can no longer be put back. Pulls in your library are not touched, and the removed ones stay + readable in plans and history. This cannot be undone. + + ); + return ( + +
+

+ When you remove a pull from the library, it waits here with its PDF and Word files. Put it back + if you removed it by mistake. Emptying the trash deletes these files for good; it never touches + the pulls in your library or files you exported. +

+ {problem && {problem}} + {!trash.length ? ( + + Nothing has been removed from the library, or the trash was emptied. + + ) : ( +
+ + + + + + + + + + + + {trash.map((p) => ( + + + + + + + + ))} + +
SectionJurisdictionPulledRemoved + Put back +
+ {p.title || p.target.codeId} + + {sectionLabel(p.target)} · {p.target.edition} + + {p.target.jurisdiction}{dateTime(p.pulledAt)}{dateTime(p.removedAt)} + +
+
+ )} +
+ + +
+
+
+ ); +} export function Viewer({ pull, back }: { pull: PullDetail; back: () => void }) { const { state, busy, run, navigate, notify, openPull, startRun } = useWorkspace(); const [remove, setRemove] = useState(false); @@ -790,18 +895,18 @@ export function Viewer({ pull, back }: { pull: PullDetail; back: () => void }) { {selectingBlocks && setSelectingBlocks(false)} />} {remove && ( - setRemove(false)}> + setRemove(false)}>

- Remove {pull.target.codeId} {sectionLabel(pull.target)} from the library. Its documents - stay on disk until you empty the trash. + {pull.target.codeId} {sectionLabel(pull.target)} leaves the library. Its PDF and Word files + stay on disk, and you can put it back from the Library’s Trash until you empty it.

diff --git a/src/ui/styles.css b/src/ui/styles.css index c159a15..f8579cf 100644 --- a/src/ui/styles.css +++ b/src/ui/styles.css @@ -1904,6 +1904,12 @@ textarea:disabled { tr.row-picked td { background: #f4f9f1; } +/* Library: the trash. */ +.cell-action { + width: 1%; + white-space: nowrap; + text-align: right; +} .library-bar { margin-top: 14px; } diff --git a/test/library.test.ts b/test/library.test.ts index 99e3a49..6237c1e 100644 --- a/test/library.test.ts +++ b/test/library.test.ts @@ -293,6 +293,65 @@ test('one damaged document among many is named by its code, unit and jurisdictio ); }); +test('a removed pull waits in the trash with its documents and can be put back until it is emptied', async (t) => { + const { store, library, folders, save } = setup(t); + const on = (iso: string) => { + const c = capture(10); + c.tree.meta.pulledAt = iso; + return c; + }; + const first = await save(on('2026-01-01T00:00:00.000Z')); + const second = await save(on('2026-02-01T00:00:00.000Z')); + const trash = () => store.trash().map((p) => p.id); + + // Removing the current pull puts it in the trash, files and all; the earlier one is current. + assert.equal(store.deletePull(second), first); + assert.deepEqual(trash(), [second]); + assert.ok(store.trash()[0]!.removedAt, 'the trash says when it was removed'); + assert.ok(folders().includes(second), 'its documents are still on disk'); + assert.equal(store.cache(target)!.id, first); + + // Put back, it is current again, and the earlier one steps down as it did before. + assert.deepEqual(store.putBack(second), { current: true }); + assert.equal(store.cache(target)!.id, second); + assert.equal(store.pullRow(first).status, 'superseded'); + assert.equal(store.pullRow(first).superseded_by, second); + assert.equal(store.pullRow(second).removed_at, null); + assert.deepEqual(trash(), []); + + // An earlier version comes back as an earlier version. + store.deletePull(first); + assert.deepEqual(store.putBack(first), { current: false }); + assert.equal(store.cache(target)!.id, second); + assert.equal(store.pullRow(first).status, 'superseded'); + + // A pull saved since it was removed is newer, and stays current. + store.deletePull(second); + const third = await save(on('2026-03-01T00:00:00.000Z')); + assert.deepEqual(store.putBack(second), { current: false }); + assert.equal(store.cache(target)!.id, third); + assert.equal(store.pullRow(second).status, 'superseded'); + assert.throws(() => store.putBack(third), /not in the trash/); + + // Pruning the history deletes the versions it drops and leaves what the user removed alone. + store.deletePull(first); + await library.prune(0); + assert.deepEqual(trash(), [first], 'the removed pull is still in the trash'); + assert.ok(folders().includes(first)); + assert.ok(!folders().includes(second), 'the pruned version is gone'); + assert.deepEqual( + store.pulls().map((p) => p.id), + [third], + ); + + // Emptying the trash deletes its documents, and then it can no longer be put back. + assert.equal(await library.emptyTrash(), 1); + assert.deepEqual(trash(), []); + assert.deepEqual(folders(), [third], 'only the library is left'); + assert.throws(() => store.putBack(first), /deleted when the trash was emptied/); + assert.equal(await library.emptyTrash(), 0, 'an empty trash empties nothing'); +}); + test('deleting every document goes on past a folder another program holds', async (t) => { const { library, folders, save } = setup(t); const held = await save(capture(12)); diff --git a/test/review-renderer.electron.cjs b/test/review-renderer.electron.cjs index 436279f..10b1a28 100644 --- a/test/review-renderer.electron.cjs +++ b/test/review-renderer.electron.cjs @@ -1749,12 +1749,48 @@ async function exercise() { await t.waitFor('the prune dialog', () => t.has('keeps the newest 3 earlier versions')); await t.click('Prune history'); await t.waitFor('the pruned history', () => t.has('Older versions pruned.')); - await t.click('Empty trash'); - await t.waitFor('the trash dialog', () => - t.has('This deletes the documents of pulls you removed'), + // The trash says what it is, even with nothing in it. + await t.click('Trash'); + await t.waitFor('the empty trash', () => t.has('The trash is empty')); + t.expect('When you remove a pull from the library, it waits here'); + if (t.button('Empty trash…')) throw Error('An empty trash offers to be emptied.'); + await t.click('Close'); + // A pull removed by mistake waits in the trash with its files and comes back. + const fireRow = () => row('Example Fire Code 2024'); + fireRow().querySelector('.plain-title').click(); + await t.click('Remove'); + await t.waitFor('the remove dialog', () => + t.has('you can put it back from the Library’s Trash until you empty it'), + ); + await t.click('Move to trash'); + await t.waitFor('the removed pull', () => t.has('Pull moved to the trash.')); + await t.idle(); + await t.go('Library'); + await t.click('Trash (1)'); + await t.waitFor( + 'the pull in the trash', + () => + t.all('tbody tr').length === 1 && + t.text(t.all('tbody tr')[0]).includes('Example Fire Code 2024'), ); - await t.click('Empty trash'); - await t.waitFor('the emptied trash', () => t.has('Trash emptied.')); + }); + await shot('05a-trash.png'); + await ui(async () => { + const t = window.t; + const row = (title) => t.find('tbody tr', (tr) => t.text(tr).includes(title)); + const fireRow = () => row('Example Fire Code 2024'); + // Emptying asks first, says what goes and what stays, and can be called off. + await t.click('Empty trash…'); + await t.waitFor('the empty-trash dialog', () => + t.has('This deletes the PDF and Word files of the 1 pull in the trash'), + ); + t.expect('Pulls in your library are not touched'); + await t.click('Keep them'); + await t.click('Put back', () => t.all('tbody tr')[0]); + await t.waitFor('the pull put back', () => t.has('Pull put back')); + await t.waitFor('the trash empty again', () => t.has('The trash is empty')); + await t.click('Close'); + await t.waitFor('the pull back in the library', fireRow); await t.waitFor('the full list', () => t.all('tbody tr').length >= 10); window.scrollTo(0, 0); t.plainCopy(); @@ -2312,7 +2348,7 @@ async function exercise() { 'model text, a narrowed subsection with its note, a cross-reference queued from the viewer, a Claude question ' + 'answered with an option, a project plan with a corrected fact, a re-plan, edits and approval, queue progress, ' + 'expired sign-in with Sign in and Retry, explicit re-assignment, the site-paused banner and Resume, Pause all, ' + - 'the pacing countdown, cancelling a running pull, capture by hand, library badges and clean-up, ticking and combining library pulls into one PDF, ' + + 'the pacing countdown, cancelling a running pull, capture by hand, library badges and clean-up, a pull put back from the trash, ticking and combining library pulls into one PDF, ' + 'a limit question, stopping and restarting a request, a refused credential, the sample, a finished plan and ' + 'its bundle, the other account actions with a saved password, a whole code drafted with its estimate, checking for updates, diagnostics, the app without a key, ' + 'the home lists folded and cleared, the brand and breadcrumb leading home, a workspace that began in ' + diff --git a/test/ui-format.test.ts b/test/ui-format.test.ts index ebc8253..5d5f01b 100644 --- a/test/ui-format.test.ts +++ b/test/ui-format.test.ts @@ -7,6 +7,7 @@ import { isUserRun, openJobs, planKind, + putBackNotice, queueRows, removedNotice, runToShow, @@ -187,9 +188,19 @@ test("only the user's requests are requests: the queue's own Claude runs are not test('removing a pull says so when the earlier version of its section became current again', () => { assert.equal( removedNotice({ restoredPullId: 'an-earlier-pull' }), - 'Pull removed. The earlier version of this section is current again.', + 'Pull moved to the trash. The earlier version of this section is current again.', ); - // Nothing came back, or nothing to tell: the notice is the one it always was. - assert.equal(removedNotice(undefined), 'Pull removed from the library.'); - assert.equal(removedNotice({}), 'Pull removed from the library.'); + // Nothing came back, or nothing to tell: the notice says where the pull went. + const moved = 'Pull moved to the trash. You can put it back from the Library’s Trash.'; + assert.equal(removedNotice(undefined), moved); + assert.equal(removedNotice({}), moved); +}); + +test('putting a pull back says when a newer pull of its section stays current', () => { + assert.equal(putBackNotice({ putBack: 'current' }), 'Pull put back in the library.'); + assert.equal( + putBackNotice({ putBack: 'earlier' }), + 'Pull put back as an earlier version. A newer pull of this section is current.', + ); + assert.equal(putBackNotice(undefined), 'Pull put back in the library.'); }); From 82322cc72c7cac81ce86ee4abbd37416b9ec5251 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 04:40:46 +0000 Subject: [PATCH 2/2] Empty the trash in the database before deleting its folders Emptying the trash read its list of pulls once, then deleted folders one by one. A pull put back while that ran was made current again and then lost its documents and file records. The pulls now leave the trash in one transaction before any folder is deleted: a pull put back meanwhile is either back already and kept, or refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T34mysav6y1nxUtCUc5Yrf --- docs/architecture.md | 6 ++++-- src/main/library.ts | 48 ++++++++++++++++++++++++++------------------ test/library.test.ts | 20 ++++++++++++++++++ 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 1ec5dde..eb03686 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -140,8 +140,10 @@ The hard rules are tested by name. Search the tests for `rule_R` to see each one - **The trash** is the removed pulls that still have `artifacts` rows (`Store.trash`); `removed_at` orders it. `Store.putBack` returns one to the library: active again when it is newer than the key's active pull, or the key has none, otherwise superseded. `Library.emptyTrash` deletes the - document folders and `artifacts` and `reissues` rows of removed pulls, every one or only those - named; `Library.prune` names only the revisions it drops, so it never empties the user's trash. + `artifacts` and `reissues` rows of removed pulls, every one or only those named, in one + transaction, and only then their document folders, so a pull put back meanwhile is either kept + whole or refused. `Library.prune` names only the revisions it drops, so it never empties the + user's trash. - **Every save records the same things.** `Library.publish` takes the adapter version and the adopting-agency table setting, so a capture by hand and one found on a screenshot are saved as a queued pull is. diff --git a/src/main/library.ts b/src/main/library.ts index 913b7a8..4280c70 100644 --- a/src/main/library.ts +++ b/src/main/library.ts @@ -439,28 +439,36 @@ export class Library { * Delete the documents of removed pulls: every pull in the trash, or only those named. Their rows * stay so plans and history remain readable; with no documents, they leave the trash and can no * longer be put back. Resolves to the number of pulls whose documents were deleted. + * + * The pulls leave the trash in one step before any folder is deleted. A pull put back while the + * folders go is either back already, and kept, or out of the trash, and refused: deleting files + * takes time, and a pull must never be put back and then lose its documents. */ async emptyTrash(only?: string[]) { - const ids = this.store - .all("SELECT id FROM pulls WHERE status='deleted'") - .map((r) => String(r.id)) - .filter((id) => !only || only.includes(id)); - let emptied = 0; - for (const id of ids) { - const rows = this.store.all( - 'SELECT path FROM artifacts WHERE pull_id=? UNION SELECT old_path FROM reissues WHERE pull_id=?', - id, - id, - ); - if (!rows.length) continue; - const folders = new Set(rows.map((r) => path.dirname(path.join(this.root, String(r.path))))); - for (const folder of folders) - if (path.resolve(folder).startsWith(path.resolve(this.root) + path.sep)) - await fs.rm(folder, { recursive: true, force: true }).catch(() => {}); - this.store.run('DELETE FROM artifacts WHERE pull_id=?', id); - this.store.run('DELETE FROM reissues WHERE pull_id=?', id); - emptied++; - } + const { emptied, folders } = this.store.tx(() => { + const ids = this.store + .all( + "SELECT id FROM pulls p WHERE status='deleted' AND (EXISTS (SELECT 1 FROM artifacts a WHERE a.pull_id=p.id) OR EXISTS (SELECT 1 FROM reissues r WHERE r.pull_id=p.id))", + ) + .map((r) => String(r.id)) + .filter((id) => !only || only.includes(id)); + const folders = new Set(); + for (const id of ids) { + for (const r of this.store.all( + 'SELECT path FROM artifacts WHERE pull_id=? UNION SELECT old_path FROM reissues WHERE pull_id=?', + id, + id, + )) + folders.add(path.dirname(path.join(this.root, String(r.path)))); + this.store.run('DELETE FROM artifacts WHERE pull_id=?', id); + this.store.run('DELETE FROM reissues WHERE pull_id=?', id); + } + return { emptied: ids.length, folders }; + }); + // A folder that cannot be removed now has no row that refers to it: the next start sweeps it. + for (const folder of folders) + if (path.resolve(folder).startsWith(path.resolve(this.root) + path.sep)) + await fs.rm(folder, { recursive: true, force: true }).catch(() => {}); return emptied; } detail(id: string): PullDetail { diff --git a/test/library.test.ts b/test/library.test.ts index 6237c1e..73e11a9 100644 --- a/test/library.test.ts +++ b/test/library.test.ts @@ -352,6 +352,26 @@ test('a removed pull waits in the trash with its documents and can be put back u assert.equal(await library.emptyTrash(), 0, 'an empty trash empties nothing'); }); +test('a pull put back while the trash is being emptied is either kept whole or refused', async (t) => { + const { store, library, folders, save } = setup(t); + const kept = await save(capture(10)); + const section: Target = { ...target, section: '40.2', scope: 'section' }; + const late = await save(capture(9, section), {}, section); + store.deletePull(kept); + store.deletePull(late); + + // Put back before the trash is emptied: it is not in the trash any more, and keeps its files. + store.putBack(kept); + // Put back while the folders are still being deleted: the trash was already emptied. + const emptying = library.emptyTrash(); + assert.throws(() => store.putBack(late), /deleted when the trash was emptied/); + assert.equal(await emptying, 1); + assert.deepEqual(folders(), [kept]); + assert.equal(store.cache(target)!.id, kept); + for (const kind of ['pdf', 'docx', 'tree_json', 'verify_report']) + assert.ok(existsSync(library.file(kept, kind)), kind); +}); + test('deleting every document goes on past a folder another program holds', async (t) => { const { library, folders, save } = setup(t); const held = await save(capture(12));