@tangle-network/agent-knowledge 8.0.7 → 8.0.9

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 CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as ResearchSourceVersionSchema, A as MemoryKbStore, At as prepareKnowledgeFileTransaction, B as extractWikilinks, Bt as withSafeDescendant, C as writeSourceRegistry, Ct as recoverPendingKnowledgeMutation, D as KB_EVENTS_PATH, Dt as assertKnowledgeMutationPath, E as KB_CLAIM_LEDGER_DIR, Et as applyKnowledgeFileTransaction, F as isScaffoldPath, Ft as readRegularFileNoFollow, G as KnowledgeGraphEdgeSchema, Gt as writeJsonDurableWithinRoot, H as DeepQuestionSchema, Ht as writeFileDurable, I as layoutFor, It as readRegularFileWithinRoot, J as KnowledgePageInvalidationSchema, K as KnowledgeGraphNodeSchema, Kt as mediaTypeFor, L as loadKnowledgePages, Lt as removeDurable, M as buildKnowledgeGraph, Mt as isKernelAnchoredPath, N as SCAFFOLD_PAGE_BASENAMES, Nt as isMissingFile, O as KB_INDEX_PATH, Ot as finishKnowledgeFileTransaction, P as initKnowledgeBase, Pt as listRegularFilesWithinRoot, Q as ResearchClaimRecordSchema, R as writeJson, Rt as renameDurable, S as sourceRegistryPath, St as inspectPendingKnowledgeMutation, T as FileSystemKbStore, Tt as withKnowledgeRead, U as KnowledgeBaseCandidateSchema, Ut as writeFileDurableWithinRoot, V as normalizeLinkTarget, Vt as withSafeDirectory, W as KnowledgeEventSchema, Wt as writeJsonDurable, X as ResearchClaimEvidenceSchema, Y as KnowledgePageSchema, Z as ResearchClaimLedgerSchema, _ as writeKnowledgeIndex, _t as normalizeClaimText, a as applyKnowledgeWriteBlocksFile, at as assertResearchClaimEvidenceIntegrity, b as loadSourceRegistry, bt as parseFrontmatter, c as validateKnowledgeIndex, ct as claimEvidenceId, d as UncheckableClaimError, dt as deepQuestionId, et as SourceAnchorSchema, f as assertGradeableEvidence, ft as emptyClaimLedger, g as buildKnowledgeIndex, gt as mergeTrackedClaims, h as verifyGradeableEvidence, ht as mergeClaimLedgers, i as applyKnowledgeWriteBlocks, it as assertDeepQuestionIntegrity, j as assertClaimLedgerId, jt as rollbackKnowledgeFileTransaction, k as KB_STORE_DIR, kt as knowledgeFileTransactionPlanHash, l as lintKnowledgeIndex, lt as claimId, m as verdictFor, mt as materializeRegisteredClaimEvidence, n as inspectKnowledgeIndex, nt as KNOWLEDGE_EVENT_TYPES, o as isSafeKnowledgePath, ot as assertResearchClaimLedgerIntegrity, p as gradeFor, pt as linkClaimContradictions, q as KnowledgeIndexSchema, qt as textSourceAdapter, r as stringMetadata, rt as ClaimLedgerGoalConflictError, s as parseKnowledgeWriteBlocks, st as assertTrackedClaimIntegrity, t as explainKnowledgeTarget, tt as SourceRecordSchema, u as CHECKABLE_RUNG_THRESHOLD, ut as claimSourceHost, v as addSourcePath, vt as researchSourceVersionKey, w as ClaimLedgerMigrationRequiredError, wt as withKnowledgeMutation, x as snapshotSourceTextInput, xt as acquireDurableFileLock, y as addSourceText, yt as formatFrontmatter, z as WIKILINK_REGEX, zt as syncDirectory } from "./inspect-B7AJ7CZS.js";
1
+ import { $ as WIKILINK_REGEX, $t as syncDirectory, A as MemoryKbStore, At as mergeTrackedClaims, B as auditKnowledgeCitations, Bt as applyKnowledgeFileTransaction, C as writeSourceRegistry, Ct as claimId, D as KB_EVENTS_PATH, Dt as linkClaimContradictions, E as KB_CLAIM_LEDGER_DIR, Et as emptyClaimLedger, F as assertCurrentRunCitationsResolved, Ft as acquireDurableFileLock, G as resolveRunScopedCitation, Gt as rollbackKnowledgeFileTransaction, H as parseKnowledgeCitationReference, Ht as finishKnowledgeFileTransaction, I as assertKnowledgeCitationAudit, It as inspectPendingKnowledgeMutation, J as initKnowledgeBase, Jt as listRegularFilesWithinRoot, K as resolveRunScopedCitations, Kt as isKernelAnchoredPath, L as assertKnowledgeCitationsResolved, Lt as recoverPendingKnowledgeMutation, M as buildKnowledgeGraph, Mt as researchSourceVersionKey, N as KnowledgeCitationAuditError, Nt as formatFrontmatter, O as KB_INDEX_PATH, Ot as materializeRegisteredClaimEvidence, P as KnowledgeCitationResolutionError, Pt as parseFrontmatter, Q as writeJson, Qt as renameDurable, R as assertRunScopedCitationsResolved, Rt as withKnowledgeMutation, S as sourceRegistryPath, St as claimEvidenceId, T as FileSystemKbStore, Tt as deepQuestionId, U as resolveKnowledgeCitation, Ut as knowledgeFileTransactionPlanHash, V as formatKnowledgeCitationReference, Vt as assertKnowledgeMutationPath, W as resolveKnowledgeCitations, Wt as prepareKnowledgeFileTransaction, X as layoutFor, Xt as readRegularFileWithinRoot, Y as isScaffoldPath, Yt as readRegularFileNoFollow, Z as loadKnowledgePages, Zt as removeDurable, _ as writeKnowledgeIndex, _t as ClaimLedgerGoalConflictError, a as applyKnowledgeWriteBlocksFile, an as writeJsonDurableWithinRoot, at as KnowledgeGraphEdgeSchema, b as loadSourceRegistry, bt as assertResearchClaimLedgerIntegrity, c as validateKnowledgeIndex, ct as KnowledgePageInvalidationSchema, d as UncheckableClaimError, dt as ResearchClaimLedgerSchema, en as withSafeDescendant, et as extractWikilinks, f as assertGradeableEvidence, ft as ResearchClaimRecordSchema, g as buildKnowledgeIndex, gt as KNOWLEDGE_EVENT_TYPES, h as verifyGradeableEvidence, ht as SourceRecordSchema, i as applyKnowledgeWriteBlocks, in as writeJsonDurable, it as KnowledgeEventSchema, j as assertClaimLedgerId, jt as normalizeClaimText, k as KB_STORE_DIR, kt as mergeClaimLedgers, l as lintKnowledgeIndex, lt as KnowledgePageSchema, m as verdictFor, mt as SourceAnchorSchema, n as inspectKnowledgeIndex, nn as writeFileDurable, nt as DeepQuestionSchema, o as isSafeKnowledgePath, on as mediaTypeFor, ot as KnowledgeGraphNodeSchema, p as gradeFor, pt as ResearchSourceVersionSchema, q as SCAFFOLD_PAGE_BASENAMES, qt as isMissingFile, r as stringMetadata, rn as writeFileDurableWithinRoot, rt as KnowledgeBaseCandidateSchema, s as parseKnowledgeWriteBlocks, sn as textSourceAdapter, st as KnowledgeIndexSchema, t as explainKnowledgeTarget, tn as withSafeDirectory, tt as normalizeLinkTarget, u as CHECKABLE_RUNG_THRESHOLD, ut as ResearchClaimEvidenceSchema, v as addSourcePath, vt as assertDeepQuestionIntegrity, w as ClaimLedgerMigrationRequiredError, wt as claimSourceHost, x as snapshotSourceTextInput, xt as assertTrackedClaimIntegrity, y as addSourceText, yt as assertResearchClaimEvidenceIntegrity, z as auditCurrentRunCitations, zt as withKnowledgeRead } from "./inspect-0tmv3xV8.js";
2
2
  import { i as textSourceId, n as slugify, r as stableId, t as sha256 } from "./ids-Bevz_pXV.js";
3
3
  import { A as runSerializedKnowledgeOptimization, C as deterministicRng, D as toOffPolicyTrajectory, E as retrievalHoldoutConfigHash, M as assertImmutableRef, O as jsonCandidateCodec, S as applySessionStickyRetrievalHoldout, T as resetRetrievalHoldoutRegistry, _ as createAgentMemoryBranch, a as createNeo4jAgentMemoryAdapter, b as renderMemoryContext, c as runAgentMemoryImprovement, d as compareAgentMemoryLearning, f as runAgentMemoryLearningExperiment, g as buildAgentMemorySequencesFromBenchmarkCases, h as buildAgentMemorySequenceScenarios, i as AgentMemoryWriteInputSchema, j as scenarioContentFingerprint, k as jsonObjectCandidateCodec, l as createGraphitiMemoryAdapter, m as agentMemorySequenceJudge, n as AgentMemoryKindSchema, o as createMem0MemoryAdapter, p as runAgentMemoryExperiment, r as AgentMemoryScopeSchema, s as mem0MemoryAdapterIdentity, t as AgentMemoryHitSchema, u as graphitiMemoryAdapterIdentity, v as forkAgentMemoryBranchSnapshot, w as emitRetrievalHoldoutBypass, x as applyRetrievalHoldout, y as defaultGetMemoryContext } from "./memory-BPgPIEhj.js";
4
4
  import { n as searchKnowledge, r as tokenizeQuery, t as reciprocalRankFusion } from "./search-CtVJ0PKX.js";
@@ -3997,6 +3997,270 @@ async function optimizeKnowledgeBasePolicy(options) {
3997
3997
  };
3998
3998
  }
3999
3999
  //#endregion
