@substrat-run/adapter-cloudflare 0.221.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 (82) 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 +244 -67
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +664 -246
  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 +7 -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 +12 -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 +26 -1
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/host.js +262 -45
  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/scope-do.d.ts +11 -2
  67. package/dist/scope-do.d.ts.map +1 -1
  68. package/dist/scope-do.js +154 -40
  69. package/dist/scope-do.js.map +1 -1
  70. package/dist/scope-sweeper-do.d.ts +22 -0
  71. package/dist/scope-sweeper-do.d.ts.map +1 -1
  72. package/dist/scope-sweeper-do.js +74 -54
  73. package/dist/scope-sweeper-do.js.map +1 -1
  74. package/dist/scope-wake.d.ts +12 -1
  75. package/dist/scope-wake.d.ts.map +1 -1
  76. package/dist/scope-wake.js +14 -1
  77. package/dist/scope-wake.js.map +1 -1
  78. package/dist/tenant-due-work-do.d.ts +95 -0
  79. package/dist/tenant-due-work-do.d.ts.map +1 -0
  80. package/dist/tenant-due-work-do.js +149 -0
  81. package/dist/tenant-due-work-do.js.map +1 -0
  82. 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, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentsOf, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, 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
@@ -551,6 +560,8 @@ const DIRECTORY_DDL = `
551
560
  ${MEMBERSHIP_FENCES_DDL}
552
561
  ${PEER_SWITCHES_DDL}
553
562
  ${SWITCH_OWED_DDL}
563
+ -- K-63 (#3624): erasures owed to a master's dependents, kept until each door answers.
564
+ ${DEPENDENT_ERASURES_DDL}
554
565
  CREATE TABLE IF NOT EXISTS _substrat_admin_log (
555
566
  id TEXT PRIMARY KEY,
556
567
  actor TEXT NOT NULL,
@@ -922,6 +933,10 @@ export const REPLIED_METHODS = [
922
933
  // #2565: refuses a listed vertical's prod with forbidden (`unlistedOnly`) or conflict (an
923
934
  // auto-admitted version). A DO from before lists it not, so the current coordinator fails closed.
924
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',
925
940
  // #2526: the role, grant and org writes at a tenant node, each with its admin row in its unit. A
926
941
  // DO from before lists none of them, so the current coordinator fails closed against it. That is
927
942
  // why the org write is `insertOrg` and not `createOrg` with a trailing row: an older DO lists
@@ -979,6 +994,8 @@ export const REPLIED_METHODS = [
979
994
  // #3530 step 4: an environment's own serving script recorded, with its admin row.
980
995
  'setEnvironmentServingAndAudit',
981
996
  'claimEnvironmentServe',
997
+ // #3530 step 6: an environment given connections of its own, with its admin row.
998
+ 'setEnvironmentEffectsAndAudit',
982
999
  ];
983
1000
  /**
984
1001
  * #1713: the directory's epoch describes THIS store's history, not its data, so it never leaves in
@@ -1071,6 +1088,39 @@ export class ControlPlaneDO extends DurableObject {
1071
1088
  kernelSql;
1072
1089
  /** Settles once the constructor's #1764 backfill check has run (awaited by the tests). */
1073
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
+ }
1074
1124
  constructor(ctx, env) {
1075
1125
  super(ctx, env);
1076
1126
  this.sql = ctx.storage.sql;
@@ -1089,10 +1139,24 @@ export class ControlPlaneDO extends DurableObject {
1089
1139
  });
1090
1140
  this.directoryBackfill = directoryBackfillFor(env, this.directoryMirror, this.directoryBackfillLimits());
1091
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
+ });
1092
1156
  this.backfillArmed = ctx.blockConcurrencyWhile(async () => {
1093
1157
  await this.armVersionMigrationsBackfill();
1094
1158
  // K-68 step 3c: the backfill's passes ride the alarm (directory-mirror-backfill.ts).
1095
- if (this.directoryMirror?.backfillWanted()) {
1159
+ if (this.directoryMirror?.backfillWanted() || this.directoryCutover?.wanted()) {
1096
1160
  const current = await ctx.storage.getAlarm();
1097
1161
  const at = Date.now() + 1_000;
1098
1162
  if (current === null || current > at)
@@ -1148,6 +1212,43 @@ export class ControlPlaneDO extends DurableObject {
1148
1212
  return { enabled: false };
1149
1213
  return { ...this.directoryVerify.status(), owners: this.directoryVerify.owners(query) };
1150
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
+ }
1151
1252
  // -- the routing read model (#3395) -------------------------------------------
1152
1253
  /** Set where a `ROUTES` KV namespace is bound; null otherwise, and the read model is off. */
1153
1254
  routePublisher = null;
@@ -1383,6 +1484,8 @@ export class ControlPlaneDO extends DurableObject {
1383
1484
  await this.retryRouteReadModel().catch((err) => console.error('route read model: retry failed', err));
1384
1485
  // K-68 step 3b: the dual-write's retry after a send an object refused.
1385
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));
1386
1489
  let more;
1387
1490
  try {
1388
1491
  more = this.ctx.storage.transactionSync(() => splitVersionMigrationsBatch(this.kernelSql)).more;
@@ -1765,6 +1868,8 @@ export class ControlPlaneDO extends DurableObject {
1765
1868
  this.addColumn('app_environments', 'serving_migration_tag TEXT');
1766
1869
  this.addColumn('app_environments', 'serve_claim TEXT');
1767
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');
1768
1873
  for (const stmt of LEGACY_SCOPE_ROWS_BACKFILL)
1769
1874
  this.sql.exec(stmt);
1770
1875
  // #2501: an ownership period for every vertical registered before the history existed.
@@ -2082,6 +2187,10 @@ export class ControlPlaneDO extends DurableObject {
2082
2187
  if (opts.requireEmpty && this.sql.exec('SELECT 1 FROM tenants LIMIT 1').toArray().length > 0) {
2083
2188
  throw substratError('conflict', RESTORE_OVERWRITE_REFUSAL);
2084
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
+ }
2085
2194
  // #1713: the epoch this directory was in, read before the drops take it.
2086
2195
  const epochBefore = this.lifecycleEpoch();
2087
2196
  this.sql.exec('PRAGMA defer_foreign_keys = ON');
@@ -2137,6 +2246,8 @@ export class ControlPlaneDO extends DurableObject {
2137
2246
  // for 3c's backfill to fill again, not sent row by row.
2138
2247
  this.directoryMirror?.install();
2139
2248
  this.directoryMirror?.markRestored();
2249
+ // K-68 step 3e: the cut-over's triggers went with the cut-over tables.
2250
+ this.directoryCutover?.install();
2140
2251
  });
2141
2252
  // A restore is a new #1764 backfill episode. It replaced the data the old failure count and
2142
2253
  // backoff were about, so neither may delay or silence it: the count is cleared and the next
@@ -2402,13 +2513,19 @@ export class ControlPlaneDO extends DurableObject {
2402
2513
  // Stamp/clear deleting_at so the grace-window sweep can age tenants (§4.8):
2403
2514
  // entering `deleting` stamps, leaving it (an un-delete) clears — the same shape
2404
2515
  // transitionScope uses for archived_at.
2516
+ const now = Date.now();
2405
2517
  this.writeAndAudit(() => {
2406
2518
  const moved = (status === 'deleting'
2407
- ? 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)
2408
2520
  : this.sql.exec('UPDATE tenants SET status = ?, deleting_at = NULL WHERE tenant_id = ?', status, tenantId)).rowsWritten > 0;
2409
2521
  this.bumpLifecycleRevision(`tenant:${tenantId}`); // #1713, with the change it counts
2410
2522
  return moved;
2411
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
+ }
2412
2529
  return before.status;
2413
2530
  }
2414
2531
  /**
@@ -2419,13 +2536,16 @@ export class ControlPlaneDO extends DurableObject {
2419
2536
  * previous status (for the audit before/after). Idempotent: set-to-empty DELETEs
2420
2537
  * plus the status flip converge on a re-run after a partial failure.
2421
2538
  */
2422
- reapTenant(tenantId, audit) {
2539
+ reapTenant(tenantId, audit, deletingBy) {
2423
2540
  const before = this.readTenant(tenantId);
2424
2541
  if (!before)
2425
2542
  throw substratError('not_found', `unknown tenant: ${tenantId}`);
2426
2543
  if (before.status !== 'deleting') {
2427
2544
  throw substratError('conflict', `tenant ${tenantId} is ${before.status}, not deleting — only a deleting tenant may be reaped`);
2428
2545
  }
2546
+ if (deletingBy !== undefined && (before.deletingAt === null || before.deletingAt > deletingBy)) {
2547
+ throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
2548
+ }
2429
2549
  // KEPT as the tombstone: the `tenants` row itself and `_substrat_admin_log` (the
2430
2550
  // compliance witness — never swept). Scope rows were already reaped individually.
2431
2551
  // One unit with the flip and `audit`, whose `before` is the status read here.
@@ -2714,8 +2834,10 @@ export class ControlPlaneDO extends DurableObject {
2714
2834
  // Idempotency is on the scope_id (§3.3: idempotent and journaled — safe to
2715
2835
  // re-run), so an existing scope short-circuits before the slug check:
2716
2836
  // re-provisioning must not collide with itself.
2717
- const existing = this.sql.exec('SELECT scope_type FROM scopes WHERE scope_id = ?', scopeId).toArray()[0];
2837
+ const existing = this.sql.exec('SELECT scope_type, parent_scope_id FROM scopes WHERE scope_id = ?', scopeId).toArray()[0];
2718
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);
2719
2841
  // #2993: a scope's type is fixed when it is provisioned. The host judged it against the row it
2720
2842
  // read; judged again here, in the write's own unit, so a provision racing another with a
2721
2843
  // different type cannot both succeed. Absent: a host with no declared types, as before.
@@ -2723,6 +2845,22 @@ export class ControlPlaneDO extends DurableObject {
2723
2845
  throw substratError('conflict', `scope ${scopeId} is a '${existing.scope_type ?? 'home'}' scope, and a scope's type is fixed when it is ` +
