@substrat-run/adapter-cloudflare 0.220.0 → 0.222.0

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 (89) hide show
  1. package/dist/broker-telemetry.d.ts +2 -5
  2. package/dist/broker-telemetry.d.ts.map +1 -1
  3. package/dist/broker-telemetry.js +2 -5
  4. package/dist/broker-telemetry.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +280 -65
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +737 -245
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +3 -2
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +10 -4
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-handoff.d.ts +17 -1
  14. package/dist/delivery-handoff.d.ts.map +1 -1
  15. package/dist/delivery-handoff.js +19 -5
  16. package/dist/delivery-handoff.js.map +1 -1
  17. package/dist/directory-cutover.d.ts +243 -0
  18. package/dist/directory-cutover.d.ts.map +1 -0
  19. package/dist/directory-cutover.js +604 -0
  20. package/dist/directory-cutover.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +19 -1
  22. package/dist/directory-mirror-apply.d.ts.map +1 -1
  23. package/dist/directory-mirror-apply.js +19 -3
  24. package/dist/directory-mirror-apply.js.map +1 -1
  25. package/dist/directory-mirror-backfill.d.ts +2 -0
  26. package/dist/directory-mirror-backfill.d.ts.map +1 -1
  27. package/dist/directory-mirror-backfill.js +6 -4
  28. package/dist/directory-mirror-backfill.js.map +1 -1
  29. package/dist/directory-mirror.d.ts +24 -0
  30. package/dist/directory-mirror.d.ts.map +1 -1
  31. package/dist/directory-mirror.js +16 -2
  32. package/dist/directory-mirror.js.map +1 -1
  33. package/dist/directory-objects.d.ts +40 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +134 -2
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts.map +1 -1
  38. package/dist/directory-placement.js +9 -1
  39. package/dist/directory-placement.js.map +1 -1
  40. package/dist/directory-split-inventory.d.ts +5 -3
  41. package/dist/directory-split-inventory.d.ts.map +1 -1
  42. package/dist/directory-split-inventory.js +13 -6
  43. package/dist/directory-split-inventory.js.map +1 -1
  44. package/dist/directory-tenant-orgs.d.ts +19 -0
  45. package/dist/directory-tenant-orgs.d.ts.map +1 -0
  46. package/dist/directory-tenant-orgs.js +33 -0
  47. package/dist/directory-tenant-orgs.js.map +1 -0
  48. package/dist/directory-tenant-roles.d.ts +35 -0
  49. package/dist/directory-tenant-roles.d.ts.map +1 -0
  50. package/dist/directory-tenant-roles.js +78 -0
  51. package/dist/directory-tenant-roles.js.map +1 -0
  52. package/dist/directory-tenant-tuples.d.ts +165 -0
  53. package/dist/directory-tenant-tuples.d.ts.map +1 -0
  54. package/dist/directory-tenant-tuples.js +197 -0
  55. package/dist/directory-tenant-tuples.js.map +1 -0
  56. package/dist/host.d.ts +65 -3
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/host.js +422 -64
  59. package/dist/host.js.map +1 -1
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +1 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/platform-sweeper-do.d.ts +1 -1
  65. package/dist/platform-sweeper-do.js +1 -1
  66. package/dist/route-read-model-publisher.d.ts +6 -1
  67. package/dist/route-read-model-publisher.d.ts.map +1 -1
  68. package/dist/route-read-model-publisher.js +51 -13
  69. package/dist/route-read-model-publisher.js.map +1 -1
  70. package/dist/scope-do.d.ts +28 -2
  71. package/dist/scope-do.d.ts.map +1 -1
  72. package/dist/scope-do.js +398 -68
  73. package/dist/scope-do.js.map +1 -1
  74. package/dist/scope-sweeper-do.d.ts +28 -0
  75. package/dist/scope-sweeper-do.d.ts.map +1 -1
  76. package/dist/scope-sweeper-do.js +88 -50
  77. package/dist/scope-sweeper-do.js.map +1 -1
  78. package/dist/scope-wake.d.ts +12 -1
  79. package/dist/scope-wake.d.ts.map +1 -1
  80. package/dist/scope-wake.js +14 -1
  81. package/dist/scope-wake.js.map +1 -1
  82. package/dist/scope-work.d.ts +1 -1
  83. package/dist/scope-work.js +1 -1
  84. package/dist/scope-work.js.map +1 -1
  85. package/dist/tenant-due-work-do.d.ts +95 -0
  86. package/dist/tenant-due-work-do.d.ts.map +1 -0
  87. package/dist/tenant-due-work-do.js +149 -0
  88. package/dist/tenant-due-work-do.js.map +1 -0
  89. package/package.json +10 -10
@@ -1,13 +1,14 @@
1
+ import { tenantDueWorkName } from './tenant-due-work-do.js';
1
2
  import { DurableObject } from 'cloudflare:workers';
2
- import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, reservedRoleDefinitionRefusal, reservedRoleRefusal, TENANT_SEATED_ROLES_SQL, tenantCoverage, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, defineEnvironmentIn, environmentsOf, removeEnvironmentIn, SWITCH_OWED_DDL, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
3
+ import { membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, MEMBERSHIP_FENCES_TABLE, membershipFencesTableExists, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, SCOPE_STORAGE_DDL, forgetScopeStorage, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeAttachmentStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, DIRECTORY_LAKE_DDL, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink as insertConnectLinkRow, listConnectLinks as listConnectLinkRows, readConnectLink as readConnectLinkRow, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentsOf, HOME_SCOPE_TYPE, homeScopeIn, secondHomeRefusal, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, setEnvironmentEffectsIn, connectionReachIn, SWITCH_OWED_DDL, DEPENDENT_ERASURES_DDL, DEPENDENT_ERASURE_DUE_SQL, DEPENDENT_ERASURE_HOLD_SQL, DEPENDENT_ERASURE_OWE_SQL, DEPENDENT_ERASURE_SETTLE_SQL, nextDependentErasureAt, clearSwitchOwed, markSwitchOwed, scopeOwesSwitch, switchesOwedOf, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, recordSwitchedOff, recordSwitchedOn, recordWriteSuperseded, restoreSwitchRecord, scopesSwitchedOffFor, switchRecordStatesOf, switchRecordsOf, switchesBackfillSqlOf, switchesDdlOf, switchesTableExists, switchesTableOf, tenantHeldOf, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, DEPLOYMENT_WIRE_AUTH_DDL, deploymentWireAuthOf, forgetVerticalWireAuth, writeDeploymentWireAuth, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, driverDeclarationsOf, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, forgetVerticalScopeStores, indexVersionScopeStores, verticalScopeStoresOf, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, versionsAwaitSplit, versionsAwaitDigest, deriveMigrationDigestsBatch, deriveVersionMigrationDigest, writeVersionMigrations, MODEL_USAGE_RETENTION_DAYS, BUILD_USAGE_RETENTION_DAYS, DO_SQL_LIMITS, ulid, isPrimaryScopeRow, samePeerVertical, peerVerticalSpellings, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, LEGACY_SCOPE_ROWS_BACKFILL, loadDirectoryDump, storesFencedRefusal, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, unknownOutcomeOf, ADMIN_LOG_INDEX_DDL, ADMIN_LOG_INDEXES_SQL, readAuditedOperations, } from '@substrat-run/kernel';
3
4
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, } from '@substrat-run/kernel';
4
5
  import { replyOf } from './do-reply.js';
5
6
  import { rowBytes, switchSqlOver } from './scope-do.js';
6
7
  import { DIRECTORY_COPY_BY_REFERENCE, quoteIdent, referenceCompareSql, referenceExtraSql, } from './directory-copy-reference.js';
7
8
  import { blankSqlComments, boundShapesColumn, executableSqlStatements, installsReconciledOf, PROVISIONED_VERSIONS_SQL, provisionedVersionsParams, } from '@substrat-run/kernel';
