@rulvar/core 1.220.0 → 1.222.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
@@ -8140,6 +8140,49 @@ declare function evidencePreservedValidator(options?: {
8140
8140
  name?: string;
8141
8141
  }): FinishValidator;
8142
8142
  /**
8143
+ * One counted per-section pattern demand of
8144
+ * {@link sectionPatternCountValidator} (RV2206).
8145
+ */
8146
+ interface SectionPatternEntry {
8147
+ /** The section marker the demand binds to. */
8148
+ section: string;
8149
+ /**
8150
+ * Regex source. A capture group makes the count DISTINCT by the
8151
+ * first capture (the parity contract's N01..N48 ids count once
8152
+ * each, however often an id repeats); without a capture the raw
8153
+ * match count applies.
8154
+ */
8155
+ pattern: string;
8156
+ flags?: string;
8157
+ /** Matches (distinct captures when capturing) required in the slice. */
8158
+ min: number;
8159
+ /** Short human name for reasons (e.g. 'numbered negative scenarios'). */
8160
+ label?: string;
8161
+ }
8162
+ /**
8163
+ * Counted collections inside named sections (RV2206, the subscription
8164
+ * parity series). The engine validated citations per section since the
8165
+ * v1.71 review, but the numbered collections the parity contract
8166
+ * demands (48 N-case ids, 16 counterexample ids) were policed by
8167
+ * nothing: the second accepted dossier carried 0 and 0 against an
8168
+ * instruction naming both, and only a runner-side format pre-teach
8169
+ * closed the gap, by hope rather than contract. Each entry slices its
8170
+ * section exactly like sectionCitationsValidator (first marker
8171
+ * occurrence to the next marker in position order) and counts matches,
8172
+ * DISTINCT by first capture when the pattern captures; the reasons
8173
+ * name the section, the label, the found count against the minimum,
8174
+ * and with a capturing pattern the missing count in ids, so a repair
8175
+ * turn knows exactly what to add (the RV2105 lesson). Default name
8176
+ * 'section-pattern-counts'.
8177
+ */
8178
+ declare function sectionPatternCountValidator(options: {
8179
+ sections: readonly string[];
8180
+ entries: readonly SectionPatternEntry[];
8181
+ name?: string;
8182
+ match?: SectionMatchMode;
8183
+ fencedCode?: FencedCodeMode;
8184
+ }): FinishValidator;
8185
+ /**
8143
8186
  * Requires at least `min` matches of `pattern` INSIDE every named
8144
8187
  * section (the v1.71 experiment review, P1.2: a total citation count
8145
8188
  * hides sections carrying zero provenance). A section's slice runs
@@ -8594,6 +8637,24 @@ interface FinishContractCitations {
8594
8637
  */
8595
8638
  sample?: string;
8596
8639
  }
8640
+ /** One counted per-section collection demand (RV2206). */
8641
+ interface FinishContractSectionPattern {
8642
+ /** A declared section marker this demand binds to. */
8643
+ section: string;
8644
+ /** Regex source; a capture group makes counting DISTINCT by first capture. */
8645
+ pattern: string;
8646
+ flags?: string;
8647
+ /** Matches (distinct captures when capturing) required inside the section. */
8648
+ min: number;
8649
+ /**
8650
+ * Literal matches for the golden fixtures and the prompt. Single
8651
+ * line each; with a capturing pattern they must together carry at
8652
+ * least `min` distinct captures.
8653
+ */
8654
+ samples: string[];
8655
+ /** Short human name for prompts and reasons. */
8656
+ label?: string;
8657
+ }
8597
8658
  /**
8598
8659
  * The single source of truth of a textual finish contract: what the
8599
8660
  * prompt promises IS what the validators enforce. Declare only textual
@@ -8622,6 +8683,16 @@ interface FinishContractManifest {
8622
8683
  /** Citation demands over the result text. */
8623
8684
  citations?: FinishContractCitations;
