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

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/extensions.controller.d.ts +5 -2
  3. package/dist/admin/extensions.controller.js +10 -1
  4. package/dist/admin/extensions.schemas.d.ts +4 -0
  5. package/dist/admin/extensions.schemas.js +9 -0
  6. package/dist/admin/health.service.d.ts +1 -1
  7. package/dist/admin/health.service.js +3 -3
  8. package/dist/catalog/catalog-content.d.ts +5 -7
  9. package/dist/catalog/catalog-items.js +1 -1
  10. package/dist/catalog/catalog-scope.service.js +5 -5
  11. package/dist/catalog/catalog.module.js +5 -4
  12. package/dist/catalog/catalog.service.d.ts +7 -1
  13. package/dist/catalog/catalog.service.js +19 -2
  14. package/dist/catalog/effect-work.d.ts +27 -0
  15. package/dist/catalog/effect-work.js +151 -0
  16. package/dist/catalog/jobs.d.ts +4 -1
  17. package/dist/catalog/jobs.js +14 -4
  18. package/dist/catalog/org-catalog.service.d.ts +2 -0
  19. package/dist/catalog/org-catalog.service.js +68 -12
  20. package/dist/catalog/org-intent.d.ts +4 -2
  21. package/dist/catalog/org-intent.js +25 -4
  22. package/dist/catalog/owned-items.d.ts +5 -1
  23. package/dist/catalog/owned-items.js +18 -3
  24. package/dist/catalog/plugin-import.d.ts +4 -2
  25. package/dist/catalog/plugin-import.js +10 -5
  26. package/dist/catalog/plugin-install.d.ts +17 -51
  27. package/dist/catalog/plugin-install.js +209 -235
  28. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  29. package/dist/catalog/plugin-upgrade.js +63 -34
  30. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  31. package/dist/catalog/scope-sync-workers.js +10 -26
  32. package/dist/catalog/scope-sync.d.ts +19 -114
  33. package/dist/catalog/scope-sync.js +220 -239
  34. package/dist/catalog/scope-writer.d.ts +10 -1
  35. package/dist/catalog/scope-writer.js +62 -4
  36. package/dist/catalog/template-connector-ensure.js +1 -1
  37. package/dist/catalog/unshare.js +1 -2
  38. package/dist/config/schema.d.ts +1 -1
  39. package/dist/config/schema.js +7 -4
  40. package/dist/db/kernel-schema.d.ts +18 -17
  41. package/dist/erasure/org-catalog.js +2 -2
  42. package/dist/erasure/org-rules.js +2 -2
  43. package/dist/extensions/admin-ops.d.ts +1 -1
  44. package/dist/extensions/admin-ops.js +1 -1
  45. package/dist/extensions/admin-view.d.ts +4 -1
  46. package/dist/extensions/admin-view.js +27 -11
  47. package/dist/extensions/bootstrap.d.ts +1 -1
  48. package/dist/extensions/bootstrap.js +2 -3
  49. package/dist/extensions/enabled.d.ts +159 -0
  50. package/dist/extensions/enabled.js +7 -0
  51. package/dist/extensions/host.d.ts +1 -0
  52. package/dist/extensions/host.js +5 -2
  53. package/dist/extensions/isolated/authorization.d.ts +8 -0
  54. package/dist/extensions/isolated/authorization.js +56 -11
  55. package/dist/extensions/isolated/broker.js +30 -11
  56. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  57. package/dist/extensions/isolated/engine-binds.js +82 -0
  58. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  59. package/dist/extensions/isolated/engine-policy.js +75 -0
  60. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  61. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  62. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  63. package/dist/extensions/isolated/engine-proxy.js +408 -0
  64. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  65. package/dist/extensions/isolated/engine-vaults.js +93 -0
  66. package/dist/extensions/isolated/lanes.d.ts +11 -3
  67. package/dist/extensions/isolated/lanes.js +43 -16
  68. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  69. package/dist/extensions/isolated/postgres-gate.js +6 -6
  70. package/dist/extensions/isolated/revision.d.ts +1 -1
  71. package/dist/extensions/isolated/revision.js +3 -2
  72. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  73. package/dist/extensions/isolated/sandbox.js +101 -117
  74. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  75. package/dist/extensions/lifecycle-topics.js +1 -0
  76. package/dist/extensions/lifecycle.js +23 -2
  77. package/dist/extensions/permission-view.d.ts +6 -1
  78. package/dist/inbox/platform-inbox.service.js +16 -27
  79. package/dist/infra/events/kernel-events.d.ts +4 -0
  80. package/dist/infra/outbox/registry.d.ts +3 -36
  81. package/dist/infra/outbox/registry.js +4 -49
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -1
  84. package/dist/orgs/org-lock.d.ts +3 -1
  85. package/dist/orgs/org-lock.js +3 -1
  86. package/dist/orgs/orgs.service.d.ts +3 -1
  87. package/dist/orgs/orgs.service.js +15 -8
  88. package/dist/overrides.d.ts +0 -3
  89. package/dist/overrides.js +0 -2
  90. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  91. package/dist/platform/ops/org-plugins.ops.js +5 -2
  92. package/dist/platform/ops/plugins.ops.js +11 -10
  93. package/dist/tools/registry.d.ts +1 -1
  94. package/dist/tools/registry.js +6 -2
  95. package/package.json +2 -2
  96. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  97. package/src/migrations/0232_contract_plugin_effect_schema.sql +49 -0
  98. package/dist/catalog/install-status.d.ts +0 -5
  99. package/dist/catalog/install-status.js +0 -5
  100. package/dist/catalog/scope-jobs.d.ts +0 -59
  101. package/dist/catalog/scope-jobs.js +0 -78
