@substrat-run/adapter-cloudflare 0.219.0 → 0.221.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/control-plane-do.d.ts +107 -5
  2. package/dist/control-plane-do.d.ts.map +1 -1
  3. package/dist/control-plane-do.js +207 -16
  4. package/dist/control-plane-do.js.map +1 -1
  5. package/dist/directory-mirror-backfill.d.ts +143 -0
  6. package/dist/directory-mirror-backfill.d.ts.map +1 -0
  7. package/dist/directory-mirror-backfill.js +467 -0
  8. package/dist/directory-mirror-backfill.js.map +1 -0
  9. package/dist/directory-mirror-verify.d.ts +166 -0
  10. package/dist/directory-mirror-verify.d.ts.map +1 -0
  11. package/dist/directory-mirror-verify.js +478 -0
  12. package/dist/directory-mirror-verify.js.map +1 -0
  13. package/dist/directory-mirror.d.ts +101 -3
  14. package/dist/directory-mirror.d.ts.map +1 -1
  15. package/dist/directory-mirror.js +143 -37
  16. package/dist/directory-mirror.js.map +1 -1
  17. package/dist/directory-objects.d.ts +14 -0
  18. package/dist/directory-objects.d.ts.map +1 -1
  19. package/dist/directory-objects.js +34 -0
  20. package/dist/directory-objects.js.map +1 -1
  21. package/dist/directory-placement.d.ts.map +1 -1
  22. package/dist/directory-placement.js +10 -2
  23. package/dist/directory-placement.js.map +1 -1
  24. package/dist/directory-split-inventory.d.ts +2 -1
  25. package/dist/directory-split-inventory.d.ts.map +1 -1
  26. package/dist/directory-split-inventory.js +4 -1
  27. package/dist/directory-split-inventory.js.map +1 -1
  28. package/dist/host.d.ts +71 -5
  29. package/dist/host.d.ts.map +1 -1
  30. package/dist/host.js +293 -37
  31. package/dist/host.js.map +1 -1
  32. package/dist/peer-call-target.d.ts.map +1 -1
  33. package/dist/peer-call-target.js +3 -2
  34. package/dist/peer-call-target.js.map +1 -1
  35. package/dist/route-read-model-publisher.d.ts +42 -1
  36. package/dist/route-read-model-publisher.d.ts.map +1 -1
  37. package/dist/route-read-model-publisher.js +176 -55
  38. package/dist/route-read-model-publisher.js.map +1 -1
  39. package/dist/route-read-model.d.ts +15 -0
  40. package/dist/route-read-model.d.ts.map +1 -1
  41. package/dist/route-read-model.js +21 -9
  42. package/dist/route-read-model.js.map +1 -1
  43. package/dist/scope-do.d.ts +48 -1
  44. package/dist/scope-do.d.ts.map +1 -1
  45. package/dist/scope-do.js +434 -29
  46. package/dist/scope-do.js.map +1 -1
  47. package/dist/scope-sweeper-do.d.ts +24 -0
  48. package/dist/scope-sweeper-do.d.ts.map +1 -1
  49. package/dist/scope-sweeper-do.js +90 -1
  50. package/dist/scope-sweeper-do.js.map +1 -1
  51. package/dist/scope-work.d.ts +2 -2
  52. package/dist/scope-work.js +2 -2
  53. package/dist/scope-work.js.map +1 -1
  54. package/package.json +18 -13
package/dist/scope-do.js CHANGED
@@ -1,30 +1,40 @@
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 { 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, } 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, 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
8
  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
9
  import { replyOf } from './do-reply.js';
8
10
  import { OperationQueue } from './serialization.js';
9
11
  import { reconcileOnWake } from './reconcile-on-wake.js';
10
12
  import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
11
13
  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_BATCH, heldPurgePass, 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';
14
+ 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
15
  import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove } from '@substrat-run/kernel';
14
16
  import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRefusal } from '@substrat-run/kernel';
15
17
  import { createDoTupleChecker, createLocalControlPlaneReader, scopeTupleReader } from './checker.js';
16
- import { settlePlatformRequestIn } from '@substrat-run/kernel';
18
+ import { clearSettledEmailIn, settlePlatformRequestIn } from '@substrat-run/kernel';
17
19
  import { loadDropsRowsOf, SCOPE_COPY_LEASE_MS, ulidTime } from '@substrat-run/kernel';
18
20
  import { handoffOutcome, reportHandoff, traceIdOf } from '@substrat-run/kernel';
19
21
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
20
22
  import { analyticsBrokerSink, brokerTelemetryDataset } from './broker-telemetry.js';
21
23
  import { DELIVERY_HANDOFF_KEY, DELIVERY_MODE_KEY, HANDOFF_ROUNDS, deliveryModeAfter, handoffAfterFailure, handoffDue, handoffPending, mergeHandoff, sameMarks, } from './delivery-handoff.js';
22
24
  import { registerPlatformDeliveryBroker } from './delivery-broker-platform.js';
23
- import { advanceMarks, brokerName, handoffQueries, messagesOf } from '@substrat-run/kernel';
25
+ import { advanceMarks, brokerName, handoffQueries, messagesOf, senderDeliveryOf } from '@substrat-run/kernel';
24
26
  import { DELIVERY_HANDOFF_ENV, intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
27
+ import { SCOPE_SWEEPER_NAME } from './scope-sweeper-do.js';
25
28
  import { SCOPE_WAKE_KEY, keepRegisteredMeanwhile, kickControlPlane, runWake, wakeAfterCommit, wakeDueAt } from './scope-wake.js';
26
29
  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';
27
30
  import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
31
+ /**
32
+ * #3540: the storage KV key of the scope's purge alarm — the pair the alarm asks its sweeper to run,
33
+ * which a commit names and the alarm does not otherwise know, and the instant before which no purge
34
+ * run is asked again (`notBefore`, set after a run that made no progress). KV, not SQL, as the wake's
35
+ * state is: what the scope's rows say is due is read from them every time (`purgeDueAt`).
36
+ */
37
+ export const PURGE_ALARM_KEY = 'substrat:purge-alarm';
28
38
  /** A scope's migration journal: `module@version` → the SQL digest it recorded (#2066). */
29
39
  function readAppliedMigrations(sql) {
30
40
  const rows = sql.exec('SELECT module_id, version, sql_digest FROM _substrat_migrations').toArray();
@@ -408,6 +418,9 @@ const KERNEL_DDL = `
408
418
  -- #3139: download links, a short-lived URL that lets a caller with no session read ONE file as
409
419
  -- the principal who minted it. Shared with the pure adapter from @substrat-run/kernel.
410
420
  ${DOWNLOAD_LINK_DDL}
421
+ -- #2996 (K-64): store proofs, a short-lived, single-use proof that an operation checked the key
422
+ -- of one store operation. Spine (kernel-written), shared with the other adapter from the kernel.
423
+ ${STORE_PROOF_DDL}
411
424
  -- #1686: where a copied scope's data came from, and the event id its own events start above.
412
425
  -- Shared with the other adapter from @substrat-run/kernel; the column comments are there.
413
426
  ${COPY_ORIGIN_DDL}
@@ -928,11 +941,17 @@ options = {}) {
928
941
  // import, rather than at the first scope it wakes.
929
942
  for (const registration of modules)
930
943
  assertModuleDeclared(options.permissions, registration.manifest.id);
944
+ // #3488: the sender's delivery declarations by type, which every handoff reads. Two modules
945
+ // declaring one type differently fail here, at the worker's first import.
946
+ const senders = senderDeliveryOf(modules.map((m) => m.manifest));
931
947
  // A5 (#3471): the broker the platform's supplied class forwards to is this kernel's.
932
948
  registerPlatformDeliveryBroker();
933
949
  // What the declared surface reserves holds in every instance too, whatever registers under its ids.
934
950
  const declaredReserved = new Set();
935
951
  const declaredListed = new Set();
952
+ // #2993 part 3: which modules (and roles) a scope of each declared type has. A class given no
953
+ // declared types has one 'home' type running every module, and reads no type at all.
954
+ const scopeTypePlan = scopeTypePlanOf(options.permissions);
936
955
  for (const m of options.permissions?.modules ?? []) {
937
956
  noteReservedKeys(declaredReserved, m.manifest);
938
957
  noteDeclaredKeys(declaredListed, m.manifest);
@@ -996,6 +1015,17 @@ options = {}) {
996
1015
  purgeOnlyKeys = new Map();
997
1016
  /** #119: a purge schedule's operation → the module that declared it and the entity it purges. */
998
1017
  purgeSchedules = new Map();
1018
+ /**
1019
+ * #3540: every registered schedule declared `due: 'event'`, by operation — what `ctx.scheduleDue`
1020
+ * may name, and the operations whose every run clears their date in its own transaction.
1021
+ */
1022
+ dueSchedules = new Map();
1023
+ /**
1024
+ * #3540: true while this scope's alarm is waiting on its sweeper's purge run. The purges that
1025
+ * run meanwhile commit through `settleCommitted`, and must not arm the alarm the handler is about
1026
+ * to set from what the run left.
1027
+ */
1028
+ #purgeAlarmRunning = false;
999
1029
  /** #116: the operations that declared `idempotency: false` — refusals, not participants. */
1000
1030
  operationIdempotencyOptOut = new Set();
1001
1031
  /** #2821: the operations that declared `impersonation: 'refused'` — no session may invoke them. */
@@ -1003,6 +1033,13 @@ options = {}) {
1003
1033
  /** #2387: the operations held to a `ctx.check` — the pure adapter's set, from the same kernel read. */
1004
1034
  operationCheckHeld = new Set();
1005
1035
  modules = new Map();
1036
+ /** #2993 part 3: a bound operation → the module that declared it, which the scope's type runs or not. */
1037
+ operationModule = new Map();
1038
+ /**
1039
+ * #2993 part 3: this scope's type, read once from `_substrat_meta` (a type never changes; the
1040
+ * fix and a load are the only writers, and both set it here). Undefined until first read.
1041
+ */
1042
+ scopeTypeHeld;
1006
1043
  /**
1007
1044
  * #2430: what a registered module, or a module the class's declared `permissions` lists, declares
1008
1045
  * `holder: 'system'` — the role and grant doors' refusals read it.
@@ -1196,9 +1233,16 @@ options = {}) {
1196
1233
  // #119: refused before anything is recorded, as in the pure adapter.
1197
1234
  const trashTargets = registerTrashTargets(manifest.id, new Set(Object.keys(registration.operations?.handlers ?? {})), registration.operations?.inputs, manifest.entityStates, manifest.schedules);
1198
1235
  this.purgeOnlyKeys.set(manifest.id, purgeOnlyKeysOf(manifest.schedules ?? []));
1236
+ for (const [operation, due] of dueByEventSchedulesOf(manifest.schedules))
1237
+ this.dueSchedules.set(operation, due);
1199
1238
  for (const schedule of manifest.schedules ?? []) {
1200
- if (schedule.purge)
1201
- this.purgeSchedules.set(schedule.operation, { moduleId: manifest.id, entityType: schedule.purge.entityType });
1239
+ if (schedule.purge) {
1240
+ this.purgeSchedules.set(schedule.operation, {
1241
+ moduleId: manifest.id,
1242
+ entityType: schedule.purge.entityType,
1243
+ everyMinutes: schedule.cadence.everyMinutes,
1244
+ });
1245
+ }
1202
1246
  }
1203
1247
  // #2068: refused before anything is recorded, as on the pure host.
1204
1248
  const erasure = moduleErasurePlan(registration);
@@ -1327,6 +1371,8 @@ options = {}) {
1327
1371
  const checkHeld = checkHeldOperationsOf(registration.operations);
1328
1372
  for (const [name, handler] of Object.entries(registration.operations?.handlers ?? {})) {
1329
1373
  this.defineOperation(name, handler);
1374
+ if (this.operations.has(name))
1375
+ this.operationModule.set(name, manifest.id);
1330
1376
  if (checkHeld.has(name) && this.operations.has(name))
1331
1377
  this.operationCheckHeld.add(name);
1332
1378
  // The schema follows the HANDLER, not the name: a withdrawn operation
@@ -1788,13 +1834,25 @@ options = {}) {
1788
1834
  async importApply(batch, tenantId, scopeId,
1789
1835
  /** #2029: the instance the peer door's gate read for the producer; on another, nothing applies. */
1790
1836
  doorInstance) {
1837
+ return this.applyImport(batch, tenantId, scopeId, doorInstance, { after: batch.after, next: batch.next });
1838
+ }
1839
+ /**
1840
+ * K-74 (#3492): an event another app's broker PUSHED here. `importApply`'s body with no
1841
+ * compare-and-set and no watermark move, so a pushed event that arrives ahead of an earlier
1842
+ * one cannot make the pull path skip that one; the pull path finds this one journaled.
1843
+ */
1844
+ async importPushed(pushed, tenantId, scopeId, doorInstance) {
1845
+ return this.applyImport(pushed, tenantId, scopeId, doorInstance, null);
1846
+ }
1847
+ /** One import, pulled (`edge`: the compare-and-set and the advance) or pushed (`edge` null). */
1848
+ async applyImport(batch, tenantId, scopeId, doorInstance, edge) {
1791
1849
  const source = batch.source;
1792
1850
  if (this.peerDoorMoved(source.vertical, doorInstance))
1793
1851
  return SYSTEM_DOOR_MOVED;
1794
1852
  await this.ensureMigrations();
1795
1853
  return await this.queue.enqueue(async () => {
1796
1854
  const liveSince = this.liveHighWaterMark();
1797
- const result = emptyImportResult(batch);
1855
+ const result = emptyImportResult({ after: edge?.after ?? null });
1798
1856
  // #1706's door, for a delivery (`operation: null`), inside the queued body: the producer
1799
1857
  // is a declared peer with its switch on, or nothing runs and the edge pauses.
1800
1858
  let peerSubject;
@@ -1806,7 +1864,9 @@ options = {}) {
1806
1864
  }
1807
1865
  const current = (this.sql.exec(IMPORT_CURSOR_OF_SQL, source.scopeId).toArray()[0]
1808
1866
  ?.cursor ?? null);
1809
- if (current !== batch.after)
1867
+ if (edge === null)
1868
+ result.cursor = current;
1869
+ else if (current !== edge.after)
1810
1870
  return { ...result, cursor: current, stale: true };
1811
1871
  const at = new Date().toISOString();
1812
1872
  const journaled = (id, moduleId) => this.sql
@@ -1882,8 +1942,11 @@ options = {}) {
1882
1942
  if (!ran)
1883
1943
  result.duplicates += 1;
1884
1944
  }
1885
- this.sql.exec(IMPORT_CURSOR_ADVANCE_SQL, source.scopeId, source.vertical, batch.next, at);
1886
- result.cursor = batch.next;
1945
+ // A pushed event moves nothing (#3492).
1946
+ if (edge !== null) {
1947
+ this.sql.exec(IMPORT_CURSOR_ADVANCE_SQL, source.scopeId, source.vertical, edge.next, at);
1948
+ result.cursor = edge.next;
1949
+ }
1887
1950
  lines.end();
1888
1951
  await this.settleCommitted(tenantId, scopeId, liveSince, null);
1889
1952
  return result;
@@ -1944,7 +2007,7 @@ options = {}) {
1944
2007
  due,
1945
2008
  ...(handedOffThrough === undefined ? {} : { handedOffThrough }),
1946
2009
  // Executors run on the coordinator, which names them; the consumers are this DO's own.
1947
- subscribers: [...outboxSubscribersOf(this.modules.values(), []), ...executors],
2010
+ subscribers: [...outboxSubscribersOf(this.modulesRun(), []), ...executors],
1948
2011
  exportTypes: this.crossVertical.exportTypes(),
1949
2012
  })));
1950
2013
  }
@@ -2449,6 +2512,10 @@ options = {}) {
2449
2512
  // else. Naming the code once here is what lets those patterns go.
2450
2513
  if (!handler)
2451
2514
  throw substratError('not_found', `unknown operation: ${operation}`);
2515
+ // #2993 part 3: an operation of a module this scope's type does not run is unknown here.
2516
+ const declaredBy = this.operationModule.get(operation);
2517
+ if (declaredBy !== undefined && !this.runs(declaredBy))
2518
+ throw operationNotInScopeType(operation, this.scopeType());
2452
2519
  // #2821: before the parse, the guards and the handler — and under read-only too.
2453
2520
  assertImpersonationAdmitted(impersonation, operation, this.operationImpersonationRefused);
2454
2521
  // #304 entitlement gate, scope-local path: fail closed on the projected view exactly as
@@ -2671,6 +2738,10 @@ options = {}) {
2671
2738
  // #2166: what the guards and the handler emit about a stamped entity, held below.
2672
2739
  const stamps = watchUpdatedStamps(doSpineSql(this.sql), this.updatedStampPlans);
2673
2740
  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);
2741
+ // #3540: a run of a due-by-event schedule's operation clears its date first, in this
2742
+ // transaction — the pure adapter's, through the same kernel function.
2743
+ if (this.dueSchedules.has(operation))
2744
+ consumeScheduleDue(doSpineSql(this.sql), operation);
2674
2745
  await this.runGuards(operation, ctx, parsed);
2675
2746
  // #2387: the handler's own checks only — the pure adapter's reset, for its reason.
2676
2747
  checks.calls = 0;
@@ -2993,14 +3064,192 @@ options = {}) {
2993
3064
  await this.ctx.storage.setAlarm(at);
2994
3065
  }
2995
3066
  /**
2996
- * The scope's alarm, shared by its two users: the live reaper (#938) closes what has expired, and
2997
- * the scope's wake (K-69, `scope-wake.ts`) asks for the drains its pending work is waiting on.
2998
- * Each re-arms for what it has next, earliest wins.
3067
+ * The scope's alarm, shared by its users: the live reaper (#938) closes what has expired, the
3068
+ * scope's wake (K-69, `scope-wake.ts`) asks for the drains its pending work is waiting on, the
3069
+ * broker handoff retries (K-74), and the purge alarm (#3540) asks for the purges its bins have
3070
+ * made due. Each re-arms for what it has next, earliest wins.
2999
3071
  */
3000
3072
  async alarm() {
3001
3073
  await this.armLiveExpiry();
3002
3074
  await this.runScopeWake();
3003
3075
  await this.retryHandoff();
3076
+ await this.runPurgeAlarm();
3077
+ }
3078
+ /**
3079
+ * #3540: whether this scope's purges are due by event: the switch is `event`, a sweeper is bound
3080
+ * for the alarm to ask, and a registered module declares a purge horizon.
3081
+ */
3082
+ purgeDueByEvent() {
3083
+ return this.dueByEventSwitched() && this.purgeSchedules.size > 0;
3084
+ }
3085
+ /** #3540: the switch is `event` and a sweeper is bound for the alarm to ask. */
3086
+ dueByEventSwitched() {
3087
+ return this.env.SUBSTRAT_PURGE_DUE === PURGE_DUE_BY_EVENT && this.env.SWEEPER !== undefined;
3088
+ }
3089
+ /**
3090
+ * #3540: whether anything here can be due by event: the switch, and a purge horizon or a
3091
+ * `due: 'event'` schedule among the registered modules.
3092
+ */
3093
+ dueAlarmApplies() {
3094
+ return this.dueByEventSwitched() && (this.purgeSchedules.size > 0 || this.dueSchedules.size > 0);
3095
+ }
3096
+ /** #3540: when this scope's purges are next due, read from its own rows (`purgeDueAt`). */
3097
+ purgeDueAtNow(now) {
3098
+ const schedules = [...this.purgeSchedules].map(([operation, s]) => ({ operation, entityType: s.entityType, everyMinutes: s.everyMinutes }));
3099
+ return purgeDueAt(doSpineSql(this.sql), this.statePlans, schedules, now);
3100
+ }
3101
+ /**
3102
+ * #3540: when anything here is next due by event — the purges, and, once a pass has said its
3103
+ * sweeper takes `runScopeDue` (`schedules`), the `due: 'event'` schedules that have run under
3104
+ * that form (`scheduleDueAt`). Earliest wins.
3105
+ */
3106
+ dueAtNow(now, schedules) {
3107
+ const purges = this.purgeDueByEvent() ? this.purgeDueAtNow(now) : null;
3108
+ const events = schedules && this.dueSchedules.size > 0 ? scheduleDueAt(doSpineSql(this.sql), this.dueSchedules.values()) : null;
3109
+ return purges === null ? events : events === null ? purges : Math.min(purges, events);
3110
+ }
3111
+ /**
3112
+ * #3540: arm the scope's alarm for its earliest due work, and record the pair the alarm will ask
3113
+ * for. Never before the `notBefore` a run with no progress left. A copy arms nothing: a fork, a
3114
+ * snapshot or a preview runs no schedule. Answers whether anything is armed.
3115
+ *
3116
+ * `takesSchedules` is a pass saying its sweeper can take `runScopeDue` (`ScheduleTick.alarmRunsDue`);
3117
+ * it is remembered, and only from then on does the alarm cover the `due: 'event'` schedules, so a
3118
+ * scope whose sweeper predates that call never arms for work it would not run.
3119
+ */
3120
+ async armPurgeAlarm(tenantId, scopeId, takesSchedules = false) {
3121
+ if (!this.dueAlarmApplies() || this.isCopyRead())
3122
+ return false;
3123
+ const held = (await this.ctx.storage.get(PURGE_ALARM_KEY)) ?? null;
3124
+ const schedules = takesSchedules || held?.schedules === true;
3125
+ const at = this.dueAtNow(Date.now(), schedules);
3126
+ if (at === null && !(takesSchedules && !held?.schedules))
3127
+ return false;
3128
+ if (!held || held.tenantId !== tenantId || held.scopeId !== scopeId || (schedules && !held.schedules)) {
3129
+ await this.ctx.storage.put(PURGE_ALARM_KEY, {
3130
+ tenantId,
3131
+ scopeId,
3132
+ ...(held?.notBefore !== undefined && held.tenantId === tenantId && held.scopeId === scopeId ? { notBefore: held.notBefore } : {}),
3133
+ ...(schedules ? { schedules: true } : {}),
3134
+ });
3135
+ }
3136
+ if (at === null)
3137
+ return false;
3138
+ await this.armAlarmBy(Math.max(at, held?.notBefore ?? 0));
3139
+ return true;
3140
+ }
3141
+ /**
3142
+ * #3540: after a commit, arm the alarm for what is now earliest: a row it binned, or a date it
3143
+ * wrote with `ctx.scheduleDue`. Never fails the commit it follows: an alarm not armed costs
3144
+ * latency, and the sweeper's pass re-arms it (the safety net).
3145
+ */
3146
+ async notePurgeDue(tenantId, scopeId) {
3147
+ if (this.#purgeAlarmRunning || !this.dueAlarmApplies())
3148
+ return;
3149
+ try {
3150
+ await this.armPurgeAlarm(tenantId, scopeId);
3151
+ }
3152
+ catch (err) {
3153
+ console.error('substrat: due alarm not armed after commit; the sweeper pass re-arms it', err);
3154
+ }
3155
+ }
3156
+ /**
3157
+ * #3540: the due alarm's half of `alarm()`. When something is due by event, the scope asks its
3158
+ * sweeper to run it for this scope alone — `runScopeDue` (its purges and its `due: 'event'`
3159
+ * schedules) once a pass has said the sweeper takes that call, `runScopePurges` until then — which
3160
+ * runs it through the coordinator's door, with every gate a pass applies. Then it re-arms from
3161
+ * what its rows say now:
3162
+ *
3163
+ * - nothing left due (a restore cancelled it, or the run did it): nothing armed;
3164
+ * - a purge lap left open by a run that answered: due again at once, since that run made progress;
3165
+ * - otherwise never sooner than `PURGE_ALARM_MIN_GAP_MS`, or the shortest cadence when the
3166
+ * sweeper could not be asked, so a run that cannot progress cannot spin the alarm;
3167
+ * - a run the sweeper held (a lifecycle, a switch, a scope off its roster): not re-armed, and no
3168
+ * commit re-arms it within the cadence. The pass re-arms it when the scope's schedules run.
3169
+ *
3170
+ * Never throws: a thrown alarm is retried by the runtime.
3171
+ */
3172
+ async runPurgeAlarm() {
3173
+ try {
3174
+ const state = (await this.ctx.storage.get(PURGE_ALARM_KEY)) ?? null;
3175
+ if (!state)
3176
+ return;
3177
+ // The switch turned off, or the scope became a copy: the pass has it again, or nothing does.
3178
+ if (!this.dueAlarmApplies() || this.isCopyRead()) {
3179
+ await this.ctx.storage.delete(PURGE_ALARM_KEY);
3180
+ return;
3181
+ }
3182
+ await this.ensureMigrations();
3183
+ const schedules = state.schedules === true;
3184
+ const keep = (notBefore) => ({
3185
+ tenantId: state.tenantId,
3186
+ scopeId: state.scopeId,
3187
+ ...(notBefore !== undefined ? { notBefore } : {}),
3188
+ ...(schedules ? { schedules: true } : {}),
3189
+ });
3190
+ // Nothing due: only a record that says the sweeper takes `runScopeDue` is worth keeping.
3191
+ const settle = async () => {
3192
+ if (schedules)
3193
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep());
3194
+ else
3195
+ await this.ctx.storage.delete(PURGE_ALARM_KEY);
3196
+ };
3197
+ const now = Date.now();
3198
+ const at = this.dueAtNow(now, schedules);
3199
+ if (at === null) {
3200
+ await settle();
3201
+ return;
3202
+ }
3203
+ const notBefore = state.notBefore ?? 0;
3204
+ if (at > now || notBefore > now) {
3205
+ await this.armAlarmBy(Math.max(at, notBefore));
3206
+ return;
3207
+ }
3208
+ const sweeper = this.env.SWEEPER;
3209
+ let answer;
3210
+ this.#purgeAlarmRunning = true;
3211
+ try {
3212
+ const stub = sweeper.get(sweeper.idFromName(SCOPE_SWEEPER_NAME));
3213
+ answer = schedules
3214
+ ? await stub.runScopeDue(state.tenantId, state.scopeId)
3215
+ : await stub.runScopePurges(state.tenantId, state.scopeId);
3216
+ }
3217
+ catch (err) {
3218
+ answer = { error: err instanceof Error ? err.message : String(err) };
3219
+ }
3220
+ finally {
3221
+ this.#purgeAlarmRunning = false;
3222
+ }
3223
+ const after = Date.now();
3224
+ const next = this.dueAtNow(after, schedules);
3225
+ if (next === null) {
3226
+ await settle();
3227
+ return;
3228
+ }
3229
+ const minutes = [...this.purgeSchedules.values(), ...(schedules ? this.dueSchedules.values() : [])].map((p) => p.everyMinutes);
3230
+ const cadence = after + Math.min(...minutes) * 60_000;
3231
+ if ('held' in answer) {
3232
+ // Not re-armed, and no commit re-arms it within the cadence: a held scope does not ask on
3233
+ // every write. The pass arms it again once the scope's schedules run.
3234
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep(cadence));
3235
+ return;
3236
+ }
3237
+ let floor;
3238
+ if ('error' in answer) {
3239
+ console.error('substrat: the due alarm could not ask its sweeper; asking again after the cadence', answer.error);
3240
+ floor = cadence;
3241
+ }
3242
+ else {
3243
+ const sql = doSpineSql(this.sql);
3244
+ const open = [...this.purgeSchedules.keys()].some((op) => readPurgeLap(sql, op).after !== null);
3245
+ floor = open ? after : after + PURGE_ALARM_MIN_GAP_MS;
3246
+ }
3247
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep(floor));
3248
+ await this.armAlarmBy(Math.max(next, floor));
3249
+ }
3250
+ catch (err) {
3251
+ console.error('substrat: due alarm failed; the sweeper pass re-arms it', err);
3252
+ }
3004
3253
  }
3005
3254
  /** K-69: a scope with the control plane's origin and secret asks for its own drains. */
3006
3255
  wakeTransport() {
@@ -3126,7 +3375,7 @@ options = {}) {
3126
3375
  // A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
3127
3376
  for (let round = 0; round < HANDOFF_ROUNDS; round++) {
3128
3377
  inFlight = null;
3129
- const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, this.sql.exec(q.sql, ...q.params).toArray(), ids, commit));
3378
+ const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, this.sql.exec(q.sql, ...q.params).toArray(), ids, commit, senders));
3130
3379
  if (sent.length === 0) {
3131
3380
  // A5: a window's start the broker has not acknowledged goes on its own.
3132
3381
  if (options.start) {
@@ -3401,6 +3650,8 @@ options = {}) {
3401
3650
  await this.dispatch(tenantId, scopeId, invocationId);
3402
3651
  // K-69: after the consumers, whose own emits and intents count too.
3403
3652
  await this.noteScopeWake(tenantId, scopeId);
3653
+ // #3540: a row this commit binned may now be the earliest due.
3654
+ await this.notePurgeDue(tenantId, scopeId);
3404
3655
  // K-74: the same, for the delivery broker. #3474: the rows this call wrote carry its trace.
3405
3656
  await this.handOffCommitted(tenantId, scopeId, { invocationId, traceId: traceIdOf(currentTraceparent()) });
3406
3657
  if (liveSince === null)
@@ -3858,6 +4109,17 @@ options = {}) {
3858
4109
  return await this.queue.enqueue(() => resolveDownloadLink({ sql: doSpineSql(this.sql), now: instant.parse(new Date().toISOString()) }, secret, attachmentId));
3859
4110
  });
3860
4111
  }
4112
+ /**
4113
+ * #2996 (K-64): spend a store proof on one call, on this scope's queue. The host's store stub
4114
+ * asks this before it sends the call, on every transport; see `redeemStoreProof`.
4115
+ */
4116
+ storeProofRedeemReply(secret, binding, operation, principal) {
4117
+ return replyOf(async () => {
4118
+ await this.ensureMigrations();
4119
+ await this.queue.enqueue(() => redeemStoreProof({ sql: doSpineSql(this.sql), now: instant.parse(new Date().toISOString()) }, secret, { binding, operation, principal }));
4120
+ return null;
4121
+ });
4122
+ }
3861
4123
  attachmentListReply(...args) {
3862
4124
  return replyOf(() => this.listAttachments(...args));
3863
4125
  }
@@ -4565,6 +4827,10 @@ options = {}) {
4565
4827
  * doors are a person acting, not a hot path, so one read is not threaded through both.
4566
4828
  */
4567
4829
  async reservedRoleRefusalFor(tenantId, roleKey, door) {
4830
+ // #2993 part 3: a role the vertical declares on other scope types only does not exist here.
4831
+ const typed = scopeTypeRoleRefusal(scopeTypePlan, this.scopeType(), roleKey);
4832
+ if (typed)
4833
+ return typed;
4568
4834
  if (door === 'platform' && this.reservedKeys.size === 0)
4569
4835
  return null;
4570
4836
  const role = await this.controlPlaneReader().getRole(tenantId, roleKey);
@@ -4584,6 +4850,10 @@ options = {}) {
4584
4850
  * door cannot know, so it refuses.
4585
4851
  */
4586
4852
  async reservedRoleRefusalHere(roleKey, door) {
4853
+ // #2993 part 3: as `reservedRoleRefusalFor`, which the early return below would skip.
4854
+ const typed = scopeTypeRoleRefusal(scopeTypePlan, this.scopeType(), roleKey);
4855
+ if (typed)
4856
+ return typed;
4587
4857
  if (door === 'platform' && this.reservedKeys.size === 0)
4588
4858
  return null;
4589
4859
  const tenantId = this.provisionedFor();
@@ -5112,7 +5382,12 @@ options = {}) {
5112
5382
  * #2517: platform requests the purge runs earlier in the same tick enqueued. LAST and optional
5113
5383
  * for the same reason; absent means none, so a refused head is a failure as before.
5114
5384
  */
5115
- earlierPurgeRequests) {
5385
+ earlierPurgeRequests,
5386
+ /**
5387
+ * #3540: who asks (`PurgeSweepMode`). LAST and optional for the same reason; absent is a pass
5388
+ * whose sweeper cannot take a scope alarm's call, which is always run, as before.
5389
+ */
5390
+ mode) {
5116
5391
  await this.ensureMigrations();
5117
5392
  const schedule = this.purgeSchedules.get(operation);
5118
5393
  if (!schedule)
@@ -5131,6 +5406,13 @@ options = {}) {
5131
5406
  const held = purgeHeldBy(this.purgeGateFacts(schedule.moduleId, tenantId));
5132
5407
  if (held !== null)
5133
5408
  return heldPurgePass(held);
5409
+ // #3540: due by event, and the pass's sweeper can take the alarm's call: the pass runs nothing
5410
+ // here, so a purge is never run by both. It arms the alarm instead, which is also how a bin
5411
+ // filled before the switch was turned on, or an alarm that was lost, comes to be armed.
5412
+ if (mode === 'deferrable' && this.purgeDueByEvent()) {
5413
+ await this.armPurgeAlarm(tenantId, scopeId);
5414
+ return { purged: 0, skipped: 0, errors: [], more: false, lapFailed: 0, byAlarm: true };
5415
+ }
5134
5416
  const due = purgeDueOf(doSpineSql(this.sql), this.statePlans, this.operationTarget, operation, schedule.entityType, new Date().toISOString(), PURGE_BATCH);
5135
5417
  // #2440: what each committed purge enqueued, from the same envelope an ordinary invoke's
5136
5418
  // caller reads. A purge that threw rolled back, and its intents with it.
@@ -5167,6 +5449,27 @@ options = {}) {
5167
5449
  * the EVALUATOR's last recorded time for that event type — a cadence gate
5168
5450
  * driven by a verdict nothing ran.
5169
5451
  */
5452
+ /**
5453
+ * #3540: one `due: 'event'` schedule's state, for the host deciding who runs it (`DueScheduleGate`).
5454
+ * `mode` is who asks: `deferrable`, a pass whose sweeper takes `runScopeDue` — then, with the switch
5455
+ * on, the scope remembers that, and a schedule that has run under the form is left to its alarm
5456
+ * (`byAlarm`), which is armed for it; or `alarm`, the scope's own alarm through that call, which
5457
+ * only reads. Absent is a pass that cannot, answered with the state alone, as a cadence read.
5458
+ */
5459
+ async dueScheduleGate(operation, tenantId, scopeId, mode) {
5460
+ await this.ensureMigrations();
5461
+ const due = this.dueSchedules.get(operation);
5462
+ if (!due)
5463
+ return { lastRunAt: await this.scheduleLastRun(operation), established: false, dueAt: null };
5464
+ const row = readScheduleDue(doSpineSql(this.sql), due);
5465
+ if (mode === 'deferrable' && this.dueByEventSwitched() && !this.isCopyRead()) {
5466
+ // The pair is the host's, which has already held it to this scope's record.
5467
+ await this.armPurgeAlarm(tenantId, scopeId, true);
5468
+ if (row.established)
5469
+ return { ...row, byAlarm: true };
5470
+ }
5471
+ return row;
5472
+ }
5170
5473
  async scheduleLastRun(operation) {
5171
5474
  const row = this.sql
5172
5475
  .exec(`SELECT last_run_at FROM _substrat_schedule_state WHERE kind = 'schedule' AND schedule_op = ?`, operation)
@@ -5575,9 +5878,68 @@ options = {}) {
5575
5878
  this.reconcileAskUnsignalled = false;
5576
5879
  return 1;
5577
5880
  }
5578
- /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
5881
+ /**
5882
+ * The derivation plans of the modules this scope runs — what `repairDerivedObjects` and its
5883
+ * checks read. #2993 part 3: a typed scope carries only its type's tables, so only what its type
5884
+ * runs was derived onto them.
5885
+ */
5579
5886
  derivedPlans() {
5580
- return { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
5887
+ const all = { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
5888
+ if (!scopeTypePlan.declared)
5889
+ return all;
5890
+ const own = (plans) => new Map([...plans].filter(([, plan]) => this.runs(plan.moduleId)));
5891
+ return { state: own(all.state), lists: own(all.lists), search: own(all.search) };
5892
+ }
5893
+ /**
5894
+ * #2993 part 3: this scope's type. `home` on a class with no declared types (read from nothing),
5895
+ * for a scope from before types, and for a store not provisioned yet, whose provision fixes it.
5896
+ */
5897
+ scopeType() {
5898
+ if (!scopeTypePlan.declared)
5899
+ return HOME_SCOPE_TYPE;
5900
+ return (this.scopeTypeHeld ??= this.metaValue(SCOPE_TYPE_META_KEY) ?? HOME_SCOPE_TYPE);
5901
+ }
5902
+ /** #2993 part 3: whether this scope's type runs the module. Every module runs on an untyped class. */
5903
+ runs(moduleId) {
5904
+ return !scopeTypePlan.declared || scopeTypeRuns(scopeTypePlan, this.scopeType(), moduleId);
5905
+ }
5906
+ /** #2993 part 3: the erasure plans of the modules this scope's type runs, whose tables it holds. */
5907
+ erasurePlansRun() {
5908
+ return scopeTypePlan.declared ? this.erasurePlans.filter((p) => this.runs(p.moduleId)) : this.erasurePlans;
5909
+ }
5910
+ /** #2993 part 3: the registered modules this scope's type runs, in registration order. */
5911
+ modulesRun() {
5912
+ const all = [...this.modules.values()];
5913
+ return scopeTypePlan.declared ? all.filter((m) => this.runs(m.id)) : all;
5914
+ }
5915
+ /**
5916
+ * #2993 part 3: fix this scope's type, at its provision — the hosted half of the pure host's
5917
+ * `scopes.scope_type`, kept in the scope's own `_substrat_meta` as its tenant is, because this
5918
+ * object decides which modules it runs. Judged by the kernel's rule against this class's
5919
+ * declared types: an undeclared type is `validation_failed`, and a type other than the one held
5920
+ * is `conflict`, both before anything is written. A store that holds no type but was provisioned,
5921
+ * or holds data, is a `home` scope (it ran every module); only an empty one takes a new type.
5922
+ *
5923
+ * Migrates nothing, so the host calls it before anything else touches a new scope: a pass run
5924
+ * first would lay down `home`'s tables. Answers the type held, written only when not `home`.
5925
+ */
5926
+ async fixScopeTypeReply(requested, scopeId) {
5927
+ return replyOf(() => this.queue.enqueue(() => {
5928
+ const held = this.metaValue(SCOPE_TYPE_META_KEY);
5929
+ const recorded = held !== null ? held : this.provisionedFor() !== null || this.holdsData() ? null : undefined;
5930
+ const type = provisionedScopeType(scopeTypePlan, requested, recorded, scopeId);
5931
+ if (held === null && type !== HOME_SCOPE_TYPE) {
5932
+ this.revision.transactionSync(() => {
5933
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, SCOPE_TYPE_META_KEY, type);
5934
+ });
5935
+ }
5936
+ this.scopeTypeHeld = type;
5937
+ return type;
5938
+ }));
5939
+ }
5940
+ /** #2993 part 3: this scope's type, for a host that seats or probes by it. Reads; writes nothing. */
5941
+ async scopeTypeHere() {
5942
+ return this.scopeType();
5581
5943
  }
5582
5944
  /** A multi-statement script on this DO's own handle, one statement per exec. */
5583
5945
  runScript(ddl) {
@@ -5611,7 +5973,8 @@ options = {}) {
5611
5973
  }
5612
5974
  /** Resolves true if this call applied at least one migration. */
5613
5975
  async applyPendingMigrations() {
5614
- const { pending, diverged } = await planMigrations(this.modules.values(), this.applied);
5976
+ // #2993 part 3: a scope applies only its type's migrations, so it carries no other type's tables.
5977
+ const { pending, diverged } = await planMigrations(this.modulesRun(), this.applied);
5615
5978
  if (diverged) {
5616
5979
  // Recorded as a failed migration is, so the coordinator projects it the same way.
5617
5980
  this.lastFailure = diverged;
@@ -5773,6 +6136,10 @@ options = {}) {
5773
6136
  isCopy() {
5774
6137
  return this.sql.exec(IS_COPY_SQL).toArray().length > 0;
5775
6138
  }
6139
+ /** #3540: `isCopy`, read on a scope that may not hold the classification's table yet. */
6140
+ isCopyRead() {
6141
+ return this.hasTable('_substrat_copy_origin') && this.isCopy();
6142
+ }
5776
6143
  /** Whether this scope is a clean-room copy (#3108, `CLEAN_ROOM_COPY_SQL`): what a seeded preview's persona link is behind. */
5777
6144
  isCleanRoomCopy() {
5778
6145
  return this.hasTable('_substrat_copy_origin') && this.sql.exec(CLEAN_ROOM_COPY_SQL).toArray().length > 0;
@@ -5972,10 +6339,17 @@ options = {}) {
5972
6339
  * row that is correctly over.
5973
6340
  */
5974
6341
  settlePlatformRequest(id, status, result, lastError, lastFailure = null) {
5975
- this.sql.exec(`UPDATE _substrat_platform_requests
5976
- SET status = ?, result = COALESCE(?, result), last_error = ?, last_failure = ?,
5977
- attempts = attempts + 1, settled_at = ?
5978
- WHERE id = ? AND status = 'pending'`, status, result, lastError, lastFailure, status === 'pending' ? null : new Date().toISOString(), id);
6342
+ const now = new Date().toISOString();
6343
+ this.revision.transactionSync(() => {
6344
+ this.sql.exec(`UPDATE _substrat_platform_requests
6345
+ SET status = ?, result = COALESCE(?, result), last_error = ?, last_failure = ?,
6346
+ attempts = attempts + 1, settled_at = ?
6347
+ WHERE id = ? AND status = 'pending'`, status, result, lastError, lastFailure, status === 'pending' ? null : now, id);
6348
+ // #3568: a settled row's message is cleared when its sender asked, in this transaction, as
6349
+ // the kernel's settle does on the other verb. Idempotent, and never a pending row.
6350
+ if (status !== 'pending')
6351
+ clearSettledEmailIn(this.switchSql(), id, now);
6352
+ });
5979
6353
  }
5980
6354
  /**
5981
6355
  * A settle that writes an outcome event (#2102): the kernel's one settle — the same
@@ -6850,6 +7224,9 @@ options = {}) {
6850
7224
  // #2096: a purge horizon's lap in progress, on a scope DO built before the column. NULL is
6851
7225
  // the start of a lap — the honest reading of every row already there.
6852
7226
  'ALTER TABLE _substrat_schedule_state ADD COLUMN purge_cursor TEXT',
7227
+ // #3540: a due-by-event schedule's next date, on a scope DO built before the column. NULL is
7228
+ // "not yet run under the form", so its cadence decides: the honest reading of every row there.
7229
+ 'ALTER TABLE _substrat_schedule_state ADD COLUMN due_at TEXT',
6853
7230
  // #2009: the copy classification on a scope DO built before it (NULL reads as a copy;
6854
7231
  // see `COPY_ORIGIN_DDL`).
6855
7232
  'ALTER TABLE _substrat_copy_origin ADD COLUMN is_copy INTEGER',
@@ -7010,6 +7387,8 @@ options = {}) {
7010
7387
  return { name: t.name, columns: ['id'], rows: at < 0 ? [] : Array.from(t.rows(), (row) => [row[at]]) };
7011
7388
  }));
7012
7389
  const receiptBefore = this.provisionedFor();
7390
+ // #2993 part 3: the type this store's own provision fixed, which a load never changes.
7391
+ const typeBefore = this.metaValue(SCOPE_TYPE_META_KEY);
7013
7392
  // #2555: this store's own permission flags, read before the drops take them.
7014
7393
  const flagsBefore = keepPermissionFlags ? PERMISSION_FLAG_KEYS.map((key) => [key, this.metaValue(key)]) : [];
7015
7394
  if (provisionedFor !== undefined && receiptBefore !== null && receiptBefore !== provisionedFor) {
@@ -7117,6 +7496,14 @@ options = {}) {
7117
7496
  if (value !== null)
7118
7497
  this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, key, value);
7119
7498
  }
7499
+ // #2993 part 3: the scope's type is this store's, as its receipt is. No dump carries it
7500
+ // (`STORE_LOCAL_META_KEYS`); one from elsewhere that did is overruled here all the same.
7501
+ this.sql.exec(`DELETE FROM _substrat_meta WHERE key = ?`, SCOPE_TYPE_META_KEY);
7502
+ if (typeBefore !== null) {
7503
+ this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, SCOPE_TYPE_META_KEY, typeBefore);
7504
+ }
7505
+ // Read again from what the load left, as a wake would: the store is the type's only record.
7506
+ this.scopeTypeHeld = undefined;
7120
7507
  // #1722: whatever stamp an export read here no longer describes this store, so every load
7121
7508
  // replaces it: with the carry's own, or with none. And the write revision moves on from
7122
7509
  // where it stood before the drops, so it never goes back.
@@ -7857,7 +8244,7 @@ options = {}) {
7857
8244
  try {
7858
8245
  // Inside the envelope: a migration refusal is an answer too, and keeps its code across the RPC.
7859
8246
  await this.ensureMigrations();
7860
- return readSubjectPage({ sql: doSpineSql(this.sql), plans: this.erasurePlans, subjectId, ...(page ? { page } : {}) });
8247
+ return readSubjectPage({ sql: doSpineSql(this.sql), plans: this.erasurePlansRun(), subjectId, ...(page ? { page } : {}) });
7861
8248
  }
7862
8249
  catch (err) {
7863
8250
  return { failure: toWireFailure(err) };
@@ -7867,11 +8254,13 @@ options = {}) {
7867
8254
  redactSubjectInTransaction(subjectId, at) {
7868
8255
  // The module half first (#2068): the declared entities, then each hook, with the search
7869
8256
  // indexes over them under FTS5 secure-delete. The spine half follows in the same transaction.
8257
+ // #2993 part 3: the modules this scope's type runs — another type's tables are not here.
8258
+ const derived = this.derivedPlans();
7870
8259
  const vertical = eraseSubjectFromModules({
7871
8260
  sql: doSpineSql(this.sql),
7872
- plans: this.erasurePlans,
7873
- searchPlans: this.searchPlans.values(),
7874
- statefulTables: statefulTablesOf(this.statePlans),
8261
+ plans: this.erasurePlansRun(),
8262
+ searchPlans: derived.search.values(),
8263
+ statefulTables: statefulTablesOf(derived.state),
7875
8264
  subjectId,
7876
8265
  at,
7877
8266
  migrationSqlOf: (moduleId, version) => this.modules.get(moduleId)?.migrations.find((m) => m.version === version)?.sql,
@@ -7959,7 +8348,8 @@ options = {}) {
7959
8348
  async dispatchRounds(tenantId, scopeId, invocationId, lines) {
7960
8349
  for (let round = 0; round < 50; round++) {
7961
8350
  let deliveredAny = false;
7962
- for (const mod of this.modules.values()) {
8351
+ // #2993 part 3: a module this scope's type does not run consumes nothing here.
8352
+ for (const mod of this.modulesRun()) {
7963
8353
  for (const consumer of mod.consumers) {
7964
8354
  const rows = this.sql
7965
8355
  .exec(`SELECT * FROM _substrat_outbox o
@@ -8482,6 +8872,21 @@ options = {}) {
8482
8872
  },
8483
8873
  atomic: createAtomic(runSub, { passed, signals }),
8484
8874
  noteTransition: noteTransitionInto(signals),
8875
+ // #3540: the schedule named is due no later than `due`, written in this operation's transaction.
8876
+ scheduleDue: (operation, due) => noteScheduleDue(doSpineSql(sql), this.dueSchedules, operation, due),
8877
+ // #2996 (K-64): the proof a store call needs, written once in the kernel. The declared key is
8878
+ // checked as the caller (a consumer's system actor is refused: its checks allow everything).
8879
+ storeProof: (binding, operation) => mintStoreProof({
8880
+ sql: doSpineSql(sql),
8881
+ subject,
8882
+ consumer: Boolean(systemActor),
8883
+ // The mint's own instant, so the proof's minute starts when it is minted.
8884
+ now: instant.parse(new Date().toISOString()),
8885
+ check: runCheck,
8886
+ assertWrites: (verb) => assertImpersonationWrites(impersonation, verb),
8887
+ minted,
8888
+ keyOf: (b, o) => storeOperationKeyOf(options.permissions?.stores, b, o),
8889
+ }, binding, operation),
8485
8890
  // #1672: mint / revoke / list, written once in the kernel — the pure adapter hands
8486
8891
  // the same function the same four things. The raw spine seam (the kernel's own write
8487
8892
  // to `_substrat_capabilities`), the operation's OWN check, and `ctx.emit`. A