@rulvar/core 1.71.0 → 1.72.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 +191 -1
- package/dist/index.js +564 -159
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -6265,6 +6265,19 @@ declare function requiredFieldsValidator(options: {
|
|
|
6265
6265
|
fields: string[];
|
|
6266
6266
|
name?: string;
|
|
6267
6267
|
}): FinishValidator;
|
|
6268
|
+
/**
|
|
6269
|
+
* Requires the result text's word count (whitespace separated tokens;
|
|
6270
|
+
* an empty text counts zero) to sit inside the configured bounds (the
|
|
6271
|
+
* v1.71 experiment review, P0.7: a formal length requirement must be
|
|
6272
|
+
* code, never a natural-language plea the model may round away). At
|
|
6273
|
+
* least one bound is required; both are positive integers with
|
|
6274
|
+
* min <= max. Default name 'word-count'.
|
|
6275
|
+
*/
|
|
6276
|
+
declare function wordCountValidator(options: {
|
|
6277
|
+
min?: number;
|
|
6278
|
+
max?: number;
|
|
6279
|
+
name?: string;
|
|
6280
|
+
}): FinishValidator;
|
|
6268
6281
|
/** The default citation shape: a path with an extension, a colon, a line number. */
|
|
6269
6282
|
declare const DEFAULT_CITATION_PATTERN = "[\\w./-]+\\.\\w+:\\d+";
|
|
6270
6283
|
/** The default preserved share, the improvement plan's RV-202 gate. */
|
|
@@ -6294,6 +6307,24 @@ declare function evidencePreservedValidator(options?: {
|
|
|
6294
6307
|
name?: string;
|
|
6295
6308
|
}): FinishValidator;
|
|
6296
6309
|
/**
|
|
6310
|
+
* Requires at least `min` matches of `pattern` INSIDE every named
|
|
6311
|
+
* section (the v1.71 experiment review, P1.2: a total citation count
|
|
6312
|
+
* hides sections carrying zero provenance). A section's slice runs
|
|
6313
|
+
* from its FIRST occurrence to the next found section marker in text
|
|
6314
|
+
* position order, or to the end of the text; a marker absent from the
|
|
6315
|
+
* text is its own failure reason, because coverage of a missing
|
|
6316
|
+
* section cannot silently count as satisfied.
|
|
6317
|
+
* requiredSectionsValidator still owns plain presence. Default name
|
|
6318
|
+
* 'section-citations'.
|
|
6319
|
+
*/
|
|
6320
|
+
declare function sectionCitationsValidator(options: {
|
|
6321
|
+
sections: string[];
|
|
6322
|
+
pattern?: string;
|
|
6323
|
+
flags?: string;
|
|
6324
|
+
min: number;
|
|
6325
|
+
name?: string;
|
|
6326
|
+
}): FinishValidator;
|
|
6327
|
+
/**
|
|
6297
6328
|
* Requires at least `min` matches of `pattern` in the result text (the
|
|
6298
6329
|
* plan's citation and source count checks: a file:line pattern, a URL
|
|
6299
6330
|
* pattern). The pattern compiles at construction (invalid patterns are a
|
|
@@ -6308,6 +6339,113 @@ declare function minMatchesValidator(options: {
|
|
|
6308
6339
|
name?: string;
|
|
6309
6340
|
}): FinishValidator;
|
|
6310
6341
|
//#endregion
|
|
6342
|
+
//#region src/orchestrator/output-contract.d.ts
|
|
6343
|
+
/** The golden citation sample used with {@link DEFAULT_CITATION_PATTERN}. */
|
|
6344
|
+
declare const DEFAULT_CITATION_SAMPLE = "docs/output-contract.md:1";
|
|
6345
|
+
/** The citation demands of a {@link FinishContractManifest}. */
|
|
6346
|
+
interface FinishContractCitations {
|
|
6347
|
+
/** Regex source over the result text; default {@link DEFAULT_CITATION_PATTERN}. */
|
|
6348
|
+
pattern?: string;
|
|
6349
|
+
flags?: string;
|
|
6350
|
+
/** Total matches required across the whole result text. */
|
|
6351
|
+
min?: number;
|
|
6352
|
+
/** Matches required inside EVERY declared section; requires `sections`. */
|
|
6353
|
+
perSection?: number;
|
|
6354
|
+
/**
|
|
6355
|
+
* A literal string matching `pattern`, embedded in the golden
|
|
6356
|
+
* fixtures (a regex cannot be sampled mechanically). REQUIRED with a
|
|
6357
|
+
* custom pattern; defaults to {@link DEFAULT_CITATION_SAMPLE} for
|
|
6358
|
+
* the default pattern. Must contain no whitespace and no declared
|
|
6359
|
+
* section marker.
|
|
6360
|
+
*/
|
|
6361
|
+
sample?: string;
|
|
6362
|
+
}
|
|
6363
|
+
/**
|
|
6364
|
+
* The single source of truth of a textual finish contract: what the
|
|
6365
|
+
* prompt promises IS what the validators enforce. Declare only textual
|
|
6366
|
+
* demands here (sections, length, citations); an object-shaped result
|
|
6367
|
+
* belongs to {@link requiredSectionsValidator}'s sibling
|
|
6368
|
+
* requiredFieldsValidator and a host-provided selfTest accept fixture.
|
|
6369
|
+
*/
|
|
6370
|
+
interface FinishContractManifest {
|
|
6371
|
+
/** Literal section markers the result must contain. */
|
|
6372
|
+
sections?: string[];
|
|
6373
|
+
/** Word bounds over the result text (whitespace separated tokens). */
|
|
6374
|
+
words?: {
|
|
6375
|
+
min?: number;
|
|
6376
|
+
max?: number;
|
|
6377
|
+
};
|
|
6378
|
+
/** Citation demands over the result text. */
|
|
6379
|
+
citations?: FinishContractCitations;
|
|
6380
|
+
}
|
|
6381
|
+
/** What {@link finishContract} builds from a manifest. */
|
|
6382
|
+
interface FinishContract {
|
|
6383
|
+
/** The normalized manifest (defaults applied), frozen. */
|
|
6384
|
+
readonly manifest: FinishContractManifest;
|
|
6385
|
+
/** sha256 hex over the JCS serialization of the normalized manifest. */
|
|
6386
|
+
readonly hash: string;
|
|
6387
|
+
/** The stock validators enforcing the manifest; names are 'contract-*'. */
|
|
6388
|
+
readonly validators: FinishValidator[];
|
|
6389
|
+
/** The contract statement for the model, one demand per line. */
|
|
6390
|
+
readonly promptLines: readonly string[];
|
|
6391
|
+
/** A generated fixture every contract validator accepts. */
|
|
6392
|
+
readonly goldenAccept: FinishValidationInput;
|
|
6393
|
+
/**
|
|
6394
|
+
* A generated fixture at least one contract validator rejects.
|
|
6395
|
+
* Absent when the manifest carries only upper bounds, because an
|
|
6396
|
+
* empty result is then legitimately acceptable.
|
|
6397
|
+
*/
|
|
6398
|
+
readonly goldenReject?: FinishValidationInput;
|
|
6399
|
+
}
|
|
6400
|
+
/**
|
|
6401
|
+
* Builds a {@link FinishContract} from one manifest: validation and the
|
|
6402
|
+
* golden fixtures happen HERE, at configuration time, so a
|
|
6403
|
+
* self-contradictory contract (mandatory content alone above words.max,
|
|
6404
|
+
* an unsampled custom pattern) fails before any run exists. Spread
|
|
6405
|
+
* `contract.validators` into finishValidation.validators and pass the
|
|
6406
|
+
* contract itself as finishValidation.contract; the orchestrator then
|
|
6407
|
+
* injects `promptLines` into the coordination and synthesis prompts,
|
|
6408
|
+
* runs the golden self test at construction, and journals the frozen
|
|
6409
|
+
* bundle descriptor.
|
|
6410
|
+
*/
|
|
6411
|
+
declare function finishContract(manifest: FinishContractManifest): FinishContract;
|
|
6412
|
+
/** Golden fixtures of the construction self test. */
|
|
6413
|
+
interface FinishSelfTestFixtures {
|
|
6414
|
+
/** Every configured validator must accept this input. */
|
|
6415
|
+
accept?: FinishValidationInput;
|
|
6416
|
+
/** At least one configured validator must reject this input. */
|
|
6417
|
+
reject?: FinishValidationInput;
|
|
6418
|
+
}
|
|
6419
|
+
/** One self test failure. */
|
|
6420
|
+
interface FinishSelfTestFailure {
|
|
6421
|
+
fixture: "accept" | "reject";
|
|
6422
|
+
/** The rejecting validator on the accept side; absent on the vacuous reject side. */
|
|
6423
|
+
validator?: string;
|
|
6424
|
+
reasons: string[];
|
|
6425
|
+
}
|
|
6426
|
+
/** The self test verdict over one validator set. */
|
|
6427
|
+
interface FinishSelfTestReport {
|
|
6428
|
+
ok: boolean;
|
|
6429
|
+
failures: FinishSelfTestFailure[];
|
|
6430
|
+
}
|
|
6431
|
+
/**
|
|
6432
|
+
* Runs a configured validator set against golden fixtures BEFORE any
|
|
6433
|
+
* provider call exists (the v1.71 experiment review, P0.3): the accept
|
|
6434
|
+
* fixture must pass every validator (a stale validator rejecting a
|
|
6435
|
+
* correct skeleton is exactly the drift the experiment died of, three
|
|
6436
|
+
* renamed sections deep into a paid run), and the reject fixture must
|
|
6437
|
+
* fail at least one (a set that accepts the known-bad input validates
|
|
6438
|
+
* nothing). A validator that THROWS here is a host defect and the
|
|
6439
|
+
* ConfigError propagates, the same posture the live loop takes.
|
|
6440
|
+
* Deterministic and free: validators are pure synchronous host code by
|
|
6441
|
+
* contract, so this costs zero provider calls.
|
|
6442
|
+
*/
|
|
6443
|
+
declare function selfTestFinishValidation(options: {
|
|
6444
|
+
validators: FinishValidator[];
|
|
6445
|
+
accept?: FinishValidationInput;
|
|
6446
|
+
reject?: FinishValidationInput;
|
|
6447
|
+
}): FinishSelfTestReport;
|
|
6448
|
+
//#endregion
|
|
6311
6449
|
//#region src/orchestrator/handles.d.ts
|
|
6312
6450
|
/** The per-child digest handed to the orchestrator. */
|
|
6313
6451
|
interface TaskDigest {
|
|
@@ -6899,6 +7037,32 @@ interface FinishValidationSpec {
|
|
|
6899
7037
|
* finish fails the run.
|
|
6900
7038
|
*/
|
|
6901
7039
|
maxRepairs?: number;
|
|
7040
|
+
/**
|
|
7041
|
+
* The unified output contract this validator set enforces (the v1.71
|
|
7042
|
+
* experiment review, P0.1/P0.2). Construction then runs the golden
|
|
7043
|
+
* self test with the contract's fixtures as defaults, the contract's
|
|
7044
|
+
* promptLines join the validator statement in BOTH the coordination
|
|
7045
|
+
* and synthesis prompts, every contract validator must appear in
|
|
7046
|
+
* `validators` by name (a promised contract nobody enforces is drift
|
|
7047
|
+
* by omission, a ConfigError), and the run journals ONE frozen
|
|
7048
|
+
* bundle descriptor (decisionType
|
|
7049
|
+
* 'orchestrator_finish_validation_bundle') recording the contract
|
|
7050
|
+
* hash and the validator names. A resumed segment whose live
|
|
7051
|
+
* contract hash differs appends a SUPERSEDING descriptor instead of
|
|
7052
|
+
* failing, because fixing a stale validator and resuming is the
|
|
7053
|
+
* intended remedy, never a fault. Absent = byte identical pre 1.72
|
|
7054
|
+
* behavior.
|
|
7055
|
+
*/
|
|
7056
|
+
contract?: FinishContract;
|
|
7057
|
+
/**
|
|
7058
|
+
* Golden fixtures of the construction self test (the v1.71
|
|
7059
|
+
* experiment review, P0.3), overriding the contract's generated
|
|
7060
|
+
* fixtures: a host with custom validators supplies an accept fixture
|
|
7061
|
+
* those validators actually accept. Fixtures without a contract run
|
|
7062
|
+
* the self test on their own. Absent with no contract = no self
|
|
7063
|
+
* test, the pre 1.72 behavior.
|
|
7064
|
+
*/
|
|
7065
|
+
selfTest?: FinishSelfTestFixtures;
|
|
6902
7066
|
}
|
|
6903
7067
|
interface OrchestrateOptions {
|
|
6904
7068
|
model?: ModelSpec;
|
|
@@ -8603,6 +8767,20 @@ interface PreflightInput {
|
|
|
8603
8767
|
* demand comparison needs them declared here.
|
|
8604
8768
|
*/
|
|
8605
8769
|
quotaRules?: readonly QuotaRule[];
|
|
8770
|
+
/**
|
|
8771
|
+
* The opt in finish validation self test (the v1.71 experiment
|
|
8772
|
+
* review, P1.1). Programmatic only: validator functions cannot ride
|
|
8773
|
+
* a JSON config file, so the CLI never carries this. When present,
|
|
8774
|
+
* preflight runs the SAME golden self test orchestrate runs at
|
|
8775
|
+
* construction and reports every drift as an error finding (code
|
|
8776
|
+
* 'output-contract-validator-mismatch') instead of throwing, so a
|
|
8777
|
+
* planner surfaces it next to the quota and budget findings.
|
|
8778
|
+
*/
|
|
8779
|
+
finishValidation?: {
|
|
8780
|
+
validators: FinishValidator[];
|
|
8781
|
+
contract?: FinishContract;
|
|
8782
|
+
selfTest?: FinishSelfTestFixtures;
|
|
8783
|
+
};
|
|
8606
8784
|
}
|
|
8607
8785
|
/** One linter verdict; `spawn` names the wave entry it is about. */
|
|
8608
8786
|
interface PreflightFinding {
|
|
@@ -8728,6 +8906,18 @@ interface PreflightReport {
|
|
|
8728
8906
|
tokens: number;
|
|
8729
8907
|
};
|
|
8730
8908
|
};
|
|
8909
|
+
/**
|
|
8910
|
+
* Present when input.finishValidation was provided: the self test
|
|
8911
|
+
* echo. `selfTest` reflects the golden fixture run alone
|
|
8912
|
+
* ('skipped' = no fixture resolvable); containment drift between a
|
|
8913
|
+
* contract and the validator set reports through findings either
|
|
8914
|
+
* way.
|
|
8915
|
+
*/
|
|
8916
|
+
finishValidation?: {
|
|
8917
|
+
contractHash?: string;
|
|
8918
|
+
validators: string[];
|
|
8919
|
+
selfTest: "passed" | "failed" | "skipped";
|
|
8920
|
+
};
|
|
8731
8921
|
findings: PreflightFinding[];
|
|
8732
8922
|
}
|
|
8733
8923
|
/**
|
|
@@ -9241,4 +9431,4 @@ interface SandboxBridge {
|
|
|
9241
9431
|
declare const SANDBOX_AGENT_OPT_KEYS: readonly string[];
|
|
9242
9432
|
declare function createSandboxBridge(ctx: Ctx<never>, options: SandboxBridgeOptions): SandboxBridge;
|
|
9243
9433
|
//#endregion
|
|
9244
|
-
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_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, FinishInfo, 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, 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, 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, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
|
9434
|
+
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, 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 };
|
package/dist/index.js
CHANGED
|
@@ -15091,6 +15091,465 @@ function buildOrchestratorTools(runtime, profileCardText, options) {
|
|
|
15091
15091
|
return tools;
|
|
15092
15092
|
}
|
|
15093
15093
|
//#endregion
|
|
15094
|
+
//#region src/orchestrator/finish-validators.ts
|
|
15095
|
+
/**
|
|
15096
|
+
* Deterministic host validation of the orchestrator finish result (the
|
|
15097
|
+
* v1.40.0 improvement plan's RV-204 slice). A validator is plain
|
|
15098
|
+
* synchronous host code judging the finish({ result }) argument; the
|
|
15099
|
+
* orchestrator runtime runs the configured set on every schema valid
|
|
15100
|
+
* finish call, returns the failure reasons to the model as the call's
|
|
15101
|
+
* error tool result (a bounded repair turn), and fails the run with a
|
|
15102
|
+
* typed error when the repair bound is exhausted. Verdicts journal as
|
|
15103
|
+
* decision entries, so a resume rolls the SAME verdicts forward without
|
|
15104
|
+
* re-running validator code.
|
|
15105
|
+
*/
|
|
15106
|
+
const ok = { ok: true };
|
|
15107
|
+
function requireNonEmptyStrings(values, what) {
|
|
15108
|
+
if (!Array.isArray(values) || values.length === 0) throw new ConfigError(`${what} must be a non empty array of strings`);
|
|
15109
|
+
for (const value of values) if (typeof value !== "string" || value.length === 0) throw new ConfigError(`${what} must contain only non empty strings`);
|
|
15110
|
+
return values;
|
|
15111
|
+
}
|
|
15112
|
+
/**
|
|
15113
|
+
* Requires every named section to appear LITERALLY in the result text
|
|
15114
|
+
* (a heading like 'FINDINGS' or any marker the goal demands). Default
|
|
15115
|
+
* name 'required-sections'; pass `name` to run several instances.
|
|
15116
|
+
*/
|
|
15117
|
+
function requiredSectionsValidator(options) {
|
|
15118
|
+
const sections = requireNonEmptyStrings(options.sections, "requiredSectionsValidator sections");
|
|
15119
|
+
return {
|
|
15120
|
+
name: options.name ?? "required-sections",
|
|
15121
|
+
validate: (input) => {
|
|
15122
|
+
const missing = sections.filter((section) => !input.text.includes(section));
|
|
15123
|
+
return missing.length === 0 ? ok : {
|
|
15124
|
+
ok: false,
|
|
15125
|
+
reasons: missing.map((section) => `required section '${section}' is missing`)
|
|
15126
|
+
};
|
|
15127
|
+
}
|
|
15128
|
+
};
|
|
15129
|
+
}
|
|
15130
|
+
/**
|
|
15131
|
+
* Requires the result to be a JSON object carrying every named field
|
|
15132
|
+
* with a substantial value: present, not null, and not an empty or
|
|
15133
|
+
* whitespace only string (empty arrays, zero, and false COUNT as
|
|
15134
|
+
* present; emptiness rules beyond strings belong to a custom
|
|
15135
|
+
* validator). Default name 'required-fields'.
|
|
15136
|
+
*/
|
|
15137
|
+
function requiredFieldsValidator(options) {
|
|
15138
|
+
const fields = requireNonEmptyStrings(options.fields, "requiredFieldsValidator fields");
|
|
15139
|
+
return {
|
|
15140
|
+
name: options.name ?? "required-fields",
|
|
15141
|
+
validate: (input) => {
|
|
15142
|
+
const result = input.result;
|
|
15143
|
+
if (typeof result !== "object" || result === null || Array.isArray(result)) return {
|
|
15144
|
+
ok: false,
|
|
15145
|
+
reasons: ["the finish result is not a JSON object"]
|
|
15146
|
+
};
|
|
15147
|
+
const record = result;
|
|
15148
|
+
const reasons = [];
|
|
15149
|
+
for (const field of fields) {
|
|
15150
|
+
const value = record[field];
|
|
15151
|
+
if (value === void 0 || value === null) reasons.push(`required field '${field}' is missing`);
|
|
15152
|
+
else if (typeof value === "string" && value.trim().length === 0) reasons.push(`required field '${field}' is empty`);
|
|
15153
|
+
}
|
|
15154
|
+
return reasons.length === 0 ? ok : {
|
|
15155
|
+
ok: false,
|
|
15156
|
+
reasons
|
|
15157
|
+
};
|
|
15158
|
+
}
|
|
15159
|
+
};
|
|
15160
|
+
}
|
|
15161
|
+
/**
|
|
15162
|
+
* Requires the result text's word count (whitespace separated tokens;
|
|
15163
|
+
* an empty text counts zero) to sit inside the configured bounds (the
|
|
15164
|
+
* v1.71 experiment review, P0.7: a formal length requirement must be
|
|
15165
|
+
* code, never a natural-language plea the model may round away). At
|
|
15166
|
+
* least one bound is required; both are positive integers with
|
|
15167
|
+
* min <= max. Default name 'word-count'.
|
|
15168
|
+
*/
|
|
15169
|
+
function wordCountValidator(options) {
|
|
15170
|
+
const { min, max } = options;
|
|
15171
|
+
if (min === void 0 && max === void 0) throw new ConfigError("wordCountValidator requires min, max, or both");
|
|
15172
|
+
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)}`);
|
|
15173
|
+
if (min !== void 0 && max !== void 0 && min > max) throw new ConfigError(`wordCountValidator min ${String(min)} exceeds max ${String(max)}`);
|
|
15174
|
+
return {
|
|
15175
|
+
name: options.name ?? "word-count",
|
|
15176
|
+
validate: (input) => {
|
|
15177
|
+
const trimmed = input.text.trim();
|
|
15178
|
+
const count = trimmed.length === 0 ? 0 : trimmed.split(/\s+/).length;
|
|
15179
|
+
const reasons = [];
|
|
15180
|
+
if (min !== void 0 && count < min) reasons.push(`result word count ${String(count)} is below the required minimum ${String(min)}`);
|
|
15181
|
+
if (max !== void 0 && count > max) reasons.push(`result word count ${String(count)} exceeds the maximum ${String(max)}`);
|
|
15182
|
+
return reasons.length === 0 ? ok : {
|
|
15183
|
+
ok: false,
|
|
15184
|
+
reasons
|
|
15185
|
+
};
|
|
15186
|
+
}
|
|
15187
|
+
};
|
|
15188
|
+
}
|
|
15189
|
+
/** The default citation shape: a path with an extension, a colon, a line number. */
|
|
15190
|
+
const DEFAULT_CITATION_PATTERN = "[\\w./-]+\\.\\w+:\\d+";
|
|
15191
|
+
/** The default preserved share, the improvement plan's RV-202 gate. */
|
|
15192
|
+
const DEFAULT_EVIDENCE_MIN_SHARE = .95;
|
|
15193
|
+
const MAX_LISTED_CITATIONS = 20;
|
|
15194
|
+
function listCitations(values) {
|
|
15195
|
+
return values.length <= MAX_LISTED_CITATIONS ? values.join(", ") : `${values.slice(0, MAX_LISTED_CITATIONS).join(", ")} and ${String(values.length - MAX_LISTED_CITATIONS)} more`;
|
|
15196
|
+
}
|
|
15197
|
+
/**
|
|
15198
|
+
* The RV-202 evidence preservation contract: the finish result must
|
|
15199
|
+
* PRESERVE the citations the children actually produced. Distinct
|
|
15200
|
+
* matches of `pattern` are collected across the outputs of children
|
|
15201
|
+
* settled 'ok' (spawn order); at least `minShare` of them (default
|
|
15202
|
+
* {@link DEFAULT_EVIDENCE_MIN_SHARE}, the plan's 95 percent gate,
|
|
15203
|
+
* compared as a ceiling on the required count so an exact boundary like
|
|
15204
|
+
* 19 of 20 passes) must appear literally in the result text. Zero child
|
|
15205
|
+
* citations pass vacuously. With `requireKnown: true` the contract also
|
|
15206
|
+
* runs in reverse: every citation in the RESULT must appear in some
|
|
15207
|
+
* child's output, so a fabricated but pattern valid citation is
|
|
15208
|
+
* rejected instead of silently counting as evidence. Rejection reasons
|
|
15209
|
+
* list the missing (and unknown) citations, capped at 20, so the repair
|
|
15210
|
+
* turn can restore them. Purely textual and deterministic; checking
|
|
15211
|
+
* that cited targets EXIST on disk is host territory (a custom
|
|
15212
|
+
* validator), not this contract. Default name 'evidence-preserved'.
|
|
15213
|
+
*/
|
|
15214
|
+
function evidencePreservedValidator(options) {
|
|
15215
|
+
const pattern = options?.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
|
|
15216
|
+
const flags = options?.flags ?? "";
|
|
15217
|
+
const globalFlags = flags.includes("g") ? flags : `${flags}g`;
|
|
15218
|
+
try {
|
|
15219
|
+
new RegExp(pattern, globalFlags);
|
|
15220
|
+
} catch (thrown) {
|
|
15221
|
+
throw new ConfigError(`evidencePreservedValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
15222
|
+
}
|
|
15223
|
+
const minShare = options?.minShare ?? .95;
|
|
15224
|
+
if (typeof minShare !== "number" || !Number.isFinite(minShare) || minShare <= 0 || minShare > 1) throw new ConfigError(`evidencePreservedValidator minShare must be a number in (0, 1]; got ${String(minShare)}`);
|
|
15225
|
+
return {
|
|
15226
|
+
name: options?.name ?? "evidence-preserved",
|
|
15227
|
+
validate: (input) => {
|
|
15228
|
+
const cited = /* @__PURE__ */ new Set();
|
|
15229
|
+
for (const child of input.children ?? []) {
|
|
15230
|
+
if (child.status !== "ok" && child.salvageableOutput !== true) continue;
|
|
15231
|
+
for (const match of child.text.match(new RegExp(pattern, globalFlags)) ?? []) cited.add(match);
|
|
15232
|
+
}
|
|
15233
|
+
const reasons = [];
|
|
15234
|
+
if (cited.size > 0) {
|
|
15235
|
+
const missing = [...cited].filter((citation) => !input.text.includes(citation));
|
|
15236
|
+
const preserved = cited.size - missing.length;
|
|
15237
|
+
if (preserved < Math.ceil(minShare * cited.size - 1e-9)) reasons.push(`evidence preservation ${String(preserved)} of ${String(cited.size)} child citations is below the required share ${String(minShare)}; missing: ${listCitations(missing)}`);
|
|
15238
|
+
}
|
|
15239
|
+
if (options?.requireKnown === true) {
|
|
15240
|
+
const fabricated = [...new Set(input.text.match(new RegExp(pattern, globalFlags)) ?? [])].filter((citation) => !cited.has(citation));
|
|
15241
|
+
if (fabricated.length > 0) reasons.push(`unknown citations not present in any child report: ${listCitations(fabricated)}`);
|
|
15242
|
+
}
|
|
15243
|
+
return reasons.length === 0 ? ok : {
|
|
15244
|
+
ok: false,
|
|
15245
|
+
reasons
|
|
15246
|
+
};
|
|
15247
|
+
}
|
|
15248
|
+
};
|
|
15249
|
+
}
|
|
15250
|
+
/**
|
|
15251
|
+
* Requires at least `min` matches of `pattern` INSIDE every named
|
|
15252
|
+
* section (the v1.71 experiment review, P1.2: a total citation count
|
|
15253
|
+
* hides sections carrying zero provenance). A section's slice runs
|
|
15254
|
+
* from its FIRST occurrence to the next found section marker in text
|
|
15255
|
+
* position order, or to the end of the text; a marker absent from the
|
|
15256
|
+
* text is its own failure reason, because coverage of a missing
|
|
15257
|
+
* section cannot silently count as satisfied.
|
|
15258
|
+
* requiredSectionsValidator still owns plain presence. Default name
|
|
15259
|
+
* 'section-citations'.
|
|
15260
|
+
*/
|
|
15261
|
+
function sectionCitationsValidator(options) {
|
|
15262
|
+
const sections = requireNonEmptyStrings(options.sections, "sectionCitationsValidator sections");
|
|
15263
|
+
const pattern = options.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
|
|
15264
|
+
const flags = options.flags ?? "";
|
|
15265
|
+
const globalFlags = flags.includes("g") ? flags : `${flags}g`;
|
|
15266
|
+
try {
|
|
15267
|
+
new RegExp(pattern, globalFlags);
|
|
15268
|
+
} catch (thrown) {
|
|
15269
|
+
throw new ConfigError(`sectionCitationsValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
15270
|
+
}
|
|
15271
|
+
if (!Number.isInteger(options.min) || options.min < 1) throw new ConfigError(`sectionCitationsValidator min must be a positive integer; got ${String(options.min)}`);
|
|
15272
|
+
return {
|
|
15273
|
+
name: options.name ?? "section-citations",
|
|
15274
|
+
validate: (input) => {
|
|
15275
|
+
const positions = /* @__PURE__ */ new Map();
|
|
15276
|
+
for (const section of sections) {
|
|
15277
|
+
const at = input.text.indexOf(section);
|
|
15278
|
+
if (at >= 0) positions.set(section, at);
|
|
15279
|
+
}
|
|
15280
|
+
const ordered = [...positions.entries()].sort((a, b) => a[1] - b[1]);
|
|
15281
|
+
const reasons = [];
|
|
15282
|
+
for (const section of sections) {
|
|
15283
|
+
const at = positions.get(section);
|
|
15284
|
+
if (at === void 0) {
|
|
15285
|
+
reasons.push(`required section '${section}' is missing, so its citation coverage cannot be judged`);
|
|
15286
|
+
continue;
|
|
15287
|
+
}
|
|
15288
|
+
const next = ordered.find(([, position]) => position > at);
|
|
15289
|
+
const matches = input.text.slice(at, next === void 0 ? input.text.length : next[1]).match(new RegExp(pattern, globalFlags))?.length ?? 0;
|
|
15290
|
+
if (matches < options.min) reasons.push(`section '${section}' carries ${String(matches)} citations matching /${pattern}/; at least ${String(options.min)} required`);
|
|
15291
|
+
}
|
|
15292
|
+
return reasons.length === 0 ? ok : {
|
|
15293
|
+
ok: false,
|
|
15294
|
+
reasons
|
|
15295
|
+
};
|
|
15296
|
+
}
|
|
15297
|
+
};
|
|
15298
|
+
}
|
|
15299
|
+
/**
|
|
15300
|
+
* Requires at least `min` matches of `pattern` in the result text (the
|
|
15301
|
+
* plan's citation and source count checks: a file:line pattern, a URL
|
|
15302
|
+
* pattern). The pattern compiles at construction (invalid patterns are a
|
|
15303
|
+
* ConfigError before any run exists) and matches globally; `min` is a
|
|
15304
|
+
* positive integer. Default name 'min-matches'; pass `name` to run
|
|
15305
|
+
* several instances, because names must be unique per orchestrate call.
|
|
15306
|
+
*/
|
|
15307
|
+
function minMatchesValidator(options) {
|
|
15308
|
+
const flags = options.flags ?? "";
|
|
15309
|
+
const globalFlags = flags.includes("g") ? flags : `${flags}g`;
|
|
15310
|
+
try {
|
|
15311
|
+
new RegExp(options.pattern, globalFlags);
|
|
15312
|
+
} catch (thrown) {
|
|
15313
|
+
throw new ConfigError(`minMatchesValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
15314
|
+
}
|
|
15315
|
+
if (!Number.isInteger(options.min) || options.min < 1) throw new ConfigError(`minMatchesValidator min must be a positive integer; got ${String(options.min)}`);
|
|
15316
|
+
return {
|
|
15317
|
+
name: options.name ?? "min-matches",
|
|
15318
|
+
validate: (input) => {
|
|
15319
|
+
const found = input.text.match(new RegExp(options.pattern, globalFlags))?.length ?? 0;
|
|
15320
|
+
return found >= options.min ? ok : {
|
|
15321
|
+
ok: false,
|
|
15322
|
+
reasons: [`expected at least ${String(options.min)} matches of /${options.pattern}/${flags}; found ${String(found)}`]
|
|
15323
|
+
};
|
|
15324
|
+
}
|
|
15325
|
+
};
|
|
15326
|
+
}
|
|
15327
|
+
//#endregion
|
|
15328
|
+
//#region src/orchestrator/output-contract.ts
|
|
15329
|
+
/**
|
|
15330
|
+
* The unified output contract (the v1.71 experiment review: P0.1 the
|
|
15331
|
+
* manifest, P0.2 the frozen bundle, P0.3 the golden self test). ONE
|
|
15332
|
+
* immutable manifest generates the prompt statement the model reads,
|
|
15333
|
+
* the stock validator set the host enforces, a stable content hash,
|
|
15334
|
+
* and golden self-test fixtures, so the prompt and the validators
|
|
15335
|
+
* cannot drift apart by construction. The experiment's terminal
|
|
15336
|
+
* failure was exactly that drift: the question renamed three sections,
|
|
15337
|
+
* the harness validator kept the old names, and the mismatch survived
|
|
15338
|
+
* until paid provider turns had burned. With a contract, the same
|
|
15339
|
+
* mistake is a ConfigError before the first provider call.
|
|
15340
|
+
*/
|
|
15341
|
+
/** The golden citation sample used with {@link DEFAULT_CITATION_PATTERN}. */
|
|
15342
|
+
const DEFAULT_CITATION_SAMPLE = "docs/output-contract.md:1";
|
|
15343
|
+
/** The filler token golden skeletons pad word counts with. */
|
|
15344
|
+
const FILLER_WORD = "placeholder";
|
|
15345
|
+
function requirePositiveInt(value, what) {
|
|
15346
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) throw new ConfigError(`${what} must be a positive integer; got ${String(value)}`);
|
|
15347
|
+
return value;
|
|
15348
|
+
}
|
|
15349
|
+
function countWords(text) {
|
|
15350
|
+
const trimmed = text.trim();
|
|
15351
|
+
return trimmed.length === 0 ? 0 : trimmed.split(/\s+/).length;
|
|
15352
|
+
}
|
|
15353
|
+
/**
|
|
15354
|
+
* Builds a {@link FinishContract} from one manifest: validation and the
|
|
15355
|
+
* golden fixtures happen HERE, at configuration time, so a
|
|
15356
|
+
* self-contradictory contract (mandatory content alone above words.max,
|
|
15357
|
+
* an unsampled custom pattern) fails before any run exists. Spread
|
|
15358
|
+
* `contract.validators` into finishValidation.validators and pass the
|
|
15359
|
+
* contract itself as finishValidation.contract; the orchestrator then
|
|
15360
|
+
* injects `promptLines` into the coordination and synthesis prompts,
|
|
15361
|
+
* runs the golden self test at construction, and journals the frozen
|
|
15362
|
+
* bundle descriptor.
|
|
15363
|
+
*/
|
|
15364
|
+
function finishContract(manifest) {
|
|
15365
|
+
if (typeof manifest !== "object" || manifest === null) throw new ConfigError("finishContract manifest must be an object");
|
|
15366
|
+
const { sections, words, citations } = manifest;
|
|
15367
|
+
if (sections === void 0 && words === void 0 && citations === void 0) throw new ConfigError("finishContract manifest must declare sections, words, or citations");
|
|
15368
|
+
let normalizedSections;
|
|
15369
|
+
if (sections !== void 0) {
|
|
15370
|
+
if (!Array.isArray(sections) || sections.length === 0) throw new ConfigError("finishContract sections must be a non empty array of strings");
|
|
15371
|
+
const seen = /* @__PURE__ */ new Set();
|
|
15372
|
+
for (const section of sections) {
|
|
15373
|
+
if (typeof section !== "string" || section.trim().length === 0) throw new ConfigError("finishContract sections must contain only non empty strings");
|
|
15374
|
+
if (section.includes("\n")) throw new ConfigError(`finishContract section '${section}' must be a single line`);
|
|
15375
|
+
if (seen.has(section)) throw new ConfigError(`finishContract sections must be unique; '${section}' repeats`);
|
|
15376
|
+
seen.add(section);
|
|
15377
|
+
}
|
|
15378
|
+
normalizedSections = [...sections];
|
|
15379
|
+
}
|
|
15380
|
+
let normalizedWords;
|
|
15381
|
+
if (words !== void 0) {
|
|
15382
|
+
if (typeof words !== "object" || words === null) throw new ConfigError("finishContract words must be an object");
|
|
15383
|
+
if (words.min === void 0 && words.max === void 0) throw new ConfigError("finishContract words requires min, max, or both");
|
|
15384
|
+
if (words.min !== void 0) requirePositiveInt(words.min, "finishContract words.min");
|
|
15385
|
+
if (words.max !== void 0) requirePositiveInt(words.max, "finishContract words.max");
|
|
15386
|
+
if (words.min !== void 0 && words.max !== void 0 && words.min > words.max) throw new ConfigError(`finishContract words.min ${String(words.min)} exceeds words.max ${String(words.max)}`);
|
|
15387
|
+
normalizedWords = {
|
|
15388
|
+
...words.min === void 0 ? {} : { min: words.min },
|
|
15389
|
+
...words.max === void 0 ? {} : { max: words.max }
|
|
15390
|
+
};
|
|
15391
|
+
}
|
|
15392
|
+
let normalizedCitations;
|
|
15393
|
+
if (citations !== void 0) {
|
|
15394
|
+
if (typeof citations !== "object" || citations === null) throw new ConfigError("finishContract citations must be an object");
|
|
15395
|
+
if (citations.min === void 0 && citations.perSection === void 0) throw new ConfigError("finishContract citations requires min, perSection, or both");
|
|
15396
|
+
if (citations.min !== void 0) requirePositiveInt(citations.min, "finishContract citations.min");
|
|
15397
|
+
if (citations.perSection !== void 0) {
|
|
15398
|
+
requirePositiveInt(citations.perSection, "finishContract citations.perSection");
|
|
15399
|
+
if (normalizedSections === void 0) throw new ConfigError("finishContract citations.perSection requires sections");
|
|
15400
|
+
}
|
|
15401
|
+
const pattern = citations.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
|
|
15402
|
+
const flags = citations.flags ?? "";
|
|
15403
|
+
const globalFlags = flags.includes("g") ? flags : `${flags}g`;
|
|
15404
|
+
try {
|
|
15405
|
+
new RegExp(pattern, globalFlags);
|
|
15406
|
+
} catch (thrown) {
|
|
15407
|
+
throw new ConfigError(`finishContract citations.pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
15408
|
+
}
|
|
15409
|
+
const sample = citations.sample ?? (citations.pattern === void 0 ? "docs/output-contract.md:1" : void 0);
|
|
15410
|
+
if (sample === void 0) throw new ConfigError("finishContract citations.sample is required with a custom pattern: the golden fixtures embed a literal match");
|
|
15411
|
+
if (typeof sample !== "string" || sample.length === 0 || /\s/u.test(sample)) throw new ConfigError("finishContract citations.sample must be a non empty string without whitespace");
|
|
15412
|
+
if (!new RegExp(pattern, globalFlags).test(sample)) throw new ConfigError(`finishContract citations.sample '${sample}' does not match the citation pattern`);
|
|
15413
|
+
if (normalizedSections?.some((section) => sample.includes(section)) === true) throw new ConfigError("finishContract citations.sample must not contain a declared section marker");
|
|
15414
|
+
normalizedCitations = {
|
|
15415
|
+
pattern,
|
|
15416
|
+
flags,
|
|
15417
|
+
sample,
|
|
15418
|
+
...citations.min === void 0 ? {} : { min: citations.min },
|
|
15419
|
+
...citations.perSection === void 0 ? {} : { perSection: citations.perSection }
|
|
15420
|
+
};
|
|
15421
|
+
}
|
|
15422
|
+
const normalized = {
|
|
15423
|
+
...normalizedSections === void 0 ? {} : { sections: normalizedSections },
|
|
15424
|
+
...normalizedWords === void 0 ? {} : { words: normalizedWords },
|
|
15425
|
+
...normalizedCitations === void 0 ? {} : { citations: normalizedCitations }
|
|
15426
|
+
};
|
|
15427
|
+
const hash = createHash("sha256").update(jcsSerialize(normalized), "utf8").digest("hex");
|
|
15428
|
+
const validators = [];
|
|
15429
|
+
if (normalizedSections !== void 0) validators.push(requiredSectionsValidator({
|
|
15430
|
+
sections: normalizedSections,
|
|
15431
|
+
name: "contract-sections"
|
|
15432
|
+
}));
|
|
15433
|
+
if (normalizedWords !== void 0) validators.push(wordCountValidator({
|
|
15434
|
+
...normalizedWords,
|
|
15435
|
+
name: "contract-words"
|
|
15436
|
+
}));
|
|
15437
|
+
if (normalizedCitations?.min !== void 0) validators.push(minMatchesValidator({
|
|
15438
|
+
pattern: normalizedCitations.pattern,
|
|
15439
|
+
flags: normalizedCitations.flags,
|
|
15440
|
+
min: normalizedCitations.min,
|
|
15441
|
+
name: "contract-citations"
|
|
15442
|
+
}));
|
|
15443
|
+
if (normalizedCitations?.perSection !== void 0 && normalizedSections !== void 0) validators.push(sectionCitationsValidator({
|
|
15444
|
+
sections: normalizedSections,
|
|
15445
|
+
pattern: normalizedCitations.pattern,
|
|
15446
|
+
flags: normalizedCitations.flags,
|
|
15447
|
+
min: normalizedCitations.perSection,
|
|
15448
|
+
name: "contract-section-citations"
|
|
15449
|
+
}));
|
|
15450
|
+
const promptLines = [];
|
|
15451
|
+
if (normalizedSections !== void 0) promptLines.push("The final result must contain each of these section markers verbatim: " + normalizedSections.map((section) => `'${section}'`).join(", ") + ".");
|
|
15452
|
+
if (normalizedWords !== void 0) {
|
|
15453
|
+
const { min, max } = normalizedWords;
|
|
15454
|
+
if (min !== void 0 && max !== void 0) promptLines.push(`The final result must be between ${String(min)} and ${String(max)} words (whitespace separated).`);
|
|
15455
|
+
else if (min !== void 0) promptLines.push(`The final result must be at least ${String(min)} words (whitespace separated).`);
|
|
15456
|
+
else if (max !== void 0) promptLines.push(`The final result must be at most ${String(max)} words (whitespace separated).`);
|
|
15457
|
+
}
|
|
15458
|
+
if (normalizedCitations !== void 0) {
|
|
15459
|
+
if (normalizedCitations.min !== void 0) promptLines.push(`Include at least ${String(normalizedCitations.min)} citations matching /${normalizedCitations.pattern}/ overall (for example '${normalizedCitations.sample}').`);
|
|
15460
|
+
if (normalizedCitations.perSection !== void 0) promptLines.push(`Every required section must itself contain at least ${String(normalizedCitations.perSection)} such citations.`);
|
|
15461
|
+
}
|
|
15462
|
+
const lines = [];
|
|
15463
|
+
const perSection = normalizedCitations?.perSection ?? 0;
|
|
15464
|
+
for (const section of normalizedSections ?? []) {
|
|
15465
|
+
lines.push(section);
|
|
15466
|
+
if (normalizedCitations !== void 0 && perSection > 0) {
|
|
15467
|
+
const sample = normalizedCitations.sample;
|
|
15468
|
+
lines.push(Array.from({ length: perSection }, () => sample).join(" "));
|
|
15469
|
+
}
|
|
15470
|
+
}
|
|
15471
|
+
if (normalizedCitations !== void 0) {
|
|
15472
|
+
const placed = (normalizedSections?.length ?? 0) * perSection;
|
|
15473
|
+
const deficit = Math.max(0, (normalizedCitations.min ?? 0) - placed);
|
|
15474
|
+
if (deficit > 0) {
|
|
15475
|
+
const sample = normalizedCitations.sample;
|
|
15476
|
+
lines.push(Array.from({ length: deficit }, () => sample).join(" "));
|
|
15477
|
+
}
|
|
15478
|
+
}
|
|
15479
|
+
let goldenText = lines.join("\n");
|
|
15480
|
+
const mandatoryWords = countWords(goldenText);
|
|
15481
|
+
if (normalizedWords?.max !== void 0 && mandatoryWords > normalizedWords.max) throw new ConfigError(`finishContract is self contradictory: its mandatory content alone is ${String(mandatoryWords)} words, above words.max ${String(normalizedWords.max)}`);
|
|
15482
|
+
if (normalizedWords?.min !== void 0 && mandatoryWords < normalizedWords.min) {
|
|
15483
|
+
const padding = Array.from({ length: normalizedWords.min - mandatoryWords }, () => FILLER_WORD).join(" ");
|
|
15484
|
+
goldenText = goldenText.length === 0 ? padding : `${goldenText}\n${padding}`;
|
|
15485
|
+
}
|
|
15486
|
+
const goldenAccept = Object.freeze({
|
|
15487
|
+
result: goldenText,
|
|
15488
|
+
text: goldenText,
|
|
15489
|
+
children: Object.freeze([Object.freeze({
|
|
15490
|
+
handle: 0,
|
|
15491
|
+
nodeId: "contract-golden",
|
|
15492
|
+
status: "ok",
|
|
15493
|
+
text: goldenText
|
|
15494
|
+
})])
|
|
15495
|
+
});
|
|
15496
|
+
const goldenReject = normalizedSections !== void 0 || normalizedWords?.min !== void 0 || normalizedCitations !== void 0 ? Object.freeze({
|
|
15497
|
+
result: "",
|
|
15498
|
+
text: "",
|
|
15499
|
+
children: Object.freeze([])
|
|
15500
|
+
}) : void 0;
|
|
15501
|
+
return Object.freeze({
|
|
15502
|
+
manifest: Object.freeze(normalized),
|
|
15503
|
+
hash,
|
|
15504
|
+
validators,
|
|
15505
|
+
promptLines: Object.freeze(promptLines),
|
|
15506
|
+
goldenAccept,
|
|
15507
|
+
...goldenReject === void 0 ? {} : { goldenReject }
|
|
15508
|
+
});
|
|
15509
|
+
}
|
|
15510
|
+
/**
|
|
15511
|
+
* Runs a configured validator set against golden fixtures BEFORE any
|
|
15512
|
+
* provider call exists (the v1.71 experiment review, P0.3): the accept
|
|
15513
|
+
* fixture must pass every validator (a stale validator rejecting a
|
|
15514
|
+
* correct skeleton is exactly the drift the experiment died of, three
|
|
15515
|
+
* renamed sections deep into a paid run), and the reject fixture must
|
|
15516
|
+
* fail at least one (a set that accepts the known-bad input validates
|
|
15517
|
+
* nothing). A validator that THROWS here is a host defect and the
|
|
15518
|
+
* ConfigError propagates, the same posture the live loop takes.
|
|
15519
|
+
* Deterministic and free: validators are pure synchronous host code by
|
|
15520
|
+
* contract, so this costs zero provider calls.
|
|
15521
|
+
*/
|
|
15522
|
+
function selfTestFinishValidation(options) {
|
|
15523
|
+
const run = (validator, input) => {
|
|
15524
|
+
try {
|
|
15525
|
+
return validator.validate(input);
|
|
15526
|
+
} catch (thrown) {
|
|
15527
|
+
throw new ConfigError(`finish validator '${validator.name}' threw during the self test instead of returning a verdict: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
15528
|
+
}
|
|
15529
|
+
};
|
|
15530
|
+
const failures = [];
|
|
15531
|
+
const accept = options.accept;
|
|
15532
|
+
if (accept !== void 0) for (const validator of options.validators) {
|
|
15533
|
+
const verdict = run(validator, accept);
|
|
15534
|
+
if (!verdict.ok) failures.push({
|
|
15535
|
+
fixture: "accept",
|
|
15536
|
+
validator: validator.name,
|
|
15537
|
+
reasons: verdict.reasons
|
|
15538
|
+
});
|
|
15539
|
+
}
|
|
15540
|
+
const reject = options.reject;
|
|
15541
|
+
if (reject !== void 0) {
|
|
15542
|
+
if (!options.validators.some((validator) => !run(validator, reject).ok)) failures.push({
|
|
15543
|
+
fixture: "reject",
|
|
15544
|
+
reasons: ["every configured validator accepts the known-bad fixture; the validation is vacuous"]
|
|
15545
|
+
});
|
|
15546
|
+
}
|
|
15547
|
+
return {
|
|
15548
|
+
ok: failures.length === 0,
|
|
15549
|
+
failures
|
|
15550
|
+
};
|
|
15551
|
+
}
|
|
15552
|
+
//#endregion
|
|
15094
15553
|
//#region src/orchestrator/orchestrate.ts
|
|
15095
15554
|
/**
|
|
15096
15555
|
* The mode (c) dynamic orchestrator (M6-T07/T08).
|
|
@@ -15192,6 +15651,25 @@ function validateOrchestrateOptions(opts) {
|
|
|
15192
15651
|
seen.add(validator.name);
|
|
15193
15652
|
}
|
|
15194
15653
|
if (fv.maxRepairs !== void 0) requireNonNegativeInteger(fv.maxRepairs, "orchestrate finishValidation.maxRepairs");
|
|
15654
|
+
const contract = fv.contract;
|
|
15655
|
+
if (contract !== void 0) {
|
|
15656
|
+
const shape = contract;
|
|
15657
|
+
if (typeof shape.hash !== "string" || !Array.isArray(shape.validators) || !Array.isArray(shape.promptLines) || shape.goldenAccept === void 0) throw new ConfigError("orchestrate finishValidation.contract must be a finishContract(...) product");
|
|
15658
|
+
for (const contractValidator of contract.validators) if (!seen.has(contractValidator.name)) throw new ConfigError(`orchestrate finishValidation.contract validator '${contractValidator.name}' is not in finishValidation.validators; spread contract.validators into the set so the promised contract is actually enforced`);
|
|
15659
|
+
}
|
|
15660
|
+
const selfTest = fv.selfTest;
|
|
15661
|
+
if (selfTest !== void 0 && (typeof selfTest !== "object" || selfTest === null)) throw new ConfigError("orchestrate finishValidation.selfTest must be an object");
|
|
15662
|
+
const acceptFixture = selfTest?.accept ?? contract?.goldenAccept;
|
|
15663
|
+
const rejectFixture = selfTest?.reject ?? contract?.goldenReject;
|
|
15664
|
+
if (selfTest !== void 0 && acceptFixture === void 0 && rejectFixture === void 0) throw new ConfigError("orchestrate finishValidation.selfTest requires an accept or reject fixture");
|
|
15665
|
+
if (acceptFixture !== void 0 || rejectFixture !== void 0) {
|
|
15666
|
+
const report = selfTestFinishValidation({
|
|
15667
|
+
validators: fv.validators,
|
|
15668
|
+
...acceptFixture === void 0 ? {} : { accept: acceptFixture },
|
|
15669
|
+
...rejectFixture === void 0 ? {} : { reject: rejectFixture }
|
|
15670
|
+
});
|
|
15671
|
+
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("; "));
|
|
15672
|
+
}
|
|
15195
15673
|
}
|
|
15196
15674
|
if (opts.synthesis !== void 0) {
|
|
15197
15675
|
const synthesis = opts.synthesis;
|
|
@@ -15240,7 +15718,11 @@ function finishValidationPromptLines(spec) {
|
|
|
15240
15718
|
if (spec === void 0) return [];
|
|
15241
15719
|
const names = spec.validators.map((validator) => validator.name).join(", ");
|
|
15242
15720
|
const repairs = spec.maxRepairs ?? 1;
|
|
15243
|
-
return [
|
|
15721
|
+
return [
|
|
15722
|
+
`The host validates every finish({ result }) with deterministic validators: ${names}.`,
|
|
15723
|
+
...spec.contract === void 0 ? [] : spec.contract.promptLines,
|
|
15724
|
+
"A rejected finish returns the failure reasons as the tool error result; repair the result and call finish again. " + (repairs === 0 ? "No repair attempt is granted: the first rejected finish fails the run." : repairs === 1 ? "At most one repair attempt is granted before the run fails." : `At most ${String(repairs)} repair attempts are granted before the run fails.`)
|
|
15725
|
+
];
|
|
15244
15726
|
}
|
|
15245
15727
|
/**
|
|
15246
15728
|
* The partial-salvage contract rides the PROMPT exactly like finish
|
|
@@ -16229,6 +16711,37 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
16229
16711
|
}
|
|
16230
16712
|
};
|
|
16231
16713
|
};
|
|
16714
|
+
/**
|
|
16715
|
+
* The frozen bundle descriptor (the v1.71 experiment review,
|
|
16716
|
+
* P0.2): with a contract configured, the run durably records WHAT
|
|
16717
|
+
* validates it. One decision entry per distinct contract hash, in
|
|
16718
|
+
* supersession order: a resume under the SAME contract appends
|
|
16719
|
+
* nothing (the descriptor already exists), and a resume under a
|
|
16720
|
+
* FIXED contract appends a superseding descriptor instead of
|
|
16721
|
+
* failing, because repairing a stale validator and resuming is the
|
|
16722
|
+
* intended remedy. No contract (or no validators at all) keeps the
|
|
16723
|
+
* journal byte identical, awaits included.
|
|
16724
|
+
*/
|
|
16725
|
+
if (validationSpec?.contract !== void 0) {
|
|
16726
|
+
const bundles = internals.replayer.snapshot().filter((entry) => entry.kind === "decision" && entry.scope === callingState.scope && entry.value?.decisionType === "orchestrator_finish_validation_bundle").map((entry) => entry.value);
|
|
16727
|
+
const last = bundles.at(-1);
|
|
16728
|
+
if (last?.contractHash !== validationSpec.contract.hash) await internals.replayer.appendSinglePhase({
|
|
16729
|
+
scope: callingState.scope,
|
|
16730
|
+
key: `finish-validation-bundle:${String(bundles.length)}`,
|
|
16731
|
+
kind: "decision",
|
|
16732
|
+
status: "ok",
|
|
16733
|
+
spanId: internals.spans.mint(callingState.spanId),
|
|
16734
|
+
site: "orchestrator-finish-validation-bundle",
|
|
16735
|
+
value: {
|
|
16736
|
+
decisionType: "orchestrator_finish_validation_bundle",
|
|
16737
|
+
ordinal: bundles.length,
|
|
16738
|
+
contractHash: validationSpec.contract.hash,
|
|
16739
|
+
validators: validationSpec.validators.map((validator) => validator.name),
|
|
16740
|
+
maxRepairs: validationSpec.maxRepairs ?? 1,
|
|
16741
|
+
...last?.contractHash === void 0 ? {} : { supersedes: last.contractHash }
|
|
16742
|
+
}
|
|
16743
|
+
});
|
|
16744
|
+
}
|
|
16232
16745
|
const agentOpts = {
|
|
16233
16746
|
role: "orchestrate",
|
|
16234
16747
|
result: "full",
|
|
@@ -17275,6 +17788,54 @@ function preflightEstimate(input) {
|
|
|
17275
17788
|
requests: 0,
|
|
17276
17789
|
tokens: 0
|
|
17277
17790
|
});
|
|
17791
|
+
/**
|
|
17792
|
+
* The finish validation self test (the v1.71 experiment review,
|
|
17793
|
+
* P1.1): the SAME golden checks orchestrate runs at construction,
|
|
17794
|
+
* reported as error findings instead of throws. The experiment's
|
|
17795
|
+
* initial preflight was silent while a stale validator waited to
|
|
17796
|
+
* reject every correct answer; with the contract declared here, that
|
|
17797
|
+
* drift is a red finding before the first paid call.
|
|
17798
|
+
*/
|
|
17799
|
+
let finishValidationEcho;
|
|
17800
|
+
if (input.finishValidation !== void 0) {
|
|
17801
|
+
const fv = input.finishValidation;
|
|
17802
|
+
if (!Array.isArray(fv.validators) || fv.validators.length === 0) throw new ConfigError("preflight finishValidation.validators must be a non empty array of validators");
|
|
17803
|
+
const names = /* @__PURE__ */ new Set();
|
|
17804
|
+
for (const candidate of fv.validators) {
|
|
17805
|
+
const validator = candidate;
|
|
17806
|
+
if (typeof validator.name !== "string" || validator.name.length === 0) throw new ConfigError("every preflight finish validator must carry a non empty name");
|
|
17807
|
+
if (typeof validator.validate !== "function") throw new ConfigError(`preflight finish validator '${validator.name}' has no validate function`);
|
|
17808
|
+
names.add(validator.name);
|
|
17809
|
+
}
|
|
17810
|
+
if (fv.contract !== void 0) {
|
|
17811
|
+
for (const contractValidator of fv.contract.validators) if (!names.has(contractValidator.name)) findings.push({
|
|
17812
|
+
severity: "error",
|
|
17813
|
+
code: "output-contract-validator-mismatch",
|
|
17814
|
+
message: `contract validator '${contractValidator.name}' is not in the configured validator set; the promised contract is not enforced`
|
|
17815
|
+
});
|
|
17816
|
+
}
|
|
17817
|
+
const acceptFixture = fv.selfTest?.accept ?? fv.contract?.goldenAccept;
|
|
17818
|
+
const rejectFixture = fv.selfTest?.reject ?? fv.contract?.goldenReject;
|
|
17819
|
+
let selfTestOutcome = "skipped";
|
|
17820
|
+
if (acceptFixture !== void 0 || rejectFixture !== void 0) {
|
|
17821
|
+
const report = selfTestFinishValidation({
|
|
17822
|
+
validators: fv.validators,
|
|
17823
|
+
...acceptFixture === void 0 ? {} : { accept: acceptFixture },
|
|
17824
|
+
...rejectFixture === void 0 ? {} : { reject: rejectFixture }
|
|
17825
|
+
});
|
|
17826
|
+
selfTestOutcome = report.ok ? "passed" : "failed";
|
|
17827
|
+
for (const failure of report.failures) findings.push({
|
|
17828
|
+
severity: "error",
|
|
17829
|
+
code: "output-contract-validator-mismatch",
|
|
17830
|
+
message: failure.validator === void 0 ? failure.reasons.join("; ") : `validator '${failure.validator}' rejected the golden accept fixture: ` + failure.reasons.join("; ")
|
|
17831
|
+
});
|
|
17832
|
+
}
|
|
17833
|
+
finishValidationEcho = {
|
|
17834
|
+
...fv.contract === void 0 ? {} : { contractHash: fv.contract.hash },
|
|
17835
|
+
validators: fv.validators.map((validator) => validator.name),
|
|
17836
|
+
selfTest: selfTestOutcome
|
|
17837
|
+
};
|
|
17838
|
+
}
|
|
17278
17839
|
const severityRank = {
|
|
17279
17840
|
error: 0,
|
|
17280
17841
|
warning: 1,
|
|
@@ -17314,6 +17875,7 @@ function preflightEstimate(input) {
|
|
|
17314
17875
|
perProvider,
|
|
17315
17876
|
...runCeiling === void 0 ? {} : { runCeiling }
|
|
17316
17877
|
},
|
|
17878
|
+
...finishValidationEcho === void 0 ? {} : { finishValidation: finishValidationEcho },
|
|
17317
17879
|
findings
|
|
17318
17880
|
};
|
|
17319
17881
|
}
|
|
@@ -17416,163 +17978,6 @@ var KeyedLimiter = class {
|
|
|
17416
17978
|
}
|
|
17417
17979
|
};
|
|
17418
17980
|
//#endregion
|
|
17419
|
-
//#region src/orchestrator/finish-validators.ts
|
|
17420
|
-
/**
|
|
17421
|
-
* Deterministic host validation of the orchestrator finish result (the
|
|
17422
|
-
* v1.40.0 improvement plan's RV-204 slice). A validator is plain
|
|
17423
|
-
* synchronous host code judging the finish({ result }) argument; the
|
|
17424
|
-
* orchestrator runtime runs the configured set on every schema valid
|
|
17425
|
-
* finish call, returns the failure reasons to the model as the call's
|
|
17426
|
-
* error tool result (a bounded repair turn), and fails the run with a
|
|
17427
|
-
* typed error when the repair bound is exhausted. Verdicts journal as
|
|
17428
|
-
* decision entries, so a resume rolls the SAME verdicts forward without
|
|
17429
|
-
* re-running validator code.
|
|
17430
|
-
*/
|
|
17431
|
-
const ok = { ok: true };
|
|
17432
|
-
function requireNonEmptyStrings(values, what) {
|
|
17433
|
-
if (!Array.isArray(values) || values.length === 0) throw new ConfigError(`${what} must be a non empty array of strings`);
|
|
17434
|
-
for (const value of values) if (typeof value !== "string" || value.length === 0) throw new ConfigError(`${what} must contain only non empty strings`);
|
|
17435
|
-
return values;
|
|
17436
|
-
}
|
|
17437
|
-
/**
|
|
17438
|
-
* Requires every named section to appear LITERALLY in the result text
|
|
17439
|
-
* (a heading like 'FINDINGS' or any marker the goal demands). Default
|
|
17440
|
-
* name 'required-sections'; pass `name` to run several instances.
|
|
17441
|
-
*/
|
|
17442
|
-
function requiredSectionsValidator(options) {
|
|
17443
|
-
const sections = requireNonEmptyStrings(options.sections, "requiredSectionsValidator sections");
|
|
17444
|
-
return {
|
|
17445
|
-
name: options.name ?? "required-sections",
|
|
17446
|
-
validate: (input) => {
|
|
17447
|
-
const missing = sections.filter((section) => !input.text.includes(section));
|
|
17448
|
-
return missing.length === 0 ? ok : {
|
|
17449
|
-
ok: false,
|
|
17450
|
-
reasons: missing.map((section) => `required section '${section}' is missing`)
|
|
17451
|
-
};
|
|
17452
|
-
}
|
|
17453
|
-
};
|
|
17454
|
-
}
|
|
17455
|
-
/**
|
|
17456
|
-
* Requires the result to be a JSON object carrying every named field
|
|
17457
|
-
* with a substantial value: present, not null, and not an empty or
|
|
17458
|
-
* whitespace only string (empty arrays, zero, and false COUNT as
|
|
17459
|
-
* present; emptiness rules beyond strings belong to a custom
|
|
17460
|
-
* validator). Default name 'required-fields'.
|
|
17461
|
-
*/
|
|
17462
|
-
function requiredFieldsValidator(options) {
|
|
17463
|
-
const fields = requireNonEmptyStrings(options.fields, "requiredFieldsValidator fields");
|
|
17464
|
-
return {
|
|
17465
|
-
name: options.name ?? "required-fields",
|
|
17466
|
-
validate: (input) => {
|
|
17467
|
-
const result = input.result;
|
|
17468
|
-
if (typeof result !== "object" || result === null || Array.isArray(result)) return {
|
|
17469
|
-
ok: false,
|
|
17470
|
-
reasons: ["the finish result is not a JSON object"]
|
|
17471
|
-
};
|
|
17472
|
-
const record = result;
|
|
17473
|
-
const reasons = [];
|
|
17474
|
-
for (const field of fields) {
|
|
17475
|
-
const value = record[field];
|
|
17476
|
-
if (value === void 0 || value === null) reasons.push(`required field '${field}' is missing`);
|
|
17477
|
-
else if (typeof value === "string" && value.trim().length === 0) reasons.push(`required field '${field}' is empty`);
|
|
17478
|
-
}
|
|
17479
|
-
return reasons.length === 0 ? ok : {
|
|
17480
|
-
ok: false,
|
|
17481
|
-
reasons
|
|
17482
|
-
};
|
|
17483
|
-
}
|
|
17484
|
-
};
|
|
17485
|
-
}
|
|
17486
|
-
/** The default citation shape: a path with an extension, a colon, a line number. */
|
|
17487
|
-
const DEFAULT_CITATION_PATTERN = "[\\w./-]+\\.\\w+:\\d+";
|
|
17488
|
-
/** The default preserved share, the improvement plan's RV-202 gate. */
|
|
17489
|
-
const DEFAULT_EVIDENCE_MIN_SHARE = .95;
|
|
17490
|
-
const MAX_LISTED_CITATIONS = 20;
|
|
17491
|
-
function listCitations(values) {
|
|
17492
|
-
return values.length <= MAX_LISTED_CITATIONS ? values.join(", ") : `${values.slice(0, MAX_LISTED_CITATIONS).join(", ")} and ${String(values.length - MAX_LISTED_CITATIONS)} more`;
|
|
17493
|
-
}
|
|
17494
|
-
/**
|
|
17495
|
-
* The RV-202 evidence preservation contract: the finish result must
|
|
17496
|
-
* PRESERVE the citations the children actually produced. Distinct
|
|
17497
|
-
* matches of `pattern` are collected across the outputs of children
|
|
17498
|
-
* settled 'ok' (spawn order); at least `minShare` of them (default
|
|
17499
|
-
* {@link DEFAULT_EVIDENCE_MIN_SHARE}, the plan's 95 percent gate,
|
|
17500
|
-
* compared as a ceiling on the required count so an exact boundary like
|
|
17501
|
-
* 19 of 20 passes) must appear literally in the result text. Zero child
|
|
17502
|
-
* citations pass vacuously. With `requireKnown: true` the contract also
|
|
17503
|
-
* runs in reverse: every citation in the RESULT must appear in some
|
|
17504
|
-
* child's output, so a fabricated but pattern valid citation is
|
|
17505
|
-
* rejected instead of silently counting as evidence. Rejection reasons
|
|
17506
|
-
* list the missing (and unknown) citations, capped at 20, so the repair
|
|
17507
|
-
* turn can restore them. Purely textual and deterministic; checking
|
|
17508
|
-
* that cited targets EXIST on disk is host territory (a custom
|
|
17509
|
-
* validator), not this contract. Default name 'evidence-preserved'.
|
|
17510
|
-
*/
|
|
17511
|
-
function evidencePreservedValidator(options) {
|
|
17512
|
-
const pattern = options?.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
|
|
17513
|
-
const flags = options?.flags ?? "";
|
|
17514
|
-
const globalFlags = flags.includes("g") ? flags : `${flags}g`;
|
|
17515
|
-
try {
|
|
17516
|
-
new RegExp(pattern, globalFlags);
|
|
17517
|
-
} catch (thrown) {
|
|
17518
|
-
throw new ConfigError(`evidencePreservedValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
17519
|
-
}
|
|
17520
|
-
const minShare = options?.minShare ?? .95;
|
|
17521
|
-
if (typeof minShare !== "number" || !Number.isFinite(minShare) || minShare <= 0 || minShare > 1) throw new ConfigError(`evidencePreservedValidator minShare must be a number in (0, 1]; got ${String(minShare)}`);
|
|
17522
|
-
return {
|
|
17523
|
-
name: options?.name ?? "evidence-preserved",
|
|
17524
|
-
validate: (input) => {
|
|
17525
|
-
const cited = /* @__PURE__ */ new Set();
|
|
17526
|
-
for (const child of input.children ?? []) {
|
|
17527
|
-
if (child.status !== "ok" && child.salvageableOutput !== true) continue;
|
|
17528
|
-
for (const match of child.text.match(new RegExp(pattern, globalFlags)) ?? []) cited.add(match);
|
|
17529
|
-
}
|
|
17530
|
-
const reasons = [];
|
|
17531
|
-
if (cited.size > 0) {
|
|
17532
|
-
const missing = [...cited].filter((citation) => !input.text.includes(citation));
|
|
17533
|
-
const preserved = cited.size - missing.length;
|
|
17534
|
-
if (preserved < Math.ceil(minShare * cited.size - 1e-9)) reasons.push(`evidence preservation ${String(preserved)} of ${String(cited.size)} child citations is below the required share ${String(minShare)}; missing: ${listCitations(missing)}`);
|
|
17535
|
-
}
|
|
17536
|
-
if (options?.requireKnown === true) {
|
|
17537
|
-
const fabricated = [...new Set(input.text.match(new RegExp(pattern, globalFlags)) ?? [])].filter((citation) => !cited.has(citation));
|
|
17538
|
-
if (fabricated.length > 0) reasons.push(`unknown citations not present in any child report: ${listCitations(fabricated)}`);
|
|
17539
|
-
}
|
|
17540
|
-
return reasons.length === 0 ? ok : {
|
|
17541
|
-
ok: false,
|
|
17542
|
-
reasons
|
|
17543
|
-
};
|
|
17544
|
-
}
|
|
17545
|
-
};
|
|
17546
|
-
}
|
|
17547
|
-
/**
|
|
17548
|
-
* Requires at least `min` matches of `pattern` in the result text (the
|
|
17549
|
-
* plan's citation and source count checks: a file:line pattern, a URL
|
|
17550
|
-
* pattern). The pattern compiles at construction (invalid patterns are a
|
|
17551
|
-
* ConfigError before any run exists) and matches globally; `min` is a
|
|
17552
|
-
* positive integer. Default name 'min-matches'; pass `name` to run
|
|
17553
|
-
* several instances, because names must be unique per orchestrate call.
|
|
17554
|
-
*/
|
|
17555
|
-
function minMatchesValidator(options) {
|
|
17556
|
-
const flags = options.flags ?? "";
|
|
17557
|
-
const globalFlags = flags.includes("g") ? flags : `${flags}g`;
|
|
17558
|
-
try {
|
|
17559
|
-
new RegExp(options.pattern, globalFlags);
|
|
17560
|
-
} catch (thrown) {
|
|
17561
|
-
throw new ConfigError(`minMatchesValidator pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
17562
|
-
}
|
|
17563
|
-
if (!Number.isInteger(options.min) || options.min < 1) throw new ConfigError(`minMatchesValidator min must be a positive integer; got ${String(options.min)}`);
|
|
17564
|
-
return {
|
|
17565
|
-
name: options.name ?? "min-matches",
|
|
17566
|
-
validate: (input) => {
|
|
17567
|
-
const found = input.text.match(new RegExp(options.pattern, globalFlags))?.length ?? 0;
|
|
17568
|
-
return found >= options.min ? ok : {
|
|
17569
|
-
ok: false,
|
|
17570
|
-
reasons: [`expected at least ${String(options.min)} matches of /${options.pattern}/${flags}; found ${String(found)}`]
|
|
17571
|
-
};
|
|
17572
|
-
}
|
|
17573
|
-
};
|
|
17574
|
-
}
|
|
17575
|
-
//#endregion
|
|
17576
17981
|
//#region src/engine/events.ts
|
|
17577
17982
|
/**
|
|
17578
17983
|
* Per-run event machinery (M1-T10): the span registry (run > phase >
|
|
@@ -19250,4 +19655,4 @@ function createSandboxBridge(ctx, options) {
|
|
|
19250
19655
|
};
|
|
19251
19656
|
}
|
|
19252
19657
|
//#endregion
|
|
19253
|
-
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_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, 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, selectStructuredOutputTier, shouldCompact, snapshotUsage, spawnDepthOf, summarizeInstruction, summarizeOutput, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolContract, toolsetHash, ttlState, usageViolations, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateUsageLimits, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
|
19658
|
+
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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulvar/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.72.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",
|