@hasna/projects
Version:
High-level project management CLI, MCP server, SDK, and AI SDK agent loop for coding agents
250 lines • 14.6 kB
TypeScript
/**
* Decides whether an existing sqlite file at a project's canonical store path
* may be adopted as the Projects app store, or must be refused.
*
* Why this exists: lane databases (for example a working ledger at
* ~/.hasna/projects/data/<wks_id>/project.db) can land on the same canonical
* path the app uses. `runProjectStoreMigrations` starts with
* `CREATE TABLE IF NOT EXISTS project_store_migrations`, so opening such a file
* would write the app's tables into somebody else's database and only then run
* the owner check, which finds no owner row and binds silently. The file is then
* a mixed store, and the damage is already written.
*
* The rule here is deliberately not a list of known foreign ledger names: a
* foreign store whose ledger we did not think of is the same hazard. A file is
* adoptable only when it is empty, or when it already carries this app's own
* migration ledger and nothing else this app did not create. The ledger alone is
* not proof of ownership — the name is one string a foreign writer can produce,
* by choosing it or by copying a store — so a file carrying the ledger beside
* its own tables is refused like any other foreign file.
*
* Object names are not enough on their own either, and that was the second half
* of the same mistake. A file whose ONLY table is called
* `project_store_migrations` satisfied the name test and was adopted: the app
* rewrote its header to WAL and created its tables in somebody else's database.
* So ownership is decided on two things, both read through the connection the
* caller is about to write through: the objects present, and the ledger's own
* shape and applied ids (`ledgerShapeProblem` below).
*
* This module imports only built-ins — `bun:sqlite`, `node:fs`, `node:os`,
* `node:path` — so
* its logic is unit-testable without the application's dependencies installed.
*/
import { Database } from "bun:sqlite";
/** The migration ledger this application owns. Declared once, here. */
export declare const PROJECTS_MIGRATION_LEDGER: "project_store_migrations";
/**
* The tables a per-project store this app created holds.
*
* Declared here, beside the verdict that has to recognise them, so the guard and
* the migrations cannot drift about what "ours" means; `db/project-store.ts`
* imports this list and re-exports it unchanged, and `runProjectStoreMigrations`
* creates exactly these tables.
*/
export declare const PROJECT_STORE_TABLES: readonly ["project_meta", "project_store_migrations", "project_data_models", "project_data_records", "project_loop_links"];
/** The pre-schema-v3 table a store being migrated still carries. */
export declare const LEGACY_PROJECT_CANVAS_TABLE: "project_canvases";
export type StoreVerdict = "new" | "ours" | "foreign";
/**
* Classify a store from the names present in it.
*
* - `ours` — the app's ledger is present and every other object is one this
* app creates, so this is an existing app store
* - `new` — no user objects at all, so the file is empty or freshly created
* - `foreign` — anything else: objects with no ledger, or the ledger beside
* objects this app has never created
*
* The second half of `foreign` is the one that needed saying. The ledger's name
* is a single string, and a writer that is not this app can produce it — by
* choosing that name, or by copying a store that has it. Testing for the name
* alone therefore adopted a file carrying `project_store_migrations` beside its
* own `schema_migration` and `payments` tables, which is exactly the mixed store
* this guard exists to prevent. Ownership means the ledger and nothing else.
*/
export declare function classifyStoreTables(tableNames: readonly string[]): StoreVerdict;
/**
* User objects in an open database, sorted for a stable error message.
*
* Views count as objects: a file holding only a view is somebody's database, not
* an empty file, and adopting it would write our tables into it.
*
* Triggers are NOT covered here, because their table already puts the file in the
* `ours` branch and a trigger on one of our tables changes what writing to it does
* — a trigger `AFTER INSERT ON project_meta` can rewrite the owner row the moment
* the first write lands. They are listed separately by `storeTriggerNames`, and
* any one of them refuses the file.
*/
export declare function storeTableNames(db: Database): string[];
/**
* Every trigger in the file, sorted for a stable error message.
*
* This app creates no triggers at all, so the expected set is empty and any row
* here means the file was written by something else, or by this app and then
* altered. A trigger is worth its own check rather than a mention in the verdict
* because it is invisible in a table list: a file our tables and our ledger are
* both present in can still carry a trigger that rewrites `project_meta` after
* every insert, and the store is then adopted and written with the planted
* behaviour attached.
*
* Indexes are the same class of object and are NOT checked here yet: this app
* creates two explicit indexes (`idx_project_data_records_model`,
* `idx_project_loop_links_role`) and SQLite creates `sqlite_autoindex_*` for every
* UNIQUE and non-integer PRIMARY KEY declaration, so an index allowlist has to be
* kept in step with the migrations' DDL. That list lives in `project-store.ts`'s
* SQL today and does not exist as data, so a copy here could drift. Refusing a
* planted index therefore waits for a single shared list; it is recorded as a
* known limitation rather than closed by a second hand-kept list.
*/
export declare function storeTriggerNames(db: Database): string[];
/**
* Every view in the file, sorted for a stable error message.
*
* This app creates no views, so the expected set is empty and any row here means
* the file was written by something else, or by this app and then altered.
*
* A view needs its own check for the same reason a trigger does, and it is the
* sharper of the two: `storeTableNames` counts a view as an object, so a view
* wearing one of our table names satisfies `classifyStoreTables` and the file is
* adopted as `ours`. Whether the adoption then breaks depends on the ledger, and
* on an empty ledger — or one holding id 1 alone, where nothing has yet created
* the tables — it used to succeed: the view took the name, migration 2's
* `CREATE TABLE IF NOT EXISTS` silently left the view in place, and the store was
* written and then broken from the first later open. On a ledger at id 2 or above
* the migration-2 table read already refused it, but that read runs only there, so
* it was never the guard for these files.
*/
export declare function storeViewNames(db: Database): string[];
/**
* `sqlite_master` rows whose `type` is not one of the four values SQLite writes.
*
* SQLite always writes these four words in lower case, but when it loads a file
* it validates the stored type against the object's own CREATE text
* case-INSENSITIVELY. A row saying `'TRIGGER'`, `'Trigger'`, `'TABLE'` or `'Table'`
* therefore loads, behaves exactly like the object it names, and passes
* `integrity_check`. Any sqlite3 build can write such a row with
* `PRAGMA writable_schema=ON`; bun's own refuses the write but reads the result.
*
* That matters because every other filter in this module compares `type` with `=`
* or `IN`, and SQLite compares those with BINARY collation, so each of them misses
* every case variant. What one such row reopens:
*
* - a trigger on `project_meta` typed `'TRIGGER'` reopens the trigger bypass — the
* file classifies as `ours`, is adopted, and the trigger rewrites the owner row
* during the adoption's own write;
* - a ledger holding ids 2 and 3 typed `'Table'` reopens the R2 bypass — its tables
* read as absent, the file is classed `new`, its header is rewritten and every
* later open throws `no such table: project_meta`;
* - a foreign `payments` table typed `'TABLE'` reopens the original defect — the
* app creates its five tables inside somebody else's database.
*
* The allowlist is the four words in the spelling SQLite writes, so nothing here is
* copied from the migrations and nothing can drift from them. Variants that
* disagree with the CREATE text, carry a trailing space or name a different object
* are refused by SQLite itself as a malformed schema, so letter case is the only
* bypass this has to close.
*/
export declare function storeForeignTypeRows(db: Database): Array<{
type: string;
name: string;
}>;
/**
* True when the sqlite header declares WAL format: bytes 18 and 19 both 2.
*
* Read from the file directly rather than from a connection, because opening a
* connection is the operation whose mode this decides. An unreadable header
* answers false, which selects the ordinary probe and lets its own error speak.
*/
export declare function declaresWalFormat(dbPath: string): boolean;
/**
* How an existing store has to be opened for a read-only inspection.
*
* `plain` is an ordinary read-only connection to the file itself.
*
* `snapshot` is for one state: a WAL-mode header with no `-wal` beside it. Such a
* file is a complete, consistent database — an absent WAL holds nothing — and
* every standard `sqlite3` build leaves exactly that state, because it deletes the
* `-wal` on its last close. So does restoring the main file alone. No read-only
* connection can open it on any platform: SQLite needs a `-shm` wal-index beside a
* WAL database and a read-only connection will not create one, so the open fails
* with SQLITE_CANTOPEN. Left alone, this app's own store would become unopenable.
*
* So the `snapshot` mode reads a copy of the main file instead, taken into a
* private temporary directory and opened read-write. A copy is used rather than
* any special open mode on the original for two reasons. The inspection must not
* write to a file it may refuse, and a read-write open of the original would at
* least create `-wal` and `-shm` beside it. And the copy is opened exactly the way
* this application opens every store it owns, so this branch relies on nothing the
* platform has not already been shown to do.
*
* That last property is the reason this mode exists in this shape. It was first
* written as a `file:…?immutable=1` URI, which worked where it was measured and
* failed on the Linux CI runner — every WAL store whose `-wal` was already gone
* threw SQLITE_CANTOPEN there, and with it every suite that opens a fixture store.
* The URI form is gone rather than patched per platform.
*
* Every other state keeps the ordinary read-only connection: a `-wal` present, a
* file that is not WAL format, and a file whose header cannot be read. That branch
* is not a convenience. A snapshot ignores `-wal` entirely, so it would see an
* older main file; on a store whose newest tables live only in the WAL frames that
* reads as "no objects yet", and the caller would adopt a file that is somebody
* else's. A header that cannot be read also answers `plain`, so the ordinary
* connection is used and its own error speaks.
*/
export declare function readOnlyMode(dbPath: string): "plain" | "snapshot";
/**
* Open an existing store for a read-only inspection, in the mode `readOnlyMode`
* decides.
*
* Every read-only inspection of a store this code did not create in the same
* call — the ownership probe, `inspect` and the legacy-canvas seams — needs the
* same two properties, so they share one opener rather than each repeating a
* bare `readonly: true`. The busy timeout matches the read-write path, where a
* legitimate concurrent writer is a wait rather than a refusal.
*/
export declare function openExistingStoreReadOnly(dbPath: string): Database;
/**
* Why this file's ledger is not this app's, or null when it is.
*
* `classifyStoreTables` decides on object names alone, and a name is one string
* any writer can produce — by choosing it, or by copying a store. The result was
* that a foreign file whose ONLY table was called `project_store_migrations` was
* classified `ours`: the app rewrote its header to WAL and created its tables in
* somebody else's database.
*
* The ledger this app writes has a shape and a small closed set of applied ids,
* so both are read here, through the same connection the caller is about to write
* through. The limit is stated rather than papered over: a writer that produces
* exactly this shape and exactly these ids is indistinguishable from this app by
* anything observable in the file. This narrows the class adopted by accident,
* which is the class that occurs; it is not an ownership proof.
*
* An EMPTY ledger of the right shape is adopted, deliberately. The migrations are
* three separate `db.exec` calls with no transaction around them
* (`runProjectStoreMigrations`, project-store.ts:511-576), so a failure between
* the ledger's CREATE and the first `INSERT ... VALUES (2)` leaves exactly this
* file — a store this app produced itself, a crash away from any foreign writer.
* Refusing it would lock the app out of its own store, which is the worse failure
* this module declines elsewhere too. Adopting it costs nothing: an empty ledger
* holds no rows, so there is no foreign content to mix with ours, and the
* migrations then run and fill it. The mixed store this guard exists to prevent
* needs somebody else's rows or tables, and that is still refused.
*/
export declare function ledgerShapeProblem(db: Database): string | null;
/**
* Throw unless the open store `db` may be adopted as the app store at `dbPath`.
*
* Takes the connection rather than a list of names, because the names are not the
* evidence: the ledger's shape and ids have to be read from the file itself, and
* read through the very connection that is about to write to it.
*
* The two callers are the read-only probe and the re-check on the read-write
* connection. Both are needed. The probe decides before anything opens the file
* for writing; the re-check exists because the path can be replaced between the
* two opens, so the file that was approved must be the file that is written.
*
* Must be called before anything writes to the file — in particular before
* `PRAGMA journal_mode=WAL`, which mutates the file header, and before any
* migration creates a table.
*/
export declare function assertStoreAdoptable(db: Database, dbPath: string): void;
//# sourceMappingURL=store-adoption.d.ts.map