8
- import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, servesAsFrom, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, } from '@substrat-run/kernel';
9
- import { autoAdmittedProdRefusal, breakingWithinMajorRefusal, listedPromoteRefusal, ON_EARLIER_MAJOR_SQL, opsFailureReferenceWhere, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
10
- import { canonicalInstant } from '@substrat-run/kernel';
9
+ import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_EXPIRED_FOR_TENANT_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, servesAsFrom, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, } from '@substrat-run/kernel';
10
+ import { autoAdmittedProdRefusal, breakingWithinMajorRefusal, earlierMajorsOf, listedPromoteRefusal, ON_EARLIER_MAJOR_SQL, opsFailureReferenceWhere, releasedEarlierMajorJson, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
11
+ import { canonicalInstant, provisionedParent } from '@substrat-run/kernel';
11
12
  import { doBuiltColumnsOf, doRedactionSql } from './sql.js';
12
13
  import { ROUTE_READ_MODEL_TABLE_GLOB, RouteReadModelPublisher, routeKvWriterOf, uninstallRouteReadModel, } from './route-read-model-publisher.js';
13
14
  import { readPeerCallTarget } from './peer-call-target.js';
@@ -16,6 +17,14 @@ import { DIRECTORY_MIRROR_TABLE_GLOB, directoryMirrorFor, isDirectoryMirrorTable
16
17
  import { durableMirrorSender } from './directory-objects.js';
17
18
  import { directoryBackfillFor } from './directory-mirror-backfill.js';
18
19
  import { directoryVerifyFor } from './directory-mirror-verify.js';
20
+ // K-68 step 3e: a tenant's role definitions read from, and first written to, its own object (off by default).
21
+ import { cutoverLive, directoryCutoverFor } from './directory-cutover.js';
22
+ // K-68 step 3e, the second family: a tenant's tuples and removal fences (directory-tenant-tuples.ts).
23
+ import { applyMembershipIn, assignTenantRoleIn, dumpTenantTupleRows, listMemberRows, revokeAndFenceIn, revokeTenantTupleIn, TENANT_TUPLES, tenantTupleRows, writeTenantTupleIn, } from './directory-tenant-tuples.js';
24
+ // K-68 step 3e, the third family: a tenant's organizations (directory-tenant-orgs.ts).
25
+ import { createOrgIn, listOrgRows, ORGS, readOrgRow } from './directory-tenant-orgs.js';
26
+ import { durableCutoverSender } from './directory-objects.js';
27
+ import { defineRoleRow, listRoleRows, readRole } from './directory-tenant-roles.js';
19
28
  import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, opsFailureFingerprint, ROUTE_SCOPE_HOSTNAMES_MAX, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_GATE_REASONS, substratError } from '@substrat-run/contracts';
20
29
  /**
21
30
  * The router's per-request directory read (`readRoute`), lifted out so its plan can be asked for
@@ -24,10 +33,12 @@ import { assertReplayableDump, AUTO_ADMISSION_NOTE, instant, isRuntimeTable, ops
24
33
  */
25
34
  export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug, h.surface, h.region,
26
35
  COALESCE(s.serving_ref, vv.deployment_ref) AS deployment_ref,
27
- CASE WHEN s.serving_ref IS NOT NULL
36
+ -- #3530 step 4: a scope on its environment's own script (\`ae\`) runs the version it is
37
+ -- bound to, which is what that script was last served: its policy is that version's.
38
+ CASE WHEN s.serving_ref IS NOT NULL AND ae.serving_ref IS NULL
28
39
  THEN json_extract(sv.manifest_json, '$.outbound')
29
40
  ELSE json_extract(vv.manifest_json, '$.outbound') END AS outbound_json,
30
- CASE WHEN s.serving_ref IS NOT NULL
41
+ CASE WHEN s.serving_ref IS NOT NULL AND ae.serving_ref IS NULL
31
42
  THEN json_extract(sv.manifest_json, '$.calls')
32
43
  ELSE json_extract(vv.manifest_json, '$.calls') END AS calls_json,
33
44
  -- #2207: the stores of the version the scope's script runs. A scope pinned to a
@@ -36,7 +47,7 @@ export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug,
36
47
  -- its store calls are refused. The control plane reads the same rule
37
48
  -- (scopeStoresOf in control-plane-api). A scope on an earlier major's script runs
38
49
  -- that major's version (K-65, #3539), which the row names: its stores.
39
- CASE WHEN s.serving_ref IS NULL
50
+ CASE WHEN s.serving_ref IS NULL OR ae.serving_ref IS NOT NULL
40
51
  THEN json_extract(vv.manifest_json, '$.scopeStores')
41
52
  WHEN s.serving_ref = vr.serving_ref OR ${ON_EARLIER_MAJOR_SQL}
42
53
  THEN json_extract(sv.manifest_json, '$.scopeStores')
@@ -56,6 +67,7 @@ export const READ_ROUTE_SQL = `SELECT h.tenant_id, h.scope_id, h.vertical_slug,
56
67
  LEFT JOIN verticals vr ON vr.slug = s.vertical
57
68
  -- K-65 (#3539 part 2): the version the scope's script runs, an earlier major's included.
58
69
  LEFT JOIN vertical_versions sv ON sv.id = ${SCRIPT_SERVING_VERSION_SQL}
70
+ ${ENVIRONMENT_SCRIPT_JOIN_SQL}
59
71
  WHERE h.hostname = ? AND h.status = 'active'
60
72
  AND s.status = 'active' AND t.status = 'active'`;
61
73
  /** snake_case row → the camelCase `issueEntry` shape (#1233). */
@@ -548,6 +560,8 @@ const DIRECTORY_DDL = `
548
560
  ${MEMBERSHIP_FENCES_DDL}
549
561
  ${PEER_SWITCHES_DDL}
550
562
  ${SWITCH_OWED_DDL}
563
+ -- K-63 (#3624): erasures owed to a master's dependents, kept until each door answers.
564
+ ${DEPENDENT_ERASURES_DDL}
551
565
  CREATE TABLE IF NOT EXISTS _substrat_admin_log (
552
566
  id TEXT PRIMARY KEY,
553
567
  actor TEXT NOT NULL,
@@ -919,6 +933,10 @@ export const REPLIED_METHODS = [
919
933
  // #2565: refuses a listed vertical's prod with forbidden (`unlistedOnly`) or conflict (an
920
934
  // auto-admitted version). A DO from before lists it not, so the current coordinator fails closed.
921
935
  'promoteChannel',
936
+ // K-65 (#3539): a release into an earlier major, judged and then recorded, each in its unit. New
937
+ // names, so a DO from before refuses them rather than moving prod or the newest major's record.
938
+ 'recordEarlierMajorPromote',
939
+ 'setEarlierMajorServing',
922
940
  // #2526: the role, grant and org writes at a tenant node, each with its admin row in its unit. A
923
941
  // DO from before lists none of them, so the current coordinator fails closed against it. That is
924
942
  // why the org write is `insertOrg` and not `createOrg` with a trailing row: an older DO lists
@@ -973,6 +991,11 @@ export const REPLIED_METHODS = [
973
991
  // D-83 (#3530 step 3): an environment named or unnamed, with its admin row in the same transaction.
974
992
  'defineEnvironmentAndAudit',
975
993
  'removeEnvironmentAndAudit',
994
+ // #3530 step 4: an environment's own serving script recorded, with its admin row.
995
+ 'setEnvironmentServingAndAudit',
996
+ 'claimEnvironmentServe',
997
+ // #3530 step 6: an environment given connections of its own, with its admin row.
998
+ 'setEnvironmentEffectsAndAudit',
976
999
  ];
977
1000
  /**
978
1001
  * #1713: the directory's epoch describes THIS store's history, not its data, so it never leaves in
@@ -1065,6 +1088,39 @@ export class ControlPlaneDO extends DurableObject {
1065
1088
  kernelSql;
1066
1089
  /** Settles once the constructor's #1764 backfill check has run (awaited by the tests). */
1067
1090
  backfillArmed;
1091
+ /** The pass recovers a handoff interrupted after the directory commit. */
1092
+ armTenantDueWork(tenantId, items) {
1093
+ const env = this.env;
1094
+ const ns = env.TENANT_DUE_WORK;
1095
+ if (!ns || items.length === 0)
1096
+ return;
1097
+ if (items[0].kind === 'copies') {
1098
+ if (env.SCOPE_COPY_OWNER !== 'tenant' || !env.DISPATCH || !env.PLATFORM_SECRET)
1099
+ return;
1100
+ }
1101
+ else if (env.REAP_OWNER !== 'tenant')
1102
+ return;
1103
+ const owner = ns.get(ns.idFromName(tenantDueWorkName(tenantId)));
1104
+ this.ctx.waitUntil(owner.ensure(tenantId, items).catch((err) => {
1105
+ console.error('directory could not arm tenant due work', { tenantId, err });
1106
+ }));
1107
+ }
1108
+ autoReapAt(setting, at) {
1109
+ const raw = Reflect.get(this.env, setting);
1110
+ if (!raw?.trim())
1111
+ return undefined;
1112
+ const days = Number(raw);
1113
+ const dueAt = at + days * 86_400_000;
1114
+ return Number.isInteger(days) && days >= 0 && dueAt <= 8.64e15 ? dueAt : undefined;
1115
+ }
1116
+ armSnapshotReap(scopeId, expiresAt) {
1117
+ if (expiresAt === null || Reflect.get(this.env, 'REAP_OWNER') !== 'tenant')
1118
+ return;
1119
+ const row = this.sql.exec("SELECT tenant_id FROM scopes WHERE scope_id = ? AND (forked_from IS NOT NULL OR kind = 'preview')", scopeId).toArray()[0];
1120
+ const dueAt = Date.parse(expiresAt);
1121
+ if (row && Number.isFinite(dueAt))
1122
+ this.armTenantDueWork(row.tenant_id, [{ kind: 'snapshot', unit: scopeId, dueAt }]);
1123
+ }
1068
1124
  constructor(ctx, env) {
1069
1125
  super(ctx, env);
1070
1126
  this.sql = ctx.storage.sql;
@@ -1083,10 +1139,24 @@ export class ControlPlaneDO extends DurableObject {
1083
1139
  });
1084
1140
  this.directoryBackfill = directoryBackfillFor(env, this.directoryMirror, this.directoryBackfillLimits());
1085
1141
  this.directoryVerify = directoryVerifyFor(env, this.directoryMirror, this.directoryVerifyLimits());
1142
+ this.directoryCutover = directoryCutoverFor(env, durableCutoverSender(env), {
1143
+ sql: this.sql,
1144
+ transaction: (fn) => ctx.storage.transactionSync(fn),
1145
+ mirror: this.directoryMirror,
1146
+ verify: this.directoryVerify,
1147
+ recordAdmin: (entry) => this.recordAdmin(entry),
1148
+ applyCarried: (write) => this.applyCarried(write),
1149
+ armRetry: async (at) => {
1150
+ const current = await ctx.storage.getAlarm();
1151
+ if (current === null || current > at)
1152
+ await ctx.storage.setAlarm(at);
1153
+ },
1154
+ ...this.directoryCutoverOptions(),
1155
+ });
1086
1156
  this.backfillArmed = ctx.blockConcurrencyWhile(async () => {
1087
1157
  await this.armVersionMigrationsBackfill();
1088
1158
  // K-68 step 3c: the backfill's passes ride the alarm (directory-mirror-backfill.ts).
1089
- if (this.directoryMirror?.backfillWanted()) {
1159
+ if (this.directoryMirror?.backfillWanted() || this.directoryCutover?.wanted()) {
1090
1160
  const current = await ctx.storage.getAlarm();
1091
1161
  const at = Date.now() + 1_000;
1092
1162
  if (current === null || current > at)
@@ -1142,6 +1212,43 @@ export class ControlPlaneDO extends DurableObject {
1142
1212
  return { enabled: false };
1143
1213
  return { ...this.directoryVerify.status(), owners: this.directoryVerify.owners(query) };
1144
1214
  }
1215
+ // -- K-68 step 3e: reads cut over per tenant, writes first to its object (directory-cutover.ts) --
1216
+ /** Set where `DIRECTORY_CUTOVER` is on, or a tenant is not off yet; null otherwise. */
1217
+ directoryCutover;
1218
+ /** The cut-over's comparison age limit: the production default, other in a test directory. */
1219
+ directoryCutoverOptions() {
1220
+ return {};
1221
+ }
1222
+ /**
1223
+ * Flip a tenant's directory reads (and first writes) of the cut-over tables to its own object, or
1224
+ * back. On is gated in code (`DirectoryCutover.refusal`): the dual-write on, the tenant's last
1225
+ * comparison clean, nothing in flight. Off drains every write the object made first into this
1226
+ * directory before reads return here. Staff only (the worker's route).
1227
+ */
1228
+ async cutOverTenantDirectory(tenantId, to, actor) {
1229
+ if (!this.directoryCutover)
1230
+ return { refused: 'the directory cut-over is off (DIRECTORY_CUTOVER), or the split’s objects are not bound' };
1231
+ try {
1232
+ return { row: await this.directoryCutover.cutOver(tenantId, to, actor) };
1233
+ }
1234
+ catch (err) {
1235
+ // A refusal crosses the hop as data: a throw would reach the worker without its code.
1236
+ if (err?.code === 'conflict')
1237
+ return { refused: err.message };
1238
+ throw err;
1239
+ }
1240
+ }
1241
+ /** Where each tenant's flag stands: a page after `after`, or the one `tenantId` names. */
1242
+ directoryCutoverStatus(query = {}) {
1243
+ return this.directoryCutover ? this.directoryCutover.status(query) : { enabled: false };
1244
+ }
1245
+ /** The alarm's cut-over pass, now (staff, and tests): drains, flips off it can complete, registry records. */
1246
+ async settleDirectoryCutover() {
1247
+ if (!this.directoryCutover)
1248
+ return { enabled: false };
1249
+ await this.directoryCutover.retry();
1250
+ return this.directoryCutover.status();
1251
+ }
1145
1252
  // -- the routing read model (#3395) -------------------------------------------
1146
1253
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1147
1254
  routePublisher = null;
@@ -1377,6 +1484,8 @@ export class ControlPlaneDO extends DurableObject {
1377
1484
  await this.retryRouteReadModel().catch((err) => console.error('route read model: retry failed', err));
1378
1485
  // K-68 step 3b: the dual-write's retry after a send an object refused.
1379
1486
  this.directoryMirror?.retry();
1487
+ // K-68 step 3e: fallback writes still owed, flips off waiting on them, and the registry's record.
1488
+ await this.directoryCutover?.retry().catch((err) => console.error('directory cutover: the alarm pass failed', err));
1380
1489
  let more;
1381
1490
  try {
1382
1491
  more = this.ctx.storage.transactionSync(() => splitVersionMigrationsBatch(this.kernelSql)).more;
@@ -1750,6 +1859,17 @@ export class ControlPlaneDO extends DurableObject {
1750
1859
  this.addColumn('_substrat_entitlements', 'plan TEXT');
1751
1860
  this.addColumn('_substrat_entitlements', 'granted_at TEXT');
1752
1861
  this.addColumn('_substrat_entitlements', 'granted_by TEXT');
1862
+ // #3530 step 4: an environment's own serving script; NULL on every row (no script of its own).
1863
+ // Written out, not looped over the kernel's list: lint:spine-ddl reads each call, and
1864
+ // directory-placement.ts's copy (`APP_ENVIRONMENT_SERVING_COLUMNS`) is held to these by directory-objects.
1865
+ this.addColumn('app_environments', 'serving_ref TEXT');
1866
+ this.addColumn('app_environments', 'serving_version_id TEXT');
1867
+ this.addColumn('app_environments', 'serving_do_classes TEXT');
1868
+ this.addColumn('app_environments', 'serving_migration_tag TEXT');
1869
+ this.addColumn('app_environments', 'serve_claim TEXT');
1870
+ this.addColumn('app_environments', 'serve_claimed_until TEXT');
1871
+ // #3530 step 6: the environment's choice of outside effects (`APP_ENVIRONMENT_EFFECTS_COLUMNS`); NULL reads as `none`.
1872
+ this.addColumn('app_environments', 'effects TEXT');
1753
1873
  for (const stmt of LEGACY_SCOPE_ROWS_BACKFILL)
1754
1874
  this.sql.exec(stmt);
1755
1875
  // #2501: an ownership period for every vertical registered before the history existed.
@@ -2067,6 +2187,10 @@ export class ControlPlaneDO extends DurableObject {
2067
2187
  if (opts.requireEmpty && this.sql.exec('SELECT 1 FROM tenants LIMIT 1').toArray().length > 0) {
2068
2188
  throw substratError('conflict', RESTORE_OVERWRITE_REFUSAL);
2069
2189
  }
2190
+ // K-68 step 3e: a tenant on its own object is not in a dump's past; flip every one off first.
2191
+ if (cutoverLive(this.sql)) {
2192
+ throw substratError('conflict', 'a tenant’s directory reads are cut over to its own object (K-68 step 3e): flip every tenant off before a restore');
2193
+ }
2070
2194
  // #1713: the epoch this directory was in, read before the drops take it.
2071
2195
  const epochBefore = this.lifecycleEpoch();
2072
2196
  this.sql.exec('PRAGMA defer_foreign_keys = ON');
@@ -2122,6 +2246,8 @@ export class ControlPlaneDO extends DurableObject {
2122
2246
  // for 3c's backfill to fill again, not sent row by row.
2123
2247
  this.directoryMirror?.install();
2124
2248
  this.directoryMirror?.markRestored();
2249
+ // K-68 step 3e: the cut-over's triggers went with the cut-over tables.
2250
+ this.directoryCutover?.install();
2125
2251
  });
2126
2252
  // A restore is a new #1764 backfill episode. It replaced the data the old failure count and
2127
2253
  // backoff were about, so neither may delay or silence it: the count is cleared and the next
@@ -2387,13 +2513,19 @@ export class ControlPlaneDO extends DurableObject {
2387
2513
  // Stamp/clear deleting_at so the grace-window sweep can age tenants (§4.8):
2388
2514
  // entering `deleting` stamps, leaving it (an un-delete) clears — the same shape
2389
2515
  // transitionScope uses for archived_at.
2516
+ const now = Date.now();
2390
2517
  this.writeAndAudit(() => {
2391
2518
  const moved = (status === 'deleting'
2392
- ? this.sql.exec('UPDATE tenants SET status = ?, deleting_at = ? WHERE tenant_id = ?', status, new Date().toISOString(), tenantId)
2519
+ ? this.sql.exec('UPDATE tenants SET status = ?, deleting_at = ? WHERE tenant_id = ?', status, new Date(now).toISOString(), tenantId)
2393
2520
  : this.sql.exec('UPDATE tenants SET status = ?, deleting_at = NULL WHERE tenant_id = ?', status, tenantId)).rowsWritten > 0;
2394
2521
  this.bumpLifecycleRevision(`tenant:${tenantId}`); // #1713, with the change it counts
2395
2522
  return moved;
2396
2523
  }, audit && { ...audit, before: { status: before.status } });
2524
+ if (status === 'deleting') {
2525
+ const dueAt = this.autoReapAt('TENANT_RETENTION_DAYS', now);
2526
+ if (dueAt !== undefined)
2527
+ this.armTenantDueWork(tenantId, [{ kind: 'tenant', unit: tenantId, dueAt }]);
2528
+ }
2397
2529
  return before.status;
2398
2530
  }
2399
2531
  /**
@@ -2404,13 +2536,16 @@ export class ControlPlaneDO extends DurableObject {
2404
2536
  * previous status (for the audit before/after). Idempotent: set-to-empty DELETEs
2405
2537
  * plus the status flip converge on a re-run after a partial failure.
2406
2538
  */
2407
- reapTenant(tenantId, audit) {
2539
+ reapTenant(tenantId, audit, deletingBy) {
2408
2540
  const before = this.readTenant(tenantId);
2409
2541
  if (!before)
2410
2542
  throw substratError('not_found', `unknown tenant: ${tenantId}`);
2411
2543
  if (before.status !== 'deleting') {
2412
2544
  throw substratError('conflict', `tenant ${tenantId} is ${before.status}, not deleting — only a deleting tenant may be reaped`);
2413
2545
  }
2546
+ if (deletingBy !== undefined && (before.deletingAt === null || before.deletingAt > deletingBy)) {
2547
+ throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
2548
+ }
2414
2549
  // KEPT as the tombstone: the `tenants` row itself and `_substrat_admin_log` (the
2415
2550
  // compliance witness — never swept). Scope rows were already reaped individually.
2416
2551
  // One unit with the flip and `audit`, whose `before` is the status read here.
@@ -2699,7 +2834,33 @@ export class ControlPlaneDO extends DurableObject {
2699
2834
  // Idempotency is on the scope_id (§3.3: idempotent and journaled — safe to
2700
2835
  // re-run), so an existing scope short-circuits before the slug check:
2701
2836
  // re-provisioning must not collide with itself.
2702
- const existed = this.sql.exec('SELECT 1 FROM scopes WHERE scope_id = ?', scopeId).toArray()[0] !== undefined;
2837
+ const existing = this.sql.exec('SELECT scope_type, parent_scope_id FROM scopes WHERE scope_id = ?', scopeId).toArray()[0];
2838
+ const existed = existing !== undefined;
2839
+ // #2995: the link is fixed at the first provision; a re-provision restates it or names none.
2840
+ const parentScopeId = provisionedParent(record.parentScopeId, existing ? existing.parent_scope_id : undefined, scopeId);
2841
+ // #2993: a scope's type is fixed when it is provisioned. The host judged it against the row it
2842
+ // read; judged again here, in the write's own unit, so a provision racing another with a
2843
+ // different type cannot both succeed. Absent: a host with no declared types, as before.
2844
+ if (existing && record.scopeType !== undefined && (existing.scope_type ?? null) !== record.scopeType) {
2845
+ throw substratError('conflict', `scope ${scopeId} is a '${existing.scope_type ?? 'home'}' scope, and a scope's type is fixed when it is ` +
2846
+ `provisioned: it cannot become '${record.scopeType ?? 'home'}'`);
2847
+ }
2848
+ if (!existed && parentScopeId !== null) {
2849
+ const parent = this.sql
2850
+ .exec('SELECT tenant_id, status, parent_scope_id, forked_from FROM scopes WHERE scope_id = ?', parentScopeId)
2851
+ .toArray()[0];
2852
+ if (!parent || parent.tenant_id !== tenantId) {
2853
+ throw substratError('not_found', `unknown parent scope for tenant: (${tenantId}, ${parentScopeId})`);
2854
+ }
2855
+ if (parent.status !== 'active') {
2856
+ throw substratError('conflict', `scope ${parentScopeId} is ${parent.status}: a child is provisioned under an active scope only`);
2857
+ }
2858
+ if (parent.forked_from !== null)
2859
+ throw substratError('conflict', `scope ${parentScopeId} is a copy, and a copy holds no children`);
2860
+ if (parent.parent_scope_id !== null) {
2861
+ throw substratError('validation_failed', `scope ${parentScopeId} is a child itself, and children are one level deep`);
2862
+ }
2863
+ }
2703
2864
  if (!existed) {
2704
2865
  // An `archived` scope (a deleted app) has released its name — and `reaped` is past
2705
2866
  // archived, so it too has released it — both excluded so the slug can be reclaimed.
@@ -2710,6 +2871,19 @@ export class ControlPlaneDO extends DurableObject {
2710
2871
  throw substratError('conflict', `scope slug '${record.slug}' already taken under tenant ${tenantId} ` +
2711
2872
  `by ${slugOwner.scope_id} (slugs are unique within a tenant)`);
2712
2873
  }
2874
+ // #3625 (K-64): one home scope per (tenant, app, environment): a second install is refused.
2875
+ if (record.claimsHome) {
2876
+ const secondHome = secondHomeRefusal(this.kernelSql, tenantId, scopeId, {
2877
+ vertical: record.vertical,
2878
+ type: record.scopeType ?? HOME_SCOPE_TYPE,
2879
+ parentScopeId,
2880
+ forkedFrom: record.forkedFrom,
2881
+ kind: record.kind,
2882
+ install: true,
2883
+ });
2884
+ if (secondHome)
2885
+ throw secondHome;
2886
+ }
2713
2887
  // A scope born while its vertical serves in place (#286) is born ON the serving
2714
2888
  // script — provisioning dispatches there — so its routing points there from row
2715
2889
  // one. Sub-selected at insert: per-scope truth that later serves can't disturb.
@@ -2724,11 +2898,14 @@ export class ControlPlaneDO extends DurableObject {
2724
2898
  // sub-select yields NULL and routing falls through to the bound version's ref.
2725
2899
  const inheritServingSlug = record.kind === 'preview' ? null : record.vertical;
2726
2900
  this.sql.exec(`INSERT INTO scopes
2727
- (scope_id, tenant_id, parent_scope_id, slug, kind, name, vertical,
2901
+ (scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
2728
2902
  storage_shape, jurisdiction, status, forked_from, forked_at, expires_at,
2729
2903
  serving_ref, created_at)
2730
- VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2731
- (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, inheritServingSlug, createdAt);
2904
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2905
+ (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId, parentScopeId,
2906
+ // #2993: NULL for 'home', so a host with no declared types writes exactly the row it always did.
2907
+ record.scopeType ?? null, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, inheritServingSlug, createdAt);
2908
+ this.armSnapshotReap(scopeId, record.expiresAt);
2732
2909
  }
2733
2910
  return !existed;
2734
2911
  }
@@ -2776,10 +2953,28 @@ export class ControlPlaneDO extends DurableObject {
2776
2953
  where.push('vertical = ?');
2777
2954
  params.push(filter.vertical);
2778
2955
  }
2956
+ if (filter.parentScopeId) {
2957
+ where.push('parent_scope_id = ?');
2958
+ params.push(filter.parentScopeId);
2959
+ }
2779
2960
  const tail = keysetTail(where, params, 'scope_id', filter);
2780
2961
  const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
2781
2962
  return this.sql.exec(sql, ...params).toArray();
2782
2963
  }
2964
+ /**
2965
+ * #2993 part 4: the scope types other than `home` that the vertical's scopes hold, every tenant's
2966
+ * and every status but `reaped`, each once. What a promote judges the incoming version's declared
2967
+ * types against. A vertical none of whose scopes is typed answers `[]`.
2968
+ */
2969
+ scopeTypesHeldBy(vertical, servingRef) {
2970
+ // K-65 (#3539): with `servingRef`, the scopes on that script alone: all a release into an earlier
2971
+ // major reaches. A DO from before ignores it and judges every scope, which only refuses more.
2972
+ const onScript = servingRef === undefined ? '' : ' AND serving_ref = ?';
2973
+ return this.sql
2974
+ .exec(`SELECT DISTINCT scope_type FROM scopes WHERE vertical = ?${onScript} AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type`, ...(servingRef === undefined ? [vertical] : [vertical, servingRef]))
2975
+ .toArray()
2976
+ .map((r) => String(r.scope_type));
2977
+ }
2783
2978
  /** #2178: `PROVISIONED_VERSIONS_SQL` over the directory — one row per version, however many scopes. */
2784
2979
  provisionedVersionsOf(vertical, serving, ownerTenant) {
2785
2980
  return installsReconciledOf(this.sql.exec(PROVISIONED_VERSIONS_SQL, ...provisionedVersionsParams(vertical, serving, ownerTenant)).toArray());
@@ -2892,8 +3087,59 @@ export class ControlPlaneDO extends DurableObject {
2892
3087
  * for it, since the row can be deleted (`deleteScopeDirectory`) between the two.
2893
3088
  */
2894
3089
  transitionScopeOrRefusal(tenantId, scopeId, from, to, action) {
3090
+ const judged = this.judgeTransition(tenantId, scopeId, from, to, action);
3091
+ if (!judged.ok)
3092
+ return judged;
3093
+ // One transaction: the status and — on a reap — the scope's switch records (#1674).
3094
+ // Reaped is terminal, so a cleanup that failed after the flip could never be retried.
3095
+ this.ctx.storage.transactionSync(() => this.applyTransition(tenantId, scopeId, judged.status, to));
3096
+ return judged;
3097
+ }
3098
+ /**
3099
+ * #2995 (K-64): archive a scope AND its children, in one unit, so a child never outlives its parent
3100
+ * by a crash between two writes. The parent is judged as `transitionScopeOrRefusal` judges it; each
3101
+ * child in `from` is archived with it, and a child already archived or reaped is left as it is. A
3102
+ * refused parent archives none. Answers the parent's previous state and each child's, for the
3103
+ * coordinator's audit rows and its lifecycle deliveries.
3104
+ */
3105
+ archiveScopeFamilyOrRefusal(tenantId, scopeId, from, action) {
3106
+ const judged = this.judgeTransition(tenantId, scopeId, from, 'archived', action);
3107
+ if (!judged.ok)
3108
+ return judged;
3109
+ const children = this.sql
3110
+ .exec(`SELECT scope_id, status, vertical FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status IN (${from.map(() => '?').join(', ')})
3111
+ ORDER BY scope_id`, tenantId, scopeId, ...from)
3112
+ .toArray().map((c) => ({
3113
+ scopeId: c.scope_id,
3114
+ status: c.status,
3115
+ vertical: c.vertical,
3116
+ }));
3117
+ this.ctx.storage.transactionSync(() => {
3118
+ for (const child of children)
3119
+ this.applyTransition(tenantId, child.scopeId, child.status, 'archived');
3120
+ this.applyTransition(tenantId, scopeId, judged.status, 'archived');
3121
+ });
3122
+ const dueAt = this.autoReapAt('SCOPE_RETENTION_DAYS', Date.now());
3123
+ if (dueAt !== undefined) {
3124
+ this.armTenantDueWork(tenantId, [scopeId, ...children.map((child) => child.scopeId)]
3125
+ .map((unit) => ({ kind: 'retention', unit, dueAt })));
3126
+ }
3127
+ return { ...judged, children };
3128
+ }
3129
+ /**
3130
+ * #2995: the ids of `parentScopeId`'s children in `tenantId` whose status is one of `statuses`, oldest
3131
+ * first. What a coordinator reaps before their parent: a child does not outlive it.
3132
+ */
3133
+ childScopeIds(tenantId, parentScopeId, statuses) {
3134
+ return this.sql
3135
+ .exec(`SELECT scope_id FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status IN (${statuses.map(() => '?').join(', ')})
3136
+ ORDER BY scope_id`, tenantId, parentScopeId, ...statuses)
3137
+ .toArray().map((r) => r.scope_id);
3138
+ }
3139
+ /** A transition's refusal, read in the same synchronous turn as the write that follows it. */
3140
+ judgeTransition(tenantId, scopeId, from, to, action) {
2895
3141
  const row = this.sql
2896
- .exec('SELECT tenant_id, status, vertical, stores_fenced_at FROM scopes WHERE scope_id = ?', scopeId)
3142
+ .exec('SELECT tenant_id, status, vertical, stores_fenced_at, parent_scope_id FROM scopes WHERE scope_id = ?', scopeId)
2897
3143
  .toArray()[0];
2898
3144
  if (!row || row.tenant_id !== tenantId) {
2899
3145
  return { ok: false, code: 'not_found', message: `unknown scope for tenant: (${tenantId}, ${scopeId})` };
@@ -2901,6 +3147,32 @@ export class ControlPlaneDO extends DurableObject {
2901
3147
  if (to === 'active' && row.stores_fenced_at !== null) {
2902
3148
  return { ok: false, code: 'conflict', message: storesFencedRefusal(scopeId) };
2903
3149
  }
3150
+ // #2995: a child does not outlive its parent. None comes back (an unarchive, an unsuspend or a late
3151
+ // activation) while its parent is archived or reaped.
3152
+ if (to === 'active' && row.parent_scope_id !== null) {
3153
+ const parent = this.sql.exec('SELECT status FROM scopes WHERE scope_id = ?', row.parent_scope_id).toArray()[0];
3154
+ if (!parent || parent.status === 'archived' || parent.status === 'reaped') {
3155
+ return {
3156
+ ok: false,
3157
+ code: 'conflict',
3158
+ message: `scope ${scopeId} is a child of ${row.parent_scope_id}, which is ${parent?.status ?? 'gone'}: a child does not outlive its parent`,
3159
+ };
3160
+ }
3161
+ }
3162
+ // #2995: nor is a parent reaped while a child of it is not. A hosted child's bytes live in its
3163
+ // vertical's deployment, so the coordinator reaps each child first (`childScopeIds`); this is the fence.
3164
+ if (to === 'reaped') {
3165
+ const child = this.sql
3166
+ .exec("SELECT scope_id FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status != 'reaped' LIMIT 1", tenantId, scopeId)
3167
+ .toArray()[0];
3168
+ if (child) {
3169
+ return {
3170
+ ok: false,
3171
+ code: 'conflict',
3172
+ message: `scope ${scopeId} holds child ${child.scope_id}, which is not reaped: a child is reaped before its parent`,
3173
+ };
3174
+ }
3175
+ }
2904
3176
  if (!from.includes(row.status)) {
2905
3177
  return {
2906
3178
  ok: false,
@@ -2909,35 +3181,34 @@ export class ControlPlaneDO extends DurableObject {
2909
3181
  `(allowed from: ${from.join('|')})`,
2910
3182
  };
2911
3183
  }
2912
- // One transaction: the status and — on a reap — the scope's switch records (#1674).
2913
- // Reaped is terminal, so a cleanup that failed after the flip could never be retried.
2914
- this.ctx.storage.transactionSync(() => {
2915
- // Stamp/clear archived_at so the reap sweep can age scopes. Entering `archived`
2916
- // records when; `unarchive` (→ active, a restore per §4.2) clears it so a later
2917
- // re-archive dates from the new event. `reaped` keeps it — it is terminal history.
2918
- // #1524: the status it left is recorded beside the stamp and cleared with it.
2919
- if (to === 'archived') {
2920
- this.sql.exec('UPDATE scopes SET status = ?, archived_at = ?, archived_from_status = ? WHERE scope_id = ?', to, new Date().toISOString(), row.status, scopeId);
2921
- }
2922
- else if (to === 'active') {
2923
- this.sql.exec('UPDATE scopes SET status = ?, archived_at = NULL, archived_from_status = NULL WHERE scope_id = ?', to, scopeId);
2924
- }
2925
- else {
2926
- this.sql.exec('UPDATE scopes SET status = ? WHERE scope_id = ?', to, scopeId);
2927
- }
2928
- if (to === 'archived' || to === 'reaped') {
2929
- this.sql.exec('UPDATE peer_bindings SET invalidated = 1 WHERE tenant_id = ? AND target_scope_id = ?', tenantId, scopeId);
2930
- }
2931
- if (to === 'reaped') {
2932
- forgetSwitchesOf(this.kernelSql, scopeId);
2933
- this.forgetLifecycleDeliveries('scope_id = ?', scopeId);
2934
- // #2515: its storage is gone, and its measured days are kept for the invoice (retention ends them).
2935
- retireScopeStorage(doRedactionSql(this.sql), scopeId);
2936
- }
2937
- this.bumpLifecycleRevision(`scope:${scopeId}`); // #1713, with the status it counts
2938
- });
2939
3184
  return { ok: true, status: row.status, vertical: row.vertical };
2940
3185
  }
3186
+ /** The writes of one judged transition. Called inside the caller's transaction. */
3187
+ applyTransition(tenantId, scopeId, previous, to) {
3188
+ // Stamp/clear archived_at so the reap sweep can age scopes. Entering `archived`
3189
+ // records when; `unarchive` (→ active, a restore per §4.2) clears it so a later
3190
+ // re-archive dates from the new event. `reaped` keeps it — it is terminal history.
3191
+ // #1524: the status it left is recorded beside the stamp and cleared with it.
3192
+ if (to === 'archived') {
3193
+ this.sql.exec('UPDATE scopes SET status = ?, archived_at = ?, archived_from_status = ? WHERE scope_id = ?', to, new Date().toISOString(), previous, scopeId);
3194
+ }
3195
+ else if (to === 'active') {
3196
+ this.sql.exec('UPDATE scopes SET status = ?, archived_at = NULL, archived_from_status = NULL WHERE scope_id = ?', to, scopeId);
3197
+ }
3198
+ else {
3199
+ this.sql.exec('UPDATE scopes SET status = ? WHERE scope_id = ?', to, scopeId);
3200
+ }
3201
+ if (to === 'archived' || to === 'reaped') {
3202
+ this.sql.exec('UPDATE peer_bindings SET invalidated = 1 WHERE tenant_id = ? AND target_scope_id = ?', tenantId, scopeId);
3203
+ }
3204
+ if (to === 'reaped') {
3205
+ forgetSwitchesOf(this.kernelSql, scopeId);
3206
+ this.forgetLifecycleDeliveries('scope_id = ?', scopeId);
3207
+ // #2515: its storage is gone, and its measured days are kept for the invoice (retention ends them).
3208
+ retireScopeStorage(doRedactionSql(this.sql), scopeId);
3209
+ }
3210
+ this.bumpLifecycleRevision(`scope:${scopeId}`); // #1713, with the status it counts
3211
+ }
2941
3212
  // -- roles (checker rule 1) -------------------------------------------------
2942
3213
  /**
2943
3214
  * Kept for a coordinator from before #2447, which calls it and reads the previous role (for the
@@ -2946,10 +3217,13 @@ export class ControlPlaneDO extends DurableObject {
2946
3217
  * that never happened.
2947
3218
  */
2948
3219
  defineRole(tenantId, role) {
3220
+ const settle = (outcome) => {
3221
+ if ('refused' in outcome)
3222
+ throw new Error(outcome.refused);
3223
+ return outcome.before;
3224
+ };
2949
3225
  const outcome = this.defineRoleOrRefusal(tenantId, role);
2950
- if ('refused' in outcome)
2951
- throw new Error(outcome.refused);
2952
- return outcome.before;
3226
+ return outcome instanceof Promise ? outcome.then(settle) : settle(outcome);
2953
3227
  }
2954
3228
  /**
2955
3229
  * INSERT OR REPLACE; answer the previous role (for the audit `before`) or null. Judged first, in
@@ -2964,87 +3238,86 @@ export class ControlPlaneDO extends DurableObject {
2964
3238
  * coordinator from before #2526 passes none and records its own.
2965
3239
  */
2966
3240
  defineRoleOrRefusal(tenantId, role, reservation = { reserved: [], declared: [] }, seatedInScopes = false, audit) {
3241
+ // K-68 step 3e: a cut-over tenant's role is judged and written in its own object first, the
3242
+ // directory's copy and the admin row after it (`directory-cutover.ts`). Asked in the method's
3243
+ // first synchronous step, so the flag and the write that follows it are of the same moment.
3244
+ if (this.directoryCutover?.isCutOver(tenantId)) {
3245
+ return this.directoryCutover.defineRole(tenantId, role, reservation, seatedInScopes, audit ?? null);
3246
+ }
2967
3247
  return this.ctx.storage.transactionSync(() => {
2968
- const outcome = this.defineRoleIn(tenantId, role, reservation, seatedInScopes);
3248
+ const outcome = defineRoleRow(this.sql, tenantId, role, reservation, seatedInScopes, new Date().toISOString());
2969
3249
  if (audit && 'before' in outcome)
2970
3250
  this.recordAdmin({ ...audit, before: outcome.before });
2971
3251
  return outcome;
2972
3252
  });
2973
3253
  }
2974
- defineRoleIn(tenantId, role, reservation, seatedInScopes) {
2975
- const tenantRoles = this.listRoles({ tenantId }).map((r) => ({
2976
- key: r.role_key,
2977
- permissions: JSON.parse(r.permissions),
2978
- holder: r.holder ?? undefined,
2979
- }));
2980
- const stored = tenantRoles.find((r) => r.key === role.key);
2981
- const seated = stored?.holder !== 'system' && role.holder === 'system' &&
2982
- (seatedInScopes ||
2983
- this.sql.exec(TENANT_SEATED_ROLES_SQL, tenantId, new Date().toISOString()).toArray().some((r) => r.role_key === role.key));
2984
- const refused = reservedRoleDefinitionRefusal(role, { reserved: new Set(reservation.reserved), declared: new Set(reservation.declared) }, tenantRoles, seated);
2985
- if (refused)
2986
- return { refused };
2987
- const before = this.getRole(tenantId, role.key) ?? null;
2988
- this.sql.exec(`INSERT OR REPLACE INTO _substrat_roles (tenant_id, role_key, permissions, source, holder)
2989
- VALUES (?, ?, ?, ?, ?)`, tenantId, role.key, JSON.stringify(role.permissions), String(role.source), role.holder ?? 'person');
2990
- return { before };
2991
- }
2992
- /** Raw rows; the coordinator parses them through the `tenantRole` contract. */
3254
+ /** Raw rows; the coordinator parses them through the `tenantRole` contract. One cut-over tenant's are its object's (3e). */
2993
3255
  listRoles(filter) {
2994
- const where = [];
2995
- const params = [];
2996
- if (filter.tenantId) {
2997
- where.push('tenant_id = ?');
2998
- params.push(filter.tenantId);
2999
- }
3000
- if (filter.source) {
3001
- where.push('source = ?');
3002
- params.push(filter.source);
3003
- }
3004
- const order = (filter.order ?? 'asc') === 'desc' ? 'DESC' : 'ASC';
3005
- if (filter.cursor) {
3006
- // Composite sort key `${tenantId}|${roleKey}` (pagination.ts) — the
3007
- // tenant id is a ULID and never contains '|', so split on the FIRST.
3008
- const split = filter.cursor.indexOf('|');
3009
- const afterTenant = split === -1 ? filter.cursor : filter.cursor.slice(0, split);
3010
- const afterKey = split === -1 ? '' : filter.cursor.slice(split + 1);
3011
- const cmp = order === 'DESC' ? '<' : '>';
3012
- where.push(`(tenant_id ${cmp} ? OR (tenant_id = ? AND role_key ${cmp} ?))`);
3013
- params.push(afterTenant, afterTenant, afterKey);
3014
- }
3015
- let sql = 'SELECT tenant_id, role_key, permissions, source, holder FROM _substrat_roles' +
3016
- (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
3017
- ` ORDER BY tenant_id ${order}, role_key ${order}`;
3018
- if (filter.limit !== undefined) {
3019
- sql += ' LIMIT ?';
3020
- params.push(assertRowLimit('limit', filter.limit));
3021
- }
3022
- return this.sql.exec(sql, ...params).toArray();
3256
+ if (filter.tenantId && this.directoryCutover?.isCutOver(filter.tenantId))
3257
+ return this.directoryCutover.listRoles(filter.tenantId, filter);
3258
+ return listRoleRows(this.sql, filter);
3023
3259
  }
3260
+ /** A role as stored; a cut-over tenant's from its object (3e). The decisions in this object read `readRole` directly. */
3024
3261
  getRole(tenantId, key) {
3025
- const row = this.sql
3026
- .exec('SELECT role_key, permissions, source, holder FROM _substrat_roles WHERE tenant_id = ? AND role_key = ?', tenantId, key)
3027
- .toArray()[0];
3028
- if (!row)
3029
- return undefined;
3262
+ if (this.directoryCutover?.isCutOver(tenantId))
3263
+ return this.directoryCutover.getRole(tenantId, key);
3264
+ return readRole(this.sql, tenantId, key);
3265
+ }
3266
+ // -- tenant-level tuples (checker rules 1, 2, 4) ----------------------------
3267
+ // K-68 step 3e (the second family): a tenant whose flip froze its tuples in reads them from, and
3268
+ // writes them first to, its own object (`directory-cutover.ts`). Every unit below runs the same code
3269
+ // in either store (`directory-tenant-tuples.ts`); which one is asked in the method's first
3270
+ // synchronous step, so the flag and the write that follows it are of the same moment.
3271
+ /** Whether the tenant's tuples and removal fences are read from, and first written to, its own object. */
3272
+ tuplesCutOver(tenantId) {
3273
+ return this.directoryCutover?.cutOverFor(tenantId, TENANT_TUPLES) ?? false;
3274
+ }
3275
+ /** Whether the tenant's organizations are read from, and first written to, its own object (the third family). */
3276
+ orgsCutOver(tenantId) {
3277
+ return this.directoryCutover?.cutOverFor(tenantId, ORGS) ?? false;
3278
+ }
3279
+ /** This directory as a `TupleStore`: its rows, its admin log, its orgs. */
3280
+ tupleStore() {
3030
3281
  return {
3031
- key: row.role_key,
3032
- permissions: JSON.parse(row.permissions),
3033
- source: row.source,
3034
- holder: row.holder ?? undefined,
3282
+ sql: this.sql,
3283
+ now: () => new Date().toISOString(),
3284
+ admin: (entry) => this.recordAdmin(entry),
3285
+ orgKnown: (tenantId, orgId) => !!readOrgRow(this.sql, tenantId, orgId),
3035
3286
  };
3036
3287
  }
3037
- // -- tenant-level tuples (checker rules 1, 2, 4) ----------------------------
3288
+ /**
3289
+ * Run `fn` with no other call into this object between its first step and its end. For a cut-over
3290
+ * tenant's unit that reads what this directory still writes (a system switch, a connection) and
3291
+ * writes first in the tenant's object: the read, the object's write and the fallback are then one
3292
+ * step for every other call here, as the synchronous unit is for a tenant not cut over. A failure
3293
+ * is answered after the step, never thrown inside it (a throw there resets the object).
3294
+ */
3295
+ async exclusive(fn) {
3296
+ const out = await this.ctx.blockConcurrencyWhile(async () => {
3297
+ try {
3298
+ return { value: await fn() };
3299
+ }
3300
+ catch (error) {
3301
+ return { error };
3302
+ }
3303
+ });
3304
+ if ('error' in out)
3305
+ throw out.error;
3306
+ return out.value;
3307
+ }
3038
3308
  /**
3039
3309
  * A tenant tuple, upserted. With `audit` (#2526, `grant` at the tenant node, called through
3040
3310
  * `reply`), its admin row commits in the same transaction; without, as a coordinator from before
3041
- * #2526 calls it, and as this object's own units do, it is the bare write.
3311
+ * #2526 calls it, it is the bare write.
3042
3312
  */
3043
3313
  writeTenantTuple(tenantId, subject, relation, object, expiresAt, audit) {
3314
+ if (this.tuplesCutOver(tenantId)) {
3315
+ return this.directoryCutover.tupleWrite(tenantId, {
3316
+ kind: 'write', subject, relation, object, expiresAt, audit: audit ?? null,
3317
+ }).then(() => undefined);
3318
+ }
3044
3319
  const write = () => {
3045
- this.sql.exec(`INSERT OR REPLACE INTO _substrat_tenant_tuples
3046
- (tenant_id, subject, relation, object, expires_at)
3047
- VALUES (?, ?, ?, ?, ?)`, tenantId, subject, relation, object, expiresAt);
3320
+ writeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, expiresAt);
3048
3321
  return true;
3049
3322
  };
3050
3323
  if (audit)
@@ -3059,41 +3332,71 @@ export class ControlPlaneDO extends DurableObject {
3059
3332
  * writes nothing. A role not defined here is not judged, as before.
3060
3333
  */
3061
3334
  assignTenantRole(tenantId, principal, roleKey, reserved, audit) {
3062
- return this.ctx.storage.transactionSync(() => {
3063
- const role = reserved.length > 0 ? this.getRole(tenantId, roleKey) : undefined;
3064
- const refused = role ? reservedRoleRefusal(role, new Set(reserved), 'platform') : null;
3065
- if (refused)
3066
- return { refused };
3067
- this.writeTenantTuple(tenantId, `principal:${principal}`, `role:${roleKey}`, `tenant:${tenantId}`, null);
3068
- this.recordAdmin(audit);
3069
- return {};
3070
- });
3335
+ if (this.tuplesCutOver(tenantId)) {
3336
+ return this.directoryCutover.tupleWrite(tenantId, {
3337
+ kind: 'assignRole', principal, roleKey, reserved: [...reserved], audit: audit,
3338
+ });
3339
+ }
3340
+ return this.ctx.storage.transactionSync(() => assignTenantRoleIn(this.tupleStore(), tenantId, principal, roleKey, reserved, audit));
3071
3341
  }
3072
3342
  /**
3073
3343
  * #2526: a tenant tuple that names an org — `grantToOrg` at the tenant node, and `addMember` —
3074
- * with its admin row, in one unit, refused `not_found` when the org is not in the tenant.
3344
+ * with its admin row, in one unit, refused `not_found` when the org is not in the tenant. For a
3345
+ * cut-over tenant the org is asked here first: an org is never removed from a live tenant, so the
3346
+ * answer still holds when the object writes.
3075
3347
  */
3076
3348
  writeOrgTenantTuple(tenantId, orgId, subject, relation, object, expiresAt, audit) {
3349
+ const unknown = () => substratError('not_found', `unknown org ${orgId} in tenant ${tenantId}`);
3350
+ if (this.orgsCutOver(tenantId)) {
3351
+ // The org and the tuple are both the object's: it judges the one and writes the other in one unit.
3352
+ return this.directoryCutover.tupleWrite(tenantId, {
3353
+ kind: 'orgTuple', orgId, subject, relation, object, expiresAt, audit: audit,
3354
+ }).then((r) => {
3355
+ if (r.unknownOrg)
3356
+ throw unknown();
3357
+ });
3358
+ }
3359
+ if (this.tuplesCutOver(tenantId)) {
3360
+ if (!readOrgRow(this.sql, tenantId, orgId))
3361
+ throw unknown();
3362
+ return this.directoryCutover.tupleWrite(tenantId, {
3363
+ kind: 'write', subject, relation, object, expiresAt, audit: audit,
3364
+ }).then(() => undefined);
3365
+ }
3077
3366
  this.writeAndAudit(() => {
3078
- if (!this.readOrg(tenantId, orgId))
3079
- throw substratError('not_found', `unknown org ${orgId} in tenant ${tenantId}`);
3080
- this.writeTenantTuple(tenantId, subject, relation, object, expiresAt);
3367
+ if (!readOrgRow(this.sql, tenantId, orgId))
3368
+ throw unknown();
3369
+ writeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, expiresAt);
3081
3370
  return true;
3082
3371
  }, audit);
3083
3372
  }
3084
3373
  /**
3085
3374
  * #1743: a tenant-level `system:<module>` grant, refused while the record holds the module
3086
3375
  * off on any scope (`scopesSwitchedOffFor`). Synchronous, so the read and the write are one
3087
- * DO unit. Answers the switched-off scopes; non-empty means nothing was written. With `audit`
3088
- * (#2526, through `reply`), the row commits with the tuple, and a refusal records none.
3376
+ * DO unit; for a cut-over tenant, one exclusive step (`exclusive`), the switch read here and the
3377
+ * grant written first in the object. Answers the switched-off scopes; non-empty means nothing was
3378
+ * written. With `audit` (#2526, through `reply`), the row commits with the tuple, and a refusal
3379
+ * records none.
3089
3380
  */
3090
3381
  writeTenantSystemGrant(tenantId, moduleId, relation, expiresAt, audit) {
3382
+ if (this.tuplesCutOver(tenantId)) {
3383
+ return this.exclusive(async () => {
3384
+ const off = scopesSwitchedOffFor(this.kernelSql, tenantId, moduleId);
3385
+ if (off.length > 0)
3386
+ return off;
3387
+ await this.directoryCutover.tupleWrite(tenantId, {
3388
+ kind: 'write', subject: `system:${moduleId}`, relation, object: `tenant:${tenantId}`, expiresAt,
3389
+ audit: audit ?? null,
3390
+ });
3391
+ return [];
3392
+ });
3393
+ }
3091
3394
  let off = [];
3092
3395
  this.writeAndAudit(() => {
3093
3396
  off = scopesSwitchedOffFor(this.kernelSql, tenantId, moduleId);
3094
3397
  if (off.length > 0)
3095
3398
  return false;
3096
- this.writeTenantTuple(tenantId, `system:${moduleId}`, relation, `tenant:${tenantId}`, expiresAt);
3399
+ writeTenantTupleIn(this.tupleStore(), tenantId, `system:${moduleId}`, relation, `tenant:${tenantId}`, expiresAt);
3097
3400
  return true;
3098
3401
  }, audit);
3099
3402
  return off;
@@ -3153,6 +3456,10 @@ export class ControlPlaneDO extends DurableObject {
3153
3456
  peerBindings(tenantId, callerScopeId) {
3154
3457
  return this.sql.exec('SELECT vertical, target_scope_id, invalidated FROM peer_bindings WHERE tenant_id = ? AND caller_scope_id = ? ORDER BY vertical', tenantId, callerScopeId).toArray();
3155
3458
  }
3459
+ /** #3625 (K-64): the home scope of (tenant, app, environment), or null (kernel `homeScopeIn`). */
3460
+ homeScopeOf(tenantId, vertical, environment) {
3461
+ return homeScopeIn(this.kernelSql, tenantId, vertical, environment);
3462
+ }
3156
3463
  /** D-83 (#3530 step 3): the app's environments in the tenant, production first (kernel `environmentsOf`). */
3157
3464
  listEnvironments(tenantId, vertical) {
3158
3465
  return environmentsOf(this.kernelSql, tenantId, vertical);
@@ -3179,6 +3486,67 @@ export class ControlPlaneDO extends DurableObject {
3179
3486
  }, () => ({ ...audit, scopeId: out.scopeId, before: { vertical: input.vertical, scopeId: out.scopeId } }));
3180
3487
  return { removed: out.removed };
3181
3488
  }
3489
+ /**
3490
+ * #3530 step 4: record what an environment's own serving script now runs, compare-and-set on the
3491
+ * record the upload diffed from (kernel `setEnvironmentServingIn`), with its admin row in the
3492
+ * same transaction. False, with nothing written and no row, when the record moved since.
3493
+ */
3494
+ setEnvironmentServingAndAudit(input, next, expected, audit, claim,
3495
+ /** #3638: what this serve acknowledges in this environment, judged and recorded here. */
3496
+ acknowledge) {
3497
+ let out;
3498
+ this.writeAndAudit(() => {
3499
+ out = setEnvironmentServingIn(this.kernelSql, input, next, expected, claim, acknowledge);
3500
+ return out.moved;
3501
+ }, () => ({
3502
+ ...audit,
3503
+ scopeId: out.scopeId,
3504
+ before: out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
3505
+ after: { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId, ...(acknowledge ? { acknowledged: acknowledge } : {}) },
3506
+ }));
3507
+ return out.moved;
3508
+ }
3509
+ /**
3510
+ * #3530 step 4: take an environment's serve lease (kernel `claimEnvironmentServeIn`), so its serves
3511
+ * run one at a time. Unaudited: it moves nothing a reader sees, and the serve it guards is audited.
3512
+ */
3513
+ claimEnvironmentServe(input, claim, leaseMs) {
3514
+ let held = false;
3515
+ this.writeAndAudit(() => {
3516
+ const now = Date.now();
3517
+ held = claimEnvironmentServeIn(this.kernelSql, input, claim, { now: new Date(now).toISOString(), until: new Date(now + leaseMs).toISOString() });
3518
+ return held;
3519
+ });
3520
+ return held;
3521
+ }
3522
+ /** #3530 step 4: give the lease back, if `claim` still holds it. */
3523
+ releaseEnvironmentServe(input, claim) {
3524
+ this.writeAndAudit(() => {
3525
+ releaseEnvironmentServeIn(this.kernelSql, input, claim);
3526
+ return true;
3527
+ });
3528
+ }
3529
+ /**
3530
+ * #3530 step 6: give a named environment connections of its own, or take that back (kernel
3531
+ * `setEnvironmentEffectsIn`), with its admin row in the same transaction. No row when nothing changed.
3532
+ */
3533
+ setEnvironmentEffectsAndAudit(input, effects, audit) {
3534
+ let out;
3535
+ this.writeAndAudit(() => {
3536
+ out = setEnvironmentEffectsIn(this.kernelSql, input, effects);
3537
+ return out.changed;
3538
+ }, () => ({
3539
+ ...audit,
3540
+ scopeId: out.scopeId,
3541
+ before: { effects: out.before },
3542
+ after: { vertical: input.vertical, scopeId: out.scopeId, effects },
3543
+ }));
3544
+ return { changed: out.changed, before: out.before };
3545
+ }
3546
+ /** #3530 step 6: which connections the scope's effects may go through (kernel `connectionReachIn`). */
3547
+ connectionReach(tenantId, scopeId) {
3548
+ return connectionReachIn(this.kernelSql, tenantId, scopeId);
3549
+ }
3182
3550
  /** Directory write and endpoint checks share this DO's serialized unit. */
3183
3551
  setPeerBinding(tenantId, callerScopeId, vertical, targetScopeId) {
3184
3552
  const caller = this.sql.exec('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?', callerScopeId).toArray()[0];
@@ -3656,6 +4024,24 @@ export class ControlPlaneDO extends DurableObject {
3656
4024
  }, audit && (() => ({ ...audit, before })));
3657
4025
  return !raced;
3658
4026
  }
4027
+ /**
4028
+ * K-65 (#3539): record a release into an earlier major, served on its own script: only that major's
4029
+ * entry of `earlier_majors` moves, compare-and-set on `expected` (`releasedEarlierMajorJson`, which
4030
+ * refuses `precondition_failed`), and `audit`'s `before` is the entry this unit read.
4031
+ */
4032
+ setEarlierMajorServing(slug, major, s, expected, audit) {
4033
+ let before = null;
4034
+ return this.writeAndAudit(() => {
4035
+ const r = this.readVertical(slug);
4036
+ if (!r)
4037
+ throw substratError('not_found', `unknown vertical '${slug}'`);
4038
+ const held = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
4039
+ before = held ? { ref: held.ref, versionId: held.versionId } : null;
4040
+ const earlier = releasedEarlierMajorJson({ vertical: slug, earlierJson: r.earlier_majors, major, expected, next: s });
4041
+ this.sql.exec('UPDATE verticals SET earlier_majors = ? WHERE slug = ?', earlier, slug);
4042
+ return true;
4043
+ }, () => ({ ...audit, before }));
4044
+ }
3659
4045
  /** #2351: the digest of the migrations read from a version's bundle, or `undefined` for no such version. */
3660
4046
  readMigrationsExtracted(id) {
3661
4047
  return versionMigrationsExtractedOf(this.kernelSql, id);
@@ -3693,11 +4079,17 @@ export class ControlPlaneDO extends DurableObject {
3693
4079
  /** Move a fork's GC deadline forward, or pin it (`null`) — preview-and-snapshots.md §9. False
3694
4080
  * when a reap has claimed the row (#3314): its deadline no longer decides anything. */
3695
4081
  setScopeExpiresAt(scopeId, expiresAt, audit) {
3696
- return this.writeAndAudit(() => this.sql.exec('UPDATE scopes SET expires_at = ? WHERE scope_id = ? AND reap_claimed_at IS NULL', expiresAt, scopeId).rowsWritten > 0, audit);
4082
+ const written = this.writeAndAudit(() => this.sql.exec('UPDATE scopes SET expires_at = ? WHERE scope_id = ? AND reap_claimed_at IS NULL', expiresAt, scopeId).rowsWritten > 0, audit);
4083
+ if (written)
4084
+ this.armSnapshotReap(scopeId, expiresAt);
4085
+ return written;
3697
4086
  }
3698
4087
  /** One atomic compare-and-set across the preview row and every entry of its copy move. */
3699
4088
  keepAlivePendingScopeCopy(tenantId, scopeId, moveId, status, expectedExpiresAt, expiresAt, audit) {
3700
- return this.writeAndAudit(() => this.sql.exec(PENDING_COPY_KEEP_ALIVE_SQL, ...pendingCopyKeepAliveParams(expiresAt, tenantId, scopeId, status, expectedExpiresAt, moveId, new Date().toISOString())).rowsWritten > 0, audit);
4089
+ const written = this.writeAndAudit(() => this.sql.exec(PENDING_COPY_KEEP_ALIVE_SQL, ...pendingCopyKeepAliveParams(expiresAt, tenantId, scopeId, status, expectedExpiresAt, moveId, new Date().toISOString())).rowsWritten > 0, audit);
4090
+ if (written)
4091
+ this.armSnapshotReap(scopeId, expiresAt);
4092
+ return written;
3701
4093
  }
3702
4094
  async listVersions(verticalSlug, page) {
3703
4095
  const where = ['vertical_slug = ?'];
@@ -3793,7 +4185,8 @@ export class ControlPlaneDO extends DurableObject {
3793
4185
  */
3794
4186
  moveScopeRow(set, setArgs, scopeId, cond, audit) {
3795
4187
  const now = new Date().toISOString();
3796
- return this.writeAndAudit(() => {
4188
+ let confirmedTenant;
4189
+ const written = this.writeAndAudit(() => {
3797
4190
  const moved = this.sql.exec(`UPDATE scopes SET ${set} WHERE scope_id = ?
3798
4191
  ${cond.expectedVersionId === undefined ? '' : 'AND vertical_version_id IS ?'}
3799
4192
  ${cond.expectedErasureEpoch === undefined ? '' : 'AND COALESCE(erasure_epoch, 0) = ? AND reap_claimed_at IS NULL'}
@@ -3805,9 +4198,15 @@ export class ControlPlaneDO extends DurableObject {
3805
4198
  const { tenant_id } = this.sql.exec('SELECT tenant_id FROM scopes WHERE scope_id = ?', scopeId).one();
3806
4199
  this.sql.exec(COPY_MOVE_CONFIRM_SQL, ...copyMoveConfirmParams(cond.confirmMove, tenant_id, scopeId, now));
3807
4200
  this.sql.exec(COPY_BACKFILL_SUPERSEDE_SQL, tenant_id, scopeId);
4201
+ if (cond.confirmMove.source === 'eligible')
4202
+ confirmedTenant = tenant_id;
3808
4203
  }
3809
4204
  return true;
3810
4205
  }, audit);
4206
+ if (confirmedTenant !== undefined) {
4207
+ this.armTenantDueWork(confirmedTenant, [{ kind: 'copies', unit: confirmedTenant, dueAt: Date.parse(now) }]);
4208
+ }
4209
+ return written;
3811
4210
  }
