@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
@@ -2,13 +2,12 @@ import { pluginDescription } from "@capybara-hq/plugin-sdk";
2
2
  import { sql } from "kysely";
3
3
  import semver from "semver";
4
4
  import { ApiError } from "../errors.js";
5
- import { enabledExtensionsByOrg } from "../extensions/enabled.js";
6
5
  import { blockingKeys } from "../extensions/permission-set.js";
7
6
  import { audit } from "../identity/audit.js";
8
7
  import { endpointCredentialIssues } from "../tools/endpoint.js";
9
8
  import { gitLocationIdentity } from "./git-source.js";
10
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
11
9
  import { entryCompatible, entryContentChanged, entryDeprecated, sourceEffective, unimportable, } from "./marketplaces.service.js";
10
+ import { orgUsable } from "./org-intent.js";
12
11
  import { ownerOf, ownersOf, PLATFORM_OWNER, packageOwner } from "./ownership.js";
13
12
  import { schemaHasPath } from "./schema-path.js";
14
13
  import { compareVersions, newestFirst, sameRelease, withBuild } from "./versions.js";
@@ -97,7 +96,7 @@ export function inAuthorOrder(manifest, order) {
97
96
  async function liveItem(db, name) {
98
97
  const item = await db
99
98
  .selectFrom("catalog_items")
100
- .select(["id", "package_name", "latest_version", "marketplace_id"])
99
+ .select(["id", "package_name", "latest_version", "platform_synced_version", "marketplace_id"])
101
100
  .where("name", "=", name)
102
101
  .where("deleted_at", "is", null)
103
102
  .executeTakeFirst();
@@ -236,7 +235,8 @@ export async function precheckCatalogImport(db, name, p) {
236
235
  * the release with the same content; `version` not taken meanwhile), creates the item when there is
237
236
  * none or adds the version (latest and display fields change only for a newer version, a version
238
237
  * equal but for build metadata being newer as the later import), and writes the version row (with
239
- * its content digest) and the `catalog.imported` audit. Returns the item id.
238
+ * its content digest) and the `catalog.imported` audit. The caller refreshes dependency edges if
239
+ * the selected version changed, after applying the new item's components.
240
240
  */
241
241
  export async function writeCatalogVersion(db, w) {
242
242
  const t = db;
@@ -244,6 +244,7 @@ export async function writeCatalogVersion(db, w) {
244
244
  const live = await liveItem(t, name);
245
245
  let id;
246
246
  const created = live === undefined;
247
+ let selectedVersionChanged = created;
247
248
  if (live) {
248
249
  id = live.id;
249
250
  assertSameSource(live, w.packageName, sourceIdentity(w.source.detail, w.marketplaceId));
@@ -257,6 +258,7 @@ export async function writeCatalogVersion(db, w) {
257
258
  if (existing.some((v) => v.version === version))
258
259
  throw versionExists(version, false, true);
259
260
  const newer = w.keepLatest !== true && compareVersions(version, live.latest_version) >= 0;
261
+ selectedVersionChanged = newer && live.platform_synced_version === null;
260
262
  await t
261
263
  .updateTable("catalog_items")
262
264
  .set({
@@ -331,7 +333,7 @@ export async function writeCatalogVersion(db, w) {
331
333
  ...w.auditDetail,
332
334
  },
333
335
  });
334
- return { id, created };
336
+ return { id, created, selectedVersionChanged };
335
337
  }
336
338
  /**
337
339
  * Records that `version` of the item was applied (ruling P3-52), in the caller's
@@ -447,34 +449,20 @@ export async function marketplaceLatest(db, config, items, versions) {
447
449
  }
448
450
  return out;
449
451
  }
450
- /** Org install counts per item (see {@link CatalogItemView.installs}). */
451
- export async function countInstalls(db, items, versions) {
452
- const orgs = new Map(items.map((i) => [i.id, new Set()]));
453
- // org-filter: the platform catalog's install count per item (super admin's catalog view): it
454
- // counts the orgs on purpose and returns no org row
455
- const installed = await db
456
- .selectFrom("plugin_installs")
457
- .select(["item_id", "org_id"])
458
- .where("item_id", "in", items.map((i) => i.id))
459
- .where("status", "=", "installed")
452
+ /** How many organizations have applied setup effects for each item. */
453
+ export async function countInstalls(db, itemIds) {
454
+ if (itemIds.length === 0)
455
+ return new Map();
456
+ const applied = await db
457
+ .selectFrom("plugin_installs as install")
458
+ .innerJoin("orgs as org", "org.id", "install.org_id")
459
+ .select(["install.item_id", (eb) => eb.fn.count("install.org_id").distinct().as("n")])
460
+ .where("install.item_id", "in", itemIds)
461
+ .where("install.status", "=", "installed")
462
+ .where("org.deleted_at", "is", null)
463
+ .groupBy("install.item_id")
460
464
  .execute();
461
- for (const r of installed)
462
- orgs.get(r.item_id)?.add(r.org_id);
463
- const withExtension = items.filter((i) => (versions.get(i.id) ?? []).find((v) => v.version === i.latest_version)?.extension_sha256 !=
464
- null);
465
- if (withExtension.length > 0) {
466
- const enabled = await db
467
- .selectFrom(enabledExtensionsByOrg(db).as("en"))
468
- .select(["en.plugin", "en.org_id"])
469
- .where("en.plugin", "in", withExtension.map((p) => p.name))
470
- .execute();
471
- for (const i of withExtension) {
472
- for (const r of enabled)
473
- if (r.plugin === i.name)
474
- orgs.get(i.id)?.add(r.org_id);
475
- }
476
- }
477
- return new Map([...orgs].map(([id, set]) => [id, set.size]));
465
+ return new Map(applied.map((row) => [row.item_id, Number(row.n)]));
478
466
  }
479
467
  /**
480
468
  * Every id is a live org (`validation_failed` naming the unknown ones otherwise): the orgs of a
@@ -580,13 +568,13 @@ export async function itemScopeFacts(db, items, confirmations) {
580
568
  for (const r of listed)
581
569
  out.get(r.item_id)?.scopeOrgs.push(r.org_id);
582
570
  const live = await db
583
- .selectFrom("plugin_installs as a")
584
- .innerJoin("orgs as o", "o.id", "a.org_id")
585
- .select(["a.item_id", (eb) => eb.fn.count("a.org_id").distinct().as("n")])
586
- .where("a.item_id", "in", ids)
587
- .where("a.status", "in", [...LIVE_INSTALL_STATUSES])
588
- .where("o.deleted_at", "is", null)
589
- .groupBy("a.item_id")
571
+ .selectFrom("catalog_items as item")
572
+ .crossJoin("orgs as org")
573
+ .select(["item.id as item_id", (eb) => eb.fn.countAll().as("n")])
574
+ .where("item.id", "in", ids)
575
+ .where("org.deleted_at", "is", null)
576
+ .where(({ ref }) => orgUsable(db, ref("org.id"), ref("item.id")))
577
+ .groupBy("item.id")
590
578
  .execute();
591
579
  for (const r of live) {
592
580
  const f = out.get(r.item_id);
@@ -611,18 +599,6 @@ export async function itemScopeFacts(db, items, confirmations) {
611
599
  f.offCount = Number(r.n);
612
600
  }
613
601
  }
614
- if (items.some((i) => i.builtin)) {
615
- const orgs = await db
616
- .selectFrom("orgs")
617
- .select((eb) => eb.fn.countAll().as("n"))
618
- .where("deleted_at", "is", null)
619
- .executeTakeFirstOrThrow();
620
- for (const i of items) {
621
- const f = out.get(i.id);
622
- if (i.builtin && f)
623
- f.enabledOrgs = Number(orgs.n);
624
- }
625
- }
626
602
  return out;
627
603
  }
628
604
  /** The `zh` text of a stored manifest's description; null without one (or an unreadable manifest). */
@@ -9,8 +9,9 @@ import { type ActorOpts, type CatalogItemView, CatalogService } from "./catalog.
9
9
  import { type ComponentKind } from "./component-state.js";
10
10
  import { type PluginConfirmResult, PluginImport } from "./plugin-import.js";
11
11
  import { PluginInstaller } from "./plugin-install.js";
12
- import { type PluginScope } from "./scope.js";
12
+ import type { PluginScope } from "./scope.js";
13
13
  import { PluginScopeSync } from "./scope-sync.js";
14
+ import { ScopeWriter } from "./scope-writer.js";
14
15
  /**
15
16
  * What a scope change or a deployment-level disable would take away (spec §5 rule 8): the orgs
16
17
  * that have the plugin on now (a live install) and would no longer want it, each with its agents
@@ -89,6 +90,7 @@ export declare function conflictsError(conflicts: ScopePreview["conflicts"]): Ap
89
90
  export declare class CatalogScopeService {
90
91
  private readonly kdb;
91
92
  private readonly adminLock;
93
+ private readonly scopeWriter;
92
94
  private readonly catalog;
93
95
  private readonly pluginImport;
94
96
  private readonly installer;
@@ -96,7 +98,7 @@ export declare class CatalogScopeService {
96
98
  private readonly ops;
97
99
  private readonly sync;
98
100
  readonly txHost: TransactionHost;
99
- constructor(kdb: KernelDb, adminLock: SuperAdminLock, catalog: CatalogService, pluginImport: PluginImport, installer: PluginInstaller, extensions: ExtensionAdmin, ops: ExtensionAdminOps, sync: PluginScopeSync, txHost: TransactionHost);
101
+ constructor(kdb: KernelDb, adminLock: SuperAdminLock, scopeWriter: ScopeWriter, catalog: CatalogService, pluginImport: PluginImport, installer: PluginInstaller, extensions: ExtensionAdmin, ops: ExtensionAdminOps, sync: PluginScopeSync, txHost: TransactionHost);
100
102
  private get db();
101
103
  /**
102
104
  * Confirms a staged import ({@link PluginImport.confirm}: installs and enables the extension,
@@ -25,17 +25,17 @@ import { assertOrgsExist } from "./catalog-items.js";
25
25
  import { nameConflictError } from "./component-scope.service.js";
26
26
  import { agentsUsing, COMPONENT_KINDS, componentOffered, componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, skillNameClashes, switchOf, themeIdClashes, } from "./component-state.js";
27
27
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
28
+ import { orgUsable } from "./org-intent.js";
28
29
  import { assertOwnerListed, assertShareable, assertShareableTarget, newlySharedWith, } from "./ownership.js";
29
30
  import { PluginImport } from "./plugin-import.js";
30
31
  import { PluginInstaller } from "./plugin-install.js";
31
- import { wantedOn } from "./scope.js";
32
32
  import { addScopeOrg } from "./scope-orgs.js";
33
33
  import { PluginScopeSync } from "./scope-sync.js";
34
+ import { ScopeWriter } from "./scope-writer.js";
34
35
  import { narrowComponentOnUnshare, narrowItemOnUnshare } from "./unshare.js";
35
36
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
36
37
  const notFound = () => new ApiError("catalog.item_not_found", "Catalog item not found");
37
38
  const builtinError = () => new ApiError("plugin.builtin", "This plugin is built in: it is on in every organization and its scope cannot be changed or disabled");
38
- const staleError = () => new ApiError("plugin.scope_stale", "What this change affects has changed since the preview; preview it again and confirm the new hash");
39
39
  /** The hash of a preview: sha256 over its sorted JSON, the target included. */
40
40
  function scopeHash(target, p) {
41
41
  return createHash("sha256")
@@ -86,6 +86,7 @@ export function conflictsError(conflicts) {
86
86
  let CatalogScopeService = class CatalogScopeService {
87
87
  kdb;
88
88
  adminLock;
89
+ scopeWriter;
89
90
  catalog;
90
91
  pluginImport;
91
92
  installer;
@@ -93,9 +94,10 @@ let CatalogScopeService = class CatalogScopeService {
93
94
  ops;
94
95
  sync;
95
96
  txHost;
96
- constructor(kdb, adminLock, catalog, pluginImport, installer, extensions, ops, sync, txHost) {
97
+ constructor(kdb, adminLock, scopeWriter, catalog, pluginImport, installer, extensions, ops, sync, txHost) {
97
98
  this.kdb = kdb;
98
99
  this.adminLock = adminLock;
100
+ this.scopeWriter = scopeWriter;
99
101
  this.catalog = catalog;
100
102
  this.pluginImport = pluginImport;
101
103
  this.installer = installer;
@@ -245,91 +247,81 @@ let CatalogScopeService = class CatalogScopeService {
245
247
  });
246
248
  }
247
249
  async writeScope(actor, itemId, target, hash, opts) {
248
- await this.adminLock.lockAndAuthorize(actor);
249
- const item = await this.item(itemId, true);
250
- const t = await this.targetOf(item, target);
251
- const from = await this.listed(itemId);
252
- // The owner stays listed (P3-17); widening goes through the share gate (P3-16)
253
- assertOwnerListed(item, t);
254
- assertShareableTarget(item, { scope: item.scope, orgs: from }, t);
255
- // A scope change sends every theme back to following the plugin (rule 2): each is `all` after
256
- // only when the plugin is (themes spec §7)
257
- await this.assertKeepsPlatformDefault(item.id, (c) => c.disabled || item.disabled ? "gone" : t.scope === "all" ? "all" : "narrower");
258
- const p = await this.compute(item, t);
259
- if (p.scopeHash !== hash)
260
- throw staleError();
261
- if (p.conflicts.length > 0)
262
- throw conflictsError(p.conflicts);
263
- if (item.scope === t.scope && from.join() === t.orgs.join() && p.replaced.length === 0)
264
- return;
265
- await this.followAgain(actor, itemId, p.replaced, opts);
266
- await this.db
267
- .updateTable("catalog_items")
268
- .set({
269
- scope: t.scope,
270
- updated_at: sql `now()`,
271
- })
272
- .where("id", "=", itemId)
273
- .execute();
274
- await this.db.deleteFrom("catalog_item_scope_orgs").where("item_id", "=", itemId).execute();
275
- if (t.orgs.length > 0) {
276
- await this.db
277
- .insertInto("catalog_item_scope_orgs")
278
- .values(t.orgs.map((org_id) => ({ item_id: itemId, org_id })))
279
- .execute();
280
- }
281
- const shared = newlySharedWith({ scope: item.scope, orgs: from }, t);
282
- if (shared === "all_orgs" || shared.length > 0) {
283
- await notifyItemShared(this.db, item.owner_org_id, { kind: "plugin", id: itemId }, item.name, shared);
284
- }
285
- await audit(this.db, {
286
- actorAccountId: actor,
287
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
288
- action: "catalog.scope_changed",
289
- target: itemId,
290
- detail: {
291
- name: item.name,
292
- from: { scope: item.scope, orgs: from },
293
- to: { scope: t.scope, orgs: t.orgs },
294
- ...opts.auditDetail,
295
- },
250
+ await this.scopeWriter.platformChange(actor, { kind: "scope", hash }, async () => {
251
+ const item = await this.item(itemId, true);
252
+ const t = await this.targetOf(item, target);
253
+ const from = await this.listed(itemId);
254
+ // The owner stays listed (P3-17); widening goes through the share gate (P3-16)
255
+ assertOwnerListed(item, t);
256
+ assertShareableTarget(item, { scope: item.scope, orgs: from }, t);
257
+ // A scope change sends every theme back to following the plugin (rule 2): each is `all` after
258
+ // only when the plugin is (themes spec §7)
259
+ await this.assertKeepsPlatformDefault(item.id, (c) => c.disabled || item.disabled ? "gone" : t.scope === "all" ? "all" : "narrower");
260
+ const p = await this.compute(item, t);
261
+ return {
262
+ preview: p,
263
+ conflict: conflictsError,
264
+ apply: async () => {
265
+ if (item.scope === t.scope && from.join() === t.orgs.join() && p.replaced.length === 0)
266
+ return;
267
+ await this.followAgain(actor, itemId, p.replaced, opts);
268
+ await this.scopeWriter.replaceScope({
269
+ kind: "plugin",
270
+ id: itemId,
271
+ scope: t.scope,
272
+ orgs: t.orgs,
273
+ });
274
+ const shared = newlySharedWith({ scope: item.scope, orgs: from }, t);
275
+ if (shared === "all_orgs" || shared.length > 0) {
276
+ await notifyItemShared(this.db, item.owner_org_id, { kind: "plugin", id: itemId }, item.name, shared);
277
+ }
278
+ await audit(this.db, {
279
+ actorAccountId: actor,
280
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
281
+ action: "catalog.scope_changed",
282
+ target: itemId,
283
+ detail: {
284
+ name: item.name,
285
+ from: { scope: item.scope, orgs: from },
286
+ to: { scope: t.scope, orgs: t.orgs },
287
+ ...opts.auditDetail,
288
+ },
289
+ });
290
+ await this.enqueue(itemId);
291
+ },
292
+ };
296
293
  });
297
- await this.enqueue(itemId);
298
294
  }
299
295
  async writeDisabled(actor, itemId, disabled, hash, opts) {
300
- await this.adminLock.lockAndAuthorize(actor);
301
- const item = await this.item(itemId, true);
302
- if (item.disabled === disabled)
303
- return;
304
- if (disabled)
305
- await this.assertKeepsPlatformDefault(item.id, () => "gone");
306
- const p = await this.compute(item, disabled
307
- ? await this.targetOf(item, { disabled: true })
308
- : { scope: item.scope, orgs: await this.listed(itemId), disabled, scopeChange: false });
309
- if (disabled && p.scopeHash !== hash)
310
- throw staleError();
311
- if (p.conflicts.length > 0)
312
- throw conflictsError(p.conflicts);
313
- await this.db
314
- .updateTable("catalog_items")
315
- .set({
316
- disabled,
317
- updated_at: sql `now()`,
318
- })
319
- .where("id", "=", itemId)
320
- .execute();
321
- await audit(this.db, {
322
- actorAccountId: actor,
323
- ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
324
- action: "catalog.scope_changed",
325
- target: itemId,
326
- detail: {
327
- name: item.name,
328
- disabled: { from: item.disabled, to: disabled },
329
- ...opts.auditDetail,
330
- },
296
+ await this.scopeWriter.platformChange(actor, disabled ? { kind: "disable", hash } : { kind: "enable" }, async () => {
297
+ const item = await this.item(itemId, true);
298
+ if (item.disabled === disabled)
299
+ return;
300
+ if (disabled)
301
+ await this.assertKeepsPlatformDefault(item.id, () => "gone");
302
+ const p = await this.compute(item, disabled
303
+ ? await this.targetOf(item, { disabled: true })
304
+ : { scope: item.scope, orgs: await this.listed(itemId), disabled, scopeChange: false });
305
+ return {
306
+ preview: p,
307
+ conflict: conflictsError,
308
+ apply: async () => {
309
+ await this.scopeWriter.setDisabled({ kind: "plugin", id: itemId }, disabled);
310
+ await audit(this.db, {
311
+ actorAccountId: actor,
312
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
313
+ action: "catalog.scope_changed",
314
+ target: itemId,
315
+ detail: {
316
+ name: item.name,
317
+ disabled: { from: item.disabled, to: disabled },
318
+ ...opts.auditDetail,
319
+ },
320
+ });
321
+ await this.enqueue(itemId);
322
+ },
323
+ };
331
324
  });
332
- await this.enqueue(itemId);
333
325
  }
334
326
  /**
335
327
  * Writes an org-owned plugin's 可共享 flag and copies it to its component rows (ruling P3-2).
@@ -475,39 +467,32 @@ let CatalogScopeService = class CatalogScopeService {
475
467
  const orgs = await db
476
468
  .selectFrom("orgs")
477
469
  .select(["id", "name"])
470
+ .select(({ ref }) => [
471
+ orgUsable(db, ref("orgs.id"), item.id).as("onNow"),
472
+ orgUsable(db, ref("orgs.id"), item.id, {
473
+ itemId: item.id,
474
+ scope: target.scope,
475
+ orgs: target.orgs,
476
+ disabled: target.disabled,
477
+ resetComponents: target.scopeChange,
478
+ }).as("onAfter"),
479
+ ])
478
480
  .where("deleted_at", "is", null)
479
481
  .orderBy("id")
480
482
  .execute();
481
- const listedNow = new Set(await this.listed(item.id));
482
- const switches = await db
483
- .selectFrom("catalog_item_org_switches")
484
- .select(["org_id", "enabled"])
485
- .where("item_id", "=", item.id)
486
- .execute();
487
483
  const installs = await db
488
484
  .selectFrom("plugin_installs")
489
485
  .select(["id", "org_id"])
490
486
  .where("item_id", "=", item.id)
491
487
  .where("status", "in", [...LIVE_INSTALL_STATUSES])
492
488
  .execute();
493
- const sw = new Map(switches.map((s) => [s.org_id, s.enabled]));
494
- const live = new Map(installs.map((a) => [a.org_id, a.id]));
495
- const listedAfter = new Set(target.orgs);
496
- const after = { scope: target.scope, disabled: target.disabled, builtin: false };
489
+ const live = new Map(installs.map((install) => [install.org_id, install.id]));
497
490
  const affected = [];
498
491
  const needsConfig = [];
499
- /** The orgs the plugin will be on in after the change (a live install kept or made). */
500
- const onAfter = new Set();
492
+ const onAfter = new Set(orgs.filter((org) => org.onAfter).map((org) => org.id));
501
493
  for (const org of orgs) {
502
- const s = sw.get(org.id) ?? null;
503
- const wanted = wantedOn(after, listedAfter.has(org.id), s);
504
494
  const installId = live.get(org.id);
505
- if (installId !== undefined) {
506
- // A live install another one depends on stays (spec §5 rule 9, as the sync does)
507
- if (wanted || (await this.sync.dependedOn(org.id, installId))) {
508
- onAfter.add(org.id);
509
- continue;
510
- }
495
+ if (installId !== undefined && !org.onAfter) {
511
496
  const p = await this.installer.previewUninstall(org.id, installId);
512
497
  affected.push({
513
498
  orgId: org.id,
@@ -519,7 +504,7 @@ let CatalogScopeService = class CatalogScopeService {
519
504
  });
520
505
  continue;
521
506
  }
522
- if (!wanted || wantedOn(item, listedNow.has(org.id), s))
507
+ if (!org.onAfter || org.onNow || installId !== undefined)
523
508
  continue;
524
509
  let needs = false;
525
510
  try {
@@ -535,7 +520,6 @@ let CatalogScopeService = class CatalogScopeService {
535
520
  // `needsConfig` names the orgs where its extension waits for the org's config
536
521
  if (needs)
537
522
  needsConfig.push(org.id);
538
- onAfter.add(org.id);
539
523
  }
540
524
  const { replaced, conflicts, themesLost } = await this.componentChanges(item, target, orgs, onAfter, affected);
541
525
  const themes = await themesPreview(db, themesLost);
@@ -585,7 +569,7 @@ let CatalogScopeService = class CatalogScopeService {
585
569
  scope: target.scope,
586
570
  disabled: target.disabled,
587
571
  listed: target.orgs.includes(org.id),
588
- installed: onAfter.has(org.id),
572
+ usable: onAfter.has(org.id),
589
573
  };
590
574
  const listed = listedIn(st, c.id, org.id);
591
575
  const s = switchOf(st, c.id, org.id);
@@ -656,27 +640,12 @@ let CatalogScopeService = class CatalogScopeService {
656
640
  */
657
641
  async followAgain(actor, itemId, replaced, opts) {
658
642
  for (const r of replaced) {
659
- const table = r.kind === "skill"
660
- ? "platform_skills"
661
- : r.kind === "agent_template"
662
- ? "platform_agent_templates"
663
- : r.kind === "theme"
664
- ? "platform_themes"
665
- : "platform_connector_templates";
666
- await this.db
667
- .updateTable(table)
668
- .set({
669
- scope_mode: "follow",
670
- updated_at: sql `now()`,
671
- })
672
- .where("id", "=", r.id)
673
- .where("scope_mode", "=", "own")
674
- .execute();
675
- await this.db
676
- .deleteFrom("component_scope_orgs")
677
- .where("kind", "=", r.kind)
678
- .where("component_id", "=", r.id)
679
- .execute();
643
+ await this.scopeWriter.replaceScope({
644
+ kind: r.kind,
645
+ id: r.id,
646
+ scopeMode: "follow",
647
+ orgs: [],
648
+ });
680
649
  await audit(this.db, {
681
650
  actorAccountId: actor,
682
651
  ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
@@ -690,12 +659,6 @@ let CatalogScopeService = class CatalogScopeService {
690
659
  __decorate([
691
660
  Transactional()
692
661
  ], CatalogScopeService.prototype, "writeShown", null);
693
- __decorate([
694
- Transactional()
695
- ], CatalogScopeService.prototype, "writeScope", null);
696
- __decorate([
697
- Transactional()
698
- ], CatalogScopeService.prototype, "writeDisabled", null);
699
662
  __decorate([
700
663
  Transactional()
701
664
  ], CatalogScopeService.prototype, "setShareable", null);
@@ -715,12 +678,13 @@ CatalogScopeService = __decorate([
715
678
  ,
716
679
  __param(0, Inject(KernelDb)),
717
680
  __param(1, Inject(SuperAdminLock)),
718
- __param(2, Inject(CatalogService)),
719
- __param(3, Inject(PluginImport)),
720
- __param(4, Inject(PluginInstaller)),
721
- __param(5, Inject(ExtensionAdmin)),
722
- __param(6, Inject(ExtensionAdminOps)),
723
- __param(7, Inject(PluginScopeSync)),
724
- __param(8, Inject(TransactionHost))
681
+ __param(2, Inject(ScopeWriter)),
682
+ __param(3, Inject(CatalogService)),
683
+ __param(4, Inject(PluginImport)),
684
+ __param(5, Inject(PluginInstaller)),
685
+ __param(6, Inject(ExtensionAdmin)),
686
+ __param(7, Inject(ExtensionAdminOps)),
687
+ __param(8, Inject(PluginScopeSync)),
688
+ __param(9, Inject(TransactionHost))
725
689
  ], CatalogScopeService);
726
690
  export { CatalogScopeService };
@@ -25,6 +25,7 @@ import { PluginInstaller } from "./plugin-install.js";
25
25
  import { PlatformPluginUpdater } from "./plugin-upgrade.js";
26
26
  import { CatalogRequestsService } from "./requests.service.js";
27
27
  import { PLUGIN_SCOPE_QUEUE, PluginScopeSync } from "./scope-sync.js";
28
+ import { ScopeWriter } from "./scope-writer.js";
28
29
  import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
29
30
  import { TemplateConnectorsQueueModule } from "./template-connector-jobs.js";
30
31
  export { CatalogImportModule };
@@ -70,6 +71,7 @@ CatalogModule = __decorate([
70
71
  PlatformPluginUpdater,
71
72
  OrgCatalogService,
72
73
  PluginScopeSync,
74
+ ScopeWriter,
73
75
  CatalogScopeService,
74
76
  ComponentScopeService,
75
77
  OrgPluginUploads,
@@ -52,7 +52,7 @@ export interface CatalogItemView {
52
52
  * shareable`, P3-1); false for platform items, which pass the gate anyway.
53
53
  */
54
54
  shareable: boolean;
55
- /** Orgs it is on in: orgs with a live plugin install of it (every org for a builtin plugin). */
55
+ /** Organizations where the plugin is usable. */
56
56
  enabledOrgs: number;
57
57
  /**
58
58
  * Orgs whose admin switched it off while its scope is `all` (layering spec §4: on in every org
@@ -368,8 +368,8 @@ export declare class CatalogService {
368
368
  private lockConnectorOrgs;
369
369
  /**
370
370
  * A live platform item whose extension (the install of the item's name from its package) is
371
- * enabled -> 409 `catalog.extension_enabled`. With `lock`, under the per-name install lock an
372
- * enable takes too (the caller's transaction), so no enable slips in between.
371
+ * enabled -> 409 `catalog.extension_enabled`. The removal holds the extension install locks
372
+ * while checking and retiring the item.
373
373
  */
374
374
  private assertExtensionDisabled;
375
375
  /**