@rulvar/core 1.106.0 → 1.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -5978,8 +5978,9 @@ declare class AdmissionController {
5978
5978
  declare function buildCostReport(attribution: CostAttribution, totalUsd: number, abandoned?: CostReport["abandoned"]): CostReport;
5979
5979
  /**
5980
5980
  * The pure journal fold: the complete CostReport from terminal entries,
5981
- * the same summation the kernel ledger uses (terminal usage exactly
5982
- * once, priced per servedBy slice, abandoned subtrees contribute zero).
5981
+ * the same summation the kernel ledger uses (each terminal entry's
5982
+ * usage enters the sum once, priced per servedBy slice, abandoned
5983
+ * subtrees contribute zero).
5983
5984
  * The orchestrator block folds too: spend attributed to the
5984
5985
  * orchestrator sub-account, the reserve-funded share of it, the armed
5985
5986
  * wake count, and the at-cap freeze flag from the journaled cap
@@ -6873,7 +6874,14 @@ declare const DEFAULT_EVIDENCE_MIN_SHARE = .95;
6873
6874
  * list the missing (and unknown) citations, capped at 20, so the repair
6874
6875
  * turn can restore them. Purely textual and deterministic; checking
6875
6876
  * that cited targets EXIST on disk is host territory (a custom
6876
- * validator), not this contract. Default name 'evidence-preserved'.
6877
+ * validator), not this contract. Intake is fail closed (RV610): a
6878
+ * pattern that can match the empty string is refused typed (an empty
6879
+ * match would enter the pool as fabricated evidence and defeat
6880
+ * `requireNonEmptyPool`), zero-length matches never enter the pool
6881
+ * even when a lookaround produces them in context, and the strict-mode
6882
+ * booleans must be real booleans, so a stray `'true'` can never
6883
+ * silently disable the mode it names. Default name
6884
+ * 'evidence-preserved'.
6877
6885
  */
6878
6886
  declare function evidencePreservedValidator(options?: {
6879
6887
  pattern?: string;
@@ -9460,6 +9468,27 @@ interface AppliedPricingRow {
9460
9468
  model: ModelRef;
9461
9469
  rates: Pricing;
9462
9470
  }
9471
+ /**
9472
+ * One pin's coverage (RV611): the run-settle that recorded it, the seq
9473
+ * range it settled FIRST, and exactly the version and rows it pinned.
9474
+ * The whole array is the per-segment provenance a single last-pin
9475
+ * version used to hide: an invoice folded over a rotation can now say
9476
+ * every table version that priced it, with the boundary seqs.
9477
+ */
9478
+ interface PinnedPricingSegment {
9479
+ /**
9480
+ * The first seq this pin covers: the previous pin's settle seq, 0 for
9481
+ * the first pin. Rows with `fromSeq <= seq < settleSeq` price under
9482
+ * this pin in the seq-aware fold.
9483
+ */
9484
+ fromSeq: number;
9485
+ /** The pinning run-settle's own seq (the exclusive upper bound). */
9486
+ settleSeq: number;
9487
+ /** The PriceTable version THIS settle pinned; absent for caps-only rows. */
9488
+ pricingVersion?: string;
9489
+ /** The applied rows THIS settle pinned. */
9490
+ rows: AppliedPricingRow[];
9491
+ }
9463
9492
  /** What `journalPricingSnapshot` rebuilds from a pinned run settle. */
9464
9493
  interface JournalPricingSnapshot {
9465
9494
  /** The PriceTable version of the LAST pin; absent for caps-only rows. */
@@ -9473,6 +9502,13 @@ interface JournalPricingSnapshot {
9473
9502
  */
9474
9503
  pinnedThroughSeq: number;
9475
9504
  /**
9505
+ * Every pin in journal order (RV611): boundaries, versions, and rows,
9506
+ * not only the last. This is the honest provenance for a fold across
9507
+ * a price-table rotation: consumers exporting `pricingVersion` alone
9508
+ * silently hid that different segments priced under different tables.
9509
+ */
9510
+ segments: PinnedPricingSegment[];
9511
+ /**
9476
9512
  * Prices usage with the PINNED rows only: a model absent from the
9477
9513
  * snapshot folds as unpriced (surfaced, never a silent zero), exactly
9478
9514
  * the honesty contract of the live fold. With a `seq`, the row is
@@ -9483,6 +9519,24 @@ interface JournalPricingSnapshot {
9483
9519
  * historical behavior.
9484
9520
  */
9485
9521
  priceUsd: (servedBy: ModelRef, usage: Usage, seq?: number) => number | undefined;
9522
+ /**
9523
+ * THE composition the engine's outcome mirror applies at settle
9524
+ * (RV611), exported so stored consumers (the CLI cost and invoice
9525
+ * views, the server cost endpoint) fold exactly like the engine
9526
+ * instead of passing the raw snapshot: a pin-covered row (`seq <
9527
+ * pinnedThroughSeq`) prices under the pin of its own segment; the
9528
+ * tail past the last pin (a segment journaled but not yet settled,
9529
+ * the crashed-mid-flight shape) and seq-less calls price at `current`
9530
+ * alone, exactly like the live debits that tail will settle with,
9531
+ * never silently at the last pin's rates. Two deliberate fallbacks,
9532
+ * both documented rather than hidden: a covered model its covering
9533
+ * pin missed back-reprices at the LAST pin when that pin names it
9534
+ * (the journal never recorded what those debits actually cost), and
9535
+ * otherwise falls to `current` (today's table may know a model the
9536
+ * run's tables never priced); a model neither names folds as
9537
+ * unpriced, surfaced, never a silent zero.
9538
+ */
9539
+ composedPriceUsd: (current: (servedBy: ModelRef, usage: Usage) => number | undefined) => (servedBy: ModelRef, usage: Usage, seq?: number) => number | undefined;
9486
9540
  }
9487
9541
  /**
9488
9542
  * The read side. Every settling segment pins the union it applied, and
@@ -9550,17 +9604,34 @@ interface InvoiceRow {
9550
9604
  reconciliation: InvoiceReconciliation;
9551
9605
  }
9552
9606
  /**
9553
- * Where the fold's rates came from (RV407): `snapshot` says the caller
9554
- * priced with the run-settle pin (`journalPricingSnapshot`), so these
9555
- * numbers are stable against later table updates; `current-table` says
9556
- * the live table priced it, the historical behavior. Attached by the
9557
- * caller, who is the one that chose.
9607
+ * Where the fold's rates came from (RV407): `composed` says the caller
9608
+ * priced with the snapshot's `composedPriceUsd` (RV611), the engine's
9609
+ * own composition, so pin-covered rows reproduce the settled numbers
9610
+ * and anything past the last pin priced at the caller's current table;
9611
+ * `snapshot` says the caller priced with the raw pinned rows alone
9612
+ * (the pre-RV611 label); `current-table` says the live table priced
9613
+ * it, the historical behavior for journals without a pin. Attached by
9614
+ * the caller, who is the one that chose.
9558
9615
  */
9559
9616
  interface InvoicePricingProvenance {
9560
- source: "snapshot" | "current-table";
9617
+ source: "snapshot" | "current-table" | "composed";
9561
9618
  pricingVersion?: string | undefined;
9562
9619
  /** The pinned rows the fold used; present on snapshot-priced exports. */
9563
9620
  rows?: AppliedPricingRow[] | undefined;
9621
+ /**
9622
+ * Per-pin coverage (RV611): every settled segment's version and rows
9623
+ * with its seq boundaries, not only the last. A fold across a
9624
+ * price-table rotation used to export one `pricingVersion` while its
9625
+ * rows priced under several; this array is the honest declaration.
9626
+ */
9627
+ segments?: PinnedPricingSegment[] | undefined;
9628
+ /**
9629
+ * On `composed` exports: the last pin's settle seq. Rows at or past
9630
+ * it (a segment journaled but not yet settled) priced at the current
9631
+ * table, not any pin; each row's `entrySeq` locates it against this
9632
+ * bound.
9633
+ */
9634
+ pinnedThroughSeq?: number | undefined;
9564
9635
  }
9565
9636
  /** The machine-readable invoice: rows plus the ledger totals. */
9566
9637
  interface InvoiceExport {
@@ -10475,4 +10546,4 @@ interface SandboxBridge {
10475
10546
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
10476
10547
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
10477
10548
  //#endregion
10478
- export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, 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, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, 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, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, 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_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FencedCodeMode, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, type FinalizationWindowBudget, FinishContract, FinishContractCitations, FinishContractGoldenReject, FinishContractManifest, FinishInfo, FinishSelfTestFailure, FinishSelfTestFixtures, FinishSelfTestReport, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, 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, JournalSerializationContext, JournalSerializationHook, type JournalStore, 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, LogicalTaskId, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, 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, 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, type PhaseRow, PhaseTarget, PipelineCollected, PipelineOpts, PlanInvariantError, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, 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_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, RateLimitObservation, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, 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, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, Semaphore, SerializationHook, Settled, SettlementError, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StepIdentityInput, StructuredOutputTier, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TerminalPatch, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, 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, 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, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, finishContract, foldTermination, 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, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, preflightEstimate, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, 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, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, stripFencedBlocks, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
10549
+ export { AWAIT_SCHEMA, AbandonAttempt, AbandonFold, AbandonPayload, AbandonedSpendView, AbortClass, 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, BriefOpts, BudgetAccountView, BudgetDefaults, BudgetExhaustedError, BudgetExhaustionDiagnostics, BudgetHooks, BudgetReserve, type Bytes, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, CacheHint, CacheTtl, CanUseTool, CanonicalId, CanonicalIdentity, CanonicalLadderSpec, CanonicalModelSpec, ChatEvent, ChatRequest, CheckpointState, ChildArtifactPage, ChildIdentityInput, ChildResultPage, type ClaimClass, type ClaimOp, type ClaimStatus, ClaimValidationOptions, CollectOpts, CollectedTurn, CompactionConfig, CompiledPermissionChain, CompiledWorkflow, ConfigError, type CoreEvents, CostAttribution, CostAttributionFacts, CostReport, CreateEngineOptions, type CriticalPath, Ctx, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_DEPTH, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_REVISIONS_PER_RUN, 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, DeclaredLadder, DedupIndex, DedupNote, DedupedClaims, DerivedKey, DeriverRegistry, type DeterminismConfig, DeterminismError, type DeterminismEvents, type DeterminismMode, DispositionRule, DispositionTable, DonorCandidate, DonorRef, DroppedItem, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, 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_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FencedCodeMode, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, type FinalizationWindowBudget, FinishContract, FinishContractCitations, FinishContractGoldenReject, FinishContractManifest, FinishInfo, FinishSelfTestFailure, FinishSelfTestFixtures, FinishSelfTestReport, FinishValidationChild, FinishValidationInput, FinishValidationSpec, FinishValidationVerdict, FinishValidator, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, Gate, GateAudit, type GateRecord, GitWorktreeProvider, GitWorktreeProviderOptions, GraftBoot, HashVersion, HookVerdict, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IdentityInput, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, IncrementalSynthesisResult, InvalidResolutionError, InvocationRole, type InvocationTable, 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, JournalSerializationContext, JournalSerializationHook, type JournalStore, 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, LogicalTaskId, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_DEPTH_CEILING, 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, 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, type PhaseRow, PhaseTarget, type PinnedPricingSegment, PipelineCollected, PipelineOpts, PlanInvariantError, PreflightAdmissionRow, PreflightFinding, PreflightInput, PreflightOrchestratorSpec, PreflightReport, PreflightSpawnReport, PreflightSpawnSpec, PreflightToolCeiling, PriceTable, PricedUsage, type Pricing, type PricingTier, ProgressReport, type ProviderAdapter, ProviderCallRecord, 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_PROFILES, RUN_SETTLE_DECISION_TYPE, RandIdentityInput, RandPayload, RateLimitObservation, ReconcileOptions, ReconcileResult, RefEntryAppender, RefEntryClassification, RefusalInfo, 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, type RunFilter, RunHandle, RunInternals, type RunMeta, RunOptions, RunOutcome, RunProfile, RunStateAudit, RunStatus, RuntimeEventSink, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, Semaphore, SerializationHook, Settled, SettlementError, ShellPatternRules, ShellSegment, ShellVerdict, SinglePhaseAppend, SpanMinter, SpanRegistry, SpawnAdmissionValue, SpawnAgentParams, SpawnKey, SpawnLineage, SpawnLineageOpt, SpawnOrigin, SpawnRecord, Spend, Stage, type StandardJSONSchemaV1, type StandardSchemaV1, StepIdentityInput, StructuredOutputTier, SuspendedAppend, SuspensionState, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, TerminalPatch, TerminationAccount, TerminationAccountSnapshot, TerminationDeniedValue, TerminationDeniedWriter, TerminationInitValue, TerminationLimits, TerminationResource, 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, 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, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, atCompactionThreshold, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidencePreservedValidator, executeWorkflow, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, finishContract, foldTermination, 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, makeOrchestratorWorkflow, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, parallelScope, parseModelRef, parseScopePath, phiInitialOf, pipelineScope, planNodeScope, preflightEstimate, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reduceAuditTrail, reduceCriticalPath, 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, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, stripFencedBlocks, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
package/dist/index.js CHANGED
@@ -2363,6 +2363,7 @@ function entryUsageSlices(entry) {
2363
2363
  usage: entry.usage
2364
2364
  }];
2365
2365
  }
2366
+ const foldOverflow = (seq, servedBy) => new ConfigError(`cost accounting overflow: the price sum for entry seq ${String(seq)} became non-finite at model ${servedBy} (individually finite prices overflowed); no public report may carry a non-finite number`);
2366
2367
  /**
2367
2368
  * The single pricing fold over one terminal entry, shared by the kernel
2368
2369
  * ledger and the CostReport fold so a run's total and its per-model
@@ -2388,6 +2389,7 @@ function priceEntryUsage(entry, priceUsd) {
2388
2389
  continue;
2389
2390
  }
2390
2391
  result.usd += usd;
2392
+ if (!Number.isFinite(result.usd)) throw foldOverflow(entry.seq, slice.servedBy);
2391
2393
  result.priced.push({
2392
2394
  ...slice,
2393
2395
  usd
@@ -2486,6 +2488,7 @@ function priceEntryBilling(entry, priceUsd) {
2486
2488
  continue;
2487
2489
  }
2488
2490
  usd += price;
2491
+ if (!Number.isFinite(usd)) throw foldOverflow(entry.seq, record.servedBy);
2489
2492
  units.push({
2490
2493
  source: "call",
2491
2494
  servedBy: record.servedBy,
@@ -2512,6 +2515,7 @@ function priceEntryBilling(entry, priceUsd) {
2512
2515
  continue;
2513
2516
  }
2514
2517
  usd += price;
2518
+ if (!Number.isFinite(usd)) throw foldOverflow(entry.seq, slice.servedBy);
2515
2519
  units.push({
2516
2520
  source: "slice",
2517
2521
  servedBy: slice.servedBy,
@@ -2827,6 +2831,31 @@ function validateEvidenceContract(value, site) {
2827
2831
  if (overheadCalls !== void 0) requireNonNegativeInteger(overheadCalls, `${site}.overheadCalls`);
2828
2832
  if (enforce !== void 0 && enforce !== "warn" && enforce !== "refuse") throw new ConfigError(`${site}.enforce must be 'warn' or 'refuse'; got ${JSON.stringify(enforce)}`);
2829
2833
  }
2834
+ /**
2835
+ * Walks a finished public accounting object (a cost report, an
2836
+ * invoice) and throws a typed ConfigError on the first non-finite
2837
+ * number (RV610): JSON serializes Infinity and NaN as null, so a
2838
+ * non-finite value in a published report is silent telemetry
2839
+ * corruption, never a representable answer. Individually finite
2840
+ * amounts can overflow in accumulation, which is exactly why the
2841
+ * boundary is guarded and not only the per-item validations.
2842
+ */
2843
+ function requireFiniteNumbersDeep(value, site) {
2844
+ const walk = (node, path) => {
2845
+ if (typeof node === "number") {
2846
+ if (!Number.isFinite(node)) throw new ConfigError(`cost accounting overflow at ${path}: the value is ${String(node)}; no public report or invoice may carry a non-finite number (JSON would serialize it as null)`);
2847
+ return;
2848
+ }
2849
+ if (Array.isArray(node)) {
2850
+ node.forEach((item, index) => {
2851
+ walk(item, `${path}[${String(index)}]`);
2852
+ });
2853
+ return;
2854
+ }
2855
+ if (typeof node === "object" && node !== null) for (const [key, item] of Object.entries(node)) walk(item, `${path}.${key}`);
2856
+ };
2857
+ walk(value, site);
2858
+ }
2830
2859
  //#endregion
2831
2860
  //#region src/knowledge/file-store.ts
2832
2861
  /**
@@ -8310,8 +8339,9 @@ function buildCostReport(attribution, totalUsd, abandoned = {
8310
8339
  }
8311
8340
  /**
8312
8341
  * The pure journal fold: the complete CostReport from terminal entries,
8313
- * the same summation the kernel ledger uses (terminal usage exactly
8314
- * once, priced per servedBy slice, abandoned subtrees contribute zero).
8342
+ * the same summation the kernel ledger uses (each terminal entry's
8343
+ * usage enters the sum once, priced per servedBy slice, abandoned
8344
+ * subtrees contribute zero).
8315
8345
  * The orchestrator block folds too: spend attributed to the
8316
8346
  * orchestrator sub-account, the reserve-funded share of it, the armed
8317
8347
  * wake count, and the at-cap freeze flag from the journaled cap
@@ -8370,7 +8400,7 @@ function costReportFromJournal(entries, priceUsd) {
8370
8400
  if (facts.finalizeReserve === true) reserveUsedUsd += priced.usd;
8371
8401
  }
8372
8402
  }
8373
- return {
8403
+ const report = {
8374
8404
  totalUsd,
8375
8405
  grossUsd: totalUsd + abandonedUsd,
8376
8406
  abandoned: {
@@ -8392,6 +8422,8 @@ function costReportFromJournal(entries, priceUsd) {
8392
8422
  unpriced,
8393
8423
  ...usageApprox ? { usageApprox: true } : {}
8394
8424
  };
8425
+ requireFiniteNumbersDeep(report, "costReport");
8426
+ return report;
8395
8427
  }
8396
8428
  //#endregion
8397
8429
  //#region src/engine/invoice.ts
@@ -8628,7 +8660,7 @@ function invoiceFromJournal(entries, priceUsd, options) {
8628
8660
  }
8629
8661
  const unallocatedUsd = allocateRows(rows, entries, priceUsd, report.grossUsd);
8630
8662
  const usageApprox = report.usageApprox === true || report.abandoned.usageApprox === true;
8631
- return {
8663
+ const invoice = {
8632
8664
  rows,
8633
8665
  totalUsd: report.grossUsd,
8634
8666
  netUsd: report.totalUsd,
@@ -8645,6 +8677,8 @@ function invoiceFromJournal(entries, priceUsd, options) {
8645
8677
  ...usageApprox ? { usageApprox: true } : {},
8646
8678
  ...options?.pricing === void 0 ? {} : { pricing: options.pricing }
8647
8679
  };
8680
+ requireFiniteNumbersDeep(invoice, "invoice");
8681
+ return invoice;
8648
8682
  }
8649
8683
  //#endregion
8650
8684
  //#region src/model/pricing.ts
@@ -8767,39 +8801,44 @@ function pinnedRows(value) {
8767
8801
  */
8768
8802
  function journalPricingSnapshot(entries) {
8769
8803
  const pins = [];
8770
- let last;
8771
8804
  for (const entry of entries) {
8772
8805
  if (entry?.kind !== "decision") continue;
8773
8806
  const value = entry.value;
8774
8807
  if (value?.decisionType !== "run_settle") continue;
8775
8808
  const rows = pinnedRows(value);
8776
8809
  if (rows === void 0) continue;
8777
- const byModel = new Map(rows.map((row) => [row.model, row.rates]));
8778
8810
  pins.push({
8779
8811
  seq: entry.seq,
8780
- byModel
8781
- });
8782
- last = {
8812
+ byModel: new Map(rows.map((row) => [row.model, row.rates])),
8783
8813
  rows,
8784
- byModel,
8785
8814
  ...typeof value.pricingVersion === "string" ? { pricingVersion: value.pricingVersion } : {}
8786
- };
8815
+ });
8787
8816
  }
8817
+ const last = pins[pins.length - 1];
8788
8818
  if (last === void 0) return;
8789
8819
  const lastByModel = last.byModel;
8820
+ const pinnedThroughSeq = last.seq;
8790
8821
  const ratesFor = (servedBy, seq) => {
8791
8822
  if (seq === void 0) return lastByModel.get(servedBy);
8792
8823
  for (const pin of pins) if (pin.seq > seq) return pin.byModel.get(servedBy) ?? lastByModel.get(servedBy);
8793
8824
  return lastByModel.get(servedBy);
8794
8825
  };
8826
+ const priceUsd = (servedBy, usage, seq) => {
8827
+ const rates = ratesFor(servedBy, seq);
8828
+ return rates === void 0 ? void 0 : priceUsdOf(rates, usage);
8829
+ };
8795
8830
  return {
8796
8831
  ...last.pricingVersion === void 0 ? {} : { pricingVersion: last.pricingVersion },
8797
8832
  rows: last.rows,
8798
- pinnedThroughSeq: pins[pins.length - 1]?.seq ?? 0,
8799
- priceUsd: (servedBy, usage, seq) => {
8800
- const rates = ratesFor(servedBy, seq);
8801
- return rates === void 0 ? void 0 : priceUsdOf(rates, usage);
8802
- }
8833
+ pinnedThroughSeq,
8834
+ segments: pins.map((pin, index) => ({
8835
+ fromSeq: index === 0 ? 0 : pins[index - 1]?.seq ?? 0,
8836
+ settleSeq: pin.seq,
8837
+ ...pin.pricingVersion === void 0 ? {} : { pricingVersion: pin.pricingVersion },
8838
+ rows: pin.rows
8839
+ })),
8840
+ priceUsd,
8841
+ composedPriceUsd: (current) => (servedBy, usage, seq) => seq !== void 0 && seq < pinnedThroughSeq ? priceUsd(servedBy, usage, seq) ?? current(servedBy, usage) : current(servedBy, usage)
8803
8842
  };
8804
8843
  }
8805
8844
  //#endregion
@@ -16510,26 +16549,39 @@ function listCitations(values) {
16510
16549
  * list the missing (and unknown) citations, capped at 20, so the repair
16511
16550
  * turn can restore them. Purely textual and deterministic; checking
16512
16551
  * that cited targets EXIST on disk is host territory (a custom
16513
- * validator), not this contract. Default name 'evidence-preserved'.
16552
+ * validator), not this contract. Intake is fail closed (RV610): a
16553
+ * pattern that can match the empty string is refused typed (an empty
16554
+ * match would enter the pool as fabricated evidence and defeat
16555
+ * `requireNonEmptyPool`), zero-length matches never enter the pool
16556
+ * even when a lookaround produces them in context, and the strict-mode
16557
+ * booleans must be real booleans, so a stray `'true'` can never
16558
+ * silently disable the mode it names. Default name
16559
+ * 'evidence-preserved'.
16514
16560
  */
16515
16561
  function evidencePreservedValidator(options) {
16516
16562
  const pattern = options?.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
16517
16563
  const flags = options?.flags ?? "";
16518
16564
  const globalFlags = flags.includes("g") ? flags : `${flags}g`;
16565
+ let probe;
16519
16566
  try {
16520
- new RegExp(pattern, globalFlags);
16567
+ probe = new RegExp(pattern, flags.replace("g", ""));
16521
16568
  } catch (thrown) {
16522
16569
  throw new ConfigError(`evidencePreservedValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
16523
16570
  }
16571
+ if (probe.test("")) throw new ConfigError(`evidencePreservedValidator pattern must not be able to match the empty string (an empty match would enter the citation pool as fabricated evidence); got ${JSON.stringify(pattern)}`);
16524
16572
  const minShare = options?.minShare ?? .95;
16525
16573
  if (typeof minShare !== "number" || !Number.isFinite(minShare) || minShare <= 0 || minShare > 1) throw new ConfigError(`evidencePreservedValidator minShare must be a number in (0, 1]; got ${String(minShare)}`);
16574
+ for (const option of ["requireKnown", "requireNonEmptyPool"]) {
16575
+ const value = options?.[option];
16576
+ if (value !== void 0 && typeof value !== "boolean") throw new ConfigError(`evidencePreservedValidator ${option} must be a boolean when given; got ${JSON.stringify(value)}`);
16577
+ }
16526
16578
  return {
16527
16579
  name: options?.name ?? "evidence-preserved",
16528
16580
  validate: (input) => {
16529
16581
  const cited = /* @__PURE__ */ new Set();
16530
16582
  for (const child of input.children ?? []) {
16531
16583
  if (child.status !== "ok" && child.salvageableOutput !== true) continue;
16532
- for (const match of child.text.match(new RegExp(pattern, globalFlags)) ?? []) cited.add(match);
16584
+ for (const match of child.text.match(new RegExp(pattern, globalFlags)) ?? []) if (match.length > 0) cited.add(match);
16533
16585
  }
16534
16586
  const reasons = [];
16535
16587
  if (cited.size === 0 && options?.requireNonEmptyPool === true) reasons.push("empty child citation pool: no ok child output contains a citation matching the pattern");
@@ -16539,7 +16591,7 @@ function evidencePreservedValidator(options) {
16539
16591
  if (preserved < Math.ceil(minShare * cited.size - 1e-9)) reasons.push(`evidence preservation ${String(preserved)} of ${String(cited.size)} child citations is below the required share ${String(minShare)}; missing: ${listCitations(missing)}`);
16540
16592
  }
16541
16593
  if (options?.requireKnown === true) {
16542
- const fabricated = [...new Set(input.text.match(new RegExp(pattern, globalFlags)) ?? [])].filter((citation) => !cited.has(citation));
16594
+ const fabricated = [...new Set(input.text.match(new RegExp(pattern, globalFlags)) ?? [])].filter((citation) => citation.length > 0 && !cited.has(citation));
16543
16595
  if (fabricated.length > 0) reasons.push(`unknown citations not present in any child report: ${listCitations(fabricated)}`);
16544
16596
  }
16545
16597
  return reasons.length === 0 ? ok : {
@@ -21107,7 +21159,7 @@ function createEngine(options) {
21107
21159
  }
21108
21160
  const ledger = replayer.ledger();
21109
21161
  const pinned = journalPricingSnapshot(replayer.snapshot());
21110
- const mirrorPriceUsd = (servedBy, usage, seq) => pinned !== void 0 && seq !== void 0 && seq < pinned.pinnedThroughSeq ? pinned.priceUsd(servedBy, usage, seq) ?? priceUsd(servedBy, usage) : priceUsd(servedBy, usage);
21162
+ const mirrorPriceUsd = pinned === void 0 ? (servedBy, usage) => priceUsd(servedBy, usage) : pinned.composedPriceUsd((servedBy, usage) => priceUsd(servedBy, usage));
21111
21163
  const outcome = {
21112
21164
  status,
21113
21165
  dropped: internals.dropped,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.106.0",
3
+ "version": "1.108.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",