3812
4211
  /**
3813
4212
  * The directory effect and its admin row either both commit or both roll back. A thunk is
@@ -3880,6 +4279,44 @@ export class ControlPlaneDO extends DurableObject {
3880
4279
  setIssueStatusAndAudit(...args) {
3881
4280
  return this.setIssueStatus(...args);
3882
4281
  }
4282
+ /**
4283
+ * K-63 (#3624): what an erasure did at a master's dependents. An `erased` dependent leaves the
4284
+ * ledger, an `outstanding` one is kept with its next try; one admin row, in the same unit.
4285
+ */
4286
+ recordDependentErasures(tenantId, subjectId, outcomes, audit) {
4287
+ if (outcomes.length === 0)
4288
+ return;
4289
+ this.writeAndAudit(() => {
4290
+ for (const o of outcomes) {
4291
+ if (o.outcome === 'erased') {
4292
+ this.sql.exec(DEPENDENT_ERASURE_SETTLE_SQL, tenantId, subjectId, o.scopeId);
4293
+ }
4294
+ else {
4295
+ this.sql.exec(DEPENDENT_ERASURE_OWE_SQL, tenantId, subjectId, o.scopeId, o.vertical, o.attempts, nextDependentErasureAt(audit.at, o.attempts), o.error, audit.at);
4296
+ }
4297
+ }
4298
+ return true;
4299
+ }, audit);
4300
+ }
4301
+ /**
4302
+ * K-63 (#3624): hold each dependent as owed, before the master's erasure runs. The statements run
4303
+ * in one synchronous call, so the object commits them together. A row already owed is kept.
4304
+ */
4305
+ holdDependentErasures(tenantId, subjectId, dependents) {
4306
+ const now = new Date().toISOString();
4307
+ for (const d of dependents)
4308
+ this.sql.exec(DEPENDENT_ERASURE_HOLD_SQL, tenantId, subjectId, d.scopeId, d.vertical, now, now);
4309
+ }
4310
+ /** K-63 (#3624): the owed dependent erasures due at `now`, oldest due first. */
4311
+ dueDependentErasures(now, limit) {
4312
+ return this.sql.exec(DEPENDENT_ERASURE_DUE_SQL, now, limit).toArray().map((r) => ({
4313
+ tenantId: r.tenant_id,
4314
+ subjectId: r.subject_id,
4315
+ scopeId: r.scope_id,
4316
+ vertical: r.vertical,
4317
+ attempts: r.attempts,
4318
+ }));
4319
+ }
3883
4320
  scopeErasureEpoch(tenantId, scopeId) {
3884
4321
  // NULL on every row from before the column (#1722): the same 0 every CAS compares against.
3885
4322
  const row = this.sql.exec('SELECT COALESCE(erasure_epoch, 0) AS erasure_epoch FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
@@ -3895,12 +4332,15 @@ export class ControlPlaneDO extends DurableObject {
3895
4332
  recordScopeScriptCopy(tenantId, scopeId, scriptRef, moveId, role = null, loadStamp = null, leaseMs = SCOPE_COPY_LEASE_MS) {
3896
4333
  if (!scriptRef || !moveId)
3897
4334
  return 'invalid';
4335
+ const dueAt = Date.now() + leaseMs;
3898
4336
  const written = this.sql.exec(`INSERT INTO scope_script_copies (tenant_id, scope_id, script_ref, move_id, state, role, load_stamp, lease_until)
3899
4337
  SELECT tenant_id, scope_id, ?, ?, 'pending', ?, ?, ? FROM scopes
3900
4338
  WHERE tenant_id = ? AND scope_id = ? AND reap_claimed_at IS NULL
3901
- ON CONFLICT (tenant_id, scope_id, script_ref, move_id) DO NOTHING`, scriptRef, moveId, role, loadStamp, new Date(Date.now() + leaseMs).toISOString(), tenantId, scopeId);
3902
- if (written.rowsWritten > 0)
4339
+ ON CONFLICT (tenant_id, scope_id, script_ref, move_id) DO NOTHING`, scriptRef, moveId, role, loadStamp, new Date(dueAt).toISOString(), tenantId, scopeId);
4340
+ if (written.rowsWritten > 0) {
4341
+ this.armTenantDueWork(tenantId, [{ kind: 'copies', unit: tenantId, dueAt }]);
3903
4342
  return 'recorded';
4343
+ }
3904
4344
  const scope = this.sql.exec('SELECT reap_claimed_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
3905
4345
  .toArray()[0];
3906
4346
  if (!scope)
@@ -3934,7 +4374,9 @@ export class ControlPlaneDO extends DurableObject {
3934
4374
  claimExpiredScopeScriptCopies(input) {
3935
4375
  const limit = assertRowLimit('limit', input.limit);
3936
4376
  return this.ctx.storage.transactionSync(() => {
3937
- const due = this.sql.exec(COPY_EXPIRED_SQL, input.now, limit).toArray();
4377
+ const due = (input.tenantId !== undefined
4378
+ ? this.sql.exec(COPY_EXPIRED_FOR_TENANT_SQL, input.now, input.tenantId, limit)
4379
+ : this.sql.exec(COPY_EXPIRED_SQL, input.now, limit)).toArray();
3938
4380
  const claimed = [];
3939
4381
  for (const r of due) {
3940
4382
  if (this.sql.exec(COPY_CLAIM_SQL, input.owner, input.leaseUntil, r.tenant_id, r.scope_id, r.script_ref, r.move_id, input.now).rowsWritten === 0)
@@ -3946,8 +4388,8 @@ export class ControlPlaneDO extends DurableObject {
3946
4388
  });
3947
4389
  }
3948
4390
  /** `HostAdmin.markScopeStoresFenced`: read and written in one synchronous step, so an unarchive is before or after. */
3949
- markScopeStoresFenced(tenantId, scopeId, whileTenantDeleting, audit) {
3950
- const scope = this.sql.exec('SELECT status, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
4391
+ markScopeStoresFenced(tenantId, scopeId, whileTenantDeleting, audit, deadlines) {
4392
+ const scope = this.sql.exec('SELECT status, archived_at, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
3951
4393
  .toArray()[0];
3952
4394
  if (!scope)
3953
4395
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
@@ -3956,8 +4398,17 @@ export class ControlPlaneDO extends DurableObject {
3956
4398
  if (scope.status !== 'archived') {
3957
4399
  throw substratError('conflict', `scope ${scopeId} is ${scope.status}, not archived, so its stores are not fenced`);
3958
4400
  }
3959
- if (whileTenantDeleting && this.readTenant(tenantId)?.status !== 'deleting') {
3960
- throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
4401
+ if (deadlines?.archivedBy !== undefined && (scope.archived_at === null || scope.archived_at > deadlines.archivedBy)) {
4402
+ throw substratError('conflict', `scope ${scopeId} has not passed its archive retention`);
4403
+ }
4404
+ if (whileTenantDeleting || deadlines?.deletingBy !== undefined) {
4405
+ const tenant = this.readTenant(tenantId);
4406
+ if (tenant?.status !== 'deleting') {
4407
+ throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
4408
+ }
4409
+ if (deadlines?.deletingBy !== undefined && (tenant.deletingAt === null || tenant.deletingAt > deadlines.deletingBy)) {
4410
+ throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
4411
+ }
3961
4412
  }
3962
4413
  this.writeAndAudit(() => this.sql.exec(`UPDATE scopes SET stores_fenced_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE tenant_id = ? AND scope_id = ?`, tenantId, scopeId).rowsWritten > 0, audit && { ...audit, before: { storesFencedAt: null } });
3963
4414
  }
@@ -3987,7 +4438,7 @@ export class ControlPlaneDO extends DurableObject {
3987
4438
  return 'pending';
3988
4439
  }
3989
4440
  settleScopeScriptCopy(tenantId, scopeId, scriptRef, moveId, state, loadStamp, revision, claimedBy) {
3990
- return this.ctx.storage.transactionSync(() => {
4441
+ const written = this.ctx.storage.transactionSync(() => {
3991
4442
  const settled = this.sql.exec(`UPDATE scope_script_copies SET state = ?, load_stamp = ?, revision = ?,
3992
4443
  last_attempt_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
3993
4444
  WHERE tenant_id = ? AND scope_id = ? AND script_ref = ? AND move_id = ?
@@ -3997,11 +4448,27 @@ export class ControlPlaneDO extends DurableObject {
3997
4448
  this.sql.exec(COPY_BACKFILL_SUPERSEDE_SQL, tenantId, scopeId);
3998
4449
  return settled;
3999
4450
  });
4451
+ if (written && state === 'eligible') {
4452
+ this.armTenantDueWork(tenantId, [{ kind: 'copies', unit: tenantId, dueAt: Date.now() }]);
4453
+ }
4454
+ return written;
4000
4455
  }
4001
4456
  touchScopeScriptCopy(tenantId, scopeId, scriptRef, moveId) {
4002
4457
  this.sql.exec(`UPDATE scope_script_copies SET last_attempt_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
4003
4458
  WHERE tenant_id = ? AND scope_id = ? AND script_ref = ? AND move_id = ? AND state = 'eligible'`, tenantId, scopeId, scriptRef, moveId);
4004
4459
  }
4460
+ nextScopeCopyDue(tenantId, now) {
4461
+ return this.sql.exec(`SELECT MIN(CASE WHEN state = 'eligible' THEN ? ELSE COALESCE(lease_until, ?) END) AS dueAt
4462
+ FROM scope_script_copies WHERE tenant_id = ? AND state IN ('eligible', 'pending')`, now, now, tenantId).one().dueAt;
4463
+ }
4464
+ listDueScopeCopyTenants(input) {
4465
+ return this.sql.exec(`SELECT tenant_id AS tenantId,
4466
+ MIN(CASE WHEN state = 'eligible' THEN ? ELSE COALESCE(lease_until, ?) END) AS dueAt
4467
+ FROM scope_script_copies
4468
+ WHERE tenant_id > ?
4469
+ AND (state = 'eligible' OR (state = 'pending' AND (lease_until IS NULL OR lease_until <= ?)))
4470
+ GROUP BY tenant_id ORDER BY tenant_id LIMIT ?`, input.now, input.now, input.after, input.by, assertRowLimit('limit', input.limit)).toArray();
4471
+ }
4005
4472
  listScopeScriptCopies(filter) {
4006
4473
  const where = [];
4007
4474
  const args = [];
@@ -4127,6 +4594,28 @@ export class ControlPlaneDO extends DurableObject {
4127
4594
  return true;
4128
4595
  }, audit);
4129
4596
  }
4597
+ /**
4598
+ * K-65 (#3539): the unit of a release into an earlier major, which moves no channel: its admin row
4599
+ * lands only while major `major`'s script still runs `from`, the version its gates were judged
4600
+ * against, with the listing and the admission read here as `promoteChannel` reads them for prod.
4601
+ * False, with nothing written, when that script moved.
4602
+ */
4603
+ recordEarlierMajorPromote(slug, major, from, versionId, unlistedOnly, audit, breakingWithinMajor) {
4604
+ return this.writeAndAudit(() => {
4605
+ const vertical = this.readVertical(slug);
4606
+ if (earlierMajorsOf(vertical?.earlier_majors).find((m) => m.major === major)?.versionId !== from)
4607
+ return false;
4608
+ const listed = vertical?.listed;
4609
+ if (listed && unlistedOnly)
4610
+ throw listedPromoteRefusal();
4611
+ if (listed && breakingWithinMajor)
4612
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
4613
+ if (listed && from !== versionId && this.versionAdmission(versionId).admission_note === AUTO_ADMISSION_NOTE) {
4614
+ throw autoAdmittedProdRefusal(slug, versionId);
4615
+ }
4616
+ return true;
4617
+ }, audit);
4618
+ }
4130
4619
  listChannels(verticalSlug, page) {
4131
4620
  const where = ['vertical_slug = ?'];
4132
4621
  const params = [verticalSlug];
@@ -4154,23 +4643,19 @@ export class ControlPlaneDO extends DurableObject {
4154
4643
  .toArray();
4155
4644
  }
4156
4645
  // -- organizations (K-22) ---------------------------------------------------
4646
+ // K-68 step 3e (the third family): a tenant whose flip froze its orgs in reads them from, and
4647
+ // creates them first in, its own object (`directory-tenant-orgs.ts`, the same code in either store).
4157
4648
  readOrg(tenantId, orgId) {
4158
- return this.sql
4159
- .exec('SELECT * FROM orgs WHERE tenant_id = ? AND org_id = ?', tenantId, orgId)
4160
- .toArray()[0];
4649
+ if (this.orgsCutOver(tenantId)) {
4650
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'org', orgId }).then((r) => r ?? undefined);
4651
+ }
4652
+ return readOrgRow(this.sql, tenantId, orgId);
4161
4653
  }
