@substrat-run/adapter-sqlite 0.220.0 → 0.221.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,11 +2,11 @@ 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, pushedImport, moduleId, 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, purgeDueAt, 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, APP_ENVIRONMENTS_DDL, defineEnvironmentIn, environmentsOf, removeEnvironmentIn, 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
8
  // #2993: the modules a scope of each declared type runs, and the type a provision fixes.
9
- import { HOME_SCOPE_TYPE, operationNotInScopeType, provisionedScopeType, scopeTypePlanOf, scopeTypeRuns } from '@substrat-run/kernel';
9
+ import { childDoorRefusal, childScopeRefusal, directAccessRefusal, HOME_SCOPE_TYPE, operationNotInScopeType, provisionedParent, provisionedScopeType, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRoleRefusal, scopeTypeRuns, } from '@substrat-run/kernel';
10
10
  import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
11
11
  import { attributedView, delegatedRevokeSql, writeExplicitTupleIn, grantEntityShapeIn, shapeTopUpBatch, topUpEntityGrantShapes, settlePlatformRequestIn, } from '@substrat-run/kernel';
12
12
  import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove, } from '@substrat-run/kernel';
@@ -357,6 +357,9 @@ const KERNEL_DDL = `
357
357
  -- #3139: download links, a short-lived URL that lets a caller with no session read ONE file as
358
358
  -- the principal who minted it. Spine (kernel-written), shared with the DO adapter from the kernel.
359
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}
360
363
  -- #1686: where a copied scope's data came from, and the event id its own events start above.
361
364
  -- Shared with the other adapter from @substrat-run/kernel; the column comments are there.
362
365
  ${COPY_ORIGIN_DDL}
@@ -1000,6 +1003,11 @@ export class SqliteScopeHost {
1000
1003
  clock;
1001
1004
  /** #3540: whether purge schedules are due by their rows (`SqliteScopeHostOptions.purgeDue`). */
1002
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();
1003
1011
  versionId;
1004
1012
  /** K-74: the broker each scope hands off to, or null (off). */
1005
1013
  deliveryBroker;
@@ -2159,6 +2167,8 @@ export class SqliteScopeHost {
2159
2167
  peers: manifest.peers ?? [],
2160
2168
  purgeOnlyKeys: purgeOnlyKeysOf(manifest.schedules ?? []),
2161
2169
  });
2170
+ for (const [operation, schedule] of dueByEventSchedulesOf(manifest.schedules))
2171
+ this.dueSchedules.set(operation, schedule);
2162
2172
  noteReservedKeys(this.reservedKeys, manifest);
2163
2173
  noteDeclaredKeys(this.declaredKeys, manifest);
2164
2174
  if (erasure)
@@ -2285,10 +2295,35 @@ export class SqliteScopeHost {
2285
2295
  // Idempotency is on the scope_id (§3.3: provisioning is idempotent and
2286
2296
  // journaled — safe to re-run), so an existing scope short-circuits before the
2287
2297
  // slug check: re-provisioning does not collide with itself.
2288
- const existingRow = this.directory.prepare('SELECT scope_type FROM scopes WHERE scope_id = ?').get(input.scopeId);
2298
+ const existingRow = this.directory.prepare('SELECT scope_type, parent_scope_id FROM scopes WHERE scope_id = ?').get(input.scopeId);
2289
2299
  const existing = existingRow !== undefined;
2290
2300
  // #2993: a declared type, and the one recorded if the scope exists. Refused before anything is written.
2291
- const scopeType = provisionedScopeType(this.scopeTypePlan, input.scopeType, existingRow?.scope_type, input.scopeId);
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
+ }
2292
2327
  if (!existing) {
2293
2328
  // The `scopes_tenant_slug` UNIQUE index makes this fail closed either way;
2294
2329
  // checking first is what turns a SQLITE_CONSTRAINT into a sentence naming
@@ -2317,9 +2352,9 @@ export class SqliteScopeHost {
2317
2352
  -- inheriting serving_ref would route it to the prod serving script instead
2318
2353
  -- (COALESCE(s.serving_ref, vv.deployment_ref)). A null slug matches no row,
2319
2354
  -- so the sub-select is NULL and routing falls through to the bound version.
2320
- VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2355
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'provisioning', ?, ?, ?,
2321
2356
  (SELECT serving_ref FROM verticals WHERE slug = ?), ?)`)
