or3-provider-sqlite 0.0.29 → 0.0.31
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 +93 -3
- package/dist/module.json +1 -1
- package/dist/runtime/server/admin/adapters/sync-sqlite.js +9 -0
- package/dist/runtime/server/background-jobs/sqlite-provider.js +18 -1
- package/dist/runtime/server/db/kysely.js +11 -2
- package/dist/runtime/server/db/migrate.js +27 -2
- package/dist/runtime/server/db/migration-schema.d.ts +2 -0
- package/dist/runtime/server/db/migration-schema.js +14 -0
- package/dist/runtime/server/db/migrations/006_sync_snapshots.js +10 -21
- package/dist/runtime/server/db/migrations/007_device_cursor_ownership.js +2 -1
- package/dist/runtime/server/db/migrations/019_background_generation_history.js +5 -16
- package/dist/runtime/server/db/migrations/021_background_request_usage.js +2 -1
- package/dist/runtime/server/db/migrations/033_tool_result_operation_ids.d.ts +4 -0
- package/dist/runtime/server/db/migrations/033_tool_result_operation_ids.js +35 -0
- package/dist/runtime/server/db/migrations/034_sync_intent_fingerprint.d.ts +3 -0
- package/dist/runtime/server/db/migrations/034_sync_intent_fingerprint.js +8 -0
- package/dist/runtime/server/db/migrations/035_sync_unavailable_records.d.ts +3 -0
- package/dist/runtime/server/db/migrations/035_sync_unavailable_records.js +24 -0
- package/dist/runtime/server/db/migrations/036_sync_history_incarnation.d.ts +3 -0
- package/dist/runtime/server/db/migrations/036_sync_history_incarnation.js +28 -0
- package/dist/runtime/server/db/schema.d.ts +5 -0
- package/dist/runtime/server/sync/canonical-project-ownership.d.ts +1 -1
- package/dist/runtime/server/sync/canonical-project-ownership.js +29 -12
- package/dist/runtime/server/sync/evidence-maintenance.d.ts +20 -0
- package/dist/runtime/server/sync/evidence-maintenance.js +130 -0
- package/dist/runtime/server/sync/history-incarnation.d.ts +8 -0
- package/dist/runtime/server/sync/history-incarnation.js +54 -0
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +28 -4
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +804 -361
- package/dist/runtime/server/sync/unavailable-records.d.ts +30 -0
- package/dist/runtime/server/sync/unavailable-records.js +55 -0
- package/dist/runtime/server/utils/digest-uuid.d.ts +2 -0
- package/dist/runtime/server/utils/digest-uuid.js +7 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,6 +4,17 @@ SQLite sync and workspace store provider for OR3 Chat. Provides a lightweight, s
|
|
|
4
4
|
|
|
5
5
|
Requires **Node.js 24.22.1 or newer on the 24.x line**, matching OR3 Chat. Development and CI pin **24.22.1** in `.node-version`.
|
|
6
6
|
|
|
7
|
+
## Release 0.0.31
|
|
8
|
+
|
|
9
|
+
Requires an OR3 host with the matching sync contracts: [Saluana/or3-chat commit `2f34682144f8cef26f76248cebf2c62f4c1178f8`](https://github.com/Saluana/or3-chat/commit/2f34682144f8cef26f76248cebf2c62f4c1178f8) or a later commit on `or3-cloud` containing those contracts. Upgrade the host and provider together; do not activate this provider on an older host.
|
|
10
|
+
|
|
11
|
+
- Validates final generic and background writes through the host's `prepareSyncWrite`, preserving atomic row/log writes and replay identity.
|
|
12
|
+
- Retains unavailable-record evidence before advancing pull or snapshot coverage, with bounded inspect/export and validated repair at a fresh winning version. Push containment requires `stored-record-v1` so matching clients hold affected intents recoverably while healthy siblings proceed.
|
|
13
|
+
- Adds persisted history incarnation `v1` fencing for pull, snapshot, push and ACK, and contiguous-prefix log GC. Recovery decisions run before stored payload reads or decode.
|
|
14
|
+
- Adds atomic native migrations and resumable, validated historical migration handling for 034–036 (intent fingerprints, unavailable evidence and history incarnation). Migration 033 guards malformed payloads so their original bytes survive for evidence and repair.
|
|
15
|
+
|
|
16
|
+
Keep a pre-upgrade database backup. These migrations are forward-only; rollback requires restoring the matching pre-upgrade snapshot. Native SQLite advertises history incarnation; D1 retains its explicit qualification boundary described below.
|
|
17
|
+
|
|
7
18
|
## What it provides
|
|
8
19
|
|
|
9
20
|
- **AuthWorkspaceStore** (`sqlite`) — user identity mapping, workspace CRUD, role resolution
|
|
@@ -231,15 +242,26 @@ upload intents, and Connect credential/lifecycle hardening and rate limits.
|
|
|
231
242
|
|
|
232
243
|
All tables use snake_case aligned with the sync wire format.
|
|
233
244
|
|
|
245
|
+
Native SQLite migrations commit pending DDL, data changes, and migration ledger
|
|
246
|
+
entries atomically. D1 retains its separate nontransactional migration path.
|
|
247
|
+
Historical additive steps in 006, 007, 019, and 021 resume only when existing
|
|
248
|
+
columns match their expected definitions; 006 also validates existing snapshot
|
|
249
|
+
schema. A leftover historical rebuild table stops startup with a recovery error
|
|
250
|
+
and preserves the surviving tables for operator inspection. Do not delete those
|
|
251
|
+
tables to bypass the error. Migration 033 uses temporary repair indexes for its
|
|
252
|
+
legacy tool-operation updates, preserves its deterministic UUID mapping, and
|
|
253
|
+
does not rerun when already recorded as complete.
|
|
254
|
+
|
|
234
255
|
### Sync semantics
|
|
235
256
|
|
|
236
257
|
- **Push**: validates ops (including a 256 KB serialized payload ceiling per operation) → checks `op_id` idempotency → allocates contiguous `server_version` values for admitted change-log entries → applies LWW to materialized tables → upserts tombstones for deletes. D1 admission and version allocation share one atomic batch; rejected notification races consume no versions.
|
|
237
|
-
- **Pull**: returns ordered changes for `server_version > cursor` with limit/pagination, optional table filtering, `oldestRetainedVersion
|
|
258
|
+
- **Pull**: returns ordered changes for `server_version > cursor` with limit/pagination, optional table filtering, and `oldestRetainedVersion`. Before reading payloads, a cursor below `max(0, oldestRetainedVersion - 1)` or ahead of the current head receives an empty `requiresSnapshot` response retaining the request cursor. This immediate ahead-of-head check does not detect every database history replacement.
|
|
238
259
|
- **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.
|
|
239
|
-
- **Page size**: pull and snapshot responses target at most 1 MiB of serialized JSON, including the envelope, as well as their row limit. A preliminary size scan limits payloads transferred from the database; the database may still read rows to determine their sizes.
|
|
260
|
+
- **Page size**: pull and snapshot responses target at most 1 MiB of serialized JSON, including the envelope, as well as their row limit. A preliminary size scan limits payloads transferred from the database; the database may still read rows to determine their sizes. Oversized records retain their original bytes in durable evidence and produce unavailable markers within the page bounds. Filtered notifications still advance the pull cursor.
|
|
240
261
|
- **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.
|
|
241
|
-
- **Retention safety**:
|
|
262
|
+
- **Retention safety**: GC is enabled only under the explicit `snapshot-v1` capability. Change-log GC removes only the contiguous version prefix that is both older than retention and acknowledged by every active device, stopping at the first recent or unacknowledged version. It does not certify history already damaged by older GC; that requires a verified recovery boundary.
|
|
242
263
|
- **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.
|
|
264
|
+
- **Numeric limits**: terminal background writes reject exhausted clocks, and all version allocations reject unsafe integers and reserve `Number.MAX_SAFE_INTEGER` for the empty-log retention sentinel, returning `VALIDATION_ERROR` on exhaustion. Rejection rolls back the transaction or D1 batch, preserving materialized rows, logs, counters, and generation receipts.
|
|
243
265
|
- **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.
|
|
244
266
|
|
|
245
267
|
Snapshot continuations are bound to the capturing user and workspace, including
|
|
@@ -378,6 +400,14 @@ Persistent Projects uses this same capability for opaque `or3:project-settings`,
|
|
|
378
400
|
|
|
379
401
|
Explicit ownership requires a live project in the same workspace. A missing or deleted project releases the chat even if a concurrent thread write retained its former pointer; legacy folders do not override that explicit release. Canonical reads leave the persisted pointer untouched.
|
|
380
402
|
|
|
403
|
+
Malformed or oversized
|
|
404
|
+
legacy project membership returns `status: 'scope_incomplete'` rather than
|
|
405
|
+
assuming the chat is unowned. Explicit ownership and independent message reads
|
|
406
|
+
remain usable. Legacy membership reads fetch one size-bounded project payload
|
|
407
|
+
at a time through composite-key seeks; they still scan workspace projects and
|
|
408
|
+
do not claim indexed membership lookup. Deleted message placeholders use their authoritative column
|
|
409
|
+
identity/revision and do not fail a batch of sibling canonical reads.
|
|
410
|
+
|
|
381
411
|
Current hosts refuse server tools and workflows when the reader cannot return
|
|
382
412
|
resolved canonical ownership. Older providers require an upgrade even for chats
|
|
383
413
|
with no explicit project pointer, because legacy folder membership may own them.
|
|
@@ -435,6 +465,16 @@ Migration 030 adds generation records, current-hash heads, and canonical write b
|
|
|
435
465
|
|
|
436
466
|
Migrations 030–032 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
|
|
437
467
|
|
|
468
|
+
Tool-result retention writes deterministic UUID operation IDs so both incremental
|
|
469
|
+
pull and snapshot bootstrap remain valid. Migration 033 repairs legacy
|
|
470
|
+
`background-tool:<sha256>` IDs in the change log, canonical KV, tombstones and
|
|
471
|
+
captured snapshot pages, including embedded payload IDs. It preserves content,
|
|
472
|
+
clocks, server versions and cursors; replay allocates no duplicate versions.
|
|
473
|
+
With the updated host, every nonempty tool result uses immutable KV chunks and
|
|
474
|
+
bounded transcript references instead of consuming the assistant response budget.
|
|
475
|
+
Full results remain available after sync/reload and for model replay. The existing
|
|
476
|
+
256 KiB per-result limit remains in force. D1 background retention remains unsupported.
|
|
477
|
+
|
|
438
478
|
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).
|
|
439
479
|
|
|
440
480
|
Background history admission and finalization failures expose structured codes for validation, authorization, conflicts, and supersession. Transient SQLite failures retain their original errors for retry.
|
|
@@ -469,3 +509,53 @@ before activation.
|
|
|
469
509
|
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.
|
|
470
510
|
|
|
471
511
|
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.
|
|
512
|
+
|
|
513
|
+
### Unavailable sync records (matched host contract v1)
|
|
514
|
+
|
|
515
|
+
This provider requires the host's `shared/sync/prepare-sync-write` contract. New generic and background writes validate their final payload and stamp before database mutation. Native writers use their existing immediate transaction; D1 prepares immutable values before its atomic batch and asserts allocation/repair preconditions inside that batch. Row and log use the same normalized value. Migration 034 retains the original generic intent fingerprint so normalization does not change replay identity; existing 0.0.30 log receipts still compare their original intent. Delete metadata and historical background envelopes keep their exact receipt identity. Legacy messages without order_key validate using the revision HLC without changing their wire payloads. Reader-valid historical payloads may contain older redundant revision fields; reads preserve those bytes and clients install the authoritative envelope revision. New writes still require consistent revision metadata. The existing generic log-GC replay horizon is unchanged.
|
|
516
|
+
|
|
517
|
+
Migration 035 stores original unavailable bytes and metadata independently of logs and snapshots. Pull and snapshot pages classify each record, retain evidence before emitting `unavailable`, and account entries and markers together within the existing 1 MiB/1,000-entry limits. The payload transfer ceiling is 256 KiB per row, including the first row; larger evidence is copied within SQL. Stored revision metadata is measured before transfer and bounded by the 1 MiB page ceiling, including corrupt text in numeric columns; oversized revisions stay in SQL evidence. Backup capture also preserves pre-transformation file bytes for evidence. Unknown notification owners are retained privately and never emitted as keys or markers. Untrustworthy ordering, identities or server versions fail coverage. Storage failures fail the request. The provider advertises `unavailableRecords: 'v1'`; deploy with the matching host's browser capability gate before enabling it for clients.
|
|
518
|
+
|
|
519
|
+
Snapshot ordering and continuation use component-wise UTF-8 BINARY tuples, preserving NUL, supplementary and CJK keys. Native and D1 accept the shared 65,536-character token ceiling. Identifiers that cannot round-trip through UTF-8 are rejected rather than renamed.
|
|
520
|
+
|
|
521
|
+
The existing authorized provider-admin action endpoint supports these workspace-scoped actions:
|
|
522
|
+
|
|
523
|
+
- `sync.evidence-inspect`: `{ after?: string }` uses an indexed workspace/ID continuation to return at most 50 metadata records and a `next` ID. Oversized locator/revision display fields are null; original metadata remains available by export.
|
|
524
|
+
- `sync.evidence-export`: `{ id, offset?: number }` returns original payload and metadata as `payloadHex`/`metadataHex` chunks of 32,768 bytes. Decode hex and concatenate each field separately at offsets 0, 32768, … until `totalBytes` is covered. Oversized originals are never loaded whole into JavaScript.
|
|
525
|
+
- `sync.evidence-revalidate`: `{ id }` checks the retained entry against the current reader contract without mutating its original bytes.
|
|
526
|
+
- `sync.evidence-repair`: `{ id, historyIncarnation, payload, operation?: 'put'|'delete' }` requires an explicit valid replacement. It publishes a fresh UUID, winning clock and server version using the normal writer transaction and atomically records the resolution. Changed canonical revisions are marked superseded; exhausted/untrustworthy clocks require explicit offline recovery, with original evidence retained. Current orphan tombstones can be repaired through the same transaction, with an assertion that no materialized winner appeared concurrently. Repair never replays obsolete evidence over a newer winner.
|
|
527
|
+
|
|
528
|
+
Provider contract regressions run with `bun run test src/runtime/__tests__/sqlite-sync-hardening.test.ts`. Set `OR3_PROJECT_HOST_ROOT` to test live matched host sources with the ordinary provider config. The separate `test:host-integration` lane enforces the release's exact pinned host commit and fixture bytes, recorded in `test/fixtures/host-next.json`; it must be qualified independently. The checked-in `test/fixtures/sync-v1/provenance.json` records the exact reviewed sync-contract bytes used by standalone tests and typechecking.
|
|
529
|
+
|
|
530
|
+
### History incarnation (matched host contract v1)
|
|
531
|
+
|
|
532
|
+
Migration 036 initializes one persisted `sync_history` UUID per database and atomically clears pre-contract snapshot sessions/items and device ACKs. Committed migration retries, normal startup, restart, backup capture and GC preserve that identity. A migrated database with a missing or invalid singleton fails closed and requires offline recovery.
|
|
533
|
+
|
|
534
|
+
The internal `backupSnapshot` API allows server workspace exports to omit the initial incarnation: it discovers history on the first page and binds continuations to the incarnation in that page's token. A stale continuation is rejected after replacement; browser `snapshot` calls still require an explicit incarnation field.
|
|
535
|
+
|
|
536
|
+
A legacy host that omits both incarnation and recognized request capability receives structured HTTP 426 `OR3_SYNC_UPDATE_REQUIRED` from pull/snapshot/push/ACK, before history dispatch. Upgrade the matching host and client together; the provider never substitutes the current history for a legacy write. A capable request missing the required field still returns 400. The old host's empty/all-invalid push shortcut and event transport remain host-owned and cannot provide the complete new protocol; independent provider-only rollout is not qualified.
|
|
537
|
+
|
|
538
|
+
Native SQLite advertises `historyIncarnation: 'v1'`. The matching host requires browser `historyIncarnationCapability: 'incarnation-v1'` on all five HTTP endpoints, including empty pushes and ACKs; older browsers receive 426. Provider requests carry the expected `historyIncarnation` outside operations/fingerprints. Successful pull, snapshot and push responses carry the bound identity; ACK success is assembled by the host after the provider transaction. Push and ACK reject stale/null identity with structured 409 `OR3_SYNC_HISTORY_CHANGED` before receipts, allocation, writes or timestamp refresh, rechecking inside the transaction. Missing/malformed fields return 400. Pull accepts explicit null discovery and returns an empty snapshot-required recovery envelope for null/mismatch before decoding history, regardless of numeric cursor/head. Snapshot permits null only for an initial page; continuations bind identity, and old tokens return 409 even if presented with the new request identity. Same-history absent/expired sessions retain 410. Watcher hints carry `{historyIncarnation, version}` and close on a changed identity before comparing numeric heads.
|
|
539
|
+
|
|
540
|
+
The managed image uses the target-owned `/app/scripts/docker/sync-history-reset.mjs` helper with exact qualified migration history. This is the sole production reset owner; its caller must stop/fence all writers and connections, prevent restart, and durably journal a fresh UUID outside replaced data **before each extraction attempt**. One immediate SQLite transaction replaces the singleton and deletes all snapshot items/headers and device ACKs; verification precedes startup. A stopped-candidate reconciliation may repeat the same UUID; re-extraction, repeated restore, rollback or safety-snapshot restoration needs a new UUID. Never invoke rotation on startup/update/GC. The helper never edits canonical rows, tombstones, log, counters or unavailable evidence; retention remains `MIN(log version)` or `head+1`, without a cross-history floor. The host Cloud CLI owns external journaling, capability preflight, safety backup retention and startup gates.
|
|
541
|
+
|
|
542
|
+
New unavailable evidence deduplicates by `[incarnation, originalRevision]` with provenance in metadata. Legacy evidence remains unknown-origin and exportable. Rotation never resolves evidence. Repair requires both the supplied current identity and the evidence provenance to match; an old reference cannot publish or mark evidence superseded in a new history. D1 implements the runtime fences and passes the SQLite-backed D1 regression lane, but deliberately does **not** advertise history incarnation until its remote/offline lifecycle is separately qualified. Image profile/publication qualification, real managed lifecycle and browser-held-intent acceptance remain integration gates; this source change performs no release or deployment.
|
|
543
|
+
|
|
544
|
+
Run `bun run test src/runtime/__tests__/sqlite-sync-incarnation.test.ts` for provider P0-5 regressions, and the ordinary full suite plus `type-check:host-contract` with `OR3_PROJECT_HOST_ROOT` pointing to the matched host. Standalone sync fixture provenance includes the exact H5 working-tree bytes and hashes; the delegation fixture is refreshed from the release's pinned host commit.
|
|
545
|
+
|
|
546
|
+
### Push stored-record containment (`stored-record-v1`)
|
|
547
|
+
|
|
548
|
+
A matched client advertises `storedRecordCapability: 'stored-record-v1'` on push. An unreadable stored receipt, losing winner, missing replay winner or notification owner yields only that operation's `STORED_RECORD_UNAVAILABLE` failure, with `evidenceRef` and a bounded fixed `error` reason. The matching host must hold the exact intent recoverably, retain its evidence link and settle healthy siblings without retrying or counting an outage. Existing `unavailable-v1` is insufficient: older clients already send it without supporting push holds. An affected batch without the new capability receives structured HTTP 426 `OR3_SYNC_UPDATE_REQUIRED` / `requiredCapability: 'stored-record-v1'`.
|
|
549
|
+
|
|
550
|
+
Stored payload/fingerprint/revision reads are bounded in SQL. Original bad bytes stay in `sync_unavailable_records` independently of source GC; a separate `source='push'` entry retains each rejected intent and its evidence link. Operations rejected during preflight consume no version or receipt. A hold never invents a replacement UUID or reports a successful replay; a D1 fault discovered after its atomic commit retains the uncertain committed intent for recovery. A valid winning write may replace an unreadable older payload only after preserving its original bytes. Database/evidence storage failures remain request failures. Inspect/export uses the existing `sync.evidence-*` admin actions; rejected intent is exportable, and repair must target the original stored evidence rather than replaying an intent entry. The committed sync fixture records the explicit S4 additive contract delta and original source hashes; live-host qualification uses the host's actual shared contract.
|
|
551
|
+
|
|
552
|
+
### Local migration capacity measurement
|
|
553
|
+
|
|
554
|
+
A disposable native SQLite qualification on macOS arm64 used 1,000,000 log rows, 200,000 canonical KV rows and 200,000 snapshot items (256-character values; 1% exact legacy tool IDs). Historical schema structure was independently checked against published 0.0.30 source. Seed WAL was checkpointed; ordinary WAL/autocheckpoint settings were retained. External 5 ms sampling measured each candidate's logical files:
|
|
555
|
+
|
|
556
|
+
| Starting ledger | Pending migrations | Elapsed | Peak WAL | Peak DB + WAL + SHM + journal |
|
|
557
|
+
| --- | --- | ---: | ---: | ---: |
|
|
558
|
+
| 032 | 033–036 | 1.586 s | 180.18 MiB | 1,064.54 MiB |
|
|
559
|
+
| 033 | 034–036 | 0.528 s | 72.44 MiB | 956.80 MiB |
|
|
560
|
+
|
|
561
|
+
Both runs retained every log/canonical row, finished ledger 36 and invalidated the snapshot items. These sampled local measurements do not qualify production hardware, physical allocated space or remote D1 limits; plan additional space for source/rollback backups. Migration 033 preserves malformed payload bytes for subsequent unavailable-record handling and retains its original deterministic UUID mapping and ledger no-rerun behavior.
|
package/dist/module.json
CHANGED
|
@@ -70,6 +70,12 @@ export const sqliteSyncAdminAdapter = {
|
|
|
70
70
|
},
|
|
71
71
|
warnings,
|
|
72
72
|
actions: [
|
|
73
|
+
...["inspect", "export", "revalidate", "repair"].map((action) => ({
|
|
74
|
+
id: `sync.evidence-${action}`,
|
|
75
|
+
label: `${action[0].toUpperCase()}${action.slice(1)} unavailable sync records`,
|
|
76
|
+
description: "Retained original sync evidence; export is chunked and repair requires an explicit replacement.",
|
|
77
|
+
danger: action === "repair"
|
|
78
|
+
})),
|
|
73
79
|
{
|
|
74
80
|
id: "sync.gc-change-log",
|
|
75
81
|
label: "Clear old sync history",
|
|
@@ -92,6 +98,9 @@ export const sqliteSyncAdminAdapter = {
|
|
|
92
98
|
statusMessage: "Workspace not resolved"
|
|
93
99
|
});
|
|
94
100
|
}
|
|
101
|
+
if (actionId.startsWith("sync.evidence-")) {
|
|
102
|
+
return getGateway().maintainUnavailableRecords(event, ctx.session.workspace.id, actionId.slice("sync.evidence-".length), _payload ?? {});
|
|
103
|
+
}
|
|
95
104
|
if (actionId === "sync.gc-change-log" || actionId === "sync.gc-tombstones") {
|
|
96
105
|
if (!canRunSyncHistoryGc()) {
|
|
97
106
|
throw createError({
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { prepareSyncWrite, nextSyncClock } from "~~/shared/sync/prepare-sync-write";
|
|
1
2
|
import { getJobConfig } from "~~/server/utils/background-jobs/store";
|
|
2
3
|
import { getScopedAdmissionKey } from "~~/server/utils/background-jobs/admission-cancels";
|
|
3
4
|
import { buildDelegationResume } from "~~/server/utils/background-jobs/delegation-resume";
|
|
@@ -5,7 +6,7 @@ import { readRequestUsage } from "~~/shared/chat/compaction";
|
|
|
5
6
|
import { DelegationActivitySchema, DelegationDispatchSchema, DelegationWaitSchema } from "~~/shared/chat/delegation-checkpoint";
|
|
6
7
|
import { delegationAdmissionFingerprint, delegationChildIdentities } from "~~/shared/chat/delegation-identities";
|
|
7
8
|
import { toolCallFingerprint } from "~~/shared/chat/tool-ledger";
|
|
8
|
-
import { parseChatGenerationAdmissionEnvelope } from "~~/shared/chat/background-history";
|
|
9
|
+
import { parseChatGenerationAdmissionEnvelope, backgroundHistoryDeviceId } from "~~/shared/chat/background-history";
|
|
9
10
|
import { matchesToolResultStorage } from "~~/shared/chat/tool-result-artifact";
|
|
10
11
|
import { normalizeError, serializeError } from "~~/shared/errors";
|
|
11
12
|
import { randomUUID } from "node:crypto";
|
|
@@ -284,6 +285,22 @@ export class SqliteBackgroundJobProvider {
|
|
|
284
285
|
const id = randomUUID();
|
|
285
286
|
const config = getJobConfig();
|
|
286
287
|
const execution = params.execution;
|
|
288
|
+
if (execution && "history" in execution && execution.history) {
|
|
289
|
+
const history = parseChatGenerationAdmissionEnvelope(execution.history);
|
|
290
|
+
for (const [tableName, row] of [["threads", history.thread], ["messages", history.userMessage], ["messages", history.assistantMessage]]) {
|
|
291
|
+
if (!row) continue;
|
|
292
|
+
nextSyncClock(row.clock);
|
|
293
|
+
const opId = "00000000-0000-4000-8000-000000000000";
|
|
294
|
+
const hlc = typeof row.hlc === "string" ? row.hlc : "background";
|
|
295
|
+
prepareSyncWrite({
|
|
296
|
+
tableName,
|
|
297
|
+
pk: row.id,
|
|
298
|
+
operation: "put",
|
|
299
|
+
payload: { ...row, ...tableName === "messages" && !row.order_key ? { order_key: hlc } : {}, hlc, op_id: opId },
|
|
300
|
+
stamp: { clock: row.clock, hlc, opId, deviceId: backgroundHistoryDeviceId(history.generationId) }
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
}
|
|
287
304
|
if (execution && "delegationWait" in execution) {
|
|
288
305
|
throw new Error("Delegation waits must be parked through the fenced transition");
|
|
289
306
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Kysely, SqliteDialect } from "kysely";
|
|
1
|
+
import { Kysely, SqliteAdapter, SqliteDialect } from "kysely";
|
|
2
2
|
import { D1Dialect } from "./d1-dialect.js";
|
|
3
3
|
let instance = null;
|
|
4
4
|
let rawDb = null;
|
|
@@ -343,6 +343,15 @@ async function resolveD1Database(options) {
|
|
|
343
343
|
function isD1Database(value) {
|
|
344
344
|
return isRecord(value) && typeof value.prepare === "function";
|
|
345
345
|
}
|
|
346
|
+
class NativeSqliteDialect extends SqliteDialect {
|
|
347
|
+
createAdapter() {
|
|
348
|
+
return new class extends SqliteAdapter {
|
|
349
|
+
get supportsTransactionalDdl() {
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
}();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
346
355
|
async function initialize(options) {
|
|
347
356
|
const driver = resolveDriver(options);
|
|
348
357
|
selectedDriver = driver;
|
|
@@ -357,7 +366,7 @@ async function initialize(options) {
|
|
|
357
366
|
rawDb = driver === "bun" ? await createBunSqliteDatabase(path) : driver === "turso" ? await createTursoDatabase(options) : await createBetterSqliteDatabase(path);
|
|
358
367
|
if (driver !== "turso") applyLocalPragmas(rawDb, options);
|
|
359
368
|
instance = new Kysely({
|
|
360
|
-
dialect: new
|
|
369
|
+
dialect: new NativeSqliteDialect({ database: new KyselyDatabaseAdapter(rawDb) })
|
|
361
370
|
});
|
|
362
371
|
return instance;
|
|
363
372
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Migrator } from "kysely";
|
|
1
|
+
import { sql, Migrator } from "kysely";
|
|
2
2
|
import * as m001 from "./migrations/001_init.js";
|
|
3
3
|
import * as m002 from "./migrations/002_sync_tables.js";
|
|
4
4
|
import * as m003 from "./migrations/003_sync_hardening.js";
|
|
@@ -57,6 +57,8 @@ const REQUIRED_SCHEMA_TABLES = [
|
|
|
57
57
|
"storage_object_generations",
|
|
58
58
|
"storage_object_heads",
|
|
59
59
|
"storage_generation_uploads",
|
|
60
|
+
"sync_unavailable_records",
|
|
61
|
+
"sync_history",
|
|
60
62
|
"sync_observations"
|
|
61
63
|
];
|
|
62
64
|
import * as m024 from "./migrations/024_signup_invites.js";
|
|
@@ -68,6 +70,11 @@ import * as m029 from "./migrations/029_delegation_wait.js";
|
|
|
68
70
|
import * as m030 from "./migrations/030_storage_generations.js";
|
|
69
71
|
import * as m031 from "./migrations/031_storage_generation_uploads.js";
|
|
70
72
|
import * as m032 from "./migrations/032_sync_observations.js";
|
|
73
|
+
import * as m033 from "./migrations/033_tool_result_operation_ids.js";
|
|
74
|
+
import * as m034 from "./migrations/034_sync_intent_fingerprint.js";
|
|
75
|
+
import * as m035 from "./migrations/035_sync_unavailable_records.js";
|
|
76
|
+
import * as m036 from "./migrations/036_sync_history_incarnation.js";
|
|
77
|
+
import { readHistoryIncarnation } from "../sync/history-incarnation.js";
|
|
71
78
|
const migrations = {
|
|
72
79
|
"001_init": m001,
|
|
73
80
|
"002_sync_tables": m002,
|
|
@@ -100,7 +107,11 @@ const migrations = {
|
|
|
100
107
|
"029_delegation_wait": m029,
|
|
101
108
|
"030_storage_generations": m030,
|
|
102
109
|
"031_storage_generation_uploads": m031,
|
|
103
|
-
"032_sync_observations": m032
|
|
110
|
+
"032_sync_observations": m032,
|
|
111
|
+
"033_tool_result_operation_ids": m033,
|
|
112
|
+
"034_sync_intent_fingerprint": m034,
|
|
113
|
+
"035_sync_unavailable_records": m035,
|
|
114
|
+
"036_sync_history_incarnation": m036
|
|
104
115
|
};
|
|
105
116
|
class StaticMigrationProvider {
|
|
106
117
|
async getMigrations() {
|
|
@@ -122,6 +133,19 @@ async function assertLatestSchemaIntegrity(db) {
|
|
|
122
133
|
}
|
|
123
134
|
}
|
|
124
135
|
export async function runMigrations(db) {
|
|
136
|
+
const rebuildTables = [
|
|
137
|
+
...["s_threads", "s_messages", "s_projects", "s_posts", "s_kv", "s_file_meta", "s_notifications"].map((table) => `${table}__new`),
|
|
138
|
+
"connect_device_authorizations_legacy",
|
|
139
|
+
"connect_device_authorizations_before_redelivery",
|
|
140
|
+
"connect_device_authorizations_before_lifecycle",
|
|
141
|
+
"connect_environments_before_lifecycle",
|
|
142
|
+
"chat_history_revisions_v2"
|
|
143
|
+
];
|
|
144
|
+
const interrupted = (await sql`SELECT name FROM sqlite_master
|
|
145
|
+
WHERE type = 'table' AND name IN (${sql.join(rebuildTables)})`.execute(db)).rows;
|
|
146
|
+
if (interrupted.length) {
|
|
147
|
+
throw new Error(`Recover interrupted SQLite rebuild before retrying migrations; preserved tables: ${interrupted.map((row) => row.name).join(", ")}`);
|
|
148
|
+
}
|
|
125
149
|
const migrator = new Migrator({
|
|
126
150
|
db,
|
|
127
151
|
provider: new StaticMigrationProvider()
|
|
@@ -141,4 +165,5 @@ export async function runMigrations(db) {
|
|
|
141
165
|
throw error;
|
|
142
166
|
}
|
|
143
167
|
await assertLatestSchemaIntegrity(db);
|
|
168
|
+
await readHistoryIncarnation();
|
|
144
169
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import { type Kysely } from 'kysely';
|
|
2
2
|
/** Resume nontransactional SQLite/D1 DDL without trusting an unrelated schema. */
|
|
3
3
|
export declare function ensureMigrationSchema(db: Kysely<unknown>, statement: string, previousTrigger?: string): Promise<void>;
|
|
4
|
+
/** Historical additive steps may already be durable without a ledger entry. */
|
|
5
|
+
export declare function ensureMigrationTextColumn(db: Kysely<unknown>, table: string, name: string, required?: boolean): Promise<void>;
|
|
@@ -19,3 +19,17 @@ export async function ensureMigrationSchema(db, statement, previousTrigger) {
|
|
|
19
19
|
}
|
|
20
20
|
await sql.raw(statement).execute(db);
|
|
21
21
|
}
|
|
22
|
+
export async function ensureMigrationTextColumn(db, table, name, required = false) {
|
|
23
|
+
const columns = (await sql`
|
|
24
|
+
PRAGMA table_info(${sql.id(table)})
|
|
25
|
+
`.execute(db)).rows;
|
|
26
|
+
if (!columns.length) throw new Error(`Missing migration table: ${table}`);
|
|
27
|
+
const column = columns.find((column2) => column2.name === name);
|
|
28
|
+
if (column) {
|
|
29
|
+
if (column.type.toUpperCase() !== "TEXT" || column.notnull !== Number(required) || column.dflt_value !== (required ? "''" : null) || column.pk !== 0) {
|
|
30
|
+
throw new Error(`Incompatible migration column: ${table}.${name}`);
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
await sql`ALTER TABLE ${sql.id(table)} ADD COLUMN ${sql.id(name)} ${sql.raw(required ? "TEXT NOT NULL DEFAULT ''" : "TEXT")}`.execute(db);
|
|
35
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationSchema, ensureMigrationTextColumn } from "../migration-schema.js";
|
|
2
3
|
const SYNCED_TABLES = [
|
|
3
4
|
["s_threads", "threads"],
|
|
4
5
|
["s_messages", "messages"],
|
|
@@ -10,9 +11,7 @@ const SYNCED_TABLES = [
|
|
|
10
11
|
];
|
|
11
12
|
export async function up(db) {
|
|
12
13
|
for (const [materializedTable, tableName] of SYNCED_TABLES) {
|
|
13
|
-
await
|
|
14
|
-
`ALTER TABLE "${materializedTable}" ADD COLUMN op_id TEXT NOT NULL DEFAULT ''`
|
|
15
|
-
).execute(db);
|
|
14
|
+
await ensureMigrationTextColumn(db, materializedTable, "op_id", true);
|
|
16
15
|
await sql.raw(`
|
|
17
16
|
UPDATE "${materializedTable}" AS materialized
|
|
18
17
|
SET op_id = COALESCE(
|
|
@@ -33,12 +32,8 @@ export async function up(db) {
|
|
|
33
32
|
WHERE materialized.op_id = ''
|
|
34
33
|
`).execute(db);
|
|
35
34
|
}
|
|
36
|
-
await
|
|
37
|
-
|
|
38
|
-
).execute(db);
|
|
39
|
-
await sql.raw(
|
|
40
|
-
`ALTER TABLE tombstones ADD COLUMN op_id TEXT NOT NULL DEFAULT ''`
|
|
41
|
-
).execute(db);
|
|
35
|
+
await ensureMigrationTextColumn(db, "tombstones", "hlc", true);
|
|
36
|
+
await ensureMigrationTextColumn(db, "tombstones", "op_id", true);
|
|
42
37
|
await sql.raw(`
|
|
43
38
|
UPDATE tombstones AS tombstone
|
|
44
39
|
SET
|
|
@@ -70,22 +65,17 @@ export async function up(db) {
|
|
|
70
65
|
)
|
|
71
66
|
WHERE tombstone.hlc = '' OR tombstone.op_id = ''
|
|
72
67
|
`).execute(db);
|
|
73
|
-
await
|
|
74
|
-
CREATE TABLE sync_snapshots (
|
|
68
|
+
await ensureMigrationSchema(db, `CREATE TABLE sync_snapshots (
|
|
75
69
|
id TEXT PRIMARY KEY,
|
|
76
70
|
workspace_id TEXT NOT NULL,
|
|
77
71
|
high_watermark INTEGER NOT NULL,
|
|
78
72
|
tables_json TEXT NOT NULL,
|
|
79
73
|
created_at INTEGER NOT NULL,
|
|
80
74
|
expires_at INTEGER NOT NULL
|
|
81
|
-
)
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
ON sync_snapshots(expires_at)
|
|
86
|
-
`).execute(db);
|
|
87
|
-
await sql.raw(`
|
|
88
|
-
CREATE TABLE sync_snapshot_items (
|
|
75
|
+
)`);
|
|
76
|
+
await ensureMigrationSchema(db, `CREATE INDEX idx_sync_snapshots_expires
|
|
77
|
+
ON sync_snapshots(expires_at)`);
|
|
78
|
+
await ensureMigrationSchema(db, `CREATE TABLE sync_snapshot_items (
|
|
89
79
|
snapshot_id TEXT NOT NULL,
|
|
90
80
|
table_name TEXT NOT NULL,
|
|
91
81
|
pk TEXT NOT NULL,
|
|
@@ -97,8 +87,7 @@ export async function up(db) {
|
|
|
97
87
|
server_deleted_at INTEGER,
|
|
98
88
|
PRIMARY KEY (snapshot_id, table_name, pk, kind),
|
|
99
89
|
FOREIGN KEY (snapshot_id) REFERENCES sync_snapshots(id) ON DELETE CASCADE
|
|
100
|
-
) WITHOUT ROWID
|
|
101
|
-
`).execute(db);
|
|
90
|
+
) WITHOUT ROWID`);
|
|
102
91
|
}
|
|
103
92
|
export async function down(db) {
|
|
104
93
|
await db.schema.dropTable("sync_snapshot_items").ifExists().execute();
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { ensureMigrationTextColumn } from "../migration-schema.js";
|
|
1
2
|
export async function up(db) {
|
|
2
|
-
await db
|
|
3
|
+
await ensureMigrationTextColumn(db, "device_cursors", "owner_user_id");
|
|
3
4
|
}
|
|
4
5
|
export async function down(_db) {
|
|
5
6
|
}
|
|
@@ -1,21 +1,10 @@
|
|
|
1
1
|
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationTextColumn } from "../migration-schema.js";
|
|
2
3
|
export async function up(db) {
|
|
3
|
-
await
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
await sql`
|
|
8
|
-
ALTER TABLE background_jobs
|
|
9
|
-
ADD COLUMN generation_id TEXT
|
|
10
|
-
`.execute(db);
|
|
11
|
-
await sql`
|
|
12
|
-
ALTER TABLE background_jobs
|
|
13
|
-
ADD COLUMN history_phase TEXT
|
|
14
|
-
`.execute(db);
|
|
15
|
-
await sql`
|
|
16
|
-
ALTER TABLE background_jobs
|
|
17
|
-
ADD COLUMN sync_provider_id TEXT
|
|
18
|
-
`.execute(db);
|
|
4
|
+
await ensureMigrationTextColumn(db, "background_jobs", "reasoning", true);
|
|
5
|
+
for (const column of ["generation_id", "history_phase", "sync_provider_id"]) {
|
|
6
|
+
await ensureMigrationTextColumn(db, "background_jobs", column);
|
|
7
|
+
}
|
|
19
8
|
}
|
|
20
9
|
export async function down(db) {
|
|
21
10
|
await sql`ALTER TABLE background_jobs DROP COLUMN sync_provider_id`.execute(db);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationTextColumn } from "../migration-schema.js";
|
|
2
3
|
export async function up(db) {
|
|
3
|
-
await
|
|
4
|
+
await ensureMigrationTextColumn(db, "background_jobs", "usage_json");
|
|
4
5
|
}
|
|
5
6
|
export async function down(db) {
|
|
6
7
|
await sql`ALTER TABLE background_jobs DROP COLUMN usage_json`.execute(db);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationSchema } from "../migration-schema.js";
|
|
3
|
+
import { digestUuid } from "../../utils/digest-uuid.js";
|
|
4
|
+
export async function up(db) {
|
|
5
|
+
const tables = [
|
|
6
|
+
["change_log", "payload_json"],
|
|
7
|
+
["s_kv", "data_json"],
|
|
8
|
+
["sync_snapshot_items", "payload_json"],
|
|
9
|
+
["tombstones", null]
|
|
10
|
+
];
|
|
11
|
+
for (const [table, payload] of tables) {
|
|
12
|
+
const repairIndex = table === "change_log" ? null : `or3_033_${table}_op_id`;
|
|
13
|
+
if (repairIndex) await ensureMigrationSchema(db, `CREATE INDEX ${repairIndex} ON ${table} (op_id)`);
|
|
14
|
+
let after = "";
|
|
15
|
+
for (; ; ) {
|
|
16
|
+
const { rows } = await sql`SELECT DISTINCT op_id FROM ${sql.table(table)}
|
|
17
|
+
WHERE op_id LIKE 'background-tool:%' AND op_id > ${after} ORDER BY op_id LIMIT 500`.execute(db);
|
|
18
|
+
if (!rows.length) break;
|
|
19
|
+
for (const { op_id: oldId } of rows) {
|
|
20
|
+
const match = /^background-tool:([a-f0-9]{64})$/.exec(oldId);
|
|
21
|
+
if (!match) continue;
|
|
22
|
+
const opId = digestUuid(match[1]);
|
|
23
|
+
const assignment = payload ? sql`, ${sql.ref(payload)} = CASE WHEN json_valid(${sql.ref(payload)}) THEN
|
|
24
|
+
CASE WHEN json_extract(${sql.ref(payload)}, '$.op_id') = ${oldId}
|
|
25
|
+
THEN json_set(${sql.ref(payload)}, '$.op_id', ${opId}) ELSE ${sql.ref(payload)} END
|
|
26
|
+
ELSE ${sql.ref(payload)} END` : sql``;
|
|
27
|
+
await sql`UPDATE ${sql.table(table)} SET op_id = ${opId}${assignment} WHERE op_id = ${oldId}`.execute(db);
|
|
28
|
+
}
|
|
29
|
+
after = rows.at(-1).op_id;
|
|
30
|
+
}
|
|
31
|
+
if (repairIndex) await sql`DROP INDEX ${sql.id(repairIndex)}`.execute(db);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export async function down(_db) {
|
|
35
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationTextColumn } from "../migration-schema.js";
|
|
3
|
+
export async function up(db) {
|
|
4
|
+
await ensureMigrationTextColumn(db, "change_log", "intent_fingerprint");
|
|
5
|
+
}
|
|
6
|
+
export async function down(db) {
|
|
7
|
+
await sql`ALTER TABLE change_log DROP COLUMN intent_fingerprint`.execute(db);
|
|
8
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationSchema, ensureMigrationTextColumn } from "../migration-schema.js";
|
|
3
|
+
export async function up(db) {
|
|
4
|
+
await ensureMigrationTextColumn(db, "sync_snapshot_items", "source_payload_json");
|
|
5
|
+
await ensureMigrationSchema(db, `CREATE TABLE sync_unavailable_records (
|
|
6
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
7
|
+
workspace_id TEXT NOT NULL,
|
|
8
|
+
source TEXT NOT NULL,
|
|
9
|
+
locator TEXT NOT NULL,
|
|
10
|
+
revision TEXT NOT NULL,
|
|
11
|
+
payload_json TEXT,
|
|
12
|
+
metadata_json TEXT NOT NULL,
|
|
13
|
+
reason TEXT NOT NULL,
|
|
14
|
+
status TEXT NOT NULL,
|
|
15
|
+
created_at INTEGER NOT NULL,
|
|
16
|
+
resolved_op_id TEXT,
|
|
17
|
+
UNIQUE (workspace_id, source, locator, revision)
|
|
18
|
+
)`);
|
|
19
|
+
await ensureMigrationSchema(db, "CREATE INDEX idx_sync_unavailable_workspace ON sync_unavailable_records (workspace_id, id)");
|
|
20
|
+
}
|
|
21
|
+
export async function down(db) {
|
|
22
|
+
await sql`DROP TABLE sync_unavailable_records`.execute(db);
|
|
23
|
+
await sql`ALTER TABLE sync_snapshot_items DROP COLUMN source_payload_json`.execute(db);
|
|
24
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { sql, CompiledQuery } from "kysely";
|
|
3
|
+
import { isD1Driver } from "../kysely.js";
|
|
4
|
+
import { ensureMigrationSchema } from "../migration-schema.js";
|
|
5
|
+
import { historyBatch, readHistoryIncarnation } from "../../sync/history-incarnation.js";
|
|
6
|
+
export async function up(db) {
|
|
7
|
+
await ensureMigrationSchema(db, "CREATE TABLE sync_history (id INTEGER PRIMARY KEY CHECK(id = 1), incarnation TEXT NOT NULL)");
|
|
8
|
+
const statements = [
|
|
9
|
+
{ sql: "DELETE FROM sync_snapshot_items WHERE NOT EXISTS (SELECT 1 FROM sync_history)" },
|
|
10
|
+
{ sql: "DELETE FROM sync_snapshots WHERE NOT EXISTS (SELECT 1 FROM sync_history)" },
|
|
11
|
+
{ sql: "DELETE FROM device_cursors WHERE NOT EXISTS (SELECT 1 FROM sync_history)" },
|
|
12
|
+
{ sql: "INSERT INTO sync_history (id,incarnation) SELECT 1,? WHERE NOT EXISTS (SELECT 1 FROM sync_history)", parameters: [randomUUID()] }
|
|
13
|
+
];
|
|
14
|
+
if (isD1Driver()) await historyBatch(statements);
|
|
15
|
+
else {
|
|
16
|
+
const initialize = async (transaction) => {
|
|
17
|
+
for (const statement of statements) {
|
|
18
|
+
await transaction.executeQuery(CompiledQuery.raw(statement.sql, statement.parameters ?? []));
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
if (db.isTransaction) await initialize(db);
|
|
22
|
+
else await db.transaction().execute(initialize);
|
|
23
|
+
}
|
|
24
|
+
await readHistoryIncarnation();
|
|
25
|
+
}
|
|
26
|
+
export async function down(db) {
|
|
27
|
+
await sql`DROP TABLE sync_history`.execute(db);
|
|
28
|
+
}
|
|
@@ -69,6 +69,7 @@ export interface ServerVersionCounterTable {
|
|
|
69
69
|
value: Generated<number>;
|
|
70
70
|
}
|
|
71
71
|
export interface ChangeLogTable {
|
|
72
|
+
intent_fingerprint: Generated<string | null>;
|
|
72
73
|
id: string;
|
|
73
74
|
workspace_id: string;
|
|
74
75
|
server_version: number;
|
|
@@ -256,6 +257,10 @@ export interface AdminWorkspaceSettingsTable {
|
|
|
256
257
|
updated_at: number;
|
|
257
258
|
}
|
|
258
259
|
export interface Or3SqliteDb {
|
|
260
|
+
sync_history: {
|
|
261
|
+
id: number;
|
|
262
|
+
incarnation: string;
|
|
263
|
+
};
|
|
259
264
|
users: UsersTable;
|
|
260
265
|
auth_accounts: AuthAccountsTable;
|
|
261
266
|
workspaces: WorkspacesTable;
|
|
@@ -2,5 +2,5 @@ import type { getRawDb } from '../db/kysely.js';
|
|
|
2
2
|
/** Resolve explicit and legacy chat ownership inside the caller's SQLite snapshot. */
|
|
3
3
|
export declare function resolveCanonicalProjectOwnership(raw: ReturnType<typeof getRawDb>, workspaceId: string, threadId: string, explicitOwner: unknown): {
|
|
4
4
|
projectId: string | null;
|
|
5
|
-
status: 'resolved' | 'conflict';
|
|
5
|
+
status: 'resolved' | 'conflict' | 'unresolved';
|
|
6
6
|
};
|