4162
4654
  /** Returns false when the org already exists (idempotent); throws on slug collision. */
4163
4655
  createOrg(orgId, tenantId, slug, name, createdAt) {
4164
- if (this.readOrg(tenantId, orgId))
4165
- return false;
4166
- const slugOwner = this.sql
4167
- .exec('SELECT org_id FROM orgs WHERE tenant_id = ? AND slug = ?', tenantId, slug)
4168
- .toArray()[0];
4169
- if (slugOwner) {
4170
- throw substratError('conflict', `org slug '${slug}' already taken by ${slugOwner.org_id} (slugs are unique per tenant)`);
4171
- }
4172
- this.sql.exec('INSERT INTO orgs (org_id, tenant_id, slug, name, created_at) VALUES (?, ?, ?, ?, ?)', orgId, tenantId, slug, name, createdAt);
4173
- return true;
4656
+ if (this.orgsCutOver(tenantId))
4657
+ return this.createOrgFirst(orgId, tenantId, slug, name, createdAt, null);
4658
+ return createOrgIn({ sql: this.sql }, orgId, tenantId, slug, name, createdAt);
4174
4659
  }
4175
4660
  /**
4176
4661
  * #2526: `createOrg` with its admin row, in one unit; an org that already exists writes nothing,
@@ -4179,19 +4664,24 @@ export class ControlPlaneDO extends DurableObject {
4179
4664
  * org created with no row, where an unknown method fails closed.
4180
4665
  */
