@substrat-run/adapter-sqlite 0.221.0 → 0.222.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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, 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';
5
+ import { PRODUCTION_ENVIRONMENT, 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, environmentServeAcknowledgement, 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, homeParentOf, homeScopeIn, secondHomeRefusal, releaseEnvironmentServeIn, removeEnvironmentIn, setEnvironmentServingIn, setEnvironmentEffectsIn, connectionReachIn, deliveryEnvironmentIn, environmentOfScopeIn, SWITCH_OWED_DDL, DEPENDENT_ERASURES_DDL, DEPENDENT_ERASURE_DUE_SQL, DEPENDENT_ERASURE_HOLD_SQL, DEPENDENT_ERASURE_OWE_SQL, DEPENDENT_ERASURE_SETTLE_SQL, nextDependentErasureAt, 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 { childDoorRefusal, childScopeRefusal, directAccessRefusal, HOME_SCOPE_TYPE, operationNotInScopeType, provisionedParent, provisionedScopeType, scopeTypePlanOf, scopeTypePlanOfManifest, scopeTypeRoleRefusal, scopeTypeRuns, } from '@substrat-run/kernel';
9
+ import { childDoorRefusal, childScopeRefusal, directAccessRefusal, HOME_SCOPE_TYPE, operationNotInScopeType, parentlessScopeRefusal, 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';
@@ -16,12 +16,12 @@ import { advanceMarks, handoffQueries, messagesOf, senderDeliveryOf, } from '@su
16
16
  import { intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
17
17
  import { MARKUP_INSERT_SQL, MARKUP_SELECT_FOR_TENANT_SQL, MARKUP_SELECT_SQL, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
18
18
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
19
- import { breakingWithinMajorRefusal, earlierMajorsOf, releaseWithinMajorRefusal, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
19
+ import { breakingWithinMajorRefusal, earlierMajorReleaseTarget, earlierMajorsOf, releasedEarlierMajorJson, releaseWithinMajorRefusal, SCRIPT_SERVING_VERSION_SQL, supersededMajorsJson } from '@substrat-run/kernel';
20
20
  import { classify as classifyRelease } from '@substrat-run/model-view/bump';
21
21
  import { ADMIN_LOG_INDEXES_SQL, SETTLE_INTENT_SQL, SETTLE_OUTCOME_SQL, settleOutcomeParamsOf, readAuditedOperations, unknownOutcomeOf, } from '@substrat-run/kernel';
22
22
  import { INERT_SCOPE_REASON, isPrimaryScopeRow, normalizeUploadMediaType } from '@substrat-run/kernel';
23
23
  import { opsFailureReferenceWhere } from '@substrat-run/kernel';
24
- import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, scopeScriptCopyOf, } from '@substrat-run/kernel';
24
+ import { COPY_BACKFILL_SCOPE_SQL, COPY_BACKFILL_SQL, COPY_BACKFILL_SUPERSEDE_SQL, COPY_CLAIM_SQL, COPY_EXPIRED_SQL, COPY_EXPIRED_FOR_TENANT_SQL, COPY_MOVE_RENEW_SQL, copyMoveRenewParams, PENDING_COPY_KEEP_ALIVE_SQL, pendingCopyKeepAliveParams, copyBackfillParams, copyBackfillRefusal, SUBJECT_ERASURE_CLAIM_SQL, subjectErasureClaimParams, COPY_MOVE_CONFIRM_SQL, COPY_MOVE_LIVE_PREDICATE, SCOPE_COPY_LEASE_MS, SCOPE_SCRIPT_COPY_COLUMNS, copyMoveConfirmParams, copyMoveLiveParams, scopeScriptCopyOf, } from '@substrat-run/kernel';
25
25
  import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
26
26
  import { LEGACY_SCOPE_ROWS_BACKFILL, assertSpineTablesBuilt, capabilitiesForLoad, dumpRowsInsert, isSpineTable, loadDirectoryDump, repointScopeGrants, settleCopiedWork, emittedHere, spineColumnAdditions } from '@substrat-run/kernel';
27
27
  import { ScopeActor } from './actor.js';
@@ -1014,6 +1014,8 @@ export class SqliteScopeHost {
1014
1014
  brokerTelemetry;
1015
1015
  /** K-74: each scope's handoff marks, a cache of what its broker holds (`DeliveryBroker.marks`). */
1016
1016
  handoffMarks = new Map();
1017
+ /** #3639: the environment each scope last handed off to, so erasure reaches that broker after the rule moved. */
1018
+ handoffEnvironments = new Map();
1017
1019
  /** A5: `deliveryHandoff`, and each scope's mode with its window start (in memory, as the marks are). */
1018
1020
  deliveryHandoff;
1019
1021
  deliveryModes = new Map();
@@ -1613,6 +1615,8 @@ export class SqliteScopeHost {
1613
1615
  ${MEMBERSHIP_FENCES_DDL}
1614
1616
  ${PEER_SWITCHES_DDL}
1615
1617
  ${SWITCH_OWED_DDL}
1618
+ -- K-63 (#3624): erasures owed to a master's dependents, kept until each door answers.
1619
+ ${DEPENDENT_ERASURES_DDL}
1616
1620
  CREATE TABLE IF NOT EXISTS _substrat_admin_log (
1617
1621
  id TEXT PRIMARY KEY,
1618
1622
  actor TEXT NOT NULL,
@@ -2308,7 +2312,17 @@ export class SqliteScopeHost {
2308
2312
  // #2995: the parent link, fixed at the first provision. A new child is held to its parent's declared
2309
2313
  // children, tenant, app, state and depth before its row is written. No await separates the check from
2310
2314
  // 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);
2315
+ const namedParent = provisionedParent(input.parentScopeId, existing ? existingRow.parent_scope_id : undefined, input.scopeId);
2316
+ // #3625 (K-64): a new typed scope that names no parent is a child of its app's home scope, judged below as any
2317
+ // named parent is. On a host that declares its own types, as the Durable Object host does: a module-less
2318
+ // coordinator judging by a vertical's types names a link through provision-child, which tells the vertical.
2319
+ const parentScopeId = existing || namedParent !== null || !this.scopeTypePlan.declared
2320
+ ? namedParent
2321
+ : homeParentOf(switchSqlOf(this.directory), input.tenantId, { vertical: record.vertical, type: scopeType, forkedFrom: record.forkedFrom });
2322
+ // #2995 (the owner's word on #3604's fourth question): a new scope of a type other than home has a parent.
2323
+ const parentless = existing ? null : parentlessScopeRefusal(scopeType, parentScopeId, record.forkedFrom, input.scopeId);
2324
+ if (parentless)
2325
+ throw parentless;
2312
2326
  if (!existing && parentScopeId !== null) {
2313
2327
  const parent = this.directory
2314
2328
  .prepare('SELECT tenant_id, status, vertical, scope_type, parent_scope_id, forked_from FROM scopes WHERE scope_id = ?')
@@ -2338,6 +2352,19 @@ export class SqliteScopeHost {
2338
2352
  throw substratError('conflict', `scope slug '${record.slug}' already taken under tenant ${input.tenantId} ` +
2339
2353
  `by ${slugOwner.scope_id} (slugs are unique within a tenant)`);
2340
2354
  }
2355
+ // #3625 (K-64): one home scope per (tenant, app, environment). A second install of the app is
2356
+ // refused; a sibling, a copy, a preview and a child are not installs. No await separates this
2357
+ // read from the INSERT below.
2358
+ const secondHome = secondHomeRefusal(switchSqlOf(this.directory), input.tenantId, input.scopeId, {
2359
+ vertical: record.vertical,
2360
+ type: scopeType,
2361
+ parentScopeId,
2362
+ forkedFrom: record.forkedFrom,
2363
+ kind: record.kind,
2364
+ install: input.install,
2365
+ });
2366
+ if (secondHome)
2367
+ throw secondHome;
2341
2368
  this.directory
2342
2369
  .prepare(`INSERT INTO scopes
2343
2370
  (scope_id, tenant_id, parent_scope_id, scope_type, slug, kind, name, vertical,
@@ -4057,12 +4084,14 @@ export class SqliteScopeHost {
4057
4084
  }
4058
4085
  /**
4059
4086
  * #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.
4087
+ * a promote judges the incoming version's declared types against. K-65 (#3539): with `servingRef`,
4088
+ * only the scopes on that script, which is all a release into an earlier major reaches.
4061
4089
  */
4062
- scopeTypesHeldBy(vertical) {
4090
+ scopeTypesHeldBy(vertical, servingRef) {
4091
+ const onScript = servingRef === undefined ? '' : ' AND serving_ref = ?';
4063
4092
  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);
4093
+ .prepare(`SELECT DISTINCT scope_type FROM scopes WHERE vertical = ?${onScript} AND scope_type IS NOT NULL AND status <> 'reaped' ORDER BY scope_type`)
4094
+ .all(...(servingRef === undefined ? [vertical] : [vertical, servingRef])).map((r) => r.scope_type);
4066
4095
  }
4067
4096
  /**
4068
4097
  * A stored version's manifest, unaudited: the platform reading its own code metadata (#1705).
@@ -6363,13 +6392,19 @@ export class SqliteScopeHost {
6363
6392
  const mode = this.deliveryModes.get(key);
6364
6393
  if (this.deliveryHandoff === 'by-mode' && !mode)
6365
6394
  return;
6395
+ // #3639 (D-83): to the broker of the scope's environment, or to none: a preview or a fork, and an
6396
+ // environment nobody gave connections of its own, hand off nothing, as a hosted one is told `off`.
6397
+ const environment = deliveryEnvironmentIn(switchSqlOf(this.directory), rt.tenantId, rt.scopeId);
6398
+ if (environment === null)
6399
+ return;
6400
+ this.handoffEnvironments.set(key, environment);
6366
6401
  const options = mode
6367
6402
  ? { mode: mode.mode, ...(mode.startPending ? { start: { ...ids, after: mode.start } } : {}) }
6368
6403
  : {};
6369
6404
  /** #3474: the round now with the broker, so a throw reports what it tried. */
6370
6405
  let inFlight = null;
6371
6406
  try {
6372
- const broker = this.deliveryBroker(ids);
6407
+ const broker = this.deliveryBroker({ ...ids, environment });
6373
6408
  let marks = this.handoffMarks.get(key) ?? (await broker.marks(rt.tenantId, rt.scopeId));
6374
6409
  // A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
6375
6410
  for (let round = 0; round < 20; round++) {
@@ -6391,7 +6426,7 @@ export class SqliteScopeHost {
6391
6426
  delete options.start;
6392
6427
  }
6393
6428
  const next = advanceMarks(marks, sent, answer);
6394
- this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer));
6429
+ this.reportHandoffRound(rt, inFlight, handoffOutcome(sent, answer), environment);
6395
6430
  inFlight = null;
6396
6431
  // An answer that acknowledges nothing new: stop; the next commit or `retryHandoffs` tries again.
6397
6432
  if (next.event === marks.event && next.intent === marks.intent)
@@ -6403,19 +6438,33 @@ export class SqliteScopeHost {
6403
6438
  }
6404
6439
  catch (err) {
6405
6440
  if (inFlight)
6406
- this.reportHandoffRound(rt, inFlight, 'failed');
6441
+ this.reportHandoffRound(rt, inFlight, 'failed', environment);
6407
6442
  console.error('substrat: delivery handoff failed; the next commit retries it', err);
6408
6443
  }
6409
6444
  }
6445
+ /**
6446
+ * #3639: the broker a scope's messages went to: the environment the directory says the scope belongs
6447
+ * to (`environmentOfScopeIn`, which does not follow its effects, so it outlives a restart and an
6448
+ * environment taken back to none), else the one this host last handed off to, else production's (a
6449
+ * scope that never handed off holds nothing in any). Only with `deliveryBroker` given.
6450
+ */
6451
+ brokerOfScope(tenantId, scopeId) {
6452
+ const environment = environmentOfScopeIn(switchSqlOf(this.directory), tenantId, scopeId) ??
6453
+ this.handoffEnvironments.get(`${tenantId}/${scopeId}`) ??
6454
+ PRODUCTION_ENVIRONMENT;
6455
+ return this.deliveryBroker({ tenantId, scopeId, environment });
6456
+ }
6410
6457
  /** #3474: one point per handoff round, when `brokerTelemetry` is given. */
6411
- reportHandoffRound(rt, round, outcome) {
6458
+ reportHandoffRound(rt, round, outcome,
6459
+ /** #3639: the environment whose broker the round went to; production's names none. */
6460
+ environment) {
6412
6461
  const t = this.brokerTelemetry;
6413
6462
  if (!t)
6414
6463
  return;
6415
6464
  const ids = { tenantId: rt.tenantId, scopeId: rt.scopeId };
6416
6465
  // Telemetry never fails the handoff it follows: the harness's `appOf` may throw.
6417
6466
  try {
6418
- reportHandoff(t.sink, { ...ids, app: t.appOf(ids) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
6467
+ reportHandoff(t.sink, { ...ids, app: t.appOf(ids), ...(environment === PRODUCTION_ENVIRONMENT ? {} : { environment }) }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
6419
6468
  }
6420
6469
  catch (err) {
6421
6470
  console.error('substrat: delivery telemetry failed; the handoff continues', err);
@@ -7193,6 +7242,10 @@ export class SqliteScopeHost {
7193
7242
  where.push('vertical = ?');
7194
7243
  params.push(filter.vertical);
7195
7244
  }
7245
+ if (filter?.parentScopeId) {
7246
+ where.push('parent_scope_id = ?');
7247
+ params.push(filter.parentScopeId);
7248
+ }
7196
7249
  const tail = keysetTail(where, params, 'scope_id', filter);
7197
7250
  const sql = 'SELECT * FROM scopes' + (where.length ? ` WHERE ${where.join(' AND ')}` : '') + tail;
7198
7251
  return this.directory.prepare(sql).all(...params);
@@ -8245,6 +8298,12 @@ export class SqliteScopeHost {
8245
8298
  this.recordAccess(actor, 'peerBindings', { tenantId, scopeId: callerScopeId }, null, rows.length);
8246
8299
  return rows.map((r) => ({ tenantId, callerScopeId, vertical: r.vertical, targetScopeId: r.target_scope_id, invalidated: r.invalidated === 1 }));
8247
8300
  },
8301
+ // #3625 (K-64): the home scope of (tenant, app, environment). The rule is the kernel's (`home-scope.ts`).
8302
+ homeScopeOf: async (actor, tenantId, vertical, environment) => {
8303
+ const scopeId = homeScopeIn(switchSqlOf(this.directory), tenantId, vertical, environment);
8304
+ this.recordAccess(actor, 'homeScopeOf', { tenantId }, { vertical, environment: environment ?? 'prod' }, scopeId ? 1 : 0);
8305
+ return scopeId;
8306
+ },
8248
8307
  // D-83 (#3530 step 3): an app's environments. The rule is the kernel's (`app-environments.ts`).
8249
8308
  listEnvironments: async (actor, tenantId, vertical) => {
8250
8309
  const rows = environmentsOf(switchSqlOf(this.directory), tenantId, vertical);
@@ -8272,13 +8331,26 @@ export class SqliteScopeHost {
8272
8331
  releaseEnvironmentServe: async (_actor, input, claim) => {
8273
8332
  releaseEnvironmentServeIn(switchSqlOf(this.directory), input, claim);
8274
8333
  },
8275
- setEnvironmentServing: async (actor, input, next, expected, claim) => this.directory.transaction(() => {
8276
- const out = setEnvironmentServingIn(switchSqlOf(this.directory), input, next, expected, claim);
8334
+ setEnvironmentServing: async (actor, input, next, expected, claim, acknowledge) => this.directory.transaction(() => {
8335
+ // #3638: judged against what this environment serves, in the write that moves it.
8336
+ const ack = acknowledge === undefined ? undefined : environmentServeAcknowledgement.parse(acknowledge);
8337
+ const out = setEnvironmentServingIn(switchSqlOf(this.directory), input, next, expected, claim, ack);
8277
8338
  if (!out.moved) {
8278
8339
  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
8340
  }
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 });
8341
+ this.recordAdmin(actor, 'setEnvironmentServing', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, out.before ? { ref: out.before.ref, versionId: out.before.versionId } : null,
8342
+ // #3638: the acknowledgement is recorded with this environment's serve, as a promote's is with prod's.
8343
+ { vertical: input.vertical, scopeId: out.scopeId, ref: next.ref, versionId: next.versionId, ...(ack ? { acknowledged: ack } : {}) });
8344
+ })(),
8345
+ // #3530 step 6: an environment given connections of its own, and the rule every connection door asks.
8346
+ setEnvironmentEffects: async (actor, input, effects) => this.directory.transaction(() => {
8347
+ const out = setEnvironmentEffectsIn(switchSqlOf(this.directory), input, effects);
8348
+ if (out.changed) {
8349
+ this.recordAdmin(actor, 'setEnvironmentEffects', { tenantId: input.tenantId, scopeId: out.scopeId, vertical: input.vertical }, { effects: out.before }, { vertical: input.vertical, scopeId: out.scopeId, effects });
8350
+ }
8351
+ return { changed: out.changed, before: out.before };
8281
8352
  })(),
8353
+ connectionReach: async (_actor, tenantId, scopeId) => connectionReachIn(switchSqlOf(this.directory), tenantId, scopeId),
8282
8354
  setPeerBinding: async (_actor, tenantId, callerScopeId, vertical, targetScopeId) => this.directory.transaction(() => {
8283
8355
  const caller = this.directory.prepare('SELECT tenant_id, status, kind, forked_from FROM scopes WHERE scope_id = ?').get(callerScopeId);
8284
8356
  if (!caller || caller.tenant_id !== tenantId || caller.status !== 'active' || !isPrimaryScopeRow(caller)) {
@@ -8664,16 +8736,36 @@ export class SqliteScopeHost {
8664
8736
  if (incoming.admission !== 'admitted') {
8665
8737
  throw substratError('conflict', `version ${versionId} is ${incoming.admission}, not admitted — it cannot be promoted`);
8666
8738
  }
8667
- const current = this.directory
8668
- .prepare('SELECT version_id FROM vertical_channels WHERE vertical_slug = ? AND channel = ?')
8669
- .get(verticalSlug, channel);
8739
+ // K-65 (#3539): a release that names an earlier major goes to that major's own script, and
8740
+ // every gate below is judged against the version that script runs, in place of the channel's.
8741
+ const target = options?.earlierMajor === undefined
8742
+ ? null
8743
+ : (() => {
8744
+ if (channel !== 'prod')
8745
+ throw substratError('validation_failed', 'an earlier major is released on prod alone');
8746
+ const row = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
8747
+ .get(verticalSlug);
8748
+ return earlierMajorReleaseTarget({
8749
+ vertical: verticalSlug,
8750
+ earlierJson: row?.earlier_majors,
8751
+ major: options.earlierMajor,
8752
+ head: { version: incoming.version, deploymentRef: incoming.deploymentRef },
8753
+ servesMajors: options.servesMajors === true,
8754
+ });
8755
+ })();
8756
+ const current = target
8757
+ ? { version_id: target.versionId }
8758
+ : this.directory
8759
+ .prepare('SELECT version_id FROM vertical_channels WHERE vertical_slug = ? AND channel = ?')
8760
+ .get(verticalSlug, channel);
8670
8761
  const outgoing = current ? await readVersion(current.version_id) : undefined;
8671
8762
  const ack = promotionAcknowledgement.parse(acknowledge ?? {});
8672
8763
  // The owning tenant's live scopes a PRIVATE prod promote re-points — below for an embedded
8673
8764
  // vertical, after the in-place serve for a dispatch-backed one (#321) — read before
8674
- // anything moves so the #2178 gate can judge each one.
8765
+ // anything moves so the #2178 gate can judge each one. A release into an earlier major
8766
+ // re-points none: only the installs on that major's script run it.
8675
8767
  const owning = channel === 'prod' ? readVertical(verticalSlug) : undefined;
8676
- const owned = owning && owning.ownerTenant !== null && !owning.listed
8768
+ const owned = !target && owning && owning.ownerTenant !== null && !owning.listed
8677
8769
  ? this.directory
8678
8770
  .prepare(`SELECT * FROM scopes
8679
8771
  WHERE vertical = ? AND tenant_id = ? AND status = 'active' AND forked_from IS NULL AND kind != 'preview'`)
@@ -8683,7 +8775,9 @@ export class SqliteScopeHost {
8683
8775
  // moves something from: the channel's version, the version served in place (a prod promote
8684
8776
  // serves the incoming one next, and a failed serve leaves it behind the channel), and what each
8685
8777
  // re-pointed scope RUNS (`runningVersionOf`: on the serving script, the served version).
8686
- const served = channel === 'prod' ? this.servingPointerOfVertical(verticalSlug) : null;
8778
+ const served = target
8779
+ ? { ref: target.ref, versionId: target.versionId }
8780
+ : channel === 'prod' ? this.servingPointerOfVertical(verticalSlug) : null;
8687
8781
  // And what each scope it moves last reconciled (`PROVISIONED_VERSIONS_SQL`).
8688
8782
  this.assertNoStrandFrom([
8689
8783
  outgoing?.id,
@@ -8705,7 +8799,8 @@ export class SqliteScopeHost {
8705
8799
  throw breakingWithinMajorRefusal(breakingWithinMajor);
8706
8800
  // #2993 part 4: the incoming version declares every type the vertical's scopes hold. Ahead
8707
8801
  // of the acknowledgements, because none of them passes it.
8708
- assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug), this.manifestJsonOf(versionId, verticalSlug));
8802
+ // K-65 (#3539): a release into an earlier major reaches the scopes on its script alone.
8803
+ assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug, target?.ref), this.manifestJsonOf(versionId, verticalSlug));
8709
8804
  // #2333: the acknowledgements answer the review they were given against, or none at all.
8710
8805
  const reviewed = (v) => ({
8711
8806
  ...v,
@@ -8737,6 +8832,30 @@ export class SqliteScopeHost {
8737
8832
  throw substratError('precondition_failed', exportBreakRefusal(breaks));
8738
8833
  }
8739
8834
  }
8835
+ // K-65 (#3539): a release into an earlier major moves no channel. Its gates were judged against
8836
+ // the version that major's script runs, so its admin row, the acknowledgement's evidence, lands
8837
+ // only while the script still runs it, with the listing and the admission read in that unit as
8838
+ // a prod promote reads them. The caller then serves it on the script and records that.
8839
+ if (target) {
8840
+ const judged = this.directoryWriteAndAudit(() => {
8841
+ const now = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
8842
+ .get(verticalSlug);
8843
+ if (earlierMajorsOf(now?.earlier_majors).find((m) => m.major === target.major)?.versionId !== target.versionId)
8844
+ return false;
8845
+ const listed = readVertical(verticalSlug)?.listed;
8846
+ if (listed && options?.unlistedOnly)
8847
+ throw listedPromoteRefusal();
8848
+ if (listed && breakingWithinMajor)
8849
+ throw breakingWithinMajorRefusal(breakingWithinMajor);
8850
+ if (listed && target.versionId !== versionId && versionAdmission(versionId).admission_note === AUTO_ADMISSION_NOTE) {
8851
+ throw autoAdmittedProdRefusal(verticalSlug, versionId);
8852
+ }
8853
+ return true;
8854
+ }, () => this.recordAdmin(actor, 'promoteVersion', { tenantId: null, vertical: verticalSlug }, outgoing ? { versionId: outgoing.id, version: outgoing.version } : null, { channel, versionId, version: incoming.version, earlierMajor: target.major, acknowledged: ack }));
8855
+ if (!judged)
8856
+ throw promoteRaceRefusal(channel);
8857
+ return;
8858
+ }
8740
8859
  const promotedAt = new Date().toISOString();
8741
8860
  // #2333: a compare-and-set. Every gate above — the review binding, the digest checkpoints,
8742
8861
  // the export breaks — was judged against `outgoing`, across awaits another promote can run
@@ -8968,7 +9087,9 @@ export class SqliteScopeHost {
8968
9087
  claimExpiredScopeScriptCopies: async (_actor, input) => {
8969
9088
  const limit = assertRowLimit('limit', input.limit);
8970
9089
  return this.directory.transaction(() => {
8971
- const due = this.directory.prepare(COPY_EXPIRED_SQL).all(input.now, limit);
9090
+ const due = (input.tenantId !== undefined
9091
+ ? this.directory.prepare(COPY_EXPIRED_FOR_TENANT_SQL).all(input.now, input.tenantId, limit)
9092
+ : this.directory.prepare(COPY_EXPIRED_SQL).all(input.now, limit));
8972
9093
  const claimed = [];
8973
9094
  for (const r of due) {
8974
9095
  if (this.directory.prepare(COPY_CLAIM_SQL).run(input.owner, input.leaseUntil, r.tenant_id, r.scope_id, r.script_ref, r.move_id, input.now).changes === 0)
@@ -8981,7 +9102,7 @@ export class SqliteScopeHost {
8981
9102
  },
8982
9103
  markScopeStoresFenced: async (actor, tenantId, scopeId, opts) => {
8983
9104
  // No await between the read and the write, so an unarchive is before or after.
8984
- const scope = this.directory.prepare('SELECT status, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?')
9105
+ const scope = this.directory.prepare('SELECT status, archived_at, stores_fenced_at FROM scopes WHERE tenant_id = ? AND scope_id = ?')
8985
9106
  .get(tenantId, scopeId);
8986
9107
  if (!scope)
8987
9108
  throw substratError('not_found', `unknown scope for tenant: (${tenantId}, ${scopeId})`);
@@ -8990,8 +9111,17 @@ export class SqliteScopeHost {
8990
9111
  if (scope.status !== 'archived') {
8991
9112
  throw substratError('conflict', `scope ${scopeId} is ${scope.status}, not archived, so its stores are not fenced`);
8992
9113
  }
8993
- if (opts?.whileTenantDeleting && readTenant(tenantId)?.status !== 'deleting') {
8994
- throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
9114
+ if (opts?.archivedBy !== undefined && (scope.archived_at === null || scope.archived_at > opts.archivedBy)) {
9115
+ throw substratError('conflict', `scope ${scopeId} has not passed its archive retention`);
9116
+ }
9117
+ if (opts?.whileTenantDeleting || opts?.deletingBy !== undefined) {
9118
+ const tenant = readTenant(tenantId);
9119
+ if (tenant?.status !== 'deleting') {
9120
+ throw substratError('conflict', `tenant ${tenantId} is no longer deleting, so the stores of scope ${scopeId} are not fenced`);
9121
+ }
9122
+ if (opts?.deletingBy !== undefined && (tenant.deletingAt === null || tenant.deletingAt > opts.deletingBy)) {
9123
+ throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
9124
+ }
8995
9125
  }
8996
9126
  this.directoryWriteAndAudit(() => this.directory.prepare(`UPDATE scopes SET stores_fenced_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE tenant_id = ? AND scope_id = ?`).run(tenantId, scopeId).changes > 0, () => this.recordAdmin(actor, 'markScopeStoresFenced', { tenantId, scopeId }, { storesFencedAt: null }, { storesFenced: true }));
8997
9127
  },
@@ -9112,6 +9242,29 @@ export class SqliteScopeHost {
9112
9242
  .get(verticalSlug);
9113
9243
  if (!r)
9114
9244
  throw substratError('not_found', `unknown vertical '${verticalSlug}'`);
9245
+ // K-65 (#3539): a release served on an earlier major's own script moves that major's entry alone.
9246
+ if (opts?.earlierMajor !== undefined) {
9247
+ const major = opts.earlierMajor;
9248
+ if (supersede)
9249
+ throw substratError('validation_failed', 'a serve records a new major or a release into an earlier one, not both');
9250
+ const entry = earlierMajorsOf(r.earlier_majors).find((m) => m.major === major);
9251
+ if (!expected || !entry || entry.versionId !== expected.versionId)
9252
+ throw servingRaceRefusal(verticalSlug);
9253
+ // #2993 part 4 and #2178, as an in-place serve is judged, over the installs on that script.
9254
+ assertScopeTypesKept(verticalSlug, this.scopeTypesHeldBy(verticalSlug, entry.ref), this.manifestJsonOf(parsed.versionId, verticalSlug));
9255
+ this.assertNoStrandFrom([entry.versionId], parsed.versionId, this.provisionedVersionsOf(verticalSlug, { ref: entry.ref, versionId: entry.versionId }, null));
9256
+ let was = null;
9257
+ this.directoryWriteAndAudit(() => {
9258
+ const now = this.directory.prepare('SELECT earlier_majors FROM verticals WHERE slug = ?')
9259
+ .get(verticalSlug);
9260
+ const held = earlierMajorsOf(now?.earlier_majors).find((m) => m.major === major);
9261
+ was = held ? { ref: held.ref, versionId: held.versionId } : null;
9262
+ const earlier = releasedEarlierMajorJson({ vertical: verticalSlug, earlierJson: now?.earlier_majors, major, expected, next: parsed });
9263
+ this.directory.prepare('UPDATE verticals SET earlier_majors = ? WHERE slug = ?').run(earlier, verticalSlug);
9264
+ return true;
9265
+ }, () => this.recordAdmin(actor, 'setVerticalServing', { tenantId: null }, was, { vertical: verticalSlug, ref: parsed.ref, versionId: parsed.versionId, earlierMajor: major }));
9266
+ return;
9267
+ }
9115
9268
  // #2577: the caller's upload diffed its DO-class migration from `expected`'s class set and tag.
9116
9269
  if (expected !== undefined && !migratesFrom(r, expected))
9117
9270
  throw servingRaceRefusal(verticalSlug);
@@ -9324,7 +9477,7 @@ export class SqliteScopeHost {
9324
9477
  // truth, so the prune keeps more, never less.
9325
9478
  const handedOffThrough = this.deliveryBroker && (this.deliveryHandoff === 'always' || this.deliveryModes.has(`${tenantId}/${scopeId}`))
9326
9479
  ? (this.handoffMarks.get(`${tenantId}/${scopeId}`) ??
9327
- (await this.deliveryBroker({ tenantId, scopeId }).marks(tenantId, scopeId).catch(() => ({})))).event ?? null
9480
+ (await this.brokerOfScope(tenantId, scopeId).marks(tenantId, scopeId).catch(() => ({})))).event ?? null
9328
9481
  : undefined;
9329
9482
  // On the scope actor, like the stamp: issued mid-invoke it would otherwise be a
9330
9483
  // SAVEPOINT inside the invoke's transaction, and roll back with it.
@@ -10283,7 +10436,8 @@ export class SqliteScopeHost {
10283
10436
  // erasure's turn with its handoffs, so every later handoff reads the outbox redacted) and
10284
10437
  // before the key. A broker that throws refuses the erasure here, with the key untouched.
10285
10438
  if (this.deliveryBroker) {
10286
- await this.deliveryBroker({ tenantId, scopeId }).eraseSubject({ tenantId, scopeId, subjectId, at });
10439
+ // #3639: the broker of the scope's environment, where its handoffs went.
10440
+ await this.brokerOfScope(tenantId, scopeId).eraseSubject({ tenantId, scopeId, subjectId, at });
10287
10441
  }
10288
10442
  // Scope stores after the scope-side redaction and before the key (#2068). A store
10289
10443
  // that errors throws here, so the key below is untouched and a retry converges.
@@ -10320,6 +10474,38 @@ export class SqliteScopeHost {
10320
10474
  throw substratError('not_found', `unknown scope ${scopeId} in tenant ${tenantId}`);
10321
10475
  return row.erasure_epoch;
10322
10476
  },
10477
+ holdDependentErasures: async (_actor, tenantId, subjectId, dependents) => {
10478
+ const now = new Date().toISOString();
10479
+ this.directory.transaction(() => {
10480
+ for (const d of dependents)
10481
+ this.directory.prepare(DEPENDENT_ERASURE_HOLD_SQL).run(tenantId, subjectId, d.scopeId, d.vertical, now, now);
10482
+ })();
10483
+ },
10484
+ recordDependentErasures: async (actor, tenantId, subjectId, outcomes) => {
10485
+ if (outcomes.length === 0)
10486
+ return;
10487
+ const now = new Date().toISOString();
10488
+ this.directory.transaction(() => {
10489
+ for (const o of outcomes) {
10490
+ if (o.outcome === 'erased') {
10491
+ this.directory.prepare(DEPENDENT_ERASURE_SETTLE_SQL).run(tenantId, subjectId, o.scopeId);
10492
+ }
10493
+ else {
10494
+ this.directory
10495
+ .prepare(DEPENDENT_ERASURE_OWE_SQL)
10496
+ .run(tenantId, subjectId, o.scopeId, o.vertical, o.attempts, nextDependentErasureAt(now, o.attempts), o.error, now);
10497
+ }
10498
+ }
10499
+ this.recordAdmin(actor, 'eraseAtDependents', { tenantId }, null, { subjectId, dependents: outcomes }, now);
10500
+ })();
10501
+ },
10502
+ dueDependentErasures: async (actor, now, limit) => {
10503
+ const rows = this.directory.prepare(DEPENDENT_ERASURE_DUE_SQL).all(now, limit);
10504
+ this.recordAccess(actor, 'dueDependentErasures', { tenantId: null }, { now, limit }, rows.length);
10505
+ return rows.map((r) => ({
10506
+ tenantId: r.tenant_id, subjectId: r.subject_id, scopeId: r.scope_id, vertical: r.vertical, attempts: r.attempts,
10507
+ }));
10508
+ },
10323
10509
  finalizeSubjectShred: async (actor, tenantId, scopeId, subjectId, redactions, expected, storeErasures) => {
10324
10510
  if (redactions.length === 0)
10325
10511
  throw substratError('conflict', 'subject erasure has no confirmed scope redaction');
@@ -10374,7 +10560,7 @@ export class SqliteScopeHost {
10374
10560
  this.recordAccess(actor, 'listImpersonations', { tenantId: (filter?.tenantId ?? null) }, filter ?? null, sessions.length);
10375
10561
  return sessions;
10376
10562
  },
10377
- reapTenant: async (actor, tenantId) => {
10563
+ reapTenant: async (actor, tenantId, opts) => {
10378
10564
  // The terminal tenant reap (§4.8), the tenant analogue of reapScope. The
10379
10565
  // caller (the reap route / grace-window sweep) has already reaped every scope's
10380
10566
  // storage above the kernel; this clears the tenant's directory-side PII/config
@@ -10413,6 +10599,9 @@ export class SqliteScopeHost {
10413
10599
  if (before.status !== 'deleting') {
10414
10600
  throw substratError('conflict', `tenant ${tenantId} is ${before.status}, not deleting — only a deleting tenant may be reaped`);
10415
10601
  }
10602
+ if (opts?.deletingBy !== undefined && (before.deletingAt === null || before.deletingAt > opts.deletingBy)) {
10603
+ throw substratError('conflict', `tenant ${tenantId} has not passed its delete grace`);
10604
+ }
10416
10605
  for (const table of tables) {
10417
10606
  this.directory.prepare(`DELETE FROM ${table} WHERE tenant_id = ?`).run(tenantId);
10418
10607
  }
@@ -11982,6 +12171,8 @@ export class SqliteScopeHost {
11982
12171
  this.ensureColumn(this.directory, 'app_environments', 'serving_migration_tag', 'serving_migration_tag TEXT');
11983
12172
  this.ensureColumn(this.directory, 'app_environments', 'serve_claim', 'serve_claim TEXT');
11984
12173
  this.ensureColumn(this.directory, 'app_environments', 'serve_claimed_until', 'serve_claimed_until TEXT');
12174
+ // #3530 step 6: the environment's choice of outside effects; NULL reads as `none`.
12175
+ this.ensureColumn(this.directory, 'app_environments', 'effects', 'effects TEXT');
11985
12176
  // §4.8's grace-window timestamp on tenants (mirrors scopes' archived_at).
11986
12177
  this.ensureColumn(this.directory, 'tenants', 'deleting_at', 'deleting_at TEXT');
11987
12178
  this.ensureColumn(this.directory, 'tenants', 'provisioned_by_tenant', 'provisioned_by_tenant TEXT REFERENCES tenants(tenant_id)');