or3-provider-sqlite 0.0.22 → 0.0.24

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
@@ -45,6 +45,8 @@ wake its ordinary sync pull immediately when the counter changes and use a
45
45
  one-minute safety pull while connected. Last-listener teardown stops the timer;
46
46
  unsupported notification routes retain normal gateway polling.
47
47
 
48
+ Background chat admissions emit the existing thread and user-message create hooks after commit when those rows are newly created. Replayed admissions do not emit them again; hook delivery failures do not fail admission.
49
+
48
50
  ## Atomic webhook registration quotas
49
51
 
50
52
  The webhook store advertises `registrationLimit: 'atomic-v1'`. `createWebhook(input, limit)` checks the user/workspace quota (or instance-wide admin quota) in the same immediate transaction as insertion. Independent connections share the limit; exhaustion throws `WEBHOOK_LIMIT_EXCEEDED`. The optional argument leaves non-quota internal calls unchanged. OR3 Chat requires this capability for registration; ship this provider change before integrating the coordinated host change.
@@ -224,7 +226,8 @@ All tables use snake_case aligned with the sync wire format.
224
226
  - **Snapshot**: captures canonical live rows and current tombstones at one `highWatermark`, then serves immutable, keyset-paginated pages ordered by `(tableName, pk, kind)`. Notification live rows are filtered to the session user.
225
227
  - **Cursor**: forward-only tracking per authenticated user and device within a workspace. Migration 028 changes the unique key so accounts sharing a browser device ID cannot claim each other’s acknowledgements. Legacy unowned rows are never adopted and expire through normal cursor GC.
226
228
  - **Retention safety**: tombstone and `change_log` GC is enabled only under the explicit `snapshot-v1` capability and deletes old revisions acknowledged by every registered device
227
- - **Notifications**: push forces `payload.user_id` to the session user; foreign notification writes are rejected; pull/snapshot omit other users' rows
229
+ - **Notifications**: push forces `payload.user_id` to the session user on puts and deletes; foreign notification writes are rejected. Successful deletes remain visible to the owner's other devices while pull/snapshot omit other users' rows.
230
+ - **Workspace Files/Trash admission**: a client without `workspaceItemCapability: 'v1'` cannot replace or delete a canonical post/project carrying workspace Files/Trash semantics, even if the submitted payload omits those fields. Native write transactions and the D1 atomic batch check canonical state before any operation or version allocation; a rejected batch returns HTTP 426 and leaves sibling writes unchanged.
228
231
 
229
232
  Snapshot continuations are bound to the capturing user and workspace, including
230
233
  backup snapshots. Each user retains at most four copies per workspace across
@@ -397,3 +400,4 @@ cancels preparation and restores admission rather than treating failure as idle.
397
400
  An additive covering index migration keeps counts off stored response bodies.
398
401
 
399
402
  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.
403
+ 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.22",
4
+ "version": "0.0.24",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -63,6 +63,13 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
63
63
  function uid() {
64
64
  return globalThis.crypto.randomUUID();
65
65
  }
66
+ function parseRequiredHistoryAdmission(input) {
67
+ try {
68
+ return parseChatGenerationAdmissionEnvelope(input);
69
+ } catch (cause) {
70
+ throw Object.assign(new Error("Invalid background history admission", { cause }), { code: "VALIDATION_ERROR" });
71
+ }
72
+ }
66
73
  function nowEpoch() {
67
74
  return Math.floor(Date.now() / 1e3);
68
75
  }
@@ -101,12 +108,20 @@ function backgroundHistoryOpId(admission, stage) {
101
108
  const value = hex.join("");
102
109
  return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
103
110
  }