@@ -0,0 +1,151 @@
1
+ import { sql } from "kysely";
2
+ import { asPlatform } from "../infra/database/org-scope.js";
3
+ export const PLUGIN_EFFECT_QUEUE = "cap-kernel-plugin-effects";
4
+ export const PLUGIN_EFFECT_JOB = "plugin-effect";
5
+ export const EFFECT_CANDIDATES_LOCK = "capybara.plugin-effect-candidates";
6
+ const pairPrefix = (itemId, orgId) => `${itemId}-${orgId}-`;
7
+ export function effectGeneration(jobId, { itemId, orgIds }) {
8
+ const orgId = orgIds[0];
9
+ const prefix = pairPrefix(itemId, orgId);
10
+ const generation = jobId.slice(prefix.length);
11
+ if (orgIds.length !== 1 ||
12
+ !orgId ||
13
+ !jobId.startsWith(prefix) ||
14
+ jobId.includes(":") ||
15
+ !/^[1-9][0-9]{0,18}$/.test(generation) ||
16
+ BigInt(generation) > 9223372036854775807n) {
17
+ throw new Error("invalid plugin effect job id");
18
+ }
19
+ return generation;
20
+ }
21
+ async function owePairs(outbox, pairs) {
22
+ await outbox.addMany(pairs.map(({ item_id: itemId, org_id: orgId, generation }) => ({
23
+ queue: PLUGIN_EFFECT_QUEUE,
24
+ name: PLUGIN_EFFECT_JOB,
25
+ jobId: `${pairPrefix(itemId, orgId)}${generation}`,
26
+ data: { kind: "chunk", itemId, orgIds: [orgId] },
27
+ orgId,
28
+ })));
29
+ }
30
+ /** Selects sparse intent or ownership first. Only an all-scope root needs the org census. */
31
+ export async function oweEffectWork(outbox, db, mutation) {
32
+ const itemIds = "itemIds" in mutation ? [...mutation.itemIds] : null;
33
+ if (itemIds?.length === 0)
34
+ return;
35
+ const previousOrgs = "itemIds" in mutation ? [...(mutation.previousOrgs ?? [])] : [];
36
+ const orgId = mutation.orgId ?? null;
37
+ const includeDependents = !("itemIds" in mutation) || mutation.includeDependents !== false;
38
+ // org-filter: deployment-wide effect candidates derived from a single committed intent graph.
39
+ await asPlatform("Select affected plugin effect pairs", async () => {
40
+ const { rows } = await sql `
41
+ WITH RECURSIVE affected(id) AS (
42
+ SELECT id FROM capybara.catalog_items
43
+ WHERE (${itemIds}::uuid[] IS NULL OR id = ANY(${itemIds}::uuid[]))
44
+ UNION
45
+ SELECT edge.item_id
46
+ FROM capybara.catalog_dependency_edges AS edge
47
+ JOIN affected ON affected.id = edge.dependency_item_id
48
+ WHERE ${includeDependents}::boolean
49
+ ), subjects AS (
50
+ SELECT item.id, item.scope, item.owner_org_id, item.shareable, item.deleted_at
51
+ FROM affected
52
+ JOIN capybara.catalog_items AS item USING (id)
53
+ WHERE NOT item.builtin
54
+ ), candidates(item_id, org_id) AS (
55
+ SELECT subjects.id, org.id
56
+ FROM subjects CROSS JOIN capybara.orgs AS org
57
+ WHERE subjects.scope = 'all' AND subjects.deleted_at IS NULL
58
+ AND (subjects.owner_org_id IS NULL OR subjects.owner_org_id = org.id OR subjects.shareable)
59
+ AND (${orgId}::text IS NULL OR org.id = ${orgId})
60
+ UNION
61
+ SELECT named.item_id, named.org_id
62
+ FROM capybara.catalog_item_scope_orgs AS named
63
+ JOIN subjects ON subjects.id = named.item_id
64
+ UNION
65
+ SELECT choice.item_id, choice.org_id
66
+ FROM capybara.catalog_item_org_switches AS choice
67
+ JOIN subjects ON subjects.id = choice.item_id
68
+ UNION
69
+ SELECT template.catalog_item_id, org.id
70
+ FROM capybara.platform_connector_templates AS template
71
+ JOIN subjects ON subjects.id = template.catalog_item_id
72
+ CROSS JOIN capybara.orgs AS org
73
+ WHERE template.scope_mode = 'own' AND template.scope = 'all'
74
+ AND template.deleted_at IS NULL AND NOT template.disabled
75
+ AND (template.owner_org_id IS NULL OR template.owner_org_id = org.id OR template.shareable)
76
+ AND (${orgId}::text IS NULL OR org.id = ${orgId})
77
+ UNION
78
+ SELECT template.catalog_item_id, named.org_id
79
+ FROM capybara.platform_connector_templates AS template
80
+ JOIN subjects ON subjects.id = template.catalog_item_id
81
+ JOIN capybara.component_scope_orgs AS named
82
+ ON named.kind = 'connector_template' AND named.component_id = template.id
83
+ UNION
84
+ SELECT template.catalog_item_id, choice.org_id
85
+ FROM capybara.platform_connector_templates AS template
86
+ JOIN subjects ON subjects.id = template.catalog_item_id
87
+ JOIN capybara.component_org_switches AS choice
88
+ ON choice.kind = 'connector_template' AND choice.component_id = template.id
89
+ UNION
90
+ SELECT inst.item_id, inst.org_id
91
+ FROM capybara.plugin_installs AS inst
92
+ JOIN subjects ON subjects.id = inst.item_id
93
+ UNION
94
+ SELECT work.item_id, work.org_id
95
+ FROM capybara.plugin_effect_work AS work
96
+ JOIN subjects ON subjects.id = work.item_id
97
+ WHERE work.state = 'pending'
98
+ UNION
99
+ SELECT subjects.id, old.org_id
100
+ FROM subjects CROSS JOIN unnest(${previousOrgs}::text[]) AS old(org_id)
101
+ )
102
+ INSERT INTO capybara.plugin_effect_work (item_id, org_id, generation, state, generation_started_at, updated_at)
103
+ SELECT candidate.item_id, candidate.org_id, 1, 'pending',
104
+ statement_timestamp(), statement_timestamp()
105
+ FROM candidates AS candidate
106
+ JOIN capybara.orgs AS org ON org.id = candidate.org_id AND org.deleted_at IS NULL
107
+ WHERE ${orgId}::text IS NULL OR candidate.org_id = ${orgId}
108
+ ORDER BY candidate.item_id, candidate.org_id
109
+ ON CONFLICT (item_id, org_id) DO UPDATE
110
+ SET generation = plugin_effect_work.generation + 1,
111
+ state = 'pending',
112
+ generation_started_at = EXCLUDED.generation_started_at,
113
+ updated_at = EXCLUDED.updated_at
114
+ -- Multiple writes in the same transaction owe its final state once.
115
+ WHERE plugin_effect_work.xmin <> pg_current_xact_id()::xid
116
+ RETURNING item_id, org_id, generation
117
+ `.execute(db);
118
+ await owePairs(outbox, rows);
119
+ });
120
+ }
121
+ /** Re-owes the same generation if a worker did not settle it. */
122
+ export async function recoverEffectWork(outbox, db) {
123
+ // org-filter: deployment-wide stale effect pairs; the job itself enters the pair's org scope.
124
+ await asPlatform("Recover stale plugin effect pairs", async () => {
125
+ const { rows } = await sql `
126
+ WITH stale AS (
127
+ SELECT item_id, org_id FROM capybara.plugin_effect_work
128
+ WHERE state = 'pending' AND updated_at < statement_timestamp() - INTERVAL '2 minutes'
129
+ ORDER BY updated_at, item_id, org_id
130
+ LIMIT 100
131
+ FOR UPDATE SKIP LOCKED
132
+ )
133
+ UPDATE capybara.plugin_effect_work AS work SET updated_at = statement_timestamp()
134
+ FROM stale WHERE work.item_id = stale.item_id AND work.org_id = stale.org_id
135
+ RETURNING work.item_id, work.org_id, work.generation
136
+ `.execute(db);
137
+ await owePairs(outbox, rows);
138
+ });
139
+ }
140
+ /** Resolve a deployed extension's live catalog item before owing its affected pairs. */
141
+ export async function oweDeployedExtensionSync(outbox, db, extensionName) {
142
+ const item = await db
143
+ .selectFrom("catalog_items")
144
+ .select("id")
145
+ .where("name", "=", extensionName)
146
+ .where("deleted_at", "is", null)
147
+ .where("builtin", "=", false)
148
+ .executeTakeFirst();
149
+ if (item)
150
+ await oweEffectWork(outbox, db, { itemIds: [item.id] });
151
+ }
@@ -3,6 +3,7 @@ import { LockService } from "../infra/lock/lock.service.js";
3
3
  import type { KernelLogger } from "../log.js";
