diff --git a/CLAUDE.md b/CLAUDE.md index 65f4cb6..4a42ac8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,12 +119,15 @@ original plan and any signed-in notes stay out of the repository (see `.gitignor API key and the spending limit render only under **Show advanced settings** (`src/ui/advanced.ts`). A new setting goes in the advanced part with a default that needs no thought, and is never removed to hide it. Stored preferences hold every value, so a changed default needs a migration to reach an - existing install (`0010_chosen_for_the_user.sql` is the pattern). Do not speed up the pacing + existing install (`0011_chosen_for_the_user.sql` is the pattern). Do not speed up the pacing defaults to make the app "more powerful": rule 10. - **An Electron test script that throws while loading would hang on a dialog.** Always run them through `test/run-electron.cjs`. - **The synthetic site is the only site the tests touch.** Nothing in CI reaches the network. - Database changes are new numbered files in `src/db/migrations`. Never edit an applied migration. + Each number is used once: a data folder records only the highest number applied. When two branches + each add the next number, the one merged second renumbers its files first. `Store` refuses a shared + number before it opens the database (`migrationScripts`), so every test fails on one. - **The app opens the data folder the version before it wrote.** Same folder, same `app.db`. When what a column holds changes form, the old rows need a migration and the reader needs a shape check (`readRun` in `src/db/store.ts`). `test/upgrade.test.ts` opens a database built from real 0.1.3 rows diff --git a/docs/adr/0011-chosen-for-the-user.md b/docs/adr/0011-chosen-for-the-user.md index 72ef6c6..b73cd88 100644 --- a/docs/adr/0011-chosen-for-the-user.md +++ b/docs/adr/0011-chosen-for-the-user.md @@ -80,7 +80,7 @@ loads one look may make (4), the three-tool-errors stop, and the library and pul ### An install that already exists Preferences are stored whole, so new defaults alone would never reach an existing install. Migration -0010 moves it once: both models to automatic (the app cannot tell a model it picked from one the +0011 moves it once: both models to automatic (the app cannot tell a model it picked from one the user picked, so a pick by hand is reset too, and the README says so); a step limit or plan size that still equals the earlier default is taken out, so the new default applies, while a value changed by hand stays; and a stored `visualFallback: false` is taken out, because off was the @@ -100,7 +100,7 @@ that screenshots of code text go to Anthropic while it is on. - **`Settings.spendLimitUsd`**: whole US dollars for one calendar month, 0 to 100,000, $200 by default, 0 for no limit. It is the one value on the short Settings page. - **What it counts.** The estimated cost of every reply recorded in the calendar month (UTC), from - `claude_months` (`Store.monthSpend`; migration 0011): the same figure the top bar shows. A run + `claude_months` (`Store.monthSpend`; migration 0012): the same figure the top bar shows. A run saves its usage after every reply, and `runs.save` adds what the save added to the month it is recorded in. Counting a run by the month it began, as the top bar did until now, would have let a run paused in one month and continued in the next go on uncounted. Runs recorded before the table diff --git a/docs/architecture.md b/docs/architecture.md index 9ff4a0f..9eac262 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -272,7 +272,7 @@ Settings shows the API key, the model in use, the spending limit and About. The while the advanced part is shown (`src/ui/advanced.ts`; `localStorage`), and saving a refused value in the hidden part shows it. An empty model setting is automatic (`resolveModel`, with `assets/models.default.json`); effort per kind of work is in the same file and fitted to the model -(`effortFor`). Migration 0010 moves an existing install to the new defaults once. +(`effortFor`). Migration 0011 moves an existing install to the new defaults once. ## Claude's context diff --git a/src/db/migrations/0010_chosen_for_the_user.sql b/src/db/migrations/0011_chosen_for_the_user.sql similarity index 100% rename from src/db/migrations/0010_chosen_for_the_user.sql rename to src/db/migrations/0011_chosen_for_the_user.sql diff --git a/src/db/migrations/0011_claude_months.sql b/src/db/migrations/0012_claude_months.sql similarity index 100% rename from src/db/migrations/0011_claude_months.sql rename to src/db/migrations/0012_claude_months.sql diff --git a/src/db/store.ts b/src/db/store.ts index 3919400..208c5b1 100644 --- a/src/db/store.ts +++ b/src/db/store.ts @@ -127,6 +127,28 @@ function readPullReview(r: Row, id: string): PullReview { ), }; } +/** + * The database steps in `folder`, in the order they run. Each needs its own number: a data folder + * records only the highest number applied, so a start could not tell which of two steps sharing a + * number had run. Two branches that each add the next step must not both be merged as they are; + * the one merged second takes the next free number. Refused before the database is opened. + */ +export function migrationScripts(folder: string): string[] { + const scripts = readdirSync(folder) + .filter((f) => /^\d+_.+\.sql$/.test(f)) + .sort(); + const seen = new Map(); + for (const script of scripts) { + const version = parseInt(script); + const other = seen.get(version); + if (other) + throw Error( + `Two database steps share the number ${version}: ${other} and ${script}. Give the one added later the next free number.`, + ); + seen.set(version, script); + } + return scripts; +} /** A job the queue still owes: waiting, running, or stopped for the user. One per dedup key. */ const OPEN_JOB = "('queued','searching','extracting','checking','blocked')"; /** Settings keys that hold the facts a plan run gathered from the user's notes, one per run. */ @@ -138,15 +160,14 @@ export class Store { readonly file: string, migrations: string, ) { + const all = migrationScripts(migrations); this.db = new DatabaseSync(file); this.db.exec('PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;'); const initialized = !!this.one("SELECT name FROM sqlite_master WHERE name='schema_migrations'"); const current = initialized ? Number(this.one('SELECT MAX(version) v FROM schema_migrations')?.v ?? 0) : 0; - const scripts = readdirSync(migrations) - .filter((f) => /^\d+_.+\.sql$/.test(f) && parseInt(f) > current) - .sort(); + const scripts = all.filter((f) => parseInt(f) > current); if (current && scripts.length && file !== ':memory:' && existsSync(file)) { this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); copyFileSync(file, file + '.bak-' + current); diff --git a/test/claude-cost.test.ts b/test/claude-cost.test.ts index ef93ce2..6e141b3 100644 --- a/test/claude-cost.test.ts +++ b/test/claude-cost.test.ts @@ -384,7 +384,7 @@ test('runs recorded before each reply was dated count in the month they began', const before = path.join(w.dir, 'before'); mkdirSync(before); for (const script of readdirSync(path.resolve('src/db/migrations'))) - if (parseInt(script) < 11) + if (parseInt(script) < 12) cpSync(path.join(path.resolve('src/db/migrations'), script), path.join(before, script)); const old = w.open(before); const insert = (id: string, at: string, cost: number) => diff --git a/test/store.test.ts b/test/store.test.ts index 974c5b9..52f2edd 100644 --- a/test/store.test.ts +++ b/test/store.test.ts @@ -13,7 +13,14 @@ import { } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { RUN_FACTS_PREFIX, Store, exactKey, now, type StoredResult } from '../src/db/store'; +import { + RUN_FACTS_PREFIX, + Store, + exactKey, + migrationScripts, + now, + type StoredResult, +} from '../src/db/store'; import { type SectionTree } from '../src/document/tree'; import type { Plan, Target } from '../src/shared/bridge'; import { @@ -56,6 +63,44 @@ function workspace(t: TestContext) { }, }; } +test('every database step has its own number, and two sharing one are refused before the data folder is touched', (t) => { + const all = path.resolve('src/db/migrations'); + const numbers = migrationScripts(all).map((script) => parseInt(script)); + assert.equal(new Set(numbers).size, numbers.length, 'no two steps share a number'); + + const dir = mkdtempSync(path.join(os.tmpdir(), 'codepull-steps-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const shared = path.join(dir, 'shared'); + mkdirSync(shared); + for (const script of readdirSync(all)) cpSync(path.join(all, script), path.join(shared, script)); + const last = Math.max(...numbers); + writeFileSync( + path.join(shared, `${String(last).padStart(4, '0')}_from_another_branch.sql`), + 'SELECT 1;', + ); + const file = path.join(dir, 'app.db'); + assert.throws(() => new Store(file, shared), /share the number/); + assert.ok(!existsSync(file), 'the data folder is not opened, so no database and no backup'); +}); +test('a data folder from before the trash, the chosen settings and the month’s spending takes all three', (t) => { + const dir = mkdtempSync(path.join(os.tmpdir(), 'codepull-upgrade-')); + const file = path.join(dir, 'app.db'); + const all = path.resolve('src/db/migrations'); + const before = path.join(dir, 'before'); + mkdirSync(before); + for (const script of readdirSync(all)) + if (parseInt(script) < 10) cpSync(path.join(all, script), path.join(before, script)); + new Store(file, before).db.close(); + const db = new Store(file, all); + t.after(() => { + db.db.close(); + rmSync(dir, { recursive: true, force: true }); + }); + assert.equal(db.one('SELECT MAX(version) v FROM schema_migrations')?.v, 12); + assert.ok(db.all('PRAGMA table_info(pulls)').some((c) => c.name === 'removed_at')); + assert.ok(db.one("SELECT name FROM sqlite_master WHERE name='claude_months'")); + assert.equal(db.settings().visualFallback, true); +}); test('the model list is whatever the key offers, and no model is written as the user’s pick', (t) => { const setup = workspace(t); const offered = ['model-b', 'model-a', 'model-c'].map((id) => ({ @@ -88,7 +133,7 @@ test('an install that already exists moves to the values CodePull now chooses, o const before = path.join(dir, 'before'); mkdirSync(before); for (const script of readdirSync(all)) - if (parseInt(script) < 10) cpSync(path.join(all, script), path.join(before, script)); + if (parseInt(script) < 11) cpSync(path.join(all, script), path.join(before, script)); const opened: Store[] = []; const open = (migrations: string) => { const store = new Store(file, migrations); @@ -158,7 +203,7 @@ test('step limits the user changed by hand survive the move to the new defaults' const before = path.join(dir, 'before'); mkdirSync(before); for (const script of readdirSync(all)) - if (parseInt(script) < 10) cpSync(path.join(all, script), path.join(before, script)); + if (parseInt(script) < 11) cpSync(path.join(all, script), path.join(before, script)); const old = new Store(file, before); old.set('preferences', { visualFallback: true,