@substrat-run/adapter-cloudflare 0.221.0 → 0.222.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/broker-telemetry.d.ts +2 -5
  2. package/dist/broker-telemetry.d.ts.map +1 -1
  3. package/dist/broker-telemetry.js +2 -5
  4. package/dist/broker-telemetry.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +244 -67
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +664 -246
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +3 -2
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +10 -4
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-handoff.d.ts +17 -1
  14. package/dist/delivery-handoff.d.ts.map +1 -1
  15. package/dist/delivery-handoff.js +19 -5
  16. package/dist/delivery-handoff.js.map +1 -1
  17. package/dist/directory-cutover.d.ts +243 -0
  18. package/dist/directory-cutover.d.ts.map +1 -0
  19. package/dist/directory-cutover.js +604 -0
  20. package/dist/directory-cutover.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +19 -1
  22. package/dist/directory-mirror-apply.d.ts.map +1 -1
  23. package/dist/directory-mirror-apply.js +19 -3
  24. package/dist/directory-mirror-apply.js.map +1 -1
  25. package/dist/directory-mirror-backfill.d.ts +2 -0
  26. package/dist/directory-mirror-backfill.d.ts.map +1 -1
  27. package/dist/directory-mirror-backfill.js +6 -4
  28. package/dist/directory-mirror-backfill.js.map +1 -1
  29. package/dist/directory-mirror.d.ts +24 -0
  30. package/dist/directory-mirror.d.ts.map +1 -1
  31. package/dist/directory-mirror.js +16 -2
  32. package/dist/directory-mirror.js.map +1 -1
  33. package/dist/directory-objects.d.ts +40 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +134 -2
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts.map +1 -1
  38. package/dist/directory-placement.js +7 -1
  39. package/dist/directory-placement.js.map +1 -1
  40. package/dist/directory-split-inventory.d.ts +5 -3
  41. package/dist/directory-split-inventory.d.ts.map +1 -1
  42. package/dist/directory-split-inventory.js +12 -6
  43. package/dist/directory-split-inventory.js.map +1 -1
  44. package/dist/directory-tenant-orgs.d.ts +19 -0
  45. package/dist/directory-tenant-orgs.d.ts.map +1 -0
  46. package/dist/directory-tenant-orgs.js +33 -0
  47. package/dist/directory-tenant-orgs.js.map +1 -0
  48. package/dist/directory-tenant-roles.d.ts +35 -0
  49. package/dist/directory-tenant-roles.d.ts.map +1 -0
  50. package/dist/directory-tenant-roles.js +78 -0
  51. package/dist/directory-tenant-roles.js.map +1 -0
  52. package/dist/directory-tenant-tuples.d.ts +165 -0
  53. package/dist/directory-tenant-tuples.d.ts.map +1 -0
  54. package/dist/directory-tenant-tuples.js +197 -0
  55. package/dist/directory-tenant-tuples.js.map +1 -0
  56. package/dist/host.d.ts +26 -1
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/host.js +262 -45
  59. package/dist/host.js.map +1 -1
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +1 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/platform-sweeper-do.d.ts +1 -1
  65. package/dist/platform-sweeper-do.js +1 -1
  66. package/dist/scope-do.d.ts +11 -2
  67. package/dist/scope-do.d.ts.map +1 -1
  68. package/dist/scope-do.js +154 -40
  69. package/dist/scope-do.js.map +1 -1
  70. package/dist/scope-sweeper-do.d.ts +22 -0
  71. package/dist/scope-sweeper-do.d.ts.map +1 -1
  72. package/dist/scope-sweeper-do.js +74 -54
  73. package/dist/scope-sweeper-do.js.map +1 -1
  74. package/dist/scope-wake.d.ts +12 -1
  75. package/dist/scope-wake.d.ts.map +1 -1
  76. package/dist/scope-wake.js +14 -1
  77. package/dist/scope-wake.js.map +1 -1
  78. package/dist/tenant-due-work-do.d.ts +95 -0
  79. package/dist/tenant-due-work-do.d.ts.map +1 -0
  80. package/dist/tenant-due-work-do.js +149 -0
  81. package/dist/tenant-due-work-do.js.map +1 -0
  82. package/package.json +10 -10
