@rulvar/core 1.243.0 → 1.245.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 (3) hide show
  1. package/dist/index.d.ts +2931 -1969
  2. package/dist/index.js +1623 -75
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1310,6 +1310,146 @@ function sanitizeTerminalText(text) {
1310
1310
  return text.replace(ESC_STRING_SEQUENCE, "").replace(ESC_CSI_SEQUENCE, "").replace(CONTROL_RUN, " ");
1311
1311
  }
1312
1312
  //#endregion
1313
+ //#region src/l0/terminal-envelope.ts
1314
+ /**
1315
+ * The unified terminal envelope (RV1105, the P1-5 arc): ONE shape
1316
+ * carrying every fact of a run's terminal, assembled once at the
1317
+ * engine's settlement chokepoint and mirrored verbatim onto the
1318
+ * resolved outcome (`outcome.envelope`), the `run:end` event
1319
+ * (`event.envelope`), and through them the HTTP outcome response and
1320
+ * the OTel run attributes. An SDK consumer, an event-only consumer,
1321
+ * and an HTTP consumer read the SAME set of facts without assembling
1322
+ * pieces from surface-specific fields; nothing pre-existing was
1323
+ * renamed or removed, the envelope is an assembly over it.
1324
+ *
1325
+ * Doctrine notes:
1326
+ * - `status` is the computation's verdict; `settled` says whether
1327
+ * anything durable records it (RV907). A resolved outcome always
1328
+ * carries `settled: true`, because an unsettled terminal REJECTS
1329
+ * `handle.result` typed instead of resolving; the `settled: false`
1330
+ * envelopes exist only on the event stream, where `settledReason:
1331
+ * 'superseded'` distinguishes the fenced-out segment (RV1009) from
1332
+ * a settlement write fault.
1333
+ * - `usageApprox` is normalized to a boolean here (the run:end field
1334
+ * keeps its absent-means-exact byte contract): `true` means some
1335
+ * priced usage was approximate, so `totalUsd` is a lower bound.
1336
+ * - `costByModel` is a detached copy of the settled fold's per-model
1337
+ * split; mutating it never touches the cost report. Since RV1213
1338
+ * `error` is detached the same way, `data` nesting included, so the
1339
+ * whole envelope is a reading a consumer may annotate freely.
1340
+ *
1341
+ * Docs: https://docs.rulvar.com/guide/observability
1342
+ */
1343
+ const ENVELOPE_STATUSES = /* @__PURE__ */ new Set([
1344
+ "ok",
1345
+ "error",
1346
+ "cancelled",
1347
+ "exhausted",
1348
+ "suspended"
1349
+ ]);
1350
+ const ENVELOPE_COMPLETIONS = /* @__PURE__ */ new Set([
1351
+ "complete",
1352
+ "partial",
1353
+ "rejected"
1354
+ ]);
1355
+ function refuseEnvelope(field, requirement, got) {
1356
+ throw new ConfigError(`terminal envelope ${field} must be ${requirement}; got ${typeof got === "number" ? String(got) : JSON.stringify(got) ?? String(got)}`);
1357
+ }
1358
+ function isPlainObject(value) {
1359
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1360
+ }
1361
+ function requireMoney(value, field) {
1362
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuseEnvelope(field, "a finite nonnegative number", value);
1363
+ return value;
1364
+ }
1365
+ function requireCount$1(value, field) {
1366
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuseEnvelope(field, "a nonnegative integer", value);
1367
+ }
1368
+ function requireBoolean(value, field) {
1369
+ if (typeof value !== "boolean") refuseEnvelope(field, "a boolean", value);
1370
+ }
1371
+ function requireNonEmptyString(value, field) {
1372
+ if (typeof value !== "string" || value.length === 0) refuseEnvelope(field, "a non-empty string", value);
1373
+ }
1374
+ /** Every numeric leaf of the usage subtree: finite and nonnegative. */
1375
+ function requireUsageNumbers(node, path) {
1376
+ if (typeof node === "number") {
1377
+ if (!Number.isFinite(node) || node < 0) refuseEnvelope(path, "a finite nonnegative number", node);
1378
+ return;
1379
+ }
1380
+ if (isPlainObject(node)) {
1381
+ for (const [key, item] of Object.entries(node)) requireUsageNumbers(item, `${path}.${key}`);
1382
+ return;
1383
+ }
1384
+ refuseEnvelope(path, "a number or a nested usage object", node);
1385
+ }
1386
+ /**
1387
+ * The runtime gate over the terminal envelope contract (RV3903, the
1388
+ * fourth comparison experiment). `terminalEnvelopeOf` is the ONE
1389
+ * producer, but a producer is a compile-time promise, and the envelope
1390
+ * crosses trust boundaries the type system never sees: a journal read
1391
+ * back after a restart, a plain JS caller, an HTTP body a pipeline
1392
+ * gates on. The experiment probed the built dist and the typed copy
1393
+ * accepted `status: 'green'`, NaN dollars, and negative counts without
1394
+ * a sound; a finance or compliance consumer downstream would have
1395
+ * gated a run on fiction.
1396
+ *
1397
+ * The gate validates the CONTRACT fields and refuses with a typed
1398
+ * {@link ConfigError} naming the field and the defect: enum `status`
1399
+ * and `completion`, finite nonnegative money (with `totalUsd <=
1400
+ * grossUsd`, gross being net plus abandoned by construction), usage
1401
+ * and counters, `settledReason` only beside `settled: false`, the
1402
+ * `costBasis` and `provenance` literals, boolean `usageApprox`, and
1403
+ * the `WireError` shape when an error rides along. Unknown top-level
1404
+ * fields pass through untouched: the contract evolves additively, and
1405
+ * a parser that refused tomorrow's field would turn every additive
1406
+ * release into a wire break. On success the SAME reference comes back,
1407
+ * typed: the gate is a boundary check, never a normalizer.
1408
+ *
1409
+ * Wired where external bytes actually enter: `persistedTerminalEnvelope`
1410
+ * runs every journal-rebuilt envelope through it (and refuses typed as
1411
+ * `malformed-envelope`), which also covers the server's persisted
1412
+ * serving by construction. The live settlement chokepoint stays
1413
+ * unparsed on purpose: it is the one producer inside one process, and
1414
+ * gating it would add a throw site to settlement itself.
1415
+ */
1416
+ function parseTerminalEnvelope(value) {
1417
+ if (!isPlainObject(value)) refuseEnvelope("value", "an object", value);
1418
+ requireNonEmptyString(value.runId, "runId");
1419
+ requireNonEmptyString(value.workflow, "workflow");
1420
+ if (typeof value.status !== "string" || !ENVELOPE_STATUSES.has(value.status)) refuseEnvelope("status", "one of 'ok' | 'error' | 'cancelled' | 'exhausted' | 'suspended'", value.status);
1421
+ requireBoolean(value.settled, "settled");
1422
+ if (value.settledReason !== void 0) {
1423
+ if (value.settledReason !== "superseded") refuseEnvelope("settledReason", "the literal 'superseded' when present", value.settledReason);
1424
+ if (value.settled !== false) refuseEnvelope("settledReason", "present only beside settled: false (a settled terminal has no supersession to explain)", value.settledReason);
1425
+ }
1426
+ const totalUsd = requireMoney(value.totalUsd, "totalUsd");
1427
+ const grossUsd = requireMoney(value.grossUsd, "grossUsd");
1428
+ if (totalUsd > grossUsd) refuseEnvelope("totalUsd", `at most grossUsd (${String(grossUsd)}): gross is the net fold plus abandoned spend`, totalUsd);
1429
+ if (value.costBasis !== "locally-estimated") refuseEnvelope("costBasis", "the literal 'locally-estimated'", value.costBasis);
1430
+ if (!isPlainObject(value.costByModel)) refuseEnvelope("costByModel", "an object of per-model dollars", value.costByModel);
1431
+ for (const [model, usd] of Object.entries(value.costByModel)) requireMoney(usd, `costByModel['${model}']`);
1432
+ if (value.wireRequests !== void 0) requireCount$1(value.wireRequests, "wireRequests");
1433
+ if (!isPlainObject(value.usage)) refuseEnvelope("usage", "a usage object", value.usage);
1434
+ requireUsageNumbers(value.usage, "usage");
1435
+ requireBoolean(value.usageApprox, "usageApprox");
1436
+ requireCount$1(value.agentsSpawned, "agentsSpawned");
1437
+ if (value.completion !== void 0 && (typeof value.completion !== "string" || !ENVELOPE_COMPLETIONS.has(value.completion))) refuseEnvelope("completion", "one of 'complete' | 'partial' | 'rejected' when present", value.completion);
1438
+ if (value.error !== void 0) {
1439
+ if (!isPlainObject(value.error)) refuseEnvelope("error", "a typed wire error object when present", value.error);
1440
+ requireNonEmptyString(value.error.code, "error.code");
1441
+ if (typeof value.error.message !== "string") refuseEnvelope("error.message", "a string", value.error.message);
1442
+ requireBoolean(value.error.retryable, "error.retryable");
1443
+ }
1444
+ if (value.deliverableAccepted !== void 0) requireBoolean(value.deliverableAccepted, "deliverableAccepted");
1445
+ if (value.resultAvailable !== void 0) requireBoolean(value.resultAvailable, "resultAvailable");
1446
+ if (value.acceptedArtifactRef !== void 0) requireCount$1(value.acceptedArtifactRef, "acceptedArtifactRef");
1447
+ if (value.claimConsistencyMeta !== void 0 && !isPlainObject(value.claimConsistencyMeta)) refuseEnvelope("claimConsistencyMeta", "an object when present", value.claimConsistencyMeta);
1448
+ if (value.configFingerprint !== void 0) requireNonEmptyString(value.configFingerprint, "configFingerprint");
1449
+ if (value.provenance !== void 0 && value.provenance !== "journal") refuseEnvelope("provenance", "the literal 'journal' when present", value.provenance);
1450
+ return value;
1451
+ }
1452
+ //#endregion
1313
1453
  //#region src/engine/terminal-envelope.ts
1314
1454
  /**
1315
1455
  * A total copy of one typed error (RV1213). `data` is `Json` by the
@@ -3112,7 +3252,7 @@ const MAX_TIMER_DELAY_MS = 2147483647;
3112
3252
  * century-long suspension journals as a perfectly valid date.
3113
3253
  */
3114
3254
  const MAX_DEADLINE_MS = 315576e7;
3115
- function refuse$1(site, requirement, value) {
3255
+ function refuse$2(site, requirement, value) {
3116
3256
  throw new ConfigError(`${site} must be ${requirement}; got ${String(value)}`);
3117
3257
  }
3118
3258
  /**
@@ -3129,26 +3269,26 @@ function requireDeadlineMs(value, site) {
3129
3269
  }
3130
3270
  /** An integer >= 1 (counts, caps, and depths). */
3131
3271
  function requirePositiveInteger$2(value, site) {
3132
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1) refuse$1(site, "a positive integer", value);
3272
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) refuse$2(site, "a positive integer", value);
3133
3273
  }
3134
3274
  /** An integer >= 0 (caps where zero means "none allowed"). */
3135
3275
  function requireNonNegativeInteger(value, site) {
3136
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuse$1(site, "a nonnegative integer", value);
3276
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuse$2(site, "a nonnegative integer", value);
3137
3277
  }
3138
3278
  /** A finite number >= 0 (USD amounts and reserves). */
3139
3279
  function requireNonNegativeNumber(value, site) {
3140
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuse$1(site, "a finite nonnegative number", value);
3280
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuse$2(site, "a finite nonnegative number", value);
3141
3281
  }
3142
3282
  /** A finite fraction in (0, 1]. */
3143
3283
  function requireFraction(value, site) {
3144
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) refuse$1(site, "a fraction in (0, 1]", value);
3284
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) refuse$2(site, "a fraction in (0, 1]", value);
3145
3285
  }
3146
3286
  /**
3147
3287
  * A relative delay handed to setTimeout as-is: an integer within the
3148
3288
  * Node timer maximum, mirroring validateRetryPolicy's bound.
3149
3289
  */
3150
3290
  function requireTimerDelayMs(value, site) {
3151
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 2147483647) refuse$1(site, "an integer between 1 and 2147483647 ms (the Node timer maximum)", value);
3291
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 2147483647) refuse$2(site, "an integer between 1 and 2147483647 ms (the Node timer maximum)", value);
3152
3292
  }
3153
3293
  /**
3154
3294
  * A declared evidence contract (RV303, enforcement RV507): minEntries
@@ -6198,8 +6338,12 @@ var LineageIndex = class {
6198
6338
  * exclusively DEBIT-ONLY API and a limits vector frozen at start in the
6199
6339
  * `termination.init` entry, plus the variant function Phi. No credit
6200
6340
  * operation exists anywhere by construction; no journal entry kind
6201
- * carries credit; B0 is immutable after start and no API, including
6202
- * HITL, can top it up. Every debit is atomic with the append of its
6341
+ * carries credit; B0 is immutable within a segment and no API,
6342
+ * including HITL, tops up a live run (the one explicit door is the
6343
+ * journaled ResumeOptions.run override at resume, RV2208, refused
6344
+ * outright under budgetPolicy 'immutable-lifetime', RV3902; the
6345
+ * frozen vector below keeps the GENESIS ceiling either way). Every
6346
+ * debit is atomic with the append of its
6203
6347
  * carrying decision entry and embeds the balance-after; an underflow
6204
6348
  * writes `termination.denied` strictly BEFORE the typed error surfaces.
6205
6349
  *
@@ -6303,8 +6447,9 @@ function readTerminationInit(entry) {
6303
6447
  /**
6304
6448
  * Config-drift detection at resume: the journaled vector
6305
6449
  * always wins; every differing field is reported for the
6306
- * `termination:config-drift` event. Dynamic budget top-up via restart is
6307
- * excluded by construction.
6450
+ * `termination:config-drift` event. Ambient config can never top up a
6451
+ * budget through a restart; the one explicit, journaled door is
6452
+ * ResumeOptions.run (RV2208), which is a decision entry, not a drift.
6308
6453
  */
6309
6454
  function terminationConfigDrift(frozen, live) {
6310
6455
  const drift = [];
@@ -8168,11 +8313,13 @@ var EscalationDecisionAbortedError = class extends Error {
8168
8313
  * Normalizes a resolution value into an ApprovalDecision. Anything that
8169
8314
  * is not an explicit allow is a deny: an approval never fails open.
8170
8315
  */
8171
- function toApprovalDecision(value) {
8316
+ function toApprovalDecision(value, entryRef) {
8172
8317
  const record = value ?? {};
8173
8318
  return {
8174
8319
  decision: record.decision === "allow" ? "allow" : "deny",
8175
- ...typeof record.reason === "string" ? { reason: record.reason } : {}
8320
+ ...typeof record.reason === "string" ? { reason: record.reason } : {},
8321
+ ...typeof record.expiresAt === "string" ? { expiresAt: record.expiresAt } : {},
8322
+ ...entryRef === void 0 ? {} : { entryRef }
8176
8323
  };
8177
8324
  }
8178
8325
  /**
@@ -8207,7 +8354,9 @@ function detachedApprovalFlavor(entry) {
8207
8354
  async function validatePayloadArms(kind, key, value, schemaSpec) {
8208
8355
  if (kind === "approval") {
8209
8356
  const decision = value?.decision;
8210
- if (decision !== "allow" && decision !== "deny") throw new InvalidResolutionError(`approval '${key}' resolves with { decision: 'allow' | 'deny', reason? }`);
8357
+ if (decision !== "allow" && decision !== "deny") throw new InvalidResolutionError(`approval '${key}' resolves with { decision: 'allow' | 'deny', reason?, expiresAt? }`);
8358
+ const expiresAt = value?.expiresAt;
8359
+ if (expiresAt !== void 0 && (typeof expiresAt !== "string" || Number.isNaN(Date.parse(expiresAt)))) throw new InvalidResolutionError(`approval '${key}' expiresAt must be an ISO 8601 date string; got ` + JSON.stringify(expiresAt));
8211
8360
  }
8212
8361
  if (kind === "decision") {
8213
8362
  const decisionKind = value?.kind;
@@ -8427,7 +8576,7 @@ var ExternalRegistry = class ExternalRegistry {
8427
8576
  entry = matched.running;
8428
8577
  replayed = true;
8429
8578
  const state = this.replayer.suspensionState(entry.seq);
8430
- if (state.state === "resolved") return toApprovalDecision(state.value);
8579
+ if (state.state === "resolved") return toApprovalDecision(state.value, entry.seq);
8431
8580
  if (state.state === "abandoned") {
8432
8581
  this.suspendActivity();
8433
8582
  return new Promise(() => void 0);
@@ -8459,7 +8608,7 @@ var ExternalRegistry = class ExternalRegistry {
8459
8608
  prompt: `approve tool '${options.toolName}'`,
8460
8609
  resolve: (value) => {
8461
8610
  resumeActivity();
8462
- resolve(toApprovalDecision(value));
8611
+ resolve(toApprovalDecision(value, entry.seq));
8463
8612
  }
8464
8613
  };
8465
8614
  if (entry.deadlineAt !== void 0) waiter.timer = setLongTimeout(() => {
@@ -8647,6 +8796,62 @@ var ExternalRegistry = class ExternalRegistry {
8647
8796
  * resolvable this way only once the segment settled (closed registry),
8648
8797
  * with the exact live-path validation and no wake.
8649
8798
  */
8799
+ /**
8800
+ * Revokes a tool approval (RV4008). A still-open approval is denied
8801
+ * through the ordinary first-closing-wins arbitration (a race with
8802
+ * a live allow stays deterministic by the journal). A RECORDED
8803
+ * allow cannot be unwritten (history is immutable): the revocation
8804
+ * appends an `approval_revoked` decision that beats the allow at
8805
+ * the consumption recheck, so an allow granted, crashed over, and
8806
+ * revoked never dispatches its tool on resume. A denied or
8807
+ * abandoned approval has nothing to revoke.
8808
+ */
8809
+ async revokeApproval(key, options) {
8810
+ if (typeof options.principal !== "string" || options.principal.length === 0) throw new InvalidResolutionError("revokeApproval principal must be a non empty string");
8811
+ if (typeof options.reason !== "string" || options.reason.length === 0) throw new InvalidResolutionError("revokeApproval reason must be a non empty string");
8812
+ const candidates = this.replayer.snapshot().filter((entry) => ExternalRegistry.suspensionKeyOf(entry) === key && entry.kind === "approval");
8813
+ const target = candidates[candidates.length - 1];
8814
+ if (target === void 0) throw new InvalidResolutionError(`no approval suspension with key '${key}' in this run`);
8815
+ const state = this.replayer.suspensionState(target.seq);
8816
+ if (state.state === "suspended") {
8817
+ await this.resolveExternal(key, {
8818
+ decision: "deny",
8819
+ reason: `revoked by ${options.principal}: ${options.reason}`
8820
+ });
8821
+ return {
8822
+ state: "denied-pending",
8823
+ entryRef: target.seq
8824
+ };
8825
+ }
8826
+ if (state.state === "resolved" && state.value?.decision === "allow") {
8827
+ if (this.replayer.snapshot().some((entry) => entry.kind === "decision" && entry.value?.decisionType === "approval_revoked" && entry.value.targetRef === target.seq)) return {
8828
+ state: "already-revoked",
8829
+ entryRef: target.seq
8830
+ };
8831
+ await this.replayer.appendSinglePhase({
8832
+ scope: target.scope,
8833
+ key: `approval-revoked:${String(target.seq)}`,
8834
+ kind: "decision",
8835
+ status: "ok",
8836
+ spanId: target.spanId ?? "",
8837
+ site: "approval-revocation",
8838
+ value: {
8839
+ decisionType: "approval_revoked",
8840
+ targetRef: target.seq,
8841
+ principal: options.principal,
8842
+ reason: options.reason
8843
+ }
8844
+ });
8845
+ return {
8846
+ state: "revoked-allow",
8847
+ entryRef: target.seq
8848
+ };
8849
+ }
8850
+ return {
8851
+ state: "already-closed",
8852
+ entryRef: target.seq
8853
+ };
8854
+ }
8650
8855
  async resolveDetached(key, value) {
8651
8856
  const candidates = this.replayer.snapshot().filter((entry) => ExternalRegistry.suspensionKeyOf(entry) === key);
8652
8857
  const open = candidates.find((entry) => this.replayer.suspensionState(entry.seq).state === "suspended");
@@ -9725,6 +9930,130 @@ function criticalPathFromJournal(entries) {
9725
9930
  return path;
9726
9931
  }
9727
9932
  //#endregion
9933
+ //#region src/stores/repair-ledger.ts
9934
+ const failedNamesOf = (failed) => {
9935
+ if (!Array.isArray(failed)) return [];
9936
+ return failed.map((row) => typeof row.name === "string" ? String(row.name) : void 0).filter((name) => name !== void 0);
9937
+ };
9938
+ const sectionsOf = (sections) => {
9939
+ if (!Array.isArray(sections) || sections.length === 0) return;
9940
+ const markers = sections.filter((marker) => typeof marker === "string");
9941
+ return markers.length === 0 ? void 0 : markers;
9942
+ };
9943
+ /**
9944
+ * Folds the workflow-wide repair ledger from a journal (RV4002). Pure
9945
+ * over the entries, so the acceptance envelope's live aggregate
9946
+ * (computed from the run's own snapshot at assembly) and a post-hoc
9947
+ * fold over the persisted journal agree by construction on every
9948
+ * count and row identity; `wireRef`/`costUsd` enrich rows exactly when
9949
+ * the asynchronous billing lane covered them.
9950
+ */
9951
+ function repairLedgerFromJournal(entries, priceUsd) {
9952
+ const ordered = [...entries].sort((a, b) => a.seq - b.seq);
9953
+ const rounds = [];
9954
+ const rowScopes = /* @__PURE__ */ new Map();
9955
+ let draft = 0;
9956
+ let composition = 0;
9957
+ let semantic = 0;
9958
+ let unstagedVerdicts = 0;
9959
+ /** Sectional acceptances by scope, to pair sections onto the rejection they healed. */
9960
+ const draftAccepts = [];
9961
+ const wireRows = [];
9962
+ for (const entry of ordered) {
9963
+ if (entry.kind === "agent" && entry.status !== "running" && entry.status !== "suspended") {
9964
+ if (entry.costAttribution?.label === "final-composition" && entry.costAttribution.phase === "repair") semantic += 1;
9965
+ continue;
9966
+ }
9967
+ if (entry.kind !== "decision") continue;
9968
+ const value = entry.value;
9969
+ if (value === void 0) continue;
9970
+ if (value.decisionType === "provider-call") {
9971
+ const row = entry.value;
9972
+ if (row.record?.phase === "repair") wireRows.push({
9973
+ seq: entry.seq,
9974
+ scope: entry.scope,
9975
+ record: row.record
9976
+ });
9977
+ continue;
9978
+ }
9979
+ if (value.decisionType === "orchestrator_draft_gate") {
9980
+ if (value.verdict === "rejected") {
9981
+ draft += 1;
9982
+ const row = {
9983
+ stage: "draft",
9984
+ seq: entry.seq,
9985
+ ...typeof value.callId === "string" ? { callId: value.callId } : {},
9986
+ failedValidators: failedNamesOf(value.failed)
9987
+ };
9988
+ rounds.push(row);
9989
+ rowScopes.set(row, entry.scope);
9990
+ } else if (value.verdict === "accepted" && value.spliced === true) {
9991
+ const sections = sectionsOf(value.sections);
9992
+ if (sections !== void 0) draftAccepts.push({
9993
+ seq: entry.seq,
9994
+ scope: entry.scope,
9995
+ sections
9996
+ });
9997
+ }
9998
+ continue;
9999
+ }
10000
+ if (value.decisionType === "orchestrator_finish_validation" && value.verdict === "repair") {
10001
+ if (value.stage !== "composition" && value.stage !== "round") {
10002
+ unstagedVerdicts += 1;
10003
+ continue;
10004
+ }
10005
+ composition += 1;
10006
+ const sections = sectionsOf(value.sections);
10007
+ const row = {
10008
+ stage: value.stage,
10009
+ seq: entry.seq,
10010
+ ...typeof value.callId === "string" ? { callId: value.callId } : {},
10011
+ failedValidators: failedNamesOf(value.failed),
10012
+ ...sections === void 0 ? {} : { sections }
10013
+ };
10014
+ rounds.push(row);
10015
+ rowScopes.set(row, entry.scope);
10016
+ continue;
10017
+ }
10018
+ if (value.decisionType === "orchestrator_finish_validation" && value.verdict === "accepted" && value.spliced === true) {
10019
+ const sections = sectionsOf(value.sections);
10020
+ if (sections !== void 0) draftAccepts.push({
10021
+ seq: entry.seq,
10022
+ scope: entry.scope,
10023
+ sections
10024
+ });
10025
+ }
10026
+ }
10027
+ for (const accept of draftAccepts) for (let index = rounds.length - 1; index >= 0; index -= 1) {
10028
+ const row = rounds[index];
10029
+ if (row === void 0 || row.seq >= accept.seq || row.sections !== void 0 || rowScopes.get(row) !== accept.scope) continue;
10030
+ row.sections = accept.sections;
10031
+ break;
10032
+ }
10033
+ for (const wire of wireRows) {
10034
+ let target;
10035
+ for (const row of rounds) {
10036
+ if (row.seq >= wire.seq || row.wireRef !== void 0 || rowScopes.get(row) !== wire.scope) continue;
10037
+ target = row;
10038
+ }
10039
+ if (target === void 0) continue;
10040
+ target.wireRef = wire.seq;
10041
+ if (priceUsd !== void 0 && wire.record.servedBy !== void 0) {
10042
+ const usd = priceUsd(wire.record.servedBy, wire.record.usage);
10043
+ if (usd !== void 0 && Number.isFinite(usd) && usd >= 0) target.costUsd = usd;
10044
+ }
10045
+ }
10046
+ rounds.sort((a, b) => a.seq - b.seq);
10047
+ return {
10048
+ draft,
10049
+ composition,
10050
+ semantic,
10051
+ total: draft + composition + semantic,
10052
+ rounds,
10053
+ unstagedVerdicts
10054
+ };
10055
+ }
10056
+ //#endregion
9728
10057
  //#region src/stores/synthesis-candidates.ts
9729
10058
  const parse = (at) => {
9730
10059
  if (at === void 0) return;
@@ -9953,9 +10282,17 @@ function toolCalibrationFromJournal(entries) {
9953
10282
  const budgetOnly = [];
9954
10283
  let dispatches = 0;
9955
10284
  let unobserved = 0;
10285
+ let coordinationDispatches = 0;
10286
+ let coordinationToolCalls = 0;
9956
10287
  for (const entry of ordered) {
9957
10288
  if (entry.kind !== "agent" || entry.ref === void 0 || entry.status === "running") continue;
9958
10289
  dispatches += 1;
10290
+ const role = entry.costAttribution?.role;
10291
+ if ((role === "orchestrate" || role === "synthesize") && entry.toolBudget !== void 0) {
10292
+ coordinationDispatches += 1;
10293
+ coordinationToolCalls += entry.toolBudget.used;
10294
+ continue;
10295
+ }
9959
10296
  const named = {
9960
10297
  scope: entry.scope,
9961
10298
  handle: entry.ref,
@@ -9978,7 +10315,11 @@ function toolCalibrationFromJournal(entries) {
9978
10315
  observed,
9979
10316
  evidenceOnly,
9980
10317
  budgetOnly,
9981
- unobserved
10318
+ unobserved,
10319
+ ...coordinationDispatches > 0 ? { coordination: {
10320
+ dispatches: coordinationDispatches,
10321
+ toolCallsUsed: coordinationToolCalls
10322
+ } } : {}
9982
10323
  };
9983
10324
  if (observed.length > 0) {
9984
10325
  const toolCallsUsed = observed.reduce((sum, row) => sum + row.toolCallsUsed, 0);
@@ -10794,6 +11135,19 @@ function fallbackTriggerOf(outcome) {
10794
11135
  }
10795
11136
  //#endregion
10796
11137
  //#region src/model/projector.ts
11138
+ /**
11139
+ * The RETENTION identity of an adapter (RV4007): the provider family,
11140
+ * composed with the adapter's declared `scopeKey` when one exists, so
11141
+ * two adapters of one family serving different accounts stop sharing
11142
+ * provider-raw blocks (cache handles, thinking blocks: provider-side
11143
+ * identifiers minted under one account are not portable to another).
11144
+ * Adapters without a scopeKey keep the family alone, byte for byte
11145
+ * the historical sharing.
11146
+ */
11147
+ function retentionKeyOf(adapter) {
11148
+ const family = providerOf(adapter);
11149
+ return adapter.scopeKey === void 0 ? family : `${family}#${adapter.scopeKey}`;
11150
+ }
10797
11151
  /** The provider family of an adapter: `provider` when set, else `id`. */
10798
11152
  function providerOf(adapter) {
10799
11153
  return adapter.provider ?? adapter.id;
@@ -10830,7 +11184,7 @@ function liftRetainedParts(providerMetadata, adapter) {
10830
11184
  const retained = namespace.retainedParts;
10831
11185
  if (!Array.isArray(retained)) return [];
10832
11186
  const blocks = retained;
10833
- const provider = providerOf(adapter);
11187
+ const provider = retentionKeyOf(adapter);
10834
11188
  return blocks.map((block) => ({
10835
11189
  type: "provider-raw",
10836
11190
  provider,
@@ -13487,6 +13841,13 @@ async function runAgent(options) {
13487
13841
  reservationId = decision.reservationId;
13488
13842
  const abandoned = await abortedAfterReserve(quota, decision.reservationId);
13489
13843
  if (abandoned !== void 0) return abandoned;
13844
+ if (options.billing?.onProviderIntent !== void 0) await options.billing.onProviderIntent({
13845
+ ordinal: providerCalls.length + 1,
13846
+ role: site.role,
13847
+ servedBy: target.resolved.ref,
13848
+ attempt: tries + 1,
13849
+ request: req
13850
+ });
13490
13851
  if (quota.reserveContinuations !== true) return streamTurn(target.adapter, req, meteredOptionsFor(target));
13491
13852
  const hooks = { onContinuationSegment: async () => {
13492
13853
  let segmentDecision;
@@ -13543,6 +13904,14 @@ async function runAgent(options) {
13543
13904
  if (options.quota === void 0) {
13544
13905
  const req = site.requestFor(target);
13545
13906
  admitExposure(req);
13907
+ const intentHook = options.billing?.onProviderIntent;
13908
+ if (intentHook !== void 0) return Promise.resolve(intentHook({
13909
+ ordinal: providerCalls.length + 1,
13910
+ role: site.role,
13911
+ servedBy: target.resolved.ref,
13912
+ attempt: tries + 1,
13913
+ request: req
13914
+ })).then(() => streamTurn(target.adapter, req, meteredOptionsFor(target)));
13546
13915
  return streamTurn(target.adapter, req, meteredOptionsFor(target));
13547
13916
  }
13548
13917
  return dispatchWithQuota(options.quota);
@@ -13636,6 +14005,7 @@ async function runAgent(options) {
13636
14005
  outcome: outcome.aborted !== void 0 ? "aborted" : outcome.wireError !== void 0 ? "error" : "ok",
13637
14006
  usage: accounted
13638
14007
  };
14008
+ if (site.phase !== void 0) record.phase = site.phase;
13639
14009
  if (typeof namespace?.responseId === "string") record.responseId = namespace.responseId;
13640
14010
  else if (typeof namespace?.response?.id === "string") record.responseId = namespace.response.id;
13641
14011
  const wire = namespace?.wireRequests;
@@ -13791,7 +14161,7 @@ async function runAgent(options) {
13791
14161
  chain: loopChain,
13792
14162
  cursor: loopCursor,
13793
14163
  requestFor: (target) => {
13794
- let req = buildRequest(target.resolved, projectHistory(drainMessages, providerOf(target.adapter)), limits, toolsRide ? allowedTools : void 0);
14164
+ let req = buildRequest(target.resolved, projectHistory(drainMessages, retentionKeyOf(target.adapter)), limits, toolsRide ? allowedTools : void 0);
13795
14165
  const reserveMax = limits.finalizationReserve?.maxOutputTokens;
13796
14166
  if (reserveMax !== void 0) req = {
13797
14167
  ...req,
@@ -13870,16 +14240,19 @@ async function runAgent(options) {
13870
14240
  break;
13871
14241
  }
13872
14242
  turns += 1;
14243
+ const lastWindowMessage = messages[messages.length - 1];
14244
+ const repairTurnWire = options.terminalTool !== void 0 && lastWindowMessage !== void 0 && lastWindowMessage.parts.some((part) => part.type === "tool-result" && part.name === options.terminalTool?.name && part.isError === true);
13873
14245
  const signals = [];
13874
14246
  if (options.signal !== void 0) signals.push(options.signal);
13875
14247
  let loopDispatch;
13876
14248
  try {
13877
14249
  loopDispatch = await dispatchPhase({
13878
14250
  role: primaryRole,
14251
+ ...repairTurnWire ? { phase: "repair" } : {},
13879
14252
  chain: loopChain,
13880
14253
  cursor: loopCursor,
13881
14254
  requestFor: (target) => {
13882
- let req = buildRequest(target.resolved, projectHistory(messages, providerOf(target.adapter)), limits, options.tools?.contracts);
14255
+ let req = buildRequest(target.resolved, projectHistory(messages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts);
13883
14256
  if (options.schema !== void 0 && options.canonicalSchema !== void 0 && !separateExtract) req = applyStructuredOutputTier(req, rideTierFor(target), options.canonicalSchema);
13884
14257
  req = applyCachePolicy(req, target, options.cache);
13885
14258
  return applyOutputBudget(req, target, options.budget);
@@ -14103,7 +14476,7 @@ async function runAgent(options) {
14103
14476
  }, ...options.summarize.fallbacks ?? []],
14104
14477
  cursor: { index: 0 },
14105
14478
  requestFor: (target) => {
14106
- let req = buildRequest(target.resolved, [...projectHistory(messages, providerOf(target.adapter)), summarizeInstruction()], limits, options.tools?.contracts);
14479
+ let req = buildRequest(target.resolved, [...projectHistory(messages, retentionKeyOf(target.adapter)), summarizeInstruction()], limits, options.tools?.contracts);
14107
14480
  if (req.tools !== void 0) req = {
14108
14481
  ...req,
14109
14482
  toolChoice: "none"
@@ -14207,7 +14580,17 @@ async function runAgent(options) {
14207
14580
  output = outcome.turn.text;
14208
14581
  break;
14209
14582
  }
14210
- if (separateExtract) break;
14583
+ if (separateExtract) {
14584
+ const rideAlong = extractCandidate(outcome.turn, rideTierFor(servedTarget));
14585
+ if (rideAlong !== void 0) {
14586
+ const validation = await validateSchemaSpec(options.schema, rideAlong.raw);
14587
+ if (validation.valid) {
14588
+ output = validation.value;
14589
+ break;
14590
+ }
14591
+ }
14592
+ break;
14593
+ }
14211
14594
  const candidate = extractCandidate(outcome.turn, rideTierFor(servedTarget));
14212
14595
  const issues = [];
14213
14596
  if (candidate !== void 0) {
@@ -14280,7 +14663,7 @@ async function runAgent(options) {
14280
14663
  chain: loopChain,
14281
14664
  cursor: loopCursor,
14282
14665
  requestFor: (target) => {
14283
- let req = buildRequest(target.resolved, projectHistory(reserveMessages, providerOf(target.adapter)), limits, options.tools?.contracts);
14666
+ let req = buildRequest(target.resolved, projectHistory(reserveMessages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts);
14284
14667
  if (options.schema !== void 0 && options.canonicalSchema !== void 0 && !separateExtract) req = applyStructuredOutputTier(req, rideTierFor(target), options.canonicalSchema);
14285
14668
  if (req.tools !== void 0) req = {
14286
14669
  ...req,
@@ -14416,7 +14799,7 @@ async function runAgent(options) {
14416
14799
  }, ...options.finalize.fallbacks ?? []],
14417
14800
  cursor: { index: 0 },
14418
14801
  requestFor: (target) => applyOutputBudget({
14419
- ...buildRequest(target.resolved, projectHistory(synthesisMessages, providerOf(target.adapter)), limits, options.tools?.contracts),
14802
+ ...buildRequest(target.resolved, projectHistory(synthesisMessages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts),
14420
14803
  toolChoice: "none"
14421
14804
  }, target, options.budget),
14422
14805
  streamOptionsFor: (target) => {
@@ -14496,7 +14879,7 @@ async function runAgent(options) {
14496
14879
  }
14497
14880
  endPhase(finalizePhase, phaseOutcome(), finalizeServed);
14498
14881
  }
14499
- if (status === "ok" && !finishedViaTool && separateExtract && options.extract !== void 0 && options.schema !== void 0) {
14882
+ if (status === "ok" && !finishedViaTool && separateExtract && output === null && options.extract !== void 0 && options.schema !== void 0) {
14500
14883
  const extractResolved = options.extract.resolved;
14501
14884
  const extractPhase = beginPhase("extract", extractResolved.ref);
14502
14885
  let extractServed;
@@ -14535,12 +14918,13 @@ async function runAgent(options) {
14535
14918
  cursor: extractCursor,
14536
14919
  requestFor: (target) => {
14537
14920
  const targetTier = extractTierFor(target);
14538
- let req = buildRequest(target.resolved, projectHistory(extractMessages, providerOf(target.adapter)), limits, options.tools?.contracts);
14921
+ let req = buildRequest(target.resolved, projectHistory(extractMessages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts);
14539
14922
  if (req.tools !== void 0 && targetTier !== "forced-tool") req = {
14540
14923
  ...req,
14541
14924
  toolChoice: "none"
14542
14925
  };
14543
14926
  req = applyStructuredOutputTier(req, targetTier, options.canonicalSchema ?? {});
14927
+ req = applyCachePolicy(req, target, options.cache);
14544
14928
  return applyOutputBudget(req, target, options.budget);
14545
14929
  },
14546
14930
  streamOptionsFor: (target) => {
@@ -14723,7 +15107,10 @@ async function runAgent(options) {
14723
15107
  * false). The one thing that can change it is `ResumeOptions.run`, an
14724
15108
  * explicit host decision journaled as its own decision entry, and it
14725
15109
  * takes effect only by opening a NEW segment: a live run can never
14726
- * raise the bound it is already being measured against.
15110
+ * raise the bound it is already being measured against. Under
15111
+ * RunOptions.budgetPolicy 'immutable-lifetime' (RV3902) even that door
15112
+ * refuses typed before ownership, and the recorded ceilings hold for
15113
+ * the run's whole life.
14727
15114
  *
14728
15115
  * The account tree: the run root plus one
14729
15116
  * sub-account per admitted child workflow (and, from M7, the orchestrator
@@ -14821,7 +15208,12 @@ function admissionReserveUsd(options) {
14821
15208
  * spawn-admission decision entries, M6).
14822
15209
  */
14823
15210
  var RunBudget = class {
14824
- /** B0; immutable after start. Undefined means no USD ceiling. */
15211
+ /**
15212
+ * B0; immutable within a segment (RV2511): only the explicit,
15213
+ * journaled ResumeOptions.run override (RV2208) changes it, by
15214
+ * opening a new segment, and budgetPolicy 'immutable-lifetime'
15215
+ * (RV3902) refuses even that. Undefined means no USD ceiling.
15216
+ */
14825
15217
  ceilingUsd;
14826
15218
  /**
14827
15219
  * The opt-in in-flight exposure cap (RV711). Undefined means the
@@ -15908,7 +16300,12 @@ function costReportFromJournal(entries, priceUsd) {
15908
16300
  if (entry.usageApprox === true) usageApprox = true;
15909
16301
  const facts = entry.costAttribution;
15910
16302
  const phase = attributionBucket(facts?.phase);
15911
- byPhase[phase] = (byPhase[phase] ?? 0) + priced.usd;
16303
+ let phaseUsd = priced.usd;
16304
+ for (const unit of priced.units) if (unit.source === "call" && unit.record?.phase === "repair") {
16305
+ byPhase.repair = (byPhase.repair ?? 0) + unit.usd;
16306
+ phaseUsd -= unit.usd;
16307
+ }
16308
+ byPhase[phase] = (byPhase[phase] ?? 0) + phaseUsd;
15912
16309
  const agentType = attributionBucket(facts?.agentType);
15913
16310
  byAgentType[agentType] = (byAgentType[agentType] ?? 0) + priced.usd;
15914
16311
  const scope = scopeBucket(entry.scope);
@@ -16197,6 +16594,48 @@ function rowUsd(priceUsd, servedBy, usage, seq) {
16197
16594
  return usd !== void 0 && Number.isFinite(usd) && usd >= 0 ? usd : void 0;
16198
16595
  }
16199
16596
  /**
16597
+ * The open provider wire intents of a journal (RV4006): every
16598
+ * `provider-intent` decision with neither a `provider-call` receipt
16599
+ * row nor a settled terminal record covering its (agentRef, ordinal,
16600
+ * attempt). ONE pairing rule, shared by the invoice's `openIntents`
16601
+ * lane and the resume refusal, the dispatchProjectionReserveUsd
16602
+ * precedent: the linter and the gate cannot drift.
16603
+ */
16604
+ function openWireIntentsOf(entries) {
16605
+ const terminals = /* @__PURE__ */ new Map();
16606
+ const receipts = /* @__PURE__ */ new Set();
16607
+ const intents = [];
16608
+ for (const entry of entries) {
16609
+ if (entry.kind === "agent" && entry.status !== "running" && typeof entry.ref === "number") {
16610
+ terminals.set(entry.ref, entry);
16611
+ continue;
16612
+ }
16613
+ if (entry.kind !== "decision") continue;
16614
+ const value = entry.value;
16615
+ if (value?.decisionType === "provider-call" && typeof value.agentRef === "number") {
16616
+ const ordinal = value.record?.ordinal;
16617
+ const attempt = typeof value.record?.attempt === "number" ? value.record.attempt : 1;
16618
+ if (typeof ordinal === "number") receipts.add(`${String(value.agentRef)}:${String(ordinal)}:${String(attempt)}`);
16619
+ continue;
16620
+ }
16621
+ if (value?.decisionType === "provider-intent" && typeof value.agentRef === "number" && typeof value.ordinal === "number" && typeof value.attempt === "number" && typeof value.servedBy === "string") intents.push({
16622
+ seq: entry.seq,
16623
+ scope: entry.scope,
16624
+ agentRef: value.agentRef,
16625
+ ordinal: value.ordinal,
16626
+ attempt: value.attempt,
16627
+ servedBy: value.servedBy,
16628
+ ...typeof value.requestFingerprint === "string" ? { requestFingerprint: value.requestFingerprint } : {}
16629
+ });
16630
+ }
16631
+ return intents.filter((intent) => {
16632
+ if (receipts.has(`${String(intent.agentRef)}:${String(intent.ordinal)}:${String(intent.attempt)}`)) return false;
16633
+ const terminal = terminals.get(intent.agentRef);
16634
+ if (terminal === void 0) return true;
16635
+ return !(terminal.providerCalls ?? []).some((call) => call.ordinal === intent.ordinal && call.attempt === intent.attempt);
16636
+ });
16637
+ }
16638
+ /**
16200
16639
  * The pure invoice fold. Pass the same entries and price table you
16201
16640
  * would pass `costReportFromJournal`; the totals are that report's
16202
16641
  * gross/net split verbatim. To make the export historically stable
@@ -16215,10 +16654,13 @@ function invoiceFromJournal(entries, priceUsd, options) {
16215
16654
  const billing = priceEntryBilling(entry, priceUsd);
16216
16655
  if (!billing.fullyAttributed) everyEntryFullyAttributed = false;
16217
16656
  const abandoned = entry.kind !== "resolution" && entry.kind !== "abandon" && abandonFold.isAbandoned(entry.ref ?? entry.seq);
16657
+ const attribution = entry.costAttribution;
16218
16658
  const base = {
16219
16659
  entrySeq: entry.seq,
16220
16660
  scope: entry.scope,
16221
- key: entry.key
16661
+ key: entry.key,
16662
+ ...attribution?.agentType === void 0 || attribution.agentType === "" ? {} : { agentType: attribution.agentType },
16663
+ ...attribution?.label === void 0 ? {} : { label: attribution.label }
16222
16664
  };
16223
16665
  const mark = abandoned ? { abandoned: true } : {};
16224
16666
  const records = entry.providerCalls ?? [];
@@ -16359,6 +16801,21 @@ function invoiceFromJournal(entries, priceUsd, options) {
16359
16801
  cardinality: cardinalityOf(rows),
16360
16802
  ...unsettled === void 0 ? {} : { unsettled },
16361
16803
  ...orphanedReceipts === void 0 ? {} : { orphanedReceipts },
16804
+ ...(() => {
16805
+ for (const entry of entries) {
16806
+ if (entry.kind !== "decision") continue;
16807
+ const value = entry.value;
16808
+ if (value?.decisionType === "execution_scope" && typeof value.scope === "object") return { executionScope: value.scope };
16809
+ }
16810
+ return {};
16811
+ })(),
16812
+ ...(() => {
16813
+ const open = openWireIntentsOf(entries);
16814
+ return open.length === 0 ? {} : { openIntents: {
16815
+ count: open.length,
16816
+ rows: open
16817
+ } };
16818
+ })(),
16362
16819
  ...(() => {
16363
16820
  const count = rows.filter((row) => row.usageUnknown === true).length;
16364
16821
  return count === 0 ? {} : { usageUnknownRows: count };
@@ -16956,7 +17413,8 @@ function statementRowsFromDelimited(text, options) {
16956
17413
  const REFUSAL_MESSAGES = {
16957
17414
  unsettled: "no run settle is journaled for this run: nothing durable records a terminal",
16958
17415
  "not-terminal": "the journaled run settle records a running segment, not a terminal",
16959
- "unknown-workflow": "no stored metadata names the workflow this run belongs to"
17416
+ "unknown-workflow": "no stored metadata names the workflow this run belongs to",
17417
+ "malformed-envelope": "the rebuilt envelope failed the runtime terminal contract gate: the journal bytes produced values the contract forbids"
16960
17418
  };
16961
17419
  /** Every envelope status; a settle may also record the non-terminal 'running'. */
16962
17420
  const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
@@ -16966,7 +17424,7 @@ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
16966
17424
  "exhausted",
16967
17425
  "suspended"
16968
17426
  ]);
16969
- function refuse(reason, message = REFUSAL_MESSAGES[reason]) {
17427
+ function refuse$1(reason, message = REFUSAL_MESSAGES[reason]) {
16970
17428
  return {
16971
17429
  available: false,
16972
17430
  reason,
@@ -16982,16 +17440,24 @@ function refuse(reason, message = REFUSAL_MESSAGES[reason]) {
16982
17440
  */
16983
17441
  function persistedTerminalEnvelope(input) {
16984
17442
  const settle = lastRunSettle(input.entries);
16985
- if (settle === void 0) return refuse("unsettled");
16986
- if (!TERMINAL_STATUSES.has(settle.runStatus)) return refuse("not-terminal");
17443
+ if (settle === void 0) return refuse$1("unsettled");
17444
+ if (!TERMINAL_STATUSES.has(settle.runStatus)) return refuse$1("not-terminal");
16987
17445
  const tail = input.entries.filter((entry) => entry.seq > settle.seq).length;
16988
- if (tail > 0) return refuse("not-terminal", `the journal continued ${String(tail)} entr${tail === 1 ? "y" : "ies"} past the settle at seq ${String(settle.seq)}: the latest segment is not settled`);
17446
+ if (tail > 0) return refuse$1("not-terminal", `the journal continued ${String(tail)} entr${tail === 1 ? "y" : "ies"} past the settle at seq ${String(settle.seq)}: the latest segment is not settled`);
16989
17447
  const workflow = input.meta?.workflowName;
16990
- if (workflow === void 0) return refuse("unknown-workflow");
17448
+ if (workflow === void 0) return refuse$1("unknown-workflow");
17449
+ try {
17450
+ return assemble(input, workflow, settle);
17451
+ } catch (error) {
17452
+ const detail = error instanceof Error ? error.message : String(error);
17453
+ return refuse$1("malformed-envelope", `${REFUSAL_MESSAGES["malformed-envelope"]}: ${detail}`);
17454
+ }
17455
+ }
17456
+ function assemble(input, workflow, settle) {
16991
17457
  const ledger = foldLedger(input.entries, buildAbandonFold(input.entries));
16992
17458
  return {
16993
17459
  available: true,
16994
- envelope: terminalEnvelopeOf({
17460
+ envelope: parseTerminalEnvelope(terminalEnvelopeOf({
16995
17461
  runId: input.runId,
16996
17462
  workflow,
16997
17463
  outcome: {
@@ -17007,7 +17473,7 @@ function persistedTerminalEnvelope(input) {
17007
17473
  agentsSpawned: ledger.agentsSpawned,
17008
17474
  ...input.meta?.configFingerprint === void 0 ? {} : { configFingerprint: input.meta.configFingerprint },
17009
17475
  provenance: "journal"
17010
- })
17476
+ }))
17011
17477
  };
17012
17478
  }
17013
17479
  //#endregion
@@ -17608,6 +18074,117 @@ function dispatchProjectionReserveUsd(spec, flatReserveUsd) {
17608
18074
  const base = spec.estCostUsd ?? flatReserveUsd;
17609
18075
  return spec.budgetUsd === void 0 ? base : Math.min(base, spec.budgetUsd);
17610
18076
  }
18077
+ /**
18078
+ * Worst-case claim judge dispatches of a declared posture
18079
+ * (RV3402/RV4001): `'both'` dispatches the judge at the draft AND the
18080
+ * final, and an armed repair round (`onFound: 'repair'`, which intake
18081
+ * refuses at stage 'draft') rejudges the repaired composition once
18082
+ * more. Absent declarations read as the historical one pass.
18083
+ */
18084
+ function acceptanceJudgePasses(stage, onFound) {
18085
+ const resolvedStage = stage ?? "draft";
18086
+ return (resolvedStage === "both" ? 2 : 1) + ((onFound ?? "report") === "repair" && resolvedStage !== "draft" ? 1 : 0);
18087
+ }
18088
+ /**
18089
+ * The ONE acceptance-tail formula (RV4001, the fifth comparison
18090
+ * experiment): what the effective cap must cover, at exact fill or
18091
+ * better, so the acceptance machinery the host declared is funded and
18092
+ * not started on luck. The RV3907 runtime gate landed WITHOUT a
18093
+ * preflight twin: preflight kept its own advisory arithmetic on
18094
+ * different terms, passed the experiment's plan green at a $4.54 cap,
18095
+ * and the runtime then refused the same plan typed at $4.82 before the
18096
+ * first wire; worse, the runtime undercounted the judge passes of
18097
+ * `stage: 'both'` (one where the worst case dispatches two) while
18098
+ * preflight counted them right, so the two calculators disagreed in
18099
+ * BOTH directions. The gate and the preflight `acceptanceReserve`
18100
+ * report block now both call this function, exactly the
18101
+ * {@link dispatchProjectionReserveUsd} precedent: one formula, so the
18102
+ * linter and the runtime cannot drift. Undeclared estimates contribute
18103
+ * zero: the tail binds exactly what the host declared. The armed
18104
+ * repair round (`onFound: 'repair'`, never at stage 'draft', which
18105
+ * intake refuses) adds one judge pass and one composition priced at
18106
+ * the declared `synthesis.estCost`.
18107
+ */
18108
+ function acceptanceTailRequiredUsd(spec) {
18109
+ const stage = spec.claimStage ?? "draft";
18110
+ const onFound = spec.claimOnFound ?? "report";
18111
+ const citationDeclared = spec.citationJudgeEstCostUsd !== void 0 || spec.citationOnFound !== void 0;
18112
+ const citationRoundArmed = spec.citationOnFound === "repair";
18113
+ const roundArmed = onFound === "repair" && stage !== "draft" || citationRoundArmed;
18114
+ const judgePasses = acceptanceJudgePasses(spec.claimStage, spec.claimOnFound) + (citationRoundArmed && spec.claimConfigured === true && stage !== "draft" ? 1 : 0);
18115
+ const citationJudgePasses = citationDeclared ? 1 + (citationRoundArmed ? 1 : 0) : 0;
18116
+ const citationJudgeEstUsd = spec.citationJudgeEstCostUsd ?? 0;
18117
+ const terms = {
18118
+ synthesisReserveUsd: spec.synthesisReserveUsd ?? 0,
18119
+ judgeEstUsd: spec.claimJudgeEstCostUsd ?? 0,
18120
+ judgePasses,
18121
+ estRepairCostUsd: spec.finishEstRepairCostUsd ?? 0,
18122
+ roundCompositionUsd: roundArmed ? spec.synthesisEstCostUsd ?? 0 : 0,
18123
+ ...citationDeclared ? {
18124
+ citationJudgeEstUsd,
18125
+ citationJudgePasses
18126
+ } : {},
18127
+ workingRoomUsd: spec.workingRoomUsd
18128
+ };
18129
+ return {
18130
+ requiredUsd: terms.synthesisReserveUsd + terms.judgeEstUsd * terms.judgePasses + terms.estRepairCostUsd + terms.roundCompositionUsd + citationJudgeEstUsd * citationJudgePasses + terms.workingRoomUsd,
18131
+ terms
18132
+ };
18133
+ }
18134
+ /**
18135
+ * The one rendering of the tail arithmetic (RV4001): the runtime
18136
+ * refusal message and the preflight finding print this same string, so
18137
+ * an operator can diff them by eye and a test can assert them equal.
18138
+ */
18139
+ function formatAcceptanceTailTerms(terms) {
18140
+ const citationUsd = (terms.citationJudgeEstUsd ?? 0) * (terms.citationJudgePasses ?? 0);
18141
+ const requiredUsd = terms.synthesisReserveUsd + terms.judgeEstUsd * terms.judgePasses + terms.estRepairCostUsd + terms.roundCompositionUsd + citationUsd + terms.workingRoomUsd;
18142
+ return `synthesisReserveUsd ${terms.synthesisReserveUsd.toFixed(4)} + judge ${terms.judgeEstUsd.toFixed(4)} x ${String(terms.judgePasses)} pass(es) + estRepairCostUsd ${terms.estRepairCostUsd.toFixed(4)} + round composition ${terms.roundCompositionUsd.toFixed(4)} + ` + (terms.citationJudgePasses === void 0 || terms.citationJudgePasses === 0 ? "" : `citation judge ${(terms.citationJudgeEstUsd ?? 0).toFixed(4)} x ${String(terms.citationJudgePasses)} pass(es) + `) + `working room ${terms.workingRoomUsd.toFixed(4)} = ${requiredUsd.toFixed(4)} USD`;
18143
+ }
18144
+ /**
18145
+ * The wire capacity of a declared orchestration plan (RV4005, the
18146
+ * fifth comparison experiment): base wires by declaration, the armed
18147
+ * repair round's delta, and the round's overhead share, from ONE
18148
+ * exported function so an answer about the runtime's own economics
18149
+ * has a source instead of an improvisation. The experiment's terminal
18150
+ * answer wrote "34 wires without repair, 35 with" and multiplied
18151
+ * retry share as `1 + r`: the round is TWO wires (its composition
18152
+ * plus the rejudge, `orchestrate.ts`'s own doctrine), so 34 becomes
18153
+ * 36 at 5.88 percent overhead, and r retries over a base of B
18154
+ * multiply wires by `1 + r/B` ({@link retryWireMultiplier}), not by
18155
+ * `1 + r`.
18156
+ */
18157
+ function wireCapacityEstimate(spec) {
18158
+ requireNonNegativeNumber(spec.childWires, "wireCapacityEstimate childWires");
18159
+ const coordinationWires = spec.coordinationWires ?? 0;
18160
+ const synthesisWires = spec.synthesisWires ?? 0;
18161
+ const judgeWires = spec.judgeWires ?? 0;
18162
+ const extractWires = spec.extractWires ?? 0;
18163
+ requireNonNegativeNumber(coordinationWires, "wireCapacityEstimate coordinationWires");
18164
+ requireNonNegativeNumber(synthesisWires, "wireCapacityEstimate synthesisWires");
18165
+ requireNonNegativeNumber(judgeWires, "wireCapacityEstimate judgeWires");
18166
+ requireNonNegativeNumber(extractWires, "wireCapacityEstimate extractWires");
18167
+ const baseWires = spec.childWires + coordinationWires + synthesisWires + judgeWires + extractWires;
18168
+ const repairRoundDeltaWires = 2;
18169
+ return {
18170
+ baseWires,
18171
+ repairRoundDeltaWires,
18172
+ mechanicalRepairDeltaWires: 1,
18173
+ wiresWithRound: baseWires + repairRoundDeltaWires,
18174
+ roundOverheadShare: baseWires === 0 ? 0 : repairRoundDeltaWires / baseWires
18175
+ };
18176
+ }
18177
+ /**
18178
+ * The retry share of a wire plan (RV4005): r retries over a base of B
18179
+ * wires re-dispatch r of the B, so totals scale by `1 + r/B`. The
18180
+ * fifth comparison run's answer multiplied by `1 + r`, reading every
18181
+ * retry as a whole extra plan.
18182
+ */
18183
+ function retryWireMultiplier(baseWires, retries) {
18184
+ requireNonNegativeNumber(retries, "retryWireMultiplier retries");
18185
+ if (!Number.isFinite(baseWires) || baseWires <= 0) throw new ConfigError(`retryWireMultiplier baseWires must be a positive finite number; got ${String(baseWires)}`);
18186
+ return 1 + retries / baseWires;
18187
+ }
17611
18188
  /** Nesting depth of a child scope: its workflow, agent, and plan-node segments. */
17612
18189
  function spawnDepthOf(childScope) {
17613
18190
  return parseScopePath(childScope).filter((segment) => segment.kind === "workflow" || segment.kind === "agent" || segment.kind === "plan-node").length;
@@ -19038,7 +19615,12 @@ function createCtx(internals, rootWorkflow) {
19038
19615
  model: slice.servedBy,
19039
19616
  usage: slice.usage
19040
19617
  });
19041
- bump(internals.cost.byPhase, state.phase ?? "", costUsd);
19618
+ let replayPhaseUsd = costUsd;
19619
+ for (const unit of replayPriced?.units ?? []) if (unit.source === "call" && unit.record?.phase === "repair") {
19620
+ bump(internals.cost.byPhase, "repair", unit.usd);
19621
+ replayPhaseUsd -= unit.usd;
19622
+ }
19623
+ bump(internals.cost.byPhase, state.phase ?? "", replayPhaseUsd);
19042
19624
  bump(internals.cost.byAgentType, agentType, costUsd);
19043
19625
  bump(internals.cost.byScope, state.scope, costUsd);
19044
19626
  internals.cost.byRole.set(primaryRole, (internals.cost.byRole.get(primaryRole) ?? 0) + costUsd);
@@ -19352,7 +19934,7 @@ function createCtx(internals, rootWorkflow) {
19352
19934
  suspend: async () => {
19353
19935
  if (internals.external === void 0) throw new ConfigError("tool approvals require the engine run context (createEngine)");
19354
19936
  const approvalDeadlineMs = chain.approvalDeadlineMs;
19355
- return internals.external.awaitApproval({
19937
+ const decision = await internals.external.awaitApproval({
19356
19938
  scope: agentScope(state.scope, running.seq),
19357
19939
  spanId: internals.spans.mint(spanId),
19358
19940
  toolName: call.name,
@@ -19365,6 +19947,22 @@ function createCtx(internals, rootWorkflow) {
19365
19947
  entryRef: entry.seq
19366
19948
  }, spanId, replayed)
19367
19949
  });
19950
+ if (decision.decision !== "allow") return decision;
19951
+ if (decision.entryRef !== void 0) {
19952
+ const revocation = internals.replayer.snapshot().find((entry) => entry.kind === "decision" && entry.value?.decisionType === "approval_revoked" && entry.value.targetRef === decision.entryRef);
19953
+ if (revocation !== void 0) {
19954
+ const why = revocation.value ?? {};
19955
+ return {
19956
+ decision: "deny",
19957
+ reason: `the recorded allow was revoked by ${typeof why.principal === "string" ? why.principal : "unknown"}: ${typeof why.reason === "string" ? why.reason : "no reason recorded"}`
19958
+ };
19959
+ }
19960
+ }
19961
+ if (decision.expiresAt !== void 0 && !(Date.parse(decision.expiresAt) >= internals.now())) return {
19962
+ decision: "deny",
19963
+ reason: `the recorded allow expired at ${decision.expiresAt}`
19964
+ };
19965
+ return decision;
19368
19966
  }
19369
19967
  };
19370
19968
  }
@@ -19452,28 +20050,47 @@ function createCtx(internals, rootWorkflow) {
19452
20050
  const cachePolicy = opts.cache ?? profile?.cache ?? internals.defaults.cache;
19453
20051
  if (cachePolicy !== void 0) runAgentOptions.cache = cachePolicy;
19454
20052
  }
19455
- runAgentOptions.billing = { onProviderCall: (record) => {
19456
- const append = internals.replayer.appendSinglePhase({
20053
+ runAgentOptions.billing = {
20054
+ onProviderCall: (record) => {
20055
+ const append = internals.replayer.appendSinglePhase({
20056
+ scope: state.scope,
20057
+ key: `pc:${String(running.seq)}:${String(record.ordinal)}`,
20058
+ kind: "decision",
20059
+ status: "ok",
20060
+ spanId,
20061
+ site: "provider-call",
20062
+ value: {
20063
+ decisionType: "provider-call",
20064
+ agentRef: running.seq,
20065
+ record
20066
+ }
20067
+ }).then(() => void 0).catch((thrown) => {
20068
+ internals.events.emit({
20069
+ type: "log",
20070
+ level: "warn",
20071
+ msg: `incremental billing row failed to append; the terminal entry remains the canonical record (${thrown instanceof Error ? thrown.message : String(thrown)})`
20072
+ }, spanId);
20073
+ });
20074
+ if (internals.defaults.billingReceipts === "awaited" || internals.defaults.billingReceipts === "intent") return append;
20075
+ },
20076
+ ...internals.defaults.billingReceipts === "intent" ? { onProviderIntent: (intent) => internals.replayer.appendSinglePhase({
19457
20077
  scope: state.scope,
19458
- key: `pc:${String(running.seq)}:${String(record.ordinal)}`,
20078
+ key: `pi:${String(running.seq)}:${String(intent.ordinal)}:${String(intent.attempt)}`,
19459
20079
  kind: "decision",
19460
20080
  status: "ok",
19461
20081
  spanId,
19462
- site: "provider-call",
20082
+ site: "provider-intent",
19463
20083
  value: {
19464
- decisionType: "provider-call",
20084
+ decisionType: "provider-intent",
19465
20085
  agentRef: running.seq,
19466
- record
20086
+ ordinal: intent.ordinal,
20087
+ role: intent.role,
20088
+ servedBy: intent.servedBy,
20089
+ attempt: intent.attempt,
20090
+ requestFingerprint: createHash("sha256").update(jcsSerialize(intent.request.messages), "utf8").digest("hex")
19467
20091
  }
19468
- }).then(() => void 0).catch((thrown) => {
19469
- internals.events.emit({
19470
- type: "log",
19471
- level: "warn",
19472
- msg: `incremental billing row failed to append; the terminal entry remains the canonical record (${thrown instanceof Error ? thrown.message : String(thrown)})`
19473
- }, spanId);
19474
- });
19475
- if (internals.defaults.billingReceipts === "awaited") return append;
19476
- } };
20092
+ }).then(() => void 0) } : {}
20093
+ };
19477
20094
  runAgentOptions.summarize = summarize;
19478
20095
  if (profile?.compaction !== void 0) runAgentOptions.compaction = profile.compaction;
19479
20096
  if (profile?.evidenceContract !== void 0) runAgentOptions.evidenceContract = profile.evidenceContract;
@@ -19814,7 +20431,15 @@ function createCtx(internals, rootWorkflow) {
19814
20431
  const sliceRole = slice.role ?? primaryRole;
19815
20432
  internals.cost.byRole.set(sliceRole, (internals.cost.byRole.get(sliceRole) ?? 0) + priced);
19816
20433
  }
19817
- bump(internals.cost.byPhase, state.phase ?? "", usd);
20434
+ let livePhaseUsd = usd;
20435
+ for (const record of result.providerCalls ?? []) {
20436
+ if (record.phase !== "repair") continue;
20437
+ const recordUsd = internals.priceUsd(record.servedBy, record.usage);
20438
+ if (recordUsd === void 0 || !Number.isFinite(recordUsd) || recordUsd < 0) continue;
20439
+ bump(internals.cost.byPhase, "repair", recordUsd);
20440
+ livePhaseUsd -= recordUsd;
20441
+ }
20442
+ bump(internals.cost.byPhase, state.phase ?? "", livePhaseUsd);
19818
20443
  bump(internals.cost.byAgentType, agentType, usd);
19819
20444
  bump(internals.cost.byScope, state.scope, usd);
19820
20445
  if (result.error?.kind === "budget" || internals.budget.exhausted && result.status !== "ok") {
@@ -22047,6 +22672,212 @@ function renderContractRequirements(manifest) {
22047
22672
  return lines.join("\n");
22048
22673
  }
22049
22674
  //#endregion
22675
+ //#region src/orchestrator/citation-audit.ts
22676
+ const DEFAULT_CITATION_SAMPLE_PER_SECTION = 2;
22677
+ const DEFAULT_CITATION_MAX_SAMPLED = 24;
22678
+ const DEFAULT_CITATION_EXCERPT_WINDOW = 3;
22679
+ /** Excerpt bounds, the claim-pass excerpt discipline. */
22680
+ const MAX_CITATION_EXCERPT_LINES = 12;
22681
+ const MAX_CITATION_EXCERPT_CHARS = 800;
22682
+ /** A citation with an optional `-end` range tail on the line half. */
22683
+ const citationWithRange = (pattern) => new RegExp(pattern, "gu");
22684
+ const RANGE_TAIL = /^(.*):(\d+)(?:-(\d+))?$/u;
22685
+ /**
22686
+ * Validates the declared plan numbers; returns the resolved bounds.
22687
+ * Garbage throws like every malformed intake.
22688
+ */
22689
+ function resolveCitationAuditPlan(options) {
22690
+ const samplePerSection = options.samplePerSection ?? 2;
22691
+ if (!Number.isInteger(samplePerSection) || samplePerSection < 1) throw new ConfigError(`citationAudit.samplePerSection must be a positive integer; got ${String(options.samplePerSection)}`);
22692
+ const maxSampled = options.maxSampled ?? 24;
22693
+ if (!Number.isInteger(maxSampled) || maxSampled < 1) throw new ConfigError(`citationAudit.maxSampled must be a positive integer; got ${String(options.maxSampled)}`);
22694
+ const window = options.window ?? 3;
22695
+ if (!Number.isInteger(window) || window < 0) throw new ConfigError(`citationAudit.window must be a non negative integer; got ${String(options.window)}`);
22696
+ const pattern = options.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
22697
+ let probe;
22698
+ try {
22699
+ probe = new RegExp(pattern, "gu");
22700
+ } catch (thrown) {
22701
+ throw new ConfigError(`citationAudit.pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
22702
+ }
22703
+ if (probe.test("")) throw new ConfigError("citationAudit.pattern matches the empty string: it would flood the sample instead of anchoring it");
22704
+ return {
22705
+ pattern,
22706
+ samplePerSection,
22707
+ maxSampled,
22708
+ window
22709
+ };
22710
+ }
22711
+ /** Splits a document into (section marker, body) runs in order. */
22712
+ function sectionsOfDocument(document) {
22713
+ const lines = document.split("\n");
22714
+ const runs = [{
22715
+ marker: "",
22716
+ body: []
22717
+ }];
22718
+ for (const line of lines) {
22719
+ if (/^##\s+\S/u.test(line) && !line.startsWith("###")) {
22720
+ runs.push({
22721
+ marker: line.trim(),
22722
+ body: []
22723
+ });
22724
+ continue;
22725
+ }
22726
+ runs.at(-1)?.body.push(line);
22727
+ }
22728
+ return runs.map((run) => ({
22729
+ marker: run.marker,
22730
+ body: run.body.join("\n")
22731
+ })).filter((run) => run.body.trim().length > 0);
22732
+ }
22733
+ /** The deterministic per-section pick: seeded index selection without replacement. */
22734
+ function pickIndexes(count, k, seedInput) {
22735
+ const indexes = Array.from({ length: count }, (_, index) => index);
22736
+ const picked = [];
22737
+ for (let round = 0; round < Math.min(k, count); round += 1) {
22738
+ const index = createHash("sha256").update(`${seedInput}:${String(round)}`).digest().readUInt32BE(0) % indexes.length;
22739
+ const chosen = indexes.splice(index, 1)[0];
22740
+ if (chosen !== void 0) picked.push(chosen);
22741
+ }
22742
+ return picked.sort((a, b) => a - b);
22743
+ }
22744
+ /**
22745
+ * The deterministic stratified sample (RV4004): per H2 section, up to
22746
+ * `samplePerSection` citing sentences, selected by a hash chain seeded
22747
+ * from the audited document's own hash, so the same candidate always
22748
+ * yields the same sample (replay-stable, no clock, no randomness) and
22749
+ * a repaired candidate re-samples afresh from its new hash. The whole
22750
+ * sample is capped at `maxSampled` by pick rank across sections (every
22751
+ * section's first pick seats before any section's second), so a
22752
+ * many-section document degrades to one citation per section instead
22753
+ * of auditing the first sections only.
22754
+ */
22755
+ function sampleCitationRows(document, plan, seed) {
22756
+ const perSection = [];
22757
+ for (const { marker, body } of sectionsOfDocument(document)) {
22758
+ const candidates = [];
22759
+ for (const sentence of sentencesOf(body)) {
22760
+ const match = citationWithRange(plan.pattern).exec(sentence);
22761
+ if (match === null) continue;
22762
+ const anchorText = new RegExp(`${match[0].replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?:-(\\d+))?`, "u").exec(sentence)?.[0] ?? match[0];
22763
+ const parsed = RANGE_TAIL.exec(anchorText);
22764
+ if (parsed === null) continue;
22765
+ const path = parsed[1] ?? "";
22766
+ const line = Number(parsed[2]);
22767
+ const endLine = parsed[3] === void 0 ? void 0 : Number(parsed[3]);
22768
+ if (path === "" || !Number.isInteger(line) || line < 1) continue;
22769
+ candidates.push({
22770
+ sentence,
22771
+ anchor: anchorText,
22772
+ path,
22773
+ line,
22774
+ ...endLine !== void 0 && Number.isInteger(endLine) && endLine >= line ? { endLine } : {}
22775
+ });
22776
+ }
22777
+ if (candidates.length === 0) continue;
22778
+ const picks = pickIndexes(candidates.length, plan.samplePerSection, `${seed}:${marker}`).map((index) => candidates[index]).filter((candidate) => candidate !== void 0);
22779
+ perSection.push({
22780
+ section: marker,
22781
+ picks
22782
+ });
22783
+ }
22784
+ const rows = [];
22785
+ for (let rank = 0; rows.length < plan.maxSampled; rank += 1) {
22786
+ let any = false;
22787
+ for (const bucket of perSection) {
22788
+ const pick = bucket.picks[rank];
22789
+ if (pick === void 0) continue;
22790
+ any = true;
22791
+ if (rows.length >= plan.maxSampled) break;
22792
+ rows.push({
22793
+ row: rows.length,
22794
+ section: bucket.section,
22795
+ ...pick
22796
+ });
22797
+ }
22798
+ if (!any) break;
22799
+ }
22800
+ return rows;
22801
+ }
22802
+ /**
22803
+ * Resolves one sampled citation's excerpt through the host's pure
22804
+ * snapshot resolver. The FIRST cited line failing to resolve returns
22805
+ * undefined (an unsupported citation by doctrine); later lines simply
22806
+ * end the excerpt (a range past the file's end reads as far as the
22807
+ * snapshot goes).
22808
+ */
22809
+ function citationExcerptOf(resolve, row, window) {
22810
+ const last = Math.min(row.endLine ?? row.line + window, row.line + 12 - 1);
22811
+ const lines = [];
22812
+ for (let line = row.line; line <= last; line += 1) {
22813
+ const text = resolve({
22814
+ path: row.path,
22815
+ line
22816
+ });
22817
+ if (text === void 0) {
22818
+ if (line === row.line) return;
22819
+ break;
22820
+ }
22821
+ lines.push(`L${String(line)}: ${text}`);
22822
+ }
22823
+ const excerpt = lines.join("\n");
22824
+ return excerpt.length > 800 ? `${excerpt.slice(0, 800)}…` : excerpt;
22825
+ }
22826
+ /** The audit judge's structured verdict schema (mirrors the claim judge). */
22827
+ const CITATION_JUDGE_SCHEMA = {
22828
+ type: "object",
22829
+ properties: { verdicts: {
22830
+ type: "array",
22831
+ items: {
22832
+ type: "object",
22833
+ properties: {
22834
+ row: { type: "integer" },
22835
+ verdict: {
22836
+ type: "string",
22837
+ enum: [
22838
+ "supported",
22839
+ "partial",
22840
+ "unsupported"
22841
+ ]
22842
+ },
22843
+ reason: { type: "string" }
22844
+ },
22845
+ required: [
22846
+ "row",
22847
+ "verdict",
22848
+ "reason"
22849
+ ],
22850
+ additionalProperties: false
22851
+ }
22852
+ } },
22853
+ required: ["verdicts"],
22854
+ additionalProperties: false
22855
+ };
22856
+ /**
22857
+ * Parses the judge output strictly: one verdict per judged row, no
22858
+ * duplicates, verdicts from the closed vocabulary. Anything else returns
22859
+ * undefined and the caller treats the invocation as a failed judge
22860
+ * (nothing was judged; partial verdicts over a partial parse would
22861
+ * claim more than the judge said).
22862
+ */
22863
+ function parseCitationVerdicts(output, rowIndexes) {
22864
+ const shaped = output;
22865
+ if (shaped === null || shaped === void 0 || !Array.isArray(shaped.verdicts)) return;
22866
+ const parsed = /* @__PURE__ */ new Map();
22867
+ for (const entry of shaped.verdicts) {
22868
+ const row = entry.row;
22869
+ const verdict = entry.verdict;
22870
+ const reason = entry.reason;
22871
+ if (typeof row !== "number" || verdict !== "supported" && verdict !== "partial" && verdict !== "unsupported" || typeof reason !== "string" || parsed.has(row)) return;
22872
+ parsed.set(row, {
22873
+ verdict,
22874
+ reason
22875
+ });
22876
+ }
22877
+ for (const index of rowIndexes) if (!parsed.has(index)) return;
22878
+ return parsed;
22879
+ }
22880
+ //#endregion
22050
22881
  //#region src/orchestrator/contradictions.ts
22051
22882
  /**
22052
22883
  * The bounded contradiction pass, pure half (RV1301, the sixteenth
@@ -23311,6 +24142,18 @@ function validateOrchestrateOptions(opts) {
23311
24142
  if (consistency.runFactCoverageRatio !== void 0 && consistency.runFacts !== true) throw new ConfigError("orchestrate claimConsistency.runFactCoverageRatio rides the runFacts pass; set claimConsistency.runFacts true");
23312
24143
  if (consistency.onLowCoverage !== void 0 && consistency.onLowCoverage !== "report" && consistency.onLowCoverage !== "fail") throw new ConfigError("orchestrate claimConsistency.onLowCoverage must be 'report' or 'fail'; got " + JSON.stringify(consistency.onLowCoverage));
23313
24144
  if (consistency.onLowCoverage !== void 0 && consistency.minimumCoverageRatio === void 0 && consistency.runFactCoverageRatio === void 0 && consistency.coverageTarget === void 0) throw new ConfigError("orchestrate claimConsistency.onLowCoverage needs a declared floor; set minimumCoverageRatio, runFactCoverageRatio, or coverageTarget");
24145
+ const coveragePolicy = consistency.coveragePolicy;
24146
+ if (coveragePolicy !== void 0 && coveragePolicy !== "observed" && coveragePolicy !== "strict-final") throw new ConfigError(`orchestrate claimConsistency.coveragePolicy must be 'observed' or 'strict-final'; got ${JSON.stringify(coveragePolicy)}`);
24147
+ if (coveragePolicy === "strict-final" && stage === "draft") throw new ConfigError("orchestrate claimConsistency.coveragePolicy 'strict-final' needs stage 'final' or 'both': a draft-only pass grades no final document, so the policy would gate on nothing");
24148
+ const waiver = consistency.waiver;
24149
+ if (waiver !== void 0) {
24150
+ if (coveragePolicy !== "strict-final") throw new ConfigError("orchestrate claimConsistency.waiver requires coveragePolicy 'strict-final': a waiver over an unenforced grade is a signature over nothing");
24151
+ if (typeof waiver !== "object" || waiver === null || Array.isArray(waiver)) throw new ConfigError(`orchestrate claimConsistency.waiver must be an object; got ${JSON.stringify(waiver)}`);
24152
+ const shaped = waiver;
24153
+ if (typeof shaped.principal !== "string" || shaped.principal.length === 0) throw new ConfigError("orchestrate claimConsistency.waiver.principal must be a non empty string; got " + JSON.stringify(shaped.principal));
24154
+ if (typeof shaped.reason !== "string" || shaped.reason.length === 0) throw new ConfigError("orchestrate claimConsistency.waiver.reason must be a non empty string; got " + JSON.stringify(shaped.reason));
24155
+ if (shaped.expiresAt !== void 0 && (typeof shaped.expiresAt !== "string" || Number.isNaN(Date.parse(shaped.expiresAt)))) throw new ConfigError(`orchestrate claimConsistency.waiver.expiresAt must be an ISO 8601 date string; got ${JSON.stringify(shaped.expiresAt)}`);
24156
+ }
23314
24157
  if (consistency.judge !== void 0) {
23315
24158
  const judge = consistency.judge;
23316
24159
  if (typeof judge !== "object" || judge === null || Array.isArray(judge)) throw new ConfigError(`orchestrate claimConsistency.judge must be an object; got ${JSON.stringify(consistency.judge)}`);
@@ -23326,6 +24169,18 @@ function validateOrchestrateOptions(opts) {
23326
24169
  }
23327
24170
  }
23328
24171
  if (opts.executionFacts !== void 0 && typeof opts.executionFacts !== "boolean") throw new ConfigError(`orchestrate executionFacts must be a boolean; got ${typeof opts.executionFacts}`);
24172
+ const audit = opts?.citationAudit;
24173
+ if (audit !== void 0) {
24174
+ if (typeof audit !== "object" || audit === null || Array.isArray(audit)) throw new ConfigError(`orchestrate citationAudit must be an object; got ${JSON.stringify(audit)}`);
24175
+ if (typeof audit.resolve !== "function") throw new ConfigError("orchestrate citationAudit.resolve must be a function: the pure host snapshot reader is the whole evidence channel of the audit");
24176
+ resolveCitationAuditPlan(audit);
24177
+ if (audit.onFound !== void 0 && audit.onFound !== "report" && audit.onFound !== "repair" && audit.onFound !== "fail") throw new ConfigError(`orchestrate citationAudit.onFound must be 'report', 'repair' or 'fail'; got ${String(audit.onFound)}`);
24178
+ if (audit.judge?.estCost !== void 0) requireNonNegativeNumber(audit.judge.estCost, "orchestrate citationAudit.judge.estCost");
24179
+ if (audit.onFound === "repair") {
24180
+ if (opts?.synthesis === void 0) throw new ConfigError("orchestrate citationAudit.onFound 'repair' requires synthesis: the bounded round is one more composition, and without one there is nothing to repair with");
24181
+ if (opts?.claimConsistency?.onFound === "repair") throw new ConfigError("orchestrate citationAudit.onFound 'repair' cannot pair with claimConsistency.onFound 'repair': the run grants ONE bounded repair round (RV3307), so arm one consumer and give the other 'report' or 'fail'");
24182
+ }
24183
+ }
23329
24184
  const spec = opts.budget;
23330
24185
  if (spec === void 0) return;
23331
24186
  if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
@@ -23337,6 +24192,7 @@ function validateOrchestrateOptions(opts) {
23337
24192
  if (opts.synthesis.mode === "incremental") throw new ConfigError("orchestrate budget.synthesisReserveUsd is incompatible with synthesis.mode 'incremental': the reserve protects the single post-fan-in invocation");
23338
24193
  }
23339
24194
  if (spec.finalizeTurns !== void 0) requirePositiveInteger$2(spec.finalizeTurns, "orchestrate budget.finalizeTurns");
24195
+ if (spec.acceptanceReserve !== void 0 && spec.acceptanceReserve !== "warn" && spec.acceptanceReserve !== "require") throw new ConfigError(`orchestrate budget.acceptanceReserve must be 'warn' or 'require'; got ${String(spec.acceptanceReserve)}`);
23340
24196
  if (spec.atCap !== void 0 && spec.atCap !== "finish-with-partial" && spec.atCap !== "fail-run") throw new ConfigError(`orchestrate budget.atCap must be 'finish-with-partial' or 'fail-run'; got ${String(spec.atCap)}`);
23341
24197
  }
23342
24198
  function orchestratorPrompt(goal, maxSpawns, extensionLines) {
@@ -23534,6 +24390,48 @@ function makeOrchestratorWorkflow(goal, opts) {
23534
24390
  };
23535
24391
  }
23536
24392
  }
24393
+ if (opts?.budget?.acceptanceReserve === "require") {
24394
+ const { requiredUsd, terms } = acceptanceTailRequiredUsd({
24395
+ ...opts.budget.synthesisReserveUsd === void 0 ? {} : { synthesisReserveUsd: opts.budget.synthesisReserveUsd },
24396
+ ...opts?.claimConsistency?.stage === void 0 ? {} : { claimStage: opts.claimConsistency.stage },
24397
+ ...opts?.claimConsistency?.onFound === void 0 ? {} : { claimOnFound: opts.claimConsistency.onFound },
24398
+ ...opts?.claimConsistency?.judge?.estCost === void 0 ? {} : { claimJudgeEstCostUsd: opts.claimConsistency.judge.estCost },
24399
+ ...opts?.finishValidation?.estRepairCostUsd === void 0 ? {} : { finishEstRepairCostUsd: opts.finishValidation.estRepairCostUsd },
24400
+ ...opts?.synthesis?.estCost === void 0 ? {} : { synthesisEstCostUsd: opts.synthesis.estCost },
24401
+ ...opts?.citationAudit?.judge?.estCost === void 0 ? {} : { citationJudgeEstCostUsd: opts.citationAudit.judge.estCost },
24402
+ ...opts?.citationAudit?.onFound === void 0 ? {} : { citationOnFound: opts.citationAudit.onFound },
24403
+ ...opts?.claimConsistency === void 0 ? {} : { claimConfigured: true },
24404
+ workingRoomUsd: capState?.turnEstimateUsd ?? internals.flatReserveUsd ?? .5
24405
+ });
24406
+ const capUsd = capState?.effectiveCapUsd;
24407
+ if (capUsd === void 0 || capUsd < requiredUsd) {
24408
+ const termsLine = formatAcceptanceTailTerms(terms);
24409
+ await internals.replayer.appendSinglePhase({
24410
+ scope: callingState.scope,
24411
+ key: deriverV2.deriveKey({ kind: "acceptance-reserve-refused" }),
24412
+ kind: "decision",
24413
+ status: "ok",
24414
+ spanId: internals.spans.mint(callingState.spanId),
24415
+ site: "orchestrator-budget",
24416
+ value: {
24417
+ decisionType: "acceptance_reserve_refused",
24418
+ requiredUsd,
24419
+ effectiveCapUsd: capUsd ?? null,
24420
+ synthesisReserveUsd: terms.synthesisReserveUsd,
24421
+ judgeEstUsd: terms.judgeEstUsd,
24422
+ judgePasses: terms.judgePasses,
24423
+ estRepairCostUsd: terms.estRepairCostUsd,
24424
+ roundCompositionUsd: terms.roundCompositionUsd,
24425
+ ...terms.citationJudgePasses === void 0 ? {} : {
24426
+ citationJudgeEstUsd: terms.citationJudgeEstUsd ?? 0,
24427
+ citationJudgePasses: terms.citationJudgePasses
24428
+ },
24429
+ workingRoomUsd: terms.workingRoomUsd
24430
+ }
24431
+ });
24432
+ throw new OrchestratorCapConfigError(capUsd === void 0 ? `budget.acceptanceReserve 'require' needs a resolved effective cap to hold the declared acceptance tail against (${termsLine}); declare budget.capUsd or a run ceiling` : `budget.acceptanceReserve 'require': the declared acceptance tail does not fit the effective cap ${capUsd.toFixed(4)} USD (${termsLine}); raise the cap or lower the declared tail`);
24433
+ }
24434
+ }
23537
24435
  const records = /* @__PURE__ */ new Map();
23538
24436
  const byOrdinal = /* @__PURE__ */ new Map();
23539
24437
  const rejectedByOrdinal = /* @__PURE__ */ new Map();
@@ -23684,6 +24582,7 @@ function makeOrchestratorWorkflow(goal, opts) {
23684
24582
  const childState = {
23685
24583
  scope,
23686
24584
  spanId: internals.spans.mint(callingState.spanId),
24585
+ phase: callingState.phase ?? "fan-out",
23687
24586
  signal: upstream === void 0 ? controller.signal : AbortSignal.any([upstream, controller.signal]),
23688
24587
  budgetScope: placement?.ownAccount === true ? scope : callingState.budgetScope ?? "run"
23689
24588
  };
@@ -24486,6 +25385,20 @@ function makeOrchestratorWorkflow(goal, opts) {
24486
25385
  */
24487
25386
  let validationInvocationStart = 0;
24488
25387
  /**
25388
+ * The stage a finish-validation verdict is rendered under (RV4002,
25389
+ * the fifth comparison experiment): 'composition' for the initial
25390
+ * composition invocation, the no-synthesis coordination finish,
25391
+ * and the reserved finalizer wake; 'round' from the moment the
25392
+ * RV3307 claim repair round's own composition dispatches. Written
25393
+ * onto every `orchestrator_finish_validation` decision so the
25394
+ * workflow-wide repair ledger is a pure journal fold instead of a
25395
+ * positional reconstruction (the experiment's judge rebuilt the
25396
+ * one draft repair from the raw transcript). Live state on the
25397
+ * RV808b doctrine: replay re-delivers the journaled decisions and
25398
+ * never re-runs validateFinish.
25399
+ */
25400
+ let finishValidationStage = "composition";
25401
+ /**
24489
25402
  * The staged release of the round's mechanical money leg (RV3802),
24490
25403
  * armed by the bounded claim repair round right before its
24491
25404
  * composition dispatches and fired at the round invocation's FIRST
@@ -24673,7 +25586,8 @@ function makeOrchestratorWorkflow(goal, opts) {
24673
25586
  };
24674
25587
  return {
24675
25588
  kind: "spliced",
24676
- result: spliceSections(retained, declared, patch)
25589
+ result: spliceSections(retained, declared, patch),
25590
+ markers
24677
25591
  };
24678
25592
  }
24679
25593
  };
@@ -24684,6 +25598,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24684
25598
  if (validationSpec === void 0) return { ok: true };
24685
25599
  let effective = call.result ?? null;
24686
25600
  let spliced = false;
25601
+ let splicedMarkers;
24687
25602
  if (sectionalRoundContext !== void 0) {
24688
25603
  const round = sectionalRoundContext;
24689
25604
  const args = call.args ?? {};
@@ -24721,6 +25636,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24721
25636
  };
24722
25637
  effective = spliceSections(round.base, round.sections, patch);
24723
25638
  spliced = true;
25639
+ splicedMarkers = markers;
24724
25640
  }
24725
25641
  } else if (finishSectional !== void 0) {
24726
25642
  const resolution = finishSectional.resolve(call);
@@ -24730,6 +25646,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24730
25646
  };
24731
25647
  effective = resolution.result ?? null;
24732
25648
  spliced = resolution.kind === "spliced";
25649
+ if (resolution.kind === "spliced") splicedMarkers = resolution.markers;
24733
25650
  }
24734
25651
  const maxRepairs = validationSpec.maxRepairs ?? 1;
24735
25652
  const known = validationDecisions();
@@ -24839,6 +25756,11 @@ function makeOrchestratorWorkflow(goal, opts) {
24839
25756
  decisionType: "orchestrator_finish_validation",
24840
25757
  callId: call.id,
24841
25758
  verdict: failed.length === 0 || deterministicRepair?.outcome === "accepted" ? "accepted" : repairsUsed < maxRepairs ? "repair" : "rejected",
25759
+ stage: finishValidationStage,
25760
+ ...spliced && splicedMarkers !== void 0 ? {
25761
+ spliced: true,
25762
+ sections: [...splicedMarkers]
25763
+ } : {},
24842
25764
  failed: deterministicRepair?.outcome === "accepted" ? [] : failed,
24843
25765
  repairsUsed,
24844
25766
  maxRepairs,
@@ -24914,6 +25836,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24914
25836
  if (policy === void 0) return Promise.resolve({ ok: true });
24915
25837
  let effective = call.result ?? null;
24916
25838
  let spliced = false;
25839
+ let splicedMarkers;
24917
25840
  if (draftSectional !== void 0) {
24918
25841
  const resolution = draftSectional.resolve(call);
24919
25842
  if (resolution.kind === "refused") return Promise.resolve({
@@ -24922,22 +25845,54 @@ function makeOrchestratorWorkflow(goal, opts) {
24922
25845
  });
24923
25846
  effective = resolution.result ?? null;
24924
25847
  spliced = resolution.kind === "spliced";
25848
+ if (resolution.kind === "spliced") splicedMarkers = resolution.markers;
24925
25849
  }
24926
25850
  const result = effective;
24927
25851
  const text = typeof result === "string" ? result : JSON.stringify(result);
24928
- const accept = () => Promise.resolve(spliced ? {
24929
- ok: true,
24930
- resolved: { result }
24931
- } : { ok: true });
24932
- const reject = (feedback) => {
25852
+ const accept = async () => {
25853
+ if (spliced && splicedMarkers !== void 0) await internals.replayer.appendSinglePhase({
25854
+ scope: callingState.scope,
25855
+ key: `draft-gate-accept:${call.id}`,
25856
+ kind: "decision",
25857
+ status: "ok",
25858
+ spanId: internals.spans.mint(callingState.spanId),
25859
+ site: "orchestrator-draft-gate",
25860
+ value: {
25861
+ decisionType: "orchestrator_draft_gate",
25862
+ callId: call.id,
25863
+ verdict: "accepted",
25864
+ spliced: true,
25865
+ sections: [...splicedMarkers]
25866
+ }
25867
+ });
25868
+ return spliced ? {
25869
+ ok: true,
25870
+ resolved: { result }
25871
+ } : { ok: true };
25872
+ };
25873
+ const reject = async (feedback, failed) => {
24933
25874
  draftSectional?.retain(result);
24934
- return Promise.resolve({
25875
+ await internals.replayer.appendSinglePhase({
25876
+ scope: callingState.scope,
25877
+ key: `draft-gate:${call.id}`,
25878
+ kind: "decision",
25879
+ status: "ok",
25880
+ spanId: internals.spans.mint(callingState.spanId),
25881
+ site: "orchestrator-draft-gate",
25882
+ value: {
25883
+ decisionType: "orchestrator_draft_gate",
25884
+ callId: call.id,
25885
+ verdict: "rejected",
25886
+ failed
25887
+ }
25888
+ });
25889
+ return {
24935
25890
  ok: false,
24936
25891
  feedback: {
24937
25892
  ...feedback,
24938
25893
  ...draftSectional === void 0 ? {} : { sectionalRepair: draftSectional.guidance() }
24939
25894
  }
24940
- });
25895
+ };
24941
25896
  };
24942
25897
  if (policy === "contract") {
24943
25898
  const failed = [];
@@ -24963,7 +25918,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24963
25918
  return reject({
24964
25919
  error: "the coordination draft failed the declared finish contract; repair the draft and call finish again: a contract-valid draft skips the synthesis invocation entirely, and every gap left here is paid for again downstream",
24965
25920
  failed
24966
- });
25921
+ }, failed);
24967
25922
  }
24968
25923
  const reasons = [];
24969
25924
  if (policy.minWords !== void 0) {
@@ -24976,7 +25931,10 @@ function makeOrchestratorWorkflow(goal, opts) {
24976
25931
  return reject({
24977
25932
  error: "the coordination draft failed the draft policy; repair the draft and call finish again: the synthesis invocation composes the FINAL result from this draft, and a collapsed draft starves it of the evidence the validators demand",
24978
25933
  reasons
24979
- });
25934
+ }, [{
25935
+ name: "draft-policy",
25936
+ reasons
25937
+ }]);
24980
25938
  };
24981
25939
  /**
24982
25940
  * The extension finish gate (RV3202, the 2026-08-11 experiment's
@@ -25071,6 +26029,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25071
26029
  };
25072
26030
  const orchestratorState = { ...callingState };
25073
26031
  if (orchestratorAccount !== void 0) orchestratorState.budgetScope = orchestratorAccount;
26032
+ orchestratorState.phase = orchestratorState.phase ?? "coordination";
25074
26033
  const loopBreakSignal = validationSpec === void 0 ? forcedFinishController.signal : AbortSignal.any([forcedFinishController.signal, validationAbort.signal]);
25075
26034
  orchestratorState.signal = callingState.signal === void 0 ? loopBreakSignal : AbortSignal.any([callingState.signal, loopBreakSignal]);
25076
26035
  /**
@@ -25126,6 +26085,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25126
26085
  if (orchestratorAccount !== void 0) internals.budget.releaseFinalizeReserve(orchestratorAccount);
25127
26086
  const finalState = { ...callingState };
25128
26087
  if (orchestratorAccount !== void 0) finalState.budgetScope = orchestratorAccount;
26088
+ finalState.phase = finalState.phase ?? "coordination";
25129
26089
  const digest = buildDigest(wakeOrdinal);
25130
26090
  const reserveBaseline = orchestratorAccount === void 0 ? 0 : internals.budget.accountView(orchestratorAccount)?.spentUsd ?? 0;
25131
26091
  const dispatched = await runtime.runInScope(finalState, () => ctx.agent([
@@ -25199,6 +26159,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25199
26159
  ].join("\n");
25200
26160
  const noteState = { ...callingState };
25201
26161
  if (orchestratorAccount !== void 0) noteState.budgetScope = orchestratorAccount;
26162
+ noteState.phase = noteState.phase ?? "composition";
25202
26163
  const noteOpts = {
25203
26164
  role: "synthesize",
25204
26165
  result: "full",
@@ -25415,6 +26376,12 @@ function makeOrchestratorWorkflow(goal, opts) {
25415
26376
  */
25416
26377
  let claimFindingsFound;
25417
26378
  /**
26379
+ * The citation findings riding the armed audit round's prompt
26380
+ * (RV4004): set exactly while that round's composition dispatches,
26381
+ * so every other synthesis prompt keeps its bytes.
26382
+ */
26383
+ let carriedCitationFindings;
26384
+ /**
25418
26385
  * The observed price of this run's own latest post draft claim
25419
26386
  * judge pass (RV3701): the fallback sizing of the repair round's
25420
26387
  * convergence hold when the host declared no `judge.estCost`. By
@@ -25693,6 +26660,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25693
26660
  ].join("\n");
25694
26661
  const judgeState = { ...callingState };
25695
26662
  if (orchestratorAccount !== void 0) judgeState.budgetScope = orchestratorAccount;
26663
+ judgeState.phase = judgeState.phase ?? "judge";
25696
26664
  const judgeOpts = {
25697
26665
  role: "synthesize",
25698
26666
  result: "full",
@@ -25788,7 +26756,204 @@ function makeOrchestratorWorkflow(goal, opts) {
25788
26756
  ...snapshot ?? {}
25789
26757
  } });
25790
26758
  };
25791
- const runSynthesis = async (draft) => {
26759
+ /**
26760
+ * The citation entailment audit's terminal state (RV4004):
26761
+ * undefined until the pass ran (or when it is not configured),
26762
+ * the meta plus the findings once it did. `citationFindingsFound`
26763
+ * carries every non-supported sampled citation (mechanically
26764
+ * unresolved rows included); `[]` is the judge's claim that every
26765
+ * sampled citation is supported.
26766
+ */
26767
+ let citationAuditMeta;
26768
+ let citationFindingsFound;
26769
+ /**
26770
+ * The citation entailment audit (RV4004): a deterministic
26771
+ * stratified sample of the document's citing sentences, excerpts
26772
+ * through the host's pure snapshot resolver, one bounded judge
26773
+ * invocation. Mirrors the claim judge's dispatch discipline
26774
+ * (declined admissions degrade typed and journaled, dead judges
26775
+ * stamp the meta, armed postures refuse to pass silently); the
26776
+ * POSTURE consequences of findings ('fail', the RV3307 round)
26777
+ * belong to the call site.
26778
+ */
26779
+ const runCitationAudit = async (document, pass) => {
26780
+ const auditSpec = opts?.citationAudit;
26781
+ if (auditSpec === void 0) return;
26782
+ const plan = resolveCitationAuditPlan(auditSpec);
26783
+ const auditedHash = createHash("sha256").update(jcsSerialize(document ?? null), "utf8").digest("hex");
26784
+ const rows = sampleCitationRows(typeof document === "string" ? document : JSON.stringify(document ?? null), plan, auditedHash).map((row) => {
26785
+ const excerpt = citationExcerptOf(auditSpec.resolve, row, plan.window);
26786
+ return excerpt === void 0 ? row : {
26787
+ ...row,
26788
+ excerpt
26789
+ };
26790
+ });
26791
+ const perSection = {};
26792
+ const bucketOf = (section) => perSection[section] ??= {
26793
+ sampled: 0,
26794
+ supported: 0,
26795
+ partial: 0,
26796
+ unsupported: 0
26797
+ };
26798
+ for (const row of rows) bucketOf(row.section).sampled += 1;
26799
+ const mechanical = rows.filter((row) => row.excerpt === void 0).map((row) => ({
26800
+ row: row.row,
26801
+ section: row.section,
26802
+ sentence: row.sentence,
26803
+ anchor: row.anchor,
26804
+ verdict: "unsupported",
26805
+ reason: "the cited location does not resolve in the host snapshot"
26806
+ }));
26807
+ for (const finding of mechanical) bucketOf(finding.section).unsupported += 1;
26808
+ const judgeRows = rows.filter((row) => row.excerpt !== void 0);
26809
+ const metaBase = {
26810
+ sampled: rows.length,
26811
+ supported: 0,
26812
+ partial: 0,
26813
+ unsupported: mechanical.length,
26814
+ unresolved: mechanical.length,
26815
+ perSection,
26816
+ auditedHash,
26817
+ samplePerSection: plan.samplePerSection,
26818
+ maxSampled: plan.maxSampled
26819
+ };
26820
+ const onFound = auditSpec.onFound ?? "report";
26821
+ if (judgeRows.length === 0) {
26822
+ citationAuditMeta = {
26823
+ ...metaBase,
26824
+ judgeInvoked: false
26825
+ };
26826
+ citationFindingsFound = mechanical;
26827
+ return;
26828
+ }
26829
+ const judgePrompt = ["You audit CITATIONS for entailment. Each row below carries one sentence from a composed document, the source location it cites, and the resolved text of the cited lines. Judge whether the cited text ENTAILS what the sentence claims about it: 'supported' when the lines carry the claimed meaning, 'partial' when they carry some of it but not the load-bearing part, 'unsupported' when they are about something else entirely, however plausible the sentence reads. Judge the MEANING, not the mechanics: the location resolving, or sharing words with the sentence, is not entailment. Answer with { verdicts: [{ row, verdict, reason }] }, one verdict per row, reason one short sentence.", `ROWS: ${JSON.stringify(judgeRows.map((row) => ({
26830
+ row: row.row,
26831
+ section: row.section,
26832
+ sentence: row.sentence,
26833
+ anchor: row.anchor,
26834
+ excerpt: row.excerpt
26835
+ })))}`].join("\n");
26836
+ const auditJudgeState = { ...callingState };
26837
+ if (orchestratorAccount !== void 0) auditJudgeState.budgetScope = orchestratorAccount;
26838
+ auditJudgeState.phase = auditJudgeState.phase ?? "judge";
26839
+ const judgeOpts = {
26840
+ role: "synthesize",
26841
+ result: "full",
26842
+ label: pass === "round" ? "citation-entailment-judge-round" : "citation-entailment-judge",
26843
+ schema: CITATION_JUDGE_SCHEMA,
26844
+ limits: auditSpec.judge?.limits ?? { maxTurns: 3 },
26845
+ ...auditSpec.judge?.model === void 0 ? {} : { model: auditSpec.judge.model },
26846
+ ...auditSpec.judge?.effort === void 0 ? {} : { effort: auditSpec.judge.effort },
26847
+ ...auditSpec.judge?.estCost === void 0 ? {} : { estCost: auditSpec.judge.estCost }
26848
+ };
26849
+ let judged;
26850
+ try {
26851
+ judged = await runtime.runInScope(auditJudgeState, () => ctx.agent(judgePrompt, judgeOpts));
26852
+ noteInternalSettle(judged);
26853
+ } catch (declined) {
26854
+ if (!(declined instanceof BudgetExhaustedError)) throw declined;
26855
+ citationAuditMeta = {
26856
+ ...metaBase,
26857
+ judgeInvoked: false,
26858
+ judgeDeclined: true
26859
+ };
26860
+ citationFindingsFound = void 0;
26861
+ const declineKey = deriverV2.deriveKey({ kind: pass === "round" ? "orchestrator-citation-judge-declined-round" : "orchestrator-citation-judge-declined" });
26862
+ if (!internals.replayer.snapshot().some((entry) => entry.kind === "decision" && entry.key === declineKey)) await internals.replayer.appendSinglePhase({
26863
+ scope: callingState.scope,
26864
+ key: declineKey,
26865
+ kind: "decision",
26866
+ status: "ok",
26867
+ spanId: internals.spans.mint(callingState.spanId),
26868
+ site: "orchestrator-budget",
26869
+ value: {
26870
+ decisionType: "orchestrator_citation_judge_declined",
26871
+ reason: declined.message.slice(0, 300),
26872
+ remainingUsd: internals.budget.remainingUsd(orchestratorAccount ?? "run") ?? null
26873
+ }
26874
+ });
26875
+ internals.events.emit({
26876
+ type: "log",
26877
+ level: "warn",
26878
+ msg: "orchestrator citation audit judge declined by admission",
26879
+ data: { reason: declined.message.slice(0, 300) }
26880
+ }, callingState.spanId);
26881
+ if (onFound === "fail" || onFound === "repair") throw new FailRunError(`the citation audit judge could not be admitted within the orchestrator account, so the armed ${onFound} posture cannot pass the document: ` + declined.message.slice(0, 300), { data: {
26882
+ source: "orchestrator_citation_audit",
26883
+ citationAuditMeta
26884
+ } });
26885
+ return;
26886
+ }
26887
+ const verdicts = judged.status === "ok" ? parseCitationVerdicts(judged.output, judgeRows.map((row) => row.row)) : void 0;
26888
+ if (verdicts === void 0) {
26889
+ citationAuditMeta = {
26890
+ ...metaBase,
26891
+ judgeInvoked: true,
26892
+ judgeFailed: true
26893
+ };
26894
+ citationFindingsFound = void 0;
26895
+ internals.events.emit({
26896
+ type: "log",
26897
+ level: "warn",
26898
+ msg: "orchestrator citation audit judge failed",
26899
+ data: { status: judged.status }
26900
+ }, callingState.spanId);
26901
+ if (onFound === "fail" || onFound === "repair") throw new FailRunError(`the citation audit judge did not produce a usable verdict, so the armed ${onFound} posture cannot pass the document`, { data: {
26902
+ source: "orchestrator_citation_audit",
26903
+ citationAuditMeta
26904
+ } });
26905
+ return;
26906
+ }
26907
+ const findings = [...mechanical];
26908
+ let supported = 0;
26909
+ let partial = 0;
26910
+ let unsupported = mechanical.length;
26911
+ for (const row of judgeRows) {
26912
+ const verdict = verdicts.get(row.row);
26913
+ if (verdict === void 0) continue;
26914
+ if (verdict.verdict === "supported") {
26915
+ supported += 1;
26916
+ bucketOf(row.section).supported += 1;
26917
+ continue;
26918
+ }
26919
+ if (verdict.verdict === "partial") {
26920
+ partial += 1;
26921
+ bucketOf(row.section).partial += 1;
26922
+ } else {
26923
+ unsupported += 1;
26924
+ bucketOf(row.section).unsupported += 1;
26925
+ }
26926
+ findings.push({
26927
+ row: row.row,
26928
+ section: row.section,
26929
+ sentence: row.sentence,
26930
+ anchor: row.anchor,
26931
+ verdict: verdict.verdict,
26932
+ reason: verdict.reason
26933
+ });
26934
+ }
26935
+ citationAuditMeta = {
26936
+ ...metaBase,
26937
+ supported,
26938
+ partial,
26939
+ unsupported,
26940
+ judgeInvoked: true
26941
+ };
26942
+ citationFindingsFound = findings;
26943
+ internals.events.emit({
26944
+ type: "log",
26945
+ level: findings.length === 0 ? "debug" : "info",
26946
+ msg: "orchestrator citation entailment audit",
26947
+ data: {
26948
+ sampled: rows.length,
26949
+ supported,
26950
+ partial,
26951
+ unsupported,
26952
+ pass
26953
+ }
26954
+ }, callingState.spanId);
26955
+ };
26956
+ const runSynthesis = async (draft, stagePhase = "composition") => {
25792
26957
  const spec = opts?.synthesis;
25793
26958
  if (spec === void 0) return draft;
25794
26959
  await recoveryDone;
@@ -26040,7 +27205,12 @@ function makeOrchestratorWorkflow(goal, opts) {
26040
27205
  ...opts?.contradictions?.onFound !== "carry" || contradictionsFound === void 0 || contradictionsFound.length === 0 ? [] : ["CHILD CONTRADICTIONS: the settled children read these cited locations differently; resolve each one EXPLICITLY in the final result (say which reading holds and why it does) instead of silently picking one. " + JSON.stringify(contradictionsFound)],
26041
27206
  ...opts?.claimConsistency?.onFound !== "carry" && opts?.claimConsistency?.onFound !== "repair" || claimFindingsFound === void 0 || claimFindingsFound.length === 0 ? [] : ["CLAIM CONTRADICTIONS: the composed draft contradicts the settled child pool at these cited locations; resolve each one EXPLICITLY in the final result (say which reading holds and why) instead of keeping the inverted claim. " + JSON.stringify(claimFindingsFound)],
26042
27207
  ...opts?.claimConsistency?.onFound !== "carry" && opts?.claimConsistency?.onFound !== "repair" || claimFindingsFound === void 0 || claimFindingsFound.length === 0 ? [] : hostValidationLessons(),
26043
- ...sectionalRoundContext === void 0 ? [] : [`RETAINED FINAL: ${JSON.stringify(sectionalRoundContext.base)}`, "SECTIONAL ROUND: the accepted document above is RETAINED; repair ONLY the sections owning the contradicted claims by calling finish({ sections: { \"<marker>\": \"<new section body>\" } }). Unchanged sections are spliced from the retained document byte for byte and the spliced whole is validated and judged. Target sections: " + JSON.stringify(sectionalRoundContext.targets) + ". Declared markers: " + JSON.stringify(sectionalRoundContext.sections) + ". Resubmit the full document as result only when a targeted repair is impossible."],
27208
+ ...carriedCitationFindings === void 0 || carriedCitationFindings.length === 0 ? [] : ["CITATION AUDIT FINDINGS: these sampled citations were judged NOT entailed by their cited lines; for each, either fix the citation to the lines that actually carry the claim or rewrite the sentence to claim what the cited lines say, and keep every other sentence byte identical. " + JSON.stringify(carriedCitationFindings)],
27209
+ ...sectionalRoundContext === void 0 ? [] : [
27210
+ `RETAINED FINAL: ${JSON.stringify(sectionalRoundContext.base)}`,
27211
+ "SECTIONAL ROUND: the accepted document above is RETAINED; repair ONLY the sections owning the contradicted claims by calling finish({ sections: { \"<marker>\": \"<new section body>\" } }). Unchanged sections are spliced from the retained document byte for byte and the spliced whole is validated and judged. Target sections: " + JSON.stringify(sectionalRoundContext.targets) + ". Declared markers: " + JSON.stringify(sectionalRoundContext.sections) + ". Resubmit the full document as result only when a targeted repair is impossible.",
27212
+ "Rewritten sections must keep the retained evidence discipline: a sentence making a verified or confirmed grade claim carries the run id or a file:line citation INSIDE the sentence, exactly like the retained sections do; a rewritten sentence that drops it fails the finish contract mechanically."
27213
+ ],
26044
27214
  ...spec.policyFacts === true ? [(() => {
26045
27215
  const byStatus = {};
26046
27216
  let extensionsGranted = 0;
@@ -26141,6 +27311,7 @@ function makeOrchestratorWorkflow(goal, opts) {
26141
27311
  const configuredReserveUsd = opts?.budget?.synthesisReserveUsd ?? 0;
26142
27312
  const heldReserveUsd = orchestratorAccount === void 0 ? 0 : internals.budget.accountView(orchestratorAccount)?.synthesisReserveUsd ?? 0;
26143
27313
  const synthesisState = { ...callingState };
27314
+ synthesisState.phase = synthesisState.phase ?? stagePhase;
26144
27315
  if (orchestratorAccount !== void 0) {
26145
27316
  synthesisState.budgetScope = orchestratorAccount;
26146
27317
  internals.budget.releaseSynthesisReserve(orchestratorAccount);
@@ -26167,6 +27338,7 @@ function makeOrchestratorWorkflow(goal, opts) {
26167
27338
  }
26168
27339
  };
26169
27340
  validationInvocationStart = validationDecisions().length;
27341
+ finishValidationStage = stagePhase === "repair" ? "round" : "composition";
26170
27342
  const synthesized = await runtime.runInScope(synthesisState, () => ctx.agent(prompt, synthesisOpts));
26171
27343
  noteInternalSettle(synthesized);
26172
27344
  synthesisSchemaRejectedExchanges = synthesized.schemaRejectedTerminalExchanges ?? 0;
@@ -26888,6 +28060,10 @@ function makeOrchestratorWorkflow(goal, opts) {
26888
28060
  if (claimStage !== "draft") {
26889
28061
  claimConsistencyDraftMeta = claimStage === "both" ? claimConsistencyMeta : void 0;
26890
28062
  await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
28063
+ if ((opts?.claimConsistency?.onFound ?? "report") === "repair" && claimConsistencyMeta !== void 0) {
28064
+ claimConsistencyMeta.passes = 1;
28065
+ claimConsistencyMeta.semanticRepairRounds = 0;
28066
+ }
26891
28067
  if ((opts?.claimConsistency?.onFound ?? "report") === "repair" && claimFindingsFound !== void 0 && claimFindingsFound.length > 0) {
26892
28068
  const hashOfDocument = (value) => createHash("sha256").update(jcsSerialize(value ?? null), "utf8").digest("hex");
26893
28069
  const preRepairHash = hashOfDocument(synthesizedFinal);
@@ -26920,7 +28096,7 @@ function makeOrchestratorWorkflow(goal, opts) {
26920
28096
  }, callingState.spanId);
26921
28097
  }
26922
28098
  try {
26923
- synthesizedFinal = await runSynthesis(result.output);
28099
+ synthesizedFinal = await runSynthesis(result.output, "repair");
26924
28100
  } catch (thrown) {
26925
28101
  await journalSynthesisAdmissionDecline(thrown);
26926
28102
  const hostRejection = thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) && thrown.data.source === "orchestrator_finish_validation" ? thrown.data : void 0;
@@ -26958,6 +28134,11 @@ function makeOrchestratorWorkflow(goal, opts) {
26958
28134
  }
26959
28135
  try {
26960
28136
  await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
28137
+ if (claimConsistencyMeta !== void 0) {
28138
+ claimConsistencyMeta.passes = 2;
28139
+ claimConsistencyMeta.firstPassFindings = carried.length;
28140
+ claimConsistencyMeta.semanticRepairRounds = 1;
28141
+ }
26961
28142
  } catch (thrown) {
26962
28143
  if (thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) && thrown.data.source === "orchestrator_claim_consistency") throw new FailRunError(thrown.message, { data: {
26963
28144
  ...thrown.data,
@@ -26979,6 +28160,93 @@ function makeOrchestratorWorkflow(goal, opts) {
26979
28160
  } });
26980
28161
  }
26981
28162
  }
28163
+ if (opts?.citationAudit !== void 0) {
28164
+ const hashOfDocument = (value) => createHash("sha256").update(jcsSerialize(value ?? null), "utf8").digest("hex");
28165
+ await runCitationAudit(synthesizedFinal, "first");
28166
+ const auditOnFound = opts.citationAudit.onFound ?? "report";
28167
+ const unsupportedOf = () => (citationFindingsFound ?? []).filter((finding) => finding.verdict === "unsupported");
28168
+ const firstUnsupported = unsupportedOf();
28169
+ if (auditOnFound === "fail" && firstUnsupported.length > 0) throw new FailRunError(`the citation audit judged ${String(firstUnsupported.length)} sampled citation${firstUnsupported.length === 1 ? "" : "s"} UNSUPPORTED by the cited lines, and the armed fail posture cannot pass the document`, { data: {
28170
+ source: "orchestrator_citation_audit",
28171
+ citationFindings: citationFindingsFound,
28172
+ citationAuditMeta,
28173
+ ...acceptanceSnapshot
28174
+ } });
28175
+ if (auditOnFound === "repair" && citationAuditMeta !== void 0) {
28176
+ citationAuditMeta.passes = 1;
28177
+ citationAuditMeta.citationRepairRounds = 0;
28178
+ }
28179
+ if (auditOnFound === "repair" && firstUnsupported.length > 0) {
28180
+ const preRepairHash = hashOfDocument(synthesizedFinal);
28181
+ const carried = firstUnsupported;
28182
+ const auditConvergenceHoldUsd = opts.citationAudit.judge?.estCost ?? 0;
28183
+ const auditHoldScope = orchestratorAccount ?? "run";
28184
+ if (auditConvergenceHoldUsd > 0) internals.budget.commitConvergenceReserve(auditHoldScope, auditConvergenceHoldUsd);
28185
+ const auditRepairHoldUsd = validationSpec === void 0 ? 0 : validationSpec.estRepairCostUsd ?? lastMechanicalRepairCostUsd(internals.replayer.snapshot(), (servedBy, usage) => internals.priceUsd(servedBy, usage)) ?? 0;
28186
+ if (auditRepairHoldUsd > 0) {
28187
+ internals.budget.commitRepairReserve(auditHoldScope, auditRepairHoldUsd);
28188
+ releaseRepairLeg = () => {
28189
+ releaseRepairLeg = void 0;
28190
+ internals.budget.releaseRepairReserve(auditHoldScope);
28191
+ };
28192
+ }
28193
+ const auditRoundPlan = validationSpec !== void 0 && typeof synthesizedFinal === "string" ? sectionalRoundPlan(synthesizedFinal, carried.map((finding) => finding.sentence)) : void 0;
28194
+ if (auditRoundPlan !== void 0) {
28195
+ sectionalRoundContext = {
28196
+ base: synthesizedFinal,
28197
+ ...auditRoundPlan
28198
+ };
28199
+ internals.events.emit({
28200
+ type: "log",
28201
+ level: "debug",
28202
+ msg: "orchestrator sectional round armed",
28203
+ data: {
28204
+ targets: auditRoundPlan.targets,
28205
+ sections: auditRoundPlan.sections.length
28206
+ }
28207
+ }, callingState.spanId);
28208
+ }
28209
+ carriedCitationFindings = carried;
28210
+ try {
28211
+ synthesizedFinal = await runSynthesis(result.output, "repair");
28212
+ } catch (thrown) {
28213
+ await journalSynthesisAdmissionDecline(thrown);
28214
+ const auditHostRejection = (thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) ? thrown.data.source : void 0) === "orchestrator_finish_validation" ? thrown.data : void 0;
28215
+ throw new FailRunError(auditHostRejection !== void 0 ? `the citation audit repair round dispatched and its repaired candidate failed host validation (${thrown instanceof Error ? thrown.message.slice(0, 300) : String(thrown)}); ${String(carried.length)} unsupported citation${carried.length === 1 ? "" : "s"} stand unconsumed and a gate armed to repair must not pass silently` : `the citation audit repair round could not dispatch (${thrown instanceof Error ? thrown.message.slice(0, 300) : String(thrown)}); ${String(carried.length)} unsupported citation${carried.length === 1 ? "" : "s"} stand unconsumed and a gate armed to repair must not pass silently`, { data: {
28216
+ source: "orchestrator_citation_audit",
28217
+ citationFindings: carried,
28218
+ citationAuditMeta,
28219
+ repairsUsed: auditHostRejection !== void 0 ? 1 : 0,
28220
+ roundDispatched: auditHostRejection !== void 0,
28221
+ preRepairHash,
28222
+ ...acceptanceSnapshot
28223
+ } });
28224
+ } finally {
28225
+ carriedCitationFindings = void 0;
28226
+ sectionalRoundContext = void 0;
28227
+ releaseRepairLeg = void 0;
28228
+ if (auditRepairHoldUsd > 0) internals.budget.releaseRepairReserve(auditHoldScope);
28229
+ if (auditConvergenceHoldUsd > 0) internals.budget.releaseConvergenceReserve(auditHoldScope);
28230
+ }
28231
+ await runCitationAudit(synthesizedFinal, "round");
28232
+ if (citationAuditMeta !== void 0) {
28233
+ citationAuditMeta.passes = 2;
28234
+ citationAuditMeta.firstPassFindings = carried.length;
28235
+ citationAuditMeta.citationRepairRounds = 1;
28236
+ }
28237
+ if (opts?.claimConsistency !== void 0 && claimStage !== "draft") await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
28238
+ const survivors = unsupportedOf();
28239
+ if (survivors.length > 0) throw new FailRunError(`the citation audit still judged ${String(survivors.length)} sampled citation${survivors.length === 1 ? "" : "s"} UNSUPPORTED after the bounded repair round: the repaired document keeps citing lines that do not carry its claims`, { data: {
28240
+ source: "orchestrator_citation_audit",
28241
+ citationFindings: citationFindingsFound,
28242
+ citationAuditMeta,
28243
+ repairsUsed: 1,
28244
+ preRepairHash,
28245
+ repairedHash: hashOfDocument(synthesizedFinal),
28246
+ ...acceptanceSnapshot
28247
+ } });
28248
+ }
28249
+ }
26982
28250
  const envelopeSchemaRecovered = (result.schemaRecoveredTerminalExchanges ?? 0) + synthesisSchemaRecoveredExchanges;
26983
28251
  const deliverable = deliverableVerdict(synthesizedFinal);
26984
28252
  const draftToFinal = opts?.synthesis === void 0 ? void 0 : (() => {
@@ -26993,6 +28261,49 @@ function makeOrchestratorWorkflow(goal, opts) {
26993
28261
  };
26994
28262
  })();
26995
28263
  const envelopeRejectedCandidates = rejectedFinishCandidates();
28264
+ const acceptedRepairs = validationDecisions().map((verdict) => verdict.deterministicRepair).filter((repair) => repair !== void 0 && repair.outcome === "accepted");
28265
+ const lastAcceptedRepair = acceptedRepairs.at(-1);
28266
+ const deterministicPatches = lastAcceptedRepair === void 0 ? void 0 : {
28267
+ decisions: acceptedRepairs.length,
28268
+ patches: acceptedRepairs.reduce((sum, repair) => sum + repair.patches.length, 0),
28269
+ lastBeforeHash: lastAcceptedRepair.beforeHash,
28270
+ lastAfterHash: lastAcceptedRepair.afterHash
28271
+ };
28272
+ const repairLedger = validationSpec !== void 0 || (opts?.claimConsistency?.onFound ?? "report") === "repair" || opts?.citationAudit?.onFound === "repair" ? repairLedgerFromJournal(internals.replayer.snapshot(), (servedBy, usage) => internals.priceUsd(servedBy, usage)) : void 0;
28273
+ let claimCoverageWaiver;
28274
+ if (opts?.claimConsistency?.coveragePolicy === "strict-final") {
28275
+ const grade = claimConsistencyMeta?.coverage ?? "not-judged";
28276
+ if (grade !== "full") {
28277
+ const waiverSpec = opts.claimConsistency.waiver;
28278
+ const expired = waiverSpec?.expiresAt !== void 0 && Date.parse(waiverSpec.expiresAt) < internals.now();
28279
+ if (waiverSpec === void 0 || expired) throw new FailRunError(`claimConsistency.coveragePolicy 'strict-final': the final coverage grade is '${grade}', not 'full', and ` + (waiverSpec === void 0 ? "no waiver is declared" : `the declared waiver expired at ${String(waiverSpec.expiresAt)}`) + "; raise the coverage (pairs, targets, critical anchors) or record a waiver naming who accepts the gap and why", { data: {
28280
+ source: "orchestrator_claim_consistency",
28281
+ coveragePolicy: "strict-final",
28282
+ coverage: grade,
28283
+ ...waiverSpec === void 0 ? {} : { waiverExpiredAt: waiverSpec.expiresAt ?? null },
28284
+ ...claimConsistencyMeta === void 0 ? {} : { claimConsistencyMeta }
28285
+ } });
28286
+ claimCoverageWaiver = {
28287
+ principal: waiverSpec.principal,
28288
+ reason: waiverSpec.reason,
28289
+ ...waiverSpec.expiresAt === void 0 ? {} : { expiresAt: waiverSpec.expiresAt },
28290
+ coverage: grade
28291
+ };
28292
+ await internals.replayer.appendSinglePhase({
28293
+ scope: callingState.scope,
28294
+ key: deriverV2.deriveKey({ kind: "claim-coverage-waived" }),
28295
+ kind: "decision",
28296
+ status: "ok",
28297
+ spanId: internals.spans.mint(callingState.spanId),
28298
+ site: "orchestrator-claim-coverage",
28299
+ value: {
28300
+ decisionType: "claim_coverage_waived",
28301
+ ...claimCoverageWaiver,
28302
+ ...claimConsistencyMeta?.judgedHash === void 0 ? {} : { judgedHash: claimConsistencyMeta.judgedHash }
28303
+ }
28304
+ });
28305
+ }
28306
+ }
26996
28307
  return {
26997
28308
  result: synthesizedFinal,
26998
28309
  completion: decision.completion,
@@ -27000,6 +28311,13 @@ function makeOrchestratorWorkflow(goal, opts) {
27000
28311
  ...deliverable.deliverableAccepted === void 0 ? {} : { deliverableAccepted: deliverable.deliverableAccepted },
27001
28312
  ...deliverable.acceptedArtifactRef === void 0 ? {} : { acceptedArtifactRef: deliverable.acceptedArtifactRef },
27002
28313
  ...envelopeRejectedCandidates.length === 0 ? {} : { rejectedFinishCandidates: envelopeRejectedCandidates },
28314
+ ...deterministicPatches === void 0 ? {} : { deterministicPatches },
28315
+ ...repairLedger === void 0 ? {} : { repairs: repairLedger },
28316
+ ...claimCoverageWaiver === void 0 ? {} : { claimCoverageWaiver },
28317
+ ...citationAuditMeta === void 0 ? {} : {
28318
+ ...citationFindingsFound === void 0 ? {} : { citationFindings: citationFindingsFound },
28319
+ citationAuditMeta
28320
+ },
27003
28321
  childStatusCounts: decision.childStatusCounts,
27004
28322
  degradedReasons: decision.degradedReasons,
27005
28323
  ...decision.salvagedPartialChildren === void 0 ? {} : { salvagedPartialChildren: decision.salvagedPartialChildren },
@@ -27053,9 +28371,9 @@ function makeOrchestratorWorkflow(goal, opts) {
27053
28371
  * Top-level surface: creates a run. `runOptions` are the ordinary
27054
28372
  * engine {@link RunOptions} of the created run; in particular
27055
28373
  * `runOptions.budgetUsd` is the ROOT hard ceiling over the WHOLE tree
27056
- * (the orchestrator and every child), immutable after start, while
27057
- * `opts.budget` only shapes the orchestrator's own sub-account inside
27058
- * that ceiling. The shortcut previously accepted no RunOptions at all,
28374
+ * (the orchestrator and every child), immutable within a segment,
28375
+ * while `opts.budget` only shapes the orchestrator's own sub-account
28376
+ * inside that ceiling. The shortcut previously accepted no RunOptions at all,
27059
28377
  * so the canonical entry point could not set a root ceiling without
27060
28378
  * dropping to `engine.run(makeOrchestratorWorkflow(...))` (v1.18.0
27061
28379
  * review P1-5).
@@ -27274,6 +28592,15 @@ function preflightEstimate(input) {
27274
28592
  });
27275
28593
  }
27276
28594
  const spec = input.orchestrator.budget;
28595
+ if (spec?.acceptanceReserve !== void 0 && spec.acceptanceReserve !== "warn" && spec.acceptanceReserve !== "require") throw new ConfigError("preflight.orchestrator.budget.acceptanceReserve must be 'warn' or 'require'; got " + JSON.stringify(spec.acceptanceReserve));
28596
+ if (input.orchestrator.synthesis?.estCost !== void 0) requireNonNegativeNumber(input.orchestrator.synthesis.estCost, "preflight.orchestrator.synthesis.estCost");
28597
+ if (input.finishValidation?.estRepairCostUsd !== void 0) requireNonNegativeNumber(input.finishValidation.estRepairCostUsd, "preflight.finishValidation.estRepairCostUsd");
28598
+ if (input.orchestrator.citationAudit?.judge?.estCost !== void 0) requireNonNegativeNumber(input.orchestrator.citationAudit.judge.estCost, "preflight.orchestrator.citationAudit.judge.estCost");
28599
+ if (input.orchestrator.citationAudit?.onFound !== void 0 && ![
28600
+ "report",
28601
+ "repair",
28602
+ "fail"
28603
+ ].includes(input.orchestrator.citationAudit.onFound)) throw new ConfigError(`preflight.orchestrator.citationAudit.onFound must be 'report', 'repair' or 'fail'; got ${JSON.stringify(input.orchestrator.citationAudit.onFound)}`);
27277
28604
  const fraction = spec?.capFraction ?? .2;
27278
28605
  const fromFraction = ceilingUsd === void 0 ? void 0 : fraction * ceilingUsd;
27279
28606
  const bounds = [spec?.capUsd, fromFraction].filter((bound) => bound !== void 0);
@@ -27301,6 +28628,36 @@ function preflightEstimate(input) {
27301
28628
  code: "orchestrator-cap-below-finalize-reserve",
27302
28629
  message: `effectiveCap ${effectiveCapUsd.toFixed(4)} USD is below the finalize reserve ${finalizeReserveUsd.toFixed(4)} USD: the run would refuse to start`
27303
28630
  });
28631
+ if (spec?.acceptanceReserve !== void 0) {
28632
+ const { requiredUsd, terms } = acceptanceTailRequiredUsd({
28633
+ ...spec.synthesisReserveUsd === void 0 ? {} : { synthesisReserveUsd: spec.synthesisReserveUsd },
28634
+ ...input.orchestrator.claimConsistency?.stage === void 0 ? {} : { claimStage: input.orchestrator.claimConsistency.stage },
28635
+ ...input.orchestrator.claimConsistency?.onFound === void 0 ? {} : { claimOnFound: input.orchestrator.claimConsistency.onFound },
28636
+ ...input.orchestrator.claimConsistency?.judge?.estCost === void 0 ? {} : { claimJudgeEstCostUsd: input.orchestrator.claimConsistency.judge.estCost },
28637
+ ...input.finishValidation?.estRepairCostUsd === void 0 ? {} : { finishEstRepairCostUsd: input.finishValidation.estRepairCostUsd },
28638
+ ...input.orchestrator.synthesis?.estCost === void 0 ? {} : { synthesisEstCostUsd: input.orchestrator.synthesis.estCost },
28639
+ ...input.orchestrator.citationAudit?.judge?.estCost === void 0 ? {} : { citationJudgeEstCostUsd: input.orchestrator.citationAudit.judge.estCost },
28640
+ ...input.orchestrator.citationAudit?.onFound === void 0 ? {} : { citationOnFound: input.orchestrator.citationAudit.onFound },
28641
+ ...input.orchestrator.claimConsistency === void 0 ? {} : { claimConfigured: true },
28642
+ workingRoomUsd: flatReserveUsd
28643
+ });
28644
+ const fits = effectiveCapUsd !== void 0 && effectiveCapUsd >= requiredUsd;
28645
+ orchestratorEcho.acceptanceReserve = {
28646
+ declared: spec.acceptanceReserve,
28647
+ requiredUsd,
28648
+ ...effectiveCapUsd === void 0 ? {} : { effectiveCapUsd },
28649
+ fits,
28650
+ terms
28651
+ };
28652
+ if (!fits) {
28653
+ const termsLine = formatAcceptanceTailTerms(terms);
28654
+ say({
28655
+ severity: spec.acceptanceReserve === "require" ? "error" : "warning",
28656
+ code: "acceptance-reserve-unfit",
28657
+ message: (effectiveCapUsd === void 0 ? `budget.acceptanceReserve '${spec.acceptanceReserve}': no effective cap resolves to hold the declared acceptance tail against (${termsLine})` : `budget.acceptanceReserve '${spec.acceptanceReserve}': the declared acceptance tail does not fit the effective cap ${effectiveCapUsd.toFixed(4)} USD (${termsLine})`) + (spec.acceptanceReserve === "require" ? "; the run would refuse to start before its first wire (RV3907): raise the cap or lower the declared tail" : "; the run would start with its acceptance machinery funded by luck: raise the cap, lower the declared tail, or declare 'require' to refuse instead")
28658
+ });
28659
+ }
28660
+ }
27304
28661
  }
27305
28662
  const spawnSpecs = input.spawns ?? [];
27306
28663
  spawnSpecs.forEach(validateSpawnSpec);
@@ -27844,8 +29201,8 @@ function preflightEstimate(input) {
27844
29201
  message: `the ceiling headroom is ${(ceilingHeadroomShare * 100).toFixed(2)} percent of the ceiling (${(ceilingHeadroomUsd ?? 0).toFixed(4)} USD over the required minimum ${(requiredMinimumCeilingUsd ?? 0).toFixed(4)} USD), below the declared ${(minCeilingHeadroomShare * 100).toFixed(2)} percent floor: a small pricing or context drift refuses the whole wave at admission; raise the ceiling or slim the wave`
27845
29202
  });
27846
29203
  const claimPosture = input.orchestrator?.claimConsistency;
27847
- const repairArmed = claimPosture?.onFound === "repair";
27848
- const worstJudgePasses = ((claimPosture?.stage ?? "draft") === "both" ? 2 : 1) + (repairArmed ? 1 : 0);
29204
+ const repairArmed = claimPosture?.onFound === "repair" && (claimPosture?.stage ?? "draft") !== "draft";
29205
+ const worstJudgePasses = acceptanceJudgePasses(claimPosture?.stage, claimPosture?.onFound);
27849
29206
  {
27850
29207
  const judgeEstUsd = input.orchestrator?.claimConsistency?.judge?.estCost;
27851
29208
  if (judgeEstUsd !== void 0 && effectiveCapUsd !== void 0 && synthesisHoldUsd > 0) {
@@ -28670,6 +30027,34 @@ function parseDeadlineAt(value) {
28670
30027
  if (month < 1 || month > 12 || day < 1 || day > daysInMonth) refuse();
28671
30028
  return parsed;
28672
30029
  }
30030
+ const SCOPE_FIELDS = [
30031
+ "tenant",
30032
+ "account",
30033
+ "project"
30034
+ ];
30035
+ /**
30036
+ * Validates and copies a declared scope (RV4007): own properties only
30037
+ * (the RV1205 doctrine: a prototype member must never resolve),
30038
+ * non-empty strings of at most 256 chars, at least one field, and the
30039
+ * copy is what gets recorded, so later host mutation of the passed
30040
+ * object cannot move the recorded identity.
30041
+ */
30042
+ function normalizeExecutionScope(value, site) {
30043
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`${site} must be an object; got ${JSON.stringify(value)}`);
30044
+ const copy = {};
30045
+ for (const field of SCOPE_FIELDS) {
30046
+ if (!Object.hasOwn(value, field)) continue;
30047
+ const declared = value[field];
30048
+ if (typeof declared !== "string" || declared.length === 0 || declared.length > 256) throw new ConfigError(`${site}.${field} must be a non-empty string of at most 256 characters; got ` + JSON.stringify(declared));
30049
+ copy[field] = declared;
30050
+ }
30051
+ if (Object.keys(copy).length === 0) throw new ConfigError(`${site} must declare at least one of tenant, account, project; an empty scope records nothing and asserts nothing`);
30052
+ return copy;
30053
+ }
30054
+ /** The canonical identity string of a scope (RV4007): JCS bytes, total and deterministic. */
30055
+ function executionScopeKey(scope) {
30056
+ return jcsSerialize(scope);
30057
+ }
28673
30058
  /** Validates a declared config fingerprint (RV3210): a non-empty string of at most 512 chars. */
28674
30059
  function requireConfigFingerprint(value, site) {
28675
30060
  if (typeof value !== "string" || value.length === 0 || value.length > 512) throw new ConfigError(`${site} must be a non-empty string of at most 512 characters; got ` + (typeof value === "string" ? `${String(value.length)} characters` : JSON.stringify(value)));
@@ -28949,7 +30334,11 @@ function createEngine(options) {
28949
30334
  if (profile.countTokens !== void 0 && !["allow", "deny"].includes(profile.countTokens)) throw new ConfigError(`createEngine defaults.profiles['${name}'].countTokens must be 'allow' or 'deny'`);
28950
30335
  }
28951
30336
  if (options.defaults?.countTokens !== void 0 && !["allow", "deny"].includes(options.defaults.countTokens)) throw new ConfigError("createEngine defaults.countTokens must be 'allow' or 'deny'");
28952
- if (options.defaults?.billingReceipts !== void 0 && !["async", "awaited"].includes(options.defaults.billingReceipts)) throw new ConfigError("createEngine defaults.billingReceipts must be 'async' or 'awaited'");
30337
+ if (options.defaults?.billingReceipts !== void 0 && ![
30338
+ "async",
30339
+ "awaited",
30340
+ "intent"
30341
+ ].includes(options.defaults.billingReceipts)) throw new ConfigError("createEngine defaults.billingReceipts must be 'async', 'awaited' or 'intent'");
28953
30342
  if (options.telemetry?.quotaDeniedAgentError !== void 0 && typeof options.telemetry.quotaDeniedAgentError !== "boolean") throw new ConfigError("createEngine telemetry.quotaDeniedAgentError must be a boolean");
28954
30343
  validateDeterminismConfig(options.determinism);
28955
30344
  validateEngineQuotaConfig(options.quota);
@@ -28986,6 +30375,8 @@ function createEngine(options) {
28986
30375
  if (opts?.configFingerprint !== void 0) requireConfigFingerprint(opts.configFingerprint, "RunOptions.configFingerprint");
28987
30376
  if (opts?.clampTurnToExposure !== void 0 && typeof opts.clampTurnToExposure !== "boolean") throw new ConfigError("RunOptions.clampTurnToExposure must be a boolean; got " + JSON.stringify(opts.clampTurnToExposure));
28988
30377
  if (opts?.strictPricing !== void 0 && typeof opts.strictPricing !== "boolean" && (typeof opts.strictPricing !== "object" || opts.strictPricing === null || Array.isArray(opts.strictPricing))) throw new ConfigError("RunOptions.strictPricing must be a boolean or an options object; got " + JSON.stringify(opts.strictPricing));
30378
+ if (opts?.budgetPolicy !== void 0 && opts.budgetPolicy !== "segment" && opts.budgetPolicy !== "immutable-lifetime") throw new ConfigError("RunOptions.budgetPolicy must be 'segment' or 'immutable-lifetime'; got " + JSON.stringify(opts.budgetPolicy));
30379
+ const declaredScope = opts?.scope === void 0 ? void 0 : normalizeExecutionScope(opts.scope, "RunOptions.scope");
28989
30380
  if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
28990
30381
  const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
28991
30382
  const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
@@ -29020,6 +30411,8 @@ function createEngine(options) {
29020
30411
  ...opts.strictPricing.allowUnpriced === void 0 ? {} : { allowUnpriced: [...opts.strictPricing.allowUnpriced] }
29021
30412
  };
29022
30413
  const configFingerprint = opts?.configFingerprint ?? resumeCtx?.configFingerprint;
30414
+ const budgetPolicy = opts?.budgetPolicy ?? resumeCtx?.budgetPolicy;
30415
+ const executionScope = declaredScope ?? resumeCtx?.scope;
29023
30416
  const makeBudget = () => new RunBudget({
29024
30417
  ...ceilingUsd === void 0 ? {} : { ceilingUsd },
29025
30418
  ...exposureCapUsd === void 0 ? {} : { maxInFlightExposureUsd: exposureCapUsd },
@@ -29202,7 +30595,9 @@ function createEngine(options) {
29202
30595
  ...ceilingUsd === void 0 ? {} : { budgetUsd: ceilingUsd },
29203
30596
  ...exposureCapUsd === void 0 ? {} : { maxInFlightExposureUsd: exposureCapUsd },
29204
30597
  ...strictPricing === void 0 ? {} : { strictPricing },
30598
+ ...budgetPolicy === "immutable-lifetime" ? { budgetPolicy } : {},
29205
30599
  ...configFingerprint === void 0 ? {} : { configFingerprint },
30600
+ ...executionScope === void 0 ? {} : { scope: executionScope },
29206
30601
  ...argsBinding.argsProvided === void 0 ? {} : { argsProvided: argsBinding.argsProvided },
29207
30602
  ...argsBinding.argsHash === void 0 ? {} : { argsHash: argsBinding.argsHash },
29208
30603
  ...genesis === void 0 ? {} : { genesis },
@@ -29294,6 +30689,34 @@ function createEngine(options) {
29294
30689
  }
29295
30690
  });
29296
30691
  }
30692
+ if (executionScope !== void 0 && resumeCtx === void 0) await replayer.appendSinglePhase({
30693
+ scope: "",
30694
+ key: deriverV2.deriveKey({ kind: "execution-scope" }),
30695
+ kind: "decision",
30696
+ status: "ok",
30697
+ spanId: rootSpanId,
30698
+ site: "execution-scope",
30699
+ value: {
30700
+ decisionType: "execution_scope",
30701
+ scope: executionScope
30702
+ }
30703
+ });
30704
+ if (resumeCtx?.acknowledgedOpenWireIntents !== void 0 && resumeCtx.acknowledgedOpenWireIntents > 0 && resumeCtx.strict !== true) await replayer.appendSinglePhase({
30705
+ scope: "",
30706
+ key: deriverV2.deriveKey({
30707
+ kind: "open-wire-intents-acknowledged",
30708
+ segment: segmentsBefore + 1
30709
+ }),
30710
+ kind: "decision",
30711
+ status: "ok",
30712
+ spanId: rootSpanId,
30713
+ site: "resume-acknowledgment",
30714
+ value: {
30715
+ decisionType: "open_wire_intents_acknowledged",
30716
+ segment: segmentsBefore + 1,
30717
+ count: resumeCtx.acknowledgedOpenWireIntents
30718
+ }
30719
+ });
29297
30720
  await putMeta("running");
29298
30721
  bus.emit({
29299
30722
  type: "run:start",
@@ -29551,6 +30974,7 @@ function createEngine(options) {
29551
30974
  events: bus.iterate(),
29552
30975
  on: (type, cb) => bus.on(type, cb),
29553
30976
  resolveExternal: (key, value) => external.resolveExternal(key, value),
30977
+ revokeApproval: (key, options) => external.revokeApproval(key, options),
29554
30978
  cancel: async (reason) => {
29555
30979
  requestCancel(reason ?? "cancelled by host");
29556
30980
  await result.then(() => void 0, () => void 0);
@@ -29618,6 +31042,15 @@ function createEngine(options) {
29618
31042
  type: "RulvarWarning"
29619
31043
  });
29620
31044
  }
31045
+ {
31046
+ const supplied = resumeOptions?.scope === void 0 ? void 0 : normalizeExecutionScope(resumeOptions.scope, "ResumeOptions.scope");
31047
+ const recorded = typeof meta?.scope === "object" && meta.scope !== null ? meta.scope : void 0;
31048
+ if (supplied !== void 0 && recorded !== void 0 && executionScopeKey(supplied) !== executionScopeKey(recorded)) throw new ConfigError(`resume: the supplied scope does not match the one run '${runId}' recorded at genesis; the execution scope is immutable for the life of the run, and the host declared exactly this check`);
31049
+ if (supplied !== void 0 && recorded === void 0) process.emitWarning(`resume: a scope was supplied but run '${runId}' never recorded one; the assertion cannot be verified (absence means NOT RECORDED)`, {
31050
+ code: "RULVAR_RESUME_SCOPE_UNRECORDED",
31051
+ type: "RulvarWarning"
31052
+ });
31053
+ }
29621
31054
  const priorEntries = (await journal.load(runId)).map((entry) => normalizeEntry(entry));
29622
31055
  scanJournalCompatibility(runId, priorEntries, buildDeriverRegistry(options.extraDerivers));
29623
31056
  if (priorEntries.some((entry) => entry.usageSemantics === void 0 && (entry.servedBy?.startsWith("openai:") === true && (entry.usage?.cacheWriteTokens ?? 0) > 0 || (entry.usageByModel?.some((slice) => slice.servedBy.startsWith("openai:") && slice.usage.cacheWriteTokens > 0) ?? false)))) process.emitWarning(`resume: run '${runId}' contains OpenAI cache-write usage recorded without a usage-semantics stamp. Entries written by rulvar v1.19.0 double-counted cache writes into inputTokens, so their recorded cost and budget debits are OVERSTATED; unstamped entries from v1.20.0 are correct. Resuming keeps the recorded debits. Audit procedure: https://docs.rulvar.com/guide/providers#openai-legacy-cache-journals`, {
@@ -29629,7 +31062,14 @@ function createEngine(options) {
29629
31062
  ...runOverride.budgetUsd === void 0 ? {} : { budgetUsd: runOverride.budgetUsd },
29630
31063
  ...runOverride.maxInFlightExposureUsd === void 0 ? {} : { maxInFlightExposureUsd: runOverride.maxInFlightExposureUsd }
29631
31064
  };
31065
+ if (budgetOverride !== void 0 && meta?.budgetPolicy === "immutable-lifetime") throw new ConfigError(`run '${runId}' was started with budgetPolicy 'immutable-lifetime': the recorded ceilings are immutable for the whole life of the run and ResumeOptions.run is refused, raising and lowering alike; cancel the run (or start a new one) instead of editing its ceilings`);
31066
+ const openIntents = openWireIntentsOf(priorEntries);
31067
+ if (openIntents.length > 0 && resumeOptions?.acknowledgeOpenWireIntents !== true) {
31068
+ const preview = openIntents.slice(0, 3).map((intent) => `agent ${String(intent.agentRef)} ordinal ${String(intent.ordinal)} attempt ${String(intent.attempt)} (${intent.servedBy})`).join("; ");
31069
+ throw new ConfigError(`resume: run '${runId}' holds ${String(openIntents.length)} provider wire intent(s) with unknown outcome (${preview}${openIntents.length > 3 ? "; …" : ""}): an intent was journaled before dispatch and neither a receipt nor a terminal record covers it, so the provider may have billed a wire this process never heard back from, and a blind retry could pay twice. Reconcile the invoice's openIntents lane (cost-audit prints it) against the provider statement, then resume with ResumeOptions.acknowledgeOpenWireIntents: true; the acknowledgment is journaled`);
31070
+ }
29632
31071
  return run(bound, resumeOptions?.args, void 0, {
31072
+ ...openIntents.length > 0 && resumeOptions?.acknowledgeOpenWireIntents === true ? { acknowledgedOpenWireIntents: openIntents.length } : {},
29633
31073
  runId,
29634
31074
  priorEntries,
29635
31075
  strict: resumeOptions?.dryRun ?? false,
@@ -29639,6 +31079,8 @@ function createEngine(options) {
29639
31079
  ...typeof meta?.budgetUsd === "number" ? { budgetUsd: meta.budgetUsd } : {},
29640
31080
  ...typeof meta?.maxInFlightExposureUsd === "number" ? { maxInFlightExposureUsd: meta.maxInFlightExposureUsd } : {},
29641
31081
  ...typeof meta?.strictPricing === "object" && meta.strictPricing !== null ? { strictPricing: meta.strictPricing } : {},
31082
+ ...typeof meta?.scope === "object" && meta.scope !== null ? { scope: meta.scope } : {},
31083
+ ...meta?.budgetPolicy === "immutable-lifetime" ? { budgetPolicy: meta.budgetPolicy } : {},
29642
31084
  segmentsBefore: typeof meta?.segments === "number" && meta.segments > 0 ? Math.floor(meta.segments) : 1,
29643
31085
  ...typeof meta?.argsProvided === "boolean" ? { argsProvided: meta.argsProvided } : {},
29644
31086
  ...typeof meta?.argsHash === "string" ? { argsHash: meta.argsHash } : {},
@@ -29668,6 +31110,9 @@ function createEngine(options) {
29668
31110
  resolveExternal: async (key, value) => {
29669
31111
  return (await handlePromise).resolveExternal(key, value);
29670
31112
  },
31113
+ revokeApproval: async (key, options) => {
31114
+ return (await handlePromise).revokeApproval(key, options);
31115
+ },
29671
31116
  cancel: async (reason) => {
29672
31117
  await (await handlePromise).cancel(reason);
29673
31118
  },
@@ -29826,6 +31271,109 @@ function createEngine(options) {
29826
31271
  };
29827
31272
  }
29828
31273
  //#endregion
31274
+ //#region src/engine/regulated-profile.ts
31275
+ /**
31276
+ * The regulated run profile (RV4009, the fifth comparison experiment;
31277
+ * previously gated behind its own word and confirmed with plan 40).
31278
+ *
31279
+ * Every assurance posture this codebase grew across the comparison
31280
+ * arcs is an OPT-IN knob, which is correct for a library and lethal
31281
+ * for an unreviewed config: the 2026-08-12 run armed every gate to
31282
+ * observe, and the fifth run's harness gated on error findings alone.
31283
+ * `compileRegulatedProfile` is the one-call composition: it takes the
31284
+ * host's ordinary options, REFUSES any field that loosens the
31285
+ * regulated floor (typed, naming the field), fills what is absent,
31286
+ * and returns the compiled options plus a profile hash over the
31287
+ * enforced posture. The hash rides RunOptions.configFingerprint, so
31288
+ * the existing genesis recording and resume assertion machinery
31289
+ * (RV3210) pin it with zero new meta surface.
31290
+ *
31291
+ * DATA, not engine semantics (the M5-T07 doctrine): the engine gains
31292
+ * no strategy enum and no behavioral branch; a host that wants the
31293
+ * posture applies the compiled options like any others. The floor
31294
+ * binds what flows through CreateEngineOptions / RunOptions /
31295
+ * OrchestrateOptions; construction-side postures the options cannot
31296
+ * see (MCP source `drift: 'refuse'` and bounds, the AI SDK bridge's
31297
+ * `providerExecutedTools: 'deny'`) are named in the docs checklist
31298
+ * beside this function, because a hash must not imply what it cannot
31299
+ * verify.
31300
+ */
31301
+ const REGULATED_VERSION = 1;
31302
+ function refuse(field, requirement) {
31303
+ throw new ConfigError(`compileRegulatedProfile: ${field} ${requirement}; the regulated floor is non-loosenable, so drop the field to inherit the floor or meet it explicitly`);
31304
+ }
31305
+ function compileRegulatedProfile(input) {
31306
+ const engine = {
31307
+ ...input.engine,
31308
+ defaults: { ...input.engine.defaults }
31309
+ };
31310
+ const run = { ...input.run };
31311
+ const orchestrate = input.orchestrate === void 0 ? void 0 : { ...input.orchestrate };
31312
+ const defaults = engine.defaults ?? {};
31313
+ const permissions = { ...defaults.permissions ?? {} };
31314
+ if (permissions.strictApprovals === false) refuse("defaults.permissions.strictApprovals", "must not be false (RV1507 monotonic mode)");
31315
+ permissions.strictApprovals = true;
31316
+ defaults.permissions = permissions;
31317
+ if (defaults.billingReceipts !== void 0 && defaults.billingReceipts !== "intent") refuse("defaults.billingReceipts", "must be 'intent' (RV4006 pre-wire intents)");
31318
+ defaults.billingReceipts = "intent";
31319
+ engine.defaults = defaults;
31320
+ const determinism = { ...engine.determinism ?? {} };
31321
+ if (determinism.mode !== void 0 && determinism.mode !== "error") refuse("determinism.mode", "must be 'error'");
31322
+ determinism.mode = "error";
31323
+ engine.determinism = determinism;
31324
+ for (const [name, profile] of Object.entries(defaults.profiles ?? {})) {
31325
+ if (profile.permissions?.strictApprovals === false) refuse(`defaults.profiles.${name}.permissions.strictApprovals`, "must not be false");
31326
+ if (profile.tools !== void 0 && profile.toolsetAttestation === void 0) refuse(`defaults.profiles.${name}`, "declares tools without a toolsetAttestation (pin the resolved hashes)");
31327
+ }
31328
+ if (typeof run.budgetUsd !== "number") refuse("run.budgetUsd", "must declare a USD ceiling");
31329
+ if (run.strictPricing === false) refuse("run.strictPricing", "must not be false");
31330
+ run.strictPricing = run.strictPricing ?? true;
31331
+ if (run.budgetPolicy !== void 0 && run.budgetPolicy !== "immutable-lifetime") refuse("run.budgetPolicy", "must be 'immutable-lifetime' (RV3902)");
31332
+ run.budgetPolicy = "immutable-lifetime";
31333
+ if (run.scope === void 0) refuse("run.scope", "must name the execution scope (RV4007): a regulated run has an owner");
31334
+ if (orchestrate !== void 0) {
31335
+ const budget = { ...orchestrate.budget ?? {} };
31336
+ if (budget.acceptanceReserve !== void 0 && budget.acceptanceReserve !== "require") refuse("orchestrate.budget.acceptanceReserve", "must be 'require' (RV3907/RV4001)");
31337
+ budget.acceptanceReserve = "require";
31338
+ orchestrate.budget = budget;
31339
+ if (orchestrate.citationAudit === void 0) refuse("orchestrate.citationAudit", "must be declared with the host snapshot resolver (RV4004): entailment is the regulated posture, not an option");
31340
+ if (orchestrate.claimConsistency !== void 0) {
31341
+ const claim = { ...orchestrate.claimConsistency };
31342
+ if (claim.coveragePolicy !== void 0 && claim.coveragePolicy !== "strict-final") refuse("orchestrate.claimConsistency.coveragePolicy", "must be 'strict-final' (RV4003)");
31343
+ if ((claim.stage ?? "draft") === "draft") refuse("orchestrate.claimConsistency.stage", "must be 'final' or 'both': the shipped document is what the pass must grade");
31344
+ claim.coveragePolicy = "strict-final";
31345
+ orchestrate.claimConsistency = claim;
31346
+ }
31347
+ }
31348
+ const posture = {
31349
+ regulated: REGULATED_VERSION,
31350
+ strictApprovals: true,
31351
+ billingReceipts: "intent",
31352
+ determinism: "error",
31353
+ strictPricing: run.strictPricing === true ? true : run.strictPricing,
31354
+ budgetPolicy: "immutable-lifetime",
31355
+ budgetUsd: run.budgetUsd,
31356
+ scope: run.scope,
31357
+ ...orchestrate === void 0 ? {} : {
31358
+ acceptanceReserve: "require",
31359
+ citationAudit: true,
31360
+ ...orchestrate.claimConsistency === void 0 ? {} : {
31361
+ coveragePolicy: "strict-final",
31362
+ claimStage: orchestrate.claimConsistency.stage
31363
+ }
31364
+ },
31365
+ ...run.configFingerprint === void 0 ? {} : { hostFingerprint: run.configFingerprint }
31366
+ };
31367
+ const profileHash = createHash("sha256").update(jcsSerialize(posture), "utf8").digest("hex");
31368
+ run.configFingerprint = `regulated:${String(REGULATED_VERSION)}:${profileHash}`;
31369
+ return {
31370
+ engine,
31371
+ run,
31372
+ ...orchestrate === void 0 ? {} : { orchestrate },
31373
+ profileHash
31374
+ };
31375
+ }
31376
+ //#endregion
29829
31377
  //#region src/runner/sandbox-bridge.ts
29830
31378
  /**
29831
31379
  * The host half of the worker sandbox contract (M6-T02).
@@ -30115,4 +31663,4 @@ function createSandboxBridge(ctx, options) {
30115
31663
  };
30116
31664
  }
30117
31665
  //#endregion
30118
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_AUTHORITY_HASH, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EXPOSURE_WAIT_SWEEP_MS, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINAL_COMPOSITION_LABEL, FINISH_LESSON_CAP_CHARS, FINISH_SCHEMA, FINISH_SECTIONAL_SCHEMA, FINISH_TOOL_NAME, FUTURE_RATES_TOLERANCE_MS, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GET_SETTLED_CHILD_RESULTS_SCHEMA, GET_SETTLED_CHILD_RESULTS_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalIntegrityError, JournalMatcher, JournalMissError, JournalOrderViolation, JournalSealedError, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SYNTHESIS_NOTE_LABEL, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyFinishRepairHints, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, attributionBucket, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimJudgeStageOf, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, insertRunIdIntoSentence, invoiceFromJournal, isClaimJudgeLabel, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastMechanicalRepairCostUsd, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, manifestValidators, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, renderContractRequirements, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredMentionsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, scopeBucket, sectionCitationsValidator, sectionPatternCountValidator, sectionalRoundPlan, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, statementRowsFromDelimited, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, synthesisCandidatesFromJournal, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolAuthority, toolCalibrationFromJournal, toolContract, toolContractHash, toolsetAuthorityHash, toolsetHash, ttlState, unionOfIntervalsMs, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
31666
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CITATION_JUDGE_SCHEMA, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_EXCERPT_WINDOW, DEFAULT_CITATION_MAX_SAMPLED, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CITATION_SAMPLE_PER_SECTION, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_AUTHORITY_HASH, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EXPOSURE_WAIT_SWEEP_MS, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINAL_COMPOSITION_LABEL, FINISH_LESSON_CAP_CHARS, FINISH_SCHEMA, FINISH_SECTIONAL_SCHEMA, FINISH_TOOL_NAME, FUTURE_RATES_TOLERANCE_MS, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GET_SETTLED_CHILD_RESULTS_SCHEMA, GET_SETTLED_CHILD_RESULTS_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalIntegrityError, JournalMatcher, JournalMissError, JournalOrderViolation, JournalSealedError, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CITATION_EXCERPT_CHARS, MAX_CITATION_EXCERPT_LINES, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SYNTHESIS_NOTE_LABEL, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, acceptanceJudgePasses, acceptanceTailRequiredUsd, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyFinishRepairHints, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, attributionBucket, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationExcerptOf, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimJudgeStageOf, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileRegulatedProfile, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, executionScopeKey, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatAcceptanceTailTerms, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, insertRunIdIntoSentence, invoiceFromJournal, isClaimJudgeLabel, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastMechanicalRepairCostUsd, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, manifestValidators, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeExecutionScope, normalizeFallbacks, openWireIntentsOf, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseCitationVerdicts, parseModelRef, parseScopePath, parseTerminalEnvelope, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, renderContractRequirements, repairLedgerFromJournal, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredMentionsValidator, requiredSectionsValidator, researchAgentProfile, resolveCitationAuditPlan, resolveModelInvocation, resolvePricing, resolveToolset, retentionKeyOf, retryClassOf, retryDelayMs, retryWireMultiplier, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sampleCitationRows, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, scopeBucket, sectionCitationsValidator, sectionPatternCountValidator, sectionalRoundPlan, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, statementRowsFromDelimited, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, synthesisCandidatesFromJournal, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolAuthority, toolCalibrationFromJournal, toolContract, toolContractHash, toolsetAuthorityHash, toolsetHash, ttlState, unionOfIntervalsMs, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wireCapacityEstimate, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };