@substrat-run/adapter-cloudflare 0.219.0 → 0.221.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 (54) hide show
  1. package/dist/control-plane-do.d.ts +107 -5
  2. package/dist/control-plane-do.d.ts.map +1 -1
  3. package/dist/control-plane-do.js +207 -16
  4. package/dist/control-plane-do.js.map +1 -1
  5. package/dist/directory-mirror-backfill.d.ts +143 -0
  6. package/dist/directory-mirror-backfill.d.ts.map +1 -0
  7. package/dist/directory-mirror-backfill.js +467 -0
  8. package/dist/directory-mirror-backfill.js.map +1 -0
  9. package/dist/directory-mirror-verify.d.ts +166 -0
  10. package/dist/directory-mirror-verify.d.ts.map +1 -0
  11. package/dist/directory-mirror-verify.js +478 -0
  12. package/dist/directory-mirror-verify.js.map +1 -0
  13. package/dist/directory-mirror.d.ts +101 -3
  14. package/dist/directory-mirror.d.ts.map +1 -1
  15. package/dist/directory-mirror.js +143 -37
  16. package/dist/directory-mirror.js.map +1 -1
  17. package/dist/directory-objects.d.ts +14 -0
  18. package/dist/directory-objects.d.ts.map +1 -1
  19. package/dist/directory-objects.js +34 -0
  20. package/dist/directory-objects.js.map +1 -1
  21. package/dist/directory-placement.d.ts.map +1 -1
  22. package/dist/directory-placement.js +10 -2
  23. package/dist/directory-placement.js.map +1 -1
  24. package/dist/directory-split-inventory.d.ts +2 -1
  25. package/dist/directory-split-inventory.d.ts.map +1 -1
  26. package/dist/directory-split-inventory.js +4 -1
  27. package/dist/directory-split-inventory.js.map +1 -1
  28. package/dist/host.d.ts +71 -5
  29. package/dist/host.d.ts.map +1 -1
  30. package/dist/host.js +293 -37
  31. package/dist/host.js.map +1 -1
  32. package/dist/peer-call-target.d.ts.map +1 -1
  33. package/dist/peer-call-target.js +3 -2
  34. package/dist/peer-call-target.js.map +1 -1
  35. package/dist/route-read-model-publisher.d.ts +42 -1
  36. package/dist/route-read-model-publisher.d.ts.map +1 -1
  37. package/dist/route-read-model-publisher.js +176 -55
  38. package/dist/route-read-model-publisher.js.map +1 -1
  39. package/dist/route-read-model.d.ts +15 -0
  40. package/dist/route-read-model.d.ts.map +1 -1
  41. package/dist/route-read-model.js +21 -9
  42. package/dist/route-read-model.js.map +1 -1
  43. package/dist/scope-do.d.ts +48 -1
  44. package/dist/scope-do.d.ts.map +1 -1
  45. package/dist/scope-do.js +434 -29
  46. package/dist/scope-do.js.map +1 -1
  47. package/dist/scope-sweeper-do.d.ts +24 -0
  48. package/dist/scope-sweeper-do.d.ts.map +1 -1
  49. package/dist/scope-sweeper-do.js +90 -1
  50. package/dist/scope-sweeper-do.js.map +1 -1
  51. package/dist/scope-work.d.ts +2 -2
  52. package/dist/scope-work.js +2 -2
  53. package/dist/scope-work.js.map +1 -1
  54. package/package.json +18 -13
package/dist/host.js CHANGED
@@ -2,16 +2,20 @@ 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, 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, 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, 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';
9
+ import { classify as classifyRelease } from '@substrat-run/model-view/bump';
8
10
  import { ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary } from '@substrat-run/kernel';
