@substrat-run/adapter-cloudflare 0.228.0 → 0.230.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/broker-lake.d.ts +26 -2
  2. package/dist/broker-lake.d.ts.map +1 -1
  3. package/dist/broker-lake.js +56 -3
  4. package/dist/broker-lake.js.map +1 -1
  5. package/dist/control-plane-do.d.ts +50 -13
  6. package/dist/control-plane-do.d.ts.map +1 -1
  7. package/dist/control-plane-do.js +128 -52
  8. package/dist/control-plane-do.js.map +1 -1
  9. package/dist/delivery-broker-do.d.ts +26 -1
  10. package/dist/delivery-broker-do.d.ts.map +1 -1
  11. package/dist/delivery-broker-do.js +50 -3
  12. package/dist/delivery-broker-do.js.map +1 -1
  13. package/dist/delivery-broker-platform.d.ts +24 -2
  14. package/dist/delivery-broker-platform.d.ts.map +1 -1
  15. package/dist/delivery-broker-platform.js +43 -2
  16. package/dist/delivery-broker-platform.js.map +1 -1
  17. package/dist/delivery-handoff.d.ts +8 -1
  18. package/dist/delivery-handoff.d.ts.map +1 -1
  19. package/dist/delivery-handoff.js +8 -5
  20. package/dist/delivery-handoff.js.map +1 -1
  21. package/dist/directory-cutover.d.ts +93 -1
  22. package/dist/directory-cutover.d.ts.map +1 -1
  23. package/dist/directory-cutover.js +85 -2
  24. package/dist/directory-cutover.js.map +1 -1
  25. package/dist/directory-objects.d.ts +12 -0
  26. package/dist/directory-objects.d.ts.map +1 -1
  27. package/dist/directory-objects.js +8 -1
  28. package/dist/directory-objects.js.map +1 -1
  29. package/dist/directory-placement.d.ts.map +1 -1
  30. package/dist/directory-placement.js +1 -0
  31. package/dist/directory-placement.js.map +1 -1
  32. package/dist/directory-tenant-identities.d.ts +30 -0
  33. package/dist/directory-tenant-identities.d.ts.map +1 -0
  34. package/dist/directory-tenant-identities.js +64 -0
  35. package/dist/directory-tenant-identities.js.map +1 -0
  36. package/dist/directory-tenant-tuples.d.ts +30 -3
  37. package/dist/directory-tenant-tuples.d.ts.map +1 -1
  38. package/dist/directory-tenant-tuples.js +27 -0
  39. package/dist/directory-tenant-tuples.js.map +1 -1
  40. package/dist/host.d.ts +35 -5
  41. package/dist/host.d.ts.map +1 -1
  42. package/dist/host.js +110 -19
  43. package/dist/host.js.map +1 -1
  44. package/dist/index.d.ts +7 -3
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +9 -2
  47. package/dist/index.js.map +1 -1
  48. package/dist/peer-call-target.d.ts +16 -2
  49. package/dist/peer-call-target.d.ts.map +1 -1
  50. package/dist/peer-call-target.js +36 -6
  51. package/dist/peer-call-target.js.map +1 -1
  52. package/dist/reconcile-on-wake.d.ts +17 -1
  53. package/dist/reconcile-on-wake.d.ts.map +1 -1
  54. package/dist/reconcile-on-wake.js +84 -12
  55. package/dist/reconcile-on-wake.js.map +1 -1
  56. package/dist/route-read-model-publisher.d.ts.map +1 -1
  57. package/dist/route-read-model-publisher.js +4 -0
  58. package/dist/route-read-model-publisher.js.map +1 -1
  59. package/dist/route-resolver.d.ts +19 -2
  60. package/dist/route-resolver.d.ts.map +1 -1
  61. package/dist/route-resolver.js +25 -5
  62. package/dist/route-resolver.js.map +1 -1
  63. package/dist/scope-do.d.ts +19 -0
  64. package/dist/scope-do.d.ts.map +1 -1
  65. package/dist/scope-do.js +398 -25
  66. package/dist/scope-do.js.map +1 -1
  67. package/dist/scope-facets.d.ts +121 -0
  68. package/dist/scope-facets.d.ts.map +1 -0
  69. package/dist/scope-facets.js +98 -0
  70. package/dist/scope-facets.js.map +1 -0
  71. package/dist/scope-supervisor-do.d.ts +93 -0
  72. package/dist/scope-supervisor-do.d.ts.map +1 -0
  73. package/dist/scope-supervisor-do.js +504 -0
  74. package/dist/scope-supervisor-do.js.map +1 -0
  75. package/dist/scope-sweeper-do.d.ts +7 -1
  76. package/dist/scope-sweeper-do.d.ts.map +1 -1
  77. package/dist/scope-sweeper-do.js +17 -1
  78. package/dist/scope-sweeper-do.js.map +1 -1
  79. package/dist/scope-wake.d.ts +5 -0
  80. package/dist/scope-wake.d.ts.map +1 -1
  81. package/dist/scope-wake.js +2 -0
  82. package/dist/scope-wake.js.map +1 -1
  83. package/dist/scope-work.d.ts +1 -1
  84. package/dist/scope-work.js +1 -1
  85. package/dist/scope-work.js.map +1 -1
  86. package/dist/supplied-pass-box.d.ts +77 -0
  87. package/dist/supplied-pass-box.d.ts.map +1 -0
  88. package/dist/supplied-pass-box.js +265 -0
  89. package/dist/supplied-pass-box.js.map +1 -0
  90. package/dist/tenant-due-index-do.d.ts +76 -0
  91. package/dist/tenant-due-index-do.d.ts.map +1 -0
  92. package/dist/tenant-due-index-do.js +90 -0
  93. package/dist/tenant-due-index-do.js.map +1 -0
  94. package/dist/tenant-due-nudge.d.ts +66 -0
  95. package/dist/tenant-due-nudge.d.ts.map +1 -0
  96. package/dist/tenant-due-nudge.js +77 -0
  97. package/dist/tenant-due-nudge.js.map +1 -0
  98. package/dist/tenant-due-work-do.d.ts +26 -0
  99. package/dist/tenant-due-work-do.d.ts.map +1 -1
  100. package/dist/tenant-due-work-do.js +69 -5
  101. package/dist/tenant-due-work-do.js.map +1 -1
  102. package/package.json +12 -12
package/dist/scope-do.js CHANGED
@@ -10,11 +10,12 @@ HOME_SCOPE_TYPE, SCOPE_TYPE_META_KEY,
10
10
  PARENT_SCOPE_META_KEY, provisionedParent, operationNotInScopeType, provisionedScopeType, scopeTypePlanOf, scopeTypeRoleRefusal, scopeTypeRuns, listQuery, cursorOf, searchLimit, searchMatchExpression, searchQuery, ATTACHMENT_TEXT_DDL, ATTACHMENT_BYTES_SQL, ATTACHMENT_CONDEMNED_DDL, ATTACHMENT_SWEEP_LICENCE_DDL, ATTACHMENT_SWEEP_LICENCE_TABLE, WIRE_NONCE_DDL, WIRE_NONCE_FULL, claimWireNonceIn, isWireNonceTable, isWireNonceWrite, clearOrphanSweepLicence, condemnLicensedOrphanAttachments, consumeOrphanSweepLicence, licensedOrphanIds, recordOrphanSweepLicence, refuseUnlicensedOrphanSweep, refuseCondemnedAttachment, refuseCondemnedInDump, rowlessAttachmentIds, attachmentRecordOfRow, enqueueAttachmentText, reconcileAttachmentText, queueAttachmentTextBackfill, startAttachmentTextBackfill, readAttachmentTextRecheckPage, requeueUnsupportedAttachmentText, startAttachmentTextRecheck, recordAttachmentText, searchAttachments, IDEMPOTENCY_DDL, REFUSALS_TABLE_DDL, REFUSALS_INDEX, refusalInsert, refusalOf, markGuardRefusal, REFUSALS_REBUILD, refusalsAdmitGuards, assertIdempotencyKey, assertPermissionKey, idempotencyLookupQuery, idempotencyPruneStatement, idempotencyRecordStatement, idempotencyOptedOutMessage, replayFor, entityVersionQuery, entityVersionOf, assertIfMatch, OUTBOX_ENTITY_INDEX, SCHEDULE_STATE_DDL, SCHEDULE_STATE_REBUILD, scheduleStateHasKind, VERTICAL_EVENTS_DDL, EXPORT_HOPS_SQL, emptyImportResult, IMPORT_CURSORS_SQL, IMPORT_CURSOR_OF_SQL, OUTBOX_MARK_SQL, exportedSinceQuery, emittedSinceQuery, emittedReportOf, EMITTED_REPORT_CAP, noteTransitionInto, withTransitions, IMPORT_CURSOR_ADVANCE_SQL, IMPORT_RECORD_SQL, moveImportCursor, CrossVerticalRegistry, exportReadPlan, exportReadQuery, planExportBatch, withheldNote, JOB_RUN_DDL, JOB_RUN_DUE_AT, jobRunListLimit, SYSTEM_DOOR_WAIT, ancestorsWithin, } from '@substrat-run/kernel';
11
11
  import { isUpgradeRequest, readSubscription, LIVE_DECIDE_ATTEMPTS, LIVE_FANOUT_LIMIT, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, LIVE_CLOSE, LIVE_SOCKETS_PER_PRINCIPAL, decodeLiveWithin, liveInstant, liveRefusal, liveRefusalStatus, } from './live-reads.js';
12
12
  import { replyOf } from './do-reply.js';
13
+ import { assertNotSupervised, HOLDS_DATA_TABLES, SUPERVISOR_OWNED_METHODS, } from './scope-facets.js';
13
14
  import { OperationQueue } from './serialization.js';
14
15
  import { reconcileOnWake } from './reconcile-on-wake.js';
15
16
  import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
16
17
  import { assertNoRuntimeStorage, doScopedSql, doBuiltColumnsOf, doRedactionSql, doSpineSql } from './sql.js';
17
- import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, STORE_PROOF_DDL, mintStoreProof, redeemStoreProof, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_ALARM_MIN_GAP_MS, PURGE_BATCH, PURGE_DUE_BY_EVENT, consumeScheduleDue, dueByEventSchedulesOf, noteScheduleDue, readScheduleDue, scheduleDueAt, heldPurgePass, purgeDueAt, readPurgeLap, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, CONNECTOR_DISPATCH_REQUESTED_BY, MAX_PENDING_CONNECTOR_DISPATCHES, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
18
+ import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, STORE_PROOF_DDL, mintStoreProof, redeemStoreProof, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_ALARM_MIN_GAP_MS, PURGE_BATCH, PURGE_DUE_BY_EVENT, consumeScheduleDue, dueByEventSchedulesOf, noteScheduleDue, readScheduleDue, scheduleDueAt, createJobVerbs, declaredJobsOf, jobRunDueAt, jobRunEndedOutbox, JOB_DEFER_MS, heldPurgePass, purgeDueAt, readPurgeLap, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, CONNECTOR_DISPATCH_REQUESTED_BY, MAX_PENDING_CONNECTOR_DISPATCHES, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
18
19
  import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove } from '@substrat-run/kernel';
19
20
  import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRefusal } from '@substrat-run/kernel';
20
21
  import { createDoTupleChecker, createLocalControlPlaneReader, scopeTupleReader } from './checker.js';
@@ -26,7 +27,7 @@ import { analyticsBrokerSink, brokerTelemetryDataset } from './broker-telemetry.
26
27
  import { DELIVERY_HANDOFF_KEY, DELIVERY_MODE_KEY, HANDOFF_ROUNDS, deliveryModeAfter, handoffAfterFailure, handoffDue, handoffPending, mergeHandoff, sameMarks, } from './delivery-handoff.js';
27
28
  import { registerPlatformDeliveryBroker } from './delivery-broker-platform.js';
28
29
  import { advanceMarks, brokerName, handoffQueries, messagesOf, senderDeliveryOf } from '@substrat-run/kernel';