2322
- .run(input.scopeId, input.tenantId,
2357
+ .run(input.scopeId, input.tenantId, parentScopeId,
2323
2358
  // NULL for 'home', the reading every row from before scope types has, so a host that
2324
2359
  // declares no types writes exactly the row it always did.
2325
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());
@@ -2367,7 +2402,12 @@ export class SqliteScopeHost {
2367
2402
  if (!existing) {
2368
2403
  this.recordAdmin(actor, 'provisionScope', { tenantId: input.tenantId, scopeId: input.scopeId, vertical: record.vertical }, null,
2369
2404
  // #2993: a typed scope's audit row names its type; a home scope's reads as it always did.
2370
- scopeType === HOME_SCOPE_TYPE ? record : { ...record, scopeType });
2405
+ // #2995: a child's names its parent.
2406
+ {
2407
+ ...record,
2408
+ ...(scopeType === HOME_SCOPE_TYPE ? {} : { scopeType }),
2409
+ ...(parentScopeId === null ? {} : { parentScopeId }),
2410
+ });
2371
2411
  }
2372
2412
  }
2373
2413
  /**
@@ -3040,6 +3080,11 @@ export class SqliteScopeHost {
3040
3080
  * host, made at once, so its seats are the ones that scope holds now (K-55).
3041
3081
  */
3042
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
+ }
3043
3088
  this.refuseUnusableScopeStores(dump.stores, input.vertical ?? null);
3044
3089
  if (judge)
3045
3090
  this.refuseDumpRoles(input.tenantId, dump);
@@ -3060,8 +3105,12 @@ export class SqliteScopeHost {
3060
3105
  // is the dump, not whatever the local module set would have built. Provenance is
3061
3106
  // stamped from the dump unless the caller already set it (§3: a fork always
3062
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);
3063
3111
  await this.provisionScope(actor, {
3064
3112
  ...input,
3113
+ ...(copiedType === undefined ? {} : { scopeType: copiedType }),
3065
3114
  forkedFrom: input.forkedFrom ?? dump.scopeId,
3066
3115
  forkedAt: input.forkedAt ?? dump.capturedAt,
3067
3116
  });
@@ -3365,11 +3414,41 @@ export class SqliteScopeHost {
3365
3414
  ? Object.freeze({ ...parsedDelegation, via: peerCallerAt(this.peerDeclarations(), parsedDelegation.via) })
3366
3415
  : parsedDelegation;
3367
3416
  const row = this.directory
3368
- .prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
3417
+ .prepare('SELECT tenant_id, status, parent_scope_id FROM scopes WHERE scope_id = ?')
3369
3418
  .get(scopeId);
3370
3419
  if (!row || row.tenant_id !== tenantId) {
3371
3420
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
3372
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 };
3373
3452
  // Lifecycle gates (control-plane.md §4.1/§4.2), all the K-3 fail-closed path.
3374
3453
  // The tenant record is mandatory: every scope has a tenant with a status
3375
3454
  // (provisioning enforces it), so a missing one is corruption, not a legacy
@@ -3419,11 +3498,18 @@ export class SqliteScopeHost {
3419
3498
  throw substratError('not_found', `no scope store is bound for '${binding}'`);
3420
3499
  }
3421
3500
  await this.scopeStoreLifecycle.start();
3501
+ const rt = this.runtime(tenantId, scopeId);
3422
3502
  return {
3423
3503
  tenantId,
3424
3504
  scopeId,
3425
3505
  subjectKind: 'principal',
3426
- 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
+ }),
3427
3513
  };
3428
3514
  }
3429
3515
  /** The scope's vertical when it has one. No vertical means this host has no store to touch. */
@@ -3956,6 +4042,28 @@ export class SqliteScopeHost {
3956
4042
  return result;
3957
4043
  });
3958
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
+ }
3959
4067
  /**
3960
4068
  * A stored version's manifest, unaudited: the platform reading its own code metadata (#1705).
3961
4069
  * `undefined` when the registry has no such version (under `slug`, when one is named).
@@ -4284,6 +4392,8 @@ export class SqliteScopeHost {
4284
4392
  const rt = await this.openActiveScope(tenantId, scopeId);
4285
4393
  const subject = asPrincipal(principalId.parse(principal));
4286
4394
  return rt.actor.enqueue(() => {
4395
+ // #2993 part 3: a role of another scope type does not exist here.
4396
+ this.refuseRoleOutsideType(scopeId, roleKey);
4287
4397
  // #2430: the answer a person's door would give — a role carrying a reserved key is refused.
4288
4398
  this.refuseReservedRole(tenantId, roleKey, 'person');
4289
4399
  return this.assignmentBound(subject, tenantId, scopeId, roleKey);
@@ -4294,6 +4404,7 @@ export class SqliteScopeHost {
4294
4404
  const subject = asPrincipal(principalId.parse(caller));
4295
4405
  const target = principalId.parse(assignee);
4296
4406
  return rt.actor.turn(async () => {
4407
+ this.refuseRoleOutsideType(scopeId, roleKey); // #2993 part 3
4297
4408
  // #2430: read in the same serialized task as the bound and the grant.
4298
4409
  this.refuseReservedRole(tenantId, roleKey, 'person');
4299
4410
  const bound = await this.assignmentBound(subject, tenantId, scopeId, roleKey);
@@ -4313,6 +4424,7 @@ export class SqliteScopeHost {
4313
4424
  const answer = await rt.actor.turn(() => {
4314
4425
  // #2430: the role moved TO is conferred by a person; the one moved from is only taken back.
4315
4426
  // Read in the same serialized task as the bound and the write.
4427
+ this.refuseRoleOutsideType(scopeId, to); // #2993 part 3
4316
4428
  this.refuseReservedRole(tenantId, to, 'person');
4317
4429
  return changeScopeRole(switchSqlOf(rt.db), scopeId, target, from, to, this.clock(), this.roleBound(caller, tenantId, scopeId), (run) => rt.db.transaction(run)());
4318
4430
  });
@@ -4465,6 +4577,16 @@ export class SqliteScopeHost {
4465
4577
  if (refusal)
4466
4578
  throw substratError('forbidden', refusal);
4467
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
+ }
4468
4590
  /**
4469
4591
  * #2447: refuse defining `role` for `tenantId` (`reservedRoleDefinitionRefusal`): against the keys
4470
4592
  * the modules registered or listed here reserve and declare, and the tenant's other roles.
@@ -4816,7 +4938,7 @@ export class SqliteScopeHost {
4816
4938
  const switched = systemScheduleState(switchSqlOf(rt.db), moduleId, nowIso);
4817
4939
  const lastRuns = new Map();
4818
4940
  if (switched !== 'on')
4819
- return { state: switched, lastRuns, purgeDue: new Map() };
4941
+ return { state: switched, lastRuns, purgeDue: new Map(), eventDue: new Map() };
4820
4942
  const read = rt.db.prepare(`SELECT last_run_at FROM _substrat_schedule_state
4821
4943
  WHERE kind = 'schedule' AND schedule_op = ?`);
4822
4944
  for (const schedule of mod.schedules) {
@@ -4833,7 +4955,20 @@ export class SqliteScopeHost {
4833
4955
  purgeDue.set(schedule.operation, purgeDueAt(spineSql(rt.db), this.statePlans, [purgeDueScheduleOf(schedule)], Date.parse(nowIso)));
4834
4956
  }
4835
4957
  }
4836
- return { state: switched, lastRuns, purgeDue };
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 };
4837
4972
  });
4838
4973
  const state = gate.state;
4839
4974
  if (state === 'ungranted')
@@ -4870,14 +5005,24 @@ export class SqliteScopeHost {
4870
5005
  },
4871
5006
  };
4872
5007
  for (const schedule of mod.schedules) {
4873
- // #3540: the scope's alarm asks for its purges only (the Durable Object's `purgeAlarm`).
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`).
4874
5010
  if (tick?.purgeAlarm && !schedule.purge)
4875
5011
  continue;
5012
+ if (tick?.dueAlarm && !schedule.purge && !gate.eventDue.has(schedule.operation))
5013
+ continue;
4876
5014
  const lastRunAt = gate.lastRuns.get(schedule.operation) ?? null;
4877
5015
  const lastRun = lastRunAt ? Date.parse(lastRunAt) : null;
4878
5016
  // #3540: a purge due by event is due when its earliest row is (null: nothing binned is ever due),
4879
- // and its lateness is measured from that row's date rather than from the cadence.
4880
- const byRows = schedule.purge && this.purgeDueByEvent ? (gate.purgeDue.get(schedule.operation) ?? null) : undefined;
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;
4881
5026
  const dueAt = byRows !== undefined ? (byRows ?? Infinity) : lastRun === null ? -Infinity : lastRun + schedule.cadence.everyMinutes * 60_000;
4882
5027
  if (now < dueAt) {
4883
5028
  report.skipped += 1;
@@ -4985,16 +5130,32 @@ export class SqliteScopeHost {
4985
5130
  * harness that wants the hosted shape sleeps until this instant and runs the pass.
4986
5131
  */
