or3-provider-sqlite 0.0.25 → 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -405,5 +405,23 @@ history delivery prevent replacement. Database failures propagate so the host
405
405
  cancels preparation and restores admission rather than treating failure as idle.
406
406
  An additive covering index migration keeps counts off stored response bodies.
407
407
 
408
+ A host that tracks in-flight workers and reconciliation can opt into
409
+ `getShutdownBlockerCount({ allowPersistedDelegation: true })`. Native SQLite then
410
+ allows saved delegation waits and terminal delegation delivery to remain pending
411
+ across restart when there is no live or indeterminate worker lease. Active model
412
+ jobs still block. This read-only count changes no retention, authorization,
413
+ recovery or replay rules: inaccessible or damaged evidence stays preserved.
414
+ D1 and callers that omit the option retain the conservative count. This support
415
+ ships in 0.0.26 and requires a matching host update.
416
+
408
417
  Admin workspace summaries, workspace details, and deployment-admin lists expose `createdAt` in Unix milliseconds for the host UI. SQLite continues to store the underlying creation timestamps in Unix seconds; no data migration is needed.
418
+
419
+ ## Dormant immutable-generation foundation (unreleased)
420
+
421
+ Migration 030 adds inert generation records, current-hash heads, and canonical write barriers after the released migrations. No runtime route creates these records, no adapter advertises `externalStorageGenerations`, and physical cleanup remains disabled. See [protocol invariants and activation blockers](docs/storage-generations.md).
422
+
423
+ Migrations 030–031 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
424
+
425
+ Migration 031 adds the dormant upload ledger and restore tickets. The optional coordinator remains unregistered. See [upload, restore, and recovery invariants](docs/storage-generation-uploads.md).
426
+
409
427
  Background history admission and finalization failures expose structured codes for validation, authorization, conflicts, and supersession. Transient SQLite failures retain their original errors for retry.
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
3
  "configKey": "or3-provider-sqlite",
4
- "version": "0.0.25",
4
+ "version": "0.0.26",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -58,6 +58,8 @@ export declare class SqliteBackgroundJobProvider implements BackgroundJobProvide
58
58
  getPendingHistoryJobs(limit: number): Promise<BackgroundJob[]>;
59
59
  cleanupExpired(): Promise<number>;
60
60
  getActiveJobCount(): Promise<number>;
61
- getShutdownBlockerCount(): Promise<number>;
61
+ getShutdownBlockerCount(options?: {
62
+ allowPersistedDelegation?: boolean;
63
+ }): Promise<number>;
62
64
  }
63
65
  export declare const sqliteBackgroundJobProvider: SqliteBackgroundJobProvider;
@@ -1425,7 +1425,24 @@ export class SqliteBackgroundJobProvider {
1425
1425
  );
1426
1426
  return row?.total ?? 0;
1427
1427
  }
