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

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 (99) hide show
  1. package/dist/admin/extensions.controller.d.ts +5 -2
  2. package/dist/admin/extensions.controller.js +10 -1
  3. package/dist/admin/extensions.schemas.d.ts +4 -0
  4. package/dist/admin/extensions.schemas.js +9 -0
  5. package/dist/admin/health.service.d.ts +1 -1
  6. package/dist/admin/health.service.js +3 -3
  7. package/dist/catalog/catalog-content.d.ts +5 -7
  8. package/dist/catalog/catalog-items.js +1 -1
  9. package/dist/catalog/catalog-scope.service.js +5 -5
  10. package/dist/catalog/catalog.module.js +5 -4
  11. package/dist/catalog/catalog.service.d.ts +7 -1
  12. package/dist/catalog/catalog.service.js +19 -2
  13. package/dist/catalog/effect-work.d.ts +27 -0
  14. package/dist/catalog/effect-work.js +151 -0
  15. package/dist/catalog/jobs.d.ts +4 -1
  16. package/dist/catalog/jobs.js +14 -4
  17. package/dist/catalog/org-catalog.service.d.ts +2 -0
  18. package/dist/catalog/org-catalog.service.js +68 -12
  19. package/dist/catalog/org-intent.d.ts +4 -2
  20. package/dist/catalog/org-intent.js +25 -4
  21. package/dist/catalog/owned-items.d.ts +5 -1
  22. package/dist/catalog/owned-items.js +18 -3
  23. package/dist/catalog/plugin-import.d.ts +4 -2
  24. package/dist/catalog/plugin-import.js +10 -5
  25. package/dist/catalog/plugin-install.d.ts +17 -51
  26. package/dist/catalog/plugin-install.js +209 -235
  27. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  28. package/dist/catalog/plugin-upgrade.js +63 -34
  29. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  30. package/dist/catalog/scope-sync-workers.js +10 -26
  31. package/dist/catalog/scope-sync.d.ts +19 -114
  32. package/dist/catalog/scope-sync.js +220 -239
  33. package/dist/catalog/scope-writer.d.ts +10 -1
  34. package/dist/catalog/scope-writer.js +62 -4
  35. package/dist/catalog/template-connector-ensure.js +1 -1
  36. package/dist/catalog/unshare.js +1 -2
  37. package/dist/config/schema.d.ts +1 -1
  38. package/dist/config/schema.js +7 -4
  39. package/dist/db/kernel-schema.d.ts +21 -5
  40. package/dist/erasure/org-catalog.js +2 -2
  41. package/dist/erasure/org-rules.js +2 -0
  42. package/dist/extensions/admin-ops.d.ts +1 -1
  43. package/dist/extensions/admin-ops.js +1 -1
  44. package/dist/extensions/admin-view.d.ts +4 -1
  45. package/dist/extensions/admin-view.js +27 -11
  46. package/dist/extensions/bootstrap.d.ts +1 -1
  47. package/dist/extensions/bootstrap.js +2 -3
  48. package/dist/extensions/enabled.d.ts +160 -0
  49. package/dist/extensions/enabled.js +7 -0
  50. package/dist/extensions/host.d.ts +1 -0
  51. package/dist/extensions/host.js +5 -2
  52. package/dist/extensions/isolated/authorization.d.ts +8 -0
  53. package/dist/extensions/isolated/authorization.js +56 -11
  54. package/dist/extensions/isolated/broker.js +30 -11
  55. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  56. package/dist/extensions/isolated/engine-binds.js +82 -0
  57. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  58. package/dist/extensions/isolated/engine-policy.js +75 -0
  59. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  60. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  61. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  62. package/dist/extensions/isolated/engine-proxy.js +408 -0
  63. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  64. package/dist/extensions/isolated/engine-vaults.js +93 -0
  65. package/dist/extensions/isolated/lanes.d.ts +11 -3
  66. package/dist/extensions/isolated/lanes.js +43 -16
  67. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  68. package/dist/extensions/isolated/postgres-gate.js +6 -6
  69. package/dist/extensions/isolated/revision.d.ts +1 -1
  70. package/dist/extensions/isolated/revision.js +3 -2
  71. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  72. package/dist/extensions/isolated/sandbox.js +101 -117
  73. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  74. package/dist/extensions/lifecycle-topics.js +1 -0
  75. package/dist/extensions/lifecycle.js +23 -2
  76. package/dist/extensions/permission-view.d.ts +6 -1
  77. package/dist/inbox/platform-inbox.service.js +16 -27
  78. package/dist/infra/events/kernel-events.d.ts +4 -0
  79. package/dist/infra/outbox/registry.d.ts +3 -36
  80. package/dist/infra/outbox/registry.js +4 -49
  81. package/dist/infra/queue/queue-names.d.ts +1 -1
  82. package/dist/infra/queue/queue-names.js +1 -1
  83. package/dist/orgs/org-lock.d.ts +3 -1
  84. package/dist/orgs/org-lock.js +3 -1
  85. package/dist/orgs/orgs.service.d.ts +3 -1
  86. package/dist/orgs/orgs.service.js +15 -8
  87. package/dist/overrides.d.ts +0 -3
  88. package/dist/overrides.js +0 -2
  89. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  90. package/dist/platform/ops/org-plugins.ops.js +5 -2
  91. package/dist/platform/ops/plugins.ops.js +11 -10
  92. package/dist/tools/registry.d.ts +1 -1
  93. package/dist/tools/registry.js +6 -2
  94. package/package.json +2 -2
  95. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  96. package/dist/catalog/install-status.d.ts +0 -5
  97. package/dist/catalog/install-status.js +0 -5
  98. package/dist/catalog/scope-jobs.d.ts +0 -59
  99. package/dist/catalog/scope-jobs.js +0 -78
