@capybara-hq/kernel 0.1.0-rc.145 → 0.1.0-rc.147

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 (185) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +71 -0
  34. package/dist/catalog/provenance.js +112 -0
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/create-ctx.d.ts +16 -0
  45. package/dist/ctx/create-ctx.js +269 -34
  46. package/dist/ctx/net.d.ts +5 -1
  47. package/dist/ctx/net.js +62 -12
  48. package/dist/db/kernel-schema.d.ts +31 -0
  49. package/dist/db/migrator.js +0 -36
  50. package/dist/dial-in/routes.js +1 -1
  51. package/dist/erasure/org-batches.js +1 -6
  52. package/dist/erasure/org-catalog.js +6 -2
  53. package/dist/erasure/org-rules.js +1 -0
  54. package/dist/erasure/org-worker.js +0 -13
  55. package/dist/errors.d.ts +6 -0
  56. package/dist/errors.js +6 -0
  57. package/dist/extensions/admin-ops.d.ts +14 -1
  58. package/dist/extensions/admin-ops.js +30 -3
  59. package/dist/extensions/admin-view.d.ts +21 -1
  60. package/dist/extensions/admin-view.js +43 -0
  61. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  62. package/dist/extensions/bootstrap-packages.js +1 -1
  63. package/dist/extensions/bootstrap-review.d.ts +251 -0
  64. package/dist/extensions/bootstrap-review.js +676 -0
  65. package/dist/extensions/bootstrap.d.ts +21 -1
  66. package/dist/extensions/bootstrap.js +72 -2
  67. package/dist/extensions/cli.d.ts +6 -0
  68. package/dist/extensions/cli.js +4 -0
  69. package/dist/extensions/enabled.d.ts +3 -0
  70. package/dist/extensions/execution-realm.d.ts +96 -0
  71. package/dist/extensions/execution-realm.js +141 -0
  72. package/dist/extensions/extensions.module.js +12 -0
  73. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  74. package/dist/extensions/full-access-disclosure.js +57 -0
  75. package/dist/extensions/grant-epoch.d.ts +9 -2
  76. package/dist/extensions/grant-epoch.js +13 -2
  77. package/dist/extensions/host.d.ts +96 -4
  78. package/dist/extensions/host.js +411 -33
  79. package/dist/extensions/installs.d.ts +18 -0
  80. package/dist/extensions/installs.js +28 -0
  81. package/dist/extensions/instance.d.ts +2 -0
  82. package/dist/extensions/instance.js +1 -0
  83. package/dist/extensions/isolated/admission.d.ts +23 -2
  84. package/dist/extensions/isolated/admission.js +32 -7
  85. package/dist/extensions/isolated/authorization.d.ts +8 -2
  86. package/dist/extensions/isolated/authorization.js +11 -3
  87. package/dist/extensions/isolated/broker.d.ts +3 -0
  88. package/dist/extensions/isolated/broker.js +50 -14
  89. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  90. package/dist/extensions/isolated/configured-package.js +2 -0
  91. package/dist/extensions/isolated/lanes.d.ts +44 -3
  92. package/dist/extensions/isolated/lanes.js +263 -80
  93. package/dist/extensions/isolated/metrics.d.ts +146 -0
  94. package/dist/extensions/isolated/metrics.js +304 -0
  95. package/dist/extensions/isolated/revision.d.ts +7 -1
  96. package/dist/extensions/isolated/revision.js +26 -5
  97. package/dist/extensions/isolated/rpc.d.ts +5 -0
  98. package/dist/extensions/isolated/rpc.js +7 -2
  99. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  100. package/dist/extensions/isolated/sandbox.js +50 -0
  101. package/dist/extensions/isolated/status.d.ts +79 -0
  102. package/dist/extensions/isolated/status.js +216 -0
  103. package/dist/extensions/isolated/tier.d.ts +127 -2
  104. package/dist/extensions/isolated/tier.js +266 -7
  105. package/dist/extensions/isolated/usage.d.ts +134 -0
  106. package/dist/extensions/isolated/usage.js +322 -0
  107. package/dist/extensions/ledger.d.ts +5 -0
  108. package/dist/extensions/ledger.js +16 -0
  109. package/dist/extensions/lifecycle.d.ts +42 -2
  110. package/dist/extensions/lifecycle.js +100 -4
  111. package/dist/extensions/org-config.js +11 -0
  112. package/dist/extensions/package.d.ts +14 -0
  113. package/dist/extensions/package.js +23 -0
  114. package/dist/extensions/permission-view.d.ts +2 -2
  115. package/dist/extensions/permissions.controller.d.ts +35 -0
  116. package/dist/extensions/permissions.controller.js +98 -0
  117. package/dist/extensions/permissions.schemas.d.ts +288 -0
  118. package/dist/extensions/permissions.schemas.js +96 -0
  119. package/dist/extensions/permissions.service.d.ts +116 -0
  120. package/dist/extensions/permissions.service.js +428 -0
  121. package/dist/extensions/realm-retirement.d.ts +65 -0
  122. package/dist/extensions/realm-retirement.js +150 -0
  123. package/dist/extensions/registry.d.ts +6 -0
  124. package/dist/extensions/registry.js +8 -0
  125. package/dist/extensions/review-hash.d.ts +114 -0
  126. package/dist/extensions/review-hash.js +145 -0
  127. package/dist/extensions/revision-approvals.d.ts +58 -3
  128. package/dist/extensions/revision-approvals.js +135 -14
  129. package/dist/extensions/revision-grants.d.ts +10 -0
  130. package/dist/extensions/revision-review.d.ts +144 -0
  131. package/dist/extensions/revision-review.js +297 -0
  132. package/dist/extensions/revocation-leases.d.ts +273 -0
  133. package/dist/extensions/revocation-leases.js +533 -0
  134. package/dist/extensions/revocation.d.ts +78 -0
  135. package/dist/extensions/revocation.js +205 -0
  136. package/dist/extensions/state.module.js +12 -0
  137. package/dist/git/run-end.d.ts +35 -7
  138. package/dist/git/run-end.js +87 -38
  139. package/dist/http/api.module.js +2 -0
  140. package/dist/identity/audit.d.ts +2 -1
  141. package/dist/identity/audit.js +4 -17
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +10 -2
  144. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  145. package/dist/infra/config/kernel-config.service.js +21 -0
  146. package/dist/infra/outbox/registry.d.ts +13 -0
  147. package/dist/infra/outbox/registry.js +8 -0
  148. package/dist/lifecycle/kernel-lifecycle.d.ts +27 -1
  149. package/dist/lifecycle/kernel-lifecycle.js +83 -22
  150. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  151. package/dist/net/private-endpoint-preflight.js +417 -0
  152. package/dist/net/private-endpoints.d.ts +68 -0
  153. package/dist/net/private-endpoints.js +164 -0
  154. package/dist/net/public-address.d.ts +14 -0
  155. package/dist/net/public-address.js +15 -1
  156. package/dist/net/safe-fetch.d.ts +2 -1
  157. package/dist/net/safe-fetch.js +10 -3
  158. package/dist/overrides.d.ts +9 -1
  159. package/dist/overrides.js +4 -0
  160. package/dist/packages/official-publisher.d.ts +65 -1
  161. package/dist/packages/official-publisher.js +171 -46
  162. package/dist/packages/provenance.d.ts +11 -0
  163. package/dist/packages/provenance.js +24 -0
  164. package/dist/platform/exclusions.js +4 -4
  165. package/dist/platform/ops/automations.ops.js +1 -1
  166. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  167. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  168. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  169. package/dist/platform/platform-ops.module.d.ts +2 -1
  170. package/dist/platform/platform-ops.module.js +2 -0
  171. package/dist/platform/route-schemas.js +2 -0
  172. package/dist/retention/purge-batch.js +10 -14
  173. package/dist/runtime/maintenance.d.ts +4 -2
  174. package/dist/runtime/maintenance.js +16 -3
  175. package/dist/runtime/run-finish.d.ts +3 -3
  176. package/dist/runtime/run-finish.js +7 -3
  177. package/dist/sandbox/permission-availability.d.ts +17 -2
  178. package/dist/sandbox/permission-availability.js +22 -1
  179. package/dist/sandbox/permission-facts.js +7 -1
  180. package/dist/tools/builtins/sandbox/common.js +2 -0
  181. package/dist/tools/pipeline.d.ts +2 -1
  182. package/dist/tools/pipeline.js +7 -2
  183. package/package.json +4 -3
  184. package/src/migrations/0238_extension_usage.sql +40 -0
  185. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -1637,6 +1637,34 @@ export interface ExtensionGrantEpochTable {
1637
1637
  epoch: Generated<string>;
1638
1638
  changed_at: Generated<Date>;
1639
1639
  }