4
4
  import { MarketplacesService } from "./marketplaces.service.js";
5
5
  import { PluginImport } from "./plugin-import.js";
6
+ import { PluginScopeSync } from "./scope-sync.js";
6
7
  import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
7
8
  /**
8
9
  * The catalog's periodic jobs, each run once per tick across replicas: the marketplace refresh
@@ -15,10 +16,11 @@ export declare class CatalogJobs {
15
16
  private readonly marketplaces;
16
17
  private readonly imports;
17
18
  private readonly templateConnectors;
19
+ private readonly pluginEffects;
18
20
  readonly config: KernelConfigService;
19
21
  readonly lockService: LockService;
20
22
  readonly log: KernelLogger;
21
- constructor(marketplaces: MarketplacesService, imports: PluginImport, templateConnectors: TemplateConnectorEnsurer, config: KernelConfigService, lockService: LockService, log: KernelLogger);
23
+ constructor(marketplaces: MarketplacesService, imports: PluginImport, templateConnectors: TemplateConnectorEnsurer, pluginEffects: PluginScopeSync, config: KernelConfigService, lockService: LockService, log: KernelLogger);
22
24
  /**
23
25
  * Refreshes every enabled marketplace in turn (overall deadline
24
26
  * {@link MARKETPLACES_REFRESH_DEADLINE_MS}; the job's signal aborts it: the stop, or the run
@@ -31,6 +33,7 @@ export declare class CatalogJobs {
31
33
  * each connector is created in its own (`TemplateConnectorEnsurer`).
32
34
  */
