@capybara-hq/kernel 0.1.0-rc.136 → 0.1.0-rc.137

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 (158) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/agents/templates.js +3 -10
  10. package/dist/app.d.ts +3 -1
  11. package/dist/app.js +1 -0
  12. package/dist/automations/automations.service.js +4 -5
  13. package/dist/catalog/catalog-content.d.ts +1 -1
  14. package/dist/catalog/catalog-content.js +17 -22
  15. package/dist/catalog/catalog-items.d.ts +5 -10
  16. package/dist/catalog/catalog-items.js +27 -51
  17. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  18. package/dist/catalog/catalog-scope.service.js +105 -141
  19. package/dist/catalog/catalog.module.js +2 -0
  20. package/dist/catalog/catalog.service.d.ts +3 -3
  21. package/dist/catalog/catalog.service.js +33 -8
  22. package/dist/catalog/cli.js +17 -0
  23. package/dist/catalog/component-promotion.js +8 -4
  24. package/dist/catalog/component-scope.service.d.ts +3 -1
  25. package/dist/catalog/component-scope.service.js +101 -140
  26. package/dist/catalog/component-state.d.ts +10 -8
  27. package/dist/catalog/component-state.js +42 -30
  28. package/dist/catalog/dependency-edges.d.ts +25 -0
  29. package/dist/catalog/dependency-edges.js +125 -0
  30. package/dist/catalog/install-status.d.ts +2 -3
  31. package/dist/catalog/install-status.js +2 -3
  32. package/dist/catalog/org-catalog.service.d.ts +3 -1
  33. package/dist/catalog/org-catalog.service.js +33 -94
  34. package/dist/catalog/org-intent.d.ts +43 -0
  35. package/dist/catalog/org-intent.js +184 -0
  36. package/dist/catalog/owned-items.d.ts +1 -1
  37. package/dist/catalog/owned-items.js +9 -29
  38. package/dist/catalog/ownership.d.ts +2 -3
  39. package/dist/catalog/ownership.js +10 -28
  40. package/dist/catalog/platform-components.d.ts +3 -1
  41. package/dist/catalog/platform-components.js +9 -1
  42. package/dist/catalog/plugin-import.js +12 -16
  43. package/dist/catalog/plugin-install.d.ts +3 -4
  44. package/dist/catalog/plugin-install.js +25 -49
  45. package/dist/catalog/plugin-upgrade.d.ts +2 -2
  46. package/dist/catalog/plugin-upgrade.js +18 -34
  47. package/dist/catalog/request-rules.js +20 -8
  48. package/dist/catalog/scope-orgs.js +2 -7
  49. package/dist/catalog/scope-state.d.ts +6 -6
  50. package/dist/catalog/scope-state.js +24 -43
  51. package/dist/catalog/scope-sync.d.ts +0 -2
  52. package/dist/catalog/scope-sync.js +11 -39
  53. package/dist/catalog/scope-writer.d.ts +78 -0
  54. package/dist/catalog/scope-writer.js +181 -0
  55. package/dist/catalog/unshare.js +8 -41
  56. package/dist/channels/connections.service.js +6 -6
  57. package/dist/channels/supervisor.js +3 -7
  58. package/dist/client/client-access.service.js +2 -12
  59. package/dist/config/schema.d.ts +6 -0
  60. package/dist/config/schema.js +29 -1
  61. package/dist/ctx/create-ctx.d.ts +2 -2
  62. package/dist/ctx/create-ctx.js +2 -60
  63. package/dist/ctx/guard-db.d.ts +6 -0
  64. package/dist/ctx/guard-db.js +55 -0
  65. package/dist/db/extension-handoff-schema.d.ts +1 -1
  66. package/dist/db/extension-handoff-schema.js +48 -10
  67. package/dist/db/extension-schema-transfer.js +5 -2
  68. package/dist/db/kernel-schema.d.ts +11 -1
  69. package/dist/device-access/host-services.d.ts +2 -2
  70. package/dist/device-access/host-services.js +5 -6
  71. package/dist/erasure/org-catalog.js +2 -2
  72. package/dist/erasure/org-rules.js +5 -0
  73. package/dist/extensions/admin-ops.d.ts +9 -5
  74. package/dist/extensions/admin-ops.js +52 -8
  75. package/dist/extensions/admin-view.js +1 -4
  76. package/dist/extensions/bootstrap.js +4 -1
  77. package/dist/extensions/cli.js +1 -0
  78. package/dist/extensions/effective-config.js +1 -4
  79. package/dist/extensions/enabled.d.ts +23 -29
  80. package/dist/extensions/enabled.js +141 -62
  81. package/dist/extensions/host.d.ts +64 -45
  82. package/dist/extensions/host.js +443 -128
  83. package/dist/extensions/installs.d.ts +9 -0
  84. package/dist/extensions/installs.js +23 -0
  85. package/dist/extensions/isolated/admission.d.ts +10 -0
  86. package/dist/extensions/isolated/admission.js +206 -0
  87. package/dist/extensions/isolated/authorization.d.ts +37 -0
  88. package/dist/extensions/isolated/authorization.js +146 -0
  89. package/dist/extensions/isolated/broker.d.ts +15 -0
  90. package/dist/extensions/isolated/broker.js +452 -0
  91. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  92. package/dist/extensions/isolated/child-protocol.js +21 -0
  93. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  94. package/dist/extensions/isolated/child-registration.js +152 -0
  95. package/dist/extensions/isolated/child-session.d.ts +6 -0
  96. package/dist/extensions/isolated/child-session.js +343 -0
  97. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  98. package/dist/extensions/isolated/child-streams.js +142 -0
  99. package/dist/extensions/isolated/child.d.ts +1 -0
  100. package/dist/extensions/isolated/child.js +10 -0
  101. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  102. package/dist/extensions/isolated/configured-package.js +73 -0
  103. package/dist/extensions/isolated/lanes.d.ts +100 -0
  104. package/dist/extensions/isolated/lanes.js +699 -0
  105. package/dist/extensions/isolated/postgres-gate.d.ts +14 -0
  106. package/dist/extensions/isolated/postgres-gate.js +255 -0
  107. package/dist/extensions/isolated/revision.d.ts +32 -0
  108. package/dist/extensions/isolated/revision.js +358 -0
  109. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  110. package/dist/extensions/isolated/rpc-frame.js +193 -0
  111. package/dist/extensions/isolated/rpc.d.ts +66 -0
  112. package/dist/extensions/isolated/rpc.js +314 -0
  113. package/dist/extensions/isolated/sandbox.d.ts +35 -0
  114. package/dist/extensions/isolated/sandbox.js +372 -0
  115. package/dist/extensions/isolated/tier.d.ts +6 -0
  116. package/dist/extensions/isolated/tier.js +45 -0
  117. package/dist/extensions/ledger.d.ts +1 -1
  118. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  119. package/dist/extensions/lifecycle-topics.js +1 -0
  120. package/dist/extensions/lifecycle.d.ts +3 -1
  121. package/dist/extensions/lifecycle.js +32 -5
  122. package/dist/extensions/locks.d.ts +2 -0
  123. package/dist/extensions/locks.js +7 -0
  124. package/dist/extensions/org-config.d.ts +17 -27
  125. package/dist/extensions/org-config.js +114 -129
  126. package/dist/extensions/plugin-guides.d.ts +5 -10
  127. package/dist/extensions/plugin-guides.js +18 -37
  128. package/dist/extensions/plugin-icons.d.ts +3 -21
  129. package/dist/extensions/plugin-icons.js +9 -44
  130. package/dist/extensions/plugin-items.d.ts +10 -30
  131. package/dist/extensions/plugin-items.js +32 -73
  132. package/dist/extensions/source-intent.d.ts +14 -0
  133. package/dist/extensions/source-intent.js +77 -0
  134. package/dist/index.d.ts +2 -1
  135. package/dist/index.js +2 -1
  136. package/dist/infra/database/database.module.js +6 -1
  137. package/dist/infra/database/kernel-db.d.ts +3 -1
  138. package/dist/infra/database/kernel-db.js +4 -0
  139. package/dist/infra/paging/paged-read.d.ts +56 -0
  140. package/dist/infra/paging/paged-read.js +78 -0
  141. package/dist/kernel.d.ts +3 -2
  142. package/dist/kernel.js +21 -2
  143. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  144. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  145. package/dist/lifecycle/tokens.d.ts +8 -0
  146. package/dist/lifecycle/tokens.js +2 -0
  147. package/dist/orgs/directory-sync.js +1 -4
  148. package/dist/platform/ops/admin.ops.js +14 -3
  149. package/dist/platform/ops/orgs.ops.js +13 -3
  150. package/dist/setup/setup-checks.service.js +3 -2
  151. package/dist/skills/usable.js +41 -30
  152. package/dist/themes/theme-state.js +3 -3
  153. package/dist/tools/registry.d.ts +1 -1
  154. package/dist/tools/registry.js +1 -1
  155. package/package.json +2 -2
  156. package/src/migrations/0228_extension_org_switches.sql +56 -0
  157. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  158. package/src/migrations/0230_audit_filter_idx.sql +18 -0