9
11
  import { CONNECTOR_DISPATCH_REQUESTED_BY, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
10
- import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, 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
+ // #2993 part 3: the modules (and seats) a scope of each declared type has.
14
+ HOME_SCOPE_TYPE, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRuns, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
11
15
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
12
16
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
13
17
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
14
- import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
18
+ import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, proofCheckedStoreInvoke, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
15
19
  import { PLATFORM_BINDING_PREFIX, PLATFORM_STORE_CODE, parseTraceparent, scopeStoreBindingName, scopeStoreObjectName, STORE_CALL_URL, storeAnswerOf, StoreError, TRACEPARENT_HEADER } from '@substrat-run/contracts';
16
20
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
17
21
  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';
@@ -408,6 +412,11 @@ export class CloudflareScopeHost {
408
412
  declaredKeys = new Set();
409
413
  /** #2430: the declared permission surface `registerModule` holds each module to, when given. */
410
414
  permissions;
415
+ /**
416
+ * #2993 part 3: the modules each declared scope type runs, from `permissions`. Undeclared: one
417
+ * `home` type running every module, and this host neither reads nor asks any scope's type.
418
+ */
419
+ scopeTypePlan;
411
420
  /**
412
421
  * #1705: this deployment's cross-vertical declarations. The DO holds the handlers and makes
413
422
  * every decision. The coordinator keeps its own copy for two reasons: registration refuses
@@ -510,6 +519,7 @@ export class CloudflareScopeHost {
510
519
  constructor(options) {
511
520
  this.servicePrincipals = options.servicePrincipals;
512
521
  this.permissions = options.permissions;
522
+ this.scopeTypePlan = scopeTypePlanOf(options.permissions);
513
523
  // #2430: what the declared surface reserves holds here too, whatever is registered under its ids.
514
524
  for (const m of options.permissions?.modules ?? []) {
515
525
  noteReservedKeys(this.reservedKeys, m.manifest);
@@ -1872,7 +1882,7 @@ export class CloudflareScopeHost {
1872
1882
  this.moduleSchedules.set(manifest.id, manifest.schedules);
1873
1883
  }
1874
1884
  if (manifest.peers && manifest.peers.length > 0) {
1875
- this.peerSources.push({ peers: manifest.peers });
1885
+ this.peerSources.push({ moduleId: manifest.id, peers: manifest.peers });
1876
1886
  }
1877
1887
  if (manifest.freshness && manifest.freshness.length > 0) {
1878
1888
  this.moduleFreshness.set(manifest.id, manifest.freshness);
@@ -1921,11 +1931,38 @@ export class CloudflareScopeHost {
1921
1931
  }
1922
1932
  /** `provisionScope`, answering whether this call created the directory row (#2555: an import's teardown). */
1923
1933
  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
+ }
1924
1939
  // Shared with the pure adapter so the defaults cannot drift between them.
1925
1940
  const record = resolveScopeRecord(input);
1941
+ // #2993: the type this provision gives the scope, by the kernel's rule, before anything is
1942
+ // written: an undeclared type, or one other than the type the directory records, is refused.
1943
+ // A host with no declared types reads nothing for it and takes 'home'. Part 4: a module-less
1944
+ // coordinator asked for another type of a vertical's scope judges it by the types the
1945
+ // vertical's deployed version declares (`verticalScopeTypePlan`); asked for none, or for
1946
+ // 'home', it reads nothing, as before.
1947
+ const own = this.scopeTypePlan;
1948
+ const plan = !own.declared && input.scopeType !== undefined && input.scopeType !== HOME_SCOPE_TYPE && record.vertical
1949
+ ? await this.verticalScopeTypePlan(record.vertical)
1950
+ : own;
1951
+ const typed = plan.declared;
1952
+ const recorded = typed ? await this.cp.getScopeRecord(input.tenantId, input.scopeId) : undefined;
1953
+ const scopeType = provisionedScopeType(plan, input.scopeType, recorded === undefined ? undefined : (recorded.scope_type ?? null), input.scopeId);
1926
1954
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1927
1955
  // or audit, so a rejected provision creates nothing and writes no audit row.
1928
- const created = await this.directory('provisionScope', input.tenantId, input.scopeId, record, new Date().toISOString());
1956
+ const created = await this.directory('provisionScope', input.tenantId, input.scopeId,
1957
+ // #2993: the directory row records the type ('home' as NULL), and refuses a different one in
1958
+ // 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());
1960
+ // #2993 part 3: the scope's own object records its type before anything migrates it, so its
1961
+ // first pass lays down only its type's tables. A host with no declared types asks nothing. A
1962
+ // coordinator judging by a vertical's types (part 4) does not either: the vertical's own
1963
+ // object is fixed by its `/internal/provision`, which the platform sends the type.
1964
+ if (own.declared)
1965
+ unwrapReply(await this.scopeStub(input.scopeId).fixScopeTypeReply(scopeType, input.scopeId));
1929
1966
  // Instantiate the scope DO and trigger its lazy migration.
1930
1967
  await this.migrateAndRecord(input.scopeId);
1931
1968
  // Scope-local permissions: a freshly-provisioned scope evaluates from its own
@@ -1943,6 +1980,9 @@ export class CloudflareScopeHost {
1943
1980
  // (`grantToSystem` still clears a tuple's tombstone, but it does not move the switch.)
1944
1981
  const seats = [];
1945
1982
  for (const [moduleId, schedules] of this.moduleSchedules) {
1983
+ // #2993 part 3: only the modules this scope's type runs seat their schedules' grants.
1984
+ if (!scopeTypeRuns(this.scopeTypePlan, scopeType, moduleId))
1985
+ continue;
1946
1986
  const perms = new Set();
1947
1987
  for (const s of schedules)
1948
1988
  for (const p of s.permissions)
@@ -1955,7 +1995,7 @@ export class CloudflareScopeHost {
1955
1995
  // call (`peerSeats`) that makes "declared and installed" mean "live". Same seat as the
1956
1996
  // schedule grants above, so a grant a switch tombstoned stays tombstoned and a
1957
1997
  // switched-off peer gets nothing seated.
1958
- for (const seat of peerSeats(collectPeers(this.peerSources), input.scopeId)) {
1998
+ for (const seat of peerSeats(collectPeers(this.peerSourcesOf(scopeType)), input.scopeId)) {
1959
1999
  seats.push({ subject: seat.subject, relation: seat.relation, object: seat.object, expires_at: null });
1960
2000
  }
1961
2001
  // #1674: re-assert the recorded OFF positions after the seat (`system-switch-record.ts`).
@@ -1974,10 +2014,43 @@ export class CloudflareScopeHost {
1974
2014
  }
1975
2015
  // Audit a real provision only; an idempotent re-provision changed nothing.
1976
2016
  if (created) {
1977
- await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null, record);
2017
+ await this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2018
+ // #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 });
1978
2020
  }
1979
2021
  return created;
1980
2022
  }
2023
+ /**
2024
+ * #2993 part 4: a vertical's scope types, as the version a new scope of it would run declares
2025
+ * them: the version its serving script serves, else the one its `prod` channel names. Read from
2026
+ * the stored manifest, unaudited, for the reason {@link versionImports} is. A vertical with no
2027
+ * such version, or one that declares no types, has the one `home` type.
2028
+ */
2029
+ async verticalScopeTypePlan(slug) {
2030
+ const vertical = await this.cp.readVertical(slug);
2031
+ const versionId = vertical?.serving_version_id ?? (await this.cp.readChannel(slug, 'prod'))?.version_id;
2032
+ const version = versionId ? await this.cp.readVersion(versionId) : undefined;
2033
+ return scopeTypePlanOfManifest(version?.manifest_json);
2034
+ }
2035
+ /** #2993 part 3: the peer declarations of the modules a scope of `scopeType` runs. */
2036
+ peerSourcesOf(scopeType) {
2037
+ return this.scopeTypePlan.declared
2038
+ ? this.peerSources.filter((p) => scopeTypeRuns(this.scopeTypePlan, scopeType, p.moduleId))
2039
+ : this.peerSources;
2040
+ }
2041
+ /**
2042
+ * #2993 part 3: the scope's type as its own object holds it, fixing it when `requested` names one.
2043
+ * Asked only when it can matter: this host declares types, or the caller named one (the object
2044
+ * judges that by its class's own declaration). Otherwise 'home', with no call, as before types.
2045
+ */
2046
+ async scopeTypeAt(scopeId, requested) {
2047
+ if (!this.scopeTypePlan.declared && requested === undefined)
2048
+ return HOME_SCOPE_TYPE;
2049
+ const stub = this.scopeStub(scopeId);
2050
+ return requested === undefined && this.scopeTypePlan.declared
2051
+ ? stub.scopeTypeHere()
2052
+ : unwrapReply(await stub.fixScopeTypeReply(requested, scopeId));
2053
+ }
1981
2054
  // Per-tenant relational stores (#301, PR-2 — the live D1 path). The coordinator holds
1982
2055
  // the platform's D1 credential (the same split secretBox uses: the DO records, it never
1983
2056
  // holds a key), the ControlPlaneDO serializes the ledger write, and the D1 REST client
@@ -2387,8 +2460,15 @@ export class CloudflareScopeHost {
2387
2460
  // replaces its provisioned schema with the dump wholesale (drop-then-replay), so
2388
2461
  // the end state is the dump, at the source's frontier. Provenance is stamped from
2389
2462
  // the dump unless the caller set it (§3: a fork always records its origin).
2463
+ // #2993 part 3: a copy is a scope of its source's type — the type names the tables the dump
2464
+ // carries. The caller's type when it names one, else the source's, when the directory holds it.
2465
+ const source = input.scopeType === undefined && this.scopeTypePlan.declared
2466
+ ? await this.cp.getScopeRecord(input.tenantId, dump.scopeId)
2467
+ : undefined;
2468
+ const copiedType = input.scopeType ?? (source ? (source.scope_type ?? HOME_SCOPE_TYPE) : undefined);
2390
2469
  const created = await this.provisionScopeCreating(actor, {
2391
2470
  ...input,
2471
+ ...(copiedType === undefined ? {} : { scopeType: copiedType }),
2392
2472
  forkedFrom: input.forkedFrom ?? dump.scopeId,
2393
2473
  forkedAt: input.forkedAt ?? dump.capturedAt,
2394
2474
  });
@@ -2613,22 +2693,30 @@ export class CloudflareScopeHost {
2613
2693
  }
2614
2694
  return this.buildStub(tenantId, scopeId, principal, undefined, undefined, options, undefined, undefined, undefined, options?.verifiedEmail ?? null, parsedDelegation);
2615
2695
  }
2616
- async getScopeStore(_principal, tenantId, scopeId, binding, options) {
2696
+ async getScopeStore(principal, tenantId, scopeId, binding, options) {
2697
+ // #2996 (K-64): every path spends the proof on the scope's own queue before it sends the call,
2698
+ // whatever the transport. The scope object is in this worker's own namespace on each of them.
2699
+ const redeem = async (secret, operation) => {
2700
+ unwrapReply(await this.scopeStub(scopeId).storeProofRedeemReply(secret, binding, operation, principal));
2701
+ };
2617
2702
  if (this.scopeStoreTransport === 'platform') {
2618
2703
  return {
2619
2704
  tenantId,
2620
2705
  scopeId,
2621
2706
  subjectKind: 'principal',
2622
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore({
2707
+ invoke: proofCheckedStoreInvoke({
2708
+ binding,
2709
+ redeem,
2623
2710
  // The egress hop answers with the platform's own codes too (#2815).
2624
- through: 'platform',
2625
- send: async (request) => {
2711
+ throughPlatform: true,
2712
+ send: async (request, proof) => {
2626
2713
  // #3368: the request's trace, so the call joins it through egress and the router.
2627
2714
  const trace = currentTraceparent();
2628
2715
  const response = await this.fetchImpl(STORE_CALL_URL, {
2629
2716
  method: 'POST',
2630
2717
  headers: { 'content-type': 'application/json', ...(parseTraceparent(trace) ? { [TRACEPARENT_HEADER]: trace } : {}) },
2631
- body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input }),
2718
+ // The spent proof rides along, so the router can refuse a call that did not pass this door.
2719
+ body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input, proof }),
2632
2720
  });
2633
2721
  try {
2634
2722
  return await response.json();
@@ -2637,7 +2725,8 @@ export class CloudflareScopeHost {
2637
2725
  throw new StoreError({ code: PLATFORM_STORE_CODE.badEnvelope, status: 502 });
2638
2726
  }
2639
2727
  },
2640
- }, operation, input, ...extra), options?.onStoreCall),
2728
+ onStoreCall: options?.onStoreCall,
2729
+ }),
2641
2730
  };
2642
2731
  }
2643
2732
  // A missing binding is answered before any directory read. A CP-less host's
@@ -2655,7 +2744,12 @@ export class CloudflareScopeHost {
2655
2744
  tenantId,
2656
2745
  scopeId,
2657
2746
  subjectKind: 'principal',
2658
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore((request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request), operation, input, ...extra), options?.onStoreCall),
2747
+ invoke: proofCheckedStoreInvoke({
2748
+ binding,
2749
+ redeem,
2750
+ send: (request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request),
2751
+ onStoreCall: options?.onStoreCall,
2752
+ }),
2659
2753
  };
2660
2754
  }
2661
2755
  const namespace = bound;
@@ -2665,7 +2759,7 @@ export class CloudflareScopeHost {
2665
2759
  tenantId,
2666
2760
  scopeId,
2667
2761
  subjectKind: 'principal',
2668
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore(storeObjectSend(object), operation, input, ...extra), options?.onStoreCall),
2762
+ invoke: proofCheckedStoreInvoke({ binding, redeem, send: storeObjectSend(object), onStoreCall: options?.onStoreCall }),
2669
2763
  };