4181
4666
  insertOrg(orgId, tenantId, slug, name, createdAt, audit) {
4182
- return this.writeAndAudit(() => this.createOrg(orgId, tenantId, slug, name, createdAt), audit);
4667
+ if (this.orgsCutOver(tenantId))
4668
+ return this.createOrgFirst(orgId, tenantId, slug, name, createdAt, audit);
4669
+ return this.writeAndAudit(() => createOrgIn({ sql: this.sql }, orgId, tenantId, slug, name, createdAt), audit);
4670
+ }
4671
+ /** A cut-over tenant's org, created first in its object; a slug's conflict is rethrown here with its code. */
4672
+ async createOrgFirst(orgId, tenantId, slug, name, createdAt, audit) {
4673
+ const r = await this.directoryCutover.tupleWrite(tenantId, {
4674
+ kind: 'createOrg', orgId, slug, name, createdAt, audit: audit,
4675
+ });
4676
+ if ('conflict' in r)
4677
+ throw substratError('conflict', r.conflict);
4678
+ return r.created;
4183
4679
  }
4184
4680
  listOrgs(tenantId) {
4185
- return this.sql
4186
- .exec('SELECT * FROM orgs WHERE tenant_id = ? ORDER BY slug', tenantId)
4187
- .toArray();
4681
+ if (this.orgsCutOver(tenantId))
4682
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'orgs' });
4683
+ return listOrgRows(this.sql, tenantId);
4188
4684
  }