8624
8685
  /**
8686
+ * Counted collections inside named sections (RV2206): each entry
8687
+ * demands at least `min` matches of `pattern` inside `section`'s
8688
+ * slice, DISTINCT by first capture when the pattern captures.
8689
+ * Requires `sections`. The `samples` are literal matches embedded in
8690
+ * the golden fixtures and quoted by the prompt: with a capturing
8691
+ * pattern they must carry at least `min` DISTINCT captures, because
8692
+ * the accept skeleton must itself satisfy the demand.
8693
+ */
8694
+ sectionPatterns?: FinishContractSectionPattern[];
8695
+ /**
8625
8696
  * Whether fenced code blocks count (cycle 74): 'counted' (the
8626
8697
  * default) or 'excluded' (fenced code is removed before section
8627
8698
  * matching, slicing, word counting, and citation matching, so code
@@ -14118,4 +14189,4 @@ interface SandboxBridge {
14118
14189
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
14119
14190
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
14120
14191
  //#endregion
14121
- 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, 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, 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, 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_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, 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, 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_AGENT_SCHEMA, SandboxBridge, SandboxBridgeOptions, SandboxError, SandboxHostToWorker, SandboxMethod, SandboxWorkerToHost, SchemaPair, SchemaSpec, SchemaValidationResult, ScopeSegment, ScriptRejected, ScriptRunner, ScrubNote, SecretMasker, SectionMatchMode, 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, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, type TerminalEnvelope, TerminalOutcomeFacts, TerminalPatch, 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, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, 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, 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, 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 };
14192
+ 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, 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, 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_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, 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, 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_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, TOOL_NAME_PATTERN, type TaskClass, TaskDigest, TaskSpec, type TerminalEnvelope, TerminalOutcomeFacts, TerminalPatch, 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, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, 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, 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 };
package/dist/index.js CHANGED
@@ -12604,6 +12604,102 @@ async function runAgent(options) {
12604
12604
  resolved: options.resolved
12605
12605
  }, ...options.fallbacks ?? []];
12606
12606
  const loopCursor = { index: 0 };
12607
+ /**
12608
+ * The drained-finalization grant (RV2204, the third parity rerun).
12609
+ * The exposure drain is terminal mid-work: spend only grows, so a
12610
+ * seat refused with no live holder left can never dispatch an
12611
+ * ordinary turn again. The third parity rerun killed three workers
12612
+ * ~30 turns into research with evidence pools of 17 and 22 under a
12613
+ * floor of 24 and a CONFIGURED finalization window: the drain came
12614
+ * before the window, and the window's play needs the very wire the
12615
+ * drain refuses. With `limits.finalizationReserve.maxOutputTokens`
12616
+ * declared, a drained seat that already did work now spends ONE
12617
+ * clamped finalization turn before its typed terminal: the output
12618
+ * clamp shrinks the turn's exposure estimate (the full estimate was
12619
+ * refused; the clamped one prices the summary allowance instead of
12620
+ * the whole per-turn cap), the finalization-window allowlist rides
12621
+ * as the turn's only tools so outstanding record_evidence calls can
12622
+ * land in parallel, and the executed calls persist through the
12623
+ * ordinary tool machinery. Best effort, exactly like the tool-budget
12624
+ * reserve turn: a refusal of even the clamped estimate warns and
12625
+ * keeps the typed drained terminal; a seat with NO completed turns
12626
+ * keeps dying free (the RV2002 zero-cost doctrine: nothing to
12627
+ * summarize, nothing paid).
12628
+ */
12629
+ let drainFinalizationRan = false;
12630
+ const runDrainFinalization = async (refusal) => {
12631
+ const allow = limits.finalizationWindow?.allow;
12632
+ const allowedTools = allow === void 0 ? void 0 : options.tools?.contracts.filter((contract) => allow.includes(contract.name));
12633
+ const toolsRide = allowedTools !== void 0 && allowedTools.length > 0;
12634
+ const drainMessages = [...messages, {
12635
+ role: "user",
12636
+ parts: [{
12637
+ type: "text",
12638
+ text: `The run's in-flight exposure pool is drained; no further ordinary turns can dispatch (${refusal}). This is your single finalization turn` + (toolsRide ? ": record any outstanding evidence with the allowed tools IN THIS turn (parallel calls), then close" : `: close`) + ` with your best final summary of the work already done.`
12639
+ }]
12640
+ }];
12641
+ let grant;
12642
+ try {
12643
+ grant = await dispatchPhase({
12644
+ role: primaryRole,
12645
+ chain: loopChain,
12646
+ cursor: loopCursor,
12647
+ requestFor: (target) => {
12648
+ let req = buildRequest(target.resolved, projectHistory(drainMessages, providerOf(target.adapter)), limits, toolsRide ? allowedTools : void 0);
12649
+ const reserveMax = limits.finalizationReserve?.maxOutputTokens;
12650
+ if (reserveMax !== void 0) req = {
12651
+ ...req,
12652
+ maxOutputTokens: Math.min(req.maxOutputTokens ?? reserveMax, reserveMax)
12653
+ };
12654
+ req = applyCachePolicy(req, target, options.cache);
12655
+ return applyOutputBudget(req, target, options.budget);
12656
+ },
12657
+ streamOptionsFor: (target) => {
12658
+ const drainStreamOptions = {
12659
+ idleTimeoutMs: limits.streamIdleTimeoutMs,
12660
+ signals: options.signal === void 0 ? [] : [options.signal],
12661
+ onUsage: (delta) => options.budget?.onUsage(delta, target.resolved.ref)
12662
+ };
12663
+ if (options.budget?.signal !== void 0) drainStreamOptions.budgetSignal = options.budget.signal;
12664
+ if (options.stream === true) drainStreamOptions.onDelta = (delta) => events?.emit({
12665
+ type: "agent:stream",
12666
+ delta
12667
+ });
12668
+ return drainStreamOptions;
12669
+ }
12670
+ });
12671
+ } catch (grantThrown) {
12672
+ if (!(grantThrown instanceof BudgetExhaustedError)) throw grantThrown;
12673
+ events?.emit({
12674
+ type: "log",
12675
+ level: "warn",
12676
+ msg: `the drained-finalization turn was skipped: ${grantThrown.message}`
12677
+ });
12678
+ return;
12679
+ }
12680
+ const { outcome: grantOutcome, target: grantTarget } = grant;
12681
+ servedBy = grantTarget.resolved.ref;
12682
+ usageApprox = usageApprox || grantOutcome.usageApprox;
12683
+ messages.push(assistantMsg(grantOutcome.turn, liftRetainedParts(grantOutcome.providerMetadata, grantTarget.adapter)));
12684
+ if (toolsRide && grantOutcome.turn.toolCalls.length > 0) try {
12685
+ await runToolCalls(grantOutcome.turn.toolCalls, []);
12686
+ } catch (toolThrown) {
12687
+ events?.emit({
12688
+ type: "log",
12689
+ level: "warn",
12690
+ msg: `a drained-finalization tool call failed: ${toolThrown instanceof Error ? toolThrown.message : String(toolThrown)}`
12691
+ });
12692
+ }
12693
+ events?.emit({
12694
+ type: "log",
12695
+ level: "info",
12696
+ msg: "the drained seat spent its finalization turn",
12697
+ data: {
12698
+ toolCalls: grantOutcome.turn.toolCalls.length,
12699
+ outputTokens: grantOutcome.usage.outputTokens
12700
+ }
12701
+ });
12702
+ };
12607
12703
  loop: while (status === "ok" && !finishedViaTool) {
12608
12704
  if (limits.timeoutMs !== void 0 && now() - startedAt >= limits.timeoutMs) {
12609
12705
  status = "limit";
@@ -12657,8 +12753,12 @@ async function runAgent(options) {
12657
12753
  });
12658
12754
  } catch (thrown) {
12659
12755
  if (!(thrown instanceof BudgetExhaustedError)) throw thrown;
12660
- status = "error";
12661
12756
  const typedReason = thrown.data?.reason;
12757
+ if (typedReason === "exposure-drained" && limits.finalizationReserve !== void 0 && turns > 1 && !drainFinalizationRan) {
12758
+ drainFinalizationRan = true;
12759
+ await runDrainFinalization(thrown.message);
12760
+ }
12761
+ status = "error";
12662
12762
  agentError = {
12663
12763
  kind: "budget",
12664
12764
  retryable: false,
@@ -19927,6 +20027,80 @@ function evidencePreservedValidator(options) {
19927
20027
  };
19928
20028
  }
19929
20029
  /**
20030
+ * Counted collections inside named sections (RV2206, the subscription
20031
+ * parity series). The engine validated citations per section since the
20032
+ * v1.71 review, but the numbered collections the parity contract
20033
+ * demands (48 N-case ids, 16 counterexample ids) were policed by
20034
+ * nothing: the second accepted dossier carried 0 and 0 against an
20035
+ * instruction naming both, and only a runner-side format pre-teach
20036
+ * closed the gap, by hope rather than contract. Each entry slices its
20037
+ * section exactly like sectionCitationsValidator (first marker
20038
+ * occurrence to the next marker in position order) and counts matches,
20039
+ * DISTINCT by first capture when the pattern captures; the reasons
20040
+ * name the section, the label, the found count against the minimum,
20041
+ * and with a capturing pattern the missing count in ids, so a repair
20042
+ * turn knows exactly what to add (the RV2105 lesson). Default name
20043
+ * 'section-pattern-counts'.
20044
+ */
20045
+ function sectionPatternCountValidator(options) {
20046
+ const sections = requireNonEmptyStrings(options.sections, "sectionPatternCountValidator sections");
20047
+ if (options.entries.length === 0) throw new ConfigError("sectionPatternCountValidator entries must be a non empty array");
20048
+ for (const entry of options.entries) {
20049
+ if (!sections.includes(entry.section)) throw new ConfigError(`sectionPatternCountValidator entry section '${entry.section}' is not a declared section`);
20050
+ const globalFlags = (entry.flags ?? "").includes("g") ? entry.flags ?? "" : `${entry.flags ?? ""}g`;
20051
+ try {
20052
+ new RegExp(entry.pattern, globalFlags);
20053
+ } catch (thrown) {
20054
+ throw new ConfigError(`sectionPatternCountValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
20055
+ }
20056
+ if (!Number.isInteger(entry.min) || entry.min < 1) throw new ConfigError(`sectionPatternCountValidator min must be a positive integer; got ${String(entry.min)}`);
20057
+ }
20058
+ const match = options.match === void 0 ? "anywhere" : requireSectionMatchMode(options.match, "sectionPatternCountValidator match");
20059
+ const fencedCode = options.fencedCode === void 0 ? "counted" : requireFencedCodeMode(options.fencedCode, "sectionPatternCountValidator fencedCode");
20060
+ const qualifier = missingSectionQualifier(match, fencedCode);
20061
+ const counted = fencedCode === "excluded" ? " (fenced code excluded)" : "";
20062
+ return {
20063
+ name: options.name ?? "section-pattern-counts",
20064
+ validate: (input) => {
20065
+ const scope = fencedCode === "excluded" ? stripFencedBlocks(input.text) : input.text;
20066
+ const positions = /* @__PURE__ */ new Map();
20067
+ for (const section of sections) {
20068
+ const at = sectionPosition(scope, section, match);
20069
+ if (at >= 0) positions.set(section, at);
20070
+ }
20071
+ const ordered = [...positions.entries()].sort((a, b) => a[1] - b[1]);
20072
+ const reasons = [];
20073
+ for (const entry of options.entries) {
20074
+ const at = positions.get(entry.section);
20075
+ const what = entry.label ?? `matches of /${entry.pattern}/`;
20076
+ if (at === void 0) {
20077
+ reasons.push(`required section '${entry.section}' is missing${qualifier}, so its ${what} count cannot be judged`);
20078
+ continue;
20079
+ }
20080
+ const next = ordered.find(([, position]) => position > at);
20081
+ const slice = scope.slice(at, next === void 0 ? scope.length : next[1]);
20082
+ const globalFlags = (entry.flags ?? "").includes("g") ? entry.flags ?? "" : `${entry.flags ?? ""}g`;
20083
+ const captures = /* @__PURE__ */ new Set();
20084
+ let raw = 0;
20085
+ let capturing = false;
20086
+ for (const found of slice.matchAll(new RegExp(entry.pattern, globalFlags))) {
20087
+ raw += 1;
20088
+ if (found[1] !== void 0) {
20089
+ capturing = true;
20090
+ captures.add(found[1]);
20091
+ }
20092
+ }
20093
+ const count = capturing ? captures.size : raw;
20094
+ if (count < entry.min) reasons.push(`section '${entry.section}' carries ${String(count)}${capturing ? " distinct" : ""} ${what} against the required ${String(entry.min)}${counted}; add the missing ${String(entry.min - count)} inside that section`);
20095
+ }
20096
+ return reasons.length === 0 ? ok : {
20097
+ ok: false,
20098
+ reasons
20099
+ };
20100
+ }
20101
+ };
20102
+ }
20103
+ /**
19930
20104
  * Requires at least `min` matches of `pattern` INSIDE every named
19931
20105
  * section (the v1.71 experiment review, P1.2: a total citation count
19932
20106
  * hides sections carrying zero provenance). A section's slice runs
@@ -20785,7 +20959,7 @@ function countWords(text) {
20785
20959
  */
20786
20960
  function finishContract(manifest) {
20787
20961
  if (typeof manifest !== "object" || manifest === null) throw new ConfigError("finishContract manifest must be an object");
20788
- const { sections, sectionsMatch, words, citations, fencedCode } = manifest;
20962
+ const { sections, sectionsMatch, words, citations, sectionPatterns, fencedCode } = manifest;
20789
20963
  if (sections === void 0 && words === void 0 && citations === void 0) throw new ConfigError("finishContract manifest must declare sections, words, or citations");
20790
20964
  let normalizedSections;
20791
20965
  if (sections !== void 0) {
@@ -20841,6 +21015,47 @@ function finishContract(manifest) {
20841
21015
  ...citations.perSection === void 0 ? {} : { perSection: citations.perSection }
20842
21016
  };
20843
21017
  }
21018
+ let normalizedSectionPatterns;
21019
+ if (sectionPatterns !== void 0) {
21020
+ if (!Array.isArray(sectionPatterns) || sectionPatterns.length === 0) throw new ConfigError("finishContract sectionPatterns must be a non empty array");
21021
+ if (normalizedSections === void 0) throw new ConfigError("finishContract sectionPatterns requires sections");
21022
+ normalizedSectionPatterns = [];
21023
+ for (const entry of sectionPatterns) {
21024
+ if (typeof entry !== "object" || entry === null) throw new ConfigError("finishContract sectionPatterns entries must be objects");
21025
+ if (!normalizedSections.includes(entry.section)) throw new ConfigError(`finishContract sectionPatterns section '${String(entry.section)}' is not a declared section`);
21026
+ requirePositiveInt(entry.min, "finishContract sectionPatterns min");
21027
+ const entryFlags = entry.flags ?? "";
21028
+ const entryGlobal = entryFlags.includes("g") ? entryFlags : `${entryFlags}g`;
21029
+ try {
21030
+ new RegExp(entry.pattern, entryGlobal);
21031
+ } catch (thrown) {
21032
+ throw new ConfigError(`finishContract sectionPatterns pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
21033
+ }
21034
+ if (!Array.isArray(entry.samples) || entry.samples.length === 0) throw new ConfigError("finishContract sectionPatterns samples must be a non empty array: the golden fixtures embed literal matches");
21035
+ const captures = /* @__PURE__ */ new Set();
21036
+ let capturing = false;
21037
+ for (const sample of entry.samples) {
21038
+ if (typeof sample !== "string" || sample.length === 0 || sample.includes("\n")) throw new ConfigError("finishContract sectionPatterns samples must be non empty single lines");
21039
+ const found = [...sample.matchAll(new RegExp(entry.pattern, entryGlobal))];
21040
+ if (found.length === 0) throw new ConfigError(`finishContract sectionPatterns sample '${sample}' does not match its pattern`);
21041
+ for (const one of found) if (one[1] !== void 0) {
21042
+ capturing = true;
21043
+ captures.add(one[1]);
21044
+ }
21045
+ if (normalizedSections.some((section) => sample.includes(section))) throw new ConfigError("finishContract sectionPatterns samples must not contain a declared section marker");
21046
+ }
21047
+ if (capturing && captures.size < entry.min) throw new ConfigError(`finishContract sectionPatterns samples carry ${String(captures.size)} distinct captures, below min ${String(entry.min)}: the golden accept skeleton could never satisfy the demand it embeds`);
21048
+ if (!capturing && entry.samples.length < entry.min) throw new ConfigError(`finishContract sectionPatterns needs at least min samples without a capture group; got ${String(entry.samples.length)} of ${String(entry.min)}`);
21049
+ normalizedSectionPatterns.push({
21050
+ section: entry.section,
21051
+ pattern: entry.pattern,
21052
+ ...entryFlags === "" ? {} : { flags: entryFlags },
21053
+ min: entry.min,
21054
+ samples: [...entry.samples],
21055
+ ...entry.label === void 0 ? {} : { label: entry.label }
21056
+ });
21057
+ }
21058
+ }
20844
21059
  let normalizedSectionsMatch;
20845
21060
  if (sectionsMatch !== void 0) {
20846
21061
  if (sectionsMatch !== "anywhere" && sectionsMatch !== "line") throw new ConfigError(`finishContract sectionsMatch must be 'anywhere' or 'line'; got ${String(sectionsMatch)}`);
@@ -20855,6 +21070,7 @@ function finishContract(manifest) {
20855
21070
  if (normalizedFencedCode === "excluded") {
20856
21071
  const opensFence = /^\s*(`{3,}|~{3,})/;
20857
21072
  for (const section of normalizedSections ?? []) if (opensFence.test(section)) throw new ConfigError(`finishContract section '${section}' would open a code fence under fencedCode 'excluded'`);
21073
+ for (const entry of normalizedSectionPatterns ?? []) for (const sample of entry.samples) if (opensFence.test(sample)) throw new ConfigError(`finishContract sectionPatterns sample '${sample}' would open a code fence under fencedCode 'excluded'`);
20858
21074
  if (normalizedCitations !== void 0 && opensFence.test(normalizedCitations.sample)) throw new ConfigError(`finishContract citations.sample '${normalizedCitations.sample}' would open a code fence under fencedCode 'excluded'`);
20859
21075
  }
20860
21076
  const normalized = {
@@ -20862,12 +21078,20 @@ function finishContract(manifest) {
20862
21078
  ...normalizedSectionsMatch === void 0 ? {} : { sectionsMatch: normalizedSectionsMatch },
20863
21079
  ...normalizedWords === void 0 ? {} : { words: normalizedWords },
20864
21080
  ...normalizedCitations === void 0 ? {} : { citations: normalizedCitations },
21081
+ ...normalizedSectionPatterns === void 0 ? {} : { sectionPatterns: normalizedSectionPatterns },
20865
21082
  ...normalizedFencedCode === void 0 ? {} : { fencedCode: normalizedFencedCode }
20866
21083
  };
20867
21084
  const hash = createHash("sha256").update(jcsSerialize(normalized), "utf8").digest("hex");
20868
21085
  if (normalizedSections !== void 0) Object.freeze(normalizedSections);
20869
21086
  if (normalizedWords !== void 0) Object.freeze(normalizedWords);
20870
21087
  if (normalizedCitations !== void 0) Object.freeze(normalizedCitations);
21088
+ if (normalizedSectionPatterns !== void 0) {
21089
+ for (const entry of normalizedSectionPatterns) {
21090
+ Object.freeze(entry.samples);
21091
+ Object.freeze(entry);
21092
+ }
21093
+ Object.freeze(normalizedSectionPatterns);
21094
+ }
20871
21095
  const matchOption = normalizedSectionsMatch === void 0 ? {} : { match: normalizedSectionsMatch };
20872
21096
  const fencedOption = normalizedFencedCode === void 0 ? {} : { fencedCode: normalizedFencedCode };
20873
21097
  const validators = [];
@@ -20898,6 +21122,19 @@ function finishContract(manifest) {
20898
21122
  ...matchOption,
20899
21123
  ...fencedOption
20900
21124
  }));
21125
+ if (normalizedSectionPatterns !== void 0 && normalizedSections !== void 0) validators.push(sectionPatternCountValidator({
21126
+ sections: normalizedSections,
21127
+ entries: normalizedSectionPatterns.map((entry) => ({
21128
+ section: entry.section,
21129
+ pattern: entry.pattern,
21130
+ ...entry.flags === void 0 ? {} : { flags: entry.flags },
21131
+ min: entry.min,
21132
+ ...entry.label === void 0 ? {} : { label: entry.label }
21133
+ })),
21134
+ name: "contract-section-patterns",
21135
+ ...matchOption,
21136
+ ...fencedOption
21137
+ }));
20901
21138
  const promptLines = [];
20902
21139
  if (normalizedSections !== void 0) promptLines.push((normalizedSectionsMatch === "line" ? "The final result must contain each of these section markers verbatim, each on its own line: " : "The final result must contain each of these section markers verbatim: ") + normalizedSections.map((section) => `'${section}'`).join(", ") + ".");
20903
21140
  if (normalizedWords !== void 0) {
@@ -20910,6 +21147,10 @@ function finishContract(manifest) {
20910
21147
  if (normalizedCitations.min !== void 0) promptLines.push(`Include at least ${String(normalizedCitations.min)} citations matching /${normalizedCitations.pattern}/ overall (for example '${normalizedCitations.sample}').`);
20911
21148
  if (normalizedCitations.perSection !== void 0) promptLines.push(`Every required section must itself contain at least ${String(normalizedCitations.perSection)} such citations.`);
20912
21149
  }
21150
+ for (const entry of normalizedSectionPatterns ?? []) {
21151
+ const what = entry.label ?? `matches of /${entry.pattern}/`;
21152
+ promptLines.push(`Section '${entry.section}' must contain at least ${String(entry.min)} distinct ${what} (for example '${entry.samples[0]}').`);
21153
+ }
20913
21154
  if (normalizedFencedCode === "excluded") promptLines.push("Text inside fenced code blocks (``` or ~~~) does not count toward sections, word counts, or citations.");
20914
21155
  const lines = [];
20915
21156
  const perSection = normalizedCitations?.perSection ?? 0;
@@ -20919,6 +21160,7 @@ function finishContract(manifest) {
20919
21160
  const sample = normalizedCitations.sample;
20920
21161
  lines.push(Array.from({ length: perSection }, () => sample).join(" "));
20921
21162
  }
21163
+ for (const entry of normalizedSectionPatterns ?? []) if (entry.section === section) lines.push(...entry.samples);
20922
21164
  }
20923
21165
  if (normalizedCitations !== void 0) {
20924
21166
  const placed = (normalizedSections?.length ?? 0) * perSection;
@@ -20976,6 +21218,20 @@ function finishContract(manifest) {
20976
21218
  addGoldenReject(validator, goldenText.split("\n").filter((line) => line !== last).join("\n"));
20977
21219
  break;
20978
21220
  }
21221
+ case "contract-section-patterns": {
21222
+ if (normalizedSectionPatterns === void 0 || normalizedSectionPatterns.length === 0) break;
21223
+ const first = normalizedSectionPatterns[0];
21224
+ const dropped = first.samples[first.samples.length - 1];
21225
+ let removed = false;
21226
+ addGoldenReject(validator, goldenText.split("\n").filter((line) => {
21227
+ if (!removed && line === dropped) {
21228
+ removed = true;
21229
+ return false;
21230
+ }
21231
+ return true;
21232
+ }).join("\n"));
21233
+ break;
21234
+ }
20979
21235
  case "contract-words": {
20980
21236
  const deficit = normalizedWords?.min !== void 0 ? normalizedWords.min - 1 : (normalizedWords?.max ?? 0) + 1;
20981
21237
  addGoldenReject(validator, Array.from({ length: deficit }, () => FILLER_WORD).join(" "));
@@ -24792,10 +25048,16 @@ function preflightEstimate(input) {
24792
25048
  spawn: label
24793
25049
  });
24794
25050
  }
24795
- if (limits.finalizationReserve !== void 0 && limits.maxToolCalls === void 0 && limits.toolUnits === void 0) say({
25051
+ if (limits.finalizationReserve !== void 0 && limits.maxToolCalls === void 0 && limits.toolUnits === void 0 && input.run?.maxInFlightExposureUsd === void 0) say({
24796
25052
  severity: "warning",
24797
25053
  code: "inert-finalization-reserve",
24798
- message: `spawn '${label}' sets finalizationReserve without maxToolCalls or toolUnits: no tool budget limiter exists for it to fire on`,
25054
+ message: `spawn '${label}' sets finalizationReserve without maxToolCalls or toolUnits: no tool budget limiter exists for it to fire on, and no in-flight exposure cap is declared for the drained-finalization grant (RV2204) to spend it at`,
25055
+ spawn: label
25056
+ });
25057
+ if (limits.finalizationWindow !== void 0 && limits.finalizationReserve?.maxOutputTokens === void 0 && input.run?.maxInFlightExposureUsd !== void 0) say({
25058
+ severity: "info",
25059
+ code: "drained-finalization-unfunded",
25060
+ message: `spawn '${label}' declares finalizationWindow under an in-flight exposure cap but no finalizationReserve.maxOutputTokens: a mid-work exposure drain refuses the wire the window needs, and without the reserve's clamped turn the seat dies with its window unplayed (RV2204); declare the reserve to fund one drained-finalization turn`,
24799
25061
  spawn: label
24800
25062
  });
24801
25063
  if (limits.toolBudgetNotices === true && limits.maxToolCalls === void 0) say({
@@ -27265,4 +27527,4 @@ function createSandboxBridge(ctx, options) {
27265
27527
  };
27266
27528
  }
27267
27529
  //#endregion
27268
- 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_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, 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, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, 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, 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, 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 };
27530
+ 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_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, 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, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, 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, 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, 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.220.0",
3
+ "version": "1.222.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",