@substrat-run/adapter-cloudflare 0.220.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.
package/dist/scope-do.js CHANGED
@@ -1,15 +1,17 @@
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_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';
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';
@@ -416,6 +418,9 @@ const KERNEL_DDL = `
416
418
  -- #3139: download links, a short-lived URL that lets a caller with no session read ONE file as
417
419
  -- the principal who minted it. Shared with the pure adapter from @substrat-run/kernel.
418
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}
419
424
  -- #1686: where a copied scope's data came from, and the event id its own events start above.
420
425
  -- Shared with the other adapter from @substrat-run/kernel; the column comments are there.
421
426
  ${COPY_ORIGIN_DDL}
@@ -944,6 +949,9 @@ options = {}) {
944
949
  // What the declared surface reserves holds in every instance too, whatever registers under its ids.
945
950
  const declaredReserved = new Set();
946
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);
947
955
  for (const m of options.permissions?.modules ?? []) {
948
956
  noteReservedKeys(declaredReserved, m.manifest);
949
957
  noteDeclaredKeys(declaredListed, m.manifest);
@@ -1007,6 +1015,11 @@ options = {}) {
1007
1015
  purgeOnlyKeys = new Map();
1008
1016
  /** #119: a purge schedule's operation → the module that declared it and the entity it purges. */
1009
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();
1010
1023
  /**
1011
1024
  * #3540: true while this scope's alarm is waiting on its sweeper's purge run. The purges that
1012
1025
  * run meanwhile commit through `settleCommitted`, and must not arm the alarm the handler is about
@@ -1020,6 +1033,13 @@ options = {}) {
1020
1033
  /** #2387: the operations held to a `ctx.check` — the pure adapter's set, from the same kernel read. */
1021
1034
  operationCheckHeld = new Set();
1022
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;
1023
1043
  /**
1024
1044
  * #2430: what a registered module, or a module the class's declared `permissions` lists, declares
1025
1045
  * `holder: 'system'` — the role and grant doors' refusals read it.
@@ -1213,6 +1233,8 @@ options = {}) {
1213
1233
  // #119: refused before anything is recorded, as in the pure adapter.
1214
1234
  const trashTargets = registerTrashTargets(manifest.id, new Set(Object.keys(registration.operations?.handlers ?? {})), registration.operations?.inputs, manifest.entityStates, manifest.schedules);
1215
1235
  this.purgeOnlyKeys.set(manifest.id, purgeOnlyKeysOf(manifest.schedules ?? []));
1236
+ for (const [operation, due] of dueByEventSchedulesOf(manifest.schedules))
1237
+ this.dueSchedules.set(operation, due);
1216
1238
  for (const schedule of manifest.schedules ?? []) {
1217
1239
  if (schedule.purge) {
1218
1240
  this.purgeSchedules.set(schedule.operation, {
@@ -1349,6 +1371,8 @@ options = {}) {
1349
1371
  const checkHeld = checkHeldOperationsOf(registration.operations);
1350
1372
  for (const [name, handler] of Object.entries(registration.operations?.handlers ?? {})) {
1351
1373
  this.defineOperation(name, handler);
1374
+ if (this.operations.has(name))
1375
+ this.operationModule.set(name, manifest.id);
1352
1376
  if (checkHeld.has(name) && this.operations.has(name))
1353
1377
  this.operationCheckHeld.add(name);
1354
1378
  // The schema follows the HANDLER, not the name: a withdrawn operation
@@ -1983,7 +2007,7 @@ options = {}) {
1983
2007
  due,
1984
2008
  ...(handedOffThrough === undefined ? {} : { handedOffThrough }),
1985
2009
  // Executors run on the coordinator, which names them; the consumers are this DO's own.
1986
- subscribers: [...outboxSubscribersOf(this.modules.values(), []), ...executors],
2010
+ subscribers: [...outboxSubscribersOf(this.modulesRun(), []), ...executors],
1987
2011
  exportTypes: this.crossVertical.exportTypes(),
1988
2012
  })));
1989
2013
  }
@@ -2488,6 +2512,10 @@ options = {}) {
2488
2512
  // else. Naming the code once here is what lets those patterns go.
2489
2513
  if (!handler)
2490
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());
2491
2519
  // #2821: before the parse, the guards and the handler — and under read-only too.
2492
2520
  assertImpersonationAdmitted(impersonation, operation, this.operationImpersonationRefused);
2493
2521
  // #304 entitlement gate, scope-local path: fail closed on the projected view exactly as
@@ -2710,6 +2738,10 @@ options = {}) {
2710
2738
  // #2166: what the guards and the handler emit about a stamped entity, held below.
2711
2739
  const stamps = watchUpdatedStamps(doSpineSql(this.sql), this.updatedStampPlans);
2712
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);
2713
2745
  await this.runGuards(operation, ctx, parsed);
2714
2746
  // #2387: the handler's own checks only — the pure adapter's reset, for its reason.
2715
2747
  checks.calls = 0;
@@ -3048,7 +3080,18 @@ options = {}) {
3048
3080
  * for the alarm to ask, and a registered module declares a purge horizon.
3049
3081
  */
3050
3082
  purgeDueByEvent() {
3051
- return this.env.SUBSTRAT_PURGE_DUE === PURGE_DUE_BY_EVENT && this.env.SWEEPER !== undefined && this.purgeSchedules.size > 0;
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);
3052
3095
  }
3053
3096
  /** #3540: when this scope's purges are next due, read from its own rows (`purgeDueAt`). */
3054
3097
  purgeDueAtNow(now) {
@@ -3056,45 +3099,70 @@ options = {}) {
3056
3099
  return purgeDueAt(doSpineSql(this.sql), this.statePlans, schedules, now);
3057
3100
  }
3058
3101
  /**
3059
- * #3540: arm the scope's alarm for its earliest due row, and record the pair the alarm will ask
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
3060
3113
  * for. Never before the `notBefore` a run with no progress left. A copy arms nothing: a fork, a
3061
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.
3062
3119
  */
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)
3120
+ async armPurgeAlarm(tenantId, scopeId, takesSchedules = false) {
3121
+ if (!this.dueAlarmApplies() || this.isCopyRead())
3068
3122
  return false;
3069
3123
  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 });
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
+ });
3072
3135
  }
3136
+ if (at === null)
3137
+ return false;
3073
3138
  await this.armAlarmBy(Math.max(at, held?.notBefore ?? 0));
3074
3139
  return true;
3075
3140
  }
3076
3141
  /**
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).
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).
3079
3145
  */
3080
3146
  async notePurgeDue(tenantId, scopeId) {
3081
- if (this.#purgeAlarmRunning || !this.purgeDueByEvent())
3147
+ if (this.#purgeAlarmRunning || !this.dueAlarmApplies())
3082
3148
  return;
3083
3149
  try {
3084
3150
  await this.armPurgeAlarm(tenantId, scopeId);
3085
3151
  }
3086
3152
  catch (err) {
3087
- console.error('substrat: purge alarm not armed after commit; the sweeper pass re-arms it', err);
3153
+ console.error('substrat: due alarm not armed after commit; the sweeper pass re-arms it', err);
3088
3154
  }
3089
3155
  }
3090
3156
  /**
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:
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:
3094
3162
  *
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
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
3098
3166
  * sweeper could not be asked, so a run that cannot progress cannot spin the alarm;
3099
3167
  * - a run the sweeper held (a lifecycle, a switch, a scope off its roster): not re-armed, and no
3100
3168
  * commit re-arms it within the cadence. The pass re-arms it when the scope's schedules run.
@@ -3107,15 +3175,29 @@ options = {}) {
3107
3175
  if (!state)
3108
3176
  return;
3109
3177
  // The switch turned off, or the scope became a copy: the pass has it again, or nothing does.
3110
- if (!this.purgeDueByEvent() || this.isCopyRead()) {
3178
+ if (!this.dueAlarmApplies() || this.isCopyRead()) {
3111
3179
  await this.ctx.storage.delete(PURGE_ALARM_KEY);
3112
3180
  return;
3113
3181
  }
3114
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
+ };
3115
3197
  const now = Date.now();
3116
- const at = this.purgeDueAtNow(now);
3198
+ const at = this.dueAtNow(now, schedules);
3117
3199
  if (at === null) {
3118
- await this.ctx.storage.delete(PURGE_ALARM_KEY);
3200
+ await settle();
3119
3201
  return;
3120
3202
  }
3121
3203
  const notBefore = state.notBefore ?? 0;
@@ -3128,7 +3210,9 @@ options = {}) {
3128
3210
  this.#purgeAlarmRunning = true;
3129
3211
  try {
3130
3212
  const stub = sweeper.get(sweeper.idFromName(SCOPE_SWEEPER_NAME));
3131
- answer = await stub.runScopePurges(state.tenantId, state.scopeId);
3213
+ answer = schedules
3214
+ ? await stub.runScopeDue(state.tenantId, state.scopeId)
3215
+ : await stub.runScopePurges(state.tenantId, state.scopeId);
3132
3216
  }
3133
3217
  catch (err) {
3134
3218
  answer = { error: err instanceof Error ? err.message : String(err) };
@@ -3137,21 +3221,22 @@ options = {}) {
3137
3221
  this.#purgeAlarmRunning = false;
3138
3222
  }
3139
3223
  const after = Date.now();
3140
- const next = this.purgeDueAtNow(after);
3224
+ const next = this.dueAtNow(after, schedules);
3141
3225
  if (next === null) {
3142
- await this.ctx.storage.delete(PURGE_ALARM_KEY);
3226
+ await settle();
3143
3227
  return;
3144
3228
  }
3145
- const cadence = after + Math.min(...[...this.purgeSchedules.values()].map((p) => p.everyMinutes)) * 60_000;
3229
+ const minutes = [...this.purgeSchedules.values(), ...(schedules ? this.dueSchedules.values() : [])].map((p) => p.everyMinutes);
3230
+ const cadence = after + Math.min(...minutes) * 60_000;
3146
3231
  if ('held' in answer) {
3147
3232
  // Not re-armed, and no commit re-arms it within the cadence: a held scope does not ask on
3148
3233
  // 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 });
3234
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep(cadence));
3150
3235
  return;
3151
3236
  }
3152
3237
  let floor;
3153
3238
  if ('error' in answer) {
3154
- console.error('substrat: the purge alarm could not ask its sweeper; asking again after the cadence', answer.error);
3239
+ console.error('substrat: the due alarm could not ask its sweeper; asking again after the cadence', answer.error);
3155
3240
  floor = cadence;
3156
3241
  }
3157
3242
  else {
@@ -3159,11 +3244,11 @@ options = {}) {
3159
3244
  const open = [...this.purgeSchedules.keys()].some((op) => readPurgeLap(sql, op).after !== null);
3160
3245
  floor = open ? after : after + PURGE_ALARM_MIN_GAP_MS;
3161
3246
  }
3162
- await this.ctx.storage.put(PURGE_ALARM_KEY, { tenantId: state.tenantId, scopeId: state.scopeId, notBefore: floor });
3247
+ await this.ctx.storage.put(PURGE_ALARM_KEY, keep(floor));
3163
3248
  await this.armAlarmBy(Math.max(next, floor));
3164
3249
  }
3165
3250
  catch (err) {
3166
- console.error('substrat: purge alarm failed; the sweeper pass re-arms it', err);
3251
+ console.error('substrat: due alarm failed; the sweeper pass re-arms it', err);
3167
3252
  }
3168
3253
  }
3169
3254
  /** K-69: a scope with the control plane's origin and secret asks for its own drains. */
@@ -4024,6 +4109,17 @@ options = {}) {
4024
4109
  return await this.queue.enqueue(() => resolveDownloadLink({ sql: doSpineSql(this.sql), now: instant.parse(new Date().toISOString()) }, secret, attachmentId));
4025
4110
  });
4026
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
+ }
4027
4123
  attachmentListReply(...args) {
4028
4124
  return replyOf(() => this.listAttachments(...args));
4029
4125
  }
@@ -4731,6 +4827,10 @@ options = {}) {
4731
4827
  * doors are a person acting, not a hot path, so one read is not threaded through both.
4732
4828
  */
4733
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;
4734
4834
  if (door === 'platform' && this.reservedKeys.size === 0)
4735
4835
  return null;
4736
4836
  const role = await this.controlPlaneReader().getRole(tenantId, roleKey);
@@ -4750,6 +4850,10 @@ options = {}) {
4750
4850
  * door cannot know, so it refuses.
4751
4851
  */
4752
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;
4753
4857
  if (door === 'platform' && this.reservedKeys.size === 0)
4754
4858
  return null;
4755
4859
  const tenantId = this.provisionedFor();
@@ -5345,6 +5449,27 @@ options = {}) {
5345
5449
  * the EVALUATOR's last recorded time for that event type — a cadence gate
5346
5450
  * driven by a verdict nothing ran.
5347
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
+ }
5348
5473
  async scheduleLastRun(operation) {
5349
5474
  const row = this.sql
5350
5475
  .exec(`SELECT last_run_at FROM _substrat_schedule_state WHERE kind = 'schedule' AND schedule_op = ?`, operation)
@@ -5753,9 +5878,68 @@ options = {}) {
5753
5878
  this.reconcileAskUnsignalled = false;
5754
5879
  return 1;
5755
5880
  }
5756
- /** 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
+ */
5757
5886
  derivedPlans() {
5758
- 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();
5759
5943
  }
5760
5944
  /** A multi-statement script on this DO's own handle, one statement per exec. */
5761
5945
  runScript(ddl) {
@@ -5789,7 +5973,8 @@ options = {}) {
5789
5973
  }
5790
5974
  /** Resolves true if this call applied at least one migration. */
5791
5975
  async applyPendingMigrations() {
5792
- 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);
5793
5978
  if (diverged) {
5794
5979
  // Recorded as a failed migration is, so the coordinator projects it the same way.
5795
5980
  this.lastFailure = diverged;
@@ -7039,6 +7224,9 @@ options = {}) {
7039
7224
  // #2096: a purge horizon's lap in progress, on a scope DO built before the column. NULL is
7040
7225
  // the start of a lap — the honest reading of every row already there.
7041
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',
7042
7230
  // #2009: the copy classification on a scope DO built before it (NULL reads as a copy;
7043
7231
  // see `COPY_ORIGIN_DDL`).
7044
7232
  'ALTER TABLE _substrat_copy_origin ADD COLUMN is_copy INTEGER',
@@ -7199,6 +7387,8 @@ options = {}) {
7199
7387
  return { name: t.name, columns: ['id'], rows: at < 0 ? [] : Array.from(t.rows(), (row) => [row[at]]) };
7200
7388
  }));
7201
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);
7202
7392
  // #2555: this store's own permission flags, read before the drops take them.
7203
7393
  const flagsBefore = keepPermissionFlags ? PERMISSION_FLAG_KEYS.map((key) => [key, this.metaValue(key)]) : [];
7204
7394
  if (provisionedFor !== undefined && receiptBefore !== null && receiptBefore !== provisionedFor) {
@@ -7306,6 +7496,14 @@ options = {}) {
7306
7496
  if (value !== null)
7307
7497
  this.sql.exec(`INSERT INTO _substrat_meta (key, value) VALUES (?, ?)`, key, value);
7308
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;
7309
7507
  // #1722: whatever stamp an export read here no longer describes this store, so every load
7310
7508
  // replaces it: with the carry's own, or with none. And the write revision moves on from
7311
7509
  // where it stood before the drops, so it never goes back.
@@ -8046,7 +8244,7 @@ options = {}) {
8046
8244
  try {
8047
8245
  // Inside the envelope: a migration refusal is an answer too, and keeps its code across the RPC.
8048
8246
  await this.ensureMigrations();
8049
- 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 } : {}) });
8050
8248
  }
8051
8249
  catch (err) {
8052
8250
  return { failure: toWireFailure(err) };
@@ -8056,11 +8254,13 @@ options = {}) {
8056
8254
  redactSubjectInTransaction(subjectId, at) {
8057
8255
  // The module half first (#2068): the declared entities, then each hook, with the search
8058
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();
8059
8259
  const vertical = eraseSubjectFromModules({
8060
8260
  sql: doSpineSql(this.sql),
8061
- plans: this.erasurePlans,
8062
- searchPlans: this.searchPlans.values(),
8063
- statefulTables: statefulTablesOf(this.statePlans),
8261
+ plans: this.erasurePlansRun(),
8262
+ searchPlans: derived.search.values(),
8263
+ statefulTables: statefulTablesOf(derived.state),
8064
8264
  subjectId,
8065
8265
  at,
8066
8266
  migrationSqlOf: (moduleId, version) => this.modules.get(moduleId)?.migrations.find((m) => m.version === version)?.sql,
@@ -8148,7 +8348,8 @@ options = {}) {
8148
8348
  async dispatchRounds(tenantId, scopeId, invocationId, lines) {
8149
8349
  for (let round = 0; round < 50; round++) {
8150
8350
  let deliveredAny = false;
8151
- 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()) {
8152
8353
  for (const consumer of mod.consumers) {
8153
8354
  const rows = this.sql
8154
8355
  .exec(`SELECT * FROM _substrat_outbox o
@@ -8671,6 +8872,21 @@ options = {}) {
8671
8872
  },
8672
8873
  atomic: createAtomic(runSub, { passed, signals }),
8673
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),
8674
8890
  // #1672: mint / revoke / list, written once in the kernel — the pure adapter hands
8675
8891
  // the same function the same four things. The raw spine seam (the kernel's own write
8676
8892
  // to `_substrat_capabilities`), the operation's OWN check, and `ctx.emit`. A