29
- import { DELIVERY_HANDOFF_ENV, intentStateOf, intentStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
30
+ import { DELIVERY_HANDOFF_ENV, intentStateOf, intentStateQuery, eventLakeStateOf, eventLakeStateQuery, witnessesOf, witnessQueries, } from '@substrat-run/kernel';
30
31
  import { SCOPE_SWEEPER_NAME, kickPlatformDrain, runScopeDueWork } from './scope-sweeper-do.js';
31
32
  import { SCOPE_WAKE_KEY, keepRegisteredMeanwhile, kickControlPlane, runWake, wakeAfterCommit, wakeDueAt } from './scope-wake.js';
32
33
  import { CARRIED_AWAY_KEY, COPY_MARK_CLEARED_KEY, KEPT_COPY_REFUSAL, KEPT_DIVERGENT_KEY, LOAD_STAMP_KEY, STORE_LOCAL_META_KEYS, WRITE_REVISION_KEY, carriedAwayDump, isCopyMarkInsert, isWriteStatement, assertSpineTablesBuilt, clearCopyMarker, dumpRowsInsert, isSpineTable, markCopyOrigin, repointScopeGrants, settleCopiedWork, emittedHere, IS_COPY_SQL, CLEAN_ROOM_COPY_SQL, isCopyLoad, isLifecycleWrite, readLifecycle, settleLifecycleAfterLoad, writeLifecycle, spineColumnAdditions } from '@substrat-run/kernel';
@@ -57,8 +58,6 @@ const REAPED_MARKER = '_substrat_reaped';
57
58
  const PROVISIONED_FOR_KEY = 'provisioned_for';
58
59
  /** #2016: the refusal of a write that would re-point a scope's tenant, in one wording. */
59
60
  const tenantReceiptRefusal = (held, asked) => `refused: this scope was provisioned for tenant ${held}, not ${asked}`;
60
- /** #2016: the spine tables whose rows say a scope holds state (`ScopeDO.holdsData`). */
61
- const HOLDS_DATA_TABLES = ['_substrat_migrations', '_substrat_tuples', '_substrat_outbox', '_substrat_schedule_state'];
62
61
  /** #2016: why `tenantId` is foreign to a scope (`held`, the receipt `tenantVerdict` read), in one wording. */
63
62
  const foreignTenant = (held, tenantId) => held !== null
64
63
  ? tenantReceiptRefusal(held, tenantId)
@@ -924,6 +923,29 @@ class SystemDoorMovedError extends Error {
924
923
  }
925
924
  /** #1834: the brand only `assertSystemDoor` sets, so nothing else can make a `SystemDoorPass`. */
926
925
  const SYSTEM_DOOR_PASSED = Symbol('system door passed');
926
+ /** One of the object's own hibernatable sockets, as a pass target that starts at `since`. */
927
+ function liveTargetOfSocket(ws, since) {
928
+ return {
929
+ since,
930
+ cursor: since,
931
+ strict: false,
932
+ deserializeAttachment: () => ws.deserializeAttachment(),
933
+ send: (frame) => ws.send(frame),
934
+ close: (code, reason) => ws.close(code, reason),
935
+ };
936
+ }
937
+ /**
938
+ * Track B: is `name` a method of the object's own class chain, below `Object.prototype`? What a
939
+ * facet's `supervisedCall` may run: never an `Object.prototype` member, never a field.
940
+ */
941
+ function definedHere(object, name) {
942
+ for (let p = Object.getPrototypeOf(object); p !== null && p !== Object.prototype; p = Object.getPrototypeOf(p)) {
943
+ const d = Object.getOwnPropertyDescriptor(p, name);
944
+ if (d)
945
+ return typeof d.value === 'function';
946
+ }
947
+ return false;
948
+ }
927
949
  /** Close a live socket whose session has ended (#938). */
928
950
  function closeSessionEnded(ws) {
929
951
  try {
@@ -940,6 +962,28 @@ export function defineScopeDO(modules, bareOps,
940
962
  * when the class is defined, as `registerModule` refuses one on either host.
941
963
  */
942
964
  options = {}) {
965
+ return scopeClass(modules, bareOps, options, 'object');
966
+ }
967
+ /**
968
+ * Track B (broker RFC §6, #3466): the same scope class, to run as a FACET a scope supervisor
969
+ * (`defineScopeSupervisorDO`) loads through the Worker Loader. Switched: nothing on `main` builds
970
+ * a scope bundle with it, so every deployed scope still runs `defineScopeDO`.
971
+ *
972
+ * Three differences, each because a facet cannot do what the object does:
973
+ *
974
+ * - **The alarm is the supervisor's.** A facet cannot set one (workerd: "Facets currently cannot
975
+ * set alarms", `spikes/scope-facet-wakeups`). The one place the class arms (`armAlarmBy`) records
976
+ * the instant instead, and the supervisor reads it back with the call's answer.
977
+ * - **The sockets are the supervisor's.** A socket a facet accepts dies with the facet, so a
978
+ * rollout would drop every live reader. The facet decides who may subscribe (`liveAdmit`) and
979
+ * what each socket is owed (`liveCatchUp`); the supervisor holds the sockets and sends.
980
+ * - **It is reached through `supervisedCall`**, which returns the wake and the scope's tenant with
981
+ * the value. Its env is empty: no binding reaches it, and nothing in it reaches the network.
982
+ */
983
+ export function defineScopeFacet(modules, bareOps, options = {}) {
984
+ return scopeClass(modules, bareOps, options, 'facet');
985
+ }
986
+ function scopeClass(modules, bareOps, options, runtime) {
943
987
  // At definition, not at construction: a worker whose module list drifted fails at its first
944
988
  // import, rather than at the first scope it wakes.
945
989
  for (const registration of modules)
@@ -1023,6 +1067,9 @@ options = {}) {
1023
1067
  * may name, and the operations whose every run clears their date in its own transaction.
1024
1068
  */
1025
1069
  dueSchedules = new Map();
1070
+ /** D-85: the modules that declare jobs, and every declared job by name (`declaredJobsOf`). */
1071
+ jobDeclarers = [];
1072
+ declaredJobs = new Map();
1026
1073
  /**
1027
1074
  * #3540: true while this scope's alarm is waiting on its sweeper's purge run. The purges that
1028
1075
  * run meanwhile commit through `settleCommitted`, and must not arm the alarm the handler is about
@@ -1164,8 +1211,23 @@ options = {}) {
1164
1211
  }
1165
1212
  return this.scopeWorkTenantId;
1166
1213
  }
1214
+ /**
1215
+ * Track B: the earliest instant (epoch ms) this facet asked to be woken at and the supervisor
1216
+ * has not yet read back (`supervisedCall`). Memory only, by design: if the object resets before
1217
+ * the supervisor reads it, the alarm the supervisor armed before the call fires instead, and
1218
+ * every alarm user re-arms from what the store holds.
1219
+ */
1220
+ #facetWakeAt = null;
1221
+ /** Track B: the tenant this facet's scope was provisioned for, once read (it never changes). */
1222
+ #facetTenant = null;
1167
1223
  constructor(ctx, env) {
1168
1224
  super(ctx, env);
1225
+ // Track B's rollback fence (`scope-facets.ts`): an object a scope supervisor served keeps the
1226
+ // scope's rows in its facet, not here. Refused before a single table is made, so a script
1227
+ // rolled back to this class neither answers from empty storage nor marks the object as a
1228
+ // scope's own. A facet's storage never holds the marker, so this is the object's check only.
1229
+ if (runtime === 'object')
1230
+ assertNotSupervised(ctx.storage);
1169
1231
  // #1860: the client's 45s keep-alive (demos/ticket0/app/src/feed.ts) answered at
1170
1232
  // the runtime level, before this object wakes for it. Without this, every idle
1171
1233
  // subscriber's ping still reaches `webSocketMessage` and pins the DO in memory —
@@ -1237,6 +1299,11 @@ options = {}) {
1237
1299
  assertBoundOperations(manifest.id, registration.operations);
1238
1300
  // #119: refused before anything is recorded, as in the pure adapter.
1239
1301
  const trashTargets = registerTrashTargets(manifest.id, new Set(Object.keys(registration.operations?.handlers ?? {})), registration.operations?.inputs, manifest.entityStates, manifest.schedules);
1302
+ // D-85: refused before anything else is recorded (a name taken, an undeclared key).
1303
+ const jobs = declaredJobsOf([...this.jobDeclarers, { manifest, jobs: registration.jobs }]);
1304
+ if (registration.jobs)
1305
+ this.jobDeclarers.push({ manifest, jobs: registration.jobs });
1306
+ this.declaredJobs = jobs;
1240
1307
  this.purgeOnlyKeys.set(manifest.id, purgeOnlyKeysOf(manifest.schedules ?? []));
1241
1308
  for (const [operation, due] of dueByEventSchedulesOf(manifest.schedules))
1242
1309
  this.dueSchedules.set(operation, due);
@@ -2945,7 +3012,12 @@ options = {}) {
2945
3012
  * anything the asserted principal could not, because the filter downstream re-checks
2946
3013
  * that principal against every frame.
2947
3014
  */
2948
- async fetch(request) {
3015
+ /**
3016
+ * Who may subscribe, decided once for both runtimes (Track B): the scope as an object accepts
3017
+ * the socket itself (`fetch`), a facet answers its supervisor (`liveAdmit`). Every check that
3018
+ * guards the handshake is here, so neither door can drift from the other.
3019
+ */
3020
+ async admitLive(request) {
2949
3021
  const url = new URL(request.url);
2950
3022
  if (url.pathname !== LIVE_SUBSCRIBE_PATH) {
2951
3023
  // The DO has exactly one fetch surface. Anything else reaching here is a
@@ -3003,6 +3075,13 @@ options = {}) {
3003
3075
  (within?.checked !== undefined && !(await this.mayWatchRoot(() => this.liveContext(subscriber), within)))) {
3004
3076
  return liveRefusal('forbidden', 'live reads: the subscriber may not watch this root', 'forbidden');
3005
3077
  }
3078
+ return { subscriber, ...(within ? { within } : {}), ...(expiresAt ? { expiresAt } : {}) };
3079
+ }
3080
+ async fetch(request) {
3081
+ const admitted = await this.admitLive(request);
3082
+ if (admitted instanceof Response)
3083
+ return admitted;
3084
+ const { subscriber, within, expiresAt } = admitted;
3006
3085
  const pair = new WebSocketPair();
3007
3086
  const [client, server] = Object.values(pair);
3008
3087
  /**
@@ -3089,6 +3168,13 @@ options = {}) {
3089
3168
  }
3090
3169
  /** The one alarm, moved only earlier: every user of it arms through here (#938, K-69). */
3091
3170
  async armAlarmBy(at) {
3171
+ if (runtime === 'facet') {
3172
+ // Track B: a facet has no alarm of its own. The supervisor reads this back with the call's
3173
+ // answer and arms its own, earliest wins, as below.
3174
+ if (this.#facetWakeAt === null || this.#facetWakeAt > at)
3175
+ this.#facetWakeAt = at;
3176
+ return;
3177
+ }
3092
3178
  const current = await this.ctx.storage.getAlarm();
3093
3179
  if (current === null || current > at)
3094
3180
  await this.ctx.storage.setAlarm(at);
@@ -3105,6 +3191,106 @@ options = {}) {
3105
3191
  await this.retryHandoff();
3106
3192
  await this.runPurgeAlarm();
3107
3193
  }
3194
+ // -- Track B: the facet's doors for its supervisor (`defineScopeFacet`) ---------------
3195
+ /** A facet-only door refuses on the scope as an object: there, nothing supervises it. */
3196
+ assertFacet(door) {
3197
+ if (runtime !== 'facet') {
3198
+ throw new Error(`scope: '${door}' is a facet's door for its supervisor, and this scope runs as an object`);
3199
+ }
3200
+ }
3201
+ /** Track B: the tenant this facet's scope was provisioned for, read once it is known. */
3202
+ facetTenant() {
3203
+ return (this.#facetTenant ??= this.provisionedFor());
3204
+ }
3205
+ /**
3206
+ * Track B: one call from the supervisor, by name, with the wake the call asked for and the
3207
+ * scope's tenant beside its value. The supervisor arms its own alarm from the first and names
3208
+ * the facet's isolate from the second. What it forwards is the supervisor's decision, read off
3209
+ * the platform's own class (`scopeRpcMethods`); here, a method of this class's prototype chain
3210
+ * that the supervisor does not answer itself is callable, plus the alarm and the admission.
3211
+ *
3212
+ * A call that throws carries no wake: the supervisor keeps the alarm it armed before the call,
3213
+ * and the wake stays here for the next call to carry.
3214
+ */
3215
+ async supervisedCall(method, args) {
3216
+ this.assertFacet('supervisedCall');
3217
+ const callable = method === 'alarm' || method === 'liveAdmit' || (typeof method === 'string' && !SUPERVISOR_OWNED_METHODS.has(method) && definedHere(this, method));
3218
+ const fn = callable ? this[method] : undefined;
3219
+ if (typeof fn !== 'function')
3220
+ throw new Error(`scope facet: no forwarded method '${String(method)}'`);
3221
+ const value = await fn.apply(this, Array.isArray(args) ? args : []);
3222
+ const wakeAt = this.#facetWakeAt;
3223
+ this.#facetWakeAt = null;
3224
+ return { value, wakeAt, tenant: this.facetTenant() };
3225
+ }
3226
+ /**
3227
+ * Track B: may this request subscribe? The same checks as the object's own handshake
3228
+ * (`admitLive`). Admitted, the subscription to hold and the outbox's mark to start from, so a
3229
+ * socket hears every change that commits after it was let in. The supervisor accepts the socket.
3230
+ */
3231
+ async liveAdmit(asked) {
3232
+ this.assertFacet('liveAdmit');
3233
+ const admitted = await this.admitLive(new Request(asked.url, { headers: asked.headers }));
3234
+ if (admitted instanceof Response) {
3235
+ return { admitted: false, status: admitted.status, headers: [...admitted.headers], body: await admitted.text() };
3236
+ }
3237
+ const mark = this.sql.exec('SELECT MAX(id) AS id FROM _substrat_outbox').toArray()[0]
3238
+ ?.id ?? '';
3239
+ const subscription = {
3240
+ ...admitted.subscriber,
3241
+ since: new Date().toISOString(),
3242
+ ...(admitted.within ? { within: admitted.within } : {}),
3243
+ ...(admitted.expiresAt ? { expiresAt: admitted.expiresAt } : {}),
3244
+ };
3245
+ return { admitted: true, subscription: { ...subscription }, cursor: mark };
3246
+ }
3247
+ /**
3248
+ * Track B: what each of the supervisor's sockets is owed since its own cursor, decided by the
3249
+ * same pass the object runs (`fanOutLiveTo`), sent back through `handle`. Strict: a socket's
3250
+ * cursor passes only rows decided for it, so a change committed while the supervisor was
3251
+ * resetting, hibernating or between passes is decided on the next pass, never skipped. A frame
3252
+ * may go out twice (a push lost after its send); the client reads a push as a hint to re-read,
3253
+ * so a duplicate costs a read and a gap would cost a stale screen.
3254
+ */
3255
+ async liveCatchUp(sockets, handle) {
3256
+ this.assertFacet('liveCatchUp');
3257
+ const cursors = {};
3258
+ let behind = false;
3259
+ const held = this.facetTenant();
3260
+ const groups = new Map();
3261
+ for (const socket of sockets) {
3262
+ cursors[socket.sid] = socket.cursor;
3263
+ const subscription = readSubscription(socket.attachment);
3264
+ // Unnamed, or named for another tenant than the scope's own: never fed (the pass skips the
3265
+ // first itself; the second is refused here, where the scope's own receipt is at hand).
3266
+ if (!subscription || (held !== null && subscription.tenantId !== held))
3267
+ continue;
3268
+ const key = `${subscription.tenantId}\n${subscription.scopeId}`;
3269
+ let group = groups.get(key);
3270
+ if (!group)
3271
+ groups.set(key, (group = { tenantId: subscription.tenantId, scopeId: subscription.scopeId, targets: [] }));
3272
+ const { sid } = socket;
3273
+ group.targets.push({
3274
+ sid,
3275
+ since: socket.cursor,
3276
+ cursor: socket.cursor,
3277
+ strict: true,
3278
+ deserializeAttachment: () => socket.attachment,
3279
+ // Not awaited: the call is issued in order on the stub as the pass decides, which is what
3280
+ // keeps no await between a decision and its send. A failure is the socket's, and the
3281
+ // supervisor's next pass, or the client's reconnect from its cursor, covers it.
3282
+ send: (frame) => void Promise.resolve(handle.liveSend(sid, frame)).catch(() => undefined),
3283
+ close: (code, reason) => void Promise.resolve(handle.liveClose(sid, code, reason)).catch(() => undefined),
3284
+ });
3285
+ }
3286
+ for (const group of groups.values()) {
3287
+ const pass = await this.fanOutLiveTo(group.targets, group.tenantId, group.scopeId);
3288
+ behind ||= pass.behind;
3289
+ for (const t of group.targets)
3290
+ cursors[t.sid] = t.cursor;
3291
+ }
3292
+ return { cursors, behind };
3293
+ }
3108
3294
  /**
3109
3295
  * #3540: whether this scope's purges are due by event: the switch is `event`, a sweeper is bound
3110
3296
  * for the alarm to ask, and a registered module declares a purge horizon.
@@ -3121,7 +3307,7 @@ options = {}) {
3121
3307
  * `due: 'event'` schedule among the registered modules.
3122
3308
  */
3123
3309
  dueAlarmApplies() {
3124
- return this.dueByEventSwitched() && (this.purgeSchedules.size > 0 || this.dueSchedules.size > 0);
3310
+ return this.dueByEventSwitched() && (this.purgeSchedules.size > 0 || this.dueSchedules.size > 0 || this.declaredJobs.size > 0);
3125
3311
  }
3126
3312
  /** #3540: when this scope's purges are next due, read from its own rows (`purgeDueAt`). */
3127
3313
  purgeDueAtNow(now) {
@@ -3136,7 +3322,11 @@ options = {}) {
3136
3322
  dueAtNow(now, schedules) {
3137
3323
  const purges = this.purgeDueByEvent() ? this.purgeDueAtNow(now) : null;
3138
3324
  const events = schedules && this.dueSchedules.size > 0 ? scheduleDueAt(doSpineSql(this.sql), this.dueSchedules.values()) : null;
3139
- return purges === null ? events : events === null ? purges : Math.min(purges, events);
3325
+ // D-85: a declared job's live runs, on the same condition as the schedules: the due work the
3326
+ // alarm runs (`runScopeDueWork`) drives them only once a pass has said its sweeper takes it.
3327
+ const jobs = schedules ? jobRunDueAt(doSpineSql(this.sql), this.declaredJobs) : null;
3328
+ const due = [purges, events, jobs].filter((at) => at !== null);
3329
+ return due.length === 0 ? null : Math.min(...due);
3140
3330
  }
3141
3331
  /**
3142
3332
  * #3540: arm the scope's alarm for its earliest due work, and record the pair the alarm will ask
@@ -3299,6 +3489,10 @@ options = {}) {
3299
3489
  return;
3300
3490
  }
3301
3491
  const minutes = [...this.purgeSchedules.values(), ...(schedules ? this.dueSchedules.values() : [])].map((p) => p.everyMinutes);
3492
+ // D-85: while a job run is due, a failed or held ask waits a job's deferral, not a schedule's
3493
+ // cadence, and a scope whose only due work is its runs does not wait forever.
3494
+ if (schedules && jobRunDueAt(doSpineSql(this.sql), this.declaredJobs) !== null)
3495
+ minutes.push(JOB_DEFER_MS / 60_000);
3302
3496
  const cadence = after + Math.min(...minutes) * 60_000;
3303
3497
  if ('held' in answer) {
3304
3498
  // Not re-armed, and no commit re-arms it within the cadence: a held scope does not ask on
@@ -3314,7 +3508,8 @@ options = {}) {
3314
3508
  else {
3315
3509
  const sql = doSpineSql(this.sql);
3316
3510
  const open = [...this.purgeSchedules.keys()].some((op) => readPurgeLap(sql, op).after !== null);
3317
- floor = open ? after : after + PURGE_ALARM_MIN_GAP_MS;
3511
+ // D-85: a job pass that left its run going (`progressed`) is an open lap too.
3512
+ floor = open || answer.progressed === true ? after : after + PURGE_ALARM_MIN_GAP_MS;
3318
3513
  }
3319
3514
  await this.ctx.storage.put(PURGE_ALARM_KEY, keep(floor));
3320
3515
  await this.armAlarmBy(Math.max(next, floor));
@@ -3384,16 +3579,19 @@ options = {}) {
3384
3579
  }
3385
3580
  let answered;
3386
3581
  let answeredEnvironment;
3582
+ let answeredLake = false;
3387
3583
  const ran = await runWake(state, Date.now(), () => this.wakeWork(), async (body) => {
3388
3584
  const answer = await kickControlPlane(transport, body);
3389
3585
  answered = answer?.broker;
3390
3586
  answeredEnvironment = answer?.brokerEnvironment;
3587
+ answeredLake = answer?.brokerLake === true;
3391
3588
  return answer;
3392
3589
  });
3393
3590
  // A5: the delivery mode the control plane holds for this tenant, on the same answer, and
3394
- // (#3639) the named environment whose broker it hands off to.
3591
+ // (#3639) the named environment whose broker it hands off to, and (A6) whether the lake is
3592
+ // that broker's.
3395
3593
  if (answered)
3396
- await this.applyDeliveryMode(state.tenantId, state.scopeId, answered, answeredEnvironment);
3594
+ await this.applyDeliveryMode(state.tenantId, state.scopeId, answered, answeredEnvironment, answeredLake);
3397
3595
  // The object took other calls while the kick was out: keep what a commit stored meanwhile.
3398
3596
  const next = keepRegisteredMeanwhile(state, ran, (await this.ctx.storage.get(SCOPE_WAKE_KEY)) ?? null);
3399
3597
  if (!next) {
@@ -3556,6 +3754,8 @@ options = {}) {
3556
3754
  return null;
3557
3755
  return {
3558
3756
  mode: state.mode,
3757
+ // A6 (#3472): the lake is the broker's, so each event is also owed the lake receiver.
3758
+ ...(state.mode === 'live' && state.lake ? { lake: true } : {}),
3559
3759
  ...(state.startPending && tenantId && scopeId ? { start: { tenantId, scopeId, after: state.start } } : {}),
3560
3760
  };
3561
3761
  }
@@ -3582,12 +3782,12 @@ options = {}) {
3582
3782
  * Public for the platform and the suites; a caller in the script can only change which receivers
3583
3783
  * its own next messages are owed, never what the control plane lets the broker drive.
3584
3784
  */
3585
- async applyDeliveryMode(tenantId, scopeId, mode, environment) {
3785
+ async applyDeliveryMode(tenantId, scopeId, mode, environment, lake) {
3586
3786
  await this.ensureMigrations();
3587
3787
  // #3639: production is named by no environment, whichever way an answer spells it.
3588
3788
  const named = environment && environment !== PRODUCTION_ENVIRONMENT ? environment : undefined;
3589
3789
  const prior = (await this.ctx.storage.get(DELIVERY_MODE_KEY)) ?? null;
3590
- const { next, seeded } = deliveryModeAfter(prior, mode, () => this.handoffSeed(), named);
3790
+ const { next, seeded } = deliveryModeAfter(prior, mode, () => this.handoffSeed(), named, lake);
3591
3791
  if (next === prior)
3592
3792
  return;
3593
3793
  if (!next) {
@@ -3616,6 +3816,12 @@ options = {}) {
3616
3816
  const q = intentStateQuery(id);
3617
3817
  return intentStateOf(this.sql.exec(q.sql, ...q.params).toArray());
3618
3818
  }
3819
+ /** A6 (#3472): whether one event of this scope is in the lake yet, for the broker's lake receiver. One primary-key read. */
3820
+ async eventLakeState(id) {
3821
+ await this.ensureMigrations();
3822
+ const q = eventLakeStateQuery(id);
3823
+ return eventLakeStateOf(this.sql.exec(q.sql, ...q.params).toArray());
3824
+ }
3619
3825
  /** #3474: one point per handoff round, when the script binds `SUBSTRAT_BROKER_TELEMETRY`. */
3620
3826
  reportHandoffRound(tenantId, scopeId, round, outcome,
3621
3827
  /** #3639: the named environment whose broker the round went to; undefined for production's. */
@@ -3823,6 +4029,17 @@ options = {}) {
3823
4029
  const sockets = this.ctx.getWebSockets();
3824
4030
  if (sockets.length === 0)
3825
4031
  return;
4032
+ await this.fanOutLiveTo(sockets.map((ws) => liveTargetOfSocket(ws, sinceEventId)), tenantId, scopeId);
4033
+ }
4034
+ /**
4035
+ * The pass `fanOutLive` describes, over any set of targets (Track B): the object's own sockets,
4036
+ * all from one mark, or a supervisor's, each from its own cursor. One page of
4037
+ * `LIVE_FANOUT_LIMIT` rows above the lowest mark; `behind` says rows remain past it.
4038
+ */
4039
+ async fanOutLiveTo(targets, tenantId, scopeId) {
4040
+ if (targets.length === 0)
4041
+ return { behind: false };
4042
+ const sinceEventId = targets.reduce((low, t) => (t.since < low ? t.since : low), targets[0].since);
3826
4043
  const rows = this.sql
3827
4044
  .exec(`SELECT id, type, entity_type, entity_id, occurred_at FROM _substrat_outbox
3828
4045
  WHERE id > ? ORDER BY id LIMIT ?`, sinceEventId, LIVE_FANOUT_LIMIT)
@@ -3830,9 +4047,27 @@ options = {}) {
3830
4047
  // Drop the undeclared entity types BEFORE any per-subscriber work. Not an
3831
4048
  // optimisation: it is the fail-closed rule stated once, in the one place that
3832
4049
  // decides, rather than relied upon inside the loop below.
4050
+ const behind = rows.length === LIVE_FANOUT_LIMIT;
4051
+ const last = rows.length > 0 ? rows[rows.length - 1].id : null;
4052
+ /** A target's cursor moved up to `upTo`, never back. */
4053
+ const advance = (t, upTo) => {
4054
+ if (upTo !== null && upTo > t.cursor)
4055
+ t.cursor = upTo;
4056
+ };
4057
+ /** The highest row of this page below `id`: where a walk that stopped at `id` has reached. */
4058
+ const lastBelow = (id) => {
4059
+ let below = null;
4060
+ for (const r of rows)
4061
+ if (r.id < id)
4062
+ below = r.id;
4063
+ return below;
4064
+ };
3833
4065
  const announceable = rows.filter((r) => this.liveTargets.has(r.entity_type));
3834
- if (announceable.length === 0)
3835
- return;
4066
+ if (announceable.length === 0) {
4067
+ for (const t of targets)
4068
+ advance(t, last);
4069
+ return { behind };
4070
+ }
3836
4071
  /**
3837
4072
  * Is a row's entity beneath a `within` root (#1853)? Each row's ancestors are walked
3838
4073
  * once per pass, on first need, so a check per socket is a set lookup — every widget
@@ -3888,7 +4123,9 @@ options = {}) {
3888
4123
  }
3889
4124
  return (await up).has(`${root.entityType}:${root.entityId}`);
3890
4125
  };
3891
- for (const ws of sockets) {
4126
+ for (const ws of targets) {
4127
+ /** The row this target's walk stopped short of (a strict target only), or null. */
4128
+ let stalledAt = null;
3892
4129
  let subscription = null;
3893
4130
  try {
3894
4131
  subscription = readSubscription(ws.deserializeAttachment());
@@ -4031,6 +4268,9 @@ options = {}) {
4031
4268
  };
4032
4269
  };
4033
4270
  rows: for (const row of announceable) {
4271
+ // Already passed by this target's own walk (a supervised socket resuming from its cursor).
4272
+ if (row.id <= ws.since)
4273
+ continue rows;
4034
4274
  for (let attempt = 0; attempt < LIVE_DECIDE_ATTEMPTS; attempt++) {
4035
4275
  const decidedAt = new Date().toISOString();
4036
4276
  const e = epochAt(decidedAt);
@@ -4067,10 +4307,17 @@ options = {}) {
4067
4307
  }
4068
4308
  continue rows;
4069
4309
  }
4070
- // Still moving after every attempt: this row is not announced, and the client's
4071
- // poll — the floor under every push — picks it up.
4310
+ // Still moving after every attempt: on the object this row is not announced, and the
4311
+ // client's poll — the floor under every push — picks it up. A supervised socket stops
4312
+ // here instead, its cursor short of this row, so its next pass decides it again.
4313
+ if (ws.strict) {
4314
+ stalledAt = row.id;
4315
+ break rows;
4316
+ }
4072
4317
  }
4318
+ advance(ws, stalledAt === null ? last : lastBelow(stalledAt));
4073
4319
  }
4320
+ return { behind };
4074
4321
  }
4075
4322
  // -- attachments (#473): the metadata half of the attachment surface --------
4076
4323
  // The coordinator (worker) holds the bytes and the per-tenant R2 binding; this
@@ -4271,6 +4518,10 @@ options = {}) {
4271
4518
  systemAttachmentRemoveReply(...args) {
4272
4519
  return replyOf(() => this.removeSystemAttachment(...args));
4273
4520
  }
4521
+ /** #3752: a module's own upload, as `system:<module>` (a container pass's `files.put`). */
4522
+ systemAttachmentAddReply(...args) {
4523
+ return replyOf(() => this.addSystemAttachment(...args));
4524
+ }
4274
4525
  /** Record an uploaded attachment: write gate + row + `attachment.added`, one txn. */
4275
4526
  async addAttachment(record, principal, tenantId, scopeId,
4276
4527
  // #476: when set, the gate is checked as this CONNECTION (not `principal`, which is
@@ -4553,6 +4804,69 @@ options = {}) {
4553
4804
  return record;
4554
4805
  });
4555
4806
  }
4807
+ /**
4808
+ * #3752: record a file a module wrote itself — a container pass's output — as `system:<module>`:
4809
+ * the target's write key, checked with the module's purge-only keys withheld, as `remove` is, and
4810
+ * refused while the module is switched off on this scope (the system door). The bytes are already in
4811
+ * the blob store; the host deletes them when this refuses. `createdBy` is the module's actor, JSON.
4812
+ */
4813
+ async addSystemAttachment(record, moduleId, tenantId, scopeId,
4814
+ /** #1834: the instance the system door's gate read; see `invoke`. */
4815
+ systemDoorInstance) {
4816
+ await this.ensureMigrations();
4817
+ let systemDoor;
4818
+ try {
4819
+ systemDoor = this.assertSystemDoor(moduleId, systemDoorInstance);
4820
+ }
4821
+ catch (err) {
4822
+ if (err instanceof SystemDoorMovedError)
4823
+ return SYSTEM_DOOR_MOVED;
4824
+ throw err;
4825
+ }
4826
+ if (!this.modules.has(moduleId)) {
4827
+ throw substratError('not_found', `module not registered in this scope: ${moduleId}`);
4828
+ }
4829
+ const parsed = attachmentRecord.parse(record);
4830
+ if (parsed.createdBy !== JSON.stringify({ system: moduleId })) {
4831
+ throw substratError('validation_failed', `a module's own file is created by ${JSON.stringify({ system: moduleId })}`);
4832
+ }
4833
+ const gate = this.attachmentGate(parsed.entity.entityType);
4834
+ return this.queue.enqueue(async () => {
4835
+ const liveSince = this.liveHighWaterMark();
4836
+ try {
4837
+ await this.revision.transaction(async () => {
4838
+ const ctx = this.operationContext(this.systemPrincipal, tenantId, scopeId, undefined, undefined, systemDoor, undefined, undefined, 'attachments.upload', undefined, [], undefined, undefined, undefined, this.systemAttachmentWithheld(moduleId));
4839
+ assertAllowed(await ctx.check(gate.write, parsed.entity));
4840
+ refuseCondemnedAttachment(doSpineSql(this.sql), parsed.id);
4841
+ this.sql.exec(`INSERT INTO _substrat_attachments
4842
+ (id, entity_type, entity_id, filename, content_type, size, sha256,
4843
+ visibility, created_by, created_at)
4844
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, parsed.id, parsed.entity.entityType, parsed.entity.entityId, parsed.filename, parsed.contentType, parsed.size, parsed.sha256, parsed.visibility, parsed.createdBy, parsed.createdAt);
4845
+ kernelEmit(ctx, {
4846
+ type: ATTACHMENT_ADDED,
4847
+ schemaVersion: 1,
4848
+ entity: parsed.entity,
4849
+ piiClass: 'none',
4850
+ payload: { attachment: parsed },
4851
+ });
4852
+ enqueueAttachmentText(doSpineSql(this.sql), parsed.id, ulid(), new Date().toISOString());
4853
+ });
4854
+ }
4855
+ catch (err) {
4856
+ if (err instanceof PermissionDenied) {
4857
+ this.recordDenial({ kind: 'system', id: moduleId }, tenantId, 'attachments.upload', err, null);
4858
+ }
4859
+ throw err;
4860
+ }
4861
+ try {
4862
+ await this.settleCommitted(tenantId, scopeId, liveSince, null);
4863
+ }
4864
+ catch (err) {
4865
+ console.error('substrat: consumer drain failed after an attachment committed', err);
4866
+ }
4867
+ return parsed;
4868
+ });
4869
+ }
4556
4870
  // -- attachment text (#1575) ---------------------------------------------------
4557
4871
  /**
4558
4872
  * Extracted-text search as `ctx`'s subject: authorized first — the check `open` makes,
@@ -5775,11 +6089,50 @@ options = {}) {
5775
6089
  * partial update that wrote three of the four would leave a run carrying the
5776
6090
  * last failure's error beside the new cursor, which reads as broken forever.
5777
6091
  */
5778
- async jobRunPatch(id, patch, owner) {
6092
+ async jobRunPatch(id, patch, owner, scope) {
5779
6093
  // A compare-and-set on `running` (#1632) and on the pass's lease (#2034) — see
5780
- // `JOB_RUN_PATCH_SQL`. `owner` is LAST and optional: a coordinator from before leases
6094
+ // `JOB_RUN_PATCH_SQL`. `owner` is optional: a coordinator from before leases
5781
6095
  // sends none, and patches the unleased rows it drives.
5782
- return this.sql.exec(JOB_RUN_PATCH_SQL, ...this.jobPatchArgs(id, patch, owner)).rowsWritten > 0;
6096
+ return this.withJobRunEnd(scope, (announce) => {
6097
+ if (this.sql.exec(JOB_RUN_PATCH_SQL, ...this.jobPatchArgs(id, patch, owner)).rowsWritten === 0)
6098
+ return false;
6099
+ if (patch.status !== 'running')
6100
+ announce(id);
6101
+ return true;
6102
+ });
6103
+ }
6104
+ /**
6105
+ * D-85: run `write` in ONE transaction, handing it `announce`, which writes a declared run's
6106
+ * `job.run-ended` event (`jobRunEndedOutbox`) beside the write that ended it. After the commit,
6107
+ * an announced end reaches this scope's consumers, as a settle's outcome event does. `scope` is
6108
+ * what the event is stamped with; a coordinator from before this change sends none, and its
6109
+ * writes announce nothing.
6110
+ */
6111
+ async withJobRunEnd(scope, write) {
6112
+ const liveSince = scope ? this.liveHighWaterMark() : null;
6113
+ let ended = false;
6114
+ const out = this.revision.transactionSync(() => write((id) => {
6115
+ if (!scope)
6116
+ return;
6117
+ const run = this.sql.exec('SELECT * FROM _substrat_job_runs WHERE id = ?', id).toArray()[0];
6118
+ const st = run &&
6119
+ jobRunEndedOutbox(run, {
6120
+ tenantId: scope.tenantId,
6121
+ scopeId: scope.scopeId,
6122
+ now: new Date().toISOString(),
6123
+ mintEventId: (ms) => this.mintEventId(ms),
6124
+ version: this.env.SUBSTRAT_VERSION_ID ?? null,
6125
+ });
6126
+ if (!st)
6127
+ return;
6128
+ this.sql.exec(st.sql, ...st.params);
6129
+ ended = true;
6130
+ }));
6131
+ if (ended && scope) {
6132
+ // #1525: null — a pass's end is the platform's write, not a vertical caller's.
6133
+ await this.queue.enqueue(() => this.settleCommitted(scope.tenantId, scope.scopeId, liveSince, null));
6134
+ }
6135
+ return out;
5783
6136
  }
5784
6137
  jobPatchArgs(id, patch, owner) {
5785
6138
  return [
@@ -5810,14 +6163,17 @@ options = {}) {
5810
6163
  * `JOB_RUN_MISS_SETTLE_SQL` (the backoff or failure that count calls for) in ONE transaction,
5811
6164
  * by this object's clock. Null = the claim no longer held the run, or had begun.
5812
6165
  */
5813
- async jobRunMiss(id, owner, note) {
5814
- return this.revision.transactionSync(() => {
6166
+ async jobRunMiss(id, owner, note, scope) {
6167
+ return this.withJobRunEnd(scope, (announce) => {
5815
6168
  const at = new Date(Date.now()).toISOString();
5816
6169
  const counted = this.sql.exec(JOB_RUN_MISS_SQL, at, id, owner).toArray()[0];
5817
6170
  if (!counted)
5818
6171
  return null;
5819
6172
  const o = admissionMissOutcome(counted.admission_misses, at, note);
5820
- this.sql.exec(JOB_RUN_MISS_SETTLE_SQL, o.status, o.nextAttemptAt, o.endedAt, o.lastError, id, counted.admission_misses);
6173
+ const settled = this.sql.exec(JOB_RUN_MISS_SETTLE_SQL, o.status, o.nextAttemptAt, o.endedAt, o.lastError, id, counted.admission_misses)
6174
+ .rowsWritten > 0;
6175
+ if (settled && o.status === 'failed')
6176
+ announce(id);
5821
6177
  return { misses: counted.admission_misses, failed: o.status === 'failed' };
5822
6178
  });
5823
6179
  }
@@ -5880,16 +6236,18 @@ options = {}) {
5880
6236
  * results, not to the cursor) then skips work it never did. The kernel's
5881
6237
  * `runJobPass` carries the full argument.
5882
6238
  */
5883
- async jobCommitPass(id, patch, owner) {
6239
+ async jobCommitPass(id, patch, owner, scope) {
5884
6240
  // `transactionSync` with both statements inline — NOT `await
5885
6241
  // this.jobRunPatch(...)` then the delete. The await is an output-gate
5886
6242
  // boundary, which is precisely the gap this method exists to close.
5887
- return this.revision.transactionSync(() => {
6243
+ return this.withJobRunEnd(scope, (announce) => {
5888
6244
  // #2034: the ledger goes only with a patch that applied — a stale holder's commit must
5889
6245
  // not empty the ledger of the pass that took the run over.
5890
6246
  if (this.sql.exec(JOB_RUN_PATCH_SQL, ...this.jobPatchArgs(id, patch, owner)).rowsWritten === 0)
5891
6247
  return false;
5892
6248
  this.sql.exec('DELETE FROM _substrat_job_steps WHERE run_id = ?', id);
6249
+ if (patch.status !== 'running')
6250
+ announce(id);
5893
6251
  return true;
5894
6252
  });
5895
6253
  }
@@ -7379,6 +7737,8 @@ options = {}) {
7379
7737
  'ALTER TABLE _substrat_job_runs ADD COLUMN lease_began_at TEXT',
7380
7738
  // #2042 r3: consecutive admission misses. NULL = none, right for every run already there.
7381
7739
  'ALTER TABLE _substrat_job_runs ADD COLUMN admission_misses INTEGER',
7740
+ // D-85: the declared job's definition version. NULL = a run of an undeclared job, or one before it.
7741
+ 'ALTER TABLE _substrat_job_runs ADD COLUMN definition_version INTEGER',
7382
7742
  // Executor retry state (#100). The defaults read as "terminal", which is
7383
7743
  // right for every row already there: each is a completed delivery or a
7384
7744
  // consumer dead-letter.
@@ -9124,6 +9484,19 @@ options = {}) {
9124
9484
  }),
9125
9485
  // Upload links: mint / revoke / list, written once in the kernel — the same four things
9126
9486
  // `capabilities` is handed, and the same consumer-is-system-actor rule.
9487
+ // D-85: start or join a declared job's run, in this transaction, checked as the caller. The
9488
+ // commit's `notePurgeDue` then arms the scope's alarm for it (`jobRunDueAt`).
9489
+ jobs: createJobVerbs({
9490
+ sql: doSpineSql(sql),
9491
+ // #2993: only the jobs of the modules this scope's type runs; the drive keeps the whole map.
9492
+ jobs: scopeTypePlan.declared ? new Map([...this.declaredJobs].filter(([, j]) => this.runs(j.moduleId))) : this.declaredJobs,
9493
+ check: (permission) => runCheck(permission),
9494
+ now: at,
9495
+ mintId: ulid,
9496
+ assertWrites: (verb) => assertImpersonationWrites(impersonation, verb),
9497
+ subject: systemActor ? { kind: 'system', id: systemActor.system } : subject,
9498
+ minted,
9499
+ }),
9127
9500
  attachments: createAttachmentVerbs({
9128
9501
  sql: doSpineSql(sql),
9129
9502
  subject: systemActor ? { kind: 'system', id: systemActor.system } : subject,