@tangle-network/agent-knowledge 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,15 @@
1
- import { S as SourceRecord, c as KnowledgeIndex, d as KnowledgeSearchResult, e as SourceRegistry, f as KnowledgeEvent, g as KnowledgeEventType, h as KnowledgePage, b as KnowledgeGraph, i as KnowledgeLintFinding, j as KnowledgeWriteBlock, k as KnowledgeClaim, l as KnowledgeRelease, m as KnowledgeWriteParseResult } from './types-C17sAROL.js';
2
- export { C as ClaimRef, n as KnowledgeBaseCandidate, K as KnowledgeGraphEdge, a as KnowledgeGraphNode, o as KnowledgeId, p as KnowledgePolicy, q as KnowledgeRelation, r as KnowledgeUnit, s as SourceAnchor } from './types-C17sAROL.js';
1
+ import { S as SourceRecord, c as KnowledgeIndex, d as KnowledgeSearchResult, e as SourceRegistry, f as KnowledgeEvent, g as KnowledgeLintFinding, h as KnowledgeEventType, i as KnowledgePage, b as KnowledgeGraph, j as KnowledgeWriteBlock, k as KnowledgeClaim, l as KnowledgeRelease, m as KnowledgeWriteParseResult } from './types-6x0OpfW6.js';
2
+ export { C as ClaimRef, n as KnowledgeBaseCandidate, K as KnowledgeGraphEdge, a as KnowledgeGraphNode, o as KnowledgeId, p as KnowledgePolicy, q as KnowledgeRelation, r as KnowledgeUnit, s as SourceAnchor } from './types-6x0OpfW6.js';
3
3
  import { KnowledgeRequirementCategory, KnowledgeAcquisitionMode, KnowledgeImportance, KnowledgeFreshness, KnowledgeSensitivity, KnowledgeRequirement, KnowledgeBundle, KnowledgeReadinessReport, UserQuestion, DataAcquisitionPlan, ControlRuntimeConfig, ControlEvalResult, RunRecord, AnalystSeverity, AnalystFinding, ReleaseTraceEvidence, GateDecision, ReleaseConfidenceScorecard } from '@tangle-network/agent-eval';
4
- import { R as RunRetrievalImprovementLoopResult, a as RunRetrievalImprovementLoopOptions } from './index-BLxw1I_F.js';
5
- export { B as BuildRetrievalBenchmarkCasesFromQrelsOptions, b as BuildRetrievalEvalDispatchOptions, c as BuildRetrievalParameterCandidatesOptions, I as INDUSTRY_MEMORY_BENCHMARKS, d as INDUSTRY_RAG_BENCHMARKS, K as KnowledgeAnswerBenchmarkCase, e as KnowledgeAnswerBenchmarkTaskKind, f as KnowledgeBenchmarkArtifact, g as KnowledgeBenchmarkCase, h as KnowledgeBenchmarkCaseBase, i as KnowledgeBenchmarkDistribution, j as KnowledgeBenchmarkEvaluation, k as KnowledgeBenchmarkFamily, l as KnowledgeBenchmarkReport, m as KnowledgeBenchmarkResponder, n as KnowledgeBenchmarkScenario, o as KnowledgeBenchmarkSliceSummary, p as KnowledgeBenchmarkSource, q as KnowledgeBenchmarkSpec, r as KnowledgeBenchmarkSplit, s as KnowledgeBenchmarkTaskKind, t as KnowledgeClaimMatcher, u as KnowledgeMemoryBenchmarkCase, v as KnowledgeMemoryBenchmarkTaskKind, w as KnowledgeMemoryEvent, x as KnowledgeMemoryFactMatcher, y as KnowledgeRetrievalBenchmarkCase, z as KnowledgeRetrievalBenchmarkQrel, A as KnowledgeRetrievalBenchmarkQuery, M as MemoryAdapterBenchmarkCandidate, C as MemoryAdapterBenchmarkRankingRow, D as RetrievalConfig, E as RetrievalEvalArtifact, F as RetrievalEvalRetriever, G as RetrievalEvalRetrieverInput, H as RetrievalEvalRetrieverResult, J as RetrievalEvalScenario, L as RetrievalGoldTarget, N as RetrievalMetricSummary, O as RetrievalMetricWeights, P as RetrievalParameterSearchSpace, Q as RetrievalParameterSweepProposerOptions, S as RetrievalRecallJudgeOptions, T as RetrievedKnowledgeHit, U as RetrievedSourceSpan, V as RunKnowledgeBenchmarkSuiteOptions, W as RunKnowledgeBenchmarkSuiteResult, X as RunMemoryAdapterBenchmarkOptions, Y as RunMemoryAdapterBenchmarkResult, Z as buildFirstPartyMemoryLifecycleBenchmarkCases, _ as buildIndustryMemoryBenchmarkSmokeCases, $ as buildIndustryRagBenchmarkSmokeCases, a0 as buildKnowledgeBenchmarkScenarios, a1 as buildRetrievalBenchmarkCasesFromQrels, a2 as buildRetrievalEvalDispatch, a3 as buildRetrievalParameterCandidates, a4 as createInMemoryBenchmarkAdapter, a5 as createMemoryAdapterBenchmarkResponder, a6 as createNoopMemoryBenchmarkAdapter, a7 as isKnowledgeMemoryBenchmarkCase, a8 as knowledgeBenchmarkJudge, a9 as parseKnowledgeBenchmarkJsonl, aa as parseKnowledgeBenchmarkQrels, ab as renderKnowledgeBenchmarkReportMarkdown, ac as respondToIndustryMemoryBenchmarkSmokeCase, ad as respondToIndustryRagBenchmarkSmokeCase, ae as retrievalConfigFromSurface, af as retrievalConfigSurface, ag as retrievalParameterSweepProposer, ah as retrievalRecallJudge, ai as runKnowledgeBenchmarkSuite, aj as runMemoryAdapterBenchmark, ak as runRetrievalImprovementLoop, al as scoreKnowledgeBenchmarkArtifact, am as scoreMemoryBenchmarkArtifact, an as scoreRetrievalArtifact, ao as summarizeKnowledgeBenchmarkCampaign } from './index-BLxw1I_F.js';
6
- import { KnowledgeFragment } from './sources/index.js';
7
- export { CornellLiiSelector, CornellLiiSourceOptions, FetchOpts, FragmentProvenance, IRS_DIMENSION_HINTS, IrsPublicationsSourceOptions, KnowledgeSource, MAX_RESPONSE_BYTES, MIN_REQUEST_GAP_MS, POLITE_USER_AGENT, PoliteFetchOptions, PoliteFetchResult, StateSosEntity, StateSosSourceConfig, __resetHttpThrottle, createCornellLiiSource, createIrsPublicationsSource, createStateSosSource, extractLinks, firstMatch, htmlToText, innerHtmlById, looksLikeBlockPage, politeFetch } from './sources/index.js';
4
+ import { AgentCandidateKnowledgeRef } from '@tangle-network/agent-interface';
8
5
  import { z } from 'zod';
9
6
  import { JsonValue, Scenario, JudgeConfig } from '@tangle-network/agent-eval/campaign';
7
+ import { R as RunRetrievalImprovementLoopResult, a as RunRetrievalImprovementLoopOptions } from './index-BHQk7jOT.js';
8
+ export { B as BuildRetrievalBenchmarkCasesFromQrelsOptions, b as BuildRetrievalEvalDispatchOptions, c as BuildRetrievalParameterCandidatesOptions, I as INDUSTRY_MEMORY_BENCHMARKS, d as INDUSTRY_RAG_BENCHMARKS, K as KnowledgeAnswerBenchmarkCase, e as KnowledgeAnswerBenchmarkTaskKind, f as KnowledgeBenchmarkArtifact, g as KnowledgeBenchmarkCase, h as KnowledgeBenchmarkCaseBase, i as KnowledgeBenchmarkDistribution, j as KnowledgeBenchmarkEvaluation, k as KnowledgeBenchmarkFamily, l as KnowledgeBenchmarkReport, m as KnowledgeBenchmarkResponder, n as KnowledgeBenchmarkScenario, o as KnowledgeBenchmarkSliceSummary, p as KnowledgeBenchmarkSource, q as KnowledgeBenchmarkSpec, r as KnowledgeBenchmarkSplit, s as KnowledgeBenchmarkTaskKind, t as KnowledgeClaimMatcher, u as KnowledgeMemoryBenchmarkCase, v as KnowledgeMemoryBenchmarkTaskKind, w as KnowledgeMemoryEvent, x as KnowledgeMemoryFactMatcher, y as KnowledgeRetrievalBenchmarkCase, z as KnowledgeRetrievalBenchmarkQrel, A as KnowledgeRetrievalBenchmarkQuery, M as MemoryAdapterBenchmarkCandidate, C as MemoryAdapterBenchmarkRankingRow, D as RetrievalConfig, E as RetrievalEvalArtifact, F as RetrievalEvalRetriever, G as RetrievalEvalRetrieverInput, H as RetrievalEvalRetrieverResult, J as RetrievalEvalScenario, L as RetrievalGoldTarget, N as RetrievalMetricSummary, O as RetrievalMetricWeights, P as RetrievalParameterSearchSpace, Q as RetrievalParameterSweepProposerOptions, S as RetrievalRecallJudgeOptions, T as RetrievedKnowledgeHit, U as RetrievedSourceSpan, V as RunKnowledgeBenchmarkSuiteOptions, W as RunKnowledgeBenchmarkSuiteResult, X as RunMemoryAdapterBenchmarkOptions, Y as RunMemoryAdapterBenchmarkResult, Z as buildFirstPartyMemoryLifecycleBenchmarkCases, _ as buildIndustryMemoryBenchmarkSmokeCases, $ as buildIndustryRagBenchmarkSmokeCases, a0 as buildKnowledgeBenchmarkScenarios, a1 as buildRetrievalBenchmarkCasesFromQrels, a2 as buildRetrievalEvalDispatch, a3 as buildRetrievalParameterCandidates, a4 as createInMemoryBenchmarkAdapter, a5 as createMemoryAdapterBenchmarkResponder, a6 as createNoopMemoryBenchmarkAdapter, a7 as isKnowledgeMemoryBenchmarkCase, a8 as knowledgeBenchmarkJudge, a9 as parseKnowledgeBenchmarkJsonl, aa as parseKnowledgeBenchmarkQrels, ab as renderKnowledgeBenchmarkReportMarkdown, ac as respondToIndustryMemoryBenchmarkSmokeCase, ad as respondToIndustryRagBenchmarkSmokeCase, ae as retrievalConfigFromSurface, af as retrievalConfigSurface, ag as retrievalParameterSweepProposer, ah as retrievalRecallJudge, ai as runKnowledgeBenchmarkSuite, aj as runMemoryAdapterBenchmark, ak as runRetrievalImprovementLoop, al as scoreKnowledgeBenchmarkArtifact, am as scoreMemoryBenchmarkArtifact, an as scoreRetrievalArtifact, ao as summarizeKnowledgeBenchmarkCampaign } from './index-BHQk7jOT.js';
9
+ import { KnowledgeFragment } from './sources/index.js';
10
+ export { CornellLiiSelector, CornellLiiSourceOptions, FetchOpts, FragmentProvenance, IRS_DIMENSION_HINTS, IrsPublicationsSourceOptions, KnowledgeSource, MAX_RESPONSE_BYTES, MIN_REQUEST_GAP_MS, POLITE_USER_AGENT, PoliteFetchOptions, PoliteFetchResult, StateSosEntity, StateSosSourceConfig, __resetHttpThrottle, createCornellLiiSource, createIrsPublicationsSource, createStateSosSource, extractLinks, firstMatch, htmlToText, innerHtmlById, looksLikeBlockPage, politeFetch } from './sources/index.js';
10
11
  export { AgentMemoryHitSchema, AgentMemoryKindSchema, AgentMemoryScopeSchema, AgentMemoryWriteInputSchema, Neo4jAgentMemoryAdapterOptions, createNeo4jAgentMemoryAdapter, defaultGetMemoryContext, memoryHitToSourceRecord, memoryWriteResultToSourceRecord, renderMemoryContext } from './memory/index.js';
11
- export { A as AgentMemoryAdapter, b as AgentMemoryContext, c as AgentMemoryHit, d as AgentMemoryKind, a as AgentMemoryScope, e as AgentMemorySearchOptions, f as AgentMemoryWriteInput, g as AgentMemoryWriteResult, R as RetrievalHoldoutBypassReason, h as RetrievalHoldoutCallContext, i as RetrievalHoldoutConfig, j as RetrievalHoldoutEligibleItem, k as RetrievalHoldoutEvent, l as RetrievalHoldoutOffPolicyOptions, m as RetrievalHoldoutOffPolicyResult, n as RetrievalHoldoutResult, o as RetrievalHoldoutSessionState, p as RetrievalHoldoutSessionSummary, q as applyRetrievalHoldout, r as applySessionStickyRetrievalHoldout, s as deterministicRng, t as emitRetrievalHoldoutBypass, u as resetRetrievalHoldoutRegistry, v as retrievalHoldoutConfigHash, w as toOffPolicyTrajectory } from './types-CjqPcTTK.js';
12
+ export { A as AgentMemoryAdapter, b as AgentMemoryContext, c as AgentMemoryHit, d as AgentMemoryKind, a as AgentMemoryScope, e as AgentMemorySearchOptions, f as AgentMemoryWriteInput, g as AgentMemoryWriteResult, R as RetrievalHoldoutBypassReason, h as RetrievalHoldoutCallContext, i as RetrievalHoldoutConfig, j as RetrievalHoldoutEligibleItem, k as RetrievalHoldoutEvent, l as RetrievalHoldoutOffPolicyOptions, m as RetrievalHoldoutOffPolicyResult, n as RetrievalHoldoutResult, o as RetrievalHoldoutSessionState, p as RetrievalHoldoutSessionSummary, q as applyRetrievalHoldout, r as applySessionStickyRetrievalHoldout, s as deterministicRng, t as emitRetrievalHoldoutBypass, u as resetRetrievalHoldoutRegistry, v as retrievalHoldoutConfigHash, w as toOffPolicyTrajectory } from './types-BFRyr390.js';
12
13
  import '@tangle-network/agent-eval/rl';
13
14
 
14
15
  interface SourceAdapterInput {
@@ -632,1383 +633,1384 @@ interface AdaptiveResearchDriver {
632
633
  */
633
634
  declare function createAdaptiveResearchDriver(options?: AdaptiveDriverOptions): AdaptiveResearchDriver;
634
635
 
635
- /**
636
- * Change detection across snapshots of one source's fragments.
637
- *
638
- * The output drives the continuous-ingestion loop: each `KnowledgeChange`
639
- * carries the eval dimensions affected (`affectedDimensions`), which an
640
- * agent-eval campaign scheduler consumes to decide which campaigns to
641
- * re-run. Three change kinds:
642
- *
643
- * - `added` — fragment id appears in `next` but not `prev`.
644
- * - `removed` — fragment id appears in `prev` but not `next`. Typical
645
- * trigger: an authority retires a Wex slug, or a state SOS reorganises
646
- * its forms catalogue.
647
- * - `modified` — fragment id appears in both, body hash differs. This
648
- * is the dominant change kind in practice — the Ryan-LLC v. FTC
649
- * vacatur case manifests as a `modified` on the Wex non-compete
650
- * fragment, NOT as a removed one.
651
- *
652
- * Unverifiable fragments are filtered out before diffing — comparing a
653
- * captcha-blocked snapshot against a real one would falsely fire every
654
- * fragment as removed. The caller can inspect the raw lists if they want
655
- * to surface block-page failures.
656
- *
657
- * Within-snapshot duplicate ids are an upstream bug; this function picks
658
- * the LAST one and emits a diagnostic via the `warnings` field.
659
- *
660
- * @stable
661
- */
662
- type KnowledgeChangeKind = 'added' | 'removed' | 'modified';
663
- interface KnowledgeChange {
664
- /** Source-scoped id (matches `KnowledgeFragment.id`). */
665
- fragmentId: string;
666
- kind: KnowledgeChangeKind;
667
- /**
668
- * For `added`: full body of the new fragment.
669
- * For `removed`: full body of the prior fragment.
670
- * For `modified`: unified-diff-style payload `{ before, after }` body strings.
671
- */
672
- diff?: {
673
- before?: string;
674
- after?: string;
675
- };
676
- /**
677
- * Eval dimensions to re-score. Computed as the union of both fragments'
678
- * `dimensionHints`. The eval cron treats this as a set of campaign tags.
679
- */
680
- affectedDimensions: string[];
681
- /** URL of the affected authority page (from whichever side has it). */
682
- url?: string;
683
- /**
684
- * Source-attested change time. For `modified`, takes the NEXT fragment's
685
- * `sourceUpdatedAt`. For `removed`, takes the PRIOR fragment's
686
- * `sourceUpdatedAt`. For `added`, takes the NEXT fragment's
687
- * `sourceUpdatedAt`. Consumers index changes by this date.
688
- */
689
- detectedAt: string;
690
- }
691
- interface DetectChangesResult {
692
- changes: KnowledgeChange[];
693
- /** Counts by kind — handy for dashboards. */
694
- summary: {
695
- added: number;
696
- removed: number;
697
- modified: number;
698
- };
699
- /** Non-fatal diagnostics (duplicate ids, dropped unverifiable fragments). */
636
+ interface ApplyWriteBlocksResult {
637
+ written: string[];
700
638
  warnings: string[];
701
639
  }
702
- interface DetectChangesOptions {
703
- /**
704
- * When true (default), unverifiable fragments are dropped from both
705
- * sides before comparison. Set false ONLY when debugging block-page
706
- * issues — comparing against unverifiable content emits false
707
- * `removed`/`modified` changes.
708
- */
709
- skipUnverifiable?: boolean;
710
- /**
711
- * When provided, only changes whose `affectedDimensions` intersect this
712
- * set are returned. Useful for cron loops that schedule per-dimension
713
- * eval campaigns and only care about a subset.
714
- */
715
- filterDimensions?: string[];
716
- }
717
- declare function detectChanges(prev: KnowledgeFragment[], next: KnowledgeFragment[], options?: DetectChangesOptions): DetectChangesResult;
640
+ declare function applyKnowledgeWriteBlocks(root: string, proposalText: string): Promise<ApplyWriteBlocksResult>;
641
+ declare function applyKnowledgeWriteBlocksFile(root: string, proposalPath: string): Promise<ApplyWriteBlocksResult>;
718
642
 
719
- interface ChunkingOptions {
720
- targetChars: number;
721
- maxChars: number;
722
- minChars: number;
723
- overlapChars: number;
643
+ interface ValidateKnowledgeOptions {
644
+ strict?: boolean;
724
645
  }
725
- interface KnowledgeChunk {
726
- index: number;
727
- text: string;
728
- headingPath: string;
729
- charStart: number;
730
- charEnd: number;
731
- oversized: boolean;
646
+ interface ValidateKnowledgeResult {
647
+ ok: boolean;
648
+ findings: KnowledgeLintFinding[];
732
649
  }
733
- declare function chunkMarkdown(content: string, options?: Partial<ChunkingOptions>): KnowledgeChunk[];
734
- declare function stripFrontmatter(content: string): {
735
- body: string;
736
- bodyOffset: number;
737
- };
738
-
739
- /**
740
- * Claim-grounding mode for `runVerifiedResearchLoop`.
741
- *
742
- * The two-agent loop's existing verifier judges a source's on-topic RELEVANCE
743
- * (is this page about the goal?). On the topic sets we have measured, its
744
- * cleanliness win is dominated by DE-DUPLICATION — which a deterministic
745
- * content-hash / canonical-URL check captures at ~none of the LLM premium (see
746
- * `docs/results/cost-quality.md`). That makes the LLM verifier look expensive
747
- * for what a cheap rule already does.
748
- *
749
- * Claim-grounding targets a DIFFERENT, harder error band: a citation that is
750
- * relevant and unique but **misattributed** — the page is on-topic, the URL is
751
- * real, yet the specific CLAIM the source is cited for does NOT actually appear
752
- * in the page. This is the citation-fabrication failure mode of LLM research:
753
- * the model writes a plausible sentence and hangs a real URL off it that never
754
- * says any such thing. Neither de-dup nor a relevance judge catches it (both can
755
- * pass a misattributed-but-on-topic page); only checking the claim against the
756
- * fetched text does.
757
- *
758
- * The check is EXECUTABLE GROUND TRUTH, not another LLM opinion: the worker
759
- * attaches the specific claim it is citing the source for, and the verifier
760
- * tests whether that claim is PRESENT (verbatim, normalized, or as a sufficient
761
- * content-word overlap / close paraphrase) in the `htmlToText` output of the
762
- * page the worker actually fetched. A claim that is not grounded is rejected as
763
- * misattributed. Because the oracle is deterministic text presence — not a model
764
- * call — it is a deployable, non-oracle verifier: it can run in production with
765
- * zero inference cost, OR be composed with the LLM relevance verifier so the
766
- * loop rejects BOTH off-topic AND misattributed sources.
767
- *
768
- * This module is content-free and any-topic: it adds (1) a way for a proposal to
769
- * carry the claim it is cited for, (2) the `groundClaimInText` oracle, and (3) a
770
- * `ResearchDriver` that gates on grounding. It composes the existing
771
- * `ResearchDriver` / `ResearchSourceProposal` contracts and the shipped
772
- * `htmlToText`; it reinvents none of them.
773
- */
650
+ declare function validateKnowledgeIndex(index: KnowledgeIndex, options?: ValidateKnowledgeOptions): ValidateKnowledgeResult;
774
651
 
775
- /**
776
- * Metadata key under which a proposal carries the specific claim it is cited
777
- * for. The worker sets `metadata[citedClaimKey] = '<the claim>'`; the
778
- * claim-grounding driver reads it and checks it against the fetched page text.
779
- */
780
- declare const citedClaimKey = "citedClaim";
781
- /** Read the cited claim a proposal carries, if any. */
782
- declare function citedClaimOf(source: ResearchSourceProposal): string | undefined;
783
- /** Attach a cited claim to a proposal (immutably returns a new proposal). */
784
- declare function withCitedClaim(source: ResearchSourceProposal, claim: string): ResearchSourceProposal;
785
- interface GroundingResult {
786
- /** True when the claim is sufficiently present in the page text. */
787
- grounded: boolean;
788
- /** How the claim matched (or why it didn't). For audit/notes. */
789
- mode: 'verbatim' | 'normalized' | 'overlap' | 'absent' | 'empty-claim' | 'empty-text';
652
+ interface KnowledgeResearchLoopContext {
653
+ root: string;
654
+ goal: string;
655
+ iteration: number;
656
+ index: KnowledgeIndex;
657
+ lintFindings: KnowledgeLintFinding[];
658
+ validation: ValidateKnowledgeResult;
659
+ readiness?: EvalKnowledgeBundleBuildResult;
660
+ previousSteps: KnowledgeResearchLoopStep[];
661
+ signal?: AbortSignal;
662
+ }
663
+ interface KnowledgeResearchLoopDecision {
790
664
  /**
791
- * Fraction of the claim's content words found in the page text. 1 for a
792
- * verbatim/normalized hit; the measured overlap otherwise.
665
+ * Free-form notes from the researcher. Keep this human-readable; products can
666
+ * store it as the research transcript.
793
667
  */
794
- overlap: number;
795
- /** Content words present in the claim but NOT in the page text. */
796
- missingWords: string[];
797
- }
798
- interface GroundClaimOptions {
668
+ notes?: string;
799
669
  /**
800
- * Minimum fraction of the claim's content words that must appear in the page
801
- * text to count as a close paraphrase when there is no verbatim/normalized
802
- * hit. Default 0.7 — a high bar, because a misattribution is exactly a claim
803
- * whose specific words the page does not contain.
670
+ * Local files to register as immutable sources before applying proposals.
804
671
  */
805
- minOverlap?: number;
672
+ sourcePaths?: string[];
806
673
  /**
807
- * Content words shorter than this are ignored (drops "the", "of", "is", …)
808
- * and never count toward overlap. Default 3.
674
+ * Textual source artifacts discovered by an agent, browser worker, connector,
675
+ * or deep-research process.
809
676
  */
810
- minWordLength?: number;
811
- }
812
- /**
813
- * THE ORACLE. Is `claim` grounded in `pageText` (the `htmlToText` output of the
814
- * page the worker fetched)? Deterministic, no model call:
815
- *
816
- * 1. verbatim — the claim string appears as-is (case-insensitive).
817
- * 2. normalized — the claim appears after collapsing punctuation/whitespace
818
- * on both sides (so "5.4x" vs "5.4 x", smart quotes, etc. still match).
819
- * 3. overlap — a close paraphrase: at least `minOverlap` of the claim's
820
- * substantive content words appear in the page text. A misattributed page
821
- * fails here because the SPECIFIC words the claim asserts are absent.
822
- *
823
- * Returns the match mode, the measured overlap, and the missing content words —
824
- * enough for the driver to give a precise rejection reason and for a test/doc to
825
- * audit WHY a claim grounded or didn't.
826
- */
827
- declare function groundClaimInText(claim: string, pageText: string, options?: GroundClaimOptions): GroundingResult;
828
- interface ClaimGroundingDriverOptions extends GroundClaimOptions {
677
+ sourceTexts?: AddSourceTextInput[];
829
678
  /**
830
- * Optional second verifier to compose AFTER grounding passes. When set, a
831
- * source must BOTH ground its claim AND pass this verifier (e.g. the LLM
832
- * relevance driver's `verifySource`). Lets the loop reject off-topic AND
833
- * misattributed sources in one driver. Omit for the pure, zero-inference
834
- * grounding gate.
679
+ * Safe write protocol text. The loop parses and applies only accepted
680
+ * `---FILE: knowledge/...---` blocks.
835
681
  */
836
- relevanceVerifier?: (source: ResearchSourceProposal, ctx: SourceVerificationContext) => Promise<SourceVerdict> | SourceVerdict;
682
+ proposalText?: string;
837
683
  /**
838
- * What to do when a proposal carries NO cited claim. `'reject'` (default) is
839
- * fail-closed: in claim-grounding mode every source must declare what it is
840
- * cited for, so an un-annotated source is treated as ungrounded. `'accept'`
841
- * lets un-annotated sources through to the relevance verifier (if any) —
842
- * useful when mixing annotated and legacy proposals.
684
+ * The researcher decides when the wiki is good enough. The loop deliberately
685
+ * does not encode a domain-specific definition of "done".
843
686
  */
844
- onMissingClaim?: 'reject' | 'accept';
845
- }
846
- /**
847
- * A `ResearchDriver`-shaped verifier (just the `verifySource` arm) that gates on
848
- * CLAIM GROUNDING: it rejects a source whose cited claim is not present in its
849
- * fetched page text — a misattributed / fabricated citation — and (optionally)
850
- * composes a relevance verifier after grounding passes.
851
- *
852
- * The returned function matches `ResearchDriver['verifySource']`, so it drops
853
- * straight into `runVerifiedResearchLoop` as `{ verifySource: createClaimGroundingVerifier(...) }`.
854
- */
855
- declare function createClaimGroundingVerifier(options?: ClaimGroundingDriverOptions): (source: ResearchSourceProposal, ctx: SourceVerificationContext) => Promise<SourceVerdict>;
856
- interface WorkerClaimDecorationOptions {
857
- router?: RouterClient;
858
- router_options?: TangleRouterOptions;
859
- /** Max output tokens for the claim-extraction call. Default 1200 (glm floor). */
860
- maxTokens?: number;
687
+ done?: boolean;
688
+ metadata?: Record<string, unknown>;
861
689
  }
690
+ interface KnowledgeResearchLoopStep {
691
+ iteration: number;
692
+ notes?: string;
693
+ addedSources: SourceRecord[];
694
+ applied?: ApplyWriteBlocksResult;
695
+ lintFindings: KnowledgeLintFinding[];
696
+ validation: ValidateKnowledgeResult;
697
+ readiness?: EvalKnowledgeBundleBuildResult;
698
+ event: KnowledgeEvent;
699
+ done: boolean;
700
+ metadata?: Record<string, unknown>;
701
+ }
702
+ interface RunKnowledgeResearchLoopOptions {
703
+ root: string;
704
+ goal: string;
705
+ maxIterations?: number;
706
+ actor?: string;
707
+ strict?: ValidateKnowledgeOptions['strict'];
708
+ readinessSpecs?: KnowledgeReadinessSpec[];
709
+ readinessTaskId?: string;
710
+ readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>;
711
+ sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>;
712
+ signal?: AbortSignal;
713
+ step(context: KnowledgeResearchLoopContext): Promise<KnowledgeResearchLoopDecision> | KnowledgeResearchLoopDecision;
714
+ onStep?: (step: KnowledgeResearchLoopStep) => Promise<void> | void;
715
+ }
716
+ interface KnowledgeResearchLoopResult {
717
+ root: string;
718
+ goal: string;
719
+ iterations: number;
720
+ done: boolean;
721
+ index: KnowledgeIndex;
722
+ lintFindings: KnowledgeLintFinding[];
723
+ validation: ValidateKnowledgeResult;
724
+ readiness?: EvalKnowledgeBundleBuildResult;
725
+ steps: KnowledgeResearchLoopStep[];
726
+ }
727
+ type KnowledgeControlLoopState = KnowledgeResearchLoopContext;
728
+ type KnowledgeControlLoopAction = KnowledgeResearchLoopDecision;
729
+ type KnowledgeControlLoopActionResult = KnowledgeResearchLoopStep;
730
+ interface KnowledgeControlLoopAdapterOptions {
731
+ root: string;
732
+ goal: string;
733
+ actor?: string;
734
+ strict?: ValidateKnowledgeOptions['strict'];
735
+ readinessSpecs?: KnowledgeReadinessSpec[];
736
+ readinessTaskId?: string;
737
+ readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>;
738
+ sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>;
739
+ }
740
+ type KnowledgeControlLoopAdapter = Pick<ControlRuntimeConfig<KnowledgeControlLoopState, KnowledgeControlLoopAction, KnowledgeControlLoopActionResult, ControlEvalResult>, 'intent' | 'observe' | 'validate' | 'act' | 'shouldStop'>;
862
741
  /**
863
- * Ask an LLM to state, for one source, the single specific factual claim a
864
- * researcher would cite THIS page for toward the goal. Used to DECORATE the
865
- * sources a relevance-only worker produced with the claim a citation would make,
866
- * so the claim-grounding verifier has something executable to check. The model
867
- * is told to ground the claim in the provided excerpt; the verifier then checks
868
- * it against the FULL page text independently — the model does not get to mark
869
- * its own homework.
870
- *
871
- * Returns the proposal annotated via `withCitedClaim`, or the original proposal
872
- * unchanged if the model returns nothing parseable (the verifier's
873
- * `onMissingClaim` policy then decides).
874
- */
875
- declare function createClaimDecorator(options?: WorkerClaimDecorationOptions): (source: ResearchSourceProposal, goal: string) => Promise<ResearchSourceProposal>;
876
-
877
- /**
878
- * The SINGLE-AGENT COLLECTION driver — the blind-collection baseline (Arm A).
879
- *
880
- * This is the honest null the depth A/B is measured against. The other drivers
881
- * spend extra inference to do something differentiated:
882
- * - `createVerifyingResearchDriver` runs an LLM gate per source (Arm B),
883
- * - `createResearchDrivingDriver` extracts claims, tracks corroboration, and
884
- * synthesizes deep follow-up questions to drive depth (Arm C).
885
- *
886
- * This driver does NONE of that. It is a pass-through: it accepts every source
887
- * the worker proposes and contributes no research, no gating, and no steering of
888
- * its own. The loop still dedups exact-uri duplicates before calling
889
- * `verifySource` (that is the loop's job, not the driver's), and the default
890
- * `foldGaps` (a plain bulleted list of the still-open readiness gaps) still folds
891
- * the gaps into the worker's next prompt — so the worker keeps researching, but
892
- * NOTHING intelligent sits between the worker and the knowledge base.
893
- *
894
- * In other words: ONE agent (the worker) collects sources round after round, and
895
- * the "driver" is an inert rubber stamp. That is exactly what "single-agent
896
- * collection" means — the topology with zero coordinator intelligence — so its
897
- * material-facts score is the floor every other arm must beat to justify its
898
- * extra inference cost.
899
- *
900
- * It adds NO router calls of its own: `verifySource` is a synchronous accept and
901
- * `foldGaps` is omitted so the loop uses its built-in gap list. So Arm A's cost
902
- * is the worker's cost alone — the cleanest possible blind-collection baseline.
903
- */
904
-
905
- /**
906
- * Build the single-agent collection driver. Accepts every source; never gates,
907
- * never researches, never steers beyond the loop's default open-gap list. The
908
- * worker is the only agent that thinks.
742
+ * Adapter for running knowledge growth through `agent-eval`'s generic control
743
+ * runtime. The caller still owns `decide`: that can be a proposer agent,
744
+ * reviewer agent, deterministic policy, or a composition of all three.
909
745
  */
910
- declare function createCollectionResearchDriver(): ResearchDriver;
746
+ declare function createKnowledgeControlLoopAdapter(options: KnowledgeControlLoopAdapterOptions): KnowledgeControlLoopAdapter;
747
+ declare function runKnowledgeResearchLoop(options: RunKnowledgeResearchLoopOptions): Promise<KnowledgeResearchLoopResult>;
911
748
 
912
- interface DiscoveryTask {
749
+ type RagKnowledgeImprovementPhase = 'retrieval-tuning' | 'gap-diagnosis' | 'knowledge-acquisition' | 'knowledge-update' | 'answer-quality' | 'promotion';
750
+ type RagKnowledgeImprovementPhaseStatus = 'completed' | 'skipped' | 'failed';
751
+ type RagGapKind = 'missing-source' | 'stale-source' | 'retrieval-miss' | 'retrieval-noise' | 'chunking-mismatch' | 'missing-multihop-evidence' | 'generator-unsupported-claim' | 'citation-mismatch' | 'incorrect-abstention' | 'unknown';
752
+ type RagGapSeverity = 'info' | 'warning' | 'error' | 'critical';
753
+ interface RagGapFinding {
913
754
  id: string;
755
+ kind: RagGapKind;
756
+ severity: RagGapSeverity;
757
+ message: string;
758
+ scenarioId?: string;
759
+ evidence?: Record<string, JsonValue>;
760
+ }
761
+ interface RagKnowledgeImprovementPhaseResult {
762
+ phase: RagKnowledgeImprovementPhase;
763
+ status: RagKnowledgeImprovementPhaseStatus;
764
+ summary: string;
765
+ startedAt: string;
766
+ finishedAt: string;
767
+ metadata?: Record<string, JsonValue>;
768
+ }
769
+ interface RagPhaseInputBase {
914
770
  goal: string;
915
- query?: string;
916
- sourceHints?: string[];
917
- metadata?: Record<string, unknown>;
771
+ phases: readonly RagKnowledgeImprovementPhaseResult[];
772
+ signal?: AbortSignal;
918
773
  }
919
- interface DiscoveryResult {
920
- taskId: string;
774
+ interface RagDiagnosisInput extends RagPhaseInputBase {
775
+ retrieval?: RunRetrievalImprovementLoopResult;
776
+ }
777
+ interface RagKnowledgeAcquisitionInput extends RagPhaseInputBase {
778
+ retrieval?: RunRetrievalImprovementLoopResult;
779
+ findings: readonly RagGapFinding[];
780
+ }
781
+ interface RagKnowledgeUpdateInput extends RagPhaseInputBase {
782
+ retrieval?: RunRetrievalImprovementLoopResult;
783
+ findings: readonly RagGapFinding[];
784
+ acquisition?: KnowledgeResearchLoopDecision;
785
+ }
786
+ interface RagKnowledgeUpdateResult {
787
+ applied: boolean;
921
788
  summary: string;
922
- sourceUris?: string[];
923
- claims?: Array<{
924
- text: string;
925
- sourceUri?: string;
926
- confidence?: number;
927
- }>;
928
- followUpTasks?: DiscoveryTask[];
929
- metadata?: Record<string, unknown>;
789
+ research?: KnowledgeResearchLoopResult;
790
+ metadata?: Record<string, JsonValue>;
930
791
  }
931
- interface KnowledgeDiscoveryWorker {
932
- run(task: DiscoveryTask, signal?: AbortSignal): Promise<DiscoveryResult> | DiscoveryResult;
792
+ interface RagAnswerQualityInput extends RagPhaseInputBase {
793
+ retrieval?: RunRetrievalImprovementLoopResult;
794
+ findings: readonly RagGapFinding[];
795
+ acquisition?: KnowledgeResearchLoopDecision;
796
+ knowledgeUpdate?: RagKnowledgeUpdateResult;
933
797
  }
934
- interface KnowledgeDiscoveryDispatcher {
935
- dispatch(tasks: DiscoveryTask[], options?: {
936
- concurrency?: number;
937
- signal?: AbortSignal;
938
- }): Promise<DiscoveryResult[]>;
798
+ interface RagAnswerQualityResult {
799
+ passed: boolean;
800
+ metrics: Record<string, number>;
801
+ findings?: readonly RagGapFinding[];
802
+ metadata?: Record<string, JsonValue>;
939
803
  }
940
- type DiscoveryLoopStopReason = 'complete' | 'max-rounds' | 'max-tasks' | 'aborted';
941
- interface DiscoveryLoopRound {
942
- round: number;
943
- tasks: DiscoveryTask[];
944
- results: DiscoveryResult[];
945
- queuedFollowUps: DiscoveryTask[];
804
+ interface RagPromotionInput extends RagPhaseInputBase {
805
+ retrieval?: RunRetrievalImprovementLoopResult;
806
+ findings: readonly RagGapFinding[];
807
+ acquisition?: KnowledgeResearchLoopDecision;
808
+ knowledgeUpdate?: RagKnowledgeUpdateResult;
809
+ answerQuality?: RagAnswerQualityResult;
946
810
  }
947
- interface DiscoveryLoopResult {
948
- stopReason: DiscoveryLoopStopReason;
949
- tasksDispatched: number;
950
- results: DiscoveryResult[];
951
- rounds: DiscoveryLoopRound[];
952
- /** Tasks retained, not dropped, when a configured limit stops the loop. */
953
- pendingTasks: DiscoveryTask[];
954
- /** Structurally identical task identities ignored to prevent cycles. */
955
- duplicateTaskIds: string[];
811
+ interface RagPromotionResult {
812
+ promoted: boolean;
813
+ reason: string;
814
+ metadata?: Record<string, JsonValue>;
956
815
  }
957
- interface RunDiscoveryLoopOptions {
958
- dispatcher: KnowledgeDiscoveryDispatcher;
959
- initialTasks: readonly DiscoveryTask[];
960
- /** Maximum follow-up depth including the initial dispatch. Default 3. */
961
- maxRounds?: number;
962
- /** Maximum tasks dispatched across all rounds. Default 24. */
963
- maxTasks?: number;
964
- /** Forwarded to the dispatcher. Default 4. */
965
- concurrency?: number;
816
+ interface RagKnowledgeResearchOptions extends Omit<RunKnowledgeResearchLoopOptions, 'goal' | 'signal' | 'step'> {
817
+ goal?: string;
818
+ step?: RunKnowledgeResearchLoopOptions['step'];
819
+ }
820
+ interface RunRagKnowledgeImprovementLoopOptions {
821
+ goal: string;
822
+ retrieval?: RunRetrievalImprovementLoopOptions;
823
+ diagnose?: (input: RagDiagnosisInput) => MaybePromise$1<readonly RagGapFinding[]>;
824
+ acquireKnowledge?: (input: RagKnowledgeAcquisitionInput) => MaybePromise$1<KnowledgeResearchLoopDecision>;
825
+ knowledgeResearch?: RagKnowledgeResearchOptions;
826
+ updateKnowledge?: (input: RagKnowledgeUpdateInput) => MaybePromise$1<RagKnowledgeUpdateResult>;
827
+ evaluateAnswers?: (input: RagAnswerQualityInput) => MaybePromise$1<RagAnswerQualityResult>;
828
+ promote?: (input: RagPromotionInput) => MaybePromise$1<RagPromotionResult>;
829
+ enabledPhases?: readonly RagKnowledgeImprovementPhase[];
830
+ requiredPhases?: readonly RagKnowledgeImprovementPhase[];
966
831
  signal?: AbortSignal;
967
- onRound?: (round: DiscoveryLoopRound) => Promise<void> | void;
832
+ now?: () => Date;
968
833
  }
969
- /**
970
- * Dispatch discovery tasks and recursively pursue worker-proposed follow-ups.
971
- *
972
- * The runner owns only bounded scheduling and accounting. Workers own search,
973
- * source verification, and domain-specific candidate shapes.
974
- */
975
- declare function runDiscoveryLoop(options: RunDiscoveryLoopOptions): Promise<DiscoveryLoopResult>;
976
- declare function createLocalDiscoveryDispatcher(worker: KnowledgeDiscoveryWorker): KnowledgeDiscoveryDispatcher;
977
-
978
- interface KnowledgeEventQuery {
979
- type?: KnowledgeEventType;
980
- target?: string;
981
- limit?: number;
834
+ interface RunRagKnowledgeImprovementLoopResult {
835
+ goal: string;
836
+ phases: readonly RagKnowledgeImprovementPhaseResult[];
837
+ retrieval?: RunRetrievalImprovementLoopResult;
838
+ findings: readonly RagGapFinding[];
839
+ acquisition?: KnowledgeResearchLoopDecision;
840
+ knowledgeUpdate?: RagKnowledgeUpdateResult;
841
+ answerQuality?: RagAnswerQualityResult;
842
+ promotion?: RagPromotionResult;
982
843
  }
983
- declare function createKnowledgeEvent(input: {
984
- type: KnowledgeEventType;
985
- actor?: string;
986
- target?: string;
987
- metadata?: Record<string, unknown>;
988
- now?: () => Date;
989
- }): KnowledgeEvent;
844
+ type MaybePromise$1<T> = T | Promise<T>;
845
+ declare function runRagKnowledgeImprovementLoop(options: RunRagKnowledgeImprovementLoopOptions): Promise<RunRagKnowledgeImprovementLoopResult>;
990
846
 
991
- /**
992
- * Knowledge freshness store: tracks when each `(workspaceId, sourceId)` pair
993
- * was last successfully refreshed, and reports staleness against a TTL.
994
- *
995
- * The contract is intentionally minimal — just enough to drive a cron loop:
996
- *
997
- * ```ts
998
- * const store = createFileSystemFreshnessStore({ root: '.agent-knowledge' })
999
- * for (const source of sources) {
1000
- * if (await store.stale({ workspaceId, sourceId: source.id, ttlMs: DAY })) {
1001
- * const fragments = await source.fetch({ cacheDir })
1002
- * await persistFragments(fragments)
1003
- * await store.mark({ workspaceId, sourceId: source.id, when: new Date() })
1004
- * }
1005
- * }
1006
- * ```
1007
- *
1008
- * Per-tenant isolation is enforced by `workspaceId` keying — there is no
1009
- * global mutable state across workspaces.
1010
- *
1011
- * Two adapters ship in-package:
1012
- *
1013
- * - `createFileSystemFreshnessStore` — JSON file under the knowledge root,
1014
- * mirrors the layout convention already used by `sources.json`.
1015
- * - `createD1FreshnessStoreStub` — adapter scaffold for Cloudflare D1 /
1016
- * Postgres. Production consumers should implement the `D1Adapter`
1017
- * interface inside their own app; this stub exists to anchor the shape.
1018
- *
1019
- * @stable contract — interface is frozen at 0.x within this major.
1020
- * @stable filesystem adapter
1021
- * @experimental D1 stub — interface will evolve as real consumers wire it.
1022
- */
1023
- /** Identity for one freshness record. */
1024
- interface FreshnessKey {
1025
- workspaceId: string;
1026
- sourceId: string;
847
+ type RagEvalProvider = 'agent-knowledge' | 'ragas' | 'deepeval' | 'trulens' | 'ragchecker' | 'custom';
848
+ type RagEvalMetricKey = 'context_precision' | 'context_recall' | 'context_relevance' | 'context_sufficiency' | 'faithfulness' | 'groundedness' | 'answer_relevance' | 'answer_correctness' | 'citation_support' | 'abstention' | 'unsupported_answer_rate';
849
+ type RagEvalSlice = 'known-answer' | 'paraphrase' | 'distractor' | 'freshness' | 'multi-source' | 'unanswerable' | 'long-tail' | 'custom';
850
+ interface RagEvalContext {
851
+ id: string;
852
+ text: string;
853
+ rank?: number;
854
+ pageId?: string;
855
+ sourceId?: string;
856
+ anchorId?: string;
857
+ stale?: boolean;
858
+ metadata?: Record<string, JsonValue>;
1027
859
  }
1028
- /** TTL bound for staleness checks. */
1029
- interface FreshnessTtl extends FreshnessKey {
1030
- /** Milliseconds — `Date.now() - last() > ttlMs` ⇒ stale. */
1031
- ttlMs: number;
1032
- /** Injected clock for deterministic tests; defaults to system time. */
1033
- now?: Date;
860
+ interface RagEvalCitation {
861
+ id: string;
862
+ claimId?: string;
863
+ contextId?: string;
864
+ pageId?: string;
865
+ sourceId?: string;
866
+ anchorId?: string;
867
+ quote?: string;
868
+ metadata?: Record<string, JsonValue>;
1034
869
  }
1035
- /** Mark argument. */
1036
- interface FreshnessMark extends FreshnessKey {
1037
- when: Date;
1038
- /** Optional content hash captured at refresh time; aids debugging. */
1039
- contentHash?: string;
870
+ interface RagEvalClaim {
871
+ id: string;
872
+ text: string;
873
+ citationIds?: readonly string[];
874
+ metadata?: Record<string, JsonValue>;
1040
875
  }
1041
- interface KnowledgeFreshnessStore {
1042
- /** Last refresh time, or null if never refreshed. */
1043
- last(key: FreshnessKey): Promise<Date | null>;
1044
- /** Record a successful refresh. */
1045
- mark(input: FreshnessMark): Promise<void>;
1046
- /** True iff `last(key)` is null or older than `ttlMs`. */
1047
- stale(input: FreshnessTtl): Promise<boolean>;
1048
- /** All records for a workspace — useful for dashboards / debugging. */
1049
- list(workspaceId: string): Promise<FreshnessRecord[]>;
876
+ interface RagRequiredContext {
877
+ id?: string;
878
+ text?: string;
879
+ pageId?: string;
880
+ sourceId?: string;
881
+ anchorId?: string;
1050
882
  }
1051
- interface FreshnessRecord {
1052
- workspaceId: string;
1053
- sourceId: string;
1054
- lastRefreshedAt: string;
1055
- contentHash?: string;
883
+ interface RagAnswerEvalScenario extends Scenario {
884
+ kind: 'rag-answer-eval';
885
+ query: string;
886
+ referenceAnswer?: string;
887
+ expectedClaims?: readonly string[];
888
+ forbiddenClaims?: readonly string[];
889
+ requiredContext?: readonly RagRequiredContext[];
890
+ unanswerable?: boolean;
891
+ requireCitations?: boolean;
892
+ slices?: readonly RagEvalSlice[];
893
+ thresholds?: Partial<Record<RagEvalMetricKey, number>>;
1056
894
  }
1057
- interface FileSystemFreshnessStoreOptions {
1058
- /**
1059
- * Knowledge root. The store writes to `<root>/.agent-knowledge/freshness.json`,
1060
- * mirroring the convention used by `sources.json`.
1061
- */
1062
- root: string;
895
+ interface ExternalRagEvalScore {
896
+ provider: RagEvalProvider | string;
897
+ scores: Record<string, number>;
898
+ reasons?: Record<string, string>;
899
+ metadata?: Record<string, JsonValue>;
1063
900
  }
1064
- /**
1065
- * Filesystem-backed implementation. Single JSON file per knowledge root,
1066
- * indexed by `${workspaceId}::${sourceId}`. Reads parse on every call —
1067
- * cron tick rate is well below the cost of one JSON parse.
1068
- *
1069
- * Writes share the package-wide filesystem lock, so multiple workers cannot
1070
- * overwrite one another or run through an interrupted knowledge promotion.
1071
- */
1072
- declare function createFileSystemFreshnessStore(options: FileSystemFreshnessStoreOptions): KnowledgeFreshnessStore;
1073
- /**
1074
- * D1 / Postgres adapter scaffold. Production consumers implement
1075
- * `D1Adapter` against their own driver (better-sqlite3, postgres,
1076
- * Cloudflare D1 binding, ...). This factory wires the adapter to the
1077
- * `KnowledgeFreshnessStore` interface.
1078
- *
1079
- * The expected schema:
1080
- *
1081
- * ```sql
1082
- * CREATE TABLE knowledge_freshness (
1083
- * workspace_id TEXT NOT NULL,
1084
- * source_id TEXT NOT NULL,
1085
- * last_refreshed_at TEXT NOT NULL,
1086
- * content_hash TEXT,
1087
- * PRIMARY KEY (workspace_id, source_id)
1088
- * );
1089
- * ```
1090
- */
1091
- interface D1Adapter {
1092
- get(workspaceId: string, sourceId: string): Promise<FreshnessRecord | null>;
1093
- upsert(record: FreshnessRecord): Promise<void>;
1094
- listByWorkspace(workspaceId: string): Promise<FreshnessRecord[]>;
901
+ interface RagAnswerEvalArtifact {
902
+ query: string;
903
+ answer: string;
904
+ contexts: readonly RagEvalContext[];
905
+ claims?: readonly RagEvalClaim[];
906
+ citations?: readonly RagEvalCitation[];
907
+ abstained?: boolean;
908
+ durationMs?: number;
909
+ costUsd?: number;
910
+ externalScores?: readonly ExternalRagEvalScore[];
911
+ metadata?: Record<string, JsonValue>;
1095
912
  }
1096
- declare function createD1FreshnessStoreStub(adapter: D1Adapter): KnowledgeFreshnessStore;
1097
-
1098
- interface ParsedFrontmatter {
1099
- frontmatter: Record<string, unknown>;
1100
- body: string;
913
+ interface RagAnswerMetricSummary {
914
+ metrics: Record<RagEvalMetricKey, number>;
915
+ composite: number;
916
+ passed: boolean;
917
+ findings: readonly RagGapFinding[];
918
+ claimCount: number;
919
+ supportedClaimCount: number;
920
+ citedClaimCount: number;
921
+ supportedCitationCount: number;
922
+ matchedRequiredContextCount: number;
923
+ requiredContextCount: number;
924
+ providerScores: Record<string, Record<RagEvalMetricKey, number>>;
1101
925
  }
1102
- declare function parseFrontmatter(content: string): ParsedFrontmatter;
1103
- declare function formatFrontmatter(frontmatter: Record<string, unknown>, body: string): string;
1104
-
1105
- declare function buildKnowledgeGraph(pages: KnowledgePage[]): KnowledgeGraph;
1106
-
1107
- declare function sha256(text: string): string;
1108
- declare function slugify(input: string): string;
1109
- declare function stableId(prefix: string, content: string): string;
1110
-
1111
- declare function buildKnowledgeIndex(root: string): Promise<KnowledgeIndex>;
1112
- declare function writeKnowledgeIndex(root: string): Promise<KnowledgeIndex>;
1113
-
1114
- interface KnowledgeInspection {
1115
- pageCount: number;
1116
- sourceCount: number;
1117
- expiredSourceCount: number;
1118
- staleSourceCount: number;
1119
- edgeCount: number;
1120
- findingCount: number;
1121
- blockingFindingCount: number;
1122
- topPages: Array<{
1123
- path: string;
1124
- title: string;
1125
- degree: number;
1126
- sources: number;
1127
- }>;
1128
- sourceFreshness: SourceFreshnessInspection[];
1129
- findings: KnowledgeLintFinding[];
926
+ interface RagAnswerQualityJudgeOptions {
927
+ name?: string;
928
+ thresholds?: Partial<Record<RagEvalMetricKey, number>>;
929
+ weights?: Partial<Record<RagEvalMetricKey, number>>;
930
+ externalScorePolicy?: 'prefer-external' | 'deterministic-first';
931
+ minClaimSupport?: number;
1130
932
  }
1131
- interface SourceFreshnessInspection {
1132
- id: string;
1133
- title?: string;
1134
- uri: string;
1135
- status: 'fresh' | 'expired' | 'unknown';
1136
- validUntil?: string;
1137
- lastVerifiedAt?: string;
933
+ interface RagAnswerEvalCase {
934
+ scenario: RagAnswerEvalScenario;
935
+ artifact: RagAnswerEvalArtifact;
1138
936
  }
1139
- declare function inspectKnowledgeIndex(index: KnowledgeIndex, options?: {
937
+ interface RagAnswerQualityHookOptions {
938
+ scenarios: readonly RagAnswerEvalScenario[];
939
+ run: (scenario: RagAnswerEvalScenario) => MaybePromise<RagAnswerEvalArtifact>;
940
+ externalEvaluator?: (item: RagAnswerEvalCase) => MaybePromise<ExternalRagEvalScore | readonly ExternalRagEvalScore[] | undefined>;
941
+ thresholds?: Partial<Record<RagEvalMetricKey, number>>;
942
+ weights?: Partial<Record<RagEvalMetricKey, number>>;
943
+ }
944
+ interface RagCalibrationOptions {
945
+ scenario: RagAnswerEvalScenario;
946
+ strong: RagAnswerEvalArtifact;
947
+ weak: RagAnswerEvalArtifact;
948
+ judge?: JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario>;
949
+ minStrongScore?: number;
950
+ maxWeakScore?: number;
951
+ signal?: AbortSignal;
952
+ }
953
+ interface RagCalibrationResult {
954
+ passed: boolean;
955
+ strongScore: number;
956
+ weakScore: number;
957
+ gap: number;
958
+ }
959
+ interface KnowledgeBaseQualityOptions {
1140
960
  now?: Date;
1141
- }): KnowledgeInspection;
1142
- interface KnowledgeExplanation {
1143
- target: string;
1144
- page?: KnowledgePage;
1145
- sources: Array<{
1146
- id: string;
1147
- title?: string;
1148
- uri: string;
1149
- }>;
1150
- links: string[];
1151
- inbound: string[];
1152
- related: Array<{
1153
- path: string;
1154
- title: string;
1155
- score: number;
1156
- }>;
961
+ strict?: boolean;
962
+ minCitationRate?: number;
963
+ maxStaleSourceRate?: number;
1157
964
  }
1158
- declare function explainKnowledgeTarget(index: KnowledgeIndex, target: string): KnowledgeExplanation;
1159
-
1160
- /**
1161
- * HELD-OUT INVESTMENT-RESEARCH EVAL SET.
1162
- *
1163
- * The point of this file is the same FIREWALL the deep-question exam uses
1164
- * (`tests/loops/held-out-exam.ts`): the material facts and their checkable
1165
- * fragments are NEVER shown to a research loop. A loop is told only the company
1166
- * + ticker + a research-as-of CUTOFF date, and asked to write an investment
1167
- * thesis. AFTER it finishes, we grade the thesis it produced against THESE
1168
- * facts — facts it never saw — so a high score is thesis QUALITY (it surfaced
1169
- * the buried, material, non-obvious drivers) and not teaching-to-the-test.
1170
- *
1171
- * Each fact is a DEPTH fact by construction: a single ticker / company-name web
1172
- * search does NOT surface it. They are the things buried in the filings or
1173
- * knowable from then-available primary sources that a thorough analyst flags and
1174
- * a one-shot search misses — customer/revenue/deposit concentration, a debt
1175
- * maturity wall, a margin-trend reversal, a governance / related-party item, a
1176
- * specific competitive or regulatory risk, an off-balance-sheet loss.
1177
- *
1178
- * THREE HARD RULES, enforced by how the data was gathered (see
1179
- * docs/eval/investment-material-facts.md for the per-item provenance + the
1180
- * curation-bias disclosure):
1181
- *
1182
- * 1. SPECIFIC + CHECKABLE. Each fact carries `expected` keyword groups — the
1183
- * specific number / name / phrase — so a deterministic, model-free
1184
- * substring grader (`gradeFactAgainstText`) can score "did the thesis
1185
- * surface it". $0, reproducible, and it cannot leak the answer key into a
1186
- * model the loop could observe.
1187
- *
1188
- * 2. DERIVED FROM REAL FETCHED EVIDENCE. Every fact records the primary source
1189
- * it came from (`sourceUrl`, an SEC EDGAR 10-K) and the literal `evidence`
1190
- * value read out of that document. Nothing here is invented; an item that
1191
- * could not be independently sourced was DROPPED, not guessed (the drop log
1192
- * is in the doc).
1193
- *
1194
- * 3. KNOWABLE AT THE CUTOFF. Every fact was disclosed in, or computable from, a
1195
- * document available on or before the company's `cutoff` date. Post-cutoff
1196
- * hindsight (the eventual bankruptcy / collapse) is NOT a checklist item —
1197
- * it is recorded separately as `knownOutcome`, purely for the reader, and is
1198
- * never graded.
1199
- *
1200
- * Grading mirrors the deep-question exam exactly: a fact is SURFACED when the
1201
- * thesis text contains at least `minGroups` of its expected groups; a group is
1202
- * satisfied when ANY of its `anyOf` fragments appears (case-insensitive
1203
- * substring), so a faithful thesis phrased in its own words still grades as a
1204
- * hit. `anyOf` groups model synonyms; the load-bearing tokens are the specific
1205
- * numbers / names.
1206
- */
1207
- /** A required answer component: satisfied when any synonym fragment is present. */
1208
- interface ExpectedGroup {
1209
- /** Human label for the component (for the doc / audit). */
1210
- label: string;
1211
- /** Case-insensitive substring fragments; any one present satisfies the group. */
1212
- anyOf: string[];
1213
- }
1214
- /** Lens the fact belongs to — so a set can be checked for category coverage. */
1215
- type MaterialFactLens = 'concentration' | 'leverage' | 'margin-trend' | 'liquidity' | 'capital-return' | 'governance' | 'off-balance-sheet' | 'regulatory';
1216
- /** One held-out material fact with a checkable expected answer + its provenance. */
1217
- interface MaterialFact {
1218
- /** Stable id, `ticker/fN`. */
1219
- id: string;
1220
- /** Which analyst lens this fact exercises. For coverage + the doc. */
1221
- lens: MaterialFactLens;
1222
- /**
1223
- * The material fact, in plain words — for the doc/audit. NEVER shown to a loop.
1224
- * This is the thing a thorough analyst would flag and a ticker search misses.
1225
- */
1226
- fact: string;
1227
- /**
1228
- * The checkable answer as required keyword GROUPS. The thesis text must contain
1229
- * at least `minGroups` of these groups (default: all). A group is satisfied
1230
- * when ANY of its `anyOf` fragments appears (case-insensitive substring).
1231
- */
1232
- expected: ExpectedGroup[];
1233
- /**
1234
- * Minimum number of `expected` groups the thesis must contain to count the
1235
- * fact SURFACED. Default = all groups (the strict bar). Lowered (and documented
1236
- * inline) only when the fact is genuinely satisfiable by a subset.
1237
- */
1238
- minGroups?: number;
1239
- /**
1240
- * PROVENANCE. The primary source URL this fact was read from — an SEC EDGAR
1241
- * 10-K primary document, fetched live during curation.
1242
- */
1243
- sourceUrl: string;
1244
- /**
1245
- * The literal value / phrase read out of `sourceUrl` that grounds the fact.
1246
- * This is the "cite the actual filing + the value" requirement — verbatim or
1247
- * near-verbatim from the filing, with the figure.
1248
- */
1249
- evidence: string;
1250
- }
1251
- /** A company + the cutoff a loop researches as-of + its held-out material facts. */
1252
- interface CompanyEvalCase {
1253
- /** Ticker as of the cutoff. */
1254
- ticker: string;
1255
- /** Legal name as of the cutoff (what the loop is told to research). */
1256
- company: string;
1257
- /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */
1258
- cik: string;
1259
- /**
1260
- * Research-as-of date (ISO). The loop must reason as if it is this date; every
1261
- * `evidence` value was knowable on or before it. >= 18 months before this set
1262
- * was curated, so the outcome is known but is NOT a checklist item.
1263
- */
1264
- cutoff: string;
1265
- /** Sector, for coverage / the curation-bias disclosure. */
1266
- sector: string;
1267
- /**
1268
- * The known POST-cutoff outcome — recorded for the reader ONLY, never graded.
1269
- * Keeping it out of `facts` is what makes the set hindsight-free.
1270
- */
1271
- knownOutcome: string;
1272
- /** The held-out material facts for this company. */
1273
- facts: MaterialFact[];
965
+ interface KnowledgeBaseQualityReport {
966
+ ok: boolean;
967
+ metrics: {
968
+ page_count: number;
969
+ source_count: number;
970
+ citation_rate: number;
971
+ source_backed_page_rate: number;
972
+ stale_source_rate: number;
973
+ duplicate_source_hash_rate: number;
974
+ lint_error_count: number;
975
+ lint_warning_count: number;
976
+ };
977
+ findings: readonly RagGapFinding[];
1274
978
  }
1275
- /**
1276
- * The eval set. 5 public companies, 5-8 held-out material facts each, every fact
1277
- * grounded in a primary SEC EDGAR 10-K filed on or before the cutoff.
1278
- *
1279
- * CURATION-BIAS DISCLOSURE (full version in the doc): all five are companies
1280
- * whose buried risks later materialized, because that is where the material-vs-
1281
- * surface distinction is sharpest AND where the figures are easy to verify after
1282
- * the fact. This biases the set toward downside risks (two of the eight lenses,
1283
- * concentration + leverage, dominate) and toward distressed names. A production
1284
- * eval would balance these with companies whose buried facts were POSITIVE
1285
- * drivers and with survivors. This set is honest about that and reports the lens
1286
- * distribution so the bias is measurable, not hidden.
1287
- */
1288
- declare const investmentThesisSet: CompanyEvalCase[];
1289
- /**
1290
- * Grade ONE material fact against an investment thesis's full text. Returns
1291
- * whether the thesis SURFACED it plus which expected groups were found. The
1292
- * check is a deterministic case-insensitive substring scan — $0, model-free,
1293
- * reproducible — so the eval never leaks into a model the loop could observe.
1294
- */
1295
- declare function gradeFactAgainstText(fact: MaterialFact, thesisText: string): {
1296
- surfaced: boolean;
1297
- groupsFound: number;
1298
- groupsTotal: number;
1299
- foundLabels: string[];
1300
- };
1301
- /** Grade a whole company's thesis text: how many of its held-out facts it surfaces. */
1302
- declare function gradeCompanyAgainstText(company: CompanyEvalCase, thesisText: string): {
1303
- surfaced: number;
1304
- total: number;
1305
- perFact: ReturnType<typeof gradeFactAgainstText>[];
1306
- };
1307
- /** Total held-out facts across the set (the denominator the doc reports). */
1308
- declare function totalMaterialFacts(set?: CompanyEvalCase[]): number;
1309
- /** Count facts per lens across the set — used to report (and bound) curation bias. */
1310
- declare function lensDistribution(set?: CompanyEvalCase[]): Record<MaterialFactLens, number>;
1311
-
1312
- /**
1313
- * The INVESTMENT-THESIS research task.
1314
- *
1315
- * Given `{ company, ticker, cik, cutoff }`, drive the SAME two-agent research
1316
- * loop the ML deep-question A/B uses (`runVerifiedResearchLoop` + the real web
1317
- * worker) to research the company AS OF the cutoff — web + SEC EDGAR, both public
1318
- * — and produce an investment-thesis PAGE in the knowledge base: a judgment, the
1319
- * drivers, and the risks, grounded in what it fetched.
1320
- *
1321
- * This file builds NOTHING new for the loop: it composes the existing worker +
1322
- * driver + loop, supplies the readiness specs that steer the worker toward the
1323
- * filing-level evidence (the analyst lenses), then writes a synthesis thesis page
1324
- * the metric (`materialFactsSurfaced`) grades against the HELD-OUT checklist.
1325
- *
1326
- * THE FIREWALL: the task is told ONLY company + ticker + cutoff (+ the generic
1327
- * analyst-lens readiness specs every company gets). It is NEVER shown the
1328
- * checklist. The checklist is read only afterward, by the metric. So a high score
1329
- * is research depth, not teaching-to-the-test.
1330
- */
979
+ type MaybePromise<T> = T | Promise<T>;
980
+ declare function ragAnswerQualityJudge(options?: RagAnswerQualityJudgeOptions): JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario>;
981
+ declare function scoreRagAnswerArtifact(artifact: RagAnswerEvalArtifact, scenario: RagAnswerEvalScenario, options?: RagAnswerQualityJudgeOptions): RagAnswerMetricSummary;
982
+ declare function diagnoseRagAnswerFailure(metrics: Record<RagEvalMetricKey, number>, scenario: RagAnswerEvalScenario, thresholds?: Partial<Record<RagEvalMetricKey, number>>): RagGapFinding[];
983
+ declare function createRagAnswerQualityHook(options: RagAnswerQualityHookOptions): () => Promise<RagAnswerQualityResult>;
984
+ declare function calibrateRagAnswerJudge(options: RagCalibrationOptions): Promise<RagCalibrationResult>;
985
+ declare function normalizeExternalRagScores(scores: readonly ExternalRagEvalScore[]): Record<string, Record<RagEvalMetricKey, number>>;
986
+ declare function toRagasEvaluationRows(cases: readonly RagAnswerEvalCase[]): {
987
+ user_input: string;
988
+ response: string;
989
+ retrieved_contexts: string[];
990
+ reference: string | undefined;
991
+ reference_contexts: string[];
992
+ }[];
993
+ declare function toDeepEvalTestCases(cases: readonly RagAnswerEvalCase[]): {
994
+ input: string;
995
+ actual_output: string;
996
+ expected_output: string | undefined;
997
+ retrieval_context: string[];
998
+ context: string[];
999
+ }[];
1000
+ declare function toTruLensRecords(cases: readonly RagAnswerEvalCase[]): {
1001
+ input: string;
1002
+ output: string;
1003
+ context: string;
1004
+ }[];
1005
+ declare function toRagCheckerRecords(cases: readonly RagAnswerEvalCase[]): {
1006
+ query_id: string;
1007
+ query: string;
1008
+ gt_answer: string | undefined;
1009
+ response: string;
1010
+ retrieved_context: {
1011
+ doc_id: string;
1012
+ text: string;
1013
+ }[];
1014
+ claims: string[];
1015
+ }[];
1016
+ declare function scoreKnowledgeBaseIndex(index: KnowledgeIndex, options?: KnowledgeBaseQualityOptions): KnowledgeBaseQualityReport;
1331
1017
 
1332
- /** The minimal brief a thesis run is given the firewall boundary. */
1333
- interface ThesisTaskInput {
1334
- /** Legal name as of the cutoff — what the loop researches. */
1335
- company: string;
1336
- /** Ticker as of the cutoff. */
1337
- ticker: string;
1338
- /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */
1339
- cik: string;
1340
- /** Research-as-of date (ISO). The loop must reason as if it is this date. */
1341
- cutoff: string;
1342
- /** Sector, for the readiness query context (NOT a checklist hint). */
1343
- sector?: string;
1018
+ type KnowledgeImprovementStatus = 'running' | 'candidate-ready' | 'promoted' | 'rejected' | 'blocked';
1019
+ interface KnowledgeImprovementMetricProvenanceBase {
1020
+ evaluator: string;
1021
+ version: string;
1344
1022
  }
1345
- /**
1346
- * The generic analyst-lens readiness specs every company gets. They are the ONLY
1347
- * thing the loop is told about WHAT to look for, and they name the LENSES a
1348
- * thorough analyst checks (balance-sheet risk, concentration, leverage, margins,
1349
- * liquidity, governance, regulatory) and where they live (the latest SEC 10-K) —
1350
- * NOT the answers. They steer the worker's web/EDGAR search toward the filing,
1351
- * not toward the held-out facts (which the loop never sees).
1352
- *
1353
- * `minSources` is set above 1 so the readiness gate stays UNMET after a single
1354
- * fetch and the loop runs multiple rounds — the depth-driving driver needs >1
1355
- * round to steer, exactly as the ML-exam multi-round probe established.
1356
- */
1357
- declare function thesisReadinessSpecs(input: ThesisTaskInput): KnowledgeReadinessSpec[];
1358
- interface ThesisRunOptions {
1359
- /** The KB root the loop writes into. */
1023
+ type KnowledgeImprovementMetricProvenance = (KnowledgeImprovementMetricProvenanceBase & {
1024
+ method: 'deterministic';
1025
+ }) | (KnowledgeImprovementMetricProvenanceBase & {
1026
+ method: 'sampled' | 'composite';
1027
+ corpusHash: string;
1028
+ runRecords: RunRecord[];
1029
+ }) | (KnowledgeImprovementMetricProvenanceBase & {
1030
+ method: 'model';
1031
+ model: string;
1032
+ corpusHash: string;
1033
+ runRecords: RunRecord[];
1034
+ });
1035
+ interface KnowledgeImprovementMetric {
1036
+ score: number;
1037
+ passed: boolean;
1038
+ dimensions?: Record<string, number>;
1039
+ notes?: string;
1040
+ provenance: KnowledgeImprovementMetricProvenance;
1041
+ }
1042
+ interface KnowledgeImprovementEvaluationInput {
1043
+ runId: string;
1044
+ iteration: number;
1360
1045
  root: string;
1361
- /** Shared router client (web search + chat). Defaults to env creds. */
1362
- router: RouterClient;
1363
- /** The driver — verify/dedup or research-driving. The loop's coordinator. */
1364
- driver: ResearchDriver;
1365
- /** Round budget. Default 3 (the depth-driving driver needs >1). */
1366
- maxRounds?: number;
1367
- /** Worker tuning forwarded to `createWebResearchWorker`. */
1368
- workerOptions?: Omit<WebResearchWorkerOptions, 'router'>;
1369
- /** Max tokens for the synthesis pass. Default 1600 (above glm-5.2's reasoning floor). */
1370
- synthesisMaxTokens?: number;
1046
+ baselineRoot: string;
1047
+ candidateRoot: string;
1048
+ baselineIndex: KnowledgeIndex;
1049
+ candidateIndex: KnowledgeIndex;
1050
+ baseHash: string;
1051
+ candidateHash: string;
1052
+ validation: ValidateKnowledgeResult;
1053
+ readiness?: EvalKnowledgeBundleBuildResult;
1054
+ kbQuality: KnowledgeBaseQualityReport;
1055
+ lifecycle?: RunRagKnowledgeImprovementLoopResult;
1371
1056
  signal?: AbortSignal;
1372
1057
  }
1373
- interface ThesisRunResult {
1374
- loop: VerifiedResearchLoopResult;
1375
- /** The synthesized thesis text. */
1376
- thesis: string;
1377
- /** Path of the thesis page written into the KB. */
1378
- thesisPath: string;
1379
- }
1380
- /**
1381
- * Run the full thesis task: drive the two-agent loop to research the company AS
1382
- * OF the cutoff, then synthesize + write the thesis page. Returns the loop result
1383
- * + the thesis text + the page path. The caller grades the KB with
1384
- * `materialFactsSurfaced(root, checklist)` — the checklist is never passed here.
1385
- */
1386
- declare function runInvestmentThesisTask(input: ThesisTaskInput, options: ThesisRunOptions): Promise<ThesisRunResult>;
1387
-
1388
- interface ApplyWriteBlocksResult {
1389
- written: string[];
1390
- warnings: string[];
1391
- }
1392
- declare function applyKnowledgeWriteBlocks(root: string, proposalText: string): Promise<ApplyWriteBlocksResult>;
1393
- declare function applyKnowledgeWriteBlocksFile(root: string, proposalPath: string): Promise<ApplyWriteBlocksResult>;
1394
-
1395
- interface ValidateKnowledgeOptions {
1396
- strict?: boolean;
1397
- }
1398
- interface ValidateKnowledgeResult {
1399
- ok: boolean;
1400
- findings: KnowledgeLintFinding[];
1058
+ type KnowledgeImprovementEvaluator = (input: KnowledgeImprovementEvaluationInput) => Promise<KnowledgeImprovementMetric> | KnowledgeImprovementMetric;
1059
+ interface KnowledgeImprovementCandidateRecord {
1060
+ iteration: number;
1061
+ candidateId: string;
1062
+ baseHash: string;
1063
+ candidateHash?: string;
1064
+ evidenceHash?: string;
1065
+ promotionPlanHash?: string;
1066
+ status: KnowledgeImprovementStatus;
1067
+ createdAt: string;
1068
+ updatedAt: string;
1401
1069
  }
1402
- declare function validateKnowledgeIndex(index: KnowledgeIndex, options?: ValidateKnowledgeOptions): ValidateKnowledgeResult;
1403
-
1404
- interface KnowledgeResearchLoopContext {
1070
+ interface KnowledgeImprovementRunState {
1071
+ runId: string;
1405
1072
  root: string;
1406
1073
  goal: string;
1407
- iteration: number;
1408
- index: KnowledgeIndex;
1409
- lintFindings: KnowledgeLintFinding[];
1410
- validation: ValidateKnowledgeResult;
1411
- readiness?: EvalKnowledgeBundleBuildResult;
1412
- previousSteps: KnowledgeResearchLoopStep[];
1413
- signal?: AbortSignal;
1074
+ status: KnowledgeImprovementStatus;
1075
+ baseHash: string;
1076
+ createdAt: string;
1077
+ updatedAt: string;
1078
+ ownerId?: string;
1079
+ candidates: KnowledgeImprovementCandidateRecord[];
1080
+ promotedCandidateId?: string;
1081
+ blockedReason?: string;
1414
1082
  }
1415
- interface KnowledgeResearchLoopDecision {
1416
- /**
1417
- * Free-form notes from the researcher. Keep this human-readable; products can
1418
- * store it as the research transcript.
1419
- */
1420
- notes?: string;
1421
- /**
1422
- * Local files to register as immutable sources before applying proposals.
1423
- */
1424
- sourcePaths?: string[];
1425
- /**
1426
- * Textual source artifacts discovered by an agent, browser worker, connector,
1427
- * or deep-research process.
1428
- */
1429
- sourceTexts?: AddSourceTextInput[];
1430
- /**
1431
- * Safe write protocol text. The loop parses and applies only accepted
1432
- * `---FILE: knowledge/...---` blocks.
1433
- */
1434
- proposalText?: string;
1435
- /**
1436
- * The researcher decides when the wiki is good enough. The loop deliberately
1437
- * does not encode a domain-specific definition of "done".
1438
- */
1439
- done?: boolean;
1440
- metadata?: Record<string, unknown>;
1083
+ interface KnowledgeImprovementResult {
1084
+ runId: string;
1085
+ state: KnowledgeImprovementRunState;
1086
+ candidate?: KnowledgeImprovementCandidateRecord;
1087
+ evaluation?: KnowledgeImprovementMetric;
1088
+ lifecycle?: RunRagKnowledgeImprovementLoopResult;
1089
+ promoted: boolean;
1090
+ blocked: boolean;
1441
1091
  }
1442
- interface KnowledgeResearchLoopStep {
1443
- iteration: number;
1444
- notes?: string;
1445
- addedSources: SourceRecord[];
1446
- applied?: ApplyWriteBlocksResult;
1447
- lintFindings: KnowledgeLintFinding[];
1448
- validation: ValidateKnowledgeResult;
1449
- readiness?: EvalKnowledgeBundleBuildResult;
1450
- event: KnowledgeEvent;
1451
- done: boolean;
1452
- metadata?: Record<string, unknown>;
1092
+ declare const KnowledgeImprovementRunStateSchema: z.ZodObject<{
1093
+ runId: z.ZodString;
1094
+ root: z.ZodString;
1095
+ goal: z.ZodString;
1096
+ status: z.ZodEnum<{
1097
+ rejected: "rejected";
1098
+ promoted: "promoted";
1099
+ running: "running";
1100
+ "candidate-ready": "candidate-ready";
1101
+ blocked: "blocked";
1102
+ }>;
1103
+ baseHash: z.ZodString;
1104
+ createdAt: z.ZodISODateTime;
1105
+ updatedAt: z.ZodISODateTime;
1106
+ ownerId: z.ZodOptional<z.ZodString>;
1107
+ candidates: z.ZodArray<z.ZodObject<{
1108
+ iteration: z.ZodNumber;
1109
+ candidateId: z.ZodString;
1110
+ baseHash: z.ZodString;
1111
+ candidateHash: z.ZodOptional<z.ZodString>;
1112
+ evidenceHash: z.ZodOptional<z.ZodString>;
1113
+ promotionPlanHash: z.ZodOptional<z.ZodString>;
1114
+ status: z.ZodEnum<{
1115
+ rejected: "rejected";
1116
+ promoted: "promoted";
1117
+ running: "running";
1118
+ "candidate-ready": "candidate-ready";
1119
+ blocked: "blocked";
1120
+ }>;
1121
+ createdAt: z.ZodISODateTime;
1122
+ updatedAt: z.ZodISODateTime;
1123
+ }, z.core.$strict>>;
1124
+ promotedCandidateId: z.ZodOptional<z.ZodString>;
1125
+ blockedReason: z.ZodOptional<z.ZodString>;
1126
+ }, z.core.$strict>;
1127
+ declare const KnowledgeImprovementEvidenceSchema: z.ZodObject<{
1128
+ kind: z.ZodLiteral<"knowledge-improvement-evidence">;
1129
+ runId: z.ZodString;
1130
+ candidateId: z.ZodString;
1131
+ iteration: z.ZodNumber;
1132
+ goalHash: z.ZodString;
1133
+ baseHash: z.ZodString;
1134
+ candidateHash: z.ZodString;
1135
+ promotionPlanHash: z.ZodString;
1136
+ validation: z.ZodUnknown;
1137
+ readiness: z.ZodNullable<z.ZodUnknown>;
1138
+ kbQuality: z.ZodUnknown;
1139
+ evaluation: z.ZodObject<{
1140
+ score: z.ZodNumber;
1141
+ passed: z.ZodBoolean;
1142
+ dimensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
1143
+ notes: z.ZodOptional<z.ZodString>;
1144
+ provenance: z.ZodDiscriminatedUnion<[z.ZodObject<{
1145
+ evaluator: z.ZodString;
1146
+ version: z.ZodString;
1147
+ method: z.ZodLiteral<"deterministic">;
1148
+ }, z.core.$strict>, z.ZodObject<{
1149
+ evaluator: z.ZodString;
1150
+ version: z.ZodString;
1151
+ method: z.ZodEnum<{
1152
+ composite: "composite";
1153
+ sampled: "sampled";
1154
+ }>;
1155
+ corpusHash: z.ZodString;
1156
+ runRecords: z.ZodArray<z.ZodCustom<RunRecord, RunRecord>>;
1157
+ }, z.core.$strict>, z.ZodObject<{
1158
+ evaluator: z.ZodString;
1159
+ version: z.ZodString;
1160
+ method: z.ZodLiteral<"model">;
1161
+ model: z.ZodString;
1162
+ corpusHash: z.ZodString;
1163
+ runRecords: z.ZodArray<z.ZodCustom<RunRecord, RunRecord>>;
1164
+ }, z.core.$strict>], "method">;
1165
+ }, z.core.$strict>;
1166
+ lifecycle: z.ZodNullable<z.ZodUnknown>;
1167
+ }, z.core.$strict>;
1168
+ type KnowledgeImprovementEvidence = z.infer<typeof KnowledgeImprovementEvidenceSchema>;
1169
+ /** Portable identity of one measured candidate. Paths and mutable run state are deliberately excluded. */
1170
+ declare const KnowledgeImprovementCandidateRefSchema: z.ZodObject<{
1171
+ kind: z.ZodLiteral<"knowledge-improvement-candidate">;
1172
+ runId: z.ZodString;
1173
+ candidateId: z.ZodString;
1174
+ goalHash: z.ZodString;
1175
+ baseHash: z.ZodString;
1176
+ candidateHash: z.ZodString;
1177
+ evidenceHash: z.ZodString;
1178
+ promotionPlanHash: z.ZodString;
1179
+ }, z.core.$strict>;
1180
+ type KnowledgeImprovementCandidateRef = z.infer<typeof KnowledgeImprovementCandidateRefSchema>;
1181
+ interface PromoteKnowledgeCandidateOptions {
1182
+ root: string;
1183
+ candidate: KnowledgeImprovementCandidateRef;
1184
+ ownerId?: string;
1185
+ leaseTtlMs?: number;
1186
+ now?: () => Date;
1187
+ onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void;
1453
1188
  }
1454
- interface RunKnowledgeResearchLoopOptions {
1189
+ interface UseKnowledgeImprovementCandidateOptions {
1455
1190
  root: string;
1456
- goal: string;
1457
- maxIterations?: number;
1458
- actor?: string;
1459
- strict?: ValidateKnowledgeOptions['strict'];
1460
- readinessSpecs?: KnowledgeReadinessSpec[];
1461
- readinessTaskId?: string;
1462
- readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>;
1463
- sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>;
1464
- signal?: AbortSignal;
1465
- step(context: KnowledgeResearchLoopContext): Promise<KnowledgeResearchLoopDecision> | KnowledgeResearchLoopDecision;
1466
- onStep?: (step: KnowledgeResearchLoopStep) => Promise<void> | void;
1191
+ candidate: KnowledgeImprovementCandidateRef;
1467
1192
  }
1468
- interface KnowledgeResearchLoopResult {
1193
+ interface ResolvedKnowledgeImprovementCandidate {
1469
1194
  root: string;
1470
- goal: string;
1471
- iterations: number;
1472
- done: boolean;
1473
- index: KnowledgeIndex;
1474
- lintFindings: KnowledgeLintFinding[];
1475
- validation: ValidateKnowledgeResult;
1476
- readiness?: EvalKnowledgeBundleBuildResult;
1477
- steps: KnowledgeResearchLoopStep[];
1195
+ candidate: KnowledgeImprovementCandidateRef;
1196
+ evaluation: KnowledgeImprovementMetric;
1478
1197
  }
1479
- type KnowledgeControlLoopState = KnowledgeResearchLoopContext;
1480
- type KnowledgeControlLoopAction = KnowledgeResearchLoopDecision;
1481
- type KnowledgeControlLoopActionResult = KnowledgeResearchLoopStep;
1482
- interface KnowledgeControlLoopAdapterOptions {
1198
+ interface KnowledgeImprovementRetrievalOptions extends Omit<RunRetrievalImprovementLoopOptions, 'index' | 'runDir'> {
1199
+ runDir?: RunRetrievalImprovementLoopOptions['runDir'];
1200
+ }
1201
+ interface KnowledgeImprovementUpdateInput extends RagKnowledgeUpdateInput {
1202
+ runId: string;
1203
+ iteration: number;
1204
+ candidateId: string;
1205
+ root: string;
1206
+ baselineRoot: string;
1207
+ candidateRoot: string;
1208
+ baseHash: string;
1209
+ }
1210
+ type KnowledgeImprovementUpdate = (input: KnowledgeImprovementUpdateInput) => Promise<RagKnowledgeUpdateResult> | RagKnowledgeUpdateResult;
1211
+ interface KnowledgeImprovementOptions {
1483
1212
  root: string;
1484
1213
  goal: string;
1485
- actor?: string;
1214
+ runId?: string;
1215
+ ownerId?: string;
1216
+ leaseTtlMs?: number;
1217
+ resume?: boolean;
1218
+ maxCandidates?: number;
1219
+ candidateResearchIterations?: number;
1486
1220
  strict?: ValidateKnowledgeOptions['strict'];
1487
1221
  readinessSpecs?: KnowledgeReadinessSpec[];
1488
1222
  readinessTaskId?: string;
1489
1223
  readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>;
1490
- sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>;
1491
- }
1492
- type KnowledgeControlLoopAdapter = Pick<ControlRuntimeConfig<KnowledgeControlLoopState, KnowledgeControlLoopAction, KnowledgeControlLoopActionResult, ControlEvalResult>, 'intent' | 'observe' | 'validate' | 'act' | 'shouldStop'>;
1493
- /**
1494
- * Adapter for running knowledge growth through `agent-eval`'s generic control
1495
- * runtime. The caller still owns `decide`: that can be a proposer agent,
1496
- * reviewer agent, deterministic policy, or a composition of all three.
1497
- */
1498
- declare function createKnowledgeControlLoopAdapter(options: KnowledgeControlLoopAdapterOptions): KnowledgeControlLoopAdapter;
1499
- declare function runKnowledgeResearchLoop(options: RunKnowledgeResearchLoopOptions): Promise<KnowledgeResearchLoopResult>;
1500
-
1501
- type RagKnowledgeImprovementPhase = 'retrieval-tuning' | 'gap-diagnosis' | 'knowledge-acquisition' | 'knowledge-update' | 'answer-quality' | 'promotion';
1502
- type RagKnowledgeImprovementPhaseStatus = 'completed' | 'skipped' | 'failed';
1503
- type RagGapKind = 'missing-source' | 'stale-source' | 'retrieval-miss' | 'retrieval-noise' | 'chunking-mismatch' | 'missing-multihop-evidence' | 'generator-unsupported-claim' | 'citation-mismatch' | 'incorrect-abstention' | 'unknown';
1504
- type RagGapSeverity = 'info' | 'warning' | 'error' | 'critical';
1505
- interface RagGapFinding {
1506
- id: string;
1507
- kind: RagGapKind;
1508
- severity: RagGapSeverity;
1509
- message: string;
1510
- scenarioId?: string;
1511
- evidence?: Record<string, JsonValue>;
1512
- }
1513
- interface RagKnowledgeImprovementPhaseResult {
1514
- phase: RagKnowledgeImprovementPhase;
1515
- status: RagKnowledgeImprovementPhaseStatus;
1516
- summary: string;
1517
- startedAt: string;
1518
- finishedAt: string;
1519
- metadata?: Record<string, JsonValue>;
1520
- }
1521
- interface RagPhaseInputBase {
1522
- goal: string;
1523
- phases: readonly RagKnowledgeImprovementPhaseResult[];
1524
- signal?: AbortSignal;
1525
- }
1526
- interface RagDiagnosisInput extends RagPhaseInputBase {
1527
- retrieval?: RunRetrievalImprovementLoopResult;
1528
- }
1529
- interface RagKnowledgeAcquisitionInput extends RagPhaseInputBase {
1530
- retrieval?: RunRetrievalImprovementLoopResult;
1531
- findings: readonly RagGapFinding[];
1532
- }
1533
- interface RagKnowledgeUpdateInput extends RagPhaseInputBase {
1534
- retrieval?: RunRetrievalImprovementLoopResult;
1535
- findings: readonly RagGapFinding[];
1536
- acquisition?: KnowledgeResearchLoopDecision;
1537
- }
1538
- interface RagKnowledgeUpdateResult {
1539
- applied: boolean;
1540
- summary: string;
1541
- research?: KnowledgeResearchLoopResult;
1542
- metadata?: Record<string, JsonValue>;
1543
- }
1544
- interface RagAnswerQualityInput extends RagPhaseInputBase {
1545
- retrieval?: RunRetrievalImprovementLoopResult;
1546
- findings: readonly RagGapFinding[];
1547
- acquisition?: KnowledgeResearchLoopDecision;
1548
- knowledgeUpdate?: RagKnowledgeUpdateResult;
1549
- }
1550
- interface RagAnswerQualityResult {
1551
- passed: boolean;
1552
- metrics: Record<string, number>;
1553
- findings?: readonly RagGapFinding[];
1554
- metadata?: Record<string, JsonValue>;
1555
- }
1556
- interface RagPromotionInput extends RagPhaseInputBase {
1557
- retrieval?: RunRetrievalImprovementLoopResult;
1558
- findings: readonly RagGapFinding[];
1559
- acquisition?: KnowledgeResearchLoopDecision;
1560
- knowledgeUpdate?: RagKnowledgeUpdateResult;
1561
- answerQuality?: RagAnswerQualityResult;
1562
- }
1563
- interface RagPromotionResult {
1564
- promoted: boolean;
1565
- reason: string;
1566
- metadata?: Record<string, JsonValue>;
1567
- }
1568
- interface RagKnowledgeResearchOptions extends Omit<RunKnowledgeResearchLoopOptions, 'goal' | 'signal' | 'step'> {
1569
- goal?: string;
1224
+ kbQuality?: KnowledgeBaseQualityOptions;
1570
1225
  step?: RunKnowledgeResearchLoopOptions['step'];
1571
- }
1572
- interface RunRagKnowledgeImprovementLoopOptions {
1573
- goal: string;
1574
- retrieval?: RunRetrievalImprovementLoopOptions;
1575
- diagnose?: (input: RagDiagnosisInput) => MaybePromise$1<readonly RagGapFinding[]>;
1576
- acquireKnowledge?: (input: RagKnowledgeAcquisitionInput) => MaybePromise$1<KnowledgeResearchLoopDecision>;
1577
- knowledgeResearch?: RagKnowledgeResearchOptions;
1578
- updateKnowledge?: (input: RagKnowledgeUpdateInput) => MaybePromise$1<RagKnowledgeUpdateResult>;
1579
- evaluateAnswers?: (input: RagAnswerQualityInput) => MaybePromise$1<RagAnswerQualityResult>;
1580
- promote?: (input: RagPromotionInput) => MaybePromise$1<RagPromotionResult>;
1226
+ knowledgeResearch?: Omit<RagKnowledgeResearchOptions, 'root'>;
1227
+ retrieval?: KnowledgeImprovementRetrievalOptions;
1228
+ diagnose?: NonNullable<RunRagKnowledgeImprovementLoopOptions['diagnose']>;
1229
+ acquireKnowledge?: NonNullable<RunRagKnowledgeImprovementLoopOptions['acquireKnowledge']>;
1230
+ updateKnowledge?: KnowledgeImprovementUpdate;
1231
+ evaluateAnswers?: NonNullable<RunRagKnowledgeImprovementLoopOptions['evaluateAnswers']>;
1232
+ decidePromotion?: NonNullable<RunRagKnowledgeImprovementLoopOptions['promote']>;
1581
1233
  enabledPhases?: readonly RagKnowledgeImprovementPhase[];
1582
1234
  requiredPhases?: readonly RagKnowledgeImprovementPhase[];
1235
+ evaluate?: KnowledgeImprovementEvaluator;
1583
1236
  signal?: AbortSignal;
1584
1237
  now?: () => Date;
1238
+ onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void;
1585
1239
  }
1586
- interface RunRagKnowledgeImprovementLoopResult {
1587
- goal: string;
1588
- phases: readonly RagKnowledgeImprovementPhaseResult[];
1589
- retrieval?: RunRetrievalImprovementLoopResult;
1590
- findings: readonly RagGapFinding[];
1591
- acquisition?: KnowledgeResearchLoopDecision;
1592
- knowledgeUpdate?: RagKnowledgeUpdateResult;
1593
- answerQuality?: RagAnswerQualityResult;
1594
- promotion?: RagPromotionResult;
1240
+ declare function knowledgeImprovementRunId(root: string, goal: string): string;
1241
+ declare function knowledgeImprovementRunDir(root: string, runId: string): string;
1242
+ declare function loadKnowledgeImprovementState(root: string, runId: string): Promise<KnowledgeImprovementRunState | null>;
1243
+ /** Freeze the exact knowledge bytes and measured evidence a later approval may promote. */
1244
+ declare function knowledgeImprovementCandidateRef(result: Pick<KnowledgeImprovementResult, 'runId' | 'state' | 'candidate'>): KnowledgeImprovementCandidateRef;
1245
+ /** Use one measured snapshot while its directory identity remains open and stable. */
1246
+ declare function withKnowledgeImprovementCandidate<T>(options: UseKnowledgeImprovementCandidateOptions, use: (candidate: ResolvedKnowledgeImprovementCandidate) => Promise<T> | T): Promise<T>;
1247
+ /** Promote one previously measured candidate without rerunning research or evaluation. */
1248
+ declare function promoteKnowledgeCandidate(options: PromoteKnowledgeCandidateOptions): Promise<KnowledgeImprovementResult>;
1249
+ declare function improveKnowledgeBase(options: KnowledgeImprovementOptions): Promise<KnowledgeImprovementResult>;
1250
+ interface KnowledgeImprovementEvent extends Record<string, unknown> {
1251
+ at: string;
1252
+ type: string;
1253
+ }
1254
+ declare function loadKnowledgeImprovementEvents(root: string, runId: string): Promise<KnowledgeImprovementEvent[]>;
1255
+ declare function hashKnowledgeBase(root: string): Promise<string>;
1256
+
1257
+ /** Convert a measured knowledge candidate into the shared review and execution identity. */
1258
+ declare function toAgentCandidateKnowledgeRef(candidate: KnowledgeImprovementCandidateRef): AgentCandidateKnowledgeRef;
1259
+ /** Recover agent-knowledge's candidate identity from the shared contract. */
1260
+ declare function fromAgentCandidateKnowledgeRef(candidate: AgentCandidateKnowledgeRef): KnowledgeImprovementCandidateRef;
1261
+
1262
+ /**
1263
+ * Change detection across snapshots of one source's fragments.
1264
+ *
1265
+ * The output drives the continuous-ingestion loop: each `KnowledgeChange`
1266
+ * carries the eval dimensions affected (`affectedDimensions`), which an
1267
+ * agent-eval campaign scheduler consumes to decide which campaigns to
1268
+ * re-run. Three change kinds:
1269
+ *
1270
+ * - `added` — fragment id appears in `next` but not `prev`.
1271
+ * - `removed` — fragment id appears in `prev` but not `next`. Typical
1272
+ * trigger: an authority retires a Wex slug, or a state SOS reorganises
1273
+ * its forms catalogue.
1274
+ * - `modified` — fragment id appears in both, body hash differs. This
1275
+ * is the dominant change kind in practice — the Ryan-LLC v. FTC
1276
+ * vacatur case manifests as a `modified` on the Wex non-compete
1277
+ * fragment, NOT as a removed one.
1278
+ *
1279
+ * Unverifiable fragments are filtered out before diffing — comparing a
1280
+ * captcha-blocked snapshot against a real one would falsely fire every
1281
+ * fragment as removed. The caller can inspect the raw lists if they want
1282
+ * to surface block-page failures.
1283
+ *
1284
+ * Within-snapshot duplicate ids are an upstream bug; this function picks
1285
+ * the LAST one and emits a diagnostic via the `warnings` field.
1286
+ *
1287
+ * @stable
1288
+ */
1289
+ type KnowledgeChangeKind = 'added' | 'removed' | 'modified';
1290
+ interface KnowledgeChange {
1291
+ /** Source-scoped id (matches `KnowledgeFragment.id`). */
1292
+ fragmentId: string;
1293
+ kind: KnowledgeChangeKind;
1294
+ /**
1295
+ * For `added`: full body of the new fragment.
1296
+ * For `removed`: full body of the prior fragment.
1297
+ * For `modified`: unified-diff-style payload `{ before, after }` body strings.
1298
+ */
1299
+ diff?: {
1300
+ before?: string;
1301
+ after?: string;
1302
+ };
1303
+ /**
1304
+ * Eval dimensions to re-score. Computed as the union of both fragments'
1305
+ * `dimensionHints`. The eval cron treats this as a set of campaign tags.
1306
+ */
1307
+ affectedDimensions: string[];
1308
+ /** URL of the affected authority page (from whichever side has it). */
1309
+ url?: string;
1310
+ /**
1311
+ * Source-attested change time. For `modified`, takes the NEXT fragment's
1312
+ * `sourceUpdatedAt`. For `removed`, takes the PRIOR fragment's
1313
+ * `sourceUpdatedAt`. For `added`, takes the NEXT fragment's
1314
+ * `sourceUpdatedAt`. Consumers index changes by this date.
1315
+ */
1316
+ detectedAt: string;
1317
+ }
1318
+ interface DetectChangesResult {
1319
+ changes: KnowledgeChange[];
1320
+ /** Counts by kind — handy for dashboards. */
1321
+ summary: {
1322
+ added: number;
1323
+ removed: number;
1324
+ modified: number;
1325
+ };
1326
+ /** Non-fatal diagnostics (duplicate ids, dropped unverifiable fragments). */
1327
+ warnings: string[];
1328
+ }
1329
+ interface DetectChangesOptions {
1330
+ /**
1331
+ * When true (default), unverifiable fragments are dropped from both
1332
+ * sides before comparison. Set false ONLY when debugging block-page
1333
+ * issues — comparing against unverifiable content emits false
1334
+ * `removed`/`modified` changes.
1335
+ */
1336
+ skipUnverifiable?: boolean;
1337
+ /**
1338
+ * When provided, only changes whose `affectedDimensions` intersect this
1339
+ * set are returned. Useful for cron loops that schedule per-dimension
1340
+ * eval campaigns and only care about a subset.
1341
+ */
1342
+ filterDimensions?: string[];
1595
1343
  }
1596
- type MaybePromise$1<T> = T | Promise<T>;
1597
- declare function runRagKnowledgeImprovementLoop(options: RunRagKnowledgeImprovementLoopOptions): Promise<RunRagKnowledgeImprovementLoopResult>;
1344
+ declare function detectChanges(prev: KnowledgeFragment[], next: KnowledgeFragment[], options?: DetectChangesOptions): DetectChangesResult;
1598
1345
 
1599
- type RagEvalProvider = 'agent-knowledge' | 'ragas' | 'deepeval' | 'trulens' | 'ragchecker' | 'custom';
1600
- type RagEvalMetricKey = 'context_precision' | 'context_recall' | 'context_relevance' | 'context_sufficiency' | 'faithfulness' | 'groundedness' | 'answer_relevance' | 'answer_correctness' | 'citation_support' | 'abstention' | 'unsupported_answer_rate';
1601
- type RagEvalSlice = 'known-answer' | 'paraphrase' | 'distractor' | 'freshness' | 'multi-source' | 'unanswerable' | 'long-tail' | 'custom';
1602
- interface RagEvalContext {
1603
- id: string;
1604
- text: string;
1605
- rank?: number;
1606
- pageId?: string;
1607
- sourceId?: string;
1608
- anchorId?: string;
1609
- stale?: boolean;
1610
- metadata?: Record<string, JsonValue>;
1611
- }
1612
- interface RagEvalCitation {
1613
- id: string;
1614
- claimId?: string;
1615
- contextId?: string;
1616
- pageId?: string;
1617
- sourceId?: string;
1618
- anchorId?: string;
1619
- quote?: string;
1620
- metadata?: Record<string, JsonValue>;
1346
+ interface ChunkingOptions {
1347
+ targetChars: number;
1348
+ maxChars: number;
1349
+ minChars: number;
1350
+ overlapChars: number;
1621
1351
  }
1622
- interface RagEvalClaim {
1623
- id: string;
1352
+ interface KnowledgeChunk {
1353
+ index: number;
1624
1354
  text: string;
1625
- citationIds?: readonly string[];
1626
- metadata?: Record<string, JsonValue>;
1355
+ headingPath: string;
1356
+ charStart: number;
1357
+ charEnd: number;
1358
+ oversized: boolean;
1627
1359
  }
1628
- interface RagRequiredContext {
1629
- id?: string;
1630
- text?: string;
1631
- pageId?: string;
1632
- sourceId?: string;
1633
- anchorId?: string;
1360
+ declare function chunkMarkdown(content: string, options?: Partial<ChunkingOptions>): KnowledgeChunk[];
1361
+ declare function stripFrontmatter(content: string): {
1362
+ body: string;
1363
+ bodyOffset: number;
1364
+ };
1365
+
1366
+ /**
1367
+ * Claim-grounding mode for `runVerifiedResearchLoop`.
1368
+ *
1369
+ * The two-agent loop's existing verifier judges a source's on-topic RELEVANCE
1370
+ * (is this page about the goal?). On the topic sets we have measured, its
1371
+ * cleanliness win is dominated by DE-DUPLICATION — which a deterministic
1372
+ * content-hash / canonical-URL check captures at ~none of the LLM premium (see
1373
+ * `docs/results/cost-quality.md`). That makes the LLM verifier look expensive
1374
+ * for what a cheap rule already does.
1375
+ *
1376
+ * Claim-grounding targets a DIFFERENT, harder error band: a citation that is
1377
+ * relevant and unique but **misattributed** — the page is on-topic, the URL is
1378
+ * real, yet the specific CLAIM the source is cited for does NOT actually appear
1379
+ * in the page. This is the citation-fabrication failure mode of LLM research:
1380
+ * the model writes a plausible sentence and hangs a real URL off it that never
1381
+ * says any such thing. Neither de-dup nor a relevance judge catches it (both can
1382
+ * pass a misattributed-but-on-topic page); only checking the claim against the
1383
+ * fetched text does.
1384
+ *
1385
+ * The check is EXECUTABLE GROUND TRUTH, not another LLM opinion: the worker
1386
+ * attaches the specific claim it is citing the source for, and the verifier
1387
+ * tests whether that claim is PRESENT (verbatim, normalized, or as a sufficient
1388
+ * content-word overlap / close paraphrase) in the `htmlToText` output of the
1389
+ * page the worker actually fetched. A claim that is not grounded is rejected as
1390
+ * misattributed. Because the oracle is deterministic text presence — not a model
1391
+ * call — it is a deployable, non-oracle verifier: it can run in production with
1392
+ * zero inference cost, OR be composed with the LLM relevance verifier so the
1393
+ * loop rejects BOTH off-topic AND misattributed sources.
1394
+ *
1395
+ * This module is content-free and any-topic: it adds (1) a way for a proposal to
1396
+ * carry the claim it is cited for, (2) the `groundClaimInText` oracle, and (3) a
1397
+ * `ResearchDriver` that gates on grounding. It composes the existing
1398
+ * `ResearchDriver` / `ResearchSourceProposal` contracts and the shipped
1399
+ * `htmlToText`; it reinvents none of them.
1400
+ */
1401
+
1402
+ /**
1403
+ * Metadata key under which a proposal carries the specific claim it is cited
1404
+ * for. The worker sets `metadata[citedClaimKey] = '<the claim>'`; the
1405
+ * claim-grounding driver reads it and checks it against the fetched page text.
1406
+ */
1407
+ declare const citedClaimKey = "citedClaim";
1408
+ /** Read the cited claim a proposal carries, if any. */
1409
+ declare function citedClaimOf(source: ResearchSourceProposal): string | undefined;
1410
+ /** Attach a cited claim to a proposal (immutably returns a new proposal). */
1411
+ declare function withCitedClaim(source: ResearchSourceProposal, claim: string): ResearchSourceProposal;
1412
+ interface GroundingResult {
1413
+ /** True when the claim is sufficiently present in the page text. */
1414
+ grounded: boolean;
1415
+ /** How the claim matched (or why it didn't). For audit/notes. */
1416
+ mode: 'verbatim' | 'normalized' | 'overlap' | 'absent' | 'empty-claim' | 'empty-text';
1417
+ /**
1418
+ * Fraction of the claim's content words found in the page text. 1 for a
1419
+ * verbatim/normalized hit; the measured overlap otherwise.
1420
+ */
1421
+ overlap: number;
1422
+ /** Content words present in the claim but NOT in the page text. */
1423
+ missingWords: string[];
1634
1424
  }
1635
- interface RagAnswerEvalScenario extends Scenario {
1636
- kind: 'rag-answer-eval';
1637
- query: string;
1638
- referenceAnswer?: string;
1639
- expectedClaims?: readonly string[];
1640
- forbiddenClaims?: readonly string[];
1641
- requiredContext?: readonly RagRequiredContext[];
1642
- unanswerable?: boolean;
1643
- requireCitations?: boolean;
1644
- slices?: readonly RagEvalSlice[];
1645
- thresholds?: Partial<Record<RagEvalMetricKey, number>>;
1425
+ interface GroundClaimOptions {
1426
+ /**
1427
+ * Minimum fraction of the claim's content words that must appear in the page
1428
+ * text to count as a close paraphrase when there is no verbatim/normalized
1429
+ * hit. Default 0.7 — a high bar, because a misattribution is exactly a claim
1430
+ * whose specific words the page does not contain.
1431
+ */
1432
+ minOverlap?: number;
1433
+ /**
1434
+ * Content words shorter than this are ignored (drops "the", "of", "is", …)
1435
+ * and never count toward overlap. Default 3.
1436
+ */
1437
+ minWordLength?: number;
1646
1438
  }
1647
- interface ExternalRagEvalScore {
1648
- provider: RagEvalProvider | string;
1649
- scores: Record<string, number>;
1650
- reasons?: Record<string, string>;
1651
- metadata?: Record<string, JsonValue>;
1439
+ /**
1440
+ * THE ORACLE. Is `claim` grounded in `pageText` (the `htmlToText` output of the
1441
+ * page the worker fetched)? Deterministic, no model call:
1442
+ *
1443
+ * 1. verbatim — the claim string appears as-is (case-insensitive).
1444
+ * 2. normalized — the claim appears after collapsing punctuation/whitespace
1445
+ * on both sides (so "5.4x" vs "5.4 x", smart quotes, etc. still match).
1446
+ * 3. overlap — a close paraphrase: at least `minOverlap` of the claim's
1447
+ * substantive content words appear in the page text. A misattributed page
1448
+ * fails here because the SPECIFIC words the claim asserts are absent.
1449
+ *
1450
+ * Returns the match mode, the measured overlap, and the missing content words —
1451
+ * enough for the driver to give a precise rejection reason and for a test/doc to
1452
+ * audit WHY a claim grounded or didn't.
1453
+ */
1454
+ declare function groundClaimInText(claim: string, pageText: string, options?: GroundClaimOptions): GroundingResult;
1455
+ interface ClaimGroundingDriverOptions extends GroundClaimOptions {
1456
+ /**
1457
+ * Optional second verifier to compose AFTER grounding passes. When set, a
1458
+ * source must BOTH ground its claim AND pass this verifier (e.g. the LLM
1459
+ * relevance driver's `verifySource`). Lets the loop reject off-topic AND
1460
+ * misattributed sources in one driver. Omit for the pure, zero-inference
1461
+ * grounding gate.
1462
+ */
1463
+ relevanceVerifier?: (source: ResearchSourceProposal, ctx: SourceVerificationContext) => Promise<SourceVerdict> | SourceVerdict;
1464
+ /**
1465
+ * What to do when a proposal carries NO cited claim. `'reject'` (default) is
1466
+ * fail-closed: in claim-grounding mode every source must declare what it is
1467
+ * cited for, so an un-annotated source is treated as ungrounded. `'accept'`
1468
+ * lets un-annotated sources through to the relevance verifier (if any) —
1469
+ * useful when mixing annotated and legacy proposals.
1470
+ */
1471
+ onMissingClaim?: 'reject' | 'accept';
1652
1472
  }
1653
- interface RagAnswerEvalArtifact {
1654
- query: string;
1655
- answer: string;
1656
- contexts: readonly RagEvalContext[];
1657
- claims?: readonly RagEvalClaim[];
1658
- citations?: readonly RagEvalCitation[];
1659
- abstained?: boolean;
1660
- durationMs?: number;
1661
- costUsd?: number;
1662
- externalScores?: readonly ExternalRagEvalScore[];
1663
- metadata?: Record<string, JsonValue>;
1473
+ /**
1474
+ * A `ResearchDriver`-shaped verifier (just the `verifySource` arm) that gates on
1475
+ * CLAIM GROUNDING: it rejects a source whose cited claim is not present in its
1476
+ * fetched page text — a misattributed / fabricated citation — and (optionally)
1477
+ * composes a relevance verifier after grounding passes.
1478
+ *
1479
+ * The returned function matches `ResearchDriver['verifySource']`, so it drops
1480
+ * straight into `runVerifiedResearchLoop` as `{ verifySource: createClaimGroundingVerifier(...) }`.
1481
+ */
1482
+ declare function createClaimGroundingVerifier(options?: ClaimGroundingDriverOptions): (source: ResearchSourceProposal, ctx: SourceVerificationContext) => Promise<SourceVerdict>;
1483
+ interface WorkerClaimDecorationOptions {
1484
+ router?: RouterClient;
1485
+ router_options?: TangleRouterOptions;
1486
+ /** Max output tokens for the claim-extraction call. Default 1200 (glm floor). */
1487
+ maxTokens?: number;
1664
1488
  }
1665
- interface RagAnswerMetricSummary {
1666
- metrics: Record<RagEvalMetricKey, number>;
1667
- composite: number;
1668
- passed: boolean;
1669
- findings: readonly RagGapFinding[];
1670
- claimCount: number;
1671
- supportedClaimCount: number;
1672
- citedClaimCount: number;
1673
- supportedCitationCount: number;
1674
- matchedRequiredContextCount: number;
1675
- requiredContextCount: number;
1676
- providerScores: Record<string, Record<RagEvalMetricKey, number>>;
1489
+ /**
1490
+ * Ask an LLM to state, for one source, the single specific factual claim a
1491
+ * researcher would cite THIS page for toward the goal. Used to DECORATE the
1492
+ * sources a relevance-only worker produced with the claim a citation would make,
1493
+ * so the claim-grounding verifier has something executable to check. The model
1494
+ * is told to ground the claim in the provided excerpt; the verifier then checks
1495
+ * it against the FULL page text independently — the model does not get to mark
1496
+ * its own homework.
1497
+ *
1498
+ * Returns the proposal annotated via `withCitedClaim`, or the original proposal
1499
+ * unchanged if the model returns nothing parseable (the verifier's
1500
+ * `onMissingClaim` policy then decides).
1501
+ */
1502
+ declare function createClaimDecorator(options?: WorkerClaimDecorationOptions): (source: ResearchSourceProposal, goal: string) => Promise<ResearchSourceProposal>;
1503
+
1504
+ /**
1505
+ * The SINGLE-AGENT COLLECTION driver — the blind-collection baseline (Arm A).
1506
+ *
1507
+ * This is the honest null the depth A/B is measured against. The other drivers
1508
+ * spend extra inference to do something differentiated:
1509
+ * - `createVerifyingResearchDriver` runs an LLM gate per source (Arm B),
1510
+ * - `createResearchDrivingDriver` extracts claims, tracks corroboration, and
1511
+ * synthesizes deep follow-up questions to drive depth (Arm C).
1512
+ *
1513
+ * This driver does NONE of that. It is a pass-through: it accepts every source
1514
+ * the worker proposes and contributes no research, no gating, and no steering of
1515
+ * its own. The loop still dedups exact-uri duplicates before calling
1516
+ * `verifySource` (that is the loop's job, not the driver's), and the default
1517
+ * `foldGaps` (a plain bulleted list of the still-open readiness gaps) still folds
1518
+ * the gaps into the worker's next prompt — so the worker keeps researching, but
1519
+ * NOTHING intelligent sits between the worker and the knowledge base.
1520
+ *
1521
+ * In other words: ONE agent (the worker) collects sources round after round, and
1522
+ * the "driver" is an inert rubber stamp. That is exactly what "single-agent
1523
+ * collection" means — the topology with zero coordinator intelligence — so its
1524
+ * material-facts score is the floor every other arm must beat to justify its
1525
+ * extra inference cost.
1526
+ *
1527
+ * It adds NO router calls of its own: `verifySource` is a synchronous accept and
1528
+ * `foldGaps` is omitted so the loop uses its built-in gap list. So Arm A's cost
1529
+ * is the worker's cost alone — the cleanest possible blind-collection baseline.
1530
+ */
1531
+
1532
+ /**
1533
+ * Build the single-agent collection driver. Accepts every source; never gates,
1534
+ * never researches, never steers beyond the loop's default open-gap list. The
1535
+ * worker is the only agent that thinks.
1536
+ */
1537
+ declare function createCollectionResearchDriver(): ResearchDriver;
1538
+
1539
+ interface DiscoveryTask {
1540
+ id: string;
1541
+ goal: string;
1542
+ query?: string;
1543
+ sourceHints?: string[];
1544
+ metadata?: Record<string, unknown>;
1677
1545
  }
1678
- interface RagAnswerQualityJudgeOptions {
1679
- name?: string;
1680
- thresholds?: Partial<Record<RagEvalMetricKey, number>>;
1681
- weights?: Partial<Record<RagEvalMetricKey, number>>;
1682
- externalScorePolicy?: 'prefer-external' | 'deterministic-first';
1683
- minClaimSupport?: number;
1546
+ interface DiscoveryResult {
1547
+ taskId: string;
1548
+ summary: string;
1549
+ sourceUris?: string[];
1550
+ claims?: Array<{
1551
+ text: string;
1552
+ sourceUri?: string;
1553
+ confidence?: number;
1554
+ }>;
1555
+ followUpTasks?: DiscoveryTask[];
1556
+ metadata?: Record<string, unknown>;
1684
1557
  }
1685
- interface RagAnswerEvalCase {
1686
- scenario: RagAnswerEvalScenario;
1687
- artifact: RagAnswerEvalArtifact;
1558
+ interface KnowledgeDiscoveryWorker {
1559
+ run(task: DiscoveryTask, signal?: AbortSignal): Promise<DiscoveryResult> | DiscoveryResult;
1688
1560
  }
1689
- interface RagAnswerQualityHookOptions {
1690
- scenarios: readonly RagAnswerEvalScenario[];
1691
- run: (scenario: RagAnswerEvalScenario) => MaybePromise<RagAnswerEvalArtifact>;
1692
- externalEvaluator?: (item: RagAnswerEvalCase) => MaybePromise<ExternalRagEvalScore | readonly ExternalRagEvalScore[] | undefined>;
1693
- thresholds?: Partial<Record<RagEvalMetricKey, number>>;
1694
- weights?: Partial<Record<RagEvalMetricKey, number>>;
1561
+ interface KnowledgeDiscoveryDispatcher {
1562
+ dispatch(tasks: DiscoveryTask[], options?: {
1563
+ concurrency?: number;
1564
+ signal?: AbortSignal;
1565
+ }): Promise<DiscoveryResult[]>;
1695
1566
  }
1696
- interface RagCalibrationOptions {
1697
- scenario: RagAnswerEvalScenario;
1698
- strong: RagAnswerEvalArtifact;
1699
- weak: RagAnswerEvalArtifact;
1700
- judge?: JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario>;
1701
- minStrongScore?: number;
1702
- maxWeakScore?: number;
1703
- signal?: AbortSignal;
1567
+ type DiscoveryLoopStopReason = 'complete' | 'max-rounds' | 'max-tasks' | 'aborted';
1568
+ interface DiscoveryLoopRound {
1569
+ round: number;
1570
+ tasks: DiscoveryTask[];
1571
+ results: DiscoveryResult[];
1572
+ queuedFollowUps: DiscoveryTask[];
1704
1573
  }
1705
- interface RagCalibrationResult {
1706
- passed: boolean;
1707
- strongScore: number;
1708
- weakScore: number;
1709
- gap: number;
1574
+ interface DiscoveryLoopResult {
1575
+ stopReason: DiscoveryLoopStopReason;
1576
+ tasksDispatched: number;
1577
+ results: DiscoveryResult[];
1578
+ rounds: DiscoveryLoopRound[];
1579
+ /** Tasks retained, not dropped, when a configured limit stops the loop. */
1580
+ pendingTasks: DiscoveryTask[];
1581
+ /** Structurally identical task identities ignored to prevent cycles. */
1582
+ duplicateTaskIds: string[];
1710
1583
  }
1711
- interface KnowledgeBaseQualityOptions {
1712
- now?: Date;
1713
- strict?: boolean;
1714
- minCitationRate?: number;
1715
- maxStaleSourceRate?: number;
1584
+ interface RunDiscoveryLoopOptions {
1585
+ dispatcher: KnowledgeDiscoveryDispatcher;
1586
+ initialTasks: readonly DiscoveryTask[];
1587
+ /** Maximum follow-up depth including the initial dispatch. Default 3. */
1588
+ maxRounds?: number;
1589
+ /** Maximum tasks dispatched across all rounds. Default 24. */
1590
+ maxTasks?: number;
1591
+ /** Forwarded to the dispatcher. Default 4. */
1592
+ concurrency?: number;
1593
+ signal?: AbortSignal;
1594
+ onRound?: (round: DiscoveryLoopRound) => Promise<void> | void;
1716
1595
  }
1717
- interface KnowledgeBaseQualityReport {
1718
- ok: boolean;
1719
- metrics: {
1720
- page_count: number;
1721
- source_count: number;
1722
- citation_rate: number;
1723
- source_backed_page_rate: number;
1724
- stale_source_rate: number;
1725
- duplicate_source_hash_rate: number;
1726
- lint_error_count: number;
1727
- lint_warning_count: number;
1728
- };
1729
- findings: readonly RagGapFinding[];
1596
+ /**
1597
+ * Dispatch discovery tasks and recursively pursue worker-proposed follow-ups.
1598
+ *
1599
+ * The runner owns only bounded scheduling and accounting. Workers own search,
1600
+ * source verification, and domain-specific candidate shapes.
1601
+ */
1602
+ declare function runDiscoveryLoop(options: RunDiscoveryLoopOptions): Promise<DiscoveryLoopResult>;
1603
+ declare function createLocalDiscoveryDispatcher(worker: KnowledgeDiscoveryWorker): KnowledgeDiscoveryDispatcher;
1604
+
1605
+ interface KnowledgeEventQuery {
1606
+ type?: KnowledgeEventType;
1607
+ target?: string;
1608
+ limit?: number;
1730
1609
  }
1731
- type MaybePromise<T> = T | Promise<T>;
1732
- declare function ragAnswerQualityJudge(options?: RagAnswerQualityJudgeOptions): JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario>;
1733
- declare function scoreRagAnswerArtifact(artifact: RagAnswerEvalArtifact, scenario: RagAnswerEvalScenario, options?: RagAnswerQualityJudgeOptions): RagAnswerMetricSummary;
1734
- declare function diagnoseRagAnswerFailure(metrics: Record<RagEvalMetricKey, number>, scenario: RagAnswerEvalScenario, thresholds?: Partial<Record<RagEvalMetricKey, number>>): RagGapFinding[];
1735
- declare function createRagAnswerQualityHook(options: RagAnswerQualityHookOptions): () => Promise<RagAnswerQualityResult>;
1736
- declare function calibrateRagAnswerJudge(options: RagCalibrationOptions): Promise<RagCalibrationResult>;
1737
- declare function normalizeExternalRagScores(scores: readonly ExternalRagEvalScore[]): Record<string, Record<RagEvalMetricKey, number>>;
1738
- declare function toRagasEvaluationRows(cases: readonly RagAnswerEvalCase[]): {
1739
- user_input: string;
1740
- response: string;
1741
- retrieved_contexts: string[];
1742
- reference: string | undefined;
1743
- reference_contexts: string[];
1744
- }[];
1745
- declare function toDeepEvalTestCases(cases: readonly RagAnswerEvalCase[]): {
1746
- input: string;
1747
- actual_output: string;
1748
- expected_output: string | undefined;
1749
- retrieval_context: string[];
1750
- context: string[];
1751
- }[];
1752
- declare function toTruLensRecords(cases: readonly RagAnswerEvalCase[]): {
1753
- input: string;
1754
- output: string;
1755
- context: string;
1756
- }[];
1757
- declare function toRagCheckerRecords(cases: readonly RagAnswerEvalCase[]): {
1758
- query_id: string;
1759
- query: string;
1760
- gt_answer: string | undefined;
1761
- response: string;
1762
- retrieved_context: {
1763
- doc_id: string;
1764
- text: string;
1765
- }[];
1766
- claims: string[];
1767
- }[];
1768
- declare function scoreKnowledgeBaseIndex(index: KnowledgeIndex, options?: KnowledgeBaseQualityOptions): KnowledgeBaseQualityReport;
1610
+ declare function createKnowledgeEvent(input: {
1611
+ type: KnowledgeEventType;
1612
+ actor?: string;
1613
+ target?: string;
1614
+ metadata?: Record<string, unknown>;
1615
+ now?: () => Date;
1616
+ }): KnowledgeEvent;
1769
1617
 
1770
- type KnowledgeImprovementStatus = 'running' | 'candidate-ready' | 'promoted' | 'rejected' | 'blocked';
1771
- interface KnowledgeImprovementMetricProvenanceBase {
1772
- evaluator: string;
1773
- version: string;
1618
+ /**
1619
+ * Knowledge freshness store: tracks when each `(workspaceId, sourceId)` pair
1620
+ * was last successfully refreshed, and reports staleness against a TTL.
1621
+ *
1622
+ * The contract is intentionally minimal — just enough to drive a cron loop:
1623
+ *
1624
+ * ```ts
1625
+ * const store = createFileSystemFreshnessStore({ root: '.agent-knowledge' })
1626
+ * for (const source of sources) {
1627
+ * if (await store.stale({ workspaceId, sourceId: source.id, ttlMs: DAY })) {
1628
+ * const fragments = await source.fetch({ cacheDir })
1629
+ * await persistFragments(fragments)
1630
+ * await store.mark({ workspaceId, sourceId: source.id, when: new Date() })
1631
+ * }
1632
+ * }
1633
+ * ```
1634
+ *
1635
+ * Per-tenant isolation is enforced by `workspaceId` keying — there is no
1636
+ * global mutable state across workspaces.
1637
+ *
1638
+ * Two adapters ship in-package:
1639
+ *
1640
+ * - `createFileSystemFreshnessStore` — JSON file under the knowledge root,
1641
+ * mirrors the layout convention already used by `sources.json`.
1642
+ * - `createD1FreshnessStoreStub` — adapter scaffold for Cloudflare D1 /
1643
+ * Postgres. Production consumers should implement the `D1Adapter`
1644
+ * interface inside their own app; this stub exists to anchor the shape.
1645
+ *
1646
+ * @stable contract — interface is frozen at 0.x within this major.
1647
+ * @stable filesystem adapter
1648
+ * @experimental D1 stub — interface will evolve as real consumers wire it.
1649
+ */
1650
+ /** Identity for one freshness record. */
1651
+ interface FreshnessKey {
1652
+ workspaceId: string;
1653
+ sourceId: string;
1774
1654
  }
1775
- type KnowledgeImprovementMetricProvenance = (KnowledgeImprovementMetricProvenanceBase & {
1776
- method: 'deterministic';
1777
- }) | (KnowledgeImprovementMetricProvenanceBase & {
1778
- method: 'sampled' | 'composite';
1779
- corpusHash: string;
1780
- runRecords: RunRecord[];
1781
- }) | (KnowledgeImprovementMetricProvenanceBase & {
1782
- method: 'model';
1783
- model: string;
1784
- corpusHash: string;
1785
- runRecords: RunRecord[];
1786
- });
1787
- interface KnowledgeImprovementMetric {
1788
- score: number;
1789
- passed: boolean;
1790
- dimensions?: Record<string, number>;
1791
- notes?: string;
1792
- provenance: KnowledgeImprovementMetricProvenance;
1655
+ /** TTL bound for staleness checks. */
1656
+ interface FreshnessTtl extends FreshnessKey {
1657
+ /** Milliseconds — `Date.now() - last() > ttlMs` ⇒ stale. */
1658
+ ttlMs: number;
1659
+ /** Injected clock for deterministic tests; defaults to system time. */
1660
+ now?: Date;
1793
1661
  }
1794
- interface KnowledgeImprovementEvaluationInput {
1795
- runId: string;
1796
- iteration: number;
1797
- root: string;
1798
- baselineRoot: string;
1799
- candidateRoot: string;
1800
- baselineIndex: KnowledgeIndex;
1801
- candidateIndex: KnowledgeIndex;
1802
- baseHash: string;
1803
- candidateHash: string;
1804
- validation: ValidateKnowledgeResult;
1805
- readiness?: EvalKnowledgeBundleBuildResult;
1806
- kbQuality: KnowledgeBaseQualityReport;
1807
- lifecycle?: RunRagKnowledgeImprovementLoopResult;
1808
- signal?: AbortSignal;
1662
+ /** Mark argument. */
1663
+ interface FreshnessMark extends FreshnessKey {
1664
+ when: Date;
1665
+ /** Optional content hash captured at refresh time; aids debugging. */
1666
+ contentHash?: string;
1667
+ }
1668
+ interface KnowledgeFreshnessStore {
1669
+ /** Last refresh time, or null if never refreshed. */
1670
+ last(key: FreshnessKey): Promise<Date | null>;
1671
+ /** Record a successful refresh. */
1672
+ mark(input: FreshnessMark): Promise<void>;
1673
+ /** True iff `last(key)` is null or older than `ttlMs`. */
1674
+ stale(input: FreshnessTtl): Promise<boolean>;
1675
+ /** All records for a workspace — useful for dashboards / debugging. */
1676
+ list(workspaceId: string): Promise<FreshnessRecord[]>;
1809
1677
  }
1810
- type KnowledgeImprovementEvaluator = (input: KnowledgeImprovementEvaluationInput) => Promise<KnowledgeImprovementMetric> | KnowledgeImprovementMetric;
1811
- interface KnowledgeImprovementCandidateRecord {
1812
- iteration: number;
1813
- candidateId: string;
1814
- baseHash: string;
1815
- candidateHash?: string;
1816
- evidenceHash?: string;
1817
- promotionPlanHash?: string;
1818
- status: KnowledgeImprovementStatus;
1819
- createdAt: string;
1820
- updatedAt: string;
1678
+ interface FreshnessRecord {
1679
+ workspaceId: string;
1680
+ sourceId: string;
1681
+ lastRefreshedAt: string;
1682
+ contentHash?: string;
1821
1683
  }
1822
- interface KnowledgeImprovementRunState {
1823
- schemaVersion: 1;
1824
- runId: string;
1684
+ interface FileSystemFreshnessStoreOptions {
1685
+ /**
1686
+ * Knowledge root. The store writes to `<root>/.agent-knowledge/freshness.json`,
1687
+ * mirroring the convention used by `sources.json`.
1688
+ */
1825
1689
  root: string;
1826
- goal: string;
1827
- status: KnowledgeImprovementStatus;
1828
- baseHash: string;
1829
- createdAt: string;
1830
- updatedAt: string;
1831
- ownerId?: string;
1832
- candidates: KnowledgeImprovementCandidateRecord[];
1833
- promotedCandidateId?: string;
1834
- blockedReason?: string;
1835
1690
  }
1836
- interface KnowledgeImprovementResult {
1837
- runId: string;
1838
- state: KnowledgeImprovementRunState;
1839
- candidate?: KnowledgeImprovementCandidateRecord;
1840
- evaluation?: KnowledgeImprovementMetric;
1841
- lifecycle?: RunRagKnowledgeImprovementLoopResult;
1842
- promoted: boolean;
1843
- blocked: boolean;
1691
+ /**
1692
+ * Filesystem-backed implementation. Single JSON file per knowledge root,
1693
+ * indexed by `${workspaceId}::${sourceId}`. Reads parse on every call —
1694
+ * cron tick rate is well below the cost of one JSON parse.
1695
+ *
1696
+ * Writes share the package-wide filesystem lock, so multiple workers cannot
1697
+ * overwrite one another or run through an interrupted knowledge promotion.
1698
+ */
1699
+ declare function createFileSystemFreshnessStore(options: FileSystemFreshnessStoreOptions): KnowledgeFreshnessStore;
1700
+ /**
1701
+ * D1 / Postgres adapter scaffold. Production consumers implement
1702
+ * `D1Adapter` against their own driver (better-sqlite3, postgres,
1703
+ * Cloudflare D1 binding, ...). This factory wires the adapter to the
1704
+ * `KnowledgeFreshnessStore` interface.
1705
+ *
1706
+ * The expected schema:
1707
+ *
1708
+ * ```sql
1709
+ * CREATE TABLE knowledge_freshness (
1710
+ * workspace_id TEXT NOT NULL,
1711
+ * source_id TEXT NOT NULL,
1712
+ * last_refreshed_at TEXT NOT NULL,
1713
+ * content_hash TEXT,
1714
+ * PRIMARY KEY (workspace_id, source_id)
1715
+ * );
1716
+ * ```
1717
+ */
1718
+ interface D1Adapter {
1719
+ get(workspaceId: string, sourceId: string): Promise<FreshnessRecord | null>;
1720
+ upsert(record: FreshnessRecord): Promise<void>;
1721
+ listByWorkspace(workspaceId: string): Promise<FreshnessRecord[]>;
1844
1722
  }
1845
- declare const KnowledgeImprovementRunStateSchema: z.ZodObject<{
1846
- schemaVersion: z.ZodLiteral<1>;
1847
- runId: z.ZodString;
1848
- root: z.ZodString;
1849
- goal: z.ZodString;
1850
- status: z.ZodEnum<{
1851
- rejected: "rejected";
1852
- promoted: "promoted";
1853
- running: "running";
1854
- "candidate-ready": "candidate-ready";
1855
- blocked: "blocked";
1723
+ declare function createD1FreshnessStoreStub(adapter: D1Adapter): KnowledgeFreshnessStore;
1724
+
1725
+ interface ParsedFrontmatter {
1726
+ frontmatter: Record<string, unknown>;
1727
+ body: string;
1728
+ }
1729
+ declare function parseFrontmatter(content: string): ParsedFrontmatter;
1730
+ declare function formatFrontmatter(frontmatter: Record<string, unknown>, body: string): string;
1731
+
1732
+ declare function buildKnowledgeGraph(pages: KnowledgePage[]): KnowledgeGraph;
1733
+
1734
+ declare function sha256(text: string): string;
1735
+ declare function slugify(input: string): string;
1736
+ declare function stableId(prefix: string, content: string): string;
1737
+
1738
+ declare function buildKnowledgeIndex(root: string): Promise<KnowledgeIndex>;
1739
+ declare function writeKnowledgeIndex(root: string): Promise<KnowledgeIndex>;
1740
+
1741
+ interface KnowledgeInspection {
1742
+ pageCount: number;
1743
+ sourceCount: number;
1744
+ expiredSourceCount: number;
1745
+ staleSourceCount: number;
1746
+ edgeCount: number;
1747
+ findingCount: number;
1748
+ blockingFindingCount: number;
1749
+ topPages: Array<{
1750
+ path: string;
1751
+ title: string;
1752
+ degree: number;
1753
+ sources: number;
1856
1754
  }>;
1857
- baseHash: z.ZodString;
1858
- createdAt: z.ZodISODateTime;
1859
- updatedAt: z.ZodISODateTime;
1860
- ownerId: z.ZodOptional<z.ZodString>;
1861
- candidates: z.ZodArray<z.ZodObject<{
1862
- iteration: z.ZodNumber;
1863
- candidateId: z.ZodString;
1864
- baseHash: z.ZodString;
1865
- candidateHash: z.ZodOptional<z.ZodString>;
1866
- evidenceHash: z.ZodOptional<z.ZodString>;
1867
- promotionPlanHash: z.ZodOptional<z.ZodString>;
1868
- status: z.ZodEnum<{
1869
- rejected: "rejected";
1870
- promoted: "promoted";
1871
- running: "running";
1872
- "candidate-ready": "candidate-ready";
1873
- blocked: "blocked";
1874
- }>;
1875
- createdAt: z.ZodISODateTime;
1876
- updatedAt: z.ZodISODateTime;
1877
- }, z.core.$strict>>;
1878
- promotedCandidateId: z.ZodOptional<z.ZodString>;
1879
- blockedReason: z.ZodOptional<z.ZodString>;
1880
- }, z.core.$strict>;
1881
- declare const KnowledgeImprovementEvidenceSchema: z.ZodObject<{
1882
- schemaVersion: z.ZodLiteral<1>;
1883
- kind: z.ZodLiteral<"knowledge-improvement-evidence">;
1884
- runId: z.ZodString;
1885
- candidateId: z.ZodString;
1886
- iteration: z.ZodNumber;
1887
- goalHash: z.ZodString;
1888
- baseHash: z.ZodString;
1889
- candidateHash: z.ZodString;
1890
- promotionPlanHash: z.ZodString;
1891
- validation: z.ZodUnknown;
1892
- readiness: z.ZodNullable<z.ZodUnknown>;
1893
- kbQuality: z.ZodUnknown;
1894
- evaluation: z.ZodObject<{
1895
- score: z.ZodNumber;
1896
- passed: z.ZodBoolean;
1897
- dimensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
1898
- notes: z.ZodOptional<z.ZodString>;
1899
- provenance: z.ZodDiscriminatedUnion<[z.ZodObject<{
1900
- evaluator: z.ZodString;
1901
- version: z.ZodString;
1902
- method: z.ZodLiteral<"deterministic">;
1903
- }, z.core.$strict>, z.ZodObject<{
1904
- evaluator: z.ZodString;
1905
- version: z.ZodString;
1906
- method: z.ZodEnum<{
1907
- composite: "composite";
1908
- sampled: "sampled";
1909
- }>;
1910
- corpusHash: z.ZodString;
1911
- runRecords: z.ZodArray<z.ZodCustom<RunRecord, RunRecord>>;
1912
- }, z.core.$strict>, z.ZodObject<{
1913
- evaluator: z.ZodString;
1914
- version: z.ZodString;
1915
- method: z.ZodLiteral<"model">;
1916
- model: z.ZodString;
1917
- corpusHash: z.ZodString;
1918
- runRecords: z.ZodArray<z.ZodCustom<RunRecord, RunRecord>>;
1919
- }, z.core.$strict>], "method">;
1920
- }, z.core.$strict>;
1921
- lifecycle: z.ZodNullable<z.ZodUnknown>;
1922
- }, z.core.$strict>;
1923
- type KnowledgeImprovementEvidence = z.infer<typeof KnowledgeImprovementEvidenceSchema>;
1924
- /** Portable identity of one measured candidate. Paths and mutable run state are deliberately excluded. */
1925
- declare const KnowledgeImprovementCandidateRefSchema: z.ZodObject<{
1926
- schemaVersion: z.ZodLiteral<1>;
1927
- kind: z.ZodLiteral<"knowledge-improvement-candidate">;
1928
- runId: z.ZodString;
1929
- candidateId: z.ZodString;
1930
- goalHash: z.ZodString;
1931
- baseHash: z.ZodString;
1932
- candidateHash: z.ZodString;
1933
- evidenceHash: z.ZodString;
1934
- promotionPlanHash: z.ZodString;
1935
- }, z.core.$strict>;
1936
- type KnowledgeImprovementCandidateRef = z.infer<typeof KnowledgeImprovementCandidateRefSchema>;
1937
- interface PromoteKnowledgeCandidateOptions {
1938
- root: string;
1939
- candidate: KnowledgeImprovementCandidateRef;
1940
- ownerId?: string;
1941
- leaseTtlMs?: number;
1942
- now?: () => Date;
1943
- onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void;
1755
+ sourceFreshness: SourceFreshnessInspection[];
1756
+ findings: KnowledgeLintFinding[];
1944
1757
  }
1945
- interface UseKnowledgeImprovementCandidateOptions {
1946
- root: string;
1947
- candidate: KnowledgeImprovementCandidateRef;
1758
+ interface SourceFreshnessInspection {
1759
+ id: string;
1760
+ title?: string;
1761
+ uri: string;
1762
+ status: 'fresh' | 'expired' | 'unknown';
1763
+ validUntil?: string;
1764
+ lastVerifiedAt?: string;
1765
+ }
1766
+ declare function inspectKnowledgeIndex(index: KnowledgeIndex, options?: {
1767
+ now?: Date;
1768
+ }): KnowledgeInspection;
1769
+ interface KnowledgeExplanation {
1770
+ target: string;
1771
+ page?: KnowledgePage;
1772
+ sources: Array<{
1773
+ id: string;
1774
+ title?: string;
1775
+ uri: string;
1776
+ }>;
1777
+ links: string[];
1778
+ inbound: string[];
1779
+ related: Array<{
1780
+ path: string;
1781
+ title: string;
1782
+ score: number;
1783
+ }>;
1784
+ }
1785
+ declare function explainKnowledgeTarget(index: KnowledgeIndex, target: string): KnowledgeExplanation;
1786
+
1787
+ /**
1788
+ * HELD-OUT INVESTMENT-RESEARCH EVAL SET.
1789
+ *
1790
+ * The point of this file is the same FIREWALL the deep-question exam uses
1791
+ * (`tests/loops/held-out-exam.ts`): the material facts and their checkable
1792
+ * fragments are NEVER shown to a research loop. A loop is told only the company
1793
+ * + ticker + a research-as-of CUTOFF date, and asked to write an investment
1794
+ * thesis. AFTER it finishes, we grade the thesis it produced against THESE
1795
+ * facts — facts it never saw — so a high score is thesis QUALITY (it surfaced
1796
+ * the buried, material, non-obvious drivers) and not teaching-to-the-test.
1797
+ *
1798
+ * Each fact is a DEPTH fact by construction: a single ticker / company-name web
1799
+ * search does NOT surface it. They are the things buried in the filings or
1800
+ * knowable from then-available primary sources that a thorough analyst flags and
1801
+ * a one-shot search misses — customer/revenue/deposit concentration, a debt
1802
+ * maturity wall, a margin-trend reversal, a governance / related-party item, a
1803
+ * specific competitive or regulatory risk, an off-balance-sheet loss.
1804
+ *
1805
+ * THREE HARD RULES, enforced by how the data was gathered (see
1806
+ * docs/eval/investment-material-facts.md for the per-item provenance + the
1807
+ * curation-bias disclosure):
1808
+ *
1809
+ * 1. SPECIFIC + CHECKABLE. Each fact carries `expected` keyword groups — the
1810
+ * specific number / name / phrase — so a deterministic, model-free
1811
+ * substring grader (`gradeFactAgainstText`) can score "did the thesis
1812
+ * surface it". $0, reproducible, and it cannot leak the answer key into a
1813
+ * model the loop could observe.
1814
+ *
1815
+ * 2. DERIVED FROM REAL FETCHED EVIDENCE. Every fact records the primary source
1816
+ * it came from (`sourceUrl`, an SEC EDGAR 10-K) and the literal `evidence`
1817
+ * value read out of that document. Nothing here is invented; an item that
1818
+ * could not be independently sourced was DROPPED, not guessed (the drop log
1819
+ * is in the doc).
1820
+ *
1821
+ * 3. KNOWABLE AT THE CUTOFF. Every fact was disclosed in, or computable from, a
1822
+ * document available on or before the company's `cutoff` date. Post-cutoff
1823
+ * hindsight (the eventual bankruptcy / collapse) is NOT a checklist item —
1824
+ * it is recorded separately as `knownOutcome`, purely for the reader, and is
1825
+ * never graded.
1826
+ *
1827
+ * Grading mirrors the deep-question exam exactly: a fact is SURFACED when the
1828
+ * thesis text contains at least `minGroups` of its expected groups; a group is
1829
+ * satisfied when ANY of its `anyOf` fragments appears (case-insensitive
1830
+ * substring), so a faithful thesis phrased in its own words still grades as a
1831
+ * hit. `anyOf` groups model synonyms; the load-bearing tokens are the specific
1832
+ * numbers / names.
1833
+ */
1834
+ /** A required answer component: satisfied when any synonym fragment is present. */
1835
+ interface ExpectedGroup {
1836
+ /** Human label for the component (for the doc / audit). */
1837
+ label: string;
1838
+ /** Case-insensitive substring fragments; any one present satisfies the group. */
1839
+ anyOf: string[];
1948
1840
  }
1949
- interface ResolvedKnowledgeImprovementCandidate {
1950
- root: string;
1951
- candidate: KnowledgeImprovementCandidateRef;
1952
- evaluation: KnowledgeImprovementMetric;
1841
+ /** Lens the fact belongs to — so a set can be checked for category coverage. */
1842
+ type MaterialFactLens = 'concentration' | 'leverage' | 'margin-trend' | 'liquidity' | 'capital-return' | 'governance' | 'off-balance-sheet' | 'regulatory';
1843
+ /** One held-out material fact with a checkable expected answer + its provenance. */
1844
+ interface MaterialFact {
1845
+ /** Stable id, `ticker/fN`. */
1846
+ id: string;
1847
+ /** Which analyst lens this fact exercises. For coverage + the doc. */
1848
+ lens: MaterialFactLens;
1849
+ /**
1850
+ * The material fact, in plain words — for the doc/audit. NEVER shown to a loop.
1851
+ * This is the thing a thorough analyst would flag and a ticker search misses.
1852
+ */
1853
+ fact: string;
1854
+ /**
1855
+ * The checkable answer as required keyword GROUPS. The thesis text must contain
1856
+ * at least `minGroups` of these groups (default: all). A group is satisfied
1857
+ * when ANY of its `anyOf` fragments appears (case-insensitive substring).
1858
+ */
1859
+ expected: ExpectedGroup[];
1860
+ /**
1861
+ * Minimum number of `expected` groups the thesis must contain to count the
1862
+ * fact SURFACED. Default = all groups (the strict bar). Lowered (and documented
1863
+ * inline) only when the fact is genuinely satisfiable by a subset.
1864
+ */
1865
+ minGroups?: number;
1866
+ /**
1867
+ * PROVENANCE. The primary source URL this fact was read from — an SEC EDGAR
1868
+ * 10-K primary document, fetched live during curation.
1869
+ */
1870
+ sourceUrl: string;
1871
+ /**
1872
+ * The literal value / phrase read out of `sourceUrl` that grounds the fact.
1873
+ * This is the "cite the actual filing + the value" requirement — verbatim or
1874
+ * near-verbatim from the filing, with the figure.
1875
+ */
1876
+ evidence: string;
1953
1877
  }
1954
- interface KnowledgeImprovementRetrievalOptions extends Omit<RunRetrievalImprovementLoopOptions, 'index' | 'runDir'> {
1955
- runDir?: RunRetrievalImprovementLoopOptions['runDir'];
1878
+ /** A company + the cutoff a loop researches as-of + its held-out material facts. */
1879
+ interface CompanyEvalCase {
1880
+ /** Ticker as of the cutoff. */
1881
+ ticker: string;
1882
+ /** Legal name as of the cutoff (what the loop is told to research). */
1883
+ company: string;
1884
+ /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */
1885
+ cik: string;
1886
+ /**
1887
+ * Research-as-of date (ISO). The loop must reason as if it is this date; every
1888
+ * `evidence` value was knowable on or before it. >= 18 months before this set
1889
+ * was curated, so the outcome is known but is NOT a checklist item.
1890
+ */
1891
+ cutoff: string;
1892
+ /** Sector, for coverage / the curation-bias disclosure. */
1893
+ sector: string;
1894
+ /**
1895
+ * The known POST-cutoff outcome — recorded for the reader ONLY, never graded.
1896
+ * Keeping it out of `facts` is what makes the set hindsight-free.
1897
+ */
1898
+ knownOutcome: string;
1899
+ /** The held-out material facts for this company. */
1900
+ facts: MaterialFact[];
1956
1901
  }
1957
- interface KnowledgeImprovementUpdateInput extends RagKnowledgeUpdateInput {
1958
- runId: string;
1959
- iteration: number;
1960
- candidateId: string;
1961
- root: string;
1962
- baselineRoot: string;
1963
- candidateRoot: string;
1964
- baseHash: string;
1902
+ /**
1903
+ * The eval set. 5 public companies, 5-8 held-out material facts each, every fact
1904
+ * grounded in a primary SEC EDGAR 10-K filed on or before the cutoff.
1905
+ *
1906
+ * CURATION-BIAS DISCLOSURE (full version in the doc): all five are companies
1907
+ * whose buried risks later materialized, because that is where the material-vs-
1908
+ * surface distinction is sharpest AND where the figures are easy to verify after
1909
+ * the fact. This biases the set toward downside risks (two of the eight lenses,
1910
+ * concentration + leverage, dominate) and toward distressed names. A production
1911
+ * eval would balance these with companies whose buried facts were POSITIVE
1912
+ * drivers and with survivors. This set is honest about that and reports the lens
1913
+ * distribution so the bias is measurable, not hidden.
1914
+ */
1915
+ declare const investmentThesisSet: CompanyEvalCase[];
1916
+ /**
1917
+ * Grade ONE material fact against an investment thesis's full text. Returns
1918
+ * whether the thesis SURFACED it plus which expected groups were found. The
1919
+ * check is a deterministic case-insensitive substring scan — $0, model-free,
1920
+ * reproducible — so the eval never leaks into a model the loop could observe.
1921
+ */
1922
+ declare function gradeFactAgainstText(fact: MaterialFact, thesisText: string): {
1923
+ surfaced: boolean;
1924
+ groupsFound: number;
1925
+ groupsTotal: number;
1926
+ foundLabels: string[];
1927
+ };
1928
+ /** Grade a whole company's thesis text: how many of its held-out facts it surfaces. */
1929
+ declare function gradeCompanyAgainstText(company: CompanyEvalCase, thesisText: string): {
1930
+ surfaced: number;
1931
+ total: number;
1932
+ perFact: ReturnType<typeof gradeFactAgainstText>[];
1933
+ };
1934
+ /** Total held-out facts across the set (the denominator the doc reports). */
1935
+ declare function totalMaterialFacts(set?: CompanyEvalCase[]): number;
1936
+ /** Count facts per lens across the set — used to report (and bound) curation bias. */
1937
+ declare function lensDistribution(set?: CompanyEvalCase[]): Record<MaterialFactLens, number>;
1938
+
1939
+ /**
1940
+ * The INVESTMENT-THESIS research task.
1941
+ *
1942
+ * Given `{ company, ticker, cik, cutoff }`, drive the SAME two-agent research
1943
+ * loop the ML deep-question A/B uses (`runVerifiedResearchLoop` + the real web
1944
+ * worker) to research the company AS OF the cutoff — web + SEC EDGAR, both public
1945
+ * — and produce an investment-thesis PAGE in the knowledge base: a judgment, the
1946
+ * drivers, and the risks, grounded in what it fetched.
1947
+ *
1948
+ * This file builds NOTHING new for the loop: it composes the existing worker +
1949
+ * driver + loop, supplies the readiness specs that steer the worker toward the
1950
+ * filing-level evidence (the analyst lenses), then writes a synthesis thesis page
1951
+ * the metric (`materialFactsSurfaced`) grades against the HELD-OUT checklist.
1952
+ *
1953
+ * THE FIREWALL: the task is told ONLY company + ticker + cutoff (+ the generic
1954
+ * analyst-lens readiness specs every company gets). It is NEVER shown the
1955
+ * checklist. The checklist is read only afterward, by the metric. So a high score
1956
+ * is research depth, not teaching-to-the-test.
1957
+ */
1958
+
1959
+ /** The minimal brief a thesis run is given — the firewall boundary. */
1960
+ interface ThesisTaskInput {
1961
+ /** Legal name as of the cutoff — what the loop researches. */
1962
+ company: string;
1963
+ /** Ticker as of the cutoff. */
1964
+ ticker: string;
1965
+ /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */
1966
+ cik: string;
1967
+ /** Research-as-of date (ISO). The loop must reason as if it is this date. */
1968
+ cutoff: string;
1969
+ /** Sector, for the readiness query context (NOT a checklist hint). */
1970
+ sector?: string;
1965
1971
  }
1966
- type KnowledgeImprovementUpdate = (input: KnowledgeImprovementUpdateInput) => Promise<RagKnowledgeUpdateResult> | RagKnowledgeUpdateResult;
1967
- interface KnowledgeImprovementOptions {
1972
+ /**
1973
+ * The generic analyst-lens readiness specs every company gets. They are the ONLY
1974
+ * thing the loop is told about WHAT to look for, and they name the LENSES a
1975
+ * thorough analyst checks (balance-sheet risk, concentration, leverage, margins,
1976
+ * liquidity, governance, regulatory) and where they live (the latest SEC 10-K) —
1977
+ * NOT the answers. They steer the worker's web/EDGAR search toward the filing,
1978
+ * not toward the held-out facts (which the loop never sees).
1979
+ *
1980
+ * `minSources` is set above 1 so the readiness gate stays UNMET after a single
1981
+ * fetch and the loop runs multiple rounds — the depth-driving driver needs >1
1982
+ * round to steer, exactly as the ML-exam multi-round probe established.
1983
+ */
1984
+ declare function thesisReadinessSpecs(input: ThesisTaskInput): KnowledgeReadinessSpec[];
1985
+ interface ThesisRunOptions {
1986
+ /** The KB root the loop writes into. */
1968
1987
  root: string;
1969
- goal: string;
1970
- runId?: string;
1971
- ownerId?: string;
1972
- leaseTtlMs?: number;
1973
- resume?: boolean;
1974
- maxCandidates?: number;
1975
- candidateResearchIterations?: number;
1976
- strict?: ValidateKnowledgeOptions['strict'];
1977
- readinessSpecs?: KnowledgeReadinessSpec[];
1978
- readinessTaskId?: string;
1979
- readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>;
1980
- kbQuality?: KnowledgeBaseQualityOptions;
1981
- step?: RunKnowledgeResearchLoopOptions['step'];
1982
- knowledgeResearch?: Omit<RagKnowledgeResearchOptions, 'root'>;
1983
- retrieval?: KnowledgeImprovementRetrievalOptions;
1984
- diagnose?: NonNullable<RunRagKnowledgeImprovementLoopOptions['diagnose']>;
1985
- acquireKnowledge?: NonNullable<RunRagKnowledgeImprovementLoopOptions['acquireKnowledge']>;
1986
- updateKnowledge?: KnowledgeImprovementUpdate;
1987
- evaluateAnswers?: NonNullable<RunRagKnowledgeImprovementLoopOptions['evaluateAnswers']>;
1988
- decidePromotion?: NonNullable<RunRagKnowledgeImprovementLoopOptions['promote']>;
1989
- enabledPhases?: readonly RagKnowledgeImprovementPhase[];
1990
- requiredPhases?: readonly RagKnowledgeImprovementPhase[];
1991
- evaluate?: KnowledgeImprovementEvaluator;
1988
+ /** Shared router client (web search + chat). Defaults to env creds. */
1989
+ router: RouterClient;
1990
+ /** The driver — verify/dedup or research-driving. The loop's coordinator. */
1991
+ driver: ResearchDriver;
1992
+ /** Round budget. Default 3 (the depth-driving driver needs >1). */
1993
+ maxRounds?: number;
1994
+ /** Worker tuning forwarded to `createWebResearchWorker`. */
1995
+ workerOptions?: Omit<WebResearchWorkerOptions, 'router'>;
1996
+ /** Max tokens for the synthesis pass. Default 1600 (above glm-5.2's reasoning floor). */
1997
+ synthesisMaxTokens?: number;
1992
1998
  signal?: AbortSignal;
1993
- now?: () => Date;
1994
- onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void;
1995
1999
  }
1996
- declare function knowledgeImprovementRunId(root: string, goal: string): string;
1997
- declare function knowledgeImprovementRunDir(root: string, runId: string): string;
1998
- declare function loadKnowledgeImprovementState(root: string, runId: string): Promise<KnowledgeImprovementRunState | null>;
1999
- /** Freeze the exact knowledge bytes and measured evidence a later approval may promote. */
2000
- declare function knowledgeImprovementCandidateRef(result: Pick<KnowledgeImprovementResult, 'runId' | 'state' | 'candidate'>): KnowledgeImprovementCandidateRef;
2001
- /** Use one measured snapshot while its directory identity remains open and stable. */
2002
- declare function withKnowledgeImprovementCandidate<T>(options: UseKnowledgeImprovementCandidateOptions, use: (candidate: ResolvedKnowledgeImprovementCandidate) => Promise<T> | T): Promise<T>;
2003
- /** Promote one previously measured candidate without rerunning research or evaluation. */
2004
- declare function promoteKnowledgeCandidate(options: PromoteKnowledgeCandidateOptions): Promise<KnowledgeImprovementResult>;
2005
- declare function improveKnowledgeBase(options: KnowledgeImprovementOptions): Promise<KnowledgeImprovementResult>;
2006
- interface KnowledgeImprovementEvent extends Record<string, unknown> {
2007
- at: string;
2008
- type: string;
2000
+ interface ThesisRunResult {
2001
+ loop: VerifiedResearchLoopResult;
2002
+ /** The synthesized thesis text. */
2003
+ thesis: string;
2004
+ /** Path of the thesis page written into the KB. */
2005
+ thesisPath: string;
2009
2006
  }
2010
- declare function loadKnowledgeImprovementEvents(root: string, runId: string): Promise<KnowledgeImprovementEvent[]>;
2011
- declare function hashKnowledgeBase(root: string): Promise<string>;
2007
+ /**
2008
+ * Run the full thesis task: drive the two-agent loop to research the company AS
2009
+ * OF the cutoff, then synthesize + write the thesis page. Returns the loop result
2010
+ * + the thesis text + the page path. The caller grades the KB with
2011
+ * `materialFactsSurfaced(root, checklist)` — the checklist is never passed here.
2012
+ */
2013
+ declare function runInvestmentThesisTask(input: ThesisTaskInput, options: ThesisRunOptions): Promise<ThesisRunResult>;
2012
2014
 
2013
2015
  interface KbStore {
2014
2016
  putSource(source: SourceRecord): Promise<void>;
@@ -2662,4 +2664,4 @@ declare function normalizeLinkTarget(target: string): string;
2662
2664
  declare function isSafeKnowledgePath(path: string, allowedPrefixes?: string[]): boolean;
2663
2665
  declare function parseKnowledgeWriteBlocks(text: string, allowedPrefixes?: string[]): KnowledgeWriteParseResult;
2664
2666
 
2665
- export { type AdaptiveDecision, type AdaptiveDriverOptions, type AdaptiveResearchDriver, type AdaptiveStats, type AddSourceOptions, type AddSourceTextInput, type ApplyWriteBlocksResult, type BuildEvalKnowledgeBundleOptions, type ChunkingOptions, type ClaimGroundingDriverOptions, type CompanyEvalCase, type D1Adapter, type DedupReason, type DeepQuestion, type DeepQuestionKind, type DefineReadinessSpecInput, type DetectChangesOptions, type DetectChangesResult, type DiscoveryLoopResult, type DiscoveryLoopRound, type DiscoveryLoopStopReason, type DiscoveryResult, type DiscoveryTask, type DriverResearchContext, type EvalKnowledgeBundleBuildResult, type EvaluateKnowledgeBaseReadinessOptions, type ExpectedGroup, type ExternalRagEvalScore, type FactResult, type FileSystemFreshnessStoreOptions, FileSystemKbStore, type FreshnessKey, type FreshnessMark, type FreshnessRecord, type FreshnessTtl, type GroundClaimOptions, type GroundingResult, type KbStore, KnowledgeBaseCandidateSchema, type KnowledgeBaseQualityOptions, type KnowledgeBaseQualityReport, type KnowledgeBaseReadinessEvaluation, type KnowledgeChange, type KnowledgeChangeKind, type KnowledgeChunk, KnowledgeClaim, type KnowledgeControlLoopAction, type KnowledgeControlLoopActionResult, type KnowledgeControlLoopAdapter, type KnowledgeControlLoopAdapterOptions, type KnowledgeControlLoopState, type KnowledgeDiscoveryDispatcher, type KnowledgeDiscoveryWorker, KnowledgeEvent, type KnowledgeEventQuery, KnowledgeEventSchema, KnowledgeEventType, type KnowledgeExplanation, KnowledgeFragment, type KnowledgeFreshnessStore, type KnowledgeGap, KnowledgeGraph, KnowledgeGraphEdgeSchema, KnowledgeGraphNodeSchema, type KnowledgeImprovementCandidateRecord, type KnowledgeImprovementCandidateRef, KnowledgeImprovementCandidateRefSchema, type KnowledgeImprovementEvaluationInput, type KnowledgeImprovementEvaluator, type KnowledgeImprovementEvent, type KnowledgeImprovementEvidence, KnowledgeImprovementEvidenceSchema, type KnowledgeImprovementMetric, type KnowledgeImprovementMetricProvenance, type KnowledgeImprovementOptions, type KnowledgeImprovementResult, type KnowledgeImprovementRetrievalOptions, type KnowledgeImprovementRunState, KnowledgeImprovementRunStateSchema, type KnowledgeImprovementStatus, type KnowledgeImprovementUpdate, type KnowledgeImprovementUpdateInput, KnowledgeIndex, KnowledgeIndexSchema, type KnowledgeInspection, type KnowledgeLayout, KnowledgeLintFinding, KnowledgePage, KnowledgePageSchema, type KnowledgeProposal, KnowledgeProposalParseError, type KnowledgeReadinessSpec, KnowledgeRelease, type KnowledgeReleaseInput, type KnowledgeReleaseReport, type KnowledgeResearchLoopContext, type KnowledgeResearchLoopDecision, type KnowledgeResearchLoopResult, type KnowledgeResearchLoopStep, KnowledgeSearchResult, KnowledgeWriteBlock, KnowledgeWriteParseResult, type MaterialFact, type MaterialFactLens, type MaterialFactsResult, MemoryKbStore, type ParsedFrontmatter, type PendingKnowledgeMutation, type PromoteKnowledgeCandidateOptions, type ProposeFromFindingsResult, READINESS_SPEC_DEFAULTS, type RagAnswerEvalArtifact, type RagAnswerEvalCase, type RagAnswerEvalScenario, type RagAnswerMetricSummary, type RagAnswerQualityHookOptions, type RagAnswerQualityInput, type RagAnswerQualityJudgeOptions, type RagAnswerQualityResult, type RagCalibrationOptions, type RagCalibrationResult, type RagDiagnosisInput, type RagEvalCitation, type RagEvalClaim, type RagEvalContext, type RagEvalMetricKey, type RagEvalProvider, type RagEvalSlice, type RagGapFinding, type RagGapKind, type RagGapSeverity, type RagKnowledgeAcquisitionInput, type RagKnowledgeImprovementPhase, type RagKnowledgeImprovementPhaseResult, type RagKnowledgeImprovementPhaseStatus, type RagKnowledgeResearchOptions, type RagKnowledgeUpdateInput, type RagKnowledgeUpdateResult, type RagPhaseInputBase, type RagPromotionInput, type RagPromotionResult, type RagRequiredContext, type RecoverPendingKnowledgeMutationOptions, type RejectedSource, type ResearchContribution, type ResearchDriver, type ResearchDrivingDriver, type ResearchDrivingDriverOptions, type ResearchDrivingState, type ResearchDrivingSteer, type ResearchSourceProposal, type ResearchWorker, type ResolvedKnowledgeImprovementCandidate, type RouterClient, RouterError, type RouterUsage, type RunDiscoveryLoopOptions, type RunKnowledgeResearchLoopOptions, type RunRagKnowledgeImprovementLoopOptions, type RunRagKnowledgeImprovementLoopResult, RunRetrievalImprovementLoopOptions, RunRetrievalImprovementLoopResult, SCAFFOLD_PAGE_BASENAMES, type SourceAdapter, type SourceAdapterInput, type SourceAdapterOutput, SourceAnchorSchema, type SourceFreshnessInspection, SourceRecord, SourceRecordSchema, SourceRegistry, type SourceVerdict, type SourceVerificationContext, type TangleRouterOptions, type ThesisRunOptions, type ThesisRunResult, type ThesisTaskInput, type TrackedClaim, type TriageClass, type TwoAgentResearchLoopOptions, type TwoAgentResearchLoopResult, type TwoAgentResearchRound, type UseKnowledgeImprovementCandidateOptions, type ValidateKnowledgeOptions, type ValidateKnowledgeResult, type VerifiedResearchLoopOptions, type VerifiedResearchLoopResult, type VerifiedResearchRound, type VerifyingDriverOptions, WIKILINK_REGEX, type WebResearchWorkerOptions, type WebSearchHit, type WorkerClaimDecorationOptions, type WorkerResearchContext, addSourcePath, addSourceText, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, buildEvalKnowledgeBundle, buildKnowledgeGraph, buildKnowledgeIndex, calibrateRagAnswerJudge, canonicalizeUrl, chunkMarkdown, citedClaimKey, citedClaimOf, contentKey, createAdaptiveResearchDriver, createClaimDecorator, createClaimGroundingVerifier, createCollectionResearchDriver, createD1FreshnessStoreStub, createFileSystemFreshnessStore, createKnowledgeControlLoopAdapter, createKnowledgeEvent, createLocalDiscoveryDispatcher, createRagAnswerQualityHook, createResearchDrivingDriver, createTangleRouterClient, createVerifyingResearchDriver, createWebResearchWorker, defineReadinessSpec, detectChanges, diagnoseRagAnswerFailure, evaluateKnowledgeBaseReadiness, explainKnowledgeTarget, extractWikilinks, formatFrontmatter, gradeCompanyAgainstText, gradeFactAgainstText, groundClaimInText, hashKnowledgeBase, improveKnowledgeBase, initKnowledgeBase, inspectKnowledgeIndex, inspectPendingKnowledgeMutation, investmentThesisSet, isSafeKnowledgePath, isScaffoldPath, kbIndexToText, knowledgeImprovementCandidateRef, knowledgeImprovementRunDir, knowledgeImprovementRunId, knowledgeReleaseReport, layoutFor, lensDistribution, lintKnowledgeIndex, loadKnowledgeImprovementEvents, loadKnowledgeImprovementState, loadKnowledgePages, loadSourceRegistry, materialFactsSurfaced, materialFactsSurfacedInText, mediaTypeFor, normalizeExternalRagScores, normalizeLinkTarget, parseFrontmatter, parseKnowledgeWriteBlocks, promoteKnowledgeCandidate, proposeFromFinding, proposeFromFindings, ragAnswerQualityJudge, reciprocalRankFusion, recoverPendingKnowledgeMutation, runDiscoveryLoop, runInvestmentThesisTask, runKnowledgeResearchLoop, runRagKnowledgeImprovementLoop, runTwoAgentResearchLoop, runVerifiedResearchLoop, scoreKnowledgeBaseIndex, scoreRagAnswerArtifact, searchKnowledge, sha256, slugify, sourceMatchesGaps, sourceRegistryPath, stableId, stripFrontmatter, textSourceAdapter, thesisReadinessSpecs, toDeepEvalTestCases, toRagCheckerRecords, toRagasEvaluationRows, toTruLensRecords, tokenizeQuery, totalMaterialFacts, triageSource, validateKnowledgeIndex, withCitedClaim, withKnowledgeImprovementCandidate, writeJson, writeKnowledgeIndex, writeSourceRegistry };
2667
+ export { type AdaptiveDecision, type AdaptiveDriverOptions, type AdaptiveResearchDriver, type AdaptiveStats, type AddSourceOptions, type AddSourceTextInput, type ApplyWriteBlocksResult, type BuildEvalKnowledgeBundleOptions, type ChunkingOptions, type ClaimGroundingDriverOptions, type CompanyEvalCase, type D1Adapter, type DedupReason, type DeepQuestion, type DeepQuestionKind, type DefineReadinessSpecInput, type DetectChangesOptions, type DetectChangesResult, type DiscoveryLoopResult, type DiscoveryLoopRound, type DiscoveryLoopStopReason, type DiscoveryResult, type DiscoveryTask, type DriverResearchContext, type EvalKnowledgeBundleBuildResult, type EvaluateKnowledgeBaseReadinessOptions, type ExpectedGroup, type ExternalRagEvalScore, type FactResult, type FileSystemFreshnessStoreOptions, FileSystemKbStore, type FreshnessKey, type FreshnessMark, type FreshnessRecord, type FreshnessTtl, type GroundClaimOptions, type GroundingResult, type KbStore, KnowledgeBaseCandidateSchema, type KnowledgeBaseQualityOptions, type KnowledgeBaseQualityReport, type KnowledgeBaseReadinessEvaluation, type KnowledgeChange, type KnowledgeChangeKind, type KnowledgeChunk, KnowledgeClaim, type KnowledgeControlLoopAction, type KnowledgeControlLoopActionResult, type KnowledgeControlLoopAdapter, type KnowledgeControlLoopAdapterOptions, type KnowledgeControlLoopState, type KnowledgeDiscoveryDispatcher, type KnowledgeDiscoveryWorker, KnowledgeEvent, type KnowledgeEventQuery, KnowledgeEventSchema, KnowledgeEventType, type KnowledgeExplanation, KnowledgeFragment, type KnowledgeFreshnessStore, type KnowledgeGap, KnowledgeGraph, KnowledgeGraphEdgeSchema, KnowledgeGraphNodeSchema, type KnowledgeImprovementCandidateRecord, type KnowledgeImprovementCandidateRef, KnowledgeImprovementCandidateRefSchema, type KnowledgeImprovementEvaluationInput, type KnowledgeImprovementEvaluator, type KnowledgeImprovementEvent, type KnowledgeImprovementEvidence, KnowledgeImprovementEvidenceSchema, type KnowledgeImprovementMetric, type KnowledgeImprovementMetricProvenance, type KnowledgeImprovementOptions, type KnowledgeImprovementResult, type KnowledgeImprovementRetrievalOptions, type KnowledgeImprovementRunState, KnowledgeImprovementRunStateSchema, type KnowledgeImprovementStatus, type KnowledgeImprovementUpdate, type KnowledgeImprovementUpdateInput, KnowledgeIndex, KnowledgeIndexSchema, type KnowledgeInspection, type KnowledgeLayout, KnowledgeLintFinding, KnowledgePage, KnowledgePageSchema, type KnowledgeProposal, KnowledgeProposalParseError, type KnowledgeReadinessSpec, KnowledgeRelease, type KnowledgeReleaseInput, type KnowledgeReleaseReport, type KnowledgeResearchLoopContext, type KnowledgeResearchLoopDecision, type KnowledgeResearchLoopResult, type KnowledgeResearchLoopStep, KnowledgeSearchResult, KnowledgeWriteBlock, KnowledgeWriteParseResult, type MaterialFact, type MaterialFactLens, type MaterialFactsResult, MemoryKbStore, type ParsedFrontmatter, type PendingKnowledgeMutation, type PromoteKnowledgeCandidateOptions, type ProposeFromFindingsResult, READINESS_SPEC_DEFAULTS, type RagAnswerEvalArtifact, type RagAnswerEvalCase, type RagAnswerEvalScenario, type RagAnswerMetricSummary, type RagAnswerQualityHookOptions, type RagAnswerQualityInput, type RagAnswerQualityJudgeOptions, type RagAnswerQualityResult, type RagCalibrationOptions, type RagCalibrationResult, type RagDiagnosisInput, type RagEvalCitation, type RagEvalClaim, type RagEvalContext, type RagEvalMetricKey, type RagEvalProvider, type RagEvalSlice, type RagGapFinding, type RagGapKind, type RagGapSeverity, type RagKnowledgeAcquisitionInput, type RagKnowledgeImprovementPhase, type RagKnowledgeImprovementPhaseResult, type RagKnowledgeImprovementPhaseStatus, type RagKnowledgeResearchOptions, type RagKnowledgeUpdateInput, type RagKnowledgeUpdateResult, type RagPhaseInputBase, type RagPromotionInput, type RagPromotionResult, type RagRequiredContext, type RecoverPendingKnowledgeMutationOptions, type RejectedSource, type ResearchContribution, type ResearchDriver, type ResearchDrivingDriver, type ResearchDrivingDriverOptions, type ResearchDrivingState, type ResearchDrivingSteer, type ResearchSourceProposal, type ResearchWorker, type ResolvedKnowledgeImprovementCandidate, type RouterClient, RouterError, type RouterUsage, type RunDiscoveryLoopOptions, type RunKnowledgeResearchLoopOptions, type RunRagKnowledgeImprovementLoopOptions, type RunRagKnowledgeImprovementLoopResult, RunRetrievalImprovementLoopOptions, RunRetrievalImprovementLoopResult, SCAFFOLD_PAGE_BASENAMES, type SourceAdapter, type SourceAdapterInput, type SourceAdapterOutput, SourceAnchorSchema, type SourceFreshnessInspection, SourceRecord, SourceRecordSchema, SourceRegistry, type SourceVerdict, type SourceVerificationContext, type TangleRouterOptions, type ThesisRunOptions, type ThesisRunResult, type ThesisTaskInput, type TrackedClaim, type TriageClass, type TwoAgentResearchLoopOptions, type TwoAgentResearchLoopResult, type TwoAgentResearchRound, type UseKnowledgeImprovementCandidateOptions, type ValidateKnowledgeOptions, type ValidateKnowledgeResult, type VerifiedResearchLoopOptions, type VerifiedResearchLoopResult, type VerifiedResearchRound, type VerifyingDriverOptions, WIKILINK_REGEX, type WebResearchWorkerOptions, type WebSearchHit, type WorkerClaimDecorationOptions, type WorkerResearchContext, addSourcePath, addSourceText, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, buildEvalKnowledgeBundle, buildKnowledgeGraph, buildKnowledgeIndex, calibrateRagAnswerJudge, canonicalizeUrl, chunkMarkdown, citedClaimKey, citedClaimOf, contentKey, createAdaptiveResearchDriver, createClaimDecorator, createClaimGroundingVerifier, createCollectionResearchDriver, createD1FreshnessStoreStub, createFileSystemFreshnessStore, createKnowledgeControlLoopAdapter, createKnowledgeEvent, createLocalDiscoveryDispatcher, createRagAnswerQualityHook, createResearchDrivingDriver, createTangleRouterClient, createVerifyingResearchDriver, createWebResearchWorker, defineReadinessSpec, detectChanges, diagnoseRagAnswerFailure, evaluateKnowledgeBaseReadiness, explainKnowledgeTarget, extractWikilinks, formatFrontmatter, fromAgentCandidateKnowledgeRef, gradeCompanyAgainstText, gradeFactAgainstText, groundClaimInText, hashKnowledgeBase, improveKnowledgeBase, initKnowledgeBase, inspectKnowledgeIndex, inspectPendingKnowledgeMutation, investmentThesisSet, isSafeKnowledgePath, isScaffoldPath, kbIndexToText, knowledgeImprovementCandidateRef, knowledgeImprovementRunDir, knowledgeImprovementRunId, knowledgeReleaseReport, layoutFor, lensDistribution, lintKnowledgeIndex, loadKnowledgeImprovementEvents, loadKnowledgeImprovementState, loadKnowledgePages, loadSourceRegistry, materialFactsSurfaced, materialFactsSurfacedInText, mediaTypeFor, normalizeExternalRagScores, normalizeLinkTarget, parseFrontmatter, parseKnowledgeWriteBlocks, promoteKnowledgeCandidate, proposeFromFinding, proposeFromFindings, ragAnswerQualityJudge, reciprocalRankFusion, recoverPendingKnowledgeMutation, runDiscoveryLoop, runInvestmentThesisTask, runKnowledgeResearchLoop, runRagKnowledgeImprovementLoop, runTwoAgentResearchLoop, runVerifiedResearchLoop, scoreKnowledgeBaseIndex, scoreRagAnswerArtifact, searchKnowledge, sha256, slugify, sourceMatchesGaps, sourceRegistryPath, stableId, stripFrontmatter, textSourceAdapter, thesisReadinessSpecs, toAgentCandidateKnowledgeRef, toDeepEvalTestCases, toRagCheckerRecords, toRagasEvaluationRows, toTruLensRecords, tokenizeQuery, totalMaterialFacts, triageSource, validateKnowledgeIndex, withCitedClaim, withKnowledgeImprovementCandidate, writeJson, writeKnowledgeIndex, writeSourceRegistry };