4000
+ //#region src/kb-improvement/selected-candidate.ts
4001
+ const DERIVED_KNOWLEDGE_PATHS = /* @__PURE__ */ new Set(["knowledge/index.md"]);
4002
+ const selectionPathSchema = z.string().min(1).transform((path, context) => {
4003
+ try {
4004
+ return assertKnowledgeMutationPath(path);
4005
+ } catch (error) {
4006
+ context.addIssue({
4007
+ code: "custom",
4008
+ message: error instanceof Error ? error.message : String(error)
4009
+ });
4010
+ return z.NEVER;
4011
+ }
4012
+ });
4013
+ const selectionMetadataSchema = z.record(z.string(), z.json());
4014
+ const measuredSelectionLifecycleSchema = z.object({
4015
+ kind: z.literal("measured-knowledge-change-selection"),
4016
+ version: z.literal(1),
4017
+ selectionDigest: z.string().regex(/^[a-f0-9]{64}$/),
4018
+ sourceCandidateId: z.string().min(1),
4019
+ sourceEvidenceHash: z.string().regex(/^[a-f0-9]{64}$/),
4020
+ sourcePlanHash: z.string().regex(/^[a-f0-9]{64}$/),
4021
+ selectedPaths: z.array(selectionPathSchema),
4022
+ selectedCandidateHash: z.string().regex(/^[a-f0-9]{64}$/),
4023
+ selectedPlanHash: z.string().regex(/^[a-f0-9]{64}$/)
4024
+ }).strict();
4025
+ const measuredSelectionReceiptSchema = z.object({
4026
+ kind: z.literal("measured-knowledge-change-selection-receipt"),
4027
+ version: z.literal(1),
4028
+ receiptHash: z.string().regex(/^[a-f0-9]{64}$/),
4029
+ selectionDigest: z.string().regex(/^[a-f0-9]{64}$/),
4030
+ sourceCandidate: KnowledgeImprovementCandidateRefSchema,
4031
+ sourcePlanHash: z.string().regex(/^[a-f0-9]{64}$/),
4032
+ selectedPaths: z.array(selectionPathSchema),
4033
+ derivedImplementationRef: immutableRefSchema,
4034
+ runId: z.string().min(1),
4035
+ derivedCandidateId: z.string().min(1),
4036
+ derivedCandidateStatus: z.string().min(1),
4037
+ selectedCandidateHash: z.string().regex(/^[a-f0-9]{64}$/),
4038
+ selectedPlanHash: z.string().regex(/^[a-f0-9]{64}$/),
4039
+ selectedEvidenceHash: z.string().regex(/^[a-f0-9]{64}$/),
4040
+ rationale: z.string().trim().min(1).optional(),
4041
+ metadata: selectionMetadataSchema.optional()
4042
+ }).strict();
4043
+ /**
4044
+ * Derive a subset from an already measured candidate, then measure the subset as
4045
+ * a new candidate before it can be promoted.
4046
+ *
4047
+ * Directly filtering an activation plan is unsafe: a whole candidate can pass
4048
+ * while one page subset breaks links, removes supporting sources, or changes a
4049
+ * readiness score. This helper instead applies the chosen changed paths to an
4050
+ * isolated baseline, recomputes the index, runs the ordinary improvement
4051
+ * evaluator, and returns the ordinary candidate reference. Promotion therefore
4052
+ * remains one path and can never admit an unmeasured hybrid.
4053
+ */
4054
+ async function improveSelectedKnowledgeCandidate(options) {
4055
+ const sourceCandidate = Object.freeze(KnowledgeImprovementCandidateRefSchema.parse(options.sourceCandidate));
4056
+ const requestedImplementationRef = immutableRefSchema.parse(options.implementationRef);
4057
+ const enabledEvaluationPhases = normalizeEvaluationPhases(options.enabledEvaluationPhases ?? EVALUATION_PHASES, "enabledEvaluationPhases");
4058
+ const requiredEvaluationPhases = normalizeEvaluationPhases(options.requiredEvaluationPhases ?? [], "requiredEvaluationPhases");
4059
+ const metadata = options.selectionMetadata ? selectionMetadataSchema.parse(structuredClone(options.selectionMetadata)) : void 0;
4060
+ return withKnowledgeImprovementComparison({
4061
+ root: options.root,
4062
+ candidate: sourceCandidate
4063
+ }, async (source) => {
4064
+ const sourcePlan = await knowledgeFilePlanEntries(source.baseline.root, source.candidate.root);
4065
+ const sourcePlanHash = knowledgeFileTransactionPlanHash(sourcePlan);
4066
+ if (sourcePlanHash !== sourceCandidate.promotionPlanHash) throw new Error("source knowledge candidate plan no longer matches its measured identity");
4067
+ const changedSourcePlan = sourcePlan.filter(planEntryChanged).filter(notDerivedPath);
4068
+ const selectedPaths = normalizeSelectedPaths(options.selectedPaths, changedSourcePlan);
4069
+ const selectionDigest = contentHash(immutableJson({
4070
+ kind: "measured-knowledge-change-selection",
4071
+ version: 1,
4072
+ sourceCandidate,
4073
+ sourcePlanHash,
4074
+ selectedPaths,
4075
+ ...options.rationale?.trim() ? { rationale: options.rationale.trim() } : {},
4076
+ ...metadata ? { metadata } : {}
4077
+ }));
4078
+ const derivedImplementationRef = immutableRefSchema.parse(`sha256:${contentHash({
4079
+ engine: "agent-knowledge/measured-selection-v1",
4080
+ implementationRef: requestedImplementationRef,
4081
+ selectionDigest
4082
+ })}`);
4083
+ const runId = options.runId ?? stableId("kimpsel", canonicalJson({
4084
+ root: options.root,
4085
+ goal: options.goal,
4086
+ derivedImplementationRef,
4087
+ selectionDigest
4088
+ }));
4089
+ const selectedEntries = selectedPaths.map((path) => {
4090
+ const entry = changedSourcePlan.find((candidate) => candidate.path === path);
4091
+ if (!entry) throw new Error(`selected knowledge path disappeared: ${path}`);
4092
+ return entry;
4093
+ });
4094
+ const selectionMutationPlanHash = knowledgeFileTransactionPlanHash(selectedEntries);
4095
+ let lifecycleSelection;
4096
+ const result = await improveKnowledgeBase({
4097
+ ...improvementOptions(options),
4098
+ root: options.root,
4099
+ goal: options.goal,
4100
+ implementationRef: derivedImplementationRef,
4101
+ runId,
4102
+ enabledPhases: ["knowledge-update", ...enabledEvaluationPhases],
4103
+ requiredPhases: ["knowledge-update", ...requiredEvaluationPhases],
4104
+ async updateKnowledge(input) {
4105
+ const purpose = `knowledge-selected-candidate:${selectionDigest}`;
4106
+ const recoveryOwner = `knowledge-selected-candidate:${sourceCandidate.candidateId}`;
4107
+ await withKnowledgeMutation(input.candidateRoot, async (lock) => {
4108
+ lock.assertOwned();
4109
+ if (!lock.recovery && selectedEntries.length > 0) {
4110
+ const transaction = await prepareKnowledgeFileTransaction({
4111
+ root: input.candidateRoot,
4112
+ transactionRoot: lock.transactionRoot,
4113
+ purpose,
4114
+ recoveryOwner,
4115
+ mutations: await selectionMutations(source.candidate.root, selectedEntries),
4116
+ now: options.now
4117
+ });
4118
+ if (transaction) {
4119
+ assertSelectionTransaction(transaction, selectionMutationPlanHash);
4120
+ await applyKnowledgeFileTransaction({
4121
+ root: input.candidateRoot,
4122
+ transactionRoot: lock.transactionRoot,
4123
+ transaction,
4124
+ beforeCommit: lock.assertOwned
4125
+ });
4126
+ await finishKnowledgeFileTransaction({
4127
+ root: input.candidateRoot,
4128
+ transactionRoot: lock.transactionRoot,
4129
+ transaction,
4130
+ assertOwned: lock.assertOwned
4131
+ });
4132
+ }
4133
+ }
4134
+ await writeKnowledgeIndex(input.candidateRoot);
4135
+ lock.assertOwned();
4136
+ }, { resumeTransaction: {
4137
+ purpose,
4138
+ recoveryOwner,
4139
+ validate: (transaction) => assertSelectionTransaction(transaction, selectionMutationPlanHash)
4140
+ } });
4141
+ const selectedPlan = await knowledgeFilePlanEntries(source.baseline.root, input.candidateRoot);
4142
+ assertExactSelectedChanges(selectedPlan, selectedPaths);
4143
+ const selectedPlanHash = knowledgeFileTransactionPlanHash(selectedPlan);
4144
+ const selectedCandidateHash = await hashKnowledgeBase(input.candidateRoot);
4145
+ lifecycleSelection = measuredSelectionLifecycleSchema.parse({
4146
+ kind: "measured-knowledge-change-selection",
4147
+ version: 1,
4148
+ selectionDigest,
4149
+ sourceCandidateId: sourceCandidate.candidateId,
4150
+ sourceEvidenceHash: sourceCandidate.evidenceHash,
4151
+ sourcePlanHash,
4152
+ selectedPaths,
4153
+ selectedCandidateHash,
4154
+ selectedPlanHash
4155
+ });
4156
+ return {
4157
+ applied: selectedPaths.length > 0,
4158
+ summary: selectedPaths.length > 0 ? `Applied ${selectedPaths.length} selected measured change(s).` : "Selected no changes; measuring the exact baseline as a null candidate.",
4159
+ metadata: { selection: lifecycleSelection }
4160
+ };
4161
+ }
4162
+ });
4163
+ const candidate = result.candidate;
4164
+ if (!candidate?.candidateHash || !candidate.promotionPlanHash || !candidate.evidenceHash) throw new Error("selected knowledge candidate did not produce measured candidate evidence");
4165
+ const recordedSelection = measuredSelectionLifecycleSchema.parse(result.lifecycle?.knowledgeUpdate?.metadata?.selection ?? lifecycleSelection);
4166
+ if (recordedSelection.selectionDigest !== selectionDigest || recordedSelection.selectedCandidateHash !== candidate.candidateHash || recordedSelection.selectedPlanHash !== candidate.promotionPlanHash || canonicalJson(recordedSelection.selectedPaths) !== canonicalJson(selectedPaths)) throw new Error("selected knowledge candidate evidence does not bind the measured subset");
4167
+ const receiptWithoutHash = immutableJson({
4168
+ kind: "measured-knowledge-change-selection-receipt",
4169
+ version: 1,
4170
+ selectionDigest,
4171
+ sourceCandidate,
4172
+ sourcePlanHash,
4173
+ selectedPaths,
4174
+ derivedImplementationRef,
4175
+ runId: result.runId,
4176
+ derivedCandidateId: candidate.candidateId,
4177
+ derivedCandidateStatus: candidate.status,
4178
+ selectedCandidateHash: candidate.candidateHash,
4179
+ selectedPlanHash: candidate.promotionPlanHash,
4180
+ selectedEvidenceHash: candidate.evidenceHash,
4181
+ ...options.rationale?.trim() ? { rationale: options.rationale.trim() } : {},
4182
+ ...metadata ? { metadata } : {}
4183
+ });
4184
+ const receipt = measuredSelectionReceiptSchema.parse({
4185
+ ...receiptWithoutHash,
4186
+ receiptHash: contentHash(receiptWithoutHash)
4187
+ });
4188
+ await persistSelectionReceipt(options.root, receipt);
4189
+ return {
4190
+ ...result,
4191
+ selection: receipt
4192
+ };
4193
+ });
4194
+ }
4195
+ function improvementOptions(options) {
4196
+ const { root: _root, goal: _goal, implementationRef: _implementationRef, sourceCandidate: _sourceCandidate, selectedPaths: _selectedPaths, runId: _runId, rationale: _rationale, selectionMetadata: _selectionMetadata, enabledEvaluationPhases: _enabledEvaluationPhases, requiredEvaluationPhases: _requiredEvaluationPhases, ...rest } = options;
4197
+ return rest;
4198
+ }
4199
+ function normalizeEvaluationPhases(phases, field) {
4200
+ const unique = [...new Set(phases)];
4201
+ for (const phase of unique) if (phase === "knowledge-acquisition" || phase === "knowledge-update") throw new Error(`${field} cannot contain the selection-owned phase '${phase}'`);
4202
+ return unique;
4203
+ }
4204
+ function normalizeSelectedPaths(paths, changedPlan) {
4205
+ const available = new Set(changedPlan.map((entry) => entry.path));
4206
+ const selected = [];
4207
+ const seen = /* @__PURE__ */ new Set();
4208
+ for (const input of paths) {
4209
+ const path = selectionPathSchema.parse(input);
4210
+ if (DERIVED_KNOWLEDGE_PATHS.has(path)) throw new Error(`derived knowledge path cannot be selected directly: ${path}`);
4211
+ if (seen.has(path)) throw new Error(`selected knowledge path is repeated: ${path}`);
4212
+ if (!available.has(path)) throw new Error(`selected knowledge path is not a changed source-candidate file: ${path}`);
4213
+ seen.add(path);
4214
+ selected.push(path);
4215
+ }
4216
+ return selected.sort((left, right) => left.localeCompare(right));
4217
+ }
4218
+ function planEntryChanged(entry) {
4219
+ return entry.beforeHash !== entry.afterHash || entry.beforeHash !== null && entry.afterHash !== null && entry.beforeMode !== entry.afterMode;
4220
+ }
4221
+ function notDerivedPath(entry) {
4222
+ return !DERIVED_KNOWLEDGE_PATHS.has(entry.path);
4223
+ }
4224
+ async function selectionMutations(sourceCandidateRoot, entries) {
4225
+ return Promise.all(entries.map(async (entry) => {
4226
+ if (entry.afterHash === null) return {
4227
+ path: entry.path,
4228
+ content: null
4229
+ };
4230
+ const file = await readRegularFileWithinRoot(sourceCandidateRoot, entry.path);
4231
+ if (createHash("sha256").update(file.bytes).digest("hex") !== entry.afterHash || file.mode !== entry.afterMode) throw new Error(`source candidate changed before subset materialization: ${entry.path}`);
4232
+ return {
4233
+ path: entry.path,
4234
+ content: file.bytes,
4235
+ mode: file.mode
4236
+ };
4237
+ }));
4238
+ }
4239
+ function assertSelectionTransaction(transaction, expectedPlanHash) {
4240
+ if (knowledgeFileTransactionPlanHash(transaction.entries) !== expectedPlanHash) throw new Error("selected knowledge transaction does not match its approved path set");
4241
+ }
4242
+ function assertExactSelectedChanges(plan, selectedPaths) {
4243
+ const actual = plan.filter(planEntryChanged).filter(notDerivedPath).map((entry) => entry.path).sort((left, right) => left.localeCompare(right));
4244
+ if (canonicalJson(actual) !== canonicalJson(selectedPaths)) throw new Error(`selected knowledge candidate changed the wrong files: expected ${selectedPaths.join(", ") || "(none)"}, got ${actual.join(", ") || "(none)"}`);
4245
+ }
4246
+ async function persistSelectionReceipt(root, receipt) {
4247
+ const runDir = knowledgeImprovementRunDir(root, receipt.runId);
4248
+ const relativePath = join("candidates", safePathSegmentSchema.parse(receipt.derivedCandidateId), "selection.json").replace(/\\/g, "/");
4249
+ try {
4250
+ if (canonicalJson(measuredSelectionReceiptSchema.parse(JSON.parse((await readRegularFileWithinRoot(runDir, relativePath)).bytes.toString("utf8")))) !== canonicalJson(receipt)) throw new Error("measured knowledge selection receipt conflicts with durable content");
4251
+ return;
4252
+ } catch (error) {
4253
+ if (!isMissingFile(error)) throw error;
4254
+ }
4255
+ await writeJsonDurableWithinRoot(runDir, relativePath, receipt);
4256
+ }
4257
+ function immutableJson(value) {
4258
+ if (value === null || typeof value !== "object") return value;
4259
+ const children = Array.isArray(value) ? value : Object.values(value);
4260
+ for (const child of children) immutableJson(child);
4261
+ return Object.freeze(value);
4262
+ }
4263
+ //#endregion
4000
4264
  //#region src/agent-candidate.ts