2670
2764
  }
2671
2765
  /**
@@ -3140,26 +3234,59 @@ export class CloudflareScopeHost {
3140
3234
  */
3141
3235
  async deliverToPeer(tenantId, scopeId, raw) {
3142
3236
  const batch = importBatch.parse(raw);
3237
+ return this.applyImportThroughDoor(tenantId, scopeId, batch, batch.after, 'deliverToPeer', (instance) => this.scopeStub(scopeId).importApply(batch, tenantId, scopeId, instance));
3238
+ }
3239
+ /**
3240
+ * K-74 (#3492): an event another app's broker PUSHED here. `deliverToPeer`'s gates, door and
3241
+ * tail, and the ScopeDO's `importPushed`, which journals by event id and moves no watermark.
3242
+ * `source` is the caller the router verified, as the receiving broker read it.
3243
+ */
3244
+ async deliverPushedToPeer(tenantId, scopeId, raw) {
3245
+ const pushed = pushedImport.parse(raw);
3246
+ return this.applyImportThroughDoor(tenantId, scopeId, pushed, null, 'deliverPushedToPeer', (instance) => this.scopeStub(scopeId).importPushed(pushed, tenantId, scopeId, instance));
3247
+ }
3248
+ /** A pushed event (#3492) for a scope served HERE, through the peer door's gate. */
3249
+ async importPushedLocal(tenantId, scopeId, pushed) {
3250
+ await this.assertServesLocally(tenantId, scopeId, 'deliverPushedToPeer');
3251
+ return this.deliverPushedToPeer(tenantId, scopeId, pushed);
3252
+ }
3253
+ /**
3254
+ * The relay's doors over this host (#3492), for `relayScopeEnds` in the app's own broker: the
3255
+ * export read and the pushed import for a scope served HERE (`exportedEventsLocal`,
3256
+ * `importPushedLocal`), and the system door a resume target is invoked through. `requests` is
3257
+ * what the app's host code does with a request it is sent.
3258
+ */
3259
+ relayScopeDoors(requests) {
3260
+ return {
3261
+ readExports: (t, s, input) => this.exportedEventsLocal(t, s, input),
3262
+ importPushed: (t, s, pushed) => this.importPushedLocal(t, s, pushed),
3263
+ invokeAsSystem: async ({ module, tenantId: t, scopeId: s, operation, input, idempotencyKey }) => (await this.getSystemScope(module, t, s)).invoke(operation, input, { idempotencyKey }),
3264
+ ...(requests ? { requests } : {}),
3265
+ };
3266
+ }
3267
+ async applyImportThroughDoor(tenantId, scopeId, batch,
3268
+ /** The pulled batch's compare-and-set watermark, which a refusal answers with; null when pushed. */
3269
+ after, verb, apply) {
3143
3270
  // The peer door's own gate (#1706): K-3's pair check, the refusal for a scope served
3144
3271
  // elsewhere, the lifecycle check and the migration. A delivery is a write into the
3145
3272
  // consumer's scope, so it takes the gate an invoke through that door takes.
3146
- const record = await this.peerScopeGate(tenantId, scopeId, 'deliverToPeer');
3273
+ const record = await this.peerScopeGate(tenantId, scopeId, verb);
3147
3274
  // #2004: a copy consumes no other vertical's events, at the door as in the sweep
3148
3275
  // (`scope-copy.ts`). A pause: nothing runs and the watermark stays.
3149
3276
  if (await this.isInertScope(tenantId, scopeId, record)) {
3150
- return { ...emptyImportResult(batch), paused: { reason: INERT_SCOPE_REASON } };
3277
+ return { ...emptyImportResult({ after }), paused: { reason: INERT_SCOPE_REASON } };
3151
3278
  }
3152
3279
  // #2029: the producer is a peer, so the delivery goes through its door: a producer the rewind
3153
3280
  // hold keeps off pauses the edge, exactly as a switched-off one does inside the DO.
3154
3281
  const door = await this.openDoor('peer', batch.source.vertical, scopeId);
3155
3282
  let applied;
3156
3283
  try {
3157
- applied = await door.through((instance) => this.scopeStub(scopeId).importApply(batch, tenantId, scopeId, instance));
3284
+ applied = await door.through(apply);
3158
3285
  }
3159
3286
  catch (err) {
3160
3287
  if (!this.isHeldRefusal(err))
3161
3288
  throw err;
3162
- return { ...emptyImportResult(batch), paused: { reason: err.message } };
3289
+ return { ...emptyImportResult({ after }), paused: { reason: err.message } };
3163
3290
  }
3164
3291
  const result = importResult.parse(applied);
3165
3292
  if (result.delivered > 0) {
@@ -3524,7 +3651,11 @@ export class CloudflareScopeHost {
3524
3651
  }
3525
3652
  const stub = this.scopeStub(scopeId);
3526
3653
  const windows = new Map();
3527
- for (const specs of this.moduleFreshness.values()) {
3654
+ // #2993 part 3: only the modules this scope's type runs are judged on it.
3655
+ const scopeType = await this.scopeTypeAt(scopeId);
3656
+ for (const [freshnessModule, specs] of this.moduleFreshness) {
3657
+ if (!scopeTypeRuns(this.scopeTypePlan, scopeType, freshnessModule))
3658
+ continue;
3528
3659
  for (const f of specs) {
3529
3660
  const prev = windows.get(f.eventType);
3530
3661
  if (prev === undefined || f.within.hours < prev)
@@ -3614,11 +3745,40 @@ export class CloudflareScopeHost {
3614
3745
  // cap refuses (`runPurgePass`): this call's, on top of what the tick's earlier calls report.
3615
3746
  const earlierPurgeRequests = tick?.earlierPurgeRequests ?? 0;
3616
3747
  let purgeRequests = 0;
3748
+ // #3540: what this call is — the scope's own alarm, which runs only the purges it found due, or a
3749
+ // pass, which tells the scope whether its sweeper can take that alarm's call (`purgeMode`).
3750
+ // `dueAlarm` is the same alarm, through `runScopeDue`, which also asks for its due schedules.
3751
+ const alarm = tick?.purgeAlarm === true || tick?.dueAlarm === true;
3752
+ const purgeMode = alarm ? 'alarm' : tick?.alarmRunsPurges ? 'deferrable' : undefined;
3617
3753
  for (const schedule of schedules) {
3618
- const last = await stub.scheduleLastRun(schedule.operation);
3754
+ if (tick?.purgeAlarm && !schedule.purge)
3755
+ continue;
3756
+ // #3540: a `due: 'event'` schedule is the scope's to place — its alarm runs it once it has run
3757
+ // under that form — wherever the caller can take that alarm's call; its cadence decides otherwise.
3758
+ const byEvent = !schedule.purge && schedule.due === 'event';
3759
+ if (tick?.dueAlarm && !schedule.purge && !byEvent)
3760
+ continue;
3761
+ let byDate;
3762
+ let last;
3763
+ if (byEvent && (tick?.dueAlarm || tick?.alarmRunsDue)) {
3764
+ const gate = await stub.dueScheduleGate(schedule.operation, tenantId, scopeId, tick.dueAlarm ? 'alarm' : 'deferrable');
3765
+ if (gate.byAlarm || (tick.dueAlarm && (gate.dueAt === null || now < gate.dueAt))) {
3766
+ // Its alarm runs it, or it is not due by its date: nothing ran, no line, no cadence row.
3767
+ report.skipped += 1;
3768
+ report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3769
+ continue;
3770
+ }
3771
+ if (tick.dueAlarm)
3772
+ byDate = gate.dueAt;
3773
+ last = gate.lastRunAt;
3774
+ }
3775
+ else {
3776
+ last = await stub.scheduleLastRun(schedule.operation);
3777
+ }
3619
3778
  const lastRun = last ? Date.parse(last) : null;
3620
- const dueAt = lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
3621
- if (now < dueAt) {
3779
+ const dueAt = byDate ?? (lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000);
3780
+ // #3540: the scope's alarm found the purge due by its rows, so the cadence does not gate it.
3781
+ if (now < dueAt && !(alarm && schedule.purge)) {
3622
3782
  report.skipped += 1;
3623
3783
  report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3624
3784
  continue;
@@ -3652,7 +3812,13 @@ export class CloudflareScopeHost {
3652
3812
  // and the deliveries their events route to the platform are counted below, as an invoke's are.
3653
3813
  // #2517: with what the purge runs before this one in the tick enqueued, so a head the cap
3654
3814
  // refuses because they filled the queue is deferred to the next tick rather than failed.
3655
- const pass = await door.through((instance) => stub.runPurgeSweep(schedule.operation, tenantId, scopeId, instance, invocationId, earlierPurgeRequests + purgeRequests));
3815
+ const pass = await door.through((instance) => stub.runPurgeSweep(schedule.operation, tenantId, scopeId, instance, invocationId, earlierPurgeRequests + purgeRequests, purgeMode));
3816
+ if (pass.byAlarm) {
3817
+ // #3540: the scope's own alarm runs it. Nothing ran here: no line, no cadence row.
3818
+ report.skipped += 1;
3819
+ report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3820
+ continue;
3821
+ }
3656
3822
  if (pass.deferred) {
3657
3823
  // Ran nothing: no line, no cadence row, `skipped` like any run that did not happen.
3658
3824
  report.skipped += 1;
@@ -3705,8 +3871,8 @@ export class CloudflareScopeHost {
3705
3871
  startedAt,
3706
3872
  outcome: status,
3707
3873
  ...failure,
3708
- dueAt: lastRun === null ? null : new Date(dueAt).toISOString(),
3709
- latenessMs: lastRun === null ? null : now - dueAt,
3874
+ dueAt: byDate === undefined && lastRun === null ? null : new Date(dueAt).toISOString(),
3875
+ latenessMs: byDate === undefined && lastRun === null ? null : now - dueAt,
3710
3876
  ...(emitted ? { emitted } : {}),
3711
3877
  });
3712
3878
  report.runs.push({ operation: schedule.operation, outcome: status === 'ok' ? 'ok' : 'failed' });
@@ -3994,6 +4160,7 @@ export class CloudflareScopeHost {
3994
4160
  previewTraceSampling: r.preview_trace_sampling ?? 0,
3995
4161
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
3996
4162
  ...(r.serving_version_id ? { servingVersionId: r.serving_version_id } : {}),
4163
+ ...(r.earlier_majors ? { earlierMajors: earlierMajorsOf(r.earlier_majors) } : {}),
3997
4164
  createdAt: r.created_at,
3998
4165
  });
3999
4166
  // A listed version carries its surfaces as lifted JSON text, not its manifest (#1677):
@@ -4075,6 +4242,8 @@ export class CloudflareScopeHost {
4075
4242
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
4076
4243
  archivedAt: r.archived_at ?? null,
4077
4244
  archivedFromStatus: (r.archived_from_status ?? null),
4245
+ // #2993: a typed scope names its type; a home scope's record (NULL) is unchanged.
4246
+ ...(r.scope_type ? { scopeType: r.scope_type } : {}),
4078
4247
  createdAt: r.created_at,
4079
4248
  });
4080
4249
  // The directory rows `listScopes` and `listScopesReadable` map, filtered and paged alike.
@@ -5179,6 +5348,32 @@ export class CloudflareScopeHost {
5179
5348
  throw substratError(answer.code, answer.message);
5180
5349
  return { changed: answer.changed, previous: answer.previous };
5181
5350
  },
5351
+ // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
5352
+ listEnvironments: async (actor, tenantId, vertical) => {
5353
+ const rows = await this.cp.listEnvironments(tenantId, verticalSlug.parse(vertical));
5354
+ await this.recordAccess(actor, 'listEnvironments', { tenantId }, { vertical }, rows.length);
5355
+ return rows.map((r) => appEnvironmentSchema.parse(r));
5356
+ },
5357
+ defineEnvironment: async (actor, input) => {
5358
+ const vertical = verticalSlug.parse(input.vertical);
5359
+ const out = await this.directory('defineEnvironmentAndAudit', { ...input, vertical }, actor, this.adminEntry(actor, 'defineEnvironment', { tenantId: input.tenantId, vertical }, null, null));
5360
+ return { environment: appEnvironmentSchema.parse(out.environment), created: out.created };
5361
+ },
5362
+ removeEnvironment: async (actor, input) => {
5363
+ const vertical = verticalSlug.parse(input.vertical);
5364
+ return this.directory('removeEnvironmentAndAudit', { ...input, vertical }, this.adminEntry(actor, 'removeEnvironment', { tenantId: input.tenantId, vertical }, null, null));
5365
+ },
5366
+ claimEnvironmentServe: async (_actor, input, claim, leaseMs) => this.directory('claimEnvironmentServe', { ...input, vertical: verticalSlug.parse(input.vertical) }, claim, leaseMs),
5367
+ releaseEnvironmentServe: async (_actor, input, claim) => {
5368
+ await this.cp.releaseEnvironmentServe({ ...input, vertical: verticalSlug.parse(input.vertical) }, claim);
5369
+ },
5370
+ setEnvironmentServing: async (actor, input, next, expected, claim) => {
5371
+ 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);
5373
+ if (!moved) {
5374
+ 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
+ }
5376
+ },
5182
5377
  resolveHostname: async (raw) =>
5183
5378
  // The router's per-request read. No actor, not logged — the same machine-path
5184
5379
  // carve-out resolveIdentity has (K-24). Shares its mapping with the router's
@@ -5390,6 +5585,22 @@ export class CloudflareScopeHost {
5390
5585
  ], incoming.id, incoming, served || owned.length > 0
5391
5586
  ? await this.cp.provisionedVersionsOf(verticalSlug, served, owned.length > 0 ? owning.owner_tenant : null)
5392
5587
  : []);
5588
+ // #3539 (K-65): a listed app takes no breaking change within its major. Ranked against what
5589
+ // the channel names and what the serving script runs (a failed serve leaves it behind), by
5590
+ // the rules `substrat changeset` writes with. Ahead of the acknowledgements, because none of
5591
+ // them passes it. Refused here when the vertical is listed as read above, and judged again in
5592
+ // the unit that moves the channel, so a listing that lands meanwhile is seen (#2565).
5593
+ const breakingWithinMajor = channel === 'prod'
5594
+ ? await this.releaseWithinMajor(verticalSlug, [outgoing, served ? await this.cp.readVersion(served.versionId) : undefined], incoming,
5595
+ // #3539 part 2: a new major is served beside the old one only by a caller that serves
5596
+ // in place, and only from a version with an archive script to serve from.
5597
+ options?.servesMajors === true && incoming.deployment_ref !== null)
5598
+ : null;
5599
+ if (breakingWithinMajor && owning?.listed)
5600
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
5601
+ // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
5602
+ // of the acknowledgements, because none of them passes it.
5603
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
5393
5604
  // #2333: the acknowledgements answer the review they were given against, or none at all.
5394
5605
  const reviewed = async (v) => ({
5395
5606
  id: v.id,
@@ -5439,7 +5650,7 @@ export class CloudflareScopeHost {
5439
5650
  from_version_id: outgoing?.id ?? null,
5440
5651
  actor,
5441
5652
  at: promotedAt,
5442
- }, options?.unlistedOnly === true, this.adminEntry(actor, 'promoteVersion', { tenantId: null, vertical: verticalSlug }, outgoing ? { versionId: outgoing.id, version: outgoing.version } : null, { channel, versionId, version: incoming.version, acknowledged: ack }));
5653
+ }, options?.unlistedOnly === true, this.adminEntry(actor, 'promoteVersion', { tenantId: null, vertical: verticalSlug }, outgoing ? { versionId: outgoing.id, version: outgoing.version } : null, { channel, versionId, version: incoming.version, acknowledged: ack }), breakingWithinMajor);
5443
5654
  if (!moved)
5444
5655
  throw promoteRaceRefusal(channel);
5445
5656
  // For a PRIVATE vertical, prod IS what the owner's apps run: re-point the
@@ -5628,20 +5839,32 @@ export class CloudflareScopeHost {
5628
5839
  versionId: r.serving_version_id,
5629
5840
  doClasses: r.serving_do_classes ? JSON.parse(r.serving_do_classes) : [],
5630
5841
  migrationTag: r.serving_migration_tag,
5842
+ // K-65 (#3539 part 2): what each earlier major's script runs.
5843
+ ...(r.earlier_majors
5844
+ ? { earlier: earlierMajorsOf(r.earlier_majors).map((m) => ({ ref: m.ref, versionId: m.versionId })) }
5845
+ : {}),
5631
5846
  });
5632
5847
  },
5633
- setVerticalServing: async (actor, verticalSlug, state, expected) => {
5848
+ setVerticalServing: async (actor, verticalSlug, state, expected, opts) => {
5634
5849
  const parsed = verticalServingState.parse(state);
5850
+ const supersede = opts?.supersede;
5635
5851
  const r = await this.cp.readVertical(verticalSlug);
5636
5852
  if (!r)
5637
5853
  throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
5638
5854
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
5639
5855
  if (expected !== undefined && !migratesFrom(r, expected))
5640
5856
  throw servingRaceRefusal(verticalSlug);
5641
- // #2178: every install on the serving script runs the new version from this moment.
5642
- if (r.serving_version_id) {
5857
+ // K-65 (#3539 part 2): a new major supersedes exactly the serving state the caller read.
5858
+ if (supersede && (!expected || expected.ref !== r.serving_ref || expected.versionId !== r.serving_version_id)) {
5859
+ throw servingRaceRefusal(verticalSlug);
5860
+ }
5861
+ // #2178: every install on the serving script runs the new version from this moment. A new
5862
+ // major's first serve moves nobody onto its script: the installs stay on the earlier one.
5863
+ if (r.serving_version_id && !supersede) {
5643
5864
  const incoming = await this.cp.readVersion(parsed.versionId);
5644
5865
  if (incoming) {
5866
+ // #2993 part 4: and it declares every type their scopes hold.
5867
+ assertScopeTypesKept(verticalSlug, await this.cp.scopeTypesHeldBy(verticalSlug), incoming.manifest_json);
5645
5868
  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) : []);
5646
5869
  }
5647
5870
  }
@@ -5653,7 +5876,10 @@ export class CloudflareScopeHost {
5653
5876
  versionId: parsed.versionId,
5654
5877
  doClassesJson: JSON.stringify(parsed.doClasses),
5655
5878
  migrationTag: parsed.migrationTag,
5656
- }, this.adminEntry(actor, 'setVerticalServing', { tenantId: null }, null, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId }), servedFromRow(r));
5879
+ }, this.adminEntry(actor, 'setVerticalServing', { tenantId: null }, null, {
5880
+ vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId,
5881
+ ...(supersede ? { supersedes: { major: supersede.major, endsAt: supersede.endsAt } } : {}),
5882
+ }), servedFromRow(r), supersede);
5657
5883
  if (!moved)