111
+ function fingerprintPayload(tableName, operation, payload) {
112
+ if (tableName !== "notifications" || operation !== "delete") return payload;
113
+ if (payload == null) return void 0;
114
+ if (typeof payload !== "object" || Array.isArray(payload)) return payload;
115
+ const intent = { ...payload };
116
+ delete intent.user_id;
117
+ return Object.keys(intent).length > 0 ? intent : void 0;
118
+ }
104
119
  function operationFingerprint(op) {
105
120
  return stableJson({
106
121
  tableName: op.tableName,
107
122
  operation: op.operation,
108
123
  pk: op.pk,
109
- payload: op.payload,
124
+ payload: fingerprintPayload(op.tableName, op.operation, op.payload),
110
125
  clock: op.stamp.clock,
111
126
  hlc: op.stamp.hlc,
112
127
  deviceId: op.stamp.deviceId
@@ -117,7 +132,7 @@ function changeLogFingerprint(row) {
117
132
  tableName: row.table_name,
118
133
  operation: row.op,
119
134
  pk: row.pk,
120
- payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
135
+ payload: fingerprintPayload(row.table_name, row.op, row.payload_json ? JSON.parse(row.payload_json) : void 0),
121
136
  clock: row.clock,
122
137
  hlc: row.hlc,
123
138
  deviceId: row.device_id
@@ -140,13 +155,50 @@ function scopeNotificationWrite(op, userId) {
140
155
  if (!userId) {
141
156
  return "Unauthorized: notification writes require a session user";
142
157
  }
143
- if (op.operation !== "put") return op;
144
158
  const payload = op.payload && typeof op.payload === "object" && !Array.isArray(op.payload) ? { ...op.payload } : {};
145
159
  if (payload.user_id !== void 0 && payload.user_id !== userId) {
146
160
  return "Forbidden: notification owner mismatch";
147
161
  }
148
162
  return { ...op, payload: { ...payload, user_id: userId } };
149
163
  }
164
+ const WORKSPACE_ITEM_UPDATE_REQUIRED = "OR3_WORKSPACE_ITEM_UPDATE_REQUIRED";
165
+ function workspaceItemUpdateRequired() {
166
+ return createError({
167
+ statusCode: 426,
168
+ statusMessage: "Update OR3 Chat to use workspace Files and Trash",
169
+ data: { code: WORKSPACE_ITEM_UPDATE_REQUIRED, requiredCapability: WORKSPACE_ITEM_CAPABILITY }
170
+ });
171
+ }
172
+ function workspaceItemCapabilityAssertion(op, workspaceId) {
173
+ const field = op.tableName === "posts" ? "meta" : "data";
174
+ const decoded = `CASE WHEN json_type(data_json, '$.${field}') = 'text'
175
+ THEN CASE WHEN json_valid(json_extract(data_json, '$.${field}'))
176
+ THEN json_extract(data_json, '$.${field}') ELSE 'null' END
177
+ ELSE COALESCE(json_extract(data_json, '$.${field}'), 'null') END`;
178
+ const semantics = op.tableName === "posts" ? `COALESCE(json_extract(data_json, '$.post_type'), json_extract(data_json, '$.postType')) = 'or3:file'
179
+ OR (json_type(metadata) = 'object' AND (
180
+ json_type(metadata, '$."or3.workspace-item"') IS NOT NULL
181
+ OR json_extract(metadata, '$.key') = 'or3.workspace-item'
182
+ ))
183
+ OR (json_type(metadata) = 'array' AND EXISTS (
184
+ SELECT 1 FROM json_each(metadata) AS entry
185
+ WHERE CASE WHEN entry.type = 'object'
186
+ THEN json_extract(entry.value, '$.key') = 'or3.workspace-item' ELSE 0 END
187
+ ))` : `json_type(metadata) = 'array' AND EXISTS (
188
+ SELECT 1 FROM json_each(metadata) AS entry
189
+ WHERE CASE WHEN entry.type = 'object'
190
+ THEN json_extract(entry.value, '$.kind') = 'file' ELSE 0 END
191
+ )`;
192
+ return {
193
+ sql: `SELECT json_extract('{}', CASE WHEN EXISTS (
194
+ SELECT 1 FROM (
195
+ SELECT data_json, ${decoded} AS metadata FROM "${SYNCED_TABLE_MAP[op.tableName]}"
196
+ WHERE workspace_id = ? AND id = ?
197
+ ) WHERE ${semantics}
198
+ ) THEN '${WORKSPACE_ITEM_UPDATE_REQUIRED}' ELSE '$' END)`,
199
+ parameters: [workspaceId, op.pk]
200
+ };
201
+ }
150
202
  const LWW_EXCLUDED_WINS = `(
151
203
  excluded.clock > TARGET.clock
152
204
  OR (excluded.clock = TARGET.clock AND excluded.hlc > TARGET.hlc)
@@ -614,24 +666,25 @@ export class SqliteSyncGatewayAdapter {
614
666
  }
615
667
  assertCanonicalActor(actor) {
616
668
  if (isD1Driver()) {
617
- throw new Error("SQLite D1 does not support background generation history v1");
669
+ throw Object.assign(new Error("SQLite D1 does not support background generation history v1"), { code: "UNSUPPORTED" });
618
670
  }
619
671
  const membership = getRawDb().prepare(
620
672
  `SELECT role FROM workspace_members
621
673
  WHERE workspace_id = ? AND user_id = ?`
622
674
  ).get(actor.workspaceId, actor.userId);
623
675
  if (!membership || membership.role !== "owner" && membership.role !== "editor") {
624
- throw new Error("Forbidden background history actor");
676
+ throw Object.assign(new Error("Forbidden background history actor"), { code: "FORBIDDEN" });
625
677
  }
626
678
  }
627
679
  async admitChatGeneration(actor, input) {
628
- const admission = parseChatGenerationAdmissionEnvelope(input);
680
+ const admission = parseRequiredHistoryAdmission(input);
629
681
  if (actor.workspaceId !== admission.workspaceId) {
630
- throw new Error("Invalid background history workspace");
682
+ throw Object.assign(new Error("Invalid background history workspace"), { code: "VALIDATION_ERROR" });
631
683
  }
632
684
  const raw = getRawDb();
633
685
  const fingerprint = createHash("sha256").update(stableJson(admission)).digest("hex");
634
- return raw.transaction(() => {
686
+ const hookEmissions = [];
687
+ const result = raw.transaction(() => {
635
688
  this.assertCanonicalActor(actor);
636
689
  const receipt = raw.prepare(
637
690
  `SELECT fingerprint, outcome, server_version
@@ -640,7 +693,7 @@ export class SqliteSyncGatewayAdapter {
640
693
  ).get(admission.workspaceId, admission.generationId);
641
694
  if (receipt) {
642
695
  if (receipt.fingerprint !== fingerprint) {
643
- throw new Error("Conflicting background admission replay");
696
+ throw Object.assign(new Error("Conflicting background admission replay"), { code: "CONFLICT" });
644
697
  }
645
698
  return {
646
699
  status: "admitted",
@@ -657,7 +710,7 @@ export class SqliteSyncGatewayAdapter {
657
710
  const expectedClock = admission.expectedAssistant?.clock ?? -1;
658
711
  const admissionClock = admission.assistantMessage.clock;
659
712
  if (row && row.deleted === 1 || row && row.clock > admissionClock || row && row.clock === admissionClock && generationId !== admission.generationId || row && row.clock > expectedClock && row.clock < admissionClock || row && row.clock === expectedClock && admission.expectedAssistant?.generationId !== void 0 && generationId !== admission.expectedAssistant.generationId) {
660
- throw new Error("Conflicting continuation admission");
713
+ throw Object.assign(new Error("Conflicting continuation admission"), { code: "CONFLICT" });
661
714
  }
662
715
  }
663
716
  const records = [
@@ -691,7 +744,7 @@ export class SqliteSyncGatewayAdapter {
691
744
  { clock: entry.record.clock, hlc, opId },
692
745
  tombstone
693
746
  )) {
694
- throw new Error("Background history record was superseded");
747
+ throw Object.assign(new Error("Background history record was superseded"), { code: "SUPERSEDED" });
695
748
  }
696
749
  const sanitized = sanitizePayloadForSync(
697
750
  entry.table,
@@ -699,12 +752,12 @@ export class SqliteSyncGatewayAdapter {
699
752
  "put"
700
753
  );
701
754
  if (!sanitized) {
702
- throw new Error("Invalid background history payload");
755
+ throw Object.assign(new Error("Invalid background history payload"), { code: "VALIDATION_ERROR" });
703
756
  }
704
757
  const payload = { ...sanitized, hlc, op_id: opId };
705
758
  const payloadJson = JSON.stringify(payload);
706
759
  if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
707
- throw new Error("Invalid background history payload size");
760
+ throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
708
761
  }
709
762
  const version = baseVersion + index + 1;
710
763
  raw.prepare(
@@ -725,7 +778,8 @@ export class SqliteSyncGatewayAdapter {
725
778
  opId,
726
779
  now
727
780
  );
728
- raw.prepare(
781
+ const existing = raw.prepare(`SELECT 1 FROM ${entry.materialized} WHERE workspace_id = ? AND id = ?`).get(admission.workspaceId, entry.record.id);
782
+ const materialized = raw.prepare(
729
783
  `INSERT INTO ${entry.materialized}
730
784
  (id, workspace_id, data_json, clock, hlc, device_id, op_id,
731
785
  deleted, created_at, updated_at)
@@ -746,6 +800,11 @@ export class SqliteSyncGatewayAdapter {
746
800
  now,
747
801
  now
748
802
  );
803
+ if ((entry.table === "threads" || entry.record.id !== admission.messageId) && !existing && materialized.changes > 0) {
804
+ const op = { tableName: entry.table, operation: "put", pk: entry.record.id, payload };
805
+ const emission = resolveHookEmission({ op, workspaceId: admission.workspaceId, now, userId: actor.userId, wasExisting: false, applied: true });
806
+ if (emission) hookEmissions.push(emission);
807
+ }
749
808
  });
750
809
  const admittedAssistant = raw.prepare(
751
810
  `SELECT data_json, clock, deleted FROM s_messages
@@ -754,7 +813,7 @@ export class SqliteSyncGatewayAdapter {
754
813
  const admittedPayload = admittedAssistant ? JSON.parse(admittedAssistant.data_json) : null;
755
814
  const admittedData = admittedPayload?.data && typeof admittedPayload.data === "object" ? admittedPayload.data : {};
756
815
  if (!admittedAssistant || admittedAssistant.deleted === 1 || admittedAssistant.clock !== admission.assistantMessage.clock || admittedData.generation_id !== admission.generationId) {
757
- throw new Error("Background assistant admission was superseded");
816
+ throw Object.assign(new Error("Background assistant admission was superseded"), { code: "SUPERSEDED" });
758
817
  }
759
818
  raw.prepare(
760
819
  `INSERT INTO background_generation_receipts
@@ -764,11 +823,19 @@ export class SqliteSyncGatewayAdapter {
764
823
  ).run(uid(), admission.workspaceId, admission.generationId, fingerprint, finalVersion, now);
765
824
  return { status: "admitted", replayed: false, serverVersion: finalVersion };
766
825
  }).immediate();
826
+ for (const emission of hookEmissions) {
827
+ try {
828
+ await emitWebhookSystemHook(emission.hookName, emission.payload);
829
+ } catch (error) {
830
+ console.error("[or3-sqlite] Background admission hook failed", error);
831
+ }
832
+ }
833
+ return result;
767
834
  }
768
835
  async finalizeChatGeneration(actor, input) {
769
- const admission = parseChatGenerationAdmissionEnvelope(input.admission);
836
+ const admission = parseRequiredHistoryAdmission(input.admission);
770
837
  if (actor.workspaceId !== admission.workspaceId) {
771
- throw new Error("Invalid background history workspace");
838
+ throw Object.assign(new Error("Invalid background history workspace"), { code: "VALIDATION_ERROR" });
772
839
  }
773
840
  const raw = getRawDb();
774
841
  const fingerprint = createHash("sha256").update(stableJson(input)).digest("hex");
@@ -781,7 +848,7 @@ export class SqliteSyncGatewayAdapter {
781
848
  ).get(admission.workspaceId, admission.generationId);
782
849
  if (receipt) {
783
850
  if (receipt.fingerprint !== fingerprint) {
784
- throw new Error("Conflicting background finalization replay");
851
+ throw Object.assign(new Error("Conflicting background finalization replay"), { code: "CONFLICT" });
785
852
  }
786
853
  return receipt.outcome === "committed" ? {
787
854
  status: "committed",
@@ -840,7 +907,7 @@ export class SqliteSyncGatewayAdapter {
840
907
  };
841
908
  const payloadJson = JSON.stringify(payload);
842
909
  if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
843
- throw new Error("Invalid background history payload size");
910
+ throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
844
911
  }
845
912
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
846
913
  const serverVersion = (counter?.value ?? 0) + 1;
@@ -1229,7 +1296,8 @@ export class SqliteSyncGatewayAdapter {
1229
1296
  uniqueOps,
1230
1297
  resultSlots,
1231
1298
  indicesByOpId,
1232
- userId
1299
+ userId,
1300
+ workspaceItemCapability: input.workspaceItemCapability
1233
1301
  });
1234
1302
  }
1235
1303
  const raw = getRawDb();
@@ -1244,11 +1312,7 @@ export class SqliteSyncGatewayAdapter {
1244
1312
  if (!table || !["posts", "projects"].includes(op.tableName)) continue;
1245
1313
  const canonical = raw.prepare("SELECT data_json FROM " + table + " WHERE id = ? AND workspace_id = ?").get(op.pk, workspaceId);
1246
1314
  if (hasWorkspaceItemSemantics(op.tableName, op.payload) || hasWorkspaceItemSemantics(op.tableName, canonical ? JSON.parse(canonical.data_json) : void 0)) {
1247
- throw createError({
1248
- statusCode: 426,
1249
- statusMessage: "Update OR3 Chat to use workspace Files and Trash",
1250
- data: { code: "OR3_WORKSPACE_ITEM_UPDATE_REQUIRED", requiredCapability: WORKSPACE_ITEM_CAPABILITY }
1251
- });
1315
+ throw workspaceItemUpdateRequired();
1252
1316
  }
1253
1317
  }
1254
1318
  }
@@ -2507,6 +2571,15 @@ export class SqliteSyncGatewayAdapter {
2507
2571
  }
2508
2572
  const now = nowEpoch();
2509
2573
  const statements = [];
2574
+ if (input.workspaceItemCapability !== WORKSPACE_ITEM_CAPABILITY) {
2575
+ for (const op of uniqueOps) {
2576
+ if (!["posts", "projects"].includes(op.tableName)) continue;
2577
+ if (hasWorkspaceItemSemantics(op.tableName, op.payload)) {
2578
+ throw workspaceItemUpdateRequired();
2579
+ }
2580
+ statements.push(workspaceItemCapabilityAssertion(op, workspaceId));
2581
+ }
2582
+ }
2510
2583
  if (newOps.length > 0) {
2511
2584
  statements.push({
2512
2585
  sql: `INSERT OR IGNORE INTO server_version_counter (workspace_id, value)
@@ -2652,7 +2725,16 @@ export class SqliteSyncGatewayAdapter {
2652
2725
  parameters: [workspaceId]
2653
2726
  });
2654
2727
  }
2655
- const batchResults = statements.length > 0 ? await d1Batch(statements) : [];
2728
+ let batchResults;
2729
+ try {
2730
+ batchResults = statements.length > 0 ? await d1Batch(statements) : [];
2731
+ } catch (error) {
2732
+ const message = error instanceof Error ? error.message : String(error);
2733
+ if (/JSON path/i.test(message) && message.includes(WORKSPACE_ITEM_UPDATE_REQUIRED)) {
2734
+ throw workspaceItemUpdateRequired();
2735
+ }
2736
+ throw error;
2737
+ }
2656
2738
  let finalServerVersion = 0;
2657
2739
  if (finalVersionResultIndex !== void 0) {
2658
2740
  const row = batchResults[finalVersionResultIndex]?.results?.[0];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.22",
3
+ "version": "0.0.24",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"