4987
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) {
4988
5144
  if (!this.purgeDueByEvent)
4989
5145
  return null;
4990
5146
  if (this.scopeWorkRefusal(tenantId, scopeId))
4991
5147
  return null;
4992
5148
  const schedules = [...this.modules.values()].flatMap((m) => m.schedules.filter((s) => s.purge).map(purgeDueScheduleOf));
4993
- if (schedules.length === 0)
5149
+ const due = withSchedules ? [...this.dueSchedules.values()] : [];
5150
+ if (schedules.length === 0 && due.length === 0)
4994
5151
  return null;
4995
5152
  const rt = this.runtime(tenantId, scopeId);
4996
5153
  await this.applyPendingMigrations(rt);
4997
- const at = await rt.actor.turn(() => purgeDueAt(spineSql(rt.db), this.statePlans, schedules, Date.parse(this.clock())));
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
+ });
4998
5159
  return at === null ? null : new Date(at).toISOString();
4999
5160
  }
5000
5161
  /**
@@ -5356,6 +5517,11 @@ export class SqliteScopeHost {
5356
5517
  // here, before the guards and the handler — the declared key first, so a caller
5357
5518
  // without it meets the same `forbidden` an active entity gives (`entity-trash.ts`).
5358
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);
5359
5525
  // Manifest guards (K-17): pre-conditions, inside the operation's own
5360
5526
  // transaction, before the handler. A throw here blocks the operation
5361
5527
  // and rolls back exactly like a handler throw — fail closed.
@@ -7001,6 +7167,8 @@ export class SqliteScopeHost {
7001
7167
  ...(r.serving_ref ? { servingRef: r.serving_ref } : {}),
7002
7168
  archivedAt: r.archived_at ?? null,
7003
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 } : {}),
7004
7172
  createdAt: r.created_at,
7005
7173
  });
7006
7174
  // The directory rows `listScopes` and `listScopesReadable` map, filtered and paged alike.
@@ -7061,7 +7229,7 @@ export class SqliteScopeHost {
7061
7229
  // describes what the transition DID, not the state it left.
7062
7230
  afterExtra) => {
7063
7231
  const row = this.directory
7064
- .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 = ?')
7065
7233
  .get(scopeId);
7066
7234
  if (!row || row.tenant_id !== tenantId) {
7067
7235
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
@@ -7069,6 +7237,14 @@ export class SqliteScopeHost {
7069
7237
  if (to === 'active' && row.stores_fenced_at !== null) {
7070
7238
  throw substratError('conflict', storesFencedRefusal(scopeId));
7071
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
+ }
7072
7248
  if (!from.includes(row.status)) {
7073
7249
  throw substratError('conflict', `illegal scope transition for ${action}: ${row.status} → ${to} ` +
7074
7250
  `(allowed from: ${from.join('|')})`);
@@ -7109,6 +7285,57 @@ export class SqliteScopeHost {
7109
7285
  this.recordAdmin(actor, action, { tenantId, scopeId, vertical: row.vertical }, { status: row.status }, { status: to, ...afterExtra });
7110
7286
  })();
7111
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
+ };
7112
7339
  const writeTenantTuple = (tenantId, subject, relation, object, expiresAt) => this.directory
7113
7340
  .prepare(`INSERT OR REPLACE INTO _substrat_tenant_tuples
7114
7341
  (tenant_id, subject, relation, object, expires_at)
@@ -7524,6 +7751,10 @@ export class SqliteScopeHost {
7524
7751
  // Before the write opens a scope's file; synchronous with a tenant node's unit, so no
7525
7752
  // definition lands between the two.
7526
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);
7527
7758
  await auditedOnNode(assignment.node, () => {
7528
7759
  if (scopeId)
7529
7760
  writeScopeTuple(assignment.node, subject, `role:${assignment.roleKey}`, `scope:${scopeId}`);
@@ -8034,6 +8265,20 @@ export class SqliteScopeHost {
8034
8265
  }
8035
8266
  return { removed: out.removed };
8036
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
+ })(),
8037
8282
  setPeerBinding: async (_actor, tenantId, callerScopeId, vertical, targetScopeId) => this.directory.transaction(() => {
8038
8283
  const caller = this.directory.prepare('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?').get(callerScopeId);
8039
8284
  if (!caller || caller.tenant_id !== tenantId || caller.status !== 'active' || !isPrimaryScopeRow(caller)) {
@@ -8075,7 +8320,9 @@ export class SqliteScopeHost {
8075
8320
  const r = this.directory
8076
8321
  .prepare(`SELECT h.tenant_id, h.scope_id, h.vertical_slug, h.surface, h.region,
8077
8322
  COALESCE(s.serving_ref, vv.deployment_ref) AS deployment_ref,
8078
- 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
8079
8326
  THEN json_extract(sv.manifest_json, '$.outbound')
8080
8327
  ELSE json_extract(vv.manifest_json, '$.outbound') END AS outbound_json,
8081
8328
  s.kind, s.forked_from,
@@ -8094,6 +8341,7 @@ export class SqliteScopeHost {
8094
8341
  LEFT JOIN verticals vr ON vr.slug = s.vertical
8095
8342
  -- K-65 (#3539 part 2): the version the scope's script runs, an earlier major's included.
8096
8343
  LEFT JOIN vertical_versions sv ON sv.id = ${SCRIPT_SERVING_VERSION_SQL}
8344
+ ${ENVIRONMENT_SCRIPT_JOIN_SQL}
8097
8345
  WHERE h.hostname = ? AND h.status = 'active'
8098
8346
  AND s.status = 'active' AND t.status = 'active'`)
8099
8347
  .get(hostname);
@@ -8455,6 +8703,9 @@ export class SqliteScopeHost {
8455
8703
  : null;
8456
8704
  if (breakingWithinMajor && owning?.listed)
8457
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));
8458
8709
  // #2333: the acknowledgements answer the review they were given against, or none at all.
8459
8710
  const reviewed = (v) => ({
8460
8711
  ...v,
@@ -8868,6 +9119,11 @@ export class SqliteScopeHost {
8868
9119
  if (supersede && (!expected || expected.ref !== r.serving_ref || expected.versionId !== r.serving_version_id)) {
8869
9120
  throw servingRaceRefusal(verticalSlug);
8870
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
+ }
8871
9127
  // #2178: every install on the serving script runs the new version from this moment. A new
8872
9128
  // major's first serve moves nobody onto its script: the installs stay on the earlier one.
8873
9129
  if (!supersede)
@@ -9861,54 +10117,33 @@ export class SqliteScopeHost {
9861
10117
  // Also from `provisioning`: a scope whose provisioning never completed (a failed
9862
10118
  // create) must be abandonable, or its slug is stranded forever (it can't reach a
9863
10119
  // terminal state that frees the name).
9864
- 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
+ })(),
9865
10130
  unarchiveScope: async (actor, tenantId, scopeId) => transitionScope(actor, 'unarchiveScope', tenantId, scopeId, ['archived'], 'active'),
9866
10131
  reapScope: async (actor, tenantId, scopeId, opts) => {
9867
- // Reap an ARCHIVED scope's storage while keeping its directory row as a tombstone
9868
- // (§4.4). Only `archived` may be reaped — an illegal source fails closed. The
9869
- // STORAGE goes before the status flip (the ordering deleteSnapshot keeps): a crash
9870
- // between leaves an `archived` row over an emptied file and re-running converges,
9871
- // whereas flipping first would strand a live file under a `reaped` row reap never
9872
- // revisits. Hostnames were released at archive and the row survives, so — unlike
9873
- // deleteSnapshot — neither is touched here.
9874
- const rec = this.directory
9875
- .prepare('SELECT tenant_id, status FROM scopes WHERE scope_id = ?')
9876
- .get(scopeId);
9877
- if (!rec || rec.tenant_id !== tenantId) {
9878
- throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
9879
- }
9880
- if (rec.status !== 'archived') {
9881
- throw substratError('conflict', `scope ${scopeId} is ${rec.status}, not archived — only an archived scope may be reaped`);
9882
- }
9883
- // A serving scope always holds ≥1 bound hostname; a truly-dead one has been
9884
- // unbound. The dashboard delete path unbinds AT archive, but a bare console
9885
- // `archiveScope` does not — so reap cannot ASSUME the release, it must verify it.
9886
- // Refuse (fail closed) while any name still resolves here: unbinding first is a
9887
- // visible, reversible step, and it is the wall that stops the irreversible wipe
9888
- // from ever landing on an app that is still online (§4.4). `force` is the
9889
- // deliberate-teardown bypass (tenant reap / retention sweep), where every name is
9890
- // being released anyway; the interactive per-scope reap never sets it.
9891
- const bound = opts?.force
9892
- ? undefined
9893
- : this.directory
9894
- .prepare('SELECT hostname FROM hostnames WHERE scope_id = ? LIMIT 1')
9895
- .get(scopeId);
9896
- if (bound) {
9897
- throw substratError('conflict', `scope ${scopeId} still resolves hostname '${bound.hostname}' — ` +
9898
- `unbind it before reaping (reap wipes storage and cannot be undone)`);
9899
- }
9900
- // The reader goes with the writer (#1624): an open handle on a removed file keeps
9901
- // reading the unlinked bytes, which is the reaped data answering as if it were live.
9902
- const rt = this.scopes.get(`${tenantId}/${scopeId}`);
9903
- if (rt)
9904
- this.closeRuntime(rt);
9905
- await this.wipeScopeStores(tenantId, scopeId);
9906
- rmSync(join(this.dir, `${tenantId}__${scopeId}.sqlite`), { force: true });
9907
- // The recoverable copy the caller stored first (#493), named in the audit entry so
9908
- // the trail answers "was there a backup" without correlating two timestamps.
9909
- await transitionScope(actor, 'reapScope', tenantId, scopeId, ['archived'], 'reaped', {
9910
- backupRef: opts?.backupRef ?? null,
9911
- });
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);
9912
10147
  },
9913
10148
  // -- subject erasure (#37) ----------------------------------------------
9914
10149
  sealSubjectPayloads: async (actor, tenantId, scopeId, items) => {
@@ -9952,7 +10187,7 @@ export class SqliteScopeHost {
9952
10187
  await this.applyPendingMigrations(rt);
9953
10188
  // One read transaction on the scope actor, so the page is consistent and no invoke's open
9954
10189
  // transaction is read half-written.
9955
- 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 } : {}) }))());
9956
10191
  this.recordAccess(actor, 'readSubject', { tenantId, scopeId }, { subjectId }, read.events.length + read.records.reduce((n, r) => n + r.rows.length, 0));
9957
10192
  return read;
9958
10193
  },
@@ -10006,11 +10241,12 @@ export class SqliteScopeHost {
10006
10241
  // The module half first (#2068): the declared entities, then each hook, with the
10007
10242
  // search indexes over them under FTS5 secure-delete. The spine half follows in the same
10008
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.
10009
10245
  vertical: eraseSubjectFromModules({
10010
10246
  sql: spineSql(db),
10011
- plans: this.erasurePlans,
10012
- searchPlans: this.searchPlans.values(),
10013
- statefulTables: statefulTablesOf(this.statePlans),
10247
+ plans: this.erasurePlansOf(scopeId),
10248
+ searchPlans: this.derivedPlans(scopeId).search.values(),
10249
+ statefulTables: statefulTablesOf(this.derivedPlans(scopeId).state),
10014
10250
  subjectId,
10015
10251
  at,
10016
10252
  migrationSqlOf: (moduleId, version) => this.modules.get(moduleId)?.migrations.find((m) => m.version === version)?.sql,
@@ -11738,6 +11974,14 @@ export class SqliteScopeHost {
11738
11974
  this.ensureColumn(this.directory, 'scopes', 'stores_fenced_at', 'stores_fenced_at TEXT');
11739
11975
  // #2993: null on every existing row, which reads as 'home', the one type a scope had before.
11740
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');
11741
11985
  // §4.8's grace-window timestamp on tenants (mirrors scopes' archived_at).
11742
11986
  this.ensureColumn(this.directory, 'tenants', 'deleting_at', 'deleting_at TEXT');
11743
11987
  this.ensureColumn(this.directory, 'tenants', 'provisioned_by_tenant', 'provisioned_by_tenant TEXT REFERENCES tenants(tenant_id)');
@@ -12327,6 +12571,21 @@ export class SqliteScopeHost {
12327
12571
  },
12328
12572
  atomic: createAtomic(runSub, { passed, signals }),
12329
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),
12330
12589
  // #1672: mint / revoke / list, written once in the kernel. The raw spine seam (this
12331
12590
  // is the kernel's own write to `_substrat_capabilities`), the operation's OWN check —
12332
12591
  // the predicate `grant` shares — and `ctx.emit` for the minted/revoked events. A
@@ -12449,6 +12708,14 @@ export class SqliteScopeHost {
12449
12708
  * declares no types, a row from before types, and a scope not provisioned yet (not cached, so its
12450
12709
  * provision decides). Cached once read, since a type never changes.
12451
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
+ }
12452
12719
  scopeTypeOf(scopeId) {
12453
12720
  if (!this.scopeTypePlan.declared)
12454
12721
  return HOME_SCOPE_TYPE;
@@ -12462,10 +12729,25 @@ export class SqliteScopeHost {
12462
12729
  this.scopeTypeCache.set(scopeId, type);
12463
12730
  return type;
12464
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
+ }
12465
12743
  /** #2993: whether this scope's type runs the module. Every module runs on a host with no declared types. */
12466
12744
  runsOn(scopeId, moduleId) {
12467
12745
  return !this.scopeTypePlan.declared || scopeTypeRuns(this.scopeTypePlan, this.scopeTypeOf(scopeId), moduleId);
12468
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
+ }
12469
12751
  /** #2993: the registered modules this scope's type runs, in registration order. */
12470
12752
  modulesOf(scopeId) {
12471
12753
  const all = [...this.modules.values()];
@@ -12829,6 +13111,9 @@ export class SqliteScopeHost {
12829
13111
  // #2096: a purge horizon's lap in progress, on a scope DB built before the column. NULL is the
12830
13112
  // start of a lap — the honest reading of every row already there. After the #1288 rebuild, as above.
12831
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');
12832
13117
  this.ensureColumn(db, '_substrat_job_runs', 'subject_id', 'subject_id TEXT');
12833
13118
  // #2034: the lease, on a scope DB built before it. NULL = nobody holds the run.
12834
13119
  this.ensureColumn(db, '_substrat_job_runs', 'lease_owner', 'lease_owner TEXT');