2724
2846
  `provisioned: it cannot become '${record.scopeType ?? 'home'}'`);
2725
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
+ }
2726
2864
  if (!existed) {
2727
2865
  // An `archived` scope (a deleted app) has released its name — and `reaped` is past
2728
2866
  // archived, so it too has released it — both excluded so the slug can be reclaimed.
@@ -2733,6 +2871,19 @@ export class ControlPlaneDO extends DurableObject {
2733
2871
  throw substratError('conflict', `scope slug '${record.slug}' already taken under tenant ${tenantId} ` +
2734
2872
  `by ${slugOwner.scope_id} (slugs are unique within a tenant)`);
2735
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
+ }
2736
2887
  // A scope born while its vertical serves in place (#286) is born ON the serving
2737
2888
  // script — provisioning dispatches there — so its routing points there from row
2738
2889
  // one. Sub-selected at insert: per-scope truth that later serves can't disturb.
@@ -2750,10 +2901,11 @@ export class ControlPlaneDO extends DurableObject {
2750
2901
  (scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
2751
2902
  storage_shape, jurisdiction, status, forked_from, forked_at, expires_at,
2752
2903
  serving_ref, created_at)
2753
- VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2754
- (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId,
2904
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2905
+ (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`, scopeId, tenantId, parentScopeId,
2755
2906
  // #2993: NULL for 'home', so a host with no declared types writes exactly the row it always did.
2756
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);
2757
2909
  }
2758
2910
  return !existed;
2759
2911
  }
@@ -2801,6 +2953,10 @@ export class ControlPlaneDO extends DurableObject {
2801
2953
  where.push('vertical = ?');
2802
2954
  params.push(filter.vertical);
2803
2955
  }
2956
+ if (filter.parentScopeId) {
2957
+ where.push('parent_scope_id = ?');
2958
+ params.push(filter.parentScopeId);
2959
+ }
2804
2960
  const tail = keysetTail(where, params, 'scope_id', filter);
2805
2961
  const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
2806
2962
  return this.sql.exec(sql, ...params).toArray();
@@ -2810,9 +2966,12 @@ export class ControlPlaneDO extends DurableObject {
2810
2966
  * and every status but `reaped`, each once. What a promote judges the incoming version's declared
2811
2967
  * types against. A vertical none of whose scopes is typed answers `[]`.
2812
2968
  */
2813
- scopeTypesHeldBy(vertical) {
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 = ?';
2814
2973
  return this.sql
2815
- .exec("SELECT DISTINCT scope_type FROM scopes WHERE vertical = ? AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type", vertical)
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]))
2816
2975
  .toArray()
2817
2976
  .map((r) => String(r.scope_type));
2818
2977
  }
@@ -2928,8 +3087,59 @@ export class ControlPlaneDO extends DurableObject {
2928
3087
  * for it, since the row can be deleted (`deleteScopeDirectory`) between the two.
2929
3088
  */
2930
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) {
2931
3141
  const row = this.sql
2932
- .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)
2933
3143
  .toArray()[0];
2934
3144
  if (!row || row.tenant_id !== tenantId) {
2935
3145
  return { ok: false, code: 'not_found', message: `unknown scope for tenant: (${tenantId}, ${scopeId})` };
@@ -2937,6 +3147,32 @@ export class ControlPlaneDO extends DurableObject {
2937
3147
  if (to === 'active' && row.stores_fenced_at !== null) {
2938
3148
  return { ok: false, code: 'conflict', message: storesFencedRefusal(scopeId) };
2939
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
+ }
2940
3176
  if (!from.includes(row.status)) {
2941
3177
  return {
2942
3178
  ok: false,
@@ -2945,35 +3181,34 @@ export class ControlPlaneDO extends DurableObject {
2945
3181
  `(allowed from: ${from.join('|')})`,
2946
3182
  };
2947
3183
  }
2948
- // One transaction: the status and — on a reap — the scope's switch records (#1674).
2949
- // Reaped is terminal, so a cleanup that failed after the flip could never be retried.
2950
- this.ctx.storage.transactionSync(() => {
2951
- // Stamp/clear archived_at so the reap sweep can age scopes. Entering `archived`
2952
- // records when; `unarchive` (→ active, a restore per §4.2) clears it so a later
2953
- // re-archive dates from the new event. `reaped` keeps it — it is terminal history.
2954
- // #1524: the status it left is recorded beside the stamp and cleared with it.
2955
- if (to === 'archived') {
2956
- this.sql.exec('UPDATE scopes SET status = ?, archived_at = ?, archived_from_status = ? WHERE scope_id = ?', to, new Date().toISOString(), row.status, scopeId);
2957
- }
2958
- else if (to === 'active') {
2959
- this.sql.exec('UPDATE scopes SET status = ?, archived_at = NULL, archived_from_status = NULL WHERE scope_id = ?', to, scopeId);
2960
- }
2961
- else {
2962
- this.sql.exec('UPDATE scopes SET status = ? WHERE scope_id = ?', to, scopeId);
2963
- }
2964
- if (to === 'archived' || to === 'reaped') {
2965
- this.sql.exec('UPDATE peer_bindings SET invalidated = 1 WHERE tenant_id = ? AND target_scope_id = ?', tenantId, scopeId);
2966
- }
2967
- if (to === 'reaped') {
2968
- forgetSwitchesOf(this.kernelSql, scopeId);
2969
- this.forgetLifecycleDeliveries('scope_id = ?', scopeId);
2970
- // #2515: its storage is gone, and its measured days are kept for the invoice (retention ends them).
2971
- retireScopeStorage(doRedactionSql(this.sql), scopeId);
2972
- }
2973
- this.bumpLifecycleRevision(`scope:${scopeId}`); // #1713, with the status it counts
2974
- });
2975
3184
  return { ok: true, status: row.status, vertical: row.vertical };
2976
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
+ }
2977
3212
  // -- roles (checker rule 1) -------------------------------------------------
2978
3213
  /**
2979
3214
  * Kept for a coordinator from before #2447, which calls it and reads the previous role (for the
@@ -2982,10 +3217,13 @@ export class ControlPlaneDO extends DurableObject {
2982
3217
  * that never happened.
2983
3218
  */
2984
3219
  defineRole(tenantId, role) {
3220
+ const settle = (outcome) => {
3221
+ if ('refused' in outcome)
3222
+ throw new Error(outcome.refused);
3223
+ return outcome.before;
3224
+ };
2985
3225
  const outcome = this.defineRoleOrRefusal(tenantId, role);
2986
- if ('refused' in outcome)
2987
- throw new Error(outcome.refused);
2988
- return outcome.before;
3226
+ return outcome instanceof Promise ? outcome.then(settle) : settle(outcome);
2989
3227
  }
2990
3228
  /**
2991
3229
  * INSERT OR REPLACE; answer the previous role (for the audit `before`) or null. Judged first, in
@@ -3000,87 +3238,86 @@ export class ControlPlaneDO extends DurableObject {
3000
3238
  * coordinator from before #2526 passes none and records its own.
3001
3239
  */
3002
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
+ }
3003
3247
  return this.ctx.storage.transactionSync(() => {
3004
- const outcome = this.defineRoleIn(tenantId, role, reservation, seatedInScopes);
3248
+ const outcome = defineRoleRow(this.sql, tenantId, role, reservation, seatedInScopes, new Date().toISOString());
3005
3249
  if (audit && 'before' in outcome)
3006
3250
  this.recordAdmin({ ...audit, before: outcome.before });
3007
3251
  return outcome;
3008
3252
  });
3009
3253
  }
3010
- defineRoleIn(tenantId, role, reservation, seatedInScopes) {
3011
- const tenantRoles = this.listRoles({ tenantId }).map((r) => ({
3012
- key: r.role_key,
3013
- permissions: JSON.parse(r.permissions),
3014
- holder: r.holder ?? undefined,
3015
- }));
3016
- const stored = tenantRoles.find((r) => r.key === role.key);
3017
- const seated = stored?.holder !== 'system' && role.holder === 'system' &&
3018
- (seatedInScopes ||
3019
- this.sql.exec(TENANT_SEATED_ROLES_SQL, tenantId, new Date().toISOString()).toArray().some((r) => r.role_key === role.key));
3020
- const refused = reservedRoleDefinitionRefusal(role, { reserved: new Set(reservation.reserved), declared: new Set(reservation.declared) }, tenantRoles, seated);
3021
- if (refused)
3022
- return { refused };
3023
- const before = this.getRole(tenantId, role.key) ?? null;
3024
- this.sql.exec(`INSERT OR REPLACE INTO _substrat_roles (tenant_id, role_key, permissions, source, holder)
3025
- VALUES (?, ?, ?, ?, ?)`, tenantId, role.key, JSON.stringify(role.permissions), String(role.source), role.holder ?? 'person');
3026
- return { before };
3027
- }
3028
- /** 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). */
3029
3255
  listRoles(filter) {
3030
- const where = [];
3031
- const params = [];
3032
- if (filter.tenantId) {
3033
- where.push('tenant_id = ?');
3034
- params.push(filter.tenantId);
3035
- }
3036
- if (filter.source) {
3037
- where.push('source = ?');
3038
- params.push(filter.source);
3039
- }
3040
- const order = (filter.order ?? 'asc') === 'desc' ? 'DESC' : 'ASC';
3041
- if (filter.cursor) {
3042
- // Composite sort key `${tenantId}|${roleKey}` (pagination.ts) — the
3043
- // tenant id is a ULID and never contains '|', so split on the FIRST.
3044
- const split = filter.cursor.indexOf('|');
3045
- const afterTenant = split === -1 ? filter.cursor : filter.cursor.slice(0, split);
3046
- const afterKey = split === -1 ? '' : filter.cursor.slice(split + 1);
3047
- const cmp = order === 'DESC' ? '<' : '>';
3048
- where.push(`(tenant_id ${cmp} ? OR (tenant_id = ? AND role_key ${cmp} ?))`);
3049
- params.push(afterTenant, afterTenant, afterKey);
3050
- }
3051
- let sql = 'SELECT tenant_id, role_key, permissions, source, holder FROM _substrat_roles' +
3052
- (where.length ? ` WHERE ${where.join(' AND ')}` : '') +
3053
- ` ORDER BY tenant_id ${order}, role_key ${order}`;
3054
- if (filter.limit !== undefined) {
3055
- sql += ' LIMIT ?';
3056
- params.push(assertRowLimit('limit', filter.limit));
3057
- }
3058
- 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);
3059
3259
  }
3260
+ /** A role as stored; a cut-over tenant's from its object (3e). The decisions in this object read `readRole` directly. */
3060
3261
  getRole(tenantId, key) {
3061
- const row = this.sql
3062
- .exec('SELECT role_key, permissions, source, holder FROM _substrat_roles WHERE tenant_id = ? AND role_key = ?', tenantId, key)
3063
- .toArray()[0];
3064
- if (!row)
3065
- 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() {
3066
3281
  return {
3067
- key: row.role_key,
3068
- permissions: JSON.parse(row.permissions),
3069
- source: row.source,
3070
- 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),
3071
3286
  };
3072
3287
  }
3073
- // -- 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
+ }
3074
3308
  /**
3075
3309
  * A tenant tuple, upserted. With `audit` (#2526, `grant` at the tenant node, called through
3076
3310
  * `reply`), its admin row commits in the same transaction; without, as a coordinator from before
3077
- * #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.
3078
3312
  */
3079
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
+ }
3080
3319
  const write = () => {
3081
- this.sql.exec(`INSERT OR REPLACE INTO _substrat_tenant_tuples
3082
- (tenant_id, subject, relation, object, expires_at)
3083
- VALUES (?, ?, ?, ?, ?)`, tenantId, subject, relation, object, expiresAt);
3320
+ writeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, expiresAt);
3084
3321
  return true;
3085
3322
  };
3086
3323
  if (audit)
@@ -3095,41 +3332,71 @@ export class ControlPlaneDO extends DurableObject {
3095
3332
  * writes nothing. A role not defined here is not judged, as before.
3096
3333
  */
3097
3334
  assignTenantRole(tenantId, principal, roleKey, reserved, audit) {
3098
- return this.ctx.storage.transactionSync(() => {
3099
- const role = reserved.length > 0 ? this.getRole(tenantId, roleKey) : undefined;
3100
- const refused = role ? reservedRoleRefusal(role, new Set(reserved), 'platform') : null;
3101
- if (refused)
3102
- return { refused };
3103
- this.writeTenantTuple(tenantId, `principal:${principal}`, `role:${roleKey}`, `tenant:${tenantId}`, null);
3104
- this.recordAdmin(audit);
3105
- return {};
3106
- });
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));
3107
3341
  }
3108
3342
  /**
3109
3343
  * #2526: a tenant tuple that names an org — `grantToOrg` at the tenant node, and `addMember` —
3110
- * 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.
3111
3347
  */
3112
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
+ }
3113
3366
  this.writeAndAudit(() => {
3114
- if (!this.readOrg(tenantId, orgId))
3115
- throw substratError('not_found', `unknown org ${orgId} in tenant ${tenantId}`);
3116
- 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);
3117
3370
  return true;
3118
3371
  }, audit);
3119
3372
  }
3120
3373
  /**
3121
3374
  * #1743: a tenant-level `system:<module>` grant, refused while the record holds the module
3122
3375
  * off on any scope (`scopesSwitchedOffFor`). Synchronous, so the read and the write are one
3123
- * DO unit. Answers the switched-off scopes; non-empty means nothing was written. With `audit`
3124
- * (#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.
3125
3380
  */
3126
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
+ }
3127
3394
  let off = [];
3128
3395
  this.writeAndAudit(() => {
3129
3396
  off = scopesSwitchedOffFor(this.kernelSql, tenantId, moduleId);
3130
3397
  if (off.length > 0)
3131
3398
  return false;
3132
- this.writeTenantTuple(tenantId, `system:${moduleId}`, relation, `tenant:${tenantId}`, expiresAt);
3399
+ writeTenantTupleIn(this.tupleStore(), tenantId, `system:${moduleId}`, relation, `tenant:${tenantId}`, expiresAt);
3133
3400
  return true;
3134
3401
  }, audit);
3135
3402
  return off;
@@ -3189,6 +3456,10 @@ export class ControlPlaneDO extends DurableObject {
3189
3456
  peerBindings(tenantId, callerScopeId) {
3190
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();
3191
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
+ }
3192
3463
  /** D-83 (#3530 step 3): the app's environments in the tenant, production first (kernel `environmentsOf`). */
3193
3464
  listEnvironments(tenantId, vertical) {
3194
3465
  return environmentsOf(this.kernelSql, tenantId, vertical);
@@ -3220,16 +3491,18 @@ export class ControlPlaneDO extends DurableObject {
3220
3491
  * record the upload diffed from (kernel `setEnvironmentServingIn`), with its admin row in the
3221
3492
  * same transaction. False, with nothing written and no row, when the record moved since.
3222
3493
  */
3223
- setEnvironmentServingAndAudit(input, next, expected, audit, claim) {
3494
+ setEnvironmentServingAndAudit(input, next, expected, audit, claim,
3495
+ /** #3638: what this serve acknowledges in this environment, judged and recorded here. */
3496
+ acknowledge) {
3224
3497
  let out;
3225
3498
  this.writeAndAudit(() => {
3226
- out = setEnvironmentServingIn(this.kernelSql, input, next, expected, claim);
3499
+ out = setEnvironmentServingIn(this.kernelSql, input, next, expected, claim, acknowledge);
3227
3500
  return out.moved;
3228
3501
  }, () => ({
3229
3502
  ...audit,
3230
3503
  scopeId: out.scopeId,
3231
3504
  before: out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
3232
- after: { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId },
3505
+ after: { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId, ...(acknowledge ? { acknowledged: acknowledge } : {}) },
3233
3506
  }));
3234
3507
  return out.moved;
3235
3508
  }
@@ -3253,6 +3526,27 @@ export class ControlPlaneDO extends DurableObject {
3253
3526
  return true;
3254
3527
  });
3255
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
+ }
3256
3550
  /** Directory write and endpoint checks share this DO's serialized unit. */
3257
3551
  setPeerBinding(tenantId, callerScopeId, vertical, targetScopeId) {
3258
3552
  const caller = this.sql.exec('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?', callerScopeId).toArray()[0];
@@ -3730,6 +4024,24 @@ export class ControlPlaneDO extends DurableObject {
3730
4024
  }, audit && (() => ({ ...audit, before })));
3731
4025
  return !raced;
3732
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
+ }
3733
4045
  /** #2351: the digest of the migrations read from a version's bundle, or `undefined` for no such version. */
3734
4046
  readMigrationsExtracted(id) {
3735
4047
  return versionMigrationsExtractedOf(this.kernelSql, id);
@@ -3767,11 +4079,17 @@ export class ControlPlaneDO extends DurableObject {
3767
4079
  /** Move a fork's GC deadline forward, or pin it (`null`) — preview-and-snapshots.md §9. False
3768
4080
  * when a reap has claimed the row (#3314): its deadline no longer decides anything. */
3769
4081
  setScopeExpiresAt(scopeId, expiresAt, audit) {
3770
- 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;
3771
4086
  }
3772
4087
  /** One atomic compare-and-set across the preview row and every entry of its copy move. */
3773
4088
  keepAlivePendingScopeCopy(tenantId, scopeId, moveId, status, expectedExpiresAt, expiresAt, audit) {
3774
- 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;
3775
4093
  }
3776
4094
  async listVersions(verticalSlug, page) {
3777
4095
  const where = ['vertical_slug = ?'];
@@ -3867,7 +4185,8 @@ export class ControlPlaneDO extends DurableObject {
3867
4185
  */
3868
4186
  moveScopeRow(set, setArgs, scopeId, cond, audit) {
3869
4187
  const now = new Date().toISOString();
3870
- return this.writeAndAudit(() => {
4188
+ let confirmedTenant;
4189
+ const written = this.writeAndAudit(() => {
3871
4190
  const moved = this.sql.exec(`UPDATE scopes SET ${set} WHERE scope_id = ?
3872
4191
  ${cond.expectedVersionId === undefined ? '' : 'AND vertical_version_id IS ?'}
3873
4192
  ${cond.expectedErasureEpoch === undefined ? '' : 'AND COALESCE(erasure_epoch, 0) = ? AND reap_claimed_at IS NULL'}
@@ -3879,9 +4198,15 @@ export class ControlPlaneDO extends DurableObject {
3879
4198
  const { tenant_id } = this.sql.exec('SELECT tenant_id FROM scopes WHERE scope_id = ?', scopeId).one();
3880
4199
  this.sql.exec(COPY_MOVE_CONFIRM_SQL, ...copyMoveConfirmParams(cond.confirmMove, tenant_id, scopeId, now));
3881
4200
  this.sql.exec(COPY_BACKFILL_SUPERSEDE_SQL, tenant_id, scopeId);
4201
+ if (cond.confirmMove.source === 'eligible')
4202
+ confirmedTenant = tenant_id;
3882
4203
  }
3883
4204
  return true;
3884
4205
  }, audit);
4206
+ if (confirmedTenant !== undefined) {
4207
+ this.armTenantDueWork(confirmedTenant, [{ kind: 'copies', unit: confirmedTenant, dueAt: Date.parse(now) }]);
4208
+ }
4209
+ return written;
3885
4210
  }
3886
4211
  /**
3887
4212
  * The directory effect and its admin row either both commit or both roll back. A thunk is
@@ -3954,6 +4279,44 @@ export class ControlPlaneDO extends DurableObject {
3954
4279
  setIssueStatusAndAudit(...args) {
3955
4280
  return this.setIssueStatus(...args);
3956
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
+ }
3957
4320
  scopeErasureEpoch(tenantId, scopeId) {
3958
4321
  // NULL on every row from before the column (#1722): the same 0 every CAS compares against.
3959
4322
  const row = this.sql.exec('SELECT COALESCE(erasure_epoch, 0) AS erasure_epoch FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
@@ -3969,12 +4332,15 @@ export class ControlPlaneDO extends DurableObject {
3969
4332
  recordScopeScriptCopy(tenantId, scopeId, scriptRef, moveId, role = null, loadStamp = null, leaseMs = SCOPE_COPY_LEASE_MS) {
3970
4333
  if (!scriptRef || !moveId)
3971
4334
  return 'invalid';
4335
+ const dueAt = Date.now() + leaseMs;
3972
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)
3973
4337
  SELECT tenant_id, scope_id, ?, ?, 'pending', ?, ?, ? FROM scopes
3974
4338
  WHERE tenant_id = ? AND scope_id = ? AND reap_claimed_at IS NULL
3975
- ON CONFLICT (tenant_id, scope_id, script_ref, move_id) DO NOTHING`, scriptRef, moveId, role, loadStamp, new Date(Date.now() + leaseMs).toISOString(), tenantId, scopeId);
3976
- 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 }]);
3977
4342
  return 'recorded';
4343
+ }
3978
4344
  const scope = this.sql.exec('SELECT reap_claimed_at FROM scopes WHERE tenant_id = ? AND scope_id = ?', tenantId, scopeId)
3979
4345
  .toArray()[0];
3980
4346
  if (!scope)
@@ -4008,7 +4374,9 @@ export class ControlPlaneDO extends DurableObject {
4008
4374
  claimExpiredScopeScriptCopies(input) {
4009
4375
  const limit = assertRowLimit('limit', input.limit);
4010
4376
  return this.ctx.storage.transactionSync(() => {
4011
- 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();
4012
4380
  const claimed = [];
4013
4381
  for (const r of due) {
4014
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)
@@ -4020,8 +4388,8 @@ export class ControlPlaneDO extends DurableObject {
4020
4388
  });
4021
4389
  }
4022
4390
  /** `HostAdmin.markScopeStoresFenced`: read and written in one synchronous step, so an unarchive is before or after. */
4023
- markScopeStoresFenced(tenantId, scopeId, whileTenantDeleting, audit) {
4024
- 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)
4025
4393
  .toArray()[0];
4026
4394
  if (!scope)
4027
4395
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
@@ -4030,8 +4398,17 @@ export class ControlPlaneDO extends DurableObject {
4030
4398
  if (scope.status !== 'archived') {
4031
4399
  throw substratError('conflict', `scope ${scopeId} is ${scope.status}, not archived, so its stores are not fenced`);
4032
4400
  }
4033
- if (whileTenantDeleting && this.readTenant(tenantId)?.status !== 'deleting') {
4034
- 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
+ }
4035
4412
  }
4036
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 } });
4037
4414
  }
@@ -4061,7 +4438,7 @@ export class ControlPlaneDO extends DurableObject {
4061
4438
  return 'pending';
4062
4439
  }
4063
4440
  settleScopeScriptCopy(tenantId, scopeId, scriptRef, moveId, state, loadStamp, revision, claimedBy) {
4064
- return this.ctx.storage.transactionSync(() => {
4441
+ const written = this.ctx.storage.transactionSync(() => {
4065
4442
  const settled = this.sql.exec(`UPDATE scope_script_copies SET state = ?, load_stamp = ?, revision = ?,
4066
4443
  last_attempt_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
4067
4444
  WHERE tenant_id = ? AND scope_id = ? AND script_ref = ? AND move_id = ?
@@ -4071,11 +4448,27 @@ export class ControlPlaneDO extends DurableObject {
4071
4448
  this.sql.exec(COPY_BACKFILL_SUPERSEDE_SQL, tenantId, scopeId);
4072
4449
  return settled;
4073
4450
  });
4451
+ if (written && state === 'eligible') {
4452
+ this.armTenantDueWork(tenantId, [{ kind: 'copies', unit: tenantId, dueAt: Date.now() }]);
4453
+ }
4454
+ return written;
4074
4455
  }
4075
4456
  touchScopeScriptCopy(tenantId, scopeId, scriptRef, moveId) {
4076
4457
  this.sql.exec(`UPDATE scope_script_copies SET last_attempt_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
4077
4458
  WHERE tenant_id = ? AND scope_id = ? AND script_ref = ? AND move_id = ? AND state = 'eligible'`, tenantId, scopeId, scriptRef, moveId);
4078
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
+ }
4079
4472
  listScopeScriptCopies(filter) {
4080
4473
  const where = [];
4081
4474
  const args = [];
@@ -4201,6 +4594,28 @@ export class ControlPlaneDO extends DurableObject {
4201
4594
  return true;
4202
4595
  }, audit);
4203
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
+ }
4204
4619
  listChannels(verticalSlug, page) {
4205
4620
  const where = ['vertical_slug = ?'];
4206
4621
  const params = [verticalSlug];
@@ -4228,23 +4643,19 @@ export class ControlPlaneDO extends DurableObject {
4228
4643
  .toArray();
4229
4644
  }
4230
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).
4231
4648
  readOrg(tenantId, orgId) {
4232
- return this.sql
4233
- .exec('SELECT * FROM orgs WHERE tenant_id = ? AND org_id = ?', tenantId, orgId)
4234
- .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);
4235
4653
  }
4236
4654
  /** Returns false when the org already exists (idempotent); throws on slug collision. */
4237
4655
  createOrg(orgId, tenantId, slug, name, createdAt) {
4238
- if (this.readOrg(tenantId, orgId))
4239
- return false;
4240
- const slugOwner = this.sql
4241
- .exec('SELECT org_id FROM orgs WHERE tenant_id = ? AND slug = ?', tenantId, slug)
4242
- .toArray()[0];
4243
- if (slugOwner) {
4244
- throw substratError('conflict', `org slug '${slug}' already taken by ${slugOwner.org_id} (slugs are unique per tenant)`);
4245
- }
4246
- this.sql.exec('INSERT INTO orgs (org_id, tenant_id, slug, name, created_at) VALUES (?, ?, ?, ?, ?)', orgId, tenantId, slug, name, createdAt);
4247
- 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);
4248
4659
  }
4249
4660
  /**
4250
4661
  * #2526: `createOrg` with its admin row, in one unit; an org that already exists writes nothing,
@@ -4253,19 +4664,24 @@ export class ControlPlaneDO extends DurableObject {
4253
4664
  * org created with no row, where an unknown method fails closed.
4254
4665
  */
4255
4666
  insertOrg(orgId, tenantId, slug, name, createdAt, audit) {
4256
- 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;
4257
4679
  }
4258
4680
  listOrgs(tenantId) {
4259
- return this.sql
4260
- .exec('SELECT * FROM orgs WHERE tenant_id = ? ORDER BY slug', tenantId)
4261
- .toArray();
4681
+ if (this.orgsCutOver(tenantId))
4682
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'orgs' });
4683
+ return listOrgRows(this.sql, tenantId);
4262
4684
  }
4263
- /** The tenant-level reads, synchronous, for a bound asked inside one of this object's units (#1184). */
4264
- directoryReader = {
4265
- now: () => new Date().toISOString(),
4266
- tenantTuples: (tenantId, subject, prefix) => this.tenantTuples(tenantId, subject, prefix),
4267
- getRole: (tenantId, key) => this.getRole(tenantId, key),
4268
- };
4269
4685
  /**
4270
4686
  * A membership change as ONE DO unit (#1184) — `HostAdmin.applyMembership`. Synchronous, so
4271
4687
  * no other request into this object runs between its reads and its writes: an add's removal
@@ -4278,48 +4694,22 @@ export class ControlPlaneDO extends DurableObject {
4278
4694
  * The org row's `before`/`after` are written here, since only the unit knows the expiry.
4279
4695
  * `reserved` (#2430) is what the coordinator's modules reserve to a system principal: an add of
4280
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.
4281
4699
  */
4282
4700
  applyMembership(change, row, orgRow, reserved = []) {
4283
- const { tenantId, principal, roleKey, boundedBy, orgId } = change;
4284
- return this.ctx.storage.transactionSync(() => {
4285
- if (change.op === 'add') {
4286
- const fence = this.sql.exec(MEMBERSHIP_FENCE_SINCE_SQL, tenantId, principal, change.unlessRemovedSince).toArray()[0];
4287
- if (fence)
4288
- return { applied: false, removedAt: fence.removed_at };
4289
- }
4290
- const role = this.getRole(tenantId, roleKey);
4291
- if (!role)
4292
- return { applied: false, unknownRole: roleKey };
4293
- const refused = change.op === 'add' ? reservedRoleRefusal(role, new Set(reserved), 'person') : null;
4294
- if (refused)
4295
- return { applied: false, reserved: refused };
4296
- const bound = tenantCoverage(this.directoryReader, tenantId, boundedBy, role.permissions);
4297
- if (!bound.covered)
4298
- return { applied: false, missing: bound.missing };
4299
- // #2047: the org, bounded by `boundedBy`'s own live membership of it.
4300
- const org = orgId ? { orgId, row: orgRow, ...orgChangeBound(this.directoryReader, tenantId, { ...change, orgId }) } : undefined;
4301
- if (org) {
4302
- if (!org.row)
4303
- throw new Error('applyMembership: an org change needs its audit row');
4304
- if (!this.readOrg(tenantId, org.orgId))
4305
- return { applied: false, unknownOrg: org.orgId };
4306
- if (!org.bounded)
4307
- return { applied: false, notMember: org.orgId };
4308
- }
4309
- if (change.op === 'remove') {
4310
- const roleTaken = this.revokeAndFenceIn(tenantId, principal, `role:${roleKey}`, `tenant:${tenantId}`, row);
4311
- const orgLeft = !!org && this.revokeAndFenceIn(tenantId, principal, 'member', `org:${org.orgId}`, { ...org.row, before: { principal, orgId: org.orgId } });
4312
- return { applied: true, changed: roleTaken || orgLeft };
4313
- }
4314
- const at = new Date().toISOString();
4315
- this.writeTenantTuple(tenantId, `principal:${principal}`, `role:${roleKey}`, `tenant:${tenantId}`, null);
4316
- this.recordAdmin({ ...row, at });
4317
- if (org?.bounded) {
4318
- this.writeTenantTuple(tenantId, `principal:${principal}`, 'member', `org:${org.orgId}`, org.expiresAt);
4319
- this.recordAdmin({ ...org.row, after: memberAddedAudit(principal, org.orgId, org.expiresAt), at });
4320
- }
4321
- return { applied: true };
4322
- });
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));
4323
4713
  }
4324
4714
  /**
4325
4715
  * A tenant-level removal as ONE DO unit (#1184) — `unassignRole` at the tenant node, and
@@ -4327,70 +4717,51 @@ export class ControlPlaneDO extends DurableObject {
4327
4717
  * K-21 writes only when something changed. The fence is raised either way: a removal of
4328
4718
  * someone whose add is still on its way takes nothing, and must still win. One method, so
4329
4719
  * no add can run between the revoke and the fence. Returns whether anything changed.
4330
- */
4331
- revokeAndFence(tenantId, principal, relation, object, row) {
4332
- return this.ctx.storage.transactionSync(() => this.revokeAndFenceIn(tenantId, principal, relation, object, row));
4333
- }
4334
- /**
4335
- * `revokeAndFence`'s writes, for inside a transaction a caller already holds.
4336
4720
  *
4337
- * The time is minted HERE, in the unit, never taken from `row.at`: the coordinator mints its
4338
- * row before an awaited RPC, and a queue delay in between would age the fence by however
4339
- * long the call waited, which an add's cutoff would read as a removal from before its window
4340
- * (Codex round 3). The fence is compared with an add's `occurredAt`, stamped by the ScopeDO's
4341
- * clock. Both are this platform's own NTP-disciplined time, sub-second apart, which is far
4342
- * 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`.
4343
4727
  */
4344
- revokeAndFenceIn(tenantId, principal, relation, object, row) {
4345
- const at = new Date().toISOString();
4346
- const changed = this.revokeTenantTuple(tenantId, `principal:${principal}`, relation, object, at);
4347
- this.sql.exec(RAISE_MEMBERSHIP_FENCE_SQL, tenantId, principal, at);
4348
- if (changed)
4349
- this.recordAdmin({ ...row, at });
4350
- 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));
4351
4735
  }
4352
4736
  /** Tombstone any tenant tuple by its exact (subject, relation, object). Returns
4353
- * 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). */
4354
4739
  revokeTenantTuple(tenantId, subject, relation, object, at) {
4355
- const before = this.sql
4356
- .exec(`SELECT 1 FROM _substrat_tenant_tuples
4357
- WHERE tenant_id = ? AND subject = ? AND relation = ? AND object = ?
4358
- AND revoked_at IS NULL`, tenantId, subject, relation, object)
4359
- .toArray();
4360
- if (before.length === 0)
4361
- return false;
4362
- this.sql.exec(`UPDATE _substrat_tenant_tuples SET revoked_at = ?
4363
- WHERE tenant_id = ? AND subject = ? AND relation = ? AND object = ?
4364
- AND revoked_at IS NULL`, at, tenantId, subject, relation, object);
4365
- return true;
4740
+ return revokeTenantTupleIn(this.tupleStore(), tenantId, subject, relation, object, at);
4366
4741
  }
4367
4742
  /** Members of an org. Live only unless `includeRevoked` — revoked rows are evidence. */
4368
4743
  listMembers(tenantId, object, includeRevoked) {
4369
- return this.sql
4370
- .exec(`SELECT subject, revoked_at, expires_at FROM _substrat_tenant_tuples
4371
- WHERE tenant_id = ? AND relation = 'member' AND object = ?
4372
- ${includeRevoked ? '' : 'AND revoked_at IS NULL'}
4373
- ORDER BY subject`, tenantId, object)
4374
- .toArray();
4744
+ if (this.tuplesCutOver(tenantId))
4745
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'members', object, includeRevoked });
4746
+ return listMemberRows(this.sql, tenantId, object, includeRevoked);
4375
4747
  }
4376
4748
  tenantTuples(tenantId, subject, relationPrefix) {
4377
- return this.sql
4378
- .exec(`SELECT subject, relation, object, expires_at, revoked_at FROM _substrat_tenant_tuples
4379
- WHERE tenant_id = ? AND subject = ? AND relation LIKE ?`, tenantId, subject, `${relationPrefix}%`)
4380
- .toArray();
4749
+ if (this.tuplesCutOver(tenantId))
4750
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'tuples', subject, relationPrefix });
4751
+ return tenantTupleRows(this.sql, tenantId, subject, relationPrefix);
4381
4752
  }
4382
4753
  /**
4383
4754
  * ALL of a tenant's tenant-level tuples — the read behind scope-local projection
4384
4755
  * (docs/architecture/scope-local-permissions.md). Includes tombstoned rows so the
4385
4756
  * projection mirrors the directory exactly and the checker's own `live()` filter
4386
4757
  * drops them identically. Not on the request hot path — this runs on the admin
4387
- * 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.
4388
4760
  */
4389
4761
  dumpTenantTuples(tenantId) {
4390
- return this.sql
4391
- .exec(`SELECT subject, relation, object, expires_at, revoked_at FROM _substrat_tenant_tuples
4392
- WHERE tenant_id = ?`, tenantId)
4393
- .toArray();
4762
+ if (this.tuplesCutOver(tenantId))
4763
+ return this.directoryCutover.tupleRead(tenantId, { kind: 'dump' });
4764
+ return dumpTenantTupleRows(this.sql, tenantId);
4394
4765
  }
4395
4766
  // -- entitlements (control-plane.md §4.3) -----------------------------------
4396
4767
  // #33: the flag carries plan fields. The PATCH merge (omitted preserves, null
@@ -4888,6 +5259,8 @@ export class ControlPlaneDO extends DurableObject {
4888
5259
  * reconcile re-seats it from when that delivery fails. Answers the connection's vertical.
4889
5260
  */
4890
5261
  grantConnectionInDirectory(row, audit) {
5262
+ if (!row.scopeId && this.tuplesCutOver(row.tenantId))
5263
+ return this.grantConnectionFirst(row, audit);
4891
5264
  return this.ctx.storage.transactionSync(() => {
4892
5265
  const conn = this.readConnection(row.connectionId);
4893
5266
  if (!conn)
@@ -4908,13 +5281,55 @@ export class ControlPlaneDO extends DurableObject {
4908
5281
  }
4909
5282
  this.recordConnectionGrant({ ...row, vertical: conn.vertical });
4910
5283
  if (!row.scopeId) {
4911
- 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);
4912
5285
  }
4913
5286
  const after = (audit.after ?? {});
4914
5287
  this.recordAdmin({ ...audit, vertical: conn.vertical, after: { ...after, provider: conn.provider } });
4915
5288
  return { vertical: conn.vertical };
4916
5289
  });
4917
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
+ }
4918
5333
  /**
4919
5334
  * #2732: `revokeFromConnection`'s directory half as one unit, after the scope's tuple was
4920
5335
  * delivered gone. The scope-level record is tombstoned (K-21), so the additive reconcile never
@@ -4982,6 +5397,9 @@ export class ControlPlaneDO extends DurableObject {
4982
5397
  * there is a tenant tuple is still switchable. Read here, where the tenant tuples live.
4983
5398
  */
4984
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 });
4985
5403
  return tenantHeldOf(this.kernelSql, kind, tenantId, keys, now);
4986
5404
  }
4987
5405
  /** The fleet read. */