@sixb/core 0.2.1 → 0.2.2

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.
Files changed (264) hide show
  1. package/dist/actions/index.js +29 -29
  2. package/dist/agents/cancel.d.ts.map +1 -1
  3. package/dist/agents/index.d.ts +5 -3
  4. package/dist/agents/index.d.ts.map +1 -1
  5. package/dist/agents/index.js +38 -32
  6. package/dist/agents/index.js.map +1 -1
  7. package/dist/agents/run-plan.d.ts +15 -1
  8. package/dist/agents/run-plan.d.ts.map +1 -1
  9. package/dist/agents/run-session-http.d.ts.map +1 -1
  10. package/dist/agents/run-session-serve.d.ts.map +1 -1
  11. package/dist/agents/run-session.d.ts +14 -2
  12. package/dist/agents/run-session.d.ts.map +1 -1
  13. package/dist/agents/skills.d.ts +3 -0
  14. package/dist/agents/skills.d.ts.map +1 -1
  15. package/dist/agents/step-limits.d.ts +6 -0
  16. package/dist/agents/step-limits.d.ts.map +1 -1
  17. package/dist/agents/streams/index.js +1 -1
  18. package/dist/agents/streams/internal.js +1 -1
  19. package/dist/agents/streams/protocol.d.ts +8 -2
  20. package/dist/agents/streams/protocol.d.ts.map +1 -1
  21. package/dist/agents/tool-files.d.ts +3 -1
  22. package/dist/agents/tool-files.d.ts.map +1 -1
  23. package/dist/agents/validation.d.ts +1 -1
  24. package/dist/agents/validation.d.ts.map +1 -1
  25. package/dist/agents/web.d.ts +47 -0
  26. package/dist/agents/web.d.ts.map +1 -0
  27. package/dist/artifacts/publish/index.js +16 -16
  28. package/dist/auth/index.js +3 -3
  29. package/dist/authorization/index.js +2 -2
  30. package/dist/authorization/resolve.d.ts +4 -3
  31. package/dist/authorization/resolve.d.ts.map +1 -1
  32. package/dist/authorization/types.d.ts +5 -5
  33. package/dist/authorization/types.d.ts.map +1 -1
  34. package/dist/bootstrap/index.js +34 -34
  35. package/dist/{chunk-neftrg0n.js → chunk-0j3crh1w.js} +2 -2
  36. package/dist/{chunk-tvbmh7tj.js → chunk-2ajw5rz0.js} +14 -10
  37. package/dist/chunk-2ajw5rz0.js.map +18 -0
  38. package/dist/{chunk-23s66j86.js → chunk-31kcqmhf.js} +1 -1
  39. package/dist/{chunk-nghc7eq0.js → chunk-3723kgba.js} +1 -1
  40. package/dist/{chunk-rjeeyssy.js → chunk-3sqqhpr7.js} +4 -4
  41. package/dist/{chunk-m3qe54bb.js → chunk-4bm0caep.js} +1 -1
  42. package/dist/{chunk-h05rg3bx.js → chunk-4s753g3k.js} +3 -3
  43. package/dist/{chunk-8wsjr52f.js → chunk-5wtnmpze.js} +1 -1
  44. package/dist/{chunk-edx8xcsm.js → chunk-7z5rkf0m.js} +29 -6
  45. package/dist/chunk-7z5rkf0m.js.map +13 -0
  46. package/dist/{chunk-2pk5hjj9.js → chunk-80gym75n.js} +1 -1
  47. package/dist/{chunk-qbrmpgvv.js → chunk-9whfmsfk.js} +1 -1
  48. package/dist/{chunk-z3evap21.js → chunk-a5v4gjdx.js} +27 -26
  49. package/dist/{chunk-z3evap21.js.map → chunk-a5v4gjdx.js.map} +3 -3
  50. package/dist/{chunk-w53trr0c.js → chunk-a7aa0nzj.js} +5 -5
  51. package/dist/{chunk-tvefbgvw.js → chunk-az95tsh3.js} +4 -2
  52. package/dist/chunk-az95tsh3.js.map +11 -0
  53. package/dist/{chunk-7hd2ez3q.js → chunk-c4nrycdy.js} +1 -1
  54. package/dist/{chunk-epyfm23v.js → chunk-c706qvyc.js} +3 -3
  55. package/dist/{chunk-t5daew4g.js → chunk-c7cfe31p.js} +6 -6
  56. package/dist/{chunk-qsg8rw04.js → chunk-d04g36fw.js} +1 -1
  57. package/dist/{chunk-ratj7t3t.js → chunk-dsv783c3.js} +305 -32
  58. package/dist/{chunk-ratj7t3t.js.map → chunk-dsv783c3.js.map} +12 -10
  59. package/dist/{chunk-cb21tx14.js → chunk-eqgr6nsa.js} +81 -25
  60. package/dist/{chunk-cb21tx14.js.map → chunk-eqgr6nsa.js.map} +8 -7
  61. package/dist/{chunk-ax10ft8d.js → chunk-f1h34y3r.js} +5 -5
  62. package/dist/{chunk-9rh8ncs5.js → chunk-fwsvshr5.js} +1 -1
  63. package/dist/{chunk-b7a97n8b.js → chunk-ga63a3dz.js} +6 -6
  64. package/dist/{chunk-b7a97n8b.js.map → chunk-ga63a3dz.js.map} +2 -2
  65. package/dist/{chunk-cgznz22f.js → chunk-gkv8r794.js} +2 -2
  66. package/dist/{chunk-t9xyr7y9.js → chunk-j8thxj7w.js} +3 -3
  67. package/dist/{chunk-31khg3g0.js → chunk-kkjfve0t.js} +73 -2
  68. package/dist/{chunk-31khg3g0.js.map → chunk-kkjfve0t.js.map} +3 -3
  69. package/dist/{chunk-8yzhjawq.js → chunk-m2vh8gh0.js} +8 -14
  70. package/dist/{chunk-8yzhjawq.js.map → chunk-m2vh8gh0.js.map} +3 -3
  71. package/dist/{chunk-nqnfz3jg.js → chunk-mbc5hvnj.js} +2 -2
  72. package/dist/{chunk-jk97v21j.js → chunk-n4zzaf6q.js} +3 -2
  73. package/dist/chunk-n4zzaf6q.js.map +10 -0
  74. package/dist/{chunk-y2x2935j.js → chunk-nh26e7c5.js} +2 -2
  75. package/dist/{chunk-jhbk10wf.js → chunk-q9nkpr8k.js} +1 -1
  76. package/dist/{chunk-47e09r7z.js → chunk-qttqe1ah.js} +86 -6
  77. package/dist/{chunk-47e09r7z.js.map → chunk-qttqe1ah.js.map} +5 -4
  78. package/dist/{chunk-3x3bebz7.js → chunk-s7j8ewqv.js} +161 -62
  79. package/dist/{chunk-3x3bebz7.js.map → chunk-s7j8ewqv.js.map} +7 -6
  80. package/dist/{chunk-dz7a4t3a.js → chunk-twfreyxr.js} +5 -10
  81. package/dist/{chunk-dz7a4t3a.js.map → chunk-twfreyxr.js.map} +4 -4
  82. package/dist/{chunk-ks87m383.js → chunk-w1btn96n.js} +49 -24
  83. package/dist/{chunk-ks87m383.js.map → chunk-w1btn96n.js.map} +6 -6
  84. package/dist/{chunk-fg1db9xx.js → chunk-wkq3kvzd.js} +5 -5
  85. package/dist/chunk-wkq3kvzd.js.map +10 -0
  86. package/dist/{chunk-aqyjb86c.js → chunk-wrjx1fqz.js} +6 -6
  87. package/dist/{chunk-agn8d8ys.js → chunk-xtztwpkh.js} +1 -1
  88. package/dist/{chunk-0g5nyx0k.js → chunk-zeykm8my.js} +2 -2
  89. package/dist/connectors/connections/runs.d.ts +7 -0
  90. package/dist/connectors/connections/runs.d.ts.map +1 -1
  91. package/dist/execution/agent.js +29 -29
  92. package/dist/execution/object-reader-security.d.ts.map +1 -1
  93. package/dist/execution/primitive.js +29 -29
  94. package/dist/execution/request.js +30 -30
  95. package/dist/index.d.ts +2 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +37 -37
  98. package/dist/materializer/index.js +15 -15
  99. package/dist/models/catalog.d.ts +16 -0
  100. package/dist/models/catalog.d.ts.map +1 -1
  101. package/dist/models/definitions.d.ts +1 -1
  102. package/dist/models/definitions.d.ts.map +1 -1
  103. package/dist/models/execution/index.js +17 -17
  104. package/dist/models/execution/model-call-recorder.d.ts +1 -1
  105. package/dist/models/execution/model-call-recorder.d.ts.map +1 -1
  106. package/dist/models/execution/web-search.d.ts +7 -0
  107. package/dist/models/execution/web-search.d.ts.map +1 -0
  108. package/dist/models/index.d.ts +3 -1
  109. package/dist/models/index.d.ts.map +1 -1
  110. package/dist/models/index.js +5 -3
  111. package/dist/models/index.js.map +1 -1
  112. package/dist/models/language-model.d.ts +12 -0
  113. package/dist/models/language-model.d.ts.map +1 -1
  114. package/dist/models/web-search-model.d.ts +66 -0
  115. package/dist/models/web-search-model.d.ts.map +1 -0
  116. package/dist/objects/index.js +29 -29
  117. package/dist/objects/query/executor.d.ts.map +1 -1
  118. package/dist/objects/query/index.d.ts +1 -0
  119. package/dist/objects/query/index.d.ts.map +1 -1
  120. package/dist/objects/query/index.js +18 -15
  121. package/dist/objects/query/index.js.map +1 -1
  122. package/dist/objects/query/sort-ties.d.ts +11 -0
  123. package/dist/objects/query/sort-ties.d.ts.map +1 -0
  124. package/dist/pipelines/index.js +15 -15
  125. package/dist/projections/internal.js +15 -15
  126. package/dist/runtime/create.d.ts +1 -1
  127. package/dist/runtime/create.d.ts.map +1 -1
  128. package/dist/runtime/internal.js +21 -21
  129. package/dist/runtime/resolve-definitions.d.ts.map +1 -1
  130. package/dist/security/index.d.ts +1 -0
  131. package/dist/security/index.d.ts.map +1 -1
  132. package/dist/security/registry.d.ts +2 -0
  133. package/dist/security/registry.d.ts.map +1 -1
  134. package/dist/security/view-conditions.d.ts.map +1 -1
  135. package/dist/security/visibility-keys.d.ts +19 -0
  136. package/dist/security/visibility-keys.d.ts.map +1 -0
  137. package/dist/shares/internal.js +15 -15
  138. package/dist/storage/agents/in-memory.d.ts +8 -2
  139. package/dist/storage/agents/in-memory.d.ts.map +1 -1
  140. package/dist/storage/agents/index.d.ts +1 -1
  141. package/dist/storage/agents/index.d.ts.map +1 -1
  142. package/dist/storage/agents/provider.d.ts +8 -2
  143. package/dist/storage/agents/provider.d.ts.map +1 -1
  144. package/dist/storage/agents/provider.js +12 -6
  145. package/dist/storage/agents/provider.js.map +1 -1
  146. package/dist/storage/agents/types.d.ts +42 -2
  147. package/dist/storage/agents/types.d.ts.map +1 -1
  148. package/dist/storage/ai-cost/provider.js +4 -4
  149. package/dist/storage/ai-limits/enforcement.js +3 -3
  150. package/dist/storage/ai-limits/provider.js +2 -2
  151. package/dist/storage/connector-connections/provider.js +3 -3
  152. package/dist/storage/connector-connections/provider.js.map +3 -3
  153. package/dist/storage/file-upload-sessions/provider.js +4 -4
  154. package/dist/storage/index.d.ts +2 -2
  155. package/dist/storage/index.d.ts.map +1 -1
  156. package/dist/storage/index.js +14 -14
  157. package/dist/storage/internal.js +2 -2
  158. package/dist/storage/migrations/types.d.ts +6 -0
  159. package/dist/storage/migrations/types.d.ts.map +1 -1
  160. package/dist/storage/objects/in-memory/query.d.ts.map +1 -1
  161. package/dist/storage/objects/index.d.ts +1 -1
  162. package/dist/storage/objects/index.d.ts.map +1 -1
  163. package/dist/storage/objects/query-preparation.d.ts +13 -0
  164. package/dist/storage/objects/query-preparation.d.ts.map +1 -1
  165. package/dist/storage/objects/read-scope.d.ts.map +1 -1
  166. package/dist/storage/objects/types.d.ts +52 -0
  167. package/dist/storage/objects/types.d.ts.map +1 -1
  168. package/dist/storage/share-grants/provider.js +2 -2
  169. package/dist/storage/workflow-runs/provider.js +4 -4
  170. package/dist/syncs/index.js +17 -17
  171. package/dist/testing/agent-storage-contract.d.ts.map +1 -1
  172. package/dist/testing/ai-limit-storage-contract.d.ts.map +1 -1
  173. package/dist/testing/ai-usage-storage-contract.d.ts.map +1 -1
  174. package/dist/testing/connector-connection-storage-contract.d.ts.map +1 -1
  175. package/dist/testing/index.js +399 -45
  176. package/dist/testing/index.js.map +8 -8
  177. package/dist/testing/object-conditional-read-scope-contract.d.ts.map +1 -1
  178. package/dist/testing/object-query-contract.d.ts.map +1 -1
  179. package/dist/webhooks/internal.js +15 -15
  180. package/dist/workflows/index.js +31 -31
  181. package/package.json +1 -1
  182. package/src/agents/README.md +2 -1
  183. package/src/agents/cancel.ts +7 -1
  184. package/src/agents/index.ts +9 -1
  185. package/src/agents/run-plan.ts +31 -0
  186. package/src/agents/run-session-http.ts +15 -12
  187. package/src/agents/run-session-serve.ts +8 -2
  188. package/src/agents/run-session.ts +31 -11
  189. package/src/agents/skills.ts +3 -0
  190. package/src/agents/step-limits.ts +6 -0
  191. package/src/agents/streams/protocol.ts +9 -4
  192. package/src/agents/tool-files.ts +11 -3
  193. package/src/agents/validation.ts +9 -0
  194. package/src/agents/web.ts +218 -0
  195. package/src/authorization/resolve.ts +9 -11
  196. package/src/authorization/types.ts +5 -5
  197. package/src/connectors/connections/runs.ts +42 -5
  198. package/src/execution/object-reader-security.ts +4 -9
  199. package/src/index.ts +2 -0
  200. package/src/models/catalog.ts +52 -3
  201. package/src/models/definitions.ts +2 -0
  202. package/src/models/execution/README.md +22 -2
  203. package/src/models/execution/model-call-recorder.ts +1 -1
  204. package/src/models/execution/web-search.ts +186 -0
  205. package/src/models/index.ts +12 -0
  206. package/src/models/language-model.ts +12 -0
  207. package/src/models/web-search-model.ts +152 -0
  208. package/src/objects/query/executor.ts +7 -3
  209. package/src/objects/query/index.ts +1 -0
  210. package/src/objects/query/sort-ties.ts +16 -0
  211. package/src/runtime/create.ts +3 -2
  212. package/src/runtime/resolve-definitions.ts +4 -0
  213. package/src/security/index.ts +1 -0
  214. package/src/security/registry.ts +2 -0
  215. package/src/security/view-conditions.ts +4 -3
  216. package/src/security/visibility-keys.ts +144 -0
  217. package/src/storage/agents/in-memory.ts +29 -2
  218. package/src/storage/agents/index.ts +2 -0
  219. package/src/storage/agents/provider.ts +57 -1
  220. package/src/storage/agents/types.ts +45 -2
  221. package/src/storage/connector-connections/in-memory.ts +2 -2
  222. package/src/storage/connector-connections/provider/connections.ts +2 -2
  223. package/src/storage/index.ts +4 -0
  224. package/src/storage/migrations/types.ts +6 -0
  225. package/src/storage/objects/in-memory/query.ts +5 -2
  226. package/src/storage/objects/index.ts +2 -0
  227. package/src/storage/objects/query-preparation.ts +59 -1
  228. package/src/storage/objects/read-scope.ts +108 -2
  229. package/src/storage/objects/types.ts +43 -0
  230. package/src/testing/agent-storage-contract.ts +70 -0
  231. package/src/testing/ai-limit-storage-contract.ts +11 -1
  232. package/src/testing/ai-usage-storage-contract.ts +15 -2
  233. package/src/testing/connector-connection-storage-contract.ts +23 -0
  234. package/src/testing/object-conditional-read-scope-contract.ts +267 -5
  235. package/src/testing/object-query-contract.ts +75 -0
  236. package/dist/chunk-edx8xcsm.js.map +0 -13
  237. package/dist/chunk-fg1db9xx.js.map +0 -10
  238. package/dist/chunk-jk97v21j.js.map +0 -10
  239. package/dist/chunk-tvbmh7tj.js.map +0 -18
  240. package/dist/chunk-tvefbgvw.js.map +0 -11
  241. /package/dist/{chunk-neftrg0n.js.map → chunk-0j3crh1w.js.map} +0 -0
  242. /package/dist/{chunk-23s66j86.js.map → chunk-31kcqmhf.js.map} +0 -0
  243. /package/dist/{chunk-nghc7eq0.js.map → chunk-3723kgba.js.map} +0 -0
  244. /package/dist/{chunk-rjeeyssy.js.map → chunk-3sqqhpr7.js.map} +0 -0
  245. /package/dist/{chunk-m3qe54bb.js.map → chunk-4bm0caep.js.map} +0 -0
  246. /package/dist/{chunk-h05rg3bx.js.map → chunk-4s753g3k.js.map} +0 -0
  247. /package/dist/{chunk-8wsjr52f.js.map → chunk-5wtnmpze.js.map} +0 -0
  248. /package/dist/{chunk-2pk5hjj9.js.map → chunk-80gym75n.js.map} +0 -0
  249. /package/dist/{chunk-qbrmpgvv.js.map → chunk-9whfmsfk.js.map} +0 -0
  250. /package/dist/{chunk-w53trr0c.js.map → chunk-a7aa0nzj.js.map} +0 -0
  251. /package/dist/{chunk-7hd2ez3q.js.map → chunk-c4nrycdy.js.map} +0 -0
  252. /package/dist/{chunk-epyfm23v.js.map → chunk-c706qvyc.js.map} +0 -0
  253. /package/dist/{chunk-t5daew4g.js.map → chunk-c7cfe31p.js.map} +0 -0
  254. /package/dist/{chunk-qsg8rw04.js.map → chunk-d04g36fw.js.map} +0 -0
  255. /package/dist/{chunk-ax10ft8d.js.map → chunk-f1h34y3r.js.map} +0 -0
  256. /package/dist/{chunk-9rh8ncs5.js.map → chunk-fwsvshr5.js.map} +0 -0
  257. /package/dist/{chunk-cgznz22f.js.map → chunk-gkv8r794.js.map} +0 -0
  258. /package/dist/{chunk-t9xyr7y9.js.map → chunk-j8thxj7w.js.map} +0 -0
  259. /package/dist/{chunk-nqnfz3jg.js.map → chunk-mbc5hvnj.js.map} +0 -0
  260. /package/dist/{chunk-y2x2935j.js.map → chunk-nh26e7c5.js.map} +0 -0
  261. /package/dist/{chunk-jhbk10wf.js.map → chunk-q9nkpr8k.js.map} +0 -0
  262. /package/dist/{chunk-aqyjb86c.js.map → chunk-wrjx1fqz.js.map} +0 -0
  263. /package/dist/{chunk-agn8d8ys.js.map → chunk-xtztwpkh.js.map} +0 -0
  264. /package/dist/{chunk-0g5nyx0k.js.map → chunk-zeykm8my.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { compareStrings, getInvalidJsonValueReason } from "../../json"
2
2
  import type { ObjectQueryPredicate, QueryScalarKind } from "../../objects/query"
3
- import { isCurrentUser } from "../../ontology/user-ref"
3
+ import { isCurrentUser, type UserRef } from "../../ontology/user-ref"
4
4
  import type {
5
5
  CompiledConditionalObjectReadScope,
6
6
  CompiledObjectReadObjectSelection,
@@ -14,6 +14,8 @@ import type {
14
14
  ObjectReadNode,
15
15
  ObjectReadObjectSelection,
16
16
  ObjectReadRoot,
17
+ ObjectReadVisibility,
18
+ ObjectVisibilityKeys,
17
19
  SelectedObjectReadScope,
18
20
  } from "./types"
19
21
 
@@ -560,7 +562,13 @@ export function compileConditionalObjectReadScope(
560
562
  objectTypeIds.add(objectTypeId)
561
563
 
562
564
  const predicate = capturePredicate(condition.predicate, `${path}.predicate`, 0, budget)
563
- conditions.push(Object.freeze({ objectTypeId, predicate }))
565
+ const visibility =
566
+ condition.visibility === undefined
567
+ ? undefined
568
+ : captureVisibility(condition.visibility, `${path}.visibility`, budget)
569
+ conditions.push(
570
+ Object.freeze({ objectTypeId, predicate, ...(visibility ? { visibility } : {}) })
571
+ )
564
572
  }
565
573
 
566
574
  conditions.sort((left, right) => compareStrings(left.objectTypeId, right.objectTypeId))
@@ -571,6 +579,104 @@ export function compileConditionalObjectReadScope(
571
579
  }) as CompiledConditionalObjectReadScope
572
580
  }
573
581
 
582
+ /** The reader's keys, user and remainder: shaped as providers read them, every predicate bound. */
583
+ function captureVisibility(
584
+ value: unknown,
585
+ path: string,
586
+ budget: { nodes: number }
587
+ ): ObjectReadVisibility {
588
+ if (!isRecord(value)) throw invalidScope(`${path} must hold keys`)
589
+
590
+ const source = captureArray(value.keys, `${path}.keys`)
591
+ if (source.length === 0) throw invalidScope(`${path}.keys must not be empty`)
592
+
593
+ const keys: ObjectVisibilityKeys[] = []
594
+ for (let index = 0; index < source.length; index += 1) {
595
+ keys.push(captureKeys(source.value[index], `${path}.keys[${index}]`, 0, budget))
596
+ }
597
+
598
+ let user: UserRef | undefined
599
+ if (value.user !== undefined) {
600
+ const ref = value.user
601
+ if (!isRecord(ref) || ref.type !== "user" || Object.keys(ref).length !== 2) {
602
+ throw invalidScope(`${path}.user must be a user reference`)
603
+ }
604
+ if (typeof ref.id !== "string" || ref.id.length === 0) {
605
+ throw invalidScope(`${path}.user.id must be a non-empty string`)
606
+ }
607
+ user = Object.freeze({ type: "user", id: ref.id })
608
+ }
609
+
610
+ const remainder =
611
+ value.remainder === undefined
612
+ ? undefined
613
+ : capturePredicate(value.remainder, `${path}.remainder`, 0, budget)
614
+
615
+ return Object.freeze({
616
+ keys: Object.freeze(keys),
617
+ ...(user ? { user } : {}),
618
+ ...(remainder ? { remainder } : {}),
619
+ })
620
+ }
621
+
622
+ function captureKeys(
623
+ value: unknown,
624
+ path: string,
625
+ depth: number,
626
+ budget: { nodes: number }
627
+ ): ObjectVisibilityKeys {
628
+ if (depth > CONDITIONAL_READ_SCOPE_LIMITS.maxPredicateDepth) {
629
+ throw invalidScope(
630
+ `${path} exceeds the maximum predicate depth of ${CONDITIONAL_READ_SCOPE_LIMITS.maxPredicateDepth}`
631
+ )
632
+ }
633
+
634
+ budget.nodes += 1
635
+ if (budget.nodes > CONDITIONAL_READ_SCOPE_LIMITS.maxPredicateNodes) {
636
+ throw invalidScope(
637
+ `scope exceeds the maximum of ${CONDITIONAL_READ_SCOPE_LIMITS.maxPredicateNodes} predicate nodes`
638
+ )
639
+ }
640
+
641
+ if (!isRecord(value)) throw invalidScope(`${path} must be visibility keys`)
642
+
643
+ switch (value.kind) {
644
+ case "everyone":
645
+ return Object.freeze({
646
+ kind: "everyone",
647
+ when: capturePredicate(value.when, `${path}.when`, depth + 1, budget),
648
+ })
649
+
650
+ case "user":
651
+ case "users":
652
+ return Object.freeze({
653
+ kind: value.kind,
654
+ propertyId: nonEmptyString(value.propertyId, `${path}.propertyId`),
655
+ })
656
+
657
+ case "union": {
658
+ const items = captureArray(value.items, `${path}.items`)
659
+ if (items.length === 0) throw invalidScope(`${path}.items must not be empty`)
660
+
661
+ const captured: ObjectVisibilityKeys[] = []
662
+ for (let index = 0; index < items.length; index += 1) {
663
+ captured.push(captureKeys(items.value[index], `${path}.items[${index}]`, depth + 1, budget))
664
+ }
665
+ return Object.freeze({ kind: "union", items: Object.freeze(captured) })
666
+ }
667
+
668
+ case "when":
669
+ return Object.freeze({
670
+ kind: "when",
671
+ when: capturePredicate(value.when, `${path}.when`, depth + 1, budget),
672
+ keys: captureKeys(value.keys, `${path}.keys`, depth + 1, budget),
673
+ })
674
+
675
+ default:
676
+ throw invalidScope(`${path}.kind must be a kind of visibility keys`)
677
+ }
678
+ }
679
+
574
680
  function capturePredicate(
575
681
  value: unknown,
576
682
  path: string,
@@ -6,6 +6,7 @@ import type {
6
6
  ObjectQuerySortField,
7
7
  QueryScalarKind,
8
8
  } from "../../objects/query"
9
+ import type { UserRef } from "../../ontology/user-ref"
9
10
  import type { Redactions } from "../../security/types"
10
11
  import type { UserProfile } from "../../users"
11
12
  import type { UniqueValueRef } from "../ontology/materializations"
@@ -203,8 +204,50 @@ export interface ObjectReadCondition {
203
204
  * bound to the reader. Providers compile it with their own predicate compiler.
204
205
  */
205
206
  readonly predicate: ObjectQueryPredicate
207
+ /**
208
+ * The same condition read from visibility keys, for a provider that indexes them. Absent when
209
+ * none of the reader's conditions on the type has keys.
210
+ */
211
+ readonly visibility?: ObjectReadVisibility
212
+ }
213
+
214
+ /**
215
+ * `predicate` read from keys: it matches an object exactly when one of `keys` shows it to everyone
216
+ * or to `user`, or when `remainder` matches it.
217
+ */
218
+ export interface ObjectReadVisibility {
219
+ /** One per condition of the reader's roles that has keys, the same for every reader. */
220
+ readonly keys: readonly ObjectVisibilityKeys[]
221
+ /** The user reading; without one, an object is only shown by keys for everyone. */
222
+ readonly user?: UserRef
223
+ /** The reader's other conditions, bound to its user: an object either matches is shown. */
224
+ readonly remainder?: ObjectQueryPredicate
206
225
  }
207
226
 
227
+ /**
228
+ * Who a view condition shows an object to, read from the object alone: everyone holding the
229
+ * condition, or the users some of its properties name.
230
+ *
231
+ * `currentUser()` only appears where a condition compares user references, so a condition has
232
+ * keys unless it negates such a comparison, or needs two of them to hold at once. Unlike the
233
+ * condition bound to a reader, keys are the same for every reader, so a provider can index them
234
+ * once per condition. A reader sees an object when its keys show it to everyone or to the reader.
235
+ */
236
+ export type ObjectVisibilityKeys =
237
+ /** Everyone, when `when` matches. `when` never reads `currentUser()`. */
238
+ | { readonly kind: "everyone"; readonly when: ObjectQueryPredicate }
239
+ /** The user a `ref.user()` property holds, as `eq(property, currentUser())` compares it. */
240
+ | { readonly kind: "user"; readonly propertyId: string }
241
+ /** Each user a list holds, as `contains(property, currentUser())` compares them. */
242
+ | { readonly kind: "users"; readonly propertyId: string }
243
+ | { readonly kind: "union"; readonly items: readonly ObjectVisibilityKeys[] }
244
+ /** `keys`, when `when` matches. `when` never reads `currentUser()`. */
245
+ | {
246
+ readonly kind: "when"
247
+ readonly when: ObjectQueryPredicate
248
+ readonly keys: ObjectVisibilityKeys
249
+ }
250
+
208
251
  /**
209
252
  * Detached and deeply immutable conditions, one per concrete type, ordered by type id.
210
253
  *
@@ -1159,6 +1159,76 @@ export function runAgentStorageContractSuite<TStorage extends AgentStorageContra
1159
1159
  })
1160
1160
  })
1161
1161
 
1162
+ // Removal proofs: have a renewal write no stop requests (those asked are lost); drop the check
1163
+ // that a request is not kept yet (a second click lists it twice).
1164
+ test("keeps what an open sixb reports of its background commands, and the stops asked", async () => {
1165
+ await withStorage(async (storage) => {
1166
+ const live = at("2026-06-23T12:01:00.000Z")
1167
+ const session = (overrides: Partial<AgentComputerSessionRecord> = {}) => ({
1168
+ projectId,
1169
+ id: "s_1",
1170
+ ownerPrincipal: owner,
1171
+ computer: laptop,
1172
+ expiresAt: live,
1173
+ ...overrides,
1174
+ })
1175
+ const running = {
1176
+ threadId: "thr_1",
1177
+ id: "bg_1",
1178
+ command: "bun dev",
1179
+ status: "running" as const,
1180
+ startedAt: "2026-06-23T11:59:00.000Z",
1181
+ }
1182
+ const ref = { threadId: "thr_1", id: "bg_1", startedAt: running.startedAt }
1183
+ const stop = (command = ref, ownerPrincipal: Principal = owner) =>
1184
+ storage.computers.requestStop({ projectId, id: "s_1", ownerPrincipal, command })
1185
+
1186
+ await storage.computers.hold(session({ backgroundCommands: [running] }))
1187
+ await expect(stop()).resolves.toEqual(
1188
+ session({ backgroundCommands: [running], stopRequests: [ref] })
1189
+ )
1190
+ await expect(stop()).resolves.toEqual(
1191
+ session({ backgroundCommands: [running], stopRequests: [ref] })
1192
+ )
1193
+ await expect(stop(ref, otherUser)).resolves.toBeNull()
1194
+
1195
+ // A renewal reports the commands anew, and keeps what was asked of them.
1196
+ const stopped = {
1197
+ ...running,
1198
+ status: "stopped" as const,
1199
+ exitCode: 143,
1200
+ endedAt: "2026-06-23T12:00:30.000Z",
1201
+ }
1202
+ await storage.computers.hold(session({ backgroundCommands: [stopped] }))
1203
+ await expect(
1204
+ storage.computers.listLive({
1205
+ projectId,
1206
+ ownerPrincipal: owner,
1207
+ now: at(running.startedAt),
1208
+ })
1209
+ ).resolves.toEqual([session({ backgroundCommands: [stopped], stopRequests: [ref] })])
1210
+
1211
+ // The newest requests are kept.
1212
+ for (let index = 2; index <= 65; index += 1) await stop({ ...ref, id: `bg_${index}` })
1213
+ const [kept] = await storage.computers.listLive({
1214
+ projectId,
1215
+ ownerPrincipal: owner,
1216
+ now: at(running.startedAt),
1217
+ })
1218
+ expect(kept?.stopRequests?.length).toBe(64)
1219
+ expect(kept?.stopRequests?.[0]?.id).toBe("bg_2")
1220
+ expect(kept?.stopRequests?.at(-1)?.id).toBe("bg_65")
1221
+
1222
+ await expectAgentError(stop({ ...ref, id: "" }), "invalid_input")
1223
+ await expectAgentError(
1224
+ storage.computers.hold(
1225
+ session({ backgroundCommands: [{ ...running, status: "lost" as "running" }] })
1226
+ ),
1227
+ "invalid_input"
1228
+ )
1229
+ })
1230
+ })
1231
+
1162
1232
  test("reads several threads at once, in the order asked", async () => {
1163
1233
  await withStorage(async (storage) => {
1164
1234
  const first = await storage.threads.create(threadInput())
@@ -570,7 +570,7 @@ export function runAiLimitStorageContractSuite<TStorage extends AiLimitStorageCo
570
570
  meter: "cost.catalogEstimated",
571
571
  amount: { currency: "USD", amountNanos: "100" },
572
572
  }
573
- for (const modelKind of ["reranking", "image", "speech"] as const) {
573
+ for (const modelKind of ["reranking", "web-search", "image", "speech"] as const) {
574
574
  await expect(
575
575
  storage.aiLimits.reserveModelCall(
576
576
  reservation(modelKind, 0, { estimates: [cost], modelKind })
@@ -591,6 +591,16 @@ export function runAiLimitStorageContractSuite<TStorage extends AiLimitStorageCo
591
591
  projectId,
592
592
  usageRecordId: "usage-reranking",
593
593
  })
594
+ await recordUsageInput(storage.aiUsage, {
595
+ id: "usage-web-search",
596
+ callId: "web-search",
597
+ modelKind: "web-search",
598
+ usage: {},
599
+ })
600
+ await storage.aiLimits.recordModelCallActuals({
601
+ projectId,
602
+ usageRecordId: "usage-web-search",
603
+ })
594
604
  expect(await status()).toMatchObject({
595
605
  accountingStatus: "complete",
596
606
  consumption: { actual: { amount: 4 } },
@@ -71,8 +71,9 @@ export function runAiUsageStorageContractSuite<TStorage extends AiUsageStorage>(
71
71
 
72
72
  describe(label, () => {
73
73
  // Removal proof: omit audioDurationMs from a row codec; this round trip fails.
74
- // Removal proof: omit 'reranking' from a storage migration's model_kind check; the write fails.
75
- test("persists transcription and reranking usage kinds without invented token totals", async () => {
74
+ // Removal proof: omit 'reranking' or 'web-search' from a storage migration's model_kind check;
75
+ // the write fails.
76
+ test("persists transcription, reranking and web search usage kinds without invented token totals", async () => {
76
77
  await withStorage(async (storage) => {
77
78
  const latest = () =>
78
79
  storage.getLatestForExecution({ projectId, executionId: agentExecutionId })
@@ -102,6 +103,18 @@ export function runAiUsageStorageContractSuite<TStorage extends AiUsageStorage>(
102
103
  })
103
104
  )
104
105
  expect((await latest())?.modelKind).toBe("reranking")
106
+
107
+ await storage.recordModelCall(
108
+ modelCallInput({
109
+ id: "usage_web_search",
110
+ callId: "call_web_search",
111
+ responseId: "response_web_search",
112
+ modelKind: "web-search",
113
+ usage: {},
114
+ occurredAt: at("2026-06-23T10:02:00.000Z"),
115
+ })
116
+ )
117
+ expect((await latest())?.modelKind).toBe("web-search")
105
118
  })
106
119
  })
107
120
  // Removal proof: omit a media count from a row codec, or 'speech' from a storage migration's
@@ -454,6 +454,29 @@ export function runConnectorConnectionStorageContractSuite<
454
454
  })
455
455
  })
456
456
 
457
+ test("connects another account to a disconnected slot without replacement", async () => {
458
+ await withStorage(async (storage) => {
459
+ const first = await createAuthorization(storage, "authorization-a", "account-a")
460
+ const connected = await connect(storage, first, "connection-a", "account-a")
461
+ await storage.disconnectConnection({
462
+ projectId,
463
+ connectorId,
464
+ connectionId: connected.connection.id,
465
+ })
466
+
467
+ const second = await createAuthorization(storage, "authorization-b", "account-b")
468
+ const reconnected = await connect(storage, second, "ignored-new-id", "account-b")
469
+
470
+ expect(reconnected.connection).toMatchObject({
471
+ id: connected.connection.id,
472
+ authorizationId: second.id,
473
+ account: { id: "account-b" },
474
+ status: "connected",
475
+ })
476
+ expect(reconnected.replaced).toBe(false)
477
+ })
478
+ })
479
+
457
480
  test("keeps pending selection untouched when connection validation fails", async () => {
458
481
  await withStorage(async (storage) => {
459
482
  const active = await createAuthorization(storage, "authorization-a", "account-a")
@@ -6,10 +6,14 @@ import {
6
6
  type ObjectQueryPredicate,
7
7
  validateObjectQuery,
8
8
  } from "../objects/query"
9
- import { defineObjectType, link, OntologyRegistry, prop } from "../ontology"
9
+ import { bindCurrentUserPredicate } from "../objects/query/current-user"
10
+ import { defineObjectType, link, OntologyRegistry, prop, ref } from "../ontology"
11
+ import type { UserRef } from "../ontology/user-ref"
12
+ import { viewConditionReadCondition } from "../security/visibility-keys"
10
13
  import { migrateStorage } from "../storage/migrations"
11
14
  import {
12
15
  compileConditionalObjectReadScope,
16
+ type ExpandedLinkValue,
13
17
  linkBatchKey,
14
18
  type ObjectReadCondition,
15
19
  type ObjectReadScopeFactory,
@@ -57,10 +61,30 @@ const Customer = defineObjectType({
57
61
  id: "ConditionCustomer",
58
62
  name: "Condition Customer",
59
63
  properties: [prop("id", "string", { required: true, primary: true }), prop("name", "string")],
60
- links: [link("invoices", Invoice)],
64
+ links: [link("invoices", Invoice), link("primaryInvoice", Invoice, { cardinality: "one" })],
61
65
  })
62
66
 
63
- const ontology = new OntologyRegistry({ sources: [Invoice, CreditNote, Customer] })
67
+ /** Who sees a ticket depends on its reader: the conditions compare `currentUser()`. */
68
+ const Ticket = defineObjectType({
69
+ id: "ConditionTicket",
70
+ name: "Condition Ticket",
71
+ properties: [
72
+ prop("id", "string", {
73
+ required: true,
74
+ primary: true,
75
+ query: { searchable: true, sortable: true },
76
+ }),
77
+ prop("status", "string", { query: { searchable: true, filterable: true } }),
78
+ prop("owner", ref.user(), { nullable: true, query: { searchable: true, filterable: true } }),
79
+ prop(
80
+ "watchers",
81
+ { type: "array", items: ref.user() },
82
+ { nullable: true, query: { searchable: true, filterable: true } }
83
+ ),
84
+ ],
85
+ })
86
+
87
+ const ontology = new OntologyRegistry({ sources: [Invoice, CreditNote, Customer, Ticket] })
64
88
 
65
89
  /**
66
90
  * Portable conditional-read contract shared by every storage provider.
@@ -393,6 +417,134 @@ export function runConditionalObjectReadScopeContractSuite<TStorage extends Stor
393
417
  })
394
418
  })
395
419
 
420
+ test("never expands through a hidden object", async () => {
421
+ await withHarness(async ({ harness }) => {
422
+ // Without conditions every edge is reached, so each expectation of the conditioned reader
423
+ // can only hold if the hidden draft and the links touching it stay out.
424
+ const unconditioned = createReader(harness.objectReadScopeFactory, [])
425
+ const conditioned = createReader(harness.objectReadScopeFactory, [noDrafts(Invoice.id)])
426
+
427
+ const customers = async (reader: ObjectReadStorage) => {
428
+ const [customer] = await queryRows(reader, {
429
+ kind: "expand",
430
+ input: {
431
+ kind: "limit",
432
+ limit: 10,
433
+ input: { kind: "start", objectTypeId: Customer.id },
434
+ },
435
+ expansions: [
436
+ { linkId: "primaryInvoice", direction: "outgoing" },
437
+ {
438
+ linkId: "invoices",
439
+ direction: "outgoing",
440
+ expand: [{ linkId: "related", direction: "outgoing" }],
441
+ },
442
+ ],
443
+ })
444
+
445
+ return {
446
+ primaryInvoice: linkedIds(customer?.links?.primaryInvoice),
447
+ invoices: Object.fromEntries(
448
+ linkedRows(customer?.links?.invoices).map((row) => [
449
+ row.primaryId,
450
+ linkedIds(row.links?.related),
451
+ ])
452
+ ),
453
+ }
454
+ }
455
+
456
+ expect(await customers(unconditioned)).toEqual({
457
+ primaryInvoice: ["inv-2"],
458
+ invoices: { "inv-1": ["inv-2", "inv-3"], "inv-2": ["inv-1"], "inv-3": [] },
459
+ })
460
+ // The hidden draft is neither a neighbour nor the middle of a nested expansion.
461
+ expect(await customers(conditioned)).toEqual({
462
+ primaryInvoice: [],
463
+ invoices: { "inv-1": ["inv-3"], "inv-3": [] },
464
+ })
465
+
466
+ const relatedFrom = async (reader: ObjectReadStorage) => {
467
+ const invoices = await queryRows(reader, {
468
+ kind: "expand",
469
+ input: {
470
+ kind: "limit",
471
+ limit: 10,
472
+ input: sorted({ kind: "start", objectTypeId: Invoice.id }, "amount"),
473
+ },
474
+ expansions: [
475
+ { linkId: "related", direction: "incoming", sourceObjectTypeId: Invoice.id },
476
+ ],
477
+ })
478
+
479
+ return invoices.map((row) => linkedIds(row.links?.related))
480
+ }
481
+
482
+ expect(await relatedFrom(unconditioned)).toEqual([["inv-2"], ["inv-1"], ["inv-1"]])
483
+ expect(await relatedFrom(conditioned)).toEqual([[], ["inv-1"]])
484
+ })
485
+ })
486
+
487
+ test("never traverses through a hidden object", async () => {
488
+ await withHarness(async ({ harness }) => {
489
+ // As above, the unconditioned reader shows what each traversal reaches through the draft.
490
+ const unconditioned = createReader(harness.objectReadScopeFactory, [])
491
+ const conditioned = createReader(harness.objectReadScopeFactory, [noDrafts(Invoice.id)])
492
+
493
+ const reached = async (reader: ObjectReadStorage, query: ObjectQuery) => {
494
+ const rows = await queryRows(reader, query)
495
+ return rows.map((row) => row.primaryId).sort()
496
+ }
497
+ const relatedOf = (input: ObjectQuery): ObjectQuery => ({
498
+ kind: "traverse",
499
+ direction: "outgoing",
500
+ linkId: "related",
501
+ input,
502
+ })
503
+ const refs = (...primaryIds: string[]): ObjectQuery => ({
504
+ kind: "refs",
505
+ refs: primaryIds.map((primaryId) => ({ objectTypeId: Invoice.id, primaryId })),
506
+ })
507
+
508
+ const twoHops = relatedOf({
509
+ kind: "traverse",
510
+ direction: "outgoing",
511
+ linkId: "invoices",
512
+ input: { kind: "start", objectTypeId: Customer.id },
513
+ })
514
+ expect(await reached(unconditioned, twoHops)).toEqual(["inv-1", "inv-2", "inv-3"])
515
+ expect(await reached(conditioned, twoHops)).toEqual(["inv-3"])
516
+
517
+ const fromRefs = relatedOf(refs("inv-1", "inv-2"))
518
+ expect(await reached(unconditioned, fromRefs)).toEqual(["inv-1", "inv-2", "inv-3"])
519
+ expect(await reached(conditioned, fromRefs)).toEqual(["inv-3"])
520
+
521
+ const fromSet = relatedOf({
522
+ kind: "set",
523
+ op: "union",
524
+ inputs: [refs("inv-2"), refs("inv-3")],
525
+ })
526
+ expect(await reached(unconditioned, fromSet)).toEqual(["inv-1"])
527
+ expect(await reached(conditioned, fromSet)).toEqual([])
528
+
529
+ // From the target side, the hidden draft is the source of a link to a visible invoice.
530
+ const sourcesOf: ObjectQuery = {
531
+ kind: "traverse",
532
+ direction: "incoming",
533
+ linkId: "related",
534
+ sourceObjectTypeId: Invoice.id,
535
+ input: refs("inv-1", "inv-3"),
536
+ }
537
+ expect(await reached(unconditioned, sourcesOf)).toEqual(["inv-1", "inv-2"])
538
+ expect(await reached(conditioned, sourcesOf)).toEqual(["inv-1"])
539
+ expect(await unconditioned.countObjects?.({ projectId, query: sourcesOf })).toEqual({
540
+ count: 2,
541
+ })
542
+ expect(await conditioned.countObjects?.({ projectId, query: sourcesOf })).toEqual({
543
+ count: 1,
544
+ })
545
+ })
546
+ })
547
+
396
548
  test("applies a condition to its concrete type only", async () => {
397
549
  await withHarness(async ({ harness }) => {
398
550
  const invoicesOnly = createReader(harness.objectReadScopeFactory, [noDrafts(Invoice.id)])
@@ -445,6 +597,84 @@ export function runConditionalObjectReadScopeContractSuite<TStorage extends Stor
445
597
  })
446
598
  })
447
599
 
600
+ // A provider may filter a member's reads on the keys of its conditions instead of their
601
+ // predicate. Both must show each reader the same objects, whatever its user's id.
602
+ test("shows a reader through its conditions' keys exactly what their predicate shows", async () => {
603
+ await withHarness(async ({ harness, fixture }) => {
604
+ const ids = ["usr_1", 'a"b', "a\\b", 'a", "b', "*", "u:usr_1"]
605
+ const users = ids.map((id): UserRef => ({ type: "user", id }))
606
+
607
+ const auth = harness.storage.auth
608
+ if (!auth) throw new Error("The conditional read contract requires auth storage.")
609
+ for (const [index, id] of ids.entries()) {
610
+ await auth.users.create({ projectId, id, email: `reader-${index}@example.com` })
611
+ }
612
+
613
+ await fixture.seed({
614
+ objects: users.flatMap((user, index) => [
615
+ object(Ticket.id, `t-${index}-owned`, {
616
+ id: `t-${index}-owned`,
617
+ status: "open",
618
+ owner: user,
619
+ }),
620
+ object(Ticket.id, `t-${index}-watched`, {
621
+ id: `t-${index}-watched`,
622
+ status: index % 2 === 0 ? "open" : "closed",
623
+ owner: users[(index + 1) % users.length]!,
624
+ watchers: [user, users[(index + 2) % users.length]!],
625
+ }),
626
+ ]),
627
+ links: [],
628
+ })
629
+
630
+ const me = { type: "currentUser" }
631
+ const conditions: ObjectQueryPredicate[] = [
632
+ { op: "eq", propertyId: "owner", value: me },
633
+ { op: "contains", propertyId: "watchers", value: me },
634
+ {
635
+ op: "or",
636
+ items: [
637
+ { op: "eq", propertyId: "status", value: "closed" },
638
+ { op: "in", propertyId: "owner", values: [me, users[0]!] },
639
+ ],
640
+ },
641
+ {
642
+ op: "and",
643
+ items: [
644
+ { op: "eq", propertyId: "status", value: "open" },
645
+ { op: "contains", propertyId: "watchers", value: me },
646
+ ],
647
+ },
648
+ // No keys: read through its predicate beside the keys of the others.
649
+ { op: "neq", propertyId: "owner", value: me },
650
+ ]
651
+
652
+ const visible = async (condition: ObjectReadCondition) => {
653
+ const reader = createReader(harness.objectReadScopeFactory, [condition])
654
+ const rows = await queryRows(reader, {
655
+ kind: "limit",
656
+ limit: 100,
657
+ input: sorted({ kind: "start", objectTypeId: Ticket.id }, "id"),
658
+ })
659
+ return rows.map((row) => row.primaryId)
660
+ }
661
+
662
+ for (const [index, condition] of conditions.entries()) {
663
+ const predicates = [ticketCondition(condition), ticketCondition(conditions[0]!)]
664
+ for (const user of [undefined, ...users]) {
665
+ const keyed = viewConditionReadCondition(Ticket.id, predicates, user)
666
+ const bound = bindCurrentUserPredicate({ op: "or", items: predicates }, user)
667
+
668
+ expect({ index, user, ids: await visible(keyed) }).toEqual({
669
+ index,
670
+ user,
671
+ ids: await visible({ objectTypeId: Ticket.id, predicate: bound }),
672
+ })
673
+ }
674
+ }
675
+ })
676
+ })
677
+
448
678
  test("never reads another project's objects or links", async () => {
449
679
  await withHarness(async ({ harness }) => {
450
680
  await migrateStorage(harness.storage, { projectId: otherProjectId, ontology })
@@ -555,7 +785,10 @@ function createReader(
555
785
  })
556
786
  }
557
787
 
558
- /** `status neq "draft"`, validated like a grant's condition so `scalarKind` is resolved. */
788
+ /**
789
+ * `status neq "draft"`, validated like a grant's condition so `scalarKind` is resolved, and read the
790
+ * way a member reads it: with its keys, which a provider may filter on instead of the predicate.
791
+ */
559
792
  function noDrafts(objectTypeId: string): ObjectReadCondition {
560
793
  const predicate: ObjectQueryPredicate = { op: "neq", propertyId: "status", value: "draft" }
561
794
  const { query } = validateObjectQuery(
@@ -564,7 +797,35 @@ function noDrafts(objectTypeId: string): ObjectReadCondition {
564
797
  )
565
798
  if (query.kind !== "filter") throw new Error("expected a validated filter")
566
799
 
567
- return { objectTypeId, predicate: query.predicate }
800
+ return viewConditionReadCondition(objectTypeId, [query.predicate], undefined)
801
+ }
802
+
803
+ /** A ticket condition as a grant's validation returns it, `currentUser()` left unbound. */
804
+ function ticketCondition(predicate: ObjectQueryPredicate): ObjectQueryPredicate {
805
+ const { query } = validateObjectQuery(
806
+ { kind: "filter", input: { kind: "start", objectTypeId: Ticket.id }, predicate },
807
+ { ontology }
808
+ )
809
+ if (query.kind !== "filter") throw new Error("expected a validated filter")
810
+ return query.predicate
811
+ }
812
+
813
+ /** Run a query as the executor does, so a provider pushes down what it can. */
814
+ async function queryRows(reader: ObjectReadStorage, query: ObjectQuery) {
815
+ const result = await executeObjectQuery({ projectId, query }, { ontology, storage: reader })
816
+ return result.objects
817
+ }
818
+
819
+ /** An expanded link's neighbours, whatever its cardinality. */
820
+ function linkedRows(value: ExpandedLinkValue | undefined) {
821
+ if (Array.isArray(value)) return value
822
+ return value ? [value] : []
823
+ }
824
+
825
+ function linkedIds(value: ExpandedLinkValue | undefined): string[] {
826
+ return linkedRows(value)
827
+ .map((row) => row.primaryId)
828
+ .sort()
568
829
  }
569
830
 
570
831
  function sorted(
@@ -595,6 +856,7 @@ async function seed(fixture: MaterializerTestFixture): Promise<void> {
595
856
  linkRow(Customer.id, "cust-1", "invoices", Invoice.id, "inv-1"),
596
857
  linkRow(Customer.id, "cust-1", "invoices", Invoice.id, "inv-2"),
597
858
  linkRow(Customer.id, "cust-1", "invoices", Invoice.id, "inv-3"),
859
+ linkRow(Customer.id, "cust-1", "primaryInvoice", Invoice.id, "inv-2"),
598
860
  linkRow(Invoice.id, "inv-1", "related", Invoice.id, "inv-2"),
599
861
  linkRow(Invoice.id, "inv-2", "related", Invoice.id, "inv-1"),
600
862
  linkRow(Invoice.id, "inv-1", "related", Invoice.id, "inv-3"),