@substrat-run/adapter-cloudflare 0.220.0 → 0.222.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/broker-telemetry.d.ts +2 -5
  2. package/dist/broker-telemetry.d.ts.map +1 -1
  3. package/dist/broker-telemetry.js +2 -5
  4. package/dist/broker-telemetry.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +280 -65
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +737 -245
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +3 -2
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +10 -4
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-handoff.d.ts +17 -1
  14. package/dist/delivery-handoff.d.ts.map +1 -1
  15. package/dist/delivery-handoff.js +19 -5
  16. package/dist/delivery-handoff.js.map +1 -1
  17. package/dist/directory-cutover.d.ts +243 -0
  18. package/dist/directory-cutover.d.ts.map +1 -0
  19. package/dist/directory-cutover.js +604 -0
  20. package/dist/directory-cutover.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +19 -1
  22. package/dist/directory-mirror-apply.d.ts.map +1 -1
  23. package/dist/directory-mirror-apply.js +19 -3
  24. package/dist/directory-mirror-apply.js.map +1 -1
  25. package/dist/directory-mirror-backfill.d.ts +2 -0
  26. package/dist/directory-mirror-backfill.d.ts.map +1 -1
  27. package/dist/directory-mirror-backfill.js +6 -4
  28. package/dist/directory-mirror-backfill.js.map +1 -1
  29. package/dist/directory-mirror.d.ts +24 -0
  30. package/dist/directory-mirror.d.ts.map +1 -1
  31. package/dist/directory-mirror.js +16 -2
  32. package/dist/directory-mirror.js.map +1 -1
  33. package/dist/directory-objects.d.ts +40 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +134 -2
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts.map +1 -1
  38. package/dist/directory-placement.js +9 -1
  39. package/dist/directory-placement.js.map +1 -1
  40. package/dist/directory-split-inventory.d.ts +5 -3
  41. package/dist/directory-split-inventory.d.ts.map +1 -1
  42. package/dist/directory-split-inventory.js +13 -6
  43. package/dist/directory-split-inventory.js.map +1 -1
  44. package/dist/directory-tenant-orgs.d.ts +19 -0
  45. package/dist/directory-tenant-orgs.d.ts.map +1 -0
  46. package/dist/directory-tenant-orgs.js +33 -0
  47. package/dist/directory-tenant-orgs.js.map +1 -0
  48. package/dist/directory-tenant-roles.d.ts +35 -0
  49. package/dist/directory-tenant-roles.d.ts.map +1 -0
  50. package/dist/directory-tenant-roles.js +78 -0
  51. package/dist/directory-tenant-roles.js.map +1 -0
  52. package/dist/directory-tenant-tuples.d.ts +165 -0
  53. package/dist/directory-tenant-tuples.d.ts.map +1 -0
  54. package/dist/directory-tenant-tuples.js +197 -0
  55. package/dist/directory-tenant-tuples.js.map +1 -0
  56. package/dist/host.d.ts +65 -3
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/host.js +422 -64
  59. package/dist/host.js.map +1 -1
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +1 -0
  63. package/dist/index.js.map +1 -1
  64. package/dist/platform-sweeper-do.d.ts +1 -1
  65. package/dist/platform-sweeper-do.js +1 -1
  66. package/dist/route-read-model-publisher.d.ts +6 -1
  67. package/dist/route-read-model-publisher.d.ts.map +1 -1
  68. package/dist/route-read-model-publisher.js +51 -13
  69. package/dist/route-read-model-publisher.js.map +1 -1
  70. package/dist/scope-do.d.ts +28 -2
  71. package/dist/scope-do.d.ts.map +1 -1
  72. package/dist/scope-do.js +398 -68
  73. package/dist/scope-do.js.map +1 -1
  74. package/dist/scope-sweeper-do.d.ts +28 -0
  75. package/dist/scope-sweeper-do.d.ts.map +1 -1
  76. package/dist/scope-sweeper-do.js +88 -50
  77. package/dist/scope-sweeper-do.js.map +1 -1
  78. package/dist/scope-wake.d.ts +12 -1
  79. package/dist/scope-wake.d.ts.map +1 -1
  80. package/dist/scope-wake.js +14 -1
  81. package/dist/scope-wake.js.map +1 -1
  82. package/dist/scope-work.d.ts +1 -1
  83. package/dist/scope-work.js +1 -1
  84. package/dist/scope-work.js.map +1 -1
  85. package/dist/tenant-due-work-do.d.ts +95 -0
  86. package/dist/tenant-due-work-do.d.ts.map +1 -0
  87. package/dist/tenant-due-work-do.js +149 -0
  88. package/dist/tenant-due-work-do.js.map +1 -0
  89. package/package.json +10 -10
package/dist/scope-do.js CHANGED
@@ -1,15 +1,19 @@
1
1
  import { REWIND_REFUSED } from './rewind-refusal.js';
2
2
  import { SYSTEM_DOOR_MOVED } from './system-door.js';
3
3
  import { DurableObject } from 'cloudflare:workers';
4
- import { ATTACHMENT_ADDED, ATTACHMENT_REMOVED, CAPTURE_REFUSALS, attachmentRecord, domainEvent, domainEventInput, eventId, instant, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, toWireFailure, grantRefFromProof, principalId, principalBecomeCapabilityInput, principalBindLinkInput, scopeId as scopeIdOf, tenantId as tenantIdOf, platformRequestInput, platformRequestId, MAX_PENDING_PLATFORM_REQUESTS, MAX_PENDING_SWEEP_RUNS, SWEEP_RUNS_KIND, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, listLimitOf, pageOf, countedPageOf, requestFingerprint, substratError, errorCodeOf, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsOf, isRuntimeTable, replayDumpObjects, dumpObjectsAudit, REDRAIN_BATCH, } from '@substrat-run/contracts';
5
- import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, ConnectionSealingKeyUnavailableError, noSealingKeyMessage, sealTo, assertReadOnlyQuery, refuseEntitlement, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleErasurePlan, redactSubjectScopeText, assertRowLimit, assertRowOffset, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_LEASE_EXPIRED_NOTE, JOB_STEP_RECORD_SQL, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, grantEntityShapeOnceIn, topUpEntityGrantShapes, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, SCOPE_SEATED_ROLES_SQL, inUnitRoleRefusal, loadedRoleSetRefusedRole, reservedRoleSetRefusedRole, reservedGrantRefusal, reservedRoleRefusal, reservedShapeRefusal, effectiveRoleGrantQuery, switchRecordedOff, switchSystemSchedules, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, PermissionDenied, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, impersonationStampOf, createAtomic, NotSearchable, isSearchIndexTable, countDumpRows, planDumpSample, sampleFilters, sampleGraph, rowCountTable, searchIndexPlans, NotListable, listIndexPlans, moduleMigrations, REGISTERED_MIGRATIONS, registeredMigrationsOf, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
4
+ import { PRODUCTION_ENVIRONMENT, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, CAPTURE_REFUSALS, attachmentRecord, domainEvent, domainEventInput, eventId, instant, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, toWireFailure, grantRefFromProof, principalId, principalBecomeCapabilityInput, principalBindLinkInput, scopeId as scopeIdOf, tenantId as tenantIdOf, platformRequestInput, platformRequestId, MAX_PENDING_PLATFORM_REQUESTS, MAX_PENDING_SWEEP_RUNS, SWEEP_RUNS_KIND, SCOPE_DUMP_PAGE_MAX_BYTES, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, listLimitOf, pageOf, countedPageOf, requestFingerprint, substratError, errorCodeOf, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsOf, isRuntimeTable, replayDumpObjects, dumpObjectsAudit, REDRAIN_BATCH, storeOperationKeyOf, SCOPE_DUE_HOST_KEY, } from '@substrat-run/contracts';
5
+ import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, ConnectionSealingKeyUnavailableError, noSealingKeyMessage, sealTo, assertReadOnlyQuery, refuseEntitlement, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleErasurePlan, redactSubjectScopeText, assertRowLimit, assertRowOffset, JOB_RUN_PATCH_SQL, JOB_RUN_CLAIM_SQL, JOB_RUN_RENEW_SQL, JOB_RUN_BEGIN_SQL, JOB_RUN_MISS_SQL, JOB_RUN_MISS_SETTLE_SQL, admissionMissOutcome, JOB_LEASE_EXPIRED_NOTE, JOB_STEP_RECORD_SQL, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, grantEntityShapeOnceIn, topUpEntityGrantShapes, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, SCOPE_SEATED_ROLES_SQL, inUnitRoleRefusal, loadedRoleSetRefusedRole, reservedRoleSetRefusedRole, reservedGrantRefusal, reservedRoleRefusal, reservedShapeRefusal, effectiveRoleGrantQuery, switchRecordedOff, switchSystemSchedules, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, PermissionDenied, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, impersonationStampOf, createAtomic, NotSearchable, isSearchIndexTable, countDumpRows, planDumpSample, sampleFilters, sampleGraph, rowCountTable, searchIndexPlans, NotListable, listIndexPlans, moduleMigrations, REGISTERED_MIGRATIONS, registeredMigrationsOf, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations,
6
+ // #2993 part 3: the scope's type, recorded here and read at wake, decides which modules it runs.
7
+ HOME_SCOPE_TYPE, SCOPE_TYPE_META_KEY,
8
+ // #2995: and its parent, recorded here beside it, which the doors of a CP-less host read.
9
+ PARENT_SCOPE_META_KEY, provisionedParent, operationNotInScopeType, provisionedScopeType, scopeTypePlanOf, scopeTypeRoleRefusal, scopeTypeRuns, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
6
10
  import { isUpgradeRequest, readSubscription, LIVE_DECIDE_ATTEMPTS, LIVE_FANOUT_LIMIT, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, LIVE_CLOSE, LIVE_SOCKETS_PER_PRINCIPAL, decodeLiveWithin, liveInstant, liveRefusal, liveRefusalStatus, } from './live-reads.js';
7
11
  import { replyOf } from './do-reply.js';
8
12
  import { OperationQueue } from './serialization.js';
9
13
  import { reconcileOnWake } from './reconcile-on-wake.js';
10
14
  import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
11
15
  import { assertNoRuntimeStorage, doScopedSql, doBuiltColumnsOf, doRedactionSql, doSpineSql } from './sql.js';
12
- import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_ALARM_MIN_GAP_MS, PURGE_BATCH, PURGE_DUE_BY_EVENT, heldPurgePass, purgeDueAt, readPurgeLap, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, CONNECTOR_DISPATCH_REQUESTED_BY, MAX_PENDING_CONNECTOR_DISPATCHES, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
16
+ import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, STORE_PROOF_DDL, mintStoreProof, redeemStoreProof, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_ALARM_MIN_GAP_MS, PURGE_BATCH, PURGE_DUE_BY_EVENT, consumeScheduleDue, dueByEventSchedulesOf, noteScheduleDue, readScheduleDue, scheduleDueAt, heldPurgePass, purgeDueAt, readPurgeLap, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, CONNECTOR_DISPATCH_REQUESTED_BY, MAX_PENDING_CONNECTOR_DISPATCHES, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
13
17
  import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove } from '@substrat-run/kernel';
14
18
  import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRefusal } from '@substrat-run/kernel';
15
19
  import { createDoTupleChecker, createLocalControlPlaneReader, scopeTupleReader } from './checker.js';
@@ -22,7 +26,7 @@ import { DELIVERY_HANDOFF_KEY, DELIVERY_MODE_KEY, HANDOFF_ROUNDS, deliveryModeAf
22
26
  import { registerPlatformDeliveryBroker } from './delivery-broker-platform.js';
23
27
  import { advanceMarks, brokerName, handoffQueries, messagesOf, senderDeliveryOf } from '@substrat-run/kernel';
24
28
  import { DELIVERY_HANDOFF_ENV, intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
25
- import { SCOPE_SWEEPER_NAME } from './scope-sweeper-do.js';
29
+ import { SCOPE_SWEEPER_NAME, kickPlatformDrain, runScopeDueWork } from './scope-sweeper-do.js';
26
30
  import { SCOPE_WAKE_KEY, keepRegisteredMeanwhile, kickControlPlane, runWake, wakeAfterCommit, wakeDueAt } from './scope-wake.js';
27
31
  import { CARRIED_AWAY_KEY, COPY_MARK_CLEARED_KEY, KEPT_COPY_REFUSAL, KEPT_DIVERGENT_KEY, LOAD_STAMP_KEY, STORE_LOCAL_META_KEYS, WRITE_REVISION_KEY, carriedAwayDump, isCopyMarkInsert, isWriteStatement, assertSpineTablesBuilt, clearCopyMarker, dumpRowsInsert, isSpineTable, markCopyOrigin, repointScopeGrants, settleCopiedWork, emittedHere, IS_COPY_SQL, CLEAN_ROOM_COPY_SQL, isCopyLoad, isLifecycleWrite, readLifecycle, settleLifecycleAfterLoad, writeLifecycle, spineColumnAdditions } from '@substrat-run/kernel';
28
32
  import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
@@ -416,6 +420,9 @@ const KERNEL_DDL = `
416
420
  -- #3139: download links, a short-lived URL that lets a caller with no session read ONE file as
417
421
  -- the principal who minted it. Shared with the pure adapter from @substrat-run/kernel.
418
422
  ${DOWNLOAD_LINK_DDL}
423
+ -- #2996 (K-64): store proofs, a short-lived, single-use proof that an operation checked the key
424
+ -- of one store operation. Spine (kernel-written), shared with the other adapter from the kernel.
425
+ ${STORE_PROOF_DDL}
419
426
  -- #1686: where a copied scope's data came from, and the event id its own events start above.
420
427
  -- Shared with the other adapter from @substrat-run/kernel; the column comments are there.
421
428
  ${COPY_ORIGIN_DDL}
@@ -944,6 +951,9 @@ options = {}) {
944
951
  // What the declared surface reserves holds in every instance too, whatever registers under its ids.
945
952
  const declaredReserved = new Set();
946
953
  const declaredListed = new Set();
954
+ // #2993 part 3: which modules (and roles) a scope of each declared type has. A class given no
955
+ // declared types has one 'home' type running every module, and reads no type at all.
956
+ const scopeTypePlan = scopeTypePlanOf(options.permissions);
947
957
  for (const m of options.permissions?.modules ?? []) {
948
958
  noteReservedKeys(declaredReserved, m.manifest);
949
959
  noteDeclaredKeys(declaredListed, m.manifest);
@@ -1007,6 +1017,11 @@ options = {}) {
1007
1017
  purgeOnlyKeys = new Map();
1008
1018
  /** #119: a purge schedule's operation → the module that declared it and the entity it purges. */
1009
1019
  purgeSchedules = new Map();
1020
+ /**
1021
+ * #3540: every registered schedule declared `due: 'event'`, by operation — what `ctx.scheduleDue`
1022
+ * may name, and the operations whose every run clears their date in its own transaction.
1023
+ */
1024
+ dueSchedules = new Map();
1010
1025
  /**
1011
1026
  * #3540: true while this scope's alarm is waiting on its sweeper's purge run. The purges that
1012
1027
  * run meanwhile commit through `settleCommitted`, and must not arm the alarm the handler is about
@@ -1020,6 +1035,15 @@ options = {}) {
1020
1035
  /** #2387: the operations held to a `ctx.check` — the pure adapter's set, from the same kernel read. */
1021
1036
  operationCheckHeld = new Set();
1022
1037
  modules = new Map();
1038
+ /** #2993 part 3: a bound operation → the module that declared it, which the scope's type runs or not. */
1039
+ operationModule = new Map();
1040
+ /**
1041
+ * #2993 part 3: this scope's type, read once from `_substrat_meta` (a type never changes; the
1042
+ * fix and a load are the only writers, and both set it here). Undefined until first read.
1043
+ */
1044
+ scopeTypeHeld;
1045
+ /** #2995: this scope's parent as its store holds it (`null`: none), read once; a load clears it. */
1046
+ scopeParentHeld;
1023
1047
  /**
1024
1048
  * #2430: what a registered module, or a module the class's declared `permissions` lists, declares
1025
1049
  * `holder: 'system'` — the role and grant doors' refusals read it.
@@ -1213,6 +1237,8 @@ options = {}) {
1213
1237
  // #119: refused before anything is recorded, as in the pure adapter.
1214
1238
  const trashTargets = registerTrashTargets(manifest.id, new Set(Object.keys(registration.operations?.handlers ?? {})), registration.operations?.inputs, manifest.entityStates, manifest.schedules);
1215
1239
  this.purgeOnlyKeys.set(manifest.id, purgeOnlyKeysOf(manifest.schedules ?? []));
1240
+ for (const [operation, due] of dueByEventSchedulesOf(manifest.schedules))
1241
+ this.dueSchedules.set(operation, due);
1216
1242
  for (const schedule of manifest.schedules ?? []) {
1217
1243
  if (schedule.purge) {
1218
1244
  this.purgeSchedules.set(schedule.operation, {
@@ -1349,6 +1375,8 @@ options = {}) {
1349
1375
  const checkHeld = checkHeldOperationsOf(registration.operations);
1350
1376
  for (const [name, handler] of Object.entries(registration.operations?.handlers ?? {})) {
1351
1377
  this.defineOperation(name, handler);
1378
+ if (this.operations.has(name))
1379
+ this.operationModule.set(name, manifest.id);
1352
1380
  if (checkHeld.has(name) && this.operations.has(name))
1353
1381
  this.operationCheckHeld.add(name);
1354
1382
  // The schema follows the HANDLER, not the name: a withdrawn operation
@@ -1739,7 +1767,12 @@ options = {}) {
1739
1767
  * `servesTenant`.
1740
1768
  */
1741
1769
  admission(tenantId) {
1742
- return { verdict: this.tenantVerdict(tenantId).verdict, lifecycle: readLifecycle(this.switchSql()) };
1770
+ return {
1771
+ verdict: this.tenantVerdict(tenantId).verdict,
1772
+ lifecycle: readLifecycle(this.switchSql()),
1773
+ type: this.scopeType(),
1774
+ parent: this.scopeParent(),
1775
+ };
1743
1776
  }
1744
1777
  /**
1745
1778
  * #1738 / #2016: this scope's tenant against `tenantId` — the one reading behind the served-here
@@ -1983,7 +2016,7 @@ options = {}) {
1983
2016
  due,
1984
2017
  ...(handedOffThrough === undefined ? {} : { handedOffThrough }),
1985
2018
  // Executors run on the coordinator, which names them; the consumers are this DO's own.
1986
- subscribers: [...outboxSubscribersOf(this.modules.values(), []), ...executors],
2019
+ subscribers: [...outboxSubscribersOf(this.modulesRun(), []), ...executors],
1987
2020
  exportTypes: this.crossVertical.exportTypes(),
1988
2021
  })));
1989
2022
  }
@@ -2488,6 +2521,10 @@ options = {}) {
2488
2521
  // else. Naming the code once here is what lets those patterns go.
2489
2522
  if (!handler)
2490
2523
  throw substratError('not_found', `unknown operation: ${operation}`);
2524
+ // #2993 part 3: an operation of a module this scope's type does not run is unknown here.
2525
+ const declaredBy = this.operationModule.get(operation);
2526
+ if (declaredBy !== undefined && !this.runs(declaredBy))
2527
+ throw operationNotInScopeType(operation, this.scopeType());
2491
2528
  // #2821: before the parse, the guards and the handler — and under read-only too.
2492
2529
  assertImpersonationAdmitted(impersonation, operation, this.operationImpersonationRefused);
2493
2530
  // #304 entitlement gate, scope-local path: fail closed on the projected view exactly as
@@ -2710,6 +2747,10 @@ options = {}) {
2710
2747
  // #2166: what the guards and the handler emit about a stamped entity, held below.
2711
2748
  const stamps = watchUpdatedStamps(doSpineSql(this.sql), this.updatedStampPlans);
2712
2749
  await refuseTrashedTarget({ sql: doSpineSql(this.sql), plans: this.statePlans, check: ctx.check, now: ctx.now() }, operation, target, parsed, purging ? { gate: this.purgeGateFacts(systemDoor.moduleId, tenantId) } : undefined);
2750
+ // #3540: a run of a due-by-event schedule's operation clears its date first, in this
2751
+ // transaction — the pure adapter's, through the same kernel function.
2752
+ if (this.dueSchedules.has(operation))
2753
+ consumeScheduleDue(doSpineSql(this.sql), operation);
2713
2754
  await this.runGuards(operation, ctx, parsed);
2714
2755
  // #2387: the handler's own checks only — the pure adapter's reset, for its reason.
2715
2756
  checks.calls = 0;
@@ -3048,7 +3089,18 @@ options = {}) {
3048
3089
  * for the alarm to ask, and a registered module declares a purge horizon.
3049
3090
  */
3050
3091
  purgeDueByEvent() {
3051
- return this.env.SUBSTRAT_PURGE_DUE === PURGE_DUE_BY_EVENT && this.env.SWEEPER !== undefined && this.purgeSchedules.size > 0;
3092
+ return this.dueByEventSwitched() && this.purgeSchedules.size > 0;
3093
+ }
3094
+ /** #3540: the switch is `event` and a sweeper is bound for the alarm to ask. */
3095
+ dueByEventSwitched() {
3096
+ return this.env.SUBSTRAT_PURGE_DUE === PURGE_DUE_BY_EVENT && this.env.SWEEPER !== undefined;
3097
+ }
3098
+ /**
3099
+ * #3540: whether anything here can be due by event: the switch, and a purge horizon or a
3100
+ * `due: 'event'` schedule among the registered modules.
3101
+ */
3102
+ dueAlarmApplies() {
3103
+ return this.dueByEventSwitched() && (this.purgeSchedules.size > 0 || this.dueSchedules.size > 0);
3052
3104
  }
3053
3105
  /** #3540: when this scope's purges are next due, read from its own rows (`purgeDueAt`). */
3054
3106
  purgeDueAtNow(now) {
@@ -3056,48 +3108,102 @@ options = {}) {
3056
3108
  return purgeDueAt(doSpineSql(this.sql), this.statePlans, schedules, now);
3057
3109
  }
3058
3110
  /**
3059
- * #3540: arm the scope's alarm for its earliest due row, and record the pair the alarm will ask
3111
+ * #3540: when anything here is next due by event — the purges, and, once a pass has said its
3112
+ * sweeper takes `runScopeDue` (`schedules`), the `due: 'event'` schedules that have run under
3113
+ * that form (`scheduleDueAt`). Earliest wins.
3114
+ */
3115
+ dueAtNow(now, schedules) {
3116
+ const purges = this.purgeDueByEvent() ? this.purgeDueAtNow(now) : null;
3117
+ const events = schedules && this.dueSchedules.size > 0 ? scheduleDueAt(doSpineSql(this.sql), this.dueSchedules.values()) : null;
3118
+ return purges === null ? events : events === null ? purges : Math.min(purges, events);
3119
+ }
3120
+ /**
3121
+ * #3540: arm the scope's alarm for its earliest due work, and record the pair the alarm will ask
3060
3122
  * for. Never before the `notBefore` a run with no progress left. A copy arms nothing: a fork, a
3061
3123
  * snapshot or a preview runs no schedule. Answers whether anything is armed.
3124
+ *
3125
+ * `takesSchedules` is a pass saying its sweeper can take `runScopeDue` (`ScheduleTick.alarmRunsDue`);
3126
+ * it is remembered, and only from then on does the alarm cover the `due: 'event'` schedules, so a
3127
+ * scope whose sweeper predates that call never arms for work it would not run.
3128
+ *
3129
+ * `fromPass` is a pass leaving the work to the alarm (`deferrable`), remembered as `passDefers`:
3130
+ * from then on the alarm may run it itself rather than ask the sweeper.
3062
3131
  */
3063
- async armPurgeAlarm(tenantId, scopeId) {
3064
- if (!this.purgeDueByEvent() || this.isCopyRead())
3065
- return false;
3066
- const at = this.purgeDueAtNow(Date.now());
3067
- if (at === null)
3132
+ async armPurgeAlarm(tenantId, scopeId, takesSchedules = false, fromPass = false) {
3133
+ if (!this.dueAlarmApplies() || this.isCopyRead())
3068
3134
  return false;
3069
3135
  const held = (await this.ctx.storage.get(PURGE_ALARM_KEY)) ?? null;
3070
- if (!held || held.tenantId !== tenantId || held.scopeId !== scopeId) {
3071
- await this.ctx.storage.put(PURGE_ALARM_KEY, { tenantId, scopeId });
3136
+ const schedules = takesSchedules || held?.schedules === true;
3137
+ const samePair = held?.tenantId === tenantId && held.scopeId === scopeId;
3138
+ const defers = fromPass || (samePair && held?.passDefers === true);
3139
+ const at = this.dueAtNow(Date.now(), schedules);
3140
+ if (at === null && !(takesSchedules && !held?.schedules))
3141
+ return false;
3142
+ if (!held || !samePair || (schedules && !held.schedules) || (defers && !held.passDefers)) {
3143
+ await this.ctx.storage.put(PURGE_ALARM_KEY, {
3144
+ tenantId,
3145
+ scopeId,
3146
+ ...(held?.notBefore !== undefined && samePair ? { notBefore: held.notBefore } : {}),
3147
+ ...(schedules ? { schedules: true } : {}),
3148
+ ...(defers ? { passDefers: true } : {}),
3149
+ });
3072
3150
  }
3151
+ if (at === null)
3152
+ return false;
3073
3153
  await this.armAlarmBy(Math.max(at, held?.notBefore ?? 0));
3074
3154
  return true;
3075
3155
  }
3076
3156
  /**
3077
- * #3540: after a commit, arm the purge alarm for what is now earliest. Never fails the commit it
3078
- * follows: an alarm not armed costs latency, and the sweeper's pass re-arms it (the safety net).
3157
+ * #3540: after a commit, arm the alarm for what is now earliest: a row it binned, or a date it
3158
+ * wrote with `ctx.scheduleDue`. Never fails the commit it follows: an alarm not armed costs
3159
+ * latency, and the sweeper's pass re-arms it (the safety net).
3079
3160
  */
3080
3161
  async notePurgeDue(tenantId, scopeId) {
3081
- if (this.#purgeAlarmRunning || !this.purgeDueByEvent())
3162
+ if (this.#purgeAlarmRunning || !this.dueAlarmApplies())
3082
3163
  return;
3083
3164
  try {
3084
3165
  await this.armPurgeAlarm(tenantId, scopeId);
3085
3166
  }
3086
3167
  catch (err) {
3087
- console.error('substrat: purge alarm not armed after commit; the sweeper pass re-arms it', err);
3168
+ console.error('substrat: due alarm not armed after commit; the sweeper pass re-arms it', err);
3088
3169
  }
3089
3170
  }
3090
3171
  /**
3091
- * #3540: the purge alarm's half of `alarm()`. When a purge is due, the scope asks its sweeper to
3092
- * run this scope's purge schedules (`runScopePurges`), which runs them through the coordinator's
3093
- * door, with every gate a pass applies. Then it re-arms from what its rows say now:
3172
+ * #3540: the vertical's own scope host, to run this scope's due work with: the one its
3173
+ * `mountPlatformSurface` builds its routes with and registers under `SCOPE_DUE_HOST_KEY`, built
3174
+ * from this object's env, which is the script's. Its door holds the tenant pair, the lifecycle,
3175
+ * the kill switch and the rewind hold, and its calls into this scope are calls like any other.
3176
+ * Null when the bundle registers none (a vertical-host older than the key, a self-host wiring its
3177
+ * own) or building it throws: the alarm then asks the sweeper, so the work is never stranded.
3178
+ */
3179
+ dueRunHost() {
3180
+ const hostFor = globalThis[Symbol.for(SCOPE_DUE_HOST_KEY)];
3181
+ if (typeof hostFor !== 'function')
3182
+ return null;
3183
+ try {
3184
+ return hostFor(this.env);
3185
+ }
3186
+ catch (err) {
3187
+ console.error('substrat: the due alarm could not build its host; asking the sweeper instead', err);
3188
+ return null;
3189
+ }
3190
+ }
3191
+ /**
3192
+ * #3540: the due alarm's half of `alarm()`. When something is due by event, the scope runs it for
3193
+ * itself alone — its purges, and its `due: 'event'` schedules once a pass has said its sweeper
3194
+ * takes `runScopeDue` — through the host's door, with every gate a pass applies
3195
+ * (`runScopeDueWork`). Once a pass has said it leaves that work to the alarm (`passDefers`), the
3196
+ * scope runs it with the vertical's own host (`dueRunHost`), and no sweeper is asked; until then,
3197
+ * or when the bundle gives it no host, it asks its sweeper to (`runScopeDue`, or `runScopePurges`
3198
+ * before that call), which runs the same work after its roster check. Then it re-arms from what
3199
+ * its rows say now:
3094
3200
  *
3095
- * - nothing left binned (a restore cancelled it, or the run purged it): nothing armed;
3096
- * - a lap left open by a run that answered: due again at once, since that run made progress;
3097
- * - otherwise never sooner than `PURGE_ALARM_MIN_GAP_MS`, or the schedule's cadence when the
3201
+ * - nothing left due (a restore cancelled it, or the run did it): nothing armed;
3202
+ * - a purge lap left open by a run that answered: due again at once, since that run made progress;
3203
+ * - otherwise never sooner than `PURGE_ALARM_MIN_GAP_MS`, or the shortest cadence when the
3098
3204
  * sweeper could not be asked, so a run that cannot progress cannot spin the alarm;
3099
- * - a run the sweeper held (a lifecycle, a switch, a scope off its roster): not re-armed, and no
3100
- * commit re-arms it within the cadence. The pass re-arms it when the scope's schedules run.
3205
+ * - a run that was held (a lifecycle, a switch, a scope off the sweeper's roster): not re-armed, and
3206
+ * no commit re-arms it within the cadence. The pass re-arms it when the scope's schedules run.
3101
3207
  *
3102
3208
  * Never throws: a thrown alarm is retried by the runtime.
3103
3209
  */
@@ -3107,15 +3213,30 @@ options = {}) {
3107
3213
  if (!state)
3108
3214
  return;
3109
3215
  // The switch turned off, or the scope became a copy: the pass has it again, or nothing does.
3110
- if (!this.purgeDueByEvent() || this.isCopyRead()) {
3216
+ if (!this.dueAlarmApplies() || this.isCopyRead()) {
3111
3217
  await this.ctx.storage.delete(PURGE_ALARM_KEY);
3112
3218
  return;
3113
3219
  }
3114
3220
  await this.ensureMigrations();
3221
+ const schedules = state.schedules === true;
3222
+ const keep = (notBefore) => ({
3223
+ tenantId: state.tenantId,
3224
+ scopeId: state.scopeId,
3225
+ ...(notBefore !== undefined ? { notBefore } : {}),
3226
+ ...(schedules ? { schedules: true } : {}),
3227
+ ...(state.passDefers ? { passDefers: true } : {}),
3228
+ });
3229
+ // Nothing due: only a record that says the sweeper takes `runScopeDue` is worth keeping.
3230
+ const settle = async () => {
3231
+ if (schedules)
3232
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep());
3233
+ else
3234
+ await this.ctx.storage.delete(PURGE_ALARM_KEY);
3235
+ };
3115
3236
  const now = Date.now();
3116
- const at = this.purgeDueAtNow(now);
3237
+ const at = this.dueAtNow(now, schedules);
3117
3238
  if (at === null) {
3118
- await this.ctx.storage.delete(PURGE_ALARM_KEY);
3239
+ await settle();
3119
3240
  return;
3120
3241
  }
3121
3242
  const notBefore = state.notBefore ?? 0;
@@ -3127,8 +3248,22 @@ options = {}) {
3127
3248
  let answer;
3128
3249
  this.#purgeAlarmRunning = true;
3129
3250
  try {
3130
- const stub = sweeper.get(sweeper.idFromName(SCOPE_SWEEPER_NAME));
3131
- answer = await stub.runScopePurges(state.tenantId, state.scopeId);
3251
+ // Its own run once a pass has said it leaves the work here, so nothing else runs it; the
3252
+ // sweeper's call otherwise, and whenever this bundle gives the scope no host to run it with.
3253
+ const host = state.passDefers === true || schedules ? this.dueRunHost() : null;
3254
+ if (host) {
3255
+ const { tenantId, scopeId } = state;
3256
+ answer = await runScopeDueWork(host, tenantId, scopeId, schedules, {
3257
+ versionId: this.env.SUBSTRAT_VERSION_ID ?? null,
3258
+ kickPlatformDrain: () => this.ctx.waitUntil(kickPlatformDrain(this.env, tenantId, scopeId).catch(() => { })),
3259
+ });
3260
+ }
3261
+ else {
3262
+ const stub = sweeper.get(sweeper.idFromName(SCOPE_SWEEPER_NAME));
3263
+ answer = schedules
3264
+ ? await stub.runScopeDue(state.tenantId, state.scopeId)
3265
+ : await stub.runScopePurges(state.tenantId, state.scopeId);
3266
+ }
3132
3267
  }
3133
3268
  catch (err) {
3134
3269
  answer = { error: err instanceof Error ? err.message : String(err) };
@@ -3137,21 +3272,22 @@ options = {}) {
3137
3272
  this.#purgeAlarmRunning = false;
3138
3273
  }
3139
3274
  const after = Date.now();
3140
- const next = this.purgeDueAtNow(after);
3275
+ const next = this.dueAtNow(after, schedules);
3141
3276
  if (next === null) {
3142
- await this.ctx.storage.delete(PURGE_ALARM_KEY);
3277
+ await settle();
3143
3278
  return;
3144
3279
  }
3145
- const cadence = after + Math.min(...[...this.purgeSchedules.values()].map((p) => p.everyMinutes)) * 60_000;
3280
+ const minutes = [...this.purgeSchedules.values(), ...(schedules ? this.dueSchedules.values() : [])].map((p) => p.everyMinutes);
3281
+ const cadence = after + Math.min(...minutes) * 60_000;
3146
3282
  if ('held' in answer) {
3147
3283
  // Not re-armed, and no commit re-arms it within the cadence: a held scope does not ask on
3148
3284
  // every write. The pass arms it again once the scope's schedules run.
3149
- await this.ctx.storage.put(PURGE_ALARM_KEY, { tenantId: state.tenantId, scopeId: state.scopeId, notBefore: cadence });
3285
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep(cadence));
3150
3286
  return;
3151
3287
  }
3152
3288
  let floor;
3153
3289
  if ('error' in answer) {
3154
- console.error('substrat: the purge alarm could not ask its sweeper; asking again after the cadence', answer.error);
3290
+ console.error('substrat: the due alarm could not ask its sweeper; asking again after the cadence', answer.error);
3155
3291
  floor = cadence;
3156
3292
  }
3157
3293
  else {
@@ -3159,11 +3295,11 @@ options = {}) {
3159
3295
  const open = [...this.purgeSchedules.keys()].some((op) => readPurgeLap(sql, op).after !== null);
3160
3296
  floor = open ? after : after + PURGE_ALARM_MIN_GAP_MS;
3161
3297
  }
3162
- await this.ctx.storage.put(PURGE_ALARM_KEY, { tenantId: state.tenantId, scopeId: state.scopeId, notBefore: floor });
3298
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep(floor));
3163
3299
  await this.armAlarmBy(Math.max(next, floor));
3164
3300
  }
3165
3301
  catch (err) {
3166
- console.error('substrat: purge alarm failed; the sweeper pass re-arms it', err);
3302
+ console.error('substrat: due alarm failed; the sweeper pass re-arms it', err);
3167
3303
  }
3168
3304
  }
3169
3305
  /** K-69: a scope with the control plane's origin and secret asks for its own drains. */
@@ -3226,14 +3362,17 @@ options = {}) {
3226
3362
  return;
3227
3363
  }
3228
3364
  let answered;
3365
+ let answeredEnvironment;
3229
3366
  const ran = await runWake(state, Date.now(), () => this.wakeWork(), async (body) => {
3230
3367
  const answer = await kickControlPlane(transport, body);
3231
3368
  answered = answer?.broker;
3369
+ answeredEnvironment = answer?.brokerEnvironment;
3232
3370
  return answer;
3233
3371
  });
3234
- // A5: the delivery mode the control plane holds for this tenant, on the same answer.
3372
+ // A5: the delivery mode the control plane holds for this tenant, on the same answer, and
3373
+ // (#3639) the named environment whose broker it hands off to.
3235
3374
  if (answered)
3236
- await this.applyDeliveryMode(state.tenantId, state.scopeId, answered);
3375
+ await this.applyDeliveryMode(state.tenantId, state.scopeId, answered, answeredEnvironment);
3237
3376
  // The object took other calls while the kick was out: keep what a commit stored meanwhile.
3238
3377
  const next = keepRegisteredMeanwhile(state, ran, (await this.ctx.storage.get(SCOPE_WAKE_KEY)) ?? null);
3239
3378
  if (!next) {
@@ -3249,13 +3388,28 @@ options = {}) {
3249
3388
  console.error('substrat: scope wake failed; the pass is the backstop', err);
3250
3389
  }
3251
3390
  }
3252
- /** K-74: this scope's broker, or null when the script binds none (the broker is off). */
3253
- deliveryBroker(tenantId) {
3391
+ /**
3392
+ * K-74: this scope's broker, or null when the script binds none (the broker is off). #3639
3393
+ * (D-83): its environment's, named by `environment`; production's (`<tenant>/<app>`, as before)
3394
+ * when it names none.
3395
+ */
3396
+ deliveryBroker(tenantId, environment) {
3254
3397
  const ns = this.env.SUBSTRAT_DELIVERY_BROKER;
3255
3398
  if (!ns)
3256
3399
  return null;
3257
3400
  const app = this.env.SUBSTRAT_VERTICAL ?? 'vertical';
3258
- return ns.get(ns.idFromName(brokerName(tenantId, app)));
3401
+ return ns.get(ns.idFromName(brokerName(tenantId, app, environment)));
3402
+ }
3403
+ /**
3404
+ * #3639: the named environment whose broker this scope hands off to, or undefined for
3405
+ * production's: what the control plane last told it (`DELIVERY_MODE_KEY`), else what its last
3406
+ * handoff stored, which outlives the mode going off.
3407
+ */
3408
+ async handoffEnvironment() {
3409
+ const mode = (await this.ctx.storage.get(DELIVERY_MODE_KEY)) ?? null;
3410
+ if (mode)
3411
+ return mode.environment;
3412
+ return ((await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null)?.environment;
3259
3413
  }
3260
3414
  /**
3261
3415
  * K-74: hand off what the scope's commits left, past its marks, and keep the marks the broker
@@ -3271,14 +3425,17 @@ options = {}) {
3271
3425
  async handOffCommitted(tenantId, scopeId,
3272
3426
  /** #3474: the invocation whose commit this follows, and its trace: its own rows carry the trace. */
3273
3427
  commit) {
3274
- const broker = this.deliveryBroker(tenantId);
3275
- if (!broker)
3428
+ if (!this.env.SUBSTRAT_DELIVERY_BROKER)
3276
3429
  return;
3277
3430
  // A5 (#3471): only while the tenant is in shadow or live, and under that mode.
3278
3431
  const options = await this.handoffOptions(tenantId, scopeId);
3279
3432
  if (options === null)
3280
3433
  return;
3434
+ // #3639: to the broker of the scope's environment, which every state this writes keeps.
3435
+ const environment = await this.handoffEnvironment();
3436
+ const broker = this.deliveryBroker(tenantId, environment);
3281
3437
  const ids = { tenantId, scopeId };
3438
+ const kept = { tenantId, scopeId, ...(environment ? { environment } : {}) };
3282
3439
  const stored = (await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null;
3283
3440
  let marks = stored?.marks;
3284
3441
  /** #3474: the round now with the broker, so a throw reports what it tried. */
@@ -3303,7 +3460,7 @@ options = {}) {
3303
3460
  break;
3304
3461
  }
3305
3462
  if (!retry) {
3306
- retry = handoffPending(stored, marks, Date.now(), ids);
3463
+ retry = handoffPending(stored, marks, Date.now(), kept);
3307
3464
  await this.keepHandoff(retry);
3308
3465
  await this.armAlarmBy(retry.due);
3309
3466
  }
@@ -3314,7 +3471,7 @@ options = {}) {
3314
3471
  delete options.start;
3315
3472
  }
3316
3473
  const next = advanceMarks(marks, sent, answer);
3317
- this.reportHandoffRound(tenantId, scopeId, inFlight, handoffOutcome(sent, answer));
3474
+ this.reportHandoffRound(tenantId, scopeId, inFlight, handoffOutcome(sent, answer), environment);
3318
3475
  inFlight = null;
3319
3476
  // An answer that acknowledges nothing new: stop, and leave the retry armed.
3320
3477
  if (sameMarks(next, marks))
@@ -3323,19 +3480,19 @@ options = {}) {
3323
3480
  await this.keepHandoff({ ...retry, marks });
3324
3481
  }
3325
3482
  if (drained) {
3326
- await this.keepHandoff({ tenantId, scopeId, marks });
3483
+ await this.keepHandoff({ ...kept, marks });
3327
3484
  return;
3328
3485
  }
3329
3486
  // The round limit, with work left: continue on the first step of the back-off.
3330
- const more = handoffPending(null, marks, Date.now(), ids);
3487
+ const more = handoffPending(null, marks, Date.now(), kept);
3331
3488
  await this.keepHandoff(more);
3332
3489
  await this.armAlarmBy(more.due);
3333
3490
  }
3334
3491
  catch (err) {
3335
3492
  if (inFlight)
3336
- this.reportHandoffRound(tenantId, scopeId, inFlight, 'failed');
3493
+ this.reportHandoffRound(tenantId, scopeId, inFlight, 'failed', environment);
3337
3494
  console.error('substrat: delivery handoff failed; the scope alarm retries it', err);
3338
- const next = handoffAfterFailure(stored, marks, Date.now(), ids);
3495
+ const next = handoffAfterFailure(stored, marks, Date.now(), kept);
3339
3496
  await this.keepHandoff(next);
3340
3497
  await this.armAlarmBy(next.due);
3341
3498
  }
@@ -3378,10 +3535,12 @@ options = {}) {
3378
3535
  * Public for the platform and the suites; a caller in the script can only change which receivers
3379
3536
  * its own next messages are owed, never what the control plane lets the broker drive.
3380
3537
  */
3381
- async applyDeliveryMode(tenantId, scopeId, mode) {
3538
+ async applyDeliveryMode(tenantId, scopeId, mode, environment) {
3382
3539
  await this.ensureMigrations();
3540
+ // #3639: production is named by no environment, whichever way an answer spells it.
3541
+ const named = environment && environment !== PRODUCTION_ENVIRONMENT ? environment : undefined;
3383
3542
  const prior = (await this.ctx.storage.get(DELIVERY_MODE_KEY)) ?? null;
3384
- const { next, seeded } = deliveryModeAfter(prior, mode, () => this.handoffSeed());
3543
+ const { next, seeded } = deliveryModeAfter(prior, mode, () => this.handoffSeed(), named);
3385
3544
  if (next === prior)
3386
3545
  return;
3387
3546
  if (!next) {
@@ -3389,7 +3548,7 @@ options = {}) {
3389
3548
  return;
3390
3549
  }
3391
3550
  if (seeded)
3392
- await this.keepHandoff({ tenantId, scopeId, marks: seeded });
3551
+ await this.keepHandoff({ tenantId, scopeId, ...(named ? { environment: named } : {}), marks: seeded });
3393
3552
  await this.ctx.storage.put(DELIVERY_MODE_KEY, next);
3394
3553
  // The window's start reaches the broker with the next handoff; one now, so a quiet scope has one too.
3395
3554
  if (seeded)
@@ -3410,14 +3569,16 @@ options = {}) {
3410
3569
  return intentStateOf(this.sql.exec(q.sql, ...q.params).toArray());
3411
3570
  }
3412
3571
  /** #3474: one point per handoff round, when the script binds `SUBSTRAT_BROKER_TELEMETRY`. */
3413
- reportHandoffRound(tenantId, scopeId, round, outcome) {
3572
+ reportHandoffRound(tenantId, scopeId, round, outcome,
3573
+ /** #3639: the named environment whose broker the round went to; undefined for production's. */
3574
+ environment) {
3414
3575
  if (this.brokerSink === undefined) {
3415
3576
  const dataset = brokerTelemetryDataset(this.env);
3416
3577
  this.brokerSink = dataset ? analyticsBrokerSink(dataset) : null;
3417
3578
  }
3418
3579
  if (!this.brokerSink)
3419
3580
  return;
3420
- reportHandoff(this.brokerSink, { tenantId, app: this.env.SUBSTRAT_VERTICAL ?? 'vertical', scopeId }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
3581
+ reportHandoff(this.brokerSink, { tenantId, app: this.env.SUBSTRAT_VERTICAL ?? 'vertical', ...(environment ? { environment } : {}), scopeId }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
3421
3582
  }
3422
3583
  brokerSink;
3423
3584
  /**
@@ -4024,6 +4185,17 @@ options = {}) {
4024
4185
  return await this.queue.enqueue(() => resolveDownloadLink({ sql: doSpineSql(this.sql), now: instant.parse(new Date().toISOString()) }, secret, attachmentId));
4025
4186
  });
4026
4187
  }
4188
+ /**
4189
+ * #2996 (K-64): spend a store proof on one call, on this scope's queue. The host's store stub
4190
+ * asks this before it sends the call, on every transport; see `redeemStoreProof`.
4191
+ */
4192
+ storeProofRedeemReply(secret, binding, operation, principal) {
4193
+ return replyOf(async () => {
4194
+ await this.ensureMigrations();
4195
+ await this.queue.enqueue(() => redeemStoreProof({ sql: doSpineSql(this.sql), now: instant.parse(new Date().toISOString()) }, secret, { binding, operation, principal }));
4196
+ return null;
4197
+ });
4198
+ }
4027
4199
  attachmentListReply(...args) {
4028
4200
  return replyOf(() => this.listAttachments(...args));
4029
4201
  }
@@ -4731,6 +4903,10 @@ options = {}) {
4731
4903
  * doors are a person acting, not a hot path, so one read is not threaded through both.
4732
4904
  */
4733
4905
  async reservedRoleRefusalFor(tenantId, roleKey, door) {
4906
+ // #2993 part 3: a role the vertical declares on other scope types only does not exist here.
4907
+ const typed = scopeTypeRoleRefusal(scopeTypePlan, this.scopeType(), roleKey);
4908
+ if (typed)
4909
+ return typed;
4734
4910
  if (door === 'platform' && this.reservedKeys.size === 0)
4735
4911
  return null;
4736
4912
  const role = await this.controlPlaneReader().getRole(tenantId, roleKey);
@@ -4750,6 +4926,10 @@ options = {}) {
4750
4926
  * door cannot know, so it refuses.
4751
4927
  */
4752
4928
  async reservedRoleRefusalHere(roleKey, door) {
4929
+ // #2993 part 3: as `reservedRoleRefusalFor`, which the early return below would skip.
4930
+ const typed = scopeTypeRoleRefusal(scopeTypePlan, this.scopeType(), roleKey);
4931
+ if (typed)
4932
+ return typed;
4753
4933
  if (door === 'platform' && this.reservedKeys.size === 0)
4754
4934
  return null;
4755
4935
  const tenantId = this.provisionedFor();
@@ -5306,7 +5486,7 @@ options = {}) {
5306
5486
  // here, so a purge is never run by both. It arms the alarm instead, which is also how a bin
5307
5487
  // filled before the switch was turned on, or an alarm that was lost, comes to be armed.
5308
5488
  if (mode === 'deferrable' && this.purgeDueByEvent()) {
5309
- await this.armPurgeAlarm(tenantId, scopeId);
5489
+ await this.armPurgeAlarm(tenantId, scopeId, false, true);
5310
5490
  return { purged: 0, skipped: 0, errors: [], more: false, lapFailed: 0, byAlarm: true };
5311
5491
  }
5312
5492
  const due = purgeDueOf(doSpineSql(this.sql), this.statePlans, this.operationTarget, operation, schedule.entityType, new Date().toISOString(), PURGE_BATCH);
@@ -5345,6 +5525,27 @@ options = {}) {
5345
5525
  * the EVALUATOR's last recorded time for that event type — a cadence gate
5346
5526
  * driven by a verdict nothing ran.
5347
5527
  */
5528
+ /**
5529
+ * #3540: one `due: 'event'` schedule's state, for the host deciding who runs it (`DueScheduleGate`).
5530
+ * `mode` is who asks: `deferrable`, a pass whose sweeper takes `runScopeDue` — then, with the switch
5531
+ * on, the scope remembers that, and a schedule that has run under the form is left to its alarm
5532
+ * (`byAlarm`), which is armed for it; or `alarm`, the scope's own alarm through that call, which
5533
+ * only reads. Absent is a pass that cannot, answered with the state alone, as a cadence read.
5534
+ */
5535
+ async dueScheduleGate(operation, tenantId, scopeId, mode) {
5536
+ await this.ensureMigrations();
5537
+ const due = this.dueSchedules.get(operation);
5538
+ if (!due)
5539
+ return { lastRunAt: await this.scheduleLastRun(operation), established: false, dueAt: null };
5540
+ const row = readScheduleDue(doSpineSql(this.sql), due);
5541
+ if (mode === 'deferrable' && this.dueByEventSwitched() && !this.isCopyRead()) {
5542
+ // The pair is the host's, which has already held it to this scope's record.
5543
+ await this.armPurgeAlarm(tenantId, scopeId, true, true);
5544
+ if (row.established)
5545
+ return { ...row, byAlarm: true };
5546
+ }
5547
+ return row;
5548
+ }
5348
5549
  async scheduleLastRun(operation) {
5349
5550
  const row = this.sql
5350
5551
  .exec(`SELECT last_run_at FROM _substrat_schedule_state WHERE kind = 'schedule' AND schedule_op = ?`, operation)
@@ -5753,9 +5954,96 @@ options = {}) {
5753
5954
  this.reconcileAskUnsignalled = false;
5754
5955
  return 1;
5755
5956
  }
5756
- /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
5957
+ /**
5958
+ * The derivation plans of the modules this scope runs — what `repairDerivedObjects` and its
5959
+ * checks read. #2993 part 3: a typed scope carries only its type's tables, so only what its type
5960
+ * runs was derived onto them.
5961
+ */
5757
5962
  derivedPlans() {
5758
- return { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
5963
+ const all = { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
5964
+ if (!scopeTypePlan.declared)
5965
+ return all;
5966
+ const own = (plans) => new Map([...plans].filter(([, plan]) => this.runs(plan.moduleId)));
5967
+ return { state: own(all.state), lists: own(all.lists), search: own(all.search) };
5968
+ }
5969
+ /**
5970
+ * #2993 part 3: this scope's type. `home` on a class with no declared types (read from nothing),
5971
+ * for a scope from before types, and for a store not provisioned yet, whose provision fixes it.
5972
+ */
5973
+ scopeType() {
5974
+ if (!scopeTypePlan.declared)
5975
+ return HOME_SCOPE_TYPE;
5976
+ return (this.scopeTypeHeld ??= this.metaValue(SCOPE_TYPE_META_KEY) ?? HOME_SCOPE_TYPE);
5977
+ }
5978
+ /** #2993 part 3: whether this scope's type runs the module. Every module runs on an untyped class. */
5979
+ runs(moduleId) {
5980
+ return !scopeTypePlan.declared || scopeTypeRuns(scopeTypePlan, this.scopeType(), moduleId);
5981
+ }
5982
+ /** #2993 part 3: the erasure plans of the modules this scope's type runs, whose tables it holds. */
5983
+ erasurePlansRun() {
5984
+ return scopeTypePlan.declared ? this.erasurePlans.filter((p) => this.runs(p.moduleId)) : this.erasurePlans;
5985
+ }
5986
+ /** #2993 part 3: the registered modules this scope's type runs, in registration order. */
5987
+ modulesRun() {
5988
+ const all = [...this.modules.values()];
5989
+ return scopeTypePlan.declared ? all.filter((m) => this.runs(m.id)) : all;
5990
+ }
5991
+ /**
5992
+ * #2993 part 3: fix this scope's type, at its provision — the hosted half of the pure host's
5993
+ * `scopes.scope_type`, kept in the scope's own `_substrat_meta` as its tenant is, because this
5994
+ * object decides which modules it runs. Judged by the kernel's rule against this class's
5995
+ * declared types: an undeclared type is `validation_failed`, and a type other than the one held
5996
+ * is `conflict`, both before anything is written. A store that holds no type but was provisioned,
5997
+ * or holds data, is a `home` scope (it ran every module); only an empty one takes a new type.
5998
+ *
5999
+ * Migrates nothing, so the host calls it before anything else touches a new scope: a pass run
6000
+ * first would lay down `home`'s tables. Answers the type held, written only when not `home`.
6001
+ */
6002
+ async fixScopeTypeReply(requested, scopeId) {
6003
+ return replyOf(() => this.queue.enqueue(() => {
6004
+ const held = this.metaValue(SCOPE_TYPE_META_KEY);
6005
+ const recorded = held !== null ? held : this.provisionedFor() !== null || this.holdsData() ? null : undefined;
6006
+ const type = provisionedScopeType(scopeTypePlan, requested, recorded, scopeId);
6007
+ if (held === null && type !== HOME_SCOPE_TYPE) {
6008
+ this.revision.transactionSync(() => {
6009
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, SCOPE_TYPE_META_KEY, type);
6010
+ });
6011
+ }
6012
+ this.scopeTypeHeld = type;
6013
+ return type;
6014
+ }));
6015
+ }
6016
+ /** #2995: this scope's parent, `null` when it has none. Read once; never written but by `fixScopeParentReply`. */
6017
+ scopeParent() {
6018
+ if (this.scopeParentHeld === undefined)
6019
+ this.scopeParentHeld = this.metaValue(PARENT_SCOPE_META_KEY);
6020
+ return this.scopeParentHeld;
6021
+ }
6022
+ /**
6023
+ * #2995 (K-64): fix this scope's parent, at its provision as a child — the hosted half of the pure
6024
+ * host's `scopes.parent_scope_id`, kept in the scope's own `_substrat_meta` beside its type, so a
6025
+ * CP-less host's doors can judge a child with no directory to ask. Fixed once, by the kernel's
6026
+ * `provisionedParent`: a provision restating the link, or naming none, keeps it; one naming another
6027
+ * parent, or a parent for a store already provisioned without one, is `conflict` and writes nothing.
6028
+ * Called after `fixScopeTypeReply` and before anything migrates. Answers the parent held.
6029
+ */
6030
+ async fixScopeParentReply(requested, scopeId) {
6031
+ return replyOf(() => this.queue.enqueue(() => {
6032
+ const held = this.metaValue(PARENT_SCOPE_META_KEY);
6033
+ const recorded = held !== null ? held : this.provisionedFor() !== null || this.holdsData() ? null : undefined;
6034
+ const parent = provisionedParent(requested, recorded, scopeId);
6035
+ if (held === null && parent !== null) {
6036
+ this.revision.transactionSync(() => {
6037
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, PARENT_SCOPE_META_KEY, parent);
6038
+ });
6039
+ }
6040
+ this.scopeParentHeld = parent;
6041
+ return parent;
6042
+ }));
6043
+ }
6044
+ /** #2993 part 3: this scope's type, for a host that seats or probes by it. Reads; writes nothing. */
6045
+ async scopeTypeHere() {
6046
+ return this.scopeType();
5759
6047
  }
5760
6048
  /** A multi-statement script on this DO's own handle, one statement per exec. */
5761
6049
  runScript(ddl) {
@@ -5789,7 +6077,8 @@ options = {}) {
5789
6077
  }
5790
6078
  /** Resolves true if this call applied at least one migration. */
5791
6079
  async applyPendingMigrations() {
5792
- const { pending, diverged } = await planMigrations(this.modules.values(), this.applied);
6080
+ // #2993 part 3: a scope applies only its type's migrations, so it carries no other type's tables.
6081
+ const { pending, diverged } = await planMigrations(this.modulesRun(), this.applied);
5793
6082
  if (diverged) {
5794
6083
  // Recorded as a failed migration is, so the coordinator projects it the same way.
5795
6084
  this.lastFailure = diverged;
@@ -7039,6 +7328,9 @@ options = {}) {
7039
7328
  // #2096: a purge horizon's lap in progress, on a scope DO built before the column. NULL is
7040
7329
  // the start of a lap — the honest reading of every row already there.
7041
7330
  'ALTER TABLE _substrat_schedule_state ADD COLUMN purge_cursor TEXT',
7331
+ // #3540: a due-by-event schedule's next date, on a scope DO built before the column. NULL is
7332
+ // "not yet run under the form", so its cadence decides: the honest reading of every row there.
7333
+ 'ALTER TABLE _substrat_schedule_state ADD COLUMN due_at TEXT',
7042
7334
  // #2009: the copy classification on a scope DO built before it (NULL reads as a copy;
7043
7335
  // see `COPY_ORIGIN_DDL`).
7044
7336
  'ALTER TABLE _substrat_copy_origin ADD COLUMN is_copy INTEGER',
@@ -7199,6 +7491,10 @@ options = {}) {
7199
7491
  return { name: t.name, columns: ['id'], rows: at < 0 ? [] : Array.from(t.rows(), (row) => [row[at]]) };
7200
7492
  }));
7201
7493
  const receiptBefore = this.provisionedFor();
7494
+ // #2993 part 3: the type this store's own provision fixed, which a load never changes.
7495
+ const typeBefore = this.metaValue(SCOPE_TYPE_META_KEY);
7496
+ // #2995: and the parent it fixed, which a load never changes either: a copy carries none.
7497
+ const parentBefore = this.metaValue(PARENT_SCOPE_META_KEY);
7202
7498
  // #2555: this store's own permission flags, read before the drops take them.
7203
7499
  const flagsBefore = keepPermissionFlags ? PERMISSION_FLAG_KEYS.map((key) => [key, this.metaValue(key)]) : [];
7204
7500
  if (provisionedFor !== undefined && receiptBefore !== null && receiptBefore !== provisionedFor) {
@@ -7306,6 +7602,19 @@ options = {}) {
7306
7602
  if (value !== null)
7307
7603
  this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, key, value);
7308
7604
  }
7605
+ // #2993 part 3: the scope's type is this store's, as its receipt is. No dump carries it
7606
+ // (`STORE_LOCAL_META_KEYS`); one from elsewhere that did is overruled here all the same.
7607
+ this.sql.exec(`DELETE FROM _substrat_meta WHERE key = ?`, SCOPE_TYPE_META_KEY);
7608
+ if (typeBefore !== null) {
7609
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, SCOPE_TYPE_META_KEY, typeBefore);
7610
+ }
7611
+ this.sql.exec(`DELETE FROM _substrat_meta WHERE key = ?`, PARENT_SCOPE_META_KEY);
7612
+ if (parentBefore !== null) {
7613
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, PARENT_SCOPE_META_KEY, parentBefore);
7614
+ }
7615
+ // Read again from what the load left, as a wake would: the store is the type's only record.
7616
+ this.scopeTypeHeld = undefined;
7617
+ this.scopeParentHeld = undefined;
7309
7618
  // #1722: whatever stamp an export read here no longer describes this store, so every load
7310
7619
  // replaces it: with the carry's own, or with none. And the write revision moves on from
7311
7620
  // where it stood before the drops, so it never goes back.
@@ -8018,7 +8327,9 @@ options = {}) {
8018
8327
  * one: whatever a handoff switch says, since a broker keeps what it took while it was on.
8019
8328
  *
8020
8329
  * The broker and the ids its messages are kept under are named first from the handoff state:
8021
- * the (tenant, scope) every handoff of this scope used, written before its first broker call. A
8330
+ * the (tenant, scope) every handoff of this scope used, written before its first broker call, and
8331
+ * (#3639) the environment whose broker those handoffs reached, so a named environment's messages
8332
+ * are erased where they went, never looked for in production's broker. A
8022
8333
  * scope whose state is gone (a restore) falls back to its own identity, its `provisioned_for`
8023
8334
  * receipt and its object name, as `wakeForReconcileAsk` reads them. So `redactSubject` takes no
8024
8335
  * new argument, and a coordinator of any version reaches the broker. A scope that can name it by
@@ -8033,7 +8344,8 @@ options = {}) {
8033
8344
  if (!tenant.success || !scope.success) {
8034
8345
  throw substratError('unavailable', 'subject erasure: this scope cannot name its delivery broker, so its copies were not erased');
8035
8346
  }
8036
- await this.deliveryBroker(tenant.data).eraseSubject({ tenantId: tenant.data, scopeId: scope.data, subjectId, at });
8347
+ // #3639: the broker of the scope's environment, which the handoff state keeps after the mode went off.
8348
+ await this.deliveryBroker(tenant.data, await this.handoffEnvironment()).eraseSubject({ tenantId: tenant.data, scopeId: scope.data, subjectId, at });
8037
8349
  }
8038
8350
  /**
8039
8351
  * One page of what this scope holds about one data subject (GDPR Art. 15, D-74): the kernel's
@@ -8046,7 +8358,7 @@ options = {}) {
8046
8358
  try {
8047
8359
  // Inside the envelope: a migration refusal is an answer too, and keeps its code across the RPC.
8048
8360
  await this.ensureMigrations();
8049
- return readSubjectPage({ sql: doSpineSql(this.sql), plans: this.erasurePlans, subjectId, ...(page ? { page } : {}) });
8361
+ return readSubjectPage({ sql: doSpineSql(this.sql), plans: this.erasurePlansRun(), subjectId, ...(page ? { page } : {}) });
8050
8362
  }
8051
8363
  catch (err) {
8052
8364
  return { failure: toWireFailure(err) };
@@ -8056,11 +8368,13 @@ options = {}) {
8056
8368
  redactSubjectInTransaction(subjectId, at) {
8057
8369
  // The module half first (#2068): the declared entities, then each hook, with the search
8058
8370
  // indexes over them under FTS5 secure-delete. The spine half follows in the same transaction.
8371
+ // #2993 part 3: the modules this scope's type runs — another type's tables are not here.
8372
+ const derived = this.derivedPlans();
8059
8373
  const vertical = eraseSubjectFromModules({
8060
8374
  sql: doSpineSql(this.sql),
8061
- plans: this.erasurePlans,
8062
- searchPlans: this.searchPlans.values(),
8063
- statefulTables: statefulTablesOf(this.statePlans),
8375
+ plans: this.erasurePlansRun(),
8376
+ searchPlans: derived.search.values(),
8377
+ statefulTables: statefulTablesOf(derived.state),
8064
8378
  subjectId,
8065
8379
  at,
8066
8380
  migrationSqlOf: (moduleId, version) => this.modules.get(moduleId)?.migrations.find((m) => m.version === version)?.sql,
@@ -8148,7 +8462,8 @@ options = {}) {
8148
8462
  async dispatchRounds(tenantId, scopeId, invocationId, lines) {
8149
8463
  for (let round = 0; round < 50; round++) {
8150
8464
  let deliveredAny = false;
8151
- for (const mod of this.modules.values()) {
8465
+ // #2993 part 3: a module this scope's type does not run consumes nothing here.
8466
+ for (const mod of this.modulesRun()) {
8152
8467
  for (const consumer of mod.consumers) {
8153
8468
  const rows = this.sql
8154
8469
  .exec(`SELECT * FROM _substrat_outbox o
@@ -8671,6 +8986,21 @@ options = {}) {
8671
8986
  },
8672
8987
  atomic: createAtomic(runSub, { passed, signals }),
8673
8988
  noteTransition: noteTransitionInto(signals),
8989
+ // #3540: the schedule named is due no later than `due`, written in this operation's transaction.
8990
+ scheduleDue: (operation, due) => noteScheduleDue(doSpineSql(sql), this.dueSchedules, operation, due),
8991
+ // #2996 (K-64): the proof a store call needs, written once in the kernel. The declared key is
8992
+ // checked as the caller (a consumer's system actor is refused: its checks allow everything).
8993
+ storeProof: (binding, operation) => mintStoreProof({
8994
+ sql: doSpineSql(sql),
8995
+ subject,
8996
+ consumer: Boolean(systemActor),
8997
+ // The mint's own instant, so the proof's minute starts when it is minted.
8998
+ now: instant.parse(new Date().toISOString()),
8999
+ check: runCheck,
9000
+ assertWrites: (verb) => assertImpersonationWrites(impersonation, verb),
9001
+ minted,
9002
+ keyOf: (b, o) => storeOperationKeyOf(options.permissions?.stores, b, o),
9003
+ }, binding, operation),
8674
9004
  // #1672: mint / revoke / list, written once in the kernel — the pure adapter hands
8675
9005
  // the same function the same four things. The raw spine seam (the kernel's own write
8676
9006
  // to `_substrat_capabilities`), the operation's OWN check, and `ctx.emit`. A