33
35
  sweepTemplateConnectors(stop?: AbortSignal): Promise<void>;
36
+ recoverPluginEffects(): Promise<void>;
34
37
  /** Deletes expired staging rows and their objects. */
35
38
  cleanupStaging(): Promise<void>;
36
39
  }
@@ -16,6 +16,7 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
16
16
  import { MARKETPLACES_REFRESH_JOB, PLUGIN_STAGING_CLEANUP_JOB, TEMPLATE_CONNECTORS_SWEEP_BATCH, TEMPLATE_CONNECTORS_SWEEP_JOB, TEMPLATE_CONNECTORS_SWEEP_PERIOD_MS, } from "./job-ids.js";
17
17
  import { MARKETPLACES_REFRESH_DEADLINE_MS, MarketplacesService } from "./marketplaces.service.js";
18
18
  import { PluginImport } from "./plugin-import.js";
19
+ import { PluginScopeSync } from "./scope-sync.js";
19
20
  import { TemplateConnectorEnsurer } from "./template-connector-ensure.js";
20
21
  /**
21
22
  * The catalog's periodic jobs, each run once per tick across replicas: the marketplace refresh
@@ -28,13 +29,15 @@ let CatalogJobs = class CatalogJobs {
28
29
  marketplaces;
29
30
  imports;
30
31
  templateConnectors;
32
+ pluginEffects;
31
33
  config;
32
34
  lockService;
33
35
  log;
34
- constructor(marketplaces, imports, templateConnectors, config, lockService, log) {
36
+ constructor(marketplaces, imports, templateConnectors, pluginEffects, config, lockService, log) {
35
37
  this.marketplaces = marketplaces;
36
38
  this.imports = imports;
37
39
  this.templateConnectors = templateConnectors;
40
+ this.pluginEffects = pluginEffects;
38
41
  this.config = config;
39
42
  this.lockService = lockService;
40
43
  this.log = log;
@@ -61,6 +64,9 @@ let CatalogJobs = class CatalogJobs {
61
64
  if (r.created > 0)
62
65
  this.log.info("template connector sweep created connectors", r);
63
66
  }
67
+ async recoverPluginEffects() {
68
+ await this.pluginEffects.recover();
69
+ }
64
70
  /** Deletes expired staging rows and their objects. */