4189
- /** The tenant-level reads, synchronous, for a bound asked inside one of this object's units (#1184). */
4190
- directoryReader = {
4191
- now: () => new Date().toISOString(),
4192
- tenantTuples: (tenantId, subject, prefix) => this.tenantTuples(tenantId, subject, prefix),
4193
- getRole: (tenantId, key) => this.getRole(tenantId, key),
4194
- };
4195
4685
  /**
4196
4686
  * A membership change as ONE DO unit (#1184) — `HostAdmin.applyMembership`. Synchronous, so
4197
4687
  * no other request into this object runs between its reads and its writes: an add's removal
@@ -4204,48 +4694,22 @@ export class ControlPlaneDO extends DurableObject {
4204
4694
  * The org row's `before`/`after` are written here, since only the unit knows the expiry.
4205
4695
  * `reserved` (#2430) is what the coordinator's modules reserve to a system principal: an add of
4206
4696
  * a role carrying one is a person conferring it, refused in the unit (`reservedRoleRefusal`).
4697
+ * For a cut-over tenant (K-68 step 3e) the same unit runs in its object, whose tuples, fences and
4698
+ * roles are the ones written first; whether the org exists is asked here, where orgs are kept.
4207
4699
  */
4208
4700
  applyMembership(change, row, orgRow, reserved = []) {
4209
- const { tenantId, principal, roleKey, boundedBy, orgId } = change;
4210
- return this.ctx.storage.transactionSync(() => {
4211
- if (change.op === 'add') {
4212
- const fence = this.sql.exec(MEMBERSHIP_FENCE_SINCE_SQL, tenantId, principal, change.unlessRemovedSince).toArray()[0];
4213
- if (fence)
4214
- return { applied: false, removedAt: fence.removed_at };
4215
- }
4216
- const role = this.getRole(tenantId, roleKey);
4217
- if (!role)
4218
- return { applied: false, unknownRole: roleKey };
4219
- const refused = change.op === 'add' ? reservedRoleRefusal(role, new Set(reserved), 'person') : null;
4220
- if (refused)
4221
- return { applied: false, reserved: refused };
4222
- const bound = tenantCoverage(this.directoryReader, tenantId, boundedBy, role.permissions);
4223
- if (!bound.covered)
4224
- return { applied: false, missing: bound.missing };
4225
- // #2047: the org, bounded by `boundedBy`'s own live membership of it.
4226
- const org = orgId ? { orgId, row: orgRow, ...orgChangeBound(this.directoryReader, tenantId, { ...change, orgId }) } : undefined;
4227
- if (org) {
4228
- if (!org.row)
4229
- throw new Error('applyMembership: an org change needs its audit row');
4230
- if (!this.readOrg(tenantId, org.orgId))
4231
- return { applied: false, unknownOrg: org.orgId };
4232
- if (!org.bounded)
4233
- return { applied: false, notMember: org.orgId };
4234
- }
4235
- if (change.op === 'remove') {
4236
- const roleTaken = this.revokeAndFenceIn(tenantId, principal, `role:${roleKey}`, `tenant:${tenantId}`, row);
4237
- const orgLeft = !!org && this.revokeAndFenceIn(tenantId, principal, 'member', `org:${org.orgId}`, { ...org.row, before: { principal, orgId: org.orgId } });
4238
- return { applied: true, changed: roleTaken || orgLeft };
4239
- }
4240
- const at = new Date().toISOString();
4241
- this.writeTenantTuple(tenantId, `principal:${principal}`, `role:${roleKey}`, `tenant:${tenantId}`, null);
4242
- this.recordAdmin({ ...row, at });
4243
- if (org?.bounded) {
4244
- this.writeTenantTuple(tenantId, `principal:${principal}`, 'member', `org:${org.orgId}`, org.expiresAt);
4245
- this.recordAdmin({ ...org.row, after: memberAddedAudit(principal, org.orgId, org.expiresAt), at });
4246
- }
4247
- return { applied: true };
4248
- });
4701
+ if (this.tuplesCutOver(change.tenantId)) {
4702
+ return this.directoryCutover.tupleWrite(change.tenantId, {
4703
+ kind: 'membership',
4704
+ change,
4705
+ row: row,
4706
+ orgRow: orgRow ?? null,
4707
+ reserved: [...reserved],
4708
+ // Orgs moved with the tuples: the object reads its own. Otherwise the directory answers here.
4709
+ orgKnown: this.orgsCutOver(change.tenantId) ? null : !!change.orgId && !!readOrgRow(this.sql, change.tenantId, change.orgId),
4710
+ });
4711
+ }
4712
+ return this.ctx.storage.transactionSync(() => applyMembershipIn(this.tupleStore(), change, row, orgRow, reserved));
4249
4713
  }