@@ -1,4 +1,4 @@
1
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
1
+ import { orgCatalogAdmits, orgUsable } from "./org-intent.js";
2
2
  import { visibleTo, wantedOn } from "./scope.js";
3
3
  import { templateDescription } from "./template-description.js";
4
4
  /** The kinds the scope, switch, ownership and preview flows (and the component routes) walk. */
@@ -20,7 +20,7 @@ function stopped(c, p) {
20
20
  * Whether the component is on in the org (`listed`: the org on the component's own `named` list;
21
21
  * `sw`: the org's component switch):
22
22
  * - never when the component or its plugin is disabled, or its plugin is deleted;
23
- * - `follow`: its plugin is on in the org (a live install, or builtin) and the switch is not off
23
+ * - `follow`: its plugin is usable in the org and the switch is not off
24
24
  * (a `defaultOff` template of a plugin that is not builtin: the switch is on);
25
25
  * - `own`: `wantedOn` over the component's own scope, the list and the switch.
26
26
  */
@@ -34,14 +34,14 @@ export function componentOn(c, p, listed, sw) {
34
34
  return wantedOn({ scope: c.scope, disabled: false, builtin: false }, listed, sw);
35
35
  }
36
36
  /**
37
- * Whether the plugin a component follows is on in the org (a live install there, or builtin); a
37
+ * Whether the plugin a component follows is usable in the org; a
38
38
  * component with its own scope does not depend on it (true). A `follow` component comes on and off
39
39
  * with its plugin (spec §5 rule 5), so its own switch only matters while this holds.
40
40
  */
41
41
  export function componentPluginOn(c, p) {
42
42
  if (c.scopeMode === "own")
43
43
  return true;
44
- return p !== null && p.live && (p.installed || p.builtin);
44
+ return p?.live === true && p.usable;
45
45
  }
46
46
  /**
47
47
  * Whether the component is offered to the org: on, or an org admin could turn it on there (spec
@@ -53,7 +53,9 @@ export function componentOffered(c, p, listed) {
53
53
  if (stopped(c, p))
54
54
  return false;
55
55
  if (c.scopeMode === "follow") {
56
- return p !== null && (p.builtin || visibleTo({ scope: p.scope }, p.listed));
56
+ return (p !== null &&
57
+ p.admitted !== false &&
58
+ (p.usable || p.builtin || visibleTo({ scope: p.scope }, p.listed)));
57
59
  }
58
60
  return visibleTo({ scope: c.scope }, listed);
59
61
  }
@@ -180,15 +182,16 @@ const groupBy = (rows, key, value) => {
180
182
  return out;
181
183
  };
182
184
  /** Reads the {@link ScopeState} of `comps` (all of one kind), one query after the other. */
183
- // org-filter: the scope state of platform components and their plugins for every org (named lists,
184
- // installs, switches keyed by platform ids); callers pick their own org out of it
185
- export async function loadScopeState(db, kind, comps) {
185
+ // org-filter: the scope state of platform components and their plugins for every org (named lists and
186
+ // switches keyed by platform IDs); org readers supply their org
187
+ export async function loadScopeState(db, kind, comps, orgId) {
186
188
  const itemIds = [...new Set(comps.map((c) => c.itemId).filter((x) => x !== null))];
187
189
  const ids = comps.map((c) => c.id);
188
190
  const state = {
189
191
  plugins: new Map(),
190
192
  pluginListed: new Map(),
191
- installed: new Map(),
193
+ usable: new Map(),
194
+ admitted: new Map(),
192
195
  listed: new Map(),
193
196
  switches: new Map(),
194
197
  };
@@ -212,13 +215,21 @@ export async function loadScopeState(db, kind, comps) {
212
215
  .where("item_id", "in", itemIds)
213
216
  .execute();
214
217
  state.pluginListed = groupBy(listed, (r) => r.item_id, (r) => r.org_id);
215
- const installs = await db
216
- .selectFrom("plugin_installs")
217
- .select(["item_id", "org_id"])
218
- .where("item_id", "in", itemIds)
219
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
220
- .execute();
221
- state.installed = groupBy(installs, (r) => r.item_id, (r) => r.org_id);
218
+ const intentQuery = db
219
+ .selectFrom("catalog_items as candidate")
220
+ .crossJoin("orgs as org")
221
+ .select(["candidate.id as item_id", "org.id as org_id"])
222
+ .select(({ ref }) => [
223
+ orgUsable(db, ref("org.id"), ref("candidate.id")).as("usable"),
224
+ orgCatalogAdmits(db, ref("org.id"), ref("candidate.id")).as("admitted"),
225
+ ])
226
+ .where("candidate.id", "in", itemIds)
227
+ .where("org.deleted_at", "is", null);
228
+ const facts = await (orgId === undefined
229
+ ? intentQuery
230
+ : intentQuery.where("org.id", "=", orgId)).execute();
231
+ state.usable = groupBy(facts.filter((row) => row.usable), (row) => row.item_id, (row) => row.org_id);
232
+ state.admitted = groupBy(facts.filter((row) => row.admitted), (row) => row.item_id, (row) => row.org_id);
222
233
  }
223
234
  if (ids.length > 0) {
224
235
  const listed = await db
@@ -244,7 +255,7 @@ export async function loadScopeState(db, kind, comps) {
244
255
  }
245
256
  /**
246
257
  * Whether a catalog item is builtin: marked so and owned by the platform. An org-owned item marked
247
- * builtin (never so in practice) is an ordinary item: never on without an install, never locked,
258
+ * builtin (never so in practice) is an ordinary item with regular scope and switches,
248
259
  * and its skills can be turned off (skills default-on spec §3).
249
260
  */
250
261
  export const platformBuiltin = (item) => item.builtin === true && item.owner_org_id === null;
@@ -260,7 +271,7 @@ export function pluginFactsOf(st, itemId, orgId) {
260
271
  builtin: false,
261
272
  scope: "optional",
262
273
  listed: false,
263
- installed: false,
274
+ usable: false,
264
275
  };
265
276
  return {
266
277
  live: true,
@@ -268,7 +279,8 @@ export function pluginFactsOf(st, itemId, orgId) {
268
279
  builtin: p.builtin,
269
280
  scope: p.scope,
270
281
  listed: st.pluginListed.get(itemId)?.has(orgId) ?? false,
271
- installed: st.installed.get(itemId)?.has(orgId) ?? false,
282
+ usable: st.usable.get(itemId)?.has(orgId) ?? false,
283
+ admitted: st.admitted.get(itemId)?.has(orgId) ?? false,
272
284
  };
273
285
  }
274
286
  /** The org's switch of a component from a {@link ScopeState}. */
@@ -406,7 +418,7 @@ export async function offeredNamed(db, orgId, kind, name) {
406
418
  const comps = await loadComponents(db, kind, { name });
407
419
  if (comps.length === 0)
408
420
  return [];
409
- const st = await loadScopeState(db, kind, comps);
421
+ const st = await loadScopeState(db, kind, comps, orgId);
410
422
  return comps.filter((c) => componentOffered(c, pluginFactsOf(st, c.itemId, orgId), listedIn(st, c.id, orgId)));
411
423
  }
412
424
  /** The other platform skills named `name` that are on in the org (rule 10). */
@@ -414,7 +426,7 @@ export async function clashingPlatformSkills(db, orgId, component, name) {
414
426
  const others = (await loadComponents(db, "skill", { name })).filter((c) => c.id !== component.id);
415
427
  if (others.length === 0)
416
428
  return [];
417
- const st = await loadScopeState(db, "skill", others);
429
+ const st = await loadScopeState(db, "skill", others, orgId);
418
430
  return others.filter((c) => componentOn(c, pluginFactsOf(st, c.itemId, orgId), listedIn(st, c.id, orgId), switchOf(st, c.id, orgId)));
419
431
  }
420
432
  /**
@@ -439,7 +451,7 @@ export async function themeIdClashes(db, orgId, self, name) {
439
451
  const others = (await loadComponents(db, "theme", { name })).filter((c) => c.id !== self?.id);
440
452
  if (others.length === 0)
441
453
  return [];
442
- const st = await loadScopeState(db, "theme", others);
454
+ const st = await loadScopeState(db, "theme", others, orgId);
443
455
  return others.filter((c) => componentOn(c, pluginFactsOf(st, c.itemId, orgId), listedIn(st, c.id, orgId), switchOf(st, c.id, orgId)));
444
456
  }
445
457
  /** A connector template's id from its manifest path (`./connectors/<id>.json`). */
@@ -455,12 +467,12 @@ export async function connectorTemplatesOn(db, orgId, itemId, ids, defaultOff) {
455
467
  if (ids.length === 0)
456
468
  return new Set();
457
469
  const comps = await loadComponents(db, "connector_template", { itemId });
458
- const st = await loadScopeState(db, "connector_template", comps);
470
+ const st = await loadScopeState(db, "connector_template", comps, orgId);
459
471
  const off = new Set(comps
460
472
  .filter((c) => {
461
473
  const p = pluginFactsOf(st, c.itemId, orgId);
462
474
  const shipped = defaultOff?.get(c.name);
463
- return !componentOn(shipped === undefined ? c : { ...c, defaultOff: shipped }, p && { ...p, installed: true }, listedIn(st, c.id, orgId), switchOf(st, c.id, orgId));
475
+ return !componentOn(shipped === undefined ? c : { ...c, defaultOff: shipped }, p && { ...p, usable: true }, listedIn(st, c.id, orgId), switchOf(st, c.id, orgId));
464
476
  })
465
477
  .map((c) => c.name));
466
478
  return new Set(ids.filter((id) => !off.has(id)));
@@ -474,19 +486,19 @@ export async function connectorTemplatesOn(db, orgId, itemId, ids, defaultOff) {
474
486
  */
475
487
  export async function connectorTemplateChoice(db, orgId, itemId, chosen) {
476
488
  const comps = await loadComponents(db, "connector_template", { itemId });
477
- const st = await loadScopeState(db, "connector_template", comps);
489
+ const st = await loadScopeState(db, "connector_template", comps, orgId);
478
490
  const on = new Set();
479
491
  const switches = [];
480
492
  const refused = [];
481
493
  for (const c of comps) {
482
494
  const p = pluginFactsOf(st, c.itemId, orgId);
483
- const installed = p && { ...p, installed: true };
495
+ const proposed = p && { ...p, usable: true };
484
496
  const listed = listedIn(st, c.id, orgId);
485
497
  const sw = switchOf(st, c.id, orgId);
486
- const now = componentOn(c, installed, listed, sw);
498
+ const now = componentOn(c, proposed, listed, sw);
487
499
  const want = chosen.has(c.name);
488
500
  if (want) {
489
- if (!componentOn(c, installed, listed, true)) {
501
+ if (!componentOn(c, proposed, listed, true)) {
490
502
  refused.push(c.name);
491
503
  continue;
492
504
  }
@@ -515,7 +527,7 @@ export async function connectorsMadeFrom(db, orgId, id) {
515
527
  }
516
528
  /**
517
529
  * Whether platform connector template `id` is on in the org (`on`), offered to it but off
518
- * (`off`: its plugin not installed for a `follow` template, or switched off there), or neither
530
+ * (`off`: its plugin off for a `follow` template, or the template switched off there), or neither
519
531
  * (`absent`: missing, deleted, without a plugin, stopped or not offered). One more connector from a
520
532
  * template needs `on` (ruling P4-T6-8), read before and again under the org lock.
521
533
  */
@@ -523,7 +535,7 @@ export async function connectorTemplateState(db, orgId, id) {
523
535
  const [c] = await loadComponents(db, "connector_template", { ids: [id] });
524
536
  if (!c || c.itemId === null)
525
537
  return "absent";
526
- const st = await loadScopeState(db, "connector_template", [c]);
538
+ const st = await loadScopeState(db, "connector_template", [c], orgId);
527
539
  const p = pluginFactsOf(st, c.itemId, orgId);
528
540
  const listed = listedIn(st, c.id, orgId);
529
541
  if (componentOn(c, p, listed, switchOf(st, c.id, orgId)))
@@ -0,0 +1,25 @@
1
+ import type { PluginManifest } from "@capybara-hq/plugin-sdk";
2
+ import { type Insertable } from "kysely";
3
+ import type { CatalogDependencyEdgesTable, KernelSchemaDb } from "../db/kernel-schema.js";
4
+ interface SelectedVersion {
5
+ id: string;
6
+ name: string;
7
+ version: string;
8
+ manifest: PluginManifest;
9
+ }
10
+ interface TemplateDependency {
11
+ id: string;
12
+ itemId: string;
13
+ plugin: string;
14
+ range: string;
15
+ }
16
+ type Edge = Insertable<CatalogDependencyEdgesTable>;
17
+ /** Resolve catalog SemVer once when the selected versions change. Missing edges are explicit. */
18
+ export declare function resolveCatalogEdges(versions: readonly SelectedVersion[], templates: readonly TemplateDependency[]): Edge[];
19
+ /** Remove the retired source's edges and make incoming requirements unresolved. */
20
+ export declare function retireCatalogDependencyEdges(db: KernelSchemaDb, itemId: string): Promise<void>;
21
+ /** Complete the cutover once, including after an interruption before the projection committed. */
22
+ export declare function initializeCatalogDependencyEdges(db: KernelSchemaDb): Promise<void>;
23
+ /** Serialize publication in the caller's transaction without taking locks on other catalog items. */
24
+ export declare function refreshCatalogDependencyEdges(db: KernelSchemaDb): Promise<void>;
25
+ export {};
@@ -0,0 +1,125 @@
1
+ import { sql } from "kysely";
2
+ import { satisfiesRange } from "./versions.js";
3
+ /** Resolve catalog SemVer once when the selected versions change. Missing edges are explicit. */
4
+ export function resolveCatalogEdges(versions, templates) {
5
+ const byName = new Map(versions.map((version) => [version.name, version]));
6
+ const byId = new Map(versions.map((version) => [version.id, version]));
7
+ const edges = [];
8
+ const add = (source, name, range, templateId) => {
9
+ const target = byName.get(name);
10
+ const resolved = target !== undefined && satisfiesRange(target.version, range) ? target : null;
11
+ edges.push({
12
+ item_id: source.id,
13
+ item_version: source.version,
14
+ dependency_name: name,
15
+ template_id: templateId,
16
+ dependency_item_id: resolved?.id ?? null,
17
+ dependency_version: resolved?.version ?? null,
18
+ });
19
+ };
20
+ for (const source of versions) {
21
+ for (const dependency of source.manifest.dependencies ?? []) {
22
+ add(source, dependency.name, dependency.version, "");
23
+ }
24
+ }
25
+ for (const template of templates) {
26
+ const source = byId.get(template.itemId);
27
+ if (source === undefined ||
28
+ template.plugin === source.name ||
29
+ !byName.has(template.plugin) ||
30
+ source.manifest.dependencies?.some((dependency) => dependency.name === template.plugin))
31
+ continue;
32
+ add(source, template.plugin, template.range, template.id);
33
+ }
34
+ return edges;
35
+ }
36
+ const initializedKey = "catalogDependencyEdgesInitialized";
37
+ async function lockCatalogDependencyEdges(db) {
38
+ await sql `LOCK TABLE capybara.catalog_dependency_edges IN SHARE ROW EXCLUSIVE MODE`.execute(db);
39
+ }
40
+ /** Remove the retired source's edges and make incoming requirements unresolved. */
41
+ export async function retireCatalogDependencyEdges(db, itemId) {
42
+ await lockCatalogDependencyEdges(db);
43
+ await db.deleteFrom("catalog_dependency_edges").where("item_id", "=", itemId).execute();
44
+ await db
45
+ .updateTable("catalog_dependency_edges")
46
+ .set({ dependency_item_id: null, dependency_version: null })
47
+ .where("dependency_item_id", "=", itemId)
48
+ .execute();
49
+ }
50
+ /** Complete the cutover once, including after an interruption before the projection committed. */
51
+ export async function initializeCatalogDependencyEdges(db) {
52
+ const initialized = () => db
53
+ .selectFrom("deployment_settings")
54
+ .select("key")
55
+ .where("key", "=", initializedKey)
56
+ .executeTakeFirst();
57
+ if (await initialized())
58
+ return;
59
+ await lockCatalogDependencyEdges(db);
60
+ if (await initialized())
61
+ return;
62
+ await writeCatalogDependencyEdges(db);
63
+ await db
64
+ .insertInto("deployment_settings")
65
+ .values({ key: initializedKey, value: "true", updated_by: null })
66
+ .execute();
67
+ }
68
+ /** Serialize publication in the caller's transaction without taking locks on other catalog items. */
69
+ export async function refreshCatalogDependencyEdges(db) {
70
+ await lockCatalogDependencyEdges(db);
71
+ await writeCatalogDependencyEdges(db);
72
+ }
73
+ async function writeCatalogDependencyEdges(db) {
74
+ const versions = await db
75
+ .selectFrom("catalog_items as item")
76
+ .innerJoin("catalog_item_versions as version", (join) => join
77
+ .onRef("version.item_id", "=", "item.id")
78
+ .on("version.version", "=", sql `coalesce(item.platform_synced_version, item.latest_version)`))
79
+ .select(["item.id", "item.name", "version.version", "version.manifest"])
80
+ .where("item.deleted_at", "is", null)
81
+ .execute();
82
+ const templates = await db
83
+ .selectFrom("platform_connector_templates")
84
+ .select(["id", "catalog_item_id", "file"])
85
+ .where("deleted_at", "is", null)
86
+ .execute();
87
+ const edges = resolveCatalogEdges(versions.map((version) => ({ ...version, manifest: version.manifest })), templates.flatMap((row) => {
88
+ const template = row.file.template;
89
+ if (template === undefined)
90
+ return [];
91
+ return [
92
+ {
93
+ id: row.id,
94
+ itemId: row.catalog_item_id,
95
+ plugin: template.plugin,
96
+ range: template.pluginVersion ?? "*",
97
+ },
98
+ ];
99
+ }));
100
+ await sql `
101
+ WITH next_edges AS (
102
+ SELECT * FROM jsonb_to_recordset(${JSON.stringify(edges)}::jsonb) AS edge(
103
+ item_id uuid, item_version text, dependency_name text, template_id text,
104
+ dependency_item_id uuid, dependency_version text
105
+ )
106
+ ), removed AS (
107
+ DELETE FROM capybara.catalog_dependency_edges AS old
108
+ WHERE NOT EXISTS (
109
+ SELECT 1 FROM next_edges AS edge
110
+ WHERE (edge.item_id, edge.dependency_name, edge.template_id)
111
+ = (old.item_id, old.dependency_name, old.template_id)
112
+ )
113
+ )
114
+ INSERT INTO capybara.catalog_dependency_edges AS old
115
+ (item_id, item_version, dependency_name, template_id, dependency_item_id, dependency_version)
116
+ SELECT item_id, item_version, dependency_name, template_id, dependency_item_id, dependency_version
117
+ FROM next_edges
118
+ ON CONFLICT (item_id, dependency_name, template_id) DO UPDATE
119
+ SET item_version = excluded.item_version,
120
+ dependency_item_id = excluded.dependency_item_id,
121
+ dependency_version = excluded.dependency_version
122
+ WHERE (old.item_version, old.dependency_item_id, old.dependency_version) IS DISTINCT FROM
123
+ (excluded.item_version, excluded.dependency_item_id, excluded.dependency_version)
124
+ `.execute(db);
125
+ }
@@ -1,6 +1,5 @@
1
1
  /**
2
- * The `plugin_installs.status` values of a live install: the plugin is on in the org (or about to
3
- * be). `failed` and `uninstalling` are not live. Every query that asks "is this plugin installed
4
- * in the org" uses this one set.
2
+ * A live install owns in-progress or applied setup effects. Failed and uninstalling records
3
+ * are excluded from this set.
5
4
  */
6
5
  export declare const LIVE_INSTALL_STATUSES: readonly ["installing", "installed"];
@@ -1,6 +1,5 @@
1
1
  /**
2
- * The `plugin_installs.status` values of a live install: the plugin is on in the org (or about to
3
- * be). `failed` and `uninstalling` are not live. Every query that asks "is this plugin installed
4
- * in the org" uses this one set.
2
+ * A live install owns in-progress or applied setup effects. Failed and uninstalling records
3
+ * are excluded from this set.
5
4
  */
6
5
  export const LIVE_INSTALL_STATUSES = ["installing", "installed"];
@@ -9,6 +9,7 @@ import { OrgLock } from "../orgs/org-lock.js";
9
9
  import { StorageService } from "../storage/storage.service.js";
10
10
  import { type CatalogIcon, type OrgCatalogDetail, type OrgCatalogItem, type OrgInstallInput, type OrgInstallResult } from "./catalog-content.js";
11
11
  import { PluginInstaller, type UninstallPreview, type UninstallReport } from "./plugin-install.js";
12
+ import { ScopeWriter } from "./scope-writer.js";
12
13
  /** The result of a switch: the item, or (switching off without `confirm`) the uninstall preview. */
13
14
  export type SwitchResult = {
14
15
  kind: "done";
@@ -36,6 +37,7 @@ export declare class OrgCatalogService {
36
37
  private readonly storage;
37
38
  private readonly registry;
38
39
  private readonly pluginInstaller;
40
+ private readonly scopeWriter;
39
41
  private readonly log;
40
42
  readonly txHost: TransactionHost;
41
43
  /** Why a plugin's extension cannot run (the `unavailable` state's reason). */
@@ -45,7 +47,7 @@ export declare class OrgCatalogService {
45
47
  private readonly icons;
46
48
  constructor(kdb: KernelDb,
47
49
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
48
- orgLock: OrgLock, storage: StorageService, registry: ExtensionRegistry, pluginInstaller: PluginInstaller, log: KernelLogger, txHost: TransactionHost,
50
+ orgLock: OrgLock, storage: StorageService, registry: ExtensionRegistry, pluginInstaller: PluginInstaller, scopeWriter: ScopeWriter, log: KernelLogger, txHost: TransactionHost,
49
51
  /** Why a plugin's extension cannot run (the `unavailable` state's reason). */
50
52
  availability: ExtensionAvailability,
51
53
  /** The effective config of an extension for the org: a wanted plugin whose config is not valid needs input. */
@@ -26,10 +26,12 @@ import { catalogHasIcon, findConnectorIn, orgTemplateView, readCatalogAgentTempl
26
26
  import { itemView, ownerOnlyFacts, versionUsable } from "./catalog-items.js";
27
27
  import { connectorTemplatesOn } from "./component-state.js";
28
28
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
29
+ import { orgSees, orgUsable } from "./org-intent.js";
29
30
  import { ownerOf, ownersOf } from "./ownership.js";
30
- import { PluginInstaller, uninstallPreviewHash, upsertOrgSwitch, } from "./plugin-install.js";
31
+ import { PluginInstaller, uninstallPreviewHash, } from "./plugin-install.js";
31
32
  import { schemaPathTitle } from "./schema-path.js";
32
- import { requestable, switchable, visibleTo, wantedOn } from "./scope.js";
33
+ import { requestable, switchable, visibleTo } from "./scope.js";
34
+ import { ScopeWriter } from "./scope-writer.js";
33
35
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
34
36
  const itemNotFound = () => new ApiError("catalog.item_not_found", "Catalog item not found");
35
37
  const notOffered = () => new ApiError("catalog.approval_required", "This plugin is not offered to this organization; an org admin can request access");
@@ -63,6 +65,7 @@ let OrgCatalogService = class OrgCatalogService {
63
65
  storage;
64
66
  registry;
65
67
  pluginInstaller;
68
+ scopeWriter;
66
69
  log;
67
70
  txHost;
68
71
  availability;
@@ -70,7 +73,7 @@ let OrgCatalogService = class OrgCatalogService {
70
73
  icons;
71
74
  constructor(kdb,
72
75
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
73
- orgLock, storage, registry, pluginInstaller, log, txHost,
76
+ orgLock, storage, registry, pluginInstaller, scopeWriter, log, txHost,
74
77
  /** Why a plugin's extension cannot run (the `unavailable` state's reason). */
75
78
  availability,
76
79
  /** The effective config of an extension for the org: a wanted plugin whose config is not valid needs input. */
@@ -80,6 +83,7 @@ let OrgCatalogService = class OrgCatalogService {
80
83
  this.storage = storage;
81
84
  this.registry = registry;
82
85
  this.pluginInstaller = pluginInstaller;
86
+ this.scopeWriter = scopeWriter;
83
87
  this.log = log;
84
88
  this.txHost = txHost;
85
89
  this.availability = availability;
@@ -97,37 +101,15 @@ let OrgCatalogService = class OrgCatalogService {
97
101
  */
98
102
  async list(orgId, accountId, itemId) {
99
103
  const isAdmin = await this.isOrgAdmin(orgId, accountId);
100
- let q = this.db
101
- .selectFrom("catalog_items")
102
- .selectAll()
103
- .where("deleted_at", "is", null)
104
- .orderBy("name")
105
- .orderBy("id");
106
- if (itemId !== undefined)
107
- q = q.where("id", "=", itemId);
108
- if (!isAdmin)
109
- q = q.where("disabled", "=", false);
110
- const all = await q.execute();
111
- const [listed, switches] = await Promise.all([
112
- this.db
113
- .selectFrom("catalog_item_scope_orgs")
114
- .select("item_id")
115
- .where("org_id", "=", orgId)
116
- .execute(),
117
- this.db
118
- .selectFrom("catalog_item_org_switches")
119
- .select(["item_id", "enabled"])
120
- .where("org_id", "=", orgId)
121
- .execute(),
122
- ]);
123
- const inList = new Set(listed.map((r) => r.item_id));
124
- // Hidden `named` items (not listed, not shown to other orgs) are absent; shown ones are
125
- // `not_offered`
126
- const items = all.filter((i) => visibleTo({ scope: i.builtin ? "all" : i.scope }, inList.has(i.id)) ||
127
- requestable(i, inList.has(i.id)));
104
+ const q = orgSees(this.db, orgId, isAdmin)
105
+ .selectAll("item")
106
+ .select("named.item_id as namedItemId")
107
+ .select((eb) => orgUsable(this.db, orgId, eb.ref("item.id")).as("usable"))
108
+ .orderBy("item.name")
109
+ .orderBy("item.id");
110
+ const items = await (itemId === undefined ? q : q.where("item.id", "=", itemId)).execute();
128
111
  if (items.length === 0)
129
112
  return [];
130
- const sw = new Map(switches.map((r) => [r.item_id, r.enabled]));
131
113
  const ids = items.map((i) => i.id);
132
114
  const [versions, pluginInstalls, requests] = await Promise.all([
133
115
  this.db
@@ -192,7 +174,6 @@ let OrgCatalogService = class OrgCatalogService {
192
174
  const latest = vs.find((v) => v.version === i.latest_version);
193
175
  const a = pluginInstalls.find((x) => x.item_id === i.id);
194
176
  const scope = i.builtin ? "all" : i.scope;
195
- const wanted = wantedOn(i, inList.has(i.id), sw.get(i.id) ?? null);
196
177
  let state;
197
178
  let reason;
198
179
  const extName = extensionOf(i);
@@ -206,27 +187,17 @@ let OrgCatalogService = class OrgCatalogService {
206
187
  state = "unavailable";
207
188
  reason = "plugin_disabled";
208
189
  }
209
- else if (requestable(i, inList.has(i.id)))
190
+ else if (!i.usable && requestable(i, i.namedItemId !== null))
210
191
  state = "not_offered";
211
- // not installed here and its extension cannot run: switching it on would fail (spec §14.2
212
- // problem 1); an installed one keeps its state (an org admin can still switch it off)
213
- else if (!a && why !== undefined) {
192
+ else if (why !== undefined) {
214
193
  state = "unavailable";
215
194
  reason = why.reason;
216
195
  }
217
- else if (a) {
196
+ else if (i.usable) {
218
197
  state = (await configInvalid()) ? "needs_config" : "on";
219
198
  }
220
- else if (i.builtin)
221
- state = "on";
222
- else if (!wanted)
199
+ else
223
200
  state = "off";
224
- else {
225
- // Wanted but not installed: the sync has not installed it (yet, or its install failed);
226
- // `off`, so an org admin can switch it on (the worker start retries it), unless its
227
- // extension's effective config is not valid here
228
- state = (await configInvalid()) ? "needs_config" : "off";
229
- }
230
201
  out.push({
231
202
  ...view,
232
203
  scope,
@@ -354,29 +325,7 @@ let OrgCatalogService = class OrgCatalogService {
354
325
  * (the super admin) every item.
355
326
  */
356
327
  async icon(itemId, isAdmin, orgId) {
357
- if (orgId === undefined)
358
- return readCatalogIcon(this.db, itemId, isAdmin);
359
- if (!UUID_RE.test(itemId))
360
- throw itemNotFound();
361
- // A hidden `named` item stays absent here too
362
- const item = await this.db
363
- .selectFrom("catalog_items")
364
- .select(["scope", "builtin", "shown_to_others", "owner_org_id", "shareable"])
365
- .where("id", "=", itemId)
366
- .where("deleted_at", "is", null)
367
- .executeTakeFirst();
368
- // Not requestable from outside its list (hidden, or held back by the share gate): only listed orgs
369
- if (item && !item.builtin && item.scope === "named" && !requestable(item, false)) {
370
- const listed = await this.db
371
- .selectFrom("catalog_item_scope_orgs")
372
- .select("item_id")
373
- .where("item_id", "=", itemId)
374
- .where("org_id", "=", orgId)
375
- .executeTakeFirst();
376
- if (listed === undefined)
377
- throw itemNotFound();
378
- }
379
- return readCatalogIcon(this.db, itemId, isAdmin);
328
+ return readCatalogIcon(this.db, itemId, isAdmin, orgId);
380
329
  }
381
330
  /** For the admin item detail: whether the latest version has an icon. */
382
331
  hasIcon(itemId) {
@@ -457,26 +406,15 @@ let OrgCatalogService = class OrgCatalogService {
457
406
  }
458
407
  /** The item when the org may see it (scope), else `catalog.item_not_found`. */
459
408
  async visibleItem(orgId, itemId) {
460
- const item = await this.db
461
- .selectFrom("catalog_items")
462
- .selectAll()
463
- .where("id", "=", itemId)
464
- .where("deleted_at", "is", null)
409
+ const item = await orgSees(this.db, orgId, true)
410
+ .selectAll("item")
411
+ .select("named.item_id as namedItemId")
412
+ .where("item.id", "=", itemId)
465
413
  .executeTakeFirst();
466
- if (!item)
414
+ if (item === undefined)
467
415
  throw itemNotFound();
468
- const listed = await this.db
469
- .selectFrom("catalog_item_scope_orgs")
470
- .select("item_id")
471
- .where("item_id", "=", itemId)
472
- .where("org_id", "=", orgId)
473
- .executeTakeFirst();
474
- if (!visibleTo({ scope: item.builtin ? "all" : item.scope }, listed !== undefined)) {
475
- // Shown to other orgs: the org sees it and may request access, but cannot switch it on
476
- if (requestable(item, false))
477
- throw notOffered();
478
- throw itemNotFound();
479
- }
416
+ if (requestable(item, item.namedItemId !== null))
417
+ throw notOffered();
480
418
  return item;
481
419
  }
482
420
  /** The org's live plugin install of the item, if any. */
@@ -602,7 +540,7 @@ let OrgCatalogService = class OrgCatalogService {
602
540
  throw itemNotFound();
603
541
  }
604
542
  }
605
- await upsertOrgSwitch(this.db, orgId, itemId, enabled, actor);
543
+ await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, enabled, actor);
606
544
  }
607
545
  /** The actor can install something in the org (forbidden otherwise), checked before item errors. */
608
546
  async assertCanInstall(orgId, actor) {
@@ -625,10 +563,11 @@ OrgCatalogService = __decorate([
625
563
  __param(2, Inject(StorageService)),
626
564
  __param(3, Inject(ExtensionRegistry)),
627
565
  __param(4, Inject(PluginInstaller)),
628
- __param(5, Inject(KERNEL_LOGGER)),
629
- __param(6, Inject(TransactionHost)),
630
- __param(7, Inject(ExtensionAvailability)),
631
- __param(8, Inject(EffectiveConfigs)),
632
- __param(9, Inject(PluginIcons))
566
+ __param(5, Inject(ScopeWriter)),
567
+ __param(6, Inject(KERNEL_LOGGER)),
568
+ __param(7, Inject(TransactionHost)),
569
+ __param(8, Inject(ExtensionAvailability)),
570
+ __param(9, Inject(EffectiveConfigs)),
571
+ __param(10, Inject(PluginIcons))
633
572
  ], OrgCatalogService);
634
573
  export { OrgCatalogService };
@@ -0,0 +1,43 @@
1
+ import { type Expression } from "kysely";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import type { PluginScope } from "./scope.js";
4
+ type Key = string | Expression<string>;
5
+ export declare const DEPENDENCY_DEPTH_LIMIT = 10;
6
+ export interface ProposedPluginScope {
7
+ itemId: string;
8
+ scope: PluginScope;
9
+ orgs: string[];
10
+ disabled: boolean;
11
+ resetComponents: boolean;
12
+ }
13
+ /** Shared ownership gate used before applying the subject's offer or intent. */
14
+ export declare function orgCatalogAdmits(db: KernelSchemaDb, orgId: Key, itemId: Key): import("kysely").RawBuilder<boolean>;
15
+ /** Catalog visibility for one org. A named association never widens the owner's share gate. */
16
+ export declare function orgSees(db: KernelSchemaDb, orgId: Key, isAdmin: boolean, view?: "catalog" | "offered"): import("kysely").SelectQueryBuilder<import("../db/kernel-schema.js").KernelDatabase & {
17
+ item: import("../db/kernel-schema.js").CatalogItemsTable;
18
+ } & {
19
+ named: import("kysely").Nullable<import("../db/kernel-schema.js").CatalogItemScopeOrgsTable>;
20
+ }, "item" | "named", Partial<Omit<unknown, never>>>;
21
+ /** Project a catalog item's direct intent, before considering dependency roots. */
22
+ export declare function orgPluginDirectIntent(db: KernelSchemaDb, orgId: Key, proposal?: ProposedPluginScope): import("kysely").SelectQueryBuilder<import("../db/kernel-schema.js").KernelDatabase & {
23
+ item: import("../db/kernel-schema.js").CatalogItemsTable;
24
+ } & {
25
+ named: import("kysely").Nullable<import("../db/kernel-schema.js").CatalogItemScopeOrgsTable>;
26
+ } & {
27
+ org_switch: import("kysely").Nullable<import("../db/kernel-schema.js").CatalogItemOrgSwitchesTable>;
28
+ }, "item" | "named" | "org_switch", Partial<Omit<unknown, never>> & {
29
+ directIntent: boolean;
30
+ }>;
31
+ /**
32
+ * Find directly enabled roots using the reverse index. Check the selected graph of each root
33
+ * for missing or ineligible dependencies. Deduplication by depth bounds repeated diamond paths
34
+ * and turns cycles and over-deep graphs into denials.
35
+ */
36
+ export declare function orgUsable(db: KernelSchemaDb, orgId: Key, itemId: string | Expression<string | null>, proposal?: ProposedPluginScope): import("kysely").RawBuilder<boolean>;
37
+ /** Setup attempts also surface failures for an authorized direct choice with a blocked dependency. */
38
+ export declare function orgPluginEffectIntent(db: KernelSchemaDb, orgId: Key, itemId: string): import("kysely").RawBuilder<boolean>;
39
+ /** Filter existing display rows with the same visibility projection as the catalog query. */
40
+ export declare function visibleCatalogRows<T extends {
41
+ id: string;
42
+ }>(db: KernelSchemaDb, rows: T[], orgId: string, isAdmin: boolean): Promise<T[]>;
43
+ export {};