package/dist/host.js CHANGED
@@ -2,14 +2,16 @@ 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 { 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
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,
13
15
  // #2993 part 3: the modules (and seats) a scope of each declared type has.
14
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';
15
17
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
@@ -112,20 +114,6 @@ function assertCopyLineage(lineage) {
112
114
  throw substratError('conflict', 'mark-copy refused: the directory classifies this scope as primary, not as a copy');
113
115
  }
114
116
  }
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
117
  function nullControlPlane() {
130
118
  const noop = async () => undefined;
131
119
  const passthrough = {
@@ -1931,11 +1919,6 @@ export class CloudflareScopeHost {
1931
1919
  }
1932
1920
  /** `provisionScope`, answering whether this call created the directory row (#2555: an import's teardown). */
1933
1921
  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
1922
  // Shared with the pure adapter so the defaults cannot drift between them.
1940
1923
  const record = resolveScopeRecord(input);
1941
1924
  // #2993: the type this provision gives the scope, by the kernel's rule, before anything is
@@ -1949,20 +1932,77 @@ export class CloudflareScopeHost {
1949
1932
  ? await this.verticalScopeTypePlan(record.vertical)
1950
1933
  : own;
1951
1934
  const typed = plan.declared;
1952
- const recorded = typed ? await this.cp.getScopeRecord(input.tenantId, input.scopeId) : undefined;
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;
1953
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
+ }
1954
1972
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1955
1973
  // or audit, so a rejected provision creates nothing and writes no audit row.
1956
1974
  const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
1957
1975
  // #2993: the directory row records the type ('home' as NULL), and refuses a different one in
1958
1976
  // 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());
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());
1960
1996
  // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1961
1997
  // first pass lays down only its type's tables. A host with no declared types asks nothing. A
1962
1998
  // coordinator judging by a vertical's types (part 4) does not either: the vertical's own
1963
1999
  // object is fixed by its `/internal/provision`, which the platform sends the type.
1964
2000
  if (own.declared)
1965
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
+ }
1966
2006
  // Instantiate the scope DO and trigger its lazy migration.
1967
2007
  await this.migrateAndRecord(input.scopeId);
1968
2008
  // Scope-local permissions: a freshly-provisioned scope evaluates from its own
@@ -2016,7 +2056,12 @@ export class CloudflareScopeHost {
2016
2056
  if (created) {
2017
2057
  await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2018
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.
2019
- scopeType === HOME_SCOPE_TYPE ? record : { ...record, scopeType });
2059
+ // #2995: a child's names its parent.
2060
+ {
2061
+ ...record,
2062
+ ...(scopeType === HOME_SCOPE_TYPE ? {} : { scopeType }),
2063
+ ...(parentScopeId === null ? {} : { parentScopeId }),
2064
+ });
2020
2065
  }
2021
2066
  return created;
2022
2067
  }
@@ -2453,6 +2498,11 @@ export class CloudflareScopeHost {
2453
2498
  * scope of this host, made at once, so its seats are the ones that scope holds now (K-55).
2454
2499
  */
2455
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
+ }
2456
2506
  this.refuseUnusableScopeStores(dump.stores, input.vertical ?? null);
2457
2507
  if (judge)
2458
2508
  await this.refuseDumpRoles(input.tenantId, null, dump);
