or3-provider-sqlite 0.0.26 → 0.0.28

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
@@ -13,6 +13,18 @@ Requires **Node.js 24.22.1 or newer on the 24.x line**, matching OR3 Chat. Devel
13
13
  - **Admin stores** (`sqlite`) — workspace access/lifecycle, workspace settings, user search, and deployment-admin grants (local, Bun, and Turso runtimes)
14
14
  - **RateLimitProvider** (`sqlite`) — durable rate-limit counters
15
15
 
16
+ OR3 Chat checks SQLite deployment-admin grants against the canonical user on
17
+ cached sessions. A granted account can manage settings only for a workspace it
18
+ owns; instance administration still requires the super-admin login. D1 does
19
+ not provide the deployment-admin grant store.
20
+
21
+ The access store also implements OR3's optional, read-only customer support reads:
22
+ `listCustomers` (keyset-paged by creation time, at most 50 rows, literal
23
+ substring search), `getCustomersByIds` and `getCustomerWorkspaces` (owned
24
+ workspaces including deleted ones, plus memberships). They never provision rows.
25
+ "Last contact" is the latest `device_cursors.updated_at` for the user. Hosts that
26
+ predate these reads ignore them.
27
+
16
28
  SSR-authenticated deployments also activate SQLite when it is selected only by
17
29
  `OR3_LIMITS_ENABLED=true` and `OR3_LIMITS_STORAGE_PROVIDER=sqlite`, independently
18
30
  of the account workspace backend.
@@ -418,10 +430,41 @@ Admin workspace summaries, workspace details, and deployment-admin lists expose
418
430
 
419
431
  ## Dormant immutable-generation foundation (unreleased)
420
432
 
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).
433
+ Migration 030 adds generation records, current-hash heads, and canonical write barriers after the released migrations. Normal transfer routes do not create these records. Cleanup is disabled by default; the Linux adapter can expose the coordinator through the explicit opt-in described below. See [protocol invariants and activation blockers](docs/storage-generations.md).
422
434
 
423
- Migrations 030–031 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
435
+ Migrations 030–032 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
424
436
 
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).
437
+ Migration 031 adds the upload ledger and restore tickets. Normal generation transfer routes remain unregistered. See [upload, restore, and recovery invariants](docs/storage-generation-uploads.md).
426
438
 
427
439
  Background history admission and finalization failures expose structured codes for validation, authorization, conflicts, and supersession. Transient SQLite failures retain their original errors for retry.
440
+
441
+ The dormant generation coordinator now exposes `retainedGenerationQuotaVersion: 1`.
442
+ It charges allocations and Trash through the existing retained ledger and only
443
+ releases enrolled-object charges after confirmed removal acknowledgement. Restores
444
+ reuse their retained charge; replacement waits for confirmed deletion. Legacy
445
+ retained objects cannot be implicitly adopted. This adds no schema migration,
446
+ registration or production cleanup activation.
447
+
448
+ ### Admin diagnostics and managed-generation inspection
449
+
450
+ The optional customer-read store includes bounded completed-sync observations
451
+ (migration `032_sync_observations`): last successful gateway operation and latest
452
+ classified failure per user/workspace. These observations contain no sync payload,
453
+ are independent of cursor contact, and cannot invalidate an accepted sync write.
454
+ The SQLite admin adapter's explicit health probe verifies a canonical database
455
+ read; configuration/enablement alone is not a health result.
456
+
457
+ The dormant generation coordinator also exposes `inspectCandidates` to trusted
458
+ server callers. It pages at most 100 exact enrolled generations per workspace,
459
+ uses the same bounded eligibility proof as claims, and changes no generation or
460
+ accounting state. Estimates describe logical managed bytes, not reclaimed disk
461
+ blocks. Mutable legacy storage is excluded. This read does not register deletion,
462
+ HTTP upload, restore, cleanup automation or a production capability. Installed
463
+ Linux filesystem and independent S3 backup/crash lifecycle gates remain required
464
+ before activation.
465
+
466
+ ### Opt-in enrolled-generation cleanup
467
+
468
+ On Linux, the SQLite/filesystem pairing exposes managed-generation cleanup only when `OR3_STORAGE_FS_CLEANUP_NAMESPACE_ID` names the existing filesystem namespace UUID and SQLite runs with `OR3_SQLITE_PRAGMA_SYNCHRONOUS=FULL` (or `EXTRA`). The namespace must already have been provisioned by the generation protocol; this setting neither provisions it nor enrolls legacy files. It does not change normal upload/download routing. Leave the namespace setting unset to keep cleanup unavailable. D1 and other unsupported drivers remain unavailable.
469
+
470
+ Manual admin cleanup rechecks canonical eligibility and uses the installed filesystem remover. Optional `OR3_STORAGE_RETENTION_WORKSPACES` selects explicit workspace IDs for the same audited primitive, with seven-day retention and at most 25 examined generations per hourly turn. Changing these environment settings requires a managed restart. Defaults remain disabled. Use the repaired managed backup/restore path for enrolled data; raw file copying is not a supported restore.
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.26",
4
+ "version": "0.0.28",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -9,6 +9,8 @@ import {
9
9
  SYNC_MAINTENANCE_RETENTION_SECONDS
10
10
  } from "../../sync/maintenance-state.js";
11
11
  import { createSqliteSyncGatewayAdapter } from "../../sync/sqlite-sync-gateway-adapter.js";
12
+ import { sql } from "kysely";
13
+ import { getSqliteDb } from "../../db/kysely.js";
12
14
  import { getSqliteDriver } from "../../db/kysely.js";
