@rulvar/core 1.77.0 → 1.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +139 -17
  2. package/dist/index.js +238 -34
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -6327,13 +6327,47 @@ interface FinishValidator {
6327
6327
  validate(input: FinishValidationInput): FinishValidationVerdict;
6328
6328
  }
6329
6329
  /**
6330
+ * How section markers must appear in the judged text (cycle 74):
6331
+ * 'anywhere' is the historical substring test; 'line' demands the
6332
+ * marker as its own line (surrounding whitespace ignored), so a
6333
+ * mid sentence mention or a quoted marker no longer satisfies a
6334
+ * heading requirement.
6335
+ */
6336
+ type SectionMatchMode = "anywhere" | "line";
6337
+ /**
6338
+ * Whether fenced code participates in textual validation (cycle 74):
6339
+ * 'counted' is the historical behavior; 'excluded' removes fenced code
6340
+ * blocks (see {@link stripFencedBlocks}) before matching, counting, or
6341
+ * slicing, so code samples can neither satisfy a section marker nor
6342
+ * inflate word and citation counts.
6343
+ */
6344
+ type FencedCodeMode = "counted" | "excluded";
6345
+ /**
6346
+ * Removes fenced code blocks from a text, the delimiter lines
6347
+ * included, and returns the remaining lines joined by newlines. The
6348
+ * grammar is the CommonMark shape as a deliberate line heuristic: a
6349
+ * fence opens at a line starting (after at most three spaces) with
6350
+ * three or more backticks or tildes, an optional info string allowed;
6351
+ * it closes at the next line carrying only at least as many of the
6352
+ * SAME character; an unclosed fence runs to the end of the text.
6353
+ * Indented (four space) code blocks are not treated as code. This is
6354
+ * the exact exclusion the `fencedCode: 'excluded'` validator option
6355
+ * applies, exported so custom host validators can stay symmetric.
6356
+ */
6357
+ declare function stripFencedBlocks(text: string): string;
6358
+ /**
6330
6359
  * Requires every named section to appear LITERALLY in the result text
6331
6360
  * (a heading like 'FINDINGS' or any marker the goal demands). Default
6332
6361
  * name 'required-sections'; pass `name` to run several instances.
6362
+ * `match: 'line'` demands each marker as its own line and
6363
+ * `fencedCode: 'excluded'` ignores markers inside fenced code blocks
6364
+ * (cycle 74); both default to the historical byte identical behavior.
6333
6365
  */
6334
6366
  declare function requiredSectionsValidator(options: {
6335
- sections: string[];
6367
+ sections: readonly string[];
6336
6368
  name?: string;
6369
+ match?: SectionMatchMode;
6370
+ fencedCode?: FencedCodeMode;
6337
6371
  }): FinishValidator;
6338
6372
  /**
6339
6373
  * Requires the result to be a JSON object carrying every named field
@@ -6343,7 +6377,7 @@ declare function requiredSectionsValidator(options: {
6343
6377
  * validator). Default name 'required-fields'.
6344
6378
  */
6345
6379
  declare function requiredFieldsValidator(options: {
6346
- fields: string[];
6380
+ fields: readonly string[];
6347
6381
  name?: string;
6348
6382
  }): FinishValidator;
6349
6383
  /**
@@ -6352,12 +6386,16 @@ declare function requiredFieldsValidator(options: {
6352
6386
  * v1.71 experiment review, P0.7: a formal length requirement must be
6353
6387
  * code, never a natural-language plea the model may round away). At
6354
6388
  * least one bound is required; both are positive integers with
6355
- * min <= max. Default name 'word-count'.
6389
+ * min <= max. Default name 'word-count'. `fencedCode: 'excluded'`
6390
+ * counts only words outside fenced code blocks (cycle 74), so code
6391
+ * samples cannot pad a length requirement; the default counts
6392
+ * everything, byte identical to the historical behavior.
6356
6393
  */
6357
6394
  declare function wordCountValidator(options: {
6358
6395
  min?: number;
6359
6396
  max?: number;
6360
6397
  name?: string;
6398
+ fencedCode?: FencedCodeMode;
6361
6399
  }): FinishValidator;
6362
6400
  /** The default citation shape: a path with an extension, a colon, a line number. */
6363
6401
  declare const DEFAULT_CITATION_PATTERN = "[\\w./-]+\\.\\w+:\\d+";
@@ -6396,14 +6434,20 @@ declare function evidencePreservedValidator(options?: {
6396
6434
  * text is its own failure reason, because coverage of a missing
6397
6435
  * section cannot silently count as satisfied.
6398
6436
  * requiredSectionsValidator still owns plain presence. Default name
6399
- * 'section-citations'.
6437
+ * 'section-citations'. `match: 'line'` anchors each section at the
6438
+ * first line equal to its marker and `fencedCode: 'excluded'` removes
6439
+ * fenced code before anchoring, slicing, and counting (cycle 74), so a
6440
+ * marker echoed inside a code sample can neither anchor a slice nor
6441
+ * donate citations; both default to the historical behavior.
6400
6442
  */
6401
6443
  declare function sectionCitationsValidator(options: {
6402
- sections: string[];
6444
+ sections: readonly string[];
6403
6445
  pattern?: string;
6404
6446
  flags?: string;
6405
6447
  min: number;
6406
6448
  name?: string;
6449
+ match?: SectionMatchMode;
6450
+ fencedCode?: FencedCodeMode;
6407
6451
  }): FinishValidator;
6408
6452
  /**
6409
6453
  * Requires at least `min` matches of `pattern` in the result text (the
@@ -6412,12 +6456,17 @@ declare function sectionCitationsValidator(options: {
6412
6456
  * ConfigError before any run exists) and matches globally; `min` is a
6413
6457
  * positive integer. Default name 'min-matches'; pass `name` to run
6414
6458
  * several instances, because names must be unique per orchestrate call.
6459
+ * `fencedCode: 'excluded'` matches only outside fenced code blocks
6460
+ * (cycle 74), so citations quoted inside code samples do not count;
6461
+ * the default matches everything, byte identical to the historical
6462
+ * behavior.
6415
6463
  */
6416
6464
  declare function minMatchesValidator(options: {
6417
6465
  pattern: string;
6418
6466
  flags?: string;
6419
6467
  min: number;
6420
6468
  name?: string;
6469
+ fencedCode?: FencedCodeMode;
6421
6470
  }): FinishValidator;
6422
6471
  //#endregion
6423
6472
  //#region src/orchestrator/output-contract.d.ts
@@ -6451,6 +6500,16 @@ interface FinishContractCitations {
6451
6500
  interface FinishContractManifest {
6452
6501
  /** Literal section markers the result must contain. */
6453
6502
  sections?: string[];
6503
+ /**
6504
+ * How section markers must appear (cycle 74): 'anywhere' (the
6505
+ * default, a plain substring test) or 'line' (each marker must
6506
+ * stand as its own line, surrounding whitespace ignored, so a mid
6507
+ * sentence mention no longer satisfies a heading). Requires
6508
+ * `sections`. Joins the hash and the prompt statement only when
6509
+ * 'line'; an explicit 'anywhere' normalizes away, keeping the hash
6510
+ * of the plain manifest.
6511
+ */
6512
+ sectionsMatch?: SectionMatchMode;
6454
6513
  /** Word bounds over the result text (whitespace separated tokens). */
6455
6514
  words?: {
6456
6515
  min?: number;
@@ -6458,14 +6517,52 @@ interface FinishContractManifest {
6458
6517
  };
6459
6518
  /** Citation demands over the result text. */
6460
6519
  citations?: FinishContractCitations;
6520
+ /**
6521
+ * Whether fenced code blocks count (cycle 74): 'counted' (the
6522
+ * default) or 'excluded' (fenced code is removed before section
6523
+ * matching, slicing, word counting, and citation matching, so code
6524
+ * samples can neither satisfy a marker nor pad a count). Joins the
6525
+ * hash and adds a prompt statement only when 'excluded'; an explicit
6526
+ * 'counted' normalizes away. With 'excluded', a section marker or a
6527
+ * citation sample that would itself OPEN a fence is a ConfigError,
6528
+ * because the golden fixtures embed both at line starts.
6529
+ */
6530
+ fencedCode?: FencedCodeMode;
6461
6531
  }
6462
- /** What {@link finishContract} builds from a manifest. */
6532
+ /**
6533
+ * One per validator reject golden (cycle 74): a fixture the NAMED
6534
+ * contract validator is proven to reject at construction time.
6535
+ * {@link selfTestFinishValidation} holds the CONFIGURED validator of
6536
+ * that name against it, so a same-name replacement weaker than the
6537
+ * contract's own validator (a words minimum of one standing in for
6538
+ * three thousand) is caught before any provider call instead of
6539
+ * silently accepting what the journaled contract hash forbids.
6540
+ */
6541
+ interface FinishContractGoldenReject {
6542
+ /** The contract validator this fixture targets, by name. */
6543
+ readonly validator: string;
6544
+ /** The fixture that validator must reject. */
6545
+ readonly input: FinishValidationInput;
6546
+ }
6547
+ /**
6548
+ * What {@link finishContract} builds from a manifest. The whole bundle
6549
+ * is DEEPLY frozen (cycle 74): the nested manifest objects, the
6550
+ * sections array, the validators array, and each validator object, so
6551
+ * a post construction mutation throws instead of silently diverging
6552
+ * behavior from the journaled contract hash.
6553
+ */
6463
6554
  interface FinishContract {
6464
- /** The normalized manifest (defaults applied), frozen. */
6555
+ /** The normalized manifest (defaults applied), deeply frozen. */
6465
6556
  readonly manifest: FinishContractManifest;
6466
6557
  /** sha256 hex over the JCS serialization of the normalized manifest. */
6467
6558
  readonly hash: string;
6468
- /** The stock validators enforcing the manifest; names are 'contract-*'. */
6559
+ /**
6560
+ * The stock validators enforcing the manifest; names are
6561
+ * 'contract-*'. The array and each validator object are frozen at
6562
+ * runtime (the type stays mutable for source compatibility), so an
6563
+ * in-place pop or a validate() swap throws instead of silently
6564
+ * weakening what the hash promises.
6565
+ */
6469
6566
  readonly validators: FinishValidator[];
6470
6567
  /** The contract statement for the model, one demand per line. */
6471
6568
  readonly promptLines: readonly string[];
@@ -6477,6 +6574,13 @@ interface FinishContract {
6477
6574
  * empty result is then legitimately acceptable.
6478
6575
  */
6479
6576
  readonly goldenReject?: FinishValidationInput;
6577
+ /**
6578
+ * One reject golden PER contract validator (cycle 74), in validator
6579
+ * order, each verified at construction; boundary sharp where a
6580
+ * boundary is mechanically safe (the words fixture sits exactly one
6581
+ * word outside the bound), the empty text otherwise.
6582
+ */
6583
+ readonly goldenRejects: readonly FinishContractGoldenReject[];
6480
6584
  }
6481
6585
  /**
6482
6586
  * Builds a {@link FinishContract} from one manifest: validation and the
@@ -6500,7 +6604,11 @@ interface FinishSelfTestFixtures {
6500
6604
  /** One self test failure. */
6501
6605
  interface FinishSelfTestFailure {
6502
6606
  fixture: "accept" | "reject";
6503
- /** The rejecting validator on the accept side; absent on the vacuous reject side. */
6607
+ /**
6608
+ * The failing validator: the rejecting one on the accept side, the
6609
+ * named one on a per validator reject golden (cycle 74); absent
6610
+ * only on the vacuous single-fixture reject side.
6611
+ */
6504
6612
  validator?: string;
6505
6613
  reasons: string[];
6506
6614
  }
@@ -6519,12 +6627,18 @@ interface FinishSelfTestReport {
6519
6627
  * nothing). A validator that THROWS here is a host defect and the
6520
6628
  * ConfigError propagates, the same posture the live loop takes.
6521
6629
  * Deterministic and free: validators are pure synchronous host code by
6522
- * contract, so this costs zero provider calls.
6630
+ * contract, so this costs zero provider calls. `rejects` (cycle 74)
6631
+ * carries the contract's per validator reject goldens: for each one
6632
+ * the CONFIGURED validator of that name must exist and must reject
6633
+ * the fixture, so a same-name replacement weaker than the contract's
6634
+ * own validator fails here instead of silently accepting what the
6635
+ * journaled contract hash forbids.
6523
6636
  */
6524
6637
  declare function selfTestFinishValidation(options: {
6525
- validators: FinishValidator[];
6638
+ validators: readonly FinishValidator[];
6526
6639
  accept?: FinishValidationInput;
6527
6640
  reject?: FinishValidationInput;
6641
+ rejects?: readonly FinishContractGoldenReject[];
6528
6642
  }): FinishSelfTestReport;
6529
6643
  //#endregion
6530
6644
  //#region src/orchestrator/handles.d.ts
@@ -7181,8 +7295,13 @@ interface FinishValidationSpec {
7181
7295
  * identical and the loop continues to a live repair turn). Decisions
7182
7296
  * recorded before 1.77 carry no hash and bind to the current
7183
7297
  * contract only while the journal holds a single bundle descriptor;
7184
- * once a supersession is recorded they are stale. Absent = byte
7185
- * identical pre 1.72 behavior.
7298
+ * once a supersession is recorded they are stale. The bundle is
7299
+ * deeply frozen and the construction self test also runs the
7300
+ * contract's per validator reject goldens against the CONFIGURED
7301
+ * set (cycle 74), so a post construction mutation throws and a
7302
+ * same-name replacement weaker than the contract's own validator is
7303
+ * a ConfigError before any provider call. Absent = byte identical
7304
+ * pre 1.72 behavior.
7186
7305
  */
7187
7306
  contract?: FinishContract;
7188
7307
  /**
@@ -8966,9 +9085,12 @@ interface PreflightInput {
8966
9085
  * review, P1.1). Programmatic only: validator functions cannot ride
8967
9086
  * a JSON config file, so the CLI never carries this. When present,
8968
9087
  * preflight runs the SAME golden self test orchestrate runs at
8969
- * construction and reports every drift as an error finding (code
8970
- * 'output-contract-validator-mismatch') instead of throwing, so a
8971
- * planner surfaces it next to the quota and budget findings.
9088
+ * construction and reports every drift as an error finding instead
9089
+ * of throwing, so a planner surfaces it next to the quota and budget
9090
+ * findings: 'output-contract-validator-mismatch' for containment and
9091
+ * accept-side drift, 'output-contract-validator-weakened' (cycle 74)
9092
+ * when a configured validator fails the contract's per validator
9093
+ * reject golden, the same-name weakened replacement.
8972
9094
  */
8973
9095
  finishValidation?: {
8974
9096
  validators: FinishValidator[];
@@ -9651,4 +9773,4 @@ interface SandboxBridge {
9651
9773
  declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
9652
9774
  declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
9653
9775
  //#endregion
9654
- 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, 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_MIN_SHARE, 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, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, type ExecutorRegistry, type ExplorationSummary, ExtensionAppendInput, ExtensionDispatchSpec, ExternalIdentityInput, ExternalRegistry, ExtractNecessityInput, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FailoverTarget, FailoverTrigger, FallbackField, FallbackTrigger, FileModelKnowledgeStore, FileModelKnowledgeStoreOptions, FileTranscriptStore, FinishContract, FinishContractCitations, 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, 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, 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, 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, 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, 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, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, 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, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, 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, snapshotUsage, spawnDepthOf, 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 };
9776
+ 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, 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_MIN_SHARE, 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, EntryKind, EntryRef, EntryStatus, EnvelopeEncryption, EnvelopeEncryptionOptions, ErrorClass, ErrorCode, ErrorPolicy, EscalatedResult, EscalationDecision, EscalationDecisionAbortedError, EscalationDigest, EscalationKind, EscalationLimits, EscalationOptions, EscalationReport, EscalationRequest, EventBus, type EvidenceRef, 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, 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, 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, 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, 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, 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, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, 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, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, 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, 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
@@ -15346,22 +15346,92 @@ const ok = { ok: true };
15346
15346
  function requireNonEmptyStrings(values, what) {
15347
15347
  if (!Array.isArray(values) || values.length === 0) throw new ConfigError(`${what} must be a non empty array of strings`);
15348
15348
  for (const value of values) if (typeof value !== "string" || value.length === 0) throw new ConfigError(`${what} must contain only non empty strings`);
15349
- return values;
15349
+ return [...values];
15350
+ }
15351
+ const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
15352
+ const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
15353
+ /**
15354
+ * Removes fenced code blocks from a text, the delimiter lines
15355
+ * included, and returns the remaining lines joined by newlines. The
15356
+ * grammar is the CommonMark shape as a deliberate line heuristic: a
15357
+ * fence opens at a line starting (after at most three spaces) with
15358
+ * three or more backticks or tildes, an optional info string allowed;
15359
+ * it closes at the next line carrying only at least as many of the
15360
+ * SAME character; an unclosed fence runs to the end of the text.
15361
+ * Indented (four space) code blocks are not treated as code. This is
15362
+ * the exact exclusion the `fencedCode: 'excluded'` validator option
15363
+ * applies, exported so custom host validators can stay symmetric.
15364
+ */
15365
+ function stripFencedBlocks(text) {
15366
+ const kept = [];
15367
+ let fence;
15368
+ for (const line of text.split("\n")) {
15369
+ if (fence === void 0) {
15370
+ const delimiter = FENCE_OPEN.exec(line)?.[1];
15371
+ if (delimiter !== void 0) {
15372
+ fence = {
15373
+ char: delimiter.charAt(0),
15374
+ length: delimiter.length
15375
+ };
15376
+ continue;
15377
+ }
15378
+ kept.push(line);
15379
+ continue;
15380
+ }
15381
+ const close = FENCE_CLOSE.exec(line)?.[1];
15382
+ if (close !== void 0 && close.charAt(0) === fence.char && close.length >= fence.length) fence = void 0;
15383
+ }
15384
+ return kept.join("\n");
15385
+ }
15386
+ function requireSectionMatchMode(value, what) {
15387
+ if (value !== "anywhere" && value !== "line") throw new ConfigError(`${what} must be 'anywhere' or 'line'; got ${String(value)}`);
15388
+ return value;
15389
+ }
15390
+ function requireFencedCodeMode(value, what) {
15391
+ if (value !== "counted" && value !== "excluded") throw new ConfigError(`${what} must be 'counted' or 'excluded'; got ${String(value)}`);
15392
+ return value;
15393
+ }
15394
+ /**
15395
+ * The first position of a section marker in the (already fence
15396
+ * filtered) scope under the configured match mode: the plain substring
15397
+ * offset for 'anywhere', the offset of the first line whose trimmed
15398
+ * content EQUALS the marker for 'line'; -1 when absent. One shared
15399
+ * primitive so presence checks and slice anchoring can never disagree.
15400
+ */
15401
+ function sectionPosition(scope, section, match) {
15402
+ if (match === "anywhere") return scope.indexOf(section);
15403
+ let offset = 0;
15404
+ for (const line of scope.split("\n")) {
15405
+ if (line.trim() === section) return offset;
15406
+ offset += line.length + 1;
15407
+ }
15408
+ return -1;
15409
+ }
15410
+ function missingSectionQualifier(match, fencedCode) {
15411
+ const demands = (match === "line" ? " as its own line" : "") + (fencedCode === "excluded" ? " outside fenced code" : "");
15412
+ return demands === "" ? "" : ` (required${demands})`;
15350
15413
  }
15351
15414
  /**
15352
15415
  * Requires every named section to appear LITERALLY in the result text
15353
15416
  * (a heading like 'FINDINGS' or any marker the goal demands). Default
15354
15417
  * name 'required-sections'; pass `name` to run several instances.
15418
+ * `match: 'line'` demands each marker as its own line and
15419
+ * `fencedCode: 'excluded'` ignores markers inside fenced code blocks
15420
+ * (cycle 74); both default to the historical byte identical behavior.
15355
15421
  */
15356
15422
  function requiredSectionsValidator(options) {
15357
15423
  const sections = requireNonEmptyStrings(options.sections, "requiredSectionsValidator sections");
15424
+ const match = options.match === void 0 ? "anywhere" : requireSectionMatchMode(options.match, "requiredSectionsValidator match");
15425
+ const fencedCode = options.fencedCode === void 0 ? "counted" : requireFencedCodeMode(options.fencedCode, "requiredSectionsValidator fencedCode");
15426
+ const qualifier = missingSectionQualifier(match, fencedCode);
15358
15427
  return {
15359
15428
  name: options.name ?? "required-sections",
15360
15429
  validate: (input) => {
15361
- const missing = sections.filter((section) => !input.text.includes(section));
15430
+ const scope = fencedCode === "excluded" ? stripFencedBlocks(input.text) : input.text;
15431
+ const missing = sections.filter((section) => sectionPosition(scope, section, match) < 0);
15362
15432
  return missing.length === 0 ? ok : {
15363
15433
  ok: false,
15364
- reasons: missing.map((section) => `required section '${section}' is missing`)
15434
+ reasons: missing.map((section) => `required section '${section}' is missing${qualifier}`)
15365
15435
  };
15366
15436
  }
15367
15437
  };
@@ -15403,21 +15473,26 @@ function requiredFieldsValidator(options) {
15403
15473
  * v1.71 experiment review, P0.7: a formal length requirement must be
15404
15474
  * code, never a natural-language plea the model may round away). At
15405
15475
  * least one bound is required; both are positive integers with
15406
- * min <= max. Default name 'word-count'.
15476
+ * min <= max. Default name 'word-count'. `fencedCode: 'excluded'`
15477
+ * counts only words outside fenced code blocks (cycle 74), so code
15478
+ * samples cannot pad a length requirement; the default counts
15479
+ * everything, byte identical to the historical behavior.
15407
15480
  */
15408
15481
  function wordCountValidator(options) {
15409
15482
  const { min, max } = options;
15410
15483
  if (min === void 0 && max === void 0) throw new ConfigError("wordCountValidator requires min, max, or both");
15411
15484
  for (const [label, value] of [["min", min], ["max", max]]) if (value !== void 0 && (!Number.isInteger(value) || value < 1)) throw new ConfigError(`wordCountValidator ${label} must be a positive integer; got ${String(value)}`);
15412
15485
  if (min !== void 0 && max !== void 0 && min > max) throw new ConfigError(`wordCountValidator min ${String(min)} exceeds max ${String(max)}`);
15486
+ const fencedCode = options.fencedCode === void 0 ? "counted" : requireFencedCodeMode(options.fencedCode, "wordCountValidator fencedCode");
15487
+ const counted = fencedCode === "excluded" ? " (fenced code excluded)" : "";
15413
15488
  return {
15414
15489
  name: options.name ?? "word-count",
15415
15490
  validate: (input) => {
15416
- const trimmed = input.text.trim();
15491
+ const trimmed = (fencedCode === "excluded" ? stripFencedBlocks(input.text) : input.text).trim();
15417
15492
  const count = trimmed.length === 0 ? 0 : trimmed.split(/\s+/).length;
15418
15493
  const reasons = [];
15419
- if (min !== void 0 && count < min) reasons.push(`result word count ${String(count)} is below the required minimum ${String(min)}`);
15420
- if (max !== void 0 && count > max) reasons.push(`result word count ${String(count)} exceeds the maximum ${String(max)}`);
15494
+ if (min !== void 0 && count < min) reasons.push(`result word count ${String(count)}${counted} is below the required minimum ${String(min)}`);
15495
+ if (max !== void 0 && count > max) reasons.push(`result word count ${String(count)}${counted} exceeds the maximum ${String(max)}`);
15421
15496
  return reasons.length === 0 ? ok : {
15422
15497
  ok: false,
15423
15498
  reasons
@@ -15495,7 +15570,11 @@ function evidencePreservedValidator(options) {
15495
15570
  * text is its own failure reason, because coverage of a missing
15496
15571
  * section cannot silently count as satisfied.
15497
15572
  * requiredSectionsValidator still owns plain presence. Default name
15498
- * 'section-citations'.
15573
+ * 'section-citations'. `match: 'line'` anchors each section at the
15574
+ * first line equal to its marker and `fencedCode: 'excluded'` removes
15575
+ * fenced code before anchoring, slicing, and counting (cycle 74), so a
15576
+ * marker echoed inside a code sample can neither anchor a slice nor
15577
+ * donate citations; both default to the historical behavior.
15499
15578
  */
15500
15579
  function sectionCitationsValidator(options) {
15501
15580
  const sections = requireNonEmptyStrings(options.sections, "sectionCitationsValidator sections");
@@ -15508,12 +15587,17 @@ function sectionCitationsValidator(options) {
15508
15587
  throw new ConfigError(`sectionCitationsValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
15509
15588
  }
15510
15589
  if (!Number.isInteger(options.min) || options.min < 1) throw new ConfigError(`sectionCitationsValidator min must be a positive integer; got ${String(options.min)}`);
15590
+ const match = options.match === void 0 ? "anywhere" : requireSectionMatchMode(options.match, "sectionCitationsValidator match");
15591
+ const fencedCode = options.fencedCode === void 0 ? "counted" : requireFencedCodeMode(options.fencedCode, "sectionCitationsValidator fencedCode");
15592
+ const qualifier = missingSectionQualifier(match, fencedCode);
15593
+ const counted = fencedCode === "excluded" ? " (fenced code excluded)" : "";
15511
15594
  return {
15512
15595
  name: options.name ?? "section-citations",
15513
15596
  validate: (input) => {
15597
+ const scope = fencedCode === "excluded" ? stripFencedBlocks(input.text) : input.text;
15514
15598
  const positions = /* @__PURE__ */ new Map();
15515
15599
  for (const section of sections) {
15516
- const at = input.text.indexOf(section);
15600
+ const at = sectionPosition(scope, section, match);
15517
15601
  if (at >= 0) positions.set(section, at);
15518
15602
  }
15519
15603
  const ordered = [...positions.entries()].sort((a, b) => a[1] - b[1]);
@@ -15521,12 +15605,12 @@ function sectionCitationsValidator(options) {
15521
15605
  for (const section of sections) {
15522
15606
  const at = positions.get(section);
15523
15607
  if (at === void 0) {
15524
- reasons.push(`required section '${section}' is missing, so its citation coverage cannot be judged`);
15608
+ reasons.push(`required section '${section}' is missing${qualifier}, so its citation coverage cannot be judged`);
15525
15609
  continue;
15526
15610
  }
15527
15611
  const next = ordered.find(([, position]) => position > at);
15528
- const matches = input.text.slice(at, next === void 0 ? input.text.length : next[1]).match(new RegExp(pattern, globalFlags))?.length ?? 0;
15529
- if (matches < options.min) reasons.push(`section '${section}' carries ${String(matches)} citations matching /${pattern}/; at least ${String(options.min)} required`);
15612
+ const matches = scope.slice(at, next === void 0 ? scope.length : next[1]).match(new RegExp(pattern, globalFlags))?.length ?? 0;
15613
+ if (matches < options.min) reasons.push(`section '${section}' carries ${String(matches)} citations matching /${pattern}/${counted}; at least ${String(options.min)} required`);
15530
15614
  }
15531
15615
  return reasons.length === 0 ? ok : {
15532
15616
  ok: false,
@@ -15542,6 +15626,10 @@ function sectionCitationsValidator(options) {
15542
15626
  * ConfigError before any run exists) and matches globally; `min` is a
15543
15627
  * positive integer. Default name 'min-matches'; pass `name` to run
15544
15628
  * several instances, because names must be unique per orchestrate call.
15629
+ * `fencedCode: 'excluded'` matches only outside fenced code blocks
15630
+ * (cycle 74), so citations quoted inside code samples do not count;
15631
+ * the default matches everything, byte identical to the historical
15632
+ * behavior.
15545
15633
  */
15546
15634
  function minMatchesValidator(options) {
15547
15635
  const flags = options.flags ?? "";
@@ -15552,13 +15640,15 @@ function minMatchesValidator(options) {
15552
15640
  throw new ConfigError(`minMatchesValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
15553
15641
  }
15554
15642
  if (!Number.isInteger(options.min) || options.min < 1) throw new ConfigError(`minMatchesValidator min must be a positive integer; got ${String(options.min)}`);
15643
+ const fencedCode = options.fencedCode === void 0 ? "counted" : requireFencedCodeMode(options.fencedCode, "minMatchesValidator fencedCode");
15644
+ const counted = fencedCode === "excluded" ? " (fenced code excluded)" : "";
15555
15645
  return {
15556
15646
  name: options.name ?? "min-matches",
15557
15647
  validate: (input) => {
15558
- const found = input.text.match(new RegExp(options.pattern, globalFlags))?.length ?? 0;
15648
+ const found = (fencedCode === "excluded" ? stripFencedBlocks(input.text) : input.text).match(new RegExp(options.pattern, globalFlags))?.length ?? 0;
15559
15649
  return found >= options.min ? ok : {
15560
15650
  ok: false,
15561
- reasons: [`expected at least ${String(options.min)} matches of /${options.pattern}/${flags}; found ${String(found)}`]
15651
+ reasons: [`expected at least ${String(options.min)} matches of /${options.pattern}/${flags}; found ${String(found)}${counted}`]
15562
15652
  };
15563
15653
  }
15564
15654
  };
@@ -15602,7 +15692,7 @@ function countWords(text) {
15602
15692
  */
15603
15693
  function finishContract(manifest) {
15604
15694
  if (typeof manifest !== "object" || manifest === null) throw new ConfigError("finishContract manifest must be an object");
15605
- const { sections, words, citations } = manifest;
15695
+ const { sections, sectionsMatch, words, citations, fencedCode } = manifest;
15606
15696
  if (sections === void 0 && words === void 0 && citations === void 0) throw new ConfigError("finishContract manifest must declare sections, words, or citations");
15607
15697
  let normalizedSections;
15608
15698
  if (sections !== void 0) {
@@ -15658,36 +15748,65 @@ function finishContract(manifest) {
15658
15748
  ...citations.perSection === void 0 ? {} : { perSection: citations.perSection }
15659
15749
  };
15660
15750
  }
15751
+ let normalizedSectionsMatch;
15752
+ if (sectionsMatch !== void 0) {
15753
+ if (sectionsMatch !== "anywhere" && sectionsMatch !== "line") throw new ConfigError(`finishContract sectionsMatch must be 'anywhere' or 'line'; got ${String(sectionsMatch)}`);
15754
+ if (normalizedSections === void 0) throw new ConfigError("finishContract sectionsMatch requires sections");
15755
+ if (sectionsMatch === "line") normalizedSectionsMatch = "line";
15756
+ }
15757
+ let normalizedFencedCode;
15758
+ if (fencedCode !== void 0) {
15759
+ if (fencedCode !== "counted" && fencedCode !== "excluded") throw new ConfigError(`finishContract fencedCode must be 'counted' or 'excluded'; got ${String(fencedCode)}`);
15760
+ if (fencedCode === "excluded") normalizedFencedCode = "excluded";
15761
+ }
15762
+ if (normalizedFencedCode === "excluded") {
15763
+ const opensFence = /^\s*(`{3,}|~{3,})/;
15764
+ for (const section of normalizedSections ?? []) if (opensFence.test(section)) throw new ConfigError(`finishContract section '${section}' would open a code fence under fencedCode 'excluded'`);
15765
+ if (normalizedCitations !== void 0 && opensFence.test(normalizedCitations.sample)) throw new ConfigError(`finishContract citations.sample '${normalizedCitations.sample}' would open a code fence under fencedCode 'excluded'`);
15766
+ }
15661
15767
  const normalized = {
15662
15768
  ...normalizedSections === void 0 ? {} : { sections: normalizedSections },
15769
+ ...normalizedSectionsMatch === void 0 ? {} : { sectionsMatch: normalizedSectionsMatch },
15663
15770
  ...normalizedWords === void 0 ? {} : { words: normalizedWords },
15664
- ...normalizedCitations === void 0 ? {} : { citations: normalizedCitations }
15771
+ ...normalizedCitations === void 0 ? {} : { citations: normalizedCitations },
15772
+ ...normalizedFencedCode === void 0 ? {} : { fencedCode: normalizedFencedCode }
15665
15773
  };
15666
15774
  const hash = createHash("sha256").update(jcsSerialize(normalized), "utf8").digest("hex");
15775
+ if (normalizedSections !== void 0) Object.freeze(normalizedSections);
15776
+ if (normalizedWords !== void 0) Object.freeze(normalizedWords);
15777
+ if (normalizedCitations !== void 0) Object.freeze(normalizedCitations);
15778
+ const matchOption = normalizedSectionsMatch === void 0 ? {} : { match: normalizedSectionsMatch };
15779
+ const fencedOption = normalizedFencedCode === void 0 ? {} : { fencedCode: normalizedFencedCode };
15667
15780
  const validators = [];
15668
15781
  if (normalizedSections !== void 0) validators.push(requiredSectionsValidator({
15669
15782
  sections: normalizedSections,
15670
- name: "contract-sections"
15783
+ name: "contract-sections",
15784
+ ...matchOption,
15785
+ ...fencedOption
15671
15786
  }));
15672
15787
  if (normalizedWords !== void 0) validators.push(wordCountValidator({
15673
15788
  ...normalizedWords,
15674
- name: "contract-words"
15789
+ name: "contract-words",
15790
+ ...fencedOption
15675
15791
  }));
15676
15792
  if (normalizedCitations?.min !== void 0) validators.push(minMatchesValidator({
15677
15793
  pattern: normalizedCitations.pattern,
15678
15794
  flags: normalizedCitations.flags,
15679
15795
  min: normalizedCitations.min,
15680
- name: "contract-citations"
15796
+ name: "contract-citations",
15797
+ ...fencedOption
15681
15798
  }));
15682
15799
  if (normalizedCitations?.perSection !== void 0 && normalizedSections !== void 0) validators.push(sectionCitationsValidator({
15683
15800
  sections: normalizedSections,
15684
15801
  pattern: normalizedCitations.pattern,
15685
15802
  flags: normalizedCitations.flags,
15686
15803
  min: normalizedCitations.perSection,
15687
- name: "contract-section-citations"
15804
+ name: "contract-section-citations",
15805
+ ...matchOption,
15806
+ ...fencedOption
15688
15807
  }));
15689
15808
  const promptLines = [];
15690
- if (normalizedSections !== void 0) promptLines.push("The final result must contain each of these section markers verbatim: " + normalizedSections.map((section) => `'${section}'`).join(", ") + ".");
15809
+ 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(", ") + ".");
15691
15810
  if (normalizedWords !== void 0) {
15692
15811
  const { min, max } = normalizedWords;
15693
15812
  if (min !== void 0 && max !== void 0) promptLines.push(`The final result must be between ${String(min)} and ${String(max)} words (whitespace separated).`);
@@ -15698,6 +15817,7 @@ function finishContract(manifest) {
15698
15817
  if (normalizedCitations.min !== void 0) promptLines.push(`Include at least ${String(normalizedCitations.min)} citations matching /${normalizedCitations.pattern}/ overall (for example '${normalizedCitations.sample}').`);
15699
15818
  if (normalizedCitations.perSection !== void 0) promptLines.push(`Every required section must itself contain at least ${String(normalizedCitations.perSection)} such citations.`);
15700
15819
  }
15820
+ if (normalizedFencedCode === "excluded") promptLines.push("Text inside fenced code blocks (``` or ~~~) does not count toward sections, word counts, or citations.");
15701
15821
  const lines = [];
15702
15822
  const perSection = normalizedCitations?.perSection ?? 0;
15703
15823
  for (const section of normalizedSections ?? []) {
@@ -15737,13 +15857,69 @@ function finishContract(manifest) {
15737
15857
  text: "",
15738
15858
  children: Object.freeze([])
15739
15859
  }) : void 0;
15860
+ for (const validator of validators) {
15861
+ const verdict = validator.validate(goldenAccept);
15862
+ if (!verdict.ok) throw new ConfigError(`finishContract self check failed: '${validator.name}' rejects the generated golden accept fixture: ${verdict.reasons.join("; ")}`);
15863
+ }
15864
+ const rejectInput = (text) => Object.freeze({
15865
+ result: text,
15866
+ text,
15867
+ children: Object.freeze([])
15868
+ });
15869
+ const goldenRejects = [];
15870
+ const addGoldenReject = (validator, candidate) => {
15871
+ let fixture = rejectInput(candidate);
15872
+ if (validator.validate(fixture).ok) fixture = rejectInput("");
15873
+ if (validator.validate(fixture).ok) throw new ConfigError(`finishContract cannot build a reject golden for '${validator.name}': it accepts both the boundary fixture and the empty text, so it validates nothing`);
15874
+ goldenRejects.push(Object.freeze({
15875
+ validator: validator.name,
15876
+ input: fixture
15877
+ }));
15878
+ };
15879
+ for (const validator of validators) switch (validator.name) {
15880
+ case "contract-sections": {
15881
+ if (normalizedSections === void 0) break;
15882
+ const last = normalizedSections[normalizedSections.length - 1];
15883
+ addGoldenReject(validator, goldenText.split("\n").filter((line) => line !== last).join("\n"));
15884
+ break;
15885
+ }
15886
+ case "contract-words": {
15887
+ const deficit = normalizedWords?.min !== void 0 ? normalizedWords.min - 1 : (normalizedWords?.max ?? 0) + 1;
15888
+ addGoldenReject(validator, Array.from({ length: deficit }, () => FILLER_WORD).join(" "));
15889
+ break;
15890
+ }
15891
+ case "contract-citations": {
15892
+ if (normalizedCitations === void 0) break;
15893
+ const sample = normalizedCitations.sample;
15894
+ addGoldenReject(validator, Array.from({ length: (normalizedCitations.min ?? 1) - 1 }, () => sample).join(" "));
15895
+ break;
15896
+ }
15897
+ case "contract-section-citations": {
15898
+ if (normalizedSections === void 0 || normalizedCitations === void 0) break;
15899
+ const markers = normalizedSections;
15900
+ const sample = normalizedCitations.sample;
15901
+ const per = normalizedCitations.perSection ?? 1;
15902
+ const rows = [];
15903
+ markers.forEach((section, index) => {
15904
+ rows.push(section);
15905
+ const grant = index === markers.length - 1 ? per - 1 : per;
15906
+ if (grant > 0) rows.push(Array.from({ length: grant }, () => sample).join(" "));
15907
+ });
15908
+ addGoldenReject(validator, rows.join("\n"));
15909
+ break;
15910
+ }
15911
+ default: break;
15912
+ }
15913
+ for (const validator of validators) Object.freeze(validator);
15914
+ Object.freeze(validators);
15740
15915
  return Object.freeze({
15741
15916
  manifest: Object.freeze(normalized),
15742
15917
  hash,
15743
15918
  validators,
15744
15919
  promptLines: Object.freeze(promptLines),
15745
15920
  goldenAccept,
15746
- ...goldenReject === void 0 ? {} : { goldenReject }
15921
+ ...goldenReject === void 0 ? {} : { goldenReject },
15922
+ goldenRejects: Object.freeze(goldenRejects)
15747
15923
  });
15748
15924
  }
15749
15925
  /**
@@ -15756,7 +15932,12 @@ function finishContract(manifest) {
15756
15932
  * nothing). A validator that THROWS here is a host defect and the
15757
15933
  * ConfigError propagates, the same posture the live loop takes.
15758
15934
  * Deterministic and free: validators are pure synchronous host code by
15759
- * contract, so this costs zero provider calls.
15935
+ * contract, so this costs zero provider calls. `rejects` (cycle 74)
15936
+ * carries the contract's per validator reject goldens: for each one
15937
+ * the CONFIGURED validator of that name must exist and must reject
15938
+ * the fixture, so a same-name replacement weaker than the contract's
15939
+ * own validator fails here instead of silently accepting what the
15940
+ * journaled contract hash forbids.
15760
15941
  */
15761
15942
  function selfTestFinishValidation(options) {
15762
15943
  const run = (validator, input) => {
@@ -15783,6 +15964,22 @@ function selfTestFinishValidation(options) {
15783
15964
  reasons: ["every configured validator accepts the known-bad fixture; the validation is vacuous"]
15784
15965
  });
15785
15966
  }
15967
+ for (const golden of options.rejects ?? []) {
15968
+ const named = options.validators.find((validator) => validator.name === golden.validator);
15969
+ if (named === void 0) {
15970
+ failures.push({
15971
+ fixture: "reject",
15972
+ validator: golden.validator,
15973
+ reasons: [`no configured validator is named '${golden.validator}', so its reject golden cannot run`]
15974
+ });
15975
+ continue;
15976
+ }
15977
+ if (run(named, golden.input).ok) failures.push({
15978
+ fixture: "reject",
15979
+ validator: golden.validator,
15980
+ reasons: ["the configured validator accepts the fixture the contract's own validator rejects; a same name replacement must be at least as strict"]
15981
+ });
15982
+ }
15786
15983
  return {
15787
15984
  ok: failures.length === 0,
15788
15985
  failures
@@ -15915,13 +16112,15 @@ function validateOrchestrateOptions(opts) {
15915
16112
  const acceptFixture = selfTest?.accept ?? contract?.goldenAccept;
15916
16113
  const rejectFixture = selfTest?.reject ?? contract?.goldenReject;
15917
16114
  if (selfTest !== void 0 && acceptFixture === void 0 && rejectFixture === void 0) throw new ConfigError("orchestrate finishValidation.selfTest requires an accept or reject fixture");
15918
- if (acceptFixture !== void 0 || rejectFixture !== void 0) {
16115
+ const rejectGoldens = contract?.goldenRejects;
16116
+ if (acceptFixture !== void 0 || rejectFixture !== void 0 || rejectGoldens !== void 0) {
15919
16117
  const report = selfTestFinishValidation({
15920
16118
  validators: fv.validators,
15921
16119
  ...acceptFixture === void 0 ? {} : { accept: acceptFixture },
15922
- ...rejectFixture === void 0 ? {} : { reject: rejectFixture }
16120
+ ...rejectFixture === void 0 ? {} : { reject: rejectFixture },
16121
+ ...rejectGoldens === void 0 ? {} : { rejects: rejectGoldens }
15923
16122
  });
15924
- if (!report.ok) throw new ConfigError("the finish validation self test failed BEFORE any provider call: " + report.failures.map((failure) => failure.validator === void 0 ? failure.reasons.join("; ") : `validator '${failure.validator}' rejected the accept fixture: ` + failure.reasons.join("; ")).join("; "));
16123
+ if (!report.ok) throw new ConfigError("the finish validation self test failed BEFORE any provider call: " + report.failures.map((failure) => failure.validator === void 0 ? failure.reasons.join("; ") : failure.fixture === "reject" ? `validator '${failure.validator}' failed its reject golden: ` + failure.reasons.join("; ") : `validator '${failure.validator}' rejected the accept fixture: ` + failure.reasons.join("; ")).join("; "));
15925
16124
  }
15926
16125
  }
15927
16126
  if (opts.synthesis !== void 0) {
@@ -18315,19 +18514,24 @@ function preflightEstimate(input) {
18315
18514
  }
18316
18515
  const acceptFixture = fv.selfTest?.accept ?? fv.contract?.goldenAccept;
18317
18516
  const rejectFixture = fv.selfTest?.reject ?? fv.contract?.goldenReject;
18517
+ const rejectGoldens = fv.contract?.goldenRejects;
18318
18518
  let selfTestOutcome = "skipped";
18319
- if (acceptFixture !== void 0 || rejectFixture !== void 0) {
18519
+ if (acceptFixture !== void 0 || rejectFixture !== void 0 || rejectGoldens !== void 0) {
18320
18520
  const report = selfTestFinishValidation({
18321
18521
  validators: fv.validators,
18322
18522
  ...acceptFixture === void 0 ? {} : { accept: acceptFixture },
18323
- ...rejectFixture === void 0 ? {} : { reject: rejectFixture }
18523
+ ...rejectFixture === void 0 ? {} : { reject: rejectFixture },
18524
+ ...rejectGoldens === void 0 ? {} : { rejects: rejectGoldens }
18324
18525
  });
18325
18526
  selfTestOutcome = report.ok ? "passed" : "failed";
18326
- for (const failure of report.failures) findings.push({
18327
- severity: "error",
18328
- code: "output-contract-validator-mismatch",
18329
- message: failure.validator === void 0 ? failure.reasons.join("; ") : `validator '${failure.validator}' rejected the golden accept fixture: ` + failure.reasons.join("; ")
18330
- });
18527
+ for (const failure of report.failures) {
18528
+ const weakened = failure.fixture === "reject" && failure.validator !== void 0;
18529
+ findings.push({
18530
+ severity: "error",
18531
+ code: weakened ? "output-contract-validator-weakened" : "output-contract-validator-mismatch",
18532
+ message: failure.validator === void 0 ? failure.reasons.join("; ") : weakened ? `validator '${failure.validator}' failed its reject golden: ` + failure.reasons.join("; ") : `validator '${failure.validator}' rejected the golden accept fixture: ` + failure.reasons.join("; ")
18533
+ });
18534
+ }
18331
18535
  }
18332
18536
  finishValidationEcho = {
18333
18537
  ...fv.contract === void 0 ? {} : { contractHash: fv.contract.hash },
@@ -20155,4 +20359,4 @@ function createSandboxBridge(ctx, options) {
20155
20359
  };
20156
20360
  }
20157
20361
  //#endregion
20158
- export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, 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, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, 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_DEPTH_CEILING, 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_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, 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, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, 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, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, 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, snapshotUsage, spawnDepthOf, 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 };
20362
+ export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_MIN_SHARE, 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, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINISH_SCHEMA, FINISH_TOOL_NAME, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalMatcher, JournalMissError, JournalOrderViolation, 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_DEPTH_CEILING, 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_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_AGENT_SCHEMA, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, 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, identityJcs, implementationAgentProfile, invoiceFromJournal, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, 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, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, 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, 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulvar/core",
3
- "version": "1.77.0",
3
+ "version": "1.78.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",