@rulvar/core 1.245.0 → 1.247.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 +1032 -36
  2. package/dist/index.js +1260 -125
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1445,6 +1445,7 @@ function parseTerminalEnvelope(value) {
1445
1445
  if (value.resultAvailable !== void 0) requireBoolean(value.resultAvailable, "resultAvailable");
1446
1446
  if (value.acceptedArtifactRef !== void 0) requireCount$1(value.acceptedArtifactRef, "acceptedArtifactRef");
1447
1447
  if (value.claimConsistencyMeta !== void 0 && !isPlainObject(value.claimConsistencyMeta)) refuseEnvelope("claimConsistencyMeta", "an object when present", value.claimConsistencyMeta);
1448
+ if (value.semanticTerminalVerdict !== void 0 && !isPlainObject(value.semanticTerminalVerdict)) refuseEnvelope("semanticTerminalVerdict", "an object when present", value.semanticTerminalVerdict);
1448
1449
  if (value.configFingerprint !== void 0) requireNonEmptyString(value.configFingerprint, "configFingerprint");
1449
1450
  if (value.provenance !== void 0 && value.provenance !== "journal") refuseEnvelope("provenance", "the literal 'journal' when present", value.provenance);
1450
1451
  return value;
@@ -1514,6 +1515,7 @@ function terminalEnvelopeOf(input) {
1514
1515
  if (outcome.resultAvailable !== void 0) envelope.resultAvailable = outcome.resultAvailable;
1515
1516
  if (outcome.acceptedArtifactRef !== void 0) envelope.acceptedArtifactRef = outcome.acceptedArtifactRef;
1516
1517
  if (outcome.claimConsistencyMeta !== void 0) envelope.claimConsistencyMeta = detachedMeta(outcome.claimConsistencyMeta);
1518
+ if (outcome.semanticTerminalVerdict !== void 0) envelope.semanticTerminalVerdict = detachedMeta(outcome.semanticTerminalVerdict);
1517
1519
  if (input.configFingerprint !== void 0) envelope.configFingerprint = input.configFingerprint;
1518
1520
  if (outcome.cost.wireRequests !== void 0) envelope.wireRequests = outcome.cost.wireRequests;
1519
1521
  if (input.settlement?.settledReason !== void 0) envelope.settledReason = input.settlement.settledReason;
@@ -4483,6 +4485,19 @@ function mcp(cfg) {
4483
4485
  };
4484
4486
  return {
4485
4487
  id: sourceIdOf(cfg),
4488
+ describeRegulatedPosture: () => ({
4489
+ regulatedPosture: 1,
4490
+ kind: "mcp-source",
4491
+ name: sourceIdOf(cfg),
4492
+ drift: cfg.drift ?? "rekey",
4493
+ bounds: {
4494
+ declared: cfg.maxTools !== void 0 && cfg.maxPages !== void 0 && cfg.maxSchemaBytes !== void 0 && cfg.timeouts?.discoveryMs !== void 0,
4495
+ ...cfg.maxTools === void 0 ? {} : { maxTools: cfg.maxTools },
4496
+ ...cfg.maxPages === void 0 ? {} : { maxPages: cfg.maxPages },
4497
+ ...cfg.maxSchemaBytes === void 0 ? {} : { maxSchemaBytes: cfg.maxSchemaBytes },
4498
+ ...cfg.timeouts?.discoveryMs === void 0 ? {} : { discoveryMs: cfg.timeouts.discoveryMs }
4499
+ }
4500
+ }),
4486
4501
  tools: async () => {
4487
4502
  if (poisoned) throw new ConfigError(`mcp: the tool list of '${sourceIdOf(cfg)}' changed after import (listChanged) and drift policy 'refuse' holds the source closed; close() and re-create the source (and re-record any toolset attestation) to import the changed list deliberately`);
4488
4503
  if (cache !== void 0) return cache;
@@ -9142,6 +9157,7 @@ const TERMINAL_TELEMETRY_SCOPE = Object.freeze({
9142
9157
  childrenAtFailure: "cumulative",
9143
9158
  semanticPasses: "terminal",
9144
9159
  claimConsistencyMeta: "terminal",
9160
+ semanticTerminalVerdict: "terminal",
9145
9161
  claimContradictions: "terminal",
9146
9162
  synthesisSkipped: "terminal",
9147
9163
  deliverableAccepted: "terminal",
@@ -9581,6 +9597,57 @@ function claimJudgeStageOf(label) {
9581
9597
  return label?.startsWith(`claim-consistency-judge-`) ?? false ? "final" : void 0;
9582
9598
  }
9583
9599
  /**
9600
+ * The label the citation entailment audit judge dispatches under
9601
+ * (RV4004; named here since RV4206 so the reducers and the
9602
+ * orchestrator share one constant, the CLAIM_JUDGE_LABEL precedent):
9603
+ * the audit judge rides role 'synthesize' exactly like the claim
9604
+ * judge, and until RV4206 no reducer knew its name, so its wall
9605
+ * folded into final composition on both surfaces.
9606
+ */
9607
+ const CITATION_JUDGE_LABEL = "citation-entailment-judge";
9608
+ /**
9609
+ * Which audit pass a citation judge label names (RV4206): the exact
9610
+ * {@link CITATION_JUDGE_LABEL} is the first pass over the shipped
9611
+ * document, and every suffixed variant is a post round re-audit
9612
+ * (today `citation-entailment-judge-round`, the RV4004 round and the
9613
+ * RV4202 merged round both dispatch it). `undefined` for every other
9614
+ * label; one classifier for both reducers, the RV3302 doctrine.
9615
+ */
9616
+ function citationJudgePassOf(label) {
9617
+ if (label === "citation-entailment-judge") return "first";
9618
+ return label?.startsWith(`citation-entailment-judge-`) ?? false ? "round" : void 0;
9619
+ }
9620
+ /**
9621
+ * The ONE synthesize-span classifier both reducers fold through
9622
+ * (RV4206, the RV3302 doctrine extended from a judge predicate to the
9623
+ * whole vocabulary): the sixth comparison experiment's citation judge
9624
+ * (label {@link CITATION_JUDGE_LABEL}, role 'synthesize') was
9625
+ * recognized by neither reducer and fell into `finalCompositionMs` on
9626
+ * both, so the run's 368889 ms "composition" was half verdict, its
9627
+ * `compositionSpans: 2` faked a repair round's signature on a clean
9628
+ * run, and `lastCandidateMs` overshot the candidate by 154 seconds.
9629
+ *
9630
+ * - 'claim-judge': {@link claimJudgeStageOf} recognizes the label.
9631
+ * - 'citation-judge': {@link citationJudgePassOf} recognizes it.
9632
+ * - 'composition': the engine's own composition labels
9633
+ * ({@link FINAL_COMPOSITION_LABEL}, {@link SYNTHESIS_NOTE_LABEL},
9634
+ * suffixed variants included) and every UNLABELLED span: streams
9635
+ * recorded before RV2901 carry no labels, and composition was the
9636
+ * only unlabelled engine dispatch, so absence keeps its historical
9637
+ * reading.
9638
+ * - 'unclassified': any OTHER label. A present label this classifier
9639
+ * does not know is a NEW vocabulary member, and folding it silently
9640
+ * into composition is exactly the failure this function exists to
9641
+ * end; the reducers bucket it under `unclassifiedSynthesisMs` with
9642
+ * its own nonzero span counter.
9643
+ */
9644
+ function synthesizeSpanClassOf(label) {
9645
+ if (claimJudgeStageOf(label) !== void 0) return "claim-judge";
9646
+ if (citationJudgePassOf(label) !== void 0) return "citation-judge";
9647
+ if (label === void 0 || label === "final-composition" || label.startsWith(`final-composition-`) || label === "synthesis-note" || label.startsWith(`synthesis-note-`)) return "composition";
9648
+ return "unclassified";
9649
+ }
9650
+ /**
9584
9651
  * Total length of the union of possibly overlapping intervals, exported
9585
9652
  * (RV3404) so the journal fold computes its window coverage through the
9586
9653
  * SAME arithmetic the live RV710 decomposition uses, never a sibling
@@ -9632,6 +9699,10 @@ function reduceCriticalPath(events) {
9632
9699
  let semanticJudgeMs = 0;
9633
9700
  let draftJudgeMs = 0;
9634
9701
  let finalJudgeMs = 0;
9702
+ let citationJudgeMs = 0;
9703
+ let citationJudgeSpans = 0;
9704
+ let unclassifiedSynthesisMs = 0;
9705
+ let unclassifiedSynthesisSpans = 0;
9635
9706
  let compositionSpans = 0;
9636
9707
  let judgeSpans = 0;
9637
9708
  let hostRejectedSpans = 0;
@@ -9678,14 +9749,20 @@ function reduceCriticalPath(events) {
9678
9749
  if (event.hostRejected === true) hostRejectedSpans += 1;
9679
9750
  if (started.role === "synthesize") {
9680
9751
  const wall = Math.max(0, at - started.at);
9681
- const stage = claimJudgeStageOf(started.label);
9682
- const judge = stage !== void 0;
9752
+ const cls = synthesizeSpanClassOf(started.label);
9683
9753
  synthesisMs += wall;
9684
- if (judge) {
9754
+ if (cls === "claim-judge") {
9755
+ const stage = claimJudgeStageOf(started.label);
9685
9756
  semanticJudgeMs += wall;
9686
9757
  judgeSpans += 1;
9687
9758
  if (stage === "draft") draftJudgeMs += wall;
9688
9759
  else finalJudgeMs += wall;
9760
+ } else if (cls === "citation-judge") {
9761
+ citationJudgeMs += wall;
9762
+ citationJudgeSpans += 1;
9763
+ } else if (cls === "unclassified") {
9764
+ unclassifiedSynthesisMs += wall;
9765
+ unclassifiedSynthesisSpans += 1;
9689
9766
  } else {
9690
9767
  finalCompositionMs += wall;
9691
9768
  compositionSpans += 1;
@@ -9695,7 +9772,7 @@ function reduceCriticalPath(events) {
9695
9772
  synthesisSpans.push({
9696
9773
  from: started.at,
9697
9774
  to: at,
9698
- judge
9775
+ cls
9699
9776
  });
9700
9777
  } else if (started.role !== "orchestrate") {
9701
9778
  workerSpans += 1;
@@ -9712,6 +9789,10 @@ function reduceCriticalPath(events) {
9712
9789
  semanticJudgeMs,
9713
9790
  draftJudgeMs,
9714
9791
  finalJudgeMs,
9792
+ citationJudgeMs,
9793
+ citationJudgeSpans,
9794
+ unclassifiedSynthesisMs,
9795
+ unclassifiedSynthesisSpans,
9715
9796
  compositionSpans,
9716
9797
  judgeSpans,
9717
9798
  workerSpans,
@@ -9741,13 +9822,18 @@ function reduceCriticalPath(events) {
9741
9822
  }
9742
9823
  const synthesisClipped = [];
9743
9824
  let judgeClippedMs = 0;
9825
+ let citationJudgeClippedMs = 0;
9826
+ let unclassifiedClippedMs = 0;
9744
9827
  let compositionClippedMs = 0;
9745
9828
  for (const span of synthesisSpans) {
9746
9829
  const clipped = clip(span);
9747
9830
  if (clipped === void 0) continue;
9748
9831
  synthesisClipped.push(clipped);
9749
- if (span.judge) judgeClippedMs += clipped.to - clipped.from;
9750
- else compositionClippedMs += clipped.to - clipped.from;
9832
+ const clippedMs = clipped.to - clipped.from;
9833
+ if (span.cls === "claim-judge") judgeClippedMs += clippedMs;
9834
+ else if (span.cls === "citation-judge") citationJudgeClippedMs += clippedMs;
9835
+ else if (span.cls === "unclassified") unclassifiedClippedMs += clippedMs;
9836
+ else compositionClippedMs += clippedMs;
9751
9837
  }
9752
9838
  const byName = {};
9753
9839
  const callsByName = {};
@@ -9776,6 +9862,8 @@ function reduceCriticalPath(events) {
9776
9862
  synthesisMs: lengthOf(synthesisClipped),
9777
9863
  finalCompositionMs: compositionClippedMs,
9778
9864
  semanticJudgeMs: judgeClippedMs,
9865
+ citationJudgeMs: citationJudgeClippedMs,
9866
+ unclassifiedSynthesisMs: unclassifiedClippedMs,
9779
9867
  coveredMs,
9780
9868
  residueMs: Math.max(0, path.postFanInMs - coveredMs)
9781
9869
  };
@@ -9813,6 +9901,10 @@ function criticalPathFromJournal(entries) {
9813
9901
  let semanticJudgeMs = 0;
9814
9902
  let draftJudgeMs = 0;
9815
9903
  let finalJudgeMs = 0;
9904
+ let citationJudgeMs = 0;
9905
+ let citationJudgeSpans = 0;
9906
+ let unclassifiedSynthesisMs = 0;
9907
+ let unclassifiedSynthesisSpans = 0;
9816
9908
  let compositionSpans = 0;
9817
9909
  let judgeSpans = 0;
9818
9910
  let firstCompositionEnd;
@@ -9852,12 +9944,19 @@ function criticalPathFromJournal(entries) {
9852
9944
  continue;
9853
9945
  }
9854
9946
  labelledSynthesis = true;
9855
- const stage = claimJudgeStageOf(label);
9856
- if (stage !== void 0) {
9947
+ const cls = synthesizeSpanClassOf(label);
9948
+ if (cls === "claim-judge") {
9949
+ const stage = claimJudgeStageOf(label);
9857
9950
  semanticJudgeMs += wall;
9858
9951
  judgeSpans += 1;
9859
9952
  if (stage === "draft") draftJudgeMs += wall;
9860
9953
  else finalJudgeMs += wall;
9954
+ } else if (cls === "citation-judge") {
9955
+ citationJudgeMs += wall;
9956
+ citationJudgeSpans += 1;
9957
+ } else if (cls === "unclassified") {
9958
+ unclassifiedSynthesisMs += wall;
9959
+ unclassifiedSynthesisSpans += 1;
9861
9960
  } else {
9862
9961
  finalCompositionMs += wall;
9863
9962
  compositionSpans += 1;
@@ -9867,7 +9966,7 @@ function criticalPathFromJournal(entries) {
9867
9966
  synthSpans.push({
9868
9967
  from: startedAt,
9869
9968
  to: endedAt,
9870
- judge: stage !== void 0
9969
+ cls
9871
9970
  });
9872
9971
  }
9873
9972
  const segments = logicalRunTelemetry(ordered).segments;
@@ -9884,6 +9983,10 @@ function criticalPathFromJournal(entries) {
9884
9983
  path.semanticJudgeMs = semanticJudgeMs;
9885
9984
  path.draftJudgeMs = draftJudgeMs;
9886
9985
  path.finalJudgeMs = finalJudgeMs;
9986
+ path.citationJudgeMs = citationJudgeMs;
9987
+ path.citationJudgeSpans = citationJudgeSpans;
9988
+ path.unclassifiedSynthesisMs = unclassifiedSynthesisMs;
9989
+ path.unclassifiedSynthesisSpans = unclassifiedSynthesisSpans;
9887
9990
  path.compositionSpans = compositionSpans;
9888
9991
  path.judgeSpans = judgeSpans;
9889
9992
  }
@@ -9901,7 +10004,7 @@ function criticalPathFromJournal(entries) {
9901
10004
  clipped.push({
9902
10005
  from: Math.max(span.from, windowFrom),
9903
10006
  to: Math.min(span.to, windowTo),
9904
- ...span.judge === void 0 ? {} : { judge: span.judge }
10007
+ ...span.cls === void 0 ? {} : { cls: span.cls }
9905
10008
  });
9906
10009
  }
9907
10010
  const synthesisCoveredMs = unionOfIntervalsMs(clipped);
@@ -9911,14 +10014,20 @@ function criticalPathFromJournal(entries) {
9911
10014
  };
9912
10015
  if (splitLegible) {
9913
10016
  let judgeClippedMs = 0;
10017
+ let citationJudgeClippedMs = 0;
10018
+ let unclassifiedClippedMs = 0;
9914
10019
  let compositionClippedMs = 0;
9915
10020
  for (const span of clipped) {
9916
10021
  const wall = span.to - span.from;
9917
- if (span.judge === true) judgeClippedMs += wall;
10022
+ if (span.cls === "claim-judge") judgeClippedMs += wall;
10023
+ else if (span.cls === "citation-judge") citationJudgeClippedMs += wall;
10024
+ else if (span.cls === "unclassified") unclassifiedClippedMs += wall;
9918
10025
  else compositionClippedMs += wall;
9919
10026
  }
9920
10027
  block.finalCompositionMs = compositionClippedMs;
9921
10028
  block.semanticJudgeMs = judgeClippedMs;
10029
+ block.citationJudgeMs = citationJudgeClippedMs;
10030
+ block.unclassifiedSynthesisMs = unclassifiedClippedMs;
9922
10031
  }
9923
10032
  if (path.postFanInMs > 0) block.unaccountedShare = block.unaccountedMs / path.postFanInMs;
9924
10033
  path.postFanIn = block;
@@ -9961,7 +10070,18 @@ function repairLedgerFromJournal(entries, priceUsd) {
9961
10070
  const wireRows = [];
9962
10071
  for (const entry of ordered) {
9963
10072
  if (entry.kind === "agent" && entry.status !== "running" && entry.status !== "suspended") {
9964
- if (entry.costAttribution?.label === "final-composition" && entry.costAttribution.phase === "repair") semantic += 1;
10073
+ if (entry.costAttribution?.label === "final-composition" && entry.costAttribution.phase === "repair") {
10074
+ semantic += 1;
10075
+ const trigger = entry.costAttribution.repairTrigger;
10076
+ const semanticRow = {
10077
+ stage: "semantic",
10078
+ seq: entry.seq,
10079
+ failedValidators: [],
10080
+ ...trigger === "claim" || trigger === "citation" || trigger === "coverage" || trigger === "combined" ? { trigger } : {}
10081
+ };
10082
+ rounds.push(semanticRow);
10083
+ rowScopes.set(semanticRow, entry.scope);
10084
+ }
9965
10085
  continue;
9966
10086
  }
9967
10087
  if (entry.kind !== "decision") continue;
@@ -10031,16 +10151,16 @@ function repairLedgerFromJournal(entries, priceUsd) {
10031
10151
  break;
10032
10152
  }
10033
10153
  for (const wire of wireRows) {
10034
- let target;
10154
+ let nearest;
10035
10155
  for (const row of rounds) {
10036
- if (row.seq >= wire.seq || row.wireRef !== void 0 || rowScopes.get(row) !== wire.scope) continue;
10037
- target = row;
10156
+ if (row.seq >= wire.seq || rowScopes.get(row) !== wire.scope) continue;
10157
+ nearest = row;
10038
10158
  }
10039
- if (target === void 0) continue;
10040
- target.wireRef = wire.seq;
10159
+ if (nearest === void 0 || nearest.wireRef !== void 0) continue;
10160
+ nearest.wireRef = wire.seq;
10041
10161
  if (priceUsd !== void 0 && wire.record.servedBy !== void 0) {
10042
10162
  const usd = priceUsd(wire.record.servedBy, wire.record.usage);
10043
- if (usd !== void 0 && Number.isFinite(usd) && usd >= 0) target.costUsd = usd;
10163
+ if (usd !== void 0 && Number.isFinite(usd) && usd >= 0) nearest.costUsd = usd;
10044
10164
  }
10045
10165
  }
10046
10166
  rounds.sort((a, b) => a.seq - b.seq);
@@ -10055,6 +10175,43 @@ function repairLedgerFromJournal(entries, priceUsd) {
10055
10175
  }
10056
10176
  //#endregion
10057
10177
  //#region src/stores/synthesis-candidates.ts
10178
+ /**
10179
+ * THE candidate hash recipe (RV4207), written down where the fold that
10180
+ * reads it lives: sha256 (hex) over the JCS canonical serialization of
10181
+ * the candidate VALUE, `null` for an absent one. This is the recipe
10182
+ * behind every `candidateHash` a finish-validation decision journals,
10183
+ * the claim judge's `judgedHash`, the citation audit's `auditedHash`,
10184
+ * and `draftToFinal`'s pair, so one function answers "which document"
10185
+ * across every surface. Two facts an auditor needs spelled out: a
10186
+ * STRING document hashes as its JSON encoding (the quotes and escapes
10187
+ * included), not as raw text bytes; and exporting the text to a file
10188
+ * with a trailing newline changes the FILE's sha256 while this hash is
10189
+ * unchanged, verify against the exact value, never the file. The sixth
10190
+ * comparison experiment's auditor re-derived all of this from source
10191
+ * because no exported function said it.
10192
+ */
10193
+ function candidateHashOf(candidate) {
10194
+ return createHash("sha256").update(jcsSerialize(candidate ?? null), "utf8").digest("hex");
10195
+ }
10196
+ /**
10197
+ * Verifies retained candidate bytes against a journaled candidateHash
10198
+ * (RV4207). The retained blob holds the candidate's TEXT verbatim (the
10199
+ * document itself for a string result, its JSON serialization
10200
+ * otherwise), while the hash covers the canonical VALUE, so the check
10201
+ * tries the value both ways: as the string document, then as parsed
10202
+ * JSON. Returns false on any mismatch or unparsable bytes, never
10203
+ * throws: the caller is an audit path, and a corrupt blob is a finding
10204
+ * there, not a crash.
10205
+ */
10206
+ function verifyCandidateBytes(bytes, hash) {
10207
+ const text = typeof bytes === "string" ? bytes : new TextDecoder().decode(bytes);
10208
+ if (candidateHashOf(text) === hash) return true;
10209
+ try {
10210
+ return candidateHashOf(JSON.parse(text)) === hash;
10211
+ } catch {
10212
+ return false;
10213
+ }
10214
+ }
10058
10215
  const parse = (at) => {
10059
10216
  if (at === void 0) return;
10060
10217
  const ms = Date.parse(at);
@@ -10203,6 +10360,7 @@ function synthesisCandidatesFromJournal(entries, priceUsd) {
10203
10360
  ...typeof value.candidateHash === "string" ? { candidateHash: value.candidateHash } : {},
10204
10361
  ...typeof value.candidateChars === "number" ? { candidateChars: value.candidateChars } : {},
10205
10362
  ...typeof value.candidateRef === "string" ? { candidateRef: value.candidateRef } : {},
10363
+ ...typeof value.bytesUnavailableReason === "string" ? { bytesUnavailableReason: value.bytesUnavailableReason } : {},
10206
10364
  failed: Array.isArray(value.failed) ? value.failed.filter((failure) => typeof failure.name === "string").map((failure) => ({
10207
10365
  name: failure.name,
10208
10366
  reasons: Array.isArray(failure.reasons) ? failure.reasons.filter((reason) => typeof reason === "string") : []
@@ -10288,7 +10446,7 @@ function toolCalibrationFromJournal(entries) {
10288
10446
  if (entry.kind !== "agent" || entry.ref === void 0 || entry.status === "running") continue;
10289
10447
  dispatches += 1;
10290
10448
  const role = entry.costAttribution?.role;
10291
- if ((role === "orchestrate" || role === "synthesize") && entry.toolBudget !== void 0) {
10449
+ if ((role === "orchestrate" || role === "synthesize") && entry.toolBudget !== void 0 && entry.evidence === void 0) {
10292
10450
  coordinationDispatches += 1;
10293
10451
  coordinationToolCalls += entry.toolBudget.used;
10294
10452
  continue;
@@ -10798,6 +10956,14 @@ function compareRates(seed, page) {
10798
10956
  const nativeNow = Date.now;
10799
10957
  /** The fixed accounting window every PerMinute cap counts over. */
10800
10958
  const QUOTA_WINDOW_MS = 6e4;
10959
+ /** The scope-dimension keys a QuotaRule can pin (RV4205). */
10960
+ const RULE_SCOPE_DIMENSIONS = [
10961
+ "account",
10962
+ "project",
10963
+ "legalDomain",
10964
+ "region",
10965
+ "providerAccount"
10966
+ ];
10801
10967
  /**
10802
10968
  * Validates a quota rule set as a typed ConfigError before any
10803
10969
  * limiter can admit under it: a non-array or empty set, a rule
@@ -10815,7 +10981,8 @@ function validateQuotaRules(rules, site = "quota rules") {
10815
10981
  for (const dimension of [
10816
10982
  "provider",
10817
10983
  "model",
10818
- "tenant"
10984
+ "tenant",
10985
+ ...RULE_SCOPE_DIMENSIONS
10819
10986
  ]) {
10820
10987
  const value = rule[dimension];
10821
10988
  if (value !== void 0 && (typeof value !== "string" || value === "")) throw new ConfigError(`${at}.${dimension} must be a nonempty string when given`);
@@ -10838,6 +11005,11 @@ function quotaRuleKey(rule) {
10838
11005
  provider: rule.provider ?? null,
10839
11006
  model: rule.model ?? null,
10840
11007
  tenant: rule.tenant ?? null,
11008
+ ...rule.account === void 0 ? {} : { account: rule.account },
11009
+ ...rule.project === void 0 ? {} : { project: rule.project },
11010
+ ...rule.legalDomain === void 0 ? {} : { legalDomain: rule.legalDomain },
11011
+ ...rule.region === void 0 ? {} : { region: rule.region },
11012
+ ...rule.providerAccount === void 0 ? {} : { providerAccount: rule.providerAccount },
10841
11013
  requestsPerMinute: rule.requestsPerMinute ?? null,
10842
11014
  tokensPerMinute: rule.tokensPerMinute ?? null
10843
11015
  });
@@ -10873,13 +11045,18 @@ function snapshotQuotaRules(rules, site = "quota rules") {
10873
11045
  ...rule.provider === void 0 ? {} : { provider: rule.provider },
10874
11046
  ...rule.model === void 0 ? {} : { model: rule.model },
10875
11047
  ...rule.tenant === void 0 ? {} : { tenant: rule.tenant },
11048
+ ...rule.account === void 0 ? {} : { account: rule.account },
11049
+ ...rule.project === void 0 ? {} : { project: rule.project },
11050
+ ...rule.legalDomain === void 0 ? {} : { legalDomain: rule.legalDomain },
11051
+ ...rule.region === void 0 ? {} : { region: rule.region },
11052
+ ...rule.providerAccount === void 0 ? {} : { providerAccount: rule.providerAccount },
10876
11053
  ...rule.requestsPerMinute === void 0 ? {} : { requestsPerMinute: rule.requestsPerMinute },
10877
11054
  ...rule.tokensPerMinute === void 0 ? {} : { tokensPerMinute: rule.tokensPerMinute }
10878
11055
  })));
10879
11056
  }
10880
11057
  /** True when every dimension the rule pins matches the request. */
10881
11058
  function quotaRuleMatches(rule, request) {
10882
- return (rule.provider === void 0 || rule.provider === request.provider) && (rule.model === void 0 || rule.model === request.model) && (rule.tenant === void 0 || rule.tenant === request.tenant);
11059
+ return (rule.provider === void 0 || rule.provider === request.provider) && (rule.model === void 0 || rule.model === request.model) && (rule.tenant === void 0 || rule.tenant === request.tenant) && (rule.account === void 0 || rule.account === request.scope?.account) && (rule.project === void 0 || rule.project === request.scope?.project) && (rule.legalDomain === void 0 || rule.legalDomain === request.scope?.legalDomain) && (rule.region === void 0 || rule.region === request.scope?.region) && (rule.providerAccount === void 0 || rule.providerAccount === request.scope?.providerAccount);
10883
11060
  }
10884
11061
  /** The tokens a reservation is admitted under: input estimate plus the output cap. */
10885
11062
  function quotaEstimateTokens(request) {
@@ -11088,6 +11265,8 @@ function validateEngineQuotaConfig(config, site = "createEngine quota") {
11088
11265
  const limiter = candidate.limiter;
11089
11266
  if (typeof limiter !== "object" || limiter === null || typeof limiter.reserve !== "function" || typeof limiter.reconcile !== "function") throw new ConfigError(`${site}.limiter must implement QuotaLimiter (reserve and reconcile functions)`);
11090
11267
  if (candidate.tenant !== void 0 && (typeof candidate.tenant !== "string" || candidate.tenant === "")) throw new ConfigError(`${site}.tenant must be a nonempty string when given`);
11268
+ const tenantFrom = candidate.tenantFrom;
11269
+ if (tenantFrom !== void 0 && tenantFrom !== "engine" && tenantFrom !== "scope") throw new ConfigError(`${site}.tenantFrom must be 'engine' or 'scope' when given`);
11091
11270
  if (candidate.onLimiterError !== void 0 && candidate.onLimiterError !== "deny" && candidate.onLimiterError !== "allow") throw new ConfigError(`${site}.onLimiterError must be 'deny' or 'allow' when given`);
11092
11271
  const reserveContinuations = candidate.reserveContinuations;
11093
11272
  if (reserveContinuations !== void 0 && typeof reserveContinuations !== "boolean") throw new ConfigError(`${site}.reserveContinuations must be a boolean when given`);
@@ -16173,6 +16352,35 @@ function isOrchestratorAccount(scope) {
16173
16352
  function attributionBucket(value) {
16174
16353
  return value === void 0 || value === "" ? "unknown" : value;
16175
16354
  }
16355
+ /**
16356
+ * The byAgentType bucket of one attributed slice (RV4206, the RV3905
16357
+ * vacuum-fill precedent carried to the agent-type table). A declared
16358
+ * agentType always wins, verbatim. The vacuum, an absent or empty
16359
+ * agentType, is FILLED from facts the journal already records instead
16360
+ * of stamping new bytes: role 'orchestrate' names the bucket
16361
+ * 'orchestrator' (the coordination loop and the forced-finish wake),
16362
+ * and role 'synthesize' names it by the dispatch label through the
16363
+ * ONE {@link synthesizeSpanClassOf} classifier: 'synthesizer' for
16364
+ * compositions and notes, 'claim-judge' and 'citation-judge' for the
16365
+ * two judges, with an unknown label keeping the honest 'unknown'.
16366
+ * Because the derivation reads only recorded facts, the live report,
16367
+ * the journal fold, and every ARCHIVED journal report the same named
16368
+ * buckets: the sixth comparison run's report read byAgentType 100%
16369
+ * 'unknown' over a run whose every dispatch had a nameable stage, and
16370
+ * that same journal now folds to named rows retroactively. Both
16371
+ * accumulation sites and the journal fold call this one function, the
16372
+ * RV3302 no-drift doctrine.
16373
+ */
16374
+ function agentTypeBucket(agentType, role, label) {
16375
+ if (agentType !== void 0 && agentType !== "") return agentType;
16376
+ if (role === "orchestrate") return "orchestrator";
16377
+ if (role === "synthesize") {
16378
+ const cls = synthesizeSpanClassOf(label);
16379
+ if (cls === "composition") return "synthesizer";
16380
+ return cls === "unclassified" ? "unknown" : cls;
16381
+ }
16382
+ return "unknown";
16383
+ }
16176
16384
  /** {@link attributionBucket} over a whole live map, merging folded keys. */
16177
16385
  function foldBuckets(source) {
16178
16386
  const folded = {};
@@ -16306,7 +16514,7 @@ function costReportFromJournal(entries, priceUsd) {
16306
16514
  phaseUsd -= unit.usd;
16307
16515
  }
16308
16516
  byPhase[phase] = (byPhase[phase] ?? 0) + phaseUsd;
16309
- const agentType = attributionBucket(facts?.agentType);
16517
+ const agentType = agentTypeBucket(facts?.agentType, facts?.role, facts?.label);
16310
16518
  byAgentType[agentType] = (byAgentType[agentType] ?? 0) + priced.usd;
16311
16519
  const scope = scopeBucket(entry.scope);
16312
16520
  byScope[scope] = (byScope[scope] ?? 0) + priced.usd;
@@ -16805,7 +17013,10 @@ function invoiceFromJournal(entries, priceUsd, options) {
16805
17013
  for (const entry of entries) {
16806
17014
  if (entry.kind !== "decision") continue;
16807
17015
  const value = entry.value;
16808
- if (value?.decisionType === "execution_scope" && typeof value.scope === "object") return { executionScope: value.scope };
17016
+ if (value?.decisionType === "execution_scope" && typeof value.scope === "object") return {
17017
+ executionScope: value.scope,
17018
+ ...typeof value.scopeDigest === "string" ? { executionScopeDigest: value.scopeDigest } : {}
17019
+ };
16809
17020
  }
16810
17021
  return {};
16811
17022
  })(),
@@ -18110,8 +18321,9 @@ function acceptanceTailRequiredUsd(spec) {
18110
18321
  const onFound = spec.claimOnFound ?? "report";
18111
18322
  const citationDeclared = spec.citationJudgeEstCostUsd !== void 0 || spec.citationOnFound !== void 0;
18112
18323
  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);
18324
+ const claimRoundArmed = onFound === "repair" && stage !== "draft";
18325
+ const roundArmed = claimRoundArmed || citationRoundArmed;
18326
+ const judgePasses = acceptanceJudgePasses(spec.claimStage, spec.claimOnFound) + (citationRoundArmed && !claimRoundArmed && spec.claimConfigured === true && stage !== "draft" ? 1 : 0);
18115
18327
  const citationJudgePasses = citationDeclared ? 1 + (citationRoundArmed ? 1 : 0) : 0;
18116
18328
  const citationJudgeEstUsd = spec.citationJudgeEstCostUsd ?? 0;
18117
18329
  const terms = {
@@ -18155,18 +18367,43 @@ function formatAcceptanceTailTerms(terms) {
18155
18367
  * `1 + r`.
18156
18368
  */
18157
18369
  function wireCapacityEstimate(spec) {
18158
- requireNonNegativeNumber(spec.childWires, "wireCapacityEstimate childWires");
18370
+ const known = [
18371
+ "childWires",
18372
+ "children",
18373
+ "turnsPerChild",
18374
+ "coordinationWires",
18375
+ "synthesisWires",
18376
+ "judgeWires",
18377
+ "citationJudgeWires",
18378
+ "extractWires"
18379
+ ];
18380
+ for (const key of Object.keys(spec)) if (!known.includes(key)) throw new ConfigError(`wireCapacityEstimate does not know the key '${key}'; the declared vocabulary is ${known.join(", ")}. A repair round is priced by the estimate itself (repairRoundDeltaWires), and retries by retryWireMultiplier; neither is an input.`);
18381
+ const structural = spec.children !== void 0 || spec.turnsPerChild !== void 0;
18382
+ if (structural) {
18383
+ if (spec.children === void 0 || spec.turnsPerChild === void 0) throw new ConfigError("wireCapacityEstimate children and turnsPerChild come as a pair: declare both, or declare the childWires total alone");
18384
+ requireNonNegativeNumber(spec.children, "wireCapacityEstimate children");
18385
+ requireNonNegativeNumber(spec.turnsPerChild, "wireCapacityEstimate turnsPerChild");
18386
+ } else if (spec.childWires === void 0) throw new ConfigError("wireCapacityEstimate needs the fan-out declared: childWires (children times their turns), or the structural pair children and turnsPerChild");
18387
+ if (spec.childWires !== void 0) requireNonNegativeNumber(spec.childWires, "wireCapacityEstimate childWires");
18388
+ if (structural && spec.childWires !== void 0) {
18389
+ const product = (spec.children ?? 0) * (spec.turnsPerChild ?? 0);
18390
+ if (spec.childWires !== product) throw new ConfigError(`wireCapacityEstimate childWires ${String(spec.childWires)} contradicts children ${String(spec.children)} x turnsPerChild ${String(spec.turnsPerChild)} = ${String(product)}: childWires is the fan-out wire TOTAL, not the child count; declare one form, or make them agree`);
18391
+ }
18392
+ const childWires = spec.childWires ?? (spec.children ?? 0) * (spec.turnsPerChild ?? 0);
18159
18393
  const coordinationWires = spec.coordinationWires ?? 0;
18160
18394
  const synthesisWires = spec.synthesisWires ?? 0;
18161
18395
  const judgeWires = spec.judgeWires ?? 0;
18396
+ const citationJudgeWires = spec.citationJudgeWires ?? 0;
18162
18397
  const extractWires = spec.extractWires ?? 0;
18163
18398
  requireNonNegativeNumber(coordinationWires, "wireCapacityEstimate coordinationWires");
18164
18399
  requireNonNegativeNumber(synthesisWires, "wireCapacityEstimate synthesisWires");
18165
18400
  requireNonNegativeNumber(judgeWires, "wireCapacityEstimate judgeWires");
18401
+ requireNonNegativeNumber(citationJudgeWires, "wireCapacityEstimate citationJudgeWires");
18166
18402
  requireNonNegativeNumber(extractWires, "wireCapacityEstimate extractWires");
18167
- const baseWires = spec.childWires + coordinationWires + synthesisWires + judgeWires + extractWires;
18403
+ const baseWires = childWires + coordinationWires + synthesisWires + judgeWires + citationJudgeWires + extractWires;
18168
18404
  const repairRoundDeltaWires = 2;
18169
18405
  return {
18406
+ basis: "declared-estimate",
18170
18407
  baseWires,
18171
18408
  repairRoundDeltaWires,
18172
18409
  mechanicalRepairDeltaWires: 1,
@@ -18658,6 +18895,78 @@ function emitSpawnRejected(events, input) {
18658
18895
  }, input.spanId, input.replayed);
18659
18896
  }
18660
18897
  //#endregion
18898
+ //#region src/orchestrator/semantic-verdict.ts
18899
+ const countOf = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
18900
+ /**
18901
+ * Folds the one semantic verdict out of envelope facts (RV4209).
18902
+ * Returns undefined when NO semantic meta is present: nothing was
18903
+ * configured, nothing judged anything, and absence must keep meaning
18904
+ * NOT RECORDED rather than a fabricated verdict. Never throws on
18905
+ * malformed shapes: an untyped field reads as absent, and the verdict
18906
+ * degrades toward 'not-judged', the fail-closed direction.
18907
+ */
18908
+ function semanticTerminalVerdictOf(input) {
18909
+ const claim = input.claimConsistencyMeta;
18910
+ const audit = input.citationAuditMeta;
18911
+ if (claim === void 0 && audit === void 0) return;
18912
+ const judgeFailures = [];
18913
+ if (claim?.judgeFailed === true) judgeFailures.push("claim-judge-failed");
18914
+ if (claim?.judgeDeclined === true) judgeFailures.push("claim-judge-declined");
18915
+ if (audit?.judgeFailed === true) judgeFailures.push("citation-judge-failed");
18916
+ if (audit?.judgeDeclined === true) judgeFailures.push("citation-judge-declined");
18917
+ if (claim?.judgedStage === "draft" && input.draftToFinal?.rewritten === true) judgeFailures.push("draft-rewritten-unjudged");
18918
+ const coverage = typeof claim?.coverage === "string" ? claim.coverage : void 0;
18919
+ if (coverage === "judge-failed" && !judgeFailures.includes("claim-judge-failed")) judgeFailures.push("claim-judge-failed");
18920
+ if (coverage === "judge-declined" && !judgeFailures.includes("claim-judge-declined")) judgeFailures.push("claim-judge-declined");
18921
+ const contradictions = countOf(claim?.findings);
18922
+ const unsupportedCitations = countOf(audit?.unsupported);
18923
+ const partialCitations = countOf(audit?.partial);
18924
+ const semanticRepairRounds = Math.max(countOf(claim?.semanticRepairRounds), countOf(audit?.citationRepairRounds));
18925
+ const waiverCandidate = input.claimCoverageWaiver;
18926
+ const waiver = waiverCandidate !== void 0 && typeof waiverCandidate.principal === "string" && typeof waiverCandidate.reason === "string" && typeof waiverCandidate.coverage === "string" ? {
18927
+ principal: waiverCandidate.principal,
18928
+ reason: waiverCandidate.reason,
18929
+ ...typeof waiverCandidate.expiresAt === "string" ? { expiresAt: waiverCandidate.expiresAt } : {},
18930
+ coverage: waiverCandidate.coverage
18931
+ } : void 0;
18932
+ const finalHash = typeof claim?.judgedHash === "string" ? claim.judgedHash : typeof audit?.auditedHash === "string" ? audit.auditedHash : void 0;
18933
+ return {
18934
+ verdict: judgeFailures.length > 0 ? "not-judged" : contradictions > 0 || unsupportedCitations > 0 ? "findings" : waiver !== void 0 ? "waived" : coverage === "partial" || coverage === "critical-uncovered" ? "partial" : coverage === "vacuous" ? "vacuous" : "clean",
18935
+ ...finalHash === void 0 ? {} : { finalHash },
18936
+ ...coverage === void 0 ? {} : { coverage },
18937
+ contradictions,
18938
+ unsupportedCitations,
18939
+ partialCitations,
18940
+ semanticRepairRounds,
18941
+ ...waiver === void 0 ? {} : { waiver },
18942
+ judgeFailures
18943
+ };
18944
+ }
18945
+ /**
18946
+ * The production acceptance predicate (RV4209): the one boolean a
18947
+ * production consumer gates on, with the stable reason when it
18948
+ * refuses. A verdict is production-acceptable exactly when it exists
18949
+ * and reads 'clean': 'partial' and 'vacuous' are legal diagnostics
18950
+ * (strict keeps exit 0 on them by documented design), 'waived' is a
18951
+ * human exception a machine gate must surface rather than inherit,
18952
+ * and an ABSENT verdict means nothing judged anything, which a
18953
+ * production gate reads fail closed. Exported so the CLI's
18954
+ * `--acceptance-policy production`, a server consumer, and a host
18955
+ * pipeline apply the SAME rule instead of three re-derivations.
18956
+ */
18957
+ function productionAcceptable(verdict) {
18958
+ if (verdict === void 0) return {
18959
+ ok: false,
18960
+ reason: "not-judged: the terminal carries no semantic verdict (no claim or citation machinery was configured, or the run predates it)"
18961
+ };
18962
+ if (verdict.verdict === "clean") return { ok: true };
18963
+ const detail = verdict.verdict === "findings" ? `${String(verdict.contradictions)} contradiction(s), ${String(verdict.unsupportedCitations)} unsupported citation(s)` : verdict.verdict === "waived" ? `waived by ${verdict.waiver?.principal ?? "unknown"} over coverage '${verdict.waiver?.coverage ?? "unknown"}'` : verdict.verdict === "not-judged" ? verdict.judgeFailures.join(", ") : `coverage '${verdict.coverage ?? "unknown"}'`;
18964
+ return {
18965
+ ok: false,
18966
+ reason: `${verdict.verdict}: ${detail}`
18967
+ };
18968
+ }
18969
+ //#endregion
18661
18970
  //#region src/runtime/permission-chain.ts
18662
18971
  /**
18663
18972
  * The layered permission chain (M3-T03): the single approval surface for
@@ -19335,6 +19644,7 @@ function createCtx(internals, rootWorkflow) {
19335
19644
  const declaredTools = opts.tools ?? profile?.tools ?? [];
19336
19645
  const toolset = await resolveToolset(escalation === void 0 ? declaredTools : [...declaredTools, escalateTool()], { runId: internals.runId }, internals.defaults.toolsets, internals.executors === void 0 ? void 0 : new Set(Object.keys(internals.executors)));
19337
19646
  if (profile?.toolsetAttestation !== void 0) enforceToolsetAttestation(agentType, profile.toolsetAttestation, toolset);
19647
+ else if (internals.defaults.requireToolsetAttestation === true && toolset.contracts.length > 0) throw new ConfigError(`agentType '${agentType}' resolves ${String(toolset.contracts.length)} tool(s) with no toolsetAttestation binding them (requireToolsetAttestation): a regulated spawn executes only pinned toolsets; record the pin with attestToolset() on the profile, or drop the tools`);
19338
19648
  const layers = [
19339
19649
  callLayer,
19340
19650
  profileLayer,
@@ -19621,7 +19931,7 @@ function createCtx(internals, rootWorkflow) {
19621
19931
  replayPhaseUsd -= unit.usd;
19622
19932
  }
19623
19933
  bump(internals.cost.byPhase, state.phase ?? "", replayPhaseUsd);
19624
- bump(internals.cost.byAgentType, agentType, costUsd);
19934
+ bump(internals.cost.byAgentType, agentTypeBucket(agentType, primaryRole, opts.label), costUsd);
19625
19935
  bump(internals.cost.byScope, state.scope, costUsd);
19626
19936
  internals.cost.byRole.set(primaryRole, (internals.cost.byRole.get(primaryRole) ?? 0) + costUsd);
19627
19937
  if (result.status === "escalated" && result.escalation !== void 0) {
@@ -20136,11 +20446,14 @@ function createCtx(internals, rootWorkflow) {
20136
20446
  if (retryPolicy !== void 0) runAgentOptions.retry = { policy: retryPolicy };
20137
20447
  if (internals.quota !== void 0) {
20138
20448
  const quota = internals.quota;
20449
+ const reservationTenant = quota.tenantFrom === "scope" ? internals.executionScope?.tenant : quota.tenant;
20450
+ const reservationScope = internals.executionScope;
20139
20451
  runAgentOptions.quota = {
20140
20452
  reserve: (request) => quota.limiter.reserve({
20141
20453
  ...request,
20142
20454
  runId: internals.runId,
20143
- ...quota.tenant === void 0 ? {} : { tenant: quota.tenant }
20455
+ ...reservationTenant === void 0 ? {} : { tenant: reservationTenant },
20456
+ ...reservationScope === void 0 ? {} : { scope: reservationScope }
20144
20457
  }),
20145
20458
  reconcile: (reservationId, usage, actual) => quota.limiter.reconcile(reservationId, usage, actual),
20146
20459
  onLimiterError: quota.onLimiterError,
@@ -20177,10 +20490,12 @@ function createCtx(internals, rootWorkflow) {
20177
20490
  internals.budget.releaseReserve(reserve, budgetAccount);
20178
20491
  const declaredRules = internals.quota?.declaredRules;
20179
20492
  if (declaredRules !== void 0 && result.rateLimitObservations !== void 0) for (const observation of result.rateLimitObservations) {
20493
+ const probeTenant = internals.quota?.tenantFrom === "scope" ? internals.executionScope?.tenant : internals.quota?.tenant;
20180
20494
  const probe = {
20181
20495
  provider: observation.provider,
20182
20496
  model: observation.model,
20183
- ...internals.quota?.tenant === void 0 ? {} : { tenant: internals.quota.tenant },
20497
+ ...probeTenant === void 0 ? {} : { tenant: probeTenant },
20498
+ ...internals.executionScope === void 0 ? {} : { scope: internals.executionScope },
20184
20499
  estimate: {
20185
20500
  requests: 1,
20186
20501
  inputTokens: 0
@@ -20329,6 +20644,7 @@ function createCtx(internals, rootWorkflow) {
20329
20644
  ...result.providerCalls === void 0 ? {} : { providerCalls: result.providerCalls },
20330
20645
  costAttribution: {
20331
20646
  ...state.phase === void 0 ? {} : { phase: state.phase },
20647
+ ...state.repairTrigger === void 0 ? {} : { repairTrigger: state.repairTrigger },
20332
20648
  agentType,
20333
20649
  role: primaryRole,
20334
20650
  budgetAccount: state.budgetScope ?? "run",
@@ -20440,7 +20756,7 @@ function createCtx(internals, rootWorkflow) {
20440
20756
  livePhaseUsd -= recordUsd;
20441
20757
  }
20442
20758
  bump(internals.cost.byPhase, state.phase ?? "", livePhaseUsd);
20443
- bump(internals.cost.byAgentType, agentType, usd);
20759
+ bump(internals.cost.byAgentType, agentTypeBucket(agentType, primaryRole, opts.label), usd);
20444
20760
  bump(internals.cost.byScope, state.scope, usd);
20445
20761
  if (result.error?.kind === "budget" || internals.budget.exhausted && result.status !== "ok") {
20446
20762
  if (!internals.budget.exhausted && result.errorMessage !== void 0 && result.errorMessage.startsWith("in flight exposure cap reached")) throw new BudgetExhaustedError(result.errorMessage, { data: {
@@ -22687,6 +23003,8 @@ const RANGE_TAIL = /^(.*):(\d+)(?:-(\d+))?$/u;
22687
23003
  * Garbage throws like every malformed intake.
22688
23004
  */
22689
23005
  function resolveCitationAuditPlan(options) {
23006
+ const resolver = options.resolver ?? 1;
23007
+ if (resolver !== 1 && resolver !== 2) throw new ConfigError(`citationAudit.resolver must be 1 or 2; got ${JSON.stringify(options.resolver)}`);
22690
23008
  const samplePerSection = options.samplePerSection ?? 2;
22691
23009
  if (!Number.isInteger(samplePerSection) || samplePerSection < 1) throw new ConfigError(`citationAudit.samplePerSection must be a positive integer; got ${String(options.samplePerSection)}`);
22692
23010
  const maxSampled = options.maxSampled ?? 24;
@@ -22705,7 +23023,8 @@ function resolveCitationAuditPlan(options) {
22705
23023
  pattern,
22706
23024
  samplePerSection,
22707
23025
  maxSampled,
22708
- window
23026
+ window,
23027
+ resolver
22709
23028
  };
22710
23029
  }
22711
23030
  /** Splits a document into (section marker, body) runs in order. */
@@ -22753,26 +23072,36 @@ function pickIndexes(count, k, seedInput) {
22753
23072
  * of auditing the first sections only.
22754
23073
  */
22755
23074
  function sampleCitationRows(document, plan, seed) {
23075
+ const allAnchors = plan.resolver === 2;
22756
23076
  const perSection = [];
22757
23077
  for (const { marker, body } of sectionsOfDocument(document)) {
22758
23078
  const candidates = [];
22759
23079
  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
- });
23080
+ const probe = citationWithRange(plan.pattern);
23081
+ const anchors = [];
23082
+ for (let match = probe.exec(sentence); match !== null; match = probe.exec(sentence)) {
23083
+ const tail = /^-(\d+)/u.exec(sentence.slice(match.index + match[0].length));
23084
+ const anchorText = tail === null ? match[0] : `${match[0]}${tail[0]}`;
23085
+ const parsed = RANGE_TAIL.exec(anchorText);
23086
+ if (parsed === null) continue;
23087
+ const path = parsed[1] ?? "";
23088
+ const line = Number(parsed[2]);
23089
+ const endLine = parsed[3] === void 0 ? void 0 : Number(parsed[3]);
23090
+ if (path === "" || !Number.isInteger(line) || line < 1) continue;
23091
+ anchors.push({
23092
+ sentence,
23093
+ anchor: anchorText,
23094
+ path,
23095
+ line,
23096
+ ...endLine !== void 0 && Number.isInteger(endLine) && endLine >= line ? { endLine } : {},
23097
+ ...allAnchors ? {
23098
+ anchorOrdinal: anchors.length,
23099
+ clause: clauseAround(sentence, match.index)
23100
+ } : {}
23101
+ });
23102
+ if (!allAnchors) break;
23103
+ }
23104
+ if (anchors.length > 0) candidates.push(anchors);
22776
23105
  }
22777
23106
  if (candidates.length === 0) continue;
22778
23107
  const picks = pickIndexes(candidates.length, plan.samplePerSection, `${seed}:${marker}`).map((index) => candidates[index]).filter((candidate) => candidate !== void 0);
@@ -22788,18 +23117,36 @@ function sampleCitationRows(document, plan, seed) {
22788
23117
  const pick = bucket.picks[rank];
22789
23118
  if (pick === void 0) continue;
22790
23119
  any = true;
22791
- if (rows.length >= plan.maxSampled) break;
22792
- rows.push({
22793
- row: rows.length,
22794
- section: bucket.section,
22795
- ...pick
22796
- });
23120
+ for (const anchor of pick) {
23121
+ if (rows.length >= plan.maxSampled) break;
23122
+ rows.push({
23123
+ row: rows.length,
23124
+ section: bucket.section,
23125
+ ...anchor
23126
+ });
23127
+ }
22797
23128
  }
22798
23129
  if (!any) break;
22799
23130
  }
22800
23131
  return rows;
22801
23132
  }
22802
23133
  /**
23134
+ * The claim clause nearest an anchor (RV4208): the sentence segment,
23135
+ * cut at clause boundaries (';' or ',' followed by whitespace), that
23136
+ * contains the anchor position. Pure text arithmetic, no NLP: the
23137
+ * point is to hand the judge the claim half the anchor was cited FOR
23138
+ * instead of the whole compound sentence.
23139
+ */
23140
+ function clauseAround(sentence, anchorIndex) {
23141
+ let start = 0;
23142
+ const cuts = /[;,]\s/gu;
23143
+ for (let cut = cuts.exec(sentence); cut !== null; cut = cuts.exec(sentence)) {
23144
+ if (cut.index >= anchorIndex) return sentence.slice(start, cut.index + 1).trim();
23145
+ start = cut.index + 1;
23146
+ }
23147
+ return sentence.slice(start).trim();
23148
+ }
23149
+ /**
22803
23150
  * Resolves one sampled citation's excerpt through the host's pure
22804
23151
  * snapshot resolver. The FIRST cited line failing to resolve returns
22805
23152
  * undefined (an unsupported citation by doctrine); later lines simply
@@ -22823,6 +23170,107 @@ function citationExcerptOf(resolve, row, window) {
22823
23170
  const excerpt = lines.join("\n");
22824
23171
  return excerpt.length > 800 ? `${excerpt.slice(0, 800)}…` : excerpt;
22825
23172
  }
23173
+ const HEADING = /^#{1,6}\s+\S/u;
23174
+ const LIST_ITEM = /^(\s*)(?:[-*+]|\d+[.)])\s+\S/u;
23175
+ const TABLE_ROW = /^\s*\|/u;
23176
+ const CODE_COMMENT = /^\s*(?:\/\/|#(?!#)|\*|\/\*|--)\s?/u;
23177
+ /**
23178
+ * Resolver v2's excerpt: the bounded LOGICAL UNIT the cited line
23179
+ * belongs to (RV4208), through the same pure line resolver v1 reads.
23180
+ * The v1 window is a fixed downward slice, and the sixth comparison
23181
+ * experiment's confirmed false negative was structural: a section
23182
+ * heading cited as the anchor with its support three lines below the
23183
+ * window. The unit rules, all bounded by {@link
23184
+ * MAX_CITATION_EXCERPT_LINES} and {@link MAX_CITATION_EXCERPT_CHARS}
23185
+ * with a `truncated` flag when clipped:
23186
+ *
23187
+ * - heading: the SECTION, the heading plus following lines to the
23188
+ * next heading;
23189
+ * - table row: the row, with the header pair above it when adjacent;
23190
+ * - list item: the marker line plus its more-indented continuation
23191
+ * lines;
23192
+ * - code comment: the comment BLOCK (expanded upward to its start)
23193
+ * plus the declaration lines it documents, to the first blank line;
23194
+ * - anything else: the paragraph, expanded upward and downward to the
23195
+ * nearest blank or heading line.
23196
+ *
23197
+ * An explicit `path:start-end` range keeps range semantics (the host
23198
+ * cited exact lines; second-guessing them would audit a different
23199
+ * citation): the ranged lines, clipped by the caps. The FIRST cited
23200
+ * line failing to resolve returns undefined, the unsupported-by-
23201
+ * doctrine verdict v1 renders.
23202
+ */
23203
+ function citationUnitExcerptOf(resolve, row) {
23204
+ const lineAt = (line) => line < 1 ? void 0 : resolve({
23205
+ path: row.path,
23206
+ line
23207
+ });
23208
+ const anchor = lineAt(row.line);
23209
+ if (anchor === void 0) return;
23210
+ const collect = (type, firstLine, include) => {
23211
+ const lines = [];
23212
+ let truncated = false;
23213
+ for (let line = firstLine;; line += 1) {
23214
+ if (lines.length >= 12) {
23215
+ truncated = true;
23216
+ break;
23217
+ }
23218
+ const text = line === row.line ? anchor : lineAt(line);
23219
+ if (text === void 0) break;
23220
+ if (line !== firstLine && line !== row.line && !include(text, line)) break;
23221
+ lines.push(`L${String(line)}: ${text}`);
23222
+ }
23223
+ let excerpt = lines.join("\n");
23224
+ if (excerpt.length > 800) {
23225
+ excerpt = `${excerpt.slice(0, 800)}…`;
23226
+ truncated = true;
23227
+ }
23228
+ return {
23229
+ excerpt,
23230
+ unit: {
23231
+ type,
23232
+ lines: lines.length,
23233
+ ...truncated ? { truncated: true } : {}
23234
+ }
23235
+ };
23236
+ };
23237
+ if (row.endLine !== void 0) {
23238
+ const last = row.endLine;
23239
+ return collect("paragraph", row.line, (_text, line) => line <= last);
23240
+ }
23241
+ if (HEADING.test(anchor)) return collect("section", row.line, (text) => !HEADING.test(text));
23242
+ if (TABLE_ROW.test(anchor)) {
23243
+ const above = lineAt(row.line - 1);
23244
+ const headerTop = lineAt(row.line - 2);
23245
+ return collect("table-row", above !== void 0 && headerTop !== void 0 && /^\s*\|[\s:|-]+\|?\s*$/u.test(above) && TABLE_ROW.test(headerTop) ? row.line - 2 : row.line, (text, line) => line <= row.line && TABLE_ROW.test(text));
23246
+ }
23247
+ const listMatch = LIST_ITEM.exec(anchor);
23248
+ if (listMatch !== null) {
23249
+ const markerIndent = (listMatch[1] ?? "").length;
23250
+ return collect("list-item", row.line, (text) => {
23251
+ if (text.trim() === "" || HEADING.test(text) || LIST_ITEM.test(text)) return false;
23252
+ return (/^(\s*)/u.exec(text)?.[1]?.length ?? 0) > markerIndent;
23253
+ });
23254
+ }
23255
+ if (CODE_COMMENT.test(anchor)) {
23256
+ let first = row.line;
23257
+ for (let line = row.line - 1; line >= 1 && row.line - line < 6; line -= 1) {
23258
+ const text = lineAt(line);
23259
+ if (text === void 0 || !CODE_COMMENT.test(text)) break;
23260
+ first = line;
23261
+ }
23262
+ return collect("comment-declaration", first, (text) => text.trim() !== "");
23263
+ }
23264
+ return collect("paragraph", (() => {
23265
+ let first = row.line;
23266
+ for (let line = row.line - 1; line >= 1 && row.line - line < 6; line -= 1) {
23267
+ const text = lineAt(line);
23268
+ if (text === void 0 || text.trim() === "" || HEADING.test(text)) break;
23269
+ first = line;
23270
+ }
23271
+ return first;
23272
+ })(), (text) => text.trim() !== "" && !HEADING.test(text));
23273
+ }
22826
23274
  /** The audit judge's structured verdict schema (mirrors the claim judge). */
22827
23275
  const CITATION_JUDGE_SCHEMA = {
22828
23276
  type: "object",
@@ -23050,6 +23498,8 @@ const DEFAULT_MAX_POOL_PER_PAIR = 3;
23050
23498
  const DEFAULT_MAX_PAIR_EXCERPT_CHARS = 400;
23051
23499
  /** Bound on the reported uncovered-critical anchor list (RV1603). */
23052
23500
  const MAX_CRITICAL_UNCOVERED = 32;
23501
+ /** Bound on the reported uncovered citing-sentence list (RV4202). */
23502
+ const MAX_UNCOVERED_SENTENCES = 24;
23053
23503
  /** Splits an anchor into path, start, and optional end at the LAST colon. */
23054
23504
  const ANCHOR_TAIL = /^(.*):(\d+)(?:-(\d+))?$/u;
23055
23505
  function requirePositiveInteger(value, what) {
@@ -23157,11 +23607,17 @@ function pairDraftClaims(draftText, rows, options) {
23157
23607
  let draftCitingSentences = 0;
23158
23608
  const criticalDraftAnchors = [];
23159
23609
  const seenCriticalAnchors = /* @__PURE__ */ new Set();
23610
+ const citingSentences = [];
23611
+ const seenCitingSentences = /* @__PURE__ */ new Set();
23160
23612
  for (const sentence of sentencesOf(draftText)) {
23161
23613
  const anchors = anchorsOf(sentence, pattern);
23162
23614
  if (anchors.length === 0) continue;
23163
23615
  draftCitingSentences += 1;
23164
23616
  const full = collapse(sentence);
23617
+ if (options?.reportUncovered === true && !seenCitingSentences.has(full)) {
23618
+ seenCitingSentences.add(full);
23619
+ citingSentences.push(full);
23620
+ }
23165
23621
  const draftExcerpt = full.slice(0, maxExcerptChars);
23166
23622
  for (const anchor of anchors) {
23167
23623
  const anchorCritical = critical !== void 0 && isCritical(anchor);
@@ -23237,6 +23693,11 @@ function pairDraftClaims(draftText, rows, options) {
23237
23693
  fold.criticalUncovered = uncovered.slice(0, 32);
23238
23694
  fold.criticalUncoveredTotal = uncovered.length;
23239
23695
  }
23696
+ if (options?.reportUncovered === true) {
23697
+ const uncovered = citingSentences.filter((sentence) => !coveredSentences.has(sentence));
23698
+ fold.uncoveredSentences = uncovered.slice(0, 24).map((sentence) => sentence.slice(0, maxExcerptChars));
23699
+ fold.uncoveredSentencesTotal = uncovered.length;
23700
+ }
23240
23701
  return fold;
23241
23702
  }
23242
23703
  /** The synthetic anchor and nodeId of run-facts pairs (RV1603). */
@@ -23749,6 +24210,15 @@ function selfTestFinishValidation(options) {
23749
24210
  /** How many rejected finishes are repaired by default: the plan's repair once. */
23750
24211
  const DEFAULT_FINISH_MAX_REPAIRS = 1;
23751
24212
  /**
24213
+ * The word ceiling of a 'digest' coordination draft (RV4210): the
24214
+ * digest is a structural evidence map the composing invocation writes
24215
+ * prose FROM, and the ceiling is the teeth that keep it from decaying
24216
+ * back into the full prose draft it exists to replace. The sixth
24217
+ * comparison run's contract-policy draft cost 344.8 seconds of model
24218
+ * output and was then rewritten whole by the composition.
24219
+ */
24220
+ const DIGEST_DRAFT_MAX_WORDS = 400;
24221
+ /**
23752
24222
  * The most hinted edits one deterministic repair attempt will apply
23753
24223
  * (RV3801): a validator caps its own hints well below this, so the
23754
24224
  * bound only guards against a custom validator flooding the journal
@@ -23951,11 +24421,21 @@ function validateOrchestrateOptions(opts) {
23951
24421
  if (estRepair !== void 0 && (typeof estRepair !== "number" || !Number.isFinite(estRepair) || estRepair < 0)) throw new ConfigError(`orchestrate finishValidation.estRepairCostUsd must be a nonnegative finite number; got ${JSON.stringify(estRepair)}`);
23952
24422
  const retain = fv.retainRejectedCandidates;
23953
24423
  if (retain !== void 0 && typeof retain !== "boolean") throw new ConfigError("orchestrate finishValidation.retainRejectedCandidates must be a boolean");
24424
+ const persistence = fv.candidatePersistence;
24425
+ if (persistence !== void 0) {
24426
+ if (persistence !== "transcript" && persistence !== "hash-only") throw new ConfigError(`orchestrate finishValidation.candidatePersistence must be 'transcript' or 'hash-only'; got ${JSON.stringify(persistence)}`);
24427
+ if (retain !== void 0) throw new ConfigError("orchestrate finishValidation.candidatePersistence supersedes retainRejectedCandidates: declare one, not both");
24428
+ }
23954
24429
  const draftPolicy = fv.draftPolicy;
23955
24430
  if (draftPolicy !== void 0) {
23956
- if (draftPolicy !== "contract" && (typeof draftPolicy !== "object" || draftPolicy === null)) throw new ConfigError("orchestrate finishValidation.draftPolicy must be an object or the sentinel 'contract'");
24431
+ if (draftPolicy !== "contract" && draftPolicy !== "digest" && (typeof draftPolicy !== "object" || draftPolicy === null)) throw new ConfigError("orchestrate finishValidation.draftPolicy must be an object or one of the sentinels 'contract' | 'digest'");
23957
24432
  if (opts.synthesis === void 0) throw new ConfigError("orchestrate finishValidation.draftPolicy requires synthesis: without a synthesis invocation the validators bind the coordination finish itself and there is no unvalidated draft to gate");
23958
- const policy = draftPolicy === "contract" ? void 0 : draftPolicy;
24433
+ if (draftPolicy === "digest") {
24434
+ const synthesisShape = opts.synthesis;
24435
+ if (synthesisShape.skipWhenDraftValid === true) throw new ConfigError("orchestrate finishValidation.draftPolicy 'digest' refuses synthesis.skipWhenDraftValid: a digest is a structural evidence map, never a shippable draft, and the skip gate exists to settle on one");
24436
+ if (synthesisShape.fallbackToValidDraft === true) throw new ConfigError("orchestrate finishValidation.draftPolicy 'digest' refuses synthesis.fallbackToValidDraft: the regression floor ships the draft, and a digest must never ship");
24437
+ }
24438
+ const policy = draftPolicy === "contract" || draftPolicy === "digest" ? void 0 : draftPolicy;
23959
24439
  if (policy !== void 0) {
23960
24440
  if (policy.minWords === void 0 && policy.requireSections === void 0) throw new ConfigError("orchestrate finishValidation.draftPolicy must declare minWords, requireSections, or both");
23961
24441
  if (policy.minWords !== void 0) {
@@ -24154,6 +24634,10 @@ function validateOrchestrateOptions(opts) {
24154
24634
  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
24635
  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
24636
  }
24637
+ const coverageRepair = consistency.coverageRepair;
24638
+ if (coverageRepair !== void 0 && typeof coverageRepair !== "boolean") throw new ConfigError(`orchestrate claimConsistency.coverageRepair must be a boolean; got ${typeof coverageRepair}`);
24639
+ if (coverageRepair === true && onFound !== "repair") throw new ConfigError("orchestrate claimConsistency.coverageRepair requires onFound 'repair': the bounded repair round is the machinery of that posture, and coverage can only join a round that exists");
24640
+ if (coverageRepair === true && coveragePolicy !== "strict-final") throw new ConfigError("orchestrate claimConsistency.coverageRepair requires coveragePolicy 'strict-final': the round averts exactly the refusal of that gate, and repairing an unenforced grade would spend a composition on nothing");
24157
24641
  if (consistency.judge !== void 0) {
24158
24642
  const judge = consistency.judge;
24159
24643
  if (typeof judge !== "object" || judge === null || Array.isArray(judge)) throw new ConfigError(`orchestrate claimConsistency.judge must be an object; got ${JSON.stringify(consistency.judge)}`);
@@ -24178,9 +24662,46 @@ function validateOrchestrateOptions(opts) {
24178
24662
  if (audit.judge?.estCost !== void 0) requireNonNegativeNumber(audit.judge.estCost, "orchestrate citationAudit.judge.estCost");
24179
24663
  if (audit.onFound === "repair") {
24180
24664
  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
24665
  }
24183
24666
  }
24667
+ const acceptance = opts.semanticAcceptance;
24668
+ if (acceptance !== void 0) {
24669
+ if (typeof acceptance !== "object" || acceptance === null || Array.isArray(acceptance)) throw new ConfigError(`orchestrate semanticAcceptance must be an object; got ${JSON.stringify(acceptance)}`);
24670
+ const knownKeys = [
24671
+ "judgedStage",
24672
+ "claimCoverage",
24673
+ "contradictions",
24674
+ "citations",
24675
+ "unresolved",
24676
+ "waiver"
24677
+ ];
24678
+ for (const key of Object.keys(acceptance)) if (!knownKeys.includes(key)) throw new ConfigError(`orchestrate semanticAcceptance carries unknown key '${key}'; the signature holds exactly judgedStage, claimCoverage, contradictions, citations, unresolved and waiver`);
24679
+ const shaped = acceptance;
24680
+ if (shaped.judgedStage !== "final") throw new ConfigError("orchestrate semanticAcceptance.judgedStage must be the literal 'final'; got " + JSON.stringify(shaped.judgedStage));
24681
+ if (shaped.claimCoverage !== "full") throw new ConfigError("orchestrate semanticAcceptance.claimCoverage must be the literal 'full'; got " + JSON.stringify(shaped.claimCoverage));
24682
+ if (shaped.contradictions !== "repair-once-then-fail" && shaped.contradictions !== "fail") throw new ConfigError(`orchestrate semanticAcceptance.contradictions must be 'repair-once-then-fail' or 'fail'; got ${JSON.stringify(shaped.contradictions)}`);
24683
+ if (shaped.citations !== "repair-once-then-fail" && shaped.citations !== "fail") throw new ConfigError(`orchestrate semanticAcceptance.citations must be 'repair-once-then-fail' or 'fail'; got ${JSON.stringify(shaped.citations)}`);
24684
+ if (shaped.unresolved !== "fail") throw new ConfigError("orchestrate semanticAcceptance.unresolved must be the literal 'fail'; got " + JSON.stringify(shaped.unresolved));
24685
+ const pinnedWaiver = typeof shaped.waiver === "object" && shaped.waiver !== null && !Array.isArray(shaped.waiver) ? shaped.waiver : void 0;
24686
+ if (shaped.waiver !== "forbid" && pinnedWaiver === void 0) throw new ConfigError("orchestrate semanticAcceptance.waiver must be 'forbid' or { judgedHash }; got " + JSON.stringify(shaped.waiver));
24687
+ if (pinnedWaiver !== void 0) {
24688
+ for (const key of Object.keys(pinnedWaiver)) if (key !== "judgedHash") throw new ConfigError(`orchestrate semanticAcceptance.waiver carries unknown key '${key}'; the pinned form holds exactly judgedHash`);
24689
+ if (typeof pinnedWaiver.judgedHash !== "string" || !/^[0-9a-f]{64}$/u.test(pinnedWaiver.judgedHash)) throw new ConfigError("orchestrate semanticAcceptance.waiver.judgedHash must be 64 lowercase hex chars (the claim meta judgedHash of the reviewed document); got " + JSON.stringify(pinnedWaiver.judgedHash));
24690
+ }
24691
+ const boundClaim = opts.claimConsistency;
24692
+ if (boundClaim === void 0) throw new ConfigError("orchestrate semanticAcceptance requires claimConsistency: the declaration binds that machinery, and omitting the pass entirely is the deepest loosening (RV4103)");
24693
+ if (audit === void 0) throw new ConfigError("orchestrate semanticAcceptance requires citationAudit: the declaration binds the entailment machinery, and omitting the audit entirely is the loosening the sixth experiment shipped five unsupported citations through");
24694
+ if (boundClaim.stage !== "final" && boundClaim.stage !== "both") throw new ConfigError("orchestrate semanticAcceptance requires claimConsistency.stage 'final' or 'both', declared: the signature judges the shipped document, and the default 'draft' judges the one the synthesis replaces; got " + JSON.stringify(boundClaim.stage));
24695
+ if (boundClaim.coveragePolicy !== "strict-final") throw new ConfigError("orchestrate semanticAcceptance requires claimConsistency.coveragePolicy 'strict-final', declared; got " + JSON.stringify(boundClaim.coveragePolicy));
24696
+ if (boundClaim.coverageTarget !== void 0 && boundClaim.coverageTarget !== 1) throw new ConfigError(`orchestrate semanticAcceptance.claimCoverage 'full' refuses coverageTarget ${JSON.stringify(boundClaim.coverageTarget)}: a pass sized to cover less than everything can never grade 'full' on a citing document, so the declaration would be unsatisfiable by construction; raise the target to 1 or drop it`);
24697
+ const wantClaimOnFound = shaped.contradictions === "fail" ? "fail" : "repair";
24698
+ if (boundClaim.onFound !== wantClaimOnFound) throw new ConfigError(`orchestrate semanticAcceptance.contradictions '${String(shaped.contradictions)}' requires claimConsistency.onFound '${wantClaimOnFound}', declared; got ` + JSON.stringify(boundClaim.onFound));
24699
+ if (shaped.contradictions === "repair-once-then-fail" && boundClaim.coverageRepair !== true) throw new ConfigError("orchestrate semanticAcceptance.contradictions 'repair-once-then-fail' requires claimConsistency.coverageRepair: true: the one bounded round serves every armed defect class, coverage included, and a declaration that repairs findings while refusing coverage the same chance is not the posture it reads as");
24700
+ const wantCitationOnFound = shaped.citations === "fail" ? "fail" : "repair";
24701
+ if (audit.onFound !== wantCitationOnFound) throw new ConfigError(`orchestrate semanticAcceptance.citations '${String(shaped.citations)}' requires citationAudit.onFound '${wantCitationOnFound}', declared; got ` + JSON.stringify(audit.onFound));
24702
+ if (shaped.waiver === "forbid" && boundClaim.waiver !== void 0) throw new ConfigError("orchestrate semanticAcceptance.waiver 'forbid' refuses a declared claimConsistency.waiver: a standing exception cannot ride a declaration that forbids exceptions");
24703
+ if (pinnedWaiver !== void 0 && boundClaim.waiver === void 0) throw new ConfigError("orchestrate semanticAcceptance.waiver pins a hash but claimConsistency.waiver is absent: the pin licenses a DECLARED waiver (principal and reason), so declare the waiver it pins");
24704
+ }
24184
24705
  const spec = opts.budget;
24185
24706
  if (spec === void 0) return;
24186
24707
  if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
@@ -25734,13 +26255,16 @@ function makeOrchestratorWorkflow(goal, opts) {
25734
26255
  }
25735
26256
  const repairsUsed = known.filter((candidate, index) => index >= validationInvocationStart && candidate.verdict !== "accepted" && contractGenerationCurrent(candidate)).length;
25736
26257
  const rejectedCandidate = failed.length > 0 && deterministicRepair?.outcome !== "accepted";
26258
+ const persistence = validationSpec.candidatePersistence;
25737
26259
  let candidateRef;
25738
- if (rejectedCandidate && validationSpec.retainRejectedCandidates === true) {
26260
+ let bytesUnavailableReason;
26261
+ if (rejectedCandidate && (validationSpec.retainRejectedCandidates === true || persistence === "transcript")) {
25739
26262
  const ref = `${internals.runId}/finish-rejected/${call.id}`;
25740
26263
  try {
25741
26264
  await internals.transcripts.put(ref, new TextEncoder().encode(input.text), internals.lease);
25742
26265
  candidateRef = ref;
25743
26266
  } catch (writeFailed) {
26267
+ if (persistence === "transcript") bytesUnavailableReason = "store-write-failed";
25744
26268
  internals.events.emit({
25745
26269
  type: "log",
25746
26270
  level: "warn",
@@ -25751,7 +26275,7 @@ function makeOrchestratorWorkflow(goal, opts) {
25751
26275
  }
25752
26276
  }, callingState.spanId);
25753
26277
  }
25754
- }
26278
+ } else if (rejectedCandidate && persistence === "hash-only") bytesUnavailableReason = "hash-only-persistence";
25755
26279
  decision = {
25756
26280
  decisionType: "orchestrator_finish_validation",
25757
26281
  callId: call.id,
@@ -25769,8 +26293,17 @@ function makeOrchestratorWorkflow(goal, opts) {
25769
26293
  ...rejectedCandidate ? {
25770
26294
  candidateHash: createHash("sha256").update(jcsSerialize(result), "utf8").digest("hex"),
25771
26295
  candidateChars: input.text.length,
25772
- ...candidateRef === void 0 ? {} : { candidateRef }
25773
- } : {}
26296
+ ...candidateRef === void 0 ? {} : { candidateRef },
26297
+ ...bytesUnavailableReason === void 0 ? {} : { bytesUnavailableReason }
26298
+ } : {},
26299
+ ...persistence !== void 0 && !rejectedCandidate ? (() => {
26300
+ const acceptedDoc = deterministicRepair?.outcome === "accepted" && patchedResult !== void 0 ? patchedResult : result;
26301
+ const acceptedText = typeof acceptedDoc === "string" ? acceptedDoc : JSON.stringify(acceptedDoc);
26302
+ return {
26303
+ candidateHash: candidateHashOf(acceptedDoc),
26304
+ candidateChars: acceptedText.length
26305
+ };
26306
+ })() : {}
25774
26307
  };
25775
26308
  await internals.replayer.appendSinglePhase({
25776
26309
  scope: callingState.scope,
@@ -25920,6 +26453,21 @@ function makeOrchestratorWorkflow(goal, opts) {
25920
26453
  failed
25921
26454
  }, failed);
25922
26455
  }
26456
+ if (policy === "digest") {
26457
+ const digestReasons = [];
26458
+ const trimmed = text.trim();
26459
+ const words = trimmed === "" ? 0 : trimmed.split(/\s+/).length;
26460
+ if (text.split("\n").filter((line) => /^\s*(?:[-*+]|\d+[.)])\s+\S/u.test(line)).length === 0) digestReasons.push("the digest carries no evidence rows: use one list row per planned section, naming its claims and the evidence behind them");
26461
+ if (words > 400) digestReasons.push(`the digest carries ${String(words)} words, over the ${String(400)} word ceiling: compress to the structural map; the composing invocation writes the prose`);
26462
+ if (digestReasons.length === 0) return accept();
26463
+ return reject({
26464
+ error: "the coordination draft failed the digest policy; repair the draft and call finish again: the digest is the structural evidence map the composing invocation writes prose from",
26465
+ reasons: digestReasons
26466
+ }, [{
26467
+ name: "digest-policy",
26468
+ reasons: digestReasons
26469
+ }]);
26470
+ }
25923
26471
  const reasons = [];
25924
26472
  if (policy.minWords !== void 0) {
25925
26473
  const trimmed = text.trim();
@@ -26382,6 +26930,27 @@ function makeOrchestratorWorkflow(goal, opts) {
26382
26930
  */
26383
26931
  let carriedCitationFindings;
26384
26932
  /**
26933
+ * The uncovered citing sentences riding a coverage-armed round's
26934
+ * prompt (RV4202): set exactly while such a round's composition
26935
+ * dispatches, mirroring `carriedCitationFindings`, so every other
26936
+ * synthesis prompt keeps its bytes.
26937
+ */
26938
+ let carriedUncoveredSentences;
26939
+ /**
26940
+ * The last FINAL pass's uncovered citing sentences (RV4202),
26941
+ * captured only under `coverageRepair` (the fold collects them
26942
+ * only then): what the coverage-armed round carries, beside the
26943
+ * uncapped count for the round's own log line.
26944
+ */
26945
+ let lastFinalUncovered;
26946
+ /**
26947
+ * The one semantic round's dispatch facts (RV4202), set when a
26948
+ * coverage-armed or merged round actually dispatched: the
26949
+ * strict-final refusal past a spent round names the round it
26950
+ * already consumed instead of implying none existed.
26951
+ */
26952
+ let semanticRoundSpent;
26953
+ /**
26385
26954
  * The observed price of this run's own latest post draft claim
26386
26955
  * judge pass (RV3701): the fallback sizing of the repair round's
26387
26956
  * convergence hold when the host declared no `judge.estCost`. By
@@ -26546,8 +27115,13 @@ function makeOrchestratorWorkflow(goal, opts) {
26546
27115
  ...spec.maxPoolPerPair === void 0 ? {} : { maxPoolPerPair: spec.maxPoolPerPair },
26547
27116
  ...spec.maxExcerptChars === void 0 ? {} : { maxExcerptChars: spec.maxExcerptChars },
26548
27117
  ...spec.critical === void 0 ? {} : { critical: spec.critical },
26549
- ...spec.coverageTarget === void 0 ? {} : { targetCoverageShare: spec.coverageTarget }
27118
+ ...spec.coverageTarget === void 0 ? {} : { targetCoverageShare: spec.coverageTarget },
27119
+ ...spec.coverageRepair === true ? { reportUncovered: true } : {}
26550
27120
  });
27121
+ if (stage === "final" && spec.coverageRepair === true) lastFinalUncovered = {
27122
+ sentences: fold.uncoveredSentences ?? [],
27123
+ total: fold.uncoveredSentencesTotal ?? 0
27124
+ };
26551
27125
  const runFold = spec.runFacts === true ? pairRunFactClaims(draftText, {
26552
27126
  text: `The run ${internals.runId} made ${String(factWires)} provider wire requests across ${String(poolChildren)} accepted children, with token totals ${String(factInput)} input and ${String(factOutput)} output (the run's own recorded execution facts; harness-observed, not production evidence). ${factRows.join(" ")}`,
26553
27127
  ids: factIds,
@@ -26782,6 +27356,14 @@ function makeOrchestratorWorkflow(goal, opts) {
26782
27356
  const plan = resolveCitationAuditPlan(auditSpec);
26783
27357
  const auditedHash = createHash("sha256").update(jcsSerialize(document ?? null), "utf8").digest("hex");
26784
27358
  const rows = sampleCitationRows(typeof document === "string" ? document : JSON.stringify(document ?? null), plan, auditedHash).map((row) => {
27359
+ if (plan.resolver === 2) {
27360
+ const resolved = citationUnitExcerptOf(auditSpec.resolve, row);
27361
+ return resolved === void 0 ? row : {
27362
+ ...row,
27363
+ excerpt: resolved.excerpt,
27364
+ unit: resolved.unit
27365
+ };
27366
+ }
26785
27367
  const excerpt = citationExcerptOf(auditSpec.resolve, row, plan.window);
26786
27368
  return excerpt === void 0 ? row : {
26787
27369
  ...row,
@@ -26815,7 +27397,8 @@ function makeOrchestratorWorkflow(goal, opts) {
26815
27397
  perSection,
26816
27398
  auditedHash,
26817
27399
  samplePerSection: plan.samplePerSection,
26818
- maxSampled: plan.maxSampled
27400
+ maxSampled: plan.maxSampled,
27401
+ ...plan.resolver === 2 ? { resolverVersion: 2 } : {}
26819
27402
  };
26820
27403
  const onFound = auditSpec.onFound ?? "report";
26821
27404
  if (judgeRows.length === 0) {
@@ -26826,20 +27409,26 @@ function makeOrchestratorWorkflow(goal, opts) {
26826
27409
  citationFindingsFound = mechanical;
26827
27410
  return;
26828
27411
  }
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");
27412
+ const judgePrompt = [
27413
+ "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.",
27414
+ ...plan.resolver === 2 ? ["Rows carrying a `clause` audit ONE anchor of a compound sentence: judge the excerpt against that clause, the claim this anchor was cited for, not against the sentence's other claims. The `unit` names the logical unit the excerpt covers; a truncated unit may end mid-thought, so judge what the lines DO carry."] : [],
27415
+ `ROWS: ${JSON.stringify(judgeRows.map((row) => ({
27416
+ row: row.row,
27417
+ section: row.section,
27418
+ sentence: row.sentence,
27419
+ anchor: row.anchor,
27420
+ ...row.clause === void 0 ? {} : { clause: row.clause },
27421
+ excerpt: row.excerpt,
27422
+ ...row.unit === void 0 ? {} : { unit: row.unit }
27423
+ })))}`
27424
+ ].join("\n");
26836
27425
  const auditJudgeState = { ...callingState };
26837
27426
  if (orchestratorAccount !== void 0) auditJudgeState.budgetScope = orchestratorAccount;
26838
27427
  auditJudgeState.phase = auditJudgeState.phase ?? "judge";
26839
27428
  const judgeOpts = {
26840
27429
  role: "synthesize",
26841
27430
  result: "full",
26842
- label: pass === "round" ? "citation-entailment-judge-round" : "citation-entailment-judge",
27431
+ label: pass === "round" ? `${CITATION_JUDGE_LABEL}-round` : CITATION_JUDGE_LABEL,
26843
27432
  schema: CITATION_JUDGE_SCHEMA,
26844
27433
  limits: auditSpec.judge?.limits ?? { maxTurns: 3 },
26845
27434
  ...auditSpec.judge?.model === void 0 ? {} : { model: auditSpec.judge.model },
@@ -26953,7 +27542,7 @@ function makeOrchestratorWorkflow(goal, opts) {
26953
27542
  }
26954
27543
  }, callingState.spanId);
26955
27544
  };
26956
- const runSynthesis = async (draft, stagePhase = "composition") => {
27545
+ const runSynthesis = async (draft, stagePhase = "composition", repairTrigger) => {
26957
27546
  const spec = opts?.synthesis;
26958
27547
  if (spec === void 0) return draft;
26959
27548
  await recoveryDone;
@@ -27206,6 +27795,7 @@ function makeOrchestratorWorkflow(goal, opts) {
27206
27795
  ...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)],
27207
27796
  ...opts?.claimConsistency?.onFound !== "carry" && opts?.claimConsistency?.onFound !== "repair" || claimFindingsFound === void 0 || claimFindingsFound.length === 0 ? [] : hostValidationLessons(),
27208
27797
  ...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)],
27798
+ ...carriedUncoveredSentences === void 0 || carriedUncoveredSentences.length === 0 ? [] : ["UNCOVERED CLAIMS: these citing sentences could not be verified against the settled child pool (no pool reading covers their cited spans, or the only readings restate them verbatim); for each, either ground the claim in material the pool actually read (cite spans the children cited), or drop the unverifiable citation and state only what the pool carries, and keep every other sentence byte identical. " + JSON.stringify(carriedUncoveredSentences)],
27209
27799
  ...sectionalRoundContext === void 0 ? [] : [
27210
27800
  `RETAINED FINAL: ${JSON.stringify(sectionalRoundContext.base)}`,
27211
27801
  "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.",
@@ -27312,6 +27902,7 @@ function makeOrchestratorWorkflow(goal, opts) {
27312
27902
  const heldReserveUsd = orchestratorAccount === void 0 ? 0 : internals.budget.accountView(orchestratorAccount)?.synthesisReserveUsd ?? 0;
27313
27903
  const synthesisState = { ...callingState };
27314
27904
  synthesisState.phase = synthesisState.phase ?? stagePhase;
27905
+ if (repairTrigger !== void 0) synthesisState.repairTrigger = repairTrigger;
27315
27906
  if (orchestratorAccount !== void 0) {
27316
27907
  synthesisState.budgetScope = orchestratorAccount;
27317
27908
  internals.budget.releaseSynthesisReserve(orchestratorAccount);
@@ -27463,6 +28054,12 @@ function makeOrchestratorWorkflow(goal, opts) {
27463
28054
  "handles you waited on. Read those with ONE get_settled_child_results call;",
27464
28055
  "never probe a handle with get_child_result to discover whether it settled."
27465
28056
  ] : [],
28057
+ ...validationSpec?.draftPolicy === "digest" ? [
28058
+ "Your finish({ result }) draft is a DIGEST, not prose: a compact structural map",
28059
+ "of the planned deliverable. One list row per planned section, each naming the",
28060
+ "claims it will carry and the evidence behind them (citations, child findings).",
28061
+ `Stay under ${String(400)} words; the composing invocation writes the prose from this map.`
28062
+ ] : [],
27466
28063
  ...finishValidationPromptLines(validationSpec, coordSectionalFinish ? "rejected-attempt" : void 0),
27467
28064
  ...acceptancePromptLines(opts?.acceptance)
27468
28065
  ];
@@ -27785,7 +28382,8 @@ function makeOrchestratorWorkflow(goal, opts) {
27785
28382
  hash: decision.candidateHash ?? "",
27786
28383
  chars: decision.candidateChars ?? 0,
27787
28384
  failed: decision.failed,
27788
- ...decision.candidateRef === void 0 ? {} : { ref: decision.candidateRef }
28385
+ ...decision.candidateRef === void 0 ? {} : { ref: decision.candidateRef },
28386
+ ...decision.bytesUnavailableReason === void 0 ? {} : { bytesUnavailableReason: decision.bytesUnavailableReason }
27789
28387
  }));
27790
28388
  const enrichSynthesisFailure = (thrown, snapshot) => {
27791
28389
  const passTruth = {
@@ -28057,14 +28655,141 @@ function makeOrchestratorWorkflow(goal, opts) {
28057
28655
  ...decision.children === void 0 ? {} : { acceptanceChildren: decision.children }
28058
28656
  });
28059
28657
  }
28658
+ const claimRepairArmed = (opts?.claimConsistency?.onFound ?? "report") === "repair";
28659
+ const coverageRoundArmed = opts?.claimConsistency?.coverageRepair === true;
28660
+ const mergedRoundArmed = claimRepairArmed && opts?.citationAudit?.onFound === "repair";
28661
+ const jcsHashOf = (value) => createHash("sha256").update(jcsSerialize(value ?? null), "utf8").digest("hex");
28662
+ /** One line naming what a round carried, for its death messages. */
28663
+ const describeCarried = (round) => {
28664
+ const parts = [];
28665
+ if (round.carriedClaims.length > 0) parts.push(`${String(round.carriedClaims.length)} judged contradiction${round.carriedClaims.length === 1 ? "" : "s"}`);
28666
+ if (round.carriedCitations.length > 0) parts.push(`${String(round.carriedCitations.length)} unsupported citation${round.carriedCitations.length === 1 ? "" : "s"}`);
28667
+ if (round.uncovered.length > 0) parts.push(`${String(round.uncovered.length)} uncovered citing sentence${round.uncovered.length === 1 ? "" : "s"}`);
28668
+ return parts.join(" and ");
28669
+ };
28670
+ /**
28671
+ * The ONE bounded semantic round, shared (RV4202): dispatches the
28672
+ * repair composition carrying whatever defect classes armed it
28673
+ * (the judged claim contradictions fold from the live findings,
28674
+ * the unsupported citations and the uncovered sentences ride the
28675
+ * carried state), under the same two-leg budget bargain as the
28676
+ * RV3307 round (the convergence hold funds the re-judging passes,
28677
+ * the mechanical leg funds the round's own repair turn) and the
28678
+ * same dispatch deaths, each naming everything it carried. Returns
28679
+ * the repaired candidate; the CALL SITE re-runs the judges and
28680
+ * rules on survivors, because which judges must re-rule differs by
28681
+ * mode. The historical single-armed rounds keep their own blocks
28682
+ * byte for byte.
28683
+ */
28684
+ const dispatchSemanticRound = async (round) => {
28685
+ const preRepairHash = jcsHashOf(synthesizedFinal);
28686
+ const holdScope = orchestratorAccount ?? "run";
28687
+ if (round.rejudgeHoldUsd > 0) internals.budget.commitConvergenceReserve(holdScope, round.rejudgeHoldUsd);
28688
+ const mechanicalHoldUsd = validationSpec === void 0 ? 0 : validationSpec.estRepairCostUsd ?? lastMechanicalRepairCostUsd(internals.replayer.snapshot(), (servedBy, usage) => internals.priceUsd(servedBy, usage)) ?? 0;
28689
+ if (mechanicalHoldUsd > 0) {
28690
+ internals.budget.commitRepairReserve(holdScope, mechanicalHoldUsd);
28691
+ releaseRepairLeg = () => {
28692
+ releaseRepairLeg = void 0;
28693
+ internals.budget.releaseRepairReserve(holdScope);
28694
+ };
28695
+ }
28696
+ const roundPlan = validationSpec !== void 0 && typeof synthesizedFinal === "string" ? sectionalRoundPlan(synthesizedFinal, [
28697
+ ...round.carriedClaims.map((finding) => finding.draftExcerpt),
28698
+ ...round.carriedCitations.map((finding) => finding.sentence),
28699
+ ...round.uncovered
28700
+ ]) : void 0;
28701
+ if (roundPlan !== void 0) {
28702
+ sectionalRoundContext = {
28703
+ base: synthesizedFinal,
28704
+ ...roundPlan
28705
+ };
28706
+ internals.events.emit({
28707
+ type: "log",
28708
+ level: "debug",
28709
+ msg: "orchestrator sectional round armed",
28710
+ data: {
28711
+ targets: roundPlan.targets,
28712
+ sections: roundPlan.sections.length
28713
+ }
28714
+ }, callingState.spanId);
28715
+ }
28716
+ if (round.carriedCitations.length > 0) carriedCitationFindings = round.carriedCitations;
28717
+ if (round.uncovered.length > 0) carriedUncoveredSentences = round.uncovered;
28718
+ try {
28719
+ const repaired = await runSynthesis(result.output, "repair", round.trigger);
28720
+ semanticRoundSpent = {
28721
+ trigger: round.trigger,
28722
+ preRepairHash
28723
+ };
28724
+ return repaired;
28725
+ } catch (thrown) {
28726
+ await journalSynthesisAdmissionDecline(thrown);
28727
+ const hostRejection = (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;
28728
+ const carriedLine = describeCarried(round);
28729
+ throw new FailRunError((hostRejection !== void 0 ? "the semantic repair round dispatched and its repaired candidate failed host validation " : "the semantic repair round could not dispatch ") + `(${thrown instanceof Error ? thrown.message.slice(0, 300) : String(thrown)}); ${carriedLine} stand unconsumed and a gate armed to repair must not pass silently`, { data: {
28730
+ source: round.source,
28731
+ ...round.carriedClaims.length === 0 ? {} : { claimContradictions: round.carriedClaims },
28732
+ ...round.carriedCitations.length === 0 ? {} : { citationFindings: round.carriedCitations },
28733
+ ...round.uncovered.length === 0 ? {} : { uncoveredSentences: round.uncovered },
28734
+ ...claimConsistencyMeta === void 0 ? {} : { claimConsistencyMeta },
28735
+ ...citationAuditMeta === void 0 ? {} : { citationAuditMeta },
28736
+ repairsUsed: hostRejection !== void 0 ? 1 : 0,
28737
+ roundDispatched: hostRejection !== void 0,
28738
+ preRepairHash,
28739
+ ...hostRejection === void 0 ? {} : { finishValidation: {
28740
+ ...hostRejection.callId === void 0 ? {} : { callId: hostRejection.callId },
28741
+ ...hostRejection.failed === void 0 ? {} : { failed: hostRejection.failed },
28742
+ ...hostRejection.repairsUsed === void 0 ? {} : { repairsUsed: hostRejection.repairsUsed },
28743
+ ...hostRejection.maxRepairs === void 0 ? {} : { maxRepairs: hostRejection.maxRepairs },
28744
+ ...hostRejection.candidateHash === void 0 ? {} : { candidateHash: hostRejection.candidateHash },
28745
+ ...hostRejection.candidateChars === void 0 ? {} : { candidateChars: hostRejection.candidateChars }
28746
+ } },
28747
+ ...acceptanceSnapshot
28748
+ } });
28749
+ } finally {
28750
+ carriedCitationFindings = void 0;
28751
+ carriedUncoveredSentences = void 0;
28752
+ sectionalRoundContext = void 0;
28753
+ releaseRepairLeg = void 0;
28754
+ if (mechanicalHoldUsd > 0) internals.budget.releaseRepairReserve(holdScope);
28755
+ if (round.rejudgeHoldUsd > 0) internals.budget.releaseConvergenceReserve(holdScope);
28756
+ }
28757
+ };
28758
+ /**
28759
+ * The re-judging claim pass after a shared round (RV4202): the
28760
+ * typed claim throws below the judge cannot know they fired inside
28761
+ * the round, so the round context rides the same data, exactly the
28762
+ * RV3701 wrap of the single-armed block.
28763
+ */
28764
+ const rejudgeClaimsAfterRound = async (carried) => {
28765
+ try {
28766
+ await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
28767
+ } catch (thrown) {
28768
+ if (thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) && thrown.data.source === "orchestrator_claim_consistency") throw new FailRunError(thrown.message, { data: {
28769
+ ...thrown.data,
28770
+ ...thrown.data.claimContradictions === void 0 ? { claimContradictions: carried } : {},
28771
+ roundDispatched: true,
28772
+ repairsUsed: 1,
28773
+ ...semanticRoundSpent === void 0 ? {} : { preRepairHash: semanticRoundSpent.preRepairHash }
28774
+ } });
28775
+ throw thrown;
28776
+ }
28777
+ };
28778
+ const parallelJudges = claimStage !== "draft" && opts?.claimConsistency !== void 0 && opts?.citationAudit !== void 0 && !claimRepairArmed && !coverageRoundArmed && (opts.citationAudit.onFound ?? "report") !== "repair";
28779
+ let parallelAuditRan = false;
28060
28780
  if (claimStage !== "draft") {
28061
28781
  claimConsistencyDraftMeta = claimStage === "both" ? claimConsistencyMeta : void 0;
28062
- await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
28782
+ if (parallelJudges) {
28783
+ const [claimSettled, auditSettled] = await Promise.allSettled([runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final"), runCitationAudit(synthesizedFinal, "first")]);
28784
+ parallelAuditRan = true;
28785
+ if (claimSettled.status === "rejected") throw claimSettled.reason;
28786
+ if (auditSettled.status === "rejected") throw auditSettled.reason;
28787
+ } else await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
28063
28788
  if ((opts?.claimConsistency?.onFound ?? "report") === "repair" && claimConsistencyMeta !== void 0) {
28064
28789
  claimConsistencyMeta.passes = 1;
28065
28790
  claimConsistencyMeta.semanticRepairRounds = 0;
28066
28791
  }
28067
- if ((opts?.claimConsistency?.onFound ?? "report") === "repair" && claimFindingsFound !== void 0 && claimFindingsFound.length > 0) {
28792
+ if (claimRepairArmed && !mergedRoundArmed && !coverageRoundArmed && claimFindingsFound !== void 0 && claimFindingsFound.length > 0) {
28068
28793
  const hashOfDocument = (value) => createHash("sha256").update(jcsSerialize(value ?? null), "utf8").digest("hex");
28069
28794
  const preRepairHash = hashOfDocument(synthesizedFinal);
28070
28795
  const carried = claimFindingsFound;
@@ -28096,7 +28821,7 @@ function makeOrchestratorWorkflow(goal, opts) {
28096
28821
  }, callingState.spanId);
28097
28822
  }
28098
28823
  try {
28099
- synthesizedFinal = await runSynthesis(result.output, "repair");
28824
+ synthesizedFinal = await runSynthesis(result.output, "repair", "claim");
28100
28825
  } catch (thrown) {
28101
28826
  await journalSynthesisAdmissionDecline(thrown);
28102
28827
  const hostRejection = thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) && thrown.data.source === "orchestrator_finish_validation" ? thrown.data : void 0;
@@ -28159,10 +28884,41 @@ function makeOrchestratorWorkflow(goal, opts) {
28159
28884
  ...acceptanceSnapshot
28160
28885
  } });
28161
28886
  }
28887
+ if (claimRepairArmed && !mergedRoundArmed && coverageRoundArmed) {
28888
+ const carriedClaims = claimFindingsFound ?? [];
28889
+ const firstGrade = claimConsistencyMeta?.coverage;
28890
+ const coverageDefect = (firstGrade ?? "full") !== "full";
28891
+ if (carriedClaims.length > 0 || coverageDefect) {
28892
+ synthesizedFinal = await dispatchSemanticRound({
28893
+ carriedClaims,
28894
+ carriedCitations: [],
28895
+ uncovered: coverageDefect ? lastFinalUncovered?.sentences ?? [] : [],
28896
+ trigger: carriedClaims.length > 0 && coverageDefect ? "combined" : carriedClaims.length > 0 ? "claim" : "coverage",
28897
+ rejudgeHoldUsd: opts?.claimConsistency?.judge?.estCost ?? observedFinalJudgeCostUsd ?? 0,
28898
+ source: "orchestrator_claim_consistency"
28899
+ });
28900
+ await rejudgeClaimsAfterRound(carriedClaims);
28901
+ if (claimConsistencyMeta !== void 0) {
28902
+ claimConsistencyMeta.passes = 2;
28903
+ claimConsistencyMeta.firstPassFindings = carriedClaims.length;
28904
+ if (firstGrade !== void 0) claimConsistencyMeta.firstPassCoverage = firstGrade;
28905
+ claimConsistencyMeta.semanticRepairRounds = 1;
28906
+ }
28907
+ if (claimFindingsFound !== void 0 && claimFindingsFound.length > 0) throw new FailRunError(`the claim-consistency judge still found ${String(claimFindingsFound.length)} contradiction${claimFindingsFound.length === 1 ? "" : "s"} after the bounded repair round: the repaired composition keeps contradicting the settled pool`, { data: {
28908
+ source: "orchestrator_claim_consistency",
28909
+ claimContradictions: claimFindingsFound,
28910
+ claimConsistencyMeta,
28911
+ repairsUsed: 1,
28912
+ ...semanticRoundSpent === void 0 ? {} : { preRepairHash: semanticRoundSpent.preRepairHash },
28913
+ repairedHash: jcsHashOf(synthesizedFinal),
28914
+ ...acceptanceSnapshot
28915
+ } });
28916
+ }
28917
+ }
28162
28918
  }
28163
28919
  if (opts?.citationAudit !== void 0) {
28164
28920
  const hashOfDocument = (value) => createHash("sha256").update(jcsSerialize(value ?? null), "utf8").digest("hex");
28165
- await runCitationAudit(synthesizedFinal, "first");
28921
+ if (!parallelAuditRan) await runCitationAudit(synthesizedFinal, "first");
28166
28922
  const auditOnFound = opts.citationAudit.onFound ?? "report";
28167
28923
  const unsupportedOf = () => (citationFindingsFound ?? []).filter((finding) => finding.verdict === "unsupported");
28168
28924
  const firstUnsupported = unsupportedOf();
@@ -28176,7 +28932,7 @@ function makeOrchestratorWorkflow(goal, opts) {
28176
28932
  citationAuditMeta.passes = 1;
28177
28933
  citationAuditMeta.citationRepairRounds = 0;
28178
28934
  }
28179
- if (auditOnFound === "repair" && firstUnsupported.length > 0) {
28935
+ if (auditOnFound === "repair" && !mergedRoundArmed && firstUnsupported.length > 0) {
28180
28936
  const preRepairHash = hashOfDocument(synthesizedFinal);
28181
28937
  const carried = firstUnsupported;
28182
28938
  const auditConvergenceHoldUsd = opts.citationAudit.judge?.estCost ?? 0;
@@ -28208,7 +28964,7 @@ function makeOrchestratorWorkflow(goal, opts) {
28208
28964
  }
28209
28965
  carriedCitationFindings = carried;
28210
28966
  try {
28211
- synthesizedFinal = await runSynthesis(result.output, "repair");
28967
+ synthesizedFinal = await runSynthesis(result.output, "repair", "citation");
28212
28968
  } catch (thrown) {
28213
28969
  await journalSynthesisAdmissionDecline(thrown);
28214
28970
  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;
@@ -28246,6 +29002,56 @@ function makeOrchestratorWorkflow(goal, opts) {
28246
29002
  ...acceptanceSnapshot
28247
29003
  } });
28248
29004
  }
29005
+ if (mergedRoundArmed) {
29006
+ const carriedClaims = claimFindingsFound ?? [];
29007
+ const carriedCitations = firstUnsupported;
29008
+ const firstGrade = claimConsistencyMeta?.coverage;
29009
+ const coverageDefect = coverageRoundArmed && (firstGrade ?? "full") !== "full";
29010
+ const defectClasses = (carriedClaims.length > 0 ? 1 : 0) + (carriedCitations.length > 0 ? 1 : 0) + (coverageDefect ? 1 : 0);
29011
+ if (defectClasses > 0) {
29012
+ synthesizedFinal = await dispatchSemanticRound({
29013
+ carriedClaims,
29014
+ carriedCitations,
29015
+ uncovered: coverageDefect ? lastFinalUncovered?.sentences ?? [] : [],
29016
+ trigger: defectClasses > 1 ? "combined" : carriedClaims.length > 0 ? "claim" : carriedCitations.length > 0 ? "citation" : "coverage",
29017
+ rejudgeHoldUsd: (opts?.claimConsistency?.judge?.estCost ?? observedFinalJudgeCostUsd ?? 0) + (opts.citationAudit.judge?.estCost ?? 0),
29018
+ source: carriedClaims.length > 0 || coverageDefect ? "orchestrator_claim_consistency" : "orchestrator_citation_audit"
29019
+ });
29020
+ await rejudgeClaimsAfterRound(carriedClaims);
29021
+ if (claimConsistencyMeta !== void 0) {
29022
+ claimConsistencyMeta.passes = 2;
29023
+ claimConsistencyMeta.firstPassFindings = carriedClaims.length;
29024
+ if (coverageRoundArmed && firstGrade !== void 0) claimConsistencyMeta.firstPassCoverage = firstGrade;
29025
+ claimConsistencyMeta.semanticRepairRounds = 1;
29026
+ }
29027
+ await runCitationAudit(synthesizedFinal, "round");
29028
+ if (citationAuditMeta !== void 0) {
29029
+ citationAuditMeta.passes = 2;
29030
+ citationAuditMeta.firstPassFindings = carriedCitations.length;
29031
+ citationAuditMeta.citationRepairRounds = 1;
29032
+ }
29033
+ if (claimFindingsFound !== void 0 && claimFindingsFound.length > 0) throw new FailRunError(`the claim-consistency judge still found ${String(claimFindingsFound.length)} contradiction${claimFindingsFound.length === 1 ? "" : "s"} after the bounded repair round: the repaired composition keeps contradicting the settled pool`, { data: {
29034
+ source: "orchestrator_claim_consistency",
29035
+ claimContradictions: claimFindingsFound,
29036
+ claimConsistencyMeta,
29037
+ ...citationAuditMeta === void 0 ? {} : { citationAuditMeta },
29038
+ repairsUsed: 1,
29039
+ ...semanticRoundSpent === void 0 ? {} : { preRepairHash: semanticRoundSpent.preRepairHash },
29040
+ repairedHash: hashOfDocument(synthesizedFinal),
29041
+ ...acceptanceSnapshot
29042
+ } });
29043
+ const mergedSurvivors = unsupportedOf();
29044
+ if (mergedSurvivors.length > 0) throw new FailRunError(`the citation audit still judged ${String(mergedSurvivors.length)} sampled citation${mergedSurvivors.length === 1 ? "" : "s"} UNSUPPORTED after the bounded repair round: the repaired document keeps citing lines that do not carry its claims`, { data: {
29045
+ source: "orchestrator_citation_audit",
29046
+ citationFindings: citationFindingsFound,
29047
+ citationAuditMeta,
29048
+ repairsUsed: 1,
29049
+ ...semanticRoundSpent === void 0 ? {} : { preRepairHash: semanticRoundSpent.preRepairHash },
29050
+ repairedHash: hashOfDocument(synthesizedFinal),
29051
+ ...acceptanceSnapshot
29052
+ } });
29053
+ }
29054
+ }
28249
29055
  }
28250
29056
  const envelopeSchemaRecovered = (result.schemaRecoveredTerminalExchanges ?? 0) + synthesisSchemaRecoveredExchanges;
28251
29057
  const deliverable = deliverableVerdict(synthesizedFinal);
@@ -28274,36 +29080,95 @@ function makeOrchestratorWorkflow(goal, opts) {
28274
29080
  if (opts?.claimConsistency?.coveragePolicy === "strict-final") {
28275
29081
  const grade = claimConsistencyMeta?.coverage ?? "not-judged";
28276
29082
  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: {
29083
+ const acceptanceWaiver = opts?.semanticAcceptance?.waiver;
29084
+ const pinnedJudgedHash = typeof acceptanceWaiver === "object" ? acceptanceWaiver.judgedHash : void 0;
29085
+ const priorWaiveDecision = internals.replayer.snapshot().find((entry) => {
29086
+ if (entry.kind !== "decision" || entry.scope !== callingState.scope) return false;
29087
+ const value = entry.value;
29088
+ if (value?.decisionType !== "claim_coverage_waived") return false;
29089
+ if (pinnedJudgedHash !== void 0) return value.judgedHash === pinnedJudgedHash && value.judgedHash === claimConsistencyMeta?.judgedHash;
29090
+ return value.judgedHash === void 0 || value.judgedHash === claimConsistencyMeta?.judgedHash;
29091
+ });
29092
+ if (acceptanceWaiver === "forbid") throw new FailRunError(`semanticAcceptance.waiver 'forbid': the final coverage grade is '${grade}', not 'full', and the declared acceptance admits no waiver` + (priorWaiveDecision === void 0 ? "" : `; a journaled claim_coverage_waived decision (seq ${String(priorWaiveDecision.seq)}) exists under a config that forbids waivers, which is a config/journal mismatch, not an authority`) + "; raise the coverage (pairs, targets, critical anchors) or ship a clean document", { data: {
28280
29093
  source: "orchestrator_claim_consistency",
28281
29094
  coveragePolicy: "strict-final",
28282
29095
  coverage: grade,
28283
- ...waiverSpec === void 0 ? {} : { waiverExpiredAt: waiverSpec.expiresAt ?? null },
29096
+ semanticAcceptanceWaiver: "forbid",
29097
+ ...priorWaiveDecision === void 0 ? {} : { conflictingWaiveDecisionRef: priorWaiveDecision.seq },
29098
+ ...semanticRoundSpent === void 0 ? {} : {
29099
+ repairsUsed: 1,
29100
+ roundTrigger: semanticRoundSpent.trigger,
29101
+ preRepairHash: semanticRoundSpent.preRepairHash
29102
+ },
28284
29103
  ...claimConsistencyMeta === void 0 ? {} : { claimConsistencyMeta }
28285
29104
  } });
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
- });
29105
+ if (priorWaiveDecision !== void 0) {
29106
+ const frozen = priorWaiveDecision.value;
29107
+ claimCoverageWaiver = {
29108
+ principal: frozen.principal,
29109
+ reason: frozen.reason,
29110
+ ...frozen.expiresAt === void 0 ? {} : { expiresAt: frozen.expiresAt },
29111
+ coverage: frozen.coverage
29112
+ };
29113
+ } else {
29114
+ const waiverSpec = opts.claimConsistency.waiver;
29115
+ const expired = waiverSpec?.expiresAt !== void 0 && Date.parse(waiverSpec.expiresAt) < internals.now();
29116
+ const pinMismatch = pinnedJudgedHash !== void 0 && claimConsistencyMeta?.judgedHash !== pinnedJudgedHash;
29117
+ if (waiverSpec === void 0 || expired || pinMismatch) throw new FailRunError(`claimConsistency.coveragePolicy 'strict-final': the final coverage grade is '${grade}', not 'full', and ` + (waiverSpec === void 0 ? "no waiver is declared" : expired ? `the declared waiver expired at ${String(waiverSpec.expiresAt)}` : `the declared waiver is pinned to judgedHash ${String(pinnedJudgedHash)} and this run judged ${String(claimConsistencyMeta?.judgedHash)}, a different document`) + "; raise the coverage (pairs, targets, critical anchors) or record a waiver naming who accepts the gap and why", { data: {
29118
+ source: "orchestrator_claim_consistency",
29119
+ coveragePolicy: "strict-final",
29120
+ coverage: grade,
29121
+ ...waiverSpec === void 0 || !expired ? {} : { waiverExpiredAt: waiverSpec.expiresAt ?? null },
29122
+ ...pinMismatch ? {
29123
+ waiverPinnedHash: pinnedJudgedHash,
29124
+ ...claimConsistencyMeta?.judgedHash === void 0 ? {} : { judgedHash: claimConsistencyMeta.judgedHash }
29125
+ } : {},
29126
+ ...semanticRoundSpent === void 0 ? {} : {
29127
+ repairsUsed: 1,
29128
+ roundTrigger: semanticRoundSpent.trigger,
29129
+ preRepairHash: semanticRoundSpent.preRepairHash
29130
+ },
29131
+ ...claimConsistencyMeta === void 0 ? {} : { claimConsistencyMeta }
29132
+ } });
29133
+ claimCoverageWaiver = {
29134
+ principal: waiverSpec.principal,
29135
+ reason: waiverSpec.reason,
29136
+ ...waiverSpec.expiresAt === void 0 ? {} : { expiresAt: waiverSpec.expiresAt },
29137
+ coverage: grade
29138
+ };
29139
+ await internals.replayer.appendSinglePhase({
29140
+ scope: callingState.scope,
29141
+ key: deriverV2.deriveKey({ kind: "claim-coverage-waived" }),
29142
+ kind: "decision",
29143
+ status: "ok",
29144
+ spanId: internals.spans.mint(callingState.spanId),
29145
+ site: "orchestrator-claim-coverage",
29146
+ value: {
29147
+ decisionType: "claim_coverage_waived",
29148
+ ...claimCoverageWaiver,
29149
+ ...claimConsistencyMeta?.judgedHash === void 0 ? {} : { judgedHash: claimConsistencyMeta.judgedHash }
29150
+ }
29151
+ });
29152
+ }
28305
29153
  }
28306
29154
  }
29155
+ if (opts?.semanticAcceptance !== void 0) {
29156
+ const shippedHash = draftToFinal?.finalHash ?? jcsHashOf(synthesizedFinal);
29157
+ const staleClaim = claimConsistencyMeta !== void 0 && claimConsistencyMeta.judgedHash !== shippedHash;
29158
+ const staleAudit = citationAuditMeta !== void 0 && citationAuditMeta.auditedHash !== shippedHash;
29159
+ if (staleClaim || staleAudit) throw new FailRunError("semanticAcceptance invariant violated: a terminal verdict describes a document other than the one shipping (" + (staleClaim ? `claim judgedHash ${String(claimConsistencyMeta?.judgedHash)}` : `audit auditedHash ${String(citationAuditMeta?.auditedHash)}`) + ` against shipped ${shippedHash}); this is an engine invariant, not a host error`, { data: {
29160
+ source: "orchestrator_claim_consistency",
29161
+ shippedHash,
29162
+ ...claimConsistencyMeta === void 0 ? {} : { judgedHash: claimConsistencyMeta.judgedHash },
29163
+ ...citationAuditMeta === void 0 ? {} : { auditedHash: citationAuditMeta.auditedHash }
29164
+ } });
29165
+ }
29166
+ const semanticTerminalVerdict = opts?.claimConsistency !== void 0 || opts?.citationAudit !== void 0 ? semanticTerminalVerdictOf({
29167
+ ...claimConsistencyMeta === void 0 ? {} : { claimConsistencyMeta },
29168
+ ...citationAuditMeta === void 0 ? {} : { citationAuditMeta },
29169
+ ...claimCoverageWaiver === void 0 ? {} : { claimCoverageWaiver },
29170
+ ...draftToFinal === void 0 ? {} : { draftToFinal }
29171
+ }) : void 0;
28307
29172
  return {
28308
29173
  result: synthesizedFinal,
28309
29174
  completion: decision.completion,
@@ -28318,6 +29183,7 @@ function makeOrchestratorWorkflow(goal, opts) {
28318
29183
  ...citationFindingsFound === void 0 ? {} : { citationFindings: citationFindingsFound },
28319
29184
  citationAuditMeta
28320
29185
  },
29186
+ ...semanticTerminalVerdict === void 0 ? {} : { semanticTerminalVerdict },
28321
29187
  childStatusCounts: decision.childStatusCounts,
28322
29188
  degradedReasons: decision.degradedReasons,
28323
29189
  ...decision.salvagedPartialChildren === void 0 ? {} : { salvagedPartialChildren: decision.salvagedPartialChildren },
@@ -30030,17 +30896,25 @@ function parseDeadlineAt(value) {
30030
30896
  const SCOPE_FIELDS = [
30031
30897
  "tenant",
30032
30898
  "account",
30033
- "project"
30899
+ "project",
30900
+ "legalDomain",
30901
+ "region",
30902
+ "providerAccount"
30034
30903
  ];
30035
30904
  /**
30036
30905
  * Validates and copies a declared scope (RV4007): own properties only
30037
30906
  * (the RV1205 doctrine: a prototype member must never resolve),
30038
30907
  * non-empty strings of at most 256 chars, at least one field, and the
30039
30908
  * copy is what gets recorded, so later host mutation of the passed
30040
- * object cannot move the recorded identity.
30909
+ * object cannot move the recorded identity. Under
30910
+ * `policy.unknown: 'reject'` (RV4205) an own enumerable field outside
30911
+ * the named dimensions refuses typed by name instead of dropping.
30041
30912
  */
30042
- function normalizeExecutionScope(value, site) {
30913
+ function normalizeExecutionScope(value, site, policy) {
30043
30914
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`${site} must be an object; got ${JSON.stringify(value)}`);
30915
+ if (policy?.unknown === "reject") {
30916
+ for (const key of Object.keys(value)) if (!SCOPE_FIELDS.includes(key)) throw new ConfigError(`${site}.${key} is not a scope dimension (scopePolicy.unknown 'reject'): the named dimensions are ${SCOPE_FIELDS.join(", ")}; a field the engine cannot record is a field nothing downstream can bind`);
30917
+ }
30044
30918
  const copy = {};
30045
30919
  for (const field of SCOPE_FIELDS) {
30046
30920
  if (!Object.hasOwn(value, field)) continue;
@@ -30048,13 +30922,23 @@ function normalizeExecutionScope(value, site) {
30048
30922
  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
30923
  copy[field] = declared;
30050
30924
  }
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`);
30925
+ if (Object.keys(copy).length === 0) throw new ConfigError(`${site} must declare at least one of ${SCOPE_FIELDS.join(", ")}; an empty scope records nothing and asserts nothing`);
30052
30926
  return copy;
30053
30927
  }
30054
30928
  /** The canonical identity string of a scope (RV4007): JCS bytes, total and deterministic. */
30055
30929
  function executionScopeKey(scope) {
30056
30930
  return jcsSerialize(scope);
30057
30931
  }
30932
+ /**
30933
+ * The canonical digest of a scope (RV4205): sha256 over the JCS bytes
30934
+ * of the NORMALIZED scope, a fixed-length identity for causal records
30935
+ * (the genesis decision, the invoice header) and external joins, so a
30936
+ * FinOps pipeline correlates runs by one column instead of comparing
30937
+ * structured objects field by field.
30938
+ */
30939
+ function executionScopeDigest(scope) {
30940
+ return createHash("sha256").update(executionScopeKey(scope), "utf8").digest("hex");
30941
+ }
30058
30942
  /** Validates a declared config fingerprint (RV3210): a non-empty string of at most 512 chars. */
30059
30943
  function requireConfigFingerprint(value, site) {
30060
30944
  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)));
@@ -30171,6 +31055,8 @@ function liftRunCompletion(candidate) {
30171
31055
  }
30172
31056
  const metaCandidate = candidate.claimConsistencyMeta;
30173
31057
  if (typeof metaCandidate === "object" && metaCandidate !== null && !Array.isArray(metaCandidate)) lifted.claimConsistencyMeta = { ...metaCandidate };
31058
+ const verdictCandidate = candidate.semanticTerminalVerdict;
31059
+ if (typeof verdictCandidate === "object" && verdictCandidate !== null && !Array.isArray(verdictCandidate)) lifted.semanticTerminalVerdict = { ...verdictCandidate };
30174
31060
  const findingsCandidate = candidate.claimContradictions;
30175
31061
  if (Array.isArray(findingsCandidate) && findingsCandidate.every((row) => typeof row === "object" && row !== null && !Array.isArray(row) && typeof row.reason === "string")) lifted.claimContradictions = findingsCandidate.map((row) => ({ ...row }));
30176
31062
  const skippedCandidate = candidate.synthesisSkipped;
@@ -30347,6 +31233,7 @@ function createEngine(options) {
30347
31233
  const quotaRuntime = options.quota === void 0 ? void 0 : {
30348
31234
  limiter: options.quota.limiter,
30349
31235
  ...options.quota.tenant === void 0 ? {} : { tenant: options.quota.tenant },
31236
+ ...options.quota.tenantFrom === void 0 ? {} : { tenantFrom: options.quota.tenantFrom },
30350
31237
  onLimiterError: options.quota.onLimiterError ?? "deny",
30351
31238
  reserveContinuations: options.quota.reserveContinuations ?? false,
30352
31239
  maxDenials: options.quota.maxDenials ?? 8,
@@ -30376,7 +31263,8 @@ function createEngine(options) {
30376
31263
  if (opts?.clampTurnToExposure !== void 0 && typeof opts.clampTurnToExposure !== "boolean") throw new ConfigError("RunOptions.clampTurnToExposure must be a boolean; got " + JSON.stringify(opts.clampTurnToExposure));
30377
31264
  if (opts?.strictPricing !== void 0 && typeof opts.strictPricing !== "boolean" && (typeof opts.strictPricing !== "object" || opts.strictPricing === null || Array.isArray(opts.strictPricing))) throw new ConfigError("RunOptions.strictPricing must be a boolean or an options object; got " + JSON.stringify(opts.strictPricing));
30378
31265
  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");
31266
+ if (opts?.scopePolicy !== void 0 && opts.scopePolicy.unknown !== void 0 && opts.scopePolicy.unknown !== "drop" && opts.scopePolicy.unknown !== "reject") throw new ConfigError("RunOptions.scopePolicy.unknown must be 'drop' or 'reject'; got " + JSON.stringify(opts.scopePolicy.unknown));
31267
+ const declaredScope = opts?.scope === void 0 ? void 0 : normalizeExecutionScope(opts.scope, "RunOptions.scope", opts.scopePolicy);
30380
31268
  if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
30381
31269
  const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
30382
31270
  const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
@@ -30540,6 +31428,7 @@ function createEngine(options) {
30540
31428
  ...defaults.toolsets === void 0 ? {} : { toolsets: defaults.toolsets },
30541
31429
  ...defaults.gates === void 0 ? {} : { gates: defaults.gates },
30542
31430
  ...defaults.countTokens === void 0 ? {} : { countTokens: defaults.countTokens },
31431
+ ...defaults.requireToolsetAttestation === void 0 ? {} : { requireToolsetAttestation: defaults.requireToolsetAttestation },
30543
31432
  ...defaults.cache === void 0 ? {} : { cache: defaults.cache },
30544
31433
  ...defaults.billingReceipts === void 0 ? {} : { billingReceipts: defaults.billingReceipts }
30545
31434
  },
@@ -30565,6 +31454,7 @@ function createEngine(options) {
30565
31454
  runSignal: controller.signal,
30566
31455
  ...defaults.isolation === void 0 ? {} : { isolation: defaults.isolation },
30567
31456
  ...options.executors === void 0 ? {} : { executors: options.executors },
31457
+ ...executionScope === void 0 ? {} : { executionScope },
30568
31458
  ...execKey === void 0 ? {} : { execKey },
30569
31459
  ...options.onEscalation === void 0 ? {} : { onEscalation: options.onEscalation },
30570
31460
  external,
@@ -30698,7 +31588,8 @@ function createEngine(options) {
30698
31588
  site: "execution-scope",
30699
31589
  value: {
30700
31590
  decisionType: "execution_scope",
30701
- scope: executionScope
31591
+ scope: executionScope,
31592
+ scopeDigest: executionScopeDigest(executionScope)
30702
31593
  }
30703
31594
  });
30704
31595
  if (resumeCtx?.acknowledgedOpenWireIntents !== void 0 && resumeCtx.acknowledgedOpenWireIntents > 0 && resumeCtx.strict !== true) await replayer.appendSinglePhase({
@@ -30848,6 +31739,7 @@ function createEngine(options) {
30848
31739
  if (lifted.acceptanceChildren !== void 0) outcomeFacts.acceptanceChildren = lifted.acceptanceChildren;
30849
31740
  if (lifted.semanticPasses !== void 0) outcomeFacts.semanticPasses = lifted.semanticPasses;
30850
31741
  if (lifted.claimConsistencyMeta !== void 0) outcomeFacts.claimConsistencyMeta = lifted.claimConsistencyMeta;
31742
+ if (lifted.semanticTerminalVerdict !== void 0) outcomeFacts.semanticTerminalVerdict = lifted.semanticTerminalVerdict;
30851
31743
  if (lifted.claimContradictions !== void 0) outcomeFacts.claimContradictions = lifted.claimContradictions;
30852
31744
  if (lifted.synthesisSkipped !== void 0) outcomeFacts.synthesisSkipped = lifted.synthesisSkipped;
30853
31745
  if (lifted.deliverableAccepted !== void 0) outcomeFacts.deliverableAccepted = lifted.deliverableAccepted;
@@ -31292,16 +32184,139 @@ function createEngine(options) {
31292
32184
  * no strategy enum and no behavioral branch; a host that wants the
31293
32185
  * posture applies the compiled options like any others. The floor
31294
32186
  * 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;
32187
+ * OrchestrateOptions, and since RV4101 it also walks the
32188
+ * CONSTRUCTIONS those options reach (adapters, tool sources in named
32189
+ * toolsets and profiles). A construction exposing
32190
+ * `describeRegulatedPosture()` has its posture judged by field name
32191
+ * (an MCP source's drift must be 'refuse' with every discovery bound
32192
+ * declared; the AI SDK bridge must keep providerExecutedTools
32193
+ * 'deny'), the sorted descriptors enter the hashed map under
32194
+ * `construction`, and constructions exposing nothing are COUNTED
32195
+ * there as `unrecognized`, so the hash names its own blind spot
32196
+ * instead of implying totality (the RV4009 rule "a hash must not
32197
+ * imply what it cannot verify", now with the verifiable part
32198
+ * verified). The between-compile-and-use window is held as well
32199
+ * (RV4102): the compiled options carry re-asserting wrappers whose
32200
+ * risk seams re-judge the descriptor on every use, and the
32201
+ * cross-process half was always held by the RV3210 fingerprint
32202
+ * assertion.
32203
+ */
32204
+ const REGULATED_VERSION = 3;
31302
32205
  function refuse(field, requirement) {
31303
32206
  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
32207
  }
32208
+ /**
32209
+ * Judges one construction's descriptor against the floor (RV4101) and
32210
+ * returns the normalized shape that enters the hashed posture map.
32211
+ * Shared by the compile walk and the use-time re-assertion (RV4102),
32212
+ * so a posture that loosens AFTER compile refuses with the same
32213
+ * field-named error it would have refused with at compile time.
32214
+ */
32215
+ function judgeDescriptor(raw) {
32216
+ const descriptor = raw;
32217
+ if (descriptor === null || typeof descriptor !== "object" || descriptor.regulatedPosture !== 1 || typeof descriptor.name !== "string" || descriptor.name === "") refuse("construction", "exposes describeRegulatedPosture() with an unrecognized shape (need regulatedPosture: 1, a non-empty string name, and a known kind)");
32218
+ if (descriptor.kind === "mcp-source") {
32219
+ const mcpPosture = descriptor;
32220
+ if (mcpPosture.drift !== "refuse") refuse(`construction['${descriptor.name}'].drift`, "must be 'refuse' (RV1516): under a rekey posture a listChanged notification imports a changed tool list beneath the regulated run");
32221
+ const bounds = mcpPosture.bounds;
32222
+ if (bounds === void 0 || bounds.declared !== true) refuse(`construction['${descriptor.name}'].bounds`, "must declare every discovery bound (maxTools, maxPages, maxSchemaBytes, timeouts.discoveryMs; RV1808): an unbounded sweep against a remote registry is an availability decision someone should have made on purpose");
32223
+ return {
32224
+ regulatedPosture: 1,
32225
+ kind: "mcp-source",
32226
+ name: descriptor.name,
32227
+ drift: "refuse",
32228
+ bounds: {
32229
+ declared: true,
32230
+ ...typeof bounds.maxTools === "number" ? { maxTools: bounds.maxTools } : {},
32231
+ ...typeof bounds.maxPages === "number" ? { maxPages: bounds.maxPages } : {},
32232
+ ...typeof bounds.maxSchemaBytes === "number" ? { maxSchemaBytes: bounds.maxSchemaBytes } : {},
32233
+ ...typeof bounds.discoveryMs === "number" ? { discoveryMs: bounds.discoveryMs } : {}
32234
+ }
32235
+ };
32236
+ }
32237
+ if (descriptor.kind === "ai-sdk-bridge") {
32238
+ if (descriptor.providerExecutedTools !== "deny") refuse(`construction['${descriptor.name}'].providerExecutedTools`, "must be 'deny': a provider-executed tool runs outside the permission chain and the journal");
32239
+ return {
32240
+ regulatedPosture: 1,
32241
+ kind: "ai-sdk-bridge",
32242
+ name: descriptor.name,
32243
+ providerExecutedTools: "deny"
32244
+ };
32245
+ }
32246
+ if (descriptor.kind === "model-adapter") {
32247
+ const adapterPosture = descriptor;
32248
+ if (adapterPosture.transport !== "official" && adapterPosture.transport !== "custom-base-url" && adapterPosture.transport !== "preconstructed-client") refuse(`construction['${descriptor.name}'].transport`, "must be 'official', 'custom-base-url' or 'preconstructed-client' (RV4204)");
32249
+ if (adapterPosture.transport === "custom-base-url" && (typeof adapterPosture.baseUrlOrigin !== "string" || adapterPosture.baseUrlOrigin === "")) refuse(`construction['${descriptor.name}'].baseUrlOrigin`, "must name the override's origin under 'custom-base-url' (RV4204): an egress the hash cannot pin is an egress nobody attested");
32250
+ return {
32251
+ regulatedPosture: 1,
32252
+ kind: "model-adapter",
32253
+ name: descriptor.name,
32254
+ transport: adapterPosture.transport,
32255
+ ...adapterPosture.transport === "custom-base-url" ? { baseUrlOrigin: adapterPosture.baseUrlOrigin } : {},
32256
+ ...adapterPosture.capsBound === void 0 ? {} : { capsBound: {
32257
+ declared: adapterPosture.capsBound.declared === true,
32258
+ ...typeof adapterPosture.capsBound.maxPages === "number" ? { maxPages: adapterPosture.capsBound.maxPages } : {}
32259
+ } }
32260
+ };
32261
+ }
32262
+ if (descriptor.kind === "tool-executor") {
32263
+ const executorPosture = descriptor;
32264
+ if (executorPosture.ledger !== true) refuse(`construction['${descriptor.name}'].ledger`, "must be armed (RV4204): an effect no ledger records is an effect nobody can reconcile; construct the executor with a ToolEffectLedger");
32265
+ const bounds = executorPosture.bounds;
32266
+ if (bounds === void 0 || typeof bounds.timeoutMs !== "number" || typeof bounds.maxOutputBytes !== "number") refuse(`construction['${descriptor.name}'].bounds`, "must carry the resolved timeoutMs and maxOutputBytes ceilings (RV4204)");
32267
+ const isolation = executorPosture.isolation;
32268
+ if (isolation === void 0 || isolation.flavor !== "subprocess" && isolation.flavor !== "container") refuse(`construction['${descriptor.name}'].isolation`, "must name its flavor, 'subprocess' or 'container' (RV4204)");
32269
+ const allowEnv = Array.isArray(executorPosture.allowEnv) ? executorPosture.allowEnv.filter((entry) => typeof entry === "string") : [];
32270
+ return {
32271
+ regulatedPosture: 1,
32272
+ kind: "tool-executor",
32273
+ name: descriptor.name,
32274
+ ledger: true,
32275
+ allowEnv,
32276
+ bounds: {
32277
+ timeoutMs: bounds.timeoutMs,
32278
+ maxOutputBytes: bounds.maxOutputBytes
32279
+ },
32280
+ isolation: isolation.flavor === "subprocess" ? {
32281
+ flavor: "subprocess",
32282
+ sandboxed: isolation.sandboxed === true
32283
+ } : {
32284
+ flavor: "container",
32285
+ network: String(isolation.network),
32286
+ readOnlyRoot: isolation.readOnlyRoot === true
32287
+ }
32288
+ };
32289
+ }
32290
+ refuse(`construction['${descriptor.name}']`, `attests an unrecognized kind '${String(descriptor.kind)}'; this floor can judge 'mcp-source', 'ai-sdk-bridge', 'model-adapter' and 'tool-executor'`);
32291
+ }
32292
+ /**
32293
+ * The use-time re-assertion (RV4102, the RV1608 template). The
32294
+ * descriptor is a snapshot, and the window between compile and use is
32295
+ * where a construction mutated in-process could walk a moved posture
32296
+ * beneath the hash. The compiled options therefore carry this proxy
32297
+ * in the original's place: every use of the risk seam (`tools` on a
32298
+ * source, `stream` on an adapter) re-reads and re-judges the
32299
+ * descriptor first. A loosening refuses with the compile-time
32300
+ * field-named error; any other movement (a rename, a bound change, a
32301
+ * vanished descriptor) refuses naming the drift. Everything else
32302
+ * passes through untouched, so `close()`, `caps()`, and identity
32303
+ * fields behave exactly as before. The cross-process half of the
32304
+ * window needs no proxy: a mutated construction compiles to a
32305
+ * different profile hash, and the RV3210 resume assertion refuses it.
32306
+ */
32307
+ function wrapReasserting(construction, frozen) {
32308
+ const guard = (seam, original) => (...args) => {
32309
+ const probe = construction.describeRegulatedPosture;
32310
+ const fresh = typeof probe === "function" ? jcsSerialize(judgeDescriptor(probe.call(construction))) : void 0;
32311
+ if (fresh !== frozen) throw new ConfigError(`compileRegulatedProfile: the construction posture moved between compile time and ${seam}() (RV4102): the compiled profile licensed ${frozen}, the construction now reports ${fresh ?? "no describeRegulatedPosture() at all"}. Recompile the profile deliberately instead of mutating a construction beneath it.`);
32312
+ return original.apply(construction, args);
32313
+ };
32314
+ return new Proxy(construction, { get(target, prop) {
32315
+ const value = Reflect.get(target, prop, target);
32316
+ if ((prop === "tools" || prop === "stream" || prop === "run") && typeof value === "function") return guard(String(prop), value);
32317
+ return value;
32318
+ } });
32319
+ }
31305
32320
  function compileRegulatedProfile(input) {
31306
32321
  const engine = {
31307
32322
  ...input.engine,
@@ -31324,44 +32339,164 @@ function compileRegulatedProfile(input) {
31324
32339
  for (const [name, profile] of Object.entries(defaults.profiles ?? {})) {
31325
32340
  if (profile.permissions?.strictApprovals === false) refuse(`defaults.profiles.${name}.permissions.strictApprovals`, "must not be false");
31326
32341
  if (profile.tools !== void 0 && profile.toolsetAttestation === void 0) refuse(`defaults.profiles.${name}`, "declares tools without a toolsetAttestation (pin the resolved hashes)");
32342
+ if (profile.toolsetAttestation !== void 0 && profile.toolsetAttestation.authorityHash === void 0) refuse(`defaults.profiles.${name}.toolsetAttestation`, "is a legacy contract-only pin (RV4204): authority drift (risk, needsApproval, executor, executorSpec) passes it silently; re-record the pin with attestToolset() so authorityHash rides it");
32343
+ }
32344
+ if (defaults.requireToolsetAttestation === false) refuse("defaults.requireToolsetAttestation", "must not be false (RV4204): a regulated spawn executes only pinned toolsets");
32345
+ defaults.requireToolsetAttestation = true;
32346
+ const walked = /* @__PURE__ */ new Set();
32347
+ const attested = [];
32348
+ const reasserted = /* @__PURE__ */ new Map();
32349
+ let unrecognized = 0;
32350
+ const unrecognizedNames = [];
32351
+ const visit = (construction) => {
32352
+ if (construction === null || typeof construction !== "object" || walked.has(construction)) return;
32353
+ walked.add(construction);
32354
+ const probe = construction.describeRegulatedPosture;
32355
+ if (typeof probe !== "function") {
32356
+ unrecognized += 1;
32357
+ const id = construction.id;
32358
+ unrecognizedNames.push(typeof id === "string" && id !== "" ? id : construction.constructor?.name ?? "anonymous");
32359
+ return;
32360
+ }
32361
+ const judged = judgeDescriptor(probe.call(construction));
32362
+ attested.push(judged);
32363
+ reasserted.set(construction, wrapReasserting(construction, jcsSerialize(judged)));
32364
+ };
32365
+ for (const adapter of engine.adapters ?? []) visit(adapter);
32366
+ const visitTools = (tools) => {
32367
+ for (const entry of tools ?? []) {
32368
+ if (typeof entry === "string" || entry.kind === "tool") continue;
32369
+ visit(entry);
32370
+ }
32371
+ };
32372
+ for (const toolset of Object.values(defaults.toolsets ?? {})) visitTools(toolset);
32373
+ for (const profile of Object.values(defaults.profiles ?? {})) visitTools(profile.tools);
32374
+ for (const executor of Object.values(engine.executors ?? {})) visit(executor);
32375
+ visit(engine.runners?.sandbox);
32376
+ if (input.construction === "require-recognized" && unrecognized > 0) refuse("construction", `must expose describeRegulatedPosture() on every construction under the 'require-recognized' floor (RV4204); ${String(unrecognized)} attested nothing: ` + unrecognizedNames.slice(0, 8).join(", "));
32377
+ const swap = (value) => typeof value === "object" && value !== null && reasserted.has(value) ? reasserted.get(value) : value;
32378
+ if (reasserted.size > 0) {
32379
+ if (engine.adapters !== void 0) engine.adapters = engine.adapters.map(swap);
32380
+ if (defaults.toolsets !== void 0) defaults.toolsets = Object.fromEntries(Object.entries(defaults.toolsets).map(([name, tools]) => [name, tools.map(swap)]));
32381
+ if (defaults.profiles !== void 0) defaults.profiles = Object.fromEntries(Object.entries(defaults.profiles).map(([name, profile]) => [name, profile.tools === void 0 ? profile : {
32382
+ ...profile,
32383
+ tools: profile.tools.map(swap)
32384
+ }]));
32385
+ if (engine.executors !== void 0) engine.executors = Object.fromEntries(Object.entries(engine.executors).map(([tag, executor]) => [tag, swap(executor)]));
32386
+ if (engine.runners?.sandbox !== void 0) engine.runners = {
32387
+ ...engine.runners,
32388
+ sandbox: swap(engine.runners.sandbox)
32389
+ };
31327
32390
  }
31328
- if (typeof run.budgetUsd !== "number") refuse("run.budgetUsd", "must declare a USD ceiling");
32391
+ const postureKeyOf = (entry) => `${entry.kind} ${entry.name}`;
32392
+ attested.sort((a, b) => postureKeyOf(a) < postureKeyOf(b) ? -1 : postureKeyOf(a) > postureKeyOf(b) ? 1 : 0);
32393
+ if (typeof run.budgetUsd !== "number" || !Number.isFinite(run.budgetUsd) || run.budgetUsd <= 0) refuse("run.budgetUsd", "must declare a positive finite USD ceiling (RV4107): NaN and Infinity are not ceilings, and a non-positive one is a run that cannot pay for its own floor");
31329
32394
  if (run.strictPricing === false) refuse("run.strictPricing", "must not be false");
31330
32395
  run.strictPricing = run.strictPricing ?? true;
31331
32396
  if (run.budgetPolicy !== void 0 && run.budgetPolicy !== "immutable-lifetime") refuse("run.budgetPolicy", "must be 'immutable-lifetime' (RV3902)");
31332
32397
  run.budgetPolicy = "immutable-lifetime";
31333
32398
  if (run.scope === void 0) refuse("run.scope", "must name the execution scope (RV4007): a regulated run has an owner");
32399
+ if (run.scopePolicy?.unknown === "drop") refuse("run.scopePolicy.unknown", "must be 'reject' (RV4205): a silently dropped dimension is a dimension nothing downstream recorded or bound");
32400
+ run.scopePolicy = { unknown: "reject" };
32401
+ run.scope = normalizeExecutionScope(run.scope, "compileRegulatedProfile run.scope", run.scopePolicy);
31334
32402
  if (orchestrate !== void 0) {
31335
32403
  const budget = { ...orchestrate.budget ?? {} };
31336
32404
  if (budget.acceptanceReserve !== void 0 && budget.acceptanceReserve !== "require") refuse("orchestrate.budget.acceptanceReserve", "must be 'require' (RV3907/RV4001)");
31337
32405
  budget.acceptanceReserve = "require";
31338
32406
  orchestrate.budget = budget;
31339
32407
  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");
32408
+ if (typeof orchestrate.citationAudit.resolve !== "function") refuse("orchestrate.citationAudit.resolve", "must be the host snapshot resolver function (RV4004/RV4107)");
32409
+ if (orchestrate.claimConsistency === void 0) refuse("orchestrate.claimConsistency", "must be declared with stage 'final' or 'both' (RV4103): the claim machinery is the regulated posture, and omitting it entirely is the deepest loosening");
31340
32410
  if (orchestrate.claimConsistency !== void 0) {
31341
32411
  const claim = { ...orchestrate.claimConsistency };
31342
32412
  if (claim.coveragePolicy !== void 0 && claim.coveragePolicy !== "strict-final") refuse("orchestrate.claimConsistency.coveragePolicy", "must be 'strict-final' (RV4003)");
31343
32413
  if ((claim.stage ?? "draft") === "draft") refuse("orchestrate.claimConsistency.stage", "must be 'final' or 'both': the shipped document is what the pass must grade");
31344
32414
  claim.coveragePolicy = "strict-final";
32415
+ if (claim.onFound === "report" || claim.onFound === "carry") refuse("orchestrate.claimConsistency.onFound", "must be 'repair' or 'fail' (RV4201): the observing postures let a run settle accepted over what its own judge found");
32416
+ claim.onFound = claim.onFound ?? "fail";
32417
+ if (claim.coverageTarget !== void 0 && claim.coverageTarget !== 1) refuse("orchestrate.claimConsistency.coverageTarget", "must be 1 or absent (RV4201): the regulated acceptance requires the 'full' grade, and a pass sized to cover less than everything can never reach it");
32418
+ if (claim.onFound === "repair") {
32419
+ if (claim.coverageRepair === false) refuse("orchestrate.claimConsistency.coverageRepair", "must not be false beside onFound 'repair' (RV4201/RV4202): the one bounded round serves every armed defect class, coverage included");
32420
+ claim.coverageRepair = true;
32421
+ }
31345
32422
  orchestrate.claimConsistency = claim;
32423
+ const auditSpec = { ...orchestrate.citationAudit };
32424
+ if (auditSpec.onFound === "report") refuse("orchestrate.citationAudit.onFound", "must be 'repair' or 'fail' (RV4201): 'report' let the sixth experiment settle accepted over five unsupported citations");
32425
+ auditSpec.onFound = auditSpec.onFound ?? "fail";
32426
+ orchestrate.citationAudit = auditSpec;
32427
+ const declared = orchestrate.semanticAcceptance;
32428
+ const declaredPin = declared !== void 0 && typeof declared.waiver === "object" ? declared.waiver.judgedHash : void 0;
32429
+ if (claim.waiver !== void 0 && declaredPin === void 0) refuse("orchestrate.claimConsistency.waiver", "is a standing waiver (RV4201): regulated acceptance admits only the pinned-hash form; declare semanticAcceptance.waiver { judgedHash } naming the one reviewed document it licenses, or drop the waiver");
32430
+ const wantContradictions = claim.onFound === "repair" ? "repair-once-then-fail" : "fail";
32431
+ const wantCitations = auditSpec.onFound === "repair" ? "repair-once-then-fail" : "fail";
32432
+ if (declared === void 0) orchestrate.semanticAcceptance = {
32433
+ judgedStage: "final",
32434
+ claimCoverage: "full",
32435
+ contradictions: wantContradictions,
32436
+ citations: wantCitations,
32437
+ unresolved: "fail",
32438
+ waiver: "forbid"
32439
+ };
32440
+ else {
32441
+ if (declared.judgedStage !== "final" || declared.claimCoverage !== "full" || declared.unresolved !== "fail") refuse("orchestrate.semanticAcceptance", "must declare judgedStage 'final', claimCoverage 'full' and unresolved 'fail'");
32442
+ if (declared.contradictions !== wantContradictions) refuse("orchestrate.semanticAcceptance.contradictions", `must be '${wantContradictions}' beside claimConsistency.onFound '${String(claim.onFound)}'`);
32443
+ if (declared.citations !== wantCitations) refuse("orchestrate.semanticAcceptance.citations", `must be '${wantCitations}' beside citationAudit.onFound '${String(auditSpec.onFound)}'`);
32444
+ if (declared.waiver !== "forbid" && declaredPin === void 0) refuse("orchestrate.semanticAcceptance.waiver", "must be 'forbid' or { judgedHash } (RV4201)");
32445
+ if (declaredPin !== void 0 && claim.waiver === void 0) refuse("orchestrate.claimConsistency.waiver", "must be declared beside the pinned semanticAcceptance.waiver: the pin licenses a declared principal and reason");
32446
+ }
31346
32447
  }
31347
32448
  }
32449
+ const toolsetAttestations = Object.fromEntries(Object.entries(defaults.profiles ?? {}).flatMap(([name, profile]) => {
32450
+ const pin = profile.toolsetAttestation;
32451
+ if (pin === void 0) return [];
32452
+ return [[name, {
32453
+ hash: pin.hash,
32454
+ ...pin.authorityHash === void 0 ? {} : { authorityHash: pin.authorityHash }
32455
+ }]];
32456
+ }));
32457
+ const semanticPosture = orchestrate === void 0 || orchestrate.claimConsistency === void 0 ? {} : {
32458
+ acceptanceReserve: "require",
32459
+ coveragePolicy: "strict-final",
32460
+ claimStage: orchestrate.claimConsistency.stage,
32461
+ claimOnFound: orchestrate.claimConsistency.onFound,
32462
+ ...orchestrate.claimConsistency.coverageRepair === true ? { claimCoverageRepair: true } : {},
32463
+ ...orchestrate.claimConsistency.coverageTarget === void 0 ? {} : { claimCoverageTarget: orchestrate.claimConsistency.coverageTarget },
32464
+ ...orchestrate.claimConsistency.judge === void 0 ? {} : { claimJudge: {
32465
+ ...orchestrate.claimConsistency.judge.model === void 0 ? {} : { model: orchestrate.claimConsistency.judge.model },
32466
+ ...orchestrate.claimConsistency.judge.effort === void 0 ? {} : { effort: orchestrate.claimConsistency.judge.effort }
32467
+ } },
32468
+ ...orchestrate.claimConsistency.waiver === void 0 ? {} : { claimWaiver: orchestrate.claimConsistency.waiver },
32469
+ ...orchestrate.contradictions?.onFound === void 0 ? {} : { contradictionsOnFound: orchestrate.contradictions.onFound },
32470
+ citationAudit: {
32471
+ onFound: orchestrate.citationAudit?.onFound,
32472
+ ...orchestrate.citationAudit?.samplePerSection === void 0 ? {} : { samplePerSection: orchestrate.citationAudit.samplePerSection },
32473
+ ...orchestrate.citationAudit?.maxSampled === void 0 ? {} : { maxSampled: orchestrate.citationAudit.maxSampled },
32474
+ ...orchestrate.citationAudit?.window === void 0 ? {} : { window: orchestrate.citationAudit.window },
32475
+ ...orchestrate.citationAudit?.pattern === void 0 ? {} : { pattern: orchestrate.citationAudit.pattern },
32476
+ ...orchestrate.citationAudit?.judge === void 0 ? {} : { judge: {
32477
+ ...orchestrate.citationAudit.judge.model === void 0 ? {} : { model: orchestrate.citationAudit.judge.model },
32478
+ ...orchestrate.citationAudit.judge.effort === void 0 ? {} : { effort: orchestrate.citationAudit.judge.effort }
32479
+ } }
32480
+ },
32481
+ semanticAcceptance: orchestrate.semanticAcceptance
32482
+ };
31348
32483
  const posture = {
31349
32484
  regulated: REGULATED_VERSION,
31350
32485
  strictApprovals: true,
31351
32486
  billingReceipts: "intent",
31352
32487
  determinism: "error",
32488
+ construction: {
32489
+ attested,
32490
+ unrecognized,
32491
+ ...input.construction === void 0 ? {} : { floor: input.construction }
32492
+ },
31353
32493
  strictPricing: run.strictPricing === true ? true : run.strictPricing,
31354
32494
  budgetPolicy: "immutable-lifetime",
31355
32495
  budgetUsd: run.budgetUsd,
31356
32496
  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
- },
32497
+ scopePolicy: "reject",
32498
+ ...Object.keys(toolsetAttestations).length === 0 ? {} : { toolsetAttestations },
32499
+ ...semanticPosture,
31365
32500
  ...run.configFingerprint === void 0 ? {} : { hostFingerprint: run.configFingerprint }
31366
32501
  };
31367
32502
  const profileHash = createHash("sha256").update(jcsSerialize(posture), "utf8").digest("hex");
@@ -31663,4 +32798,4 @@ function createSandboxBridge(ctx, options) {
31663
32798
  };
31664
32799
  }
31665
32800
  //#endregion
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 };
32801
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CITATION_JUDGE_LABEL, 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, DIGEST_DRAFT_MAX_WORDS, 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, MAX_UNCOVERED_SENTENCES, 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, agentTypeBucket, applyClaimOps, applyFinishRepairHints, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, attributionBucket, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, candidateHashOf, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationExcerptOf, citationJudgePassOf, citationTargetsValidator, citationUnitExcerptOf, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimJudgeStageOf, claimOpIssues, classifyAgentError, classifyAttemptOutcome, clauseAround, 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, executionScopeDigest, 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, productionAcceptable, 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, semanticTerminalVerdictOf, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, statementRowsFromDelimited, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, synthesisCandidatesFromJournal, synthesizeSpanClassOf, 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, verifyCandidateBytes, wireCapacityEstimate, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };