@substrat-run/adapter-cloudflare 0.215.0 → 0.217.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 (83) hide show
  1. package/dist/broker-telemetry.d.ts +20 -0
  2. package/dist/broker-telemetry.d.ts.map +1 -0
  3. package/dist/broker-telemetry.js +29 -0
  4. package/dist/broker-telemetry.js.map +1 -0
  5. package/dist/connection-sweep-do.d.ts +83 -0
  6. package/dist/connection-sweep-do.d.ts.map +1 -0
  7. package/dist/connection-sweep-do.js +89 -0
  8. package/dist/connection-sweep-do.js.map +1 -0
  9. package/dist/control-plane-do.d.ts +54 -43
  10. package/dist/control-plane-do.d.ts.map +1 -1
  11. package/dist/control-plane-do.js +131 -80
  12. package/dist/control-plane-do.js.map +1 -1
  13. package/dist/delivery-broker-do.d.ts +94 -0
  14. package/dist/delivery-broker-do.d.ts.map +1 -0
  15. package/dist/delivery-broker-do.js +172 -0
  16. package/dist/delivery-broker-do.js.map +1 -0
  17. package/dist/delivery-handoff.d.ts +46 -0
  18. package/dist/delivery-handoff.d.ts.map +1 -0
  19. package/dist/delivery-handoff.js +61 -0
  20. package/dist/delivery-handoff.js.map +1 -0
  21. package/dist/directory-mirror-apply.d.ts +59 -0
  22. package/dist/directory-mirror-apply.d.ts.map +1 -0
  23. package/dist/directory-mirror-apply.js +158 -0
  24. package/dist/directory-mirror-apply.js.map +1 -0
  25. package/dist/directory-mirror-claims.d.ts +77 -0
  26. package/dist/directory-mirror-claims.d.ts.map +1 -0
  27. package/dist/directory-mirror-claims.js +129 -0
  28. package/dist/directory-mirror-claims.js.map +1 -0
  29. package/dist/directory-mirror.d.ts +201 -0
  30. package/dist/directory-mirror.d.ts.map +1 -0
  31. package/dist/directory-mirror.js +557 -0
  32. package/dist/directory-mirror.js.map +1 -0
  33. package/dist/directory-objects.d.ts +24 -0
  34. package/dist/directory-objects.d.ts.map +1 -1
  35. package/dist/directory-objects.js +125 -1
  36. package/dist/directory-objects.js.map +1 -1
  37. package/dist/directory-placement.d.ts +17 -0
  38. package/dist/directory-placement.d.ts.map +1 -1
  39. package/dist/directory-placement.js +28 -2
  40. package/dist/directory-placement.js.map +1 -1
  41. package/dist/directory-split-inventory.d.ts +4 -1
  42. package/dist/directory-split-inventory.d.ts.map +1 -1
  43. package/dist/directory-split-inventory.js +7 -1
  44. package/dist/directory-split-inventory.js.map +1 -1
  45. package/dist/host.d.ts +11 -1
  46. package/dist/host.d.ts.map +1 -1
  47. package/dist/host.js +44 -5
  48. package/dist/host.js.map +1 -1
  49. package/dist/index.d.ts +3 -0
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +4 -0
  52. package/dist/index.js.map +1 -1
  53. package/dist/peer-call-target.d.ts +61 -0
  54. package/dist/peer-call-target.d.ts.map +1 -0
  55. package/dist/peer-call-target.js +98 -0
  56. package/dist/peer-call-target.js.map +1 -0
  57. package/dist/reconcile-on-wake.d.ts.map +1 -1
  58. package/dist/reconcile-on-wake.js +5 -3
  59. package/dist/reconcile-on-wake.js.map +1 -1
  60. package/dist/route-read-model-publisher.d.ts +29 -4
  61. package/dist/route-read-model-publisher.d.ts.map +1 -1
  62. package/dist/route-read-model-publisher.js +137 -3
  63. package/dist/route-read-model-publisher.js.map +1 -1
  64. package/dist/route-read-model.d.ts +75 -1
  65. package/dist/route-read-model.d.ts.map +1 -1
  66. package/dist/route-read-model.js +118 -0
  67. package/dist/route-read-model.js.map +1 -1
  68. package/dist/route-resolver.d.ts +33 -5
  69. package/dist/route-resolver.d.ts.map +1 -1
  70. package/dist/route-resolver.js +130 -70
  71. package/dist/route-resolver.js.map +1 -1
  72. package/dist/scope-do.d.ts +11 -0
  73. package/dist/scope-do.d.ts.map +1 -1
  74. package/dist/scope-do.js +292 -21
  75. package/dist/scope-do.js.map +1 -1
  76. package/dist/scope-sweeper-do.d.ts +12 -2
  77. package/dist/scope-sweeper-do.d.ts.map +1 -1
  78. package/dist/scope-sweeper-do.js.map +1 -1
  79. package/dist/scope-work.d.ts +1 -1
  80. package/dist/scope-work.d.ts.map +1 -1
  81. package/dist/scope-work.js +1 -0
  82. package/dist/scope-work.js.map +1 -1
  83. package/package.json +9 -9
