@substrat-run/adapter-cloudflare 0.220.0 → 0.222.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/broker-telemetry.d.ts +2 -5
  2. package/dist/broker-telemetry.d.ts.map +1 -1
  3. package/dist/broker-telemetry.js +2 -5
  4. package/dist/broker-telemetry.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +280 -65
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +737 -245
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +3 -2
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +10 -4
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-handoff.d.ts +17 -1
  14. package/dist/delivery-handoff.d.ts.map +1 -1
  15. package/dist/delivery-handoff.js +19 -5
  16. package/dist/delivery-handoff.js.map +1 -1
  17. package/dist/directory-cutover.d.ts +243 -0
  18. package/dist/directory-cutover.d.ts.map +1 -0
  19. package/dist/directory-cutover.js +604 -0
  20. package/dist/directory-cutover.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +19 -1
  22. package/dist/directory-mirror-apply.d.ts.map +1 -1
  23. package/dist/directory-mirror-apply.js +19 -3
  24. package/dist/directory-mirror-apply.js.map +1 -1
  25. package/dist/directory-mirror-backfill.d.ts +2 -0
  26. package/dist/directory-mirror-backfill.d.ts.map +1 -1
  27. package/dist/directory-mirror-backfill.js +6 -4
  28. package/dist/directory-mirror-backfill.js.map +1 -1
  29. package/dist/directory-mirror.d.ts +24 -0
  30. package/dist/directory-mirror.d.ts.map +1 -1
  31. package/dist/directory-mirror.js +16 -2
  32. package/dist/directory-mirror.js.map +1 -1
  33. package/dist/directory-objects.d.ts +40 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +134 -2
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts.map +1 -1
  38. package/dist/directory-placement.js +9 -1
  39. package/dist/directory-placement.js.map +1 -1
  40. package/dist/directory-split-inventory.d.ts +5 -3
  41. package/dist/directory-split-inventory.d.ts.map +1 -1
  42. package/dist/directory-split-inventory.js +13 -6
  43. package/dist/directory-split-inventory.js.map +1 -1
  44. package/dist/directory-tenant-orgs.d.ts +19 -0
  45. package/dist/directory-tenant-orgs.d.ts.map +1 -0
  46. package/dist/directory-tenant-orgs.js +33 -0
  47. package/dist/directory-tenant-orgs.js.map +1 -0
  48. package/dist/directory-tenant-roles.d.ts +35 -0
  49. package/dist/directory-tenant-roles.d.ts.map +1 -0
  50. package/dist/directory-tenant-roles.js +78 -0
  51. package/dist/directory-tenant-roles.js.map +1 -0
  52. package/dist/directory-tenant-tuples.d.ts +165 -0
  53. package/dist/directory-tenant-tuples.d.ts.map +1 -0
  54. package/dist/directory-tenant-tuples.js +197 -0
  55. package/dist/directory-tenant-tuples.js.map +1 -0
  56. package/dist/host.d.ts +65 -3
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/host.js +422 -64
  59. package/dist/host.js.map +1 -1
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +1 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/platform-sweeper-do.d.ts +1 -1
  65. package/dist/platform-sweeper-do.js +1 -1
  66. package/dist/route-read-model-publisher.d.ts +6 -1
  67. package/dist/route-read-model-publisher.d.ts.map +1 -1
  68. package/dist/route-read-model-publisher.js +51 -13
  69. package/dist/route-read-model-publisher.js.map +1 -1
  70. package/dist/scope-do.d.ts +28 -2
  71. package/dist/scope-do.d.ts.map +1 -1
  72. package/dist/scope-do.js +398 -68
  73. package/dist/scope-do.js.map +1 -1
  74. package/dist/scope-sweeper-do.d.ts +28 -0
  75. package/dist/scope-sweeper-do.d.ts.map +1 -1
  76. package/dist/scope-sweeper-do.js +88 -50
  77. package/dist/scope-sweeper-do.js.map +1 -1
  78. package/dist/scope-wake.d.ts +12 -1
  79. package/dist/scope-wake.d.ts.map +1 -1
  80. package/dist/scope-wake.js +14 -1
  81. package/dist/scope-wake.js.map +1 -1
  82. package/dist/scope-work.d.ts +1 -1
  83. package/dist/scope-work.js +1 -1
  84. package/dist/scope-work.js.map +1 -1
  85. package/dist/tenant-due-work-do.d.ts +95 -0
  86. package/dist/tenant-due-work-do.d.ts.map +1 -0
  87. package/dist/tenant-due-work-do.js +149 -0
  88. package/dist/tenant-due-work-do.js.map +1 -0
  89. package/package.json +10 -10
package/dist/host.js CHANGED
@@ -2,18 +2,22 @@ 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, 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 { 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
6
  import { normalizeHostname, toRouteTarget } from './route-resolver.js';
7
7
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
8
- import { breakingWithinMajorRefusal, earlierMajorsOf, releaseWithinMajorRefusal } from '@substrat-run/kernel';
8
+ import { breakingWithinMajorRefusal, earlierMajorReleaseTarget, earlierMajorsOf, releaseWithinMajorRefusal } from '@substrat-run/kernel';
9
9
  import { classify as classifyRelease } from '@substrat-run/model-view/bump';
10
10
  import { ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary } from '@substrat-run/kernel';
11
11
  import { CONNECTOR_DISPATCH_REQUESTED_BY, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
12
- import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, provisionedScopeType, 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';
12
+ import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, provisionedScopeType,
13
+ // #2995: the parent link a provision-child writes, and the doors it decides.
14
+ childDoorRefusal, childScopeRefusal, claimsHome, directAccessRefusal, parentlessScopeRefusal, provisionedParent,
15
+ // #2993 part 3: the modules (and seats) a scope of each declared type has.
16
+ 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';
13
17
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
14
18
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
15
19
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
16
- import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
20
+ import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, proofCheckedStoreInvoke, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
17
21
  import { PLATFORM_BINDING_PREFIX, PLATFORM_STORE_CODE, parseTraceparent, scopeStoreBindingName, scopeStoreObjectName, STORE_CALL_URL, storeAnswerOf, StoreError, TRACEPARENT_HEADER } from '@substrat-run/contracts';
18
22
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
19
23
  import { isOrangeToOrange, isUpgradeRequest, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, liveInstant, encodeLiveWithin, liveRefusalStatus, liveWithinOf, } from './live-reads.js';
@@ -110,20 +114,6 @@ function assertCopyLineage(lineage) {
110
114
  throw substratError('conflict', 'mark-copy refused: the directory classifies this scope as primary, not as a copy');
111
115
  }
112
116
  }
113
- /**
114
- * A control-plane stand-in for a CP-less vertical (scope-local-permissions.md Phase 3).
115
- * The hot path a served scope actually touches becomes trust-the-upstream:
116
- * - `scopeAccessRefusal` / `setMigrationState` → no-op: the router gates the scope's
117
- * lifecycle + tenancy from the shared directory, and the vertical does not re-read a
118
- * directory it does not have. Its own half of both gates reads the scope's storage
119
- * instead (`validateScopeAccess`): the tenant the scope was provisioned for (#2016) and the lifecycle
120
- * the platform delivered (#1713).
121
- * - `tenantHoldsEntitlement` → true: the SKU was enforced on the shared control plane
122
- * at provision (before `provisionInstance`), so a scope that EXISTS here was granted
123
- * it upstream — a single-vertical deployment holds its own entitlements by construction.
124
- * - `recordAdmin` / `recordAccess` → no-op: the shared control plane owns the audit spine.
125
- * Every other method throws — the admin directory surface genuinely is unavailable.
126
- */
127
117
  function nullControlPlane() {
128
118
  const noop = async () => undefined;
129
119
  const passthrough = {
@@ -410,6 +400,11 @@ export class CloudflareScopeHost {
410
400
  declaredKeys = new Set();
411
401
  /** #2430: the declared permission surface `registerModule` holds each module to, when given. */
412
402
  permissions;
403
+ /**
404
+ * #2993 part 3: the modules each declared scope type runs, from `permissions`. Undeclared: one
405
+ * `home` type running every module, and this host neither reads nor asks any scope's type.
406
+ */
407
+ scopeTypePlan;
413
408
  /**
414
409
  * #1705: this deployment's cross-vertical declarations. The DO holds the handlers and makes
415
410
  * every decision. The coordinator keeps its own copy for two reasons: registration refuses
@@ -512,6 +507,7 @@ export class CloudflareScopeHost {
512
507
  constructor(options) {
513
508
  this.servicePrincipals = options.servicePrincipals;
514
509
  this.permissions = options.permissions;
510
+ this.scopeTypePlan = scopeTypePlanOf(options.permissions);
515
511
  // #2430: what the declared surface reserves holds here too, whatever is registered under its ids.
516
512
  for (const m of options.permissions?.modules ?? []) {
517
513
  noteReservedKeys(this.reservedKeys, m.manifest);
@@ -1874,7 +1870,7 @@ export class CloudflareScopeHost {
1874
1870
  this.moduleSchedules.set(manifest.id, manifest.schedules);
1875
1871
  }
1876
1872
  if (manifest.peers && manifest.peers.length > 0) {
1877
- this.peerSources.push({ peers: manifest.peers });
1873
+ this.peerSources.push({ moduleId: manifest.id, peers: manifest.peers });
1878
1874
  }
1879
1875
  if (manifest.freshness && manifest.freshness.length > 0) {
1880
1876
  this.moduleFreshness.set(manifest.id, manifest.freshness);
@@ -1925,13 +1921,88 @@ export class CloudflareScopeHost {
1925
1921
  async provisionScopeCreating(actor, input) {
1926
1922
  // Shared with the pure adapter so the defaults cannot drift between them.
1927
1923
  const record = resolveScopeRecord(input);
1928
- // #2993: this host runs no declared scope types yet, so it takes 'home' and refuses any
1929
- // other type, by the kernel's rule, before anything is written. A typed scope provisioned
1930
- // here as 'home' would carry the wrong modules for its life.
1931
- provisionedScopeType({ declared: false }, input.scopeType, undefined, input.scopeId);
1924
+ // #2993: the type this provision gives the scope, by the kernel's rule, before anything is
1925
+ // written: an undeclared type, or one other than the type the directory records, is refused.
1926
+ // A host with no declared types reads nothing for it and takes 'home'. Part 4: a module-less
1927
+ // coordinator asked for another type of a vertical's scope judges it by the types the
1928
+ // vertical's deployed version declares (`verticalScopeTypePlan`); asked for none, or for
1929
+ // 'home', it reads nothing, as before.
1930
+ const own = this.scopeTypePlan;
1931
+ const plan = !own.declared && input.scopeType !== undefined && input.scopeType !== HOME_SCOPE_TYPE && record.vertical
1932
+ ? await this.verticalScopeTypePlan(record.vertical)
1933
+ : own;
1934
+ const typed = plan.declared;
1935
+ // #2995: a provision naming a parent reads the row too, for the link it may already hold.
1936
+ const recorded = typed || input.parentScopeId !== undefined ? await this.cp.getScopeRecord(input.tenantId, input.scopeId) : undefined;
1937
+ const scopeType = provisionedScopeType(plan, input.scopeType, recorded === undefined ? undefined : (recorded.scope_type ?? null), input.scopeId);
1938
+ // #2995 (K-64): the parent link, judged before anything is written. A new child is held to its
1939
+ // parent's declared children, tenant, app, state and depth (`childScopeRefusal`); the directory
1940
+ // judges the parent's state and the link's fixedness again in the write's own unit, so an archive
1941
+ // of the parent landing between the two is refused there. Then (the owner's word on #3604's
1942
+ // fourth question) a new scope of a type other than home has a parent, unless it is a copy.
1943
+ const namedParent = recorded === undefined && input.parentScopeId === undefined
1944
+ ? null
1945
+ : provisionedParent(input.parentScopeId, recorded === undefined ? undefined : (recorded.parent_scope_id ?? null), input.scopeId);
1946
+ // #3625 (K-64): a new typed scope that names no parent is a child of its app's home scope, judged
1947
+ // below as any named parent is. Only where this host runs the scope's modules (`own.declared`) and so
1948
+ // fixes the link on the scope's own object itself: a module-less coordinator's vertical learns a link
1949
+ // from `/internal/provision`, which `provision-child` alone sends, so there it is named that way.
1950
+ const parentScopeId = recorded === undefined && namedParent === null && own.declared &&
1951
+ scopeType !== HOME_SCOPE_TYPE && record.forkedFrom === null && record.vertical !== null
1952
+ ? (await this.cp.homeScopeOf(input.tenantId, record.vertical))
1953
+ : namedParent;
1954
+ if (recorded === undefined) {
1955
+ if (parentScopeId !== null) {
1956
+ const parent = await this.cp.getScopeRecord(input.tenantId, parentScopeId);
1957
+ const refusal = childScopeRefusal(plan, parentScopeId, parent && {
1958
+ tenantId: parent.tenant_id,
1959
+ status: parent.status,
1960
+ vertical: parent.vertical,
1961
+ type: parent.scope_type ?? HOME_SCOPE_TYPE,
1962
+ parentScopeId: parent.parent_scope_id ?? null,
1963
+ forkedFrom: parent.forked_from ?? null,
1964
+ }, { tenantId: input.tenantId, vertical: record.vertical, type: scopeType });
1965
+ if (refusal)
1966
+ throw refusal;
1967
+ }
1968
+ const parentless = parentlessScopeRefusal(scopeType, parentScopeId, record.forkedFrom, input.scopeId);
1969
+ if (parentless)
1970
+ throw parentless;
1971
+ }
1932
1972
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1933
1973
  // or audit, so a rejected provision creates nothing and writes no audit row.
1934
- const created = await this.directory('provisionScope', input.tenantId, input.scopeId, record, new Date().toISOString());
1974
+ const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
1975
+ // #2993: the directory row records the type ('home' as NULL), and refuses a different one in
1976
+ // its own unit. An untyped host sends none and writes the row it always did.
1977
+ {
1978
+ ...(typed ? { ...record, scopeType: scopeType === HOME_SCOPE_TYPE ? null : scopeType } : record),
1979
+ // #2995: the link as the caller named it; the directory fixes it against its row. #3625: or the
1980
+ // home scope a typed scope's parent defaulted to above.
1981
+ ...(input.parentScopeId !== undefined
1982
+ ? { parentScopeId: input.parentScopeId }
1983
+ : recorded === undefined && parentScopeId !== null ? { parentScopeId } : {}),
1984
+ // #3625 (K-64): an install, which the directory refuses in its own unit while the app has a home
1985
+ // scope in the tenant (`secondHomeRefusal`). Sent only when true, so a write without it is judged
1986
+ // as before.
1987
+ ...(claimsHome({
1988
+ vertical: record.vertical,
1989
+ type: scopeType,
1990
+ parentScopeId,
1991
+ forkedFrom: record.forkedFrom,
1992
+ kind: record.kind,
1993
+ install: input.install,
1994
+ }) ? { claimsHome: true } : {}),
1995
+ }, new Date().toISOString());
1996
+ // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1997
+ // first pass lays down only its type's tables. A host with no declared types asks nothing. A
1998
+ // coordinator judging by a vertical's types (part 4) does not either: the vertical's own
1999
+ // object is fixed by its `/internal/provision`, which the platform sends the type.
2000
+ if (own.declared)
2001
+ unwrapReply(await this.scopeStub(input.scopeId).fixScopeTypeReply(scopeType, input.scopeId));
2002
+ // #2995: and its parent, so a door of this host's own namespace judges a child as the directory does.
2003
+ if (own.declared && parentScopeId !== null) {
2004
+ unwrapReply(await this.scopeStub(input.scopeId).fixScopeParentReply(parentScopeId, input.scopeId));
2005
+ }
1935
2006
  // Instantiate the scope DO and trigger its lazy migration.
1936
2007
  await this.migrateAndRecord(input.scopeId);
1937
2008
  // Scope-local permissions: a freshly-provisioned scope evaluates from its own
@@ -1949,6 +2020,9 @@ export class CloudflareScopeHost {
1949
2020
  // (`grantToSystem` still clears a tuple's tombstone, but it does not move the switch.)
1950
2021
  const seats = [];
1951
2022
  for (const [moduleId, schedules] of this.moduleSchedules) {
2023
+ // #2993 part 3: only the modules this scope's type runs seat their schedules' grants.
2024
+ if (!scopeTypeRuns(this.scopeTypePlan, scopeType, moduleId))
2025
+ continue;
1952
2026
  const perms = new Set();
1953
2027
  for (const s of schedules)
1954
2028
  for (const p of s.permissions)
@@ -1961,7 +2035,7 @@ export class CloudflareScopeHost {
1961
2035
  // call (`peerSeats`) that makes "declared and installed" mean "live". Same seat as the
1962
2036
  // schedule grants above, so a grant a switch tombstoned stays tombstoned and a
1963
2037
  // switched-off peer gets nothing seated.
1964
- for (const seat of peerSeats(collectPeers(this.peerSources), input.scopeId)) {
2038
+ for (const seat of peerSeats(collectPeers(this.peerSourcesOf(scopeType)), input.scopeId)) {
1965
2039
  seats.push({ subject: seat.subject, relation: seat.relation, object: seat.object, expires_at: null });
1966
2040
  }
1967
2041
  // #1674: re-assert the recorded OFF positions after the seat (`system-switch-record.ts`).
@@ -1980,10 +2054,48 @@ export class CloudflareScopeHost {
1980
2054
  }
1981
2055
  // Audit a real provision only; an idempotent re-provision changed nothing.
1982
2056
  if (created) {
1983
- await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null, record);
2057
+ await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2058
+ // #2993: a typed scope's audit row names its type, as on the pure host; a home scope's reads as it always did.
2059
+ // #2995: a child's names its parent.
2060
+ {
2061
+ ...record,
2062
+ ...(scopeType === HOME_SCOPE_TYPE ? {} : { scopeType }),
2063
+ ...(parentScopeId === null ? {} : { parentScopeId }),
2064
+ });
1984
2065
  }
1985
2066
  return created;
1986
2067
  }
2068
+ /**
2069
+ * #2993 part 4: a vertical's scope types, as the version a new scope of it would run declares
2070
+ * them: the version its serving script serves, else the one its `prod` channel names. Read from
2071
+ * the stored manifest, unaudited, for the reason {@link versionImports} is. A vertical with no
2072
+ * such version, or one that declares no types, has the one `home` type.
2073
+ */
2074
+ async verticalScopeTypePlan(slug) {
2075
+ const vertical = await this.cp.readVertical(slug);
2076
+ const versionId = vertical?.serving_version_id ?? (await this.cp.readChannel(slug, 'prod'))?.version_id;
2077
+ const version = versionId ? await this.cp.readVersion(versionId) : undefined;
2078
+ return scopeTypePlanOfManifest(version?.manifest_json);
2079
+ }
2080
+ /** #2993 part 3: the peer declarations of the modules a scope of `scopeType` runs. */
2081
+ peerSourcesOf(scopeType) {
2082
+ return this.scopeTypePlan.declared
2083
+ ? this.peerSources.filter((p) => scopeTypeRuns(this.scopeTypePlan, scopeType, p.moduleId))
2084
+ : this.peerSources;
2085
+ }
2086
+ /**
2087
+ * #2993 part 3: the scope's type as its own object holds it, fixing it when `requested` names one.
2088
+ * Asked only when it can matter: this host declares types, or the caller named one (the object
2089
+ * judges that by its class's own declaration). Otherwise 'home', with no call, as before types.
2090
+ */
2091
+ async scopeTypeAt(scopeId, requested) {
2092
+ if (!this.scopeTypePlan.declared && requested === undefined)
2093
+ return HOME_SCOPE_TYPE;
2094
+ const stub = this.scopeStub(scopeId);
2095
+ return requested === undefined && this.scopeTypePlan.declared
2096
+ ? stub.scopeTypeHere()
2097
+ : unwrapReply(await stub.fixScopeTypeReply(requested, scopeId));
2098
+ }
1987
2099
  // Per-tenant relational stores (#301, PR-2 — the live D1 path). The coordinator holds
1988
2100
  // the platform's D1 credential (the same split secretBox uses: the DO records, it never
1989
2101
  // holds a key), the ControlPlaneDO serializes the ledger write, and the D1 REST client
@@ -2386,6 +2498,11 @@ export class CloudflareScopeHost {
2386
2498
  * scope of this host, made at once, so its seats are the ones that scope holds now (K-55).
2387
2499
  */
2388
2500
  async importScopeFrom(actor, input, dump, judge) {
2501
+ // #2995: a copy carries no parent link. A link is written by provision-child alone, so a copy of a
2502
+ // child is a scope of its type with no parent, and nothing reaches it through the source's parent.
2503
+ if (input.parentScopeId !== undefined) {
2504
+ throw substratError('validation_failed', 'a copy carries no parent link: a child is provisioned through provision-child only');
2505
+ }
2389
2506
  this.refuseUnusableScopeStores(dump.stores, input.vertical ?? null);
2390
2507
  if (judge)
2391
2508
  await this.refuseDumpRoles(input.tenantId, null, dump);
@@ -2393,8 +2510,15 @@ export class CloudflareScopeHost {
2393
2510
  // replaces its provisioned schema with the dump wholesale (drop-then-replay), so
2394
2511
  // the end state is the dump, at the source's frontier. Provenance is stamped from
2395
2512
  // the dump unless the caller set it (§3: a fork always records its origin).
2513
+ // #2993 part 3: a copy is a scope of its source's type — the type names the tables the dump
2514
+ // carries. The caller's type when it names one, else the source's, when the directory holds it.
2515
+ const source = input.scopeType === undefined && this.scopeTypePlan.declared
2516
+ ? await this.cp.getScopeRecord(input.tenantId, dump.scopeId)
2517
+ : undefined;
2518
+ const copiedType = input.scopeType ?? (source ? (source.scope_type ?? HOME_SCOPE_TYPE) : undefined);
2396
2519
  const created = await this.provisionScopeCreating(actor, {
2397
2520
  ...input,
2521
+ ...(copiedType === undefined ? {} : { scopeType: copiedType }),
2398
2522
  forkedFrom: input.forkedFrom ?? dump.scopeId,
2399
2523
  forkedAt: input.forkedAt ?? dump.capturedAt,
2400
2524
  });
@@ -2606,7 +2730,60 @@ export class CloudflareScopeHost {
2606
2730
  const parsedDelegation = parseScopeDelegation(options?.delegation);
2607
2731
  // Lifecycle gates (control-plane.md §4.1/§4.2), the K-3 fail-closed path,
2608
2732
  // evaluated durably in the ControlPlaneDO. A throw propagates here.
2609
- await this.assertLive(tenantId, scopeId, 'getScope');
2733
+ const held = {};
2734
+ await this.assertLive(tenantId, scopeId, 'getScope', held);
2735
+ // #2995: a child whose type accepts its parent only is not reached by a direct request.
2736
+ if (this.scopeTypePlan.declared) {
2737
+ const link = this.cpLess ? held : await this.directoryLinkOf(tenantId, scopeId);
2738
+ const direct = directAccessRefusal(this.scopeTypePlan, link.type ?? HOME_SCOPE_TYPE, link.parent ?? null, scopeId);
2739
+ if (direct)
2740
+ throw direct;
2741
+ }
2742
+ return this.personDoor(principal, tenantId, scopeId, options, parsedDelegation);
2743
+ }
2744
+ /**
2745
+ * `ScopeHost.getChildScope` (#2995, K-64): the person's stub on a child, for host code of its parent,
2746
+ * between two of its own transactions. The link, the child's type and the parent's state are judged
2747
+ * first (`childDoorRefusal`), from the directory, or on a CP-less host from the two scopes' own
2748
+ * storage: the child holds its type and its parent (`fixScopeParentReply`), and the parent the
2749
+ * lifecycle the platform delivered it. A parent this deployment does not hold (a child on another
2750
+ * script) reads as unknown, so the call is refused rather than sent to an empty object. Then the
2751
+ * person's door runs as `getScope` runs it, and every check in the child is the person's own grants.
2752
+ */
2753
+ async getChildScope(caller, tenantId, scopeId, options) {
2754
+ if (caller?.actor?.kind !== 'person') {
2755
+ throw substratError('validation_failed', 'a call into a child acts for a person: the app acting as itself is not built (#2995)');
2756
+ }
2757
+ const parsedDelegation = parseScopeDelegation(options?.delegation);
2758
+ let child;
2759
+ let parent;
2760
+ if (this.cpLess) {
2761
+ const held = (v) => v.verdict === 'recorded' || v.verdict === 'inferred';
2762
+ const c = await this.scopeStub(scopeId).admission(tenantId);
2763
+ const p = await this.scopeStub(caller.parentScopeId).admission(tenantId);
2764
+ child = held(c) ? { tenantId, type: c.type, parentScopeId: c.parent } : undefined;
2765
+ // Nothing delivered yet reads as live, as at every CP-less door; the child's own door below judges the tenant.
2766
+ parent = held(p) ? { tenantId, status: p.lifecycle?.scope ?? 'active' } : undefined;
2767
+ }
2768
+ else {
2769
+ const c = await this.cp.getScopeRecord(tenantId, scopeId);
2770
+ const p = await this.cp.getScopeRecord(tenantId, caller.parentScopeId);
2771
+ child = c && { tenantId: c.tenant_id, type: c.scope_type ?? HOME_SCOPE_TYPE, parentScopeId: c.parent_scope_id ?? null };
2772
+ parent = p && { tenantId: p.tenant_id, status: p.status };
2773
+ }
2774
+ const refusal = childDoorRefusal(this.scopeTypePlan, tenantId, caller.parentScopeId, scopeId, child, parent);
2775
+ if (refusal)
2776
+ throw refusal;
2777
+ await this.assertLive(tenantId, scopeId, 'getChildScope');
2778
+ return this.personDoor(caller.actor.principal, tenantId, scopeId, options, parsedDelegation);
2779
+ }
2780
+ /** #2995: a scope's type and parent as the directory records them. */
2781
+ async directoryLinkOf(tenantId, scopeId) {
2782
+ const rec = await this.cp.getScopeRecord(tenantId, scopeId);
2783
+ return { type: rec?.scope_type ?? HOME_SCOPE_TYPE, parent: rec?.parent_scope_id ?? null };
2784
+ }
2785
+ /** The person's door past the pair, lifecycle and reach checks: migrations, then the stub. */
2786
+ async personDoor(principal, tenantId, scopeId, options, parsedDelegation) {
2610
2787
  await this.migrateAndRecord(scopeId);
2611
2788
  // #3161: a person's call arriving through a peer goes through that peer's door, as
2612
2789
  // `getVerticalScope` opens it (the name `peers` uses, the rewind hold, the pin), and the
@@ -2619,22 +2796,30 @@ export class CloudflareScopeHost {
2619
2796
  }
2620
2797
  return this.buildStub(tenantId, scopeId, principal, undefined, undefined, options, undefined, undefined, undefined, options?.verifiedEmail ?? null, parsedDelegation);
2621
2798
  }
2622
- async getScopeStore(_principal, tenantId, scopeId, binding, options) {
2799
+ async getScopeStore(principal, tenantId, scopeId, binding, options) {
2800
+ // #2996 (K-64): every path spends the proof on the scope's own queue before it sends the call,
2801
+ // whatever the transport. The scope object is in this worker's own namespace on each of them.
2802
+ const redeem = async (secret, operation) => {
2803
+ unwrapReply(await this.scopeStub(scopeId).storeProofRedeemReply(secret, binding, operation, principal));
2804
+ };
2623
2805
  if (this.scopeStoreTransport === 'platform') {
2624
2806
  return {
2625
2807
  tenantId,
2626
2808
  scopeId,
2627
2809
  subjectKind: 'principal',
2628
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore({
2810
+ invoke: proofCheckedStoreInvoke({
2811
+ binding,
2812
+ redeem,
2629
2813
  // The egress hop answers with the platform's own codes too (#2815).
2630
- through: 'platform',
2631
- send: async (request) => {
2814
+ throughPlatform: true,
2815
+ send: async (request, proof) => {
2632
2816
  // #3368: the request's trace, so the call joins it through egress and the router.
2633
2817
  const trace = currentTraceparent();
2634
2818
  const response = await this.fetchImpl(STORE_CALL_URL, {
2635
2819
  method: 'POST',
2636
2820
  headers: { 'content-type': 'application/json', ...(parseTraceparent(trace) ? { [TRACEPARENT_HEADER]: trace } : {}) },
2637
- body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input }),
2821
+ // The spent proof rides along, so the router can refuse a call that did not pass this door.
2822
+ body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input, proof }),
2638
2823
  });
2639
2824
  try {
2640
2825
  return await response.json();
@@ -2643,7 +2828,8 @@ export class CloudflareScopeHost {
2643
2828
  throw new StoreError({ code: PLATFORM_STORE_CODE.badEnvelope, status: 502 });
2644
2829
  }
2645
2830
  },
2646
- }, operation, input, ...extra), options?.onStoreCall),
2831
+ onStoreCall: options?.onStoreCall,
2832
+ }),
2647
2833
  };
2648
2834
  }
2649
2835
  // A missing binding is answered before any directory read. A CP-less host's
@@ -2661,7 +2847,12 @@ export class CloudflareScopeHost {
2661
2847
  tenantId,
2662
2848
  scopeId,
2663
2849
  subjectKind: 'principal',
2664
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore((request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request), operation, input, ...extra), options?.onStoreCall),
2850
+ invoke: proofCheckedStoreInvoke({
2851
+ binding,
2852
+ redeem,
2853
+ send: (request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request),
2854
+ onStoreCall: options?.onStoreCall,
2855
+ }),
2665
2856
  };
2666
2857
  }
2667
2858
  const namespace = bound;
@@ -2671,7 +2862,7 @@ export class CloudflareScopeHost {
2671
2862
  tenantId,
2672
2863
  scopeId,
2673
2864
  subjectKind: 'principal',
2674
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore(storeObjectSend(object), operation, input, ...extra), options?.onStoreCall),
2865
+ invoke: proofCheckedStoreInvoke({ binding, redeem, send: storeObjectSend(object), onStoreCall: options?.onStoreCall }),
2675
2866
  };
2676
2867
  }
2677
2868
  /**
@@ -3563,7 +3754,11 @@ export class CloudflareScopeHost {
3563
3754
  }
3564
3755
  const stub = this.scopeStub(scopeId);
3565
3756
  const windows = new Map();
3566
- for (const specs of this.moduleFreshness.values()) {
3757
+ // #2993 part 3: only the modules this scope's type runs are judged on it.
3758
+ const scopeType = await this.scopeTypeAt(scopeId);
3759
+ for (const [freshnessModule, specs] of this.moduleFreshness) {
3760
+ if (!scopeTypeRuns(this.scopeTypePlan, scopeType, freshnessModule))
3761
+ continue;
3567
3762
  for (const f of specs) {
3568
3763
  const prev = windows.get(f.eventType);
3569
3764
  if (prev === undefined || f.within.hours < prev)
@@ -3655,15 +3850,38 @@ export class CloudflareScopeHost {
3655
3850
  let purgeRequests = 0;
3656
3851
  // #3540: what this call is — the scope's own alarm, which runs only the purges it found due, or a
3657
3852
  // pass, which tells the scope whether its sweeper can take that alarm's call (`purgeMode`).
3658
- const purgeMode = tick?.purgeAlarm ? 'alarm' : tick?.alarmRunsPurges ? 'deferrable' : undefined;
3853
+ // `dueAlarm` is the same alarm, through `runScopeDue`, which also asks for its due schedules.
3854
+ const alarm = tick?.purgeAlarm === true || tick?.dueAlarm === true;
3855
+ const purgeMode = alarm ? 'alarm' : tick?.alarmRunsPurges ? 'deferrable' : undefined;
3659
3856
  for (const schedule of schedules) {
3660
3857
  if (tick?.purgeAlarm && !schedule.purge)
3661
3858
  continue;
3662
- const last = await stub.scheduleLastRun(schedule.operation);
3859
+ // #3540: a `due: 'event'` schedule is the scope's to place — its alarm runs it once it has run
3860
+ // under that form — wherever the caller can take that alarm's call; its cadence decides otherwise.
3861
+ const byEvent = !schedule.purge && schedule.due === 'event';
3862
+ if (tick?.dueAlarm && !schedule.purge && !byEvent)
3863
+ continue;
3864
+ let byDate;
3865
+ let last;
3866
+ if (byEvent && (tick?.dueAlarm || tick?.alarmRunsDue)) {
3867
+ const gate = await stub.dueScheduleGate(schedule.operation, tenantId, scopeId, tick.dueAlarm ? 'alarm' : 'deferrable');
3868
+ if (gate.byAlarm || (tick.dueAlarm && (gate.dueAt === null || now < gate.dueAt))) {
3869
+ // Its alarm runs it, or it is not due by its date: nothing ran, no line, no cadence row.
3870
+ report.skipped += 1;
3871
+ report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3872
+ continue;
3873
+ }
3874
+ if (tick.dueAlarm)
3875
+ byDate = gate.dueAt;
3876
+ last = gate.lastRunAt;
3877
+ }
3878
+ else {
3879
+ last = await stub.scheduleLastRun(schedule.operation);
3880
+ }
3663
3881
  const lastRun = last ? Date.parse(last) : null;
3664
- const dueAt = lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
3882
+ const dueAt = byDate ?? (lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000);
3665
3883
  // #3540: the scope's alarm found the purge due by its rows, so the cadence does not gate it.
3666
- if (now < dueAt && !tick?.purgeAlarm) {
3884
+ if (now < dueAt && !(alarm && schedule.purge)) {
3667
3885
  report.skipped += 1;
3668
3886
  report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3669
3887
  continue;
@@ -3756,8 +3974,8 @@ export class CloudflareScopeHost {
3756
3974
  startedAt,
3757
3975
  outcome: status,
3758
3976
  ...failure,
3759
- dueAt: lastRun === null ? null : new Date(dueAt).toISOString(),
3760
- latenessMs: lastRun === null ? null : now - dueAt,
3977
+ dueAt: byDate === undefined && lastRun === null ? null : new Date(dueAt).toISOString(),
3978
+ latenessMs: byDate === undefined && lastRun === null ? null : now - dueAt,
3761
3979
  ...(emitted ? { emitted } : {}),
3762
3980
  });
3763
3981
  report.runs.push({ operation: schedule.operation, outcome: status === 'ok' ? 'ok' : 'failed' });
@@ -4127,6 +4345,8 @@ export class CloudflareScopeHost {
4127
4345
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
4128
4346
  archivedAt: r.archived_at ?? null,
4129
4347
  archivedFromStatus: (r.archived_from_status ?? null),
4348
+ // #2993: a typed scope names its type; a home scope's record (NULL) is unchanged.
4349
+ ...(r.scope_type ? { scopeType: r.scope_type } : {}),
4130
4350
  createdAt: r.created_at,
4131
4351
  });
4132
4352
  // The directory rows `listScopes` and `listScopesReadable` map, filtered and paged alike.
@@ -4138,6 +4358,7 @@ export class CloudflareScopeHost {
4138
4358
  : [filter.status]
4139
4359
  : undefined,
4140
4360
  vertical: filter?.vertical,
4361
+ ...(filter?.parentScopeId ? { parentScopeId: filter.parentScopeId } : {}),
4141
4362
  limit: filter?.limit,
4142
4363
  cursor: filter?.cursor,
4143
4364
  order: filter?.order,
@@ -5231,6 +5452,12 @@ export class CloudflareScopeHost {
5231
5452
  throw substratError(answer.code, answer.message);
5232
5453
  return { changed: answer.changed, previous: answer.previous };
5233
5454
  },
5455
+ // #3625 (K-64): the home scope of (tenant, app, environment). The rule is the kernel's (`home-scope.ts`).
5456
+ homeScopeOf: async (actor, tenantId, vertical, environment) => {
5457
+ const scopeId = await this.cp.homeScopeOf(tenantId, vertical, environment);
5458
+ await this.recordAccess(actor, 'homeScopeOf', { tenantId }, { vertical, environment: environment ?? 'prod' }, scopeId ? 1 : 0);
5459
+ return scopeId;
5460
+ },
5234
5461
  // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
5235
5462
  listEnvironments: async (actor, tenantId, vertical) => {
5236
5463
  const rows = await this.cp.listEnvironments(tenantId, verticalSlug.parse(vertical));
@@ -5246,6 +5473,25 @@ export class CloudflareScopeHost {
5246
5473
  const vertical = verticalSlug.parse(input.vertical);
5247
5474
  return this.directory('removeEnvironmentAndAudit', { ...input, vertical }, this.adminEntry(actor, 'removeEnvironment', { tenantId: input.tenantId, vertical }, null, null));
5248
5475
  },
5476
+ claimEnvironmentServe: async (_actor, input, claim, leaseMs) => this.directory('claimEnvironmentServe', { ...input, vertical: verticalSlug.parse(input.vertical) }, claim, leaseMs),
5477
+ releaseEnvironmentServe: async (_actor, input, claim) => {
5478
+ await this.cp.releaseEnvironmentServe({ ...input, vertical: verticalSlug.parse(input.vertical) }, claim);
5479
+ },
5480
+ setEnvironmentServing: async (actor, input, next, expected, claim, acknowledge) => {
5481
+ const vertical = verticalSlug.parse(input.vertical);
5482
+ // #3638: parsed here, judged in the directory's write that moves what the environment serves.
5483
+ const ack = acknowledge === undefined ? undefined : environmentServeAcknowledgement.parse(acknowledge);
5484
+ const moved = await this.directory('setEnvironmentServingAndAudit', { ...input, vertical }, next, expected, this.adminEntry(actor, 'setEnvironmentServing', { tenantId: input.tenantId, vertical }, null, null), claim, ack);
5485
+ if (!moved) {
5486
+ throw substratError('precondition_failed', `the environment '${input.name}' of '${vertical}' serves another record than the one this serve was diffed from: read it again`);
5487
+ }
5488
+ },
5489
+ // #3530 step 6: an environment given connections of its own, and the rule every connection door asks.
5490
+ setEnvironmentEffects: async (actor, input, effects) => {
5491
+ const vertical = verticalSlug.parse(input.vertical);
5492
+ return this.directory('setEnvironmentEffectsAndAudit', { ...input, vertical }, environmentEffectsSchema.parse(effects), this.adminEntry(actor, 'setEnvironmentEffects', { tenantId: input.tenantId, vertical }, null, null));
5493
+ },
5494
+ connectionReach: async (_actor, tenantId, scopeId) => connectionReachSchema.parse(await this.cp.connectionReach(tenantId, scopeId)),
5249
5495
  resolveHostname: async (raw) =>
5250
5496
  // The router's per-request read. No actor, not logged — the same machine-path
5251
5497
  // carve-out resolveIdentity has (K-24). Shares its mapping with the router's
@@ -5432,23 +5678,41 @@ export class CloudflareScopeHost {
5432
5678
  if (incoming.admission !== 'admitted') {
5433
5679
  throw substratError('conflict', `version ${versionId} is ${incoming.admission}, not admitted — it cannot be promoted`);
5434
5680
  }
5435
- const current = await this.cp.readChannel(verticalSlug, channel);
5681
+ // K-65 (#3539): a release that names an earlier major goes to that major's own script, and
5682
+ // every gate below is judged against the version that script runs, in place of the channel's.
5683
+ const target = options?.earlierMajor === undefined
5684
+ ? null
5685
+ : await (async () => {
5686
+ if (channel !== 'prod')
5687
+ throw substratError('validation_failed', 'an earlier major is released on prod alone');
5688
+ return earlierMajorReleaseTarget({
5689
+ vertical: verticalSlug,
5690
+ earlierJson: (await this.cp.readVertical(verticalSlug))?.earlier_majors,
5691
+ major: options.earlierMajor,
5692
+ head: { version: incoming.version, deploymentRef: incoming.deployment_ref },
5693
+ servesMajors: options.servesMajors === true,
5694
+ });
5695
+ })();
5696
+ const current = target ? { version_id: target.versionId } : await this.cp.readChannel(verticalSlug, channel);
5436
5697
  const outgoing = current ? await this.cp.readVersion(current.version_id) : undefined;
5437
5698
  const ack = promotionAcknowledgement.parse(acknowledge ?? {});
5438
5699
  // The owning tenant's live scopes a PRIVATE prod promote re-points — below for an embedded
5439
5700
  // vertical, after the in-place serve for a dispatch-backed one (#321) — read before
5440
- // anything moves so the #2178 gate can judge each one.
5701
+ // anything moves so the #2178 gate can judge each one. A release into an earlier major
5702
+ // re-points none: only the installs on that major's script run it.
5441
5703
  const owning = channel === 'prod' ? await this.cp.readVertical(verticalSlug) : undefined;
5442
- const owned = owning && owning.owner_tenant !== null && !owning.listed
5704
+ const owned = !target && owning && owning.owner_tenant !== null && !owning.listed
5443
5705
  ? (await this.cp.listScopes({ tenantId: owning.owner_tenant, vertical: verticalSlug, status: ['active'] })).filter(isPrimaryScopeRow)
5444
5706
  : [];
5445
5707
  // #2178, ahead of the acknowledgements below because none of them passes it. What the promote
5446
5708
  // moves something from: the channel's version, the version served in place (a prod promote
5447
5709
  // serves the incoming one next, and a failed serve leaves it behind the channel), and what each
5448
5710
  // re-pointed scope RUNS (`runningVersionOf`: on the serving script, the served version).
5449
- const served = channel === 'prod' && owning?.serving_ref && owning.serving_version_id
5450
- ? { ref: owning.serving_ref, versionId: owning.serving_version_id }
5451
- : null;
5711
+ const served = target
5712
+ ? { ref: target.ref, versionId: target.versionId }
5713
+ : channel === 'prod' && owning?.serving_ref && owning.serving_version_id
5714
+ ? { ref: owning.serving_ref, versionId: owning.serving_version_id }
5715
+ : null;
5452
5716
  // And what each scope it moves last reconciled (`PROVISIONED_VERSIONS_SQL`).
5453
5717
  await this.assertNoStrandFrom([
5454
5718
  outgoing?.id,
@@ -5470,6 +5734,10 @@ export class CloudflareScopeHost {
5470
5734
  : null;
5471
5735
  if (breakingWithinMajor && owning?.listed)
5472
5736
  throw breakingWithinMajorRefusal(breakingWithinMajor);
5737
+ // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
5738
+ // of the acknowledgements, because none of them passes it.
5739
+ // K-65 (#3539): a release into an earlier major reaches the scopes on its script alone.
5740
+ assertScopeTypesKept(verticalSlug, await (target ? this.cp.scopeTypesHeldBy(verticalSlug, target.ref) : this.cp.scopeTypesHeldBy(verticalSlug)), incoming.manifest_json);
5473
5741
  // #2333: the acknowledgements answer the review they were given against, or none at all.
5474
5742
  const reviewed = async (v) => ({
5475
5743
  id: v.id,
@@ -5502,6 +5770,16 @@ export class CloudflareScopeHost {
5502
5770
  throw substratError('precondition_failed', exportBreakRefusal(breaks));
5503
5771
  }
5504
5772
  }
5773
+ // K-65 (#3539): a release into an earlier major moves no channel. Its admin row, the
5774
+ // acknowledgement's evidence, lands only while that major's script still runs the version its
5775
+ // gates were judged against, with the listing and the admission read in the DO's unit as a
5776
+ // prod promote's are. The caller then serves it on the script and records that.
5777
+ if (target) {
5778
+ 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);
5779
+ if (!judged)
5780
+ throw promoteRaceRefusal(channel);
5781
+ return;
5782
+ }
5505
5783
  const promotedAt = new Date().toISOString();
5506
5784
  // #2333: a compare-and-set. Every gate above — the review binding, the digest checkpoints,
5507
5785
  // the export breaks — was judged against `outgoing`, across awaits another promote can run
@@ -5654,7 +5932,7 @@ export class CloudflareScopeHost {
5654
5932
  throw substratError('precondition_failed', `scope ${scopeId} is being reaped`);
5655
5933
  },
5656
5934
  markScopeStoresFenced: async (actor, tenantId, scopeId, opts) => {
5657
- await this.directory('markScopeStoresFenced', tenantId, scopeId, opts?.whileTenantDeleting === true, this.adminEntry(actor, 'markScopeStoresFenced', { tenantId, scopeId }, null, { storesFenced: true }));
5935
+ 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);
5658
5936
  },
5659
5937
  scopeStoresFencedAt: async (_actor, tenantId, scopeId) => this.cp.scopeStoresFencedAt(tenantId, scopeId),
5660
5938
  beginScopeScriptReap: async (_actor, tenantId, scopeId, opts) => {
@@ -5720,6 +5998,26 @@ export class CloudflareScopeHost {
5720
5998
  const r = await this.cp.readVertical(verticalSlug);
5721
5999
  if (!r)
5722
6000
  throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
6001
+ // K-65 (#3539): a release served on an earlier major's own script moves that major's entry alone.
6002
+ if (opts?.earlierMajor !== undefined) {
6003
+ const major = opts.earlierMajor;
6004
+ if (supersede)
6005
+ throw substratError('validation_failed', 'a serve records a new major or a release into an earlier one, not both');
6006
+ const entry = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
6007
+ if (!expected || !entry || entry.versionId !== expected.versionId)
6008
+ throw servingRaceRefusal(verticalSlug);
6009
+ const incoming = await this.cp.readVersion(parsed.versionId);
6010
+ if (!incoming || incoming.vertical_slug !== verticalSlug) {
6011
+ throw substratError('not_found', `unknown version ${parsed.versionId} for vertical '${verticalSlug}'`);
6012
+ }
6013
+ // #2993 part 4 and #2178, as an in-place serve is judged, over the installs on that script.
6014
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug, entry.ref), incoming.manifest_json);
6015
+ await this.assertNoStrandFrom([entry.versionId], incoming.id, incoming, await this.cp.provisionedVersionsOf(verticalSlug, { ref: entry.ref, versionId: entry.versionId }, null));
6016
+ await this.directory('setEarlierMajorServing', verticalSlug, major, {
6017
+ ref: parsed.ref, versionId: parsed.versionId, doClasses: parsed.doClasses, migrationTag: parsed.migrationTag,
6018
+ }, { 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 }));
6019
+ return;
6020
+ }
5723
6021
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
5724
6022
  if (expected !== undefined && !migratesFrom(r, expected))
5725
6023
  throw servingRaceRefusal(verticalSlug);
@@ -5732,6 +6030,8 @@ export class CloudflareScopeHost {
5732
6030
  if (r.serving_version_id && !supersede) {
5733
6031
  const incoming = await this.cp.readVersion(parsed.versionId);
5734
6032
  if (incoming) {
6033
+ // #2993 part 4: and it declares every type their scopes hold.
6034
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
5735
6035
  await this.assertNoStrandFrom([r.serving_version_id], incoming.id, incoming, r.serving_ref ? await this.cp.provisionedVersionsOf(verticalSlug, { ref: r.serving_ref, versionId: r.serving_version_id }, null) : []);
5736
6036
  }
5737
6037
  }
@@ -5962,12 +6262,12 @@ export class CloudflareScopeHost {
5962
6262
  // A rename to the current name writes nothing and is not audited; the DO fills `before`.
5963
6263
  await this.directory('setTenantName', tenantId, name, this.adminEntry(actor, 'setTenantName', { tenantId }, null, { name }));
5964
6264
  },
5965
- reapTenant: async (actor, tenantId) => {
6265
+ reapTenant: async (actor, tenantId, opts) => {
5966
6266
  // Directory-side terminal reap (§4.8). The caller reaped every scope's storage
5967
6267
  // first (archive-if-needed → reapScope in the vertical deployment); the DO clears
5968
6268
  // the tenant's PII/config rows and flips the row to a `reaped` tombstone, keeping
5969
6269
  // the row + admin log. Only a `deleting` tenant may be reaped (checked in the DO).
5970
- await this.directory('reapTenant', tenantId, this.adminEntry(actor, 'reapTenant', { tenantId }, null, { status: 'reaped' }));
6270
+ await this.directory('reapTenant', tenantId, this.adminEntry(actor, 'reapTenant', { tenantId }, null, { status: 'reaped' }), opts?.deletingBy);
5971
6271
  },
5972
6272
  listTenants: async (actor, page) => {
5973
6273
  const tenants = (await this.cp.listTenants(page)).map((t) => tenantSchema.parse(t));
@@ -6461,10 +6761,26 @@ export class CloudflareScopeHost {
6461
6761
  },
6462
6762
  suspendScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'suspendScope', tenantId, scopeId, ['active'], 'suspended'),
6463
6763
  unsuspendScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'unsuspendScope', tenantId, scopeId, ['suspended'], 'active'),
6464
- archiveScope: async (actor, tenantId, scopeId) =>
6465
- // Also from `provisioning`: a scope whose provisioning never completed (a failed
6466
- // create) must be abandonable, or its slug is stranded forever.
6467
- transitionScope(actor, 'archiveScope', tenantId, scopeId, ['provisioning', 'active', 'suspended'], 'archived'),
6764
+ archiveScope: async (actor, tenantId, scopeId) => {
6765
+ // Also from `provisioning`: a scope whose provisioning never completed (a failed
6766
+ // create) must be abandonable, or its slug is stranded forever.
6767
+ //
6768
+ // #2995: lifecycle follows the link. The scope's children are archived with it, in the same
6769
+ // directory unit, each with its own audit row naming the parent; a refused parent archives
6770
+ // none. A child already archived stays as it is. Each is then delivered its lifecycle, as a
6771
+ // single archive is, so a child's own deployment stops serving it too.
6772
+ const from = ['provisioning', 'active', 'suspended'];
6773
+ const before = await this.cp.archiveScopeFamilyOrRefusal(tenantId, scopeId, from, 'archiveScope');
6774
+ if (!before.ok)
6775
+ throw before.code ? substratError(before.code, before.message) : new Error(before.message);
6776
+ for (const child of before.children) {
6777
+ await this.recordAdmin(actor, 'archiveScope', { tenantId, scopeId: child.scopeId, vertical: child.vertical }, { status: child.status }, { status: 'archived', withParent: scopeId });
6778
+ }
6779
+ await this.recordAdmin(actor, 'archiveScope', { tenantId, scopeId, vertical: before.vertical }, { status: before.status }, { status: 'archived' });
6780
+ for (const child of before.children)
6781
+ await this.deliverLifecycles(actor, { scopeId: child.scopeId });
6782
+ await this.deliverLifecycles(actor, { scopeId });
6783
+ },
6468
6784
  unarchiveScope: async (actor, tenantId, scopeId) => {
6469
6785
  // An archived scope is outside `fanOut`'s status filter (#1386), so every
6470
6786
  // tenant-level revoke that landed while it sat archived never reached its local
@@ -6522,6 +6838,14 @@ export class CloudflareScopeHost {
6522
6838
  throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound[0].hostname}' — ` +
6523
6839
  `unbind it before reaping (reap wipes storage and cannot be undone)`);
6524
6840
  }
6841
+ // #2995: a child does not outlive its parent, and a hosted child's bytes live in its vertical's
6842
+ // deployment, which this host does not reach: whoever reaps the parent reaps each child first,
6843
+ // through the same sequence (`reapChildrenFirst` in control-plane-api). Refused before anything
6844
+ // is wiped; the directory refuses the flip too, in its own unit.
6845
+ const unreaped = await this.cp.childScopeIds(tenantId, scopeId, ['provisioning', 'active', 'suspended', 'archived']);
6846
+ if (unreaped.length > 0) {
6847
+ throw substratError('conflict', `scope ${scopeId} holds ${unreaped.length} child scope(s) not reaped (${unreaped.join(', ')}): a child is reaped before its parent`);
6848
+ }
6525
6849
  await this.wipeScopeStores(tenantId, scopeId);
6526
6850
  await this.scopeStub(scopeId).destroyStorage();
6527
6851
  // The recoverable copy the caller stored first (#493), named in the audit entry so
@@ -6660,6 +6984,20 @@ export class CloudflareScopeHost {
6660
6984
  return receipt;
6661
6985
  },
6662
6986
  scopeErasureEpoch: async (_actor, tenantId, scopeId) => this.cp.scopeErasureEpoch(tenantId, scopeId),
6987
+ recordDependentErasures: async (actor, tenantId, subjectId, outcomes) => {
6988
+ if (outcomes.length === 0)
6989
+ return;
6990
+ await this.cp.recordDependentErasures(tenantId, subjectId, outcomes, this.adminEntry(actor, 'eraseAtDependents', { tenantId }, null, { subjectId, dependents: outcomes }));
6991
+ },
6992
+ dueDependentErasures: async (actor, now, limit) => {
6993
+ const owed = await this.cp.dueDependentErasures(now, limit);
6994
+ await this.recordAccess(actor, 'dueDependentErasures', { tenantId: null }, { now, limit }, owed.length);
6995
+ return owed;
6996
+ },
6997
+ holdDependentErasures: async (_actor, tenantId, subjectId, dependents) => {
6998
+ if (dependents.length > 0)
6999
+ await this.cp.holdDependentErasures(tenantId, subjectId, dependents);
7000
+ },
6663
7001
  finalizeSubjectShred: async (actor, tenantId, scopeId, subjectId, redactions, expected, storeErasures = []) => {
6664
7002
  await this.assertScope(tenantId, scopeId);
6665
7003
  if (redactions.length === 0)
@@ -7550,7 +7888,9 @@ export class CloudflareScopeHost {
7550
7888
  */
7551
7889
  async validateScopeAccess(tenantId, scopeId,
7552
7890
  /** The host method the call came through, named in `tenantUnrecordedRefusedLine` only. */
7553
- door) {
7891
+ door,
7892
+ /** #2995: filled, on a CP-less host, with the scope's type and parent as its storage holds them. */
7893
+ held) {
7554
7894
  const refusal = await this.cp.scopeAccessRefusal(tenantId, scopeId);
7555
7895
  if (refusal) {
7556
7896
  throw refusal.code
@@ -7559,7 +7899,11 @@ export class CloudflareScopeHost {
7559
7899
  }
7560
7900
  if (!this.cpLess)
7561
7901
  return null;
7562
- const { verdict, lifecycle } = await this.scopeStub(scopeId).admission(tenantId);
7902
+ const { verdict, lifecycle, type, parent } = await this.scopeStub(scopeId).admission(tenantId);
7903
+ if (held) {
7904
+ held.type = type;
7905
+ held.parent = parent;
7906
+ }
7563
7907
  // #2035: a scope with no tenant record and no role rows has nothing to hold the pair against, so
7564
7908
  // it is refused like a foreign one. The platform's paths record the tenant without passing this
7565
7909
  // door — a provision or reconcile (every push runs one, #1172), a restore or snapshot, a
@@ -7586,8 +7930,8 @@ export class CloudflareScopeHost {
7586
7930
  * The admin and diagnostic reads (dead letters, job runs, platform requests, delivered
7587
7931
  * grants) keep `validateScopeAccess` alone: an operator still reads a suspended scope.
7588
7932
  */
7589
- async assertLive(tenantId, scopeId, door) {
7590
- const refusal = lifecycleRefusal(await this.validateScopeAccess(tenantId, scopeId, door), { tenantId, scopeId });
7933
+ async assertLive(tenantId, scopeId, door, held) {
7934
+ const refusal = lifecycleRefusal(await this.validateScopeAccess(tenantId, scopeId, door, held), { tenantId, scopeId });
7591
7935
  if (refusal)
7592
7936
  throw substratError('conflict', refusal, { reason: SCOPE_GATE_REASONS.notActive });
7593
7937
  }
@@ -8550,6 +8894,14 @@ export class CloudflareScopeHost {
8550
8894
  */
8551
8895
  async provisionScopeLocal(input) {
8552
8896
  const carry = recordedOffFromWire(input);
8897
+ // #2993 part 3: first, before anything can migrate the scope: its first pass must lay down only
8898
+ // its type's tables. A refused type writes nothing. A host and a call that name no type ask nothing.
8899
+ const scopeType = await this.scopeTypeAt(input.scopeId, input.scopeType);
8900
+ // #2995: then its parent, also before anything migrates. Judged against the store, which holds the
8901
+ // link the first provision fixed; whether the parent may hold this child is the directory's call.
8902
+ const parentScopeId = input.parentScopeId === undefined
8903
+ ? undefined
8904
+ : unwrapReply(await this.scopeStub(input.scopeId).fixScopeParentReply(input.parentScopeId, input.scopeId));
8553
8905
  // #2430: refused before anything is written, rather than at the top-up after the projection.
8554
8906
  if (input.entityGrants)
8555
8907
  await this.refuseReservedShapes(input.entityGrants, input.scopeId);
@@ -8600,7 +8952,7 @@ export class CloudflareScopeHost {
8600
8952
  expires_at: null,
8601
8953
  lockout_reseat: true,
8602
8954
  },
8603
- ...this.declaredSeatsLocal(input.scopeId, connections.seat),
8955
+ ...this.declaredSeatsLocal(input.scopeId, connections.seat, scopeType),
8604
8956
  ],
8605
8957
  // #406: identity links, delivered by the platform with provisioning exactly as
8606
8958
  // entitlements are (#310). Preserve-on-undefined, so an absent field never wipes
@@ -8632,6 +8984,8 @@ export class CloudflareScopeHost {
8632
8984
  ? await this.topUpEntityGrantShapesLocal(input.tenantId, input.scopeId, input.entityGrants)
8633
8985
  : null;
8634
8986
  return {
8987
+ ...(input.scopeType !== undefined ? { scopeType } : {}),
8988
+ ...(typeof parentScopeId === 'string' ? { parentScopeId } : {}),
8635
8989
  ...(carry ? { switchedOff } : {}),
8636
8990
  ...(shapes ? { retirementsLeftOpen: shapes.retirementsLeftOpen ?? 0 } : {}),
8637
8991
  ...(shapes?.boundEver ? { boundShapeTypes: shapes.boundEver } : {}),
@@ -8888,16 +9242,18 @@ export class CloudflareScopeHost {
8888
9242
  * function that decides them), and the tenant's connection grants the platform delivered (#592,
8889
9243
  * the provision-time mirror of `connectorGrantLocal`).
8890
9244
  */
8891
- declaredSeatsLocal(scopeId, connectionGrants) {
9245
+ declaredSeatsLocal(scopeId, connectionGrants,
9246
+ /** #2993 part 3: only the modules this type runs seat their schedule and peer grants. */
9247
+ scopeType) {
8892
9248
  return [
8893
- ...[...this.moduleSchedules].flatMap(([modId, schedules]) => {
9249
+ ...[...this.moduleSchedules].filter(([modId]) => scopeTypeRuns(this.scopeTypePlan, scopeType, modId)).flatMap(([modId, schedules]) => {
8894
9250
  const perms = new Set();
8895
9251
  for (const s of schedules)
8896
9252
  for (const p of s.permissions)
8897
9253
  perms.add(p);
8898
9254
  return [...perms].map((perm) => ({ subject: `system:${modId}`, relation: `granted:${perm}`, object: `scope:${scopeId}`, expires_at: null }));
8899
9255
  }),
8900
- ...peerSeats(collectPeers(this.peerSources), scopeId).map((seat) => ({ ...seat, expires_at: null })),
9256
+ ...peerSeats(collectPeers(this.peerSourcesOf(scopeType)), scopeId).map((seat) => ({ ...seat, expires_at: null })),
8901
9257
  ...(connectionGrants ?? []).map((g) => ({
8902
9258
  subject: `connection:${g.connectionId}`,
8903
9259
  relation: `granted:${g.permission}`,
@@ -8930,7 +9286,9 @@ export class CloudflareScopeHost {
8930
9286
  const carry = recordedOffFromWire(input);
8931
9287
  const connections = await this.seatableConnectionGrants(input.tenantId, input.scopeId, input.connectionGrants); // #2430
8932
9288
  await this.migrateAndRecord(input.scopeId);
8933
- const seated = await stub.seatTuplesFor(input.tenantId, this.declaredSeatsLocal(input.scopeId, connections.seat), carry ? { scopeId: input.scopeId, at: new Date().toISOString(), ...carry } : undefined);
9289
+ const seated = await stub.seatTuplesFor(input.tenantId,
9290
+ // #2993 part 3: the type the scope holds; this seat never names one.
9291
+ this.declaredSeatsLocal(input.scopeId, connections.seat, await this.scopeTypeAt(input.scopeId)), carry ? { scopeId: input.scopeId, at: new Date().toISOString(), ...carry } : undefined);
8934
9292
  // Reaped or recorded for another tenant since the check: K-3's refusal, naming no other tenant.
8935
9293
  if ('refused' in seated)
8936
9294
  throw unknownScopeForTenant(input.tenantId, input.scopeId);