@@ -2680,7 +2730,60 @@ export class CloudflareScopeHost {
2680
2730
  const parsedDelegation = parseScopeDelegation(options?.delegation);
2681
2731
  // Lifecycle gates (control-plane.md §4.1/§4.2), the K-3 fail-closed path,
2682
2732
  // evaluated durably in the ControlPlaneDO. A throw propagates here.
2683
- 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) {
2684
2787
  await this.migrateAndRecord(scopeId);
2685
2788
  // #3161: a person's call arriving through a peer goes through that peer's door, as
2686
2789
  // `getVerticalScope` opens it (the name `peers` uses, the rewind hold, the pin), and the
@@ -4255,6 +4358,7 @@ export class CloudflareScopeHost {
4255
4358
  : [filter.status]
4256
4359
  : undefined,
4257
4360
  vertical: filter?.vertical,
4361
+ ...(filter?.parentScopeId ? { parentScopeId: filter.parentScopeId } : {}),
4258
4362
  limit: filter?.limit,
4259
4363
  cursor: filter?.cursor,
4260
4364
  order: filter?.order,
@@ -5348,6 +5452,12 @@ export class CloudflareScopeHost {
5348
5452
  throw substratError(answer.code, answer.message);
5349
5453
  return { changed: answer.changed, previous: answer.previous };
5350
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
+ },
5351
5461
  // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
5352
5462
  listEnvironments: async (actor, tenantId, vertical) => {
5353
5463
  const rows = await this.cp.listEnvironments(tenantId, verticalSlug.parse(vertical));
@@ -5367,13 +5477,21 @@ export class CloudflareScopeHost {
5367
5477
  releaseEnvironmentServe: async (_actor, input, claim) => {
5368
5478
  await this.cp.releaseEnvironmentServe({ ...input, vertical: verticalSlug.parse(input.vertical) }, claim);
5369
5479
  },
5370
- setEnvironmentServing: async (actor, input, next, expected, claim) => {
5480
+ setEnvironmentServing: async (actor, input, next, expected, claim, acknowledge) => {
5371
5481
  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);
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);
5373
5485
  if (!moved) {
5374
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`);
5375
5487
  }
5376
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)),
5377
5495
  resolveHostname: async (raw) =>
5378
5496
  // The router's per-request read. No actor, not logged — the same machine-path
5379
5497
  // carve-out resolveIdentity has (K-24). Shares its mapping with the router's
@@ -5560,23 +5678,41 @@ export class CloudflareScopeHost {
5560
5678
  if (incoming.admission !== 'admitted') {
5561
5679
  throw substratError('conflict', `version ${versionId} is ${incoming.admission}, not admitted — it cannot be promoted`);
5562
5680
  }
5563
- 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);
5564
5697
  const outgoing = current ? await this.cp.readVersion(current.version_id) : undefined;
5565
5698
  const ack = promotionAcknowledgement.parse(acknowledge ?? {});
5566
5699
  // The owning tenant's live scopes a PRIVATE prod promote re-points — below for an embedded
5567
5700
  // 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.
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.
5569
5703
  const owning = channel === 'prod' ? await this.cp.readVertical(verticalSlug) : undefined;
5570
- const owned = owning && owning.owner_tenant !== null && !owning.listed
5704
+ const owned = !target && owning && owning.owner_tenant !== null && !owning.listed
5571
5705
  ? (await this.cp.listScopes({ tenantId: owning.owner_tenant, vertical: verticalSlug, status: ['active'] })).filter(isPrimaryScopeRow)
5572
5706
  : [];
5573
5707
  // #2178, ahead of the acknowledgements below because none of them passes it. What the promote
5574
5708
  // moves something from: the channel's version, the version served in place (a prod promote
5575
5709
  // serves the incoming one next, and a failed serve leaves it behind the channel), and what each
5576
5710
  // 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;
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;
5580
5716
  // And what each scope it moves last reconciled (`PROVISIONED_VERSIONS_SQL`).
5581
5717
  await this.assertNoStrandFrom([
5582
5718
  outgoing?.id,
@@ -5600,7 +5736,8 @@ export class CloudflareScopeHost {
5600
5736
  throw breakingWithinMajorRefusal(breakingWithinMajor);
5601
5737
  // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
5602
5738
  // of the acknowledgements, because none of them passes it.
5603
- assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
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);
5604
5741
  // #2333: the acknowledgements answer the review they were given against, or none at all.
5605
5742
  const reviewed = async (v) => ({
5606
5743
  id: v.id,
@@ -5633,6 +5770,16 @@ export class CloudflareScopeHost {
5633
5770
  throw substratError('precondition_failed', exportBreakRefusal(breaks));
5634
5771
  }
5635
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
+ }
5636
5783
  const promotedAt = new Date().toISOString();
5637
5784
  // #2333: a compare-and-set. Every gate above — the review binding, the digest checkpoints,
5638
5785
  // the export breaks — was judged against `outgoing`, across awaits another promote can run
@@ -5785,7 +5932,7 @@ export class CloudflareScopeHost {
5785
5932
  throw substratError('precondition_failed', `scope ${scopeId} is being reaped`);
5786
5933
  },
5787
5934
  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 }));
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);
5789
5936
  },
5790
5937
  scopeStoresFencedAt: async (_actor, tenantId, scopeId) => this.cp.scopeStoresFencedAt(tenantId, scopeId),
5791
5938
  beginScopeScriptReap: async (_actor, tenantId, scopeId, opts) => {
@@ -5851,6 +5998,26 @@ export class CloudflareScopeHost {
5851
5998
  const r = await this.cp.readVertical(verticalSlug);
5852
5999
  if (!r)
5853
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
+ }
5854
6021
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
5855
6022
  if (expected !== undefined && !migratesFrom(r, expected))
5856
6023
  throw servingRaceRefusal(verticalSlug);
@@ -6095,12 +6262,12 @@ export class CloudflareScopeHost {
6095
6262
  // A rename to the current name writes nothing and is not audited; the DO fills `before`.
6096
6263
  await this.directory('setTenantName', tenantId, name, this.adminEntry(actor, 'setTenantName', { tenantId }, null, { name }));
6097
6264
  },
6098
- reapTenant: async (actor, tenantId) => {
6265
+ reapTenant: async (actor, tenantId, opts) => {
6099
6266
  // Directory-side terminal reap (§4.8). The caller reaped every scope's storage
6100
6267
  // first (archive-if-needed → reapScope in the vertical deployment); the DO clears
6101
6268
  // the tenant's PII/config rows and flips the row to a `reaped` tombstone, keeping
6102
6269
  // 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' }));
6270
+ await this.directory('reapTenant', tenantId, this.adminEntry(actor, 'reapTenant', { tenantId }, null, { status: 'reaped' }), opts?.deletingBy);
6104
6271
  },
6105
6272
  listTenants: async (actor, page) => {
6106
6273
  const tenants = (await this.cp.listTenants(page)).map((t) => tenantSchema.parse(t));
@@ -6594,10 +6761,26 @@ export class CloudflareScopeHost {
6594
6761
  },
6595
6762
  suspendScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'suspendScope', tenantId, scopeId, ['active'], 'suspended'),
6596
6763
  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'),
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
+ },
6601
6784
  unarchiveScope: async (actor, tenantId, scopeId) => {
6602
6785
  // An archived scope is outside `fanOut`'s status filter (#1386), so every
6603
6786
  // tenant-level revoke that landed while it sat archived never reached its local
@@ -6655,6 +6838,14 @@ export class CloudflareScopeHost {
6655
6838
  throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound[0].hostname}' — ` +
6656
6839
  `unbind it before reaping (reap wipes storage and cannot be undone)`);
6657
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
+ }
6658
6849
  await this.wipeScopeStores(tenantId, scopeId);
6659
6850
  await this.scopeStub(scopeId).destroyStorage();
6660
6851
  // The recoverable copy the caller stored first (#493), named in the audit entry so
@@ -6793,6 +6984,20 @@ export class CloudflareScopeHost {
6793
6984
  return receipt;
6794
6985
  },
6795
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
+ },
6796
7001
  finalizeSubjectShred: async (actor, tenantId, scopeId, subjectId, redactions, expected, storeErasures = []) => {
6797
7002
  await this.assertScope(tenantId, scopeId);
6798
7003
  if (redactions.length === 0)
@@ -7683,7 +7888,9 @@ export class CloudflareScopeHost {
7683
7888
  */
7684
7889
  async validateScopeAccess(tenantId, scopeId,
7685
7890
  /** The host method the call came through, named in `tenantUnrecordedRefusedLine` only. */
7686
- 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) {
7687
7894
  const refusal = await this.cp.scopeAccessRefusal(tenantId, scopeId);
7688
7895
  if (refusal) {
7689
7896
  throw refusal.code
@@ -7692,7 +7899,11 @@ export class CloudflareScopeHost {
7692
7899
  }
7693
7900
  if (!this.cpLess)
7694
7901
  return null;
7695
- 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
+ }
7696
7907
  // #2035: a scope with no tenant record and no role rows has nothing to hold the pair against, so
7697
7908
  // it is refused like a foreign one. The platform's paths record the tenant without passing this
7698
7909
  // door — a provision or reconcile (every push runs one, #1172), a restore or snapshot, a
@@ -7719,8 +7930,8 @@ export class CloudflareScopeHost {
7719
7930
  * The admin and diagnostic reads (dead letters, job runs, platform requests, delivered
7720
7931
  * grants) keep `validateScopeAccess` alone: an operator still reads a suspended scope.
7721
7932
  */
7722
- async assertLive(tenantId, scopeId, door) {
7723
- 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 });
7724
7935
  if (refusal)
7725
7936
  throw substratError('conflict', refusal, { reason: SCOPE_GATE_REASONS.notActive });
7726
7937
  }
@@ -8686,6 +8897,11 @@ export class CloudflareScopeHost {
8686
8897
  // #2993 part 3: first, before anything can migrate the scope: its first pass must lay down only
8687
8898
  // its type's tables. A refused type writes nothing. A host and a call that name no type ask nothing.
8688
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));
8689
8905
  // #2430: refused before anything is written, rather than at the top-up after the projection.
8690
8906
  if (input.entityGrants)
8691
8907
  await this.refuseReservedShapes(input.entityGrants, input.scopeId);
@@ -8769,6 +8985,7 @@ export class CloudflareScopeHost {
8769
8985
  : null;
8770
8986
  return {
8771
8987
  ...(input.scopeType !== undefined ? { scopeType } : {}),
8988
+ ...(typeof parentScopeId === 'string' ? { parentScopeId } : {}),
8772
8989
  ...(carry ? { switchedOff } : {}),
8773
8990
  ...(shapes ? { retirementsLeftOpen: shapes.retirementsLeftOpen ?? 0 } : {}),
8774
8991
  ...(shapes?.boundEver ? { boundShapeTypes: shapes.boundEver } : {}),