4001
4265
  /** Convert a measured knowledge candidate into the shared review and execution identity. */
4002
4266
  function toAgentCandidateKnowledgeRef(candidate) {
@@ -4259,6 +4523,45 @@ function mergeTinyChunks(chunks, opts) {
4259
4523
  return out;
4260
4524
  }
4261
4525
  //#endregion
4526
+ //#region src/citation-lint.ts
4527
+ /** Convert a chain-aware citation audit into the package lint vocabulary. */
4528
+ function knowledgeCitationAuditFindings(report) {
4529
+ return report.issues.map(issueToFinding);
4530
+ }
4531
+ /** Lint only current-run pages against their complete declared visibility chain. */
4532
+ async function lintCurrentRunCitations(stores, runId) {
4533
+ return knowledgeCitationAuditFindings(await auditCurrentRunCitations(stores, runId));
4534
+ }
4535
+ function issueToFinding(issue) {
4536
+ const candidates = issue.candidates.map((candidate) => ({
4537
+ pageId: candidate.pageId,
4538
+ path: candidate.page.path,
4539
+ origin: candidate.origin
4540
+ }));
4541
+ if (issue.kind === "ambiguous") return {
4542
+ type: "ambiguous-citation",
4543
+ severity: "error",
4544
+ page: issue.sourcePath,
4545
+ message: `Citation "${issue.persistedCitation}" resolves to ${issue.candidates.length} visible pages; qualify it as here::<pageId>, inherited:<runId>::<pageId>, or shared::<pageId>.`,
4546
+ metadata: {
4547
+ sourcePageId: issue.sourcePageId,
4548
+ sourceOrigin: issue.sourceOrigin,
4549
+ candidates
4550
+ }
4551
+ };
4552
+ return {
4553
+ type: "broken-citation",
4554
+ severity: "error",
4555
+ page: issue.sourcePath,
4556
+ message: issue.kind === "self" ? `Page "${issue.sourcePageId}" cites itself through "${issue.persistedCitation}".` : `Citation "${issue.persistedCitation}" resolves to no visible page.`,
4557
+ metadata: {
4558
+ sourcePageId: issue.sourcePageId,
4559
+ sourceOrigin: issue.sourceOrigin,
4560
+ candidates
4561
+ }
4562
+ };
4563
+ }
4564
+ //#endregion
4262
4565
  //#region src/collection-research-driver.ts
4263
4566
  /**
4264
4567
  * Build the single-agent collection driver. Accepts every source; never gates,
@@ -5651,6 +5954,379 @@ async function runInvestmentThesisTask(input, options) {
5651
5954
  };
5652
5955
  }
5653
5956
  //#endregion
5957
+ //#region src/knowledge-use-receipts.ts
5958
+ const KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION = "1.0.0";
5959
+ const KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM = "rfc8785-sha256";
5960
+ /** Stable content identity for one exact knowledge page. */
5961
+ function knowledgePageDigest(page) {
5962
+ validateKnowledgePage(page);
5963
+ return canonicalCandidateDigest({
5964
+ id: page.id,
5965
+ path: page.path,
5966
+ title: page.title,
5967
+ text: page.text,
5968
+ frontmatter: page.frontmatter,
5969
+ sourceIds: [...page.sourceIds],
5970
+ tags: [...page.tags],
5971
+ outLinks: [...page.outLinks],
5972
+ contradicts: [...page.contradicts ?? []],
5973
+ invalidation: page.invalidation ?? null
5974
+ });
5975
+ }
5976
+ /** Snapshot the exact ordered current/ancestor/shared page view. */
5977
+ function createKnowledgeVisibilitySnapshot(visiblePages) {
5978
+ if (!Array.isArray(visiblePages)) throw new TypeError("knowledge visibility must be an array");
5979
+ const identities = /* @__PURE__ */ new Set();
5980
+ const entries = visiblePages.map((entry, position) => {
5981
+ if (!entry || typeof entry !== "object") throw new TypeError(`knowledge visibility[${position}] must be an originated page`);
5982
+ const origin = validateOrigin(entry.origin, `knowledge visibility[${position}].origin`);
5983
+ validateKnowledgePage(entry.page);
5984
+ const identity = `${origin}\u0000${entry.page.path}`;
5985
+ if (identities.has(identity)) throw new Error(`knowledge visibility repeats path '${entry.page.path}' at origin '${origin}'`);
5986
+ identities.add(identity);
5987
+ return Object.freeze({
5988
+ position,
5989
+ pageId: entry.page.id,
5990
+ origin,
5991
+ path: entry.page.path,
5992
+ pageDigest: knowledgePageDigest(entry.page),
5993
+ sourceIds: Object.freeze([...entry.page.sourceIds]),
5994
+ invalidated: entry.page.invalidation !== void 0
5995
+ });
5996
+ });
5997
+ const material = visibilityMaterial(entries);
5998
+ return Object.freeze({
5999
+ ...material,
6000
+ snapshotDigest: canonicalCandidateDigest(material),
6001
+ entries: Object.freeze(entries)
6002
+ });
6003
+ }
6004
+ /** Create a retrieval receipt and refuse results that were not in the view. */
6005
+ function createKnowledgeRetrievalReceipt(input) {
6006
+ if (!input || typeof input !== "object") throw new TypeError("knowledge retrieval receipt input is required");
6007
+ const runId = nonEmpty(input.runId, "knowledge retrieval runId");
6008
+ const actorId = optionalText(input.actorId, "knowledge retrieval actorId");
6009
+ const profileDigest = optionalDigest(input.profileDigest, "knowledge retrieval profileDigest");
6010
+ const executionRef = optionalDigest(input.executionRef, "knowledge retrieval executionRef");
6011
+ const query = nonEmpty(input.query, "knowledge retrieval query");
6012
+ const retriever = normalizeRetriever(input.retriever);
6013
+ const visibility = createKnowledgeVisibilitySnapshot(input.visiblePages);
6014
+ const results = normalizeRetrievalResults(input.results, visibility);
6015
+ const evidenceRefs = normalizeEvidenceRefs(input.evidenceRefs ?? []);
6016
+ const attributes = normalizeAttributes(input.attributes ?? {});
6017
+ const material = retrievalMaterial({
6018
+ createdAt: isoTimestamp(input.createdAt, "knowledge retrieval createdAt"),
6019
+ runId,
6020
+ actorId,
6021
+ profileDigest,
6022
+ executionRef,
6023
+ query,
6024
+ retriever,
6025
+ visibility,
6026
+ results,
6027
+ evidenceRefs,
6028
+ attributes
6029
+ });
6030
+ return Object.freeze({
6031
+ ...material,
6032
+ receiptDigest: canonicalCandidateDigest(material)
6033
+ });
6034
+ }
6035
+ /** Verify the receipt's schema, internal joins, and canonical digest. */
6036
+ function verifyKnowledgeRetrievalReceipt(receipt) {
6037
+ if (!receipt || typeof receipt !== "object") throw new TypeError("knowledge retrieval receipt is required");
6038
+ if (receipt.schemaVersion !== "1.0.0") throw new Error(`unsupported knowledge retrieval schemaVersion '${receipt.schemaVersion}'`);
6039
+ if (receipt.kind !== "knowledge-retrieval") throw new Error(`knowledge retrieval receipt kind must be 'knowledge-retrieval'`);
6040
+ if (receipt.digestAlgorithm !== "rfc8785-sha256") throw new Error(`unsupported knowledge retrieval digestAlgorithm '${receipt.digestAlgorithm}'`);
6041
+ if (canonicalCandidateDigest(visibilityMaterial(receipt.visibility.entries)) !== receipt.visibility.snapshotDigest) throw new Error("knowledge retrieval visibility snapshot digest mismatch");
6042
+ validateReceiptResults(receipt.results, receipt.visibility);
6043
+ if (canonicalCandidateDigest(retrievalMaterial({
6044
+ createdAt: isoTimestamp(receipt.createdAt, "knowledge retrieval createdAt"),
6045
+ runId: nonEmpty(receipt.runId, "knowledge retrieval runId"),
6046
+ actorId: optionalText(receipt.actorId, "knowledge retrieval actorId"),
6047
+ profileDigest: optionalDigest(receipt.profileDigest, "knowledge retrieval profileDigest"),
6048
+ executionRef: optionalDigest(receipt.executionRef, "knowledge retrieval executionRef"),
6049
+ query: nonEmpty(receipt.query, "knowledge retrieval query"),
6050
+ retriever: normalizeRetriever(receipt.retriever),
6051
+ visibility: receipt.visibility,
6052
+ results: receipt.results,
6053
+ evidenceRefs: normalizeEvidenceRefs(receipt.evidenceRefs),
6054
+ attributes: normalizeAttributes(receipt.attributes)
6055
+ })) !== receipt.receiptDigest) throw new Error("knowledge retrieval receipt digest mismatch");
6056
+ return receipt;
6057
+ }
6058
+ /** Prove that a receipt still describes the supplied visibility bytes. */
6059
+ function assertKnowledgeRetrievalMatchesVisibility(receipt, visiblePages) {
6060
+ verifyKnowledgeRetrievalReceipt(receipt);
6061
+ if (createKnowledgeVisibilitySnapshot(visiblePages).snapshotDigest !== receipt.visibility.snapshotDigest) throw new Error("knowledge retrieval receipt does not match the supplied visibility snapshot");
6062
+ }
6063
+ /** Create a downstream-use receipt for one exact ranked result. */
6064
+ function createKnowledgeUseReceipt(input) {
6065
+ if (!input || typeof input !== "object") throw new TypeError("knowledge use receipt input is required");
6066
+ const retrieval = verifyKnowledgeRetrievalReceipt(input.retrieval);
6067
+ if (!Number.isSafeInteger(input.selectedRank) || input.selectedRank < 1) throw new TypeError("knowledge use selectedRank must be a positive safe integer");
6068
+ const selected = retrieval.results.find((result) => result.rank === input.selectedRank);
6069
+ if (!selected) throw new Error(`knowledge use selectedRank ${input.selectedRank} was not returned by retrieval ${retrieval.receiptDigest}`);
6070
+ const relation = validateUseRelation(input.relation);
6071
+ const consumer = normalizeConsumer(input.consumer);
6072
+ const evidenceRefs = normalizeEvidenceRefs(input.evidenceRefs ?? []);
6073
+ const attributes = normalizeAttributes(input.attributes ?? {});
6074
+ const material = useMaterial({
6075
+ createdAt: isoTimestamp(input.createdAt, "knowledge use createdAt"),
6076
+ retrieval,
6077
+ used: Object.freeze({
6078
+ rank: selected.rank,
6079
+ pageId: selected.pageId,
6080
+ origin: selected.origin,
6081
+ path: selected.path,
6082
+ pageDigest: selected.pageDigest
6083
+ }),
6084
+ relation,
6085
+ consumer,
6086
+ evidenceRefs,
6087
+ attributes
6088
+ });
6089
+ return Object.freeze({
6090
+ ...material,
6091
+ receiptDigest: canonicalCandidateDigest(material)
6092
+ });
6093
+ }
6094
+ /** Verify one use receipt against the exact retrieval that authorized it. */
6095
+ function verifyKnowledgeUseReceipt(receipt, retrieval) {
6096
+ if (!receipt || typeof receipt !== "object") throw new TypeError("knowledge use receipt is required");
6097
+ const verifiedRetrieval = verifyKnowledgeRetrievalReceipt(retrieval);
6098
+ if (receipt.schemaVersion !== "1.0.0") throw new Error(`unsupported knowledge use schemaVersion '${receipt.schemaVersion}'`);
6099
+ if (receipt.kind !== "knowledge-use") throw new Error(`knowledge use receipt kind must be 'knowledge-use'`);
6100
+ if (receipt.digestAlgorithm !== "rfc8785-sha256") throw new Error(`unsupported knowledge use digestAlgorithm '${receipt.digestAlgorithm}'`);
6101
+ if (receipt.retrievalReceiptDigest !== verifiedRetrieval.receiptDigest) throw new Error("knowledge use receipt references a different retrieval receipt");
6102
+ const selected = verifiedRetrieval.results.find((result) => result.rank === receipt.used.rank);
6103
+ if (!selected || selected.pageId !== receipt.used.pageId || selected.origin !== receipt.used.origin || selected.path !== receipt.used.path || selected.pageDigest !== receipt.used.pageDigest) throw new Error("knowledge use receipt selected result does not match the retrieval receipt");
6104
+ if (canonicalCandidateDigest(useMaterial({
6105
+ createdAt: isoTimestamp(receipt.createdAt, "knowledge use createdAt"),
6106
+ retrieval: verifiedRetrieval,
6107
+ used: receipt.used,
6108
+ relation: validateUseRelation(receipt.relation),
6109
+ consumer: normalizeConsumer(receipt.consumer),
6110
+ evidenceRefs: normalizeEvidenceRefs(receipt.evidenceRefs),
6111
+ attributes: normalizeAttributes(receipt.attributes)
6112
+ })) !== receipt.receiptDigest) throw new Error("knowledge use receipt digest mismatch");
6113
+ return receipt;
6114
+ }
6115
+ function visibilityMaterial(entries) {
6116
+ return {
6117
+ schemaVersion: KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION,
6118
+ digestAlgorithm: KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM,
6119
+ entries: entries.map((entry, position) => {
6120
+ if (entry.position !== position) throw new Error(`knowledge visibility position mismatch: expected ${position}, observed ${entry.position}`);
6121
+ return {
6122
+ position,
6123
+ pageId: nonEmpty(entry.pageId, `knowledge visibility[${position}].pageId`),
6124
+ origin: validateOrigin(entry.origin, `knowledge visibility[${position}].origin`),
6125
+ path: nonEmpty(entry.path, `knowledge visibility[${position}].path`),
6126
+ pageDigest: digest(entry.pageDigest, `knowledge visibility[${position}].pageDigest`),
6127
+ sourceIds: entry.sourceIds.map((sourceId, sourceIndex) => nonEmpty(sourceId, `knowledge visibility[${position}].sourceIds[${sourceIndex}]`)),
6128
+ invalidated: Boolean(entry.invalidated)
6129
+ };
6130
+ })
6131
+ };
6132
+ }
6133
+ function retrievalMaterial(input) {
6134
+ return {
6135
+ schemaVersion: KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION,
6136
+ kind: "knowledge-retrieval",
6137
+ digestAlgorithm: KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM,
6138
+ createdAt: input.createdAt,
6139
+ runId: input.runId,
6140
+ ...input.actorId === void 0 ? {} : { actorId: input.actorId },
6141
+ ...input.profileDigest === void 0 ? {} : { profileDigest: input.profileDigest },
6142
+ ...input.executionRef === void 0 ? {} : { executionRef: input.executionRef },
6143
+ query: input.query,
6144
+ retriever: input.retriever,
6145
+ visibility: input.visibility,
6146
+ results: input.results,
6147
+ evidenceRefs: input.evidenceRefs,
6148
+ attributes: input.attributes
6149
+ };
6150
+ }
6151
+ function useMaterial(input) {
6152
+ return {
6153
+ schemaVersion: KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION,
6154
+ kind: "knowledge-use",
6155
+ digestAlgorithm: KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM,
6156
+ createdAt: input.createdAt,
6157
+ runId: input.retrieval.runId,
6158
+ ...input.retrieval.actorId === void 0 ? {} : { actorId: input.retrieval.actorId },
6159
+ ...input.retrieval.profileDigest === void 0 ? {} : { profileDigest: input.retrieval.profileDigest },
6160
+ ...input.retrieval.executionRef === void 0 ? {} : { executionRef: input.retrieval.executionRef },
6161
+ retrievalReceiptDigest: input.retrieval.receiptDigest,
6162
+ used: input.used,
6163
+ relation: input.relation,
6164
+ consumer: input.consumer,
6165
+ evidenceRefs: input.evidenceRefs,
6166
+ attributes: input.attributes
6167
+ };
6168
+ }
6169
+ function normalizeRetrievalResults(results, visibility) {
6170
+ if (!Array.isArray(results)) throw new TypeError("knowledge retrieval results must be an array");
6171
+ const visible = new Map(visibility.entries.map((entry) => [`${entry.origin}\u0000${entry.path}`, entry]));
6172
+ const seenRanks = /* @__PURE__ */ new Set();
6173
+ const seenPages = /* @__PURE__ */ new Set();
6174
+ const normalized = results.map((result, index) => {
6175
+ if (!result || typeof result !== "object") throw new TypeError(`knowledge retrieval results[${index}] must be an object`);
6176
+ if (!Number.isSafeInteger(result.rank) || result.rank < 1) throw new TypeError(`knowledge retrieval results[${index}].rank must be positive`);
6177
+ if (seenRanks.has(result.rank)) throw new Error(`knowledge retrieval repeats rank ${result.rank}`);
6178
+ seenRanks.add(result.rank);
6179
+ const origin = validateOrigin(result.origin, `knowledge retrieval results[${index}].origin`);
6180
+ validateKnowledgePage(result.page);
6181
+ const key = `${origin}\u0000${result.page.path}`;
6182
+ if (seenPages.has(key)) throw new Error(`knowledge retrieval repeats page '${result.page.path}' at origin '${origin}'`);
6183
+ seenPages.add(key);
6184
+ const visibleEntry = visible.get(key);
6185
+ if (!visibleEntry) throw new Error(`knowledge retrieval result '${result.page.path}' at origin '${origin}' was not visible`);
6186
+ const pageDigest = knowledgePageDigest(result.page);
6187
+ if (visibleEntry.pageId !== result.page.id || visibleEntry.pageDigest !== pageDigest) throw new Error(`knowledge retrieval result '${result.page.path}' does not match its visibility snapshot`);
6188
+ finite(result.rrfScore, `knowledge retrieval results[${index}].rrfScore`);
6189
+ finite(result.normalizedScore, `knowledge retrieval results[${index}].normalizedScore`);
6190
+ if (result.normalizedScore < 0 || result.normalizedScore > 1) throw new TypeError(`knowledge retrieval results[${index}].normalizedScore must be in [0,1]`);
6191
+ return Object.freeze({
6192
+ rank: result.rank,
6193
+ pageId: result.page.id,
6194
+ origin,
6195
+ path: result.page.path,
6196
+ pageDigest,
6197
+ rrfScore: result.rrfScore,
6198
+ normalizedScore: result.normalizedScore,
6199
+ snippet: typeof result.snippet === "string" ? result.snippet : "",
6200
+ reasons: Object.freeze(result.reasons.map((reason, reasonIndex) => nonEmpty(reason, `knowledge retrieval results[${index}].reasons[${reasonIndex}]`)))
6201
+ });
6202
+ });
6203
+ normalized.sort((left, right) => left.rank - right.rank);
6204
+ normalized.forEach((result, index) => {
6205
+ if (result.rank !== index + 1) throw new Error(`knowledge retrieval ranks must be contiguous from 1; expected ${index + 1}, observed ${result.rank}`);
6206
+ });
6207
+ return Object.freeze(normalized);
6208
+ }
6209
+ function validateReceiptResults(results, visibility) {
6210
+ const visible = new Map(visibility.entries.map((entry) => [`${entry.origin}\u0000${entry.path}`, entry]));
6211
+ const seen = /* @__PURE__ */ new Set();
6212
+ results.forEach((result, index) => {
6213
+ if (result.rank !== index + 1) throw new Error(`knowledge retrieval ranks must be contiguous from 1; expected ${index + 1}, observed ${result.rank}`);
6214
+ const key = `${validateOrigin(result.origin, `knowledge retrieval results[${index}].origin`)}\u0000${nonEmpty(result.path, `knowledge retrieval results[${index}].path`)}`;
6215
+ if (seen.has(key)) throw new Error(`knowledge retrieval repeats visible page '${result.path}'`);
6216
+ seen.add(key);
6217
+ const entry = visible.get(key);
6218
+ if (!entry || entry.pageId !== result.pageId || entry.pageDigest !== result.pageDigest) throw new Error(`knowledge retrieval result rank ${result.rank} is not in the visibility snapshot`);
6219
+ finite(result.rrfScore, `knowledge retrieval results[${index}].rrfScore`);
6220
+ finite(result.normalizedScore, `knowledge retrieval results[${index}].normalizedScore`);
6221
+ if (result.normalizedScore < 0 || result.normalizedScore > 1) throw new TypeError(`knowledge retrieval results[${index}].normalizedScore must be in [0,1]`);
6222
+ if (!Array.isArray(result.reasons)) throw new TypeError(`knowledge retrieval results[${index}].reasons must be an array`);
6223
+ });
6224
+ }
6225
+ function normalizeRetriever(input) {
6226
+ if (!input || typeof input !== "object") throw new TypeError("knowledge retriever identity is required");
6227
+ return Object.freeze({
6228
+ id: nonEmpty(input.id, "knowledge retriever id"),
6229
+ version: nonEmpty(input.version, "knowledge retriever version"),
6230
+ configDigest: digest(input.configDigest, "knowledge retriever configDigest")
6231
+ });
6232
+ }
6233
+ function normalizeConsumer(input) {
6234
+ if (!input || typeof input !== "object") throw new TypeError("knowledge consumer reference is required");
6235
+ if (![
6236
+ "decision",
6237
+ "artifact",
6238
+ "experiment",
6239
+ "candidate",
6240
+ "message",
6241
+ "other"
6242
+ ].includes(input.kind)) throw new TypeError(`knowledge consumer kind is invalid: ${String(input.kind)}`);
6243
+ return Object.freeze({
6244
+ kind: input.kind,
6245
+ uri: nonEmpty(input.uri, "knowledge consumer uri"),
6246
+ ...input.digest === void 0 ? {} : { digest: digest(input.digest, "knowledge consumer digest") }
6247
+ });
6248
+ }
6249
+ function normalizeEvidenceRefs(values) {
6250
+ if (!Array.isArray(values)) throw new TypeError("knowledge evidenceRefs must be an array");
6251
+ const allowed = [
6252
+ "span",
6253
+ "event",
6254
+ "artifact",
6255
+ "finding",
6256
+ "metric"
6257
+ ];
6258
+ return Object.freeze(values.map((value, index) => {
6259
+ if (!value || typeof value !== "object" || !allowed.includes(value.kind)) throw new TypeError(`knowledge evidenceRefs[${index}].kind is invalid`);
6260
+ return Object.freeze({
6261
+ kind: value.kind,
6262
+ uri: nonEmpty(value.uri, `knowledge evidenceRefs[${index}].uri`),
6263
+ ...value.excerpt === void 0 ? {} : { excerpt: nonEmpty(value.excerpt, `knowledge evidenceRefs[${index}].excerpt`) }
6264
+ });
6265
+ }));
6266
+ }
6267
+ function normalizeAttributes(input) {
6268
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new TypeError("knowledge receipt attributes must be an object");
6269
+ const normalized = {};
6270
+ for (const [key, value] of Object.entries(input)) {
6271
+ const name = nonEmpty(key, "knowledge receipt attribute key");
6272
+ if (value !== null && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new TypeError(`knowledge receipt attribute '${name}' has an unsupported value`);
6273
+ if (typeof value === "number") finite(value, `knowledge receipt attribute '${name}'`);
6274
+ normalized[name] = value;
6275
+ }
6276
+ return Object.freeze(normalized);
6277
+ }
6278
+ function validateUseRelation(value) {
6279
+ if (![
6280
+ "supports",
6281
+ "contradicts",
6282
+ "extends",
6283
+ "rederives",
6284
+ "background"
6285
+ ].includes(value)) throw new TypeError(`knowledge use relation is invalid: ${String(value)}`);
6286
+ return value;
6287
+ }
6288
+ function validateKnowledgePage(page) {
6289
+ if (!page || typeof page !== "object") throw new TypeError("knowledge page must be an object");
6290
+ nonEmpty(page.id, "knowledge page id");
6291
+ nonEmpty(page.path, "knowledge page path");
6292
+ nonEmpty(page.title, "knowledge page title");
6293
+ if (typeof page.text !== "string") throw new TypeError("knowledge page text must be a string");
6294
+ if (!page.frontmatter || typeof page.frontmatter !== "object" || Array.isArray(page.frontmatter)) throw new TypeError("knowledge page frontmatter must be an object");
6295
+ for (const [name, values] of [
6296
+ ["sourceIds", page.sourceIds],
6297
+ ["tags", page.tags],
6298
+ ["outLinks", page.outLinks]
6299
+ ]) if (!Array.isArray(values) || values.some((value) => typeof value !== "string")) throw new TypeError(`knowledge page ${name} must be a string array`);
6300
+ }
6301
+ function validateOrigin(value, label) {
6302
+ if (value === "here" || value === "shared") return value;
6303
+ if (typeof value === "string" && value.startsWith("inherited:") && value.slice(10).trim().length > 0) return value;
6304
+ throw new TypeError(`${label} is invalid: ${String(value)}`);
6305
+ }
6306
+ function digest(value, label) {
6307
+ const parsed = sha256DigestSchema.safeParse(value);
6308
+ if (!parsed.success) throw new TypeError(`${label} must be a lowercase sha256 digest`);
6309
+ return parsed.data;
6310
+ }
6311
+ function optionalDigest(value, label) {
6312
+ return value === void 0 ? void 0 : digest(value, label);
6313
+ }
6314
+ function nonEmpty(value, label) {
6315
+ if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${label} must be a non-empty string`);
6316
+ return value.trim();
6317
+ }
6318
+ function optionalText(value, label) {
6319
+ return value === void 0 ? void 0 : nonEmpty(value, label);
6320
+ }
6321
+ function finite(value, label) {
6322
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError(`${label} must be a finite number`);
6323
+ }
6324
+ function isoTimestamp(value, label) {
6325
+ const date = value === void 0 ? /* @__PURE__ */ new Date() : value instanceof Date ? value : new Date(value);
6326
+ if (!Number.isFinite(date.getTime())) throw new TypeError(`${label} must be a valid timestamp`);
6327
+ return date.toISOString();
6328
+ }
6329
+ //#endregion
5654
6330
  //#region src/propose-from-finding.ts
5655
6331
  var KnowledgeProposalParseError = class extends Error {
5656
6332
  findingId;
@@ -6621,57 +7297,57 @@ function buildSteerText(gaps, deepQuestions, invalidationTargets, minIndependent
6621
7297
  /**
6622
7298
  * Run-scoped knowledge stores with lineage-chain reads.
6623
7299
  *
6624
- * One store per run, physically isolated, with inheritance only by declared ancestry. The design
6625
- * answers a failure mode a discovery campaign paid for twice: when every run writes one shared
6626
- * store, a false "measured" claim from one arm becomes the next arm's settled provenance — twice
6627
- * in that campaign a wrong claim crossed run boundaries and became standing instruction before
6628
- * anyone re-derived it. Isolation makes "what did THIS run learn" a directory listing, and the
6629
- * knowledge delta between two runs a diff of two directories.
6630
- *
6631
- * A branch still inherits: reads walk the run's own store, then each ancestor up a recorded
6632
- * parent chain, then an optional shared store — every page labeled with where it came from,
6633
- * because "I established this", "an earlier attempt believed this", and "the lab curates this"
6634
- * are three different provenance claims and a reader must be able to weigh them differently.
7300
+ * One store exists per run, physically isolated, with inheritance only through
7301
+ * declared ancestry. Reads expose the current store, every declared ancestor,
7302
+ * and an optional curated shared store with an explicit origin label.
6635
7303
  */
6636
7304
  const RUN_LINEAGE_BASENAME = "lineage.json";
6637
- /** Ancestry chains longer than this indicate a cycle or a runaway, not a real lineage. */
7305
+ /** Ancestry beyond this bound is invalid durable state. */
6638
7306
  const MAX_LINEAGE_HOPS = 64;
6639
7307
  function createRunScopedStores(options) {
7308
+ if (!options || typeof options !== "object") throw new TypeError("createRunScopedStores options are required");
7309
+ if (typeof options.root !== "string" || options.root.trim().length === 0) throw new TypeError("createRunScopedStores root must be a non-empty string");
7310
+ if (options.runStorePath !== void 0 && typeof options.runStorePath !== "function") throw new TypeError("createRunScopedStores runStorePath must be a function when present");
7311
+ if (options.lineageAuthority !== void 0) validateLineageAuthority(options.lineageAuthority);
6640
7312
  const storePath = options.runStorePath ?? ((runId) => join(options.root, runId, "knowledge-base"));
6641
- async function parentOf(runId) {
6642
- try {
6643
- const snapshot = await readRegularFileWithinRoot(storePath(runId), RUN_LINEAGE_BASENAME);
6644
- return JSON.parse(snapshot.bytes.toString("utf8")).parentRunId;
6645
- } catch (error) {
6646
- if (isMissingFile(error)) return null;
6647
- throw error;
7313
+ const internalAuthority = createFileRunLineageAuthority(storePath);
7314
+ const authority = options.lineageAuthority ?? internalAuthority;
7315
+ const resolveLineage = async (runId) => {
7316
+ assertRunId(runId);
7317
+ const chain = [];
7318
+ const seen = /* @__PURE__ */ new Set([runId]);
7319
+ let current = runId;
7320
+ for (let hop = 0; hop <= MAX_LINEAGE_HOPS; hop += 1) {
7321
+ const parent = await authority.parentOf(current);
7322
+ if (parent === null) return chain;
7323
+ assertRunId(parent, `parent of '${current}'`);
7324
+ if (seen.has(parent)) throw new Error(`run lineage cycle: ${parent} is its own ancestor (via ${runId})`);
7325
+ seen.add(parent);
7326
+ chain.push(parent);
7327
+ current = parent;
6648
7328
  }
6649
- }
7329
+ throw new Error(`run lineage for '${runId}' exceeds ${MAX_LINEAGE_HOPS} ancestors`);
7330
+ };
6650
7331
  return {
6651
7332
  async init(runId, initOptions = {}) {
7333
+ assertRunId(runId);
7334
+ const parentRunId = initOptions.parentRunId ?? null;
7335
+ if (parentRunId !== null) assertRunId(parentRunId, `parent of '${runId}'`);
7336
+ if (!authority.record) {
7337
+ const existingParent = await authority.parentOf(runId);
7338
+ if (existingParent !== parentRunId) throw new Error(`external lineage authority disagrees for '${runId}': expected ${renderParent(parentRunId)}, observed ${renderParent(existingParent)}`);
7339
+ }
6652
7340
  const layout = await initKnowledgeBase(storePath(runId));
6653
- const record = {
7341
+ if (authority.record) await authority.record(Object.freeze({
6654
7342
  runId,
6655
- parentRunId: initOptions.parentRunId ?? null,
7343
+ parentRunId,
6656
7344
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
6657
- };
6658
- await writeJson(join(storePath(runId), RUN_LINEAGE_BASENAME), record);
7345
+ }));
6659
7346
  return layout;
6660
7347
  },
6661
- async lineage(runId) {
6662
- const chain = [];
6663
- const seen = /* @__PURE__ */ new Set([runId]);
6664
- let current = runId;
6665
- for (let hop = 0; hop < MAX_LINEAGE_HOPS && current !== null; hop += 1) {
6666
- current = await parentOf(current);
6667
- if (current === null) break;
6668
- if (seen.has(current)) throw new Error(`run lineage cycle: ${current} is its own ancestor (via ${runId})`);
6669
- seen.add(current);
6670
- chain.push(current);
6671
- }
6672
- return chain;
6673
- },
7348
+ lineage: resolveLineage,
6674
7349
  async loadChain(runId) {
7350
+ assertRunId(runId);
6675
7351
  const out = [];
6676
7352
  const readInto = async (root, origin) => {
6677
7353
  let pages;
@@ -6687,13 +7363,80 @@ function createRunScopedStores(options) {
6687
7363
  });
6688
7364
  };
6689
7365
  await readInto(storePath(runId), "here");
6690
- for (const ancestor of await this.lineage(runId)) await readInto(storePath(ancestor), `inherited:${ancestor}`);
7366
+ for (const ancestor of await resolveLineage(runId)) await readInto(storePath(ancestor), `inherited:${ancestor}`);
6691
7367
  if (options.sharedRoot) await readInto(options.sharedRoot, "shared");
6692
7368
  return out;
6693
7369
  }
6694
7370
  };
6695
7371
  }
7372
+ /** File-backed authority used when the product has no separate run manifest. */
7373
+ function createFileRunLineageAuthority(runStorePath) {
7374
+ if (typeof runStorePath !== "function") throw new TypeError("createFileRunLineageAuthority requires a runStorePath function");
7375
+ const readRecord = async (runId) => {
7376
+ assertRunId(runId);
7377
+ const root = runStorePath(runId);
7378
+ try {
7379
+ return parseLineageRecord((await readRegularFileWithinRoot(root, RUN_LINEAGE_BASENAME)).bytes.toString("utf8"), runId);
7380
+ } catch (error) {
7381
+ if (isMissingFile(error)) return null;
7382
+ throw error;
7383
+ }
7384
+ };
7385
+ return {
7386
+ async parentOf(runId) {
7387
+ return (await readRecord(runId))?.parentRunId ?? null;
7388
+ },
7389
+ async record(record) {
7390
+ const validated = validateLineageRecord(record);
7391
+ const root = runStorePath(validated.runId);
7392
+ await withKnowledgeMutation(root, async () => {
7393
+ const existing = await readRecord(validated.runId);
7394
+ if (existing) {
7395
+ if (existing.parentRunId !== validated.parentRunId) throw new Error(`run lineage conflict for '${validated.runId}': existing parent ${renderParent(existing.parentRunId)}, requested ${renderParent(validated.parentRunId)}`);
7396
+ return;
7397
+ }
7398
+ await writeJson(join(root, RUN_LINEAGE_BASENAME), validated);
7399
+ });
7400
+ }
7401
+ };
7402
+ }
7403
+ function validateLineageAuthority(authority) {
7404
+ if (!authority || typeof authority !== "object") throw new TypeError("lineageAuthority must be an object");
7405
+ if (typeof authority.parentOf !== "function") throw new TypeError("lineageAuthority.parentOf must be a function");
7406
+ if (authority.record !== void 0 && typeof authority.record !== "function") throw new TypeError("lineageAuthority.record must be a function when present");
7407
+ }
7408
+ function parseLineageRecord(text, expectedRunId) {
7409
+ let parsed;
7410
+ try {
7411
+ parsed = JSON.parse(text);
7412
+ } catch (cause) {
7413
+ throw new Error(`invalid lineage JSON for '${expectedRunId}'`, { cause });
7414
+ }
7415
+ const record = validateLineageRecord(parsed);
7416
+ if (record.runId !== expectedRunId) throw new Error(`lineage record identity mismatch: expected '${expectedRunId}', found '${record.runId}'`);
7417
+ return record;
7418
+ }
7419
+ function validateLineageRecord(value) {
7420
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("run lineage record must be an object");
7421
+ const record = value;
7422
+ assertRunId(record.runId, "lineage record runId");
7423
+ if (record.parentRunId !== null) assertRunId(record.parentRunId, `parent of '${record.runId}'`);
7424
+ if (typeof record.createdAt !== "string" || record.createdAt.trim().length === 0 || !Number.isFinite(Date.parse(record.createdAt))) throw new TypeError("run lineage record createdAt must be an ISO timestamp");
7425
+ return {
7426
+ runId: record.runId,
7427
+ parentRunId: record.parentRunId,
7428
+ createdAt: record.createdAt
7429
+ };
7430
+ }
7431
+ function assertRunId(value, label = "runId") {
7432
+ if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${label} must be a non-empty string`);
7433
+ const trimmed = value.trim();
7434
+ if (trimmed === "." || trimmed === ".." || /[/\\\0]/.test(value)) throw new TypeError(`${label} must not contain path separators or dot segments`);
7435
+ }
7436
+ function renderParent(parentRunId) {
7437
+ return parentRunId === null ? "none" : `'${parentRunId}'`;
7438
+ }
6696
7439
  //#endregion
6697
- export { AgentMemoryHitSchema, AgentMemoryKindSchema, AgentMemoryLifecycleTimeoutError, AgentMemoryLifecycleUnsafeError, AgentMemoryScopeSchema, AgentMemoryWriteInputSchema, CHECKABLE_RUNG_THRESHOLD, ClaimLedgerGoalConflictError, ClaimLedgerMigrationRequiredError, DEFAULT_MEMORY_CLEANUP_TIMEOUT_MS, DeepQuestionSchema, FileSystemKbStore, FileSystemSearchProvider, INDUSTRY_MEMORY_BENCHMARKS, INDUSTRY_RAG_BENCHMARKS, IRS_DIMENSION_HINTS, KB_CLAIM_LEDGER_DIR, KB_EVENTS_PATH, KB_INDEX_PATH, KB_STORE_DIR, KNOWLEDGE_EVENT_TYPES, KnowledgeBaseCandidateSchema, KnowledgeEventSchema, KnowledgeGraphEdgeSchema, KnowledgeGraphNodeSchema, KnowledgeImprovementCandidateRefSchema, KnowledgeImprovementEvidenceSchema, KnowledgeImprovementRunStateSchema, KnowledgeIndexSchema, KnowledgePageInvalidationSchema, KnowledgePageSchema, KnowledgeProposalParseError, MAX_RESPONSE_BYTES, MIN_REQUEST_GAP_MS, MemoryKbStore, POLITE_USER_AGENT, READINESS_SPEC_DEFAULTS, RUN_LINEAGE_BASENAME, ResearchClaimEvidenceSchema, ResearchClaimLedgerSchema, ResearchClaimRecordSchema, ResearchSourceVersionSchema, RouterError, SCAFFOLD_PAGE_BASENAMES, SourceAnchorSchema, SourceRecordSchema, UncheckableClaimError, WIKILINK_REGEX, __resetHttpThrottle, acquireAgentMemoryRunLease, addSourcePath, addSourceText, agentMemorySequenceJudge, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, applyRetrievalHoldout, applySessionStickyRetrievalHoldout, assertClaimLedgerId, assertDeepQuestionIntegrity, assertGradeableEvidence, assertResearchClaimEvidenceIntegrity, assertResearchClaimLedgerIntegrity, assertTrackedClaimIntegrity, buildAgentMemorySequenceScenarios, buildAgentMemorySequencesFromBenchmarkCases, buildEvalKnowledgeBundle, buildFirstPartyMemoryLifecycleBenchmarkCases, buildIndustryMemoryBenchmarkSmokeCases, buildIndustryRagBenchmarkSmokeCases, buildKnowledgeBenchmarkScenarios, buildKnowledgeGraph, buildKnowledgeIndex, buildRetrievalBenchmarkCasesFromQrels, buildRetrievalEvalDispatch, calibrateRagAnswerJudge, canonicalizeUrl, chunkMarkdown, citedClaimKey, citedClaimOf, claimEvidenceId, claimId, claimSourceHost, compareAgentMemoryLearning, contentKey, createAdaptiveResearchDriver, createAgentMemoryBranch, createClaimDecorator, createClaimGroundingVerifier, createCollectionResearchDriver, createCornellLiiSource, createD1FreshnessStoreStub, createFileSystemFreshnessStore, createFileSystemSearchProvider, createGraphitiMemoryAdapter, createInMemoryBenchmarkAdapter, createIrsPublicationsSource, createKnowledgeControlLoopAdapter, createKnowledgeEvent, createLocalDiscoveryDispatcher, createMem0MemoryAdapter, createMemoryExecutionPool, createNeo4jAgentMemoryAdapter, createNoopMemoryBenchmarkAdapter, createPersistentResearchDrivingDriver, createRagAnswerQualityHook, createResearchDrivingDriver, createRunScopedStores, createStateSosSource, createTangleRouterClient, createVerifyingResearchDriver, createWebResearchWorker, deepQuestionId, defaultGetMemoryContext, defineReadinessSpec, detectChanges, detectNearDuplicatePages, deterministicRng, diagnoseRagAnswerFailure, emitRetrievalHoldoutBypass, emptyClaimLedger, evaluateKnowledgeBaseReadiness, explainKnowledgeTarget, extractLinks, extractWikilinks, firstMatch, forkAgentMemoryBranchSnapshot, formatFrontmatter, fromAgentCandidateKnowledgeRef, gradeCompanyAgainstText, gradeFactAgainstText, gradeFor, graphitiMemoryAdapterIdentity, groundClaimInText, hashKnowledgeBase, htmlToText, improveKnowledgeBase, initKnowledgeBase, innerHtmlById, inspectKnowledgeIndex, inspectPendingKnowledgeMutation, investmentThesisSet, isKernelAnchoredPath, isKnowledgeMemoryBenchmarkCase, isMissingFile, isSafeKnowledgePath, isScaffoldPath, jsonCandidateCodec, jsonObjectCandidateCodec, kbIndexToText, knowledgeBenchmarkJudge, knowledgeImprovementCandidateRef, knowledgeImprovementRunDir, knowledgeImprovementRunId, knowledgeReleaseReport, layoutFor, lensDistribution, linkClaimContradictions, lintKnowledgeIndex, listRegularFilesWithinRoot, loadKnowledgeImprovementActivationResult, loadKnowledgeImprovementEvents, loadKnowledgeImprovementState, loadKnowledgePages, loadSourceRegistry, looksLikeBlockPage, materialFactsSurfaced, materialFactsSurfacedInText, materializeRegisteredClaimEvidence, mediaTypeFor, mem0MemoryAdapterIdentity, memoryHitToSourceRecord, memoryRecoveryDelayMs, memoryWriteResultToSourceRecord, mergeClaimLedgers, mergeTrackedClaims, normalizeClaimText, normalizeExternalRagScores, normalizeLinkTarget, normalizePageText, optimizeKnowledgeBasePolicy, parseFrontmatter, parseKnowledgeBenchmarkJsonl, parseKnowledgeBenchmarkQrels, parseKnowledgeWriteBlocks, partitionRetrievalScenarios, politeFetch, promoteKnowledgeCandidate, proposeFromFinding, proposeFromFindings, ragAnswerQualityJudge, readRegularFileNoFollow, readRegularFileWithinRoot, reciprocalRankFusion, recoverPendingKnowledgeMutation, removeDurable, renameDurable, renderKnowledgeBenchmarkReportMarkdown, renderMemoryContext, researchSourceVersionKey, resetRetrievalHoldoutRegistry, resolveMemoryCleanupTimeoutMs, respondToIndustryMemoryBenchmarkSmokeCase, respondToIndustryRagBenchmarkSmokeCase, restoreKnowledgeCandidateBaseline, retrievalConfigFromSurface, retrievalConfigSurface, retrievalHoldoutConfigHash, retrievalRecallJudge, runAgentMemoryExperiment, runAgentMemoryImprovement, runAgentMemoryLearningExperiment, runBoundedMemoryLifecycle, runDiscoveryLoop, runInvestmentThesisTask, runKnowledgeBenchmarkSuite, runKnowledgeResearchLoop, runMemoryAdapterBenchmark, runRagKnowledgeImprovementLoop, runRagOptimization, runRetrievalImprovementLoop, runSerializedKnowledgeOptimization, runVerifiedResearchLoop, scenarioContentFingerprint, scoreKnowledgeBaseIndex, scoreKnowledgeBenchmarkArtifact, scoreMemoryBenchmarkArtifact, scoreRagAnswerArtifact, scoreRetrievalArtifact, searchKnowledge, sha256, sleepForMemoryRecovery, slugify, snapshotSourceTextInput, sourceMatchesGaps, sourceRegistryPath, stableId, stripFrontmatter, summarizeKnowledgeBenchmarkCampaign, syncDirectory, textSourceAdapter, textSourceId, thesisReadinessSpecs, toAgentCandidateKnowledgeRef, toDeepEvalTestCases, toOffPolicyTrajectory, toRagCheckerRecords, toRagasEvaluationRows, toTruLensRecords, tokenizeQuery, totalMaterialFacts, triageSource, validateKnowledgeIndex, verdictFor, verifyGradeableEvidence, withCitedClaim, withKnowledgeImprovementCandidate, withKnowledgeImprovementComparison, withKnowledgeMutation, withKnowledgeRead, withSafeDescendant, withSafeDirectory, writeFileDurable, writeFileDurableWithinRoot, writeJson, writeJsonDurable, writeJsonDurableWithinRoot, writeKnowledgeIndex, writeSourceRegistry };
7440
+ export { AgentMemoryHitSchema, AgentMemoryKindSchema, AgentMemoryLifecycleTimeoutError, AgentMemoryLifecycleUnsafeError, AgentMemoryScopeSchema, AgentMemoryWriteInputSchema, CHECKABLE_RUNG_THRESHOLD, ClaimLedgerGoalConflictError, ClaimLedgerMigrationRequiredError, DEFAULT_MEMORY_CLEANUP_TIMEOUT_MS, DeepQuestionSchema, FileSystemKbStore, FileSystemSearchProvider, INDUSTRY_MEMORY_BENCHMARKS, INDUSTRY_RAG_BENCHMARKS, IRS_DIMENSION_HINTS, KB_CLAIM_LEDGER_DIR, KB_EVENTS_PATH, KB_INDEX_PATH, KB_STORE_DIR, KNOWLEDGE_EVENT_TYPES, KNOWLEDGE_RECEIPT_DIGEST_ALGORITHM, KNOWLEDGE_USE_RECEIPT_SCHEMA_VERSION, KnowledgeBaseCandidateSchema, KnowledgeCitationAuditError, KnowledgeCitationResolutionError, KnowledgeEventSchema, KnowledgeGraphEdgeSchema, KnowledgeGraphNodeSchema, KnowledgeImprovementCandidateRefSchema, KnowledgeImprovementEvidenceSchema, KnowledgeImprovementRunStateSchema, KnowledgeIndexSchema, KnowledgePageInvalidationSchema, KnowledgePageSchema, KnowledgeProposalParseError, MAX_RESPONSE_BYTES, MIN_REQUEST_GAP_MS, MemoryKbStore, POLITE_USER_AGENT, READINESS_SPEC_DEFAULTS, RUN_LINEAGE_BASENAME, ResearchClaimEvidenceSchema, ResearchClaimLedgerSchema, ResearchClaimRecordSchema, ResearchSourceVersionSchema, RouterError, SCAFFOLD_PAGE_BASENAMES, SourceAnchorSchema, SourceRecordSchema, UncheckableClaimError, WIKILINK_REGEX, __resetHttpThrottle, acquireAgentMemoryRunLease, addSourcePath, addSourceText, agentMemorySequenceJudge, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, applyRetrievalHoldout, applySessionStickyRetrievalHoldout, assertClaimLedgerId, assertCurrentRunCitationsResolved, assertDeepQuestionIntegrity, assertGradeableEvidence, assertKnowledgeCitationAudit, assertKnowledgeCitationsResolved, assertKnowledgeRetrievalMatchesVisibility, assertResearchClaimEvidenceIntegrity, assertResearchClaimLedgerIntegrity, assertRunScopedCitationsResolved, assertTrackedClaimIntegrity, auditCurrentRunCitations, auditKnowledgeCitations, buildAgentMemorySequenceScenarios, buildAgentMemorySequencesFromBenchmarkCases, buildEvalKnowledgeBundle, buildFirstPartyMemoryLifecycleBenchmarkCases, buildIndustryMemoryBenchmarkSmokeCases, buildIndustryRagBenchmarkSmokeCases, buildKnowledgeBenchmarkScenarios, buildKnowledgeGraph, buildKnowledgeIndex, buildRetrievalBenchmarkCasesFromQrels, buildRetrievalEvalDispatch, calibrateRagAnswerJudge, canonicalizeUrl, chunkMarkdown, citedClaimKey, citedClaimOf, claimEvidenceId, claimId, claimSourceHost, compareAgentMemoryLearning, contentKey, createAdaptiveResearchDriver, createAgentMemoryBranch, createClaimDecorator, createClaimGroundingVerifier, createCollectionResearchDriver, createCornellLiiSource, createD1FreshnessStoreStub, createFileRunLineageAuthority, createFileSystemFreshnessStore, createFileSystemSearchProvider, createGraphitiMemoryAdapter, createInMemoryBenchmarkAdapter, createIrsPublicationsSource, createKnowledgeControlLoopAdapter, createKnowledgeEvent, createKnowledgeRetrievalReceipt, createKnowledgeUseReceipt, createKnowledgeVisibilitySnapshot, createLocalDiscoveryDispatcher, createMem0MemoryAdapter, createMemoryExecutionPool, createNeo4jAgentMemoryAdapter, createNoopMemoryBenchmarkAdapter, createPersistentResearchDrivingDriver, createRagAnswerQualityHook, createResearchDrivingDriver, createRunScopedStores, createStateSosSource, createTangleRouterClient, createVerifyingResearchDriver, createWebResearchWorker, deepQuestionId, defaultGetMemoryContext, defineReadinessSpec, detectChanges, detectNearDuplicatePages, deterministicRng, diagnoseRagAnswerFailure, emitRetrievalHoldoutBypass, emptyClaimLedger, evaluateKnowledgeBaseReadiness, explainKnowledgeTarget, extractLinks, extractWikilinks, firstMatch, forkAgentMemoryBranchSnapshot, formatFrontmatter, formatKnowledgeCitationReference, fromAgentCandidateKnowledgeRef, gradeCompanyAgainstText, gradeFactAgainstText, gradeFor, graphitiMemoryAdapterIdentity, groundClaimInText, hashKnowledgeBase, htmlToText, improveKnowledgeBase, improveSelectedKnowledgeCandidate, initKnowledgeBase, innerHtmlById, inspectKnowledgeIndex, inspectPendingKnowledgeMutation, investmentThesisSet, isKernelAnchoredPath, isKnowledgeMemoryBenchmarkCase, isMissingFile, isSafeKnowledgePath, isScaffoldPath, jsonCandidateCodec, jsonObjectCandidateCodec, kbIndexToText, knowledgeBenchmarkJudge, knowledgeCitationAuditFindings, knowledgeImprovementCandidateRef, knowledgeImprovementRunDir, knowledgeImprovementRunId, knowledgePageDigest, knowledgeReleaseReport, layoutFor, lensDistribution, linkClaimContradictions, lintCurrentRunCitations, lintKnowledgeIndex, listRegularFilesWithinRoot, loadKnowledgeImprovementActivationResult, loadKnowledgeImprovementEvents, loadKnowledgeImprovementState, loadKnowledgePages, loadSourceRegistry, looksLikeBlockPage, materialFactsSurfaced, materialFactsSurfacedInText, materializeRegisteredClaimEvidence, mediaTypeFor, mem0MemoryAdapterIdentity, memoryHitToSourceRecord, memoryRecoveryDelayMs, memoryWriteResultToSourceRecord, mergeClaimLedgers, mergeTrackedClaims, normalizeClaimText, normalizeExternalRagScores, normalizeLinkTarget, normalizePageText, optimizeKnowledgeBasePolicy, parseFrontmatter, parseKnowledgeBenchmarkJsonl, parseKnowledgeBenchmarkQrels, parseKnowledgeCitationReference, parseKnowledgeWriteBlocks, partitionRetrievalScenarios, politeFetch, promoteKnowledgeCandidate, proposeFromFinding, proposeFromFindings, ragAnswerQualityJudge, readRegularFileNoFollow, readRegularFileWithinRoot, reciprocalRankFusion, recoverPendingKnowledgeMutation, removeDurable, renameDurable, renderKnowledgeBenchmarkReportMarkdown, renderMemoryContext, researchSourceVersionKey, resetRetrievalHoldoutRegistry, resolveKnowledgeCitation, resolveKnowledgeCitations, resolveMemoryCleanupTimeoutMs, resolveRunScopedCitation, resolveRunScopedCitations, respondToIndustryMemoryBenchmarkSmokeCase, respondToIndustryRagBenchmarkSmokeCase, restoreKnowledgeCandidateBaseline, retrievalConfigFromSurface, retrievalConfigSurface, retrievalHoldoutConfigHash, retrievalRecallJudge, runAgentMemoryExperiment, runAgentMemoryImprovement, runAgentMemoryLearningExperiment, runBoundedMemoryLifecycle, runDiscoveryLoop, runInvestmentThesisTask, runKnowledgeBenchmarkSuite, runKnowledgeResearchLoop, runMemoryAdapterBenchmark, runRagKnowledgeImprovementLoop, runRagOptimization, runRetrievalImprovementLoop, runSerializedKnowledgeOptimization, runVerifiedResearchLoop, scenarioContentFingerprint, scoreKnowledgeBaseIndex, scoreKnowledgeBenchmarkArtifact, scoreMemoryBenchmarkArtifact, scoreRagAnswerArtifact, scoreRetrievalArtifact, searchKnowledge, sha256, sleepForMemoryRecovery, slugify, snapshotSourceTextInput, sourceMatchesGaps, sourceRegistryPath, stableId, stripFrontmatter, summarizeKnowledgeBenchmarkCampaign, syncDirectory, textSourceAdapter, textSourceId, thesisReadinessSpecs, toAgentCandidateKnowledgeRef, toDeepEvalTestCases, toOffPolicyTrajectory, toRagCheckerRecords, toRagasEvaluationRows, toTruLensRecords, tokenizeQuery, totalMaterialFacts, triageSource, validateKnowledgeIndex, verdictFor, verifyGradeableEvidence, verifyKnowledgeRetrievalReceipt, verifyKnowledgeUseReceipt, withCitedClaim, withKnowledgeImprovementCandidate, withKnowledgeImprovementComparison, withKnowledgeMutation, withKnowledgeRead, withSafeDescendant, withSafeDirectory, writeFileDurable, writeFileDurableWithinRoot, writeJson, writeJsonDurable, writeJsonDurableWithinRoot, writeKnowledgeIndex, writeSourceRegistry };
6698
7441
 
6699
7442
  //# sourceMappingURL=index.js.map