@rulvar/core 1.231.0 → 1.233.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 +313 -14
  2. package/dist/index.js +485 -22
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -1085,6 +1085,24 @@ type JournalEntry = {
1085
1085
  citation?: string;
1086
1086
  }>;
1087
1087
  /**
1088
+ * Terminal agent entries: the durable subset of the tool-budget
1089
+ * summary (RV3002): the loop's executed-call counter and the
1090
+ * effective cap at the end, journaled at settle whenever the live
1091
+ * result carried a summary. The counter has always been durable in
1092
+ * the terminal checkpoint, but checkpoints are blobs and journal
1093
+ * folds read entries only, so without this field observed
1094
+ * calls-per-evidence-entry calibration cannot be a pure fold. Replay
1095
+ * restores AgentResult.toolBudget from here unconditionally; entries
1096
+ * without the field (every pre-existing journal) keep the RV509
1097
+ * decision-conditional path byte for byte. Live-only summary fields
1098
+ * (unitsUsed, noticesFired, limiter, and the rest) never journal.
1099
+ * Policy, never identity, exactly like evidence.
1100
+ */
1101
+ toolBudget?: {
1102
+ used: number;
1103
+ cap?: number;
1104
+ };
1105
+ /**
1088
1106
  * Terminal escalated entries ONLY: the schema-validated
1089
1107
  * EscalationReport with runtime-filled costToDate and salvage; replay
1090
1108
  * synthesizes the byte-identical report from here (DEF-1).
@@ -2357,16 +2375,19 @@ interface ExplorationSummary {
2357
2375
  * visible BEFORE the terminal 'limit' a starved worker would settle
2358
2376
  * with. Attached to the full AgentResult and to the live `agent:end`
2359
2377
  * event whenever maxToolCalls, toolUnits, or toolBudgetExtension is
2360
- * configured. The snapshot itself never journals, but since RV509 it
2361
- * has a durable subset: an extension grant and the finalization-window
2362
- * entry journal as decision entries the moment they fire, a
2363
- * crash-resume restores them from the journal, and a replayed result
2364
- * carries `used` (from the terminal checkpoint), the granted `cap`,
2365
- * `extensionsGranted`, and `finalizationWindowEntered` whenever the
2366
- * invocation journaled at least one such decision. Every other field
2367
- * (unitsUsed/unitsMax, noticesFired, finalizationReserveUsed, limiter,
2368
- * and the cap of a grant-free run) is live-only fidelity, exactly like
2369
- * transportRetries, and stays absent on replay.
2378
+ * configured. The durable subset: since RV3002 the terminal entry
2379
+ * journals `used` and the effective `cap` at settle, so a replayed
2380
+ * result restores them unconditionally on new journals; an extension
2381
+ * grant and the finalization-window entry journal as decision entries
2382
+ * the moment they fire (RV509) and merge into the restored summary as
2383
+ * `extensionsGranted` and `finalizationWindowEntered`. A journal
2384
+ * written before the entry field shipped keeps the RV509 behavior byte
2385
+ * for byte: `used` from the terminal checkpoint plus the
2386
+ * decision-backed fields, present exactly when the invocation
2387
+ * journaled at least one decision. Every other field
2388
+ * (unitsUsed/unitsMax, noticesFired, finalizationReserveUsed, limiter)
2389
+ * is live-only fidelity, exactly like transportRetries, and stays
2390
+ * absent on replay.
2370
2391
  */
2371
2392
  interface ToolBudgetSummary {
2372
2393
  /** Executed tool calls (the loop's own counter). */
@@ -3732,6 +3753,11 @@ interface TerminalPatch {
3732
3753
  claim: string;
3733
3754
  citation?: string;
3734
3755
  }>;
3756
+ /** Terminal agent entries: the durable tool-budget subset; see JournalEntry. */
3757
+ toolBudget?: {
3758
+ used: number;
3759
+ cap?: number;
3760
+ };
3735
3761
  /** Terminal escalated entries: the validated EscalationReport. */
3736
3762
  escalation?: unknown;
3737
3763
  /**
@@ -7854,6 +7880,19 @@ interface ResumeOptions {
7854
7880
  */
7855
7881
  args?: unknown;
7856
7882
  /**
7883
+ * What an in-process body-hash mismatch does (RV3001). The default
7884
+ * 'warn' keeps the historical design: the mismatch emits the loud
7885
+ * `RULVAR_RESUME_HASH_MISMATCH` warning and the resume proceeds,
7886
+ * because the journal decides replay versus live per content keys
7887
+ * and reports orphans honestly. 'refuse' turns the same mismatch
7888
+ * into a typed ConfigError BEFORE ownership, meta writes, or any
7889
+ * append: the pin for hosts that treat an edited body as a
7890
+ * different workflow. The vocabulary is
7891
+ * {@link EvidenceContract.enforce}'s. Name mismatches and compiled
7892
+ * source mismatches are hard errors regardless, exactly as before.
7893
+ */
7894
+ bodyHash?: "warn" | "refuse";
7895
+ /**
7857
7896
  * Dry-run: replay-strict matching; the first would-be-live call throws
7858
7897
  * JournalMissError and the run settles with that typed error, zero live
7859
7898
  * calls performed.
@@ -7905,7 +7944,9 @@ interface Engine {
7905
7944
  * Rebinds a journal to a workflow definition and resumes. Requires wf
7906
7945
  * for in-process workflows;
7907
7946
  * a name mismatch is a typed ConfigError; a body-hash mismatch warns
7908
- * loudly and proceeds (the journal decides replay per content keys).
7947
+ * loudly and proceeds (the journal decides replay per content keys),
7948
+ * unless {@link ResumeOptions.bodyHash} is 'refuse', which makes it
7949
+ * a typed ConfigError before any durable mutation (RV3001).
7909
7950
  * A compiled run resumes WITHOUT wf: the engine rehydrates the
7910
7951
  * persisted source pinned by workflowHash; supplying a compiled wf
7911
7952
  * whose source hash differs from the recorded one is a typed
@@ -8709,6 +8750,22 @@ interface ClaimPairOptions {
8709
8750
  * 40).
8710
8751
  */
8711
8752
  critical?: readonly string[];
8753
+ /**
8754
+ * The declared coverage target (RV2903), in (0, 1]: size the
8755
+ * reported pairs to COVER at least this share of the citing
8756
+ * sentences instead of taking the first `max` pairs blind. The
8757
+ * ninth comparison run judged 43 of 115 citing sentences because
8758
+ * its host guessed `max: 56`, and nothing sized the pass to a goal.
8759
+ * Under a target the selection is coverage-first: every critical
8760
+ * candidate, then ONE candidate per still-uncovered sentence in
8761
+ * draft order until the target is met; pairs that only deepen an
8762
+ * already covered sentence are skipped, because under a declared
8763
+ * target the bounded budget buys coverage, not depth. `max` stays a
8764
+ * hard ceiling, and `truncated` then means exactly that the ceiling
8765
+ * cut selection the target still wanted. Unset = the exact
8766
+ * historical first-`max` selection, byte for byte.
8767
+ */
8768
+ targetCoverageShare?: number;
8712
8769
  }
8713
8770
  /** What the fold produced, beside the pairs themselves. */
8714
8771
  interface ClaimPairsFold {
@@ -8727,6 +8784,13 @@ interface ClaimPairsFold {
8727
8784
  */
8728
8785
  coveredCitingSentences: number;
8729
8786
  /**
8787
+ * Present when `targetCoverageShare` was declared (RV2903): the
8788
+ * sentence count the target resolved to against THIS draft, so a
8789
+ * consumer holds `coveredCitingSentences` against the goal the
8790
+ * selection was sized for, not against a share it must re-derive.
8791
+ */
8792
+ targetCoveredSentences?: number;
8793
+ /**
8730
8794
  * Present only when `critical` was given: the critical draft anchors
8731
8795
  * (verbatim, draft order, deduplicated) with no reported pair, capped
8732
8796
  * at {@link MAX_CRITICAL_UNCOVERED} entries.
@@ -10252,6 +10316,22 @@ interface OrchestrateClaimConsistency {
10252
10316
  /** Bound on each excerpt; default {@link DEFAULT_MAX_PAIR_EXCERPT_CHARS}. */
10253
10317
  maxExcerptChars?: number;
10254
10318
  /**
10319
+ * The declared coverage target (RV2903), in (0, 1]: the pass sizes
10320
+ * itself to COVER this share of the draft's citing sentences instead
10321
+ * of judging the first `max` pairs blind. The ninth comparison run
10322
+ * covered 43 of 115 citing sentences because its host guessed
10323
+ * `max: 56` plus the default run-fact bound, and the honest
10324
+ * 'partial' grade was the constant's echo, not a policy. Under a
10325
+ * target the pairing selects coverage-first (criticals, then one
10326
+ * pair per uncovered sentence until the target is met; `max` stays a
10327
+ * hard ceiling), the run-fact pass judges EVERY matched candidate
10328
+ * instead of the default bound, and an undeclared
10329
+ * `minimumCoverageRatio` defaults to the target, so the RV1809
10330
+ * floor machinery (the `lowCoverage` block, `onLowCoverage`, the
10331
+ * strict CLI exit) enforces the same number that sized the pass.
10332
+ */
10333
+ coverageTarget?: number;
10334
+ /**
10255
10335
  * Critical anchor declarations (RV1603): paths (a file, or a
10256
10336
  * directory matched as a prefix) or span anchors
10257
10337
  * (`src/exec.ts:250-300`). Pairs whose draft anchor matches sort
@@ -10353,6 +10433,12 @@ interface OrchestrateClaimConsistencyMeta {
10353
10433
  */
10354
10434
  coveredCitingSentences: number;
10355
10435
  /**
10436
+ * Present when `coverageTarget` was declared (RV2903): the share the
10437
+ * pass sized itself for, echoed so a persisted outcome says WHAT the
10438
+ * coverage was held against, not only what it reached.
10439
+ */
10440
+ coverageTarget?: number;
10441
+ /**
10356
10442
  * Present when `critical` was declared: the critical draft anchors
10357
10443
  * with no judged pair (capped at {@link MAX_CRITICAL_UNCOVERED});
10358
10444
  * `[]` means every declared claim the draft cited was judged.
@@ -10487,8 +10573,23 @@ interface OrchestrateSynthesis {
10487
10573
  * (harness-observed, not production evidence). Folded ONLY from
10488
10574
  * journal-replayed material; off by default, and the prompt stays
10489
10575
  * byte identical when unset.
10490
- */
10491
- runFacts?: boolean;
10576
+ *
10577
+ * The object form (RV3004) keeps the child line and adds opt-ins.
10578
+ * `workflowSoFar: true` appends a RUN FACTS SO FAR line: the same
10579
+ * counters folded over the settled children PLUS this
10580
+ * orchestration's own settled internal spans as of this dispatch's
10581
+ * composition (coordination turns, draft claim judges, judged
10582
+ * contradiction passes, synthesis notes), so the number the model
10583
+ * quotes sits next to the invoice instead of a third of it. The
10584
+ * composing dispatch itself and anything still running are excluded
10585
+ * by construction, the line says so, and dollars stay absent for
10586
+ * the same replay reason as the child line. `runFacts: true` keeps
10587
+ * today's prompt bytes exactly; the SO FAR line exists only under
10588
+ * the object opt-in.
10589
+ */
10590
+ runFacts?: boolean | {
10591
+ workflowSoFar?: boolean;
10592
+ };
10492
10593
  /**
10493
10594
  * Admission estimate for the synthesize invocation, like
10494
10595
  * AgentOpts.estCost: under a tight orchestrator cap the default
@@ -13012,6 +13113,11 @@ interface JournaledChild {
13012
13113
  minEntries: number;
13013
13114
  met: boolean;
13014
13115
  };
13116
+ /** The RV3002 durable tool-budget subset, when the terminal journaled it. */
13117
+ toolBudget?: {
13118
+ used: number;
13119
+ cap?: number;
13120
+ };
13015
13121
  /**
13016
13122
  * Present and true when the orchestration ABANDONED this child's
13017
13123
  * branch (RV2804): the work happened and the provider billed it, and
@@ -13177,6 +13283,156 @@ interface JournaledCriticalPath {
13177
13283
  */
13178
13284
  declare function criticalPathFromJournal(entries: readonly JournalEntry[]): JournaledCriticalPath;
13179
13285
  //#endregion
13286
+ //#region src/stores/synthesis-candidates.d.ts
13287
+ /** One failed validator on a journaled finish verdict, verbatim. */
13288
+ interface SynthesisCandidateFailure {
13289
+ name: string;
13290
+ reasons: readonly string[];
13291
+ }
13292
+ /** One finish candidate, folded from its journaled verdict (RV2902). */
13293
+ interface JournaledSynthesisCandidate {
13294
+ /** The journaled verdict: 'accepted', 'repair', or 'rejected'. */
13295
+ verdict: "accepted" | "repair" | "rejected";
13296
+ /** The verdict decision's seq: the candidate's address in the run. */
13297
+ verdictSeq: number;
13298
+ /** The verdict decision's stamp, when the entry carried one. */
13299
+ verdictAt?: string;
13300
+ /** The finish call id the verdict was keyed by. */
13301
+ callId?: string;
13302
+ /** Repairs spent BEFORE this candidate, from the verdict itself. */
13303
+ repairsUsed?: number;
13304
+ maxRepairs?: number;
13305
+ /** The contract generation the verdict was rendered under. */
13306
+ contractHash?: string;
13307
+ /** The non-accepted candidate's identity (RV2507), when journaled. */
13308
+ candidateHash?: string;
13309
+ candidateChars?: number;
13310
+ /** The rejected candidate's transcript blob, under retention. */
13311
+ candidateRef?: string;
13312
+ /** The failed validators with their reasons, verbatim. */
13313
+ failed: readonly SynthesisCandidateFailure[];
13314
+ /** The hosting span's dispatch label (RV2901), when journaled. */
13315
+ spanLabel?: string;
13316
+ /**
13317
+ * Wall from the previous boundary (the span's start, or the prior
13318
+ * verdict) to this verdict's stamp. Absent when the candidate is not
13319
+ * hosted by a settled synthesize span or a stamp is missing.
13320
+ */
13321
+ windowMs?: number;
13322
+ /**
13323
+ * Provider wire requests inside this candidate's window (absorbed
13324
+ * continuations counted). Present only when the incremental rows
13325
+ * cover the hosting span's terminal call records exactly.
13326
+ */
13327
+ wires?: number;
13328
+ /** Summed recorded usage of the window's wires; same condition. */
13329
+ usage?: Usage;
13330
+ /**
13331
+ * Window wires that recorded NO usage on a non-ok outcome: the
13332
+ * provider may have billed them anyway, so `costUsd` is a floor
13333
+ * whenever this is nonzero.
13334
+ */
13335
+ usageUnknownWires?: number;
13336
+ /**
13337
+ * The window priced per call at the caller's table. Present only
13338
+ * when a price function was given and it priced EVERY window wire;
13339
+ * an unpriced model drops the field rather than shrinking it.
13340
+ */
13341
+ costUsd?: number;
13342
+ }
13343
+ /** What `synthesisCandidatesFromJournal` folded, beside the candidates. */
13344
+ interface JournaledSynthesisCandidateReport {
13345
+ /** Every hosted candidate, in verdict seq order. */
13346
+ candidates: readonly JournaledSynthesisCandidate[];
13347
+ /** Settled synthesize spans the journal holds. */
13348
+ synthesisSpans: number;
13349
+ /**
13350
+ * Finish verdicts NOT hosted by a settled synthesize span: draft
13351
+ * stage validations in the coordination span, and verdicts inside a
13352
+ * synthesis that never settled. Counted, never guessed into
13353
+ * candidates.
13354
+ */
13355
+ unhostedVerdicts: number;
13356
+ /**
13357
+ * Settled synthesize spans whose incremental billing rows do not
13358
+ * cover their terminal call records (the rows append asynchronously
13359
+ * and may be missing); their candidates carry verdict facts only.
13360
+ */
13361
+ unattributedSpans: number;
13362
+ /** Wires after a span's LAST verdict: attributed to no candidate. */
13363
+ tailWires: number;
13364
+ }
13365
+ /**
13366
+ * Fold the finish candidates (RV2902) out of a run's journal: each
13367
+ * journaled validation verdict with the window of wall, wires, usage,
13368
+ * and priced cost that produced the candidate it judged.
13369
+ *
13370
+ * @param entries the journal of one run, in any order
13371
+ * @param priceUsd prices one call's usage at its serving model, the
13372
+ * same shape `invoiceFromJournal` takes; omit to fold without money
13373
+ */
13374
+ declare function synthesisCandidatesFromJournal(entries: readonly JournalEntry[], priceUsd?: (servedBy: ModelRef, usage: Usage) => number | undefined): JournaledSynthesisCandidateReport;
13375
+ //#endregion
13376
+ //#region src/stores/tool-calibration.d.ts
13377
+ /** One dispatch carrying BOTH sides of the calibration pair (RV3003). */
13378
+ interface ToolCalibrationRow {
13379
+ /** The scope the dispatch journaled under. */
13380
+ scope: string;
13381
+ /** The dispatch seq (the terminal's `ref`): the child's handle. */
13382
+ handle: number;
13383
+ /** The profile the dispatch ran under, when the terminal recorded it. */
13384
+ agentType?: string;
13385
+ /** The journaled terminal status. */
13386
+ status: string;
13387
+ /** Successful `record_evidence` executions the RV806 verdict counted. */
13388
+ recordedEntries: number;
13389
+ /** The declared floor the verdict was judged against. */
13390
+ minEntries: number;
13391
+ /** Executed tool calls the RV3002 terminal subset journaled. */
13392
+ toolCallsUsed: number;
13393
+ /** `toolCallsUsed / recordedEntries`; absent when recordedEntries is 0. */
13394
+ callsPerEntry?: number;
13395
+ }
13396
+ /** A dispatch named but excluded from the rate: one side is NOT RECORDED. */
13397
+ interface ToolCalibrationExclusion {
13398
+ scope: string;
13399
+ handle: number;
13400
+ status: string;
13401
+ }
13402
+ /** The observed calls-per-evidence-entry calibration of one journal (RV3003). */
13403
+ interface ToolCalibrationReport {
13404
+ /** Terminal agent dispatches the journal holds, the partition's whole. */
13405
+ dispatches: number;
13406
+ /** Dispatches carrying both the verdict and the counter, in seq order. */
13407
+ observed: ToolCalibrationRow[];
13408
+ /**
13409
+ * The observed aggregate over `observed` rows: summed executed calls
13410
+ * against summed recorded entries, with the rate absent when the
13411
+ * entry sum is 0. Absent entirely when no row paired.
13412
+ */
13413
+ aggregate?: {
13414
+ toolCallsUsed: number;
13415
+ recordedEntries: number;
13416
+ callsPerEntry?: number;
13417
+ };
13418
+ /** A declared contract whose counter was never journaled (pre-RV3002 journals). */
13419
+ evidenceOnly: ToolCalibrationExclusion[];
13420
+ /** A journaled counter with no declared contract: nothing to divide by. */
13421
+ budgetOnly: ToolCalibrationExclusion[];
13422
+ /** Dispatches carrying neither side. */
13423
+ unobserved: number;
13424
+ }
13425
+ /**
13426
+ * Folds the observed tool-budget calibration from a journal (RV3003):
13427
+ * every terminal agent entry is partitioned by which sides of the
13428
+ * evidence/counter pair it recorded, the paired rows carry their
13429
+ * per-dispatch rate, and the aggregate is the number a host compares
13430
+ * against its declared `estCallsPerEntry`. Pure over the entries, so
13431
+ * live and resumed journals fold identically; nothing is re-derived
13432
+ * and no checkpoint blob is read.
13433
+ */
13434
+ declare function toolCalibrationFromJournal(entries: readonly JournalEntry[]): ToolCalibrationReport;
13435
+ //#endregion
13180
13436
  //#region src/stores/jsonl.d.ts
13181
13437
  declare class JsonlFileStore implements MetaLookupStore {
13182
13438
  private readonly dir;
@@ -13773,6 +14029,32 @@ declare function statementFromRows(input: {
13773
14029
  rows: readonly Record<string, unknown>[];
13774
14030
  map: StatementColumnMap;
13775
14031
  }): ProviderStatement;
14032
+ /** How {@link statementRowsFromDelimited} splits cells; default ','. */
14033
+ interface DelimitedStatementOptions {
14034
+ delimiter?: "," | ";" | " " | "|";
14035
+ }
14036
+ /**
14037
+ * Parses a delimited billing export (the CSV/TSV a provider console
14038
+ * hands a host) into the header-keyed rows {@link statementFromRows}
14039
+ * consumes (RV2908). The library deliberately hard-codes NO provider's
14040
+ * export format: the host owns the column map, this owns only the
14041
+ * delimited grammar, and the pair closes the last manual step between
14042
+ * a downloaded export and {@link reconcileStatement}.
14043
+ *
14044
+ * Fail-closed at the record, like the rest of this module: a data row
14045
+ * whose cell count differs from the header, a quote opened and never
14046
+ * closed, a stray quote inside an unquoted cell, an empty or duplicate
14047
+ * header name, all refuse typed with the line instead of flowing a
14048
+ * shifted column into a reconciliation, because a column shifted one
14049
+ * to the left prices `outputTokens` as dollars and calls it evidence.
14050
+ * RFC 4180 quoting is honored (quoted cells may carry the delimiter,
14051
+ * doubled quotes, and line breaks); CRLF and lone LF both delimit
14052
+ * records; one trailing empty line is an artifact of every exporter
14053
+ * and is ignored. Cells come back as raw strings, so an empty cell
14054
+ * reads as "the export does not carry this figure" downstream, exactly
14055
+ * the absence contract `statementFromRows` documents.
14056
+ */
14057
+ declare function statementRowsFromDelimited(text: string, options?: DelimitedStatementOptions): Record<string, string>[];
13776
14058
  //#endregion
13777
14059
  //#region src/engine/persisted-terminal.d.ts
13778
14060
  /**
@@ -14876,6 +15158,23 @@ interface PostFanInBreakdown {
14876
15158
  * composition in {@link reduceCriticalPath}.
14877
15159
  */
14878
15160
  declare const CLAIM_JUDGE_LABEL = "claim-consistency-judge";
15161
+ /**
15162
+ * The label the final synthesis (composition) invocation dispatches
15163
+ * under (RV2901). The engine labelling its OWN dispatches is what lets
15164
+ * `criticalPathFromJournal` split the synthesize bucket offline: the
15165
+ * split demands a label on EVERY synthesize span, and the comparison
15166
+ * run that shipped the journal fold still refused it because this one
15167
+ * dispatch stayed anonymous while the claim judge was labelled.
15168
+ */
15169
+ declare const FINAL_COMPOSITION_LABEL = "final-composition";
15170
+ /**
15171
+ * The label an incremental synthesis note dispatches under (RV2901).
15172
+ * Notes ride role 'synthesize' and are composition-side work, so both
15173
+ * reducers count them toward the composition half of the split; the
15174
+ * label exists so a journal reader can tell WHICH composition spans
15175
+ * were notes without guessing from their size.
15176
+ */
15177
+ declare const SYNTHESIS_NOTE_LABEL = "synthesis-note";
14879
15178
  declare function reduceCriticalPath(events: Iterable<WorkflowEvent>): CriticalPath;
14880
15179
  //#endregion
14881
15180
  //#region src/runner/sandbox-bridge.d.ts
@@ -14950,4 +15249,4 @@ interface SandboxBridge {
14950
15249
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
14951
15250
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
14952
15251
  //#endregion
14953
- export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, AcceptanceChildSummary, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, type AgentInvocationRow, AgentOpts, AgentProfile, AgentProfilePermissions, AgentProfileTemplateOptions, AgentResult, AgentResultMeta, AgentStatus, type AppliedPricingRow, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BillingComponent, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CachePolicy, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildExecutionFacts, ChildIdentityInput, ChildResultPage, ChildrenAtFailure, CitationTarget, type ClaimClass, ClaimContradictionFinding, ClaimCoverageGrade, ClaimCoverageInput, type ClaimOp, ClaimPair, ClaimPairOptions, ClaimPairsFold, ClaimPoolReading, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ComponentDelta, ConfigError, Contradiction, ContradictionClaim, ContradictionOptions, ContradictionSource, type CoreEvents, CostAttribution, CostAttributionFacts, type CostBasis, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DecisionChainRow, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DocumentedRates, DonorCandidate, DonorRef, DroppedItem, 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, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryBillingFold, EntryBillingUnit, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, EvidenceContract, type EvidenceRef, type ExecKeyDerivation, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_SECTIONAL_SCHEMA, FINISH_TOOL_NAME, FUTURE_RATES_TOLERANCE_MS, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FencedCodeMode, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, type FinalizationWindowBudget, FinishContract, FinishContractCitations, FinishContractGoldenReject, FinishContractManifest, FinishContractSectionPattern, FinishInfo, FinishSelfTestFailure, FinishSelfTestFixtures, FinishSelfTestReport, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GET_SETTLED_CHILD_RESULTS_SCHEMA, GET_SETTLED_CHILD_RESULTS_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, InvoiceCardinality, InvoiceExport, InvoicePricingProvenance, InvoiceReconciliation, InvoiceRow, type IsolatedExecContext, type IsolatedExecRequest, type IsolatedExecutorTag, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, type JournalPricingSnapshot, JournalSealedError, JournalSerializationContext, JournalSerializationHook, type JournalStore, JournaledChild, JournaledChildRoster, JournaledCriticalPath, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalRunTelemetry, LogicalTaskId, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, MemoryQuotaLimiter, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateAcceptance, OrchestrateClaimConsistency, OrchestrateClaimConsistencyMeta, OrchestrateContradictions, OrchestrateContradictionsMeta, OrchestrateDraftToFinal, OrchestrateOptions, OrchestrateSynthesis, OrchestrateSynthesisSkipReason, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, PersistedTerminalRefusal, PersistedTerminalResult, type PhaseRow, PhaseTarget, PilotAgentProfileOptions, PilotAgentProfileResult, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, type PostFanInBreakdown, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedComponent, PricedComponents, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, ProviderStatement, QUOTA_WINDOW_MS, QualityFloors, QuotaCounters, type QuotaDecision, type QuotaEstimate, type QuotaLimiter, type QuotaReservationRequest, QuotaRule, QuotaWindowSnapshot, 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, RandIdentityInput, RandPayload, RateLimitObservation, ReconcileOptions, ReconcileResult, ReconcileStatementOptions, RefEntryAppender, RefEntryClassification, RefusalInfo, RejectedFinishCandidate, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, RunFactPairOptions, RunFactPairsFold, RunFactsSheet, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, SectionPatternEntry, SemanticPassSummary, SemanticPassesSummary, Semaphore, SerializationHook, Settled, SettlementError, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StatementCategoryRow, StatementColumnMap, StatementCoverage, StatementReconciliation, StatementRequestRow, StepIdentityInput, type StreamHooks, StructuredOutputTier, SupersededError, SuspendedAppend, SuspensionState, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TelemetryScope, type TerminalEnvelope, TerminalOutcomeFacts, TerminalPatch, TerminalTelemetryScopes, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, ToolAuthority, type ToolBudgetSummary, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, type ToolExecutorProvider, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, ToolsetAttestation, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, sectionPatternCountValidator, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolAuthority, toolContract, toolContractHash, toolsetAuthorityHash, toolsetHash, ttlState, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
15252
+ export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, AcceptanceChildSummary, type AdaptiveEvents, AdmissionController, AdmissionDecision, AdmissionRejectedError, AdmissionStatsBefore, AdmitLineage, AdmitRejectReason, AdmitSpec, AdmitVerdict, AgentCallError, AgentError, type AgentEvents, AgentIdentityInput, type AgentInvocationRow, AgentOpts, AgentProfile, AgentProfilePermissions, AgentProfileTemplateOptions, AgentResult, AgentResultMeta, AgentStatus, type AppliedPricingRow, ApproachSignatureInputs, ApprovalDecision, ApprovalIdentityInput, Artifact, AttemptOutcomeClass, AuditCategory, AuditRecord, AuditRunsOptions, BUDGET_ABORT_REASON, BaseAppend, BillingComponent, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CachePolicy, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildExecutionFacts, ChildIdentityInput, ChildResultPage, ChildrenAtFailure, CitationTarget, type ClaimClass, ClaimContradictionFinding, ClaimCoverageGrade, ClaimCoverageInput, type ClaimOp, ClaimPair, ClaimPairOptions, ClaimPairsFold, ClaimPoolReading, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ComponentDelta, ConfigError, Contradiction, ContradictionClaim, ContradictionOptions, ContradictionSource, type CoreEvents, CostAttribution, CostAttributionFacts, type CostBasis, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DataKeyProvider, DebitResult, DecisionChainRow, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DelimitedStatementOptions, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DocumentedRates, DonorCandidate, DonorRef, DroppedItem, 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, EffectiveUsageLimits, Effort, Engine, EngineDefaults, EngineQuotaConfig, EngineQuotaRuntime, EntryBillingFold, EntryBillingUnit, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, EvidenceContract, type EvidenceRef, type ExecKeyDerivation, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINAL_COMPOSITION_LABEL, FINISH_SCHEMA, FINISH_SECTIONAL_SCHEMA, FINISH_TOOL_NAME, FUTURE_RATES_TOLERANCE_MS, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FencedCodeMode, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, type FinalizationWindowBudget, FinishContract, FinishContractCitations, FinishContractGoldenReject, FinishContractManifest, FinishContractSectionPattern, FinishInfo, FinishSelfTestFailure, FinishSelfTestFixtures, FinishSelfTestReport, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GET_SETTLED_CHILD_RESULTS_SCHEMA, GET_SETTLED_CHILD_RESULTS_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, InvoiceCardinality, InvoiceExport, InvoicePricingProvenance, InvoiceReconciliation, InvoiceRow, type IsolatedExecContext, type IsolatedExecRequest, type IsolatedExecutorTag, type IsolationProvider, type IsolationSpec, Issue$1 as Issue, JOURNAL_ENVELOPE_MARKER, JournalCompatSubCode, JournalCompatibilityError, JournalEntry, JournalMatcher, JournalMissError, JournalOperation, JournalOrderViolation, type JournalPricingSnapshot, JournalSealedError, JournalSerializationContext, JournalSerializationHook, type JournalStore, JournaledChild, JournaledChildRoster, JournaledCriticalPath, JournaledSynthesisCandidate, JournaledSynthesisCandidateReport, type Json, JsonSchema, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, type KbProposal, type KbProposalTrigger, KeyDeriver, KeyRing, KeyedLimiter, KnowledgeCasError, type KnowledgeSnapshot, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LadderSpec, type LeasableStore, type Lease, LeaseHeldError, Ledger, LineageCounters, LineageIndex, LineageRef, LineageRelation, LineageStats, LogicalRunTelemetry, LogicalTaskId, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, MatchResult, McpConfig, McpToolSource, MechanicalGateProfile, MechanicalGateVerdict, MemoryQuotaLimiter, type MetaLookupStore, type ModelCaps, ModelChoice, type ModelClaim, ModelEpochInputs, type ModelKnowledgeHandle, type ModelKnowledgeStore, ModelListConstraint, ModelRef, ModelRetry, ModelSpec, Msg, NoProgressDetector, NodeId, NodeLinkValue, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OnEscalation, OperationDisposition, OrchestrateAcceptance, OrchestrateClaimConsistency, OrchestrateClaimConsistencyMeta, OrchestrateContradictions, OrchestrateContradictionsMeta, OrchestrateDraftToFinal, OrchestrateOptions, OrchestrateSynthesis, OrchestrateSynthesisSkipReason, OrchestratorBudgetSpec, OrchestratorCapConfigError, OrchestratorExtension, OrchestratorExtensionIO, OrchestratorRuntime, Out, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, Part, PendingExternal, PendingToolTurn, PermissionConfig, PermissionGate, PermissionHook, PermissionPreset, PermissionRule, PermissionVerdict, PersistedTerminalRefusal, PersistedTerminalResult, type PhaseRow, PhaseTarget, PilotAgentProfileOptions, PilotAgentProfileResult, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, type PostFanInBreakdown, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedComponent, PricedComponents, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, ProviderStatement, QUOTA_WINDOW_MS, QualityFloors, QuotaCounters, type QuotaDecision, type QuotaEstimate, type QuotaLimiter, type QuotaReservationRequest, QuotaRule, QuotaWindowSnapshot, 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, RandIdentityInput, RandPayload, RateLimitObservation, ReconcileOptions, ReconcileResult, ReconcileStatementOptions, RefEntryAppender, RefEntryClassification, RefusalInfo, RejectedFinishCandidate, RepeatedClaim, ReplayDisposition, ReplayMode, ReplayPlanHashMismatch, Replayer, RepositoryResearchToolset, RepositoryResearchToolsetOptions, ResearchAgentProfileOptions, ResearchAgentProfileResult, ResearchEvidenceEntry, ResolutionArbiter, ResolutionAttempt, ResolutionBy, ResolutionFold, ResolutionLayer, ResolutionOutcome, ResolutionPayload, ResolvedInvocation, ResolvedToolset, ResumeHandle, ResumeOptions, ResumePreview, ResumeReport, RetryClass, RetryPolicy, ReuseConfig, RiskRuleValue, Role, RulvarError, RulvarErrorCode, RunAgentOptions, RunAuditVerdict, RunBudget, RunEventSink, RunExport, RunFactPairOptions, RunFactPairsFold, RunFactsSheet, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SYNTHESIS_NOTE_LABEL, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, SectionPatternEntry, SemanticPassSummary, SemanticPassesSummary, Semaphore, SerializationHook, Settled, SettlementError, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StatementCategoryRow, StatementColumnMap, StatementCoverage, StatementReconciliation, StatementRequestRow, StepIdentityInput, type StreamHooks, StructuredOutputTier, SupersededError, SuspendedAppend, SuspensionState, SynthesisCandidateFailure, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TelemetryScope, type TerminalEnvelope, TerminalOutcomeFacts, TerminalPatch, TerminalTelemetryScopes, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, ToolAuthority, type ToolBudgetSummary, ToolCalibrationExclusion, ToolCalibrationReport, ToolCalibrationRow, ToolCallRequest, ToolChoice, type ToolContext, ToolContextSeed, ToolContract, type ToolDef, type ToolEvents, type ToolExecutor, type ToolExecutorProvider, ToolInit, type ToolRisk, ToolRuntime, type ToolSource, type ToolSourceSession, ToolsOption, ToolsetAttestation, TranscriptSerializationHook, type TranscriptStore, TriggerClass, TtlState, Usage, UsageLimits, UsageSlice, VerifiedRecommendation, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, WakeBudgetBlock, WakeDigest, WakeTrigger, WireError, Workflow, WorkflowCallOpts, type WorkflowEvent, type WorkflowEventBody, WorkflowRegistry, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, sectionPatternCountValidator, 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, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -7902,6 +7902,7 @@ var Replayer = class {
7902
7902
  if (patch.checkpointRef !== void 0) entry.checkpointRef = patch.checkpointRef;
7903
7903
  if (patch.evidence !== void 0) entry.evidence = patch.evidence;
7904
7904
  if (patch.evidenceEntries !== void 0) entry.evidenceEntries = patch.evidenceEntries;
7905
+ if (patch.toolBudget !== void 0) entry.toolBudget = patch.toolBudget;
7905
7906
  if (patch.artifacts !== void 0) entry.artifacts = toJournalValue(patch.artifacts, "terminal artifacts");
7906
7907
  if (patch.escalation !== void 0) entry.escalation = toJournalValue(patch.escalation, "escalation report");
7907
7908
  if (patch.memoizeOutcome !== void 0) entry.memoizeOutcome = patch.memoizeOutcome;
@@ -8972,7 +8973,8 @@ function childRostersFromJournal(entries) {
8972
8973
  ...abandoned.isAbandoned(dispatch.seq) ? { abandoned: true } : {},
8973
8974
  ...terminal?.costAttribution?.agentType === void 0 ? {} : { agentType: terminal.costAttribution.agentType },
8974
8975
  ...terminal === void 0 ? {} : { status: terminal.status },
8975
- ...terminal?.evidence === void 0 ? {} : { evidence: { ...terminal.evidence } }
8976
+ ...terminal?.evidence === void 0 ? {} : { evidence: { ...terminal.evidence } },
8977
+ ...terminal?.toolBudget === void 0 ? {} : { toolBudget: { ...terminal.toolBudget } }
8976
8978
  });
8977
8979
  }
8978
8980
  return [...rosters.values()];
@@ -9221,6 +9223,23 @@ function reduceInvocationTable(events) {
9221
9223
  * composition in {@link reduceCriticalPath}.
9222
9224
  */
9223
9225
  const CLAIM_JUDGE_LABEL = "claim-consistency-judge";
9226
+ /**
9227
+ * The label the final synthesis (composition) invocation dispatches
9228
+ * under (RV2901). The engine labelling its OWN dispatches is what lets
9229
+ * `criticalPathFromJournal` split the synthesize bucket offline: the
9230
+ * split demands a label on EVERY synthesize span, and the comparison
9231
+ * run that shipped the journal fold still refused it because this one
9232
+ * dispatch stayed anonymous while the claim judge was labelled.
9233
+ */
9234
+ const FINAL_COMPOSITION_LABEL = "final-composition";
9235
+ /**
9236
+ * The label an incremental synthesis note dispatches under (RV2901).
9237
+ * Notes ride role 'synthesize' and are composition-side work, so both
9238
+ * reducers count them toward the composition half of the split; the
9239
+ * label exists so a journal reader can tell WHICH composition spans
9240
+ * were notes without guessing from their size.
9241
+ */
9242
+ const SYNTHESIS_NOTE_LABEL = "synthesis-note";
9224
9243
  /** Total length of the union of possibly overlapping intervals. */
9225
9244
  function unionLength(intervals) {
9226
9245
  const positive = intervals.filter((interval) => interval.to > interval.from);
@@ -9380,7 +9399,7 @@ function reduceCriticalPath(events) {
9380
9399
  }
9381
9400
  //#endregion
9382
9401
  //#region src/stores/critical-path.ts
9383
- const parse = (at) => {
9402
+ const parse$1 = (at) => {
9384
9403
  if (at === void 0) return;
9385
9404
  const ms = Date.parse(at);
9386
9405
  return Number.isFinite(ms) ? ms : void 0;
@@ -9403,8 +9422,8 @@ function criticalPathFromJournal(entries) {
9403
9422
  let labelledSynthesis = false;
9404
9423
  let unlabelledSynthesis = false;
9405
9424
  for (const entry of ordered) {
9406
- const startedAt = parse(entry.startedAt);
9407
- const endedAt = parse(entry.endedAt);
9425
+ const startedAt = parse$1(entry.startedAt);
9426
+ const endedAt = parse$1(entry.endedAt);
9408
9427
  if (startedAt !== void 0) runStart = runStart === void 0 ? startedAt : Math.min(runStart, startedAt);
9409
9428
  const last = endedAt ?? startedAt;
9410
9429
  if (last !== void 0) runEnd = runEnd === void 0 ? last : Math.max(runEnd, last);
@@ -9453,6 +9472,249 @@ function criticalPathFromJournal(entries) {
9453
9472
  return path;
9454
9473
  }
9455
9474
  //#endregion
9475
+ //#region src/stores/synthesis-candidates.ts
9476
+ const parse = (at) => {
9477
+ if (at === void 0) return;
9478
+ const ms = Date.parse(at);
9479
+ return Number.isFinite(ms) ? ms : void 0;
9480
+ };
9481
+ const VERDICTS = /* @__PURE__ */ new Set([
9482
+ "accepted",
9483
+ "repair",
9484
+ "rejected"
9485
+ ]);
9486
+ const OPTIONAL_USAGE_KEYS = [
9487
+ "reasoningTokens",
9488
+ "cacheWrite5mTokens",
9489
+ "cacheWrite1hTokens"
9490
+ ];
9491
+ function sumUsage$1(rows) {
9492
+ const total = {
9493
+ inputTokens: 0,
9494
+ outputTokens: 0,
9495
+ cacheReadTokens: 0,
9496
+ cacheWriteTokens: 0
9497
+ };
9498
+ for (const row of rows) {
9499
+ if (row.usage === void 0) continue;
9500
+ total.inputTokens += row.usage.inputTokens;
9501
+ total.outputTokens += row.usage.outputTokens;
9502
+ total.cacheReadTokens += row.usage.cacheReadTokens;
9503
+ total.cacheWriteTokens += row.usage.cacheWriteTokens;
9504
+ for (const key of OPTIONAL_USAGE_KEYS) {
9505
+ const share = row.usage[key];
9506
+ if (share !== void 0) total[key] = (total[key] ?? 0) + share;
9507
+ }
9508
+ }
9509
+ return total;
9510
+ }
9511
+ const usageUnknown = (row) => {
9512
+ if (row.outcome === "ok") return false;
9513
+ const usage = row.usage;
9514
+ if (usage === void 0) return true;
9515
+ return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.cacheReadTokens === 0 && usage.cacheWriteTokens === 0 && (usage.reasoningTokens ?? 0) === 0;
9516
+ };
9517
+ /**
9518
+ * Fold the finish candidates (RV2902) out of a run's journal: each
9519
+ * journaled validation verdict with the window of wall, wires, usage,
9520
+ * and priced cost that produced the candidate it judged.
9521
+ *
9522
+ * @param entries the journal of one run, in any order
9523
+ * @param priceUsd prices one call's usage at its serving model, the
9524
+ * same shape `invoiceFromJournal` takes; omit to fold without money
9525
+ */
9526
+ function synthesisCandidatesFromJournal(entries, priceUsd) {
9527
+ const ordered = [...entries].sort((a, b) => a.seq - b.seq);
9528
+ const spans = [];
9529
+ for (const entry of ordered) {
9530
+ if (entry.kind !== "agent" || entry.status === "running" || entry.status === "suspended" || entry.costAttribution?.role !== "synthesize" || typeof entry.ref !== "number") continue;
9531
+ spans.push({
9532
+ runningSeq: entry.ref,
9533
+ terminalSeq: entry.seq,
9534
+ startedAt: parse(entry.startedAt),
9535
+ ...entry.costAttribution.label === void 0 ? {} : { label: entry.costAttribution.label },
9536
+ records: entry.providerCalls,
9537
+ wires: [],
9538
+ verdictSeqs: []
9539
+ });
9540
+ }
9541
+ const bySeqOpen = /* @__PURE__ */ new Map();
9542
+ for (const span of spans) bySeqOpen.set(span.runningSeq, span);
9543
+ const verdicts = [];
9544
+ for (const entry of ordered) {
9545
+ if (entry.kind !== "decision") continue;
9546
+ const value = entry.value;
9547
+ if (value === void 0) continue;
9548
+ if (value.decisionType === "provider-call") {
9549
+ const wire = value;
9550
+ if (typeof wire.agentRef !== "number") continue;
9551
+ const span = bySeqOpen.get(wire.agentRef);
9552
+ const record = wire.record;
9553
+ if (span === void 0 || record === void 0 || typeof record.ordinal !== "number") continue;
9554
+ span.wires.push({
9555
+ seq: entry.seq,
9556
+ ordinal: record.ordinal,
9557
+ ...typeof record.servedBy === "string" ? { servedBy: record.servedBy } : {},
9558
+ outcome: typeof record.outcome === "string" ? record.outcome : "ok",
9559
+ ...record.usage === void 0 ? {} : { usage: record.usage },
9560
+ wireRequests: typeof record.wireRequests === "number" ? record.wireRequests : 1
9561
+ });
9562
+ continue;
9563
+ }
9564
+ if (value.decisionType !== "orchestrator_finish_validation") continue;
9565
+ const verdictValue = value;
9566
+ if (typeof verdictValue.verdict !== "string" || !VERDICTS.has(verdictValue.verdict)) continue;
9567
+ let host;
9568
+ for (const span of spans) if (entry.seq > span.runningSeq && entry.seq < span.terminalSeq) {
9569
+ if (host === void 0 || span.runningSeq > host.runningSeq) host = span;
9570
+ }
9571
+ if (host !== void 0) host.verdictSeqs.push(entry.seq);
9572
+ verdicts.push({
9573
+ seq: entry.seq,
9574
+ ...entry.startedAt === void 0 ? {} : { at: entry.startedAt },
9575
+ value: verdictValue,
9576
+ ...host === void 0 ? {} : { span: host }
9577
+ });
9578
+ }
9579
+ const attributable = /* @__PURE__ */ new Set();
9580
+ let unattributedSpans = 0;
9581
+ for (const span of spans) {
9582
+ const recorded = (span.records ?? []).map((record) => record.ordinal).sort((a, b) => a - b);
9583
+ const rows = [...span.wires].map((wire) => wire.ordinal).sort((a, b) => a - b);
9584
+ if (span.records !== void 0 && recorded.length === rows.length && recorded.every((ordinal, index) => ordinal === rows[index])) attributable.add(span);
9585
+ else unattributedSpans += 1;
9586
+ }
9587
+ let tailWires = 0;
9588
+ for (const span of spans) {
9589
+ if (!attributable.has(span)) continue;
9590
+ const lastVerdict = span.verdictSeqs.length === 0 ? void 0 : Math.max(...span.verdictSeqs);
9591
+ if (lastVerdict === void 0) continue;
9592
+ for (const wire of span.wires) if (wire.seq > lastVerdict) tailWires += wire.wireRequests;
9593
+ }
9594
+ const candidates = [];
9595
+ let unhostedVerdicts = 0;
9596
+ const previousBoundary = /* @__PURE__ */ new Map();
9597
+ for (const verdict of verdicts) {
9598
+ const value = verdict.value;
9599
+ if (verdict.span === void 0) {
9600
+ unhostedVerdicts += 1;
9601
+ continue;
9602
+ }
9603
+ const span = verdict.span;
9604
+ const boundary = previousBoundary.get(span) ?? {
9605
+ seq: span.runningSeq,
9606
+ ...span.startedAt === void 0 ? {} : { at: span.startedAt }
9607
+ };
9608
+ const verdictAtMs = parse(verdict.at);
9609
+ previousBoundary.set(span, {
9610
+ seq: verdict.seq,
9611
+ ...verdictAtMs === void 0 ? {} : { at: verdictAtMs }
9612
+ });
9613
+ const candidate = {
9614
+ verdict: value.verdict,
9615
+ verdictSeq: verdict.seq,
9616
+ ...verdict.at === void 0 ? {} : { verdictAt: verdict.at },
9617
+ ...typeof value.callId === "string" ? { callId: value.callId } : {},
9618
+ ...typeof value.repairsUsed === "number" ? { repairsUsed: value.repairsUsed } : {},
9619
+ ...typeof value.maxRepairs === "number" ? { maxRepairs: value.maxRepairs } : {},
9620
+ ...typeof value.contractHash === "string" ? { contractHash: value.contractHash } : {},
9621
+ ...typeof value.candidateHash === "string" ? { candidateHash: value.candidateHash } : {},
9622
+ ...typeof value.candidateChars === "number" ? { candidateChars: value.candidateChars } : {},
9623
+ ...typeof value.candidateRef === "string" ? { candidateRef: value.candidateRef } : {},
9624
+ failed: Array.isArray(value.failed) ? value.failed.filter((failure) => typeof failure.name === "string").map((failure) => ({
9625
+ name: failure.name,
9626
+ reasons: Array.isArray(failure.reasons) ? failure.reasons.filter((reason) => typeof reason === "string") : []
9627
+ })) : [],
9628
+ ...span.label === void 0 ? {} : { spanLabel: span.label }
9629
+ };
9630
+ if (boundary.at !== void 0 && verdictAtMs !== void 0) candidate.windowMs = Math.max(0, verdictAtMs - boundary.at);
9631
+ if (attributable.has(span)) {
9632
+ const window = span.wires.filter((wire) => wire.seq > boundary.seq && wire.seq < verdict.seq);
9633
+ candidate.wires = window.reduce((sum, wire) => sum + wire.wireRequests, 0);
9634
+ candidate.usage = sumUsage$1(window);
9635
+ const unknown = window.filter((wire) => usageUnknown(wire)).length;
9636
+ if (unknown > 0) candidate.usageUnknownWires = unknown;
9637
+ if (priceUsd !== void 0) {
9638
+ let priced = 0;
9639
+ let complete = true;
9640
+ for (const wire of window) {
9641
+ const usd = wire.servedBy === void 0 || wire.usage === void 0 ? void 0 : priceUsd(wire.servedBy, wire.usage);
9642
+ if (usd === void 0) {
9643
+ complete = false;
9644
+ break;
9645
+ }
9646
+ priced += usd;
9647
+ }
9648
+ if (complete) candidate.costUsd = priced;
9649
+ }
9650
+ }
9651
+ candidates.push(candidate);
9652
+ }
9653
+ return {
9654
+ candidates,
9655
+ synthesisSpans: spans.length,
9656
+ unhostedVerdicts,
9657
+ unattributedSpans,
9658
+ tailWires
9659
+ };
9660
+ }
9661
+ //#endregion
9662
+ //#region src/stores/tool-calibration.ts
9663
+ /**
9664
+ * Folds the observed tool-budget calibration from a journal (RV3003):
9665
+ * every terminal agent entry is partitioned by which sides of the
9666
+ * evidence/counter pair it recorded, the paired rows carry their
9667
+ * per-dispatch rate, and the aggregate is the number a host compares
9668
+ * against its declared `estCallsPerEntry`. Pure over the entries, so
9669
+ * live and resumed journals fold identically; nothing is re-derived
9670
+ * and no checkpoint blob is read.
9671
+ */
9672
+ function toolCalibrationFromJournal(entries) {
9673
+ const ordered = [...entries].sort((a, b) => a.seq - b.seq);
9674
+ const observed = [];
9675
+ const evidenceOnly = [];
9676
+ const budgetOnly = [];
9677
+ let dispatches = 0;
9678
+ let unobserved = 0;
9679
+ for (const entry of ordered) {
9680
+ if (entry.kind !== "agent" || entry.ref === void 0 || entry.status === "running") continue;
9681
+ dispatches += 1;
9682
+ const named = {
9683
+ scope: entry.scope,
9684
+ handle: entry.ref,
9685
+ status: String(entry.status ?? "")
9686
+ };
9687
+ if (entry.evidence !== void 0 && entry.toolBudget !== void 0) observed.push({
9688
+ ...named,
9689
+ ...entry.costAttribution?.agentType === void 0 || entry.costAttribution.agentType === "" ? {} : { agentType: entry.costAttribution.agentType },
9690
+ recordedEntries: entry.evidence.recordedEntries,
9691
+ minEntries: entry.evidence.minEntries,
9692
+ toolCallsUsed: entry.toolBudget.used,
9693
+ ...entry.evidence.recordedEntries > 0 ? { callsPerEntry: entry.toolBudget.used / entry.evidence.recordedEntries } : {}
9694
+ });
9695
+ else if (entry.evidence !== void 0) evidenceOnly.push(named);
9696
+ else if (entry.toolBudget !== void 0) budgetOnly.push(named);
9697
+ else unobserved += 1;
9698
+ }
9699
+ const report = {
9700
+ dispatches,
9701
+ observed,
9702
+ evidenceOnly,
9703
+ budgetOnly,
9704
+ unobserved
9705
+ };
9706
+ if (observed.length > 0) {
9707
+ const toolCallsUsed = observed.reduce((sum, row) => sum + row.toolCallsUsed, 0);
9708
+ const recordedEntries = observed.reduce((sum, row) => sum + row.recordedEntries, 0);
9709
+ report.aggregate = {
9710
+ toolCallsUsed,
9711
+ recordedEntries,
9712
+ ...recordedEntries > 0 ? { callsPerEntry: toolCallsUsed / recordedEntries } : {}
9713
+ };
9714
+ }
9715
+ return report;
9716
+ }
9717
+ //#endregion
9456
9718
  //#region src/stores/jsonl.ts
9457
9719
  /**
9458
9720
  * JsonlFileStore (M2-T01): the durable file store. One JSON entry per
@@ -16125,6 +16387,94 @@ function statementFromRows(input) {
16125
16387
  })
16126
16388
  };
16127
16389
  }
16390
+ /**
16391
+ * Parses a delimited billing export (the CSV/TSV a provider console
16392
+ * hands a host) into the header-keyed rows {@link statementFromRows}
16393
+ * consumes (RV2908). The library deliberately hard-codes NO provider's
16394
+ * export format: the host owns the column map, this owns only the
16395
+ * delimited grammar, and the pair closes the last manual step between
16396
+ * a downloaded export and {@link reconcileStatement}.
16397
+ *
16398
+ * Fail-closed at the record, like the rest of this module: a data row
16399
+ * whose cell count differs from the header, a quote opened and never
16400
+ * closed, a stray quote inside an unquoted cell, an empty or duplicate
16401
+ * header name, all refuse typed with the line instead of flowing a
16402
+ * shifted column into a reconciliation, because a column shifted one
16403
+ * to the left prices `outputTokens` as dollars and calls it evidence.
16404
+ * RFC 4180 quoting is honored (quoted cells may carry the delimiter,
16405
+ * doubled quotes, and line breaks); CRLF and lone LF both delimit
16406
+ * records; one trailing empty line is an artifact of every exporter
16407
+ * and is ignored. Cells come back as raw strings, so an empty cell
16408
+ * reads as "the export does not carry this figure" downstream, exactly
16409
+ * the absence contract `statementFromRows` documents.
16410
+ */
16411
+ function statementRowsFromDelimited(text, options) {
16412
+ const delimiter = options?.delimiter ?? ",";
16413
+ const records = [];
16414
+ let cells = [];
16415
+ let cell = "";
16416
+ let quoted = false;
16417
+ let cellHadQuote = false;
16418
+ let line = 1;
16419
+ const endCell = () => {
16420
+ cells.push(cell);
16421
+ cell = "";
16422
+ cellHadQuote = false;
16423
+ };
16424
+ const endRecord = () => {
16425
+ endCell();
16426
+ records.push(cells);
16427
+ cells = [];
16428
+ };
16429
+ for (let index = 0; index < text.length; index += 1) {
16430
+ const char = text[index];
16431
+ if (quoted) {
16432
+ if (char === "\"") {
16433
+ if (text[index + 1] === "\"") {
16434
+ cell += "\"";
16435
+ index += 1;
16436
+ continue;
16437
+ }
16438
+ quoted = false;
16439
+ continue;
16440
+ }
16441
+ if (char === "\n") line += 1;
16442
+ cell += char;
16443
+ continue;
16444
+ }
16445
+ if (char === "\"") {
16446
+ if (cell.length > 0 || cellHadQuote) throw new ConfigError(`statementRowsFromDelimited: line ${String(line)} carries a quote inside an unquoted cell; quote the whole cell (RFC 4180) or fix the export`);
16447
+ quoted = true;
16448
+ cellHadQuote = true;
16449
+ continue;
16450
+ }
16451
+ if (char === delimiter) {
16452
+ endCell();
16453
+ continue;
16454
+ }
16455
+ if (char === "\r" && text[index + 1] === "\n") continue;
16456
+ if (char === "\n") {
16457
+ endRecord();
16458
+ line += 1;
16459
+ continue;
16460
+ }
16461
+ cell += char;
16462
+ }
16463
+ if (quoted) throw new ConfigError(`statementRowsFromDelimited: a quoted cell opened on line ${String(line)} never closes; the export is torn`);
16464
+ if (cell.length > 0 || cellHadQuote || cells.length > 0) endRecord();
16465
+ if (records.length === 0) throw new ConfigError("statementRowsFromDelimited: the export carries no header record");
16466
+ const header = records[0];
16467
+ const seen = /* @__PURE__ */ new Set();
16468
+ header.forEach((name, index) => {
16469
+ if (name.length === 0) throw new ConfigError(`statementRowsFromDelimited: header column ${String(index)} is empty; every column needs a name for the map to address`);
16470
+ if (seen.has(name)) throw new ConfigError(`statementRowsFromDelimited: header names column '${name}' twice; an ambiguous address cannot be mapped`);
16471
+ seen.add(name);
16472
+ });
16473
+ return records.slice(1).map((record, index) => {
16474
+ if (record.length !== header.length) throw new ConfigError(`statementRowsFromDelimited: data record ${String(index)} carries ${String(record.length)} cell(s) against ${String(header.length)} header column(s); a shifted column prices the wrong figure, so a ragged export refuses instead`);
16475
+ return Object.fromEntries(header.map((name, column) => [name, record[column]]));
16476
+ });
16477
+ }
16128
16478
  //#endregion
16129
16479
  //#region src/engine/persisted-terminal.ts
16130
16480
  const REFUSAL_MESSAGES = {
@@ -18049,7 +18399,13 @@ function createCtx(internals, rootWorkflow) {
18049
18399
  }
18050
18400
  {
18051
18401
  const durable = readToolBudgetDecisions(internals.replayer.snapshot(), matched.running.seq);
18052
- if (durable !== void 0 && replayedToolCallsUsed !== void 0) {
18402
+ if (terminal?.toolBudget !== void 0) {
18403
+ const restoredSummary = { used: terminal.toolBudget.used };
18404
+ if (terminal.toolBudget.cap !== void 0) restoredSummary.cap = terminal.toolBudget.cap;
18405
+ if (durable !== void 0 && durable.extensionsGranted > 0) restoredSummary.extensionsGranted = durable.extensionsGranted;
18406
+ if (durable !== void 0 && durable.finalizationWindowEntered) restoredSummary.finalizationWindowEntered = true;
18407
+ result.toolBudget = restoredSummary;
18408
+ } else if (durable !== void 0 && replayedToolCallsUsed !== void 0) {
18053
18409
  const restoredSummary = { used: replayedToolCallsUsed };
18054
18410
  if (durable.cap !== void 0) restoredSummary.cap = durable.cap;
18055
18411
  if (durable.extensionsGranted > 0) restoredSummary.extensionsGranted = durable.extensionsGranted;
@@ -18815,6 +19171,10 @@ function createCtx(internals, rootWorkflow) {
18815
19171
  if (result.artifacts !== void 0) terminalPatch.artifacts = result.artifacts;
18816
19172
  if (result.evidence !== void 0) terminalPatch.evidence = result.evidence;
18817
19173
  if (result.evidenceEntries !== void 0) terminalPatch.evidenceEntries = [...result.evidenceEntries];
19174
+ if (result.toolBudget !== void 0) terminalPatch.toolBudget = {
19175
+ used: result.toolBudget.used,
19176
+ ...result.toolBudget.cap === void 0 ? {} : { cap: result.toolBudget.cap }
19177
+ };
18818
19178
  if (result.abortClass !== void 0) {
18819
19179
  terminalPatch.memoizeOutcome = true;
18820
19180
  if (terminalPatch.error !== void 0) {
@@ -21201,6 +21561,8 @@ function pairDraftClaims(draftText, rows, options) {
21201
21561
  const max = requirePositiveInteger(options?.max ?? 40, "pairDraftClaims max");
21202
21562
  const maxPoolPerPair = requirePositiveInteger(options?.maxPoolPerPair ?? 3, "pairDraftClaims maxPoolPerPair");
21203
21563
  const maxExcerptChars = requirePositiveInteger(options?.maxExcerptChars ?? 400, "pairDraftClaims maxExcerptChars");
21564
+ const targetShare = options?.targetCoverageShare;
21565
+ if (targetShare !== void 0 && (typeof targetShare !== "number" || !Number.isFinite(targetShare) || targetShare <= 0 || targetShare > 1)) throw new ConfigError(`pairDraftClaims targetCoverageShare must be a number in (0, 1]; got ` + JSON.stringify(targetShare));
21204
21566
  const poolByPath = /* @__PURE__ */ new Map();
21205
21567
  for (const row of rows) for (const sentence of sentencesOf(row.text)) {
21206
21568
  const anchors = anchorsOf(sentence, pattern);
@@ -21292,13 +21654,37 @@ function pairDraftClaims(draftText, rows, options) {
21292
21654
  });
21293
21655
  }
21294
21656
  }
21295
- const reported = (critical === void 0 ? candidates : [...candidates.filter((candidate) => candidate.critical), ...candidates.filter((candidate) => !candidate.critical)]).slice(0, max);
21657
+ const ordered = critical === void 0 ? candidates : [...candidates.filter((candidate) => candidate.critical), ...candidates.filter((candidate) => !candidate.critical)];
21658
+ let reported;
21659
+ let maxCut;
21660
+ let targetSentences;
21661
+ if (targetShare === void 0) {
21662
+ reported = ordered.slice(0, max);
21663
+ maxCut = candidates.length > reported.length;
21664
+ } else {
21665
+ targetSentences = Math.min(draftCitingSentences, Math.ceil(targetShare * draftCitingSentences));
21666
+ const covering = /* @__PURE__ */ new Set();
21667
+ const wanted = [];
21668
+ for (const candidate of ordered) {
21669
+ if (candidate.critical) {
21670
+ wanted.push(candidate);
21671
+ covering.add(candidate.sentence);
21672
+ continue;
21673
+ }
21674
+ if (covering.size >= targetSentences || covering.has(candidate.sentence)) continue;
21675
+ wanted.push(candidate);
21676
+ covering.add(candidate.sentence);
21677
+ }
21678
+ reported = wanted.slice(0, max);
21679
+ maxCut = wanted.length > reported.length;
21680
+ }
21296
21681
  const coveredSentences = new Set(reported.map((candidate) => candidate.sentence));
21297
21682
  const fold = {
21298
21683
  pairs: reported.map((candidate) => candidate.pair),
21299
- truncated: candidates.length > reported.length,
21684
+ truncated: maxCut,
21300
21685
  draftCitingSentences,
21301
- coveredCitingSentences: coveredSentences.size
21686
+ coveredCitingSentences: coveredSentences.size,
21687
+ ...targetSentences === void 0 ? {} : { targetCoveredSentences: targetSentences }
21302
21688
  };
21303
21689
  if (critical !== void 0) {
21304
21690
  const reportedAnchors = new Set(reported.map((candidate) => candidate.pair.anchor));
@@ -22044,7 +22430,12 @@ function validateOrchestrateOptions(opts) {
22044
22430
  if (synthesis.instructions !== void 0 && typeof synthesis.instructions !== "string") throw new ConfigError(`orchestrate synthesis.instructions must be a string; got ${typeof synthesis.instructions}`);
22045
22431
  const facts = synthesis;
22046
22432
  if (facts.policyFacts !== void 0 && typeof facts.policyFacts !== "boolean") throw new ConfigError(`orchestrate synthesis.policyFacts must be a boolean; got ${typeof facts.policyFacts}`);
22047
- if (facts.runFacts !== void 0 && typeof facts.runFacts !== "boolean") throw new ConfigError(`orchestrate synthesis.runFacts must be a boolean; got ${typeof facts.runFacts}`);
22433
+ if (facts.runFacts !== void 0 && typeof facts.runFacts !== "boolean") {
22434
+ if (typeof facts.runFacts !== "object" || facts.runFacts === null || Array.isArray(facts.runFacts)) throw new ConfigError(`orchestrate synthesis.runFacts must be a boolean or { workflowSoFar?: boolean }; got ${typeof facts.runFacts}`);
22435
+ const runFactsSpec = facts.runFacts;
22436
+ for (const key of Object.keys(runFactsSpec)) if (key !== "workflowSoFar") throw new ConfigError(`orchestrate synthesis.runFacts carries unknown key '${key}'; the object form takes only workflowSoFar`);
22437
+ if (runFactsSpec["workflowSoFar"] !== void 0 && typeof runFactsSpec["workflowSoFar"] !== "boolean") throw new ConfigError(`orchestrate synthesis.runFacts.workflowSoFar must be a boolean; got ${typeof runFactsSpec["workflowSoFar"]}`);
22438
+ }
22048
22439
  if (synthesis.estCost !== void 0) requireNonNegativeNumber(synthesis.estCost, "orchestrate synthesis.estCost");
22049
22440
  }
22050
22441
  if (opts.contradictions !== void 0) {
@@ -22105,10 +22496,14 @@ function validateOrchestrateOptions(opts) {
22105
22496
  if (consistency.runFacts !== true) throw new ConfigError("orchestrate claimConsistency.runFactTerms rides the runFacts pass; set claimConsistency.runFacts true");
22106
22497
  if (!Array.isArray(consistency.runFactTerms) || consistency.runFactTerms.some((term) => typeof term !== "string" || term.length === 0)) throw new ConfigError("orchestrate claimConsistency.runFactTerms must be an array of nonempty strings; got " + JSON.stringify(consistency.runFactTerms));
22107
22498
  }
22108
- for (const [label, ratio] of [["minimumCoverageRatio", consistency.minimumCoverageRatio], ["runFactCoverageRatio", consistency.runFactCoverageRatio]]) if (ratio !== void 0 && (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio <= 0 || ratio > 1)) throw new ConfigError(`orchestrate claimConsistency.${label} must be a number in (0, 1]; got ` + JSON.stringify(ratio));
22499
+ for (const [label, ratio] of [
22500
+ ["minimumCoverageRatio", consistency.minimumCoverageRatio],
22501
+ ["runFactCoverageRatio", consistency.runFactCoverageRatio],
22502
+ ["coverageTarget", consistency.coverageTarget]
22503
+ ]) if (ratio !== void 0 && (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio <= 0 || ratio > 1)) throw new ConfigError(`orchestrate claimConsistency.${label} must be a number in (0, 1]; got ` + JSON.stringify(ratio));
22109
22504
  if (consistency.runFactCoverageRatio !== void 0 && consistency.runFacts !== true) throw new ConfigError("orchestrate claimConsistency.runFactCoverageRatio rides the runFacts pass; set claimConsistency.runFacts true");
22110
22505
  if (consistency.onLowCoverage !== void 0 && consistency.onLowCoverage !== "report" && consistency.onLowCoverage !== "fail") throw new ConfigError("orchestrate claimConsistency.onLowCoverage must be 'report' or 'fail'; got " + JSON.stringify(consistency.onLowCoverage));
22111
- if (consistency.onLowCoverage !== void 0 && consistency.minimumCoverageRatio === void 0 && consistency.runFactCoverageRatio === void 0) throw new ConfigError("orchestrate claimConsistency.onLowCoverage needs a declared floor; set minimumCoverageRatio or runFactCoverageRatio");
22506
+ if (consistency.onLowCoverage !== void 0 && consistency.minimumCoverageRatio === void 0 && consistency.runFactCoverageRatio === void 0 && consistency.coverageTarget === void 0) throw new ConfigError("orchestrate claimConsistency.onLowCoverage needs a declared floor; set minimumCoverageRatio, runFactCoverageRatio, or coverageTarget");
22112
22507
  if (consistency.judge !== void 0) {
22113
22508
  const judge = consistency.judge;
22114
22509
  if (typeof judge !== "object" || judge === null || Array.isArray(judge)) throw new ConfigError(`orchestrate claimConsistency.judge must be an object; got ${JSON.stringify(consistency.judge)}`);
@@ -23780,6 +24175,7 @@ function makeOrchestratorWorkflow(goal, opts) {
23780
24175
  const noteOpts = {
23781
24176
  role: "synthesize",
23782
24177
  result: "full",
24178
+ label: SYNTHESIS_NOTE_LABEL,
23783
24179
  tools: finishOnly,
23784
24180
  limits: spec.noteLimits ?? { maxTurns: 2 },
23785
24181
  ...spec.model === void 0 ? {} : { model: spec.model },
@@ -23787,7 +24183,10 @@ function makeOrchestratorWorkflow(goal, opts) {
23787
24183
  ...spec.estCost === void 0 ? {} : { estCost: spec.estCost },
23788
24184
  [kTerminalTool]: { name: FINISH_TOOL_NAME }
23789
24185
  };
23790
- return runtime.runInScope(noteState, () => ctx.agent(prompt, noteOpts));
24186
+ return runtime.runInScope(noteState, () => ctx.agent(prompt, noteOpts)).then((settled) => {
24187
+ noteInternalSettle(settled);
24188
+ return settled;
24189
+ });
23791
24190
  };
23792
24191
  /**
23793
24192
  * Note dispatch is idempotent per child: the settle hook and the
@@ -23945,6 +24344,33 @@ function makeOrchestratorWorkflow(goal, opts) {
23945
24344
  */
23946
24345
  let synthesisSkipDecisionRef;
23947
24346
  /**
24347
+ * The orchestration's own settled internal spans so far (RV3004):
24348
+ * the coordination dispatch, claim judges, synthesis notes, and
24349
+ * settled compositions, folded through
24350
+ * {@link executionFactsOf} in dispatch order the moment each
24351
+ * settles. Replay-stable by the same argument as the RUN FACTS
24352
+ * child line: every ingredient restores verbatim from the journal
24353
+ * and the settle order is deterministic, so a resumed composition
24354
+ * re-derives identical SO FAR bytes. A dispatch that never settled
24355
+ * (a declined judge admission, a crash) contributes nothing, which
24356
+ * is RV1209, not an undercount.
24357
+ */
24358
+ const internalSpansSoFar = {
24359
+ spans: 0,
24360
+ wireRequests: 0,
24361
+ wireIdsMissing: 0,
24362
+ inputTokens: 0,
24363
+ outputTokens: 0
24364
+ };
24365
+ const noteInternalSettle = (settled) => {
24366
+ const facts = executionFactsOf(settled);
24367
+ internalSpansSoFar.spans += 1;
24368
+ internalSpansSoFar.wireRequests += facts.wireRequests;
24369
+ internalSpansSoFar.wireIdsMissing += facts.wireIdsMissing;
24370
+ internalSpansSoFar.inputTokens += facts.inputTokens;
24371
+ internalSpansSoFar.outputTokens += facts.outputTokens;
24372
+ };
24373
+ /**
23948
24374
  * The bounded contradiction pass's findings (RV1302), set exactly
23949
24375
  * when the pass is configured: an EMPTY array is a fact (the pass
23950
24376
  * ran and the pool agreed) and `undefined` is a different fact
@@ -24116,7 +24542,8 @@ function makeOrchestratorWorkflow(goal, opts) {
24116
24542
  max: spec.max ?? 40,
24117
24543
  ...spec.maxPoolPerPair === void 0 ? {} : { maxPoolPerPair: spec.maxPoolPerPair },
24118
24544
  ...spec.maxExcerptChars === void 0 ? {} : { maxExcerptChars: spec.maxExcerptChars },
24119
- ...spec.critical === void 0 ? {} : { critical: spec.critical }
24545
+ ...spec.critical === void 0 ? {} : { critical: spec.critical },
24546
+ ...spec.coverageTarget === void 0 ? {} : { targetCoverageShare: spec.coverageTarget }
24120
24547
  });
24121
24548
  const runFold = spec.runFacts === true ? pairRunFactClaims(draftText, {
24122
24549
  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(" ")}`,
@@ -24129,7 +24556,8 @@ function makeOrchestratorWorkflow(goal, opts) {
24129
24556
  ]
24130
24557
  }, {
24131
24558
  ...spec.runFactTerms === void 0 ? {} : { terms: spec.runFactTerms },
24132
- ...spec.maxExcerptChars === void 0 ? {} : { maxExcerptChars: spec.maxExcerptChars }
24559
+ ...spec.maxExcerptChars === void 0 ? {} : { maxExcerptChars: spec.maxExcerptChars },
24560
+ ...spec.coverageTarget === void 0 ? {} : { max: Number.MAX_SAFE_INTEGER }
24133
24561
  }) : void 0;
24134
24562
  const allPairs = runFold === void 0 ? fold.pairs : [...fold.pairs, ...runFold.pairs];
24135
24563
  const onFound = spec.onFound ?? "report";
@@ -24139,6 +24567,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24139
24567
  pairs: allPairs.length,
24140
24568
  truncated: fold.truncated,
24141
24569
  coveredCitingSentences: fold.coveredCitingSentences,
24570
+ ...spec.coverageTarget === void 0 ? {} : { coverageTarget: spec.coverageTarget },
24142
24571
  ...fold.criticalUncovered === void 0 ? {} : {
24143
24572
  criticalUncovered: fold.criticalUncovered,
24144
24573
  criticalUncoveredTotal: fold.criticalUncoveredTotal ?? 0
@@ -24149,14 +24578,15 @@ function makeOrchestratorWorkflow(goal, opts) {
24149
24578
  runFactCandidates: runFold.candidates
24150
24579
  },
24151
24580
  ...(() => {
24581
+ const coverageFloor = spec.minimumCoverageRatio ?? spec.coverageTarget;
24152
24582
  const coverageRatio = fold.draftCitingSentences === 0 ? 1 : fold.coveredCitingSentences / fold.draftCitingSentences;
24153
24583
  const runFactRatio = runFold === void 0 || runFold.candidates === 0 ? void 0 : runFold.pairs.length / runFold.candidates;
24154
- const belowCoverage = spec.minimumCoverageRatio !== void 0 && fold.draftCitingSentences > 0 && coverageRatio < spec.minimumCoverageRatio;
24584
+ const belowCoverage = coverageFloor !== void 0 && fold.draftCitingSentences > 0 && coverageRatio < coverageFloor;
24155
24585
  const belowRunFacts = spec.runFactCoverageRatio !== void 0 && runFactRatio !== void 0 && runFactRatio < spec.runFactCoverageRatio;
24156
24586
  if (!belowCoverage && !belowRunFacts) return {};
24157
24587
  return { lowCoverage: {
24158
24588
  coverageRatio,
24159
- ...spec.minimumCoverageRatio === void 0 ? {} : { coverageFloor: spec.minimumCoverageRatio },
24589
+ ...coverageFloor === void 0 ? {} : { coverageFloor },
24160
24590
  ...runFactRatio === void 0 ? {} : { runFactRatio },
24161
24591
  ...spec.runFactCoverageRatio === void 0 ? {} : { runFactFloor: spec.runFactCoverageRatio }
24162
24592
  } };
@@ -24240,6 +24670,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24240
24670
  let judged;
24241
24671
  try {
24242
24672
  judged = await runtime.runInScope(judgeState, () => ctx.agent(judgePrompt, judgeOpts));
24673
+ noteInternalSettle(judged);
24243
24674
  } catch (declined) {
24244
24675
  if (!(declined instanceof BudgetExhaustedError)) throw declined;
24245
24676
  claimConsistencyMeta = finishMeta({
@@ -24557,6 +24988,8 @@ function makeOrchestratorWorkflow(goal, opts) {
24557
24988
  };
24558
24989
  });
24559
24990
  })();
24991
+ const runFactsEnabled = spec.runFacts === true || typeof spec.runFacts === "object" && spec.runFacts !== null;
24992
+ const runFactsSoFar = typeof spec.runFacts === "object" && spec.runFacts !== null && spec.runFacts.workflowSoFar === true;
24560
24993
  const prompt = [
24561
24994
  "You are the synthesis invocation of an orchestrated run. Compose the FINAL result of the run from the goal, the coordination draft, and the settled child evidence below by calling finish({ result }) EXACTLY once. Preserve the evidence and citations the draft relies on; do not invent findings. " + (exposeTools ? "Beside finish, get_child_result and read_child_artifact page any SETTLED child's FULL output and artifacts by handle (each DIGEST row carries its handle); read what the validators will hold you to before finishing." : "No other tool exists."),
24562
24995
  ...repeatedClaims === void 0 ? [] : ["Repeated claims across children were deduplicated before this prompt: only the first occurrence of each repeated line remains in the digest, and the REPEATED CLAIMS index below lists each one with its reporters."],
@@ -24586,7 +25019,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24586
25019
  finalizationReservesUsed: reservesUsed
24587
25020
  })}`;
24588
25021
  })()] : [],
24589
- ...spec.runFacts === true ? [(() => {
25022
+ ...runFactsEnabled ? [(() => {
24590
25023
  const byStatus = {};
24591
25024
  let wireRequests = 0;
24592
25025
  let wireIdsMissing = 0;
@@ -24612,6 +25045,29 @@ function makeOrchestratorWorkflow(goal, opts) {
24612
25045
  outputTokens
24613
25046
  })} (live-observed by run ${internals.runId}, this run's own harness; production evidence it is not; the settled children ONLY, excluding this orchestrator, judges, and synthesis; the whole run's totals are the terminal envelope and invoice)`;
24614
25047
  })()] : [],
25048
+ ...runFactsSoFar ? [(() => {
25049
+ let wireRequests = internalSpansSoFar.wireRequests;
25050
+ let wireIdsMissing = internalSpansSoFar.wireIdsMissing;
25051
+ let inputTokens = internalSpansSoFar.inputTokens;
25052
+ let outputTokens = internalSpansSoFar.outputTokens;
25053
+ for (const [, record] of settledEntries) {
25054
+ const facts = executionFactsOf(record.settled);
25055
+ wireRequests += facts.wireRequests;
25056
+ wireIdsMissing += facts.wireIdsMissing;
25057
+ inputTokens += facts.inputTokens;
25058
+ outputTokens += facts.outputTokens;
25059
+ }
25060
+ return `RUN FACTS SO FAR: ${JSON.stringify({
25061
+ scope: "run-so-far-at-this-dispatch",
25062
+ runId: internals.runId,
25063
+ children: settledEntries.length,
25064
+ internalSpans: internalSpansSoFar.spans,
25065
+ wireRequests,
25066
+ wireIdsMissing,
25067
+ inputTokens,
25068
+ outputTokens
25069
+ })} (live-observed by run ${internals.runId}, this run's own harness; production evidence it is not; the settled children PLUS this orchestration's settled coordination, judge, note, and composition spans as of THIS dispatch; it excludes this dispatch itself and anything still running, so the whole run's totals remain the terminal envelope and invoice)`;
25070
+ })()] : [],
24615
25071
  `GOAL: ${goal}`,
24616
25072
  `DRAFT: ${draftJson}`,
24617
25073
  `DIGEST: ${digestJson}`,
@@ -24653,6 +25109,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24653
25109
  const synthesisOpts = {
24654
25110
  role: "synthesize",
24655
25111
  result: "full",
25112
+ label: FINAL_COMPOSITION_LABEL,
24656
25113
  tools: synthesisTools,
24657
25114
  [kExposureWait]: true,
24658
25115
  limits: spec.limits ?? { maxTurns: 4 },
@@ -24668,6 +25125,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24668
25125
  }
24669
25126
  };
24670
25127
  const synthesized = await runtime.runInScope(synthesisState, () => ctx.agent(prompt, synthesisOpts));
25128
+ noteInternalSettle(synthesized);
24671
25129
  synthesisSchemaRejectedExchanges = synthesized.schemaRejectedTerminalExchanges ?? 0;
24672
25130
  synthesisSchemaRecoveredExchanges = synthesized.schemaRecoveredTerminalExchanges ?? 0;
24673
25131
  if (configuredReserveUsd > 0) {
@@ -24796,6 +25254,7 @@ function makeOrchestratorWorkflow(goal, opts) {
24796
25254
  let result;
24797
25255
  try {
24798
25256
  result = await runtime.runInScope(orchestratorState, () => ctx.agent(orchestratorPrompt(goal, opts?.maxSpawns, promptLines.length === 0 ? void 0 : promptLines), agentOpts));
25257
+ noteInternalSettle(result);
24799
25258
  } catch (thrown) {
24800
25259
  if (thrown instanceof BudgetExhaustedError) {
24801
25260
  const repairEntryRef = thrown.data?.entryRef;
@@ -27882,6 +28341,7 @@ function createEngine(options) {
27882
28341
  const handlePromise = (async () => {
27883
28342
  if (resumeOptions?.run?.budgetUsd !== void 0) requireNonNegativeNumber(resumeOptions.run.budgetUsd, "ResumeOptions.run.budgetUsd");
27884
28343
  if (resumeOptions?.run?.maxInFlightExposureUsd !== void 0) requireNonNegativeNumber(resumeOptions.run.maxInFlightExposureUsd, "ResumeOptions.run.maxInFlightExposureUsd");
28344
+ if (resumeOptions?.bodyHash !== void 0 && resumeOptions.bodyHash !== "warn" && resumeOptions.bodyHash !== "refuse") throw new ConfigError(`ResumeOptions.bodyHash must be 'warn' or 'refuse'; got ` + JSON.stringify(resumeOptions.bodyHash));
27885
28345
  const meta = await readRunMeta(journal, runId);
27886
28346
  let supplied = wf;
27887
28347
  if (supplied === void 0 && meta?.workflowSourceRef === void 0) {
@@ -27910,10 +28370,13 @@ function createEngine(options) {
27910
28370
  if (meta?.workflowHash !== void 0 && meta.workflowHash !== expectedHash) throw new ConfigError(`resume binding mismatch: the supplied CompiledWorkflow source hash differs from the one recorded for run '${runId}'`);
27911
28371
  } else {
27912
28372
  const expectedHash = hashWorkflowBody(supplied);
27913
- if (meta?.workflowHash !== void 0 && meta.workflowHash !== expectedHash) process.emitWarning(`resume: the body of workflow '${supplied.name}' changed since run '${runId}' started; orphans and misses will be reported honestly`, {
27914
- code: "RULVAR_RESUME_HASH_MISMATCH",
27915
- type: "RulvarWarning"
27916
- });
28373
+ if (meta?.workflowHash !== void 0 && meta.workflowHash !== expectedHash) {
28374
+ if (resumeOptions?.bodyHash === "refuse") throw new ConfigError(`resume: the body of workflow '${supplied.name}' changed since run '${runId}' started and ResumeOptions.bodyHash is 'refuse'; resume with the original body, or drop the option to proceed under the loud warning`);
28375
+ process.emitWarning(`resume: the body of workflow '${supplied.name}' changed since run '${runId}' started; orphans and misses will be reported honestly`, {
28376
+ code: "RULVAR_RESUME_HASH_MISMATCH",
28377
+ type: "RulvarWarning"
28378
+ });
28379
+ }
27917
28380
  }
27918
28381
  bound = supplied;
27919
28382
  }
@@ -28411,4 +28874,4 @@ function createSandboxBridge(ctx, options) {
28411
28874
  };
28412
28875
  }
28413
28876
  //#endregion
28414
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_AUTHORITY_HASH, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EXPOSURE_WAIT_SWEEP_MS, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, 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, JournalMatcher, JournalMissError, JournalOrderViolation, JournalSealedError, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, sectionPatternCountValidator, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolAuthority, toolContract, toolContractHash, toolsetAuthorityHash, toolsetHash, ttlState, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
28877
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_AUTHORITY_HASH, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EXPOSURE_WAIT_SWEEP_MS, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINAL_COMPOSITION_LABEL, FINISH_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, JournalMatcher, JournalMissError, JournalOrderViolation, JournalSealedError, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SYNTHESIS_NOTE_LABEL, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, sectionCitationsValidator, sectionPatternCountValidator, 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, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.231.0",
3
+ "version": "1.233.0",
4
4
  "description": "Rulvar core: L0 contracts, journal kernel, ctx primitives, agent runtime, model router, tool system, dynamic orchestrator, InMemory and JSONL stores, event stream.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",