@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
@@ -0,0 +1,184 @@
1
+ import { sql } from "kysely";
2
+ export const DEPENDENCY_DEPTH_LIMIT = 10;
3
+ function proposed(item, proposal, stored, next) {
4
+ return proposal === undefined
5
+ ? stored
6
+ : sql `CASE WHEN ${sql.ref(`${item}.id`)} = ${proposal.itemId} THEN ${next} ELSE ${stored} END`;
7
+ }
8
+ function orgCatalogItems(db, orgId, isAdmin) {
9
+ return db
10
+ .selectFrom("catalog_items as item")
11
+ .leftJoin("catalog_item_scope_orgs as named", (join) => join.onRef("named.item_id", "=", "item.id").on("named.org_id", "=", orgId))
12
+ .where("item.deleted_at", "is", null)
13
+ .where((eb) => eb.or([
14
+ eb("item.owner_org_id", "is", null),
15
+ eb("item.owner_org_id", "=", orgId),
16
+ eb.and([
17
+ eb("item.shareable", "=", true),
18
+ eb.exists(eb
19
+ .selectFrom("catalog_item_versions as visible_version")
20
+ .select("visible_version.item_id")
21
+ .whereRef("visible_version.item_id", "=", "item.id")
22
+ .whereRef("visible_version.version", "=", "item.latest_version")
23
+ .where("visible_version.applied_at", "is not", null)),
24
+ ]),
25
+ ]))
26
+ .$if(!isAdmin, (q) => q.where("item.disabled", "=", false));
27
+ }
28
+ /** Shared ownership gate used before applying the subject's offer or intent. */
29
+ export function orgCatalogAdmits(db, orgId, itemId) {
30
+ return sql `exists (${orgCatalogItems(db, orgId, true)
31
+ .select("item.id")
32
+ .where("item.id", "=", itemId)})`;
33
+ }
34
+ /** Catalog visibility for one org. A named association never widens the owner's share gate. */
35
+ export function orgSees(db, orgId, isAdmin, view = "catalog") {
36
+ return orgCatalogItems(db, orgId, isAdmin).where((eb) => eb.or([
37
+ eb("item.builtin", "=", true),
38
+ eb("item.scope", "!=", "named"),
39
+ eb("named.item_id", "is not", null),
40
+ ...(view === "catalog" ? [eb("item.shown_to_others", "=", true)] : []),
41
+ orgUsable(db, orgId, eb.ref("item.id")),
42
+ ]));
43
+ }
44
+ /** Project a catalog item's direct intent, before considering dependency roots. */
45
+ export function orgPluginDirectIntent(db, orgId, proposal) {
46
+ const scope = proposed("item", proposal, sql `item.scope`, sql `${proposal?.scope}::text`);
47
+ const enabled = proposed("item", proposal, sql `NOT item.disabled`, sql `${!proposal?.disabled}::boolean`);
48
+ const listed = proposed("item", proposal, sql `named.item_id IS NOT NULL`, sql `${orgId} = ANY(${proposal?.orgs}::text[])`);
49
+ return orgCatalogItems(db, orgId, true)
50
+ .leftJoin("catalog_item_org_switches as org_switch", (join) => join.onRef("org_switch.item_id", "=", "item.id").on("org_switch.org_id", "=", orgId))
51
+ .select(sql `(${enabled} AND (
52
+ (item.builtin AND item.owner_org_id IS NULL) OR
53
+ (${scope} = 'optional' AND org_switch.enabled IS TRUE) OR
54
+ ((${scope} = 'all' OR (${scope} = 'named' AND ${listed})) AND org_switch.enabled IS NOT FALSE)
55
+ ))`.as("directIntent"));
56
+ }
57
+ /** The live catalog and ownership gate for every item in the selected dependency graph. */
58
+ function graphAdmits(alias, orgId, proposal) {
59
+ const item = sql.table(alias);
60
+ const enabled = proposed(alias, proposal, sql `NOT ${item}.disabled`, sql `${!proposal?.disabled}::boolean`);
61
+ return sql `
62
+ ${item}.deleted_at IS NULL AND ${enabled}
63
+ AND (
64
+ ${item}.owner_org_id IS NULL OR ${item}.owner_org_id = ${orgId}
65
+ OR (${item}.shareable AND EXISTS (
66
+ SELECT 1 FROM capybara.catalog_item_versions AS published
67
+ WHERE published.item_id = ${item}.id
68
+ AND published.version = ${item}.latest_version
69
+ AND published.applied_at IS NOT NULL
70
+ ))
71
+ )`;
72
+ }
73
+ /** Declared dependencies always apply. An implied provider follows its template's own intent. */
74
+ function edgeApplies(orgId, proposal) {
75
+ const follows = proposed("parent", proposal, sql `template.scope_mode = 'follow'`, sql `${proposal?.resetComponents ?? false} OR template.scope_mode = 'follow'`);
76
+ return sql `(
77
+ edge.template_id = '' OR EXISTS (
78
+ SELECT 1
79
+ FROM capybara.platform_connector_templates AS template
80
+ LEFT JOIN capybara.component_org_switches AS choice
81
+ ON choice.kind = 'connector_template' AND choice.component_id = template.id
82
+ AND choice.org_id = ${orgId}
83
+ LEFT JOIN capybara.component_scope_orgs AS named
84
+ ON named.kind = 'connector_template' AND named.component_id = template.id
85
+ AND named.org_id = ${orgId}
86
+ WHERE template.id = edge.template_id
87
+ AND template.deleted_at IS NULL AND NOT template.disabled
88
+ AND (template.owner_org_id IS NULL OR template.owner_org_id = ${orgId} OR template.shareable)
89
+ AND CASE WHEN ${follows} THEN
90
+ CASE WHEN (NOT parent.builtin OR parent.owner_org_id IS NOT NULL)
91
+ AND template.file->>'defaultEnabled' = 'false'
92
+ THEN choice.enabled IS TRUE ELSE choice.enabled IS NOT FALSE END
93
+ WHEN template.scope = 'optional' THEN choice.enabled IS TRUE
94
+ ELSE (template.scope = 'all' OR named.component_id IS NOT NULL)
95
+ AND choice.enabled IS NOT FALSE
96
+ END
97
+ )
98
+ )`;
99
+ }
100
+ /** Implied providers must be offered to the org. Only a declared dependency can lift that gate. */
101
+ function edgeAdmitsTarget(orgId, proposal) {
102
+ const scope = proposed("dep", proposal, sql `dep.scope`, sql `${proposal?.scope}::text`);
103
+ const listed = proposed("dep", proposal, sql `EXISTS (
104
+ SELECT 1 FROM capybara.catalog_item_scope_orgs AS offer
105
+ WHERE offer.item_id = dep.id AND offer.org_id = ${orgId}
106
+ )`, sql `${orgId} = ANY(${proposal?.orgs}::text[])`);
107
+ return sql `(
108
+ edge.template_id = '' OR ${scope} <> 'named' OR dep.builtin OR ${listed}
109
+ )`;
110
+ }
111
+ /**
112
+ * Find directly enabled roots using the reverse index. Check the selected graph of each root
113
+ * for missing or ineligible dependencies. Deduplication by depth bounds repeated diamond paths
114
+ * and turns cycles and over-deep graphs into denials.
115
+ */
116
+ export function orgUsable(db, orgId, itemId, proposal) {
117
+ const direct = orgPluginDirectIntent(db, orgId, proposal)
118
+ .where("item.id", "=", sql `reach.id`)
119
+ .limit(1);
120
+ return sql `exists (
121
+ WITH RECURSIVE reach(id, version) AS (
122
+ SELECT target.id, coalesce(target.platform_synced_version, target.latest_version)
123
+ FROM capybara.catalog_items AS target
124
+ WHERE target.id = ${itemId} AND ${graphAdmits("target", orgId, proposal)}
125
+ AND EXISTS (SELECT 1 FROM capybara.orgs AS live_org WHERE live_org.id = ${orgId} AND live_org.deleted_at IS NULL)
126
+ UNION
127
+ SELECT parent.id, edge.item_version
128
+ FROM reach
129
+ JOIN LATERAL (
130
+ SELECT item_id, item_version, template_id
131
+ FROM capybara.catalog_dependency_edges
132
+ WHERE dependency_item_id = reach.id AND dependency_version = reach.version
133
+ OFFSET 0
134
+ ) AS edge ON true
135
+ JOIN capybara.catalog_items AS parent ON parent.id = edge.item_id
136
+ WHERE ${graphAdmits("parent", orgId, proposal)}
137
+ AND edge.item_version = coalesce(parent.platform_synced_version, parent.latest_version)
138
+ AND ${edgeApplies(orgId, proposal)}
139
+ ), roots AS (
140
+ SELECT reach.id, reach.version FROM reach
141
+ JOIN LATERAL (${direct}) AS root ON root."directIntent"
142
+ ), requirements(root_id, id, version, depth, blocked) AS (
143
+ SELECT roots.id, roots.id, roots.version, 0, false FROM roots
144
+ UNION
145
+ SELECT requirements.root_id, dep.id, edge.dependency_version, requirements.depth + 1,
146
+ dep.id IS NULL OR requirements.depth >= ${DEPENDENCY_DEPTH_LIMIT}
147
+ FROM requirements
148
+ JOIN LATERAL (
149
+ SELECT item_id, template_id, dependency_item_id, dependency_version
150
+ FROM capybara.catalog_dependency_edges
151
+ WHERE item_id = requirements.id AND item_version = requirements.version
152
+ OFFSET 0
153
+ ) AS edge ON true
154
+ JOIN capybara.catalog_items AS parent ON parent.id = edge.item_id
155
+ LEFT JOIN capybara.catalog_items AS dep
156
+ ON dep.id = edge.dependency_item_id
157
+ AND coalesce(dep.platform_synced_version, dep.latest_version) = edge.dependency_version
158
+ AND ${graphAdmits("dep", orgId, proposal)} AND ${edgeAdmitsTarget(orgId, proposal)}
159
+ WHERE NOT requirements.blocked AND ${edgeApplies(orgId, proposal)}
160
+ )
161
+ SELECT 1 FROM roots
162
+ WHERE NOT EXISTS (
163
+ SELECT 1 FROM requirements WHERE requirements.root_id = roots.id AND requirements.blocked
164
+ )
165
+ )`;
166
+ }
167
+ /** Setup attempts also surface failures for an authorized direct choice with a blocked dependency. */
168
+ export function orgPluginEffectIntent(db, orgId, itemId) {
169
+ const direct = orgPluginDirectIntent(db, orgId).where("item.id", "=", itemId);
170
+ return sql `(
171
+ coalesce((${direct}), false) OR ${orgUsable(db, orgId, itemId)}
172
+ )`;
173
+ }
174
+ /** Filter existing display rows with the same visibility projection as the catalog query. */
175
+ export async function visibleCatalogRows(db, rows, orgId, isAdmin) {
176
+ if (rows.length === 0)
177
+ return [];
178
+ const visible = await orgSees(db, orgId, isAdmin)
179
+ .select("item.id")
180
+ .where("item.id", "in", [...new Set(rows.map((row) => row.id))])
181
+ .execute();
182
+ const ids = new Set(visible.map((row) => row.id));
183
+ return rows.filter((row) => ids.has(row.id));
184
+ }
@@ -131,7 +131,7 @@ export declare class OwnedItems {
131
131
  * `named` = the orgs using it, ruling P3-39; an `optional` item stays `optional`, ruling P3-40:
132
132
  * it passed the share gate already, so every org could see it, and the former owner is then an
133
133
  * ordinary org that may switch it on again), written
134
- * directly rather than through the guarded scope writer (ruling P3-27); platform notice
134
+ * using the scope writer under the ownership transaction (ruling P3-27); platform notice
135
135
  * `ownership_transferred`, audit `catalog.ownership_transferred`, the scope sync owed with it
136
136
  * (it uninstalls the former owner's install). Otherwise -> `removed`: the soft delete of
137
137
  * `catalog.remove` ({@link CatalogService.removeIn}); an owner delete
@@ -35,6 +35,7 @@ import { agentsUsing, COMPONENT_KINDS, componentOn, listedIn, loadComponents, lo
35
35
  import { orgsUsing } from "./ownership.js";
36
36
  import { PluginInstaller } from "./plugin-install.js";
37
37
  import { ScopeStillWanted } from "./scope-state.js";
38
+ import { writeScope } from "./scope-writer.js";
38
39
  import { narrowComponentOnUnshare } from "./unshare.js";
39
40
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
40
41
  const notFound = () => new ApiError("catalog.item_not_found", "Catalog item not found");
@@ -375,7 +376,7 @@ let OwnedItems = class OwnedItems {
375
376
  * `named` = the orgs using it, ruling P3-39; an `optional` item stays `optional`, ruling P3-40:
376
377
  * it passed the share gate already, so every org could see it, and the former owner is then an
377
378
  * ordinary org that may switch it on again), written
378
- * directly rather than through the guarded scope writer (ruling P3-27); platform notice
379
+ * using the scope writer under the ownership transaction (ruling P3-27); platform notice
379
380
  * `ownership_transferred`, audit `catalog.ownership_transferred`, the scope sync owed with it
380
381
  * (it uninstalls the former owner's install). Otherwise -> `removed`: the soft delete of
381
382
  * `catalog.remove` ({@link CatalogService.removeIn}); an owner delete
@@ -422,7 +423,6 @@ let OwnedItems = class OwnedItems {
422
423
  .set({
423
424
  owner_org_id: null,
424
425
  ...(!item.shareable && { shown_to_others: false }),
425
- ...(item.scope === "all" && { scope: "named" }),
426
426
  updated_at: now,
427
427
  })
428
428
  .where("id", "=", item.id)
@@ -430,11 +430,12 @@ let OwnedItems = class OwnedItems {
430
430
  if (item.scope === "all") {
431
431
  // org-filter: deployment-wide rewrite of the transferred item's named list.
432
432
  await asPlatform("replace the transferred plugin's named scope", async () => {
433
- await t.deleteFrom("catalog_item_scope_orgs").where("item_id", "=", item.id).execute();
434
- await t
435
- .insertInto("catalog_item_scope_orgs")
436
- .values(others.map((o) => ({ item_id: item.id, org_id: o.id })))
437
- .execute();
433
+ await writeScope(t, {
434
+ kind: "plugin",
435
+ id: item.id,
436
+ scope: "named",
437
+ orgs: others.map((o) => o.id),
438
+ });
438
439
  });
439
440
  }
440
441
  else {
@@ -470,11 +471,6 @@ let OwnedItems = class OwnedItems {
470
471
  }
471
472
  }
472
473
  for (const { c, orgs } of narrow) {
473
- await t
474
- .updateTable(TABLE_OF[c.kind])
475
- .set({ scope: "named", updated_at: now })
476
- .where("id", "=", c.id)
477
- .execute();
478
474
  await this.replaceComponentScope(c.kind, c.id, orgs);
479
475
  await audit(t, {
480
476
  actorAccountId: actor,
@@ -609,9 +605,6 @@ let OwnedItems = class OwnedItems {
609
605
  .set({
610
606
  owner_org_id: null,
611
607
  ...(!c.shareable && { shown_to_others: false }),
612
- ...(narrowTo !== null && {
613
- scope: "named",
614
- }),
615
608
  updated_at: now,
616
609
  })
617
610
  .where("id", "=", id)
@@ -673,20 +666,7 @@ let OwnedItems = class OwnedItems {
673
666
  /** Replaces a transferred component's named list in the transfer's transaction. */
674
667
  async replaceComponentScope(kind, id, orgs) {
675
668
  // org-filter: deployment-wide rewrite of the transferred component's named list.
676
- await asPlatform("replace the transferred component's named scope", async () => {
677
- const t = this.db;
678
- await t
679
- .deleteFrom("component_scope_orgs")
680
- .where("kind", "=", kind)
681
- .where("component_id", "=", id)
682
- .execute();
683
- if (orgs.length > 0) {
684
- await t
685
- .insertInto("component_scope_orgs")
686
- .values(orgs.map((org_id) => ({ kind, component_id: id, org_id })))
687
- .execute();
688
- }
689
- });
669
+ await asPlatform("replace the transferred component's named scope", () => writeScope(this.db, { kind, id, scopeMode: "own", scope: "named", orgs }));
690
670
  }
691
671
  /**
692
672
  * The owner org's live install of a removed plugin, uninstalled in the caller's transaction
@@ -1,6 +1,6 @@
1
1
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
2
  import { ApiError } from "../errors.js";
3
- import { type PluginScope } from "./scope.js";
3
+ import type { PluginScope } from "./scope.js";
4
4
  /** Who owns an item or component: the platform, or one org (by id and name, deleted orgs too). */
5
5
  export type Owner = {
6
6
  kind: "platform";
@@ -121,8 +121,7 @@ export type OwnedRef = {
121
121
  id: string;
122
122
  };
123
123
  /**
124
- * The live orgs an item is on in (ruling P3-18: listed and not switched off for `named`, switched
125
- * on for `optional`, any live org for `all`; a component by {@link componentOn}), minus
124
+ * The live orgs where the item is usable, minus
126
125
  * `except` (usually the owner), by name. One definition for the update notices and the
127
126
  * "used by another org" check of deletes. An item that is gone or disabled is on nowhere.
128
127
  */
@@ -7,7 +7,7 @@ import { sql } from "kysely";
7
7
  import { ApiError } from "../errors.js";
8
8
  import { asPlatform } from "../infra/database/org-scope.js";
9
9
  import { componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "./component-state.js";
10
- import { wantedOn } from "./scope.js";
10
+ import { orgUsable } from "./org-intent.js";
11
11
  export const PLATFORM_OWNER = { kind: "platform" };
12
12
  /**
13
13
  * The share gate (P3-1): a platform item, or an org-owned one its owner made shareable. Closed:
@@ -217,45 +217,27 @@ export function ownerOf(ownerOrgId, owners) {
217
217
  return owners.get(ownerOrgId) ?? { kind: "org", orgId: ownerOrgId, name: ownerOrgId };
218
218
  }
219
219
  /**
220
- * The live orgs an item is on in (ruling P3-18: listed and not switched off for `named`, switched
221
- * on for `optional`, any live org for `all`; a component by {@link componentOn}), minus
220
+ * The live orgs where the item is usable, minus
222
221
  * `except` (usually the owner), by name. One definition for the update notices and the
223
222
  * "used by another org" check of deletes. An item that is gone or disabled is on nowhere.
224
223
  */
225
224
  export function orgsUsing(db, ref, opts = {}) {
226
225
  // org-filter: deployment-wide subscriber lookup, keyed by the shared item id.
227
226
  return asPlatform("find the live organizations using this shared item", async () => {
228
- const orgs = await db
227
+ let query = db
229
228
  .selectFrom("orgs")
230
229
  .select(["id", "name"])
231
230
  .where("deleted_at", "is", null)
232
231
  .orderBy("name")
233
- .orderBy("id")
234
- .execute();
235
- const others = orgs.filter((o) => o.id !== opts.except);
236
- if (others.length === 0)
237
- return [];
232
+ .orderBy("id");
233
+ if (opts.except != null)
234
+ query = query.where("id", "!=", opts.except);
238
235
  if (ref.kind === "plugin") {
239
- const item = await db
240
- .selectFrom("catalog_items")
241
- .select(["scope", "builtin", "disabled"])
242
- .where("id", "=", ref.id)
243
- .where("deleted_at", "is", null)
244
- .executeTakeFirst();
245
- if (!item)
246
- return [];
247
- const listed = new Set((await db
248
- .selectFrom("catalog_item_scope_orgs")
249
- .select("org_id")
250
- .where("item_id", "=", ref.id)
251
- .execute()).map((r) => r.org_id));
252
- const switches = new Map((await db
253
- .selectFrom("catalog_item_org_switches")
254
- .select(["org_id", "enabled"])
255
- .where("item_id", "=", ref.id)
256
- .execute()).map((r) => [r.org_id, r.enabled]));
257
- return others.filter((o) => wantedOn(item, listed.has(o.id), switches.get(o.id) ?? null));
236
+ return query.where(({ ref: column }) => orgUsable(db, column("orgs.id"), ref.id)).execute();
258
237
  }
238
+ const others = await query.execute();
239
+ if (others.length === 0)
240
+ return [];
259
241
  const kind = ref.kind;
260
242
  const [c] = await loadComponents(db, kind, { ids: [ref.id] });
261
243
  if (!c)
@@ -180,6 +180,7 @@ export declare class PlatformComponents {
180
180
  private files;
181
181
  constructor(kdb: KernelDb, storage: StorageService, itemLock: CatalogItemLock, log: KernelLogger, txHost: TransactionHost);
182
182
  private get db();
183
+ initializeDependencyEdges(): Promise<void>;
183
184
  /** CLI only (see `PluginImport.useCliStorage`): files go to the object store the CLI set up. */
184
185
  useCliStorage(storage: PrefixedStorage): void;
185
186
  /**
@@ -194,7 +195,8 @@ export declare class PlatformComponents {
194
195
  prepareImport(source: SyncSource): Promise<PreparedSync>;
195
196
  /**
196
197
  * The second phase: writes the prepared rows in the caller's transaction and records
197
- * `platform_synced_version`. A component changed since the plan -> {@link PlanStale} (the caller
198
+ * `platform_synced_version`. The caller refreshes edges after all version and component changes.
199
+ * A component changed since the plan -> {@link PlanStale} (the caller
198
200
  * prepares again).
199
201
  */
200
202
  applySyncIn(p: PreparedSync): Promise<PlatformSyncResult>;
@@ -28,6 +28,7 @@ import { StorageService } from "../storage/storage.service.js";
28
28
  import { canonicalJson } from "../tools/canonical-json.js";
29
29
  import { readCatalogAgentTemplates, readCatalogFiles, readCatalogTemplates, readCatalogThemes, skillFilesDigest, skillOf, themeAssetsDigest, } from "./catalog-content.js";
30
30
  import { putCatalogFiles } from "./catalog-items.js";
31
+ import { initializeCatalogDependencyEdges } from "./dependency-edges.js";
31
32
  import { CatalogItemLock } from "./locks.js";
32
33
  import { relinkDeletedItemConnectors } from "./plugin-connectors.js";
33
34
  /** The prefix (in `deployment/`) of a platform skill version's files. */
@@ -78,6 +79,9 @@ let PlatformComponents = class PlatformComponents {
78
79
  get db() {
79
80
  return this.kdb.db;
80
81
  }
82
+ async initializeDependencyEdges() {
83
+ await initializeCatalogDependencyEdges(this.db);
84
+ }
81
85
  /** CLI only (see `PluginImport.useCliStorage`): files go to the object store the CLI set up. */
82
86
  useCliStorage(storage) {
83
87
  this.files = storage;
@@ -109,7 +113,8 @@ let PlatformComponents = class PlatformComponents {
109
113
  }
110
114
  /**
111
115
  * The second phase: writes the prepared rows in the caller's transaction and records
112
- * `platform_synced_version`. A component changed since the plan -> {@link PlanStale} (the caller
116
+ * `platform_synced_version`. The caller refreshes edges after all version and component changes.
117
+ * A component changed since the plan -> {@link PlanStale} (the caller
113
118
  * prepares again).
114
119
  */
115
120
  async applySyncIn(p) {
@@ -828,6 +833,9 @@ let PlatformComponents = class PlatformComponents {
828
833
  return out;
829
834
  }
830
835
  };
836
+ __decorate([
837
+ Transactional()
838
+ ], PlatformComponents.prototype, "initializeDependencyEdges", null);
831
839
  __decorate([
832
840
  Transactional({ propagation: "mandatory" })
833
841
  ], PlatformComponents.prototype, "applySyncIn", null);
@@ -50,6 +50,7 @@ import { CLAUDE_PLUGIN_FILE, claudeContentDigest, } from "./claude/manifest.js";
50
50
  import { CLAUDE_MCP_CONNECTOR } from "./claude/mcp.js";
51
51
  import { item as reportItem, sortItems, } from "./claude/report.js";
52
52
  import { isClaudePluginTree, translateClaudePlugin } from "./claude/translate.js";
53
+ import { refreshCatalogDependencyEdges } from "./dependency-edges.js";
53
54
  import { CatalogItemLock } from "./locks.js";
54
55
  import { requireMarketplacePublisher } from "./marketplace-fetch.js";
55
56
  import { assertNameFree, assertPackageFree, assertShareable, packageOwner, shareGate, usableBy, } from "./ownership.js";
@@ -60,6 +61,7 @@ import { hasImportRequests, importRequestOf, resolveImportRequests } from "./req
60
61
  import { assertNameNotReserved } from "./reserved-names.js";
61
62
  import { oweScopeItem } from "./scope-jobs.js";
62
63
  import { addScopeOrg } from "./scope-orgs.js";
64
+ import { writeScope } from "./scope-writer.js";
63
65
  import { templateDescriptionText } from "./template-description.js";
64
66
  import { maxSatisfying, satisfiesRange } from "./versions.js";
65
67
  /**
@@ -942,7 +944,7 @@ let PluginImport = class PluginImport {
942
944
  previous,
943
945
  };
944
946
  }
945
- const { id: itemId, created } = await writeCatalogVersion(t, {
947
+ const { id: itemId, created, selectedVersionChanged, } = await writeCatalogVersion(t, {
946
948
  // an org's version becomes its latest only when applied or confirmed (P3-34)
947
949
  ...(owner !== undefined && { keepLatest: true }),
948
950
  actor,
@@ -987,26 +989,18 @@ let PluginImport = class PluginImport {
987
989
  // A new item gets the scope chosen in the review; a new version keeps the item's scope, its
988
990
  // org list and its scope version (prepare reuses the live item's id, so the id cannot tell)
989
991
  if (created) {
990
- await t
991
- .updateTable("catalog_items")
992
- .set({
993
- scope: scope.scope,
994
- // an org upload: the org owns it, nobody else sees it until shared and shown (P3-16)
995
- ...(owner !== undefined && {
992
+ if (owner !== undefined) {
993
+ await t
994
+ .updateTable("catalog_items")
995
+ .set({
996
996
  owner_org_id: owner.orgId,
997
997
  shareable: scope.shareable === true,
998
998
  shown_to_others: false,
999
- }),
1000
- })
1001
- .where("id", "=", itemId)
1002
- .execute();
1003
- if (scope.scope === "named" && scope.orgs.length > 0) {
1004
- await t
1005
- .insertInto("catalog_item_scope_orgs")
1006
- .values(scope.orgs.map((org_id) => ({ item_id: itemId, org_id })))
1007
- .onConflict((oc) => oc.doNothing())
999
+ })
1000
+ .where("id", "=", itemId)
1008
1001
  .execute();
1009
1002
  }
1003
+ await writeScope(t, { kind: "plugin", id: itemId, scope: scope.scope, orgs: scope.orgs });
1010
1004
  }
1011
1005
  // The org requests this staging answers resolve with the confirm; on an item that existed
1012
1006
  // already (imported meanwhile) a `named` scope gains their orgs. An org-owned item held back by
@@ -1058,6 +1052,8 @@ let PluginImport = class PluginImport {
1058
1052
  await oweScopeItem(this.outbox, t, itemId);
1059
1053
  }
1060
1054
  }
1055
+ if (selectedVersionChanged)
1056
+ await refreshCatalogDependencyEdges(t);
1061
1057
  return {
1062
1058
  itemId,
1063
1059
  created,
@@ -16,6 +16,7 @@ import type { ConnectorDetail, CreateConnectorInput, ToolIssue } from "../tools/
16
16
  import { ConnectorsService } from "../tools/connectors.service.js";
17
17
  import { type CatalogVersionFiles, type TemplateDeps } from "./catalog-content.js";
18
18
  import { type DefinitionRefs, type TemplateSwitch } from "./component-state.js";
19
+ import { ScopeWriter } from "./scope-writer.js";
19
20
  /**
20
21
  * What an org fills in for one more connector from a connector template (C30; `POST …/
21
22
  * connector-templates/:templateId/connectors`). Installs and enables take none (plugin pages spec
@@ -103,8 +104,6 @@ export interface UninstallPreview {
103
104
  }
104
105
  /** The confirm hash of an uninstall preview: sha256 over its sorted JSON (the scheme of `diffHash`). */
105
106
  export declare function uninstallPreviewHash(p: UninstallPreview): string;
106
- /** Upserts the org's switch row of an item in the caller's transaction (the org lock is held). */
107
- export declare function upsertOrgSwitch(db: KernelSchemaDb, orgId: string, itemId: string, enabled: boolean, actor: string | null): Promise<void>;
108
107
  /** A plugin install in an org (`GET /orgs/:orgId/plugin-installs`). */
109
108
  export interface PluginInstallView {
110
109
  id: string;
@@ -146,7 +145,6 @@ export interface ResolvedDependency {
146
145
  version: string;
147
146
  }
148
147
  /** How deep plugin dependencies may nest (the root plugin's dependencies are level 1). */
149
- export declare const DEPENDENCY_DEPTH_LIMIT = 10;
150
148
  /** A component as an install records it (see `plugin_install_components`). */
151
149
  export interface Component {
152
150
  kind: ComponentKind;
@@ -269,6 +267,7 @@ export declare class PluginInstaller {
269
267
  private readonly registry;
270
268
  private readonly skills;
271
269
  private readonly orgConfigs;
270
+ private readonly scopeWriter;
272
271
  private readonly config;
273
272
  /** Org connectors: installs create, upgrade and remove them. */
274
273
  private readonly connectors;
@@ -280,7 +279,7 @@ export declare class PluginInstaller {
280
279
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
281
280
  orgLock: OrgLock, storage: StorageService,
282
281
  /** The loaded extensions and connectors of this replica (the extension registry). */
283
- registry: ExtensionRegistry, skills: SkillsService, orgConfigs: OrgExtensionConfigs, config: KernelConfigService,
282
+ registry: ExtensionRegistry, skills: SkillsService, orgConfigs: OrgExtensionConfigs, scopeWriter: ScopeWriter, config: KernelConfigService,
284
283
  /** Org connectors: installs create, upgrade and remove them. */
285
284
  connectors: ConnectorsService, log: KernelLogger,
286
285
  /** Owes the template connector ensure of an install's commit (`markInstalled`). */