@substrat-run/adapter-cloudflare 0.218.0 → 0.220.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 +69 -5
  2. package/dist/control-plane-do.d.ts.map +1 -1
  3. package/dist/control-plane-do.js +126 -9
  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 +7 -1
  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 +3 -1
  27. package/dist/directory-split-inventory.js.map +1 -1
  28. package/dist/host.d.ts +39 -6
  29. package/dist/host.d.ts.map +1 -1
  30. package/dist/host.js +136 -15
  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 +37 -1
  36. package/dist/route-read-model-publisher.d.ts.map +1 -1
  37. package/dist/route-read-model-publisher.js +127 -44
  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 +31 -1
  44. package/dist/scope-do.d.ts.map +1 -1
  45. package/dist/scope-do.js +235 -24
  46. package/dist/scope-do.js.map +1 -1
  47. package/dist/scope-sweeper-do.d.ts +18 -0
  48. package/dist/scope-sweeper-do.d.ts.map +1 -1
  49. package/dist/scope-sweeper-do.js +72 -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,12 +2,14 @@ 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, 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, kernelJobFor, attachmentTextBackfillJob, 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, 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
13
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
12
14
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
13
15
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
@@ -926,10 +928,16 @@ export class CloudflareScopeHost {
926
928
  // deployment registers them, and none can shadow them. The backfill starts here, on
927
929
  // the drive, so a scope's first request never pays for attachments that predate it.
928
930
  const stub = this.scopeStub(scopeId);
929
- await stub.attachmentTextBackfillStart();
931
+ // The recheck likewise, in the same request, once per change of extractor set: what an
932
+ // older set recorded `unsupported` and this one reads is queued again (`startAttachmentTextRecheck`).
933
+ await stub.attachmentTextBackfillStart(attachmentExtractorSetKey(this.attachmentExtractors));
930
934
  const kernelJobs = {
931
935
  [ATTACHMENT_TEXT_JOB]: this.attachmentTextHandler(tenantId, scopeId),
932
936
  [ATTACHMENT_TEXT_BACKFILL_JOB]: attachmentTextBackfillJob({ queueBatch: (after) => stub.attachmentTextBackfillBatch(after) }),
937
+ [ATTACHMENT_TEXT_RECHECK_JOB]: attachmentTextRecheckJob({
938
+ page: (after) => stub.attachmentTextRecheckPage(after),
939
+ requeue: (ids) => stub.attachmentTextRequeueUnsupported(ids),
940
+ }, this.attachmentExtractors),
933
941
  };
934
942
  // #1834: the door is opened FOR a pass, so its "not now" is tied to that pass alone. #3443: one
935
943
  // door per pass, shared by `pass.scope()` and `pass.attachments()` — one gate, one answer.
@@ -1917,6 +1925,10 @@ export class CloudflareScopeHost {
1917
1925
  async provisionScopeCreating(actor, input) {
1918
1926
  // Shared with the pure adapter so the defaults cannot drift between them.
1919
1927
  const record = resolveScopeRecord(input);
1928
+ // #2993: this host runs no declared scope types yet, so it takes 'home' and refuses any
1929
+ // other type, by the kernel's rule, before anything is written. A typed scope provisioned
1930
+ // here as 'home' would carry the wrong modules for its life.
1931
+ provisionedScopeType({ declared: false }, input.scopeType, undefined, input.scopeId);
1920
1932
  // Fail-closed tenant gate throws out of the awaited cp call BEFORE migrate
1921
1933
  // or audit, so a rejected provision creates nothing and writes no audit row.
1922
1934
  const created = await this.directory('provisionScope', input.tenantId, input.scopeId, record, new Date().toISOString());
@@ -3134,26 +3146,59 @@ export class CloudflareScopeHost {
3134
3146
  */
3135
3147
  async deliverToPeer(tenantId, scopeId, raw) {
3136
3148
  const batch = importBatch.parse(raw);
3149
+ return this.applyImportThroughDoor(tenantId, scopeId, batch, batch.after, 'deliverToPeer', (instance) => this.scopeStub(scopeId).importApply(batch, tenantId, scopeId, instance));
3150
+ }
3151
+ /**
3152
+ * K-74 (#3492): an event another app's broker PUSHED here. `deliverToPeer`'s gates, door and
3153
+ * tail, and the ScopeDO's `importPushed`, which journals by event id and moves no watermark.
3154
+ * `source` is the caller the router verified, as the receiving broker read it.
3155
+ */
3156
+ async deliverPushedToPeer(tenantId, scopeId, raw) {
3157
+ const pushed = pushedImport.parse(raw);
3158
+ return this.applyImportThroughDoor(tenantId, scopeId, pushed, null, 'deliverPushedToPeer', (instance) => this.scopeStub(scopeId).importPushed(pushed, tenantId, scopeId, instance));
3159
+ }
3160
+ /** A pushed event (#3492) for a scope served HERE, through the peer door's gate. */
3161
+ async importPushedLocal(tenantId, scopeId, pushed) {
3162
+ await this.assertServesLocally(tenantId, scopeId, 'deliverPushedToPeer');
3163
+ return this.deliverPushedToPeer(tenantId, scopeId, pushed);
3164
+ }
3165
+ /**
3166
+ * The relay's doors over this host (#3492), for `relayScopeEnds` in the app's own broker: the
3167
+ * export read and the pushed import for a scope served HERE (`exportedEventsLocal`,
3168
+ * `importPushedLocal`), and the system door a resume target is invoked through. `requests` is
3169
+ * what the app's host code does with a request it is sent.
3170
+ */
3171
+ relayScopeDoors(requests) {
3172
+ return {
3173
+ readExports: (t, s, input) => this.exportedEventsLocal(t, s, input),
3174
+ importPushed: (t, s, pushed) => this.importPushedLocal(t, s, pushed),
3175
+ invokeAsSystem: async ({ module, tenantId: t, scopeId: s, operation, input, idempotencyKey }) => (await this.getSystemScope(module, t, s)).invoke(operation, input, { idempotencyKey }),
3176
+ ...(requests ? { requests } : {}),
3177
+ };
3178
+ }
3179
+ async applyImportThroughDoor(tenantId, scopeId, batch,
3180
+ /** The pulled batch's compare-and-set watermark, which a refusal answers with; null when pushed. */
3181
+ after, verb, apply) {
3137
3182
  // The peer door's own gate (#1706): K-3's pair check, the refusal for a scope served
3138
3183
  // elsewhere, the lifecycle check and the migration. A delivery is a write into the
3139
3184
  // consumer's scope, so it takes the gate an invoke through that door takes.
3140
- const record = await this.peerScopeGate(tenantId, scopeId, 'deliverToPeer');
3185
+ const record = await this.peerScopeGate(tenantId, scopeId, verb);
3141
3186
  // #2004: a copy consumes no other vertical's events, at the door as in the sweep
3142
3187
  // (`scope-copy.ts`). A pause: nothing runs and the watermark stays.
3143
3188
  if (await this.isInertScope(tenantId, scopeId, record)) {
3144
- return { ...emptyImportResult(batch), paused: { reason: INERT_SCOPE_REASON } };
3189
+ return { ...emptyImportResult({ after }), paused: { reason: INERT_SCOPE_REASON } };
3145
3190
  }
3146
3191
  // #2029: the producer is a peer, so the delivery goes through its door: a producer the rewind
3147
3192
  // hold keeps off pauses the edge, exactly as a switched-off one does inside the DO.
3148
3193
  const door = await this.openDoor('peer', batch.source.vertical, scopeId);
3149
3194
  let applied;
3150
3195
  try {
3151
- applied = await door.through((instance) => this.scopeStub(scopeId).importApply(batch, tenantId, scopeId, instance));
3196
+ applied = await door.through(apply);
3152
3197
  }
3153
3198
  catch (err) {
3154
3199
  if (!this.isHeldRefusal(err))
3155
3200
  throw err;
3156
- return { ...emptyImportResult(batch), paused: { reason: err.message } };
3201
+ return { ...emptyImportResult({ after }), paused: { reason: err.message } };
3157
3202
  }
3158
3203
  const result = importResult.parse(applied);
3159
3204
  if (result.delivered > 0) {
@@ -3608,11 +3653,17 @@ export class CloudflareScopeHost {
3608
3653
  // cap refuses (`runPurgePass`): this call's, on top of what the tick's earlier calls report.
3609
3654
  const earlierPurgeRequests = tick?.earlierPurgeRequests ?? 0;
3610
3655
  let purgeRequests = 0;
3656
+ // #3540: what this call is — the scope's own alarm, which runs only the purges it found due, or a
3657
+ // pass, which tells the scope whether its sweeper can take that alarm's call (`purgeMode`).
3658
+ const purgeMode = tick?.purgeAlarm ? 'alarm' : tick?.alarmRunsPurges ? 'deferrable' : undefined;
3611
3659
  for (const schedule of schedules) {
3660
+ if (tick?.purgeAlarm && !schedule.purge)
3661
+ continue;
3612
3662
  const last = await stub.scheduleLastRun(schedule.operation);
3613
3663
  const lastRun = last ? Date.parse(last) : null;
3614
3664
  const dueAt = lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
3615
- if (now < dueAt) {
3665
+ // #3540: the scope's alarm found the purge due by its rows, so the cadence does not gate it.
3666
+ if (now < dueAt && !tick?.purgeAlarm) {
3616
3667
  report.skipped += 1;
3617
3668
  report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3618
3669
  continue;
@@ -3646,7 +3697,13 @@ export class CloudflareScopeHost {
3646
3697
  // and the deliveries their events route to the platform are counted below, as an invoke's are.
3647
3698
  // #2517: with what the purge runs before this one in the tick enqueued, so a head the cap
3648
3699
  // refuses because they filled the queue is deferred to the next tick rather than failed.
3649
- const pass = await door.through((instance) => stub.runPurgeSweep(schedule.operation, tenantId, scopeId, instance, invocationId, earlierPurgeRequests + purgeRequests));
3700
+ const pass = await door.through((instance) => stub.runPurgeSweep(schedule.operation, tenantId, scopeId, instance, invocationId, earlierPurgeRequests + purgeRequests, purgeMode));
3701
+ if (pass.byAlarm) {
3702
+ // #3540: the scope's own alarm runs it. Nothing ran here: no line, no cadence row.
3703
+ report.skipped += 1;
3704
+ report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
3705
+ continue;
3706
+ }
3650
3707
  if (pass.deferred) {
3651
3708
  // Ran nothing: no line, no cadence row, `skipped` like any run that did not happen.
3652
3709
  report.skipped += 1;
@@ -3988,6 +4045,7 @@ export class CloudflareScopeHost {
3988
4045
  previewTraceSampling: r.preview_trace_sampling ?? 0,
3989
4046
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
3990
4047
  ...(r.serving_version_id ? { servingVersionId: r.serving_version_id } : {}),
4048
+ ...(r.earlier_majors ? { earlierMajors: earlierMajorsOf(r.earlier_majors) } : {}),
3991
4049
  createdAt: r.created_at,
3992
4050
  });
3993
4051
  // A listed version carries its surfaces as lifted JSON text, not its manifest (#1677):
@@ -5173,6 +5231,21 @@ export class CloudflareScopeHost {
5173
5231
  throw substratError(answer.code, answer.message);
5174
5232
  return { changed: answer.changed, previous: answer.previous };
5175
5233
  },
5234
+ // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
5235
+ listEnvironments: async (actor, tenantId, vertical) => {
5236
+ const rows = await this.cp.listEnvironments(tenantId, verticalSlug.parse(vertical));
5237
+ await this.recordAccess(actor, 'listEnvironments', { tenantId }, { vertical }, rows.length);
5238
+ return rows.map((r) => appEnvironmentSchema.parse(r));
5239
+ },
5240
+ defineEnvironment: async (actor, input) => {
5241
+ const vertical = verticalSlug.parse(input.vertical);
5242
+ const out = await this.directory('defineEnvironmentAndAudit', { ...input, vertical }, actor, this.adminEntry(actor, 'defineEnvironment', { tenantId: input.tenantId, vertical }, null, null));
5243
+ return { environment: appEnvironmentSchema.parse(out.environment), created: out.created };
5244
+ },
5245
+ removeEnvironment: async (actor, input) => {
5246
+ const vertical = verticalSlug.parse(input.vertical);
5247
+ return this.directory('removeEnvironmentAndAudit', { ...input, vertical }, this.adminEntry(actor, 'removeEnvironment', { tenantId: input.tenantId, vertical }, null, null));
5248
+ },
5176
5249
  resolveHostname: async (raw) =>
5177
5250
  // The router's per-request read. No actor, not logged — the same machine-path
5178
5251
  // carve-out resolveIdentity has (K-24). Shares its mapping with the router's
@@ -5384,6 +5457,19 @@ export class CloudflareScopeHost {
5384
5457
  ], incoming.id, incoming, served || owned.length > 0
5385
5458
  ? await this.cp.provisionedVersionsOf(verticalSlug, served, owned.length > 0 ? owning.owner_tenant : null)
5386
5459
  : []);
5460
+ // #3539 (K-65): a listed app takes no breaking change within its major. Ranked against what
5461
+ // the channel names and what the serving script runs (a failed serve leaves it behind), by
5462
+ // the rules `substrat changeset` writes with. Ahead of the acknowledgements, because none of
5463
+ // them passes it. Refused here when the vertical is listed as read above, and judged again in
5464
+ // the unit that moves the channel, so a listing that lands meanwhile is seen (#2565).
5465
+ const breakingWithinMajor = channel === 'prod'
5466
+ ? await this.releaseWithinMajor(verticalSlug, [outgoing, served ? await this.cp.readVersion(served.versionId) : undefined], incoming,
5467
+ // #3539 part 2: a new major is served beside the old one only by a caller that serves
5468
+ // in place, and only from a version with an archive script to serve from.
5469
+ options?.servesMajors === true && incoming.deployment_ref !== null)
5470
+ : null;
5471
+ if (breakingWithinMajor && owning?.listed)
5472
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
5387
5473
  // #2333: the acknowledgements answer the review they were given against, or none at all.
5388
5474
  const reviewed = async (v) => ({
5389
5475
  id: v.id,
@@ -5433,7 +5519,7 @@ export class CloudflareScopeHost {
5433
5519
  from_version_id: outgoing?.id ?? null,
5434
5520
  actor,
5435
5521
  at: promotedAt,
5436
- }, 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 }));
5522
+ }, 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);
5437
5523
  if (!moved)
5438
5524
  throw promoteRaceRefusal(channel);
5439
5525
  // For a PRIVATE vertical, prod IS what the owner's apps run: re-point the
@@ -5622,18 +5708,28 @@ export class CloudflareScopeHost {
5622
5708
  versionId: r.serving_version_id,
5623
5709
  doClasses: r.serving_do_classes ? JSON.parse(r.serving_do_classes) : [],
5624
5710
  migrationTag: r.serving_migration_tag,
5711
+ // K-65 (#3539 part 2): what each earlier major's script runs.
5712
+ ...(r.earlier_majors
5713
+ ? { earlier: earlierMajorsOf(r.earlier_majors).map((m) => ({ ref: m.ref, versionId: m.versionId })) }
5714
+ : {}),
5625
5715
  });
5626
5716
  },
5627
- setVerticalServing: async (actor, verticalSlug, state, expected) => {
5717
+ setVerticalServing: async (actor, verticalSlug, state, expected, opts) => {
5628
5718
  const parsed = verticalServingState.parse(state);
5719
+ const supersede = opts?.supersede;
5629
5720
  const r = await this.cp.readVertical(verticalSlug);
5630
5721
  if (!r)
5631
5722
  throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
5632
5723
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
5633
5724
  if (expected !== undefined && !migratesFrom(r, expected))
5634
5725
  throw servingRaceRefusal(verticalSlug);
5635
- // #2178: every install on the serving script runs the new version from this moment.
5636
- if (r.serving_version_id) {
5726
+ // K-65 (#3539 part 2): a new major supersedes exactly the serving state the caller read.
5727
+ if (supersede && (!expected || expected.ref !== r.serving_ref || expected.versionId !== r.serving_version_id)) {
5728
+ throw servingRaceRefusal(verticalSlug);
5729
+ }
5730
+ // #2178: every install on the serving script runs the new version from this moment. A new
5731
+ // major's first serve moves nobody onto its script: the installs stay on the earlier one.
5732
+ if (r.serving_version_id && !supersede) {
5637
5733
  const incoming = await this.cp.readVersion(parsed.versionId);
5638
5734
  if (incoming) {
5639
5735
  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) : []);
@@ -5647,7 +5743,10 @@ export class CloudflareScopeHost {
5647
5743
  versionId: parsed.versionId,
5648
5744
  doClassesJson: JSON.stringify(parsed.doClasses),
5649
5745
  migrationTag: parsed.migrationTag,
5650
- }, this.adminEntry(actor, 'setVerticalServing', { tenantId: null }, null, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId }), servedFromRow(r));
5746
+ }, this.adminEntry(actor, 'setVerticalServing', { tenantId: null }, null, {
5747
+ vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId,
5748
+ ...(supersede ? { supersedes: { major: supersede.major, endsAt: supersede.endsAt } } : {}),
5749
+ }), servedFromRow(r), supersede);
5651
5750
  if (!moved)
5652
5751
  throw servingRaceRefusal(verticalSlug);
5653
5752
  },
@@ -9353,7 +9452,29 @@ export class CloudflareScopeHost {
9353
9452
  */
9354
9453
  async servingPointerOf(scope, servingRef) {
9355
9454
  const vertical = scope.vertical && (scope.servingRef || servingRef) ? await this.cp.readVertical(scope.vertical) : undefined;
9356
- return vertical?.serving_ref && vertical.serving_version_id ? { ref: vertical.serving_ref, versionId: vertical.serving_version_id } : null;
9455
+ if (!vertical?.serving_ref || !vertical.serving_version_id)
9456
+ return null;
9457
+ // K-65 (#3539 part 2): an install on an earlier major runs that major's version.
9458
+ const earlier = earlierMajorsOf(vertical.earlier_majors).map((m) => ({ ref: m.ref, versionId: m.versionId }));
9459
+ return { ref: vertical.serving_ref, versionId: vertical.serving_version_id, ...(earlier.length ? { earlier } : {}) };
9460
+ }
9461
+ /**
9462
+ * #3539 (K-65): the refusal promoting `incoming` over any of `bases` earns if the vertical is
9463
+ * listed, each distinct version judged once, or null. The first that refuses is the one named.
9464
+ */
9465
+ async releaseWithinMajor(vertical, bases, incoming, servesMajors = false) {
9466
+ const side = (v) => ({ id: v.id, version: v.version, manifestJson: v.manifest_json });
9467
+ const seen = new Set();
9468
+ const distinct = bases.filter((b) => !!b && !seen.has(b.id) && !!seen.add(b.id));
9469
+ // A first promote (nothing named, nothing served) is judged against nothing.
9470
+ if (distinct.length === 0)
9471
+ return null;
9472
+ for (const base of distinct) {
9473
+ const refusal = releaseWithinMajorRefusal({ vertical, base: side(base), head: side(incoming), classify: classifyRelease, servesMajors });
9474
+ if (refusal)
9475
+ return refusal;
9476
+ }
9477
+ return null;
9357
9478
  }
9358
9479
  /** #2178: refuse running `incoming` where any of `froms` ran, each distinct version judged once. */
9359
9480
  async assertNoStrandFrom(froms, afterId, held, receipts = []) {