13
15
  const SQLITE_PROVIDER_ID = "sqlite";
14
16
  let gatewayInstance;
@@ -19,6 +21,10 @@ function getGateway() {
19
21
  export const sqliteSyncAdminAdapter = {
20
22
  id: SQLITE_PROVIDER_ID,
21
23
  kind: "sync",
24
+ async check() {
25
+ await sql`SELECT 1 FROM users LIMIT 1`.execute(getSqliteDb());
26
+ return { result: "passed", kind: "database_read", scope: "canonical SQLite database", code: "read_ok" };
27
+ },
22
28
  async getStatus(_event, _ctx) {
23
29
  const driver = getSqliteDriver();
24
30
  const isLocalDriver = driver === "better-sqlite3" || driver === "bun";
@@ -1,4 +1,6 @@
1
+ import { sql } from "kysely";
1
2
  import { getSqliteDb } from "../../db/kysely.js";
3
+ import { SqliteExternalStorageGenerationCoordinator } from "../../storage/sqlite-generation-coordinator.js";
2
4
  function nowEpoch() {
3
5
  return Math.floor(Date.now() / 1e3);
4
6
  }
@@ -8,10 +10,46 @@ function normalizeEmail(value) {
8
10
  function isEmail(value) {
9
11
  return value.includes("@");
10
12
  }
13
+ const CUSTOMER_PAGE_MAX = 50;
14
+ function escapeLike(value) {
15
+ return value.replace(/[\\%_]/g, (character) => `\\${character}`);
16
+ }
17
+ function encodeCursor(createdAt, id) {
18
+ return Buffer.from(JSON.stringify([createdAt, id])).toString("base64url");
19
+ }
20
+ function decodeCursor(cursor) {
21
+ try {
22
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
23
+ return Array.isArray(value) && value.length === 2 && Number.isSafeInteger(value[0]) && typeof value[1] === "string" ? [value[0], value[1]] : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
11
28
  class SqliteWorkspaceAccessStore {
29
+ async getStorageGenerationCandidates(input) {
30
+ return new SqliteExternalStorageGenerationCoordinator({ storageProviderId: input.storageProviderId }).inspectCandidates(input);
31
+ }
12
32
  get db() {
13
33
  return getSqliteDb();
14
34
  }
35
+ async recordSyncObservation(input) {
36
+ if (!Number.isSafeInteger(input.observedAt) || input.observedAt < 0) throw new Error("Invalid observation time");
37
+ const success = input.outcome === "success";
38
+ const code = ["provider_failed", "request_rejected", "operation_rejected", "rate_limited", "access_denied"].includes(input.code ?? "") ? input.code : "provider_failed";
39
+ await sql`INSERT INTO sync_observations (user_id, workspace_id, last_success_at, last_success_operation, last_failure_at, last_failure_code)
40
+ VALUES (${input.userId}, ${input.workspaceId}, ${success ? input.observedAt : null}, ${success ? input.operation : null}, ${success ? null : input.observedAt}, ${success ? null : code})
41
+ ON CONFLICT (user_id, workspace_id) DO UPDATE SET
42
+ last_success_at = CASE WHEN excluded.last_success_at >= COALESCE(last_success_at, 0) THEN excluded.last_success_at ELSE last_success_at END,
43
+ last_success_operation = CASE WHEN excluded.last_success_at >= COALESCE(last_success_at, 0) THEN excluded.last_success_operation ELSE last_success_operation END,
44
+ last_failure_at = CASE WHEN excluded.last_failure_at >= COALESCE(last_failure_at, 0) THEN excluded.last_failure_at ELSE last_failure_at END,
45
+ last_failure_code = CASE WHEN excluded.last_failure_at >= COALESCE(last_failure_at, 0) THEN excluded.last_failure_code ELSE last_failure_code END`.execute(this.db);
46
+ }
47
+ async getCustomerSyncObservations(input) {
48
+ const result = await sql`
49
+ SELECT workspace_id, last_success_at, last_success_operation, last_failure_at, last_failure_code
50
+ FROM sync_observations WHERE user_id = ${input.userId} ORDER BY workspace_id LIMIT 500`.execute(this.db);
51
+ return result.rows.map((row) => ({ workspaceId: row.workspace_id, lastSuccessAt: row.last_success_at, lastSuccessOperation: row.last_success_operation, lastFailureAt: row.last_failure_at, lastFailureCode: row.last_failure_code }));
52
+ }
15
53
  async listMembers(input) {
16
54
  const rows = await this.db.selectFrom("workspace_members").innerJoin("users", "users.id", "workspace_members.user_id").select([
17
55
  "workspace_members.user_id as user_id",
@@ -282,6 +320,74 @@ class SqliteWorkspaceAccessStore {
282
320
  deleted_at: null
283
321
  }).where("id", "=", input.workspaceId).execute();
284
322
  }
323
+ /** Bounded, read-only canonical directory. Keyset-paginated by creation time; never provisions. */
324
+ async listCustomers(input) {
325
+ const limit = Math.max(1, Math.min(input.limit, CUSTOMER_PAGE_MAX));
326
+ const query = input.query?.trim();
327
+ const cursor = input.cursor ? decodeCursor(input.cursor) : null;
328
+ if (input.cursor && !cursor) throw new Error("Invalid customer cursor");
329
+ let rows = this.db.selectFrom("users").select(["id", "email", "display_name", "created_at"]);
330
+ if (query) {
331
+ const pattern = `%${escapeLike(query)}%`;
332
+ rows = rows.where(sql`(email LIKE ${pattern} ESCAPE '\\' OR display_name LIKE ${pattern} ESCAPE '\\' OR id LIKE ${pattern} ESCAPE '\\')`);
333
+ }
334
+ if (cursor) rows = rows.where(sql`(created_at < ${cursor[0]} OR (created_at = ${cursor[0]} AND id < ${cursor[1]}))`);
335
+ const page = await rows.orderBy("created_at", "desc").orderBy("id", "desc").limit(limit + 1).execute();
336
+ const items = page.slice(0, limit);
337
+ const last = items.at(-1);
338
+ return {
339
+ items: await this.withLastContact(items),
340
+ nextCursor: page.length > limit && last ? encodeCursor(last.created_at, last.id) : null
341
+ };
342
+ }
343
+ /** Batch lookup by internal IDs. Unknown IDs are omitted, never invented. */
344
+ async getCustomersByIds(input) {
345
+ const ids = [...new Set(input.userIds)].slice(0, CUSTOMER_PAGE_MAX);
346
+ if (!ids.length) return [];
347
+ const rows = await this.db.selectFrom("users").select(["id", "email", "display_name", "created_at"]).where("id", "in", ids).execute();
348
+ return this.withLastContact(rows);
349
+ }
350
+ /** Owned workspaces (including retained deleted ones) and memberships for one canonical user. */
351
+ async getCustomerWorkspaces(input) {
352
+ const rows = await this.db.selectFrom("workspaces").leftJoin("workspace_members as membership", (join) => join.onRef("membership.workspace_id", "=", "workspaces.id").on("membership.user_id", "=", input.userId)).select([
353
+ "workspaces.id as id",
354
+ "workspaces.name as name",
355
+ "workspaces.owner_user_id as owner_user_id",
356
+ "workspaces.created_at as created_at",
357
+ "workspaces.deleted as deleted",
358
+ "workspaces.deleted_at as deleted_at",
359
+ "membership.role as role",
360
+ (eb) => eb.selectFrom("workspace_members").select((inner) => inner.fn.countAll().as("n")).whereRef("workspace_members.workspace_id", "=", "workspaces.id").as("member_count"),
361
+ (eb) => eb.selectFrom("device_cursors").select((inner) => inner.fn.max("device_cursors.updated_at").as("t")).whereRef("device_cursors.workspace_id", "=", "workspaces.id").where("device_cursors.owner_user_id", "=", input.userId).as("last_contact")
362
+ ]).where((eb) => eb.or([
363
+ eb("workspaces.owner_user_id", "=", input.userId),
364
+ eb("membership.user_id", "=", input.userId)
365
+ ])).orderBy("workspaces.created_at", "asc").limit(500).execute();
366
+ return rows.map((row) => ({
367
+ id: row.id,
368
+ name: row.name,
369
+ role: row.owner_user_id === input.userId ? "owner" : row.role ?? "viewer",
370
+ ownerUserId: row.owner_user_id,
371
+ createdAt: row.created_at * 1e3,
372
+ deleted: row.deleted === 1,
373
+ deletedAt: row.deleted_at ?? void 0,
374
+ memberCount: Number(row.member_count ?? 0),
375
+ lastContactAt: row.last_contact == null ? null : Number(row.last_contact) * 1e3
376
+ }));
377
+ }
378
+ /** Last sync cursor write by this user (server contact, not proof of a completed sync). */
379
+ async withLastContact(rows) {
380
+ if (!rows.length) return [];
381
+ const contacts = await this.db.selectFrom("device_cursors").select(["owner_user_id", (eb) => eb.fn.max("updated_at").as("t")]).where("owner_user_id", "in", rows.map((row) => row.id)).groupBy("owner_user_id").execute();
382
+ const byUser = new Map(contacts.map((row) => [row.owner_user_id, Number(row.t) * 1e3]));
383
+ return rows.map((row) => ({
384
+ userId: row.id,
385
+ email: row.email ?? void 0,
386
+ displayName: row.display_name ?? void 0,
387
+ createdAt: row.created_at * 1e3,
388
+ lastContactAt: byUser.get(row.id) ?? null
389
+ }));
390
+ }
285
391
  async searchUsers(input) {
286
392
  const query = input.query.trim();
287
393
  const limit = Math.max(1, Math.min(input.limit ?? 20, 100));
@@ -56,7 +56,8 @@ const REQUIRED_SCHEMA_TABLES = [
56
56
  "background_generation_receipts",
57
57
  "storage_object_generations",
58
58
  "storage_object_heads",
59
- "storage_generation_uploads"
59
+ "storage_generation_uploads",
60
+ "sync_observations"
60
61
  ];
61
62
  import * as m024 from "./migrations/024_signup_invites.js";
62
63
  import * as m025 from "./migrations/025_background_shutdown_accounting.js";
@@ -66,6 +67,7 @@ import * as m028 from "./migrations/028_user_scoped_device_cursors.js";
66
67
  import * as m029 from "./migrations/029_delegation_wait.js";
67
68
  import * as m030 from "./migrations/030_storage_generations.js";
68
69
  import * as m031 from "./migrations/031_storage_generation_uploads.js";
70
+ import * as m032 from "./migrations/032_sync_observations.js";
69
71
  const migrations = {
70
72
  "001_init": m001,
71
73
  "002_sync_tables": m002,
@@ -97,7 +99,8 @@ const migrations = {
97
99
  "028_user_scoped_device_cursors": m028,
98
100
  "029_delegation_wait": m029,
99
101
  "030_storage_generations": m030,
100
- "031_storage_generation_uploads": m031
102
+ "031_storage_generation_uploads": m031,
103
+ "032_sync_observations": m032
101
104
  };
102
105
  class StaticMigrationProvider {
103
106
  async getMigrations() {
@@ -0,0 +1,3 @@
1
+ import { type Kysely } from 'kysely';
2
+ export declare function up(db: Kysely<unknown>): Promise<void>;
3
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { sql } from "kysely";
2
+ import { ensureMigrationSchema } from "../migration-schema.js";
3
+ export async function up(db) {
4
+ await ensureMigrationSchema(db, `CREATE TABLE sync_observations (
5
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
6
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
7
+ last_success_at INTEGER, last_success_operation TEXT,
8
+ last_failure_at INTEGER, last_failure_code TEXT,
9
+ PRIMARY KEY (user_id, workspace_id)
10
+ )`);
11
+ await ensureMigrationSchema(db, "CREATE INDEX idx_users_admin_created_id ON users (created_at DESC, id DESC)");
12
+ }
13
+ export async function down(db) {
14
+ await sql`DROP INDEX idx_users_admin_created_id`.execute(db);
15
+ await sql`DROP TABLE sync_observations`.execute(db);
16
+ }
@@ -48,6 +48,29 @@ export declare class SqliteExternalStorageGenerationCoordinator implements Exter
48
48
  generation: ExternalStorageGenerationRecord;
49
49
  }>;
50
50
  getGeneration(input: ExternalStorageGenerationKey): Promise<ExternalStorageGenerationRecord | null>;
51
+ private eligibility;
52
+ /** Read-only bounded advisory proof. A result is never deletion authority;
53
+ * claimGeneration repeats every proof in its own durable transaction. */
54
+ inspectCandidates(input: {
55
+ workspaceId: string;
56
+ retentionSeconds: number;
57
+ limit?: number;
58
+ cursor?: string;
59
+ }): Promise<{
60
+ items: {
61
+ generation: ExternalStorageGenerationRecord;
62
+ status: "deleted" | "blocked" | "claimed" | "eligible";
63
+ reason: "missing" | "not_current" | "in_use" | "unknown_references" | "active_upload" | "claim_conflict" | "retention" | "proof_incomplete" | null;
64
+ }[];
65
+ complete: boolean;
66
+ nextCursor: string | null;
67
+ observedAt: number;
68
+ workspaceId: string;
69
+ retentionSeconds: number;
70
+ estimatedLogicalBytes: number | null;
71
+ scope: "managed_generations_only";
72
+ legacyIncluded: false;
73
+ }>;
51
74
  claimGeneration(input: ExternalStorageGenerationKey & {
52
75
  claimId: string;
53
76
  retentionSeconds: number;
@@ -58,5 +81,10 @@ export declare class SqliteExternalStorageGenerationCoordinator implements Exter
58
81
  status: 'deleted' | 'replayed';
59
82
  generation: ExternalStorageGenerationRecord;
60
83
  }>;
84
+ /** Runs under the same guarded transaction as removal acknowledgement.
85
+ * Only permanently enrolled targets may release a retained hash charge;
86
+ * legacy objects and any successor/pending generation keep their charge.
87
+ */
88
+ protected releaseManagedRetainedCharge(key: ExternalStorageGenerationKey): void;
61
89
  }
62
90
  export {};
@@ -12,7 +12,7 @@ import {
12
12
  generationReferencesSql,
13
13
  validGenerationReferencesSql
14
14
  } from "../db/storage-generation-guards.js";
15
- import { generationUploadGuardTriggers } from "../db/storage-generation-upload-guards.js";
15
+ import { generationUploadGuardTriggers, GENERATION_UPLOAD_TABLE } from "../db/storage-generation-upload-guards.js";
16
16
  export function assertGenerationIdentifier(value, name, max = 256) {
17
17
  if (typeof value !== "string" || !value || value.length > max || value !== value.trim() || [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) {
18
18
  throw new Error(`Invalid storage generation ${name}`);
@@ -173,6 +173,64 @@ export class SqliteExternalStorageGenerationCoordinator {
173
173
  return row ? generationRecord(row) : null;
174
174
  });
175
175
  }
176
+ eligibility(row, retentionSeconds) {
177
+ const key = generationRecord(row);
178
+ if (this.head(key)?.generation_id !== key.generationId) return { reason: "not_current", lastActivity: row.last_activity_at };
179
+ const proof = this.metadataProof(key, false, row.storage_id) ?? this.referenceProof(key, false);
180
+ if (proof) return { reason: proof, lastActivity: row.last_activity_at };
181
+ const now = this.now();
182
+ const intents = this.raw.prepare(`SELECT ${validGenerationHashSql("hash")} AS valid_hash,
183
+ ${generationHashSql("hash")} AS hash, expires_at FROM upload_intents
184
+ WHERE workspace_id = ? AND status = 'active' LIMIT ?`).all(key.workspaceId, GENERATION_PROOF_ROWS + 1);
185
+ if (intents.length > GENERATION_PROOF_ROWS) return { reason: "proof_incomplete", lastActivity: row.last_activity_at };
186
+ let lastActivity = row.last_activity_at;
187
+ for (const intent of intents) {
188
+ if (intent.valid_hash !== 1 || !Number.isSafeInteger(intent.expires_at) || intent.expires_at < 0) {
189
+ return { reason: "unknown_references", lastActivity: row.last_activity_at };
190
+ }
191
+ if (intent.hash !== key.hash) continue;
192
+ if (intent.expires_at > now) return { reason: "active_upload", lastActivity: row.last_activity_at };
193
+ lastActivity = Math.max(lastActivity, intent.expires_at);
194
+ }
195
+ if (now < lastActivity || now - lastActivity < retentionSeconds) return { reason: "retention", lastActivity: row.last_activity_at };
196
+ return { reason: null, lastActivity };
197
+ }
198
+ /** Read-only bounded advisory proof. A result is never deletion authority;
199
+ * claimGeneration repeats every proof in its own durable transaction. */
200
+ async inspectCandidates(input) {
201
+ assertGenerationIdentifier(input.workspaceId, "workspace");
202
+ const limit = input.limit ?? 25;
203
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("Invalid storage candidate limit");
204
+ if (!Number.isSafeInteger(input.retentionSeconds) || input.retentionSeconds < 0) throw new Error("Invalid storage retention interval");
205
+ if (input.cursor !== void 0) assertGenerationIdentifier(input.cursor, "cursor");
206
+ if (this.raw.inTransaction !== false) throw new Error("Storage inspection requires its own read snapshot");
207
+ return this.raw.transaction(() => {
208
+ this.assertIntegrity();
209
+ const rows = this.raw.prepare(`SELECT * FROM ${GENERATION_TABLE} WHERE workspace_id = ? AND storage_provider_id = ?
210
+ AND generation_id > ? ORDER BY generation_id LIMIT ?`).all(input.workspaceId, this.storageProviderId, input.cursor ?? "", limit + 1);
211
+ const complete = rows.length <= limit;
212
+ const items = rows.slice(0, limit).map((row) => {
213
+ const proof = row.state === "verified" ? this.eligibility(row, input.retentionSeconds) : null;
214
+ return {
215
+ generation: generationRecord(row),
216
+ status: row.state !== "verified" ? row.state : proof?.reason ? "blocked" : "eligible",
217
+ reason: proof?.reason ?? null
218
+ };
219
+ });
220
+ const estimated = items.filter((item) => item.status === "eligible").reduce((sum, item) => sum + item.generation.sizeBytes, 0);
221
+ return {
222
+ items,
223
+ complete,
224
+ nextCursor: complete ? null : items.at(-1).generation.generationId,
225
+ observedAt: this.now(),
226
+ workspaceId: input.workspaceId,
227
+ retentionSeconds: input.retentionSeconds,
228
+ estimatedLogicalBytes: Number.isSafeInteger(estimated) ? estimated : null,
229
+ scope: "managed_generations_only",
230
+ legacyIncluded: false
231
+ };
232
+ })();
233
+ }
176
234
  async claimGeneration(input) {
177
235
  const key = this.key(input);
178
236
  assertGenerationIdentifier(input.claimId, "claim");
@@ -181,24 +239,9 @@ export class SqliteExternalStorageGenerationCoordinator {
181
239
  const row = this.find(key);
182
240
  if (!row) return { status: "blocked", reason: "missing" };
183
241
  if (row.state !== "verified") return row.claim_id === input.claimId ? { status: "replayed", generation: generationRecord(row) } : { status: "blocked", reason: "claim_conflict" };
184
- if (this.head(key)?.generation_id !== key.generationId) return { status: "blocked", reason: "not_current" };
185
- const proof = this.metadataProof(key, false, row.storage_id) ?? this.referenceProof(key, false);
186
- if (proof) return { status: "blocked", reason: proof };
242
+ const { reason, lastActivity } = this.eligibility(row, input.retentionSeconds);
243
+ if (reason) return { status: "blocked", reason };
187
244
  const now = this.now();
188
- const intents = this.raw.prepare(`SELECT ${validGenerationHashSql("hash")} AS valid_hash,
189
- ${generationHashSql("hash")} AS hash, expires_at FROM upload_intents
190
- WHERE workspace_id = ? AND status = 'active' LIMIT ?`).all(key.workspaceId, GENERATION_PROOF_ROWS + 1);
191
- if (intents.length > GENERATION_PROOF_ROWS) return { status: "blocked", reason: "proof_incomplete" };
192
- let lastActivity = row.last_activity_at;
193
- for (const intent of intents) {
194
- if (intent.valid_hash !== 1 || !Number.isSafeInteger(intent.expires_at) || intent.expires_at < 0) {
195
- return { status: "blocked", reason: "unknown_references" };
196
- }
197
- if (intent.hash !== key.hash) continue;
198
- if (intent.expires_at > now) return { status: "blocked", reason: "active_upload" };
199
- lastActivity = Math.max(lastActivity, intent.expires_at);
200
- }
201
- if (now < lastActivity || now - lastActivity < input.retentionSeconds) return { status: "blocked", reason: "retention" };
202
245
  if (this.raw.prepare(`SELECT 1 FROM ${GENERATION_TABLE} WHERE claim_id = ?`).get(input.claimId)) {
203
246
  return { status: "blocked", reason: "claim_conflict" };
204
247
  }
@@ -213,11 +256,33 @@ export class SqliteExternalStorageGenerationCoordinator {
213
256
  return this.mutate(() => {
214
257
  const row = this.find(key);
215
258
  if (!row || row.claim_id !== input.claimId || row.state === "verified") throw new Error("Storage generation claim mismatch");
216
- if (row.state === "deleted") return { status: "replayed", generation: generationRecord(row) };
259
+ if (row.state === "deleted") {
260
+ this.releaseManagedRetainedCharge(key);
261
+ return { status: "replayed", generation: generationRecord(row) };
262
+ }
217
263
  const now = this.now();
218
264
  if (row.claimed_at === null || now < row.claimed_at) throw new Error("Storage generation server clock regressed");
219
265
  this.raw.prepare(`UPDATE ${GENERATION_TABLE} SET state = 'deleted', deleted_at = ? WHERE generation_id = ?`).run(now, key.generationId);
266
+ this.releaseManagedRetainedCharge(key);
220
267
  return { status: "deleted", generation: generationRecord(this.find(key)) };
221
268
  });
222
269
  }
270
+ /** Runs under the same guarded transaction as removal acknowledgement.
271
+ * Only permanently enrolled targets may release a retained hash charge;
272
+ * legacy objects and any successor/pending generation keep their charge.
273
+ */
274
+ releaseManagedRetainedCharge(key) {
275
+ const origins = this.raw.prepare(`SELECT generation_id, state, published_generation_id FROM ${GENERATION_UPLOAD_TABLE}
276
+ WHERE workspace_id = ? AND hash = ? AND purpose = 'upload' LIMIT ?`).all(key.workspaceId, key.hash, GENERATION_PROOF_ROWS + 1);
277
+ if (!origins.length || origins.length > GENERATION_PROOF_ROWS) return;
278
+ if (this.raw.prepare(`SELECT 1 FROM ${GENERATION_TABLE} WHERE workspace_id = ? AND hash = ? AND state <> 'deleted' LIMIT 1`).get(key.workspaceId, key.hash)) return;
279
+ if (origins.some((row) => row.state !== "abandoned" && !(row.state === "materialized" && row.published_generation_id === row.generation_id))) return;
280
+ if (this.raw.prepare(`SELECT 1 FROM upload_intents WHERE workspace_id = ? AND hash = ? AND status = 'active' LIMIT 1`).get(key.workspaceId, key.hash)) return;
281
+ const retained = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(key.workspaceId, key.hash);
282
+ if (!retained) return;
283
+ if (!Number.isSafeInteger(retained.size_bytes) || retained.size_bytes < 0) throw new Error("Invalid retained storage charge");
284
+ const result = this.raw.prepare("UPDATE storage_usage SET used_bytes=used_bytes-? WHERE workspace_id=? AND used_bytes>=?").run(retained.size_bytes, key.workspaceId, retained.size_bytes);
285
+ if (result.changes !== 1) throw new Error("Retained storage accounting mismatch");
286
+ this.raw.prepare("DELETE FROM retained_storage WHERE workspace_id=? AND hash=?").run(key.workspaceId, key.hash);
287
+ }
223
288
  }
@@ -25,6 +25,9 @@ type RestoreInput = ExternalStorageGenerationUploadKey & {
25
25
  /** Optional trusted-server factory input only. No adapter or route registers it. */
26
26
  export declare class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExternalStorageGenerationCoordinator implements ExternalStorageGenerationUploadCoordinatorV1 {
27
27
  readonly uploadVersion: 1;
28
+ /** Allocation/Trash/claimed bytes remain in the canonical retained ledger
29
+ * until independently verified removal is acknowledged. */
30
+ readonly retainedGenerationQuotaVersion: 1;
28
31
  private uploadKey;
29
32
  private claimKey;
30
33
  private upload;
@@ -32,6 +35,8 @@ export declare class SqliteExternalStorageGenerationUploadCoordinator extends Sq
32
35
  private mustUpload;
33
36
  private activeIntents;
34
37
  private quotaUsed;
38
+ private retainedBytes;
39
+ private chargedBytes;
35
40
  private sum;
36
41
  reserveGenerationUpload(input: ReserveInput): Promise<{
37
42
  status: 'reserved' | 'replayed';
@@ -3,7 +3,7 @@ import {
3
3
  assertGenerationIdentifier,
4
4
  generationRecord
5
5
  } from "./sqlite-generation-coordinator.js";
6
- import { GENERATION_TABLE, HEAD_TABLE, GENERATION_PROOF_ROWS, generationHashSql, validGenerationHashSql, validGenerationObjectSql } from "../db/storage-generation-guards.js";
6
+ import { GENERATION_TABLE, HEAD_TABLE, GENERATION_PROOF_ROWS, generationHashSql, validGenerationHashSql } from "../db/storage-generation-guards.js";
7
7
  import {
8
8
  GENERATION_UPLOAD_TABLE as UPLOADS,
9
9
  GENERATION_UPLOAD_HOLD_EXPIRY,
@@ -38,6 +38,9 @@ function intent(row) {
38
38
  }
39
39
  export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExternalStorageGenerationCoordinator {
40
40
  uploadVersion = 1;
41
+ /** Allocation/Trash/claimed bytes remain in the canonical retained ledger
42
+ * until independently verified removal is acknowledged. */
43
+ retainedGenerationQuotaVersion = 1;
41
44
  uploadKey(input) {
42
45
  assertGenerationIdentifier(input.intentId, "upload intent");
43
46
  assertGenerationIdentifier(input.userId, "upload owner");
@@ -98,22 +101,29 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
98
101
  return rows;
99
102
  }
100
103
  quotaUsed(workspaceId) {
101
- const rows = this.raw.prepare(`SELECT deleted, data_json, ${validGenerationObjectSql("data_json")} AS valid
102
- FROM s_file_meta WHERE workspace_id = ? LIMIT ?`).all(workspaceId, GENERATION_PROOF_ROWS + 1);
103
- if (rows.length > GENERATION_PROOF_ROWS) throw new Error("Storage upload proof_incomplete: metadata budget");
104
+ const rows = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? LIMIT ?").all(workspaceId, GENERATION_PROOF_ROWS + 1);
105
+ if (rows.length > GENERATION_PROOF_ROWS) throw new Error("Storage upload proof_incomplete: retained budget");
104
106
  let used = 0;
105
107
  for (const row of rows) {
106
- if (row.deleted !== 0) continue;
107
- if (row.valid !== 1) throw new Error("Storage upload invalid canonical metadata");
108
- const data = JSON.parse(row.data_json);
109
- const size = data.size_bytes ?? data.sizeBytes;
110
- if ("size_bytes" in data && "sizeBytes" in data || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
111
- throw new Error("Storage upload invalid canonical file size");
112
- }
113
- used = this.sum(used, size);
108
+ used = this.sum(used, row.size_bytes);
114
109
  }
115
110
  return used;
116
111
  }
112
+ retainedBytes(workspaceId, hash) {
113
+ const row = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(workspaceId, hash);
114
+ return this.sum(0, row?.size_bytes ?? 0);
115
+ }
116
+ chargedBytes(workspaceId, hash, now) {
117
+ let charged = this.quotaUsed(workspaceId);
118
+ const pending = /* @__PURE__ */ new Map();
119
+ for (const row of this.activeIntents(workspaceId)) {
120
+ if (row.expires_at <= now) continue;
121
+ if (row.hash === hash) throw new Error("Storage upload already has an active reservation");
122
+ pending.set(row.hash, Math.max(pending.get(row.hash) ?? 0, row.reserved_bytes));
123
+ }
124
+ for (const [digest, size] of pending) charged = this.sum(charged, Math.max(0, size - this.retainedBytes(workspaceId, digest)));
125
+ return charged;
126
+ }
117
127
  sum(left, right) {
118
128
  const value = left + right;
119
129
  if (!Number.isSafeInteger(value) || value < 0) throw new Error("Storage upload quota accounting overflow");
@@ -148,10 +158,13 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
148
158
  throw new Error("Storage generation identity or target cannot be reused");
149
159
  }
150
160
  const head = this.head(key);
151
- if (head && (head.storage_provider_id !== this.storageProviderId || head.state === "verified")) {
152
- throw new Error("Current storage generation must be irreversibly claimed before replacement");
161
+ if (head && (head.storage_provider_id !== this.storageProviderId || head.state !== "deleted")) {
162
+ throw new Error("Current storage generation must have confirmed removal before replacement");
153
163
  }
154
164
  const enrolled = Boolean(this.raw.prepare(`SELECT 1 FROM ${UPLOADS} WHERE workspace_id = ? AND hash = ? LIMIT 1`).get(key.workspaceId, key.hash));
165
+ if (!enrolled && this.raw.prepare("SELECT 1 FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(key.workspaceId, key.hash)) {
166
+ throw new Error("Storage generation cannot adopt legacy retained bytes");
167
+ }
155
168
  const proof = this.metadataProof(key, !head && !enrolled, input.storageId) ?? this.referenceProof(key, !head && !enrolled);
156
169
  if (proof) throw new Error(`Legacy storage adoption or upload proof failed: ${proof}`);
157
170
  const pending = this.raw.prepare(`SELECT count(*) AS count FROM ${UPLOADS} WHERE workspace_id = ?
@@ -159,12 +172,7 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
159
172
  if (pending.count >= GENERATION_UPLOAD_MAX_PENDING) throw new Error("Storage upload pending allocation limit");
160
173
  const now = this.now();
161
174
  const expires = this.sum(now, input.expiresInSeconds);
162
- let charged = this.quotaUsed(key.workspaceId);
163
- for (const row of this.activeIntents(key.workspaceId)) {
164
- if (row.expires_at <= now) continue;
165
- if (row.hash === key.hash) throw new Error("Storage upload already has an active reservation");
166
- charged = this.sum(charged, row.reserved_bytes);
167
- }
175
+ const charged = this.chargedBytes(key.workspaceId, key.hash, now);
168
176
  const projectedBytes = this.sum(charged, input.sizeBytes);
169
177
  if (input.workspaceQuotaBytes !== void 0 && projectedBytes > input.workspaceQuotaBytes) {
170
178
  throw new Error("Workspace storage quota exceeded");
@@ -202,6 +210,8 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
202
210
  input.storageId,
203
211
  now
204
212
  );
213
+ this.raw.prepare(`INSERT INTO retained_storage(workspace_id,hash,size_bytes) VALUES (?,?,?)
214
+ ON CONFLICT(workspace_id,hash) DO UPDATE SET size_bytes=MAX(size_bytes,excluded.size_bytes)`).run(key.workspaceId, key.hash, input.sizeBytes);
205
215
  return { status: "reserved", intent: intent(this.mustUpload(key)) };
206
216
  });
207
217
  }
@@ -241,13 +251,8 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
241
251
  if (pending.count >= GENERATION_UPLOAD_MAX_PENDING) throw new Error("Storage restore pending allocation limit");
242
252
  const now = this.now();
243
253
  if (now < generation.last_activity_at) throw new Error("Storage restore server clock regressed");
244
- let charged = this.quotaUsed(key.workspaceId);
245
- for (const row of this.activeIntents(key.workspaceId)) {
246
- if (row.expires_at <= now) continue;
247
- if (row.hash === key.hash) throw new Error("Storage restore already has an active reservation");
248
- charged = this.sum(charged, row.reserved_bytes);
249
- }
250
- const projected = this.sum(charged, origin.size_bytes);
254
+ const charged = this.chargedBytes(key.workspaceId, key.hash, now);
255
+ const projected = this.sum(charged, Math.max(0, origin.size_bytes - this.retainedBytes(key.workspaceId, key.hash)));
251
256
  if (input.workspaceQuotaBytes !== void 0 && projected > input.workspaceQuotaBytes) throw new Error("Workspace storage quota exceeded");
252
257
  this.raw.prepare(`INSERT INTO ${UPLOADS}
253
258
  (intent_id,workspace_id,hash,generation_id,user_id,storage_provider_id,namespace_id,storage_id,mime_type,
@@ -396,11 +401,15 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
396
401
  return this.mutate(() => {
397
402
  const row = this.claimedUpload(key);
398
403
  if (!row) throw new Error("Storage upload abandonment claim mismatch");
399
- if (row.state === "abandoned") return { status: "replayed", intent: intent(row) };
404
+ if (row.state === "abandoned") {
405
+ this.releaseManagedRetainedCharge(key);
406
+ return { status: "replayed", intent: intent(row) };
407
+ }
400
408
  const now = this.now();
401
409
  if (row.claimed_at === null || now < row.claimed_at) throw new Error("Storage upload server clock regressed");
402
410
  if (row.published_generation_id !== null) this.raw.prepare(`UPDATE ${GENERATION_TABLE} SET state = 'deleted', deleted_at = ? WHERE generation_id = ? AND state = 'claimed'`).run(now, key.generationId);
403
411
  this.raw.prepare(`UPDATE ${UPLOADS} SET state = 'abandoned', deleted_at = ? WHERE intent_id = ?`).run(now, key.intentId);
412
+ this.releaseManagedRetainedCharge(key);
404
413
  return { status: "abandoned", intent: intent(this.upload(key)) };
405
414
  });
406
415
  }
@@ -1,3 +1,4 @@
1
+ import { SqliteExternalStorageGenerationUploadCoordinator } from '../storage/sqlite-generation-upload-coordinator.js';
1
2
  /**
2
3
  * SQLite implementation of SyncGatewayAdapter.
3
4
  *
@@ -18,19 +19,14 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
18
19
  watchVersion(event: H3Event, scope: {
19
20
  workspaceId: string;
20
21
  }, onVersion: (version: number) => void, onError: (error: unknown) => void): Promise<() => void>;
22
+ /** Construct only on use, after the provider initializes its database. */
23
+ get storageGenerationCoordinator(): SqliteExternalStorageGenerationUploadCoordinator | undefined;
21
24
  get capabilities(): {
22
25
  readonly snapshotBootstrap: "snapshot-v1";
23
26
  readonly historyRetention: "snapshot-v1";
24
27
  readonly retainedStorageMetadata: "v1";
25
28
  readonly atomicUploadQuota: "retained-v1";
26
- readonly backgroundGenerationHistory?: undefined;
27
- readonly delegationTerminalHistory?: undefined;
28
- readonly canonicalChatHistory?: undefined;
29
- readonly projectOwnership?: undefined;
30
- readonly workspaceItems?: undefined;
31
29
  } | {
32
- readonly snapshotBootstrap: "snapshot-v1";
33
- readonly historyRetention: "snapshot-v1";
34
30
  readonly backgroundGenerationHistory: "v1";
35
31
  readonly delegationTerminalHistory: "v1";
36
32
  readonly canonicalChatHistory: "v1";
@@ -38,6 +34,9 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
38
34
  readonly workspaceItems: "v1";
39
35
  readonly retainedStorageMetadata: "v1";
40
36
  readonly atomicUploadQuota: "retained-v1";
37
+ readonly externalStorageGenerations?: "v1" | undefined;
38
+ readonly snapshotBootstrap: "snapshot-v1";
39
+ readonly historyRetention: "snapshot-v1";
41
40
  };
42
41
  private get db();
43
42
  readChatHistory(actor: CanonicalHistoryActor, query: CanonicalChatQuery, signal?: AbortSignal): Promise<CanonicalChatReadResult>;
@@ -1,3 +1,4 @@
1
+ import { SqliteExternalStorageGenerationUploadCoordinator } from "../storage/sqlite-generation-upload-coordinator.js";
1
2
  import { backgroundFinalizationFingerprint, stableJson } from "./background-history-fingerprint.js";
2
3
  import { hasWorkspaceItemSemantics, WORKSPACE_ITEM_CAPABILITY } from "./workspace-item-capability.js";
3
4
  import { createHash } from "node:crypto";
@@ -560,6 +561,16 @@ export class SqliteSyncGatewayAdapter {
560
561
  if (this.versionWatchers.get(scope.workspaceId) === current) this.versionWatchers.delete(scope.workspaceId);
561
562
  };
562
563
  }
564
+ /** Construct only on use, after the provider initializes its database. */
565
+ get storageGenerationCoordinator() {
566
+ const namespace = process.env.OR3_STORAGE_FS_CLEANUP_NAMESPACE_ID;
567
+ if (process.platform !== "linux" || !namespace || isD1Driver()) return void 0;
568
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(namespace)) throw new Error("Invalid filesystem cleanup namespace");
569
+ const raw = getRawDb();
570
+ const durability = raw.prepare("PRAGMA synchronous").get();
571
+ if (durability.synchronous !== 2 && durability.synchronous !== 3) return void 0;
572
+ return new SqliteExternalStorageGenerationUploadCoordinator({ storageProviderId: "fs", database: raw });
573
+ }
563
574
  get capabilities() {
564
575
  return isD1Driver() ? {
565
576
  snapshotBootstrap: "snapshot-v1",
@@ -569,6 +580,7 @@ export class SqliteSyncGatewayAdapter {
569
580
  } : {
570
581
  snapshotBootstrap: "snapshot-v1",
571
582
  historyRetention: "snapshot-v1",
583
+ ...this.storageGenerationCoordinator ? { externalStorageGenerations: "v1" } : {},
572
584
  backgroundGenerationHistory: "v1",
573
585
  delegationTerminalHistory: "v1",
574
586
  canonicalChatHistory: "v1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.26",
3
+ "version": "0.0.28",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"