4250
4714
  /**
4251
4715
  * A tenant-level removal as ONE DO unit (#1184) — `unassignRole` at the tenant node, and
@@ -4253,70 +4717,51 @@ export class ControlPlaneDO extends DurableObject {
4253
4717
  * K-21 writes only when something changed. The fence is raised either way: a removal of
4254
4718
  * someone whose add is still on its way takes nothing, and must still win. One method, so
4255
4719
  * no add can run between the revoke and the fence. Returns whether anything changed.
4256
- */
4257
- revokeAndFence(tenantId, principal, relation, object, row) {
4258
- return this.ctx.storage.transactionSync(() => this.revokeAndFenceIn(tenantId, principal, relation, object, row));
4259
- }
4260
- /**
4261
- * `revokeAndFence`'s writes, for inside a transaction a caller already holds.
4262
4720
  *
4263
- * The time is minted HERE, in the unit, never taken from `row.at`: the coordinator mints its
4264
- * row before an awaited RPC, and a queue delay in between would age the fence by however
4265
- * long the call waited, which an add's cutoff would read as a removal from before its window
4266
- * (Codex round 3). The fence is compared with an add's `occurredAt`, stamped by the ScopeDO's
4267
- * clock. Both are this platform's own NTP-disciplined time, sub-second apart, which is far
4268
- * inside `MEMBERSHIP_REMOVAL_SKEW_MS`.
4721
+ * The time is minted in the unit, never taken from `row.at`: the coordinator mints its row
4722
+ * before an awaited RPC, and a queue delay in between would age the fence by however long the
4723
+ * call waited, which an add's cutoff would read as a removal from before its window (Codex
4724
+ * round 3). The fence is compared with an add's `occurredAt`, stamped by the ScopeDO's clock.
4725
+ * Both are this platform's own NTP-disciplined time, sub-second apart, which is far inside
4726
+ * `MEMBERSHIP_REMOVAL_SKEW_MS`.
4269
4727
  */