1428
- async getShutdownBlockerCount() {
1428
+ async getShutdownBlockerCount(options) {
1429
+ if (options?.allowPersistedDelegation && !isD1Driver()) {
1430
+ const row2 = await one(
1431
+ `SELECT COUNT(*) AS total FROM background_jobs
1432
+ WHERE (status = 'streaming' OR history_phase IN ('admission_pending', 'finalization_pending')
1433
+ OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL)
1434
+ AND NOT (
1435
+ COALESCE(kind, 'chat') = 'chat'
1436
+ AND ((lease_owner IS NULL AND lease_expires_at IS NULL)
1437
+ OR (lease_owner IS NOT NULL AND typeof(lease_expires_at) = 'integer' AND lease_expires_at <= ?))
1438
+ AND (delegation_wait_active = 1
1439
+ OR (status != 'streaming' AND json_extract(execution_json, '$.delegationRecoveryPolicy') IS 'v1'))
1440
+ )`,
1441
+ Date.now()
1442
+ );
1443
+ if (!row2) throw new Error("SQLite shutdown accounting unavailable");
1444
+ return row2.total;
1445
+ }
1429
1446
  const row = await one(
1430
1447
  `SELECT
1431
1448
  (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming') +
@@ -22,6 +22,7 @@ type SqliteTransaction<T> = ((...args: unknown[]) => T) & {
22
22
  immediate: (...args: unknown[]) => T;
23
23
  };
24
24
  export interface SqliteRawDatabase {
25
+ readonly inTransaction?: boolean;
25
26
  close(): void;
26
27
  prepare(sql: string): SqliteRawStatement;
27
28
  pragma?(source: string): unknown;
@@ -105,6 +105,9 @@ class BunDatabaseAdapter {
105
105
  constructor(database) {
106
106
  this.database = database;
107
107
  }
108
+ get inTransaction() {
109
+ return this.database.inTransaction;
110
+ }
108
111
  close() {
109
112
  this.database.close();
110
113
  }
@@ -53,7 +53,10 @@ const REQUIRED_SCHEMA_TABLES = [
53
53
  "background_jobs",
54
54
  "background_job_execution_quarantine",
55
55
  "background_admission_cancels",
56
- "background_generation_receipts"
56
+ "background_generation_receipts",
57
+ "storage_object_generations",
58
+ "storage_object_heads",
59
+ "storage_generation_uploads"
57
60
  ];
58
61
  import * as m024 from "./migrations/024_signup_invites.js";
59
62
  import * as m025 from "./migrations/025_background_shutdown_accounting.js";
@@ -61,6 +64,8 @@ import * as m026 from "./migrations/026_retained_storage_usage.js";
61
64
  import * as m027 from "./migrations/027_verified_storage_usage.js";
62
65
  import * as m028 from "./migrations/028_user_scoped_device_cursors.js";
63
66
  import * as m029 from "./migrations/029_delegation_wait.js";
67
+ import * as m030 from "./migrations/030_storage_generations.js";
68
+ import * as m031 from "./migrations/031_storage_generation_uploads.js";
64
69
  const migrations = {
65
70
  "001_init": m001,
66
71
  "002_sync_tables": m002,
@@ -90,7 +95,9 @@ const migrations = {
90
95
  "026_retained_storage_usage": m026,
91
96
  "027_verified_storage_usage": m027,
92
97
  "028_user_scoped_device_cursors": m028,
93
- "029_delegation_wait": m029
98
+ "029_delegation_wait": m029,
99
+ "030_storage_generations": m030,
100
+ "031_storage_generation_uploads": m031
94
101
  };
95
102
  class StaticMigrationProvider {
96
103
  async getMigrations() {
@@ -0,0 +1,3 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Resume nontransactional SQLite/D1 DDL without trusting an unrelated schema. */
3
+ export declare function ensureMigrationSchema(db: Kysely<unknown>, statement: string, previousTrigger?: string): Promise<void>;
@@ -0,0 +1,21 @@
1
+ import { sql } from "kysely";
2
+ export async function ensureMigrationSchema(db, statement, previousTrigger) {
3
+ const match = /^CREATE (?:UNIQUE )?(TABLE|INDEX|TRIGGER) (\w+)/.exec(statement);
4
+ if (!match) throw new Error("Unsupported migration schema statement");
5
+ const [, kind, name] = match;
6
+ const existing = (await sql`
7
+ SELECT type, sql FROM sqlite_master WHERE name = ${name}
8
+ `.execute(db)).rows;
9
+ if (existing.length) {
10
+ const current = existing[0];
11
+ if (existing.length !== 1 || !current || current.type !== kind?.toLowerCase()) {
12
+ throw new Error(`Incompatible migration schema: ${name}`);
13
+ }
14
+ if (current.sql?.trim() === statement.trim()) return;
15
+ if (kind !== "TRIGGER" || !previousTrigger || current.sql?.trim() !== previousTrigger.trim()) {
16
+ throw new Error(`Incompatible migration schema: ${name}`);
17
+ }
18
+ await sql.raw(`DROP TRIGGER ${name}`).execute(db);
19
+ }
20
+ await sql.raw(statement).execute(db);
21
+ }
@@ -0,0 +1,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Dormant foundation: no runtime creates managed rows or advertises this protocol. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { sql } from "kysely";
2
+ import { ensureMigrationSchema } from "../migration-schema.js";
3
+ import { GENERATION_TABLE, HEAD_TABLE, generationGuardTriggers } from "../storage-generation-guards.js";
4
+ export async function up(db) {
5
+ await ensureMigrationSchema(db, `CREATE TABLE ${GENERATION_TABLE} (
6
+ generation_id TEXT PRIMARY KEY,
7
+ workspace_id TEXT NOT NULL,
8
+ hash TEXT NOT NULL,
9
+ storage_provider_id TEXT NOT NULL,
10
+ storage_id TEXT NOT NULL UNIQUE,
11
+ size_bytes INTEGER NOT NULL CHECK (typeof(size_bytes) = 'integer' AND size_bytes BETWEEN 0 AND 9007199254740991),
12
+ state TEXT NOT NULL CHECK (state IN ('verified', 'claimed', 'deleted')),
13
+ created_at INTEGER NOT NULL CHECK (typeof(created_at) = 'integer' AND created_at BETWEEN 0 AND 9007199254740991),
14
+ last_activity_at INTEGER NOT NULL CHECK (typeof(last_activity_at) = 'integer' AND last_activity_at BETWEEN 0 AND 9007199254740991),
15
+ claim_id TEXT UNIQUE,
16
+ claimed_at INTEGER CHECK (claimed_at IS NULL OR (typeof(claimed_at) = 'integer' AND claimed_at BETWEEN 0 AND 9007199254740991)),
17
+ deleted_at INTEGER CHECK (deleted_at IS NULL OR (typeof(deleted_at) = 'integer' AND deleted_at BETWEEN 0 AND 9007199254740991)),
18
+ UNIQUE (workspace_id, hash, generation_id),
19
+ CHECK (last_activity_at >= created_at),
20
+ CHECK ((state = 'verified' AND claim_id IS NULL AND claimed_at IS NULL AND deleted_at IS NULL)
21
+ OR (state = 'claimed' AND claim_id IS NOT NULL AND claimed_at IS NOT NULL AND claimed_at >= last_activity_at AND deleted_at IS NULL)
22
+ OR (state = 'deleted' AND claim_id IS NOT NULL AND claimed_at IS NOT NULL AND deleted_at IS NOT NULL
23
+ AND claimed_at >= last_activity_at AND deleted_at >= claimed_at))
24
+ )`);
25
+ await ensureMigrationSchema(db, `CREATE TABLE ${HEAD_TABLE} (
26
+ workspace_id TEXT NOT NULL,
27
+ hash TEXT NOT NULL,
28
+ generation_id TEXT NOT NULL UNIQUE,
29
+ PRIMARY KEY (workspace_id, hash),
30
+ FOREIGN KEY (workspace_id, hash, generation_id)
31
+ REFERENCES ${GENERATION_TABLE}(workspace_id, hash, generation_id) ON DELETE RESTRICT
32
+ )`);
33
+ await ensureMigrationSchema(db, `CREATE INDEX storage_generations_workspace_hash ON ${GENERATION_TABLE}(workspace_id, hash)`);
34
+ for (const trigger of Object.values(generationGuardTriggers())) await ensureMigrationSchema(db, trigger);
35
+ }
36
+ export async function down(db) {
37
+ const result = await sql`SELECT count(*) AS count FROM storage_object_generations`.execute(db);
38
+ if (result.rows[0]?.count) throw new Error("Managed generation barriers are permanent; cannot roll back this schema.");
39
+ for (const name of Object.keys(generationGuardTriggers())) await sql.raw(`DROP TRIGGER IF EXISTS ${name}`).execute(db);
40
+ await sql.raw(`DROP TABLE ${HEAD_TABLE}`).execute(db);
41
+ await sql.raw(`DROP TABLE ${GENERATION_TABLE}`).execute(db);
42
+ }
@@ -0,0 +1,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Dormant: no production route or factory registers upload enrollment. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { sql } from "kysely";
2
+ import { ensureMigrationSchema } from "../migration-schema.js";
3
+ import { generationGuardTriggers } from "../storage-generation-guards.js";
4
+ import { GENERATION_UPLOAD_TABLE, generationUploadGuardTriggers } from "../storage-generation-upload-guards.js";
5
+ export async function up(db) {
6
+ await ensureMigrationSchema(db, `CREATE TABLE ${GENERATION_UPLOAD_TABLE} (
7
+ intent_id TEXT PRIMARY KEY,
8
+ workspace_id TEXT NOT NULL, hash TEXT NOT NULL,
9
+ generation_id TEXT NOT NULL, storage_id TEXT NOT NULL,
10
+ purpose TEXT NOT NULL DEFAULT 'upload' CHECK (purpose IN ('upload','restore')),
11
+ storage_provider_id TEXT NOT NULL, namespace_id TEXT NOT NULL, user_id TEXT NOT NULL,
12
+ mime_type TEXT NOT NULL,
13
+ size_bytes INTEGER NOT NULL CHECK (typeof(size_bytes) = 'integer' AND size_bytes BETWEEN 0 AND 9007199254740991),
14
+ reserved_bytes INTEGER NOT NULL CHECK (typeof(reserved_bytes) = 'integer' AND reserved_bytes >= 0),
15
+ created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,
16
+ request_ttl INTEGER NOT NULL, quota_bytes INTEGER,
17
+ state TEXT NOT NULL CHECK (state IN ('reserved','ready','published_pending_metadata','materialized','abandon_claimed','abandoned')),
18
+ ready_receipt_id TEXT, ready_at INTEGER,
19
+ published_generation_id TEXT, published_at INTEGER, materialized_at INTEGER,
20
+ claim_id TEXT UNIQUE, claimed_at INTEGER, deleted_at INTEGER,
21
+ CHECK (typeof(created_at) = 'integer' AND created_at >= 0 AND typeof(expires_at) = 'integer' AND expires_at > created_at),
22
+ CHECK ((state IN ('reserved','ready','published_pending_metadata') AND reserved_bytes = size_bytes)
23
+ OR (state IN ('materialized','abandon_claimed','abandoned') AND reserved_bytes = 0)),
24
+ CHECK ((state = 'reserved' AND ready_receipt_id IS NULL AND ready_at IS NULL)
25
+ OR (state <> 'reserved' AND ready_receipt_id IS NOT NULL AND ready_at IS NOT NULL AND ready_at >= created_at)),
26
+ CHECK ((published_generation_id IS NULL AND published_at IS NULL)
27
+ OR (published_generation_id = generation_id AND published_at IS NOT NULL AND published_at >= ready_at)),
28
+ CHECK (state NOT IN ('published_pending_metadata','materialized') OR published_generation_id IS NOT NULL),
29
+ CHECK (purpose = 'upload' OR (published_generation_id IS NOT NULL AND state NOT IN ('reserved','ready'))),
30
+ CHECK ((state = 'materialized' AND materialized_at IS NOT NULL AND materialized_at >= published_at)
31
+ OR (state <> 'materialized' AND materialized_at IS NULL)),
32
+ CHECK ((state IN ('abandon_claimed','abandoned') AND claim_id IS NOT NULL AND claimed_at IS NOT NULL AND claimed_at >= expires_at AND claimed_at >= ready_at)
33
+ OR (state NOT IN ('abandon_claimed','abandoned') AND claim_id IS NULL AND claimed_at IS NULL)),
34
+ CHECK ((state = 'abandoned' AND deleted_at IS NOT NULL AND deleted_at >= claimed_at)
35
+ OR (state <> 'abandoned' AND deleted_at IS NULL)),
36
+ FOREIGN KEY (intent_id) REFERENCES upload_intents(id) DEFERRABLE INITIALLY DEFERRED,
37
+ FOREIGN KEY (published_generation_id) REFERENCES storage_object_generations(generation_id) DEFERRABLE INITIALLY DEFERRED
38
+ )`);
39
+ await ensureMigrationSchema(db, `CREATE UNIQUE INDEX storage_upload_generation_identity ON ${GENERATION_UPLOAD_TABLE}(generation_id) WHERE purpose = 'upload'`);
40
+ await ensureMigrationSchema(db, `CREATE UNIQUE INDEX storage_upload_target_identity ON ${GENERATION_UPLOAD_TABLE}(storage_id) WHERE purpose = 'upload'`);
41
+ await ensureMigrationSchema(db, `CREATE UNIQUE INDEX storage_upload_pending_hash ON ${GENERATION_UPLOAD_TABLE}(workspace_id, hash)
42
+ WHERE state IN ('reserved','ready','published_pending_metadata')`);
43
+ await ensureMigrationSchema(db, `CREATE INDEX storage_upload_recovery ON ${GENERATION_UPLOAD_TABLE}(workspace_id, intent_id)`);
44
+ for (const [name, trigger] of Object.entries(generationUploadGuardTriggers())) {
45
+ await ensureMigrationSchema(db, trigger, generationGuardTriggers()[name]);
46
+ }
47
+ }
48
+ export async function down(db) {
49
+ const result = await sql`SELECT count(*) AS count FROM storage_generation_uploads`.execute(db);
50
+ if (result.rows[0]?.count) throw new Error("Managed upload bindings are permanent; cannot roll back this schema.");
51
+ for (const name of Object.keys(generationUploadGuardTriggers())) await sql.raw(`DROP TRIGGER IF EXISTS ${name}`).execute(db);
52
+ await sql.raw(`DROP TABLE ${GENERATION_UPLOAD_TABLE}`).execute(db);
53
+ for (const [name, trigger] of Object.entries(generationGuardTriggers())) {
54
+ if (name in generationUploadGuardTriggers()) await sql.raw(trigger).execute(db);
55
+ }
56
+ }
@@ -0,0 +1,17 @@
1
+ /** Dormant managed-generation barriers. All identifiers below are internal constants. */
2
+ export declare const GENERATION_TABLE = "storage_object_generations";
3
+ export declare const HEAD_TABLE = "storage_object_heads";
4
+ export declare const MAX_GENERATION_PAYLOAD_BYTES: number;
5
+ export declare const MAX_GENERATION_ROW_EDGES = 1000;
6
+ export declare const GENERATION_PROOF_ROWS = 1000;
7
+ export declare const GENERATION_PROOF_EDGES = 10000;
8
+ /** Do not trim: whitespace and unknown prefixes are invalid, never invisible aliases. */
9
+ export declare function generationHashSql(value: string): string;
10
+ export declare function validGenerationHashSql(value: string): string;
11
+ /** JSON path labels containing NUL can shadow exact keys in SQLite. */
12
+ export declare function validGenerationObjectSql(json: string): string;
13
+ export declare function generationReferencesSql(json: string): string;
14
+ export declare function validGenerationReferencesSql(json: string): string;
15
+ /** Exact SQL is also checked inside every coordinator mutation transaction. */
16
+ export declare function generationGuardTriggers(): Record<string, string>;
17
+ export declare function canonicalGuardSql(sql: string): string;
@@ -0,0 +1,169 @@
1
+ export const GENERATION_TABLE = "storage_object_generations";
2
+ export const HEAD_TABLE = "storage_object_heads";
3
+ export const MAX_GENERATION_PAYLOAD_BYTES = 256 * 1024;
4
+ export const MAX_GENERATION_ROW_EDGES = 1e3;
5
+ export const GENERATION_PROOF_ROWS = 1e3;
6
+ export const GENERATION_PROOF_EDGES = 1e4;
7
+ export function generationHashSql(value) {
8
+ return `(CASE WHEN lower(substr(${value}, 1, 7)) = 'sha256:' THEN lower(substr(${value}, 8))
9
+ WHEN lower(substr(${value}, 1, 4)) = 'md5:' THEN lower(substr(${value}, 5)) ELSE lower(${value}) END)`;
10
+ }
11
+ export function validGenerationHashSql(value) {
12
+ const hash = generationHashSql(value);
13
+ return `(typeof(${value}) = 'text' AND length(CAST(${value} AS BLOB)) = length(${value})
14
+ AND ${hash} NOT GLOB '*[^0-9a-f]*'
15
+ AND ((length(${value}) IN (32, 64) AND length(${hash}) = length(${value}))
16
+ OR (length(${value}) = 71 AND lower(substr(${value}, 1, 7)) = 'sha256:' AND length(${hash}) = 64)
17
+ OR (length(${value}) = 36 AND lower(substr(${value}, 1, 4)) = 'md5:' AND length(${hash}) = 32)))`;
18
+ }
19
+ export function validGenerationObjectSql(json) {
20
+ return `(CASE WHEN typeof(${json}) <> 'text' OR length(CAST(${json} AS BLOB)) > ${MAX_GENERATION_PAYLOAD_BYTES}
21
+ OR json_valid(${json}) IS NOT 1 THEN 0
22
+ WHEN json_type(${json}) <> 'object' THEN 0
23
+ WHEN EXISTS (SELECT 1 FROM json_each(${json}) WHERE instr(key, char(0)) > 0) THEN 0
24
+ WHEN EXISTS (SELECT 1 FROM json_each(${json}) GROUP BY key HAVING count(*) > 1) THEN 0
25
+ ELSE 1 END)`;
26
+ }
27
+ export function generationReferencesSql(json) {
28
+ return `(CASE WHEN json_type(${json}, '$.file_hashes') IS NULL OR json_type(${json}, '$.file_hashes') = 'null' THEN '[]'
29
+ ELSE json_extract(${json}, '$.file_hashes') END)`;
30
+ }
31
+ export function validGenerationReferencesSql(json) {
32
+ const refs = generationReferencesSql(json);
33
+ return `(CASE WHEN ${validGenerationObjectSql(json)} = 0 THEN 0
34
+ WHEN json_type(${json}, '$.fileHashes') IS NOT NULL THEN 0
35
+ WHEN json_type(${json}, '$.file_hashes') IS NULL OR json_type(${json}, '$.file_hashes') = 'null' THEN 1
36
+ WHEN json_type(${json}, '$.file_hashes') NOT IN ('text', 'array') THEN 0
37
+ WHEN json_valid(${refs}) IS NOT 1 THEN 0
38
+ WHEN json_type(${refs}) <> 'array' OR json_array_length(${refs}) > ${MAX_GENERATION_ROW_EDGES} THEN 0
39
+ WHEN EXISTS (SELECT 1 FROM json_each(${refs}) WHERE type <> 'text' OR NOT ${validGenerationHashSql("value")}) THEN 0
40
+ ELSE 1 END)`;
41
+ }
42
+ function safeReferencesSql(json) {
43
+ return `(CASE WHEN ${validGenerationReferencesSql(json)} = 1 THEN ${generationReferencesSql(json)} ELSE '[]' END)`;
44
+ }
45
+ function metadataStorageSql(json) {
46
+ return `coalesce(json_extract(${json}, '$.storage_id'), json_extract(${json}, '$.storageId'))`;
47
+ }
48
+ function sourceTouch(table, row, prior = false) {
49
+ const match = `${row}.deleted = 0 AND ${row}.workspace_id = ${GENERATION_TABLE}.workspace_id
50
+ AND (${validGenerationReferencesSql(`${row}.data_json`)} = 0
51
+ OR ${GENERATION_TABLE}.hash IN (SELECT ${generationHashSql("value")} FROM json_each(${safeReferencesSql(`${row}.data_json`)})))`;
52
+ return `UPDATE ${GENERATION_TABLE} SET last_activity_at = max(last_activity_at, unixepoch())
53
+ WHERE state = 'verified' AND generation_id IN (SELECT generation_id FROM ${HEAD_TABLE})
54
+ AND ${prior ? `EXISTS (SELECT 1 FROM ${table} prior WHERE ${table === "upload_intents" ? "" : "prior.workspace_id = NEW.workspace_id AND "}prior.id = NEW.id AND ${match})` : `(${match})`};`;
55
+ }
56
+ function keyTouch(table, row, prior = false) {
57
+ const column = table === "s_file_meta" ? "id" : "hash";
58
+ const match = `${row}.workspace_id = ${GENERATION_TABLE}.workspace_id
59
+ AND ${generationHashSql(`${row}.${column}`)} = ${GENERATION_TABLE}.hash
60
+ ${table === "upload_intents" ? `AND ${row}.status = 'active'` : ""}`;
61
+ return `UPDATE ${GENERATION_TABLE} SET last_activity_at = max(last_activity_at, unixepoch())
62
+ WHERE state = 'verified' AND generation_id IN (SELECT generation_id FROM ${HEAD_TABLE})
63
+ AND ${prior ? `EXISTS (SELECT 1 FROM ${table} prior WHERE ${table === "upload_intents" ? "" : "prior.workspace_id = NEW.workspace_id AND "}prior.id = NEW.id AND ${match})` : `(${match})`};`;
64
+ }
65
+ export function generationGuardTriggers() {
66
+ const triggers = {};
67
+ const add = (name, clause) => {
68
+ triggers[name] = `CREATE TRIGGER ${name} ${clause}`;
69
+ };
70
+ add("storage_generation_no_replace", `BEFORE INSERT ON ${GENERATION_TABLE}
71
+ WHEN EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = NEW.generation_id OR storage_id = NEW.storage_id)
72
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_IDENTITY_REUSE'); END`);
73
+ add("storage_generation_no_delete", `BEFORE DELETE ON ${GENERATION_TABLE}
74
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_PERMANENT'); END`);
75
+ add("storage_generation_immutable", `BEFORE UPDATE ON ${GENERATION_TABLE}
76
+ WHEN NEW.generation_id IS NOT OLD.generation_id OR NEW.workspace_id IS NOT OLD.workspace_id
77
+ OR NEW.hash IS NOT OLD.hash OR NEW.storage_id IS NOT OLD.storage_id
78
+ OR NEW.storage_provider_id IS NOT OLD.storage_provider_id OR NEW.size_bytes IS NOT OLD.size_bytes
79
+ OR NEW.created_at IS NOT OLD.created_at OR NEW.last_activity_at < OLD.last_activity_at
80
+ OR (OLD.state = 'verified' AND NEW.state = 'deleted')
81
+ OR (OLD.state <> 'verified' AND NEW.last_activity_at IS NOT OLD.last_activity_at)
82
+ OR (OLD.state <> 'verified' AND (NEW.claim_id IS NOT OLD.claim_id OR NEW.claimed_at IS NOT OLD.claimed_at))
83
+ OR (OLD.state = 'claimed' AND NEW.state NOT IN ('claimed', 'deleted'))
84
+ OR (OLD.state = 'deleted' AND (NEW.state <> 'deleted' OR NEW.deleted_at IS NOT OLD.deleted_at))
85
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_IMMUTABLE'); END`);
86
+ add("storage_generation_head_insert", `BEFORE INSERT ON ${HEAD_TABLE}
87
+ WHEN EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = NEW.workspace_id AND hash = NEW.hash)
88
+ OR NOT EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = NEW.generation_id
89
+ AND workspace_id = NEW.workspace_id AND hash = NEW.hash AND state = 'verified')
90
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_HEAD_CONFLICT'); END`);
91
+ add("storage_generation_head_update", `BEFORE UPDATE ON ${HEAD_TABLE}
92
+ WHEN NEW.workspace_id IS NOT OLD.workspace_id OR NEW.hash IS NOT OLD.hash
93
+ OR NOT EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = OLD.generation_id AND state IN ('claimed', 'deleted'))
94
+ OR NOT EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = NEW.generation_id
95
+ AND workspace_id = NEW.workspace_id AND hash = NEW.hash AND state = 'verified')
96
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_HEAD_CONFLICT'); END`);
97
+ add("storage_generation_head_no_delete", `BEFORE DELETE ON ${HEAD_TABLE}
98
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_HEAD_PERMANENT'); END`);
99
+ for (const table of ["s_messages", "s_posts"]) {
100
+ for (const event of ["INSERT", "UPDATE"]) {
101
+ add(`${table}_generation_guard_${event.toLowerCase()}`, `BEFORE ${event} ON ${table}
102
+ WHEN NEW.deleted = 0 AND EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = NEW.workspace_id)
103
+ BEGIN
104
+ SELECT CASE WHEN ${validGenerationReferencesSql("NEW.data_json")} = 0
105
+ THEN RAISE(ABORT, 'STORAGE_GENERATION_UNKNOWN_REFERENCES') END;
106
+ SELECT CASE WHEN EXISTS (
107
+ SELECT 1 FROM json_each(${generationReferencesSql("NEW.data_json")}) edge
108
+ JOIN ${HEAD_TABLE} head ON head.workspace_id = NEW.workspace_id AND head.hash = ${generationHashSql("edge.value")}
109
+ JOIN ${GENERATION_TABLE} generation ON generation.generation_id = head.generation_id
110
+ WHERE generation.state <> 'verified') THEN RAISE(ABORT, 'STORAGE_GENERATION_CLAIMED') END;
111
+ END`);
112
+ }
113
+ }
114
+ const knownMetadata = `EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = NEW.workspace_id
115
+ AND (hash = ${generationHashSql("NEW.id")} OR ${validGenerationHashSql("NEW.id")} IS NOT 1
116
+ OR CASE WHEN ${validGenerationObjectSql("NEW.data_json")} = 0 THEN 1
117
+ WHEN json_type(NEW.data_json, '$.hash') IS NOT NULL THEN
118
+ ${validGenerationHashSql("json_extract(NEW.data_json, '$.hash')")} IS NOT 1
119
+ OR ${generationHashSql("json_extract(NEW.data_json, '$.hash')")} IS NOT ${generationHashSql("NEW.id")}
120
+ ELSE 0 END))
121
+ OR EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(NEW.data_json) THEN NEW.data_json ELSE '{}' END) field
122
+ JOIN ${GENERATION_TABLE} generation ON generation.storage_id = field.value
123
+ WHERE field.key IN ('storage_id', 'storageId') AND field.type = 'text')`;
124
+ for (const event of ["INSERT", "UPDATE"]) {
125
+ add(`s_file_meta_generation_guard_${event.toLowerCase()}`, `BEFORE ${event} ON s_file_meta
126
+ WHEN NEW.deleted = 0 AND (${knownMetadata})
127
+ BEGIN
128
+ SELECT CASE WHEN ${validGenerationObjectSql("NEW.data_json")} = 0
129
+ THEN RAISE(ABORT, 'STORAGE_GENERATION_INVALID_METADATA') END;
130
+ SELECT CASE WHEN (json_type(NEW.data_json, '$.storage_id') IS NOT NULL AND json_type(NEW.data_json, '$.storageId') IS NOT NULL)
131
+ OR (json_type(NEW.data_json, '$.size_bytes') IS NOT NULL AND json_type(NEW.data_json, '$.sizeBytes') IS NOT NULL)
132
+ THEN RAISE(ABORT, 'STORAGE_GENERATION_AMBIGUOUS_METADATA') END;
133
+ SELECT CASE WHEN NOT EXISTS (
134
+ SELECT 1 FROM ${HEAD_TABLE} head JOIN ${GENERATION_TABLE} generation ON generation.generation_id = head.generation_id
135
+ WHERE head.workspace_id = NEW.workspace_id AND head.hash = ${generationHashSql("NEW.id")}
136
+ AND generation.state = 'verified' AND ${validGenerationHashSql("NEW.id")}
137
+ AND ${validGenerationHashSql("json_extract(NEW.data_json, '$.hash')")}
138
+ AND ${generationHashSql("json_extract(NEW.data_json, '$.hash')")} = head.hash
139
+ AND typeof(${metadataStorageSql("NEW.data_json")}) = 'text'
140
+ AND ${metadataStorageSql("NEW.data_json")} = generation.storage_id
141
+ AND typeof(coalesce(json_extract(NEW.data_json, '$.size_bytes'), json_extract(NEW.data_json, '$.sizeBytes'))) = 'integer'
142
+ AND coalesce(json_extract(NEW.data_json, '$.size_bytes'), json_extract(NEW.data_json, '$.sizeBytes')) = generation.size_bytes
143
+ ) THEN RAISE(ABORT, 'STORAGE_GENERATION_METADATA_MISMATCH') END;
144
+ END`);
145
+ add(`upload_intents_generation_guard_${event.toLowerCase()}`, `BEFORE ${event} ON upload_intents
146
+ WHEN NEW.status = 'active' AND EXISTS (SELECT 1 FROM ${HEAD_TABLE} head
147
+ JOIN ${GENERATION_TABLE} generation ON generation.generation_id = head.generation_id
148
+ WHERE head.workspace_id = NEW.workspace_id AND (${validGenerationHashSql("NEW.hash")} IS NOT 1
149
+ OR (head.hash = ${generationHashSql("NEW.hash")} AND generation.state <> 'verified')))
150
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_UPLOAD_BLOCKED'); END`);
151
+ }
152
+ add("s_file_meta_generation_identity_update", `BEFORE UPDATE ON s_file_meta
153
+ WHEN (NEW.workspace_id IS NOT OLD.workspace_id OR NEW.id IS NOT OLD.id)
154
+ AND EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = OLD.workspace_id AND hash = ${generationHashSql("OLD.id")})
155
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_METADATA_IDENTITY'); END`);
156
+ for (const table of ["s_messages", "s_posts", "s_file_meta", "upload_intents"]) {
157
+ const touch = table === "s_messages" || table === "s_posts" ? sourceTouch : keyTouch;
158
+ add(`${table}_generation_replace_activity`, `BEFORE INSERT ON ${table} BEGIN ${touch(table, "prior", true)} END`);
159
+ for (const event of ["INSERT", "UPDATE", "DELETE"]) {
160
+ const rows = event === "UPDATE" ? ["OLD", "NEW"] : event === "DELETE" ? ["OLD"] : ["NEW"];
161
+ add(`${table}_generation_activity_${event.toLowerCase()}`, `AFTER ${event} ON ${table}
162
+ BEGIN ${rows.map((row) => touch(table, row)).join("\n")} END`);
163
+ }
164
+ }
165
+ return triggers;
166
+ }
167
+ export function canonicalGuardSql(sql) {
168
+ return sql.trim().replace(/;$/, "");
169
+ }
@@ -0,0 +1,7 @@
1
+ export declare const GENERATION_UPLOAD_TABLE = "storage_generation_uploads";
2
+ /** Accounting holds have no automatic expiry. Credentials have their own deadline. */
3
+ export declare const GENERATION_UPLOAD_HOLD_EXPIRY: number;
4
+ export declare const GENERATION_UPLOAD_MAX_TTL_SECONDS = 900;
5
+ export declare const GENERATION_UPLOAD_MAX_PENDING = 128;
6
+ /** Migration 025 only: the original migration remains reproducible. */
7
+ export declare function generationUploadGuardTriggers(): Record<string, string>;