@task-master/cadence 0.0.0-stage → 0.2.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.cjs ADDED
@@ -0,0 +1,1957 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DEFAULTS: () => DEFAULTS,
24
+ EnqueueRejected: () => EnqueueRejected,
25
+ EnqueueUncertain: () => EnqueueUncertain,
26
+ ProgrammingError: () => ProgrammingError,
27
+ TERMINAL_OUTCOME_KINDS: () => TERMINAL_OUTCOME_KINDS,
28
+ activateReservation: () => activateReservation,
29
+ addSuspension: () => addSuspension,
30
+ admissibility: () => admissibility,
31
+ admit: () => admit,
32
+ assertTerminal: () => assertTerminal,
33
+ attemptBudget: () => attemptBudget,
34
+ attentionReasons: () => attentionReasons,
35
+ backoffMs: () => backoffMs,
36
+ blockRun: () => blockRun,
37
+ clearAttention: () => clearAttention,
38
+ completionOutcome: () => completionOutcome,
39
+ computeWindow: () => computeWindow,
40
+ connect: () => connect,
41
+ countsTowardQuarantine: () => countsTowardQuarantine,
42
+ defaultIntegrationPolicy: () => defaultIntegrationPolicy,
43
+ defaultTrafficPolicy: () => defaultTrafficPolicy,
44
+ downloadNext: () => downloadNext,
45
+ ensureIndexes: () => ensureIndexes,
46
+ expireSubmissionClaim: () => expireSubmissionClaim,
47
+ finalize: () => finalize,
48
+ grantIsLive: () => grantIsLive,
49
+ isEnqueueRejected: () => isEnqueueRejected,
50
+ isEnqueueUncertain: () => isEnqueueUncertain,
51
+ isRepetitionSafe: () => isRepetitionSafe,
52
+ isUnitComplete: () => isUnitComplete,
53
+ markUnknown: () => markUnknown,
54
+ nextSweepAt: () => nextSweepAt,
55
+ outcomeFor: () => outcomeFor,
56
+ patchAvailability: () => patchAvailability,
57
+ plan: () => plan,
58
+ pollRun: () => pollRun,
59
+ publishOutbox: () => publishOutbox,
60
+ raiseAttention: () => raiseAttention,
61
+ reconcile: () => reconcile,
62
+ refreshEligibility: () => refreshEligibility,
63
+ refreshIntegrationEligibility: () => refreshIntegrationEligibility,
64
+ removeSuspension: () => removeSuspension,
65
+ requestDispositionFor: () => requestDispositionFor,
66
+ runId: () => runId,
67
+ setTrafficPolicy: () => setTrafficPolicy,
68
+ submitKickoff: () => submitKickoff,
69
+ terminalRunState: () => terminalRunState,
70
+ trafficStateAt: () => trafficStateAt,
71
+ unblockRun: () => unblockRun
72
+ });
73
+ module.exports = __toCommonJS(index_exports);
74
+
75
+ // src/config.ts
76
+ var DEFAULTS = {
77
+ /** How long a publisher may hold an outbox entry before reclamation. */
78
+ outboxClaimTtlMs: 6e4,
79
+ /** How long a worker may hold a submission claim before reconciliation resolves it. */
80
+ submissionClaimTtlMs: 6e5,
81
+ /** No observable progress for this long makes a run a candidate for termination. */
82
+ noProgressDeadlineMs: 36e5
83
+ };
84
+ function defaultIntegrationPolicy(overrides = {}) {
85
+ return {
86
+ defaultSince: /* @__PURE__ */ new Date("2024-01-01T00:00:00.000Z"),
87
+ overlapBufferMs: 3e5,
88
+ maxCatchUpWindowMs: 6048e5,
89
+ failureThreshold: 3,
90
+ emptyStreakThreshold: 10,
91
+ backoffBaseMs: 6e4,
92
+ backoffMaxMs: 36e5,
93
+ maxAttempts: 5,
94
+ partialPolicy: "advance_with_repair",
95
+ ...overrides
96
+ };
97
+ }
98
+ function defaultTrafficPolicy(overrides = {}) {
99
+ return {
100
+ version: 1,
101
+ timezone: "America/New_York",
102
+ enforcement: "kickoff_only",
103
+ rules: [],
104
+ minRemainingWindowMs: 9e5,
105
+ resumeJitterMs: 9e5,
106
+ ...overrides
107
+ };
108
+ }
109
+
110
+ // src/db/collections.ts
111
+ var import_mongodb = require("mongodb");
112
+ async function connect(uri, dbName) {
113
+ const client = new import_mongodb.MongoClient(uri);
114
+ await client.connect();
115
+ const db = client.db(dbName);
116
+ const c = {
117
+ client,
118
+ db,
119
+ integrations: db.collection("integration"),
120
+ units: db.collection("unit"),
121
+ requests: db.collection("request"),
122
+ runs: db.collection("run"),
123
+ outbox: db.collection("dispatchOutbox"),
124
+ coverage: db.collection("coverage"),
125
+ repairs: db.collection("repairItem")
126
+ };
127
+ await ensureIndexes(c);
128
+ return c;
129
+ }
130
+ async function ensureIndexes(c) {
131
+ await c.units.createIndex(
132
+ { integrationId: 1, adminState: 1, executionState: 1, scheduledNextEligibleAt: 1 },
133
+ { name: "due_units" }
134
+ );
135
+ await c.requests.createIndex(
136
+ { dedupFingerprint: 1 },
137
+ {
138
+ name: "open_request_dedup",
139
+ unique: true,
140
+ partialFilterExpression: { isOpen: true }
141
+ }
142
+ );
143
+ await c.requests.createIndex(
144
+ { integrationId: 1, unitKey: 1, kind: 1, isOpen: 1 },
145
+ { name: "open_by_unit_kind" }
146
+ );
147
+ await c.runs.createIndex({ unitKey: 1, appliedAt: 1 }, { name: "open_runs" });
148
+ await c.outbox.createIndex({ state: 1, nextAttemptAt: 1 }, { name: "publishable" });
149
+ await c.repairs.createIndex({ integrationId: 1, state: 1 }, { name: "open_repairs" });
150
+ await c.repairs.createIndex(
151
+ { unitKey: 1, cause: 1, "interval.from": 1, "interval.to": 1 },
152
+ { name: "open_repair_dedup", unique: true, partialFilterExpression: { state: "open" } }
153
+ );
154
+ }
155
+
156
+ // src/domain/outcomes.ts
157
+ var ProgrammingError = class extends Error {
158
+ };
159
+ var Abort = class extends Error {
160
+ };
161
+ var TERMINAL_OUTCOME_KINDS = [
162
+ "succeeded",
163
+ "succeeded_empty",
164
+ "partial",
165
+ "failed",
166
+ "terminated_confirmed"
167
+ ];
168
+ var TERMINAL = new Set(TERMINAL_OUTCOME_KINDS);
169
+ function assertTerminal(outcome) {
170
+ if (!TERMINAL.has(outcome.kind)) {
171
+ throw new ProgrammingError(`uncertainty_is_not_terminal:${outcome.kind}`);
172
+ }
173
+ }
174
+ function terminalRunState(kind) {
175
+ switch (kind) {
176
+ case "succeeded":
177
+ return "succeeded";
178
+ case "succeeded_empty":
179
+ return "succeeded_empty";
180
+ case "partial":
181
+ return "partial";
182
+ case "failed":
183
+ return "failed";
184
+ case "terminated_confirmed":
185
+ return "terminated_confirmed";
186
+ }
187
+ }
188
+ function requestDispositionFor(outcome, opts) {
189
+ switch (outcome.kind) {
190
+ case "succeeded":
191
+ case "succeeded_empty":
192
+ return { state: "satisfied", isOpen: false };
193
+ case "partial":
194
+ return opts.safe ? { state: "satisfied_with_repair", isOpen: false } : { state: "blocked", isOpen: true };
195
+ case "failed":
196
+ return opts.attemptsRemaining ? { state: "open", isOpen: true } : { state: "failed", isOpen: false };
197
+ case "terminated_confirmed":
198
+ return opts.safe ? { state: "open", isOpen: true } : { state: "blocked", isOpen: true };
199
+ }
200
+ }
201
+ function isRepetitionSafe(cls) {
202
+ return cls === "idempotent_acquisition" || cls === "idempotent_effect";
203
+ }
204
+ function countsTowardQuarantine(cls) {
205
+ return cls !== "throttled";
206
+ }
207
+
208
+ // src/domain/ids.ts
209
+ var import_node_crypto = require("crypto");
210
+ function compactHash(value) {
211
+ return (0, import_node_crypto.createHash)("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 24);
212
+ }
213
+ function scopeHash(scope) {
214
+ return compactHash({
215
+ resourceTypes: [...scope.resourceTypes].sort(),
216
+ typeFilters: [...scope.typeFilters].sort(),
217
+ patients: scope.patients ? [...scope.patients].sort() : null
218
+ });
219
+ }
220
+ function windowFingerprint(window, scope) {
221
+ return compactHash({
222
+ from: window.from.toISOString(),
223
+ to: window.to ? window.to.toISOString() : null,
224
+ domain: window.domain,
225
+ scope: scopeHash(scope)
226
+ });
227
+ }
228
+ function dedupFingerprint(integrationId, unitKey, kind, window, scope) {
229
+ return compactHash({ integrationId, unitKey, kind, w: windowFingerprint(window, scope) });
230
+ }
231
+ function runId(requestId, attemptNumber) {
232
+ return `${requestId}:${attemptNumber}`;
233
+ }
234
+ function newToken() {
235
+ return (0, import_node_crypto.randomUUID)();
236
+ }
237
+
238
+ // src/domain/time.ts
239
+ var FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T00:00:00.000Z");
240
+ function addMs(d, ms) {
241
+ return new Date(d.getTime() + ms);
242
+ }
243
+ function maxDate(...ds) {
244
+ let out = null;
245
+ for (const d of ds) if (d && (!out || d > out)) out = d;
246
+ return out;
247
+ }
248
+ function minDate(...ds) {
249
+ let out = null;
250
+ for (const d of ds) if (d && (!out || d < out)) out = d;
251
+ return out;
252
+ }
253
+ function mergeIntervals(ivs) {
254
+ const sorted = [...ivs].filter((iv) => iv.to > iv.from).sort((a, b) => a.from.getTime() - b.from.getTime());
255
+ const out = [];
256
+ for (const iv of sorted) {
257
+ const last = out[out.length - 1];
258
+ if (last && iv.from <= last.to) {
259
+ if (iv.to > last.to) last.to = iv.to;
260
+ } else {
261
+ out.push({ from: iv.from, to: iv.to });
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+ function intersectionMs(ivs, from, to) {
267
+ let total = 0;
268
+ for (const iv of mergeIntervals(ivs)) {
269
+ const s = Math.max(iv.from.getTime(), from.getTime());
270
+ const e = Math.min(iv.to.getTime(), to.getTime());
271
+ if (e > s) total += e - s;
272
+ }
273
+ return total;
274
+ }
275
+ var FORMATTERS = /* @__PURE__ */ new Map();
276
+ function formatter(tz) {
277
+ let f = FORMATTERS.get(tz);
278
+ if (!f) {
279
+ f = new Intl.DateTimeFormat("en-US", {
280
+ timeZone: tz,
281
+ hourCycle: "h23",
282
+ year: "numeric",
283
+ month: "2-digit",
284
+ day: "2-digit",
285
+ hour: "2-digit",
286
+ minute: "2-digit",
287
+ second: "2-digit"
288
+ });
289
+ FORMATTERS.set(tz, f);
290
+ }
291
+ return f;
292
+ }
293
+ function wallPartsAt(instant, tz) {
294
+ const parts = formatter(tz).formatToParts(instant);
295
+ const get = (type) => {
296
+ const p = parts.find((x) => x.type === type);
297
+ if (!p) throw new Error(`missing ${type} for zone ${tz}`);
298
+ return Number(p.value);
299
+ };
300
+ return {
301
+ year: get("year"),
302
+ month: get("month"),
303
+ day: get("day"),
304
+ hour: get("hour") % 24,
305
+ minute: get("minute"),
306
+ second: get("second")
307
+ };
308
+ }
309
+ function asUtcMs(c) {
310
+ return Date.UTC(c.year, c.month - 1, c.day, c.hour, c.minute, c.second ?? 0);
311
+ }
312
+ function zonedToInstant(c, tz, prefer) {
313
+ const naive = asUtcMs(c);
314
+ const guess1 = naive - offsetMsAt(new Date(naive), tz);
315
+ const guess2 = naive - offsetMsAt(new Date(guess1), tz);
316
+ const candidates = Array.from(/* @__PURE__ */ new Set([guess1, guess2])).sort((a, b) => a - b);
317
+ const valid = candidates.filter((t) => wallEquals(new Date(t), c, tz));
318
+ if (valid.length === 0) {
319
+ return new Date(Math.max(...candidates));
320
+ }
321
+ const chosen = prefer === "earlier" ? valid[0] : valid[valid.length - 1];
322
+ return new Date(chosen);
323
+ }
324
+ function offsetMsAt(instant, tz) {
325
+ return asUtcMs(wallPartsAt(instant, tz)) - instant.getTime();
326
+ }
327
+ function wallEquals(instant, c, tz) {
328
+ const w = wallPartsAt(instant, tz);
329
+ return w.year === c.year && w.month === c.month && w.day === c.day && w.hour === c.hour && w.minute === c.minute;
330
+ }
331
+ function parseHhMm(s) {
332
+ const m = /^(\d{2}):(\d{2})$/.exec(s);
333
+ if (!m) throw new Error(`invalid HH:MM: ${s}`);
334
+ return { hour: Number(m[1]), minute: Number(m[2]) };
335
+ }
336
+ function addCivilDays(d, n) {
337
+ const t = new Date(Date.UTC(d.year, d.month - 1, d.day) + n * 864e5);
338
+ return { year: t.getUTCFullYear(), month: t.getUTCMonth() + 1, day: t.getUTCDate() };
339
+ }
340
+ function dayOfWeek(d) {
341
+ return new Date(Date.UTC(d.year, d.month - 1, d.day)).getUTCDay();
342
+ }
343
+ function localDaysBetween(from, to, tz) {
344
+ const start = wallPartsAt(from, tz);
345
+ const end = wallPartsAt(to, tz);
346
+ const out = [];
347
+ let cur = Date.UTC(start.year, start.month - 1, start.day) - 864e5;
348
+ const last = Date.UTC(end.year, end.month - 1, end.day);
349
+ while (cur <= last) {
350
+ const d = new Date(cur);
351
+ out.push({ year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() });
352
+ cur += 864e5;
353
+ }
354
+ return out;
355
+ }
356
+
357
+ // src/engine/traffic.ts
358
+ function materialize(policy, from, to) {
359
+ const out = [];
360
+ const days = localDaysBetween(from, to, policy.timezone);
361
+ for (const day of days) {
362
+ for (const rule of policy.rules) {
363
+ if (!rule.days.includes(dayOfWeek(day))) continue;
364
+ const f = parseHhMm(rule.from);
365
+ const t = parseHhMm(rule.to);
366
+ const spansMidnight = t.hour * 60 + t.minute <= f.hour * 60 + f.minute;
367
+ const endDay = spansMidnight ? addCivilDays(day, 1) : day;
368
+ out.push({
369
+ ruleId: rule.id,
370
+ effect: rule.effect,
371
+ appliesTo: rule.appliesTo,
372
+ // Opposite preferences: a denial must not shrink across a DST transition.
373
+ from: zonedToInstant({ ...day, hour: f.hour, minute: f.minute }, policy.timezone, "earlier"),
374
+ to: zonedToInstant({ ...endDay, hour: t.hour, minute: t.minute }, policy.timezone, "later")
375
+ });
376
+ }
377
+ }
378
+ return out.filter((iv) => iv.to > from && iv.from < to).sort((a, b) => a.from.getTime() - b.from.getTime());
379
+ }
380
+ var HORIZON_MS = 14 * 864e5;
381
+ var LOOKBACK_MS = 2 * 864e5;
382
+ function appliesToOp(iv, op) {
383
+ return iv.appliesTo === "all" || iv.appliesTo === op;
384
+ }
385
+ function trafficStateAt(policy, now, op) {
386
+ const open = { denied: false, opensAt: null, remainingMs: Number.POSITIVE_INFINITY };
387
+ if (policy.enforcement === "throughput_only") return open;
388
+ if (policy.enforcement === "kickoff_only" && op !== "kickoff") return open;
389
+ const ivs = materialize(policy, addMs(now, -LOOKBACK_MS), addMs(now, HORIZON_MS)).filter(
390
+ (iv) => appliesToOp(iv, op)
391
+ );
392
+ const denies = ivs.filter((iv) => iv.effect === "deny");
393
+ const allows = ivs.filter((iv) => iv.effect === "allow");
394
+ const covering = (list, at) => list.find((iv) => iv.from <= at && at < iv.to);
395
+ const activeDeny = covering(denies, now);
396
+ if (activeDeny && !covering(allows, now)) {
397
+ return { denied: true, opensAt: endOfDenial(denies, allows, activeDeny), remainingMs: 0 };
398
+ }
399
+ const nextDeny = denies.find((iv) => iv.from > now && !covering(allows, iv.from));
400
+ return {
401
+ denied: false,
402
+ opensAt: null,
403
+ remainingMs: nextDeny ? nextDeny.from.getTime() - now.getTime() : Number.POSITIVE_INFINITY
404
+ };
405
+ }
406
+ function endOfDenial(denies, allows, start) {
407
+ let end = start.to;
408
+ let moved = true;
409
+ while (moved) {
410
+ moved = false;
411
+ for (const iv of denies) {
412
+ if (iv.from <= end && iv.to > end) {
413
+ end = iv.to;
414
+ moved = true;
415
+ }
416
+ }
417
+ }
418
+ const rescuing = allows.find((a) => a.from <= end && end < a.to);
419
+ return rescuing ? rescuing.from : end;
420
+ }
421
+
422
+ // src/engine/admissibility.ts
423
+ var no = (reason, until = null) => ({
424
+ admissible: false,
425
+ reason,
426
+ until
427
+ });
428
+ function activeSuspension(suspensions, now) {
429
+ for (const s of suspensions) {
430
+ if (s.from <= now && (s.until === null || now < s.until)) return s;
431
+ }
432
+ return null;
433
+ }
434
+ function admissibility(unit, integration, now, kind) {
435
+ if (unit.adminState !== "active") return no("admin_state");
436
+ if (integration.vendorCooldownUntil && now < integration.vendorCooldownUntil) {
437
+ return no("vendor_cooldown", integration.vendorCooldownUntil);
438
+ }
439
+ const a = unit.availability;
440
+ if (kind === "scheduled" && a.dispatchFrom && now < a.dispatchFrom) {
441
+ return no("before_dispatch_from", a.dispatchFrom);
442
+ }
443
+ if (a.dispatchUntil && now >= a.dispatchUntil && kind !== "adhoc") {
444
+ const target = a.dataUntil ?? a.dispatchUntil;
445
+ const marker = unit.watermark.scheduledThrough;
446
+ const incomplete = marker === null || marker < target;
447
+ if (!incomplete) return no("unit_complete");
448
+ const mayCatchUp = kind === "scheduled" && a.allowFinalCatchUp;
449
+ if (!mayCatchUp) return no("after_dispatch_until");
450
+ }
451
+ const sus = activeSuspension(a.suspensions, now);
452
+ if (sus && (sus.appliesTo === "all" || kind === "scheduled")) {
453
+ return no("suspended", sus.until);
454
+ }
455
+ const win = trafficStateAt(integration.trafficPolicy, now, "kickoff");
456
+ if (win.denied) return no("vendor_traffic_window", win.opensAt);
457
+ if (integration.trafficPolicy.enforcement === "all_vendor_traffic" && win.remainingMs < integration.trafficPolicy.minRemainingWindowMs) {
458
+ return no("insufficient_remaining_window", null);
459
+ }
460
+ return { admissible: true };
461
+ }
462
+
463
+ // src/engine/window.ts
464
+ function computeWindow(unit, integration, now) {
465
+ const { policy, profile } = integration;
466
+ const a = unit.availability;
467
+ const floor = maxDate(policy.defaultSince, a.dataFrom) ?? policy.defaultSince;
468
+ const base = unit.watermark.seeded && unit.watermark.scheduledThrough ? addMs(unit.watermark.scheduledThrough, -policy.overlapBufferMs) : floor;
469
+ const from = maxDate(base, floor) ?? floor;
470
+ const hardStop = a.dataUntil;
471
+ let to = profile.until ? minDate(now, hardStop) ?? now : null;
472
+ const span = (to ?? now).getTime() - from.getTime();
473
+ const oversized = span > policy.maxCatchUpWindowMs;
474
+ let capped = false;
475
+ let capUnenforceable = false;
476
+ let deferred = null;
477
+ if (oversized) {
478
+ if (profile.until) {
479
+ const cappedTo = addMs(from, policy.maxCatchUpWindowMs);
480
+ deferred = { from: cappedTo, to: to ?? now };
481
+ to = cappedTo;
482
+ capped = true;
483
+ } else {
484
+ capUnenforceable = true;
485
+ }
486
+ }
487
+ return { window: { from, to, domain: "modification_time" }, capped, capUnenforceable, deferred };
488
+ }
489
+
490
+ // src/engine/marker.ts
491
+ function advanceMarker(set, run, unit, outcome, now) {
492
+ if (run.kind !== "scheduled") return;
493
+ if (outcome.kind !== "succeeded" && outcome.kind !== "succeeded_empty") return;
494
+ const basis = outcome.transactionTime ?? run.window.to ?? run.admittedAt;
495
+ const basisLabel = outcome.transactionTime ? "transaction_time" : "client_start_time";
496
+ let boundary = basis;
497
+ if (run.window.to) boundary = minDate(boundary, run.window.to) ?? boundary;
498
+ const dataUntil = run.admissionSnapshot.dataUntil;
499
+ if (dataUntil) boundary = minDate(boundary, dataUntil) ?? boundary;
500
+ const prior = unit.watermark.scheduledThrough;
501
+ if (prior && boundary <= prior) return;
502
+ set["watermark.scheduledThrough"] = boundary;
503
+ set["watermark.basis"] = basisLabel;
504
+ set["watermark.seeded"] = true;
505
+ set["watermark.updatedAt"] = now;
506
+ }
507
+ function isUnitComplete(unit) {
508
+ const a = unit.availability;
509
+ const target = a.dataUntil ?? a.dispatchUntil;
510
+ if (!target) return false;
511
+ const marker = unit.watermark.scheduledThrough;
512
+ return marker !== null && marker >= target;
513
+ }
514
+
515
+ // src/engine/plan.ts
516
+ function grantIsLive(request, againstRunId = request.lastRunId) {
517
+ const g = request.operatorGrant;
518
+ if (!g || g.consumedAt !== null) return false;
519
+ return g.appliesToRunId === againstRunId;
520
+ }
521
+ function attemptBudget(request, againstRunId = request.lastRunId) {
522
+ const extra = grantIsLive(request, againstRunId) ? request.operatorGrant?.extraAttempts ?? 0 : 0;
523
+ return request.maxAttempts + extra;
524
+ }
525
+ async function plan(c, integrationId, now) {
526
+ const integration = await c.integrations.findOne({ _id: integrationId });
527
+ if (!integration) throw new Error(`unknown integration ${integrationId}`);
528
+ const proposals = [];
529
+ const skipped = [];
530
+ const taken = /* @__PURE__ */ new Set();
531
+ const units = await c.units.find({
532
+ integrationId,
533
+ adminState: "active",
534
+ activeRunId: null,
535
+ executionState: { $in: ["idle", "backoff"] },
536
+ scheduledNextEligibleAt: { $lte: now }
537
+ }).toArray();
538
+ for (const unit of units) {
539
+ const adm = admissibility(unit, integration, now, "scheduled");
540
+ if (!adm.admissible) {
541
+ skipped.push({ unitKey: unit._id, reason: adm.reason });
542
+ continue;
543
+ }
544
+ const p = await scheduledProposal(c, unit, integration, now);
545
+ if ("reason" in p) {
546
+ skipped.push({ unitKey: unit._id, reason: p.reason });
547
+ } else {
548
+ proposals.push(p);
549
+ taken.add(unit._id);
550
+ }
551
+ }
552
+ const openRequests = await c.requests.find({
553
+ integrationId,
554
+ kind: { $in: ["adhoc", "repair"] },
555
+ state: "open",
556
+ isOpen: true,
557
+ activeRunId: null,
558
+ nextAttemptAt: { $lte: now }
559
+ }).toArray();
560
+ for (const request of openRequests) {
561
+ if (request.attemptCounter >= attemptBudget(request)) continue;
562
+ if (taken.has(request.unitKey)) {
563
+ skipped.push({ unitKey: request.unitKey, reason: "unit_already_proposed" });
564
+ continue;
565
+ }
566
+ const unit = await c.units.findOne({ _id: request.unitKey, activeRunId: null });
567
+ if (!unit) continue;
568
+ const adm = admissibility(unit, integration, now, request.kind);
569
+ if (!adm.admissible) {
570
+ skipped.push({ unitKey: unit._id, reason: adm.reason });
571
+ continue;
572
+ }
573
+ proposals.push({
574
+ integrationId,
575
+ unitKey: unit._id,
576
+ kind: request.kind,
577
+ window: request.window,
578
+ scope: request.scope,
579
+ reuseRequestId: request._id,
580
+ consumesGrant: grantIsLive(request),
581
+ effectiveBudget: integration.capacity.budget,
582
+ capUnenforceable: false,
583
+ deferred: null,
584
+ repairId: request.repairId
585
+ });
586
+ taken.add(unit._id);
587
+ }
588
+ const workedRepairs = new Set(
589
+ (await c.requests.find({ integrationId, kind: "repair", isOpen: true, repairId: { $ne: null } }).toArray()).map((r) => r.repairId.toHexString())
590
+ );
591
+ const repairs = await c.repairs.find({ integrationId, state: "open" }).toArray();
592
+ for (const repair of repairs) {
593
+ if (workedRepairs.has(repair._id.toHexString())) continue;
594
+ if (taken.has(repair.unitKey)) {
595
+ skipped.push({ unitKey: repair.unitKey, reason: "unit_already_proposed" });
596
+ continue;
597
+ }
598
+ const unit = await c.units.findOne({
599
+ _id: repair.unitKey,
600
+ adminState: "active",
601
+ activeRunId: null
602
+ });
603
+ if (!unit) continue;
604
+ const adm = admissibility(unit, integration, now, "repair");
605
+ if (!adm.admissible) {
606
+ skipped.push({ unitKey: unit._id, reason: adm.reason });
607
+ continue;
608
+ }
609
+ proposals.push({
610
+ integrationId,
611
+ unitKey: unit._id,
612
+ kind: "repair",
613
+ // A repair carries the interval it owes, not a window recomputed against `now`.
614
+ window: { from: repair.interval.from, to: repair.interval.to, domain: "modification_time" },
615
+ scope: repair.scope,
616
+ reuseRequestId: null,
617
+ consumesGrant: false,
618
+ effectiveBudget: integration.capacity.budget,
619
+ capUnenforceable: false,
620
+ deferred: null,
621
+ repairId: repair._id
622
+ });
623
+ taken.add(unit._id);
624
+ }
625
+ return { proposals, skipped };
626
+ }
627
+ async function scheduledProposal(c, unit, integration, now) {
628
+ const existing = await c.requests.findOne({
629
+ integrationId: integration._id,
630
+ unitKey: unit._id,
631
+ kind: "scheduled",
632
+ isOpen: true
633
+ });
634
+ if (existing) {
635
+ if (existing.activeRunId) return { reason: "request_in_flight" };
636
+ const live = grantIsLive(existing);
637
+ if (existing.attemptCounter >= attemptBudget(existing)) {
638
+ return { reason: "attempts_exhausted" };
639
+ }
640
+ if (existing.nextAttemptAt > now && !(live && existing.operatorGrant?.overridesBackoff)) {
641
+ return { reason: "backoff" };
642
+ }
643
+ return {
644
+ integrationId: integration._id,
645
+ unitKey: unit._id,
646
+ kind: "scheduled",
647
+ window: existing.window,
648
+ scope: existing.scope,
649
+ reuseRequestId: existing._id,
650
+ consumesGrant: live,
651
+ effectiveBudget: integration.capacity.budget,
652
+ capUnenforceable: false,
653
+ deferred: null,
654
+ repairId: null
655
+ };
656
+ }
657
+ const wp = computeWindow(unit, integration, now);
658
+ return {
659
+ integrationId: integration._id,
660
+ unitKey: unit._id,
661
+ kind: "scheduled",
662
+ window: wp.window,
663
+ scope: defaultScope(),
664
+ reuseRequestId: null,
665
+ consumesGrant: false,
666
+ effectiveBudget: integration.capacity.budget,
667
+ capUnenforceable: wp.capUnenforceable,
668
+ deferred: wp.deferred,
669
+ repairId: null
670
+ };
671
+ }
672
+ function defaultScope() {
673
+ return {
674
+ resourceTypes: ["Patient", "Observation"],
675
+ typeFilters: [],
676
+ typeFilterHash: "none",
677
+ patients: null
678
+ };
679
+ }
680
+
681
+ // src/engine/admit.ts
682
+ var import_mongodb2 = require("mongodb");
683
+ async function admit(c, p, now) {
684
+ const session = c.client.startSession();
685
+ let result = { admitted: false, reason: "not_attempted" };
686
+ try {
687
+ await session.withTransaction(async () => {
688
+ const cap = await c.integrations.updateOne(
689
+ {
690
+ _id: p.integrationId,
691
+ $expr: {
692
+ $lt: [
693
+ { $add: ["$capacity.reserved", "$capacity.active"] },
694
+ { $min: ["$capacity.budget", p.effectiveBudget] }
695
+ ]
696
+ }
697
+ },
698
+ { $inc: { "capacity.reserved": 1 } },
699
+ { session }
700
+ );
701
+ if (cap.matchedCount !== 1) throw new Abort("no_capacity");
702
+ const integration = await c.integrations.findOne({ _id: p.integrationId }, { session });
703
+ if (!integration) throw new Abort("unknown_integration");
704
+ const { request, attemptNumber } = p.reuseRequestId ? await claimRequest(c, p, p.reuseRequestId, now, session) : await createRequest(c, p, now, session);
705
+ const runId2 = runId(request._id.toHexString(), attemptNumber);
706
+ await c.requests.updateOne(
707
+ { _id: request._id, activeRunId: null },
708
+ { $set: { activeRunId: runId2, updatedAt: now } },
709
+ { session }
710
+ );
711
+ const unitFilter = {
712
+ _id: p.unitKey,
713
+ adminState: "active",
714
+ activeRunId: null,
715
+ ...p.kind === "scheduled" ? { scheduledNextEligibleAt: { $lte: now } } : {}
716
+ };
717
+ const unit = await c.units.findOneAndUpdate(
718
+ unitFilter,
719
+ { $set: { activeRunId: runId2, executionState: "dispatching" } },
720
+ { session, returnDocument: "before" }
721
+ );
722
+ if (!unit) throw new Abort("unit_not_claimable");
723
+ const adm = admissibility(unit, integration, now, p.kind);
724
+ if (!adm.admissible) throw new Abort(`inadmissible:${adm.reason}`);
725
+ const run = buildRun(runId2, request, unit, integration, p, attemptNumber, now);
726
+ await c.runs.insertOne(run, { session });
727
+ await c.outbox.insertOne(
728
+ {
729
+ _id: new import_mongodb2.ObjectId(),
730
+ runId: runId2,
731
+ integrationId: p.integrationId,
732
+ payload: { runId: runId2, unitKey: p.unitKey, kind: p.kind },
733
+ state: "pending",
734
+ nextAttemptAt: now,
735
+ claimToken: null,
736
+ claimedBy: null,
737
+ claimedAt: null,
738
+ claimExpiresAt: null
739
+ },
740
+ { session }
741
+ );
742
+ result = { admitted: true, runId: runId2, requestId: request._id, attemptNumber };
743
+ });
744
+ } catch (e) {
745
+ if (e instanceof Abort) return { admitted: false, reason: e.message };
746
+ if (isDuplicateKey(e)) return { admitted: false, reason: "duplicate_open_request" };
747
+ throw e;
748
+ } finally {
749
+ await session.endSession();
750
+ }
751
+ return result;
752
+ }
753
+ async function claimRequest(c, p, requestId, now, session) {
754
+ const budgetExpr = {
755
+ $lt: [
756
+ "$attemptCounter",
757
+ {
758
+ $add: [
759
+ "$maxAttempts",
760
+ {
761
+ $cond: [
762
+ {
763
+ $and: [
764
+ { $eq: [{ $ifNull: ["$operatorGrant.consumedAt", null] }, null] },
765
+ { $eq: [{ $ifNull: ["$operatorGrant.appliesToRunId", null] }, "$lastRunId"] }
766
+ ]
767
+ },
768
+ { $ifNull: ["$operatorGrant.extraAttempts", 0] },
769
+ 0
770
+ ]
771
+ }
772
+ ]
773
+ }
774
+ ]
775
+ };
776
+ const conditions = [{ $expr: budgetExpr }];
777
+ if (p.consumesGrant) {
778
+ conditions.push({ "operatorGrant.consumedAt": null });
779
+ conditions.push({ $expr: { $eq: ["$operatorGrant.appliesToRunId", "$lastRunId"] } });
780
+ } else {
781
+ conditions.push({ nextAttemptAt: { $lte: now } });
782
+ }
783
+ const set = { updatedAt: now };
784
+ if (p.consumesGrant) set["operatorGrant.consumedAt"] = now;
785
+ const claimed = await c.requests.findOneAndUpdate(
786
+ {
787
+ _id: requestId,
788
+ state: "open",
789
+ isOpen: true,
790
+ activeRunId: null,
791
+ $and: conditions
792
+ },
793
+ { $inc: { attemptCounter: 1 }, $set: set },
794
+ { session, returnDocument: "after" }
795
+ );
796
+ if (!claimed) throw new Abort("request_not_claimable");
797
+ return { request: claimed, attemptNumber: claimed.attemptCounter };
798
+ }
799
+ async function createRequest(c, p, now, session) {
800
+ const integration = await c.integrations.findOne({ _id: p.integrationId }, { session });
801
+ if (!integration) throw new Abort("unknown_integration");
802
+ const request = {
803
+ _id: new import_mongodb2.ObjectId(),
804
+ dedupFingerprint: dedupFingerprint(p.integrationId, p.unitKey, p.kind, p.window, p.scope),
805
+ integrationId: p.integrationId,
806
+ unitKey: p.unitKey,
807
+ kind: p.kind,
808
+ window: p.window,
809
+ scope: p.scope,
810
+ state: "open",
811
+ isOpen: true,
812
+ attemptCounter: 1,
813
+ maxAttempts: integration.policy.maxAttempts,
814
+ nextAttemptAt: now,
815
+ activeRunId: null,
816
+ lastRunId: null,
817
+ operatorGrant: null,
818
+ repairId: p.repairId,
819
+ createdAt: now,
820
+ updatedAt: now
821
+ };
822
+ await c.requests.insertOne(request, { session });
823
+ return { request, attemptNumber: 1 };
824
+ }
825
+ function buildRun(runId2, request, unit, integration, p, attemptNumber, now) {
826
+ return {
827
+ _id: runId2,
828
+ requestId: request._id,
829
+ integrationId: p.integrationId,
830
+ unitKey: p.unitKey,
831
+ kind: p.kind,
832
+ attemptNumber,
833
+ window: p.window,
834
+ scope: p.scope,
835
+ state: "dispatch_pending",
836
+ publication: "pending",
837
+ execution: "not_started",
838
+ vendorSubmission: "none",
839
+ reservation: "held",
840
+ admittedAt: now,
841
+ publishedAt: null,
842
+ taskId: null,
843
+ appliedAt: null,
844
+ completedAt: null,
845
+ outcome: null,
846
+ blocked: null,
847
+ stall: { count: 0, since: null, blockedOps: [], intervals: [] },
848
+ counterSnapshot: {
849
+ consecutiveFailures: unit.counters[p.kind].consecutiveFailures,
850
+ emptyStreak: unit.counters.scheduled.emptyStreak
851
+ },
852
+ // Historical intent at dispatch. `advanceMarker` reads these and the live unit —
853
+ // never a field that nothing writes.
854
+ admissionSnapshot: {
855
+ dispatchUntil: unit.availability.dispatchUntil,
856
+ dataUntil: unit.availability.dataUntil,
857
+ priorMarker: unit.watermark.scheduledThrough,
858
+ trafficPolicyVersion: integration.trafficPolicy.version,
859
+ sideEffectClass: integration.sideEffectClass,
860
+ sideEffectClassVerifiedBy: integration.sideEffectClassVerifiedBy
861
+ },
862
+ executionOwner: null,
863
+ executionToken: null,
864
+ executionClaimExpiresAt: null,
865
+ submissionAttempts: 0,
866
+ vendorJobRef: null,
867
+ pollingLocation: null,
868
+ pollingExpiresAt: null,
869
+ polledAt: null,
870
+ manifest: null,
871
+ orphanedSubmissions: [],
872
+ lastProgressAt: now,
873
+ lastProgressNote: null
874
+ };
875
+ }
876
+ function isDuplicateKey(e) {
877
+ return typeof e === "object" && e !== null && e.code === 11e3;
878
+ }
879
+ function backoffMs(attempt, integration) {
880
+ const base = integration.policy.backoffBaseMs * 2 ** Math.max(0, attempt - 1);
881
+ return Math.min(base, integration.policy.backoffMaxMs);
882
+ }
883
+
884
+ // src/engine/publish.ts
885
+ var ClaimLost = class extends Error {
886
+ };
887
+ var REJECTED = "cadence/enqueue_rejected";
888
+ var UNCERTAIN = "cadence/enqueue_uncertain";
889
+ var EnqueueUncertain = class extends Error {
890
+ cadenceCode = UNCERTAIN;
891
+ };
892
+ var EnqueueRejected = class extends Error {
893
+ cadenceCode = REJECTED;
894
+ };
895
+ function hasCode(e, code) {
896
+ return typeof e === "object" && e !== null && e.cadenceCode === code;
897
+ }
898
+ var isEnqueueRejected = (e) => hasCode(e, REJECTED);
899
+ var isEnqueueUncertain = (e) => hasCode(e, UNCERTAIN);
900
+ async function activateReservation(c, runId2, integrationId, session) {
901
+ const r = await c.runs.updateOne(
902
+ { _id: runId2, reservation: "held" },
903
+ { $set: { reservation: "active" } },
904
+ { session }
905
+ );
906
+ if (r.matchedCount !== 1) return false;
907
+ await c.integrations.updateOne(
908
+ { _id: integrationId },
909
+ { $inc: { "capacity.reserved": -1, "capacity.active": 1 } },
910
+ { session }
911
+ );
912
+ return true;
913
+ }
914
+ async function publishOutbox(c, queue, now, opts) {
915
+ const claimToken = newToken();
916
+ const claim = await c.outbox.findOneAndUpdate(
917
+ {
918
+ state: "pending",
919
+ nextAttemptAt: { $lte: now },
920
+ $or: [{ claimExpiresAt: null }, { claimExpiresAt: { $lte: now } }]
921
+ },
922
+ {
923
+ $set: {
924
+ state: "publishing",
925
+ claimToken,
926
+ claimedBy: opts.instanceId,
927
+ claimedAt: now,
928
+ claimExpiresAt: addMs(now, opts.claimTtlMs)
929
+ }
930
+ },
931
+ { returnDocument: "after" }
932
+ );
933
+ if (!claim) return { published: false, reason: "nothing_pending" };
934
+ let taskId;
935
+ try {
936
+ const res = await queue.enqueue(claim.payload, { idempotencyKey: claim.runId });
937
+ taskId = res.taskId;
938
+ } catch (e) {
939
+ if (isEnqueueRejected(e)) {
940
+ await recordRejection(c, claim, claimToken, e.message);
941
+ return { published: false, reason: "rejected" };
942
+ }
943
+ await recordUncertainty(c, claim, claimToken);
944
+ return { published: false, reason: "uncertain" };
945
+ }
946
+ try {
947
+ await persistPublication(c, claim, claimToken, taskId, now, opts);
948
+ } catch (e) {
949
+ if (e instanceof ClaimLost) return { published: false, reason: "claim_lost" };
950
+ await recordUncertainty(c, claim, claimToken);
951
+ return { published: false, reason: "uncertain" };
952
+ }
953
+ return { published: true, runId: claim.runId, taskId };
954
+ }
955
+ async function persistPublication(c, claim, claimToken, taskId, now, opts) {
956
+ const session = c.client.startSession();
957
+ try {
958
+ await session.withTransaction(async () => {
959
+ const o = await c.outbox.updateOne(
960
+ { _id: claim._id, state: "publishing", claimToken, claimedBy: opts.instanceId },
961
+ { $set: { state: "published" } },
962
+ { session }
963
+ );
964
+ if (o.matchedCount !== 1) throw new ClaimLost("outbox_claim_lost");
965
+ await c.runs.updateOne(
966
+ { _id: claim.runId, publication: "pending" },
967
+ { $set: { publication: "published", publishedAt: now, taskId } },
968
+ { session }
969
+ );
970
+ await c.runs.updateOne(
971
+ { _id: claim.runId, state: "dispatch_pending" },
972
+ { $set: { state: "submitted" } },
973
+ { session }
974
+ );
975
+ await activateReservation(c, claim.runId, claim.integrationId, session);
976
+ });
977
+ } finally {
978
+ await session.endSession();
979
+ }
980
+ }
981
+ async function recordUncertainty(c, claim, claimToken) {
982
+ const o = await c.outbox.updateOne(
983
+ { _id: claim._id, state: "publishing", claimToken },
984
+ { $set: { state: "awaiting_resolution" } }
985
+ );
986
+ if (o.matchedCount !== 1) return;
987
+ await c.runs.updateOne(
988
+ { _id: claim.runId, publication: "pending", state: "dispatch_pending" },
989
+ { $set: { publication: "awaiting_resolution" }, $inc: { submissionAttempts: 1 } }
990
+ );
991
+ }
992
+ async function recordRejection(c, claim, claimToken, message) {
993
+ const o = await c.outbox.updateOne(
994
+ { _id: claim._id, state: "publishing", claimToken },
995
+ { $set: { state: "failed" } }
996
+ );
997
+ if (o.matchedCount !== 1) return;
998
+ await c.runs.updateOne(
999
+ { _id: claim.runId, publication: "pending" },
1000
+ { $set: { publication: "failed", outcome: { kind: "failed", failure: { class: "invalid_config", message } } } }
1001
+ );
1002
+ }
1003
+
1004
+ // src/engine/stall.ts
1005
+ async function enterStall(c, runId2, stallKey, now) {
1006
+ await c.runs.updateOne({ _id: runId2 }, { $addToSet: { "stall.blockedOps": stallKey } });
1007
+ const opened = await c.runs.findOneAndUpdate(
1008
+ { _id: runId2, "stall.since": null },
1009
+ { $set: { "stall.since": now }, $inc: { "stall.count": 1 } },
1010
+ { returnDocument: "after" }
1011
+ );
1012
+ return opened !== null;
1013
+ }
1014
+ async function exitStall(c, runId2, stallKey, now) {
1015
+ await c.runs.updateOne({ _id: runId2 }, { $pull: { "stall.blockedOps": stallKey } });
1016
+ const closed = await c.runs.findOneAndUpdate(
1017
+ { _id: runId2, "stall.blockedOps": { $size: 0 }, "stall.since": { $ne: null } },
1018
+ { $set: { "stall.since": null } },
1019
+ { returnDocument: "before" }
1020
+ );
1021
+ if (!closed?.stall.since) return false;
1022
+ await c.runs.updateOne(
1023
+ { _id: runId2 },
1024
+ { $push: { "stall.intervals": { from: closed.stall.since, to: now } } }
1025
+ );
1026
+ return true;
1027
+ }
1028
+ function stallIntervals(run, now) {
1029
+ const ivs = [...run.stall.intervals];
1030
+ if (run.stall.since) ivs.push({ from: run.stall.since, to: now });
1031
+ return ivs;
1032
+ }
1033
+ function eligibleMs(run, from, to) {
1034
+ const wall = to.getTime() - from.getTime();
1035
+ return Math.max(0, wall - intersectionMs(stallIntervals(run, to), from, to));
1036
+ }
1037
+ function externalExpiryElapsedMs(from, to) {
1038
+ return to.getTime() - from.getTime();
1039
+ }
1040
+
1041
+ // src/engine/worker.ts
1042
+ async function beforeVendorContact(c, run, integration, op, now, stallKey = op) {
1043
+ const st = trafficStateAt(integration.trafficPolicy, now, op);
1044
+ if (st.denied) {
1045
+ await enterStall(c, run._id, stallKey, now);
1046
+ return { proceed: false, opensAt: st.opensAt };
1047
+ }
1048
+ await exitStall(c, run._id, stallKey, now);
1049
+ return { proceed: true, opensAt: null };
1050
+ }
1051
+ async function submitKickoff(c, vendor, integration, runId2, now, opts) {
1052
+ const run = await c.runs.findOne({ _id: runId2 });
1053
+ if (!run) return { status: "not_owner" };
1054
+ if (run.vendorSubmission === "confirmed") return { status: "already_confirmed" };
1055
+ if (run.vendorSubmission === "unknown") {
1056
+ return { status: "escalated", reason: "already_unknown" };
1057
+ }
1058
+ if (run.vendorSubmission === "claimed" || run.vendorSubmission === "intent_recorded") {
1059
+ return recoverSubmission(c, vendor, run, now, opts);
1060
+ }
1061
+ const token = newToken();
1062
+ const claimed = await c.runs.findOneAndUpdate(
1063
+ { _id: runId2, vendorSubmission: "none" },
1064
+ {
1065
+ $set: {
1066
+ vendorSubmission: "claimed",
1067
+ execution: "running",
1068
+ executionOwner: opts.workerId,
1069
+ executionToken: token,
1070
+ executionClaimExpiresAt: addMs(now, opts.claimTtlMs)
1071
+ }
1072
+ },
1073
+ { returnDocument: "after" }
1074
+ );
1075
+ if (!claimed) return { status: "not_owner" };
1076
+ await activateReservation(c, runId2, run.integrationId);
1077
+ const gate = await beforeVendorContact(
1078
+ c,
1079
+ claimed,
1080
+ integration,
1081
+ "kickoff",
1082
+ now,
1083
+ `kickoff:${opts.workerId}`
1084
+ );
1085
+ if (!gate.proceed) {
1086
+ await c.runs.updateOne(
1087
+ { _id: runId2, executionToken: token, vendorSubmission: "claimed" },
1088
+ {
1089
+ $set: {
1090
+ vendorSubmission: "none",
1091
+ execution: "not_started",
1092
+ executionOwner: null,
1093
+ executionToken: null,
1094
+ executionClaimExpiresAt: null
1095
+ }
1096
+ }
1097
+ );
1098
+ return { status: "deferred", reason: "vendor_traffic_window", retryAt: gate.opensAt };
1099
+ }
1100
+ return contactVendor(c, vendor, runId2, token, now, opts);
1101
+ }
1102
+ async function contactVendor(c, vendor, runId2, token, now, opts) {
1103
+ const intent = await c.runs.updateOne(
1104
+ {
1105
+ _id: runId2,
1106
+ executionToken: token,
1107
+ executionOwner: opts.workerId,
1108
+ vendorSubmission: "claimed",
1109
+ executionClaimExpiresAt: { $gt: now }
1110
+ },
1111
+ { $set: { vendorSubmission: "intent_recorded" }, $inc: { submissionAttempts: 1 } }
1112
+ );
1113
+ if (intent.matchedCount !== 1) {
1114
+ return { status: "claim_lost", contacted: false };
1115
+ }
1116
+ const run = await c.runs.findOne({ _id: runId2 });
1117
+ if (!run) return { status: "claim_lost", contacted: false };
1118
+ const res = await vendor.kickoff(run);
1119
+ const confirmed = await c.runs.updateOne(
1120
+ { _id: runId2, executionToken: token, vendorSubmission: "intent_recorded" },
1121
+ {
1122
+ $set: {
1123
+ vendorSubmission: "confirmed",
1124
+ state: "in_progress",
1125
+ vendorJobRef: res.jobRef,
1126
+ pollingLocation: res.contentLocation,
1127
+ lastProgressAt: now
1128
+ }
1129
+ }
1130
+ );
1131
+ if (confirmed.matchedCount !== 1) {
1132
+ await c.runs.updateOne(
1133
+ { _id: runId2 },
1134
+ { $push: { orphanedSubmissions: { jobRef: res.jobRef, at: now, by: opts.workerId } } }
1135
+ );
1136
+ return { status: "orphaned", jobRef: res.jobRef };
1137
+ }
1138
+ return { status: "submitted", jobRef: res.jobRef };
1139
+ }
1140
+ async function recoverSubmission(c, vendor, run, now, opts) {
1141
+ const mine = run.executionOwner === opts.workerId && run.executionClaimExpiresAt !== null && run.executionClaimExpiresAt > now;
1142
+ if (!mine) return { status: "not_owner" };
1143
+ const safe = isRepetitionSafe(run.admissionSnapshot.sideEffectClass);
1144
+ if (vendor.findByClientRequestId && safe) {
1145
+ const job = await vendor.findByClientRequestId(run._id);
1146
+ if (job) {
1147
+ await c.runs.updateOne(
1148
+ { _id: run._id, executionToken: run.executionToken },
1149
+ {
1150
+ $set: {
1151
+ vendorSubmission: "confirmed",
1152
+ state: "in_progress",
1153
+ vendorJobRef: job.jobRef,
1154
+ pollingLocation: job.contentLocation,
1155
+ lastProgressAt: now
1156
+ }
1157
+ }
1158
+ );
1159
+ return { status: "submitted", jobRef: job.jobRef };
1160
+ }
1161
+ }
1162
+ await markUnknown(c, run._id);
1163
+ return { status: "escalated", reason: "no_vendor_job_lookup" };
1164
+ }
1165
+ async function markUnknown(c, runId2) {
1166
+ await c.runs.updateOne(
1167
+ { _id: runId2, vendorSubmission: { $in: ["claimed", "intent_recorded"] } },
1168
+ { $set: { vendorSubmission: "unknown", execution: "crashed" } }
1169
+ );
1170
+ }
1171
+ async function expireSubmissionClaim(c, runId2, at) {
1172
+ await c.runs.updateOne({ _id: runId2 }, { $set: { executionClaimExpiresAt: at } });
1173
+ }
1174
+
1175
+ // src/engine/availability.ts
1176
+ function deriveHint(unit, integration, now) {
1177
+ const a = unit.availability;
1178
+ let t = unit.scheduledCadenceAt;
1179
+ if (a.dispatchFrom && t < a.dispatchFrom) t = a.dispatchFrom;
1180
+ const sus = activeSuspension(a.suspensions, now);
1181
+ if (sus) t = sus.until ?? FAR_FUTURE;
1182
+ const upcoming = a.suspensions.filter((s) => s.from > now).sort((x, y) => x.from.getTime() - y.from.getTime())[0];
1183
+ if (upcoming && t >= upcoming.from && t < (upcoming.until ?? FAR_FUTURE)) {
1184
+ t = upcoming.until ?? FAR_FUTURE;
1185
+ }
1186
+ if (integration.vendorCooldownUntil) t = maxDate(t, integration.vendorCooldownUntil) ?? t;
1187
+ const at = maxDate(t, now) ?? t;
1188
+ const win = trafficStateAt(integration.trafficPolicy, at, "kickoff");
1189
+ if (win.denied && win.opensAt) t = maxDate(t, win.opensAt) ?? t;
1190
+ return t;
1191
+ }
1192
+ async function refreshEligibility(c, unitKey, now) {
1193
+ const unit = await c.units.findOne({ _id: unitKey });
1194
+ if (!unit) throw new Error(`unknown unit ${unitKey}`);
1195
+ const integration = await c.integrations.findOne({ _id: unit.integrationId });
1196
+ if (!integration) throw new Error(`unknown integration ${unit.integrationId}`);
1197
+ const hint = deriveHint(unit, integration, now);
1198
+ await c.units.updateOne({ _id: unitKey }, { $set: { scheduledNextEligibleAt: hint } });
1199
+ return hint;
1200
+ }
1201
+ async function refreshIntegrationEligibility(c, integrationId, now) {
1202
+ const units = await c.units.find({ integrationId }).project({ _id: 1 }).toArray();
1203
+ for (const u of units) await refreshEligibility(c, u._id, now);
1204
+ }
1205
+ async function patchAvailability(c, unitKey, patch, now) {
1206
+ const set = {};
1207
+ for (const [k, v] of Object.entries(patch)) set[`availability.${k}`] = v;
1208
+ if (Object.keys(set).length > 0) {
1209
+ await c.units.updateOne({ _id: unitKey }, { $set: set });
1210
+ }
1211
+ await refreshEligibility(c, unitKey, now);
1212
+ }
1213
+ async function addSuspension(c, unitKey, suspension, now) {
1214
+ const unit = await c.units.findOne({ _id: unitKey });
1215
+ if (!unit) throw new Error(`unknown unit ${unitKey}`);
1216
+ const overlaps = unit.availability.suspensions.some(
1217
+ (s) => (s.until === null || s.until > suspension.from) && (suspension.until === null || suspension.until > s.from)
1218
+ );
1219
+ if (overlaps) throw new Error("suspension_overlap");
1220
+ await c.units.updateOne({ _id: unitKey }, { $push: { "availability.suspensions": suspension } });
1221
+ await refreshEligibility(c, unitKey, now);
1222
+ }
1223
+ async function removeSuspension(c, unitKey, suspensionId, now) {
1224
+ await c.units.updateOne(
1225
+ { _id: unitKey },
1226
+ { $pull: { "availability.suspensions": { id: suspensionId } } }
1227
+ );
1228
+ await refreshEligibility(c, unitKey, now);
1229
+ }
1230
+ async function setTrafficPolicy(c, integrationId, policy, now) {
1231
+ await c.integrations.updateOne({ _id: integrationId }, { $set: { trafficPolicy: policy } });
1232
+ await refreshIntegrationEligibility(c, integrationId, now);
1233
+ }
1234
+
1235
+ // src/engine/execute.ts
1236
+ async function pollRun(c, vendor, integration, runId2, now, opts) {
1237
+ const run = await c.runs.findOne({ _id: runId2 });
1238
+ if (!run) return { status: "not_pollable" };
1239
+ if (run.appliedAt !== null) return { status: "not_pollable" };
1240
+ if (run.vendorSubmission !== "confirmed" || run.pollingLocation === null) {
1241
+ return { status: "not_pollable" };
1242
+ }
1243
+ if (run.manifest) return { status: "manifest_ready", entries: run.manifest.entries.length };
1244
+ if (run.pollingExpiresAt && now >= run.pollingExpiresAt) {
1245
+ return {
1246
+ status: "terminal",
1247
+ outcome: {
1248
+ kind: "failed",
1249
+ failure: { class: "vendor_error", message: "polling_location_expired" }
1250
+ }
1251
+ };
1252
+ }
1253
+ const gate = await beforeVendorContact(
1254
+ c,
1255
+ run,
1256
+ integration,
1257
+ "poll",
1258
+ now,
1259
+ `poll:${opts.workerId}`
1260
+ );
1261
+ if (!gate.proceed) {
1262
+ return { status: "deferred", reason: "vendor_traffic_window", retryAt: gate.opensAt };
1263
+ }
1264
+ const result = await vendor.poll(run);
1265
+ switch (result.status) {
1266
+ case "accepted": {
1267
+ const set = { polledAt: now };
1268
+ if (result.expiresAt) set["pollingExpiresAt"] = result.expiresAt;
1269
+ if (result.progress !== void 0 && result.progress !== run.lastProgressNote) {
1270
+ set["lastProgressAt"] = now;
1271
+ set["lastProgressNote"] = result.progress;
1272
+ }
1273
+ await c.runs.updateOne({ _id: runId2 }, { $set: set });
1274
+ return { status: "working" };
1275
+ }
1276
+ case "complete": {
1277
+ const entries = result.entries.map((e, i) => ({
1278
+ id: `${i}`,
1279
+ resourceType: e.resourceType,
1280
+ url: e.url,
1281
+ count: e.count,
1282
+ state: "pending",
1283
+ claimedBy: null,
1284
+ claimExpiresAt: null,
1285
+ attempts: 0,
1286
+ bytes: null
1287
+ }));
1288
+ await c.runs.updateOne(
1289
+ { _id: runId2, manifest: null },
1290
+ {
1291
+ $set: {
1292
+ manifest: {
1293
+ transactionTime: result.transactionTime,
1294
+ entries,
1295
+ partial: result.partial ?? null
1296
+ },
1297
+ lastProgressAt: now,
1298
+ polledAt: now
1299
+ }
1300
+ }
1301
+ );
1302
+ return { status: "manifest_ready", entries: entries.length };
1303
+ }
1304
+ case "throttled": {
1305
+ const until = addMs(now, result.retryAfterMs);
1306
+ await c.integrations.updateOne(
1307
+ { _id: integration._id, $or: [{ vendorCooldownUntil: null }, { vendorCooldownUntil: { $lt: until } }] },
1308
+ { $set: { vendorCooldownUntil: until } }
1309
+ );
1310
+ await refreshIntegrationEligibility(c, integration._id, now);
1311
+ return { status: "deferred", reason: "vendor_cooldown", retryAt: until };
1312
+ }
1313
+ case "expired":
1314
+ return {
1315
+ status: "terminal",
1316
+ outcome: {
1317
+ kind: "failed",
1318
+ failure: { class: "vendor_error", message: "polling_location_expired" }
1319
+ }
1320
+ };
1321
+ case "failed":
1322
+ return { status: "terminal", outcome: { kind: "failed", failure: result.failure } };
1323
+ }
1324
+ }
1325
+ async function downloadNext(c, sink, integration, runId2, now, opts) {
1326
+ const run = await c.runs.findOne({ _id: runId2 });
1327
+ if (!run?.manifest || run.appliedAt !== null) return { status: "nothing_claimable" };
1328
+ const gate = await beforeVendorContact(
1329
+ c,
1330
+ run,
1331
+ integration,
1332
+ "download",
1333
+ now,
1334
+ `download:${opts.workerId}`
1335
+ );
1336
+ if (!gate.proceed) {
1337
+ return { status: "deferred", reason: "vendor_traffic_window", retryAt: gate.opensAt };
1338
+ }
1339
+ const owner = `${opts.workerId}:${newToken()}`;
1340
+ const claim = {
1341
+ $set: {
1342
+ "manifest.entries.$.state": "claimed",
1343
+ "manifest.entries.$.claimedBy": owner,
1344
+ "manifest.entries.$.claimExpiresAt": addMs(now, opts.entryClaimTtlMs)
1345
+ },
1346
+ $inc: { "manifest.entries.$.attempts": 1 }
1347
+ };
1348
+ let claimed = await c.runs.findOneAndUpdate(
1349
+ { _id: runId2, "manifest.entries.state": "pending" },
1350
+ claim,
1351
+ { returnDocument: "after" }
1352
+ );
1353
+ if (!claimed) {
1354
+ claimed = await c.runs.findOneAndUpdate(
1355
+ {
1356
+ _id: runId2,
1357
+ "manifest.entries": { $elemMatch: { state: "claimed", claimExpiresAt: { $lte: now } } }
1358
+ },
1359
+ claim,
1360
+ { returnDocument: "after" }
1361
+ );
1362
+ }
1363
+ const entry = claimed?.manifest?.entries.find((e) => e.claimedBy === owner);
1364
+ if (!entry) return { status: "nothing_claimable" };
1365
+ try {
1366
+ const res = await sink.fetch(entry, claimed);
1367
+ await c.runs.updateOne(
1368
+ { _id: runId2, "manifest.entries.claimedBy": owner },
1369
+ {
1370
+ $set: {
1371
+ "manifest.entries.$.state": "done",
1372
+ "manifest.entries.$.bytes": res.bytes,
1373
+ "manifest.entries.$.count": res.count,
1374
+ lastProgressAt: now
1375
+ }
1376
+ }
1377
+ );
1378
+ return { status: "downloaded", entryId: entry.id };
1379
+ } catch (e) {
1380
+ const message = e instanceof Error ? e.message : String(e);
1381
+ await c.runs.updateOne(
1382
+ { _id: runId2, "manifest.entries.claimedBy": owner },
1383
+ { $set: { "manifest.entries.$.state": "failed", lastProgressAt: now } }
1384
+ );
1385
+ return { status: "entry_failed", entryId: entry.id, message };
1386
+ }
1387
+ }
1388
+ function completionOutcome(run) {
1389
+ const manifest = run.manifest;
1390
+ if (!manifest) return null;
1391
+ if (manifest.entries.some((e) => e.state === "pending" || e.state === "claimed")) return null;
1392
+ if (manifest.entries.some((e) => e.state === "failed")) {
1393
+ const failed = manifest.entries.filter((e) => e.state === "failed").length;
1394
+ return {
1395
+ kind: "failed",
1396
+ failure: {
1397
+ class: "transient_transport",
1398
+ message: `${failed}_of_${manifest.entries.length}_files_unretrieved`
1399
+ }
1400
+ };
1401
+ }
1402
+ if (manifest.partial) {
1403
+ return {
1404
+ kind: "partial",
1405
+ transactionTime: manifest.transactionTime,
1406
+ verifiedPortion: { from: run.window.from, to: manifest.partial.verifiedThrough },
1407
+ failedPortion: { from: manifest.partial.failedFrom, to: manifest.partial.failedTo }
1408
+ };
1409
+ }
1410
+ const total = manifest.entries.reduce((n, e) => n + (e.count ?? 0), 0);
1411
+ return total === 0 ? { kind: "succeeded_empty", transactionTime: manifest.transactionTime } : { kind: "succeeded", transactionTime: manifest.transactionTime };
1412
+ }
1413
+ async function outcomeFor(c, runId2) {
1414
+ const run = await c.runs.findOne({ _id: runId2 });
1415
+ return run ? completionOutcome(run) : null;
1416
+ }
1417
+
1418
+ // src/engine/finalize.ts
1419
+ var import_mongodb3 = require("mongodb");
1420
+ async function finalize(c, runId2, outcome, now) {
1421
+ assertTerminal(outcome);
1422
+ const session = c.client.startSession();
1423
+ let result = { applied: false, reason: "not_attempted" };
1424
+ try {
1425
+ await session.withTransaction(async () => {
1426
+ const claimed = await c.runs.findOneAndUpdate(
1427
+ { _id: runId2, appliedAt: null },
1428
+ { $set: { appliedAt: now, blocked: null } },
1429
+ { session, returnDocument: "before" }
1430
+ );
1431
+ if (!claimed) throw new Abort("already_applied");
1432
+ const integration = await c.integrations.findOne({ _id: claimed.integrationId }, { session });
1433
+ if (!integration) throw new Abort("unknown_integration");
1434
+ const unit = await c.units.findOne(
1435
+ { _id: claimed.unitKey, activeRunId: runId2 },
1436
+ { session }
1437
+ );
1438
+ if (!unit) throw new Abort("unit_occupancy_lost");
1439
+ const request = await c.requests.findOne({ _id: claimed.requestId }, { session });
1440
+ if (!request) throw new Abort("unknown_request");
1441
+ const safe = isRepetitionSafe(claimed.admissionSnapshot.sideEffectClass);
1442
+ const attemptsRemaining = request.attemptCounter < attemptBudget(request, runId2);
1443
+ const disp = requestDispositionFor(outcome, { safe, attemptsRemaining });
1444
+ const retryAt = addMs(now, backoffMs(request.attemptCounter, integration));
1445
+ const repairResolution = request.repairId && !disp.isOpen ? disp.state === "failed" ? "accepted" : "resolved" : null;
1446
+ const counters = unit.counters[claimed.kind];
1447
+ const set = {
1448
+ activeRunId: null,
1449
+ executionState: "idle"
1450
+ };
1451
+ switch (outcome.kind) {
1452
+ case "succeeded": {
1453
+ set[`counters.${claimed.kind}.consecutiveFailures`] = 0;
1454
+ set[`counters.${claimed.kind}.emptyStreak`] = 0;
1455
+ set[`counters.${claimed.kind}.totalRuns`] = counters.totalRuns + 1;
1456
+ advanceMarker(set, claimed, unit, outcome, now);
1457
+ break;
1458
+ }
1459
+ case "succeeded_empty": {
1460
+ const streak = counters.emptyStreak + 1;
1461
+ set[`counters.${claimed.kind}.consecutiveFailures`] = 0;
1462
+ set[`counters.${claimed.kind}.emptyStreak`] = streak;
1463
+ set[`counters.${claimed.kind}.totalRuns`] = counters.totalRuns + 1;
1464
+ advanceMarker(set, claimed, unit, outcome, now);
1465
+ if (streak >= integration.policy.emptyStreakThreshold) {
1466
+ set["attention"] = [
1467
+ ...unit.attention.filter((a) => a.reason !== "empty_streak"),
1468
+ { episodeId: new import_mongodb3.ObjectId().toHexString(), reason: "empty_streak", since: now }
1469
+ ];
1470
+ }
1471
+ break;
1472
+ }
1473
+ case "partial": {
1474
+ set[`counters.${claimed.kind}.consecutiveFailures`] = 0;
1475
+ set[`counters.${claimed.kind}.totalRuns`] = counters.totalRuns + 1;
1476
+ if (safe && integration.policy.partialPolicy === "advance_with_repair") {
1477
+ const prior = unit.watermark.scheduledThrough;
1478
+ if (claimed.kind === "scheduled" && (!prior || outcome.verifiedPortion.to > prior)) {
1479
+ set["watermark.scheduledThrough"] = outcome.verifiedPortion.to;
1480
+ set["watermark.basis"] = "verified_portion";
1481
+ set["watermark.seeded"] = true;
1482
+ set["watermark.updatedAt"] = now;
1483
+ }
1484
+ await c.repairs.updateOne(
1485
+ {
1486
+ unitKey: claimed.unitKey,
1487
+ cause: "partial_export",
1488
+ state: "open",
1489
+ "interval.from": outcome.failedPortion.from,
1490
+ "interval.to": outcome.failedPortion.to
1491
+ },
1492
+ {
1493
+ $setOnInsert: {
1494
+ _id: new import_mongodb3.ObjectId(),
1495
+ integrationId: claimed.integrationId,
1496
+ scope: claimed.scope,
1497
+ createdAt: now
1498
+ }
1499
+ },
1500
+ { upsert: true, session }
1501
+ );
1502
+ } else {
1503
+ set["executionState"] = "blocked_unconfirmed";
1504
+ }
1505
+ break;
1506
+ }
1507
+ case "failed": {
1508
+ const fails = counters.consecutiveFailures + 1;
1509
+ set[`counters.${claimed.kind}.consecutiveFailures`] = fails;
1510
+ set[`counters.${claimed.kind}.totalRuns`] = counters.totalRuns + 1;
1511
+ if (countsTowardQuarantine(outcome.failure.class) && fails >= integration.policy.failureThreshold) {
1512
+ set["executionState"] = "quarantined";
1513
+ set["adminState"] = "paused";
1514
+ } else {
1515
+ set["executionState"] = "backoff";
1516
+ }
1517
+ break;
1518
+ }
1519
+ case "terminated_confirmed": {
1520
+ set[`counters.${claimed.kind}.totalRuns`] = counters.totalRuns + 1;
1521
+ if (!safe) set["executionState"] = "blocked_unconfirmed";
1522
+ break;
1523
+ }
1524
+ }
1525
+ set[pointerField(claimed.kind)] = runId2;
1526
+ if (repairResolution === "accepted") {
1527
+ set["attention"] = [
1528
+ ...unit.attention.filter((a) => a.reason !== "repair_abandoned"),
1529
+ {
1530
+ episodeId: new import_mongodb3.ObjectId().toHexString(),
1531
+ reason: "repair_abandoned",
1532
+ since: now,
1533
+ detail: request.repairId.toHexString()
1534
+ }
1535
+ ];
1536
+ }
1537
+ if (claimed.kind === "scheduled") {
1538
+ set["scheduledCadenceAt"] = disp.isOpen ? retryAt : addMs(now, unit.cadenceMs);
1539
+ }
1540
+ const unitUpdate = await c.units.updateOne(
1541
+ { _id: claimed.unitKey, activeRunId: runId2 },
1542
+ { $set: set },
1543
+ { session }
1544
+ );
1545
+ if (unitUpdate.matchedCount !== 1) throw new Abort("unit_update_lost");
1546
+ if (claimed.reservation === "held") {
1547
+ await c.integrations.updateOne(
1548
+ { _id: claimed.integrationId },
1549
+ { $inc: { "capacity.reserved": -1 } },
1550
+ { session }
1551
+ );
1552
+ } else if (claimed.reservation === "active") {
1553
+ await c.integrations.updateOne(
1554
+ { _id: claimed.integrationId },
1555
+ { $inc: { "capacity.active": -1 } },
1556
+ { session }
1557
+ );
1558
+ }
1559
+ const runState = terminalRunState(outcome.kind);
1560
+ await c.runs.updateOne(
1561
+ { _id: runId2 },
1562
+ {
1563
+ $set: {
1564
+ state: runState,
1565
+ completedAt: now,
1566
+ outcome,
1567
+ reservation: "released",
1568
+ execution: "finished"
1569
+ }
1570
+ },
1571
+ { session }
1572
+ );
1573
+ await c.requests.updateOne(
1574
+ { _id: request._id },
1575
+ {
1576
+ $set: {
1577
+ state: disp.state,
1578
+ isOpen: disp.isOpen,
1579
+ // Nulled on close so the partial unique index stops applying and a future
1580
+ // identical window can be requested again.
1581
+ dedupFingerprint: disp.isOpen ? request.dedupFingerprint : null,
1582
+ activeRunId: null,
1583
+ lastRunId: runId2,
1584
+ nextAttemptAt: disp.isOpen ? retryAt : request.nextAttemptAt,
1585
+ updatedAt: now
1586
+ }
1587
+ },
1588
+ { session }
1589
+ );
1590
+ if (repairResolution) {
1591
+ await c.repairs.updateOne(
1592
+ { _id: request.repairId, state: "open" },
1593
+ { $set: { state: repairResolution } },
1594
+ { session }
1595
+ );
1596
+ }
1597
+ if (outcome.kind === "succeeded" || outcome.kind === "partial") {
1598
+ await c.coverage.insertOne(
1599
+ {
1600
+ _id: new import_mongodb3.ObjectId(),
1601
+ unitKey: claimed.unitKey,
1602
+ runId: runId2,
1603
+ kind: claimed.kind,
1604
+ interval: {
1605
+ from: claimed.window.from,
1606
+ to: claimed.window.to ?? outcome.transactionTime
1607
+ },
1608
+ scope: claimed.scope
1609
+ },
1610
+ { session }
1611
+ );
1612
+ }
1613
+ result = { applied: true, runState, requestState: disp.state };
1614
+ });
1615
+ } catch (e) {
1616
+ if (e instanceof Abort) return { applied: false, reason: e.message };
1617
+ throw e;
1618
+ } finally {
1619
+ await session.endSession();
1620
+ }
1621
+ if (result.applied) {
1622
+ const run = await c.runs.findOne({ _id: runId2 });
1623
+ const unit = run ? await c.units.findOne({ _id: run.unitKey }) : null;
1624
+ const integration = run ? await c.integrations.findOne({ _id: run.integrationId }) : null;
1625
+ if (unit && integration) {
1626
+ const hint = maxDate(deriveHint(unit, integration, now), now) ?? now;
1627
+ await c.units.updateOne({ _id: unit._id }, { $set: { scheduledNextEligibleAt: hint } });
1628
+ }
1629
+ }
1630
+ return result;
1631
+ }
1632
+ function pointerField(kind) {
1633
+ switch (kind) {
1634
+ case "scheduled":
1635
+ return "lastScheduledRunId";
1636
+ case "adhoc":
1637
+ return "lastAdhocRunId";
1638
+ case "repair":
1639
+ return "lastRepairRunId";
1640
+ }
1641
+ }
1642
+
1643
+ // src/domain/types.ts
1644
+ var TERMINAL_RUN_STATES = [
1645
+ "succeeded",
1646
+ "succeeded_empty",
1647
+ "partial",
1648
+ "failed",
1649
+ "terminated_confirmed"
1650
+ ];
1651
+
1652
+ // src/engine/block.ts
1653
+ async function blockRun(c, runId2, reason, evidenceNeeded, now) {
1654
+ const r = await c.runs.updateOne(
1655
+ { _id: runId2, appliedAt: null, state: { $nin: [...TERMINAL_RUN_STATES] } },
1656
+ { $set: { state: "blocked", blocked: { reason, since: now, evidenceNeeded } } }
1657
+ );
1658
+ if (r.matchedCount !== 1) return false;
1659
+ const run = await c.runs.findOne({ _id: runId2 });
1660
+ if (run) {
1661
+ await c.units.updateOne(
1662
+ { _id: run.unitKey, activeRunId: runId2 },
1663
+ { $set: { executionState: "blocked_unconfirmed" } }
1664
+ );
1665
+ await c.requests.updateOne(
1666
+ { _id: run.requestId, isOpen: true },
1667
+ { $set: { state: "blocked", updatedAt: now } }
1668
+ );
1669
+ }
1670
+ return true;
1671
+ }
1672
+ async function unblockRun(c, runId2, now) {
1673
+ const r = await c.runs.updateOne(
1674
+ { _id: runId2, state: "blocked", appliedAt: null },
1675
+ { $set: { state: "in_progress", blocked: null, lastProgressAt: now } }
1676
+ );
1677
+ if (r.matchedCount !== 1) return false;
1678
+ const run = await c.runs.findOne({ _id: runId2 });
1679
+ if (run) {
1680
+ await c.units.updateOne(
1681
+ { _id: run.unitKey, activeRunId: runId2 },
1682
+ { $set: { executionState: "in_flight" } }
1683
+ );
1684
+ await c.requests.updateOne(
1685
+ { _id: run.requestId, state: "blocked" },
1686
+ { $set: { state: "open", updatedAt: now } }
1687
+ );
1688
+ }
1689
+ return true;
1690
+ }
1691
+
1692
+ // src/engine/attention.ts
1693
+ var import_mongodb4 = require("mongodb");
1694
+ async function raiseAttention(c, unitKey, reason, now, detail) {
1695
+ const episode = {
1696
+ episodeId: new import_mongodb4.ObjectId().toHexString(),
1697
+ reason,
1698
+ since: now,
1699
+ ...detail ? { detail } : {}
1700
+ };
1701
+ const r = await c.units.updateOne(
1702
+ { _id: unitKey, "attention.reason": { $ne: reason } },
1703
+ { $push: { attention: episode } }
1704
+ );
1705
+ return r.modifiedCount === 1;
1706
+ }
1707
+ async function clearAttention(c, unitKey, reason) {
1708
+ await c.units.updateOne({ _id: unitKey }, { $pull: { attention: { reason } } });
1709
+ }
1710
+ async function attentionReasons(c, unitKey) {
1711
+ const u = await c.units.findOne({ _id: unitKey });
1712
+ return (u?.attention ?? []).map((a) => a.reason).sort();
1713
+ }
1714
+
1715
+ // src/engine/reconcile.ts
1716
+ var emptyReport = () => ({
1717
+ submissionClaimsReleased: 0,
1718
+ submissionsAdopted: 0,
1719
+ submissionsEscalated: 0,
1720
+ outboxClaimsReclaimed: 0,
1721
+ publicationsResolved: 0,
1722
+ publicationsEscalated: 0,
1723
+ runsTerminated: 0,
1724
+ runsBlocked: 0
1725
+ });
1726
+ async function reconcile(c, now, opts, deps = {}) {
1727
+ const report = emptyReport();
1728
+ await reclaimSubmissionClaims(c, now, deps, report);
1729
+ await reclaimOutboxClaims(c, now, report);
1730
+ await resolvePublications(c, now, opts, deps, report);
1731
+ await resolveStuckRuns(c, now, opts, deps, report);
1732
+ return report;
1733
+ }
1734
+ async function reclaimSubmissionClaims(c, now, deps, report) {
1735
+ const lapsed = await c.runs.find({
1736
+ appliedAt: null,
1737
+ vendorSubmission: { $in: ["claimed", "intent_recorded"] },
1738
+ executionClaimExpiresAt: { $lte: now }
1739
+ }).toArray();
1740
+ for (const run of lapsed) {
1741
+ if (run.vendorSubmission === "claimed") {
1742
+ const r = await c.runs.updateOne(
1743
+ {
1744
+ _id: run._id,
1745
+ vendorSubmission: "claimed",
1746
+ executionClaimExpiresAt: { $lte: now }
1747
+ },
1748
+ {
1749
+ $set: {
1750
+ vendorSubmission: "none",
1751
+ execution: "not_started",
1752
+ executionOwner: null,
1753
+ executionToken: null,
1754
+ executionClaimExpiresAt: null
1755
+ }
1756
+ }
1757
+ );
1758
+ if (r.modifiedCount === 1) report.submissionClaimsReleased += 1;
1759
+ continue;
1760
+ }
1761
+ const safe = isRepetitionSafe(run.admissionSnapshot.sideEffectClass);
1762
+ const lookup = deps.vendor?.findByClientRequestId;
1763
+ if (safe && lookup) {
1764
+ const job = await lookup.call(deps.vendor, run._id);
1765
+ if (job) {
1766
+ const r2 = await c.runs.updateOne(
1767
+ { _id: run._id, vendorSubmission: "intent_recorded" },
1768
+ {
1769
+ $set: {
1770
+ vendorSubmission: "confirmed",
1771
+ state: "in_progress",
1772
+ execution: "running",
1773
+ vendorJobRef: job.jobRef,
1774
+ pollingLocation: job.contentLocation,
1775
+ executionOwner: null,
1776
+ executionToken: null,
1777
+ executionClaimExpiresAt: null,
1778
+ lastProgressAt: now
1779
+ }
1780
+ }
1781
+ );
1782
+ if (r2.modifiedCount === 1) report.submissionsAdopted += 1;
1783
+ continue;
1784
+ }
1785
+ const r = await c.runs.updateOne(
1786
+ { _id: run._id, vendorSubmission: "intent_recorded" },
1787
+ {
1788
+ $set: {
1789
+ vendorSubmission: "none",
1790
+ execution: "not_started",
1791
+ executionOwner: null,
1792
+ executionToken: null,
1793
+ executionClaimExpiresAt: null
1794
+ }
1795
+ }
1796
+ );
1797
+ if (r.modifiedCount === 1) report.submissionClaimsReleased += 1;
1798
+ continue;
1799
+ }
1800
+ await markUnknown(c, run._id);
1801
+ await blockRun(c, run._id, "unresolved_submission", "vendor job lookup or operator check", now);
1802
+ await raiseAttention(c, run.unitKey, "unresolved_submission", now, run._id);
1803
+ report.submissionsEscalated += 1;
1804
+ }
1805
+ }
1806
+ async function reclaimOutboxClaims(c, now, report) {
1807
+ const stale = await c.outbox.find({ state: "publishing", claimExpiresAt: { $lte: now } }).toArray();
1808
+ for (const entry of stale) {
1809
+ const r = await c.outbox.updateOne(
1810
+ { _id: entry._id, state: "publishing", claimToken: entry.claimToken },
1811
+ {
1812
+ $set: {
1813
+ state: "pending",
1814
+ nextAttemptAt: now,
1815
+ claimToken: null,
1816
+ claimedBy: null,
1817
+ claimedAt: null,
1818
+ claimExpiresAt: null
1819
+ }
1820
+ }
1821
+ );
1822
+ if (r.modifiedCount === 1) report.outboxClaimsReclaimed += 1;
1823
+ }
1824
+ }
1825
+ async function resolvePublications(c, now, opts, deps, report) {
1826
+ const pending = await c.outbox.find({ state: "awaiting_resolution" }).toArray();
1827
+ const lookup = deps.queue?.findByIdempotencyKey;
1828
+ for (const entry of pending) {
1829
+ if (lookup) {
1830
+ const task = await lookup.call(deps.queue, entry.runId);
1831
+ if (task) {
1832
+ await completePublication(c, entry, task.taskId, now);
1833
+ report.publicationsResolved += 1;
1834
+ } else {
1835
+ const r = await c.outbox.updateOne(
1836
+ { _id: entry._id, state: "awaiting_resolution" },
1837
+ { $set: { state: "pending", nextAttemptAt: now } }
1838
+ );
1839
+ if (r.modifiedCount === 1) report.publicationsResolved += 1;
1840
+ }
1841
+ continue;
1842
+ }
1843
+ const run = await c.runs.findOne({ _id: entry.runId });
1844
+ if (!run) continue;
1845
+ if (now.getTime() - run.admittedAt.getTime() < opts.publicationResolutionGraceMs) continue;
1846
+ await blockRun(c, run._id, "needs_investigation", "queue state for this run", now);
1847
+ await raiseAttention(c, run.unitKey, "unresolved_publication", now, run._id);
1848
+ report.publicationsEscalated += 1;
1849
+ }
1850
+ }
1851
+ async function completePublication(c, entry, taskId, now) {
1852
+ const session = c.client.startSession();
1853
+ try {
1854
+ await session.withTransaction(async () => {
1855
+ const o = await c.outbox.updateOne(
1856
+ { _id: entry._id, state: "awaiting_resolution" },
1857
+ { $set: { state: "published" } },
1858
+ { session }
1859
+ );
1860
+ if (o.modifiedCount !== 1) return;
1861
+ await c.runs.updateOne(
1862
+ { _id: entry.runId, publication: { $in: ["pending", "awaiting_resolution"] } },
1863
+ { $set: { publication: "published", publishedAt: now, taskId } },
1864
+ { session }
1865
+ );
1866
+ await c.runs.updateOne(
1867
+ { _id: entry.runId, state: "dispatch_pending" },
1868
+ { $set: { state: "submitted" } },
1869
+ { session }
1870
+ );
1871
+ await activateReservation(c, entry.runId, entry.integrationId, session);
1872
+ });
1873
+ } finally {
1874
+ await session.endSession();
1875
+ }
1876
+ }
1877
+ async function resolveStuckRuns(c, now, opts, deps, report) {
1878
+ const live = await c.runs.find({ appliedAt: null, state: { $in: ["submitted", "in_progress"] } }).toArray();
1879
+ for (const run of live) {
1880
+ const expired = run.pollingExpiresAt !== null && externalExpiryElapsedMs(run.pollingExpiresAt, now) >= 0;
1881
+ const idle = eligibleMs(run, run.lastProgressAt, now) >= opts.noProgressDeadlineMs;
1882
+ if (!expired && !idle) continue;
1883
+ const integration = await c.integrations.findOne({ _id: run.integrationId });
1884
+ if (!integration) continue;
1885
+ const cancelled = await confirmCancellation(run, integration, deps);
1886
+ if (cancelled) {
1887
+ await finalize(c, run._id, { kind: "terminated_confirmed" }, now);
1888
+ report.runsTerminated += 1;
1889
+ } else {
1890
+ await blockRun(c, run._id, "unconfirmed_termination", "vendor job status", now);
1891
+ await raiseAttention(c, run.unitKey, "no_progress", now, run._id);
1892
+ report.runsBlocked += 1;
1893
+ }
1894
+ }
1895
+ }
1896
+ async function confirmCancellation(run, integration, deps) {
1897
+ const cancel = deps.vendor?.cancel;
1898
+ if (!cancel) return false;
1899
+ if (!isRepetitionSafe(integration.sideEffectClass)) return false;
1900
+ return cancel.call(deps.vendor, run);
1901
+ }
1902
+ function nextSweepAt(now, intervalMs) {
1903
+ return addMs(now, intervalMs);
1904
+ }
1905
+ // Annotate the CommonJS export names for ESM import in node:
1906
+ 0 && (module.exports = {
1907
+ DEFAULTS,
1908
+ EnqueueRejected,
1909
+ EnqueueUncertain,
1910
+ ProgrammingError,
1911
+ TERMINAL_OUTCOME_KINDS,
1912
+ activateReservation,
1913
+ addSuspension,
1914
+ admissibility,
1915
+ admit,
1916
+ assertTerminal,
1917
+ attemptBudget,
1918
+ attentionReasons,
1919
+ backoffMs,
1920
+ blockRun,
1921
+ clearAttention,
1922
+ completionOutcome,
1923
+ computeWindow,
1924
+ connect,
1925
+ countsTowardQuarantine,
1926
+ defaultIntegrationPolicy,
1927
+ defaultTrafficPolicy,
1928
+ downloadNext,
1929
+ ensureIndexes,
1930
+ expireSubmissionClaim,
1931
+ finalize,
1932
+ grantIsLive,
1933
+ isEnqueueRejected,
1934
+ isEnqueueUncertain,
1935
+ isRepetitionSafe,
1936
+ isUnitComplete,
1937
+ markUnknown,
1938
+ nextSweepAt,
1939
+ outcomeFor,
1940
+ patchAvailability,
1941
+ plan,
1942
+ pollRun,
1943
+ publishOutbox,
1944
+ raiseAttention,
1945
+ reconcile,
1946
+ refreshEligibility,
1947
+ refreshIntegrationEligibility,
1948
+ removeSuspension,
1949
+ requestDispositionFor,
1950
+ runId,
1951
+ setTrafficPolicy,
1952
+ submitKickoff,
1953
+ terminalRunState,
1954
+ trafficStateAt,
1955
+ unblockRun
1956
+ });
1957
+ //# sourceMappingURL=index.cjs.map