package/dist/scope-do.js CHANGED
@@ -10,10 +10,16 @@ import { reconcileOnWake } from './reconcile-on-wake.js';
10
10
  import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
11
11
  import { assertNoWorkerdStorage, doScopedSql, doBuiltColumnsOf, doRedactionSql, doSpineSql } from './sql.js';
12
12
  import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_BATCH, heldPurgePass, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, CONNECTOR_DISPATCH_REQUESTED_BY, MAX_PENDING_CONNECTOR_DISPATCHES, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
13
+ import { assertSameAttachmentGate, attachmentGateOf, decideAttachmentRemove } from '@substrat-run/kernel';
13
14
  import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRefusal } from '@substrat-run/kernel';
14
15
  import { createDoTupleChecker, createLocalControlPlaneReader, scopeTupleReader } from './checker.js';
15
16
  import { settlePlatformRequestIn } from '@substrat-run/kernel';
16
17
  import { loadDropsRowsOf, SCOPE_COPY_LEASE_MS, ulidTime } from '@substrat-run/kernel';
18
+ import { handoffOutcome, reportHandoff, traceIdOf } from '@substrat-run/kernel';
19
+ import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
20
+ import { analyticsBrokerSink, brokerTelemetryDataset } from './broker-telemetry.js';
21
+ import { DELIVERY_HANDOFF_KEY, HANDOFF_ROUNDS, handoffAfterFailure, handoffDue, handoffPending, mergeHandoff, sameMarks } from './delivery-handoff.js';
22
+ import { advanceMarks, brokerName, handoffQueries, messagesOf } from '@substrat-run/kernel';
17
23
  import { SCOPE_WAKE_KEY, keepRegisteredMeanwhile, kickControlPlane, runWake, wakeAfterCommit, wakeDueAt } from './scope-wake.js';
18
24
  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';
19
25
  import { GRANT_CHILDREN_INDEX_DDL, SHAPE_MARKER_INDEX_DDL, grantedEntitiesForContext } from '@substrat-run/kernel';
@@ -1026,7 +1032,7 @@ options = {}) {
1026
1032
  updatedStampPlans = new Map();
1027
1033
  /** #2068: each registered module's erasure, in registration order — what `redactSubject` runs. */
1028
1034
  erasurePlans = [];
1029
- /** entityType → the declared attachment gate (#473): read key + write key (default: read). */
1035
+ /** entityType → the declared attachment gate (#473): read key, write key (default: read), remove key (#3434). */
1030
1036
  attachmentTargets = new Map();
1031
1037
  /** entityType → the `uploadLinks` policy its `attachmentTargets` entry declares; absent = no links. */
1032
1038
  uploadLinkPolicies = new Map();
@@ -1051,6 +1057,14 @@ options = {}) {
1051
1057
  * underneath rows it already stored.
1052
1058
  */
1053
1059
  mintEventId = createUlid();
1060
+ /**
1061
+ * K-74: the intent-id mint for THIS scope, floored at its own highest intent as `mintEventId` is at
1062
+ * its highest event. The handoff reads intents past a mark with `id > ?`, so an intent minted
1063
+ * below one already handed off (a clock stepped back across a restart) would never be handed off.
1064
+ * Per scope, never the process-wide mint: seeding that from one scope would move every other
1065
+ * scope's ids forward.
1066
+ */
1067
+ mintIntentId = createUlid();
1054
1068
  /** `module@version` → the SQL digest its journal row recorded, null for a row from before #2066. */
1055
1069
  applied = new Map();
1056
1070
  migrationPromise;
@@ -1157,6 +1171,9 @@ options = {}) {
1157
1171
  const highest = this.sql.exec('SELECT MAX(id) AS id FROM _substrat_outbox').toArray()[0]?.id;
1158
1172
  if (highest)
1159
1173
  this.mintEventId.seedFrom(highest);
1174
+ const highestIntent = this.sql.exec('SELECT MAX(id) AS id FROM _substrat_platform_requests').toArray()[0]?.id;
1175
+ if (highestIntent)
1176
+ this.mintIntentId.seedFrom(highestIntent);
1160
1177
  const controlPlane = this.controlPlaneReader();
1161
1178
  // #2263: a peer holds only what this code's declaration names, whatever the tuples say. The
1162
1179
  // union is this class's code-time module set, so a promote (new code) is a new union.
@@ -1241,15 +1258,8 @@ options = {}) {
1241
1258
  // ambiguous authority must not depend on registration order (mirror of the pure
1242
1259
  // adapter, which validates the same way).
1243
1260
  for (const target of manifest.attachmentTargets) {
1244
- const gate = {
1245
- read: target.readPermission,
1246
- write: target.writePermission ?? target.readPermission,
1247
- };
1248
- const existing = this.attachmentTargets.get(target.entityType);
1249
- if (existing && (existing.read !== gate.read || existing.write !== gate.write)) {
1250
- throw new Error(`conflicting attachmentTargets for '${target.entityType}': ` +
1251
- `(${existing.read}/${existing.write}) vs (${gate.read}/${gate.write})`);
1252
- }
1261
+ const gate = attachmentGateOf(target);
1262
+ assertSameAttachmentGate(target.entityType, this.attachmentTargets.get(target.entityType), gate);
1253
1263
  this.attachmentTargets.set(target.entityType, gate);
1254
1264
  if (target.uploadLinks) {
1255
1265
  const known = this.uploadLinkPolicies.get(target.entityType);
@@ -1918,10 +1928,16 @@ options = {}) {
1918
1928
  * transaction, so the rows, their deliveries and the pruned-through floor go together.
1919
1929
  */
1920
1930
  async pruneDrainedEvents(drainedBefore, limit, executors, due = true) {
1931
+ // K-74: with a broker bound, only what it has acknowledged may go: the scope's own marks,
1932
+ // which are only ever at or below what the broker holds, so the prune keeps more, never less.
1933
+ const handedOffThrough = this.env.SUBSTRAT_DELIVERY_BROKER
1934
+ ? ((await this.ctx.storage.get(DELIVERY_HANDOFF_KEY))?.marks?.event ?? null)
1935
+ : undefined;
1921
1936
  return this.queue.enqueue(() => this.revision.transactionSync(() => pruneDrainedOutbox(this.switchSql(), {
1922
1937
  drainedBefore,
1923
1938
  limit,
1924
1939
  due,
1940
+ ...(handedOffThrough === undefined ? {} : { handedOffThrough }),
1925
1941
  // Executors run on the coordinator, which names them; the consumers are this DO's own.
1926
1942
  subscribers: [...outboxSubscribersOf(this.modules.values(), []), ...executors],
1927
1943
  exportTypes: this.crossVertical.exportTypes(),
@@ -2979,6 +2995,7 @@ options = {}) {
2979
2995
  async alarm() {
2980
2996
  await this.armLiveExpiry();
2981
2997
  await this.runScopeWake();
2998
+ await this.retryHandoff();
2982
2999
  }
2983
3000
  /** K-69: a scope with the control plane's origin and secret asks for its own drains. */
2984
3001
  wakeTransport() {
@@ -3055,6 +3072,120 @@ options = {}) {
3055
3072
  console.error('substrat: scope wake failed; the pass is the backstop', err);
3056
3073
  }
3057
3074
  }
3075
+ /** K-74: this scope's broker, or null when the script binds none (the broker is off). */
3076
+ deliveryBroker(tenantId) {
3077
+ const ns = this.env.SUBSTRAT_DELIVERY_BROKER;
3078
+ if (!ns)
3079
+ return null;
3080
+ const app = this.env.SUBSTRAT_VERTICAL ?? 'vertical';
3081
+ return ns.get(ns.idFromName(brokerName(tenantId, app)));
3082
+ }
3083
+ /**
3084
+ * K-74: hand off what the scope's commits left, past its marks, and keep the marks the broker
3085
+ * acknowledged. The marks live in storage KV (`DELIVERY_HANDOFF_KEY`), never SQL, as the wake's
3086
+ * state does: a cache of what the broker holds, which it answers for when they are lost. Never
3087
+ * fails the commit it follows.
3088
+ *
3089
+ * A retry is durable before the first broker call, so an object reset mid-handoff leaves one the
3090
+ * alarm runs. It is cleared only by a read that finds nothing left. A handoff that fails, that
3091
+ * makes no progress, or that stops at its round limit with work left keeps it, on
3092
+ * `HANDOFF_RETRY_MS`.
3093
+ */
3094
+ async handOffCommitted(tenantId, scopeId) {
3095
+ const broker = this.deliveryBroker(tenantId);
3096
+ if (!broker)
3097
+ return;
3098
+ const ids = { tenantId, scopeId };
3099
+ const stored = (await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null;
3100
+ let marks = stored?.marks;
3101
+ /** #3474: the round now with the broker, so a throw reports what it tried. */
3102
+ let inFlight = null;
3103
+ try {
3104
+ marks ??= await broker.marks(tenantId, scopeId);
3105
+ let retry = null;
3106
+ let drained = false;
3107
+ // A backlog larger than one batch follows in the next round; bounded, so a commit never spins.
3108
+ for (let round = 0; round < HANDOFF_ROUNDS; round++) {
3109
+ inFlight = null;
3110
+ const sent = handoffQueries(marks).flatMap((q) => messagesOf(q.kind, this.sql.exec(q.sql, ...q.params).toArray(), ids));
3111
+ if (sent.length === 0) {
3112
+ drained = true;
3113
+ break;
3114
+ }
3115
+ if (!retry) {
3116
+ retry = handoffPending(stored, marks, Date.now(), ids);
3117
+ await this.keepHandoff(retry);
3118
+ await this.armAlarmBy(retry.due);
3119
+ }
3120
+ inFlight = { sent, startedAt: Date.now() };
3121
+ const answer = await broker.handOff(sent);
3122
+ const next = advanceMarks(marks, sent, answer);
3123
+ this.reportHandoffRound(tenantId, scopeId, inFlight, handoffOutcome(sent, answer));
3124
+ inFlight = null;
3125
+ // An answer that acknowledges nothing new: stop, and leave the retry armed.
3126
+ if (sameMarks(next, marks))
3127
+ throw new Error('the broker acknowledged none of the handoff');
3128
+ marks = next;
3129
+ await this.keepHandoff({ ...retry, marks });
3130
+ }
3131
+ if (drained) {
3132
+ await this.keepHandoff({ tenantId, scopeId, marks });
3133
+ return;
3134
+ }
3135
+ // The round limit, with work left: continue on the first step of the back-off.
3136
+ const more = handoffPending(null, marks, Date.now(), ids);
3137
+ await this.keepHandoff(more);
3138
+ await this.armAlarmBy(more.due);
3139
+ }
3140
+ catch (err) {
3141
+ if (inFlight)
3142
+ this.reportHandoffRound(tenantId, scopeId, inFlight, 'failed');
3143
+ console.error('substrat: delivery handoff failed; the scope alarm retries it', err);
3144
+ const next = handoffAfterFailure(stored, marks, Date.now(), ids);
3145
+ await this.keepHandoff(next);
3146
+ await this.armAlarmBy(next.due);
3147
+ }
3148
+ }
3149
+ /** #3474: one point per handoff round, when the script binds `SUBSTRAT_BROKER_TELEMETRY`. */
3150
+ reportHandoffRound(tenantId, scopeId, round, outcome) {
3151
+ if (this.brokerSink === undefined) {
3152
+ const dataset = brokerTelemetryDataset(this.env);
3153
+ this.brokerSink = dataset ? analyticsBrokerSink(dataset) : null;
3154
+ }
3155
+ if (!this.brokerSink)
3156
+ return;
3157
+ reportHandoff(this.brokerSink, { tenantId, app: this.env.SUBSTRAT_VERTICAL ?? 'vertical', scopeId }, { ...round, outcome, at: Date.now(), traceId: traceIdOf(currentTraceparent()) });
3158
+ }
3159
+ brokerSink;
3160
+ /**
3161
+ * Store the handoff state, never moving a mark backwards: another commit's handoff may have
3162
+ * stored a later one while this one awaited the broker.
3163
+ */
3164
+ async keepHandoff(next) {
3165
+ const fresh = (await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null;
3166
+ await this.ctx.storage.put(DELIVERY_HANDOFF_KEY, mergeHandoff(fresh, next));
3167
+ }
3168
+ /** K-74: the handoff's half of the alarm. Never throws. */
3169
+ async retryHandoff() {
3170
+ try {
3171
+ const state = (await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null;
3172
+ if (state?.due === undefined)
3173
+ return;
3174
+ // The alarm is shared: another of its users may have fired it first. Keep this one's time.
3175
+ if (!handoffDue(state, Date.now())) {
3176
+ await this.armAlarmBy(state.due);
3177
+ return;
3178
+ }
3179
+ const tenant = tenantIdOf.safeParse(state?.tenantId);
3180
+ const scope = scopeIdOf.safeParse(state?.scopeId);
3181
+ if (!tenant.success || !scope.success)
3182
+ return;
3183
+ await this.handOffCommitted(tenant.data, scope.data);
3184
+ }
3185
+ catch (err) {
3186
+ console.error('substrat: delivery handoff retry failed', err);
3187
+ }
3188
+ }
3058
3189
  /** The context a live subscriber's checks run in: its own principal, under `live.subscribe`. */
3059
3190
  liveContext(subscriber) {
3060
3191
  return this.operationContext(subscriber.principal, subscriber.tenantId, subscriber.scopeId, undefined, undefined, undefined, undefined, undefined, 'live.subscribe');
@@ -3171,6 +3302,8 @@ options = {}) {
3171
3302
  await this.dispatch(tenantId, scopeId, invocationId);
3172
3303
  // K-69: after the consumers, whose own emits and intents count too.
3173
3304
  await this.noteScopeWake(tenantId, scopeId);
3305
+ // K-74: the same, for the delivery broker.
3306
+ await this.handOffCommitted(tenantId, scopeId);
3174
3307
  if (liveSince === null)
3175
3308
  return;
3176
3309
  try {
@@ -3647,6 +3780,12 @@ options = {}) {
3647
3780
  attachmentRemoveReply(...args) {
3648
3781
  return replyOf(() => this.removeAttachment(...args));
3649
3782
  }
3783
+ systemAttachmentRemove(...args) {
3784
+ return thrownForRpc(() => this.removeSystemAttachment(...args));
3785
+ }
3786
+ systemAttachmentRemoveReply(...args) {
3787
+ return replyOf(() => this.removeSystemAttachment(...args));
3788
+ }
3650
3789
  /** Record an uploaded attachment: write gate + row + `attachment.added`, one txn. */
3651
3790
  async addAttachment(record, principal, tenantId, scopeId,
3652
3791
  // #476: when set, the gate is checked as this CONNECTION (not `principal`, which is
@@ -3796,6 +3935,14 @@ options = {}) {
3796
3935
  }
3797
3936
  return record;
3798
3937
  }
3938
+ /**
3939
+ * #119 / #3434: a module's purge-only keys, withheld from its system principal's attachment
3940
+ * checks as from every system check but the purge sweep's own invoke — so holding the purge
3941
+ * key never admits an `open` or a `remove` of a file.
3942
+ */
3943
+ systemAttachmentWithheld(moduleId) {
3944
+ return withheldKeysFor(this.purgeOnlyKeys.get(moduleId), undefined, false);
3945
+ }
3799
3946
  /** Authorize a job's read as its registered module, never as a person. */
3800
3947
  async authorizeSystemAttachment(attachmentId, moduleId, tenantId, scopeId,
3801
3948
  /** #1834: the instance the system door's gate read; see `invoke`. */
@@ -3818,7 +3965,7 @@ options = {}) {
3818
3965
  return null;
3819
3966
  const gate = this.attachmentGate(record.entity.entityType);
3820
3967
  try {
3821
- const ctx = this.operationContext(this.systemPrincipal, tenantId, scopeId, undefined, undefined, systemDoor, undefined, undefined, 'attachments.open');
3968
+ const ctx = this.operationContext(this.systemPrincipal, tenantId, scopeId, undefined, undefined, systemDoor, undefined, undefined, 'attachments.open', undefined, [], undefined, undefined, undefined, this.systemAttachmentWithheld(moduleId));
3822
3969
  assertAllowed(await ctx.check(gate.read, record.entity));
3823
3970
  }
3824
3971
  catch (err) {
@@ -3842,7 +3989,8 @@ options = {}) {
3842
3989
  try {
3843
3990
  await this.revision.transaction(async () => {
3844
3991
  const ctx = this.operationContext(principal, tenantId, scopeId, undefined, connectionId, undefined, undefined, undefined, 'attachments.remove');
3845
- assertAllowed(await ctx.check(gate.write, record.entity));
3992
+ // #3434: the write key, or the target's remove key when it declares one.
3993
+ assertAllowed(await decideAttachmentRemove((p, e) => ctx.check(p, e), gate, record.entity));
3846
3994
  this.sql.exec('DELETE FROM _substrat_attachments WHERE id = ?', attachmentId);
3847
3995
  kernelEmit(ctx, {
3848
3996
  type: ATTACHMENT_REMOVED,
@@ -3865,6 +4013,61 @@ options = {}) {
3865
4013
  return record;
3866
4014
  });
3867
4015
  }
4016
+ /**
4017
+ * #3434: remove an attachment's metadata fact as a registered module's system principal — a
4018
+ * retention schedule deleting a file it never uploaded. The system door's pin first, exactly
4019
+ * as `authorizeSystemAttachment` and a system invoke take it; then the gate a person's remove
4020
+ * meets (the write key, or the declared remove key), checked as `system:<moduleId>`, so the
4021
+ * kill switch applies as it does to any system check, and the module's purge-only keys are
4022
+ * withheld (`systemAttachmentWithheld`). The row
4023
+ * and `attachment.removed` commit together, the event attributed to the module.
4024
+ */
4025
+ async removeSystemAttachment(attachmentId, moduleId, tenantId, scopeId,
4026
+ /** #1834: the instance the system door's gate read; see `invoke`. */
4027
+ systemDoorInstance) {
4028
+ await this.ensureMigrations();
4029
+ let systemDoor;
4030
+ try {
4031
+ systemDoor = this.assertSystemDoor(moduleId, systemDoorInstance);
4032
+ }
4033
+ catch (err) {
4034
+ if (err instanceof SystemDoorMovedError)
4035
+ return SYSTEM_DOOR_MOVED;
4036
+ throw err;
4037
+ }
4038
+ if (!this.modules.has(moduleId)) {
4039
+ throw substratError('not_found', `module not registered in this scope: ${moduleId}`);
4040
+ }
4041
+ return this.queue.enqueue(async () => {
4042
+ const record = this.attachmentRow(attachmentId);
4043
+ if (!record)
4044
+ return null;
4045
+ const gate = this.attachmentGate(record.entity.entityType);
4046
+ const liveSince = this.liveHighWaterMark();
4047
+ try {
4048
+ await this.revision.transaction(async () => {
4049
+ const ctx = this.operationContext(this.systemPrincipal, tenantId, scopeId, undefined, undefined, systemDoor, undefined, undefined, 'attachments.remove', undefined, [], undefined, undefined, undefined, this.systemAttachmentWithheld(moduleId));
4050
+ assertAllowed(await decideAttachmentRemove((p, e) => ctx.check(p, e), gate, record.entity));
4051
+ this.sql.exec('DELETE FROM _substrat_attachments WHERE id = ?', attachmentId);
4052
+ kernelEmit(ctx, {
4053
+ type: ATTACHMENT_REMOVED,
4054
+ schemaVersion: 1,
4055
+ entity: record.entity,
4056
+ piiClass: 'none',
4057
+ payload: { attachment: record },
4058
+ });
4059
+ });
4060
+ }
4061
+ catch (err) {
4062
+ if (err instanceof PermissionDenied) {
4063
+ this.recordDenial({ kind: 'system', id: moduleId }, tenantId, 'attachments.remove', err, null);
4064
+ }
4065
+ throw err;
4066
+ }
4067
+ await this.settleCommitted(tenantId, scopeId, liveSince, null);
4068
+ return record;
4069
+ });
4070
+ }
3868
4071
  // -- attachment text (#1575) ---------------------------------------------------
3869
4072
  /**
3870
4073
  * Extracted-text search as `ctx`'s subject: authorized first — the check `open` makes,
@@ -5181,8 +5384,9 @@ options = {}) {
5181
5384
  : this.applyPendingMigrations();
5182
5385
  // K-69: only after the pass SUCCEEDED — a scope failing closed asks for nothing, and the
5183
5386
  // rejection passes through untouched.
5184
- this.migrationPromise = pass.then((applied) => {
5185
- this.askReconcileOnWake(upgrade);
5387
+ this.migrationPromise = pass.then(async (applied) => {
5388
+ if (this.askReconcileOnWake(upgrade))
5389
+ await this.wakeForReconcileAsk();
5186
5390
  return applied;
5187
5391
  });
5188
5392
  }
@@ -5192,19 +5396,57 @@ options = {}) {
5192
5396
  * K-69 (rfc/tenant-scale.md §7.5): the first wake on a version this scope has not asked about
5193
5397
  * writes one `provision-reconcile` intent (`reconcileOnWake`). Never throws: a scope that cannot
5194
5398
  * ask is still reached by the batched pass, and failing the request over it protects nothing.
5399
+ * True when it wrote the intent.
5195
5400
  */
5196
5401
  askReconcileOnWake(upgrade) {
5197
5402
  try {
5198
5403
  const asked = reconcileOnWake(this.sql, this.env.SUBSTRAT_VERSION_ID, upgrade, new Date().toISOString());
5199
- if (asked === 'requested')
5200
- this.reconcileAskUnsignalled = true;
5404
+ if (asked !== 'requested')
5405
+ return false;
5406
+ this.reconcileAskUnsignalled = true;
5407
+ return true;
5201
5408
  }
5202
5409
  catch (err) {
5203
5410
  console.warn('reconcile-on-wake: could not ask; the batched pass is the backstop', {
5204
5411
  error: err instanceof Error ? err.message : String(err),
5205
5412
  });
5413
+ return false;
5414
+ }
5415
+ }
5416
+ /**
5417
+ * K-69 (#3435): the ask is written by the migration pass, not by a committing door, so neither
5418
+ * of the commit's two kicks sees it. The router's flag rides only a committed invoke's response
5419
+ * (`takeReconcileAsk`), and a wake whose requests commit nothing (page loads, reads, OIDC
5420
+ * discovery) never carries one; the scope's own wake (`noteScopeWake`) runs only after a commit.
5421
+ * Left to those, the ask waited for the next pass. So the pass arms the scope's wake itself, as
5422
+ * a commit that enqueued an intent would: its alarm asks for the drain within seconds, whatever
5423
+ * request woke the scope. The router's flag still goes out on a committed invoke, which is
5424
+ * sooner; the alarm then finds the intent settled and asks nothing.
5425
+ *
5426
+ * The scope names itself as its stubs do (`idFromName(scopeId)`), and its tenant as the pair
5427
+ * check reads it (`tenantVerdict`): the `provisioned_for` receipt, or, on a scope from before
5428
+ * receipts, the one tenant its role rows name. Missing either, it arms nothing: the flag and the
5429
+ * pass remain. Never throws, as `noteScopeWake` does not.
5430
+ */
5431
+ async wakeForReconcileAsk() {
5432
+ try {
5433
+ const tenant = tenantIdOf.safeParse(this.provisionedFor() ?? this.soleRoleTenant());
5434
+ const scope = scopeIdOf.safeParse(this.ctx.id.name);
5435
+ if (!tenant.success || !scope.success)
5436
+ return;
5437
+ await this.noteScopeWake(tenant.data, scope.data);
5438
+ }
5439
+ catch (err) {
5440
+ console.error('reconcile-on-wake: scope wake not armed; the router flag and the pass remain', err);
5206
5441
  }
5207
5442
  }
5443
+ /** The one tenant this scope's role rows name, or null for none or several (`tenantVerdict`'s `inferred`). */
5444
+ soleRoleTenant() {
5445
+ if (!this.hasTable('_substrat_roles'))
5446
+ return null;
5447
+ const rows = this.sql.exec('SELECT DISTINCT tenant_id FROM _substrat_roles LIMIT 2').toArray();
5448
+ return rows.length === 1 ? rows[0].tenant_id : null;
5449
+ }
5208
5450
  /** K-69: 1 once, on the first committed invoke after the wake asked, so its response flags a drain. */
5209
5451
  takeReconcileAsk() {
5210
5452
  if (!this.reconcileAskUnsignalled)
@@ -5667,7 +5909,7 @@ options = {}) {
5667
5909
  invocationId = null) {
5668
5910
  if (this.pendingConnectorDispatches() >= MAX_PENDING_CONNECTOR_DISPATCHES)
5669
5911
  return null;
5670
- const id = platformRequestId.parse(ulid());
5912
+ const id = platformRequestId.parse(this.mintIntentId());
5671
5913
  // K-42: the intent inherits the SOURCE EVENT's stamp rather than being written
5672
5914
  // unstamped. Nobody is impersonating at this moment — the drain runs long after
5673
5915
  // the session's invoke returned — but the intent exists BECAUSE of an event that
@@ -5684,8 +5926,10 @@ options = {}) {
5684
5926
  // K-69: this intent is enqueued by the coordinator after the commit's own wake was armed, so
5685
5927
  // it arms one too, under the ids its source event carries. Both writes above are made before
5686
5928
  // this await, as one unit.
5687
- if (source)
5929
+ if (source) {
5688
5930
  await this.noteScopeWake(tenantIdOf.parse(source.tenant_id), scopeIdOf.parse(source.scope_id));
5931
+ await this.handOffCommitted(tenantIdOf.parse(source.tenant_id), scopeIdOf.parse(source.scope_id));
5932
+ }
5689
5933
  return id;
5690
5934
  }
5691
5935
  /** #3365: the routed connector deliveries this scope holds pending — their own room. */
@@ -5739,7 +5983,7 @@ options = {}) {
5739
5983
  if (counts.c >= MAX_PENDING_PLATFORM_REQUESTS || (counts.k ?? 0) >= MAX_PENDING_SWEEP_RUNS) {
5740
5984
  return null;
5741
5985
  }
5742
- const id = platformRequestId.parse(ulid());
5986
+ const id = platformRequestId.parse(this.mintIntentId());
5743
5987
  this.sql.exec(`INSERT INTO _substrat_platform_requests
5744
5988
  (id, kind, payload, requested_by, impersonation, status, attempts, requested_at)
5745
5989
  VALUES (?, ?, ?, ?, NULL, 'pending', 0, ?)`, id, SWEEP_RUNS_KIND, payload, requestedBy, instant.parse(new Date().toISOString()));
@@ -7447,12 +7691,39 @@ options = {}) {
7447
7691
  // one reads a failure as a reply missing its counts and refuses before the key, which is
7448
7692
  // the safe reading.
7449
7693
  try {
7450
- return this.revision.transactionSync(() => this.redactSubjectInTransaction(subjectId, at));
7694
+ const counts = this.revision.transactionSync(() => this.redactSubjectInTransaction(subjectId, at));
7695
+ // #3484: the broker's copies, after the spine (so a handoff that reads the outbox from here on
7696
+ // reads it redacted) and before this answers, so before the coordinator reaches the key. A
7697
+ // broker that cannot be reached answers a failure, and the erasure is refused before the key.
7698
+ await this.eraseSubjectFromBroker(subjectId, at);
7699
+ return counts;
7451
7700
  }
7452
7701
  catch (err) {
7453
7702
  return { failure: toWireFailure(err) };
7454
7703
  }
7455
7704
  }
7705
+ /**
7706
+ * #3484: this scope's subject erasure reaching its delivery broker, whenever the script binds
7707
+ * one: whatever a handoff switch says, since a broker keeps what it took while it was on.
7708
+ *
7709
+ * The broker and the ids its messages are kept under are named first from the handoff state:
7710
+ * the (tenant, scope) every handoff of this scope used, written before its first broker call. A
7711
+ * scope whose state is gone (a restore) falls back to its own identity, its `provisioned_for`
7712
+ * receipt and its object name, as `wakeForReconcileAsk` reads them. So `redactSubject` takes no
7713
+ * new argument, and a coordinator of any version reaches the broker. A scope that can name it by
7714
+ * neither refuses: fail closed, before the key.
7715
+ */
7716
+ async eraseSubjectFromBroker(subjectId, at) {
7717
+ if (!this.env.SUBSTRAT_DELIVERY_BROKER)
7718
+ return;
7719
+ const handed = (await this.ctx.storage.get(DELIVERY_HANDOFF_KEY)) ?? null;
7720
+ const tenant = tenantIdOf.safeParse(handed?.tenantId ?? this.provisionedFor() ?? this.soleRoleTenant());
7721
+ const scope = scopeIdOf.safeParse(handed?.scopeId ?? this.ctx.id.name);
7722
+ if (!tenant.success || !scope.success) {
7723
+ throw substratError('unavailable', 'subject erasure: this scope cannot name its delivery broker, so its copies were not erased');
7724
+ }
7725
+ await this.deliveryBroker(tenant.data).eraseSubject({ tenantId: tenant.data, scopeId: scope.data, subjectId, at });
7726
+ }
7456
7727
  /**
7457
7728
  * One page of what this scope holds about one data subject (GDPR Art. 15, D-74): the kernel's
7458
7729
  * `readSubjectPage` over the same erasure plans `redactSubject` runs, so access reads exactly
@@ -7973,7 +8244,7 @@ options = {}) {
7973
8244
  .exec(`SELECT COUNT(*) AS c FROM _substrat_platform_requests WHERE status = 'pending' AND requested_by != ?`, CONNECTOR_DISPATCH_REQUESTED_BY)
7974
8245
  .toArray()[0].c);
7975
8246
  assertPlatformRequestRoom(pending);
7976
- const id = platformRequestId.parse(ulid());
8247
+ const id = platformRequestId.parse(this.mintIntentId());
7977
8248
  const requestedBy = systemActor ?? derivedActor;
7978
8249
  sql.exec(`INSERT INTO _substrat_platform_requests
7979
8250
  (id, kind, payload, requested_by, impersonation, status, attempts, requested_at)