@tangle-network/agent-knowledge 3.1.0 → 3.2.1

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/web-research-worker.ts","../src/adaptive-driver.ts","../src/agent-candidate.ts","../src/kb-improvement.ts","../src/claim-grounding.ts","../src/rag-eval.ts","../src/research-loop.ts","../src/events.ts","../src/eval-readiness.ts","../src/readiness-helpers.ts","../src/rag-improvement-loop.ts","../src/changes.ts","../src/chunking.ts","../src/collection-research-driver.ts","../src/discovery.ts","../src/freshness.ts","../src/investment-thesis-set.ts","../src/investment-thesis-task.ts","../src/material-facts-metric.ts","../src/two-agent-research-loop.ts","../src/kb-store.ts","../src/propose-from-finding.ts","../src/readiness-check.ts","../src/release.ts","../src/research-driving-driver.ts"],"sourcesContent":["/**\n * Real web-research worker + verifying driver for `runVerifiedResearchLoop`.\n *\n * This is the GENERAL, any-topic implementation behind the two-agent research\n * loop's live arm. Given the open knowledge gaps the readiness gate surfaces,\n * the worker:\n *\n * 1. asks an LLM (glm-5.2 by default) to turn each gap into focused web\n * search queries,\n * 2. runs a REAL web search over the Tangle router (`POST /v1/search` — the\n * same endpoint `tcloud mcp`'s `web_search` tool forwards to), so there is\n * no hardcoded corpus,\n * 3. fetches the top results with the repo's polite, cached `politeFetch` and\n * reduces each page to text with `htmlToText`,\n * 4. proposes the readable, verifiable pages as `ResearchSourceProposal`s plus\n * a `buildPages` that writes citing `knowledge/*.md` pages from the sources\n * the driver accepts.\n *\n * The verifying DRIVER is the differentiated role from the two-agent loop: a\n * second LLM pass that judges each fetched source's on-topic relevance to the\n * goal + open gaps and rejects off-topic / spam / already-covered material. The\n * worker ADDS; the driver GATES. Together they build a cleaner knowledge base\n * than a single agent at the same compute budget.\n *\n * Dependency-free on purpose: it talks to the router over `fetch` directly with\n * the published OpenAI-compatible chat shape and the `/v1/search` shape, so it\n * works whether or not the `tcloud` CLI is installed. Point it at any router by\n * passing `baseUrl`; supply the key via `apiKey` or `TANGLE_API_KEY`.\n */\n\nimport { htmlToText } from './sources/html'\nimport { politeFetch } from './sources/http'\nimport type {\n KnowledgeGap,\n ResearchContribution,\n ResearchDriver,\n ResearchSourceProposal,\n ResearchWorker,\n SourceVerdict,\n SourceVerificationContext,\n WorkerResearchContext,\n} from './two-agent-research-loop'\nimport type { SourceRecord } from './types'\n\n/** Default router model. Plain id (no namespace) — see CLAUDE/creds notes. */\nconst DEFAULT_MODEL = 'glm-5.2'\n/** Default router base. */\nconst DEFAULT_BASE_URL = 'https://router.tangle.tools/v1'\n/**\n * glm-5.2 spends its first tokens on hidden `reasoning_content`; below ~1200\n * output tokens it returns EMPTY visible content. Floor every call so a\n * reasoning model never silently yields nothing. (Verified creds note.)\n */\nconst MIN_MAX_TOKENS = 1200\n\n/** One live web result, as the router's `/v1/search` returns it. */\nexport interface WebSearchHit {\n title: string\n url: string\n snippet?: string\n}\n\n/**\n * The two router capabilities the worker/driver need. Injectable so tests can\n * stub the network; the default talks to the live Tangle router over `fetch`.\n */\nexport interface RouterClient {\n /** Live web search — returns title/url/snippet hits. */\n search(query: string, opts?: { maxResults?: number }): Promise<WebSearchHit[]>\n /** Chat completion — returns the assistant message's visible text. */\n chat(\n messages: { role: 'system' | 'user'; content: string }[],\n maxTokens?: number,\n ): Promise<string>\n /** Cumulative cost (chat + search) since this client was created. */\n usage(): RouterUsage\n}\n\n/**\n * Cumulative router cost — the per-arm signal the A/B reports ALONGSIDE quality,\n * so \"2.3 fewer sources\" can be read against the token/$/latency it cost. A\n * two-agent round is one worker pass plus N `verifySource` LLM calls; counting\n * each call here is what surfaces that the two-agent loop spends more inference\n * than its \"equal passes\" budget implies.\n */\nexport interface RouterUsage {\n chatCalls: number\n searchCalls: number\n promptTokens: number\n completionTokens: number\n usd: number\n wallMs: number\n}\n\nexport interface TangleRouterOptions {\n /** Router base URL. Defaults to `https://router.tangle.tools/v1`. */\n baseUrl?: string\n /** Bearer key. Defaults to `process.env.TANGLE_API_KEY`. */\n apiKey?: string\n /** Chat model id. Defaults to `glm-5.2`. */\n model?: string\n /** Optional preferred search provider (exa | you | perplexity | …). */\n searchProvider?: string\n /**\n * Retries on a TRANSIENT upstream status (502/503/504/429) with exponential\n * backoff. Default 4. A 4xx that isn't 429, and a 401, are NOT retried — those\n * are not transient. After the budget is exhausted the call still fails loud\n * with the original `RouterError`, so the fail-closed contract holds; this only\n * stops a single upstream-capacity blip from voiding a whole multi-topic run.\n */\n maxRetries?: number\n /** Base backoff in ms (doubled each retry, ±25% jitter). Default 1500. */\n retryBaseMs?: number\n signal?: AbortSignal\n}\n\n/** Transient upstream statuses worth a retry (capacity / rate-limit / gateway). */\nconst transientStatuses = new Set([429, 502, 503, 504])\n\n/**\n * POST with bounded exponential backoff on transient upstream statuses. Returns\n * the first `res.ok` response, or the LAST response (so the caller throws the\n * real status). A non-transient failure returns immediately — only 502/503/504/\n * 429 are retried. Aborts propagate at once.\n */\nasync function fetchWithRetry(\n url: string,\n init: RequestInit,\n opts: { maxRetries: number; retryBaseMs: number; signal?: AbortSignal },\n): Promise<Response> {\n let lastRes: Response | undefined\n for (let attempt = 0; attempt <= opts.maxRetries; attempt += 1) {\n if (opts.signal?.aborted) throw new RouterError(0, 'aborted')\n const res = await fetch(url, init)\n if (res.ok || !transientStatuses.has(res.status)) return res\n lastRes = res\n if (attempt === opts.maxRetries) break\n // Drain the body so the socket frees before we wait.\n await res.text().catch(() => '')\n const backoff = opts.retryBaseMs * 2 ** attempt\n const jitter = backoff * (0.75 + Math.random() * 0.5)\n await new Promise((resolve) => setTimeout(resolve, jitter))\n }\n // Exhausted: hand back the last transient response so the caller fails loud\n // with its real status.\n if (lastRes) return lastRes\n throw new RouterError(0, 'fetchWithRetry produced no response')\n}\n\n/** A small error so a failed router call fails loud rather than returning junk. */\nexport class RouterError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(`router ${status}: ${message}`)\n this.name = 'RouterError'\n }\n}\n\n/**\n * Build a dependency-free Tangle router client over `fetch`. This is the same\n * wire surface the `tcloud` SDK + `tcloud mcp` use (`/v1/search` for web search,\n * `/v1/chat/completions` for chat) so it needs no CLI installed.\n */\nexport function createTangleRouterClient(options: TangleRouterOptions = {}): RouterClient {\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const apiKey = options.apiKey ?? process.env.TANGLE_API_KEY\n if (!apiKey) {\n throw new RouterError(401, 'no TANGLE_API_KEY (pass apiKey or set the env var)')\n }\n const model = options.model ?? DEFAULT_MODEL\n const maxRetries = Math.max(0, options.maxRetries ?? 4)\n const retryBaseMs = Math.max(1, options.retryBaseMs ?? 1500)\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n }\n\n // glm-5.2 pricing (USD per token) + a cumulative accumulator. Read via usage().\n const price = { prompt: 0.95 / 1_000_000, completion: 3.0 / 1_000_000 }\n const acc: RouterUsage = {\n chatCalls: 0,\n searchCalls: 0,\n promptTokens: 0,\n completionTokens: 0,\n usd: 0,\n wallMs: 0,\n }\n\n return {\n async search(query, opts) {\n const t0 = Date.now()\n const res = await fetchWithRetry(\n `${baseUrl}/search`,\n {\n method: 'POST',\n headers,\n signal: options.signal,\n body: JSON.stringify({\n query,\n ...(options.searchProvider ? { provider: options.searchProvider } : {}),\n ...(opts?.maxResults != null ? { maxResults: opts.maxResults } : {}),\n }),\n },\n { maxRetries, retryBaseMs, signal: options.signal },\n )\n acc.searchCalls += 1\n acc.wallMs += Date.now() - t0\n if (!res.ok) {\n throw new RouterError(res.status, await res.text().catch(() => res.statusText))\n }\n const body = (await res.json()) as { data?: WebSearchHit[] }\n return (body.data ?? [])\n .filter((hit) => typeof hit?.url === 'string' && hit.url.length > 0)\n .map((hit) => ({ title: hit.title ?? hit.url, url: hit.url, snippet: hit.snippet }))\n },\n async chat(messages, maxTokens) {\n // Reasoning-model floor: never let glm-5.2 spend the whole budget on\n // hidden reasoning and return empty visible content.\n const max_tokens = Math.max(MIN_MAX_TOKENS, maxTokens ?? MIN_MAX_TOKENS)\n const t0 = Date.now()\n const res = await fetchWithRetry(\n `${baseUrl}/chat/completions`,\n {\n method: 'POST',\n headers,\n signal: options.signal,\n body: JSON.stringify({ model, messages, max_tokens, temperature: 0.2, stream: false }),\n },\n { maxRetries, retryBaseMs, signal: options.signal },\n )\n if (!res.ok) {\n throw new RouterError(res.status, await res.text().catch(() => res.statusText))\n }\n const body = (await res.json()) as {\n choices?: { message?: { content?: string } }[]\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const promptTokens = body.usage?.prompt_tokens ?? 0\n const completionTokens = body.usage?.completion_tokens ?? 0\n acc.chatCalls += 1\n acc.promptTokens += promptTokens\n acc.completionTokens += completionTokens\n acc.usd += promptTokens * price.prompt + completionTokens * price.completion\n acc.wallMs += Date.now() - t0\n return body.choices?.[0]?.message?.content ?? ''\n },\n usage() {\n return { ...acc }\n },\n }\n}\n\nexport interface WebResearchWorkerOptions {\n /** Router client. Defaults to a live Tangle router client from env creds. */\n router?: RouterClient\n router_options?: TangleRouterOptions\n /** Max search queries the LLM may form per gap. Default 2. */\n queriesPerGap?: number\n /** Max web results fetched per query. Default 3. */\n resultsPerQuery?: number\n /** Hard cap on sources proposed per round (across all gaps). Default 6. */\n maxSourcesPerRound?: number\n /** Disk cache dir for `politeFetch`. Optional; speeds repeat runs. */\n cacheDir?: string\n /** Minimum readable text length to keep a fetched page. Default 200. */\n minTextChars?: number\n /** Max chars of page text stored per source (keeps pages bounded). Default 4000. */\n maxTextChars?: number\n}\n\n/** Resolve the router client lazily so a worker with an injected client never reads env. */\nfunction resolveRouter(opts: {\n router?: RouterClient\n router_options?: TangleRouterOptions\n}): RouterClient {\n return opts.router ?? createTangleRouterClient(opts.router_options)\n}\n\n/**\n * The real web-research worker. Conforms to the loop's `ResearchWorker`\n * contract: given the open gaps, it returns the sources it found plus a\n * `buildPages` that emits citing pages from the sources the driver accepted.\n */\nexport function createWebResearchWorker(options: WebResearchWorkerOptions = {}): ResearchWorker {\n const queriesPerGap = Math.max(1, options.queriesPerGap ?? 2)\n const resultsPerQuery = Math.max(1, options.resultsPerQuery ?? 3)\n const maxSourcesPerRound = Math.max(1, options.maxSourcesPerRound ?? 6)\n const minTextChars = Math.max(1, options.minTextChars ?? 200)\n const maxTextChars = Math.max(minTextChars, options.maxTextChars ?? 4000)\n\n return async (ctx: WorkerResearchContext): Promise<ResearchContribution> => {\n const router = resolveRouter(options)\n // Target the BLOCKING gaps first; fall back to all gaps if none are blocking.\n const targetGaps = ctx.gaps.filter((gap) => gap.blocking)\n const gaps = targetGaps.length > 0 ? targetGaps : ctx.gaps\n if (gaps.length === 0) {\n return { sources: [], notes: 'no open gaps to research' }\n }\n\n const queries = await formSearchQueries(router, ctx, gaps, queriesPerGap)\n const proposals: ResearchSourceProposal[] = []\n const seenUris = new Set<string>()\n\n for (const query of queries) {\n if (proposals.length >= maxSourcesPerRound) break\n if (ctx.signal?.aborted) break\n let hits: WebSearchHit[]\n try {\n hits = await router.search(query, { maxResults: resultsPerQuery })\n } catch (error) {\n // A single failed query must not sink the round — record nothing, move on.\n if ((error as { name?: string }).name === 'AbortError') break\n continue\n }\n for (const hit of hits) {\n if (proposals.length >= maxSourcesPerRound) break\n if (seenUris.has(hit.url)) continue\n const fetched = await politeFetch(hit.url, {\n signal: ctx.signal,\n cacheDir: options.cacheDir,\n })\n if (!fetched.verifiable) continue\n const text = htmlToText(fetched.body).slice(0, maxTextChars)\n if (text.length < minTextChars) continue\n seenUris.add(hit.url)\n proposals.push({\n uri: hit.url,\n title: hit.title || hit.url,\n text,\n // We just fetched + verified this page, so stamp `lastVerifiedAt` with\n // fetch time. Do NOT set `validUntil`: a live page has no inherent\n // future expiry, and the readiness freshness check treats any\n // `validUntil <= now` as EXPIRED (score 0). The page's `Last-Modified`\n // is a PAST date, so writing it here would mark every real source stale\n // and zero out coverage. Record it as provenance metadata instead.\n lastVerifiedAt: fetched.fetchedAt,\n metadata: {\n discoveredVia: query,\n snippet: hit.snippet ?? '',\n goal: ctx.goal,\n sourceUpdatedAt: fetched.sourceUpdatedAt,\n },\n })\n }\n }\n\n return {\n sources: proposals,\n buildPages: buildCitingPages(proposals),\n notes: `web-research worker: ${queries.length} queries → ${proposals.length} fetched sources`,\n }\n }\n}\n\n/**\n * Ask the LLM to turn the open gaps into focused web search queries. Falls back\n * to the gap's own readiness query if the model returns nothing parseable, so a\n * model hiccup degrades to a sane search rather than an empty round.\n */\nasync function formSearchQueries(\n router: RouterClient,\n ctx: WorkerResearchContext,\n gaps: KnowledgeGap[],\n queriesPerGap: number,\n): Promise<string[]> {\n const gapLines = gaps\n .map((gap, i) => `${i + 1}. ${gap.description} (readiness query: \"${gap.query}\")`)\n .join('\\n')\n const want = gaps.length * queriesPerGap\n const system =\n 'You are a research librarian. Turn knowledge gaps into precise web search queries that will ' +\n 'surface authoritative primary sources (papers, docs, standards, official pages). ' +\n 'Return ONLY a JSON array of query strings, no prose.'\n const user = [\n `Research goal: ${ctx.goal}`,\n ctx.steer ? `Steer from the coordinator:\\n${ctx.steer}` : '',\n `Open knowledge gaps:\\n${gapLines}`,\n `Return up to ${want} search query strings as a JSON array (e.g. [\"query one\",\"query two\"]).`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n MIN_MAX_TOKENS,\n )\n } catch {\n raw = ''\n }\n const parsed = parseQueryList(raw)\n const fromLlm = parsed.slice(0, want)\n if (fromLlm.length > 0) return dedupeStrings(fromLlm)\n // Degrade to the readiness queries themselves — still a real search.\n return dedupeStrings(gaps.map((gap) => gap.query || gap.description))\n}\n\n/** Parse a JSON array of query strings, tolerant of code fences / surrounding prose. */\nfunction parseQueryList(raw: string): string[] {\n const text = raw.trim()\n if (!text) return []\n const candidates: string[] = []\n // Prefer a fenced or bare JSON array.\n const arrayMatch = text.match(/\\[[\\s\\S]*\\]/)\n if (arrayMatch) {\n try {\n const arr = JSON.parse(arrayMatch[0]) as unknown[]\n for (const item of arr)\n if (typeof item === 'string' && item.trim()) candidates.push(item.trim())\n } catch {\n /* fall through to line parsing */\n }\n }\n if (candidates.length === 0) {\n for (const line of text.split('\\n')) {\n const cleaned = line\n .replace(/^\\s*(?:[-*]|\\d+[.)])\\s*/, '')\n .replace(/^[\"']|[\"']$/g, '')\n .trim()\n if (cleaned && cleaned.length > 2 && !cleaned.startsWith('{')) candidates.push(cleaned)\n }\n }\n return candidates\n}\n\nfunction dedupeStrings(values: string[]): string[] {\n const seen = new Set<string>()\n const out: string[] = []\n for (const value of values) {\n const key = value.toLowerCase().trim()\n if (key && !seen.has(key)) {\n seen.add(key)\n out.push(value.trim())\n }\n }\n return out\n}\n\n/**\n * Build the curated `knowledge/*.md` pages from the sources the driver accepted.\n * Each page cites the registered source by its assigned `record.id` (matched back\n * to the proposal via `metadata.originalUri`, which `addSourceText` stashes).\n */\nfunction buildCitingPages(\n proposals: ResearchSourceProposal[],\n): (acceptedSources: SourceRecord[]) => string | undefined {\n return (acceptedSources) => {\n if (acceptedSources.length === 0) return undefined\n const blocks = acceptedSources.map((record) => {\n const proposal = proposals.find((p) => p.uri === record.metadata?.originalUri)\n const uri = proposal?.uri ?? record.id\n const slug =\n uri\n .replace(/^https?:\\/\\//, '')\n .replace(/[^a-z0-9]+/gi, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 120) || record.id\n const title = proposal?.title ?? record.id\n const body = proposal?.text ?? ''\n return [\n `---FILE: knowledge/${slug}.md---`,\n '---',\n `title: ${escapeYaml(title)}`,\n `sources: [\"${record.id}\"]`,\n `source_url: ${uri}`,\n '---',\n `# ${title}`,\n '',\n body,\n '',\n `Source: ${uri}`,\n '---END FILE---',\n ].join('\\n')\n })\n return blocks.join('\\n')\n }\n}\n\nfunction escapeYaml(value: string): string {\n // Keep the frontmatter line single-valued and safe: collapse newlines, strip\n // quotes that would break the scalar.\n return value\n .replace(/[\\r\\n]+/g, ' ')\n .replace(/\"/g, \"'\")\n .trim()\n}\n\nexport interface VerifyingDriverOptions {\n router?: RouterClient\n router_options?: TangleRouterOptions\n /**\n * When the LLM verdict can't be parsed, default to REJECT (fail-closed) so a\n * model hiccup never poisons the KB with an unverified source. Set `true` to\n * accept-on-parse-failure only if you have a reason to. Default false.\n */\n acceptOnParseFailure?: boolean\n}\n\n/**\n * The verifying driver: a real LLM pass that judges each candidate source's\n * on-topic relevance to the goal + open gaps and whether it duplicates material\n * already accepted this round. This is the differentiated coordinator role — it\n * GATES the worker's additions; it adds nothing itself.\n *\n * The loop already dedups exact-uri duplicates and only calls this on genuinely\n * new candidates, so the verifier focuses on relevance + near-duplicate\n * judgement, not bookkeeping.\n */\nexport function createVerifyingResearchDriver(\n options: VerifyingDriverOptions = {},\n): ResearchDriver {\n const acceptOnParseFailure = options.acceptOnParseFailure ?? false\n return {\n async verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> {\n const router = resolveRouter(options)\n const gapLines = ctx.gaps\n .map((gap) => `- ${gap.description} (query: \"${gap.query}\")`)\n .join('\\n')\n const acceptedTitles = ctx.acceptedThisRound\n .map((accepted) => `- ${accepted.title ?? accepted.uri}`)\n .join('\\n')\n const excerpt = source.text.slice(0, 1500)\n const system =\n 'You verify whether a fetched web source belongs in a curated knowledge base. ' +\n 'Accept a source ONLY if it is genuinely on-topic for the research goal and helps close ' +\n 'one of the open gaps, AND it is not a near-duplicate of an already-accepted source. ' +\n 'Reject spam, listicles, off-topic pages, marketing, and near-duplicates. ' +\n 'Respond with ONLY a JSON object: {\"accept\": true|false, \"reason\": \"<short reason>\"}.'\n const user = [\n `Research goal: ${ctx.goal}`,\n `Open gaps:\\n${gapLines || '(none specified)'}`,\n acceptedTitles\n ? `Already accepted this round:\\n${acceptedTitles}`\n : 'Nothing accepted yet this round.',\n `Candidate source:\\nURL: ${source.uri}\\nTitle: ${source.title ?? '(none)'}\\nExcerpt:\\n${excerpt}`,\n 'Verdict as JSON {\"accept\": boolean, \"reason\": string}:',\n ].join('\\n\\n')\n\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n MIN_MAX_TOKENS,\n )\n } catch (error) {\n if ((error as { name?: string }).name === 'AbortError') throw error\n // Router failure: fail-closed (reject) so an unverified source can't slip in.\n return acceptOnParseFailure\n ? { accept: true }\n : { accept: false, reason: `verifier unavailable: ${(error as Error).message}` }\n }\n\n const verdict = parseVerdict(raw)\n if (verdict) return verdict\n return acceptOnParseFailure\n ? { accept: true }\n : { accept: false, reason: 'verifier returned an unparseable verdict' }\n },\n }\n}\n\n/** Parse the verifier's `{accept, reason}` JSON, tolerant of fences / prose. */\nfunction parseVerdict(raw: string): SourceVerdict | null {\n const text = raw.trim()\n if (!text) return null\n const objMatch = text.match(/\\{[\\s\\S]*\\}/)\n if (!objMatch) return null\n try {\n const parsed = JSON.parse(objMatch[0]) as { accept?: unknown; reason?: unknown }\n if (typeof parsed.accept !== 'boolean') return null\n if (parsed.accept) return { accept: true }\n return {\n accept: false,\n reason:\n typeof parsed.reason === 'string' && parsed.reason.trim()\n ? parsed.reason.trim()\n : 'rejected by verifier',\n }\n } catch {\n return null\n }\n}\n","/**\n * Adaptive verifier mode for `runVerifiedResearchLoop`.\n *\n * The cost/quality A/B (`docs/results/cost-quality.md`) found the LLM relevance\n * verifier's cleanliness win is dominated by DE-DUPLICATION — which a\n * deterministic content-hash / canonical-URL check captures at ~none of the LLM\n * premium — and that an LLM check only earns its dollar on the off-scope tail.\n * The honest production move it names is: do the cheap deterministic work first,\n * spend the LLM only where it pays. This module is that driver.\n *\n * Per candidate source the adaptive driver runs THREE stages, cheapest first,\n * and stops at the first that decides:\n *\n * 1. DEDUP ($0, no LLM). Reject a source whose CONTENT (normalized-text hash)\n * or whose CANONICAL URL matches one already accepted this round or already\n * in the knowledge base. This is the de-dup the relevance judge was being\n * paid to do; doing it deterministically is free and exact.\n *\n * 2. HEURISTIC TRIAGE ($0, no LLM). For a unique survivor, a cheap host /\n * title / length signal classifies it as clearly-keep, clearly-drop, or\n * AMBIGUOUS. Clear cases are resolved without a model: an authoritative host\n * (arxiv, *.edu, *.gov, official docs) with a substantial readable body is\n * kept; an obvious spam/listicle/marketing title or a too-thin body is\n * dropped. Only genuinely ambiguous survivors fall through.\n *\n * 3. LLM ESCALATION ($, one call). ONLY the ambiguous survivors reach the LLM\n * `verifySource` — the shipped `createVerifyingResearchDriver` relevance\n * judge. This is where the verifier earns its premium: the off-scope tail a\n * cheap rule can't adjudicate.\n *\n * The result is the cost/quality frontier point the doc predicted: most of the\n * cleanliness (dedup + clear drops) at a fraction of the LLM $/calls (only the\n * ambiguous tail pays). It is a real `ResearchDriver` — same contract the\n * two-agent loop already gates on — and reuses `sha256`, the relevance verifier,\n * and the index; it reinvents none of them.\n */\n\nimport { sha256 } from './ids'\nimport type {\n ResearchSourceProposal,\n SourceVerdict,\n SourceVerificationContext,\n} from './two-agent-research-loop'\nimport {\n createVerifyingResearchDriver,\n type RouterClient,\n type TangleRouterOptions,\n type VerifyingDriverOptions,\n} from './web-research-worker'\n\n/**\n * Canonicalize a URL for duplicate detection: lowercase host, strip a leading\n * `www.`, drop the scheme, the fragment, a trailing slash, and tracking query\n * params (`utm_*`, `ref`, `fbclid`, `gclid`, …). Two URLs that differ only by\n * those decorations canonicalize to the same key, so the dedup stage treats them\n * as the same source. Falls back to the lowercased raw string when the input is\n * not a parseable absolute URL (so non-http identifiers still dedup by equality).\n */\nexport function canonicalizeUrl(uri: string): string {\n const trimmed = uri.trim()\n try {\n const url = new URL(trimmed)\n const host = url.hostname.toLowerCase().replace(/^www\\./, '')\n // Keep only non-tracking query params, sorted for stable ordering.\n const kept: [string, string][] = []\n for (const [key, value] of url.searchParams) {\n const lower = key.toLowerCase()\n if (lower.startsWith('utm_')) continue\n if (trackingParams.has(lower)) continue\n kept.push([key, value])\n }\n kept.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n const query = kept.map(([k, v]) => `${k}=${v}`).join('&')\n const path = url.pathname.replace(/\\/+$/, '') || '/'\n return `${host}${path}${query ? `?${query}` : ''}`\n } catch {\n return trimmed.toLowerCase()\n }\n}\n\n/** Tracking / referrer query params dropped during URL canonicalization. */\nconst trackingParams = new Set([\n 'ref',\n 'ref_src',\n 'source',\n 'fbclid',\n 'gclid',\n 'mc_cid',\n 'mc_eid',\n 'igshid',\n 'spm',\n '_hsenc',\n '_hsmi',\n])\n\n/**\n * A stable content key for a fetched page: the sha256 of its normalized text\n * (lowercased, punctuation/whitespace collapsed). Two pages whose readable body\n * is the same modulo formatting collide here, so the dedup stage rejects a\n * mirror/syndication of an already-accepted source even when the URL differs.\n */\nexport function contentKey(text: string): string {\n const normalized = text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return sha256(normalized)\n}\n\n/** Why the deterministic dedup stage rejected a candidate (for audit/notes). */\nexport type DedupReason = 'duplicate-url' | 'duplicate-content'\n\n/** The cheap-triage classification of a unique survivor. */\nexport type TriageClass = 'keep' | 'drop' | 'ambiguous'\n\n/** One source's adaptive routing decision, for instrumentation and the doc. */\nexport interface AdaptiveDecision {\n uri: string\n /** The stage that decided this source: dedup | heuristic | llm. */\n stage: 'dedup' | 'heuristic' | 'llm'\n accepted: boolean\n /** The triage class assigned (set once past dedup). */\n triage?: TriageClass\n reason?: string\n}\n\n/** Running tally of where the adaptive driver spent its decisions. */\nexport interface AdaptiveStats {\n total: number\n /** Rejected by deterministic dedup (URL or content). $0. */\n dedupRejected: number\n /** Kept by the cheap heuristic without an LLM call. $0. */\n heuristicKept: number\n /** Dropped by the cheap heuristic without an LLM call. $0. */\n heuristicDropped: number\n /** Escalated to the LLM relevance verifier ($ — the only paid stage). */\n llmCalls: number\n /** Of the escalations, how many the LLM accepted. */\n llmAccepted: number\n decisions: AdaptiveDecision[]\n}\n\nexport interface AdaptiveDriverOptions {\n /** Router client for the LLM escalation. Defaults to a live client from env. */\n router?: RouterClient\n router_options?: TangleRouterOptions\n /** Passed through to the escalation relevance verifier. */\n verifying?: Pick<VerifyingDriverOptions, 'acceptOnParseFailure'>\n /**\n * Hosts an authoritative source lives on. A unique survivor on one of these,\n * with a substantial body, is KEPT deterministically (no LLM). Suffix-matched\n * against the canonical host, so `arxiv.org` matches `export.arxiv.org`. The\n * defaults cover papers, official docs, and standards bodies.\n */\n authoritativeHosts?: string[]\n /**\n * Title/snippet patterns that mark obvious spam / listicle / marketing — a\n * unique survivor matching one is DROPPED deterministically (no LLM).\n */\n spamPatterns?: RegExp[]\n /**\n * Below this many readable chars a survivor is too thin to be a real reference\n * and is dropped deterministically. Default 400.\n */\n minBodyChars?: number\n /**\n * A survivor whose body is at or above this many chars AND on an authoritative\n * host is kept without an LLM call. Default 600.\n */\n substantialBodyChars?: number\n /** Receives each routing decision as it is made (for live instrumentation). */\n onDecision?: (decision: AdaptiveDecision) => void\n}\n\n/** Default authoritative host suffixes — papers, official docs, standards. */\nconst defaultAuthoritativeHosts = [\n 'arxiv.org',\n 'aclanthology.org',\n 'openreview.net',\n 'dl.acm.org',\n 'ieeexplore.ieee.org',\n 'nature.com',\n 'science.org',\n 'pubmed.ncbi.nlm.nih.gov',\n 'ncbi.nlm.nih.gov',\n '.edu',\n '.gov',\n 'docs.python.org',\n 'pytorch.org',\n 'tensorflow.org',\n 'huggingface.co',\n 'github.com',\n 'developer.mozilla.org',\n 'wikipedia.org',\n 'w3.org',\n 'ietf.org',\n 'rfc-editor.org',\n]\n\n/** Default spam/listicle/marketing title patterns. */\nconst defaultSpamPatterns = [\n /\\bbuy\\b.*\\b(cheap|now|deal|sale|discount)\\b/i,\n /\\b\\d+\\s+(things|ways|reasons|tips|tricks|secrets|hacks)\\b.*\\b(you|that|will)\\b/i,\n /\\bshock(ing|ed)?\\b/i,\n /\\bclickbait\\b/i,\n /!!!|\\$\\$\\$/,\n /\\b(coupon|promo code|affiliate|sponsored)\\b/i,\n /\\bbest .* (of \\d{4}|in \\d{4})\\b/i,\n]\n\n/**\n * Classify a UNIQUE survivor (already past dedup) with cheap host/title/length\n * signals only — no LLM. Returns `keep`, `drop`, or `ambiguous`. `ambiguous` is\n * the residue the LLM is reserved for: on-topic-looking pages on unknown hosts\n * with a plausible body, which a host/title rule cannot adjudicate.\n */\nexport function triageSource(\n source: ResearchSourceProposal,\n options: {\n authoritativeHosts: string[]\n spamPatterns: RegExp[]\n minBodyChars: number\n substantialBodyChars: number\n },\n): { triage: TriageClass; reason: string } {\n const titleAndSnippet = `${source.title ?? ''} ${\n typeof source.metadata?.snippet === 'string' ? source.metadata.snippet : ''\n }`.trim()\n const bodyLen = source.text.trim().length\n\n // Clear DROP: obvious spam/listicle/marketing title, OR a too-thin body that\n // can't be a real reference.\n for (const pattern of options.spamPatterns) {\n if (pattern.test(titleAndSnippet)) {\n return { triage: 'drop', reason: `spam/listicle title (${pattern.source})` }\n }\n }\n if (bodyLen < options.minBodyChars) {\n return { triage: 'drop', reason: `thin body (${bodyLen} < ${options.minBodyChars} chars)` }\n }\n\n // Clear KEEP: an authoritative host with a substantial readable body. The host\n // is a strong prior for a real reference; the length rules out a stub page.\n const host = hostOf(source.uri)\n const authoritative =\n host.length > 0 && options.authoritativeHosts.some((suffix) => hostMatches(host, suffix))\n if (authoritative && bodyLen >= options.substantialBodyChars) {\n return { triage: 'keep', reason: `authoritative host ${host} + substantial body (${bodyLen})` }\n }\n\n // Everything else is AMBIGUOUS — an unknown host with a plausible body. This\n // is exactly the off-scope tail the LLM relevance judge is reserved for.\n return { triage: 'ambiguous', reason: `unknown host ${host || '(none)'}, body ${bodyLen} chars` }\n}\n\nfunction hostOf(uri: string): string {\n try {\n return new URL(uri.trim()).hostname.toLowerCase().replace(/^www\\./, '')\n } catch {\n return ''\n }\n}\n\n/** Suffix host match: `.edu` matches `mit.edu`; `arxiv.org` matches `export.arxiv.org`. */\nfunction hostMatches(host: string, suffix: string): boolean {\n if (suffix.startsWith('.')) return host.endsWith(suffix) || host === suffix.slice(1)\n return host === suffix || host.endsWith(`.${suffix}`)\n}\n\nexport interface AdaptiveResearchDriver {\n verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict>\n /** Live tally of where decisions were spent — the cost/quality instrumentation. */\n stats(): AdaptiveStats\n}\n\n/**\n * Build the adaptive verifier. The deterministic stages (dedup + heuristic\n * triage) cost $0; only AMBIGUOUS survivors escalate to the LLM relevance\n * verifier. `stats()` exposes where every decision was spent so the A/B can read\n * the LLM $/calls the adaptive driver saved against the cleanliness it kept.\n *\n * Dedup state is kept on the driver instance: it tracks the canonical URLs and\n * content hashes it has ACCEPTED, plus those it sees in the verification\n * context's `acceptedThisRound` and the KB index. Use one driver per loop run.\n */\nexport function createAdaptiveResearchDriver(\n options: AdaptiveDriverOptions = {},\n): AdaptiveResearchDriver {\n const authoritativeHosts = options.authoritativeHosts ?? defaultAuthoritativeHosts\n const spamPatterns = options.spamPatterns ?? defaultSpamPatterns\n const minBodyChars = Math.max(1, options.minBodyChars ?? 400)\n const substantialBodyChars = Math.max(minBodyChars, options.substantialBodyChars ?? 600)\n\n // The shipped LLM relevance verifier — the ONLY paid stage, reused, not rebuilt.\n const relevance = createVerifyingResearchDriver({\n router: options.router,\n router_options: options.router_options,\n acceptOnParseFailure: options.verifying?.acceptOnParseFailure,\n })\n\n // Dedup memory across the run: every URL/content key this driver ACCEPTED.\n const acceptedUrlKeys = new Set<string>()\n const acceptedContentKeys = new Set<string>()\n\n const stats: AdaptiveStats = {\n total: 0,\n dedupRejected: 0,\n heuristicKept: 0,\n heuristicDropped: 0,\n llmCalls: 0,\n llmAccepted: 0,\n decisions: [],\n }\n\n function record(decision: AdaptiveDecision): void {\n stats.decisions.push(decision)\n options.onDecision?.(decision)\n }\n\n return {\n async verifySource(source, ctx): Promise<SourceVerdict> {\n stats.total += 1\n const urlKey = canonicalizeUrl(source.uri)\n const cKey = contentKey(source.text)\n\n // ---- STAGE 1: DETERMINISTIC DEDUP ($0) ----------------------------------\n // Seed the dup sets from what the loop already accepted this round AND from\n // the KB index, so a duplicate of an existing source is caught even if this\n // driver instance hasn't seen it yet.\n const roundUrlKeys = new Set(\n ctx.acceptedThisRound.map((accepted) => canonicalizeUrl(accepted.uri)),\n )\n const roundContentKeys = new Set(\n ctx.acceptedThisRound.map((accepted) => contentKey(accepted.text)),\n )\n const indexUrlKeys = new Set(\n ctx.index.sources.flatMap((indexed) =>\n typeof indexed.metadata?.originalUri === 'string'\n ? [canonicalizeUrl(indexed.metadata.originalUri)]\n : [],\n ),\n )\n const dupUrl =\n acceptedUrlKeys.has(urlKey) || roundUrlKeys.has(urlKey) || indexUrlKeys.has(urlKey)\n const dupContent = acceptedContentKeys.has(cKey) || roundContentKeys.has(cKey)\n if (dupUrl || dupContent) {\n stats.dedupRejected += 1\n const reason: DedupReason = dupUrl ? 'duplicate-url' : 'duplicate-content'\n record({ uri: source.uri, stage: 'dedup', accepted: false, reason })\n return { accept: false, reason: `dedup: ${reason}` }\n }\n\n // ---- STAGE 2: CHEAP HEURISTIC TRIAGE ($0) -------------------------------\n const { triage, reason } = triageSource(source, {\n authoritativeHosts,\n spamPatterns,\n minBodyChars,\n substantialBodyChars,\n })\n if (triage === 'keep') {\n stats.heuristicKept += 1\n acceptedUrlKeys.add(urlKey)\n acceptedContentKeys.add(cKey)\n record({ uri: source.uri, stage: 'heuristic', accepted: true, triage, reason })\n return { accept: true }\n }\n if (triage === 'drop') {\n stats.heuristicDropped += 1\n record({ uri: source.uri, stage: 'heuristic', accepted: false, triage, reason })\n return { accept: false, reason: `heuristic drop: ${reason}` }\n }\n\n // ---- STAGE 3: LLM ESCALATION ($ — ambiguous tail only) ------------------\n stats.llmCalls += 1\n const verdict = await relevance.verifySource(source, ctx)\n if (verdict.accept) {\n stats.llmAccepted += 1\n acceptedUrlKeys.add(urlKey)\n acceptedContentKeys.add(cKey)\n }\n record({\n uri: source.uri,\n stage: 'llm',\n accepted: verdict.accept,\n triage,\n reason: verdict.accept ? 'llm accepted' : verdict.reason,\n })\n return verdict\n },\n stats(): AdaptiveStats {\n return {\n ...stats,\n decisions: [...stats.decisions],\n }\n },\n }\n}\n","import {\n type AgentCandidateKnowledgeRef,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n type KnowledgeImprovementCandidateRef,\n KnowledgeImprovementCandidateRefSchema,\n} from './kb-improvement'\n\n/** Convert a measured knowledge candidate into the shared review and execution identity. */\nexport function toAgentCandidateKnowledgeRef(\n candidate: KnowledgeImprovementCandidateRef,\n): AgentCandidateKnowledgeRef {\n const parsed = KnowledgeImprovementCandidateRefSchema.parse(candidate)\n return {\n ...parsed,\n goalHash: prefixedDigest(parsed.goalHash),\n baseHash: prefixedDigest(parsed.baseHash),\n candidateHash: prefixedDigest(parsed.candidateHash),\n evidenceHash: prefixedDigest(parsed.evidenceHash),\n promotionPlanHash: prefixedDigest(parsed.promotionPlanHash),\n }\n}\n\n/** Recover agent-knowledge's candidate identity from the shared contract. */\nexport function fromAgentCandidateKnowledgeRef(\n candidate: AgentCandidateKnowledgeRef,\n): KnowledgeImprovementCandidateRef {\n return KnowledgeImprovementCandidateRefSchema.parse({\n ...candidate,\n goalHash: rawDigest(candidate.goalHash),\n baseHash: rawDigest(candidate.baseHash),\n candidateHash: rawDigest(candidate.candidateHash),\n evidenceHash: rawDigest(candidate.evidenceHash),\n promotionPlanHash: rawDigest(candidate.promotionPlanHash),\n })\n}\n\nfunction prefixedDigest(value: string) {\n return sha256DigestSchema.parse(`sha256:${value}`)\n}\n\nfunction rawDigest(value: string): string {\n return sha256DigestSchema.parse(value).slice('sha256:'.length)\n}\n","import { createHash } from 'node:crypto'\nimport { cp, lstat, mkdir, mkdtemp, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport {\n canonicalJson,\n contentHash,\n type RunRecord,\n validateRunRecord,\n} from '@tangle-network/agent-eval'\nimport { z } from 'zod'\nimport {\n isMissingFile,\n listRegularFilesWithinRoot,\n readRegularFileWithinRoot,\n renameDurable,\n withSafeDirectory,\n writeJsonDurableWithinRoot,\n} from './durable-fs'\nimport type {\n BuildEvalKnowledgeBundleOptions,\n EvalKnowledgeBundleBuildResult,\n KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport {\n applyKnowledgeFileTransaction,\n assertKnowledgeMutationPath,\n finishKnowledgeFileTransaction,\n type KnowledgeFileMutation,\n type KnowledgeFileTransaction,\n type KnowledgeFileTransactionPlanEntry,\n knowledgeFileTransactionPlanHash,\n prepareKnowledgeFileTransaction,\n rollbackKnowledgeFileTransaction,\n} from './file-transaction'\nimport { sha256, slugify, stableId } from './ids'\nimport { buildKnowledgeIndex, writeKnowledgeIndex } from './indexer'\nimport { acquireDurableFileLock, withKnowledgeMutation, withKnowledgeRead } from './mutation-lock'\nimport {\n type KnowledgeBaseQualityOptions,\n type KnowledgeBaseQualityReport,\n scoreKnowledgeBaseIndex,\n} from './rag-eval'\nimport {\n type RagKnowledgeImprovementPhase,\n type RagKnowledgeResearchOptions,\n type RagKnowledgeUpdateInput,\n type RagKnowledgeUpdateResult,\n type RunRagKnowledgeImprovementLoopOptions,\n type RunRagKnowledgeImprovementLoopResult,\n runRagKnowledgeImprovementLoop,\n} from './rag-improvement-loop'\nimport { readinessFor } from './readiness-helpers'\nimport type { RunKnowledgeResearchLoopOptions } from './research-loop'\nimport type { RunRetrievalImprovementLoopOptions } from './retrieval-eval'\nimport { layoutFor } from './store'\nimport type { KnowledgeIndex } from './types'\nimport {\n type ValidateKnowledgeOptions,\n type ValidateKnowledgeResult,\n validateKnowledgeIndex,\n} from './validate'\n\nexport type KnowledgeImprovementStatus =\n | 'running'\n | 'candidate-ready'\n | 'promoted'\n | 'rejected'\n | 'blocked'\n\ninterface KnowledgeImprovementMetricProvenanceBase {\n evaluator: string\n version: string\n}\n\nexport type KnowledgeImprovementMetricProvenance =\n | (KnowledgeImprovementMetricProvenanceBase & {\n method: 'deterministic'\n })\n | (KnowledgeImprovementMetricProvenanceBase & {\n method: 'sampled' | 'composite'\n corpusHash: string\n runRecords: RunRecord[]\n })\n | (KnowledgeImprovementMetricProvenanceBase & {\n method: 'model'\n model: string\n corpusHash: string\n runRecords: RunRecord[]\n })\n\nexport interface KnowledgeImprovementMetric {\n score: number\n passed: boolean\n dimensions?: Record<string, number>\n notes?: string\n provenance: KnowledgeImprovementMetricProvenance\n}\n\nexport interface KnowledgeImprovementEvaluationInput {\n runId: string\n iteration: number\n root: string\n baselineRoot: string\n candidateRoot: string\n baselineIndex: KnowledgeIndex\n candidateIndex: KnowledgeIndex\n baseHash: string\n candidateHash: string\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n kbQuality: KnowledgeBaseQualityReport\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n signal?: AbortSignal\n}\n\nexport type KnowledgeImprovementEvaluator = (\n input: KnowledgeImprovementEvaluationInput,\n) => Promise<KnowledgeImprovementMetric> | KnowledgeImprovementMetric\n\nexport interface KnowledgeImprovementCandidateRecord {\n iteration: number\n candidateId: string\n baseHash: string\n candidateHash?: string\n evidenceHash?: string\n promotionPlanHash?: string\n status: KnowledgeImprovementStatus\n createdAt: string\n updatedAt: string\n}\n\nexport interface KnowledgeImprovementRunState {\n runId: string\n root: string\n goal: string\n status: KnowledgeImprovementStatus\n baseHash: string\n createdAt: string\n updatedAt: string\n ownerId?: string\n candidates: KnowledgeImprovementCandidateRecord[]\n promotedCandidateId?: string\n blockedReason?: string\n}\n\nexport interface KnowledgeImprovementResult {\n runId: string\n state: KnowledgeImprovementRunState\n candidate?: KnowledgeImprovementCandidateRecord\n evaluation?: KnowledgeImprovementMetric\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n promoted: boolean\n blocked: boolean\n}\n\nconst digestSchema = z.string().regex(/^[a-f0-9]{64}$/)\nconst runIdSchema = z.string().min(1).max(2_048)\nconst safePathSegmentSchema = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/)\nconst improvementStatusSchema = z.enum([\n 'running',\n 'candidate-ready',\n 'promoted',\n 'rejected',\n 'blocked',\n])\nconst runRecordSchema = z.custom<RunRecord>((value) => {\n try {\n validateRunRecord(value)\n return true\n } catch {\n return false\n }\n}, 'invalid agent-eval RunRecord')\nconst deterministicMetricProvenanceSchema = z\n .object({\n evaluator: z.string().min(1),\n version: z.string().min(1),\n method: z.literal('deterministic'),\n })\n .strict()\nconst measuredMetricProvenanceSchema = z\n .object({\n evaluator: z.string().min(1),\n version: z.string().min(1),\n method: z.enum(['sampled', 'composite']),\n corpusHash: digestSchema,\n runRecords: z.array(runRecordSchema).min(1),\n })\n .strict()\nconst modelMetricProvenanceSchema = z\n .object({\n evaluator: z.string().min(1),\n version: z.string().min(1),\n method: z.literal('model'),\n model: z.string().min(1),\n corpusHash: digestSchema,\n runRecords: z.array(runRecordSchema).min(1),\n })\n .strict()\nconst improvementMetricSchema = z\n .object({\n score: z.number().finite().min(0).max(1),\n passed: z.boolean(),\n dimensions: z.record(z.string(), z.number().finite()).optional(),\n notes: z.string().optional(),\n provenance: z.discriminatedUnion('method', [\n deterministicMetricProvenanceSchema,\n measuredMetricProvenanceSchema,\n modelMetricProvenanceSchema,\n ]),\n })\n .strict()\n .superRefine((metric, context) => {\n if (metric.provenance.method === 'deterministic') return\n const actualCorpusHash = contentHash(metric.provenance.runRecords)\n if (actualCorpusHash !== metric.provenance.corpusHash) {\n context.addIssue({\n code: 'custom',\n path: ['provenance', 'corpusHash'],\n message: 'metric corpus hash must bind the complete RunRecord array',\n })\n }\n })\nconst candidateRecordSchema = z\n .object({\n iteration: z.number().int().positive(),\n candidateId: safePathSegmentSchema,\n baseHash: digestSchema,\n candidateHash: digestSchema.optional(),\n evidenceHash: digestSchema.optional(),\n promotionPlanHash: digestSchema.optional(),\n status: improvementStatusSchema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n })\n .strict()\n\nexport const KnowledgeImprovementRunStateSchema = z\n .object({\n runId: runIdSchema,\n root: z.string().min(1),\n goal: z.string().min(1),\n status: improvementStatusSchema,\n baseHash: digestSchema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n ownerId: z.string().min(1).optional(),\n candidates: z.array(candidateRecordSchema),\n promotedCandidateId: safePathSegmentSchema.optional(),\n blockedReason: z.string().min(1).optional(),\n })\n .strict()\n .superRefine((state, context) => {\n const candidateIds = new Set<string>()\n for (const [index, candidate] of state.candidates.entries()) {\n if (candidateIds.has(candidate.candidateId)) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index, 'candidateId'],\n message: 'candidate ids must be unique within an improvement run',\n })\n }\n candidateIds.add(candidate.candidateId)\n if (candidate.baseHash !== state.baseHash) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index, 'baseHash'],\n message: 'candidate base hash must match its improvement run',\n })\n }\n if (candidate.status === 'candidate-ready') {\n if (!candidate.candidateHash || !candidate.evidenceHash || !candidate.promotionPlanHash) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index],\n message: 'ready candidates require content, evidence, and promotion-plan identities',\n })\n }\n }\n if (\n candidate.status === 'promoted' &&\n (!candidate.candidateHash || !candidate.evidenceHash || !candidate.promotionPlanHash)\n ) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index],\n message: 'promoted candidates require content, evidence, and promotion-plan identities',\n })\n }\n if (\n candidate.status === 'promoted' &&\n Boolean(candidate.evidenceHash) !== Boolean(candidate.promotionPlanHash)\n ) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index],\n message: 'promoted candidate evidence and promotion-plan identities must appear together',\n })\n }\n if (candidate.status === 'promoted' && state.status !== 'promoted') {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index, 'status'],\n message: 'only a promoted run may contain a promoted candidate',\n })\n }\n }\n if (state.status === 'promoted') {\n const promoted = state.candidates.filter(\n (candidate) => candidate.candidateId === state.promotedCandidateId,\n )\n if (promoted.length !== 1 || promoted[0]?.status !== 'promoted') {\n context.addIssue({\n code: 'custom',\n path: ['promotedCandidateId'],\n message: 'promoted state must identify exactly one promoted candidate',\n })\n }\n } else if (state.promotedCandidateId !== undefined) {\n context.addIssue({\n code: 'custom',\n path: ['promotedCandidateId'],\n message: 'only a promoted run may identify a promoted candidate',\n })\n }\n if (\n state.status === 'candidate-ready' &&\n state.candidates.filter((candidate) => candidate.status === 'candidate-ready').length !== 1\n ) {\n context.addIssue({\n code: 'custom',\n path: ['status'],\n message: 'candidate-ready state must contain exactly one ready candidate',\n })\n }\n if (state.status === 'blocked' && state.blockedReason === undefined) {\n context.addIssue({\n code: 'custom',\n path: ['blockedReason'],\n message: 'blocked state must include a reason',\n })\n }\n })\n\nexport const KnowledgeImprovementEvidenceSchema = z\n .object({\n kind: z.literal('knowledge-improvement-evidence'),\n runId: runIdSchema,\n candidateId: safePathSegmentSchema,\n iteration: z.number().int().positive(),\n goalHash: digestSchema,\n baseHash: digestSchema,\n candidateHash: digestSchema,\n promotionPlanHash: digestSchema,\n validation: z.unknown(),\n readiness: z.unknown().nullable(),\n kbQuality: z.unknown(),\n evaluation: improvementMetricSchema,\n lifecycle: z.unknown().nullable(),\n })\n .strict()\n\nexport type KnowledgeImprovementEvidence = z.infer<typeof KnowledgeImprovementEvidenceSchema>\n\n/** Portable identity of one measured candidate. Paths and mutable run state are deliberately excluded. */\nexport const KnowledgeImprovementCandidateRefSchema = z\n .object({\n kind: z.literal('knowledge-improvement-candidate'),\n runId: runIdSchema,\n candidateId: safePathSegmentSchema,\n goalHash: digestSchema,\n baseHash: digestSchema,\n candidateHash: digestSchema,\n evidenceHash: digestSchema,\n promotionPlanHash: digestSchema,\n })\n .strict()\n\nexport type KnowledgeImprovementCandidateRef = z.infer<\n typeof KnowledgeImprovementCandidateRefSchema\n>\n\nexport interface PromoteKnowledgeCandidateOptions {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n ownerId?: string\n leaseTtlMs?: number\n now?: () => Date\n onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void\n}\n\nexport type RestoreKnowledgeCandidateBaselineOptions = PromoteKnowledgeCandidateOptions\n\nexport interface UseKnowledgeImprovementCandidateOptions {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n}\n\nexport interface ResolvedKnowledgeImprovementCandidate {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n evaluation: KnowledgeImprovementMetric\n}\n\nexport interface KnowledgeImprovementRetrievalOptions\n extends Omit<RunRetrievalImprovementLoopOptions, 'index' | 'runDir'> {\n runDir?: RunRetrievalImprovementLoopOptions['runDir']\n}\n\nexport interface KnowledgeImprovementUpdateInput extends RagKnowledgeUpdateInput {\n runId: string\n iteration: number\n candidateId: string\n root: string\n baselineRoot: string\n candidateRoot: string\n baseHash: string\n}\n\nexport type KnowledgeImprovementUpdate = (\n input: KnowledgeImprovementUpdateInput,\n) => Promise<RagKnowledgeUpdateResult> | RagKnowledgeUpdateResult\n\nexport interface KnowledgeImprovementOptions {\n root: string\n goal: string\n runId?: string\n ownerId?: string\n leaseTtlMs?: number\n resume?: boolean\n maxCandidates?: number\n candidateResearchIterations?: number\n strict?: ValidateKnowledgeOptions['strict']\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n kbQuality?: KnowledgeBaseQualityOptions\n step?: RunKnowledgeResearchLoopOptions['step']\n knowledgeResearch?: Omit<RagKnowledgeResearchOptions, 'root'>\n retrieval?: KnowledgeImprovementRetrievalOptions\n diagnose?: NonNullable<RunRagKnowledgeImprovementLoopOptions['diagnose']>\n acquireKnowledge?: NonNullable<RunRagKnowledgeImprovementLoopOptions['acquireKnowledge']>\n updateKnowledge?: KnowledgeImprovementUpdate\n evaluateAnswers?: NonNullable<RunRagKnowledgeImprovementLoopOptions['evaluateAnswers']>\n decidePromotion?: NonNullable<RunRagKnowledgeImprovementLoopOptions['promote']>\n enabledPhases?: readonly RagKnowledgeImprovementPhase[]\n requiredPhases?: readonly RagKnowledgeImprovementPhase[]\n evaluate?: KnowledgeImprovementEvaluator\n signal?: AbortSignal\n now?: () => Date\n onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void\n}\n\ninterface LeaseHandle {\n ownerId: string\n assertOwned(): void\n release(): Promise<void>\n}\n\nconst DEFAULT_LEASE_TTL_MS = 15 * 60 * 1000\nconst UPDATE_PHASES: readonly RagKnowledgeImprovementPhase[] = [\n 'knowledge-acquisition',\n 'knowledge-update',\n]\nconst EVALUATION_PHASES: readonly RagKnowledgeImprovementPhase[] = [\n 'retrieval-tuning',\n 'gap-diagnosis',\n 'answer-quality',\n 'promotion',\n]\n\nexport function knowledgeImprovementRunId(root: string, goal: string): string {\n return stableId('kimpr', `${root}:${goal}`)\n}\n\nexport function knowledgeImprovementRunDir(root: string, runId: string): string {\n const parsedRunId = runIdSchema.parse(runId)\n const safeRunId = safePathSegmentSchema.safeParse(parsedRunId)\n const runSegment = safeRunId.success\n ? safeRunId.data\n : `${slugify(parsedRunId).slice(0, 72)}-${sha256(parsedRunId).slice(0, 16)}`\n const improvementsDir = join(layoutFor(root).cacheDir, 'improvements')\n const runDir = join(improvementsDir, runSegment)\n const resolvedImprovementsDir = resolve(improvementsDir)\n const resolvedRunDir = resolve(runDir)\n if (!resolvedRunDir.startsWith(`${resolvedImprovementsDir}${sep}`)) {\n throw new Error('knowledge improvement run directory escaped its root')\n }\n return runDir\n}\n\nasync function withKnowledgeImprovementRun<T>(\n root: string,\n runId: string,\n create: boolean,\n use: (runDir: string) => Promise<T> | T,\n): Promise<T> {\n const runDir = knowledgeImprovementRunDir(root, runId)\n const relativePath = descendantPath(root, runDir)\n if (!relativePath) throw new Error('knowledge improvement run directory escaped its root')\n return withSafeDirectory(root, relativePath, create, async (openedRunDir) => {\n const result = await use(openedRunDir)\n const openedIdentity = await stat(openedRunDir)\n const currentIdentity = await withSafeDirectory(root, relativePath, false, (currentRunDir) =>\n stat(currentRunDir),\n )\n if (openedIdentity.dev !== currentIdentity.dev || openedIdentity.ino !== currentIdentity.ino) {\n throw new Error('knowledge improvement run directory changed during use')\n }\n return result\n })\n}\n\nexport async function loadKnowledgeImprovementState(\n root: string,\n runId: string,\n): Promise<KnowledgeImprovementRunState | null> {\n const expectedRunId = runIdSchema.parse(runId)\n try {\n return await withKnowledgeImprovementRun(root, expectedRunId, false, (runDir) =>\n loadKnowledgeImprovementStateFromRun(root, expectedRunId, runDir),\n )\n } catch (error) {\n if (isMissingFile(error)) return null\n throw error\n }\n}\n\nasync function loadKnowledgeImprovementStateFromRun(\n root: string,\n runId: string,\n runDir: string,\n): Promise<KnowledgeImprovementRunState> {\n const stateFile = await readRegularFileWithinRoot(runDir, 'state.json')\n const raw = JSON.parse(stateFile.bytes.toString('utf8')) as unknown\n const state = KnowledgeImprovementRunStateSchema.parse(raw) as KnowledgeImprovementRunState\n if (state.runId !== runId) {\n throw new Error('knowledge improvement state does not match the requested run')\n }\n if (resolve(state.root) !== resolve(root)) {\n throw new Error('knowledge improvement state does not match the requested root')\n }\n for (const candidate of state.candidates) {\n if (candidate.status === 'running') await assertCandidateWorkspace(runDir, candidate)\n }\n return state\n}\n\n/** Freeze the exact knowledge bytes and measured evidence a later approval may promote. */\nexport function knowledgeImprovementCandidateRef(\n result: Pick<KnowledgeImprovementResult, 'runId' | 'state' | 'candidate'>,\n): KnowledgeImprovementCandidateRef {\n if (!result.candidate) throw new Error('knowledge improvement result has no candidate')\n return candidateRefFor(result.runId, result.state, result.candidate)\n}\n\n/** Use one measured snapshot while its directory identity remains open and stable. */\nexport async function withKnowledgeImprovementCandidate<T>(\n options: UseKnowledgeImprovementCandidateOptions,\n use: (candidate: ResolvedKnowledgeImprovementCandidate) => Promise<T> | T,\n): Promise<T> {\n assertExactCandidatePlatform()\n const candidateRef = KnowledgeImprovementCandidateRefSchema.parse(options.candidate)\n return withKnowledgeImprovementRun(options.root, candidateRef.runId, false, async (runDir) => {\n const state = await loadKnowledgeImprovementStateFromRun(\n options.root,\n candidateRef.runId,\n runDir,\n )\n return withMeasuredCandidateSnapshot(options.root, runDir, state, candidateRef, (resolved) =>\n withIsolatedCandidateCopy(resolved.root, candidateRef.candidateHash, (root) =>\n use({\n root,\n candidate: candidateRef,\n evaluation: resolved.evidence.evaluation,\n }),\n ),\n )\n })\n}\n\n/** Promote one previously measured candidate without rerunning research or evaluation. */\nexport async function promoteKnowledgeCandidate(\n options: PromoteKnowledgeCandidateOptions,\n): Promise<KnowledgeImprovementResult> {\n return transitionKnowledgeCandidate(options, 'candidate')\n}\n\n/** Restore the frozen baseline paired with one previously measured candidate. */\nexport async function restoreKnowledgeCandidateBaseline(\n options: RestoreKnowledgeCandidateBaselineOptions,\n): Promise<KnowledgeImprovementResult> {\n return transitionKnowledgeCandidate(options, 'baseline')\n}\n\ntype KnowledgeCandidateTarget = 'candidate' | 'baseline'\n\nasync function transitionKnowledgeCandidate(\n options: PromoteKnowledgeCandidateOptions,\n target: KnowledgeCandidateTarget,\n): Promise<KnowledgeImprovementResult> {\n assertExactCandidatePlatform()\n const candidateRef = Object.freeze(\n KnowledgeImprovementCandidateRefSchema.parse(options.candidate),\n )\n const now = options.now ?? (() => new Date())\n return withKnowledgeImprovementRun(options.root, candidateRef.runId, false, async (runDir) => {\n const lease = await acquireRunLease(runDir, {\n ownerId: options.ownerId ?? `pid-${process.pid}`,\n ttlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n })\n try {\n lease.assertOwned()\n const state = await loadKnowledgeImprovementStateFromRun(\n options.root,\n candidateRef.runId,\n runDir,\n )\n return await applyKnowledgeCandidateTarget(\n {\n root: options.root,\n runDir,\n state,\n candidateRef,\n leaseTtlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n assertRunOwned: lease.assertOwned,\n now,\n onState: options.onState,\n },\n target,\n )\n } finally {\n await lease.release()\n }\n })\n}\n\nexport async function improveKnowledgeBase(\n options: KnowledgeImprovementOptions,\n): Promise<KnowledgeImprovementResult> {\n assertExactCandidatePlatform()\n assertKnowledgeImprovementOptions(options)\n const now = options.now ?? (() => new Date())\n const runId = runIdSchema.parse(\n options.runId ?? knowledgeImprovementRunId(options.root, options.goal),\n )\n return withKnowledgeImprovementRun(options.root, runId, true, (runDir) =>\n improveKnowledgeBaseInRun(options, runId, runDir, now),\n )\n}\n\nasync function improveKnowledgeBaseInRun(\n options: KnowledgeImprovementOptions,\n runId: string,\n runDir: string,\n now: () => Date,\n): Promise<KnowledgeImprovementResult> {\n const lease = await acquireRunLease(runDir, {\n ownerId: options.ownerId ?? `pid-${process.pid}`,\n ttlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n })\n\n try {\n lease.assertOwned()\n let state =\n options.resume === false\n ? null\n : await loadKnowledgeImprovementStateFromRun(options.root, runId, runDir).catch((error) => {\n if (isMissingFile(error)) return null\n throw error\n })\n if (!state) {\n const baseHash = await hashKnowledgeBase(options.root)\n await createBaselineSnapshot(runDir, options.root, baseHash)\n state = {\n runId,\n root: options.root,\n goal: options.goal,\n status: 'running',\n baseHash,\n createdAt: now().toISOString(),\n updatedAt: now().toISOString(),\n ownerId: lease.ownerId,\n candidates: [],\n }\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, { type: 'run.created', runId, baseHash })\n }\n if (state.goal !== options.goal) {\n throw new Error('knowledge improvement state does not match the requested goal')\n }\n const promotedCandidateId = state.promotedCandidateId\n const promotedCandidate =\n state.status === 'promoted'\n ? state.candidates.find((candidate) => candidate.candidateId === promotedCandidateId)\n : undefined\n if (state.status === 'promoted' && !promotedCandidate) {\n throw new Error('promoted knowledge state has no promoted candidate')\n }\n const resumablePromotion = state.candidates.find(\n (candidate) =>\n (candidate.status === 'candidate-ready' || candidate.status === 'promoted') &&\n candidate.evidenceHash !== undefined &&\n candidate.promotionPlanHash !== undefined,\n )\n const resumableCandidateRef = resumablePromotion\n ? candidateRefFor(runId, state, resumablePromotion)\n : undefined\n await withKnowledgeMutation(options.root, () => undefined, {\n resumeTransaction: resumableCandidateRef\n ? {\n purpose: knowledgeCandidateTransitionPurpose(resumableCandidateRef, 'candidate'),\n validate: (transaction) =>\n assertCandidateTransitionTransaction(transaction, resumableCandidateRef, 'candidate'),\n }\n : undefined,\n })\n await ensureBaselineSnapshot(runDir, options.root, state.baseHash)\n\n if (state.status === 'promoted') {\n const promoted = promotedCandidate!\n return await applyKnowledgeCandidateTarget(\n {\n root: options.root,\n runDir,\n state,\n candidateRef: candidateRefFor(runId, state, promoted),\n leaseTtlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n assertRunOwned: lease.assertOwned,\n now,\n onState: options.onState,\n },\n 'candidate',\n )\n }\n if (state.status === 'blocked') {\n return { runId, state, promoted: false, blocked: true }\n }\n\n const maxCandidates = Math.max(1, options.maxCandidates ?? 1)\n let candidate = findActiveCandidate(state)\n let lastRejectedCandidate: KnowledgeImprovementCandidateRecord | undefined\n let lastRejectedEvaluation: KnowledgeImprovementMetric | undefined\n let lifecycle: RunRagKnowledgeImprovementLoopResult | undefined\n\n while (candidate || state.candidates.length < maxCandidates) {\n if (!candidate) {\n const currentHash = await hashKnowledgeBase(options.root)\n if (currentHash !== state.baseHash) {\n state = await blockRun(\n runDir,\n state,\n `base changed before candidate creation: expected ${state.baseHash}, got ${currentHash}`,\n options.onState,\n now,\n )\n return { runId, state, promoted: false, blocked: true }\n }\n const activeState = state\n candidate = await withBaselineSnapshot(runDir, activeState.baseHash, (baselineRoot) =>\n createCandidateWorkspace(runDir, activeState, baselineRoot, now),\n )\n state.candidates.push(candidate)\n state.status = 'running'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, {\n type: 'candidate.created',\n runId,\n candidateId: candidate.candidateId,\n iteration: candidate.iteration,\n })\n }\n\n const measured = await measureCandidate(runId, runDir, state, candidate, options, now)\n candidate = measured.candidate\n const evaluation = measured.evaluation\n lifecycle = measured.lifecycle\n\n if (evaluation.passed) {\n candidate.status = 'candidate-ready'\n candidate.updatedAt = now().toISOString()\n state.status = 'candidate-ready'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, {\n type: 'candidate.ready',\n runId,\n candidateId: candidate.candidateId,\n })\n break\n }\n\n candidate.status = 'rejected'\n state.status = 'running'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, {\n type: 'candidate.rejected',\n runId,\n candidateId: candidate.candidateId,\n })\n lastRejectedCandidate = candidate\n lastRejectedEvaluation = evaluation\n candidate = undefined\n }\n\n if (!candidate) {\n state.status = 'rejected'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n return {\n runId,\n state,\n candidate: lastRejectedCandidate,\n ...(lastRejectedEvaluation ? { evaluation: lastRejectedEvaluation } : {}),\n lifecycle,\n promoted: false,\n blocked: false,\n }\n }\n\n const evidence = await assertCandidateEvidence(runDir, candidateRefFor(runId, state, candidate))\n return {\n runId,\n state,\n candidate,\n evaluation: evidence.evaluation,\n lifecycle,\n promoted: false,\n blocked: false,\n }\n } finally {\n await lease.release()\n }\n}\n\ninterface KnowledgeCandidateTransitionInput {\n root: string\n runDir: string\n state: KnowledgeImprovementRunState\n candidateRef: KnowledgeImprovementCandidateRef\n leaseTtlMs: number\n assertRunOwned(): void\n now: () => Date\n onState?: KnowledgeImprovementOptions['onState']\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n}\n\nasync function applyKnowledgeCandidateTarget(\n input: KnowledgeCandidateTransitionInput,\n target: KnowledgeCandidateTarget,\n): Promise<KnowledgeImprovementResult> {\n const { candidateRef, runDir, state } = input\n assertStateIdentity(input.root, candidateRef, state)\n const candidate = state.candidates.find((entry) => entry.candidateId === candidateRef.candidateId)\n if (\n !candidate ||\n canonicalJson(candidateRefFor(candidateRef.runId, state, candidate)) !==\n canonicalJson(candidateRef)\n ) {\n throw new Error('knowledge candidate approval does not match the measured candidate')\n }\n\n const action = target === 'candidate' ? 'promotion' : 'restore'\n const desiredHash = target === 'candidate' ? candidateRef.candidateHash : candidateRef.baseHash\n const purpose = knowledgeCandidateTransitionPurpose(candidateRef, target)\n return withKnowledgeMutation(\n input.root,\n async (mutationLock) => {\n input.assertRunOwned()\n const transactionRoot = mutationLock.transactionRoot\n let pending: KnowledgeFileTransaction | null = null\n const currentHash = await hashKnowledgeBase(input.root)\n if (state.status === 'promoted' && state.promotedCandidateId !== candidate.candidateId) {\n throw new Error(\n `knowledge run already promoted '${state.promotedCandidateId ?? 'unknown'}'`,\n )\n }\n if (\n target === 'candidate' &&\n state.status === 'promoted' &&\n currentHash !== candidateRef.candidateHash\n ) {\n throw new Error(\n `promoted knowledge base changed: expected ${candidateRef.candidateHash}, got ${currentHash}`,\n )\n }\n if (state.status !== 'promoted' && state.status !== 'candidate-ready') {\n throw new Error(\n `knowledge candidate is not ready for ${action}: run=${state.status}, candidate=${candidate.status}`,\n )\n }\n if (currentHash !== state.baseHash && currentHash !== candidateRef.candidateHash) {\n const reason =\n target === 'candidate'\n ? `base changed before promotion: expected ${state.baseHash}, got ${currentHash}`\n : `knowledge changed before restore: expected ${candidateRef.candidateHash}, got ${currentHash}`\n return await blockCandidateTransition(input, candidate, target, reason)\n }\n\n if (currentHash !== desiredHash) {\n pending = await withMeasuredCandidateSnapshot(\n input.root,\n runDir,\n state,\n candidateRef,\n (resolved) =>\n withBaselineSnapshot(runDir, state.baseHash, async (baselineRoot) => {\n const sourceRoot = target === 'candidate' ? baselineRoot : resolved.root\n const targetRoot = target === 'candidate' ? resolved.root : baselineRoot\n const plan = await knowledgeFilePlanEntries(sourceRoot, targetRoot)\n assertCandidateTransitionPlan(plan, candidateRef, target)\n return prepareKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n purpose,\n mutations: await knowledgePlanMutations(targetRoot, plan),\n includeUnchanged: true,\n now: input.now,\n })\n }),\n )\n if (!pending) {\n throw new Error(`knowledge ${action} plan unexpectedly contained no file changes`)\n }\n try {\n assertCandidateTransitionTransaction(pending, candidateRef, target)\n } catch (error) {\n try {\n await rollbackKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n beforeCommit() {\n mutationLock.assertOwned()\n input.assertRunOwned()\n },\n })\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n assertOwned() {\n mutationLock.assertOwned()\n input.assertRunOwned()\n },\n })\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n `invalid knowledge ${action} transaction could not be removed`,\n )\n }\n throw error\n }\n }\n try {\n if (pending) {\n await applyKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n beforeCommit() {\n mutationLock.assertOwned()\n input.assertRunOwned()\n },\n })\n }\n mutationLock.assertOwned()\n input.assertRunOwned()\n if ((await hashKnowledgeBase(input.root)) !== desiredHash) {\n throw new Error(`knowledge ${action} content does not match the approved target`)\n }\n await writeKnowledgeIndex(input.root)\n } catch (error) {\n if (!pending) throw error\n try {\n mutationLock.assertOwned()\n input.assertRunOwned()\n } catch (ownershipError) {\n throw new AggregateError(\n [error, ownershipError],\n `knowledge ${action} lost its lock and left the transaction pending`,\n )\n }\n try {\n await rollbackKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n beforeCommit() {\n mutationLock.assertOwned()\n input.assertRunOwned()\n },\n })\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n assertOwned() {\n mutationLock.assertOwned()\n input.assertRunOwned()\n },\n })\n await writeKnowledgeIndex(input.root)\n } catch (rollbackError) {\n throw new AggregateError(\n [error, rollbackError],\n `knowledge ${action} failed and could not restore the previous files`,\n )\n }\n throw error\n }\n candidate.status = target === 'candidate' ? 'promoted' : 'candidate-ready'\n candidate.updatedAt = input.now().toISOString()\n state.status = candidate.status\n if (target === 'candidate') state.promotedCandidateId = candidate.candidateId\n else delete state.promotedCandidateId\n delete state.blockedReason\n state.updatedAt = input.now().toISOString()\n await saveState(runDir, state, input.onState)\n await ensureCandidateTransitionEvent(runDir, candidateRef, target)\n if (pending) {\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n assertOwned() {\n mutationLock.assertOwned()\n input.assertRunOwned()\n },\n })\n }\n return candidateTransitionResult(input, candidate, target === 'candidate', false)\n },\n {\n staleMs: input.leaseTtlMs,\n resumeTransaction: {\n purpose,\n validate: (transaction) =>\n assertCandidateTransitionTransaction(transaction, candidateRef, target),\n },\n },\n )\n}\n\nasync function blockCandidateTransition(\n input: KnowledgeCandidateTransitionInput,\n candidate: KnowledgeImprovementCandidateRecord,\n target: KnowledgeCandidateTarget,\n reason: string,\n): Promise<KnowledgeImprovementResult> {\n if (input.state.status === 'promoted') {\n candidate.status = 'blocked'\n candidate.updatedAt = input.now().toISOString()\n delete input.state.promotedCandidateId\n }\n await blockRun(input.runDir, input.state, reason, input.onState, input.now)\n await appendLedger(input.runDir, {\n type: target === 'candidate' ? 'promotion.blocked' : 'restore.blocked',\n runId: input.candidateRef.runId,\n candidateId: candidate.candidateId,\n reason,\n })\n return candidateTransitionResult(input, candidate, false, true)\n}\n\nfunction candidateTransitionResult(\n input: KnowledgeCandidateTransitionInput,\n candidate: KnowledgeImprovementCandidateRecord,\n promoted: boolean,\n blocked: boolean,\n): KnowledgeImprovementResult {\n return {\n runId: input.candidateRef.runId,\n state: input.state,\n candidate,\n ...(input.lifecycle ? { lifecycle: input.lifecycle } : {}),\n promoted,\n blocked,\n }\n}\n\nfunction candidateRefFor(\n runId: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n): KnowledgeImprovementCandidateRef {\n if (!candidate.candidateHash) {\n throw new Error(`knowledge candidate '${candidate.candidateId}' has no content hash`)\n }\n if (!candidate.evidenceHash) {\n throw new Error(`knowledge candidate '${candidate.candidateId}' has no evidence hash`)\n }\n if (!candidate.promotionPlanHash) {\n throw new Error(`knowledge candidate '${candidate.candidateId}' has no promotion plan hash`)\n }\n if (candidate.status !== 'candidate-ready' && candidate.status !== 'promoted') {\n throw new Error(`knowledge candidate '${candidate.candidateId}' is not ready`)\n }\n return Object.freeze({\n kind: 'knowledge-improvement-candidate',\n runId,\n candidateId: candidate.candidateId,\n goalHash: sha256(state.goal),\n baseHash: candidate.baseHash,\n candidateHash: candidate.candidateHash,\n evidenceHash: candidate.evidenceHash,\n promotionPlanHash: candidate.promotionPlanHash,\n })\n}\n\nasync function withMeasuredCandidateSnapshot<T>(\n liveRoot: string,\n runDir: string,\n state: KnowledgeImprovementRunState,\n candidateRef: KnowledgeImprovementCandidateRef,\n use: (snapshot: {\n root: string\n candidate: KnowledgeImprovementCandidateRecord\n evidence: KnowledgeImprovementEvidence\n }) => Promise<T> | T,\n): Promise<T> {\n assertStateIdentity(liveRoot, candidateRef, state)\n const candidate = state.candidates.find((entry) => entry.candidateId === candidateRef.candidateId)\n if (!candidate) {\n throw new Error(`knowledge candidate '${candidateRef.candidateId}' does not exist`)\n }\n const expectedRef = candidateRefFor(candidateRef.runId, state, candidate)\n if (canonicalJson(expectedRef) !== canonicalJson(candidateRef)) {\n throw new Error('knowledge candidate approval does not match the measured candidate')\n }\n const evidence = await assertCandidateEvidence(runDir, candidateRef)\n const relativePath = join(\n 'candidates',\n candidate.candidateId,\n 'snapshots',\n candidateRef.candidateHash,\n )\n return withSafeDirectory(runDir, relativePath, false, async (root) => {\n if ((await hashKnowledgeBase(root)) !== candidateRef.candidateHash) {\n throw new Error('knowledge candidate snapshot changed after approval')\n }\n const result = await use({ root, candidate, evidence })\n if ((await hashKnowledgeBase(root)) !== candidateRef.candidateHash) {\n throw new Error('knowledge candidate snapshot changed during use')\n }\n return result\n })\n}\n\nasync function withIsolatedCandidateCopy<T>(\n sourceRoot: string,\n expectedHash: string,\n use: (root: string) => Promise<T> | T,\n): Promise<T> {\n const isolationRoot = await mkdtemp(join(tmpdir(), 'agent-knowledge-candidate-'))\n const candidateRoot = join(isolationRoot, 'candidate')\n try {\n await copyKnowledgeWorkspace(sourceRoot, candidateRoot)\n if ((await hashKnowledgeBase(candidateRoot)) !== expectedHash) {\n throw new Error('isolated knowledge candidate does not match its approved content')\n }\n const result = await use(candidateRoot)\n if ((await hashKnowledgeBase(candidateRoot)) !== expectedHash) {\n throw new Error('knowledge candidate snapshot changed during use')\n }\n return result\n } finally {\n await rm(isolationRoot, { recursive: true, force: true })\n }\n}\n\nasync function assertCandidateEvidence(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRef,\n): Promise<KnowledgeImprovementEvidence> {\n const evidence = KnowledgeImprovementEvidenceSchema.parse(\n JSON.parse(\n (\n await readRegularFileWithinRoot(\n runDir,\n candidateEvidenceRelativePath(candidate.candidateId),\n )\n ).bytes.toString('utf8'),\n ),\n )\n const actualHash = contentHash(evidence)\n if (actualHash !== candidate.evidenceHash) {\n throw new Error(\n `knowledge candidate evidence changed after approval: expected ${candidate.evidenceHash}, got ${actualHash}`,\n )\n }\n if (\n evidence.runId !== candidate.runId ||\n evidence.candidateId !== candidate.candidateId ||\n evidence.goalHash !== candidate.goalHash ||\n evidence.baseHash !== candidate.baseHash ||\n evidence.candidateHash !== candidate.candidateHash ||\n evidence.promotionPlanHash !== candidate.promotionPlanHash ||\n evidence.evaluation.passed !== true\n ) {\n throw new Error('knowledge candidate evidence does not match the approved candidate')\n }\n return evidence\n}\n\nfunction assertStateIdentity(\n root: string,\n candidateRef: KnowledgeImprovementCandidateRef,\n state: KnowledgeImprovementRunState,\n): void {\n if (state.runId !== candidateRef.runId) {\n throw new Error('knowledge candidate run identity does not match persisted state')\n }\n if (resolve(state.root) !== resolve(root)) {\n throw new Error('knowledge candidate root does not match persisted state')\n }\n if (sha256(state.goal) !== candidateRef.goalHash) {\n throw new Error('knowledge candidate goal does not match persisted state')\n }\n if (state.baseHash !== candidateRef.baseHash) {\n throw new Error('knowledge candidate base does not match persisted state')\n }\n}\n\nasync function assertCandidateWorkspace(\n runDir: string,\n candidate: Pick<KnowledgeImprovementCandidateRecord, 'candidateId'>,\n): Promise<void> {\n await withCandidateWorkspace(runDir, candidate, () => undefined)\n}\n\nasync function withCandidateWorkspace<T>(\n runDir: string,\n candidate: Pick<KnowledgeImprovementCandidateRecord, 'candidateId'>,\n use: (candidateRoot: string) => Promise<T> | T,\n): Promise<T> {\n return withSafeDirectory(\n runDir,\n join('candidates', safePathSegmentSchema.parse(candidate.candidateId), 'workspace'),\n false,\n use,\n )\n}\n\nfunction assertKnowledgeImprovementOptions(options: KnowledgeImprovementOptions): void {\n if (options.step && options.knowledgeResearch?.step) {\n throw new Error('improveKnowledgeBase accepts either step or knowledgeResearch.step, not both')\n }\n const updateDrivers = [\n Boolean(options.step ?? options.knowledgeResearch),\n Boolean(options.updateKnowledge),\n ].filter(Boolean).length\n if (updateDrivers > 1) {\n throw new Error(\n 'improveKnowledgeBase accepts only one knowledge-update driver: knowledgeResearch or updateKnowledge',\n )\n }\n}\n\nasync function measureCandidate(\n runId: string,\n runDir: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<{\n candidate: KnowledgeImprovementCandidateRecord\n evaluation: KnowledgeImprovementMetric\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n}> {\n return withCandidateWorkspace(runDir, candidate, async (candidateRoot) => {\n const currentCandidateHash = await hashKnowledgeBase(candidateRoot)\n if (\n candidate.status === 'candidate-ready' &&\n candidate.candidateHash === currentCandidateHash &&\n candidate.evidenceHash !== undefined &&\n candidate.promotionPlanHash !== undefined\n ) {\n const evidence = await assertCandidateEvidence(\n runDir,\n candidateRefFor(runId, state, candidate),\n )\n return { candidate, evaluation: evidence.evaluation }\n }\n\n clearCandidateMeasurement(candidate)\n const lifecycles: RunRagKnowledgeImprovementLoopResult[] = []\n if (candidate.status === 'running') {\n const updateLifecycle = await runCandidateUpdateLifecycle(\n runId,\n candidate,\n candidateRoot,\n options,\n now,\n )\n if (updateLifecycle) lifecycles.push(updateLifecycle)\n }\n return withFrozenCandidateWorkspace(runDir, candidate, candidateRoot, async (snapshot) => {\n const evaluationLifecycle = await runCandidateEvaluationLifecycle(\n runDir,\n candidate,\n snapshot.root,\n options,\n now,\n )\n if (evaluationLifecycle) lifecycles.push(evaluationLifecycle)\n const lifecycle = mergeLifecycleResults(options.goal, lifecycles)\n const measured = await evaluateCandidate(\n runDir,\n state,\n candidate,\n snapshot,\n lifecycle,\n options,\n now,\n )\n return { ...measured, ...(lifecycle ? { lifecycle } : {}) }\n })\n })\n}\n\nasync function runCandidateUpdateLifecycle(\n runId: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<RunRagKnowledgeImprovementLoopResult | undefined> {\n if (!shouldRunUpdateStage(options)) return undefined\n const lifecycle = await runRagKnowledgeImprovementLoop({\n goal: options.goal,\n acquireKnowledge: options.acquireKnowledge,\n knowledgeResearch: candidateKnowledgeResearchOptions(candidateRoot, options),\n updateKnowledge: candidateUpdateHook(runId, candidate, candidateRoot, options),\n enabledPhases: selectedStagePhases(options, UPDATE_PHASES),\n requiredPhases: selectedStageRequiredPhases(options, UPDATE_PHASES),\n signal: options.signal,\n now,\n })\n return lifecycle\n}\n\nasync function runCandidateEvaluationLifecycle(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<RunRagKnowledgeImprovementLoopResult | undefined> {\n if (!shouldRunEvaluationStage(options)) return undefined\n const candidateIndex = await buildKnowledgeIndex(candidateRoot)\n const lifecycle = await runRagKnowledgeImprovementLoop({\n goal: options.goal,\n retrieval: options.retrieval\n ? {\n ...options.retrieval,\n index: candidateIndex,\n runDir: options.retrieval.runDir ?? join(runDir, 'retrieval', candidate.candidateId),\n }\n : undefined,\n diagnose: options.diagnose,\n evaluateAnswers: options.evaluateAnswers,\n promote: options.decidePromotion,\n enabledPhases: selectedStagePhases(options, EVALUATION_PHASES),\n requiredPhases: selectedStageRequiredPhases(options, EVALUATION_PHASES),\n signal: options.signal,\n now,\n })\n return lifecycle\n}\n\nfunction candidateKnowledgeResearchOptions(\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n): RagKnowledgeResearchOptions | undefined {\n if (!options.step && !options.knowledgeResearch) return undefined\n const { step: researchStep, ...rest } = options.knowledgeResearch ?? {}\n const step = options.step ?? researchStep\n return {\n ...rest,\n root: candidateRoot,\n step,\n maxIterations:\n rest.maxIterations ?? (step ? (options.candidateResearchIterations ?? 3) : undefined),\n strict: rest.strict ?? options.strict,\n readinessSpecs: rest.readinessSpecs ?? options.readinessSpecs,\n readinessTaskId: rest.readinessTaskId ?? options.readinessTaskId,\n readiness: rest.readiness ?? options.readiness,\n }\n}\n\nfunction candidateUpdateHook(\n runId: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n): RunRagKnowledgeImprovementLoopOptions['updateKnowledge'] {\n if (!options.updateKnowledge) return undefined\n return (input) =>\n options.updateKnowledge!({\n ...input,\n runId,\n iteration: candidate.iteration,\n candidateId: candidate.candidateId,\n root: candidateRoot,\n baselineRoot: options.root,\n candidateRoot,\n baseHash: candidate.baseHash,\n })\n}\n\nfunction shouldRunUpdateStage(options: KnowledgeImprovementOptions): boolean {\n const phases = selectedStagePhases(options, UPDATE_PHASES)\n if (phases.length === 0) return false\n return Boolean(\n options.acquireKnowledge ||\n options.step ||\n options.knowledgeResearch ||\n options.updateKnowledge ||\n selectedStageRequiredPhases(options, UPDATE_PHASES).length > 0,\n )\n}\n\nfunction shouldRunEvaluationStage(options: KnowledgeImprovementOptions): boolean {\n const phases = selectedStagePhases(options, EVALUATION_PHASES)\n if (phases.length === 0) return false\n return Boolean(\n options.retrieval ||\n options.diagnose ||\n options.evaluateAnswers ||\n options.decidePromotion ||\n selectedStageRequiredPhases(options, EVALUATION_PHASES).length > 0,\n )\n}\n\nfunction selectedStagePhases(\n options: Pick<KnowledgeImprovementOptions, 'enabledPhases'>,\n stagePhases: readonly RagKnowledgeImprovementPhase[],\n): RagKnowledgeImprovementPhase[] {\n const requested = options.enabledPhases ?? stagePhases\n return requested.filter((phase) => stagePhases.includes(phase))\n}\n\nfunction selectedStageRequiredPhases(\n options: Pick<KnowledgeImprovementOptions, 'requiredPhases'>,\n stagePhases: readonly RagKnowledgeImprovementPhase[],\n): RagKnowledgeImprovementPhase[] {\n return (options.requiredPhases ?? []).filter((phase) => stagePhases.includes(phase))\n}\n\nfunction mergeLifecycleResults(\n goal: string,\n lifecycles: readonly RunRagKnowledgeImprovementLoopResult[],\n): RunRagKnowledgeImprovementLoopResult | undefined {\n if (lifecycles.length === 0) return undefined\n return {\n goal,\n phases: lifecycles.flatMap((lifecycle) => lifecycle.phases),\n retrieval: lastDefined(lifecycles.map((lifecycle) => lifecycle.retrieval)),\n findings: lifecycles.flatMap((lifecycle) => lifecycle.findings),\n acquisition: lastDefined(lifecycles.map((lifecycle) => lifecycle.acquisition)),\n knowledgeUpdate: lastDefined(lifecycles.map((lifecycle) => lifecycle.knowledgeUpdate)),\n answerQuality: lastDefined(lifecycles.map((lifecycle) => lifecycle.answerQuality)),\n promotion: lastDefined(lifecycles.map((lifecycle) => lifecycle.promotion)),\n }\n}\n\nfunction lastDefined<T>(values: readonly (T | undefined)[]): T | undefined {\n for (let index = values.length - 1; index >= 0; index -= 1) {\n if (values[index] !== undefined) return values[index]\n }\n return undefined\n}\n\nasync function evaluateCandidate(\n runDir: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n snapshot: { root: string; hash: string },\n lifecycle: RunRagKnowledgeImprovementLoopResult | undefined,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<{\n candidate: KnowledgeImprovementCandidateRecord\n evaluation: KnowledgeImprovementMetric\n}> {\n return withBaselineSnapshot(runDir, state.baseHash, async (baselineRoot) => {\n const [baselineIndex, candidateIndex] = await Promise.all([\n buildKnowledgeIndex(baselineRoot),\n buildKnowledgeIndex(snapshot.root),\n ])\n const validation = validateKnowledgeIndex(candidateIndex, { strict: options.strict })\n const readiness = readinessFor(options, candidateIndex)\n const kbQuality = scoreKnowledgeBaseIndex(candidateIndex, {\n strict: options.strict,\n ...options.kbQuality,\n })\n const candidateHash = snapshot.hash\n const metric =\n options.evaluate?.({\n runId: state.runId,\n iteration: candidate.iteration,\n root: options.root,\n baselineRoot,\n candidateRoot: snapshot.root,\n baselineIndex,\n candidateIndex,\n baseHash: state.baseHash,\n candidateHash,\n validation,\n readiness,\n kbQuality,\n lifecycle,\n signal: options.signal,\n }) ??\n defaultKnowledgeImprovementMetric(\n validation,\n readiness,\n options.readinessSpecs,\n kbQuality,\n lifecycle,\n )\n const evaluation = applyLifecycleFailures(normalizeMetric(await metric), lifecycle)\n const measuredHash = await hashKnowledgeBase(snapshot.root)\n if (measuredHash !== candidateHash) {\n throw new Error(\n `knowledge candidate changed during evaluation: expected ${candidateHash}, got ${measuredHash}`,\n )\n }\n candidate.candidateHash = candidateHash\n candidate.promotionPlanHash = knowledgeFileTransactionPlanHash(\n await knowledgeFilePlanEntries(baselineRoot, snapshot.root),\n )\n const evidence = KnowledgeImprovementEvidenceSchema.parse(\n JSON.parse(\n JSON.stringify({\n kind: 'knowledge-improvement-evidence',\n runId: state.runId,\n candidateId: candidate.candidateId,\n iteration: candidate.iteration,\n goalHash: sha256(state.goal),\n baseHash: candidate.baseHash,\n candidateHash,\n promotionPlanHash: candidate.promotionPlanHash,\n validation,\n readiness: readiness ?? null,\n kbQuality,\n evaluation,\n lifecycle: lifecycle ?? null,\n }),\n ),\n )\n candidate.evidenceHash = contentHash(evidence)\n candidate.updatedAt = now().toISOString()\n await writeJsonDurableWithinRoot(\n runDir,\n candidateEvidenceRelativePath(candidate.candidateId),\n evidence,\n )\n await appendLedger(runDir, {\n type: 'candidate.evaluated',\n runId: state.runId,\n candidateId: candidate.candidateId,\n score: evaluation.score,\n passed: evaluation.passed,\n })\n return { candidate, evaluation }\n })\n}\n\nfunction defaultKnowledgeImprovementMetric(\n validation: ValidateKnowledgeResult,\n readiness: EvalKnowledgeBundleBuildResult | undefined,\n readinessSpecs: readonly KnowledgeReadinessSpec[] | undefined,\n kbQuality: KnowledgeBaseQualityReport,\n lifecycle: RunRagKnowledgeImprovementLoopResult | undefined,\n): KnowledgeImprovementMetric {\n const blockingMissing = readiness?.report.blockingMissingRequirements.length ?? 0\n const blockingTotal = readinessSpecs?.filter((spec) => spec.importance === 'blocking').length ?? 0\n const blockingReadiness =\n blockingTotal === 0 ? 1 : Math.max(0, blockingTotal - blockingMissing) / blockingTotal\n const answerQuality = lifecycle?.answerQuality\n ? average(Object.values(lifecycle.answerQuality.metrics).filter(Number.isFinite))\n : 1\n const promotionDecision = lifecycle?.promotion ? (lifecycle.promotion.promoted ? 1 : 0) : 1\n const dimensions = {\n validation: validation.ok ? 1 : 0,\n kb_quality: kbQuality.ok ? 1 : 0,\n blocking_readiness: blockingReadiness,\n answer_quality: answerQuality,\n promotion_decision: promotionDecision,\n }\n const failedReasons = [\n validation.ok ? undefined : 'candidate validation failed',\n kbQuality.ok ? undefined : 'candidate KB quality check failed',\n blockingMissing === 0\n ? undefined\n : `${blockingMissing}/${blockingTotal} blocking knowledge requirements still missing`,\n ].filter((reason): reason is string => Boolean(reason))\n return {\n score: average(Object.values(dimensions)),\n passed: failedReasons.length === 0,\n dimensions,\n notes:\n failedReasons.length === 0 ? 'candidate passed configured checks' : failedReasons.join('; '),\n provenance: {\n evaluator: '@tangle-network/agent-knowledge/default-knowledge-improvement-metric',\n version: '1',\n method: 'deterministic',\n },\n }\n}\n\nfunction applyLifecycleFailures(\n metric: KnowledgeImprovementMetric,\n lifecycle: RunRagKnowledgeImprovementLoopResult | undefined,\n): KnowledgeImprovementMetric {\n const reasons = [\n metric.notes,\n lifecycle?.answerQuality && !lifecycle.answerQuality.passed\n ? 'answer quality failed'\n : undefined,\n lifecycle?.promotion && !lifecycle.promotion.promoted\n ? `promotion decision held: ${lifecycle.promotion.reason}`\n : undefined,\n ].filter((reason): reason is string => Boolean(reason))\n const forcedFailure =\n Boolean(lifecycle?.answerQuality && !lifecycle.answerQuality.passed) ||\n Boolean(lifecycle?.promotion && !lifecycle.promotion.promoted)\n return {\n ...metric,\n passed: metric.passed && !forcedFailure,\n notes: reasons.length > 0 ? reasons.join('; ') : metric.notes,\n }\n}\n\nfunction normalizeMetric(metric: KnowledgeImprovementMetric): KnowledgeImprovementMetric {\n return improvementMetricSchema.parse(metric)\n}\n\nasync function createCandidateWorkspace(\n runDir: string,\n state: KnowledgeImprovementRunState,\n root: string,\n now: () => Date,\n): Promise<KnowledgeImprovementCandidateRecord> {\n const iteration = state.candidates.length + 1\n const candidateId = stableId('kcand', `${state.runId}:${iteration}:${now().toISOString()}`)\n const candidateRoot = candidateWorkspacePath(runDir, candidateId)\n await copyKnowledgeWorkspace(root, candidateRoot)\n const createdAt = now().toISOString()\n return {\n iteration,\n candidateId,\n baseHash: state.baseHash,\n status: 'running',\n createdAt,\n updatedAt: createdAt,\n }\n}\n\nfunction candidateWorkspacePath(runDir: string, candidateId: string): string {\n return join(runDir, 'candidates', safePathSegmentSchema.parse(candidateId), 'workspace')\n}\n\nfunction baselineSnapshotPath(runDir: string): string {\n return join(runDir, 'baseline')\n}\n\nasync function createBaselineSnapshot(\n runDir: string,\n root: string,\n expectedHash: string,\n): Promise<void> {\n const target = baselineSnapshotPath(runDir)\n try {\n await assertBaselineSnapshot(runDir, expectedHash)\n return\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n const preparation = await mkdtemp(join(runDir, 'baseline-prepare-'))\n let activated = false\n try {\n await copyKnowledgeWorkspace(root, preparation)\n const actualHash = await hashKnowledgeBase(preparation)\n if (actualHash !== expectedHash) {\n throw new Error(\n `knowledge base changed while baseline was frozen: expected ${expectedHash}, got ${actualHash}`,\n )\n }\n await renameDurable(preparation, target)\n activated = true\n } finally {\n if (!activated) await rm(preparation, { recursive: true, force: true })\n }\n}\n\nasync function ensureBaselineSnapshot(\n runDir: string,\n root: string,\n expectedHash: string,\n): Promise<void> {\n try {\n await assertBaselineSnapshot(runDir, expectedHash)\n } catch (error) {\n if (!isMissingFile(error)) throw error\n const liveHash = await hashKnowledgeBase(root)\n if (liveHash !== expectedHash) {\n throw new Error(\n 'knowledge improvement baseline snapshot is missing and cannot be reconstructed',\n )\n }\n await createBaselineSnapshot(runDir, root, expectedHash)\n }\n}\n\nasync function assertBaselineSnapshot(runDir: string, expectedHash: string): Promise<void> {\n await withBaselineSnapshot(runDir, expectedHash, () => undefined)\n}\n\nasync function withBaselineSnapshot<T>(\n runDir: string,\n expectedHash: string,\n use: (baselineRoot: string) => Promise<T> | T,\n): Promise<T> {\n return withSafeDirectory(runDir, 'baseline', false, async (baselineRoot) => {\n const actualHash = await hashKnowledgeBase(baselineRoot)\n if (actualHash !== expectedHash) {\n throw new Error(\n `knowledge improvement baseline changed: expected ${expectedHash}, got ${actualHash}`,\n )\n }\n return use(baselineRoot)\n })\n}\n\nasync function withFrozenCandidateWorkspace<T>(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n use: (snapshot: { root: string; hash: string }) => Promise<T> | T,\n): Promise<T> {\n const snapshotsPath = join(\n 'candidates',\n safePathSegmentSchema.parse(candidate.candidateId),\n 'snapshots',\n )\n return withSafeDirectory(runDir, snapshotsPath, true, async (snapshotsDir) => {\n const preparation = await mkdtemp(join(snapshotsDir, 'prepare-'))\n let activated = false\n try {\n await copyKnowledgeWorkspace(candidateRoot, preparation)\n const hash = await hashKnowledgeBase(preparation)\n try {\n const result = await withSafeDirectory(snapshotsDir, hash, false, async (existing) => {\n if ((await hashKnowledgeBase(existing)) !== hash) {\n throw new Error('knowledge candidate snapshot does not match its content identity')\n }\n return use({ root: existing, hash })\n })\n await rm(preparation, { recursive: true, force: true })\n activated = true\n return result\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n await renameDurable(preparation, join(snapshotsDir, hash))\n activated = true\n return withSafeDirectory(snapshotsDir, hash, false, (root) => use({ root, hash }))\n } finally {\n if (!activated) await rm(preparation, { recursive: true, force: true })\n }\n })\n}\n\nfunction clearCandidateMeasurement(candidate: KnowledgeImprovementCandidateRecord): void {\n delete candidate.candidateHash\n delete candidate.evidenceHash\n delete candidate.promotionPlanHash\n}\n\nfunction findActiveCandidate(\n state: KnowledgeImprovementRunState,\n): KnowledgeImprovementCandidateRecord | undefined {\n return [...state.candidates]\n .reverse()\n .find((candidate) => candidate.status === 'candidate-ready' || candidate.status === 'running')\n}\n\nasync function copyKnowledgeWorkspace(sourceRoot: string, targetRoot: string): Promise<void> {\n await rm(targetRoot, { recursive: true, force: true })\n await mkdir(join(targetRoot, 'knowledge'), { recursive: true })\n await mkdir(join(targetRoot, 'raw', 'sources'), { recursive: true })\n await copyIfExists(join(sourceRoot, 'knowledge'), join(targetRoot, 'knowledge'))\n await copyIfExists(join(sourceRoot, 'raw'), join(targetRoot, 'raw'))\n await copyIfExists(\n join(layoutFor(sourceRoot).cacheDir, 'sources.json'),\n join(layoutFor(targetRoot).cacheDir, 'sources.json'),\n )\n await writeKnowledgeIndex(targetRoot)\n}\n\nfunction knowledgeCandidateTransitionPurpose(\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeCandidateTarget,\n): string {\n const action = target === 'candidate' ? 'promotion' : 'restore'\n return `knowledge-${action}:${contentHash(candidate)}`\n}\n\nasync function knowledgeFilePlanEntries(\n sourceRoot: string,\n targetRoot: string,\n): Promise<KnowledgeFileTransactionPlanEntry[]> {\n const [before, after] = await Promise.all([\n knowledgeHashEntries(sourceRoot),\n knowledgeHashEntries(targetRoot),\n ])\n const beforeByPath = new Map(before.map((entry) => [entry.path, entry]))\n const afterByPath = new Map(after.map((entry) => [entry.path, entry]))\n const paths = [\n ...new Set([...before.map((entry) => entry.path), ...after.map((entry) => entry.path)]),\n ].sort((left, right) => left.localeCompare(right))\n return paths.map((path) => {\n assertKnowledgeMutationPath(path)\n const beforeEntry = beforeByPath.get(path)\n const afterEntry = afterByPath.get(path)\n return {\n path,\n beforeHash: beforeEntry?.transactionHash ?? null,\n afterHash: afterEntry?.transactionHash ?? null,\n ...(beforeEntry ? { beforeMode: beforeEntry.mode } : {}),\n ...(afterEntry ? { afterMode: afterEntry.mode } : {}),\n }\n })\n}\n\nasync function knowledgePlanMutations(\n targetRoot: string,\n plan: readonly KnowledgeFileTransactionPlanEntry[],\n): Promise<KnowledgeFileMutation[]> {\n return Promise.all(\n plan.map(async (entry) => {\n if (entry.afterHash === null) return { path: entry.path, content: null }\n const file = await readRegularFileWithinRoot(targetRoot, entry.path)\n const actualHash = createHash('sha256').update(file.bytes).digest('hex')\n if (actualHash !== entry.afterHash || file.mode !== entry.afterMode) {\n throw new Error(`knowledge target file changed before activation: ${entry.path}`)\n }\n return { path: entry.path, content: file.bytes, mode: file.mode }\n }),\n )\n}\n\nfunction assertCandidateTransitionPlan(\n plan: readonly KnowledgeFileTransactionPlanEntry[],\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeCandidateTarget,\n): void {\n const approvedDirection = target === 'candidate' ? plan : reverseKnowledgeFilePlan(plan)\n const actualPlanHash = knowledgeFileTransactionPlanHash(approvedDirection)\n if (actualPlanHash !== candidate.promotionPlanHash) {\n throw new Error(\n `knowledge candidate plan changed after approval: expected ${candidate.promotionPlanHash}, got ${actualPlanHash}`,\n )\n }\n}\n\nfunction assertCandidateTransitionTransaction(\n transaction: KnowledgeFileTransaction,\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeCandidateTarget,\n): void {\n assertCandidateTransitionPlan(transaction.entries, candidate, target)\n}\n\nfunction reverseKnowledgeFilePlan(\n plan: readonly KnowledgeFileTransactionPlanEntry[],\n): KnowledgeFileTransactionPlanEntry[] {\n return plan.map((entry) => ({\n path: entry.path,\n beforeHash: entry.afterHash,\n afterHash: entry.beforeHash,\n ...(entry.afterMode === undefined ? {} : { beforeMode: entry.afterMode }),\n ...(entry.beforeMode === undefined ? {} : { afterMode: entry.beforeMode }),\n }))\n}\n\nasync function ensureCandidateTransitionEvent(\n runDir: string,\n candidateRef: KnowledgeImprovementCandidateRef,\n target: KnowledgeCandidateTarget,\n): Promise<void> {\n if (await hasCandidateTransitionEvent(runDir, candidateRef, target)) return\n await appendLedger(runDir, {\n type: target === 'candidate' ? 'candidate.promoted' : 'candidate.restored',\n runId: candidateRef.runId,\n candidateId: candidateRef.candidateId,\n candidateHash: candidateRef.candidateHash,\n evidenceHash: candidateRef.evidenceHash,\n promotionPlanHash: candidateRef.promotionPlanHash,\n })\n}\n\nasync function hasCandidateTransitionEvent(\n runDir: string,\n candidateRef: KnowledgeImprovementCandidateRef,\n target: KnowledgeCandidateTarget,\n): Promise<boolean> {\n const eventType = target === 'candidate' ? 'candidate.promoted' : 'candidate.restored'\n let matched = false\n for (const row of await loadKnowledgeImprovementEventsFromRun(runDir)) {\n if (row.type !== eventType || row.candidateId !== candidateRef.candidateId) continue\n if (\n row.runId !== candidateRef.runId ||\n row.candidateHash !== candidateRef.candidateHash ||\n row.evidenceHash !== candidateRef.evidenceHash ||\n row.promotionPlanHash !== candidateRef.promotionPlanHash\n ) {\n throw new Error('persisted knowledge activation event conflicts with the approved candidate')\n }\n matched = true\n }\n return matched\n}\n\nexport interface KnowledgeImprovementEvent extends Record<string, unknown> {\n at: string\n type: string\n}\n\nexport async function loadKnowledgeImprovementEvents(\n root: string,\n runId: string,\n): Promise<KnowledgeImprovementEvent[]> {\n const parsedRunId = runIdSchema.parse(runId)\n try {\n return await withKnowledgeImprovementRun(root, parsedRunId, false, (runDir) =>\n loadKnowledgeImprovementEventsFromRun(runDir),\n )\n } catch (error) {\n if (isMissingFile(error)) return []\n throw error\n }\n}\n\nasync function loadKnowledgeImprovementEventsFromRun(\n runDir: string,\n): Promise<KnowledgeImprovementEvent[]> {\n const events: KnowledgeImprovementEvent[] = []\n try {\n for (const file of await listRegularFilesWithinRoot(runDir, 'events')) {\n const name = file.path.slice('events/'.length)\n if (name.includes('/') || !name.endsWith('.json')) {\n throw new Error(`knowledge event store contains an unsupported entry: ${name}`)\n }\n events.push(parseKnowledgeImprovementEvent(JSON.parse(file.bytes.toString('utf8'))))\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n\n const unique = new Map<string, KnowledgeImprovementEvent>()\n for (const event of events) {\n const { at: _at, ...semantic } = event\n unique.set(contentHash(semantic), event)\n }\n return [...unique.values()].sort((left, right) => left.at.localeCompare(right.at))\n}\n\nfunction parseKnowledgeImprovementEvent(value: unknown): KnowledgeImprovementEvent {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('knowledge improvement event is not an object')\n }\n const event = value as Record<string, unknown>\n if (typeof event.at !== 'string' || typeof event.type !== 'string') {\n throw new Error('knowledge improvement event is missing at or type')\n }\n return event as KnowledgeImprovementEvent\n}\n\nasync function copyIfExists(source: string, target: string): Promise<void> {\n let sourceStat: Awaited<ReturnType<typeof lstat>>\n try {\n sourceStat = await lstat(source)\n } catch (error) {\n if (isMissingFile(error)) return\n throw error\n }\n if (!sourceStat.isDirectory() && !sourceStat.isFile()) {\n throw new Error(`knowledge surface contains an unsupported filesystem entry: ${source}`)\n }\n await mkdir(dirname(target), { recursive: true })\n await cp(source, target, { recursive: sourceStat.isDirectory(), dereference: false })\n}\n\nexport async function hashKnowledgeBase(root: string): Promise<string> {\n return withKnowledgeRead(root, () => hashKnowledgeBaseUnlocked(root))\n}\n\nasync function hashKnowledgeBaseUnlocked(root: string): Promise<string> {\n const entries = await knowledgeHashEntries(root)\n return sha256(JSON.stringify(entries.map(({ path, hash, mode }) => ({ path, hash, mode }))))\n}\n\ninterface KnowledgeFileIdentity {\n path: string\n hash: string\n transactionHash: string\n mode: number\n}\n\nasync function knowledgeHashEntries(root: string): Promise<KnowledgeFileIdentity[]> {\n const entries: KnowledgeFileIdentity[] = []\n for (const rel of ['knowledge', 'raw']) {\n try {\n for (const file of await listRegularFilesWithinRoot(root, rel)) {\n entries.push(knowledgeFileIdentity(file.path, file.bytes, file.mode))\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n }\n const sourceRegistry = relative(root, layoutFor(root).sourceRegistryPath).replace(/\\\\/g, '/')\n try {\n const file = await readRegularFileWithinRoot(root, sourceRegistry)\n entries.push(knowledgeFileIdentity(sourceRegistry, file.bytes, file.mode))\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n entries.sort((a, b) => a.path.localeCompare(b.path))\n return entries\n}\n\nfunction knowledgeFileIdentity(path: string, bytes: Buffer, mode: number): KnowledgeFileIdentity {\n return {\n path,\n hash: sha256(bytes.toString('base64')),\n transactionHash: createHash('sha256').update(bytes).digest('hex'),\n mode,\n }\n}\n\nasync function acquireRunLease(\n runDir: string,\n options: { ownerId: string; ttlMs: number },\n): Promise<LeaseHandle> {\n const path = join(runDir, 'run.lock.durable')\n const acquired = await acquireDurableFileLock(runDir, {\n lockfilePath: path,\n staleMs: options.ttlMs,\n })\n return {\n ownerId: options.ownerId,\n assertOwned: acquired.assertOwned,\n release: acquired.release,\n }\n}\n\nasync function blockRun(\n runDir: string,\n state: KnowledgeImprovementRunState,\n reason: string,\n onState: KnowledgeImprovementOptions['onState'],\n now: () => Date,\n): Promise<KnowledgeImprovementRunState> {\n state.status = 'blocked'\n state.blockedReason = reason\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, onState)\n return state\n}\n\nasync function saveState(\n runDir: string,\n state: KnowledgeImprovementRunState,\n onState?: KnowledgeImprovementOptions['onState'],\n): Promise<void> {\n await writeJsonDurableWithinRoot(\n runDir,\n 'state.json',\n KnowledgeImprovementRunStateSchema.parse(state),\n )\n await onState?.(state)\n}\n\nasync function appendLedger(runDir: string, value: Record<string, unknown>): Promise<void> {\n const type = value.type\n if (typeof type !== 'string' || type.length === 0) {\n throw new Error('knowledge improvement event requires a type')\n }\n const relativePath = join('events', `${contentHash(value)}.json`).replace(/\\\\/g, '/')\n try {\n const file = await readRegularFileWithinRoot(runDir, relativePath)\n const existing = parseKnowledgeImprovementEvent(JSON.parse(file.bytes.toString('utf8')))\n const { at: _at, ...semantic } = existing\n if (canonicalJson(semantic) !== canonicalJson(value)) {\n throw new Error('knowledge improvement event identity conflicts with durable content')\n }\n return\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n await writeJsonDurableWithinRoot(runDir, relativePath, {\n at: new Date().toISOString(),\n ...value,\n })\n}\n\nfunction candidateEvidenceRelativePath(candidateId: string): string {\n return join('candidates', safePathSegmentSchema.parse(candidateId), 'evidence.json').replace(\n /\\\\/g,\n '/',\n )\n}\n\nfunction descendantPath(root: string, path: string): string | undefined {\n const value = relative(resolve(root), resolve(path)).replace(/\\\\/g, '/')\n if (value === '' || value === '..' || value.startsWith('../') || isAbsolute(value))\n return undefined\n return value\n}\n\nfunction assertExactCandidatePlatform(): void {\n if (process.platform !== 'linux') {\n throw new Error('exact knowledge candidate workflows require Linux directory descriptors')\n }\n}\n\nfunction average(values: readonly number[]): number {\n const finite = values.filter(Number.isFinite)\n if (finite.length === 0) return 0\n return finite.reduce((sum, value) => sum + value, 0) / finite.length\n}\n","/**\n * Claim-grounding mode for `runVerifiedResearchLoop`.\n *\n * The two-agent loop's existing verifier judges a source's on-topic RELEVANCE\n * (is this page about the goal?). On the topic sets we have measured, its\n * cleanliness win is dominated by DE-DUPLICATION — which a deterministic\n * content-hash / canonical-URL check captures at ~none of the LLM premium (see\n * `docs/results/cost-quality.md`). That makes the LLM verifier look expensive\n * for what a cheap rule already does.\n *\n * Claim-grounding targets a DIFFERENT, harder error band: a citation that is\n * relevant and unique but **misattributed** — the page is on-topic, the URL is\n * real, yet the specific CLAIM the source is cited for does NOT actually appear\n * in the page. This is the citation-fabrication failure mode of LLM research:\n * the model writes a plausible sentence and hangs a real URL off it that never\n * says any such thing. Neither de-dup nor a relevance judge catches it (both can\n * pass a misattributed-but-on-topic page); only checking the claim against the\n * fetched text does.\n *\n * The check is EXECUTABLE GROUND TRUTH, not another LLM opinion: the worker\n * attaches the specific claim it is citing the source for, and the verifier\n * tests whether that claim is PRESENT (verbatim, normalized, or as a sufficient\n * content-word overlap / close paraphrase) in the `htmlToText` output of the\n * page the worker actually fetched. A claim that is not grounded is rejected as\n * misattributed. Because the oracle is deterministic text presence — not a model\n * call — it is a deployable, non-oracle verifier: it can run in production with\n * zero inference cost, OR be composed with the LLM relevance verifier so the\n * loop rejects BOTH off-topic AND misattributed sources.\n *\n * This module is content-free and any-topic: it adds (1) a way for a proposal to\n * carry the claim it is cited for, (2) the `groundClaimInText` oracle, and (3) a\n * `ResearchDriver` that gates on grounding. It composes the existing\n * `ResearchDriver` / `ResearchSourceProposal` contracts and the shipped\n * `htmlToText`; it reinvents none of them.\n */\n\nimport type {\n ResearchSourceProposal,\n SourceVerdict,\n SourceVerificationContext,\n} from './two-agent-research-loop'\nimport {\n createTangleRouterClient,\n type RouterClient,\n type TangleRouterOptions,\n} from './web-research-worker'\n\n/**\n * Metadata key under which a proposal carries the specific claim it is cited\n * for. The worker sets `metadata[citedClaimKey] = '<the claim>'`; the\n * claim-grounding driver reads it and checks it against the fetched page text.\n */\nexport const citedClaimKey = 'citedClaim'\n\n/** Read the cited claim a proposal carries, if any. */\nexport function citedClaimOf(source: ResearchSourceProposal): string | undefined {\n const claim = source.metadata?.[citedClaimKey]\n return typeof claim === 'string' && claim.trim() ? claim.trim() : undefined\n}\n\n/** Attach a cited claim to a proposal (immutably returns a new proposal). */\nexport function withCitedClaim(\n source: ResearchSourceProposal,\n claim: string,\n): ResearchSourceProposal {\n return { ...source, metadata: { ...source.metadata, [citedClaimKey]: claim } }\n}\n\nexport interface GroundingResult {\n /** True when the claim is sufficiently present in the page text. */\n grounded: boolean\n /** How the claim matched (or why it didn't). For audit/notes. */\n mode: 'verbatim' | 'normalized' | 'overlap' | 'absent' | 'empty-claim' | 'empty-text'\n /**\n * Fraction of the claim's content words found in the page text. 1 for a\n * verbatim/normalized hit; the measured overlap otherwise.\n */\n overlap: number\n /** Content words present in the claim but NOT in the page text. */\n missingWords: string[]\n}\n\nexport interface GroundClaimOptions {\n /**\n * Minimum fraction of the claim's content words that must appear in the page\n * text to count as a close paraphrase when there is no verbatim/normalized\n * hit. Default 0.7 — a high bar, because a misattribution is exactly a claim\n * whose specific words the page does not contain.\n */\n minOverlap?: number\n /**\n * Content words shorter than this are ignored (drops \"the\", \"of\", \"is\", …)\n * and never count toward overlap. Default 3.\n */\n minWordLength?: number\n}\n\n/**\n * Stopwords stripped before overlap scoring so the bar measures the claim's\n * SUBSTANTIVE words (the numbers, nouns, methods it asserts), not filler a\n * misattributed page would trivially share with the real one.\n */\nconst stopwords = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'but',\n 'of',\n 'to',\n 'in',\n 'on',\n 'for',\n 'with',\n 'as',\n 'by',\n 'at',\n 'from',\n 'that',\n 'this',\n 'these',\n 'those',\n 'it',\n 'its',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'has',\n 'have',\n 'had',\n 'can',\n 'will',\n 'would',\n 'should',\n 'may',\n 'might',\n 'not',\n 'no',\n 'than',\n 'then',\n 'over',\n 'under',\n 'about',\n 'into',\n 'their',\n 'they',\n 'them',\n])\n\n/** Normalize for presence checks: lowercase, collapse whitespace + punctuation. */\nfunction normalize(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** The claim's substantive content words (deduped, stopwords + short words removed). */\nfunction contentWords(claim: string, minWordLength: number): string[] {\n const words = normalize(claim)\n .split(' ')\n .filter((word) => word.length >= minWordLength && !stopwords.has(word))\n return [...new Set(words)]\n}\n\n/**\n * THE ORACLE. Is `claim` grounded in `pageText` (the `htmlToText` output of the\n * page the worker fetched)? Deterministic, no model call:\n *\n * 1. verbatim — the claim string appears as-is (case-insensitive).\n * 2. normalized — the claim appears after collapsing punctuation/whitespace\n * on both sides (so \"5.4x\" vs \"5.4 x\", smart quotes, etc. still match).\n * 3. overlap — a close paraphrase: at least `minOverlap` of the claim's\n * substantive content words appear in the page text. A misattributed page\n * fails here because the SPECIFIC words the claim asserts are absent.\n *\n * Returns the match mode, the measured overlap, and the missing content words —\n * enough for the driver to give a precise rejection reason and for a test/doc to\n * audit WHY a claim grounded or didn't.\n */\nexport function groundClaimInText(\n claim: string,\n pageText: string,\n options: GroundClaimOptions = {},\n): GroundingResult {\n const minOverlap = options.minOverlap ?? 0.7\n const minWordLength = Math.max(1, options.minWordLength ?? 3)\n\n const claimTrimmed = claim.trim()\n if (!claimTrimmed) return { grounded: false, mode: 'empty-claim', overlap: 0, missingWords: [] }\n if (!pageText.trim()) return { grounded: false, mode: 'empty-text', overlap: 0, missingWords: [] }\n\n const haystackLower = pageText.toLowerCase()\n if (haystackLower.includes(claimTrimmed.toLowerCase())) {\n return { grounded: true, mode: 'verbatim', overlap: 1, missingWords: [] }\n }\n\n const haystackNorm = normalize(pageText)\n const claimNorm = normalize(claimTrimmed)\n if (claimNorm && haystackNorm.includes(claimNorm)) {\n return { grounded: true, mode: 'normalized', overlap: 1, missingWords: [] }\n }\n\n const words = contentWords(claimTrimmed, minWordLength)\n if (words.length === 0) {\n // The claim has no substantive content words (all stopwords/short). With no\n // verbatim/normalized hit there is nothing to ground — treat as absent.\n return { grounded: false, mode: 'absent', overlap: 0, missingWords: [] }\n }\n // Word-boundary presence so \"rotary\" does not match inside \"rotaryxyz\".\n const present = words.filter((word) =>\n new RegExp(`\\\\b${word.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(haystackNorm),\n )\n const missingWords = words.filter((word) => !present.includes(word))\n const overlap = present.length / words.length\n const grounded = overlap >= minOverlap\n return { grounded, mode: grounded ? 'overlap' : 'absent', overlap, missingWords }\n}\n\nexport interface ClaimGroundingDriverOptions extends GroundClaimOptions {\n /**\n * Optional second verifier to compose AFTER grounding passes. When set, a\n * source must BOTH ground its claim AND pass this verifier (e.g. the LLM\n * relevance driver's `verifySource`). Lets the loop reject off-topic AND\n * misattributed sources in one driver. Omit for the pure, zero-inference\n * grounding gate.\n */\n relevanceVerifier?: (\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ) => Promise<SourceVerdict> | SourceVerdict\n /**\n * What to do when a proposal carries NO cited claim. `'reject'` (default) is\n * fail-closed: in claim-grounding mode every source must declare what it is\n * cited for, so an un-annotated source is treated as ungrounded. `'accept'`\n * lets un-annotated sources through to the relevance verifier (if any) —\n * useful when mixing annotated and legacy proposals.\n */\n onMissingClaim?: 'reject' | 'accept'\n}\n\n/**\n * A `ResearchDriver`-shaped verifier (just the `verifySource` arm) that gates on\n * CLAIM GROUNDING: it rejects a source whose cited claim is not present in its\n * fetched page text — a misattributed / fabricated citation — and (optionally)\n * composes a relevance verifier after grounding passes.\n *\n * The returned function matches `ResearchDriver['verifySource']`, so it drops\n * straight into `runVerifiedResearchLoop` as `{ verifySource: createClaimGroundingVerifier(...) }`.\n */\nexport function createClaimGroundingVerifier(options: ClaimGroundingDriverOptions = {}) {\n const onMissingClaim = options.onMissingClaim ?? 'reject'\n return async function verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> {\n const claim = citedClaimOf(source)\n if (!claim) {\n if (onMissingClaim === 'reject') {\n return {\n accept: false,\n reason: 'no cited claim: claim-grounding mode requires every source to declare its claim',\n }\n }\n // accept-on-missing: fall through to the relevance verifier (or accept).\n return options.relevanceVerifier ? options.relevanceVerifier(source, ctx) : { accept: true }\n }\n\n const grounding = groundClaimInText(claim, source.text, options)\n if (!grounding.grounded) {\n const detail =\n grounding.mode === 'empty-text'\n ? 'fetched page has no text'\n : `claim not found in the fetched page (overlap ${(grounding.overlap * 100).toFixed(0)}%${\n grounding.missingWords.length\n ? `, missing: ${grounding.missingWords.slice(0, 6).join(', ')}`\n : ''\n })`\n return {\n accept: false,\n reason: `misattributed citation: ${detail}`,\n }\n }\n\n // Claim is grounded. Compose the relevance verifier if one was provided.\n if (options.relevanceVerifier) return options.relevanceVerifier(source, ctx)\n return { accept: true }\n }\n}\n\nexport interface WorkerClaimDecorationOptions {\n router?: RouterClient\n router_options?: TangleRouterOptions\n /** Max output tokens for the claim-extraction call. Default 1200 (glm floor). */\n maxTokens?: number\n}\n\n/**\n * Ask an LLM to state, for one source, the single specific factual claim a\n * researcher would cite THIS page for toward the goal. Used to DECORATE the\n * sources a relevance-only worker produced with the claim a citation would make,\n * so the claim-grounding verifier has something executable to check. The model\n * is told to ground the claim in the provided excerpt; the verifier then checks\n * it against the FULL page text independently — the model does not get to mark\n * its own homework.\n *\n * Returns the proposal annotated via `withCitedClaim`, or the original proposal\n * unchanged if the model returns nothing parseable (the verifier's\n * `onMissingClaim` policy then decides).\n */\nexport function createClaimDecorator(options: WorkerClaimDecorationOptions = {}) {\n const maxTokens = options.maxTokens ?? 1200\n return async function decorate(\n source: ResearchSourceProposal,\n goal: string,\n ): Promise<ResearchSourceProposal> {\n const router = options.router ?? createTangleRouterClient(options.router_options)\n const excerpt = source.text.slice(0, 1500)\n const system =\n 'You extract the single most important factual claim a researcher would cite a page for. ' +\n \"State ONE concrete, checkable sentence using the page's own key terms and numbers. \" +\n 'Do NOT invent facts not in the excerpt. Respond with ONLY the claim sentence, no prose.'\n const user = [\n `Research goal: ${goal}`,\n `Page title: ${source.title ?? '(none)'}`,\n `Page excerpt:\\n${excerpt}`,\n 'The single claim this page should be cited for:',\n ].join('\\n\\n')\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n maxTokens,\n )\n } catch {\n return source\n }\n const claim = raw.trim().split('\\n')[0]?.trim()\n if (!claim) return source\n return withCitedClaim(source, claim)\n }\n}\n","import type { JsonValue, JudgeConfig, Scenario } from '@tangle-network/agent-eval/campaign'\nimport { groundClaimInText } from './claim-grounding'\nimport { lintKnowledgeIndex } from './lint'\nimport type { RagAnswerQualityResult, RagGapFinding } from './rag-improvement-loop'\nimport type { KnowledgeIndex } from './types'\nimport { validateKnowledgeIndex } from './validate'\n\nexport type RagEvalProvider =\n | 'agent-knowledge'\n | 'ragas'\n | 'deepeval'\n | 'trulens'\n | 'ragchecker'\n | 'custom'\n\nexport type RagEvalMetricKey =\n | 'context_precision'\n | 'context_recall'\n | 'context_relevance'\n | 'context_sufficiency'\n | 'faithfulness'\n | 'groundedness'\n | 'answer_relevance'\n | 'answer_correctness'\n | 'citation_support'\n | 'abstention'\n | 'unsupported_answer_rate'\n\nexport type RagEvalSlice =\n | 'known-answer'\n | 'paraphrase'\n | 'distractor'\n | 'freshness'\n | 'multi-source'\n | 'unanswerable'\n | 'long-tail'\n | 'custom'\n\nexport interface RagEvalContext {\n id: string\n text: string\n rank?: number\n pageId?: string\n sourceId?: string\n anchorId?: string\n stale?: boolean\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagEvalCitation {\n id: string\n claimId?: string\n contextId?: string\n pageId?: string\n sourceId?: string\n anchorId?: string\n quote?: string\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagEvalClaim {\n id: string\n text: string\n citationIds?: readonly string[]\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagRequiredContext {\n id?: string\n text?: string\n pageId?: string\n sourceId?: string\n anchorId?: string\n}\n\nexport interface RagAnswerEvalScenario extends Scenario {\n kind: 'rag-answer-eval'\n query: string\n referenceAnswer?: string\n expectedClaims?: readonly string[]\n forbiddenClaims?: readonly string[]\n requiredContext?: readonly RagRequiredContext[]\n unanswerable?: boolean\n requireCitations?: boolean\n slices?: readonly RagEvalSlice[]\n thresholds?: Partial<Record<RagEvalMetricKey, number>>\n}\n\nexport interface ExternalRagEvalScore {\n provider: RagEvalProvider | string\n scores: Record<string, number>\n reasons?: Record<string, string>\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagAnswerEvalArtifact {\n query: string\n answer: string\n contexts: readonly RagEvalContext[]\n claims?: readonly RagEvalClaim[]\n citations?: readonly RagEvalCitation[]\n abstained?: boolean\n durationMs?: number\n costUsd?: number\n externalScores?: readonly ExternalRagEvalScore[]\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagAnswerMetricSummary {\n metrics: Record<RagEvalMetricKey, number>\n composite: number\n passed: boolean\n findings: readonly RagGapFinding[]\n claimCount: number\n supportedClaimCount: number\n citedClaimCount: number\n supportedCitationCount: number\n matchedRequiredContextCount: number\n requiredContextCount: number\n providerScores: Record<string, Record<RagEvalMetricKey, number>>\n}\n\nexport interface RagAnswerQualityJudgeOptions {\n name?: string\n thresholds?: Partial<Record<RagEvalMetricKey, number>>\n weights?: Partial<Record<RagEvalMetricKey, number>>\n externalScorePolicy?: 'prefer-external' | 'deterministic-first'\n minClaimSupport?: number\n}\n\nexport interface RagAnswerEvalCase {\n scenario: RagAnswerEvalScenario\n artifact: RagAnswerEvalArtifact\n}\n\nexport interface RagAnswerQualityHookOptions {\n scenarios: readonly RagAnswerEvalScenario[]\n run: (scenario: RagAnswerEvalScenario) => MaybePromise<RagAnswerEvalArtifact>\n externalEvaluator?: (\n item: RagAnswerEvalCase,\n ) => MaybePromise<ExternalRagEvalScore | readonly ExternalRagEvalScore[] | undefined>\n thresholds?: Partial<Record<RagEvalMetricKey, number>>\n weights?: Partial<Record<RagEvalMetricKey, number>>\n}\n\nexport interface RagCalibrationOptions {\n scenario: RagAnswerEvalScenario\n strong: RagAnswerEvalArtifact\n weak: RagAnswerEvalArtifact\n judge?: JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario>\n minStrongScore?: number\n maxWeakScore?: number\n signal?: AbortSignal\n}\n\nexport interface RagCalibrationResult {\n passed: boolean\n strongScore: number\n weakScore: number\n gap: number\n}\n\nexport interface KnowledgeBaseQualityOptions {\n now?: Date\n strict?: boolean\n minCitationRate?: number\n maxStaleSourceRate?: number\n}\n\nexport interface KnowledgeBaseQualityReport {\n ok: boolean\n metrics: {\n page_count: number\n source_count: number\n citation_rate: number\n source_backed_page_rate: number\n stale_source_rate: number\n duplicate_source_hash_rate: number\n lint_error_count: number\n lint_warning_count: number\n }\n findings: readonly RagGapFinding[]\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nconst defaultThresholds: Partial<Record<RagEvalMetricKey, number>> = {\n context_precision: 0.5,\n context_recall: 0.8,\n context_relevance: 0.5,\n context_sufficiency: 0.8,\n faithfulness: 0.9,\n answer_relevance: 0.7,\n citation_support: 0.9,\n abstention: 1,\n unsupported_answer_rate: 0,\n}\n\nconst defaultWeights: Partial<Record<RagEvalMetricKey, number>> = {\n context_relevance: 1,\n context_sufficiency: 1,\n faithfulness: 2,\n answer_relevance: 1,\n citation_support: 1,\n abstention: 1,\n}\n\nconst metricAliases: Record<string, RagEvalMetricKey> = {\n answer_correctness: 'answer_correctness',\n answer_relevance: 'answer_relevance',\n answer_relevancy: 'answer_relevance',\n answerrelevancy: 'answer_relevance',\n context_precision: 'context_precision',\n context_recall: 'context_recall',\n context_relevance: 'context_relevance',\n context_relevancy: 'context_relevance',\n context_sufficiency: 'context_sufficiency',\n contextual_precision: 'context_precision',\n contextual_recall: 'context_recall',\n contextual_relevancy: 'context_relevance',\n faithfulness: 'faithfulness',\n groundedness: 'groundedness',\n claim_recall: 'context_recall',\n claim_precision: 'faithfulness',\n citation_support: 'citation_support',\n abstention: 'abstention',\n unsupported_answer_rate: 'unsupported_answer_rate',\n}\n\nexport function ragAnswerQualityJudge(\n options: RagAnswerQualityJudgeOptions = {},\n): JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario> {\n return {\n name: options.name ?? 'rag-answer-quality',\n dimensions: [\n { key: 'context_precision', description: 'share of retrieved context that is useful' },\n { key: 'context_recall', description: 'share of required evidence present in context' },\n { key: 'context_relevance', description: 'context relevance to the query and answer target' },\n { key: 'context_sufficiency', description: 'whether context is enough to answer' },\n { key: 'faithfulness', description: 'share of answer claims supported by retrieved context' },\n { key: 'answer_relevance', description: 'answer addresses the user query' },\n { key: 'answer_correctness', description: 'answer contains expected claims' },\n { key: 'citation_support', description: 'citations support the claims they cite' },\n { key: 'abstention', description: 'answer abstains exactly when the case is unanswerable' },\n ],\n appliesTo: (scenario) => scenario.kind === 'rag-answer-eval',\n async score({ artifact, scenario }) {\n const summary = scoreRagAnswerArtifact(artifact, scenario, options)\n return {\n dimensions: summary.metrics,\n composite: summary.composite,\n notes: summary.findings.map((finding) => finding.message).join('; '),\n }\n },\n }\n}\n\nexport function scoreRagAnswerArtifact(\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n options: RagAnswerQualityJudgeOptions = {},\n): RagAnswerMetricSummary {\n const claims = normalizeClaims(artifact)\n const abstained = artifact.abstained ?? looksLikeAbstention(artifact.answer)\n const requiredTargets = requiredContextTargets(scenario)\n const matchedRequiredContextCount = requiredTargets.filter((target) =>\n artifact.contexts.some((context) => contextMatchesTarget(context, target)),\n ).length\n const requiredContextCount = requiredTargets.length\n const contextRecall =\n requiredContextCount === 0\n ? neutralScore(Boolean(scenario.unanswerable) || artifact.contexts.length > 0)\n : matchedRequiredContextCount / requiredContextCount\n const relevantContextCount = artifact.contexts.filter((context) =>\n contextIsRelevant(context, scenario),\n ).length\n const contextPrecision =\n artifact.contexts.length === 0\n ? scenario.unanswerable\n ? 1\n : 0\n : relevantContextCount / artifact.contexts.length\n const contextRelevance =\n artifact.contexts.length === 0\n ? scenario.unanswerable\n ? 1\n : 0\n : average(artifact.contexts.map((context) => contextRelevanceScore(context, scenario)))\n const contextSufficiency = requiredContextCount === 0 ? contextRelevance : contextRecall\n const support = claims.map((claim) => claimSupport(claim.text, artifact.contexts, options))\n const supportedClaimCount = support.filter(Boolean).length\n const faithfulness =\n claims.length === 0 ? (abstained ? 1 : 0) : supportedClaimCount / Math.max(1, claims.length)\n const citation = scoreCitations(claims, artifact, scenario, options)\n const answerRelevance = scoreAnswerRelevance(artifact, scenario, abstained)\n const answerCorrectness = scoreAnswerCorrectness(artifact, scenario, abstained)\n const abstention = scenario.unanswerable ? (abstained ? 1 : 0) : abstained ? 0 : 1\n const unsupportedAnswerRate =\n claims.length === 0 ? (abstained ? 0 : 1) : 1 - supportedClaimCount / Math.max(1, claims.length)\n\n const deterministicMetrics: Record<RagEvalMetricKey, number> = {\n context_precision: clamp01(contextPrecision),\n context_recall: clamp01(contextRecall),\n context_relevance: clamp01(contextRelevance),\n context_sufficiency: clamp01(contextSufficiency),\n faithfulness: clamp01(faithfulness),\n groundedness: clamp01(faithfulness),\n answer_relevance: clamp01(answerRelevance),\n answer_correctness: clamp01(answerCorrectness),\n citation_support: clamp01(citation.support),\n abstention: clamp01(abstention),\n unsupported_answer_rate: clamp01(unsupportedAnswerRate),\n }\n const providerScores = normalizeExternalRagScores(artifact.externalScores ?? [])\n const metrics = mergeMetrics(deterministicMetrics, providerScores, options.externalScorePolicy)\n const thresholds = { ...defaultThresholds, ...scenario.thresholds, ...options.thresholds }\n const findings = diagnoseRagAnswerFailure(metrics, scenario, thresholds)\n const composite = weightedComposite(metrics, options.weights ?? defaultWeights)\n\n return {\n metrics,\n composite,\n passed: findings.every(\n (finding) => finding.severity !== 'error' && finding.severity !== 'critical',\n ),\n findings,\n claimCount: claims.length,\n supportedClaimCount,\n citedClaimCount: citation.citedClaimCount,\n supportedCitationCount: citation.supportedCitationCount,\n matchedRequiredContextCount,\n requiredContextCount,\n providerScores,\n }\n}\n\nexport function diagnoseRagAnswerFailure(\n metrics: Record<RagEvalMetricKey, number>,\n scenario: RagAnswerEvalScenario,\n thresholds: Partial<Record<RagEvalMetricKey, number>> = defaultThresholds,\n): RagGapFinding[] {\n const findings: RagGapFinding[] = []\n if (below(metrics.context_recall, thresholds.context_recall)) {\n findings.push({\n id: `${scenario.id}:context-recall`,\n kind: scenario.slices?.includes('multi-source')\n ? 'missing-multihop-evidence'\n : 'retrieval-miss',\n severity: 'error',\n scenarioId: scenario.id,\n message: 'Required evidence was not present in retrieved context.',\n evidence: { context_recall: metrics.context_recall },\n })\n }\n if (below(metrics.context_precision, thresholds.context_precision)) {\n findings.push({\n id: `${scenario.id}:context-precision`,\n kind: 'retrieval-noise',\n severity: 'warning',\n scenarioId: scenario.id,\n message: 'Retrieved context contains too much irrelevant material.',\n evidence: { context_precision: metrics.context_precision },\n })\n }\n if (below(metrics.faithfulness, thresholds.faithfulness)) {\n findings.push({\n id: `${scenario.id}:faithfulness`,\n kind: 'generator-unsupported-claim',\n severity: 'error',\n scenarioId: scenario.id,\n message: 'The answer contains claims not supported by retrieved context.',\n evidence: { faithfulness: metrics.faithfulness },\n })\n }\n if (below(metrics.citation_support, thresholds.citation_support)) {\n findings.push({\n id: `${scenario.id}:citation-support`,\n kind: 'citation-mismatch',\n severity: 'error',\n scenarioId: scenario.id,\n message: 'Citations do not support the claims they are attached to.',\n evidence: { citation_support: metrics.citation_support },\n })\n }\n if (below(metrics.abstention, thresholds.abstention)) {\n findings.push({\n id: `${scenario.id}:abstention`,\n kind: 'incorrect-abstention',\n severity: 'error',\n scenarioId: scenario.id,\n message: scenario.unanswerable\n ? 'The system answered a case marked unanswerable.'\n : 'The system abstained from an answerable case.',\n evidence: { abstention: metrics.abstention },\n })\n }\n return findings\n}\n\nexport function createRagAnswerQualityHook(\n options: RagAnswerQualityHookOptions,\n): () => Promise<RagAnswerQualityResult> {\n return async () => {\n const summaries: RagAnswerMetricSummary[] = []\n const findings: RagGapFinding[] = []\n for (const scenario of options.scenarios) {\n const initialArtifact = await options.run(scenario)\n const external = await options.externalEvaluator?.({ scenario, artifact: initialArtifact })\n const artifact = external\n ? {\n ...initialArtifact,\n externalScores: [\n ...(initialArtifact.externalScores ?? []),\n ...(Array.isArray(external) ? external : [external]),\n ],\n }\n : initialArtifact\n const summary = scoreRagAnswerArtifact(artifact, scenario, {\n thresholds: options.thresholds,\n weights: options.weights,\n })\n summaries.push(summary)\n findings.push(...summary.findings)\n }\n const metrics = aggregateRagAnswerMetrics(summaries)\n return {\n passed: findings.length === 0,\n metrics,\n findings,\n metadata: { scenarioCount: options.scenarios.length },\n }\n }\n}\n\nexport async function calibrateRagAnswerJudge(\n options: RagCalibrationOptions,\n): Promise<RagCalibrationResult> {\n const judge = options.judge ?? ragAnswerQualityJudge()\n const strong = await judge.score({\n artifact: options.strong,\n scenario: options.scenario,\n signal: options.signal ?? new AbortController().signal,\n })\n const weak = await judge.score({\n artifact: options.weak,\n scenario: options.scenario,\n signal: options.signal ?? new AbortController().signal,\n })\n const strongScore = strong.composite\n const weakScore = weak.composite\n const minStrongScore = options.minStrongScore ?? 0.7\n const maxWeakScore = options.maxWeakScore ?? 0.3\n return {\n passed: strongScore >= minStrongScore && weakScore <= maxWeakScore,\n strongScore,\n weakScore,\n gap: strongScore - weakScore,\n }\n}\n\nexport function normalizeExternalRagScores(\n scores: readonly ExternalRagEvalScore[],\n): Record<string, Record<RagEvalMetricKey, number>> {\n const normalized: Record<string, Record<RagEvalMetricKey, number>> = {}\n for (const item of scores) {\n const provider = item.provider || 'custom'\n const providerScores = (normalized[provider] ?? {}) as Record<RagEvalMetricKey, number>\n for (const [key, value] of Object.entries(item.scores)) {\n const canonical = metricAliases[normalizeMetricName(key)]\n if (!canonical) continue\n if (Number.isFinite(value)) providerScores[canonical] = clamp01(value)\n }\n normalized[provider] = providerScores\n }\n return normalized\n}\n\nexport function toRagasEvaluationRows(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n user_input: scenario.query,\n response: artifact.answer,\n retrieved_contexts: artifact.contexts.map((context) => context.text),\n reference: scenario.referenceAnswer,\n reference_contexts: requiredContextTexts(scenario),\n }))\n}\n\nexport function toDeepEvalTestCases(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n input: scenario.query,\n actual_output: artifact.answer,\n expected_output: scenario.referenceAnswer,\n retrieval_context: artifact.contexts.map((context) => context.text),\n context: requiredContextTexts(scenario),\n }))\n}\n\nexport function toTruLensRecords(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n input: scenario.query,\n output: artifact.answer,\n context: artifact.contexts.map((context) => context.text).join('\\n\\n'),\n }))\n}\n\nexport function toRagCheckerRecords(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n query_id: scenario.id,\n query: scenario.query,\n gt_answer: scenario.referenceAnswer,\n response: artifact.answer,\n retrieved_context: artifact.contexts.map((context) => ({\n doc_id: context.id,\n text: context.text,\n })),\n claims: normalizeClaims(artifact).map((claim) => claim.text),\n }))\n}\n\nexport function scoreKnowledgeBaseIndex(\n index: KnowledgeIndex,\n options: KnowledgeBaseQualityOptions = {},\n): KnowledgeBaseQualityReport {\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const lintFindings = lintKnowledgeIndex(index)\n const now = options.now ?? new Date()\n const staleSourceCount = index.sources.filter((source) => {\n return source.validUntil ? Date.parse(source.validUntil) < now.getTime() : false\n }).length\n const sourceHashCounts = new Map<string, number>()\n for (const source of index.sources) {\n sourceHashCounts.set(source.contentHash, (sourceHashCounts.get(source.contentHash) ?? 0) + 1)\n }\n const duplicateSourceHashCount = [...sourceHashCounts.values()].filter(\n (count) => count > 1,\n ).length\n const pagesWithInlineCitations = index.pages.filter(\n (page) => sourceRefs(page.text).length > 0,\n ).length\n const pagesWithSources = index.pages.filter((page) => page.sourceIds.length > 0).length\n const metrics = {\n page_count: index.pages.length,\n source_count: index.sources.length,\n citation_rate: index.pages.length === 0 ? 1 : pagesWithInlineCitations / index.pages.length,\n source_backed_page_rate: index.pages.length === 0 ? 1 : pagesWithSources / index.pages.length,\n stale_source_rate: index.sources.length === 0 ? 0 : staleSourceCount / index.sources.length,\n duplicate_source_hash_rate:\n index.sources.length === 0 ? 0 : duplicateSourceHashCount / index.sources.length,\n lint_error_count: validation.findings.filter((finding) => finding.severity === 'error').length,\n lint_warning_count: lintFindings.filter((finding) => finding.severity === 'warning').length,\n }\n const findings: RagGapFinding[] = []\n if (metrics.lint_error_count > 0) {\n findings.push({\n id: 'kb:lint-errors',\n kind: 'unknown',\n severity: 'critical',\n message: `${metrics.lint_error_count} validation error(s) in the knowledge index.`,\n evidence: { lint_error_count: metrics.lint_error_count },\n })\n }\n if (metrics.citation_rate < (options.minCitationRate ?? 0)) {\n findings.push({\n id: 'kb:citation-rate',\n kind: 'missing-source',\n severity: 'error',\n message: 'Inline citation coverage is below the configured minimum.',\n evidence: { citation_rate: metrics.citation_rate },\n })\n }\n if (metrics.stale_source_rate > (options.maxStaleSourceRate ?? 1)) {\n findings.push({\n id: 'kb:stale-source-rate',\n kind: 'stale-source',\n severity: 'error',\n message: 'Stale source rate exceeds the configured maximum.',\n evidence: { stale_source_rate: metrics.stale_source_rate },\n })\n }\n return { ok: findings.length === 0, metrics, findings }\n}\n\nfunction requiredContextTargets(scenario: RagAnswerEvalScenario): RagRequiredContext[] {\n if (scenario.requiredContext?.length) return [...scenario.requiredContext]\n return (scenario.expectedClaims ?? []).map((text) => ({ text }))\n}\n\nfunction requiredContextTexts(scenario: RagAnswerEvalScenario): string[] {\n return requiredContextTargets(scenario).flatMap((target) => (target.text ? [target.text] : []))\n}\n\nfunction contextMatchesTarget(context: RagEvalContext, target: RagRequiredContext): boolean {\n if (target.id && context.id === target.id) return true\n if (target.pageId && context.pageId === target.pageId) return true\n if (target.sourceId && context.sourceId === target.sourceId) return true\n if (target.anchorId && context.anchorId === target.anchorId) return true\n if (target.text && textSupportScore(target.text, context.text) >= 0.7) return true\n return false\n}\n\nfunction contextIsRelevant(context: RagEvalContext, scenario: RagAnswerEvalScenario): boolean {\n return contextRelevanceScore(context, scenario) >= 0.3\n}\n\nfunction contextRelevanceScore(context: RagEvalContext, scenario: RagAnswerEvalScenario): number {\n const targets = [\n scenario.query,\n scenario.referenceAnswer,\n ...(scenario.expectedClaims ?? []),\n ...requiredContextTexts(scenario),\n ].filter((value): value is string => Boolean(value?.trim()))\n if (targets.length === 0) return 1\n return Math.max(...targets.map((target) => textSupportScore(target, context.text)))\n}\n\nfunction claimSupport(\n claim: string,\n contexts: readonly RagEvalContext[],\n options: Pick<RagAnswerQualityJudgeOptions, 'minClaimSupport'>,\n): boolean {\n if (contexts.length === 0) return false\n const combined = contexts.map((context) => context.text).join('\\n\\n')\n const deterministic = groundClaimInText(claim, combined, {\n minOverlap: options.minClaimSupport ?? 0.7,\n })\n return (\n deterministic.grounded || textSupportScore(claim, combined) >= (options.minClaimSupport ?? 0.7)\n )\n}\n\nfunction scoreCitations(\n claims: readonly RagEvalClaim[],\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n options: Pick<RagAnswerQualityJudgeOptions, 'minClaimSupport'>,\n): { support: number; citedClaimCount: number; supportedCitationCount: number } {\n if (claims.length === 0)\n return { support: scenario.unanswerable ? 1 : 0, citedClaimCount: 0, supportedCitationCount: 0 }\n const citations = artifact.citations ?? []\n const citedClaims = claims.filter((claim) => citationsForClaim(claim, citations).length > 0)\n if (citedClaims.length === 0) {\n return {\n support: scenario.requireCitations ? 0 : 1,\n citedClaimCount: 0,\n supportedCitationCount: 0,\n }\n }\n let supportedCitationCount = 0\n for (const claim of citedClaims) {\n const citedContexts = contextsForClaim(claim, citations, artifact.contexts)\n if (claimSupport(claim.text, citedContexts, options)) supportedCitationCount += 1\n }\n return {\n support: supportedCitationCount / citedClaims.length,\n citedClaimCount: citedClaims.length,\n supportedCitationCount,\n }\n}\n\nfunction citationsForClaim(\n claim: RagEvalClaim,\n citations: readonly RagEvalCitation[],\n): RagEvalCitation[] {\n const claimCitationIds = new Set(claim.citationIds ?? [])\n return citations.filter((citation) => {\n return citation.claimId === claim.id || (citation.id && claimCitationIds.has(citation.id))\n })\n}\n\nfunction contextsForClaim(\n claim: RagEvalClaim,\n citations: readonly RagEvalCitation[],\n contexts: readonly RagEvalContext[],\n): readonly RagEvalContext[] {\n const matchedCitations = citationsForClaim(claim, citations)\n const matchedContexts = contexts.filter((context) =>\n matchedCitations.some((citation) => {\n if (citation.contextId && citation.contextId === context.id) return true\n if (citation.pageId && citation.pageId === context.pageId) return true\n if (citation.sourceId && citation.sourceId === context.sourceId) return true\n if (citation.anchorId && citation.anchorId === context.anchorId) return true\n return false\n }),\n )\n return matchedContexts.length > 0 ? matchedContexts : contexts\n}\n\nfunction scoreAnswerRelevance(\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n abstained: boolean,\n): number {\n if (scenario.unanswerable) return abstained ? 1 : 0\n if (abstained) return 0\n const targets = [\n scenario.referenceAnswer,\n ...(scenario.expectedClaims ?? []),\n scenario.query,\n ].filter((value): value is string => Boolean(value?.trim()))\n return Math.max(...targets.map((target) => textSupportScore(target, artifact.answer)))\n}\n\nfunction scoreAnswerCorrectness(\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n abstained: boolean,\n): number {\n if (scenario.unanswerable) return abstained ? 1 : 0\n const expected = scenario.expectedClaims ?? []\n const forbidden = scenario.forbiddenClaims ?? []\n const expectedScore =\n expected.length === 0\n ? scoreAnswerRelevance(artifact, scenario, abstained)\n : average(expected.map((claim) => textSupportScore(claim, artifact.answer)))\n const forbiddenPenalty =\n forbidden.length === 0\n ? 0\n : forbidden.filter((claim) => textSupportScore(claim, artifact.answer) >= 0.7).length /\n forbidden.length\n return clamp01(expectedScore * (1 - forbiddenPenalty))\n}\n\nfunction normalizeClaims(artifact: RagAnswerEvalArtifact): RagEvalClaim[] {\n if (artifact.claims?.length) return [...artifact.claims]\n return splitSentences(artifact.answer).map((text, index) => ({ id: `claim-${index + 1}`, text }))\n}\n\nfunction splitSentences(text: string): string[] {\n return text\n .split(/(?<=[.!?])\\s+/)\n .map((sentence) => sentence.trim())\n .filter((sentence) => sentence.length > 0 && !looksLikeAbstention(sentence))\n}\n\nfunction looksLikeAbstention(answer: string): boolean {\n const normalized = answer.toLowerCase()\n return [\n \"i don't know\",\n 'i do not know',\n 'not enough information',\n 'cannot answer',\n \"can't answer\",\n 'insufficient information',\n 'no reliable answer',\n ].some((phrase) => normalized.includes(phrase))\n}\n\nfunction mergeMetrics(\n deterministic: Record<RagEvalMetricKey, number>,\n providerScores: Record<string, Record<RagEvalMetricKey, number>>,\n policy: RagAnswerQualityJudgeOptions['externalScorePolicy'] = 'prefer-external',\n): Record<RagEvalMetricKey, number> {\n if (policy === 'deterministic-first') return deterministic\n const merged = { ...deterministic }\n for (const scores of Object.values(providerScores)) {\n for (const [key, value] of Object.entries(scores) as Array<[RagEvalMetricKey, number]>) {\n merged[key] = value\n if (key === 'groundedness') merged.faithfulness = value\n if (key === 'faithfulness') merged.groundedness = value\n }\n }\n return merged\n}\n\nfunction aggregateRagAnswerMetrics(\n summaries: readonly RagAnswerMetricSummary[],\n): Record<string, number> {\n const keys = new Set<RagEvalMetricKey>()\n for (const summary of summaries) {\n for (const key of Object.keys(summary.metrics) as RagEvalMetricKey[]) keys.add(key)\n }\n const out: Record<string, number> = {}\n for (const key of [...keys].sort()) {\n out[key] = average(summaries.map((summary) => summary.metrics[key]))\n }\n out.composite = average(summaries.map((summary) => summary.composite))\n return out\n}\n\nfunction weightedComposite(\n metrics: Record<RagEvalMetricKey, number>,\n weights: Partial<Record<RagEvalMetricKey, number>>,\n): number {\n let weighted = 0\n let total = 0\n for (const [key, weight] of Object.entries(weights) as Array<[RagEvalMetricKey, number]>) {\n if (!Number.isFinite(weight) || weight <= 0) continue\n const metric = metrics[key]\n if (!Number.isFinite(metric)) continue\n const value = key === 'unsupported_answer_rate' ? 1 - metric : metric\n weighted += value * weight\n total += weight\n }\n return total === 0 ? 0 : weighted / total\n}\n\nfunction normalizeMetricName(metric: string): string {\n return metric\n .trim()\n .toLowerCase()\n .replace(/[@/.-]+/g, '_')\n .replace(/\\s+/g, '_')\n}\n\nfunction textSupportScore(needle: string, haystack: string): number {\n const needleWords = contentWords(needle)\n if (needleWords.length === 0) return 0\n const haystackWords = new Set(contentWords(haystack))\n const present = needleWords.filter((word) => haystackWords.has(word))\n return present.length / needleWords.length\n}\n\nfunction contentWords(text: string): string[] {\n const normalized = text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .split(/\\s+/)\n .map((word) => stem(word.trim()))\n .filter((word) => (word.length >= 3 || /^\\d+$/.test(word)) && !stopwords.has(word))\n return [...new Set(normalized)]\n}\n\nfunction stem(word: string): string {\n if (word.endsWith('ies') && word.length > 4) return `${word.slice(0, -3)}y`\n if (word.endsWith('ing') && word.length > 5) return word.slice(0, -3)\n if (word.endsWith('ed') && word.length > 4) return word.slice(0, -2)\n if (word.endsWith('s') && word.length > 3) return word.slice(0, -1)\n return word\n}\n\nfunction sourceRefs(text: string): string[] {\n const refs: string[] = []\n const regex = /\\[\\^([A-Za-z0-9_-]+)(?:#([A-Za-z0-9_.:-]+))?\\]/g\n let match = regex.exec(text)\n while (match !== null) {\n refs.push(match[0])\n match = regex.exec(text)\n }\n return refs\n}\n\nfunction below(metric: number, threshold: number | undefined): boolean {\n return threshold !== undefined && metric < threshold\n}\n\nfunction neutralScore(condition: boolean): number {\n return condition ? 1 : 0\n}\n\nfunction average(values: readonly number[]): number {\n const finite = values.filter(Number.isFinite)\n return finite.length === 0 ? 0 : finite.reduce((sum, value) => sum + value, 0) / finite.length\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.min(1, value))\n}\n\nconst stopwords = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'but',\n 'of',\n 'to',\n 'in',\n 'on',\n 'for',\n 'with',\n 'as',\n 'by',\n 'at',\n 'from',\n 'that',\n 'this',\n 'these',\n 'those',\n 'it',\n 'its',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'has',\n 'have',\n 'had',\n 'can',\n 'will',\n 'would',\n 'should',\n 'may',\n 'might',\n 'not',\n 'no',\n 'than',\n 'then',\n 'over',\n 'under',\n 'about',\n 'into',\n 'their',\n 'they',\n 'them',\n 'what',\n 'when',\n 'where',\n 'who',\n 'why',\n 'how',\n])\n","import {\n blockingKnowledgeEval,\n type ControlEvalResult,\n type ControlRuntimeConfig,\n objectiveEval,\n} from '@tangle-network/agent-eval'\nimport type {\n BuildEvalKnowledgeBundleOptions,\n EvalKnowledgeBundleBuildResult,\n KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport { createKnowledgeEvent } from './events'\nimport { buildKnowledgeIndex } from './indexer'\nimport { lintKnowledgeIndex } from './lint'\nimport { type ApplyWriteBlocksResult, applyKnowledgeWriteBlocks } from './proposals'\nimport { readinessFor } from './readiness-helpers'\nimport {\n type AddSourceOptions,\n type AddSourceTextInput,\n addSourcePath,\n addSourceText,\n} from './sources'\nimport { initKnowledgeBase } from './store'\nimport type { KnowledgeEvent, KnowledgeIndex, KnowledgeLintFinding, SourceRecord } from './types'\nimport {\n type ValidateKnowledgeOptions,\n type ValidateKnowledgeResult,\n validateKnowledgeIndex,\n} from './validate'\n\nexport interface KnowledgeResearchLoopContext {\n root: string\n goal: string\n iteration: number\n index: KnowledgeIndex\n lintFindings: KnowledgeLintFinding[]\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n previousSteps: KnowledgeResearchLoopStep[]\n signal?: AbortSignal\n}\n\nexport interface KnowledgeResearchLoopDecision {\n /**\n * Free-form notes from the researcher. Keep this human-readable; products can\n * store it as the research transcript.\n */\n notes?: string\n /**\n * Local files to register as immutable sources before applying proposals.\n */\n sourcePaths?: string[]\n /**\n * Textual source artifacts discovered by an agent, browser worker, connector,\n * or deep-research process.\n */\n sourceTexts?: AddSourceTextInput[]\n /**\n * Safe write protocol text. The loop parses and applies only accepted\n * `---FILE: knowledge/...---` blocks.\n */\n proposalText?: string\n /**\n * The researcher decides when the wiki is good enough. The loop deliberately\n * does not encode a domain-specific definition of \"done\".\n */\n done?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface KnowledgeResearchLoopStep {\n iteration: number\n notes?: string\n addedSources: SourceRecord[]\n applied?: ApplyWriteBlocksResult\n lintFindings: KnowledgeLintFinding[]\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n event: KnowledgeEvent\n done: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface RunKnowledgeResearchLoopOptions {\n root: string\n goal: string\n maxIterations?: number\n actor?: string\n strict?: ValidateKnowledgeOptions['strict']\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>\n signal?: AbortSignal\n step(\n context: KnowledgeResearchLoopContext,\n ): Promise<KnowledgeResearchLoopDecision> | KnowledgeResearchLoopDecision\n onStep?: (step: KnowledgeResearchLoopStep) => Promise<void> | void\n}\n\nexport interface KnowledgeResearchLoopResult {\n root: string\n goal: string\n iterations: number\n done: boolean\n index: KnowledgeIndex\n lintFindings: KnowledgeLintFinding[]\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n steps: KnowledgeResearchLoopStep[]\n}\n\nexport type KnowledgeControlLoopState = KnowledgeResearchLoopContext\nexport type KnowledgeControlLoopAction = KnowledgeResearchLoopDecision\nexport type KnowledgeControlLoopActionResult = KnowledgeResearchLoopStep\n\nexport interface KnowledgeControlLoopAdapterOptions {\n root: string\n goal: string\n actor?: string\n strict?: ValidateKnowledgeOptions['strict']\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>\n}\n\nexport type KnowledgeControlLoopAdapter = Pick<\n ControlRuntimeConfig<\n KnowledgeControlLoopState,\n KnowledgeControlLoopAction,\n KnowledgeControlLoopActionResult,\n ControlEvalResult\n >,\n 'intent' | 'observe' | 'validate' | 'act' | 'shouldStop'\n>\n\n/**\n * Adapter for running knowledge growth through `agent-eval`'s generic control\n * runtime. The caller still owns `decide`: that can be a proposer agent,\n * reviewer agent, deterministic policy, or a composition of all three.\n */\nexport function createKnowledgeControlLoopAdapter(\n options: KnowledgeControlLoopAdapterOptions,\n): KnowledgeControlLoopAdapter {\n let initialized = false\n const appliedSteps: KnowledgeResearchLoopStep[] = []\n\n return {\n intent: options.goal,\n async observe({ history, abortSignal }) {\n if (abortSignal.aborted) throw new Error('Knowledge control loop aborted')\n if (!initialized) {\n await initKnowledgeBase(options.root)\n initialized = true\n }\n const index = await buildKnowledgeIndex(options.root)\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const lintFindings = lintKnowledgeIndex(index)\n const readiness = readinessFor(options, index)\n return {\n root: options.root,\n goal: options.goal,\n iteration: history.length + 1,\n index,\n lintFindings,\n validation,\n readiness,\n previousSteps: [...appliedSteps],\n signal: abortSignal,\n }\n },\n validate({ state }) {\n const errorFindings = state.validation.findings.filter(\n (finding) => finding.severity === 'error',\n )\n const evals: ControlEvalResult[] = [\n objectiveEval({\n id: 'knowledge-valid',\n passed: state.validation.ok,\n severity: 'critical',\n detail: state.validation.ok\n ? 'Knowledge index is valid.'\n : 'Knowledge index has validation errors.',\n metadata: { findings: state.validation.findings },\n }),\n objectiveEval({\n id: 'knowledge-lint-errors',\n passed: errorFindings.length === 0,\n severity: 'error',\n detail:\n errorFindings.length === 0\n ? 'No lint errors.'\n : `${errorFindings.length} lint error(s).`,\n metadata: { findings: errorFindings },\n }),\n ]\n if (state.readiness) evals.push(blockingKnowledgeEval(state.readiness.report))\n return evals\n },\n shouldStop() {\n return { stop: false, pass: false, reason: 'knowledge driver owns stop decisions' }\n },\n async act(action, ctx) {\n const step = await applyKnowledgeResearchDecision(options, action, ctx.state.iteration)\n appliedSteps.push(step)\n return step\n },\n }\n}\n\nexport async function runKnowledgeResearchLoop(\n options: RunKnowledgeResearchLoopOptions,\n): Promise<KnowledgeResearchLoopResult> {\n const maxIterations = Math.max(1, options.maxIterations ?? 3)\n await initKnowledgeBase(options.root)\n const steps: KnowledgeResearchLoopStep[] = []\n let index = await buildKnowledgeIndex(options.root)\n let validation = validateKnowledgeIndex(index, { strict: options.strict })\n let lintFindings = lintKnowledgeIndex(index)\n let readiness = readinessFor(options, index)\n let done = false\n\n for (let iteration = 1; iteration <= maxIterations; iteration++) {\n if (options.signal?.aborted) throw new Error('Knowledge research loop aborted')\n const decision = await options.step({\n root: options.root,\n goal: options.goal,\n iteration,\n index,\n lintFindings,\n validation,\n readiness,\n previousSteps: steps,\n signal: options.signal,\n })\n\n done = Boolean(decision.done)\n const step = await applyKnowledgeResearchDecision(options, decision, iteration)\n index = await buildKnowledgeIndex(options.root)\n validation = step.validation\n lintFindings = step.lintFindings\n readiness = step.readiness\n steps.push(step)\n await options.onStep?.(step)\n\n if (done) break\n if (!step.applied && step.addedSources.length === 0) break\n }\n\n return {\n root: options.root,\n goal: options.goal,\n iterations: steps.length,\n done,\n index,\n lintFindings,\n validation,\n readiness,\n steps,\n }\n}\n\nasync function applyKnowledgeResearchDecision(\n options: KnowledgeControlLoopAdapterOptions,\n decision: KnowledgeResearchLoopDecision,\n iteration = 1,\n): Promise<KnowledgeResearchLoopStep> {\n const addedSources: SourceRecord[] = []\n for (const sourcePath of decision.sourcePaths ?? []) {\n addedSources.push(...(await addSourcePath(options.root, sourcePath, options.sourceOptions)))\n }\n for (const sourceText of decision.sourceTexts ?? []) {\n addedSources.push(await addSourceText(options.root, sourceText, options.sourceOptions))\n }\n\n const applied = decision.proposalText\n ? await applyKnowledgeWriteBlocks(options.root, decision.proposalText)\n : undefined\n\n const index = await buildKnowledgeIndex(options.root)\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const lintFindings = lintKnowledgeIndex(index)\n const readiness = readinessFor(options, index)\n const done = Boolean(decision.done)\n const event = createKnowledgeEvent({\n type: 'research.iteration',\n actor: options.actor,\n target: options.root,\n metadata: {\n goal: options.goal,\n iteration,\n done,\n addedSourceCount: addedSources.length,\n written: applied?.written,\n warningCount: applied?.warnings.length ?? 0,\n errorCount: validation.findings.filter((finding) => finding.severity === 'error').length,\n },\n })\n\n return {\n iteration,\n notes: decision.notes,\n addedSources,\n applied,\n lintFindings,\n validation,\n readiness,\n event,\n done,\n metadata: decision.metadata,\n }\n}\n","import { stableId } from './ids'\nimport type { KnowledgeEvent, KnowledgeEventType } from './types'\n\nexport interface KnowledgeEventQuery {\n type?: KnowledgeEventType\n target?: string\n limit?: number\n}\n\nexport function createKnowledgeEvent(input: {\n type: KnowledgeEventType\n actor?: string\n target?: string\n metadata?: Record<string, unknown>\n now?: () => Date\n}): KnowledgeEvent {\n const createdAt = (input.now ?? (() => new Date()))().toISOString()\n return {\n id: stableId(\n 'evt',\n `${input.type}:${input.target ?? ''}:${createdAt}:${JSON.stringify(input.metadata ?? {})}`,\n ),\n type: input.type,\n createdAt,\n actor: input.actor,\n target: input.target,\n metadata: input.metadata,\n }\n}\n","import {\n acquisitionPlansForKnowledgeGaps,\n type DataAcquisitionPlan,\n type KnowledgeAcquisitionMode,\n type KnowledgeBundle,\n type KnowledgeFreshness,\n type KnowledgeImportance,\n type KnowledgeReadinessReport,\n type KnowledgeRequirement,\n type KnowledgeRequirementCategory,\n type KnowledgeSensitivity,\n scoreKnowledgeReadiness,\n type UserQuestion,\n userQuestionsForKnowledgeGaps,\n} from '@tangle-network/agent-eval'\nimport { stringMetadata } from './metadata'\nimport { searchKnowledge } from './search'\nimport type { KnowledgeIndex, KnowledgeSearchResult } from './types'\n\nexport interface KnowledgeReadinessSpec {\n id: string\n description: string\n query: string\n requiredFor: string[]\n category: KnowledgeRequirementCategory\n acquisitionMode: KnowledgeAcquisitionMode\n importance: KnowledgeImportance\n freshness: KnowledgeFreshness\n sensitivity: KnowledgeSensitivity\n confidenceNeeded: number\n fallbackPolicy?: KnowledgeRequirement['fallbackPolicy']\n minSources?: number\n minHits?: number\n metadata?: Record<string, unknown>\n}\n\n/**\n * Defaults applied by `defineReadinessSpec` when the caller omits the field.\n *\n * These are deliberately conservative: a domain-specific topic that an agent\n * needs grounded to a high-confidence threshold from at least one authoritative\n * source. Override any field to specialise (e.g. `freshness: 'daily'` for a\n * topic that must reflect today's regulatory state).\n */\nexport const READINESS_SPEC_DEFAULTS = {\n category: 'domain_specific',\n acquisitionMode: 'search_web',\n importance: 'high',\n freshness: 'monthly',\n sensitivity: 'public',\n confidenceNeeded: 0.7,\n minSources: 1,\n minHits: 2,\n} as const satisfies Pick<\n KnowledgeReadinessSpec,\n | 'category'\n | 'acquisitionMode'\n | 'importance'\n | 'freshness'\n | 'sensitivity'\n | 'confidenceNeeded'\n | 'minSources'\n | 'minHits'\n>\n\n/**\n * Inputs accepted by `defineReadinessSpec`. The four fields the caller cannot\n * sanely default (id, description, query, requiredFor) are required; everything\n * else is optional and pulls from `READINESS_SPEC_DEFAULTS`.\n */\nexport type DefineReadinessSpecInput = Pick<\n KnowledgeReadinessSpec,\n 'id' | 'description' | 'query' | 'requiredFor'\n> &\n Partial<Omit<KnowledgeReadinessSpec, 'id' | 'description' | 'query' | 'requiredFor'>>\n\n/**\n * Builder that returns a fully-typed `KnowledgeReadinessSpec` from a slim input.\n *\n * Motivation: `KnowledgeReadinessSpec` has eleven required fields. Most of them\n * (category, acquisition mode, importance, freshness, sensitivity, confidence\n * threshold, source/hit minima) have a clear default for domain-specific KB\n * topics — agents end up copy-pasting the same boilerplate across every spec.\n * This helper collapses that boilerplate while keeping every field overridable.\n *\n * @example\n * defineReadinessSpec({\n * id: 'coop/intent-grounding',\n * description: 'Required grounding for coop pack intent stage',\n * query: 'flock size space ventilation predator',\n * requiredFor: ['IntentIntakeAgent', 'requirements'],\n * })\n *\n * @example // override defaults where the topic demands it\n * defineReadinessSpec({\n * id: 'medical/dosing',\n * description: 'Dosing guidance for compounding pharmacy',\n * query: 'compounding dose schedule',\n * requiredFor: ['DosingAgent'],\n * importance: 'blocking',\n * freshness: 'daily',\n * sensitivity: 'private',\n * confidenceNeeded: 0.95,\n * minSources: 3,\n * })\n */\nexport function defineReadinessSpec(input: DefineReadinessSpecInput): KnowledgeReadinessSpec {\n return {\n ...READINESS_SPEC_DEFAULTS,\n ...input,\n }\n}\n\nexport interface BuildEvalKnowledgeBundleOptions {\n taskId: string\n index: KnowledgeIndex\n specs: KnowledgeReadinessSpec[]\n userAnswers?: Record<string, string>\n searchLimit?: number\n metadata?: Record<string, unknown>\n now?: Date\n}\n\nexport interface EvalKnowledgeBundleBuildResult {\n bundle: KnowledgeBundle\n report: KnowledgeReadinessReport\n requirements: KnowledgeRequirement[]\n searchResultsByRequirement: Record<string, KnowledgeSearchResult[]>\n questions: UserQuestion[]\n acquisitionPlans: DataAcquisitionPlan[]\n}\n\nexport function buildEvalKnowledgeBundle(\n options: BuildEvalKnowledgeBundleOptions,\n): EvalKnowledgeBundleBuildResult {\n const searchLimit = options.searchLimit ?? 5\n const now = options.now ?? new Date()\n const searchResultsByRequirement: Record<string, KnowledgeSearchResult[]> = {}\n const requirements = options.specs.map((spec) => {\n const results = searchKnowledge(options.index, spec.query, searchLimit)\n searchResultsByRequirement[spec.id] = results\n return requirementFromSearch(options.index, spec, results, now)\n })\n const report = scoreKnowledgeReadiness({\n taskId: options.taskId,\n requirements,\n userAnswers: options.userAnswers,\n evidenceIds: requirements.flatMap((requirement) => requirement.evidenceIds),\n claimIds: [],\n wikiPageIds: unique(\n requirements.flatMap((requirement) =>\n pageIdsFromResults(searchResultsByRequirement[requirement.id] ?? []),\n ),\n ),\n metadata: options.metadata,\n })\n const questions = userQuestionsForKnowledgeGaps(report.blockingMissingRequirements)\n const acquisitionPlans = acquisitionPlansForKnowledgeGaps([\n ...report.blockingMissingRequirements,\n ...report.nonBlockingGaps,\n ])\n\n return {\n bundle: report.bundle,\n report,\n requirements,\n searchResultsByRequirement,\n questions,\n acquisitionPlans,\n }\n}\n\nfunction requirementFromSearch(\n index: KnowledgeIndex,\n spec: KnowledgeReadinessSpec,\n results: KnowledgeSearchResult[],\n now: Date,\n): KnowledgeRequirement {\n const hitCount = results.length\n const sourceIds = unique(results.flatMap((result) => result.page.sourceIds))\n const sources = index.sources.filter((source) => sourceIds.includes(source.id))\n const bestScore = results[0]?.normalizedScore ?? 0\n const sourceCoverage = spec.minSources\n ? Math.min(1, sourceIds.length / spec.minSources)\n : sourceIds.length > 0\n ? 1\n : 0\n const hitCoverage = spec.minHits ? Math.min(1, hitCount / spec.minHits) : hitCount > 0 ? 1 : 0\n const freshness = sourceFreshness(sources, now)\n const currentConfidence = round(Math.min(bestScore, sourceCoverage, hitCoverage, freshness.score))\n\n return {\n id: spec.id,\n description: spec.description,\n requiredFor: spec.requiredFor,\n category: spec.category,\n acquisitionMode: spec.acquisitionMode,\n importance: spec.importance,\n freshness: spec.freshness,\n sensitivity: spec.sensitivity,\n confidenceNeeded: spec.confidenceNeeded,\n currentConfidence,\n evidenceIds: unique([\n ...sourceIds.map((sourceId) => `source:${sourceId}`),\n ...results.map((result) => `page:${result.page.id}`),\n ]),\n fallbackPolicy:\n spec.fallbackPolicy ?? (spec.importance === 'blocking' ? 'block' : 'continue_with_caveat'),\n metadata: {\n ...spec.metadata,\n query: spec.query,\n hitCount,\n sourceCount: sourceIds.length,\n bestNormalizedScore: bestScore,\n expiredSourceIds: freshness.expiredSourceIds,\n freshnessScore: freshness.score,\n validUntil: freshness.validUntil,\n lastVerifiedAt: freshness.lastVerifiedAt,\n },\n }\n}\n\nfunction sourceFreshness(\n sources: KnowledgeIndex['sources'],\n now: Date,\n): { score: number; validUntil?: string; lastVerifiedAt?: string; expiredSourceIds: string[] } {\n if (sources.length === 0) return { score: 0, expiredSourceIds: [] }\n const validUntilValues = sources\n .map(\n (source) =>\n source.validUntil ??\n stringMetadata(source.metadata, 'validUntil') ??\n stringMetadata(source.metadata, 'expiresAt'),\n )\n .filter(isIsoDate)\n const lastVerifiedValues = sources\n .map((source) => source.lastVerifiedAt ?? stringMetadata(source.metadata, 'lastVerifiedAt'))\n .filter(isIsoDate)\n const expiredSourceIds = sources\n .filter((source) => {\n const validUntil =\n source.validUntil ??\n stringMetadata(source.metadata, 'validUntil') ??\n stringMetadata(source.metadata, 'expiresAt')\n return validUntil ? Date.parse(validUntil) <= now.getTime() : false\n })\n .map((source) => source.id)\n return {\n score: expiredSourceIds.length > 0 ? 0 : 1,\n validUntil: earliestIso(validUntilValues),\n lastVerifiedAt: latestIso(lastVerifiedValues),\n expiredSourceIds,\n }\n}\n\nfunction isIsoDate(value: string | undefined): value is string {\n return Boolean(value && Number.isFinite(Date.parse(value)))\n}\n\nfunction earliestIso(values: string[]): string | undefined {\n return values.sort((a, b) => Date.parse(a) - Date.parse(b))[0]\n}\n\nfunction latestIso(values: string[]): string | undefined {\n return values.sort((a, b) => Date.parse(b) - Date.parse(a))[0]\n}\n\nfunction pageIdsFromResults(results: KnowledgeSearchResult[]): string[] {\n return results.map((result) => result.page.id)\n}\n\nfunction unique<T>(items: T[]): T[] {\n return [...new Set(items)]\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000\n}\n","import {\n type BuildEvalKnowledgeBundleOptions,\n buildEvalKnowledgeBundle,\n type EvalKnowledgeBundleBuildResult,\n type KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport type { KnowledgeIndex } from './types'\n\n/**\n * The subset of a research-loop options object the readiness gate needs:\n * the goal (default task id), the readiness specs, an optional task-id\n * override, and the rest of the bundle options minus the fields this helper\n * supplies (`taskId`/`index`/`specs`).\n *\n * Both the single-agent (`research-loop`) and two-agent (`two-agent-research-loop`)\n * options shapes satisfy this structurally, so the gate is single-sourced.\n */\nexport interface ReadinessGateOptions {\n goal: string\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n}\n\n/**\n * Build the readiness bundle for a loop run over the given index, or\n * `undefined` when no readiness specs are configured (no gate to report).\n */\nexport function readinessFor(\n options: ReadinessGateOptions,\n index: KnowledgeIndex,\n): EvalKnowledgeBundleBuildResult | undefined {\n if (!options.readinessSpecs?.length) return undefined\n return buildEvalKnowledgeBundle({\n ...(options.readiness ?? {}),\n taskId: options.readinessTaskId ?? options.goal,\n index,\n specs: options.readinessSpecs,\n })\n}\n","import type { JsonValue } from '@tangle-network/agent-eval/campaign'\nimport {\n type KnowledgeResearchLoopDecision,\n type KnowledgeResearchLoopResult,\n type RunKnowledgeResearchLoopOptions,\n runKnowledgeResearchLoop,\n} from './research-loop'\nimport {\n type RunRetrievalImprovementLoopOptions,\n type RunRetrievalImprovementLoopResult,\n runRetrievalImprovementLoop,\n} from './retrieval-eval'\n\nexport type RagKnowledgeImprovementPhase =\n | 'retrieval-tuning'\n | 'gap-diagnosis'\n | 'knowledge-acquisition'\n | 'knowledge-update'\n | 'answer-quality'\n | 'promotion'\n\nexport type RagKnowledgeImprovementPhaseStatus = 'completed' | 'skipped' | 'failed'\n\nexport type RagGapKind =\n | 'missing-source'\n | 'stale-source'\n | 'retrieval-miss'\n | 'retrieval-noise'\n | 'chunking-mismatch'\n | 'missing-multihop-evidence'\n | 'generator-unsupported-claim'\n | 'citation-mismatch'\n | 'incorrect-abstention'\n | 'unknown'\n\nexport type RagGapSeverity = 'info' | 'warning' | 'error' | 'critical'\n\nexport interface RagGapFinding {\n id: string\n kind: RagGapKind\n severity: RagGapSeverity\n message: string\n scenarioId?: string\n evidence?: Record<string, JsonValue>\n}\n\nexport interface RagKnowledgeImprovementPhaseResult {\n phase: RagKnowledgeImprovementPhase\n status: RagKnowledgeImprovementPhaseStatus\n summary: string\n startedAt: string\n finishedAt: string\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagPhaseInputBase {\n goal: string\n phases: readonly RagKnowledgeImprovementPhaseResult[]\n signal?: AbortSignal\n}\n\nexport interface RagDiagnosisInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n}\n\nexport interface RagKnowledgeAcquisitionInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n}\n\nexport interface RagKnowledgeUpdateInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n}\n\nexport interface RagKnowledgeUpdateResult {\n applied: boolean\n summary: string\n research?: KnowledgeResearchLoopResult\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagAnswerQualityInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n knowledgeUpdate?: RagKnowledgeUpdateResult\n}\n\nexport interface RagAnswerQualityResult {\n passed: boolean\n metrics: Record<string, number>\n findings?: readonly RagGapFinding[]\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagPromotionInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n knowledgeUpdate?: RagKnowledgeUpdateResult\n answerQuality?: RagAnswerQualityResult\n}\n\nexport interface RagPromotionResult {\n promoted: boolean\n reason: string\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagKnowledgeResearchOptions\n extends Omit<RunKnowledgeResearchLoopOptions, 'goal' | 'signal' | 'step'> {\n goal?: string\n step?: RunKnowledgeResearchLoopOptions['step']\n}\n\nexport interface RunRagKnowledgeImprovementLoopOptions {\n goal: string\n retrieval?: RunRetrievalImprovementLoopOptions\n diagnose?: (input: RagDiagnosisInput) => MaybePromise<readonly RagGapFinding[]>\n acquireKnowledge?: (\n input: RagKnowledgeAcquisitionInput,\n ) => MaybePromise<KnowledgeResearchLoopDecision>\n knowledgeResearch?: RagKnowledgeResearchOptions\n updateKnowledge?: (input: RagKnowledgeUpdateInput) => MaybePromise<RagKnowledgeUpdateResult>\n evaluateAnswers?: (input: RagAnswerQualityInput) => MaybePromise<RagAnswerQualityResult>\n promote?: (input: RagPromotionInput) => MaybePromise<RagPromotionResult>\n enabledPhases?: readonly RagKnowledgeImprovementPhase[]\n requiredPhases?: readonly RagKnowledgeImprovementPhase[]\n signal?: AbortSignal\n now?: () => Date\n}\n\nexport interface RunRagKnowledgeImprovementLoopResult {\n goal: string\n phases: readonly RagKnowledgeImprovementPhaseResult[]\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n knowledgeUpdate?: RagKnowledgeUpdateResult\n answerQuality?: RagAnswerQualityResult\n promotion?: RagPromotionResult\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport async function runRagKnowledgeImprovementLoop(\n options: RunRagKnowledgeImprovementLoopOptions,\n): Promise<RunRagKnowledgeImprovementLoopResult> {\n assertConfiguredRequiredPhases(options)\n const now = options.now ?? (() => new Date())\n const phases: RagKnowledgeImprovementPhaseResult[] = []\n let retrieval: RunRetrievalImprovementLoopResult | undefined\n let findings: RagGapFinding[] = []\n let acquisition: KnowledgeResearchLoopDecision | undefined\n let knowledgeUpdate: RagKnowledgeUpdateResult | undefined\n let answerQuality: RagAnswerQualityResult | undefined\n let promotion: RagPromotionResult | undefined\n\n if (phaseEnabled(options, 'retrieval-tuning')) {\n if (options.retrieval) {\n retrieval = await runPhase(\n phases,\n now,\n 'retrieval-tuning',\n async () => {\n assertNotAborted(options.signal)\n return runRetrievalImprovementLoop(options.retrieval!)\n },\n summarizeRetrievalResult,\n )\n } else {\n skipPhase(phases, now, 'retrieval-tuning', 'no retrieval options provided')\n }\n }\n\n if (phaseEnabled(options, 'gap-diagnosis')) {\n if (options.diagnose) {\n findings = [\n ...(await runPhase(\n phases,\n now,\n 'gap-diagnosis',\n async () => {\n assertNotAborted(options.signal)\n return options.diagnose!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n })\n },\n (diagnosed) => `${diagnosed.length} finding(s)`,\n )),\n ]\n } else {\n skipPhase(phases, now, 'gap-diagnosis', 'no diagnosis hook provided')\n }\n }\n\n if (phaseEnabled(options, 'knowledge-acquisition')) {\n if (options.acquireKnowledge) {\n acquisition = await runPhase(\n phases,\n now,\n 'knowledge-acquisition',\n async () => {\n assertNotAborted(options.signal)\n return options.acquireKnowledge!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n })\n },\n summarizeAcquisitionDecision,\n )\n } else {\n skipPhase(phases, now, 'knowledge-acquisition', 'no acquisition hook provided')\n }\n }\n\n if (phaseEnabled(options, 'knowledge-update')) {\n if (options.updateKnowledge) {\n knowledgeUpdate = await runPhase(\n phases,\n now,\n 'knowledge-update',\n async () => {\n assertNotAborted(options.signal)\n return options.updateKnowledge!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n acquisition,\n })\n },\n (result) => result.summary,\n )\n } else if (options.knowledgeResearch) {\n knowledgeUpdate = await runPhase(\n phases,\n now,\n 'knowledge-update',\n async () => {\n assertNotAborted(options.signal)\n return runKnowledgeResearchUpdate(options, acquisition)\n },\n (result) => result.summary,\n )\n } else {\n skipPhase(phases, now, 'knowledge-update', 'no update hook or research loop provided')\n }\n }\n\n if (phaseEnabled(options, 'answer-quality')) {\n if (options.evaluateAnswers) {\n answerQuality = await runPhase(\n phases,\n now,\n 'answer-quality',\n async () => {\n assertNotAborted(options.signal)\n return options.evaluateAnswers!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n acquisition,\n knowledgeUpdate,\n })\n },\n summarizeAnswerQuality,\n )\n findings = [...findings, ...(answerQuality.findings ?? [])]\n } else {\n skipPhase(phases, now, 'answer-quality', 'no answer-quality hook provided')\n }\n }\n\n if (phaseEnabled(options, 'promotion')) {\n if (options.promote) {\n promotion = await runPhase(\n phases,\n now,\n 'promotion',\n async () => {\n assertNotAborted(options.signal)\n return options.promote!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n acquisition,\n knowledgeUpdate,\n answerQuality,\n })\n },\n (result) => `${result.promoted ? 'promoted' : 'held'}: ${result.reason}`,\n )\n } else {\n skipPhase(phases, now, 'promotion', 'no promotion hook provided')\n }\n }\n\n return {\n goal: options.goal,\n phases,\n retrieval,\n findings,\n acquisition,\n knowledgeUpdate,\n answerQuality,\n promotion,\n }\n}\n\nasync function runKnowledgeResearchUpdate(\n options: RunRagKnowledgeImprovementLoopOptions,\n acquisition: KnowledgeResearchLoopDecision | undefined,\n): Promise<RagKnowledgeUpdateResult> {\n const research = options.knowledgeResearch\n if (!research) {\n throw new Error('knowledgeResearch options are required to run the knowledge update phase')\n }\n const { goal, step, ...rest } = research\n const researchStep = step ?? acquisitionBackedResearchStep(acquisition)\n const maxIterations = step ? rest.maxIterations : 1\n const result = await runKnowledgeResearchLoop({\n ...rest,\n goal: goal ?? options.goal,\n maxIterations,\n signal: options.signal,\n step: researchStep,\n })\n return {\n applied: result.steps.some((stepResult) => {\n return stepResult.addedSources.length > 0 || Boolean(stepResult.applied)\n }),\n summary: `${result.iterations} research iteration(s); done=${String(result.done)}`,\n research: result,\n }\n}\n\nfunction acquisitionBackedResearchStep(\n acquisition: KnowledgeResearchLoopDecision | undefined,\n): RunKnowledgeResearchLoopOptions['step'] {\n if (!acquisition) {\n throw new Error(\n 'knowledgeResearch requires either a step hook or a knowledge-acquisition result to apply',\n )\n }\n return () => ({ ...acquisition, done: acquisition.done ?? true })\n}\n\nasync function runPhase<T>(\n phases: RagKnowledgeImprovementPhaseResult[],\n now: () => Date,\n phase: RagKnowledgeImprovementPhase,\n action: () => MaybePromise<T>,\n summarize: (result: T) => string,\n): Promise<T> {\n const startedAt = now().toISOString()\n try {\n const result = await action()\n phases.push({\n phase,\n status: 'completed',\n summary: summarize(result),\n startedAt,\n finishedAt: now().toISOString(),\n })\n return result\n } catch (error) {\n phases.push({\n phase,\n status: 'failed',\n summary: (error as Error).message,\n startedAt,\n finishedAt: now().toISOString(),\n })\n throw error\n }\n}\n\nfunction skipPhase(\n phases: RagKnowledgeImprovementPhaseResult[],\n now: () => Date,\n phase: RagKnowledgeImprovementPhase,\n summary: string,\n): void {\n const timestamp = now().toISOString()\n phases.push({ phase, status: 'skipped', summary, startedAt: timestamp, finishedAt: timestamp })\n}\n\nfunction summarizeRetrievalResult(result: RunRetrievalImprovementLoopResult): string {\n return `${result.candidates.length} candidate(s); winner=${JSON.stringify(result.winnerConfig)}`\n}\n\nfunction summarizeAcquisitionDecision(decision: KnowledgeResearchLoopDecision): string {\n const sourcePathCount = decision.sourcePaths?.length ?? 0\n const sourceTextCount = decision.sourceTexts?.length ?? 0\n const proposal = decision.proposalText ? 'proposal' : 'no proposal'\n return `${sourcePathCount} path source(s), ${sourceTextCount} text source(s), ${proposal}`\n}\n\nfunction summarizeAnswerQuality(result: RagAnswerQualityResult): string {\n const metrics = Object.entries(result.metrics)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, value]) => `${key}=${formatMetric(value)}`)\n .join(', ')\n return `${result.passed ? 'passed' : 'failed'}${metrics ? `; ${metrics}` : ''}`\n}\n\nfunction formatMetric(value: number): string {\n return Number.isFinite(value) ? value.toFixed(3) : String(value)\n}\n\nfunction phaseEnabled(\n options: RunRagKnowledgeImprovementLoopOptions,\n phase: RagKnowledgeImprovementPhase,\n): boolean {\n return !options.enabledPhases || options.enabledPhases.includes(phase)\n}\n\nfunction assertConfiguredRequiredPhases(options: RunRagKnowledgeImprovementLoopOptions): void {\n for (const phase of options.requiredPhases ?? []) {\n if (!phaseEnabled(options, phase)) {\n throw new Error(`required phase ${phase} is not enabled`)\n }\n if (!phaseConfigured(options, phase)) {\n throw new Error(requiredPhaseMessage(phase))\n }\n }\n}\n\nfunction phaseConfigured(\n options: RunRagKnowledgeImprovementLoopOptions,\n phase: RagKnowledgeImprovementPhase,\n): boolean {\n switch (phase) {\n case 'retrieval-tuning':\n return Boolean(options.retrieval)\n case 'gap-diagnosis':\n return Boolean(options.diagnose)\n case 'knowledge-acquisition':\n return Boolean(options.acquireKnowledge)\n case 'knowledge-update':\n return Boolean(options.updateKnowledge ?? options.knowledgeResearch)\n case 'answer-quality':\n return Boolean(options.evaluateAnswers)\n case 'promotion':\n return Boolean(options.promote)\n }\n}\n\nfunction requiredPhaseMessage(phase: RagKnowledgeImprovementPhase): string {\n switch (phase) {\n case 'retrieval-tuning':\n return 'required phase retrieval-tuning requires retrieval options'\n case 'gap-diagnosis':\n return 'required phase gap-diagnosis requires a diagnose hook'\n case 'knowledge-acquisition':\n return 'required phase knowledge-acquisition requires an acquireKnowledge hook'\n case 'knowledge-update':\n return 'required phase knowledge-update requires updateKnowledge or knowledgeResearch'\n case 'answer-quality':\n return 'required phase answer-quality requires an evaluateAnswers hook'\n case 'promotion':\n return 'required phase promotion requires a promote hook'\n }\n}\n\nfunction assertNotAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new Error('RAG knowledge improvement loop aborted')\n }\n}\n","import type { KnowledgeFragment } from './sources/types'\n\n/**\n * Change detection across snapshots of one source's fragments.\n *\n * The output drives the continuous-ingestion loop: each `KnowledgeChange`\n * carries the eval dimensions affected (`affectedDimensions`), which an\n * agent-eval campaign scheduler consumes to decide which campaigns to\n * re-run. Three change kinds:\n *\n * - `added` — fragment id appears in `next` but not `prev`.\n * - `removed` — fragment id appears in `prev` but not `next`. Typical\n * trigger: an authority retires a Wex slug, or a state SOS reorganises\n * its forms catalogue.\n * - `modified` — fragment id appears in both, body hash differs. This\n * is the dominant change kind in practice — the Ryan-LLC v. FTC\n * vacatur case manifests as a `modified` on the Wex non-compete\n * fragment, NOT as a removed one.\n *\n * Unverifiable fragments are filtered out before diffing — comparing a\n * captcha-blocked snapshot against a real one would falsely fire every\n * fragment as removed. The caller can inspect the raw lists if they want\n * to surface block-page failures.\n *\n * Within-snapshot duplicate ids are an upstream bug; this function picks\n * the LAST one and emits a diagnostic via the `warnings` field.\n *\n * @stable\n */\n\nexport type KnowledgeChangeKind = 'added' | 'removed' | 'modified'\n\nexport interface KnowledgeChange {\n /** Source-scoped id (matches `KnowledgeFragment.id`). */\n fragmentId: string\n kind: KnowledgeChangeKind\n /**\n * For `added`: full body of the new fragment.\n * For `removed`: full body of the prior fragment.\n * For `modified`: unified-diff-style payload `{ before, after }` body strings.\n */\n diff?: { before?: string; after?: string }\n /**\n * Eval dimensions to re-score. Computed as the union of both fragments'\n * `dimensionHints`. The eval cron treats this as a set of campaign tags.\n */\n affectedDimensions: string[]\n /** URL of the affected authority page (from whichever side has it). */\n url?: string\n /**\n * Source-attested change time. For `modified`, takes the NEXT fragment's\n * `sourceUpdatedAt`. For `removed`, takes the PRIOR fragment's\n * `sourceUpdatedAt`. For `added`, takes the NEXT fragment's\n * `sourceUpdatedAt`. Consumers index changes by this date.\n */\n detectedAt: string\n}\n\nexport interface DetectChangesResult {\n changes: KnowledgeChange[]\n /** Counts by kind — handy for dashboards. */\n summary: { added: number; removed: number; modified: number }\n /** Non-fatal diagnostics (duplicate ids, dropped unverifiable fragments). */\n warnings: string[]\n}\n\nexport interface DetectChangesOptions {\n /**\n * When true (default), unverifiable fragments are dropped from both\n * sides before comparison. Set false ONLY when debugging block-page\n * issues — comparing against unverifiable content emits false\n * `removed`/`modified` changes.\n */\n skipUnverifiable?: boolean\n /**\n * When provided, only changes whose `affectedDimensions` intersect this\n * set are returned. Useful for cron loops that schedule per-dimension\n * eval campaigns and only care about a subset.\n */\n filterDimensions?: string[]\n}\n\nexport function detectChanges(\n prev: KnowledgeFragment[],\n next: KnowledgeFragment[],\n options: DetectChangesOptions = {},\n): DetectChangesResult {\n const skipUnverifiable = options.skipUnverifiable ?? true\n const warnings: string[] = []\n\n const { map: prevMap, warnings: prevWarn } = indexFragments(prev, skipUnverifiable, 'prev')\n const { map: nextMap, warnings: nextWarn } = indexFragments(next, skipUnverifiable, 'next')\n warnings.push(...prevWarn, ...nextWarn)\n\n const changes: KnowledgeChange[] = []\n const seen = new Set<string>()\n\n for (const [id, nextFragment] of nextMap) {\n seen.add(id)\n const prevFragment = prevMap.get(id)\n if (!prevFragment) {\n changes.push({\n fragmentId: id,\n kind: 'added',\n diff: { after: nextFragment.body },\n affectedDimensions: dedup(nextFragment.dimensionHints),\n url: nextFragment.provenance.url,\n detectedAt: nextFragment.provenance.sourceUpdatedAt,\n })\n continue\n }\n if (prevFragment.bodyHash !== nextFragment.bodyHash) {\n changes.push({\n fragmentId: id,\n kind: 'modified',\n diff: { before: prevFragment.body, after: nextFragment.body },\n affectedDimensions: dedup([...prevFragment.dimensionHints, ...nextFragment.dimensionHints]),\n url: nextFragment.provenance.url,\n detectedAt: nextFragment.provenance.sourceUpdatedAt,\n })\n }\n }\n\n for (const [id, prevFragment] of prevMap) {\n if (seen.has(id)) continue\n changes.push({\n fragmentId: id,\n kind: 'removed',\n diff: { before: prevFragment.body },\n affectedDimensions: dedup(prevFragment.dimensionHints),\n url: prevFragment.provenance.url,\n detectedAt: prevFragment.provenance.sourceUpdatedAt,\n })\n }\n\n const filtered = options.filterDimensions\n ? changes.filter((c) => c.affectedDimensions.some((d) => options.filterDimensions?.includes(d)))\n : changes\n\n return {\n changes: filtered,\n summary: {\n added: filtered.filter((c) => c.kind === 'added').length,\n removed: filtered.filter((c) => c.kind === 'removed').length,\n modified: filtered.filter((c) => c.kind === 'modified').length,\n },\n warnings,\n }\n}\n\nfunction indexFragments(\n fragments: KnowledgeFragment[],\n skipUnverifiable: boolean,\n side: string,\n): { map: Map<string, KnowledgeFragment>; warnings: string[] } {\n const map = new Map<string, KnowledgeFragment>()\n const warnings: string[] = []\n let dropped = 0\n for (const fragment of fragments) {\n if (skipUnverifiable && !fragment.provenance.verifiable) {\n dropped += 1\n continue\n }\n if (map.has(fragment.id)) {\n warnings.push(`${side}: duplicate fragment id ${fragment.id} — keeping last`)\n }\n map.set(fragment.id, fragment)\n }\n if (dropped > 0) {\n warnings.push(`${side}: dropped ${dropped} unverifiable fragment(s) before diff`)\n }\n return { map, warnings }\n}\n\nfunction dedup<T>(items: T[]): T[] {\n return [...new Set(items)]\n}\n","export interface ChunkingOptions {\n targetChars: number\n maxChars: number\n minChars: number\n overlapChars: number\n}\n\nexport interface KnowledgeChunk {\n index: number\n text: string\n headingPath: string\n charStart: number\n charEnd: number\n oversized: boolean\n}\n\nconst DEFAULT_OPTIONS: ChunkingOptions = {\n targetChars: 1000,\n maxChars: 1500,\n minChars: 160,\n overlapChars: 180,\n}\n\nexport function chunkMarkdown(\n content: string,\n options?: Partial<ChunkingOptions>,\n): KnowledgeChunk[] {\n const opts = normalizeOptions({ ...DEFAULT_OPTIONS, ...(options ?? {}) })\n const { body, bodyOffset } = stripFrontmatter(content)\n if (body.trim() === '') return []\n\n const sections = splitSections(body, bodyOffset)\n const chunks: KnowledgeChunk[] = []\n for (const section of sections) {\n for (const part of chunkText(section.text, opts)) {\n const start = section.start + part.start\n chunks.push({\n index: chunks.length,\n text: part.text,\n headingPath: section.headingPath,\n charStart: start,\n charEnd: start + part.text.length,\n oversized: part.text.length > opts.maxChars,\n })\n }\n }\n return chunks\n}\n\nexport function stripFrontmatter(content: string): { body: string; bodyOffset: number } {\n const normalized = content.replace(/\\r\\n/g, '\\n')\n if (!normalized.startsWith('---\\n')) return { body: normalized, bodyOffset: 0 }\n const match = /^---\\n[\\s\\S]*?\\n---\\s*\\n?/.exec(normalized)\n if (!match) return { body: normalized, bodyOffset: 0 }\n return { body: normalized.slice(match[0].length), bodyOffset: match[0].length }\n}\n\nfunction normalizeOptions(opts: ChunkingOptions): ChunkingOptions {\n if (opts.maxChars < opts.targetChars) opts.maxChars = opts.targetChars\n if (opts.overlapChars >= opts.targetChars) opts.overlapChars = Math.floor(opts.targetChars / 2)\n return opts\n}\n\ninterface Section {\n text: string\n start: number\n headingPath: string\n}\n\nfunction splitSections(body: string, bodyOffset: number): Section[] {\n const lines = body.split('\\n')\n const sections: Section[] = []\n const headings: Record<number, string> = {}\n let current: { lines: string[]; start: number; headingPath: string } = {\n lines: [],\n start: bodyOffset,\n headingPath: '',\n }\n let cursor = bodyOffset\n let fence: string | null = null\n\n const flush = () => {\n const text = current.lines.join('\\n')\n if (text.trim() !== '')\n sections.push({ text, start: current.start, headingPath: current.headingPath })\n }\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n const lineLen = line.length + (i < lines.length - 1 ? 1 : 0)\n const fenceMatch = /^(`{3,}|~{3,})/.exec(line)\n if (fenceMatch) {\n const marker = fenceMatch[1]!\n fence = fence === null ? marker : line.startsWith(fence) ? null : fence\n current.lines.push(line)\n cursor += lineLen\n continue\n }\n const heading = fence === null ? /^(#{1,6})\\s+(.+?)\\s*$/.exec(line) : null\n if (heading) {\n flush()\n const level = heading[1]!.length\n headings[level] = heading[2]!.trim()\n for (let next = level + 1; next <= 6; next++) delete headings[next]\n current = {\n lines: [line],\n start: cursor,\n headingPath: Object.entries(headings)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([levelText, title]) => `${'#'.repeat(Number(levelText))} ${title}`)\n .join(' > '),\n }\n cursor += lineLen\n continue\n }\n current.lines.push(line)\n cursor += lineLen\n }\n flush()\n return sections\n}\n\nfunction chunkText(text: string, opts: ChunkingOptions): Array<{ text: string; start: number }> {\n if (text.length <= opts.targetChars) return [{ text, start: 0 }]\n const atoms = splitAtoms(text)\n const chunks: Array<{ text: string; start: number }> = []\n let buffer = ''\n let bufferStart = 0\n for (const atom of atoms) {\n if (buffer === '') bufferStart = atom.start\n if (buffer.length > 0 && buffer.length + atom.text.length > opts.targetChars) {\n chunks.push({ text: buffer.trimEnd(), start: bufferStart })\n const overlap = buffer.slice(Math.max(0, buffer.length - opts.overlapChars))\n buffer = overlap + atom.text\n bufferStart = Math.max(bufferStart, atom.start - overlap.length)\n } else {\n buffer += atom.text\n }\n }\n if (buffer.trim() !== '') chunks.push({ text: buffer.trimEnd(), start: bufferStart })\n return mergeTinyChunks(chunks, opts)\n}\n\nfunction splitAtoms(text: string): Array<{ text: string; start: number }> {\n const parts: Array<{ text: string; start: number }> = []\n const paragraphs = text.split(/(\\n\\s*\\n)/)\n let cursor = 0\n for (let i = 0; i < paragraphs.length; i += 2) {\n const paragraph = (paragraphs[i] ?? '') + (paragraphs[i + 1] ?? '')\n if (paragraph === '') continue\n parts.push({ text: paragraph, start: cursor })\n cursor += paragraph.length\n }\n return parts\n}\n\nfunction mergeTinyChunks(\n chunks: Array<{ text: string; start: number }>,\n opts: ChunkingOptions,\n): Array<{ text: string; start: number }> {\n const out: Array<{ text: string; start: number }> = []\n for (const chunk of chunks) {\n const prev = out[out.length - 1]\n if (\n prev &&\n chunk.text.length < opts.minChars &&\n prev.text.length + chunk.text.length <= opts.maxChars\n ) {\n prev.text = `${prev.text}\\n\\n${chunk.text}`\n } else {\n out.push({ ...chunk })\n }\n }\n return out\n}\n","/**\n * The SINGLE-AGENT COLLECTION driver — the blind-collection baseline (Arm A).\n *\n * This is the honest null the depth A/B is measured against. The other drivers\n * spend extra inference to do something differentiated:\n * - `createVerifyingResearchDriver` runs an LLM gate per source (Arm B),\n * - `createResearchDrivingDriver` extracts claims, tracks corroboration, and\n * synthesizes deep follow-up questions to drive depth (Arm C).\n *\n * This driver does NONE of that. It is a pass-through: it accepts every source\n * the worker proposes and contributes no research, no gating, and no steering of\n * its own. The loop still dedups exact-uri duplicates before calling\n * `verifySource` (that is the loop's job, not the driver's), and the default\n * `foldGaps` (a plain bulleted list of the still-open readiness gaps) still folds\n * the gaps into the worker's next prompt — so the worker keeps researching, but\n * NOTHING intelligent sits between the worker and the knowledge base.\n *\n * In other words: ONE agent (the worker) collects sources round after round, and\n * the \"driver\" is an inert rubber stamp. That is exactly what \"single-agent\n * collection\" means — the topology with zero coordinator intelligence — so its\n * material-facts score is the floor every other arm must beat to justify its\n * extra inference cost.\n *\n * It adds NO router calls of its own: `verifySource` is a synchronous accept and\n * `foldGaps` is omitted so the loop uses its built-in gap list. So Arm A's cost\n * is the worker's cost alone — the cleanest possible blind-collection baseline.\n */\n\nimport type {\n ResearchDriver,\n ResearchSourceProposal,\n SourceVerdict,\n} from './two-agent-research-loop'\n\n/**\n * Build the single-agent collection driver. Accepts every source; never gates,\n * never researches, never steers beyond the loop's default open-gap list. The\n * worker is the only agent that thinks.\n */\nexport function createCollectionResearchDriver(): ResearchDriver {\n return {\n verifySource(_source: ResearchSourceProposal): SourceVerdict {\n return { accept: true }\n },\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\n\nexport interface DiscoveryTask {\n id: string\n goal: string\n query?: string\n sourceHints?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface DiscoveryResult {\n taskId: string\n summary: string\n sourceUris?: string[]\n claims?: Array<{ text: string; sourceUri?: string; confidence?: number }>\n followUpTasks?: DiscoveryTask[]\n metadata?: Record<string, unknown>\n}\n\nexport interface KnowledgeDiscoveryWorker {\n run(task: DiscoveryTask, signal?: AbortSignal): Promise<DiscoveryResult> | DiscoveryResult\n}\n\nexport interface KnowledgeDiscoveryDispatcher {\n dispatch(\n tasks: DiscoveryTask[],\n options?: {\n concurrency?: number\n signal?: AbortSignal\n },\n ): Promise<DiscoveryResult[]>\n}\n\nexport type DiscoveryLoopStopReason = 'complete' | 'max-rounds' | 'max-tasks' | 'aborted'\n\nexport interface DiscoveryLoopRound {\n round: number\n tasks: DiscoveryTask[]\n results: DiscoveryResult[]\n queuedFollowUps: DiscoveryTask[]\n}\n\nexport interface DiscoveryLoopResult {\n stopReason: DiscoveryLoopStopReason\n tasksDispatched: number\n results: DiscoveryResult[]\n rounds: DiscoveryLoopRound[]\n /** Tasks retained, not dropped, when a configured limit stops the loop. */\n pendingTasks: DiscoveryTask[]\n /** Structurally identical task identities ignored to prevent cycles. */\n duplicateTaskIds: string[]\n}\n\nexport interface RunDiscoveryLoopOptions {\n dispatcher: KnowledgeDiscoveryDispatcher\n initialTasks: readonly DiscoveryTask[]\n /** Maximum follow-up depth including the initial dispatch. Default 3. */\n maxRounds?: number\n /** Maximum tasks dispatched across all rounds. Default 24. */\n maxTasks?: number\n /** Forwarded to the dispatcher. Default 4. */\n concurrency?: number\n signal?: AbortSignal\n onRound?: (round: DiscoveryLoopRound) => Promise<void> | void\n}\n\n/**\n * Dispatch discovery tasks and recursively pursue worker-proposed follow-ups.\n *\n * The runner owns only bounded scheduling and accounting. Workers own search,\n * source verification, and domain-specific candidate shapes.\n */\nexport async function runDiscoveryLoop(\n options: RunDiscoveryLoopOptions,\n): Promise<DiscoveryLoopResult> {\n const maxRounds = positiveInteger(options.maxRounds ?? 3, 'maxRounds')\n const maxTasks = positiveInteger(options.maxTasks ?? 24, 'maxTasks')\n const concurrency = positiveInteger(options.concurrency ?? 4, 'concurrency')\n const known = new Map<string, DiscoveryTask>()\n const pending: DiscoveryTask[] = []\n const duplicateTaskIds = new Set<string>()\n enqueueTasks(options.initialTasks, known, pending, duplicateTaskIds)\n\n const rounds: DiscoveryLoopRound[] = []\n const results: DiscoveryResult[] = []\n let tasksDispatched = 0\n let aborted = false\n\n while (pending.length > 0 && rounds.length < maxRounds && tasksDispatched < maxTasks) {\n if (options.signal?.aborted) {\n aborted = true\n break\n }\n const capacity = maxTasks - tasksDispatched\n const tasks = pending.splice(0, capacity)\n let dispatched: DiscoveryResult[]\n try {\n dispatched = orderCompleteDispatch(\n tasks,\n await options.dispatcher.dispatch(tasks, {\n concurrency,\n signal: options.signal,\n }),\n )\n } catch (cause) {\n if (!options.signal?.aborted) throw cause\n pending.unshift(...tasks)\n aborted = true\n break\n }\n tasksDispatched += tasks.length\n results.push(...dispatched)\n\n const queuedFollowUps: DiscoveryTask[] = []\n for (const result of dispatched) {\n enqueueTasks(result.followUpTasks ?? [], known, queuedFollowUps, duplicateTaskIds)\n }\n pending.push(...queuedFollowUps)\n const round: DiscoveryLoopRound = {\n round: rounds.length + 1,\n tasks,\n results: dispatched,\n queuedFollowUps,\n }\n rounds.push(round)\n await options.onRound?.(round)\n if (options.signal?.aborted) {\n aborted = true\n break\n }\n }\n\n const stopReason: DiscoveryLoopStopReason = aborted\n ? 'aborted'\n : pending.length === 0\n ? 'complete'\n : tasksDispatched >= maxTasks\n ? 'max-tasks'\n : 'max-rounds'\n return {\n stopReason,\n tasksDispatched,\n results,\n rounds,\n pendingTasks: pending,\n duplicateTaskIds: [...duplicateTaskIds],\n }\n}\n\nexport function createLocalDiscoveryDispatcher(\n worker: KnowledgeDiscoveryWorker,\n): KnowledgeDiscoveryDispatcher {\n return {\n async dispatch(tasks, options = {}) {\n const concurrency = Math.max(1, options.concurrency ?? 4)\n const results: DiscoveryResult[] = []\n let cursor = 0\n async function runNext(): Promise<void> {\n while (cursor < tasks.length) {\n if (options.signal?.aborted) throw new Error('Discovery dispatch aborted')\n const task = tasks[cursor++]!\n results.push(await worker.run(task, options.signal))\n }\n }\n await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, runNext))\n return orderCompleteDispatch(tasks, results)\n },\n }\n}\n\nfunction enqueueTasks(\n tasks: readonly DiscoveryTask[],\n known: Map<string, DiscoveryTask>,\n destination: DiscoveryTask[],\n duplicateTaskIds: Set<string>,\n): void {\n for (const task of tasks) {\n assertTask(task)\n const prior = known.get(task.id)\n if (!prior) {\n known.set(task.id, task)\n destination.push(task)\n continue\n }\n if (!isDeepStrictEqual(prior, task)) {\n throw new Error(`Discovery task id '${task.id}' refers to conflicting tasks`)\n }\n duplicateTaskIds.add(task.id)\n }\n}\n\nfunction assertTask(task: DiscoveryTask): void {\n if (!task.id.trim()) throw new Error('Discovery task id must not be empty')\n if (!task.goal.trim()) throw new Error(`Discovery task '${task.id}' goal must not be empty`)\n}\n\nfunction orderCompleteDispatch(\n tasks: readonly DiscoveryTask[],\n results: readonly DiscoveryResult[],\n): DiscoveryResult[] {\n const order = new Map(tasks.map((task, index) => [task.id, index]))\n const received = new Set<string>()\n for (const result of results) {\n if (!order.has(result.taskId)) {\n throw new Error(`Discovery dispatcher returned unknown task '${result.taskId}'`)\n }\n if (received.has(result.taskId)) {\n throw new Error(`Discovery dispatcher returned task '${result.taskId}' more than once`)\n }\n received.add(result.taskId)\n }\n const missing = tasks.filter((task) => !received.has(task.id)).map((task) => task.id)\n if (missing.length > 0) {\n throw new Error(`Discovery dispatcher omitted tasks: ${missing.join(', ')}`)\n }\n return [...results].sort(\n (a, b) => (order.get(a.taskId) as number) - (order.get(b.taskId) as number),\n )\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`Discovery loop ${name} must be a positive integer`)\n }\n return value\n}\n","import { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { z } from 'zod'\nimport { isMissingFile, writeJsonDurableWithinRoot } from './durable-fs'\nimport { withKnowledgeMutation, withKnowledgeRead } from './mutation-lock'\n\n/**\n * Knowledge freshness store: tracks when each `(workspaceId, sourceId)` pair\n * was last successfully refreshed, and reports staleness against a TTL.\n *\n * The contract is intentionally minimal — just enough to drive a cron loop:\n *\n * ```ts\n * const store = createFileSystemFreshnessStore({ root: '.agent-knowledge' })\n * for (const source of sources) {\n * if (await store.stale({ workspaceId, sourceId: source.id, ttlMs: DAY })) {\n * const fragments = await source.fetch({ cacheDir })\n * await persistFragments(fragments)\n * await store.mark({ workspaceId, sourceId: source.id, when: new Date() })\n * }\n * }\n * ```\n *\n * Per-tenant isolation is enforced by `workspaceId` keying — there is no\n * global mutable state across workspaces.\n *\n * Two adapters ship in-package:\n *\n * - `createFileSystemFreshnessStore` — JSON file under the knowledge root,\n * mirrors the layout convention already used by `sources.json`.\n * - `createD1FreshnessStoreStub` — adapter scaffold for Cloudflare D1 /\n * Postgres. Production consumers should implement the `D1Adapter`\n * interface inside their own app; this stub exists to anchor the shape.\n *\n * @stable contract — interface is frozen at 0.x within this major.\n * @stable filesystem adapter\n * @experimental D1 stub — interface will evolve as real consumers wire it.\n */\n\n/** Identity for one freshness record. */\nexport interface FreshnessKey {\n workspaceId: string\n sourceId: string\n}\n\n/** TTL bound for staleness checks. */\nexport interface FreshnessTtl extends FreshnessKey {\n /** Milliseconds — `Date.now() - last() > ttlMs` ⇒ stale. */\n ttlMs: number\n /** Injected clock for deterministic tests; defaults to system time. */\n now?: Date\n}\n\n/** Mark argument. */\nexport interface FreshnessMark extends FreshnessKey {\n when: Date\n /** Optional content hash captured at refresh time; aids debugging. */\n contentHash?: string\n}\n\nexport interface KnowledgeFreshnessStore {\n /** Last refresh time, or null if never refreshed. */\n last(key: FreshnessKey): Promise<Date | null>\n /** Record a successful refresh. */\n mark(input: FreshnessMark): Promise<void>\n /** True iff `last(key)` is null or older than `ttlMs`. */\n stale(input: FreshnessTtl): Promise<boolean>\n /** All records for a workspace — useful for dashboards / debugging. */\n list(workspaceId: string): Promise<FreshnessRecord[]>\n}\n\nexport interface FreshnessRecord {\n workspaceId: string\n sourceId: string\n lastRefreshedAt: string\n contentHash?: string\n}\n\nexport interface FileSystemFreshnessStoreOptions {\n /**\n * Knowledge root. The store writes to `<root>/.agent-knowledge/freshness.json`,\n * mirroring the convention used by `sources.json`.\n */\n root: string\n}\n\nconst freshnessRecordSchema = z\n .object({\n workspaceId: z.string().min(1),\n sourceId: z.string().min(1),\n lastRefreshedAt: z.iso.datetime(),\n contentHash: z.string().min(1).optional(),\n })\n .strict()\nconst freshnessFileSchema = z\n .object({ records: z.record(z.string(), freshnessRecordSchema) })\n .strict()\n\n/**\n * Filesystem-backed implementation. Single JSON file per knowledge root,\n * indexed by `${workspaceId}::${sourceId}`. Reads parse on every call —\n * cron tick rate is well below the cost of one JSON parse.\n *\n * Writes share the package-wide filesystem lock, so multiple workers cannot\n * overwrite one another or run through an interrupted knowledge promotion.\n */\nexport function createFileSystemFreshnessStore(\n options: FileSystemFreshnessStoreOptions,\n): KnowledgeFreshnessStore {\n const path = join(options.root, '.agent-knowledge', 'freshness.json')\n\n const read = async (): Promise<Record<string, FreshnessRecord>> => {\n return withKnowledgeRead(options.root, async () => {\n try {\n return freshnessFileSchema.parse(JSON.parse(await readFile(path, 'utf8'))).records\n } catch (error) {\n if (isMissingFile(error)) return {}\n throw error\n }\n })\n }\n\n const write = async (records: Record<string, FreshnessRecord>): Promise<void> => {\n await writeJsonDurableWithinRoot(\n options.root,\n '.agent-knowledge/freshness.json',\n freshnessFileSchema.parse({ records }),\n )\n }\n\n return {\n async last(key) {\n const records = await read()\n const record = records[buildKey(key)]\n return record ? new Date(record.lastRefreshedAt) : null\n },\n async mark(input) {\n await withKnowledgeMutation(options.root, async () => {\n const records = await read()\n records[buildKey(input)] = {\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n lastRefreshedAt: input.when.toISOString(),\n ...(input.contentHash === undefined ? {} : { contentHash: input.contentHash }),\n }\n await write(records)\n })\n },\n async stale(input) {\n const last = await this.last(input)\n if (!last) return true\n const now = input.now ?? new Date()\n return now.getTime() - last.getTime() > input.ttlMs\n },\n async list(workspaceId) {\n const records = await read()\n return Object.values(records).filter((r) => r.workspaceId === workspaceId)\n },\n }\n}\n\n/**\n * D1 / Postgres adapter scaffold. Production consumers implement\n * `D1Adapter` against their own driver (better-sqlite3, postgres,\n * Cloudflare D1 binding, ...). This factory wires the adapter to the\n * `KnowledgeFreshnessStore` interface.\n *\n * The expected schema:\n *\n * ```sql\n * CREATE TABLE knowledge_freshness (\n * workspace_id TEXT NOT NULL,\n * source_id TEXT NOT NULL,\n * last_refreshed_at TEXT NOT NULL,\n * content_hash TEXT,\n * PRIMARY KEY (workspace_id, source_id)\n * );\n * ```\n */\nexport interface D1Adapter {\n get(workspaceId: string, sourceId: string): Promise<FreshnessRecord | null>\n upsert(record: FreshnessRecord): Promise<void>\n listByWorkspace(workspaceId: string): Promise<FreshnessRecord[]>\n}\n\nexport function createD1FreshnessStoreStub(adapter: D1Adapter): KnowledgeFreshnessStore {\n return {\n async last(key) {\n const record = await adapter.get(key.workspaceId, key.sourceId)\n return record ? new Date(record.lastRefreshedAt) : null\n },\n async mark(input) {\n await adapter.upsert({\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n lastRefreshedAt: input.when.toISOString(),\n contentHash: input.contentHash,\n })\n },\n async stale(input) {\n const last = await this.last(input)\n if (!last) return true\n const now = input.now ?? new Date()\n return now.getTime() - last.getTime() > input.ttlMs\n },\n async list(workspaceId) {\n return adapter.listByWorkspace(workspaceId)\n },\n }\n}\n\nfunction buildKey(key: FreshnessKey): string {\n return `${key.workspaceId}::${key.sourceId}`\n}\n","/**\n * HELD-OUT INVESTMENT-RESEARCH EVAL SET.\n *\n * The point of this file is the same FIREWALL the deep-question exam uses\n * (`tests/loops/held-out-exam.ts`): the material facts and their checkable\n * fragments are NEVER shown to a research loop. A loop is told only the company\n * + ticker + a research-as-of CUTOFF date, and asked to write an investment\n * thesis. AFTER it finishes, we grade the thesis it produced against THESE\n * facts — facts it never saw — so a high score is thesis QUALITY (it surfaced\n * the buried, material, non-obvious drivers) and not teaching-to-the-test.\n *\n * Each fact is a DEPTH fact by construction: a single ticker / company-name web\n * search does NOT surface it. They are the things buried in the filings or\n * knowable from then-available primary sources that a thorough analyst flags and\n * a one-shot search misses — customer/revenue/deposit concentration, a debt\n * maturity wall, a margin-trend reversal, a governance / related-party item, a\n * specific competitive or regulatory risk, an off-balance-sheet loss.\n *\n * THREE HARD RULES, enforced by how the data was gathered (see\n * docs/eval/investment-material-facts.md for the per-item provenance + the\n * curation-bias disclosure):\n *\n * 1. SPECIFIC + CHECKABLE. Each fact carries `expected` keyword groups — the\n * specific number / name / phrase — so a deterministic, model-free\n * substring grader (`gradeFactAgainstText`) can score \"did the thesis\n * surface it\". $0, reproducible, and it cannot leak the answer key into a\n * model the loop could observe.\n *\n * 2. DERIVED FROM REAL FETCHED EVIDENCE. Every fact records the primary source\n * it came from (`sourceUrl`, an SEC EDGAR 10-K) and the literal `evidence`\n * value read out of that document. Nothing here is invented; an item that\n * could not be independently sourced was DROPPED, not guessed (the drop log\n * is in the doc).\n *\n * 3. KNOWABLE AT THE CUTOFF. Every fact was disclosed in, or computable from, a\n * document available on or before the company's `cutoff` date. Post-cutoff\n * hindsight (the eventual bankruptcy / collapse) is NOT a checklist item —\n * it is recorded separately as `knownOutcome`, purely for the reader, and is\n * never graded.\n *\n * Grading mirrors the deep-question exam exactly: a fact is SURFACED when the\n * thesis text contains at least `minGroups` of its expected groups; a group is\n * satisfied when ANY of its `anyOf` fragments appears (case-insensitive\n * substring), so a faithful thesis phrased in its own words still grades as a\n * hit. `anyOf` groups model synonyms; the load-bearing tokens are the specific\n * numbers / names.\n */\n\n/** A required answer component: satisfied when any synonym fragment is present. */\nexport interface ExpectedGroup {\n /** Human label for the component (for the doc / audit). */\n label: string\n /** Case-insensitive substring fragments; any one present satisfies the group. */\n anyOf: string[]\n}\n\n/** Lens the fact belongs to — so a set can be checked for category coverage. */\nexport type MaterialFactLens =\n | 'concentration' // customer / revenue / deposit concentration\n | 'leverage' // debt load / maturity wall / interest burden\n | 'margin-trend' // gross/operating margin reversal\n | 'liquidity' // cash burn / negative operating cash flow\n | 'capital-return' // buyback / dividend draining the balance sheet\n | 'governance' // dual-class / related-party / control item\n | 'off-balance-sheet' // unrealized losses not in earnings/equity\n | 'regulatory' // a specific regulatory / legal / recall exposure\n\n/** One held-out material fact with a checkable expected answer + its provenance. */\nexport interface MaterialFact {\n /** Stable id, `ticker/fN`. */\n id: string\n /** Which analyst lens this fact exercises. For coverage + the doc. */\n lens: MaterialFactLens\n /**\n * The material fact, in plain words — for the doc/audit. NEVER shown to a loop.\n * This is the thing a thorough analyst would flag and a ticker search misses.\n */\n fact: string\n /**\n * The checkable answer as required keyword GROUPS. The thesis text must contain\n * at least `minGroups` of these groups (default: all). A group is satisfied\n * when ANY of its `anyOf` fragments appears (case-insensitive substring).\n */\n expected: ExpectedGroup[]\n /**\n * Minimum number of `expected` groups the thesis must contain to count the\n * fact SURFACED. Default = all groups (the strict bar). Lowered (and documented\n * inline) only when the fact is genuinely satisfiable by a subset.\n */\n minGroups?: number\n /**\n * PROVENANCE. The primary source URL this fact was read from — an SEC EDGAR\n * 10-K primary document, fetched live during curation.\n */\n sourceUrl: string\n /**\n * The literal value / phrase read out of `sourceUrl` that grounds the fact.\n * This is the \"cite the actual filing + the value\" requirement — verbatim or\n * near-verbatim from the filing, with the figure.\n */\n evidence: string\n}\n\n/** A company + the cutoff a loop researches as-of + its held-out material facts. */\nexport interface CompanyEvalCase {\n /** Ticker as of the cutoff. */\n ticker: string\n /** Legal name as of the cutoff (what the loop is told to research). */\n company: string\n /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */\n cik: string\n /**\n * Research-as-of date (ISO). The loop must reason as if it is this date; every\n * `evidence` value was knowable on or before it. >= 18 months before this set\n * was curated, so the outcome is known but is NOT a checklist item.\n */\n cutoff: string\n /** Sector, for coverage / the curation-bias disclosure. */\n sector: string\n /**\n * The known POST-cutoff outcome — recorded for the reader ONLY, never graded.\n * Keeping it out of `facts` is what makes the set hindsight-free.\n */\n knownOutcome: string\n /** The held-out material facts for this company. */\n facts: MaterialFact[]\n}\n\n/**\n * The eval set. 5 public companies, 5-8 held-out material facts each, every fact\n * grounded in a primary SEC EDGAR 10-K filed on or before the cutoff.\n *\n * CURATION-BIAS DISCLOSURE (full version in the doc): all five are companies\n * whose buried risks later materialized, because that is where the material-vs-\n * surface distinction is sharpest AND where the figures are easy to verify after\n * the fact. This biases the set toward downside risks (two of the eight lenses,\n * concentration + leverage, dominate) and toward distressed names. A production\n * eval would balance these with companies whose buried facts were POSITIVE\n * drivers and with survivors. This set is honest about that and reports the lens\n * distribution so the bias is measurable, not hidden.\n */\nexport const investmentThesisSet: CompanyEvalCase[] = [\n {\n ticker: 'SIVB',\n company: 'SVB Financial Group',\n cik: '719739',\n cutoff: '2023-02-24',\n sector: 'Banking',\n knownOutcome:\n 'Failed in a deposit run and was placed in FDIC receivership on March 10, 2023; the holding company filed Chapter 11 on March 17, 2023.',\n facts: [\n {\n id: 'SIVB/f1',\n lens: 'off-balance-sheet',\n fact: 'Held-to-maturity (HTM) securities carried at $91.3B amortized cost had a fair value of only $76.2B — a ~$15.1B unrealized loss that, because the portfolio is HTM, never touched earnings or equity and sat only in the footnotes.',\n expected: [\n {\n label: 'HTM securities',\n anyOf: ['held-to-maturity', 'held to maturity', 'htm'],\n },\n {\n label: 'large unrealized loss (~$15B) / fair value gap',\n anyOf: [\n '15.1',\n '15.2',\n '$15 billion',\n '15 billion',\n '76,169',\n '76.2 billion',\n '91,321',\n 'unrealized loss',\n 'below amortized cost',\n 'fair value',\n ],\n },\n ],\n minGroups: 2,\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n 'Balance sheet (Dec 31, 2022): \"Held-to-maturity securities, at amortized cost ... 91,321\" with parenthetical \"(fair value of $ 76,169 ...)\". The gap = $91,321M - $76,169M = ~$15,152M unrealized loss, disclosed only in the notes.',\n },\n {\n id: 'SIVB/f2',\n lens: 'off-balance-sheet',\n fact: \"The HTM unrealized loss (~$15.1B) was roughly equal to the company's entire $16.0B total stockholders' equity — a mark-to-market wipeout hidden by HTM accounting.\",\n expected: [\n {\n label: 'loss near/exceeds total equity',\n anyOf: [\n 'equity',\n 'capital',\n 'insolvent',\n 'wipe out',\n 'exceeds',\n 'nearly all',\n 'tangible book',\n '16,004',\n '16 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"Total SVBFG stockholders\\' equity 16,004\" (Dec 31, 2022). The ~$15.15B HTM unrealized loss is ~95% of the $16.0B reported equity.',\n },\n {\n id: 'SIVB/f3',\n lens: 'concentration',\n fact: 'Estimated uninsured deposits in U.S. offices were $151.5B at year-end 2022 — the run-prone funding base; a high share of total deposits exceeded the FDIC limit.',\n expected: [\n {\n label: 'large uninsured deposit base',\n anyOf: [\n 'uninsured deposit',\n 'above the fdic',\n 'exceed the fdic',\n 'exceeds the fdic',\n '151.5',\n '$151 billion',\n 'fdic insurance limit',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"As of December 31, 2022 ... the amount of estimated uninsured deposits in U.S. offices that exceed the FDIC insurance limit were $151.5 billion\".',\n },\n {\n id: 'SIVB/f4',\n lens: 'margin-trend',\n fact: 'Cheap noninterest-bearing demand deposits fell 20 percentage points in one year — to 47% of total deposits from 67% — meaning funding costs were set to rise sharply as clients moved to interest-bearing accounts.',\n expected: [\n {\n label: 'deposit mix shift to costlier funding',\n anyOf: [\n 'noninterest-bearing',\n 'non-interest-bearing',\n 'noninterest bearing',\n 'deposit mix',\n 'funding cost',\n 'cost of deposits',\n 'interest-bearing',\n '47 percent',\n '20 percentage',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"Noninterest-bearing demand deposits to total deposits decreased by 20 percentage points to 47 percent as of December 31, 2022, compared to ... 2021.\"',\n },\n {\n id: 'SIVB/f5',\n lens: 'concentration',\n fact: 'The deposit and loan base was concentrated in a single client type — the \"innovation economy\" (venture-backed technology and life-science startups) — so a downturn in venture funding would hit deposits and credit simultaneously.',\n expected: [\n {\n label: 'concentration in tech / startups / innovation economy',\n anyOf: [\n 'innovation economy',\n 'technology',\n 'life science',\n 'venture',\n 'startup',\n 'early-stage',\n 'concentrat',\n 'single industry',\n 'sector concentration',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n 'The 10-K repeatedly frames the franchise around clients in \"the innovation economy\" (technology, life science / healthcare, and the venture firms that back them) — a single-sector deposit + credit concentration.',\n },\n {\n id: 'SIVB/f6',\n lens: 'off-balance-sheet',\n fact: 'Available-for-sale (AFS) securities of $28.6B amortized cost were marked to a $26.1B fair value — a ~$2.5B loss that DID flow through equity (AOCI), the visible tip of a much larger unrealized-loss iceberg dominated by the footnote-only HTM book.',\n expected: [\n {\n label: 'AFS unrealized loss / AOCI',\n anyOf: [\n 'available-for-sale',\n 'available for sale',\n 'afs',\n 'aoci',\n 'accumulated other comprehensive',\n '28,602',\n '26,069',\n '2.5 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"Available-for-sale securities, at fair value (cost of $ 28,602 ...) 26,069\" — a ~$2.5B AFS unrealized loss carried in AOCI, separate from and much smaller than the HTM gap.',\n },\n ],\n },\n {\n ticker: 'BBBY',\n company: 'Bed Bath & Beyond Inc.',\n cik: '886158',\n cutoff: '2022-04-21',\n sector: 'Specialty retail',\n knownOutcome: 'Filed for Chapter 11 bankruptcy on April 23, 2023; shareholders were wiped out.',\n facts: [\n {\n id: 'BBBY/f1',\n lens: 'capital-return',\n fact: 'The company had repurchased ~$11.685B of its own stock since 2004 — including $574.9M in fiscal 2021 alone, \"two years ahead of schedule\" — draining the balance sheet of a business that was losing money.',\n expected: [\n {\n label: 'massive buyback program',\n anyOf: [\n 'repurchas',\n 'buyback',\n 'buy back',\n 'share repurchase',\n '11.685',\n '$11.7 billion',\n '574.9',\n '$575 million',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n '\"Since 2004 through the end of Fiscal 2021, we have repurchased approximately $11.685 billion of our common stock\"; FY2021 alone \"completed share repurchases of $574.9 million ... two years ahead of schedule.\"',\n },\n {\n id: 'BBBY/f2',\n lens: 'liquidity',\n fact: 'Operating cash flow collapsed to just $17.9M in FY2021, down from $268.1M and $590.9M in the two prior years — a near-total loss of internally generated cash while it kept buying back stock.',\n expected: [\n {\n label: 'operating cash flow collapse',\n anyOf: [\n 'operating cash flow',\n 'cash from operations',\n 'cash provided by operating',\n 'cash flow from operations',\n '17.9',\n '17,854',\n 'declining cash flow',\n 'cash generation',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n 'Statement of cash flows: \"Net cash provided by operating activities 17,854 268,108 590,941\" (FY2021 / FY2020 / FY2019, $ thousands).',\n },\n {\n id: 'BBBY/f3',\n lens: 'liquidity',\n fact: \"Total shareholders' equity fell ~86% in one year — from $1.277B to $174.1M — as losses plus buybacks ate the equity cushion.\",\n expected: [\n {\n label: 'equity erosion',\n anyOf: [\n 'shareholders’ equity',\n \"shareholders' equity\",\n 'stockholders equity',\n 'book value',\n 'equity',\n 'net worth',\n '174.1',\n '174,145',\n 'eroded',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n '\"Total shareholders\\' equity 174,145 1,276,936\" (FY2021 vs FY2020, $ thousands) — an ~86% decline in one year.',\n },\n {\n id: 'BBBY/f4',\n lens: 'liquidity',\n fact: 'The company posted a $559.6M net loss in FY2021 — yet spent $574.9M on buybacks the same year, i.e. it returned more cash to shareholders than it had, let alone earned.',\n expected: [\n {\n label: 'net loss FY2021',\n anyOf: [\n 'net loss',\n 'unprofitable',\n 'lost money',\n 'losing money',\n '559.6',\n '559,623',\n '$560 million',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence: '\"Net loss $ ( 559,623 )\" for fiscal 2021 ($ thousands).',\n },\n {\n id: 'BBBY/f5',\n lens: 'margin-trend',\n fact: 'Merchandise inventories rose to $1.725B even as sales fell — inventory building into a demand decline, a classic markdown-risk and cash-trap signal.',\n expected: [\n {\n label: 'inventory building into falling demand',\n anyOf: [\n 'inventor',\n 'merchandise inventories',\n 'overstock',\n 'markdown',\n '1,725',\n '1.7 billion',\n 'stockpile',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n '\"Merchandise inventories 1,725,410 1,671,909\" ($ thousands) — inventory grew year over year while comparable sales declined.',\n },\n ],\n },\n {\n ticker: 'CVNA',\n company: 'Carvana Co.',\n cik: '1690820',\n cutoff: '2023-02-23',\n sector: 'Auto e-commerce',\n knownOutcome:\n 'The stock fell ~98% from its 2021 peak; the company narrowly avoided bankruptcy via a 2023 debt-exchange that cut and extended its obligations.',\n facts: [\n {\n id: 'CVNA/f1',\n lens: 'leverage',\n fact: 'Total debt had grown to $8.39B by year-end 2022 (from $5.45B) — a debt load far larger than the equity base, built up funding growth and the ADESA deal.',\n expected: [\n {\n label: 'large/growing debt load',\n anyOf: [\n 'total debt',\n 'long-term debt',\n 'leverage',\n 'highly leveraged',\n 'debt load',\n '8,391',\n '8.4 billion',\n '$8.4 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence: '\"Total debt 8,391 5,447\" (Dec 31, 2022 vs 2021, $ millions).',\n },\n {\n id: 'CVNA/f2',\n lens: 'leverage',\n fact: 'Interest expense nearly tripled to $486M in 2022 (from $176M) — debt-service was consuming cash a still-unprofitable company did not have.',\n expected: [\n {\n label: 'rising interest burden',\n anyOf: [\n 'interest expense',\n 'interest cost',\n 'debt service',\n 'cost of debt',\n '486',\n 'interest burden',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence: '\"Interest expense 486 176\" (FY2022 vs FY2021, $ millions).',\n },\n {\n id: 'CVNA/f3',\n lens: 'leverage',\n fact: \"In May 2022 Carvana bought ADESA's U.S. physical auction business for ~$2.2B in cash — a debt-funded acquisition that stretched the balance sheet right as used-car demand turned.\",\n expected: [\n {\n label: 'ADESA acquisition ~$2.2B',\n anyOf: ['adesa', '2.2 billion', '$2.2 billion', 'physical auction', 'acquisition'],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence:\n '\"physical auction business of ADESA US Auction, LLC for approximately $2.2 billion in cash (the \\'ADESA Acquisition\\')\", closed 2022-05-09.',\n },\n {\n id: 'CVNA/f4',\n lens: 'governance',\n fact: 'Carvana leases hubs and properties from DriveTime — a company controlled by founder/CEO Ernest Garcia III and his father Ernest Garcia II — a recurring related-party arrangement with the controlling family.',\n expected: [\n {\n label: 'related-party with founder family / DriveTime',\n anyOf: [\n 'related party',\n 'related-party',\n 'drivetime',\n 'garcia',\n 'controlled by',\n 'affiliate of',\n 'conflict of interest',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence:\n 'Related Party Transactions note: lease agreements with \"DriveTime Automotive Group\", a related party \"due to Ernest Garcia II, Ernest Garcia III, and entities controlled by one or both of them\".',\n },\n {\n id: 'CVNA/f5',\n lens: 'liquidity',\n fact: 'The 2022 net loss was $2.894B — a loss far wider than prior years, showing the unit economics had not turned even at scale.',\n expected: [\n {\n label: 'large net loss FY2022',\n anyOf: [\n 'net loss',\n 'unprofitable',\n 'losing money',\n 'cash burn',\n '2,894',\n '2.9 billion',\n '$2.9 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence: '\"Net loss $ (2,894 ...\" for fiscal 2022 ($ millions).',\n },\n ],\n },\n {\n ticker: 'PTON',\n company: 'Peloton Interactive, Inc.',\n cik: '1639825',\n cutoff: '2022-09-07',\n sector: 'Consumer fitness hardware',\n knownOutcome:\n 'The stock fell ~95% from its 2021 peak; the founder-CEO departed, the company underwent mass layoffs and a multi-year turnaround through fiscal 2024.',\n facts: [\n {\n id: 'PTON/f1',\n lens: 'margin-trend',\n fact: 'Connected Fitness (hardware) gross margin turned NEGATIVE — to (11)% in FY2022 — meaning Peloton lost money on every bike/tread it sold before any operating cost; revenue growth was masking a broken unit economics.',\n expected: [\n {\n label: 'negative / collapsing hardware gross margin',\n anyOf: [\n 'gross margin',\n 'negative margin',\n 'gross profit',\n 'margin compression',\n 'losing money on each',\n 'below cost',\n '(11)',\n '-11',\n 'negative gross',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n 'MD&A \"Gross Profit, and Gross Margin\" table: Connected Fitness \"Gross Margin decreased to (11)\" percent in fiscal 2022 — a negative hardware gross margin.',\n },\n {\n id: 'PTON/f2',\n lens: 'liquidity',\n fact: 'Inventories climbed to $1.105B as pandemic demand normalized — a glut of unsold equipment that tied up cash and risked markdowns.',\n expected: [\n {\n label: 'inventory glut',\n anyOf: [\n 'inventor',\n 'overstock',\n 'excess inventory',\n 'glut',\n 'markdown',\n 'unsold',\n '1,104',\n '1.1 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence: '\"Inventories, net 1,104.5 937\" (FY2022 vs FY2021, $ millions).',\n },\n {\n id: 'PTON/f3',\n lens: 'governance',\n fact: \"A dual-class structure gives Class B holders 20 votes per share vs 1 for Class A — concentrating control with insiders/founders and limiting public shareholders' say.\",\n expected: [\n {\n label: 'dual-class super-voting control',\n anyOf: [\n 'dual-class',\n 'dual class',\n 'class b',\n '20 votes',\n 'super-voting',\n 'supervoting',\n 'voting control',\n 'multiple votes per share',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n '\"Class B common stock has 20 votes per share and our Class A common stock has one vote per share.\"',\n },\n {\n id: 'PTON/f4',\n lens: 'liquidity',\n fact: 'Peloton reported a $2.827B net loss in FY2022 — an order-of-magnitude wider loss than the prior year, signaling the demand normalization had broken the model, not just dented it.',\n expected: [\n {\n label: 'large net loss FY2022',\n anyOf: [\n 'net loss',\n 'unprofitable',\n 'losing money',\n 'cash burn',\n '2,827',\n '2.8 billion',\n '$2.8 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence: '\"Net loss $ (2,827 ...\" for fiscal 2022 ($ millions).',\n },\n {\n id: 'PTON/f5',\n lens: 'regulatory',\n fact: 'Peloton was running a CPSC recall of its Tread+ treadmill (tied to injuries and a child death) — an open product-safety and legal exposure beyond the demand story.',\n expected: [\n {\n label: 'Tread+ / CPSC recall exposure',\n anyOf: [\n 'recall',\n 'cpsc',\n 'consumer product safety',\n 'tread+',\n 'tread plus',\n 'product safety',\n 'injuries',\n 'safety',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n '\"recall on Tread+, which we are conducting in collaboration with the Consumer Product Safety Commission (\\'CPSC\\')\"; the Tread product recalls \"in the fourth quarter of fiscal 2021 continued to impact\" results.',\n },\n {\n id: 'PTON/f6',\n lens: 'leverage',\n fact: 'Peloton was locked into ~$334M of manufacturing purchase commitments even as demand fell — contractual inventory it had to take on regardless of whether it could sell it.',\n expected: [\n {\n label: 'locked-in purchase commitments',\n anyOf: [\n 'purchase commitment',\n 'purchase obligation',\n 'minimum purchase',\n 'take-or-pay',\n 'committed to purchase',\n '334',\n 'manufacturing commitment',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n '\"purchase commitments related to the manufacture of Peloton products were estimated to be approximately $334\" million.',\n },\n ],\n },\n {\n ticker: 'SI',\n company: 'Silvergate Capital Corporation',\n cik: '1312109',\n cutoff: '2022-02-28',\n sector: 'Banking (digital-asset)',\n knownOutcome:\n 'After the FTX collapse triggered a deposit run, Silvergate announced a voluntary wind-down of Silvergate Bank and liquidation in March 2023.',\n facts: [\n {\n id: 'SI/f1',\n lens: 'concentration',\n fact: 'About 99.5% of total deposits were noninterest-bearing — essentially all funding was non-term money that could leave on demand, an extreme run-risk masked by very low funding cost.',\n expected: [\n {\n label: 'almost all deposits noninterest-bearing / on-demand',\n anyOf: [\n 'noninterest bearing',\n 'noninterest-bearing',\n 'non-interest-bearing',\n 'demand deposit',\n 'no term',\n 'on demand',\n '99.5',\n '99 percent',\n 'leave at any time',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n '\"noninterest bearing deposits as a percentage of total deposits was 99.5% as of December 31, 2021.\"',\n },\n {\n id: 'SI/f2',\n lens: 'concentration',\n fact: 'Roughly 58% of deposits came from digital-currency EXCHANGES alone — a handful of correlated crypto counterparties whose own troubles would pull deposits out together.',\n expected: [\n {\n label: 'deposits concentrated in crypto exchanges',\n anyOf: [\n 'digital currency exchange',\n 'crypto exchange',\n 'exchanges represent',\n 'counterpart',\n 'concentrat',\n '58%',\n '58 percent',\n 'approximately 58',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n '\"Deposits from digital currency exchanges represent approximately 58%\" of deposits.',\n },\n {\n id: 'SI/f3',\n lens: 'concentration',\n fact: 'The entire deposit franchise was tied to a single, volatile industry — digital-currency (crypto) customers — so a crypto downturn was a direct, undiversified funding shock.',\n expected: [\n {\n // The buried, depth signal is the CONCENTRATION framing — that the\n // whole deposit base is one undiversified industry bet — NOT the bare\n // fact that it banks crypto (a one-line ticker summary has that). So\n // bare \"crypto\" / \"digital asset\" are excluded; the load-bearing\n // tokens are the concentration / single-industry / undiversified\n // characterization or the filing's own \"digital currency customers\".\n label: 'single-industry deposit CONCENTRATION (not just \"it banks crypto\")',\n anyOf: [\n 'digital currency customers',\n 'single industry',\n 'one industry',\n 'single volatile industry',\n 'sector concentration',\n 'undiversified',\n 'concentrat',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n 'The 10-K\\'s strategy and risk factors center the bank on \"digital currency customers\" and \"the concentration of our deposits\" in that single industry.',\n },\n {\n id: 'SI/f4',\n lens: 'liquidity',\n fact: 'Total deposits had ballooned to $14.3B (from $10.4B) — fast, hot-money growth from the crypto boom that could reverse just as fast.',\n expected: [\n {\n // The depth signal is the SIZE/character of the deposit base — the\n // specific $14.3B figure or the explicit hot-money / volatile-deposit\n // characterization — NOT bare \"total deposits\" / \"grew rapidly\", which\n // any growth-story summary trips. Those generic phrases are excluded.\n label: 'specific hot-money deposit base ($14.3B / volatile)',\n anyOf: [\n 'hot money',\n 'hot-money',\n 'volatile deposit',\n 'could reverse',\n '14.3 billion',\n '14,290',\n '$14.3b',\n '$14 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence: '\"Total deposits $ 14,290,628\" ... prior year \"$ 10,411,278\" ($ thousands).',\n },\n {\n id: 'SI/f5',\n lens: 'concentration',\n fact: 'The franchise hinged on a single proprietary product — the Silvergate Exchange Network (SEN), a payment network built exclusively for the digital-currency industry — so its competitive moat and its deposit base were the SAME crypto-dependent bet, not two diversified ones.',\n expected: [\n {\n // The depth signal is naming the SPECIFIC proprietary product (the\n // Silvergate Exchange Network / SEN) and that the moat and the deposit\n // base are the same single bet — NOT bare \"proprietary\" / \"payment\n // network\", which a generic crypto-bank summary mentions. Those bare\n // terms are excluded; the SEN name or the single-product framing is\n // load-bearing.\n label: 'names the SEN single-product dependence (not generic \"payment network\")',\n anyOf: [\n 'silvergate exchange network',\n 'the sen',\n 'sen)',\n \"sen'\",\n 'single product',\n 'single-product',\n 'core product',\n 'one product',\n 'same bet',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n \"\\\"Silvergate Exchange Network ('SEN'), our proprietary, virtually instantaneous payment network for participants in the digital currency industry\\\" — the bank's differentiator and its deposit magnet are the same crypto-only product.\",\n },\n ],\n },\n]\n\n/**\n * Grade ONE material fact against an investment thesis's full text. Returns\n * whether the thesis SURFACED it plus which expected groups were found. The\n * check is a deterministic case-insensitive substring scan — $0, model-free,\n * reproducible — so the eval never leaks into a model the loop could observe.\n */\nexport function gradeFactAgainstText(\n fact: MaterialFact,\n thesisText: string,\n): { surfaced: boolean; groupsFound: number; groupsTotal: number; foundLabels: string[] } {\n const haystack = thesisText.toLowerCase()\n const found = fact.expected.filter((group) =>\n group.anyOf.some((fragment) => haystack.includes(fragment.toLowerCase())),\n )\n const minGroups = fact.minGroups ?? fact.expected.length\n return {\n surfaced: found.length >= minGroups,\n groupsFound: found.length,\n groupsTotal: fact.expected.length,\n foundLabels: found.map((group) => group.label),\n }\n}\n\n/** Grade a whole company's thesis text: how many of its held-out facts it surfaces. */\nexport function gradeCompanyAgainstText(\n company: CompanyEvalCase,\n thesisText: string,\n): { surfaced: number; total: number; perFact: ReturnType<typeof gradeFactAgainstText>[] } {\n const perFact = company.facts.map((fact) => gradeFactAgainstText(fact, thesisText))\n return {\n surfaced: perFact.filter((result) => result.surfaced).length,\n total: company.facts.length,\n perFact,\n }\n}\n\n/** Total held-out facts across the set (the denominator the doc reports). */\nexport function totalMaterialFacts(set: CompanyEvalCase[] = investmentThesisSet): number {\n return set.reduce((sum, company) => sum + company.facts.length, 0)\n}\n\n/** Count facts per lens across the set — used to report (and bound) curation bias. */\nexport function lensDistribution(\n set: CompanyEvalCase[] = investmentThesisSet,\n): Record<MaterialFactLens, number> {\n const dist = {} as Record<MaterialFactLens, number>\n for (const company of set) {\n for (const fact of company.facts) {\n dist[fact.lens] = (dist[fact.lens] ?? 0) + 1\n }\n }\n return dist\n}\n","/**\n * The INVESTMENT-THESIS research task.\n *\n * Given `{ company, ticker, cik, cutoff }`, drive the SAME two-agent research\n * loop the ML deep-question A/B uses (`runVerifiedResearchLoop` + the real web\n * worker) to research the company AS OF the cutoff — web + SEC EDGAR, both public\n * — and produce an investment-thesis PAGE in the knowledge base: a judgment, the\n * drivers, and the risks, grounded in what it fetched.\n *\n * This file builds NOTHING new for the loop: it composes the existing worker +\n * driver + loop, supplies the readiness specs that steer the worker toward the\n * filing-level evidence (the analyst lenses), then writes a synthesis thesis page\n * the metric (`materialFactsSurfaced`) grades against the HELD-OUT checklist.\n *\n * THE FIREWALL: the task is told ONLY company + ticker + cutoff (+ the generic\n * analyst-lens readiness specs every company gets). It is NEVER shown the\n * checklist. The checklist is read only afterward, by the metric. So a high score\n * is research depth, not teaching-to-the-test.\n */\n\nimport { join } from 'node:path'\nimport { writeFileDurableWithinRoot } from './durable-fs'\nimport { defineReadinessSpec, type KnowledgeReadinessSpec } from './eval-readiness'\nimport { slugify } from './ids'\nimport { buildKnowledgeIndex } from './indexer'\nimport { kbIndexToText } from './material-facts-metric'\nimport { withKnowledgeMutation } from './mutation-lock'\nimport {\n type ResearchDriver,\n runVerifiedResearchLoop,\n type VerifiedResearchLoopResult,\n} from './two-agent-research-loop'\nimport {\n createWebResearchWorker,\n type RouterClient,\n type WebResearchWorkerOptions,\n} from './web-research-worker'\n\n/** The minimal brief a thesis run is given — the firewall boundary. */\nexport interface ThesisTaskInput {\n /** Legal name as of the cutoff — what the loop researches. */\n company: string\n /** Ticker as of the cutoff. */\n ticker: string\n /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */\n cik: string\n /** Research-as-of date (ISO). The loop must reason as if it is this date. */\n cutoff: string\n /** Sector, for the readiness query context (NOT a checklist hint). */\n sector?: string\n}\n\n/**\n * The generic analyst-lens readiness specs every company gets. They are the ONLY\n * thing the loop is told about WHAT to look for, and they name the LENSES a\n * thorough analyst checks (balance-sheet risk, concentration, leverage, margins,\n * liquidity, governance, regulatory) and where they live (the latest SEC 10-K) —\n * NOT the answers. They steer the worker's web/EDGAR search toward the filing,\n * not toward the held-out facts (which the loop never sees).\n *\n * `minSources` is set above 1 so the readiness gate stays UNMET after a single\n * fetch and the loop runs multiple rounds — the depth-driving driver needs >1\n * round to steer, exactly as the ML-exam multi-round probe established.\n */\nexport function thesisReadinessSpecs(input: ThesisTaskInput): KnowledgeReadinessSpec[] {\n const c = input.company\n const t = input.ticker\n const filing = `${c} ${t} SEC 10-K annual report SEC.gov EDGAR filing`\n return [\n defineReadinessSpec({\n id: 'thesis/filing',\n description: `the most recent SEC 10-K annual report for ${c} (${t}) filed on or before ${input.cutoff}, from SEC EDGAR`,\n query: filing,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n defineReadinessSpec({\n id: 'thesis/balance-sheet',\n description: `${c} balance-sheet risks: securities marked below cost, unrealized losses, leverage / total debt, debt maturities, interest expense`,\n query: `${c} ${t} 10-K balance sheet total debt unrealized losses interest expense leverage`,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n defineReadinessSpec({\n id: 'thesis/concentration-liquidity',\n description: `${c} concentration + liquidity: customer / deposit / revenue concentration, uninsured deposits, operating cash flow, net loss, inventory, equity erosion`,\n query: `${c} ${t} 10-K customer deposit concentration operating cash flow net loss inventory`,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n defineReadinessSpec({\n id: 'thesis/governance-regulatory',\n description: `${c} governance + regulatory: related-party transactions, dual-class / super-voting control, buybacks / dividends, recalls, regulatory or legal exposure, margin trends`,\n query: `${c} ${t} 10-K related party dual class share repurchase recall regulatory gross margin`,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n ]\n}\n\n/**\n * The thesis-writer prompt. After the loop has fetched + curated the filings, we\n * ask the model to SYNTHESIZE a thesis page from the curated KB text — a\n * judgment, the key drivers, and the material risks, grounded ONLY in the fetched\n * evidence. The held-out checklist is NOT in this prompt; the model writes from\n * what the loop actually pulled, so a fact only appears if the research surfaced\n * the underlying evidence.\n */\nfunction thesisSynthesisMessages(\n input: ThesisTaskInput,\n kbText: string,\n): { role: 'system' | 'user'; content: string }[] {\n const system =\n 'You are a buy-side investment analyst writing a thesis memo. You are given ' +\n 'the raw research your team gathered from public filings (SEC 10-K) and the web. ' +\n 'Write a thesis that a thorough analyst would write: lead with your JUDGMENT, ' +\n 'then the KEY DRIVERS, then the MATERIAL RISKS. Be specific and quantitative — ' +\n 'name the actual figures, balance-sheet items, concentrations, leverage, ' +\n 'margin trends, governance items, and regulatory exposures that appear in the ' +\n 'research. Surface the buried, non-obvious drivers a one-line ticker summary ' +\n 'misses. Ground every claim in the research provided; do NOT invent figures. ' +\n 'If the research does not contain a figure, do not state it.'\n const user = [\n `Company: ${input.company} (${input.ticker})`,\n `As-of date (reason as if it is this date): ${input.cutoff}`,\n input.sector ? `Sector: ${input.sector}` : '',\n '',\n 'Research gathered (filings + web excerpts):',\n '\"\"\"',\n kbText.slice(0, 24000),\n '\"\"\"',\n '',\n 'Write the investment thesis now. Structure:',\n '## Judgment',\n '## Key drivers',\n '## Material risks',\n ]\n .filter(Boolean)\n .join('\\n')\n return [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ]\n}\n\n/** Write the synthesis thesis page into the KB so the index + metric pick it up. */\nasync function writeThesisPage(\n root: string,\n input: ThesisTaskInput,\n thesis: string,\n): Promise<string> {\n return withKnowledgeMutation(root, async () => {\n const relativePath = `knowledge/thesis-${slugify(input.ticker)}.md`\n const body = [\n '---',\n `title: Investment thesis — ${input.company} (${input.ticker})`,\n `ticker: ${input.ticker}`,\n `cutoff: ${input.cutoff}`,\n 'kind: investment-thesis',\n '---',\n `# Investment thesis — ${input.company} (${input.ticker}), as of ${input.cutoff}`,\n '',\n thesis.trim(),\n '',\n ].join('\\n')\n await writeFileDurableWithinRoot(root, relativePath, body, { encoding: 'utf8' })\n return join(root, relativePath)\n })\n}\n\nexport interface ThesisRunOptions {\n /** The KB root the loop writes into. */\n root: string\n /** Shared router client (web search + chat). Defaults to env creds. */\n router: RouterClient\n /** The driver — verify/dedup or research-driving. The loop's coordinator. */\n driver: ResearchDriver\n /** Round budget. Default 3 (the depth-driving driver needs >1). */\n maxRounds?: number\n /** Worker tuning forwarded to `createWebResearchWorker`. */\n workerOptions?: Omit<WebResearchWorkerOptions, 'router'>\n /** Max tokens for the synthesis pass. Default 1600 (above glm-5.2's reasoning floor). */\n synthesisMaxTokens?: number\n signal?: AbortSignal\n}\n\nexport interface ThesisRunResult {\n loop: VerifiedResearchLoopResult\n /** The synthesized thesis text. */\n thesis: string\n /** Path of the thesis page written into the KB. */\n thesisPath: string\n}\n\n/**\n * Run the full thesis task: drive the two-agent loop to research the company AS\n * OF the cutoff, then synthesize + write the thesis page. Returns the loop result\n * + the thesis text + the page path. The caller grades the KB with\n * `materialFactsSurfaced(root, checklist)` — the checklist is never passed here.\n */\nexport async function runInvestmentThesisTask(\n input: ThesisTaskInput,\n options: ThesisRunOptions,\n): Promise<ThesisRunResult> {\n const worker = createWebResearchWorker({ ...options.workerOptions, router: options.router })\n const goal = `${input.company} (${input.ticker}) investment thesis as of ${input.cutoff}`\n\n const loop = await runVerifiedResearchLoop({\n root: options.root,\n goal,\n worker,\n driver: options.driver,\n readinessSpecs: thesisReadinessSpecs(input),\n maxRounds: options.maxRounds ?? 3,\n signal: options.signal,\n })\n\n // Synthesize the thesis from what the loop actually curated + fetched.\n const index = await buildKnowledgeIndex(options.root)\n const kbText = kbIndexToText(index)\n const messages = thesisSynthesisMessages(input, kbText)\n const thesis = await options.router.chat(messages, options.synthesisMaxTokens ?? 1600)\n\n const thesisPath = await writeThesisPage(options.root, input, thesis)\n return { loop, thesis, thesisPath }\n}\n","/**\n * `materialFactsSurfaced` — the held-out investment-research METRIC.\n *\n * Given a knowledge base a research loop built for a company and the company's\n * HELD-OUT material-fact checklist (`tests/eval/investment-thesis-set.ts`, never\n * shown to the loop), this returns the FRACTION of checklist items the KB's\n * pages surface + ground. The check is the same `$0`, model-free, deterministic\n * substring grader the loop's checklist already ships (`gradeFactAgainstText` /\n * `gradeCompanyAgainstText`) — so the answer key never reaches a model the loop\n * could observe, exactly the firewall the ML deep-question exam uses.\n *\n * The ONLY thing this file adds over the raw grader is the KB→text join: it reads\n * the curated pages (and the raw source text) the loop wrote and hands their\n * concatenation to the grader. That join mirrors `kbText` in the research-quality\n * A/B (research-driving-ab.test.ts) so the thesis metric and the ML-exam metric\n * read a KB the same way.\n *\n * WHY pages AND source text: an honest thesis surfaces a buried fact in its\n * curated thesis PAGE (the judgment), but a loop whose page is thin while its\n * fetched filings are rich should still get credit for what it actually pulled.\n * Grading the union is the faithful, not the lenient, choice — it rewards the\n * loop that REACHED the filing even if its synthesis was terse, and it cannot\n * manufacture a hit the underlying evidence does not contain.\n */\n\nimport { buildKnowledgeIndex } from './indexer'\nimport {\n type CompanyEvalCase,\n gradeCompanyAgainstText,\n gradeFactAgainstText,\n} from './investment-thesis-set'\nimport type { KnowledgeIndex } from './types'\n\n/** Per-fact grade plus the fact's id/lens, for the audit trail. */\nexport interface FactResult {\n id: string\n lens: CompanyEvalCase['facts'][number]['lens']\n surfaced: boolean\n groupsFound: number\n groupsTotal: number\n foundLabels: string[]\n}\n\n/** The metric's result for one company: the surfaced fraction + the per-fact trail. */\nexport interface MaterialFactsResult {\n ticker: string\n company: string\n /** Held-out facts the KB surfaced + grounded. */\n surfaced: number\n /** Total held-out facts for this company (the denominator). */\n total: number\n /** `surfaced / total` in [0, 1]. */\n fraction: number\n /** Per-fact grade, in checklist order, for the doc / audit. */\n perFact: FactResult[]\n}\n\n/**\n * Join a KB index into the single text blob the grader scans: every curated PAGE\n * (title + body) followed by every raw SOURCE (title + fetched text). This is the\n * text read AFTER the loop finished — it is never handed to the loop. Identical\n * in spirit to `kbText` in the research-quality A/B so both metrics read a KB the\n * same way.\n */\nexport function kbIndexToText(index: KnowledgeIndex): string {\n const pageText = index.pages.map((page) => `${page.title}\\n${page.text}`).join('\\n\\n')\n const sourceText = index.sources\n .map((source) => `${source.title ?? ''}\\n${source.text ?? ''}`)\n .join('\\n\\n')\n return `${pageText}\\n\\n${sourceText}`\n}\n\n/**\n * Grade one company's KB against its held-out material-fact checklist, given the\n * KB's already-joined text. The pure core — no I/O — so calibration can score a\n * hand-written shallow/deep thesis string directly and the live path can score a\n * real KB. Returns the surfaced FRACTION plus the per-fact audit trail.\n */\nexport function materialFactsSurfacedInText(\n company: CompanyEvalCase,\n kbText: string,\n): MaterialFactsResult {\n const grade = gradeCompanyAgainstText(company, kbText)\n const perFact: FactResult[] = company.facts.map((fact) => {\n const r = gradeFactAgainstText(fact, kbText)\n return {\n id: fact.id,\n lens: fact.lens,\n surfaced: r.surfaced,\n groupsFound: r.groupsFound,\n groupsTotal: r.groupsTotal,\n foundLabels: r.foundLabels,\n }\n })\n return {\n ticker: company.ticker,\n company: company.company,\n surfaced: grade.surfaced,\n total: grade.total,\n fraction: grade.total === 0 ? 0 : grade.surfaced / grade.total,\n perFact,\n }\n}\n\n/**\n * `materialFactsSurfaced(kb, checklist)` — the metric in its KB-reading form.\n *\n * `kb` is EITHER a knowledge-base root directory (the loop wrote pages there) or\n * an already-built `KnowledgeIndex`. `checklist` is the company's held-out\n * `CompanyEvalCase`. Returns the surfaced fraction + per-fact trail.\n *\n * The checklist is HELD OUT by construction: it lives in the test eval set, is\n * never passed to the loop, and is read only here, after the loop finished.\n */\nexport async function materialFactsSurfaced(\n kb: string | KnowledgeIndex,\n checklist: CompanyEvalCase,\n): Promise<MaterialFactsResult> {\n const index = typeof kb === 'string' ? await buildKnowledgeIndex(kb) : kb\n return materialFactsSurfacedInText(checklist, kbIndexToText(index))\n}\n","import type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n buildEvalKnowledgeBundle,\n type EvalKnowledgeBundleBuildResult,\n type KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport { createKnowledgeEvent } from './events'\nimport { buildKnowledgeIndex } from './indexer'\nimport { applyKnowledgeWriteBlocks } from './proposals'\nimport { readinessFor } from './readiness-helpers'\nimport { searchKnowledge } from './search'\nimport { type AddSourceOptions, type AddSourceTextInput, addSourceText } from './sources'\nimport { initKnowledgeBase } from './store'\nimport type { KnowledgeEvent, KnowledgeIndex, KnowledgeSearchResult, SourceRecord } from './types'\n\n/**\n * A knowledge gap the loop surfaces from `scoreKnowledgeReadiness`. The worker\n * targets these; the driver folds the unfilled remainder into the worker's next\n * prompt and runs its own gap-fill pass over them.\n */\nexport interface KnowledgeGap {\n /** Readiness-spec id this gap belongs to. */\n id: string\n /** Human-readable description of what's missing. */\n description: string\n /** The search query the readiness check ran for this requirement. */\n query: string\n /** True when the gap blocks readiness (vs. a soft, non-blocking gap). */\n blocking: boolean\n}\n\n/** A new source the worker (or driver) discovered and wants to add to the KB. */\nexport type ResearchSourceProposal = AddSourceTextInput\n\n/**\n * What a research agent contributes in one round. Both the worker and (when\n * `driverResearches` is on) the driver produce this shape — the worker ADDS\n * primary findings, the driver gap-FILLS the ones the worker missed.\n *\n * `proposalText` is the safe write-protocol text (`---FILE: knowledge/...---`\n * blocks). The loop only applies it AFTER the driver has verified the round's\n * sources, so a rejected source never reaches the curated pages.\n */\nexport interface ResearchContribution {\n /** Immutable sources to register (the raw evidence). */\n sources?: ResearchSourceProposal[]\n /** Safe write-protocol text producing curated `knowledge/*.md` pages. */\n proposalText?: string\n /**\n * Build the page write-protocol text FROM the sources the driver accepted —\n * the curated, citing pages the readiness gate searches. Receives the\n * registered `SourceRecord`s (with their assigned ids, so a page's frontmatter\n * `sources:` can cite them). Returns `---FILE: knowledge/...---` block text or\n * `undefined`. Runs after verification, so a page never cites a rejected\n * source. Concatenated after any static `proposalText`.\n */\n buildPages?: (acceptedSources: SourceRecord[]) => string | undefined\n /** Free-form research transcript — products can persist this. */\n notes?: string\n metadata?: Record<string, unknown>\n}\n\n/** Context handed to the worker each round. */\nexport interface WorkerResearchContext {\n root: string\n goal: string\n round: number\n index: KnowledgeIndex\n /** Gaps the readiness gate currently reports — what the worker should close. */\n gaps: KnowledgeGap[]\n /** Steer text the driver folded in from the previous round's remaining gaps. */\n steer?: string\n readiness: EvalKnowledgeBundleBuildResult\n signal?: AbortSignal\n}\n\n/** Context handed to the driver's verifier for one candidate source. */\nexport interface SourceVerificationContext {\n root: string\n goal: string\n round: number\n index: KnowledgeIndex\n gaps: KnowledgeGap[]\n /** Sources already accepted earlier THIS round (in-round dedup). */\n acceptedThisRound: ResearchSourceProposal[]\n signal?: AbortSignal\n}\n\n/** A single rejected source plus the reason the driver gave. */\nexport interface RejectedSource {\n source: ResearchSourceProposal\n reason: string\n}\n\n/** Context handed to the driver's gap-fill pass (only when `driverResearches`). */\nexport interface DriverResearchContext {\n root: string\n goal: string\n round: number\n index: KnowledgeIndex\n /** Gaps STILL open after the worker's accepted contribution applied. */\n remainingGaps: KnowledgeGap[]\n readiness: EvalKnowledgeBundleBuildResult\n signal?: AbortSignal\n}\n\n/**\n * The differentiated driver role.\n *\n * - `verifySource` — the gate the worker's additions pass before they commit.\n * Return `{ accept: true }` to keep a source or `{ accept: false, reason }`\n * to reject it (not real / not relevant / duplicate). The loop dedups exact\n * duplicates (same `uri` already in the KB or accepted this round) BEFORE\n * calling this, so the verifier only sees genuinely-new candidates.\n * - `research` — the driver's OWN gap-fill pass over the gaps the worker left\n * open. Only invoked when `driverResearches` is true.\n * - `foldGaps` — turn the remaining gaps into a steer string for the worker's\n * next prompt. Defaults to a compact bulleted list when omitted.\n */\nexport interface ResearchDriver {\n verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> | SourceVerdict\n research?(ctx: DriverResearchContext): Promise<ResearchContribution> | ResearchContribution\n foldGaps?(gaps: KnowledgeGap[]): string\n}\n\nexport type SourceVerdict = { accept: true } | { accept: false; reason: string }\n\n/** The worker: primary research targeting the round's gaps. */\nexport type ResearchWorker = (\n ctx: WorkerResearchContext,\n) => Promise<ResearchContribution> | ResearchContribution\n\nexport interface VerifiedResearchLoopOptions {\n root: string\n goal: string\n worker: ResearchWorker\n driver: ResearchDriver\n /**\n * When false (default), the driver ONLY verifies + gates — a pure coordinator\n * that contributes no research of its own (the \"doesn't participate in the\n * work\" mode). When true, the driver also runs its `research` gap-fill pass\n * each round over the gaps the worker left open.\n */\n driverResearches?: boolean\n maxRounds?: number\n actor?: string\n /** Readiness specs define the gate; an empty list means the loop never gates. */\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>\n signal?: AbortSignal\n onRound?: (round: VerifiedResearchRound) => Promise<void> | void\n}\n\nexport interface VerifiedResearchRound {\n round: number\n /** Gaps reported at the START of the round (what the worker targeted). */\n gaps: KnowledgeGap[]\n /** Worker sources accepted by the driver and written to the KB. */\n acceptedWorkerSources: SourceRecord[]\n /** Worker sources the driver rejected (with reasons) — never written. */\n rejectedWorkerSources: RejectedSource[]\n /** Sources the driver itself added in its gap-fill pass. */\n driverSources: SourceRecord[]\n /** Curated pages written this round (worker proposal + driver proposal). */\n writtenPages: string[]\n readiness?: EvalKnowledgeBundleBuildResult\n /** True once the readiness gate reports no blocking gaps. */\n ready: boolean\n event: KnowledgeEvent\n notes: { worker?: string; driver?: string }\n}\n\nexport interface VerifiedResearchLoopResult {\n root: string\n goal: string\n rounds: number\n ready: boolean\n index: KnowledgeIndex\n readiness?: EvalKnowledgeBundleBuildResult\n steps: VerifiedResearchRound[]\n}\n\n/**\n * Two-agent (driver + worker) sibling of `runKnowledgeResearchLoop`.\n *\n * Both agents research to grow ONE knowledge base. The roles are differentiated:\n *\n * - **WORKER** = primary research. Each round it reads the open gaps, discovers\n * new sources, and proposes additions (`sources` + `proposalText`). It ADDS.\n * - **DRIVER** = the verifier / gap-filler / gate. It (1) VERIFIES the worker's\n * sources before they commit — dedup against the KB, then `verifySource`\n * rejects ones that aren't real/relevant; (2) GAP-FILLS the gaps the worker\n * missed with its own research pass (when `driverResearches`); (3) folds the\n * remaining gaps into the worker's next prompt; and (4) GATES on\n * `scoreKnowledgeReadiness` — the loop stops as soon as there are no blocking\n * gaps.\n *\n * Set `driverResearches: false` (default) for the pure-coordinator mode: the\n * driver only verifies + gates and contributes no research itself.\n *\n * Composes existing atoms — `initKnowledgeBase`, `addSourceText`,\n * `applyKnowledgeWriteBlocks`, `buildEvalKnowledgeBundle` (the readiness gate),\n * and `searchKnowledge` — and reinvents none of them.\n */\nexport async function runVerifiedResearchLoop(\n options: VerifiedResearchLoopOptions,\n): Promise<VerifiedResearchLoopResult> {\n const maxRounds = Math.max(1, options.maxRounds ?? 3)\n await initKnowledgeBase(options.root)\n const steps: VerifiedResearchRound[] = []\n let index = await buildKnowledgeIndex(options.root)\n let readiness = readinessFor(options, index)\n let ready = isReady(readiness?.report)\n let steer: string | undefined\n\n for (let round = 1; round <= maxRounds && !ready; round++) {\n if (options.signal?.aborted) throw new Error('Two-agent research loop aborted')\n\n const gaps = gapsFromReadiness(readiness)\n\n // 1. WORKER: primary research over the open gaps.\n const workerContribution = await options.worker({\n root: options.root,\n goal: options.goal,\n round,\n index,\n gaps,\n steer,\n readiness: requireReadiness(readiness, options),\n signal: options.signal,\n })\n\n // 2. DRIVER VERIFIES the worker's sources before they commit.\n const accepted: ResearchSourceProposal[] = []\n const rejectedWorkerSources: RejectedSource[] = []\n // Dedup against the ORIGINAL input uri. `addSourceText` rewrites `record.uri`\n // to a slugified raw path and stashes the caller's uri under\n // `metadata.originalUri`, so that — not the stored uri — is the round-to-round\n // identity a verifier dedups against.\n const existingUris = new Set(\n index.sources.flatMap((source) =>\n typeof source.metadata?.originalUri === 'string' ? [source.metadata.originalUri] : [],\n ),\n )\n for (const source of workerContribution.sources ?? []) {\n if (isDuplicate(source, existingUris, accepted)) {\n rejectedWorkerSources.push({ source, reason: 'duplicate: already in the knowledge base' })\n continue\n }\n const verdict = await options.driver.verifySource(source, {\n root: options.root,\n goal: options.goal,\n round,\n index,\n gaps,\n acceptedThisRound: accepted,\n signal: options.signal,\n })\n if (verdict.accept) accepted.push(source)\n else rejectedWorkerSources.push({ source, reason: verdict.reason })\n }\n\n // Register the accepted worker sources, then apply the worker's curated\n // pages — but only when at least one source survived verification, so a\n // page never cites a rejected source.\n const acceptedWorkerSources = await registerSources(options, accepted)\n const writtenPages: string[] = []\n writtenPages.push(\n ...(await applyPages(options.root, workerContribution, acceptedWorkerSources)),\n )\n\n // Re-index so the driver's gap-fill pass sees the worker's contribution.\n index = await buildKnowledgeIndex(options.root)\n readiness = readinessFor(options, index)\n\n // 3. DRIVER GAP-FILLS the gaps the worker left open (opt-in).\n let driverSources: SourceRecord[] = []\n let driverNotes: string | undefined\n if (options.driverResearches && options.driver.research) {\n const remainingGaps = gapsFromReadiness(readiness)\n const driverContribution = await options.driver.research({\n root: options.root,\n goal: options.goal,\n round,\n index,\n remainingGaps,\n readiness: requireReadiness(readiness, options),\n signal: options.signal,\n })\n driverNotes = driverContribution.notes\n driverSources = await registerSources(options, driverContribution.sources ?? [])\n writtenPages.push(...(await applyPages(options.root, driverContribution, driverSources)))\n index = await buildKnowledgeIndex(options.root)\n readiness = readinessFor(options, index)\n }\n\n // 4. DRIVER GATES on readiness and folds the remainder into the next prompt.\n ready = isReady(readiness?.report)\n const remainingGaps = gapsFromReadiness(readiness)\n steer = ready ? undefined : foldGaps(options.driver, remainingGaps)\n\n const step: VerifiedResearchRound = {\n round,\n gaps,\n acceptedWorkerSources,\n rejectedWorkerSources,\n driverSources,\n writtenPages,\n readiness,\n ready,\n event: createKnowledgeEvent({\n type: 'research.iteration',\n actor: options.actor,\n target: options.root,\n metadata: {\n goal: options.goal,\n round,\n ready,\n acceptedWorkerSourceCount: acceptedWorkerSources.length,\n rejectedWorkerSourceCount: rejectedWorkerSources.length,\n driverSourceCount: driverSources.length,\n writtenPageCount: writtenPages.length,\n remainingGapCount: remainingGaps.length,\n },\n }),\n notes: { worker: workerContribution.notes, driver: driverNotes },\n }\n steps.push(step)\n await options.onRound?.(step)\n }\n\n return {\n root: options.root,\n goal: options.goal,\n rounds: steps.length,\n ready,\n index,\n readiness,\n steps,\n }\n}\n\nfunction isReady(report: KnowledgeReadinessReport | undefined): boolean {\n // No specs ⇒ no gate ⇒ the loop runs to `maxRounds`. With specs, the gate is\n // \"no blocking gaps remain\".\n if (!report) return false\n return report.blockingMissingRequirements.length === 0\n}\n\nfunction gapsFromReadiness(readiness: EvalKnowledgeBundleBuildResult | undefined): KnowledgeGap[] {\n if (!readiness) return []\n const blocking = readiness.report.blockingMissingRequirements.map((requirement) =>\n gapFor(requirement, readiness, true),\n )\n const nonBlocking = readiness.report.nonBlockingGaps.map((requirement) =>\n gapFor(requirement, readiness, false),\n )\n return [...blocking, ...nonBlocking]\n}\n\nfunction gapFor(\n requirement: { id: string; description: string; metadata?: Record<string, unknown> },\n readiness: EvalKnowledgeBundleBuildResult,\n blocking: boolean,\n): KnowledgeGap {\n const spec = readiness.requirements.find((entry) => entry.id === requirement.id)\n const query =\n typeof spec?.metadata?.query === 'string' ? spec.metadata.query : requirement.description\n return { id: requirement.id, description: requirement.description, query, blocking }\n}\n\nfunction foldGaps(driver: ResearchDriver, gaps: KnowledgeGap[]): string | undefined {\n if (gaps.length === 0) return undefined\n if (driver.foldGaps) return driver.foldGaps(gaps)\n return [\n 'The knowledge base is still missing the following. Prioritise these next round:',\n ...gaps.map(\n (gap) => `- (${gap.blocking ? 'blocking' : 'soft'}) ${gap.description} [${gap.id}]`,\n ),\n ].join('\\n')\n}\n\nfunction isDuplicate(\n source: ResearchSourceProposal,\n existingUris: Set<string>,\n accepted: ResearchSourceProposal[],\n): boolean {\n return existingUris.has(source.uri) || accepted.some((candidate) => candidate.uri === source.uri)\n}\n\nasync function registerSources(\n options: VerifiedResearchLoopOptions,\n sources: ResearchSourceProposal[],\n): Promise<SourceRecord[]> {\n const records: SourceRecord[] = []\n for (const source of sources) {\n records.push(await addSourceText(options.root, source, options.sourceOptions))\n }\n return records\n}\n\n/**\n * Apply a contribution's curated pages. Static `proposalText` plus a\n * `buildPages(acceptedSources)` result are concatenated and run through the safe\n * write protocol — but ONLY when at least one source survived verification, so a\n * page never cites a rejected (or absent) source.\n */\nasync function applyPages(\n root: string,\n contribution: ResearchContribution,\n acceptedSources: SourceRecord[],\n): Promise<string[]> {\n if (acceptedSources.length === 0) return []\n const parts: string[] = []\n if (contribution.proposalText) parts.push(contribution.proposalText)\n const built = contribution.buildPages?.(acceptedSources)\n if (built) parts.push(built)\n if (parts.length === 0) return []\n const applied = await applyKnowledgeWriteBlocks(root, parts.join('\\n'))\n return applied.written\n}\n\nfunction requireReadiness(\n readiness: EvalKnowledgeBundleBuildResult | undefined,\n options: VerifiedResearchLoopOptions,\n): EvalKnowledgeBundleBuildResult {\n if (readiness) return readiness\n // The worker/driver contexts type `readiness` as required for ergonomics; when\n // no specs are configured there is no gate to report, so synthesise an empty\n // bundle rather than forcing every caller to handle `undefined`.\n return buildEvalKnowledgeBundle({\n ...(options.readiness ?? {}),\n taskId: options.readinessTaskId ?? options.goal,\n index: emptyIndex(options.root),\n specs: [],\n })\n}\n\nfunction emptyIndex(root: string): KnowledgeIndex {\n return {\n root,\n generatedAt: new Date(0).toISOString(),\n sources: [],\n pages: [],\n graph: { nodes: [], edges: [] },\n }\n}\n\n/**\n * Helper for verifiers: does the candidate source's text/title overlap any page\n * the readiness search returns for a gap query? A cheap relevance heuristic the\n * driver can compose into `verifySource` (real verifiers can do more).\n */\nexport function sourceMatchesGaps(\n source: ResearchSourceProposal,\n index: KnowledgeIndex,\n gaps: KnowledgeGap[],\n): KnowledgeSearchResult[] {\n const haystack = `${source.title ?? ''}\\n${source.text}`.toLowerCase()\n const hits: KnowledgeSearchResult[] = []\n for (const gap of gaps) {\n for (const token of gap.query.toLowerCase().split(/\\s+/).filter(Boolean)) {\n if (haystack.includes(token)) {\n hits.push(...searchKnowledge(index, gap.query, 1))\n break\n }\n }\n }\n return hits\n}\n\n// ── Deprecated aliases ───────────────────────────────────────────────────────────\n// The old \"TwoAgent\" names described the MECHANISM (a proposer worker + a verifier driver)\n// instead of the VALUE (research whose sources are verified before admission). Kept as\n// aliases so existing importers do not break; prefer the `Verified*` names.\n\n/** @deprecated Renamed to {@link runVerifiedResearchLoop}. */\nexport const runTwoAgentResearchLoop = runVerifiedResearchLoop\n/** @deprecated Renamed to {@link VerifiedResearchLoopOptions}. */\nexport type TwoAgentResearchLoopOptions = VerifiedResearchLoopOptions\n/** @deprecated Renamed to {@link VerifiedResearchLoopResult}. */\nexport type TwoAgentResearchLoopResult = VerifiedResearchLoopResult\n/** @deprecated Renamed to {@link VerifiedResearchRound}. */\nexport type TwoAgentResearchRound = VerifiedResearchRound\n","import { z } from 'zod'\nimport { readRegularFileWithinRoot, writeJsonDurableWithinRoot } from './durable-fs'\nimport type { KnowledgeEventQuery } from './events'\nimport { buildKnowledgeGraph } from './graph'\nimport { withKnowledgeMutation, withKnowledgeRead } from './mutation-lock'\nimport {\n KnowledgeEventSchema,\n KnowledgeIndexSchema,\n KnowledgePageSchema,\n SourceRecordSchema,\n} from './schemas'\nimport type { KnowledgeEvent, KnowledgeIndex, KnowledgePage, SourceRecord } from './types'\n\nexport interface KbStore {\n putSource(source: SourceRecord): Promise<void>\n getSource(id: string): Promise<SourceRecord | null>\n listSources(): Promise<SourceRecord[]>\n putPage(page: KnowledgePage): Promise<void>\n getPage(idOrPath: string): Promise<KnowledgePage | null>\n listPages(): Promise<KnowledgePage[]>\n putIndex(index: KnowledgeIndex): Promise<void>\n getIndex(): Promise<KnowledgeIndex | null>\n putEvent(event: KnowledgeEvent): Promise<void>\n listEvents(query?: KnowledgeEventQuery): Promise<KnowledgeEvent[]>\n}\n\nexport class MemoryKbStore implements KbStore {\n private readonly sources = new Map<string, SourceRecord>()\n private readonly pages = new Map<string, KnowledgePage>()\n private readonly events: KnowledgeEvent[] = []\n private index: KnowledgeIndex | null = null\n\n async putSource(source: SourceRecord): Promise<void> {\n this.sources.set(source.id, clone(source))\n }\n\n async getSource(id: string): Promise<SourceRecord | null> {\n return clone(this.sources.get(id) ?? null)\n }\n\n async listSources(): Promise<SourceRecord[]> {\n return [...this.sources.values()].map(clone)\n }\n\n async putPage(page: KnowledgePage): Promise<void> {\n this.pages.set(page.id, clone(page))\n }\n\n async getPage(idOrPath: string): Promise<KnowledgePage | null> {\n return clone(\n this.pages.get(idOrPath) ??\n [...this.pages.values()].find((page) => page.path === idOrPath) ??\n null,\n )\n }\n\n async listPages(): Promise<KnowledgePage[]> {\n return [...this.pages.values()].map(clone)\n }\n\n async putIndex(index: KnowledgeIndex): Promise<void> {\n this.index = clone(index)\n }\n\n async getIndex(): Promise<KnowledgeIndex | null> {\n if (this.index) return clone(this.index)\n const pages = await this.listPages()\n const sources = await this.listSources()\n return {\n root: 'memory',\n generatedAt: new Date().toISOString(),\n sources,\n pages,\n graph: buildKnowledgeGraph(pages),\n }\n }\n\n async putEvent(event: KnowledgeEvent): Promise<void> {\n this.events.push(clone(event))\n }\n\n async listEvents(query: KnowledgeEventQuery = {}): Promise<KnowledgeEvent[]> {\n let out = this.events\n if (query.type) out = out.filter((event) => event.type === query.type)\n if (query.target) out = out.filter((event) => event.target === query.target)\n out = [...out].sort((a, b) => a.createdAt.localeCompare(b.createdAt))\n return out.slice(-(query.limit ?? out.length)).map(clone)\n }\n}\n\nconst knowledgeEventsSchema = z.array(KnowledgeEventSchema)\n\nexport class FileSystemKbStore implements KbStore {\n constructor(private readonly dir: string) {}\n\n async putSource(source: SourceRecord): Promise<void> {\n const parsed = SourceRecordSchema.parse(source) as SourceRecord\n await this.updateIndex((index) => ({\n ...index,\n generatedAt: new Date().toISOString(),\n sources: [parsed, ...index.sources.filter((entry) => entry.id !== parsed.id)],\n }))\n }\n\n async getSource(id: string): Promise<SourceRecord | null> {\n return withKnowledgeRead(this.dir, async () => {\n const index = await this.readIndex()\n return clone(index?.sources.find((source) => source.id === id) ?? null)\n })\n }\n\n async listSources(): Promise<SourceRecord[]> {\n return withKnowledgeRead(this.dir, async () => clone((await this.readIndex())?.sources ?? []))\n }\n\n async putPage(page: KnowledgePage): Promise<void> {\n const parsed = KnowledgePageSchema.parse(page) as KnowledgePage\n await this.updateIndex((index) => {\n const pages = [parsed, ...index.pages.filter((entry) => entry.id !== parsed.id)]\n return {\n ...index,\n generatedAt: new Date().toISOString(),\n pages,\n graph: buildKnowledgeGraph(pages),\n }\n })\n }\n\n async getPage(idOrPath: string): Promise<KnowledgePage | null> {\n return withKnowledgeRead(this.dir, async () => {\n const index = await this.readIndex()\n return clone(\n index?.pages.find((page) => page.id === idOrPath || page.path === idOrPath) ?? null,\n )\n })\n }\n\n async listPages(): Promise<KnowledgePage[]> {\n return withKnowledgeRead(this.dir, async () => clone((await this.readIndex())?.pages ?? []))\n }\n\n async putIndex(index: KnowledgeIndex): Promise<void> {\n const parsed = KnowledgeIndexSchema.parse(index) as KnowledgeIndex\n await withKnowledgeMutation(this.dir, () =>\n writeJsonDurableWithinRoot(this.dir, 'index.json', parsed),\n )\n }\n\n async getIndex(): Promise<KnowledgeIndex | null> {\n return withKnowledgeRead(this.dir, () => this.readIndex())\n }\n\n async putEvent(event: KnowledgeEvent): Promise<void> {\n const parsed = KnowledgeEventSchema.parse(event) as KnowledgeEvent\n await withKnowledgeMutation(this.dir, async () => {\n const current = await this.readEvents()\n const next = [...current.filter((entry) => entry.id !== parsed.id), parsed].sort((a, b) =>\n a.createdAt.localeCompare(b.createdAt),\n )\n await writeJsonDurableWithinRoot(this.dir, 'events.json', next)\n })\n }\n\n async listEvents(query: KnowledgeEventQuery = {}): Promise<KnowledgeEvent[]> {\n return withKnowledgeRead(this.dir, async () => {\n let events = await this.readEvents()\n if (query.type) events = events.filter((event) => event.type === query.type)\n if (query.target) events = events.filter((event) => event.target === query.target)\n return clone(events.slice(-(query.limit ?? events.length)))\n })\n }\n\n private async updateIndex(change: (index: KnowledgeIndex) => KnowledgeIndex): Promise<void> {\n await withKnowledgeMutation(this.dir, async () => {\n const current = (await this.readIndex()) ?? emptyIndex(this.dir)\n const next = KnowledgeIndexSchema.parse(change(current)) as KnowledgeIndex\n await writeJsonDurableWithinRoot(this.dir, 'index.json', next)\n })\n }\n\n private async readIndex(): Promise<KnowledgeIndex | null> {\n return readJsonFile(\n this.dir,\n 'index.json',\n KnowledgeIndexSchema,\n ) as Promise<KnowledgeIndex | null>\n }\n\n private async readEvents(): Promise<KnowledgeEvent[]> {\n return ((await readJsonFile(this.dir, 'events.json', knowledgeEventsSchema)) ??\n []) as KnowledgeEvent[]\n }\n}\n\nfunction emptyIndex(root: string): KnowledgeIndex {\n return {\n root,\n generatedAt: new Date(0).toISOString(),\n sources: [],\n pages: [],\n graph: { nodes: [], edges: [] },\n }\n}\n\nasync function readJsonFile<T>(\n root: string,\n relativePath: string,\n schema: z.ZodType<T>,\n): Promise<T | null> {\n try {\n const file = await readRegularFileWithinRoot(root, relativePath)\n return schema.parse(JSON.parse(file.bytes.toString('utf8')))\n } catch (error) {\n if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return null\n throw error\n }\n}\n\nfunction clone<T>(value: T): T {\n return value == null ? value : (JSON.parse(JSON.stringify(value)) as T)\n}\n","/**\n * Bridge from `AnalystFinding` (agent-eval) to knowledge proposals.\n *\n * Closes the failure → wiki side of the recursive-self-improvement\n * loop: a knowledge-gap or knowledge-poisoning finding produced by an\n * analyst becomes a concrete proposal an operator (or auto-merge bot)\n * can review and apply. The bridge is intentionally lossless on the\n * fail-loud side — a finding the parser can't classify returns a\n * `KnowledgeProposalParseError` rather than a silent skip, so the\n * loop never accepts an underspecified edit.\n *\n * Subject grammar this bridge understands (analyst-side convention,\n * stamped in the kind prompts):\n *\n * agent-knowledge:wiki:<page-slug> create / update page\n * agent-knowledge:wiki:<page-slug>#<heading> insert section under page\n * agent-knowledge:claim:<topic> draft claim row\n * agent-knowledge:raw:<source-id> lift raw → curated\n * agent-knowledge:stale:<page-slug> mark page superseded\n *\n * Anything else (websearch:outdated:*, tool-doc:*, system-prompt:*,\n * memory:*) is NOT a knowledge-base concern and returns `null` so the\n * loop's improvement-applier handles it.\n */\n\nimport type { AnalystFinding, AnalystSeverity } from '@tangle-network/agent-eval'\nimport type { ClaimRef, KnowledgeClaim, KnowledgeWriteBlock } from './types'\n\nexport interface KnowledgeProposal {\n /**\n * Stable id derived from the finding so cross-run diffs share an\n * identity. Re-proposing the same finding produces the same id.\n */\n id: string\n /** The finding that generated this proposal — useful for audit + revert. */\n sourceFindingId: string\n /** What the proposal does. */\n kind:\n | 'create-page'\n | 'update-page'\n | 'append-section'\n | 'create-claim'\n | 'lift-raw'\n | 'mark-stale'\n /** Locus on disk (page slug or claim topic). */\n locus: string\n /**\n * Page write blocks the standard `applyKnowledgeWriteBlocks` consumer\n * accepts. Empty for proposals that don't change page text (e.g.\n * `create-claim` produces a `claim` field instead).\n */\n writeBlocks: KnowledgeWriteBlock[]\n /**\n * Granular claim draft for proposals whose unit-of-change is a claim\n * row rather than a whole page. `status: 'draft'` until reviewed.\n */\n claim?: KnowledgeClaim\n /** Per-proposal metadata: severity, confidence, source span. */\n metadata: {\n severity: AnalystSeverity\n confidence: number\n evidence_uri?: string\n analyst_id: string\n }\n}\n\nexport class KnowledgeProposalParseError extends Error {\n constructor(\n public readonly findingId: string,\n public readonly subject: string,\n message: string,\n ) {\n super(`proposeFromFinding(${findingId}, subject=${subject}): ${message}`)\n this.name = 'KnowledgeProposalParseError'\n }\n}\n\n/**\n * Convert one `AnalystFinding` into a knowledge proposal. Returns\n * `null` when the finding's locus isn't a knowledge-base concern\n * (`websearch:outdated:*`, `tool-doc:*`, `system-prompt:*`,\n * `memory:*`, missing subject). Throws when the locus IS a\n * knowledge-base concern but is malformed — that's a bug in the\n * analyst prompt and should fail loud.\n *\n * Caller convention: feed the function the analyst's full findings\n * list and filter out the `null`s; the orchestrator passes the\n * remaining proposals to the existing review / apply pipeline.\n */\nexport function proposeFromFinding(finding: AnalystFinding): KnowledgeProposal | null {\n if (!finding.subject) return null\n if (!finding.subject.startsWith('agent-knowledge:')) return null\n\n const rest = finding.subject.slice('agent-knowledge:'.length)\n const [kindPart, ...locusParts] = rest.split(':')\n const locus = locusParts.join(':')\n if (!kindPart || !locus) {\n throw new KnowledgeProposalParseError(\n finding.finding_id,\n finding.subject,\n 'expected `agent-knowledge:<kind>:<locus>` shape',\n )\n }\n\n const baseMeta: KnowledgeProposal['metadata'] = {\n severity: finding.severity,\n confidence: finding.confidence,\n evidence_uri: finding.evidence_refs[0]?.uri,\n analyst_id: finding.analyst_id,\n }\n\n switch (kindPart) {\n case 'wiki':\n return wikiProposal(finding, locus, baseMeta)\n case 'claim':\n return claimProposal(finding, locus, baseMeta)\n case 'raw':\n return liftRawProposal(finding, locus, baseMeta)\n case 'stale':\n return markStaleProposal(finding, locus, baseMeta)\n default:\n throw new KnowledgeProposalParseError(\n finding.finding_id,\n finding.subject,\n `unknown kind \"${kindPart}\" (expected one of: wiki | claim | raw | stale)`,\n )\n }\n}\n\nfunction wikiProposal(\n finding: AnalystFinding,\n locus: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const hashIdx = locus.indexOf('#')\n const pageSlug = hashIdx >= 0 ? locus.slice(0, hashIdx) : locus\n const heading = hashIdx >= 0 ? locus.slice(hashIdx + 1) : null\n const path = `knowledge/${ensureSlug(pageSlug)}.md`\n\n const body = renderWikiBody(finding, pageSlug, heading)\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: heading ? 'append-section' : 'create-page',\n locus: pageSlug,\n writeBlocks: [{ path, content: body }],\n metadata,\n }\n}\n\nfunction claimProposal(\n finding: AnalystFinding,\n locus: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const refs: ClaimRef[] = finding.evidence_refs\n .filter((r) => r.uri)\n .map((r) => ({\n sourceId: `analyst-finding:${finding.finding_id}`,\n anchorId: r.uri,\n quote: r.excerpt,\n }))\n const claim: KnowledgeClaim = {\n id: `claim-${finding.finding_id}`,\n text: finding.recommended_action ?? finding.claim,\n refs,\n confidence: finding.confidence,\n status: 'draft',\n metadata: {\n analyst_id: finding.analyst_id,\n source_finding_id: finding.finding_id,\n topic: locus,\n },\n }\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: 'create-claim',\n locus,\n writeBlocks: [],\n claim,\n metadata,\n }\n}\n\nfunction liftRawProposal(\n finding: AnalystFinding,\n sourceId: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const path = `knowledge/${ensureSlug(sourceId)}.md`\n const body = [\n '---',\n `title: ${sourceId}`,\n `source: ${sourceId}`,\n `status: draft`,\n `lifted_from_finding: ${finding.finding_id}`,\n '---',\n '',\n '## Why this page exists',\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['## Rationale', '', finding.rationale, ''] : []),\n ...(finding.recommended_action\n ? ['## Recommended action', '', finding.recommended_action, '']\n : []),\n ].join('\\n')\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: 'lift-raw',\n locus: sourceId,\n writeBlocks: [{ path, content: body }],\n metadata,\n }\n}\n\nfunction markStaleProposal(\n finding: AnalystFinding,\n pageSlug: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const path = `knowledge/${ensureSlug(pageSlug)}.stale.md`\n const body = [\n '---',\n `title: ${pageSlug} (marked stale)`,\n `status: superseded`,\n `superseded_by_finding: ${finding.finding_id}`,\n `confidence: ${finding.confidence}`,\n '---',\n '',\n '## Why marked stale',\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['## Evidence', '', finding.rationale, ''] : []),\n ...(finding.recommended_action ? ['## Action', '', finding.recommended_action, ''] : []),\n ].join('\\n')\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: 'mark-stale',\n locus: pageSlug,\n writeBlocks: [{ path, content: body }],\n metadata,\n }\n}\n\n/**\n * Plural convenience: filter + map across an entire findings batch\n * with one call. Parse errors collect into `errors[]`; the loop\n * decides per-error whether to abort or continue.\n */\nexport interface ProposeFromFindingsResult {\n proposals: KnowledgeProposal[]\n skipped: number\n errors: KnowledgeProposalParseError[]\n}\n\nexport function proposeFromFindings(\n findings: ReadonlyArray<AnalystFinding>,\n): ProposeFromFindingsResult {\n const proposals: KnowledgeProposal[] = []\n const errors: KnowledgeProposalParseError[] = []\n let skipped = 0\n for (const f of findings) {\n try {\n const p = proposeFromFinding(f)\n if (p) proposals.push(p)\n else skipped += 1\n } catch (err) {\n if (err instanceof KnowledgeProposalParseError) errors.push(err)\n else throw err\n }\n }\n return { proposals, skipped, errors }\n}\n\nfunction ensureSlug(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\nfunction renderWikiBody(finding: AnalystFinding, slug: string, heading: string | null): string {\n const title = humanize(slug)\n if (heading) {\n return [\n `## ${heading}`,\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['### Rationale', '', finding.rationale, ''] : []),\n ...(finding.recommended_action ? ['### Action', '', finding.recommended_action, ''] : []),\n `_Drafted from finding ${finding.finding_id} (confidence ${finding.confidence.toFixed(2)})._`,\n ].join('\\n')\n }\n return [\n '---',\n `title: ${title}`,\n `status: draft`,\n `drafted_from_finding: ${finding.finding_id}`,\n `confidence: ${finding.confidence}`,\n '---',\n '',\n `# ${title}`,\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['## Rationale', '', finding.rationale, ''] : []),\n ...(finding.recommended_action\n ? ['## Recommended action', '', finding.recommended_action, '']\n : []),\n ].join('\\n')\n}\n\nfunction humanize(slug: string): string {\n return (\n slug\n .split('-')\n .filter(Boolean)\n .map((w) => w[0]?.toUpperCase() + w.slice(1))\n .join(' ') || slug\n )\n}\n","import type {\n BuildEvalKnowledgeBundleOptions,\n EvalKnowledgeBundleBuildResult,\n KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport { buildKnowledgeIndex } from './indexer'\nimport {\n type KnowledgeBaseQualityOptions,\n type KnowledgeBaseQualityReport,\n scoreKnowledgeBaseIndex,\n} from './rag-eval'\nimport { readinessFor } from './readiness-helpers'\nimport type { KnowledgeIndex } from './types'\nimport {\n type ValidateKnowledgeOptions,\n type ValidateKnowledgeResult,\n validateKnowledgeIndex,\n} from './validate'\n\nexport interface EvaluateKnowledgeBaseReadinessOptions {\n root: string\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: ValidateKnowledgeOptions['strict']\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\nexport interface KnowledgeBaseReadinessEvaluation {\n ready: boolean\n summary: string\n index: KnowledgeIndex\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n kbQuality: KnowledgeBaseQualityReport\n dimensions: {\n validation: number\n kb_quality: number\n blocking_readiness: number\n }\n}\n\nexport async function evaluateKnowledgeBaseReadiness(\n options: EvaluateKnowledgeBaseReadinessOptions,\n): Promise<KnowledgeBaseReadinessEvaluation> {\n const index = await buildKnowledgeIndex(options.root)\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const readiness = readinessFor(\n {\n ...options,\n readinessSpecs: options.readinessSpecs ? [...options.readinessSpecs] : undefined,\n },\n index,\n )\n const kbQuality = scoreKnowledgeBaseIndex(index, {\n strict: options.strict,\n ...options.kbQuality,\n })\n const blockingMissing = readiness?.report.blockingMissingRequirements.length ?? 0\n const blockingTotal =\n options.readinessSpecs?.filter((spec) => spec.importance === 'blocking').length ?? 0\n const blockingReadiness =\n blockingTotal === 0 ? 1 : Math.max(0, blockingTotal - blockingMissing) / blockingTotal\n const ready = validation.ok && kbQuality.ok && blockingMissing === 0\n const failures = [\n validation.ok ? undefined : `${validation.findings.length} validation finding(s)`,\n kbQuality.ok ? undefined : `${kbQuality.findings.length} KB quality finding(s)`,\n blockingMissing === 0\n ? undefined\n : `${blockingMissing}/${blockingTotal} blocking readiness requirement(s) missing`,\n ].filter((failure): failure is string => Boolean(failure))\n\n return {\n ready,\n summary: ready ? 'knowledge base passed readiness checks' : failures.join('; '),\n index,\n validation,\n readiness,\n kbQuality,\n dimensions: {\n validation: validation.ok ? 1 : 0,\n kb_quality: kbQuality.ok ? 1 : 0,\n blocking_readiness: blockingReadiness,\n },\n }\n}\n","import {\n evaluateReleaseConfidence,\n type GateDecision,\n type ReleaseConfidenceScorecard,\n type ReleaseTraceEvidence,\n type RunRecord,\n validateRunRecord,\n} from '@tangle-network/agent-eval'\nimport { stableId } from './ids'\nimport type { KnowledgeRelease } from './types'\n\nexport interface KnowledgeReleaseReport {\n release: KnowledgeRelease\n scorecard: ReleaseConfidenceScorecard\n candidateRuns: RunRecord[]\n baselineRuns: RunRecord[]\n}\n\n/**\n * Campaign-native release report. The caller (a consumer's KB self-improvement\n * loop) supplies the candidate/baseline `RunRecord[]` (e.g. via\n * `campaignToRunRecords`) + optional per-instance `ReleaseTraceEvidence` + the\n * gate decision; this folds them into a `ReleaseConfidenceScorecard` + a\n * `KnowledgeRelease`. Release confidence is computed from run records + traces,\n * independent of any optimizer result shape.\n */\nexport interface KnowledgeReleaseInput {\n candidateId: string\n baselineId?: string\n candidateRuns: RunRecord[]\n baselineRuns?: RunRecord[]\n traces?: ReleaseTraceEvidence[]\n gateDecision?: GateDecision | null\n /**\n * True when a held-out split was evaluated (drives the holdout threshold).\n *\n * Constraint: the substrate gate keys the holdout requirement off a scenario\n * corpus, which this run-only report does not carry. With `hasHoldout: true`\n * the gate fails closed (`missing_holdout_split`) even when holdout RunRecords\n * are supplied. Callers that gate on a real held-out split should drive\n * `evaluateReleaseConfidence` directly with a dataset/scenarios.\n */\n hasHoldout?: boolean\n /** Candidate is the search-best variant — a promotion precondition. Default true. */\n promotedIsBest?: boolean\n createdAt?: string\n minScore?: number\n}\n\nexport function knowledgeReleaseReport(input: KnowledgeReleaseInput): KnowledgeReleaseReport {\n const baselineRuns = input.baselineRuns ?? []\n const runRecords = [...input.candidateRuns, ...baselineRuns].map(validateRunRecord)\n const scorecard = evaluateReleaseConfidence({\n target: 'agent-knowledge-base',\n candidateId: input.candidateId,\n baselineId: input.baselineId ?? 'baseline',\n traces: input.traces ?? [],\n runs: runRecords,\n gateDecision: input.gateDecision ?? null,\n thresholds: {\n requireCorpus: false,\n // The report gates on RunRecord-level outcomes, not on a separate scenario\n // corpus (KnowledgeReleaseInput carries no dataset/scenarios). The scenario\n // floor must therefore be 0 — otherwise the corpus axis fails closed on a\n // dimension the report has no way to satisfy, masking the run-based gate.\n minScenarioCount: 0,\n requireHoldout: input.hasHoldout ?? false,\n minHoldoutRuns: input.hasHoldout ? 1 : 0,\n minSearchRuns: 1,\n minMeanScore: input.minScore ?? 0.7,\n },\n })\n const release: KnowledgeRelease = {\n id: stableId('krel', `${input.candidateId}:${input.createdAt ?? new Date().toISOString()}`),\n candidateId: input.candidateId,\n createdAt: input.createdAt ?? new Date().toISOString(),\n promoted: scorecard.status !== 'fail' && (input.promotedIsBest ?? true),\n scorecard,\n runRecordIds: runRecords.map((record) => record.runId),\n }\n return { release, scorecard, candidateRuns: input.candidateRuns, baselineRuns }\n}\n","/**\n * Research-DRIVING driver for `runVerifiedResearchLoop`.\n *\n * The shipped drivers all FILTER the worker's sources:\n * - `createVerifyingResearchDriver` judges on-topic relevance,\n * - `createAdaptiveResearchDriver` dedups then triages then escalates,\n * - `createClaimGroundingVerifier` rejects misattributed citations.\n *\n * This driver does the OPPOSITE job: instead of narrowing the worker's output,\n * it DRIVES the research DEEPER each round. Its value is not \"fewer sources\" —\n * it is \"more answered, better-corroborated sub-questions\". Concretely, each\n * round it:\n *\n * 1. EXTRACTS the key claims from the worker's new sources (one LLM pass per\n * source, in `verifySource`; falls back to a deterministic sentence-pull\n * when the model is unavailable so a round never silently extracts nothing).\n * 2. TRACKS each claim's support — the set of INDEPENDENT sources (by canonical\n * host) that assert it — and detects CONTRADICTIONS between a new claim and\n * one already on the ledger.\n * 3. GENERATES the next round's DEEP sub-questions from the accumulated claims,\n * in four kinds — comparative (\"how does X's tradeoff differ from Y's?\"),\n * mechanism (\"under what precise condition does X fail?\"), gap (\"what\n * specific result is missing?\"), and contradiction (\"does any source\n * challenge claim Z?\").\n * 4. FLAGS weakly-supported claims (only ONE independent source) and\n * contradicted claims as INVALIDATION targets and demands the worker find\n * corroborating / refuting evidence for them.\n * 5. FOLDS the deep sub-questions + invalidation challenges into the worker's\n * next prompt via the loop's `foldGaps` → `steer` channel — that is the\n * mechanism that drives DEPTH and VALIDATION rather than breadth.\n *\n * COMPLETION (`isComplete` / the `done` judgment the caller gates on) does NOT\n * look at source COUNT. It is done only when every deep sub-question it raised\n * has been addressed AND every key claim is either supported by >= 2 independent\n * sources OR explicitly marked CONTESTED (a contradiction the loop surfaced and\n * could not resolve). A KB with twenty sources all asserting one unchallenged\n * claim is NOT done; a KB whose handful of claims are each corroborated or\n * contested IS.\n *\n * It reuses `runVerifiedResearchLoop` (it is a plain `ResearchDriver`), the web\n * worker, `sha256` (claim identity), `canonicalizeUrl` (independent-source\n * identity), and the `RouterClient` chat surface; it reinvents none of them.\n */\n\nimport { canonicalizeUrl } from './adaptive-driver'\nimport { sha256 } from './ids'\nimport type {\n KnowledgeGap,\n ResearchDriver,\n ResearchSourceProposal,\n SourceVerdict,\n SourceVerificationContext,\n} from './two-agent-research-loop'\nimport {\n createTangleRouterClient,\n type RouterClient,\n type TangleRouterOptions,\n} from './web-research-worker'\n\n/** The four deep sub-question kinds the driver generates to drive depth. */\nexport type DeepQuestionKind = 'comparative' | 'mechanism' | 'gap' | 'contradiction'\n\n/** A deep sub-question the driver folds into the worker's next prompt. */\nexport interface DeepQuestion {\n kind: DeepQuestionKind\n text: string\n /** sha256-derived stable id, so \"addressed\" can be tracked across rounds. */\n id: string\n /** Claim id(s) this question interrogates (for contradiction/mechanism kinds). */\n claimIds: string[]\n /** True once a later round's evidence addressed it (see `markAddressed`). */\n addressed: boolean\n /** The round this question was raised in. */\n raisedRound: number\n}\n\n/** One tracked claim plus the independent sources that assert it. */\nexport interface TrackedClaim {\n id: string\n /** The claim text as first extracted (kept for prompts/audit). */\n text: string\n /** Canonical hosts of the INDEPENDENT sources that assert this claim. */\n supportingHosts: Set<string>\n /** Source URIs that assert this claim (provenance; may share a host). */\n supportingUris: string[]\n /** Claim ids this claim was found to CONTRADICT (and vice versa). */\n contradicts: Set<string>\n /**\n * CONTESTED = a contradiction the loop surfaced but could not resolve to a\n * single supported claim. A contested claim counts as \"settled enough to be\n * done\" (we report the disagreement) even with < 2 independent sources.\n */\n contested: boolean\n firstSeenRound: number\n}\n\n/** The driver's accumulated research state — the completion oracle reads this. */\nexport interface ResearchDrivingState {\n /** Every claim extracted from the worker's sources, by id. */\n claims: TrackedClaim[]\n /** Every deep sub-question raised, by id. */\n questions: DeepQuestion[]\n /** Claims with exactly one independent source AND not contested. */\n weaklySupported: TrackedClaim[]\n /** Claims supported by >= 2 independent sources. */\n corroborated: TrackedClaim[]\n /** Claims marked contested (a surfaced, unresolved contradiction). */\n contested: TrackedClaim[]\n /** Deep questions still unaddressed. */\n openQuestions: DeepQuestion[]\n /** How many rounds the driver has folded steer for. */\n rounds: number\n}\n\nexport interface ResearchDrivingDriverOptions {\n /** Router client for claim extraction + deep-question generation. */\n router?: RouterClient\n router_options?: TangleRouterOptions\n /**\n * A claim is CORROBORATED at this many INDEPENDENT supporting sources (distinct\n * canonical hosts). Default 2 — the task's \">= 2 independent sources\" bar.\n */\n minIndependentSources?: number\n /** Max deep sub-questions to fold into one round's steer. Default 6. */\n maxQuestionsPerRound?: number\n /** Max claims to extract from a single source. Default 3. */\n maxClaimsPerSource?: number\n /**\n * When the extractor LLM is unavailable, fall back to a deterministic claim\n * pull (the source's leading sentences) so the driver still drives. Default\n * true. Set false to require the model (claims will be empty without it).\n */\n deterministicFallback?: boolean\n /** Observe each round's generated steer (for instrumentation / the script). */\n onSteer?: (steer: ResearchDrivingSteer) => void\n}\n\n/** What the driver folded into one round's worker prompt, surfaced for audit. */\nexport interface ResearchDrivingSteer {\n round: number\n deepQuestions: DeepQuestion[]\n /** Claims it demanded corroborating/refuting evidence for this round. */\n invalidationTargets: TrackedClaim[]\n /** The readiness gaps it interleaved (passed through from the loop). */\n gaps: KnowledgeGap[]\n /** The full steer text handed to the worker. */\n text: string\n}\n\n/**\n * The research-driving driver. It is a `ResearchDriver` (drops straight into\n * `runVerifiedResearchLoop`) PLUS a completion oracle and live state, mirroring\n * how `createAdaptiveResearchDriver` exposes `stats()`.\n */\nexport interface ResearchDrivingDriver extends ResearchDriver {\n /** Live snapshot of the claim ledger + deep questions. */\n researchState(): ResearchDrivingState\n /**\n * The completion oracle — gate `done` on THIS, not on source count. True when\n * every deep sub-question is addressed AND every claim is corroborated\n * (>= `minIndependentSources` independent sources) or explicitly contested.\n * False while any claim is weakly-supported or any deep question is open.\n * Returns false before any claim has been seen (nothing researched yet).\n */\n isComplete(): boolean\n /**\n * The last round's generated steer, or undefined before the first fold. Useful\n * to assert the driver produced deeper questions / invalidation challenges.\n */\n lastSteer(): ResearchDrivingSteer | undefined\n}\n\n/** A claim the extractor returns for one source. */\ninterface ExtractedClaim {\n text: string\n /** A claim id ALREADY on the ledger that this one CONTRADICTS, if the model says so. */\n contradictsExistingId?: string\n}\n\nexport function createResearchDrivingDriver(\n options: ResearchDrivingDriverOptions = {},\n): ResearchDrivingDriver {\n const minIndependentSources = Math.max(2, options.minIndependentSources ?? 2)\n const maxQuestionsPerRound = Math.max(1, options.maxQuestionsPerRound ?? 6)\n const maxClaimsPerSource = Math.max(1, options.maxClaimsPerSource ?? 3)\n const deterministicFallback = options.deterministicFallback ?? true\n\n // The claim ledger, keyed by claim id (sha256 of the normalized claim text).\n const claims = new Map<string, TrackedClaim>()\n // Every deep question raised, by id — so we can mark them addressed later.\n const questions = new Map<string, DeepQuestion>()\n let rounds = 0\n let lastSteer: ResearchDrivingSteer | undefined\n\n function resolveRouter(): RouterClient {\n return options.router ?? createTangleRouterClient(options.router_options)\n }\n\n /** Record a claim from a source, growing its independent-source support. */\n function recordClaim(extracted: ExtractedClaim, sourceUri: string, round: number): TrackedClaim {\n const id = claimId(extracted.text)\n const host = hostOf(sourceUri)\n const existing = claims.get(id)\n if (existing) {\n if (host) existing.supportingHosts.add(host)\n if (!existing.supportingUris.includes(sourceUri)) existing.supportingUris.push(sourceUri)\n linkContradiction(existing, extracted.contradictsExistingId)\n return existing\n }\n const tracked: TrackedClaim = {\n id,\n text: extracted.text.trim(),\n supportingHosts: new Set(host ? [host] : []),\n supportingUris: [sourceUri],\n contradicts: new Set(),\n contested: false,\n firstSeenRound: round,\n }\n linkContradiction(tracked, extracted.contradictsExistingId)\n claims.set(id, tracked)\n return tracked\n }\n\n /** Wire a bidirectional contradiction edge and mark BOTH claims contested. */\n function linkContradiction(claim: TrackedClaim, otherId: string | undefined): void {\n if (!otherId || otherId === claim.id) return\n const other = claims.get(otherId)\n if (!other) return\n claim.contradicts.add(otherId)\n other.contradicts.add(claim.id)\n claim.contested = true\n other.contested = true\n }\n\n /** A claim's independent-source count = distinct canonical hosts. */\n function independentSupport(claim: TrackedClaim): number {\n return claim.supportingHosts.size\n }\n\n function isCorroborated(claim: TrackedClaim): boolean {\n return independentSupport(claim) >= minIndependentSources\n }\n\n /** Weakly-supported = NOT corroborated AND NOT contested → an invalidation target. */\n function isWeak(claim: TrackedClaim): boolean {\n return !isCorroborated(claim) && !claim.contested\n }\n\n function snapshot(): ResearchDrivingState {\n const all = [...claims.values()]\n const allQuestions = [...questions.values()]\n return {\n claims: all,\n questions: allQuestions,\n weaklySupported: all.filter(isWeak),\n corroborated: all.filter(isCorroborated),\n contested: all.filter((claim) => claim.contested),\n openQuestions: allQuestions.filter((question) => !question.addressed),\n rounds,\n }\n }\n\n /**\n * Mark deep questions addressed when later evidence speaks to them. A question\n * is addressed once a NEW claim's text shares enough content words with the\n * question — i.e. the worker brought back evidence on the thing we asked about.\n * Cheap and deterministic; the LLM is reserved for GENERATING questions, not\n * grading them, so the oracle stays a non-model check.\n */\n function markAddressed(newClaimTexts: string[]): void {\n for (const question of questions.values()) {\n if (question.addressed) continue\n // Contradiction questions resolve when one of their claims becomes\n // corroborated or contested (the disagreement was surfaced/settled).\n if (question.kind === 'contradiction') {\n const settled = question.claimIds.some((id) => {\n const claim = claims.get(id)\n return claim ? isCorroborated(claim) || claim.contested : false\n })\n if (settled) question.addressed = true\n continue\n }\n const qWords = contentWordSet(question.text)\n if (qWords.size === 0) continue\n for (const text of newClaimTexts) {\n const overlap = overlapFraction(qWords, contentWordSet(text))\n if (overlap >= 0.5) {\n question.addressed = true\n break\n }\n }\n }\n }\n\n return {\n /**\n * `verifySource` — the per-source hook. This driver does NOT filter for\n * relevance/dedup (other drivers do that, and the loop already dedups exact\n * uris). Its job here is to EXTRACT the source's claims and grow the ledger.\n * It accepts every source that yields at least one extractable claim; it\n * only rejects a source with NO extractable signal at all (empty/unusable),\n * because such a source cannot drive the research and pollutes the KB.\n */\n async verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> {\n const extracted = await extractClaims(source, ctx)\n if (extracted.length === 0) {\n return {\n accept: false,\n reason: 'no extractable claim: source yields nothing to drive the research deeper',\n }\n }\n const newTexts: string[] = []\n for (const claim of extracted) {\n recordClaim(claim, source.uri, ctx.round)\n newTexts.push(claim.text)\n }\n markAddressed(newTexts)\n return { accept: true }\n },\n\n /**\n * `foldGaps` — the DEPTH driver. Runs after the worker's contribution is\n * applied each round. It builds the next round's steer from (1) the readiness\n * gaps the loop still reports, (2) freshly generated DEEP sub-questions, and\n * (3) INVALIDATION challenges for weakly-supported / contradicted claims.\n */\n foldGaps(gaps: KnowledgeGap[]): string {\n rounds += 1\n const round = rounds\n const ledger = [...claims.values()]\n\n // Invalidation targets: claims with one source (need corroboration) OR\n // contradicted claims (need a refutation/resolution). These are what the\n // worker is told to go SHORE UP, not new breadth.\n const invalidationTargets = ledger.filter(\n (claim) => isWeak(claim) || claim.contradicts.size > 0,\n )\n\n // Generate this round's deep sub-questions from the actual ledger claims\n // and register them so completion can track whether they get addressed.\n const deepQuestions = synthesizeDeepQuestions(ledger, round).slice(0, maxQuestionsPerRound)\n for (const question of deepQuestions) {\n if (!questions.has(question.id)) questions.set(question.id, question)\n }\n\n const text = buildSteerText(gaps, deepQuestions, invalidationTargets, minIndependentSources)\n lastSteer = { round, deepQuestions, invalidationTargets, gaps, text }\n options.onSteer?.(lastSteer)\n return text\n },\n\n researchState: snapshot,\n\n isComplete(): boolean {\n const all = [...claims.values()]\n if (all.length === 0) return false\n const everyClaimSettled = all.every((claim) => isCorroborated(claim) || claim.contested)\n const everyQuestionAddressed = [...questions.values()].every((question) => question.addressed)\n return everyClaimSettled && everyQuestionAddressed\n },\n\n lastSteer(): ResearchDrivingSteer | undefined {\n return lastSteer\n },\n }\n\n // -- claim extraction ------------------------------------------------------\n\n async function extractClaims(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<ExtractedClaim[]> {\n const ledger = [...claims.values()]\n const fromLlm = await extractClaimsWithLlm(source, ctx, ledger)\n if (fromLlm.length > 0) return fromLlm.slice(0, maxClaimsPerSource)\n if (deterministicFallback) return deterministicClaims(source).slice(0, maxClaimsPerSource)\n return []\n }\n\n async function extractClaimsWithLlm(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ledger: TrackedClaim[],\n ): Promise<ExtractedClaim[]> {\n let router: RouterClient\n try {\n router = resolveRouter()\n } catch {\n return []\n }\n const excerpt = source.text.slice(0, 1800)\n const ledgerLines = ledger\n .slice(0, 20)\n .map((claim) => `- [${claim.id}] ${claim.text}`)\n .join('\\n')\n const system =\n 'You extract the KEY factual claims a researcher would cite a page for, and flag ' +\n 'CONTRADICTIONS with claims already on the ledger. ' +\n \"A claim is one concrete, checkable assertion using the page's own terms and numbers. \" +\n 'Return ONLY a JSON array; each item is {\"claim\": string, \"contradicts\": string|null} where ' +\n 'contradicts is the bracketed [id] of a ledger claim this page DIRECTLY contradicts, else null. ' +\n `Return at most ${maxClaimsPerSource} claims. No prose.`\n const user = [\n `Research goal: ${ctx.goal}`,\n `Page title: ${source.title ?? '(none)'}`,\n ledgerLines ? `Claims already on the ledger:\\n${ledgerLines}` : 'Ledger is empty.',\n `Page excerpt:\\n${excerpt}`,\n 'Key claims as JSON [{\"claim\": \"...\", \"contradicts\": \"[id]\"|null}]:',\n ].join('\\n\\n')\n\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n 1200,\n )\n } catch {\n return []\n }\n return parseExtractedClaims(raw, ledger)\n }\n\n /**\n * Deterministic fallback: pull the leading sentences as candidate claims. Used\n * only when the model is unavailable, so the driver still drives (and the\n * offline test runs with no creds). Each sentence becomes a checkable claim.\n */\n function deterministicClaims(source: ResearchSourceProposal): ExtractedClaim[] {\n const sentences = source.text\n .split(/(?<=[.!?])\\s+/)\n .map((sentence) => sentence.trim())\n .filter((sentence) => contentWordSet(sentence).size >= 3)\n return sentences.slice(0, maxClaimsPerSource).map((text) => ({ text }))\n }\n\n // -- deep-question synthesis ----------------------------------------------\n\n /**\n * Build the four deep-question kinds from the actual ledger claims. This is\n * intentionally deterministic (not an LLM call): the loop's `foldGaps` contract\n * is synchronous (`foldGaps(gaps): string`), and a template grounded in the\n * real claim text gives a faithful, non-fabricated sub-question every round —\n * comparative, mechanism, gap, and contradiction. Claim EXTRACTION, which runs\n * inside the awaited `verifySource`, is where the model does the open-ended\n * work; question generation just interrogates what was extracted.\n */\n function synthesizeDeepQuestions(ledger: TrackedClaim[], round: number): DeepQuestion[] {\n if (ledger.length === 0) return []\n const out: DeepQuestion[] = []\n\n // CONTRADICTION questions: for every contradiction edge, ask the worker to\n // find evidence that resolves which claim holds.\n for (const claim of ledger) {\n for (const otherId of claim.contradicts) {\n const other = ledger.find((entry) => entry.id === otherId)\n if (!other || other.id < claim.id) continue // emit each pair once\n out.push(\n makeQuestion(\n 'contradiction',\n `Does any independent source resolve the contradiction between \"${truncate(claim.text)}\" and \"${truncate(other.text)}\"? Find evidence that confirms or refutes one of them.`,\n [claim.id, other.id],\n round,\n ),\n )\n }\n }\n\n // GAP questions: for each weakly-supported claim, ask for the specific\n // corroborating result that is missing.\n for (const claim of ledger.filter((entry) => !entry.contested)) {\n if (claim.supportingHosts.size < minIndependentSources) {\n out.push(\n makeQuestion(\n 'gap',\n `Only one independent source supports \"${truncate(claim.text)}\". What specific corroborating result, dataset, or independent measurement is missing to confirm it?`,\n [claim.id],\n round,\n ),\n )\n }\n }\n\n // MECHANISM questions: for the best-supported claims, probe the failure\n // boundary — under what precise condition does the asserted effect break.\n for (const claim of [...ledger]\n .sort((a, b) => b.supportingHosts.size - a.supportingHosts.size)\n .slice(0, 2)) {\n out.push(\n makeQuestion(\n 'mechanism',\n `Under what precise condition does \"${truncate(claim.text)}\" stop holding? Find a source that states the mechanism, limit, or failure mode.`,\n [claim.id],\n round,\n ),\n )\n }\n\n // COMPARATIVE questions: pair the two most-supported claims and ask how their\n // tradeoffs differ.\n const ranked = [...ledger].sort((a, b) => b.supportingHosts.size - a.supportingHosts.size)\n if (ranked.length >= 2 && ranked[0] && ranked[1]) {\n out.push(\n makeQuestion(\n 'comparative',\n `How does the tradeoff in \"${truncate(ranked[0].text)}\" differ from \"${truncate(ranked[1].text)}\"? Find a source that compares them directly.`,\n [ranked[0].id, ranked[1].id],\n round,\n ),\n )\n }\n\n // Stable order: contradiction → gap → mechanism → comparative (most urgent\n // validation work first).\n const priority: Record<DeepQuestionKind, number> = {\n contradiction: 0,\n gap: 1,\n mechanism: 2,\n comparative: 3,\n }\n return out.sort((a, b) => priority[a.kind] - priority[b.kind])\n }\n}\n\n// ---------------------------------------------------------------------------\n// pure helpers\n// ---------------------------------------------------------------------------\n\nfunction makeQuestion(\n kind: DeepQuestionKind,\n text: string,\n claimIds: string[],\n raisedRound: number,\n): DeepQuestion {\n return {\n kind,\n text,\n id: `q_${sha256(`${kind}:${text}`).slice(0, 16)}`,\n claimIds,\n addressed: false,\n raisedRound,\n }\n}\n\n/** Claim identity = sha256 of the normalized claim text (same words ⇒ same claim). */\nfunction claimId(text: string): string {\n return `c_${sha256(normalizeText(text)).slice(0, 16)}`\n}\n\nfunction hostOf(uri: string): string {\n try {\n return new URL(uri.trim()).hostname.toLowerCase().replace(/^www\\./, '')\n } catch {\n // Non-URL identifier (offline corpus uris like `web/foo`): canonicalize so\n // distinct identifiers still count as distinct independent sources.\n return canonicalizeUrl(uri)\n }\n}\n\nfunction normalizeText(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nconst stopwords = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'but',\n 'of',\n 'to',\n 'in',\n 'on',\n 'for',\n 'with',\n 'as',\n 'by',\n 'at',\n 'from',\n 'that',\n 'this',\n 'these',\n 'those',\n 'it',\n 'its',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'has',\n 'have',\n 'had',\n 'can',\n 'will',\n 'would',\n 'should',\n 'may',\n 'might',\n 'not',\n 'no',\n 'than',\n 'then',\n 'over',\n 'under',\n 'about',\n 'into',\n 'their',\n 'they',\n 'them',\n])\n\nfunction contentWordSet(text: string): Set<string> {\n return new Set(\n normalizeText(text)\n .split(' ')\n .filter((word) => word.length >= 3 && !stopwords.has(word)),\n )\n}\n\nfunction overlapFraction(a: Set<string>, b: Set<string>): number {\n if (a.size === 0) return 0\n let hits = 0\n for (const word of a) if (b.has(word)) hits += 1\n return hits / a.size\n}\n\nfunction truncate(text: string, max = 140): string {\n const t = text.trim().replace(/\\s+/g, ' ')\n return t.length <= max ? t : `${t.slice(0, max - 1)}…`\n}\n\n/**\n * Parse the extractor's JSON array of `{claim, contradicts}` items, tolerant of\n * code fences / surrounding prose. `contradicts` is mapped from a `[id]` token to\n * a ledger claim id only when that id is actually on the ledger.\n */\nfunction parseExtractedClaims(raw: string, ledger: TrackedClaim[]): ExtractedClaim[] {\n const text = raw.trim()\n if (!text) return []\n const arrayMatch = text.match(/\\[[\\s\\S]*\\]/)\n if (!arrayMatch) return []\n let parsed: unknown\n try {\n parsed = JSON.parse(arrayMatch[0])\n } catch {\n return []\n }\n if (!Array.isArray(parsed)) return []\n const ledgerIds = new Set(ledger.map((claim) => claim.id))\n const out: ExtractedClaim[] = []\n for (const item of parsed) {\n if (!item || typeof item !== 'object') continue\n const record = item as { claim?: unknown; contradicts?: unknown }\n if (typeof record.claim !== 'string' || !record.claim.trim()) continue\n const contradictsId = extractBracketId(record.contradicts)\n out.push({\n text: record.claim.trim(),\n contradictsExistingId:\n contradictsId && ledgerIds.has(contradictsId) ? contradictsId : undefined,\n })\n }\n return out\n}\n\n/** Pull a ledger id out of a `contradicts` field: `\"[c_abc]\"` or `\"c_abc\"`. */\nfunction extractBracketId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (!trimmed || trimmed.toLowerCase() === 'null') return undefined\n const bracket = trimmed.match(/\\[([^\\]]+)\\]/)\n const id = (bracket?.[1] ?? trimmed).trim()\n return id.startsWith('c_') ? id : undefined\n}\n\n/**\n * Build the steer string handed to the worker's next prompt. Interleaves the\n * readiness gaps the loop still reports with the deep sub-questions and the\n * invalidation challenges — the part that drives DEPTH + VALIDATION.\n */\nfunction buildSteerText(\n gaps: KnowledgeGap[],\n deepQuestions: DeepQuestion[],\n invalidationTargets: TrackedClaim[],\n minIndependentSources: number,\n): string {\n const lines: string[] = []\n lines.push(\n 'Do NOT just add more sources. Go DEEPER and VALIDATE. Address the following before adding breadth:',\n )\n\n if (deepQuestions.length > 0) {\n lines.push('', 'Deep sub-questions to answer this round:')\n for (const question of deepQuestions) {\n lines.push(`- (${question.kind}) ${question.text}`)\n }\n }\n\n if (invalidationTargets.length > 0) {\n lines.push(\n '',\n `Claims needing corroboration or refutation (each must reach >= ${minIndependentSources} INDEPENDENT sources, or be shown contested):`,\n )\n for (const claim of invalidationTargets) {\n const reason =\n claim.contradicts.size > 0\n ? 'CONTRADICTED by another source — find evidence that resolves it'\n : `only ${claim.supportingHosts.size} independent source — find a SECOND, independent corroborating source`\n lines.push(`- \"${truncate(claim.text)}\" — ${reason}`)\n }\n }\n\n if (gaps.length > 0) {\n lines.push('', 'Readiness gaps still open:')\n for (const gap of gaps) {\n lines.push(`- (${gap.blocking ? 'blocking' : 'soft'}) ${gap.description} [${gap.id}]`)\n }\n }\n\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,IAAI,WAAW,KAAK,IAAI,EAAE,GAAG;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["resolve","reason","contentWords","stopwords","candidate","average","unique","round","join","z","z","join","join","round","remainingGaps","join","z","z","emptyIndex","validateRunRecord","validateRunRecord","resolveRouter","round","hostOf","stopwords"]}
1
+ {"version":3,"sources":["../src/web-research-worker.ts","../src/adaptive-driver.ts","../src/agent-candidate.ts","../src/kb-improvement.ts","../src/claim-grounding.ts","../src/rag-eval.ts","../src/research-loop.ts","../src/events.ts","../src/eval-readiness.ts","../src/readiness-helpers.ts","../src/rag-improvement-loop.ts","../src/changes.ts","../src/chunking.ts","../src/collection-research-driver.ts","../src/discovery.ts","../src/freshness.ts","../src/investment-thesis-set.ts","../src/investment-thesis-task.ts","../src/material-facts-metric.ts","../src/two-agent-research-loop.ts","../src/kb-store.ts","../src/propose-from-finding.ts","../src/readiness-check.ts","../src/release.ts","../src/research-driving-driver.ts"],"sourcesContent":["/**\n * Real web-research worker + verifying driver for `runVerifiedResearchLoop`.\n *\n * This is the GENERAL, any-topic implementation behind the two-agent research\n * loop's live arm. Given the open knowledge gaps the readiness gate surfaces,\n * the worker:\n *\n * 1. asks an LLM (glm-5.2 by default) to turn each gap into focused web\n * search queries,\n * 2. runs a REAL web search over the Tangle router (`POST /v1/search` — the\n * same endpoint `tcloud mcp`'s `web_search` tool forwards to), so there is\n * no hardcoded corpus,\n * 3. fetches the top results with the repo's polite, cached `politeFetch` and\n * reduces each page to text with `htmlToText`,\n * 4. proposes the readable, verifiable pages as `ResearchSourceProposal`s plus\n * a `buildPages` that writes citing `knowledge/*.md` pages from the sources\n * the driver accepts.\n *\n * The verifying DRIVER is the differentiated role from the two-agent loop: a\n * second LLM pass that judges each fetched source's on-topic relevance to the\n * goal + open gaps and rejects off-topic / spam / already-covered material. The\n * worker ADDS; the driver GATES. Together they build a cleaner knowledge base\n * than a single agent at the same compute budget.\n *\n * Dependency-free on purpose: it talks to the router over `fetch` directly with\n * the published OpenAI-compatible chat shape and the `/v1/search` shape, so it\n * works whether or not the `tcloud` CLI is installed. Point it at any router by\n * passing `baseUrl`; supply the key via `apiKey` or `TANGLE_API_KEY`.\n */\n\nimport { htmlToText } from './sources/html'\nimport { politeFetch } from './sources/http'\nimport type {\n KnowledgeGap,\n ResearchContribution,\n ResearchDriver,\n ResearchSourceProposal,\n ResearchWorker,\n SourceVerdict,\n SourceVerificationContext,\n WorkerResearchContext,\n} from './two-agent-research-loop'\nimport type { SourceRecord } from './types'\n\n/** Default router model. Plain id (no namespace) — see CLAUDE/creds notes. */\nconst DEFAULT_MODEL = 'glm-5.2'\n/** Default router base. */\nconst DEFAULT_BASE_URL = 'https://router.tangle.tools/v1'\n/**\n * glm-5.2 spends its first tokens on hidden `reasoning_content`; below ~1200\n * output tokens it returns EMPTY visible content. Floor every call so a\n * reasoning model never silently yields nothing. (Verified creds note.)\n */\nconst MIN_MAX_TOKENS = 1200\n\n/** One live web result, as the router's `/v1/search` returns it. */\nexport interface WebSearchHit {\n title: string\n url: string\n snippet?: string\n}\n\n/**\n * The two router capabilities the worker/driver need. Injectable so tests can\n * stub the network; the default talks to the live Tangle router over `fetch`.\n */\nexport interface RouterClient {\n /** Live web search — returns title/url/snippet hits. */\n search(query: string, opts?: { maxResults?: number }): Promise<WebSearchHit[]>\n /** Chat completion — returns the assistant message's visible text. */\n chat(\n messages: { role: 'system' | 'user'; content: string }[],\n maxTokens?: number,\n ): Promise<string>\n /** Cumulative cost (chat + search) since this client was created. */\n usage(): RouterUsage\n}\n\n/**\n * Cumulative router cost — the per-arm signal the A/B reports ALONGSIDE quality,\n * so \"2.3 fewer sources\" can be read against the token/$/latency it cost. A\n * two-agent round is one worker pass plus N `verifySource` LLM calls; counting\n * each call here is what surfaces that the two-agent loop spends more inference\n * than its \"equal passes\" budget implies.\n */\nexport interface RouterUsage {\n chatCalls: number\n searchCalls: number\n promptTokens: number\n completionTokens: number\n usd: number\n wallMs: number\n}\n\nexport interface TangleRouterOptions {\n /** Router base URL. Defaults to `https://router.tangle.tools/v1`. */\n baseUrl?: string\n /** Bearer key. Defaults to `process.env.TANGLE_API_KEY`. */\n apiKey?: string\n /** Chat model id. Defaults to `glm-5.2`. */\n model?: string\n /** Optional preferred search provider (exa | you | perplexity | …). */\n searchProvider?: string\n /**\n * Retries on a TRANSIENT upstream status (502/503/504/429) with exponential\n * backoff. Default 4. A 4xx that isn't 429, and a 401, are NOT retried — those\n * are not transient. After the budget is exhausted the call still fails loud\n * with the original `RouterError`, so the fail-closed contract holds; this only\n * stops a single upstream-capacity blip from voiding a whole multi-topic run.\n */\n maxRetries?: number\n /** Base backoff in ms (doubled each retry, ±25% jitter). Default 1500. */\n retryBaseMs?: number\n signal?: AbortSignal\n}\n\n/** Transient upstream statuses worth a retry (capacity / rate-limit / gateway). */\nconst transientStatuses = new Set([429, 502, 503, 504])\n\n/**\n * POST with bounded exponential backoff on transient upstream statuses. Returns\n * the first `res.ok` response, or the LAST response (so the caller throws the\n * real status). A non-transient failure returns immediately — only 502/503/504/\n * 429 are retried. Aborts propagate at once.\n */\nasync function fetchWithRetry(\n url: string,\n init: RequestInit,\n opts: { maxRetries: number; retryBaseMs: number; signal?: AbortSignal },\n): Promise<Response> {\n let lastRes: Response | undefined\n for (let attempt = 0; attempt <= opts.maxRetries; attempt += 1) {\n if (opts.signal?.aborted) throw new RouterError(0, 'aborted')\n const res = await fetch(url, init)\n if (res.ok || !transientStatuses.has(res.status)) return res\n lastRes = res\n if (attempt === opts.maxRetries) break\n // Drain the body so the socket frees before we wait.\n await res.text().catch(() => '')\n const backoff = opts.retryBaseMs * 2 ** attempt\n const jitter = backoff * (0.75 + Math.random() * 0.5)\n await new Promise((resolve) => setTimeout(resolve, jitter))\n }\n // Exhausted: hand back the last transient response so the caller fails loud\n // with its real status.\n if (lastRes) return lastRes\n throw new RouterError(0, 'fetchWithRetry produced no response')\n}\n\n/** A small error so a failed router call fails loud rather than returning junk. */\nexport class RouterError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(`router ${status}: ${message}`)\n this.name = 'RouterError'\n }\n}\n\n/**\n * Build a dependency-free Tangle router client over `fetch`. This is the same\n * wire surface the `tcloud` SDK + `tcloud mcp` use (`/v1/search` for web search,\n * `/v1/chat/completions` for chat) so it needs no CLI installed.\n */\nexport function createTangleRouterClient(options: TangleRouterOptions = {}): RouterClient {\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const apiKey = options.apiKey ?? process.env.TANGLE_API_KEY\n if (!apiKey) {\n throw new RouterError(401, 'no TANGLE_API_KEY (pass apiKey or set the env var)')\n }\n const model = options.model ?? DEFAULT_MODEL\n const maxRetries = Math.max(0, options.maxRetries ?? 4)\n const retryBaseMs = Math.max(1, options.retryBaseMs ?? 1500)\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n }\n\n // glm-5.2 pricing (USD per token) + a cumulative accumulator. Read via usage().\n const price = { prompt: 0.95 / 1_000_000, completion: 3.0 / 1_000_000 }\n const acc: RouterUsage = {\n chatCalls: 0,\n searchCalls: 0,\n promptTokens: 0,\n completionTokens: 0,\n usd: 0,\n wallMs: 0,\n }\n\n return {\n async search(query, opts) {\n const t0 = Date.now()\n const res = await fetchWithRetry(\n `${baseUrl}/search`,\n {\n method: 'POST',\n headers,\n signal: options.signal,\n body: JSON.stringify({\n query,\n ...(options.searchProvider ? { provider: options.searchProvider } : {}),\n ...(opts?.maxResults != null ? { maxResults: opts.maxResults } : {}),\n }),\n },\n { maxRetries, retryBaseMs, signal: options.signal },\n )\n acc.searchCalls += 1\n acc.wallMs += Date.now() - t0\n if (!res.ok) {\n throw new RouterError(res.status, await res.text().catch(() => res.statusText))\n }\n const body = (await res.json()) as { data?: WebSearchHit[] }\n return (body.data ?? [])\n .filter((hit) => typeof hit?.url === 'string' && hit.url.length > 0)\n .map((hit) => ({ title: hit.title ?? hit.url, url: hit.url, snippet: hit.snippet }))\n },\n async chat(messages, maxTokens) {\n // Reasoning-model floor: never let glm-5.2 spend the whole budget on\n // hidden reasoning and return empty visible content.\n const max_tokens = Math.max(MIN_MAX_TOKENS, maxTokens ?? MIN_MAX_TOKENS)\n const t0 = Date.now()\n const res = await fetchWithRetry(\n `${baseUrl}/chat/completions`,\n {\n method: 'POST',\n headers,\n signal: options.signal,\n body: JSON.stringify({ model, messages, max_tokens, temperature: 0.2, stream: false }),\n },\n { maxRetries, retryBaseMs, signal: options.signal },\n )\n if (!res.ok) {\n throw new RouterError(res.status, await res.text().catch(() => res.statusText))\n }\n const body = (await res.json()) as {\n choices?: { message?: { content?: string } }[]\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const promptTokens = body.usage?.prompt_tokens ?? 0\n const completionTokens = body.usage?.completion_tokens ?? 0\n acc.chatCalls += 1\n acc.promptTokens += promptTokens\n acc.completionTokens += completionTokens\n acc.usd += promptTokens * price.prompt + completionTokens * price.completion\n acc.wallMs += Date.now() - t0\n return body.choices?.[0]?.message?.content ?? ''\n },\n usage() {\n return { ...acc }\n },\n }\n}\n\nexport interface WebResearchWorkerOptions {\n /** Router client. Defaults to a live Tangle router client from env creds. */\n router?: RouterClient\n router_options?: TangleRouterOptions\n /** Max search queries the LLM may form per gap. Default 2. */\n queriesPerGap?: number\n /** Max web results fetched per query. Default 3. */\n resultsPerQuery?: number\n /** Hard cap on sources proposed per round (across all gaps). Default 6. */\n maxSourcesPerRound?: number\n /** Disk cache dir for `politeFetch`. Optional; speeds repeat runs. */\n cacheDir?: string\n /** Minimum readable text length to keep a fetched page. Default 200. */\n minTextChars?: number\n /** Max chars of page text stored per source (keeps pages bounded). Default 4000. */\n maxTextChars?: number\n}\n\n/** Resolve the router client lazily so a worker with an injected client never reads env. */\nfunction resolveRouter(opts: {\n router?: RouterClient\n router_options?: TangleRouterOptions\n}): RouterClient {\n return opts.router ?? createTangleRouterClient(opts.router_options)\n}\n\n/**\n * The real web-research worker. Conforms to the loop's `ResearchWorker`\n * contract: given the open gaps, it returns the sources it found plus a\n * `buildPages` that emits citing pages from the sources the driver accepted.\n */\nexport function createWebResearchWorker(options: WebResearchWorkerOptions = {}): ResearchWorker {\n const queriesPerGap = Math.max(1, options.queriesPerGap ?? 2)\n const resultsPerQuery = Math.max(1, options.resultsPerQuery ?? 3)\n const maxSourcesPerRound = Math.max(1, options.maxSourcesPerRound ?? 6)\n const minTextChars = Math.max(1, options.minTextChars ?? 200)\n const maxTextChars = Math.max(minTextChars, options.maxTextChars ?? 4000)\n\n return async (ctx: WorkerResearchContext): Promise<ResearchContribution> => {\n const router = resolveRouter(options)\n // Target the BLOCKING gaps first; fall back to all gaps if none are blocking.\n const targetGaps = ctx.gaps.filter((gap) => gap.blocking)\n const gaps = targetGaps.length > 0 ? targetGaps : ctx.gaps\n if (gaps.length === 0) {\n return { sources: [], notes: 'no open gaps to research' }\n }\n\n const queries = await formSearchQueries(router, ctx, gaps, queriesPerGap)\n const proposals: ResearchSourceProposal[] = []\n const seenUris = new Set<string>()\n\n for (const query of queries) {\n if (proposals.length >= maxSourcesPerRound) break\n if (ctx.signal?.aborted) break\n let hits: WebSearchHit[]\n try {\n hits = await router.search(query, { maxResults: resultsPerQuery })\n } catch (error) {\n // A single failed query must not sink the round — record nothing, move on.\n if ((error as { name?: string }).name === 'AbortError') break\n continue\n }\n for (const hit of hits) {\n if (proposals.length >= maxSourcesPerRound) break\n if (seenUris.has(hit.url)) continue\n const fetched = await politeFetch(hit.url, {\n signal: ctx.signal,\n cacheDir: options.cacheDir,\n })\n if (!fetched.verifiable) continue\n const text = htmlToText(fetched.body).slice(0, maxTextChars)\n if (text.length < minTextChars) continue\n seenUris.add(hit.url)\n proposals.push({\n uri: hit.url,\n title: hit.title || hit.url,\n text,\n // We just fetched + verified this page, so stamp `lastVerifiedAt` with\n // fetch time. Do NOT set `validUntil`: a live page has no inherent\n // future expiry, and the readiness freshness check treats any\n // `validUntil <= now` as EXPIRED (score 0). The page's `Last-Modified`\n // is a PAST date, so writing it here would mark every real source stale\n // and zero out coverage. Record it as provenance metadata instead.\n lastVerifiedAt: fetched.fetchedAt,\n metadata: {\n discoveredVia: query,\n snippet: hit.snippet ?? '',\n goal: ctx.goal,\n sourceUpdatedAt: fetched.sourceUpdatedAt,\n },\n })\n }\n }\n\n return {\n sources: proposals,\n buildPages: buildCitingPages(proposals),\n notes: `web-research worker: ${queries.length} queries → ${proposals.length} fetched sources`,\n }\n }\n}\n\n/**\n * Ask the LLM to turn the open gaps into focused web search queries. Falls back\n * to the gap's own readiness query if the model returns nothing parseable, so a\n * model hiccup degrades to a sane search rather than an empty round.\n */\nasync function formSearchQueries(\n router: RouterClient,\n ctx: WorkerResearchContext,\n gaps: KnowledgeGap[],\n queriesPerGap: number,\n): Promise<string[]> {\n const gapLines = gaps\n .map((gap, i) => `${i + 1}. ${gap.description} (readiness query: \"${gap.query}\")`)\n .join('\\n')\n const want = gaps.length * queriesPerGap\n const system =\n 'You are a research librarian. Turn knowledge gaps into precise web search queries that will ' +\n 'surface authoritative primary sources (papers, docs, standards, official pages). ' +\n 'Return ONLY a JSON array of query strings, no prose.'\n const user = [\n `Research goal: ${ctx.goal}`,\n ctx.steer ? `Steer from the coordinator:\\n${ctx.steer}` : '',\n `Open knowledge gaps:\\n${gapLines}`,\n `Return up to ${want} search query strings as a JSON array (e.g. [\"query one\",\"query two\"]).`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n MIN_MAX_TOKENS,\n )\n } catch {\n raw = ''\n }\n const parsed = parseQueryList(raw)\n const fromLlm = parsed.slice(0, want)\n if (fromLlm.length > 0) return dedupeStrings(fromLlm)\n // Degrade to the readiness queries themselves — still a real search.\n return dedupeStrings(gaps.map((gap) => gap.query || gap.description))\n}\n\n/** Parse a JSON array of query strings, tolerant of code fences / surrounding prose. */\nfunction parseQueryList(raw: string): string[] {\n const text = raw.trim()\n if (!text) return []\n const candidates: string[] = []\n // Prefer a fenced or bare JSON array.\n const arrayMatch = text.match(/\\[[\\s\\S]*\\]/)\n if (arrayMatch) {\n try {\n const arr = JSON.parse(arrayMatch[0]) as unknown[]\n for (const item of arr)\n if (typeof item === 'string' && item.trim()) candidates.push(item.trim())\n } catch {\n /* fall through to line parsing */\n }\n }\n if (candidates.length === 0) {\n for (const line of text.split('\\n')) {\n const cleaned = line\n .replace(/^\\s*(?:[-*]|\\d+[.)])\\s*/, '')\n .replace(/^[\"']|[\"']$/g, '')\n .trim()\n if (cleaned && cleaned.length > 2 && !cleaned.startsWith('{')) candidates.push(cleaned)\n }\n }\n return candidates\n}\n\nfunction dedupeStrings(values: string[]): string[] {\n const seen = new Set<string>()\n const out: string[] = []\n for (const value of values) {\n const key = value.toLowerCase().trim()\n if (key && !seen.has(key)) {\n seen.add(key)\n out.push(value.trim())\n }\n }\n return out\n}\n\n/**\n * Build the curated `knowledge/*.md` pages from the sources the driver accepted.\n * Each page cites the registered source by its assigned `record.id` (matched back\n * to the proposal via `metadata.originalUri`, which `addSourceText` stashes).\n */\nfunction buildCitingPages(\n proposals: ResearchSourceProposal[],\n): (acceptedSources: SourceRecord[]) => string | undefined {\n return (acceptedSources) => {\n if (acceptedSources.length === 0) return undefined\n const blocks = acceptedSources.map((record) => {\n const proposal = proposals.find((p) => p.uri === record.metadata?.originalUri)\n const uri = proposal?.uri ?? record.id\n const slug =\n uri\n .replace(/^https?:\\/\\//, '')\n .replace(/[^a-z0-9]+/gi, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 120) || record.id\n const title = proposal?.title ?? record.id\n const body = proposal?.text ?? ''\n return [\n `---FILE: knowledge/${slug}.md---`,\n '---',\n `title: ${escapeYaml(title)}`,\n `sources: [\"${record.id}\"]`,\n `source_url: ${uri}`,\n '---',\n `# ${title}`,\n '',\n body,\n '',\n `Source: ${uri}`,\n '---END FILE---',\n ].join('\\n')\n })\n return blocks.join('\\n')\n }\n}\n\nfunction escapeYaml(value: string): string {\n // Keep the frontmatter line single-valued and safe: collapse newlines, strip\n // quotes that would break the scalar.\n return value\n .replace(/[\\r\\n]+/g, ' ')\n .replace(/\"/g, \"'\")\n .trim()\n}\n\nexport interface VerifyingDriverOptions {\n router?: RouterClient\n router_options?: TangleRouterOptions\n /**\n * When the LLM verdict can't be parsed, default to REJECT (fail-closed) so a\n * model hiccup never poisons the KB with an unverified source. Set `true` to\n * accept-on-parse-failure only if you have a reason to. Default false.\n */\n acceptOnParseFailure?: boolean\n}\n\n/**\n * The verifying driver: a real LLM pass that judges each candidate source's\n * on-topic relevance to the goal + open gaps and whether it duplicates material\n * already accepted this round. This is the differentiated coordinator role — it\n * GATES the worker's additions; it adds nothing itself.\n *\n * The loop already dedups exact-uri duplicates and only calls this on genuinely\n * new candidates, so the verifier focuses on relevance + near-duplicate\n * judgement, not bookkeeping.\n */\nexport function createVerifyingResearchDriver(\n options: VerifyingDriverOptions = {},\n): ResearchDriver {\n const acceptOnParseFailure = options.acceptOnParseFailure ?? false\n return {\n async verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> {\n const router = resolveRouter(options)\n const gapLines = ctx.gaps\n .map((gap) => `- ${gap.description} (query: \"${gap.query}\")`)\n .join('\\n')\n const acceptedTitles = ctx.acceptedThisRound\n .map((accepted) => `- ${accepted.title ?? accepted.uri}`)\n .join('\\n')\n const excerpt = source.text.slice(0, 1500)\n const system =\n 'You verify whether a fetched web source belongs in a curated knowledge base. ' +\n 'Accept a source ONLY if it is genuinely on-topic for the research goal and helps close ' +\n 'one of the open gaps, AND it is not a near-duplicate of an already-accepted source. ' +\n 'Reject spam, listicles, off-topic pages, marketing, and near-duplicates. ' +\n 'Respond with ONLY a JSON object: {\"accept\": true|false, \"reason\": \"<short reason>\"}.'\n const user = [\n `Research goal: ${ctx.goal}`,\n `Open gaps:\\n${gapLines || '(none specified)'}`,\n acceptedTitles\n ? `Already accepted this round:\\n${acceptedTitles}`\n : 'Nothing accepted yet this round.',\n `Candidate source:\\nURL: ${source.uri}\\nTitle: ${source.title ?? '(none)'}\\nExcerpt:\\n${excerpt}`,\n 'Verdict as JSON {\"accept\": boolean, \"reason\": string}:',\n ].join('\\n\\n')\n\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n MIN_MAX_TOKENS,\n )\n } catch (error) {\n if ((error as { name?: string }).name === 'AbortError') throw error\n // Router failure: fail-closed (reject) so an unverified source can't slip in.\n return acceptOnParseFailure\n ? { accept: true }\n : { accept: false, reason: `verifier unavailable: ${(error as Error).message}` }\n }\n\n const verdict = parseVerdict(raw)\n if (verdict) return verdict\n return acceptOnParseFailure\n ? { accept: true }\n : { accept: false, reason: 'verifier returned an unparseable verdict' }\n },\n }\n}\n\n/** Parse the verifier's `{accept, reason}` JSON, tolerant of fences / prose. */\nfunction parseVerdict(raw: string): SourceVerdict | null {\n const text = raw.trim()\n if (!text) return null\n const objMatch = text.match(/\\{[\\s\\S]*\\}/)\n if (!objMatch) return null\n try {\n const parsed = JSON.parse(objMatch[0]) as { accept?: unknown; reason?: unknown }\n if (typeof parsed.accept !== 'boolean') return null\n if (parsed.accept) return { accept: true }\n return {\n accept: false,\n reason:\n typeof parsed.reason === 'string' && parsed.reason.trim()\n ? parsed.reason.trim()\n : 'rejected by verifier',\n }\n } catch {\n return null\n }\n}\n","/**\n * Adaptive verifier mode for `runVerifiedResearchLoop`.\n *\n * The cost/quality A/B (`docs/results/cost-quality.md`) found the LLM relevance\n * verifier's cleanliness win is dominated by DE-DUPLICATION — which a\n * deterministic content-hash / canonical-URL check captures at ~none of the LLM\n * premium — and that an LLM check only earns its dollar on the off-scope tail.\n * The honest production move it names is: do the cheap deterministic work first,\n * spend the LLM only where it pays. This module is that driver.\n *\n * Per candidate source the adaptive driver runs THREE stages, cheapest first,\n * and stops at the first that decides:\n *\n * 1. DEDUP ($0, no LLM). Reject a source whose CONTENT (normalized-text hash)\n * or whose CANONICAL URL matches one already accepted this round or already\n * in the knowledge base. This is the de-dup the relevance judge was being\n * paid to do; doing it deterministically is free and exact.\n *\n * 2. HEURISTIC TRIAGE ($0, no LLM). For a unique survivor, a cheap host /\n * title / length signal classifies it as clearly-keep, clearly-drop, or\n * AMBIGUOUS. Clear cases are resolved without a model: an authoritative host\n * (arxiv, *.edu, *.gov, official docs) with a substantial readable body is\n * kept; an obvious spam/listicle/marketing title or a too-thin body is\n * dropped. Only genuinely ambiguous survivors fall through.\n *\n * 3. LLM ESCALATION ($, one call). ONLY the ambiguous survivors reach the LLM\n * `verifySource` — the shipped `createVerifyingResearchDriver` relevance\n * judge. This is where the verifier earns its premium: the off-scope tail a\n * cheap rule can't adjudicate.\n *\n * The result is the cost/quality frontier point the doc predicted: most of the\n * cleanliness (dedup + clear drops) at a fraction of the LLM $/calls (only the\n * ambiguous tail pays). It is a real `ResearchDriver` — same contract the\n * two-agent loop already gates on — and reuses `sha256`, the relevance verifier,\n * and the index; it reinvents none of them.\n */\n\nimport { sha256 } from './ids'\nimport type {\n ResearchSourceProposal,\n SourceVerdict,\n SourceVerificationContext,\n} from './two-agent-research-loop'\nimport {\n createVerifyingResearchDriver,\n type RouterClient,\n type TangleRouterOptions,\n type VerifyingDriverOptions,\n} from './web-research-worker'\n\n/**\n * Canonicalize a URL for duplicate detection: lowercase host, strip a leading\n * `www.`, drop the scheme, the fragment, a trailing slash, and tracking query\n * params (`utm_*`, `ref`, `fbclid`, `gclid`, …). Two URLs that differ only by\n * those decorations canonicalize to the same key, so the dedup stage treats them\n * as the same source. Falls back to the lowercased raw string when the input is\n * not a parseable absolute URL (so non-http identifiers still dedup by equality).\n */\nexport function canonicalizeUrl(uri: string): string {\n const trimmed = uri.trim()\n try {\n const url = new URL(trimmed)\n const host = url.hostname.toLowerCase().replace(/^www\\./, '')\n // Keep only non-tracking query params, sorted for stable ordering.\n const kept: [string, string][] = []\n for (const [key, value] of url.searchParams) {\n const lower = key.toLowerCase()\n if (lower.startsWith('utm_')) continue\n if (trackingParams.has(lower)) continue\n kept.push([key, value])\n }\n kept.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n const query = kept.map(([k, v]) => `${k}=${v}`).join('&')\n const path = url.pathname.replace(/\\/+$/, '') || '/'\n return `${host}${path}${query ? `?${query}` : ''}`\n } catch {\n return trimmed.toLowerCase()\n }\n}\n\n/** Tracking / referrer query params dropped during URL canonicalization. */\nconst trackingParams = new Set([\n 'ref',\n 'ref_src',\n 'source',\n 'fbclid',\n 'gclid',\n 'mc_cid',\n 'mc_eid',\n 'igshid',\n 'spm',\n '_hsenc',\n '_hsmi',\n])\n\n/**\n * A stable content key for a fetched page: the sha256 of its normalized text\n * (lowercased, punctuation/whitespace collapsed). Two pages whose readable body\n * is the same modulo formatting collide here, so the dedup stage rejects a\n * mirror/syndication of an already-accepted source even when the URL differs.\n */\nexport function contentKey(text: string): string {\n const normalized = text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return sha256(normalized)\n}\n\n/** Why the deterministic dedup stage rejected a candidate (for audit/notes). */\nexport type DedupReason = 'duplicate-url' | 'duplicate-content'\n\n/** The cheap-triage classification of a unique survivor. */\nexport type TriageClass = 'keep' | 'drop' | 'ambiguous'\n\n/** One source's adaptive routing decision, for instrumentation and the doc. */\nexport interface AdaptiveDecision {\n uri: string\n /** The stage that decided this source: dedup | heuristic | llm. */\n stage: 'dedup' | 'heuristic' | 'llm'\n accepted: boolean\n /** The triage class assigned (set once past dedup). */\n triage?: TriageClass\n reason?: string\n}\n\n/** Running tally of where the adaptive driver spent its decisions. */\nexport interface AdaptiveStats {\n total: number\n /** Rejected by deterministic dedup (URL or content). $0. */\n dedupRejected: number\n /** Kept by the cheap heuristic without an LLM call. $0. */\n heuristicKept: number\n /** Dropped by the cheap heuristic without an LLM call. $0. */\n heuristicDropped: number\n /** Escalated to the LLM relevance verifier ($ — the only paid stage). */\n llmCalls: number\n /** Of the escalations, how many the LLM accepted. */\n llmAccepted: number\n decisions: AdaptiveDecision[]\n}\n\nexport interface AdaptiveDriverOptions {\n /** Router client for the LLM escalation. Defaults to a live client from env. */\n router?: RouterClient\n router_options?: TangleRouterOptions\n /** Passed through to the escalation relevance verifier. */\n verifying?: Pick<VerifyingDriverOptions, 'acceptOnParseFailure'>\n /**\n * Hosts an authoritative source lives on. A unique survivor on one of these,\n * with a substantial body, is KEPT deterministically (no LLM). Suffix-matched\n * against the canonical host, so `arxiv.org` matches `export.arxiv.org`. The\n * defaults cover papers, official docs, and standards bodies.\n */\n authoritativeHosts?: string[]\n /**\n * Title/snippet patterns that mark obvious spam / listicle / marketing — a\n * unique survivor matching one is DROPPED deterministically (no LLM).\n */\n spamPatterns?: RegExp[]\n /**\n * Below this many readable chars a survivor is too thin to be a real reference\n * and is dropped deterministically. Default 400.\n */\n minBodyChars?: number\n /**\n * A survivor whose body is at or above this many chars AND on an authoritative\n * host is kept without an LLM call. Default 600.\n */\n substantialBodyChars?: number\n /** Receives each routing decision as it is made (for live instrumentation). */\n onDecision?: (decision: AdaptiveDecision) => void\n}\n\n/** Default authoritative host suffixes — papers, official docs, standards. */\nconst defaultAuthoritativeHosts = [\n 'arxiv.org',\n 'aclanthology.org',\n 'openreview.net',\n 'dl.acm.org',\n 'ieeexplore.ieee.org',\n 'nature.com',\n 'science.org',\n 'pubmed.ncbi.nlm.nih.gov',\n 'ncbi.nlm.nih.gov',\n '.edu',\n '.gov',\n 'docs.python.org',\n 'pytorch.org',\n 'tensorflow.org',\n 'huggingface.co',\n 'github.com',\n 'developer.mozilla.org',\n 'wikipedia.org',\n 'w3.org',\n 'ietf.org',\n 'rfc-editor.org',\n]\n\n/** Default spam/listicle/marketing title patterns. */\nconst defaultSpamPatterns = [\n /\\bbuy\\b.*\\b(cheap|now|deal|sale|discount)\\b/i,\n /\\b\\d+\\s+(things|ways|reasons|tips|tricks|secrets|hacks)\\b.*\\b(you|that|will)\\b/i,\n /\\bshock(ing|ed)?\\b/i,\n /\\bclickbait\\b/i,\n /!!!|\\$\\$\\$/,\n /\\b(coupon|promo code|affiliate|sponsored)\\b/i,\n /\\bbest .* (of \\d{4}|in \\d{4})\\b/i,\n]\n\n/**\n * Classify a UNIQUE survivor (already past dedup) with cheap host/title/length\n * signals only — no LLM. Returns `keep`, `drop`, or `ambiguous`. `ambiguous` is\n * the residue the LLM is reserved for: on-topic-looking pages on unknown hosts\n * with a plausible body, which a host/title rule cannot adjudicate.\n */\nexport function triageSource(\n source: ResearchSourceProposal,\n options: {\n authoritativeHosts: string[]\n spamPatterns: RegExp[]\n minBodyChars: number\n substantialBodyChars: number\n },\n): { triage: TriageClass; reason: string } {\n const titleAndSnippet = `${source.title ?? ''} ${\n typeof source.metadata?.snippet === 'string' ? source.metadata.snippet : ''\n }`.trim()\n const bodyLen = source.text.trim().length\n\n // Clear DROP: obvious spam/listicle/marketing title, OR a too-thin body that\n // can't be a real reference.\n for (const pattern of options.spamPatterns) {\n if (pattern.test(titleAndSnippet)) {\n return { triage: 'drop', reason: `spam/listicle title (${pattern.source})` }\n }\n }\n if (bodyLen < options.minBodyChars) {\n return { triage: 'drop', reason: `thin body (${bodyLen} < ${options.minBodyChars} chars)` }\n }\n\n // Clear KEEP: an authoritative host with a substantial readable body. The host\n // is a strong prior for a real reference; the length rules out a stub page.\n const host = hostOf(source.uri)\n const authoritative =\n host.length > 0 && options.authoritativeHosts.some((suffix) => hostMatches(host, suffix))\n if (authoritative && bodyLen >= options.substantialBodyChars) {\n return { triage: 'keep', reason: `authoritative host ${host} + substantial body (${bodyLen})` }\n }\n\n // Everything else is AMBIGUOUS — an unknown host with a plausible body. This\n // is exactly the off-scope tail the LLM relevance judge is reserved for.\n return { triage: 'ambiguous', reason: `unknown host ${host || '(none)'}, body ${bodyLen} chars` }\n}\n\nfunction hostOf(uri: string): string {\n try {\n return new URL(uri.trim()).hostname.toLowerCase().replace(/^www\\./, '')\n } catch {\n return ''\n }\n}\n\n/** Suffix host match: `.edu` matches `mit.edu`; `arxiv.org` matches `export.arxiv.org`. */\nfunction hostMatches(host: string, suffix: string): boolean {\n if (suffix.startsWith('.')) return host.endsWith(suffix) || host === suffix.slice(1)\n return host === suffix || host.endsWith(`.${suffix}`)\n}\n\nexport interface AdaptiveResearchDriver {\n verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict>\n /** Live tally of where decisions were spent — the cost/quality instrumentation. */\n stats(): AdaptiveStats\n}\n\n/**\n * Build the adaptive verifier. The deterministic stages (dedup + heuristic\n * triage) cost $0; only AMBIGUOUS survivors escalate to the LLM relevance\n * verifier. `stats()` exposes where every decision was spent so the A/B can read\n * the LLM $/calls the adaptive driver saved against the cleanliness it kept.\n *\n * Dedup state is kept on the driver instance: it tracks the canonical URLs and\n * content hashes it has ACCEPTED, plus those it sees in the verification\n * context's `acceptedThisRound` and the KB index. Use one driver per loop run.\n */\nexport function createAdaptiveResearchDriver(\n options: AdaptiveDriverOptions = {},\n): AdaptiveResearchDriver {\n const authoritativeHosts = options.authoritativeHosts ?? defaultAuthoritativeHosts\n const spamPatterns = options.spamPatterns ?? defaultSpamPatterns\n const minBodyChars = Math.max(1, options.minBodyChars ?? 400)\n const substantialBodyChars = Math.max(minBodyChars, options.substantialBodyChars ?? 600)\n\n // The shipped LLM relevance verifier — the ONLY paid stage, reused, not rebuilt.\n const relevance = createVerifyingResearchDriver({\n router: options.router,\n router_options: options.router_options,\n acceptOnParseFailure: options.verifying?.acceptOnParseFailure,\n })\n\n // Dedup memory across the run: every URL/content key this driver ACCEPTED.\n const acceptedUrlKeys = new Set<string>()\n const acceptedContentKeys = new Set<string>()\n\n const stats: AdaptiveStats = {\n total: 0,\n dedupRejected: 0,\n heuristicKept: 0,\n heuristicDropped: 0,\n llmCalls: 0,\n llmAccepted: 0,\n decisions: [],\n }\n\n function record(decision: AdaptiveDecision): void {\n stats.decisions.push(decision)\n options.onDecision?.(decision)\n }\n\n return {\n async verifySource(source, ctx): Promise<SourceVerdict> {\n stats.total += 1\n const urlKey = canonicalizeUrl(source.uri)\n const cKey = contentKey(source.text)\n\n // ---- STAGE 1: DETERMINISTIC DEDUP ($0) ----------------------------------\n // Seed the dup sets from what the loop already accepted this round AND from\n // the KB index, so a duplicate of an existing source is caught even if this\n // driver instance hasn't seen it yet.\n const roundUrlKeys = new Set(\n ctx.acceptedThisRound.map((accepted) => canonicalizeUrl(accepted.uri)),\n )\n const roundContentKeys = new Set(\n ctx.acceptedThisRound.map((accepted) => contentKey(accepted.text)),\n )\n const indexUrlKeys = new Set(\n ctx.index.sources.flatMap((indexed) =>\n typeof indexed.metadata?.originalUri === 'string'\n ? [canonicalizeUrl(indexed.metadata.originalUri)]\n : [],\n ),\n )\n const dupUrl =\n acceptedUrlKeys.has(urlKey) || roundUrlKeys.has(urlKey) || indexUrlKeys.has(urlKey)\n const dupContent = acceptedContentKeys.has(cKey) || roundContentKeys.has(cKey)\n if (dupUrl || dupContent) {\n stats.dedupRejected += 1\n const reason: DedupReason = dupUrl ? 'duplicate-url' : 'duplicate-content'\n record({ uri: source.uri, stage: 'dedup', accepted: false, reason })\n return { accept: false, reason: `dedup: ${reason}` }\n }\n\n // ---- STAGE 2: CHEAP HEURISTIC TRIAGE ($0) -------------------------------\n const { triage, reason } = triageSource(source, {\n authoritativeHosts,\n spamPatterns,\n minBodyChars,\n substantialBodyChars,\n })\n if (triage === 'keep') {\n stats.heuristicKept += 1\n acceptedUrlKeys.add(urlKey)\n acceptedContentKeys.add(cKey)\n record({ uri: source.uri, stage: 'heuristic', accepted: true, triage, reason })\n return { accept: true }\n }\n if (triage === 'drop') {\n stats.heuristicDropped += 1\n record({ uri: source.uri, stage: 'heuristic', accepted: false, triage, reason })\n return { accept: false, reason: `heuristic drop: ${reason}` }\n }\n\n // ---- STAGE 3: LLM ESCALATION ($ — ambiguous tail only) ------------------\n stats.llmCalls += 1\n const verdict = await relevance.verifySource(source, ctx)\n if (verdict.accept) {\n stats.llmAccepted += 1\n acceptedUrlKeys.add(urlKey)\n acceptedContentKeys.add(cKey)\n }\n record({\n uri: source.uri,\n stage: 'llm',\n accepted: verdict.accept,\n triage,\n reason: verdict.accept ? 'llm accepted' : verdict.reason,\n })\n return verdict\n },\n stats(): AdaptiveStats {\n return {\n ...stats,\n decisions: [...stats.decisions],\n }\n },\n }\n}\n","import {\n type AgentCandidateKnowledgeRef,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n type KnowledgeImprovementCandidateRef,\n KnowledgeImprovementCandidateRefSchema,\n} from './kb-improvement'\n\n/** Convert a measured knowledge candidate into the shared review and execution identity. */\nexport function toAgentCandidateKnowledgeRef(\n candidate: KnowledgeImprovementCandidateRef,\n): AgentCandidateKnowledgeRef {\n const parsed = KnowledgeImprovementCandidateRefSchema.parse(candidate)\n return {\n ...parsed,\n goalHash: prefixedDigest(parsed.goalHash),\n baseHash: prefixedDigest(parsed.baseHash),\n candidateHash: prefixedDigest(parsed.candidateHash),\n evidenceHash: prefixedDigest(parsed.evidenceHash),\n promotionPlanHash: prefixedDigest(parsed.promotionPlanHash),\n }\n}\n\n/** Recover agent-knowledge's candidate identity from the shared contract. */\nexport function fromAgentCandidateKnowledgeRef(\n candidate: AgentCandidateKnowledgeRef,\n): KnowledgeImprovementCandidateRef {\n return KnowledgeImprovementCandidateRefSchema.parse({\n ...candidate,\n goalHash: rawDigest(candidate.goalHash),\n baseHash: rawDigest(candidate.baseHash),\n candidateHash: rawDigest(candidate.candidateHash),\n evidenceHash: rawDigest(candidate.evidenceHash),\n promotionPlanHash: rawDigest(candidate.promotionPlanHash),\n })\n}\n\nfunction prefixedDigest(value: string) {\n return sha256DigestSchema.parse(`sha256:${value}`)\n}\n\nfunction rawDigest(value: string): string {\n return sha256DigestSchema.parse(value).slice('sha256:'.length)\n}\n","import { createHash } from 'node:crypto'\nimport { cp, lstat, mkdir, mkdtemp, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport {\n canonicalJson,\n contentHash,\n type RunRecord,\n validateRunRecord,\n} from '@tangle-network/agent-eval'\nimport {\n type AgentImprovementActivation,\n type AgentImprovementActivationResult,\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n canonicalCandidateDigest,\n omitTopLevelDigest,\n type Sha256Digest,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport { z } from 'zod'\nimport {\n isMissingFile,\n listRegularFilesWithinRoot,\n readRegularFileWithinRoot,\n renameDurable,\n withSafeDirectory,\n writeJsonDurableWithinRoot,\n} from './durable-fs'\nimport type {\n BuildEvalKnowledgeBundleOptions,\n EvalKnowledgeBundleBuildResult,\n KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport {\n applyKnowledgeFileTransaction,\n assertKnowledgeMutationPath,\n finishKnowledgeFileTransaction,\n type KnowledgeFileMutation,\n type KnowledgeFileTransaction,\n type KnowledgeFileTransactionPlanEntry,\n knowledgeFileTransactionPlanHash,\n prepareKnowledgeFileTransaction,\n rollbackKnowledgeFileTransaction,\n} from './file-transaction'\nimport { sha256, slugify, stableId } from './ids'\nimport { buildKnowledgeIndex, writeKnowledgeIndex } from './indexer'\nimport { acquireDurableFileLock, withKnowledgeMutation, withKnowledgeRead } from './mutation-lock'\nimport {\n type KnowledgeBaseQualityOptions,\n type KnowledgeBaseQualityReport,\n scoreKnowledgeBaseIndex,\n} from './rag-eval'\nimport {\n type RagKnowledgeImprovementPhase,\n type RagKnowledgeResearchOptions,\n type RagKnowledgeUpdateInput,\n type RagKnowledgeUpdateResult,\n type RunRagKnowledgeImprovementLoopOptions,\n type RunRagKnowledgeImprovementLoopResult,\n runRagKnowledgeImprovementLoop,\n} from './rag-improvement-loop'\nimport { readinessFor } from './readiness-helpers'\nimport type { RunKnowledgeResearchLoopOptions } from './research-loop'\nimport type { RunRetrievalImprovementLoopOptions } from './retrieval-eval'\nimport { layoutFor } from './store'\nimport type { KnowledgeIndex } from './types'\nimport {\n type ValidateKnowledgeOptions,\n type ValidateKnowledgeResult,\n validateKnowledgeIndex,\n} from './validate'\n\nexport type KnowledgeImprovementStatus =\n | 'running'\n | 'candidate-ready'\n | 'promoted'\n | 'rejected'\n | 'blocked'\n\ninterface KnowledgeImprovementMetricProvenanceBase {\n evaluator: string\n version: string\n}\n\nexport type KnowledgeImprovementMetricProvenance =\n | (KnowledgeImprovementMetricProvenanceBase & {\n method: 'deterministic'\n })\n | (KnowledgeImprovementMetricProvenanceBase & {\n method: 'sampled' | 'composite'\n corpusHash: string\n runRecords: RunRecord[]\n })\n | (KnowledgeImprovementMetricProvenanceBase & {\n method: 'model'\n model: string\n corpusHash: string\n runRecords: RunRecord[]\n })\n\nexport interface KnowledgeImprovementMetric {\n score: number\n passed: boolean\n dimensions?: Record<string, number>\n notes?: string\n provenance: KnowledgeImprovementMetricProvenance\n}\n\nexport interface KnowledgeImprovementEvaluationInput {\n runId: string\n iteration: number\n root: string\n baselineRoot: string\n candidateRoot: string\n baselineIndex: KnowledgeIndex\n candidateIndex: KnowledgeIndex\n baseHash: string\n candidateHash: string\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n kbQuality: KnowledgeBaseQualityReport\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n signal?: AbortSignal\n}\n\nexport type KnowledgeImprovementEvaluator = (\n input: KnowledgeImprovementEvaluationInput,\n) => Promise<KnowledgeImprovementMetric> | KnowledgeImprovementMetric\n\nexport interface KnowledgeImprovementCandidateRecord {\n iteration: number\n candidateId: string\n baseHash: string\n candidateHash?: string\n evidenceHash?: string\n promotionPlanHash?: string\n status: KnowledgeImprovementStatus\n createdAt: string\n updatedAt: string\n}\n\nexport interface KnowledgeImprovementRunState {\n runId: string\n root: string\n goal: string\n status: KnowledgeImprovementStatus\n baseHash: string\n createdAt: string\n updatedAt: string\n ownerId?: string\n candidates: KnowledgeImprovementCandidateRecord[]\n promotedCandidateId?: string\n blockedReason?: string\n}\n\nexport interface KnowledgeImprovementResult {\n runId: string\n state: KnowledgeImprovementRunState\n candidate?: KnowledgeImprovementCandidateRecord\n evaluation?: KnowledgeImprovementMetric\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n promoted: boolean\n blocked: boolean\n}\n\nexport type KnowledgeImprovementTarget = 'candidate' | 'baseline'\n\nexport interface KnowledgeImprovementMutationReceipt {\n target: KnowledgeImprovementTarget\n beforeHash: string\n afterHash: string\n changed: boolean\n transactionId: string | null\n recovered: boolean\n}\n\nexport interface KnowledgeImprovementMutationResult extends KnowledgeImprovementResult {\n candidate: KnowledgeImprovementCandidateRecord\n mutation: KnowledgeImprovementMutationReceipt\n activationResult?: AgentImprovementActivationResult\n}\n\nexport interface KnowledgeImprovementActivationPersistence {\n activation: AgentImprovementActivation\n attemptedAt: string\n identity: string\n /** May run again after interruption; keep this deterministic and free of external side effects. */\n createResult(\n mutation: KnowledgeImprovementMutationReceipt,\n ): Promise<AgentImprovementActivationResult> | AgentImprovementActivationResult\n}\n\nconst digestSchema = z.string().regex(/^[a-f0-9]{64}$/)\nconst runIdSchema = z.string().min(1).max(2_048)\nconst safePathSegmentSchema = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/)\n\nconst knowledgeImprovementMutationReceiptSchema = z\n .object({\n target: z.enum(['candidate', 'baseline']),\n beforeHash: digestSchema,\n afterHash: digestSchema,\n changed: z.boolean(),\n transactionId: z.string().uuid().nullable(),\n recovered: z.boolean(),\n })\n .strict()\n\nconst knowledgeImprovementActivationRecordSchema = z\n .object({\n kind: z.literal('knowledge-improvement-activation-result'),\n candidateId: safePathSegmentSchema,\n mutation: knowledgeImprovementMutationReceiptSchema,\n result: agentImprovementActivationResultSchema,\n })\n .strict()\ntype KnowledgeImprovementActivationRecord = z.infer<\n typeof knowledgeImprovementActivationRecordSchema\n>\nconst improvementStatusSchema = z.enum([\n 'running',\n 'candidate-ready',\n 'promoted',\n 'rejected',\n 'blocked',\n])\nconst runRecordSchema = z.custom<RunRecord>((value) => {\n try {\n validateRunRecord(value)\n return true\n } catch {\n return false\n }\n}, 'invalid agent-eval RunRecord')\nconst deterministicMetricProvenanceSchema = z\n .object({\n evaluator: z.string().min(1),\n version: z.string().min(1),\n method: z.literal('deterministic'),\n })\n .strict()\nconst measuredMetricProvenanceSchema = z\n .object({\n evaluator: z.string().min(1),\n version: z.string().min(1),\n method: z.enum(['sampled', 'composite']),\n corpusHash: digestSchema,\n runRecords: z.array(runRecordSchema).min(1),\n })\n .strict()\nconst modelMetricProvenanceSchema = z\n .object({\n evaluator: z.string().min(1),\n version: z.string().min(1),\n method: z.literal('model'),\n model: z.string().min(1),\n corpusHash: digestSchema,\n runRecords: z.array(runRecordSchema).min(1),\n })\n .strict()\nconst improvementMetricSchema = z\n .object({\n score: z.number().finite().min(0).max(1),\n passed: z.boolean(),\n dimensions: z.record(z.string(), z.number().finite()).optional(),\n notes: z.string().optional(),\n provenance: z.discriminatedUnion('method', [\n deterministicMetricProvenanceSchema,\n measuredMetricProvenanceSchema,\n modelMetricProvenanceSchema,\n ]),\n })\n .strict()\n .superRefine((metric, context) => {\n if (metric.provenance.method === 'deterministic') return\n const actualCorpusHash = contentHash(metric.provenance.runRecords)\n if (actualCorpusHash !== metric.provenance.corpusHash) {\n context.addIssue({\n code: 'custom',\n path: ['provenance', 'corpusHash'],\n message: 'metric corpus hash must bind the complete RunRecord array',\n })\n }\n })\nconst candidateRecordSchema = z\n .object({\n iteration: z.number().int().positive(),\n candidateId: safePathSegmentSchema,\n baseHash: digestSchema,\n candidateHash: digestSchema.optional(),\n evidenceHash: digestSchema.optional(),\n promotionPlanHash: digestSchema.optional(),\n status: improvementStatusSchema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n })\n .strict()\n\nexport const KnowledgeImprovementRunStateSchema = z\n .object({\n runId: runIdSchema,\n root: z.string().min(1),\n goal: z.string().min(1),\n status: improvementStatusSchema,\n baseHash: digestSchema,\n createdAt: z.iso.datetime(),\n updatedAt: z.iso.datetime(),\n ownerId: z.string().min(1).optional(),\n candidates: z.array(candidateRecordSchema),\n promotedCandidateId: safePathSegmentSchema.optional(),\n blockedReason: z.string().min(1).optional(),\n })\n .strict()\n .superRefine((state, context) => {\n const candidateIds = new Set<string>()\n for (const [index, candidate] of state.candidates.entries()) {\n if (candidateIds.has(candidate.candidateId)) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index, 'candidateId'],\n message: 'candidate ids must be unique within an improvement run',\n })\n }\n candidateIds.add(candidate.candidateId)\n if (candidate.baseHash !== state.baseHash) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index, 'baseHash'],\n message: 'candidate base hash must match its improvement run',\n })\n }\n if (candidate.status === 'candidate-ready') {\n if (!candidate.candidateHash || !candidate.evidenceHash || !candidate.promotionPlanHash) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index],\n message: 'ready candidates require content, evidence, and promotion-plan identities',\n })\n }\n }\n if (\n candidate.status === 'promoted' &&\n (!candidate.candidateHash || !candidate.evidenceHash || !candidate.promotionPlanHash)\n ) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index],\n message: 'promoted candidates require content, evidence, and promotion-plan identities',\n })\n }\n if (\n candidate.status === 'promoted' &&\n Boolean(candidate.evidenceHash) !== Boolean(candidate.promotionPlanHash)\n ) {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index],\n message: 'promoted candidate evidence and promotion-plan identities must appear together',\n })\n }\n if (candidate.status === 'promoted' && state.status !== 'promoted') {\n context.addIssue({\n code: 'custom',\n path: ['candidates', index, 'status'],\n message: 'only a promoted run may contain a promoted candidate',\n })\n }\n }\n if (state.status === 'promoted') {\n const promoted = state.candidates.filter(\n (candidate) => candidate.candidateId === state.promotedCandidateId,\n )\n if (promoted.length !== 1 || promoted[0]?.status !== 'promoted') {\n context.addIssue({\n code: 'custom',\n path: ['promotedCandidateId'],\n message: 'promoted state must identify exactly one promoted candidate',\n })\n }\n } else if (state.promotedCandidateId !== undefined) {\n context.addIssue({\n code: 'custom',\n path: ['promotedCandidateId'],\n message: 'only a promoted run may identify a promoted candidate',\n })\n }\n if (\n state.status === 'candidate-ready' &&\n state.candidates.filter((candidate) => candidate.status === 'candidate-ready').length !== 1\n ) {\n context.addIssue({\n code: 'custom',\n path: ['status'],\n message: 'candidate-ready state must contain exactly one ready candidate',\n })\n }\n if (state.status === 'blocked' && state.blockedReason === undefined) {\n context.addIssue({\n code: 'custom',\n path: ['blockedReason'],\n message: 'blocked state must include a reason',\n })\n }\n })\n\nexport const KnowledgeImprovementEvidenceSchema = z\n .object({\n kind: z.literal('knowledge-improvement-evidence'),\n runId: runIdSchema,\n candidateId: safePathSegmentSchema,\n iteration: z.number().int().positive(),\n goalHash: digestSchema,\n baseHash: digestSchema,\n candidateHash: digestSchema,\n promotionPlanHash: digestSchema,\n validation: z.unknown(),\n readiness: z.unknown().nullable(),\n kbQuality: z.unknown(),\n evaluation: improvementMetricSchema,\n lifecycle: z.unknown().nullable(),\n })\n .strict()\n\nexport type KnowledgeImprovementEvidence = z.infer<typeof KnowledgeImprovementEvidenceSchema>\n\n/** Portable identity of one measured candidate. Paths and mutable run state are deliberately excluded. */\nexport const KnowledgeImprovementCandidateRefSchema = z\n .object({\n kind: z.literal('knowledge-improvement-candidate'),\n runId: runIdSchema,\n candidateId: safePathSegmentSchema,\n goalHash: digestSchema,\n baseHash: digestSchema,\n candidateHash: digestSchema,\n evidenceHash: digestSchema,\n promotionPlanHash: digestSchema,\n })\n .strict()\n\nexport type KnowledgeImprovementCandidateRef = z.infer<\n typeof KnowledgeImprovementCandidateRefSchema\n>\n\nexport interface PromoteKnowledgeCandidateOptions {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n activation?: KnowledgeImprovementActivationPersistence\n ownerId?: string\n leaseTtlMs?: number\n now?: () => Date\n onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void\n}\n\nexport type RestoreKnowledgeCandidateBaselineOptions = PromoteKnowledgeCandidateOptions\n\nexport interface LoadKnowledgeImprovementActivationResultOptions {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n activation: AgentImprovementActivation\n identity: string\n}\n\nexport interface UseKnowledgeImprovementCandidateOptions {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n}\n\nexport interface ResolvedKnowledgeImprovementComparisonSnapshot {\n root: string\n hash: string\n}\n\nexport interface ResolvedKnowledgeImprovementComparison {\n reference: KnowledgeImprovementCandidateRef\n evaluation: KnowledgeImprovementMetric\n baseline: ResolvedKnowledgeImprovementComparisonSnapshot\n candidate: ResolvedKnowledgeImprovementComparisonSnapshot\n}\n\nexport interface ResolvedKnowledgeImprovementCandidate {\n root: string\n candidate: KnowledgeImprovementCandidateRef\n evaluation: KnowledgeImprovementMetric\n}\n\nexport interface KnowledgeImprovementRetrievalOptions\n extends Omit<RunRetrievalImprovementLoopOptions, 'index' | 'runDir'> {\n runDir?: RunRetrievalImprovementLoopOptions['runDir']\n}\n\nexport interface KnowledgeImprovementUpdateInput extends RagKnowledgeUpdateInput {\n runId: string\n iteration: number\n candidateId: string\n root: string\n baselineRoot: string\n candidateRoot: string\n baseHash: string\n}\n\nexport type KnowledgeImprovementUpdate = (\n input: KnowledgeImprovementUpdateInput,\n) => Promise<RagKnowledgeUpdateResult> | RagKnowledgeUpdateResult\n\nexport interface KnowledgeImprovementOptions {\n root: string\n goal: string\n runId?: string\n ownerId?: string\n leaseTtlMs?: number\n resume?: boolean\n maxCandidates?: number\n candidateResearchIterations?: number\n strict?: ValidateKnowledgeOptions['strict']\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n kbQuality?: KnowledgeBaseQualityOptions\n step?: RunKnowledgeResearchLoopOptions['step']\n knowledgeResearch?: Omit<RagKnowledgeResearchOptions, 'root'>\n retrieval?: KnowledgeImprovementRetrievalOptions\n diagnose?: NonNullable<RunRagKnowledgeImprovementLoopOptions['diagnose']>\n acquireKnowledge?: NonNullable<RunRagKnowledgeImprovementLoopOptions['acquireKnowledge']>\n updateKnowledge?: KnowledgeImprovementUpdate\n evaluateAnswers?: NonNullable<RunRagKnowledgeImprovementLoopOptions['evaluateAnswers']>\n decidePromotion?: NonNullable<RunRagKnowledgeImprovementLoopOptions['promote']>\n enabledPhases?: readonly RagKnowledgeImprovementPhase[]\n requiredPhases?: readonly RagKnowledgeImprovementPhase[]\n evaluate?: KnowledgeImprovementEvaluator\n signal?: AbortSignal\n now?: () => Date\n onState?: (state: KnowledgeImprovementRunState) => Promise<void> | void\n}\n\ninterface LeaseHandle {\n ownerId: string\n assertOwned(): void\n release(): Promise<void>\n}\n\nconst DEFAULT_LEASE_TTL_MS = 15 * 60 * 1000\nconst UPDATE_PHASES: readonly RagKnowledgeImprovementPhase[] = [\n 'knowledge-acquisition',\n 'knowledge-update',\n]\nconst EVALUATION_PHASES: readonly RagKnowledgeImprovementPhase[] = [\n 'retrieval-tuning',\n 'gap-diagnosis',\n 'answer-quality',\n 'promotion',\n]\n\nexport function knowledgeImprovementRunId(root: string, goal: string): string {\n return stableId('kimpr', `${root}:${goal}`)\n}\n\nexport function knowledgeImprovementRunDir(root: string, runId: string): string {\n const parsedRunId = runIdSchema.parse(runId)\n const safeRunId = safePathSegmentSchema.safeParse(parsedRunId)\n const runSegment = safeRunId.success\n ? safeRunId.data\n : `${slugify(parsedRunId).slice(0, 72)}-${sha256(parsedRunId).slice(0, 16)}`\n const improvementsDir = join(layoutFor(root).cacheDir, 'improvements')\n const runDir = join(improvementsDir, runSegment)\n const resolvedImprovementsDir = resolve(improvementsDir)\n const resolvedRunDir = resolve(runDir)\n if (!resolvedRunDir.startsWith(`${resolvedImprovementsDir}${sep}`)) {\n throw new Error('knowledge improvement run directory escaped its root')\n }\n return runDir\n}\n\nasync function withKnowledgeImprovementRun<T>(\n root: string,\n runId: string,\n create: boolean,\n use: (runDir: string) => Promise<T> | T,\n): Promise<T> {\n const runDir = knowledgeImprovementRunDir(root, runId)\n const relativePath = descendantPath(root, runDir)\n if (!relativePath) throw new Error('knowledge improvement run directory escaped its root')\n return withSafeDirectory(root, relativePath, create, async (openedRunDir) => {\n const result = await use(openedRunDir)\n const openedIdentity = await stat(openedRunDir)\n const currentIdentity = await withSafeDirectory(root, relativePath, false, (currentRunDir) =>\n stat(currentRunDir),\n )\n if (openedIdentity.dev !== currentIdentity.dev || openedIdentity.ino !== currentIdentity.ino) {\n throw new Error('knowledge improvement run directory changed during use')\n }\n return result\n })\n}\n\nexport async function loadKnowledgeImprovementState(\n root: string,\n runId: string,\n): Promise<KnowledgeImprovementRunState | null> {\n const expectedRunId = runIdSchema.parse(runId)\n try {\n return await withKnowledgeImprovementRun(root, expectedRunId, false, (runDir) =>\n loadKnowledgeImprovementStateFromRun(root, expectedRunId, runDir),\n )\n } catch (error) {\n if (isMissingFile(error)) return null\n throw error\n }\n}\n\n/** Load the durable result for one exact activation without changing knowledge or run state. */\nexport async function loadKnowledgeImprovementActivationResult(\n options: LoadKnowledgeImprovementActivationResultOptions,\n): Promise<AgentImprovementActivationResult | null> {\n assertExactCandidatePlatform()\n const candidate = Object.freeze(KnowledgeImprovementCandidateRefSchema.parse(options.candidate))\n const activation = verifyCanonicalKnowledgeActivation(options.activation)\n const target = targetForKnowledgeActivation(activation)\n assertKnowledgeActivationAuthority(activation, candidate, target, options.identity)\n return withKnowledgeImprovementRun(options.root, candidate.runId, false, async (runDir) => {\n const record = await loadKnowledgeActivationRecord(\n runDir,\n candidate,\n activation,\n target,\n options.identity,\n )\n return record?.result ?? null\n })\n}\n\nasync function loadKnowledgeImprovementStateFromRun(\n root: string,\n runId: string,\n runDir: string,\n): Promise<KnowledgeImprovementRunState> {\n const stateFile = await readRegularFileWithinRoot(runDir, 'state.json')\n const raw = JSON.parse(stateFile.bytes.toString('utf8')) as unknown\n const state = KnowledgeImprovementRunStateSchema.parse(raw) as KnowledgeImprovementRunState\n if (state.runId !== runId) {\n throw new Error('knowledge improvement state does not match the requested run')\n }\n if (resolve(state.root) !== resolve(root)) {\n throw new Error('knowledge improvement state does not match the requested root')\n }\n for (const candidate of state.candidates) {\n if (candidate.status === 'running') await assertCandidateWorkspace(runDir, candidate)\n }\n return state\n}\n\n/** Freeze the exact knowledge bytes and measured evidence a later approval may promote. */\nexport function knowledgeImprovementCandidateRef(\n result: Pick<KnowledgeImprovementResult, 'runId' | 'state' | 'candidate'>,\n): KnowledgeImprovementCandidateRef {\n if (!result.candidate) throw new Error('knowledge improvement result has no candidate')\n return candidateRefFor(result.runId, result.state, result.candidate)\n}\n\n/** Use both frozen sides of one measured comparison in isolated, integrity-checked copies. */\nexport async function withKnowledgeImprovementComparison<T>(\n options: UseKnowledgeImprovementCandidateOptions,\n use: (comparison: ResolvedKnowledgeImprovementComparison) => Promise<T> | T,\n): Promise<T> {\n assertExactCandidatePlatform()\n const reference = Object.freeze(KnowledgeImprovementCandidateRefSchema.parse(options.candidate))\n return withKnowledgeImprovementRun(options.root, reference.runId, false, async (runDir) => {\n const state = await loadKnowledgeImprovementStateFromRun(options.root, reference.runId, runDir)\n return withMeasuredCandidateSnapshot(options.root, runDir, state, reference, (resolved) =>\n withBaselineSnapshot(runDir, reference.baseHash, (baselineRoot) =>\n withIsolatedKnowledgeCopy(baselineRoot, reference.baseHash, 'baseline', (baseline) =>\n withIsolatedKnowledgeCopy(\n resolved.root,\n reference.candidateHash,\n 'candidate',\n (candidate) =>\n use(\n Object.freeze({\n reference,\n evaluation: immutableJsonValue(structuredClone(resolved.evidence.evaluation)),\n baseline: Object.freeze({ root: baseline, hash: reference.baseHash }),\n candidate: Object.freeze({ root: candidate, hash: reference.candidateHash }),\n }),\n ),\n ),\n ),\n ),\n )\n })\n}\n\n/** Use the frozen candidate side of one measured comparison. */\nexport async function withKnowledgeImprovementCandidate<T>(\n options: UseKnowledgeImprovementCandidateOptions,\n use: (candidate: ResolvedKnowledgeImprovementCandidate) => Promise<T> | T,\n): Promise<T> {\n assertExactCandidatePlatform()\n const candidateRef = Object.freeze(\n KnowledgeImprovementCandidateRefSchema.parse(options.candidate),\n )\n return withKnowledgeImprovementRun(options.root, candidateRef.runId, false, async (runDir) => {\n const state = await loadKnowledgeImprovementStateFromRun(\n options.root,\n candidateRef.runId,\n runDir,\n )\n return withMeasuredCandidateSnapshot(options.root, runDir, state, candidateRef, (resolved) =>\n withIsolatedKnowledgeCopy(resolved.root, candidateRef.candidateHash, 'candidate', (root) =>\n use(\n Object.freeze({\n root,\n candidate: candidateRef,\n evaluation: immutableJsonValue(structuredClone(resolved.evidence.evaluation)),\n }),\n ),\n ),\n )\n })\n}\n\n/** Promote one previously measured candidate without rerunning research or evaluation. */\nexport async function promoteKnowledgeCandidate(\n options: PromoteKnowledgeCandidateOptions,\n): Promise<KnowledgeImprovementMutationResult> {\n return transitionKnowledgeCandidate(options, 'candidate')\n}\n\n/** Restore the frozen baseline paired with one previously measured candidate. */\nexport async function restoreKnowledgeCandidateBaseline(\n options: RestoreKnowledgeCandidateBaselineOptions,\n): Promise<KnowledgeImprovementMutationResult> {\n return transitionKnowledgeCandidate(options, 'baseline')\n}\n\nasync function transitionKnowledgeCandidate(\n options: PromoteKnowledgeCandidateOptions,\n target: KnowledgeImprovementTarget,\n): Promise<KnowledgeImprovementMutationResult> {\n assertExactCandidatePlatform()\n const candidateRef = Object.freeze(\n KnowledgeImprovementCandidateRefSchema.parse(options.candidate),\n )\n const now = options.now ?? (() => new Date())\n const activation = options.activation\n ? resolveKnowledgeActivationPersistence(options.activation, candidateRef, target)\n : undefined\n return withKnowledgeImprovementRun(options.root, candidateRef.runId, false, async (runDir) => {\n const lease = await acquireRunLease(runDir, {\n ownerId: options.ownerId ?? `pid-${process.pid}`,\n ttlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n })\n try {\n lease.assertOwned()\n const state = await loadKnowledgeImprovementStateFromRun(\n options.root,\n candidateRef.runId,\n runDir,\n )\n return await applyKnowledgeCandidateTarget(\n {\n root: options.root,\n runDir,\n state,\n candidateRef,\n leaseTtlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n assertRunOwned: lease.assertOwned,\n now,\n onState: options.onState,\n activation,\n },\n target,\n )\n } finally {\n await lease.release()\n }\n })\n}\n\nexport async function improveKnowledgeBase(\n options: KnowledgeImprovementOptions,\n): Promise<KnowledgeImprovementResult> {\n assertExactCandidatePlatform()\n assertKnowledgeImprovementOptions(options)\n const now = options.now ?? (() => new Date())\n const runId = runIdSchema.parse(\n options.runId ?? knowledgeImprovementRunId(options.root, options.goal),\n )\n return withKnowledgeImprovementRun(options.root, runId, true, (runDir) =>\n improveKnowledgeBaseInRun(options, runId, runDir, now),\n )\n}\n\nasync function improveKnowledgeBaseInRun(\n options: KnowledgeImprovementOptions,\n runId: string,\n runDir: string,\n now: () => Date,\n): Promise<KnowledgeImprovementResult> {\n const lease = await acquireRunLease(runDir, {\n ownerId: options.ownerId ?? `pid-${process.pid}`,\n ttlMs: options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n })\n\n try {\n lease.assertOwned()\n let state =\n options.resume === false\n ? null\n : await loadKnowledgeImprovementStateFromRun(options.root, runId, runDir).catch((error) => {\n if (isMissingFile(error)) return null\n throw error\n })\n if (!state) {\n const baseHash = await hashKnowledgeBase(options.root)\n await createBaselineSnapshot(runDir, options.root, baseHash)\n state = {\n runId,\n root: options.root,\n goal: options.goal,\n status: 'running',\n baseHash,\n createdAt: now().toISOString(),\n updatedAt: now().toISOString(),\n ownerId: lease.ownerId,\n candidates: [],\n }\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, { type: 'run.created', runId, baseHash })\n }\n if (state.goal !== options.goal) {\n throw new Error('knowledge improvement state does not match the requested goal')\n }\n const promotedCandidateId = state.promotedCandidateId\n const promotedCandidate =\n state.status === 'promoted'\n ? state.candidates.find((candidate) => candidate.candidateId === promotedCandidateId)\n : undefined\n if (state.status === 'promoted' && !promotedCandidate) {\n throw new Error('promoted knowledge state has no promoted candidate')\n }\n if (state.status === 'promoted') {\n const promoted = promotedCandidate!\n const promotedState = state\n return withKnowledgeMutation(options.root, async () => {\n const currentHash = await hashKnowledgeBase(options.root)\n if (currentHash !== promoted.candidateHash) {\n throw new Error(\n `promoted knowledge base changed: expected ${promoted.candidateHash}, got ${currentHash}`,\n )\n }\n const evidence = await assertCandidateEvidence(\n runDir,\n candidateRefFor(runId, promotedState, promoted),\n )\n return {\n runId,\n state: promotedState,\n candidate: promoted,\n evaluation: evidence.evaluation,\n promoted: true,\n blocked: false,\n }\n })\n }\n await withKnowledgeMutation(options.root, () => undefined)\n await ensureBaselineSnapshot(runDir, options.root, state.baseHash)\n\n if (state.status === 'blocked') {\n return { runId, state, promoted: false, blocked: true }\n }\n\n const maxCandidates = Math.max(1, options.maxCandidates ?? 1)\n let candidate = findActiveCandidate(state)\n let lastRejectedCandidate: KnowledgeImprovementCandidateRecord | undefined\n let lastRejectedEvaluation: KnowledgeImprovementMetric | undefined\n let lifecycle: RunRagKnowledgeImprovementLoopResult | undefined\n\n while (candidate || state.candidates.length < maxCandidates) {\n if (!candidate) {\n const currentHash = await hashKnowledgeBase(options.root)\n if (currentHash !== state.baseHash) {\n state = await blockRun(\n runDir,\n state,\n `base changed before candidate creation: expected ${state.baseHash}, got ${currentHash}`,\n options.onState,\n now,\n )\n return { runId, state, promoted: false, blocked: true }\n }\n const activeState = state\n candidate = await withBaselineSnapshot(runDir, activeState.baseHash, (baselineRoot) =>\n createCandidateWorkspace(runDir, activeState, baselineRoot, now),\n )\n state.candidates.push(candidate)\n state.status = 'running'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, {\n type: 'candidate.created',\n runId,\n candidateId: candidate.candidateId,\n iteration: candidate.iteration,\n })\n }\n\n const measured = await measureCandidate(runId, runDir, state, candidate, options, now)\n candidate = measured.candidate\n const evaluation = measured.evaluation\n lifecycle = measured.lifecycle\n\n if (evaluation.passed) {\n candidate.status = 'candidate-ready'\n candidate.updatedAt = now().toISOString()\n state.status = 'candidate-ready'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, {\n type: 'candidate.ready',\n runId,\n candidateId: candidate.candidateId,\n })\n break\n }\n\n candidate.status = 'rejected'\n state.status = 'running'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n await appendLedger(runDir, {\n type: 'candidate.rejected',\n runId,\n candidateId: candidate.candidateId,\n })\n lastRejectedCandidate = candidate\n lastRejectedEvaluation = evaluation\n candidate = undefined\n }\n\n if (!candidate) {\n state.status = 'rejected'\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, options.onState)\n return {\n runId,\n state,\n candidate: lastRejectedCandidate,\n ...(lastRejectedEvaluation ? { evaluation: lastRejectedEvaluation } : {}),\n lifecycle,\n promoted: false,\n blocked: false,\n }\n }\n\n const evidence = await assertCandidateEvidence(runDir, candidateRefFor(runId, state, candidate))\n return {\n runId,\n state,\n candidate,\n evaluation: evidence.evaluation,\n lifecycle,\n promoted: false,\n blocked: false,\n }\n } finally {\n await lease.release()\n }\n}\n\ninterface KnowledgeCandidateTransitionInput {\n root: string\n runDir: string\n state: KnowledgeImprovementRunState\n candidateRef: KnowledgeImprovementCandidateRef\n activation?: ResolvedKnowledgeImprovementActivationPersistence\n leaseTtlMs: number\n assertRunOwned(): void\n now: () => Date\n onState?: KnowledgeImprovementOptions['onState']\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n}\n\ninterface ResolvedKnowledgeImprovementActivationPersistence\n extends KnowledgeImprovementActivationPersistence {\n activation: AgentImprovementActivation\n}\n\nasync function applyKnowledgeCandidateTarget(\n input: KnowledgeCandidateTransitionInput,\n target: KnowledgeImprovementTarget,\n): Promise<KnowledgeImprovementMutationResult> {\n const { candidateRef, runDir, state } = input\n assertStateIdentity(input.root, candidateRef, state)\n const candidate = state.candidates.find((entry) => entry.candidateId === candidateRef.candidateId)\n if (\n !candidate ||\n canonicalJson(candidateIdentityFor(candidateRef.runId, state, candidate)) !==\n canonicalJson(candidateRef)\n ) {\n throw new Error('knowledge candidate approval does not match the measured candidate')\n }\n\n const action = target === 'candidate' ? 'promotion' : 'restore'\n const desiredHash = target === 'candidate' ? candidateRef.candidateHash : candidateRef.baseHash\n const purpose = knowledgeCandidateTransitionPurpose(candidateRef, target)\n const recoveryOwner = input.activation\n ? `knowledge-improvement-activation:${input.activation.activation.digest}`\n : 'knowledge-improvement-candidate-transition'\n return withKnowledgeMutation(\n input.root,\n async (mutationLock) => {\n const assertOwned = () => {\n mutationLock.assertOwned()\n input.assertRunOwned()\n }\n assertOwned()\n const transactionRoot = mutationLock.transactionRoot\n const recovery =\n mutationLock.recovery?.purpose === purpose ? mutationLock.recovery : undefined\n const existingActivation = input.activation\n ? await loadKnowledgeActivationRecord(\n runDir,\n candidateRef,\n input.activation.activation,\n target,\n input.activation.identity,\n )\n : null\n if (existingActivation) {\n if (recovery?.direction === 'rollback') {\n throw new Error('stored knowledge activation result conflicts with a pending rollback')\n }\n if (recovery) {\n const recoveredHash = await hashKnowledgeBase(input.root)\n if (recoveredHash !== existingActivation.mutation.afterHash) {\n throw new Error('stored knowledge activation result does not match the recovered files')\n }\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: recovery.transaction,\n assertOwned,\n })\n }\n if (existingActivation.result.outcome.status === 'conflict') {\n const reason = candidateTransitionConflictReason(\n target,\n candidateRef,\n existingActivation.mutation.afterHash,\n )\n const blocked = await blockCandidateTransition(\n input,\n candidate,\n target,\n reason,\n existingActivation.mutation.afterHash,\n )\n return { ...blocked, activationResult: existingActivation.result }\n }\n return candidateTransitionResult(\n input,\n candidate,\n target === 'candidate' && state.status === 'promoted',\n false,\n existingActivation.mutation,\n existingActivation.result,\n )\n }\n if (recovery?.direction === 'rollback') {\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: recovery.transaction,\n assertOwned,\n })\n }\n const recovered = recovery?.direction === 'apply' ? recovery : undefined\n let pending: KnowledgeFileTransaction | null =\n input.activation && recovered ? recovered.transaction : null\n const currentHash = await hashKnowledgeBase(input.root)\n let transactionId = recovered?.transactionId ?? null\n if (recovered && currentHash !== desiredHash) {\n throw new Error(`recovered knowledge ${action} does not match the approved target`)\n }\n if (state.status === 'promoted' && state.promotedCandidateId !== candidate.candidateId) {\n throw new Error(\n `knowledge run already promoted '${state.promotedCandidateId ?? 'unknown'}'`,\n )\n }\n if (\n target === 'candidate' &&\n state.status === 'promoted' &&\n currentHash !== candidateRef.candidateHash\n ) {\n throw new Error(\n `promoted knowledge base changed: expected ${candidateRef.candidateHash}, got ${currentHash}`,\n )\n }\n if (state.status !== 'promoted' && state.status !== 'candidate-ready') {\n throw new Error(\n `knowledge candidate is not ready for ${action}: run=${state.status}, candidate=${candidate.status}`,\n )\n }\n if (currentHash !== state.baseHash && currentHash !== candidateRef.candidateHash) {\n const reason =\n target === 'candidate'\n ? `base changed before promotion: expected ${state.baseHash}, got ${currentHash}`\n : `knowledge changed before restore: expected ${candidateRef.candidateHash}, got ${currentHash}`\n const mutation = Object.freeze({\n target,\n beforeHash: currentHash,\n afterHash: currentHash,\n changed: false,\n transactionId: null,\n recovered: false,\n }) satisfies KnowledgeImprovementMutationReceipt\n const activationResult = input.activation\n ? await persistKnowledgeActivationResult(\n runDir,\n candidateRef,\n input.activation,\n target,\n mutation,\n )\n : undefined\n const blocked = await blockCandidateTransition(\n input,\n candidate,\n target,\n reason,\n currentHash,\n )\n return activationResult ? { ...blocked, activationResult } : blocked\n }\n\n if (currentHash !== desiredHash && !pending) {\n pending = await withMeasuredCandidateSnapshot(\n input.root,\n runDir,\n state,\n candidateRef,\n (resolved) =>\n withBaselineSnapshot(runDir, state.baseHash, async (baselineRoot) => {\n const sourceRoot = target === 'candidate' ? baselineRoot : resolved.root\n const targetRoot = target === 'candidate' ? resolved.root : baselineRoot\n const plan = await knowledgeFilePlanEntries(sourceRoot, targetRoot)\n assertCandidateTransitionPlan(plan, candidateRef, target)\n return prepareKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n purpose,\n recoveryOwner,\n mutations: await knowledgePlanMutations(targetRoot, plan),\n includeUnchanged: true,\n now: input.now,\n })\n }),\n )\n if (!pending) {\n throw new Error(`knowledge ${action} plan unexpectedly contained no file changes`)\n }\n transactionId = pending.transactionId\n try {\n assertCandidateTransitionTransaction(pending, candidateRef, target)\n } catch (error) {\n try {\n await rollbackKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n beforeCommit: assertOwned,\n })\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n assertOwned,\n })\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n `invalid knowledge ${action} transaction could not be removed`,\n )\n }\n throw error\n }\n }\n try {\n if (pending) {\n await applyKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n beforeCommit: assertOwned,\n })\n }\n assertOwned()\n if ((await hashKnowledgeBase(input.root)) !== desiredHash) {\n throw new Error(`knowledge ${action} content does not match the approved target`)\n }\n await writeKnowledgeIndex(input.root)\n } catch (error) {\n if (!pending) throw error\n if (recovered && input.activation) throw error\n try {\n assertOwned()\n } catch (ownershipError) {\n throw new AggregateError(\n [error, ownershipError],\n `knowledge ${action} lost its lock and left the transaction pending`,\n )\n }\n try {\n await rollbackKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n beforeCommit: assertOwned,\n })\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n assertOwned,\n })\n await writeKnowledgeIndex(input.root)\n } catch (rollbackError) {\n throw new AggregateError(\n [error, rollbackError],\n `knowledge ${action} failed and could not restore the previous files`,\n )\n }\n throw error\n }\n candidate.status = target === 'candidate' ? 'promoted' : 'candidate-ready'\n candidate.updatedAt = input.now().toISOString()\n state.status = candidate.status\n if (target === 'candidate') state.promotedCandidateId = candidate.candidateId\n else delete state.promotedCandidateId\n delete state.blockedReason\n state.updatedAt = input.now().toISOString()\n await saveState(runDir, state, input.onState)\n await ensureCandidateTransitionEvent(runDir, candidateRef, target)\n let finalHash = await hashKnowledgeBase(input.root)\n if (finalHash !== desiredHash) {\n throw new Error(`knowledge ${action} changed before its result was returned`)\n }\n const mutation = Object.freeze({\n target,\n beforeHash: transactionId ? sourceKnowledgeHash(candidateRef, target) : currentHash,\n afterHash: finalHash,\n changed: transactionId !== null,\n transactionId,\n recovered: recovered !== undefined,\n }) satisfies KnowledgeImprovementMutationReceipt\n const activationResult = input.activation\n ? await persistKnowledgeActivationResult(\n runDir,\n candidateRef,\n input.activation,\n target,\n mutation,\n )\n : undefined\n if ((await hashKnowledgeBase(input.root)) !== finalHash) {\n throw new Error(`knowledge ${action} changed while its result was persisted`)\n }\n if (pending) {\n await finishKnowledgeFileTransaction({\n root: input.root,\n transactionRoot,\n transaction: pending,\n assertOwned,\n })\n }\n finalHash = await hashKnowledgeBase(input.root)\n if (finalHash !== desiredHash) {\n throw new Error(`knowledge ${action} changed before its result was returned`)\n }\n return candidateTransitionResult(\n input,\n candidate,\n target === 'candidate',\n false,\n mutation,\n activationResult,\n )\n },\n {\n staleMs: input.leaseTtlMs,\n resumeTransaction: {\n purpose,\n recoveryOwner,\n validate: (transaction) =>\n assertCandidateTransitionTransaction(transaction, candidateRef, target),\n deferFinish: input.activation !== undefined,\n },\n },\n )\n}\n\nfunction candidateTransitionConflictReason(\n target: KnowledgeImprovementTarget,\n candidate: KnowledgeImprovementCandidateRef,\n currentHash: string,\n): string {\n return target === 'candidate'\n ? `base changed before promotion: expected ${candidate.baseHash}, got ${currentHash}`\n : `knowledge changed before restore: expected ${candidate.candidateHash}, got ${currentHash}`\n}\n\nasync function blockCandidateTransition(\n input: KnowledgeCandidateTransitionInput,\n candidate: KnowledgeImprovementCandidateRecord,\n target: KnowledgeImprovementTarget,\n reason: string,\n currentHash: string,\n): Promise<KnowledgeImprovementMutationResult> {\n if (input.state.status === 'promoted') {\n candidate.status = 'blocked'\n candidate.updatedAt = input.now().toISOString()\n delete input.state.promotedCandidateId\n }\n await blockRun(input.runDir, input.state, reason, input.onState, input.now)\n await appendLedger(input.runDir, {\n type: target === 'candidate' ? 'promotion.blocked' : 'restore.blocked',\n runId: input.candidateRef.runId,\n candidateId: candidate.candidateId,\n reason,\n })\n return candidateTransitionResult(input, candidate, false, true, {\n target,\n beforeHash: currentHash,\n afterHash: currentHash,\n changed: false,\n transactionId: null,\n recovered: false,\n })\n}\n\nfunction candidateTransitionResult(\n input: KnowledgeCandidateTransitionInput,\n candidate: KnowledgeImprovementCandidateRecord,\n promoted: boolean,\n blocked: boolean,\n mutation: KnowledgeImprovementMutationReceipt,\n activationResult?: AgentImprovementActivationResult,\n): KnowledgeImprovementMutationResult {\n return {\n runId: input.candidateRef.runId,\n state: input.state,\n candidate,\n ...(input.lifecycle ? { lifecycle: input.lifecycle } : {}),\n mutation,\n ...(activationResult ? { activationResult } : {}),\n promoted,\n blocked,\n }\n}\n\nfunction sourceKnowledgeHash(\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): string {\n return target === 'candidate' ? candidate.baseHash : candidate.candidateHash\n}\n\nfunction targetForKnowledgeActivation(\n activation: AgentImprovementActivation,\n): KnowledgeImprovementTarget {\n return activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n}\n\nfunction resolveKnowledgeActivationPersistence(\n input: KnowledgeImprovementActivationPersistence,\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): ResolvedKnowledgeImprovementActivationPersistence {\n const activation = verifyCanonicalKnowledgeActivation(input.activation)\n assertKnowledgeActivationAuthority(activation, candidate, target, input.identity)\n const attemptedAt = z.iso.datetime().parse(input.attemptedAt)\n if (\n Date.parse(attemptedAt) < Date.parse(activation.authorizedAt) ||\n Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n ) {\n throw new Error('knowledge activation attempt is outside its authorization window')\n }\n return Object.freeze({\n activation,\n attemptedAt,\n identity: input.identity,\n createResult: input.createResult,\n })\n}\n\nfunction assertKnowledgeActivationAuthority(\n activation: AgentImprovementActivation,\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n identity: string,\n): void {\n if (!identity.trim()) throw new Error('knowledge activation identity is required')\n if (targetForKnowledgeActivation(activation) !== target) {\n throw new Error('knowledge activation intent does not match the requested transition')\n }\n if (activation.targets.length !== 1) {\n throw new Error('knowledge activation requires exactly one target')\n }\n const authorizedTarget = activation.targets[0]\n if (authorizedTarget.surface !== 'knowledge' || authorizedTarget.identity !== identity) {\n throw new Error('knowledge activation target does not match this knowledge base')\n }\n if (\n authorizedTarget.expectedBaseDigest !==\n prefixedKnowledgeDigest(sourceKnowledgeHash(candidate, target))\n ) {\n throw new Error('knowledge activation does not authorize the measured source state')\n }\n}\n\nfunction verifyCanonicalKnowledgeActivation(\n value: AgentImprovementActivation,\n): AgentImprovementActivation {\n const activation = agentImprovementActivationSchema.parse(value)\n if (canonicalCandidateDigest(omitTopLevelDigest(activation)) !== activation.digest) {\n throw new Error('knowledge activation digest does not match its canonical content')\n }\n return immutableJsonValue(structuredClone(activation))\n}\n\nfunction verifyCanonicalKnowledgeActivationResult(\n value: AgentImprovementActivationResult,\n): AgentImprovementActivationResult {\n const result = agentImprovementActivationResultSchema.parse(value)\n if (canonicalCandidateDigest(omitTopLevelDigest(result)) !== result.digest) {\n throw new Error('knowledge activation result digest does not match its canonical content')\n }\n return immutableJsonValue(structuredClone(result))\n}\n\nasync function persistKnowledgeActivationResult(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRef,\n persistence: ResolvedKnowledgeImprovementActivationPersistence,\n target: KnowledgeImprovementTarget,\n mutation: KnowledgeImprovementMutationReceipt,\n): Promise<AgentImprovementActivationResult> {\n const result = assertKnowledgeActivationResult(\n persistence.activation,\n candidate,\n target,\n persistence.identity,\n mutation,\n await persistence.createResult(Object.freeze({ ...mutation })),\n persistence.attemptedAt,\n )\n const record = knowledgeImprovementActivationRecordSchema.parse({\n kind: 'knowledge-improvement-activation-result',\n candidateId: candidate.candidateId,\n mutation,\n result,\n })\n const existing = await loadKnowledgeActivationRecord(\n runDir,\n candidate,\n persistence.activation,\n target,\n persistence.identity,\n )\n if (existing) {\n if (canonicalJson(existing) !== canonicalJson(record)) {\n throw new Error('knowledge activation result identity conflicts with durable content')\n }\n return existing.result\n }\n await writeJsonDurableWithinRoot(\n runDir,\n knowledgeActivationResultPath(persistence.activation.digest),\n record,\n )\n const stored = await loadKnowledgeActivationRecord(\n runDir,\n candidate,\n persistence.activation,\n target,\n persistence.identity,\n )\n if (!stored || canonicalJson(stored) !== canonicalJson(record)) {\n throw new Error('knowledge activation result was not durably persisted')\n }\n return stored.result\n}\n\nasync function loadKnowledgeActivationRecord(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRef,\n activation: AgentImprovementActivation,\n target: KnowledgeImprovementTarget,\n identity: string,\n): Promise<KnowledgeImprovementActivationRecord | null> {\n let raw: unknown\n try {\n const file = await readRegularFileWithinRoot(\n runDir,\n knowledgeActivationResultPath(activation.digest),\n )\n raw = JSON.parse(file.bytes.toString('utf8')) as unknown\n } catch (error) {\n if (isMissingFile(error)) return null\n throw error\n }\n const record = knowledgeImprovementActivationRecordSchema.parse(raw)\n if (record.candidateId !== candidate.candidateId) {\n throw new Error('knowledge activation result belongs to another candidate')\n }\n const result = assertKnowledgeActivationResult(\n activation,\n candidate,\n target,\n identity,\n record.mutation,\n record.result,\n )\n return immutableJsonValue({ ...record, result })\n}\n\nfunction assertKnowledgeActivationResult(\n activation: AgentImprovementActivation,\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n identity: string,\n mutationInput: KnowledgeImprovementMutationReceipt,\n resultInput: AgentImprovementActivationResult,\n attemptedAt?: string,\n): AgentImprovementActivationResult {\n assertKnowledgeActivationAuthority(activation, candidate, target, identity)\n const mutation = knowledgeImprovementMutationReceiptSchema.parse(mutationInput)\n const result = verifyCanonicalKnowledgeActivationResult(resultInput)\n if (\n result.idempotencyKey !== activation.digest ||\n (attemptedAt !== undefined && result.attemptedAt !== attemptedAt) ||\n Date.parse(result.attemptedAt) < Date.parse(activation.authorizedAt) ||\n Date.parse(result.attemptedAt) >= Date.parse(activation.expiresAt) ||\n mutation.target !== target ||\n mutation.changed !== (mutation.beforeHash !== mutation.afterHash) ||\n (!mutation.changed && (mutation.transactionId !== null || mutation.recovered))\n ) {\n throw new Error('knowledge activation result does not bind its authorized mutation')\n }\n\n const sourceDigest = prefixedKnowledgeDigest(sourceKnowledgeHash(candidate, target))\n const desiredDigest = prefixedKnowledgeDigest(\n target === 'candidate' ? candidate.candidateHash : candidate.baseHash,\n )\n const beforeDigest = prefixedKnowledgeDigest(mutation.beforeHash)\n const afterDigest = prefixedKnowledgeDigest(mutation.afterHash)\n const outcome = result.outcome\n if (mutation.changed) {\n if (\n mutation.transactionId === null ||\n beforeDigest !== sourceDigest ||\n afterDigest !== desiredDigest ||\n outcome.status !== 'applied' ||\n outcome.transactionId !== mutation.transactionId ||\n outcome.targets.length !== 1 ||\n outcome.targets[0]?.surface !== 'knowledge' ||\n outcome.targets[0]?.identity !== identity ||\n outcome.targets[0]?.beforeDigest !== beforeDigest ||\n outcome.targets[0]?.afterDigest !== afterDigest\n ) {\n throw new Error('knowledge activation result does not prove the applied transaction')\n }\n return result\n }\n\n const expectedStatus = afterDigest === desiredDigest ? 'already-applied' : 'conflict'\n if (\n afterDigest === sourceDigest ||\n outcome.status !== expectedStatus ||\n outcome.targets.length !== 1 ||\n outcome.targets[0]?.surface !== 'knowledge' ||\n outcome.targets[0]?.identity !== identity ||\n outcome.targets[0]?.currentDigest !== afterDigest\n ) {\n throw new Error('knowledge activation result does not prove the observed target state')\n }\n return result\n}\n\nfunction knowledgeActivationResultPath(digest: Sha256Digest): string {\n const parsed = sha256DigestSchema.parse(digest)\n return `activation-results/${parsed.slice('sha256:'.length)}.json`\n}\n\nfunction prefixedKnowledgeDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${digestSchema.parse(hash)}`)\n}\n\nfunction immutableJsonValue<T>(value: T): T {\n if (value === null || typeof value !== 'object') return value\n for (const child of Object.values(value)) immutableJsonValue(child)\n return Object.freeze(value)\n}\n\nfunction candidateRefFor(\n runId: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n): KnowledgeImprovementCandidateRef {\n if (candidate.status !== 'candidate-ready' && candidate.status !== 'promoted') {\n throw new Error(`knowledge candidate '${candidate.candidateId}' is not ready`)\n }\n return candidateIdentityFor(runId, state, candidate)\n}\n\nfunction candidateIdentityFor(\n runId: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n): KnowledgeImprovementCandidateRef {\n if (!candidate.candidateHash) {\n throw new Error(`knowledge candidate '${candidate.candidateId}' has no content hash`)\n }\n if (!candidate.evidenceHash) {\n throw new Error(`knowledge candidate '${candidate.candidateId}' has no evidence hash`)\n }\n if (!candidate.promotionPlanHash) {\n throw new Error(`knowledge candidate '${candidate.candidateId}' has no promotion plan hash`)\n }\n return Object.freeze({\n kind: 'knowledge-improvement-candidate',\n runId,\n candidateId: candidate.candidateId,\n goalHash: sha256(state.goal),\n baseHash: candidate.baseHash,\n candidateHash: candidate.candidateHash,\n evidenceHash: candidate.evidenceHash,\n promotionPlanHash: candidate.promotionPlanHash,\n })\n}\n\nasync function withMeasuredCandidateSnapshot<T>(\n liveRoot: string,\n runDir: string,\n state: KnowledgeImprovementRunState,\n candidateRef: KnowledgeImprovementCandidateRef,\n use: (snapshot: {\n root: string\n candidate: KnowledgeImprovementCandidateRecord\n evidence: KnowledgeImprovementEvidence\n }) => Promise<T> | T,\n): Promise<T> {\n assertStateIdentity(liveRoot, candidateRef, state)\n const candidate = state.candidates.find((entry) => entry.candidateId === candidateRef.candidateId)\n if (!candidate) {\n throw new Error(`knowledge candidate '${candidateRef.candidateId}' does not exist`)\n }\n const expectedRef = candidateRefFor(candidateRef.runId, state, candidate)\n if (canonicalJson(expectedRef) !== canonicalJson(candidateRef)) {\n throw new Error('knowledge candidate approval does not match the measured candidate')\n }\n const evidence = await assertCandidateEvidence(runDir, candidateRef)\n const relativePath = join(\n 'candidates',\n candidate.candidateId,\n 'snapshots',\n candidateRef.candidateHash,\n )\n return withSafeDirectory(runDir, relativePath, false, async (root) => {\n if ((await hashKnowledgeBase(root)) !== candidateRef.candidateHash) {\n throw new Error('knowledge candidate snapshot changed after approval')\n }\n const result = await use({ root, candidate, evidence })\n if ((await hashKnowledgeBase(root)) !== candidateRef.candidateHash) {\n throw new Error('knowledge candidate snapshot changed during use')\n }\n return result\n })\n}\n\nasync function withIsolatedKnowledgeCopy<T>(\n sourceRoot: string,\n expectedHash: string,\n target: KnowledgeImprovementTarget,\n use: (root: string) => Promise<T> | T,\n): Promise<T> {\n const isolationRoot = await mkdtemp(join(tmpdir(), 'agent-knowledge-snapshot-'))\n const snapshotRoot = join(isolationRoot, 'snapshot')\n try {\n await copyKnowledgeWorkspace(sourceRoot, snapshotRoot)\n if ((await hashKnowledgeBase(snapshotRoot)) !== expectedHash) {\n throw new Error(`isolated knowledge ${target} does not match its measured content`)\n }\n const result = await use(snapshotRoot)\n if ((await hashKnowledgeBase(snapshotRoot)) !== expectedHash) {\n throw new Error(`knowledge ${target} snapshot changed during use`)\n }\n return result\n } finally {\n await rm(isolationRoot, { recursive: true, force: true })\n }\n}\n\nasync function assertCandidateEvidence(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRef,\n): Promise<KnowledgeImprovementEvidence> {\n const evidence = KnowledgeImprovementEvidenceSchema.parse(\n JSON.parse(\n (\n await readRegularFileWithinRoot(\n runDir,\n candidateEvidenceRelativePath(candidate.candidateId),\n )\n ).bytes.toString('utf8'),\n ),\n )\n const actualHash = contentHash(evidence)\n if (actualHash !== candidate.evidenceHash) {\n throw new Error(\n `knowledge candidate evidence changed after approval: expected ${candidate.evidenceHash}, got ${actualHash}`,\n )\n }\n if (\n evidence.runId !== candidate.runId ||\n evidence.candidateId !== candidate.candidateId ||\n evidence.goalHash !== candidate.goalHash ||\n evidence.baseHash !== candidate.baseHash ||\n evidence.candidateHash !== candidate.candidateHash ||\n evidence.promotionPlanHash !== candidate.promotionPlanHash ||\n evidence.evaluation.passed !== true\n ) {\n throw new Error('knowledge candidate evidence does not match the approved candidate')\n }\n return evidence\n}\n\nfunction assertStateIdentity(\n root: string,\n candidateRef: KnowledgeImprovementCandidateRef,\n state: KnowledgeImprovementRunState,\n): void {\n if (state.runId !== candidateRef.runId) {\n throw new Error('knowledge candidate run identity does not match persisted state')\n }\n if (resolve(state.root) !== resolve(root)) {\n throw new Error('knowledge candidate root does not match persisted state')\n }\n if (sha256(state.goal) !== candidateRef.goalHash) {\n throw new Error('knowledge candidate goal does not match persisted state')\n }\n if (state.baseHash !== candidateRef.baseHash) {\n throw new Error('knowledge candidate base does not match persisted state')\n }\n}\n\nasync function assertCandidateWorkspace(\n runDir: string,\n candidate: Pick<KnowledgeImprovementCandidateRecord, 'candidateId'>,\n): Promise<void> {\n await withCandidateWorkspace(runDir, candidate, () => undefined)\n}\n\nasync function withCandidateWorkspace<T>(\n runDir: string,\n candidate: Pick<KnowledgeImprovementCandidateRecord, 'candidateId'>,\n use: (candidateRoot: string) => Promise<T> | T,\n): Promise<T> {\n return withSafeDirectory(\n runDir,\n join('candidates', safePathSegmentSchema.parse(candidate.candidateId), 'workspace'),\n false,\n use,\n )\n}\n\nfunction assertKnowledgeImprovementOptions(options: KnowledgeImprovementOptions): void {\n if (options.step && options.knowledgeResearch?.step) {\n throw new Error('improveKnowledgeBase accepts either step or knowledgeResearch.step, not both')\n }\n const updateDrivers = [\n Boolean(options.step ?? options.knowledgeResearch),\n Boolean(options.updateKnowledge),\n ].filter(Boolean).length\n if (updateDrivers > 1) {\n throw new Error(\n 'improveKnowledgeBase accepts only one knowledge-update driver: knowledgeResearch or updateKnowledge',\n )\n }\n}\n\nasync function measureCandidate(\n runId: string,\n runDir: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<{\n candidate: KnowledgeImprovementCandidateRecord\n evaluation: KnowledgeImprovementMetric\n lifecycle?: RunRagKnowledgeImprovementLoopResult\n}> {\n return withCandidateWorkspace(runDir, candidate, async (candidateRoot) => {\n const currentCandidateHash = await hashKnowledgeBase(candidateRoot)\n if (\n candidate.status === 'candidate-ready' &&\n candidate.candidateHash === currentCandidateHash &&\n candidate.evidenceHash !== undefined &&\n candidate.promotionPlanHash !== undefined\n ) {\n const evidence = await assertCandidateEvidence(\n runDir,\n candidateRefFor(runId, state, candidate),\n )\n return { candidate, evaluation: evidence.evaluation }\n }\n\n clearCandidateMeasurement(candidate)\n const lifecycles: RunRagKnowledgeImprovementLoopResult[] = []\n if (candidate.status === 'running') {\n const updateLifecycle = await runCandidateUpdateLifecycle(\n runId,\n candidate,\n candidateRoot,\n options,\n now,\n )\n if (updateLifecycle) lifecycles.push(updateLifecycle)\n }\n return withFrozenCandidateWorkspace(runDir, candidate, candidateRoot, async (snapshot) => {\n const evaluationLifecycle = await runCandidateEvaluationLifecycle(\n runDir,\n candidate,\n snapshot.root,\n options,\n now,\n )\n if (evaluationLifecycle) lifecycles.push(evaluationLifecycle)\n const lifecycle = mergeLifecycleResults(options.goal, lifecycles)\n const measured = await evaluateCandidate(\n runDir,\n state,\n candidate,\n snapshot,\n lifecycle,\n options,\n now,\n )\n return { ...measured, ...(lifecycle ? { lifecycle } : {}) }\n })\n })\n}\n\nasync function runCandidateUpdateLifecycle(\n runId: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<RunRagKnowledgeImprovementLoopResult | undefined> {\n if (!shouldRunUpdateStage(options)) return undefined\n const lifecycle = await runRagKnowledgeImprovementLoop({\n goal: options.goal,\n acquireKnowledge: options.acquireKnowledge,\n knowledgeResearch: candidateKnowledgeResearchOptions(candidateRoot, options),\n updateKnowledge: candidateUpdateHook(runId, candidate, candidateRoot, options),\n enabledPhases: selectedStagePhases(options, UPDATE_PHASES),\n requiredPhases: selectedStageRequiredPhases(options, UPDATE_PHASES),\n signal: options.signal,\n now,\n })\n return lifecycle\n}\n\nasync function runCandidateEvaluationLifecycle(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<RunRagKnowledgeImprovementLoopResult | undefined> {\n if (!shouldRunEvaluationStage(options)) return undefined\n const candidateIndex = await buildKnowledgeIndex(candidateRoot)\n const lifecycle = await runRagKnowledgeImprovementLoop({\n goal: options.goal,\n retrieval: options.retrieval\n ? {\n ...options.retrieval,\n index: candidateIndex,\n runDir: options.retrieval.runDir ?? join(runDir, 'retrieval', candidate.candidateId),\n }\n : undefined,\n diagnose: options.diagnose,\n evaluateAnswers: options.evaluateAnswers,\n promote: options.decidePromotion,\n enabledPhases: selectedStagePhases(options, EVALUATION_PHASES),\n requiredPhases: selectedStageRequiredPhases(options, EVALUATION_PHASES),\n signal: options.signal,\n now,\n })\n return lifecycle\n}\n\nfunction candidateKnowledgeResearchOptions(\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n): RagKnowledgeResearchOptions | undefined {\n if (!options.step && !options.knowledgeResearch) return undefined\n const { step: researchStep, ...rest } = options.knowledgeResearch ?? {}\n const step = options.step ?? researchStep\n return {\n ...rest,\n root: candidateRoot,\n step,\n maxIterations:\n rest.maxIterations ?? (step ? (options.candidateResearchIterations ?? 3) : undefined),\n strict: rest.strict ?? options.strict,\n readinessSpecs: rest.readinessSpecs ?? options.readinessSpecs,\n readinessTaskId: rest.readinessTaskId ?? options.readinessTaskId,\n readiness: rest.readiness ?? options.readiness,\n }\n}\n\nfunction candidateUpdateHook(\n runId: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n options: KnowledgeImprovementOptions,\n): RunRagKnowledgeImprovementLoopOptions['updateKnowledge'] {\n if (!options.updateKnowledge) return undefined\n return (input) =>\n options.updateKnowledge!({\n ...input,\n runId,\n iteration: candidate.iteration,\n candidateId: candidate.candidateId,\n root: candidateRoot,\n baselineRoot: options.root,\n candidateRoot,\n baseHash: candidate.baseHash,\n })\n}\n\nfunction shouldRunUpdateStage(options: KnowledgeImprovementOptions): boolean {\n const phases = selectedStagePhases(options, UPDATE_PHASES)\n if (phases.length === 0) return false\n return Boolean(\n options.acquireKnowledge ||\n options.step ||\n options.knowledgeResearch ||\n options.updateKnowledge ||\n selectedStageRequiredPhases(options, UPDATE_PHASES).length > 0,\n )\n}\n\nfunction shouldRunEvaluationStage(options: KnowledgeImprovementOptions): boolean {\n const phases = selectedStagePhases(options, EVALUATION_PHASES)\n if (phases.length === 0) return false\n return Boolean(\n options.retrieval ||\n options.diagnose ||\n options.evaluateAnswers ||\n options.decidePromotion ||\n selectedStageRequiredPhases(options, EVALUATION_PHASES).length > 0,\n )\n}\n\nfunction selectedStagePhases(\n options: Pick<KnowledgeImprovementOptions, 'enabledPhases'>,\n stagePhases: readonly RagKnowledgeImprovementPhase[],\n): RagKnowledgeImprovementPhase[] {\n const requested = options.enabledPhases ?? stagePhases\n return requested.filter((phase) => stagePhases.includes(phase))\n}\n\nfunction selectedStageRequiredPhases(\n options: Pick<KnowledgeImprovementOptions, 'requiredPhases'>,\n stagePhases: readonly RagKnowledgeImprovementPhase[],\n): RagKnowledgeImprovementPhase[] {\n return (options.requiredPhases ?? []).filter((phase) => stagePhases.includes(phase))\n}\n\nfunction mergeLifecycleResults(\n goal: string,\n lifecycles: readonly RunRagKnowledgeImprovementLoopResult[],\n): RunRagKnowledgeImprovementLoopResult | undefined {\n if (lifecycles.length === 0) return undefined\n return {\n goal,\n phases: lifecycles.flatMap((lifecycle) => lifecycle.phases),\n retrieval: lastDefined(lifecycles.map((lifecycle) => lifecycle.retrieval)),\n findings: lifecycles.flatMap((lifecycle) => lifecycle.findings),\n acquisition: lastDefined(lifecycles.map((lifecycle) => lifecycle.acquisition)),\n knowledgeUpdate: lastDefined(lifecycles.map((lifecycle) => lifecycle.knowledgeUpdate)),\n answerQuality: lastDefined(lifecycles.map((lifecycle) => lifecycle.answerQuality)),\n promotion: lastDefined(lifecycles.map((lifecycle) => lifecycle.promotion)),\n }\n}\n\nfunction lastDefined<T>(values: readonly (T | undefined)[]): T | undefined {\n for (let index = values.length - 1; index >= 0; index -= 1) {\n if (values[index] !== undefined) return values[index]\n }\n return undefined\n}\n\nasync function evaluateCandidate(\n runDir: string,\n state: KnowledgeImprovementRunState,\n candidate: KnowledgeImprovementCandidateRecord,\n snapshot: { root: string; hash: string },\n lifecycle: RunRagKnowledgeImprovementLoopResult | undefined,\n options: KnowledgeImprovementOptions,\n now: () => Date,\n): Promise<{\n candidate: KnowledgeImprovementCandidateRecord\n evaluation: KnowledgeImprovementMetric\n}> {\n return withBaselineSnapshot(runDir, state.baseHash, async (baselineRoot) => {\n const [baselineIndex, candidateIndex] = await Promise.all([\n buildKnowledgeIndex(baselineRoot),\n buildKnowledgeIndex(snapshot.root),\n ])\n const validation = validateKnowledgeIndex(candidateIndex, { strict: options.strict })\n const readiness = readinessFor(options, candidateIndex)\n const kbQuality = scoreKnowledgeBaseIndex(candidateIndex, {\n strict: options.strict,\n ...options.kbQuality,\n })\n const candidateHash = snapshot.hash\n const metric =\n options.evaluate?.({\n runId: state.runId,\n iteration: candidate.iteration,\n root: options.root,\n baselineRoot,\n candidateRoot: snapshot.root,\n baselineIndex,\n candidateIndex,\n baseHash: state.baseHash,\n candidateHash,\n validation,\n readiness,\n kbQuality,\n lifecycle,\n signal: options.signal,\n }) ??\n defaultKnowledgeImprovementMetric(\n validation,\n readiness,\n options.readinessSpecs,\n kbQuality,\n lifecycle,\n )\n const evaluation = applyLifecycleFailures(normalizeMetric(await metric), lifecycle)\n const measuredHash = await hashKnowledgeBase(snapshot.root)\n if (measuredHash !== candidateHash) {\n throw new Error(\n `knowledge candidate changed during evaluation: expected ${candidateHash}, got ${measuredHash}`,\n )\n }\n candidate.candidateHash = candidateHash\n candidate.promotionPlanHash = knowledgeFileTransactionPlanHash(\n await knowledgeFilePlanEntries(baselineRoot, snapshot.root),\n )\n const evidence = KnowledgeImprovementEvidenceSchema.parse(\n JSON.parse(\n JSON.stringify({\n kind: 'knowledge-improvement-evidence',\n runId: state.runId,\n candidateId: candidate.candidateId,\n iteration: candidate.iteration,\n goalHash: sha256(state.goal),\n baseHash: candidate.baseHash,\n candidateHash,\n promotionPlanHash: candidate.promotionPlanHash,\n validation,\n readiness: readiness ?? null,\n kbQuality,\n evaluation,\n lifecycle: lifecycle ?? null,\n }),\n ),\n )\n candidate.evidenceHash = contentHash(evidence)\n candidate.updatedAt = now().toISOString()\n await writeJsonDurableWithinRoot(\n runDir,\n candidateEvidenceRelativePath(candidate.candidateId),\n evidence,\n )\n await appendLedger(runDir, {\n type: 'candidate.evaluated',\n runId: state.runId,\n candidateId: candidate.candidateId,\n score: evaluation.score,\n passed: evaluation.passed,\n })\n return { candidate, evaluation }\n })\n}\n\nfunction defaultKnowledgeImprovementMetric(\n validation: ValidateKnowledgeResult,\n readiness: EvalKnowledgeBundleBuildResult | undefined,\n readinessSpecs: readonly KnowledgeReadinessSpec[] | undefined,\n kbQuality: KnowledgeBaseQualityReport,\n lifecycle: RunRagKnowledgeImprovementLoopResult | undefined,\n): KnowledgeImprovementMetric {\n const blockingMissing = readiness?.report.blockingMissingRequirements.length ?? 0\n const blockingTotal = readinessSpecs?.filter((spec) => spec.importance === 'blocking').length ?? 0\n const blockingReadiness =\n blockingTotal === 0 ? 1 : Math.max(0, blockingTotal - blockingMissing) / blockingTotal\n const answerQuality = lifecycle?.answerQuality\n ? average(Object.values(lifecycle.answerQuality.metrics).filter(Number.isFinite))\n : 1\n const promotionDecision = lifecycle?.promotion ? (lifecycle.promotion.promoted ? 1 : 0) : 1\n const dimensions = {\n validation: validation.ok ? 1 : 0,\n kb_quality: kbQuality.ok ? 1 : 0,\n blocking_readiness: blockingReadiness,\n answer_quality: answerQuality,\n promotion_decision: promotionDecision,\n }\n const failedReasons = [\n validation.ok ? undefined : 'candidate validation failed',\n kbQuality.ok ? undefined : 'candidate KB quality check failed',\n blockingMissing === 0\n ? undefined\n : `${blockingMissing}/${blockingTotal} blocking knowledge requirements still missing`,\n ].filter((reason): reason is string => Boolean(reason))\n return {\n score: average(Object.values(dimensions)),\n passed: failedReasons.length === 0,\n dimensions,\n notes:\n failedReasons.length === 0 ? 'candidate passed configured checks' : failedReasons.join('; '),\n provenance: {\n evaluator: '@tangle-network/agent-knowledge/default-knowledge-improvement-metric',\n version: '1',\n method: 'deterministic',\n },\n }\n}\n\nfunction applyLifecycleFailures(\n metric: KnowledgeImprovementMetric,\n lifecycle: RunRagKnowledgeImprovementLoopResult | undefined,\n): KnowledgeImprovementMetric {\n const reasons = [\n metric.notes,\n lifecycle?.answerQuality && !lifecycle.answerQuality.passed\n ? 'answer quality failed'\n : undefined,\n lifecycle?.promotion && !lifecycle.promotion.promoted\n ? `promotion decision held: ${lifecycle.promotion.reason}`\n : undefined,\n ].filter((reason): reason is string => Boolean(reason))\n const forcedFailure =\n Boolean(lifecycle?.answerQuality && !lifecycle.answerQuality.passed) ||\n Boolean(lifecycle?.promotion && !lifecycle.promotion.promoted)\n return {\n ...metric,\n passed: metric.passed && !forcedFailure,\n notes: reasons.length > 0 ? reasons.join('; ') : metric.notes,\n }\n}\n\nfunction normalizeMetric(metric: KnowledgeImprovementMetric): KnowledgeImprovementMetric {\n return improvementMetricSchema.parse(metric)\n}\n\nasync function createCandidateWorkspace(\n runDir: string,\n state: KnowledgeImprovementRunState,\n root: string,\n now: () => Date,\n): Promise<KnowledgeImprovementCandidateRecord> {\n const iteration = state.candidates.length + 1\n const candidateId = stableId('kcand', `${state.runId}:${iteration}:${now().toISOString()}`)\n const candidateRoot = candidateWorkspacePath(runDir, candidateId)\n await copyKnowledgeWorkspace(root, candidateRoot)\n const createdAt = now().toISOString()\n return {\n iteration,\n candidateId,\n baseHash: state.baseHash,\n status: 'running',\n createdAt,\n updatedAt: createdAt,\n }\n}\n\nfunction candidateWorkspacePath(runDir: string, candidateId: string): string {\n return join(runDir, 'candidates', safePathSegmentSchema.parse(candidateId), 'workspace')\n}\n\nfunction baselineSnapshotPath(runDir: string): string {\n return join(runDir, 'baseline')\n}\n\nasync function createBaselineSnapshot(\n runDir: string,\n root: string,\n expectedHash: string,\n): Promise<void> {\n const target = baselineSnapshotPath(runDir)\n try {\n await assertBaselineSnapshot(runDir, expectedHash)\n return\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n const preparation = await mkdtemp(join(runDir, 'baseline-prepare-'))\n let activated = false\n try {\n await copyKnowledgeWorkspace(root, preparation)\n const actualHash = await hashKnowledgeBase(preparation)\n if (actualHash !== expectedHash) {\n throw new Error(\n `knowledge base changed while baseline was frozen: expected ${expectedHash}, got ${actualHash}`,\n )\n }\n await renameDurable(preparation, target)\n activated = true\n } finally {\n if (!activated) await rm(preparation, { recursive: true, force: true })\n }\n}\n\nasync function ensureBaselineSnapshot(\n runDir: string,\n root: string,\n expectedHash: string,\n): Promise<void> {\n try {\n await assertBaselineSnapshot(runDir, expectedHash)\n } catch (error) {\n if (!isMissingFile(error)) throw error\n const liveHash = await hashKnowledgeBase(root)\n if (liveHash !== expectedHash) {\n throw new Error(\n 'knowledge improvement baseline snapshot is missing and cannot be reconstructed',\n )\n }\n await createBaselineSnapshot(runDir, root, expectedHash)\n }\n}\n\nasync function assertBaselineSnapshot(runDir: string, expectedHash: string): Promise<void> {\n await withBaselineSnapshot(runDir, expectedHash, () => undefined)\n}\n\nasync function withBaselineSnapshot<T>(\n runDir: string,\n expectedHash: string,\n use: (baselineRoot: string) => Promise<T> | T,\n): Promise<T> {\n return withSafeDirectory(runDir, 'baseline', false, async (baselineRoot) => {\n const actualHash = await hashKnowledgeBase(baselineRoot)\n if (actualHash !== expectedHash) {\n throw new Error(\n `knowledge improvement baseline changed: expected ${expectedHash}, got ${actualHash}`,\n )\n }\n return use(baselineRoot)\n })\n}\n\nasync function withFrozenCandidateWorkspace<T>(\n runDir: string,\n candidate: KnowledgeImprovementCandidateRecord,\n candidateRoot: string,\n use: (snapshot: { root: string; hash: string }) => Promise<T> | T,\n): Promise<T> {\n const snapshotsPath = join(\n 'candidates',\n safePathSegmentSchema.parse(candidate.candidateId),\n 'snapshots',\n )\n return withSafeDirectory(runDir, snapshotsPath, true, async (snapshotsDir) => {\n const preparation = await mkdtemp(join(snapshotsDir, 'prepare-'))\n let activated = false\n try {\n await copyKnowledgeWorkspace(candidateRoot, preparation)\n const hash = await hashKnowledgeBase(preparation)\n try {\n const result = await withSafeDirectory(snapshotsDir, hash, false, async (existing) => {\n if ((await hashKnowledgeBase(existing)) !== hash) {\n throw new Error('knowledge candidate snapshot does not match its content identity')\n }\n return use({ root: existing, hash })\n })\n await rm(preparation, { recursive: true, force: true })\n activated = true\n return result\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n await renameDurable(preparation, join(snapshotsDir, hash))\n activated = true\n return withSafeDirectory(snapshotsDir, hash, false, (root) => use({ root, hash }))\n } finally {\n if (!activated) await rm(preparation, { recursive: true, force: true })\n }\n })\n}\n\nfunction clearCandidateMeasurement(candidate: KnowledgeImprovementCandidateRecord): void {\n delete candidate.candidateHash\n delete candidate.evidenceHash\n delete candidate.promotionPlanHash\n}\n\nfunction findActiveCandidate(\n state: KnowledgeImprovementRunState,\n): KnowledgeImprovementCandidateRecord | undefined {\n return [...state.candidates]\n .reverse()\n .find((candidate) => candidate.status === 'candidate-ready' || candidate.status === 'running')\n}\n\nasync function copyKnowledgeWorkspace(sourceRoot: string, targetRoot: string): Promise<void> {\n await rm(targetRoot, { recursive: true, force: true })\n await mkdir(join(targetRoot, 'knowledge'), { recursive: true })\n await mkdir(join(targetRoot, 'raw', 'sources'), { recursive: true })\n await copyIfExists(join(sourceRoot, 'knowledge'), join(targetRoot, 'knowledge'))\n await copyIfExists(join(sourceRoot, 'raw'), join(targetRoot, 'raw'))\n await copyIfExists(\n join(layoutFor(sourceRoot).cacheDir, 'sources.json'),\n join(layoutFor(targetRoot).cacheDir, 'sources.json'),\n )\n await writeKnowledgeIndex(targetRoot)\n}\n\nfunction knowledgeCandidateTransitionPurpose(\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): string {\n const action = target === 'candidate' ? 'promotion' : 'restore'\n return `knowledge-${action}:${contentHash(candidate)}`\n}\n\nasync function knowledgeFilePlanEntries(\n sourceRoot: string,\n targetRoot: string,\n): Promise<KnowledgeFileTransactionPlanEntry[]> {\n const [before, after] = await Promise.all([\n knowledgeHashEntries(sourceRoot),\n knowledgeHashEntries(targetRoot),\n ])\n const beforeByPath = new Map(before.map((entry) => [entry.path, entry]))\n const afterByPath = new Map(after.map((entry) => [entry.path, entry]))\n const paths = [\n ...new Set([...before.map((entry) => entry.path), ...after.map((entry) => entry.path)]),\n ].sort((left, right) => left.localeCompare(right))\n return paths.map((path) => {\n assertKnowledgeMutationPath(path)\n const beforeEntry = beforeByPath.get(path)\n const afterEntry = afterByPath.get(path)\n return {\n path,\n beforeHash: beforeEntry?.transactionHash ?? null,\n afterHash: afterEntry?.transactionHash ?? null,\n ...(beforeEntry ? { beforeMode: beforeEntry.mode } : {}),\n ...(afterEntry ? { afterMode: afterEntry.mode } : {}),\n }\n })\n}\n\nasync function knowledgePlanMutations(\n targetRoot: string,\n plan: readonly KnowledgeFileTransactionPlanEntry[],\n): Promise<KnowledgeFileMutation[]> {\n return Promise.all(\n plan.map(async (entry) => {\n if (entry.afterHash === null) return { path: entry.path, content: null }\n const file = await readRegularFileWithinRoot(targetRoot, entry.path)\n const actualHash = createHash('sha256').update(file.bytes).digest('hex')\n if (actualHash !== entry.afterHash || file.mode !== entry.afterMode) {\n throw new Error(`knowledge target file changed before activation: ${entry.path}`)\n }\n return { path: entry.path, content: file.bytes, mode: file.mode }\n }),\n )\n}\n\nfunction assertCandidateTransitionPlan(\n plan: readonly KnowledgeFileTransactionPlanEntry[],\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): void {\n const approvedDirection = target === 'candidate' ? plan : reverseKnowledgeFilePlan(plan)\n const actualPlanHash = knowledgeFileTransactionPlanHash(approvedDirection)\n if (actualPlanHash !== candidate.promotionPlanHash) {\n throw new Error(\n `knowledge candidate plan changed after approval: expected ${candidate.promotionPlanHash}, got ${actualPlanHash}`,\n )\n }\n}\n\nfunction assertCandidateTransitionTransaction(\n transaction: KnowledgeFileTransaction,\n candidate: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): void {\n assertCandidateTransitionPlan(transaction.entries, candidate, target)\n}\n\nfunction reverseKnowledgeFilePlan(\n plan: readonly KnowledgeFileTransactionPlanEntry[],\n): KnowledgeFileTransactionPlanEntry[] {\n return plan.map((entry) => ({\n path: entry.path,\n beforeHash: entry.afterHash,\n afterHash: entry.beforeHash,\n ...(entry.afterMode === undefined ? {} : { beforeMode: entry.afterMode }),\n ...(entry.beforeMode === undefined ? {} : { afterMode: entry.beforeMode }),\n }))\n}\n\nasync function ensureCandidateTransitionEvent(\n runDir: string,\n candidateRef: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): Promise<void> {\n if (await hasCandidateTransitionEvent(runDir, candidateRef, target)) return\n await appendLedger(runDir, {\n type: target === 'candidate' ? 'candidate.promoted' : 'candidate.restored',\n runId: candidateRef.runId,\n candidateId: candidateRef.candidateId,\n candidateHash: candidateRef.candidateHash,\n evidenceHash: candidateRef.evidenceHash,\n promotionPlanHash: candidateRef.promotionPlanHash,\n })\n}\n\nasync function hasCandidateTransitionEvent(\n runDir: string,\n candidateRef: KnowledgeImprovementCandidateRef,\n target: KnowledgeImprovementTarget,\n): Promise<boolean> {\n const eventType = target === 'candidate' ? 'candidate.promoted' : 'candidate.restored'\n let matched = false\n for (const row of await loadKnowledgeImprovementEventsFromRun(runDir)) {\n if (row.type !== eventType || row.candidateId !== candidateRef.candidateId) continue\n if (\n row.runId !== candidateRef.runId ||\n row.candidateHash !== candidateRef.candidateHash ||\n row.evidenceHash !== candidateRef.evidenceHash ||\n row.promotionPlanHash !== candidateRef.promotionPlanHash\n ) {\n throw new Error('persisted knowledge activation event conflicts with the approved candidate')\n }\n matched = true\n }\n return matched\n}\n\nexport interface KnowledgeImprovementEvent extends Record<string, unknown> {\n at: string\n type: string\n}\n\nexport async function loadKnowledgeImprovementEvents(\n root: string,\n runId: string,\n): Promise<KnowledgeImprovementEvent[]> {\n const parsedRunId = runIdSchema.parse(runId)\n try {\n return await withKnowledgeImprovementRun(root, parsedRunId, false, (runDir) =>\n loadKnowledgeImprovementEventsFromRun(runDir),\n )\n } catch (error) {\n if (isMissingFile(error)) return []\n throw error\n }\n}\n\nasync function loadKnowledgeImprovementEventsFromRun(\n runDir: string,\n): Promise<KnowledgeImprovementEvent[]> {\n const events: KnowledgeImprovementEvent[] = []\n try {\n for (const file of await listRegularFilesWithinRoot(runDir, 'events')) {\n const name = file.path.slice('events/'.length)\n if (name.includes('/') || !name.endsWith('.json')) {\n throw new Error(`knowledge event store contains an unsupported entry: ${name}`)\n }\n events.push(parseKnowledgeImprovementEvent(JSON.parse(file.bytes.toString('utf8'))))\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n\n const unique = new Map<string, KnowledgeImprovementEvent>()\n for (const event of events) {\n const { at: _at, ...semantic } = event\n unique.set(contentHash(semantic), event)\n }\n return [...unique.values()].sort((left, right) => left.at.localeCompare(right.at))\n}\n\nfunction parseKnowledgeImprovementEvent(value: unknown): KnowledgeImprovementEvent {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('knowledge improvement event is not an object')\n }\n const event = value as Record<string, unknown>\n if (typeof event.at !== 'string' || typeof event.type !== 'string') {\n throw new Error('knowledge improvement event is missing at or type')\n }\n return event as KnowledgeImprovementEvent\n}\n\nasync function copyIfExists(source: string, target: string): Promise<void> {\n let sourceStat: Awaited<ReturnType<typeof lstat>>\n try {\n sourceStat = await lstat(source)\n } catch (error) {\n if (isMissingFile(error)) return\n throw error\n }\n if (!sourceStat.isDirectory() && !sourceStat.isFile()) {\n throw new Error(`knowledge surface contains an unsupported filesystem entry: ${source}`)\n }\n await mkdir(dirname(target), { recursive: true })\n await cp(source, target, { recursive: sourceStat.isDirectory(), dereference: false })\n}\n\nexport async function hashKnowledgeBase(root: string): Promise<string> {\n return withKnowledgeRead(root, () => hashKnowledgeBaseUnlocked(root))\n}\n\nasync function hashKnowledgeBaseUnlocked(root: string): Promise<string> {\n const entries = await knowledgeHashEntries(root)\n return sha256(JSON.stringify(entries.map(({ path, hash, mode }) => ({ path, hash, mode }))))\n}\n\ninterface KnowledgeFileIdentity {\n path: string\n hash: string\n transactionHash: string\n mode: number\n}\n\nasync function knowledgeHashEntries(root: string): Promise<KnowledgeFileIdentity[]> {\n const entries: KnowledgeFileIdentity[] = []\n for (const rel of ['knowledge', 'raw']) {\n try {\n for (const file of await listRegularFilesWithinRoot(root, rel)) {\n entries.push(knowledgeFileIdentity(file.path, file.bytes, file.mode))\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n }\n const sourceRegistry = relative(root, layoutFor(root).sourceRegistryPath).replace(/\\\\/g, '/')\n try {\n const file = await readRegularFileWithinRoot(root, sourceRegistry)\n entries.push(knowledgeFileIdentity(sourceRegistry, file.bytes, file.mode))\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n entries.sort((a, b) => a.path.localeCompare(b.path))\n return entries\n}\n\nfunction knowledgeFileIdentity(path: string, bytes: Buffer, mode: number): KnowledgeFileIdentity {\n return {\n path,\n hash: sha256(bytes.toString('base64')),\n transactionHash: createHash('sha256').update(bytes).digest('hex'),\n mode,\n }\n}\n\nasync function acquireRunLease(\n runDir: string,\n options: { ownerId: string; ttlMs: number },\n): Promise<LeaseHandle> {\n const path = join(runDir, 'run.lock.durable')\n const acquired = await acquireDurableFileLock(runDir, {\n lockfilePath: path,\n staleMs: options.ttlMs,\n })\n return {\n ownerId: options.ownerId,\n assertOwned: acquired.assertOwned,\n release: acquired.release,\n }\n}\n\nasync function blockRun(\n runDir: string,\n state: KnowledgeImprovementRunState,\n reason: string,\n onState: KnowledgeImprovementOptions['onState'],\n now: () => Date,\n): Promise<KnowledgeImprovementRunState> {\n state.status = 'blocked'\n state.blockedReason = reason\n state.updatedAt = now().toISOString()\n await saveState(runDir, state, onState)\n return state\n}\n\nasync function saveState(\n runDir: string,\n state: KnowledgeImprovementRunState,\n onState?: KnowledgeImprovementOptions['onState'],\n): Promise<void> {\n await writeJsonDurableWithinRoot(\n runDir,\n 'state.json',\n KnowledgeImprovementRunStateSchema.parse(state),\n )\n await onState?.(state)\n}\n\nasync function appendLedger(runDir: string, value: Record<string, unknown>): Promise<void> {\n const type = value.type\n if (typeof type !== 'string' || type.length === 0) {\n throw new Error('knowledge improvement event requires a type')\n }\n const relativePath = join('events', `${contentHash(value)}.json`).replace(/\\\\/g, '/')\n try {\n const file = await readRegularFileWithinRoot(runDir, relativePath)\n const existing = parseKnowledgeImprovementEvent(JSON.parse(file.bytes.toString('utf8')))\n const { at: _at, ...semantic } = existing\n if (canonicalJson(semantic) !== canonicalJson(value)) {\n throw new Error('knowledge improvement event identity conflicts with durable content')\n }\n return\n } catch (error) {\n if (!isMissingFile(error)) throw error\n }\n await writeJsonDurableWithinRoot(runDir, relativePath, {\n at: new Date().toISOString(),\n ...value,\n })\n}\n\nfunction candidateEvidenceRelativePath(candidateId: string): string {\n return join('candidates', safePathSegmentSchema.parse(candidateId), 'evidence.json').replace(\n /\\\\/g,\n '/',\n )\n}\n\nfunction descendantPath(root: string, path: string): string | undefined {\n const value = relative(resolve(root), resolve(path)).replace(/\\\\/g, '/')\n if (value === '' || value === '..' || value.startsWith('../') || isAbsolute(value))\n return undefined\n return value\n}\n\nfunction assertExactCandidatePlatform(): void {\n if (process.platform !== 'linux') {\n throw new Error('exact knowledge candidate workflows require Linux directory descriptors')\n }\n}\n\nfunction average(values: readonly number[]): number {\n const finite = values.filter(Number.isFinite)\n if (finite.length === 0) return 0\n return finite.reduce((sum, value) => sum + value, 0) / finite.length\n}\n","/**\n * Claim-grounding mode for `runVerifiedResearchLoop`.\n *\n * The two-agent loop's existing verifier judges a source's on-topic RELEVANCE\n * (is this page about the goal?). On the topic sets we have measured, its\n * cleanliness win is dominated by DE-DUPLICATION — which a deterministic\n * content-hash / canonical-URL check captures at ~none of the LLM premium (see\n * `docs/results/cost-quality.md`). That makes the LLM verifier look expensive\n * for what a cheap rule already does.\n *\n * Claim-grounding targets a DIFFERENT, harder error band: a citation that is\n * relevant and unique but **misattributed** — the page is on-topic, the URL is\n * real, yet the specific CLAIM the source is cited for does NOT actually appear\n * in the page. This is the citation-fabrication failure mode of LLM research:\n * the model writes a plausible sentence and hangs a real URL off it that never\n * says any such thing. Neither de-dup nor a relevance judge catches it (both can\n * pass a misattributed-but-on-topic page); only checking the claim against the\n * fetched text does.\n *\n * The check is EXECUTABLE GROUND TRUTH, not another LLM opinion: the worker\n * attaches the specific claim it is citing the source for, and the verifier\n * tests whether that claim is PRESENT (verbatim, normalized, or as a sufficient\n * content-word overlap / close paraphrase) in the `htmlToText` output of the\n * page the worker actually fetched. A claim that is not grounded is rejected as\n * misattributed. Because the oracle is deterministic text presence — not a model\n * call — it is a deployable, non-oracle verifier: it can run in production with\n * zero inference cost, OR be composed with the LLM relevance verifier so the\n * loop rejects BOTH off-topic AND misattributed sources.\n *\n * This module is content-free and any-topic: it adds (1) a way for a proposal to\n * carry the claim it is cited for, (2) the `groundClaimInText` oracle, and (3) a\n * `ResearchDriver` that gates on grounding. It composes the existing\n * `ResearchDriver` / `ResearchSourceProposal` contracts and the shipped\n * `htmlToText`; it reinvents none of them.\n */\n\nimport type {\n ResearchSourceProposal,\n SourceVerdict,\n SourceVerificationContext,\n} from './two-agent-research-loop'\nimport {\n createTangleRouterClient,\n type RouterClient,\n type TangleRouterOptions,\n} from './web-research-worker'\n\n/**\n * Metadata key under which a proposal carries the specific claim it is cited\n * for. The worker sets `metadata[citedClaimKey] = '<the claim>'`; the\n * claim-grounding driver reads it and checks it against the fetched page text.\n */\nexport const citedClaimKey = 'citedClaim'\n\n/** Read the cited claim a proposal carries, if any. */\nexport function citedClaimOf(source: ResearchSourceProposal): string | undefined {\n const claim = source.metadata?.[citedClaimKey]\n return typeof claim === 'string' && claim.trim() ? claim.trim() : undefined\n}\n\n/** Attach a cited claim to a proposal (immutably returns a new proposal). */\nexport function withCitedClaim(\n source: ResearchSourceProposal,\n claim: string,\n): ResearchSourceProposal {\n return { ...source, metadata: { ...source.metadata, [citedClaimKey]: claim } }\n}\n\nexport interface GroundingResult {\n /** True when the claim is sufficiently present in the page text. */\n grounded: boolean\n /** How the claim matched (or why it didn't). For audit/notes. */\n mode: 'verbatim' | 'normalized' | 'overlap' | 'absent' | 'empty-claim' | 'empty-text'\n /**\n * Fraction of the claim's content words found in the page text. 1 for a\n * verbatim/normalized hit; the measured overlap otherwise.\n */\n overlap: number\n /** Content words present in the claim but NOT in the page text. */\n missingWords: string[]\n}\n\nexport interface GroundClaimOptions {\n /**\n * Minimum fraction of the claim's content words that must appear in the page\n * text to count as a close paraphrase when there is no verbatim/normalized\n * hit. Default 0.7 — a high bar, because a misattribution is exactly a claim\n * whose specific words the page does not contain.\n */\n minOverlap?: number\n /**\n * Content words shorter than this are ignored (drops \"the\", \"of\", \"is\", …)\n * and never count toward overlap. Default 3.\n */\n minWordLength?: number\n}\n\n/**\n * Stopwords stripped before overlap scoring so the bar measures the claim's\n * SUBSTANTIVE words (the numbers, nouns, methods it asserts), not filler a\n * misattributed page would trivially share with the real one.\n */\nconst stopwords = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'but',\n 'of',\n 'to',\n 'in',\n 'on',\n 'for',\n 'with',\n 'as',\n 'by',\n 'at',\n 'from',\n 'that',\n 'this',\n 'these',\n 'those',\n 'it',\n 'its',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'has',\n 'have',\n 'had',\n 'can',\n 'will',\n 'would',\n 'should',\n 'may',\n 'might',\n 'not',\n 'no',\n 'than',\n 'then',\n 'over',\n 'under',\n 'about',\n 'into',\n 'their',\n 'they',\n 'them',\n])\n\n/** Normalize for presence checks: lowercase, collapse whitespace + punctuation. */\nfunction normalize(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** The claim's substantive content words (deduped, stopwords + short words removed). */\nfunction contentWords(claim: string, minWordLength: number): string[] {\n const words = normalize(claim)\n .split(' ')\n .filter((word) => word.length >= minWordLength && !stopwords.has(word))\n return [...new Set(words)]\n}\n\n/**\n * THE ORACLE. Is `claim` grounded in `pageText` (the `htmlToText` output of the\n * page the worker fetched)? Deterministic, no model call:\n *\n * 1. verbatim — the claim string appears as-is (case-insensitive).\n * 2. normalized — the claim appears after collapsing punctuation/whitespace\n * on both sides (so \"5.4x\" vs \"5.4 x\", smart quotes, etc. still match).\n * 3. overlap — a close paraphrase: at least `minOverlap` of the claim's\n * substantive content words appear in the page text. A misattributed page\n * fails here because the SPECIFIC words the claim asserts are absent.\n *\n * Returns the match mode, the measured overlap, and the missing content words —\n * enough for the driver to give a precise rejection reason and for a test/doc to\n * audit WHY a claim grounded or didn't.\n */\nexport function groundClaimInText(\n claim: string,\n pageText: string,\n options: GroundClaimOptions = {},\n): GroundingResult {\n const minOverlap = options.minOverlap ?? 0.7\n const minWordLength = Math.max(1, options.minWordLength ?? 3)\n\n const claimTrimmed = claim.trim()\n if (!claimTrimmed) return { grounded: false, mode: 'empty-claim', overlap: 0, missingWords: [] }\n if (!pageText.trim()) return { grounded: false, mode: 'empty-text', overlap: 0, missingWords: [] }\n\n const haystackLower = pageText.toLowerCase()\n if (haystackLower.includes(claimTrimmed.toLowerCase())) {\n return { grounded: true, mode: 'verbatim', overlap: 1, missingWords: [] }\n }\n\n const haystackNorm = normalize(pageText)\n const claimNorm = normalize(claimTrimmed)\n if (claimNorm && haystackNorm.includes(claimNorm)) {\n return { grounded: true, mode: 'normalized', overlap: 1, missingWords: [] }\n }\n\n const words = contentWords(claimTrimmed, minWordLength)\n if (words.length === 0) {\n // The claim has no substantive content words (all stopwords/short). With no\n // verbatim/normalized hit there is nothing to ground — treat as absent.\n return { grounded: false, mode: 'absent', overlap: 0, missingWords: [] }\n }\n // Word-boundary presence so \"rotary\" does not match inside \"rotaryxyz\".\n const present = words.filter((word) =>\n new RegExp(`\\\\b${word.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`).test(haystackNorm),\n )\n const missingWords = words.filter((word) => !present.includes(word))\n const overlap = present.length / words.length\n const grounded = overlap >= minOverlap\n return { grounded, mode: grounded ? 'overlap' : 'absent', overlap, missingWords }\n}\n\nexport interface ClaimGroundingDriverOptions extends GroundClaimOptions {\n /**\n * Optional second verifier to compose AFTER grounding passes. When set, a\n * source must BOTH ground its claim AND pass this verifier (e.g. the LLM\n * relevance driver's `verifySource`). Lets the loop reject off-topic AND\n * misattributed sources in one driver. Omit for the pure, zero-inference\n * grounding gate.\n */\n relevanceVerifier?: (\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ) => Promise<SourceVerdict> | SourceVerdict\n /**\n * What to do when a proposal carries NO cited claim. `'reject'` (default) is\n * fail-closed: in claim-grounding mode every source must declare what it is\n * cited for, so an un-annotated source is treated as ungrounded. `'accept'`\n * lets un-annotated sources through to the relevance verifier (if any) —\n * useful when mixing annotated and legacy proposals.\n */\n onMissingClaim?: 'reject' | 'accept'\n}\n\n/**\n * A `ResearchDriver`-shaped verifier (just the `verifySource` arm) that gates on\n * CLAIM GROUNDING: it rejects a source whose cited claim is not present in its\n * fetched page text — a misattributed / fabricated citation — and (optionally)\n * composes a relevance verifier after grounding passes.\n *\n * The returned function matches `ResearchDriver['verifySource']`, so it drops\n * straight into `runVerifiedResearchLoop` as `{ verifySource: createClaimGroundingVerifier(...) }`.\n */\nexport function createClaimGroundingVerifier(options: ClaimGroundingDriverOptions = {}) {\n const onMissingClaim = options.onMissingClaim ?? 'reject'\n return async function verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> {\n const claim = citedClaimOf(source)\n if (!claim) {\n if (onMissingClaim === 'reject') {\n return {\n accept: false,\n reason: 'no cited claim: claim-grounding mode requires every source to declare its claim',\n }\n }\n // accept-on-missing: fall through to the relevance verifier (or accept).\n return options.relevanceVerifier ? options.relevanceVerifier(source, ctx) : { accept: true }\n }\n\n const grounding = groundClaimInText(claim, source.text, options)\n if (!grounding.grounded) {\n const detail =\n grounding.mode === 'empty-text'\n ? 'fetched page has no text'\n : `claim not found in the fetched page (overlap ${(grounding.overlap * 100).toFixed(0)}%${\n grounding.missingWords.length\n ? `, missing: ${grounding.missingWords.slice(0, 6).join(', ')}`\n : ''\n })`\n return {\n accept: false,\n reason: `misattributed citation: ${detail}`,\n }\n }\n\n // Claim is grounded. Compose the relevance verifier if one was provided.\n if (options.relevanceVerifier) return options.relevanceVerifier(source, ctx)\n return { accept: true }\n }\n}\n\nexport interface WorkerClaimDecorationOptions {\n router?: RouterClient\n router_options?: TangleRouterOptions\n /** Max output tokens for the claim-extraction call. Default 1200 (glm floor). */\n maxTokens?: number\n}\n\n/**\n * Ask an LLM to state, for one source, the single specific factual claim a\n * researcher would cite THIS page for toward the goal. Used to DECORATE the\n * sources a relevance-only worker produced with the claim a citation would make,\n * so the claim-grounding verifier has something executable to check. The model\n * is told to ground the claim in the provided excerpt; the verifier then checks\n * it against the FULL page text independently — the model does not get to mark\n * its own homework.\n *\n * Returns the proposal annotated via `withCitedClaim`, or the original proposal\n * unchanged if the model returns nothing parseable (the verifier's\n * `onMissingClaim` policy then decides).\n */\nexport function createClaimDecorator(options: WorkerClaimDecorationOptions = {}) {\n const maxTokens = options.maxTokens ?? 1200\n return async function decorate(\n source: ResearchSourceProposal,\n goal: string,\n ): Promise<ResearchSourceProposal> {\n const router = options.router ?? createTangleRouterClient(options.router_options)\n const excerpt = source.text.slice(0, 1500)\n const system =\n 'You extract the single most important factual claim a researcher would cite a page for. ' +\n \"State ONE concrete, checkable sentence using the page's own key terms and numbers. \" +\n 'Do NOT invent facts not in the excerpt. Respond with ONLY the claim sentence, no prose.'\n const user = [\n `Research goal: ${goal}`,\n `Page title: ${source.title ?? '(none)'}`,\n `Page excerpt:\\n${excerpt}`,\n 'The single claim this page should be cited for:',\n ].join('\\n\\n')\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n maxTokens,\n )\n } catch {\n return source\n }\n const claim = raw.trim().split('\\n')[0]?.trim()\n if (!claim) return source\n return withCitedClaim(source, claim)\n }\n}\n","import type { JsonValue, JudgeConfig, Scenario } from '@tangle-network/agent-eval/campaign'\nimport { groundClaimInText } from './claim-grounding'\nimport { lintKnowledgeIndex } from './lint'\nimport type { RagAnswerQualityResult, RagGapFinding } from './rag-improvement-loop'\nimport type { KnowledgeIndex } from './types'\nimport { validateKnowledgeIndex } from './validate'\n\nexport type RagEvalProvider =\n | 'agent-knowledge'\n | 'ragas'\n | 'deepeval'\n | 'trulens'\n | 'ragchecker'\n | 'custom'\n\nexport type RagEvalMetricKey =\n | 'context_precision'\n | 'context_recall'\n | 'context_relevance'\n | 'context_sufficiency'\n | 'faithfulness'\n | 'groundedness'\n | 'answer_relevance'\n | 'answer_correctness'\n | 'citation_support'\n | 'abstention'\n | 'unsupported_answer_rate'\n\nexport type RagEvalSlice =\n | 'known-answer'\n | 'paraphrase'\n | 'distractor'\n | 'freshness'\n | 'multi-source'\n | 'unanswerable'\n | 'long-tail'\n | 'custom'\n\nexport interface RagEvalContext {\n id: string\n text: string\n rank?: number\n pageId?: string\n sourceId?: string\n anchorId?: string\n stale?: boolean\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagEvalCitation {\n id: string\n claimId?: string\n contextId?: string\n pageId?: string\n sourceId?: string\n anchorId?: string\n quote?: string\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagEvalClaim {\n id: string\n text: string\n citationIds?: readonly string[]\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagRequiredContext {\n id?: string\n text?: string\n pageId?: string\n sourceId?: string\n anchorId?: string\n}\n\nexport interface RagAnswerEvalScenario extends Scenario {\n kind: 'rag-answer-eval'\n query: string\n referenceAnswer?: string\n expectedClaims?: readonly string[]\n forbiddenClaims?: readonly string[]\n requiredContext?: readonly RagRequiredContext[]\n unanswerable?: boolean\n requireCitations?: boolean\n slices?: readonly RagEvalSlice[]\n thresholds?: Partial<Record<RagEvalMetricKey, number>>\n}\n\nexport interface ExternalRagEvalScore {\n provider: RagEvalProvider | string\n scores: Record<string, number>\n reasons?: Record<string, string>\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagAnswerEvalArtifact {\n query: string\n answer: string\n contexts: readonly RagEvalContext[]\n claims?: readonly RagEvalClaim[]\n citations?: readonly RagEvalCitation[]\n abstained?: boolean\n durationMs?: number\n costUsd?: number\n externalScores?: readonly ExternalRagEvalScore[]\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagAnswerMetricSummary {\n metrics: Record<RagEvalMetricKey, number>\n composite: number\n passed: boolean\n findings: readonly RagGapFinding[]\n claimCount: number\n supportedClaimCount: number\n citedClaimCount: number\n supportedCitationCount: number\n matchedRequiredContextCount: number\n requiredContextCount: number\n providerScores: Record<string, Record<RagEvalMetricKey, number>>\n}\n\nexport interface RagAnswerQualityJudgeOptions {\n name?: string\n thresholds?: Partial<Record<RagEvalMetricKey, number>>\n weights?: Partial<Record<RagEvalMetricKey, number>>\n externalScorePolicy?: 'prefer-external' | 'deterministic-first'\n minClaimSupport?: number\n}\n\nexport interface RagAnswerEvalCase {\n scenario: RagAnswerEvalScenario\n artifact: RagAnswerEvalArtifact\n}\n\nexport interface RagAnswerQualityHookOptions {\n scenarios: readonly RagAnswerEvalScenario[]\n run: (scenario: RagAnswerEvalScenario) => MaybePromise<RagAnswerEvalArtifact>\n externalEvaluator?: (\n item: RagAnswerEvalCase,\n ) => MaybePromise<ExternalRagEvalScore | readonly ExternalRagEvalScore[] | undefined>\n thresholds?: Partial<Record<RagEvalMetricKey, number>>\n weights?: Partial<Record<RagEvalMetricKey, number>>\n}\n\nexport interface RagCalibrationOptions {\n scenario: RagAnswerEvalScenario\n strong: RagAnswerEvalArtifact\n weak: RagAnswerEvalArtifact\n judge?: JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario>\n minStrongScore?: number\n maxWeakScore?: number\n signal?: AbortSignal\n}\n\nexport interface RagCalibrationResult {\n passed: boolean\n strongScore: number\n weakScore: number\n gap: number\n}\n\nexport interface KnowledgeBaseQualityOptions {\n now?: Date\n strict?: boolean\n minCitationRate?: number\n maxStaleSourceRate?: number\n}\n\nexport interface KnowledgeBaseQualityReport {\n ok: boolean\n metrics: {\n page_count: number\n source_count: number\n citation_rate: number\n source_backed_page_rate: number\n stale_source_rate: number\n duplicate_source_hash_rate: number\n lint_error_count: number\n lint_warning_count: number\n }\n findings: readonly RagGapFinding[]\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nconst defaultThresholds: Partial<Record<RagEvalMetricKey, number>> = {\n context_precision: 0.5,\n context_recall: 0.8,\n context_relevance: 0.5,\n context_sufficiency: 0.8,\n faithfulness: 0.9,\n answer_relevance: 0.7,\n citation_support: 0.9,\n abstention: 1,\n unsupported_answer_rate: 0,\n}\n\nconst defaultWeights: Partial<Record<RagEvalMetricKey, number>> = {\n context_relevance: 1,\n context_sufficiency: 1,\n faithfulness: 2,\n answer_relevance: 1,\n citation_support: 1,\n abstention: 1,\n}\n\nconst metricAliases: Record<string, RagEvalMetricKey> = {\n answer_correctness: 'answer_correctness',\n answer_relevance: 'answer_relevance',\n answer_relevancy: 'answer_relevance',\n answerrelevancy: 'answer_relevance',\n context_precision: 'context_precision',\n context_recall: 'context_recall',\n context_relevance: 'context_relevance',\n context_relevancy: 'context_relevance',\n context_sufficiency: 'context_sufficiency',\n contextual_precision: 'context_precision',\n contextual_recall: 'context_recall',\n contextual_relevancy: 'context_relevance',\n faithfulness: 'faithfulness',\n groundedness: 'groundedness',\n claim_recall: 'context_recall',\n claim_precision: 'faithfulness',\n citation_support: 'citation_support',\n abstention: 'abstention',\n unsupported_answer_rate: 'unsupported_answer_rate',\n}\n\nexport function ragAnswerQualityJudge(\n options: RagAnswerQualityJudgeOptions = {},\n): JudgeConfig<RagAnswerEvalArtifact, RagAnswerEvalScenario> {\n return {\n name: options.name ?? 'rag-answer-quality',\n dimensions: [\n { key: 'context_precision', description: 'share of retrieved context that is useful' },\n { key: 'context_recall', description: 'share of required evidence present in context' },\n { key: 'context_relevance', description: 'context relevance to the query and answer target' },\n { key: 'context_sufficiency', description: 'whether context is enough to answer' },\n { key: 'faithfulness', description: 'share of answer claims supported by retrieved context' },\n { key: 'answer_relevance', description: 'answer addresses the user query' },\n { key: 'answer_correctness', description: 'answer contains expected claims' },\n { key: 'citation_support', description: 'citations support the claims they cite' },\n { key: 'abstention', description: 'answer abstains exactly when the case is unanswerable' },\n ],\n appliesTo: (scenario) => scenario.kind === 'rag-answer-eval',\n async score({ artifact, scenario }) {\n const summary = scoreRagAnswerArtifact(artifact, scenario, options)\n return {\n dimensions: summary.metrics,\n composite: summary.composite,\n notes: summary.findings.map((finding) => finding.message).join('; '),\n }\n },\n }\n}\n\nexport function scoreRagAnswerArtifact(\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n options: RagAnswerQualityJudgeOptions = {},\n): RagAnswerMetricSummary {\n const claims = normalizeClaims(artifact)\n const abstained = artifact.abstained ?? looksLikeAbstention(artifact.answer)\n const requiredTargets = requiredContextTargets(scenario)\n const matchedRequiredContextCount = requiredTargets.filter((target) =>\n artifact.contexts.some((context) => contextMatchesTarget(context, target)),\n ).length\n const requiredContextCount = requiredTargets.length\n const contextRecall =\n requiredContextCount === 0\n ? neutralScore(Boolean(scenario.unanswerable) || artifact.contexts.length > 0)\n : matchedRequiredContextCount / requiredContextCount\n const relevantContextCount = artifact.contexts.filter((context) =>\n contextIsRelevant(context, scenario),\n ).length\n const contextPrecision =\n artifact.contexts.length === 0\n ? scenario.unanswerable\n ? 1\n : 0\n : relevantContextCount / artifact.contexts.length\n const contextRelevance =\n artifact.contexts.length === 0\n ? scenario.unanswerable\n ? 1\n : 0\n : average(artifact.contexts.map((context) => contextRelevanceScore(context, scenario)))\n const contextSufficiency = requiredContextCount === 0 ? contextRelevance : contextRecall\n const support = claims.map((claim) => claimSupport(claim.text, artifact.contexts, options))\n const supportedClaimCount = support.filter(Boolean).length\n const faithfulness =\n claims.length === 0 ? (abstained ? 1 : 0) : supportedClaimCount / Math.max(1, claims.length)\n const citation = scoreCitations(claims, artifact, scenario, options)\n const answerRelevance = scoreAnswerRelevance(artifact, scenario, abstained)\n const answerCorrectness = scoreAnswerCorrectness(artifact, scenario, abstained)\n const abstention = scenario.unanswerable ? (abstained ? 1 : 0) : abstained ? 0 : 1\n const unsupportedAnswerRate =\n claims.length === 0 ? (abstained ? 0 : 1) : 1 - supportedClaimCount / Math.max(1, claims.length)\n\n const deterministicMetrics: Record<RagEvalMetricKey, number> = {\n context_precision: clamp01(contextPrecision),\n context_recall: clamp01(contextRecall),\n context_relevance: clamp01(contextRelevance),\n context_sufficiency: clamp01(contextSufficiency),\n faithfulness: clamp01(faithfulness),\n groundedness: clamp01(faithfulness),\n answer_relevance: clamp01(answerRelevance),\n answer_correctness: clamp01(answerCorrectness),\n citation_support: clamp01(citation.support),\n abstention: clamp01(abstention),\n unsupported_answer_rate: clamp01(unsupportedAnswerRate),\n }\n const providerScores = normalizeExternalRagScores(artifact.externalScores ?? [])\n const metrics = mergeMetrics(deterministicMetrics, providerScores, options.externalScorePolicy)\n const thresholds = { ...defaultThresholds, ...scenario.thresholds, ...options.thresholds }\n const findings = diagnoseRagAnswerFailure(metrics, scenario, thresholds)\n const composite = weightedComposite(metrics, options.weights ?? defaultWeights)\n\n return {\n metrics,\n composite,\n passed: findings.every(\n (finding) => finding.severity !== 'error' && finding.severity !== 'critical',\n ),\n findings,\n claimCount: claims.length,\n supportedClaimCount,\n citedClaimCount: citation.citedClaimCount,\n supportedCitationCount: citation.supportedCitationCount,\n matchedRequiredContextCount,\n requiredContextCount,\n providerScores,\n }\n}\n\nexport function diagnoseRagAnswerFailure(\n metrics: Record<RagEvalMetricKey, number>,\n scenario: RagAnswerEvalScenario,\n thresholds: Partial<Record<RagEvalMetricKey, number>> = defaultThresholds,\n): RagGapFinding[] {\n const findings: RagGapFinding[] = []\n if (below(metrics.context_recall, thresholds.context_recall)) {\n findings.push({\n id: `${scenario.id}:context-recall`,\n kind: scenario.slices?.includes('multi-source')\n ? 'missing-multihop-evidence'\n : 'retrieval-miss',\n severity: 'error',\n scenarioId: scenario.id,\n message: 'Required evidence was not present in retrieved context.',\n evidence: { context_recall: metrics.context_recall },\n })\n }\n if (below(metrics.context_precision, thresholds.context_precision)) {\n findings.push({\n id: `${scenario.id}:context-precision`,\n kind: 'retrieval-noise',\n severity: 'warning',\n scenarioId: scenario.id,\n message: 'Retrieved context contains too much irrelevant material.',\n evidence: { context_precision: metrics.context_precision },\n })\n }\n if (below(metrics.faithfulness, thresholds.faithfulness)) {\n findings.push({\n id: `${scenario.id}:faithfulness`,\n kind: 'generator-unsupported-claim',\n severity: 'error',\n scenarioId: scenario.id,\n message: 'The answer contains claims not supported by retrieved context.',\n evidence: { faithfulness: metrics.faithfulness },\n })\n }\n if (below(metrics.citation_support, thresholds.citation_support)) {\n findings.push({\n id: `${scenario.id}:citation-support`,\n kind: 'citation-mismatch',\n severity: 'error',\n scenarioId: scenario.id,\n message: 'Citations do not support the claims they are attached to.',\n evidence: { citation_support: metrics.citation_support },\n })\n }\n if (below(metrics.abstention, thresholds.abstention)) {\n findings.push({\n id: `${scenario.id}:abstention`,\n kind: 'incorrect-abstention',\n severity: 'error',\n scenarioId: scenario.id,\n message: scenario.unanswerable\n ? 'The system answered a case marked unanswerable.'\n : 'The system abstained from an answerable case.',\n evidence: { abstention: metrics.abstention },\n })\n }\n return findings\n}\n\nexport function createRagAnswerQualityHook(\n options: RagAnswerQualityHookOptions,\n): () => Promise<RagAnswerQualityResult> {\n return async () => {\n const summaries: RagAnswerMetricSummary[] = []\n const findings: RagGapFinding[] = []\n for (const scenario of options.scenarios) {\n const initialArtifact = await options.run(scenario)\n const external = await options.externalEvaluator?.({ scenario, artifact: initialArtifact })\n const artifact = external\n ? {\n ...initialArtifact,\n externalScores: [\n ...(initialArtifact.externalScores ?? []),\n ...(Array.isArray(external) ? external : [external]),\n ],\n }\n : initialArtifact\n const summary = scoreRagAnswerArtifact(artifact, scenario, {\n thresholds: options.thresholds,\n weights: options.weights,\n })\n summaries.push(summary)\n findings.push(...summary.findings)\n }\n const metrics = aggregateRagAnswerMetrics(summaries)\n return {\n passed: findings.length === 0,\n metrics,\n findings,\n metadata: { scenarioCount: options.scenarios.length },\n }\n }\n}\n\nexport async function calibrateRagAnswerJudge(\n options: RagCalibrationOptions,\n): Promise<RagCalibrationResult> {\n const judge = options.judge ?? ragAnswerQualityJudge()\n const strong = await judge.score({\n artifact: options.strong,\n scenario: options.scenario,\n signal: options.signal ?? new AbortController().signal,\n })\n const weak = await judge.score({\n artifact: options.weak,\n scenario: options.scenario,\n signal: options.signal ?? new AbortController().signal,\n })\n const strongScore = strong.composite\n const weakScore = weak.composite\n const minStrongScore = options.minStrongScore ?? 0.7\n const maxWeakScore = options.maxWeakScore ?? 0.3\n return {\n passed: strongScore >= minStrongScore && weakScore <= maxWeakScore,\n strongScore,\n weakScore,\n gap: strongScore - weakScore,\n }\n}\n\nexport function normalizeExternalRagScores(\n scores: readonly ExternalRagEvalScore[],\n): Record<string, Record<RagEvalMetricKey, number>> {\n const normalized: Record<string, Record<RagEvalMetricKey, number>> = {}\n for (const item of scores) {\n const provider = item.provider || 'custom'\n const providerScores = (normalized[provider] ?? {}) as Record<RagEvalMetricKey, number>\n for (const [key, value] of Object.entries(item.scores)) {\n const canonical = metricAliases[normalizeMetricName(key)]\n if (!canonical) continue\n if (Number.isFinite(value)) providerScores[canonical] = clamp01(value)\n }\n normalized[provider] = providerScores\n }\n return normalized\n}\n\nexport function toRagasEvaluationRows(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n user_input: scenario.query,\n response: artifact.answer,\n retrieved_contexts: artifact.contexts.map((context) => context.text),\n reference: scenario.referenceAnswer,\n reference_contexts: requiredContextTexts(scenario),\n }))\n}\n\nexport function toDeepEvalTestCases(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n input: scenario.query,\n actual_output: artifact.answer,\n expected_output: scenario.referenceAnswer,\n retrieval_context: artifact.contexts.map((context) => context.text),\n context: requiredContextTexts(scenario),\n }))\n}\n\nexport function toTruLensRecords(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n input: scenario.query,\n output: artifact.answer,\n context: artifact.contexts.map((context) => context.text).join('\\n\\n'),\n }))\n}\n\nexport function toRagCheckerRecords(cases: readonly RagAnswerEvalCase[]) {\n return cases.map(({ scenario, artifact }) => ({\n query_id: scenario.id,\n query: scenario.query,\n gt_answer: scenario.referenceAnswer,\n response: artifact.answer,\n retrieved_context: artifact.contexts.map((context) => ({\n doc_id: context.id,\n text: context.text,\n })),\n claims: normalizeClaims(artifact).map((claim) => claim.text),\n }))\n}\n\nexport function scoreKnowledgeBaseIndex(\n index: KnowledgeIndex,\n options: KnowledgeBaseQualityOptions = {},\n): KnowledgeBaseQualityReport {\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const lintFindings = lintKnowledgeIndex(index)\n const now = options.now ?? new Date()\n const staleSourceCount = index.sources.filter((source) => {\n return source.validUntil ? Date.parse(source.validUntil) < now.getTime() : false\n }).length\n const sourceHashCounts = new Map<string, number>()\n for (const source of index.sources) {\n sourceHashCounts.set(source.contentHash, (sourceHashCounts.get(source.contentHash) ?? 0) + 1)\n }\n const duplicateSourceHashCount = [...sourceHashCounts.values()].filter(\n (count) => count > 1,\n ).length\n const pagesWithInlineCitations = index.pages.filter(\n (page) => sourceRefs(page.text).length > 0,\n ).length\n const pagesWithSources = index.pages.filter((page) => page.sourceIds.length > 0).length\n const metrics = {\n page_count: index.pages.length,\n source_count: index.sources.length,\n citation_rate: index.pages.length === 0 ? 1 : pagesWithInlineCitations / index.pages.length,\n source_backed_page_rate: index.pages.length === 0 ? 1 : pagesWithSources / index.pages.length,\n stale_source_rate: index.sources.length === 0 ? 0 : staleSourceCount / index.sources.length,\n duplicate_source_hash_rate:\n index.sources.length === 0 ? 0 : duplicateSourceHashCount / index.sources.length,\n lint_error_count: validation.findings.filter((finding) => finding.severity === 'error').length,\n lint_warning_count: lintFindings.filter((finding) => finding.severity === 'warning').length,\n }\n const findings: RagGapFinding[] = []\n if (metrics.lint_error_count > 0) {\n findings.push({\n id: 'kb:lint-errors',\n kind: 'unknown',\n severity: 'critical',\n message: `${metrics.lint_error_count} validation error(s) in the knowledge index.`,\n evidence: { lint_error_count: metrics.lint_error_count },\n })\n }\n if (metrics.citation_rate < (options.minCitationRate ?? 0)) {\n findings.push({\n id: 'kb:citation-rate',\n kind: 'missing-source',\n severity: 'error',\n message: 'Inline citation coverage is below the configured minimum.',\n evidence: { citation_rate: metrics.citation_rate },\n })\n }\n if (metrics.stale_source_rate > (options.maxStaleSourceRate ?? 1)) {\n findings.push({\n id: 'kb:stale-source-rate',\n kind: 'stale-source',\n severity: 'error',\n message: 'Stale source rate exceeds the configured maximum.',\n evidence: { stale_source_rate: metrics.stale_source_rate },\n })\n }\n return { ok: findings.length === 0, metrics, findings }\n}\n\nfunction requiredContextTargets(scenario: RagAnswerEvalScenario): RagRequiredContext[] {\n if (scenario.requiredContext?.length) return [...scenario.requiredContext]\n return (scenario.expectedClaims ?? []).map((text) => ({ text }))\n}\n\nfunction requiredContextTexts(scenario: RagAnswerEvalScenario): string[] {\n return requiredContextTargets(scenario).flatMap((target) => (target.text ? [target.text] : []))\n}\n\nfunction contextMatchesTarget(context: RagEvalContext, target: RagRequiredContext): boolean {\n if (target.id && context.id === target.id) return true\n if (target.pageId && context.pageId === target.pageId) return true\n if (target.sourceId && context.sourceId === target.sourceId) return true\n if (target.anchorId && context.anchorId === target.anchorId) return true\n if (target.text && textSupportScore(target.text, context.text) >= 0.7) return true\n return false\n}\n\nfunction contextIsRelevant(context: RagEvalContext, scenario: RagAnswerEvalScenario): boolean {\n return contextRelevanceScore(context, scenario) >= 0.3\n}\n\nfunction contextRelevanceScore(context: RagEvalContext, scenario: RagAnswerEvalScenario): number {\n const targets = [\n scenario.query,\n scenario.referenceAnswer,\n ...(scenario.expectedClaims ?? []),\n ...requiredContextTexts(scenario),\n ].filter((value): value is string => Boolean(value?.trim()))\n if (targets.length === 0) return 1\n return Math.max(...targets.map((target) => textSupportScore(target, context.text)))\n}\n\nfunction claimSupport(\n claim: string,\n contexts: readonly RagEvalContext[],\n options: Pick<RagAnswerQualityJudgeOptions, 'minClaimSupport'>,\n): boolean {\n if (contexts.length === 0) return false\n const combined = contexts.map((context) => context.text).join('\\n\\n')\n const deterministic = groundClaimInText(claim, combined, {\n minOverlap: options.minClaimSupport ?? 0.7,\n })\n return (\n deterministic.grounded || textSupportScore(claim, combined) >= (options.minClaimSupport ?? 0.7)\n )\n}\n\nfunction scoreCitations(\n claims: readonly RagEvalClaim[],\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n options: Pick<RagAnswerQualityJudgeOptions, 'minClaimSupport'>,\n): { support: number; citedClaimCount: number; supportedCitationCount: number } {\n if (claims.length === 0)\n return { support: scenario.unanswerable ? 1 : 0, citedClaimCount: 0, supportedCitationCount: 0 }\n const citations = artifact.citations ?? []\n const citedClaims = claims.filter((claim) => citationsForClaim(claim, citations).length > 0)\n if (citedClaims.length === 0) {\n return {\n support: scenario.requireCitations ? 0 : 1,\n citedClaimCount: 0,\n supportedCitationCount: 0,\n }\n }\n let supportedCitationCount = 0\n for (const claim of citedClaims) {\n const citedContexts = contextsForClaim(claim, citations, artifact.contexts)\n if (claimSupport(claim.text, citedContexts, options)) supportedCitationCount += 1\n }\n return {\n support: supportedCitationCount / citedClaims.length,\n citedClaimCount: citedClaims.length,\n supportedCitationCount,\n }\n}\n\nfunction citationsForClaim(\n claim: RagEvalClaim,\n citations: readonly RagEvalCitation[],\n): RagEvalCitation[] {\n const claimCitationIds = new Set(claim.citationIds ?? [])\n return citations.filter((citation) => {\n return citation.claimId === claim.id || (citation.id && claimCitationIds.has(citation.id))\n })\n}\n\nfunction contextsForClaim(\n claim: RagEvalClaim,\n citations: readonly RagEvalCitation[],\n contexts: readonly RagEvalContext[],\n): readonly RagEvalContext[] {\n const matchedCitations = citationsForClaim(claim, citations)\n const matchedContexts = contexts.filter((context) =>\n matchedCitations.some((citation) => {\n if (citation.contextId && citation.contextId === context.id) return true\n if (citation.pageId && citation.pageId === context.pageId) return true\n if (citation.sourceId && citation.sourceId === context.sourceId) return true\n if (citation.anchorId && citation.anchorId === context.anchorId) return true\n return false\n }),\n )\n return matchedContexts.length > 0 ? matchedContexts : contexts\n}\n\nfunction scoreAnswerRelevance(\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n abstained: boolean,\n): number {\n if (scenario.unanswerable) return abstained ? 1 : 0\n if (abstained) return 0\n const targets = [\n scenario.referenceAnswer,\n ...(scenario.expectedClaims ?? []),\n scenario.query,\n ].filter((value): value is string => Boolean(value?.trim()))\n return Math.max(...targets.map((target) => textSupportScore(target, artifact.answer)))\n}\n\nfunction scoreAnswerCorrectness(\n artifact: RagAnswerEvalArtifact,\n scenario: RagAnswerEvalScenario,\n abstained: boolean,\n): number {\n if (scenario.unanswerable) return abstained ? 1 : 0\n const expected = scenario.expectedClaims ?? []\n const forbidden = scenario.forbiddenClaims ?? []\n const expectedScore =\n expected.length === 0\n ? scoreAnswerRelevance(artifact, scenario, abstained)\n : average(expected.map((claim) => textSupportScore(claim, artifact.answer)))\n const forbiddenPenalty =\n forbidden.length === 0\n ? 0\n : forbidden.filter((claim) => textSupportScore(claim, artifact.answer) >= 0.7).length /\n forbidden.length\n return clamp01(expectedScore * (1 - forbiddenPenalty))\n}\n\nfunction normalizeClaims(artifact: RagAnswerEvalArtifact): RagEvalClaim[] {\n if (artifact.claims?.length) return [...artifact.claims]\n return splitSentences(artifact.answer).map((text, index) => ({ id: `claim-${index + 1}`, text }))\n}\n\nfunction splitSentences(text: string): string[] {\n return text\n .split(/(?<=[.!?])\\s+/)\n .map((sentence) => sentence.trim())\n .filter((sentence) => sentence.length > 0 && !looksLikeAbstention(sentence))\n}\n\nfunction looksLikeAbstention(answer: string): boolean {\n const normalized = answer.toLowerCase()\n return [\n \"i don't know\",\n 'i do not know',\n 'not enough information',\n 'cannot answer',\n \"can't answer\",\n 'insufficient information',\n 'no reliable answer',\n ].some((phrase) => normalized.includes(phrase))\n}\n\nfunction mergeMetrics(\n deterministic: Record<RagEvalMetricKey, number>,\n providerScores: Record<string, Record<RagEvalMetricKey, number>>,\n policy: RagAnswerQualityJudgeOptions['externalScorePolicy'] = 'prefer-external',\n): Record<RagEvalMetricKey, number> {\n if (policy === 'deterministic-first') return deterministic\n const merged = { ...deterministic }\n for (const scores of Object.values(providerScores)) {\n for (const [key, value] of Object.entries(scores) as Array<[RagEvalMetricKey, number]>) {\n merged[key] = value\n if (key === 'groundedness') merged.faithfulness = value\n if (key === 'faithfulness') merged.groundedness = value\n }\n }\n return merged\n}\n\nfunction aggregateRagAnswerMetrics(\n summaries: readonly RagAnswerMetricSummary[],\n): Record<string, number> {\n const keys = new Set<RagEvalMetricKey>()\n for (const summary of summaries) {\n for (const key of Object.keys(summary.metrics) as RagEvalMetricKey[]) keys.add(key)\n }\n const out: Record<string, number> = {}\n for (const key of [...keys].sort()) {\n out[key] = average(summaries.map((summary) => summary.metrics[key]))\n }\n out.composite = average(summaries.map((summary) => summary.composite))\n return out\n}\n\nfunction weightedComposite(\n metrics: Record<RagEvalMetricKey, number>,\n weights: Partial<Record<RagEvalMetricKey, number>>,\n): number {\n let weighted = 0\n let total = 0\n for (const [key, weight] of Object.entries(weights) as Array<[RagEvalMetricKey, number]>) {\n if (!Number.isFinite(weight) || weight <= 0) continue\n const metric = metrics[key]\n if (!Number.isFinite(metric)) continue\n const value = key === 'unsupported_answer_rate' ? 1 - metric : metric\n weighted += value * weight\n total += weight\n }\n return total === 0 ? 0 : weighted / total\n}\n\nfunction normalizeMetricName(metric: string): string {\n return metric\n .trim()\n .toLowerCase()\n .replace(/[@/.-]+/g, '_')\n .replace(/\\s+/g, '_')\n}\n\nfunction textSupportScore(needle: string, haystack: string): number {\n const needleWords = contentWords(needle)\n if (needleWords.length === 0) return 0\n const haystackWords = new Set(contentWords(haystack))\n const present = needleWords.filter((word) => haystackWords.has(word))\n return present.length / needleWords.length\n}\n\nfunction contentWords(text: string): string[] {\n const normalized = text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .split(/\\s+/)\n .map((word) => stem(word.trim()))\n .filter((word) => (word.length >= 3 || /^\\d+$/.test(word)) && !stopwords.has(word))\n return [...new Set(normalized)]\n}\n\nfunction stem(word: string): string {\n if (word.endsWith('ies') && word.length > 4) return `${word.slice(0, -3)}y`\n if (word.endsWith('ing') && word.length > 5) return word.slice(0, -3)\n if (word.endsWith('ed') && word.length > 4) return word.slice(0, -2)\n if (word.endsWith('s') && word.length > 3) return word.slice(0, -1)\n return word\n}\n\nfunction sourceRefs(text: string): string[] {\n const refs: string[] = []\n const regex = /\\[\\^([A-Za-z0-9_-]+)(?:#([A-Za-z0-9_.:-]+))?\\]/g\n let match = regex.exec(text)\n while (match !== null) {\n refs.push(match[0])\n match = regex.exec(text)\n }\n return refs\n}\n\nfunction below(metric: number, threshold: number | undefined): boolean {\n return threshold !== undefined && metric < threshold\n}\n\nfunction neutralScore(condition: boolean): number {\n return condition ? 1 : 0\n}\n\nfunction average(values: readonly number[]): number {\n const finite = values.filter(Number.isFinite)\n return finite.length === 0 ? 0 : finite.reduce((sum, value) => sum + value, 0) / finite.length\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.min(1, value))\n}\n\nconst stopwords = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'but',\n 'of',\n 'to',\n 'in',\n 'on',\n 'for',\n 'with',\n 'as',\n 'by',\n 'at',\n 'from',\n 'that',\n 'this',\n 'these',\n 'those',\n 'it',\n 'its',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'has',\n 'have',\n 'had',\n 'can',\n 'will',\n 'would',\n 'should',\n 'may',\n 'might',\n 'not',\n 'no',\n 'than',\n 'then',\n 'over',\n 'under',\n 'about',\n 'into',\n 'their',\n 'they',\n 'them',\n 'what',\n 'when',\n 'where',\n 'who',\n 'why',\n 'how',\n])\n","import {\n blockingKnowledgeEval,\n type ControlEvalResult,\n type ControlRuntimeConfig,\n objectiveEval,\n} from '@tangle-network/agent-eval'\nimport type {\n BuildEvalKnowledgeBundleOptions,\n EvalKnowledgeBundleBuildResult,\n KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport { createKnowledgeEvent } from './events'\nimport { buildKnowledgeIndex } from './indexer'\nimport { lintKnowledgeIndex } from './lint'\nimport { type ApplyWriteBlocksResult, applyKnowledgeWriteBlocks } from './proposals'\nimport { readinessFor } from './readiness-helpers'\nimport {\n type AddSourceOptions,\n type AddSourceTextInput,\n addSourcePath,\n addSourceText,\n} from './sources'\nimport { initKnowledgeBase } from './store'\nimport type { KnowledgeEvent, KnowledgeIndex, KnowledgeLintFinding, SourceRecord } from './types'\nimport {\n type ValidateKnowledgeOptions,\n type ValidateKnowledgeResult,\n validateKnowledgeIndex,\n} from './validate'\n\nexport interface KnowledgeResearchLoopContext {\n root: string\n goal: string\n iteration: number\n index: KnowledgeIndex\n lintFindings: KnowledgeLintFinding[]\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n previousSteps: KnowledgeResearchLoopStep[]\n signal?: AbortSignal\n}\n\nexport interface KnowledgeResearchLoopDecision {\n /**\n * Free-form notes from the researcher. Keep this human-readable; products can\n * store it as the research transcript.\n */\n notes?: string\n /**\n * Local files to register as immutable sources before applying proposals.\n */\n sourcePaths?: string[]\n /**\n * Textual source artifacts discovered by an agent, browser worker, connector,\n * or deep-research process.\n */\n sourceTexts?: AddSourceTextInput[]\n /**\n * Safe write protocol text. The loop parses and applies only accepted\n * `---FILE: knowledge/...---` blocks.\n */\n proposalText?: string\n /**\n * The researcher decides when the wiki is good enough. The loop deliberately\n * does not encode a domain-specific definition of \"done\".\n */\n done?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface KnowledgeResearchLoopStep {\n iteration: number\n notes?: string\n addedSources: SourceRecord[]\n applied?: ApplyWriteBlocksResult\n lintFindings: KnowledgeLintFinding[]\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n event: KnowledgeEvent\n done: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface RunKnowledgeResearchLoopOptions {\n root: string\n goal: string\n maxIterations?: number\n actor?: string\n strict?: ValidateKnowledgeOptions['strict']\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>\n signal?: AbortSignal\n step(\n context: KnowledgeResearchLoopContext,\n ): Promise<KnowledgeResearchLoopDecision> | KnowledgeResearchLoopDecision\n onStep?: (step: KnowledgeResearchLoopStep) => Promise<void> | void\n}\n\nexport interface KnowledgeResearchLoopResult {\n root: string\n goal: string\n iterations: number\n done: boolean\n index: KnowledgeIndex\n lintFindings: KnowledgeLintFinding[]\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n steps: KnowledgeResearchLoopStep[]\n}\n\nexport type KnowledgeControlLoopState = KnowledgeResearchLoopContext\nexport type KnowledgeControlLoopAction = KnowledgeResearchLoopDecision\nexport type KnowledgeControlLoopActionResult = KnowledgeResearchLoopStep\n\nexport interface KnowledgeControlLoopAdapterOptions {\n root: string\n goal: string\n actor?: string\n strict?: ValidateKnowledgeOptions['strict']\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>\n}\n\nexport type KnowledgeControlLoopAdapter = Pick<\n ControlRuntimeConfig<\n KnowledgeControlLoopState,\n KnowledgeControlLoopAction,\n KnowledgeControlLoopActionResult,\n ControlEvalResult\n >,\n 'intent' | 'observe' | 'validate' | 'act' | 'shouldStop'\n>\n\n/**\n * Adapter for running knowledge growth through `agent-eval`'s generic control\n * runtime. The caller still owns `decide`: that can be a proposer agent,\n * reviewer agent, deterministic policy, or a composition of all three.\n */\nexport function createKnowledgeControlLoopAdapter(\n options: KnowledgeControlLoopAdapterOptions,\n): KnowledgeControlLoopAdapter {\n let initialized = false\n const appliedSteps: KnowledgeResearchLoopStep[] = []\n\n return {\n intent: options.goal,\n async observe({ history, abortSignal }) {\n if (abortSignal.aborted) throw new Error('Knowledge control loop aborted')\n if (!initialized) {\n await initKnowledgeBase(options.root)\n initialized = true\n }\n const index = await buildKnowledgeIndex(options.root)\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const lintFindings = lintKnowledgeIndex(index)\n const readiness = readinessFor(options, index)\n return {\n root: options.root,\n goal: options.goal,\n iteration: history.length + 1,\n index,\n lintFindings,\n validation,\n readiness,\n previousSteps: [...appliedSteps],\n signal: abortSignal,\n }\n },\n validate({ state }) {\n const errorFindings = state.validation.findings.filter(\n (finding) => finding.severity === 'error',\n )\n const evals: ControlEvalResult[] = [\n objectiveEval({\n id: 'knowledge-valid',\n passed: state.validation.ok,\n severity: 'critical',\n detail: state.validation.ok\n ? 'Knowledge index is valid.'\n : 'Knowledge index has validation errors.',\n metadata: { findings: state.validation.findings },\n }),\n objectiveEval({\n id: 'knowledge-lint-errors',\n passed: errorFindings.length === 0,\n severity: 'error',\n detail:\n errorFindings.length === 0\n ? 'No lint errors.'\n : `${errorFindings.length} lint error(s).`,\n metadata: { findings: errorFindings },\n }),\n ]\n if (state.readiness) evals.push(blockingKnowledgeEval(state.readiness.report))\n return evals\n },\n shouldStop() {\n return { stop: false, pass: false, reason: 'knowledge driver owns stop decisions' }\n },\n async act(action, ctx) {\n const step = await applyKnowledgeResearchDecision(options, action, ctx.state.iteration)\n appliedSteps.push(step)\n return step\n },\n }\n}\n\nexport async function runKnowledgeResearchLoop(\n options: RunKnowledgeResearchLoopOptions,\n): Promise<KnowledgeResearchLoopResult> {\n const maxIterations = Math.max(1, options.maxIterations ?? 3)\n await initKnowledgeBase(options.root)\n const steps: KnowledgeResearchLoopStep[] = []\n let index = await buildKnowledgeIndex(options.root)\n let validation = validateKnowledgeIndex(index, { strict: options.strict })\n let lintFindings = lintKnowledgeIndex(index)\n let readiness = readinessFor(options, index)\n let done = false\n\n for (let iteration = 1; iteration <= maxIterations; iteration++) {\n if (options.signal?.aborted) throw new Error('Knowledge research loop aborted')\n const decision = await options.step({\n root: options.root,\n goal: options.goal,\n iteration,\n index,\n lintFindings,\n validation,\n readiness,\n previousSteps: steps,\n signal: options.signal,\n })\n\n done = Boolean(decision.done)\n const step = await applyKnowledgeResearchDecision(options, decision, iteration)\n index = await buildKnowledgeIndex(options.root)\n validation = step.validation\n lintFindings = step.lintFindings\n readiness = step.readiness\n steps.push(step)\n await options.onStep?.(step)\n\n if (done) break\n if (!step.applied && step.addedSources.length === 0) break\n }\n\n return {\n root: options.root,\n goal: options.goal,\n iterations: steps.length,\n done,\n index,\n lintFindings,\n validation,\n readiness,\n steps,\n }\n}\n\nasync function applyKnowledgeResearchDecision(\n options: KnowledgeControlLoopAdapterOptions,\n decision: KnowledgeResearchLoopDecision,\n iteration = 1,\n): Promise<KnowledgeResearchLoopStep> {\n const addedSources: SourceRecord[] = []\n for (const sourcePath of decision.sourcePaths ?? []) {\n addedSources.push(...(await addSourcePath(options.root, sourcePath, options.sourceOptions)))\n }\n for (const sourceText of decision.sourceTexts ?? []) {\n addedSources.push(await addSourceText(options.root, sourceText, options.sourceOptions))\n }\n\n const applied = decision.proposalText\n ? await applyKnowledgeWriteBlocks(options.root, decision.proposalText)\n : undefined\n\n const index = await buildKnowledgeIndex(options.root)\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const lintFindings = lintKnowledgeIndex(index)\n const readiness = readinessFor(options, index)\n const done = Boolean(decision.done)\n const event = createKnowledgeEvent({\n type: 'research.iteration',\n actor: options.actor,\n target: options.root,\n metadata: {\n goal: options.goal,\n iteration,\n done,\n addedSourceCount: addedSources.length,\n written: applied?.written,\n warningCount: applied?.warnings.length ?? 0,\n errorCount: validation.findings.filter((finding) => finding.severity === 'error').length,\n },\n })\n\n return {\n iteration,\n notes: decision.notes,\n addedSources,\n applied,\n lintFindings,\n validation,\n readiness,\n event,\n done,\n metadata: decision.metadata,\n }\n}\n","import { stableId } from './ids'\nimport type { KnowledgeEvent, KnowledgeEventType } from './types'\n\nexport interface KnowledgeEventQuery {\n type?: KnowledgeEventType\n target?: string\n limit?: number\n}\n\nexport function createKnowledgeEvent(input: {\n type: KnowledgeEventType\n actor?: string\n target?: string\n metadata?: Record<string, unknown>\n now?: () => Date\n}): KnowledgeEvent {\n const createdAt = (input.now ?? (() => new Date()))().toISOString()\n return {\n id: stableId(\n 'evt',\n `${input.type}:${input.target ?? ''}:${createdAt}:${JSON.stringify(input.metadata ?? {})}`,\n ),\n type: input.type,\n createdAt,\n actor: input.actor,\n target: input.target,\n metadata: input.metadata,\n }\n}\n","import {\n acquisitionPlansForKnowledgeGaps,\n type DataAcquisitionPlan,\n type KnowledgeAcquisitionMode,\n type KnowledgeBundle,\n type KnowledgeFreshness,\n type KnowledgeImportance,\n type KnowledgeReadinessReport,\n type KnowledgeRequirement,\n type KnowledgeRequirementCategory,\n type KnowledgeSensitivity,\n scoreKnowledgeReadiness,\n type UserQuestion,\n userQuestionsForKnowledgeGaps,\n} from '@tangle-network/agent-eval'\nimport { stringMetadata } from './metadata'\nimport { searchKnowledge } from './search'\nimport type { KnowledgeIndex, KnowledgeSearchResult } from './types'\n\nexport interface KnowledgeReadinessSpec {\n id: string\n description: string\n query: string\n requiredFor: string[]\n category: KnowledgeRequirementCategory\n acquisitionMode: KnowledgeAcquisitionMode\n importance: KnowledgeImportance\n freshness: KnowledgeFreshness\n sensitivity: KnowledgeSensitivity\n confidenceNeeded: number\n fallbackPolicy?: KnowledgeRequirement['fallbackPolicy']\n minSources?: number\n minHits?: number\n metadata?: Record<string, unknown>\n}\n\n/**\n * Defaults applied by `defineReadinessSpec` when the caller omits the field.\n *\n * These are deliberately conservative: a domain-specific topic that an agent\n * needs grounded to a high-confidence threshold from at least one authoritative\n * source. Override any field to specialise (e.g. `freshness: 'daily'` for a\n * topic that must reflect today's regulatory state).\n */\nexport const READINESS_SPEC_DEFAULTS = {\n category: 'domain_specific',\n acquisitionMode: 'search_web',\n importance: 'high',\n freshness: 'monthly',\n sensitivity: 'public',\n confidenceNeeded: 0.7,\n minSources: 1,\n minHits: 2,\n} as const satisfies Pick<\n KnowledgeReadinessSpec,\n | 'category'\n | 'acquisitionMode'\n | 'importance'\n | 'freshness'\n | 'sensitivity'\n | 'confidenceNeeded'\n | 'minSources'\n | 'minHits'\n>\n\n/**\n * Inputs accepted by `defineReadinessSpec`. The four fields the caller cannot\n * sanely default (id, description, query, requiredFor) are required; everything\n * else is optional and pulls from `READINESS_SPEC_DEFAULTS`.\n */\nexport type DefineReadinessSpecInput = Pick<\n KnowledgeReadinessSpec,\n 'id' | 'description' | 'query' | 'requiredFor'\n> &\n Partial<Omit<KnowledgeReadinessSpec, 'id' | 'description' | 'query' | 'requiredFor'>>\n\n/**\n * Builder that returns a fully-typed `KnowledgeReadinessSpec` from a slim input.\n *\n * Motivation: `KnowledgeReadinessSpec` has eleven required fields. Most of them\n * (category, acquisition mode, importance, freshness, sensitivity, confidence\n * threshold, source/hit minima) have a clear default for domain-specific KB\n * topics — agents end up copy-pasting the same boilerplate across every spec.\n * This helper collapses that boilerplate while keeping every field overridable.\n *\n * @example\n * defineReadinessSpec({\n * id: 'coop/intent-grounding',\n * description: 'Required grounding for coop pack intent stage',\n * query: 'flock size space ventilation predator',\n * requiredFor: ['IntentIntakeAgent', 'requirements'],\n * })\n *\n * @example // override defaults where the topic demands it\n * defineReadinessSpec({\n * id: 'medical/dosing',\n * description: 'Dosing guidance for compounding pharmacy',\n * query: 'compounding dose schedule',\n * requiredFor: ['DosingAgent'],\n * importance: 'blocking',\n * freshness: 'daily',\n * sensitivity: 'private',\n * confidenceNeeded: 0.95,\n * minSources: 3,\n * })\n */\nexport function defineReadinessSpec(input: DefineReadinessSpecInput): KnowledgeReadinessSpec {\n return {\n ...READINESS_SPEC_DEFAULTS,\n ...input,\n }\n}\n\nexport interface BuildEvalKnowledgeBundleOptions {\n taskId: string\n index: KnowledgeIndex\n specs: KnowledgeReadinessSpec[]\n userAnswers?: Record<string, string>\n searchLimit?: number\n metadata?: Record<string, unknown>\n now?: Date\n}\n\nexport interface EvalKnowledgeBundleBuildResult {\n bundle: KnowledgeBundle\n report: KnowledgeReadinessReport\n requirements: KnowledgeRequirement[]\n searchResultsByRequirement: Record<string, KnowledgeSearchResult[]>\n questions: UserQuestion[]\n acquisitionPlans: DataAcquisitionPlan[]\n}\n\nexport function buildEvalKnowledgeBundle(\n options: BuildEvalKnowledgeBundleOptions,\n): EvalKnowledgeBundleBuildResult {\n const searchLimit = options.searchLimit ?? 5\n const now = options.now ?? new Date()\n const searchResultsByRequirement: Record<string, KnowledgeSearchResult[]> = {}\n const requirements = options.specs.map((spec) => {\n const results = searchKnowledge(options.index, spec.query, searchLimit)\n searchResultsByRequirement[spec.id] = results\n return requirementFromSearch(options.index, spec, results, now)\n })\n const report = scoreKnowledgeReadiness({\n taskId: options.taskId,\n requirements,\n userAnswers: options.userAnswers,\n evidenceIds: requirements.flatMap((requirement) => requirement.evidenceIds),\n claimIds: [],\n wikiPageIds: unique(\n requirements.flatMap((requirement) =>\n pageIdsFromResults(searchResultsByRequirement[requirement.id] ?? []),\n ),\n ),\n metadata: options.metadata,\n })\n const questions = userQuestionsForKnowledgeGaps(report.blockingMissingRequirements)\n const acquisitionPlans = acquisitionPlansForKnowledgeGaps([\n ...report.blockingMissingRequirements,\n ...report.nonBlockingGaps,\n ])\n\n return {\n bundle: report.bundle,\n report,\n requirements,\n searchResultsByRequirement,\n questions,\n acquisitionPlans,\n }\n}\n\nfunction requirementFromSearch(\n index: KnowledgeIndex,\n spec: KnowledgeReadinessSpec,\n results: KnowledgeSearchResult[],\n now: Date,\n): KnowledgeRequirement {\n const hitCount = results.length\n const sourceIds = unique(results.flatMap((result) => result.page.sourceIds))\n const sources = index.sources.filter((source) => sourceIds.includes(source.id))\n const bestScore = results[0]?.normalizedScore ?? 0\n const sourceCoverage = spec.minSources\n ? Math.min(1, sourceIds.length / spec.minSources)\n : sourceIds.length > 0\n ? 1\n : 0\n const hitCoverage = spec.minHits ? Math.min(1, hitCount / spec.minHits) : hitCount > 0 ? 1 : 0\n const freshness = sourceFreshness(sources, now)\n const currentConfidence = round(Math.min(bestScore, sourceCoverage, hitCoverage, freshness.score))\n\n return {\n id: spec.id,\n description: spec.description,\n requiredFor: spec.requiredFor,\n category: spec.category,\n acquisitionMode: spec.acquisitionMode,\n importance: spec.importance,\n freshness: spec.freshness,\n sensitivity: spec.sensitivity,\n confidenceNeeded: spec.confidenceNeeded,\n currentConfidence,\n evidenceIds: unique([\n ...sourceIds.map((sourceId) => `source:${sourceId}`),\n ...results.map((result) => `page:${result.page.id}`),\n ]),\n fallbackPolicy:\n spec.fallbackPolicy ?? (spec.importance === 'blocking' ? 'block' : 'continue_with_caveat'),\n metadata: {\n ...spec.metadata,\n query: spec.query,\n hitCount,\n sourceCount: sourceIds.length,\n bestNormalizedScore: bestScore,\n expiredSourceIds: freshness.expiredSourceIds,\n freshnessScore: freshness.score,\n validUntil: freshness.validUntil,\n lastVerifiedAt: freshness.lastVerifiedAt,\n },\n }\n}\n\nfunction sourceFreshness(\n sources: KnowledgeIndex['sources'],\n now: Date,\n): { score: number; validUntil?: string; lastVerifiedAt?: string; expiredSourceIds: string[] } {\n if (sources.length === 0) return { score: 0, expiredSourceIds: [] }\n const validUntilValues = sources\n .map(\n (source) =>\n source.validUntil ??\n stringMetadata(source.metadata, 'validUntil') ??\n stringMetadata(source.metadata, 'expiresAt'),\n )\n .filter(isIsoDate)\n const lastVerifiedValues = sources\n .map((source) => source.lastVerifiedAt ?? stringMetadata(source.metadata, 'lastVerifiedAt'))\n .filter(isIsoDate)\n const expiredSourceIds = sources\n .filter((source) => {\n const validUntil =\n source.validUntil ??\n stringMetadata(source.metadata, 'validUntil') ??\n stringMetadata(source.metadata, 'expiresAt')\n return validUntil ? Date.parse(validUntil) <= now.getTime() : false\n })\n .map((source) => source.id)\n return {\n score: expiredSourceIds.length > 0 ? 0 : 1,\n validUntil: earliestIso(validUntilValues),\n lastVerifiedAt: latestIso(lastVerifiedValues),\n expiredSourceIds,\n }\n}\n\nfunction isIsoDate(value: string | undefined): value is string {\n return Boolean(value && Number.isFinite(Date.parse(value)))\n}\n\nfunction earliestIso(values: string[]): string | undefined {\n return values.sort((a, b) => Date.parse(a) - Date.parse(b))[0]\n}\n\nfunction latestIso(values: string[]): string | undefined {\n return values.sort((a, b) => Date.parse(b) - Date.parse(a))[0]\n}\n\nfunction pageIdsFromResults(results: KnowledgeSearchResult[]): string[] {\n return results.map((result) => result.page.id)\n}\n\nfunction unique<T>(items: T[]): T[] {\n return [...new Set(items)]\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000\n}\n","import {\n type BuildEvalKnowledgeBundleOptions,\n buildEvalKnowledgeBundle,\n type EvalKnowledgeBundleBuildResult,\n type KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport type { KnowledgeIndex } from './types'\n\n/**\n * The subset of a research-loop options object the readiness gate needs:\n * the goal (default task id), the readiness specs, an optional task-id\n * override, and the rest of the bundle options minus the fields this helper\n * supplies (`taskId`/`index`/`specs`).\n *\n * Both the single-agent (`research-loop`) and two-agent (`two-agent-research-loop`)\n * options shapes satisfy this structurally, so the gate is single-sourced.\n */\nexport interface ReadinessGateOptions {\n goal: string\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n}\n\n/**\n * Build the readiness bundle for a loop run over the given index, or\n * `undefined` when no readiness specs are configured (no gate to report).\n */\nexport function readinessFor(\n options: ReadinessGateOptions,\n index: KnowledgeIndex,\n): EvalKnowledgeBundleBuildResult | undefined {\n if (!options.readinessSpecs?.length) return undefined\n return buildEvalKnowledgeBundle({\n ...(options.readiness ?? {}),\n taskId: options.readinessTaskId ?? options.goal,\n index,\n specs: options.readinessSpecs,\n })\n}\n","import type { JsonValue } from '@tangle-network/agent-eval/campaign'\nimport {\n type KnowledgeResearchLoopDecision,\n type KnowledgeResearchLoopResult,\n type RunKnowledgeResearchLoopOptions,\n runKnowledgeResearchLoop,\n} from './research-loop'\nimport {\n type RunRetrievalImprovementLoopOptions,\n type RunRetrievalImprovementLoopResult,\n runRetrievalImprovementLoop,\n} from './retrieval-eval'\n\nexport type RagKnowledgeImprovementPhase =\n | 'retrieval-tuning'\n | 'gap-diagnosis'\n | 'knowledge-acquisition'\n | 'knowledge-update'\n | 'answer-quality'\n | 'promotion'\n\nexport type RagKnowledgeImprovementPhaseStatus = 'completed' | 'skipped' | 'failed'\n\nexport type RagGapKind =\n | 'missing-source'\n | 'stale-source'\n | 'retrieval-miss'\n | 'retrieval-noise'\n | 'chunking-mismatch'\n | 'missing-multihop-evidence'\n | 'generator-unsupported-claim'\n | 'citation-mismatch'\n | 'incorrect-abstention'\n | 'unknown'\n\nexport type RagGapSeverity = 'info' | 'warning' | 'error' | 'critical'\n\nexport interface RagGapFinding {\n id: string\n kind: RagGapKind\n severity: RagGapSeverity\n message: string\n scenarioId?: string\n evidence?: Record<string, JsonValue>\n}\n\nexport interface RagKnowledgeImprovementPhaseResult {\n phase: RagKnowledgeImprovementPhase\n status: RagKnowledgeImprovementPhaseStatus\n summary: string\n startedAt: string\n finishedAt: string\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagPhaseInputBase {\n goal: string\n phases: readonly RagKnowledgeImprovementPhaseResult[]\n signal?: AbortSignal\n}\n\nexport interface RagDiagnosisInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n}\n\nexport interface RagKnowledgeAcquisitionInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n}\n\nexport interface RagKnowledgeUpdateInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n}\n\nexport interface RagKnowledgeUpdateResult {\n applied: boolean\n summary: string\n research?: KnowledgeResearchLoopResult\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagAnswerQualityInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n knowledgeUpdate?: RagKnowledgeUpdateResult\n}\n\nexport interface RagAnswerQualityResult {\n passed: boolean\n metrics: Record<string, number>\n findings?: readonly RagGapFinding[]\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagPromotionInput extends RagPhaseInputBase {\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n knowledgeUpdate?: RagKnowledgeUpdateResult\n answerQuality?: RagAnswerQualityResult\n}\n\nexport interface RagPromotionResult {\n promoted: boolean\n reason: string\n metadata?: Record<string, JsonValue>\n}\n\nexport interface RagKnowledgeResearchOptions\n extends Omit<RunKnowledgeResearchLoopOptions, 'goal' | 'signal' | 'step'> {\n goal?: string\n step?: RunKnowledgeResearchLoopOptions['step']\n}\n\nexport interface RunRagKnowledgeImprovementLoopOptions {\n goal: string\n retrieval?: RunRetrievalImprovementLoopOptions\n diagnose?: (input: RagDiagnosisInput) => MaybePromise<readonly RagGapFinding[]>\n acquireKnowledge?: (\n input: RagKnowledgeAcquisitionInput,\n ) => MaybePromise<KnowledgeResearchLoopDecision>\n knowledgeResearch?: RagKnowledgeResearchOptions\n updateKnowledge?: (input: RagKnowledgeUpdateInput) => MaybePromise<RagKnowledgeUpdateResult>\n evaluateAnswers?: (input: RagAnswerQualityInput) => MaybePromise<RagAnswerQualityResult>\n promote?: (input: RagPromotionInput) => MaybePromise<RagPromotionResult>\n enabledPhases?: readonly RagKnowledgeImprovementPhase[]\n requiredPhases?: readonly RagKnowledgeImprovementPhase[]\n signal?: AbortSignal\n now?: () => Date\n}\n\nexport interface RunRagKnowledgeImprovementLoopResult {\n goal: string\n phases: readonly RagKnowledgeImprovementPhaseResult[]\n retrieval?: RunRetrievalImprovementLoopResult\n findings: readonly RagGapFinding[]\n acquisition?: KnowledgeResearchLoopDecision\n knowledgeUpdate?: RagKnowledgeUpdateResult\n answerQuality?: RagAnswerQualityResult\n promotion?: RagPromotionResult\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport async function runRagKnowledgeImprovementLoop(\n options: RunRagKnowledgeImprovementLoopOptions,\n): Promise<RunRagKnowledgeImprovementLoopResult> {\n assertConfiguredRequiredPhases(options)\n const now = options.now ?? (() => new Date())\n const phases: RagKnowledgeImprovementPhaseResult[] = []\n let retrieval: RunRetrievalImprovementLoopResult | undefined\n let findings: RagGapFinding[] = []\n let acquisition: KnowledgeResearchLoopDecision | undefined\n let knowledgeUpdate: RagKnowledgeUpdateResult | undefined\n let answerQuality: RagAnswerQualityResult | undefined\n let promotion: RagPromotionResult | undefined\n\n if (phaseEnabled(options, 'retrieval-tuning')) {\n if (options.retrieval) {\n retrieval = await runPhase(\n phases,\n now,\n 'retrieval-tuning',\n async () => {\n assertNotAborted(options.signal)\n return runRetrievalImprovementLoop(options.retrieval!)\n },\n summarizeRetrievalResult,\n )\n } else {\n skipPhase(phases, now, 'retrieval-tuning', 'no retrieval options provided')\n }\n }\n\n if (phaseEnabled(options, 'gap-diagnosis')) {\n if (options.diagnose) {\n findings = [\n ...(await runPhase(\n phases,\n now,\n 'gap-diagnosis',\n async () => {\n assertNotAborted(options.signal)\n return options.diagnose!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n })\n },\n (diagnosed) => `${diagnosed.length} finding(s)`,\n )),\n ]\n } else {\n skipPhase(phases, now, 'gap-diagnosis', 'no diagnosis hook provided')\n }\n }\n\n if (phaseEnabled(options, 'knowledge-acquisition')) {\n if (options.acquireKnowledge) {\n acquisition = await runPhase(\n phases,\n now,\n 'knowledge-acquisition',\n async () => {\n assertNotAborted(options.signal)\n return options.acquireKnowledge!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n })\n },\n summarizeAcquisitionDecision,\n )\n } else {\n skipPhase(phases, now, 'knowledge-acquisition', 'no acquisition hook provided')\n }\n }\n\n if (phaseEnabled(options, 'knowledge-update')) {\n if (options.updateKnowledge) {\n knowledgeUpdate = await runPhase(\n phases,\n now,\n 'knowledge-update',\n async () => {\n assertNotAborted(options.signal)\n return options.updateKnowledge!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n acquisition,\n })\n },\n (result) => result.summary,\n )\n } else if (options.knowledgeResearch) {\n knowledgeUpdate = await runPhase(\n phases,\n now,\n 'knowledge-update',\n async () => {\n assertNotAborted(options.signal)\n return runKnowledgeResearchUpdate(options, acquisition)\n },\n (result) => result.summary,\n )\n } else {\n skipPhase(phases, now, 'knowledge-update', 'no update hook or research loop provided')\n }\n }\n\n if (phaseEnabled(options, 'answer-quality')) {\n if (options.evaluateAnswers) {\n answerQuality = await runPhase(\n phases,\n now,\n 'answer-quality',\n async () => {\n assertNotAborted(options.signal)\n return options.evaluateAnswers!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n acquisition,\n knowledgeUpdate,\n })\n },\n summarizeAnswerQuality,\n )\n findings = [...findings, ...(answerQuality.findings ?? [])]\n } else {\n skipPhase(phases, now, 'answer-quality', 'no answer-quality hook provided')\n }\n }\n\n if (phaseEnabled(options, 'promotion')) {\n if (options.promote) {\n promotion = await runPhase(\n phases,\n now,\n 'promotion',\n async () => {\n assertNotAborted(options.signal)\n return options.promote!({\n goal: options.goal,\n phases,\n signal: options.signal,\n retrieval,\n findings,\n acquisition,\n knowledgeUpdate,\n answerQuality,\n })\n },\n (result) => `${result.promoted ? 'promoted' : 'held'}: ${result.reason}`,\n )\n } else {\n skipPhase(phases, now, 'promotion', 'no promotion hook provided')\n }\n }\n\n return {\n goal: options.goal,\n phases,\n retrieval,\n findings,\n acquisition,\n knowledgeUpdate,\n answerQuality,\n promotion,\n }\n}\n\nasync function runKnowledgeResearchUpdate(\n options: RunRagKnowledgeImprovementLoopOptions,\n acquisition: KnowledgeResearchLoopDecision | undefined,\n): Promise<RagKnowledgeUpdateResult> {\n const research = options.knowledgeResearch\n if (!research) {\n throw new Error('knowledgeResearch options are required to run the knowledge update phase')\n }\n const { goal, step, ...rest } = research\n const researchStep = step ?? acquisitionBackedResearchStep(acquisition)\n const maxIterations = step ? rest.maxIterations : 1\n const result = await runKnowledgeResearchLoop({\n ...rest,\n goal: goal ?? options.goal,\n maxIterations,\n signal: options.signal,\n step: researchStep,\n })\n return {\n applied: result.steps.some((stepResult) => {\n return stepResult.addedSources.length > 0 || Boolean(stepResult.applied)\n }),\n summary: `${result.iterations} research iteration(s); done=${String(result.done)}`,\n research: result,\n }\n}\n\nfunction acquisitionBackedResearchStep(\n acquisition: KnowledgeResearchLoopDecision | undefined,\n): RunKnowledgeResearchLoopOptions['step'] {\n if (!acquisition) {\n throw new Error(\n 'knowledgeResearch requires either a step hook or a knowledge-acquisition result to apply',\n )\n }\n return () => ({ ...acquisition, done: acquisition.done ?? true })\n}\n\nasync function runPhase<T>(\n phases: RagKnowledgeImprovementPhaseResult[],\n now: () => Date,\n phase: RagKnowledgeImprovementPhase,\n action: () => MaybePromise<T>,\n summarize: (result: T) => string,\n): Promise<T> {\n const startedAt = now().toISOString()\n try {\n const result = await action()\n phases.push({\n phase,\n status: 'completed',\n summary: summarize(result),\n startedAt,\n finishedAt: now().toISOString(),\n })\n return result\n } catch (error) {\n phases.push({\n phase,\n status: 'failed',\n summary: (error as Error).message,\n startedAt,\n finishedAt: now().toISOString(),\n })\n throw error\n }\n}\n\nfunction skipPhase(\n phases: RagKnowledgeImprovementPhaseResult[],\n now: () => Date,\n phase: RagKnowledgeImprovementPhase,\n summary: string,\n): void {\n const timestamp = now().toISOString()\n phases.push({ phase, status: 'skipped', summary, startedAt: timestamp, finishedAt: timestamp })\n}\n\nfunction summarizeRetrievalResult(result: RunRetrievalImprovementLoopResult): string {\n return `${result.candidates.length} candidate(s); winner=${JSON.stringify(result.winnerConfig)}`\n}\n\nfunction summarizeAcquisitionDecision(decision: KnowledgeResearchLoopDecision): string {\n const sourcePathCount = decision.sourcePaths?.length ?? 0\n const sourceTextCount = decision.sourceTexts?.length ?? 0\n const proposal = decision.proposalText ? 'proposal' : 'no proposal'\n return `${sourcePathCount} path source(s), ${sourceTextCount} text source(s), ${proposal}`\n}\n\nfunction summarizeAnswerQuality(result: RagAnswerQualityResult): string {\n const metrics = Object.entries(result.metrics)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, value]) => `${key}=${formatMetric(value)}`)\n .join(', ')\n return `${result.passed ? 'passed' : 'failed'}${metrics ? `; ${metrics}` : ''}`\n}\n\nfunction formatMetric(value: number): string {\n return Number.isFinite(value) ? value.toFixed(3) : String(value)\n}\n\nfunction phaseEnabled(\n options: RunRagKnowledgeImprovementLoopOptions,\n phase: RagKnowledgeImprovementPhase,\n): boolean {\n return !options.enabledPhases || options.enabledPhases.includes(phase)\n}\n\nfunction assertConfiguredRequiredPhases(options: RunRagKnowledgeImprovementLoopOptions): void {\n for (const phase of options.requiredPhases ?? []) {\n if (!phaseEnabled(options, phase)) {\n throw new Error(`required phase ${phase} is not enabled`)\n }\n if (!phaseConfigured(options, phase)) {\n throw new Error(requiredPhaseMessage(phase))\n }\n }\n}\n\nfunction phaseConfigured(\n options: RunRagKnowledgeImprovementLoopOptions,\n phase: RagKnowledgeImprovementPhase,\n): boolean {\n switch (phase) {\n case 'retrieval-tuning':\n return Boolean(options.retrieval)\n case 'gap-diagnosis':\n return Boolean(options.diagnose)\n case 'knowledge-acquisition':\n return Boolean(options.acquireKnowledge)\n case 'knowledge-update':\n return Boolean(options.updateKnowledge ?? options.knowledgeResearch)\n case 'answer-quality':\n return Boolean(options.evaluateAnswers)\n case 'promotion':\n return Boolean(options.promote)\n }\n}\n\nfunction requiredPhaseMessage(phase: RagKnowledgeImprovementPhase): string {\n switch (phase) {\n case 'retrieval-tuning':\n return 'required phase retrieval-tuning requires retrieval options'\n case 'gap-diagnosis':\n return 'required phase gap-diagnosis requires a diagnose hook'\n case 'knowledge-acquisition':\n return 'required phase knowledge-acquisition requires an acquireKnowledge hook'\n case 'knowledge-update':\n return 'required phase knowledge-update requires updateKnowledge or knowledgeResearch'\n case 'answer-quality':\n return 'required phase answer-quality requires an evaluateAnswers hook'\n case 'promotion':\n return 'required phase promotion requires a promote hook'\n }\n}\n\nfunction assertNotAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new Error('RAG knowledge improvement loop aborted')\n }\n}\n","import type { KnowledgeFragment } from './sources/types'\n\n/**\n * Change detection across snapshots of one source's fragments.\n *\n * The output drives the continuous-ingestion loop: each `KnowledgeChange`\n * carries the eval dimensions affected (`affectedDimensions`), which an\n * agent-eval campaign scheduler consumes to decide which campaigns to\n * re-run. Three change kinds:\n *\n * - `added` — fragment id appears in `next` but not `prev`.\n * - `removed` — fragment id appears in `prev` but not `next`. Typical\n * trigger: an authority retires a Wex slug, or a state SOS reorganises\n * its forms catalogue.\n * - `modified` — fragment id appears in both, body hash differs. This\n * is the dominant change kind in practice — the Ryan-LLC v. FTC\n * vacatur case manifests as a `modified` on the Wex non-compete\n * fragment, NOT as a removed one.\n *\n * Unverifiable fragments are filtered out before diffing — comparing a\n * captcha-blocked snapshot against a real one would falsely fire every\n * fragment as removed. The caller can inspect the raw lists if they want\n * to surface block-page failures.\n *\n * Within-snapshot duplicate ids are an upstream bug; this function picks\n * the LAST one and emits a diagnostic via the `warnings` field.\n *\n * @stable\n */\n\nexport type KnowledgeChangeKind = 'added' | 'removed' | 'modified'\n\nexport interface KnowledgeChange {\n /** Source-scoped id (matches `KnowledgeFragment.id`). */\n fragmentId: string\n kind: KnowledgeChangeKind\n /**\n * For `added`: full body of the new fragment.\n * For `removed`: full body of the prior fragment.\n * For `modified`: unified-diff-style payload `{ before, after }` body strings.\n */\n diff?: { before?: string; after?: string }\n /**\n * Eval dimensions to re-score. Computed as the union of both fragments'\n * `dimensionHints`. The eval cron treats this as a set of campaign tags.\n */\n affectedDimensions: string[]\n /** URL of the affected authority page (from whichever side has it). */\n url?: string\n /**\n * Source-attested change time. For `modified`, takes the NEXT fragment's\n * `sourceUpdatedAt`. For `removed`, takes the PRIOR fragment's\n * `sourceUpdatedAt`. For `added`, takes the NEXT fragment's\n * `sourceUpdatedAt`. Consumers index changes by this date.\n */\n detectedAt: string\n}\n\nexport interface DetectChangesResult {\n changes: KnowledgeChange[]\n /** Counts by kind — handy for dashboards. */\n summary: { added: number; removed: number; modified: number }\n /** Non-fatal diagnostics (duplicate ids, dropped unverifiable fragments). */\n warnings: string[]\n}\n\nexport interface DetectChangesOptions {\n /**\n * When true (default), unverifiable fragments are dropped from both\n * sides before comparison. Set false ONLY when debugging block-page\n * issues — comparing against unverifiable content emits false\n * `removed`/`modified` changes.\n */\n skipUnverifiable?: boolean\n /**\n * When provided, only changes whose `affectedDimensions` intersect this\n * set are returned. Useful for cron loops that schedule per-dimension\n * eval campaigns and only care about a subset.\n */\n filterDimensions?: string[]\n}\n\nexport function detectChanges(\n prev: KnowledgeFragment[],\n next: KnowledgeFragment[],\n options: DetectChangesOptions = {},\n): DetectChangesResult {\n const skipUnverifiable = options.skipUnverifiable ?? true\n const warnings: string[] = []\n\n const { map: prevMap, warnings: prevWarn } = indexFragments(prev, skipUnverifiable, 'prev')\n const { map: nextMap, warnings: nextWarn } = indexFragments(next, skipUnverifiable, 'next')\n warnings.push(...prevWarn, ...nextWarn)\n\n const changes: KnowledgeChange[] = []\n const seen = new Set<string>()\n\n for (const [id, nextFragment] of nextMap) {\n seen.add(id)\n const prevFragment = prevMap.get(id)\n if (!prevFragment) {\n changes.push({\n fragmentId: id,\n kind: 'added',\n diff: { after: nextFragment.body },\n affectedDimensions: dedup(nextFragment.dimensionHints),\n url: nextFragment.provenance.url,\n detectedAt: nextFragment.provenance.sourceUpdatedAt,\n })\n continue\n }\n if (prevFragment.bodyHash !== nextFragment.bodyHash) {\n changes.push({\n fragmentId: id,\n kind: 'modified',\n diff: { before: prevFragment.body, after: nextFragment.body },\n affectedDimensions: dedup([...prevFragment.dimensionHints, ...nextFragment.dimensionHints]),\n url: nextFragment.provenance.url,\n detectedAt: nextFragment.provenance.sourceUpdatedAt,\n })\n }\n }\n\n for (const [id, prevFragment] of prevMap) {\n if (seen.has(id)) continue\n changes.push({\n fragmentId: id,\n kind: 'removed',\n diff: { before: prevFragment.body },\n affectedDimensions: dedup(prevFragment.dimensionHints),\n url: prevFragment.provenance.url,\n detectedAt: prevFragment.provenance.sourceUpdatedAt,\n })\n }\n\n const filtered = options.filterDimensions\n ? changes.filter((c) => c.affectedDimensions.some((d) => options.filterDimensions?.includes(d)))\n : changes\n\n return {\n changes: filtered,\n summary: {\n added: filtered.filter((c) => c.kind === 'added').length,\n removed: filtered.filter((c) => c.kind === 'removed').length,\n modified: filtered.filter((c) => c.kind === 'modified').length,\n },\n warnings,\n }\n}\n\nfunction indexFragments(\n fragments: KnowledgeFragment[],\n skipUnverifiable: boolean,\n side: string,\n): { map: Map<string, KnowledgeFragment>; warnings: string[] } {\n const map = new Map<string, KnowledgeFragment>()\n const warnings: string[] = []\n let dropped = 0\n for (const fragment of fragments) {\n if (skipUnverifiable && !fragment.provenance.verifiable) {\n dropped += 1\n continue\n }\n if (map.has(fragment.id)) {\n warnings.push(`${side}: duplicate fragment id ${fragment.id} — keeping last`)\n }\n map.set(fragment.id, fragment)\n }\n if (dropped > 0) {\n warnings.push(`${side}: dropped ${dropped} unverifiable fragment(s) before diff`)\n }\n return { map, warnings }\n}\n\nfunction dedup<T>(items: T[]): T[] {\n return [...new Set(items)]\n}\n","export interface ChunkingOptions {\n targetChars: number\n maxChars: number\n minChars: number\n overlapChars: number\n}\n\nexport interface KnowledgeChunk {\n index: number\n text: string\n headingPath: string\n charStart: number\n charEnd: number\n oversized: boolean\n}\n\nconst DEFAULT_OPTIONS: ChunkingOptions = {\n targetChars: 1000,\n maxChars: 1500,\n minChars: 160,\n overlapChars: 180,\n}\n\nexport function chunkMarkdown(\n content: string,\n options?: Partial<ChunkingOptions>,\n): KnowledgeChunk[] {\n const opts = normalizeOptions({ ...DEFAULT_OPTIONS, ...(options ?? {}) })\n const { body, bodyOffset } = stripFrontmatter(content)\n if (body.trim() === '') return []\n\n const sections = splitSections(body, bodyOffset)\n const chunks: KnowledgeChunk[] = []\n for (const section of sections) {\n for (const part of chunkText(section.text, opts)) {\n const start = section.start + part.start\n chunks.push({\n index: chunks.length,\n text: part.text,\n headingPath: section.headingPath,\n charStart: start,\n charEnd: start + part.text.length,\n oversized: part.text.length > opts.maxChars,\n })\n }\n }\n return chunks\n}\n\nexport function stripFrontmatter(content: string): { body: string; bodyOffset: number } {\n const normalized = content.replace(/\\r\\n/g, '\\n')\n if (!normalized.startsWith('---\\n')) return { body: normalized, bodyOffset: 0 }\n const match = /^---\\n[\\s\\S]*?\\n---\\s*\\n?/.exec(normalized)\n if (!match) return { body: normalized, bodyOffset: 0 }\n return { body: normalized.slice(match[0].length), bodyOffset: match[0].length }\n}\n\nfunction normalizeOptions(opts: ChunkingOptions): ChunkingOptions {\n if (opts.maxChars < opts.targetChars) opts.maxChars = opts.targetChars\n if (opts.overlapChars >= opts.targetChars) opts.overlapChars = Math.floor(opts.targetChars / 2)\n return opts\n}\n\ninterface Section {\n text: string\n start: number\n headingPath: string\n}\n\nfunction splitSections(body: string, bodyOffset: number): Section[] {\n const lines = body.split('\\n')\n const sections: Section[] = []\n const headings: Record<number, string> = {}\n let current: { lines: string[]; start: number; headingPath: string } = {\n lines: [],\n start: bodyOffset,\n headingPath: '',\n }\n let cursor = bodyOffset\n let fence: string | null = null\n\n const flush = () => {\n const text = current.lines.join('\\n')\n if (text.trim() !== '')\n sections.push({ text, start: current.start, headingPath: current.headingPath })\n }\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n const lineLen = line.length + (i < lines.length - 1 ? 1 : 0)\n const fenceMatch = /^(`{3,}|~{3,})/.exec(line)\n if (fenceMatch) {\n const marker = fenceMatch[1]!\n fence = fence === null ? marker : line.startsWith(fence) ? null : fence\n current.lines.push(line)\n cursor += lineLen\n continue\n }\n const heading = fence === null ? /^(#{1,6})\\s+(.+?)\\s*$/.exec(line) : null\n if (heading) {\n flush()\n const level = heading[1]!.length\n headings[level] = heading[2]!.trim()\n for (let next = level + 1; next <= 6; next++) delete headings[next]\n current = {\n lines: [line],\n start: cursor,\n headingPath: Object.entries(headings)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([levelText, title]) => `${'#'.repeat(Number(levelText))} ${title}`)\n .join(' > '),\n }\n cursor += lineLen\n continue\n }\n current.lines.push(line)\n cursor += lineLen\n }\n flush()\n return sections\n}\n\nfunction chunkText(text: string, opts: ChunkingOptions): Array<{ text: string; start: number }> {\n if (text.length <= opts.targetChars) return [{ text, start: 0 }]\n const atoms = splitAtoms(text)\n const chunks: Array<{ text: string; start: number }> = []\n let buffer = ''\n let bufferStart = 0\n for (const atom of atoms) {\n if (buffer === '') bufferStart = atom.start\n if (buffer.length > 0 && buffer.length + atom.text.length > opts.targetChars) {\n chunks.push({ text: buffer.trimEnd(), start: bufferStart })\n const overlap = buffer.slice(Math.max(0, buffer.length - opts.overlapChars))\n buffer = overlap + atom.text\n bufferStart = Math.max(bufferStart, atom.start - overlap.length)\n } else {\n buffer += atom.text\n }\n }\n if (buffer.trim() !== '') chunks.push({ text: buffer.trimEnd(), start: bufferStart })\n return mergeTinyChunks(chunks, opts)\n}\n\nfunction splitAtoms(text: string): Array<{ text: string; start: number }> {\n const parts: Array<{ text: string; start: number }> = []\n const paragraphs = text.split(/(\\n\\s*\\n)/)\n let cursor = 0\n for (let i = 0; i < paragraphs.length; i += 2) {\n const paragraph = (paragraphs[i] ?? '') + (paragraphs[i + 1] ?? '')\n if (paragraph === '') continue\n parts.push({ text: paragraph, start: cursor })\n cursor += paragraph.length\n }\n return parts\n}\n\nfunction mergeTinyChunks(\n chunks: Array<{ text: string; start: number }>,\n opts: ChunkingOptions,\n): Array<{ text: string; start: number }> {\n const out: Array<{ text: string; start: number }> = []\n for (const chunk of chunks) {\n const prev = out[out.length - 1]\n if (\n prev &&\n chunk.text.length < opts.minChars &&\n prev.text.length + chunk.text.length <= opts.maxChars\n ) {\n prev.text = `${prev.text}\\n\\n${chunk.text}`\n } else {\n out.push({ ...chunk })\n }\n }\n return out\n}\n","/**\n * The SINGLE-AGENT COLLECTION driver — the blind-collection baseline (Arm A).\n *\n * This is the honest null the depth A/B is measured against. The other drivers\n * spend extra inference to do something differentiated:\n * - `createVerifyingResearchDriver` runs an LLM gate per source (Arm B),\n * - `createResearchDrivingDriver` extracts claims, tracks corroboration, and\n * synthesizes deep follow-up questions to drive depth (Arm C).\n *\n * This driver does NONE of that. It is a pass-through: it accepts every source\n * the worker proposes and contributes no research, no gating, and no steering of\n * its own. The loop still dedups exact-uri duplicates before calling\n * `verifySource` (that is the loop's job, not the driver's), and the default\n * `foldGaps` (a plain bulleted list of the still-open readiness gaps) still folds\n * the gaps into the worker's next prompt — so the worker keeps researching, but\n * NOTHING intelligent sits between the worker and the knowledge base.\n *\n * In other words: ONE agent (the worker) collects sources round after round, and\n * the \"driver\" is an inert rubber stamp. That is exactly what \"single-agent\n * collection\" means — the topology with zero coordinator intelligence — so its\n * material-facts score is the floor every other arm must beat to justify its\n * extra inference cost.\n *\n * It adds NO router calls of its own: `verifySource` is a synchronous accept and\n * `foldGaps` is omitted so the loop uses its built-in gap list. So Arm A's cost\n * is the worker's cost alone — the cleanest possible blind-collection baseline.\n */\n\nimport type {\n ResearchDriver,\n ResearchSourceProposal,\n SourceVerdict,\n} from './two-agent-research-loop'\n\n/**\n * Build the single-agent collection driver. Accepts every source; never gates,\n * never researches, never steers beyond the loop's default open-gap list. The\n * worker is the only agent that thinks.\n */\nexport function createCollectionResearchDriver(): ResearchDriver {\n return {\n verifySource(_source: ResearchSourceProposal): SourceVerdict {\n return { accept: true }\n },\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\n\nexport interface DiscoveryTask {\n id: string\n goal: string\n query?: string\n sourceHints?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface DiscoveryResult {\n taskId: string\n summary: string\n sourceUris?: string[]\n claims?: Array<{ text: string; sourceUri?: string; confidence?: number }>\n followUpTasks?: DiscoveryTask[]\n metadata?: Record<string, unknown>\n}\n\nexport interface KnowledgeDiscoveryWorker {\n run(task: DiscoveryTask, signal?: AbortSignal): Promise<DiscoveryResult> | DiscoveryResult\n}\n\nexport interface KnowledgeDiscoveryDispatcher {\n dispatch(\n tasks: DiscoveryTask[],\n options?: {\n concurrency?: number\n signal?: AbortSignal\n },\n ): Promise<DiscoveryResult[]>\n}\n\nexport type DiscoveryLoopStopReason = 'complete' | 'max-rounds' | 'max-tasks' | 'aborted'\n\nexport interface DiscoveryLoopRound {\n round: number\n tasks: DiscoveryTask[]\n results: DiscoveryResult[]\n queuedFollowUps: DiscoveryTask[]\n}\n\nexport interface DiscoveryLoopResult {\n stopReason: DiscoveryLoopStopReason\n tasksDispatched: number\n results: DiscoveryResult[]\n rounds: DiscoveryLoopRound[]\n /** Tasks retained, not dropped, when a configured limit stops the loop. */\n pendingTasks: DiscoveryTask[]\n /** Structurally identical task identities ignored to prevent cycles. */\n duplicateTaskIds: string[]\n}\n\nexport interface RunDiscoveryLoopOptions {\n dispatcher: KnowledgeDiscoveryDispatcher\n initialTasks: readonly DiscoveryTask[]\n /** Maximum follow-up depth including the initial dispatch. Default 3. */\n maxRounds?: number\n /** Maximum tasks dispatched across all rounds. Default 24. */\n maxTasks?: number\n /** Forwarded to the dispatcher. Default 4. */\n concurrency?: number\n signal?: AbortSignal\n onRound?: (round: DiscoveryLoopRound) => Promise<void> | void\n}\n\n/**\n * Dispatch discovery tasks and recursively pursue worker-proposed follow-ups.\n *\n * The runner owns only bounded scheduling and accounting. Workers own search,\n * source verification, and domain-specific candidate shapes.\n */\nexport async function runDiscoveryLoop(\n options: RunDiscoveryLoopOptions,\n): Promise<DiscoveryLoopResult> {\n const maxRounds = positiveInteger(options.maxRounds ?? 3, 'maxRounds')\n const maxTasks = positiveInteger(options.maxTasks ?? 24, 'maxTasks')\n const concurrency = positiveInteger(options.concurrency ?? 4, 'concurrency')\n const known = new Map<string, DiscoveryTask>()\n const pending: DiscoveryTask[] = []\n const duplicateTaskIds = new Set<string>()\n enqueueTasks(options.initialTasks, known, pending, duplicateTaskIds)\n\n const rounds: DiscoveryLoopRound[] = []\n const results: DiscoveryResult[] = []\n let tasksDispatched = 0\n let aborted = false\n\n while (pending.length > 0 && rounds.length < maxRounds && tasksDispatched < maxTasks) {\n if (options.signal?.aborted) {\n aborted = true\n break\n }\n const capacity = maxTasks - tasksDispatched\n const tasks = pending.splice(0, capacity)\n let dispatched: DiscoveryResult[]\n try {\n dispatched = orderCompleteDispatch(\n tasks,\n await options.dispatcher.dispatch(tasks, {\n concurrency,\n signal: options.signal,\n }),\n )\n } catch (cause) {\n if (!options.signal?.aborted) throw cause\n pending.unshift(...tasks)\n aborted = true\n break\n }\n tasksDispatched += tasks.length\n results.push(...dispatched)\n\n const queuedFollowUps: DiscoveryTask[] = []\n for (const result of dispatched) {\n enqueueTasks(result.followUpTasks ?? [], known, queuedFollowUps, duplicateTaskIds)\n }\n pending.push(...queuedFollowUps)\n const round: DiscoveryLoopRound = {\n round: rounds.length + 1,\n tasks,\n results: dispatched,\n queuedFollowUps,\n }\n rounds.push(round)\n await options.onRound?.(round)\n if (options.signal?.aborted) {\n aborted = true\n break\n }\n }\n\n const stopReason: DiscoveryLoopStopReason = aborted\n ? 'aborted'\n : pending.length === 0\n ? 'complete'\n : tasksDispatched >= maxTasks\n ? 'max-tasks'\n : 'max-rounds'\n return {\n stopReason,\n tasksDispatched,\n results,\n rounds,\n pendingTasks: pending,\n duplicateTaskIds: [...duplicateTaskIds],\n }\n}\n\nexport function createLocalDiscoveryDispatcher(\n worker: KnowledgeDiscoveryWorker,\n): KnowledgeDiscoveryDispatcher {\n return {\n async dispatch(tasks, options = {}) {\n const concurrency = Math.max(1, options.concurrency ?? 4)\n const results: DiscoveryResult[] = []\n let cursor = 0\n async function runNext(): Promise<void> {\n while (cursor < tasks.length) {\n if (options.signal?.aborted) throw new Error('Discovery dispatch aborted')\n const task = tasks[cursor++]!\n results.push(await worker.run(task, options.signal))\n }\n }\n await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, runNext))\n return orderCompleteDispatch(tasks, results)\n },\n }\n}\n\nfunction enqueueTasks(\n tasks: readonly DiscoveryTask[],\n known: Map<string, DiscoveryTask>,\n destination: DiscoveryTask[],\n duplicateTaskIds: Set<string>,\n): void {\n for (const task of tasks) {\n assertTask(task)\n const prior = known.get(task.id)\n if (!prior) {\n known.set(task.id, task)\n destination.push(task)\n continue\n }\n if (!isDeepStrictEqual(prior, task)) {\n throw new Error(`Discovery task id '${task.id}' refers to conflicting tasks`)\n }\n duplicateTaskIds.add(task.id)\n }\n}\n\nfunction assertTask(task: DiscoveryTask): void {\n if (!task.id.trim()) throw new Error('Discovery task id must not be empty')\n if (!task.goal.trim()) throw new Error(`Discovery task '${task.id}' goal must not be empty`)\n}\n\nfunction orderCompleteDispatch(\n tasks: readonly DiscoveryTask[],\n results: readonly DiscoveryResult[],\n): DiscoveryResult[] {\n const order = new Map(tasks.map((task, index) => [task.id, index]))\n const received = new Set<string>()\n for (const result of results) {\n if (!order.has(result.taskId)) {\n throw new Error(`Discovery dispatcher returned unknown task '${result.taskId}'`)\n }\n if (received.has(result.taskId)) {\n throw new Error(`Discovery dispatcher returned task '${result.taskId}' more than once`)\n }\n received.add(result.taskId)\n }\n const missing = tasks.filter((task) => !received.has(task.id)).map((task) => task.id)\n if (missing.length > 0) {\n throw new Error(`Discovery dispatcher omitted tasks: ${missing.join(', ')}`)\n }\n return [...results].sort(\n (a, b) => (order.get(a.taskId) as number) - (order.get(b.taskId) as number),\n )\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`Discovery loop ${name} must be a positive integer`)\n }\n return value\n}\n","import { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { z } from 'zod'\nimport { isMissingFile, writeJsonDurableWithinRoot } from './durable-fs'\nimport { withKnowledgeMutation, withKnowledgeRead } from './mutation-lock'\n\n/**\n * Knowledge freshness store: tracks when each `(workspaceId, sourceId)` pair\n * was last successfully refreshed, and reports staleness against a TTL.\n *\n * The contract is intentionally minimal — just enough to drive a cron loop:\n *\n * ```ts\n * const store = createFileSystemFreshnessStore({ root: '.agent-knowledge' })\n * for (const source of sources) {\n * if (await store.stale({ workspaceId, sourceId: source.id, ttlMs: DAY })) {\n * const fragments = await source.fetch({ cacheDir })\n * await persistFragments(fragments)\n * await store.mark({ workspaceId, sourceId: source.id, when: new Date() })\n * }\n * }\n * ```\n *\n * Per-tenant isolation is enforced by `workspaceId` keying — there is no\n * global mutable state across workspaces.\n *\n * Two adapters ship in-package:\n *\n * - `createFileSystemFreshnessStore` — JSON file under the knowledge root,\n * mirrors the layout convention already used by `sources.json`.\n * - `createD1FreshnessStoreStub` — adapter scaffold for Cloudflare D1 /\n * Postgres. Production consumers should implement the `D1Adapter`\n * interface inside their own app; this stub exists to anchor the shape.\n *\n * @stable contract — interface is frozen at 0.x within this major.\n * @stable filesystem adapter\n * @experimental D1 stub — interface will evolve as real consumers wire it.\n */\n\n/** Identity for one freshness record. */\nexport interface FreshnessKey {\n workspaceId: string\n sourceId: string\n}\n\n/** TTL bound for staleness checks. */\nexport interface FreshnessTtl extends FreshnessKey {\n /** Milliseconds — `Date.now() - last() > ttlMs` ⇒ stale. */\n ttlMs: number\n /** Injected clock for deterministic tests; defaults to system time. */\n now?: Date\n}\n\n/** Mark argument. */\nexport interface FreshnessMark extends FreshnessKey {\n when: Date\n /** Optional content hash captured at refresh time; aids debugging. */\n contentHash?: string\n}\n\nexport interface KnowledgeFreshnessStore {\n /** Last refresh time, or null if never refreshed. */\n last(key: FreshnessKey): Promise<Date | null>\n /** Record a successful refresh. */\n mark(input: FreshnessMark): Promise<void>\n /** True iff `last(key)` is null or older than `ttlMs`. */\n stale(input: FreshnessTtl): Promise<boolean>\n /** All records for a workspace — useful for dashboards / debugging. */\n list(workspaceId: string): Promise<FreshnessRecord[]>\n}\n\nexport interface FreshnessRecord {\n workspaceId: string\n sourceId: string\n lastRefreshedAt: string\n contentHash?: string\n}\n\nexport interface FileSystemFreshnessStoreOptions {\n /**\n * Knowledge root. The store writes to `<root>/.agent-knowledge/freshness.json`,\n * mirroring the convention used by `sources.json`.\n */\n root: string\n}\n\nconst freshnessRecordSchema = z\n .object({\n workspaceId: z.string().min(1),\n sourceId: z.string().min(1),\n lastRefreshedAt: z.iso.datetime(),\n contentHash: z.string().min(1).optional(),\n })\n .strict()\nconst freshnessFileSchema = z\n .object({ records: z.record(z.string(), freshnessRecordSchema) })\n .strict()\n\n/**\n * Filesystem-backed implementation. Single JSON file per knowledge root,\n * indexed by `${workspaceId}::${sourceId}`. Reads parse on every call —\n * cron tick rate is well below the cost of one JSON parse.\n *\n * Writes share the package-wide filesystem lock, so multiple workers cannot\n * overwrite one another or run through an interrupted knowledge promotion.\n */\nexport function createFileSystemFreshnessStore(\n options: FileSystemFreshnessStoreOptions,\n): KnowledgeFreshnessStore {\n const path = join(options.root, '.agent-knowledge', 'freshness.json')\n\n const read = async (): Promise<Record<string, FreshnessRecord>> => {\n return withKnowledgeRead(options.root, async () => {\n try {\n return freshnessFileSchema.parse(JSON.parse(await readFile(path, 'utf8'))).records\n } catch (error) {\n if (isMissingFile(error)) return {}\n throw error\n }\n })\n }\n\n const write = async (records: Record<string, FreshnessRecord>): Promise<void> => {\n await writeJsonDurableWithinRoot(\n options.root,\n '.agent-knowledge/freshness.json',\n freshnessFileSchema.parse({ records }),\n )\n }\n\n return {\n async last(key) {\n const records = await read()\n const record = records[buildKey(key)]\n return record ? new Date(record.lastRefreshedAt) : null\n },\n async mark(input) {\n await withKnowledgeMutation(options.root, async () => {\n const records = await read()\n records[buildKey(input)] = {\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n lastRefreshedAt: input.when.toISOString(),\n ...(input.contentHash === undefined ? {} : { contentHash: input.contentHash }),\n }\n await write(records)\n })\n },\n async stale(input) {\n const last = await this.last(input)\n if (!last) return true\n const now = input.now ?? new Date()\n return now.getTime() - last.getTime() > input.ttlMs\n },\n async list(workspaceId) {\n const records = await read()\n return Object.values(records).filter((r) => r.workspaceId === workspaceId)\n },\n }\n}\n\n/**\n * D1 / Postgres adapter scaffold. Production consumers implement\n * `D1Adapter` against their own driver (better-sqlite3, postgres,\n * Cloudflare D1 binding, ...). This factory wires the adapter to the\n * `KnowledgeFreshnessStore` interface.\n *\n * The expected schema:\n *\n * ```sql\n * CREATE TABLE knowledge_freshness (\n * workspace_id TEXT NOT NULL,\n * source_id TEXT NOT NULL,\n * last_refreshed_at TEXT NOT NULL,\n * content_hash TEXT,\n * PRIMARY KEY (workspace_id, source_id)\n * );\n * ```\n */\nexport interface D1Adapter {\n get(workspaceId: string, sourceId: string): Promise<FreshnessRecord | null>\n upsert(record: FreshnessRecord): Promise<void>\n listByWorkspace(workspaceId: string): Promise<FreshnessRecord[]>\n}\n\nexport function createD1FreshnessStoreStub(adapter: D1Adapter): KnowledgeFreshnessStore {\n return {\n async last(key) {\n const record = await adapter.get(key.workspaceId, key.sourceId)\n return record ? new Date(record.lastRefreshedAt) : null\n },\n async mark(input) {\n await adapter.upsert({\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n lastRefreshedAt: input.when.toISOString(),\n contentHash: input.contentHash,\n })\n },\n async stale(input) {\n const last = await this.last(input)\n if (!last) return true\n const now = input.now ?? new Date()\n return now.getTime() - last.getTime() > input.ttlMs\n },\n async list(workspaceId) {\n return adapter.listByWorkspace(workspaceId)\n },\n }\n}\n\nfunction buildKey(key: FreshnessKey): string {\n return `${key.workspaceId}::${key.sourceId}`\n}\n","/**\n * HELD-OUT INVESTMENT-RESEARCH EVAL SET.\n *\n * The point of this file is the same FIREWALL the deep-question exam uses\n * (`tests/loops/held-out-exam.ts`): the material facts and their checkable\n * fragments are NEVER shown to a research loop. A loop is told only the company\n * + ticker + a research-as-of CUTOFF date, and asked to write an investment\n * thesis. AFTER it finishes, we grade the thesis it produced against THESE\n * facts — facts it never saw — so a high score is thesis QUALITY (it surfaced\n * the buried, material, non-obvious drivers) and not teaching-to-the-test.\n *\n * Each fact is a DEPTH fact by construction: a single ticker / company-name web\n * search does NOT surface it. They are the things buried in the filings or\n * knowable from then-available primary sources that a thorough analyst flags and\n * a one-shot search misses — customer/revenue/deposit concentration, a debt\n * maturity wall, a margin-trend reversal, a governance / related-party item, a\n * specific competitive or regulatory risk, an off-balance-sheet loss.\n *\n * THREE HARD RULES, enforced by how the data was gathered (see\n * docs/eval/investment-material-facts.md for the per-item provenance + the\n * curation-bias disclosure):\n *\n * 1. SPECIFIC + CHECKABLE. Each fact carries `expected` keyword groups — the\n * specific number / name / phrase — so a deterministic, model-free\n * substring grader (`gradeFactAgainstText`) can score \"did the thesis\n * surface it\". $0, reproducible, and it cannot leak the answer key into a\n * model the loop could observe.\n *\n * 2. DERIVED FROM REAL FETCHED EVIDENCE. Every fact records the primary source\n * it came from (`sourceUrl`, an SEC EDGAR 10-K) and the literal `evidence`\n * value read out of that document. Nothing here is invented; an item that\n * could not be independently sourced was DROPPED, not guessed (the drop log\n * is in the doc).\n *\n * 3. KNOWABLE AT THE CUTOFF. Every fact was disclosed in, or computable from, a\n * document available on or before the company's `cutoff` date. Post-cutoff\n * hindsight (the eventual bankruptcy / collapse) is NOT a checklist item —\n * it is recorded separately as `knownOutcome`, purely for the reader, and is\n * never graded.\n *\n * Grading mirrors the deep-question exam exactly: a fact is SURFACED when the\n * thesis text contains at least `minGroups` of its expected groups; a group is\n * satisfied when ANY of its `anyOf` fragments appears (case-insensitive\n * substring), so a faithful thesis phrased in its own words still grades as a\n * hit. `anyOf` groups model synonyms; the load-bearing tokens are the specific\n * numbers / names.\n */\n\n/** A required answer component: satisfied when any synonym fragment is present. */\nexport interface ExpectedGroup {\n /** Human label for the component (for the doc / audit). */\n label: string\n /** Case-insensitive substring fragments; any one present satisfies the group. */\n anyOf: string[]\n}\n\n/** Lens the fact belongs to — so a set can be checked for category coverage. */\nexport type MaterialFactLens =\n | 'concentration' // customer / revenue / deposit concentration\n | 'leverage' // debt load / maturity wall / interest burden\n | 'margin-trend' // gross/operating margin reversal\n | 'liquidity' // cash burn / negative operating cash flow\n | 'capital-return' // buyback / dividend draining the balance sheet\n | 'governance' // dual-class / related-party / control item\n | 'off-balance-sheet' // unrealized losses not in earnings/equity\n | 'regulatory' // a specific regulatory / legal / recall exposure\n\n/** One held-out material fact with a checkable expected answer + its provenance. */\nexport interface MaterialFact {\n /** Stable id, `ticker/fN`. */\n id: string\n /** Which analyst lens this fact exercises. For coverage + the doc. */\n lens: MaterialFactLens\n /**\n * The material fact, in plain words — for the doc/audit. NEVER shown to a loop.\n * This is the thing a thorough analyst would flag and a ticker search misses.\n */\n fact: string\n /**\n * The checkable answer as required keyword GROUPS. The thesis text must contain\n * at least `minGroups` of these groups (default: all). A group is satisfied\n * when ANY of its `anyOf` fragments appears (case-insensitive substring).\n */\n expected: ExpectedGroup[]\n /**\n * Minimum number of `expected` groups the thesis must contain to count the\n * fact SURFACED. Default = all groups (the strict bar). Lowered (and documented\n * inline) only when the fact is genuinely satisfiable by a subset.\n */\n minGroups?: number\n /**\n * PROVENANCE. The primary source URL this fact was read from — an SEC EDGAR\n * 10-K primary document, fetched live during curation.\n */\n sourceUrl: string\n /**\n * The literal value / phrase read out of `sourceUrl` that grounds the fact.\n * This is the \"cite the actual filing + the value\" requirement — verbatim or\n * near-verbatim from the filing, with the figure.\n */\n evidence: string\n}\n\n/** A company + the cutoff a loop researches as-of + its held-out material facts. */\nexport interface CompanyEvalCase {\n /** Ticker as of the cutoff. */\n ticker: string\n /** Legal name as of the cutoff (what the loop is told to research). */\n company: string\n /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */\n cik: string\n /**\n * Research-as-of date (ISO). The loop must reason as if it is this date; every\n * `evidence` value was knowable on or before it. >= 18 months before this set\n * was curated, so the outcome is known but is NOT a checklist item.\n */\n cutoff: string\n /** Sector, for coverage / the curation-bias disclosure. */\n sector: string\n /**\n * The known POST-cutoff outcome — recorded for the reader ONLY, never graded.\n * Keeping it out of `facts` is what makes the set hindsight-free.\n */\n knownOutcome: string\n /** The held-out material facts for this company. */\n facts: MaterialFact[]\n}\n\n/**\n * The eval set. 5 public companies, 5-8 held-out material facts each, every fact\n * grounded in a primary SEC EDGAR 10-K filed on or before the cutoff.\n *\n * CURATION-BIAS DISCLOSURE (full version in the doc): all five are companies\n * whose buried risks later materialized, because that is where the material-vs-\n * surface distinction is sharpest AND where the figures are easy to verify after\n * the fact. This biases the set toward downside risks (two of the eight lenses,\n * concentration + leverage, dominate) and toward distressed names. A production\n * eval would balance these with companies whose buried facts were POSITIVE\n * drivers and with survivors. This set is honest about that and reports the lens\n * distribution so the bias is measurable, not hidden.\n */\nexport const investmentThesisSet: CompanyEvalCase[] = [\n {\n ticker: 'SIVB',\n company: 'SVB Financial Group',\n cik: '719739',\n cutoff: '2023-02-24',\n sector: 'Banking',\n knownOutcome:\n 'Failed in a deposit run and was placed in FDIC receivership on March 10, 2023; the holding company filed Chapter 11 on March 17, 2023.',\n facts: [\n {\n id: 'SIVB/f1',\n lens: 'off-balance-sheet',\n fact: 'Held-to-maturity (HTM) securities carried at $91.3B amortized cost had a fair value of only $76.2B — a ~$15.1B unrealized loss that, because the portfolio is HTM, never touched earnings or equity and sat only in the footnotes.',\n expected: [\n {\n label: 'HTM securities',\n anyOf: ['held-to-maturity', 'held to maturity', 'htm'],\n },\n {\n label: 'large unrealized loss (~$15B) / fair value gap',\n anyOf: [\n '15.1',\n '15.2',\n '$15 billion',\n '15 billion',\n '76,169',\n '76.2 billion',\n '91,321',\n 'unrealized loss',\n 'below amortized cost',\n 'fair value',\n ],\n },\n ],\n minGroups: 2,\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n 'Balance sheet (Dec 31, 2022): \"Held-to-maturity securities, at amortized cost ... 91,321\" with parenthetical \"(fair value of $ 76,169 ...)\". The gap = $91,321M - $76,169M = ~$15,152M unrealized loss, disclosed only in the notes.',\n },\n {\n id: 'SIVB/f2',\n lens: 'off-balance-sheet',\n fact: \"The HTM unrealized loss (~$15.1B) was roughly equal to the company's entire $16.0B total stockholders' equity — a mark-to-market wipeout hidden by HTM accounting.\",\n expected: [\n {\n label: 'loss near/exceeds total equity',\n anyOf: [\n 'equity',\n 'capital',\n 'insolvent',\n 'wipe out',\n 'exceeds',\n 'nearly all',\n 'tangible book',\n '16,004',\n '16 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"Total SVBFG stockholders\\' equity 16,004\" (Dec 31, 2022). The ~$15.15B HTM unrealized loss is ~95% of the $16.0B reported equity.',\n },\n {\n id: 'SIVB/f3',\n lens: 'concentration',\n fact: 'Estimated uninsured deposits in U.S. offices were $151.5B at year-end 2022 — the run-prone funding base; a high share of total deposits exceeded the FDIC limit.',\n expected: [\n {\n label: 'large uninsured deposit base',\n anyOf: [\n 'uninsured deposit',\n 'above the fdic',\n 'exceed the fdic',\n 'exceeds the fdic',\n '151.5',\n '$151 billion',\n 'fdic insurance limit',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"As of December 31, 2022 ... the amount of estimated uninsured deposits in U.S. offices that exceed the FDIC insurance limit were $151.5 billion\".',\n },\n {\n id: 'SIVB/f4',\n lens: 'margin-trend',\n fact: 'Cheap noninterest-bearing demand deposits fell 20 percentage points in one year — to 47% of total deposits from 67% — meaning funding costs were set to rise sharply as clients moved to interest-bearing accounts.',\n expected: [\n {\n label: 'deposit mix shift to costlier funding',\n anyOf: [\n 'noninterest-bearing',\n 'non-interest-bearing',\n 'noninterest bearing',\n 'deposit mix',\n 'funding cost',\n 'cost of deposits',\n 'interest-bearing',\n '47 percent',\n '20 percentage',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"Noninterest-bearing demand deposits to total deposits decreased by 20 percentage points to 47 percent as of December 31, 2022, compared to ... 2021.\"',\n },\n {\n id: 'SIVB/f5',\n lens: 'concentration',\n fact: 'The deposit and loan base was concentrated in a single client type — the \"innovation economy\" (venture-backed technology and life-science startups) — so a downturn in venture funding would hit deposits and credit simultaneously.',\n expected: [\n {\n label: 'concentration in tech / startups / innovation economy',\n anyOf: [\n 'innovation economy',\n 'technology',\n 'life science',\n 'venture',\n 'startup',\n 'early-stage',\n 'concentrat',\n 'single industry',\n 'sector concentration',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n 'The 10-K repeatedly frames the franchise around clients in \"the innovation economy\" (technology, life science / healthcare, and the venture firms that back them) — a single-sector deposit + credit concentration.',\n },\n {\n id: 'SIVB/f6',\n lens: 'off-balance-sheet',\n fact: 'Available-for-sale (AFS) securities of $28.6B amortized cost were marked to a $26.1B fair value — a ~$2.5B loss that DID flow through equity (AOCI), the visible tip of a much larger unrealized-loss iceberg dominated by the footnote-only HTM book.',\n expected: [\n {\n label: 'AFS unrealized loss / AOCI',\n anyOf: [\n 'available-for-sale',\n 'available for sale',\n 'afs',\n 'aoci',\n 'accumulated other comprehensive',\n '28,602',\n '26,069',\n '2.5 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm',\n evidence:\n '\"Available-for-sale securities, at fair value (cost of $ 28,602 ...) 26,069\" — a ~$2.5B AFS unrealized loss carried in AOCI, separate from and much smaller than the HTM gap.',\n },\n ],\n },\n {\n ticker: 'BBBY',\n company: 'Bed Bath & Beyond Inc.',\n cik: '886158',\n cutoff: '2022-04-21',\n sector: 'Specialty retail',\n knownOutcome: 'Filed for Chapter 11 bankruptcy on April 23, 2023; shareholders were wiped out.',\n facts: [\n {\n id: 'BBBY/f1',\n lens: 'capital-return',\n fact: 'The company had repurchased ~$11.685B of its own stock since 2004 — including $574.9M in fiscal 2021 alone, \"two years ahead of schedule\" — draining the balance sheet of a business that was losing money.',\n expected: [\n {\n label: 'massive buyback program',\n anyOf: [\n 'repurchas',\n 'buyback',\n 'buy back',\n 'share repurchase',\n '11.685',\n '$11.7 billion',\n '574.9',\n '$575 million',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n '\"Since 2004 through the end of Fiscal 2021, we have repurchased approximately $11.685 billion of our common stock\"; FY2021 alone \"completed share repurchases of $574.9 million ... two years ahead of schedule.\"',\n },\n {\n id: 'BBBY/f2',\n lens: 'liquidity',\n fact: 'Operating cash flow collapsed to just $17.9M in FY2021, down from $268.1M and $590.9M in the two prior years — a near-total loss of internally generated cash while it kept buying back stock.',\n expected: [\n {\n label: 'operating cash flow collapse',\n anyOf: [\n 'operating cash flow',\n 'cash from operations',\n 'cash provided by operating',\n 'cash flow from operations',\n '17.9',\n '17,854',\n 'declining cash flow',\n 'cash generation',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n 'Statement of cash flows: \"Net cash provided by operating activities 17,854 268,108 590,941\" (FY2021 / FY2020 / FY2019, $ thousands).',\n },\n {\n id: 'BBBY/f3',\n lens: 'liquidity',\n fact: \"Total shareholders' equity fell ~86% in one year — from $1.277B to $174.1M — as losses plus buybacks ate the equity cushion.\",\n expected: [\n {\n label: 'equity erosion',\n anyOf: [\n 'shareholders’ equity',\n \"shareholders' equity\",\n 'stockholders equity',\n 'book value',\n 'equity',\n 'net worth',\n '174.1',\n '174,145',\n 'eroded',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n '\"Total shareholders\\' equity 174,145 1,276,936\" (FY2021 vs FY2020, $ thousands) — an ~86% decline in one year.',\n },\n {\n id: 'BBBY/f4',\n lens: 'liquidity',\n fact: 'The company posted a $559.6M net loss in FY2021 — yet spent $574.9M on buybacks the same year, i.e. it returned more cash to shareholders than it had, let alone earned.',\n expected: [\n {\n label: 'net loss FY2021',\n anyOf: [\n 'net loss',\n 'unprofitable',\n 'lost money',\n 'losing money',\n '559.6',\n '559,623',\n '$560 million',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence: '\"Net loss $ ( 559,623 )\" for fiscal 2021 ($ thousands).',\n },\n {\n id: 'BBBY/f5',\n lens: 'margin-trend',\n fact: 'Merchandise inventories rose to $1.725B even as sales fell — inventory building into a demand decline, a classic markdown-risk and cash-trap signal.',\n expected: [\n {\n label: 'inventory building into falling demand',\n anyOf: [\n 'inventor',\n 'merchandise inventories',\n 'overstock',\n 'markdown',\n '1,725',\n '1.7 billion',\n 'stockpile',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm',\n evidence:\n '\"Merchandise inventories 1,725,410 1,671,909\" ($ thousands) — inventory grew year over year while comparable sales declined.',\n },\n ],\n },\n {\n ticker: 'CVNA',\n company: 'Carvana Co.',\n cik: '1690820',\n cutoff: '2023-02-23',\n sector: 'Auto e-commerce',\n knownOutcome:\n 'The stock fell ~98% from its 2021 peak; the company narrowly avoided bankruptcy via a 2023 debt-exchange that cut and extended its obligations.',\n facts: [\n {\n id: 'CVNA/f1',\n lens: 'leverage',\n fact: 'Total debt had grown to $8.39B by year-end 2022 (from $5.45B) — a debt load far larger than the equity base, built up funding growth and the ADESA deal.',\n expected: [\n {\n label: 'large/growing debt load',\n anyOf: [\n 'total debt',\n 'long-term debt',\n 'leverage',\n 'highly leveraged',\n 'debt load',\n '8,391',\n '8.4 billion',\n '$8.4 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence: '\"Total debt 8,391 5,447\" (Dec 31, 2022 vs 2021, $ millions).',\n },\n {\n id: 'CVNA/f2',\n lens: 'leverage',\n fact: 'Interest expense nearly tripled to $486M in 2022 (from $176M) — debt-service was consuming cash a still-unprofitable company did not have.',\n expected: [\n {\n label: 'rising interest burden',\n anyOf: [\n 'interest expense',\n 'interest cost',\n 'debt service',\n 'cost of debt',\n '486',\n 'interest burden',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence: '\"Interest expense 486 176\" (FY2022 vs FY2021, $ millions).',\n },\n {\n id: 'CVNA/f3',\n lens: 'leverage',\n fact: \"In May 2022 Carvana bought ADESA's U.S. physical auction business for ~$2.2B in cash — a debt-funded acquisition that stretched the balance sheet right as used-car demand turned.\",\n expected: [\n {\n label: 'ADESA acquisition ~$2.2B',\n anyOf: ['adesa', '2.2 billion', '$2.2 billion', 'physical auction', 'acquisition'],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence:\n '\"physical auction business of ADESA US Auction, LLC for approximately $2.2 billion in cash (the \\'ADESA Acquisition\\')\", closed 2022-05-09.',\n },\n {\n id: 'CVNA/f4',\n lens: 'governance',\n fact: 'Carvana leases hubs and properties from DriveTime — a company controlled by founder/CEO Ernest Garcia III and his father Ernest Garcia II — a recurring related-party arrangement with the controlling family.',\n expected: [\n {\n label: 'related-party with founder family / DriveTime',\n anyOf: [\n 'related party',\n 'related-party',\n 'drivetime',\n 'garcia',\n 'controlled by',\n 'affiliate of',\n 'conflict of interest',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence:\n 'Related Party Transactions note: lease agreements with \"DriveTime Automotive Group\", a related party \"due to Ernest Garcia II, Ernest Garcia III, and entities controlled by one or both of them\".',\n },\n {\n id: 'CVNA/f5',\n lens: 'liquidity',\n fact: 'The 2022 net loss was $2.894B — a loss far wider than prior years, showing the unit economics had not turned even at scale.',\n expected: [\n {\n label: 'large net loss FY2022',\n anyOf: [\n 'net loss',\n 'unprofitable',\n 'losing money',\n 'cash burn',\n '2,894',\n '2.9 billion',\n '$2.9 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm',\n evidence: '\"Net loss $ (2,894 ...\" for fiscal 2022 ($ millions).',\n },\n ],\n },\n {\n ticker: 'PTON',\n company: 'Peloton Interactive, Inc.',\n cik: '1639825',\n cutoff: '2022-09-07',\n sector: 'Consumer fitness hardware',\n knownOutcome:\n 'The stock fell ~95% from its 2021 peak; the founder-CEO departed, the company underwent mass layoffs and a multi-year turnaround through fiscal 2024.',\n facts: [\n {\n id: 'PTON/f1',\n lens: 'margin-trend',\n fact: 'Connected Fitness (hardware) gross margin turned NEGATIVE — to (11)% in FY2022 — meaning Peloton lost money on every bike/tread it sold before any operating cost; revenue growth was masking a broken unit economics.',\n expected: [\n {\n label: 'negative / collapsing hardware gross margin',\n anyOf: [\n 'gross margin',\n 'negative margin',\n 'gross profit',\n 'margin compression',\n 'losing money on each',\n 'below cost',\n '(11)',\n '-11',\n 'negative gross',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n 'MD&A \"Gross Profit, and Gross Margin\" table: Connected Fitness \"Gross Margin decreased to (11)\" percent in fiscal 2022 — a negative hardware gross margin.',\n },\n {\n id: 'PTON/f2',\n lens: 'liquidity',\n fact: 'Inventories climbed to $1.105B as pandemic demand normalized — a glut of unsold equipment that tied up cash and risked markdowns.',\n expected: [\n {\n label: 'inventory glut',\n anyOf: [\n 'inventor',\n 'overstock',\n 'excess inventory',\n 'glut',\n 'markdown',\n 'unsold',\n '1,104',\n '1.1 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence: '\"Inventories, net 1,104.5 937\" (FY2022 vs FY2021, $ millions).',\n },\n {\n id: 'PTON/f3',\n lens: 'governance',\n fact: \"A dual-class structure gives Class B holders 20 votes per share vs 1 for Class A — concentrating control with insiders/founders and limiting public shareholders' say.\",\n expected: [\n {\n label: 'dual-class super-voting control',\n anyOf: [\n 'dual-class',\n 'dual class',\n 'class b',\n '20 votes',\n 'super-voting',\n 'supervoting',\n 'voting control',\n 'multiple votes per share',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n '\"Class B common stock has 20 votes per share and our Class A common stock has one vote per share.\"',\n },\n {\n id: 'PTON/f4',\n lens: 'liquidity',\n fact: 'Peloton reported a $2.827B net loss in FY2022 — an order-of-magnitude wider loss than the prior year, signaling the demand normalization had broken the model, not just dented it.',\n expected: [\n {\n label: 'large net loss FY2022',\n anyOf: [\n 'net loss',\n 'unprofitable',\n 'losing money',\n 'cash burn',\n '2,827',\n '2.8 billion',\n '$2.8 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence: '\"Net loss $ (2,827 ...\" for fiscal 2022 ($ millions).',\n },\n {\n id: 'PTON/f5',\n lens: 'regulatory',\n fact: 'Peloton was running a CPSC recall of its Tread+ treadmill (tied to injuries and a child death) — an open product-safety and legal exposure beyond the demand story.',\n expected: [\n {\n label: 'Tread+ / CPSC recall exposure',\n anyOf: [\n 'recall',\n 'cpsc',\n 'consumer product safety',\n 'tread+',\n 'tread plus',\n 'product safety',\n 'injuries',\n 'safety',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n '\"recall on Tread+, which we are conducting in collaboration with the Consumer Product Safety Commission (\\'CPSC\\')\"; the Tread product recalls \"in the fourth quarter of fiscal 2021 continued to impact\" results.',\n },\n {\n id: 'PTON/f6',\n lens: 'leverage',\n fact: 'Peloton was locked into ~$334M of manufacturing purchase commitments even as demand fell — contractual inventory it had to take on regardless of whether it could sell it.',\n expected: [\n {\n label: 'locked-in purchase commitments',\n anyOf: [\n 'purchase commitment',\n 'purchase obligation',\n 'minimum purchase',\n 'take-or-pay',\n 'committed to purchase',\n '334',\n 'manufacturing commitment',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm',\n evidence:\n '\"purchase commitments related to the manufacture of Peloton products were estimated to be approximately $334\" million.',\n },\n ],\n },\n {\n ticker: 'SI',\n company: 'Silvergate Capital Corporation',\n cik: '1312109',\n cutoff: '2022-02-28',\n sector: 'Banking (digital-asset)',\n knownOutcome:\n 'After the FTX collapse triggered a deposit run, Silvergate announced a voluntary wind-down of Silvergate Bank and liquidation in March 2023.',\n facts: [\n {\n id: 'SI/f1',\n lens: 'concentration',\n fact: 'About 99.5% of total deposits were noninterest-bearing — essentially all funding was non-term money that could leave on demand, an extreme run-risk masked by very low funding cost.',\n expected: [\n {\n label: 'almost all deposits noninterest-bearing / on-demand',\n anyOf: [\n 'noninterest bearing',\n 'noninterest-bearing',\n 'non-interest-bearing',\n 'demand deposit',\n 'no term',\n 'on demand',\n '99.5',\n '99 percent',\n 'leave at any time',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n '\"noninterest bearing deposits as a percentage of total deposits was 99.5% as of December 31, 2021.\"',\n },\n {\n id: 'SI/f2',\n lens: 'concentration',\n fact: 'Roughly 58% of deposits came from digital-currency EXCHANGES alone — a handful of correlated crypto counterparties whose own troubles would pull deposits out together.',\n expected: [\n {\n label: 'deposits concentrated in crypto exchanges',\n anyOf: [\n 'digital currency exchange',\n 'crypto exchange',\n 'exchanges represent',\n 'counterpart',\n 'concentrat',\n '58%',\n '58 percent',\n 'approximately 58',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n '\"Deposits from digital currency exchanges represent approximately 58%\" of deposits.',\n },\n {\n id: 'SI/f3',\n lens: 'concentration',\n fact: 'The entire deposit franchise was tied to a single, volatile industry — digital-currency (crypto) customers — so a crypto downturn was a direct, undiversified funding shock.',\n expected: [\n {\n // The buried, depth signal is the CONCENTRATION framing — that the\n // whole deposit base is one undiversified industry bet — NOT the bare\n // fact that it banks crypto (a one-line ticker summary has that). So\n // bare \"crypto\" / \"digital asset\" are excluded; the load-bearing\n // tokens are the concentration / single-industry / undiversified\n // characterization or the filing's own \"digital currency customers\".\n label: 'single-industry deposit CONCENTRATION (not just \"it banks crypto\")',\n anyOf: [\n 'digital currency customers',\n 'single industry',\n 'one industry',\n 'single volatile industry',\n 'sector concentration',\n 'undiversified',\n 'concentrat',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n 'The 10-K\\'s strategy and risk factors center the bank on \"digital currency customers\" and \"the concentration of our deposits\" in that single industry.',\n },\n {\n id: 'SI/f4',\n lens: 'liquidity',\n fact: 'Total deposits had ballooned to $14.3B (from $10.4B) — fast, hot-money growth from the crypto boom that could reverse just as fast.',\n expected: [\n {\n // The depth signal is the SIZE/character of the deposit base — the\n // specific $14.3B figure or the explicit hot-money / volatile-deposit\n // characterization — NOT bare \"total deposits\" / \"grew rapidly\", which\n // any growth-story summary trips. Those generic phrases are excluded.\n label: 'specific hot-money deposit base ($14.3B / volatile)',\n anyOf: [\n 'hot money',\n 'hot-money',\n 'volatile deposit',\n 'could reverse',\n '14.3 billion',\n '14,290',\n '$14.3b',\n '$14 billion',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence: '\"Total deposits $ 14,290,628\" ... prior year \"$ 10,411,278\" ($ thousands).',\n },\n {\n id: 'SI/f5',\n lens: 'concentration',\n fact: 'The franchise hinged on a single proprietary product — the Silvergate Exchange Network (SEN), a payment network built exclusively for the digital-currency industry — so its competitive moat and its deposit base were the SAME crypto-dependent bet, not two diversified ones.',\n expected: [\n {\n // The depth signal is naming the SPECIFIC proprietary product (the\n // Silvergate Exchange Network / SEN) and that the moat and the deposit\n // base are the same single bet — NOT bare \"proprietary\" / \"payment\n // network\", which a generic crypto-bank summary mentions. Those bare\n // terms are excluded; the SEN name or the single-product framing is\n // load-bearing.\n label: 'names the SEN single-product dependence (not generic \"payment network\")',\n anyOf: [\n 'silvergate exchange network',\n 'the sen',\n 'sen)',\n \"sen'\",\n 'single product',\n 'single-product',\n 'core product',\n 'one product',\n 'same bet',\n ],\n },\n ],\n sourceUrl:\n 'https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm',\n evidence:\n \"\\\"Silvergate Exchange Network ('SEN'), our proprietary, virtually instantaneous payment network for participants in the digital currency industry\\\" — the bank's differentiator and its deposit magnet are the same crypto-only product.\",\n },\n ],\n },\n]\n\n/**\n * Grade ONE material fact against an investment thesis's full text. Returns\n * whether the thesis SURFACED it plus which expected groups were found. The\n * check is a deterministic case-insensitive substring scan — $0, model-free,\n * reproducible — so the eval never leaks into a model the loop could observe.\n */\nexport function gradeFactAgainstText(\n fact: MaterialFact,\n thesisText: string,\n): { surfaced: boolean; groupsFound: number; groupsTotal: number; foundLabels: string[] } {\n const haystack = thesisText.toLowerCase()\n const found = fact.expected.filter((group) =>\n group.anyOf.some((fragment) => haystack.includes(fragment.toLowerCase())),\n )\n const minGroups = fact.minGroups ?? fact.expected.length\n return {\n surfaced: found.length >= minGroups,\n groupsFound: found.length,\n groupsTotal: fact.expected.length,\n foundLabels: found.map((group) => group.label),\n }\n}\n\n/** Grade a whole company's thesis text: how many of its held-out facts it surfaces. */\nexport function gradeCompanyAgainstText(\n company: CompanyEvalCase,\n thesisText: string,\n): { surfaced: number; total: number; perFact: ReturnType<typeof gradeFactAgainstText>[] } {\n const perFact = company.facts.map((fact) => gradeFactAgainstText(fact, thesisText))\n return {\n surfaced: perFact.filter((result) => result.surfaced).length,\n total: company.facts.length,\n perFact,\n }\n}\n\n/** Total held-out facts across the set (the denominator the doc reports). */\nexport function totalMaterialFacts(set: CompanyEvalCase[] = investmentThesisSet): number {\n return set.reduce((sum, company) => sum + company.facts.length, 0)\n}\n\n/** Count facts per lens across the set — used to report (and bound) curation bias. */\nexport function lensDistribution(\n set: CompanyEvalCase[] = investmentThesisSet,\n): Record<MaterialFactLens, number> {\n const dist = {} as Record<MaterialFactLens, number>\n for (const company of set) {\n for (const fact of company.facts) {\n dist[fact.lens] = (dist[fact.lens] ?? 0) + 1\n }\n }\n return dist\n}\n","/**\n * The INVESTMENT-THESIS research task.\n *\n * Given `{ company, ticker, cik, cutoff }`, drive the SAME two-agent research\n * loop the ML deep-question A/B uses (`runVerifiedResearchLoop` + the real web\n * worker) to research the company AS OF the cutoff — web + SEC EDGAR, both public\n * — and produce an investment-thesis PAGE in the knowledge base: a judgment, the\n * drivers, and the risks, grounded in what it fetched.\n *\n * This file builds NOTHING new for the loop: it composes the existing worker +\n * driver + loop, supplies the readiness specs that steer the worker toward the\n * filing-level evidence (the analyst lenses), then writes a synthesis thesis page\n * the metric (`materialFactsSurfaced`) grades against the HELD-OUT checklist.\n *\n * THE FIREWALL: the task is told ONLY company + ticker + cutoff (+ the generic\n * analyst-lens readiness specs every company gets). It is NEVER shown the\n * checklist. The checklist is read only afterward, by the metric. So a high score\n * is research depth, not teaching-to-the-test.\n */\n\nimport { join } from 'node:path'\nimport { writeFileDurableWithinRoot } from './durable-fs'\nimport { defineReadinessSpec, type KnowledgeReadinessSpec } from './eval-readiness'\nimport { slugify } from './ids'\nimport { buildKnowledgeIndex } from './indexer'\nimport { kbIndexToText } from './material-facts-metric'\nimport { withKnowledgeMutation } from './mutation-lock'\nimport {\n type ResearchDriver,\n runVerifiedResearchLoop,\n type VerifiedResearchLoopResult,\n} from './two-agent-research-loop'\nimport {\n createWebResearchWorker,\n type RouterClient,\n type WebResearchWorkerOptions,\n} from './web-research-worker'\n\n/** The minimal brief a thesis run is given — the firewall boundary. */\nexport interface ThesisTaskInput {\n /** Legal name as of the cutoff — what the loop researches. */\n company: string\n /** Ticker as of the cutoff. */\n ticker: string\n /** SEC Central Index Key (CIK), zero-stripped — the EDGAR filer id. */\n cik: string\n /** Research-as-of date (ISO). The loop must reason as if it is this date. */\n cutoff: string\n /** Sector, for the readiness query context (NOT a checklist hint). */\n sector?: string\n}\n\n/**\n * The generic analyst-lens readiness specs every company gets. They are the ONLY\n * thing the loop is told about WHAT to look for, and they name the LENSES a\n * thorough analyst checks (balance-sheet risk, concentration, leverage, margins,\n * liquidity, governance, regulatory) and where they live (the latest SEC 10-K) —\n * NOT the answers. They steer the worker's web/EDGAR search toward the filing,\n * not toward the held-out facts (which the loop never sees).\n *\n * `minSources` is set above 1 so the readiness gate stays UNMET after a single\n * fetch and the loop runs multiple rounds — the depth-driving driver needs >1\n * round to steer, exactly as the ML-exam multi-round probe established.\n */\nexport function thesisReadinessSpecs(input: ThesisTaskInput): KnowledgeReadinessSpec[] {\n const c = input.company\n const t = input.ticker\n const filing = `${c} ${t} SEC 10-K annual report SEC.gov EDGAR filing`\n return [\n defineReadinessSpec({\n id: 'thesis/filing',\n description: `the most recent SEC 10-K annual report for ${c} (${t}) filed on or before ${input.cutoff}, from SEC EDGAR`,\n query: filing,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n defineReadinessSpec({\n id: 'thesis/balance-sheet',\n description: `${c} balance-sheet risks: securities marked below cost, unrealized losses, leverage / total debt, debt maturities, interest expense`,\n query: `${c} ${t} 10-K balance sheet total debt unrealized losses interest expense leverage`,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n defineReadinessSpec({\n id: 'thesis/concentration-liquidity',\n description: `${c} concentration + liquidity: customer / deposit / revenue concentration, uninsured deposits, operating cash flow, net loss, inventory, equity erosion`,\n query: `${c} ${t} 10-K customer deposit concentration operating cash flow net loss inventory`,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n defineReadinessSpec({\n id: 'thesis/governance-regulatory',\n description: `${c} governance + regulatory: related-party transactions, dual-class / super-voting control, buybacks / dividends, recalls, regulatory or legal exposure, margin trends`,\n query: `${c} ${t} 10-K related party dual class share repurchase recall regulatory gross margin`,\n requiredFor: ['ResearchAgent'],\n importance: 'blocking',\n minSources: 2,\n minHits: 1,\n }),\n ]\n}\n\n/**\n * The thesis-writer prompt. After the loop has fetched + curated the filings, we\n * ask the model to SYNTHESIZE a thesis page from the curated KB text — a\n * judgment, the key drivers, and the material risks, grounded ONLY in the fetched\n * evidence. The held-out checklist is NOT in this prompt; the model writes from\n * what the loop actually pulled, so a fact only appears if the research surfaced\n * the underlying evidence.\n */\nfunction thesisSynthesisMessages(\n input: ThesisTaskInput,\n kbText: string,\n): { role: 'system' | 'user'; content: string }[] {\n const system =\n 'You are a buy-side investment analyst writing a thesis memo. You are given ' +\n 'the raw research your team gathered from public filings (SEC 10-K) and the web. ' +\n 'Write a thesis that a thorough analyst would write: lead with your JUDGMENT, ' +\n 'then the KEY DRIVERS, then the MATERIAL RISKS. Be specific and quantitative — ' +\n 'name the actual figures, balance-sheet items, concentrations, leverage, ' +\n 'margin trends, governance items, and regulatory exposures that appear in the ' +\n 'research. Surface the buried, non-obvious drivers a one-line ticker summary ' +\n 'misses. Ground every claim in the research provided; do NOT invent figures. ' +\n 'If the research does not contain a figure, do not state it.'\n const user = [\n `Company: ${input.company} (${input.ticker})`,\n `As-of date (reason as if it is this date): ${input.cutoff}`,\n input.sector ? `Sector: ${input.sector}` : '',\n '',\n 'Research gathered (filings + web excerpts):',\n '\"\"\"',\n kbText.slice(0, 24000),\n '\"\"\"',\n '',\n 'Write the investment thesis now. Structure:',\n '## Judgment',\n '## Key drivers',\n '## Material risks',\n ]\n .filter(Boolean)\n .join('\\n')\n return [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ]\n}\n\n/** Write the synthesis thesis page into the KB so the index + metric pick it up. */\nasync function writeThesisPage(\n root: string,\n input: ThesisTaskInput,\n thesis: string,\n): Promise<string> {\n return withKnowledgeMutation(root, async () => {\n const relativePath = `knowledge/thesis-${slugify(input.ticker)}.md`\n const body = [\n '---',\n `title: Investment thesis — ${input.company} (${input.ticker})`,\n `ticker: ${input.ticker}`,\n `cutoff: ${input.cutoff}`,\n 'kind: investment-thesis',\n '---',\n `# Investment thesis — ${input.company} (${input.ticker}), as of ${input.cutoff}`,\n '',\n thesis.trim(),\n '',\n ].join('\\n')\n await writeFileDurableWithinRoot(root, relativePath, body, { encoding: 'utf8' })\n return join(root, relativePath)\n })\n}\n\nexport interface ThesisRunOptions {\n /** The KB root the loop writes into. */\n root: string\n /** Shared router client (web search + chat). Defaults to env creds. */\n router: RouterClient\n /** The driver — verify/dedup or research-driving. The loop's coordinator. */\n driver: ResearchDriver\n /** Round budget. Default 3 (the depth-driving driver needs >1). */\n maxRounds?: number\n /** Worker tuning forwarded to `createWebResearchWorker`. */\n workerOptions?: Omit<WebResearchWorkerOptions, 'router'>\n /** Max tokens for the synthesis pass. Default 1600 (above glm-5.2's reasoning floor). */\n synthesisMaxTokens?: number\n signal?: AbortSignal\n}\n\nexport interface ThesisRunResult {\n loop: VerifiedResearchLoopResult\n /** The synthesized thesis text. */\n thesis: string\n /** Path of the thesis page written into the KB. */\n thesisPath: string\n}\n\n/**\n * Run the full thesis task: drive the two-agent loop to research the company AS\n * OF the cutoff, then synthesize + write the thesis page. Returns the loop result\n * + the thesis text + the page path. The caller grades the KB with\n * `materialFactsSurfaced(root, checklist)` — the checklist is never passed here.\n */\nexport async function runInvestmentThesisTask(\n input: ThesisTaskInput,\n options: ThesisRunOptions,\n): Promise<ThesisRunResult> {\n const worker = createWebResearchWorker({ ...options.workerOptions, router: options.router })\n const goal = `${input.company} (${input.ticker}) investment thesis as of ${input.cutoff}`\n\n const loop = await runVerifiedResearchLoop({\n root: options.root,\n goal,\n worker,\n driver: options.driver,\n readinessSpecs: thesisReadinessSpecs(input),\n maxRounds: options.maxRounds ?? 3,\n signal: options.signal,\n })\n\n // Synthesize the thesis from what the loop actually curated + fetched.\n const index = await buildKnowledgeIndex(options.root)\n const kbText = kbIndexToText(index)\n const messages = thesisSynthesisMessages(input, kbText)\n const thesis = await options.router.chat(messages, options.synthesisMaxTokens ?? 1600)\n\n const thesisPath = await writeThesisPage(options.root, input, thesis)\n return { loop, thesis, thesisPath }\n}\n","/**\n * `materialFactsSurfaced` — the held-out investment-research METRIC.\n *\n * Given a knowledge base a research loop built for a company and the company's\n * HELD-OUT material-fact checklist (`tests/eval/investment-thesis-set.ts`, never\n * shown to the loop), this returns the FRACTION of checklist items the KB's\n * pages surface + ground. The check is the same `$0`, model-free, deterministic\n * substring grader the loop's checklist already ships (`gradeFactAgainstText` /\n * `gradeCompanyAgainstText`) — so the answer key never reaches a model the loop\n * could observe, exactly the firewall the ML deep-question exam uses.\n *\n * The ONLY thing this file adds over the raw grader is the KB→text join: it reads\n * the curated pages (and the raw source text) the loop wrote and hands their\n * concatenation to the grader. That join mirrors `kbText` in the research-quality\n * A/B (research-driving-ab.test.ts) so the thesis metric and the ML-exam metric\n * read a KB the same way.\n *\n * WHY pages AND source text: an honest thesis surfaces a buried fact in its\n * curated thesis PAGE (the judgment), but a loop whose page is thin while its\n * fetched filings are rich should still get credit for what it actually pulled.\n * Grading the union is the faithful, not the lenient, choice — it rewards the\n * loop that REACHED the filing even if its synthesis was terse, and it cannot\n * manufacture a hit the underlying evidence does not contain.\n */\n\nimport { buildKnowledgeIndex } from './indexer'\nimport {\n type CompanyEvalCase,\n gradeCompanyAgainstText,\n gradeFactAgainstText,\n} from './investment-thesis-set'\nimport type { KnowledgeIndex } from './types'\n\n/** Per-fact grade plus the fact's id/lens, for the audit trail. */\nexport interface FactResult {\n id: string\n lens: CompanyEvalCase['facts'][number]['lens']\n surfaced: boolean\n groupsFound: number\n groupsTotal: number\n foundLabels: string[]\n}\n\n/** The metric's result for one company: the surfaced fraction + the per-fact trail. */\nexport interface MaterialFactsResult {\n ticker: string\n company: string\n /** Held-out facts the KB surfaced + grounded. */\n surfaced: number\n /** Total held-out facts for this company (the denominator). */\n total: number\n /** `surfaced / total` in [0, 1]. */\n fraction: number\n /** Per-fact grade, in checklist order, for the doc / audit. */\n perFact: FactResult[]\n}\n\n/**\n * Join a KB index into the single text blob the grader scans: every curated PAGE\n * (title + body) followed by every raw SOURCE (title + fetched text). This is the\n * text read AFTER the loop finished — it is never handed to the loop. Identical\n * in spirit to `kbText` in the research-quality A/B so both metrics read a KB the\n * same way.\n */\nexport function kbIndexToText(index: KnowledgeIndex): string {\n const pageText = index.pages.map((page) => `${page.title}\\n${page.text}`).join('\\n\\n')\n const sourceText = index.sources\n .map((source) => `${source.title ?? ''}\\n${source.text ?? ''}`)\n .join('\\n\\n')\n return `${pageText}\\n\\n${sourceText}`\n}\n\n/**\n * Grade one company's KB against its held-out material-fact checklist, given the\n * KB's already-joined text. The pure core — no I/O — so calibration can score a\n * hand-written shallow/deep thesis string directly and the live path can score a\n * real KB. Returns the surfaced FRACTION plus the per-fact audit trail.\n */\nexport function materialFactsSurfacedInText(\n company: CompanyEvalCase,\n kbText: string,\n): MaterialFactsResult {\n const grade = gradeCompanyAgainstText(company, kbText)\n const perFact: FactResult[] = company.facts.map((fact) => {\n const r = gradeFactAgainstText(fact, kbText)\n return {\n id: fact.id,\n lens: fact.lens,\n surfaced: r.surfaced,\n groupsFound: r.groupsFound,\n groupsTotal: r.groupsTotal,\n foundLabels: r.foundLabels,\n }\n })\n return {\n ticker: company.ticker,\n company: company.company,\n surfaced: grade.surfaced,\n total: grade.total,\n fraction: grade.total === 0 ? 0 : grade.surfaced / grade.total,\n perFact,\n }\n}\n\n/**\n * `materialFactsSurfaced(kb, checklist)` — the metric in its KB-reading form.\n *\n * `kb` is EITHER a knowledge-base root directory (the loop wrote pages there) or\n * an already-built `KnowledgeIndex`. `checklist` is the company's held-out\n * `CompanyEvalCase`. Returns the surfaced fraction + per-fact trail.\n *\n * The checklist is HELD OUT by construction: it lives in the test eval set, is\n * never passed to the loop, and is read only here, after the loop finished.\n */\nexport async function materialFactsSurfaced(\n kb: string | KnowledgeIndex,\n checklist: CompanyEvalCase,\n): Promise<MaterialFactsResult> {\n const index = typeof kb === 'string' ? await buildKnowledgeIndex(kb) : kb\n return materialFactsSurfacedInText(checklist, kbIndexToText(index))\n}\n","import type { KnowledgeReadinessReport } from '@tangle-network/agent-eval'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n buildEvalKnowledgeBundle,\n type EvalKnowledgeBundleBuildResult,\n type KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport { createKnowledgeEvent } from './events'\nimport { buildKnowledgeIndex } from './indexer'\nimport { applyKnowledgeWriteBlocks } from './proposals'\nimport { readinessFor } from './readiness-helpers'\nimport { searchKnowledge } from './search'\nimport { type AddSourceOptions, type AddSourceTextInput, addSourceText } from './sources'\nimport { initKnowledgeBase } from './store'\nimport type { KnowledgeEvent, KnowledgeIndex, KnowledgeSearchResult, SourceRecord } from './types'\n\n/**\n * A knowledge gap the loop surfaces from `scoreKnowledgeReadiness`. The worker\n * targets these; the driver folds the unfilled remainder into the worker's next\n * prompt and runs its own gap-fill pass over them.\n */\nexport interface KnowledgeGap {\n /** Readiness-spec id this gap belongs to. */\n id: string\n /** Human-readable description of what's missing. */\n description: string\n /** The search query the readiness check ran for this requirement. */\n query: string\n /** True when the gap blocks readiness (vs. a soft, non-blocking gap). */\n blocking: boolean\n}\n\n/** A new source the worker (or driver) discovered and wants to add to the KB. */\nexport type ResearchSourceProposal = AddSourceTextInput\n\n/**\n * What a research agent contributes in one round. Both the worker and (when\n * `driverResearches` is on) the driver produce this shape — the worker ADDS\n * primary findings, the driver gap-FILLS the ones the worker missed.\n *\n * `proposalText` is the safe write-protocol text (`---FILE: knowledge/...---`\n * blocks). The loop only applies it AFTER the driver has verified the round's\n * sources, so a rejected source never reaches the curated pages.\n */\nexport interface ResearchContribution {\n /** Immutable sources to register (the raw evidence). */\n sources?: ResearchSourceProposal[]\n /** Safe write-protocol text producing curated `knowledge/*.md` pages. */\n proposalText?: string\n /**\n * Build the page write-protocol text FROM the sources the driver accepted —\n * the curated, citing pages the readiness gate searches. Receives the\n * registered `SourceRecord`s (with their assigned ids, so a page's frontmatter\n * `sources:` can cite them). Returns `---FILE: knowledge/...---` block text or\n * `undefined`. Runs after verification, so a page never cites a rejected\n * source. Concatenated after any static `proposalText`.\n */\n buildPages?: (acceptedSources: SourceRecord[]) => string | undefined\n /** Free-form research transcript — products can persist this. */\n notes?: string\n metadata?: Record<string, unknown>\n}\n\n/** Context handed to the worker each round. */\nexport interface WorkerResearchContext {\n root: string\n goal: string\n round: number\n index: KnowledgeIndex\n /** Gaps the readiness gate currently reports — what the worker should close. */\n gaps: KnowledgeGap[]\n /** Steer text the driver folded in from the previous round's remaining gaps. */\n steer?: string\n readiness: EvalKnowledgeBundleBuildResult\n signal?: AbortSignal\n}\n\n/** Context handed to the driver's verifier for one candidate source. */\nexport interface SourceVerificationContext {\n root: string\n goal: string\n round: number\n index: KnowledgeIndex\n gaps: KnowledgeGap[]\n /** Sources already accepted earlier THIS round (in-round dedup). */\n acceptedThisRound: ResearchSourceProposal[]\n signal?: AbortSignal\n}\n\n/** A single rejected source plus the reason the driver gave. */\nexport interface RejectedSource {\n source: ResearchSourceProposal\n reason: string\n}\n\n/** Context handed to the driver's gap-fill pass (only when `driverResearches`). */\nexport interface DriverResearchContext {\n root: string\n goal: string\n round: number\n index: KnowledgeIndex\n /** Gaps STILL open after the worker's accepted contribution applied. */\n remainingGaps: KnowledgeGap[]\n readiness: EvalKnowledgeBundleBuildResult\n signal?: AbortSignal\n}\n\n/**\n * The differentiated driver role.\n *\n * - `verifySource` — the gate the worker's additions pass before they commit.\n * Return `{ accept: true }` to keep a source or `{ accept: false, reason }`\n * to reject it (not real / not relevant / duplicate). The loop dedups exact\n * duplicates (same `uri` already in the KB or accepted this round) BEFORE\n * calling this, so the verifier only sees genuinely-new candidates.\n * - `research` — the driver's OWN gap-fill pass over the gaps the worker left\n * open. Only invoked when `driverResearches` is true.\n * - `foldGaps` — turn the remaining gaps into a steer string for the worker's\n * next prompt. Defaults to a compact bulleted list when omitted.\n */\nexport interface ResearchDriver {\n verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> | SourceVerdict\n research?(ctx: DriverResearchContext): Promise<ResearchContribution> | ResearchContribution\n foldGaps?(gaps: KnowledgeGap[]): string\n}\n\nexport type SourceVerdict = { accept: true } | { accept: false; reason: string }\n\n/** The worker: primary research targeting the round's gaps. */\nexport type ResearchWorker = (\n ctx: WorkerResearchContext,\n) => Promise<ResearchContribution> | ResearchContribution\n\nexport interface VerifiedResearchLoopOptions {\n root: string\n goal: string\n worker: ResearchWorker\n driver: ResearchDriver\n /**\n * When false (default), the driver ONLY verifies + gates — a pure coordinator\n * that contributes no research of its own (the \"doesn't participate in the\n * work\" mode). When true, the driver also runs its `research` gap-fill pass\n * each round over the gaps the worker left open.\n */\n driverResearches?: boolean\n maxRounds?: number\n actor?: string\n /** Readiness specs define the gate; an empty list means the loop never gates. */\n readinessSpecs?: KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n sourceOptions?: Pick<AddSourceOptions, 'adapters' | 'now'>\n signal?: AbortSignal\n onRound?: (round: VerifiedResearchRound) => Promise<void> | void\n}\n\nexport interface VerifiedResearchRound {\n round: number\n /** Gaps reported at the START of the round (what the worker targeted). */\n gaps: KnowledgeGap[]\n /** Worker sources accepted by the driver and written to the KB. */\n acceptedWorkerSources: SourceRecord[]\n /** Worker sources the driver rejected (with reasons) — never written. */\n rejectedWorkerSources: RejectedSource[]\n /** Sources the driver itself added in its gap-fill pass. */\n driverSources: SourceRecord[]\n /** Curated pages written this round (worker proposal + driver proposal). */\n writtenPages: string[]\n readiness?: EvalKnowledgeBundleBuildResult\n /** True once the readiness gate reports no blocking gaps. */\n ready: boolean\n event: KnowledgeEvent\n notes: { worker?: string; driver?: string }\n}\n\nexport interface VerifiedResearchLoopResult {\n root: string\n goal: string\n rounds: number\n ready: boolean\n index: KnowledgeIndex\n readiness?: EvalKnowledgeBundleBuildResult\n steps: VerifiedResearchRound[]\n}\n\n/**\n * Two-agent (driver + worker) sibling of `runKnowledgeResearchLoop`.\n *\n * Both agents research to grow ONE knowledge base. The roles are differentiated:\n *\n * - **WORKER** = primary research. Each round it reads the open gaps, discovers\n * new sources, and proposes additions (`sources` + `proposalText`). It ADDS.\n * - **DRIVER** = the verifier / gap-filler / gate. It (1) VERIFIES the worker's\n * sources before they commit — dedup against the KB, then `verifySource`\n * rejects ones that aren't real/relevant; (2) GAP-FILLS the gaps the worker\n * missed with its own research pass (when `driverResearches`); (3) folds the\n * remaining gaps into the worker's next prompt; and (4) GATES on\n * `scoreKnowledgeReadiness` — the loop stops as soon as there are no blocking\n * gaps.\n *\n * Set `driverResearches: false` (default) for the pure-coordinator mode: the\n * driver only verifies + gates and contributes no research itself.\n *\n * Composes existing atoms — `initKnowledgeBase`, `addSourceText`,\n * `applyKnowledgeWriteBlocks`, `buildEvalKnowledgeBundle` (the readiness gate),\n * and `searchKnowledge` — and reinvents none of them.\n */\nexport async function runVerifiedResearchLoop(\n options: VerifiedResearchLoopOptions,\n): Promise<VerifiedResearchLoopResult> {\n const maxRounds = Math.max(1, options.maxRounds ?? 3)\n await initKnowledgeBase(options.root)\n const steps: VerifiedResearchRound[] = []\n let index = await buildKnowledgeIndex(options.root)\n let readiness = readinessFor(options, index)\n let ready = isReady(readiness?.report)\n let steer: string | undefined\n\n for (let round = 1; round <= maxRounds && !ready; round++) {\n if (options.signal?.aborted) throw new Error('Two-agent research loop aborted')\n\n const gaps = gapsFromReadiness(readiness)\n\n // 1. WORKER: primary research over the open gaps.\n const workerContribution = await options.worker({\n root: options.root,\n goal: options.goal,\n round,\n index,\n gaps,\n steer,\n readiness: requireReadiness(readiness, options),\n signal: options.signal,\n })\n\n // 2. DRIVER VERIFIES the worker's sources before they commit.\n const accepted: ResearchSourceProposal[] = []\n const rejectedWorkerSources: RejectedSource[] = []\n // Dedup against the ORIGINAL input uri. `addSourceText` rewrites `record.uri`\n // to a slugified raw path and stashes the caller's uri under\n // `metadata.originalUri`, so that — not the stored uri — is the round-to-round\n // identity a verifier dedups against.\n const existingUris = new Set(\n index.sources.flatMap((source) =>\n typeof source.metadata?.originalUri === 'string' ? [source.metadata.originalUri] : [],\n ),\n )\n for (const source of workerContribution.sources ?? []) {\n if (isDuplicate(source, existingUris, accepted)) {\n rejectedWorkerSources.push({ source, reason: 'duplicate: already in the knowledge base' })\n continue\n }\n const verdict = await options.driver.verifySource(source, {\n root: options.root,\n goal: options.goal,\n round,\n index,\n gaps,\n acceptedThisRound: accepted,\n signal: options.signal,\n })\n if (verdict.accept) accepted.push(source)\n else rejectedWorkerSources.push({ source, reason: verdict.reason })\n }\n\n // Register the accepted worker sources, then apply the worker's curated\n // pages — but only when at least one source survived verification, so a\n // page never cites a rejected source.\n const acceptedWorkerSources = await registerSources(options, accepted)\n const writtenPages: string[] = []\n writtenPages.push(\n ...(await applyPages(options.root, workerContribution, acceptedWorkerSources)),\n )\n\n // Re-index so the driver's gap-fill pass sees the worker's contribution.\n index = await buildKnowledgeIndex(options.root)\n readiness = readinessFor(options, index)\n\n // 3. DRIVER GAP-FILLS the gaps the worker left open (opt-in).\n let driverSources: SourceRecord[] = []\n let driverNotes: string | undefined\n if (options.driverResearches && options.driver.research) {\n const remainingGaps = gapsFromReadiness(readiness)\n const driverContribution = await options.driver.research({\n root: options.root,\n goal: options.goal,\n round,\n index,\n remainingGaps,\n readiness: requireReadiness(readiness, options),\n signal: options.signal,\n })\n driverNotes = driverContribution.notes\n driverSources = await registerSources(options, driverContribution.sources ?? [])\n writtenPages.push(...(await applyPages(options.root, driverContribution, driverSources)))\n index = await buildKnowledgeIndex(options.root)\n readiness = readinessFor(options, index)\n }\n\n // 4. DRIVER GATES on readiness and folds the remainder into the next prompt.\n ready = isReady(readiness?.report)\n const remainingGaps = gapsFromReadiness(readiness)\n steer = ready ? undefined : foldGaps(options.driver, remainingGaps)\n\n const step: VerifiedResearchRound = {\n round,\n gaps,\n acceptedWorkerSources,\n rejectedWorkerSources,\n driverSources,\n writtenPages,\n readiness,\n ready,\n event: createKnowledgeEvent({\n type: 'research.iteration',\n actor: options.actor,\n target: options.root,\n metadata: {\n goal: options.goal,\n round,\n ready,\n acceptedWorkerSourceCount: acceptedWorkerSources.length,\n rejectedWorkerSourceCount: rejectedWorkerSources.length,\n driverSourceCount: driverSources.length,\n writtenPageCount: writtenPages.length,\n remainingGapCount: remainingGaps.length,\n },\n }),\n notes: { worker: workerContribution.notes, driver: driverNotes },\n }\n steps.push(step)\n await options.onRound?.(step)\n }\n\n return {\n root: options.root,\n goal: options.goal,\n rounds: steps.length,\n ready,\n index,\n readiness,\n steps,\n }\n}\n\nfunction isReady(report: KnowledgeReadinessReport | undefined): boolean {\n // No specs ⇒ no gate ⇒ the loop runs to `maxRounds`. With specs, the gate is\n // \"no blocking gaps remain\".\n if (!report) return false\n return report.blockingMissingRequirements.length === 0\n}\n\nfunction gapsFromReadiness(readiness: EvalKnowledgeBundleBuildResult | undefined): KnowledgeGap[] {\n if (!readiness) return []\n const blocking = readiness.report.blockingMissingRequirements.map((requirement) =>\n gapFor(requirement, readiness, true),\n )\n const nonBlocking = readiness.report.nonBlockingGaps.map((requirement) =>\n gapFor(requirement, readiness, false),\n )\n return [...blocking, ...nonBlocking]\n}\n\nfunction gapFor(\n requirement: { id: string; description: string; metadata?: Record<string, unknown> },\n readiness: EvalKnowledgeBundleBuildResult,\n blocking: boolean,\n): KnowledgeGap {\n const spec = readiness.requirements.find((entry) => entry.id === requirement.id)\n const query =\n typeof spec?.metadata?.query === 'string' ? spec.metadata.query : requirement.description\n return { id: requirement.id, description: requirement.description, query, blocking }\n}\n\nfunction foldGaps(driver: ResearchDriver, gaps: KnowledgeGap[]): string | undefined {\n if (gaps.length === 0) return undefined\n if (driver.foldGaps) return driver.foldGaps(gaps)\n return [\n 'The knowledge base is still missing the following. Prioritise these next round:',\n ...gaps.map(\n (gap) => `- (${gap.blocking ? 'blocking' : 'soft'}) ${gap.description} [${gap.id}]`,\n ),\n ].join('\\n')\n}\n\nfunction isDuplicate(\n source: ResearchSourceProposal,\n existingUris: Set<string>,\n accepted: ResearchSourceProposal[],\n): boolean {\n return existingUris.has(source.uri) || accepted.some((candidate) => candidate.uri === source.uri)\n}\n\nasync function registerSources(\n options: VerifiedResearchLoopOptions,\n sources: ResearchSourceProposal[],\n): Promise<SourceRecord[]> {\n const records: SourceRecord[] = []\n for (const source of sources) {\n records.push(await addSourceText(options.root, source, options.sourceOptions))\n }\n return records\n}\n\n/**\n * Apply a contribution's curated pages. Static `proposalText` plus a\n * `buildPages(acceptedSources)` result are concatenated and run through the safe\n * write protocol — but ONLY when at least one source survived verification, so a\n * page never cites a rejected (or absent) source.\n */\nasync function applyPages(\n root: string,\n contribution: ResearchContribution,\n acceptedSources: SourceRecord[],\n): Promise<string[]> {\n if (acceptedSources.length === 0) return []\n const parts: string[] = []\n if (contribution.proposalText) parts.push(contribution.proposalText)\n const built = contribution.buildPages?.(acceptedSources)\n if (built) parts.push(built)\n if (parts.length === 0) return []\n const applied = await applyKnowledgeWriteBlocks(root, parts.join('\\n'))\n return applied.written\n}\n\nfunction requireReadiness(\n readiness: EvalKnowledgeBundleBuildResult | undefined,\n options: VerifiedResearchLoopOptions,\n): EvalKnowledgeBundleBuildResult {\n if (readiness) return readiness\n // The worker/driver contexts type `readiness` as required for ergonomics; when\n // no specs are configured there is no gate to report, so synthesise an empty\n // bundle rather than forcing every caller to handle `undefined`.\n return buildEvalKnowledgeBundle({\n ...(options.readiness ?? {}),\n taskId: options.readinessTaskId ?? options.goal,\n index: emptyIndex(options.root),\n specs: [],\n })\n}\n\nfunction emptyIndex(root: string): KnowledgeIndex {\n return {\n root,\n generatedAt: new Date(0).toISOString(),\n sources: [],\n pages: [],\n graph: { nodes: [], edges: [] },\n }\n}\n\n/**\n * Helper for verifiers: does the candidate source's text/title overlap any page\n * the readiness search returns for a gap query? A cheap relevance heuristic the\n * driver can compose into `verifySource` (real verifiers can do more).\n */\nexport function sourceMatchesGaps(\n source: ResearchSourceProposal,\n index: KnowledgeIndex,\n gaps: KnowledgeGap[],\n): KnowledgeSearchResult[] {\n const haystack = `${source.title ?? ''}\\n${source.text}`.toLowerCase()\n const hits: KnowledgeSearchResult[] = []\n for (const gap of gaps) {\n for (const token of gap.query.toLowerCase().split(/\\s+/).filter(Boolean)) {\n if (haystack.includes(token)) {\n hits.push(...searchKnowledge(index, gap.query, 1))\n break\n }\n }\n }\n return hits\n}\n\n// ── Deprecated aliases ───────────────────────────────────────────────────────────\n// The old \"TwoAgent\" names described the MECHANISM (a proposer worker + a verifier driver)\n// instead of the VALUE (research whose sources are verified before admission). Kept as\n// aliases so existing importers do not break; prefer the `Verified*` names.\n\n/** @deprecated Renamed to {@link runVerifiedResearchLoop}. */\nexport const runTwoAgentResearchLoop = runVerifiedResearchLoop\n/** @deprecated Renamed to {@link VerifiedResearchLoopOptions}. */\nexport type TwoAgentResearchLoopOptions = VerifiedResearchLoopOptions\n/** @deprecated Renamed to {@link VerifiedResearchLoopResult}. */\nexport type TwoAgentResearchLoopResult = VerifiedResearchLoopResult\n/** @deprecated Renamed to {@link VerifiedResearchRound}. */\nexport type TwoAgentResearchRound = VerifiedResearchRound\n","import { z } from 'zod'\nimport { readRegularFileWithinRoot, writeJsonDurableWithinRoot } from './durable-fs'\nimport type { KnowledgeEventQuery } from './events'\nimport { buildKnowledgeGraph } from './graph'\nimport { withKnowledgeMutation, withKnowledgeRead } from './mutation-lock'\nimport {\n KnowledgeEventSchema,\n KnowledgeIndexSchema,\n KnowledgePageSchema,\n SourceRecordSchema,\n} from './schemas'\nimport type { KnowledgeEvent, KnowledgeIndex, KnowledgePage, SourceRecord } from './types'\n\nexport interface KbStore {\n putSource(source: SourceRecord): Promise<void>\n getSource(id: string): Promise<SourceRecord | null>\n listSources(): Promise<SourceRecord[]>\n putPage(page: KnowledgePage): Promise<void>\n getPage(idOrPath: string): Promise<KnowledgePage | null>\n listPages(): Promise<KnowledgePage[]>\n putIndex(index: KnowledgeIndex): Promise<void>\n getIndex(): Promise<KnowledgeIndex | null>\n putEvent(event: KnowledgeEvent): Promise<void>\n listEvents(query?: KnowledgeEventQuery): Promise<KnowledgeEvent[]>\n}\n\nexport class MemoryKbStore implements KbStore {\n private readonly sources = new Map<string, SourceRecord>()\n private readonly pages = new Map<string, KnowledgePage>()\n private readonly events: KnowledgeEvent[] = []\n private index: KnowledgeIndex | null = null\n\n async putSource(source: SourceRecord): Promise<void> {\n this.sources.set(source.id, clone(source))\n }\n\n async getSource(id: string): Promise<SourceRecord | null> {\n return clone(this.sources.get(id) ?? null)\n }\n\n async listSources(): Promise<SourceRecord[]> {\n return [...this.sources.values()].map(clone)\n }\n\n async putPage(page: KnowledgePage): Promise<void> {\n this.pages.set(page.id, clone(page))\n }\n\n async getPage(idOrPath: string): Promise<KnowledgePage | null> {\n return clone(\n this.pages.get(idOrPath) ??\n [...this.pages.values()].find((page) => page.path === idOrPath) ??\n null,\n )\n }\n\n async listPages(): Promise<KnowledgePage[]> {\n return [...this.pages.values()].map(clone)\n }\n\n async putIndex(index: KnowledgeIndex): Promise<void> {\n this.index = clone(index)\n }\n\n async getIndex(): Promise<KnowledgeIndex | null> {\n if (this.index) return clone(this.index)\n const pages = await this.listPages()\n const sources = await this.listSources()\n return {\n root: 'memory',\n generatedAt: new Date().toISOString(),\n sources,\n pages,\n graph: buildKnowledgeGraph(pages),\n }\n }\n\n async putEvent(event: KnowledgeEvent): Promise<void> {\n this.events.push(clone(event))\n }\n\n async listEvents(query: KnowledgeEventQuery = {}): Promise<KnowledgeEvent[]> {\n let out = this.events\n if (query.type) out = out.filter((event) => event.type === query.type)\n if (query.target) out = out.filter((event) => event.target === query.target)\n out = [...out].sort((a, b) => a.createdAt.localeCompare(b.createdAt))\n return out.slice(-(query.limit ?? out.length)).map(clone)\n }\n}\n\nconst knowledgeEventsSchema = z.array(KnowledgeEventSchema)\n\nexport class FileSystemKbStore implements KbStore {\n constructor(private readonly dir: string) {}\n\n async putSource(source: SourceRecord): Promise<void> {\n const parsed = SourceRecordSchema.parse(source) as SourceRecord\n await this.updateIndex((index) => ({\n ...index,\n generatedAt: new Date().toISOString(),\n sources: [parsed, ...index.sources.filter((entry) => entry.id !== parsed.id)],\n }))\n }\n\n async getSource(id: string): Promise<SourceRecord | null> {\n return withKnowledgeRead(this.dir, async () => {\n const index = await this.readIndex()\n return clone(index?.sources.find((source) => source.id === id) ?? null)\n })\n }\n\n async listSources(): Promise<SourceRecord[]> {\n return withKnowledgeRead(this.dir, async () => clone((await this.readIndex())?.sources ?? []))\n }\n\n async putPage(page: KnowledgePage): Promise<void> {\n const parsed = KnowledgePageSchema.parse(page) as KnowledgePage\n await this.updateIndex((index) => {\n const pages = [parsed, ...index.pages.filter((entry) => entry.id !== parsed.id)]\n return {\n ...index,\n generatedAt: new Date().toISOString(),\n pages,\n graph: buildKnowledgeGraph(pages),\n }\n })\n }\n\n async getPage(idOrPath: string): Promise<KnowledgePage | null> {\n return withKnowledgeRead(this.dir, async () => {\n const index = await this.readIndex()\n return clone(\n index?.pages.find((page) => page.id === idOrPath || page.path === idOrPath) ?? null,\n )\n })\n }\n\n async listPages(): Promise<KnowledgePage[]> {\n return withKnowledgeRead(this.dir, async () => clone((await this.readIndex())?.pages ?? []))\n }\n\n async putIndex(index: KnowledgeIndex): Promise<void> {\n const parsed = KnowledgeIndexSchema.parse(index) as KnowledgeIndex\n await withKnowledgeMutation(this.dir, () =>\n writeJsonDurableWithinRoot(this.dir, 'index.json', parsed),\n )\n }\n\n async getIndex(): Promise<KnowledgeIndex | null> {\n return withKnowledgeRead(this.dir, () => this.readIndex())\n }\n\n async putEvent(event: KnowledgeEvent): Promise<void> {\n const parsed = KnowledgeEventSchema.parse(event) as KnowledgeEvent\n await withKnowledgeMutation(this.dir, async () => {\n const current = await this.readEvents()\n const next = [...current.filter((entry) => entry.id !== parsed.id), parsed].sort((a, b) =>\n a.createdAt.localeCompare(b.createdAt),\n )\n await writeJsonDurableWithinRoot(this.dir, 'events.json', next)\n })\n }\n\n async listEvents(query: KnowledgeEventQuery = {}): Promise<KnowledgeEvent[]> {\n return withKnowledgeRead(this.dir, async () => {\n let events = await this.readEvents()\n if (query.type) events = events.filter((event) => event.type === query.type)\n if (query.target) events = events.filter((event) => event.target === query.target)\n return clone(events.slice(-(query.limit ?? events.length)))\n })\n }\n\n private async updateIndex(change: (index: KnowledgeIndex) => KnowledgeIndex): Promise<void> {\n await withKnowledgeMutation(this.dir, async () => {\n const current = (await this.readIndex()) ?? emptyIndex(this.dir)\n const next = KnowledgeIndexSchema.parse(change(current)) as KnowledgeIndex\n await writeJsonDurableWithinRoot(this.dir, 'index.json', next)\n })\n }\n\n private async readIndex(): Promise<KnowledgeIndex | null> {\n return readJsonFile(\n this.dir,\n 'index.json',\n KnowledgeIndexSchema,\n ) as Promise<KnowledgeIndex | null>\n }\n\n private async readEvents(): Promise<KnowledgeEvent[]> {\n return ((await readJsonFile(this.dir, 'events.json', knowledgeEventsSchema)) ??\n []) as KnowledgeEvent[]\n }\n}\n\nfunction emptyIndex(root: string): KnowledgeIndex {\n return {\n root,\n generatedAt: new Date(0).toISOString(),\n sources: [],\n pages: [],\n graph: { nodes: [], edges: [] },\n }\n}\n\nasync function readJsonFile<T>(\n root: string,\n relativePath: string,\n schema: z.ZodType<T>,\n): Promise<T | null> {\n try {\n const file = await readRegularFileWithinRoot(root, relativePath)\n return schema.parse(JSON.parse(file.bytes.toString('utf8')))\n } catch (error) {\n if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return null\n throw error\n }\n}\n\nfunction clone<T>(value: T): T {\n return value == null ? value : (JSON.parse(JSON.stringify(value)) as T)\n}\n","/**\n * Bridge from `AnalystFinding` (agent-eval) to knowledge proposals.\n *\n * Closes the failure → wiki side of the recursive-self-improvement\n * loop: a knowledge-gap or knowledge-poisoning finding produced by an\n * analyst becomes a concrete proposal an operator (or auto-merge bot)\n * can review and apply. The bridge is intentionally lossless on the\n * fail-loud side — a finding the parser can't classify returns a\n * `KnowledgeProposalParseError` rather than a silent skip, so the\n * loop never accepts an underspecified edit.\n *\n * Subject grammar this bridge understands (analyst-side convention,\n * stamped in the kind prompts):\n *\n * agent-knowledge:wiki:<page-slug> create / update page\n * agent-knowledge:wiki:<page-slug>#<heading> insert section under page\n * agent-knowledge:claim:<topic> draft claim row\n * agent-knowledge:raw:<source-id> lift raw → curated\n * agent-knowledge:stale:<page-slug> mark page superseded\n *\n * Anything else (websearch:outdated:*, tool-doc:*, system-prompt:*,\n * memory:*) is NOT a knowledge-base concern and returns `null` so the\n * loop's improvement-applier handles it.\n */\n\nimport type { AnalystFinding, AnalystSeverity } from '@tangle-network/agent-eval'\nimport type { ClaimRef, KnowledgeClaim, KnowledgeWriteBlock } from './types'\n\nexport interface KnowledgeProposal {\n /**\n * Stable id derived from the finding so cross-run diffs share an\n * identity. Re-proposing the same finding produces the same id.\n */\n id: string\n /** The finding that generated this proposal — useful for audit + revert. */\n sourceFindingId: string\n /** What the proposal does. */\n kind:\n | 'create-page'\n | 'update-page'\n | 'append-section'\n | 'create-claim'\n | 'lift-raw'\n | 'mark-stale'\n /** Locus on disk (page slug or claim topic). */\n locus: string\n /**\n * Page write blocks the standard `applyKnowledgeWriteBlocks` consumer\n * accepts. Empty for proposals that don't change page text (e.g.\n * `create-claim` produces a `claim` field instead).\n */\n writeBlocks: KnowledgeWriteBlock[]\n /**\n * Granular claim draft for proposals whose unit-of-change is a claim\n * row rather than a whole page. `status: 'draft'` until reviewed.\n */\n claim?: KnowledgeClaim\n /** Per-proposal metadata: severity, confidence, source span. */\n metadata: {\n severity: AnalystSeverity\n confidence: number\n evidence_uri?: string\n analyst_id: string\n }\n}\n\nexport class KnowledgeProposalParseError extends Error {\n constructor(\n public readonly findingId: string,\n public readonly subject: string,\n message: string,\n ) {\n super(`proposeFromFinding(${findingId}, subject=${subject}): ${message}`)\n this.name = 'KnowledgeProposalParseError'\n }\n}\n\n/**\n * Convert one `AnalystFinding` into a knowledge proposal. Returns\n * `null` when the finding's locus isn't a knowledge-base concern\n * (`websearch:outdated:*`, `tool-doc:*`, `system-prompt:*`,\n * `memory:*`, missing subject). Throws when the locus IS a\n * knowledge-base concern but is malformed — that's a bug in the\n * analyst prompt and should fail loud.\n *\n * Caller convention: feed the function the analyst's full findings\n * list and filter out the `null`s; the orchestrator passes the\n * remaining proposals to the existing review / apply pipeline.\n */\nexport function proposeFromFinding(finding: AnalystFinding): KnowledgeProposal | null {\n if (!finding.subject) return null\n if (!finding.subject.startsWith('agent-knowledge:')) return null\n\n const rest = finding.subject.slice('agent-knowledge:'.length)\n const [kindPart, ...locusParts] = rest.split(':')\n const locus = locusParts.join(':')\n if (!kindPart || !locus) {\n throw new KnowledgeProposalParseError(\n finding.finding_id,\n finding.subject,\n 'expected `agent-knowledge:<kind>:<locus>` shape',\n )\n }\n\n const baseMeta: KnowledgeProposal['metadata'] = {\n severity: finding.severity,\n confidence: finding.confidence,\n evidence_uri: finding.evidence_refs[0]?.uri,\n analyst_id: finding.analyst_id,\n }\n\n switch (kindPart) {\n case 'wiki':\n return wikiProposal(finding, locus, baseMeta)\n case 'claim':\n return claimProposal(finding, locus, baseMeta)\n case 'raw':\n return liftRawProposal(finding, locus, baseMeta)\n case 'stale':\n return markStaleProposal(finding, locus, baseMeta)\n default:\n throw new KnowledgeProposalParseError(\n finding.finding_id,\n finding.subject,\n `unknown kind \"${kindPart}\" (expected one of: wiki | claim | raw | stale)`,\n )\n }\n}\n\nfunction wikiProposal(\n finding: AnalystFinding,\n locus: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const hashIdx = locus.indexOf('#')\n const pageSlug = hashIdx >= 0 ? locus.slice(0, hashIdx) : locus\n const heading = hashIdx >= 0 ? locus.slice(hashIdx + 1) : null\n const path = `knowledge/${ensureSlug(pageSlug)}.md`\n\n const body = renderWikiBody(finding, pageSlug, heading)\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: heading ? 'append-section' : 'create-page',\n locus: pageSlug,\n writeBlocks: [{ path, content: body }],\n metadata,\n }\n}\n\nfunction claimProposal(\n finding: AnalystFinding,\n locus: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const refs: ClaimRef[] = finding.evidence_refs\n .filter((r) => r.uri)\n .map((r) => ({\n sourceId: `analyst-finding:${finding.finding_id}`,\n anchorId: r.uri,\n quote: r.excerpt,\n }))\n const claim: KnowledgeClaim = {\n id: `claim-${finding.finding_id}`,\n text: finding.recommended_action ?? finding.claim,\n refs,\n confidence: finding.confidence,\n status: 'draft',\n metadata: {\n analyst_id: finding.analyst_id,\n source_finding_id: finding.finding_id,\n topic: locus,\n },\n }\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: 'create-claim',\n locus,\n writeBlocks: [],\n claim,\n metadata,\n }\n}\n\nfunction liftRawProposal(\n finding: AnalystFinding,\n sourceId: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const path = `knowledge/${ensureSlug(sourceId)}.md`\n const body = [\n '---',\n `title: ${sourceId}`,\n `source: ${sourceId}`,\n `status: draft`,\n `lifted_from_finding: ${finding.finding_id}`,\n '---',\n '',\n '## Why this page exists',\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['## Rationale', '', finding.rationale, ''] : []),\n ...(finding.recommended_action\n ? ['## Recommended action', '', finding.recommended_action, '']\n : []),\n ].join('\\n')\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: 'lift-raw',\n locus: sourceId,\n writeBlocks: [{ path, content: body }],\n metadata,\n }\n}\n\nfunction markStaleProposal(\n finding: AnalystFinding,\n pageSlug: string,\n metadata: KnowledgeProposal['metadata'],\n): KnowledgeProposal {\n const path = `knowledge/${ensureSlug(pageSlug)}.stale.md`\n const body = [\n '---',\n `title: ${pageSlug} (marked stale)`,\n `status: superseded`,\n `superseded_by_finding: ${finding.finding_id}`,\n `confidence: ${finding.confidence}`,\n '---',\n '',\n '## Why marked stale',\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['## Evidence', '', finding.rationale, ''] : []),\n ...(finding.recommended_action ? ['## Action', '', finding.recommended_action, ''] : []),\n ].join('\\n')\n return {\n id: `prop-${finding.finding_id}`,\n sourceFindingId: finding.finding_id,\n kind: 'mark-stale',\n locus: pageSlug,\n writeBlocks: [{ path, content: body }],\n metadata,\n }\n}\n\n/**\n * Plural convenience: filter + map across an entire findings batch\n * with one call. Parse errors collect into `errors[]`; the loop\n * decides per-error whether to abort or continue.\n */\nexport interface ProposeFromFindingsResult {\n proposals: KnowledgeProposal[]\n skipped: number\n errors: KnowledgeProposalParseError[]\n}\n\nexport function proposeFromFindings(\n findings: ReadonlyArray<AnalystFinding>,\n): ProposeFromFindingsResult {\n const proposals: KnowledgeProposal[] = []\n const errors: KnowledgeProposalParseError[] = []\n let skipped = 0\n for (const f of findings) {\n try {\n const p = proposeFromFinding(f)\n if (p) proposals.push(p)\n else skipped += 1\n } catch (err) {\n if (err instanceof KnowledgeProposalParseError) errors.push(err)\n else throw err\n }\n }\n return { proposals, skipped, errors }\n}\n\nfunction ensureSlug(s: string): string {\n return (\n s\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 200) || 'untitled'\n )\n}\n\nfunction renderWikiBody(finding: AnalystFinding, slug: string, heading: string | null): string {\n const title = humanize(slug)\n if (heading) {\n return [\n `## ${heading}`,\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['### Rationale', '', finding.rationale, ''] : []),\n ...(finding.recommended_action ? ['### Action', '', finding.recommended_action, ''] : []),\n `_Drafted from finding ${finding.finding_id} (confidence ${finding.confidence.toFixed(2)})._`,\n ].join('\\n')\n }\n return [\n '---',\n `title: ${title}`,\n `status: draft`,\n `drafted_from_finding: ${finding.finding_id}`,\n `confidence: ${finding.confidence}`,\n '---',\n '',\n `# ${title}`,\n '',\n finding.claim,\n '',\n ...(finding.rationale ? ['## Rationale', '', finding.rationale, ''] : []),\n ...(finding.recommended_action\n ? ['## Recommended action', '', finding.recommended_action, '']\n : []),\n ].join('\\n')\n}\n\nfunction humanize(slug: string): string {\n return (\n slug\n .split('-')\n .filter(Boolean)\n .map((w) => w[0]?.toUpperCase() + w.slice(1))\n .join(' ') || slug\n )\n}\n","import type {\n BuildEvalKnowledgeBundleOptions,\n EvalKnowledgeBundleBuildResult,\n KnowledgeReadinessSpec,\n} from './eval-readiness'\nimport { buildKnowledgeIndex } from './indexer'\nimport {\n type KnowledgeBaseQualityOptions,\n type KnowledgeBaseQualityReport,\n scoreKnowledgeBaseIndex,\n} from './rag-eval'\nimport { readinessFor } from './readiness-helpers'\nimport type { KnowledgeIndex } from './types'\nimport {\n type ValidateKnowledgeOptions,\n type ValidateKnowledgeResult,\n validateKnowledgeIndex,\n} from './validate'\n\nexport interface EvaluateKnowledgeBaseReadinessOptions {\n root: string\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: ValidateKnowledgeOptions['strict']\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\nexport interface KnowledgeBaseReadinessEvaluation {\n ready: boolean\n summary: string\n index: KnowledgeIndex\n validation: ValidateKnowledgeResult\n readiness?: EvalKnowledgeBundleBuildResult\n kbQuality: KnowledgeBaseQualityReport\n dimensions: {\n validation: number\n kb_quality: number\n blocking_readiness: number\n }\n}\n\nexport async function evaluateKnowledgeBaseReadiness(\n options: EvaluateKnowledgeBaseReadinessOptions,\n): Promise<KnowledgeBaseReadinessEvaluation> {\n const index = await buildKnowledgeIndex(options.root)\n const validation = validateKnowledgeIndex(index, { strict: options.strict })\n const readiness = readinessFor(\n {\n ...options,\n readinessSpecs: options.readinessSpecs ? [...options.readinessSpecs] : undefined,\n },\n index,\n )\n const kbQuality = scoreKnowledgeBaseIndex(index, {\n strict: options.strict,\n ...options.kbQuality,\n })\n const blockingMissing = readiness?.report.blockingMissingRequirements.length ?? 0\n const blockingTotal =\n options.readinessSpecs?.filter((spec) => spec.importance === 'blocking').length ?? 0\n const blockingReadiness =\n blockingTotal === 0 ? 1 : Math.max(0, blockingTotal - blockingMissing) / blockingTotal\n const ready = validation.ok && kbQuality.ok && blockingMissing === 0\n const failures = [\n validation.ok ? undefined : `${validation.findings.length} validation finding(s)`,\n kbQuality.ok ? undefined : `${kbQuality.findings.length} KB quality finding(s)`,\n blockingMissing === 0\n ? undefined\n : `${blockingMissing}/${blockingTotal} blocking readiness requirement(s) missing`,\n ].filter((failure): failure is string => Boolean(failure))\n\n return {\n ready,\n summary: ready ? 'knowledge base passed readiness checks' : failures.join('; '),\n index,\n validation,\n readiness,\n kbQuality,\n dimensions: {\n validation: validation.ok ? 1 : 0,\n kb_quality: kbQuality.ok ? 1 : 0,\n blocking_readiness: blockingReadiness,\n },\n }\n}\n","import {\n evaluateReleaseConfidence,\n type GateDecision,\n type ReleaseConfidenceScorecard,\n type ReleaseTraceEvidence,\n type RunRecord,\n validateRunRecord,\n} from '@tangle-network/agent-eval'\nimport { stableId } from './ids'\nimport type { KnowledgeRelease } from './types'\n\nexport interface KnowledgeReleaseReport {\n release: KnowledgeRelease\n scorecard: ReleaseConfidenceScorecard\n candidateRuns: RunRecord[]\n baselineRuns: RunRecord[]\n}\n\n/**\n * Campaign-native release report. The caller (a consumer's KB self-improvement\n * loop) supplies the candidate/baseline `RunRecord[]` (e.g. via\n * `campaignToRunRecords`) + optional per-instance `ReleaseTraceEvidence` + the\n * gate decision; this folds them into a `ReleaseConfidenceScorecard` + a\n * `KnowledgeRelease`. Release confidence is computed from run records + traces,\n * independent of any optimizer result shape.\n */\nexport interface KnowledgeReleaseInput {\n candidateId: string\n baselineId?: string\n candidateRuns: RunRecord[]\n baselineRuns?: RunRecord[]\n traces?: ReleaseTraceEvidence[]\n gateDecision?: GateDecision | null\n /**\n * True when a held-out split was evaluated (drives the holdout threshold).\n *\n * Constraint: the substrate gate keys the holdout requirement off a scenario\n * corpus, which this run-only report does not carry. With `hasHoldout: true`\n * the gate fails closed (`missing_holdout_split`) even when holdout RunRecords\n * are supplied. Callers that gate on a real held-out split should drive\n * `evaluateReleaseConfidence` directly with a dataset/scenarios.\n */\n hasHoldout?: boolean\n /** Candidate is the search-best variant — a promotion precondition. Default true. */\n promotedIsBest?: boolean\n createdAt?: string\n minScore?: number\n}\n\nexport function knowledgeReleaseReport(input: KnowledgeReleaseInput): KnowledgeReleaseReport {\n const baselineRuns = input.baselineRuns ?? []\n const runRecords = [...input.candidateRuns, ...baselineRuns].map(validateRunRecord)\n const scorecard = evaluateReleaseConfidence({\n target: 'agent-knowledge-base',\n candidateId: input.candidateId,\n baselineId: input.baselineId ?? 'baseline',\n traces: input.traces ?? [],\n runs: runRecords,\n gateDecision: input.gateDecision ?? null,\n thresholds: {\n requireCorpus: false,\n // The report gates on RunRecord-level outcomes, not on a separate scenario\n // corpus (KnowledgeReleaseInput carries no dataset/scenarios). The scenario\n // floor must therefore be 0 — otherwise the corpus axis fails closed on a\n // dimension the report has no way to satisfy, masking the run-based gate.\n minScenarioCount: 0,\n requireHoldout: input.hasHoldout ?? false,\n minHoldoutRuns: input.hasHoldout ? 1 : 0,\n minSearchRuns: 1,\n minMeanScore: input.minScore ?? 0.7,\n },\n })\n const release: KnowledgeRelease = {\n id: stableId('krel', `${input.candidateId}:${input.createdAt ?? new Date().toISOString()}`),\n candidateId: input.candidateId,\n createdAt: input.createdAt ?? new Date().toISOString(),\n promoted: scorecard.status !== 'fail' && (input.promotedIsBest ?? true),\n scorecard,\n runRecordIds: runRecords.map((record) => record.runId),\n }\n return { release, scorecard, candidateRuns: input.candidateRuns, baselineRuns }\n}\n","/**\n * Research-DRIVING driver for `runVerifiedResearchLoop`.\n *\n * The shipped drivers all FILTER the worker's sources:\n * - `createVerifyingResearchDriver` judges on-topic relevance,\n * - `createAdaptiveResearchDriver` dedups then triages then escalates,\n * - `createClaimGroundingVerifier` rejects misattributed citations.\n *\n * This driver does the OPPOSITE job: instead of narrowing the worker's output,\n * it DRIVES the research DEEPER each round. Its value is not \"fewer sources\" —\n * it is \"more answered, better-corroborated sub-questions\". Concretely, each\n * round it:\n *\n * 1. EXTRACTS the key claims from the worker's new sources (one LLM pass per\n * source, in `verifySource`; falls back to a deterministic sentence-pull\n * when the model is unavailable so a round never silently extracts nothing).\n * 2. TRACKS each claim's support — the set of INDEPENDENT sources (by canonical\n * host) that assert it — and detects CONTRADICTIONS between a new claim and\n * one already on the ledger.\n * 3. GENERATES the next round's DEEP sub-questions from the accumulated claims,\n * in four kinds — comparative (\"how does X's tradeoff differ from Y's?\"),\n * mechanism (\"under what precise condition does X fail?\"), gap (\"what\n * specific result is missing?\"), and contradiction (\"does any source\n * challenge claim Z?\").\n * 4. FLAGS weakly-supported claims (only ONE independent source) and\n * contradicted claims as INVALIDATION targets and demands the worker find\n * corroborating / refuting evidence for them.\n * 5. FOLDS the deep sub-questions + invalidation challenges into the worker's\n * next prompt via the loop's `foldGaps` → `steer` channel — that is the\n * mechanism that drives DEPTH and VALIDATION rather than breadth.\n *\n * COMPLETION (`isComplete` / the `done` judgment the caller gates on) does NOT\n * look at source COUNT. It is done only when every deep sub-question it raised\n * has been addressed AND every key claim is either supported by >= 2 independent\n * sources OR explicitly marked CONTESTED (a contradiction the loop surfaced and\n * could not resolve). A KB with twenty sources all asserting one unchallenged\n * claim is NOT done; a KB whose handful of claims are each corroborated or\n * contested IS.\n *\n * It reuses `runVerifiedResearchLoop` (it is a plain `ResearchDriver`), the web\n * worker, `sha256` (claim identity), `canonicalizeUrl` (independent-source\n * identity), and the `RouterClient` chat surface; it reinvents none of them.\n */\n\nimport { canonicalizeUrl } from './adaptive-driver'\nimport { sha256 } from './ids'\nimport type {\n KnowledgeGap,\n ResearchDriver,\n ResearchSourceProposal,\n SourceVerdict,\n SourceVerificationContext,\n} from './two-agent-research-loop'\nimport {\n createTangleRouterClient,\n type RouterClient,\n type TangleRouterOptions,\n} from './web-research-worker'\n\n/** The four deep sub-question kinds the driver generates to drive depth. */\nexport type DeepQuestionKind = 'comparative' | 'mechanism' | 'gap' | 'contradiction'\n\n/** A deep sub-question the driver folds into the worker's next prompt. */\nexport interface DeepQuestion {\n kind: DeepQuestionKind\n text: string\n /** sha256-derived stable id, so \"addressed\" can be tracked across rounds. */\n id: string\n /** Claim id(s) this question interrogates (for contradiction/mechanism kinds). */\n claimIds: string[]\n /** True once a later round's evidence addressed it (see `markAddressed`). */\n addressed: boolean\n /** The round this question was raised in. */\n raisedRound: number\n}\n\n/** One tracked claim plus the independent sources that assert it. */\nexport interface TrackedClaim {\n id: string\n /** The claim text as first extracted (kept for prompts/audit). */\n text: string\n /** Canonical hosts of the INDEPENDENT sources that assert this claim. */\n supportingHosts: Set<string>\n /** Source URIs that assert this claim (provenance; may share a host). */\n supportingUris: string[]\n /** Claim ids this claim was found to CONTRADICT (and vice versa). */\n contradicts: Set<string>\n /**\n * CONTESTED = a contradiction the loop surfaced but could not resolve to a\n * single supported claim. A contested claim counts as \"settled enough to be\n * done\" (we report the disagreement) even with < 2 independent sources.\n */\n contested: boolean\n firstSeenRound: number\n}\n\n/** The driver's accumulated research state — the completion oracle reads this. */\nexport interface ResearchDrivingState {\n /** Every claim extracted from the worker's sources, by id. */\n claims: TrackedClaim[]\n /** Every deep sub-question raised, by id. */\n questions: DeepQuestion[]\n /** Claims with exactly one independent source AND not contested. */\n weaklySupported: TrackedClaim[]\n /** Claims supported by >= 2 independent sources. */\n corroborated: TrackedClaim[]\n /** Claims marked contested (a surfaced, unresolved contradiction). */\n contested: TrackedClaim[]\n /** Deep questions still unaddressed. */\n openQuestions: DeepQuestion[]\n /** How many rounds the driver has folded steer for. */\n rounds: number\n}\n\nexport interface ResearchDrivingDriverOptions {\n /** Router client for claim extraction + deep-question generation. */\n router?: RouterClient\n router_options?: TangleRouterOptions\n /**\n * A claim is CORROBORATED at this many INDEPENDENT supporting sources (distinct\n * canonical hosts). Default 2 — the task's \">= 2 independent sources\" bar.\n */\n minIndependentSources?: number\n /** Max deep sub-questions to fold into one round's steer. Default 6. */\n maxQuestionsPerRound?: number\n /** Max claims to extract from a single source. Default 3. */\n maxClaimsPerSource?: number\n /**\n * When the extractor LLM is unavailable, fall back to a deterministic claim\n * pull (the source's leading sentences) so the driver still drives. Default\n * true. Set false to require the model (claims will be empty without it).\n */\n deterministicFallback?: boolean\n /** Observe each round's generated steer (for instrumentation / the script). */\n onSteer?: (steer: ResearchDrivingSteer) => void\n}\n\n/** What the driver folded into one round's worker prompt, surfaced for audit. */\nexport interface ResearchDrivingSteer {\n round: number\n deepQuestions: DeepQuestion[]\n /** Claims it demanded corroborating/refuting evidence for this round. */\n invalidationTargets: TrackedClaim[]\n /** The readiness gaps it interleaved (passed through from the loop). */\n gaps: KnowledgeGap[]\n /** The full steer text handed to the worker. */\n text: string\n}\n\n/**\n * The research-driving driver. It is a `ResearchDriver` (drops straight into\n * `runVerifiedResearchLoop`) PLUS a completion oracle and live state, mirroring\n * how `createAdaptiveResearchDriver` exposes `stats()`.\n */\nexport interface ResearchDrivingDriver extends ResearchDriver {\n /** Live snapshot of the claim ledger + deep questions. */\n researchState(): ResearchDrivingState\n /**\n * The completion oracle — gate `done` on THIS, not on source count. True when\n * every deep sub-question is addressed AND every claim is corroborated\n * (>= `minIndependentSources` independent sources) or explicitly contested.\n * False while any claim is weakly-supported or any deep question is open.\n * Returns false before any claim has been seen (nothing researched yet).\n */\n isComplete(): boolean\n /**\n * The last round's generated steer, or undefined before the first fold. Useful\n * to assert the driver produced deeper questions / invalidation challenges.\n */\n lastSteer(): ResearchDrivingSteer | undefined\n}\n\n/** A claim the extractor returns for one source. */\ninterface ExtractedClaim {\n text: string\n /** A claim id ALREADY on the ledger that this one CONTRADICTS, if the model says so. */\n contradictsExistingId?: string\n}\n\nexport function createResearchDrivingDriver(\n options: ResearchDrivingDriverOptions = {},\n): ResearchDrivingDriver {\n const minIndependentSources = Math.max(2, options.minIndependentSources ?? 2)\n const maxQuestionsPerRound = Math.max(1, options.maxQuestionsPerRound ?? 6)\n const maxClaimsPerSource = Math.max(1, options.maxClaimsPerSource ?? 3)\n const deterministicFallback = options.deterministicFallback ?? true\n\n // The claim ledger, keyed by claim id (sha256 of the normalized claim text).\n const claims = new Map<string, TrackedClaim>()\n // Every deep question raised, by id — so we can mark them addressed later.\n const questions = new Map<string, DeepQuestion>()\n let rounds = 0\n let lastSteer: ResearchDrivingSteer | undefined\n\n function resolveRouter(): RouterClient {\n return options.router ?? createTangleRouterClient(options.router_options)\n }\n\n /** Record a claim from a source, growing its independent-source support. */\n function recordClaim(extracted: ExtractedClaim, sourceUri: string, round: number): TrackedClaim {\n const id = claimId(extracted.text)\n const host = hostOf(sourceUri)\n const existing = claims.get(id)\n if (existing) {\n if (host) existing.supportingHosts.add(host)\n if (!existing.supportingUris.includes(sourceUri)) existing.supportingUris.push(sourceUri)\n linkContradiction(existing, extracted.contradictsExistingId)\n return existing\n }\n const tracked: TrackedClaim = {\n id,\n text: extracted.text.trim(),\n supportingHosts: new Set(host ? [host] : []),\n supportingUris: [sourceUri],\n contradicts: new Set(),\n contested: false,\n firstSeenRound: round,\n }\n linkContradiction(tracked, extracted.contradictsExistingId)\n claims.set(id, tracked)\n return tracked\n }\n\n /** Wire a bidirectional contradiction edge and mark BOTH claims contested. */\n function linkContradiction(claim: TrackedClaim, otherId: string | undefined): void {\n if (!otherId || otherId === claim.id) return\n const other = claims.get(otherId)\n if (!other) return\n claim.contradicts.add(otherId)\n other.contradicts.add(claim.id)\n claim.contested = true\n other.contested = true\n }\n\n /** A claim's independent-source count = distinct canonical hosts. */\n function independentSupport(claim: TrackedClaim): number {\n return claim.supportingHosts.size\n }\n\n function isCorroborated(claim: TrackedClaim): boolean {\n return independentSupport(claim) >= minIndependentSources\n }\n\n /** Weakly-supported = NOT corroborated AND NOT contested → an invalidation target. */\n function isWeak(claim: TrackedClaim): boolean {\n return !isCorroborated(claim) && !claim.contested\n }\n\n function snapshot(): ResearchDrivingState {\n const all = [...claims.values()]\n const allQuestions = [...questions.values()]\n return {\n claims: all,\n questions: allQuestions,\n weaklySupported: all.filter(isWeak),\n corroborated: all.filter(isCorroborated),\n contested: all.filter((claim) => claim.contested),\n openQuestions: allQuestions.filter((question) => !question.addressed),\n rounds,\n }\n }\n\n /**\n * Mark deep questions addressed when later evidence speaks to them. A question\n * is addressed once a NEW claim's text shares enough content words with the\n * question — i.e. the worker brought back evidence on the thing we asked about.\n * Cheap and deterministic; the LLM is reserved for GENERATING questions, not\n * grading them, so the oracle stays a non-model check.\n */\n function markAddressed(newClaimTexts: string[]): void {\n for (const question of questions.values()) {\n if (question.addressed) continue\n // Contradiction questions resolve when one of their claims becomes\n // corroborated or contested (the disagreement was surfaced/settled).\n if (question.kind === 'contradiction') {\n const settled = question.claimIds.some((id) => {\n const claim = claims.get(id)\n return claim ? isCorroborated(claim) || claim.contested : false\n })\n if (settled) question.addressed = true\n continue\n }\n const qWords = contentWordSet(question.text)\n if (qWords.size === 0) continue\n for (const text of newClaimTexts) {\n const overlap = overlapFraction(qWords, contentWordSet(text))\n if (overlap >= 0.5) {\n question.addressed = true\n break\n }\n }\n }\n }\n\n return {\n /**\n * `verifySource` — the per-source hook. This driver does NOT filter for\n * relevance/dedup (other drivers do that, and the loop already dedups exact\n * uris). Its job here is to EXTRACT the source's claims and grow the ledger.\n * It accepts every source that yields at least one extractable claim; it\n * only rejects a source with NO extractable signal at all (empty/unusable),\n * because such a source cannot drive the research and pollutes the KB.\n */\n async verifySource(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<SourceVerdict> {\n const extracted = await extractClaims(source, ctx)\n if (extracted.length === 0) {\n return {\n accept: false,\n reason: 'no extractable claim: source yields nothing to drive the research deeper',\n }\n }\n const newTexts: string[] = []\n for (const claim of extracted) {\n recordClaim(claim, source.uri, ctx.round)\n newTexts.push(claim.text)\n }\n markAddressed(newTexts)\n return { accept: true }\n },\n\n /**\n * `foldGaps` — the DEPTH driver. Runs after the worker's contribution is\n * applied each round. It builds the next round's steer from (1) the readiness\n * gaps the loop still reports, (2) freshly generated DEEP sub-questions, and\n * (3) INVALIDATION challenges for weakly-supported / contradicted claims.\n */\n foldGaps(gaps: KnowledgeGap[]): string {\n rounds += 1\n const round = rounds\n const ledger = [...claims.values()]\n\n // Invalidation targets: claims with one source (need corroboration) OR\n // contradicted claims (need a refutation/resolution). These are what the\n // worker is told to go SHORE UP, not new breadth.\n const invalidationTargets = ledger.filter(\n (claim) => isWeak(claim) || claim.contradicts.size > 0,\n )\n\n // Generate this round's deep sub-questions from the actual ledger claims\n // and register them so completion can track whether they get addressed.\n const deepQuestions = synthesizeDeepQuestions(ledger, round).slice(0, maxQuestionsPerRound)\n for (const question of deepQuestions) {\n if (!questions.has(question.id)) questions.set(question.id, question)\n }\n\n const text = buildSteerText(gaps, deepQuestions, invalidationTargets, minIndependentSources)\n lastSteer = { round, deepQuestions, invalidationTargets, gaps, text }\n options.onSteer?.(lastSteer)\n return text\n },\n\n researchState: snapshot,\n\n isComplete(): boolean {\n const all = [...claims.values()]\n if (all.length === 0) return false\n const everyClaimSettled = all.every((claim) => isCorroborated(claim) || claim.contested)\n const everyQuestionAddressed = [...questions.values()].every((question) => question.addressed)\n return everyClaimSettled && everyQuestionAddressed\n },\n\n lastSteer(): ResearchDrivingSteer | undefined {\n return lastSteer\n },\n }\n\n // -- claim extraction ------------------------------------------------------\n\n async function extractClaims(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ): Promise<ExtractedClaim[]> {\n const ledger = [...claims.values()]\n const fromLlm = await extractClaimsWithLlm(source, ctx, ledger)\n if (fromLlm.length > 0) return fromLlm.slice(0, maxClaimsPerSource)\n if (deterministicFallback) return deterministicClaims(source).slice(0, maxClaimsPerSource)\n return []\n }\n\n async function extractClaimsWithLlm(\n source: ResearchSourceProposal,\n ctx: SourceVerificationContext,\n ledger: TrackedClaim[],\n ): Promise<ExtractedClaim[]> {\n let router: RouterClient\n try {\n router = resolveRouter()\n } catch {\n return []\n }\n const excerpt = source.text.slice(0, 1800)\n const ledgerLines = ledger\n .slice(0, 20)\n .map((claim) => `- [${claim.id}] ${claim.text}`)\n .join('\\n')\n const system =\n 'You extract the KEY factual claims a researcher would cite a page for, and flag ' +\n 'CONTRADICTIONS with claims already on the ledger. ' +\n \"A claim is one concrete, checkable assertion using the page's own terms and numbers. \" +\n 'Return ONLY a JSON array; each item is {\"claim\": string, \"contradicts\": string|null} where ' +\n 'contradicts is the bracketed [id] of a ledger claim this page DIRECTLY contradicts, else null. ' +\n `Return at most ${maxClaimsPerSource} claims. No prose.`\n const user = [\n `Research goal: ${ctx.goal}`,\n `Page title: ${source.title ?? '(none)'}`,\n ledgerLines ? `Claims already on the ledger:\\n${ledgerLines}` : 'Ledger is empty.',\n `Page excerpt:\\n${excerpt}`,\n 'Key claims as JSON [{\"claim\": \"...\", \"contradicts\": \"[id]\"|null}]:',\n ].join('\\n\\n')\n\n let raw = ''\n try {\n raw = await router.chat(\n [\n { role: 'system', content: system },\n { role: 'user', content: user },\n ],\n 1200,\n )\n } catch {\n return []\n }\n return parseExtractedClaims(raw, ledger)\n }\n\n /**\n * Deterministic fallback: pull the leading sentences as candidate claims. Used\n * only when the model is unavailable, so the driver still drives (and the\n * offline test runs with no creds). Each sentence becomes a checkable claim.\n */\n function deterministicClaims(source: ResearchSourceProposal): ExtractedClaim[] {\n const sentences = source.text\n .split(/(?<=[.!?])\\s+/)\n .map((sentence) => sentence.trim())\n .filter((sentence) => contentWordSet(sentence).size >= 3)\n return sentences.slice(0, maxClaimsPerSource).map((text) => ({ text }))\n }\n\n // -- deep-question synthesis ----------------------------------------------\n\n /**\n * Build the four deep-question kinds from the actual ledger claims. This is\n * intentionally deterministic (not an LLM call): the loop's `foldGaps` contract\n * is synchronous (`foldGaps(gaps): string`), and a template grounded in the\n * real claim text gives a faithful, non-fabricated sub-question every round —\n * comparative, mechanism, gap, and contradiction. Claim EXTRACTION, which runs\n * inside the awaited `verifySource`, is where the model does the open-ended\n * work; question generation just interrogates what was extracted.\n */\n function synthesizeDeepQuestions(ledger: TrackedClaim[], round: number): DeepQuestion[] {\n if (ledger.length === 0) return []\n const out: DeepQuestion[] = []\n\n // CONTRADICTION questions: for every contradiction edge, ask the worker to\n // find evidence that resolves which claim holds.\n for (const claim of ledger) {\n for (const otherId of claim.contradicts) {\n const other = ledger.find((entry) => entry.id === otherId)\n if (!other || other.id < claim.id) continue // emit each pair once\n out.push(\n makeQuestion(\n 'contradiction',\n `Does any independent source resolve the contradiction between \"${truncate(claim.text)}\" and \"${truncate(other.text)}\"? Find evidence that confirms or refutes one of them.`,\n [claim.id, other.id],\n round,\n ),\n )\n }\n }\n\n // GAP questions: for each weakly-supported claim, ask for the specific\n // corroborating result that is missing.\n for (const claim of ledger.filter((entry) => !entry.contested)) {\n if (claim.supportingHosts.size < minIndependentSources) {\n out.push(\n makeQuestion(\n 'gap',\n `Only one independent source supports \"${truncate(claim.text)}\". What specific corroborating result, dataset, or independent measurement is missing to confirm it?`,\n [claim.id],\n round,\n ),\n )\n }\n }\n\n // MECHANISM questions: for the best-supported claims, probe the failure\n // boundary — under what precise condition does the asserted effect break.\n for (const claim of [...ledger]\n .sort((a, b) => b.supportingHosts.size - a.supportingHosts.size)\n .slice(0, 2)) {\n out.push(\n makeQuestion(\n 'mechanism',\n `Under what precise condition does \"${truncate(claim.text)}\" stop holding? Find a source that states the mechanism, limit, or failure mode.`,\n [claim.id],\n round,\n ),\n )\n }\n\n // COMPARATIVE questions: pair the two most-supported claims and ask how their\n // tradeoffs differ.\n const ranked = [...ledger].sort((a, b) => b.supportingHosts.size - a.supportingHosts.size)\n if (ranked.length >= 2 && ranked[0] && ranked[1]) {\n out.push(\n makeQuestion(\n 'comparative',\n `How does the tradeoff in \"${truncate(ranked[0].text)}\" differ from \"${truncate(ranked[1].text)}\"? Find a source that compares them directly.`,\n [ranked[0].id, ranked[1].id],\n round,\n ),\n )\n }\n\n // Stable order: contradiction → gap → mechanism → comparative (most urgent\n // validation work first).\n const priority: Record<DeepQuestionKind, number> = {\n contradiction: 0,\n gap: 1,\n mechanism: 2,\n comparative: 3,\n }\n return out.sort((a, b) => priority[a.kind] - priority[b.kind])\n }\n}\n\n// ---------------------------------------------------------------------------\n// pure helpers\n// ---------------------------------------------------------------------------\n\nfunction makeQuestion(\n kind: DeepQuestionKind,\n text: string,\n claimIds: string[],\n raisedRound: number,\n): DeepQuestion {\n return {\n kind,\n text,\n id: `q_${sha256(`${kind}:${text}`).slice(0, 16)}`,\n claimIds,\n addressed: false,\n raisedRound,\n }\n}\n\n/** Claim identity = sha256 of the normalized claim text (same words ⇒ same claim). */\nfunction claimId(text: string): string {\n return `c_${sha256(normalizeText(text)).slice(0, 16)}`\n}\n\nfunction hostOf(uri: string): string {\n try {\n return new URL(uri.trim()).hostname.toLowerCase().replace(/^www\\./, '')\n } catch {\n // Non-URL identifier (offline corpus uris like `web/foo`): canonicalize so\n // distinct identifiers still count as distinct independent sources.\n return canonicalizeUrl(uri)\n }\n}\n\nfunction normalizeText(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\nconst stopwords = new Set([\n 'the',\n 'a',\n 'an',\n 'and',\n 'or',\n 'but',\n 'of',\n 'to',\n 'in',\n 'on',\n 'for',\n 'with',\n 'as',\n 'by',\n 'at',\n 'from',\n 'that',\n 'this',\n 'these',\n 'those',\n 'it',\n 'its',\n 'is',\n 'are',\n 'was',\n 'were',\n 'be',\n 'been',\n 'being',\n 'has',\n 'have',\n 'had',\n 'can',\n 'will',\n 'would',\n 'should',\n 'may',\n 'might',\n 'not',\n 'no',\n 'than',\n 'then',\n 'over',\n 'under',\n 'about',\n 'into',\n 'their',\n 'they',\n 'them',\n])\n\nfunction contentWordSet(text: string): Set<string> {\n return new Set(\n normalizeText(text)\n .split(' ')\n .filter((word) => word.length >= 3 && !stopwords.has(word)),\n )\n}\n\nfunction overlapFraction(a: Set<string>, b: Set<string>): number {\n if (a.size === 0) return 0\n let hits = 0\n for (const word of a) if (b.has(word)) hits += 1\n return hits / a.size\n}\n\nfunction truncate(text: string, max = 140): string {\n const t = text.trim().replace(/\\s+/g, ' ')\n return t.length <= max ? t : `${t.slice(0, max - 1)}…`\n}\n\n/**\n * Parse the extractor's JSON array of `{claim, contradicts}` items, tolerant of\n * code fences / surrounding prose. `contradicts` is mapped from a `[id]` token to\n * a ledger claim id only when that id is actually on the ledger.\n */\nfunction parseExtractedClaims(raw: string, ledger: TrackedClaim[]): ExtractedClaim[] {\n const text = raw.trim()\n if (!text) return []\n const arrayMatch = text.match(/\\[[\\s\\S]*\\]/)\n if (!arrayMatch) return []\n let parsed: unknown\n try {\n parsed = JSON.parse(arrayMatch[0])\n } catch {\n return []\n }\n if (!Array.isArray(parsed)) return []\n const ledgerIds = new Set(ledger.map((claim) => claim.id))\n const out: ExtractedClaim[] = []\n for (const item of parsed) {\n if (!item || typeof item !== 'object') continue\n const record = item as { claim?: unknown; contradicts?: unknown }\n if (typeof record.claim !== 'string' || !record.claim.trim()) continue\n const contradictsId = extractBracketId(record.contradicts)\n out.push({\n text: record.claim.trim(),\n contradictsExistingId:\n contradictsId && ledgerIds.has(contradictsId) ? contradictsId : undefined,\n })\n }\n return out\n}\n\n/** Pull a ledger id out of a `contradicts` field: `\"[c_abc]\"` or `\"c_abc\"`. */\nfunction extractBracketId(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (!trimmed || trimmed.toLowerCase() === 'null') return undefined\n const bracket = trimmed.match(/\\[([^\\]]+)\\]/)\n const id = (bracket?.[1] ?? trimmed).trim()\n return id.startsWith('c_') ? id : undefined\n}\n\n/**\n * Build the steer string handed to the worker's next prompt. Interleaves the\n * readiness gaps the loop still reports with the deep sub-questions and the\n * invalidation challenges — the part that drives DEPTH + VALIDATION.\n */\nfunction buildSteerText(\n gaps: KnowledgeGap[],\n deepQuestions: DeepQuestion[],\n invalidationTargets: TrackedClaim[],\n minIndependentSources: number,\n): string {\n const lines: string[] = []\n lines.push(\n 'Do NOT just add more sources. Go DEEPER and VALIDATE. Address the following before adding breadth:',\n )\n\n if (deepQuestions.length > 0) {\n lines.push('', 'Deep sub-questions to answer this round:')\n for (const question of deepQuestions) {\n lines.push(`- (${question.kind}) ${question.text}`)\n }\n }\n\n if (invalidationTargets.length > 0) {\n lines.push(\n '',\n `Claims needing corroboration or refutation (each must reach >= ${minIndependentSources} INDEPENDENT sources, or be shown contested):`,\n )\n for (const claim of invalidationTargets) {\n const reason =\n claim.contradicts.size > 0\n ? 'CONTRADICTED by another source — find evidence that resolves it'\n : `only ${claim.supportingHosts.size} independent source — find a SECOND, independent corroborating source`\n lines.push(`- \"${truncate(claim.text)}\" — ${reason}`)\n }\n }\n\n if (gaps.length > 0) {\n lines.push('', 'Readiness gaps still open:')\n for (const gap of gaps) {\n lines.push(`- (${gap.blocking ? 'blocking' : 'soft'}) ${gap.description} [${gap.id}]`)\n }\n }\n\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAM,gBAAgB;AAEtB,IAAM,mBAAmB;AAMzB,IAAM,iBAAiB;AAgEvB,IAAM,oBAAoB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAQtD,eAAe,eACb,KACA,MACA,MACmB;AACnB,MAAI;AACJ,WAAS,UAAU,GAAG,WAAW,KAAK,YAAY,WAAW,GAAG;AAC9D,QAAI,KAAK,QAAQ,QAAS,OAAM,IAAI,YAAY,GAAG,SAAS;AAC5D,UAAM,MAAM,MAAM,MAAM,KAAK,IAAI;AACjC,QAAI,IAAI,MAAM,CAAC,kBAAkB,IAAI,IAAI,MAAM,EAAG,QAAO;AACzD,cAAU;AACV,QAAI,YAAY,KAAK,WAAY;AAEjC,UAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC/B,UAAM,UAAU,KAAK,cAAc,KAAK;AACxC,UAAM,SAAS,WAAW,OAAO,KAAK,OAAO,IAAI;AACjD,UAAM,IAAI,QAAQ,CAACA,aAAY,WAAWA,UAA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AAA,EACF;AAEA,MAAI,KAAK,SAAS,GAAG;AACnB,UAAM,KAAK,IAAI,4BAA4B;AAC3C,eAAW,OAAO,MAAM;AACtB,YAAM,KAAK,MAAM,IAAI,WAAW,aAAa,MAAM,KAAK,IAAI,WAAW,KAAK,IAAI,EAAE,GAAG;AAAA,IACvF;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["resolve","reason","sha256DigestSchema","contentWords","stopwords","candidate","evidence","mutation","activationResult","average","unique","sha256DigestSchema","round","join","z","z","join","join","round","remainingGaps","join","z","z","emptyIndex","validateRunRecord","validateRunRecord","resolveRouter","round","hostOf","stopwords"]}