@@ -14,6 +14,7 @@ import { templateGuideOf } from "../extensions/plugin-guides.js";
14
14
  import { PluginIcons } from "../extensions/plugin-icons.js";
15
15
  import { ExtensionRegistry } from "../extensions/registry.js";
16
16
  import { ExtensionAvailability } from "../extensions/unavailable.js";
17
+ import { audit } from "../identity/audit.js";
17
18
  import { KernelDb } from "../infra/database/kernel-db.js";
18
19
  import { TransactionHost } from "../infra/database/transaction-host.js";
19
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
@@ -22,10 +23,10 @@ import { OrgLock } from "../orgs/org-lock.js";
22
23
  import { can, roleAtLeast } from "../orgs/roles.js";
23
24
  import { packagePath } from "../packages/tgz.js";
24
25
  import { StorageService } from "../storage/storage.service.js";
26
+ import { assertNotPlatformDefault } from "../themes/theme-usage.js";
25
27
  import { catalogHasIcon, findConnectorIn, orgTemplateView, readCatalogAgentTemplates, readCatalogIcon, readCatalogTemplates, templatePluginProblem, } from "./catalog-content.js";
26
28
  import { itemView, ownerOnlyFacts, versionUsable } from "./catalog-items.js";
27
29
  import { connectorTemplatesOn } from "./component-state.js";
28
- import { LIVE_INSTALL_STATUSES } from "./install-status.js";
29
30
  import { orgSees, orgUsable } from "./org-intent.js";
30
31
  import { ownerOf, ownersOf } from "./ownership.js";
31
32
  import { PluginInstaller, uninstallPreviewHash, } from "./plugin-install.js";