5658
5884
  throw servingRaceRefusal(verticalSlug);
5659
5885
  },
@@ -8457,6 +8683,9 @@ export class CloudflareScopeHost {
8457
8683
  */
8458
8684
  async provisionScopeLocal(input) {
8459
8685
  const carry = recordedOffFromWire(input);
8686
+ // #2993 part 3: first, before anything can migrate the scope: its first pass must lay down only
8687
+ // its type's tables. A refused type writes nothing. A host and a call that name no type ask nothing.
8688
+ const scopeType = await this.scopeTypeAt(input.scopeId, input.scopeType);
8460
8689
  // #2430: refused before anything is written, rather than at the top-up after the projection.
8461
8690
  if (input.entityGrants)
8462
8691
  await this.refuseReservedShapes(input.entityGrants, input.scopeId);
@@ -8507,7 +8736,7 @@ export class CloudflareScopeHost {
8507
8736
  expires_at: null,
8508
8737
  lockout_reseat: true,
8509
8738
  },
8510
- ...this.declaredSeatsLocal(input.scopeId, connections.seat),
8739
+ ...this.declaredSeatsLocal(input.scopeId, connections.seat, scopeType),
8511
8740
  ],
8512
8741
  // #406: identity links, delivered by the platform with provisioning exactly as
8513
8742
  // entitlements are (#310). Preserve-on-undefined, so an absent field never wipes
@@ -8539,6 +8768,7 @@ export class CloudflareScopeHost {
8539
8768
  ? await this.topUpEntityGrantShapesLocal(input.tenantId, input.scopeId, input.entityGrants)
8540
8769
  : null;
8541
8770
  return {
8771
+ ...(input.scopeType !== undefined ? { scopeType } : {}),
8542
8772
  ...(carry ? { switchedOff } : {}),
8543
8773
  ...(shapes ? { retirementsLeftOpen: shapes.retirementsLeftOpen ?? 0 } : {}),
8544
8774
  ...(shapes?.boundEver ? { boundShapeTypes: shapes.boundEver } : {}),
@@ -8795,16 +9025,18 @@ export class CloudflareScopeHost {
8795
9025
  * function that decides them), and the tenant's connection grants the platform delivered (#592,
8796
9026
  * the provision-time mirror of `connectorGrantLocal`).
8797
9027
  */
8798
- declaredSeatsLocal(scopeId, connectionGrants) {
9028
+ declaredSeatsLocal(scopeId, connectionGrants,
9029
+ /** #2993 part 3: only the modules this type runs seat their schedule and peer grants. */
9030
+ scopeType) {
8799
9031
  return [
8800
- ...[...this.moduleSchedules].flatMap(([modId, schedules]) => {
9032
+ ...[...this.moduleSchedules].filter(([modId]) => scopeTypeRuns(this.scopeTypePlan, scopeType, modId)).flatMap(([modId, schedules]) => {
8801
9033
  const perms = new Set();
8802
9034
  for (const s of schedules)
8803
9035
  for (const p of s.permissions)
8804
9036
  perms.add(p);
8805
9037
  return [...perms].map((perm) => ({ subject: `system:${modId}`, relation: `granted:${perm}`, object: `scope:${scopeId}`, expires_at: null }));
8806
9038
  }),
8807
- ...peerSeats(collectPeers(this.peerSources), scopeId).map((seat) => ({ ...seat, expires_at: null })),
9039
+ ...peerSeats(collectPeers(this.peerSourcesOf(scopeType)), scopeId).map((seat) => ({ ...seat, expires_at: null })),
8808
9040
  ...(connectionGrants ?? []).map((g) => ({
8809
9041
  subject: `connection:${g.connectionId}`,
8810
9042
  relation: `granted:${g.permission}`,
@@ -8837,7 +9069,9 @@ export class CloudflareScopeHost {
8837
9069
  const carry = recordedOffFromWire(input);
8838
9070
  const connections = await this.seatableConnectionGrants(input.tenantId, input.scopeId, input.connectionGrants); // #2430
8839
9071
  await this.migrateAndRecord(input.scopeId);
8840
- const seated = await stub.seatTuplesFor(input.tenantId, this.declaredSeatsLocal(input.scopeId, connections.seat), carry ? { scopeId: input.scopeId, at: new Date().toISOString(), ...carry } : undefined);
9072
+ const seated = await stub.seatTuplesFor(input.tenantId,
9073
+ // #2993 part 3: the type the scope holds; this seat never names one.
9074
+ this.declaredSeatsLocal(input.scopeId, connections.seat, await this.scopeTypeAt(input.scopeId)), carry ? { scopeId: input.scopeId, at: new Date().toISOString(), ...carry } : undefined);
8841
9075
  // Reaped or recorded for another tenant since the check: K-3's refusal, naming no other tenant.
8842
9076
  if ('refused' in seated)
8843
9077
  throw unknownScopeForTenant(input.tenantId, input.scopeId);
@@ -9359,7 +9593,29 @@ export class CloudflareScopeHost {
9359
9593
  */
9360
9594
  async servingPointerOf(scope, servingRef) {
9361
9595
  const vertical = scope.vertical && (scope.servingRef || servingRef) ? await this.cp.readVertical(scope.vertical) : undefined;
9362
- return vertical?.serving_ref && vertical.serving_version_id ? { ref: vertical.serving_ref, versionId: vertical.serving_version_id } : null;
9596
+ if (!vertical?.serving_ref || !vertical.serving_version_id)
9597
+ return null;
9598
+ // K-65 (#3539 part 2): an install on an earlier major runs that major's version.
9599
+ const earlier = earlierMajorsOf(vertical.earlier_majors).map((m) => ({ ref: m.ref, versionId: m.versionId }));
9600
+ return { ref: vertical.serving_ref, versionId: vertical.serving_version_id, ...(earlier.length ? { earlier } : {}) };
9601
+ }
9602
+ /**
9603
+ * #3539 (K-65): the refusal promoting `incoming` over any of `bases` earns if the vertical is
9604
+ * listed, each distinct version judged once, or null. The first that refuses is the one named.
9605
+ */
9606
+ async releaseWithinMajor(vertical, bases, incoming, servesMajors = false) {
9607
+ const side = (v) => ({ id: v.id, version: v.version, manifestJson: v.manifest_json });
9608
+ const seen = new Set();
9609
+ const distinct = bases.filter((b) => !!b && !seen.has(b.id) && !!seen.add(b.id));
9610
+ // A first promote (nothing named, nothing served) is judged against nothing.
9611
+ if (distinct.length === 0)
9612
+ return null;
9613
+ for (const base of distinct) {
9614
+ const refusal = releaseWithinMajorRefusal({ vertical, base: side(base), head: side(incoming), classify: classifyRelease, servesMajors });
9615
+ if (refusal)
9616
+ return refusal;
9617
+ }
9618
+ return null;
9363
9619
  }
9364
9620
  /** #2178: refuse running `incoming` where any of `froms` ran, each distinct version judged once. */
9365
9621
  async assertNoStrandFrom(froms, afterId, held, receipts = []) {