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
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ 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
`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.
Expand Down
26 changes: 22 additions & 4 deletions docs/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions src/db/migrations/0010_trash.sql
Original file line number Diff line number Diff line change
@@ -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;
89 changes: 75 additions & 14 deletions src/db/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
);
Expand All @@ -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.');
Expand Down
53 changes: 36 additions & 17 deletions src/main/library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,28 +429,47 @@ 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<string>();
for (const r of rows) folders.add(path.dirname(path.join(this.root, String(r.path))));
/**
* 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 { 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<string>();
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(() => {});
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;
return emptied;
}
detail(id: string): PullDetail {
const r = this.store.pullRow(id),
Expand Down
19 changes: 18 additions & 1 deletion src/main/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,7 @@ export class Workspace implements Omit<Bridge, 'subscribe'> {
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,
Expand Down Expand Up @@ -1567,7 +1568,23 @@ export class Workspace implements Omit<Bridge, 'subscribe'> {
action: Parameters<Bridge['library']>[0],
pullId: string,
): Promise<LibraryOutcome | void> {
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();
Expand Down
21 changes: 18 additions & 3 deletions src/shared/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -478,11 +490,14 @@ export interface Bridge {
importSample(): Promise<string>;
pull(id: string): Promise<PullDetail>;
/**
* `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<LibraryOutcome | void>;
exportPull(id: string, format: 'pdf' | 'docx'): Promise<boolean>;
Expand Down
9 changes: 7 additions & 2 deletions src/ui/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]) {
Expand Down
Loading
Loading