@rulvar/core 1.244.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 +2745 -1970
  2. package/dist/index.js +1378 -76
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3252,7 +3252,7 @@ const MAX_TIMER_DELAY_MS = 2147483647;
3252
3252
  * century-long suspension journals as a perfectly valid date.
3253
3253
  */
3254
3254
  const MAX_DEADLINE_MS = 315576e7;
3255
- function refuse$1(site, requirement, value) {
3255
+ function refuse$2(site, requirement, value) {
3256
3256
  throw new ConfigError(`${site} must be ${requirement}; got ${String(value)}`);
3257
3257
  }
3258
3258
  /**
@@ -3269,26 +3269,26 @@ function requireDeadlineMs(value, site) {
3269
3269
  }
3270
3270
  /** An integer >= 1 (counts, caps, and depths). */
3271
3271
  function requirePositiveInteger$2(value, site) {
3272
- 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);
3273
3273
  }
3274
3274
  /** An integer >= 0 (caps where zero means "none allowed"). */
3275
3275
  function requireNonNegativeInteger(value, site) {
3276
- 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);
3277
3277
  }
3278
3278
  /** A finite number >= 0 (USD amounts and reserves). */
3279
3279
  function requireNonNegativeNumber(value, site) {
3280
- 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);
3281
3281
  }
3282
3282
  /** A finite fraction in (0, 1]. */
3283
3283
  function requireFraction(value, site) {
3284
- 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);
3285
3285
  }
3286
3286
  /**
3287
3287
  * A relative delay handed to setTimeout as-is: an integer within the
3288
3288
  * Node timer maximum, mirroring validateRetryPolicy's bound.
3289
3289
  */
3290
3290
  function requireTimerDelayMs(value, site) {
3291
- 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);
3292
3292
  }
3293
3293
  /**
3294
3294
  * A declared evidence contract (RV303, enforcement RV507): minEntries
@@ -8313,11 +8313,13 @@ var EscalationDecisionAbortedError = class extends Error {
8313
8313
  * Normalizes a resolution value into an ApprovalDecision. Anything that
8314
8314
  * is not an explicit allow is a deny: an approval never fails open.
8315
8315
  */
8316
- function toApprovalDecision(value) {
8316
+ function toApprovalDecision(value, entryRef) {
8317
8317
  const record = value ?? {};
8318
8318
  return {
8319
8319
  decision: record.decision === "allow" ? "allow" : "deny",
8320
- ...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 }
8321
8323
  };
8322
8324
  }
8323
8325
  /**
@@ -8352,7 +8354,9 @@ function detachedApprovalFlavor(entry) {
8352
8354
  async function validatePayloadArms(kind, key, value, schemaSpec) {
8353
8355
  if (kind === "approval") {
8354
8356
  const decision = value?.decision;
8355
- 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));
8356
8360
  }
8357
8361
  if (kind === "decision") {
8358
8362
  const decisionKind = value?.kind;
@@ -8572,7 +8576,7 @@ var ExternalRegistry = class ExternalRegistry {
8572
8576
  entry = matched.running;
8573
8577
  replayed = true;
8574
8578
  const state = this.replayer.suspensionState(entry.seq);
8575
- if (state.state === "resolved") return toApprovalDecision(state.value);
8579
+ if (state.state === "resolved") return toApprovalDecision(state.value, entry.seq);
8576
8580
  if (state.state === "abandoned") {
8577
8581
  this.suspendActivity();
8578
8582
  return new Promise(() => void 0);
@@ -8604,7 +8608,7 @@ var ExternalRegistry = class ExternalRegistry {
8604
8608
  prompt: `approve tool '${options.toolName}'`,
8605
8609
  resolve: (value) => {
8606
8610
  resumeActivity();
8607
- resolve(toApprovalDecision(value));
8611
+ resolve(toApprovalDecision(value, entry.seq));
8608
8612
  }
8609
8613
  };
8610
8614
  if (entry.deadlineAt !== void 0) waiter.timer = setLongTimeout(() => {
@@ -8792,6 +8796,62 @@ var ExternalRegistry = class ExternalRegistry {
8792
8796
  * resolvable this way only once the segment settled (closed registry),
8793
8797
  * with the exact live-path validation and no wake.
8794
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
+ }
8795
8855
  async resolveDetached(key, value) {
8796
8856
  const candidates = this.replayer.snapshot().filter((entry) => ExternalRegistry.suspensionKeyOf(entry) === key);
8797
8857
  const open = candidates.find((entry) => this.replayer.suspensionState(entry.seq).state === "suspended");
@@ -9870,6 +9930,130 @@ function criticalPathFromJournal(entries) {
9870
9930
  return path;
9871
9931
  }
9872
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
9873
10057
  //#region src/stores/synthesis-candidates.ts
9874
10058
  const parse = (at) => {
9875
10059
  if (at === void 0) return;
@@ -10098,9 +10282,17 @@ function toolCalibrationFromJournal(entries) {
10098
10282
  const budgetOnly = [];
10099
10283
  let dispatches = 0;
10100
10284
  let unobserved = 0;
10285
+ let coordinationDispatches = 0;
10286
+ let coordinationToolCalls = 0;
10101
10287
  for (const entry of ordered) {
10102
10288
  if (entry.kind !== "agent" || entry.ref === void 0 || entry.status === "running") continue;
10103
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
+ }
10104
10296
  const named = {
10105
10297
  scope: entry.scope,
10106
10298
  handle: entry.ref,
@@ -10123,7 +10315,11 @@ function toolCalibrationFromJournal(entries) {
10123
10315
  observed,
10124
10316
  evidenceOnly,
10125
10317
  budgetOnly,
10126
- unobserved
10318
+ unobserved,
10319
+ ...coordinationDispatches > 0 ? { coordination: {
10320
+ dispatches: coordinationDispatches,
10321
+ toolCallsUsed: coordinationToolCalls
10322
+ } } : {}
10127
10323
  };
10128
10324
  if (observed.length > 0) {
10129
10325
  const toolCallsUsed = observed.reduce((sum, row) => sum + row.toolCallsUsed, 0);
@@ -10939,6 +11135,19 @@ function fallbackTriggerOf(outcome) {
10939
11135
  }
10940
11136
  //#endregion
10941
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
+ }
10942
11151
  /** The provider family of an adapter: `provider` when set, else `id`. */
