@substrat-run/adapter-cloudflare 0.221.0 → 0.223.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 (86) 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 +251 -67
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +666 -247
  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/executor-route.d.ts +13 -0
  57. package/dist/executor-route.d.ts.map +1 -0
  58. package/dist/executor-route.js +12 -0
  59. package/dist/executor-route.js.map +1 -0
  60. package/dist/host.d.ts +76 -2
  61. package/dist/host.d.ts.map +1 -1
  62. package/dist/host.js +386 -67
  63. package/dist/host.js.map +1 -1
  64. package/dist/index.d.ts +2 -1
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +1 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/platform-sweeper-do.d.ts +1 -1
  69. package/dist/platform-sweeper-do.js +1 -1
  70. package/dist/scope-do.d.ts +11 -2
  71. package/dist/scope-do.d.ts.map +1 -1
  72. package/dist/scope-do.js +206 -58
  73. package/dist/scope-do.js.map +1 -1
  74. package/dist/scope-sweeper-do.d.ts +22 -0
  75. package/dist/scope-sweeper-do.d.ts.map +1 -1
  76. package/dist/scope-sweeper-do.js +74 -54
  77. package/dist/scope-sweeper-do.js.map +1 -1
  78. package/dist/scope-wake.d.ts +12 -1
  79. package/dist/scope-wake.d.ts.map +1 -1
  80. package/dist/scope-wake.js +14 -1
  81. package/dist/scope-wake.js.map +1 -1
  82. package/dist/tenant-due-work-do.d.ts +99 -0
  83. package/dist/tenant-due-work-do.d.ts.map +1 -0
  84. package/dist/tenant-due-work-do.js +149 -0
  85. package/dist/tenant-due-work-do.js.map +1 -0
  86. package/package.json +10 -10
package/dist/host.js CHANGED
@@ -2,16 +2,19 @@ import { restoreChunksOf } from './directory-restore-chunks.js';
2
2
  import { env as ambientEnv } from 'cloudflare:workers';
3
3
  import { isRewindRefusal, REWIND_REFUSED } from './rewind-refusal.js';
4
4
  import { isSystemDoorMoved, SYSTEM_DOOR_MOVED, SYSTEM_DOOR_REGATES } from './system-door.js';
5
- import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, pushedImport, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, assertScopeTypesKept, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, verticalTraceSampling, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, staleScope, staleScopeTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, appEnvironment as appEnvironmentSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
5
+ import { EXECUTOR_ROUTE_NOT_DUE } from './executor-route.js';
6
+ import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, pushedImport, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, assertScopeTypesKept, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, verticalTraceSampling, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, staleScope, staleScopeTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, appEnvironment as appEnvironmentSchema, environmentServeAcknowledgement, environmentEffects as environmentEffectsSchema, connectionReach as connectionReachSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
6
7
  import { normalizeHostname, toRouteTarget } from './route-resolver.js';
7
8
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
8
- import { breakingWithinMajorRefusal, earlierMajorsOf, releaseWithinMajorRefusal } from '@substrat-run/kernel';
9
+ import { breakingWithinMajorRefusal, earlierMajorReleaseTarget, earlierMajorsOf, releaseWithinMajorRefusal } from '@substrat-run/kernel';
9
10
  import { classify as classifyRelease } from '@substrat-run/model-view/bump';
10
11
  import { ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary } from '@substrat-run/kernel';
11
12
  import { CONNECTOR_DISPATCH_REQUESTED_BY, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
12
13
  import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, provisionedScopeType,
14
+ // #2995: the parent link a provision-child writes, and the doors it decides.
15
+ childDoorRefusal, childScopeRefusal, claimsHome, directAccessRefusal, parentlessScopeRefusal, provisionedParent,
13
16
  // #2993 part 3: the modules (and seats) a scope of each declared type has.
14
- HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
17
+ HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, sealingKeysForReach, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
15
18
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
16
19
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
17
20
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
@@ -53,6 +56,12 @@ export const LIFECYCLE_EPOCH_SKEW_MS = 24 * 60 * 60 * 1000;
53
56
  * before the record) costs at most this many deliveries a pass and starves nothing.
54
57
  */
55
58
  export const TENANT_UNRECORDED_PER_PASS = 50;
59
+ /**
60
+ * K-69 (#3540): how soon after a failed delivery its first retry is due. The directory's own back-off
61
+ * (#3119) waits nothing after a first failure, which the sweep read as "the next pass"; an alarm
62
+ * looks again a minute on, then on the directory's back-off.
63
+ */
64
+ export const LIFECYCLE_RETRY_FIRST_LOOK_MS = 60_000;
56
65
  /**
57
66
  * K-3's refusal of a (tenant, scope) pair the host does not hold — the same answer for a scope that
58
67
  * does not exist and for one of another tenant (#1718), in one wording.
@@ -112,20 +121,6 @@ function assertCopyLineage(lineage) {
112
121
  throw substratError('conflict', 'mark-copy refused: the directory classifies this scope as primary, not as a copy');
113
122
  }
114
123
  }
115
- /**
116
- * A control-plane stand-in for a CP-less vertical (scope-local-permissions.md Phase 3).
117
- * The hot path a served scope actually touches becomes trust-the-upstream:
118
- * - `scopeAccessRefusal` / `setMigrationState` → no-op: the router gates the scope's
119
- * lifecycle + tenancy from the shared directory, and the vertical does not re-read a
120
- * directory it does not have. Its own half of both gates reads the scope's storage
121
- * instead (`validateScopeAccess`): the tenant the scope was provisioned for (#2016) and the lifecycle
122
- * the platform delivered (#1713).
123
- * - `tenantHoldsEntitlement` → true: the SKU was enforced on the shared control plane
124
- * at provision (before `provisionInstance`), so a scope that EXISTS here was granted
125
- * it upstream — a single-vertical deployment holds its own entitlements by construction.
126
- * - `recordAdmin` / `recordAccess` → no-op: the shared control plane owns the audit spine.
127
- * Every other method throws — the admin directory surface genuinely is unavailable.
128
- */
129
124
  function nullControlPlane() {
130
125
  const noop = async () => undefined;
131
126
  const passthrough = {
@@ -486,6 +481,7 @@ export class CloudflareScopeHost {
486
481
  systemSwitchDelegation;
487
482
  /** #1713: the lifecycle's reach into the deployment serving a scope. */
488
483
  lifecycleDelegation;
484
+ lifecycleRetryOwner;
489
485
  /** #1706: the peer kill switch's reach into the deployment serving a scope. */
490
486
  peerSwitchDelegation;
491
487
  /** #1705 PR 3: the replay lever's reach into the deployment serving a consumer scope. */
@@ -558,6 +554,7 @@ export class CloudflareScopeHost {
558
554
  this.eventDrainDelegation = options.eventDrainDelegation;
559
555
  this.systemSwitchDelegation = options.systemSwitchDelegation;
560
556
  this.lifecycleDelegation = options.lifecycleDelegation;
557
+ this.lifecycleRetryOwner = options.lifecycleRetryOwner;
561
558
  this.peerSwitchDelegation = options.peerSwitchDelegation;
562
559
  this.importCursorDelegation = options.importCursorDelegation;
563
560
  this.capabilityDelegation = options.capabilityDelegation;
@@ -604,14 +601,19 @@ export class CloudflareScopeHost {
604
601
  tenantId,
605
602
  scopeId,
606
603
  vertical: vertical ?? '',
607
- connection: async (provider) => {
604
+ connection: async (provider, options) => {
608
605
  if (!vertical) {
609
606
  throw new Error(`scope ${scopeId} is bound to no vertical, so it has no connection namespace — ` +
610
607
  `provision it with a vertical before using connectors`);
611
608
  }
612
- const open = await admin.openConnection(tenantId, vertical, provider);
609
+ // #3530 step 6: `own` opens this scope's own connection, and never the tenant's.
610
+ const open = options?.own
611
+ ? await admin.openConnection(tenantId, vertical, provider, undefined, scopeId)
612
+ : await admin.openConnection(tenantId, vertical, provider);
613
613
  if (!open) {
614
- throw new Error(`no live '${provider}' connection for tenant ${tenantId} / vertical '${vertical}'`);
614
+ throw new Error(options?.own
615
+ ? `scope ${scopeId} owns no live '${provider}' connection, and a dispatch held to its own opens no other`
616
+ : `no live '${provider}' connection for tenant ${tenantId} / vertical '${vertical}'`);
615
617
  }
616
618
  return {
617
619
  ...open,
@@ -805,6 +807,13 @@ export class CloudflareScopeHost {
805
807
  roomFull = true;
806
808
  continue drain;
807
809
  }
810
+ if (routed === EXECUTOR_ROUTE_NOT_DUE) {
811
+ // #3676: another pass acting on the same due read routed it first. The scope decided
812
+ // that in the transaction that would have written, so nothing was: not an attempt,
813
+ // and not a full room — the pass goes on to the next delivery.
814
+ report.attempted -= 1;
815
+ continue;
816
+ }
808
817
  report.routedToPlatform += 1;
809
818
  outcomeOf(event, 'routed');
810
819
  // Handed on, not run here: the platform's drain owns its attempts from now on.
@@ -1931,11 +1940,6 @@ export class CloudflareScopeHost {
1931
1940
  }
1932
1941
  /** `provisionScope`, answering whether this call created the directory row (#2555: an import's teardown). */
1933
1942
  async provisionScopeCreating(actor, input) {
1934
- // #2995: this host does not keep parent links yet (the pure host does). A child provisioned here
1935
- // would be a scope with no link, reachable as a sibling and outliving its parent, so it is refused.
1936
- if (input.parentScopeId !== undefined) {
1937
- throw substratError('unavailable', 'a child scope cannot be provisioned on this host yet: the parent link is kept by the pure host only (#2995)');
1938
- }
1939
1943
  // Shared with the pure adapter so the defaults cannot drift between them.
1940
1944
  const record = resolveScopeRecord(input);
1941
1945
  // #2993: the type this provision gives the scope, by the kernel's rule, before anything is
@@ -1949,20 +1953,85 @@ export class CloudflareScopeHost {
1949
1953
  ? await this.verticalScopeTypePlan(record.vertical)
1950
1954
  : own;
1951
1955
  const typed = plan.declared;
1952
- const recorded = typed ? await this.cp.getScopeRecord(input.tenantId, input.scopeId) : undefined;
1956
+ // #2995: a provision naming a parent reads the row too, for the link it may already hold.
1957
+ const recorded = typed || input.parentScopeId !== undefined ? await this.cp.getScopeRecord(input.tenantId, input.scopeId) : undefined;
1953
1958
  const scopeType = provisionedScopeType(plan, input.scopeType, recorded === undefined ? undefined : (recorded.scope_type ?? null), input.scopeId);
1959
+ // #2995 (K-64): the parent link, judged before anything is written. A new child is held to its
1960
+ // parent's declared children, tenant, app, state and depth (`childScopeRefusal`); the directory
1961
+ // judges the parent's state and the link's fixedness again in the write's own unit, so an archive
1962
+ // of the parent landing between the two is refused there. Then (the owner's word on #3604's
1963
+ // fourth question) a new scope of a type other than home has a parent, unless it is a copy.
1964
+ const namedParent = recorded === undefined && input.parentScopeId === undefined
1965
+ ? null
1966
+ : provisionedParent(input.parentScopeId, recorded === undefined ? undefined : (recorded.parent_scope_id ?? null), input.scopeId);
1967
+ // #3625 (K-64): a new typed scope that names no parent is a child of its app's home scope, judged
1968
+ // below as any named parent is. Only where this host runs the scope's modules (`own.declared`) and so
1969
+ // fixes the link on the scope's own object itself: a module-less coordinator's vertical learns a link
1970
+ // from `/internal/provision`, which `provision-child` alone sends, so there it is named that way.
1971
+ const parentScopeId = recorded === undefined && namedParent === null && own.declared &&
1972
+ scopeType !== HOME_SCOPE_TYPE && record.forkedFrom === null && record.vertical !== null
1973
+ ? (await this.cp.homeScopeOf(input.tenantId, record.vertical))
1974
+ : namedParent;
1975
+ if (recorded === undefined) {
1976
+ if (parentScopeId !== null) {
1977
+ const parent = await this.cp.getScopeRecord(input.tenantId, parentScopeId);
1978
+ const refusal = childScopeRefusal(plan, parentScopeId, parent && {
1979
+ tenantId: parent.tenant_id,
1980
+ status: parent.status,
1981
+ vertical: parent.vertical,
1982
+ type: parent.scope_type ?? HOME_SCOPE_TYPE,
1983
+ parentScopeId: parent.parent_scope_id ?? null,
1984
+ forkedFrom: parent.forked_from ?? null,
1985
+ }, { tenantId: input.tenantId, vertical: record.vertical, type: scopeType });
1986
+ if (refusal)
1987
+ throw refusal;
1988
+ }
1989
+ const parentless = parentlessScopeRefusal(scopeType, parentScopeId, record.forkedFrom, input.scopeId);
1990
+ if (parentless)
1991
+ throw parentless;
1992
+ }
1993
+ // #2993 (K-64): a sibling of an app that declares scope types claims the home as an install does,
1994
+ // judged by the directory in its own unit. Typed by this host's own declaration, or (a module-less
1995
+ // coordinator) by the vertical's deployed version's, read only for a sibling.
1996
+ const typedSibling = input.sibling === true && record.vertical !== null &&
1997
+ (plan.declared || (await this.verticalScopeTypePlan(record.vertical)).declared);
1998
+ const homeClaim = {
1999
+ vertical: record.vertical,
2000
+ type: scopeType,
2001
+ parentScopeId,
2002
+ forkedFrom: record.forkedFrom,
2003
+ kind: record.kind,
2004
+ install: input.install,
2005
+ sibling: input.sibling,
2006
+ typed: typedSibling,
2007
+ };
1954
2008
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1955
2009
  // or audit, so a rejected provision creates nothing and writes no audit row.
1956
2010
  const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
1957
2011
  // #2993: the directory row records the type ('home' as NULL), and refuses a different one in
1958
2012
  // its own unit. An untyped host sends none and writes the row it always did.
1959
- typed ? { ...record, scopeType: scopeType === HOME_SCOPE_TYPE ? null : scopeType } : record, new Date().toISOString());
2013
+ {
2014
+ ...(typed ? { ...record, scopeType: scopeType === HOME_SCOPE_TYPE ? null : scopeType } : record),
2015
+ // #2995: the link as the caller named it; the directory fixes it against its row. #3625: or the
2016
+ // home scope a typed scope's parent defaulted to above.
2017
+ ...(input.parentScopeId !== undefined
2018
+ ? { parentScopeId: input.parentScopeId }
2019
+ : recorded === undefined && parentScopeId !== null ? { parentScopeId } : {}),
2020
+ // #3625 (K-64): an install, which the directory refuses in its own unit while the app has a home
2021
+ // scope in the tenant (`secondHomeRefusal`). Sent only when it claims, so a write without it is
2022
+ // judged as before. #2993: `'sibling'` for a sibling of a typed app, refused in its own words.
2023
+ ...(claimsHome(homeClaim) ? { claimsHome: input.install === true ? true : 'sibling' } : {}),
2024
+ }, new Date().toISOString());
1960
2025
  // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1961
2026
  // first pass lays down only its type's tables. A host with no declared types asks nothing. A
1962
2027
  // coordinator judging by a vertical's types (part 4) does not either: the vertical's own
1963
2028
  // object is fixed by its `/internal/provision`, which the platform sends the type.
1964
2029
  if (own.declared)
1965
2030
  unwrapReply(await this.scopeStub(input.scopeId).fixScopeTypeReply(scopeType, input.scopeId));
2031
+ // #2995: and its parent, so a door of this host's own namespace judges a child as the directory does.
2032
+ if (own.declared && parentScopeId !== null) {
2033
+ unwrapReply(await this.scopeStub(input.scopeId).fixScopeParentReply(parentScopeId, input.scopeId));
2034
+ }
1966
2035
  // Instantiate the scope DO and trigger its lazy migration.
1967
2036
  await this.migrateAndRecord(input.scopeId);
1968
2037
  // Scope-local permissions: a freshly-provisioned scope evaluates from its own
@@ -2016,7 +2085,12 @@ export class CloudflareScopeHost {
2016
2085
  if (created) {
2017
2086
  await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2018
2087
  // #2993: a typed scope's audit row names its type, as on the pure host; a home scope's reads as it always did.
2019
- scopeType === HOME_SCOPE_TYPE ? record : { ...record, scopeType });
2088
+ // #2995: a child's names its parent.
2089
+ {
2090
+ ...record,
2091
+ ...(scopeType === HOME_SCOPE_TYPE ? {} : { scopeType }),
2092
+ ...(parentScopeId === null ? {} : { parentScopeId }),
2093
+ });
2020
2094
  }
2021
2095
  return created;
2022
2096
  }
@@ -2453,6 +2527,11 @@ export class CloudflareScopeHost {
2453
2527
  * scope of this host, made at once, so its seats are the ones that scope holds now (K-55).
2454
2528
  */
2455
2529
  async importScopeFrom(actor, input, dump, judge) {
2530
+ // #2995: a copy carries no parent link. A link is written by provision-child alone, so a copy of a
2531
+ // child is a scope of its type with no parent, and nothing reaches it through the source's parent.
2532
+ if (input.parentScopeId !== undefined) {
2533
+ throw substratError('validation_failed', 'a copy carries no parent link: a child is provisioned through provision-child only');
2534
+ }
2456
2535
  this.refuseUnusableScopeStores(dump.stores, input.vertical ?? null);
2457
2536
  if (judge)
2458
2537
  await this.refuseDumpRoles(input.tenantId, null, dump);
@@ -2476,7 +2555,7 @@ export class CloudflareScopeHost {
2476
2555
  const load = { sourceScopeId: dump.scopeId, exact: true };
2477
2556
  // #2555: an import lands with the directory's current permission state, as a restore does. A
2478
2557
  // snapshot is left as it was: a same-instant copy of a live scope the fan-out keeps current.
2479
- const projection = judge ? await this.loadProjectionFor(input.tenantId, input.vertical) : undefined;
2558
+ const projection = judge ? await this.loadProjectionFor(input.tenantId, input.vertical, input.scopeId) : undefined;
2480
2559
  let reprojected;
2481
2560
  if (projection === undefined)
2482
2561
  await this.scopeStub(input.scopeId).importDump(dump.tables, input.scopeId, load);
@@ -2524,7 +2603,7 @@ export class CloudflareScopeHost {
2524
2603
  // #2555: judged before the fence, so a refused restore moves nothing.
2525
2604
  await this.refuseDumpRoles(tenantId, scopeId, dump);
2526
2605
  // #2555: the directory's state the load projects, judged again in its unit against the seats it loads.
2527
- const projection = await this.loadProjectionFor(tenantId, existing.vertical);
2606
+ const projection = await this.loadProjectionFor(tenantId, existing.vertical, scopeId);
2528
2607
  // #2314: the load replaces the scope's rows, so the orphan sweep is fenced first.
2529
2608
  await this.fenceOrphanSweep(scopeId, tenantId);
2530
2609
  // #1742: a dump from before a switch was pulled brings the module's grants back live, so
@@ -2680,7 +2759,60 @@ export class CloudflareScopeHost {
2680
2759
  const parsedDelegation = parseScopeDelegation(options?.delegation);
2681
2760
  // Lifecycle gates (control-plane.md §4.1/§4.2), the K-3 fail-closed path,
2682
2761
  // evaluated durably in the ControlPlaneDO. A throw propagates here.
2683
- await this.assertLive(tenantId, scopeId, 'getScope');
2762
+ const held = {};
2763
+ await this.assertLive(tenantId, scopeId, 'getScope', held);
2764
+ // #2995: a child whose type accepts its parent only is not reached by a direct request.
2765
+ if (this.scopeTypePlan.declared) {
2766
+ const link = this.cpLess ? held : await this.directoryLinkOf(tenantId, scopeId);
2767
+ const direct = directAccessRefusal(this.scopeTypePlan, link.type ?? HOME_SCOPE_TYPE, link.parent ?? null, scopeId);
2768
+ if (direct)
2769
+ throw direct;
2770
+ }
2771
+ return this.personDoor(principal, tenantId, scopeId, options, parsedDelegation);
2772
+ }
2773
+ /**
2774
+ * `ScopeHost.getChildScope` (#2995, K-64): the person's stub on a child, for host code of its parent,
2775
+ * between two of its own transactions. The link, the child's type and the parent's state are judged
2776
+ * first (`childDoorRefusal`), from the directory, or on a CP-less host from the two scopes' own
2777
+ * storage: the child holds its type and its parent (`fixScopeParentReply`), and the parent the
2778
+ * lifecycle the platform delivered it. A parent this deployment does not hold (a child on another
2779
+ * script) reads as unknown, so the call is refused rather than sent to an empty object. Then the
2780
+ * person's door runs as `getScope` runs it, and every check in the child is the person's own grants.
2781
+ */
2782
+ async getChildScope(caller, tenantId, scopeId, options) {
2783
+ if (caller?.actor?.kind !== 'person') {
2784
+ throw substratError('validation_failed', 'a call into a child acts for a person: the app acting as itself is not built (#2995)');
2785
+ }
2786
+ const parsedDelegation = parseScopeDelegation(options?.delegation);
2787
+ let child;
2788
+ let parent;
2789
+ if (this.cpLess) {
2790
+ const held = (v) => v.verdict === 'recorded' || v.verdict === 'inferred';
2791
+ const c = await this.scopeStub(scopeId).admission(tenantId);
2792
+ const p = await this.scopeStub(caller.parentScopeId).admission(tenantId);
2793
+ child = held(c) ? { tenantId, type: c.type, parentScopeId: c.parent } : undefined;
2794
+ // Nothing delivered yet reads as live, as at every CP-less door; the child's own door below judges the tenant.
2795
+ parent = held(p) ? { tenantId, status: p.lifecycle?.scope ?? 'active' } : undefined;
2796
+ }
2797
+ else {
2798
+ const c = await this.cp.getScopeRecord(tenantId, scopeId);
2799
+ const p = await this.cp.getScopeRecord(tenantId, caller.parentScopeId);
2800
+ child = c && { tenantId: c.tenant_id, type: c.scope_type ?? HOME_SCOPE_TYPE, parentScopeId: c.parent_scope_id ?? null };
2801
+ parent = p && { tenantId: p.tenant_id, status: p.status };
2802
+ }
2803
+ const refusal = childDoorRefusal(this.scopeTypePlan, tenantId, caller.parentScopeId, scopeId, child, parent);
2804
+ if (refusal)
2805
+ throw refusal;
2806
+ await this.assertLive(tenantId, scopeId, 'getChildScope');
2807
+ return this.personDoor(caller.actor.principal, tenantId, scopeId, options, parsedDelegation);
2808
+ }
2809
+ /** #2995: a scope's type and parent as the directory records them. */
2810
+ async directoryLinkOf(tenantId, scopeId) {
2811
+ const rec = await this.cp.getScopeRecord(tenantId, scopeId);
2812
+ return { type: rec?.scope_type ?? HOME_SCOPE_TYPE, parent: rec?.parent_scope_id ?? null };
2813
+ }
2814
+ /** The person's door past the pair, lifecycle and reach checks: migrations, then the stub. */
2815
+ async personDoor(principal, tenantId, scopeId, options, parsedDelegation) {
2684
2816
  await this.migrateAndRecord(scopeId);
2685
2817
  // #3161: a person's call arriving through a peer goes through that peer's door, as
2686
2818
  // `getVerticalScope` opens it (the name `peers` uses, the rewind hold, the pin), and the
@@ -4255,6 +4387,7 @@ export class CloudflareScopeHost {
4255
4387
  : [filter.status]
4256
4388
  : undefined,
4257
4389
  vertical: filter?.vertical,
4390
+ ...(filter?.parentScopeId ? { parentScopeId: filter.parentScopeId } : {}),
4258
4391
  limit: filter?.limit,
4259
4392
  cursor: filter?.cursor,
4260
4393
  order: filter?.order,
@@ -5348,6 +5481,12 @@ export class CloudflareScopeHost {
5348
5481
  throw substratError(answer.code, answer.message);
5349
5482
  return { changed: answer.changed, previous: answer.previous };
5350
5483
  },
5484
+ // #3625 (K-64): the home scope of (tenant, app, environment). The rule is the kernel's (`home-scope.ts`).
5485
+ homeScopeOf: async (actor, tenantId, vertical, environment) => {
5486
+ const scopeId = await this.cp.homeScopeOf(tenantId, vertical, environment);
5487
+ await this.recordAccess(actor, 'homeScopeOf', { tenantId }, { vertical, environment: environment ?? 'prod' }, scopeId ? 1 : 0);
5488
+ return scopeId;
5489
+ },
5351
5490
  // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
5352
5491
  listEnvironments: async (actor, tenantId, vertical) => {
5353
5492
  const rows = await this.cp.listEnvironments(tenantId, verticalSlug.parse(vertical));
@@ -5367,13 +5506,21 @@ export class CloudflareScopeHost {
5367
5506
  releaseEnvironmentServe: async (_actor, input, claim) => {
5368
5507
  await this.cp.releaseEnvironmentServe({ ...input, vertical: verticalSlug.parse(input.vertical) }, claim);
5369
5508
  },
5370
- setEnvironmentServing: async (actor, input, next, expected, claim) => {
5509
+ setEnvironmentServing: async (actor, input, next, expected, claim, acknowledge) => {
5371
5510
  const vertical = verticalSlug.parse(input.vertical);
5372
- const moved = await this.directory('setEnvironmentServingAndAudit', { ...input, vertical }, next, expected, this.adminEntry(actor, 'setEnvironmentServing', { tenantId: input.tenantId, vertical }, null, null), claim);
5511
+ // #3638: parsed here, judged in the directory's write that moves what the environment serves.
5512
+ const ack = acknowledge === undefined ? undefined : environmentServeAcknowledgement.parse(acknowledge);
5513
+ const moved = await this.directory('setEnvironmentServingAndAudit', { ...input, vertical }, next, expected, this.adminEntry(actor, 'setEnvironmentServing', { tenantId: input.tenantId, vertical }, null, null), claim, ack);
5373
5514
  if (!moved) {
5374
5515
  throw substratError('precondition_failed', `the environment '${input.name}' of '${vertical}' serves another record than the one this serve was diffed from: read it again`);
5375
5516
  }
5376
5517
  },
5518
+ // #3530 step 6: an environment given connections of its own, and the rule every connection door asks.
5519
+ setEnvironmentEffects: async (actor, input, effects) => {
5520
+ const vertical = verticalSlug.parse(input.vertical);
5521
+ return this.directory('setEnvironmentEffectsAndAudit', { ...input, vertical }, environmentEffectsSchema.parse(effects), this.adminEntry(actor, 'setEnvironmentEffects', { tenantId: input.tenantId, vertical }, null, null));
5522
+ },
5523
+ connectionReach: async (_actor, tenantId, scopeId) => connectionReachSchema.parse(await this.cp.connectionReach(tenantId, scopeId)),
5377
5524
  resolveHostname: async (raw) =>
5378
5525
  // The router's per-request read. No actor, not logged — the same machine-path
5379
5526
  // carve-out resolveIdentity has (K-24). Shares its mapping with the router's
@@ -5560,23 +5707,41 @@ export class CloudflareScopeHost {
5560
5707
  if (incoming.admission !== 'admitted') {
5561
5708
  throw substratError('conflict', `version ${versionId} is ${incoming.admission}, not admitted — it cannot be promoted`);
5562
5709
  }
5563
- const current = await this.cp.readChannel(verticalSlug, channel);
5710
+ // K-65 (#3539): a release that names an earlier major goes to that major's own script, and
5711
+ // every gate below is judged against the version that script runs, in place of the channel's.
5712
+ const target = options?.earlierMajor === undefined
5713
+ ? null
5714
+ : await (async () => {
5715
+ if (channel !== 'prod')
5716
+ throw substratError('validation_failed', 'an earlier major is released on prod alone');
5717
+ return earlierMajorReleaseTarget({
5718
+ vertical: verticalSlug,
5719
+ earlierJson: (await this.cp.readVertical(verticalSlug))?.earlier_majors,
5720
+ major: options.earlierMajor,
5721
+ head: { version: incoming.version, deploymentRef: incoming.deployment_ref },
5722
+ servesMajors: options.servesMajors === true,
5723
+ });
5724
+ })();
5725
+ const current = target ? { version_id: target.versionId } : await this.cp.readChannel(verticalSlug, channel);
5564
5726
  const outgoing = current ? await this.cp.readVersion(current.version_id) : undefined;
5565
5727
  const ack = promotionAcknowledgement.parse(acknowledge ?? {});
5566
5728
  // The owning tenant's live scopes a PRIVATE prod promote re-points — below for an embedded
5567
5729
  // vertical, after the in-place serve for a dispatch-backed one (#321) — read before
5568
- // anything moves so the #2178 gate can judge each one.
5730
+ // anything moves so the #2178 gate can judge each one. A release into an earlier major
5731
+ // re-points none: only the installs on that major's script run it.
5569
5732
  const owning = channel === 'prod' ? await this.cp.readVertical(verticalSlug) : undefined;
5570
- const owned = owning && owning.owner_tenant !== null && !owning.listed
5733
+ const owned = !target && owning && owning.owner_tenant !== null && !owning.listed
5571
5734
  ? (await this.cp.listScopes({ tenantId: owning.owner_tenant, vertical: verticalSlug, status: ['active'] })).filter(isPrimaryScopeRow)
5572
5735
  : [];
5573
5736
  // #2178, ahead of the acknowledgements below because none of them passes it. What the promote
5574
5737
  // moves something from: the channel's version, the version served in place (a prod promote
5575
5738
  // serves the incoming one next, and a failed serve leaves it behind the channel), and what each
5576
5739
  // re-pointed scope RUNS (`runningVersionOf`: on the serving script, the served version).
5577
- const served = channel === 'prod' && owning?.serving_ref && owning.serving_version_id
5578
- ? { ref: owning.serving_ref, versionId: owning.serving_version_id }
5579
- : null;
5740
+ const served = target
5741
+ ? { ref: target.ref, versionId: target.versionId }
5742
+ : channel === 'prod' && owning?.serving_ref && owning.serving_version_id
5743
+ ? { ref: owning.serving_ref, versionId: owning.serving_version_id }
5744
+ : null;
5580
5745
  // And what each scope it moves last reconciled (`PROVISIONED_VERSIONS_SQL`).
5581
5746
  await this.assertNoStrandFrom([
5582
5747
  outgoing?.id,
@@ -5600,7 +5765,8 @@ export class CloudflareScopeHost {
5600
5765
  throw breakingWithinMajorRefusal(breakingWithinMajor);
5601
5766
  // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
5602
5767
  // of the acknowledgements, because none of them passes it.
5603
- assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
5768
+ // K-65 (#3539): a release into an earlier major reaches the scopes on its script alone.
5769
+ assertScopeTypesKept(verticalSlug, await (target ? this.cp.scopeTypesHeldBy(verticalSlug, target.ref) : this.cp.scopeTypesHeldBy(verticalSlug)), incoming.manifest_json);
5604
5770
  // #2333: the acknowledgements answer the review they were given against, or none at all.
5605
5771
  const reviewed = async (v) => ({
5606
5772
  id: v.id,
@@ -5633,6 +5799,16 @@ export class CloudflareScopeHost {
5633
5799
  throw substratError('precondition_failed', exportBreakRefusal(breaks));
5634
5800
  }
5635
5801
  }
5802
+ // K-65 (#3539): a release into an earlier major moves no channel. Its admin row, the
5803
+ // acknowledgement's evidence, lands only while that major's script still runs the version its
5804
+ // gates were judged against, with the listing and the admission read in the DO's unit as a
5805
+ // prod promote's are. The caller then serves it on the script and records that.
5806
+ if (target) {
5807
+ const judged = await this.directory('recordEarlierMajorPromote', verticalSlug, target.major, target.versionId, versionId, options?.unlistedOnly === true, this.adminEntry(actor, 'promoteVersion', { tenantId: null, vertical: verticalSlug }, outgoing ? { versionId: outgoing.id, version: outgoing.version } : null, { channel, versionId, version: incoming.version, earlierMajor: target.major, acknowledged: ack }), breakingWithinMajor);
5808
+ if (!judged)
5809
+ throw promoteRaceRefusal(channel);
5810
+ return;
5811
+ }
5636
5812
  const promotedAt = new Date().toISOString();
5637
5813
  // #2333: a compare-and-set. Every gate above — the review binding, the digest checkpoints,
5638
5814
  // the export breaks — was judged against `outgoing`, across awaits another promote can run
@@ -5785,7 +5961,7 @@ export class CloudflareScopeHost {
5785
5961
  throw substratError('precondition_failed', `scope ${scopeId} is being reaped`);
5786
5962
  },
5787
5963
  markScopeStoresFenced: async (actor, tenantId, scopeId, opts) => {
5788
- await this.directory('markScopeStoresFenced', tenantId, scopeId, opts?.whileTenantDeleting === true, this.adminEntry(actor, 'markScopeStoresFenced', { tenantId, scopeId }, null, { storesFenced: true }));
5964
+ await this.directory('markScopeStoresFenced', tenantId, scopeId, opts?.whileTenantDeleting === true, this.adminEntry(actor, 'markScopeStoresFenced', { tenantId, scopeId }, null, { storesFenced: true }), opts?.archivedBy === undefined && opts?.deletingBy === undefined ? undefined : opts);
5789
5965
  },
5790
5966
  scopeStoresFencedAt: async (_actor, tenantId, scopeId) => this.cp.scopeStoresFencedAt(tenantId, scopeId),
5791
5967
  beginScopeScriptReap: async (_actor, tenantId, scopeId, opts) => {
@@ -5851,6 +6027,26 @@ export class CloudflareScopeHost {
5851
6027
  const r = await this.cp.readVertical(verticalSlug);
5852
6028
  if (!r)
5853
6029
  throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
6030
+ // K-65 (#3539): a release served on an earlier major's own script moves that major's entry alone.
6031
+ if (opts?.earlierMajor !== undefined) {
6032
+ const major = opts.earlierMajor;
6033
+ if (supersede)
6034
+ throw substratError('validation_failed', 'a serve records a new major or a release into an earlier one, not both');
6035
+ const entry = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
6036
+ if (!expected || !entry || entry.versionId !== expected.versionId)
6037
+ throw servingRaceRefusal(verticalSlug);
6038
+ const incoming = await this.cp.readVersion(parsed.versionId);
6039
+ if (!incoming || incoming.vertical_slug !== verticalSlug) {
6040
+ throw substratError('not_found', `unknown version ${parsed.versionId} for vertical '${verticalSlug}'`);
6041
+ }
6042
+ // #2993 part 4 and #2178, as an in-place serve is judged, over the installs on that script.
6043
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug, entry.ref), incoming.manifest_json);
6044
+ await this.assertNoStrandFrom([entry.versionId], incoming.id, incoming, await this.cp.provisionedVersionsOf(verticalSlug, { ref: entry.ref, versionId: entry.versionId }, null));
6045
+ await this.directory('setEarlierMajorServing', verticalSlug, major, {
6046
+ ref: parsed.ref, versionId: parsed.versionId, doClasses: parsed.doClasses, migrationTag: parsed.migrationTag,
6047
+ }, { versionId: expected.versionId, doClasses: expected.doClasses, migrationTag: expected.migrationTag }, this.adminEntry(actor, 'setVerticalServing', { tenantId: null }, null, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId, earlierMajor: major }));
6048
+ return;
6049
+ }
5854
6050
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
5855
6051
  if (expected !== undefined && !migratesFrom(r, expected))
5856
6052
  throw servingRaceRefusal(verticalSlug);
@@ -6095,12 +6291,12 @@ export class CloudflareScopeHost {
6095
6291
  // A rename to the current name writes nothing and is not audited; the DO fills `before`.
6096
6292
  await this.directory('setTenantName', tenantId, name, this.adminEntry(actor, 'setTenantName', { tenantId }, null, { name }));
6097
6293
  },
6098
- reapTenant: async (actor, tenantId) => {
6294
+ reapTenant: async (actor, tenantId, opts) => {
6099
6295
  // Directory-side terminal reap (§4.8). The caller reaped every scope's storage
6100
6296
  // first (archive-if-needed → reapScope in the vertical deployment); the DO clears
6101
6297
  // the tenant's PII/config rows and flips the row to a `reaped` tombstone, keeping
6102
6298
  // the row + admin log. Only a `deleting` tenant may be reaped (checked in the DO).
6103
- await this.directory('reapTenant', tenantId, this.adminEntry(actor, 'reapTenant', { tenantId }, null, { status: 'reaped' }));
6299
+ await this.directory('reapTenant', tenantId, this.adminEntry(actor, 'reapTenant', { tenantId }, null, { status: 'reaped' }), opts?.deletingBy);
6104
6300
  },
6105
6301
  listTenants: async (actor, page) => {
6106
6302
  const tenants = (await this.cp.listTenants(page)).map((t) => tenantSchema.parse(t));
@@ -6594,10 +6790,26 @@ export class CloudflareScopeHost {
6594
6790
  },
6595
6791
  suspendScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'suspendScope', tenantId, scopeId, ['active'], 'suspended'),
6596
6792
  unsuspendScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'unsuspendScope', tenantId, scopeId, ['suspended'], 'active'),
6597
- archiveScope: async (actor, tenantId, scopeId) =>
6598
- // Also from `provisioning`: a scope whose provisioning never completed (a failed
6599
- // create) must be abandonable, or its slug is stranded forever.
6600
- transitionScope(actor, 'archiveScope', tenantId, scopeId, ['provisioning', 'active', 'suspended'], 'archived'),
6793
+ archiveScope: async (actor, tenantId, scopeId) => {
6794
+ // Also from `provisioning`: a scope whose provisioning never completed (a failed
6795
+ // create) must be abandonable, or its slug is stranded forever.
6796
+ //
6797
+ // #2995: lifecycle follows the link. The scope's children are archived with it, in the same
6798
+ // directory unit, each with its own audit row naming the parent; a refused parent archives
6799
+ // none. A child already archived stays as it is. Each is then delivered its lifecycle, as a
6800
+ // single archive is, so a child's own deployment stops serving it too.
6801
+ const from = ['provisioning', 'active', 'suspended'];
6802
+ const before = await this.cp.archiveScopeFamilyOrRefusal(tenantId, scopeId, from, 'archiveScope');
6803
+ if (!before.ok)
6804
+ throw before.code ? substratError(before.code, before.message) : new Error(before.message);
6805
+ for (const child of before.children) {
6806
+ await this.recordAdmin(actor, 'archiveScope', { tenantId, scopeId: child.scopeId, vertical: child.vertical }, { status: child.status }, { status: 'archived', withParent: scopeId });
6807
+ }
6808
+ await this.recordAdmin(actor, 'archiveScope', { tenantId, scopeId, vertical: before.vertical }, { status: before.status }, { status: 'archived' });
6809
+ for (const child of before.children)
6810
+ await this.deliverLifecycles(actor, { scopeId: child.scopeId });
6811
+ await this.deliverLifecycles(actor, { scopeId });
6812
+ },
6601
6813
  unarchiveScope: async (actor, tenantId, scopeId) => {
6602
6814
  // An archived scope is outside `fanOut`'s status filter (#1386), so every
6603
6815
  // tenant-level revoke that landed while it sat archived never reached its local
@@ -6655,6 +6867,14 @@ export class CloudflareScopeHost {
6655
6867
  throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound[0].hostname}' — ` +
6656
6868
  `unbind it before reaping (reap wipes storage and cannot be undone)`);
6657
6869
  }
6870
+ // #2995: a child does not outlive its parent, and a hosted child's bytes live in its vertical's
6871
+ // deployment, which this host does not reach: whoever reaps the parent reaps each child first,
6872
+ // through the same sequence (`reapChildrenFirst` in control-plane-api). Refused before anything
6873
+ // is wiped; the directory refuses the flip too, in its own unit.
6874
+ const unreaped = await this.cp.childScopeIds(tenantId, scopeId, ['provisioning', 'active', 'suspended', 'archived']);
6875
+ if (unreaped.length > 0) {
6876
+ throw substratError('conflict', `scope ${scopeId} holds ${unreaped.length} child scope(s) not reaped (${unreaped.join(', ')}): a child is reaped before its parent`);
6877
+ }
6658
6878
  await this.wipeScopeStores(tenantId, scopeId);
6659
6879
  await this.scopeStub(scopeId).destroyStorage();
6660
6880
  // The recoverable copy the caller stored first (#493), named in the audit entry so
@@ -6793,6 +7013,20 @@ export class CloudflareScopeHost {
6793
7013
  return receipt;
6794
7014
  },
6795
7015
  scopeErasureEpoch: async (_actor, tenantId, scopeId) => this.cp.scopeErasureEpoch(tenantId, scopeId),
7016
+ recordDependentErasures: async (actor, tenantId, subjectId, outcomes) => {
7017
+ if (outcomes.length === 0)
7018
+ return;
7019
+ await this.cp.recordDependentErasures(tenantId, subjectId, outcomes, this.adminEntry(actor, 'eraseAtDependents', { tenantId }, null, { subjectId, dependents: outcomes }));
7020
+ },
7021
+ dueDependentErasures: async (actor, now, limit) => {
7022
+ const owed = await this.cp.dueDependentErasures(now, limit);
7023
+ await this.recordAccess(actor, 'dueDependentErasures', { tenantId: null }, { now, limit }, owed.length);
7024
+ return owed;
7025
+ },
7026
+ holdDependentErasures: async (_actor, tenantId, subjectId, dependents) => {
7027
+ if (dependents.length > 0)
7028
+ await this.cp.holdDependentErasures(tenantId, subjectId, dependents);
7029
+ },
6796
7030
  finalizeSubjectShred: async (actor, tenantId, scopeId, subjectId, redactions, expected, storeErasures = []) => {
6797
7031
  await this.assertScope(tenantId, scopeId);
6798
7032
  if (redactions.length === 0)
@@ -7018,7 +7252,7 @@ export class CloudflareScopeHost {
7018
7252
  // here could never be removed.
7019
7253
  },
7020
7254
  connectionSealingKey: async (id) => this.ensureSealingKey(id),
7021
- connectionSealingKeys: async (tenantId, vertical) => {
7255
+ connectionSealingKeys: async (tenantId, vertical, scopeId) => {
7022
7256
  // LIVE connections only. A revoked connection's key is KEPT (its pending
7023
7257
  // ciphertext must still open) but stops being projected, so a scope can no
7024
7258
  // longer seal to a credential that has been withdrawn. Tenant-owned only (#2732): a
@@ -7027,7 +7261,23 @@ export class CloudflareScopeHost {
7027
7261
  const out = [];
7028
7262
  for (const r of rows)
7029
7263
  out.push(await this.ensureSealingKey(r.id));
7030
- return out;
7264
+ if (!scopeId)
7265
+ return out;
7266
+ // #3530 step 6: the scope of an environment given connections of its own seals to its own
7267
+ // connection of a provider in place of the tenant's (`sealingKeysForReach`), the oldest per provider.
7268
+ const reach = connectionReachSchema.parse(await this.cp.connectionReach(tenantId, scopeId));
7269
+ if (reach !== 'own')
7270
+ return out;
7271
+ const owned = (await this.cp.listConnections({ tenantId, vertical, ownerScopeId: scopeId })).sort((a, b) => String(a.created_at).localeCompare(String(b.created_at)));
7272
+ const seen = new Set();
7273
+ const own = [];
7274
+ for (const r of owned) {
7275
+ if (seen.has(r.provider))
7276
+ continue;
7277
+ seen.add(r.provider);
7278
+ own.push(await this.ensureSealingKey(r.id));
7279
+ }
7280
+ return sealingKeysForReach(reach, out, own);
7031
7281
  },
7032
7282
  listConnections: async (actor, filter) => {
7033
7283
  const f = filter ?? {};
@@ -7683,7 +7933,9 @@ export class CloudflareScopeHost {
7683
7933
  */
7684
7934
  async validateScopeAccess(tenantId, scopeId,
7685
7935
  /** The host method the call came through, named in `tenantUnrecordedRefusedLine` only. */
7686
- door) {
7936
+ door,
7937
+ /** #2995: filled, on a CP-less host, with the scope's type and parent as its storage holds them. */
7938
+ held) {
7687
7939
  const refusal = await this.cp.scopeAccessRefusal(tenantId, scopeId);
7688
7940
  if (refusal) {
7689
7941
  throw refusal.code
@@ -7692,7 +7944,11 @@ export class CloudflareScopeHost {
7692
7944
  }
7693
7945
  if (!this.cpLess)
7694
7946
  return null;
7695
- const { verdict, lifecycle } = await this.scopeStub(scopeId).admission(tenantId);
7947
+ const { verdict, lifecycle, type, parent } = await this.scopeStub(scopeId).admission(tenantId);
7948
+ if (held) {
7949
+ held.type = type;
7950
+ held.parent = parent;
7951
+ }
7696
7952
  // #2035: a scope with no tenant record and no role rows has nothing to hold the pair against, so
7697
7953
  // it is refused like a foreign one. The platform's paths record the tenant without passing this
7698
7954
  // door — a provision or reconcile (every push runs one, #1172), a restore or snapshot, a
@@ -7719,8 +7975,8 @@ export class CloudflareScopeHost {
7719
7975
  * The admin and diagnostic reads (dead letters, job runs, platform requests, delivered
7720
7976
  * grants) keep `validateScopeAccess` alone: an operator still reads a suspended scope.
7721
7977
  */
7722
- async assertLive(tenantId, scopeId, door) {
7723
- const refusal = lifecycleRefusal(await this.validateScopeAccess(tenantId, scopeId, door), { tenantId, scopeId });
7978
+ async assertLive(tenantId, scopeId, door, held) {
7979
+ const refusal = lifecycleRefusal(await this.validateScopeAccess(tenantId, scopeId, door, held), { tenantId, scopeId });
7724
7980
  if (refusal)
7725
7981
  throw substratError('conflict', refusal, { reason: SCOPE_GATE_REASONS.notActive });
7726
7982
  }
@@ -7738,12 +7994,19 @@ export class CloudflareScopeHost {
7738
7994
  * again: on the next pass after the first failure, then backing off (#3119), so a scope that can
7739
7995
  * never be delivered to is not asked every pass for good. Only news is an ops-failure row — the
7740
7996
  * first failure against a receipt and a deployment, or another error than the last.
7997
+ *
7998
+ * K-69 (#3540): with a `lifecycleRetryOwner`, that retry is the owner's. A failed delivery is
7999
+ * handed over as it fails, and the heal sweep hands over, undelivered, the scopes it finds owed one.
8000
+ * `retry` is the owner's own run: only a scope owed a retry, delivered even when the receipt says
8001
+ * nothing changed (a failure is owed whatever the receipt), and never handed over again.
7741
8002
  */
7742
8003
  async deliverLifecycles(actor, filter) {
7743
8004
  const report = { attempted: 0, delivered: 0, failed: 0 };
7744
8005
  const delegation = this.lifecycleDelegation;
7745
8006
  if (!delegation || this.cpLess)
7746
8007
  return report;
8008
+ const owner = filter.retry ? undefined : this.lifecycleRetryOwner;
8009
+ const handOver = [];
7747
8010
  let targets;
7748
8011
  // #2016: the heal also asks the served scopes whose deployment has not answered that it holds a
7749
8012
  // record of the scope's tenant, a copy as much as a primary (no push reconciles a copy), until
@@ -7772,6 +8035,14 @@ export class CloudflareScopeHost {
7772
8035
  for (const first of targets) {
7773
8036
  const tenantId = first.tenant_id;
7774
8037
  const scopeId = first.scope_id;
8038
+ if (filter.retry && first.retry_at === null)
8039
+ continue;
8040
+ // K-69 (#3540): the sweep's check. A scope owed a retry is its owner's, at once: the directory
8041
+ // only lists one whose back-off is over, or whose receipt or deployment moved since.
8042
+ if (filter.drift && owner && first.retry_at !== null) {
8043
+ handOver.push({ tenantId, scopeId, dueAt: Date.now() });
8044
+ continue;
8045
+ }
7775
8046
  let t = first;
7776
8047
  let lifecycle = this.lifecycleOfTarget(t);
7777
8048
  if (!lifecycle) {
@@ -7786,7 +8057,8 @@ export class CloudflareScopeHost {
7786
8057
  // deployment carries the route, from posting a delivery that changes nothing. After a
7787
8058
  // restore (epoch > 0) no receipt says nothing about what the deployment holds, so it is
7788
8059
  // delivered. A HOLD is always delivered, and so is a scope the heal asks for its tenant record.
7789
- if (!askTenant.has(scopeId) &&
8060
+ if (!filter.retry &&
8061
+ !askTenant.has(scopeId) &&
7790
8062
  lifecycleRefusal(lifecycle) === null &&
7791
8063
  (t.delivered === null ? t.epoch === 0 : t.delivered === lifecycleReceipt(lifecycle))) {
7792
8064
  continue;
@@ -7854,14 +8126,19 @@ export class CloudflareScopeHost {
7854
8126
  const text = err instanceof Error ? err.message : String(err);
7855
8127
  // #3119: a repeat of the last failure is counted, not filed. If the count cannot be kept,
7856
8128
  // the row is filed: a missed failure is worse than a repeated one.
7857
- const news = await this.cp
8129
+ const counted = await this.cp
7858
8130
  .recordLifecycleFailure(scopeId, lifecycleReceipt(lifecycle), t.deployment, text, new Date().toISOString())
7859
- .then((f) => f.news)
7860
8131
  .catch((e) => {
7861
8132
  console.error('substrat: could not count a lifecycle delivery failure (#3119)', e);
7862
- return true;
8133
+ return null;
7863
8134
  });
7864
- if (!news)
8135
+ // K-69 (#3540): the failure is the event that makes its retry due on the owner, a minute on
8136
+ // or at the end of the directory's back-off, whichever is later.
8137
+ if (owner) {
8138
+ const retryAt = counted ? Date.parse(counted.retryAt) : 0;
8139
+ handOver.push({ tenantId, scopeId, dueAt: Math.max(retryAt, Date.now() + LIFECYCLE_RETRY_FIRST_LOOK_MS) });
8140
+ }
8141
+ if (counted && !counted.news)
7865
8142
  continue;
7866
8143
  try {
7867
8144
  // #2554: the throw is the deployment's or its runtime's text, and the deployment serving
@@ -7875,6 +8152,16 @@ export class CloudflareScopeHost {
7875
8152
  }
7876
8153
  }
7877
8154
  }
8155
+ if (owner && handOver.length > 0) {
8156
+ try {
8157
+ await owner.handOver(handOver);
8158
+ report.handedOver = handOver.length;
8159
+ }
8160
+ catch (err) {
8161
+ // Never thrown, like a failed delivery: the failure row stays, and the next sweep hands it over again.
8162
+ console.error('substrat: could not hand lifecycle retries to their owner (#3540)', { scopes: handOver.length, err });
8163
+ }
8164
+ }
7878
8165
  return report;
7879
8166
  }
7880
8167
  /** One directory row as the lifecycle a delivery carries (#1713), or null for a status this code does not know. */
@@ -7896,6 +8183,27 @@ export class CloudflareScopeHost {
7896
8183
  async healLifecycles(actor, opts) {
7897
8184
  return this.deliverLifecycles(actor, { drift: true, limit: opts?.limit ?? 200 });
7898
8185
  }
8186
+ /**
8187
+ * K-69 (#3540): one retry of a scope's failed lifecycle delivery, for its `lifecycleRetryOwner`.
8188
+ * Re-reads the directory and delivers only when the scope is still owed a retry (a later
8189
+ * transition that landed owes none), with the delivery's own epoch handling and failure count.
8190
+ * Answers when to look again (epoch ms), or null when nothing more is owed. Throws only when the
8191
+ * directory cannot be read, so the owner keeps the retry.
8192
+ */
8193
+ async retryLifecycle(actor, tenantId, scopeId) {
8194
+ const [owed] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8195
+ if (!owed || owed.retry_at === null)
8196
+ return null;
8197
+ const report = await this.deliverLifecycles(actor, { tenantId, scopeId, retry: true });
8198
+ if (report.failed === 0)
8199
+ return null;
8200
+ // A failure the directory did not count (a foreign epoch, a status this code cannot read) is
8201
+ // not a retry: the sweep delivers that scope itself, as it did before.
8202
+ const [after] = await this.cp.lifecycleTargets({ tenantId, scopeId });
8203
+ if (!after || after.retry_at === null)
8204
+ return null;
8205
+ return Math.max(Date.parse(after.retry_at), Date.now() + LIFECYCLE_RETRY_FIRST_LOOK_MS);
8206
+ }
7899
8207
  /**
7900
8208
  * Whether a CP-less host holds this scope's work (#1713): `assertLive`'s predicate, answered
7901
8209
  * rather than thrown, for the entry points that defer instead of refusing — a sweep pass, a
@@ -8579,10 +8887,10 @@ export class CloudflareScopeHost {
8579
8887
  * this scope a write channel into a credential it may not reach. `[]` for a scope
8580
8888
  * bound to no vertical — which then seals to nothing, the fail-closed direction.
8581
8889
  */
8582
- async connectionKeyRows(tenantId, vertical) {
8890
+ async connectionKeyRows(tenantId, vertical, scopeId) {
8583
8891
  if (!vertical)
8584
8892
  return [];
8585
- const keys = await this.admin.connectionSealingKeys(tenantId, vertical);
8893
+ const keys = await this.admin.connectionSealingKeys(tenantId, vertical, scopeId);
8586
8894
  return keys.map((k) => ({
8587
8895
  connection_id: k.connectionId,
8588
8896
  provider: k.provider,
@@ -8602,7 +8910,7 @@ export class CloudflareScopeHost {
8602
8910
  if (!scope)
8603
8911
  throw unknownScopeForTenant(tenantId, scopeId);
8604
8912
  const { roles, tuples, entitlements, identities } = await this.tenantProjection(tenantId);
8605
- const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical);
8913
+ const connectionKeys = await this.connectionKeyRows(tenantId, scope.vertical, scopeId);
8606
8914
  unwrapReply(await this.scopeStub(scopeId).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, connectionKeys));
8607
8915
  }
8608
8916
  /**
@@ -8649,10 +8957,14 @@ export class CloudflareScopeHost {
8649
8957
  // revoke for the tenant's healthy ones. The failure is still loud, after the rest have landed.
8650
8958
  const settled = await Promise.allSettled(scopes.map(async (s) => {
8651
8959
  const vertical = s.vertical ?? '';
8652
- if (!keysByVertical.has(vertical)) {
8653
- keysByVertical.set(vertical, this.connectionKeyRows(tenantId, s.vertical));
8960
+ // #3530 step 6: a scope that is no install may be a named environment's, given connections of
8961
+ // its own, which seals to those: asked for itself, never shared with the vertical's installs.
8962
+ const primary = isPrimaryScopeRow(s);
8963
+ const memo = primary ? vertical : `${vertical}\u0000${s.scope_id}`;
8964
+ if (!keysByVertical.has(memo)) {
8965
+ keysByVertical.set(memo, this.connectionKeyRows(tenantId, s.vertical, primary ? undefined : s.scope_id));
8654
8966
  }
8655
- unwrapReply(await this.scopeStub(s.scope_id).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, await keysByVertical.get(vertical)));
8967
+ unwrapReply(await this.scopeStub(s.scope_id).applyProjectionReply(tenantId, roles, tuples, entitlements, undefined, identities, await keysByVertical.get(memo)));
8656
8968
  }));
8657
8969
  const failed = settled.flatMap((r, i) => (r.status === 'rejected' ? [{ scope: scopes[i].scope_id, reason: r.reason }] : []));
8658
8970
  if (failed.length === 0)
@@ -8686,6 +8998,11 @@ export class CloudflareScopeHost {
8686
8998
  // #2993 part 3: first, before anything can migrate the scope: its first pass must lay down only
8687
8999
  // its type's tables. A refused type writes nothing. A host and a call that name no type ask nothing.
8688
9000
  const scopeType = await this.scopeTypeAt(input.scopeId, input.scopeType);
9001
+ // #2995: then its parent, also before anything migrates. Judged against the store, which holds the
9002
+ // link the first provision fixed; whether the parent may hold this child is the directory's call.
9003
+ const parentScopeId = input.parentScopeId === undefined
9004
+ ? undefined
9005
+ : unwrapReply(await this.scopeStub(input.scopeId).fixScopeParentReply(input.parentScopeId, input.scopeId));
8689
9006
  // #2430: refused before anything is written, rather than at the top-up after the projection.
8690
9007
  if (input.entityGrants)
8691
9008
  await this.refuseReservedShapes(input.entityGrants, input.scopeId);
@@ -8769,6 +9086,7 @@ export class CloudflareScopeHost {
8769
9086
  : null;
8770
9087
  return {
8771
9088
  ...(input.scopeType !== undefined ? { scopeType } : {}),
9089
+ ...(typeof parentScopeId === 'string' ? { parentScopeId } : {}),
8772
9090
  ...(carry ? { switchedOff } : {}),
8773
9091
  ...(shapes ? { retirementsLeftOpen: shapes.retirementsLeftOpen ?? 0 } : {}),
8774
9092
  ...(shapes?.boundEver ? { boundShapeTypes: shapes.boundEver } : {}),
@@ -8880,10 +9198,11 @@ export class CloudflareScopeHost {
8880
9198
  * judge its roles by. Null on a host that does not project permissions into its scopes: there the
8881
9199
  * load only keeps the destination's permission flags.
8882
9200
  */
8883
- async loadProjectionFor(tenantId, vertical) {
9201
+ async loadProjectionFor(tenantId, vertical, scopeId) {
8884
9202
  if (!this.scopeLocalPermissions)
8885
9203
  return null;
8886
- const [state, connectionKeys] = await Promise.all([this.tenantProjection(tenantId), this.connectionKeyRows(tenantId, vertical)]);
9204
+ // #3530 step 6: the keys the scope itself seals to, its own where it is an environment given its own.
9205
+ const [state, connectionKeys] = await Promise.all([this.tenantProjection(tenantId), this.connectionKeyRows(tenantId, vertical, scopeId)]);
8887
9206
  return { tenantId, ...state, connectionKeys, judge: this.roleJudge() };
8888
9207
  }
8889
9208
  /**
@@ -8951,7 +9270,7 @@ export class CloudflareScopeHost {
8951
9270
  */
8952
9271
  async convergeLoadedProjection(tenantId, scopeId, vertical, loaded, verb) {
8953
9272
  try {
8954
- const now = await this.loadProjectionFor(tenantId, vertical);
9273
+ const now = await this.loadProjectionFor(tenantId, vertical, scopeId);
8955
9274
  if (!now || projectionDigest(now) === projectionDigest(loaded))
8956
9275
  return {};
8957
9276
  unwrapReply(await this.scopeStub(scopeId).applyJudgedProjectionReply(this.roleJudge(), tenantId, now.roles, now.tuples, now.entitlements, undefined, now.identities, now.connectionKeys));