@tangle-network/agent-app 0.61.4 → 0.62.0
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/dist/{DesignCanvas-L6J72JQ2.js → DesignCanvas-IQKYAEC4.js} +3 -2
- package/dist/{DesignCanvasEditor-QFQD63MR.js → DesignCanvasEditor-O7OCZTGC.js} +5 -4
- package/dist/{TimelineEditor-7KBPJQLT.js → TimelineEditor-VB2UJ34D.js} +4 -2
- package/dist/VaultPane-AYW7CO33.js +8 -0
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +0 -82
- package/dist/agent-profiles/index.js +1 -21
- package/dist/agent-profiles/self-management.d.ts +0 -55
- package/dist/alerting/index.d.ts +1 -1
- package/dist/alerting/index.js +1 -3
- package/dist/alerting/slack.d.ts +6 -79
- package/dist/app-auth/drizzle.d.ts +17 -271
- package/dist/app-auth/drizzle.js +6 -2
- package/dist/app-auth/drizzle.js.map +1 -1
- package/dist/app-auth/index.js +3 -3
- package/dist/assets/types.d.ts +2 -1
- package/dist/assistant/AssistantPanel.d.ts +1 -1
- package/dist/assistant/index.js +635 -392
- package/dist/assistant/index.js.map +1 -1
- package/dist/billing/identity-locks.d.ts +5 -0
- package/dist/billing/index.js +1 -1
- package/dist/brand-extraction/index.js.map +1 -1
- package/dist/brand-extraction/types.d.ts +2 -1
- package/dist/chat-react/index.js +6 -5
- package/dist/chat-routes/attachment-write-safety.d.ts +4 -0
- package/dist/chat-routes/draft-persistence.d.ts +2 -14
- package/dist/chat-routes/index.d.ts +1 -0
- package/dist/chat-routes/index.js +853 -773
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/sandbox-model-source.d.ts +20 -0
- package/dist/chat-routes/stored-attachments.d.ts +18 -0
- package/dist/chat-routes/turn-admission.d.ts +1 -1
- package/dist/chat-routes/turn-execution.d.ts +2 -2
- package/dist/chat-routes/turn-route-contracts.d.ts +3 -29
- package/dist/chat-store/core.d.ts +19 -1
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/store.d.ts +3 -29
- package/dist/{chunk-ATQQCG4I.js → chunk-2VJLLRVV.js} +2 -2
- package/dist/{chunk-R4X5474U.js → chunk-52SDU43B.js} +12 -27
- package/dist/chunk-52SDU43B.js.map +1 -0
- package/dist/{chunk-MDRH3SDA.js → chunk-54YIL7WM.js} +3 -3
- package/dist/{chunk-6QJ3GB3A.js → chunk-5GSZGTPJ.js} +2 -2
- package/dist/{chunk-5IM2CLYX.js → chunk-6JEDSKFH.js} +232 -218
- package/dist/chunk-6JEDSKFH.js.map +1 -0
- package/dist/{chunk-6PRQ45QE.js → chunk-6OG4244Y.js} +1 -1
- package/dist/chunk-6OG4244Y.js.map +1 -0
- package/dist/{chunk-ZDPUC6CM.js → chunk-6ZVSMA4T.js} +3 -3
- package/dist/{chunk-TXUAGSFR.js → chunk-76MPX7JQ.js} +47 -1
- package/dist/chunk-76MPX7JQ.js.map +1 -0
- package/dist/{chunk-BOQ4HVVH.js → chunk-7ISHKBAD.js} +61 -52
- package/dist/chunk-7ISHKBAD.js.map +1 -0
- package/dist/chunk-7PULOECS.js +22 -0
- package/dist/chunk-7PULOECS.js.map +1 -0
- package/dist/{chunk-KJODHPWM.js → chunk-CPVGRQ43.js} +511 -339
- package/dist/chunk-CPVGRQ43.js.map +1 -0
- package/dist/{chunk-LO6VQ35O.js → chunk-CQZVJVME.js} +2 -2
- package/dist/{chunk-Y43PXON2.js → chunk-EFQUAWWF.js} +577 -546
- package/dist/chunk-EFQUAWWF.js.map +1 -0
- package/dist/{chunk-FPNZMIAW.js → chunk-ELX5YITO.js} +1 -1
- package/dist/chunk-ELX5YITO.js.map +1 -0
- package/dist/chunk-FGAROAUF.js +19 -0
- package/dist/chunk-FGAROAUF.js.map +1 -0
- package/dist/{chunk-HN6MZ2XL.js → chunk-FTNGGR37.js} +641 -466
- package/dist/chunk-FTNGGR37.js.map +1 -0
- package/dist/{chunk-G4F2NWZH.js → chunk-FZ3ZFVAC.js} +4 -4
- package/dist/{chunk-UCCSJX64.js → chunk-GIEUZBQQ.js} +1112 -644
- package/dist/chunk-GIEUZBQQ.js.map +1 -0
- package/dist/{chunk-MEKOWH5E.js → chunk-IVBREL7A.js} +785 -526
- package/dist/chunk-IVBREL7A.js.map +1 -0
- package/dist/{chunk-WSEXFTN4.js → chunk-JBXNU5WD.js} +26 -26
- package/dist/chunk-JBXNU5WD.js.map +1 -0
- package/dist/{chunk-F2VX6TTJ.js → chunk-JRCZHDRG.js} +2 -41
- package/dist/chunk-JRCZHDRG.js.map +1 -0
- package/dist/{chunk-LXYQOOXU.js → chunk-JRW6LCIA.js} +552 -302
- package/dist/chunk-JRW6LCIA.js.map +1 -0
- package/dist/{chunk-TVPH5T4F.js → chunk-KS4I7KVC.js} +16 -22
- package/dist/{chunk-TVPH5T4F.js.map → chunk-KS4I7KVC.js.map} +1 -1
- package/dist/{chunk-J2BBYVGF.js → chunk-MRZP65DZ.js} +1 -117
- package/dist/chunk-MRZP65DZ.js.map +1 -0
- package/dist/{chunk-4ZSLX3LY.js → chunk-OODZCBSM.js} +1 -1
- package/dist/chunk-OODZCBSM.js.map +1 -0
- package/dist/chunk-P4RRC4AO.js +47 -0
- package/dist/chunk-P4RRC4AO.js.map +1 -0
- package/dist/{chunk-ORQD4AUO.js → chunk-PCAY23GS.js} +1 -6
- package/dist/chunk-PCAY23GS.js.map +1 -0
- package/dist/{chunk-NMZUW6VJ.js → chunk-PEJ5OP5B.js} +3 -3
- package/dist/chunk-PEJ5OP5B.js.map +1 -0
- package/dist/{chunk-NHYRIM4I.js → chunk-PIPNDZ6H.js} +304 -194
- package/dist/chunk-PIPNDZ6H.js.map +1 -0
- package/dist/{chunk-L7LQRJGD.js → chunk-TCJ4TMOW.js} +37 -33
- package/dist/{chunk-L7LQRJGD.js.map → chunk-TCJ4TMOW.js.map} +1 -1
- package/dist/chunk-UHSUY6H6.js +79 -0
- package/dist/chunk-UHSUY6H6.js.map +1 -0
- package/dist/{chunk-PDD5A43Y.js → chunk-UTL6TEN6.js} +3 -3
- package/dist/{chunk-VJBFCNAU.js → chunk-UW2DKTEM.js} +123 -130
- package/dist/chunk-UW2DKTEM.js.map +1 -0
- package/dist/{chunk-S27DKRI6.js → chunk-VDYEVCQQ.js} +2 -2
- package/dist/{chunk-UFQM46NV.js → chunk-VK3F4N4U.js} +2 -2
- package/dist/{chunk-6ZIC6OG5.js → chunk-VYBTQK25.js} +126 -122
- package/dist/chunk-VYBTQK25.js.map +1 -0
- package/dist/{chunk-RL3Z747H.js → chunk-W2BV2XOC.js} +1491 -700
- package/dist/chunk-W2BV2XOC.js.map +1 -0
- package/dist/{chunk-FUZETA6Z.js → chunk-X6SZGQTK.js} +2 -2
- package/dist/{chunk-CD2LQXY6.js → chunk-XOHE6SKU.js} +14 -16
- package/dist/{chunk-CD2LQXY6.js.map → chunk-XOHE6SKU.js.map} +1 -1
- package/dist/{chunk-ZBB5KQ6B.js → chunk-Y3GO6SG3.js} +73 -66
- package/dist/chunk-Y3GO6SG3.js.map +1 -0
- package/dist/chunk-ZAMHLXNS.js +56 -0
- package/dist/chunk-ZAMHLXNS.js.map +1 -0
- package/dist/{chunk-RHFN7TUV.js → chunk-ZDHCV462.js} +47 -44
- package/dist/{chunk-RHFN7TUV.js.map → chunk-ZDHCV462.js.map} +1 -1
- package/dist/chunk-ZOS3D26Z.js +72 -0
- package/dist/chunk-ZOS3D26Z.js.map +1 -0
- package/dist/design-canvas/index.js +32 -32
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/components/DesignCanvas.d.ts +1 -1
- package/dist/design-canvas-react/components/Workspace.d.ts +1 -1
- package/dist/design-canvas-react/components/glyphs.d.ts +31 -40
- package/dist/design-canvas-react/components/transform-math.d.ts +0 -8
- package/dist/design-canvas-react/components/use-workspace-keyboard.d.ts +2 -2
- package/dist/design-canvas-react/contracts.d.ts +2 -2
- package/dist/design-canvas-react/engine.js +1 -1
- package/dist/design-canvas-react/index.js +9 -7
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/eval/calibration.d.ts +1 -38
- package/dist/eval/index.d.ts +2 -4
- package/dist/eval/index.js +0 -84
- package/dist/eval/index.js.map +1 -1
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/harness/session-selection.d.ts +2 -2
- package/dist/hub-approvals/index.js +1 -1
- package/dist/hub-approvals/result.d.ts +1 -1
- package/dist/hub-approvals-react/index.js +4 -4
- package/dist/hub-approvals-react/index.js.map +1 -1
- package/dist/hub-approvals-react/parts.d.ts +1 -1
- package/dist/launch-invariants/cli.js +4 -4
- package/dist/launch-invariants/index.js +3 -3
- package/dist/launch-invariants/testing.js +4 -4
- package/dist/legibility/cli.js +1 -1
- package/dist/legibility/index.js +1 -1
- package/dist/{mention-editor-B23OMFT2.js → mention-editor-4BKBMWIK.js} +83 -57
- package/dist/mention-editor-4BKBMWIK.js.map +1 -0
- package/dist/missions/index.js +144 -137
- package/dist/missions/index.js.map +1 -1
- package/dist/operator/index.js +1 -1
- package/dist/peer-floors/check.js +1 -1
- package/dist/peer-floors/cli.js +6 -14
- package/dist/peer-floors/cli.js.map +1 -1
- package/dist/peer-floors/source-entries.d.ts +6 -0
- package/dist/platform/index.js +10 -10
- package/dist/preset-cloudflare/index.js +1 -1
- package/dist/profile/index.d.ts +0 -1
- package/dist/profile/index.js +1 -422
- package/dist/profile/index.js.map +1 -1
- package/dist/profile-editor/server.d.ts +0 -1
- package/dist/profile-editor/server.js +0 -1
- package/dist/profile-editor/server.js.map +1 -1
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +6 -6
- package/dist/record/drizzle.js +156 -148
- package/dist/record/drizzle.js.map +1 -1
- package/dist/runtime/index.js +4 -4
- package/dist/runtime/router-turn.js +3 -3
- package/dist/sandbox/index.js +5 -5
- package/dist/sequences/drizzle.js +5 -15
- package/dist/sequences/drizzle.js.map +1 -1
- package/dist/sequences/index.d.ts +1 -0
- package/dist/sequences/index.js +18 -14
- package/dist/sequences/index.js.map +1 -1
- package/dist/sequences/row-mapping.d.ts +7 -0
- package/dist/sequences-react/components/TimelineEditor.d.ts +0 -40
- package/dist/sequences-react/components/TimelineHistory.d.ts +31 -0
- package/dist/sequences-react/components/glyphs.d.ts +12 -21
- package/dist/sequences-react/components/index.d.ts +0 -2
- package/dist/sequences-react/components/interaction-math.d.ts +3 -3
- package/dist/sequences-react/contracts.d.ts +1 -1
- package/dist/sequences-react/engine/snap.d.ts +2 -2
- package/dist/sequences-react/index.js +4 -4
- package/dist/sequences-react/index.js.map +1 -1
- package/dist/settings-react/index.js +13 -30
- package/dist/settings-react/index.js.map +1 -1
- package/dist/settings-react/timezone-picker.d.ts +0 -6
- package/dist/signoff/browser-budget.d.ts +6 -1
- package/dist/signoff/cli.d.ts +0 -7
- package/dist/signoff/cli.js +1 -2
- package/dist/signoff/cli.js.map +1 -1
- package/dist/signoff/index.js +1 -1
- package/dist/skills/index.d.ts +1 -1
- package/dist/skills/index.js +5 -25
- package/dist/skills/marketplace.d.ts +1 -75
- package/dist/skills-placement/box.js +3 -4
- package/dist/skills-placement/box.js.map +1 -1
- package/dist/skills-placement/index.js +3 -4
- package/dist/spend/cli-args.d.ts +1 -1
- package/dist/spend/cli.js +3 -3
- package/dist/spend/cli.js.map +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/stories/design-canvas/fixtures.d.ts +1 -14
- package/dist/stream/index.js +17 -17
- package/dist/studio/generation.d.ts +1 -1
- package/dist/studio/index.js +1 -1
- package/dist/studio-react/index.js +353 -184
- package/dist/studio-react/index.js.map +1 -1
- package/dist/studio-react/studio-composer.d.ts +1 -5
- package/dist/studio-react/studio-history-screen.d.ts +1 -1
- package/dist/teams/invitations-api.d.ts +3 -3
- package/dist/teams/invitations-api.js +74 -72
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/teams/member-sync.d.ts +2 -0
- package/dist/teams/members-api.d.ts +2 -2
- package/dist/teams/members-api.js +1 -1
- package/dist/teams-react/index.js +28 -45
- package/dist/teams-react/index.js.map +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/mcp-arguments.d.ts +1 -1
- package/dist/trace/index.d.ts +1 -18
- package/dist/trace/index.js +1 -36
- package/dist/trace/index.js.map +1 -1
- package/dist/trace/mission-flow.d.ts +1 -59
- package/dist/turn-health/index.d.ts +1 -1
- package/dist/turn-health/index.js +2 -2
- package/dist/turn-health/sink.d.ts +2 -1
- package/dist/turn-trace/index.js +2 -4
- package/dist/turn-trace/recorder.d.ts +0 -2
- package/dist/vault/VaultPane.d.ts +0 -20
- package/dist/vault/VaultPaneOperations.d.ts +318 -0
- package/dist/vault/index.js +2 -1
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/lazy.js +1 -1
- package/dist/web-react/agent-profile-editor.d.ts +1 -2
- package/dist/web-react/agent-profile-editor.js +6 -5
- package/dist/web-react/chat-composer.d.ts +1 -1
- package/dist/web-react/durable-plan-flow.d.ts +6 -1
- package/dist/web-react/editor-glyphs.d.ts +12 -0
- package/dist/web-react/focus-navigation.d.ts +12 -0
- package/dist/web-react/history-controls.d.ts +37 -0
- package/dist/web-react/index.js +36 -34
- package/dist/web-react/interaction-question-card.d.ts +1 -1
- package/dist/web-react/record-grid-writes.d.ts +31 -0
- package/dist/web-react/record-grid.d.ts +1 -48
- package/dist/web-react/session-history-panel.d.ts +1 -9
- package/dist/web-react/use-document-dark.d.ts +1 -0
- package/dist/workspace-export/engine.d.ts +1 -6
- package/dist/workspace-export/index.js +198 -185
- package/dist/workspace-export/index.js.map +1 -1
- package/dist/workspace-export/routes.d.ts +1 -1
- package/dist/workspace-react/index.js +9 -8
- package/dist/workspace-react/index.js.map +1 -1
- package/package.json +1 -11
- package/dist/VaultPane-RXL3WLA2.js +0 -7
- package/dist/agent-profiles/reaper.d.ts +0 -31
- package/dist/agent-profiles/reaper.js +0 -29
- package/dist/agent-profiles/reaper.js.map +0 -1
- package/dist/chunk-4ZSLX3LY.js.map +0 -1
- package/dist/chunk-5IM2CLYX.js.map +0 -1
- package/dist/chunk-6OSJNJA2.js +0 -251
- package/dist/chunk-6OSJNJA2.js.map +0 -1
- package/dist/chunk-6PRQ45QE.js.map +0 -1
- package/dist/chunk-6ZIC6OG5.js.map +0 -1
- package/dist/chunk-BDEBQ4WO.js +0 -38
- package/dist/chunk-BDEBQ4WO.js.map +0 -1
- package/dist/chunk-BOQ4HVVH.js.map +0 -1
- package/dist/chunk-F2VX6TTJ.js.map +0 -1
- package/dist/chunk-FPNZMIAW.js.map +0 -1
- package/dist/chunk-HN6MZ2XL.js.map +0 -1
- package/dist/chunk-J2BBYVGF.js.map +0 -1
- package/dist/chunk-KJODHPWM.js.map +0 -1
- package/dist/chunk-LTWJYNEC.js +0 -100
- package/dist/chunk-LTWJYNEC.js.map +0 -1
- package/dist/chunk-LXYQOOXU.js.map +0 -1
- package/dist/chunk-MEKOWH5E.js.map +0 -1
- package/dist/chunk-NHYRIM4I.js.map +0 -1
- package/dist/chunk-NMZUW6VJ.js.map +0 -1
- package/dist/chunk-ORQD4AUO.js.map +0 -1
- package/dist/chunk-R4X5474U.js.map +0 -1
- package/dist/chunk-RL3Z747H.js.map +0 -1
- package/dist/chunk-TXUAGSFR.js.map +0 -1
- package/dist/chunk-UCCSJX64.js.map +0 -1
- package/dist/chunk-VJBFCNAU.js.map +0 -1
- package/dist/chunk-WSEXFTN4.js.map +0 -1
- package/dist/chunk-Y43PXON2.js.map +0 -1
- package/dist/chunk-ZBB5KQ6B.js.map +0 -1
- package/dist/eval/parity.d.ts +0 -74
- package/dist/mention-editor-B23OMFT2.js.map +0 -1
- package/dist/profile/humanizer-skill.d.ts +0 -23
- package/dist/profile/humanizer-skill.vendored.d.ts +0 -4
- package/dist/sequences-react/components/BrandMark.d.ts +0 -10
- package/dist/skills/marketplace-drizzle.d.ts +0 -121
- package/dist/skills/marketplace-drizzle.js +0 -34
- package/dist/skills/marketplace-drizzle.js.map +0 -1
- package/dist/teams-react/components/BrandMark.d.ts +0 -10
- /package/dist/{DesignCanvas-L6J72JQ2.js.map → DesignCanvas-IQKYAEC4.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-QFQD63MR.js.map → DesignCanvasEditor-O7OCZTGC.js.map} +0 -0
- /package/dist/{TimelineEditor-7KBPJQLT.js.map → TimelineEditor-VB2UJ34D.js.map} +0 -0
- /package/dist/{VaultPane-RXL3WLA2.js.map → VaultPane-AYW7CO33.js.map} +0 -0
- /package/dist/{chunk-ATQQCG4I.js.map → chunk-2VJLLRVV.js.map} +0 -0
- /package/dist/{chunk-MDRH3SDA.js.map → chunk-54YIL7WM.js.map} +0 -0
- /package/dist/{chunk-6QJ3GB3A.js.map → chunk-5GSZGTPJ.js.map} +0 -0
- /package/dist/{chunk-ZDPUC6CM.js.map → chunk-6ZVSMA4T.js.map} +0 -0
- /package/dist/{chunk-LO6VQ35O.js.map → chunk-CQZVJVME.js.map} +0 -0
- /package/dist/{chunk-G4F2NWZH.js.map → chunk-FZ3ZFVAC.js.map} +0 -0
- /package/dist/{chunk-PDD5A43Y.js.map → chunk-UTL6TEN6.js.map} +0 -0
- /package/dist/{chunk-S27DKRI6.js.map → chunk-VDYEVCQQ.js.map} +0 -0
- /package/dist/{chunk-UFQM46NV.js.map → chunk-VK3F4N4U.js.map} +0 -0
- /package/dist/{chunk-FUZETA6Z.js.map → chunk-X6SZGQTK.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/record/drizzle/schema.ts","../../src/record/drizzle/store.ts"],"sourcesContent":["/**\n * Drizzle table factory for a record-entry table. The product owns its\n * scope (workspace / tenant / account) table; this factory creates the entry\n * table and wires the foreign key into it, so the whole graph lives in one\n * drizzle schema with real cascade semantics.\n *\n * The table NAME is a parameter, so one product can host several independent\n * record tables (different domains, different schema maps) side by side.\n *\n * Three storage invariants are encoded here, and the store depends on all\n * three:\n *\n * 1. **Every key column is NOT NULL with a sentinel.** SQLite treats NULLs as\n * distinct inside a unique index, so a nullable `item_key` or `dimension`\n * would let two live heads coexist on one logical key and the partial\n * unique index below would silently stop enforcing anything. `''` and `0`\n * are the sentinels; see `RECORD_KEY_SENTINEL` / `RECORD_PERIOD_SENTINEL`.\n * 2. **The live head is unique per key.** The partial unique index covers only\n * rows that are `accepted` and not superseded, which is exactly the set the\n * materializer reads. Two writers racing for the same head make the second\n * one fail loudly instead of both landing.\n * 3. **Ordering is `seq`, never a timestamp.** `created_at` is epoch\n * milliseconds and is display-only. `(scope_id, seq)` is unique, so the\n * fold has a total order even for rows written in the same millisecond.\n *\n * `superseded_by_id` deliberately carries NO foreign key: the supersede batch\n * stamps the replacement's id onto the outgoing head BEFORE inserting the\n * replacement row, and SQLite cannot defer the constraint check to allow that\n * order. Rows are append-only and cascade with their scope, so the link cannot\n * dangle.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, SQLiteColumnBuilderBase } from 'drizzle-orm/sqlite-core'\nimport type { RecordReviewState, RecordSourceLocator } from '../model'\n\n/** A product table referenced by foreign key — only its `id` column is used. */\nexport type RecordParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/**\n * Product columns added to the entry table, keyed by the property name the\n * store and the product read them under. Ordinary drizzle column builders, so\n * a product declares foreign keys, defaults and null-ability exactly as it\n * would in its own schema.\n */\nexport type RecordExtraColumns = Readonly<Record<string, SQLiteColumnBuilderBase>>\n\n/** Options for {@link createRecordTable}. */\nexport interface CreateRecordTableOptions {\n /**\n * SQL table name, chosen by the product. Also the default prefix for the\n * index names, so two record tables in one schema never collide.\n */\n tableName: string\n /**\n * The tenant table entries belong to. Rows cascade with it — deleting a\n * workspace deletes its record.\n */\n scopeTable: RecordParentTable\n /**\n * Optional table `source_ref` points at (a documents table, a source-record\n * table). Wire it ONLY when every source kind's ref points at this one\n * table; a product whose refs are heterogeneous (a document id for one kind,\n * a message id for another) leaves it off and keeps `source_ref` plain text.\n * When wired, deleting the source sets the ref null and leaves the entry\n * with its quote and locator intact.\n */\n sourceTable?: RecordParentTable\n /** Optional table `reviewed_by` points at (a users table). */\n reviewerTable?: RecordParentTable\n /** Index-name prefix. Defaults to {@link tableName}. */\n indexPrefix?: string\n /**\n * Product columns merged into the table, the `/missions` store-port pattern.\n *\n * The built-in `source_ref` is ONE column, which is right for a store whose\n * refs all point at one table and wrong for one whose kinds cite different\n * things — a chat-sourced row citing a message and a document-sourced row\n * citing a document each want their own foreign key with their own\n * `ON DELETE` behaviour. Declare them here, require them per source kind\n * through `policy.requireExtras`, and pass their values on `write`; the\n * store carries them and reads none of them.\n *\n * A key that collides with a built-in column is refused at construction —\n * silently shadowing `path` or `review_state` would break every invariant\n * the store rests on.\n */\n extraColumns?: RecordExtraColumns\n}\n\n/** Column property names the store owns. An extra column may not take one, and\n * neither may an `extras` value on a write — shadowing `path` or\n * `review_state` would break every invariant this table encodes. */\nexport const RECORD_STORE_COLUMNS: ReadonlySet<string> = new Set([\n 'id',\n 'scopeId',\n 'seq',\n 'dimension',\n 'period',\n 'path',\n 'itemKey',\n 'valueJson',\n 'affirmedEmpty',\n 'reviewState',\n 'conflict',\n 'supersededById',\n 'sourceKind',\n 'sourceRef',\n 'sourceLocator',\n 'sourceQuote',\n 'confidence',\n 'reviewedAt',\n 'reviewedBy',\n 'createdAt',\n])\n\n/** The base table, built with no spread of a type variable so drizzle infers\n * the exact row shape {@link RecordEntryRow} is derived from. */\nfunction buildRecordEntryTable(options: CreateRecordTableOptions) {\n const { tableName, scopeTable, sourceTable, reviewerTable } = options\n const prefix = options.indexPrefix ?? tableName\n const extraColumns = options.extraColumns ?? {}\n const collisions = Object.keys(extraColumns).filter((name) => RECORD_STORE_COLUMNS.has(name))\n if (collisions.length > 0) {\n throw new Error(\n `createRecordTable('${tableName}'): extraColumns may not redefine the store's own columns — ${collisions.sort().join(', ')}`,\n )\n }\n\n // The base columns are an ordinary object literal so drizzle infers the\n // exact table shape `RecordTable` is derived from; the product's columns are\n // attached through a widened reference, which adds them at RUNTIME (drizzle\n // reads the map, migrations emit them) without an index signature leaking\n // into the inferred row type and erasing every built-in column.\n const columns = {\n /** ULID minted by the store — an atomic supersede needs the replacement\n * id before the insert, so this has no column default. */\n id: text('id').primaryKey(),\n scopeId: text('scope_id')\n .notNull()\n .references(() => scopeTable.id, { onDelete: 'cascade' }),\n /** Per-scope monotonic write counter, assigned inside the insert\n * statement. The fold's only ordering key. */\n seq: integer('seq').notNull(),\n /** Consumer-defined partition inside the scope; `''` when unused. */\n dimension: text('dimension').notNull().default(''),\n /** The period the assertion became true in; `0` when the consumer has no\n * time dimension. */\n period: integer('period').notNull().default(0),\n /** The field this entry asserts. Validated against the consumer's schema\n * map on every write. */\n path: text('path').notNull(),\n /** Which element of a collection the path belongs to; `''` when not\n * applicable. */\n itemKey: text('item_key').notNull().default(''),\n /** Canonical JSON (sorted keys) of the validated value. */\n valueJson: text('value_json').notNull(),\n /** \"There are none of these\" — written against an affirmable path with\n * `item_key = ''` and `value_json = 'null'`. */\n affirmedEmpty: integer('affirmed_empty', { mode: 'boolean' }).notNull().default(false),\n reviewState: text('review_state').$type<RecordReviewState>().notNull(),\n /** Set when this entry disagreed with a live head from a different source\n * kind at write time — surfaced for a human to resolve. */\n conflict: integer('conflict', { mode: 'boolean' }).notNull().default(false),\n /** Audit link to the accepted entry that replaced this one; NULL marks a\n * live head. */\n supersededById: text('superseded_by_id'),\n /** Stamped by the server call site, never accepted from model output. */\n sourceKind: text('source_kind').notNull(),\n sourceRef: sourceTable\n ? text('source_ref').references(() => sourceTable.id, { onDelete: 'set null' })\n : text('source_ref'),\n /** JSON position inside the source. */\n sourceLocator: text('source_locator', { mode: 'json' }).$type<RecordSourceLocator>(),\n sourceQuote: text('source_quote'),\n confidence: real('confidence'),\n /** Epoch milliseconds. */\n reviewedAt: integer('reviewed_at'),\n reviewedBy: reviewerTable\n ? text('reviewed_by').references(() => reviewerTable.id, { onDelete: 'set null' })\n : text('reviewed_by'),\n /** Epoch milliseconds. Display only — `seq` orders the fold. */\n createdAt: integer('created_at')\n .notNull()\n .$defaultFn(() => Date.now()),\n }\n const widened: Record<string, SQLiteColumnBuilderBase> = columns\n for (const [name, column] of Object.entries(extraColumns)) widened[name] = column\n\n return sqliteTable(\n tableName,\n columns,\n (table) => [\n uniqueIndex(`${prefix}_scope_seq_uidx`).on(table.scopeId, table.seq),\n uniqueIndex(`${prefix}_live_head_uidx`)\n .on(table.scopeId, table.dimension, table.path, table.itemKey, table.period)\n .where(sql`review_state = 'accepted' AND superseded_by_id IS NULL`),\n index(`${prefix}_scope_period_idx`).on(table.scopeId, table.period),\n index(`${prefix}_scope_review_idx`).on(table.scopeId, table.reviewState),\n index(`${prefix}_scope_path_idx`).on(table.scopeId, table.path),\n ],\n )\n}\n\n/** The table shape {@link createRecordTable} produces. */\nexport type RecordTable = ReturnType<typeof buildRecordEntryTable>\n\n/** One stored entry, as selected. */\nexport type RecordEntryRow = RecordTable['$inferSelect']\n\n/** The record table plus the product's own columns, so a product's direct\n * queries name them and the store still sees the shape it depends on. */\nexport type RecordTableWithExtras<TExtra extends RecordExtraColumns> =\n RecordTable & { readonly [K in keyof TExtra]: AnySQLiteColumn }\n\n/**\n * Build one record-entry table wired to the product's tables.\n *\n * The returned table is an ordinary drizzle table: the product puts it in its\n * schema, generates migrations from it, and queries it directly for anything\n * the store does not cover. Declaring `extraColumns` names those columns on\n * the returned type as well.\n */\n// The `extraColumns` overload comes FIRST: overload resolution takes the\n// earliest match, and `extraColumns` is optional on the plain signature, so\n// the plain one would otherwise swallow every call and drop the product's\n// columns from the returned type.\nexport function createRecordTable<TExtra extends RecordExtraColumns>(\n options: CreateRecordTableOptions & { extraColumns: TExtra },\n): RecordTableWithExtras<TExtra>\nexport function createRecordTable(options: CreateRecordTableOptions): RecordTable\nexport function createRecordTable(options: CreateRecordTableOptions): RecordTable {\n return buildRecordEntryTable(options)\n}\n","/**\n * The write / review / list / materialize surface over a table from\n * {@link createRecordTable}. Policy is enforced HERE, at the write boundary,\n * never in callers.\n *\n * - `path` must be a key of the consumer's schema map, and the value must pass\n * that path's validator. Nothing the fold cannot type-check reaches storage.\n * - `reviewState` on write is a function of `sourceKind` alone, read from the\n * consumer's `reviewStateOnWrite` map. An undeclared source kind is refused.\n * - Conflict rule: a write whose key already holds a live accepted entry from a\n * DIFFERENT source kind with a materially different value does not supersede\n * — it lands `proposed` with `conflict = true` for a human to resolve.\n * - Accepting a proposal is the ONLY path from `proposed` to `accepted`, and it\n * clears the conflict flag — a human looked at the disagreement and chose.\n * Accepted entries change by supersession (a new write), never by re-review.\n *\n * ## The D1 rules this store is built around\n *\n * **`transaction()` does not work on D1.** Drizzle exposes it, and on the D1\n * driver it does not give you a transaction — `batch()` is the only atomic\n * primitive Cloudflare offers. So a supersede is one `db.batch([guard, main])`:\n * a guarded UPDATE that marks the outgoing head, and the INSERT (or the accept\n * UPDATE) that installs the new one. A driver with no `batch` (better-sqlite3)\n * gets an explicit `BEGIN IMMEDIATE` / `COMMIT` instead; a driver with neither\n * is refused with `unsupported-driver` rather than quietly running two\n * statements that can half-land.\n *\n * **Unique indexes do not dedupe NULLs in SQLite.** Every key column is NOT\n * NULL with a sentinel (see the schema factory), which is what makes the\n * partial unique index on the live head enforce anything at all.\n *\n * **Ordering never depends on a timestamp.** `created_at` is second- or\n * millisecond-resolution and two entries can share it; `seq` is assigned\n * inside the INSERT statement (SQLite executes a statement atomically, so\n * `MAX(seq) + 1` cannot race, and `(scope_id, seq)` unique backstops it).\n *\n * ## Losing the head race\n *\n * The guarded UPDATE matches the outgoing head by id AND by \"still accepted,\n * still live\". If a competing writer got there first, one of two things\n * happens, and both are safe:\n *\n * - the competitor installed its own live head, so this write's INSERT trips\n * the partial unique index and the WHOLE batch is rolled back — surfaced as\n * a unique violation and retried from a fresh read;\n * - or the batch committed with the guard matching zero rows, which the live\n * head index makes unreachable. That is an invariant breach, so it is\n * returned as `supersede-race` rather than retried: a retry would insert a\n * SECOND row for a write that already landed.\n *\n * ## Losing the REVIEW race\n *\n * The head race is only half of it. On the accept path the dependent statement\n * has a precondition of its own — the proposal must still be `proposed` — and\n * a second reviewer can reject it between this store's read and its write. A\n * `batch` driver cannot look at the first statement before running the second,\n * so the guard carries that precondition too (`markHeadStatement`'s\n * `requireProposedId`): either both statements match or neither does, and a\n * head can never be stamped superseded by an entry that was rejected. Both row\n * counts are then checked, and which one missed decides the answer — a\n * resolved proposal is `not-reviewable`, a moved head is a retry.\n *\n * Every method returns a typed outcome; callers inspect `succeeded` before\n * touching `value`.\n */\n\nimport { and, asc, eq, getTableColumns, getTableName, isNull, lte, sql } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n canonicalRecordJson,\n detectRecordConflict,\n recordFail,\n recordOk,\n resolveWriteReviewState,\n validateRecordValue,\n RECORD_KEY_SENTINEL,\n RECORD_PERIOD_SENTINEL,\n type RecordOutcome,\n type RecordReviewState,\n type RecordSourceLocator,\n type RecordWritePolicy,\n} from '../model'\nimport {\n defaultRecordPeriodScope,\n foldRecordEntries,\n recordEntryVisibleInPeriod,\n type FoldableRecordEntry,\n type RecordFoldRules,\n type RecordPeriodScopeResolver,\n} from '../fold'\nimport { recordUlid } from '../ulid'\nimport { RECORD_STORE_COLUMNS } from './schema'\nimport type { RecordEntryRow, RecordTable } from './schema'\n\n/**\n * Any SQLite drizzle database. The run-result and schema generics are erased\n * to `unknown` so better-sqlite3, D1 and libsql handles all fit; `batch` is\n * declared optional because only D1 and libsql expose it.\n */\nexport type RecordDatabase = BaseSQLiteDatabase<'sync' | 'async', unknown, Record<string, unknown>> & {\n batch?(statements: [unknown, ...unknown[]]): Promise<unknown[]>\n}\n\n/** How this store executes a two-statement atomic unit on the caller's driver. */\nexport type RecordAtomicStrategy = 'batch' | 'begin-immediate'\n\n/** Input to {@link RecordStore.write}. */\nexport interface WriteRecordEntryInput {\n scopeId: string\n /** Must be a key of the policy's schema map, or — when `affirmedEmpty` — one\n * of its affirmable paths. */\n path: string\n /** Defaults to {@link RECORD_PERIOD_SENTINEL}. */\n period?: number\n /** Defaults to {@link RECORD_KEY_SENTINEL}; canonicalized by the policy. */\n dimension?: string\n /** Defaults to {@link RECORD_KEY_SENTINEL}; canonicalized by the policy. */\n itemKey?: string\n /** The value. Must be absent when `affirmedEmpty` is true. */\n value?: unknown\n /** Assert \"there are none of these\" at `path`. */\n affirmedEmpty?: boolean\n /** Stamped by the SERVER call site — never read from model arguments. */\n sourceKind: string\n sourceRef?: string | null\n sourceLocator?: RecordSourceLocator | null\n sourceQuote?: string | null\n confidence?: number | null\n /**\n * Values for the product columns declared through the table factory's\n * `extraColumns`. Carried onto the INSERT verbatim — the store reads none of\n * them and knows none of their names. `policy.requireExtras` is where a\n * product says which ones a given source kind must supply.\n *\n * A key with no matching column is refused rather than dropped: a citation\n * that silently did not store its source id is the failure this store exists\n * to make impossible.\n */\n extras?: Readonly<Record<string, unknown>>\n}\n\n/** What a write produced. */\nexport interface WriteRecordEntryResult {\n entry: RecordEntryRow\n /** True when the write landed `proposed` with the conflict flag set. */\n conflict: boolean\n /** Id of the live head this write superseded, when it superseded one. */\n supersededEntryId: string | null\n}\n\n/** Input to {@link RecordStore.review}. */\nexport interface ReviewRecordEntryInput {\n scopeId: string\n entryId: string\n action: 'accept' | 'reject'\n /** Recorded on the row; the store never derives it. */\n reviewedBy?: string | null\n}\n\n/** Filters for {@link RecordStore.list}. */\nexport interface ListRecordEntriesInput {\n scopeId: string\n /** Narrow to one review state. Does not resurrect superseded entries. */\n reviewState?: RecordReviewState\n /** Resolve visibility against this period. Omit to return every period. */\n period?: number\n /** Include entries a later accepted entry replaced. Default false. */\n includeSuperseded?: boolean\n /** Include rejected entries. Default false, unless `reviewState` asks for\n * them explicitly. */\n includeRejected?: boolean\n}\n\n/** Input to {@link RecordStore.heads}. */\nexport interface ReadRecordHeadsInput {\n scopeId: string\n /**\n * The period to resolve against. Defaults to {@link RECORD_PERIOD_SENTINEL},\n * which is the right default ONLY for a consumer with no time dimension —\n * every entry it writes sits at `0`. A consumer that uses periods passes one\n * on every read; omitting it there resolves against period `0` and returns\n * nothing, rather than quietly mixing periods together.\n */\n period?: number\n}\n\n/** Input to {@link RecordStore.materialize}. */\nexport interface MaterializeRecordInput<T> {\n scopeId: string\n /** The consumer's grouping rules. */\n rules: RecordFoldRules<T>\n /** Same default and same caveat as {@link ReadRecordHeadsInput.period}. */\n period?: number\n}\n\n/** What a materialization produced. */\nexport interface MaterializeRecordResult<T> {\n value: T\n /** Live accepted entries folded in. */\n entryCount: number\n /** Proposed entries visible at this period and still awaiting review. */\n pendingProposed: number\n /** Subset of those flagged by the conflict rule. */\n conflicts: number\n}\n\n/** Options for {@link createRecordStore}. */\nexport interface CreateRecordStoreOptions {\n db: RecordDatabase\n /** The table from `createRecordTable`. */\n table: RecordTable\n /** Everything domain-specific about a write. */\n policy: RecordWritePolicy\n /**\n * Period scope per path, used by `list`'s period filter and as the default\n * for `materialize` when the fold rules omit their own. Defaults to `'exact'`\n * for every path.\n */\n periodScope?: RecordPeriodScopeResolver\n /** Id minter. Defaults to a ULID. */\n newId?: () => string\n /** Clock for `reviewedAt`. Defaults to `Date.now`. */\n now?: () => number\n /** Attempts before a contended head write gives up. Defaults to 3. */\n maxWriteAttempts?: number\n}\n\n/** The store surface. */\nexport interface RecordStore {\n /** Which atomic primitive this store resolved for the injected driver. */\n readonly atomicStrategy: RecordAtomicStrategy\n /** Append one entry, superseding the live head when the write is accepted. */\n write(input: WriteRecordEntryInput): Promise<RecordOutcome<WriteRecordEntryResult>>\n /** Accept or reject a proposed entry. */\n review(input: ReviewRecordEntryInput): Promise<RecordOutcome<RecordEntryRow>>\n /** Entries visible under the filters, ordered by `seq`. */\n list(input: ListRecordEntriesInput): Promise<RecordOutcome<RecordEntryRow[]>>\n /** Live accepted heads visible at `period`, ordered by `seq`. Visibility is\n * the store's period scope, the same rule `list` applies — an `exact`-scoped\n * entry from an earlier period is not a head at a later one. */\n heads(input: ReadRecordHeadsInput): Promise<RecordOutcome<RecordEntryRow[]>>\n /** Fold the live heads into the consumer's shape. */\n materialize<T>(input: MaterializeRecordInput<T>): Promise<RecordOutcome<MaterializeRecordResult<T>>>\n}\n\nconst DEFAULT_WRITE_ATTEMPTS = 3\n\n/**\n * Build a store bound to one table and one policy. `scopeId` is per call, not\n * per store, so one instance serves every tenant a worker handles — and every\n * query pins it in the WHERE clause, so a leaked id from another scope reads\n * and writes nothing.\n */\nexport function createRecordStore(options: CreateRecordStoreOptions): RecordStore {\n const { db, table, policy } = options\n const tableName = getTableName(table)\n const newId = options.newId ?? (() => recordUlid())\n const now = options.now ?? (() => Date.now())\n const attempts = options.maxWriteAttempts ?? DEFAULT_WRITE_ATTEMPTS\n const storePeriodScope = options.periodScope ?? defaultRecordPeriodScope\n const strategy = resolveAtomicStrategy(db)\n const affirmable = new Set(policy.affirmablePaths ?? [])\n const requireRef = new Set(policy.requireSourceRef ?? [])\n const requireQuote = new Set(policy.requireSourceQuote ?? [])\n // The PRODUCT's column keys — every column on the table minus the ones this\n // store owns. An `extras` key outside this set is a refusal: with no column\n // it would be a value drizzle drops on the floor, and with a store-owned\n // column it would shadow the row's own identity.\n const extraColumnNames = new Set(\n Object.keys(getTableColumns(table)).filter((name) => !RECORD_STORE_COLUMNS.has(name)),\n )\n\n function liveHeadWhere(scopeId: string, key: ValidatedKey) {\n return and(\n eq(table.scopeId, scopeId),\n eq(table.dimension, key.dimension),\n eq(table.path, key.path),\n eq(table.itemKey, key.itemKey),\n eq(table.period, key.period),\n eq(table.reviewState, 'accepted'),\n isNull(table.supersededById),\n )\n }\n\n async function loadLiveHead(scopeId: string, key: ValidatedKey): Promise<RecordEntryRow | undefined> {\n const rows = await db.select().from(table).where(liveHeadWhere(scopeId, key)).limit(1)\n return rows[0]\n }\n\n /**\n * The guarded UPDATE that marks an outgoing head superseded.\n *\n * `requireProposedId` folds the DEPENDENT statement's own precondition into\n * this one. On a `batch` driver the pair commits unconditionally and nothing\n * can inspect the first statement before the second runs, so the two must be\n * unable to disagree. Without it, a proposal a concurrent reviewer rejected\n * still gets its id stamped onto the head as `superseded_by_id` while the\n * accept UPDATE matches nothing — the record left with NO live head while the\n * caller is told the review did not happen.\n */\n function markHeadStatement(headId: string, replacementId: string, requireProposedId?: string) {\n const guards = [eq(table.id, headId), eq(table.reviewState, 'accepted'), isNull(table.supersededById)]\n if (requireProposedId !== undefined) {\n guards.push(\n sql`EXISTS (SELECT 1 FROM ${sql.identifier(tableName)} WHERE id = ${requireProposedId} AND review_state = 'proposed')`,\n )\n }\n return db\n .update(table)\n .set({ supersededById: replacementId })\n .where(and(...guards))\n .returning({ id: table.id })\n }\n\n /** Re-read one entry by id inside its scope. Used to name WHICH precondition\n * a guarded pair failed on, which decides retry versus refusal. */\n async function loadEntry(scopeId: string, entryId: string): Promise<RecordEntryRow | undefined> {\n const rows = await db\n .select()\n .from(table)\n .where(and(eq(table.id, entryId), eq(table.scopeId, scopeId)))\n .limit(1)\n return rows[0]\n }\n\n async function write(input: WriteRecordEntryInput): Promise<RecordOutcome<WriteRecordEntryResult>> {\n const validated = validateWrite(input)\n if (!validated.succeeded) return validated\n const draft = validated.value\n\n let lastError = ''\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n const head = await loadLiveHead(input.scopeId, draft.key)\n const conflict = detectRecordConflict(policy, head, draft)\n const reviewState: RecordReviewState = conflict ? 'proposed' : draft.reviewState\n\n const id = newId()\n const values = insertValues(input, draft, id, reviewState, conflict)\n\n if (reviewState === 'accepted' && head !== undefined) {\n const paired = await runGuardedPair(\n db,\n strategy,\n markHeadStatement(head.id, id),\n db.insert(table).values(values).returning(),\n )\n if (!paired.guardMatched) {\n if (paired.rolledBack) {\n lastError = `write: lost the head race on '${draft.key.path}' (head ${head.id} changed underneath)`\n continue\n }\n return recordFail(\n 'supersede-race',\n `write: head ${head.id} on '${draft.key.path}' was not markable but the write committed — the live-head index is not enforcing`,\n )\n }\n // An INSERT has no precondition to miss, so an empty main here is a\n // driver defect rather than a lost race — and `runGuardedPair` has\n // already rolled the pair back where the driver allows it, so the\n // head is not left marked against a row that was never written.\n const row = firstRow(paired.mainRows)\n if (!row) return recordFail('storage-failed', 'write: insert returned no row')\n return recordOk({ entry: row, conflict: false, supersededEntryId: head.id })\n }\n\n const inserted = await db.insert(table).values(values).returning()\n const row = firstRow(inserted)\n if (!row) return recordFail('storage-failed', 'write: insert returned no row')\n return recordOk({ entry: row, conflict, supersededEntryId: null })\n } catch (error) {\n if (isUniqueViolation(error)) {\n lastError = `write: concurrent head write on '${draft.key.path}' — ${errorMessage(error)}`\n continue\n }\n return recordFail('storage-failed', `write: ${errorMessage(error)}`)\n }\n }\n return recordFail('supersede-race', `${lastError} (gave up after ${attempts} attempts)`)\n }\n\n async function review(input: ReviewRecordEntryInput): Promise<RecordOutcome<RecordEntryRow>> {\n let existing: RecordEntryRow | undefined\n try {\n const rows = await db\n .select()\n .from(table)\n .where(and(eq(table.id, input.entryId), eq(table.scopeId, input.scopeId)))\n .limit(1)\n existing = rows[0]\n } catch (error) {\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n if (!existing) {\n return recordFail('not-found', `review: entry '${input.entryId}' not found in scope '${input.scopeId}'`)\n }\n if (existing.reviewState !== 'proposed') {\n return recordFail(\n 'not-reviewable',\n `review: entry '${input.entryId}' is '${existing.reviewState}' — only proposed entries are reviewable`,\n )\n }\n\n const reviewedAt = now()\n const reviewedBy = input.reviewedBy ?? null\n\n if (input.action === 'reject') {\n try {\n const updated = await db\n .update(table)\n .set({ reviewState: 'rejected', reviewedAt, reviewedBy })\n .where(and(eq(table.id, existing.id), eq(table.reviewState, 'proposed')))\n .returning()\n const row = firstRow(updated)\n if (!row) {\n return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n }\n return recordOk(row)\n } catch (error) {\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n }\n\n const key: ValidatedKey = {\n dimension: existing.dimension,\n path: existing.path,\n itemKey: existing.itemKey,\n period: existing.period,\n }\n\n let lastError = ''\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n const head = await loadLiveHead(input.scopeId, key)\n const acceptStatement = db\n .update(table)\n .set({ reviewState: 'accepted', conflict: false, reviewedAt, reviewedBy })\n .where(and(eq(table.id, existing.id), eq(table.reviewState, 'proposed')))\n .returning()\n\n if (head !== undefined) {\n const paired = await runGuardedPair(\n db,\n strategy,\n markHeadStatement(head.id, existing.id, existing.id),\n acceptStatement,\n )\n if (!paired.guardMatched && paired.mainMatched) {\n return recordFail(\n 'supersede-race',\n `review: head ${head.id} was not markable but the accept committed — the live-head index is not enforcing`,\n )\n }\n if (paired.guardMatched && !paired.mainMatched && !paired.rolledBack) {\n // The head is stamped superseded by an entry the accept did not\n // install. Nothing can be retried past this: the record's live\n // value is gone and only an operator can put it back.\n return recordFail(\n 'supersede-race',\n `review: head ${head.id} was marked superseded by '${input.entryId}' but the accept matched no row — the batch is not atomic`,\n )\n }\n if (!paired.guardMatched || !paired.mainMatched) {\n // Nothing landed. Which precondition failed decides the answer: a\n // proposal a concurrent reviewer already resolved is a refusal, a\n // head that moved underneath is a retry.\n const current = await loadEntry(input.scopeId, existing.id)\n if (current === undefined || current.reviewState !== 'proposed') {\n return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n }\n lastError = `review: lost the head race accepting '${input.entryId}' (head ${head.id} changed underneath)`\n continue\n }\n const row = firstRow(paired.mainRows)\n if (!row) return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n return recordOk(row)\n }\n\n const accepted = await acceptStatement\n const row = firstRow(accepted)\n if (!row) return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n return recordOk(row)\n } catch (error) {\n if (isUniqueViolation(error)) {\n lastError = `review: concurrent head write accepting '${input.entryId}' — ${errorMessage(error)}`\n continue\n }\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n }\n return recordFail('supersede-race', `${lastError} (gave up after ${attempts} attempts)`)\n }\n\n async function list(input: ListRecordEntriesInput): Promise<RecordOutcome<RecordEntryRow[]>> {\n if (input.period !== undefined && !Number.isInteger(input.period)) {\n return recordFail('invalid-input', `list: period must be an integer, got ${String(input.period)}`)\n }\n try {\n const where = input.period === undefined\n ? eq(table.scopeId, input.scopeId)\n : and(eq(table.scopeId, input.scopeId), lte(table.period, input.period))\n const rows = await db.select().from(table).where(where).orderBy(asc(table.seq))\n\n const visible = rows.filter((row) => {\n if (input.period !== undefined\n && !recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, input.period)) return false\n if (input.reviewState !== undefined) {\n if (row.reviewState !== input.reviewState) return false\n } else if (!input.includeRejected && row.reviewState === 'rejected') {\n return false\n }\n if (!input.includeSuperseded && row.supersededById !== null) return false\n return true\n })\n return recordOk(visible)\n } catch (error) {\n return recordFail('storage-failed', `list: ${errorMessage(error)}`)\n }\n }\n\n /**\n * The raw live-accepted query. `period <= N` is the only predicate SQL can\n * express — whether an entry written at an earlier period is still TRUE at\n * `N` is the period scope's call, and that resolver is per path, so it runs\n * in JS over these rows.\n */\n async function loadHeads(scopeId: string, period: number): Promise<RecordEntryRow[]> {\n return db\n .select()\n .from(table)\n .where(and(\n eq(table.scopeId, scopeId),\n eq(table.reviewState, 'accepted'),\n isNull(table.supersededById),\n lte(table.period, period),\n ))\n .orderBy(asc(table.seq))\n }\n\n async function heads(input: ReadRecordHeadsInput): Promise<RecordOutcome<RecordEntryRow[]>> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `heads: period must be an integer, got ${String(period)}`)\n }\n try {\n const rows = await loadHeads(input.scopeId, period)\n // The same visibility rule `list` applies. Without it an `exact`-scoped\n // entry written at an earlier period reads as live at a later one, and\n // the two published reads answer the same question differently.\n return recordOk(rows.filter((row) => recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, period)))\n } catch (error) {\n return recordFail('storage-failed', `heads: ${errorMessage(error)}`)\n }\n }\n\n async function materialize<T>(input: MaterializeRecordInput<T>): Promise<RecordOutcome<MaterializeRecordResult<T>>> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `materialize: period must be an integer, got ${String(period)}`)\n }\n // Deliberately the RAW rows, not `heads()`: the fold applies the caller's\n // own `rules.periodScope` when it supplies one, so pre-filtering here with\n // the store's resolver would drop entries those rules would have kept.\n let loaded: RecordEntryRow[]\n try {\n loaded = await loadHeads(input.scopeId, period)\n } catch (error) {\n return recordFail('storage-failed', `materialize: ${errorMessage(error)}`)\n }\n\n const rules: RecordFoldRules<T> = input.rules.periodScope\n ? input.rules\n : { ...input.rules, periodScope: storePeriodScope }\n const folded = foldRecordEntries(loaded.map(toFoldable), { rules, period })\n if (!folded.succeeded) return folded\n\n const periodScope = rules.periodScope ?? storePeriodScope\n try {\n const proposed = await db\n .select({ path: table.path, period: table.period, conflict: table.conflict })\n .from(table)\n .where(and(\n eq(table.scopeId, input.scopeId),\n eq(table.reviewState, 'proposed'),\n lte(table.period, period),\n ))\n const visible = proposed.filter((row) => recordEntryVisibleInPeriod(periodScope(row.path), row.period, period))\n return recordOk({\n value: folded.value.value,\n entryCount: folded.value.entryCount,\n pendingProposed: visible.length,\n conflicts: visible.filter((row) => row.conflict).length,\n })\n } catch (error) {\n return recordFail('storage-failed', `materialize: ${errorMessage(error)}`)\n }\n }\n\n interface ValidatedKey {\n dimension: string\n path: string\n itemKey: string\n period: number\n }\n\n interface ValidatedWrite {\n key: ValidatedKey\n valueJson: string\n affirmedEmpty: boolean\n reviewState: RecordReviewState\n sourceKind: string\n }\n\n function validateWrite(input: WriteRecordEntryInput): RecordOutcome<ValidatedWrite> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n const minPeriod = policy.minPeriod ?? RECORD_PERIOD_SENTINEL\n const maxPeriod = policy.maxPeriod ?? Number.MAX_SAFE_INTEGER\n if (!Number.isInteger(period) || period < minPeriod || period > maxPeriod) {\n return recordFail(\n 'invalid-input',\n `write: period must be an integer in [${minPeriod}, ${maxPeriod}], got ${String(period)}`,\n )\n }\n if (requireRef.has(input.sourceKind) && !input.sourceRef) {\n return recordFail('invalid-input', `write: source kind '${input.sourceKind}' requires a sourceRef ('${input.path}')`)\n }\n if (requireQuote.has(input.sourceKind) && !input.sourceQuote) {\n return recordFail('invalid-input', `write: source kind '${input.sourceKind}' requires a sourceQuote ('${input.path}')`)\n }\n const extras = input.extras ?? {}\n for (const key of Object.keys(extras)) {\n if (!extraColumnNames.has(key)) {\n return recordFail(\n 'invalid-input',\n `write: extras key '${key}' has no column on '${tableName}' — declare it in createRecordTable's extraColumns`,\n )\n }\n }\n for (const key of policy.requireExtras?.[input.sourceKind] ?? []) {\n const held = extras[key]\n if (held === undefined || held === null || held === '') {\n return recordFail(\n 'invalid-input',\n `write: source kind '${input.sourceKind}' requires extras.${key} ('${input.path}')`,\n )\n }\n }\n if (input.confidence !== undefined && input.confidence !== null\n && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) {\n return recordFail('invalid-input', `write: confidence must be in [0, 1], got ${String(input.confidence)}`)\n }\n\n const state = resolveWriteReviewState(policy, input.sourceKind)\n if (!state.succeeded) return state\n\n const dimension = canonicalize(policy.canonicalizeDimension, input.path, input.dimension ?? RECORD_KEY_SENTINEL, 'dimension')\n if (!dimension.succeeded) return dimension\n\n if (input.affirmedEmpty === true) {\n if (input.value !== undefined) {\n return recordFail('invalid-input', `write: an affirmedEmpty entry must not carry a value ('${input.path}')`)\n }\n if (!affirmable.has(input.path)) {\n return recordFail(\n 'unknown-path',\n `write: '${input.path}' is not an affirmable path — affirmedEmpty targets a path declared in policy.affirmablePaths`,\n )\n }\n if ((input.itemKey ?? RECORD_KEY_SENTINEL) !== RECORD_KEY_SENTINEL) {\n return recordFail(\n 'invalid-input',\n `write: an affirmedEmpty entry uses the itemKey sentinel — it asserts that a whole path is empty ('${input.path}')`,\n )\n }\n return recordOk({\n key: { dimension: dimension.value, path: input.path, itemKey: RECORD_KEY_SENTINEL, period },\n valueJson: 'null',\n affirmedEmpty: true,\n reviewState: state.value,\n sourceKind: input.sourceKind,\n })\n }\n\n const validator = policy.schemas[input.path]\n if (validator === undefined) {\n return recordFail('unknown-path', `write: unknown path '${input.path}' — not a key of the policy's schema map`)\n }\n if (input.value === undefined) {\n return recordFail('invalid-input', `write: a value is required unless affirmedEmpty is true ('${input.path}')`)\n }\n const parsed = validateRecordValue(validator, input.value)\n if (!parsed.succeeded) {\n return recordFail('invalid-value', `write: value for '${input.path}' failed validation — ${parsed.error}`)\n }\n\n const itemKey = canonicalize(policy.canonicalizeItemKey, input.path, input.itemKey ?? RECORD_KEY_SENTINEL, 'itemKey')\n if (!itemKey.succeeded) return itemKey\n\n return recordOk({\n key: { dimension: dimension.value, path: input.path, itemKey: itemKey.value, period },\n valueJson: canonicalRecordJson(parsed.value),\n affirmedEmpty: false,\n reviewState: state.value,\n sourceKind: input.sourceKind,\n })\n }\n\n function insertValues(\n input: WriteRecordEntryInput,\n draft: ValidatedWrite,\n id: string,\n reviewState: RecordReviewState,\n conflict: boolean,\n ) {\n return {\n // First, so a product column can never shadow a store-owned one even if\n // the guards above were bypassed.\n ...(input.extras ?? {}),\n id,\n scopeId: input.scopeId,\n // Assigned inside the statement: SQLite executes one statement\n // atomically, so MAX + 1 cannot race, and `(scope_id, seq)` unique\n // backstops it.\n seq: sql<number>`(SELECT COALESCE(MAX(seq), 0) + 1 FROM ${sql.identifier(tableName)} WHERE scope_id = ${input.scopeId})`,\n dimension: draft.key.dimension,\n period: draft.key.period,\n path: draft.key.path,\n itemKey: draft.key.itemKey,\n valueJson: draft.valueJson,\n affirmedEmpty: draft.affirmedEmpty,\n reviewState,\n conflict,\n supersededById: null,\n sourceKind: input.sourceKind,\n sourceRef: input.sourceRef ?? null,\n sourceLocator: input.sourceLocator ?? null,\n sourceQuote: input.sourceQuote ?? null,\n confidence: input.confidence ?? null,\n // A write that lands accepted by policy was not REVIEWED — nobody looked\n // at it. `createdAt` records when it landed; these two stay null until an\n // actual accept/reject.\n reviewedAt: null,\n reviewedBy: null,\n }\n }\n\n return { atomicStrategy: strategy, write, review, list, heads, materialize }\n}\n\n/** Project a stored row onto the slice the pure fold reads. */\nexport function toFoldable(row: RecordEntryRow): FoldableRecordEntry {\n return {\n id: row.id,\n seq: row.seq,\n dimension: row.dimension,\n period: row.period,\n path: row.path,\n itemKey: row.itemKey,\n valueJson: row.valueJson,\n affirmedEmpty: row.affirmedEmpty,\n }\n}\n\nfunction canonicalize(\n canonicalizer: ((path: string, raw: string) => RecordOutcome<string>) | undefined,\n path: string,\n raw: string,\n column: string,\n): RecordOutcome<string> {\n if (!canonicalizer) return recordOk(raw)\n const result = canonicalizer(path, raw)\n if (!result.succeeded) return recordFail('invalid-input', `write: '${path}' ${column} — ${result.error}`)\n return result\n}\n\nfunction firstRow(rows: unknown): RecordEntryRow | undefined {\n return Array.isArray(rows) ? (rows[0] as RecordEntryRow | undefined) : undefined\n}\n\n/**\n * Pick the driver's atomic primitive. `batch` first and unconditionally: on D1\n * it is the ONLY one that works, and a D1 handle also exposes a `transaction`\n * method that does not give you a transaction.\n */\nexport function resolveAtomicStrategy(db: RecordDatabase): RecordAtomicStrategy {\n if (typeof db.batch === 'function') return 'batch'\n if (typeof db.run === 'function') return 'begin-immediate'\n throw new Error(\n 'createRecordStore: the injected driver exposes neither batch() nor run() — an atomic supersede is impossible on it',\n )\n}\n\ninterface GuardedPairResult {\n /** True when the guarded statement matched exactly one row. */\n guardMatched: boolean\n /** True when the dependent statement matched at least one row. */\n mainMatched: boolean\n /** True when a failed precondition left NOTHING written. */\n rolledBack: boolean\n /** Rows the second statement returned. */\n mainRows: unknown[]\n}\n\n/**\n * Run a guarded statement and its dependent statement as one atomic unit.\n *\n * BOTH statements' row counts are reported, and both matter. With only the\n * guard's checked, the destructive half of a supersede can commit alone — the\n * outgoing head stamped `superseded_by_id` while the dependent accept matches\n * zero rows, leaving the record with no live head at all.\n *\n * `batch` (D1, libsql) commits both or neither and cannot inspect the first\n * statement before the second runs — the guard has to carry the dependent\n * statement's precondition itself (see `markHeadStatement`), and the row counts\n * read afterwards say which precondition failed. `begin-immediate`\n * (better-sqlite3 and any driver without `batch`) can do better: it inspects\n * each statement as it runs and rolls back on either mismatch, so the caller\n * retries from a fresh read with nothing written.\n */\nasync function runGuardedPair(\n db: RecordDatabase,\n strategy: RecordAtomicStrategy,\n guard: unknown,\n main: unknown,\n): Promise<GuardedPairResult> {\n if (strategy === 'batch') {\n const batch = db.batch\n if (typeof batch !== 'function') {\n throw new Error('runGuardedPair: batch strategy resolved but the driver has no batch()')\n }\n const results = await batch.call(db, [guard, main] as [unknown, ...unknown[]])\n const guardRows = results[0]\n const mainRows = Array.isArray(results[1]) ? results[1] : []\n return {\n guardMatched: Array.isArray(guardRows) && guardRows.length === 1,\n mainMatched: mainRows.length > 0,\n rolledBack: false,\n mainRows,\n }\n }\n\n await db.run(sql`begin immediate`)\n try {\n const guardRows = await (guard as Promise<unknown>)\n if (!Array.isArray(guardRows) || guardRows.length !== 1) {\n await db.run(sql`rollback`)\n return { guardMatched: false, mainMatched: false, rolledBack: true, mainRows: [] }\n }\n const mainRows = await (main as Promise<unknown>)\n if (!Array.isArray(mainRows) || mainRows.length === 0) {\n await db.run(sql`rollback`)\n return { guardMatched: true, mainMatched: false, rolledBack: true, mainRows: [] }\n }\n await db.run(sql`commit`)\n return { guardMatched: true, mainMatched: true, rolledBack: false, mainRows }\n } catch (error) {\n await rollbackQuietly(db)\n throw error\n }\n}\n\n/** Roll back without masking the error that caused it. */\nasync function rollbackQuietly(db: RecordDatabase): Promise<void> {\n try {\n await db.run(sql`rollback`)\n } catch {\n // The transaction is already gone; the original error is the one to report.\n }\n}\n\n/** Flatten a driver error's cause chain into one readable message. */\nfunction errorMessage(error: unknown): string {\n const parts: string[] = []\n let cursor: unknown = error\n for (let depth = 0; depth < 5 && cursor instanceof Error; depth++) {\n parts.push(cursor.message)\n cursor = cursor.cause\n }\n return parts.length > 0 ? parts.join(' — ') : String(error)\n}\n\n/** Drizzle wraps driver errors (\"Failed query: …\") and keeps the SQLite error\n * in the cause chain, so the whole chain is inspected. */\nfunction isUniqueViolation(error: unknown): boolean {\n let cursor: unknown = error\n for (let depth = 0; depth < 5 && cursor instanceof Error; depth++) {\n if (cursor.message.includes('UNIQUE constraint failed')) return true\n cursor = cursor.cause\n }\n return false\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,MAAM,mBAAmB;AA6D9D,IAAM,uBAA4C,oBAAI,IAAI;AAAA,EAC/D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,SAAS,sBAAsB,SAAmC;AAChE,QAAM,EAAE,WAAW,YAAY,aAAa,cAAc,IAAI;AAC9D,QAAM,SAAS,QAAQ,eAAe;AACtC,QAAM,eAAe,QAAQ,gBAAgB,CAAC;AAC9C,QAAM,aAAa,OAAO,KAAK,YAAY,EAAE,OAAO,CAAC,SAAS,qBAAqB,IAAI,IAAI,CAAC;AAC5F,MAAI,WAAW,SAAS,GAAG;AACzB,UAAM,IAAI;AAAA,MACR,sBAAsB,SAAS,oEAA+D,WAAW,KAAK,EAAE,KAAK,IAAI,CAAC;AAAA,IAC5H;AAAA,EACF;AAOA,QAAM,UAAU;AAAA;AAAA;AAAA,IAGd,IAAI,KAAK,IAAI,EAAE,WAAW;AAAA,IAC1B,SAAS,KAAK,UAAU,EACrB,QAAQ,EACR,WAAW,MAAM,WAAW,IAAI,EAAE,UAAU,UAAU,CAAC;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M,GAAG,IAAIA,cAAa;AAC1B,aAAO,EAAE,cAAc,OAAO,aAAa,OAAO,YAAY,MAAM,UAAU,CAAC,EAAE;AAAA,IACnF;AACA,UAAM,WAAW,MAAO;AACxB,QAAI,CAAC,MAAM,QAAQ,QAAQ,KAAK,SAAS,WAAW,GAAG;AACrD,YAAM,GAAG,IAAIA,cAAa;AAC1B,aAAO,EAAE,cAAc,MAAM,aAAa,OAAO,YAAY,MAAM,UAAU,CAAC,EAAE;AAAA,IAClF;AACA,UAAM,GAAG,IAAIA,YAAW;AACxB,WAAO,EAAE,cAAc,MAAM,aAAa,MAAM,YAAY,OAAO,SAAS;AAAA,EAC9E,SAAS,OAAO;AACd,UAAM,gBAAgB,EAAE;AACxB,UAAM;AAAA,EACR;AACF;AAGA,eAAe,gBAAgB,IAAmC;AAChE,MAAI;AACF,UAAM,GAAG,IAAIA,cAAa;AAAA,EAC5B,QAAQ;AAAA,EAER;AACF;AAGA,SAAS,aAAa,OAAwB;AAC5C,QAAM,QAAkB,CAAC;AACzB,MAAI,SAAkB;AACtB,WAAS,QAAQ,GAAG,QAAQ,KAAK,kBAAkB,OAAO,SAAS;AACjE,UAAM,KAAK,OAAO,OAAO;AACzB,aAAS,OAAO;AAAA,EAClB;AACA,SAAO,MAAM,SAAS,IAAI,MAAM,KAAK,UAAK,IAAI,OAAO,KAAK;AAC5D;AAIA,SAAS,kBAAkB,OAAyB;AAClD,MAAI,SAAkB;AACtB,WAAS,QAAQ,GAAG,QAAQ,KAAK,kBAAkB,OAAO,SAAS;AACjE,QAAI,OAAO,QAAQ,SAAS,0BAA0B,EAAG,QAAO;AAChE,aAAS,OAAO;AAAA,EAClB;AACA,SAAO;AACT;","names":["sql","sql","row"]}
|
|
1
|
+
{"version":3,"sources":["../../src/record/drizzle/schema.ts","../../src/record/drizzle/store.ts"],"sourcesContent":["/**\n * Drizzle table factory for a record-entry table. The product owns its\n * scope (workspace / tenant / account) table; this factory creates the entry\n * table and wires the foreign key into it, so the whole graph lives in one\n * drizzle schema with real cascade semantics.\n *\n * The table NAME is a parameter, so one product can host several independent\n * record tables (different domains, different schema maps) side by side.\n *\n * Three storage invariants are encoded here, and the store depends on all\n * three:\n *\n * 1. **Every key column is NOT NULL with a sentinel.** SQLite treats NULLs as\n * distinct inside a unique index, so a nullable `item_key` or `dimension`\n * would let two live heads coexist on one logical key and the partial\n * unique index below would silently stop enforcing anything. `''` and `0`\n * are the sentinels; see `RECORD_KEY_SENTINEL` / `RECORD_PERIOD_SENTINEL`.\n * 2. **The live head is unique per key.** The partial unique index covers only\n * rows that are `accepted` and not superseded, which is exactly the set the\n * materializer reads. Two writers racing for the same head make the second\n * one fail loudly instead of both landing.\n * 3. **Ordering is `seq`, never a timestamp.** `created_at` is epoch\n * milliseconds and is display-only. `(scope_id, seq)` is unique, so the\n * fold has a total order even for rows written in the same millisecond.\n *\n * `superseded_by_id` deliberately carries NO foreign key: the supersede batch\n * stamps the replacement's id onto the outgoing head BEFORE inserting the\n * replacement row, and SQLite cannot defer the constraint check to allow that\n * order. Rows are append-only and cascade with their scope, so the link cannot\n * dangle.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, SQLiteColumnBuilderBase } from 'drizzle-orm/sqlite-core'\nimport type { RecordReviewState, RecordSourceLocator } from '../model'\n\n/** A product table referenced by foreign key — only its `id` column is used. */\nexport type RecordParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/**\n * Product columns added to the entry table, keyed by the property name the\n * store and the product read them under. Ordinary drizzle column builders, so\n * a product declares foreign keys, defaults and null-ability exactly as it\n * would in its own schema.\n */\nexport type RecordExtraColumns = Readonly<Record<string, SQLiteColumnBuilderBase>>\n\n/** Options for {@link createRecordTable}. */\nexport interface CreateRecordTableOptions {\n /**\n * SQL table name, chosen by the product. Also the default prefix for the\n * index names, so two record tables in one schema never collide.\n */\n tableName: string\n /**\n * The tenant table entries belong to. Rows cascade with it — deleting a\n * workspace deletes its record.\n */\n scopeTable: RecordParentTable\n /**\n * Optional table `source_ref` points at (a documents table, a source-record\n * table). Wire it ONLY when every source kind's ref points at this one\n * table; a product whose refs are heterogeneous (a document id for one kind,\n * a message id for another) leaves it off and keeps `source_ref` plain text.\n * When wired, deleting the source sets the ref null and leaves the entry\n * with its quote and locator intact.\n */\n sourceTable?: RecordParentTable\n /** Optional table `reviewed_by` points at (a users table). */\n reviewerTable?: RecordParentTable\n /** Index-name prefix. Defaults to {@link tableName}. */\n indexPrefix?: string\n /**\n * Product columns merged into the table, the `/missions` store-port pattern.\n *\n * The built-in `source_ref` is ONE column, which is right for a store whose\n * refs all point at one table and wrong for one whose kinds cite different\n * things — a chat-sourced row citing a message and a document-sourced row\n * citing a document each want their own foreign key with their own\n * `ON DELETE` behaviour. Declare them here, require them per source kind\n * through `policy.requireExtras`, and pass their values on `write`; the\n * store carries them and reads none of them.\n *\n * A key that collides with a built-in column is refused at construction —\n * silently shadowing `path` or `review_state` would break every invariant\n * the store rests on.\n */\n extraColumns?: RecordExtraColumns\n}\n\n/** Column property names the store owns. An extra column may not take one, and\n * neither may an `extras` value on a write — shadowing `path` or\n * `review_state` would break every invariant this table encodes. */\nexport const RECORD_STORE_COLUMNS: ReadonlySet<string> = new Set([\n 'id',\n 'scopeId',\n 'seq',\n 'dimension',\n 'period',\n 'path',\n 'itemKey',\n 'valueJson',\n 'affirmedEmpty',\n 'reviewState',\n 'conflict',\n 'supersededById',\n 'sourceKind',\n 'sourceRef',\n 'sourceLocator',\n 'sourceQuote',\n 'confidence',\n 'reviewedAt',\n 'reviewedBy',\n 'createdAt',\n])\n\n/** The base table, built with no spread of a type variable so drizzle infers\n * the exact row shape {@link RecordEntryRow} is derived from. */\nfunction buildRecordEntryTable(options: CreateRecordTableOptions) {\n const { tableName, scopeTable, sourceTable, reviewerTable } = options\n const prefix = options.indexPrefix ?? tableName\n const extraColumns = options.extraColumns ?? {}\n const collisions = Object.keys(extraColumns).filter((name) => RECORD_STORE_COLUMNS.has(name))\n if (collisions.length > 0) {\n throw new Error(\n `createRecordTable('${tableName}'): extraColumns may not redefine the store's own columns — ${collisions.sort().join(', ')}`,\n )\n }\n\n // The base columns are an ordinary object literal so drizzle infers the\n // exact table shape `RecordTable` is derived from; the product's columns are\n // attached through a widened reference, which adds them at RUNTIME (drizzle\n // reads the map, migrations emit them) without an index signature leaking\n // into the inferred row type and erasing every built-in column.\n const columns = {\n /** ULID minted by the store — an atomic supersede needs the replacement\n * id before the insert, so this has no column default. */\n id: text('id').primaryKey(),\n scopeId: text('scope_id')\n .notNull()\n .references(() => scopeTable.id, { onDelete: 'cascade' }),\n /** Per-scope monotonic write counter, assigned inside the insert\n * statement. The fold's only ordering key. */\n seq: integer('seq').notNull(),\n /** Consumer-defined partition inside the scope; `''` when unused. */\n dimension: text('dimension').notNull().default(''),\n /** The period the assertion became true in; `0` when the consumer has no\n * time dimension. */\n period: integer('period').notNull().default(0),\n /** The field this entry asserts. Validated against the consumer's schema\n * map on every write. */\n path: text('path').notNull(),\n /** Which element of a collection the path belongs to; `''` when not\n * applicable. */\n itemKey: text('item_key').notNull().default(''),\n /** Canonical JSON (sorted keys) of the validated value. */\n valueJson: text('value_json').notNull(),\n /** \"There are none of these\" — written against an affirmable path with\n * `item_key = ''` and `value_json = 'null'`. */\n affirmedEmpty: integer('affirmed_empty', { mode: 'boolean' }).notNull().default(false),\n reviewState: text('review_state').$type<RecordReviewState>().notNull(),\n /** Set when this entry disagreed with a live head from a different source\n * kind at write time — surfaced for a human to resolve. */\n conflict: integer('conflict', { mode: 'boolean' }).notNull().default(false),\n /** Audit link to the accepted entry that replaced this one; NULL marks a\n * live head. */\n supersededById: text('superseded_by_id'),\n /** Stamped by the server call site, never accepted from model output. */\n sourceKind: text('source_kind').notNull(),\n sourceRef: sourceTable\n ? text('source_ref').references(() => sourceTable.id, { onDelete: 'set null' })\n : text('source_ref'),\n /** JSON position inside the source. */\n sourceLocator: text('source_locator', { mode: 'json' }).$type<RecordSourceLocator>(),\n sourceQuote: text('source_quote'),\n confidence: real('confidence'),\n /** Epoch milliseconds. */\n reviewedAt: integer('reviewed_at'),\n reviewedBy: reviewerTable\n ? text('reviewed_by').references(() => reviewerTable.id, { onDelete: 'set null' })\n : text('reviewed_by'),\n /** Epoch milliseconds. Display only — `seq` orders the fold. */\n createdAt: integer('created_at')\n .notNull()\n .$defaultFn(() => Date.now()),\n }\n const widened: Record<string, SQLiteColumnBuilderBase> = columns\n for (const [name, column] of Object.entries(extraColumns)) widened[name] = column\n\n return sqliteTable(\n tableName,\n columns,\n (table) => [\n uniqueIndex(`${prefix}_scope_seq_uidx`).on(table.scopeId, table.seq),\n uniqueIndex(`${prefix}_live_head_uidx`)\n .on(table.scopeId, table.dimension, table.path, table.itemKey, table.period)\n .where(sql`review_state = 'accepted' AND superseded_by_id IS NULL`),\n index(`${prefix}_scope_period_idx`).on(table.scopeId, table.period),\n index(`${prefix}_scope_review_idx`).on(table.scopeId, table.reviewState),\n index(`${prefix}_scope_path_idx`).on(table.scopeId, table.path),\n ],\n )\n}\n\n/** The table shape {@link createRecordTable} produces. */\nexport type RecordTable = ReturnType<typeof buildRecordEntryTable>\n\n/** One stored entry, as selected. */\nexport type RecordEntryRow = RecordTable['$inferSelect']\n\n/** The record table plus the product's own columns, so a product's direct\n * queries name them and the store still sees the shape it depends on. */\nexport type RecordTableWithExtras<TExtra extends RecordExtraColumns> =\n RecordTable & { readonly [K in keyof TExtra]: AnySQLiteColumn }\n\n/**\n * Build one record-entry table wired to the product's tables.\n *\n * The returned table is an ordinary drizzle table: the product puts it in its\n * schema, generates migrations from it, and queries it directly for anything\n * the store does not cover. Declaring `extraColumns` names those columns on\n * the returned type as well.\n */\n// The `extraColumns` overload comes FIRST: overload resolution takes the\n// earliest match, and `extraColumns` is optional on the plain signature, so\n// the plain one would otherwise swallow every call and drop the product's\n// columns from the returned type.\nexport function createRecordTable<TExtra extends RecordExtraColumns>(\n options: CreateRecordTableOptions & { extraColumns: TExtra },\n): RecordTableWithExtras<TExtra>\nexport function createRecordTable(options: CreateRecordTableOptions): RecordTable\nexport function createRecordTable(options: CreateRecordTableOptions): RecordTable {\n return buildRecordEntryTable(options)\n}\n","/**\n * The write / review / list / materialize surface over a table from\n * {@link createRecordTable}. Policy is enforced HERE, at the write boundary,\n * never in callers.\n *\n * - `path` must be a key of the consumer's schema map, and the value must pass\n * that path's validator. Nothing the fold cannot type-check reaches storage.\n * - `reviewState` on write is a function of `sourceKind` alone, read from the\n * consumer's `reviewStateOnWrite` map. An undeclared source kind is refused.\n * - Conflict rule: a write whose key already holds a live accepted entry from a\n * DIFFERENT source kind with a materially different value does not supersede\n * — it lands `proposed` with `conflict = true` for a human to resolve.\n * - Accepting a proposal is the ONLY path from `proposed` to `accepted`, and it\n * clears the conflict flag — a human looked at the disagreement and chose.\n * Accepted entries change by supersession (a new write), never by re-review.\n *\n * ## The D1 rules this store is built around\n *\n * **`transaction()` does not work on D1.** Drizzle exposes it, and on the D1\n * driver it does not give you a transaction — `batch()` is the only atomic\n * primitive Cloudflare offers. So a supersede is one `db.batch([guard, main])`:\n * a guarded UPDATE that marks the outgoing head, and the INSERT (or the accept\n * UPDATE) that installs the new one. A driver with no `batch` (better-sqlite3)\n * gets an explicit `BEGIN IMMEDIATE` / `COMMIT` instead; a driver with neither\n * is refused with `unsupported-driver` rather than quietly running two\n * statements that can half-land.\n *\n * **Unique indexes do not dedupe NULLs in SQLite.** Every key column is NOT\n * NULL with a sentinel (see the schema factory), which is what makes the\n * partial unique index on the live head enforce anything at all.\n *\n * **Ordering never depends on a timestamp.** `created_at` is second- or\n * millisecond-resolution and two entries can share it; `seq` is assigned\n * inside the INSERT statement (SQLite executes a statement atomically, so\n * `MAX(seq) + 1` cannot race, and `(scope_id, seq)` unique backstops it).\n *\n * ## Losing the head race\n *\n * The guarded UPDATE matches the outgoing head by id AND by \"still accepted,\n * still live\". If a competing writer got there first, one of two things\n * happens, and both are safe:\n *\n * - the competitor installed its own live head, so this write's INSERT trips\n * the partial unique index and the WHOLE batch is rolled back — surfaced as\n * a unique violation and retried from a fresh read;\n * - or the batch committed with the guard matching zero rows, which the live\n * head index makes unreachable. That is an invariant breach, so it is\n * returned as `supersede-race` rather than retried: a retry would insert a\n * SECOND row for a write that already landed.\n *\n * ## Losing the REVIEW race\n *\n * The head race is only half of it. On the accept path the dependent statement\n * has a precondition of its own — the proposal must still be `proposed` — and\n * a second reviewer can reject it between this store's read and its write. A\n * `batch` driver cannot look at the first statement before running the second,\n * so the guard carries that precondition too (`markHeadStatement`'s\n * `requireProposedId`): either both statements match or neither does, and a\n * head can never be stamped superseded by an entry that was rejected. Both row\n * counts are then checked, and which one missed decides the answer — a\n * resolved proposal is `not-reviewable`, a moved head is a retry.\n *\n * Every method returns a typed outcome; callers inspect `succeeded` before\n * touching `value`.\n */\n\nimport { and, asc, eq, getTableColumns, getTableName, isNull, lte, sql } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n canonicalRecordJson,\n detectRecordConflict,\n recordFail,\n recordOk,\n resolveWriteReviewState,\n validateRecordValue,\n RECORD_KEY_SENTINEL,\n RECORD_PERIOD_SENTINEL,\n type RecordOutcome,\n type RecordReviewState,\n type RecordSourceLocator,\n type RecordWritePolicy,\n} from '../model'\nimport {\n defaultRecordPeriodScope,\n foldRecordEntries,\n recordEntryVisibleInPeriod,\n type FoldableRecordEntry,\n type RecordFoldRules,\n type RecordPeriodScopeResolver,\n} from '../fold'\nimport { recordUlid } from '../ulid'\nimport { RECORD_STORE_COLUMNS } from './schema'\nimport type { RecordEntryRow, RecordTable } from './schema'\n\n/**\n * Any SQLite drizzle database. The run-result and schema generics are erased\n * to `unknown` so better-sqlite3, D1 and libsql handles all fit; `batch` is\n * declared optional because only D1 and libsql expose it.\n */\nexport type RecordDatabase = BaseSQLiteDatabase<'sync' | 'async', unknown, Record<string, unknown>> & {\n batch?(statements: [unknown, ...unknown[]]): Promise<unknown[]>\n}\n\n/** How this store executes a two-statement atomic unit on the caller's driver. */\nexport type RecordAtomicStrategy = 'batch' | 'begin-immediate'\n\n/** Input to {@link RecordStore.write}. */\nexport interface WriteRecordEntryInput {\n scopeId: string\n /** Must be a key of the policy's schema map, or — when `affirmedEmpty` — one\n * of its affirmable paths. */\n path: string\n /** Defaults to {@link RECORD_PERIOD_SENTINEL}. */\n period?: number\n /** Defaults to {@link RECORD_KEY_SENTINEL}; canonicalized by the policy. */\n dimension?: string\n /** Defaults to {@link RECORD_KEY_SENTINEL}; canonicalized by the policy. */\n itemKey?: string\n /** The value. Must be absent when `affirmedEmpty` is true. */\n value?: unknown\n /** Assert \"there are none of these\" at `path`. */\n affirmedEmpty?: boolean\n /** Stamped by the SERVER call site — never read from model arguments. */\n sourceKind: string\n sourceRef?: string | null\n sourceLocator?: RecordSourceLocator | null\n sourceQuote?: string | null\n confidence?: number | null\n /**\n * Values for the product columns declared through the table factory's\n * `extraColumns`. Carried onto the INSERT verbatim — the store reads none of\n * them and knows none of their names. `policy.requireExtras` is where a\n * product says which ones a given source kind must supply.\n *\n * A key with no matching column is refused rather than dropped: a citation\n * that silently did not store its source id is the failure this store exists\n * to make impossible.\n */\n extras?: Readonly<Record<string, unknown>>\n}\n\n/** What a write produced. */\nexport interface WriteRecordEntryResult {\n entry: RecordEntryRow\n /** True when the write landed `proposed` with the conflict flag set. */\n conflict: boolean\n /** Id of the live head this write superseded, when it superseded one. */\n supersededEntryId: string | null\n}\n\n/** Input to {@link RecordStore.review}. */\nexport interface ReviewRecordEntryInput {\n scopeId: string\n entryId: string\n action: 'accept' | 'reject'\n /** Recorded on the row; the store never derives it. */\n reviewedBy?: string | null\n}\n\n/** Filters for {@link RecordStore.list}. */\nexport interface ListRecordEntriesInput {\n scopeId: string\n /** Narrow to one review state. Does not resurrect superseded entries. */\n reviewState?: RecordReviewState\n /** Resolve visibility against this period. Omit to return every period. */\n period?: number\n /** Include entries a later accepted entry replaced. Default false. */\n includeSuperseded?: boolean\n /** Include rejected entries. Default false, unless `reviewState` asks for\n * them explicitly. */\n includeRejected?: boolean\n}\n\n/** Input to {@link RecordStore.heads}. */\nexport interface ReadRecordHeadsInput {\n scopeId: string\n /**\n * The period to resolve against. Defaults to {@link RECORD_PERIOD_SENTINEL},\n * which is the right default ONLY for a consumer with no time dimension —\n * every entry it writes sits at `0`. A consumer that uses periods passes one\n * on every read; omitting it there resolves against period `0` and returns\n * nothing, rather than quietly mixing periods together.\n */\n period?: number\n}\n\n/** Input to {@link RecordStore.materialize}. */\nexport interface MaterializeRecordInput<T> {\n scopeId: string\n /** The consumer's grouping rules. */\n rules: RecordFoldRules<T>\n /** Same default and same caveat as {@link ReadRecordHeadsInput.period}. */\n period?: number\n}\n\n/** What a materialization produced. */\nexport interface MaterializeRecordResult<T> {\n value: T\n /** Live accepted entries folded in. */\n entryCount: number\n /** Proposed entries visible at this period and still awaiting review. */\n pendingProposed: number\n /** Subset of those flagged by the conflict rule. */\n conflicts: number\n}\n\n/** Options for {@link createRecordStore}. */\nexport interface CreateRecordStoreOptions {\n db: RecordDatabase\n /** The table from `createRecordTable`. */\n table: RecordTable\n /** Everything domain-specific about a write. */\n policy: RecordWritePolicy\n /**\n * Period scope per path, used by `list`'s period filter and as the default\n * for `materialize` when the fold rules omit their own. Defaults to `'exact'`\n * for every path.\n */\n periodScope?: RecordPeriodScopeResolver\n /** Id minter. Defaults to a ULID. */\n newId?: () => string\n /** Clock for `reviewedAt`. Defaults to `Date.now`. */\n now?: () => number\n /** Attempts before a contended head write gives up. Defaults to 3. */\n maxWriteAttempts?: number\n}\n\n/** The store surface. */\nexport interface RecordStore {\n /** Which atomic primitive this store resolved for the injected driver. */\n readonly atomicStrategy: RecordAtomicStrategy\n /** Append one entry, superseding the live head when the write is accepted. */\n write(input: WriteRecordEntryInput): Promise<RecordOutcome<WriteRecordEntryResult>>\n /** Accept or reject a proposed entry. */\n review(input: ReviewRecordEntryInput): Promise<RecordOutcome<RecordEntryRow>>\n /** Entries visible under the filters, ordered by `seq`. */\n list(input: ListRecordEntriesInput): Promise<RecordOutcome<RecordEntryRow[]>>\n /** Live accepted heads visible at `period`, ordered by `seq`. Visibility is\n * the store's period scope, the same rule `list` applies — an `exact`-scoped\n * entry from an earlier period is not a head at a later one. */\n heads(input: ReadRecordHeadsInput): Promise<RecordOutcome<RecordEntryRow[]>>\n /** Fold the live heads into the consumer's shape. */\n materialize<T>(input: MaterializeRecordInput<T>): Promise<RecordOutcome<MaterializeRecordResult<T>>>\n}\n\nconst DEFAULT_WRITE_ATTEMPTS = 3\n\n/**\n * Build a store bound to one table and one policy. `scopeId` is per call, not\n * per store, so one instance serves every tenant a worker handles — and every\n * query pins it in the WHERE clause, so a leaked id from another scope reads\n * and writes nothing.\n */\nexport function createRecordStore(options: CreateRecordStoreOptions): RecordStore {\n const { db, table, policy } = options\n const tableName = getTableName(table)\n const newId = options.newId ?? (() => recordUlid())\n const now = options.now ?? (() => Date.now())\n const attempts = options.maxWriteAttempts ?? DEFAULT_WRITE_ATTEMPTS\n const storePeriodScope = options.periodScope ?? defaultRecordPeriodScope\n const strategy = resolveAtomicStrategy(db)\n const affirmable = new Set(policy.affirmablePaths ?? [])\n const requireRef = new Set(policy.requireSourceRef ?? [])\n const requireQuote = new Set(policy.requireSourceQuote ?? [])\n // The PRODUCT's column keys — every column on the table minus the ones this\n // store owns. An `extras` key outside this set is a refusal: with no column\n // it would be a value drizzle drops on the floor, and with a store-owned\n // column it would shadow the row's own identity.\n const extraColumnNames = new Set(\n Object.keys(getTableColumns(table)).filter((name) => !RECORD_STORE_COLUMNS.has(name)),\n )\n\n function liveHeadWhere(scopeId: string, key: ValidatedKey) {\n return and(\n eq(table.scopeId, scopeId),\n eq(table.dimension, key.dimension),\n eq(table.path, key.path),\n eq(table.itemKey, key.itemKey),\n eq(table.period, key.period),\n eq(table.reviewState, 'accepted'),\n isNull(table.supersededById),\n )\n }\n\n async function loadLiveHead(scopeId: string, key: ValidatedKey): Promise<RecordEntryRow | undefined> {\n const rows = await db.select().from(table).where(liveHeadWhere(scopeId, key)).limit(1)\n return rows[0]\n }\n\n /**\n * The guarded UPDATE that marks an outgoing head superseded.\n *\n * `requireProposedId` folds the DEPENDENT statement's own precondition into\n * this one. On a `batch` driver the pair commits unconditionally and nothing\n * can inspect the first statement before the second runs, so the two must be\n * unable to disagree. Without it, a proposal a concurrent reviewer rejected\n * still gets its id stamped onto the head as `superseded_by_id` while the\n * accept UPDATE matches nothing — the record left with NO live head while the\n * caller is told the review did not happen.\n */\n function markHeadStatement(headId: string, replacementId: string, requireProposedId?: string) {\n const guards = [eq(table.id, headId), eq(table.reviewState, 'accepted'), isNull(table.supersededById)]\n if (requireProposedId !== undefined) {\n guards.push(\n sql`EXISTS (SELECT 1 FROM ${sql.identifier(tableName)} WHERE id = ${requireProposedId} AND review_state = 'proposed')`,\n )\n }\n return db\n .update(table)\n .set({ supersededById: replacementId })\n .where(and(...guards))\n .returning({ id: table.id })\n }\n\n /** Re-read one entry by id inside its scope. Used to name WHICH precondition\n * a guarded pair failed on, which decides retry versus refusal. */\n async function loadEntry(scopeId: string, entryId: string): Promise<RecordEntryRow | undefined> {\n const rows = await db\n .select()\n .from(table)\n .where(and(eq(table.id, entryId), eq(table.scopeId, scopeId)))\n .limit(1)\n return rows[0]\n }\n\n async function write(input: WriteRecordEntryInput): Promise<RecordOutcome<WriteRecordEntryResult>> {\n const validated = validateWrite(input)\n if (!validated.succeeded) return validated\n const draft = validated.value\n\n let lastError = ''\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n const head = await loadLiveHead(input.scopeId, draft.key)\n const conflict = detectRecordConflict(policy, head, draft)\n const reviewState: RecordReviewState = conflict ? 'proposed' : draft.reviewState\n\n const id = newId()\n const values = insertValues(input, draft, id, reviewState, conflict)\n\n if (reviewState === 'accepted' && head !== undefined) {\n const paired = await runGuardedPair(\n db,\n strategy,\n markHeadStatement(head.id, id),\n db.insert(table).values(values).returning(),\n )\n if (!paired.guardMatched) {\n if (paired.rolledBack) {\n lastError = `write: lost the head race on '${draft.key.path}' (head ${head.id} changed underneath)`\n continue\n }\n return recordFail(\n 'supersede-race',\n `write: head ${head.id} on '${draft.key.path}' was not markable but the write committed — the live-head index is not enforcing`,\n )\n }\n // An INSERT has no precondition to miss, so an empty main here is a\n // driver defect rather than a lost race — and `runGuardedPair` has\n // already rolled the pair back where the driver allows it, so the\n // head is not left marked against a row that was never written.\n const row = firstRow(paired.mainRows)\n if (!row) return recordFail('storage-failed', 'write: insert returned no row')\n return recordOk({ entry: row, conflict: false, supersededEntryId: head.id })\n }\n\n const inserted = await db.insert(table).values(values).returning()\n const row = firstRow(inserted)\n if (!row) return recordFail('storage-failed', 'write: insert returned no row')\n return recordOk({ entry: row, conflict, supersededEntryId: null })\n } catch (error) {\n if (isUniqueViolation(error)) {\n lastError = `write: concurrent head write on '${draft.key.path}' — ${errorMessage(error)}`\n continue\n }\n return recordFail('storage-failed', `write: ${errorMessage(error)}`)\n }\n }\n return recordFail('supersede-race', `${lastError} (gave up after ${attempts} attempts)`)\n }\n\n async function review(input: ReviewRecordEntryInput): Promise<RecordOutcome<RecordEntryRow>> {\n let existing: RecordEntryRow | undefined\n try {\n const rows = await db\n .select()\n .from(table)\n .where(and(eq(table.id, input.entryId), eq(table.scopeId, input.scopeId)))\n .limit(1)\n existing = rows[0]\n } catch (error) {\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n if (!existing) {\n return recordFail('not-found', `review: entry '${input.entryId}' not found in scope '${input.scopeId}'`)\n }\n if (existing.reviewState !== 'proposed') {\n return recordFail(\n 'not-reviewable',\n `review: entry '${input.entryId}' is '${existing.reviewState}' — only proposed entries are reviewable`,\n )\n }\n\n const reviewedAt = now()\n const reviewedBy = input.reviewedBy ?? null\n\n if (input.action === 'reject') {\n try {\n const updated = await db\n .update(table)\n .set({ reviewState: 'rejected', reviewedAt, reviewedBy })\n .where(and(eq(table.id, existing.id), eq(table.reviewState, 'proposed')))\n .returning()\n const row = firstRow(updated)\n if (!row) {\n return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n }\n return recordOk(row)\n } catch (error) {\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n }\n\n const key: ValidatedKey = {\n dimension: existing.dimension,\n path: existing.path,\n itemKey: existing.itemKey,\n period: existing.period,\n }\n\n let lastError = ''\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n const head = await loadLiveHead(input.scopeId, key)\n const acceptStatement = db\n .update(table)\n .set({ reviewState: 'accepted', conflict: false, reviewedAt, reviewedBy })\n .where(and(eq(table.id, existing.id), eq(table.reviewState, 'proposed')))\n .returning()\n\n if (head !== undefined) {\n const paired = await runGuardedPair(\n db,\n strategy,\n markHeadStatement(head.id, existing.id, existing.id),\n acceptStatement,\n )\n if (!paired.guardMatched && paired.mainMatched) {\n return recordFail(\n 'supersede-race',\n `review: head ${head.id} was not markable but the accept committed — the live-head index is not enforcing`,\n )\n }\n if (paired.guardMatched && !paired.mainMatched && !paired.rolledBack) {\n // The head is stamped superseded by an entry the accept did not\n // install. Nothing can be retried past this: the record's live\n // value is gone and only an operator can put it back.\n return recordFail(\n 'supersede-race',\n `review: head ${head.id} was marked superseded by '${input.entryId}' but the accept matched no row — the batch is not atomic`,\n )\n }\n if (!paired.guardMatched || !paired.mainMatched) {\n // Nothing landed. Which precondition failed decides the answer: a\n // proposal a concurrent reviewer already resolved is a refusal, a\n // head that moved underneath is a retry.\n const current = await loadEntry(input.scopeId, existing.id)\n if (current === undefined || current.reviewState !== 'proposed') {\n return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n }\n lastError = `review: lost the head race accepting '${input.entryId}' (head ${head.id} changed underneath)`\n continue\n }\n const row = firstRow(paired.mainRows)\n if (!row) return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n return recordOk(row)\n }\n\n const accepted = await acceptStatement\n const row = firstRow(accepted)\n if (!row) return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n return recordOk(row)\n } catch (error) {\n if (isUniqueViolation(error)) {\n lastError = `review: concurrent head write accepting '${input.entryId}' — ${errorMessage(error)}`\n continue\n }\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n }\n return recordFail('supersede-race', `${lastError} (gave up after ${attempts} attempts)`)\n }\n\n const { list, heads, materialize } = createRecordReads(table, db, storePeriodScope)\n\n const { validateWrite, insertValues } = createRecordWriteInputs(policy, requireRef, requireQuote, extraColumnNames, tableName, affirmable)\n\n return { atomicStrategy: strategy, write, review, list, heads, materialize }\n}\n\n/** Project a stored row onto the slice the pure fold reads. */\nexport function toFoldable(row: RecordEntryRow): FoldableRecordEntry {\n return {\n id: row.id,\n seq: row.seq,\n dimension: row.dimension,\n period: row.period,\n path: row.path,\n itemKey: row.itemKey,\n valueJson: row.valueJson,\n affirmedEmpty: row.affirmedEmpty,\n }\n}\n\nfunction canonicalize(\n canonicalizer: ((path: string, raw: string) => RecordOutcome<string>) | undefined,\n path: string,\n raw: string,\n column: string,\n): RecordOutcome<string> {\n if (!canonicalizer) return recordOk(raw)\n const result = canonicalizer(path, raw)\n if (!result.succeeded) return recordFail('invalid-input', `write: '${path}' ${column} — ${result.error}`)\n return result\n}\n\nfunction firstRow(rows: unknown): RecordEntryRow | undefined {\n return Array.isArray(rows) ? (rows[0] as RecordEntryRow | undefined) : undefined\n}\n\n/**\n * Pick the driver's atomic primitive. `batch` first and unconditionally: on D1\n * it is the ONLY one that works, and a D1 handle also exposes a `transaction`\n * method that does not give you a transaction.\n */\nexport function resolveAtomicStrategy(db: RecordDatabase): RecordAtomicStrategy {\n if (typeof db.batch === 'function') return 'batch'\n if (typeof db.run === 'function') return 'begin-immediate'\n throw new Error(\n 'createRecordStore: the injected driver exposes neither batch() nor run() — an atomic supersede is impossible on it',\n )\n}\n\ninterface GuardedPairResult {\n /** True when the guarded statement matched exactly one row. */\n guardMatched: boolean\n /** True when the dependent statement matched at least one row. */\n mainMatched: boolean\n /** True when a failed precondition left NOTHING written. */\n rolledBack: boolean\n /** Rows the second statement returned. */\n mainRows: unknown[]\n}\n\n/**\n * Run a guarded statement and its dependent statement as one atomic unit.\n *\n * BOTH statements' row counts are reported, and both matter. With only the\n * guard's checked, the destructive half of a supersede can commit alone — the\n * outgoing head stamped `superseded_by_id` while the dependent accept matches\n * zero rows, leaving the record with no live head at all.\n *\n * `batch` (D1, libsql) commits both or neither and cannot inspect the first\n * statement before the second runs — the guard has to carry the dependent\n * statement's precondition itself (see `markHeadStatement`), and the row counts\n * read afterwards say which precondition failed. `begin-immediate`\n * (better-sqlite3 and any driver without `batch`) can do better: it inspects\n * each statement as it runs and rolls back on either mismatch, so the caller\n * retries from a fresh read with nothing written.\n */\nasync function runGuardedPair(\n db: RecordDatabase,\n strategy: RecordAtomicStrategy,\n guard: unknown,\n main: unknown,\n): Promise<GuardedPairResult> {\n if (strategy === 'batch') {\n const batch = db.batch\n if (typeof batch !== 'function') {\n throw new Error('runGuardedPair: batch strategy resolved but the driver has no batch()')\n }\n const results = await batch.call(db, [guard, main] as [unknown, ...unknown[]])\n const guardRows = results[0]\n const mainRows = Array.isArray(results[1]) ? results[1] : []\n return {\n guardMatched: Array.isArray(guardRows) && guardRows.length === 1,\n mainMatched: mainRows.length > 0,\n rolledBack: false,\n mainRows,\n }\n }\n\n await db.run(sql`begin immediate`)\n try {\n const guardRows = await (guard as Promise<unknown>)\n if (!Array.isArray(guardRows) || guardRows.length !== 1) {\n await db.run(sql`rollback`)\n return { guardMatched: false, mainMatched: false, rolledBack: true, mainRows: [] }\n }\n const mainRows = await (main as Promise<unknown>)\n if (!Array.isArray(mainRows) || mainRows.length === 0) {\n await db.run(sql`rollback`)\n return { guardMatched: true, mainMatched: false, rolledBack: true, mainRows: [] }\n }\n await db.run(sql`commit`)\n return { guardMatched: true, mainMatched: true, rolledBack: false, mainRows }\n } catch (error) {\n await rollbackQuietly(db)\n throw error\n }\n}\n\n/** Roll back without masking the error that caused it. */\nasync function rollbackQuietly(db: RecordDatabase): Promise<void> {\n try {\n await db.run(sql`rollback`)\n } catch {\n // The transaction is already gone; the original error is the one to report.\n }\n}\n\n/** Flatten a driver error's cause chain into one readable message. */\nfunction errorMessage(error: unknown): string {\n const parts: string[] = []\n let cursor: unknown = error\n for (let depth = 0;depth < 5 && cursor instanceof Error;depth++) {\n parts.push(cursor.message)\n cursor = cursor.cause\n }\n return parts.length > 0 ? parts.join(' — ') : String(error)\n}\n\n/** Drizzle wraps driver errors (\"Failed query: …\") and keeps the SQLite error\n * in the cause chain, so the whole chain is inspected. */\nfunction isUniqueViolation(error: unknown): boolean {\n let cursor: unknown = error\n for (let depth = 0;depth < 5 && cursor instanceof Error;depth++) {\n if (cursor.message.includes('UNIQUE constraint failed')) return true\n cursor = cursor.cause\n }\n return false\n}\n\ninterface ValidatedKey {\n dimension: string\n path: string\n itemKey: string\n period: number\n}\n\ninterface ValidatedWrite {\n key: ValidatedKey\n valueJson: string\n affirmedEmpty: boolean\n reviewState: RecordReviewState\n sourceKind: string\n}\n\n\nfunction createRecordWriteInputs(\n policy: CreateRecordStoreOptions['policy'],\n requireRef: Set<string>,\n requireQuote: Set<string>,\n extraColumnNames: Set<string>,\n tableName: ReturnType<typeof getTableName>,\n affirmable: Set<string>,\n) {\n function validateWrite(input: WriteRecordEntryInput): RecordOutcome<ValidatedWrite> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n const minPeriod = policy.minPeriod ?? RECORD_PERIOD_SENTINEL\n const maxPeriod = policy.maxPeriod ?? Number.MAX_SAFE_INTEGER\n if (!Number.isInteger(period) || period < minPeriod || period > maxPeriod) {\n return recordFail(\n 'invalid-input',\n `write: period must be an integer in [${minPeriod}, ${maxPeriod}], got ${String(period)}`,\n )\n }\n if (requireRef.has(input.sourceKind) && !input.sourceRef) {\n return recordFail('invalid-input', `write: source kind '${input.sourceKind}' requires a sourceRef ('${input.path}')`)\n }\n if (requireQuote.has(input.sourceKind) && !input.sourceQuote) {\n return recordFail('invalid-input', `write: source kind '${input.sourceKind}' requires a sourceQuote ('${input.path}')`)\n }\n const extras = input.extras ?? {}\n for (const key of Object.keys(extras)) {\n if (!extraColumnNames.has(key)) {\n return recordFail(\n 'invalid-input',\n `write: extras key '${key}' has no column on '${tableName}' — declare it in createRecordTable's extraColumns`,\n )\n }\n }\n for (const key of policy.requireExtras?.[input.sourceKind] ?? []) {\n const held = extras[key]\n if (held === undefined || held === null || held === '') {\n return recordFail(\n 'invalid-input',\n `write: source kind '${input.sourceKind}' requires extras.${key} ('${input.path}')`,\n )\n }\n }\n if (input.confidence !== undefined && input.confidence !== null\n && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) {\n return recordFail('invalid-input', `write: confidence must be in [0, 1], got ${String(input.confidence)}`)\n }\n\n const state = resolveWriteReviewState(policy, input.sourceKind)\n if (!state.succeeded) return state\n\n const dimension = canonicalize(policy.canonicalizeDimension, input.path, input.dimension ?? RECORD_KEY_SENTINEL, 'dimension')\n if (!dimension.succeeded) return dimension\n\n if (input.affirmedEmpty === true) {\n if (input.value !== undefined) {\n return recordFail('invalid-input', `write: an affirmedEmpty entry must not carry a value ('${input.path}')`)\n }\n if (!affirmable.has(input.path)) {\n return recordFail(\n 'unknown-path',\n `write: '${input.path}' is not an affirmable path — affirmedEmpty targets a path declared in policy.affirmablePaths`,\n )\n }\n if ((input.itemKey ?? RECORD_KEY_SENTINEL) !== RECORD_KEY_SENTINEL) {\n return recordFail(\n 'invalid-input',\n `write: an affirmedEmpty entry uses the itemKey sentinel — it asserts that a whole path is empty ('${input.path}')`,\n )\n }\n return recordOk({\n key: { dimension: dimension.value, path: input.path, itemKey: RECORD_KEY_SENTINEL, period },\n valueJson: 'null',\n affirmedEmpty: true,\n reviewState: state.value,\n sourceKind: input.sourceKind,\n })\n }\n\n const validator = policy.schemas[input.path]\n if (validator === undefined) {\n return recordFail('unknown-path', `write: unknown path '${input.path}' — not a key of the policy's schema map`)\n }\n if (input.value === undefined) {\n return recordFail('invalid-input', `write: a value is required unless affirmedEmpty is true ('${input.path}')`)\n }\n const parsed = validateRecordValue(validator, input.value)\n if (!parsed.succeeded) {\n return recordFail('invalid-value', `write: value for '${input.path}' failed validation — ${parsed.error}`)\n }\n\n const itemKey = canonicalize(policy.canonicalizeItemKey, input.path, input.itemKey ?? RECORD_KEY_SENTINEL, 'itemKey')\n if (!itemKey.succeeded) return itemKey\n\n return recordOk({\n key: { dimension: dimension.value, path: input.path, itemKey: itemKey.value, period },\n valueJson: canonicalRecordJson(parsed.value),\n affirmedEmpty: false,\n reviewState: state.value,\n sourceKind: input.sourceKind,\n })\n }\n\n function insertValues(\n input: WriteRecordEntryInput,\n draft: ValidatedWrite,\n id: string,\n reviewState: RecordReviewState,\n conflict: boolean,\n ) {\n return {\n // First, so a product column can never shadow a store-owned one even if\n // the guards above were bypassed.\n ...(input.extras ?? {}),\n id,\n scopeId: input.scopeId,\n // Assigned inside the statement: SQLite executes one statement\n // atomically, so MAX + 1 cannot race, and `(scope_id, seq)` unique\n // backstops it.\n seq: sql<number>`(SELECT COALESCE(MAX(seq), 0) + 1 FROM ${sql.identifier(tableName)} WHERE scope_id = ${input.scopeId})`,\n dimension: draft.key.dimension,\n period: draft.key.period,\n path: draft.key.path,\n itemKey: draft.key.itemKey,\n valueJson: draft.valueJson,\n affirmedEmpty: draft.affirmedEmpty,\n reviewState,\n conflict,\n supersededById: null,\n sourceKind: input.sourceKind,\n sourceRef: input.sourceRef ?? null,\n sourceLocator: input.sourceLocator ?? null,\n sourceQuote: input.sourceQuote ?? null,\n confidence: input.confidence ?? null,\n // A write that lands accepted by policy was not REVIEWED — nobody looked\n // at it. `createdAt` records when it landed; these two stay null until an\n // actual accept/reject.\n reviewedAt: null,\n reviewedBy: null,\n }\n }\n return { validateWrite, insertValues }\n}\n\nfunction createRecordReads(table: CreateRecordStoreOptions['table'], db: CreateRecordStoreOptions['db'], storePeriodScope: RecordPeriodScopeResolver) {\n async function list(input: ListRecordEntriesInput): Promise<RecordOutcome<RecordEntryRow[]>> {\n if (input.period !== undefined && !Number.isInteger(input.period)) {\n return recordFail('invalid-input', `list: period must be an integer, got ${String(input.period)}`)\n }\n try {\n const where = input.period === undefined\n ? eq(table.scopeId, input.scopeId)\n : and(eq(table.scopeId, input.scopeId), lte(table.period, input.period))\n const rows = await db.select().from(table).where(where).orderBy(asc(table.seq))\n\n const visible = rows.filter((row) => {\n if (input.period !== undefined\n && !recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, input.period)) return false\n if (input.reviewState !== undefined) {\n if (row.reviewState !== input.reviewState) return false\n } else if (!input.includeRejected && row.reviewState === 'rejected') {\n return false\n }\n if (!input.includeSuperseded && row.supersededById !== null) return false\n return true\n })\n return recordOk(visible)\n } catch (error) {\n return recordFail('storage-failed', `list: ${errorMessage(error)}`)\n }\n }\n\n /**\n * The raw live-accepted query. `period <= N` is the only predicate SQL can\n * express — whether an entry written at an earlier period is still TRUE at\n * `N` is the period scope's call, and that resolver is per path, so it runs\n * in JS over these rows.\n */\n async function loadHeads(scopeId: string, period: number): Promise<RecordEntryRow[]> {\n return db\n .select()\n .from(table)\n .where(and(\n eq(table.scopeId, scopeId),\n eq(table.reviewState, 'accepted'),\n isNull(table.supersededById),\n lte(table.period, period),\n ))\n .orderBy(asc(table.seq))\n }\n\n async function heads(input: ReadRecordHeadsInput): Promise<RecordOutcome<RecordEntryRow[]>> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `heads: period must be an integer, got ${String(period)}`)\n }\n try {\n const rows = await loadHeads(input.scopeId, period)\n // The same visibility rule `list` applies. Without it an `exact`-scoped\n // entry written at an earlier period reads as live at a later one, and\n // the two published reads answer the same question differently.\n return recordOk(rows.filter((row) => recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, period)))\n } catch (error) {\n return recordFail('storage-failed', `heads: ${errorMessage(error)}`)\n }\n }\n\n async function materialize<T>(input: MaterializeRecordInput<T>): Promise<RecordOutcome<MaterializeRecordResult<T>>> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `materialize: period must be an integer, got ${String(period)}`)\n }\n // Deliberately the RAW rows, not `heads()`: the fold applies the caller's\n // own `rules.periodScope` when it supplies one, so pre-filtering here with\n // the store's resolver would drop entries those rules would have kept.\n let loaded: RecordEntryRow[]\n try {\n loaded = await loadHeads(input.scopeId, period)\n } catch (error) {\n return recordFail('storage-failed', `materialize: ${errorMessage(error)}`)\n }\n\n const rules: RecordFoldRules<T> = input.rules.periodScope\n ? input.rules\n : { ...input.rules, periodScope: storePeriodScope }\n const folded = foldRecordEntries(loaded.map(toFoldable), { rules, period })\n if (!folded.succeeded) return folded\n\n const periodScope = rules.periodScope ?? storePeriodScope\n try {\n const proposed = await db\n .select({ path: table.path, period: table.period, conflict: table.conflict })\n .from(table)\n .where(and(\n eq(table.scopeId, input.scopeId),\n eq(table.reviewState, 'proposed'),\n lte(table.period, period),\n ))\n const visible = proposed.filter((row) => recordEntryVisibleInPeriod(periodScope(row.path), row.period, period))\n return recordOk({\n value: folded.value.value,\n entryCount: folded.value.entryCount,\n pendingProposed: visible.length,\n conflicts: visible.filter((row) => row.conflict).length,\n })\n } catch (error) {\n return recordFail('storage-failed', `materialize: ${errorMessage(error)}`)\n }\n }\n return { list, heads, materialize }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,MAAM,mBAAmB;AA6D9D,IAAM,uBAA4C,oBAAI,IAAI;AAAA,EAC/D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AA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W,MAAM,GACpB,OAAO,EAAE,MAAM,MAAM,MAAM,QAAQ,MAAM,QAAQ,UAAU,MAAM,SAAS,CAAC,EAC3E,KAAK,KAAK,EACV,MAAM;AAAA,QACL,GAAG,MAAM,SAAS,MAAM,OAAO;AAAA,QAC/B,GAAG,MAAM,aAAa,UAAU;AAAA,QAChC,IAAI,MAAM,QAAQ,MAAM;AAAA,MAC1B,CAAC;AACH,YAAM,UAAU,SAAS,OAAO,CAAC,QAAQ,2BAA2B,YAAY,IAAI,IAAI,GAAG,IAAI,QAAQ,MAAM,CAAC;AAC9G,aAAO,SAAS;AAAA,QACd,OAAO,OAAO,MAAM;AAAA,QACpB,YAAY,OAAO,MAAM;AAAA,QACzB,iBAAiB,QAAQ;AAAA,QACzB,WAAW,QAAQ,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE;AAAA,MACnD,CAAC;AAAA,IACH,SAAS,OAAO;AACd,aAAO,WAAW,kBAAkB,gBAAgB,aAAa,KAAK,CAAC,EAAE;AAAA,IAC3E;AAAA,EACF;AACA,SAAO,EAAE,MAAM,OAAO,YAAY;AACpC;","names":["sql","sql","row"]}
|
package/dist/runtime/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
ProtectedModelSettlementError,
|
|
3
3
|
createRouterProtectedModelPort,
|
|
4
4
|
runProtectedRouterTurn
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-CQZVJVME.js";
|
|
6
6
|
import {
|
|
7
7
|
DURABLE_HOP_BUDGET_MS,
|
|
8
8
|
asksForLanguage,
|
|
@@ -26,8 +26,8 @@ import {
|
|
|
26
26
|
turnKnowledgeInstructions,
|
|
27
27
|
workspaceKnowledgeForTurn,
|
|
28
28
|
workspaceTurnCheckpoints
|
|
29
|
-
} from "../chunk-
|
|
30
|
-
import "../chunk-
|
|
29
|
+
} from "../chunk-UW2DKTEM.js";
|
|
30
|
+
import "../chunk-VK3F4N4U.js";
|
|
31
31
|
import {
|
|
32
32
|
DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
|
|
33
33
|
DEFAULT_TANGLE_ROUTER_BASE_URL,
|
|
@@ -54,7 +54,7 @@ import {
|
|
|
54
54
|
resolveCatalogModelId,
|
|
55
55
|
sortModelsByFreshness
|
|
56
56
|
} from "../chunk-AMUXRAUO.js";
|
|
57
|
-
import "../chunk-
|
|
57
|
+
import "../chunk-PCAY23GS.js";
|
|
58
58
|
|
|
59
59
|
// src/runtime/certified-delivery.ts
|
|
60
60
|
import {
|
|
@@ -13,11 +13,11 @@ import {
|
|
|
13
13
|
turnKnowledgeInstructions,
|
|
14
14
|
workspaceKnowledgeForTurn,
|
|
15
15
|
workspaceTurnCheckpoints
|
|
16
|
-
} from "../chunk-
|
|
17
|
-
import "../chunk-
|
|
16
|
+
} from "../chunk-UW2DKTEM.js";
|
|
17
|
+
import "../chunk-VK3F4N4U.js";
|
|
18
18
|
import "../chunk-D6UJEOZQ.js";
|
|
19
19
|
import "../chunk-AMUXRAUO.js";
|
|
20
|
-
import "../chunk-
|
|
20
|
+
import "../chunk-PCAY23GS.js";
|
|
21
21
|
export {
|
|
22
22
|
DURABLE_HOP_BUDGET_MS,
|
|
23
23
|
asksForLanguage,
|
package/dist/sandbox/index.js
CHANGED
|
@@ -101,7 +101,7 @@ import {
|
|
|
101
101
|
warmKey,
|
|
102
102
|
warmReceiptId,
|
|
103
103
|
warmWeekdayOf
|
|
104
|
-
} from "../chunk-
|
|
104
|
+
} from "../chunk-TCJ4TMOW.js";
|
|
105
105
|
import {
|
|
106
106
|
createWarmCache
|
|
107
107
|
} from "../chunk-F4TUZYMX.js";
|
|
@@ -147,14 +147,14 @@ import "../chunk-DSMGS4IV.js";
|
|
|
147
147
|
import "../chunk-5BJHKQ33.js";
|
|
148
148
|
import "../chunk-6A7MYOUI.js";
|
|
149
149
|
import "../chunk-O7UX55EU.js";
|
|
150
|
-
import "../chunk-XEAZWJ3W.js";
|
|
151
150
|
import "../chunk-S5SRJJQG.js";
|
|
151
|
+
import "../chunk-XEAZWJ3W.js";
|
|
152
152
|
import "../chunk-7TZA2TAM.js";
|
|
153
153
|
import "../chunk-UGWQLQDS.js";
|
|
154
154
|
import "../chunk-WSQFNMIA.js";
|
|
155
|
-
import "../chunk-
|
|
155
|
+
import "../chunk-VK3F4N4U.js";
|
|
156
156
|
import "../chunk-D6UJEOZQ.js";
|
|
157
|
-
import "../chunk-
|
|
157
|
+
import "../chunk-PCAY23GS.js";
|
|
158
158
|
import {
|
|
159
159
|
readSandboxBinaryBytes,
|
|
160
160
|
shellQuote,
|
|
@@ -162,7 +162,7 @@ import {
|
|
|
162
162
|
statSandboxFileSize,
|
|
163
163
|
writeProfileFilesToBox
|
|
164
164
|
} from "../chunk-CTREXL3O.js";
|
|
165
|
-
import "../chunk-
|
|
165
|
+
import "../chunk-ELX5YITO.js";
|
|
166
166
|
import "../chunk-HY57QRRW.js";
|
|
167
167
|
export {
|
|
168
168
|
DEFAULT_ESCALATION_TOOLS,
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
sequenceMetaFromRow
|
|
3
|
+
} from "../chunk-FGAROAUF.js";
|
|
1
4
|
import {
|
|
2
5
|
MIN_SEQUENCE_CLIP_FRAMES
|
|
3
6
|
} from "../chunk-SISVELAA.js";
|
|
@@ -146,7 +149,7 @@ function createDrizzleSequenceStore(options) {
|
|
|
146
149
|
]);
|
|
147
150
|
const media = resolveMedia ? await resolveMedia(clipRows) : void 0;
|
|
148
151
|
return {
|
|
149
|
-
sequence:
|
|
152
|
+
sequence: sequenceMetaFromRow(sequenceRow),
|
|
150
153
|
tracks: trackRows.map(mapTrack),
|
|
151
154
|
clips: clipRows.map((row) => mapClip(row, media?.get(row.id)))
|
|
152
155
|
};
|
|
@@ -241,7 +244,7 @@ function createDrizzleSequenceStore(options) {
|
|
|
241
244
|
}
|
|
242
245
|
const [row] = await db.update(sequences).set({ durationFrames, updatedAt: /* @__PURE__ */ new Date() }).where(sequenceScope()).returning();
|
|
243
246
|
if (!row) throw new Error(`Sequence ${scope.sequenceId} not found in workspace ${scope.workspaceId}`);
|
|
244
|
-
return
|
|
247
|
+
return sequenceMetaFromRow(row);
|
|
245
248
|
},
|
|
246
249
|
async recordDecision(input) {
|
|
247
250
|
await requireSequenceRow();
|
|
@@ -286,19 +289,6 @@ function createDrizzleSequenceStore(options) {
|
|
|
286
289
|
}
|
|
287
290
|
};
|
|
288
291
|
}
|
|
289
|
-
function mapSequence(row) {
|
|
290
|
-
return {
|
|
291
|
-
id: row.id,
|
|
292
|
-
title: row.title,
|
|
293
|
-
fps: row.fps,
|
|
294
|
-
width: row.width,
|
|
295
|
-
height: row.height,
|
|
296
|
-
aspectRatio: row.aspectRatio,
|
|
297
|
-
durationFrames: row.durationFrames,
|
|
298
|
-
status: row.status,
|
|
299
|
-
metadata: row.metadata ?? {}
|
|
300
|
-
};
|
|
301
|
-
}
|
|
302
292
|
function mapTrack(row) {
|
|
303
293
|
return {
|
|
304
294
|
id: row.id,
|