10943
11152
  function providerOf(adapter) {
10944
11153
  return adapter.provider ?? adapter.id;
@@ -10975,7 +11184,7 @@ function liftRetainedParts(providerMetadata, adapter) {
10975
11184
  const retained = namespace.retainedParts;
10976
11185
  if (!Array.isArray(retained)) return [];
10977
11186
  const blocks = retained;
10978
- const provider = providerOf(adapter);
11187
+ const provider = retentionKeyOf(adapter);
10979
11188
  return blocks.map((block) => ({
10980
11189
  type: "provider-raw",
10981
11190
  provider,
@@ -13632,6 +13841,13 @@ async function runAgent(options) {
13632
13841
  reservationId = decision.reservationId;
13633
13842
  const abandoned = await abortedAfterReserve(quota, decision.reservationId);
13634
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
+ });
13635
13851
  if (quota.reserveContinuations !== true) return streamTurn(target.adapter, req, meteredOptionsFor(target));
13636
13852
  const hooks = { onContinuationSegment: async () => {
13637
13853
  let segmentDecision;
@@ -13688,6 +13904,14 @@ async function runAgent(options) {
13688
13904
  if (options.quota === void 0) {
13689
13905
  const req = site.requestFor(target);
13690
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)));
13691
13915
  return streamTurn(target.adapter, req, meteredOptionsFor(target));
13692
13916
  }
13693
13917
  return dispatchWithQuota(options.quota);
@@ -13781,6 +14005,7 @@ async function runAgent(options) {
13781
14005
  outcome: outcome.aborted !== void 0 ? "aborted" : outcome.wireError !== void 0 ? "error" : "ok",
13782
14006
  usage: accounted
13783
14007
  };
14008
+ if (site.phase !== void 0) record.phase = site.phase;
13784
14009
  if (typeof namespace?.responseId === "string") record.responseId = namespace.responseId;
13785
14010
  else if (typeof namespace?.response?.id === "string") record.responseId = namespace.response.id;
13786
14011
  const wire = namespace?.wireRequests;
@@ -13936,7 +14161,7 @@ async function runAgent(options) {
13936
14161
  chain: loopChain,
13937
14162
  cursor: loopCursor,
13938
14163
  requestFor: (target) => {
13939
- 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);
13940
14165
  const reserveMax = limits.finalizationReserve?.maxOutputTokens;
13941
14166
  if (reserveMax !== void 0) req = {
13942
14167
  ...req,
@@ -14015,16 +14240,19 @@ async function runAgent(options) {
14015
14240
  break;
14016
14241
  }
14017
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);
14018
14245
  const signals = [];
14019
14246
  if (options.signal !== void 0) signals.push(options.signal);
14020
14247
  let loopDispatch;
14021
14248
  try {
14022
14249
  loopDispatch = await dispatchPhase({
14023
14250
  role: primaryRole,
14251
+ ...repairTurnWire ? { phase: "repair" } : {},
14024
14252
  chain: loopChain,
14025
14253
  cursor: loopCursor,
14026
14254
  requestFor: (target) => {
14027
- 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);
14028
14256
  if (options.schema !== void 0 && options.canonicalSchema !== void 0 && !separateExtract) req = applyStructuredOutputTier(req, rideTierFor(target), options.canonicalSchema);
14029
14257
  req = applyCachePolicy(req, target, options.cache);
14030
14258
  return applyOutputBudget(req, target, options.budget);
@@ -14248,7 +14476,7 @@ async function runAgent(options) {
14248
14476
  }, ...options.summarize.fallbacks ?? []],
14249
14477
  cursor: { index: 0 },
14250
14478
  requestFor: (target) => {
14251
- 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);
14252
14480
  if (req.tools !== void 0) req = {
14253
14481
  ...req,
14254
14482
  toolChoice: "none"
@@ -14435,7 +14663,7 @@ async function runAgent(options) {
14435
14663
  chain: loopChain,
14436
14664
  cursor: loopCursor,
14437
14665
  requestFor: (target) => {
14438
- 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);
14439
14667
  if (options.schema !== void 0 && options.canonicalSchema !== void 0 && !separateExtract) req = applyStructuredOutputTier(req, rideTierFor(target), options.canonicalSchema);
14440
14668
  if (req.tools !== void 0) req = {
14441
14669
  ...req,
@@ -14571,7 +14799,7 @@ async function runAgent(options) {
14571
14799
  }, ...options.finalize.fallbacks ?? []],
14572
14800
  cursor: { index: 0 },
14573
14801
  requestFor: (target) => applyOutputBudget({
14574
- ...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),
14575
14803
  toolChoice: "none"
14576
14804
  }, target, options.budget),
14577
14805
  streamOptionsFor: (target) => {
@@ -14690,7 +14918,7 @@ async function runAgent(options) {
14690
14918
  cursor: extractCursor,
14691
14919
  requestFor: (target) => {
14692
14920
  const targetTier = extractTierFor(target);
14693
- 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);
14694
14922
  if (req.tools !== void 0 && targetTier !== "forced-tool") req = {
14695
14923
  ...req,
14696
14924
  toolChoice: "none"
@@ -16072,7 +16300,12 @@ function costReportFromJournal(entries, priceUsd) {
16072
16300
  if (entry.usageApprox === true) usageApprox = true;
16073
16301
  const facts = entry.costAttribution;
16074
16302
  const phase = attributionBucket(facts?.phase);
16075
- 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;
16076
16309
  const agentType = attributionBucket(facts?.agentType);
16077
16310
  byAgentType[agentType] = (byAgentType[agentType] ?? 0) + priced.usd;
16078
16311
  const scope = scopeBucket(entry.scope);
@@ -16361,6 +16594,48 @@ function rowUsd(priceUsd, servedBy, usage, seq) {
16361
16594
  return usd !== void 0 && Number.isFinite(usd) && usd >= 0 ? usd : void 0;
16362
16595
  }
16363
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
+ /**
16364
16639
  * The pure invoice fold. Pass the same entries and price table you
16365
16640
  * would pass `costReportFromJournal`; the totals are that report's
16366
16641
  * gross/net split verbatim. To make the export historically stable
@@ -16526,6 +16801,21 @@ function invoiceFromJournal(entries, priceUsd, options) {
16526
16801
  cardinality: cardinalityOf(rows),
16527
16802
  ...unsettled === void 0 ? {} : { unsettled },
16528
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
+ })(),
16529
16819
  ...(() => {
16530
16820
  const count = rows.filter((row) => row.usageUnknown === true).length;
16531
16821
  return count === 0 ? {} : { usageUnknownRows: count };
@@ -17134,7 +17424,7 @@ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
17134
17424
  "exhausted",
17135
17425
  "suspended"
17136
17426
  ]);
17137
- function refuse(reason, message = REFUSAL_MESSAGES[reason]) {
17427
+ function refuse$1(reason, message = REFUSAL_MESSAGES[reason]) {
17138
17428
  return {
17139
17429
  available: false,
17140
17430
  reason,
@@ -17150,17 +17440,17 @@ function refuse(reason, message = REFUSAL_MESSAGES[reason]) {
17150
17440
  */
17151
17441
  function persistedTerminalEnvelope(input) {
17152
17442
  const settle = lastRunSettle(input.entries);
17153
- if (settle === void 0) return refuse("unsettled");
17154
- 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");
17155
17445
  const tail = input.entries.filter((entry) => entry.seq > settle.seq).length;
17156
- 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`);
17157
17447
  const workflow = input.meta?.workflowName;
17158
- if (workflow === void 0) return refuse("unknown-workflow");
17448
+ if (workflow === void 0) return refuse$1("unknown-workflow");
17159
17449
  try {
17160
17450
  return assemble(input, workflow, settle);
17161
17451
  } catch (error) {
17162
17452
  const detail = error instanceof Error ? error.message : String(error);
17163
- return refuse("malformed-envelope", `${REFUSAL_MESSAGES["malformed-envelope"]}: ${detail}`);
17453
+ return refuse$1("malformed-envelope", `${REFUSAL_MESSAGES["malformed-envelope"]}: ${detail}`);
17164
17454
  }
17165
17455
  }
17166
17456
  function assemble(input, workflow, settle) {
@@ -17784,6 +18074,117 @@ function dispatchProjectionReserveUsd(spec, flatReserveUsd) {
17784
18074
  const base = spec.estCostUsd ?? flatReserveUsd;
17785
18075
  return spec.budgetUsd === void 0 ? base : Math.min(base, spec.budgetUsd);
17786
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
+ }
17787
18188
  /** Nesting depth of a child scope: its workflow, agent, and plan-node segments. */
17788
18189
  function spawnDepthOf(childScope) {
17789
18190
  return parseScopePath(childScope).filter((segment) => segment.kind === "workflow" || segment.kind === "agent" || segment.kind === "plan-node").length;
@@ -19214,7 +19615,12 @@ function createCtx(internals, rootWorkflow) {
19214
19615
  model: slice.servedBy,
19215
19616
  usage: slice.usage
19216
19617
  });
19217
- 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);
19218
19624
  bump(internals.cost.byAgentType, agentType, costUsd);
19219
19625
  bump(internals.cost.byScope, state.scope, costUsd);
19220
19626
  internals.cost.byRole.set(primaryRole, (internals.cost.byRole.get(primaryRole) ?? 0) + costUsd);
@@ -19528,7 +19934,7 @@ function createCtx(internals, rootWorkflow) {
19528
19934
  suspend: async () => {
19529
19935
  if (internals.external === void 0) throw new ConfigError("tool approvals require the engine run context (createEngine)");
19530
19936
  const approvalDeadlineMs = chain.approvalDeadlineMs;
19531
- return internals.external.awaitApproval({
19937
+ const decision = await internals.external.awaitApproval({
19532
19938
  scope: agentScope(state.scope, running.seq),
19533
19939
  spanId: internals.spans.mint(spanId),
19534
19940
  toolName: call.name,
@@ -19541,6 +19947,22 @@ function createCtx(internals, rootWorkflow) {
19541
19947
  entryRef: entry.seq
19542
19948
  }, spanId, replayed)
19543
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;
19544
19966
  }
19545
19967
  };
19546
19968
  }
@@ -19628,28 +20050,47 @@ function createCtx(internals, rootWorkflow) {
19628
20050
  const cachePolicy = opts.cache ?? profile?.cache ?? internals.defaults.cache;
19629
20051
  if (cachePolicy !== void 0) runAgentOptions.cache = cachePolicy;
19630
20052
  }
19631
- runAgentOptions.billing = { onProviderCall: (record) => {
19632
- 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({
19633
20077
  scope: state.scope,
19634
- key: `pc:${String(running.seq)}:${String(record.ordinal)}`,
20078
+ key: `pi:${String(running.seq)}:${String(intent.ordinal)}:${String(intent.attempt)}`,
19635
20079
  kind: "decision",
19636
20080
  status: "ok",
19637
20081
  spanId,
19638
- site: "provider-call",
20082
+ site: "provider-intent",
19639
20083
  value: {
19640
- decisionType: "provider-call",
20084
+ decisionType: "provider-intent",
19641
20085
  agentRef: running.seq,
19642
- 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")
19643
20091
  }
19644
- }).then(() => void 0).catch((thrown) => {
19645
- internals.events.emit({
19646
- type: "log",
19647
- level: "warn",
19648
- msg: `incremental billing row failed to append; the terminal entry remains the canonical record (${thrown instanceof Error ? thrown.message : String(thrown)})`
19649
- }, spanId);
19650
- });
19651
- if (internals.defaults.billingReceipts === "awaited") return append;
19652
- } };
20092
+ }).then(() => void 0) } : {}
20093
+ };
19653
20094
  runAgentOptions.summarize = summarize;
19654
20095
  if (profile?.compaction !== void 0) runAgentOptions.compaction = profile.compaction;
19655
20096
  if (profile?.evidenceContract !== void 0) runAgentOptions.evidenceContract = profile.evidenceContract;
@@ -19990,7 +20431,15 @@ function createCtx(internals, rootWorkflow) {
19990
20431
  const sliceRole = slice.role ?? primaryRole;
19991
20432
  internals.cost.byRole.set(sliceRole, (internals.cost.byRole.get(sliceRole) ?? 0) + priced);
19992
20433
  }
19993
- 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);
19994
20443
  bump(internals.cost.byAgentType, agentType, usd);
19995
20444
  bump(internals.cost.byScope, state.scope, usd);
19996
20445
  if (result.error?.kind === "budget" || internals.budget.exhausted && result.status !== "ok") {
@@ -22223,6 +22672,212 @@ function renderContractRequirements(manifest) {
22223
22672
  return lines.join("\n");
22224
22673
  }
22225
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
22226
22881
  //#region src/orchestrator/contradictions.ts
22227
22882
  /**
22228
22883
  * The bounded contradiction pass, pure half (RV1301, the sixteenth
@@ -23487,6 +24142,18 @@ function validateOrchestrateOptions(opts) {
23487
24142
  if (consistency.runFactCoverageRatio !== void 0 && consistency.runFacts !== true) throw new ConfigError("orchestrate claimConsistency.runFactCoverageRatio rides the runFacts pass; set claimConsistency.runFacts true");
23488
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));
23489
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
+ }
23490
24157
  if (consistency.judge !== void 0) {
23491
24158
  const judge = consistency.judge;
23492
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)}`);
@@ -23502,6 +24169,18 @@ function validateOrchestrateOptions(opts) {
23502
24169
  }
23503
24170
  }
23504
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
+ }
23505
24184
  const spec = opts.budget;
23506
24185
  if (spec === void 0) return;
23507
24186
  if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
@@ -23712,19 +24391,21 @@ function makeOrchestratorWorkflow(goal, opts) {
23712
24391
  }
23713
24392
  }
23714
24393
  if (opts?.budget?.acceptanceReserve === "require") {
23715
- const synthesisHoldUsd = opts.budget.synthesisReserveUsd ?? 0;
23716
- const judgeEstUsd = opts?.claimConsistency?.judge?.estCost ?? 0;
23717
- const bootClaimStage = opts?.claimConsistency?.stage ?? "draft";
23718
- const roundArmed = (opts?.claimConsistency?.onFound ?? "report") === "repair" && bootClaimStage !== "draft";
23719
- const judgePasses = 1 + (roundArmed ? 1 : 0);
23720
- const judgeTailUsd = judgeEstUsd * judgePasses;
23721
- const mechanicalRepairUsd = opts?.finishValidation?.estRepairCostUsd ?? 0;
23722
- const roundCompositionUsd = roundArmed ? opts?.synthesis?.estCost ?? 0 : 0;
23723
- const workingRoomUsd = capState?.turnEstimateUsd ?? internals.flatReserveUsd ?? .5;
23724
- const requiredUsd = synthesisHoldUsd + judgeTailUsd + mechanicalRepairUsd + roundCompositionUsd + workingRoomUsd;
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
+ });
23725
24406
  const capUsd = capState?.effectiveCapUsd;
23726
24407
  if (capUsd === void 0 || capUsd < requiredUsd) {
23727
- const terms = `synthesisReserveUsd ${synthesisHoldUsd.toFixed(4)} + judge ${judgeEstUsd.toFixed(4)} x ${String(judgePasses)} pass(es) + estRepairCostUsd ${mechanicalRepairUsd.toFixed(4)} + round composition ${roundCompositionUsd.toFixed(4)} + working room ${workingRoomUsd.toFixed(4)} = ${requiredUsd.toFixed(4)} USD`;
24408
+ const termsLine = formatAcceptanceTailTerms(terms);
23728
24409
  await internals.replayer.appendSinglePhase({
23729
24410
  scope: callingState.scope,
23730
24411
  key: deriverV2.deriveKey({ kind: "acceptance-reserve-refused" }),
@@ -23736,15 +24417,19 @@ function makeOrchestratorWorkflow(goal, opts) {
23736
24417
  decisionType: "acceptance_reserve_refused",
23737
24418
  requiredUsd,
23738
24419
  effectiveCapUsd: capUsd ?? null,
23739
- synthesisReserveUsd: synthesisHoldUsd,
23740
- judgeEstUsd,
23741
- judgePasses,
23742
- estRepairCostUsd: mechanicalRepairUsd,
23743
- roundCompositionUsd,
23744
- workingRoomUsd
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
23745
24430
  }
23746
24431
  });
23747
- throw new OrchestratorCapConfigError(capUsd === void 0 ? `budget.acceptanceReserve 'require' needs a resolved effective cap to hold the declared acceptance tail against (${terms}); declare budget.capUsd or a run ceiling` : `budget.acceptanceReserve 'require': the declared acceptance tail does not fit the effective cap ${capUsd.toFixed(4)} USD (${terms}); raise the cap or lower the declared tail`);
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`);
23748
24433
  }
23749
24434
  }
23750
24435
  const records = /* @__PURE__ */ new Map();
@@ -24700,6 +25385,20 @@ function makeOrchestratorWorkflow(goal, opts) {
24700
25385
  */
24701
25386
  let validationInvocationStart = 0;
24702
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
+ /**
24703
25402
  * The staged release of the round's mechanical money leg (RV3802),
24704
25403
  * armed by the bounded claim repair round right before its
24705
25404
  * composition dispatches and fired at the round invocation's FIRST
@@ -24887,7 +25586,8 @@ function makeOrchestratorWorkflow(goal, opts) {
24887
25586
  };
24888
25587
  return {
24889
25588
  kind: "spliced",
24890
- result: spliceSections(retained, declared, patch)
25589
+ result: spliceSections(retained, declared, patch),
25590
+ markers
24891
25591
  };
24892
25592
  }
24893
25593
  };
@@ -24898,6 +25598,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24898
25598
  if (validationSpec === void 0) return { ok: true };
24899
25599
  let effective = call.result ?? null;
24900
25600
  let spliced = false;
25601
+ let splicedMarkers;
24901
25602
  if (sectionalRoundContext !== void 0) {
24902
25603
  const round = sectionalRoundContext;
24903
25604
  const args = call.args ?? {};
@@ -24935,6 +25636,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24935
25636
  };
24936
25637
  effective = spliceSections(round.base, round.sections, patch);
24937
25638
  spliced = true;
25639
+ splicedMarkers = markers;
24938
25640
  }
24939
25641
  } else if (finishSectional !== void 0) {
24940
25642
  const resolution = finishSectional.resolve(call);
@@ -24944,6 +25646,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24944
25646
  };
24945
25647
  effective = resolution.result ?? null;
24946
25648
  spliced = resolution.kind === "spliced";
25649
+ if (resolution.kind === "spliced") splicedMarkers = resolution.markers;
24947
25650
  }
24948
25651
  const maxRepairs = validationSpec.maxRepairs ?? 1;
24949
25652
  const known = validationDecisions();
@@ -25053,6 +25756,11 @@ function makeOrchestratorWorkflow(goal, opts) {
25053
25756
  decisionType: "orchestrator_finish_validation",
25054
25757
  callId: call.id,
25055
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
+ } : {},
25056
25764
  failed: deterministicRepair?.outcome === "accepted" ? [] : failed,
25057
25765
  repairsUsed,
25058
25766
  maxRepairs,
@@ -25128,6 +25836,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25128
25836
  if (policy === void 0) return Promise.resolve({ ok: true });
25129
25837
  let effective = call.result ?? null;
25130
25838
  let spliced = false;
25839
+ let splicedMarkers;
25131
25840
  if (draftSectional !== void 0) {
25132
25841
  const resolution = draftSectional.resolve(call);
25133
25842
  if (resolution.kind === "refused") return Promise.resolve({
@@ -25136,22 +25845,54 @@ function makeOrchestratorWorkflow(goal, opts) {
25136
25845
  });
25137
25846
  effective = resolution.result ?? null;
25138
25847
  spliced = resolution.kind === "spliced";
25848
+ if (resolution.kind === "spliced") splicedMarkers = resolution.markers;
25139
25849
  }
25140
25850
  const result = effective;
25141
25851
  const text = typeof result === "string" ? result : JSON.stringify(result);
25142
- const accept = () => Promise.resolve(spliced ? {
25143
- ok: true,
25144
- resolved: { result }
25145
- } : { ok: true });
25146
- 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) => {
25147
25874
  draftSectional?.retain(result);
25148
- 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 {
25149
25890
  ok: false,
25150
25891
  feedback: {
25151
25892
  ...feedback,
25152
25893
  ...draftSectional === void 0 ? {} : { sectionalRepair: draftSectional.guidance() }
25153
25894
  }
25154
- });
25895
+ };
25155
25896
  };
25156
25897
  if (policy === "contract") {
25157
25898
  const failed = [];
@@ -25177,7 +25918,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25177
25918
  return reject({
25178
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",
25179
25920
  failed
25180
- });
25921
+ }, failed);
25181
25922
  }
25182
25923
  const reasons = [];
25183
25924
  if (policy.minWords !== void 0) {
@@ -25190,7 +25931,10 @@ function makeOrchestratorWorkflow(goal, opts) {
25190
25931
  return reject({
25191
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",
25192
25933
  reasons
25193
- });
25934
+ }, [{
25935
+ name: "draft-policy",
25936
+ reasons
25937
+ }]);
25194
25938
  };
25195
25939
  /**
25196
25940
  * The extension finish gate (RV3202, the 2026-08-11 experiment's
@@ -25632,6 +26376,12 @@ function makeOrchestratorWorkflow(goal, opts) {
25632
26376
  */
25633
26377
  let claimFindingsFound;
25634
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
+ /**
25635
26385
  * The observed price of this run's own latest post draft claim
25636
26386
  * judge pass (RV3701): the fallback sizing of the repair round's
25637
26387
  * convergence hold when the host declared no `judge.estCost`. By
@@ -26006,6 +26756,203 @@ function makeOrchestratorWorkflow(goal, opts) {
26006
26756
  ...snapshot ?? {}
26007
26757
  } });
26008
26758
  };
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
+ };
26009
26956
  const runSynthesis = async (draft, stagePhase = "composition") => {
26010
26957
  const spec = opts?.synthesis;
26011
26958
  if (spec === void 0) return draft;
@@ -26258,6 +27205,7 @@ function makeOrchestratorWorkflow(goal, opts) {
26258
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)],
26259
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)],
26260
27207
  ...opts?.claimConsistency?.onFound !== "carry" && opts?.claimConsistency?.onFound !== "repair" || claimFindingsFound === void 0 || claimFindingsFound.length === 0 ? [] : hostValidationLessons(),
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)],
26261
27209
  ...sectionalRoundContext === void 0 ? [] : [
26262
27210
  `RETAINED FINAL: ${JSON.stringify(sectionalRoundContext.base)}`,
26263
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.",
@@ -26390,6 +27338,7 @@ function makeOrchestratorWorkflow(goal, opts) {
26390
27338
  }
26391
27339
  };
26392
27340
  validationInvocationStart = validationDecisions().length;
27341
+ finishValidationStage = stagePhase === "repair" ? "round" : "composition";
26393
27342
  const synthesized = await runtime.runInScope(synthesisState, () => ctx.agent(prompt, synthesisOpts));
26394
27343
  noteInternalSettle(synthesized);
26395
27344
  synthesisSchemaRejectedExchanges = synthesized.schemaRejectedTerminalExchanges ?? 0;
@@ -27211,6 +28160,93 @@ function makeOrchestratorWorkflow(goal, opts) {
27211
28160
  } });
27212
28161
  }
27213
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
+ }
27214
28250
  const envelopeSchemaRecovered = (result.schemaRecoveredTerminalExchanges ?? 0) + synthesisSchemaRecoveredExchanges;
27215
28251
  const deliverable = deliverableVerdict(synthesizedFinal);
27216
28252
  const draftToFinal = opts?.synthesis === void 0 ? void 0 : (() => {
@@ -27233,6 +28269,41 @@ function makeOrchestratorWorkflow(goal, opts) {
27233
28269
  lastBeforeHash: lastAcceptedRepair.beforeHash,
27234
28270
  lastAfterHash: lastAcceptedRepair.afterHash
27235
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
+ }
27236
28307
  return {
27237
28308
  result: synthesizedFinal,
27238
28309
  completion: decision.completion,
@@ -27241,6 +28312,12 @@ function makeOrchestratorWorkflow(goal, opts) {
27241
28312
  ...deliverable.acceptedArtifactRef === void 0 ? {} : { acceptedArtifactRef: deliverable.acceptedArtifactRef },
27242
28313
  ...envelopeRejectedCandidates.length === 0 ? {} : { rejectedFinishCandidates: envelopeRejectedCandidates },
27243
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
+ },
27244
28321
  childStatusCounts: decision.childStatusCounts,
27245
28322
  degradedReasons: decision.degradedReasons,
27246
28323
  ...decision.salvagedPartialChildren === void 0 ? {} : { salvagedPartialChildren: decision.salvagedPartialChildren },
@@ -27515,6 +28592,15 @@ function preflightEstimate(input) {
27515
28592
  });
27516
28593
  }
27517
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)}`);
27518
28604
  const fraction = spec?.capFraction ?? .2;
27519
28605
  const fromFraction = ceilingUsd === void 0 ? void 0 : fraction * ceilingUsd;
27520
28606
  const bounds = [spec?.capUsd, fromFraction].filter((bound) => bound !== void 0);
@@ -27542,6 +28628,36 @@ function preflightEstimate(input) {
27542
28628
  code: "orchestrator-cap-below-finalize-reserve",
27543
28629
  message: `effectiveCap ${effectiveCapUsd.toFixed(4)} USD is below the finalize reserve ${finalizeReserveUsd.toFixed(4)} USD: the run would refuse to start`
27544
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
+ }
27545
28661
  }
27546
28662
  const spawnSpecs = input.spawns ?? [];
27547
28663
  spawnSpecs.forEach(validateSpawnSpec);
@@ -28085,8 +29201,8 @@ function preflightEstimate(input) {
28085
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`
28086
29202
  });
28087
29203
  const claimPosture = input.orchestrator?.claimConsistency;
28088
- const repairArmed = claimPosture?.onFound === "repair";
28089
- 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);
28090
29206
  {
28091
29207
  const judgeEstUsd = input.orchestrator?.claimConsistency?.judge?.estCost;
28092
29208
  if (judgeEstUsd !== void 0 && effectiveCapUsd !== void 0 && synthesisHoldUsd > 0) {
@@ -28911,6 +30027,34 @@ function parseDeadlineAt(value) {
28911
30027
  if (month < 1 || month > 12 || day < 1 || day > daysInMonth) refuse();
28912
30028
  return parsed;
28913
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
+ }
28914
30058
  /** Validates a declared config fingerprint (RV3210): a non-empty string of at most 512 chars. */
28915
30059
  function requireConfigFingerprint(value, site) {
28916
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)));
@@ -29190,7 +30334,11 @@ function createEngine(options) {
29190
30334
  if (profile.countTokens !== void 0 && !["allow", "deny"].includes(profile.countTokens)) throw new ConfigError(`createEngine defaults.profiles['${name}'].countTokens must be 'allow' or 'deny'`);
29191
30335
  }
29192
30336
  if (options.defaults?.countTokens !== void 0 && !["allow", "deny"].includes(options.defaults.countTokens)) throw new ConfigError("createEngine defaults.countTokens must be 'allow' or 'deny'");
29193
- 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'");
29194
30342
  if (options.telemetry?.quotaDeniedAgentError !== void 0 && typeof options.telemetry.quotaDeniedAgentError !== "boolean") throw new ConfigError("createEngine telemetry.quotaDeniedAgentError must be a boolean");
29195
30343
  validateDeterminismConfig(options.determinism);
29196
30344
  validateEngineQuotaConfig(options.quota);
@@ -29228,6 +30376,7 @@ function createEngine(options) {
29228
30376
  if (opts?.clampTurnToExposure !== void 0 && typeof opts.clampTurnToExposure !== "boolean") throw new ConfigError("RunOptions.clampTurnToExposure must be a boolean; got " + JSON.stringify(opts.clampTurnToExposure));
29229
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));
29230
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");
29231
30380
  if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
29232
30381
  const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
29233
30382
  const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
@@ -29263,6 +30412,7 @@ function createEngine(options) {
29263
30412
  };
29264
30413
  const configFingerprint = opts?.configFingerprint ?? resumeCtx?.configFingerprint;
29265
30414
  const budgetPolicy = opts?.budgetPolicy ?? resumeCtx?.budgetPolicy;
30415
+ const executionScope = declaredScope ?? resumeCtx?.scope;
29266
30416
  const makeBudget = () => new RunBudget({
29267
30417
  ...ceilingUsd === void 0 ? {} : { ceilingUsd },
29268
30418
  ...exposureCapUsd === void 0 ? {} : { maxInFlightExposureUsd: exposureCapUsd },
@@ -29447,6 +30597,7 @@ function createEngine(options) {
29447
30597
  ...strictPricing === void 0 ? {} : { strictPricing },
29448
30598
  ...budgetPolicy === "immutable-lifetime" ? { budgetPolicy } : {},
29449
30599
  ...configFingerprint === void 0 ? {} : { configFingerprint },
30600
+ ...executionScope === void 0 ? {} : { scope: executionScope },
29450
30601
  ...argsBinding.argsProvided === void 0 ? {} : { argsProvided: argsBinding.argsProvided },
29451
30602
  ...argsBinding.argsHash === void 0 ? {} : { argsHash: argsBinding.argsHash },
29452
30603
  ...genesis === void 0 ? {} : { genesis },
@@ -29538,6 +30689,34 @@ function createEngine(options) {
29538
30689
  }
29539
30690
  });
29540
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
+ });
29541
30720
  await putMeta("running");
29542
30721
  bus.emit({
29543
30722
  type: "run:start",
@@ -29795,6 +30974,7 @@ function createEngine(options) {
29795
30974
  events: bus.iterate(),
29796
30975
  on: (type, cb) => bus.on(type, cb),
29797
30976
  resolveExternal: (key, value) => external.resolveExternal(key, value),
30977
+ revokeApproval: (key, options) => external.revokeApproval(key, options),
29798
30978
  cancel: async (reason) => {
29799
30979
  requestCancel(reason ?? "cancelled by host");
29800
30980
  await result.then(() => void 0, () => void 0);
@@ -29862,6 +31042,15 @@ function createEngine(options) {
29862
31042
  type: "RulvarWarning"
29863
31043
  });
29864
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
+ }
29865
31054
  const priorEntries = (await journal.load(runId)).map((entry) => normalizeEntry(entry));
29866
31055
  scanJournalCompatibility(runId, priorEntries, buildDeriverRegistry(options.extraDerivers));
29867
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`, {
@@ -29874,7 +31063,13 @@ function createEngine(options) {
29874
31063
  ...runOverride.maxInFlightExposureUsd === void 0 ? {} : { maxInFlightExposureUsd: runOverride.maxInFlightExposureUsd }
29875
31064
  };
29876
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
+ }
29877
31071
  return run(bound, resumeOptions?.args, void 0, {
31072
+ ...openIntents.length > 0 && resumeOptions?.acknowledgeOpenWireIntents === true ? { acknowledgedOpenWireIntents: openIntents.length } : {},
29878
31073
  runId,
29879
31074
  priorEntries,
29880
31075
  strict: resumeOptions?.dryRun ?? false,
@@ -29884,6 +31079,7 @@ function createEngine(options) {
29884
31079
  ...typeof meta?.budgetUsd === "number" ? { budgetUsd: meta.budgetUsd } : {},
29885
31080
  ...typeof meta?.maxInFlightExposureUsd === "number" ? { maxInFlightExposureUsd: meta.maxInFlightExposureUsd } : {},
29886
31081
  ...typeof meta?.strictPricing === "object" && meta.strictPricing !== null ? { strictPricing: meta.strictPricing } : {},
31082
+ ...typeof meta?.scope === "object" && meta.scope !== null ? { scope: meta.scope } : {},
29887
31083
  ...meta?.budgetPolicy === "immutable-lifetime" ? { budgetPolicy: meta.budgetPolicy } : {},
29888
31084
  segmentsBefore: typeof meta?.segments === "number" && meta.segments > 0 ? Math.floor(meta.segments) : 1,
29889
31085
  ...typeof meta?.argsProvided === "boolean" ? { argsProvided: meta.argsProvided } : {},
@@ -29914,6 +31110,9 @@ function createEngine(options) {
29914
31110
  resolveExternal: async (key, value) => {
29915
31111
  return (await handlePromise).resolveExternal(key, value);
29916
31112
  },
31113
+ revokeApproval: async (key, options) => {
31114
+ return (await handlePromise).revokeApproval(key, options);
31115
+ },
29917
31116
  cancel: async (reason) => {
29918
31117
  await (await handlePromise).cancel(reason);
29919
31118
  },
@@ -30072,6 +31271,109 @@ function createEngine(options) {
30072
31271
  };
30073
31272
  }
30074
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
30075
31377
  //#region src/runner/sandbox-bridge.ts
30076
31378
  /**
30077
31379
  * The host half of the worker sandbox contract (M6-T02).
@@ -30361,4 +31663,4 @@ function createSandboxBridge(ctx, options) {
30361
31663
  };
30362
31664
  }
30363
31665
  //#endregion
30364
- 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, 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, 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 };