@substrat-run/adapter-sqlite 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.
package/dist/index.js CHANGED
@@ -2,18 +2,22 @@ import { createHash } from 'node:crypto';
2
2
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, writeFileSync, writeSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import Database from 'better-sqlite3';
5
- import { accessLogEntry, adminLogEntry, delegatedReadParams, operationSeriesCount, opsFailureEntry, opsFailureFingerprint, issueEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunEntry, modelUsageEntry, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, createTenantInput, domainEvent, domainEventInput, exportReadInput, importBatch, importCursorMove, exportsOfManifestJson, assertNoBindingShapeBreak, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, entitlementGrant, entitlementGrantInput, eventId, meterReading, platformRequestInput, platformRequestId, identityLink, identityPool, instant, isSubstratError, connection, capabilityGrant, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchRecord, peerSwitch, verticalCaller, verticalSlug as verticalSlugOf, subjectRef, requestFingerprint, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, routeTarget, ROUTE_SCOPE_HOSTNAMES_MAX, registerVerticalInput, vertical as verticalSchema, verticalChannel, verticalVersion, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, grantRefFromProof, org as orgSchema, orgMembership, principalId, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, principalBecomeCapabilityInput, principalBindLinkInput, mergeDumpPages, subjectShredReceipt, subjectAccessReceipt, SCOPE_TABLE_PAGE_DEFAULT, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, verticalServingState, verticalTraceSampling, deploymentWireAuth, callsOfManifestJson, outboundOfManifestJson, listLimitOf, pageOf, countedPageOf, SCOPE_GATE_REASONS, substratError, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsAudit, dumpObjectsOf, isRuntimeTable, replayDumpObjects, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, redrainEventsInput, REDRAIN_BATCH, errorCodeOf, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
6
- import { actorOf, asPrincipal, assertAllowed, assertNoSecret, assertPermissionKey, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, redeemOrReplayUploadLink, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, becomeMintCheck, mintBecomeCapabilityAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, capabilityTokenHash, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, entityStateMigrations, assertNoCallerPurge, assertPlatformRequestRoom, isUnreachableParent, heldPurgePass, purgeDueOf, purgeHeldBy, lifecycleRefusal, scopeNotHeldRefusal, purgeOnlyKeysOf, purgeReportOf, purgeStillDue, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, runPurgePass, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, heldKeysOf, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability as exchangeCapabilitySecret, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, plausibleSessionToken, readCapabilityPage, redactSecrets, redactSecretText, moduleLog, consoleLogSink, asyncInvocationId, asyncLinePass, consoleInvocationLineSink, resolveCapabilitySession, revokeCapabilityAsPlatform, assertReadOnlyQuery, attachmentBlobKey, attachmentSha256, isSizedByteStream, knownLengthStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, guardSpine, guardSqlLimits, DO_SQL_LIMITS, tooManyResultColumns, tooManyTableColumns, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, ATTACHMENT_BYTES_SQL, SCOPE_STORAGE_DDL, forgetScopeStorage, listScopeAttachmentStorageRows, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, DIRECTORY_LAKE_DDL, ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink, listConnectLinks as listConnectLinkRows, readConnectLink, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, assertRowOffset, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, foldModelUsage, backoffAt, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleRowsErased, moduleErasurePlan, redactSubjectScopeText, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, 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_STEP_RECORD_SQL, JOB_LEASE_EXPIRED_NOTE, assertLeaseMs, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, dumpRoleRefusal, reservedGrantRefusal, reservedRoleDefinitionRefusal, reservedRoleRefusal, reservedShapeRefusal, SCOPE_SEATED_ROLES_SQL, SEAT_HOLDING_SCOPE_STATUSES, TENANT_SEATED_ROLES_SQL, admitPeer, boundToPeerDeclarations, peerCallerAt, collectPeers, peerSeats, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, peerVerticalSpellings, samePeerVertical, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, SWITCH_OWED_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, executableSqlStatements, blankSqlComments, recordWriteSuperseded, switchFencesOf, switchSupersededMessage, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, moveSwitch, reassertActionOf, reassertEntry, reassertOffRow, recordSwitchedOff, recordSwitchedOn, restoreSwitchRecord, scopesSwitchedOffFor, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, switchRecordsOf, switchedOffOf, switchesBackfillSqlOf, switchesTableExists, tenantHeldOf, tenantHoldsGrant, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, withRecorded, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, forgetVerticalScopeStores, DEPLOYMENT_WIRE_AUTH_DDL, assertWireAuthFilter, deploymentWireAuthOf, forgetVerticalWireAuth, wireAuthAccessTarget, writeDeploymentWireAuth, indexVersionScopeStores, driverDeclarationsOf, verticalScopeStoresOf, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, splitManifestMigrations, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, deriveVersionMigrationDigest, publishedMigrationDigest, migrationChangeRefusal, writeVersionMigrations, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, pruneInputOf, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, ImpersonationRefused, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, assertSessionUsable, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, impersonationStampOf, mapImpersonationRow, newImpersonationSession, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, tenantCoverage, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, noSealingKeyMessage, openSealed, sealTo, ConnectionSealingKeyUnavailableError, PermissionDenied, createAtomic, NotSearchable, NotListable, listIndexMigrations, listIndexPlans, listQuery, cursorOf, moduleMigrations, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, isSearchIndexTable, rowCountTable, searchIndexMigrations, searchIndexPlans, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, fenceAttachmentSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, sweepOrphanAttachments, missingAttachmentStore, SETTLED_COPY_STATES, unsettledCopyRefusal, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, attachmentRecordOfRow, attachmentTextJob, enqueueAttachmentText, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, queueAttachmentTextBackfill, startAttachmentTextBackfill, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, reconcileAttachmentText, recordAttachmentText, searchAttachments, 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, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, exportedSinceQuery, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, autoAdmittedProdRefusal, listedPromoteRefusal, rebindRaceRefusal, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, migratesFrom, servedFromRow, servesAsFrom, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, isPrimaryScope, PROVISIONED_VERSIONS_SQL, installsReconciledOf, strandJudgmentsOf, provisionedVersionsParams, boundShapesColumn, boundShapesOfColumn, installReconciled, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, jobRunOf, runDueJobRuns, startJobRun, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, globalFetch, fetchLikeOf, deadlineFetch, createUlid, facetEvents, readHistory, walkEventCause, walkEventEffects, assertRedrainWindow, readInvocation, readDeadLetters, readLifecycleFlow, readOperationSeries, domainEventOf, readUndrainedOutbox, undrainedEventsOf, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, unknownRoleError, callReservedStoreOperation, storesFencedRefusal, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf, } from '@substrat-run/kernel';
5
+ import { accessLogEntry, adminLogEntry, delegatedReadParams, operationSeriesCount, opsFailureEntry, opsFailureFingerprint, issueEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunEntry, modelUsageEntry, ATTACHMENT_ADDED, ATTACHMENT_REMOVED, createTenantInput, domainEvent, domainEventInput, exportReadInput, importBatch, pushedImport, moduleId, importCursorMove, exportsOfManifestJson, assertNoBindingShapeBreak, assertScopeTypesKept, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, entitlementGrant, entitlementGrantInput, eventId, meterReading, platformRequestInput, platformRequestId, identityLink, identityPool, instant, isSubstratError, connection, capabilityGrant, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchRecord, peerSwitch, verticalCaller, verticalSlug as verticalSlugOf, subjectRef, requestFingerprint, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, routeTarget, ROUTE_SCOPE_HOSTNAMES_MAX, registerVerticalInput, vertical as verticalSchema, verticalChannel, verticalVersion, objectRef, entityObjectRef, assertModuleEmittableType, assertKernelAuthoredType, grantRefFromProof, org as orgSchema, orgMembership, principalId, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, principalBecomeCapabilityInput, principalBindLinkInput, mergeDumpPages, subjectShredReceipt, subjectAccessReceipt, SCOPE_TABLE_PAGE_DEFAULT, SCOPE_TABLE_PAGE_MAX, SCOPE_QUERY_ROW_MAX, verticalServingState, verticalTraceSampling, deploymentWireAuth, callsOfManifestJson, outboundOfManifestJson, listLimitOf, pageOf, countedPageOf, SCOPE_GATE_REASONS, substratError, assertReplayableDump, DUMP_OBJECTS_QUERY, dumpObjectsAudit, dumpObjectsOf, isRuntimeTable, replayDumpObjects, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, brokerDeadLetterAudit, redrainEventsInput, REDRAIN_BATCH, errorCodeOf, storeDriverDumpPageBytes, storeOperationKeyOf, } from '@substrat-run/contracts';
6
+ import { actorOf, asPrincipal, assertAllowed, assertNoSecret, assertPermissionKey, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, STORE_PROOF_DDL, mintStoreProof, redeemStoreProof, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, redeemOrReplayUploadLink, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, becomeMintCheck, mintBecomeCapabilityAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, capabilityTokenHash, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, entityStateMigrations, assertNoCallerPurge, assertPlatformRequestRoom, isUnreachableParent, heldPurgePass, purgeDueAt, purgeDueOf, consumeScheduleDue, dueByEventSchedulesOf, noteScheduleDue, readScheduleDue, scheduleDueAt, purgeHeldBy, lifecycleRefusal, scopeNotHeldRefusal, purgeOnlyKeysOf, purgeReportOf, purgeStillDue, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, runPurgePass, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, heldKeysOf, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability as exchangeCapabilitySecret, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, plausibleSessionToken, readCapabilityPage, redactSecrets, redactSecretText, moduleLog, consoleLogSink, asyncInvocationId, asyncLinePass, consoleInvocationLineSink, resolveCapabilitySession, revokeCapabilityAsPlatform, assertReadOnlyQuery, attachmentBlobKey, attachmentSha256, isSizedByteStream, knownLengthStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, guardSpine, guardSqlLimits, DO_SQL_LIMITS, tooManyResultColumns, tooManyTableColumns, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, ISSUE_RETENTION_DAYS, telemetryRetentionStatements, FINDINGS_DDL, ATTACHMENT_BYTES_SQL, SCOPE_STORAGE_DDL, forgetScopeStorage, listScopeAttachmentStorageRows, retireScopeStorage, listScopeStorageAttemptRows, listScopeStorageRows, listScopeStoreStorageRows, pruneScopeStorageRows, recordScopeStorageRows, readBoundedTenantStorageGauge, REQUEST_ROLLUP_DDL, listRequestDayRows, listRequestRollupDayRows, pruneRequestDayRows, recordRequestDayRows, readTenantRequestMeterRows, readRequestMeterDayRows, COST_ROLLUP_DDL, listCostDayRows, listCostRollupDayRows, sumCostDayRows, pruneCostDayRows, recordCostDayRows, recordCostContainerRows, recordScopeObjectRow, scopeObjectsDueRows, METER_DAYS_DDL, DIRECTORY_LAKE_DDL, ACCESS_SUMMARY_METHOD, AccessSummary, openAccessSummary, ackDirectoryOutbox, ensureDirectoryLakeTriggers, advanceDirectoryLakeBackfill, pruneDirectoryLakeWindow, readDirectoryLakeBackfill, readDirectoryLakeCapture, readDirectoryOutbox, setDirectoryLakeCapture, STALE_SCOPES_DDL, listStaleScopeRows, listStaleScopeTakeRows, recordStaleScopeRows, VERTICAL_OWNERS_BACKFILL, VERTICAL_OWNERS_DDL, closeVerticalOwnerRow, listVerticalOwnerRows, openVerticalOwnerRow, verticalOwnerNow, listMeterDayRows, listMeterDayTakeRows, pruneMeterDayRows, recordMeterDayRows, CONNECT_LINKS_DDL, consumeConnectLinkRow, insertConnectLink, listConnectLinks as listConnectLinkRows, readConnectLink, restoreConnectLinkRow, revokeConnectLinkRow, createFindingRule, findingOfOpsFailure, findingOfSweepRun, pruneFindings, listFindingRules, listFindings, observeFinding, revokeFindingRule, setFindingStatus, assertRowLimit, assertRowOffset, OPS_FAILURE_RETENTION_DAYS, SWEEP_RUN_RETENTION_DAYS, SWEEP_RUNS_INTENT_INDEX, sweepRunsIntentHasKind, CONNECTIONS_LIVE_INDEX, connectionsLiveIndexHasOwner, BUILD_USAGE_RETENTION_DAYS, MODEL_USAGE_RETENTION_DAYS, foldModelUsage, backoffAt, platformRequestHistoryQuery, platformRequestOf, PLATFORM_REQUEST_COLUMNS, PLATFORM_REQUEST_REDACTION_SQL, platformRequestRedactionParams, platformRequestRedactionQuery, intentPayloadCarriesSubject, redactSubjectJobRuns, eraseSubjectFromModules, readSubjectPage, moduleRowsErased, moduleErasurePlan, redactSubjectScopeText, redactSubjectDirectoryText, ISSUE_EXEMPLAR_OWNER_BACKFILL_SQL, issueExemplarOwner, 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_STEP_RECORD_SQL, JOB_LEASE_EXPIRED_NOTE, assertLeaseMs, DELIVERY_ERROR_REDACTION_SQL, REDACTED_DELIVERY_NOTE, seatScopeTuple, applyScopeRoleChange, changeScopeRole, revokeScopeRoles, scopeRoleHolders, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, dumpRoleRefusal, reservedGrantRefusal, reservedRoleDefinitionRefusal, reservedRoleRefusal, reservedShapeRefusal, SCOPE_SEATED_ROLES_SQL, SEAT_HOLDING_SCOPE_STATUSES, TENANT_SEATED_ROLES_SQL, admitPeer, boundToPeerDeclarations, peerCallerAt, collectPeers, peerSeats, resolveVerticalInstanceFrom, resolvePeerInstanceFrom, peerVerticalSpellings, samePeerVertical, peerGrantsStatus, systemGrantsStatus, systemScheduleState, systemSwitchedOff, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, PEER_SWITCHES_DDL, PEER_BINDINGS_DDL, APP_ENVIRONMENTS_DDL, claimEnvironmentServeIn, defineEnvironmentIn, ENVIRONMENT_SCRIPT_JOIN_SQL, environmentsOf, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, SWITCH_OWED_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, executableSqlStatements, blankSqlComments, recordWriteSuperseded, switchFencesOf, switchSupersededMessage, SWITCH_KINDS, SYSTEM_SWITCHES_DDL, forgetSwitchesOf, listSystemSwitchRecords, moveSwitch, reassertActionOf, reassertEntry, reassertOffRow, recordSwitchedOff, recordSwitchedOn, restoreSwitchRecord, scopesSwitchedOffFor, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, switchRecordsOf, switchedOffOf, switchesBackfillSqlOf, switchesTableExists, tenantHeldOf, tenantHoldsGrant, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, withRecorded, VERSION_MIGRATIONS_DDL, VERTICAL_SCOPE_STORES_DDL, forgetVerticalScopeStores, DEPLOYMENT_WIRE_AUTH_DDL, assertWireAuthFilter, deploymentWireAuthOf, forgetVerticalWireAuth, wireAuthAccessTarget, writeDeploymentWireAuth, indexVersionScopeStores, driverDeclarationsOf, verticalScopeStoresOf, STORE_DRIVER_RELEASES_DDL, approveStoreDriverReleaseIn, legacyStoreDriverConflict, legacyStoreDriverRenames, beginStoreDriverRolloutIn, finishStoreDriverRolloutIn, holdStoreDriverIn, advanceStoreDriverRebuildIn, claimStoreDriverRebuildIn, storeDriverRebuildIn, recordStoreDriverReleaseIn, recordStoreDriverRevokeWalkIn, releaseStoreDriverHoldIn, revokeStoreDriverReleaseIn, liveStoreDriverApprovalIn, storeDriverApprovalsIn, storeDriverRevokeWalkIn, storeDriverReleaseIn, storeDriverStateIn, storeDriverRolloutPendingIn, storeDriverRolloutWalkedIn, splitManifestMigrations, splitVersionMigrationsBatch, versionMigrationsOf, versionMigrationsExtractedOf, recordVersionMigrationsExtracted, deriveVersionMigrationDigest, publishedMigrationDigest, migrationChangeRefusal, writeVersionMigrations, OUTBOX_PRUNED_DDL, outboxSubscribersOf, pruneDrainedOutbox, pruneInputOf, denialListQuery, refusalListQuery, mapRefusalRow, denialSummaryQuery, denialTotalsQuery, DENIAL_WINDOW_QUERY, mapDenialRow, mapDenialSummaryBuckets, IMPERSONATION_COLUMNS, IMPERSONATION_DDL, ImpersonationRefused, assertImpersonationAdmitted, assertImpersonationWrites, assertModuleEnqueueableKind, assertSessionUsable, impersonationByIdQuery, impersonationListQuery, impersonationRowValues, impersonationStampOf, mapImpersonationRow, newImpersonationSession, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, membershipFencesBackfillSql, MEMBERSHIP_FENCES_DDL, membershipFencesTableExists, MEMBERSHIP_FENCE_SINCE_SQL, RAISE_MEMBERSHIP_FENCE_SQL, memberAddedAudit, orgChangeBound, tenantCoverage, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, noSealingKeyMessage, openSealed, sealTo, ConnectionSealingKeyUnavailableError, PermissionDenied, createAtomic, NotSearchable, NotListable, listIndexMigrations, listIndexPlans, listQuery, cursorOf, moduleMigrations, MIGRATION_DIGEST_FENCE_DDL, MIGRATION_DIGEST_MARK_LEGACY, assertJournalDumpCoherent, assertMigrationSql, migrationDivergence, migrationFailedError, migrationSetDivergence, migrationSteps, planMigrations, isSearchIndexTable, rowCountTable, searchIndexMigrations, searchIndexPlans, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, fenceAttachmentSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, sweepOrphanAttachments, missingAttachmentStore, SETTLED_COPY_STATES, unsettledCopyRefusal, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, attachmentRecordOfRow, attachmentTextJob, enqueueAttachmentText, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, ATTACHMENT_TEXT_RECHECK_JOB, kernelJobFor, queueAttachmentTextBackfill, startAttachmentTextBackfill, attachmentTextBackfillJob, attachmentExtractorSetKey, attachmentTextRecheckJob, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, reconcileAttachmentText, recordAttachmentText, searchAttachments, 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, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, exportedSinceQuery, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, autoAdmittedProdRefusal, listedPromoteRefusal, rebindRaceRefusal, SERVES_NOW_CONDITION, SERVES_NOW_PREDICATE, servesNowParams, migratesFrom, servedFromRow, servesAsFrom, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, isPrimaryScope, PROVISIONED_VERSIONS_SQL, installsReconciledOf, strandJudgmentsOf, provisionedVersionsParams, boundShapesColumn, boundShapesOfColumn, installReconciled, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, jobRunOf, runDueJobRuns, startJobRun, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, globalFetch, fetchLikeOf, deadlineFetch, createUlid, facetEvents, readHistory, walkEventCause, walkEventEffects, assertRedrainWindow, readInvocation, readDeadLetters, readLifecycleFlow, readOperationSeries, domainEventOf, readUndrainedOutbox, undrainedEventsOf, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, unknownRoleError, callReservedStoreOperation, storesFencedRefusal, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, proofCheckedStoreInvoke, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf, } from '@substrat-run/kernel';
7
7
  import { handoffOutcome, reportHandoff, traceIdOf } from '@substrat-run/kernel';
8
+ // #2993: the modules a scope of each declared type runs, and the type a provision fixes.
9
+ import { childDoorRefusal, childScopeRefusal, directAccessRefusal, HOME_SCOPE_TYPE, operationNotInScopeType, provisionedParent, provisionedScopeType, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRoleRefusal, scopeTypeRuns, } from '@substrat-run/kernel';
8
10
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
9
11
  import { attributedView, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, shapeTopUpBatch, topUpEntityGrantShapes, settlePlatformRequestIn, } from '@substrat-run/kernel';
10
12
  import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove, } from '@substrat-run/kernel';
11
13
  import { DIRECTORY_CLAIMS_DDL, DIRECTORY_CROSSINGS_DDL, oneDatabaseDirectoryObjects, } from '@substrat-run/kernel';
12
14
  import { canonicalInstant } from '@substrat-run/kernel';
13
- import { advanceMarks, handoffQueries, messagesOf } from '@substrat-run/kernel';
15
+ import { advanceMarks, handoffQueries, messagesOf, senderDeliveryOf, } from '@substrat-run/kernel';
14
16
  import { intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
15
17
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
16
18
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
19
+ import { breakingWithinMajorRefusal, earlierMajorsOf, releaseWithinMajorRefusal, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
20
+ import { classify as classifyRelease } from '@substrat-run/model-view/bump';
17
21
  import { ADMIN_LOG_INDEXES_SQL, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, readAuditedOperations, unknownOutcomeOf, } from '@substrat-run/kernel';
18
22
  import { INERT_SCOPE_REASON, isPrimaryScopeRow, normalizeUploadMediaType } from '@substrat-run/kernel';
19
23
  import { opsFailureReferenceWhere } from '@substrat-run/kernel';
@@ -26,6 +30,7 @@ import { decidedByOf, entityString, forgetInvocationTrace, invocationTrace, trac
26
30
  export { scopeStoreRunnersFor } from './scope-store-runners.js';
27
31
  export { InProcessDeliveryBroker } from './delivery-broker.js';
28
32
  export { devMailOutbox, MAIL_OUTBOX_ENV } from './dev-mail-outbox.js';
33
+ export { devConnectorNetwork, DEV_RECORDING_FILE } from './dev-connector-network.js';
29
34
  /**
30
35
  * A fault in the database itself (full, corrupt, I/O), as opposed to one statement failing.
31
36
  * The #1764 backfill logs and opens past a failed batch, but never past one of these.
@@ -40,6 +45,10 @@ export function isStorageFault(err) {
40
45
  * by the context object and never exported, so module code — which can reach `ctx` but not
41
46
  * this map — cannot write one. Registered as each context is built.
42
47
  */
48
+ /** #3540: what `purgeDueAt` needs of a purge schedule. Called only on a schedule that has `purge`. */
49
+ function purgeDueScheduleOf(schedule) {
50
+ return { operation: schedule.operation, entityType: schedule.purge.entityType, everyMinutes: schedule.cadence.everyMinutes };
51
+ }
43
52
  const kernelEmitters = new WeakMap();
44
53
  /**
45
54
  * Node's running SHA-256 (#2498), for a streamed upload — the kernel's `putAttachmentBytes` takes
@@ -348,6 +357,9 @@ const KERNEL_DDL = `
348
357
  -- #3139: download links, a short-lived URL that lets a caller with no session read ONE file as
349
358
  -- the principal who minted it. Spine (kernel-written), shared with the DO adapter from the kernel.
350
359
  ${DOWNLOAD_LINK_DDL}
360
+ -- #2996 (K-64): store proofs, a short-lived, single-use proof that an operation checked the key
361
+ -- of one store operation. Spine (kernel-written), shared with the other adapter from the kernel.
362
+ ${STORE_PROOF_DDL}
351
363
  -- #1686: where a copied scope's data came from, and the event id its own events start above.
352
364
  -- Shared with the other adapter from @substrat-run/kernel; the column comments are there.
353
365
  ${COPY_ORIGIN_DDL}
@@ -889,6 +901,10 @@ export class SqliteScopeHost {
889
901
  declaredKeys = new Set();
890
902
  /** #2430: the declared permission surface `registerModule` holds each module to, when given. */
891
903
  permissions;
904
+ /** #2993: which modules a scope of each declared type runs; `declared: false` runs every module. */
905
+ scopeTypePlan;
906
+ /** #2993: a provisioned scope's type, read once from its directory row. A type never changes. */
907
+ scopeTypeCache = new Map();
892
908
  /** #1705: what this deployment exports to other verticals and imports from them. */
893
909
  crossVertical = new CrossVerticalRegistry();
894
910
  /** operation name → guards declared before it, in registration order (K-17). */
@@ -985,6 +1001,13 @@ export class SqliteScopeHost {
985
1001
  streamIdleMs;
986
1002
  connectorCalls;
987
1003
  clock;
1004
+ /** #3540: whether purge schedules are due by their rows (`SqliteScopeHostOptions.purgeDue`). */
1005
+ purgeDueByEvent;
1006
+ /**
1007
+ * #3540: every registered schedule declared `due: 'event'`, by operation — what `ctx.scheduleDue`
1008
+ * may name, and the operations whose every run clears their date in its own transaction.
1009
+ */
1010
+ dueSchedules = new Map();
988
1011
  versionId;
989
1012
  /** K-74: the broker each scope hands off to, or null (off). */
990
1013
  deliveryBroker;
@@ -1015,12 +1038,14 @@ export class SqliteScopeHost {
1015
1038
  this.streamIdleMs = options.streamIdleTimeoutMs;
1016
1039
  this.connectorCalls = options.connectorCalls ?? noopConnectorCallRecorder;
1017
1040
  this.clock = options.clock ?? (() => instant.parse(new Date().toISOString()));
1041
+ this.purgeDueByEvent = options.purgeDue === 'event';
1018
1042
  this.versionId = options.versionId ?? null;
1019
1043
  this.deliveryBroker = options.deliveryBroker ?? null;
1020
1044
  this.deliveryHandoff = options.deliveryHandoff ?? 'always';
1021
1045
  this.brokerTelemetry = options.brokerTelemetry ?? null;
1022
1046
  this.migrationsDigest = options.migrationsDigest;
1023
1047
  this.permissions = options.permissions;
1048
+ this.scopeTypePlan = scopeTypePlanOf(options.permissions);
1024
1049
  // #2430: what the declared surface reserves holds here too, whatever is registered under its ids.
1025
1050
  for (const m of options.permissions?.modules ?? []) {
1026
1051
  noteReservedKeys(this.reservedKeys, m.manifest);
@@ -1122,6 +1147,9 @@ export class SqliteScopeHost {
1122
1147
  scope_id TEXT PRIMARY KEY,
1123
1148
  tenant_id TEXT NOT NULL,
1124
1149
  parent_scope_id TEXT,
1150
+ -- #2993: the declared type this scope was provisioned as, fixed for its life. NULL is
1151
+ -- 'home', which every row from before scope types is.
1152
+ scope_type TEXT,
1125
1153
  slug TEXT,
1126
1154
  kind TEXT,
1127
1155
  name TEXT,
@@ -1198,6 +1226,8 @@ export class SqliteScopeHost {
1198
1226
  CREATE INDEX IF NOT EXISTS private_continuation_positions_expiry
1199
1227
  ON private_continuation_positions (expires_at);
1200
1228
  ${PEER_BINDINGS_DDL}
1229
+ -- D-83 (#3530 step 3): an app's named environments, each over its tagged, pinned preview.
1230
+ ${APP_ENVIRONMENTS_DDL}
1201
1231
  -- The hostname map (K-26). A single environment-wide router resolves against
1202
1232
  -- this before dispatching to the vertical's worker.
1203
1233
  --
@@ -1299,6 +1329,9 @@ export class SqliteScopeHost {
1299
1329
  serving_version_id TEXT,
1300
1330
  serving_do_classes TEXT,
1301
1331
  serving_migration_tag TEXT,
1332
+ -- K-65 (#3539 part 2): each earlier major still served beside the current one, on a
1333
+ -- script of its own (JSON, oldest first: earlierMajor). NULL: one major, one script.
1334
+ earlier_majors TEXT,
1302
1335
  created_at TEXT NOT NULL
1303
1336
  );
1304
1337
  -- admission: 'pending' until the gates pass. A push is not a deploy, and
@@ -2023,6 +2056,8 @@ export class SqliteScopeHost {
2023
2056
  throw new Error(`module already registered: ${manifest.id}`);
2024
2057
  }
2025
2058
  assertModuleDeclared(this.permissions, manifest.id); // #2430
2059
+ // #3488: the sender's delivery declarations, refused before anything is kept when two disagree.
2060
+ const senders = senderDeliveryOf([...this.senderManifests, manifest]);
2026
2061
  // #1835: the operations are the binder's own value, or the maps beside the handlers are a
2027
2062
  // copy nothing bound to them.
2028
2063
  assertBoundOperations(manifest.id, registration.operations);
@@ -2118,6 +2153,8 @@ export class SqliteScopeHost {
2118
2153
  // #1705: validated whole and kept only if it passes, so a refused module leaves nothing.
2119
2154
  this.crossVertical.register(manifest, registration.imports);
2120
2155
  this.peerUnion = undefined; // #2263: the next check reads the new module set's declarations
2156
+ this.senderManifests.push(manifest);
2157
+ this.senders = senders;
2121
2158
  this.modules.set(manifest.id, {
2122
2159
  id: manifest.id,
2123
2160
  // The order the kernel writes once (#1677): authored, then search, then list indexes.
@@ -2130,6 +2167,8 @@ export class SqliteScopeHost {
2130
2167
  peers: manifest.peers ?? [],
2131
2168
  purgeOnlyKeys: purgeOnlyKeysOf(manifest.schedules ?? []),
2132
2169
  });
2170
+ for (const [operation, schedule] of dueByEventSchedulesOf(manifest.schedules))
2171
+ this.dueSchedules.set(operation, schedule);
2133
2172
  noteReservedKeys(this.reservedKeys, manifest);
2134
2173
  noteDeclaredKeys(this.declaredKeys, manifest);
2135
2174
  if (erasure)
@@ -2256,8 +2295,35 @@ export class SqliteScopeHost {
2256
2295
  // Idempotency is on the scope_id (§3.3: provisioning is idempotent and
2257
2296
  // journaled — safe to re-run), so an existing scope short-circuits before the
2258
2297
  // slug check: re-provisioning does not collide with itself.
2259
- const existing = this.directory.prepare('SELECT 1 FROM scopes WHERE scope_id = ?').get(input.scopeId) !==
2260
- undefined;
2298
+ const existingRow = this.directory.prepare('SELECT scope_type, parent_scope_id FROM scopes WHERE scope_id = ?').get(input.scopeId);
2299
+ const existing = existingRow !== undefined;
2300
+ // #2993: a declared type, and the one recorded if the scope exists. Refused before anything is written.
2301
+ // Part 4: a module-less coordinator asked for another type of a vertical's scope judges it by
2302
+ // the types the vertical's deployed version declares; this host's own objects still run as an
2303
+ // untyped host's do (`scopeTypeOf`).
2304
+ const plan = !this.scopeTypePlan.declared && input.scopeType !== undefined && input.scopeType !== HOME_SCOPE_TYPE && record.vertical
2305
+ ? this.verticalScopeTypePlan(record.vertical)
2306
+ : this.scopeTypePlan;
2307
+ const scopeType = provisionedScopeType(plan, input.scopeType, existingRow?.scope_type, input.scopeId);
2308
+ // #2995: the parent link, fixed at the first provision. A new child is held to its parent's declared
2309
+ // children, tenant, app, state and depth before its row is written. No await separates the check from
2310
+ // the INSERT below, so no archive of the parent can land between them.
2311
+ const parentScopeId = provisionedParent(input.parentScopeId, existing ? existingRow.parent_scope_id : undefined, input.scopeId);
2312
+ if (!existing && parentScopeId !== null) {
2313
+ const parent = this.directory
2314
+ .prepare('SELECT tenant_id, status, vertical, scope_type, parent_scope_id, forked_from FROM scopes WHERE scope_id = ?')
2315
+ .get(parentScopeId);
2316
+ const refusal = childScopeRefusal(plan, parentScopeId, parent && {
2317
+ tenantId: parent.tenant_id,
2318
+ status: parent.status,
2319
+ vertical: parent.vertical,
2320
+ type: parent.scope_type ?? HOME_SCOPE_TYPE,
2321
+ parentScopeId: parent.parent_scope_id,
2322
+ forkedFrom: parent.forked_from,
2323
+ }, { tenantId: input.tenantId, vertical: record.vertical, type: scopeType });
2324
+ if (refusal)
2325
+ throw refusal;
2326
+ }
2261
2327
  if (!existing) {
2262
2328
  // The `scopes_tenant_slug` UNIQUE index makes this fail closed either way;
2263
2329
  // checking first is what turns a SQLITE_CONSTRAINT into a sentence naming
@@ -2274,7 +2340,7 @@ export class SqliteScopeHost {
2274
2340
  }
2275
2341
  this.directory
2276
2342
  .prepare(`INSERT INTO scopes
2277
- (scope_id, tenant_id, parent_scope_id, slug, kind, name, vertical,
2343
+ (scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
2278
2344
  storage_shape, jurisdiction, status, forked_from, forked_at, expires_at,
2279
2345
  serving_ref, created_at)
2280
2346
  -- 'provisioning', not 'active' (K-31): the directory row exists before the
@@ -2286,9 +2352,12 @@ export class SqliteScopeHost {
2286
2352
  -- inheriting serving_ref would route it to the prod serving script instead
2287
2353
  -- (COALESCE(s.serving_ref, vv.deployment_ref)). A null slug matches no row,
2288
2354
  -- so the sub-select is NULL and routing falls through to the bound version.
2289
- VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2355
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2290
2356
  (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`)
2291
- .run(input.scopeId, input.tenantId, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, record.kind === 'preview' ? null : record.vertical, new Date().toISOString());
2357
+ .run(input.scopeId, input.tenantId, parentScopeId,
2358
+ // NULL for 'home', the reading every row from before scope types has, so a host that
2359
+ // declares no types writes exactly the row it always did.
2360
+ scopeType === HOME_SCOPE_TYPE ? null : scopeType, record.slug, record.kind, record.name, record.vertical, record.storageShape, record.jurisdiction, record.forkedFrom, record.forkedAt, record.expiresAt, record.kind === 'preview' ? null : record.vertical, new Date().toISOString());
2292
2361
  }
2293
2362
  const rt = this.runtime(input.tenantId, input.scopeId);
2294
2363
  await this.applyPendingMigrations(rt);
@@ -2305,7 +2374,8 @@ export class SqliteScopeHost {
2305
2374
  // invoke held its transaction open joined it, and a rollback un-seated the grant
2306
2375
  // after provisioning had returned. The switch check lives inside the seat statement.
2307
2376
  await rt.actor.turn(() => {
2308
- for (const mod of this.modules.values()) {
2377
+ // #2993: only the modules this scope's type runs seat their schedules' grants here.
2378
+ for (const mod of this.modulesOf(input.scopeId)) {
2309
2379
  const perms = new Set();
2310
2380
  for (const s of mod.schedules)
2311
2381
  for (const p of s.permissions)
@@ -2320,7 +2390,7 @@ export class SqliteScopeHost {
2320
2390
  // call that makes "declared and installed" mean "live" (`peerSeats`). Same seat, same
2321
2391
  // rules: a grant a switch tombstoned stays tombstoned, and a switched-off peer gets
2322
2392
  // nothing seated.
2323
- for (const peer of peerSeats(this.peerDeclarations(), input.scopeId)) {
2393
+ for (const peer of peerSeats(this.scopeTypePlan.declared ? collectPeers(this.modulesOf(input.scopeId)) : this.peerDeclarations(), input.scopeId)) {
2324
2394
  const seat = seatScopeTuple(peer.subject, peer.relation, peer.object, null);
2325
2395
  rt.db.prepare(seat.sql).run(...seat.params);
2326
2396
  }
@@ -2330,7 +2400,14 @@ export class SqliteScopeHost {
2330
2400
  });
2331
2401
  // Audit a real provision only; an idempotent re-provision changed nothing.
2332
2402
  if (!existing) {
2333
- this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null, record);
2403
+ this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2404
+ // #2993: a typed scope's audit row names its type; a home scope's reads as it always did.
2405
+ // #2995: a child's names its parent.
2406
+ {
2407
+ ...record,
2408
+ ...(scopeType === HOME_SCOPE_TYPE ? {} : { scopeType }),
2409
+ ...(parentScopeId === null ? {} : { parentScopeId }),
2410
+ });
2334
2411
  }
2335
2412
  }
2336
2413
  /**
@@ -3003,6 +3080,11 @@ export class SqliteScopeHost {
3003
3080
  * host, made at once, so its seats are the ones that scope holds now (K-55).
3004
3081
  */
3005
3082
  async importScopeFrom(actor, input, dump, judge) {
3083
+ // #2995: a copy carries no parent link. A link is written by provision-child alone, so a copy of a
3084
+ // child is a scope of its type with no parent, and nothing reaches it through the source's parent.
3085
+ if (input.parentScopeId !== undefined) {
3086
+ throw substratError('validation_failed', 'a copy carries no parent link: a child is provisioned through provision-child only');
3087
+ }
3006
3088
  this.refuseUnusableScopeStores(dump.stores, input.vertical ?? null);
3007
3089
  if (judge)
3008
3090
  this.refuseDumpRoles(input.tenantId, dump);
@@ -3023,8 +3105,12 @@ export class SqliteScopeHost {
3023
3105
  // is the dump, not whatever the local module set would have built. Provenance is
3024
3106
  // stamped from the dump unless the caller already set it (§3: a fork always
3025
3107
  // records where it came from).
3108
+ // #2993 part 3: a copy is a scope of its source's type — the type names the tables the dump
3109
+ // carries. The caller's type when it names one, else the source's, when this directory holds it.
3110
+ const copiedType = input.scopeType ?? this.recordedScopeType(dump.scopeId);
3026
3111
  await this.provisionScope(actor, {
3027
3112
  ...input,
3113
+ ...(copiedType === undefined ? {} : { scopeType: copiedType }),
3028
3114
  forkedFrom: input.forkedFrom ?? dump.scopeId,
3029
3115
  forkedAt: input.forkedAt ?? dump.capturedAt,
3030
3116
  });
@@ -3328,11 +3414,41 @@ export class SqliteScopeHost {
3328
3414
  ? Object.freeze({ ...parsedDelegation, via: peerCallerAt(this.peerDeclarations(), parsedDelegation.via) })
3329
3415
  : parsedDelegation;
3330
3416
  const row = this.directory
3331
- .prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
3417
+ .prepare('SELECT tenant_id, status, parent_scope_id FROM scopes WHERE scope_id = ?')
3332
3418
  .get(scopeId);
3333
3419
  if (!row || row.tenant_id !== tenantId) {
3334
3420
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
3335
3421
  }
3422
+ // #2995: a child whose type accepts its parent only is not reached by a direct request.
3423
+ const direct = directAccessRefusal(this.scopeTypePlan, this.scopeTypeOf(scopeId), row.parent_scope_id, scopeId);
3424
+ if (direct)
3425
+ throw direct;
3426
+ return this.personDoor(principal, tenantId, scopeId, row.status, options, delegation);
3427
+ }
3428
+ /**
3429
+ * `ScopeHost.getChildScope` (#2995): the person's stub on a child, for host code of its parent. The
3430
+ * link, the child's type and the parent's state are checked first (`childDoorRefusal`); then the
3431
+ * person's door runs as `getScope` runs it, with every check in the child the person's own.
3432
+ */
3433
+ async getChildScope(caller, tenantId, scopeId, options) {
3434
+ if (caller?.actor?.kind !== 'person') {
3435
+ throw substratError('validation_failed', 'a call into a child acts for a person: the app acting as itself is not built (#2995)');
3436
+ }
3437
+ const parsedDelegation = parseScopeDelegation(options?.delegation);
3438
+ const delegation = parsedDelegation?.via
3439
+ ? Object.freeze({ ...parsedDelegation, via: peerCallerAt(this.peerDeclarations(), parsedDelegation.via) })
3440
+ : parsedDelegation;
3441
+ const read = this.directory.prepare('SELECT tenant_id, status, parent_scope_id FROM scopes WHERE scope_id = ?');
3442
+ const child = read.get(scopeId);
3443
+ const parent = read.get(caller.parentScopeId);
3444
+ const refusal = childDoorRefusal(this.scopeTypePlan, tenantId, caller.parentScopeId, scopeId, child && { tenantId: child.tenant_id, type: this.scopeTypeOf(scopeId), parentScopeId: child.parent_scope_id }, parent && { tenantId: parent.tenant_id, status: parent.status });
3445
+ if (refusal)
3446
+ throw refusal;
3447
+ return this.personDoor(caller.actor.principal, tenantId, scopeId, child.status, options, delegation);
3448
+ }
3449
+ /** The person's door past the directory pair and the reach check: lifecycle gates, migrations, the stub. */
3450
+ async personDoor(principal, tenantId, scopeId, status, options, delegation) {
3451
+ const row = { status };
3336
3452
  // Lifecycle gates (control-plane.md §4.1/§4.2), all the K-3 fail-closed path.
3337
3453
  // The tenant record is mandatory: every scope has a tenant with a status
3338
3454
  // (provisioning enforces it), so a missing one is corruption, not a legacy
@@ -3382,11 +3498,18 @@ export class SqliteScopeHost {
3382
3498
  throw substratError('not_found', `no scope store is bound for '${binding}'`);
3383
3499
  }
3384
3500
  await this.scopeStoreLifecycle.start();
3501
+ const rt = this.runtime(tenantId, scopeId);
3385
3502
  return {
3386
3503
  tenantId,
3387
3504
  scopeId,
3388
3505
  subjectKind: 'principal',
3389
- invoke: (operation, input, ...extra) => observeStoreCall(binding, operation, () => callScopeStore((request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request), operation, input, ...extra), options?.onStoreCall),
3506
+ // #2996 (K-64): the proof is spent on the scope's own queue, then the runner is called.
3507
+ invoke: proofCheckedStoreInvoke({
3508
+ binding,
3509
+ redeem: (secret, operation) => rt.actor.enqueue(() => redeemStoreProof({ sql: spineSql(rt.db), now: this.clock() }, secret, { binding, operation, principal })),
3510
+ send: (request) => runner.invoke({ tenantId, vertical, scopeId, binding }, request),
3511
+ onStoreCall: options?.onStoreCall,
3512
+ }),
3390
3513
  };
3391
3514
  }
3392
3515
  /** The scope's vertical when it has one. No vertical means this host has no store to touch. */
@@ -3763,10 +3886,41 @@ export class SqliteScopeHost {
3763
3886
  // Parsed at the door, like an operation's input: HostAdmin callers are trusted to be the
3764
3887
  // platform, not to have built a well-formed batch.
3765
3888
  const batch = importBatch.parse(raw);
3889
+ return this.applyImport(tenantId, scopeId, batch, { after: batch.after, next: batch.next });
3890
+ }
3891
+ /**
3892
+ * K-74 (#3492): an event another app's broker PUSHED here, as the receiving broker hands it
3893
+ * on. `deliverToPeer`'s door, row for row (the inert-copy pause, the peer admission, a journal
3894
+ * row per (event, module), a dead letter per withheld row, the tail), with no compare-and-set
3895
+ * and no watermark move: pushed ahead of an earlier event, a moved watermark would make the
3896
+ * pull path skip that one. The pull path finds what this journaled and counts it a duplicate.
3897
+ * `source` is the caller the router verified, as the receiving broker read it from the envelope.
3898
+ */
3899
+ async deliverPushedToPeer(tenantId, scopeId, raw) {
3900
+ return this.applyImport(tenantId, scopeId, pushedImport.parse(raw), null);
3901
+ }
3902
+ /**
3903
+ * The relay's doors over this host (#3492), for `relayScopeEnds`: the export read as the pull
3904
+ * path reads it (audited under `actor`), the pushed import, and the system door a resume target
3905
+ * is invoked through. `requests` is what the app's host code does with a request it is sent.
3906
+ */
3907
+ relayScopeDoors(actor, requests) {
3908
+ return {
3909
+ readExports: (t, s, input) => this.admin.readExportedEvents(actor, t, s, input),
3910
+ importPushed: (t, s, pushed) => this.deliverPushedToPeer(t, s, pushed),
3911
+ invokeAsSystem: async ({ module, tenantId: t, scopeId: s, operation, input, idempotencyKey }) => (await this.getSystemScope(moduleId.parse(module), t, s)).invoke(operation, input, { idempotencyKey }),
3912
+ ...(requests ? { requests } : {}),
3913
+ };
3914
+ }
3915
+ /**
3916
+ * One import, pulled (`edge`: the compare-and-set and the advance) or pushed (`edge` null:
3917
+ * neither). Everything else is the same door.
3918
+ */
3919
+ async applyImport(tenantId, scopeId, batch, edge) {
3766
3920
  const source = batch.source;
3767
3921
  const rt = await this.openActiveScope(tenantId, scopeId);
3768
3922
  return rt.actor.enqueue(async () => {
3769
- const result = emptyImportResult(batch);
3923
+ const result = emptyImportResult({ after: edge?.after ?? null });
3770
3924
  // #2004: a copy consumes no other vertical's events, at the door as in the sweep
3771
3925
  // (`scope-copy.ts`). A pause: nothing runs and the watermark stays.
3772
3926
  if (!this.isPrimaryInDirectory(scopeId))
@@ -3785,7 +3939,9 @@ export class SqliteScopeHost {
3785
3939
  // The compare-and-set. Inside the actor, so nothing moves the watermark between this
3786
3940
  // read and the advance at the end.
3787
3941
  const current = rt.db.prepare(IMPORT_CURSOR_OF_SQL).get(source.scopeId)?.cursor ?? null;
3788
- if (current !== batch.after)
3942
+ if (edge === null)
3943
+ result.cursor = current;
3944
+ else if (current !== edge.after)
3789
3945
  return { ...result, cursor: current, stale: true };
3790
3946
  const at = new Date().toISOString();
3791
3947
  const record = rt.db.prepare(IMPORT_RECORD_SQL);
@@ -3870,17 +4026,44 @@ export class SqliteScopeHost {
3870
4026
  result.duplicates += 1;
3871
4027
  }
3872
4028
  // LAST, in this scope's store: a crash before here redelivers the batch, and the journal
3873
- // rows above absorb it.
3874
- rt.db.prepare(IMPORT_CURSOR_ADVANCE_SQL).run(source.scopeId, source.vertical, batch.next, at);
3875
- result.cursor = batch.next;
4029
+ // rows above absorb it. A pushed event moves nothing (#3492).
4030
+ if (edge !== null) {
4031
+ rt.db.prepare(IMPORT_CURSOR_ADVANCE_SQL).run(source.scopeId, source.vertical, edge.next, at);
4032
+ result.cursor = edge.next;
4033
+ }
3876
4034
  lines.end();
3877
4035
  // What the handlers emitted reaches this scope's own consumers and executors in the same
3878
4036
  // tail, under the ordinary cascade cap.
3879
4037
  await this.dispatch(rt, null);
3880
4038
  await this.dispatchExecutors(rt, null);
4039
+ // K-74: what the import's commits and their consumers emitted (never throws), as the
4040
+ // Durable Object's `settleCommitted` hands it off.
4041
+ await this.handOffCommitted(rt);
3881
4042
  return result;
3882
4043
  });
3883
4044
  }
4045
+ /**
4046
+ * #2993 part 4: a vertical's scope types, as the version a new scope of it would run declares
4047
+ * them: the version it serves in place, else the one its `prod` channel names. A vertical with no
4048
+ * such version, or one that declares no types, has the one `home` type.
4049
+ */
4050
+ verticalScopeTypePlan(slug) {
4051
+ const serving = this.directory.prepare('SELECT serving_version_id FROM verticals WHERE slug = ?').get(slug);
4052
+ const prod = this.directory
4053
+ .prepare("SELECT version_id FROM vertical_channels WHERE vertical_slug = ? AND channel = 'prod'")
4054
+ .get(slug);
4055
+ const versionId = serving?.serving_version_id ?? prod?.version_id;
4056
+ return scopeTypePlanOfManifest(versionId ? this.manifestJsonOf(versionId, slug) : undefined);
4057
+ }
4058
+ /**
4059
+ * #2993 part 4: the types other than `home` the vertical's unreaped scopes hold, each once: what
4060
+ * a promote judges the incoming version's declared types against.
4061
+ */
4062
+ scopeTypesHeldBy(vertical) {
4063
+ return this.directory
4064
+ .prepare("SELECT DISTINCT scope_type FROM scopes WHERE vertical = ? AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type")
4065
+ .all(vertical).map((r) => r.scope_type);
4066
+ }
3884
4067
  /**
3885
4068
  * A stored version's manifest, unaudited: the platform reading its own code metadata (#1705).
3886
4069
  * `undefined` when the registry has no such version (under `slug`, when one is named).
@@ -3920,9 +4103,31 @@ export class SqliteScopeHost {
3920
4103
  /** What `slug` serves in place, or null when nothing is. */
3921
4104
  servingPointerOfVertical(slug) {
3922
4105
  const v = this.directory
3923
- .prepare('SELECT serving_ref, serving_version_id FROM verticals WHERE slug = ?')
4106
+ .prepare('SELECT serving_ref, serving_version_id, earlier_majors FROM verticals WHERE slug = ?')
3924
4107
  .get(slug);
3925
- return v?.serving_ref && v.serving_version_id ? { ref: v.serving_ref, versionId: v.serving_version_id } : null;
4108
+ if (!v?.serving_ref || !v.serving_version_id)
4109
+ return null;
4110
+ // K-65 (#3539 part 2): an install on an earlier major runs that major's version.
4111
+ const earlier = earlierMajorsOf(v.earlier_majors).map((m) => ({ ref: m.ref, versionId: m.versionId }));
4112
+ return { ref: v.serving_ref, versionId: v.serving_version_id, ...(earlier.length ? { earlier } : {}) };
4113
+ }
4114
+ /**
4115
+ * #3539 (K-65): the refusal promoting `incoming` over any of `bases` earns if the vertical is
4116
+ * listed, each distinct version judged once, or null. The first that refuses is the one named.
4117
+ */
4118
+ releaseWithinMajor(vertical, bases, incoming, servesMajors = false) {
4119
+ const side = (v) => ({ id: v.id, version: v.version, manifestJson: this.manifestJsonOf(v.id) ?? null });
4120
+ const seen = new Set();
4121
+ const distinct = bases.filter((b) => !!b && !seen.has(b.id) && !!seen.add(b.id));
4122
+ if (distinct.length === 0)
4123
+ return null;
4124
+ const head = side(incoming);
4125
+ for (const base of distinct) {
4126
+ const refusal = releaseWithinMajorRefusal({ vertical, base: side(base), head, classify: classifyRelease, servesMajors });
4127
+ if (refusal)
4128
+ return refusal;
4129
+ }
4130
+ return null;
3926
4131
  }
3927
4132
  /**
3928
4133
  * #2178: refuse running `incomingId` where any of `froms` ran, each distinct version judged once,
@@ -4152,6 +4357,9 @@ export class SqliteScopeHost {
4152
4357
  return (this.peerUnion ??= collectPeers(this.modules.values()));
4153
4358
  }
4154
4359
  peerUnion;
4360
+ /** #3488: the registered manifests' sender declarations by type, which every handoff reads. */
4361
+ senders = new Map();
4362
+ senderManifests = [];
4155
4363
  /**
4156
4364
  * The peer door (#1706) — mirror of the connection, system and capability doors. The caller is
4157
4365
  * the local broker's word (the platform's, on the pure host); the pair and lifecycle gate run
@@ -4184,6 +4392,8 @@ export class SqliteScopeHost {
4184
4392
  const rt = await this.openActiveScope(tenantId, scopeId);
4185
4393
  const subject = asPrincipal(principalId.parse(principal));
4186
4394
  return rt.actor.enqueue(() => {
4395
+ // #2993 part 3: a role of another scope type does not exist here.
4396
+ this.refuseRoleOutsideType(scopeId, roleKey);
4187
4397
  // #2430: the answer a person's door would give — a role carrying a reserved key is refused.
4188
4398
  this.refuseReservedRole(tenantId, roleKey, 'person');
4189
4399
  return this.assignmentBound(subject, tenantId, scopeId, roleKey);
@@ -4194,6 +4404,7 @@ export class SqliteScopeHost {
4194
4404
  const subject = asPrincipal(principalId.parse(caller));
4195
4405
  const target = principalId.parse(assignee);
4196
4406
  return rt.actor.turn(async () => {
4407
+ this.refuseRoleOutsideType(scopeId, roleKey); // #2993 part 3
4197
4408
  // #2430: read in the same serialized task as the bound and the grant.
4198
4409
  this.refuseReservedRole(tenantId, roleKey, 'person');
4199
4410
  const bound = await this.assignmentBound(subject, tenantId, scopeId, roleKey);
@@ -4213,6 +4424,7 @@ export class SqliteScopeHost {
4213
4424
  const answer = await rt.actor.turn(() => {
4214
4425
  // #2430: the role moved TO is conferred by a person; the one moved from is only taken back.
4215
4426
  // Read in the same serialized task as the bound and the write.
4427
+ this.refuseRoleOutsideType(scopeId, to); // #2993 part 3
4216
4428
  this.refuseReservedRole(tenantId, to, 'person');
4217
4429
  return changeScopeRole(switchSqlOf(rt.db), scopeId, target, from, to, this.clock(), this.roleBound(caller, tenantId, scopeId), (run) => rt.db.transaction(run)());
4218
4430
  });
@@ -4365,6 +4577,16 @@ export class SqliteScopeHost {
4365
4577
  if (refusal)
4366
4578
  throw substratError('forbidden', refusal);
4367
4579
  }
4580
+ /**
4581
+ * #2993 part 3: refuse seating `roleKey` at a scope whose type does not hold it
4582
+ * (`scopeTypeRoleRefusal`). Nothing is refused on a host with no declared types, or for a role no
4583
+ * type names.
4584
+ */
4585
+ refuseRoleOutsideType(scopeId, roleKey) {
4586
+ const refusal = scopeTypeRoleRefusal(this.scopeTypePlan, this.scopeTypeOf(scopeId), roleKey);
4587
+ if (refusal)
4588
+ throw substratError('forbidden', refusal);
4589
+ }
4368
4590
  /**
4369
4591
  * #2447: refuse defining `role` for `tenantId` (`reservedRoleDefinitionRefusal`): against the keys
4370
4592
  * the modules registered or listed here reserve and declare, and the tenant's other roles.
@@ -4619,7 +4841,7 @@ export class SqliteScopeHost {
4619
4841
  // `last_status` are the last RECORDED at and verdict — nothing ran.
4620
4842
  // Collapse duplicate event types to the tightest window, ACROSS modules.
4621
4843
  const windows = new Map();
4622
- for (const m of this.modules.values()) {
4844
+ for (const m of this.modulesOf(scopeId)) {
4623
4845
  for (const f of m.freshness) {
4624
4846
  const prev = windows.get(f.eventType);
4625
4847
  if (prev === undefined || f.within.hours < prev)
@@ -4683,6 +4905,9 @@ export class SqliteScopeHost {
4683
4905
  const mod = this.modules.get(moduleId);
4684
4906
  if (!mod || mod.schedules.length === 0)
4685
4907
  return report;
4908
+ // #2993: a scope whose type does not run the module has nothing of it due.
4909
+ if (!this.runsOn(scopeId, moduleId))
4910
+ return report;
4686
4911
  // The scope must be a live scope of this host. A non-active or missing scope is
4687
4912
  // not this driver's problem to raise — it simply has nothing due (the sweep
4688
4913
  // already enumerated `active` scopes; this guards a race where one archived
@@ -4713,14 +4938,37 @@ export class SqliteScopeHost {
4713
4938
  const switched = systemScheduleState(switchSqlOf(rt.db), moduleId, nowIso);
4714
4939
  const lastRuns = new Map();
4715
4940
  if (switched !== 'on')
4716
- return { state: switched, lastRuns };
4941
+ return { state: switched, lastRuns, purgeDue: new Map(), eventDue: new Map() };
4717
4942
  const read = rt.db.prepare(`SELECT last_run_at FROM _substrat_schedule_state
4718
4943
  WHERE kind = 'schedule' AND schedule_op = ?`);
4719
4944
  for (const schedule of mod.schedules) {
4720
4945
  const row = read.get(schedule.operation);
4721
4946
  lastRuns.set(schedule.operation, row?.last_run_at ?? null);
4722
4947
  }
4723
- return { state: switched, lastRuns };
4948
+ // #3540: under `purgeDue: 'event'`, when each purge schedule is due by its own rows — read in
4949
+ // the same turn as the cadence rows, for the reason that turn gives.
4950
+ const purgeDue = new Map();
4951
+ if (this.purgeDueByEvent) {
4952
+ for (const schedule of mod.schedules) {
4953
+ if (!schedule.purge)
4954
+ continue;
4955
+ purgeDue.set(schedule.operation, purgeDueAt(spineSql(rt.db), this.statePlans, [purgeDueScheduleOf(schedule)], Date.parse(nowIso)));
4956
+ }
4957
+ }
4958
+ // #3540: under the same switch, when each `due: 'event'` schedule that has run under that form
4959
+ // is next due (null: nothing is). One that has not is absent, and its cadence decides.
4960
+ const eventDue = new Map();
4961
+ if (this.purgeDueByEvent) {
4962
+ for (const schedule of mod.schedules) {
4963
+ const due = this.dueSchedules.get(schedule.operation);
4964
+ if (!due || schedule.purge)
4965
+ continue;
4966
+ const row = readScheduleDue(spineSql(rt.db), due);
4967
+ if (row.established)
4968
+ eventDue.set(schedule.operation, row.dueAt);
4969
+ }
4970
+ }
4971
+ return { state: switched, lastRuns, purgeDue, eventDue };
4724
4972
  });
4725
4973
  const state = gate.state;
4726
4974
  if (state === 'ungranted')
@@ -4757,9 +5005,25 @@ export class SqliteScopeHost {
4757
5005
  },
4758
5006
  };
4759
5007
  for (const schedule of mod.schedules) {
5008
+ // #3540: the scope's alarm asks for its purges only (the Durable Object's `purgeAlarm`), or for
5009
+ // its purges and the `due: 'event'` schedules that have run under that form (`dueAlarm`).
5010
+ if (tick?.purgeAlarm && !schedule.purge)
5011
+ continue;
5012
+ if (tick?.dueAlarm && !schedule.purge && !gate.eventDue.has(schedule.operation))
5013
+ continue;
4760
5014
  const lastRunAt = gate.lastRuns.get(schedule.operation) ?? null;
4761
5015
  const lastRun = lastRunAt ? Date.parse(lastRunAt) : null;
4762
- const dueAt = lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
5016
+ // #3540: a purge due by event is due when its earliest row is (null: nothing binned is ever due),
5017
+ // and its lateness is measured from that row's date rather than from the cadence. A `due: 'event'`
5018
+ // schedule that has run under that form is due when the date its work wrote is.
5019
+ const byRows = schedule.purge
5020
+ ? this.purgeDueByEvent
5021
+ ? (gate.purgeDue.get(schedule.operation) ?? null)
5022
+ : undefined
5023
+ : gate.eventDue.has(schedule.operation)
5024
+ ? (gate.eventDue.get(schedule.operation) ?? null)
5025
+ : undefined;
5026
+ const dueAt = byRows !== undefined ? (byRows ?? Infinity) : lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
4763
5027
  if (now < dueAt) {
4764
5028
  report.skipped += 1;
4765
5029
  report.runs.push({ operation: schedule.operation, outcome: 'skipped' });
@@ -4834,8 +5098,8 @@ export class SqliteScopeHost {
4834
5098
  outcome: status,
4835
5099
  ...failure,
4836
5100
  // Against the host's clock, which is what decided the run was due.
4837
- dueAt: lastRun === null ? null : new Date(dueAt).toISOString(),
4838
- latenessMs: lastRun === null ? null : now - dueAt,
5101
+ dueAt: byRows != null ? new Date(byRows).toISOString() : lastRun === null || byRows !== undefined ? null : new Date(dueAt).toISOString(),
5102
+ latenessMs: byRows != null ? now - byRows : lastRun === null || byRows !== undefined ? null : now - dueAt,
4839
5103
  ...(emitted ? { emitted } : {}),
4840
5104
  versionId: this.versionId,
4841
5105
  });
@@ -4859,6 +5123,41 @@ export class SqliteScopeHost {
4859
5123
  report.purgeRequests = purgeRequests;
4860
5124
  return report;
4861
5125
  }
5126
+ /**
5127
+ * #3540: the instant this scope's purge alarm would stand at — the Durable Object arms its one
5128
+ * alarm for exactly this (`purgeDueAt`) — or null when nothing in its bins will ever be due, or
5129
+ * purges are not due by event on this host (`purgeDue`). This host has no alarm of its own: a
5130
+ * harness that wants the hosted shape sleeps until this instant and runs the pass.
5131
+ */
5132
+ async purgeAlarmAt(tenantId, scopeId) {
5133
+ return this.alarmAt(tenantId, scopeId, false);
5134
+ }
5135
+ /**
5136
+ * #3540: the instant this scope's alarm would stand at for everything due by event — its purges
5137
+ * (`purgeAlarmAt`) and its `due: 'event'` schedules that have run under that form — or null when
5138
+ * nothing is, or nothing is due by event on this host (`purgeDue`). The pass runs them when due.
5139
+ */
5140
+ async dueAlarmAt(tenantId, scopeId) {
5141
+ return this.alarmAt(tenantId, scopeId, true);
5142
+ }
5143
+ async alarmAt(tenantId, scopeId, withSchedules) {
5144
+ if (!this.purgeDueByEvent)
5145
+ return null;
5146
+ if (this.scopeWorkRefusal(tenantId, scopeId))
5147
+ return null;
5148
+ const schedules = [...this.modules.values()].flatMap((m) => m.schedules.filter((s) => s.purge).map(purgeDueScheduleOf));
5149
+ const due = withSchedules ? [...this.dueSchedules.values()] : [];
5150
+ if (schedules.length === 0 && due.length === 0)
5151
+ return null;
5152
+ const rt = this.runtime(tenantId, scopeId);
5153
+ await this.applyPendingMigrations(rt);
5154
+ const at = await rt.actor.turn(() => {
5155
+ const purges = schedules.length > 0 ? purgeDueAt(spineSql(rt.db), this.statePlans, schedules, Date.parse(this.clock())) : null;
5156
+ const events = scheduleDueAt(spineSql(rt.db), due);
5157
+ return purges === null ? events : events === null ? purges : Math.min(purges, events);
5158
+ });
5159
+ return at === null ? null : new Date(at).toISOString();
5160
+ }
4862
5161
  /**
4863
5162
  * One pass of a purge horizon's schedule on one scope (#119) — the Durable Object's
4864
5163
  * `runPurgeSweep`, mirrored. The caller names only which schedule: the module and the entity come
@@ -4982,6 +5281,11 @@ export class SqliteScopeHost {
4982
5281
  // gives it, so a demo and a hosted vertical answer 404 for the same reason.
4983
5282
  if (!handler)
4984
5283
  return Promise.reject(substratError('not_found', `unknown operation: ${operation}`));
5284
+ // #2993: an operation of a module this scope's type does not run is unknown here.
5285
+ const declaredBy = this.operationEntitlement.get(operation)?.moduleId;
5286
+ if (declaredBy !== undefined && !this.runsOn(scopeId, declaredBy)) {
5287
+ return Promise.reject(operationNotInScopeType(operation, this.scopeTypeOf(scopeId)));
5288
+ }
4985
5289
  // K-42: re-read the session on EVERY invoke, not once when the stub was
4986
5290
  // minted. A stub is a capability and nothing takes it away, so a session
4987
5291
  // checked only at the door would be a time box the one caller holding it
@@ -5213,6 +5517,11 @@ export class SqliteScopeHost {
5213
5517
  // here, before the guards and the handler — the declared key first, so a caller
5214
5518
  // without it meets the same `forbidden` an active entity gives (`entity-trash.ts`).
5215
5519
  await refuseTrashedTarget({ sql: spineSql(rt.db), plans: this.statePlans, check: ctx.check, now: ctx.now() }, operation, target, parsed, purging ? { gate: this.purgeGateFacts(rt, subject.id, tenantId, scopeId) } : undefined);
5520
+ // #3540: a run of a due-by-event schedule's operation clears its date first, in this
5521
+ // transaction, and the handler writes the next one for what it leaves. A throw rolls the
5522
+ // clearing back with the rest, so the date it was due by is still there for the next try.
5523
+ if (this.dueSchedules.has(operation))
5524
+ consumeScheduleDue(spineSql(rt.db), operation);
5216
5525
  // Manifest guards (K-17): pre-conditions, inside the operation's own
5217
5526
  // transaction, before the handler. A throw here blocks the operation
5218
5527
  // and rolls back exactly like a handler throw — fail closed.
@@ -5950,7 +6259,7 @@ export class SqliteScopeHost {
5950
6259
  // host that does not run the scope's modules must never clear (or overwrite)
5951
6260
  // a failure recorded by the deployment that does.
5952
6261
  // A scope that applied different SQL (#2066) is not a noop: the pass below fails it.
5953
- const plan = await planMigrations(this.modules.values(), rt.appliedMigrations);
6262
+ const plan = await planMigrations(this.modulesOf(rt.scopeId), rt.appliedMigrations);
5954
6263
  const pending = plan.pending.length > 0 || plan.diverged !== undefined;
5955
6264
  // #2090: with nothing pending, the pass still checks and repairs what the kernel derived —
5956
6265
  // the one way a scope stripped before that check existed is ever put right.
@@ -6064,7 +6373,7 @@ export class SqliteScopeHost {
6064
6373
  let marks = this.handoffMarks.get(key) ?? (await broker.marks(rt.tenantId, rt.scopeId));
6065
6374
  // A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
6066
6375
  for (let round = 0; round < 20; round++) {
6067
- const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, rt.db.prepare(q.sql).all(...q.params), ids, commit));
6376
+ const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, rt.db.prepare(q.sql).all(...q.params), ids, commit, this.senders));
6068
6377
  if (sent.length === 0) {
6069
6378
  // A5: a window's start the broker has not acknowledged goes on its own.
6070
6379
  if (options.start) {
@@ -6186,7 +6495,7 @@ export class SqliteScopeHost {
6186
6495
  async dispatchRounds(rt, invocationId, lines) {
6187
6496
  for (let round = 0; round < 50; round++) {
6188
6497
  let deliveredAny = false;
6189
- for (const mod of this.modules.values()) {
6498
+ for (const mod of this.modulesOf(rt.scopeId)) {
6190
6499
  for (const consumer of mod.consumers) {
6191
6500
  const rows = rt.db
6192
6501
  .prepare(`SELECT * FROM _substrat_outbox o
@@ -6742,6 +7051,7 @@ export class SqliteScopeHost {
6742
7051
  previewTraceSampling: r.preview_trace_sampling ?? 0,
6743
7052
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
6744
7053
  ...(r.serving_version_id ? { servingVersionId: r.serving_version_id } : {}),
7054
+ ...(r.earlier_majors ? { earlierMajors: earlierMajorsOf(r.earlier_majors) } : {}),
6745
7055
  createdAt: r.created_at,
6746
7056
  });
6747
7057
  const readVertical = (slugValue) => {
@@ -6857,6 +7167,8 @@ export class SqliteScopeHost {
6857
7167
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
6858
7168
  archivedAt: r.archived_at ?? null,
6859
7169
  archivedFromStatus: (r.archived_from_status ?? null),
7170
+ // #2993: a typed scope names its type; a home scope's record (NULL) is unchanged.
7171
+ ...(r.scope_type ? { scopeType: r.scope_type } : {}),
6860
7172
  createdAt: r.created_at,
6861
7173
  });
6862
7174
  // The directory rows `listScopes` and `listScopesReadable` map, filtered and paged alike.
@@ -6917,7 +7229,7 @@ export class SqliteScopeHost {
6917
7229
  // describes what the transition DID, not the state it left.
6918
7230
  afterExtra) => {
6919
7231
  const row = this.directory
6920
- .prepare('SELECT tenant_id, status, vertical, stores_fenced_at FROM scopes WHERE scope_id = ?')
7232
+ .prepare('SELECT tenant_id, status, vertical, stores_fenced_at, parent_scope_id FROM scopes WHERE scope_id = ?')
6921
7233
  .get(scopeId);
6922
7234
  if (!row || row.tenant_id !== tenantId) {
6923
7235
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
@@ -6925,6 +7237,14 @@ export class SqliteScopeHost {
6925
7237
  if (to === 'active' && row.stores_fenced_at !== null) {
6926
7238
  throw substratError('conflict', storesFencedRefusal(scopeId));
6927
7239
  }
7240
+ // #2995: a child does not outlive its parent. Archiving a parent archives its children, and
7241
+ // none of them comes back (an unarchive, or a late activation) while the parent is archived.
7242
+ if (to === 'active' && row.parent_scope_id !== null) {
7243
+ const parent = this.directory.prepare('SELECT status FROM scopes WHERE scope_id = ?').get(row.parent_scope_id);
7244
+ if (!parent || parent.status === 'archived' || parent.status === 'reaped') {
7245
+ throw substratError('conflict', `scope ${scopeId} is a child of ${row.parent_scope_id}, which is ${parent?.status ?? 'gone'}: a child does not outlive its parent`);
7246
+ }
7247
+ }
6928
7248
  if (!from.includes(row.status)) {
6929
7249
  throw substratError('conflict', `illegal scope transition for ${action}: ${row.status} → ${to} ` +
6930
7250
  `(allowed from: ${from.join('|')})`);
@@ -6965,6 +7285,57 @@ export class SqliteScopeHost {
6965
7285
  this.recordAdmin(actor, action, { tenantId, scopeId, vertical: row.vertical }, { status: row.status }, { status: to, ...afterExtra });
6966
7286
  })();
6967
7287
  };
7288
+ // Reap an ARCHIVED scope's storage while keeping its directory row as a tombstone
7289
+ // (§4.4). Only `archived` may be reaped — an illegal source fails closed. The
7290
+ // STORAGE goes before the status flip (the ordering deleteSnapshot keeps): a crash
7291
+ // between leaves an `archived` row over an emptied file and re-running converges,
7292
+ // whereas flipping first would strand a live file under a `reaped` row reap never
7293
+ // revisits. Hostnames were released at archive and the row survives, so — unlike
7294
+ // deleteSnapshot — neither is touched here.
7295
+ const assertReapable = (tenantId, scopeId, opts) => {
7296
+ const rec = this.directory
7297
+ .prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
7298
+ .get(scopeId);
7299
+ if (!rec || rec.tenant_id !== tenantId) {
7300
+ throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
7301
+ }
7302
+ if (rec.status !== 'archived') {
7303
+ throw substratError('conflict', `scope ${scopeId} is ${rec.status}, not archived — only an archived scope may be reaped`);
7304
+ }
7305
+ // A serving scope always holds ≥1 bound hostname; a truly-dead one has been
7306
+ // unbound. The dashboard delete path unbinds AT archive, but a bare console
7307
+ // `archiveScope` does not — so reap cannot ASSUME the release, it must verify it.
7308
+ // Refuse (fail closed) while any name still resolves here: unbinding first is a
7309
+ // visible, reversible step, and it is the wall that stops the irreversible wipe
7310
+ // from ever landing on an app that is still online (§4.4). `force` is the
7311
+ // deliberate-teardown bypass (tenant reap / retention sweep), where every name is
7312
+ // being released anyway; the interactive per-scope reap never sets it.
7313
+ const bound = opts?.force
7314
+ ? undefined
7315
+ : this.directory
7316
+ .prepare('SELECT hostname FROM hostnames WHERE scope_id = ? LIMIT 1')
7317
+ .get(scopeId);
7318
+ if (bound) {
7319
+ throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound.hostname}' — ` +
7320
+ `unbind it before reaping (reap wipes storage and cannot be undone)`);
7321
+ }
7322
+ };
7323
+ const reapOne = async (actor, tenantId, scopeId, opts) => {
7324
+ assertReapable(tenantId, scopeId, opts);
7325
+ // The reader goes with the writer (#1624): an open handle on a removed file keeps
7326
+ // reading the unlinked bytes, which is the reaped data answering as if it were live.
7327
+ const rt = this.scopes.get(`${tenantId}/${scopeId}`);
7328
+ if (rt)
7329
+ this.closeRuntime(rt);
7330
+ await this.wipeScopeStores(tenantId, scopeId);
7331
+ rmSync(join(this.dir, `${tenantId}__${scopeId}.sqlite`), { force: true });
7332
+ // The recoverable copy the caller stored first (#493), named in the audit entry so
7333
+ // the trail answers "was there a backup" without correlating two timestamps.
7334
+ await transitionScope(actor, 'reapScope', tenantId, scopeId, ['archived'], 'reaped', {
7335
+ backupRef: opts?.backupRef ?? null,
7336
+ ...(opts?.withParent ? { withParent: opts.withParent } : {}),
7337
+ });
7338
+ };
6968
7339
  const writeTenantTuple = (tenantId, subject, relation, object, expiresAt) => this.directory
6969
7340
  .prepare(`INSERT OR REPLACE INTO _substrat_tenant_tuples
6970
7341
  (tenant_id, subject, relation, object, expires_at)
@@ -7380,6 +7751,10 @@ export class SqliteScopeHost {
7380
7751
  // Before the write opens a scope's file; synchronous with a tenant node's unit, so no
7381
7752
  // definition lands between the two.
7382
7753
  this.refuseReservedRole(tenantId, assignment.roleKey, 'platform');
7754
+ // #2993 part 3: a scope-level seat in a role of another scope type is refused. A tenant-level
7755
+ // one names no scope, so no type: the role reaches the scopes whose type holds it.
7756
+ if (scopeId)
7757
+ this.refuseRoleOutsideType(scopeId, assignment.roleKey);
7383
7758
  await auditedOnNode(assignment.node, () => {
7384
7759
  if (scopeId)
7385
7760
  writeScopeTuple(assignment.node, subject, `role:${assignment.roleKey}`, `scope:${scopeId}`);
@@ -7870,6 +8245,40 @@ export class SqliteScopeHost {
7870
8245
  this.recordAccess(actor, 'peerBindings', { tenantId, scopeId: callerScopeId }, null, rows.length);
7871
8246
  return rows.map((r) => ({ tenantId, callerScopeId, vertical: r.vertical, targetScopeId: r.target_scope_id, invalidated: r.invalidated === 1 }));
7872
8247
  },
8248
+ // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
8249
+ listEnvironments: async (actor, tenantId, vertical) => {
8250
+ const rows = environmentsOf(switchSqlOf(this.directory), tenantId, vertical);
8251
+ this.recordAccess(actor, 'listEnvironments', { tenantId }, { vertical }, rows.length);
8252
+ return rows;
8253
+ },
8254
+ defineEnvironment: async (actor, input) => this.directory.transaction(() => {
8255
+ const out = defineEnvironmentIn(switchSqlOf(this.directory), input, { at: new Date().toISOString(), by: actor });
8256
+ if (out.created) {
8257
+ this.recordAdmin(actor, 'defineEnvironment', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, null, { vertical: input.vertical, scopeId: out.scopeId });
8258
+ }
8259
+ return { environment: out.environment, created: out.created };
8260
+ })(),
8261
+ removeEnvironment: async (actor, input) => this.directory.transaction(() => {
8262
+ const out = removeEnvironmentIn(switchSqlOf(this.directory), input);
8263
+ if (out.removed) {
8264
+ this.recordAdmin(actor, 'removeEnvironment', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, { vertical: input.vertical, scopeId: out.scopeId }, null);
8265
+ }
8266
+ return { removed: out.removed };
8267
+ })(),
8268
+ claimEnvironmentServe: async (_actor, input, claim, leaseMs) => this.directory.transaction(() => {
8269
+ const now = Date.now();
8270
+ return claimEnvironmentServeIn(switchSqlOf(this.directory), input, claim, { now: new Date(now).toISOString(), until: new Date(now + leaseMs).toISOString() });
8271
+ })(),
8272
+ releaseEnvironmentServe: async (_actor, input, claim) => {
8273
+ releaseEnvironmentServeIn(switchSqlOf(this.directory), input, claim);
8274
+ },
8275
+ setEnvironmentServing: async (actor, input, next, expected, claim) => this.directory.transaction(() => {
8276
+ const out = setEnvironmentServingIn(switchSqlOf(this.directory), input, next, expected, claim);
8277
+ if (!out.moved) {
8278
+ throw substratError('precondition_failed', `the environment '${input.name}' of '${input.vertical}' serves another record than the one this serve was diffed from: read it again`);
8279
+ }
8280
+ this.recordAdmin(actor, 'setEnvironmentServing', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null, { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId });
8281
+ })(),
7873
8282
  setPeerBinding: async (_actor, tenantId, callerScopeId, vertical, targetScopeId) => this.directory.transaction(() => {
7874
8283
  const caller = this.directory.prepare('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?').get(callerScopeId);
7875
8284
  if (!caller || caller.tenant_id !== tenantId || caller.status !== 'active' || !isPrimaryScopeRow(caller)) {
@@ -7911,7 +8320,9 @@ export class SqliteScopeHost {
7911
8320
  const r = this.directory
7912
8321
  .prepare(`SELECT h.tenant_id, h.scope_id, h.vertical_slug, h.surface, h.region,
7913
8322
  COALESCE(s.serving_ref, vv.deployment_ref) AS deployment_ref,
7914
- CASE WHEN s.serving_ref IS NOT NULL
8323
+ -- #3530 step 4: a scope on its environment's own script runs the version it is
8324
+ -- bound to, which is what that script was last served (\`ae\`, null otherwise).
8325
+ CASE WHEN s.serving_ref IS NOT NULL AND ae.serving_ref IS NULL
7915
8326
  THEN json_extract(sv.manifest_json, '$.outbound')
7916
8327
  ELSE json_extract(vv.manifest_json, '$.outbound') END AS outbound_json,
7917
8328
  s.kind, s.forked_from,
@@ -7928,7 +8339,9 @@ export class SqliteScopeHost {
7928
8339
  JOIN tenants t ON t.tenant_id = s.tenant_id
7929
8340
  LEFT JOIN vertical_versions vv ON vv.id = s.vertical_version_id
7930
8341
  LEFT JOIN verticals vr ON vr.slug = s.vertical
7931
- LEFT JOIN vertical_versions sv ON sv.id = vr.serving_version_id
8342
+ -- K-65 (#3539 part 2): the version the scope's script runs, an earlier major's included.
8343
+ LEFT JOIN vertical_versions sv ON sv.id = ${SCRIPT_SERVING_VERSION_SQL}
8344
+ ${ENVIRONMENT_SCRIPT_JOIN_SQL}
7932
8345
  WHERE h.hostname = ? AND h.status = 'active'
7933
8346
  AND s.status = 'active' AND t.status = 'active'`)
7934
8347
  .get(hostname);
@@ -8277,6 +8690,22 @@ export class SqliteScopeHost {
8277
8690
  served?.versionId,
8278
8691
  ...owned.map((s) => runningVersionOf(mapScope(s), served)),
8279
8692
  ], versionId, served || owned.length > 0 ? this.provisionedVersionsOf(verticalSlug, served, owned.length > 0 ? owning.ownerTenant : null) : []);
8693
+ // #3539 (K-65): a listed app takes no breaking change within its major. Ranked against what
8694
+ // the channel names and what the serving script runs (a failed serve leaves it behind), by
8695
+ // the rules `substrat changeset` writes with. Ahead of the acknowledgements, because none of
8696
+ // them passes it. Refused here when the vertical is listed as read above, and judged again in
8697
+ // the unit that moves the channel, so a listing that lands meanwhile is seen (#2565).
8698
+ const breakingWithinMajor = channel === 'prod'
8699
+ ? this.releaseWithinMajor(verticalSlug, [outgoing, served ? await readVersion(served.versionId) : undefined], incoming,
8700
+ // #3539 part 2: a new major is served beside the old one only by a caller that serves
8701
+ // in place, and only from a version with an archive script to serve from.
8702
+ options?.servesMajors === true && incoming.deploymentRef !== null)
8703
+ : null;
8704
+ if (breakingWithinMajor && owning?.listed)
8705
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
8706
+ // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
8707
+ // of the acknowledgements, because none of them passes it.
8708
+ assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug), this.manifestJsonOf(versionId, verticalSlug));
8280
8709
  // #2333: the acknowledgements answer the review they were given against, or none at all.
8281
8710
  const reviewed = (v) => ({
8282
8711
  ...v,
@@ -8324,6 +8753,9 @@ export class SqliteScopeHost {
8324
8753
  const listed = readVertical(verticalSlug)?.listed;
8325
8754
  if (listed && options?.unlistedOnly)
8326
8755
  throw listedPromoteRefusal();
8756
+ // #3539 (K-65): ranked above; whether the vertical is listed is this unit's to read.
8757
+ if (listed && channel === 'prod' && breakingWithinMajor)
8758
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
8327
8759
  // A re-promote of what prod already names, and what serves (if anything does), moves
8328
8760
  // nothing, so it is not judged again. One whose serve would change what runs is.
8329
8761
  const serving = this.servingPointerOfVertical(verticalSlug)?.versionId ?? versionId;
@@ -8666,10 +9098,15 @@ export class SqliteScopeHost {
8666
9098
  versionId: r.serving_version_id,
8667
9099
  doClasses: r.serving_do_classes ? JSON.parse(r.serving_do_classes) : [],
8668
9100
  migrationTag: r.serving_migration_tag,
9101
+ // K-65 (#3539 part 2): what each earlier major's script runs.
9102
+ ...(r.earlier_majors
9103
+ ? { earlier: earlierMajorsOf(r.earlier_majors).map((m) => ({ ref: m.ref, versionId: m.versionId })) }
9104
+ : {}),
8669
9105
  });
8670
9106
  },
8671
- setVerticalServing: async (actor, verticalSlug, state, expected) => {
9107
+ setVerticalServing: async (actor, verticalSlug, state, expected, opts) => {
8672
9108
  const parsed = verticalServingState.parse(state);
9109
+ const supersede = opts?.supersede;
8673
9110
  const r = this.directory
8674
9111
  .prepare('SELECT * FROM verticals WHERE slug = ?')
8675
9112
  .get(verticalSlug);
@@ -8678,8 +9115,19 @@ export class SqliteScopeHost {
8678
9115
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
8679
9116
  if (expected !== undefined && !migratesFrom(r, expected))
8680
9117
  throw servingRaceRefusal(verticalSlug);
8681
- // #2178: every install on the serving script runs the new version from this moment.
8682
- this.assertNoStrandFrom([r.serving_version_id], parsed.versionId, r.serving_ref ? this.provisionedVersionsOf(verticalSlug, r.serving_version_id ? { ref: r.serving_ref, versionId: r.serving_version_id } : null, null) : []);
9118
+ // K-65 (#3539 part 2): a new major supersedes exactly the serving state the caller read.
9119
+ if (supersede && (!expected || expected.ref !== r.serving_ref || expected.versionId !== r.serving_version_id)) {
9120
+ throw servingRaceRefusal(verticalSlug);
9121
+ }
9122
+ // #2993 part 4: every install on the serving script runs the new version from this moment,
9123
+ // so it declares every type their scopes hold.
9124
+ if (!supersede && r.serving_version_id) {
9125
+ assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug), this.manifestJsonOf(parsed.versionId, verticalSlug));
9126
+ }
9127
+ // #2178: every install on the serving script runs the new version from this moment. A new
9128
+ // major's first serve moves nobody onto its script: the installs stay on the earlier one.
9129
+ if (!supersede)
9130
+ this.assertNoStrandFrom([r.serving_version_id], parsed.versionId, r.serving_ref ? this.provisionedVersionsOf(verticalSlug, r.serving_version_id ? { ref: r.serving_ref, versionId: r.serving_version_id } : null, null) : []);
8683
9131
  // #2528/#2577: a compare-and-set on the serving state the gate judged, its ref, version,
8684
9132
  // class set and tag (a serve and a re-serve can bring the ref and version back over a grown
8685
9133
  // class set), and the row's `before` read in the transaction that moves it, as the
@@ -8696,12 +9144,29 @@ export class SqliteScopeHost {
8696
9144
  raced = !servesAsFrom(now, servedFromRow(r));
8697
9145
  if (raced)
8698
9146
  return false;
9147
+ const earlier = supersede
9148
+ ? supersededMajorsJson({
9149
+ vertical: verticalSlug,
9150
+ earlierJson: now.earlier_majors,
9151
+ current: {
9152
+ ref: now.serving_ref,
9153
+ versionId: now.serving_version_id,
9154
+ doClasses: now.serving_do_classes ? JSON.parse(now.serving_do_classes) : [],
9155
+ migrationTag: now.serving_migration_tag,
9156
+ },
9157
+ nextRef: parsed.ref,
9158
+ supersede,
9159
+ })
9160
+ : (now.earlier_majors ?? null);
8699
9161
  this.directory
8700
9162
  .prepare(`UPDATE verticals SET serving_ref = ?, serving_version_id = ?,
8701
- serving_do_classes = ?, serving_migration_tag = ? WHERE slug = ?`)
8702
- .run(parsed.ref, parsed.versionId, JSON.stringify(parsed.doClasses), parsed.migrationTag, verticalSlug);
9163
+ serving_do_classes = ?, serving_migration_tag = ?, earlier_majors = ? WHERE slug = ?`)
9164
+ .run(parsed.ref, parsed.versionId, JSON.stringify(parsed.doClasses), parsed.migrationTag, earlier, verticalSlug);
8703
9165
  return true;
8704
- }, () => this.recordAdmin(actor, 'setVerticalServing', { tenantId: null }, before, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId }));
9166
+ }, () => this.recordAdmin(actor, 'setVerticalServing', { tenantId: null }, before, {
9167
+ vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId,
9168
+ ...(supersede ? { supersedes: { major: supersede.major, endsAt: supersede.endsAt } } : {}),
9169
+ }));
8705
9170
  if (raced)
8706
9171
  throw servingRaceRefusal(verticalSlug);
8707
9172
  },
@@ -8868,7 +9333,7 @@ export class SqliteScopeHost {
8868
9333
  limit: input.limit,
8869
9334
  due: input.due ?? true,
8870
9335
  ...(handedOffThrough === undefined ? {} : { handedOffThrough }),
8871
- subscribers: outboxSubscribersOf(this.modules.values(), this.executors),
9336
+ subscribers: outboxSubscribersOf(this.modulesOf(scopeId), this.executors),
8872
9337
  exportTypes: this.crossVertical.exportTypes(),
8873
9338
  }))());
8874
9339
  // Deleting a tenant's events is a mutation, so it is audited, and only when something went.
@@ -9652,54 +10117,33 @@ export class SqliteScopeHost {
9652
10117
  // Also from `provisioning`: a scope whose provisioning never completed (a failed
9653
10118
  // create) must be abandonable, or its slug is stranded forever (it can't reach a
9654
10119
  // terminal state that frees the name).
9655
- transitionScope(actor, 'archiveScope', tenantId, scopeId, ['provisioning', 'active', 'suspended'], 'archived'),
10120
+ //
10121
+ // #2995: lifecycle follows the link. The scope's children are archived with it, in the same
10122
+ // directory transaction, each with its own audit row naming the parent; a refused parent
10123
+ // archives none of them. A child already archived stays as it is.
10124
+ this.directory.transaction(() => {
10125
+ for (const child of this.childScopesOf(tenantId, scopeId, ['provisioning', 'active', 'suspended'])) {
10126
+ transitionScope(actor, 'archiveScope', tenantId, child, ['provisioning', 'active', 'suspended'], 'archived', { withParent: scopeId });
10127
+ }
10128
+ transitionScope(actor, 'archiveScope', tenantId, scopeId, ['provisioning', 'active', 'suspended'], 'archived');
10129
+ })(),
9656
10130
  unarchiveScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'unarchiveScope', tenantId, scopeId, ['archived'], 'active'),
9657
10131
  reapScope: async (actor, tenantId, scopeId, opts) => {
9658
- // Reap an ARCHIVED scope's storage while keeping its directory row as a tombstone
9659
- // (§4.4). Only `archived` may be reaped — an illegal source fails closed. The
9660
- // STORAGE goes before the status flip (the ordering deleteSnapshot keeps): a crash
9661
- // between leaves an `archived` row over an emptied file and re-running converges,
9662
- // whereas flipping first would strand a live file under a `reaped` row reap never
9663
- // revisits. Hostnames were released at archive and the row survives, so — unlike
9664
- // deleteSnapshot — neither is touched here.
9665
- const rec = this.directory
9666
- .prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
9667
- .get(scopeId);
9668
- if (!rec || rec.tenant_id !== tenantId) {
9669
- throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
9670
- }
9671
- if (rec.status !== 'archived') {
9672
- throw substratError('conflict', `scope ${scopeId} is ${rec.status}, not archived — only an archived scope may be reaped`);
9673
- }
9674
- // A serving scope always holds ≥1 bound hostname; a truly-dead one has been
9675
- // unbound. The dashboard delete path unbinds AT archive, but a bare console
9676
- // `archiveScope` does not — so reap cannot ASSUME the release, it must verify it.
9677
- // Refuse (fail closed) while any name still resolves here: unbinding first is a
9678
- // visible, reversible step, and it is the wall that stops the irreversible wipe
9679
- // from ever landing on an app that is still online (§4.4). `force` is the
9680
- // deliberate-teardown bypass (tenant reap / retention sweep), where every name is
9681
- // being released anyway; the interactive per-scope reap never sets it.
9682
- const bound = opts?.force
9683
- ? undefined
9684
- : this.directory
9685
- .prepare('SELECT hostname FROM hostnames WHERE scope_id = ? LIMIT 1')
9686
- .get(scopeId);
9687
- if (bound) {
9688
- throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound.hostname}' — ` +
9689
- `unbind it before reaping (reap wipes storage and cannot be undone)`);
9690
- }
9691
- // The reader goes with the writer (#1624): an open handle on a removed file keeps
9692
- // reading the unlinked bytes, which is the reaped data answering as if it were live.
9693
- const rt = this.scopes.get(`${tenantId}/${scopeId}`);
9694
- if (rt)
9695
- this.closeRuntime(rt);
9696
- await this.wipeScopeStores(tenantId, scopeId);
9697
- rmSync(join(this.dir, `${tenantId}__${scopeId}.sqlite`), { force: true });
9698
- // The recoverable copy the caller stored first (#493), named in the audit entry so
9699
- // the trail answers "was there a backup" without correlating two timestamps.
9700
- await transitionScope(actor, 'reapScope', tenantId, scopeId, ['archived'], 'reaped', {
9701
- backupRef: opts?.backupRef ?? null,
9702
- });
10132
+ // #2995: a child does not outlive its parent, so a parent's reap reaps its children first,
10133
+ // each as its own reap with its own audit row. Everything that could refuse is checked over
10134
+ // the parent AND its children before anything is wiped: each is archived (an archive of the
10135
+ // parent archived them), and none still resolves a hostname. A crash part-way leaves the
10136
+ // parent archived over fewer children, and running the reap again finishes it.
10137
+ const rec = this.directory.prepare('SELECT tenant_id FROM scopes WHERE scope_id = ?').get(scopeId);
10138
+ const children = rec?.tenant_id === tenantId ? this.childScopesOf(tenantId, scopeId, ['provisioning', 'active', 'suspended', 'archived']) : [];
10139
+ for (const child of children)
10140
+ assertReapable(tenantId, child, opts);
10141
+ assertReapable(tenantId, scopeId, opts);
10142
+ // A child's audit row names its parent and no backup: the caller's `backupRef` is a copy of the
10143
+ // parent, and naming it on a child would say a copy of the child was taken.
10144
+ for (const child of children)
10145
+ await reapOne(actor, tenantId, child, { force: opts?.force, withParent: scopeId });
10146
+ await reapOne(actor, tenantId, scopeId, opts);
9703
10147
  },
9704
10148
  // -- subject erasure (#37) ----------------------------------------------
9705
10149
  sealSubjectPayloads: async (actor, tenantId, scopeId, items) => {
@@ -9743,7 +10187,7 @@ export class SqliteScopeHost {
9743
10187
  await this.applyPendingMigrations(rt);
9744
10188
  // One read transaction on the scope actor, so the page is consistent and no invoke's open
9745
10189
  // transaction is read half-written.
9746
- const read = await rt.actor.turn(() => db.transaction(() => readSubjectPage({ sql: spineSql(db), plans: this.erasurePlans, subjectId, ...(page ? { page } : {}) }))());
10190
+ const read = await rt.actor.turn(() => db.transaction(() => readSubjectPage({ sql: spineSql(db), plans: this.erasurePlansOf(scopeId), subjectId, ...(page ? { page } : {}) }))());
9747
10191
  this.recordAccess(actor, 'readSubject', { tenantId, scopeId }, { subjectId }, read.events.length + read.records.reduce((n, r) => n + r.rows.length, 0));
9748
10192
  return read;
9749
10193
  },
@@ -9797,11 +10241,12 @@ export class SqliteScopeHost {
9797
10241
  // The module half first (#2068): the declared entities, then each hook, with the
9798
10242
  // search indexes over them under FTS5 secure-delete. The spine half follows in the same
9799
10243
  // transaction, so the order between them decides nothing but the reading order.
10244
+ // #2993 part 3: the modules this scope's type runs — another type's tables are not here.
9800
10245
  vertical: eraseSubjectFromModules({
9801
10246
  sql: spineSql(db),
9802
- plans: this.erasurePlans,
9803
- searchPlans: this.searchPlans.values(),
9804
- statefulTables: statefulTablesOf(this.statePlans),
10247
+ plans: this.erasurePlansOf(scopeId),
10248
+ searchPlans: this.derivedPlans(scopeId).search.values(),
10249
+ statefulTables: statefulTablesOf(this.derivedPlans(scopeId).state),
9805
10250
  subjectId,
9806
10251
  at,
9807
10252
  migrationSqlOf: (moduleId, version) => this.modules.get(moduleId)?.migrations.find((m) => m.version === version)?.sql,
@@ -9952,6 +10397,7 @@ export class SqliteScopeHost {
9952
10397
  '_substrat_membership_fences', // #1184: the latest removal, per principal
9953
10398
  '_substrat_peer_switches', // #2029: the peer switch's record, per scope
9954
10399
  'peer_bindings', // #1720: a tenant's explicit caller-to-target choices
10400
+ 'app_environments', // D-83: the names over the tenant's pinned previews
9955
10401
  '_substrat_switch_owed', // #2045: subjects owed a re-assert, per scope
9956
10402
  '_substrat_findings', // #1748: the tenant's findings
9957
10403
  '_substrat_finding_rules', // #1748: the tenant's suppress rules
@@ -11526,6 +11972,16 @@ export class SqliteScopeHost {
11526
11972
  this.ensureColumn(this.directory, 'scopes', 'erasure_epoch', 'erasure_epoch INTEGER');
11527
11973
  this.ensureColumn(this.directory, 'scopes', 'reap_claimed_at', 'reap_claimed_at TEXT');
11528
11974
  this.ensureColumn(this.directory, 'scopes', 'stores_fenced_at', 'stores_fenced_at TEXT');
11975
+ // #2993: null on every existing row, which reads as 'home', the one type a scope had before.
11976
+ this.ensureColumn(this.directory, 'scopes', 'scope_type', 'scope_type TEXT');
11977
+ // #3530 step 4: an environment's own serving script, NULL on every row (no script of its own).
11978
+ // Written out, not looped over the kernel's list: lint:spine-ddl reads each call.
11979
+ this.ensureColumn(this.directory, 'app_environments', 'serving_ref', 'serving_ref TEXT');
11980
+ this.ensureColumn(this.directory, 'app_environments', 'serving_version_id', 'serving_version_id TEXT');
11981
+ this.ensureColumn(this.directory, 'app_environments', 'serving_do_classes', 'serving_do_classes TEXT');
11982
+ this.ensureColumn(this.directory, 'app_environments', 'serving_migration_tag', 'serving_migration_tag TEXT');
11983
+ this.ensureColumn(this.directory, 'app_environments', 'serve_claim', 'serve_claim TEXT');
11984
+ this.ensureColumn(this.directory, 'app_environments', 'serve_claimed_until', 'serve_claimed_until TEXT');
11529
11985
  // §4.8's grace-window timestamp on tenants (mirrors scopes' archived_at).
11530
11986
  this.ensureColumn(this.directory, 'tenants', 'deleting_at', 'deleting_at TEXT');
11531
11987
  this.ensureColumn(this.directory, 'tenants', 'provisioned_by_tenant', 'provisioned_by_tenant TEXT REFERENCES tenants(tenant_id)');
@@ -11560,6 +12016,8 @@ export class SqliteScopeHost {
11560
12016
  this.ensureColumn(this.directory, 'verticals', 'serving_version_id', 'serving_version_id TEXT');
11561
12017
  this.ensureColumn(this.directory, 'verticals', 'serving_do_classes', 'serving_do_classes TEXT');
11562
12018
  this.ensureColumn(this.directory, 'verticals', 'serving_migration_tag', 'serving_migration_tag TEXT');
12019
+ // K-65 (#3539 part 2): the earlier majors still served beside the current one.
12020
+ this.ensureColumn(this.directory, 'verticals', 'earlier_majors', 'earlier_majors TEXT');
11563
12021
  this.ensureColumn(this.directory, 'vertical_versions', 'manifest_json', 'manifest_json TEXT');
11564
12022
  // Push provenance (git CI vs a terminal) — null for a pre-tracking push.
11565
12023
  this.ensureColumn(this.directory, 'vertical_versions', 'origin_json', 'origin_json TEXT');
@@ -11937,8 +12395,8 @@ export class SqliteScopeHost {
11937
12395
  sql: tracedSql(guardSecrets(guardSqlLimits(scopedSql(rt.db, true, statefulTablesOf(statePlans),
11938
12396
  // #119 / #2090: after runtime DDL, inside this operation's transaction, what the kernel
11939
12397
  // derived onto any table is repaired — and a lost state column fails the operation.
11940
- derivesAnything(this.derivedPlans())
11941
- ? () => afterRuntimeDdl(spineSql(rt.db), (ddl) => execSqlStatements(rt.db, ddl), this.derivedPlans())
12398
+ derivesAnything(this.derivedPlans(rt.scopeId))
12399
+ ? () => afterRuntimeDdl(spineSql(rt.db), (ddl) => execSqlStatements(rt.db, ddl), this.derivedPlans(rt.scopeId))
11942
12400
  : undefined)), minted), trace, (text) => redactSecretText(text, minted), (value) => redactSecrets(value, minted)),
11943
12401
  now: () => at,
11944
12402
  // #1746/#1747: the host stamps who and where; module code supplies only the template
@@ -12113,6 +12571,21 @@ export class SqliteScopeHost {
12113
12571
  },
12114
12572
  atomic: createAtomic(runSub, { passed, signals }),
12115
12573
  noteTransition: noteTransitionInto(signals),
12574
+ // #3540: the schedule named is due no later than `at`, written in this operation's transaction.
12575
+ scheduleDue: (operation, due) => noteScheduleDue(spineSql(rt.db), this.dueSchedules, operation, due),
12576
+ // #2996 (K-64): the proof a store call needs, written once in the kernel. The declared key is
12577
+ // checked as the caller (a consumer's system actor is refused: its checks allow everything).
12578
+ storeProof: (binding, operation) => mintStoreProof({
12579
+ sql: spineSql(rt.db),
12580
+ subject,
12581
+ consumer: Boolean(overrideActor),
12582
+ // The mint's own instant, so the proof's minute starts when it is minted.
12583
+ now: this.clock(),
12584
+ check: runCheck,
12585
+ assertWrites: (verb) => assertImpersonationWrites(impersonation, verb),
12586
+ minted,
12587
+ keyOf: (b, o) => storeOperationKeyOf(this.permissions?.stores, b, o),
12588
+ }, binding, operation),
12116
12589
  // #1672: mint / revoke / list, written once in the kernel. The raw spine seam (this
12117
12590
  // is the kernel's own write to `_substrat_capabilities`), the operation's OWN check —
12118
12591
  // the predicate `grant` shares — and `ctx.emit` for the minted/revoked events. A
@@ -12222,8 +12695,63 @@ export class SqliteScopeHost {
12222
12695
  return ctxRef;
12223
12696
  }
12224
12697
  /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
12225
- derivedPlans() {
12226
- return { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
12698
+ derivedPlans(scopeId) {
12699
+ const all = { state: this.statePlans, lists: this.listPlans, search: this.searchPlans };
12700
+ if (!this.scopeTypePlan.declared || scopeId === undefined)
12701
+ return all;
12702
+ // #2993: only what this scope's type runs was derived onto its tables.
12703
+ const own = (plans) => new Map([...plans].filter(([, plan]) => this.runsOn(scopeId, plan.moduleId)));
12704
+ return { state: own(all.state), lists: own(all.lists), search: own(all.search) };
12705
+ }
12706
+ /**
12707
+ * #2993: the declared type of a provisioned scope, from its directory row. `home` for a host that
12708
+ * declares no types, a row from before types, and a scope not provisioned yet (not cached, so its
12709
+ * provision decides). Cached once read, since a type never changes.
12710
+ */
12711
+ /** #2995: the ids of `parentScopeId`'s children in `tenantId` whose status is one of `statuses`, oldest first. */
12712
+ childScopesOf(tenantId, parentScopeId, statuses) {
12713
+ const rows = this.directory
12714
+ .prepare(`SELECT scope_id FROM scopes WHERE tenant_id = ? AND parent_scope_id = ? AND status IN (${statuses.map(() => '?').join(', ')})
12715
+ ORDER BY scope_id`)
12716
+ .all(tenantId, parentScopeId, ...statuses);
12717
+ return rows.map((r) => r.scope_id);
12718
+ }
12719
+ scopeTypeOf(scopeId) {
12720
+ if (!this.scopeTypePlan.declared)
12721
+ return HOME_SCOPE_TYPE;
12722
+ const cached = this.scopeTypeCache.get(scopeId);
12723
+ if (cached !== undefined)
12724
+ return cached;
12725
+ const row = this.directory.prepare('SELECT scope_type FROM scopes WHERE scope_id = ?').get(scopeId);
12726
+ if (!row)
12727
+ return HOME_SCOPE_TYPE;
12728
+ const type = row.scope_type ?? HOME_SCOPE_TYPE;
12729
+ this.scopeTypeCache.set(scopeId, type);
12730
+ return type;
12731
+ }
12732
+ /**
12733
+ * #2993 part 3: the type this directory records for `scopeId`, for a copy of it to take. Undefined
12734
+ * on a host with no declared types (a copy provisions as it always did) and for a scope this
12735
+ * directory does not hold (a dump from elsewhere carries no type, so the caller names one).
12736
+ */
12737
+ recordedScopeType(scopeId) {
12738
+ if (!this.scopeTypePlan.declared)
12739
+ return undefined;
12740
+ const row = this.directory.prepare('SELECT scope_type FROM scopes WHERE scope_id = ?').get(scopeId);
12741
+ return row ? (row.scope_type ?? HOME_SCOPE_TYPE) : undefined;
12742
+ }
12743
+ /** #2993: whether this scope's type runs the module. Every module runs on a host with no declared types. */
12744
+ runsOn(scopeId, moduleId) {
12745
+ return !this.scopeTypePlan.declared || scopeTypeRuns(this.scopeTypePlan, this.scopeTypeOf(scopeId), moduleId);
12746
+ }
12747
+ /** #2993 part 3: the erasure plans of the modules this scope's type runs, whose tables it holds. */
12748
+ erasurePlansOf(scopeId) {
12749
+ return this.scopeTypePlan.declared ? this.erasurePlans.filter((p) => this.runsOn(scopeId, p.moduleId)) : this.erasurePlans;
12750
+ }
12751
+ /** #2993: the registered modules this scope's type runs, in registration order. */
12752
+ modulesOf(scopeId) {
12753
+ const all = [...this.modules.values()];
12754
+ return this.scopeTypePlan.declared ? all.filter((m) => this.runsOn(scopeId, m.id)) : all;
12227
12755
  }
12228
12756
  /**
12229
12757
  * #2090: a pass with nothing pending, once per runtime — check and repair what the kernel
@@ -12237,7 +12765,7 @@ export class SqliteScopeHost {
12237
12765
  await rt.actor.enqueue(() => {
12238
12766
  rt.db.exec('BEGIN IMMEDIATE');
12239
12767
  try {
12240
- repairDerivedObjects(spineSql(rt.db), (ddl) => execSqlStatements(rt.db, ddl), this.derivedPlans(), {
12768
+ repairDerivedObjects(spineSql(rt.db), (ddl) => execSqlStatements(rt.db, ddl), this.derivedPlans(rt.scopeId), {
12241
12769
  after: 'an applied migration',
12242
12770
  });
12243
12771
  rt.db.exec('COMMIT');
@@ -12254,7 +12782,8 @@ export class SqliteScopeHost {
12254
12782
  rt.derivedRepaired = true;
12255
12783
  }
12256
12784
  async applyPendingMigrations(rt, plan) {
12257
- const { pending, diverged } = plan ?? (await planMigrations(this.modules.values(), rt.appliedMigrations));
12785
+ // #2993: a scope applies only its type's modules' migrations, so it carries no other type's tables.
12786
+ const { pending, diverged } = plan ?? (await planMigrations(this.modulesOf(rt.scopeId), rt.appliedMigrations));
12258
12787
  if (diverged) {
12259
12788
  this.recordMigrationState(rt, diverged);
12260
12789
  throw migrationFailedError(diverged.version, diverged.error);
@@ -12314,7 +12843,7 @@ export class SqliteScopeHost {
12314
12843
  // #2090: the state columns this migration must have left, and after the last of the
12315
12844
  // pass, the triggers and indexes a create-copy-rename rebuild dropped.
12316
12845
  const last = i === pending.length - 1;
12317
- afterMigration(spineSql(rt.db), (ddl) => execSqlStatements(rt.db, ddl), this.derivedPlans(), key, last);
12846
+ afterMigration(spineSql(rt.db), (ddl) => execSqlStatements(rt.db, ddl), this.derivedPlans(rt.scopeId), key, last);
12318
12847
  const after = rt.db.prepare('SELECT total_changes() AS n').get().n;
12319
12848
  // After the count: `rows_changed` is the migration's own, never the kernel's bookkeeping.
12320
12849
  recordOwnershipSteps(spineSql(rt.db), moduleId, steps, this.clock());
@@ -12582,6 +13111,9 @@ export class SqliteScopeHost {
12582
13111
  // #2096: a purge horizon's lap in progress, on a scope DB built before the column. NULL is the
12583
13112
  // start of a lap — the honest reading of every row already there. After the #1288 rebuild, as above.
12584
13113
  this.ensureColumn(db, '_substrat_schedule_state', 'purge_cursor', 'purge_cursor TEXT');
13114
+ // #3540: a due-by-event schedule's next date, on a scope DB built before the column. NULL is "not
13115
+ // yet run under the form", so its cadence decides: the honest reading of every row already there.
13116
+ this.ensureColumn(db, '_substrat_schedule_state', 'due_at', 'due_at TEXT');
12585
13117
  this.ensureColumn(db, '_substrat_job_runs', 'subject_id', 'subject_id TEXT');
12586
13118
  // #2034: the lease, on a scope DB built before it. NULL = nobody holds the run.
12587
13119
  this.ensureColumn(db, '_substrat_job_runs', 'lease_owner', 'lease_owner TEXT');