@@ -111,7 +112,7 @@ let OrgCatalogService = class OrgCatalogService {
111
112
  if (items.length === 0)
112
113
  return [];
113
114
  const ids = items.map((i) => i.id);
114
- const [versions, pluginInstalls, requests] = await Promise.all([
115
+ const [versions, pluginInstalls, requests, pendingEffectWork] = await Promise.all([
115
116
  this.db
116
117
  .selectFrom("catalog_item_versions")
117
118
  .select([
@@ -128,9 +129,9 @@ let OrgCatalogService = class OrgCatalogService {
128
129
  .execute(),
129
130
  this.db
130
131
  .selectFrom("plugin_installs")
131
- .select(["id", "item_id", "version"])
132
+ .select(["id", "item_id", "version", "status"])
132
133
  .where("org_id", "=", orgId)
133
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
134
+ .where("item_id", "in", ids)
134
135
  .execute(),
135
136
  this.db
136
137
  .selectFrom("catalog_requests")
@@ -141,7 +142,15 @@ let OrgCatalogService = class OrgCatalogService {
141
142
  .where("status", "=", "pending")
142
143
  .orderBy("created_at")
143
144
  .execute(),
145
+ this.db
146
+ .selectFrom("plugin_effect_work")
147
+ .select("item_id")
148
+ .where("org_id", "=", orgId)
149
+ .where("item_id", "in", ids)
150
+ .where("state", "=", "pending")
151
+ .execute(),
144
152
  ]);
153
+ const pendingEffects = new Set(pendingEffectWork.map((work) => work.item_id));
145
154
  const pending = new Map(requests.map((r) => [
146
155
  r.item_id,
147
156
  { id: r.id, kind: r.kind, createdAt: r.created_at.toISOString() },
@@ -203,10 +212,13 @@ let OrgCatalogService = class OrgCatalogService {
203
212
  scope,
204
213
  builtin: i.builtin,
205
214
  state,
215
+ ...(pendingEffects.has(i.id) && { setup: "pending" }),
216
+ ...(!pendingEffects.has(i.id) &&
217
+ a?.status === "install_failed" && { setup: "install_failed" }),
206
218
  ...(reason !== undefined && { reason }),
207
219
  switchable: state !== "not_offered" && switchable(i),
208
220
  notDeployed: latest !== undefined && undeployed.has(i.id),
209
- installed: a
221
+ installed: a?.version != null
210
222
  ? {
211
223
  pluginInstallId: a.id,
212
224
  version: a.version,
@@ -400,7 +412,7 @@ let OrgCatalogService = class OrgCatalogService {
400
412
  const view = await this.pluginInstaller.install(orgId, actor, itemId, version, body, opts);
401
413
  return {
402
414
  status: 201,
403
- installed: { itemId, version, pluginInstallId: view.id },
415
+ installed: { itemId, version, pluginInstallId: view?.id ?? null },
404
416
  install: view,
405
417
  };
406
418
  }
@@ -424,7 +436,7 @@ let OrgCatalogService = class OrgCatalogService {
424
436
  .select("id")
425
437
  .where("org_id", "=", orgId)
426
438
  .where("item_id", "=", itemId)
427
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
439
+ .where("version", "is not", null)
428
440
  .executeTakeFirst();
429
441
  }
430
442
  /**
@@ -447,7 +459,7 @@ let OrgCatalogService = class OrgCatalogService {
447
459
  if (item.disabled)
448
460
  throw pluginDisabled();
449
461
  if ((await this.liveInstall(orgId, itemId)) !== undefined) {
450
- await this.recordSwitch(orgId, actor, itemId, true);
462
+ await this.recordSwitch(orgId, actor, itemId, true, opts);
451
463
  }
452
464
  else {
453
465
  await this.install(orgId, actor, itemId, body.inputs ?? {}, actorTokenId, auditDetail);
@@ -459,7 +471,11 @@ let OrgCatalogService = class OrgCatalogService {
459
471
  }
460
472
  const live = await this.liveInstall(orgId, itemId);
461
473
  if (live === undefined) {
462
- await this.recordSwitch(orgId, actor, itemId, false);
474
+ const preview = await this.previewContentOff(orgId, itemId);
475
+ if (preview && body.confirm === undefined) {
476
+ return { kind: "preview", preview, confirm: uninstallPreviewHash(preview) };
477
+ }
478
+ await this.recordSwitch(orgId, actor, itemId, false, opts, body.confirm);
463
479
  return { kind: "done", item: await this.itemOf(orgId, actor, itemId) };
464
480
  }
465
481
  // The platform default theme is locked on (themes spec §7): refused at the preview already;
@@ -488,12 +504,12 @@ let OrgCatalogService = class OrgCatalogService {
488
504
  const row = await this.db
489
505
  .selectFrom("plugin_installs as a")
490
506
  .innerJoin("catalog_items as i", "i.id", "a.item_id")
491
- .select(["i.scope", "i.builtin", "a.status"])
507
+ .select(["i.scope", "i.builtin", "a.version"])
492
508
  .where("a.id", "=", installId)
493
509
  .where("a.org_id", "=", orgId)
494
510
  .executeTakeFirst();
495
511
  // A failed or stuck install is cleaned up whatever the scope (it is not on anyway)
496
- const live = row?.status === "installed";
512
+ const live = row?.version != null;
497
513
  if (row !== undefined && live && !switchable(row)) {
498
514
  throw new ApiError("plugin.scope_locked", "This plugin is built in: it is on for every organization and cannot be uninstalled here");
499
515
  }
@@ -505,6 +521,17 @@ let OrgCatalogService = class OrgCatalogService {
505
521
  // item its scope wants stays wanted and the sync installs it again
506
522
  row !== undefined && live ? {} : undefined);
507
523
  }
524
+ /** The switch-off impact even when there are no applied org resources. */
525
+ async previewContentOff(orgId, itemId) {
526
+ const preview = await this.pluginInstaller.previewContentOff(orgId, itemId);
527
+ if (!preview)
528
+ return null;
529
+ const themes = preview.themes ?? [];
530
+ if (themes.length > 0) {
531
+ await assertNotPlatformDefault(this.db, themes.map((theme) => theme.id), () => "narrower");
532
+ }
533
+ return preview.agents.length > 0 || themes.length > 0 ? preview : null;
534
+ }
508
535
  async itemOf(orgId, accountId, itemId) {
509
536
  const [item] = await this.list(orgId, accountId, itemId);
510
537
  if (!item)
@@ -516,7 +543,7 @@ let OrgCatalogService = class OrgCatalogService {
516
543
  * SHARE first (exclusive with a scope change, an unshare, ruling P3-25, and an owner's delete or
517
544
  * transfer); switching on re-checks that the org may still see it; the install path re-checks the same in `assertItemInstallable`.
518
545
  */
519
- async recordSwitch(orgId, actor, itemId, enabled) {
546
+ async recordSwitch(orgId, actor, itemId, enabled, opts, confirm) {
520
547
  await this.orgLock.lock(orgId);
521
548
  // Both directions lock the item row FOR SHARE: an owner's delete or transfer (FOR UPDATE)
522
549
  // decides on who uses it, so a switch-off racing it must not change that answer meanwhile
@@ -540,7 +567,36 @@ let OrgCatalogService = class OrgCatalogService {
540
567
  throw itemNotFound();
541
568
  }
542
569
  }
570
+ else {
571
+ if (item?.builtin)
572
+ throw new ApiError("plugin.scope_locked", "A built-in plugin cannot be switched off");
573
+ const themes = await this.db
574
+ .selectFrom("platform_themes")
575
+ .select("id")
576
+ .where("catalog_item_id", "=", itemId)
577
+ .where("scope_mode", "=", "follow")
578
+ .where("deleted_at", "is", null)
579
+ .where("disabled", "=", false)
580
+ .orderBy("id")
581
+ .forShare()
582
+ .execute();
583
+ await assertNotPlatformDefault(this.db, themes.map((theme) => theme.id), () => "narrower");
584
+ }
585
+ if (!enabled) {
586
+ const preview = await this.previewContentOff(orgId, itemId);
587
+ if (preview && uninstallPreviewHash(preview) !== confirm) {
588
+ throw new ApiError("plugin.switch_stale", "The switch preview changed; review it and confirm again");
589
+ }
590
+ }
543
591
  await this.scopeWriter.setOrgSwitch({ kind: "plugin", id: itemId }, orgId, enabled, actor);
592
+ await audit(this.db, {
593
+ actorAccountId: actor,
594
+ ...(opts.actorTokenId !== undefined && { actorTokenId: opts.actorTokenId }),
595
+ orgId,
596
+ action: "catalog.scope_changed",
597
+ target: itemId,
598
+ detail: { enabled, ...opts.auditDetail },
599
+ });
544
600
  }
545
601
  /** The actor can install something in the org (forbidden otherwise), checked before item errors. */
546
602
  async assertCanInstall(orgId, actor) {
@@ -19,7 +19,7 @@ export declare function orgSees(db: KernelSchemaDb, orgId: Key, isAdmin: boolean
19
19
  named: import("kysely").Nullable<import("../db/kernel-schema.js").CatalogItemScopeOrgsTable>;
20
20
  }, "item" | "named", Partial<Omit<unknown, never>>>;
21
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 & {
22
+ export declare function orgPluginDirectIntent(db: KernelSchemaDb, orgId: Key, proposal?: ProposedPluginScope, offItemId?: string): import("kysely").SelectQueryBuilder<import("../db/kernel-schema.js").KernelDatabase & {
23
23
  item: import("../db/kernel-schema.js").CatalogItemsTable;
24
24
  } & {
25
25
  named: import("kysely").Nullable<import("../db/kernel-schema.js").CatalogItemScopeOrgsTable>;
@@ -33,7 +33,9 @@ export declare function orgPluginDirectIntent(db: KernelSchemaDb, orgId: Key, pr
33
33
  * for missing or ineligible dependencies. Deduplication by depth bounds repeated diamond paths
34
34
  * and turns cycles and over-deep graphs into denials.
35
35
  */
36
- export declare function orgUsable(db: KernelSchemaDb, orgId: Key, itemId: string | Expression<string | null>, proposal?: ProposedPluginScope): import("kysely").RawBuilder<boolean>;
36
+ export declare function orgUsable(db: KernelSchemaDb, orgId: Key, itemId: string | Expression<string | null>, proposal?: ProposedPluginScope, offItemId?: string): import("kysely").RawBuilder<boolean>;
37
+ /** Content lost when the org stops following one root, while other roots remain available. */
38
+ export declare function contentLostWhenOff(db: KernelSchemaDb, orgId: string, itemId: string): Promise<string[]>;
37
39
  /** Setup attempts also surface failures for an authorized direct choice with a blocked dependency. */
38
40
  export declare function orgPluginEffectIntent(db: KernelSchemaDb, orgId: Key, itemId: string): import("kysely").RawBuilder<boolean>;
39
41
  /** Filter existing display rows with the same visibility projection as the catalog query. */
@@ -42,13 +42,13 @@ export function orgSees(db, orgId, isAdmin, view = "catalog") {
42
42
  ]));
43
43
  }
44
44
  /** Project a catalog item's direct intent, before considering dependency roots. */
45
- export function orgPluginDirectIntent(db, orgId, proposal) {
45
+ export function orgPluginDirectIntent(db, orgId, proposal, offItemId) {
46
46
  const scope = proposed("item", proposal, sql `item.scope`, sql `${proposal?.scope}::text`);
47
47
  const enabled = proposed("item", proposal, sql `NOT item.disabled`, sql `${!proposal?.disabled}::boolean`);
48
48
  const listed = proposed("item", proposal, sql `named.item_id IS NOT NULL`, sql `${orgId} = ANY(${proposal?.orgs}::text[])`);
49
49
  return orgCatalogItems(db, orgId, true)
50
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 (
51
+ .select(sql `(${enabled} AND ${offItemId === undefined ? sql `true` : sql `item.id <> ${offItemId}`} AND (
52
52
  (item.builtin AND item.owner_org_id IS NULL) OR
53
53
  (${scope} = 'optional' AND org_switch.enabled IS TRUE) OR
54
54
  ((${scope} = 'all' OR (${scope} = 'named' AND ${listed})) AND org_switch.enabled IS NOT FALSE)
@@ -113,8 +113,8 @@ function edgeAdmitsTarget(orgId, proposal) {
113
113
  * for missing or ineligible dependencies. Deduplication by depth bounds repeated diamond paths
114
114
  * and turns cycles and over-deep graphs into denials.
115
115
  */
116
- export function orgUsable(db, orgId, itemId, proposal) {
117
- const direct = orgPluginDirectIntent(db, orgId, proposal)
116
+ export function orgUsable(db, orgId, itemId, proposal, offItemId) {
117
+ const direct = orgPluginDirectIntent(db, orgId, proposal, offItemId)
118
118
  .where("item.id", "=", sql `reach.id`)
119
119
  .limit(1);
120
120
  return sql `exists (
@@ -164,6 +164,27 @@ export function orgUsable(db, orgId, itemId, proposal) {
164
164
  )
165
165
  )`;
166
166
  }
167
+ /** Content lost when the org stops following one root, while other roots remain available. */
168
+ export async function contentLostWhenOff(db, orgId, itemId) {
169
+ const candidateId = sql.ref("affected.id");
170
+ const { rows } = await sql `
171
+ WITH RECURSIVE affected(id) AS (
172
+ SELECT id FROM capybara.catalog_items WHERE id = ${itemId}
173
+ UNION
174
+ SELECT edge.dependency_item_id
175
+ FROM affected
176
+ JOIN capybara.catalog_items AS parent ON parent.id = affected.id
177
+ JOIN capybara.catalog_dependency_edges AS edge ON edge.item_id = parent.id
178
+ AND edge.item_version = coalesce(parent.platform_synced_version, parent.latest_version)
179
+ WHERE edge.dependency_item_id IS NOT NULL
180
+ )
181
+ SELECT id FROM affected
182
+ WHERE ${orgUsable(db, orgId, candidateId)}
183
+ AND NOT ${orgUsable(db, orgId, candidateId, undefined, itemId)}
184
+ ORDER BY id
185
+ `.execute(db);
186
+ return rows.map((row) => row.id);
187
+ }
167
188
  /** Setup attempts also surface failures for an authorized direct choice with a blocked dependency. */
168
189
  export function orgPluginEffectIntent(db, orgId, itemId) {
169
190
  const direct = orgPluginDirectIntent(db, orgId).where("item.id", "=", itemId);
@@ -1,5 +1,7 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { XactLock } from "../infra/database/xact-lock.js";
4
+ import { KernelEvents } from "../infra/events/kernel-events.js";
3
5
  import type { KernelLogger } from "../log.js";
4
6
  import { OrgLock } from "../orgs/org-lock.js";
5
7
  import { SkillsService } from "../skills/skills.service.js";
@@ -46,11 +48,13 @@ export declare class OwnedItems {
46
48
  private readonly skills;
47
49
  private readonly log;
48
50
  readonly txHost: TransactionHost;
51
+ private readonly xactLock;
52
+ private readonly events;
49
53
  constructor(kdb: KernelDb, orgLock: OrgLock, catalog: CatalogService, scope: CatalogScopeService,
50
54
  /** The owner org's own uninstall of a removed plugin (ruling P3-41). */
51
55
  installer: PluginInstaller,
52
56
  /** The owner's org skill row, soft-deleted after its promoted platform row leaves it. */
53
- skills: SkillsService, log: KernelLogger, txHost: TransactionHost);
57
+ skills: SkillsService, log: KernelLogger, txHost: TransactionHost, xactLock: XactLock, events: KernelEvents);
54
58
  private get db();
55
59
  /**
56
60
  * The owner org's 可共享 flag of its item, written on the item and (a plugin) every component
@@ -20,10 +20,13 @@ import { loadTemplates, readOwnTemplate, softDeleteTemplateIn } from "../agents/
20
20
  import { ApiError } from "../errors.js";
21
21
  import { audit } from "../identity/audit.js";
22
22
  import { addPlatformNotice } from "../inbox/platform-notices.js";
23
+ import { afterCommit } from "../infra/database/after-commit.js";
23
24
  import { KernelDb } from "../infra/database/kernel-db.js";
24
25
  import { asPlatform } from "../infra/database/org-scope.js";
25
26
  import { TransactionHost } from "../infra/database/transaction-host.js";
26
27
  import { Transactional } from "../infra/database/transactional.decorator.js";
28
+ import { XactLock } from "../infra/database/xact-lock.js";
29
+ import { KernelEvents } from "../infra/events/kernel-events.js";
27
30
  import { KERNEL_LOGGER } from "../infra/tokens.js";
28
31
  import { OrgLock } from "../orgs/org-lock.js";
29
32
  import { SkillsService } from "../skills/skills.service.js";
@@ -32,6 +35,7 @@ import { CatalogService } from "./catalog.service.js";
32
35
  import { CatalogScopeService } from "./catalog-scope.service.js";
33
36
  import { notOwnedError } from "./component-promotion.js";
34
37
  import { agentsUsing, COMPONENT_KINDS, componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "./component-state.js";
38
+ import { EFFECT_CANDIDATES_LOCK } from "./effect-work.js";
35
39
  import { orgsUsing } from "./ownership.js";
36
40
  import { PluginInstaller } from "./plugin-install.js";
37
41
  import { ScopeStillWanted } from "./scope-state.js";
@@ -79,11 +83,13 @@ let OwnedItems = class OwnedItems {
79
83
  skills;
80
84
  log;
81
85
  txHost;
86
+ xactLock;
87
+ events;
82
88
  constructor(kdb, orgLock, catalog, scope,
83
89
  /** The owner org's own uninstall of a removed plugin (ruling P3-41). */
84
90
  installer,
85
91
  /** The owner's org skill row, soft-deleted after its promoted platform row leaves it. */
86
- skills, log, txHost) {
92
+ skills, log, txHost, xactLock, events) {
87
93
  this.kdb = kdb;
88
94
  this.orgLock = orgLock;
89
95
  this.catalog = catalog;
@@ -92,6 +98,8 @@ let OwnedItems = class OwnedItems {
92
98
  this.skills = skills;
93
99
  this.log = log;
94
100
  this.txHost = txHost;
101
+ this.xactLock = xactLock;
102
+ this.events = events;
95
103
  }
96
104
  get db() {
97
105
  return this.kdb.db;
@@ -105,6 +113,7 @@ let OwnedItems = class OwnedItems {
105
113
  * `catalog.shareable_changed`.
106
114
  */
107
115
  async setShareable(orgId, actor, ref, shareable, opts = {}) {
116
+ await this.xactLock.lock(EFFECT_CANDIDATES_LOCK);
108
117
  if (ref.kind !== "plugin") {
109
118
  await this.setComponentShareable(orgId, actor, ref.kind, ref.id, shareable, opts);
110
119
  return;
@@ -361,6 +370,7 @@ let OwnedItems = class OwnedItems {
361
370
  * {@link transferOrRemove} with reason `owner_deleted`.
362
371
  */
363
372
  async delete(orgId, actor, itemId, previewHash, opts = {}) {
373
+ await this.xactLock.lock(EFFECT_CANDIDATES_LOCK);
364
374
  await this.orgLock.lockAndAuthorize(orgId, actor, "catalog.upload");
365
375
  const item = await this.ownedRow(orgId, itemId, true);
366
376
  if ((await this.computeDelete(orgId, item)).previewHash !== previewHash)
@@ -513,6 +523,9 @@ let OwnedItems = class OwnedItems {
513
523
  },
514
524
  });
515
525
  await this.scope.enqueueSync(item.id);
526
+ if (reason === "owner_deleted") {
527
+ afterCommit(() => this.events.emit("catalog.org-intent-changed", {}));
528
+ }
516
529
  return "transferred";
517
530
  }
518
531
  /**
@@ -680,7 +693,7 @@ let OwnedItems = class OwnedItems {
680
693
  .select("id")
681
694
  .where("org_id", "=", owner)
682
695
  .where("item_id", "=", itemId)
683
- .where("status", "=", "installed")
696
+ .where("version", "is not", null)
684
697
  .executeTakeFirst();
685
698
  if (live === undefined)
686
699
  return;
@@ -761,6 +774,8 @@ OwnedItems = __decorate([
761
774
  __param(4, Inject(PluginInstaller)),
762
775
  __param(5, Inject(SkillsService)),
763
776
  __param(6, Inject(KERNEL_LOGGER)),
764
- __param(7, Inject(TransactionHost))
777
+ __param(7, Inject(TransactionHost)),
778
+ __param(8, Inject(XactLock)),
779
+ __param(9, Inject(KernelEvents))
765
780
  ], OwnedItems);
766
781
  export { OwnedItems };
@@ -15,6 +15,7 @@ import { SuperAdminLock } from "../identity/super-admin.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { XactLock } from "../infra/database/xact-lock.js";
18
19
  import { OutboxService } from "../infra/outbox/outbox.service.js";
19
20
  import type { KernelLogger } from "../log.js";
20
21
  import { OrgLock } from "../orgs/org-lock.js";
@@ -421,6 +422,7 @@ export declare class PluginImport {
421
422
  private readonly registry;
422
423
  private readonly log;
423
424
  readonly txHost: TransactionHost;
425
+ private readonly xactLock;
424
426
  /** The platform rows of a new item's components, written in the confirm's transaction. */
425
427
  private readonly platform;
426
428
  /** The item's scope sync, owed by the confirm's commit when it deploys no extension. */
@@ -441,11 +443,11 @@ export declare class PluginImport {
441
443
  /** Reads a package from the package store (confirm recomputes the permission set). */
442
444
  blobs: ExtensionBlobs,
443
445
  /** Config-declared names, loaded connectors and extension versions (the extension registry). */
444
- registry: ExtensionRegistry, log: KernelLogger, txHost: TransactionHost,
446
+ registry: ExtensionRegistry, log: KernelLogger, txHost: TransactionHost, xactLock: XactLock,
445
447
  /** The platform rows of a new item's components, written in the confirm's transaction. */
446
448
  platform: PlatformComponents,
447
449
  /** The item's scope sync, owed by the confirm's commit when it deploys no extension. */
448
- outbox: Pick<OutboxService, "add">);
450
+ outbox: Pick<OutboxService, "add" | "addMany">);
449
451
  /** The kernel-schema handle of the current context (the transaction, else the pool). */
450
452
  private get db();
451
453
  /**
@@ -34,6 +34,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
34
34
  import { asPlatform } from "../infra/database/org-scope.js";
35
35
  import { TransactionHost } from "../infra/database/transaction-host.js";
36
36
  import { Transactional } from "../infra/database/transactional.decorator.js";
37
+ import { XactLock } from "../infra/database/xact-lock.js";
37
38
  import { OutboxService } from "../infra/outbox/outbox.service.js";
38
39
  import { KERNEL_LOGGER } from "../infra/tokens.js";
39
40
  import { OrgLock } from "../orgs/org-lock.js";
@@ -51,6 +52,7 @@ import { CLAUDE_MCP_CONNECTOR } from "./claude/mcp.js";
51
52
  import { item as reportItem, sortItems, } from "./claude/report.js";
52
53
  import { isClaudePluginTree, translateClaudePlugin } from "./claude/translate.js";
53
54
  import { refreshCatalogDependencyEdges } from "./dependency-edges.js";
55
+ import { EFFECT_CANDIDATES_LOCK, oweEffectWork } from "./effect-work.js";
54
56
  import { CatalogItemLock } from "./locks.js";
55
57
  import { requireMarketplacePublisher } from "./marketplace-fetch.js";
56
58
  import { assertNameFree, assertPackageFree, assertShareable, packageOwner, shareGate, usableBy, } from "./ownership.js";
@@ -59,7 +61,6 @@ import { assertDeclarativeUpload, PluginPackageError, readPluginFiles, readPlugi
59
61
  import { OFFICIAL_MARKETPLACE_ID, officialPublisherProofMode } from "./publisher-policy.js";
60
62
  import { hasImportRequests, importRequestOf, resolveImportRequests } from "./request-rules.js";
61
63
  import { assertNameNotReserved } from "./reserved-names.js";
62
- import { oweScopeItem } from "./scope-jobs.js";
63
64
  import { addScopeOrg } from "./scope-orgs.js";
64
65
  import { writeScope } from "./scope-writer.js";
65
66
  import { templateDescriptionText } from "./template-description.js";
@@ -164,6 +165,7 @@ let PluginImport = class PluginImport {
164
165
  registry;
165
166
  log;
166
167
  txHost;
168
+ xactLock;
167
169
  platform;
168
170
  outbox;
169
171
  /** Where plugin files go (the kernel's object storage; the CLI's own, see {@link useCliStorage}). */
@@ -182,7 +184,7 @@ let PluginImport = class PluginImport {
182
184
  /** Reads a package from the package store (confirm recomputes the permission set). */
183
185
  blobs,
184
186
  /** Config-declared names, loaded connectors and extension versions (the extension registry). */
185
- registry, log, txHost,
187
+ registry, log, txHost, xactLock,
186
188
  /** The platform rows of a new item's components, written in the confirm's transaction. */
187
189
  platform,
188
190
  /** The item's scope sync, owed by the confirm's commit when it deploys no extension. */
@@ -202,6 +204,7 @@ let PluginImport = class PluginImport {
202
204
  this.registry = registry;
203
205
  this.log = log;
204
206
  this.txHost = txHost;
207
+ this.xactLock = xactLock;
205
208
  this.platform = platform;
206
209
  this.outbox = outbox;
207
210
  this.files = storage;
@@ -834,6 +837,7 @@ let PluginImport = class PluginImport {
834
837
  const reviewed = review.extension;
835
838
  const stale = () => reviewStale(review);
836
839
  const { owner } = scope;
840
+ await this.xactLock.lock(EFFECT_CANDIDATES_LOCK);
837
841
  await this.authorizeActor(actor, owner);
838
842
  const t = this.db;
839
843
  // The settings writer takes the same super-admin lock. A staged pin-only import
@@ -1049,7 +1053,7 @@ let PluginImport = class PluginImport {
1049
1053
  .where("id", "=", itemId)
1050
1054
  .executeTakeFirstOrThrow();
1051
1055
  if (item.scope !== "optional" || owner !== undefined) {
1052
- await oweScopeItem(this.outbox, t, itemId);
1056
+ await oweEffectWork(this.outbox, t, { itemIds: [itemId] });
1053
1057
  }
1054
1058
  }
1055
1059
  if (selectedVersionChanged)
@@ -1641,8 +1645,9 @@ PluginImport = __decorate([
1641
1645
  __param(13, Inject(ExtensionRegistry)),
1642
1646
  __param(14, Inject(KERNEL_LOGGER)),
1643
1647
  __param(15, Inject(TransactionHost)),
1644
- __param(16, Inject(PlatformComponents)),
1645
- __param(17, Inject(OutboxService))
1648
+ __param(16, Inject(XactLock)),
1649
+ __param(17, Inject(PlatformComponents)),
1650
+ __param(18, Inject(OutboxService))
1646
1651
  ], PluginImport);
1647
1652
  export { PluginImport };
1648
1653
  /**
@@ -1,12 +1,10 @@
1
1
  import { type AgentTemplate, type ConnectorTemplateFile, type PluginManifest } from "@capybara-hq/plugin-sdk";
2
- import type { KernelSchemaDb, PluginInstallStatus, SourceFormat } from "../db/kernel-schema.js";
2
+ import type { KernelSchemaDb, PluginEffectError, PluginInstallStatus, SourceFormat } from "../db/kernel-schema.js";
3
3
  import { OrgExtensionConfigs, type OrgExtensionInput, type OrgExtensionPutOptions } from "../extensions/org-config.js";
4
4
  import { ExtensionRegistry } from "../extensions/registry.js";
5
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
5
  import { KernelDb } from "../infra/database/kernel-db.js";
7
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
8
7
  import { OutboxService } from "../infra/outbox/outbox.service.js";
9
- import type { KernelLogger } from "../log.js";
10
8
  import { OrgLock } from "../orgs/org-lock.js";
11
9
  import type { OrgAction } from "../orgs/roles.js";
12
10
  import { type SkillConflict, SkillsService } from "../skills/skills.service.js";
@@ -79,9 +77,9 @@ export interface UninstallReport {
79
77
  * plugin's skills, connectors or agent templates.
80
78
  */
81
79
  export interface UninstallPreview {
82
- installId: string;
80
+ installId: string | null;
83
81
  name: string;
84
- version: string;
82
+ version: string | null;
85
83
  components: {
86
84
  kind: ComponentKind;
87
85
  ref: string;
@@ -109,15 +107,11 @@ export interface PluginInstallView {
109
107
  id: string;
110
108
  itemId: string;
111
109
  name: string;
112
- version: string;
110
+ version: string | null;
113
111
  status: PluginInstallStatus;
114
112
  installedBy: string | null;
115
113
  installedAt: string;
116
- /** The failed install's step and code, or the last failed upgrade's (the install stays installed). */
117
- error: {
118
- step: string;
119
- code: string;
120
- } | null;
114
+ error: PluginEffectError | null;
121
115
  /**
122
116
  * `dropped`: an upgrade removed it from the plugin but kept it because an agent uses it ("no
123
117
  * longer in the plugin"); uninstalling still removes it once nothing uses it.
@@ -268,10 +262,8 @@ export declare class PluginInstaller {
268
262
  private readonly skills;
269
263
  private readonly orgConfigs;
270
264
  private readonly scopeWriter;
271
- private readonly config;
272
265
  /** Org connectors: installs create, upgrade and remove them. */
273
266
  private readonly connectors;
274
- private readonly log;
275
267
  /** Owes the template connector ensure of an install's commit (`markInstalled`). */
276
268
  private readonly outbox;
277
269
  readonly txHost: TransactionHost;
@@ -279,15 +271,13 @@ export declare class PluginInstaller {
279
271
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
280
272
  orgLock: OrgLock, storage: StorageService,
281
273
  /** The loaded extensions and connectors of this replica (the extension registry). */
282
- registry: ExtensionRegistry, skills: SkillsService, orgConfigs: OrgExtensionConfigs, scopeWriter: ScopeWriter, config: KernelConfigService,
274
+ registry: ExtensionRegistry, skills: SkillsService, orgConfigs: OrgExtensionConfigs, scopeWriter: ScopeWriter,
283
275
  /** Org connectors: installs create, upgrade and remove them. */
284
- connectors: ConnectorsService, log: KernelLogger,
276
+ connectors: ConnectorsService,
285
277
  /** Owes the template connector ensure of an install's commit (`markInstalled`). */
286
278
  outbox: Pick<OutboxService, "add">, txHost: TransactionHost);
287
279
  /** The kernel-schema handle of the current context (the transaction, else the pool). */
288
280
  private get db();
289
- /** `catalog.staleInstallMinutes`: an install `installing` for longer can be cleaned up by uninstalling it. */
290
- staleInstallMinutes(): number;
291
281
  /**
292
282
  * The checks an install runs before it creates anything, without the org's input (for the org
293
283
  * catalog to run before a request is created): dependency resolution, the extensions deployed and
@@ -301,7 +291,9 @@ export declare class PluginInstaller {
301
291
  auditDetail?: AuditDetail;
302
292
  switchOn?: boolean;
303
293
  via?: "scope";
304
- }): Promise<PluginInstallView>;
294
+ }): Promise<PluginInstallView | null>;
295
+ private effectGeneration;
296
+ private recordInstallFailure;
305
297
  /**
306
298
  * Refuses a plan whose skills would overwrite a skill of other provenance (spec §9.2, Decision
307
299
  * 8) with 409 `plugin.skill_conflict`, before anything is written: for the plugin and each
@@ -395,27 +387,12 @@ export declare class PluginInstaller {
395
387
  switchOn?: boolean;
396
388
  /** Installed by the plugin scope sync (recorded in the audits). */
397
389
  via?: "scope";
398
- }): Promise<string>;
399
- /**
400
- * The install row (role and item policy re-checked under the lock; one live install per org and
401
- * item). A step of the install: committed on its own.
402
- */
403
- /**
404
- * Enables a plugin's extension for the org and records it as a component of the install, in one
405
- * transaction (`put` joins it): "enabled before" is decided under the org row lock (already
406
- * enabled: `put` writes nothing, the config is untouched, the component is recorded as not
407
- * created), and the ledger row is written before the COMMIT, so no concurrent uninstall fits
408
- * between enabling and recording. Used only by a fresh install (and a dependency the install or a
409
- * platform update adds): a platform update of an installed plugin and switching an installed
410
- * plugin on again never call it, so an extension the org switched off stays off (extension switch
411
- * spec 2026-12-02 §3.2).
412
- */
413
- enableExtension(orgId: string, name: string, input: OrgExtensionInput, actor: string | null, actorTokenId: string | undefined, opts: Pick<OrgExtensionPutOptions, "viaItem" | "approvedBy">, record: (c: Component) => Promise<void>): Promise<void>;
390
+ }): Promise<string | null>;
391
+ /** Validates extension setup and owes connector discovery in the caller's transaction. */
392
+ enableExtension(orgId: string, name: string, input: OrgExtensionInput, actor: string | null, actorTokenId: string | undefined, opts: Pick<OrgExtensionPutOptions, "viaItem" | "approvedBy">): Promise<void>;
414
393
  private createInstallRow;
415
394
  /** The install `installed` and its `plugin.org_installed` audit, under the org row lock (its own transaction). */
416
395
  private markInstalled;
417
- /** The install `failed` with `{ step, code }` and its `plugin.org_install_failed` audit (its own transaction). */
418
- private markFailed;
419
396
  /**
420
397
  * The extension to enable: the plugin's own, when it has one. Not loaded on this replica ->
421
398
  * `catalog.not_deployed`; not yet enabled in this org while its own catalog item is disabled ->
@@ -423,20 +400,6 @@ export declare class PluginInstaller {
423
400
  * unaffected.
424
401
  */
425
402
  planExtension(orgId: string, manifest: PluginManifest): Promise<string | null>;
426
- /**
427
- * Undoes the components this install created, in reverse order (the role is not re-checked: it
428
- * undoes this install's own changes); returns the ones that failed. The component rows of undone
429
- * (or already gone) components are deleted in the same transaction, so cleaning up the failed
430
- * install later only handles what failed to undo or was kept, and does not undo again an extension
431
- * an org admin re-enabled by hand or a skill version a user uploaded since.
432
- */
433
- private rollback;
434
- /**
435
- * Undoes one component of a failed install and deletes its component row, under the org row lock,
436
- * in a transaction of its own (committed when it returns); returns the extensions it disabled
437
- * (the caller notifies them).
438
- */
439
- private rollbackOne;
440
403
  /** Removes one component (one already gone is no error); returns whether anything changed. */
441
404
  removeComponent(orgId: string, actor: string | null, c: Component, reason: string): Promise<boolean>;
442
405
  /**
@@ -588,7 +551,7 @@ export declare class PluginInstaller {
588
551
  * the item whose status is one of `statuses` (`created`: the plugin made it, so an uninstall and
589
552
  * upgrades see it), in the caller's transaction. True when such an install exists.
590
553
  */
591
- recordTemplateConnectorIn(orgId: string, itemId: string, connectorId: string, templateId: string, statuses: readonly PluginInstallStatus[]): Promise<boolean>;
554
+ recordTemplateConnectorIn(orgId: string, itemId: string, connectorId: string, templateId: string): Promise<boolean>;
592
555
  /**
593
556
  * Records a connector made from a plugin's template on the org's live install of that plugin,
594
557
  * when there is one, under the org lock (so an uninstall in between is seen).
@@ -613,6 +576,9 @@ export declare class PluginInstaller {
613
576
  * update keeps copies of removed components).
614
577
  */
615
578
  previewUninstall(orgId: string, installId: string): Promise<UninstallPreview>;
579
+ /** A pure content plugin can take components away without an org install row. */
580
+ previewContentOff(orgId: string, itemId: string): Promise<UninstallPreview | null>;
581
+ private previewRemoval;
616
582
  /**
617
583
  * The connectors, skills (selected, pinned, or in an inline sub-agent template) and agent
618
584
  * templates (`subagents.templates`) referenced by the current definitions of the org's live