@sixb/core 0.1.21 → 0.1.22
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/actions/commit-edits.d.ts +3 -1
- package/dist/actions/commit-edits.d.ts.map +1 -1
- package/dist/actions/execution.d.ts.map +1 -1
- package/dist/actions/index.js +63 -59
- package/dist/actions/index.js.map +1 -1
- package/dist/actions/read-facade.d.ts +9 -1
- package/dist/actions/read-facade.d.ts.map +1 -1
- package/dist/actions/request.d.ts +15 -1
- package/dist/actions/request.d.ts.map +1 -1
- package/dist/actions/run/context.d.ts +1 -0
- package/dist/actions/run/context.d.ts.map +1 -1
- package/dist/actions/run/execute.d.ts +2 -3
- package/dist/actions/run/execute.d.ts.map +1 -1
- package/dist/actions/run/executor.d.ts +3 -0
- package/dist/actions/run/executor.d.ts.map +1 -1
- package/dist/actions/run/normalize.d.ts +2 -1
- package/dist/actions/run/normalize.d.ts.map +1 -1
- package/dist/actions/run/signals.d.ts +1 -3
- package/dist/actions/run/signals.d.ts.map +1 -1
- package/dist/actions/run/types.d.ts +16 -1
- package/dist/actions/run/types.d.ts.map +1 -1
- package/dist/actions/run-authorization.d.ts +14 -0
- package/dist/actions/run-authorization.d.ts.map +1 -1
- package/dist/actions/types/context.d.ts +17 -1
- package/dist/actions/types/context.d.ts.map +1 -1
- package/dist/actions/validators.d.ts.map +1 -1
- package/dist/activity/timeline.d.ts +8 -1
- package/dist/activity/timeline.d.ts.map +1 -1
- package/dist/agents/accounting.d.ts +15 -0
- package/dist/agents/accounting.d.ts.map +1 -0
- package/dist/agents/adapters.d.ts.map +1 -1
- package/dist/agents/agent-mail.d.ts +9 -0
- package/dist/agents/agent-mail.d.ts.map +1 -0
- package/dist/agents/api-gateway.d.ts +5 -0
- package/dist/agents/api-gateway.d.ts.map +1 -1
- package/dist/agents/approval-continuation.d.ts +23 -0
- package/dist/agents/approval-continuation.d.ts.map +1 -0
- package/dist/agents/approval-executor.d.ts +56 -0
- package/dist/agents/approval-executor.d.ts.map +1 -0
- package/dist/agents/approval-outcome.d.ts +8 -0
- package/dist/agents/approval-outcome.d.ts.map +1 -0
- package/dist/agents/approvals.d.ts +210 -0
- package/dist/agents/approvals.d.ts.map +1 -0
- package/dist/agents/authority.d.ts +10 -0
- package/dist/agents/authority.d.ts.map +1 -1
- package/dist/agents/builders.d.ts.map +1 -1
- package/dist/agents/cancel.d.ts +23 -0
- package/dist/agents/cancel.d.ts.map +1 -0
- package/dist/agents/child-question.d.ts +18 -0
- package/dist/agents/child-question.d.ts.map +1 -0
- package/dist/agents/children.d.ts +99 -0
- package/dist/agents/children.d.ts.map +1 -0
- package/dist/agents/context/index.js +1 -1
- package/dist/agents/context-compaction.d.ts.map +1 -1
- package/dist/agents/errors.d.ts +13 -1
- package/dist/agents/errors.d.ts.map +1 -1
- package/dist/agents/execution.d.ts +180 -14
- package/dist/agents/execution.d.ts.map +1 -1
- package/dist/agents/fork.d.ts +16 -0
- package/dist/agents/fork.d.ts.map +1 -0
- package/dist/agents/ids.d.ts +7 -0
- package/dist/agents/ids.d.ts.map +1 -1
- package/dist/agents/index.d.ts +19 -8
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +159 -86
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/memory-execution.d.ts +57 -0
- package/dist/agents/memory-execution.d.ts.map +1 -0
- package/dist/agents/memory.d.ts +49 -0
- package/dist/agents/memory.d.ts.map +1 -0
- package/dist/agents/message.d.ts +50 -1
- package/dist/agents/message.d.ts.map +1 -1
- package/dist/agents/model-loop.d.ts +19 -0
- package/dist/agents/model-loop.d.ts.map +1 -1
- package/dist/agents/model-routing.d.ts +19 -0
- package/dist/agents/model-routing.d.ts.map +1 -0
- package/dist/agents/participants.d.ts +18 -0
- package/dist/agents/participants.d.ts.map +1 -0
- package/dist/agents/reference.d.ts.map +1 -1
- package/dist/agents/request.d.ts +36 -2
- package/dist/agents/request.d.ts.map +1 -1
- package/dist/agents/run-scope.d.ts +51 -0
- package/dist/agents/run-scope.d.ts.map +1 -0
- package/dist/agents/streams/index.d.ts +3 -2
- package/dist/agents/streams/index.d.ts.map +1 -1
- package/dist/agents/streams/index.js +7 -3
- package/dist/agents/streams/index.js.map +1 -1
- package/dist/agents/streams/internal.d.ts +1 -1
- package/dist/agents/streams/internal.d.ts.map +1 -1
- package/dist/agents/streams/internal.js +5 -3
- package/dist/agents/streams/internal.js.map +1 -1
- package/dist/agents/streams/protocol.d.ts +122 -3
- package/dist/agents/streams/protocol.d.ts.map +1 -1
- package/dist/agents/subagent-runs.d.ts +12 -0
- package/dist/agents/subagent-runs.d.ts.map +1 -0
- package/dist/agents/thread-access.d.ts +53 -0
- package/dist/agents/thread-access.d.ts.map +1 -0
- package/dist/agents/tool-definition.d.ts +5 -4
- package/dist/agents/tool-definition.d.ts.map +1 -1
- package/dist/agents/types.d.ts +23 -4
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/validation.d.ts +1 -1
- package/dist/agents/validation.d.ts.map +1 -1
- package/dist/artifacts/access.d.ts +52 -0
- package/dist/artifacts/access.d.ts.map +1 -0
- package/dist/artifacts/canvas.d.ts +92 -0
- package/dist/artifacts/canvas.d.ts.map +1 -0
- package/dist/artifacts/csv.d.ts +5 -0
- package/dist/artifacts/csv.d.ts.map +1 -1
- package/dist/artifacts/errors.d.ts +7 -2
- package/dist/artifacts/errors.d.ts.map +1 -1
- package/dist/artifacts/execution.d.ts +102 -7
- package/dist/artifacts/execution.d.ts.map +1 -1
- package/dist/artifacts/formula/check.d.ts +24 -0
- package/dist/artifacts/formula/check.d.ts.map +1 -0
- package/dist/artifacts/formula/evaluate.d.ts +32 -0
- package/dist/artifacts/formula/evaluate.d.ts.map +1 -0
- package/dist/artifacts/formula/index.d.ts +38 -0
- package/dist/artifacts/formula/index.d.ts.map +1 -0
- package/dist/artifacts/formula/parser.d.ts +67 -0
- package/dist/artifacts/formula/parser.d.ts.map +1 -0
- package/dist/artifacts/frames/assets.d.ts +11 -9
- package/dist/artifacts/frames/assets.d.ts.map +1 -1
- package/dist/artifacts/frames/entries.d.ts +19 -0
- package/dist/artifacts/frames/entries.d.ts.map +1 -0
- package/dist/artifacts/frames/grants.d.ts +6 -6
- package/dist/artifacts/frames/grants.d.ts.map +1 -1
- package/dist/artifacts/frames/index.d.ts +4 -2
- package/dist/artifacts/frames/index.d.ts.map +1 -1
- package/dist/artifacts/frames/index.js +444 -51
- package/dist/artifacts/frames/index.js.map +10 -8
- package/dist/artifacts/frames/kit.d.ts +10 -5
- package/dist/artifacts/frames/kit.d.ts.map +1 -1
- package/dist/artifacts/frames/probe.d.ts +16 -12
- package/dist/artifacts/frames/probe.d.ts.map +1 -1
- package/dist/artifacts/frames/protocol.d.ts +79 -10
- package/dist/artifacts/frames/protocol.d.ts.map +1 -1
- package/dist/artifacts/frames/runtime.d.ts +27 -9
- package/dist/artifacts/frames/runtime.d.ts.map +1 -1
- package/dist/artifacts/index.d.ts +11 -5
- package/dist/artifacts/index.d.ts.map +1 -1
- package/dist/artifacts/index.js +128 -6
- package/dist/artifacts/index.js.map +3 -3
- package/dist/artifacts/kinds.d.ts +1 -1
- package/dist/artifacts/kinds.d.ts.map +1 -1
- package/dist/artifacts/limits.d.ts +30 -0
- package/dist/artifacts/limits.d.ts.map +1 -1
- package/dist/artifacts/live-sheet.d.ts +65 -0
- package/dist/artifacts/live-sheet.d.ts.map +1 -0
- package/dist/artifacts/outline.d.ts +27 -1
- package/dist/artifacts/outline.d.ts.map +1 -1
- package/dist/artifacts/publish/index.d.ts +2 -0
- package/dist/artifacts/publish/index.d.ts.map +1 -1
- package/dist/artifacts/publish/index.js +59 -19
- package/dist/artifacts/publish/index.js.map +1 -1
- package/dist/artifacts/publish/publish.d.ts +43 -11
- package/dist/artifacts/publish/publish.d.ts.map +1 -1
- package/dist/artifacts/publish/queries.d.ts +33 -0
- package/dist/artifacts/publish/queries.d.ts.map +1 -0
- package/dist/artifacts/publish/references.d.ts +6 -3
- package/dist/artifacts/publish/references.d.ts.map +1 -1
- package/dist/artifacts/publish/validate/canvas.d.ts +18 -0
- package/dist/artifacts/publish/validate/canvas.d.ts.map +1 -0
- package/dist/artifacts/publish/validate/html.d.ts +20 -0
- package/dist/artifacts/publish/validate/html.d.ts.map +1 -0
- package/dist/artifacts/publish/validate/page.d.ts +15 -0
- package/dist/artifacts/publish/validate/page.d.ts.map +1 -0
- package/dist/artifacts/publish/validate/sheet.d.ts +11 -3
- package/dist/artifacts/publish/validate/sheet.d.ts.map +1 -1
- package/dist/artifacts/publish/validate/slides.d.ts +1 -7
- package/dist/artifacts/publish/validate/slides.d.ts.map +1 -1
- package/dist/artifacts/queries.d.ts +95 -0
- package/dist/artifacts/queries.d.ts.map +1 -0
- package/dist/artifacts/resolve.d.ts +6 -0
- package/dist/artifacts/resolve.d.ts.map +1 -1
- package/dist/artifacts/run-query.d.ts +26 -0
- package/dist/artifacts/run-query.d.ts.map +1 -0
- package/dist/artifacts/serialize-query.d.ts +12 -0
- package/dist/artifacts/serialize-query.d.ts.map +1 -0
- package/dist/artifacts/sheet-rules.d.ts +26 -0
- package/dist/artifacts/sheet-rules.d.ts.map +1 -0
- package/dist/artifacts/tones.d.ts +8 -0
- package/dist/artifacts/tones.d.ts.map +1 -0
- package/dist/artifacts/workbook.d.ts +76 -5
- package/dist/artifacts/workbook.d.ts.map +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +14 -11
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/member-events.d.ts +13 -0
- package/dist/auth/member-events.d.ts.map +1 -0
- package/dist/auth/profile.d.ts +11 -0
- package/dist/auth/profile.d.ts.map +1 -0
- package/dist/auth/runtime.d.ts +31 -3
- package/dist/auth/runtime.d.ts.map +1 -1
- package/dist/auth/strategy.d.ts +3 -1
- package/dist/auth/strategy.d.ts.map +1 -1
- package/dist/auth/strategy.js +7 -3
- package/dist/auth/strategy.js.map +1 -1
- package/dist/auth/types.d.ts +30 -1
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/authorization/decision.d.ts +15 -0
- package/dist/authorization/decision.d.ts.map +1 -1
- package/dist/authorization/event-visibility.d.ts +5 -1
- package/dist/authorization/event-visibility.d.ts.map +1 -1
- package/dist/authorization/grant-kinds.d.ts +2 -2
- package/dist/authorization/grant-kinds.d.ts.map +1 -1
- package/dist/authorization/index.d.ts +2 -2
- package/dist/authorization/index.d.ts.map +1 -1
- package/dist/authorization/index.js +12 -7
- package/dist/authorization/index.js.map +1 -1
- package/dist/authorization/resolve.d.ts +19 -1
- package/dist/authorization/resolve.d.ts.map +1 -1
- package/dist/authorization/run-visibility.d.ts +8 -1
- package/dist/authorization/run-visibility.d.ts.map +1 -1
- package/dist/authorization/types.d.ts +14 -0
- package/dist/authorization/types.d.ts.map +1 -1
- package/dist/bootstrap/index.js +69 -65
- package/dist/bootstrap/index.js.map +2 -2
- package/dist/{chunk-ky3j490c.js → chunk-02bzjgnt.js} +6 -6
- package/dist/{chunk-ky3j490c.js.map → chunk-02bzjgnt.js.map} +1 -1
- package/dist/{chunk-mfs23znk.js → chunk-07kkp2e1.js} +1 -1
- package/dist/{chunk-c1rxbz5y.js → chunk-098anw4f.js} +21 -19
- package/dist/chunk-098anw4f.js.map +12 -0
- package/dist/{chunk-z58tm0hm.js → chunk-0phpbbvm.js} +3 -3
- package/dist/{chunk-ere85b8y.js → chunk-0xmt5p5y.js} +116 -27
- package/dist/chunk-0xmt5p5y.js.map +14 -0
- package/dist/{chunk-t6f3tdnr.js → chunk-16a9dmfy.js} +33 -2
- package/dist/{chunk-t6f3tdnr.js.map → chunk-16a9dmfy.js.map} +5 -4
- package/dist/chunk-18sk89cg.js +47 -0
- package/dist/chunk-18sk89cg.js.map +10 -0
- package/dist/{chunk-e17zdm62.js → chunk-1t6k1avb.js} +1 -1
- package/dist/chunk-2626mh4m.js +693 -0
- package/dist/chunk-2626mh4m.js.map +19 -0
- package/dist/{chunk-qczk96d9.js → chunk-2adz0h75.js} +13 -4
- package/dist/chunk-2adz0h75.js.map +11 -0
- package/dist/{chunk-kge7k6ey.js → chunk-2fn60nvs.js} +2 -2
- package/dist/{chunk-99nd4rc1.js → chunk-2gjj5dx3.js} +5 -4
- package/dist/{chunk-99nd4rc1.js.map → chunk-2gjj5dx3.js.map} +3 -3
- package/dist/{chunk-mjddfa7k.js → chunk-3fqxbn31.js} +2 -24
- package/dist/{chunk-mjddfa7k.js.map → chunk-3fqxbn31.js.map} +3 -4
- package/dist/{chunk-y0c4e6ex.js → chunk-3gbefjg5.js} +1 -1
- package/dist/{chunk-5hx48dnn.js → chunk-45ngkxkp.js} +52 -31
- package/dist/chunk-45ngkxkp.js.map +13 -0
- package/dist/{chunk-cy4mbddw.js → chunk-48jezz3j.js} +1 -1
- package/dist/{chunk-561r0yc9.js → chunk-4b26qwbg.js} +13 -13
- package/dist/{chunk-561r0yc9.js.map → chunk-4b26qwbg.js.map} +1 -1
- package/dist/{chunk-9k93ah50.js → chunk-4f3ydv7t.js} +33 -69
- package/dist/chunk-4f3ydv7t.js.map +10 -0
- package/dist/chunk-4y26vs3v.js +97 -0
- package/dist/chunk-4y26vs3v.js.map +10 -0
- package/dist/{chunk-4as3wt1c.js → chunk-4ymrcdbm.js} +7 -3
- package/dist/chunk-4ymrcdbm.js.map +12 -0
- package/dist/{chunk-hcbyfxbe.js → chunk-5grk14e5.js} +76 -2
- package/dist/{chunk-hcbyfxbe.js.map → chunk-5grk14e5.js.map} +4 -3
- package/dist/{chunk-8frc8a4j.js → chunk-65pyhyas.js} +90 -83
- package/dist/chunk-65pyhyas.js.map +20 -0
- package/dist/{chunk-hwksyjks.js → chunk-661ezhks.js} +182 -6
- package/dist/chunk-661ezhks.js.map +11 -0
- package/dist/{chunk-447a5c0p.js → chunk-6n69k945.js} +2 -2
- package/dist/{chunk-0bphap9y.js → chunk-6p0pastb.js} +5 -5
- package/dist/{chunk-9j4jw7as.js → chunk-6rrtzea3.js} +18 -5
- package/dist/chunk-6rrtzea3.js.map +14 -0
- package/dist/{chunk-431pyp2c.js → chunk-6y0mkhex.js} +2 -2
- package/dist/{chunk-f4pamkt9.js → chunk-73v685wb.js} +10 -10
- package/dist/{chunk-f4pamkt9.js.map → chunk-73v685wb.js.map} +3 -3
- package/dist/{chunk-akzryx9h.js → chunk-7gr4j2eq.js} +7836 -5047
- package/dist/chunk-7gr4j2eq.js.map +120 -0
- package/dist/{chunk-bk9svbcq.js → chunk-7mc2wkre.js} +386 -86
- package/dist/chunk-7mc2wkre.js.map +50 -0
- package/dist/{chunk-6rqgmkde.js → chunk-7z5p905k.js} +335 -703
- package/dist/chunk-7z5p905k.js.map +22 -0
- package/dist/{chunk-yxd3nnqt.js → chunk-9mab3dvg.js} +26 -2
- package/dist/chunk-9mab3dvg.js.map +11 -0
- package/dist/chunk-9wr3yajk.js +42 -0
- package/dist/chunk-9wr3yajk.js.map +10 -0
- package/dist/chunk-az47zep4.js +41 -0
- package/dist/chunk-az47zep4.js.map +10 -0
- package/dist/{chunk-s7jg7pmn.js → chunk-bab05bhg.js} +1 -1
- package/dist/{chunk-858emn8m.js → chunk-bktev1ds.js} +14 -11
- package/dist/{chunk-858emn8m.js.map → chunk-bktev1ds.js.map} +3 -3
- package/dist/{chunk-dhcv7yxc.js → chunk-c0vk1djt.js} +5 -3
- package/dist/chunk-c0vk1djt.js.map +11 -0
- package/dist/chunk-c69nj7se.js +3 -0
- package/dist/{chunk-7n30ybym.js.map → chunk-c69nj7se.js.map} +1 -1
- package/dist/{chunk-q5e5tv4b.js → chunk-c844dkwd.js} +1 -1
- package/dist/{chunk-g257jwnc.js → chunk-cdk3egjj.js} +17 -4
- package/dist/chunk-cdk3egjj.js.map +12 -0
- package/dist/chunk-cswhawa2.js +113 -0
- package/dist/chunk-cswhawa2.js.map +10 -0
- package/dist/{chunk-cfj9dfbb.js → chunk-d2m879s4.js} +2 -2
- package/dist/{chunk-arns890k.js → chunk-d7vyc7k6.js} +2 -2
- package/dist/chunk-d7vyc7k6.js.map +10 -0
- package/dist/{chunk-q7gn29y3.js → chunk-dp0cdtj2.js} +2 -2
- package/dist/{chunk-6x0pqh32.js → chunk-e5wf5vz0.js} +3 -1
- package/dist/chunk-e5wf5vz0.js.map +10 -0
- package/dist/{chunk-cn0fwwhy.js → chunk-efmm01gj.js} +108 -1045
- package/dist/chunk-efmm01gj.js.map +18 -0
- package/dist/{chunk-918wwnaa.js → chunk-ezne9wc9.js} +1224 -430
- package/dist/chunk-ezne9wc9.js.map +71 -0
- package/dist/{chunk-tbc1ngpd.js → chunk-fe8zwt8b.js} +58 -12
- package/dist/{chunk-tbc1ngpd.js.map → chunk-fe8zwt8b.js.map} +5 -4
- package/dist/{chunk-br3k6qbf.js → chunk-fm62y49k.js} +1 -1
- package/dist/{chunk-nq6gpjt7.js → chunk-fntqb7qy.js} +30 -4
- package/dist/{chunk-nq6gpjt7.js.map → chunk-fntqb7qy.js.map} +5 -5
- package/dist/{chunk-1cc1xaf3.js → chunk-fp2kq35z.js} +26 -10
- package/dist/{chunk-1cc1xaf3.js.map → chunk-fp2kq35z.js.map} +5 -5
- package/dist/{chunk-vvxtn22d.js → chunk-g663fahq.js} +2 -2
- package/dist/{chunk-k43ct2ke.js → chunk-gvj5cd3b.js} +16 -9
- package/dist/chunk-gvj5cd3b.js.map +12 -0
- package/dist/{chunk-rmakanzx.js → chunk-h33shhq6.js} +5 -5
- package/dist/{chunk-nn5xnx3s.js → chunk-h3pbv7n8.js} +1738 -38
- package/dist/chunk-h3pbv7n8.js.map +48 -0
- package/dist/chunk-hn2r7z41.js.map +1 -1
- package/dist/{chunk-pbcbn83d.js → chunk-hqsp2sx4.js} +54 -8
- package/dist/chunk-hqsp2sx4.js.map +14 -0
- package/dist/{chunk-d09e3rax.js → chunk-hwarjrgf.js} +1 -1
- package/dist/{chunk-vf57cr4t.js → chunk-hyesv9dv.js} +1 -1
- package/dist/chunk-hz5d43gn.js +45 -0
- package/dist/chunk-hz5d43gn.js.map +10 -0
- package/dist/{chunk-91mg3nj9.js → chunk-j936th07.js} +86 -41
- package/dist/chunk-j936th07.js.map +12 -0
- package/dist/chunk-kcqpk9w1.js +75 -0
- package/dist/chunk-kcqpk9w1.js.map +10 -0
- package/dist/{chunk-5vems3nx.js → chunk-m2nevja0.js} +2 -2
- package/dist/{chunk-x9v4cx1d.js → chunk-m36fw8ft.js} +1 -1
- package/dist/{chunk-a40ad1ft.js → chunk-mbsbxarb.js} +1 -1
- package/dist/chunk-mzx71snp.js +129 -0
- package/dist/chunk-mzx71snp.js.map +10 -0
- package/dist/{chunk-6aawea28.js → chunk-n8q5j6y5.js} +1 -1
- package/dist/{chunk-d7dnxdep.js → chunk-n9zpx9c6.js} +4 -4
- package/dist/{chunk-xvsc5m8n.js → chunk-npcr0228.js} +1 -1
- package/dist/chunk-nydf3dbe.js +663 -0
- package/dist/chunk-nydf3dbe.js.map +13 -0
- package/dist/chunk-pdt5cw8z.js +233 -0
- package/dist/chunk-pdt5cw8z.js.map +11 -0
- package/dist/{chunk-rj69qcrd.js → chunk-pgrf64hp.js} +55 -7
- package/dist/chunk-pgrf64hp.js.map +12 -0
- package/dist/{chunk-y5tah2kf.js → chunk-q4pmvkg0.js} +1 -1
- package/dist/chunk-qhqgp4jf.js +1418 -0
- package/dist/chunk-qhqgp4jf.js.map +22 -0
- package/dist/{chunk-48qjhh6v.js → chunk-qx00vjrj.js} +19 -60
- package/dist/chunk-qx00vjrj.js.map +13 -0
- package/dist/{chunk-5948n82c.js → chunk-r6szek0x.js} +184 -7
- package/dist/chunk-r6szek0x.js.map +10 -0
- package/dist/{chunk-v4jbb3rs.js → chunk-rap5w0x0.js} +156 -2
- package/dist/chunk-rap5w0x0.js.map +10 -0
- package/dist/{chunk-pfp1txq2.js → chunk-sgx82nnt.js} +5 -31
- package/dist/{chunk-pfp1txq2.js.map → chunk-sgx82nnt.js.map} +3 -4
- package/dist/{chunk-bkpke1sg.js → chunk-t5608tkq.js} +3 -1
- package/dist/{chunk-bkpke1sg.js.map → chunk-t5608tkq.js.map} +3 -3
- package/dist/{chunk-29yx306f.js → chunk-tdxfsg1c.js} +507 -265
- package/dist/chunk-tdxfsg1c.js.map +23 -0
- package/dist/{chunk-d5rjr8c0.js → chunk-vabga7fk.js} +1 -1
- package/dist/{chunk-dhdha526.js → chunk-vhbw5sqm.js} +26 -2
- package/dist/chunk-vhbw5sqm.js.map +10 -0
- package/dist/{chunk-e6k4thh5.js → chunk-vpgwq5nf.js} +98 -12
- package/dist/chunk-vpgwq5nf.js.map +21 -0
- package/dist/{chunk-61y5xs4p.js → chunk-vyt322b6.js} +69 -50
- package/dist/{chunk-61y5xs4p.js.map → chunk-vyt322b6.js.map} +4 -4
- package/dist/chunk-waqk73p1.js +2380 -0
- package/dist/chunk-waqk73p1.js.map +23 -0
- package/dist/chunk-wsc1brye.js +27 -0
- package/dist/chunk-wsc1brye.js.map +10 -0
- package/dist/{chunk-96yw3pwd.js → chunk-y7dbmaqh.js} +28 -2
- package/dist/chunk-y7dbmaqh.js.map +10 -0
- package/dist/{chunk-6vb4st8k.js → chunk-yc9ners4.js} +120 -19
- package/dist/{chunk-6vb4st8k.js.map → chunk-yc9ners4.js.map} +8 -8
- package/dist/{chunk-dvd2fp9q.js → chunk-zbc929zg.js} +28 -4
- package/dist/chunk-zbc929zg.js.map +13 -0
- package/dist/chunk-zrvhsq7f.js +37 -0
- package/dist/chunk-zrvhsq7f.js.map +10 -0
- package/dist/datasets/write.js +5 -5
- package/dist/error-reporting/internal.js +3 -3
- package/dist/errors/catalog.d.ts +26 -0
- package/dist/errors/catalog.d.ts.map +1 -1
- package/dist/errors/internal.d.ts.map +1 -1
- package/dist/errors/internal.js +1 -1
- package/dist/events/definitions.d.ts +7 -0
- package/dist/events/definitions.d.ts.map +1 -1
- package/dist/events/execution.d.ts.map +1 -1
- package/dist/events/index.d.ts +2 -3
- package/dist/events/index.d.ts.map +1 -1
- package/dist/events/index.js +8 -10
- package/dist/events/index.js.map +1 -1
- package/dist/events/scope.d.ts.map +1 -1
- package/dist/events/scope.js +1 -1
- package/dist/events/selectors/builder.d.ts +12 -1
- package/dist/events/selectors/builder.d.ts.map +1 -1
- package/dist/events/selectors/index.d.ts +2 -2
- package/dist/events/selectors/index.d.ts.map +1 -1
- package/dist/events/selectors/index.js +2 -2
- package/dist/events/selectors/types.d.ts +19 -3
- package/dist/events/selectors/types.d.ts.map +1 -1
- package/dist/events/service.d.ts +17 -2
- package/dist/events/service.d.ts.map +1 -1
- package/dist/events/types/index.d.ts +3 -1
- package/dist/events/types/index.d.ts.map +1 -1
- package/dist/events/types/users.d.ts +63 -0
- package/dist/events/types/users.d.ts.map +1 -0
- package/dist/events/view-conditions.d.ts +34 -0
- package/dist/events/view-conditions.d.ts.map +1 -0
- package/dist/execution/agent.d.ts +15 -0
- package/dist/execution/agent.d.ts.map +1 -1
- package/dist/execution/agent.js +63 -57
- package/dist/execution/agent.js.map +1 -1
- package/dist/execution/authorization.d.ts.map +1 -1
- package/dist/execution/authorized-object-reader.d.ts +51 -2
- package/dist/execution/authorized-object-reader.d.ts.map +1 -1
- package/dist/execution/lineage.d.ts +7 -0
- package/dist/execution/lineage.d.ts.map +1 -0
- package/dist/execution/object-reader-ontology.d.ts +2 -2
- package/dist/execution/object-reader-ontology.d.ts.map +1 -1
- package/dist/execution/object-reader-security.d.ts +24 -3
- package/dist/execution/object-reader-security.d.ts.map +1 -1
- package/dist/execution/object-reader-users.d.ts +20 -0
- package/dist/execution/object-reader-users.d.ts.map +1 -0
- package/dist/execution/preparation.d.ts +23 -0
- package/dist/execution/preparation.d.ts.map +1 -0
- package/dist/execution/primitive.js +61 -57
- package/dist/execution/primitive.js.map +1 -1
- package/dist/execution/request.d.ts +2 -1
- package/dist/execution/request.d.ts.map +1 -1
- package/dist/execution/request.js +64 -56
- package/dist/execution/request.js.map +3 -3
- package/dist/execution/unique-lookup.d.ts +14 -0
- package/dist/execution/unique-lookup.d.ts.map +1 -0
- package/dist/execution/visible-objects.d.ts +12 -0
- package/dist/execution/visible-objects.d.ts.map +1 -0
- package/dist/http/api-routes.d.ts +17 -0
- package/dist/http/api-routes.d.ts.map +1 -1
- package/dist/http/index.js +1 -1
- package/dist/index.d.ts +32 -15
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +137 -126
- package/dist/index.js.map +1 -1
- package/dist/lake-storage/index.js +5 -5
- package/dist/materialization/errors.d.ts +25 -0
- package/dist/materialization/errors.d.ts.map +1 -1
- package/dist/materialization/event-envelopes.d.ts +5 -0
- package/dist/materialization/event-envelopes.d.ts.map +1 -1
- package/dist/materialization/index.d.ts +1 -1
- package/dist/materialization/index.d.ts.map +1 -1
- package/dist/materialization/index.js +14 -8
- package/dist/materialization/index.js.map +1 -1
- package/dist/materialization/model.d.ts +20 -2
- package/dist/materialization/model.d.ts.map +1 -1
- package/dist/materializer/edits/commit.d.ts.map +1 -1
- package/dist/materializer/edits/load-state.d.ts +5 -1
- package/dist/materializer/edits/load-state.d.ts.map +1 -1
- package/dist/materializer/edits/plan.d.ts.map +1 -1
- package/dist/materializer/edits/unique-values.d.ts +47 -0
- package/dist/materializer/edits/unique-values.d.ts.map +1 -0
- package/dist/materializer/edits/working-state.d.ts +6 -1
- package/dist/materializer/edits/working-state.d.ts.map +1 -1
- package/dist/materializer/execution/work-records.d.ts +7 -1
- package/dist/materializer/execution/work-records.d.ts.map +1 -1
- package/dist/materializer/index.js +45 -41
- package/dist/materializer/index.js.map +1 -1
- package/dist/materializer/projections/replacement-plan.d.ts.map +1 -1
- package/dist/materializer/projections/source-materialization.d.ts +1 -0
- package/dist/materializer/projections/source-materialization.d.ts.map +1 -1
- package/dist/materializer/shared/normalize.d.ts.map +1 -1
- package/dist/materializer/shared/projection-run.d.ts +0 -1
- package/dist/materializer/shared/projection-run.d.ts.map +1 -1
- package/dist/materializer/telemetry/plan.d.ts.map +1 -1
- package/dist/models/audio/catalog.d.ts +13 -1
- package/dist/models/audio/catalog.d.ts.map +1 -1
- package/dist/models/audio/errors.d.ts +6 -1
- package/dist/models/audio/errors.d.ts.map +1 -1
- package/dist/models/audio/runtime.d.ts.map +1 -1
- package/dist/models/audio/speech.d.ts +8 -0
- package/dist/models/audio/speech.d.ts.map +1 -0
- package/dist/models/audio/types.d.ts +93 -0
- package/dist/models/audio/types.d.ts.map +1 -1
- package/dist/models/calls.d.ts +27 -0
- package/dist/models/calls.d.ts.map +1 -0
- package/dist/models/catalog-index.d.ts +7 -4
- package/dist/models/catalog-index.d.ts.map +1 -1
- package/dist/models/catalog.d.ts +55 -3
- package/dist/models/catalog.d.ts.map +1 -1
- package/dist/models/decision/runtime.d.ts +6 -1
- package/dist/models/decision/runtime.d.ts.map +1 -1
- package/dist/models/decision/validation.d.ts +4 -1
- package/dist/models/decision/validation.d.ts.map +1 -1
- package/dist/models/definitions.d.ts +23 -1
- package/dist/models/definitions.d.ts.map +1 -1
- package/dist/models/events.d.ts +12 -1
- package/dist/models/events.d.ts.map +1 -1
- package/dist/models/execution/binding.d.ts +3 -1
- package/dist/models/execution/binding.d.ts.map +1 -1
- package/dist/models/execution/index.d.ts +1 -0
- package/dist/models/execution/index.d.ts.map +1 -1
- package/dist/models/execution/index.js +44 -34
- package/dist/models/execution/index.js.map +1 -1
- package/dist/models/execution/model-call-accounting.d.ts.map +1 -1
- package/dist/models/execution/model-call-recorder.d.ts +3 -0
- package/dist/models/execution/model-call-recorder.d.ts.map +1 -1
- package/dist/models/execution/usage.d.ts.map +1 -1
- package/dist/models/execution.d.ts +4 -2
- package/dist/models/execution.d.ts.map +1 -1
- package/dist/models/generation-types.d.ts +8 -1
- package/dist/models/generation-types.d.ts.map +1 -1
- package/dist/models/image/catalog.d.ts +13 -0
- package/dist/models/image/catalog.d.ts.map +1 -0
- package/dist/models/image/errors.d.ts +8 -0
- package/dist/models/image/errors.d.ts.map +1 -0
- package/dist/models/image/runtime.d.ts +8 -0
- package/dist/models/image/runtime.d.ts.map +1 -0
- package/dist/models/image/types.d.ts +103 -0
- package/dist/models/image/types.d.ts.map +1 -0
- package/dist/models/index.d.ts +12 -8
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +17 -7
- package/dist/models/index.js.map +1 -1
- package/dist/models/input-file.d.ts +9 -0
- package/dist/models/input-file.d.ts.map +1 -0
- package/dist/models/language-model.d.ts +13 -0
- package/dist/models/language-model.d.ts.map +1 -1
- package/dist/models/pricing.d.ts +25 -10
- package/dist/models/pricing.d.ts.map +1 -1
- package/dist/models/rate-card.d.ts +44 -6
- package/dist/models/rate-card.d.ts.map +1 -1
- package/dist/objects/conditional-writes.d.ts +37 -0
- package/dist/objects/conditional-writes.d.ts.map +1 -0
- package/dist/objects/execution.d.ts +2 -0
- package/dist/objects/execution.d.ts.map +1 -1
- package/dist/objects/index.d.ts +1 -0
- package/dist/objects/index.d.ts.map +1 -1
- package/dist/objects/index.js +68 -58
- package/dist/objects/index.js.map +1 -1
- package/dist/objects/link/authorization.d.ts +3 -0
- package/dist/objects/link/authorization.d.ts.map +1 -1
- package/dist/objects/link/endpoints.d.ts +21 -2
- package/dist/objects/link/endpoints.d.ts.map +1 -1
- package/dist/objects/link/remove.d.ts.map +1 -1
- package/dist/objects/link/upsert-batch.d.ts.map +1 -1
- package/dist/objects/link/upsert.d.ts.map +1 -1
- package/dist/objects/materializer-adapter.d.ts +13 -4
- package/dist/objects/materializer-adapter.d.ts.map +1 -1
- package/dist/objects/object/delete.d.ts +3 -0
- package/dist/objects/object/delete.d.ts.map +1 -1
- package/dist/objects/object/upsert-batch.d.ts.map +1 -1
- package/dist/objects/object/upsert.d.ts.map +1 -1
- package/dist/objects/query/current-user.d.ts +17 -0
- package/dist/objects/query/current-user.d.ts.map +1 -0
- package/dist/objects/query/executor.d.ts +14 -0
- package/dist/objects/query/executor.d.ts.map +1 -1
- package/dist/objects/query/index.d.ts +2 -2
- package/dist/objects/query/index.d.ts.map +1 -1
- package/dist/objects/query/index.js +49 -44
- package/dist/objects/query/index.js.map +1 -1
- package/dist/objects/query/ir.d.ts +19 -1
- package/dist/objects/query/ir.d.ts.map +1 -1
- package/dist/objects/query/matches-predicate.d.ts +9 -0
- package/dist/objects/query/matches-predicate.d.ts.map +1 -0
- package/dist/objects/query/normalize.d.ts.map +1 -1
- package/dist/objects/query/user-expansions.d.ts +27 -0
- package/dist/objects/query/user-expansions.d.ts.map +1 -0
- package/dist/objects/query/validate.d.ts.map +1 -1
- package/dist/objects/runtime-batch.d.ts +3 -1
- package/dist/objects/runtime-batch.d.ts.map +1 -1
- package/dist/objects/sdk/object-set.d.ts.map +1 -1
- package/dist/objects/sdk/query-executor.d.ts +6 -0
- package/dist/objects/sdk/query-executor.d.ts.map +1 -1
- package/dist/objects/serialize.d.ts +39 -0
- package/dist/objects/serialize.d.ts.map +1 -0
- package/dist/objects/unique-violation.d.ts +22 -0
- package/dist/objects/unique-violation.d.ts.map +1 -0
- package/dist/ontology/builders.d.ts +3 -1
- package/dist/ontology/builders.d.ts.map +1 -1
- package/dist/ontology/index.d.ts +2 -2
- package/dist/ontology/index.d.ts.map +1 -1
- package/dist/ontology/index.js +11 -7
- package/dist/ontology/index.js.map +1 -1
- package/dist/ontology/internal.js +7 -5
- package/dist/ontology/internal.js.map +3 -3
- package/dist/ontology/json-schema.d.ts.map +1 -1
- package/dist/ontology/primitives.d.ts +3 -0
- package/dist/ontology/primitives.d.ts.map +1 -1
- package/dist/ontology/registry.d.ts +6 -0
- package/dist/ontology/registry.d.ts.map +1 -1
- package/dist/ontology/types.d.ts +9 -0
- package/dist/ontology/types.d.ts.map +1 -1
- package/dist/ontology/unique-values.d.ts +26 -0
- package/dist/ontology/unique-values.d.ts.map +1 -0
- package/dist/ontology/user-ref.d.ts +23 -0
- package/dist/ontology/user-ref.d.ts.map +1 -1
- package/dist/ontology/validation/properties.d.ts.map +1 -1
- package/dist/ontology/validation/schema.d.ts.map +1 -1
- package/dist/pipelines/index.js +43 -40
- package/dist/pipelines/index.js.map +1 -1
- package/dist/projections/internal.js +36 -33
- package/dist/projections/internal.js.map +1 -1
- package/dist/projections/registry.d.ts +4 -0
- package/dist/projections/registry.d.ts.map +1 -1
- package/dist/projections/revision.d.ts +15 -0
- package/dist/projections/revision.d.ts.map +1 -1
- package/dist/projections/run-dispatch.d.ts.map +1 -1
- package/dist/projections/types.d.ts +2 -0
- package/dist/projections/types.d.ts.map +1 -1
- package/dist/query.d.ts +4 -2
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +2 -2
- package/dist/rules/execution.d.ts.map +1 -1
- package/dist/runtime/ai-cost.d.ts +2 -0
- package/dist/runtime/ai-cost.d.ts.map +1 -1
- package/dist/runtime/ai-usage.d.ts +7 -0
- package/dist/runtime/ai-usage.d.ts.map +1 -1
- package/dist/runtime/host.d.ts.map +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/internal.js +42 -38
- package/dist/runtime/internal.js.map +1 -1
- package/dist/runtime/resolve-definitions.d.ts.map +1 -1
- package/dist/runtime/sixb.d.ts +2 -0
- package/dist/runtime/sixb.d.ts.map +1 -1
- package/dist/runtime/types.d.ts +66 -8
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/sandboxes/index.js +7 -6
- package/dist/sandboxes/index.js.map +1 -1
- package/dist/schedules/builders.d.ts.map +1 -1
- package/dist/schedules/index.js +3 -3
- package/dist/schedules/runtime.d.ts.map +1 -1
- package/dist/schedules/validation.d.ts.map +1 -1
- package/dist/security/grants.d.ts +12 -4
- package/dist/security/grants.d.ts.map +1 -1
- package/dist/security/index.d.ts +1 -1
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/internal.js +1 -1
- package/dist/security/project.d.ts +4 -1
- package/dist/security/project.d.ts.map +1 -1
- package/dist/security/public.js +2 -2
- package/dist/security/registry.d.ts +6 -0
- package/dist/security/registry.d.ts.map +1 -1
- package/dist/security/types.d.ts +47 -9
- package/dist/security/types.d.ts.map +1 -1
- package/dist/security/validation.d.ts.map +1 -1
- package/dist/security/view-conditions.d.ts +37 -0
- package/dist/security/view-conditions.d.ts.map +1 -0
- package/dist/shares/execution.d.ts.map +1 -1
- package/dist/shares/internal.js +34 -31
- package/dist/shares/internal.js.map +2 -2
- package/dist/storage/action-runs/failure.js +2 -2
- package/dist/storage/action-runs/provider.js +1 -1
- package/dist/storage/action-runs/types.d.ts +1 -1
- package/dist/storage/action-runs/types.d.ts.map +1 -1
- package/dist/storage/agents/errors.d.ts +3 -1
- package/dist/storage/agents/errors.d.ts.map +1 -1
- package/dist/storage/agents/in-memory.d.ts +120 -3
- package/dist/storage/agents/in-memory.d.ts.map +1 -1
- package/dist/storage/agents/index.d.ts +2 -2
- package/dist/storage/agents/index.d.ts.map +1 -1
- package/dist/storage/agents/provider.d.ts +154 -4
- package/dist/storage/agents/provider.d.ts.map +1 -1
- package/dist/storage/agents/provider.js +60 -5
- package/dist/storage/agents/provider.js.map +1 -1
- package/dist/storage/agents/types.d.ts +565 -13
- package/dist/storage/agents/types.d.ts.map +1 -1
- package/dist/storage/ai-cost/analytics.d.ts +10 -1
- package/dist/storage/ai-cost/analytics.d.ts.map +1 -1
- package/dist/storage/ai-cost/groups.d.ts +9 -0
- package/dist/storage/ai-cost/groups.d.ts.map +1 -1
- package/dist/storage/ai-cost/index.d.ts +1 -1
- package/dist/storage/ai-cost/index.d.ts.map +1 -1
- package/dist/storage/ai-cost/provider.d.ts +2 -1
- package/dist/storage/ai-cost/provider.d.ts.map +1 -1
- package/dist/storage/ai-cost/provider.js +11 -5
- package/dist/storage/ai-cost/provider.js.map +1 -1
- package/dist/storage/ai-cost/types.d.ts +14 -2
- package/dist/storage/ai-cost/types.d.ts.map +1 -1
- package/dist/storage/ai-cost/validation.d.ts.map +1 -1
- package/dist/storage/ai-limits/enforcement.js +5 -4
- package/dist/storage/ai-limits/enforcement.js.map +1 -1
- package/dist/storage/ai-limits/provider.d.ts +1 -1
- package/dist/storage/ai-limits/provider.d.ts.map +1 -1
- package/dist/storage/ai-limits/provider.js +3 -2
- package/dist/storage/ai-limits/provider.js.map +1 -1
- package/dist/storage/ai-usage/in-memory.d.ts +5 -1
- package/dist/storage/ai-usage/in-memory.d.ts.map +1 -1
- package/dist/storage/ai-usage/index.d.ts +2 -2
- package/dist/storage/ai-usage/index.d.ts.map +1 -1
- package/dist/storage/ai-usage/record.d.ts +5 -1
- package/dist/storage/ai-usage/record.d.ts.map +1 -1
- package/dist/storage/ai-usage/types.d.ts +33 -0
- package/dist/storage/ai-usage/types.d.ts.map +1 -1
- package/dist/storage/ai-usage/usage.d.ts +2 -0
- package/dist/storage/ai-usage/usage.d.ts.map +1 -1
- package/dist/storage/artifacts/errors.d.ts +12 -2
- package/dist/storage/artifacts/errors.d.ts.map +1 -1
- package/dist/storage/artifacts/in-memory.d.ts +23 -2
- package/dist/storage/artifacts/in-memory.d.ts.map +1 -1
- package/dist/storage/artifacts/index.d.ts +2 -2
- package/dist/storage/artifacts/index.d.ts.map +1 -1
- package/dist/storage/artifacts/record.d.ts +19 -2
- package/dist/storage/artifacts/record.d.ts.map +1 -1
- package/dist/storage/artifacts/types.d.ts +87 -8
- package/dist/storage/artifacts/types.d.ts.map +1 -1
- package/dist/storage/auth/in-memory/auth-storage.d.ts +3 -2
- package/dist/storage/auth/in-memory/auth-storage.d.ts.map +1 -1
- package/dist/storage/auth/in-memory/users.d.ts +7 -3
- package/dist/storage/auth/in-memory/users.d.ts.map +1 -1
- package/dist/storage/auth/index.d.ts +1 -1
- package/dist/storage/auth/index.d.ts.map +1 -1
- package/dist/storage/auth/types.d.ts +40 -9
- package/dist/storage/auth/types.d.ts.map +1 -1
- package/dist/storage/connector-connections/provider.js +1 -1
- package/dist/storage/executions/in-memory.d.ts +2 -1
- package/dist/storage/executions/in-memory.d.ts.map +1 -1
- package/dist/storage/executions/index.d.ts +1 -1
- package/dist/storage/executions/index.d.ts.map +1 -1
- package/dist/storage/executions/types.d.ts +15 -0
- package/dist/storage/executions/types.d.ts.map +1 -1
- package/dist/storage/file-upload-sessions/provider.js +15 -12
- package/dist/storage/file-upload-sessions/provider.js.map +1 -1
- package/dist/storage/index.d.ts +13 -11
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/index.js +50 -39
- package/dist/storage/index.js.map +1 -1
- package/dist/storage/internal.d.ts +2 -2
- package/dist/storage/internal.d.ts.map +1 -1
- package/dist/storage/internal.js +19 -8
- package/dist/storage/internal.js.map +1 -1
- package/dist/storage/migrations/migrate-storage.d.ts +4 -1
- package/dist/storage/migrations/migrate-storage.d.ts.map +1 -1
- package/dist/storage/migrations/prepare-unique-properties.d.ts +18 -0
- package/dist/storage/migrations/prepare-unique-properties.d.ts.map +1 -0
- package/dist/storage/objects/guard.d.ts +1 -1
- package/dist/storage/objects/guard.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/conditional-reader.d.ts +5 -0
- package/dist/storage/objects/in-memory/conditional-reader.d.ts.map +1 -0
- package/dist/storage/objects/in-memory/query.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/read-scope.d.ts +3 -9
- package/dist/storage/objects/in-memory/read-scope.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/read-source.d.ts +10 -1
- package/dist/storage/objects/in-memory/read-source.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/scoped-reader.d.ts +14 -0
- package/dist/storage/objects/in-memory/scoped-reader.d.ts.map +1 -0
- package/dist/storage/objects/in-memory/selected-reader.d.ts.map +1 -1
- package/dist/storage/objects/in-memory/storage.d.ts +36 -1
- package/dist/storage/objects/in-memory/storage.d.ts.map +1 -1
- package/dist/storage/objects/index.d.ts +2 -2
- package/dist/storage/objects/index.d.ts.map +1 -1
- package/dist/storage/objects/read-scope.d.ts +9 -1
- package/dist/storage/objects/read-scope.d.ts.map +1 -1
- package/dist/storage/objects/types.d.ts +64 -1
- package/dist/storage/objects/types.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/index.d.ts +2 -0
- package/dist/storage/ontology/in-memory/index.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/materializations.d.ts +1 -0
- package/dist/storage/ontology/in-memory/materializations.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/replacement-plans.d.ts.map +1 -1
- package/dist/storage/ontology/in-memory/unique-values.d.ts +32 -0
- package/dist/storage/ontology/in-memory/unique-values.d.ts.map +1 -0
- package/dist/storage/ontology/index.d.ts +4 -1
- package/dist/storage/ontology/index.d.ts.map +1 -1
- package/dist/storage/ontology/materializations.d.ts +34 -1
- package/dist/storage/ontology/materializations.d.ts.map +1 -1
- package/dist/storage/ontology/provider-work.d.ts +15 -2
- package/dist/storage/ontology/provider-work.d.ts.map +1 -1
- package/dist/storage/ontology/provider.d.ts +1 -1
- package/dist/storage/ontology/provider.d.ts.map +1 -1
- package/dist/storage/ontology/provider.js +9 -4
- package/dist/storage/ontology/provider.js.map +1 -1
- package/dist/storage/ontology/unique-values.d.ts +54 -0
- package/dist/storage/ontology/unique-values.d.ts.map +1 -0
- package/dist/storage/operation-scope.d.ts +1 -1
- package/dist/storage/operation-scope.d.ts.map +1 -1
- package/dist/storage/operation-scope.js +1 -1
- package/dist/storage/projection-runs/in-memory.d.ts +0 -6
- package/dist/storage/projection-runs/in-memory.d.ts.map +1 -1
- package/dist/storage/projection-runs/provider.js +2 -2
- package/dist/storage/share-grants/provider.js +4 -3
- package/dist/storage/share-grants/provider.js.map +1 -1
- package/dist/storage/types.d.ts +2 -2
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/storage/workflow-runs/provider.js +15 -12
- package/dist/storage/workflow-runs/provider.js.map +1 -1
- package/dist/syncs/index.js +42 -39
- package/dist/syncs/index.js.map +1 -1
- package/dist/testing/agent-approval-storage-contract.d.ts +17 -0
- package/dist/testing/agent-approval-storage-contract.d.ts.map +1 -0
- package/dist/testing/agent-memory-storage-contract.d.ts +12 -0
- package/dist/testing/agent-memory-storage-contract.d.ts.map +1 -0
- package/dist/testing/agent-storage-contract.d.ts.map +1 -1
- package/dist/testing/ai-cost-storage-contract.d.ts.map +1 -1
- package/dist/testing/ai-limit-storage-contract.d.ts +0 -1
- package/dist/testing/ai-limit-storage-contract.d.ts.map +1 -1
- package/dist/testing/ai-model-call-groups-contract.d.ts.map +1 -1
- package/dist/testing/ai-usage-storage-contract.d.ts.map +1 -1
- package/dist/testing/artifact-storage-contract.d.ts.map +1 -1
- package/dist/testing/auth-storage-contract.d.ts +13 -0
- package/dist/testing/auth-storage-contract.d.ts.map +1 -1
- package/dist/testing/broker-contract.d.ts +5 -0
- package/dist/testing/broker-contract.d.ts.map +1 -1
- package/dist/testing/effective-storage-contract.d.ts.map +1 -1
- package/dist/testing/execution-storage-contract.d.ts.map +1 -1
- package/dist/testing/file-upload-session-storage-contract.d.ts.map +1 -1
- package/dist/testing/index.d.ts +9 -5
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +7938 -3743
- package/dist/testing/index.js.map +29 -25
- package/dist/testing/lake-storage-contract.d.ts.map +1 -1
- package/dist/testing/materializer-storage-contract.d.ts.map +1 -1
- package/dist/testing/object-conditional-read-scope-contract.d.ts +11 -0
- package/dist/testing/object-conditional-read-scope-contract.d.ts.map +1 -0
- package/dist/testing/object-query-contract.d.ts +0 -2
- package/dist/testing/object-query-contract.d.ts.map +1 -1
- package/dist/testing/ontology-storage-contract.d.ts.map +1 -1
- package/dist/testing/projection-run-storage-contract.d.ts.map +1 -1
- package/dist/testing/queues-contract.d.ts +5 -0
- package/dist/testing/queues-contract.d.ts.map +1 -1
- package/dist/testing/sandboxes-contract.d.ts.map +1 -1
- package/dist/testing/share-grant-storage-contract.d.ts.map +1 -1
- package/dist/testing/share-session-storage-contract.d.ts.map +1 -1
- package/dist/testing/unique-values-contract.d.ts +21 -0
- package/dist/testing/unique-values-contract.d.ts.map +1 -0
- package/dist/testing/webhook-execution.d.ts +0 -8
- package/dist/testing/webhook-execution.d.ts.map +1 -1
- package/dist/testing/webhook-run-storage-contract.d.ts.map +1 -1
- package/dist/users/execution.d.ts +40 -0
- package/dist/users/execution.d.ts.map +1 -0
- package/dist/users/index.d.ts +3 -0
- package/dist/users/index.d.ts.map +1 -0
- package/dist/webhooks/internal.js +34 -31
- package/dist/webhooks/internal.js.map +2 -2
- package/dist/workers/index.js +4 -6
- package/dist/workers/index.js.map +4 -4
- package/dist/workers/queue-worker.d.ts +0 -2
- package/dist/workers/queue-worker.d.ts.map +1 -1
- package/dist/workers/worker.d.ts +0 -2
- package/dist/workers/worker.d.ts.map +1 -1
- package/dist/workflows/builders.d.ts.map +1 -1
- package/dist/workflows/index.js +67 -63
- package/dist/workflows/index.js.map +1 -1
- package/dist/workflows/request.d.ts +12 -1
- package/dist/workflows/request.d.ts.map +1 -1
- package/dist/workflows/types.d.ts +6 -2
- package/dist/workflows/types.d.ts.map +1 -1
- package/dist/workflows/validation.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/actions/commit-edits.ts +6 -1
- package/src/actions/execution.ts +42 -15
- package/src/actions/read-facade.ts +33 -0
- package/src/actions/request.ts +224 -71
- package/src/actions/run/context.ts +47 -1
- package/src/actions/run/execute.ts +13 -6
- package/src/actions/run/executor.ts +11 -2
- package/src/actions/run/normalize.ts +12 -2
- package/src/actions/run/phases.ts +2 -0
- package/src/actions/run/run-action.ts +12 -3
- package/src/actions/run/signals.ts +3 -9
- package/src/actions/run/types.ts +17 -1
- package/src/actions/run-authorization.ts +72 -0
- package/src/actions/types/context.ts +20 -3
- package/src/actions/validators.ts +19 -8
- package/src/activity/README.md +5 -2
- package/src/activity/timeline.ts +39 -78
- package/src/agents/accounting.ts +59 -0
- package/src/agents/adapters.ts +10 -0
- package/src/agents/agent-mail.ts +29 -0
- package/src/agents/api-gateway.ts +14 -3
- package/src/agents/approval-continuation.ts +48 -0
- package/src/agents/approval-executor.ts +318 -0
- package/src/agents/approval-outcome.ts +59 -0
- package/src/agents/approvals.ts +566 -0
- package/src/agents/authority.ts +24 -1
- package/src/agents/builders.ts +5 -3
- package/src/agents/cancel.ts +103 -0
- package/src/agents/child-question.ts +46 -0
- package/src/agents/children.ts +404 -0
- package/src/agents/context-compaction.ts +12 -0
- package/src/agents/errors.ts +31 -0
- package/src/agents/execution.ts +788 -90
- package/src/agents/fork.ts +158 -0
- package/src/agents/ids.ts +18 -6
- package/src/agents/index.ts +55 -0
- package/src/agents/memory-execution.ts +186 -0
- package/src/agents/memory.ts +178 -0
- package/src/agents/message.ts +57 -0
- package/src/agents/model-loop.ts +93 -6
- package/src/agents/model-routing.ts +193 -0
- package/src/agents/participants.ts +213 -0
- package/src/agents/reference.ts +2 -0
- package/src/agents/request.ts +398 -69
- package/src/agents/run-scope.ts +134 -0
- package/src/agents/streams/index.ts +5 -0
- package/src/agents/streams/internal.ts +1 -0
- package/src/agents/streams/protocol.ts +385 -7
- package/src/agents/subagent-runs.ts +41 -0
- package/src/agents/thread-access.ts +137 -0
- package/src/agents/tool-definition.ts +5 -3
- package/src/agents/types.ts +35 -10
- package/src/agents/validation.ts +2 -0
- package/src/artifacts/access.ts +125 -0
- package/src/artifacts/canvas.ts +369 -0
- package/src/artifacts/csv.ts +10 -0
- package/src/artifacts/errors.ts +12 -1
- package/src/artifacts/execution.ts +436 -36
- package/src/artifacts/formula/check.ts +171 -0
- package/src/artifacts/formula/evaluate.ts +288 -0
- package/src/artifacts/formula/index.ts +199 -0
- package/src/artifacts/formula/parser.ts +357 -0
- package/src/artifacts/frames/assets.ts +35 -19
- package/src/artifacts/frames/entries.ts +35 -0
- package/src/artifacts/frames/grants.ts +10 -9
- package/src/artifacts/frames/index.ts +8 -2
- package/src/artifacts/frames/kit.ts +191 -14
- package/src/artifacts/frames/probe.ts +66 -18
- package/src/artifacts/frames/protocol.ts +164 -10
- package/src/artifacts/frames/runtime.ts +273 -28
- package/src/artifacts/index.ts +66 -2
- package/src/artifacts/kinds.ts +1 -1
- package/src/artifacts/limits.ts +31 -0
- package/src/artifacts/live-sheet.ts +345 -0
- package/src/artifacts/outline.ts +34 -1
- package/src/artifacts/publish/index.ts +2 -0
- package/src/artifacts/publish/publish.ts +120 -34
- package/src/artifacts/publish/queries.ts +336 -0
- package/src/artifacts/publish/references.ts +18 -13
- package/src/artifacts/publish/validate/canvas.ts +118 -0
- package/src/artifacts/publish/validate/html.ts +78 -0
- package/src/artifacts/publish/validate/page.ts +65 -0
- package/src/artifacts/publish/validate/sheet.ts +115 -69
- package/src/artifacts/publish/validate/slides.ts +11 -63
- package/src/artifacts/queries.ts +512 -0
- package/src/artifacts/resolve.ts +20 -5
- package/src/artifacts/run-query.ts +212 -0
- package/src/artifacts/serialize-query.ts +25 -0
- package/src/artifacts/sheet-rules.ts +180 -0
- package/src/artifacts/tones.ts +20 -0
- package/src/artifacts/workbook.ts +374 -15
- package/src/auth/index.ts +4 -0
- package/src/auth/member-events.ts +114 -0
- package/src/auth/profile.ts +118 -0
- package/src/auth/runtime.ts +190 -9
- package/src/auth/strategy.ts +3 -0
- package/src/auth/types.ts +32 -0
- package/src/authorization/decision.ts +47 -0
- package/src/authorization/event-visibility.ts +17 -16
- package/src/authorization/grant-kinds.ts +32 -0
- package/src/authorization/index.ts +6 -1
- package/src/authorization/resolve.ts +58 -1
- package/src/authorization/run-visibility.ts +8 -1
- package/src/authorization/types.ts +14 -0
- package/src/errors/catalog.ts +26 -1
- package/src/errors/internal.ts +17 -8
- package/src/events/definitions.ts +26 -0
- package/src/events/execution.ts +43 -6
- package/src/events/index.ts +10 -1
- package/src/events/scope.ts +2 -0
- package/src/events/selectors/builder.ts +50 -0
- package/src/events/selectors/index.ts +4 -0
- package/src/events/selectors/types.ts +32 -1
- package/src/events/service.ts +55 -2
- package/src/events/types/index.ts +10 -0
- package/src/events/types/users.ts +73 -0
- package/src/events/view-conditions.ts +241 -0
- package/src/execution/agent.ts +25 -0
- package/src/execution/authorization.ts +70 -0
- package/src/execution/authorized-object-reader.ts +238 -32
- package/src/execution/lineage.ts +14 -0
- package/src/execution/object-reader-ontology.ts +11 -14
- package/src/execution/object-reader-security.ts +134 -10
- package/src/execution/object-reader-users.ts +122 -0
- package/src/execution/preparation.ts +78 -0
- package/src/execution/request.ts +2 -0
- package/src/execution/unique-lookup.ts +55 -0
- package/src/execution/visible-objects.ts +26 -0
- package/src/http/api-routes.ts +206 -7
- package/src/index.ts +99 -2
- package/src/materialization/errors.ts +37 -0
- package/src/materialization/event-envelopes.ts +11 -3
- package/src/materialization/index.ts +1 -0
- package/src/materialization/model.ts +24 -4
- package/src/materializer/README.md +7 -1
- package/src/materializer/edits/commit.ts +56 -12
- package/src/materializer/edits/load-state.ts +15 -7
- package/src/materializer/edits/operations.ts +12 -0
- package/src/materializer/edits/plan.ts +2 -0
- package/src/materializer/edits/unique-values.ts +255 -0
- package/src/materializer/edits/working-state.ts +8 -1
- package/src/materializer/execution/work-records.ts +47 -0
- package/src/materializer/projections/finish-run.ts +0 -1
- package/src/materializer/projections/replace.ts +1 -1
- package/src/materializer/projections/replacement-plan.ts +4 -1
- package/src/materializer/projections/source-materialization.ts +2 -1
- package/src/materializer/shared/normalize.ts +37 -6
- package/src/materializer/shared/projection-run.ts +1 -2
- package/src/materializer/telemetry/append.ts +14 -17
- package/src/materializer/telemetry/plan.ts +2 -0
- package/src/models/audio/catalog.ts +89 -10
- package/src/models/audio/errors.ts +18 -1
- package/src/models/audio/runtime.ts +10 -13
- package/src/models/audio/speech.ts +261 -0
- package/src/models/audio/types.ts +97 -0
- package/src/models/calls.ts +100 -0
- package/src/models/catalog-index.ts +21 -2
- package/src/models/catalog.ts +211 -35
- package/src/models/decision/runtime.ts +21 -22
- package/src/models/decision/validation.ts +4 -1
- package/src/models/definitions.ts +57 -8
- package/src/models/events.ts +72 -1
- package/src/models/execution/README.md +34 -5
- package/src/models/execution/binding.ts +3 -1
- package/src/models/execution/embedding.ts +1 -0
- package/src/models/execution/index.ts +5 -0
- package/src/models/execution/model-call-accounting.ts +3 -1
- package/src/models/execution/model-call-recorder.ts +29 -1
- package/src/models/execution/usage.ts +8 -0
- package/src/models/execution.ts +20 -22
- package/src/models/generation-types.ts +8 -1
- package/src/models/image/catalog.ts +89 -0
- package/src/models/image/errors.ts +19 -0
- package/src/models/image/runtime.ts +335 -0
- package/src/models/image/types.ts +111 -0
- package/src/models/index.ts +38 -4
- package/src/models/{audio/file.ts → input-file.ts} +22 -13
- package/src/models/language-model.ts +13 -0
- package/src/models/pricing.ts +263 -42
- package/src/models/rate-card.ts +161 -12
- package/src/objects/authorized-ontology-view.ts +1 -0
- package/src/objects/conditional-writes.ts +109 -0
- package/src/objects/execution.ts +4 -0
- package/src/objects/index.ts +8 -0
- package/src/objects/link/authorization.ts +12 -3
- package/src/objects/link/endpoints.ts +42 -11
- package/src/objects/link/remove.ts +25 -10
- package/src/objects/link/upsert-batch.ts +2 -0
- package/src/objects/link/upsert.ts +18 -12
- package/src/objects/materializer-adapter.ts +55 -18
- package/src/objects/object/delete.ts +24 -7
- package/src/objects/object/upsert-batch.ts +44 -14
- package/src/objects/object/upsert.ts +23 -5
- package/src/objects/query/current-user.ts +76 -0
- package/src/objects/query/executor.ts +39 -103
- package/src/objects/query/explain.ts +20 -7
- package/src/objects/query/index.ts +2 -0
- package/src/objects/query/ir.ts +20 -0
- package/src/objects/query/links.ts +8 -0
- package/src/objects/query/matches-predicate.ts +108 -0
- package/src/objects/query/normalize.ts +50 -19
- package/src/objects/query/scalar-values.ts +19 -3
- package/src/objects/query/user-expansions.ts +65 -0
- package/src/objects/query/validate.ts +248 -10
- package/src/objects/runtime-batch.ts +8 -2
- package/src/objects/sdk/object-set.ts +12 -1
- package/src/objects/sdk/query-builder.ts +39 -8
- package/src/objects/sdk/query-executor.ts +6 -0
- package/src/objects/serialize.ts +79 -0
- package/src/objects/unique-violation.ts +59 -0
- package/src/objects/vectors/handle.ts +3 -3
- package/src/ontology/builders.ts +3 -0
- package/src/ontology/docs-markdown.ts +1 -0
- package/src/ontology/index.ts +2 -2
- package/src/ontology/json-schema.ts +4 -0
- package/src/ontology/primitives.ts +21 -8
- package/src/ontology/registry.ts +16 -0
- package/src/ontology/types.ts +9 -0
- package/src/ontology/unique-values.ts +84 -0
- package/src/ontology/user-ref.ts +39 -0
- package/src/ontology/validation/properties.ts +43 -0
- package/src/ontology/validation/schema.ts +9 -1
- package/src/projections/registry.ts +16 -10
- package/src/projections/revision.ts +112 -45
- package/src/projections/run-dispatch.ts +38 -25
- package/src/projections/types.ts +2 -0
- package/src/query.ts +5 -0
- package/src/rules/execution.ts +43 -11
- package/src/runtime/ai-cost.ts +30 -0
- package/src/runtime/ai-usage.ts +32 -1
- package/src/runtime/host.ts +18 -1
- package/src/runtime/index.ts +2 -0
- package/src/runtime/resolve-definitions.ts +3 -0
- package/src/runtime/sixb.ts +35 -8
- package/src/runtime/types.ts +99 -9
- package/src/schedules/builders.ts +3 -1
- package/src/schedules/runtime.ts +6 -0
- package/src/schedules/validation.ts +23 -1
- package/src/security/README.md +62 -0
- package/src/security/grants.ts +155 -10
- package/src/security/index.ts +3 -1
- package/src/security/project.ts +6 -1
- package/src/security/registry.ts +32 -7
- package/src/security/types.ts +54 -9
- package/src/security/validation.ts +27 -11
- package/src/security/view-conditions.ts +215 -0
- package/src/shares/execution.ts +43 -10
- package/src/storage/action-runs/types.ts +2 -0
- package/src/storage/agents/errors.ts +3 -0
- package/src/storage/agents/in-memory.ts +779 -32
- package/src/storage/agents/index.ts +42 -0
- package/src/storage/agents/provider.ts +733 -8
- package/src/storage/agents/types.ts +620 -12
- package/src/storage/ai-cost/analytics.ts +60 -7
- package/src/storage/ai-cost/codec.ts +6 -1
- package/src/storage/ai-cost/groups.ts +44 -1
- package/src/storage/ai-cost/index.ts +1 -0
- package/src/storage/ai-cost/provider.ts +2 -0
- package/src/storage/ai-cost/types.ts +18 -1
- package/src/storage/ai-cost/validation.ts +39 -12
- package/src/storage/ai-limits/provider.ts +4 -7
- package/src/storage/ai-usage/in-memory.ts +28 -1
- package/src/storage/ai-usage/index.ts +9 -1
- package/src/storage/ai-usage/record.ts +44 -7
- package/src/storage/ai-usage/types.ts +38 -0
- package/src/storage/ai-usage/usage.ts +15 -1
- package/src/storage/artifacts/errors.ts +13 -1
- package/src/storage/artifacts/in-memory.ts +156 -8
- package/src/storage/artifacts/index.ts +6 -1
- package/src/storage/artifacts/record.ts +61 -1
- package/src/storage/artifacts/types.ts +92 -8
- package/src/storage/auth/in-memory/auth-storage.ts +27 -2
- package/src/storage/auth/in-memory/users.ts +40 -6
- package/src/storage/auth/index.ts +1 -0
- package/src/storage/auth/types.ts +43 -7
- package/src/storage/executions/in-memory.ts +32 -0
- package/src/storage/executions/index.ts +2 -0
- package/src/storage/executions/types.ts +17 -0
- package/src/storage/index.ts +69 -1
- package/src/storage/internal.ts +9 -1
- package/src/storage/migrations/migrate-storage.ts +8 -1
- package/src/storage/migrations/prepare-unique-properties.ts +161 -0
- package/src/storage/objects/guard.ts +7 -3
- package/src/storage/objects/in-memory/conditional-reader.ts +72 -0
- package/src/storage/objects/in-memory/query.ts +4 -105
- package/src/storage/objects/in-memory/read-scope.ts +15 -14
- package/src/storage/objects/in-memory/read-source.ts +11 -1
- package/src/storage/objects/in-memory/scoped-reader.ts +243 -0
- package/src/storage/objects/in-memory/selected-reader.ts +6 -231
- package/src/storage/objects/in-memory/storage.ts +183 -1
- package/src/storage/objects/index.ts +9 -1
- package/src/storage/objects/read-scope.ts +191 -0
- package/src/storage/objects/types.ts +68 -1
- package/src/storage/ontology/in-memory/index.ts +3 -0
- package/src/storage/ontology/in-memory/materializations.ts +35 -0
- package/src/storage/ontology/in-memory/replacement-plans.ts +4 -0
- package/src/storage/ontology/in-memory/unique-values.ts +62 -0
- package/src/storage/ontology/index.ts +10 -0
- package/src/storage/ontology/materializations.ts +35 -1
- package/src/storage/ontology/provider-work.ts +76 -0
- package/src/storage/ontology/provider.ts +3 -0
- package/src/storage/ontology/unique-values.ts +56 -0
- package/src/storage/operation-scope.ts +9 -1
- package/src/storage/projection-runs/in-memory.ts +3 -35
- package/src/storage/types.ts +2 -0
- package/src/testing/agent-approval-storage-contract.ts +1117 -0
- package/src/testing/agent-memory-storage-contract.ts +400 -0
- package/src/testing/agent-storage-contract.ts +1188 -33
- package/src/testing/ai-cost-storage-contract.ts +31 -1
- package/src/testing/ai-limit-storage-contract.ts +9 -7
- package/src/testing/ai-model-call-groups-contract.ts +76 -0
- package/src/testing/ai-usage-storage-contract.ts +120 -13
- package/src/testing/artifact-storage-contract.ts +338 -4
- package/src/testing/auth-storage-contract.ts +550 -73
- package/src/testing/broker-contract.ts +28 -23
- package/src/testing/effective-storage-contract.ts +3 -8
- package/src/testing/execution-storage-contract.ts +53 -0
- package/src/testing/file-upload-session-storage-contract.ts +12 -24
- package/src/testing/index.ts +17 -4
- package/src/testing/lake-storage-contract.ts +22 -28
- package/src/testing/materializer-storage-contract.ts +36 -9
- package/src/testing/object-conditional-read-scope-contract.ts +634 -0
- package/src/testing/object-query-contract.ts +386 -186
- package/src/testing/ontology-storage-contract.ts +230 -21
- package/src/testing/projection-run-storage-contract.ts +8 -18
- package/src/testing/queues-contract.ts +39 -70
- package/src/testing/sandboxes-contract.ts +3 -14
- package/src/testing/share-grant-storage-contract.ts +13 -16
- package/src/testing/share-session-storage-contract.ts +4 -14
- package/src/testing/unique-values-contract.ts +907 -0
- package/src/testing/webhook-execution.ts +1 -1
- package/src/testing/webhook-run-storage-contract.ts +6 -9
- package/src/users/execution.ts +131 -0
- package/src/users/index.ts +2 -0
- package/src/workers/queue-worker.ts +1 -3
- package/src/workers/worker.ts +1 -3
- package/src/workflows/builders.ts +6 -0
- package/src/workflows/request.ts +46 -8
- package/src/workflows/types.ts +6 -2
- package/src/workflows/validation.ts +23 -9
- package/dist/chunk-29yx306f.js.map +0 -22
- package/dist/chunk-3jms7je7.js +0 -14
- package/dist/chunk-3jms7je7.js.map +0 -10
- package/dist/chunk-3qct2mdc.js +0 -297
- package/dist/chunk-3qct2mdc.js.map +0 -12
- package/dist/chunk-48qjhh6v.js.map +0 -13
- package/dist/chunk-4as3wt1c.js.map +0 -12
- package/dist/chunk-5948n82c.js.map +0 -10
- package/dist/chunk-5hx48dnn.js.map +0 -14
- package/dist/chunk-6rqgmkde.js.map +0 -29
- package/dist/chunk-6x0pqh32.js.map +0 -10
- package/dist/chunk-7n30ybym.js +0 -3
- package/dist/chunk-7n440zgt.js +0 -261
- package/dist/chunk-7n440zgt.js.map +0 -12
- package/dist/chunk-7q8t23v4.js +0 -467
- package/dist/chunk-7q8t23v4.js.map +0 -14
- package/dist/chunk-8frc8a4j.js.map +0 -20
- package/dist/chunk-918wwnaa.js.map +0 -68
- package/dist/chunk-91mg3nj9.js.map +0 -12
- package/dist/chunk-96yw3pwd.js.map +0 -10
- package/dist/chunk-9j4jw7as.js.map +0 -14
- package/dist/chunk-9k93ah50.js.map +0 -11
- package/dist/chunk-9kgkfg6v.js +0 -502
- package/dist/chunk-9kgkfg6v.js.map +0 -14
- package/dist/chunk-akzryx9h.js.map +0 -100
- package/dist/chunk-arns890k.js.map +0 -10
- package/dist/chunk-bk9svbcq.js.map +0 -49
- package/dist/chunk-c06hmxyy.js +0 -31
- package/dist/chunk-c06hmxyy.js.map +0 -10
- package/dist/chunk-c1rxbz5y.js.map +0 -12
- package/dist/chunk-cn0fwwhy.js.map +0 -19
- package/dist/chunk-dhcv7yxc.js.map +0 -11
- package/dist/chunk-dhdha526.js.map +0 -10
- package/dist/chunk-dvd2fp9q.js.map +0 -13
- package/dist/chunk-e6k4thh5.js.map +0 -19
- package/dist/chunk-ere85b8y.js.map +0 -15
- package/dist/chunk-g257jwnc.js.map +0 -12
- package/dist/chunk-hwksyjks.js.map +0 -11
- package/dist/chunk-k43ct2ke.js.map +0 -12
- package/dist/chunk-nn5xnx3s.js.map +0 -40
- package/dist/chunk-pbcbn83d.js.map +0 -14
- package/dist/chunk-pqajwytd.js +0 -68
- package/dist/chunk-pqajwytd.js.map +0 -11
- package/dist/chunk-qczk96d9.js.map +0 -11
- package/dist/chunk-rdghfsss.js +0 -39
- package/dist/chunk-rdghfsss.js.map +0 -10
- package/dist/chunk-rj69qcrd.js.map +0 -11
- package/dist/chunk-v4jbb3rs.js.map +0 -10
- package/dist/chunk-yxd3nnqt.js.map +0 -11
- package/dist/events/toStoredEvent.d.ts +0 -9
- package/dist/events/toStoredEvent.d.ts.map +0 -1
- package/dist/models/audio/file.d.ts +0 -9
- package/dist/models/audio/file.d.ts.map +0 -1
- package/src/events/toStoredEvent.ts +0 -33
- /package/dist/{chunk-mfs23znk.js.map → chunk-07kkp2e1.js.map} +0 -0
- /package/dist/{chunk-z58tm0hm.js.map → chunk-0phpbbvm.js.map} +0 -0
- /package/dist/{chunk-e17zdm62.js.map → chunk-1t6k1avb.js.map} +0 -0
- /package/dist/{chunk-kge7k6ey.js.map → chunk-2fn60nvs.js.map} +0 -0
- /package/dist/{chunk-y0c4e6ex.js.map → chunk-3gbefjg5.js.map} +0 -0
- /package/dist/{chunk-cy4mbddw.js.map → chunk-48jezz3j.js.map} +0 -0
- /package/dist/{chunk-twe4dx8p.js → chunk-5tfev0fv.js} +0 -0
- /package/dist/{chunk-twe4dx8p.js.map → chunk-5tfev0fv.js.map} +0 -0
- /package/dist/{chunk-447a5c0p.js.map → chunk-6n69k945.js.map} +0 -0
- /package/dist/{chunk-0bphap9y.js.map → chunk-6p0pastb.js.map} +0 -0
- /package/dist/{chunk-431pyp2c.js.map → chunk-6y0mkhex.js.map} +0 -0
- /package/dist/{chunk-s7jg7pmn.js.map → chunk-bab05bhg.js.map} +0 -0
- /package/dist/{chunk-q5e5tv4b.js.map → chunk-c844dkwd.js.map} +0 -0
- /package/dist/{chunk-cfj9dfbb.js.map → chunk-d2m879s4.js.map} +0 -0
- /package/dist/{chunk-q7gn29y3.js.map → chunk-dp0cdtj2.js.map} +0 -0
- /package/dist/{chunk-br3k6qbf.js.map → chunk-fm62y49k.js.map} +0 -0
- /package/dist/{chunk-vvxtn22d.js.map → chunk-g663fahq.js.map} +0 -0
- /package/dist/{chunk-rmakanzx.js.map → chunk-h33shhq6.js.map} +0 -0
- /package/dist/{chunk-d09e3rax.js.map → chunk-hwarjrgf.js.map} +0 -0
- /package/dist/{chunk-vf57cr4t.js.map → chunk-hyesv9dv.js.map} +0 -0
- /package/dist/{chunk-5vems3nx.js.map → chunk-m2nevja0.js.map} +0 -0
- /package/dist/{chunk-x9v4cx1d.js.map → chunk-m36fw8ft.js.map} +0 -0
- /package/dist/{chunk-a40ad1ft.js.map → chunk-mbsbxarb.js.map} +0 -0
- /package/dist/{chunk-6aawea28.js.map → chunk-n8q5j6y5.js.map} +0 -0
- /package/dist/{chunk-d7dnxdep.js.map → chunk-n9zpx9c6.js.map} +0 -0
- /package/dist/{chunk-xvsc5m8n.js.map → chunk-npcr0228.js.map} +0 -0
- /package/dist/{chunk-y5tah2kf.js.map → chunk-q4pmvkg0.js.map} +0 -0
- /package/dist/{chunk-d5rjr8c0.js.map → chunk-vabga7fk.js.map} +0 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/storage/action-runs/in-memory.ts", "../src/agents/message.ts", "../src/storage/agents/in-memory.ts", "../src/storage/ai-cost/errors.ts", "../src/storage/ai-cost/in-memory.ts", "../src/storage/ai-limits/in-memory.ts", "../src/storage/connector-connections/in-memory.ts", "../src/storage/file-upload-sessions/in-memory.ts", "../src/storage/in-memory/index.ts", "../src/storage/activity/in-memory.ts", "../src/storage/artifacts/in-memory.ts", "../src/storage/executions/in-memory.ts", "../src/storage/file-download-grants/in-memory.ts", "../src/storage/objects/keys.ts", "../src/objects/query/scalar-values.ts", "../src/objects/query/matches-predicate.ts", "../src/storage/objects/in-memory/keys.ts", "../src/storage/objects/in-memory/query.ts", "../src/storage/objects/in-memory/scoped-reader.ts", "../src/storage/objects/in-memory/conditional-reader.ts", "../src/storage/objects/in-memory/read-scope.ts", "../src/storage/objects/in-memory/selected-reader.ts", "../src/storage/objects/in-memory/storage.ts", "../src/storage/ontology/in-memory/shared-state.ts", "../src/storage/ontology/in-memory/commits.ts", "../src/storage/timeseries/store.ts", "../src/storage/ontology/in-memory/materializations-state.ts", "../src/storage/ontology/in-memory/materializations-work.ts", "../src/storage/ontology/in-memory/materializations-finalization.ts", "../src/storage/ontology/in-memory/source-roots.ts", "../src/storage/ontology/in-memory/replacement-plans.ts", "../src/storage/ontology/in-memory/vectors.ts", "../src/storage/ontology/in-memory/materializations.ts", "../src/storage/ontology/in-memory/outbox.ts", "../src/storage/ontology/in-memory/sources.ts", "../src/storage/ontology/in-memory/state-reader.ts", "../src/storage/ontology/in-memory/testing.ts", "../src/storage/ontology/in-memory/unique-values.ts", "../src/storage/ontology/in-memory/vector-indexing.ts", "../src/storage/ontology/in-memory/index.ts", "../src/storage/run-listing.ts", "../src/storage/pipeline-runs/types.ts", "../src/storage/pipeline-runs/in-memory.ts", "../src/storage/projection-runs/in-memory.ts", "../src/storage/rules/in-memory.ts", "../src/storage/share-grants/in-memory.ts", "../src/storage/share-sessions/in-memory.ts", "../src/storage/sync-runs/types.ts", "../src/storage/sync-runs/in-memory.ts", "../src/storage/webhook-runs/types.ts", "../src/storage/webhook-runs/in-memory.ts", "../src/storage/workflow-interventions/errors.ts", "../src/storage/workflow-interventions/in-memory.ts", "../src/storage/workflow-runs/types.ts", "../src/storage/workflow-runs/in-memory.ts", "../src/storage/in-memory/testing.ts", "../src/storage/objects/query-preparation.ts", "../src/storage/migrations/prepare-unique-properties.ts", "../src/storage/migrations/migrate-storage.ts", "../src/storage/migrations/check-schema.ts", "../src/storage/migrations/migration-set.ts", "../src/storage/ontology/vector-indexing.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { ExecutionStorage } from \"../executions\"\nimport { ActionRunError } from \"./errors\"\nimport { actionSubjectsEqual } from \"./idempotency\"\nimport { assertActionRunExecution } from \"./provider\"\nimport { normalizeRecordActionRunInput, resolveActionRunEffects } from \"./record\"\nimport type {\n ActionRunRecord,\n ActionRunStorage,\n ListActionRunsInput,\n ListActionRunsResult,\n RecordActionEffectsInput,\n RecordActionRunInput,\n} from \"./types\"\n\ntype RunRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\n\nconst runDirectly: RunRootOperation = async <T>(run: () => Promise<T> | T): Promise<T> => run()\n\nfunction actionRunKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction cloneActionRunRecord(record: ActionRunRecord): ActionRunRecord {\n return structuredClone(record)\n}\n\nfunction compareRuns(a: ActionRunRecord, b: ActionRunRecord, order: \"asc\" | \"desc\"): number {\n const delta = a.startedAt.getTime() - b.startedAt.getTime()\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n\n if (a.id === b.id) {\n return 0\n }\n\n return order === \"asc\" ? a.id.localeCompare(b.id) : b.id.localeCompare(a.id)\n}\n\nexport class InMemoryActionRunStorage implements ActionRunStorage {\n private readonly rows = new Map<string, ActionRunRecord>()\n private readonly runRootOperation: RunRootOperation\n\n constructor(\n private readonly executions: ExecutionStorage,\n input: { readonly runRootOperation?: RunRootOperation } = {}\n ) {\n this.runRootOperation = input.runRootOperation ?? runDirectly\n }\n\n snapshot(): InMemoryActionRunStorageSnapshot {\n return structuredClone(this.rows)\n }\n\n restore(snapshot: InMemoryActionRunStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.rows.set(key, record)\n }\n }\n\n async record(input: RecordActionRunInput): Promise<ActionRunRecord> {\n return this.runRootOperation(async () => {\n const record = normalizeRecordActionRunInput(input)\n const key = actionRunKey(record.projectId, record.id)\n if (this.rows.has(key)) {\n throw new ActionRunError(\n `[Sixb] Action run '${record.id}' is already recorded for project '${record.projectId}'.`\n )\n }\n if (\n [...this.rows.values()].some(\n (run) => run.projectId === record.projectId && run.executionId === record.executionId\n )\n ) {\n throw new ActionRunError(\n `[Sixb] Execution '${record.executionId}' already belongs to another Action run.`\n )\n }\n await assertActionRunExecution({\n executions: this.executions,\n projectId: record.projectId,\n executionId: record.executionId,\n runId: record.id,\n actionId: record.actionId,\n })\n\n this.rows.set(key, structuredClone(record))\n return cloneActionRunRecord(record)\n })\n }\n\n async recordEffects(input: RecordActionEffectsInput): Promise<ActionRunRecord> {\n return this.runRootOperation(() => {\n const key = actionRunKey(input.projectId, input.id)\n const { run, effects } = resolveActionRunEffects(this.rows.get(key) ?? null, input)\n if (!effects) return cloneActionRunRecord(run)\n\n const next: ActionRunRecord = { ...run, phase: \"effects\", effects }\n this.rows.set(key, structuredClone(next))\n return cloneActionRunRecord(next)\n })\n }\n\n async getById(params: { projectId: string; id: string }): Promise<ActionRunRecord | null> {\n return this.runRootOperation(() => {\n const record = this.rows.get(actionRunKey(params.projectId, params.id))\n return record ? cloneActionRunRecord(record) : null\n })\n }\n\n async getByExecutionIds(params: {\n readonly projectId: string\n readonly executionIds: readonly string[]\n }): Promise<readonly ActionRunRecord[]> {\n return this.runRootOperation(() => {\n const byExecution = new Map(\n [...this.rows.values()]\n .filter((record) => record.projectId === params.projectId)\n .map((record) => [record.executionId, record])\n )\n\n return [...new Set(params.executionIds)].flatMap((executionId) => {\n const record = byExecution.get(executionId)\n return record ? [cloneActionRunRecord(record)] : []\n })\n })\n }\n\n async list(input: ListActionRunsInput): Promise<ListActionRunsResult> {\n return this.runRootOperation(() => {\n if (input.actionIds?.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n\n const order = input.order ?? \"desc\"\n const offset = input.offset ?? 0\n const limit = input.limit ?? this.rows.size\n const actionIds = input.actionIds ? new Set(input.actionIds) : null\n const objectTypeIds = input.objectTypeIds ? new Set(input.objectTypeIds) : null\n const statuses = input.statuses ? new Set(input.statuses) : null\n\n const filtered = [...this.rows.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.actionId ? record.actionId === input.actionId : true))\n .filter((record) => (actionIds ? actionIds.has(record.actionId) : true))\n .filter((record) =>\n objectTypeIds\n ? record.subject.kind !== \"object\" || objectTypeIds.has(record.subject.objectTypeId)\n : true\n )\n .filter((record) =>\n input.subject ? actionSubjectsEqual(record.subject, input.subject) : true\n )\n .filter((record) =>\n input.objectTypeId\n ? record.subject.kind === \"object\" && record.subject.objectTypeId === input.objectTypeId\n : true\n )\n .filter((record) =>\n input.primaryId\n ? record.subject.kind === \"object\" && record.subject.primaryId === input.primaryId\n : true\n )\n .filter((record) => (statuses ? statuses.has(record.status) : true))\n .filter((record) => (input.startedAfter ? record.startedAt >= input.startedAfter : true))\n .filter((record) => (input.startedBefore ? record.startedAt <= input.startedBefore : true))\n .sort((a, b) => compareRuns(a, b, order))\n\n const total = filtered.length\n const runs = filtered.slice(offset, offset + limit).map(cloneActionRunRecord)\n return { runs, hasMore: offset + runs.length < total, total }\n })\n }\n}\n\nexport type InMemoryActionRunStorageSnapshot = Map<string, ActionRunRecord>\n",
|
|
6
|
+
"import type { FileRef } from \"../blob-storage\"\nimport type { JsonValue } from \"../json\"\nimport type { ProviderData } from \"../models\"\nimport type {\n AgentApprovalCall,\n AgentApprovalOutcome,\n AgentApprovalStatus,\n} from \"../storage/agents/types\"\nimport type { AgentContextPart } from \"./context/entries\"\n\n/**\n * The agent's own, SDK-independent message. We store messages and threads — not an SDK transport —\n * so a message is just a `role` plus structured `parts` (and optional `metadata`). There is no\n * self-describing wrapper: the storage row owns the message's identity, and `contentVersion` (a\n * column) versions the parts shape so it can be migrated.\n *\n * The part union is intentionally focused on what agent runs actually produce (text, reasoning, step\n * boundaries, tool calls). The model loop validates and normalizes output before its steps are\n * projected into this union; storage validates the durable write contract independently.\n */\nexport const AGENT_MESSAGE_CONTENT_VERSION = 2 as const\n\nexport type AgentMessageRole = \"system\" | \"user\" | \"assistant\"\n\n/** A plain text part (assistant output, user input, or system text). */\nexport interface AgentTextPart {\n readonly type: \"text\"\n readonly text: string\n /** Provider passthrough (kept because some providers require it on the next turn). */\n readonly providerMetadata?: ProviderData\n}\n\n/**\n * A reasoning (\"thinking\") part. `providerMetadata` is load-bearing here: some providers require\n * the reasoning signature back on the following turn, so dropping it would break multi-step loops.\n */\nexport interface AgentReasoningPart {\n readonly type: \"reasoning\"\n readonly text: string\n readonly providerMetadata?: ProviderData\n}\n\n/** A step boundary between assistant loop iterations. */\nexport interface AgentStepStartPart {\n readonly type: \"step-start\"\n}\n\n/** A blob-backed file attached to a user message or produced by an agent/tool. */\nexport interface AgentFilePart {\n readonly type: \"file\"\n readonly fileRef: FileRef\n /** Provider passthrough for future model-specific file handling. */\n readonly providerMetadata?: ProviderData\n}\n\ninterface AgentToolCallBase {\n readonly type: \"tool-call\"\n readonly toolCallId: string\n readonly toolName: string\n /** `true` when the model identifies the call as a dynamic tool. */\n readonly dynamic?: boolean\n /** `true` when the provider executed the tool inline (steers model projection). */\n readonly providerExecuted?: boolean\n readonly input: JsonValue\n readonly providerMetadata?: ProviderData\n}\n\n/**\n * The user asked the Agent to continue an answer the turn limit cut short. Sixb writes the\n * instruction the model reads; chats show no message for it.\n */\nexport interface AgentContinuationPart {\n readonly type: \"continuation\"\n}\n\n/**\n * How a call the Agent made in an earlier turn ended, once its requester decided on it or it was\n * set aside. Sixb writes it at the start of the next user message; chats show no text for it.\n */\nexport interface AgentApprovalOutcomePart {\n readonly type: \"approval-outcome\"\n readonly approvalId: string\n readonly status: Exclude<AgentApprovalStatus, \"pending\">\n readonly call: AgentApprovalCallSummary\n /** What the approved call gave, when it ran. */\n readonly outcome?: AgentApprovalOutcome\n /** The turn's sub-agent that made the call, when the turn did not make it itself. */\n readonly caller?: AgentApprovalCaller\n}\n\n/** A turn's sub-agent that made a call: its run, and the key it was spawned with. */\nexport interface AgentApprovalCaller {\n readonly runId: string\n readonly key: string\n /** The message resumes the turn and the sub-agent paused on its calls: it goes on. */\n readonly continues?: true\n}\n\n/** The call an approval held, as the model asked for it, without its params. */\nexport type AgentApprovalCallSummary =\n | Pick<Extract<AgentApprovalCall, { readonly kind: \"action\" }>, \"kind\" | \"actionId\" | \"subject\">\n | Pick<Extract<AgentApprovalCall, { readonly kind: \"workflow\" }>, \"kind\" | \"workflowId\">\n\n/**\n * A message a sub-agent read before its next step: today, its parent steering it, or answering the\n * question it paused on. Sixb writes it in the sub-agent's thread, where the child read it; the\n * model reads it as data from the sender, never from the user.\n */\nexport interface AgentMailPart {\n readonly type: \"mail\"\n /** The mail's id, the same in the sender's and the reader's records. */\n readonly id: string\n readonly from: \"parent\"\n /** `answer`: the reply to the question it asked, `inReplyTo`. */\n readonly kind: \"message\" | \"answer\"\n /** The question an answer replies to. */\n readonly inReplyTo?: string\n readonly text: string\n /**\n * It came as the reader answered: the sender has not received that answer, so the reader writes\n * its whole result again.\n */\n readonly afterAnswer?: true\n}\n\n/** Ordered, hidden provider state required to replay a model response losslessly. */\nexport interface AgentProviderStatePart {\n readonly type: \"provider-state\"\n readonly providerId: string\n readonly data: JsonValue\n}\n\n/**\n * A completed tool call. Only terminal states are modelled — transient states\n * (`input-streaming`, `input-available`, `approval-*`) are never persisted because messages are\n * written only once a run finishes.\n */\nexport type AgentToolCallPart = AgentToolCallBase &\n (\n | { readonly state: \"output-available\"; readonly output: JsonValue }\n | { readonly state: \"output-error\"; readonly errorText: string }\n )\n\nexport type AgentMessagePart =\n | AgentTextPart\n | AgentReasoningPart\n | AgentStepStartPart\n | AgentFilePart\n | AgentContextPart\n | AgentContinuationPart\n | AgentApprovalOutcomePart\n | AgentMailPart\n | AgentToolCallPart\n | AgentProviderStatePart\n\nexport type AgentMessagePartType = AgentMessagePart[\"type\"]\nexport type AgentToolCallState = AgentToolCallPart[\"state\"]\n\n/** The logical agent message the adapters speak and the store persists (as columns). */\nexport interface AgentMessage {\n readonly role: AgentMessageRole\n readonly parts: readonly AgentMessagePart[]\n /** Optional JSON metadata associated with the message. */\n readonly metadata?: JsonValue\n}\n",
|
|
7
|
+
"import { AGENT_MESSAGE_CONTENT_VERSION } from \"../../agents/message\"\nimport { type Principal, principalsEqual } from \"../../auth\"\nimport { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport type { ExecutionStorage } from \"../executions\"\nimport { AgentStorageError } from \"./errors\"\nimport {\n agentApprovalCallKey,\n agentApprovalClaimable,\n agentApprovalHoldsRun,\n agentApprovalMatches,\n agentApprovalRepairable,\n agentApprovalStops,\n agentContextCheckpointMatchesCreateInput,\n agentMemoryConflicts,\n agentMemoryHistoryCutoff,\n agentRunMayHoldCalls,\n assertAgentApprovalCaller,\n assertAgentApprovalModeInput,\n assertAgentContextCheckpointAnchors,\n assertAgentContextCheckpointAuthority,\n assertAgentContextCheckpointReplayState,\n assertAgentRunExecution,\n assertAgentRunFinishPayload,\n assertAwaitingApprovalFinish,\n assertConversationAgentRunSpec,\n assertConversationThreadRow,\n assertCreateAgentContextCheckpointInput,\n assertCreateSubagentRunInput,\n assertRequestAgentApprovalInput,\n assertSaveAgentMemoryInput,\n assertSubagentThreadTakesRun,\n compareAgentMemoryPaths,\n compareAgentThreadParticipants,\n countsAsThreadMessage,\n LIVE_AGENT_APPROVAL_STATUSES,\n newAgentApprovalRecord,\n newSubagentThreadRecord,\n participantsToAdd,\n planAgentThreadFork,\n remapArtifactIds,\n snapshotAgentThreadSandboxParams,\n subagentRunMatchesCreateInput,\n transitionAgentThreadSandbox,\n} from \"./provider\"\nimport type {\n AddAgentThreadParticipantsInput,\n AgentApprovalCursor,\n AgentApprovalMode,\n AgentApprovalModeStore,\n AgentApprovalOutcome,\n AgentApprovalRecord,\n AgentApprovalStore,\n AgentContextCheckpointRecord,\n AgentContextCheckpointStore,\n AgentMemoryChange,\n AgentMemoryRepoRecord,\n AgentMemoryRevisionRecord,\n AgentMemoryStore,\n AgentMessageRecord,\n AgentMessageStore,\n AgentRunFailureCode,\n AgentRunRecord,\n AgentRunStore,\n AgentStorage,\n AgentThreadParticipantRecord,\n AgentThreadRecord,\n AgentThreadSandboxState,\n AgentThreadStore,\n AppendAgentMessageInput,\n ConfirmAgentRunExecutionOwnershipInput,\n ConversationAgentRunRecord,\n CreateAgentContextCheckpointInput,\n CreateAgentRunInput,\n CreateAgentThreadInput,\n CreateSubagentRunInput,\n DecideAgentApprovalInput,\n DecideAgentApprovalResult,\n DeleteAgentMessagesByRunInput,\n FinishAgentRunInput,\n FinishQueuedAgentRunInput,\n ForkAgentThreadInput,\n ListAgentApprovalsInput,\n ListAgentApprovalsResult,\n ListAgentMemoryRevisionsInput,\n ListAgentMemoryRevisionsResult,\n ListAgentMessagesInput,\n ListAgentMessagesResult,\n ListAgentRunsInput,\n ListAgentRunsResult,\n ListAgentThreadChildrenInput,\n ListAgentThreadParticipantsInput,\n ListAgentThreadsInput,\n ListAgentThreadsResult,\n ListThreadSubagentsInput,\n MarkAgentApprovalsReportedInput,\n ReclaimAgentRunInput,\n RemoveAgentThreadParticipantInput,\n RequestAgentApprovalInput,\n RequestAgentApprovalResult,\n SaveAgentMemoryInput,\n SaveAgentMemoryResult,\n SettleAgentApprovalsInput,\n StartAgentRunInput,\n StopAgentApprovalsInput,\n StopAgentApprovalsResult,\n SubagentRunRecord,\n TransitionAgentThreadSandboxInput,\n} from \"./types\"\nimport { AGENT_RUN_FAILURE_CODES } from \"./types\"\n\nfunction normalizeFailure(\n failure: SixbFailure<AgentRunFailureCode> | undefined\n): SixbFailure<AgentRunFailureCode> | undefined {\n return failure ? parseSixbFailure(failure, AGENT_RUN_FAILURE_CODES) : undefined\n}\n\nfunction key(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction clone<T>(value: T): T {\n return structuredClone(value)\n}\n\nfunction compareByDate(\n left: Date | undefined,\n right: Date | undefined,\n leftId: string,\n rightId: string,\n order: \"asc\" | \"desc\"\n): number {\n const delta = (left?.getTime() ?? 0) - (right?.getTime() ?? 0)\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n if (leftId === rightId) {\n return 0\n }\n return order === \"asc\" ? leftId.localeCompare(rightId) : rightId.localeCompare(leftId)\n}\n\ninterface Window<T> {\n readonly page: T[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nfunction applyWindow<T>(rows: T[], offset = 0, limit?: number): Window<T> {\n const total = rows.length\n const end = limit === undefined ? total : offset + limit\n const page = rows.slice(offset, end)\n return { page, hasMore: offset + page.length < total, total }\n}\n\n/**\n * Shared in-memory state behind the sub-stores. They are tiered for ergonomics\n * (`storage.runs.create(...)`), but several operations span tables — creating/finishing a run\n * updates the thread anchor, appending a message bumps thread stats, and checkpoint creation reads\n * run/thread/message anchors — so they all read and write the same maps through this object.\n */\ninterface AgentStoreState {\n readonly threads: Map<string, AgentThreadRecord>\n /** By thread key; each thread's participants in the order they were added. */\n readonly participants: Map<string, AgentThreadParticipantRecord[]>\n readonly runs: Map<string, AgentRunRecord>\n readonly messages: Map<string, AgentMessageRecord>\n readonly checkpoints: Map<string, AgentContextCheckpointRecord>\n readonly memory: Map<string, StoredAgentMemoryRepo>\n readonly approvals: Map<string, AgentApprovalRecord>\n /** By `[projectId, principal]` for a default, `[projectId, threadId, principal]` for a thread. */\n readonly approvalModes: Map<string, AgentApprovalMode>\n}\n\n/** A memory repo as its two SQL tables hold it: revisions, and the file versions each wrote. */\ninterface StoredAgentMemoryRepo {\n /** Oldest first. */\n readonly revisions: readonly Omit<AgentMemoryRevisionRecord, \"changes\">[]\n /** In insertion order, so by revision. `contents: null` deleted the path. */\n readonly files: readonly (AgentMemoryChange & { readonly revision: number })[]\n}\n\nexport interface InMemoryAgentStorageSnapshot {\n readonly threads: Map<string, AgentThreadRecord>\n readonly participants: Map<string, AgentThreadParticipantRecord[]>\n readonly runs: Map<string, AgentRunRecord>\n readonly messages: Map<string, AgentMessageRecord>\n readonly checkpoints: Map<string, AgentContextCheckpointRecord>\n readonly memory: Map<string, StoredAgentMemoryRepo>\n readonly approvals: Map<string, AgentApprovalRecord>\n readonly approvalModes: Map<string, AgentApprovalMode>\n}\n\n// ── threads ───────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentThreadStore implements AgentThreadStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async transitionSandbox(\n input: TransitionAgentThreadSandboxInput\n ): Promise<AgentThreadSandboxState> {\n const threadKey = key(input.projectId, input.id)\n const thread = this.state.threads.get(threadKey) ?? null\n const run =\n input.action === \"recreate\"\n ? null\n : (this.state.runs.get(key(input.projectId, input.runId)) ?? null)\n const sandboxState = transitionAgentThreadSandbox(thread, run, input)\n if (!thread) throw new AgentStorageError(\"thread_not_found\", \"[Sixb] Thread not found.\")\n this.state.threads.set(threadKey, { ...thread, sandboxState: clone(sandboxState) })\n return clone(sandboxState)\n }\n\n async create(input: CreateAgentThreadInput): Promise<AgentThreadRecord> {\n const sandboxParams =\n input.sandboxParams === undefined\n ? undefined\n : snapshotAgentThreadSandboxParams(input.sandboxParams)\n const threadKey = key(input.projectId, input.id)\n if (this.state.threads.has(threadKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent thread '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const createdAt = new Date(input.createdAt ?? new Date())\n const record: AgentThreadRecord = {\n id: input.id,\n projectId: input.projectId,\n kind: \"conversation\",\n ownerPrincipal: clone(input.ownerPrincipal),\n ...(sandboxParams === undefined ? {} : { sandboxParams }),\n ...(input.title === undefined ? {} : { title: input.title }),\n status: input.status ?? \"active\",\n activeRunId: null,\n messageCount: 0,\n createdAt,\n updatedAt: new Date(input.updatedAt ?? createdAt),\n }\n\n this.state.threads.set(threadKey, clone(record))\n return clone(record)\n }\n\n async fork(input: ForkAgentThreadInput): Promise<AgentThreadRecord> {\n // No `await` between reading the source and writing the fork: one in-memory critical section.\n const source = this.state.threads.get(key(input.projectId, input.sourceThreadId))\n if (!source) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.sourceThreadId}' not found for project '${input.projectId}'.`\n )\n }\n assertConversationThreadRow(source, \"can be forked\")\n\n const forkKey = key(input.projectId, input.id)\n if (this.state.threads.has(forkKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent thread '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const activeRun =\n source.activeRunId === null\n ? undefined\n : this.state.runs.get(key(input.projectId, source.activeRunId))\n\n const messages = [...this.state.messages.values()]\n .filter((message) => message.projectId === input.projectId)\n .filter((message) => message.threadId === source.id)\n .sort((left, right) => left.seq - right.seq)\n\n const checkpoints = [...this.state.checkpoints.values()]\n .filter((checkpoint) => checkpoint.projectId === input.projectId)\n .filter((checkpoint) => checkpoint.threadId === source.id)\n .sort(compareLatestCheckpoints)\n\n const plan = planAgentThreadFork(input, {\n ...(activeRun?.kind === \"conversation\"\n ? { triggerMessageId: activeRun.triggerMessageId }\n : {}),\n messages: messages.map((message) => ({\n ...message,\n counted: countsAsThreadMessage(message),\n })),\n checkpoints,\n })\n\n this.state.threads.set(forkKey, clone(plan.thread))\n\n const copyIds = new Map(plan.messages.map((copy) => [copy.sourceId, copy.id]))\n for (const message of messages) {\n const id = copyIds.get(message.id)\n if (id === undefined) continue\n\n const parts = JSON.parse(\n remapArtifactIds(JSON.stringify(message.parts), input.artifactCopies)\n ) as AgentMessageRecord[\"parts\"]\n this.state.messages.set(\n key(input.projectId, id),\n clone({ ...message, id, threadId: input.id, parts })\n )\n }\n\n if (plan.checkpoint) {\n this.state.checkpoints.set(key(input.projectId, plan.checkpoint.id), clone(plan.checkpoint))\n }\n\n return clone(plan.thread)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null> {\n const record = this.state.threads.get(key(params.projectId, params.id))\n return record ? clone(record) : null\n }\n\n async getByIds(params: {\n readonly projectId: string\n readonly ids: readonly string[]\n }): Promise<readonly AgentThreadRecord[]> {\n return [...new Set(params.ids)].flatMap((id) => {\n const record = this.state.threads.get(key(params.projectId, id))\n return record ? [clone(record)] : []\n })\n }\n\n async listChildren(input: ListAgentThreadChildrenInput): Promise<readonly AgentThreadRecord[]> {\n const offset = input.offset ?? 0\n return [...this.state.threads.values()]\n .filter((thread) => thread.projectId === input.projectId)\n .filter((thread) => thread.parent?.threadId === input.parentThreadId)\n .filter((thread) =>\n input.parentRunId === undefined ? true : thread.parent?.spawnedBy === input.parentRunId\n )\n .sort((a, b) => compareByDate(a.createdAt, b.createdAt, a.id, b.id, \"asc\"))\n .slice(offset, offset + (input.limit ?? 100))\n .map(clone)\n }\n\n async list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult> {\n const order = input.order ?? \"desc\"\n const statuses = input.statuses ? new Set(input.statuses) : null\n const filtered = [...this.state.threads.values()]\n .filter((thread) => thread.projectId === input.projectId)\n .filter((thread) => thread.kind === \"conversation\")\n .filter((thread) => (statuses ? statuses.has(thread.status) : true))\n .filter((thread) =>\n input.ownerPrincipal ? principalsEqual(thread.ownerPrincipal, input.ownerPrincipal) : true\n )\n .filter((thread) => {\n const participant = input.participantPrincipal\n if (!participant) return true\n\n return this.participantsOf(thread.projectId, thread.id).some(\n (record) => record.principal.id === participant.id\n )\n })\n .sort((a, b) =>\n compareByDate(\n a.lastMessageAt ?? a.createdAt,\n b.lastMessageAt ?? b.createdAt,\n a.id,\n b.id,\n order\n )\n )\n\n const { page, hasMore, total } = applyWindow(filtered, input.offset, input.limit)\n return { threads: page.map(clone), hasMore, total }\n }\n\n async addParticipants(\n input: AddAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]> {\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n assertConversationThreadRow(thread, \"has participants\")\n\n // No `await` from here on: the read and the write are one critical section.\n const existing = this.participantsOf(input.projectId, input.threadId)\n const addedAt = new Date(input.addedAt ?? new Date())\n const added = participantsToAdd(input, existing).map((principal) => ({\n projectId: input.projectId,\n threadId: input.threadId,\n principal,\n addedAt: new Date(addedAt),\n addedBy: clone(input.addedBy),\n }))\n\n const participants = [...existing, ...added].sort(compareAgentThreadParticipants)\n this.state.participants.set(threadKey, participants)\n return clone(participants)\n }\n\n async removeParticipant(input: RemoveAgentThreadParticipantInput): Promise<boolean> {\n const threadKey = key(input.projectId, input.threadId)\n const existing = this.state.participants.get(threadKey)\n const kept = existing?.filter((record) => record.principal.id !== input.principal.id)\n if (!existing || !kept || kept.length === existing.length) return false\n\n this.state.participants.set(threadKey, kept)\n return true\n }\n\n async listParticipants(\n input: ListAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]> {\n return [...new Set(input.threadIds)]\n .flatMap((threadId) => clone(this.participantsOf(input.projectId, threadId)))\n .sort(compareAgentThreadParticipants)\n }\n\n private participantsOf(projectId: string, threadId: string): AgentThreadParticipantRecord[] {\n return this.state.participants.get(key(projectId, threadId)) ?? []\n }\n}\n\n// ── runs ──────────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentRunStore implements AgentRunStore {\n constructor(\n private readonly state: AgentStoreState,\n private readonly executions: ExecutionStorage\n ) {}\n\n async create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord> {\n assertConversationAgentRunSpec(input.spec)\n await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n // No `await` between read and write: the in-memory critical section is atomic, so two concurrent\n // queued runs on the same thread cannot both win — the second observes `activeRunId` set.\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n assertConversationThreadRow(thread, \"takes turns\")\n if (thread.activeRunId !== null) {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[Sixb] Agent thread '${input.threadId}' already has an active run '${thread.activeRunId}'.`\n )\n }\n\n const runKey = key(input.projectId, input.id)\n if (this.state.runs.has(runKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.state.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Execution '${input.executionId}' already belongs to another Agent run.`\n )\n }\n\n const createdAt = new Date(input.createdAt ?? new Date())\n const run: ConversationAgentRunRecord = {\n kind: \"conversation\",\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n threadId: input.threadId,\n triggerMessageId: input.triggerMessageId,\n spec: clone(input.spec),\n status: \"queued\",\n attempt: 0,\n createdAt,\n }\n this.state.runs.set(runKey, clone(run))\n\n const updatedThread: AgentThreadRecord = {\n ...thread,\n activeRunId: run.id,\n updatedAt: createdAt,\n }\n this.state.threads.set(threadKey, clone(updatedThread))\n\n return clone(run)\n }\n\n async createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord> {\n assertCreateSubagentRunInput(input)\n const execution = await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n\n const runKey = key(input.projectId, input.id)\n const existing = this.state.runs.get(runKey)\n if (existing) {\n if (subagentRunMatchesCreateInput(existing, input)) return clone(existing)\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Subagent run '${input.id}' already exists with different immutable inputs.`\n )\n }\n\n const parent = this.state.runs.get(key(input.projectId, input.parentRunId))\n if (!parent || parent.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"run_not_found\",\n `[Sixb] Parent Agent run '${input.parentRunId}' was not found.`\n )\n }\n if (parent.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Parent Agent run '${parent.id}' is not running (status '${parent.status}').`\n )\n }\n if (\n execution.source.type !== \"execution\" ||\n execution.source.executionId !== parent.executionId\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[Sixb] Subagent execution '${execution.id}' is not a child of parent execution '${parent.executionId}'.`\n )\n }\n if (parent.execution?.token !== input.parentExecutionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[Sixb] Parent Agent run '${parent.id}' is no longer owned by this execution.`\n )\n }\n const activeChildren = [...this.state.runs.values()].filter(\n (run) =>\n run.kind === \"subagent\" &&\n run.projectId === input.projectId &&\n run.parentRunId === parent.id &&\n (run.status === \"queued\" || run.status === \"running\")\n ).length\n if (activeChildren >= input.maxActiveChildren) {\n throw new AgentStorageError(\n \"active_child_limit\",\n `[Sixb] Agent run '${parent.id}' already has ${activeChildren} active subagents.`\n )\n }\n if (\n [...this.state.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Execution '${input.executionId}' already belongs to another Agent run.`\n )\n }\n\n // The child's thread: created by its first run, taken by a later one while it is idle.\n const createdAt = new Date(input.createdAt ?? new Date())\n const threadKey = key(input.projectId, input.thread.id)\n const existingThread = this.state.threads.get(threadKey) ?? null\n let thread: AgentThreadRecord\n if (input.thread.create) {\n if (existingThread) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent thread '${input.thread.id}' already exists for project '${input.projectId}'.`\n )\n }\n const conversation = this.state.threads.get(key(input.projectId, parent.threadId))\n if (!conversation) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${parent.threadId}' not found for project '${input.projectId}'.`\n )\n }\n thread = newSubagentThreadRecord(input, conversation, createdAt)\n } else {\n assertSubagentThreadTakesRun(existingThread, input, parent.threadId)\n thread = {\n ...existingThread,\n activeRunId: input.id,\n messageCount: existingThread.messageCount + 1,\n lastMessageAt: createdAt,\n updatedAt: createdAt,\n }\n }\n\n const run: SubagentRunRecord = {\n kind: \"subagent\",\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n threadId: input.thread.id,\n triggerMessageId: input.trigger.id,\n parentRunId: input.parentRunId,\n spawnKey: input.spawnKey,\n spec: clone(input.spec),\n status: \"queued\",\n attempt: 0,\n createdAt,\n }\n const trigger: AgentMessageRecord = {\n id: input.trigger.id,\n projectId: input.projectId,\n threadId: input.thread.id,\n runId: input.id,\n role: \"user\",\n seq: nextMessageSeq(this.state, input.projectId, input.thread.id),\n parts: clone(input.trigger.parts),\n ...(input.trigger.metadata === undefined ? {} : { metadata: clone(input.trigger.metadata) }),\n contentVersion: AGENT_MESSAGE_CONTENT_VERSION,\n createdAt,\n }\n if (this.state.messages.has(key(input.projectId, trigger.id))) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent message '${trigger.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n this.state.threads.set(threadKey, clone(thread))\n this.state.messages.set(key(input.projectId, trigger.id), clone(trigger))\n this.state.runs.set(runKey, clone(run))\n return clone(run)\n }\n\n async start(input: StartAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireStatus(input.projectId, input.id, \"queued\")\n const startedAt = new Date(input.startedAt ?? new Date())\n const next: AgentRunRecord = {\n ...run,\n status: \"running\",\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n attempt: 1,\n execution: clone(input.execution),\n startedAt,\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n return clone(next)\n }\n\n async finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireStatus(input.projectId, input.id, \"queued\")\n const completedAt = new Date(input.completedAt ?? new Date())\n const next: AgentRunRecord = {\n ...run,\n status: input.status,\n ...(input.error === undefined ? {} : { error: normalizeFailure(input.error) }),\n completedAt,\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n this.releaseThread(run, completedAt)\n return clone(next)\n }\n\n async reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireRunning(input.projectId, input.id)\n const next: AgentRunRecord = {\n ...run,\n attempt: run.attempt + 1,\n execution: clone(input.execution),\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n return clone(next)\n }\n\n async confirmExecutionOwnership(\n input: ConfirmAgentRunExecutionOwnershipInput\n ): Promise<AgentRunRecord> {\n const run = this.requireRunning(input.projectId, input.id)\n if (!run.execution || run.execution.token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[Sixb] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n\n const next: AgentRunRecord = {\n ...run,\n execution: {\n ...run.execution,\n queueLeaseExpiresAt: new Date(\n Math.max(run.execution.queueLeaseExpiresAt.getTime(), input.queueLeaseExpiresAt.getTime())\n ),\n },\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n return clone(next)\n }\n\n async finish(input: FinishAgentRunInput): Promise<AgentRunRecord> {\n const run = this.requireRunning(input.projectId, input.id)\n if (!run.execution || run.execution.token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[Sixb] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n assertAgentRunFinishPayload(run.kind, input, run.id, \"Sixb\")\n if (input.finishReason === \"awaiting_approval\") {\n assertAwaitingApprovalFinish({\n runId: run.id,\n status: input.status,\n holdsApproval: holdsRun(this.state, run.projectId, run.id),\n })\n }\n\n const completedAt = new Date(input.completedAt ?? new Date())\n const next: AgentRunRecord = {\n ...run,\n status: input.status,\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n ...(input.finishReason === undefined ? {} : { finishReason: input.finishReason }),\n ...(input.diagnostics === undefined ? {} : { diagnostics: clone(input.diagnostics) }),\n ...(input.status === \"succeeded\" && input.result !== undefined\n ? { result: clone(input.result) }\n : {}),\n ...(input.status === \"succeeded\" || input.error === undefined\n ? {}\n : { error: normalizeFailure(input.error) }),\n execution: undefined,\n completedAt,\n }\n this.state.runs.set(key(input.projectId, input.id), clone(next))\n\n this.releaseThread(run, completedAt)\n this.settleApprovals(run, input, completedAt)\n\n return clone(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null> {\n const record = this.state.runs.get(key(params.projectId, params.id))\n return record ? clone(record) : null\n }\n\n async getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]> {\n return [...new Set(params.ids)]\n .map((id) => this.state.runs.get(key(params.projectId, id)))\n .filter((record): record is AgentRunRecord => record !== undefined)\n .map(clone)\n }\n\n async listThreadSubagents(\n input: ListThreadSubagentsInput\n ): Promise<readonly SubagentRunRecord[]> {\n const runs = [...this.state.runs.values()].filter((run) => run.projectId === input.projectId)\n const turns = new Map(\n runs.flatMap((run) =>\n run.kind === \"conversation\" && run.threadId === input.threadId ? [[run.id, run]] : []\n )\n )\n const children = runs\n .filter((run): run is SubagentRunRecord => run.kind === \"subagent\")\n .filter((run) => turns.has(run.parentRunId))\n .filter((run) => (input.spawnKey === undefined ? true : run.spawnKey === input.spawnKey))\n .filter((run) =>\n input.finishReason === undefined ? true : run.finishReason === input.finishReason\n )\n .sort((left, right) => {\n const [a, b] = [turns.get(left.parentRunId), turns.get(right.parentRunId)]\n return (\n compareByDate(\n a?.startedAt ?? a?.createdAt,\n b?.startedAt ?? b?.createdAt,\n left.parentRunId,\n right.parentRunId,\n \"desc\"\n ) || compareByDate(left.createdAt, right.createdAt, left.id, right.id, \"desc\")\n )\n })\n return children.slice(0, input.limit ?? 100).map(clone)\n }\n\n async list(input: ListAgentRunsInput): Promise<ListAgentRunsResult> {\n const order = input.order ?? \"desc\"\n const statuses = input.statuses ? new Set(input.statuses) : null\n const kinds = input.kinds ? new Set(input.kinds) : null\n\n const filtered = [...this.state.runs.values()]\n .filter((run) => run.projectId === input.projectId)\n .filter((run) => (kinds ? kinds.has(run.kind) : true))\n .filter((run) => (input.threadId ? run.threadId === input.threadId : true))\n .filter((run) =>\n input.parentRunId ? run.kind === \"subagent\" && run.parentRunId === input.parentRunId : true\n )\n .filter((run) => (statuses ? statuses.has(run.status) : true))\n .filter((run) =>\n input.startedAfter ? (run.startedAt ?? run.createdAt) >= input.startedAfter : true\n )\n .filter((run) =>\n input.startedBefore ? (run.startedAt ?? run.createdAt) <= input.startedBefore : true\n )\n .sort((a, b) =>\n compareByDate(a.startedAt ?? a.createdAt, b.startedAt ?? b.createdAt, a.id, b.id, order)\n )\n\n const { page, hasMore, total } = applyWindow(filtered, input.offset, input.limit)\n return { runs: page.map(clone), hasMore, total }\n }\n\n private requireRunning(projectId: string, id: string): AgentRunRecord {\n return this.requireStatus(projectId, id, \"running\")\n }\n\n private requireStatus(\n projectId: string,\n id: string,\n status: AgentRunRecord[\"status\"]\n ): AgentRunRecord {\n const run = this.state.runs.get(key(projectId, id))\n if (!run) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[Sixb] Agent run '${id}' not found for project '${projectId}'.`\n )\n }\n if (run.status !== status) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent run '${id}' is not ${status} (status '${run.status}').`\n )\n }\n return run\n }\n\n /**\n * A turn that pauses keeps its calls for their decision. A turn that ends any other way cancels\n * the ones still waiting, a late one included, and never resumes on the rest. A child that fails\n * or is cancelled takes its own pending calls with it.\n */\n private settleApprovals(run: AgentRunRecord, input: FinishAgentRunInput, at: Date): void {\n if (input.finishReason === \"awaiting_approval\" || !agentRunMayHoldCalls(run)) return\n\n const turn = run.kind === \"conversation\"\n if (!turn && input.status === \"succeeded\") return\n for (const [approvalKey, approval] of this.state.approvals) {\n if (approval.projectId !== run.projectId) continue\n const ownCall = approval.runId === run.id || approval.callerRunId === run.id\n const cancel = approval.status === \"pending\" && ownCall\n const stop =\n turn &&\n approval.runId === run.id &&\n approval.reportedInMessageId === undefined &&\n approval.turnStoppedAt === undefined\n if (!cancel && !stop) continue\n\n this.state.approvals.set(approvalKey, {\n ...approval,\n ...(cancel ? { status: \"cancelled\" as const } : {}),\n ...(stop ? { turnStoppedAt: new Date(at) } : {}),\n })\n }\n }\n\n /** A turn releases its conversation, a child run its own thread. */\n private releaseThread(run: AgentRunRecord, completedAt: Date): void {\n const threadKey = key(run.projectId, run.threadId)\n const thread = this.state.threads.get(threadKey)\n if (thread && thread.activeRunId === run.id) {\n this.state.threads.set(\n threadKey,\n clone({ ...thread, activeRunId: null, updatedAt: completedAt })\n )\n }\n }\n}\n\n// ── messages ──────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentMessageStore implements AgentMessageStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async append(input: AppendAgentMessageInput): Promise<AgentMessageRecord> {\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n const messageKey = key(input.projectId, input.id)\n if (this.state.messages.has(messageKey)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent message '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n if (input.runId !== null && !this.state.runs.has(key(input.projectId, input.runId))) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[Sixb] Agent run '${input.runId}' not found for project '${input.projectId}'.`\n )\n }\n\n const createdAt = new Date(input.createdAt ?? new Date())\n const seq = nextMessageSeq(this.state, input.projectId, input.threadId)\n const message: AgentMessageRecord = {\n id: input.id,\n projectId: input.projectId,\n threadId: input.threadId,\n runId: input.runId,\n role: input.role,\n ...(input.authorPrincipal === undefined\n ? {}\n : { authorPrincipal: clone(input.authorPrincipal) }),\n seq,\n parts: clone(input.parts),\n ...(input.metadata === undefined ? {} : { metadata: clone(input.metadata) }),\n contentVersion: AGENT_MESSAGE_CONTENT_VERSION,\n createdAt,\n ...(input.completedAt === undefined ? {} : { completedAt: new Date(input.completedAt) }),\n }\n this.state.messages.set(messageKey, clone(message))\n\n this.state.threads.set(\n threadKey,\n clone({\n ...thread,\n messageCount: thread.messageCount + (countsAsThreadMessage(input) ? 1 : 0),\n lastMessageAt: createdAt,\n updatedAt: createdAt,\n })\n )\n\n return clone(message)\n }\n\n async deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number> {\n const threadKey = key(input.projectId, input.threadId)\n const thread = this.state.threads.get(threadKey)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n const messages = [...this.state.messages.entries()].filter(\n ([, message]) =>\n message.projectId === input.projectId &&\n message.threadId === input.threadId &&\n message.runId === input.runId\n )\n if (messages.length === 0) {\n return 0\n }\n\n for (const [messageKey] of messages) {\n this.state.messages.delete(messageKey)\n }\n\n const remainingMessages = [...this.state.messages.values()]\n .filter(\n (message) => message.projectId === input.projectId && message.threadId === input.threadId\n )\n .sort((left, right) => right.seq - left.seq)\n const latestMessage = remainingMessages[0]\n const updatedAt = new Date()\n this.state.threads.set(\n threadKey,\n clone({\n ...thread,\n messageCount: remainingMessages.filter(countsAsThreadMessage).length,\n lastMessageAt: latestMessage?.createdAt,\n updatedAt,\n })\n )\n\n return messages.length\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null> {\n const record = this.state.messages.get(key(params.projectId, params.id))\n return record ? clone(record) : null\n }\n\n async list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult> {\n const order = input.order ?? \"asc\"\n const roles = input.roles ? new Set(input.roles) : null\n\n const filtered = [...this.state.messages.values()]\n .filter((message) => message.projectId === input.projectId)\n .filter((message) => message.threadId === input.threadId)\n .filter((message) => (input.afterSeq === undefined ? true : message.seq > input.afterSeq))\n .filter((message) => (roles ? roles.has(message.role) : true))\n .sort((a, b) => (order === \"asc\" ? a.seq - b.seq : b.seq - a.seq))\n\n const { page, hasMore, total } = applyWindow(filtered, input.offset, input.limit)\n return { messages: page.map(clone), hasMore, total }\n }\n}\n\nfunction nextMessageSeq(state: AgentStoreState, projectId: string, threadId: string): number {\n let max = 0\n for (const message of state.messages.values()) {\n if (message.projectId === projectId && message.threadId === threadId && message.seq > max) {\n max = message.seq\n }\n }\n return max + 1\n}\n\n// ── context checkpoints ──────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentContextCheckpointStore implements AgentContextCheckpointStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord> {\n assertCreateAgentContextCheckpointInput(input)\n\n // No `await` between authority checks and append: this is one in-memory critical section.\n const run = this.state.runs.get(key(input.projectId, input.createdByRunId)) ?? null\n const thread = this.state.threads.get(key(input.projectId, input.threadId)) ?? null\n assertAgentContextCheckpointAuthority({ create: input, run, thread })\n\n const messages = [...this.state.messages.values()].filter(\n (message) => message.projectId === input.projectId && message.threadId === input.threadId\n )\n const headSeq = messages.reduce((head, message) => Math.max(head, message.seq), 0)\n const latest = this.findLatest(input.projectId, input.threadId)\n\n const existingForRun = [...this.state.checkpoints.values()].find(\n (checkpoint) =>\n checkpoint.projectId === input.projectId &&\n checkpoint.threadId === input.threadId &&\n checkpoint.createdByRunId === input.createdByRunId\n )\n if (existingForRun) {\n if (agentContextCheckpointMatchesCreateInput(existingForRun, input)) {\n assertAgentContextCheckpointReplayState({\n create: input,\n existing: existingForRun,\n latest,\n headSeq,\n })\n return clone(existingForRun)\n }\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent run '${input.createdByRunId}' already created a different context checkpoint.`\n )\n }\n\n if (this.state.checkpoints.has(key(input.projectId, input.id))) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent context checkpoint '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const firstRetained =\n messages\n .filter((message) => message.seq > input.summarizedThroughSeq)\n .sort((left, right) => left.seq - right.seq)[0] ?? null\n assertAgentContextCheckpointAnchors({\n create: input,\n latest,\n headSeq,\n firstRetained,\n })\n\n const record: AgentContextCheckpointRecord = {\n id: input.id,\n projectId: input.projectId,\n threadId: input.threadId,\n createdByRunId: input.createdByRunId,\n ...(input.expectedPreviousCheckpointId === null\n ? {}\n : { previousCheckpointId: input.expectedPreviousCheckpointId }),\n reason: input.reason,\n summary: input.summary,\n summaryFormatVersion: input.summaryFormatVersion,\n summarizedThroughSeq: input.summarizedThroughSeq,\n observedHeadSeq: input.observedHeadSeq,\n estimatedInputTokensBefore: input.estimatedInputTokensBefore,\n estimatedInputTokensAfter: input.estimatedInputTokensAfter,\n summaryModelId: input.summaryModelId,\n createdAt: new Date(input.createdAt ?? new Date()),\n }\n this.state.checkpoints.set(key(input.projectId, input.id), clone(record))\n return clone(record)\n }\n\n async getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null> {\n const record = this.findLatest(input.projectId, input.threadId)\n return record ? clone(record) : null\n }\n\n async getByRunIds(input: {\n readonly projectId: string\n readonly threadId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]> {\n const byRunId = new Map(\n [...this.state.checkpoints.values()]\n .filter((checkpoint) => checkpoint.projectId === input.projectId)\n .filter((checkpoint) => checkpoint.threadId === input.threadId)\n .map((checkpoint) => [checkpoint.createdByRunId, checkpoint] as const)\n )\n return [...new Set(input.runIds)].flatMap((runId) => {\n const checkpoint = byRunId.get(runId)\n return checkpoint ? [clone(checkpoint)] : []\n })\n }\n\n private findLatest(projectId: string, threadId: string): AgentContextCheckpointRecord | null {\n return (\n [...this.state.checkpoints.values()]\n .filter(\n (checkpoint) => checkpoint.projectId === projectId && checkpoint.threadId === threadId\n )\n .sort(compareLatestCheckpoints)[0] ?? null\n )\n }\n}\n\n/** The order `getLatest` reads: the furthest boundary, then the newest. */\nfunction compareLatestCheckpoints(\n left: AgentContextCheckpointRecord,\n right: AgentContextCheckpointRecord\n): number {\n return (\n right.summarizedThroughSeq - left.summarizedThroughSeq ||\n right.createdAt.getTime() - left.createdAt.getTime() ||\n right.id.localeCompare(left.id)\n )\n}\n\n// ── memory ────────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentMemoryStore implements AgentMemoryStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async get(input: {\n projectId: string\n repoId: string\n asOf?: Date\n revision?: number\n }): Promise<AgentMemoryRepoRecord> {\n const repo = this.state.memory.get(key(input.projectId, input.repoId))\n const { asOf, revision: upTo } = input\n const saved = repo?.revisions.filter(\n (entry) =>\n (!asOf || entry.createdAt.getTime() <= asOf.getTime()) &&\n (upTo === undefined || entry.revision <= upTo)\n )\n const revision = saved?.reduce((highest, entry) => Math.max(highest, entry.revision), 0) ?? 0\n if (!repo || revision === 0) return { revision: 0, files: [] }\n const files = [\n ...latestMemoryFiles({\n revisions: repo.revisions,\n files: repo.files.filter((file) => file.revision <= revision),\n }).values(),\n ]\n .flatMap((file) =>\n file.contents === null ? [] : [{ path: file.path, contents: file.contents }]\n )\n .sort((left, right) => compareAgentMemoryPaths(left.path, right.path))\n return { revision, files }\n }\n\n async save(input: SaveAgentMemoryInput): Promise<SaveAgentMemoryResult> {\n assertSaveAgentMemoryInput(input)\n const repoKey = key(input.projectId, input.repoId)\n const repo = this.state.memory.get(repoKey) ?? { revisions: [], files: [] }\n const head = repo.revisions.at(-1)?.revision ?? 0\n const conflicts = agentMemoryConflicts(input, head, latestMemoryFiles(repo))\n if (conflicts.length > 0) return { saved: false, revision: head, conflicts }\n\n const revision = head + 1\n const createdAt = input.createdAt ?? new Date()\n const revisions = [\n ...repo.revisions,\n {\n revision,\n message: input.message,\n author: clone(input.author),\n ...(input.source === undefined ? {} : { source: input.source }),\n createdAt: new Date(createdAt),\n },\n ]\n const files = [...repo.files, ...input.changes.map((change) => ({ ...change, revision }))]\n\n const cutoff = agentMemoryHistoryCutoff(createdAt).getTime()\n const savedAt = new Map(revisions.map((entry) => [entry.revision, entry.createdAt.getTime()]))\n const latest = latestMemoryFiles({ revisions, files })\n this.state.memory.set(repoKey, {\n revisions,\n files: files.filter(\n (file) => latest.get(file.path) === file || (savedAt.get(file.revision) ?? 0) >= cutoff\n ),\n })\n return { saved: true, revision }\n }\n\n async listRevisions(\n input: ListAgentMemoryRevisionsInput\n ): Promise<ListAgentMemoryRevisionsResult> {\n const repo = this.state.memory.get(key(input.projectId, input.repoId))\n const newestFirst = [...(repo?.revisions ?? [])].reverse()\n const { page, hasMore, total } = applyWindow(newestFirst, input.offset, input.limit)\n const revisions = page.map(\n (entry): AgentMemoryRevisionRecord => ({\n ...clone(entry),\n changes: (repo?.files ?? [])\n .filter((file) => file.revision === entry.revision)\n .map((file) => ({ path: file.path, deleted: file.contents === null }))\n .sort((left, right) => compareAgentMemoryPaths(left.path, right.path)),\n })\n )\n return { revisions, hasMore, total }\n }\n\n async delete(input: { projectId: string; repoId: string }): Promise<void> {\n this.state.memory.delete(key(input.projectId, input.repoId))\n }\n}\n\n/** Each path's highest-revision version, the deleted ones included. */\nfunction latestMemoryFiles(\n repo: StoredAgentMemoryRepo\n): Map<string, StoredAgentMemoryRepo[\"files\"][number]> {\n const latest = new Map<string, StoredAgentMemoryRepo[\"files\"][number]>()\n for (const file of repo.files) latest.set(file.path, file)\n return latest\n}\n\n// ── approvals ─────────────────────────────────────────────────────────────────────────────────\n\nclass InMemoryAgentApprovalStore implements AgentApprovalStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async request(input: RequestAgentApprovalInput): Promise<RequestAgentApprovalResult> {\n assertRequestAgentApprovalInput(input)\n\n const threadId = assertAgentApprovalCaller({\n request: input,\n turn: this.state.runs.get(key(input.projectId, input.runId)) ?? null,\n caller: this.state.runs.get(key(input.projectId, input.callerRunId)) ?? null,\n })\n const callKey = agentApprovalCallKey(input.call)\n const live = [...this.state.approvals.values()].find(\n (approval) =>\n approval.projectId === input.projectId &&\n approval.threadId === threadId &&\n approval.callKey === callKey &&\n (LIVE_AGENT_APPROVAL_STATUSES as readonly string[]).includes(approval.status)\n )\n if (live) return { approval: clone(live), created: false }\n\n if (this.state.approvals.has(key(input.projectId, input.id))) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[Sixb] Agent approval '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n const approval = newAgentApprovalRecord(input, threadId)\n this.state.approvals.set(key(input.projectId, input.id), clone(approval))\n return { approval: clone(approval), created: true }\n }\n\n async decide(input: DecideAgentApprovalInput): Promise<DecideAgentApprovalResult | null> {\n const approvalKey = key(input.projectId, input.id)\n const approval = this.state.approvals.get(approvalKey)\n if (!approval) return null\n if (approval.status !== \"pending\") return { approval: clone(approval), decided: false }\n\n const decidedAt = new Date(input.decidedAt ?? new Date())\n const next: AgentApprovalRecord =\n approval.expiresAt <= decidedAt\n ? { ...approval, status: \"expired\" }\n : {\n ...approval,\n status: input.decision,\n decidedAt,\n decidedBy: clone(input.decidedBy),\n ...(input.decision === \"approved\" && input.raisedMode !== undefined\n ? { raisedMode: input.raisedMode }\n : {}),\n }\n this.state.approvals.set(approvalKey, clone(next))\n return { approval: clone(next), decided: next.status === input.decision }\n }\n\n async recordOutcome(input: {\n readonly projectId: string\n readonly id: string\n readonly outcome: AgentApprovalOutcome\n }): Promise<AgentApprovalRecord> {\n const approvalKey = key(input.projectId, input.id)\n const approval = this.state.approvals.get(approvalKey)\n if (!approval) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent approval '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n if (approval.status !== \"approved\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[Sixb] Agent approval '${input.id}' is not approved (status '${approval.status}').`\n )\n }\n if (approval.outcome) return clone(approval)\n\n const next = { ...approval, outcome: clone(input.outcome) }\n this.state.approvals.set(approvalKey, clone(next))\n return clone(next)\n }\n\n async settle(input: SettleAgentApprovalsInput): Promise<readonly AgentApprovalRecord[]> {\n const settled: AgentApprovalRecord[] = []\n for (const [approvalKey, approval] of this.state.approvals) {\n if (\n approval.projectId !== input.projectId ||\n approval.threadId !== input.threadId ||\n approval.status !== \"pending\"\n ) {\n continue\n }\n const next = { ...approval, status: input.status }\n this.state.approvals.set(approvalKey, clone(next))\n settled.push(next)\n }\n return settled.sort(compareApprovals).map(clone)\n }\n\n async expireDue(input: {\n readonly projectId: string\n readonly now: Date\n readonly limit?: number\n }): Promise<readonly AgentApprovalRecord[]> {\n const due = [...this.state.approvals.values()]\n .filter(\n (approval) =>\n approval.projectId === input.projectId &&\n approval.status === \"pending\" &&\n approval.expiresAt <= input.now\n )\n .sort(compareApprovals)\n .slice(0, input.limit)\n\n return due.map((approval) => {\n const next = { ...approval, status: \"expired\" as const }\n this.state.approvals.set(key(approval.projectId, approval.id), clone(next))\n return clone(next)\n })\n }\n\n async stop(input: StopAgentApprovalsInput): Promise<StopAgentApprovalsResult> {\n const stoppedAt = new Date(input.stoppedAt ?? new Date())\n const cancelled: AgentApprovalRecord[] = []\n let stopped = 0\n for (const [approvalKey, approval] of this.state.approvals) {\n if (!agentApprovalStops(approval, input)) continue\n\n const cancel = approval.status === \"pending\"\n const stop = approval.turnStoppedAt === undefined\n if (!cancel && !stop) continue\n const next: AgentApprovalRecord = {\n ...approval,\n ...(cancel ? { status: \"cancelled\" as const } : {}),\n ...(stop ? { turnStoppedAt: stoppedAt } : {}),\n }\n this.state.approvals.set(approvalKey, clone(next))\n if (cancel) cancelled.push(next)\n if (stop) stopped += 1\n }\n return { cancelled: cancelled.sort(compareApprovals).map(clone), stopped }\n }\n\n async holdsRun(input: { readonly projectId: string; readonly runId: string }): Promise<boolean> {\n return holdsRun(this.state, input.projectId, input.runId)\n }\n\n async claimExecution(input: {\n readonly projectId: string\n readonly id: string\n readonly claimedAt: Date\n readonly staleBefore: Date\n }): Promise<AgentApprovalRecord | null> {\n const approvalKey = key(input.projectId, input.id)\n const approval = this.state.approvals.get(approvalKey)\n if (!approval || !agentApprovalClaimable(approval, input.staleBefore)) return null\n\n const next = { ...approval, executionClaimedAt: new Date(input.claimedAt) }\n this.state.approvals.set(approvalKey, clone(next))\n return clone(next)\n }\n\n async listRepairable(input: {\n readonly projectId: string\n readonly claimableBefore: Date\n readonly after?: AgentApprovalCursor\n readonly limit: number\n }): Promise<readonly AgentApprovalRecord[]> {\n const { after } = input\n return [...this.state.approvals.values()]\n .filter(\n (approval) =>\n approval.projectId === input.projectId &&\n agentApprovalRepairable(approval, input.claimableBefore) &&\n (after === undefined ||\n approval.createdAt > after.createdAt ||\n (approval.createdAt.getTime() === after.createdAt.getTime() && approval.id > after.id))\n )\n .sort(compareApprovals)\n .slice(0, input.limit)\n .map(clone)\n }\n\n async markReported(input: MarkAgentApprovalsReportedInput): Promise<readonly string[]> {\n const marked: string[] = []\n for (const id of new Set(input.ids)) {\n const approvalKey = key(input.projectId, id)\n const approval = this.state.approvals.get(approvalKey)\n if (\n !approval ||\n approval.threadId !== input.threadId ||\n approval.reportedInMessageId !== undefined ||\n (input.resuming === true && approval.turnStoppedAt !== undefined)\n ) {\n continue\n }\n this.state.approvals.set(approvalKey, { ...approval, reportedInMessageId: input.messageId })\n marked.push(id)\n }\n return marked\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<AgentApprovalRecord | null> {\n const approval = this.state.approvals.get(key(params.projectId, params.id))\n return approval ? clone(approval) : null\n }\n\n async list(input: ListAgentApprovalsInput): Promise<ListAgentApprovalsResult> {\n const matching = [...this.state.approvals.values()]\n .filter((approval) => agentApprovalMatches(approval, input))\n .sort(compareApprovals)\n const { page, hasMore, total } = applyWindow(matching, input.offset, input.limit)\n return { approvals: page.map(clone), hasMore, total }\n }\n}\n\nfunction holdsRun(state: AgentStoreState, projectId: string, runId: string): boolean {\n return [...state.approvals.values()].some(\n (approval) => approval.projectId === projectId && agentApprovalHoldsRun(approval, runId)\n )\n}\n\n/** Oldest first, then by id: the order every provider lists approvals in. */\nfunction compareApprovals(left: AgentApprovalRecord, right: AgentApprovalRecord): number {\n return compareByDate(left.createdAt, right.createdAt, left.id, right.id, \"asc\")\n}\n\nclass InMemoryAgentApprovalModeStore implements AgentApprovalModeStore {\n constructor(private readonly state: AgentStoreState) {}\n\n async getDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null> {\n return this.state.approvalModes.get(defaultModeKey(input)) ?? null\n }\n\n async setDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode\n }): Promise<void> {\n assertAgentApprovalModeInput(input.mode)\n this.state.approvalModes.set(defaultModeKey(input), input.mode)\n }\n\n async getForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null> {\n return this.state.approvalModes.get(threadModeKey(input)) ?? null\n }\n\n async setForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode | null\n }): Promise<void> {\n if (input.mode !== null) assertAgentApprovalModeInput(input.mode)\n if (!this.state.threads.has(key(input.projectId, input.threadId))) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[Sixb] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n if (input.mode === null) {\n this.state.approvalModes.delete(threadModeKey(input))\n return\n }\n this.state.approvalModes.set(threadModeKey(input), input.mode)\n }\n}\n\nfunction defaultModeKey(input: { readonly projectId: string; readonly principal: Principal }) {\n return JSON.stringify([input.projectId, input.principal.type, input.principal.id])\n}\n\nfunction threadModeKey(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n}) {\n return JSON.stringify([input.projectId, input.threadId, input.principal.type, input.principal.id])\n}\n\nexport class InMemoryAgentStorage implements AgentStorage {\n private readonly state: AgentStoreState = {\n threads: new Map(),\n participants: new Map(),\n runs: new Map(),\n messages: new Map(),\n checkpoints: new Map(),\n memory: new Map(),\n approvals: new Map(),\n approvalModes: new Map(),\n }\n\n readonly threads: InMemoryAgentThreadStore\n readonly runs: InMemoryAgentRunStore\n readonly messages: InMemoryAgentMessageStore\n readonly checkpoints: InMemoryAgentContextCheckpointStore\n readonly memory: InMemoryAgentMemoryStore\n readonly approvals: InMemoryAgentApprovalStore\n readonly approvalModes: InMemoryAgentApprovalModeStore\n\n constructor(executions: ExecutionStorage) {\n this.threads = new InMemoryAgentThreadStore(this.state)\n this.runs = new InMemoryAgentRunStore(this.state, executions)\n this.messages = new InMemoryAgentMessageStore(this.state)\n this.checkpoints = new InMemoryAgentContextCheckpointStore(this.state)\n this.memory = new InMemoryAgentMemoryStore(this.state)\n this.approvals = new InMemoryAgentApprovalStore(this.state)\n this.approvalModes = new InMemoryAgentApprovalModeStore(this.state)\n }\n\n snapshot(): InMemoryAgentStorageSnapshot {\n return {\n threads: structuredClone(this.state.threads),\n participants: structuredClone(this.state.participants),\n runs: structuredClone(this.state.runs),\n messages: structuredClone(this.state.messages),\n checkpoints: structuredClone(this.state.checkpoints),\n memory: structuredClone(this.state.memory),\n approvals: structuredClone(this.state.approvals),\n approvalModes: structuredClone(this.state.approvalModes),\n }\n }\n\n restore(snapshot: InMemoryAgentStorageSnapshot): void {\n replace(this.state.threads, snapshot.threads)\n replace(this.state.participants, snapshot.participants)\n replace(this.state.runs, snapshot.runs)\n replace(this.state.messages, snapshot.messages)\n replace(this.state.checkpoints, snapshot.checkpoints)\n replace(this.state.memory, snapshot.memory)\n replace(this.state.approvals, snapshot.approvals)\n replace(this.state.approvalModes, snapshot.approvalModes)\n }\n}\n\nfunction replace<T>(target: Map<string, T>, source: Map<string, T>): void {\n target.clear()\n for (const [k, value] of structuredClone(source)) {\n target.set(k, value)\n }\n}\n",
|
|
8
|
+
"export type AiCostStorageErrorCode = \"missing_usage\" | \"cost_mismatch\"\n\nexport class AiCostStorageError extends Error {\n readonly name = \"AiCostStorageError\"\n\n constructor(\n readonly code: AiCostStorageErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n",
|
|
9
|
+
"import type { AiModelCallUsageRecord, InMemoryAiUsageStorageSnapshot } from \"../ai-usage\"\nimport type { AiAccountingRecordSetItem } from \"./analytics\"\nimport { buildAiAccountingOverview, buildAiModelCallAccountingList } from \"./analytics\"\nimport { AiCostStorageError } from \"./errors\"\nimport { type AiAccountingGroupIdentity, buildAiModelCallGroups } from \"./groups\"\nimport type {\n AiAccountingAttribution,\n AiAccountingOverview,\n AiCostStorage,\n AiCostSummary,\n AiModelCallCostRecord,\n AiMoney,\n ListAiModelCallAccountingInput,\n ListAiModelCallAccountingResult,\n ListAiModelCallGroupsInput,\n ListAiModelCallGroupsResult,\n QueryAiAccountingOverviewInput,\n SummarizeAiCostExecutionsInput,\n} from \"./types\"\nimport { aiModelCallCostMatchesUsage, normalizeAiModelCallCostRecord } from \"./validation\"\n\nexport interface InMemoryAiCostStorageSnapshot {\n readonly recordsByUsage: Map<string, AiModelCallCostRecord>\n}\n\ninterface InMemoryAiCostUsageSource {\n snapshot(): InMemoryAiUsageStorageSnapshot\n}\n\nexport interface InMemoryAiAccountingAttributionSource {\n resolveGroup?(input: {\n readonly projectId: string\n readonly executionId: string\n }): Promise<{ readonly executionId: string; readonly attribution?: AiAccountingAttribution }>\n resolve(input: {\n readonly projectId: string\n readonly executionId: string\n }): Promise<AiAccountingAttribution | undefined>\n}\n\n/** In-memory immutable model-call costs and accounting reads. */\nexport class InMemoryAiCostStorage implements AiCostStorage {\n private readonly recordsByUsage = new Map<string, AiModelCallCostRecord>()\n\n constructor(\n private readonly usage: InMemoryAiCostUsageSource,\n private readonly attribution?: InMemoryAiAccountingAttributionSource\n ) {}\n\n async recordModelCallCost(input: AiModelCallCostRecord): Promise<void> {\n const record = normalizeAiModelCallCostRecord(input)\n const usage = this.usageRecord(record.projectId, record.usageRecordId)\n if (!usage) throw missingUsage(record)\n if (!aiModelCallCostMatchesUsage(record, usage)) {\n throw new AiCostStorageError(\n \"cost_mismatch\",\n `[Sixb] AI valuation for usage '${record.usageRecordId}' does not match its usage record.`\n )\n }\n const key = usageRecordKey(record.projectId, record.usageRecordId)\n if (!this.recordsByUsage.has(key)) this.recordsByUsage.set(key, structuredClone(record))\n }\n\n async summarizeExecutions(\n input: SummarizeAiCostExecutionsInput\n ): Promise<readonly AiCostSummary[]> {\n assertNonBlank(input.projectId, \"cost summary projectId\")\n for (const id of input.executionIds) assertNonBlank(id, \"cost summary executionId\")\n const requested = new Set(input.executionIds)\n const usageByExecution = new Map(input.executionIds.map((id) => [id, [] as string[]]))\n for (const usage of this.usage.snapshot().records.values()) {\n if (usage.projectId === input.projectId && requested.has(usage.executionId)) {\n usageByExecution.get(usage.executionId)!.push(usage.id)\n }\n }\n return input.executionIds.map((id) =>\n this.summarizeUsageIds(input.projectId, usageByExecution.get(id) ?? [])\n )\n }\n\n async queryProjectOverview(input: QueryAiAccountingOverviewInput): Promise<AiAccountingOverview> {\n return buildAiAccountingOverview(input, await this.accountingItems())\n }\n\n async listModelCalls(\n input: ListAiModelCallAccountingInput\n ): Promise<ListAiModelCallAccountingResult> {\n return buildAiModelCallAccountingList(input, await this.accountingItems())\n }\n\n snapshot(): InMemoryAiCostStorageSnapshot {\n return structuredClone({ recordsByUsage: this.recordsByUsage })\n }\n\n async listModelCallGroups(\n input: ListAiModelCallGroupsInput\n ): Promise<ListAiModelCallGroupsResult> {\n const items = await this.accountingItems()\n const roots = new Map<string, Promise<AiAccountingGroupIdentity>>()\n return buildAiModelCallGroups(\n input,\n await Promise.all(\n items.map(async (item) => {\n const key = usageRecordKey(item.usage.projectId, item.usage.executionId)\n let root = roots.get(key)\n if (!root) {\n root =\n this.attribution?.resolveGroup?.({\n projectId: item.usage.projectId,\n executionId: item.usage.executionId,\n }) ??\n Promise.resolve({\n executionId: item.usage.executionId,\n attribution: item.attribution,\n })\n roots.set(key, root)\n }\n return { ...item, root: await root }\n })\n )\n )\n }\n\n restore(snapshot: InMemoryAiCostStorageSnapshot): void {\n replaceMap(this.recordsByUsage, snapshot.recordsByUsage)\n }\n\n /** @internal Immutable accounting source used by in-memory AI limit enforcement. */\n getRecord(projectId: string, usageRecordId: string): AiModelCallCostRecord | null {\n const record = this.recordsByUsage.get(usageRecordKey(projectId, usageRecordId))\n return record ? structuredClone(record) : null\n }\n\n private usageRecord(projectId: string, id: string): AiModelCallUsageRecord | undefined {\n return [...this.usage.snapshot().records.values()].find(\n (record) => record.projectId === projectId && record.id === id\n )\n }\n\n private async accountingItems(): Promise<readonly AiAccountingRecordSetItem[]> {\n return Promise.all(\n [...this.usage.snapshot().records.values()].map(async (usage) => {\n const cost = this.recordsByUsage.get(usageRecordKey(usage.projectId, usage.id))\n const attribution = await this.attribution?.resolve({\n projectId: usage.projectId,\n executionId: usage.executionId,\n })\n return {\n usage,\n ...(attribution ? { attribution } : {}),\n ...(cost ? { cost } : {}),\n }\n })\n )\n }\n\n private summarizeUsageIds(projectId: string, ids: readonly string[]): AiCostSummary {\n const amounts = new Map<string, bigint>()\n let ratedCallCount = 0\n let unpriceableCallCount = 0\n let unvaluedCallCount = 0\n for (const id of ids) {\n const cost = this.recordsByUsage.get(usageRecordKey(projectId, id))\n if (!cost) unvaluedCallCount += 1\n else if (cost.status === \"unpriceable\") unpriceableCallCount += 1\n else {\n ratedCallCount += 1\n addMoney(amounts, cost.money)\n }\n }\n return {\n amounts: [...amounts]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([currency, amount]) => ({ currency, amountNanos: amount.toString() })),\n ratedCallCount,\n unpriceableCallCount,\n unvaluedCallCount,\n }\n }\n}\n\nfunction missingUsage(record: { readonly projectId: string; readonly usageRecordId: string }) {\n return new AiCostStorageError(\n \"missing_usage\",\n `[Sixb] AI usage '${record.usageRecordId}' does not exist in project '${record.projectId}'.`\n )\n}\n\nfunction addMoney(amounts: Map<string, bigint>, money: AiMoney): void {\n amounts.set(money.currency, (amounts.get(money.currency) ?? 0n) + BigInt(money.amountNanos))\n}\n\nfunction usageRecordKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction assertNonBlank(value: string, field: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI ${field} must be nonblank.`)\n }\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) target.set(key, value)\n}\n",
|
|
10
|
+
"import type { AiModelCallCostRecord } from \"../ai-cost\"\nimport type { AiModelCallUsageRecord } from \"../ai-usage\"\nimport type { ExecutionRecord } from \"../executions\"\nimport { AiLimitStorageError } from \"./errors\"\nimport { aiLimitCalendarMonth } from \"./period\"\nimport type { AiLimitAccountingEntry } from \"./provider\"\nimport {\n AiLimitOperationLock,\n aiLimitAccountingEntryAppliesToSubject,\n aiLimitAmountKey,\n aiLimitMeterApplies,\n aiLimitPolicyDimensionKey,\n aiLimitQuantityFromAmount,\n aiLimitReservationBuckets,\n aiLimitReservationRequestKey,\n aiLimitReservationRequestMatches,\n aiLimitSubjectKey,\n aiLimitSubjectsFromAccountingEntry,\n aiModelCallReservationKey,\n assertAiLimitAccountingMatchesReservation,\n assertNonBlank,\n cloneAiLimitPolicy,\n cloneValidDate,\n type NormalizedAiLimitAmount,\n normalizeAiLimitAmount,\n normalizeAiModelCallReservationIdentity,\n normalizeCreateAiLimitPolicy,\n normalizeReserveAiModelCall,\n normalizeUpdateAiLimitPolicy,\n resolveAiLimitActual,\n} from \"./provider\"\nimport type {\n AiLimitPeriod,\n AiLimitPolicy,\n AiLimitPolicyStatus,\n AiLimitQuantity,\n AiLimitStorage,\n AiLimitSubject,\n AiModelCallReservation,\n CreateAiLimitPolicyInput,\n DeleteAiLimitPolicyInput,\n GetAiLimitPolicyInput,\n ListAiLimitPoliciesInput,\n ListAiLimitPolicyStatusesInput,\n MarkAiModelCallReservationUnknownInput,\n ReconcileAiModelCallInput,\n RecordAiModelCallLimitActualsInput,\n ReserveAiModelCallInput,\n ReserveAiModelCallResult,\n UpdateAiLimitPolicyInput,\n} from \"./types\"\n\ninterface AiLimitPeriodState {\n readonly projectId: string\n readonly subject: AiLimitSubject\n readonly meter: AiLimitQuantity[\"meter\"]\n readonly currency: string\n readonly period: AiLimitPeriod\n actual: bigint\n reserved: bigint\n unknown: bigint\n accountingStatus: \"complete\" | \"unavailable\"\n updatedAt: Date\n}\n\nexport interface InMemoryAiLimitStorageOptions {\n readonly executionExists?: (input: {\n readonly projectId: string\n readonly executionId: string\n }) => boolean | Promise<boolean>\n readonly resolveExecution?: (input: {\n readonly projectId: string\n readonly executionId: string\n }) => ExecutionRecord | null | Promise<ExecutionRecord | null>\n readonly resolveUsageRecord?: (input: {\n readonly projectId: string\n readonly usageRecordId: string\n }) => AiModelCallUsageRecord | null | Promise<AiModelCallUsageRecord | null>\n readonly resolveCostRecord?: (input: {\n readonly projectId: string\n readonly usageRecordId: string\n }) => AiModelCallCostRecord | null | Promise<AiModelCallCostRecord | null>\n readonly listUsageRecords?: (input: {\n readonly projectId: string\n }) => readonly AiModelCallUsageRecord[] | Promise<readonly AiModelCallUsageRecord[]>\n}\n\nexport interface InMemoryAiLimitStorageSnapshot {\n readonly policies: Map<string, AiLimitPolicy>\n readonly policyIdsByDimension: Map<string, string>\n readonly periodStates: Map<string, AiLimitPeriodState>\n readonly reservations: Map<string, AiModelCallReservation>\n}\n\n/** In-memory AI limit provider used by development runtimes and contract tests. */\nexport class InMemoryAiLimitStorage implements AiLimitStorage {\n private readonly policies = new Map<string, AiLimitPolicy>()\n private readonly policyIdsByDimension = new Map<string, string>()\n private readonly periodStates = new Map<string, AiLimitPeriodState>()\n private readonly reservations = new Map<string, AiModelCallReservation>()\n private readonly operations = new AiLimitOperationLock()\n\n constructor(private readonly options: InMemoryAiLimitStorageOptions = {}) {}\n\n /** @internal The root transaction must settle queued work before restoring its snapshot. */\n settleOperations(): Promise<void> {\n return this.operations.settle()\n }\n\n async createPolicy(input: CreateAiLimitPolicyInput): Promise<AiLimitPolicy> {\n return this.operations.run(async () => {\n const policy = normalizeCreateAiLimitPolicy(input)\n const key = policyKey(policy.projectId, policy.id)\n const dimensionKey = aiLimitPolicyDimensionKey(policy)\n if (this.policies.has(key) || this.policyIdsByDimension.has(dimensionKey)) {\n throw new AiLimitStorageError(\n \"duplicate_policy\",\n `[Sixb] An AI limit policy already exists for '${aiLimitSubjectKey(policy.subject)}' and '${aiLimitAmountKey(normalizeAiLimitAmount(policy.limit))}'.`\n )\n }\n this.policies.set(key, structuredClone(policy))\n this.policyIdsByDimension.set(dimensionKey, key)\n return cloneAiLimitPolicy(policy)\n })\n }\n\n async updatePolicy(input: UpdateAiLimitPolicyInput): Promise<AiLimitPolicy> {\n return this.operations.run(async () => {\n const update = normalizeUpdateAiLimitPolicy(input)\n const key = policyKey(update.projectId, update.id)\n const existing = this.policies.get(key)\n if (!existing) throw missingPolicy(update.projectId, update.id)\n if (update.limit !== undefined) {\n const previous = normalizeAiLimitAmount(existing.limit)\n const next = normalizeAiLimitAmount(update.limit)\n if (aiLimitAmountKey(previous) !== aiLimitAmountKey(next)) {\n throw new TypeError(\"[Sixb] AI limit policy meter and cost currency are immutable.\")\n }\n }\n const policy: AiLimitPolicy = {\n ...existing,\n ...(update.limit === undefined ? {} : { limit: update.limit }),\n ...(update.enabled === undefined ? {} : { enabled: update.enabled }),\n updatedAt: update.updatedAt,\n }\n this.policies.set(key, structuredClone(policy))\n return cloneAiLimitPolicy(policy)\n })\n }\n\n async deletePolicy(input: DeleteAiLimitPolicyInput): Promise<boolean> {\n return this.operations.run(async () => {\n validatePolicyIdentity(input)\n const key = policyKey(input.projectId, input.id)\n const existing = this.policies.get(key)\n if (!existing) return false\n this.policies.delete(key)\n this.policyIdsByDimension.delete(aiLimitPolicyDimensionKey(existing))\n return true\n })\n }\n\n async getPolicy(input: GetAiLimitPolicyInput): Promise<AiLimitPolicy | null> {\n validatePolicyIdentity(input)\n const policy = this.policies.get(policyKey(input.projectId, input.id))\n return policy ? cloneAiLimitPolicy(policy) : null\n }\n\n async listPolicies(input: ListAiLimitPoliciesInput): Promise<readonly AiLimitPolicy[]> {\n assertNonBlank(input.projectId, \"projectId\")\n return [...this.policies.values()]\n .filter(\n (policy) =>\n policy.projectId === input.projectId && (input.includeDisabled || policy.enabled)\n )\n .sort((left, right) => left.id.localeCompare(right.id))\n .map(cloneAiLimitPolicy)\n }\n\n async listPolicyStatuses(\n input: ListAiLimitPolicyStatusesInput\n ): Promise<readonly AiLimitPolicyStatus[]> {\n return this.operations.run(async () => {\n assertNonBlank(input.projectId, \"projectId\")\n const period = aiLimitCalendarMonth(input.at ?? new Date())\n const existingGroups =\n input.existingGroupIds === undefined ? undefined : new Set(input.existingGroupIds)\n const policies = await this.listPolicies({\n projectId: input.projectId,\n includeDisabled: input.includeDisabled,\n })\n return Promise.all(\n policies.map((policy) => this.policyStatus(policy, period, existingGroups))\n )\n })\n }\n\n async reserveModelCall(input: ReserveAiModelCallInput): Promise<ReserveAiModelCallResult> {\n return this.operations.run(async () => {\n const request = normalizeReserveAiModelCall(input)\n const reservationKey = aiModelCallReservationKey(request.identity)\n const existing = this.reservations.get(reservationKey)\n if (existing) {\n if (!aiLimitReservationRequestMatches(existing, request)) {\n throw new AiLimitStorageError(\n \"reservation_conflict\",\n `[Sixb] AI model-call reservation '${input.callId}' was replayed with different subjects, estimates, or period.`\n )\n }\n if (existing.state !== \"active\") {\n return { status: \"terminal\", reservation: structuredClone(existing), created: false }\n }\n return { status: \"reserved\", reservation: structuredClone(existing), created: false }\n }\n await this.assertExecutionExists(request.identity.projectId, request.identity.executionId)\n\n const enabledPolicies = [...this.policies.values()].filter(\n (policy) => policy.projectId === request.identity.projectId && policy.enabled\n )\n const subjectKeys = new Set(request.subjects.map(aiLimitSubjectKey))\n const estimates = new Map(\n request.estimates.map((quantity) => {\n const amount = normalizeAiLimitAmount(quantity)\n return [aiLimitAmountKey(amount), amount] as const\n })\n )\n const exhaustedPolicies: AiLimitPolicyStatus[] = []\n const unavailablePolicies: AiLimitPolicyStatus[] = []\n const unavailableReasons = new Set<\"missingEstimate\" | \"incompleteAccounting\">()\n for (const policy of enabledPolicies) {\n if (\n !subjectKeys.has(aiLimitSubjectKey(policy.subject)) ||\n !aiLimitMeterApplies(policy.limit.meter, request.modelKind)\n ) {\n continue\n }\n const limit = normalizeAiLimitAmount(policy.limit)\n const estimate = estimates.get(aiLimitAmountKey(limit))\n const status = await this.policyStatus(policy, request.period)\n if (!estimate || status.accountingStatus === \"unavailable\") {\n unavailablePolicies.push(status)\n if (!estimate) unavailableReasons.add(\"missingEstimate\")\n if (status.accountingStatus === \"unavailable\") {\n unavailableReasons.add(\"incompleteAccounting\")\n }\n continue\n }\n const actual = normalizeAiLimitAmount(status.consumption.actual).amount\n const reserved = normalizeAiLimitAmount(status.consumption.reserved).amount\n const unknown = normalizeAiLimitAmount(status.consumption.unknown).amount\n if (actual + reserved + unknown + estimate.amount > limit.amount) {\n exhaustedPolicies.push(status)\n }\n }\n if (unavailablePolicies.length > 0) {\n unavailablePolicies.sort((left, right) => left.policy.id.localeCompare(right.policy.id))\n return {\n status: \"unavailable\",\n unavailablePolicies,\n reasons: [...unavailableReasons].sort(),\n }\n }\n if (exhaustedPolicies.length > 0) {\n exhaustedPolicies.sort((left, right) => left.policy.id.localeCompare(right.policy.id))\n return {\n status: \"denied\",\n exhaustedPolicies,\n resetAt: new Date(\n Math.min(...exhaustedPolicies.map((status) => status.period.resetAt.getTime()))\n ),\n }\n }\n\n const buckets = aiLimitReservationBuckets(\n enabledPolicies,\n request.subjects,\n request.estimates,\n request.modelKind\n )\n if (buckets.length === 0) return { status: \"notRequired\" }\n for (const bucket of buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const state = this.requirePeriodState(\n request.identity.projectId,\n bucket.subject,\n amount,\n request.period\n )\n state.reserved += amount.amount\n state.updatedAt = new Date(request.reservedAt)\n }\n const reservation: AiModelCallReservation = {\n ...request.identity,\n buckets,\n requestKey: aiLimitReservationRequestKey(request),\n period: request.period,\n state: \"active\",\n reservedAt: request.reservedAt,\n updatedAt: new Date(request.reservedAt),\n }\n this.reservations.set(reservationKey, structuredClone(reservation))\n return { status: \"reserved\", reservation: structuredClone(reservation), created: true }\n })\n }\n\n async recordModelCallActuals(input: RecordAiModelCallLimitActualsInput): Promise<void> {\n return this.operations.run(async () => {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.usageRecordId, \"usageRecordId\")\n const recordedAt = cloneValidDate(input.recordedAt ?? new Date(), \"recordedAt\")\n const entry = await this.requireAccountingEntry(input.projectId, input.usageRecordId)\n const period = aiLimitCalendarMonth(entry.occurredAt)\n const subjectKeys = new Set(aiLimitSubjectsFromAccountingEntry(entry).map(aiLimitSubjectKey))\n for (const state of this.periodStates.values()) {\n if (\n state.projectId !== input.projectId ||\n state.period.start.getTime() !== period.start.getTime() ||\n !subjectKeys.has(aiLimitSubjectKey(state.subject))\n ) {\n continue\n }\n const actual = resolveAiLimitActual([entry], state)\n state.actual += actual.amount\n if (actual.accountingStatus === \"unavailable\") state.accountingStatus = \"unavailable\"\n state.updatedAt = new Date(recordedAt)\n }\n })\n }\n\n async reconcileModelCall(input: ReconcileAiModelCallInput): Promise<AiModelCallReservation> {\n return this.operations.run(async () => {\n const identity = normalizeAiModelCallReservationIdentity(input)\n assertNonBlank(input.usageRecordId, \"usageRecordId\")\n const reconciledAt = cloneValidDate(input.reconciledAt ?? new Date(), \"reconciledAt\")\n const key = aiModelCallReservationKey(identity)\n const reservation = this.reservations.get(key)\n if (!reservation) throw missingReservation(identity)\n if (reservation.state === \"reconciled\") {\n if (reservation.usageRecordId === input.usageRecordId) {\n return structuredClone(reservation)\n }\n throw new AiLimitStorageError(\n \"reconciliation_conflict\",\n `[Sixb] AI model-call reservation '${identity.callId}' was reconciled with a different usage record.`\n )\n }\n const accounting = await this.requireAccountingEntry(identity.projectId, input.usageRecordId)\n assertAiLimitAccountingMatchesReservation(reservation, accounting)\n this.reconcileEstimateCounters(reservation, accounting, reconciledAt)\n const reconciled: AiModelCallReservation = {\n ...reservation,\n state: \"reconciled\",\n usageRecordId: input.usageRecordId,\n updatedAt: reconciledAt,\n }\n this.reservations.set(key, structuredClone(reconciled))\n return structuredClone(reconciled)\n })\n }\n\n async markReservationUnknown(\n input: MarkAiModelCallReservationUnknownInput\n ): Promise<AiModelCallReservation> {\n return this.operations.run(async () => {\n const identity = normalizeAiModelCallReservationIdentity(input)\n const markedAt = cloneValidDate(input.markedAt ?? new Date(), \"markedAt\")\n const key = aiModelCallReservationKey(identity)\n const reservation = this.reservations.get(key)\n if (!reservation) throw missingReservation(identity)\n if (reservation.state === \"unknown\") return structuredClone(reservation)\n if (reservation.state !== \"active\") throw invalidState(reservation, \"mark unknown\")\n this.moveEstimateCounter(reservation, \"reserved\", -1n, markedAt)\n this.moveEstimateCounter(reservation, \"unknown\", 1n, markedAt)\n const unknown: AiModelCallReservation = {\n ...reservation,\n state: \"unknown\",\n updatedAt: markedAt,\n }\n this.reservations.set(key, structuredClone(unknown))\n return structuredClone(unknown)\n })\n }\n\n snapshot(): InMemoryAiLimitStorageSnapshot {\n return structuredClone({\n policies: this.policies,\n policyIdsByDimension: this.policyIdsByDimension,\n periodStates: this.periodStates,\n reservations: this.reservations,\n })\n }\n\n restore(snapshot: InMemoryAiLimitStorageSnapshot): void {\n replaceMap(this.policies, snapshot.policies)\n replaceMap(this.policyIdsByDimension, snapshot.policyIdsByDimension)\n replaceMap(this.periodStates, snapshot.periodStates)\n replaceMap(this.reservations, snapshot.reservations)\n }\n\n private async policyStatus(\n policy: AiLimitPolicy,\n period: AiLimitPeriod,\n existingGroups?: ReadonlySet<string>\n ): Promise<AiLimitPolicyStatus> {\n const limit = normalizeAiLimitAmount(policy.limit)\n const state = await this.ensurePeriodState(policy, period)\n const reserved = state.reserved\n const unknown = state.unknown\n const consumed = state.actual + reserved + unknown\n const remaining = limit.amount > consumed ? limit.amount - consumed : 0n\n const quantity = (amount: bigint): AiLimitQuantity =>\n aiLimitQuantityFromAmount({ ...limit, amount })\n return {\n policy: cloneAiLimitPolicy(policy),\n period: structuredClone(period),\n consumption: {\n actual: quantity(state.actual),\n reserved: quantity(reserved),\n unknown: quantity(unknown),\n remaining: quantity(remaining),\n },\n accountingStatus: state.accountingStatus,\n exhausted: consumed >= limit.amount,\n orphaned:\n policy.subject.type === \"group\" &&\n existingGroups !== undefined &&\n !existingGroups.has(policy.subject.id),\n }\n }\n\n private async ensurePeriodState(\n policy: AiLimitPolicy,\n period: AiLimitPeriod\n ): Promise<AiLimitPeriodState> {\n const amount = normalizeAiLimitAmount(policy.limit)\n const key = periodStateKey(policy.projectId, policy.subject, amount, period)\n const existing = this.periodStates.get(key)\n if (existing?.accountingStatus === \"complete\") return existing\n // A late valuation can repair the ledger after this period was cached as unavailable.\n const actual = await this.resolvePolicyActual(policy, period, amount)\n if (existing) {\n existing.actual = actual.amount\n existing.accountingStatus = actual.accountingStatus\n existing.updatedAt = new Date()\n return existing\n }\n const state: AiLimitPeriodState = {\n projectId: policy.projectId,\n subject: structuredClone(policy.subject),\n meter: amount.meter,\n currency: amount.currency,\n period: structuredClone(period),\n actual: actual.amount,\n reserved: 0n,\n unknown: 0n,\n accountingStatus: actual.accountingStatus,\n updatedAt: new Date(),\n }\n this.periodStates.set(key, state)\n return state\n }\n\n private moveEstimateCounter(\n reservation: AiModelCallReservation,\n counter: \"reserved\" | \"unknown\",\n direction: 1n | -1n,\n updatedAt: Date\n ): void {\n for (const bucket of reservation.buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const state = this.requirePeriodState(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period\n )\n state[counter] += direction * amount.amount\n if (state[counter] < 0n) {\n throw new Error(`[Sixb] In-memory AI limit ${counter} counter became negative.`)\n }\n state.updatedAt = new Date(updatedAt)\n }\n }\n\n private reconcileEstimateCounters(\n reservation: AiModelCallReservation,\n entry: AiLimitAccountingEntry,\n updatedAt: Date\n ): void {\n for (const bucket of reservation.buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const state = this.requirePeriodState(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period\n )\n const counter = reservation.state === \"active\" ? \"reserved\" : \"unknown\"\n const actual = resolveAiLimitActual([entry], amount)\n if (actual.accountingStatus === \"complete\") {\n state[counter] -= amount.amount\n } else if (reservation.state === \"active\") {\n state.reserved -= amount.amount\n state.unknown += amount.amount\n }\n if (state.reserved < 0n || state.unknown < 0n) {\n throw new Error(\"[Sixb] In-memory AI limit reservation counter became negative.\")\n }\n state.updatedAt = new Date(updatedAt)\n }\n }\n\n private requirePeriodState(\n projectId: string,\n subject: AiLimitSubject,\n amount: NormalizedAiLimitAmount,\n period: AiLimitPeriod\n ): AiLimitPeriodState {\n const state = this.periodStates.get(periodStateKey(projectId, subject, amount, period))\n if (!state) throw new Error(\"[Sixb] In-memory AI limit period state is inconsistent.\")\n return state\n }\n\n private async assertExecutionExists(projectId: string, executionId: string): Promise<void> {\n if (this.options.resolveExecution) {\n if (await this.options.resolveExecution({ projectId, executionId })) return\n throw new AiLimitStorageError(\n \"missing_execution\",\n `[Sixb] AI limit execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n if (\n this.options.executionExists &&\n (await this.options.executionExists({ projectId, executionId }))\n ) {\n return\n }\n throw new AiLimitStorageError(\n \"missing_execution\",\n `[Sixb] AI limit execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n\n private async resolvePolicyActual(\n policy: AiLimitPolicy,\n period: AiLimitPeriod,\n dimension: NormalizedAiLimitAmount\n ): Promise<ReturnType<typeof resolveAiLimitActual>> {\n if (\n !this.options.listUsageRecords ||\n ((policy.subject.type === \"user\" || policy.subject.type === \"serviceAccount\") &&\n !this.options.resolveExecution)\n ) {\n return { amount: 0n, accountingStatus: \"unavailable\" }\n }\n const records = await this.options.listUsageRecords({ projectId: policy.projectId })\n const entries = await Promise.all(\n records\n .filter(\n (record) =>\n record.occurredAt.getTime() >= period.start.getTime() &&\n record.occurredAt.getTime() < period.end.getTime()\n )\n .map((record) => this.accountingEntry(record))\n )\n return resolveAiLimitActual(\n entries.filter((entry) => aiLimitAccountingEntryAppliesToSubject(entry, policy.subject)),\n dimension\n )\n }\n\n private async requireAccountingEntry(\n projectId: string,\n usageRecordId: string\n ): Promise<AiLimitAccountingEntry> {\n if (!this.options.resolveUsageRecord) {\n throw new AiLimitStorageError(\n \"unavailable_actuals\",\n \"[Sixb] In-memory AI limit storage has no immutable accounting source.\"\n )\n }\n const record = await this.options.resolveUsageRecord({ projectId, usageRecordId })\n if (!record) {\n throw new AiLimitStorageError(\n \"missing_usage_record\",\n `[Sixb] AI usage record '${usageRecordId}' does not exist in project '${projectId}'.`\n )\n }\n return this.accountingEntry(record)\n }\n\n private async accountingEntry(record: AiModelCallUsageRecord): Promise<AiLimitAccountingEntry> {\n const [execution, cost] = await Promise.all([\n this.options.resolveExecution?.({\n projectId: record.projectId,\n executionId: record.executionId,\n }),\n this.options.resolveCostRecord?.({\n projectId: record.projectId,\n usageRecordId: record.id,\n }),\n ])\n const requester = execution?.requestedBy\n return {\n projectId: record.projectId,\n usageRecordId: record.id,\n executionId: record.executionId,\n attempt: record.attempt,\n callId: record.callId,\n occurredAt: new Date(record.occurredAt),\n ...(record.modelKind === undefined ? {} : { modelKind: record.modelKind }),\n ...(record.usage.totalTokens === undefined ? {} : { totalTokens: record.usage.totalTokens }),\n requesterGroupIds: [...record.requesterGroupIds],\n ...(requester?.type === \"user\" || requester?.type === \"serviceAccount\"\n ? { requester: { type: requester.type, id: requester.id } }\n : {}),\n ...(cost?.status === \"rated\"\n ? { valuation: { status: \"rated\" as const, money: structuredClone(cost.money) } }\n : cost\n ? { valuation: { status: \"unavailable\" as const } }\n : {}),\n }\n }\n}\n\nfunction policyKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction periodStateKey(\n projectId: string,\n subject: AiLimitSubject,\n amount: Pick<NormalizedAiLimitAmount, \"meter\" | \"currency\">,\n period: AiLimitPeriod\n): string {\n return JSON.stringify([\n projectId,\n aiLimitSubjectKey(subject),\n amount.meter,\n amount.currency,\n period.start.toISOString(),\n ])\n}\n\nfunction validatePolicyIdentity(input: GetAiLimitPolicyInput): void {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.id, \"policy id\")\n}\n\nfunction missingPolicy(projectId: string, id: string): AiLimitStorageError {\n return new AiLimitStorageError(\n \"missing_policy\",\n `[Sixb] AI limit policy '${id}' does not exist in project '${projectId}'.`\n )\n}\n\nfunction missingReservation(identity: {\n readonly projectId: string\n readonly executionId: string\n readonly attempt: number\n readonly callId: string\n}): AiLimitStorageError {\n return new AiLimitStorageError(\n \"missing_reservation\",\n `[Sixb] AI model-call reservation '${identity.callId}' does not exist for execution '${identity.executionId}' attempt ${identity.attempt}.`\n )\n}\n\nfunction invalidState(reservation: AiModelCallReservation, operation: string): AiLimitStorageError {\n return new AiLimitStorageError(\n \"invalid_reservation_state\",\n `[Sixb] Cannot ${operation} AI model-call reservation '${reservation.callId}' in state '${reservation.state}'.`\n )\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) target.set(key, value)\n}\n",
|
|
11
|
+
"import { timingSafeEqual } from \"node:crypto\"\nimport { createSixbError, parseSixbFailure, toSixbFailure } from \"../../errors/internal\"\nimport { ConnectorConnectionStorageError } from \"./errors\"\nimport type {\n AttachConnectorConnectionRunAuthorizationInput,\n ClaimConnectorConnectionRunCallbackInput,\n ClaimConnectorConnectionRunCallbackResult,\n ClaimConnectorCredentialMutationInput,\n ClaimConnectorCredentialMutationResult,\n ConnectorAuthorizationAttemptRecord,\n ConnectorAuthorizationKey,\n ConnectorAuthorizationRecord,\n ConnectorConnectionKey,\n ConnectorConnectionRecord,\n ConnectorConnectionRunAwaitingProviderRecord,\n ConnectorConnectionRunAwaitingSelectionRecord,\n ConnectorConnectionRunProcessingRecord,\n ConnectorConnectionRunRecord,\n ConnectorConnectionRunSucceededRecord,\n ConnectorConnectionStorage,\n ConnectorCredentialMutationFence,\n CreateConnectorAuthorizationAttemptInput,\n CreateConnectorAuthorizationInput,\n CreateConnectorConnectionRunInput,\n CreateConnectorConnectionSelectionRunInput,\n FinalizeConnectorReauthorizationInput,\n FinishConnectorConnectionRunInput,\n GetConnectorConnectionInput,\n GetConnectorConnectionRunInput,\n InitializeConnectorAuthorizationAccountsInput,\n ListConnectorConnectionsInput,\n MarkConnectorAuthorizationNeedsReauthorizationInput,\n MarkConnectorCredentialMutationExecutingInput,\n PutConnectorConnectionFromRunInput,\n PutConnectorConnectionFromRunResult,\n PutConnectorConnectionInput,\n PutConnectorConnectionResult,\n RecoverExpiredConnectorCredentialMutationInput,\n ReleaseConnectorCredentialMutationInput,\n RenewConnectorCredentialMutationInput,\n StageConnectorCredentialMutationCredentialsInput,\n StageConnectorCredentialMutationRevocationInput,\n WaitForConnectorConnectionRunSelectionInput,\n} from \"./types\"\nimport { CONNECTOR_CONNECTION_RUN_FAILURE_CODES } from \"./types\"\n\nexport interface InMemoryConnectorConnectionStorageSnapshot {\n readonly attempts: Map<string, ConnectorAuthorizationAttemptRecord>\n readonly connectionRuns: Map<string, ConnectorConnectionRunRecord>\n readonly authorizations: Map<string, ConnectorAuthorizationRecord>\n readonly connections: Map<string, ConnectorConnectionRecord>\n}\n\nfunction connectionRunBase(record: ConnectorConnectionRunRecord, updatedAt: Date) {\n return {\n id: record.id,\n projectId: record.projectId,\n connectorId: record.connectorId,\n kind: record.kind,\n owner: structuredClone(record.owner),\n slot: record.slot,\n initiatedByExecutionId: record.initiatedByExecutionId,\n createdAt: new Date(record.createdAt),\n updatedAt: new Date(updatedAt),\n }\n}\n\nfunction expireConnectionRun(\n record: Extract<ConnectorConnectionRunRecord, { readonly status: \"waiting\" }>,\n now: Date\n) {\n return {\n ...connectionRunBase(record, now),\n status: \"expired\" as const,\n ...(record.waitingFor === \"account_selection\"\n ? { authorizationId: record.authorizationId }\n : {}),\n finishedAt: new Date(now),\n }\n}\n\nfunction failExpiredProcessingRun(record: ConnectorConnectionRunProcessingRecord, now: Date) {\n return {\n ...connectionRunBase(record, now),\n status: \"failed\" as const,\n ...(record.authorizationId === undefined ? {} : { authorizationId: record.authorizationId }),\n error: toSixbFailure(\n createSixbError(\n \"internal.unexpected\",\n \"[Sixb] Connector callback processing did not complete before its deadline.\"\n ),\n { allowedCodes: CONNECTOR_CONNECTION_RUN_FAILURE_CODES, at: now }\n ),\n finishedAt: new Date(now),\n }\n}\n\nexport interface InMemoryConnectorConnectionStorageOptions {\n /** Storage-authoritative clock. Durable implementations should use their database clock. */\n readonly now?: () => Date\n}\n\nexport class InMemoryConnectorConnectionStorage implements ConnectorConnectionStorage {\n readonly durability = \"ephemeral\" as const\n private readonly attempts = new Map<string, ConnectorAuthorizationAttemptRecord>()\n private readonly connectionRuns = new Map<string, ConnectorConnectionRunRecord>()\n private readonly authorizations = new Map<string, ConnectorAuthorizationRecord>()\n private readonly connections = new Map<string, ConnectorConnectionRecord>()\n\n constructor(private readonly options: InMemoryConnectorConnectionStorageOptions = {}) {}\n\n async createAuthorizationAttempt(\n input: CreateConnectorAuthorizationAttemptInput\n ): Promise<ConnectorAuthorizationAttemptRecord> {\n assertPositiveDuration(input.ttlMs, \"authorization attempt TTL\")\n if (this.attempts.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"attempt_conflict\",\n \"[Sixb] Connector authorization attempt already exists.\"\n )\n }\n if (input.connectionRunId !== undefined) {\n const run = this.connectionRuns.get(input.connectionRunId)\n const existingAttempt = this.findAuthorizationAttemptByConnectionRunId(input.connectionRunId)\n if (\n !run ||\n existingAttempt ||\n run.projectId !== input.projectId ||\n run.connectorId !== input.connectorId ||\n run.status !== \"waiting\" ||\n run.waitingFor !== \"provider_authorization\" ||\n run.slot !== input.slot ||\n run.initiatedByExecutionId !== input.initiatedByExecutionId\n ) {\n throw new ConnectorConnectionStorageError(\n \"attempt_conflict\",\n \"[Sixb] Connector authorization attempt does not match its connection run.\"\n )\n }\n }\n const now = this.now()\n const record: ConnectorAuthorizationAttemptRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n owner: structuredClone(input.owner),\n slot: input.slot,\n initiatedByExecutionId: input.initiatedByExecutionId,\n stateHash: input.stateHash,\n ...(input.codeVerifier === undefined\n ? {}\n : { codeVerifier: structuredClone(input.codeVerifier) }),\n redirectUri: input.redirectUri,\n ...(input.connectionRunId === undefined ? {} : { connectionRunId: input.connectionRunId }),\n ...(input.returnTo === undefined ? {} : { returnTo: input.returnTo }),\n ...(input.callbackBindingHash === undefined\n ? {}\n : { callbackBindingHash: input.callbackBindingHash }),\n ...(input.reauthorizationId === undefined\n ? {}\n : { reauthorizationId: input.reauthorizationId }),\n ...(input.reauthorizationRevision === undefined\n ? {}\n : { reauthorizationRevision: input.reauthorizationRevision }),\n ...(input.reauthorizationConnectionIds === undefined\n ? {}\n : { reauthorizationConnectionIds: [...input.reauthorizationConnectionIds] }),\n createdAt: now,\n expiresAt: new Date(now.getTime() + input.ttlMs),\n }\n this.attempts.set(record.id, record)\n return structuredClone(record)\n }\n\n async consumeAuthorizationAttempt(\n input: Parameters<ConnectorConnectionStorage[\"consumeAuthorizationAttempt\"]>[0]\n ): Promise<ConnectorAuthorizationAttemptRecord> {\n const record = this.attempts.get(input.id)\n if (record && record.expiresAt.getTime() <= this.now().getTime()) {\n this.attempts.delete(record.id)\n throw invalidAttempt()\n }\n if (\n !record ||\n record.projectId !== input.projectId ||\n record.connectorId !== input.connectorId ||\n record.redirectUri !== input.redirectUri ||\n !safeEqual(record.stateHash, input.stateHash)\n ) {\n throw invalidAttempt()\n }\n\n this.attempts.delete(input.id)\n return structuredClone(record)\n }\n\n async createConnectionRun(\n input: CreateConnectorConnectionRunInput\n ): Promise<ConnectorConnectionRunRecord> {\n assertPositiveDuration(input.ttlMs, \"connection run TTL\")\n if (this.connectionRuns.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"run_conflict\",\n \"[Sixb] Connector connection run already exists.\"\n )\n }\n const now = this.now()\n const record: ConnectorConnectionRunAwaitingProviderRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n kind: input.kind,\n owner: structuredClone(input.owner),\n slot: input.slot,\n initiatedByExecutionId: input.initiatedByExecutionId,\n status: \"waiting\",\n waitingFor: \"provider_authorization\",\n createdAt: now,\n updatedAt: now,\n expiresAt: new Date(now.getTime() + input.ttlMs),\n }\n this.connectionRuns.set(record.id, record)\n return structuredClone(record)\n }\n\n async createConnectionSelectionRun(\n input: CreateConnectorConnectionSelectionRunInput\n ): Promise<ConnectorConnectionRunAwaitingSelectionRecord> {\n assertPositiveDuration(input.ttlMs, \"connection run TTL\")\n if (this.connectionRuns.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"run_conflict\",\n \"[Sixb] Connector connection run already exists.\"\n )\n }\n const authorization = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(authorization, input) ||\n authorization.status !== \"active\" ||\n authorization.credentialMutation\n ) {\n throw authorizationConflict()\n }\n const now = this.now()\n const record: ConnectorConnectionRunAwaitingSelectionRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n kind: \"connect\",\n owner: structuredClone(input.owner),\n slot: input.slot,\n initiatedByExecutionId: input.initiatedByExecutionId,\n status: \"waiting\",\n waitingFor: \"account_selection\",\n authorizationId: input.authorizationId,\n createdAt: now,\n updatedAt: now,\n expiresAt: new Date(now.getTime() + input.ttlMs),\n }\n this.connectionRuns.set(record.id, record)\n return structuredClone(record)\n }\n\n async claimConnectionRunCallback(\n input: ClaimConnectorConnectionRunCallbackInput\n ): Promise<ClaimConnectorConnectionRunCallbackResult | null> {\n assertPositiveDuration(input.processingTtlMs, \"connection run processing TTL\")\n const attempt = this.attempts.get(input.attemptId)\n if (\n !attempt ||\n attempt.projectId !== input.projectId ||\n attempt.connectionRunId === undefined ||\n attempt.returnTo === undefined ||\n attempt.callbackBindingHash === undefined ||\n attempt.redirectUri !== input.redirectUri ||\n !safeEqual(attempt.stateHash, input.stateHash) ||\n !safeEqual(attempt.callbackBindingHash, input.callbackBindingHash)\n ) {\n return null\n }\n\n const run = this.connectionRuns.get(attempt.connectionRunId)\n if (\n !run ||\n run.projectId !== input.projectId ||\n run.connectorId !== attempt.connectorId ||\n run.status !== \"waiting\" ||\n run.waitingFor !== \"provider_authorization\" ||\n run.slot !== attempt.slot ||\n run.initiatedByExecutionId !== attempt.initiatedByExecutionId\n ) {\n return null\n }\n\n const now = this.now()\n this.attempts.delete(attempt.id)\n if (attempt.expiresAt.getTime() <= now.getTime() || run.expiresAt.getTime() <= now.getTime()) {\n const expired = expireConnectionRun(run, now)\n this.connectionRuns.set(run.id, expired)\n return { type: \"expired\", run: structuredClone(expired), returnTo: attempt.returnTo }\n }\n\n const processing: ConnectorConnectionRunProcessingRecord = {\n ...connectionRunBase(run, now),\n status: \"running\" as const,\n processingId: input.processingId,\n callbackStartedAt: now,\n expiresAt: new Date(now.getTime() + input.processingTtlMs),\n ...(attempt.reauthorizationId === undefined\n ? {}\n : { authorizationId: attempt.reauthorizationId }),\n }\n this.connectionRuns.set(run.id, processing)\n return {\n type: \"claimed\",\n run: structuredClone(processing),\n attempt: structuredClone(attempt),\n returnTo: attempt.returnTo,\n }\n }\n\n async attachConnectionRunAuthorization(\n input: AttachConnectorConnectionRunAuthorizationInput\n ): Promise<ConnectorConnectionRunProcessingRecord | null> {\n const run = this.currentConnectionRun(input.runId)\n const authorization = this.authorizations.get(input.authorizationId)\n if (\n !sameConnectionRunScope(run, input) ||\n run.status !== \"running\" ||\n run.processingId !== input.processingId ||\n (run.authorizationId !== undefined && run.authorizationId !== input.authorizationId) ||\n !sameAuthorizationScope(authorization, input) ||\n authorization.status !== \"pending_selection\"\n ) {\n return null\n }\n const updated: ConnectorConnectionRunProcessingRecord = {\n ...run,\n authorizationId: input.authorizationId,\n updatedAt: this.now(),\n }\n this.connectionRuns.set(run.id, updated)\n return structuredClone(updated)\n }\n\n async waitForConnectionRunSelection(input: WaitForConnectorConnectionRunSelectionInput) {\n const run = this.currentConnectionRun(input.runId)\n if (\n !sameConnectionRunScope(run, input) ||\n run.status !== \"running\" ||\n run.kind !== \"connect\" ||\n run.processingId !== input.processingId ||\n run.authorizationId !== input.authorizationId\n ) {\n return null\n }\n const now = this.now()\n const waiting = {\n ...connectionRunBase(run, now),\n status: \"waiting\" as const,\n waitingFor: \"account_selection\" as const,\n authorizationId: input.authorizationId,\n expiresAt: new Date(input.expiresAt),\n }\n this.connectionRuns.set(run.id, waiting)\n return structuredClone(waiting)\n }\n\n async finishConnectionRun(\n input: FinishConnectorConnectionRunInput\n ): Promise<ConnectorConnectionRunRecord | null> {\n const run = this.currentConnectionRun(input.runId)\n if (!sameConnectionRunScope(run, input) || run.status !== \"running\") return null\n if (input.processingId !== run.processingId) return null\n const now = this.now()\n const authorizationId =\n input.status === \"succeeded\"\n ? input.authorizationId\n : input.status === \"failed\"\n ? (input.authorizationId ?? run.authorizationId)\n : run.authorizationId\n if (input.status !== \"succeeded\" && run.kind === \"connect\" && authorizationId) {\n this.markPendingAuthorizationForCleanup(run.connectorId, authorizationId, now)\n }\n const base = connectionRunBase(run, now)\n const finished: ConnectorConnectionRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n status: \"succeeded\",\n authorizationId: input.authorizationId,\n ...(input.cleanupAuthorizationId === undefined\n ? {}\n : { cleanupAuthorizationId: input.cleanupAuthorizationId }),\n connections: structuredClone(input.connections),\n finishedAt: now,\n }\n : input.status === \"failed\"\n ? {\n ...base,\n status: \"failed\",\n ...(authorizationId === undefined ? {} : { authorizationId }),\n error: parseSixbFailure(input.error, CONNECTOR_CONNECTION_RUN_FAILURE_CODES),\n finishedAt: now,\n }\n : {\n ...base,\n status: \"cancelled\",\n ...(authorizationId === undefined ? {} : { authorizationId }),\n finishedAt: now,\n }\n this.connectionRuns.set(run.id, finished)\n return structuredClone(finished)\n }\n\n async listPendingConnectionRuns(\n input: Parameters<ConnectorConnectionStorage[\"listPendingConnectionRuns\"]>[0]\n ): Promise<readonly ConnectorConnectionRunRecord[]> {\n return [...this.connectionRuns.values()]\n .filter(\n (run) =>\n run.projectId === input.projectId &&\n run.connectorId === input.connectorId &&\n (run.status === \"running\" ||\n (run.status === \"waiting\" && run.waitingFor === \"account_selection\"))\n )\n .map((run) => structuredClone(run))\n }\n\n async getConnectionRun(\n input: GetConnectorConnectionRunInput\n ): Promise<ConnectorConnectionRunRecord | null> {\n const run = this.currentConnectionRun(input.runId)\n return sameConnectionRunScope(run, input) ? structuredClone(run) : null\n }\n\n async createAuthorization(\n input: CreateConnectorAuthorizationInput\n ): Promise<ConnectorAuthorizationRecord> {\n assertPositiveDuration(input.selectionTtlMs, \"account selection TTL\")\n if (this.authorizations.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector authorization already exists.\"\n )\n }\n const now = this.now()\n const record: ConnectorAuthorizationRecord = {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n authorizedBy: structuredClone(input.authorizedBy),\n credentials: structuredClone(input.credentials),\n ...(input.credentialExpiresAt === undefined\n ? {}\n : { credentialExpiresAt: new Date(input.credentialExpiresAt) }),\n scopes: [...input.scopes],\n accounts: structuredClone(input.accounts),\n status: \"pending_selection\",\n selectionExpiresAt: new Date(now.getTime() + input.selectionTtlMs),\n revision: 0,\n createdAt: now,\n updatedAt: now,\n }\n this.authorizations.set(record.id, record)\n return structuredClone(record)\n }\n\n async initializeAuthorizationAccounts(\n input: InitializeConnectorAuthorizationAccountsInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(record, input) ||\n record.revision !== input.expectedRevision ||\n record.status !== \"pending_selection\" ||\n record.credentialMutation\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n accounts: structuredClone(input.accounts),\n revision: record.revision + 1,\n updatedAt: this.now(),\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async getAuthorization(\n input: ConnectorAuthorizationKey\n ): Promise<ConnectorAuthorizationRecord | null> {\n const authorization = this.authorizations.get(input.authorizationId)\n return sameAuthorizationScope(authorization, input) ? structuredClone(authorization) : null\n }\n\n async getAuthorizationByConnectionId(\n input: ConnectorConnectionKey\n ): Promise<ConnectorAuthorizationRecord | null> {\n const connection = this.connections.get(input.connectionId)\n if (!sameConnectionScope(connection, input)) return null\n const authorization = this.authorizations.get(connection.authorizationId)\n return sameAuthorizationScope(authorization, input) ? structuredClone(authorization) : null\n }\n\n async claimCredentialMutation(\n input: ClaimConnectorCredentialMutationInput\n ): Promise<ClaimConnectorCredentialMutationResult | null> {\n assertPositiveDuration(input.leaseDurationMs, \"credential mutation lease duration\")\n assertPositiveDuration(input.operationTimeoutMs, \"credential mutation timeout\")\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(record, input) ||\n record.revision !== input.expectedRevision ||\n !canClaimMutation(record.status, input.mutation.kind)\n ) {\n return null\n }\n\n if (record.credentialMutation) {\n const canReplacePrepared =\n record.credentialMutation.phase === \"prepared\" &&\n record.credentialMutation.expiresAt.getTime() <= now.getTime()\n if (!canReplacePrepared) return null\n }\n\n const attached = this.connectedConnectionsForAuthorization(record.id)\n if (\n input.mutation.kind === \"reauthorization\" &&\n !sameIds(\n attached.map((connection) => connection.id),\n input.expectedConnectionIds ?? []\n )\n ) {\n return null\n }\n\n const deadlineAt = new Date(now.getTime() + input.operationTimeoutMs)\n const mutation = {\n ...structuredClone(input.mutation),\n phase: \"prepared\" as const,\n expiresAt: leaseExpiry(now, input.leaseDurationMs, deadlineAt),\n deadlineAt,\n ...(input.mutation.kind === \"reauthorization\"\n ? { expectedConnectionIds: [...(input.expectedConnectionIds ?? [])] }\n : {}),\n }\n const startsRevocation =\n input.mutation.kind === \"revocation\" && record.status !== \"revocation_pending\"\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n status: input.mutation.kind === \"revocation\" ? \"revocation_pending\" : record.status,\n selectionExpiresAt:\n input.mutation.kind === \"revocation\" ? undefined : record.selectionExpiresAt,\n revision: startsRevocation ? record.revision + 1 : record.revision,\n credentialMutation: mutation,\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n\n const disconnected: ConnectorConnectionRecord[] = []\n if (input.mutation.kind === \"revocation\") {\n for (const connection of attached) {\n const updatedConnection = disconnectConnectionRecord(connection, now)\n this.connections.set(connection.id, updatedConnection)\n disconnected.push(structuredClone(updatedConnection))\n }\n }\n return { authorization: structuredClone(updated), disconnected }\n }\n\n async markCredentialMutationExecuting(\n input: MarkConnectorCredentialMutationExecutingInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase !== \"prepared\" ||\n mutationExpired(record, now)\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: { ...record.credentialMutation, phase: \"executing\" },\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async renewCredentialMutation(\n input: RenewConnectorCredentialMutationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n assertPositiveDuration(input.leaseDurationMs, \"credential mutation lease duration\")\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase === \"result_staged\" ||\n mutationExpired(record, now)\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: {\n ...record.credentialMutation,\n expiresAt: leaseExpiry(now, input.leaseDurationMs, record.credentialMutation.deadlineAt),\n },\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async stageCredentialMutationCredentials(\n input: StageConnectorCredentialMutationCredentialsInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase !== \"executing\" ||\n mutationExpired(record, now) ||\n record.credentialMutation.kind === \"revocation\"\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: {\n ...record.credentialMutation,\n phase: \"result_staged\",\n stagedCredentials: {\n credentials: structuredClone(input.credentials),\n ...(input.credentialExpiresAt === undefined\n ? {}\n : { credentialExpiresAt: new Date(input.credentialExpiresAt) }),\n scopes: [...input.scopes],\n },\n },\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async stageCredentialMutationRevocation(\n input: StageConnectorCredentialMutationRevocationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const now = this.now()\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase !== \"executing\" ||\n record.credentialMutation.kind !== \"revocation\" ||\n mutationExpired(record, now)\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n credentialMutation: { ...record.credentialMutation, phase: \"result_staged\" },\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async releaseCredentialMutation(\n input: ReleaseConnectorCredentialMutationInput\n ): Promise<boolean> {\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input, input.holderId) ||\n record.credentialMutation.phase === \"result_staged\"\n ) {\n return false\n }\n this.authorizations.set(record.id, {\n ...record,\n credentialMutation: undefined,\n updatedAt: this.now(),\n })\n return true\n }\n\n async recoverExpiredCredentialMutation(\n input: RecoverExpiredConnectorCredentialMutationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (!sameAuthorizationScope(record, input) || !record.credentialMutation) return null\n if (record.credentialMutation.phase === \"result_staged\") return structuredClone(record)\n\n const now = this.now()\n if (!mutationExpired(record, now)) return null\n const ambiguous = record.credentialMutation.phase === \"executing\"\n const failClosed = ambiguous && record.credentialMutation.kind !== \"revocation\"\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n status: failClosed ? \"needs_reauthorization\" : record.status,\n selectionExpiresAt: failClosed ? undefined : record.selectionExpiresAt,\n revision: failClosed ? record.revision + 1 : record.revision,\n credentialMutation: undefined,\n updatedAt: now,\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async markNeedsReauthorization(\n input: MarkConnectorAuthorizationNeedsReauthorizationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (!matchesMutation(record, input)) return null\n const staged = record.credentialMutation.stagedCredentials\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n ...(staged\n ? {\n credentials: structuredClone(staged.credentials),\n credentialExpiresAt:\n staged.credentialExpiresAt === undefined\n ? undefined\n : new Date(staged.credentialExpiresAt),\n scopes: [...staged.scopes],\n }\n : {}),\n status: \"needs_reauthorization\",\n selectionExpiresAt: undefined,\n revision: record.revision + 1,\n credentialMutation: undefined,\n updatedAt: this.now(),\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async finalizeRefresh(\n input: ConnectorCredentialMutationFence\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n const staged = stagedCredentials(record, input, \"refresh\")\n if (!record || !staged) return null\n const updated = applyStagedCredentials(record, staged, this.now(), {\n status: \"active\",\n accounts: record.accounts,\n })\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async finalizeReauthorization(\n input: FinalizeConnectorReauthorizationInput\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n const staged = stagedCredentials(record, input, \"reauthorization\")\n if (!record || !staged || !record.credentialMutation) return null\n const attached = this.connectedConnectionsForAuthorization(record.id)\n if (\n !sameIds(\n attached.map((connection) => connection.id),\n record.credentialMutation.expectedConnectionIds ?? []\n )\n ) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connections attached to the connector authorization changed during reauthorization.\"\n )\n }\n const accountsById = new Map(input.accounts.map((account) => [account.id, account]))\n if (attached.some((connection) => !accountsById.has(connection.account.id))) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Reauthorized connector grant no longer exposes every attached account.\"\n )\n }\n\n const now = this.now()\n const updated = applyStagedCredentials(record, staged, now, {\n status: \"active\",\n accounts: input.accounts,\n })\n this.authorizations.set(record.id, updated)\n for (const connection of attached) {\n this.connections.set(connection.id, {\n ...connection,\n account: structuredClone(accountsById.get(connection.account.id)!),\n updatedAt: now,\n })\n }\n return structuredClone(updated)\n }\n\n async finalizeRevocation(\n input: ConnectorCredentialMutationFence\n ): Promise<ConnectorAuthorizationRecord | null> {\n const record = this.authorizations.get(input.authorizationId)\n if (\n !matchesMutation(record, input) ||\n record.credentialMutation.kind !== \"revocation\" ||\n record.credentialMutation.phase !== \"result_staged\"\n ) {\n return null\n }\n const updated: ConnectorAuthorizationRecord = {\n ...record,\n status: \"revoked\",\n credentials: undefined,\n credentialExpiresAt: undefined,\n scopes: [],\n accounts: [],\n selectionExpiresAt: undefined,\n revision: record.revision + 1,\n credentialMutation: undefined,\n updatedAt: this.now(),\n }\n this.authorizations.set(record.id, updated)\n return structuredClone(updated)\n }\n\n async putConnection(input: PutConnectorConnectionInput): Promise<PutConnectorConnectionResult> {\n return this.putConnectionNow(input, this.now())\n }\n\n async putConnectionFromRun(\n input: PutConnectorConnectionFromRunInput\n ): Promise<PutConnectorConnectionFromRunResult> {\n const run = this.currentConnectionRun(input.runId)\n if (\n !sameConnectionRunScope(run, input) ||\n run.status !== \"waiting\" ||\n run.waitingFor !== \"account_selection\"\n ) {\n throw invalidRun()\n }\n const now = this.now()\n const result = this.putConnectionNow(\n {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n owner: run.owner,\n slot: run.slot,\n authorizationId: run.authorizationId,\n account: input.account,\n replace: input.replace,\n },\n now\n )\n const succeeded: ConnectorConnectionRunSucceededRecord = {\n ...connectionRunBase(run, now),\n status: \"succeeded\",\n authorizationId: run.authorizationId,\n ...(result.revocationPendingAuthorizationId === undefined\n ? {}\n : { cleanupAuthorizationId: result.revocationPendingAuthorizationId }),\n connections: [structuredClone(result.connection)],\n finishedAt: now,\n }\n this.connectionRuns.set(run.id, succeeded)\n return { ...result, run: structuredClone(succeeded) }\n }\n\n private putConnectionNow(\n input: PutConnectorConnectionInput,\n now: Date\n ): PutConnectorConnectionResult {\n const authorization = this.authorizations.get(input.authorizationId)\n if (\n !sameAuthorizationScope(authorization, input) ||\n !isSelectable(authorization.status) ||\n authorization.credentialMutation?.kind === \"reauthorization\"\n ) {\n throw authorizationConflict()\n }\n const account = authorization.accounts.find((candidate) => candidate.id === input.account.id)\n if (!account) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector connection account is not exposed by its authorization.\"\n )\n }\n const existing = this.findConnectionRecord(input)\n const sameAccount = existing?.account.id === account.id\n if (existing && !sameAccount && !input.replace) {\n throw new ConnectorConnectionStorageError(\n \"connection_conflict\",\n `[Sixb] Connector slot '${input.slot}' is already connected to another account; explicit replacement is required.`\n )\n }\n if (!existing && this.connections.has(input.id)) {\n throw new ConnectorConnectionStorageError(\n \"connection_conflict\",\n \"[Sixb] Connector connection id already exists.\"\n )\n }\n\n let revocationPendingAuthorizationId: string | undefined\n if (existing?.status === \"connected\" && existing.authorizationId !== authorization.id) {\n const previous = this.authorizations.get(existing.authorizationId)\n if (!previous) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Existing connector connection references an unavailable authorization.\"\n )\n }\n const remaining = this.connectedConnectionsForAuthorization(previous.id).filter(\n (connection) => connection.id !== existing.id\n )\n this.assertConnectionCanMove(existing, previous, remaining.length === 0)\n if (remaining.length === 0) {\n const pending = markAuthorizationRevocationPending(previous, now)\n this.authorizations.set(previous.id, pending)\n revocationPendingAuthorizationId = previous.id\n }\n } else if (existing?.status === \"connected\") {\n const previous = this.authorizations.get(existing.authorizationId)\n if (previous) this.assertConnectionCanMove(existing, previous, false)\n }\n\n const updatedAuthorization: ConnectorAuthorizationRecord =\n authorization.status === \"pending_selection\"\n ? {\n ...authorization,\n status: \"active\",\n selectionExpiresAt: undefined,\n revision: authorization.revision + 1,\n updatedAt: now,\n }\n : authorization\n const connection: ConnectorConnectionRecord = existing\n ? {\n ...existing,\n authorizationId: input.authorizationId,\n account: structuredClone(account),\n status: \"connected\",\n disconnectedAt: undefined,\n updatedAt: now,\n }\n : {\n id: input.id,\n projectId: input.projectId,\n connectorId: input.connectorId,\n owner: structuredClone(input.owner),\n slot: input.slot,\n authorizationId: input.authorizationId,\n account: structuredClone(account),\n status: \"connected\",\n createdAt: now,\n updatedAt: now,\n }\n\n if (updatedAuthorization !== authorization) {\n this.authorizations.set(updatedAuthorization.id, updatedAuthorization)\n }\n this.connections.set(connection.id, connection)\n return {\n connection: structuredClone(connection),\n authorization: structuredClone(updatedAuthorization),\n ...(revocationPendingAuthorizationId === undefined\n ? {}\n : { revocationPendingAuthorizationId }),\n created: existing === undefined,\n replaced: existing !== undefined && !sameAccount,\n }\n }\n\n async getConnection(\n input: GetConnectorConnectionInput\n ): Promise<ConnectorConnectionRecord | null> {\n const connection = this.findConnectionRecord(input)\n return connection?.status === \"connected\" ? structuredClone(connection) : null\n }\n\n async getConnectionById(\n input: ConnectorConnectionKey\n ): Promise<ConnectorConnectionRecord | null> {\n const connection = this.connections.get(input.connectionId)\n return sameConnectionScope(connection, input) ? structuredClone(connection) : null\n }\n\n async listConnections(\n input: ListConnectorConnectionsInput\n ): Promise<readonly ConnectorConnectionRecord[]> {\n return [...this.connections.values()]\n .filter((connection) => sameConnectionScope(connection, input))\n .map((connection) => structuredClone(connection))\n }\n\n async listConnectionsByAuthorization(\n input: ConnectorAuthorizationKey\n ): Promise<readonly ConnectorConnectionRecord[]> {\n const authorization = this.authorizations.get(input.authorizationId)\n if (!sameAuthorizationScope(authorization, input)) return []\n return this.connectedConnectionsForAuthorization(input.authorizationId)\n .filter((connection) => sameConnectionScope(connection, input))\n .map((connection) => structuredClone(connection))\n }\n\n async disconnectConnection(input: ConnectorConnectionKey): Promise<{\n readonly connection: ConnectorConnectionRecord\n readonly authorization: ConnectorAuthorizationRecord\n readonly revocationPendingAuthorizationId?: string\n } | null> {\n const connection = this.connections.get(input.connectionId)\n if (\n !connection ||\n connection.projectId !== input.projectId ||\n connection.connectorId !== input.connectorId\n ) {\n return null\n }\n const authorization = this.authorizations.get(connection.authorizationId)\n if (!sameAuthorizationScope(authorization, input)) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector connection references an unavailable authorization.\"\n )\n }\n if (connection.status === \"disconnected\") {\n return {\n connection: structuredClone(connection),\n authorization: structuredClone(authorization),\n ...(authorization.status === \"revocation_pending\"\n ? { revocationPendingAuthorizationId: authorization.id }\n : {}),\n }\n }\n\n const now = this.now()\n const remaining = this.connectedConnectionsForAuthorization(authorization.id).filter(\n (candidate) => candidate.id !== connection.id\n )\n this.assertConnectionCanMove(connection, authorization, remaining.length === 0)\n const disconnected = disconnectConnectionRecord(connection, now)\n this.connections.set(connection.id, disconnected)\n const updatedAuthorization =\n remaining.length === 0\n ? markAuthorizationRevocationPending(authorization, now)\n : authorization\n if (updatedAuthorization !== authorization) {\n this.authorizations.set(authorization.id, updatedAuthorization)\n }\n return {\n connection: structuredClone(disconnected),\n authorization: structuredClone(updatedAuthorization),\n ...(updatedAuthorization.status === \"revocation_pending\" && remaining.length === 0\n ? { revocationPendingAuthorizationId: updatedAuthorization.id }\n : {}),\n }\n }\n\n snapshot(): InMemoryConnectorConnectionStorageSnapshot {\n return {\n attempts: structuredClone(this.attempts),\n connectionRuns: structuredClone(this.connectionRuns),\n authorizations: structuredClone(this.authorizations),\n connections: structuredClone(this.connections),\n }\n }\n\n restore(snapshot: InMemoryConnectorConnectionStorageSnapshot): void {\n replaceMap(this.attempts, snapshot.attempts)\n replaceMap(this.connectionRuns, snapshot.connectionRuns)\n replaceMap(this.authorizations, snapshot.authorizations)\n replaceMap(this.connections, snapshot.connections)\n }\n\n private now(): Date {\n return new Date(this.options.now?.() ?? new Date())\n }\n\n private currentConnectionRun(runId: string): ConnectorConnectionRunRecord | undefined {\n const run = this.connectionRuns.get(runId)\n if (!run || (run.status !== \"waiting\" && run.status !== \"running\")) return run\n\n if (run.status === \"waiting\" && run.waitingFor === \"account_selection\") return run\n const now = this.now()\n if (run.expiresAt.getTime() > now.getTime()) return run\n\n if (run.status === \"waiting\" && run.waitingFor === \"provider_authorization\") {\n const attempt = this.findAuthorizationAttemptByConnectionRunId(run.id)\n if (attempt) this.attempts.delete(attempt.id)\n }\n if (run.status === \"waiting\") {\n const expired = expireConnectionRun(run, now)\n this.connectionRuns.set(run.id, expired)\n return expired\n }\n\n if (run.kind === \"connect\" && run.authorizationId) {\n this.markPendingAuthorizationForCleanup(run.connectorId, run.authorizationId, now)\n }\n const failed = failExpiredProcessingRun(run, now)\n this.connectionRuns.set(run.id, failed)\n return failed\n }\n\n private findConnectionRecord(\n input: GetConnectorConnectionInput\n ): ConnectorConnectionRecord | undefined {\n for (const connection of this.connections.values()) {\n if (\n connection.projectId === input.projectId &&\n connection.connectorId === input.connectorId &&\n connection.owner.type === input.owner.type &&\n connection.slot === input.slot\n ) {\n return connection\n }\n }\n return undefined\n }\n\n private findAuthorizationAttemptByConnectionRunId(\n connectionRunId: string\n ): ConnectorAuthorizationAttemptRecord | undefined {\n for (const attempt of this.attempts.values()) {\n if (attempt.connectionRunId === connectionRunId) return attempt\n }\n return undefined\n }\n\n private connectionRecordsForAuthorization(authorizationId: string): ConnectorConnectionRecord[] {\n return [...this.connections.values()].filter(\n (connection) => connection.authorizationId === authorizationId\n )\n }\n\n private connectedConnectionsForAuthorization(\n authorizationId: string\n ): ConnectorConnectionRecord[] {\n return this.connectionRecordsForAuthorization(authorizationId).filter(\n (connection) => connection.status === \"connected\"\n )\n }\n\n private assertConnectionCanMove(\n _connection: ConnectorConnectionRecord,\n authorization: ConnectorAuthorizationRecord,\n removingLastConnection = true\n ): void {\n const mutation = authorization.credentialMutation\n if (mutation?.kind === \"reauthorization\") {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connections cannot change while their connector authorization is being reauthorized.\"\n )\n }\n if (removingLastConnection && mutation) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] The last connector connection cannot be removed while credentials are being mutated.\"\n )\n }\n }\n\n private markPendingAuthorizationForCleanup(\n connectorId: string,\n authorizationId: string,\n now: Date\n ): void {\n const authorization = this.authorizations.get(authorizationId)\n if (\n !authorization ||\n authorization.connectorId !== connectorId ||\n authorization.status !== \"pending_selection\"\n ) {\n return\n }\n this.authorizations.set(\n authorization.id,\n markAuthorizationRevocationPending(authorization, now)\n )\n }\n}\n\nfunction disconnectConnectionRecord(\n connection: ConnectorConnectionRecord,\n now: Date\n): ConnectorConnectionRecord {\n return {\n ...connection,\n status: \"disconnected\",\n disconnectedAt: new Date(now),\n updatedAt: new Date(now),\n }\n}\n\nfunction markAuthorizationRevocationPending(\n authorization: ConnectorAuthorizationRecord,\n now: Date\n): ConnectorAuthorizationRecord {\n if (authorization.status === \"revocation_pending\" || authorization.status === \"revoked\") {\n return authorization\n }\n if (authorization.credentialMutation) {\n throw new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector authorization cannot begin revocation while credentials are being mutated.\"\n )\n }\n return {\n ...authorization,\n status: \"revocation_pending\",\n selectionExpiresAt: undefined,\n revision: authorization.revision + 1,\n updatedAt: new Date(now),\n }\n}\n\nfunction safeEqual(left: string, right: string): boolean {\n const leftBytes = Buffer.from(left)\n const rightBytes = Buffer.from(right)\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes)\n}\n\nfunction invalidRun(): ConnectorConnectionStorageError {\n return new ConnectorConnectionStorageError(\n \"run_invalid\",\n \"[Sixb] Connector connection run is invalid, expired, or already used.\"\n )\n}\n\nfunction replaceMap<TKey, TValue>(target: Map<TKey, TValue>, source: Map<TKey, TValue>): void {\n target.clear()\n for (const [key, value] of structuredClone(source)) target.set(key, value)\n}\n\nfunction sameIds(left: readonly string[], right: readonly string[]): boolean {\n const leftSorted = [...left].sort()\n const rightSorted = [...right].sort()\n return (\n leftSorted.length === rightSorted.length &&\n leftSorted.every((value, index) => value === rightSorted[index])\n )\n}\n\nfunction invalidAttempt(): ConnectorConnectionStorageError {\n return new ConnectorConnectionStorageError(\n \"attempt_invalid\",\n \"[Sixb] Connector authorization attempt is invalid, expired, or already used.\"\n )\n}\n\nfunction authorizationConflict(): ConnectorConnectionStorageError {\n return new ConnectorConnectionStorageError(\n \"authorization_conflict\",\n \"[Sixb] Connector connection requires a selectable authorization from the same project and connector.\"\n )\n}\n\nfunction assertPositiveDuration(value: number, name: string): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new ConnectorConnectionStorageError(\n \"invalid_input\",\n `[Sixb] Connector ${name} must be positive.`\n )\n }\n}\n\nfunction sameAuthorizationScope(\n record: ConnectorAuthorizationRecord | undefined,\n input: { readonly projectId: string; readonly connectorId: string }\n): record is ConnectorAuthorizationRecord {\n return (\n record !== undefined &&\n record.projectId === input.projectId &&\n record.connectorId === input.connectorId\n )\n}\n\nfunction sameConnectionScope(\n record: ConnectorConnectionRecord | undefined,\n input: { readonly projectId: string; readonly connectorId: string }\n): record is ConnectorConnectionRecord {\n return (\n record !== undefined &&\n record.projectId === input.projectId &&\n record.connectorId === input.connectorId\n )\n}\n\nfunction sameConnectionRunScope(\n record: ConnectorConnectionRunRecord | undefined,\n input: { readonly projectId: string; readonly connectorId: string }\n): record is ConnectorConnectionRunRecord {\n return (\n record !== undefined &&\n record.projectId === input.projectId &&\n record.connectorId === input.connectorId\n )\n}\n\nfunction canClaimMutation(\n status: ConnectorAuthorizationRecord[\"status\"],\n kind: ClaimConnectorCredentialMutationInput[\"mutation\"][\"kind\"]\n): boolean {\n if (kind === \"refresh\") return status === \"active\"\n if (kind === \"reauthorization\") {\n return status === \"active\" || status === \"needs_reauthorization\"\n }\n return status !== \"revoked\"\n}\n\nfunction isSelectable(status: ConnectorAuthorizationRecord[\"status\"]): boolean {\n return status === \"pending_selection\" || status === \"active\"\n}\n\nfunction leaseExpiry(now: Date, durationMs: number, deadlineAt: Date): Date {\n return new Date(Math.min(now.getTime() + durationMs, deadlineAt.getTime()))\n}\n\nfunction mutationExpired(record: ConnectorAuthorizationRecord, now: Date): boolean {\n return (\n record.credentialMutation!.expiresAt.getTime() <= now.getTime() ||\n record.credentialMutation!.deadlineAt.getTime() <= now.getTime()\n )\n}\n\nfunction matchesMutation(\n record: ConnectorAuthorizationRecord | undefined,\n input: ConnectorCredentialMutationFence,\n holderId?: string\n): record is ConnectorAuthorizationRecord & {\n readonly credentialMutation: NonNullable<ConnectorAuthorizationRecord[\"credentialMutation\"]>\n} {\n return (\n sameAuthorizationScope(record, input) &&\n record.revision === input.expectedRevision &&\n record.credentialMutation?.id === input.mutationId &&\n (holderId === undefined || record.credentialMutation.holderId === holderId)\n )\n}\n\nfunction stagedCredentials(\n record: ConnectorAuthorizationRecord | undefined,\n input: ConnectorCredentialMutationFence,\n kind: \"refresh\" | \"reauthorization\"\n) {\n if (\n !matchesMutation(record, input) ||\n record.credentialMutation.kind !== kind ||\n record.credentialMutation.phase !== \"result_staged\"\n ) {\n return null\n }\n return record.credentialMutation.stagedCredentials ?? null\n}\n\nfunction applyStagedCredentials(\n record: ConnectorAuthorizationRecord,\n staged: NonNullable<ReturnType<typeof stagedCredentials>>,\n now: Date,\n input: {\n readonly status: \"active\"\n readonly accounts: readonly ConnectorAuthorizationRecord[\"accounts\"][number][]\n }\n): ConnectorAuthorizationRecord {\n return {\n ...record,\n credentials: structuredClone(staged.credentials),\n credentialExpiresAt:\n staged.credentialExpiresAt === undefined ? undefined : new Date(staged.credentialExpiresAt),\n scopes: [...staged.scopes],\n accounts: structuredClone(input.accounts),\n status: input.status,\n selectionExpiresAt: undefined,\n revision: record.revision + 1,\n credentialMutation: undefined,\n updatedAt: now,\n }\n}\n",
|
|
12
|
+
"import {\n DurableFileUploadSessions,\n type FileUploadSessionPersistence,\n type FileUploadSessionPersistenceBackend,\n} from \"./provider\"\nimport type {\n CreateFileUploadSessionInput,\n FileUploadSession,\n ListAbandonedFileUploadSessionsInput,\n} from \"./types\"\nimport { isAbandonedFileUploadSession, shouldDeleteFileUploadSession } from \"./utils\"\n\nexport type InMemoryFileUploadSessionsSnapshot = Map<string, FileUploadSession>\n\n/**\n * In-memory {@link FileUploadSessionStore}: the shared durable state machine over a Map.\n *\n * Sessions live only in this process's memory: they do not survive a restart and are not\n * shared across instances, so staged uploads need a single instance. `@sixb/pg` and\n * `@sixb/sqlite` provide durable stores. Reapable sessions are also reaped on `create`.\n */\nexport class InMemoryFileUploadSessions extends DurableFileUploadSessions {\n private readonly sessionsById: Map<string, FileUploadSession>\n\n constructor() {\n const sessionsById = new Map<string, FileUploadSession>()\n super(new InMemoryFileUploadSessionBackend(sessionsById))\n this.sessionsById = sessionsById\n }\n\n override async create(input: CreateFileUploadSessionInput): Promise<FileUploadSession> {\n await this.cleanupExpired()\n return super.create(input)\n }\n\n snapshot(): InMemoryFileUploadSessionsSnapshot {\n return structuredClone(this.sessionsById)\n }\n\n restore(snapshot: InMemoryFileUploadSessionsSnapshot): void {\n this.sessionsById.clear()\n for (const [id, session] of snapshot) {\n this.sessionsById.set(id, structuredClone(session))\n }\n }\n}\n\nclass InMemoryFileUploadSessionBackend implements FileUploadSessionPersistenceBackend {\n private readonly persistence: FileUploadSessionPersistence\n // Every await yields; chaining transactions keeps read-modify-write atomic.\n private tail: Promise<unknown> = Promise.resolve()\n\n constructor(sessionsById: Map<string, FileUploadSession>) {\n this.persistence = new InMemoryFileUploadSessionPersistence(sessionsById)\n }\n\n read<T>(run: (persistence: FileUploadSessionPersistence) => Promise<T>): Promise<T> {\n return run(this.persistence)\n }\n\n transaction<T>(run: (persistence: FileUploadSessionPersistence) => Promise<T>): Promise<T> {\n const result = this.tail.then(() => run(this.persistence))\n this.tail = result.catch(() => undefined)\n return result\n }\n}\n\nclass InMemoryFileUploadSessionPersistence implements FileUploadSessionPersistence {\n constructor(private readonly sessionsById: Map<string, FileUploadSession>) {}\n\n async now(): Promise<Date> {\n return new Date()\n }\n\n async insert(session: FileUploadSession): Promise<boolean> {\n if (this.sessionsById.has(session.id)) return false\n this.sessionsById.set(session.id, session)\n return true\n }\n\n async get(uploadId: string): Promise<FileUploadSession | null> {\n return this.sessionsById.get(uploadId) ?? null\n }\n\n async update(session: FileUploadSession): Promise<void> {\n this.sessionsById.set(session.id, session)\n }\n\n async listAbandoned(\n input: ListAbandonedFileUploadSessionsInput\n ): Promise<readonly FileUploadSession[]> {\n return [...this.sessionsById.values()]\n .filter(\n (session) =>\n session.projectId === input.projectId &&\n isAbandonedFileUploadSession(session, input.now.getTime())\n )\n .sort((left, right) => left.expiresAt.getTime() - right.expiresAt.getTime())\n .slice(0, input.limit)\n }\n\n async deleteReapable(now: Date): Promise<number> {\n let deleted = 0\n for (const [id, session] of this.sessionsById) {\n if (shouldDeleteFileUploadSession(session, now.getTime())) {\n this.sessionsById.delete(id)\n deleted += 1\n }\n }\n return deleted\n }\n}\n",
|
|
13
|
+
"import { AsyncLocalStorage } from \"node:async_hooks\"\nimport { InMemoryActionRunStorage } from \"../action-runs\"\nimport { type ActivityStorage, InMemoryActivityStorage } from \"../activity\"\nimport { type AgentStorage, InMemoryAgentStorage } from \"../agents\"\nimport { type AiAccountingAttribution, type AiCostStorage, InMemoryAiCostStorage } from \"../ai-cost\"\nimport { directModelCallAttribution } from \"../ai-cost/attribution\"\nimport { type AiLimitStorage, InMemoryAiLimitStorage } from \"../ai-limits\"\nimport { type AiUsageStorage, InMemoryAiUsageStorage } from \"../ai-usage\"\nimport { type ArtifactStorage, InMemoryArtifactStorage } from \"../artifacts\"\nimport { type AuthStorage, InMemoryAuthStorage } from \"../auth\"\nimport {\n type ConnectorConnectionStorage,\n InMemoryConnectorConnectionStorage,\n} from \"../connector-connections\"\nimport { StorageTransactionError } from \"../errors\"\nimport { InMemoryExecutionStorage } from \"../executions/in-memory\"\nimport type { ExecutionStorage } from \"../executions/types\"\nimport {\n type FileDownloadGrantStorage,\n InMemoryFileDownloadGrantStorage,\n} from \"../file-download-grants\"\nimport { type FileUploadSessionStore, InMemoryFileUploadSessions } from \"../file-upload-sessions\"\nimport type { ObjectStorage } from \"../objects\"\nimport { InMemoryObjectStorage } from \"../objects/in-memory\"\nimport type { OntologyStorage } from \"../ontology\"\nimport { InMemoryOntologyStorage } from \"../ontology/in-memory\"\nimport { ProviderMaterializationTransactionLifecycle } from \"../ontology/provider\"\nimport {\n createAgentOperationScope,\n createAuthOperationScope,\n createObjectOperationScope,\n createOntologyOperationScope,\n createOperationScopedFacade,\n createStorageOperationScope,\n createWorkflowRunOperationScope,\n} from \"../operation-scope\"\nimport { InMemoryPipelineRunStorage, type PipelineRunStorage } from \"../pipeline-runs\"\nimport { InMemoryProjectionRunStorage } from \"../projection-runs\"\nimport { InMemoryRulesStorage, type RulesStorage } from \"../rules\"\nimport { InMemoryShareGrantStorage, type ShareGrantStorage } from \"../share-grants\"\nimport { InMemoryShareSessionStorage, type ShareSessionStorage } from \"../share-sessions\"\nimport { InMemorySyncRunStorage, type SyncRunStorage } from \"../sync-runs\"\nimport type { TimeseriesStorage } from \"../timeseries\"\nimport { InMemoryTimeseriesStorage } from \"../timeseries/store\"\nimport { createTransactionStorageProxy, throwNestedStorageTransaction } from \"../transaction\"\nimport type { Storage, StorageTransactionOptions } from \"../types\"\nimport { InMemoryWebhookRunStorage, type WebhookRunStorage } from \"../webhook-runs\"\nimport {\n InMemoryWorkflowInterventionStorage,\n type WorkflowInterventionStorage,\n} from \"../workflow-interventions\"\nimport { InMemoryWorkflowRunStorage, type WorkflowRunStorage } from \"../workflow-runs\"\nimport { registerInMemoryStorageTestingAdapter } from \"./testing\"\n\n/**\n * In-memory {@link Storage} used for dev and tests.\n *\n * Every top-level storage call (\"root operation\") serializes against a single promise-chain lock\n * unless a transaction is already active, which is what gives {@link InMemoryStorage.transaction}\n * snapshot/rollback atomicity. The provider owns one operation scope and applies it to every async\n * root capability. Transaction calls reuse the already-active scope and therefore never reacquire\n * its non-reentrant lock.\n */\nexport interface InMemoryStorageOptions {\n readonly connectorConnections?: {\n /** Storage-authoritative clock override for deterministic development and tests. */\n readonly now?: () => Date\n }\n}\n\nexport class InMemoryStorage implements Storage {\n readonly objects: ObjectStorage\n readonly timeseries: TimeseriesStorage\n readonly ontology: OntologyStorage\n private readonly objectStorage = new InMemoryObjectStorage()\n private readonly timeseriesStorage = new InMemoryTimeseriesStorage()\n private readonly ontologyStorage: InMemoryOntologyStorage\n private readonly authStorage = new InMemoryAuthStorage()\n private readonly shareGrantStorage = new InMemoryShareGrantStorage()\n private readonly shareSessionStorage = new InMemoryShareSessionStorage(this.shareGrantStorage)\n private readonly executionStorage = new InMemoryExecutionStorage(this.authStorage, {\n shareSessions: this.shareSessionStorage,\n })\n private readonly agentStorage = new InMemoryAgentStorage(this.executionStorage)\n private readonly artifactStorage = new InMemoryArtifactStorage()\n private readonly aiUsageStorage = new InMemoryAiUsageStorage(this.executionStorage)\n private readonly aiCostStorage = new InMemoryAiCostStorage(this.aiUsageStorage, {\n resolve: (input) => this.resolveAiAccountingAttribution(input),\n resolveGroup: async (input) => {\n const attribution = await this.resolveAiAccountingAttribution(input)\n if (attribution?.kind !== \"subagent\") return { executionId: input.executionId, attribution }\n const parent = await this.agentStorage.runs.getById({\n projectId: input.projectId,\n id: attribution.parentRunId,\n })\n if (!parent) throw new Error(\"[Sixb] Subagent accounting parent is missing.\")\n return {\n executionId: parent.executionId,\n attribution: await this.resolveAiAccountingAttribution({\n ...input,\n executionId: parent.executionId,\n }),\n }\n },\n })\n private readonly aiLimitStorage = new InMemoryAiLimitStorage({\n resolveExecution: ({ projectId, executionId }) =>\n this.executionStorage.getById({ projectId, id: executionId }),\n resolveUsageRecord: ({ projectId, usageRecordId }) =>\n this.aiUsageStorage.getRecord(projectId, usageRecordId),\n resolveCostRecord: ({ projectId, usageRecordId }) =>\n this.aiCostStorage.getRecord(projectId, usageRecordId),\n listUsageRecords: ({ projectId }) => this.aiUsageStorage.listRecords(projectId),\n })\n private readonly actionRunStorage = new InMemoryActionRunStorage(this.executionStorage)\n private readonly syncRunStorage = new InMemorySyncRunStorage(this.executionStorage)\n private readonly pipelineRunStorage = new InMemoryPipelineRunStorage(this.executionStorage)\n private readonly projectionRunStorage = new InMemoryProjectionRunStorage({\n executions: this.executionStorage,\n })\n private readonly workflowRunStorage = new InMemoryWorkflowRunStorage(this.executionStorage)\n private readonly workflowInterventionStorage = new InMemoryWorkflowInterventionStorage()\n private readonly webhookRunStorage = new InMemoryWebhookRunStorage(this.executionStorage)\n private readonly rulesStorage = new InMemoryRulesStorage()\n private readonly fileUploadSessionStorage = new InMemoryFileUploadSessions()\n private readonly fileDownloadGrantStorage = new InMemoryFileDownloadGrantStorage()\n private readonly connectorConnectionStorage: InMemoryConnectorConnectionStorage\n private readonly activityStorage = new InMemoryActivityStorage()\n readonly auth: AuthStorage\n readonly executions: ExecutionStorage\n readonly agents: AgentStorage\n readonly artifacts: ArtifactStorage\n readonly aiUsage: AiUsageStorage\n readonly aiCosts: AiCostStorage\n readonly aiLimits: AiLimitStorage\n readonly actionRuns: InMemoryActionRunStorage\n readonly syncRuns: SyncRunStorage\n readonly pipelineRuns: PipelineRunStorage\n readonly projectionRuns: InMemoryProjectionRunStorage\n readonly workflowRuns: WorkflowRunStorage\n readonly workflowInterventions: WorkflowInterventionStorage\n readonly webhookRuns: WebhookRunStorage\n readonly rules: RulesStorage\n readonly shareGrants: ShareGrantStorage\n readonly shareSessions: ShareSessionStorage\n readonly fileUploadSessions: FileUploadSessionStore\n readonly fileDownloadGrants: FileDownloadGrantStorage\n readonly connectorConnections: ConnectorConnectionStorage\n readonly activity: ActivityStorage\n\n constructor(options: InMemoryStorageOptions = {}) {\n this.connectorConnectionStorage = new InMemoryConnectorConnectionStorage(\n options.connectorConnections\n )\n const scope = createStorageOperationScope(\n (run) => this.withStorageOperation(run),\n () => this.assertRootOperationAvailable()\n )\n this.objects = createObjectOperationScope(this.objectStorage, scope)\n this.timeseries = createOperationScopedFacade(this.timeseriesStorage, scope)\n this.auth = createAuthOperationScope(this.authStorage, scope)\n this.executions = createOperationScopedFacade(this.executionStorage, scope)\n this.agents = createAgentOperationScope(this.agentStorage, scope)\n this.artifacts = createOperationScopedFacade(this.artifactStorage, scope)\n this.aiUsage = createOperationScopedFacade(this.aiUsageStorage, scope)\n this.aiCosts = createOperationScopedFacade(this.aiCostStorage, scope)\n this.aiLimits = createOperationScopedFacade(this.aiLimitStorage, scope)\n this.actionRuns = createOperationScopedFacade(this.actionRunStorage, scope)\n this.syncRuns = createOperationScopedFacade(this.syncRunStorage, scope)\n this.pipelineRuns = createOperationScopedFacade(this.pipelineRunStorage, scope)\n this.projectionRuns = createOperationScopedFacade(this.projectionRunStorage, scope)\n this.workflowRuns = createWorkflowRunOperationScope(this.workflowRunStorage, scope)\n this.workflowInterventions = createOperationScopedFacade(\n this.workflowInterventionStorage,\n scope\n )\n this.webhookRuns = createOperationScopedFacade(this.webhookRunStorage, scope)\n this.rules = createOperationScopedFacade(this.rulesStorage, scope)\n this.shareGrants = createOperationScopedFacade(this.shareGrantStorage, scope)\n this.shareSessions = createOperationScopedFacade(this.shareSessionStorage, scope)\n this.fileUploadSessions = createOperationScopedFacade(this.fileUploadSessionStorage, scope)\n this.fileDownloadGrants = createOperationScopedFacade(this.fileDownloadGrantStorage, scope)\n this.connectorConnections = createOperationScopedFacade(this.connectorConnectionStorage, scope)\n this.activity = createOperationScopedFacade(this.activityStorage, scope)\n this.ontologyStorage = new InMemoryOntologyStorage(this.objectStorage, this.timeseriesStorage, {\n runRootOperation: async (run) => run(),\n getTransactionToken: () => this.getActiveTransactionToken(),\n getMaterializationLifecycle: () => this.getActiveMaterializationLifecycle(),\n assertSourceMaterializationExecution: (input) =>\n this.projectionRunStorage.assertSourceMaterializationExecutionUnlocked(input),\n readExecution: (projectId, executionId) =>\n this.executionStorage.getById({ projectId, id: executionId }),\n })\n this.ontology = createOntologyOperationScope(this.ontologyStorage, scope)\n this.ontologyStorage.registerTestingAlias(this.ontology)\n registerInMemoryStorageTestingAdapter(this, { snapshot: () => this.snapshot() })\n }\n\n private async resolveAiAccountingAttribution(input: {\n readonly projectId: string\n readonly executionId: string\n }): Promise<AiAccountingAttribution | undefined> {\n const execution = await this.executionStorage.getById({\n projectId: input.projectId,\n id: input.executionId,\n })\n if (!execution) return undefined\n if (execution.executor.type !== \"agent\") {\n const executor = execution.executor\n return directModelCallAttribution(\n executor.type === \"primitive\" ? executor.kind : executor.type,\n executor.type === \"request\"\n ? executor.requestId\n : executor.type === \"primitive\"\n ? executor.runId\n : null,\n execution.authorizationRef.type === \"trustedPrimitive\"\n ? execution.authorizationRef.primitive.id\n : null\n )\n }\n const directRun = await this.agentStorage.runs.getById({\n projectId: input.projectId,\n id: execution.executor.runId,\n })\n if (directRun?.kind === \"conversation\") {\n return {\n kind: \"agent\",\n agentRunId: directRun.id,\n threadId: directRun.threadId,\n }\n }\n if (directRun?.kind === \"subagent\") {\n return {\n kind: \"subagent\",\n subagentRunId: directRun.id,\n parentRunId: directRun.parentRunId,\n }\n }\n const agentRun = await this.workflowRunStorage.agentNodes.getByNodeRunId({\n projectId: input.projectId,\n nodeRunId: execution.executor.runId,\n })\n if (!agentRun) return undefined\n const node = await this.workflowRunStorage.nodes.getById({\n projectId: input.projectId,\n id: agentRun.nodeRunId,\n })\n if (!node) return undefined\n return {\n kind: \"workflowAgent\",\n agentStepId: node.nodeId,\n nodeRunId: agentRun.nodeRunId,\n workflowId: node.workflowId,\n workflowRunId: node.workflowRunId,\n }\n }\n\n private readonly transactionScope = new AsyncLocalStorage<object>()\n private readonly activeTransactionTokens = new WeakSet<object>()\n private readonly materializationLifecycles = new WeakMap<\n object,\n ProviderMaterializationTransactionLifecycle\n >()\n private transactionTail: Promise<void> = Promise.resolve()\n\n async ping(): Promise<void> {\n await this.withStorageOperation(() => undefined)\n }\n\n /**\n * Run `run` against a transactional view of this storage.\n *\n * Atomicity is achieved by snapshotting every store before the callback and restoring that\n * snapshot if it throws. The snapshot is a full structural clone of the in-memory dataset, so\n * its cost scales with total dataset size rather than changeset size. That is acceptable for the\n * dev/test role of {@link InMemoryStorage} but is the reason it is not intended for large\n * datasets under heavy transactional load — the SQL providers use real database transactions.\n *\n * The `isolation` option is intentionally ignored: the promise-chain lock serializes\n * transactions one at a time, which is at least as strong as `serializable`.\n */\n async transaction<T>(\n run: (tx: Storage) => Promise<T> | T,\n _options: StorageTransactionOptions = {}\n ): Promise<T> {\n const inheritedTransactionToken = this.transactionScope.getStore()\n if (inheritedTransactionToken && this.activeTransactionTokens.has(inheritedTransactionToken)) {\n throwNestedStorageTransaction()\n }\n\n return this.withTransactionLock(async () => {\n const snapshot = this.snapshot()\n let active = true\n const tx = createTransactionStorageProxy(this.createTransactionStorage(), () => active)\n const transactionToken = {}\n const materializationLifecycle = new ProviderMaterializationTransactionLifecycle()\n this.activeTransactionTokens.add(transactionToken)\n this.materializationLifecycles.set(transactionToken, materializationLifecycle)\n\n try {\n const result = await this.transactionScope.run(transactionToken, async () => {\n try {\n return await run(tx)\n } finally {\n await this.aiLimitStorage.settleOperations()\n }\n })\n materializationLifecycle.assertCommittable()\n return result\n } catch (error) {\n // A failed rollback leaves the store in an unknown state. Surface that explicitly instead\n // of letting the restore error silently replace (mask) the original transaction error.\n try {\n this.restore(snapshot)\n } catch (restoreError) {\n throw new StorageTransactionError(\n `[Sixb] In-memory storage failed to roll back after a transaction error; state may be inconsistent. Original transaction error: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: restoreError }\n )\n }\n throw error\n } finally {\n this.ontologyStorage.completeTransaction(transactionToken)\n materializationLifecycle.deactivate()\n this.activeTransactionTokens.delete(transactionToken)\n active = false\n }\n })\n }\n\n private async withStorageOperation<T>(run: () => Promise<T> | T): Promise<T> {\n this.assertRootOperationAvailable()\n return this.withTransactionLock(async () => run())\n }\n\n private assertRootOperationAvailable(): void {\n if (!this.getActiveTransactionToken()) return\n throw new StorageTransactionError(\n \"[Sixb] Root storage cannot be used inside a transaction callback; use the provided tx storage.\"\n )\n }\n\n private getActiveTransactionToken(): object | null {\n const token = this.transactionScope.getStore()\n return token && this.activeTransactionTokens.has(token) ? token : null\n }\n\n private getActiveMaterializationLifecycle(): ProviderMaterializationTransactionLifecycle | null {\n const token = this.getActiveTransactionToken()\n return token ? (this.materializationLifecycles.get(token) ?? null) : null\n }\n\n private async withTransactionLock<T>(run: () => Promise<T>): Promise<T> {\n const previous = this.transactionTail\n let release!: () => void\n this.transactionTail = new Promise<void>((resolve) => {\n release = resolve\n })\n\n await previous\n try {\n return await run()\n } finally {\n release()\n }\n }\n\n private createTransactionStorage(): Storage {\n return {\n objects: this.objectStorage,\n timeseries: this.timeseriesStorage,\n ontology: this.ontologyStorage,\n auth: this.authStorage,\n executions: this.executionStorage,\n agents: this.agentStorage,\n artifacts: this.artifactStorage,\n aiUsage: this.aiUsageStorage,\n aiCosts: this.aiCostStorage,\n aiLimits: this.aiLimitStorage,\n actionRuns: this.actionRunStorage,\n syncRuns: this.syncRunStorage,\n pipelineRuns: this.pipelineRunStorage,\n projectionRuns: this.projectionRunStorage,\n workflowRuns: this.workflowRunStorage,\n workflowInterventions: this.workflowInterventionStorage,\n webhookRuns: this.webhookRunStorage,\n rules: this.rulesStorage,\n shareGrants: this.shareGrantStorage,\n shareSessions: this.shareSessionStorage,\n fileUploadSessions: this.fileUploadSessionStorage,\n fileDownloadGrants: this.fileDownloadGrantStorage,\n connectorConnections: this.connectorConnectionStorage,\n activity: this.activityStorage,\n ping: async () => undefined,\n transaction: async <T>(): Promise<T> => {\n throwNestedStorageTransaction()\n },\n }\n }\n\n private snapshot(): InMemoryStorageSnapshot {\n return {\n objects: this.objectStorage.snapshot(),\n timeseries: this.timeseriesStorage.snapshot(),\n ontology: this.ontologyStorage.snapshot(),\n auth: this.authStorage.snapshot(),\n executions: this.executionStorage.snapshot(),\n agents: this.agentStorage.snapshot(),\n artifacts: this.artifactStorage.snapshot(),\n aiUsage: this.aiUsageStorage.snapshot(),\n aiCosts: this.aiCostStorage.snapshot(),\n aiLimits: this.aiLimitStorage.snapshot(),\n actionRuns: this.actionRunStorage.snapshot(),\n syncRuns: this.syncRunStorage.snapshot(),\n pipelineRuns: this.pipelineRunStorage.snapshot(),\n projectionRuns: this.projectionRunStorage.snapshot(),\n workflowRuns: this.workflowRunStorage.snapshot(),\n workflowInterventions: this.workflowInterventionStorage.snapshot(),\n webhookRuns: this.webhookRunStorage.snapshot(),\n rules: this.rulesStorage.snapshot(),\n shareGrants: this.shareGrantStorage.snapshot(),\n shareSessions: this.shareSessionStorage.snapshot(),\n fileUploadSessions: this.fileUploadSessionStorage.snapshot(),\n fileDownloadGrants: this.fileDownloadGrantStorage.snapshot(),\n connectorConnections: this.connectorConnectionStorage.snapshot(),\n activity: this.activityStorage.snapshot(),\n }\n }\n\n private restore(snapshot: InMemoryStorageSnapshot): void {\n this.objectStorage.restore(snapshot.objects)\n this.timeseriesStorage.restore(snapshot.timeseries)\n this.ontologyStorage.restore(snapshot.ontology)\n this.authStorage.restore(snapshot.auth)\n this.executionStorage.restore(snapshot.executions)\n this.agentStorage.restore(snapshot.agents)\n this.artifactStorage.restore(snapshot.artifacts)\n this.aiUsageStorage.restore(snapshot.aiUsage)\n this.aiCostStorage.restore(snapshot.aiCosts)\n this.aiLimitStorage.restore(snapshot.aiLimits)\n this.actionRunStorage.restore(snapshot.actionRuns)\n this.syncRunStorage.restore(snapshot.syncRuns)\n this.pipelineRunStorage.restore(snapshot.pipelineRuns)\n this.projectionRunStorage.restore(snapshot.projectionRuns)\n this.workflowRunStorage.restore(snapshot.workflowRuns)\n this.workflowInterventionStorage.restore(snapshot.workflowInterventions)\n this.webhookRunStorage.restore(snapshot.webhookRuns)\n this.rulesStorage.restore(snapshot.rules)\n this.shareGrantStorage.restore(snapshot.shareGrants)\n this.shareSessionStorage.restore(snapshot.shareSessions)\n this.fileUploadSessionStorage.restore(snapshot.fileUploadSessions)\n this.fileDownloadGrantStorage.restore(snapshot.fileDownloadGrants)\n this.connectorConnectionStorage.restore(snapshot.connectorConnections)\n this.activityStorage.restore(snapshot.activity)\n }\n}\n\nexport interface InMemoryStorageSnapshot {\n readonly objects: ReturnType<InMemoryObjectStorage[\"snapshot\"]>\n readonly timeseries: ReturnType<InMemoryTimeseriesStorage[\"snapshot\"]>\n readonly ontology: ReturnType<InMemoryOntologyStorage[\"snapshot\"]>\n readonly auth: ReturnType<InMemoryAuthStorage[\"snapshot\"]>\n readonly executions: ReturnType<InMemoryExecutionStorage[\"snapshot\"]>\n readonly agents: ReturnType<InMemoryAgentStorage[\"snapshot\"]>\n readonly artifacts: ReturnType<InMemoryArtifactStorage[\"snapshot\"]>\n readonly aiUsage: ReturnType<InMemoryAiUsageStorage[\"snapshot\"]>\n readonly aiCosts: ReturnType<InMemoryAiCostStorage[\"snapshot\"]>\n readonly aiLimits: ReturnType<InMemoryAiLimitStorage[\"snapshot\"]>\n readonly actionRuns: ReturnType<InMemoryActionRunStorage[\"snapshot\"]>\n readonly syncRuns: ReturnType<InMemorySyncRunStorage[\"snapshot\"]>\n readonly pipelineRuns: ReturnType<InMemoryPipelineRunStorage[\"snapshot\"]>\n readonly projectionRuns: ReturnType<InMemoryProjectionRunStorage[\"snapshot\"]>\n readonly workflowRuns: ReturnType<InMemoryWorkflowRunStorage[\"snapshot\"]>\n readonly workflowInterventions: ReturnType<InMemoryWorkflowInterventionStorage[\"snapshot\"]>\n readonly webhookRuns: ReturnType<InMemoryWebhookRunStorage[\"snapshot\"]>\n readonly rules: ReturnType<InMemoryRulesStorage[\"snapshot\"]>\n readonly shareGrants: ReturnType<InMemoryShareGrantStorage[\"snapshot\"]>\n readonly shareSessions: ReturnType<InMemoryShareSessionStorage[\"snapshot\"]>\n readonly fileUploadSessions: ReturnType<InMemoryFileUploadSessions[\"snapshot\"]>\n readonly fileDownloadGrants: ReturnType<InMemoryFileDownloadGrantStorage[\"snapshot\"]>\n readonly connectorConnections: ReturnType<InMemoryConnectorConnectionStorage[\"snapshot\"]>\n readonly activity: ReturnType<InMemoryActivityStorage[\"snapshot\"]>\n}\n",
|
|
14
|
+
"import {\n ACTIVITY_MAX_VISIT_MS,\n type ActivitySourceState,\n activityCalendarDays,\n activityDay,\n type PlannedActivityPageView,\n planActivityAppend,\n validateActivityAppend,\n} from \"./policy\"\nimport type {\n ActivityActor,\n ActivityAttribution,\n ActivityCalendarInput,\n ActivityCursor,\n ActivityDay,\n ActivityInteraction,\n ActivityPageView,\n ActivityPeriodInput,\n ActivitySessionVisits,\n ActivityStorage,\n ActivitySummary,\n ActivityUsersPage,\n ActivityVisit,\n ActivityVisitsPage,\n AppendActivityInput,\n AppendActivityResult,\n ListActivitySessionVisitsInput,\n ListActivityUsersInput,\n ListActivityVisitsInput,\n ReadActivityVisitInput,\n StoredActivityVisitPage,\n} from \"./types\"\n\ninterface StoredVisit {\n readonly projectId: string\n readonly id: string\n readonly actor: ActivityActor\n readonly sessionId: string\n readonly attribution: ActivityAttribution | null\n readonly startedAt: Date\n lastSeenAt: Date\n pageViews: number\n interactions: number\n}\n\ninterface StoredPageView extends PlannedActivityPageView {\n readonly projectId: string\n}\n\ninterface StoredInteraction extends ActivityInteraction {\n readonly projectId: string\n}\n\n/** A source as stored: the start of its visit is read from the visit, which may be gone. */\ntype StoredSource = Omit<ActivitySourceState, \"visitStartedAt\">\n\ninterface InMemoryActivitySnapshot {\n readonly sources: Map<string, StoredSource>\n readonly visits: Map<string, StoredVisit>\n readonly pageViews: StoredPageView[]\n readonly interactions: StoredInteraction[]\n}\n\n/** Activity for tests and local development. Each append runs without yielding, so it is atomic. */\nexport class InMemoryActivityStorage implements ActivityStorage {\n private sources = new Map<string, StoredSource>()\n private visits = new Map<string, StoredVisit>()\n private pageViews: StoredPageView[] = []\n private interactions: StoredInteraction[] = []\n\n async append(input: AppendActivityInput): Promise<AppendActivityResult> {\n validateActivityAppend(input)\n\n const sourceKey = JSON.stringify([input.projectId, input.actor.type, input.sessionId])\n const stored = [...this.pageViews, ...this.interactions].filter(\n (event) =>\n event.projectId === input.projectId &&\n this.isFromSession(event, input) &&\n input.events.some((candidate) => candidate.id === event.id)\n )\n\n const plan = planActivityAppend(input, this.source(sourceKey, input.projectId), stored)\n if (plan.status !== \"append\") {\n return { status: plan.status === \"duplicate\" ? \"accepted\" : \"throttled\", accepted: 0 }\n }\n\n const visitKey = JSON.stringify([input.projectId, plan.state.visitId])\n const lastSeenAt = new Date(plan.state.lastSeenAt)\n\n if (plan.newVisit) {\n if (this.visits.has(visitKey)) {\n throw new Error(\"[Sixb] Activity visit id already exists.\")\n }\n\n this.visits.set(visitKey, {\n projectId: input.projectId,\n id: plan.state.visitId,\n actor: structuredClone(input.actor),\n sessionId: input.sessionId,\n attribution: plan.newVisit.attribution,\n startedAt: lastSeenAt,\n lastSeenAt,\n pageViews: plan.pageViews.length,\n interactions: plan.interactions.length,\n })\n } else {\n const visit = this.requireVisit(input.projectId, plan.state.visitId)\n visit.lastSeenAt = lastSeenAt\n visit.pageViews += plan.pageViews.length\n visit.interactions += plan.interactions.length\n }\n\n const { visitStartedAt: _startedAt, ...source } = plan.state\n this.sources.set(sourceKey, source)\n for (const pageView of plan.pageViews) {\n this.pageViews.push({ ...pageView, projectId: input.projectId })\n }\n for (const interaction of plan.interactions) {\n this.interactions.push({ ...interaction, projectId: input.projectId })\n }\n\n return { status: \"accepted\", accepted: plan.accepted }\n }\n\n async list(input: ListActivityVisitsInput): Promise<ActivityVisitsPage> {\n const visits = this.overlapping(input)\n .filter((visit) => isBefore(visit.lastSeenAt, visit.id, input.before))\n .sort(byLastSeenDescending((visit) => visit.id))\n\n return {\n visits: visits.slice(0, input.limit).map(toVisit),\n hasMore: visits.length > input.limit,\n }\n }\n\n async users(input: ListActivityUsersInput): Promise<ActivityUsersPage> {\n const byUser = new Map<string, { lastSeenAt: Date; visits: number; pageViews: number }>()\n\n for (const visit of this.overlapping(input)) {\n if (visit.actor.type !== \"user\") {\n continue\n }\n\n const user = byUser.get(visit.actor.userId) ?? {\n lastSeenAt: visit.lastSeenAt,\n visits: 0,\n pageViews: 0,\n }\n if (visit.lastSeenAt > user.lastSeenAt) {\n user.lastSeenAt = visit.lastSeenAt\n }\n user.visits += 1\n user.pageViews += this.pageViewsInPeriod(visit, input).length\n byUser.set(visit.actor.userId, user)\n }\n\n const users = [...byUser]\n .map(([userId, user]) => ({ userId, ...user }))\n .filter((user) => isBefore(user.lastSeenAt, user.userId, input.before))\n .sort(byLastSeenDescending((user) => user.userId))\n\n return {\n users: users.slice(0, input.limit).map((user) => ({ ...user })),\n hasMore: users.length > input.limit,\n }\n }\n\n async summarize(input: ActivityPeriodInput): Promise<ActivitySummary> {\n const visits = this.overlapping(input)\n const userIds = visits.flatMap((visit) =>\n visit.actor.type === \"user\" ? [visit.actor.userId] : []\n )\n\n return {\n users: new Set(userIds).size,\n visits: visits.length,\n sharedVisits: visits.filter((visit) => visit.actor.type === \"share\").length,\n pageViews: visits.reduce(\n (total, visit) => total + this.pageViewsInPeriod(visit, input).length,\n 0\n ),\n }\n }\n\n async calendar(input: ActivityCalendarInput): Promise<readonly ActivityDay[]> {\n const visits = this.overlapping(input)\n\n const pageViewsByDay = new Map<string, number>()\n for (const visit of visits) {\n for (const pageView of this.pageViewsInPeriod(visit, input)) {\n const day = activityDay(pageView.receivedAt)\n pageViewsByDay.set(day, (pageViewsByDay.get(day) ?? 0) + 1)\n }\n }\n\n return activityCalendarDays(input, visits, pageViewsByDay)\n }\n\n async read(input: ReadActivityVisitInput): Promise<StoredActivityVisitPage | null> {\n const visit = this.visits.get(JSON.stringify([input.projectId, input.id]))\n if (!visit) {\n return null\n }\n\n const ofVisit = (event: StoredPageView | StoredInteraction) =>\n event.projectId === visit.projectId && event.visitId === visit.id\n\n const events = [...this.pageViews.filter(ofVisit), ...this.interactions.filter(ofVisit)].sort(\n (left, right) => left.sequence - right.sequence\n )\n\n const pageViews: ActivityPageView[] = []\n const interactions: ActivityInteraction[] = []\n for (const event of events.slice(0, input.limit)) {\n const { id, visitId, sequence, route } = event\n const pageView = { id, visitId, sequence, route, receivedAt: new Date(event.receivedAt) }\n\n if (\"name\" in event) {\n interactions.push({ ...pageView, name: event.name })\n } else {\n pageViews.push(pageView)\n }\n }\n\n return {\n visit: toVisit(visit),\n sessionId: visit.sessionId,\n pageViews,\n interactions,\n hasMore: events.length > input.limit,\n }\n }\n\n async sessionVisits(\n input: ListActivitySessionVisitsInput\n ): Promise<readonly ActivitySessionVisits[]> {\n const sessionIds = new Set(input.sessionIds)\n const bySession = new Map<string, StoredVisit[]>()\n\n for (const visit of this.visits.values()) {\n if (\n visit.projectId !== input.projectId ||\n visit.actor.type !== \"user\" ||\n visit.actor.userId !== input.userId ||\n !sessionIds.has(visit.sessionId)\n ) {\n continue\n }\n\n const visits = bySession.get(visit.sessionId) ?? []\n visits.push(visit)\n bySession.set(visit.sessionId, visits)\n }\n\n return [...bySession].map(([sessionId, visits]) => ({\n sessionId,\n visits: visits.length,\n latest: visits.sort(byStartDescending).slice(0, input.limit).map(toVisit),\n }))\n }\n\n snapshot(): InMemoryActivitySnapshot {\n return structuredClone({\n sources: this.sources,\n visits: this.visits,\n pageViews: this.pageViews,\n interactions: this.interactions,\n })\n }\n\n restore(snapshot: InMemoryActivitySnapshot): void {\n const restored = structuredClone(snapshot)\n this.sources = restored.sources\n this.visits = restored.visits\n this.pageViews = restored.pageViews\n this.interactions = restored.interactions\n }\n\n private source(key: string, projectId: string): ActivitySourceState | undefined {\n const source = this.sources.get(key)\n if (!source) {\n return undefined\n }\n\n const visit = this.visits.get(JSON.stringify([projectId, source.visitId]))\n return { ...source, visitStartedAt: visit ? visit.startedAt.getTime() : null }\n }\n\n /**\n * Visits active at some point of `[from, to)`, optionally one account's. A visit lasts less than\n * a day, so one active in the period started at most a day before it.\n */\n private overlapping(input: ActivityPeriodInput): StoredVisit[] {\n const earliestStart = input.from.getTime() - ACTIVITY_MAX_VISIT_MS\n return [...this.visits.values()].filter(\n (visit) =>\n visit.projectId === input.projectId &&\n visit.startedAt.getTime() >= earliestStart &&\n visit.startedAt < input.to &&\n visit.lastSeenAt >= input.from &&\n (input.userId === undefined ||\n (visit.actor.type === \"user\" && visit.actor.userId === input.userId))\n )\n }\n\n private pageViewsOf(visit: StoredVisit): StoredPageView[] {\n return this.pageViews.filter(\n (pageView) => pageView.projectId === visit.projectId && pageView.visitId === visit.id\n )\n }\n\n private pageViewsInPeriod(\n visit: StoredVisit,\n period: ActivityPeriodInput | ActivityCalendarInput\n ) {\n return this.pageViewsOf(visit).filter(\n (pageView) => pageView.receivedAt >= period.from && pageView.receivedAt < period.to\n )\n }\n\n private isFromSession(\n event: StoredPageView | StoredInteraction,\n input: AppendActivityInput\n ): boolean {\n const visit = this.visits.get(JSON.stringify([event.projectId, event.visitId]))\n return visit?.actor.type === input.actor.type && visit.sessionId === input.sessionId\n }\n\n private requireVisit(projectId: string, id: string): StoredVisit {\n const visit = this.visits.get(JSON.stringify([projectId, id]))\n if (!visit) {\n throw new Error(\"[Sixb] Activity visit is missing.\")\n }\n return visit\n }\n}\n\nfunction toVisit(visit: StoredVisit): ActivityVisit {\n return {\n id: visit.id,\n actor: structuredClone(visit.actor),\n attribution: structuredClone(visit.attribution),\n startedAt: new Date(visit.startedAt),\n lastSeenAt: new Date(visit.lastSeenAt),\n pageViews: visit.pageViews,\n interactions: visit.interactions,\n }\n}\n\nfunction isBefore(at: Date, id: string, cursor: ActivityCursor | undefined): boolean {\n if (!cursor) {\n return true\n }\n return at < cursor.at || (at.getTime() === cursor.at.getTime() && id < cursor.id)\n}\n\nfunction byStartDescending(left: StoredVisit, right: StoredVisit): number {\n const byTime = right.startedAt.getTime() - left.startedAt.getTime()\n if (byTime !== 0) {\n return byTime\n }\n return left.id < right.id ? 1 : left.id > right.id ? -1 : 0\n}\n\n/** Newest first, then by descending id compared byte by byte, as the SQL providers sort. */\nfunction byLastSeenDescending<T extends { readonly lastSeenAt: Date }>(id: (row: T) => string) {\n return (left: T, right: T) => {\n const byTime = right.lastSeenAt.getTime() - left.lastSeenAt.getTime()\n if (byTime !== 0) {\n return byTime\n }\n return id(left) < id(right) ? 1 : id(left) > id(right) ? -1 : 0\n }\n}\n",
|
|
15
|
+
"import { type Principal, principalsEqual } from \"../../auth\"\nimport { paginate } from \"../pagination\"\nimport { artifactStateBytes, artifactStorageErrors, checkArtifactStateWrite } from \"./record\"\nimport type {\n ArtifactFrameGrantRecord,\n ArtifactRecord,\n ArtifactStateEntry,\n ArtifactStateKeyInput,\n ArtifactStateScope,\n ArtifactStorage,\n ArtifactVersionInput,\n ArtifactVersionRecord,\n CopyArtifactInput,\n CreateArtifactInput,\n DeleteArtifactInput,\n DeleteArtifactVersionsByOriginInput,\n DeleteExpiredArtifactFrameGrantsInput,\n FindArtifactFrameGrantInput,\n GetArtifactInput,\n GetArtifactVersionInput,\n ListArtifactsInput,\n ListArtifactsResult,\n ListArtifactVersionsInput,\n ListArtifactVersionsResult,\n ListReferencingVersionsInput,\n PublishArtifactVersionInput,\n PublishedArtifactVersion,\n SetArtifactStateInput,\n} from \"./types\"\n\ninterface StoredArtifact {\n readonly record: ArtifactRecord\n /** Oldest first. */\n readonly versions: readonly ArtifactVersionRecord[]\n /** The number the next version gets; it only grows, so a deleted number is never reused. */\n readonly nextVersion: number\n /** The threads it is shared in, by id. */\n readonly threads: ReadonlyMap<string, ThreadLink>\n}\n\ninterface ThreadLink {\n /** When it was first shared there. */\n readonly sharedAt: Date\n /** Copied for the thread: shared there whatever versions it keeps. */\n readonly copied: boolean\n}\n\ninterface InMemoryArtifactSnapshot {\n readonly artifacts: ReadonlyMap<string, StoredArtifact>\n readonly frameGrants: ReadonlyMap<string, ArtifactFrameGrantRecord>\n readonly state: ReadonlyMap<string, ReadonlyMap<string, ArtifactStateEntry>>\n}\n\nexport class InMemoryArtifactStorage implements ArtifactStorage {\n private artifacts = new Map<string, StoredArtifact>()\n private frameGrants = new Map<string, ArtifactFrameGrantRecord>()\n /** By artifact and reader, then by key. */\n private state = new Map<string, Map<string, ArtifactStateEntry>>()\n\n async create(input: CreateArtifactInput): Promise<PublishedArtifactVersion> {\n const key = artifactKey(input.projectId, input.id)\n if (this.artifacts.has(key)) throw artifactStorageErrors.exists(input.id)\n const version = versionRecord(input.projectId, input.id, 1, input.version)\n const record: ArtifactRecord = {\n projectId: input.projectId,\n id: input.id,\n kind: input.kind,\n title: version.title,\n owner: { ...input.owner },\n latestVersion: 1,\n createdAt: new Date(version.createdAt),\n updatedAt: new Date(version.createdAt),\n }\n this.artifacts.set(key, {\n record,\n versions: [version],\n nextVersion: 2,\n threads: sharedIn(new Map(), version),\n })\n return published(record, version)\n }\n\n async publish(input: PublishArtifactVersionInput): Promise<PublishedArtifactVersion> {\n const key = artifactKey(input.projectId, input.artifactId)\n const stored = this.artifacts.get(key)\n if (!stored) throw artifactStorageErrors.notFound(input.artifactId)\n if (stored.record.kind !== input.kind) {\n throw artifactStorageErrors.kindMismatch(input.artifactId, stored.record.kind, input.kind)\n }\n const latest = stored.versions.find(\n (candidate) => candidate.version === stored.record.latestVersion\n )\n if (input.baseVersion !== undefined && latest && latest.version !== input.baseVersion) {\n throw artifactStorageErrors.moved(input.artifactId, input.baseVersion, {\n version: latest.version,\n author: structuredClone(latest.author),\n })\n }\n const version = versionRecord(\n input.projectId,\n input.artifactId,\n stored.nextVersion,\n input.version\n )\n const record: ArtifactRecord = {\n ...stored.record,\n title: version.title,\n latestVersion: version.version,\n updatedAt: new Date(version.createdAt),\n }\n this.artifacts.set(key, {\n record,\n versions: [...stored.versions, version],\n nextVersion: stored.nextVersion + 1,\n threads: sharedIn(stored.threads, version),\n })\n return published(record, version)\n }\n\n async get(input: GetArtifactInput): Promise<ArtifactRecord | null> {\n const stored = this.artifacts.get(artifactKey(input.projectId, input.id))\n return stored ? structuredClone(stored.record) : null\n }\n\n async list(input: ListArtifactsInput): Promise<ListArtifactsResult> {\n const matching = [...this.artifacts.values()]\n .filter(\n ({ record, threads }) =>\n record.projectId === input.projectId &&\n (!input.owner || principalsEqual(record.owner, input.owner)) &&\n (input.kind === undefined || record.kind === input.kind) &&\n (input.threadId === undefined || threads.has(input.threadId))\n )\n .map(({ record }) => record)\n .sort(\n (left, right) =>\n right.updatedAt.getTime() - left.updatedAt.getTime() || left.id.localeCompare(right.id)\n )\n const { page, hasMore, total } = paginate(matching, input)\n return { artifacts: structuredClone(page), hasMore, total }\n }\n\n async getVersion(input: GetArtifactVersionInput): Promise<ArtifactVersionRecord | null> {\n const stored = this.artifacts.get(artifactKey(input.projectId, input.artifactId))\n const version = stored?.versions.find((candidate) => candidate.version === input.version)\n return version ? structuredClone(version) : null\n }\n\n async listVersions(input: ListArtifactVersionsInput): Promise<ListArtifactVersionsResult> {\n const stored = this.artifacts.get(artifactKey(input.projectId, input.artifactId))\n const newestFirst = [...(stored?.versions ?? [])].reverse()\n const { page, hasMore, total } = paginate(newestFirst, input)\n return { versions: structuredClone(page), hasMore, total }\n }\n\n async listThreadIds(input: GetArtifactInput): Promise<string[]> {\n const stored = this.artifacts.get(artifactKey(input.projectId, input.id))\n // Code-unit order, as SQLite compares text.\n return [...(stored?.threads.keys() ?? [])].sort((left, right) => (left < right ? -1 : 1))\n }\n\n async copy(input: CopyArtifactInput): Promise<ArtifactRecord> {\n const source = this.artifacts.get(artifactKey(input.projectId, input.sourceId))\n if (!source) throw artifactStorageErrors.notFound(input.sourceId)\n\n const key = artifactKey(input.projectId, input.id)\n if (this.artifacts.has(key)) throw artifactStorageErrors.exists(input.id)\n\n const record: ArtifactRecord = { ...source.record, id: input.id, owner: { ...input.owner } }\n const versions = source.versions.map(({ origin: _origin, ...version }) =>\n structuredClone({ ...version, artifactId: input.id })\n )\n const sharedAt = new Date(input.copiedAt ?? new Date())\n this.artifacts.set(key, {\n record,\n versions,\n nextVersion: source.nextVersion,\n threads: new Map([[input.threadId, { sharedAt, copied: true }]]),\n })\n return structuredClone(record)\n }\n\n async listReferencingVersions(\n input: ListReferencingVersionsInput\n ): Promise<ArtifactVersionRecord[]> {\n const prefix = `artifact:${input.artifactId}`\n const referencing: ArtifactVersionRecord[] = []\n for (const stored of this.artifacts.values()) {\n if (stored.record.projectId !== input.projectId) continue\n const latest = stored.versions.find(\n (candidate) => candidate.version === stored.record.latestVersion\n )\n if (latest?.references.some((reference) => refersTo(reference.address, prefix))) {\n referencing.push(structuredClone(latest))\n }\n }\n // Code-unit order, as SQLite compares text.\n return referencing.sort((left, right) => (left.artifactId < right.artifactId ? -1 : 1))\n }\n\n async createFrameGrant(record: ArtifactFrameGrantRecord): Promise<void> {\n if (!this.artifacts.has(artifactKey(record.projectId, record.artifactId))) {\n throw artifactStorageErrors.notFound(record.artifactId)\n }\n this.frameGrants.set(artifactKey(record.projectId, record.tokenHash), structuredClone(record))\n }\n\n async findFrameGrant(\n input: FindArtifactFrameGrantInput\n ): Promise<ArtifactFrameGrantRecord | null> {\n const grant = this.frameGrants.get(artifactKey(input.projectId, input.tokenHash))\n return grant ? structuredClone(grant) : null\n }\n\n async deleteExpiredFrameGrants(input: DeleteExpiredArtifactFrameGrantsInput): Promise<number> {\n let deleted = 0\n for (const [key, grant] of this.frameGrants) {\n if (deleted >= input.limit) break\n if (grant.projectId !== input.projectId || grant.expiresAt >= input.expiredBefore) continue\n this.frameGrants.delete(key)\n deleted += 1\n }\n return deleted\n }\n\n async getState(input: ArtifactStateKeyInput): Promise<ArtifactStateEntry | null> {\n const entry = this.state.get(stateKey(input))?.get(input.key)\n return entry ? structuredClone(entry) : null\n }\n\n async setState(input: SetArtifactStateInput): Promise<void> {\n if (!this.artifacts.has(artifactKey(input.projectId, input.artifactId))) {\n throw artifactStorageErrors.notFound(input.artifactId)\n }\n const kept = this.state.get(stateKey(input)) ?? new Map<string, ArtifactStateEntry>()\n const others = [...kept.values()].filter((entry) => entry.key !== input.key)\n const sizeBytes = artifactStateBytes(input.value)\n checkArtifactStateWrite({\n key: input.key,\n valueBytes: sizeBytes,\n others: {\n keys: others.length,\n bytes: others.reduce((total, entry) => total + entry.sizeBytes, 0),\n },\n })\n kept.set(input.key, {\n key: input.key,\n value: input.value,\n sizeBytes,\n updatedAt: new Date(input.updatedAt),\n })\n this.state.set(stateKey(input), kept)\n }\n\n async deleteState(input: ArtifactStateKeyInput): Promise<boolean> {\n return this.state.get(stateKey(input))?.delete(input.key) ?? false\n }\n\n async listState(input: ArtifactStateScope): Promise<ArtifactStateEntry[]> {\n const kept = [...(this.state.get(stateKey(input))?.values() ?? [])]\n // Code-unit order, as SQLite compares text.\n return structuredClone(kept.sort((left, right) => (left.key < right.key ? -1 : 1)))\n }\n\n async clearState(input: ArtifactStateScope): Promise<number> {\n const count = this.state.get(stateKey(input))?.size ?? 0\n this.state.delete(stateKey(input))\n return count\n }\n\n async delete(input: DeleteArtifactInput): Promise<boolean> {\n return this.deleteArtifact(artifactKey(input.projectId, input.id))\n }\n\n async deleteVersionsByOrigin(input: DeleteArtifactVersionsByOriginInput): Promise<number> {\n let deleted = 0\n for (const [key, stored] of this.artifacts) {\n if (stored.record.projectId !== input.projectId) continue\n const remaining = stored.versions.filter((version) => version.origin?.runId !== input.runId)\n if (remaining.length === stored.versions.length) continue\n deleted += stored.versions.length - remaining.length\n const latest = remaining.at(-1)\n if (!latest) {\n this.deleteArtifact(key)\n continue\n }\n\n // A run publishes from one thread: the link stays only if a version from it remains.\n const threadId = stored.versions.find((version) => version.origin?.runId === input.runId)\n ?.origin?.threadId\n const threads = new Map(stored.threads)\n if (\n threadId &&\n !threads.get(threadId)?.copied &&\n !remaining.some((version) => version.origin?.threadId === threadId)\n ) {\n threads.delete(threadId)\n }\n\n this.artifacts.set(key, {\n ...stored,\n record: {\n ...stored.record,\n title: latest.title,\n latestVersion: latest.version,\n updatedAt: new Date(latest.createdAt),\n },\n versions: remaining,\n threads,\n })\n }\n return deleted\n }\n\n snapshot(): InMemoryArtifactSnapshot {\n return structuredClone({\n artifacts: this.artifacts,\n frameGrants: this.frameGrants,\n state: this.state,\n })\n }\n\n restore(snapshot: InMemoryArtifactSnapshot): void {\n const restored = structuredClone(snapshot)\n this.artifacts = new Map(restored.artifacts)\n this.frameGrants = new Map(restored.frameGrants)\n this.state = new Map([...restored.state].map(([key, kept]) => [key, new Map(kept)]))\n }\n\n /**\n * Deletes an artifact with its frame grants and what it keeps for its readers, as the SQL\n * providers' cascade does.\n */\n private deleteArtifact(key: string): boolean {\n for (const [grantKey, grant] of this.frameGrants) {\n if (artifactKey(grant.projectId, grant.artifactId) === key) this.frameGrants.delete(grantKey)\n }\n for (const kept of this.state.keys()) {\n if (kept.startsWith(`${key}\\0`)) this.state.delete(kept)\n }\n return this.artifacts.delete(key)\n }\n}\n\nfunction versionRecord(\n projectId: string,\n artifactId: string,\n version: number,\n input: ArtifactVersionInput\n): ArtifactVersionRecord {\n return structuredClone({ ...input, projectId, artifactId, version })\n}\n\n/** The links an artifact has once this version is stored: its origin's thread among them. */\nfunction sharedIn(\n threads: ReadonlyMap<string, ThreadLink>,\n version: ArtifactVersionRecord\n): ReadonlyMap<string, ThreadLink> {\n const threadId = version.origin?.threadId\n if (!threadId || threads.has(threadId)) return threads\n\n return new Map(threads).set(threadId, { sharedAt: new Date(version.createdAt), copied: false })\n}\n\nfunction published(\n record: ArtifactRecord,\n version: ArtifactVersionRecord\n): PublishedArtifactVersion {\n return structuredClone({ artifact: record, version })\n}\n\nfunction artifactKey(projectId: string, id: string): string {\n return `${projectId}\\0${id}`\n}\n\n/** An artifact's key, then its reader's. */\nfunction stateKey(scope: {\n readonly projectId: string\n readonly artifactId: string\n readonly principal: Principal\n}): string {\n return `${artifactKey(scope.projectId, scope.artifactId)}\\0${scope.principal.type}\\0${scope.principal.id}`\n}\n\n/** Whether an address names the artifact `artifact:<id>` is, at any version, file, or part. */\nfunction refersTo(address: string, prefix: string): boolean {\n return address.startsWith(prefix) && /^(?:$|[@/#])/.test(address.slice(prefix.length))\n}\n",
|
|
16
|
+
"import type { AuthStorage } from \"../auth\"\nimport type { ShareSessionStorage } from \"../share-sessions\"\nimport { ExecutionStorageError } from \"./errors\"\nimport { compareExecutionCreation } from \"./provider\"\nimport type {\n CreateExecutionInput,\n ExecutionDescendant,\n ExecutionRecord,\n ExecutionStorage,\n ListExecutionDescendantsInput,\n ListSessionExecutionsInput,\n SessionExecutions,\n} from \"./types\"\nimport { cloneExecutionRecord, prepareExecutionRecord } from \"./validation\"\n\ntype RunRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\n\nconst runDirectly: RunRootOperation = async <T>(run: () => Promise<T> | T): Promise<T> => run()\n\nfunction executionKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nexport class InMemoryExecutionStorage implements ExecutionStorage {\n private readonly rows = new Map<string, ExecutionRecord>()\n private readonly runRootOperation: RunRootOperation\n private readonly shareSessions?: Pick<ShareSessionStorage, \"getById\">\n\n constructor(\n private readonly auth: AuthStorage,\n input: {\n readonly runRootOperation?: RunRootOperation\n readonly shareSessions?: Pick<ShareSessionStorage, \"getById\">\n } = {}\n ) {\n this.runRootOperation = input.runRootOperation ?? runDirectly\n this.shareSessions = input.shareSessions\n }\n\n snapshot(): InMemoryExecutionStorageSnapshot {\n return structuredClone(this.rows)\n }\n\n restore(snapshot: InMemoryExecutionStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.rows.set(key, record)\n }\n }\n\n async create(input: CreateExecutionInput): Promise<ExecutionRecord> {\n return this.runRootOperation(async () => {\n const key = executionKey(input.projectId, input.id)\n if (this.rows.has(key)) {\n throw new ExecutionStorageError(\n \"duplicate_execution\",\n `[Sixb] Execution '${input.id}' already exists in project '${input.projectId}'.`\n )\n }\n\n const record = await prepareExecutionRecord(input, {\n auth: this.auth,\n getExecution: async ({ projectId, id }) => {\n const existing = this.rows.get(executionKey(projectId, id))\n return existing ? cloneExecutionRecord(existing) : null\n },\n getShareSession: async ({ projectId, id }) =>\n (await this.shareSessions?.getById({ projectId, id })) ?? null,\n })\n\n this.rows.set(key, cloneExecutionRecord(record))\n return cloneExecutionRecord(record)\n })\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<ExecutionRecord | null> {\n return this.runRootOperation(() => {\n const record = this.rows.get(executionKey(params.projectId, params.id))\n return record ? cloneExecutionRecord(record) : null\n })\n }\n\n async listBySession(input: ListSessionExecutionsInput): Promise<SessionExecutions> {\n return this.runRootOperation(() => {\n const rows = [...this.rows.values()].filter((row) => row.projectId === input.projectId)\n\n const roots = rows\n .filter(\n (row) =>\n row.source.type !== \"execution\" &&\n row.createdAt >= input.from &&\n row.createdAt < input.to &&\n isFromSession(row, input.session)\n )\n .sort(compareExecutionCreation)\n .slice(0, input.limit + 1)\n\n // Level by level, as the SQL providers walk the tree, so truncation keeps roots first.\n const found = [...roots]\n let level = roots\n while (level.length > 0 && found.length <= input.limit) {\n const parents = new Set(level.map((row) => row.id))\n level = rows\n .filter((row) => row.source.type === \"execution\" && parents.has(row.source.executionId))\n .sort(compareExecutionCreation)\n found.push(...level)\n }\n\n return {\n executions: found\n .slice(0, input.limit)\n .sort(compareExecutionCreation)\n .map(cloneExecutionRecord),\n truncated: found.length > input.limit,\n }\n })\n }\n\n async listDescendants(\n input: ListExecutionDescendantsInput\n ): Promise<readonly ExecutionDescendant[]> {\n return this.runRootOperation(() => {\n const rows = [...this.rows.values()].filter((row) => row.projectId === input.projectId)\n const seen = new Set(input.executionIds)\n const found: ExecutionRecord[] = []\n\n let parents = new Set(input.executionIds)\n while (parents.size > 0) {\n const level = rows.filter(\n (row) =>\n row.source.type === \"execution\" &&\n parents.has(row.source.executionId) &&\n !seen.has(row.id)\n )\n\n for (const row of level) seen.add(row.id)\n found.push(...level)\n parents = new Set(level.map((row) => row.id))\n }\n\n return found\n .flatMap((row) =>\n row.source.type === \"execution\" ? [{ id: row.id, parentId: row.source.executionId }] : []\n )\n .sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))\n })\n }\n}\n\nfunction isFromSession(\n row: ExecutionRecord,\n session: ListSessionExecutionsInput[\"session\"]\n): boolean {\n const ref = row.authorizationRef\n\n if (session.type === \"user\") {\n return (\n ref.type === \"principal\" &&\n ref.credential?.type === \"session\" &&\n ref.credential.id === session.id\n )\n }\n\n return ref.type === \"delegated\" && ref.delegation.sessionId === session.id\n}\n\nexport type InMemoryExecutionStorageSnapshot = Map<string, ExecutionRecord>\n",
|
|
17
|
+
"import { cloneFileDownloadGrantRecord } from \"./record\"\nimport type {\n DeleteExpiredFileDownloadGrantsInput,\n FileDownloadGrantRecord,\n FileDownloadGrantStorage,\n FindFileDownloadGrantInput,\n RevokeFileDownloadGrantInput,\n} from \"./types\"\n\nexport class InMemoryFileDownloadGrantStorage implements FileDownloadGrantStorage {\n private rows = new Map<string, FileDownloadGrantRecord>()\n\n async create(record: FileDownloadGrantRecord): Promise<void> {\n const duplicate = [...this.rows.values()].some(\n (current) =>\n current.projectId === record.projectId &&\n (current.id === record.id || current.tokenHash === record.tokenHash)\n )\n if (duplicate) {\n throw new Error(`[Sixb] File download grant '${record.id}' conflicts with an existing one.`)\n }\n this.rows.set(rowKey(record.projectId, record.id), cloneFileDownloadGrantRecord(record))\n }\n\n async findByTokenHash(\n input: FindFileDownloadGrantInput\n ): Promise<FileDownloadGrantRecord | null> {\n for (const record of this.rows.values()) {\n if (record.projectId === input.projectId && record.tokenHash === input.tokenHash) {\n return cloneFileDownloadGrantRecord(record)\n }\n }\n return null\n }\n\n async revoke(input: RevokeFileDownloadGrantInput): Promise<FileDownloadGrantRecord | null> {\n const key = rowKey(input.projectId, input.id)\n const current = this.rows.get(key)\n if (!current) return null\n if (!current.revokedAt) {\n this.rows.set(key, { ...current, revokedAt: new Date(input.revokedAt) })\n }\n return cloneFileDownloadGrantRecord(this.rows.get(key) as FileDownloadGrantRecord)\n }\n\n async deleteExpired(input: DeleteExpiredFileDownloadGrantsInput): Promise<number> {\n const expired = [...this.rows.entries()]\n .filter(\n ([, record]) =>\n record.projectId === input.projectId &&\n record.expiresAt.getTime() < input.expiredBefore.getTime()\n )\n .slice(0, input.limit)\n for (const [key] of expired) this.rows.delete(key)\n return expired.length\n }\n\n snapshot(): ReadonlyMap<string, FileDownloadGrantRecord> {\n return new Map(\n [...this.rows].map(([key, record]) => [key, cloneFileDownloadGrantRecord(record)])\n )\n }\n\n restore(snapshot: ReadonlyMap<string, FileDownloadGrantRecord>): void {\n this.rows = new Map(\n [...snapshot].map(([key, record]) => [key, cloneFileDownloadGrantRecord(record)])\n )\n }\n}\n\nfunction rowKey(projectId: string, id: string): string {\n return `${projectId}\\0${id}`\n}\n",
|
|
18
|
+
"import type { ObjectLinkCursor, ObjectLinkRow } from \"./types\"\n\nexport type ObjectBatchKey = string & {\n readonly __sixbObjectBatchKey: true\n}\n\nexport type LinkBatchKey = string & {\n readonly __sixbLinkBatchKey: true\n}\n\n/** Collision-safe key for object batch-read results. */\nexport function objectBatchKey(objectTypeId: string, primaryId: string): ObjectBatchKey {\n return JSON.stringify([objectTypeId, primaryId]) as ObjectBatchKey\n}\n\n/** Collision-safe key for directional link batch-read results, keyed by the requested object. */\nexport function linkBatchKey(objectTypeId: string, objectId: string, linkId: string): LinkBatchKey {\n return JSON.stringify([objectTypeId, objectId, linkId]) as LinkBatchKey\n}\n\n/** Canonical storage ordering and cursor for physical links. */\nexport function objectLinkCursor(link: ObjectLinkRow): ObjectLinkCursor {\n return [link.sourceTypeId, link.sourceId, link.linkId, link.targetTypeId, link.targetId]\n}\n\nexport function compareObjectLinkCursors(left: ObjectLinkCursor, right: ObjectLinkCursor): number {\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] < right[index]) return -1\n if (left[index] > right[index]) return 1\n }\n return 0\n}\n\nexport function compareObjectLinks(left: ObjectLinkRow, right: ObjectLinkRow): number {\n return compareObjectLinkCursors(objectLinkCursor(left), objectLinkCursor(right))\n}\n",
|
|
19
|
+
"import { compareDecimalValues } from \"../../ontology\"\nimport type { QueryScalarKind } from \"./ir\"\n\n/** Compare two values according to the scalar schema resolved by query validation. */\nexport function compareQueryScalarValues(\n left: unknown,\n right: unknown,\n scalarKind?: QueryScalarKind\n): number {\n if (left === undefined || right === undefined || left === null || right === null) {\n return Number.NaN\n }\n\n if (scalarKind === undefined) return compareRuntimeValues(left, right)\n\n switch (scalarKind) {\n case \"string\":\n case \"uuid\":\n return typeof left === \"string\" && typeof right === \"string\"\n ? compareStrings(left, right)\n : Number.NaN\n case \"boolean\":\n return typeof left === \"boolean\" && typeof right === \"boolean\"\n ? Number(left) - Number(right)\n : Number.NaN\n case \"integer\":\n case \"double\":\n return typeof left === \"number\" && typeof right === \"number\" ? left - right : Number.NaN\n case \"decimal\":\n return typeof left === \"string\" && typeof right === \"string\"\n ? compareDecimalValues(left, right)\n : Number.NaN\n case \"date\":\n case \"timestamp\":\n return compareTemporalValues(left, right)\n case \"userRef\":\n // Identity only: user references have no order.\n return Number.NaN\n }\n}\n\n/** Test equality with the same schema semantics used for ordered comparisons. */\nexport function queryScalarValuesEqual(\n left: unknown,\n right: unknown,\n scalarKind?: QueryScalarKind\n): boolean {\n if (scalarKind === \"decimal\") {\n const comparison = compareQueryScalarValues(left, right, scalarKind)\n return !Number.isNaN(comparison) && comparison === 0\n }\n\n if (scalarKind === \"date\" || scalarKind === \"timestamp\") {\n const comparison = compareTemporalValues(left, right)\n return !Number.isNaN(comparison) && comparison === 0\n }\n\n if (scalarKind === \"userRef\") return userRefsEqual(left, right)\n if (scalarKind !== undefined) return Object.is(left, right)\n return runtimeValuesEqual(left, right)\n}\n\nfunction userRefsEqual(left: unknown, right: unknown): boolean {\n if (left === null || right === null) return left === right\n return (\n isRecord(left) &&\n isRecord(right) &&\n left.type === right.type &&\n typeof left.id === \"string\" &&\n left.id === right.id\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction compareRuntimeValues(left: unknown, right: unknown): number {\n if (typeof left === \"number\" && typeof right === \"number\") return left - right\n if (typeof left === \"string\" && typeof right === \"string\") return compareStrings(left, right)\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return Number(left) - Number(right)\n }\n if (left instanceof Date || right instanceof Date) return compareTemporalValues(left, right)\n return Number.NaN\n}\n\nfunction runtimeValuesEqual(left: unknown, right: unknown): boolean {\n if (left instanceof Date || right instanceof Date) {\n const comparison = compareTemporalValues(left, right)\n return !Number.isNaN(comparison) && comparison === 0\n }\n return Object.is(left, right)\n}\n\nfunction compareTemporalValues(left: unknown, right: unknown): number {\n const leftTime = dateTime(left)\n const rightTime = dateTime(right)\n if (leftTime === null || rightTime === null) return Number.NaN\n return leftTime - rightTime\n}\n\nfunction dateTime(value: unknown): number | null {\n if (value instanceof Date) {\n const time = value.getTime()\n return Number.isNaN(time) ? null : time\n }\n if (typeof value === \"string\" || typeof value === \"number\") {\n const time = new Date(value).getTime()\n return Number.isNaN(time) ? null : time\n }\n return null\n}\n\n/**\n * Code-point order, as SQLite's BINARY and PostgreSQL's \"C\" collation compare UTF-8 bytes.\n * JavaScript's `<` compares UTF-16 code units, which puts a surrogate pair (U+10000 and above)\n * before U+E000–U+FFFF; only that range needs its units remapped.\n */\nfunction compareStrings(left: string, right: string): number {\n if (left === right) return 0\n\n const length = Math.min(left.length, right.length)\n let index = 0\n while (index < length && left.charCodeAt(index) === right.charCodeAt(index)) index++\n if (index === length) return left.length - right.length\n\n return codePointRank(left.charCodeAt(index)) - codePointRank(right.charCodeAt(index))\n}\n\nfunction codePointRank(unit: number): number {\n if (unit >= 0xe000) return unit - 0x800\n if (unit >= 0xd800) return unit + 0x2000\n return unit\n}\n",
|
|
20
|
+
"import type { ObjectRow } from \"../../storage\"\nimport type { ObjectQueryPredicate, QueryScalarKind } from \"./ir\"\nimport { compareQueryScalarValues, queryScalarValuesEqual } from \"./scalar-values\"\n\n/**\n * Whether an object's properties match a validated predicate, with the semantics every object\n * storage implements: the in-memory store and the query executor's fallback evaluate it here, and\n * so does anything that decides on an object's state without reading it.\n */\nexport function matchesPredicate(\n row: Pick<ObjectRow, \"properties\">,\n predicate: ObjectQueryPredicate\n): boolean {\n switch (predicate.op) {\n case \"and\":\n return predicate.items.every((item) => matchesPredicate(row, item))\n case \"or\":\n return predicate.items.some((item) => matchesPredicate(row, item))\n case \"not\":\n return !matchesPredicate(row, predicate.item)\n case \"constant\":\n return predicate.value\n case \"eq\":\n return queryScalarValuesEqual(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n )\n case \"neq\":\n return !queryScalarValuesEqual(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n )\n case \"lt\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) < 0\n )\n case \"lte\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) <= 0\n )\n case \"gt\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) > 0\n )\n case \"gte\":\n return (\n compareQueryScalarValues(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n ) >= 0\n )\n case \"in\":\n return predicate.values.some((value) =>\n queryScalarValuesEqual(row.properties[predicate.propertyId], value, predicate.scalarKind)\n )\n case \"exists\": {\n const exists =\n Object.hasOwn(row.properties, predicate.propertyId) &&\n row.properties[predicate.propertyId] !== undefined\n return predicate.value ? exists : !exists\n }\n case \"contains\":\n return containsValue(\n row.properties[predicate.propertyId],\n predicate.value,\n predicate.scalarKind\n )\n }\n}\n\nfunction containsValue(\n actual: unknown,\n expected: unknown,\n itemScalarKind: QueryScalarKind | undefined\n): boolean {\n if (typeof actual === \"string\" && typeof expected === \"string\") {\n return actual.includes(expected)\n }\n\n if (Array.isArray(actual)) {\n return actual.some((item) => queryScalarValuesEqual(item, expected, itemScalarKind))\n }\n\n if (isPlainObject(actual) && typeof expected === \"string\") {\n return Object.hasOwn(actual, expected)\n }\n\n return false\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
|
|
21
|
+
"import { objectBatchKey } from \"../keys\"\nimport type { ObjectLinkRow, ObjectRow } from \"../types\"\n\nexport function objectRowKey(projectId: string, objectTypeId: string): string {\n return JSON.stringify([projectId, objectTypeId])\n}\n\nexport function objectRowProjectPrefix(projectId: string): string {\n return `[${JSON.stringify(projectId)},`\n}\n\nexport function compareStrings(left: string, right: string): number {\n if (left < right) return -1\n if (left > right) return 1\n return 0\n}\n\nexport function sourceLinkBucketKey(\n projectId: string,\n sourceTypeId: string,\n sourceId: string\n): string {\n return JSON.stringify([projectId, sourceTypeId, sourceId])\n}\n\nexport function linkRowKey(linkId: string, targetTypeId: string, targetId: string): string {\n return JSON.stringify([linkId, targetTypeId, targetId])\n}\n\nexport function fullLinkRowKey(row: ObjectLinkRow): string {\n return JSON.stringify([\n row.sourceTypeId,\n row.sourceId,\n row.linkId,\n row.targetTypeId,\n row.targetId,\n ])\n}\n\nexport function rowIdentityKey(row: ObjectRow): string {\n return rowIdentityKeyParts(row.objectTypeId, row.primaryId)\n}\n\nexport function rowIdentityKeyParts(objectTypeId: string, primaryId: string): string {\n return objectBatchKey(objectTypeId, primaryId)\n}\n",
|
|
22
|
+
"import type { ObjectQuery, ObjectQuerySortField } from \"../../../objects/query\"\nimport { matchesPredicate } from \"../../../objects/query/matches-predicate\"\nimport { compareQueryScalarValues } from \"../../../objects/query/scalar-values\"\nimport { vectorSources } from \"../../../objects/vectors/profile\"\nimport type { LinkBatchKey } from \"../keys\"\nimport {\n compareObjectLinkCursors,\n compareObjectLinks,\n linkBatchKey,\n objectLinkCursor,\n} from \"../keys\"\nimport type {\n ObjectFacetRequest,\n ObjectFacetResult,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n} from \"../types\"\nimport { compareStrings, fullLinkRowKey, rowIdentityKey, rowIdentityKeyParts } from \"./keys\"\nimport type { InMemoryReadSource } from \"./read-source\"\n\nexport const IN_MEMORY_OBJECT_QUERY_CAPABILITIES: ObjectQueryCapabilities = {\n queryObjects: true,\n countObjects: true,\n existsObjects: true,\n facetObjects: true,\n nodes: {\n start: true,\n refs: true,\n filter: true,\n text: true,\n vector: true,\n traverse: true,\n set: true,\n sort: true,\n limit: true,\n page: true,\n project: true,\n },\n predicateOps: {\n and: true,\n or: true,\n not: true,\n eq: true,\n neq: true,\n lt: true,\n lte: true,\n gt: true,\n gte: true,\n in: true,\n exists: true,\n contains: true,\n constant: true,\n },\n sortKinds: {\n property: true,\n relevance: true,\n },\n traversalDirections: {\n outgoing: true,\n incoming: true,\n },\n setOps: {\n union: true,\n intersect: true,\n subtract: true,\n },\n scalarOperations: {\n string: { equality: true, ordering: true },\n uuid: { equality: true, ordering: true },\n boolean: { equality: true },\n integer: { equality: true, ordering: true },\n double: { equality: true, ordering: true },\n decimal: { equality: true, ordering: true },\n date: { equality: true, ordering: true },\n timestamp: { equality: true, ordering: true },\n userRef: { equality: true },\n },\n limits: {\n totalCount: true,\n stablePageTokens: true,\n },\n}\n\ntype QueryEntry = {\n row: ObjectRow\n score: number\n order: number\n}\n\ntype QueryEvaluation = {\n entries: QueryEntry[]\n total: number\n hasMore: boolean\n nextPageToken?: string\n}\n\nconst PAGE_TOKEN_PREFIX = \"offset:\"\n\nfunction assertLinkQueryLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object link query limit must be a positive safe integer.\")\n }\n}\n\nexport function evaluateObjectQuery(\n query: ObjectQuery,\n source: InMemoryReadSource\n): QueryEvaluation {\n switch (query.kind) {\n case \"rerank\":\n throw new Error(\"[Sixb] Reranking must execute in the model runtime, not storage.\")\n case \"start\":\n return evaluateStart(query.objectTypeId, source)\n case \"refs\":\n return evaluateRefs(query.refs, source)\n case \"filter\": {\n const input = evaluateObjectQuery(query.input, source)\n const entries = input.entries.filter((entry) => matchesPredicate(entry.row, query.predicate))\n return completeEvaluation(entries)\n }\n case \"text\": {\n const input = evaluateObjectQuery(query.input, source)\n const scoredEntries = input.entries.flatMap((entry) => {\n const score = textScore(entry.row, query.query, query.fields, query.fieldsByObjectType)\n return score > 0 ? [{ ...entry, score: entry.score + score }] : []\n })\n return completeEvaluation(scoredEntries)\n }\n case \"vector\": {\n if (typeof query.vector === \"string\")\n throw new Error(\"[Sixb] Vector search text must be embedded before storage execution.\")\n const vector = query.vector\n const input = evaluateObjectQuery(query.input, source)\n const scoredEntries = input.entries.flatMap((entry) => {\n const stored = source.getVector?.(entry.row, query.profile)\n if (\n !stored ||\n !query.configuration ||\n stored.configuration !== query.configuration ||\n vectorSources(stored.source, entry.row.properties).sourceFingerprint !==\n stored.sourceFingerprint\n )\n return []\n const score = vectorSimilarity(stored.values, vector)\n return score === null\n ? []\n : [{ ...entry, score: entry.score + Math.max(-1, Math.min(1, score)) }]\n })\n scoredEntries.sort(\n (a, b) =>\n b.score - a.score ||\n Buffer.compare(Buffer.from(a.row.objectTypeId), Buffer.from(b.row.objectTypeId)) ||\n Buffer.compare(Buffer.from(a.row.primaryId), Buffer.from(b.row.primaryId))\n )\n const limit = Math.max(0, query.k)\n return {\n entries: scoredEntries.slice(0, limit),\n total: Math.min(limit, scoredEntries.length),\n hasMore: false,\n }\n }\n case \"traverse\": {\n const input = evaluateObjectQuery(query.input, source)\n const entries =\n query.direction === \"outgoing\"\n ? traverseOutgoing(input.entries, query.linkId, source)\n : traverseIncoming(input.entries, query.linkId, query.sourceObjectTypeId, source)\n return completeEvaluation(entries)\n }\n case \"set\":\n return evaluateSet(query.op, query.inputs, source)\n case \"sort\": {\n const input = evaluateObjectQuery(query.input, source)\n return {\n ...input,\n entries: sortEntries(input.entries, query.fields),\n }\n }\n case \"limit\": {\n const input = evaluateObjectQuery(query.input, source)\n const limit = Math.max(0, query.limit)\n return {\n entries: input.entries.slice(0, limit),\n total: input.entries.length,\n hasMore: limit < input.entries.length,\n }\n }\n case \"page\": {\n const input = evaluateObjectQuery(query.input, source)\n const offset = decodePageOffset(query.pageToken)\n const pageSize = Math.max(0, query.pageSize)\n const nextOffset = offset + pageSize\n const hasMore = pageSize > 0 && nextOffset < input.entries.length\n return {\n entries: input.entries.slice(offset, nextOffset),\n total: input.entries.length,\n hasMore,\n nextPageToken: hasMore ? encodePageOffset(nextOffset) : undefined,\n }\n }\n case \"project\": {\n const input = evaluateObjectQuery(query.input, source)\n if (!query.properties) return input\n const properties = query.properties\n return {\n ...input,\n entries: input.entries.map((entry) => ({\n ...entry,\n row: projectRow(entry.row, properties),\n })),\n }\n }\n case \"expand\":\n // `expand` is output-shaping and is gated off by the planner in this\n // slice (and stripped before aggregates run), so the in-memory engine\n // should never receive one. Link hydration lands in a later slice.\n throw new Error(\"[Sixb] In-memory object storage does not support 'expand' execution yet\")\n }\n}\n\nfunction evaluateStart(objectTypeId: string, source: InMemoryReadSource): QueryEvaluation {\n const rows = source.objectsOfType(objectTypeId)\n const entries = rows.map((row, index) => ({\n row,\n score: 0,\n order: index,\n }))\n return completeEvaluation(entries)\n}\n\nfunction evaluateRefs(\n refs: readonly { objectTypeId: string; primaryId: string }[],\n source: InMemoryReadSource\n): QueryEvaluation {\n const seen = new Set<string>()\n const entries = refs\n .flatMap((ref) => {\n const key = JSON.stringify([ref.objectTypeId, ref.primaryId])\n if (seen.has(key)) return []\n seen.add(key)\n const row = source.getObject(ref.objectTypeId, ref.primaryId)\n return row ? [row] : []\n })\n .sort(\n (left, right) =>\n compareStrings(left.objectTypeId, right.objectTypeId) ||\n compareStrings(left.primaryId, right.primaryId)\n )\n .map((row, order) => ({ row, score: 0, order }))\n\n return completeEvaluation(entries)\n}\n\nfunction evaluateSet(\n op: \"union\" | \"intersect\" | \"subtract\",\n inputs: readonly ObjectQuery[],\n source: InMemoryReadSource\n): QueryEvaluation {\n const evaluations = inputs.map((input) => evaluateObjectQuery(input, source))\n const first = evaluations[0]\n if (!first) return completeEvaluation([])\n\n if (op === \"union\") {\n const entriesByKey = new Map<string, QueryEntry>()\n for (const evaluation of evaluations) {\n for (const entry of evaluation.entries) {\n upsertEntry(entriesByKey, entry)\n }\n }\n return completeEvaluation([...entriesByKey.values()])\n }\n\n if (op === \"intersect\") {\n const otherKeySets = evaluations\n .slice(1)\n .map((evaluation) => new Set(evaluation.entries.map((entry) => rowIdentityKey(entry.row))))\n const entries = first.entries.filter((entry) => {\n const key = rowIdentityKey(entry.row)\n return otherKeySets.every((keys) => keys.has(key))\n })\n return completeEvaluation(entries)\n }\n\n const subtractKeys = new Set(\n evaluations\n .slice(1)\n .flatMap((evaluation) => evaluation.entries.map((entry) => rowIdentityKey(entry.row)))\n )\n return completeEvaluation(\n first.entries.filter((entry) => !subtractKeys.has(rowIdentityKey(entry.row)))\n )\n}\n\nfunction traverseOutgoing(\n entries: readonly QueryEntry[],\n linkId: string,\n source: InMemoryReadSource\n): QueryEntry[] {\n const resultsByKey = new Map<string, QueryEntry>()\n\n entries.forEach((entry, index) => {\n const links = [...source.outgoingLinks(entry.row.objectTypeId, entry.row.primaryId)]\n\n for (const link of links) {\n if (link.linkId !== linkId) continue\n const target = source.getObject(link.targetTypeId, link.targetId)\n if (!target) continue\n upsertEntry(resultsByKey, {\n row: target,\n score: entry.score,\n order: entry.order + index / 1_000_000,\n })\n }\n })\n\n return [...resultsByKey.values()]\n}\n\nfunction traverseIncoming(\n entries: readonly QueryEntry[],\n linkId: string,\n sourceObjectTypeId: string | undefined,\n source: InMemoryReadSource\n): QueryEntry[] {\n const inputEntriesByTarget = new Map(entries.map((entry) => [rowIdentityKey(entry.row), entry]))\n const resultsByKey = new Map<string, QueryEntry>()\n\n const links = [...source.allLinks()]\n for (const link of links) {\n if (link.projectId !== source.projectId || link.linkId !== linkId) continue\n if (sourceObjectTypeId !== undefined && link.sourceTypeId !== sourceObjectTypeId) continue\n const targetEntry = inputEntriesByTarget.get(\n rowIdentityKeyParts(link.targetTypeId, link.targetId)\n )\n if (!targetEntry) continue\n\n const row = source.getObject(link.sourceTypeId, link.sourceId)\n if (!row) continue\n upsertEntry(resultsByKey, {\n row,\n score: targetEntry.score,\n order: targetEntry.order,\n })\n }\n\n return [...resultsByKey.values()]\n}\n\nfunction completeEvaluation(entries: QueryEntry[]): QueryEvaluation {\n return {\n entries,\n total: entries.length,\n hasMore: false,\n }\n}\n\nfunction textScore(\n row: ObjectRow,\n query: string,\n fields: readonly string[] | undefined,\n fieldsByObjectType: Readonly<Record<string, readonly string[]>> | undefined\n): number {\n const terms = tokenize(query)\n if (terms.length === 0) return 0\n\n const scopedFields = fields ?? fieldsByObjectType?.[row.objectTypeId]\n const values = fields\n ? fields.flatMap((field) => collectTextValues(row.properties[field]))\n : scopedFields\n ? scopedFields.flatMap((field) => collectTextValues(row.properties[field]))\n : [row.primaryId, ...Object.values(row.properties).flatMap(collectTextValues)]\n const haystack = values.join(\" \").toLowerCase()\n if (!terms.every((term) => haystack.includes(term))) return 0\n\n const phrase = query.trim().toLowerCase()\n const phraseBoost = phrase.length > 0 && haystack.includes(phrase) ? terms.length : 0\n return terms.reduce((score, term) => score + countOccurrences(haystack, term), phraseBoost)\n}\n\nfunction tokenize(query: string): string[] {\n return query\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0)\n}\n\nfunction collectTextValues(value: unknown): string[] {\n if (typeof value === \"string\") return [value]\n if (Array.isArray(value)) return value.flatMap(collectTextValues)\n return []\n}\n\nfunction countOccurrences(value: string, needle: string): number {\n if (!needle) return 0\n let count = 0\n let index = value.indexOf(needle)\n while (index !== -1) {\n count += 1\n index = value.indexOf(needle, index + needle.length)\n }\n return count\n}\n\nfunction vectorSimilarity(actual: unknown, expected: readonly number[]): number | null {\n if (!Array.isArray(actual) || actual.length !== expected.length || actual.length === 0) {\n return null\n }\n\n let dot = 0\n let actualNorm = 0\n let expectedNorm = 0\n for (let index = 0; index < expected.length; index += 1) {\n const actualValue = actual[index]\n const expectedValue = expected[index]\n if (\n typeof actualValue !== \"number\" ||\n typeof expectedValue !== \"number\" ||\n !Number.isFinite(actualValue) ||\n !Number.isFinite(expectedValue)\n ) {\n return null\n }\n\n dot += actualValue * expectedValue\n actualNorm += actualValue * actualValue\n expectedNorm += expectedValue * expectedValue\n }\n\n if (actualNorm === 0 || expectedNorm === 0) return null\n return dot / (Math.sqrt(actualNorm) * Math.sqrt(expectedNorm))\n}\n\nfunction sortEntries(\n entries: readonly QueryEntry[],\n fields: readonly ObjectQuerySortField[]\n): QueryEntry[] {\n return [...entries].sort((left, right) => {\n for (const field of fields) {\n const comparison = compareSortField(left, right, field)\n if (comparison !== 0) return comparison\n }\n return (\n left.order - right.order || rowIdentityKey(left.row).localeCompare(rowIdentityKey(right.row))\n )\n })\n}\n\nfunction compareSortField(\n left: QueryEntry,\n right: QueryEntry,\n field: ObjectQuerySortField\n): number {\n if (field.kind === \"relevance\") {\n const direction = field.direction ?? \"desc\"\n const comparison = right.score - left.score\n return direction === \"desc\" ? comparison : -comparison\n }\n\n const leftValue = left.row.properties[field.propertyId]\n const rightValue = right.row.properties[field.propertyId]\n const leftMissing = leftValue === undefined || leftValue === null\n const rightMissing = rightValue === undefined || rightValue === null\n if (leftMissing && rightMissing) return 0\n if (leftMissing) return 1\n if (rightMissing) return -1\n\n const comparison = compareQueryScalarValues(leftValue, rightValue, field.scalarKind)\n if (Number.isNaN(comparison)) return 0\n return field.direction === \"desc\" ? -comparison : comparison\n}\n\nfunction projectRow(row: ObjectRow, properties: readonly string[]): ObjectRow {\n const projected: Record<string, unknown> = {}\n for (const propertyId of properties) {\n if (Object.hasOwn(row.properties, propertyId)) {\n projected[propertyId] = row.properties[propertyId]\n }\n }\n return {\n ...row,\n properties: projected,\n }\n}\n\nexport function stripOuterRowShape(query: ObjectQuery): ObjectQuery {\n switch (query.kind) {\n case \"limit\":\n case \"page\":\n case \"project\":\n case \"sort\":\n // `expand` is output-shaping: aggregates ignore it (it never changes which\n // objects match).\n case \"expand\":\n return stripOuterRowShape(query.input)\n default:\n return query\n }\n}\n\nexport function buildFacetResults(\n rows: readonly ObjectRow[],\n facets: readonly ObjectFacetRequest[]\n): ObjectFacetResult[] {\n return facets.map((facet) => ({\n propertyId: facet.propertyId,\n buckets: buildFacetBuckets(rows, facet),\n }))\n}\n\nfunction buildFacetBuckets(\n rows: readonly ObjectRow[],\n facet: ObjectFacetRequest\n): ObjectFacetResult[\"buckets\"] {\n const buckets = new Map<string, { value: unknown; count: number }>()\n\n for (const row of rows) {\n if (!Object.hasOwn(row.properties, facet.propertyId)) continue\n const value = row.properties[facet.propertyId]\n if (value === undefined) continue\n const key = facetValueKey(value)\n const existing = buckets.get(key)\n if (existing) {\n existing.count += 1\n } else {\n buckets.set(key, { value, count: 1 })\n }\n }\n\n return [...buckets.values()]\n .sort(\n (left, right) =>\n right.count - left.count ||\n facetValueSortKey(left.value).localeCompare(facetValueSortKey(right.value))\n )\n .slice(0, facet.limit)\n}\n\nfunction facetValueKey(value: unknown): string {\n return JSON.stringify(value) ?? String(value)\n}\n\nfunction facetValueSortKey(value: unknown): string {\n return JSON.stringify(value) ?? String(value)\n}\n\nexport async function queryLinksFrom(\n params: QueryObjectLinksInput,\n listLinks: (\n input: Parameters<ObjectReadStorage[\"listLinks\"]>[0]\n ) => Promise<readonly ObjectLinkRow[]> | readonly ObjectLinkRow[]\n): Promise<QueryObjectLinksResult> {\n assertLinkQueryLimit(params.limit)\n if (params.objectRefs.length === 0 || params.endpointObjectTypeIds?.length === 0) {\n return { links: [], hasMore: false }\n }\n\n const allowedTypes = params.endpointObjectTypeIds\n ? new Set(params.endpointObjectTypeIds)\n : undefined\n const deduped = new Map<string, ObjectLinkRow>()\n for (const object of params.objectRefs) {\n const rows = await listLinks({\n projectId: params.projectId,\n objectTypeId: object.objectTypeId,\n objectId: object.primaryId,\n direction: params.direction,\n ...(params.linkId === undefined ? {} : { linkId: params.linkId }),\n })\n for (const row of rows) {\n if (\n allowedTypes &&\n (!allowedTypes.has(row.sourceTypeId) || !allowedTypes.has(row.targetTypeId))\n ) {\n continue\n }\n if (params.after && compareObjectLinkCursors(objectLinkCursor(row), params.after) <= 0) {\n continue\n }\n deduped.set(fullLinkRowKey(row), row)\n }\n }\n\n const rows = [...deduped.values()].sort(compareObjectLinks).slice(0, params.limit + 1)\n return { links: rows.slice(0, params.limit), hasMore: rows.length > params.limit }\n}\n\ninterface LinkBatchSource {\n all(): Iterable<ObjectLinkRow>\n outgoing(item: {\n readonly objectTypeId: string\n readonly objectId: string\n readonly linkId: string\n }): Iterable<ObjectLinkRow>\n}\n\nexport function collectLinksBatch(\n source: LinkBatchSource,\n params: Parameters<ObjectReadStorage[\"listLinksBatch\"]>[0],\n cloneRows: boolean\n): Map<LinkBatchKey, ObjectLinkRow[]> {\n const direction = params.direction ?? \"outgoing\"\n const orderedKeys = [\n ...new Set(\n params.items.map((item) => linkBatchKey(item.objectTypeId, item.objectId, item.linkId))\n ),\n ]\n const requestedKeys = new Set(orderedKeys)\n const grouped = new Map<LinkBatchKey, Map<string, ObjectLinkRow>>()\n const append = (key: LinkBatchKey, row: ObjectLinkRow): void => {\n const bucket = grouped.get(key) ?? new Map<string, ObjectLinkRow>()\n bucket.set(fullLinkRowKey(row), row)\n grouped.set(key, bucket)\n }\n\n if (direction === \"outgoing\" || direction === \"both\") {\n for (const item of params.items) {\n const key = linkBatchKey(item.objectTypeId, item.objectId, item.linkId)\n for (const row of source.outgoing(item)) {\n if (row.projectId === params.projectId && row.linkId === item.linkId) append(key, row)\n }\n }\n }\n\n if (direction === \"incoming\" || direction === \"both\") {\n for (const row of source.all()) {\n if (row.projectId !== params.projectId) continue\n const key = linkBatchKey(row.targetTypeId, row.targetId, row.linkId)\n if (requestedKeys.has(key)) append(key, row)\n }\n }\n\n return new Map(\n orderedKeys.flatMap((key) => {\n const bucket = grouped.get(key)\n if (!bucket) return []\n return [\n [key, [...bucket.values()].map((row) => (cloneRows ? structuredClone(row) : row))] as const,\n ]\n })\n )\n}\n\nfunction upsertEntry(entriesByKey: Map<string, QueryEntry>, entry: QueryEntry): void {\n const key = rowIdentityKey(entry.row)\n const existing = entriesByKey.get(key)\n if (!existing) {\n entriesByKey.set(key, entry)\n return\n }\n\n if (entry.score > existing.score) {\n entriesByKey.set(key, {\n ...existing,\n score: entry.score,\n })\n }\n}\n\nfunction encodePageOffset(offset: number): string {\n return `${PAGE_TOKEN_PREFIX}${offset}`\n}\n\nfunction decodePageOffset(token: string | undefined): number {\n if (!token) return 0\n if (!token.startsWith(PAGE_TOKEN_PREFIX)) {\n throw new Error(\"[Sixb] Invalid object query page token\")\n }\n\n const offset = Number(token.slice(PAGE_TOKEN_PREFIX.length))\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error(\"[Sixb] Invalid object query page token\")\n }\n return offset\n}\n",
|
|
23
|
+
"import { hasVectorProfile } from \"../../../objects/vectors/query\"\nimport {\n assertObjectReadFacetCount,\n assertObjectReadOutputWithinLimit,\n type ObjectReadExecutionLimits,\n} from \"../execution-limits\"\nimport { type ObjectBatchKey, objectBatchKey } from \"../keys\"\nimport { assertObjectReaderProject } from \"../read-scope\"\nimport type {\n CountObjectsInput,\n ExistsObjectsInput,\n FacetObjectsInput,\n LinkDirection,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n QueryObjectsInput,\n} from \"../types\"\nimport { fullLinkRowKey } from \"./keys\"\nimport {\n buildFacetResults,\n collectLinksBatch,\n evaluateObjectQuery,\n queryLinksFrom,\n stripOuterRowShape,\n} from \"./query\"\nimport type { InMemoryScopedReadSource } from \"./read-source\"\n\n/**\n * Answer every terminal from what a scope leaves visible, resolved again for each operation so\n * reads stay live. Rows leave detached; output budgets apply when the scope carries them.\n */\nexport function createInMemoryScopedReader(params: {\n projectId: string\n resolve: () => InMemoryScopedReadSource\n limits?: ObjectReadExecutionLimits\n queryCapabilities: () => ObjectQueryCapabilities\n}): ObjectReadStorage {\n const { projectId, resolve, limits, queryCapabilities } = params\n const assertProject = (actualProjectId: string) =>\n assertObjectReaderProject(projectId, actualProjectId)\n const visible = <T>(value: T): T => {\n if (limits) assertObjectReadOutputWithinLimit(value, limits)\n return value\n }\n const visibleMap = <TKey, TValue>(value: Map<TKey, TValue>): Map<TKey, TValue> => {\n if (limits) assertObjectReadOutputWithinLimit([...value.entries()], limits)\n return value\n }\n const selectsObjectProperties: ObjectReadStorage[\"selectsObjectProperties\"] = async (input) => {\n assertProject(input.projectId)\n const source = resolve()\n return visible(\n input.items.map((item) =>\n source.selectsProperty(item.objectTypeId, item.primaryId, item.propertyId)\n )\n )\n }\n\n return Object.freeze({\n queryCapabilities,\n queryObjects: async (input: QueryObjectsInput) => {\n assertProject(input.projectId)\n const result = evaluateObjectQuery(input.query, resolve())\n return visible({\n objects: result.entries.map((entry) => ({\n ...structuredClone(entry.row),\n ...(hasVectorProfile(input.query) ? { score: entry.score } : {}),\n })),\n hasMore: result.hasMore,\n nextPageToken: result.nextPageToken,\n ...(input.includeTotal === false ? {} : { total: result.total }),\n })\n },\n countObjects: async (input: CountObjectsInput) => {\n assertProject(input.projectId)\n return visible({\n count: evaluateObjectQuery(stripOuterRowShape(input.query), resolve()).total,\n })\n },\n existsObjects: async (input: ExistsObjectsInput) => {\n assertProject(input.projectId)\n return visible({\n exists: evaluateObjectQuery(stripOuterRowShape(input.query), resolve()).total > 0,\n })\n },\n facetObjects: async (input: FacetObjectsInput) => {\n assertProject(input.projectId)\n assertObjectReadFacetCount(input.facets.length)\n const result = evaluateObjectQuery(stripOuterRowShape(input.query), resolve())\n return visible(\n structuredClone({\n total: result.entries.length,\n facets: buildFacetResults(\n result.entries.map((entry) => entry.row),\n input.facets\n ),\n })\n )\n },\n getByPrimaryId: async (input) => {\n assertProject(input.projectId)\n const row = resolve().getObject(input.objectTypeId, input.primaryId)\n return visible(row ? structuredClone(row) : null)\n },\n getByUniqueValue: async (input) => {\n assertProject(input.projectId)\n const source = resolve()\n const holder = source.uniqueHolder(input)\n const row = holder === undefined ? undefined : source.getObject(input.objectTypeId, holder)\n return visible(row ? structuredClone(row) : null)\n },\n selectsObjectProperties,\n listLinks: async (input) => {\n assertProject(input.projectId)\n return visible(listScopedLinks(resolve(), input).map((row) => structuredClone(row)))\n },\n getByPrimaryIdBatch: async (input) => {\n assertProject(input.projectId)\n const source = resolve()\n const rows = new Map<ObjectBatchKey, ObjectRow>()\n for (const item of input.items) {\n const row = source.getObject(item.objectTypeId, item.primaryId)\n if (row) {\n rows.set(objectBatchKey(item.objectTypeId, item.primaryId), structuredClone(row))\n }\n }\n return visibleMap(rows)\n },\n listLinksBatch: async (input) => {\n assertProject(input.projectId)\n const source = resolve()\n return visibleMap(\n collectLinksBatch(\n {\n all: () => source.allLinks(),\n outgoing: (item) => source.outgoingLinks(item.objectTypeId, item.objectId),\n },\n input,\n true\n )\n )\n },\n queryLinks: async (input) => {\n assertProject(input.projectId)\n const source = resolve()\n return visible(\n structuredClone(await queryLinksFrom(input, (item) => listScopedLinks(source, item)))\n )\n },\n list: async (input) => {\n assertProject(input.projectId)\n return visible(listRows(input, [...resolve().allObjects()]))\n },\n } satisfies ObjectReadStorage)\n}\n\nfunction listScopedLinks(\n source: InMemoryScopedReadSource,\n params: {\n readonly projectId: string\n readonly objectTypeId: string\n readonly objectId: string\n readonly linkId?: string\n readonly direction?: LinkDirection\n }\n): ObjectLinkRow[] {\n const direction = params.direction ?? \"outgoing\"\n const matches = (row: ObjectLinkRow) => !params.linkId || row.linkId === params.linkId\n const rows: ObjectLinkRow[] = []\n\n if (direction === \"outgoing\" || direction === \"both\") {\n for (const row of source.outgoingLinks(params.objectTypeId, params.objectId)) {\n if (matches(row)) rows.push(row)\n }\n }\n if (direction === \"incoming\" || direction === \"both\") {\n for (const row of source.allLinks()) {\n if (\n row.targetTypeId === params.objectTypeId &&\n row.targetId === params.objectId &&\n matches(row)\n ) {\n rows.push(row)\n }\n }\n }\n\n if (direction !== \"both\") return rows\n return [...new Map(rows.map((row) => [fullLinkRowKey(row), row])).values()]\n}\n\nfunction listRows(\n params: Parameters<ObjectReadStorage[\"list\"]>[0],\n candidates: readonly ObjectRow[]\n): { objects: readonly ObjectRow[]; hasMore: boolean; total: number } {\n const requestedTypes =\n params.objectTypeId === undefined\n ? undefined\n : new Set(\n typeof params.objectTypeId === \"string\" ? [params.objectTypeId] : params.objectTypeId\n )\n let rows = candidates.filter(\n (row) =>\n row.projectId === params.projectId &&\n (!requestedTypes || requestedTypes.has(row.objectTypeId))\n )\n\n rows = rows.filter(\n (row) =>\n (!params.primaryIdPrefix || row.primaryId.startsWith(params.primaryIdPrefix)) &&\n (!params.primaryIdSuffix || row.primaryId.endsWith(params.primaryIdSuffix)) &&\n (!params.updatedAfter || row.updatedAt >= params.updatedAfter) &&\n (!params.updatedBefore || row.updatedAt <= params.updatedBefore) &&\n (!params.createdAfter || row.createdAt >= params.createdAfter) &&\n (!params.createdBefore || row.createdAt <= params.createdBefore)\n )\n\n const total = rows.length\n const offset = params.offset ?? 0\n const limit = params.limit ?? 50\n if (limit === 0) return { objects: [], hasMore: offset < total, total }\n\n const orderBy = params.orderBy ?? \"updatedAt\"\n const order = params.order ?? \"desc\"\n rows.sort((left, right) => {\n const comparison =\n orderBy === \"primaryId\"\n ? left.primaryId.localeCompare(right.primaryId)\n : orderBy === \"createdAt\"\n ? left.createdAt.getTime() - right.createdAt.getTime()\n : left.updatedAt.getTime() - right.updatedAt.getTime()\n return order === \"desc\" ? -comparison : comparison\n })\n\n const objects = rows.slice(offset, offset + limit).map((row) => structuredClone(row))\n return {\n objects,\n hasMore: offset + limit < total,\n total,\n }\n}\n",
|
|
24
|
+
"import type { ObjectQueryPredicate } from \"../../../objects/query\"\nimport { matchesPredicate } from \"../../../objects/query/matches-predicate\"\nimport type {\n CompiledConditionalObjectReadScope,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n} from \"../types\"\nimport type { InMemoryReadSource, InMemoryScopedReadSource } from \"./read-source\"\nimport { createInMemoryScopedReader } from \"./scoped-reader\"\n\n/** Read the live store through a conditional scope. */\nexport function createInMemoryConditionalReader(\n source: InMemoryReadSource,\n scope: CompiledConditionalObjectReadScope,\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n const conditional = createConditionalReadSource(source, scope)\n\n return createInMemoryScopedReader({\n projectId: source.projectId,\n resolve: () => conditional,\n queryCapabilities,\n })\n}\n\n/**\n * Filter the live source as it is read: an object of a conditioned type exists only while its\n * condition matches, and a link only while both its endpoints do.\n */\nfunction createConditionalReadSource(\n source: InMemoryReadSource,\n scope: CompiledConditionalObjectReadScope\n): InMemoryScopedReadSource {\n const predicates = new Map<string, ObjectQueryPredicate>(\n scope.conditions.map((condition) => [condition.objectTypeId, condition.predicate])\n )\n\n const isVisible = (row: ObjectRow): boolean => {\n const predicate = predicates.get(row.objectTypeId)\n return predicate === undefined || matchesPredicate(row, predicate)\n }\n\n const getObject = (objectTypeId: string, primaryId: string): ObjectRow | undefined => {\n const row = source.getObject(objectTypeId, primaryId)\n return row && isVisible(row) ? row : undefined\n }\n\n // An endpoint of an unconditioned type is read as unscoped storage reads it, stored or not.\n const isVisibleEndpoint = (objectTypeId: string, primaryId: string): boolean =>\n !predicates.has(objectTypeId) || getObject(objectTypeId, primaryId) !== undefined\n\n const isVisibleLink = (link: ObjectLinkRow): boolean =>\n isVisibleEndpoint(link.sourceTypeId, link.sourceId) &&\n isVisibleEndpoint(link.targetTypeId, link.targetId)\n\n return {\n projectId: source.projectId,\n selectsProperty: (objectTypeId, primaryId) => getObject(objectTypeId, primaryId) !== undefined,\n // Read only for rows a query already found here.\n getVector: (ref, profile) => source.getVector?.(ref, profile),\n allObjects: () => [...source.allObjects()].filter(isVisible),\n objectsOfType: (objectTypeId) => source.objectsOfType(objectTypeId).filter(isVisible),\n getObject,\n outgoingLinks: (objectTypeId, primaryId) =>\n [...source.outgoingLinks(objectTypeId, primaryId)].filter(isVisibleLink),\n allLinks: () => [...source.allLinks()].filter(isVisibleLink),\n // A hidden holder is read through getObject, which finds nothing.\n uniqueHolder: (value) => source.uniqueHolder(value),\n }\n}\n",
|
|
25
|
+
"import { type ObjectReadExecutionLimits, ObjectReadLimitExceededError } from \"../execution-limits\"\nimport type {\n CompiledObjectReadRoot,\n CompiledObjectReadStep,\n CompiledSelectedObjectReadScope,\n ObjectLinkRow,\n ObjectRow,\n} from \"../types\"\nimport { fullLinkRowKey, rowIdentityKey, rowIdentityKeyParts, sourceLinkBucketKey } from \"./keys\"\nimport type { InMemoryReadSource, InMemoryScopedReadSource } from \"./read-source\"\n\ninterface InMemoryReadPlan {\n readonly roots: readonly CompiledObjectReadRoot[]\n readonly selectionsByNode: ReadonlyMap<number, ReadonlyMap<string, ReadonlySet<string>>>\n readonly steps: readonly CompiledObjectReadStep[]\n}\n\nexport function prepareReadPlan(scope: CompiledSelectedObjectReadScope): InMemoryReadPlan {\n const selectionsByNode = new Map<number, Map<string, ReadonlySet<string>>>()\n for (const selection of scope.objects) {\n const byType = selectionsByNode.get(selection.nodeId) ?? new Map()\n byType.set(selection.objectTypeId, new Set(selection.propertyIds))\n selectionsByNode.set(selection.nodeId, byType)\n }\n\n // The compiler allocates node ids parent-first. Resolve every step from lower parent ids to\n // higher child ids so a node reached through several concrete definitions is complete before\n // its nested selections run.\n const steps = [...scope.steps].sort(\n (left, right) =>\n left.parentNodeId - right.parentNodeId ||\n left.nodeId - right.nodeId ||\n left.sourceObjectTypeId.localeCompare(right.sourceObjectTypeId) ||\n left.linkId.localeCompare(right.linkId) ||\n left.targetObjectTypeId.localeCompare(right.targetObjectTypeId)\n )\n return {\n roots: scope.roots,\n selectionsByNode,\n steps,\n }\n}\n\nexport function resolveSelectedReadUniverse(\n source: InMemoryReadSource,\n plan: InMemoryReadPlan,\n limits: ObjectReadExecutionLimits\n): InMemoryScopedReadSource {\n // Reachability stays path-sensitive until every finite selection step has run. The final\n // object/link universes union exact identities only after that traversal, so the same type\n // reached through another branch cannot inherit nested link authority.\n const reachableByNode = new Map<number, Map<string, ObjectRow>>()\n const rawObjects = new Map<string, ObjectRow>()\n const objectProperties = new Map<string, Set<string>>()\n const authorizedLinks = new Map<\n string,\n { readonly row: ObjectLinkRow; readonly propertyIds: Set<string> }\n >()\n let traversalFacts = 0\n const consumeTraversalFact = (): void => {\n traversalFacts += 1\n if (traversalFacts > limits.maxTraversalFacts) {\n throw new ObjectReadLimitExceededError(\"traversalFacts\", limits.maxTraversalFacts)\n }\n }\n\n const addReachable = (nodeId: number, row: ObjectRow): void => {\n const selectedProperties = plan.selectionsByNode.get(nodeId)?.get(row.objectTypeId)\n if (!selectedProperties) return\n const key = rowIdentityKey(row)\n const reachable = reachableByNode.get(nodeId) ?? new Map<string, ObjectRow>()\n reachable.set(key, row)\n reachableByNode.set(nodeId, reachable)\n rawObjects.set(key, row)\n unionInto(objectProperties, key, selectedProperties)\n }\n\n for (const root of plan.roots) {\n const row = source.getObject(root.objectTypeId, root.primaryId)\n if (row) {\n consumeTraversalFact()\n addReachable(root.nodeId, row)\n }\n }\n\n for (const step of plan.steps) {\n const parents = reachableByNode.get(step.parentNodeId)\n if (!parents) continue\n for (const parent of parents.values()) {\n if (parent.objectTypeId !== step.sourceObjectTypeId) continue\n for (const link of source.outgoingLinks(parent.objectTypeId, parent.primaryId)) {\n if (link.linkId !== step.linkId || link.targetTypeId !== step.targetObjectTypeId) {\n continue\n }\n const target = source.getObject(link.targetTypeId, link.targetId)\n if (!target) continue\n consumeTraversalFact()\n addReachable(step.nodeId, target)\n\n const linkKey = fullLinkRowKey(link)\n const selected = authorizedLinks.get(linkKey)\n if (selected) {\n for (const propertyId of step.propertyIds) selected.propertyIds.add(propertyId)\n } else {\n authorizedLinks.set(linkKey, {\n row: link,\n propertyIds: new Set(step.propertyIds),\n })\n }\n }\n }\n }\n\n const objects = new Map<string, ObjectRow>()\n for (const [key, propertyIds] of objectProperties) {\n const row = rawObjects.get(key)\n if (row) objects.set(key, redactObjectRow(row, propertyIds))\n }\n\n const links = new Map<string, ObjectLinkRow>()\n for (const [key, selected] of authorizedLinks) {\n // Both endpoint identities must remain live and selected. This also prevents a stale link\n // from exposing metadata after its target object disappears.\n if (\n !objects.has(rowIdentityKeyParts(selected.row.sourceTypeId, selected.row.sourceId)) ||\n !objects.has(rowIdentityKeyParts(selected.row.targetTypeId, selected.row.targetId))\n ) {\n continue\n }\n links.set(key, redactLinkRow(selected.row, selected.propertyIds))\n }\n\n return createReadUniverse(source, objects, links, objectProperties)\n}\n\nfunction createReadUniverse(\n source: InMemoryReadSource,\n objects: ReadonlyMap<string, ObjectRow>,\n links: ReadonlyMap<string, ObjectLinkRow>,\n objectProperties: ReadonlyMap<string, ReadonlySet<string>>\n): InMemoryScopedReadSource {\n const projectId = source.projectId\n const linksBySource = new Map<string, ObjectLinkRow[]>()\n for (const link of links.values()) {\n const key = sourceLinkBucketKey(link.projectId, link.sourceTypeId, link.sourceId)\n const bucket = linksBySource.get(key) ?? []\n bucket.push(link)\n linksBySource.set(key, bucket)\n }\n return {\n projectId,\n selectsProperty: (objectTypeId, primaryId, propertyId) =>\n objectProperties.get(rowIdentityKeyParts(objectTypeId, primaryId))?.has(propertyId) ?? false,\n getVector: (ref, profile) => {\n const key = rowIdentityKeyParts(ref.objectTypeId, ref.primaryId)\n if (!objects.has(key)) return undefined\n const value = source.getVector?.(ref, profile)\n return value?.source.every((id) => objectProperties.get(key)?.has(id)) ? value : undefined\n },\n allObjects: () => objects.values(),\n objectsOfType: (objectTypeId) =>\n [...objects.values()].filter((row) => row.objectTypeId === objectTypeId),\n getObject: (objectTypeId, primaryId) =>\n objects.get(rowIdentityKeyParts(objectTypeId, primaryId)),\n outgoingLinks: (objectTypeId, primaryId) =>\n linksBySource.get(sourceLinkBucketKey(projectId, objectTypeId, primaryId)) ?? [],\n allLinks: () => links.values(),\n // A holder outside the selection, or whose value it does not select, holds nothing here.\n uniqueHolder: (value) => {\n const holder = source.uniqueHolder(value)\n if (holder === undefined) return undefined\n const key = rowIdentityKeyParts(value.objectTypeId, holder)\n return objects.has(key) && objectProperties.get(key)?.has(value.propertyId)\n ? holder\n : undefined\n },\n }\n}\n\nfunction unionInto(\n target: Map<string, Set<string>>,\n key: string,\n values: ReadonlySet<string>\n): void {\n const union = target.get(key) ?? new Set<string>()\n for (const value of values) union.add(value)\n target.set(key, union)\n}\n\nfunction redactObjectRow(row: ObjectRow, propertyIds: ReadonlySet<string>): ObjectRow {\n const clone = structuredClone(row)\n delete clone.links\n clone.properties = redactProperties(clone.properties, propertyIds)\n return clone\n}\n\nfunction redactLinkRow(row: ObjectLinkRow, propertyIds: ReadonlySet<string>): ObjectLinkRow {\n const clone = structuredClone(row)\n const properties = redactProperties(clone.properties ?? {}, propertyIds)\n if (Object.keys(properties).length === 0) {\n delete clone.properties\n } else {\n clone.properties = properties\n }\n return clone\n}\n\nfunction redactProperties(\n properties: Readonly<Record<string, unknown>>,\n propertyIds: ReadonlySet<string>\n): Record<string, unknown> {\n // Object.fromEntries uses CreateDataProperty, so valid ontology ids such as `__proto__` remain\n // ordinary own properties without changing the returned object's prototype.\n return Object.fromEntries(\n [...propertyIds]\n .filter((propertyId) => Object.hasOwn(properties, propertyId))\n .map((propertyId) => [propertyId, properties[propertyId]])\n )\n}\n",
|
|
26
|
+
"import {\n type ObjectReadExecutionLimits,\n snapshotObjectReadExecutionLimits,\n} from \"../execution-limits\"\nimport type {\n CompiledSelectedObjectReadScope,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n} from \"../types\"\nimport { prepareReadPlan, resolveSelectedReadUniverse } from \"./read-scope\"\nimport type { InMemoryReadSource } from \"./read-source\"\nimport { createInMemoryScopedReader } from \"./scoped-reader\"\n\n/** Capture a selection once, then resolve its live data and enforce budgets per operation. */\nexport function createInMemorySelectedReader(\n source: InMemoryReadSource,\n params: {\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n },\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n const plan = prepareReadPlan(params.scope)\n const limits = snapshotObjectReadExecutionLimits(params.limits)\n\n return createInMemoryScopedReader({\n projectId: source.projectId,\n resolve: () => resolveSelectedReadUniverse(source, plan, limits),\n limits,\n queryCapabilities,\n })\n}\n",
|
|
27
|
+
"import type { EffectiveLinkSnapshot, EffectiveObjectSnapshot } from \"../../../materialization/model\"\nimport { hasVectorProfile } from \"../../../objects/vectors/query\"\nimport { uniqueValueKey } from \"../../../ontology/unique-values\"\nimport type {\n ExactUniqueValueClaim,\n ExactUniqueValueWrite,\n UniqueValueRef,\n} from \"../../ontology/materializations\"\nimport { uniqueValueViolation } from \"../../ontology/provider-work\"\nimport type { PreparedUniqueProperty, UniqueValueEntry } from \"../../ontology/unique-values\"\nimport type { StoredObjectVector } from \"../../ontology/vectors\"\nimport type { ObjectReadExecutionLimits } from \"../execution-limits\"\nimport { type LinkBatchKey, type ObjectBatchKey, objectBatchKey } from \"../keys\"\nimport type {\n CompiledConditionalObjectReadScope,\n CompiledSelectedObjectReadScope,\n CountObjectsInput,\n CountObjectsResult,\n ExistsObjectsInput,\n ExistsObjectsResult,\n FacetObjectsInput,\n FacetObjectsResult,\n LinkDirection,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n ObjectRow,\n ObjectStorage,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n QueryObjectsInput,\n QueryObjectsResult,\n} from \"../types\"\nimport { createInMemoryConditionalReader } from \"./conditional-reader\"\nimport {\n compareStrings,\n fullLinkRowKey,\n linkRowKey,\n objectRowKey,\n objectRowProjectPrefix,\n sourceLinkBucketKey,\n} from \"./keys\"\nimport {\n buildFacetResults,\n collectLinksBatch,\n evaluateObjectQuery,\n IN_MEMORY_OBJECT_QUERY_CAPABILITIES,\n queryLinksFrom,\n stripOuterRowShape,\n} from \"./query\"\nimport type { InMemoryReadSource } from \"./read-source\"\nimport { createInMemorySelectedReader } from \"./selected-reader\"\n\nexport interface InMemoryObjectStorageSnapshot {\n readonly rows: Map<string, Map<string, ObjectRow>>\n readonly links: Map<string, Map<string, ObjectLinkRow>>\n readonly uniqueValues: Map<string, Map<string, string>>\n readonly uniqueProperties: Map<string, InMemoryPreparedUniqueProperty>\n}\n\ninterface InMemoryPreparedUniqueProperty extends PreparedUniqueProperty {\n readonly projectId: string\n readonly preparedAt: string\n}\n\ntype VectorReader = (\n projectId: string,\n ref: { objectTypeId: string; primaryId: string },\n profile: string\n) => StoredObjectVector | undefined\n\ninterface InMemoryObjectMaterializerAdapter {\n setVectorReader(reader: VectorReader): void\n getExactObjectRow(projectId: string, objectTypeId: string, primaryId: string): ObjectRow | null\n getExactLinkRow(\n projectId: string,\n ref: {\n readonly sourceTypeId: string\n readonly sourceId: string\n readonly linkId: string\n readonly targetTypeId: string\n readonly targetId: string\n }\n ): ObjectLinkRow | null\n applyExactObject(row: EffectiveObjectSnapshot, projectId: string): void\n deleteExactObject(projectId: string, objectTypeId: string, primaryId: string): void\n applyExactLink(row: EffectiveLinkSnapshot, projectId: string): void\n deleteExactLink(row: {\n projectId: string\n sourceTypeId: string\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n }): void\n visitExactLinks(projectId: string, visit: (row: ObjectLinkRow) => void): void\n visitExactScopeLinks(\n projectId: string,\n sourceTypeId: string,\n sourceId: string,\n linkId: string,\n visit: (row: ObjectLinkRow) => void\n ): void\n getUniqueHolder(projectId: string, value: UniqueValueRef): string | null\n releaseUniqueValue(projectId: string, value: ExactUniqueValueWrite): void\n /** Throws `UniqueValueViolationError` when another object holds the value. */\n claimUniqueValue(projectId: string, value: ExactUniqueValueClaim): void\n listPreparedUniqueProperties(projectId: string): PreparedUniqueProperty[]\n clearUniqueProperty(projectId: string, objectTypeId: string, propertyId: string): void\n insertUniqueValues(\n projectId: string,\n objectTypeId: string,\n propertyId: string,\n entries: readonly UniqueValueEntry[]\n ): void\n markUniquePropertyPrepared(input: InMemoryPreparedUniqueProperty): void\n}\n\nconst materializerAdapters = new WeakMap<InMemoryObjectStorage, InMemoryObjectMaterializerAdapter>()\n\n/** @internal Exact access for the in-memory ontology provider; not exported from package barrels. */\nexport function getInMemoryObjectMaterializerAdapter(\n storage: InMemoryObjectStorage\n): InMemoryObjectMaterializerAdapter {\n const adapter = materializerAdapters.get(storage)\n if (!adapter) throw new Error(\"[Sixb] In-memory object materializer adapter is unavailable.\")\n return adapter\n}\n\nexport class InMemoryObjectStorage implements ObjectStorage {\n private readonly rows = new Map<string, Map<string, ObjectRow>>()\n private readonly links = new Map<string, Map<string, ObjectLinkRow>>()\n /** Holder primary ids by value key, for each unique property of a project. */\n private readonly uniqueValues = new Map<string, Map<string, string>>()\n private readonly uniqueProperties = new Map<string, InMemoryPreparedUniqueProperty>()\n\n private vectorReader?: VectorReader\n\n constructor() {\n materializerAdapters.set(this, {\n setVectorReader: (reader) => {\n this.vectorReader = reader\n },\n getExactObjectRow: (projectId, objectTypeId, primaryId) =>\n this.getExactObjectRow(projectId, objectTypeId, primaryId),\n getExactLinkRow: (projectId, ref) => this.getExactLinkRow(projectId, ref),\n applyExactObject: (row, projectId) => this.applyExactObject(row, projectId),\n deleteExactObject: (projectId, objectTypeId, primaryId) =>\n this.deleteExactObject(projectId, objectTypeId, primaryId),\n applyExactLink: (row, projectId) => this.applyExactLink(row, projectId),\n deleteExactLink: (row) => this.deleteExactLink(row),\n visitExactLinks: (projectId, visit) => {\n for (const bucket of this.links.values()) {\n for (const row of bucket.values()) {\n if (row.projectId === projectId) visit(structuredClone(row))\n }\n }\n },\n visitExactScopeLinks: (projectId, sourceTypeId, sourceId, linkId, visit) => {\n const bucket = this.links.get(sourceLinkBucketKey(projectId, sourceTypeId, sourceId))\n if (!bucket) return\n for (const row of bucket.values()) {\n if (row.linkId === linkId) visit(structuredClone(row))\n }\n },\n getUniqueHolder: (projectId, value) => this.uniqueHolder(projectId, value) ?? null,\n releaseUniqueValue: (projectId, value) => this.releaseUniqueValue(projectId, value),\n claimUniqueValue: (projectId, value) => this.claimUniqueValue(projectId, value),\n listPreparedUniqueProperties: (projectId) =>\n [...this.uniqueProperties.values()]\n .filter((prepared) => prepared.projectId === projectId)\n .map(({ objectTypeId, propertyId, keyKind, keyVersion }) => ({\n objectTypeId,\n propertyId,\n keyKind,\n keyVersion,\n })),\n clearUniqueProperty: (projectId, objectTypeId, propertyId) => {\n const key = uniquePropertyKey(projectId, objectTypeId, propertyId)\n this.uniqueValues.delete(key)\n this.uniqueProperties.delete(key)\n },\n insertUniqueValues: (projectId, objectTypeId, propertyId, entries) => {\n for (const { valueKey, primaryId } of entries) {\n this.holdUniqueValue(projectId, { objectTypeId, propertyId, valueKey, primaryId })\n }\n },\n markUniquePropertyPrepared: (input) => {\n this.uniqueProperties.set(\n uniquePropertyKey(input.projectId, input.objectTypeId, input.propertyId),\n { ...input }\n )\n },\n })\n }\n\n snapshot(): InMemoryObjectStorageSnapshot {\n return {\n rows: cloneObjectBuckets(this.rows),\n links: cloneLinkBuckets(this.links),\n uniqueValues: cloneUniqueValues(this.uniqueValues),\n uniqueProperties: new Map(this.uniqueProperties),\n }\n }\n\n restore(snapshot: InMemoryObjectStorageSnapshot): void {\n this.rows.clear()\n for (const [key, bucket] of cloneObjectBuckets(snapshot.rows)) {\n this.rows.set(key, bucket)\n }\n\n this.links.clear()\n for (const [key, bucket] of cloneLinkBuckets(snapshot.links)) {\n this.links.set(key, bucket)\n }\n\n this.uniqueValues.clear()\n for (const [key, holders] of cloneUniqueValues(snapshot.uniqueValues)) {\n this.uniqueValues.set(key, holders)\n }\n\n this.uniqueProperties.clear()\n for (const [key, prepared] of snapshot.uniqueProperties) {\n this.uniqueProperties.set(key, prepared)\n }\n }\n\n /** The object holding a unique value, or undefined when none does. */\n private uniqueHolder(projectId: string, value: UniqueValueRef): string | undefined {\n return this.uniqueValues\n .get(uniquePropertyKey(projectId, value.objectTypeId, value.propertyId))\n ?.get(value.valueKey)\n }\n\n private releaseUniqueValue(projectId: string, value: ExactUniqueValueWrite): void {\n if (this.uniqueHolder(projectId, value) !== value.primaryId) return\n this.uniqueValues\n .get(uniquePropertyKey(projectId, value.objectTypeId, value.propertyId))\n ?.delete(value.valueKey)\n }\n\n private claimUniqueValue(projectId: string, claim: ExactUniqueValueClaim): void {\n this.prepareUniqueProperty(projectId, claim)\n this.holdUniqueValue(projectId, claim)\n }\n\n /**\n * The in-memory store holds every object, so it builds a property's values the first time a\n * claim needs them, where SQL stores refuse until `sixb db migrate` built them. A boot\n * therefore needs no preparation, and a store shared by two ontologies rebuilds what changed.\n */\n private prepareUniqueProperty(projectId: string, claim: ExactUniqueValueClaim): void {\n const key = uniquePropertyKey(projectId, claim.objectTypeId, claim.propertyId)\n const prepared = this.uniqueProperties.get(key)\n if (prepared?.keyKind === claim.keyKind && prepared.keyVersion === claim.keyVersion) return\n\n this.uniqueValues.delete(key)\n const bucket = this.rows.get(objectRowKey(projectId, claim.objectTypeId))\n for (const row of bucket?.values() ?? []) {\n const valueKey = uniqueValueKey(claim.keyKind, row.properties[claim.propertyId])\n if (valueKey === null) continue\n this.holdUniqueValue(projectId, { ...claim, valueKey, primaryId: row.primaryId })\n }\n\n this.uniqueProperties.set(key, {\n projectId,\n objectTypeId: claim.objectTypeId,\n propertyId: claim.propertyId,\n keyKind: claim.keyKind,\n keyVersion: claim.keyVersion,\n preparedAt: new Date().toISOString(),\n })\n }\n\n private holdUniqueValue(projectId: string, value: ExactUniqueValueWrite): void {\n const holder = this.uniqueHolder(projectId, value)\n if (holder !== undefined && holder !== value.primaryId) {\n throw uniqueValueViolation(value, holder, value.primaryId)\n }\n\n const key = uniquePropertyKey(projectId, value.objectTypeId, value.propertyId)\n const holders = this.uniqueValues.get(key) ?? new Map<string, string>()\n this.uniqueValues.set(key, holders)\n holders.set(value.valueKey, value.primaryId)\n }\n\n private getExactObjectRow(\n projectId: string,\n objectTypeId: string,\n primaryId: string\n ): ObjectRow | null {\n const row = this.rows.get(objectRowKey(projectId, objectTypeId))?.get(primaryId)\n return row ? structuredClone(row) : null\n }\n\n private getExactLinkRow(\n projectId: string,\n ref: {\n readonly sourceTypeId: string\n readonly sourceId: string\n readonly linkId: string\n readonly targetTypeId: string\n readonly targetId: string\n }\n ): ObjectLinkRow | null {\n const row = this.links\n .get(sourceLinkBucketKey(projectId, ref.sourceTypeId, ref.sourceId))\n ?.get(linkRowKey(ref.linkId, ref.targetTypeId, ref.targetId))\n return row ? structuredClone(row) : null\n }\n\n private applyExactObject(row: EffectiveObjectSnapshot, projectId: string): void {\n const bucketId = objectRowKey(projectId, row.ref.objectTypeId)\n const bucket = this.rows.get(bucketId) ?? new Map<string, ObjectRow>()\n this.rows.set(bucketId, bucket)\n bucket.set(row.ref.primaryId, {\n projectId,\n objectTypeId: row.ref.objectTypeId,\n primaryId: row.ref.primaryId,\n properties: structuredClone(row.properties) as Record<string, unknown>,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n version: row.version,\n lastCommitId: row.lastCommitId,\n })\n }\n\n private deleteExactObject(projectId: string, objectTypeId: string, primaryId: string): void {\n this.deleteObjectRow(projectId, objectTypeId, primaryId)\n }\n\n private applyExactLink(row: EffectiveLinkSnapshot, projectId: string): void {\n const bucketKey = sourceLinkBucketKey(\n projectId,\n row.ref.source.objectTypeId,\n row.ref.source.primaryId\n )\n const bucket = this.links.get(bucketKey) ?? new Map<string, ObjectLinkRow>()\n this.links.set(bucketKey, bucket)\n bucket.set(linkRowKey(row.ref.linkId, row.ref.target.objectTypeId, row.ref.target.primaryId), {\n projectId,\n sourceTypeId: row.ref.source.objectTypeId,\n sourceId: row.ref.source.primaryId,\n linkId: row.ref.linkId,\n targetTypeId: row.ref.target.objectTypeId,\n targetId: row.ref.target.primaryId,\n properties: row.properties\n ? (structuredClone(row.properties) as Record<string, unknown>)\n : undefined,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n lastCommitId: row.lastCommitId,\n })\n }\n\n private deleteExactLink(row: {\n projectId: string\n sourceTypeId: string\n sourceId: string\n linkId: string\n targetTypeId: string\n targetId: string\n }): void {\n this.deleteLinkRow(\n row.projectId,\n row.sourceTypeId,\n row.sourceId,\n row.linkId,\n row.targetTypeId,\n row.targetId\n )\n }\n\n queryCapabilities(): ObjectQueryCapabilities {\n return IN_MEMORY_OBJECT_QUERY_CAPABILITIES\n }\n\n createSelectedReadScope(params: {\n projectId: string\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n }): ObjectReadStorage {\n return createInMemorySelectedReader(this.readSource(params.projectId), params, () =>\n this.queryCapabilities()\n )\n }\n\n createConditionalReadScope(params: {\n projectId: string\n scope: CompiledConditionalObjectReadScope\n }): ObjectReadStorage {\n return createInMemoryConditionalReader(this.readSource(params.projectId), params.scope, () =>\n this.queryCapabilities()\n )\n }\n\n private readSource(projectId: string): InMemoryReadSource {\n // Keep indexed access live across writes and snapshot restores; do not capture individual buckets.\n return {\n projectId,\n getVector: (ref, profile) => this.vectorReader?.(projectId, ref, profile),\n allObjects: () => projectObjectRows(this.rows, projectId),\n objectsOfType: (objectTypeId) => [\n ...(this.rows.get(objectRowKey(projectId, objectTypeId))?.values() ?? []),\n ],\n getObject: (objectTypeId, primaryId) =>\n this.rows.get(objectRowKey(projectId, objectTypeId))?.get(primaryId),\n outgoingLinks: (objectTypeId, primaryId) =>\n this.links.get(sourceLinkBucketKey(projectId, objectTypeId, primaryId))?.values() ?? [],\n allLinks: () => projectLinkRows(this.links, projectId),\n uniqueHolder: (value) => this.uniqueHolder(projectId, value),\n }\n }\n\n async queryObjects(params: QueryObjectsInput): Promise<QueryObjectsResult> {\n const result = evaluateObjectQuery(params.query, this.readSource(params.projectId))\n return {\n objects: result.entries.map((entry) => ({\n ...entry.row,\n ...(hasVectorProfile(params.query) ? { score: entry.score } : {}),\n })),\n hasMore: result.hasMore,\n nextPageToken: result.nextPageToken,\n ...(params.includeTotal === false ? {} : { total: result.total }),\n }\n }\n\n async countObjects(params: CountObjectsInput): Promise<CountObjectsResult> {\n return {\n count: evaluateObjectQuery(\n stripOuterRowShape(params.query),\n this.readSource(params.projectId)\n ).total,\n }\n }\n\n async existsObjects(params: ExistsObjectsInput): Promise<ExistsObjectsResult> {\n return {\n exists:\n evaluateObjectQuery(stripOuterRowShape(params.query), this.readSource(params.projectId))\n .total > 0,\n }\n }\n\n async facetObjects(params: FacetObjectsInput): Promise<FacetObjectsResult> {\n const result = evaluateObjectQuery(\n stripOuterRowShape(params.query),\n this.readSource(params.projectId)\n )\n return {\n total: result.entries.length,\n facets: buildFacetResults(\n result.entries.map((entry) => entry.row),\n params.facets\n ),\n }\n }\n\n /**\n * Reads return the *live* stored row by reference (the SQL providers detach a copy via JSON\n * round-trip). Callers must treat read results as immutable: mutating a returned row mutates the\n * store in place — including after the transaction that read it has completed, which escapes the\n * transaction guard. Internal call sites (e.g. the EditBatch planner) already copy before\n * mutating; external callers must do the same.\n */\n async getByPrimaryId(params: {\n projectId: string\n objectTypeId: string\n primaryId: string\n }): Promise<ObjectRow | null> {\n const bucket = this.rows.get(objectRowKey(params.projectId, params.objectTypeId))\n if (!bucket) return null\n return bucket.get(params.primaryId) ?? null\n }\n\n async getByUniqueValue(\n params: Parameters<ObjectReadStorage[\"getByUniqueValue\"]>[0]\n ): Promise<ObjectRow | null> {\n const holder = this.uniqueHolder(params.projectId, params)\n if (holder === undefined) return null\n return this.getByPrimaryId({ ...params, primaryId: holder })\n }\n\n async selectsObjectProperties(\n params: Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\n ): Promise<readonly boolean[]> {\n return params.items.map(\n (item) =>\n this.rows.get(objectRowKey(params.projectId, item.objectTypeId))?.has(item.primaryId) ??\n false\n )\n }\n\n async listLinks(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }): Promise<readonly ObjectLinkRow[]> {\n const direction = params.direction ?? \"outgoing\"\n const matches = (row: ObjectLinkRow) => !params.linkId || row.linkId === params.linkId\n const rows: ObjectLinkRow[] = []\n\n if (direction === \"outgoing\" || direction === \"both\") {\n const bucket = this.links.get(\n sourceLinkBucketKey(params.projectId, params.objectTypeId, params.objectId)\n )\n if (bucket) rows.push(...[...bucket.values()].filter(matches))\n }\n\n if (direction === \"incoming\" || direction === \"both\") {\n for (const bucket of this.links.values()) {\n for (const row of bucket.values()) {\n if (\n row.projectId === params.projectId &&\n row.targetTypeId === params.objectTypeId &&\n row.targetId === params.objectId &&\n matches(row)\n ) {\n rows.push(row)\n }\n }\n }\n }\n\n if (direction !== \"both\") return rows\n return [...new Map(rows.map((row) => [fullLinkRowKey(row), row])).values()]\n }\n\n async getByPrimaryIdBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; primaryId: string }[]\n }): Promise<Map<ObjectBatchKey, ObjectRow>> {\n const result = new Map<ObjectBatchKey, ObjectRow>()\n for (const item of params.items) {\n const row = await this.getByPrimaryId({\n projectId: params.projectId,\n objectTypeId: item.objectTypeId,\n primaryId: item.primaryId,\n })\n if (row) {\n result.set(objectBatchKey(item.objectTypeId, item.primaryId), row)\n }\n }\n return result\n }\n\n async listLinksBatch(params: {\n projectId: string\n direction?: LinkDirection\n items: readonly { objectTypeId: string; objectId: string; linkId: string }[]\n }): Promise<Map<LinkBatchKey, ObjectLinkRow[]>> {\n return collectLinksBatch(\n {\n all: () => allLinkRows(this.links),\n outgoing: (item) =>\n this.links\n .get(sourceLinkBucketKey(params.projectId, item.objectTypeId, item.objectId))\n ?.values() ?? [],\n },\n params,\n false\n )\n }\n\n async queryLinks(params: QueryObjectLinksInput): Promise<QueryObjectLinksResult> {\n return queryLinksFrom(params, (input) => this.listLinks(input))\n }\n\n async listIncidentLinksBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; objectId: string }[]\n }): Promise<readonly ObjectLinkRow[]> {\n const deduped = new Map<string, ObjectLinkRow>()\n for (const item of params.items) {\n const rows = await this.listLinks({\n projectId: params.projectId,\n objectTypeId: item.objectTypeId,\n objectId: item.objectId,\n direction: \"both\",\n })\n for (const row of rows) {\n deduped.set(fullLinkRowKey(row), row)\n }\n }\n return [...deduped.values()]\n }\n\n async listByPrimaryIdPage(params: {\n projectId: string\n objectTypeId: string\n afterPrimaryId?: string\n limit: number\n }): Promise<{ objects: readonly ObjectRow[]; nextPrimaryId?: string }> {\n assertReconciliationPageLimit(params.limit)\n const bucket = this.rows.get(objectRowKey(params.projectId, params.objectTypeId))\n const rows = [...(bucket?.values() ?? [])]\n .filter(\n (row) => !params.afterPrimaryId || compareStrings(row.primaryId, params.afterPrimaryId) > 0\n )\n .sort((left, right) => compareStrings(left.primaryId, right.primaryId))\n .slice(0, params.limit + 1)\n const hasMore = rows.length > params.limit\n const objects = rows.slice(0, params.limit).map((row) => structuredClone(row))\n const last = objects.at(-1)\n return {\n objects,\n ...(hasMore && last ? { nextPrimaryId: last.primaryId } : {}),\n }\n }\n\n async list(params: {\n projectId: string\n objectTypeId?: string | readonly string[]\n primaryIdPrefix?: string\n primaryIdSuffix?: string\n updatedAfter?: Date\n updatedBefore?: Date\n createdAfter?: Date\n createdBefore?: Date\n limit?: number\n offset?: number\n orderBy?: \"createdAt\" | \"updatedAt\" | \"primaryId\"\n order?: \"asc\" | \"desc\"\n }): Promise<{ objects: readonly ObjectRow[]; hasMore: boolean; total: number }> {\n let allRows: ObjectRow[] = []\n\n if (params.objectTypeId) {\n const typeIds = Array.isArray(params.objectTypeId)\n ? params.objectTypeId\n : [params.objectTypeId]\n for (const typeId of typeIds) {\n const bucket = this.rows.get(objectRowKey(params.projectId, typeId))\n if (bucket) {\n allRows.push(...bucket.values())\n }\n }\n } else {\n for (const [key, bucket] of this.rows) {\n if (key.startsWith(objectRowProjectPrefix(params.projectId))) {\n allRows.push(...bucket.values())\n }\n }\n }\n\n const {\n primaryIdPrefix,\n primaryIdSuffix,\n updatedAfter,\n updatedBefore,\n createdAfter,\n createdBefore,\n } = params\n if (\n primaryIdPrefix ||\n primaryIdSuffix ||\n updatedAfter ||\n updatedBefore ||\n createdAfter ||\n createdBefore\n ) {\n allRows = allRows.filter(\n (row) =>\n (!primaryIdPrefix || row.primaryId.startsWith(primaryIdPrefix)) &&\n (!primaryIdSuffix || row.primaryId.endsWith(primaryIdSuffix)) &&\n (!updatedAfter || row.updatedAt >= updatedAfter) &&\n (!updatedBefore || row.updatedAt <= updatedBefore) &&\n (!createdAfter || row.createdAt >= createdAfter) &&\n (!createdBefore || row.createdAt <= createdBefore)\n )\n }\n\n const total = allRows.length\n\n const offset = params.offset ?? 0\n const limit = params.limit ?? 50\n if (limit === 0) return { objects: [], hasMore: offset < total, total }\n\n const orderBy = params.orderBy ?? \"updatedAt\"\n const order = params.order ?? \"desc\"\n\n allRows.sort((a, b) => {\n let comparison = 0\n switch (orderBy) {\n case \"primaryId\":\n comparison = a.primaryId.localeCompare(b.primaryId)\n break\n case \"createdAt\":\n comparison = a.createdAt.getTime() - b.createdAt.getTime()\n break\n default:\n comparison = a.updatedAt.getTime() - b.updatedAt.getTime()\n break\n }\n return order === \"desc\" ? -comparison : comparison\n })\n\n const objects = allRows.slice(offset, offset + limit)\n const hasMore = offset + limit < total\n\n return { objects, hasMore, total }\n }\n\n private deleteObjectRow(projectId: string, objectTypeId: string, primaryId: string): void {\n const bucket = this.rows.get(objectRowKey(projectId, objectTypeId))\n bucket?.delete(primaryId)\n }\n\n private deleteLinkRow(\n projectId: string,\n sourceTypeId: string,\n sourceId: string,\n linkId: string,\n targetTypeId: string,\n targetId: string\n ): void {\n const bucket = this.links.get(sourceLinkBucketKey(projectId, sourceTypeId, sourceId))\n bucket?.delete(linkRowKey(linkId, targetTypeId, targetId))\n }\n}\n\nfunction assertReconciliationPageLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object reconciliation page limit must be a positive safe integer.\")\n }\n}\n\nfunction cloneObjectBuckets(\n rows: Map<string, Map<string, ObjectRow>>\n): Map<string, Map<string, ObjectRow>> {\n const clone = new Map<string, Map<string, ObjectRow>>()\n for (const [key, bucket] of rows) {\n clone.set(\n key,\n new Map([...bucket.entries()].map(([primaryId, row]) => [primaryId, structuredClone(row)]))\n )\n }\n return clone\n}\n\nfunction uniquePropertyKey(projectId: string, objectTypeId: string, propertyId: string): string {\n return JSON.stringify([projectId, objectTypeId, propertyId])\n}\n\nfunction cloneUniqueValues(\n values: Map<string, Map<string, string>>\n): Map<string, Map<string, string>> {\n return new Map([...values].map(([key, holders]) => [key, new Map(holders)]))\n}\n\nfunction cloneLinkBuckets(\n links: Map<string, Map<string, ObjectLinkRow>>\n): Map<string, Map<string, ObjectLinkRow>> {\n const clone = new Map<string, Map<string, ObjectLinkRow>>()\n for (const [key, bucket] of links) {\n clone.set(\n key,\n new Map([...bucket.entries()].map(([linkId, row]) => [linkId, structuredClone(row)]))\n )\n }\n return clone\n}\n\nfunction* projectObjectRows(\n buckets: ReadonlyMap<string, ReadonlyMap<string, ObjectRow>>,\n projectId: string\n): Iterable<ObjectRow> {\n const prefix = objectRowProjectPrefix(projectId)\n for (const [key, bucket] of buckets) {\n if (key.startsWith(prefix)) yield* bucket.values()\n }\n}\n\n/** Link buckets are keyed like object buckets, project first. */\nfunction* projectLinkRows(\n buckets: ReadonlyMap<string, ReadonlyMap<string, ObjectLinkRow>>,\n projectId: string\n): Iterable<ObjectLinkRow> {\n const prefix = objectRowProjectPrefix(projectId)\n for (const [key, bucket] of buckets) {\n if (key.startsWith(prefix)) yield* bucket.values()\n }\n}\n\nfunction* allLinkRows(\n buckets: ReadonlyMap<string, ReadonlyMap<string, ObjectLinkRow>>\n): Iterable<ObjectLinkRow> {\n for (const bucket of buckets.values()) yield* bucket.values()\n}\n",
|
|
28
|
+
"import { MaterializationValidationError } from \"../../../materialization/errors\"\nimport type {\n LinkSlotOverride,\n OntologyMaterializationOrigin,\n ProjectionEntityRef,\n} from \"../../../materialization/model\"\nimport type { ExecutionRecord } from \"../../executions/types\"\nimport type { OntologyCommitOriginSelector, OntologyCommitRecord } from \"../commits\"\nimport type {\n MaterializationWorkRecord,\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n} from \"../materializations\"\nimport type { OntologyMaterializationEventDraft, OntologyOutboxRecord } from \"../outbox\"\nimport type {\n OntologySourceRecord,\n StageSourceAssertion,\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n} from \"../sources\"\nimport type { VectorIndexingWork } from \"../vector-indexing\"\nimport type { StoredObjectVector } from \"../vectors\"\nimport type { InMemoryCommitTouches, InMemoryReplacementPlan } from \"./replacement-plans\"\n\nexport interface InMemorySourceRoot {\n readonly root: ProjectionEntityRef\n readonly stagingOrdinal: number\n readonly deleted: boolean\n readonly entityKeys: Set<string>\n active: boolean\n retiredAt: string | null\n}\n\nexport interface InMemorySourceMaterialization extends OntologySourceRecord {\n readonly roots: Map<string, InMemorySourceRoot>\n readonly rowsByEntity: Map<string, StageSourceAssertion>\n readonly rootOrdinals: Map<string, number>\n readonly ordinalRoots: Map<number, string>\n}\n\nexport interface InMemoryStoredObjectOverride extends StoredObjectOverride {\n readonly projectId: string\n}\n\nexport interface InMemoryStoredLinkOverride extends StoredLinkOverride {\n readonly projectId: string\n}\n\nexport interface InMemoryStoredLinkSlotOverride extends Omit<StoredLinkSlotOverride, \"value\"> {\n readonly projectId: string\n readonly value: LinkSlotOverride\n}\n\nexport interface InMemoryOntologyState {\n readonly vectorIndexing: Map<\n string,\n VectorIndexingWork & { projectId: string; dispatchAt: string }\n >\n readonly vectors: Map<string, Map<string, StoredObjectVector>>\n readonly commitsById: Map<string, OntologyCommitRecord>\n readonly commitIdByIdempotency: Map<string, string>\n readonly commitIdByOrigin: Map<string, string>\n readonly sourceMaterializations: Map<string, InMemorySourceMaterialization>\n readonly activeSourceHeads: Map<string, string>\n readonly activeSourceRoots: Map<string, Map<string, string>>\n readonly activeSourceRows: Map<string, Map<string, StoredSourceAssertion>>\n readonly activeSourceLinkScopes: Map<string, Map<string, StoredSourceLinkAssertion>>\n readonly objectOverrides: Map<string, InMemoryStoredObjectOverride>\n readonly linkOverrides: Map<string, InMemoryStoredLinkOverride>\n readonly linkSlotOverrides: Map<string, InMemoryStoredLinkSlotOverride>\n readonly outbox: Map<string, InMemoryOutboxRow>\n readonly replacementPlans: Map<string, InMemoryReplacementPlan>\n /** What each commit touched among the inputs plans read, keyed by its `commitsById` ordinal. */\n readonly commitTouches: Map<number, InMemoryCommitTouches>\n}\n\n/** Reads one execution of the same storage, the record an ontology commit references. */\nexport type InMemoryExecutionReader = (\n projectId: string,\n executionId: string\n) => Promise<ExecutionRecord | null>\n\n/** An outbox row as stored: the event's draft, rebuilt from its commit when claimed. */\nexport interface InMemoryOutboxRow extends Omit<OntologyOutboxRecord, \"envelope\"> {\n readonly projectId: string\n readonly id: string\n readonly commitId: string\n readonly commitOrdinal: number\n readonly event: OntologyMaterializationEventDraft\n}\n\n/** @internal Test-only failure injection for the in-memory ontology provider. */\nexport interface InMemoryOntologyStorageTestHooks {\n readonly beforeRead?: (boundary: string) => void\n readonly beforeWrite?: (boundary: string, ordinal: number) => void\n readonly observeBuffer?: (boundary: string, rows: number) => void\n readonly observeWork?: (records: readonly MaterializationWorkRecord[]) => void\n}\n\nexport function createInMemoryOntologyState(): InMemoryOntologyState {\n return {\n vectors: new Map(),\n vectorIndexing: new Map(),\n commitsById: new Map(),\n commitIdByIdempotency: new Map(),\n commitIdByOrigin: new Map(),\n sourceMaterializations: new Map(),\n activeSourceHeads: new Map(),\n activeSourceRoots: new Map(),\n activeSourceRows: new Map(),\n activeSourceLinkScopes: new Map(),\n objectOverrides: new Map(),\n linkOverrides: new Map(),\n linkSlotOverrides: new Map(),\n outbox: new Map(),\n replacementPlans: new Map(),\n commitTouches: new Map(),\n }\n}\n\nexport function projectEntityKey(projectId: string, entityKey: string): string {\n return JSON.stringify([projectId, entityKey])\n}\n\nexport function sourceMaterializationKey(\n projectId: string,\n sourceId: string,\n materializationId: string\n): string {\n return JSON.stringify([projectId, sourceId, materializationId])\n}\n\nexport function sourceMaterializationRecord(\n materialization: InMemorySourceMaterialization\n): OntologySourceRecord {\n const {\n rowsByEntity: _rows,\n rootOrdinals: _roots,\n ordinalRoots: _ordinals,\n roots: _sourceRoots,\n ...record\n } = materialization\n return structuredClone(record)\n}\n\nexport function commitKey(projectId: string, commitId: string): string {\n return JSON.stringify([projectId, commitId])\n}\n\nexport function idempotencyKey(projectId: string, key: string): string {\n return JSON.stringify([projectId, key])\n}\n\nexport function ontologyCommitOriginSelector(\n origin: OntologyMaterializationOrigin\n): OntologyCommitOriginSelector | null {\n if (origin.kind === \"action\") return { kind: \"action\", actionRunId: origin.runId }\n if (origin.kind === \"projection\") {\n return { kind: \"projection\", projectionRunId: origin.projectionRunId }\n }\n if (origin.kind === \"telemetry\" && origin.source.kind === \"projection\") {\n return {\n kind: \"telemetry\",\n projectionRunId: origin.source.projectionRunId,\n batchOrdinal: origin.source.batchOrdinal,\n }\n }\n return null\n}\n\nexport function commitOriginKey(projectId: string, origin: OntologyCommitOriginSelector): string {\n switch (origin.kind) {\n case \"action\":\n return JSON.stringify([projectId, origin.kind, origin.actionRunId])\n case \"projection\":\n return JSON.stringify([projectId, origin.kind, origin.projectionRunId])\n case \"telemetry\":\n return JSON.stringify([projectId, origin.kind, origin.projectionRunId, origin.batchOrdinal])\n }\n}\n\nexport function outboxKey(projectId: string, eventId: string): string {\n return JSON.stringify([projectId, eventId])\n}\n\nexport function cloneOntologyState(state: InMemoryOntologyState): InMemoryOntologyState {\n return structuredClone(state)\n}\n\nexport function restoreOntologyState(\n target: InMemoryOntologyState,\n snapshot: InMemoryOntologyState\n): void {\n for (const key of Object.keys(target) as (keyof InMemoryOntologyState)[]) {\n const targetMap = target[key] as Map<unknown, unknown>\n const sourceMap = structuredClone(snapshot[key]) as Map<unknown, unknown>\n targetMap.clear()\n for (const [entryKey, value] of sourceMap) targetMap.set(entryKey, value)\n }\n}\n\n/** Insert `value` into a sorted, size-bounded accumulator, dropping the largest entry past `limit`. */\nexport function insertBounded<T>(\n values: T[],\n value: T,\n limit: number,\n compare: (left: T, right: T) => number\n): void {\n if (limit <= 0) return\n if (values.length >= limit && compare(value, values[values.length - 1]!) >= 0) return\n let low = 0\n let high = values.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if (compare(value, values[middle]!) < 0) high = middle\n else low = middle + 1\n }\n values.splice(low, 0, value)\n if (values.length > limit) values.pop()\n}\n\nexport function assertNonblank(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new MaterializationValidationError(`${label} must be nonblank.`)\n }\n}\n\nexport function assertTimestamp(value: string, label: string): number {\n const milliseconds = Date.parse(value)\n if (!Number.isFinite(milliseconds) || new Date(milliseconds).toISOString() !== value) {\n throw new MaterializationValidationError(`${label} must be a canonical UTC timestamp.`)\n }\n return milliseconds\n}\n",
|
|
29
|
+
"import type {\n GetOntologyCommitByIdempotencyKeyInput,\n GetOntologyCommitByIdInput,\n GetOntologyCommitByOriginInput,\n ListOntologyCommitsInput,\n ListOntologyCommitsResult,\n OntologyCommitRecord,\n OntologyCommitRunSelector,\n OntologyCommitStorage,\n} from \"../commits\"\nimport {\n commitKey,\n commitOriginKey,\n type InMemoryOntologyState,\n idempotencyKey,\n} from \"./shared-state\"\n\nexport class InMemoryOntologyCommitStorage implements OntologyCommitStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n ) {}\n\n async getByIdempotencyKey(\n input: GetOntologyCommitByIdempotencyKeyInput\n ): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n const id = this.state.commitIdByIdempotency.get(\n idempotencyKey(input.projectId, input.idempotencyKey)\n )\n if (!id) return null\n return structuredClone(this.state.commitsById.get(commitKey(input.projectId, id)) ?? null)\n })\n }\n\n async getById(input: GetOntologyCommitByIdInput): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() =>\n structuredClone(this.state.commitsById.get(commitKey(input.projectId, input.id)) ?? null)\n )\n }\n\n async getByOrigin(input: GetOntologyCommitByOriginInput): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n assertOriginLookup(input)\n const id = this.state.commitIdByOrigin.get(commitOriginKey(input.projectId, input.origin))\n if (!id) return null\n return structuredClone(this.state.commitsById.get(commitKey(input.projectId, id)) ?? null)\n })\n }\n\n async list(input: ListOntologyCommitsInput): Promise<ListOntologyCommitsResult> {\n return this.runRootOperation(() => {\n if (input.projectId.trim().length === 0 || input.run?.id.trim().length === 0) {\n throw new Error(\"[Sixb] Ontology commit project and run ids must be nonblank.\")\n }\n const offset = input.offset ?? 0\n const limit = input.limit ?? this.state.commitsById.size\n if (\n !Number.isSafeInteger(offset) ||\n offset < 0 ||\n !Number.isSafeInteger(limit) ||\n limit < 0\n ) {\n throw new Error(\n \"[Sixb] Ontology commit list limit and offset must be nonnegative integers.\"\n )\n }\n const direction = input.order === \"desc\" ? -1 : 1\n const commits = [...this.state.commitsById.values()]\n .filter((commit) => commit.projectId === input.projectId)\n .filter((commit) => (input.run ? commitMatchesRun(commit, input.run) : true))\n .sort((left, right) => {\n if (input.run?.kind === \"projection\") {\n const byOrdinal = projectionRunOrdinal(left) - projectionRunOrdinal(right)\n if (byOrdinal !== 0) return byOrdinal * direction\n }\n const byTime = left.committedAt.localeCompare(right.committedAt)\n if (byTime !== 0) return byTime * direction\n return left.id.localeCompare(right.id) * direction\n })\n const total = commits.length\n const page = commits.slice(offset, offset + limit).map((commit) => structuredClone(commit))\n return { commits: page, total, hasMore: offset + page.length < total }\n })\n }\n}\n\nfunction assertOriginLookup(input: GetOntologyCommitByOriginInput): void {\n if (input.projectId.trim().length === 0) {\n throw new Error(\"[Sixb] Ontology commit project id must be nonblank.\")\n }\n const runId =\n input.origin.kind === \"action\" ? input.origin.actionRunId : input.origin.projectionRunId\n if (runId.trim().length === 0) {\n throw new Error(\"[Sixb] Ontology commit origin run id must be nonblank.\")\n }\n if (\n input.origin.kind === \"telemetry\" &&\n (!Number.isSafeInteger(input.origin.batchOrdinal) || input.origin.batchOrdinal < 0)\n ) {\n throw new Error(\"[Sixb] Ontology telemetry commit batch ordinal must be nonnegative.\")\n }\n}\n\nfunction commitMatchesRun(commit: OntologyCommitRecord, run: OntologyCommitRunSelector): boolean {\n if (run.kind === \"action\") {\n return commit.origin.kind === \"action\" && commit.origin.runId === run.id\n }\n if (commit.origin.kind === \"projection\") return commit.origin.projectionRunId === run.id\n return (\n commit.origin.kind === \"telemetry\" &&\n commit.origin.source.kind === \"projection\" &&\n commit.origin.source.projectionRunId === run.id\n )\n}\n\nfunction projectionRunOrdinal(commit: OntologyCommitRecord): number {\n if (commit.origin.kind === \"telemetry\" && commit.origin.source.kind === \"projection\") {\n return commit.origin.source.batchOrdinal\n }\n return 0\n}\n",
|
|
30
|
+
"import type { TelemetrySeriesRef } from \"../../materialization/model\"\nimport type { StoredTelemetryPoint } from \"../ontology/materializations\"\nimport type { TimeseriesHistoryBatchInput, TimeseriesPoint, TimeseriesStorage } from \"./types\"\n\nfunction pointKey(\n projectId: string,\n objectTypeId: string,\n objectId: string,\n propertyId: string\n): string {\n return JSON.stringify([projectId, objectTypeId, objectId, propertyId])\n}\n\nexport class InMemoryTimeseriesStorage implements TimeseriesStorage {\n // A telemetry point is uniquely identified by (series, at): one value per\n // instant per series. Re-applying the same instant is a last-write-wins\n // upsert, which makes telemetry writes idempotent under replay for free.\n private readonly pointsByKey = new Map<string, Map<number, TimeseriesPoint>>()\n\n constructor() {\n materializerAdapters.set(this, {\n getExactPoint: (projectId, series, at) => this.getExactPoint(projectId, series, at),\n listLatestForObject: (projectId, objectTypeId, objectId) =>\n this.listLatestForObject(projectId, objectTypeId, objectId),\n applyExactPoint: (projectId, point) => this.applyExactPoint(projectId, point),\n })\n }\n\n snapshot(): InMemoryTimeseriesStorageSnapshot {\n return {\n pointsByKey: structuredClone(this.pointsByKey),\n }\n }\n\n restore(snapshot: InMemoryTimeseriesStorageSnapshot): void {\n this.pointsByKey.clear()\n for (const [key, points] of structuredClone(snapshot.pointsByKey)) {\n this.pointsByKey.set(key, points)\n }\n }\n\n private getExactPoint(\n projectId: string,\n series: TelemetrySeriesRef,\n at: string\n ): TimeseriesPoint | null {\n const point =\n this.pointsByKey\n .get(\n pointKey(\n projectId,\n series.object.objectTypeId,\n series.object.primaryId,\n series.propertyId\n )\n )\n ?.get(new Date(at).getTime()) ?? null\n return point ? clonePoint(point) : null\n }\n\n private listLatestForObject(\n projectId: string,\n objectTypeId: string,\n objectId: string\n ): TimeseriesPoint[] {\n const latest: TimeseriesPoint[] = []\n for (const series of this.pointsByKey.values()) {\n let point: TimeseriesPoint | null = null\n for (const candidate of series.values()) {\n if (\n candidate.projectId !== projectId ||\n candidate.objectTypeId !== objectTypeId ||\n candidate.objectId !== objectId\n ) {\n continue\n }\n if (!point || candidate.at > point.at) point = candidate\n }\n if (point) latest.push(clonePoint(point))\n }\n return latest\n }\n\n private applyExactPoint(projectId: string, point: StoredTelemetryPoint): void {\n const key = pointKey(\n projectId,\n point.series.object.objectTypeId,\n point.series.object.primaryId,\n point.series.propertyId\n )\n const series = this.pointsByKey.get(key) ?? new Map<number, TimeseriesPoint>()\n series.set(new Date(point.at).getTime(), {\n projectId,\n objectTypeId: point.series.object.objectTypeId,\n objectId: point.series.object.primaryId,\n propertyId: point.series.propertyId,\n value: structuredClone(point.value),\n ...(point.unit !== undefined ? { unit: point.unit } : {}),\n at: new Date(point.at),\n lastCommitId: point.lastCommitId,\n })\n this.pointsByKey.set(key, series)\n }\n\n async getHistory(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n propertyId: string\n from?: Date\n to?: Date\n limit?: number\n order?: \"asc\" | \"desc\"\n }): Promise<readonly TimeseriesPoint[]> {\n const key = pointKey(params.projectId, params.objectTypeId, params.objectId, params.propertyId)\n const { from, to } = params\n let points = [...(this.pointsByKey.get(key)?.values() ?? [])]\n if (from || to) {\n points = points.filter((point) => (!from || point.at >= from) && (!to || point.at <= to))\n }\n\n points.sort((a, b) => a.at.getTime() - b.at.getTime())\n if (params.order === \"desc\") {\n points.reverse()\n }\n\n if (params.limit !== undefined) {\n points = points.slice(0, Math.max(0, params.limit))\n }\n\n return points.map(clonePoint)\n }\n\n async getHistoryBatch(input: TimeseriesHistoryBatchInput): Promise<\n readonly {\n objectTypeId: string\n objectId: string\n propertyId: string\n points: readonly TimeseriesPoint[]\n }[]\n > {\n // Start every read before yielding so one batch observes one in-memory snapshot. The SQL\n // providers get the same guarantee from their single query.\n return Promise.all(\n input.series.map(async (series) => ({\n ...series,\n points: await this.getHistory({\n projectId: input.projectId,\n objectTypeId: series.objectTypeId,\n objectId: series.objectId,\n propertyId: series.propertyId,\n from: input.from,\n to: input.to,\n limit: input.limitPerSeries,\n order: input.order,\n }),\n }))\n )\n }\n\n async getLatest(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n propertyId: string\n }): Promise<TimeseriesPoint | null> {\n const series = this.pointsByKey.get(\n pointKey(params.projectId, params.objectTypeId, params.objectId, params.propertyId)\n )\n if (!series || series.size === 0) {\n return null\n }\n\n let latest: TimeseriesPoint | null = null\n for (const point of series.values()) {\n if (!latest || point.at.getTime() > latest.at.getTime()) {\n latest = point\n }\n }\n return latest ? clonePoint(latest) : null\n }\n}\n\ninterface InMemoryTimeseriesMaterializerAdapter {\n getExactPoint(projectId: string, series: TelemetrySeriesRef, at: string): TimeseriesPoint | null\n listLatestForObject(projectId: string, objectTypeId: string, objectId: string): TimeseriesPoint[]\n applyExactPoint(projectId: string, point: StoredTelemetryPoint): void\n}\n\nconst materializerAdapters = new WeakMap<\n InMemoryTimeseriesStorage,\n InMemoryTimeseriesMaterializerAdapter\n>()\n\n/** @internal Exact access for the in-memory ontology provider; not exported from package barrels. */\nexport function getInMemoryTimeseriesMaterializerAdapter(\n storage: InMemoryTimeseriesStorage\n): InMemoryTimeseriesMaterializerAdapter {\n const adapter = materializerAdapters.get(storage)\n if (!adapter) throw new Error(\"[Sixb] In-memory timeseries materializer adapter is unavailable.\")\n return adapter\n}\n\nfunction clonePoint(point: TimeseriesPoint): TimeseriesPoint {\n return {\n ...structuredClone(point),\n value: structuredClone(point.value),\n at: new Date(point.at),\n }\n}\n\nexport interface InMemoryTimeseriesStorageSnapshot {\n readonly pointsByKey: Map<string, Map<number, TimeseriesPoint>>\n}\n",
|
|
31
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type {\n EffectiveLinkSnapshot,\n EffectiveObjectSnapshot,\n OntologyLinkRef,\n} from \"../../../materialization/model\"\nimport type { ObjectLinkRow, ObjectRow } from \"../../objects/types\"\nimport type { TimeseriesPoint } from \"../../timeseries/types\"\nimport type {\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n StoredTelemetryPoint,\n} from \"../materializations\"\nimport type {\n StageSourceAssertion,\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n StoredSourceObjectAssertion,\n} from \"../sources\"\nimport type {\n InMemoryOntologyState,\n InMemorySourceMaterialization,\n InMemoryStoredLinkOverride,\n InMemoryStoredLinkSlotOverride,\n InMemoryStoredObjectOverride,\n} from \"./shared-state\"\nimport { projectEntityKey, sourceMaterializationKey } from \"./shared-state\"\n\nexport function publicObjectOverride(\n value: InMemoryStoredObjectOverride | undefined\n): StoredObjectOverride | null {\n if (!value) return null\n const { projectId: _, ...stored } = value\n return stored\n}\n\nexport function publicLinkOverride(\n value: InMemoryStoredLinkOverride | undefined\n): StoredLinkOverride | null {\n if (!value) return null\n const { projectId: _, ...stored } = value\n return stored\n}\n\nexport function publicLinkSlotOverride(\n value: InMemoryStoredLinkSlotOverride | undefined\n): StoredLinkSlotOverride | null {\n if (!value) return null\n const { projectId: _, ...stored } = value\n return stored\n}\n\nexport function uniqueBy<T>(values: readonly T[], keyOf: (value: T) => string): T[] {\n return [...new Map(values.map((value) => [keyOf(value), structuredClone(value)])).values()]\n}\n\nexport function objectSnapshot(row: ObjectRow): EffectiveObjectSnapshot {\n if (!row.lastCommitId)\n throw new MaterializationConflictError(\n \"effective-state\",\n `Effective object ${row.objectTypeId}:${row.primaryId} lacks materializer provenance.`\n )\n return {\n ref: { objectTypeId: row.objectTypeId, primaryId: row.primaryId },\n properties: structuredClone(row.properties) as EffectiveObjectSnapshot[\"properties\"],\n version: row.version,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n lastCommitId: row.lastCommitId,\n }\n}\n\nexport function linkSnapshot(row: ObjectLinkRow): EffectiveLinkSnapshot {\n if (!row.lastCommitId)\n throw new MaterializationConflictError(\n \"effective-state\",\n `Effective link lacks materializer provenance.`\n )\n return {\n ref: linkRef(row),\n ...(row.properties\n ? { properties: structuredClone(row.properties) as EffectiveLinkSnapshot[\"properties\"] }\n : {}),\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n lastCommitId: row.lastCommitId,\n }\n}\n\nexport function linkRef(row: ObjectLinkRow): OntologyLinkRef {\n return {\n source: { objectTypeId: row.sourceTypeId, primaryId: row.sourceId },\n linkId: row.linkId,\n target: { objectTypeId: row.targetTypeId, primaryId: row.targetId },\n }\n}\n\nexport function storedPoint(point: TimeseriesPoint): StoredTelemetryPoint {\n if (!point.lastCommitId)\n throw new MaterializationConflictError(\n \"timeseries-point\",\n \"Telemetry point lacks materializer provenance.\"\n )\n return {\n series: {\n object: { objectTypeId: point.objectTypeId, primaryId: point.objectId },\n propertyId: point.propertyId,\n },\n value: structuredClone(point.value) as StoredTelemetryPoint[\"value\"],\n ...(point.unit !== undefined ? { unit: point.unit } : {}),\n at: point.at.toISOString(),\n lastCommitId: point.lastCommitId,\n }\n}\n\nexport function findActiveSourceMaterialization(\n state: InMemoryOntologyState,\n projectId: string,\n sourceId: string\n): InMemorySourceMaterialization | undefined {\n const id = state.activeSourceHeads.get(projectEntityKey(projectId, sourceId))\n return id\n ? state.sourceMaterializations.get(sourceMaterializationKey(projectId, sourceId, id))\n : undefined\n}\n\nexport function storedSource(\n sourceId: string,\n materializationId: string,\n row: StageSourceAssertion\n): StoredSourceAssertion {\n return {\n source: { projectionId: sourceId },\n materializationId,\n root: structuredClone(row.root),\n assertion: structuredClone(row.assertion),\n stagingOrdinal: row.stagingOrdinal,\n } as StoredSourceAssertion\n}\n\nexport function storedSourceObject(\n sourceId: string,\n materializationId: string | undefined,\n row: StageSourceAssertion | undefined\n): StoredSourceObjectAssertion | null {\n if (!materializationId || !row || row.assertion.kind !== \"object\") return null\n return storedSource(sourceId, materializationId, row) as StoredSourceObjectAssertion\n}\n\nexport function storedSourceLink(\n sourceId: string,\n materializationId: string | undefined,\n row: StageSourceAssertion | undefined\n): StoredSourceLinkAssertion | null {\n if (!materializationId || !row || row.assertion.kind !== \"link\") return null\n return storedSource(sourceId, materializationId, row) as StoredSourceLinkAssertion\n}\n",
|
|
32
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type {\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n} from \"../materializations\"\n\nexport * from \"../provider-work\"\n\nexport function assertLastCommit(\n value: StoredObjectOverride | StoredLinkOverride | StoredLinkSlotOverride | undefined,\n expected: string | null,\n label: string\n): void {\n if ((value?.lastCommitId ?? null) !== expected) {\n throw new MaterializationConflictError(\"effective-state\", `Expected ${label} changed.`)\n }\n}\n",
|
|
33
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport { assertPinnedDatasetWatermark } from \"../../../materialization/dataset-watermark\"\nimport { MaterializationConflictError } from \"../../../materialization/errors\"\nimport { createEventId } from \"../../../materialization/identity\"\nimport type {\n EffectiveChangeCounts,\n OntologyObjectRef,\n PinnedDatasetVersion,\n TelemetryCommitResult,\n} from \"../../../materialization/model\"\nimport { linkRefKey, linkRefSortKey, objectRefKey } from \"../../../materialization/refs\"\nimport {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport type { MaterializationCardinalityOccupantWorkRecord } from \"../materializations\"\nimport type { SessionState } from \"./materializations\"\nimport { findActiveSourceMaterialization, linkRef } from \"./materializations-state\"\nimport { compareEventWork, invalidCorrelation } from \"./materializations-work\"\nimport { type InMemoryOntologyState, outboxKey, sourceMaterializationKey } from \"./shared-state\"\n\nexport function assertFinalizationCorrelations(\n session: SessionState,\n finalization: import(\"../materializations\").MaterializationPlanFinalization,\n state: InMemoryOntologyState,\n objects: InMemoryObjectStorage\n): void {\n const { commit } = session.header\n const { result, sourceActivations } = finalization\n if (\n result.commitId !== commit.id ||\n result.kind !== commit.intent.kind ||\n result.committedAt !== commit.committedAt ||\n result.created !== true ||\n !Number.isSafeInteger(result.eventCount) ||\n result.eventCount < 0 ||\n result.eventCount !== session.outboxWrites.size\n ) {\n invalidCorrelation(\"Materialization result does not correlate with its commit intent.\")\n }\n for (let ordinal = 0; ordinal < result.eventCount; ordinal += 1) {\n if (!session.outboxWrites.has(ordinal)) {\n invalidCorrelation(\"Outbox event ordinals must be contiguous from zero.\")\n }\n }\n\n if (commit.intent.kind === \"edit\") {\n if (result.kind !== \"edit\" || result.outcomes.length !== commit.intent.operationCount) {\n invalidCorrelation(\"Edit result does not correlate with its operation count.\")\n }\n if (sourceActivations.length !== 0) {\n invalidCorrelation(\"Edit materialization cannot activate a source materialization.\")\n }\n } else if (commit.intent.kind === \"projection\") {\n if (result.kind !== \"projection\" || sourceActivations.length !== 1) {\n invalidCorrelation(\"Projection result requires exactly one correlated source activation.\")\n }\n } else if (result.kind !== \"telemetry\" || sourceActivations.length !== 0) {\n invalidCorrelation(\"Telemetry result does not correlate with its point intent.\")\n }\n\n for (const activation of sourceActivations) {\n assertSourceActivationCorrelation(activation, session, state)\n }\n if (sourceActivations[0]) {\n assertPlanCoverage(session, sourceActivations[0])\n }\n assertFinalizedWork(session, state, objects)\n if (commit.intent.kind === \"projection\") {\n if (result.kind !== \"projection\" || !projectionCountsCorrelate(session, result.counts)) {\n invalidCorrelation(\"Projection result counts do not correlate with finalized work.\")\n }\n } else if (\n commit.intent.kind === \"telemetry\" &&\n (result.kind !== \"telemetry\" ||\n !telemetryCountsCorrelate(session, commit.intent.pointCount, result))\n ) {\n invalidCorrelation(\"Telemetry result counts do not correlate with finalized work.\")\n }\n}\n\nfunction projectionCountsCorrelate(session: SessionState, actual: EffectiveChangeCounts): boolean {\n const expected = deriveExpectedProjectionCounts(session)\n if (expected === null) return false\n\n return effectiveChangeCountsMatch(actual, expected)\n}\n\ninterface ClassifiedProjectionCounts {\n objects: number\n links: number\n}\n\ninterface AppliedProjectionChangeCounts {\n objectsCreated: number\n objectsUpdated: number\n objectsDeleted: number\n linksCreated: number\n linksUpdated: number\n linksDeleted: number\n}\n\nconst effectiveChangeCountKeys = [\n \"objectsCreated\",\n \"objectsUpdated\",\n \"objectsDeleted\",\n \"objectsUnchanged\",\n \"linksCreated\",\n \"linksUpdated\",\n \"linksDeleted\",\n \"linksUnchanged\",\n] as const satisfies readonly (keyof EffectiveChangeCounts)[]\n\nfunction deriveExpectedProjectionCounts(session: SessionState): EffectiveChangeCounts | null {\n const classified = countClassifiedProjectionEntities(session)\n const applied = countAppliedProjectionChanges(session)\n const objectsUnchanged = remainingClassifiedCount(\n classified.objects,\n applied.objectsCreated,\n applied.objectsUpdated,\n applied.objectsDeleted\n )\n const linksUnchanged = remainingClassifiedCount(\n classified.links,\n applied.linksCreated,\n applied.linksUpdated,\n applied.linksDeleted\n )\n\n if (objectsUnchanged < 0 || linksUnchanged < 0) return null\n\n return { ...applied, objectsUnchanged, linksUnchanged }\n}\n\nfunction countClassifiedProjectionEntities(session: SessionState): ClassifiedProjectionCounts {\n const counts = { objects: 0, links: 0 }\n\n for (const record of session.work.values()) {\n if (record.kind !== \"classification\") continue\n\n if (record.entityKind === \"object\") counts.objects += 1\n if (record.entityKind === \"link\") counts.links += 1\n }\n\n return counts\n}\n\nfunction countAppliedProjectionChanges(session: SessionState): AppliedProjectionChangeCounts {\n const counts: AppliedProjectionChangeCounts = {\n objectsCreated: 0,\n objectsUpdated: 0,\n objectsDeleted: 0,\n linksCreated: 0,\n linksUpdated: 0,\n linksDeleted: 0,\n }\n\n for (const work of session.applyWork) {\n const { item } = work\n\n switch (item.kind) {\n case \"object-upsert\":\n if (item.value.expected.exists) counts.objectsUpdated += 1\n else counts.objectsCreated += 1\n break\n case \"object-delete\":\n counts.objectsDeleted += 1\n break\n case \"link-upsert\":\n if (item.value.expected.exists) counts.linksUpdated += 1\n else counts.linksCreated += 1\n break\n case \"link-delete\":\n counts.linksDeleted += 1\n break\n }\n }\n\n return counts\n}\n\nfunction remainingClassifiedCount(\n classified: number,\n created: number,\n updated: number,\n deleted: number\n): number {\n return classified - created - updated - deleted\n}\n\nfunction effectiveChangeCountsMatch(\n actual: EffectiveChangeCounts,\n expected: EffectiveChangeCounts\n): boolean {\n return effectiveChangeCountKeys.every((key) => {\n const count = actual[key]\n return Number.isSafeInteger(count) && count >= 0 && count === expected[key]\n })\n}\n\nfunction telemetryCountsCorrelate(\n session: SessionState,\n pointCount: number,\n actual: TelemetryCommitResult\n): boolean {\n let pointsCreated = 0\n let pointsUpdated = 0\n let latestObjectsChanged = 0\n for (const work of session.applyWork) {\n if (work.item.kind === \"point-upsert\") {\n if (work.item.value.expected.lastCommitId === null) pointsCreated += 1\n else pointsUpdated += 1\n } else if (work.item.kind === \"object-upsert\") {\n latestObjectsChanged += 1\n }\n }\n const expected = {\n pointsCreated,\n pointsUpdated,\n pointsUnchanged: pointCount - pointsCreated - pointsUpdated,\n latestObjectsChanged,\n }\n return (\n expected.pointsUnchanged >= 0 &&\n (Object.keys(expected) as (keyof typeof expected)[]).every(\n (key) =>\n Number.isSafeInteger(actual[key]) && actual[key] >= 0 && actual[key] === expected[key]\n )\n )\n}\n\nfunction assertSourceActivationCorrelation(\n activation: import(\"../materializations\").SourceActivationWrite,\n session: SessionState,\n state: InMemoryOntologyState\n): void {\n const { header } = session\n const { commit } = header\n if (\n commit.intent.kind !== \"projection\" ||\n commit.origin.kind !== \"projection\" ||\n activation.source.projectionId !== commit.intent.source.projectionId ||\n activation.source.projectionId !== commit.origin.projectionId ||\n activation.execution.projectionRunId !== commit.origin.projectionRunId ||\n activation.protocol !== \"replacement\" ||\n stableJsonStringify(activation.datasetVersion) !==\n stableJsonStringify(commit.intent.datasetVersion) ||\n activation.projectionRevision !== commit.projectionRevision ||\n activation.ownershipHash !== commit.ownershipHash ||\n activation.ontologyRevision !== commit.ontologyRevision ||\n activation.lastCommitId !== commit.id ||\n activation.updatedAt !== commit.committedAt ||\n !header.expected.sources.some(\n (expected) => stableJsonStringify(expected) === stableJsonStringify(activation.expected)\n )\n ) {\n invalidCorrelation(\"Source activation does not correlate with its projection commit.\")\n }\n const candidate = state.sourceMaterializations.get(\n sourceMaterializationKey(\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId\n )\n )\n if (!candidate || candidate.status !== \"ready\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source activation candidate is missing or is not ready.\"\n )\n }\n if (\n candidate.projectionRunId !== activation.execution.projectionRunId ||\n candidate.executionToken !== activation.execution.executionToken ||\n candidate.projectionKind !== activation.projectionKind ||\n candidate.protocol !== activation.protocol ||\n stableJsonStringify(candidate.datasetVersion) !==\n stableJsonStringify(activation.datasetVersion) ||\n candidate.projectionRevision !== activation.projectionRevision ||\n candidate.ownershipHash !== activation.ownershipHash ||\n candidate.ontologyRevision !== activation.ontologyRevision\n ) {\n invalidCorrelation(\"Source activation does not match its ready candidate identity.\")\n }\n if (candidate.readyAt === null) {\n invalidCorrelation(\"Source activation candidate has no ready timestamp.\")\n }\n assertTimestampNotBefore(\n activation.updatedAt,\n candidate.readyAt,\n \"Source activation cannot precede candidate readiness.\"\n )\n const previous = findActiveSourceMaterialization(\n state,\n commit.projectId,\n activation.source.projectionId\n )\n if (previous) {\n assertSourceDatasetWatermark(previous.datasetVersion, activation.datasetVersion)\n assertTimestampNotBefore(\n activation.updatedAt,\n previous.updatedAt,\n \"Source activation cannot precede the active materialization update.\"\n )\n }\n}\n\nfunction assertSourceDatasetWatermark(\n active: PinnedDatasetVersion,\n next: PinnedDatasetVersion\n): void {\n assertPinnedDatasetWatermark(active, next, \"Source activation\")\n}\n\nfunction assertFinalizedWork(\n session: SessionState,\n state: InMemoryOntologyState,\n objects: InMemoryObjectStorage\n): void {\n if (!session.applied) {\n invalidCorrelation(\"A materialization plan must apply before it finalizes.\")\n }\n assertFinalCardinality(session.cardinalityWork, session.header.commit.projectId, objects)\n if (session.header.commit.intent.kind === \"telemetry\") {\n const pointKeys = classificationKeys(session, \"point\")\n if (pointKeys.length !== session.header.commit.intent.pointCount) {\n invalidCorrelation(\n \"Telemetry point classification coverage does not match the commit intent.\"\n )\n }\n }\n\n const expectedEvents = [...session.eventWork].sort(compareEventWork)\n if (session.outboxWrites.size !== expectedEvents.length) {\n invalidCorrelation(\"Materialization event work was not fully written to the outbox.\")\n }\n for (let ordinal = 0; ordinal < expectedEvents.length; ordinal += 1) {\n const expected = expectedEvents[ordinal]\n const actual = session.outboxWrites.get(ordinal)\n if (!expected || !actual) {\n invalidCorrelation(\"Materialization event work was not fully written to the outbox.\")\n }\n if (\n actual.commitOrdinal !== ordinal ||\n actual.id !==\n createEventId(session.header.commit.projectId, session.header.commit.id, ordinal) ||\n stableJsonStringify(actual.event) !== stableJsonStringify(expected.draft)\n ) {\n invalidCorrelation(\"Materialization outbox event does not match its staged event work.\")\n }\n const persisted = state.outbox.get(outboxKey(session.header.commit.projectId, actual.id))\n if (!persisted || stableJsonStringify(persisted.event) !== stableJsonStringify(actual.event)) {\n invalidCorrelation(\"Materialization outbox event was not persisted.\")\n }\n }\n}\n\nfunction assertFinalCardinality(\n records: readonly MaterializationCardinalityOccupantWorkRecord[],\n projectId: string,\n objects: InMemoryObjectStorage\n): void {\n const effectiveOccupants = records.filter((record) => record.view === \"effective\")\n const scopes = new Map<\n string,\n {\n readonly source: OntologyObjectRef\n readonly linkId: string\n readonly occupiedLinkKeys: Set<string>\n }\n >()\n // Apply already rejected a scope with two staged occupants; this checks what it wrote.\n for (const record of effectiveOccupants) {\n const scope = scopes.get(record.scopeSortKey) ?? {\n source: structuredClone(record.ref.source),\n linkId: record.ref.linkId,\n occupiedLinkKeys: new Set<string>(),\n }\n scopes.set(record.scopeSortKey, scope)\n if (record.occupied) scope.occupiedLinkKeys.add(record.linkSortKey)\n }\n\n const adapter = getInMemoryObjectMaterializerAdapter(objects)\n for (const scope of scopes.values()) {\n const effectiveLinkKeys: string[] = []\n adapter.visitExactScopeLinks(\n projectId,\n scope.source.objectTypeId,\n scope.source.primaryId,\n scope.linkId,\n (row) => effectiveLinkKeys.push(linkRefSortKey(linkRef(row)))\n )\n effectiveLinkKeys.sort()\n const occupiedLinkKeys = [...scope.occupiedLinkKeys].sort()\n if (stableJsonStringify(effectiveLinkKeys) !== stableJsonStringify(occupiedLinkKeys)) {\n invalidCorrelation(\n \"Materialization cardinality work does not match the final effective link scope.\"\n )\n }\n }\n}\n\n/** Every identity the plan decides with a diff is classified once, and nothing else is. */\nfunction assertPlanCoverage(\n session: SessionState,\n activation: import(\"../materializations\").SourceActivationWrite\n): void {\n const plan = session.plan\n if (\n !plan ||\n plan.sourceId !== activation.source.projectionId ||\n plan.materializationId !== activation.materializationId ||\n plan.projectionKind !== activation.projectionKind\n ) {\n invalidCorrelation(\"Source activation does not match the replacement plan the session applies.\")\n }\n const expected = (kind: \"object\" | \"link\") =>\n [...plan.identities.values()]\n .filter((identity) => identity.entity.kind === kind && identity.diffRequired)\n .map((identity) =>\n identity.entity.kind === \"object\"\n ? objectRefKey(identity.entity.ref)\n : linkRefKey(identity.entity.ref)\n )\n .sort()\n if (\n stableJsonStringify(classificationKeys(session, \"object\")) !==\n stableJsonStringify(expected(\"object\")) ||\n stableJsonStringify(classificationKeys(session, \"link\")) !==\n stableJsonStringify(expected(\"link\")) ||\n classificationKeys(session, \"point\").length > 0\n ) {\n invalidCorrelation(\"Projection replacement classification coverage does not match its plan.\")\n }\n}\n\nfunction classificationKeys(\n session: SessionState,\n entityKind: import(\"../materializations\").MaterializationWorkEntityKind\n): string[] {\n return [...session.work.values()]\n .filter(\n (record): record is import(\"../materializations\").MaterializationClassificationWorkRecord =>\n record.kind === \"classification\" && record.entityKind === entityKind\n )\n .map((record) => record.identityKey)\n .sort()\n}\n\nfunction assertTimestampNotBefore(value: string, minimum: string, message: string): void {\n if (Date.parse(value) < Date.parse(minimum)) invalidCorrelation(message)\n}\n",
|
|
34
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport { linkRefKey, linkScopeSortKey, projectionEntityKey } from \"../../../materialization/refs\"\nimport type { SourceActivationWrite } from \"../materializations\"\nimport type { StoredSourceAssertion, StoredSourceLinkAssertion } from \"../sources\"\nimport { storedSource } from \"./materializations-state\"\nimport type { InMemoryCommitTouches } from \"./replacement-plans\"\nimport {\n type InMemoryOntologyState,\n type InMemorySourceMaterialization,\n projectEntityKey,\n sourceMaterializationKey,\n} from \"./shared-state\"\n\nexport function* previousSourceRows(\n state: InMemoryOntologyState,\n candidate: InMemorySourceMaterialization\n): Iterable<StoredSourceAssertion> {\n const sourceKey = projectEntityKey(candidate.projectId, candidate.source.projectionId)\n const active = state.activeSourceRoots.get(sourceKey)\n if (!active) return\n for (const rootKey of candidate.base ? candidate.roots.keys() : active.keys()) {\n const materializationId = active.get(rootKey)\n if (!materializationId) continue\n const materialization = state.sourceMaterializations.get(\n sourceMaterializationKey(\n candidate.projectId,\n candidate.source.projectionId,\n materializationId\n )\n )!\n for (const entityKey of materialization.roots.get(rootKey)!.entityKeys) {\n yield storedSource(\n candidate.source.projectionId,\n materializationId,\n materialization.rowsByEntity.get(entityKey)!\n )\n }\n }\n}\n\n/** Activates the candidate's roots, touching each link a root it retires or activates asserts. */\nexport function activateSourceRoots(\n state: InMemoryOntologyState,\n candidate: InMemorySourceMaterialization,\n activation: SourceActivationWrite,\n touches: InMemoryCommitTouches\n): void {\n if (\n candidate.base &&\n (candidate.base.materializationId !== activation.expected.activeMaterializationId ||\n candidate.base.lastCommitId !== activation.expected.lastCommitId)\n ) {\n throw new MaterializationConflictError(\n \"projection-fence\",\n \"Source delta base changed before activation.\"\n )\n }\n const sourceKey = projectEntityKey(candidate.projectId, candidate.source.projectionId)\n const active = state.activeSourceRoots.get(sourceKey) ?? new Map<string, string>()\n for (const key of candidate.base ? candidate.roots.keys() : [...active.keys()]) {\n const materializationId = active.get(key)\n if (!materializationId) continue\n const old = state.sourceMaterializations.get(\n sourceMaterializationKey(\n candidate.projectId,\n candidate.source.projectionId,\n materializationId\n )\n )!\n const root = old.roots.get(key)!\n root.active = false\n root.retiredAt = activation.updatedAt\n active.delete(key)\n for (const entityKey of root.entityKeys) {\n const row = old.rowsByEntity.get(entityKey)!\n const indexKey = projectEntityKey(candidate.projectId, entityKey)\n const sources = state.activeSourceRows.get(indexKey)!\n sources.delete(candidate.source.projectionId)\n if (sources.size === 0) state.activeSourceRows.delete(indexKey)\n if (row.assertion.kind === \"link\") {\n touches.links.add(linkRefKey(row.assertion.ref))\n const scopeKey = projectEntityKey(\n candidate.projectId,\n linkScopeSortKey(row.assertion.ref.source, row.assertion.ref.linkId)\n )\n const scope = state.activeSourceLinkScopes.get(scopeKey)!\n scope.delete(JSON.stringify([candidate.source.projectionId, entityKey]))\n if (scope.size === 0) state.activeSourceLinkScopes.delete(scopeKey)\n }\n }\n }\n for (const [rootKey, root] of candidate.roots) {\n root.active = !root.deleted\n root.retiredAt = root.deleted ? activation.updatedAt : null\n if (root.deleted) continue\n active.set(rootKey, candidate.materializationId)\n for (const entityKey of root.entityKeys) {\n // These are internal immutable assertions. Share their payload between indexes;\n // read methods clone returned values and transaction snapshots preserve aliases.\n const row = {\n source: candidate.source,\n materializationId: candidate.materializationId,\n ...candidate.rowsByEntity.get(entityKey)!,\n } as StoredSourceAssertion\n const indexKey = projectEntityKey(candidate.projectId, projectionEntityKey(row.assertion))\n const sources =\n state.activeSourceRows.get(indexKey) ?? new Map<string, StoredSourceAssertion>()\n sources.set(candidate.source.projectionId, row)\n state.activeSourceRows.set(indexKey, sources)\n if (row.assertion.kind === \"link\") {\n touches.links.add(linkRefKey(row.assertion.ref))\n const scopeKey = projectEntityKey(\n candidate.projectId,\n linkScopeSortKey(row.assertion.ref.source, row.assertion.ref.linkId)\n )\n const scope =\n state.activeSourceLinkScopes.get(scopeKey) ?? new Map<string, StoredSourceLinkAssertion>()\n scope.set(\n JSON.stringify([candidate.source.projectionId, entityKey]),\n row as StoredSourceLinkAssertion\n )\n state.activeSourceLinkScopes.set(scopeKey, scope)\n }\n }\n }\n state.activeSourceRoots.set(sourceKey, active)\n state.activeSourceHeads.set(sourceKey, candidate.materializationId)\n}\n",
|
|
35
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport {\n MaterializationConflictError,\n MaterializationValidationError,\n} from \"../../../materialization/errors\"\nimport type {\n OntologyLinkRef,\n OntologyObjectRef,\n ProjectionEntityRef,\n} from \"../../../materialization/model\"\nimport {\n linkRefKey,\n linkRefSortKey,\n linkScopeKey,\n linkScopeSortKey,\n objectRefKey,\n objectRefSortKey,\n projectionEntityKey,\n} from \"../../../materialization/refs\"\nimport {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport type {\n MaterializationObjectExistence,\n MaterializationPlanWorkItem,\n MaterializationWorkRecord,\n SourceReplacementLinkState,\n SourceReplacementObjectState,\n} from \"../materializations\"\nimport { assertPageRows, duplicateMaterializationWork } from \"../provider\"\nimport { assertNonblank, assertPositiveInteger } from \"../provider-validation\"\nimport {\n assertReplacementPlanCommit,\n prepareReplacementIdentities,\n projectionChangeCounts,\n workUniquenessKey,\n} from \"../provider-work\"\nimport type {\n OntologyReplacementPlanStorage,\n OpenedReplacementPlan,\n OpenReplacementPlanInput,\n PurgeReplacementPlansInput,\n ReplacementPlanRef,\n ReplacementPlanStatePage,\n ReplacementPlanStatus,\n StageReplacementPlanInput,\n StreamReplacementPlanStateInput,\n} from \"../replacement-plans\"\nimport type { AssertSourceMaterializationExecution } from \"../sources\"\nimport {\n findActiveSourceMaterialization,\n linkRef,\n storedSourceLink,\n storedSourceObject,\n} from \"./materializations-state\"\nimport {\n type InMemoryOntologyState,\n type InMemoryOntologyStorageTestHooks,\n type InMemorySourceMaterialization,\n projectEntityKey,\n sourceMaterializationKey,\n} from \"./shared-state\"\nimport { previousSourceRows } from \"./source-roots\"\nimport type { InMemoryMaterializationStateReader } from \"./state-reader\"\n\nexport interface InMemoryPlanIdentity {\n readonly entity: ProjectionEntityRef\n readonly sortKey: string\n diffRequired: boolean\n /** Whether link expansion already started from this identity since it was last planned. */\n expanded: boolean\n /** Revision of the inputs the identity's state was last read at. */\n readRevision: string | null\n /** Revision its records were planned from; null while it is still to plan. */\n plannedRevision: string | null\n records: readonly MaterializationWorkRecord[]\n}\n\nexport interface InMemoryReplacementPlan {\n readonly projectId: string\n readonly sourceId: string\n readonly materializationId: string\n readonly projectionKind: \"object\" | \"link\"\n /** The commit the plan's work carries, and its time fixed when the plan opened. */\n readonly commitId: string\n readonly committedAt: string\n /** The active source the plan replaces, null when none was active. */\n readonly replacedMaterializationId: string | null\n readonly replacedLastCommitId: string | null\n /** Commits finalized when every planned identity was last known fresh. */\n watermark: number\n /** Entities this replacement decides: its own rows and those of the roots it replaces. */\n readonly owned: Set<string>\n /** Keyed by `projectionEntityKey`. */\n readonly identities: Map<string, InMemoryPlanIdentity>\n /** Record and uniqueness keys of the planned work, each unique within the plan. */\n readonly workKeys: Set<string>\n}\n\n/** The entities whose plan inputs one commit changed, by key. */\nexport interface InMemoryCommitTouches {\n readonly projectId: string\n /** `objectRefKey`s, `linkRefKey`s and `linkScopeKey`s. */\n readonly objects: Set<string>\n readonly links: Set<string>\n readonly scopes: Set<string>\n}\n\nexport function emptyCommitTouches(projectId: string): InMemoryCommitTouches {\n return { projectId, objects: new Set(), links: new Set(), scopes: new Set() }\n}\n\n/**\n * Records what applying `item` changes among the inputs a plan reads. The SQL providers derive the\n * same keys from their work tables.\n */\nexport function touchPlanItem(touches: InMemoryCommitTouches, item: MaterializationPlanWorkItem) {\n switch (item.kind) {\n case \"object-override-upsert\":\n case \"object-override-delete\":\n case \"object-delete\":\n touches.objects.add(objectRefKey(item.value.ref))\n return\n case \"object-upsert\":\n touches.objects.add(objectRefKey(item.value.row.ref))\n return\n case \"point-upsert\":\n touches.objects.add(objectRefKey(item.value.point.series.object))\n return\n case \"link-override-upsert\":\n case \"link-override-delete\":\n case \"link-delete\":\n touches.links.add(linkRefKey(item.value.ref))\n return\n case \"link-upsert\":\n touches.links.add(linkRefKey(item.value.row.ref))\n return\n case \"link-slot-override-upsert\":\n case \"link-slot-override-delete\":\n touches.scopes.add(linkScopeKey(item.value.ref.source, item.value.ref.linkId))\n return\n // A plan reads no unique value: its claims are checked when they apply.\n case \"unique-value-release\":\n case \"unique-value-claim\":\n return\n }\n}\n\nexport function replacementPlanKey(input: {\n readonly projectId: string\n readonly source: { readonly projectionId: string }\n readonly materializationId: string\n}): string {\n return sourceMaterializationKey(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n}\n\nexport class InMemoryOntologyReplacementPlanStorage implements OntologyReplacementPlanStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly objects: InMemoryObjectStorage,\n private readonly reader: InMemoryMaterializationStateReader,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>,\n private readonly assertExecution: AssertSourceMaterializationExecution,\n private readonly hooks: InMemoryOntologyStorageTestHooks = {}\n ) {}\n\n async open(input: OpenReplacementPlanInput): Promise<OpenedReplacementPlan> {\n return this.runRootOperation(async () => {\n assertReplacementPlanCommit(input.commit)\n const candidate = await this.requireCandidate(input)\n const key = replacementPlanKey(input)\n const active = findActiveSourceMaterialization(\n this.state,\n input.projectId,\n input.source.projectionId\n )\n const replacedMaterializationId = active?.materializationId ?? null\n const replacedLastCommitId = active?.lastCommitId ?? null\n const existing = this.state.replacementPlans.get(key)\n // A plan decides the entities of the source it replaces: once that moved, it starts over.\n if (\n existing?.replacedMaterializationId === replacedMaterializationId &&\n existing.replacedLastCommitId === replacedLastCommitId\n ) {\n return { committedAt: existing.committedAt }\n }\n const plan: InMemoryReplacementPlan = {\n projectId: input.projectId,\n sourceId: input.source.projectionId,\n materializationId: input.materializationId,\n projectionKind: candidate.projectionKind,\n commitId: input.commit.id,\n committedAt: input.commit.committedAt,\n replacedMaterializationId,\n replacedLastCommitId,\n watermark: this.state.commitsById.size,\n owned: new Set(),\n identities: new Map(),\n workKeys: new Set(),\n }\n for (const rows of [\n previousSourceRows(this.state, candidate),\n candidate.rowsByEntity.values(),\n ]) {\n for (const row of rows) {\n plan.owned.add(projectionEntityKey(row.assertion))\n addIdentity(plan, row.assertion, true)\n }\n }\n this.state.replacementPlans.set(key, plan)\n return { committedAt: plan.committedAt }\n })\n }\n\n async *streamState(\n input: StreamReplacementPlanStateInput\n ): AsyncIterable<ReplacementPlanStatePage> {\n assertPageRows(input.pageRows)\n this.hooks.beforeRead?.(`replacement-plan.${input.entityKind}`)\n const pending = await this.runRootOperation(async () => {\n const { plan } = await this.requirePlan(input)\n if (input.entityKind === \"object\" && plan.projectionKind !== \"object\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Link projection replacement cannot stream object state.\"\n )\n }\n if (input.entityKind === \"link\") {\n if (unplanned(plan, \"object\").length > 0) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Object projection replacement must plan every object before its links.\"\n )\n }\n this.expandLinks(plan)\n }\n return unplanned(plan, input.entityKind).map((identity) =>\n projectionEntityKey(identity.entity)\n )\n })\n for (let offset = 0; offset < pending.length; offset += input.pageRows) {\n const keys = pending.slice(offset, offset + input.pageRows)\n const page = await this.runRootOperation(async () => {\n const { plan, candidate } = await this.requirePlan(input)\n // Looked up again: a rolled back transaction restores the plan as copies.\n const selected = keys.flatMap((key) => {\n const identity = plan.identities.get(key)\n return identity?.plannedRevision === null ? [identity] : []\n })\n if (selected.length === 0) return null\n return input.entityKind === \"object\"\n ? this.objectPage(plan, candidate, selected)\n : this.linkPage(plan, candidate, selected)\n })\n if (!page) continue\n this.hooks.observeBuffer?.(\n `replacement.${input.entityKind}.page`,\n page.objects.length + page.links.length\n )\n yield page\n }\n }\n\n async stage(input: StageReplacementPlanInput): Promise<void> {\n await this.runRootOperation(async () => {\n const { plan } = await this.requirePlan(input)\n // Only an identity streamed and still to plan has the revision its work is planned from,\n // and holds no work: unplanning one deletes its work and forgets what it read.\n const updates = prepareReplacementIdentities(input, plan).map((prepared) => {\n const current = plan.identities.get(prepared.entityKey)\n if (!current || current.readRevision === null || current.plannedRevision !== null) {\n throw new MaterializationValidationError(\n `Replacement identity ${prepared.entityKey} is not streamed and still to plan.`\n )\n }\n return { current, records: structuredClone(prepared.records) }\n })\n const claimed = new Set<string>()\n for (const { records } of updates) {\n for (const record of records) {\n for (const key of workKeys(record)) {\n if (claimed.has(key) || plan.workKeys.has(key)) {\n throw duplicateMaterializationWork(record.recordKey)\n }\n claimed.add(key)\n }\n }\n }\n const staged = updates.flatMap(({ records }) => records)\n this.hooks.observeWork?.(staged)\n for (const { current, records } of updates) {\n current.records = records\n current.plannedRevision = current.readRevision\n }\n for (const key of claimed) plan.workKeys.add(key)\n this.hooks.observeBuffer?.(\"plan.stage\", updates.length)\n })\n }\n\n async refresh(input: ReplacementPlanRef): Promise<ReplacementPlanStatus> {\n const { plan } = await this.requirePlan(input)\n const pending = [...plan.identities.values()].filter(\n (identity) => identity.plannedRevision === null\n )\n if (pending.length > 0) return { fresh: false, unplanned: pending.length }\n let unplannedCount = 0\n if (this.state.commitsById.size !== plan.watermark) {\n // Purge keeps every commit's touches past the watermark of a ready plan.\n const touched = emptyCommitTouches(plan.projectId)\n for (let ordinal = plan.watermark + 1; ordinal <= this.state.commitsById.size; ordinal += 1) {\n const touches = this.state.commitTouches.get(ordinal)\n if (touches?.projectId !== plan.projectId) continue\n for (const kind of [\"objects\", \"links\", \"scopes\"] as const) {\n for (const key of touches[kind]) touched[kind].add(key)\n }\n }\n for (const identity of plan.identities.values()) {\n if (!touchesIdentity(touched, identity.entity)) continue\n if (this.revision(plan, identity) === identity.plannedRevision) continue\n unplan(plan, identity)\n unplannedCount += 1\n }\n unplannedCount += this.expandTouched(plan, touched)\n plan.watermark = this.state.commitsById.size\n }\n if (unplannedCount > 0) return { fresh: false, unplanned: unplannedCount }\n return {\n fresh: true,\n counts: projectionChangeCounts(\n [...plan.identities.values()].flatMap((identity) => identity.records)\n ),\n }\n }\n\n async purge(input: PurgeReplacementPlansInput): Promise<number> {\n assertNonblank(input.projectId, \"Replacement plan purge project id\")\n assertPositiveInteger(input.limit, \"Replacement plan purge limit\")\n return this.runRootOperation(() => {\n // Commits and abandons delete their plan at once: only touches outlive what reads them.\n let horizon = this.state.commitsById.size\n for (const plan of this.state.replacementPlans.values()) {\n if (plan.projectId === input.projectId) horizon = Math.min(horizon, plan.watermark)\n }\n let deleted = 0\n for (const [ordinal, touches] of this.state.commitTouches) {\n if (deleted === input.limit) break\n if (ordinal > horizon || touches.projectId !== input.projectId) continue\n this.state.commitTouches.delete(ordinal)\n deleted += 1\n }\n return deleted\n })\n }\n\n private async objectPage(\n plan: InMemoryReplacementPlan,\n candidate: InMemorySourceMaterialization,\n selected: readonly InMemoryPlanIdentity[]\n ): Promise<ReplacementPlanStatePage> {\n const objects: SourceReplacementObjectState[] = []\n for (const identity of selected) {\n const ref = identity.entity.ref as OntologyObjectRef\n const base = await this.reader.objectState(plan.projectId, ref)\n objects.push({\n ref: base.ref,\n candidateSource: storedSourceObject(\n plan.sourceId,\n plan.materializationId,\n candidate.rowsByEntity.get(projectionEntityKey(identity.entity))\n ),\n override: base.override,\n effective: base.effective,\n latestTelemetry: base.latestTelemetry,\n })\n identity.readRevision = this.revision(plan, identity)\n }\n return { objects, links: [], endpoints: [] }\n }\n\n private async linkPage(\n plan: InMemoryReplacementPlan,\n candidate: InMemorySourceMaterialization,\n selected: readonly InMemoryPlanIdentity[]\n ): Promise<ReplacementPlanStatePage> {\n const links: SourceReplacementLinkState[] = []\n const endpoints = new Map<string, MaterializationObjectExistence>()\n for (const identity of selected) {\n const ref = identity.entity.ref as OntologyLinkRef\n const key = projectionEntityKey(identity.entity)\n const base = await this.reader.linkState(plan.projectId, ref)\n links.push({\n ref: base.ref,\n candidateSource: plan.owned.has(key)\n ? storedSourceLink(plan.sourceId, plan.materializationId, candidate.rowsByEntity.get(key))\n : base.source,\n override: base.override,\n slotOverride: base.slotOverride,\n effective: base.effective,\n diffRequired: identity.diffRequired,\n })\n for (const endpoint of [ref.source, ref.target]) {\n endpoints.set(objectRefKey(endpoint), {\n ref: structuredClone(endpoint),\n exists: this.endpointExists(plan, endpoint),\n })\n }\n identity.readRevision = this.revision(plan, identity)\n }\n return { objects: [], links, endpoints: [...endpoints.values()] }\n }\n\n /** An endpoint exists as this plan leaves it when the plan decides it, else as effective. */\n private endpointExists(plan: InMemoryReplacementPlan, ref: OntologyObjectRef): boolean {\n const planned = plan.identities.get(projectionEntityKey({ kind: \"object\", ref }))\n const existence = planned?.records.find((record) => record.kind === \"object-existence\")\n if (existence?.kind === \"object-existence\") return existence.exists\n return (\n getInMemoryObjectMaterializerAdapter(this.objects).getExactObjectRow(\n plan.projectId,\n ref.objectTypeId,\n ref.primaryId\n ) !== null\n )\n }\n\n /**\n * The revision of everything an identity's plan reads. An object reads its effective row, its\n * override and its latest telemetry; a link reads its effective row, its edge and slot\n * overrides, the live source asserting it when this replacement does not, and the existence of\n * both endpoints: as planned for an object of this plan, which follows its whole revision, and\n * as it is for any other.\n */\n private revision(plan: InMemoryReplacementPlan, identity: InMemoryPlanIdentity): string {\n if (identity.entity.kind === \"object\") {\n return stableJsonStringify(this.objectRevision(plan.projectId, identity.entity.ref))\n }\n const ref = identity.entity.ref\n const projectId = plan.projectId\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactLinkRow(projectId, {\n sourceTypeId: ref.source.objectTypeId,\n sourceId: ref.source.primaryId,\n linkId: ref.linkId,\n targetTypeId: ref.target.objectTypeId,\n targetId: ref.target.primaryId,\n })\n const live = this.reader.findActiveLinkSource(projectId, ref)\n return stableJsonStringify([\n row?.lastCommitId ?? null,\n this.state.linkOverrides.get(projectEntityKey(projectId, linkRefKey(ref)))?.lastCommitId ??\n null,\n this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(ref.source, ref.linkId))\n )?.lastCommitId ?? null,\n live ? [live.source.projectionId, live.materializationId, live.stagingOrdinal] : null,\n this.endpointRevision(plan, ref.source),\n this.endpointRevision(plan, ref.target),\n ])\n }\n\n private endpointRevision(plan: InMemoryReplacementPlan, ref: OntologyObjectRef): unknown {\n if (plan.identities.has(projectionEntityKey({ kind: \"object\", ref }))) {\n return this.objectRevision(plan.projectId, ref)\n }\n return (\n getInMemoryObjectMaterializerAdapter(this.objects).getExactObjectRow(\n plan.projectId,\n ref.objectTypeId,\n ref.primaryId\n ) !== null\n )\n }\n\n private objectRevision(projectId: string, ref: OntologyObjectRef): unknown {\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactObjectRow(\n projectId,\n ref.objectTypeId,\n ref.primaryId\n )\n return [\n row ? [row.version, row.lastCommitId] : null,\n this.state.objectOverrides.get(projectEntityKey(projectId, objectRefKey(ref)))\n ?.lastCommitId ?? null,\n this.reader\n .latestTelemetry(projectId, ref)\n .map((point) => [point.series.propertyId, point.at, point.lastCommitId]),\n ]\n }\n\n /**\n * Adds the links a plan must decide besides its own, from the identities planned since they were\n * last expanded: those incident to an object whose existence it flips, and every member of a\n * scope it changes. Returns how many identities this left to plan, counting an existing one that\n * now needs a diff. What commits add later is found from their touches by `expandTouched`.\n */\n private expandLinks(plan: InMemoryReplacementPlan): number {\n const projectId = plan.projectId\n const incident = new Set<string>()\n for (const identity of plan.identities.values()) {\n if (identity.entity.kind !== \"object\" || identity.expanded) continue\n if (identity.plannedRevision === null) continue\n identity.expanded = true\n for (const record of identity.records) {\n if (record.kind === \"incident-object\") incident.add(objectRefKey(record.ref))\n }\n }\n let added = 0\n const consider = (ref: OntologyLinkRef, diffRequired: boolean): void => {\n if (addIdentity(plan, { kind: \"link\", ref }, diffRequired)) added += 1\n }\n if (incident.size > 0) {\n const index = this.reader.incidentLinkIndex(projectId)\n for (const key of incident) {\n for (const ref of index.get(key) ?? []) consider(ref, true)\n }\n }\n const adapter = getInMemoryObjectMaterializerAdapter(this.objects)\n const scopes = new Map<string, Pick<OntologyLinkRef, \"source\" | \"linkId\">>()\n for (const identity of plan.identities.values()) {\n if (identity.entity.kind !== \"link\" || !identity.diffRequired || identity.expanded) continue\n identity.expanded = true\n const ref = identity.entity.ref\n scopes.set(linkScopeSortKey(ref.source, ref.linkId), ref)\n }\n for (const scope of scopes.values()) {\n adapter.visitExactScopeLinks(\n projectId,\n scope.source.objectTypeId,\n scope.source.primaryId,\n scope.linkId,\n (row) => consider(linkRef(row), false)\n )\n const override = this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(scope.source, scope.linkId))\n )\n if (override) consider({ ...scope, target: override.value.target }, false)\n }\n return added\n }\n\n /**\n * Adds the links commits brought within the plan's reach, from what they touched: a link that\n * now exists incident to an object the plan flips, or in a scope a planned link changes. It\n * considers the links `expandLinks` would find, among those the commits touched.\n */\n private expandTouched(plan: InMemoryReplacementPlan, touched: InMemoryCommitTouches): number {\n const projectId = plan.projectId\n const incident = new Set<string>()\n const scopes = new Set<string>()\n for (const identity of plan.identities.values()) {\n for (const record of identity.records) {\n if (record.kind === \"incident-object\") incident.add(objectRefKey(record.ref))\n }\n if (identity.entity.kind === \"link\" && identity.diffRequired) {\n scopes.add(linkScopeKey(identity.entity.ref.source, identity.entity.ref.linkId))\n }\n }\n let added = 0\n const consider = (ref: OntologyLinkRef, member: boolean): void => {\n if (incident.has(objectRefKey(ref.source)) || incident.has(objectRefKey(ref.target))) {\n if (addIdentity(plan, { kind: \"link\", ref }, true)) added += 1\n } else if (member && scopes.has(linkScopeKey(ref.source, ref.linkId))) {\n if (addIdentity(plan, { kind: \"link\", ref }, false)) added += 1\n }\n }\n const adapter = getInMemoryObjectMaterializerAdapter(this.objects)\n for (const key of touched.links) {\n const ref = parseLinkKey(key)\n const effective =\n adapter.getExactLinkRow(projectId, {\n sourceTypeId: ref.source.objectTypeId,\n sourceId: ref.source.primaryId,\n linkId: ref.linkId,\n targetTypeId: ref.target.objectTypeId,\n targetId: ref.target.primaryId,\n }) !== null\n if (\n effective ||\n this.state.linkOverrides.has(projectEntityKey(projectId, key)) ||\n this.state.activeSourceRows.has(\n projectEntityKey(projectId, projectionEntityKey({ kind: \"link\", ref }))\n )\n ) {\n consider(ref, effective)\n }\n }\n for (const key of touched.scopes) {\n const override = this.state.linkSlotOverrides.get(projectEntityKey(projectId, key))\n if (override) consider({ ...override.ref, target: override.value.target }, true)\n }\n return added\n }\n\n private async requireCandidate(\n input: ReplacementPlanRef\n ): Promise<InMemorySourceMaterialization> {\n const candidate = this.state.sourceMaterializations.get(replacementPlanKey(input))\n if (\n !candidate ||\n candidate.status !== \"ready\" ||\n candidate.projectionRunId !== input.execution.projectionRunId ||\n candidate.executionToken !== input.execution.executionToken\n ) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Candidate source materialization '${input.materializationId}' is missing, not ready, or owned by another execution.`\n )\n }\n await this.assertExecution({\n projectId: input.projectId,\n source: input.source,\n execution: input.execution,\n })\n return candidate\n }\n\n private async requirePlan(\n input: ReplacementPlanRef\n ): Promise<{ plan: InMemoryReplacementPlan; candidate: InMemorySourceMaterialization }> {\n const candidate = await this.requireCandidate(input)\n const plan = this.state.replacementPlans.get(replacementPlanKey(input))\n if (!plan) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Candidate source materialization '${input.materializationId}' has no open plan.`\n )\n }\n return { plan, candidate }\n }\n}\n\n/** Adds an identity, or makes an existing one need a diff. True when it left one to plan. */\nfunction addIdentity(\n plan: InMemoryReplacementPlan,\n entity: ProjectionEntityRef,\n diffRequired: boolean\n): boolean {\n const key = projectionEntityKey(entity)\n const existing = plan.identities.get(key)\n if (existing) {\n if (!diffRequired || existing.diffRequired) return false\n existing.diffRequired = true\n unplan(plan, existing)\n return true\n }\n plan.identities.set(key, {\n entity: structuredClone({ kind: entity.kind, ref: entity.ref } as ProjectionEntityRef),\n sortKey: entity.kind === \"object\" ? objectRefSortKey(entity.ref) : linkRefSortKey(entity.ref),\n diffRequired,\n expanded: false,\n readRevision: null,\n plannedRevision: null,\n records: [],\n })\n return true\n}\n\nfunction unplan(plan: InMemoryReplacementPlan, identity: InMemoryPlanIdentity): void {\n for (const record of identity.records) {\n for (const key of workKeys(record)) plan.workKeys.delete(key)\n }\n identity.readRevision = null\n identity.plannedRevision = null\n identity.expanded = false\n identity.records = []\n}\n\n/** Whether a commit that touched `touched` may have changed an identity's revision. */\nfunction touchesIdentity(touched: InMemoryCommitTouches, entity: ProjectionEntityRef): boolean {\n if (entity.kind === \"object\") return touched.objects.has(objectRefKey(entity.ref))\n const { ref } = entity\n return (\n touched.links.has(linkRefKey(ref)) ||\n touched.scopes.has(linkScopeKey(ref.source, ref.linkId)) ||\n touched.objects.has(objectRefKey(ref.source)) ||\n touched.objects.has(objectRefKey(ref.target))\n )\n}\n\nfunction parseLinkKey(key: string): OntologyLinkRef {\n const [sourceTypeId, sourceId, linkId, targetTypeId, targetId] = JSON.parse(key) as string[]\n return {\n source: { objectTypeId: sourceTypeId!, primaryId: sourceId! },\n linkId: linkId!,\n target: { objectTypeId: targetTypeId!, primaryId: targetId! },\n }\n}\n\nfunction workKeys(record: MaterializationWorkRecord): readonly string[] {\n return [`record:${record.recordKey}`, `unique:${workUniquenessKey(record)}`]\n}\n\nfunction unplanned(plan: InMemoryReplacementPlan, kind: \"object\" | \"link\"): InMemoryPlanIdentity[] {\n return [...plan.identities.values()]\n .filter((identity) => identity.entity.kind === kind && identity.plannedRevision === null)\n .sort((left, right) => left.sortKey.localeCompare(right.sortKey))\n}\n",
|
|
36
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type { MaterializationSession } from \"../materializations\"\nimport type { OntologyVectorStorage, StoredObjectVector } from \"../vectors\"\n\nexport function vectorObjectKey(projectId: string, ref: StoredObjectVector[\"ref\"]): string {\n return JSON.stringify([projectId, ref.objectTypeId, ref.primaryId])\n}\n\nexport class InMemoryOntologyVectorStorage implements OntologyVectorStorage {\n constructor(\n private readonly state: Map<string, Map<string, StoredObjectVector>>,\n private readonly assertSession: (\n session: MaterializationSession,\n projectId: string,\n commitId?: string\n ) => void,\n private readonly runRootOperation: <T>(run: () => T) => Promise<T>\n ) {}\n\n async list(input: Parameters<OntologyVectorStorage[\"list\"]>[0]) {\n return this.listBatch({ projectId: input.projectId, refs: [input.ref] })\n }\n\n async listBatch(input: Parameters<OntologyVectorStorage[\"listBatch\"]>[0]) {\n return this.runRootOperation(() =>\n [...new Set(input.refs.map((ref) => vectorObjectKey(input.projectId, ref)))].flatMap((key) =>\n [...(this.state.get(key)?.values() ?? [])].map(({ values: _values, ...metadata }) =>\n structuredClone(metadata)\n )\n )\n )\n }\n\n async removeBatch(input: Parameters<OntologyVectorStorage[\"removeBatch\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n for (const entry of input.entries) {\n await this.remove({ session: input.session, projectId: input.projectId, ...entry })\n }\n }\n\n async write(input: Parameters<OntologyVectorStorage[\"write\"]>[0]) {\n this.assertSession(input.session, input.projectId, input.value.lastCommitId)\n const key = vectorObjectKey(input.projectId, input.value.ref)\n const profiles = this.state.get(key) ?? new Map<string, StoredObjectVector>()\n this.assertRevision(profiles.get(input.value.profile), input.expectedCommitId)\n profiles.set(input.value.profile, structuredClone(input.value))\n this.state.set(key, profiles)\n }\n\n async writeBatch(input: Parameters<OntologyVectorStorage[\"writeBatch\"]>[0]): Promise<void> {\n for (const entry of input.entries) {\n await this.write({ session: input.session, projectId: input.projectId, ...entry })\n }\n }\n\n async remove(input: Parameters<OntologyVectorStorage[\"remove\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n const key = vectorObjectKey(input.projectId, input.ref)\n const profiles = this.state.get(key)\n this.assertRevision(profiles?.get(input.profile), input.expectedCommitId)\n profiles?.delete(input.profile)\n if (profiles?.size === 0) this.state.delete(key)\n }\n\n private assertRevision(current: StoredObjectVector | undefined, expected: string | null) {\n if ((current?.lastCommitId ?? null) !== expected) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Vector changed since it was prepared.\"\n )\n }\n }\n}\n",
|
|
37
|
+
"import {\n MaterializationConflictError,\n MaterializationValidationError,\n} from \"../../../materialization/errors\"\nimport type {\n ExpectedLinkRevision,\n ExpectedObjectRevision,\n OntologyLinkRef,\n OntologyObjectRef,\n} from \"../../../materialization/model\"\nimport {\n linkRefKey,\n linkRefSortKey,\n linkScopeKey,\n linkScopeSortKey,\n objectRefKey,\n objectRefSortKey,\n telemetryPointKey,\n telemetryPointSortKey,\n} from \"../../../materialization/refs\"\nimport {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport {\n getInMemoryTimeseriesMaterializerAdapter,\n type InMemoryTimeseriesStorage,\n} from \"../../timeseries/store\"\nimport type { OntologyCommitRecord } from \"../commits\"\nimport type {\n AppliedMaterialization,\n ApplyMaterializationInput,\n ApplyMaterializationResult,\n ExactUniqueValueWrite,\n ExpectedSourceRevision,\n ExpectedTimeseriesPointRevision,\n FinalizeMaterializationInput,\n MaterializationCardinalityOccupantWorkRecord,\n MaterializationEventWorkRecord,\n MaterializationLinkScopeRevision,\n MaterializationLinkScopeState,\n MaterializationLinkState,\n MaterializationObjectState,\n MaterializationPlanHeader,\n MaterializationPlanWorkRecord,\n MaterializationSession,\n MaterializationStatePage,\n MaterializationVectorChange,\n MaterializationVectorChangePage,\n MaterializationWorkRecord,\n OntologyMaterializationStorage,\n StageMaterializationWorkInput,\n StoredTelemetryPoint,\n StreamMaterializationStateInput,\n StreamMaterializationVectorChangesInput,\n UniqueValueRef,\n} from \"../materializations\"\nimport {\n assertExpectedLinkRevision,\n assertExpectedLinkScopeRevision,\n assertExpectedObjectRevision,\n assertMaterializationHeader,\n beginMaterializationApply,\n beginMaterializationVectorChanges,\n duplicateMaterializationWork,\n type ProviderMaterializationTransactionLifecycle,\n prepareMaterializationWork,\n uniqueSorted,\n} from \"../provider\"\nimport { assertFinalizationCorrelations } from \"./materializations-finalization\"\nimport { findActiveSourceMaterialization, storedPoint, uniqueBy } from \"./materializations-state\"\nimport {\n assertLastCommit,\n assertPageRows,\n compareCardinalityWork,\n compareEventWork,\n comparePlanWork,\n createCardinalityValidator,\n invalidCorrelation,\n type MaterializationPlanChunk,\n materializationChunkRows,\n materializationOutboxWrite,\n materializationPlanChunk,\n type OntologyOutboxWrite,\n workUniquenessKey,\n} from \"./materializations-work\"\nimport {\n emptyCommitTouches,\n type InMemoryReplacementPlan,\n replacementPlanKey,\n touchPlanItem,\n} from \"./replacement-plans\"\nimport {\n assertTimestamp,\n commitKey,\n commitOriginKey,\n type InMemoryExecutionReader,\n type InMemoryOntologyState,\n type InMemoryOntologyStorageTestHooks,\n idempotencyKey,\n ontologyCommitOriginSelector,\n outboxKey,\n projectEntityKey,\n sourceMaterializationKey,\n} from \"./shared-state\"\nimport { activateSourceRoots } from \"./source-roots\"\nimport type { InMemoryMaterializationStateReader } from \"./state-reader\"\nimport { vectorObjectKey } from \"./vectors\"\n\nexport interface SessionState {\n readonly providerToken: object\n readonly header: MaterializationPlanHeader\n readonly transactionToken: object\n readonly lifecycle: ProviderMaterializationTransactionLifecycle\n active: boolean\n writeOrdinal: number\n readonly work: Map<string, MaterializationWorkRecord>\n readonly workUniqueKeys: Set<string>\n readonly applyWork: MaterializationPlanWorkRecord[]\n readonly cardinalityWork: MaterializationCardinalityOccupantWorkRecord[]\n readonly eventWork: MaterializationEventWorkRecord[]\n readonly outboxWrites: Map<number, OntologyOutboxWrite>\n workSealed: boolean\n vectorChangesStreamed: boolean\n applied: boolean\n appliedEventCount: number\n incidentLinksByObject: Map<string, readonly OntologyLinkRef[]> | null\n linkSlotStates: Map<string, MaterializationLinkScopeState> | null\n /** The durable replacement plan this session applies instead of staged work. */\n readonly plan: InMemoryReplacementPlan | null\n}\n\nexport class InMemoryOntologyMaterializationStorage implements OntologyMaterializationStorage {\n private readonly sessions = new WeakMap<object, SessionState>()\n private readonly liveSessions = new Set<SessionState>()\n\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly objects: InMemoryObjectStorage,\n private readonly timeseries: InMemoryTimeseriesStorage,\n private readonly reader: InMemoryMaterializationStateReader,\n private readonly getTransactionToken: () => object | null,\n private readonly getMaterializationLifecycle: () => ProviderMaterializationTransactionLifecycle | null,\n private readonly readExecution: InMemoryExecutionReader,\n private readonly hooks: InMemoryOntologyStorageTestHooks = {}\n ) {}\n\n async begin(input: MaterializationPlanHeader): Promise<MaterializationSession> {\n const transactionToken = this.getTransactionToken()\n const lifecycle = this.getMaterializationLifecycle()\n if (!transactionToken || !lifecycle) {\n throw new MaterializationValidationError(\n \"Materialization sessions require an active storage transaction.\"\n )\n }\n assertMaterializationHeader(input)\n if (!(await this.readExecution(input.commit.projectId, input.commit.executionId))) {\n throw new MaterializationValidationError(\n `Ontology commit execution '${input.commit.executionId}' does not exist in project '${input.commit.projectId}'.`\n )\n }\n this.assertCommitAbsent(input)\n for (const expected of input.expected.sources)\n this.assertSource(expected, input.commit.projectId)\n for (const expected of input.expected.objects)\n await this.assertObject(expected, input.commit.projectId)\n for (const expected of input.expected.links)\n await this.assertLink(expected, input.commit.projectId)\n const expectedScopeRevisions = new Map<string, MaterializationLinkScopeRevision>()\n for (const expected of input.expected.linkScopes) {\n const key = linkScopeSortKey(expected.source, expected.linkId)\n const current =\n expectedScopeRevisions.get(key) ??\n this.reader.effectiveLinkScope(input.commit.projectId, expected.source, expected.linkId)\n expectedScopeRevisions.set(key, current)\n assertExpectedLinkScopeRevision(current.fingerprint, expected)\n }\n for (const expected of input.expected.points) this.assertPoint(expected, input.commit.projectId)\n const plan = input.plan ? this.requirePlan(input) : null\n\n const providerToken = {}\n const session = {\n providerToken,\n header: structuredClone(input),\n transactionToken,\n lifecycle,\n active: true,\n writeOrdinal: 0,\n work: new Map<string, MaterializationWorkRecord>(),\n workUniqueKeys: new Set<string>(),\n applyWork: [],\n cardinalityWork: [],\n eventWork: [],\n outboxWrites: new Map<number, OntologyOutboxWrite>(),\n workSealed: false,\n vectorChangesStreamed: false,\n applied: false,\n appliedEventCount: 0,\n incidentLinksByObject: null,\n linkSlotStates: new Map(),\n plan,\n }\n if (plan) {\n for (const identity of plan.identities.values()) {\n for (const record of structuredClone(identity.records)) this.addWork(session, record)\n }\n }\n this.sessions.set(providerToken, session)\n this.liveSessions.add(session)\n lifecycle.register(providerToken)\n return { providerToken }\n }\n\n deactivateTransaction(transactionToken: object): void {\n for (const session of this.liveSessions) {\n if (session.transactionToken !== transactionToken) continue\n this.releaseSession(session)\n }\n }\n\n /** Deactivate a session, drop its transaction-local work, and stop tracking it as live. */\n private releaseSession(session: SessionState): void {\n session.active = false\n session.work.clear()\n session.workUniqueKeys.clear()\n session.applyWork.length = 0\n session.cardinalityWork.length = 0\n session.eventWork.length = 0\n session.outboxWrites.clear()\n session.incidentLinksByObject = null\n session.linkSlotStates = null\n this.liveSessions.delete(session)\n session.lifecycle.complete(session.providerToken)\n }\n\n async *streamState(\n input: StreamMaterializationStateInput\n ): AsyncIterable<MaterializationStatePage> {\n const session = this.requireSession(input.session)\n assertPageRows(input.pageRows)\n for await (const request of input.requests) {\n this.requireSession(input.session)\n this.hooks.beforeRead?.(\"state.read\")\n const objectRefs = uniqueSorted(request.objects, objectRefKey, objectRefSortKey)\n for (let offset = 0; offset < objectRefs.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const objects: MaterializationObjectState[] = []\n for (const ref of objectRefs.slice(offset, offset + input.pageRows)) {\n objects.push(await this.reader.objectState(session.header.commit.projectId, ref))\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.object.page\", objects.length)\n yield { objects, links: [], linkScopes: [], points: [] }\n }\n\n const linkRefs = uniqueSorted(request.links, linkRefKey, linkRefSortKey)\n for (let offset = 0; offset < linkRefs.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const links: MaterializationLinkState[] = []\n for (const ref of linkRefs.slice(offset, offset + input.pageRows)) {\n links.push(await this.reader.linkState(session.header.commit.projectId, ref))\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.link.page\", links.length)\n yield { objects: [], links, linkScopes: [], points: [] }\n }\n\n const incidentRefs = this.incidentLinkRefs(session, request.incidentObjects)\n for (let offset = 0; offset < incidentRefs.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const refs = incidentRefs.slice(offset, offset + input.pageRows)\n const links: MaterializationLinkState[] = []\n for (const ref of refs)\n links.push(await this.reader.linkState(session.header.commit.projectId, ref))\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.incident-link.page\", links.length)\n yield { objects: [], links, linkScopes: [], points: [] }\n }\n\n for (const scope of uniqueBy(request.linkScopes, (value) =>\n linkScopeSortKey(value.source, value.linkId)\n )) {\n this.requireSession(input.session)\n const value = this.linkSlotState(session, scope.source, scope.linkId)\n // Scope rows are currently only requested for cardinality-one links, so the complete member\n // set is bounded by the ontology invariant. Replacement scope enumeration is flattened in\n // its dedicated stream and never uses this shape.\n yield { objects: [], links: [], linkScopes: [value], points: [] }\n }\n\n const uniqueHolders = this.uniqueHolders(session, request.uniqueValues ?? [])\n for (let offset = 0; offset < uniqueHolders.length; offset += input.pageRows) {\n this.requireSession(input.session)\n yield {\n objects: [],\n links: [],\n linkScopes: [],\n points: [],\n uniqueHolders: uniqueHolders.slice(offset, offset + input.pageRows),\n }\n }\n\n const requestedPoints = uniqueSorted(\n request.points,\n (point) => telemetryPointKey(point.series, point.at),\n (point) => telemetryPointSortKey(point.series, point.at)\n )\n for (let offset = 0; offset < requestedPoints.length; offset += input.pageRows) {\n this.requireSession(input.session)\n const points: StoredTelemetryPoint[] = []\n for (const point of requestedPoints.slice(offset, offset + input.pageRows)) {\n const stored = getInMemoryTimeseriesMaterializerAdapter(this.timeseries).getExactPoint(\n session.header.commit.projectId,\n point.series,\n point.at\n )\n if (stored) points.push(storedPoint(stored))\n }\n this.requireSession(input.session)\n this.hooks.observeBuffer?.(\"state.point.page\", points.length)\n if (points.length > 0) yield { objects: [], links: [], linkScopes: [], points }\n }\n }\n }\n\n async stageWork(input: StageMaterializationWorkInput): Promise<void> {\n const session = this.requireSession(input.session)\n for (const { record, uniqueKey } of prepareMaterializationWork(session, input)) {\n if (session.work.has(record.recordKey) || session.workUniqueKeys.has(uniqueKey)) {\n throw duplicateMaterializationWork(record.recordKey)\n }\n }\n const cloned = input.records.map((record) => structuredClone(record))\n this.hooks.observeWork?.(cloned)\n for (const record of cloned) this.addWork(session, record)\n this.hooks.observeBuffer?.(\"work.stage\", cloned.length)\n }\n\n private addWork(session: SessionState, record: MaterializationWorkRecord): void {\n session.work.set(record.recordKey, record)\n session.workUniqueKeys.add(workUniquenessKey(record))\n if (record.kind === \"plan\") session.applyWork.push(record)\n if (record.kind === \"cardinality\") session.cardinalityWork.push(record)\n if (record.kind === \"event\") session.eventWork.push(record)\n }\n\n async *streamVectorChanges(\n input: StreamMaterializationVectorChangesInput\n ): AsyncIterable<MaterializationVectorChangePage> {\n const session = this.requireSession(input.session)\n assertPageRows(input.pageRows)\n this.sealWork(session, beginMaterializationVectorChanges)\n const projectId = session.header.commit.projectId\n const profiled = new Set(input.objectTypeIds)\n const changes = session.applyWork.flatMap((record): MaterializationVectorChange[] => {\n const item = record.item\n if (item.kind !== \"object-upsert\" && item.kind !== \"object-delete\") return []\n const ref = item.kind === \"object-upsert\" ? item.value.row.ref : item.value.ref\n return profiled.has(ref.objectTypeId) ||\n (this.state.vectors.get(vectorObjectKey(projectId, ref))?.size ?? 0) > 0\n ? [item]\n : []\n })\n for (let offset = 0; offset < changes.length; offset += input.pageRows) {\n this.requireSession(input.session)\n yield { items: structuredClone(changes.slice(offset, offset + input.pageRows)) }\n }\n this.requireSession(input.session)\n }\n\n async apply(input: ApplyMaterializationInput): Promise<AppliedMaterialization> {\n const session = this.requireSession(input.session)\n this.sealWork(session, beginMaterializationApply)\n const cardinality = createCardinalityValidator()\n for (const record of session.cardinalityWork) cardinality.accept(record)\n for (let start = 0; start < session.applyWork.length; ) {\n const phase = session.applyWork[start]!.applyPhase\n let end = start\n while (session.applyWork[end]?.applyPhase === phase) end += 1\n const items = session.applyWork.slice(start, end).map((record) => record.item)\n this.writeChunk(session, materializationPlanChunk(items))\n start = end\n }\n const outbox = session.eventWork.map((record, ordinal) =>\n materializationOutboxWrite(session.header.commit, record.draft, ordinal)\n )\n this.writeChunk(session, materializationPlanChunk([], outbox))\n session.appliedEventCount = outbox.length\n return { eventCount: outbox.length }\n }\n\n private writeChunk(session: SessionState, chunk: MaterializationPlanChunk): void {\n const projectId = session.header.commit.projectId\n this.hooks.observeBuffer?.(\"apply.chunk\", materializationChunkRows(chunk))\n const write = (boundary: string, apply: () => void): void => {\n this.hooks.beforeWrite?.(boundary, session.writeOrdinal++)\n apply()\n }\n\n for (const item of chunk.overrides.objects.upserts)\n write(\"override.object.upsert\", () => {\n const key = projectEntityKey(projectId, objectRefKey(item.ref))\n assertLastCommit(\n this.state.objectOverrides.get(key),\n item.expectedLastCommitId,\n \"object override\"\n )\n this.state.objectOverrides.set(\n key,\n structuredClone({\n projectId,\n ref: item.ref,\n value: item.value,\n editedAt: { ...item.editedAt },\n lastCommitId: item.lastCommitId,\n updatedAt: item.updatedAt,\n })\n )\n })\n for (const item of chunk.overrides.objects.deletes)\n write(\"override.object.delete\", () => {\n const key = projectEntityKey(projectId, objectRefKey(item.ref))\n assertLastCommit(\n this.state.objectOverrides.get(key),\n item.expectedLastCommitId,\n \"object override\"\n )\n this.state.objectOverrides.delete(key)\n })\n for (const item of chunk.overrides.links.edges.upserts)\n write(\"override.link.upsert\", () => {\n const key = projectEntityKey(projectId, linkRefKey(item.ref))\n assertLastCommit(\n this.state.linkOverrides.get(key),\n item.expectedLastCommitId,\n \"link edge override\"\n )\n this.state.linkOverrides.set(\n key,\n structuredClone({\n projectId,\n ref: item.ref,\n value: item.value,\n lastCommitId: item.lastCommitId,\n updatedAt: item.updatedAt,\n })\n )\n })\n for (const item of chunk.overrides.links.edges.deletes)\n write(\"override.link.delete\", () => {\n const key = projectEntityKey(projectId, linkRefKey(item.ref))\n assertLastCommit(\n this.state.linkOverrides.get(key),\n item.expectedLastCommitId,\n \"link edge override\"\n )\n this.state.linkOverrides.delete(key)\n })\n for (const item of chunk.overrides.links.slots.upserts)\n write(\"override.link-slot.upsert\", () => {\n const key = projectEntityKey(projectId, linkScopeKey(item.ref.source, item.ref.linkId))\n assertLastCommit(\n this.state.linkSlotOverrides.get(key),\n item.expectedLastCommitId,\n \"link slot override\"\n )\n this.state.linkSlotOverrides.set(\n key,\n structuredClone({\n projectId,\n ref: item.ref,\n value: item.value,\n lastCommitId: item.lastCommitId,\n updatedAt: item.updatedAt,\n })\n )\n })\n for (const item of chunk.overrides.links.slots.deletes)\n write(\"override.link-slot.delete\", () => {\n const key = projectEntityKey(projectId, linkScopeKey(item.ref.source, item.ref.linkId))\n assertLastCommit(\n this.state.linkSlotOverrides.get(key),\n item.expectedLastCommitId,\n \"link slot override\"\n )\n this.state.linkSlotOverrides.delete(key)\n })\n\n for (const item of chunk.effective.linkDeletes)\n write(\"effective.link.delete\", () => {\n this.assertLinkSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).deleteExactLink({\n projectId,\n sourceTypeId: item.ref.source.objectTypeId,\n sourceId: item.ref.source.primaryId,\n linkId: item.ref.linkId,\n targetTypeId: item.ref.target.objectTypeId,\n targetId: item.ref.target.primaryId,\n })\n })\n for (const item of chunk.effective.objectDeletes)\n write(\"effective.object.delete\", () => {\n this.assertObjectSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).deleteExactObject(\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId\n )\n })\n for (const item of chunk.effective.objectUpserts)\n write(\"effective.object.upsert\", () => {\n this.assertObjectSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).applyExactObject(item.row, projectId)\n })\n for (const item of chunk.effective.linkUpserts)\n write(\"effective.link.upsert\", () => {\n this.assertLinkSync(item.expected, projectId)\n getInMemoryObjectMaterializerAdapter(this.objects).applyExactLink(item.row, projectId)\n })\n for (const item of chunk.unique.releases)\n write(\"unique.release\", () => {\n getInMemoryObjectMaterializerAdapter(this.objects).releaseUniqueValue(projectId, item)\n })\n for (const item of chunk.unique.claims)\n write(\"unique.claim\", () => {\n getInMemoryObjectMaterializerAdapter(this.objects).claimUniqueValue(projectId, item)\n })\n for (const item of chunk.timeseries.pointUpserts)\n write(\"timeseries.point.upsert\", () => {\n this.assertPoint(item.expected, projectId)\n getInMemoryTimeseriesMaterializerAdapter(this.timeseries).applyExactPoint(\n projectId,\n item.point\n )\n })\n for (const item of chunk.outbox)\n write(\"outbox.insert\", () => {\n assertTimestamp(item.createdAt, \"Outbox createdAt\")\n const key = outboxKey(projectId, item.id)\n if (this.state.outbox.has(key)) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Duplicate outbox event '${item.id}'.`\n )\n }\n if (session.outboxWrites.has(item.commitOrdinal))\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Duplicate outbox commit ordinal.\"\n )\n this.state.outbox.set(key, {\n projectId,\n id: item.id,\n commitId: session.header.commit.id,\n commitOrdinal: item.commitOrdinal,\n event: structuredClone(item.event),\n availableAt: item.createdAt,\n attempts: 0,\n leaseId: null,\n leaseExpiresAt: null,\n publishedAt: null,\n lastFailure: null,\n createdAt: item.createdAt,\n })\n session.outboxWrites.set(item.commitOrdinal, structuredClone(item))\n })\n }\n\n async finalize(input: FinalizeMaterializationInput): Promise<ApplyMaterializationResult> {\n const session = this.requireSession(input.session)\n const { commit } = session.header\n // Recheck reservations at the durable boundary: callers may open more than one session in the\n // same transaction before either one finalizes.\n this.assertCommitAbsent(session.header)\n assertFinalizationCorrelations(session, input.finalization, this.state, this.objects)\n this.hooks.beforeWrite?.(\"finalize\", session.writeOrdinal++)\n const touches = emptyCommitTouches(commit.projectId)\n for (const record of session.applyWork) touchPlanItem(touches, record.item)\n for (const activation of input.finalization.sourceActivations) {\n this.hooks.beforeWrite?.(\"source.activate\", session.writeOrdinal++)\n assertTimestamp(activation.datasetVersion.createdAt, \"Source dataset version createdAt\")\n assertTimestamp(activation.updatedAt, \"Source activation updatedAt\")\n this.assertSource(activation.expected, commit.projectId)\n const candidateKey = sourceMaterializationKey(\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId\n )\n const candidate = this.state.sourceMaterializations.get(candidateKey)\n if (!candidate || candidate.status !== \"ready\")\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source activation candidate is missing or is not ready.\"\n )\n const previous = findActiveSourceMaterialization(\n this.state,\n commit.projectId,\n activation.source.projectionId\n )\n if (previous) {\n this.state.sourceMaterializations.set(\n sourceMaterializationKey(\n previous.projectId,\n previous.source.projectionId,\n previous.materializationId\n ),\n {\n ...previous,\n status: \"superseded\",\n executionToken: null,\n terminalAt: activation.updatedAt,\n updatedAt: activation.updatedAt,\n }\n )\n }\n activateSourceRoots(this.state, candidate, activation, touches)\n this.state.sourceMaterializations.set(candidateKey, {\n ...candidate,\n status: \"active\",\n executionToken: null,\n activatedAt: activation.updatedAt,\n lastCommitId: activation.lastCommitId,\n updatedAt: activation.updatedAt,\n })\n }\n if (session.plan) {\n this.state.replacementPlans.delete(\n replacementPlanKey({\n projectId: commit.projectId,\n source: { projectionId: session.plan.sourceId },\n materializationId: session.plan.materializationId,\n })\n )\n }\n const record = {\n ...structuredClone(commit),\n result: structuredClone(input.finalization.result),\n } as OntologyCommitRecord\n this.state.commitsById.set(commitKey(commit.projectId, commit.id), record)\n this.state.commitTouches.set(this.state.commitsById.size, touches)\n this.state.commitIdByIdempotency.set(\n idempotencyKey(commit.projectId, commit.idempotencyKey),\n commit.id\n )\n const origin = ontologyCommitOriginSelector(commit.origin)\n if (origin) {\n this.state.commitIdByOrigin.set(commitOriginKey(commit.projectId, origin), commit.id)\n }\n this.releaseSession(session)\n return { commit: structuredClone(record) }\n }\n\n /** @internal Share the existing transaction/session fence with derived vector writes. */\n assertVectorSession(session: MaterializationSession, projectId: string, commitId?: string): void {\n const active = this.requireSession(session)\n if (\n active.header.commit.projectId !== projectId ||\n (commitId !== undefined && active.header.commit.id !== commitId)\n ) {\n throw new MaterializationValidationError(\n \"Vector mutation does not belong to this materialization session.\"\n )\n }\n }\n\n /** Begins a sealing step, and puts the work in canonical order the first time it seals. */\n private sealWork(session: SessionState, begin: (state: SessionState) => void): void {\n const sealed = session.workSealed\n begin(session)\n if (sealed) return\n session.applyWork.sort(comparePlanWork)\n session.cardinalityWork.sort(compareCardinalityWork)\n session.eventWork.sort(compareEventWork)\n }\n\n /** The fresh, fully planned plan a projection commit applies, with exactly its commit. */\n private requirePlan(header: MaterializationPlanHeader): InMemoryReplacementPlan {\n const { commit, plan: ref } = header\n const plan = ref\n ? this.state.replacementPlans.get(replacementPlanKey({ projectId: commit.projectId, ...ref }))\n : undefined\n if (!plan || commit.intent.kind !== \"projection\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"A plan-bound session needs the open plan of a projection candidate.\"\n )\n }\n if (plan.commitId !== commit.id || plan.committedAt !== commit.committedAt) {\n invalidCorrelation(\"A plan-bound session must begin with the commit its plan carries.\")\n }\n if (\n plan.watermark !== this.state.commitsById.size ||\n [...plan.identities.values()].some((identity) => identity.plannedRevision === null)\n ) {\n invalidCorrelation(\"A replacement plan applies only fully planned and just refreshed.\")\n }\n return plan\n }\n\n private requireSession(session: MaterializationSession): SessionState {\n const value = this.sessions.get(session.providerToken)\n if (\n !value ||\n !value.active ||\n !this.getTransactionToken() ||\n this.getTransactionToken() !== value.transactionToken\n ) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Materialization session is inactive.\"\n )\n }\n return value\n }\n\n private assertCommitAbsent(header: MaterializationPlanHeader): void {\n if (this.state.commitsById.has(commitKey(header.commit.projectId, header.commit.id))) {\n throw new MaterializationConflictError(\n \"idempotency\",\n `Ontology commit '${header.commit.id}' already exists.`\n )\n }\n if (\n this.state.commitIdByIdempotency.has(\n idempotencyKey(header.commit.projectId, header.commit.idempotencyKey)\n )\n ) {\n throw new MaterializationConflictError(\n \"idempotency\",\n \"Ontology idempotency key already exists.\"\n )\n }\n const origin = ontologyCommitOriginSelector(header.commit.origin)\n if (\n origin &&\n this.state.commitIdByOrigin.has(commitOriginKey(header.commit.projectId, origin))\n ) {\n throw new MaterializationConflictError(\n \"run-correlation\",\n \"Ontology commit origin already has an authoritative commit.\"\n )\n }\n }\n\n private assertSource(expected: ExpectedSourceRevision, projectId: string): void {\n const current = findActiveSourceMaterialization(\n this.state,\n projectId,\n expected.source.projectionId\n )\n if (\n (current?.materializationId ?? null) !== expected.activeMaterializationId ||\n (current?.lastCommitId ?? null) !== expected.lastCommitId\n ) {\n throw new MaterializationConflictError(\n \"projection-fence\",\n `Source '${expected.source.projectionId}' changed.`\n )\n }\n }\n\n private async assertObject(expected: ExpectedObjectRevision, projectId: string): Promise<void> {\n this.assertObjectSync(expected, projectId)\n }\n\n private assertObjectSync(expected: ExpectedObjectRevision, projectId: string): void {\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactObjectRow(\n projectId,\n expected.ref.objectTypeId,\n expected.ref.primaryId\n )\n assertExpectedObjectRevision(row ?? null, expected)\n }\n\n private async assertLink(expected: ExpectedLinkRevision, projectId: string): Promise<void> {\n this.assertLinkSync(expected, projectId)\n }\n\n private assertLinkSync(expected: ExpectedLinkRevision, projectId: string): void {\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactLinkRow(projectId, {\n sourceTypeId: expected.ref.source.objectTypeId,\n sourceId: expected.ref.source.primaryId,\n linkId: expected.ref.linkId,\n targetTypeId: expected.ref.target.objectTypeId,\n targetId: expected.ref.target.primaryId,\n })\n assertExpectedLinkRevision(row?.lastCommitId, expected)\n }\n\n private assertPoint(expected: ExpectedTimeseriesPointRevision, projectId: string): void {\n const point = getInMemoryTimeseriesMaterializerAdapter(this.timeseries).getExactPoint(\n projectId,\n expected.series,\n expected.at\n )\n if ((point?.lastCommitId ?? null) !== expected.lastCommitId) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(expected.series, expected.at)} changed.`\n )\n }\n }\n\n private uniqueHolders(\n session: SessionState,\n values: readonly UniqueValueRef[]\n ): ExactUniqueValueWrite[] {\n const adapter = getInMemoryObjectMaterializerAdapter(this.objects)\n const holders: ExactUniqueValueWrite[] = []\n for (const value of values) {\n const primaryId = adapter.getUniqueHolder(session.header.commit.projectId, value)\n if (primaryId !== null) holders.push({ ...value, primaryId })\n }\n return holders\n }\n\n private linkSlotState(\n session: SessionState,\n source: OntologyObjectRef,\n linkId: string\n ): MaterializationLinkScopeState {\n session.linkSlotStates ??= new Map()\n const key = linkScopeSortKey(source, linkId)\n const existing = session.linkSlotStates.get(key)\n if (existing) return structuredClone(existing)\n const computed = this.reader.linkSlotState(session.header.commit.projectId, source, linkId)\n session.linkSlotStates.set(key, computed)\n return structuredClone(computed)\n }\n\n private incidentLinkRefs(\n session: SessionState,\n objects: readonly OntologyObjectRef[]\n ): readonly OntologyLinkRef[] {\n if (objects.length === 0) return []\n session.incidentLinksByObject ??= this.reader.incidentLinkIndex(session.header.commit.projectId)\n const selected = new Map<string, OntologyLinkRef>()\n for (const object of objects) {\n for (const ref of session.incidentLinksByObject.get(objectRefKey(object)) ?? []) {\n selected.set(linkRefSortKey(ref), ref)\n }\n }\n return [...selected.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, ref]) => ref)\n }\n}\n",
|
|
38
|
+
"import {\n MaterializationConflictError,\n MaterializationValidationError,\n} from \"../../../materialization/errors\"\nimport type {\n ClaimedOntologyOutboxRow,\n ClaimOntologyOutboxInput,\n CompleteOntologyOutboxLeaseInput,\n OntologyOutboxStorage,\n OntologyOutboxSummary,\n PurgePublishedOntologyOutboxInput,\n RescheduleOntologyOutboxLeaseInput,\n SummarizeOntologyOutboxInput,\n} from \"../outbox\"\nimport { claimedOutboxRows, type OutboxEventContext } from \"../provider-work\"\nimport {\n assertNonblank,\n assertTimestamp,\n commitKey,\n type InMemoryExecutionReader,\n type InMemoryOntologyState,\n type InMemoryOutboxRow,\n insertBounded,\n outboxKey,\n} from \"./shared-state\"\n\nexport class InMemoryOntologyOutboxStorage implements OntologyOutboxStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>,\n private readonly readExecution: InMemoryExecutionReader\n ) {}\n\n async claim(input: ClaimOntologyOutboxInput): Promise<readonly ClaimedOntologyOutboxRow[]> {\n return this.runRootOperation(() => this.claimUnlocked(input))\n }\n\n private async claimUnlocked(\n input: ClaimOntologyOutboxInput\n ): Promise<readonly ClaimedOntologyOutboxRow[]> {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertPositiveLimit(input.limit)\n const now = assertTimestamp(input.now, \"Ontology outbox claim time\")\n const leaseExpiresAt = assertTimestamp(input.leaseExpiresAt, \"Ontology outbox lease expiry\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n if (leaseExpiresAt <= now) {\n throw new MaterializationValidationError(\n \"Ontology outbox lease expiry must be later than the claim time.\"\n )\n }\n const rows: InMemoryOutboxRow[] = []\n for (const row of this.state.outbox.values()) {\n if (row.projectId !== input.projectId) continue\n assertPairedLease(row)\n if (row.publishedAt !== null || Date.parse(row.availableAt) > now) continue\n if (row.leaseExpiresAt !== null && Date.parse(row.leaseExpiresAt) > now) continue\n insertBounded(rows, row, input.limit, compareClaimRows)\n }\n const claimed = rows.map((row) => ({\n ...row,\n attempts: row.attempts + 1,\n leaseId: input.leaseId,\n leaseExpiresAt: input.leaseExpiresAt,\n }))\n // Rebuilt before any lease is taken: a row that cannot be rebuilt leaves the outbox untouched.\n const contexts = new Map<string, OutboxEventContext>()\n for (const commitId of new Set(claimed.map((row) => row.commitId))) {\n const commit = this.state.commitsById.get(commitKey(input.projectId, commitId))\n const execution = commit && (await this.readExecution(input.projectId, commit.executionId))\n if (commit && execution) contexts.set(commitId, { commit, execution })\n }\n const records = claimedOutboxRows(structuredClone(claimed), (commitId) =>\n contexts.get(commitId)\n )\n for (const row of claimed) this.state.outbox.set(outboxKey(input.projectId, row.id), row)\n return records\n }\n\n async markPublished(input: CompleteOntologyOutboxLeaseInput): Promise<void> {\n await this.runRootOperation(() => this.markPublishedUnlocked(input))\n }\n\n private markPublishedUnlocked(input: CompleteOntologyOutboxLeaseInput): void {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n assertTimestamp(input.publishedAt, \"Ontology outbox publishedAt\")\n const rows = this.validateLeaseBatch(input.projectId, input.ids, input.leaseId)\n for (const [key, row] of rows) {\n this.state.outbox.set(key, {\n ...row,\n publishedAt: input.publishedAt,\n leaseId: null,\n leaseExpiresAt: null,\n })\n }\n }\n\n async reschedule(input: RescheduleOntologyOutboxLeaseInput): Promise<void> {\n await this.runRootOperation(() => this.rescheduleUnlocked(input))\n }\n\n private rescheduleUnlocked(input: RescheduleOntologyOutboxLeaseInput): void {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n assertTimestamp(input.availableAt, \"Ontology outbox availableAt\")\n const rows = this.validateLeaseBatch(input.projectId, input.ids, input.leaseId)\n for (const [key, row] of rows) {\n this.state.outbox.set(key, {\n ...row,\n availableAt: input.availableAt,\n lastFailure: input.failure === undefined ? row.lastFailure : structuredClone(input.failure),\n leaseId: null,\n leaseExpiresAt: null,\n })\n }\n }\n\n async purgePublished(input: PurgePublishedOntologyOutboxInput): Promise<number> {\n return this.runRootOperation(() => this.purgePublishedUnlocked(input))\n }\n\n async summarize(input: SummarizeOntologyOutboxInput): Promise<OntologyOutboxSummary> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n let pendingCount = 0\n let oldestPendingAt: string | null = null\n let retryingCount = 0\n let maxAttempts = 0\n\n for (const row of this.state.outbox.values()) {\n if (row.projectId !== input.projectId || row.publishedAt !== null) continue\n pendingCount += 1\n if (row.attempts > 0) retryingCount += 1\n maxAttempts = Math.max(maxAttempts, row.attempts)\n if (oldestPendingAt === null || row.createdAt < oldestPendingAt) {\n oldestPendingAt = row.createdAt\n }\n }\n\n return { pendingCount, oldestPendingAt, retryingCount, maxAttempts }\n })\n }\n\n private purgePublishedUnlocked(input: PurgePublishedOntologyOutboxInput): number {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertPositiveLimit(input.limit)\n const cutoff = assertTimestamp(input.publishedBefore, \"Ontology outbox purge cutoff\")\n const rows: [string, InMemoryOutboxRow][] = []\n for (const entry of this.state.outbox.entries()) {\n const [, row] = entry\n if (\n row.projectId !== input.projectId ||\n row.publishedAt === null ||\n Date.parse(row.publishedAt) >= cutoff\n ) {\n continue\n }\n insertBounded(rows, entry, input.limit, ([, left], [, right]) =>\n comparePublishedRows(left, right)\n )\n }\n for (const [key] of rows) this.state.outbox.delete(key)\n return rows.length\n }\n\n private requireLease(key: string, leaseId: string) {\n const row = this.state.outbox.get(key)\n if (!row || row.leaseId !== leaseId || row.leaseExpiresAt === null) {\n throw new MaterializationConflictError(\n \"outbox-lease\",\n \"Ontology outbox lease does not match.\"\n )\n }\n return row\n }\n\n private validateLeaseBatch(\n projectId: string,\n ids: readonly string[],\n leaseId: string\n ): readonly (readonly [string, ReturnType<InMemoryOntologyOutboxStorage[\"requireLease\"]>])[] {\n const seen = new Set<string>()\n return ids.map((id) => {\n assertNonblank(id, \"Ontology outbox event id\")\n if (seen.has(id)) {\n throw new MaterializationValidationError(\n `Ontology outbox lease batch repeats event '${id}'.`\n )\n }\n seen.add(id)\n const key = outboxKey(projectId, id)\n return [key, this.requireLease(key, leaseId)] as const\n })\n }\n}\n\n/**\n * Deterministic claim order.\n *\n * Every row of one commit shares `createdAt`, so `commitOrdinal` gives providers a stable batch\n * order. It correlates facts but does not promise broker delivery order: concurrent leases and\n * retries may publish later rows first.\n */\nfunction compareClaimRows(left: InMemoryOutboxRow, right: InMemoryOutboxRow): number {\n return (\n left.createdAt.localeCompare(right.createdAt) ||\n left.commitId.localeCompare(right.commitId) ||\n left.commitOrdinal - right.commitOrdinal\n )\n}\n\nfunction comparePublishedRows(left: InMemoryOutboxRow, right: InMemoryOutboxRow): number {\n return (\n (left.publishedAt ?? \"\").localeCompare(right.publishedAt ?? \"\") ||\n left.id.localeCompare(right.id)\n )\n}\n\nfunction assertPositiveLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new MaterializationValidationError(\"Ontology outbox limit must be positive.\")\n }\n}\n\nfunction assertPairedLease(row: {\n readonly leaseId: string | null\n readonly leaseExpiresAt: string | null\n}): void {\n if ((row.leaseId === null) !== (row.leaseExpiresAt === null)) {\n throw new MaterializationConflictError(\n \"outbox-lease\",\n \"Ontology outbox row has an unpaired lease lifecycle.\"\n )\n }\n}\n",
|
|
39
|
+
"import { stableJsonStringify } from \"../../../json\"\nimport { MaterializationValidationError } from \"../../../materialization/errors\"\nimport type { ProjectionExecution } from \"../../../materialization/model\"\nimport { projectionEntityKey } from \"../../../materialization/refs\"\nimport {\n assertSourceBeginInput as assertBeginInput,\n assertTimestamp as assertCanonicalTimestamp,\n assertSourceProject as assertProjectAndSource,\n assertSourceCandidateOwner,\n assertSourceExecutionIdentity,\n assertSourceStagedRow,\n assertSourceWriteIdentity as assertWriteIdentity,\n isExactStagingManifest,\n sourceConflict,\n sourceMaterializationIdentity,\n sourceStageRoots,\n} from \"../provider\"\nimport type {\n AbandonRunSourceMaterializationInput,\n AbandonSourceMaterializationCandidateInput,\n AbandonSourceMaterializationInput,\n ActiveOntologySource,\n AdoptedSourceMaterialization,\n AdoptSourceMaterializationInput,\n AssertSourceMaterializationExecution,\n BeginSourceMaterializationInput,\n CleanupTerminalSourceMaterializationsInput,\n CleanupTerminalSourceMaterializationsResult,\n GetActiveOntologySourceInput,\n ListActiveOntologySourcesInput,\n MarkSourceMaterializationReadyInput,\n OntologySourceRecord,\n OntologySourceStorage,\n PurgeAbandonedSourceMaterializationsInput,\n StageSourceAssertion,\n StageSourceRowsInput,\n StageSourceRowsResult,\n} from \"../sources\"\nimport { findActiveSourceMaterialization } from \"./materializations-state\"\nimport {\n assertNonblank,\n type InMemoryOntologyState,\n type InMemorySourceMaterialization,\n type InMemorySourceRoot,\n insertBounded,\n sourceMaterializationKey,\n sourceMaterializationRecord,\n} from \"./shared-state\"\n\nexport class InMemoryOntologySourceStorage implements OntologySourceStorage {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>,\n private readonly assertExecution: AssertSourceMaterializationExecution\n ) {}\n\n async beginMaterialization(\n input: BeginSourceMaterializationInput\n ): Promise<OntologySourceRecord> {\n return this.runRootOperation(async () => {\n assertBeginInput(input)\n await this.assertCurrentExecution(input)\n const key = sourceMaterializationKey(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n const existing = this.state.sourceMaterializations.get(key)\n if (existing) {\n if (isExactStagingManifest(sourceMaterializationRecord(existing), input)) {\n return sourceMaterializationRecord(existing)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' already exists with different identity or state.`\n )\n }\n\n const nonterminal = this.findRunCandidates(\n input.projectId,\n input.source.projectionId,\n input.execution.projectionRunId\n )\n if (nonterminal.length > 0) {\n throw sourceConflict(\n `Projection run '${input.execution.projectionRunId}' already has a nonterminal source materialization; adopt it before beginning another.`\n )\n }\n\n const materialization: InMemorySourceMaterialization = {\n projectId: input.projectId,\n source: structuredClone(input.source),\n materializationId: input.materializationId,\n projectionRunId: input.execution.projectionRunId,\n projectionKind: input.projectionKind,\n protocol: input.protocol,\n status: \"staging\",\n executionToken: input.execution.executionToken,\n datasetVersion: structuredClone(input.datasetVersion),\n projectionRevision: input.projectionRevision,\n ownershipHash: input.ownershipHash,\n ontologyRevision: input.ontologyRevision,\n ...(input.base ? { base: structuredClone(input.base) } : {}),\n rootCount: null,\n assertionCount: null,\n createdAt: input.createdAt,\n readyAt: null,\n activatedAt: null,\n terminalAt: null,\n lastCommitId: null,\n updatedAt: input.createdAt,\n rowsByEntity: new Map(),\n roots: new Map(),\n rootOrdinals: new Map(),\n ordinalRoots: new Map(),\n }\n this.state.sourceMaterializations.set(key, materialization)\n return sourceMaterializationRecord(materialization)\n })\n }\n\n async stageRows(input: StageSourceRowsInput): Promise<StageSourceRowsResult> {\n return this.runRootOperation(async () => {\n assertWriteIdentity(input)\n await this.assertCurrentExecution(input)\n const materialization = this.requireMaterialization(input)\n assertSourceCandidateOwner(sourceMaterializationRecord(materialization), input.execution)\n if (materialization.status !== \"staging\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' is '${materialization.status}' and cannot accept rows.`\n )\n }\n return stageRowsAtomically(materialization, input)\n })\n }\n\n async markReady(input: MarkSourceMaterializationReadyInput): Promise<OntologySourceRecord> {\n return this.runRootOperation(async () => {\n assertWriteIdentity(input)\n assertCanonicalTimestamp(input.readyAt, \"Source readyAt\")\n assertCount(input.rootCount, \"Source root count\")\n assertCount(input.assertionCount, \"Source assertion count\")\n await this.assertCurrentExecution(input)\n const materialization = this.requireMaterialization(input)\n assertSourceCandidateOwner(sourceMaterializationRecord(materialization), input.execution)\n\n if (materialization.status === \"ready\") {\n if (\n materialization.rootCount === input.rootCount &&\n materialization.assertionCount === input.assertionCount &&\n materialization.readyAt === input.readyAt\n ) {\n return sourceMaterializationRecord(materialization)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' was marked ready with different counts or time.`\n )\n }\n if (materialization.status !== \"staging\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' cannot transition from '${materialization.status}' to 'ready'.`\n )\n }\n assertNotBefore(input.readyAt, materialization.createdAt, \"Source readyAt\", \"createdAt\")\n assertReadyCounts(materialization, input.rootCount, input.assertionCount)\n\n const ready: InMemorySourceMaterialization = {\n ...materialization,\n status: \"ready\",\n rootCount: input.rootCount,\n assertionCount: input.assertionCount,\n readyAt: input.readyAt,\n updatedAt: input.readyAt,\n }\n this.state.sourceMaterializations.set(\n sourceMaterializationKey(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n ),\n ready\n )\n return sourceMaterializationRecord(ready)\n })\n }\n\n async getActive(input: GetActiveOntologySourceInput): Promise<OntologySourceRecord | null> {\n return this.runRootOperation(() => {\n assertProjectAndSource(input)\n const active = findActiveSourceMaterialization(\n this.state,\n input.projectId,\n input.source.projectionId\n )\n return active ? sourceMaterializationRecord(active) : null\n })\n }\n\n async listActive(\n input: ListActiveOntologySourcesInput\n ): Promise<readonly ActiveOntologySource[]> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Source project id\")\n\n const active: ActiveOntologySource[] = []\n for (const materialization of this.state.sourceMaterializations.values()) {\n if (materialization.projectId !== input.projectId) continue\n if (materialization.status !== \"active\") continue\n active.push({\n source: { projectionId: materialization.source.projectionId },\n datasetVersion: { ...materialization.datasetVersion },\n projectionRevision: materialization.projectionRevision,\n })\n }\n\n return active\n })\n }\n\n async adopt(\n input: AdoptSourceMaterializationInput\n ): Promise<AdoptedSourceMaterialization | null> {\n return this.runRootOperation(async () => {\n assertProjectAndSource(input)\n assertSourceExecutionIdentity(input.execution.projectionRunId, input.execution.executionToken)\n assertCanonicalTimestamp(input.adoptedAt, \"Source adoptedAt\")\n await this.assertCurrentExecution(input)\n const [candidate, ...others] = this.findRunCandidates(\n input.projectId,\n input.source.projectionId,\n input.execution.projectionRunId\n )\n if (!candidate) return null\n if (others.length > 0) throw multipleRunCandidates(input.execution.projectionRunId)\n const [key, materialization] = candidate\n const adopted: InMemorySourceMaterialization = {\n ...materialization,\n executionToken: input.execution.executionToken,\n // Workers' clocks differ; adoption never moves the record back in time.\n updatedAt:\n input.adoptedAt > materialization.updatedAt ? input.adoptedAt : materialization.updatedAt,\n }\n this.state.sourceMaterializations.set(key, adopted)\n return {\n record: sourceMaterializationRecord(adopted),\n resumeStagingOrdinal:\n adopted.status === \"ready\"\n ? (adopted.rootCount ?? 0)\n : Math.max(0, ...adopted.ordinalRoots.keys()),\n }\n })\n }\n\n async abandon(input: AbandonSourceMaterializationCandidateInput): Promise<OntologySourceRecord>\n async abandon(input: AbandonRunSourceMaterializationInput): Promise<OntologySourceRecord | null>\n async abandon(input: AbandonSourceMaterializationInput): Promise<OntologySourceRecord | null> {\n return this.runRootOperation(async () => {\n assertProjectAndSource(input)\n assertSourceExecutionIdentity(input.execution.projectionRunId, input.execution.executionToken)\n assertCanonicalTimestamp(input.abandonedAt, \"Source abandonedAt\")\n await this.assertCurrentExecution(input)\n return input.kind === \"candidate\"\n ? this.abandonCandidate(input)\n : this.abandonRunCandidate(input)\n })\n }\n\n async cleanupTerminal(\n input: CleanupTerminalSourceMaterializationsInput\n ): Promise<CleanupTerminalSourceMaterializationsResult> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Terminal source cleanup project id\")\n assertCanonicalTimestamp(input.terminalBefore, \"Terminal source cleanup cutoff\")\n assertCleanupLimit(input.limit)\n\n const candidates: [string, InMemorySourceMaterialization][] = []\n for (const entry of this.state.sourceMaterializations.entries()) {\n const materialization = entry[1]\n if (\n materialization.projectId !== input.projectId ||\n materialization.status !== \"superseded\" ||\n materialization.terminalAt === null ||\n materialization.terminalAt >= input.terminalBefore\n ) {\n continue\n }\n if (\n materialization.roots.size > 0 &&\n ![...materialization.roots.values()].some(\n (root) =>\n !root.active && root.retiredAt !== null && root.retiredAt < input.terminalBefore\n )\n )\n continue\n insertBounded(candidates, entry, input.limit, compareTerminalMaterializations)\n }\n\n return this.deleteRetiredRoots(\n candidates,\n input.limit,\n (root) => !root.active && root.retiredAt !== null && root.retiredAt < input.terminalBefore\n )\n })\n }\n\n async purgeAbandoned(\n input: PurgeAbandonedSourceMaterializationsInput\n ): Promise<CleanupTerminalSourceMaterializationsResult> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Abandoned source purge project id\")\n assertCleanupLimit(input.limit)\n const abandoned = [...this.state.sourceMaterializations.entries()]\n .filter(\n ([, materialization]) =>\n materialization.projectId === input.projectId && materialization.status === \"abandoned\"\n )\n .sort(compareTerminalMaterializations)\n return this.deleteRetiredRoots(abandoned, input.limit, () => true)\n })\n }\n\n private deleteRetiredRoots(\n candidates: readonly [string, InMemorySourceMaterialization][],\n limit: number,\n retired: (root: InMemorySourceRoot) => boolean\n ): CleanupTerminalSourceMaterializationsResult {\n let remaining = limit\n let rowsDeleted = 0\n let materializationsDeleted = 0\n for (const [key, candidate] of candidates) {\n if (remaining === 0) break\n const current = this.state.sourceMaterializations.get(key)\n if (current !== candidate) continue\n current.rootOrdinals.clear()\n current.ordinalRoots.clear()\n for (const [rootKey, root] of current.roots) {\n if (remaining === 0) break\n if (!retired(root)) continue\n for (const entityKey of root.entityKeys) {\n if (remaining === 0) break\n current.rowsByEntity.delete(entityKey)\n root.entityKeys.delete(entityKey)\n rowsDeleted += 1\n remaining -= 1\n }\n if (root.entityKeys.size === 0 && remaining > 0) {\n current.roots.delete(rootKey)\n current.rootOrdinals.delete(rootKey)\n current.ordinalRoots.delete(root.stagingOrdinal)\n rowsDeleted += 1\n remaining -= 1\n }\n }\n if (current.roots.size === 0 && current.rowsByEntity.size === 0 && remaining > 0) {\n this.state.sourceMaterializations.delete(key)\n materializationsDeleted += 1\n remaining -= 1\n }\n }\n return { rowsDeleted, materializationsDeleted }\n }\n\n private async assertCurrentExecution(\n input:\n | BeginSourceMaterializationInput\n | {\n readonly projectId: string\n readonly source: BeginSourceMaterializationInput[\"source\"]\n readonly execution: ProjectionExecution\n }\n ): Promise<void> {\n await this.assertExecution({\n projectId: input.projectId,\n source: input.source,\n execution: input.execution,\n ...(\"projectionKind\" in input ? { identity: sourceMaterializationIdentity(input) } : {}),\n })\n }\n\n private requireMaterialization(input: {\n readonly projectId: string\n readonly source: BeginSourceMaterializationInput[\"source\"]\n readonly materializationId: string\n }): InMemorySourceMaterialization {\n const materialization = this.state.sourceMaterializations.get(\n sourceMaterializationKey(input.projectId, input.source.projectionId, input.materializationId)\n )\n if (!materialization) {\n throw sourceConflict(`Source materialization '${input.materializationId}' does not exist.`)\n }\n return materialization\n }\n\n private abandonCandidate(\n input: AbandonSourceMaterializationCandidateInput\n ): OntologySourceRecord {\n const materialization = this.requireMaterialization(input)\n if (materialization.status === \"abandoned\") {\n if (\n materialization.projectionRunId === input.execution.projectionRunId &&\n materialization.terminalAt === input.abandonedAt\n ) {\n return sourceMaterializationRecord(materialization)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' was abandoned by another execution or at another time.`\n )\n }\n assertSourceCandidateOwner(sourceMaterializationRecord(materialization), input.execution)\n if (materialization.status !== \"staging\" && materialization.status !== \"ready\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' cannot transition from '${materialization.status}' to 'abandoned'.`\n )\n }\n return this.transitionToAbandoned(materialization, input.abandonedAt)\n }\n\n private abandonRunCandidate(\n input: AbandonRunSourceMaterializationInput\n ): OntologySourceRecord | null {\n const candidates = this.findRunCandidates(\n input.projectId,\n input.source.projectionId,\n input.execution.projectionRunId\n )\n if (candidates.length > 1) throw multipleRunCandidates(input.execution.projectionRunId)\n const candidate = candidates[0]?.[1]\n return candidate ? this.transitionToAbandoned(candidate, input.abandonedAt) : null\n }\n\n private transitionToAbandoned(\n materialization: InMemorySourceMaterialization,\n abandonedAt: string\n ): OntologySourceRecord {\n assertNotBefore(abandonedAt, materialization.createdAt, \"Source abandonedAt\", \"createdAt\")\n if (materialization.readyAt !== null) {\n assertNotBefore(abandonedAt, materialization.readyAt, \"Source abandonedAt\", \"readyAt\")\n }\n for (const root of materialization.roots.values()) root.retiredAt = abandonedAt\n const abandoned: InMemorySourceMaterialization = {\n ...materialization,\n status: \"abandoned\",\n executionToken: null,\n terminalAt: abandonedAt,\n updatedAt: abandonedAt,\n }\n const key = sourceMaterializationKey(\n materialization.projectId,\n materialization.source.projectionId,\n materialization.materializationId\n )\n this.state.sourceMaterializations.set(key, abandoned)\n // Nothing applies an abandoned candidate's plan.\n this.state.replacementPlans.delete(key)\n return sourceMaterializationRecord(abandoned)\n }\n\n private findRunCandidates(\n projectId: string,\n sourceId: string,\n projectionRunId: string\n ): [string, InMemorySourceMaterialization][] {\n return [...this.state.sourceMaterializations.entries()].filter(\n ([, materialization]) =>\n materialization.projectId === projectId &&\n materialization.source.projectionId === sourceId &&\n materialization.projectionRunId === projectionRunId &&\n (materialization.status === \"staging\" || materialization.status === \"ready\")\n )\n }\n}\n\nfunction stageRowsAtomically(\n materialization: InMemorySourceMaterialization,\n input: StageSourceRowsInput\n): StageSourceRowsResult {\n let inserted = 0\n let unchanged = 0\n const newRows = new Map<string, StageSourceRowsInput[\"rows\"][number]>()\n const newRootOrdinals = new Map<string, number>()\n const newOrdinalRoots = new Map<number, string>()\n const roots = sourceStageRoots(materialization.projectionKind, input)\n if (!materialization.base && roots.some((root) => root.deleted)) {\n throw new MaterializationValidationError(\"Root deletions require a source delta base.\")\n }\n for (const root of roots) {\n const previous = materialization.roots.get(root.rootKey)\n const otherRoot = materialization.ordinalRoots.get(root.stagingOrdinal)\n if (\n (previous &&\n (previous.deleted !== root.deleted || previous.stagingOrdinal !== root.stagingOrdinal)) ||\n (otherRoot !== undefined && otherRoot !== root.rootKey)\n ) {\n throw new MaterializationValidationError(\n \"Source materialization repeats root or stream ordinal with different content.\"\n )\n }\n newRootOrdinals.set(root.rootKey, root.stagingOrdinal)\n newOrdinalRoots.set(root.stagingOrdinal, root.rootKey)\n }\n for (const row of input.rows) {\n assertSourceStagedRow(materialization.projectionKind, row)\n\n const rootKey = projectionEntityKey(row.root)\n const existingOrdinal =\n materialization.rootOrdinals.get(rootKey) ?? newRootOrdinals.get(rootKey)\n if (existingOrdinal !== undefined && existingOrdinal !== row.stagingOrdinal) {\n throw new MaterializationValidationError(\n `Source materialization repeats root ${rootKey} at a different stream ordinal.`\n )\n }\n const existingRoot =\n materialization.ordinalRoots.get(row.stagingOrdinal) ??\n newOrdinalRoots.get(row.stagingOrdinal)\n if (existingRoot !== undefined && existingRoot !== rootKey) {\n throw new MaterializationValidationError(\n `Source materialization repeats stream ordinal ${row.stagingOrdinal} for another root.`\n )\n }\n\n const entityKey = projectionEntityKey(row.assertion)\n const existing = materialization.rowsByEntity.get(entityKey) ?? newRows.get(entityKey)\n if (existing) {\n if (stableJsonStringify(existing) === stableJsonStringify(row)) {\n unchanged += 1\n continue\n }\n throw new MaterializationValidationError(\n `Source materialization repeats asserted entity ${entityKey}.`\n )\n }\n\n newRootOrdinals.set(rootKey, row.stagingOrdinal)\n newOrdinalRoots.set(row.stagingOrdinal, rootKey)\n newRows.set(entityKey, structuredClone(row))\n inserted += 1\n }\n\n for (const [rootKey, ordinal] of newRootOrdinals) {\n materialization.rootOrdinals.set(rootKey, ordinal)\n }\n for (const [ordinal, rootKey] of newOrdinalRoots) {\n materialization.ordinalRoots.set(ordinal, rootKey)\n }\n for (const root of roots) {\n if (!materialization.roots.has(root.rootKey))\n materialization.roots.set(root.rootKey, {\n root: structuredClone(root.root),\n stagingOrdinal: root.stagingOrdinal,\n deleted: root.deleted,\n entityKeys: new Set(),\n active: false,\n retiredAt: null,\n })\n }\n for (const [entityKey, row] of newRows) {\n materialization.rowsByEntity.set(entityKey, row)\n materialization.roots.get(projectionEntityKey(row.root))!.entityKeys.add(entityKey)\n }\n return { inserted, unchanged }\n}\n\nfunction assertReadyCounts(\n materialization: InMemorySourceMaterialization,\n rootCount: number,\n assertionCount: number\n): void {\n if (\n materialization.rootOrdinals.size !== rootCount ||\n materialization.ordinalRoots.size !== rootCount ||\n materialization.rowsByEntity.size !== assertionCount\n ) {\n throw new MaterializationValidationError(\n \"Source ready counts do not match the staged roots and assertions.\"\n )\n }\n for (let ordinal = 0; ordinal < rootCount; ordinal += 1) {\n if (!materialization.ordinalRoots.has(ordinal)) {\n throw new MaterializationValidationError(\n `Source staging ordinals must be contiguous from zero; missing ${ordinal}.`\n )\n }\n }\n assertReadyTopology(materialization)\n}\n\nfunction assertReadyTopology(materialization: InMemorySourceMaterialization): void {\n const rowsByRoot = new Map<string, StageSourceAssertion[]>()\n for (const row of materialization.rowsByEntity.values()) {\n const rootKey = projectionEntityKey(row.root)\n const rows = rowsByRoot.get(rootKey) ?? []\n rows.push(row)\n rowsByRoot.set(rootKey, rows)\n }\n\n for (const rootKey of materialization.rootOrdinals.keys()) {\n const rows = rowsByRoot.get(rootKey) ?? []\n if (materialization.roots.get(rootKey)?.deleted) {\n if (rows.length > 0)\n throw new MaterializationValidationError(\"Deleted source roots cannot contain assertions.\")\n continue\n }\n const first = rows[0]\n if (!first) {\n throw new MaterializationValidationError(`Source root ${rootKey} has no staged assertions.`)\n }\n const root = first.root\n\n if (materialization.projectionKind === \"link\") {\n if (\n rows.length !== 1 ||\n root.kind !== \"link\" ||\n first.assertion.kind !== \"link\" ||\n projectionEntityKey(first.assertion) !== rootKey\n ) {\n throw new MaterializationValidationError(\n `Link projection root ${rootKey} must contain exactly its matching link assertion.`\n )\n }\n continue\n }\n\n if (root.kind !== \"object\") {\n throw new MaterializationValidationError(\n `Object projection root ${rootKey} must be an object.`\n )\n }\n const matchingObjects = rows.filter(\n (row) => row.assertion.kind === \"object\" && projectionEntityKey(row.assertion) === rootKey\n )\n const hasForeignAssertion = rows.some((row) => {\n if (row.assertion.kind === \"object\") return projectionEntityKey(row.assertion) !== rootKey\n return projectionEntityKey({ kind: \"object\", ref: row.assertion.ref.source }) !== rootKey\n })\n if (matchingObjects.length !== 1 || hasForeignAssertion) {\n throw new MaterializationValidationError(\n `Object projection root ${rootKey} must contain exactly its matching object assertion plus links sourced from that root.`\n )\n }\n }\n}\n\nfunction assertCount(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new MaterializationValidationError(`${label} must be a nonnegative safe integer.`)\n }\n}\n\nfunction assertNotBefore(\n value: string,\n minimum: string,\n label: string,\n minimumLabel: string\n): void {\n if (value < minimum) {\n throw new MaterializationValidationError(`${label} cannot precede source ${minimumLabel}.`)\n }\n}\n\nfunction assertCleanupLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new MaterializationValidationError(\n \"Terminal source cleanup limit must be a positive safe integer.\"\n )\n }\n}\n\nfunction multipleRunCandidates(projectionRunId: string) {\n return sourceConflict(\n `Projection run '${projectionRunId}' has multiple nonterminal source materializations.`\n )\n}\n\nfunction compareTerminalMaterializations(\n [, left]: readonly [string, InMemorySourceMaterialization],\n [, right]: readonly [string, InMemorySourceMaterialization]\n): number {\n return (\n (left.terminalAt ?? \"\").localeCompare(right.terminalAt ?? \"\") ||\n left.source.projectionId.localeCompare(right.source.projectionId) ||\n left.materializationId.localeCompare(right.materializationId)\n )\n}\n",
|
|
40
|
+
"import { MaterializationConflictError } from \"../../../materialization/errors\"\nimport type { OntologyLinkRef, OntologyObjectRef } from \"../../../materialization/model\"\nimport {\n linkRefKey,\n linkRefSortKey,\n linkScopeKey,\n linkScopeSortKey,\n objectRefKey,\n projectionEntityKey,\n} from \"../../../materialization/refs\"\nimport {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport type { ObjectLinkRow } from \"../../objects/types\"\nimport {\n getInMemoryTimeseriesMaterializerAdapter,\n type InMemoryTimeseriesStorage,\n} from \"../../timeseries/store\"\nimport type {\n MaterializationLinkScopeRevision,\n MaterializationLinkScopeState,\n MaterializationLinkState,\n MaterializationObjectState,\n StoredTelemetryPoint,\n} from \"../materializations\"\nimport { appendScopeSnapshot, finishScopeAccumulator, startScopeAccumulator } from \"../provider\"\nimport type {\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n StoredSourceObjectAssertion,\n} from \"../sources\"\nimport {\n linkRef,\n linkSnapshot,\n objectSnapshot,\n publicLinkOverride,\n publicLinkSlotOverride,\n publicObjectOverride,\n storedPoint,\n} from \"./materializations-state\"\nimport {\n type InMemoryOntologyState,\n type InMemoryOntologyStorageTestHooks,\n projectEntityKey,\n} from \"./shared-state\"\n\n/** Reads one project's current ontology state for materialization sessions and plans. */\nexport class InMemoryMaterializationStateReader {\n constructor(\n private readonly state: InMemoryOntologyState,\n private readonly objects: InMemoryObjectStorage,\n private readonly timeseries: InMemoryTimeseriesStorage,\n private readonly hooks: InMemoryOntologyStorageTestHooks = {}\n ) {}\n\n async objectState(\n projectId: string,\n ref: OntologyObjectRef\n ): Promise<MaterializationObjectState> {\n const row = await this.objects.getByPrimaryId({\n projectId,\n objectTypeId: ref.objectTypeId,\n primaryId: ref.primaryId,\n })\n return {\n ref: structuredClone(ref),\n source: this.findActiveObjectSource(projectId, ref),\n override: structuredClone(\n publicObjectOverride(\n this.state.objectOverrides.get(projectEntityKey(projectId, objectRefKey(ref)))\n )\n ),\n effective: row ? objectSnapshot(row) : null,\n latestTelemetry: getInMemoryTimeseriesMaterializerAdapter(this.timeseries)\n .listLatestForObject(projectId, ref.objectTypeId, ref.primaryId)\n .map(storedPoint),\n }\n }\n\n latestTelemetry(projectId: string, ref: OntologyObjectRef): StoredTelemetryPoint[] {\n return getInMemoryTimeseriesMaterializerAdapter(this.timeseries)\n .listLatestForObject(projectId, ref.objectTypeId, ref.primaryId)\n .map(storedPoint)\n }\n\n async linkState(projectId: string, ref: OntologyLinkRef): Promise<MaterializationLinkState> {\n const row = getInMemoryObjectMaterializerAdapter(this.objects).getExactLinkRow(projectId, {\n sourceTypeId: ref.source.objectTypeId,\n sourceId: ref.source.primaryId,\n linkId: ref.linkId,\n targetTypeId: ref.target.objectTypeId,\n targetId: ref.target.primaryId,\n })\n return {\n ref: structuredClone(ref),\n source: this.findActiveLinkSource(projectId, ref),\n override: structuredClone(\n publicLinkOverride(\n this.state.linkOverrides.get(projectEntityKey(projectId, linkRefKey(ref)))\n )\n ),\n slotOverride: structuredClone(\n publicLinkSlotOverride(\n this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(ref.source, ref.linkId))\n )\n )\n ),\n effective: row ? linkSnapshot(row) : null,\n }\n }\n\n linkSlotState(\n projectId: string,\n source: OntologyObjectRef,\n linkId: string\n ): MaterializationLinkScopeState {\n const value = this.effectiveLinkScope(projectId, source, linkId)\n return {\n ...value,\n sourceAssertion: this.findActiveLinkScopeSource(projectId, source, linkId),\n override: structuredClone(\n publicLinkSlotOverride(\n this.state.linkSlotOverrides.get(\n projectEntityKey(projectId, linkScopeKey(source, linkId))\n )\n )\n ),\n }\n }\n\n effectiveLinkScope(\n projectId: string,\n source: OntologyObjectRef,\n linkId: string\n ): MaterializationLinkScopeRevision & Pick<MaterializationLinkScopeState, \"effective\"> {\n const rows: ObjectLinkRow[] = []\n getInMemoryObjectMaterializerAdapter(this.objects).visitExactScopeLinks(\n projectId,\n source.objectTypeId,\n source.primaryId,\n linkId,\n (row) => rows.push(row)\n )\n rows.sort((left, right) =>\n linkRefSortKey(linkRef(left)).localeCompare(linkRefSortKey(linkRef(right)))\n )\n const accumulator = startScopeAccumulator(source, linkId)\n for (let offset = 0; offset < rows.length; offset += 1_000) {\n const page = rows.slice(offset, offset + 1_000)\n this.hooks.observeBuffer?.(\"state.link-scope.page\", page.length)\n for (const row of page) {\n appendScopeSnapshot(accumulator, linkSnapshot(row))\n }\n }\n const effective = rows.length === 1 ? linkSnapshot(rows[0]!) : null\n return {\n ...finishScopeAccumulator(accumulator),\n effective,\n }\n }\n\n findActiveLinkScopeSource(\n projectId: string,\n source: OntologyObjectRef,\n linkId: string\n ): StoredSourceLinkAssertion | null {\n const rows = this.state.activeSourceLinkScopes.get(\n projectEntityKey(projectId, linkScopeSortKey(source, linkId))\n )\n if (rows && rows.size > 1)\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Multiple active source links assert cardinality-one scope '${source.objectTypeId}.${linkId}'.`\n )\n return structuredClone(rows?.values().next().value ?? null)\n }\n\n findActiveObjectSource(\n projectId: string,\n ref: OntologyObjectRef\n ): StoredSourceObjectAssertion | null {\n const found = this.findActiveSource(projectId, projectionEntityKey({ kind: \"object\", ref }))\n return found?.assertion.kind === \"object\" ? (found as StoredSourceObjectAssertion) : null\n }\n\n findActiveLinkSource(projectId: string, ref: OntologyLinkRef): StoredSourceLinkAssertion | null {\n const found = this.findActiveSource(projectId, projectionEntityKey({ kind: \"link\", ref }))\n return found?.assertion.kind === \"link\" ? (found as StoredSourceLinkAssertion) : null\n }\n\n findActiveSource(projectId: string, entityKey: string): StoredSourceAssertion | null {\n const rows = this.state.activeSourceRows.get(projectEntityKey(projectId, entityKey))\n if (rows && rows.size > 1)\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Multiple active sources assert ${entityKey}.`\n )\n return structuredClone(rows?.values().next().value ?? null)\n }\n\n incidentLinkIndex(projectId: string): Map<string, readonly OntologyLinkRef[]> {\n const mutable = new Map<string, Map<string, OntologyLinkRef>>()\n const consider = (ref: OntologyLinkRef): void => {\n const sortKey = linkRefSortKey(ref)\n for (const endpoint of [ref.source, ref.target]) {\n const key = objectRefKey(endpoint)\n const links = mutable.get(key) ?? new Map<string, OntologyLinkRef>()\n links.set(sortKey, structuredClone(ref))\n mutable.set(key, links)\n }\n }\n getInMemoryObjectMaterializerAdapter(this.objects).visitExactLinks(projectId, (row) =>\n consider(linkRef(row))\n )\n for (const override of this.state.linkOverrides.values()) {\n if (override.projectId === projectId) consider(override.ref)\n }\n for (const override of this.state.linkSlotOverrides.values()) {\n if (override.projectId !== projectId) continue\n consider({\n source: override.ref.source,\n linkId: override.ref.linkId,\n target: override.value.target,\n })\n }\n for (const [scopeKey, rows] of this.state.activeSourceLinkScopes) {\n if (JSON.parse(scopeKey)[0] !== projectId) continue\n for (const row of rows.values()) {\n if (row.assertion.kind === \"link\") consider(row.assertion.ref)\n }\n }\n const index = new Map<string, readonly OntologyLinkRef[]>()\n for (const [objectKey, refs] of mutable) {\n index.set(\n objectKey,\n [...refs.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([, ref]) => ref)\n )\n }\n return index\n }\n}\n",
|
|
41
|
+
"import type { OntologyStorage } from \"..\"\nimport type { InMemoryOntologyState, InMemoryOntologyStorageTestHooks } from \"./shared-state\"\n\nexport interface InMemoryOntologyStorageTestingAdapter {\n setTestHooks(hooks: InMemoryOntologyStorageTestHooks): void\n snapshot(): InMemoryOntologyState\n}\n\nconst testingAdapters = new WeakMap<object, InMemoryOntologyStorageTestingAdapter>()\n\nexport function registerInMemoryOntologyStorageTestingAdapter(\n storage: OntologyStorage,\n adapter: InMemoryOntologyStorageTestingAdapter\n): void {\n testingAdapters.set(storage, adapter)\n}\n\n/** @internal Relative test-only access; intentionally absent from every package barrel. */\nexport function getInMemoryOntologyStorageTestingAdapter(\n storage: OntologyStorage\n): InMemoryOntologyStorageTestingAdapter {\n const adapter = testingAdapters.get(storage)\n if (!adapter) {\n throw new Error(\"[Sixb] In-memory ontology storage testing adapter is unavailable.\")\n }\n return adapter\n}\n\nexport type { InMemoryOntologyStorageTestHooks } from \"./shared-state\"\n",
|
|
42
|
+
"import {\n getInMemoryObjectMaterializerAdapter,\n type InMemoryObjectStorage,\n} from \"../../objects/in-memory\"\nimport type {\n OntologyUniqueValueStorage,\n PreparedUniqueProperty,\n UniqueValueEntry,\n} from \"../unique-values\"\n\n/** Unique values live with the in-memory objects, so a transaction snapshot covers both. */\nexport class InMemoryOntologyUniqueValueStorage implements OntologyUniqueValueStorage {\n constructor(\n private readonly objects: InMemoryObjectStorage,\n private readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n ) {}\n\n /** In-memory transactions already run one at a time. */\n async lockPreparation(_input: { readonly projectId: string }): Promise<void> {}\n\n async listPrepared(input: {\n readonly projectId: string\n }): Promise<readonly PreparedUniqueProperty[]> {\n return this.runRootOperation(() => this.adapter().listPreparedUniqueProperties(input.projectId))\n }\n\n async clear(input: {\n readonly projectId: string\n readonly objectTypeId: string\n readonly propertyId: string\n }): Promise<void> {\n await this.runRootOperation(() =>\n this.adapter().clearUniqueProperty(input.projectId, input.objectTypeId, input.propertyId)\n )\n }\n\n async insert(input: {\n readonly projectId: string\n readonly objectTypeId: string\n readonly propertyId: string\n readonly entries: readonly UniqueValueEntry[]\n }): Promise<void> {\n await this.runRootOperation(() =>\n this.adapter().insertUniqueValues(\n input.projectId,\n input.objectTypeId,\n input.propertyId,\n input.entries\n )\n )\n }\n\n async markPrepared(\n input: PreparedUniqueProperty & { readonly projectId: string; readonly preparedAt: string }\n ): Promise<void> {\n await this.runRootOperation(() => this.adapter().markUniquePropertyPrepared(input))\n }\n\n private adapter() {\n return getInMemoryObjectMaterializerAdapter(this.objects)\n }\n}\n",
|
|
43
|
+
"import type { MaterializationSession } from \"../materializations\"\nimport type { OntologyVectorIndexingStorage, VectorIndexingWork } from \"../vector-indexing\"\n\nexport class InMemoryVectorIndexingStorage implements OntologyVectorIndexingStorage {\n constructor(\n private readonly state: Map<\n string,\n VectorIndexingWork & { projectId: string; dispatchAt: string }\n >,\n private readonly assertSession: (session: MaterializationSession, projectId: string) => void,\n private readonly run: <T>(fn: () => T) => Promise<T>\n ) {}\n\n async schedule(input: Parameters<OntologyVectorIndexingStorage[\"schedule\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n if (input.deleted.length) {\n const deleted = new Set(\n input.deleted.map((ref) => JSON.stringify([ref.objectTypeId, ref.primaryId]))\n )\n for (const [key, work] of this.state) {\n if (\n work.projectId === input.projectId &&\n deleted.has(JSON.stringify([work.ref.objectTypeId, work.ref.primaryId]))\n )\n this.state.delete(key)\n }\n }\n for (const request of input.requests) {\n const key = JSON.stringify([\n input.projectId,\n request.ref.objectTypeId,\n request.ref.primaryId,\n request.profile,\n ])\n this.state.set(\n key,\n structuredClone({\n ...request,\n projectId: input.projectId,\n status: \"pending\",\n availableAt: input.availableAt,\n dispatchAt: input.availableAt,\n })\n )\n }\n }\n\n async complete(input: Parameters<OntologyVectorIndexingStorage[\"complete\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n for (const entry of input.entries) {\n const key = JSON.stringify([\n input.projectId,\n entry.ref.objectTypeId,\n entry.ref.primaryId,\n entry.profile,\n ])\n const work = this.state.get(key)\n if (\n work?.configuration === entry.configuration &&\n work.sourceFingerprint === entry.sourceFingerprint\n ) {\n this.state.delete(key)\n }\n }\n }\n\n async dispatched(input: Parameters<OntologyVectorIndexingStorage[\"dispatched\"]>[0]) {\n await this.run(() => {\n for (const [key, work] of this.state)\n if (work.projectId === input.projectId && input.ids.includes(work.id))\n this.state.set(key, { ...work, dispatchAt: input.nextDispatchAt })\n })\n }\n async get(input: Parameters<OntologyVectorIndexingStorage[\"get\"]>[0]) {\n return this.run(() =>\n structuredClone(\n [...this.state.values()].find(\n (work) => work.projectId === input.projectId && work.id === input.id\n ) ?? null\n )\n )\n }\n\n async getBatch(input: Parameters<OntologyVectorIndexingStorage[\"getBatch\"]>[0]) {\n return this.run(() =>\n structuredClone(\n [...this.state.values()]\n .filter((work) => work.projectId === input.projectId && work.batchId === input.batchId)\n .sort((a, b) => a.id.localeCompare(b.id))\n )\n )\n }\n\n async getBatchMember(input: Parameters<OntologyVectorIndexingStorage[\"getBatchMember\"]>[0]) {\n return this.run(() => {\n const work = this.state.get(\n JSON.stringify([\n input.projectId,\n input.ref.objectTypeId,\n input.ref.primaryId,\n input.profile,\n ])\n )\n return work?.batchId === input.batchId ? structuredClone(work) : null\n })\n }\n\n async updateBatch(input: Parameters<OntologyVectorIndexingStorage[\"updateBatch\"]>[0]) {\n return this.run(() => {\n const updates = new Map(input.updates.map((update) => [update.id, update]))\n const matches = [...this.state.entries()].filter(\n ([, work]) =>\n work.projectId === input.projectId && updates.get(work.id)?.expectedStatus === work.status\n )\n if (input.requireAll && matches.length !== input.updates.length) return false\n for (const [key, work] of matches) {\n const update = updates.get(work.id)!\n this.state.set(\n key,\n structuredClone({\n ...work,\n status: update.status,\n availableAt: update.availableAt,\n values: update.values ?? work.values,\n error: update.error,\n })\n )\n }\n return true\n })\n }\n\n async listDue(input: Parameters<OntologyVectorIndexingStorage[\"listDue\"]>[0]) {\n return this.run(() =>\n [...this.state.values()]\n .filter(\n (work) =>\n work.projectId === input.projectId &&\n work.status !== \"failed\" &&\n work.dispatchAt <= input.now\n )\n .sort((a, b) => a.dispatchAt.localeCompare(b.dispatchAt) || a.id.localeCompare(b.id))\n .slice(0, input.limit)\n .map(({ values: _values, ...work }) => structuredClone(work))\n )\n }\n\n async update(input: Parameters<OntologyVectorIndexingStorage[\"update\"]>[0]) {\n return this.run(() => {\n for (const [key, work] of this.state) {\n if (\n work.projectId !== input.projectId ||\n work.id !== input.id ||\n work.status !== input.expectedStatus\n )\n continue\n this.state.set(\n key,\n structuredClone({\n ...work,\n status: input.status,\n availableAt: input.availableAt,\n values: input.values ?? work.values,\n error: input.error,\n })\n )\n return true\n }\n return false\n })\n }\n\n async remove(input: Parameters<OntologyVectorIndexingStorage[\"remove\"]>[0]) {\n await this.run(() => {\n for (const [key, work] of this.state)\n if (work.projectId === input.projectId && work.id === input.id) this.state.delete(key)\n })\n }\n}\n",
|
|
44
|
+
"import type { InMemoryObjectStorage } from \"../../objects/in-memory\"\nimport { getInMemoryObjectMaterializerAdapter } from \"../../objects/in-memory\"\nimport type { InMemoryTimeseriesStorage } from \"../../timeseries/store\"\nimport type { OntologyStorage } from \"..\"\nimport type { ProviderMaterializationTransactionLifecycle } from \"../provider\"\nimport type { AssertSourceMaterializationExecution } from \"../sources\"\nimport { InMemoryOntologyCommitStorage } from \"./commits\"\nimport { InMemoryOntologyMaterializationStorage } from \"./materializations\"\nimport { InMemoryOntologyOutboxStorage } from \"./outbox\"\nimport { InMemoryOntologyReplacementPlanStorage } from \"./replacement-plans\"\nimport {\n cloneOntologyState,\n createInMemoryOntologyState,\n type InMemoryExecutionReader,\n type InMemoryOntologyState,\n type InMemoryOntologyStorageTestHooks,\n restoreOntologyState,\n} from \"./shared-state\"\nimport { InMemoryOntologySourceStorage } from \"./sources\"\nimport { InMemoryMaterializationStateReader } from \"./state-reader\"\nimport {\n type InMemoryOntologyStorageTestingAdapter,\n registerInMemoryOntologyStorageTestingAdapter,\n} from \"./testing\"\nimport { InMemoryOntologyUniqueValueStorage } from \"./unique-values\"\n\nexport type InMemoryOntologyStorageSnapshot = InMemoryOntologyState\n\ninterface InMemoryOntologyStorageOptions {\n readonly runRootOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n readonly getTransactionToken: () => object | null\n readonly getMaterializationLifecycle: () => ProviderMaterializationTransactionLifecycle | null\n readonly assertSourceMaterializationExecution: AssertSourceMaterializationExecution\n readonly readExecution: InMemoryExecutionReader\n}\n\nimport { InMemoryVectorIndexingStorage } from \"./vector-indexing\"\nimport { InMemoryOntologyVectorStorage, vectorObjectKey } from \"./vectors\"\n\nexport class InMemoryOntologyStorage implements OntologyStorage {\n private readonly state = createInMemoryOntologyState()\n readonly vectorIndexing: InMemoryVectorIndexingStorage\n readonly vectors: InMemoryOntologyVectorStorage\n readonly commits: InMemoryOntologyCommitStorage\n readonly sources: InMemoryOntologySourceStorage\n readonly materializations: InMemoryOntologyMaterializationStorage\n readonly replacementPlans: InMemoryOntologyReplacementPlanStorage\n readonly outbox: InMemoryOntologyOutboxStorage\n readonly uniqueValues: InMemoryOntologyUniqueValueStorage\n private testHooks: InMemoryOntologyStorageTestHooks = {}\n private readonly testingAdapter: InMemoryOntologyStorageTestingAdapter = {\n setTestHooks: (hooks) => this.setTestHooks(hooks),\n snapshot: () => this.snapshot(),\n }\n\n constructor(\n objects: InMemoryObjectStorage,\n timeseries: InMemoryTimeseriesStorage,\n options: InMemoryOntologyStorageOptions\n ) {\n this.vectorIndexing = new InMemoryVectorIndexingStorage(\n this.state.vectorIndexing,\n (session, projectId) => this.materializations.assertVectorSession(session, projectId),\n options.runRootOperation\n )\n this.vectors = new InMemoryOntologyVectorStorage(\n this.state.vectors,\n (session, projectId, commitId) =>\n this.materializations.assertVectorSession(session, projectId, commitId),\n options.runRootOperation\n )\n getInMemoryObjectMaterializerAdapter(objects).setVectorReader((projectId, ref, profile) =>\n this.state.vectors.get(vectorObjectKey(projectId, ref))?.get(profile)\n )\n this.commits = new InMemoryOntologyCommitStorage(this.state, options.runRootOperation)\n this.sources = new InMemoryOntologySourceStorage(\n this.state,\n options.runRootOperation,\n options.assertSourceMaterializationExecution\n )\n this.outbox = new InMemoryOntologyOutboxStorage(\n this.state,\n options.runRootOperation,\n options.readExecution\n )\n this.uniqueValues = new InMemoryOntologyUniqueValueStorage(objects, options.runRootOperation)\n const hooks: InMemoryOntologyStorageTestHooks = {\n beforeRead: (boundary) => this.testHooks.beforeRead?.(boundary),\n beforeWrite: (boundary, ordinal) => this.testHooks.beforeWrite?.(boundary, ordinal),\n observeBuffer: (boundary, rows) => this.testHooks.observeBuffer?.(boundary, rows),\n observeWork: (records) => this.testHooks.observeWork?.(records),\n }\n const reader = new InMemoryMaterializationStateReader(this.state, objects, timeseries, hooks)\n this.materializations = new InMemoryOntologyMaterializationStorage(\n this.state,\n objects,\n timeseries,\n reader,\n options.getTransactionToken,\n options.getMaterializationLifecycle,\n options.readExecution,\n hooks\n )\n this.replacementPlans = new InMemoryOntologyReplacementPlanStorage(\n this.state,\n objects,\n reader,\n options.runRootOperation,\n options.assertSourceMaterializationExecution,\n hooks\n )\n registerInMemoryOntologyStorageTestingAdapter(this, this.testingAdapter)\n }\n\n /** @internal Test-only failure injection; not part of OntologyStorage. */\n setTestHooks(hooks: InMemoryOntologyStorageTestHooks): void {\n this.testHooks = hooks\n }\n\n /** @internal Register a decorated facade as an alias for the same test adapter. */\n registerTestingAlias(storage: OntologyStorage): void {\n registerInMemoryOntologyStorageTestingAdapter(storage, this.testingAdapter)\n }\n\n snapshot(): InMemoryOntologyStorageSnapshot {\n return cloneOntologyState(this.state)\n }\n\n restore(snapshot: InMemoryOntologyStorageSnapshot): void {\n restoreOntologyState(this.state, snapshot)\n }\n\n completeTransaction(transactionToken: object): void {\n this.materializations.deactivateTransaction(transactionToken)\n }\n}\n\nexport type { InMemoryOntologyStorageTestHooks } from \"./shared-state\"\n",
|
|
45
|
+
"export type RunListOrder = \"asc\" | \"desc\"\n\nexport type { ListPage as RunListPage, ListWindow as RunListWindow } from \"./pagination\"\nexport { paginate } from \"./pagination\"\n\nexport interface StartedAtRunRecord<TStatus extends string = string> {\n readonly id: string\n readonly status: TStatus\n readonly startedAt?: Date\n readonly queuedAt?: Date\n}\n\nexport function storageKey(projectId: string, id: string): string {\n return `${projectId}:${id}`\n}\n\nexport function cloneRecord<T>(record: T): T {\n return structuredClone(record)\n}\n\nexport function hasEmptyStatuses(input: { readonly statuses?: readonly unknown[] }): boolean {\n return input.statuses !== undefined && input.statuses.length === 0\n}\n\nexport function toStatusSet<TStatus extends string>(\n statuses: readonly TStatus[] | undefined\n): ReadonlySet<TStatus> | null {\n return statuses ? new Set(statuses) : null\n}\n\nexport function matchesRunListDateFilters<TStatus extends string>(\n record: StartedAtRunRecord<TStatus>,\n filters: {\n readonly statuses: ReadonlySet<TStatus> | null\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n }\n): boolean {\n if (filters.statuses && !filters.statuses.has(record.status)) {\n return false\n }\n\n const startedAt = effectiveStartedAt(record)\n\n if (filters.startedAfter && startedAt < filters.startedAfter) {\n return false\n }\n\n if (filters.startedBefore && startedAt > filters.startedBefore) {\n return false\n }\n\n return true\n}\n\nexport function compareStartedAt(\n left: { readonly id: string; readonly startedAt?: Date; readonly queuedAt?: Date },\n right: { readonly id: string; readonly startedAt?: Date; readonly queuedAt?: Date },\n order: RunListOrder\n): number {\n const delta = effectiveStartedAt(left).getTime() - effectiveStartedAt(right).getTime()\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n\n if (left.id === right.id) {\n return 0\n }\n\n return order === \"asc\" ? left.id.localeCompare(right.id) : right.id.localeCompare(left.id)\n}\n\nexport function latestStartedAtByOwnerId<\n TRecord extends { readonly id: string; readonly startedAt?: Date; readonly queuedAt?: Date },\n>(\n records: readonly TRecord[],\n ownerIds: readonly string[],\n ownerIdFor: (record: TRecord) => string\n): readonly TRecord[] {\n const uniqueOwnerIds = [...new Set(ownerIds)]\n if (uniqueOwnerIds.length === 0) {\n return []\n }\n\n const requested = new Set(uniqueOwnerIds)\n const latestByOwnerId = new Map<string, TRecord>()\n\n for (const record of records) {\n const ownerId = ownerIdFor(record)\n if (!requested.has(ownerId)) {\n continue\n }\n\n const current = latestByOwnerId.get(ownerId)\n if (!current || compareStartedAt(record, current, \"desc\") < 0) {\n latestByOwnerId.set(ownerId, record)\n }\n }\n\n return uniqueOwnerIds.flatMap((ownerId) => {\n const record = latestByOwnerId.get(ownerId)\n return record ? [record] : []\n })\n}\n\nfunction effectiveStartedAt(record: {\n readonly id: string\n readonly startedAt?: Date\n readonly queuedAt?: Date\n}): Date {\n const value = record.startedAt ?? record.queuedAt\n if (!value) {\n throw new Error(`[Sixb] Run '${record.id}' has neither startedAt nor queuedAt.`)\n }\n return value\n}\n",
|
|
46
|
+
"import type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { DatasetVersionRef, DatasetWriteMode } from \"../../lake-storage\"\n\nexport type PipelineRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\nexport type PipelineStepRunStatus = Exclude<PipelineRunStatus, \"queued\">\n/** Error codes a pipeline or pipeline-step run can persist and expose. */\nexport const PIPELINE_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"queue.enqueue_failed\",\n \"pipeline.step_failed\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type PipelineRunFailureCode = (typeof PIPELINE_RUN_FAILURE_CODES)[number]\n\nexport interface PipelineRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly pipelineId: string\n readonly status: PipelineRunStatus\n readonly queuedAt: Date\n readonly startedAt?: Date\n readonly finishedAt?: Date\n /** Final step output in sequential V1. */\n readonly output?: DatasetVersionRef\n readonly error?: SixbFailure<PipelineRunFailureCode>\n}\n\nexport interface PipelineStepRunRecord {\n readonly id: string\n readonly projectId: string\n readonly pipelineRunId: string\n readonly pipelineId: string\n readonly stepId: string\n readonly datasetId: string\n readonly mode: DatasetWriteMode\n readonly status: PipelineStepRunStatus\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly inputs: readonly DatasetVersionRef[]\n readonly output?: DatasetVersionRef\n readonly rowsWritten?: number\n readonly error?: SixbFailure<PipelineRunFailureCode>\n}\n\nexport interface QueuePipelineRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly pipelineId: string\n readonly queuedAt?: Date\n}\n\nexport interface StartPipelineRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n}\n\nexport type FinishPipelineRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n readonly output?: DatasetVersionRef\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\"\n readonly finishedAt?: Date\n readonly error: SixbFailure<PipelineRunFailureCode>\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"cancelled\"\n readonly finishedAt?: Date\n readonly error?: SixbFailure<PipelineRunFailureCode>\n }\n\nexport interface StartPipelineStepRunInput {\n readonly id: string\n readonly projectId: string\n readonly pipelineRunId: string\n readonly pipelineId: string\n readonly stepId: string\n readonly datasetId: string\n readonly mode: DatasetWriteMode\n readonly startedAt?: Date\n readonly inputs: readonly DatasetVersionRef[]\n}\n\nexport type FinishPipelineStepRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n readonly output: DatasetVersionRef\n readonly rowsWritten?: number\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly finishedAt?: Date\n readonly rowsWritten?: number\n readonly error?: SixbFailure<PipelineRunFailureCode>\n }\n\nexport interface ListPipelineRunsInput {\n readonly projectId: string\n readonly pipelineId?: string\n readonly pipelineIds?: readonly string[]\n readonly statuses?: readonly PipelineRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListPipelineRunsResult {\n readonly runs: readonly PipelineRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestPipelineRunsInput {\n readonly projectId: string\n readonly pipelineIds: readonly string[]\n}\n\nexport interface ListLatestPipelineRunsResult {\n readonly runs: readonly PipelineRunRecord[]\n}\n\nexport interface ListPipelineStepRunsInput {\n readonly projectId: string\n readonly pipelineRunId?: string\n readonly pipelineId?: string\n readonly stepId?: string\n readonly datasetId?: string\n readonly statuses?: readonly PipelineStepRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListPipelineStepRunsResult {\n readonly steps: readonly PipelineStepRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface PipelineRunStorage {\n queue(input: QueuePipelineRunInput): Promise<PipelineRunRecord>\n start(input: StartPipelineRunInput): Promise<PipelineRunRecord>\n finish(input: FinishPipelineRunInput): Promise<PipelineRunRecord>\n startStep(input: StartPipelineStepRunInput): Promise<PipelineStepRunRecord>\n finishStep(input: FinishPipelineStepRunInput): Promise<PipelineStepRunRecord>\n getById(params: { projectId: string; id: string }): Promise<PipelineRunRecord | null>\n list(input: ListPipelineRunsInput): Promise<ListPipelineRunsResult>\n listLatestByPipelineIds(input: ListLatestPipelineRunsInput): Promise<ListLatestPipelineRunsResult>\n listSteps(input: ListPipelineStepRunsInput): Promise<ListPipelineStepRunsResult>\n}\n",
|
|
47
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n cloneRecord,\n compareStartedAt,\n hasEmptyStatuses,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n paginate,\n storageKey,\n toStatusSet,\n} from \"../run-listing\"\nimport { PipelineRunError } from \"./errors\"\nimport { canRequeuePipelineRunAfterEnqueueFailure } from \"./idempotency\"\nimport { assertPipelineRunExecution } from \"./provider\"\nimport type {\n FinishPipelineRunInput,\n FinishPipelineStepRunInput,\n ListLatestPipelineRunsInput,\n ListLatestPipelineRunsResult,\n ListPipelineRunsInput,\n ListPipelineRunsResult,\n ListPipelineStepRunsInput,\n ListPipelineStepRunsResult,\n PipelineRunFailureCode,\n PipelineRunRecord,\n PipelineRunStorage,\n PipelineStepRunRecord,\n QueuePipelineRunInput,\n StartPipelineRunInput,\n StartPipelineStepRunInput,\n} from \"./types\"\nimport { PIPELINE_RUN_FAILURE_CODES } from \"./types\"\n\nfunction normalizeError(\n error: SixbFailure<PipelineRunFailureCode> | undefined\n): SixbFailure<PipelineRunFailureCode> | undefined {\n return error ? parseSixbFailure(error, PIPELINE_RUN_FAILURE_CODES) : undefined\n}\n\nfunction assertNonNegativeInteger(value: number | undefined, fieldName: string): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n throw new PipelineRunError(`[Sixb] Pipeline run ${fieldName} must be a non-negative integer.`)\n }\n}\n\nexport class InMemoryPipelineRunStorage implements PipelineRunStorage {\n private readonly runs = new Map<string, PipelineRunRecord>()\n private readonly steps = new Map<string, PipelineStepRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {}\n\n snapshot(): InMemoryPipelineRunStorageSnapshot {\n return {\n runs: structuredClone(this.runs),\n steps: structuredClone(this.steps),\n }\n }\n\n restore(snapshot: InMemoryPipelineRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot.runs)) {\n this.runs.set(key, record)\n }\n\n this.steps.clear()\n for (const [key, record] of structuredClone(snapshot.steps)) {\n this.steps.set(key, record)\n }\n }\n\n async queue(input: QueuePipelineRunInput): Promise<PipelineRunRecord> {\n const key = storageKey(input.projectId, input.id)\n const existing = this.runs.get(key)\n if (existing && !canRequeuePipelineRunAfterEnqueueFailure(existing, input)) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.runs.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new PipelineRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Pipeline run.`\n )\n }\n await assertPipelineRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n pipelineId: input.pipelineId,\n })\n\n const queuedAt = new Date(input.queuedAt ?? new Date())\n if (existing) {\n const next: PipelineRunRecord = {\n ...existing,\n status: \"queued\",\n queuedAt,\n startedAt: undefined,\n finishedAt: undefined,\n output: undefined,\n error: undefined,\n }\n this.runs.set(key, cloneRecord(next))\n return cloneRecord(next)\n }\n\n const record: PipelineRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n pipelineId: input.pipelineId,\n status: \"queued\",\n queuedAt,\n }\n\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async start(input: StartPipelineRunInput): Promise<PipelineRunRecord> {\n const key = storageKey(input.projectId, input.id)\n const existing = this.runs.get(key)\n if (!existing) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n if (existing.status !== \"queued\") {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' cannot start from status '${existing.status}'.`\n )\n }\n\n const next: PipelineRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n error: undefined,\n }\n this.runs.set(key, cloneRecord(next))\n return cloneRecord(next)\n }\n\n async finish(input: FinishPipelineRunInput): Promise<PipelineRunRecord> {\n const existing = this.requireExistingPipelineRun(input.projectId, input.id)\n const enqueueFailure = input.status === \"failed\" && input.error.code === \"queue.enqueue_failed\"\n if (\n (enqueueFailure && existing.status !== \"queued\") ||\n (!enqueueFailure && existing.status !== \"running\")\n ) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${input.id}' cannot finish from status '${existing.status}'.`\n )\n }\n const base: PipelineRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: PipelineRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: input.output ? cloneRecord(input.output) : undefined,\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeError(input.error),\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async startStep(input: StartPipelineStepRunInput): Promise<PipelineStepRunRecord> {\n const pipelineRun = this.requireRunningPipelineRun(input.projectId, input.pipelineRunId)\n if (pipelineRun.pipelineId !== input.pipelineId) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${input.id}' pipeline '${input.pipelineId}' does not match pipeline run '${input.pipelineRunId}' pipeline '${pipelineRun.pipelineId}'.`\n )\n }\n\n const key = storageKey(input.projectId, input.id)\n if (this.steps.has(key)) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const record: PipelineStepRunRecord = {\n id: input.id,\n projectId: input.projectId,\n pipelineRunId: input.pipelineRunId,\n pipelineId: input.pipelineId,\n stepId: input.stepId,\n datasetId: input.datasetId,\n mode: input.mode,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n inputs: cloneRecord(input.inputs),\n }\n\n this.steps.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async finishStep(input: FinishPipelineStepRunInput): Promise<PipelineStepRunRecord> {\n assertNonNegativeInteger(input.rowsWritten, \"rowsWritten\")\n\n const existing = this.requireRunningStepRun(input.projectId, input.id)\n\n if (input.status === \"succeeded\" && input.output.datasetId !== existing.datasetId) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${input.id}' output dataset '${input.output.datasetId}' does not match '${existing.datasetId}'.`\n )\n }\n\n const base: PipelineStepRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n rowsWritten: input.rowsWritten ?? existing.rowsWritten,\n }\n\n const next: PipelineStepRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: cloneRecord(input.output),\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeError(input.error),\n }\n\n this.steps.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<PipelineRunRecord | null> {\n const record = this.runs.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListPipelineRunsInput): Promise<ListPipelineRunsResult> {\n if (hasEmptyStatuses(input) || input.pipelineIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const pipelineIds = input.pipelineIds ? new Set(input.pipelineIds) : null\n const filtered = [...this.runs.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.pipelineId ? record.pipelineId === input.pipelineId : true))\n .filter((record) => (pipelineIds ? pipelineIds.has(record.pipelineId) : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestByPipelineIds(\n input: ListLatestPipelineRunsInput\n ): Promise<ListLatestPipelineRunsResult> {\n const runs = latestStartedAtByOwnerId(\n [...this.runs.values()].filter((record) => record.projectId === input.projectId),\n input.pipelineIds,\n (record) => record.pipelineId\n )\n\n return {\n runs: runs.map(cloneRecord),\n }\n }\n\n async listSteps(input: ListPipelineStepRunsInput): Promise<ListPipelineStepRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n steps: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const filtered = [...this.steps.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) =>\n input.pipelineRunId ? record.pipelineRunId === input.pipelineRunId : true\n )\n .filter((record) => (input.pipelineId ? record.pipelineId === input.pipelineId : true))\n .filter((record) => (input.stepId ? record.stepId === input.stepId : true))\n .filter((record) => (input.datasetId ? record.datasetId === input.datasetId : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n steps: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requireExistingPipelineRun(projectId: string, id: string): PipelineRunRecord {\n const record = this.runs.get(storageKey(projectId, id))\n if (!record) {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${id}' not found for project '${projectId}'.`\n )\n }\n\n return record\n }\n\n private requireRunningPipelineRun(projectId: string, id: string): PipelineRunRecord {\n const record = this.requireExistingPipelineRun(projectId, id)\n if (record.status !== \"running\") {\n throw new PipelineRunError(\n `[Sixb] Pipeline run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n\n private requireRunningStepRun(projectId: string, id: string): PipelineStepRunRecord {\n const record = this.steps.get(storageKey(projectId, id))\n if (!record) {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"running\") {\n throw new PipelineRunError(\n `[Sixb] Pipeline step run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n}\n\nexport interface InMemoryPipelineRunStorageSnapshot {\n readonly runs: Map<string, PipelineRunRecord>\n readonly steps: Map<string, PipelineStepRunRecord>\n}\n",
|
|
48
|
+
"import { randomUUID } from \"node:crypto\"\nimport type { ExecutionStorage } from \"../executions\"\nimport type { AssertSourceMaterializationExecutionInput } from \"../ontology/sources\"\nimport {\n compareStartedAt,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n} from \"../run-listing\"\nimport { ProjectionRunError } from \"./errors\"\nimport {\n advanceProjectionTelemetry,\n assertGenericProgressDoesNotAdvanceTelemetry,\n assertProjectionMissingTarget,\n assertProjectionRunAttempt,\n assertProjectionRunDurableExecution,\n assertProjectionRunIdentityMatches,\n assertProjectionRunListWindow,\n assertProjectionRunNonEmpty,\n assertProjectionRunQueueInput,\n assertProjectionRunRunning,\n assertProjectionRunStartInput,\n canRequeueProjectionRunAfterEnqueueFailure,\n createProjectionRunClaim,\n createProjectionRunRecord,\n failProjectionRunEnqueue,\n finishProjectionRunRecord,\n immutableDatasetVersionConflict,\n mergeProjectionRunProgress,\n parseProjectionAttemptFailure,\n planProjectionRunReclaim,\n projectionRunNotFound,\n projectionRunSupersedes,\n publicProjectionRunRecord,\n requireTelemetryProjectionRun,\n type StoredProjectionRunRecord,\n staleProjectionRunExecution,\n} from \"./provider\"\nimport {\n type AdvanceProjectionTelemetryCheckpointInput,\n type FailProjectionRunEnqueueInput,\n type FindSupersedingProjectionRunInput,\n type FinishProjectionRunInput,\n type ListLatestProjectionRunsInput,\n type ListLatestProjectionRunsResult,\n type ListProjectionRunsInput,\n type ListProjectionRunsResult,\n type LockProjectionRunForMaterializationInput,\n type ProjectionRunClaim,\n type ProjectionRunRecord,\n type ProjectionRunStorage,\n projectionRunObjectTypesVisible,\n type QueueProjectionRunInput,\n type RecordProjectionAttemptFailureInput,\n type RecordProjectionMissingTargetInput,\n type StartOrReclaimProjectionRunInput,\n type TelemetryProjectionRunRecord,\n type UpdateProjectionRunInput,\n} from \"./types\"\n\ntype RunRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\nconst runDirectly: RunRootOperation = async <T>(run: () => Promise<T> | T): Promise<T> => run()\n\nfunction projectionRunKey(projectId: string, id: string): string {\n return JSON.stringify([projectId, id])\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction compareRuns(a: ProjectionRunRecord, b: ProjectionRunRecord, order: \"asc\" | \"desc\") {\n return compareStartedAt(a, b, order)\n}\n\nexport class InMemoryProjectionRunStorage implements ProjectionRunStorage {\n private readonly rows = new Map<string, StoredProjectionRunRecord>()\n private readonly runRootOperation: RunRootOperation\n\n constructor(input: {\n readonly executions: ExecutionStorage\n readonly runRootOperation?: RunRootOperation\n }) {\n this.executions = input.executions\n this.runRootOperation = input.runRootOperation ?? runDirectly\n }\n\n private readonly executions: ExecutionStorage\n\n snapshot(): InMemoryProjectionRunStorageSnapshot {\n return structuredClone({ rows: this.rows })\n }\n\n restore(snapshot: InMemoryProjectionRunStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot.rows)) this.rows.set(key, record)\n }\n\n async queue(input: QueueProjectionRunInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(async () => {\n assertProjectionRunQueueInput(input)\n this.assertDatasetVersionIsImmutable(input)\n const key = projectionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (existing && !canRequeueProjectionRunAfterEnqueueFailure(existing, input)) {\n throw new ProjectionRunError(\n `[Sixb] Projection run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.rows.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new ProjectionRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Projection run.`\n )\n }\n await assertProjectionRunDurableExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n projectionId: input.identity.projectionId,\n datasetId: input.identity.datasetVersion.datasetId,\n datasetVersionId: input.identity.datasetVersion.versionId,\n })\n const record = createProjectionRunRecord(input)\n this.rows.set(key, structuredClone(record))\n return publicProjectionRunRecord(record)\n })\n }\n\n async startOrReclaim(input: StartOrReclaimProjectionRunInput): Promise<ProjectionRunClaim> {\n return this.runRootOperation(() => {\n assertProjectionRunStartInput(input)\n const key = projectionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (!existing) throw projectionRunNotFound(input.projectId, input.id)\n const attempt = planProjectionRunReclaim(existing, input).attempt\n const record: StoredProjectionRunRecord = {\n ...existing,\n status: \"running\",\n attempt,\n // A fresh token per claim fences every earlier execution of this run.\n executionToken: randomUUID(),\n startedAt: existing.startedAt ?? new Date(input.startedAt ?? new Date()),\n finishedAt: undefined,\n }\n\n this.rows.set(key, structuredClone(record))\n return createProjectionRunClaim(record)\n })\n }\n\n async failEnqueue(input: FailProjectionRunEnqueueInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const key = projectionRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (!existing) throw projectionRunNotFound(input.projectId, input.id)\n const next = failProjectionRunEnqueue(existing, input)\n this.rows.set(key, structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n\n async lockForMaterialization(\n input: LockProjectionRunForMaterializationInput\n ): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => publicProjectionRunRecord(this.requireExecution(input)))\n }\n\n /** @internal The caller must already hold InMemoryStorage's root operation lock. */\n assertSourceMaterializationExecutionUnlocked(\n input: AssertSourceMaterializationExecutionInput\n ): void {\n assertProjectionRunNonEmpty(input.source.projectionId, \"projectionId\")\n assertProjectionRunNonEmpty(input.execution.executionToken, \"executionToken\")\n const record = this.requireRunning(input.projectId, input.execution.projectionRunId)\n if (\n record.identity.projectionId !== input.source.projectionId ||\n record.identity.protocol !== \"replacement\"\n ) {\n throw new ProjectionRunError(\n `[Sixb] Projection run '${record.id}' does not own replacement source '${input.source.projectionId}'.`\n )\n }\n if (record.executionToken !== input.execution.executionToken) {\n throw staleProjectionRunExecution(record.id)\n }\n if (input.identity) {\n assertProjectionRunIdentityMatches(record, {\n projectionId: input.source.projectionId,\n ...input.identity,\n })\n }\n }\n\n async update(input: UpdateProjectionRunInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireExecution(input)\n assertGenericProgressDoesNotAdvanceTelemetry(existing, input.progress)\n const next = {\n ...existing,\n progress: mergeProjectionRunProgress(existing.progress, input.progress),\n }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n async advanceTelemetryCheckpoint(\n input: AdvanceProjectionTelemetryCheckpointInput\n ): Promise<TelemetryProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireTelemetryExecution(input)\n const advance = advanceProjectionTelemetry(existing, input)\n const next: TelemetryProjectionRunRecord & { readonly executionToken: string } = {\n ...existing,\n progress: advance.progress,\n telemetryCheckpoint: advance.checkpoint,\n missingTarget: undefined,\n }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next) as TelemetryProjectionRunRecord\n })\n }\n\n async recordMissingTarget(\n input: RecordProjectionMissingTargetInput\n ): Promise<TelemetryProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireTelemetryExecution(input)\n const next: TelemetryProjectionRunRecord & { readonly executionToken: string } = {\n ...existing,\n missingTarget: assertProjectionMissingTarget(existing, input.missingTarget),\n }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next) as TelemetryProjectionRunRecord\n })\n }\n\n async recordAttemptFailure(\n input: RecordProjectionAttemptFailureInput\n ): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireExecution(input)\n const next = { ...existing, error: parseProjectionAttemptFailure(existing, input.error) }\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n\n async finish(input: FinishProjectionRunInput): Promise<ProjectionRunRecord> {\n return this.runRootOperation(() => {\n const existing = this.requireExecution(input)\n const next = finishProjectionRunRecord(existing, input)\n this.rows.set(projectionRunKey(input.projectId, input.id), structuredClone(next))\n return publicProjectionRunRecord(next)\n })\n }\n\n async getById(params: { projectId: string; id: string }): Promise<ProjectionRunRecord | null> {\n return this.runRootOperation(() => {\n const record = this.rows.get(projectionRunKey(params.projectId, params.id))\n return record ? publicProjectionRunRecord(record) : null\n })\n }\n\n async list(input: ListProjectionRunsInput): Promise<ListProjectionRunsResult> {\n return this.runRootOperation(() => {\n assertProjectionRunNonEmpty(input.projectId, \"projectId\")\n assertProjectionRunListWindow(input.limit, \"limit\")\n assertProjectionRunListWindow(input.offset, \"offset\")\n if (input.statuses?.length === 0 || input.errorCodes?.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n\n const order = input.order ?? \"desc\"\n const offset = input.offset ?? 0\n const limit = input.limit ?? this.rows.size\n const statuses = input.statuses ? new Set(input.statuses) : null\n const objectTypeIds = input.objectTypeIds ? new Set(input.objectTypeIds) : null\n const errorCodes = input.errorCodes ? new Set(input.errorCodes) : null\n const filtered = [...this.rows.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) =>\n input.projectionId ? record.identity.projectionId === input.projectionId : true\n )\n .filter((record) =>\n input.projectionKind ? record.identity.projectionKind === input.projectionKind : true\n )\n .filter((record) =>\n input.datasetId ? record.identity.datasetVersion.datasetId === input.datasetId : true\n )\n .filter((record) =>\n input.datasetVersionId\n ? record.identity.datasetVersion.versionId === input.datasetVersionId\n : true\n )\n .filter((record) =>\n objectTypeIds\n ? projectionRunObjectTypesVisible(record, (id) => objectTypeIds.has(id))\n : true\n )\n .filter((record) => (statuses ? statuses.has(record.status) : true))\n .filter((record) =>\n errorCodes ? record.error !== undefined && errorCodes.has(record.error.code) : true\n )\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareRuns(left, right, order))\n\n const total = filtered.length\n const runs = filtered.slice(offset, offset + limit).map(publicProjectionRunRecord)\n return { runs, hasMore: offset + runs.length < total, total }\n })\n }\n\n async findSupersedingRun(\n input: FindSupersedingProjectionRunInput\n ): Promise<ProjectionRunRecord | null> {\n return this.runRootOperation(() => {\n const run = this.rows.get(projectionRunKey(input.projectId, input.id))\n if (!run) throw projectionRunNotFound(input.projectId, input.id)\n const newest = [...this.rows.values()]\n .filter((candidate) => projectionRunSupersedes(candidate, run))\n .sort(\n (left, right) =>\n compareText(\n right.identity.datasetVersion.createdAt,\n left.identity.datasetVersion.createdAt\n ) || compareText(right.id, left.id)\n )[0]\n return newest ? publicProjectionRunRecord(newest) : null\n })\n }\n\n async listLatestByProjectionIds(\n input: ListLatestProjectionRunsInput\n ): Promise<ListLatestProjectionRunsResult> {\n return this.runRootOperation(() => {\n const runs = latestStartedAtByOwnerId(\n [...this.rows.values()].filter(\n (record) => record.projectId === input.projectId && record.status !== \"superseded\"\n ),\n input.projectionIds,\n (record) => record.identity.projectionId\n )\n return { runs: runs.map(publicProjectionRunRecord) }\n })\n }\n\n private assertDatasetVersionIsImmutable(input: QueueProjectionRunInput): void {\n for (const candidate of this.rows.values()) {\n if (\n candidate.projectId === input.projectId &&\n candidate.id !== input.id &&\n candidate.identity.datasetVersion.datasetId === input.identity.datasetVersion.datasetId &&\n candidate.identity.datasetVersion.versionId === input.identity.datasetVersion.versionId &&\n candidate.identity.datasetVersion.createdAt !== input.identity.datasetVersion.createdAt\n ) {\n throw immutableDatasetVersionConflict(input.identity)\n }\n }\n }\n\n private requireExecution(\n input: LockProjectionRunForMaterializationInput\n ): StoredProjectionRunRecord & { readonly executionToken: string } {\n const record = this.requireRunning(input.projectId, input.id)\n assertProjectionRunAttempt(record, input)\n return record\n }\n\n private requireTelemetryExecution(\n input: LockProjectionRunForMaterializationInput\n ): TelemetryProjectionRunRecord & { readonly executionToken: string } {\n const record = this.requireExecution(input)\n return requireTelemetryProjectionRun(record)\n }\n\n private requireRunning(projectId: string, id: string): StoredProjectionRunRecord {\n assertProjectionRunNonEmpty(projectId, \"projectId\")\n assertProjectionRunNonEmpty(id, \"id\")\n const record = this.rows.get(projectionRunKey(projectId, id))\n if (!record) {\n throw projectionRunNotFound(projectId, id)\n }\n assertProjectionRunRunning(record)\n return record\n }\n}\n\nexport interface InMemoryProjectionRunStorageSnapshot {\n readonly rows: Map<string, StoredProjectionRunRecord>\n}\n",
|
|
49
|
+
"import type {\n RuleEventSubject,\n StoredRuleResolvedEvent,\n StoredRuleTriggeredEvent,\n} from \"../../events\"\nimport type {\n ListActiveRuleStatesInput,\n ListActiveRuleStatesResult,\n ListRuleStatesReconciliationPageInput,\n ListRuleStatesReconciliationPageResult,\n RuleStateCursor,\n RuleStateRecord,\n RuleStateTransitionEvent,\n RulesStorage,\n} from \"./types\"\n\nfunction stateKey(params: {\n readonly projectId: string\n readonly ruleId: string\n readonly subject: RuleEventSubject\n}): string {\n return JSON.stringify([\n params.projectId,\n params.ruleId,\n params.subject.kind,\n params.subject.objectTypeId,\n params.subject.primaryId,\n ])\n}\n\nfunction cloneRuleStateRecord(record: RuleStateRecord): RuleStateRecord {\n return structuredClone(record)\n}\n\nfunction compareRuleStateRecords(\n left: RuleStateRecord,\n right: RuleStateRecord,\n order: \"asc\" | \"desc\"\n): number {\n const direction = order === \"asc\" ? 1 : -1\n const fields = [\n left.triggeredAt.localeCompare(right.triggeredAt),\n left.ruleId.localeCompare(right.ruleId),\n left.subject.objectTypeId.localeCompare(right.subject.objectTypeId),\n left.subject.primaryId.localeCompare(right.subject.primaryId),\n ]\n\n for (const value of fields) {\n if (value !== 0) {\n return value * direction\n }\n }\n\n return 0\n}\n\nfunction compareRuleStateIdentity(left: RuleStateRecord, right: RuleStateRecord): number {\n return (\n left.ruleId.localeCompare(right.ruleId) ||\n left.subject.objectTypeId.localeCompare(right.subject.objectTypeId) ||\n left.subject.primaryId.localeCompare(right.subject.primaryId)\n )\n}\n\nfunction compareCursor(record: RuleStateRecord, cursor: RuleStateCursor): number {\n return (\n record.ruleId.localeCompare(cursor.ruleId) ||\n record.subject.objectTypeId.localeCompare(cursor.objectTypeId) ||\n record.subject.primaryId.localeCompare(cursor.primaryId)\n )\n}\n\nexport class InMemoryRulesStorage implements RulesStorage {\n private readonly active = new Map<string, RuleStateRecord>()\n\n snapshot(): InMemoryRulesStorageSnapshot {\n return structuredClone(this.active)\n }\n\n restore(snapshot: InMemoryRulesStorageSnapshot): void {\n this.active.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.active.set(key, record)\n }\n }\n\n async getActive(params: {\n projectId: string\n ruleId: string\n subject: RuleEventSubject\n }): Promise<RuleStateRecord | null> {\n const record = this.active.get(stateKey(params))\n return record ? cloneRuleStateRecord(record) : null\n }\n\n async getActiveBatch(params: {\n projectId: string\n items: readonly { readonly ruleId: string; readonly subject: RuleEventSubject }[]\n }): Promise<readonly RuleStateRecord[]> {\n return params.items.flatMap((item) => {\n const record = this.active.get(stateKey({ projectId: params.projectId, ...item }))\n return record ? [cloneRuleStateRecord(record)] : []\n })\n }\n\n async listActive(input: ListActiveRuleStatesInput): Promise<ListActiveRuleStatesResult> {\n if (input.objectTypeIds?.length === 0) {\n return { states: [], hasMore: false, total: 0 }\n }\n\n const order = input.order ?? \"desc\"\n const offset = input.offset ?? 0\n const objectTypeIds = input.objectTypeIds ? new Set(input.objectTypeIds) : null\n const states = [...this.active.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => !input.ruleId || record.ruleId === input.ruleId)\n .filter((record) => !input.objectTypeId || record.subject.objectTypeId === input.objectTypeId)\n .filter((record) => (objectTypeIds ? objectTypeIds.has(record.subject.objectTypeId) : true))\n .filter((record) => !input.primaryId || record.subject.primaryId === input.primaryId)\n .sort((left, right) => compareRuleStateRecords(left, right, order))\n\n const total = states.length\n const windowed =\n input.limit === undefined ? states.slice(offset) : states.slice(offset, offset + input.limit)\n\n return {\n states: windowed.map(cloneRuleStateRecord),\n hasMore: offset + windowed.length < total,\n total,\n }\n }\n\n async listReconciliationPage(\n input: ListRuleStatesReconciliationPageInput\n ): Promise<ListRuleStatesReconciliationPageResult> {\n const rows = [...this.active.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => record.subject.kind === \"object\")\n .filter((record) => !input.after || compareCursor(record, input.after) > 0)\n .sort(compareRuleStateIdentity)\n .slice(0, input.limit + 1)\n const hasMore = rows.length > input.limit\n const states = rows.slice(0, input.limit).map(cloneRuleStateRecord)\n const last = states.at(-1)\n return {\n states,\n ...(hasMore && last\n ? {\n next: {\n ruleId: last.ruleId,\n objectTypeId: last.subject.objectTypeId,\n primaryId: last.subject.primaryId,\n },\n }\n : {}),\n }\n }\n\n async applyTriggered(event: StoredRuleTriggeredEvent): Promise<void> {\n const record: RuleStateRecord = {\n projectId: event.projectId,\n ruleId: event.payload.ruleId,\n subject: structuredClone(event.payload.subject),\n triggeredAt: event.payload.triggeredAt,\n }\n\n this.active.set(stateKey(record), cloneRuleStateRecord(record))\n }\n\n async applyResolved(event: StoredRuleResolvedEvent): Promise<void> {\n this.active.delete(\n stateKey({\n projectId: event.projectId,\n ruleId: event.payload.ruleId,\n subject: event.payload.subject,\n })\n )\n }\n\n async applyTransitions(events: readonly RuleStateTransitionEvent[]): Promise<void> {\n for (const event of events) {\n if (event.type === \"rule.triggered\") {\n await this.applyTriggered(event)\n } else {\n await this.applyResolved(event)\n }\n }\n }\n}\n\nexport type InMemoryRulesStorageSnapshot = Map<string, RuleStateRecord>\n",
|
|
50
|
+
"import { ShareGrantStorageError } from \"./errors\"\nimport {\n cloneShareGrantRecord,\n normalizeGetShareGrantByIdInput,\n normalizeListShareGrantsInput,\n normalizeRevokeShareGrantInput,\n normalizeShareGrantCreate,\n parseShareGrantRecord,\n} from \"./record\"\nimport type {\n CreateShareGrantInput,\n GetShareGrantByIdInput,\n GetShareGrantsByIdsInput,\n ListShareGrantsInput,\n ListShareGrantsResult,\n RevokeShareGrantInput,\n ShareGrantRecord,\n ShareGrantStorage,\n} from \"./types\"\n\nexport class InMemoryShareGrantStorage implements ShareGrantStorage {\n private rows = new Map<string, ShareGrantRecord>()\n\n async create(input: CreateShareGrantInput): Promise<ShareGrantRecord> {\n const record = normalizeShareGrantCreate(input)\n const key = rowKey(record.projectId, record.id)\n const duplicateTokenHash = [...this.rows.values()].some(\n (current) => current.projectId === record.projectId && current.tokenHash === record.tokenHash\n )\n if (this.rows.has(key) || duplicateTokenHash) {\n throw new ShareGrantStorageError(\n \"duplicate\",\n `[Sixb] Share grant '${record.id}' conflicts with an existing record.`\n )\n }\n\n this.rows.set(key, record)\n return cloneShareGrantRecord(record)\n }\n\n async getById(input: GetShareGrantByIdInput): Promise<ShareGrantRecord | null> {\n const normalized = normalizeGetShareGrantByIdInput(input)\n const record = this.rows.get(rowKey(normalized.projectId, normalized.id))\n return record ? cloneShareGrantRecord(record) : null\n }\n\n async getByIds(input: GetShareGrantsByIdsInput): Promise<readonly ShareGrantRecord[]> {\n return [...new Set(input.ids)].flatMap((id) => {\n const record = this.rows.get(rowKey(input.projectId, id))\n return record ? [cloneShareGrantRecord(record)] : []\n })\n }\n\n async list(input: ListShareGrantsInput): Promise<ListShareGrantsResult> {\n const normalized = normalizeListShareGrantsInput(input)\n const matching = [...this.rows.values()]\n .filter(\n (record) =>\n record.projectId === normalized.projectId &&\n (normalized.definitionId === undefined ||\n record.definitionId === normalized.definitionId) &&\n (normalized.target === undefined ||\n (record.target.objectTypeId === normalized.target.objectTypeId &&\n record.target.primaryId === normalized.target.primaryId)) &&\n (normalized.includeRevoked || record.revokedAt === undefined) &&\n (normalized.includeExpired || record.expiresAt.getTime() > normalized.now.getTime())\n )\n .sort(compareShareGrants)\n\n const total = matching.length\n const grants = matching\n .slice(normalized.offset, normalized.offset + normalized.limit)\n .map(cloneShareGrantRecord)\n return {\n grants,\n total,\n hasMore: normalized.offset + grants.length < total,\n }\n }\n\n async revoke(input: RevokeShareGrantInput): Promise<ShareGrantRecord | null> {\n const normalized = normalizeRevokeShareGrantInput(input)\n const key = rowKey(normalized.projectId, normalized.id)\n const current = this.rows.get(key)\n if (!current) return null\n if (current.revokedAt) return cloneShareGrantRecord(current)\n\n const revocation = normalizeRevokeShareGrantInput(normalized, current.createdAt)\n const updated: ShareGrantRecord = {\n ...current,\n revokedAt: new Date(revocation.revokedAt),\n revokedBy: { ...revocation.revokedBy },\n }\n this.rows.set(key, updated)\n return cloneShareGrantRecord(updated)\n }\n\n snapshot(): ReadonlyMap<string, ShareGrantRecord> {\n return new Map([...this.rows].map(([key, record]) => [key, cloneShareGrantRecord(record)]))\n }\n\n restore(snapshot: ReadonlyMap<string, ShareGrantRecord>): void {\n this.rows = new Map([...snapshot].map(([key, record]) => [key, parseShareGrantRecord(record)]))\n }\n}\n\nfunction compareShareGrants(left: ShareGrantRecord, right: ShareGrantRecord): number {\n const created = right.createdAt.getTime() - left.createdAt.getTime()\n if (created !== 0) return created\n return left.id === right.id ? 0 : left.id < right.id ? 1 : -1\n}\n\nfunction rowKey(projectId: string, id: string): string {\n return `${projectId}\\0${id}`\n}\n",
|
|
51
|
+
"import type { ShareGrantStorage } from \"../share-grants\"\nimport { ShareSessionStorageError } from \"./errors\"\nimport {\n cloneShareSessionRecord,\n normalizeGetShareSessionByIdInput,\n normalizeRenewShareSessionIfValidInput,\n normalizeRevokeShareSessionInput,\n normalizeShareSessionCreate,\n parseShareSessionRecord,\n} from \"./record\"\nimport type {\n CreateShareSessionInput,\n GetShareSessionByIdInput,\n RenewShareSessionIfValidInput,\n RevokeShareSessionInput,\n ShareSessionRecord,\n ShareSessionStorage,\n} from \"./types\"\n\nexport class InMemoryShareSessionStorage implements ShareSessionStorage {\n private rows = new Map<string, ShareSessionRecord>()\n\n constructor(private readonly grants: Pick<ShareGrantStorage, \"getById\">) {}\n\n async create(input: CreateShareSessionInput): Promise<ShareSessionRecord> {\n const record = normalizeShareSessionCreate(input)\n const grant = await this.grants.getById({ projectId: record.projectId, id: record.grantId })\n if (!grant) {\n throw new ShareSessionStorageError(\n \"invalid_input\",\n `[Sixb] Share grant '${record.grantId}' does not exist in project '${record.projectId}'.`\n )\n }\n const key = rowKey(record.projectId, record.id)\n const duplicateTokenHash = [...this.rows.values()].some(\n (current) => current.projectId === record.projectId && current.tokenHash === record.tokenHash\n )\n if (this.rows.has(key) || duplicateTokenHash) {\n throw new ShareSessionStorageError(\n \"duplicate\",\n `[Sixb] Share session '${record.id}' conflicts with an existing record.`\n )\n }\n this.rows.set(key, record)\n return cloneShareSessionRecord(record)\n }\n\n async getById(input: GetShareSessionByIdInput): Promise<ShareSessionRecord | null> {\n const normalized = normalizeGetShareSessionByIdInput(input)\n const record = this.rows.get(rowKey(normalized.projectId, normalized.id))\n return record ? cloneShareSessionRecord(record) : null\n }\n\n async renewIfValid(input: RenewShareSessionIfValidInput): Promise<ShareSessionRecord | null> {\n const normalized = normalizeRenewShareSessionIfValidInput(input)\n const key = rowKey(normalized.projectId, normalized.id)\n const current = this.rows.get(key)\n if (\n !current ||\n current.grantId !== normalized.grantId ||\n current.tokenHash !== normalized.tokenHash ||\n current.revokedAt !== undefined ||\n current.createdAt.getTime() > normalized.now.getTime() ||\n current.expiresAt.getTime() <= normalized.now.getTime() ||\n current.absoluteExpiresAt.getTime() <= normalized.now.getTime()\n ) {\n return null\n }\n\n const nextExpiry = Math.min(\n current.absoluteExpiresAt.getTime(),\n Math.max(current.expiresAt.getTime(), normalized.expiresAt.getTime())\n )\n const updated = { ...current, expiresAt: new Date(nextExpiry) }\n this.rows.set(key, updated)\n return cloneShareSessionRecord(updated)\n }\n\n async revoke(input: RevokeShareSessionInput): Promise<ShareSessionRecord | null> {\n const normalized = normalizeRevokeShareSessionInput(input)\n const key = rowKey(normalized.projectId, normalized.id)\n const current = this.rows.get(key)\n if (!current) return null\n if (current.revokedAt) return cloneShareSessionRecord(current)\n\n const revocation = normalizeRevokeShareSessionInput(normalized, current.createdAt)\n const updated = { ...current, revokedAt: new Date(revocation.revokedAt) }\n this.rows.set(key, updated)\n return cloneShareSessionRecord(updated)\n }\n\n snapshot(): ReadonlyMap<string, ShareSessionRecord> {\n return new Map([...this.rows].map(([key, record]) => [key, cloneShareSessionRecord(record)]))\n }\n\n restore(snapshot: ReadonlyMap<string, ShareSessionRecord>): void {\n this.rows = new Map(\n [...snapshot].map(([key, record]) => [key, parseShareSessionRecord(record)])\n )\n }\n}\n\nfunction rowKey(projectId: string, id: string): string {\n return `${projectId}\\0${id}`\n}\n",
|
|
52
|
+
"import type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonValue } from \"../../json\"\nimport type { DatasetVersionRef, DatasetWriteMode } from \"../../lake-storage\"\n\nexport type SyncRunMode = DatasetWriteMode | \"merge\"\n\nexport type SyncRunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\"\n/** Error codes a sync run can persist and expose through its public contract. */\nexport const SYNC_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"queue.enqueue_failed\",\n \"sync.execution_failed\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type SyncRunFailureCode = (typeof SYNC_RUN_FAILURE_CODES)[number]\n\nexport interface SyncRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly syncId: string\n readonly datasetId: string\n readonly mode: SyncRunMode\n readonly status: SyncRunStatus\n readonly queuedAt: Date\n readonly startedAt?: Date\n readonly finishedAt?: Date\n /** Source items successfully consumed. Merge runs count both upserts and deletes. */\n readonly rowsRead?: number\n readonly output?: DatasetVersionRef\n readonly expectedLatestVersionId?: string\n readonly commitMessage?: string\n readonly error?: SixbFailure<SyncRunFailureCode>\n readonly checkpoint?: JsonValue\n}\n\nexport interface QueueSyncRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly syncId: string\n readonly datasetId: string\n readonly mode: SyncRunMode\n readonly queuedAt?: Date\n readonly expectedLatestVersionId?: string\n readonly commitMessage?: string\n}\n\nexport interface StartSyncRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n}\n\nexport type FinishSyncRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n /** Source items successfully consumed. Merge runs count both upserts and deletes. */\n readonly rowsRead: number\n /** Absent when a successful run has no dataset version to reference. */\n readonly output?: DatasetVersionRef\n readonly checkpoint?: JsonValue\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\"\n readonly finishedAt?: Date\n /** Source items successfully consumed before the failure or cancellation. */\n readonly rowsRead?: number\n readonly error: SixbFailure<SyncRunFailureCode>\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"cancelled\"\n readonly finishedAt?: Date\n /** Source items successfully consumed before cancellation. */\n readonly rowsRead?: number\n readonly error?: SixbFailure<SyncRunFailureCode>\n }\n\nexport interface ListSyncRunsInput {\n readonly projectId: string\n readonly syncId?: string\n readonly syncIds?: readonly string[]\n readonly datasetId?: string\n readonly statuses?: readonly SyncRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListSyncRunsResult {\n readonly runs: readonly SyncRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestSyncRunsInput {\n readonly projectId: string\n readonly syncIds: readonly string[]\n}\n\nexport interface ListLatestSyncRunsResult {\n readonly runs: readonly SyncRunRecord[]\n}\n\nexport interface SyncRunStorage {\n queue(input: QueueSyncRunInput): Promise<SyncRunRecord>\n start(input: StartSyncRunInput): Promise<SyncRunRecord>\n finish(input: FinishSyncRunInput): Promise<SyncRunRecord>\n getById(params: { projectId: string; id: string }): Promise<SyncRunRecord | null>\n list(input: ListSyncRunsInput): Promise<ListSyncRunsResult>\n listLatestBySyncIds(input: ListLatestSyncRunsInput): Promise<ListLatestSyncRunsResult>\n}\n",
|
|
53
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport { cloneJsonValue, type JsonValue } from \"../../json\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n compareStartedAt,\n hasEmptyStatuses,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n paginate,\n toStatusSet,\n} from \"../run-listing\"\nimport { SyncRunError } from \"./errors\"\nimport { canRequeueSyncRunAfterEnqueueFailure } from \"./idempotency\"\nimport { assertSyncRunExecution } from \"./provider\"\nimport type {\n FinishSyncRunInput,\n ListLatestSyncRunsInput,\n ListLatestSyncRunsResult,\n ListSyncRunsInput,\n ListSyncRunsResult,\n QueueSyncRunInput,\n StartSyncRunInput,\n SyncRunFailureCode,\n SyncRunRecord,\n SyncRunStorage,\n} from \"./types\"\nimport { SYNC_RUN_FAILURE_CODES } from \"./types\"\n\nfunction syncRunKey(projectId: string, id: string): string {\n return `${projectId}:${id}`\n}\n\nfunction cloneSyncRunRecord(record: SyncRunRecord): SyncRunRecord {\n return structuredClone(record)\n}\n\nfunction normalizeCheckpoint(checkpoint: JsonValue | undefined): JsonValue | undefined {\n return checkpoint !== undefined ? cloneJsonValue(checkpoint) : undefined\n}\n\nfunction normalizeError(\n error: SixbFailure<SyncRunFailureCode> | undefined\n): SixbFailure<SyncRunFailureCode> | undefined {\n return error ? parseSixbFailure(error, SYNC_RUN_FAILURE_CODES) : undefined\n}\n\nexport class InMemorySyncRunStorage implements SyncRunStorage {\n private readonly rows = new Map<string, SyncRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {}\n\n snapshot(): InMemorySyncRunStorageSnapshot {\n return structuredClone(this.rows)\n }\n\n restore(snapshot: InMemorySyncRunStorageSnapshot): void {\n this.rows.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.rows.set(key, record)\n }\n }\n\n async queue(input: QueueSyncRunInput): Promise<SyncRunRecord> {\n const key = syncRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (existing && !canRequeueSyncRunAfterEnqueueFailure(existing, input)) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.rows.values()].some(\n (run) =>\n run.projectId === input.projectId &&\n run.id !== input.id &&\n run.executionId === input.executionId\n )\n ) {\n throw new SyncRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Sync run.`\n )\n }\n await assertSyncRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n syncId: input.syncId,\n })\n\n const queuedAt = new Date(input.queuedAt ?? new Date())\n if (existing) {\n const next: SyncRunRecord = {\n ...existing,\n status: \"queued\",\n queuedAt,\n startedAt: undefined,\n finishedAt: undefined,\n rowsRead: undefined,\n output: undefined,\n error: undefined,\n checkpoint: undefined,\n }\n this.rows.set(key, structuredClone(next))\n return cloneSyncRunRecord(next)\n }\n\n const record: SyncRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n syncId: input.syncId,\n datasetId: input.datasetId,\n mode: input.mode,\n status: \"queued\",\n queuedAt,\n expectedLatestVersionId: input.expectedLatestVersionId,\n commitMessage: input.commitMessage,\n }\n\n this.rows.set(key, structuredClone(record))\n return cloneSyncRunRecord(record)\n }\n\n async start(input: StartSyncRunInput): Promise<SyncRunRecord> {\n const key = syncRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n if (!existing) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n if (existing.status !== \"queued\") {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' cannot start from status '${existing.status}'.`\n )\n }\n\n const next: SyncRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n error: undefined,\n }\n this.rows.set(key, structuredClone(next))\n return cloneSyncRunRecord(next)\n }\n\n async finish(input: FinishSyncRunInput): Promise<SyncRunRecord> {\n const key = syncRunKey(input.projectId, input.id)\n const existing = this.rows.get(key)\n\n if (!existing) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const enqueueFailure = input.status === \"failed\" && input.error.code === \"queue.enqueue_failed\"\n if (\n (enqueueFailure && existing.status !== \"queued\") ||\n (!enqueueFailure && existing.status !== \"running\")\n ) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' cannot finish from status '${existing.status}'.`\n )\n }\n\n if (input.status === \"succeeded\") {\n if (input.output && input.output.datasetId !== existing.datasetId) {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' output dataset '${input.output.datasetId}' does not match '${existing.datasetId}'.`\n )\n }\n if (!input.output && input.rowsRead !== 0 && existing.mode !== \"merge\") {\n throw new SyncRunError(\n `[Sixb] Sync run '${input.id}' may omit its output with rows read only for an initial merge no-op.`\n )\n }\n }\n\n const base: SyncRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: SyncRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n rowsRead: input.rowsRead,\n output: input.output ? structuredClone(input.output) : undefined,\n error: undefined,\n checkpoint: normalizeCheckpoint(input.checkpoint),\n }\n : {\n ...base,\n rowsRead: input.rowsRead ?? existing.rowsRead,\n output: undefined,\n error: normalizeError(input.error),\n checkpoint: undefined,\n }\n\n this.rows.set(key, structuredClone(next))\n return cloneSyncRunRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<SyncRunRecord | null> {\n const record = this.rows.get(syncRunKey(params.projectId, params.id))\n return record ? cloneSyncRunRecord(record) : null\n }\n\n async list(input: ListSyncRunsInput): Promise<ListSyncRunsResult> {\n if (hasEmptyStatuses(input) || input.syncIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const syncIds = input.syncIds ? new Set(input.syncIds) : null\n\n const filtered = [...this.rows.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.syncId ? record.syncId === input.syncId : true))\n .filter((record) => (syncIds ? syncIds.has(record.syncId) : true))\n .filter((record) => (input.datasetId ? record.datasetId === input.datasetId : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneSyncRunRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestBySyncIds(input: ListLatestSyncRunsInput): Promise<ListLatestSyncRunsResult> {\n const runs = latestStartedAtByOwnerId(\n [...this.rows.values()].filter((record) => record.projectId === input.projectId),\n input.syncIds,\n (record) => record.syncId\n )\n\n return {\n runs: runs.map(cloneSyncRunRecord),\n }\n }\n}\n\nexport type InMemorySyncRunStorageSnapshot = Map<string, SyncRunRecord>\n",
|
|
54
|
+
"import type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\n\nexport type WebhookRunStatus = \"running\" | \"succeeded\" | \"failed\"\nexport type FinishWebhookRunStatus = Exclude<WebhookRunStatus, \"running\">\n\n/** Error codes a webhook run can persist and expose through its public contract. */\nexport const WEBHOOK_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"webhook.delivery_failed\",\n \"webhook.delivery_rejected\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type WebhookRunFailureCode = (typeof WEBHOOK_RUN_FAILURE_CODES)[number]\n\nexport interface WebhookRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly status: WebhookRunStatus\n readonly method: string\n readonly route: string\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly requestBodyBytes: number\n readonly requestBodySha256: string\n readonly responseStatus?: number\n readonly idempotencyKey?: string\n readonly error?: SixbFailure<WebhookRunFailureCode>\n}\n\nexport interface StartWebhookRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly method: string\n readonly route: string\n readonly requestBodyBytes: number\n readonly requestBodySha256: string\n readonly idempotencyKey?: string\n readonly startedAt?: Date\n}\n\nexport interface RestartWebhookRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n}\n\ninterface FinishWebhookRunBaseInput {\n readonly id: string\n readonly projectId: string\n readonly finishedAt?: Date\n readonly responseStatus?: number\n}\n\nexport type FinishWebhookRunInput = FinishWebhookRunBaseInput &\n (\n | {\n readonly status: \"succeeded\"\n readonly error?: never\n }\n | {\n readonly status: \"failed\"\n readonly error: SixbFailure<WebhookRunFailureCode>\n }\n )\n\nexport interface GetWebhookRunByDeliveryInput {\n readonly projectId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly idempotencyKey: string\n}\n\nexport interface ListWebhookRunsInput {\n readonly projectId: string\n readonly connectorId?: string\n readonly webhookId?: string\n readonly statuses?: readonly WebhookRunStatus[]\n readonly idempotencyKey?: string\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWebhookRunsResult {\n readonly runs: readonly WebhookRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface WebhookRunStorage {\n start(input: StartWebhookRunInput): Promise<WebhookRunRecord>\n restart(input: RestartWebhookRunInput): Promise<WebhookRunRecord>\n finish(input: FinishWebhookRunInput): Promise<WebhookRunRecord>\n getById(params: { projectId: string; id: string }): Promise<WebhookRunRecord | null>\n getByDelivery(input: GetWebhookRunByDeliveryInput): Promise<WebhookRunRecord | null>\n list(input: ListWebhookRunsInput): Promise<ListWebhookRunsResult>\n}\n\n/** Provider retries may reopen only failures classified as retryable by the shared error policy. */\nexport function canRetryWebhookRun(run: WebhookRunRecord): boolean {\n return run.status === \"failed\" && run.error?.retryable === true\n}\n",
|
|
55
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n cloneRecord,\n compareStartedAt,\n hasEmptyStatuses,\n matchesRunListDateFilters,\n paginate,\n storageKey,\n toStatusSet,\n} from \"../run-listing\"\nimport { WebhookRunError } from \"./errors\"\nimport { assertWebhookRunExecution } from \"./provider\"\nimport type {\n FinishWebhookRunInput,\n ListWebhookRunsInput,\n ListWebhookRunsResult,\n RestartWebhookRunInput,\n StartWebhookRunInput,\n WebhookRunRecord,\n WebhookRunStorage,\n} from \"./types\"\nimport { canRetryWebhookRun, WEBHOOK_RUN_FAILURE_CODES } from \"./types\"\n\nexport class InMemoryWebhookRunStorage implements WebhookRunStorage {\n private readonly runs = new Map<string, WebhookRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {}\n\n snapshot(): InMemoryWebhookRunStorageSnapshot {\n return structuredClone(this.runs)\n }\n\n restore(snapshot: InMemoryWebhookRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.runs.set(key, record)\n }\n }\n\n async start(input: StartWebhookRunInput): Promise<WebhookRunRecord> {\n await assertWebhookRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n route: input.route,\n })\n const key = storageKey(input.projectId, input.id)\n if (this.runs.has(key) || this.findByDelivery(input)) {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${input.id}' or delivery key already exists for project '${input.projectId}'.`,\n \"duplicate_run\"\n )\n }\n\n const record: WebhookRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n connectorId: input.connectorId,\n webhookId: input.webhookId,\n status: \"running\",\n method: input.method,\n route: input.route,\n startedAt: new Date(input.startedAt ?? new Date()),\n requestBodyBytes: input.requestBodyBytes,\n requestBodySha256: input.requestBodySha256,\n idempotencyKey: input.idempotencyKey,\n }\n\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async restart(input: RestartWebhookRunInput): Promise<WebhookRunRecord> {\n const existing = this.requireWebhookRun(input.projectId, input.id)\n if (!canRetryWebhookRun(existing)) {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${input.id}' cannot restart from status '${existing.status}'.`,\n \"invalid_transition\"\n )\n }\n const next: WebhookRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n finishedAt: undefined,\n responseStatus: undefined,\n error: undefined,\n }\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async finish(input: FinishWebhookRunInput): Promise<WebhookRunRecord> {\n const existing = this.requireRunningWebhookRun(input.projectId, input.id)\n const next: WebhookRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n responseStatus: input.responseStatus,\n error:\n input.status === \"failed\"\n ? parseSixbFailure(input.error, WEBHOOK_RUN_FAILURE_CODES)\n : undefined,\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WebhookRunRecord | null> {\n const record = this.runs.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async getByDelivery(input: {\n projectId: string\n connectorId: string\n webhookId: string\n idempotencyKey: string\n }): Promise<WebhookRunRecord | null> {\n const record = this.findByDelivery(input)\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWebhookRunsInput): Promise<ListWebhookRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const filtered = [...this.runs.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.connectorId ? record.connectorId === input.connectorId : true))\n .filter((record) => (input.webhookId ? record.webhookId === input.webhookId : true))\n .filter((record) =>\n input.idempotencyKey ? record.idempotencyKey === input.idempotencyKey : true\n )\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requireWebhookRun(projectId: string, id: string): WebhookRunRecord {\n const record = this.runs.get(storageKey(projectId, id))\n if (!record) {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${id}' not found for project '${projectId}'.`,\n \"not_found\"\n )\n }\n\n return record\n }\n\n private requireRunningWebhookRun(projectId: string, id: string): WebhookRunRecord {\n const record = this.requireWebhookRun(projectId, id)\n\n if (record.status !== \"running\") {\n throw new WebhookRunError(\n `[Sixb] Webhook run '${id}' for project '${projectId}' is already terminal.`,\n \"invalid_transition\"\n )\n }\n\n return record\n }\n\n private findByDelivery(input: {\n readonly projectId: string\n readonly connectorId: string\n readonly webhookId: string\n readonly idempotencyKey?: string\n }): WebhookRunRecord | undefined {\n if (input.idempotencyKey === undefined) return undefined\n return [...this.runs.values()].find(\n (run) =>\n run.projectId === input.projectId &&\n run.connectorId === input.connectorId &&\n run.webhookId === input.webhookId &&\n run.idempotencyKey === input.idempotencyKey\n )\n }\n}\n\nexport type InMemoryWebhookRunStorageSnapshot = Map<string, WebhookRunRecord>\n",
|
|
56
|
+
"/**\n * Base error for workflow-intervention storage operations.\n */\nexport class WorkflowInterventionError extends Error {\n readonly name = \"WorkflowInterventionError\"\n}\n",
|
|
57
|
+
"import { cloneRecord, hasEmptyStatuses, paginate, storageKey, toStatusSet } from \"../run-listing\"\nimport { WorkflowInterventionError } from \"./errors\"\nimport type {\n CancelWorkflowInterventionInput,\n CreateWorkflowInterventionInput,\n ExpireWorkflowInterventionInput,\n ListWorkflowInterventionsInput,\n ListWorkflowInterventionsResult,\n SubmitWorkflowInterventionInput,\n WorkflowInterventionRecord,\n WorkflowInterventionStorage,\n} from \"./types\"\n\nfunction assertNonNegativeInteger(value: number, fieldName: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention ${fieldName} must be a non-negative integer.`\n )\n }\n}\n\nexport class InMemoryWorkflowInterventionStorage implements WorkflowInterventionStorage {\n private readonly interventions = new Map<string, WorkflowInterventionRecord>()\n\n snapshot(): InMemoryWorkflowInterventionStorageSnapshot {\n return structuredClone(this.interventions)\n }\n\n restore(snapshot: InMemoryWorkflowInterventionStorageSnapshot): void {\n this.interventions.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.interventions.set(key, record)\n }\n }\n\n async create(input: CreateWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n assertNonNegativeInteger(input.nodeIndex, \"nodeIndex\")\n\n const key = storageKey(input.projectId, input.id)\n if (this.interventions.has(key)) {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const record: WorkflowInterventionRecord = {\n id: input.id,\n projectId: input.projectId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n nodeRunId: input.nodeRunId,\n nodeIndex: input.nodeIndex,\n nodeId: input.nodeId,\n nodeKey: input.nodeKey,\n interventionId: input.interventionId,\n input: cloneRecord(input.input),\n defaultResponse: cloneRecord(input.defaultResponse),\n status: \"pending\",\n requestedAt: new Date(input.requestedAt ?? new Date()),\n expiresAt: input.expiresAt ? new Date(input.expiresAt) : undefined,\n }\n\n this.interventions.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async submit(input: SubmitWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n const next: WorkflowInterventionRecord = {\n ...existing,\n status: \"submitted\",\n submittedAt: new Date(input.submittedAt ?? new Date()),\n submittedBy: input.submittedBy ? cloneRecord(input.submittedBy) : undefined,\n response: cloneRecord(input.response),\n }\n\n this.interventions.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async cancel(input: CancelWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n const next: WorkflowInterventionRecord = {\n ...existing,\n status: \"cancelled\",\n cancelledAt: new Date(input.cancelledAt ?? new Date()),\n cancelledBy: input.cancelledBy ? cloneRecord(input.cancelledBy) : undefined,\n }\n\n this.interventions.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async expire(input: ExpireWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n const next: WorkflowInterventionRecord = {\n ...existing,\n status: \"expired\",\n expiredAt: new Date(input.expiredAt ?? new Date()),\n }\n\n this.interventions.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: {\n projectId: string\n id: string\n }): Promise<WorkflowInterventionRecord | null> {\n const record = this.interventions.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWorkflowInterventionsInput): Promise<ListWorkflowInterventionsResult> {\n if (hasEmptyStatuses(input) || input.workflowIds?.length === 0) {\n return {\n interventions: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const workflowIds = input.workflowIds ? new Set(input.workflowIds) : null\n const filtered = [...this.interventions.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (statuses ? statuses.has(record.status) : true))\n .filter((record) => (input.workflowId ? record.workflowId === input.workflowId : true))\n .filter((record) => (workflowIds ? workflowIds.has(record.workflowId) : true))\n .filter((record) =>\n input.workflowRunId ? record.workflowRunId === input.workflowRunId : true\n )\n .filter((record) => (input.nodeRunId ? record.nodeRunId === input.nodeRunId : true))\n .filter((record) => (input.nodeId ? record.nodeId === input.nodeId : true))\n .filter((record) => (input.nodeKey ? record.nodeKey === input.nodeKey : true))\n .filter((record) =>\n input.interventionId ? record.interventionId === input.interventionId : true\n )\n .filter((record) =>\n input.requestedAfter ? record.requestedAt >= input.requestedAfter : true\n )\n .filter((record) =>\n input.requestedBefore ? record.requestedAt <= input.requestedBefore : true\n )\n .sort((left, right) => compareRequestedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n interventions: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requirePendingIntervention(projectId: string, id: string): WorkflowInterventionRecord {\n const record = this.interventions.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"pending\") {\n throw new WorkflowInterventionError(\n `[Sixb] Workflow intervention '${id}' for project '${projectId}' is not pending.`\n )\n }\n\n return record\n }\n}\n\nexport type InMemoryWorkflowInterventionStorageSnapshot = Map<string, WorkflowInterventionRecord>\n\nfunction compareRequestedAt(\n left: { readonly id: string; readonly requestedAt: Date },\n right: { readonly id: string; readonly requestedAt: Date },\n order: \"asc\" | \"desc\"\n): number {\n const delta = left.requestedAt.getTime() - right.requestedAt.getTime()\n if (delta !== 0) {\n return order === \"asc\" ? delta : -delta\n }\n\n if (left.id === right.id) {\n return 0\n }\n\n return order === \"asc\" ? left.id.localeCompare(right.id) : right.id.localeCompare(left.id)\n}\n",
|
|
58
|
+
"import type { AgentMessagePart } from \"../../agents/message\"\nimport type { SixbErrorCode, SixbFailure } from \"../../errors/types\"\nimport type { JsonValue } from \"../../json\"\nimport type { WorkflowIOSnapshot } from \"../../workflows/types\"\nimport type { AgentExecutionStatus, AgentRunFailureCode, AgentRunFinishReason } from \"../agents\"\n\nexport type { WorkflowIOSnapshot } from \"../../workflows/types\"\n\nexport type WorkflowRunStatus =\n | \"queued\"\n | \"running\"\n | \"waiting\"\n | \"succeeded\"\n | \"failed\"\n | \"cancelled\"\nexport type WorkflowNodeRunStatus = Exclude<WorkflowRunStatus, \"queued\">\nexport type WorkflowNodeRunType = \"step\" | \"action\" | \"intervention\" | \"agent\"\n\n/** Error codes a workflow or workflow-node run can persist and expose. */\nexport const WORKFLOW_RUN_FAILURE_CODES = [\n \"internal.unexpected\",\n \"runtime.cancelled\",\n \"workflow.node_failed\",\n \"ai.usage_limit_exceeded\",\n \"ai.usage_limit_unavailable\",\n] as const satisfies readonly [SixbErrorCode, ...SixbErrorCode[]]\n\nexport type WorkflowRunFailureCode = (typeof WORKFLOW_RUN_FAILURE_CODES)[number]\n\nexport interface WorkflowRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\nexport type WorkflowAgentNodeRunStatus = AgentExecutionStatus\n\nexport interface WorkflowAgentNodeRunExecution {\n readonly token: string\n readonly queueLeaseExpiresAt: Date\n}\n\n/** Execution details for an agent workflow node. The generic node run owns business IO. */\nexport interface WorkflowAgentNodeRunRecord {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionId: string\n /** Stable managed actor for the workflow + Agent step, not the step definition id. */\n readonly actorId: string\n readonly status: WorkflowAgentNodeRunStatus\n readonly prompt: string\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly trace?: readonly AgentMessagePart[]\n readonly diagnostics?: readonly JsonValue[]\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly attempt: number\n readonly execution?: WorkflowAgentNodeRunExecution\n readonly createdAt: Date\n readonly startedAt?: Date\n readonly completedAt?: Date\n}\n\nexport interface CreateWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionId: string\n readonly actorId: string\n readonly prompt: string\n readonly createdAt?: Date\n}\n\nexport interface StartWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly modelId?: string\n readonly execution: WorkflowAgentNodeRunExecution\n readonly startedAt?: Date\n}\n\nexport interface ReclaimWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly execution: WorkflowAgentNodeRunExecution\n}\n\nexport interface ConfirmWorkflowAgentNodeRunExecutionOwnershipInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionToken: string\n readonly queueLeaseExpiresAt: Date\n}\n\ninterface FinishWorkflowAgentNodeRunBaseInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly executionToken: string\n readonly modelId?: string\n readonly finishReason?: AgentRunFinishReason\n readonly trace?: readonly AgentMessagePart[]\n readonly diagnostics?: readonly JsonValue[]\n readonly completedAt?: Date\n}\n\nexport type FinishWorkflowAgentNodeRunInput =\n | (FinishWorkflowAgentNodeRunBaseInput & {\n readonly status: \"succeeded\"\n })\n | (FinishWorkflowAgentNodeRunBaseInput & {\n readonly status: \"failed\" | \"cancelled\"\n readonly error?: SixbFailure<AgentRunFailureCode>\n })\n\nexport interface CancelWorkflowAgentNodeRunInput {\n readonly projectId: string\n readonly nodeRunId: string\n readonly error?: SixbFailure<AgentRunFailureCode>\n readonly completedAt?: Date\n}\n\nexport interface ListWorkflowAgentNodeRunsInput {\n readonly projectId: string\n readonly actorId?: string\n readonly statuses?: readonly WorkflowAgentNodeRunStatus[]\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWorkflowAgentNodeRunsResult {\n readonly runs: readonly WorkflowAgentNodeRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface WorkflowRunRecord {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly workflowId: string\n readonly status: WorkflowRunStatus\n readonly input: WorkflowIOSnapshot\n readonly output?: WorkflowIOSnapshot\n readonly queuedAt?: Date\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n readonly attempt: number\n readonly execution?: WorkflowRunExecution\n}\n\nexport interface WorkflowNodeRunRecord {\n readonly id: string\n readonly projectId: string\n readonly workflowRunId: string\n readonly workflowId: string\n readonly nodeIndex: number\n readonly nodeType: WorkflowNodeRunType\n readonly nodeId: string\n readonly nodeKey: string\n readonly status: WorkflowNodeRunStatus\n readonly input: WorkflowIOSnapshot\n readonly startedAt: Date\n readonly finishedAt?: Date\n readonly output?: WorkflowIOSnapshot\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n}\n\nexport interface StartWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly startedAt?: Date\n readonly execution?: WorkflowRunExecution\n}\n\nexport interface QueueWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly executionId: string\n readonly workflowId: string\n readonly input: WorkflowIOSnapshot\n readonly queuedAt?: Date\n}\n\nexport interface ReclaimWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly execution: WorkflowRunExecution\n}\n\nexport interface ConfirmWorkflowRunExecutionOwnershipInput {\n readonly id: string\n readonly projectId: string\n readonly executionToken: string\n readonly queueLeaseExpiresAt: Date\n}\n\nexport interface WaitWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly waitingAt?: Date\n readonly executionToken?: string\n}\n\nexport interface ResumeWorkflowRunInput {\n readonly id: string\n readonly projectId: string\n readonly resumedAt?: Date\n readonly execution?: WorkflowRunExecution\n}\n\nexport type FinishWorkflowRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly output: WorkflowIOSnapshot\n readonly finishedAt?: Date\n readonly executionToken?: string\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly finishedAt?: Date\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n readonly executionToken?: string\n }\n\nexport interface StartWorkflowNodeRunInput {\n readonly id: string\n readonly projectId: string\n readonly workflowRunId: string\n readonly workflowId: string\n readonly nodeIndex: number\n readonly nodeType: WorkflowNodeRunType\n readonly nodeId: string\n readonly nodeKey: string\n readonly input: WorkflowIOSnapshot\n readonly startedAt?: Date\n readonly executionToken?: string\n}\n\nexport interface WaitWorkflowNodeRunInput {\n readonly id: string\n readonly projectId: string\n readonly waitingAt?: Date\n readonly executionToken?: string\n}\n\nexport type FinishWorkflowNodeRunInput =\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"succeeded\"\n readonly finishedAt?: Date\n readonly output?: WorkflowIOSnapshot\n readonly executionToken?: string\n }\n | {\n readonly id: string\n readonly projectId: string\n readonly status: \"failed\" | \"cancelled\"\n readonly finishedAt?: Date\n readonly error?: SixbFailure<WorkflowRunFailureCode>\n readonly executionToken?: string\n }\n\nexport interface ListWorkflowRunsInput {\n readonly projectId: string\n readonly workflowId?: string\n readonly workflowIds?: readonly string[]\n readonly statuses?: readonly WorkflowRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWorkflowRunsResult {\n readonly runs: readonly WorkflowRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface ListLatestWorkflowRunsInput {\n readonly projectId: string\n readonly workflowIds: readonly string[]\n}\n\nexport interface ListLatestWorkflowRunsResult {\n readonly runs: readonly WorkflowRunRecord[]\n}\n\nexport interface ListWorkflowNodeRunsInput {\n readonly projectId: string\n readonly workflowRunId?: string\n readonly workflowId?: string\n readonly nodeType?: WorkflowNodeRunType\n readonly nodeId?: string\n readonly nodeKey?: string\n readonly statuses?: readonly WorkflowNodeRunStatus[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n readonly limit?: number\n readonly offset?: number\n readonly order?: \"asc\" | \"desc\"\n}\n\nexport interface ListWorkflowNodeRunsResult {\n readonly nodes: readonly WorkflowNodeRunRecord[]\n readonly hasMore: boolean\n readonly total: number\n}\n\nexport interface WorkflowRunStorage {\n readonly nodes: WorkflowNodeRunStorage\n readonly agentNodes: WorkflowAgentNodeRunStorage\n\n queue(input: QueueWorkflowRunInput): Promise<WorkflowRunRecord>\n /** Atomically claims a queued run by transitioning it to running; competing claims must fail. */\n start(input: StartWorkflowRunInput): Promise<WorkflowRunRecord>\n reclaim(input: ReclaimWorkflowRunInput): Promise<WorkflowRunRecord>\n confirmExecutionOwnership(\n input: ConfirmWorkflowRunExecutionOwnershipInput\n ): Promise<WorkflowRunRecord>\n wait(input: WaitWorkflowRunInput): Promise<WorkflowRunRecord>\n resume(input: ResumeWorkflowRunInput): Promise<WorkflowRunRecord>\n finish(input: FinishWorkflowRunInput): Promise<WorkflowRunRecord>\n getById(params: { projectId: string; id: string }): Promise<WorkflowRunRecord | null>\n /** The runs of these executions, in first-occurrence input order; a missing one is omitted. */\n getByExecutionIds(params: {\n readonly projectId: string\n readonly executionIds: readonly string[]\n }): Promise<readonly WorkflowRunRecord[]>\n list(input: ListWorkflowRunsInput): Promise<ListWorkflowRunsResult>\n listLatestByWorkflowIds(input: ListLatestWorkflowRunsInput): Promise<ListLatestWorkflowRunsResult>\n}\n\nexport interface WorkflowAgentNodeRunStorage {\n create(input: CreateWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n start(input: StartWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n reclaim(input: ReclaimWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n confirmExecutionOwnership(\n input: ConfirmWorkflowAgentNodeRunExecutionOwnershipInput\n ): Promise<WorkflowAgentNodeRunRecord>\n cancel(input: CancelWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n finish(input: FinishWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord>\n getByNodeRunId(params: {\n projectId: string\n nodeRunId: string\n }): Promise<WorkflowAgentNodeRunRecord | null>\n list(input: ListWorkflowAgentNodeRunsInput): Promise<ListWorkflowAgentNodeRunsResult>\n}\n\nexport interface WorkflowNodeRunStorage {\n start(input: StartWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord>\n wait(input: WaitWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord>\n finish(input: FinishWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord>\n getById(params: { projectId: string; id: string }): Promise<WorkflowNodeRunRecord | null>\n list(input: ListWorkflowNodeRunsInput): Promise<ListWorkflowNodeRunsResult>\n}\n",
|
|
59
|
+
"import { parseSixbFailure } from \"../../errors/internal\"\nimport type { SixbFailure } from \"../../errors/types\"\nimport type { AgentRunFailureCode } from \"../agents\"\nimport { AGENT_RUN_FAILURE_CODES } from \"../agents\"\nimport type { ExecutionStorage } from \"../executions\"\nimport {\n cloneRecord,\n compareStartedAt,\n hasEmptyStatuses,\n latestStartedAtByOwnerId,\n matchesRunListDateFilters,\n paginate,\n storageKey,\n toStatusSet,\n} from \"../run-listing\"\nimport { WorkflowRunError } from \"./errors\"\nimport { assertWorkflowAgentNodeRunExecution, assertWorkflowRunExecution } from \"./provider\"\nimport type {\n CancelWorkflowAgentNodeRunInput,\n ConfirmWorkflowAgentNodeRunExecutionOwnershipInput,\n ConfirmWorkflowRunExecutionOwnershipInput,\n CreateWorkflowAgentNodeRunInput,\n FinishWorkflowAgentNodeRunInput,\n FinishWorkflowNodeRunInput,\n FinishWorkflowRunInput,\n ListLatestWorkflowRunsInput,\n ListLatestWorkflowRunsResult,\n ListWorkflowAgentNodeRunsInput,\n ListWorkflowAgentNodeRunsResult,\n ListWorkflowNodeRunsInput,\n ListWorkflowNodeRunsResult,\n ListWorkflowRunsInput,\n ListWorkflowRunsResult,\n QueueWorkflowRunInput,\n ReclaimWorkflowAgentNodeRunInput,\n ReclaimWorkflowRunInput,\n ResumeWorkflowRunInput,\n StartWorkflowAgentNodeRunInput,\n StartWorkflowNodeRunInput,\n StartWorkflowRunInput,\n WaitWorkflowNodeRunInput,\n WaitWorkflowRunInput,\n WorkflowAgentNodeRunRecord,\n WorkflowAgentNodeRunStorage,\n WorkflowNodeRunRecord,\n WorkflowNodeRunStorage,\n WorkflowRunFailureCode,\n WorkflowRunRecord,\n WorkflowRunStorage,\n} from \"./types\"\nimport { WORKFLOW_RUN_FAILURE_CODES } from \"./types\"\n\nfunction normalizeFailure(\n failure: SixbFailure<WorkflowRunFailureCode> | undefined\n): SixbFailure<WorkflowRunFailureCode> | undefined {\n return failure ? parseSixbFailure(failure, WORKFLOW_RUN_FAILURE_CODES) : undefined\n}\n\nfunction normalizeAgentFailure(\n failure: SixbFailure<AgentRunFailureCode> | undefined\n): SixbFailure<AgentRunFailureCode> | undefined {\n return failure ? parseSixbFailure(failure, AGENT_RUN_FAILURE_CODES) : undefined\n}\n\nfunction assertNonNegativeInteger(value: number, fieldName: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new WorkflowRunError(`[Sixb] Workflow run ${fieldName} must be a non-negative integer.`)\n }\n}\n\nexport class InMemoryWorkflowRunStorage implements WorkflowRunStorage {\n readonly nodes: InMemoryWorkflowNodeRunStorage\n readonly agentNodes: InMemoryWorkflowAgentNodeRunStorage\n\n private readonly runs = new Map<string, WorkflowRunRecord>()\n\n constructor(private readonly executions: ExecutionStorage) {\n this.nodes = new InMemoryWorkflowNodeRunStorage({\n requireRunningWorkflowRun: (projectId, id) => this.requireRunningWorkflowRun(projectId, id),\n requireActiveWorkflowRun: (projectId, id) => this.requireActiveWorkflowRun(projectId, id),\n assertExecutionOwnership: (projectId, id, token) =>\n this.assertExecutionOwnership(projectId, id, token),\n })\n this.agentNodes = new InMemoryWorkflowAgentNodeRunStorage(\n {\n requireAgentNodeRun: (projectId, id) => this.nodes.requireAgentNodeRun(projectId, id),\n requireWorkflowRun: (projectId, id) => this.requireExistingWorkflowRun(projectId, id),\n },\n this.executions\n )\n }\n\n snapshot(): InMemoryWorkflowRunStorageSnapshot {\n return {\n runs: structuredClone(this.runs),\n nodes: this.nodes.snapshot(),\n agentNodes: this.agentNodes.snapshot(),\n }\n }\n\n restore(snapshot: InMemoryWorkflowRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot.runs)) {\n this.runs.set(key, record)\n }\n this.nodes.restore(snapshot.nodes)\n this.agentNodes.restore(snapshot.agentNodes)\n }\n\n async queue(input: QueueWorkflowRunInput): Promise<WorkflowRunRecord> {\n const key = storageKey(input.projectId, input.id)\n if (this.runs.has(key)) {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n if (\n [...this.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new WorkflowRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another workflow run.`\n )\n }\n await assertWorkflowRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n workflowId: input.workflowId,\n })\n\n const queuedAt = new Date(input.queuedAt ?? new Date())\n const record: WorkflowRunRecord = {\n id: input.id,\n projectId: input.projectId,\n executionId: input.executionId,\n workflowId: input.workflowId,\n status: \"queued\",\n input: cloneRecord(input.input),\n queuedAt,\n startedAt: queuedAt,\n attempt: 0,\n }\n\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async start(input: StartWorkflowRunInput): Promise<WorkflowRunRecord> {\n const key = storageKey(input.projectId, input.id)\n const existing = this.runs.get(key)\n if (!existing || existing.status !== \"queued\") {\n throw new WorkflowRunError(\n existing\n ? `[Sixb] Workflow run '${input.id}' cannot start from status '${existing.status}'.`\n : `[Sixb] Workflow run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const next: WorkflowRunRecord = {\n ...existing,\n status: \"running\",\n startedAt: new Date(input.startedAt ?? new Date()),\n finishedAt: undefined,\n error: undefined,\n attempt: existing.attempt + 1,\n execution: input.execution ? cloneRecord(input.execution) : undefined,\n }\n\n this.runs.set(key, cloneRecord(next))\n return cloneRecord(next)\n }\n\n async finish(input: FinishWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireFinishableWorkflowRun(input)\n this.assertRecordExecutionOwnership(existing, input.executionToken)\n const base: WorkflowRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n execution: undefined,\n }\n\n const next: WorkflowRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: cloneRecord(input.output),\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeFailure(input.error),\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async wait(input: WaitWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireRunningWorkflowRun(input.projectId, input.id)\n this.assertRecordExecutionOwnership(existing, input.executionToken)\n const next: WorkflowRunRecord = {\n ...existing,\n status: \"waiting\",\n finishedAt: undefined,\n error: undefined,\n execution: undefined,\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async resume(input: ResumeWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireWaitingWorkflowRun(input.projectId, input.id)\n const next: WorkflowRunRecord = {\n ...existing,\n status: \"running\",\n finishedAt: undefined,\n error: undefined,\n attempt: existing.attempt + 1,\n execution: input.execution ? cloneRecord(input.execution) : undefined,\n }\n\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async reclaim(input: ReclaimWorkflowRunInput): Promise<WorkflowRunRecord> {\n const existing = this.requireRunningWorkflowRun(input.projectId, input.id)\n const next: WorkflowRunRecord = {\n ...existing,\n attempt: existing.attempt + 1,\n execution: cloneRecord(input.execution),\n }\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async confirmExecutionOwnership(\n input: ConfirmWorkflowRunExecutionOwnershipInput\n ): Promise<WorkflowRunRecord> {\n const existing = this.requireRunningWorkflowRun(input.projectId, input.id)\n this.assertRecordExecutionOwnership(existing, input.executionToken)\n const next: WorkflowRunRecord = {\n ...existing,\n execution: {\n token: input.executionToken,\n queueLeaseExpiresAt: new Date(\n Math.max(\n existing.execution!.queueLeaseExpiresAt.getTime(),\n input.queueLeaseExpiresAt.getTime()\n )\n ),\n },\n }\n this.runs.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WorkflowRunRecord | null> {\n const record = this.runs.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async getByExecutionIds(params: {\n readonly projectId: string\n readonly executionIds: readonly string[]\n }): Promise<readonly WorkflowRunRecord[]> {\n const byExecution = new Map(\n [...this.runs.values()]\n .filter((record) => record.projectId === params.projectId)\n .map((record) => [record.executionId, record])\n )\n\n return [...new Set(params.executionIds)].flatMap((executionId) => {\n const record = byExecution.get(executionId)\n return record ? [cloneRecord(record)] : []\n })\n }\n\n async list(input: ListWorkflowRunsInput): Promise<ListWorkflowRunsResult> {\n if (hasEmptyStatuses(input) || input.workflowIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const workflowIds = input.workflowIds ? new Set(input.workflowIds) : null\n const filtered = [...this.runs.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) => (input.workflowId ? record.workflowId === input.workflowId : true))\n .filter((record) => (workflowIds ? workflowIds.has(record.workflowId) : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n runs: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestByWorkflowIds(\n input: ListLatestWorkflowRunsInput\n ): Promise<ListLatestWorkflowRunsResult> {\n const runs = latestStartedAtByOwnerId(\n [...this.runs.values()].filter((record) => record.projectId === input.projectId),\n input.workflowIds,\n (record) => record.workflowId\n )\n\n return {\n runs: runs.map(cloneRecord),\n }\n }\n\n private requireExistingWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.runs.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' not found for project '${projectId}'.`\n )\n }\n\n return record\n }\n\n private requireRunningWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(projectId, id)\n if (record.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' for project '${projectId}' must be running.`\n )\n }\n\n return record\n }\n\n private requireWaitingWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(projectId, id)\n if (record.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' for project '${projectId}' must be waiting.`\n )\n }\n\n return record\n }\n\n private requireActiveWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(projectId, id)\n if (record.status !== \"running\" && record.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n\n private requireFinishableWorkflowRun(input: FinishWorkflowRunInput): WorkflowRunRecord {\n const record = this.requireExistingWorkflowRun(input.projectId, input.id)\n if (record.status === \"running\") {\n return record\n }\n\n if (record.status === \"waiting\" && input.status !== \"succeeded\") {\n return record\n }\n\n if (record.status === \"queued\" && input.status !== \"succeeded\") {\n return record\n }\n\n throw new WorkflowRunError(\n `[Sixb] Workflow run '${input.id}' for project '${input.projectId}' cannot be finished from status '${record.status}'.`\n )\n }\n\n private assertExecutionOwnership(projectId: string, id: string, token?: string): void {\n this.assertRecordExecutionOwnership(this.requireExistingWorkflowRun(projectId, id), token)\n }\n\n private assertRecordExecutionOwnership(record: WorkflowRunRecord, token?: string): void {\n if (record.execution?.token !== token) {\n throw new WorkflowRunError(\n `[Sixb] Execution token is no longer current on workflow run '${record.id}'.`\n )\n }\n }\n}\n\nexport class InMemoryWorkflowNodeRunStorage implements WorkflowNodeRunStorage {\n private readonly nodes = new Map<string, WorkflowNodeRunRecord>()\n\n constructor(\n private readonly workflowRuns: {\n requireRunningWorkflowRun(projectId: string, id: string): WorkflowRunRecord\n requireActiveWorkflowRun(projectId: string, id: string): WorkflowRunRecord\n assertExecutionOwnership(projectId: string, id: string, token?: string): void\n }\n ) {}\n\n snapshot(): InMemoryWorkflowNodeRunStorageSnapshot {\n return structuredClone(this.nodes)\n }\n\n restore(snapshot: InMemoryWorkflowNodeRunStorageSnapshot): void {\n this.nodes.clear()\n for (const [key, record] of structuredClone(snapshot)) {\n this.nodes.set(key, record)\n }\n }\n\n async start(input: StartWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n assertNonNegativeInteger(input.nodeIndex, \"nodeIndex\")\n\n const workflowRun = this.workflowRuns.requireRunningWorkflowRun(\n input.projectId,\n input.workflowRunId\n )\n this.workflowRuns.assertExecutionOwnership(\n input.projectId,\n input.workflowRunId,\n input.executionToken\n )\n if (workflowRun.workflowId !== input.workflowId) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${input.id}' workflow '${input.workflowId}' does not match workflow run '${input.workflowRunId}' workflow '${workflowRun.workflowId}'.`\n )\n }\n\n const key = storageKey(input.projectId, input.id)\n if (this.nodes.has(key)) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const record: WorkflowNodeRunRecord = {\n id: input.id,\n projectId: input.projectId,\n workflowRunId: input.workflowRunId,\n workflowId: input.workflowId,\n nodeIndex: input.nodeIndex,\n nodeType: input.nodeType,\n nodeId: input.nodeId,\n nodeKey: input.nodeKey,\n status: \"running\",\n input: cloneRecord(input.input),\n startedAt: new Date(input.startedAt ?? new Date()),\n }\n\n this.nodes.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async finish(input: FinishWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n const existing = this.requireActiveNodeRun(input.projectId, input.id)\n this.workflowRuns.assertExecutionOwnership(\n input.projectId,\n existing.workflowRunId,\n input.executionToken\n )\n const base: WorkflowNodeRunRecord = {\n ...existing,\n status: input.status,\n finishedAt: new Date(input.finishedAt ?? new Date()),\n }\n\n const next: WorkflowNodeRunRecord =\n input.status === \"succeeded\"\n ? {\n ...base,\n output: input.output ? cloneRecord(input.output) : undefined,\n error: undefined,\n }\n : {\n ...base,\n output: undefined,\n error: normalizeFailure(input.error),\n }\n\n this.nodes.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async wait(input: WaitWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n const existing = this.requireRunningNodeRun(input.projectId, input.id)\n this.workflowRuns.requireActiveWorkflowRun(input.projectId, existing.workflowRunId)\n this.workflowRuns.assertExecutionOwnership(\n input.projectId,\n existing.workflowRunId,\n input.executionToken\n )\n\n const next: WorkflowNodeRunRecord = {\n ...existing,\n status: \"waiting\",\n finishedAt: undefined,\n output: undefined,\n error: undefined,\n }\n\n this.nodes.set(storageKey(input.projectId, input.id), cloneRecord(next))\n return cloneRecord(next)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WorkflowNodeRunRecord | null> {\n const record = this.nodes.get(storageKey(params.projectId, params.id))\n return record ? cloneRecord(record) : null\n }\n\n async list(input: ListWorkflowNodeRunsInput): Promise<ListWorkflowNodeRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n nodes: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const order = input.order ?? \"desc\"\n const statuses = toStatusSet(input.statuses)\n const filtered = [...this.nodes.values()]\n .filter((record) => record.projectId === input.projectId)\n .filter((record) =>\n input.workflowRunId ? record.workflowRunId === input.workflowRunId : true\n )\n .filter((record) => (input.workflowId ? record.workflowId === input.workflowId : true))\n .filter((record) => (input.nodeType ? record.nodeType === input.nodeType : true))\n .filter((record) => (input.nodeId ? record.nodeId === input.nodeId : true))\n .filter((record) => (input.nodeKey ? record.nodeKey === input.nodeKey : true))\n .filter((record) =>\n matchesRunListDateFilters(record, {\n statuses,\n startedAfter: input.startedAfter,\n startedBefore: input.startedBefore,\n })\n )\n .sort((left, right) => compareStartedAt(left, right, order))\n\n const { page, total, hasMore } = paginate(filtered, input)\n\n return {\n nodes: page.map(cloneRecord),\n hasMore,\n total,\n }\n }\n\n private requireRunningNodeRun(projectId: string, id: string): WorkflowNodeRunRecord {\n const record = this.nodes.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' for project '${projectId}' must be running.`\n )\n }\n\n return record\n }\n\n private requireActiveNodeRun(projectId: string, id: string): WorkflowNodeRunRecord {\n const record = this.nodes.get(storageKey(projectId, id))\n if (!record) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (record.status !== \"running\" && record.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' for project '${projectId}' is already terminal.`\n )\n }\n\n return record\n }\n\n requireAgentNodeRun(projectId: string, id: string): WorkflowNodeRunRecord {\n const node = this.nodes.get(storageKey(projectId, id))\n if (!node) {\n throw new WorkflowRunError(\n `[Sixb] Workflow node run '${id}' not found for project '${projectId}'.`\n )\n }\n if (node.nodeType !== \"agent\") {\n throw new WorkflowRunError(`[Sixb] Workflow node run '${id}' is not an agent node.`)\n }\n return node\n }\n}\n\nexport class InMemoryWorkflowAgentNodeRunStorage implements WorkflowAgentNodeRunStorage {\n private readonly runs = new Map<string, WorkflowAgentNodeRunRecord>()\n\n constructor(\n private readonly nodes: {\n requireAgentNodeRun(projectId: string, id: string): WorkflowNodeRunRecord\n requireWorkflowRun(projectId: string, id: string): WorkflowRunRecord\n },\n private readonly executions: ExecutionStorage\n ) {}\n\n snapshot(): InMemoryWorkflowAgentNodeRunStorageSnapshot {\n return structuredClone(this.runs)\n }\n\n restore(snapshot: InMemoryWorkflowAgentNodeRunStorageSnapshot): void {\n this.runs.clear()\n for (const [key, record] of structuredClone(snapshot)) this.runs.set(key, record)\n }\n\n async create(input: CreateWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const node = this.nodes.requireAgentNodeRun(input.projectId, input.nodeRunId)\n const workflowRun = this.nodes.requireWorkflowRun(input.projectId, node.workflowRunId)\n await assertWorkflowAgentNodeRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n nodeRunId: input.nodeRunId,\n actorId: input.actorId,\n workflowExecutionId: workflowRun.executionId,\n })\n if (node.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${input.nodeRunId}' must be running when queued.`\n )\n }\n const key = storageKey(input.projectId, input.nodeRunId)\n if (this.runs.has(key)) {\n throw new WorkflowRunError(\n `[Sixb] Agent execution already exists for workflow node run '${input.nodeRunId}'.`\n )\n }\n if (\n [...this.runs.values()].some(\n (run) => run.projectId === input.projectId && run.executionId === input.executionId\n )\n ) {\n throw new WorkflowRunError(\n `[Sixb] Execution '${input.executionId}' already belongs to another Workflow Agent-node run.`\n )\n }\n const record: WorkflowAgentNodeRunRecord = {\n projectId: input.projectId,\n nodeRunId: input.nodeRunId,\n executionId: input.executionId,\n actorId: input.actorId,\n status: \"queued\",\n prompt: input.prompt,\n attempt: 0,\n createdAt: new Date(input.createdAt ?? new Date()),\n }\n this.runs.set(key, cloneRecord(record))\n return cloneRecord(record)\n }\n\n async start(input: StartWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireStatus(input.projectId, input.nodeRunId, \"queued\")\n const next: WorkflowAgentNodeRunRecord = {\n ...run,\n status: \"running\",\n ...(input.modelId ? { modelId: input.modelId } : {}),\n attempt: 1,\n execution: cloneRecord(input.execution),\n startedAt: new Date(input.startedAt ?? new Date()),\n }\n return this.save(next)\n }\n\n async reclaim(input: ReclaimWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireStatus(input.projectId, input.nodeRunId, \"running\")\n return this.save({ ...run, attempt: run.attempt + 1, execution: cloneRecord(input.execution) })\n }\n\n async confirmExecutionOwnership(\n input: ConfirmWorkflowAgentNodeRunExecutionOwnershipInput\n ): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireOwned(input.projectId, input.nodeRunId, input.executionToken)\n return this.save({\n ...run,\n execution: {\n token: input.executionToken,\n queueLeaseExpiresAt: new Date(\n Math.max(\n run.execution!.queueLeaseExpiresAt.getTime(),\n input.queueLeaseExpiresAt.getTime()\n )\n ),\n },\n })\n }\n\n async finish(input: FinishWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireOwned(input.projectId, input.nodeRunId, input.executionToken)\n return this.save({\n ...run,\n status: input.status,\n ...(input.modelId === undefined ? {} : { modelId: input.modelId }),\n ...(input.finishReason === undefined ? {} : { finishReason: input.finishReason }),\n ...(input.trace === undefined ? {} : { trace: cloneRecord(input.trace) }),\n ...(input.diagnostics === undefined ? {} : { diagnostics: cloneRecord(input.diagnostics) }),\n ...(input.status === \"succeeded\" || input.error === undefined\n ? {}\n : { error: normalizeAgentFailure(input.error) }),\n execution: undefined,\n completedAt: new Date(input.completedAt ?? new Date()),\n })\n }\n\n async cancel(input: CancelWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const run = this.requireExisting(input.projectId, input.nodeRunId)\n if (run.status !== \"queued\" && run.status !== \"running\") {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${input.nodeRunId}' cannot be cancelled from status '${run.status}'.`\n )\n }\n return this.save({\n ...run,\n status: \"cancelled\",\n execution: undefined,\n error: normalizeAgentFailure(input.error),\n completedAt: new Date(input.completedAt ?? new Date()),\n })\n }\n\n async getByNodeRunId(params: {\n projectId: string\n nodeRunId: string\n }): Promise<WorkflowAgentNodeRunRecord | null> {\n const run = this.runs.get(storageKey(params.projectId, params.nodeRunId))\n return run ? cloneRecord(run) : null\n }\n\n async list(input: ListWorkflowAgentNodeRunsInput): Promise<ListWorkflowAgentNodeRunsResult> {\n const statuses = input.statuses ? new Set(input.statuses) : null\n const order = input.order ?? \"desc\"\n const filtered = [...this.runs.values()]\n .filter((run) => run.projectId === input.projectId)\n .filter((run) => (input.actorId ? run.actorId === input.actorId : true))\n .filter((run) => (statuses ? statuses.has(run.status) : true))\n .sort((a, b) =>\n order === \"asc\"\n ? a.createdAt.getTime() - b.createdAt.getTime()\n : b.createdAt.getTime() - a.createdAt.getTime()\n )\n const { page, total, hasMore } = paginate(filtered, input)\n return { runs: page.map(cloneRecord), total, hasMore }\n }\n\n private requireStatus(\n projectId: string,\n nodeRunId: string,\n status: WorkflowAgentNodeRunRecord[\"status\"]\n ): WorkflowAgentNodeRunRecord {\n const run = this.runs.get(storageKey(projectId, nodeRunId))\n if (!run) throw new WorkflowRunError(`[Sixb] Agent workflow node run '${nodeRunId}' not found.`)\n if (run.status !== status) {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${nodeRunId}' must be ${status} (status '${run.status}').`\n )\n }\n return run\n }\n\n private requireExisting(projectId: string, nodeRunId: string): WorkflowAgentNodeRunRecord {\n const run = this.runs.get(storageKey(projectId, nodeRunId))\n if (!run) {\n throw new WorkflowRunError(\n `[Sixb] Agent workflow node run '${nodeRunId}' not found for project '${projectId}'.`\n )\n }\n return run\n }\n\n private requireOwned(\n projectId: string,\n nodeRunId: string,\n token: string\n ): WorkflowAgentNodeRunRecord {\n const run = this.requireStatus(projectId, nodeRunId, \"running\")\n if (run.execution?.token !== token) {\n throw new WorkflowRunError(\n `[Sixb] Execution token is no longer current on agent workflow node run '${nodeRunId}'.`\n )\n }\n return run\n }\n\n private save(record: WorkflowAgentNodeRunRecord): WorkflowAgentNodeRunRecord {\n this.runs.set(storageKey(record.projectId, record.nodeRunId), cloneRecord(record))\n return cloneRecord(record)\n }\n}\n\nexport interface InMemoryWorkflowRunStorageSnapshot {\n readonly runs: Map<string, WorkflowRunRecord>\n readonly nodes: InMemoryWorkflowNodeRunStorageSnapshot\n readonly agentNodes: InMemoryWorkflowAgentNodeRunStorageSnapshot\n}\n\nexport type InMemoryWorkflowNodeRunStorageSnapshot = Map<string, WorkflowNodeRunRecord>\nexport type InMemoryWorkflowAgentNodeRunStorageSnapshot = Map<string, WorkflowAgentNodeRunRecord>\n",
|
|
60
|
+
"import type { InMemoryStorageSnapshot } from \".\"\n\nexport interface InMemoryStorageTestingAdapter {\n snapshot(): InMemoryStorageSnapshot\n}\n\nconst testingAdapters = new WeakMap<object, InMemoryStorageTestingAdapter>()\n\nexport function registerInMemoryStorageTestingAdapter(\n storage: object,\n adapter: InMemoryStorageTestingAdapter\n): void {\n testingAdapters.set(storage, adapter)\n}\n\n/** @internal Relative test-only access; intentionally absent from every package barrel. */\nexport function getInMemoryStorageTestingAdapter(storage: object): InMemoryStorageTestingAdapter {\n const adapter = testingAdapters.get(storage)\n if (!adapter) throw new Error(\"[Sixb] In-memory storage testing adapter is unavailable.\")\n return adapter\n}\n",
|
|
61
|
+
"import type { QueryScalarKind } from \"../../objects/query/ir\"\nimport {\n queryScalarKindForSchema,\n resolvePropertyQueryCapabilities,\n resolveQuerySchema,\n} from \"../../ontology/query-capabilities\"\nimport type { OntologyDefinitionCatalog } from \"../../ontology/registry\"\nimport type { ObjectQueryIndexDefinition } from \"../../ontology/types\"\nimport type { Storage } from \"../types\"\n\nexport interface ObjectQueryPreparationPlan {\n readonly projectId: string\n readonly objectTypes: readonly {\n readonly objectTypeId: string\n readonly properties: readonly {\n readonly propertyId: string\n readonly scalarKind?: QueryScalarKind\n readonly filterable: boolean\n readonly sortable: boolean\n readonly text: boolean\n }[]\n readonly indexes: readonly ObjectQueryIndexDefinition[]\n }[]\n}\n\nexport interface ObjectQueryPreparationResult {\n readonly status: \"prepared\" | \"current\"\n readonly objectTypes: number\n readonly indexes: number\n readonly warnings: readonly string[]\n}\n\n/** Optional maintenance capability, separate from object reads and writes. */\nexport interface QueryPreparationCapableStorage extends Storage {\n /** Coordinate concurrent callers and skip completed plans. Backfills may block writes. */\n prepareObjectQueries(plan: ObjectQueryPreparationPlan): Promise<ObjectQueryPreparationResult>\n}\n\nexport function isQueryPreparationCapableStorage(\n storage: Storage\n): storage is QueryPreparationCapableStorage {\n return \"prepareObjectQueries\" in storage && typeof storage.prepareObjectQueries === \"function\"\n}\n\n/** Prepare declared query access paths after schema migration. Providers own physical layout;\n * applications describe their ontology, not PostgreSQL expressions or generated columns.\n * This is maintenance: backfills may block writes and must not run in a request handler. */\nexport async function prepareObjectQueries(input: {\n projectId: string\n ontology: OntologyDefinitionCatalog\n storage: Storage\n}): Promise<ObjectQueryPreparationResult> {\n if (!isQueryPreparationCapableStorage(input.storage)) {\n throw new Error(\"[Sixb] This storage provider does not support object query preparation\")\n }\n\n const values = input.ontology.getValueTypesById()\n const objectTypes = input.ontology.listObjectTypes().map((type) => ({\n objectTypeId: type.id,\n properties: type.properties\n .filter((property) => property.mode !== \"telemetry\" && !property.primary)\n .map((property) => {\n const capabilities = resolvePropertyQueryCapabilities(property, values)\n const schema = resolveQuerySchema(property.schema, values)\n return {\n propertyId: property.id,\n scalarKind: schema ? queryScalarKindForSchema(schema) : undefined,\n filterable: capabilities.operators.includes(\"eq\"),\n sortable: capabilities.sortable,\n text: capabilities.text,\n }\n })\n .filter((property) => property.filterable || property.sortable || property.text),\n indexes: type.query?.indexes ?? [],\n }))\n return input.storage.prepareObjectQueries({ projectId: input.projectId, objectTypes })\n}\n",
|
|
62
|
+
"import { UniqueValueViolationError } from \"../../materialization/errors\"\nimport type { OntologyDefinitionCatalog } from \"../../ontology/registry\"\nimport {\n UNIQUE_VALUE_KEY_VERSION,\n type UniquePropertyDefinition,\n uniquePropertiesOf,\n uniqueValueKey,\n} from \"../../ontology/unique-values\"\nimport { isStorageSerializationFailure } from \"../errors\"\nimport type { PreparedUniqueProperty, UniqueValueEntry } from \"../ontology/unique-values\"\nimport type { Storage } from \"../types\"\n\n/** Objects read, and values inserted, per round of a property's backfill. */\nconst BACKFILL_PAGE_ROWS = 1_000\n\n/** A write committing during a backfill makes it fail serialization: start it over. */\nconst MAX_PREPARATION_ATTEMPTS = 5\nconst FIRST_RETRY_DELAY_MS = 50\n\ninterface DeclaredUniqueProperty extends UniquePropertyDefinition {\n readonly objectTypeId: string\n}\n\n/**\n * Brings the stored unique values in line with the ontology: builds those of a property that is\n * newly unique (or whose keys changed kind or version) from the objects already stored, and drops\n * those of a property that is no longer unique. Object writes keep them current from then on, and\n * refuse to claim a value of a property this has not prepared.\n *\n * Each property is prepared in its own serializable transaction, which first takes the provider's\n * preparation lock. Two objects already sharing a value fail the preparation, naming both, and\n * leave the property unprepared.\n */\nexport async function prepareUniqueProperties(input: {\n readonly storage: Storage\n readonly projectId: string\n readonly ontology: OntologyDefinitionCatalog\n}): Promise<void> {\n const { storage, projectId } = input\n const declared = declaredUniqueProperties(input.ontology)\n const declaredKeys = new Set(declared.map(propertyKey))\n\n for (const property of declared) {\n await withRetries(property, () =>\n storage.transaction((tx) => backfillProperty(tx, projectId, property), {\n isolation: \"serializable\",\n })\n )\n }\n\n const undeclared = (await storage.ontology.uniqueValues.listPrepared({ projectId })).filter(\n (property) => !declaredKeys.has(propertyKey(property))\n )\n for (const { objectTypeId, propertyId } of undeclared) {\n await withRetries({ objectTypeId, propertyId }, () =>\n storage.transaction(\n async (tx) => {\n await tx.ontology.uniqueValues.lockPreparation({ projectId })\n await tx.ontology.uniqueValues.clear({ projectId, objectTypeId, propertyId })\n },\n { isolation: \"serializable\" }\n )\n )\n }\n}\n\nfunction declaredUniqueProperties(ontology: OntologyDefinitionCatalog): DeclaredUniqueProperty[] {\n const valueTypesById = ontology.getValueTypesById()\n return ontology.listObjectTypes().flatMap((objectType) =>\n uniquePropertiesOf(objectType, valueTypesById).map((property) => ({\n objectTypeId: objectType.id,\n ...property,\n }))\n )\n}\n\nasync function withRetries(\n property: { readonly objectTypeId: string; readonly propertyId: string },\n run: () => Promise<void>\n): Promise<void> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await run()\n } catch (error) {\n if (!isStorageSerializationFailure(error) || attempt >= MAX_PREPARATION_ATTEMPTS) {\n throw preparationError(property, error)\n }\n await new Promise((resolve) => setTimeout(resolve, FIRST_RETRY_DELAY_MS * 2 ** (attempt - 1)))\n }\n }\n}\n\nasync function backfillProperty(\n tx: Storage,\n projectId: string,\n property: DeclaredUniqueProperty\n): Promise<void> {\n const { objectTypeId, propertyId } = property\n const values = tx.ontology.uniqueValues\n await values.lockPreparation({ projectId })\n\n const current = (await values.listPrepared({ projectId })).find(\n (prepared) => propertyKey(prepared) === propertyKey(property)\n )\n if (current && isCurrent(current, property)) return\n\n await values.clear({ projectId, objectTypeId, propertyId })\n\n let afterPrimaryId: string | undefined\n do {\n const page = await tx.objects.listByPrimaryIdPage({\n projectId,\n objectTypeId,\n limit: BACKFILL_PAGE_ROWS,\n ...(afterPrimaryId === undefined ? {} : { afterPrimaryId }),\n })\n if (afterPrimaryId === undefined && page.objects.length > 0) {\n console.info(`[Sixb] Preparing unique property '${objectTypeId}.${propertyId}'.`)\n }\n\n const entries: UniqueValueEntry[] = []\n for (const object of page.objects) {\n const valueKey = uniqueValueKey(property.kind, object.properties[propertyId])\n if (valueKey !== null) entries.push({ valueKey, primaryId: object.primaryId })\n }\n if (entries.length > 0) await values.insert({ projectId, objectTypeId, propertyId, entries })\n\n afterPrimaryId = page.nextPrimaryId\n } while (afterPrimaryId !== undefined)\n\n await values.markPrepared({\n projectId,\n objectTypeId,\n propertyId,\n keyKind: property.kind,\n keyVersion: UNIQUE_VALUE_KEY_VERSION,\n preparedAt: new Date().toISOString(),\n })\n}\n\n/** Keys are rebuilt when they were computed for another kind, as after a schema change. */\nfunction isCurrent(prepared: PreparedUniqueProperty, property: DeclaredUniqueProperty): boolean {\n return prepared.keyKind === property.kind && prepared.keyVersion === UNIQUE_VALUE_KEY_VERSION\n}\n\nfunction preparationError(\n property: { readonly objectTypeId: string; readonly propertyId: string },\n error: unknown\n): unknown {\n if (!(error instanceof UniqueValueViolationError)) return error\n return new Error(\n `[Sixb] Cannot make '${property.objectTypeId}.${property.propertyId}' unique: objects ` +\n `'${error.holderPrimaryId}' and '${error.claimantPrimaryId}' share a value. ` +\n \"Fix the data, then start again.\",\n { cause: error }\n )\n}\n\nfunction propertyKey(property: { readonly objectTypeId: string; readonly propertyId: string }) {\n return JSON.stringify([property.objectTypeId, property.propertyId])\n}\n",
|
|
63
|
+
"import {\n isQueryPreparationCapableStorage,\n type ObjectQueryPreparationResult,\n prepareObjectQueries,\n} from \"../objects/query-preparation\"\nimport type { Storage } from \"../types\"\nimport { prepareUniqueProperties } from \"./prepare-unique-properties\"\nimport type {\n MigrationCapableStorage,\n MigrationReport,\n StorageMigrationOptions,\n StorageMigrationResult,\n} from \"./types\"\n\nexport function isMigrationCapableStorage(storage: Storage): storage is MigrationCapableStorage {\n return Array.isArray((storage as { migrators?: unknown }).migrators)\n}\n\n/**\n * Run schema migrations, then, given the project's ontology, prepare query indexes when the\n * provider supports it and the stored values of unique properties.\n */\nexport async function migrateStorage(\n storage: Storage,\n options?: StorageMigrationOptions\n): Promise<StorageMigrationResult> {\n const reports: MigrationReport[] = []\n if (isMigrationCapableStorage(storage)) {\n for (const migrator of storage.migrators) {\n reports.push(await migrator.migrate())\n }\n }\n\n let queries: ObjectQueryPreparationResult | undefined\n if (options && isQueryPreparationCapableStorage(storage)) {\n queries = await prepareObjectQueries({ ...options, storage })\n for (const warning of queries.warnings) {\n console.warn(`[Sixb] ${warning}`)\n }\n }\n\n // Not part of the status: it only reads and writes rows, and says when it builds values.\n if (options) await prepareUniqueProperties({ ...options, storage })\n\n let status: StorageMigrationResult[\"status\"] = \"skipped\"\n if (reports.length > 0 || queries) {\n status = \"current\"\n }\n if (reports.some((report) => report.status === \"migrated\") || queries?.status === \"prepared\") {\n status = \"migrated\"\n }\n\n if (queries) return { status, reports, queries }\n return { status, reports }\n}\n",
|
|
64
|
+
"import type { Storage } from \"../types\"\nimport { isMigrationCapableStorage } from \"./migrate-storage\"\n\nexport interface StorageSchemaCheck {\n readonly ok: boolean\n /**\n * Whether anything was read. False when the storage exposes no migrators: usable on the\n * strength of having no schema rather than of a verified one.\n */\n readonly verified: boolean\n /** Absent only when `ok`. Names the adapter, the state, and what to do about it. */\n readonly reason?: string\n}\n\n/**\n * Reports whether the configured storage's schema is usable, without touching it.\n *\n * Storage with no migrators is usable by definition. Failures are returned rather than thrown,\n * because both callers report instead of aborting: `/ready` and `sixb check`.\n */\nexport async function checkStorageSchema(storage: Storage): Promise<StorageSchemaCheck> {\n if (!isMigrationCapableStorage(storage)) return { ok: true, verified: false }\n\n try {\n // `status()` is the only read-only member of the migrator contract: `migrate()` calls\n // `ensure()` first, so it runs DDL and takes an advisory lock. This serves `/ready`.\n const statuses = await Promise.all(storage.migrators.map((migrator) => migrator.status()))\n const unusable = statuses.filter((status) => status.state !== \"current\")\n\n if (unusable.length === 0) return { ok: true, verified: true }\n\n return {\n ok: false,\n verified: true,\n // Named, because \"could not be verified\" leaves an operator guessing between a missing\n // migration, a schema newer than the build, and no database at all.\n reason: unusable\n .map((status) => `${status.adapterId}: ${status.state} — ${status.reason ?? \"\"}`)\n .join(\"; \"),\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n ok: false,\n verified: false,\n reason: `Storage schema could not be verified: ${message}`,\n }\n }\n}\n",
|
|
65
|
+
"import type {\n DefineMigrationsOptions,\n MigrationHistoryStore,\n MigrationPlan,\n MigrationRecord,\n MigrationReport,\n MigrationSet,\n MigrationStatus,\n MigrationStep,\n MigrationStepOptions,\n} from \"./types\"\n\nexport interface PlanMigrationSetParams<TContext> {\n readonly migrations: MigrationSet<TContext>\n readonly state: MigrationHistoryStore\n}\n\nexport interface RunMigrationSetParams<TContext> extends PlanMigrationSetParams<TContext> {\n readonly context: TContext\n readonly now?: () => string\n}\n\nexport function step<TContext>(\n id: string,\n up: (context: TContext) => void | Promise<void>,\n options: MigrationStepOptions = {}\n): MigrationStep<TContext> {\n const { version, name } = parseMigrationId(id)\n\n return {\n id,\n version,\n name,\n checksum: options.checksum,\n up,\n }\n}\n\nexport function defineMigrations<TContext>(\n options: DefineMigrationsOptions<TContext>\n): MigrationSet<TContext> {\n const steps = [...options.steps]\n assertValidSteps(options.adapterId, steps)\n\n return {\n adapterId: options.adapterId,\n latestVersion: steps.at(-1)?.version ?? 0,\n steps,\n }\n}\n\nasync function planMigrationSet<TContext>(\n params: PlanMigrationSetParams<TContext>\n): Promise<MigrationPlan<TContext>> {\n await params.state.ensure()\n\n const rows = await params.state.readHistory(params.migrations.adapterId)\n const applied = assertAppliedPrefix(params.migrations, rows)\n\n return {\n adapterId: params.migrations.adapterId,\n latestVersion: params.migrations.latestVersion,\n applied,\n pending: params.migrations.steps.slice(applied.length),\n }\n}\n\nexport async function runMigrationSet<TContext>(\n params: RunMigrationSetParams<TContext>\n): Promise<MigrationReport> {\n const now = params.now ?? (() => new Date().toISOString())\n const plan = await planMigrationSet(params)\n const applied: string[] = []\n\n for (const migration of plan.pending) {\n await params.state.transaction(async () => {\n await params.state.markStarted(plan.adapterId, migration, now())\n await migration.up(params.context)\n await params.state.markApplied(plan.adapterId, migration, now())\n })\n\n applied.push(migration.id)\n }\n\n return {\n adapterId: plan.adapterId,\n latestVersion: plan.latestVersion,\n status: applied.length > 0 ? \"migrated\" : \"current\",\n applied,\n skipped: plan.applied.map((migration) => migration.id),\n }\n}\n\nfunction parseMigrationId(id: string): { version: number; name: string } {\n const match = /^(\\d+)(?:[-_](.+))?$/.exec(id)\n\n if (!match) {\n throw new Error(`[Sixb] Migration id must start with a numeric prefix: ${id}`)\n }\n\n const version = Number(match[1])\n\n if (!Number.isInteger(version) || version < 1) {\n throw new Error(`[Sixb] Migration id must start with a positive version: ${id}`)\n }\n\n return {\n version,\n name: match[2] ?? id,\n }\n}\n\nfunction assertValidSteps<TContext>(\n adapterId: string,\n steps: readonly MigrationStep<TContext>[]\n): void {\n let previousVersion = 0\n\n for (const migration of steps) {\n if (migration.version <= previousVersion) {\n throw new Error(`[${adapterId}] Migrations must be ordered by ascending version.`)\n }\n\n previousVersion = migration.version\n }\n}\n\n/**\n * Classifies migration history without touching the database.\n *\n * The single source of truth for what a history means. `status()` reports the result\n * and `assertAppliedPrefix` throws on it, so the read-only probe and the migration\n * path can never disagree about whether a database is usable.\n *\n * `rows: null` means the history table itself is absent, which a probe must be able to\n * express without creating it.\n */\nexport function describeMigrationHistory<TContext>(params: {\n readonly migrations: MigrationSet<TContext>\n readonly rows: readonly MigrationRecord[] | null\n}): MigrationStatus {\n const { migrations, rows } = params\n const base = { adapterId: migrations.adapterId, latestVersion: migrations.latestVersion }\n\n // An adapter that declares no migrations and has recorded none is as current as it can\n // be. Reading that as `uninitialized` sent an operator to run `sixb db migrate`, which\n // would have applied nothing and reported the same state again. Only the empty history\n // qualifies: an adapter with no steps whose database recorded some is `ahead`, which\n // the walk below still finds.\n if (rows === null) {\n return migrations.steps.length === 0\n ? { ...base, appliedVersion: 0, state: \"current\" }\n : {\n ...base,\n appliedVersion: 0,\n state: \"uninitialized\",\n reason: \"No migration history exists. Run `sixb db migrate`.\",\n }\n }\n\n const applied = [...rows].sort((a, b) => a.version - b.version)\n const appliedVersion = applied.at(-1)?.version ?? 0\n const found = { ...base, appliedVersion }\n const seen = new Set<number>()\n\n for (const row of applied) {\n if (row.adapterId !== migrations.adapterId) {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Migration state belongs to a different adapter: ${row.adapterId}`,\n }\n }\n\n if (row.status === \"started\") {\n return {\n ...found,\n state: \"dirty\",\n reason: `Migration '${row.id}' started and never finished. Resolve it by hand before serving traffic.`,\n }\n }\n\n if (row.status !== \"applied\") {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Invalid migration status: ${row.status}`,\n }\n }\n\n if (seen.has(row.version)) {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Duplicate applied migration: ${row.version}`,\n }\n }\n\n seen.add(row.version)\n }\n\n for (const [index, row] of applied.entries()) {\n const migration = migrations.steps[index]\n\n if (!migration || row.version > migrations.latestVersion) {\n return {\n ...found,\n state: \"ahead\",\n reason:\n \"Database schema is newer than this Sixb version. Downgrades are not supported; \" +\n \"deploy a build that knows this schema.\",\n }\n }\n\n if (row.version !== migration.version || row.id !== migration.id) {\n return {\n ...found,\n state: \"incompatible\",\n reason: \"Applied migration history does not match declared migrations\",\n }\n }\n\n if ((row.checksum ?? null) !== (migration.checksum ?? null)) {\n return {\n ...found,\n state: \"incompatible\",\n reason: `Applied migration checksum changed: ${row.id}`,\n }\n }\n }\n\n if (applied.length === 0) {\n return migrations.steps.length === 0\n ? { ...found, state: \"current\" }\n : {\n ...found,\n state: \"uninitialized\",\n reason: \"Migration history is empty. Run `sixb db migrate`.\",\n }\n }\n\n const pendingCount = migrations.steps.length - applied.length\n if (pendingCount > 0) {\n return {\n ...found,\n state: \"pending\",\n reason: `${pendingCount} migration(s) are not applied. Run \\`sixb db migrate\\`.`,\n }\n }\n\n return { ...found, state: \"current\" }\n}\n\nfunction assertAppliedPrefix<TContext>(\n migrations: MigrationSet<TContext>,\n rows: readonly MigrationRecord[]\n): readonly MigrationRecord[] {\n const status = describeMigrationHistory({ migrations, rows })\n\n // `uninitialized` and `pending` are the normal inputs to a migration, not failures.\n if (\n status.state !== \"current\" &&\n status.state !== \"uninitialized\" &&\n status.state !== \"pending\"\n ) {\n throw new Error(`[${migrations.adapterId}] ${status.reason}`)\n }\n\n return [...rows].sort((a, b) => a.version - b.version)\n}\n",
|
|
66
|
+
"import type { SixbFailure } from \"../../errors/types\"\nimport type { OntologyObjectRef } from \"../../materialization/model\"\nimport type { MaterializationSession } from \"./materializations\"\n\nexport const VECTOR_INDEXING_FAILURE_CODES = [\n \"vector.model_unavailable\",\n \"vector.response_invalid\",\n \"vector.outcome_unknown\",\n \"internal.unexpected\",\n] as const\n\nexport type VectorIndexingFailureCode = (typeof VECTOR_INDEXING_FAILURE_CODES)[number]\n\n/** Latest desired representation; replacing its id fences every older delivery. */\nexport interface VectorIndexingRequest {\n readonly id: string\n /** Set only by projection materialization; a bounded, immediately durable group. */\n readonly batchId?: string\n readonly ref: OntologyObjectRef\n readonly profile: string\n readonly configuration: string\n readonly sourceFingerprint: string\n readonly sourceCommitId: string\n}\n\nexport interface VectorIndexingWork extends VectorIndexingRequest {\n readonly status: \"pending\" | \"running\" | \"ready\" | \"failed\"\n readonly availableAt: string\n readonly values?: readonly number[]\n readonly error?: SixbFailure<VectorIndexingFailureCode>\n}\n\nexport interface VectorIndexingUpdate {\n readonly id: string\n readonly expectedStatus: VectorIndexingWork[\"status\"]\n readonly status: VectorIndexingWork[\"status\"]\n readonly availableAt: string\n readonly values?: readonly number[]\n readonly error?: SixbFailure<VectorIndexingFailureCode>\n}\n\n/** Durable intent belongs to ontology storage; delivery leases belong to Queues. */\nexport interface OntologyVectorIndexingStorage {\n /** Called inside the transaction that changes the effective object. */\n schedule(input: {\n projectId: string\n session: MaterializationSession\n requests: readonly VectorIndexingRequest[]\n deleted: readonly OntologyObjectRef[]\n availableAt: string\n }): Promise<void>\n /** Clear matching intent atomically with a successful automatic or explicit vector write. */\n complete(input: {\n projectId: string\n session: MaterializationSession\n entries: readonly Pick<\n VectorIndexingRequest,\n \"ref\" | \"profile\" | \"configuration\" | \"sourceFingerprint\"\n >[]\n }): Promise<void>\n dispatched(input: {\n projectId: string\n ids: readonly string[]\n nextDispatchAt: string\n }): Promise<void>\n get(input: { projectId: string; id: string }): Promise<VectorIndexingWork | null>\n getBatch(input: { projectId: string; batchId: string }): Promise<readonly VectorIndexingWork[]>\n /** Read only the result this kernel batch is allowed to publish. */\n getBatchMember(input: {\n projectId: string\n batchId: string\n ref: OntologyObjectRef\n profile: string\n }): Promise<VectorIndexingWork | null>\n /** Atomic transitions; requireAll prevents admission if any prepared member was superseded. */\n updateBatch(input: {\n projectId: string\n updates: readonly VectorIndexingUpdate[]\n requireAll?: boolean\n }): Promise<boolean>\n /** Bounded fair redispatch scan. Never scans objects or backfills existing data. */\n listDue(input: {\n projectId: string\n now: string\n limit: number\n }): Promise<readonly VectorIndexingWork[]>\n /** CAS also fences concurrent deliveries and source changes. */\n update(input: {\n projectId: string\n id: string\n expectedStatus: VectorIndexingWork[\"status\"]\n status: VectorIndexingWork[\"status\"]\n availableAt: string\n values?: readonly number[]\n error?: SixbFailure<VectorIndexingFailureCode>\n }): Promise<boolean>\n remove(input: { projectId: string; id: string }): Promise<void>\n}\n"
|
|
67
|
+
],
|
|
68
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,cAAgC,OAAU,QAA0C,IAAI;AAE9F,SAAS,YAAY,CAAC,WAAmB,IAAoB;AAAA,EAC3D,OAAO,KAAK,UAAU,CAAC,WAAW,EAAE,CAAC;AAAA;AAGvC,SAAS,oBAAoB,CAAC,QAA0C;AAAA,EACtE,OAAO,gBAAgB,MAAM;AAAA;AAG/B,SAAS,WAAW,CAAC,GAAoB,GAAoB,OAA+B;AAAA,EAC1F,MAAM,QAAQ,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ;AAAA,EAC1D,IAAI,UAAU,GAAG;AAAA,IACf,OAAO,UAAU,QAAQ,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,IAAI,EAAE,OAAO,EAAE,IAAI;AAAA,IACjB,OAAO;AAAA,EACT;AAAA,EAEA,OAAO,UAAU,QAAQ,EAAE,GAAG,cAAc,EAAE,EAAE,IAAI,EAAE,GAAG,cAAc,EAAE,EAAE;AAAA;AAAA;AAGtE,MAAM,0BAAqD;AAAA,EAK7C;AAAA,EAJ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