65
71
  async cleanupStaging() {
66
72
  const n = await this.imports.cleanupExpired();
@@ -76,6 +82,9 @@ __decorate([
76
82
  __decorate([
77
83
  LockedInterval(TEMPLATE_CONNECTORS_SWEEP_JOB, () => TEMPLATE_CONNECTORS_SWEEP_PERIOD_MS)
78
84
  ], CatalogJobs.prototype, "sweepTemplateConnectors", null);
85
+ __decorate([
86
+ LockedInterval("plugin-effect-recovery", () => 10_000)
87
+ ], CatalogJobs.prototype, "recoverPluginEffects", null);
79
88
  __decorate([
80
89
  LockedCron("0 * * * *", { name: PLUGIN_STAGING_CLEANUP_JOB })
81
90
  ], CatalogJobs.prototype, "cleanupStaging", null);
@@ -84,8 +93,9 @@ CatalogJobs = __decorate([
84
93
  __param(0, Inject(MarketplacesService)),
85
94
  __param(1, Inject(PluginImport)),
86
95
  __param(2, Inject(TemplateConnectorEnsurer)),
87
- __param(3, Inject(KernelConfigService)),
88
- __param(4, Inject(LockService)),
89
- __param(5, Inject(KERNEL_LOGGER))
96
+ __param(3, Inject(PluginScopeSync)),
97
+ __param(4, Inject(KernelConfigService)),
98
+ __param(5, Inject(LockService)),
99
+ __param(6, Inject(KERNEL_LOGGER))
90
100
  ], CatalogJobs);
91
101
  export { CatalogJobs };
@@ -119,6 +119,8 @@ export declare class OrgCatalogService {
119
119
  uninstall(orgId: string, actor: string, installId: string, actorTokenId?: string,
120
120
  /** Merged into the audit detail (a write made through the Platform tool). */
121
121
  auditDetail?: Record<string, unknown>): Promise<UninstallReport>;
122
+ /** The switch-off impact even when there are no applied org resources. */
123
+ previewContentOff(orgId: string, itemId: string): Promise<UninstallPreview | null>;
122
124
  private itemOf;
123
125
  /**
124
126
  * Writes the org's switch row of the item under the org row lock. The item row is locked FOR
@@ -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
  /**