1640
+ /**
1641
+ * Isolated extension usage counters (migration 0238): one row per org, plugin, hour and counter,
1642
+ * incremented by each replica's 10 s flush (`extensions/isolated/usage.ts`).
1643
+ */
1644
+ export interface ExtensionUsageTable {
1645
+ org_id: string;
1646
+ plugin: string;
1647
+ hour: Ts;
1648
+ counter: string;
1649
+ /** bigint; pg returns it as a string. */
1650
+ amount: Int8;
1651
+ }
1652
+ /** The flush batches already applied (migration 0238): makes a retried batch count once. */
1653
+ export interface ExtensionUsageBatchesTable {
1654
+ id: string;
1655
+ flushed_at: Generated<Date>;
1656
+ }
1657
+ /** 0239: each replica's isolation supervisor readiness and shadow placements (plan task 1.4j). */
1658
+ export interface ExtensionReplicaIsolationTable {
1659
+ replica_id: string;
1660
+ state: "available" | "failing" | "not_configured";
1661
+ failed_check: "guard_reachability" | "engine_runtime" | "image" | "postgres_socket" | null;
1662
+ message: string | null;
1663
+ shadow: ColumnType<unknown[], string | undefined, string>;
1664
+ http_replica_id: string | null;
1665
+ probed_at: TsNullable;
1666
+ heartbeat_at: Generated<Date>;
1667
+ }
1640
1668
  export interface ExtensionReplicaStatusTable {
1641
1669
  replica_id: string;
1642
1670
  plugin: string;
@@ -2248,7 +2276,10 @@ export interface KernelDatabase {
2248
2276
  extension_revision_grants: ExtensionRevisionGrantsTable;
2249
2277
  extension_revision_grant_orgs: ExtensionRevisionGrantOrgsTable;
2250
2278
  extension_replica_status: ExtensionReplicaStatusTable;
2279
+ extension_replica_isolation: ExtensionReplicaIsolationTable;
2251
2280
  extension_grant_epoch: ExtensionGrantEpochTable;
2281
+ extension_usage: ExtensionUsageTable;
2282
+ extension_usage_batches: ExtensionUsageBatchesTable;
2252
2283
  extension_name_owners: ExtensionNameOwnersTable;
2253
2284
  extension_handoff_tables: ExtensionHandoffTablesTable;
2254
2285
  extension_admission_refusals: ExtensionAdmissionRefusalsTable;
@@ -48,37 +48,6 @@ export async function canMigrateKernel(db) {
48
48
  return privileges.can_create && (privileges.owns_schema ?? true);
49
49
  }
50
50
  const migrateHint = "Run capybara migrate with CAPYBARA_DB__MIGRATION_URL set to the schema owner URL for split roles.";
51
- const eventOrgContract = "0219_event_org_constraint_check.sql";
52
- /** The rc.159 worker is the last release that can backfill events before 0219. */
53
- async function checkEventOrgBackfill(client) {
54
- await client.query("begin read only");
55
- try {
56
- await client.query("set local row_security = off");
57
- const { rows: [table], } = await client.query(`
58
- select exists (
59
- select from pg_catalog.pg_attribute
60
- where attrelid = relation and attname = 'org_id' and attnum > 0 and not attisdropped
61
- ) as has_org_id
62
- from (select pg_catalog.to_regclass('capybara.conversation_events') as relation) events
63
- where relation is not null
64
- `);
65
- if (!table)
66
- return;
67
- // Before 0215, every existing event would receive a null org_id from the expansion.
68
- const filter = table.has_org_id ? "where org_id is null" : "";
69
- const { rows: [state], } = await client.query(`select exists (select from capybara.conversation_events ${filter}) as incomplete`);
70
- if (state?.incomplete) {
71
- throw new Error("Migration 0219 requires the conversation event organization backfill. " +
72
- "Upgrade to Capybara 0.1.0-rc.159 and run its worker after older writers have drained. " +
73
- "Wait for EventOrgBackfillJob to finish, then verify " +
74
- "SELECT count(*) FROM capybara.conversation_events WHERE org_id IS NULL returns 0 " +
75
- "before rerunning capybara migrate.");
76
- }
77
- }
78
- finally {
79
- await client.query("rollback");
80
- }
81
- }
82
51
  /** Verify the files expected by this binary without taking a migration lock or writing the journal.
83
52
  * Extra entries are valid when a newer release has already migrated a shared database.
84
53
  */
@@ -209,11 +178,6 @@ export async function migrate(connectionString, owner, opts = {}) {
209
178
  throw new Error(`Migration ${schema}/${f.name} is out of order: a higher-numbered migration (${String(highest).padStart(4, "0")}) is already applied`);
210
179
  }
211
180
  }
212
- if (schema === "capybara" &&
213
- !done.has(eventOrgContract) &&
214
- files.some((f) => f.name === eventOrgContract)) {
215
- await checkEventOrgBackfill(client);
216
- }
217
181
  const applied = [];
218
182
  for (const f of files) {
219
183
  if (done.has(f.name))
@@ -57,7 +57,7 @@ export function protocolMismatchMessage(plugin, expected, spoken) {
57
57
  : "this program speaks another protocol";
58
58
  const fix = theirs && ours && theirs.name === ours.name && theirs.major > ours.major
59
59
  ? "This deployment is older than the program; ask the platform's super admin to upgrade it, or install the program release that matches this deployment."
60
- : "Update the program on the machine to the release that speaks this protocol (for capybara-device: npm install -g @capybara-hq/device@next), then start it again.";
60
+ : "Update the program on the machine to the release that speaks this protocol (for capybara-device: npm install -g @capybara-hq/device), then start it again.";
61
61
  return `This device is served by ${plugin}, which speaks ${expected}; ${said}. ${fix}`;
62
62
  }
63
63
  /**
@@ -67,14 +67,9 @@ const globalChecks = [
67
67
  AND data->'payload'->>'orgId' = (SELECT id FROM subject))
68
68
  )`,
69
69
  },
70
- {
71
- table: "conversation_events",
72
- order: "conversation_id, seq",
73
- predicate: "org_id IS NULL AND conversation_id IN (SELECT id FROM capybara.conversations WHERE org_id = (SELECT id FROM subject))",
74
- },
75
70
  ];
76
71
  function globalBlocker(db, orgId) {
77
- // org-filter: deployment-wide read checks FK survivors, detached jobs and legacy event ownership
72
+ // org-filter: deployment-wide read checks FK survivors and detached jobs
78
73
  return asPlatform("check org erasure dependencies", () => firstRemaining(db, orgId, globalChecks));
79
74
  }
80
75
  const unsettled = [
@@ -1,10 +1,14 @@
1
1
  import { sql } from "kysely";
2
- // PostgreSQL 17 after 0237. Re-review the ownership map before updating this fingerprint.
2
+ // PostgreSQL 17 after 0239. Re-review the ownership map before updating this fingerprint.
3
3
  // 0234 adds extension_grant_epoch: deployment state with no org or account reference, so it
4
4
  // needs no erasure rule. 0235 adds extension_revision_grants (approver columns cleared by account
5
5
  // erasure, deployment scope) and extension_revision_grant_orgs (an org row rule; the org FK
6
6
  // cascades), plus the install revision columns, their grant foreign key and extension_packages.sha512.
7
7
  // 0237 adds the handoff inventory and admission refusals, both deployment metadata.
8
+ // 0238 adds extension_usage (an org row rule; the org FK cascades) and extension_usage_batches
9
+ // (deployment state: flush batch ids with no org or account reference, no erasure rule).
10
+ // 0239 adds extension_replica_isolation (deployment state: each replica's supervisor checks and
11
+ // shadow placements by plugin and version, no org or account reference, no erasure rule).
8
12
  // The fingerprint includes relation/column identities and ordered PK, UNIQUE and inbound/outbound FK
9
13
  // columns and actions, including FKs from outside the kernel schema.
10
14
  export async function orgCatalogDrift(db) {
@@ -35,5 +39,5 @@ WITH catalog AS (
35
39
  )
36
40
  SELECT md5(string_agg(entry, chr(10) ORDER BY entry COLLATE "C")) AS fingerprint FROM catalog
37
41
  `.execute(db);
38
- return rows[0]?.fingerprint === "a9f59a4747b2fa6ee329121f9a0af5b3" ? undefined : "schema-drift";
42
+ return rows[0]?.fingerprint === "d3b21b83bd3b12ee253eb2800f0731c6" ? undefined : "schema-drift";
39
43
  }
@@ -33,6 +33,7 @@ export const rowRules = [
33
33
  rule("extension_org_configs", "plugin, org_id"),
34
34
  rule("extension_org_overrides", "plugin, org_id"),
35
35
  rule("extension_revision_grant_orgs", "plugin, version, sha512, generation, org_id"),
36
+ rule("extension_usage", "org_id, plugin, hour, counter"),
36
37
  rule("file_previewers", "org_id, plugin, previewer_id"),
37
38
  rule("inbox_items", "id"),
38
39
  rule("invitations", "id"),
@@ -197,19 +197,6 @@ let OrgErasure = class OrgErasure {
197
197
  await this.requests.advance(work, "roots", null, new Date(), { ...progress, storageIdentity });
198
198
  }
199
199
  async roots(work, orgId, deletedAt) {
200
- // org-filter: deployment-wide visibility for rows predating conversation event ownership.
201
- const legacy = await asPlatform("verify org conversation ownership backfill before purging", () => this.db
202
- .selectFrom("conversation_events as e")
203
- .innerJoin("conversations as c", "c.id", "e.conversation_id")
204
- .select("e.seq")
205
- .where("c.org_id", "=", orgId)
206
- .where("e.org_id", "is", null)
207
- .limit(1)
208
- .executeTakeFirst());
209
- if (legacy) {
210
- await this.defer(work, "event-ownership-backfill");
211
- return;
212
- }
213
200
  const root = await this.db
214
201
  .selectFrom("conversations")
215
202
  .select(["id", "account_id"])
package/dist/errors.d.ts CHANGED
@@ -156,6 +156,10 @@ export declare const ERROR_CODES: {
156
156
  readonly "extension.plugin_not_installed": 409;
157
157
  readonly "extension.name_conflict": 409;
158
158
  readonly "extension.approval_stale": 409;
159
+ readonly "extension.permission_review_stale": 409;
160
+ readonly "extension.permission_review_unavailable": 409;
161
+ readonly "extension.permission_keys_unknown": 409;
162
+ readonly "extension.permission_grant_not_found": 404;
159
163
  readonly "extension.not_pending": 409;
160
164
  readonly "extension.package_unavailable": 409;
161
165
  readonly "extension.package_not_found": 404;
@@ -278,6 +282,7 @@ export declare const ERROR_CODES: {
278
282
  readonly "plugin.switch_stale": 409;
279
283
  readonly "plugin.builtin": 409;
280
284
  readonly "plugin.scope_stale": 409;
285
+ readonly "plugin.scope_widening_not_allowed": 403;
281
286
  readonly "component.not_found": 404;
282
287
  readonly "component.version_stale": 409;
283
288
  /** A platform component offered to the org but off there (one more connector from a template). */
@@ -336,6 +341,7 @@ export declare const ERROR_CODES: {
336
341
  readonly "marketplace.host_not_allowed": 403;
337
342
  readonly "marketplace.path_unsupported": 422;
338
343
  readonly "plugin.review_stale": 409;
344
+ readonly "plugin.full_access_ack_invalid": 409;
339
345
  readonly "plugin.name_taken": 409;
340
346
  readonly "plugin.name_reserved": 409;
341
347
  readonly "plugin.dependency_unavailable": 409;
package/dist/errors.js CHANGED
@@ -156,6 +156,10 @@ export const ERROR_CODES = {
156
156
  "extension.plugin_not_installed": 409,
157
157
  "extension.name_conflict": 409,
158
158
  "extension.approval_stale": 409,
159
+ "extension.permission_review_stale": 409,
160
+ "extension.permission_review_unavailable": 409,
161
+ "extension.permission_keys_unknown": 409,
162
+ "extension.permission_grant_not_found": 404,
159
163
  "extension.not_pending": 409,
160
164
  "extension.package_unavailable": 409,
161
165
  "extension.package_not_found": 404,
@@ -278,6 +282,7 @@ export const ERROR_CODES = {
278
282
  "plugin.switch_stale": 409,
279
283
  "plugin.builtin": 409,
280
284
  "plugin.scope_stale": 409,
285
+ "plugin.scope_widening_not_allowed": 403,
281
286
  "component.not_found": 404,
282
287
  "component.version_stale": 409,
283
288
  /** A platform component offered to the org but off there (one more connector from a template). */
@@ -336,6 +341,7 @@ export const ERROR_CODES = {
336
341
  "marketplace.host_not_allowed": 403,
337
342
  "marketplace.path_unsupported": 422,
338
343
  "plugin.review_stale": 409,
344
+ "plugin.full_access_ack_invalid": 409,
339
345
  "plugin.name_taken": 409,
340
346
  "plugin.name_reserved": 409,
341
347
  "plugin.dependency_unavailable": 409,
@@ -14,6 +14,7 @@ import { ExtensionLifecycle } from "./lifecycle.js";
14
14
  import { PluginInstallLock } from "./locks.js";
15
15
  import type { AdminExtensionView } from "./permission-view.js";
16
16
  import { ExtensionRegistry } from "./registry.js";
17
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
17
18
  import { SingleProviderGuard, type SingleProviderNote } from "./single-provider.js";
18
19
  /**
19
20
  * Deployment-level extension install / enable / disable / uninstall (C16 / D15): writes only the PG
@@ -88,6 +89,8 @@ export declare class ExtensionAdminOps {
88
89
  private readonly outbox;
89
90
  /** A platform enable, disable or new version publishes `platform-caps` after the commit. */
90
91
  private readonly hints;
92
+ /** The install's approved / candidate revision (shadow mode, plan task 1.3a). */
93
+ private readonly revisions;
91
94
  constructor(kdb: KernelDb, txHost: TransactionHost,
92
95
  /** The super admin lock (identity/super-admin.ts): joins the transaction. */
93
96
  adminLock: SuperAdminLock,
@@ -116,8 +119,18 @@ export declare class ExtensionAdminOps {
116
119
  /** The plugin scope sync a deploy owes (`oweDeployedExtensionSync`). */
117
120
  outbox: Pick<OutboxService, "add" | "addMany">,
118
121
  /** A platform enable, disable or new version publishes `platform-caps` after the commit. */
119
- hints: HintPublisher);
122
+ hints: HintPublisher,
123
+ /** The install's approved / candidate revision (shadow mode, plan task 1.3a). */
124
+ revisions: Pick<ExtensionRevisionApprovals, "promoteInstalled">);
120
125
  private get db();
126
+ /**
127
+ * The install now runs `sha256`: it becomes the approved revision under its own grant, or a
128
+ * continuation, else the candidate waiting for review (shadow mode until plan task 1.5a: the
129
+ * legacy snapshot keeps governing admission). A downgrade is a rollback, served only under the
130
+ * selected revision's own grant. A package whose sha512 is not recorded yet is left to the
131
+ * backfill; the shadow decision reports it.
132
+ */
133
+ private promoteRevision;
121
134
  /**
122
135
  * New install or version change (upgrade / downgrade): the install record points at package
123
136
  * `sha256`; the desired state is unchanged (a new install is disabled). Audit `extension.installed`.
@@ -38,9 +38,10 @@ import { ExtensionBlobs } from "./blobs.js";
38
38
  import { ExtensionLifecycle, PLUGINS_CHANGED_TOPIC } from "./lifecycle.js";
39
39
  import { PluginInstallLock } from "./locks.js";
40
40
  import { unrunMigrations } from "./migrate-lock.js";
41
- import { ExtensionPackageError, extensionPackageApiError, readExtensionPackage, } from "./package.js";
41
+ import { ExtensionPackageError, extensionPackageApiError, permissionSetOfSection, readExtensionPackage, } from "./package.js";
42
42
  import { extensionSourcesQuery } from "./plugin-items.js";
43
43
  import { ExtensionRegistry } from "./registry.js";
44
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
44
45
  import { isSingleProviderCode, SingleProviderGuard, singleProviderNote, } from "./single-provider.js";
45
46
  import { captureSourceIntent, restoreSourceIntent } from "./source-intent.js";
46
47
  let ExtensionAdminOps = class ExtensionAdminOps {
@@ -60,6 +61,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
60
61
  singleProvider;
61
62
  outbox;
62
63
  hints;
64
+ revisions;
63
65
  constructor(kdb, txHost,
64
66
  /** The super admin lock (identity/super-admin.ts): joins the transaction. */
65
67
  adminLock,
@@ -88,7 +90,9 @@ let ExtensionAdminOps = class ExtensionAdminOps {
88
90
  /** The plugin scope sync a deploy owes (`oweDeployedExtensionSync`). */
89
91
  outbox,
90
92
  /** A platform enable, disable or new version publishes `platform-caps` after the commit. */
91
- hints) {
93
+ hints,
94
+ /** The install's approved / candidate revision (shadow mode, plan task 1.3a). */
95
+ revisions) {
92
96
  this.kdb = kdb;
93
97
  this.txHost = txHost;
94
98
  this.adminLock = adminLock;
@@ -105,10 +109,28 @@ let ExtensionAdminOps = class ExtensionAdminOps {
105
109
  this.singleProvider = singleProvider;
106
110
  this.outbox = outbox;
107
111
  this.hints = hints;
112
+ this.revisions = revisions;
108
113
  }
109
114
  get db() {
110
115
  return this.kdb.db;
111
116
  }
117
+ /**
118
+ * The install now runs `sha256`: it becomes the approved revision under its own grant, or a
119
+ * continuation, else the candidate waiting for review (shadow mode until plan task 1.5a: the
120
+ * legacy snapshot keeps governing admission). A downgrade is a rollback, served only under the
121
+ * selected revision's own grant. A package whose sha512 is not recorded yet is left to the
122
+ * backfill; the shadow decision reports it.
123
+ */
124
+ async promoteRevision(name, sha256, version, target, previous) {
125
+ const pkg = await this.db
126
+ .selectFrom("extension_packages")
127
+ .select("sha512")
128
+ .where("sha256", "=", sha256)
129
+ .executeTakeFirst();
130
+ if (!pkg?.sha512)
131
+ return;
132
+ await this.revisions.promoteInstalled({ plugin: name, version, sha512: pkg.sha512 }, permissionSetOfSection(target.section, target.migrationSql), previous && isDowngrade(version, previous.version) ? "rollback" : "upgrade");
133
+ }
112
134
  /**
113
135
  * New install or version change (upgrade / downgrade): the install record points at package
114
136
  * `sha256`; the desired state is unchanged (a new install is disabled). Audit `extension.installed`.
@@ -334,6 +356,7 @@ let ExtensionAdminOps = class ExtensionAdminOps {
334
356
  .execute();
335
357
  if (sourceIntent)
336
358
  await restoreSourceIntent(db, name, sourceIntent, actor);
359
+ await this.promoteRevision(name, sha256, pkg.version, target, row ?? undefined);
337
360
  if (leftDisabled !== undefined ||
338
361
  staticPermissionDeclarations(target.section.manifest).permissions.deviceAccess?.siteAccess !==
339
362
  true) {
@@ -558,6 +581,9 @@ let ExtensionAdminOps = class ExtensionAdminOps {
558
581
  }
559
582
  }
560
583
  };
584
+ __decorate([
585
+ Transactional({ propagation: "mandatory" })
586
+ ], ExtensionAdminOps.prototype, "promoteRevision", null);
561
587
  __decorate([
562
588
  Transactional()
563
589
  ], ExtensionAdminOps.prototype, "writeInstall", null);
@@ -590,7 +616,8 @@ ExtensionAdminOps = __decorate([
590
616
  __param(12, Inject(KERNEL_LOGGER)),
591
617
  __param(13, Inject(SingleProviderGuard)),
592
618
  __param(14, Inject(OutboxService)),
593
- __param(15, Inject(InvalidationHints))
619
+ __param(15, Inject(InvalidationHints)),
620
+ __param(16, Inject(ExtensionRevisionApprovals))
594
621
  ], ExtensionAdminOps);
595
622
  export { ExtensionAdminOps };
596
623
  /**
@@ -1,3 +1,4 @@
1
+ import { ApiError } from "../errors.js";
1
2
  import { SuperAdminLock } from "../identity/super-admin.js";
2
3
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -18,7 +19,7 @@ import { type AdminExtensionView } from "./permission-view.js";
18
19
  import { PluginIcons } from "./plugin-icons.js";
19
20
  import { SingleProviderGuard } from "./single-provider.js";
20
21
  export { PLUGINS_CHANGED_TOPIC };
21
- /** The web approval request body (`POST /api/v1/admin/extensions/:name/approve`). */
22
+ /** Legacy snapshot input used while revision grant enforcement is in shadow mode. */
22
23
  export interface ApproveBody {
23
24
  /** 安装记录的包;配置声明的插件为 null。 */
24
25
  sha256: string | null;
@@ -28,6 +29,11 @@ export interface ApproveBody {
28
29
  export interface PublishBus {
29
30
  publish(topic: string, payload: unknown): Promise<void>;
30
31
  }
32
+ /** An install's legacy approval subject (opaque outside this file). */
33
+ export type LegacyApprovalSubject = {
34
+ readonly name: string;
35
+ readonly version: string;
36
+ };
31
37
  /**
32
38
  * 部署级插件后台(超级管理员):列表 / 详情与网页批准权限(D8)。无状态,多副本共用;
33
39
  * 状态由 PG(安装记录、快照、各副本状态行)与本副本宿主(配置声明插件的清单)推出。
@@ -114,6 +120,20 @@ export declare class ExtensionAdmin {
114
120
  approve(actor: string, name: string, body: ApproveBody, opts?: {
115
121
  actorTokenId?: string;
116
122
  }): Promise<AdminExtensionView>;
123
+ /**
124
+ * The legacy approval of an install, for the permission approve route (plan task 1.4a): read
125
+ * outside any transaction (the package), then {@link writeLegacyApproval} inside the caller's,
126
+ * then {@link notifyApproved} after its commit. Undefined for an unknown or unreadable install.
127
+ */
128
+ legacySubject(name: string): Promise<LegacyApprovalSubject | undefined>;
129
+ /**
130
+ * Writes the legacy snapshot in the caller's transaction (the permission approve route, which
131
+ * records the revision grant in the same one), under the same locks and checks as
132
+ * {@link approve}. Returns false when the snapshot already covers the permissions.
133
+ */
134
+ writeLegacyApproval(actor: string, name: string, subject: LegacyApprovalSubject, actorTokenId: string | undefined, stale: () => ApiError): Promise<boolean>;
135
+ /** After an approval committed: other replicas are told, this one reconciles. */
136
+ notifyApproved(name: string): Promise<void>;
117
137
  private writeApproval;
118
138
  /** 配置声明 → 安装记录(与配置声明重名的安装记录不生效,不单列)。`only` 给出时只取这一个。 */
119
139
  private subjects;
@@ -200,6 +200,46 @@ let ExtensionAdmin = class ExtensionAdmin {
200
200
  }
201
201
  return this.get(name);
202
202
  }
203
+ /**
204
+ * The legacy approval of an install, for the permission approve route (plan task 1.4a): read
205
+ * outside any transaction (the package), then {@link writeLegacyApproval} inside the caller's,
206
+ * then {@link notifyApproved} after its commit. Undefined for an unknown or unreadable install.
207
+ */
208
+ async legacySubject(name) {
209
+ const s = (await this.subjects(name))[0];
210
+ return s && s.broken === undefined && s.install !== null ? s : undefined;
211
+ }
212
+ /**
213
+ * Writes the legacy snapshot in the caller's transaction (the permission approve route, which
214
+ * records the revision grant in the same one), under the same locks and checks as
215
+ * {@link approve}. Returns false when the snapshot already covers the permissions.
216
+ */
217
+ async writeLegacyApproval(actor, name, subject, actorTokenId, stale) {
218
+ try {
219
+ await this.writeApproval(actor, name, subject, actorTokenId, stale);
220
+ return true;
221
+ }
222
+ catch (err) {
223
+ if (err instanceof ApiError && err.code === "extension.not_pending")
224
+ return false;
225
+ throw err;
226
+ }
227
+ }
228
+ /** After an approval committed: other replicas are told, this one reconciles. */
229
+ async notifyApproved(name) {
230
+ try {
231
+ await this.bus.publish(PLUGINS_CHANGED_TOPIC, { plugin: name });
232
+ }
233
+ catch (err) {
234
+ this.log.warn("cannot publish plugins.changed after approval", { plugin: name, err });
235
+ }
236
+ try {
237
+ await this.lifecycle.reconcile(`approved:${name}`);
238
+ }
239
+ catch (err) {
240
+ this.log.error("loading approved plugins on this replica failed", { plugin: name, err });
241
+ }
242
+ }
203
243
  async writeApproval(actor, name, s, actorTokenId, stale) {
204
244
  const db = this.db;
205
245
  await this.adminLock.lockAndAuthorize(actor);
@@ -595,6 +635,9 @@ let ExtensionAdmin = class ExtensionAdmin {
595
635
  return { clients, reports };
596
636
  }
597
637
  };
638
+ __decorate([
639
+ Transactional({ propagation: "mandatory" })
640
+ ], ExtensionAdmin.prototype, "writeLegacyApproval", null);
598
641
  __decorate([
599
642
  Transactional()
600
643
  ], ExtensionAdmin.prototype, "writeApproval", null);
@@ -70,6 +70,11 @@ export declare function bootstrapGitMarketplace(manifest: Pick<MergedBootstrapMa
70
70
  * for the `soft` entries (recorded in `failed`, left out of the result).
71
71
  */
72
72
  export declare function resolveBootstrapPackages(manifest: MergedBootstrapManifest, o: BootstrapResolveOptions): Promise<Map<string, Uint8Array>>;
73
+ /**
74
+ * The `*.tgz` files directly in `dir` by their sha512 integrity. A missing directory is an empty
75
+ * one; a file larger than `maxBytes` is skipped with a warning.
76
+ */
77
+ export declare function scanOfflineDir(dir: string, maxBytes: number, log: Pick<Logger, "warn"> | undefined): Promise<Map<string, Uint8Array>>;
73
78
  /** What a git entry's tree is, as the bootstrap import reads it ({@link readBootstrapGitPlugin}). */
74
79
  export interface BootstrapGitPlugin {
75
80
  /** `capybara`: `.capybara-plugin/plugin.json`; `claude`: a Claude Code plugin; `skills`: skills only. */
@@ -207,7 +207,7 @@ function registryOrigin(registry) {
207
207
  * The `*.tgz` files directly in `dir` by their sha512 integrity. A missing directory is an empty
208
208
  * one; a file larger than `maxBytes` is skipped with a warning.
209
209
  */
210
- async function scanOfflineDir(dir, maxBytes, log) {
210
+ export async function scanOfflineDir(dir, maxBytes, log) {
211
211
  const out = new Map();
212
212
  let names;
213
213
  try {