4270
- revokeAndFenceIn(tenantId, principal, relation, object, row) {
4271
- const at = new Date().toISOString();
4272
- const changed = this.revokeTenantTuple(tenantId, `principal:${principal}`, relation, object, at);
4273
- this.sql.exec(RAISE_MEMBERSHIP_FENCE_SQL, tenantId, principal, at);
4274
- if (changed)
4275
- this.recordAdmin({ ...row, at });
4276
- return changed;
4728
+ revokeAndFence(tenantId, principal, relation, object, row) {
4729
+ if (this.tuplesCutOver(tenantId)) {
4730
+ return this.directoryCutover.tupleWrite(tenantId, {
4731
+ kind: 'revokeAndFence', principal, relation, object, row: row,
4732
+ }).then((r) => r.changed);
4733
+ }
4734
+ return this.ctx.storage.transactionSync(() => revokeAndFenceIn(this.tupleStore(), tenantId, principal, relation, object, row));
4277
4735
  }
4278
4736
  /** Tombstone any tenant tuple by its exact (subject, relation, object). Returns
4279
- * whether a live row changed, so a repeat revoke is a silent no-op. */
4737
+ * whether a live row changed, so a repeat revoke is a silent no-op. A cut-over tenant's is
4738
+ * refused here (K-68 step 3e: its tuples are written in its object first). */
4280
4739
  revokeTenantTuple(tenantId, subject, relation, object, at) {
4281
- const before = this.sql
4282
- .exec(`SELECT 1 FROM _substrat_tenant_tuples
4283
- WHERE tenant_id = ? AND subject = ? AND relation = ? AND object = ?
4284
- AND revoked_at IS NULL`, tenantId, subject, relation, object)
4285
- .toArray();
4286
- if (before.length === 0)
4287
- return false;
4288
- this.sql.exec(`UPDATE _substrat_tenant_tuples SET revoked_at = ?
4289
- WHERE tenant_id = ? AND subject = ? AND relation = ? AND object = ?
4290
- AND revoked_at IS NULL`, at, tenantId, subject, relation, object);
4291
- return true;
4740
+ return revokeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, at);
4292
4741
  }
4293
4742
  /** Members of an org. Live only unless `includeRevoked` — revoked rows are evidence. */
4294
4743
  listMembers(tenantId, object, includeRevoked) {
4295
- return this.sql
4296
- .exec(`SELECT subject, revoked_at, expires_at FROM _substrat_tenant_tuples
4297
- WHERE tenant_id = ? AND relation = 'member' AND object = ?
4298
- ${includeRevoked ? '' : 'AND revoked_at IS NULL'}
4299
- ORDER BY subject`, tenantId, object)
4300
- .toArray();
4744
+ if (this.tuplesCutOver(tenantId))
4745
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'members', object, includeRevoked });
4746
+ return listMemberRows(this.sql, tenantId, object, includeRevoked);
4301
4747
  }
4302
4748
  tenantTuples(tenantId, subject, relationPrefix) {
4303
- return this.sql
4304
- .exec(`SELECT subject, relation, object, expires_at, revoked_at FROM _substrat_tenant_tuples
4305
- WHERE tenant_id = ? AND subject = ? AND relation LIKE ?`, tenantId, subject, `${relationPrefix}%`)
4306
- .toArray();
4749
+ if (this.tuplesCutOver(tenantId))
4750
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'tuples', subject, relationPrefix });
4751
+ return tenantTupleRows(this.sql, tenantId, subject, relationPrefix);
4307
4752
  }
4308
4753
  /**
4309
4754
  * ALL of a tenant's tenant-level tuples — the read behind scope-local projection
4310
4755
  * (docs/architecture/scope-local-permissions.md). Includes tombstoned rows so the
4311
4756
  * projection mirrors the directory exactly and the checker's own `live()` filter
4312
4757
  * drops them identically. Not on the request hot path — this runs on the admin
4313
- * write path, projecting into a tenant's scopes.
4758
+ * write path, projecting into a tenant's scopes. A cut-over tenant's are its object's, so a
4759
+ * revocation it made first is projected even while its fallback is still owed here.
4314
4760
  */
4315
4761
  dumpTenantTuples(tenantId) {
4316
- return this.sql
4317
- .exec(`SELECT subject, relation, object, expires_at, revoked_at FROM _substrat_tenant_tuples
4318
- WHERE tenant_id = ?`, tenantId)
4319
- .toArray();
4762
+ if (this.tuplesCutOver(tenantId))
4763
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'dump' });
4764
+ return dumpTenantTupleRows(this.sql, tenantId);
4320
4765
  }
4321
4766
  // -- entitlements (control-plane.md §4.3) -----------------------------------
4322
4767
  // #33: the flag carries plan fields. The PATCH merge (omitted preserves, null
@@ -4814,6 +5259,8 @@ export class ControlPlaneDO extends DurableObject {
4814
5259
  * reconcile re-seats it from when that delivery fails. Answers the connection's vertical.
4815
5260
  */
4816
5261
  grantConnectionInDirectory(row, audit) {
5262
+ if (!row.scopeId && this.tuplesCutOver(row.tenantId))
5263
+ return this.grantConnectionFirst(row, audit);
4817
5264
  return this.ctx.storage.transactionSync(() => {
4818
5265
  const conn = this.readConnection(row.connectionId);
4819
5266
  if (!conn)
@@ -4834,13 +5281,55 @@ export class ControlPlaneDO extends DurableObject {
4834
5281
  }
4835
5282
  this.recordConnectionGrant({ ...row, vertical: conn.vertical });
4836
5283
  if (!row.scopeId) {
4837
- this.writeTenantTuple(row.tenantId, `connection:${row.connectionId}`, `granted:${row.permission}`, `tenant:${row.tenantId}`, row.expiresAt);
5284
+ writeTenantTupleIn(this.tupleStore(), row.tenantId, `connection:${row.connectionId}`, `granted:${row.permission}`, `tenant:${row.tenantId}`, row.expiresAt);
4838
5285
  }
4839
5286
  const after = (audit.after ?? {});
4840
5287
  this.recordAdmin({ ...audit, vertical: conn.vertical, after: { ...after, provider: conn.provider } });
4841
5288
  return { vertical: conn.vertical };
4842
5289
  });
4843
5290
  }
5291
+ /**
5292
+ * K-68 step 3e: a tenant-level connection grant of a cut-over tenant, as one exclusive step
5293
+ * (`exclusive`): the connection judged here as it stands, the tuple written first in the tenant's
5294
+ * object, and the record (`_substrat_connection_grants`, still this directory's) carried with it to
5295
+ * the fallback, which writes the record, the tuple and the admin row in one transaction. A revoke of
5296
+ * the connection can then land only after the grant, as it could in the synchronous unit; if the
5297
+ * fallback is applied later, `applyCarried` tombstones the record as that revoke's cascade would have.
5298
+ */
5299
+ grantConnectionFirst(row, audit) {
5300
+ return this.exclusive(async () => {
5301
+ const conn = this.readConnection(row.connectionId);
5302
+ if (!conn)
5303
+ throw new Error(`connection not found: ${row.connectionId}`);
5304
+ if (conn.revoked_at)
5305
+ throw new Error(`connection ${row.connectionId} is revoked — grant nothing to it`);
5306
+ if (conn.tenant_id !== row.tenantId) {
5307
+ throw new Error(`connection ${row.connectionId} belongs to tenant ${conn.tenant_id} and cannot be granted anything in ${row.tenantId}`);
5308
+ }
5309
+ const after = (audit.after ?? {});
5310
+ await this.directoryCutover.tupleWrite(row.tenantId, {
5311
+ kind: 'write', subject: `connection:${row.connectionId}`, relation: `granted:${row.permission}`, object: `tenant:${row.tenantId}`,
5312
+ expiresAt: row.expiresAt,
5313
+ audit: { ...audit, vertical: conn.vertical, after: { ...after, provider: conn.provider } },
5314
+ }, [{ kind: 'connectionGrant', row: { ...row, scopeId: null, vertical: conn.vertical } }]);
5315
+ return { vertical: conn.vertical };
5316
+ });
5317
+ }
5318
+ /**
5319
+ * K-68 step 3e: a write the directory still owns that rode a first write (`CarriedWrite`), in the
5320
+ * fallback's transaction. A connection revoked since the grant was judged tombstones the record at
5321
+ * its revoke time (#592's cascade): the grant came first, and the revoke took it.
5322
+ */
5323
+ applyCarried(write) {
5324
+ if (write.kind !== 'connectionGrant')
5325
+ throw new Error(`directory cutover: no carried write ${write.kind}`);
5326
+ this.recordConnectionGrant(write.row);
5327
+ const conn = this.readConnection(write.row.connectionId);
5328
+ if (conn?.revoked_at) {
5329
+ this.sql.exec(`UPDATE _substrat_connection_grants SET revoked_at = ?
5330
+ WHERE connection_id = ? AND permission = ? AND scope_id IS NULL AND revoked_at IS NULL`, conn.revoked_at, write.row.connectionId, write.row.permission);
5331
+ }
5332
+ }
4844
5333
  /**
4845
5334
  * #2732: `revokeFromConnection`'s directory half as one unit, after the scope's tuple was
4846
5335
  * delivered gone. The scope-level record is tombstoned (K-21), so the additive reconcile never
@@ -4908,6 +5397,9 @@ export class ControlPlaneDO extends DurableObject {
4908
5397
  * there is a tenant tuple is still switchable. Read here, where the tenant tuples live.
4909
5398
  */
4910
5399
  tenantHeldOf(kind, tenantId, keys, now) {
5400
+ // K-68 step 3e: a cut-over tenant's grants are its object's.
5401
+ if (this.tuplesCutOver(tenantId))
5402
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'held', switchKind: kind, keys: [...keys], now });
4911
5403
  return tenantHeldOf(this.kernelSql, kind, tenantId, keys, now);
4912
5404
  }
4913
5405
  /** The fleet read. */