@tangle-network/agent-knowledge 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,25 +1,9 @@
1
- import { c as KnowledgeWriteParseResult, S as SourceRecord, d as KnowledgeEventType, e as KnowledgeEvent, f as KnowledgePage, g as KnowledgeIndex, h as SourceRegistry, b as KnowledgeGraph, i as KnowledgeSearchResult, j as KnowledgeLintFinding, k as KnowledgeBaseCandidate, l as KnowledgeRelease } from './types-DTUp66Gr.js';
2
- export { C as ClaimRef, m as KnowledgeClaim, K as KnowledgeGraphEdge, a as KnowledgeGraphNode, n as KnowledgeId, o as KnowledgePolicy, p as KnowledgeRelation, q as KnowledgeUnit, r as KnowledgeWriteBlock, s as SourceAnchor } from './types-DTUp66Gr.js';
1
+ import { S as SourceRecord, c as KnowledgeIndex, d as KnowledgeSearchResult, e as KnowledgeEventType, f as KnowledgeEvent, g as KnowledgePage, b as KnowledgeGraph, h as KnowledgeLintFinding, i as KnowledgeBaseCandidate, j as KnowledgeWriteBlock, k as KnowledgeClaim, l as KnowledgeRelease, m as SourceRegistry, n as KnowledgeWriteParseResult } from './types-CAeh7Lwb.js';
2
+ export { C as ClaimRef, K as KnowledgeGraphEdge, a as KnowledgeGraphNode, o as KnowledgeId, p as KnowledgePolicy, q as KnowledgeRelation, r as KnowledgeUnit, s as SourceAnchor } from './types-CAeh7Lwb.js';
3
+ import { KnowledgeFragment } from './sources/index.js';
4
+ export { CornellLiiSelector, CornellLiiSourceOptions, FetchOpts, FragmentProvenance, IRS_DIMENSION_HINTS, IrsPublicationsSourceOptions, KnowledgeSource, MAX_RESPONSE_BYTES, MIN_REQUEST_GAP_MS, POLITE_USER_AGENT, PoliteFetchOptions, PoliteFetchResult, StateSosEntity, StateSosSourceConfig, __resetHttpThrottle, createCornellLiiSource, createIrsPublicationsSource, createStateSosSource, extractLinks, firstMatch, htmlToText, innerHtmlById, looksLikeBlockPage, politeFetch } from './sources/index.js';
5
+ import { KnowledgeRequirementCategory, KnowledgeAcquisitionMode, KnowledgeImportance, KnowledgeFreshness, KnowledgeSensitivity, KnowledgeRequirement, KnowledgeBundle, KnowledgeReadinessReport, UserQuestion, DataAcquisitionPlan, MultiShotVariant, MultiShotOptimizationConfig, MultiShotRunner, MultiShotScorer, MultiShotMutateAdapter, MultiShotOptimizationResult, AnalystSeverity, AnalystFinding, ReleaseConfidenceScorecard, RunRecord, ControlRuntimeConfig, ControlEvalResult } from '@tangle-network/agent-eval';
3
6
  import { z } from 'zod';
4
- import { MultiShotVariant, MultiShotOptimizationConfig, MultiShotRunner, MultiShotScorer, MultiShotMutateAdapter, MultiShotOptimizationResult, ReleaseConfidenceScorecard, RunRecord, KnowledgeRequirementCategory, KnowledgeAcquisitionMode, KnowledgeImportance, KnowledgeFreshness, KnowledgeSensitivity, KnowledgeRequirement, KnowledgeBundle, KnowledgeReadinessReport, UserQuestion, DataAcquisitionPlan, ControlRuntimeConfig, ControlEvalResult } from '@tangle-network/agent-eval';
5
-
6
- declare function sha256(text: string): string;
7
- declare function slugify(input: string): string;
8
- declare function stableId(prefix: string, content: string): string;
9
-
10
- interface ParsedFrontmatter {
11
- frontmatter: Record<string, unknown>;
12
- body: string;
13
- }
14
- declare function parseFrontmatter(content: string): ParsedFrontmatter;
15
- declare function formatFrontmatter(frontmatter: Record<string, unknown>, body: string): string;
16
-
17
- declare const WIKILINK_REGEX: RegExp;
18
- declare function extractWikilinks(content: string): string[];
19
- declare function normalizeLinkTarget(target: string): string;
20
-
21
- declare function isSafeKnowledgePath(path: string, allowedPrefixes?: string[]): boolean;
22
- declare function parseKnowledgeWriteBlocks(text: string, allowedPrefixes?: string[]): KnowledgeWriteParseResult;
23
7
 
24
8
  interface SourceAdapterInput {
25
9
  uri: string;
@@ -42,231 +26,109 @@ interface SourceAdapter {
42
26
  declare const textSourceAdapter: SourceAdapter;
43
27
  declare function mediaTypeFor(uri: string): string;
44
28
 
45
- interface ApplyWriteBlocksResult {
46
- written: string[];
29
+ /**
30
+ * Change detection across snapshots of one source's fragments.
31
+ *
32
+ * The output drives the continuous-ingestion loop: each `KnowledgeChange`
33
+ * carries the eval dimensions affected (`affectedDimensions`), which an
34
+ * agent-eval campaign scheduler consumes to decide which campaigns to
35
+ * re-run. Three change kinds:
36
+ *
37
+ * - `added` — fragment id appears in `next` but not `prev`.
38
+ * - `removed` — fragment id appears in `prev` but not `next`. Typical
39
+ * trigger: an authority retires a Wex slug, or a state SOS reorganises
40
+ * its forms catalogue.
41
+ * - `modified` — fragment id appears in both, body hash differs. This
42
+ * is the dominant change kind in practice — the Ryan-LLC v. FTC
43
+ * vacatur case manifests as a `modified` on the Wex non-compete
44
+ * fragment, NOT as a removed one.
45
+ *
46
+ * Unverifiable fragments are filtered out before diffing — comparing a
47
+ * captcha-blocked snapshot against a real one would falsely fire every
48
+ * fragment as removed. The caller can inspect the raw lists if they want
49
+ * to surface block-page failures.
50
+ *
51
+ * Within-snapshot duplicate ids are an upstream bug; this function picks
52
+ * the LAST one and emits a diagnostic via the `warnings` field.
53
+ *
54
+ * @stable
55
+ */
56
+ type KnowledgeChangeKind = 'added' | 'removed' | 'modified';
57
+ interface KnowledgeChange {
58
+ /** Source-scoped id (matches `KnowledgeFragment.id`). */
59
+ fragmentId: string;
60
+ kind: KnowledgeChangeKind;
61
+ /**
62
+ * For `added`: full body of the new fragment.
63
+ * For `removed`: full body of the prior fragment.
64
+ * For `modified`: unified-diff-style payload `{ before, after }` body strings.
65
+ */
66
+ diff?: {
67
+ before?: string;
68
+ after?: string;
69
+ };
70
+ /**
71
+ * Eval dimensions to re-score. Computed as the union of both fragments'
72
+ * `dimensionHints`. The eval cron treats this as a set of campaign tags.
73
+ */
74
+ affectedDimensions: string[];
75
+ /** URL of the affected authority page (from whichever side has it). */
76
+ url?: string;
77
+ /**
78
+ * Source-attested change time. For `modified`, takes the NEXT fragment's
79
+ * `sourceUpdatedAt`. For `removed`, takes the PRIOR fragment's
80
+ * `sourceUpdatedAt`. For `added`, takes the NEXT fragment's
81
+ * `sourceUpdatedAt`. Consumers index changes by this date.
82
+ */
83
+ detectedAt: string;
84
+ }
85
+ interface DetectChangesResult {
86
+ changes: KnowledgeChange[];
87
+ /** Counts by kind — handy for dashboards. */
88
+ summary: {
89
+ added: number;
90
+ removed: number;
91
+ modified: number;
92
+ };
93
+ /** Non-fatal diagnostics (duplicate ids, dropped unverifiable fragments). */
47
94
  warnings: string[];
48
95
  }
49
- declare function applyKnowledgeWriteBlocks(root: string, proposalText: string): Promise<ApplyWriteBlocksResult>;
50
- declare function applyKnowledgeWriteBlocksFile(root: string, proposalPath: string): Promise<ApplyWriteBlocksResult>;
51
-
52
- declare const SourceAnchorSchema: z.ZodObject<{
53
- id: z.ZodString;
54
- sourceId: z.ZodString;
55
- label: z.ZodOptional<z.ZodString>;
56
- page: z.ZodOptional<z.ZodNumber>;
57
- lineStart: z.ZodOptional<z.ZodNumber>;
58
- lineEnd: z.ZodOptional<z.ZodNumber>;
59
- charStart: z.ZodOptional<z.ZodNumber>;
60
- charEnd: z.ZodOptional<z.ZodNumber>;
61
- timestampMs: z.ZodOptional<z.ZodNumber>;
62
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
63
- }, z.core.$strip>;
64
- declare const SourceRecordSchema: z.ZodObject<{
65
- id: z.ZodString;
66
- uri: z.ZodString;
67
- title: z.ZodOptional<z.ZodString>;
68
- mediaType: z.ZodOptional<z.ZodString>;
69
- contentHash: z.ZodString;
70
- text: z.ZodOptional<z.ZodString>;
71
- anchors: z.ZodOptional<z.ZodArray<z.ZodObject<{
72
- id: z.ZodString;
73
- sourceId: z.ZodString;
74
- label: z.ZodOptional<z.ZodString>;
75
- page: z.ZodOptional<z.ZodNumber>;
76
- lineStart: z.ZodOptional<z.ZodNumber>;
77
- lineEnd: z.ZodOptional<z.ZodNumber>;
78
- charStart: z.ZodOptional<z.ZodNumber>;
79
- charEnd: z.ZodOptional<z.ZodNumber>;
80
- timestampMs: z.ZodOptional<z.ZodNumber>;
81
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
82
- }, z.core.$strip>>>;
83
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
84
- createdAt: z.ZodString;
85
- }, z.core.$strip>;
86
- declare const KnowledgePageSchema: z.ZodObject<{
87
- id: z.ZodString;
88
- path: z.ZodString;
89
- title: z.ZodString;
90
- text: z.ZodString;
91
- frontmatter: z.ZodRecord<z.ZodString, z.ZodUnknown>;
92
- sourceIds: z.ZodArray<z.ZodString>;
93
- tags: z.ZodArray<z.ZodString>;
94
- outLinks: z.ZodArray<z.ZodString>;
95
- }, z.core.$strip>;
96
- declare const KnowledgeGraphNodeSchema: z.ZodObject<{
97
- id: z.ZodString;
98
- title: z.ZodString;
99
- path: z.ZodString;
100
- tags: z.ZodArray<z.ZodString>;
101
- sourceIds: z.ZodArray<z.ZodString>;
102
- outDegree: z.ZodNumber;
103
- inDegree: z.ZodNumber;
104
- }, z.core.$strip>;
105
- declare const KnowledgeGraphEdgeSchema: z.ZodObject<{
106
- source: z.ZodString;
107
- target: z.ZodString;
108
- weight: z.ZodNumber;
109
- reasons: z.ZodArray<z.ZodString>;
110
- }, z.core.$strip>;
111
- declare const KnowledgeIndexSchema: z.ZodObject<{
112
- root: z.ZodString;
113
- generatedAt: z.ZodString;
114
- sources: z.ZodArray<z.ZodObject<{
115
- id: z.ZodString;
116
- uri: z.ZodString;
117
- title: z.ZodOptional<z.ZodString>;
118
- mediaType: z.ZodOptional<z.ZodString>;
119
- contentHash: z.ZodString;
120
- text: z.ZodOptional<z.ZodString>;
121
- anchors: z.ZodOptional<z.ZodArray<z.ZodObject<{
122
- id: z.ZodString;
123
- sourceId: z.ZodString;
124
- label: z.ZodOptional<z.ZodString>;
125
- page: z.ZodOptional<z.ZodNumber>;
126
- lineStart: z.ZodOptional<z.ZodNumber>;
127
- lineEnd: z.ZodOptional<z.ZodNumber>;
128
- charStart: z.ZodOptional<z.ZodNumber>;
129
- charEnd: z.ZodOptional<z.ZodNumber>;
130
- timestampMs: z.ZodOptional<z.ZodNumber>;
131
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
132
- }, z.core.$strip>>>;
133
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
134
- createdAt: z.ZodString;
135
- }, z.core.$strip>>;
136
- pages: z.ZodArray<z.ZodObject<{
137
- id: z.ZodString;
138
- path: z.ZodString;
139
- title: z.ZodString;
140
- text: z.ZodString;
141
- frontmatter: z.ZodRecord<z.ZodString, z.ZodUnknown>;
142
- sourceIds: z.ZodArray<z.ZodString>;
143
- tags: z.ZodArray<z.ZodString>;
144
- outLinks: z.ZodArray<z.ZodString>;
145
- }, z.core.$strip>>;
146
- graph: z.ZodObject<{
147
- nodes: z.ZodArray<z.ZodObject<{
148
- id: z.ZodString;
149
- title: z.ZodString;
150
- path: z.ZodString;
151
- tags: z.ZodArray<z.ZodString>;
152
- sourceIds: z.ZodArray<z.ZodString>;
153
- outDegree: z.ZodNumber;
154
- inDegree: z.ZodNumber;
155
- }, z.core.$strip>>;
156
- edges: z.ZodArray<z.ZodObject<{
157
- source: z.ZodString;
158
- target: z.ZodString;
159
- weight: z.ZodNumber;
160
- reasons: z.ZodArray<z.ZodString>;
161
- }, z.core.$strip>>;
162
- }, z.core.$strip>;
163
- }, z.core.$strip>;
164
- declare const KnowledgeEventSchema: z.ZodObject<{
165
- id: z.ZodString;
166
- type: z.ZodEnum<{
167
- "source.added": "source.added";
168
- "proposal.applied": "proposal.applied";
169
- "index.built": "index.built";
170
- "lint.run": "lint.run";
171
- "optimization.run": "optimization.run";
172
- "release.promoted": "release.promoted";
173
- "release.rejected": "release.rejected";
174
- }>;
175
- createdAt: z.ZodString;
176
- actor: z.ZodOptional<z.ZodString>;
177
- target: z.ZodOptional<z.ZodString>;
178
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
179
- }, z.core.$strip>;
180
- declare const KnowledgeBaseCandidateSchema: z.ZodObject<{
181
- id: z.ZodString;
182
- units: z.ZodArray<z.ZodObject<{
183
- id: z.ZodString;
184
- title: z.ZodString;
185
- text: z.ZodString;
186
- claims: z.ZodOptional<z.ZodArray<z.ZodObject<{
187
- id: z.ZodString;
188
- text: z.ZodString;
189
- refs: z.ZodArray<z.ZodObject<{
190
- sourceId: z.ZodString;
191
- anchorId: z.ZodOptional<z.ZodString>;
192
- quote: z.ZodOptional<z.ZodString>;
193
- }, z.core.$strip>>;
194
- confidence: z.ZodOptional<z.ZodNumber>;
195
- status: z.ZodOptional<z.ZodEnum<{
196
- draft: "draft";
197
- active: "active";
198
- superseded: "superseded";
199
- rejected: "rejected";
200
- }>>;
201
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
202
- }, z.core.$strip>>>;
203
- relations: z.ZodOptional<z.ZodArray<z.ZodObject<{
204
- sourceId: z.ZodString;
205
- targetId: z.ZodString;
206
- predicate: z.ZodString;
207
- weight: z.ZodOptional<z.ZodNumber>;
208
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
209
- }, z.core.$strip>>>;
210
- sourceIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
211
- tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
212
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
213
- updatedAt: z.ZodOptional<z.ZodString>;
214
- }, z.core.$strip>>;
215
- retrievalPolicy: z.ZodOptional<z.ZodString>;
216
- synthesisPolicy: z.ZodOptional<z.ZodString>;
217
- questionPolicy: z.ZodOptional<z.ZodString>;
218
- updatePolicy: z.ZodOptional<z.ZodString>;
219
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
220
- }, z.core.$strip>;
221
-
222
- interface KnowledgeEventQuery {
223
- type?: KnowledgeEventType;
224
- target?: string;
225
- limit?: number;
96
+ interface DetectChangesOptions {
97
+ /**
98
+ * When true (default), unverifiable fragments are dropped from both
99
+ * sides before comparison. Set false ONLY when debugging block-page
100
+ * issues — comparing against unverifiable content emits false
101
+ * `removed`/`modified` changes.
102
+ */
103
+ skipUnverifiable?: boolean;
104
+ /**
105
+ * When provided, only changes whose `affectedDimensions` intersect this
106
+ * set are returned. Useful for cron loops that schedule per-dimension
107
+ * eval campaigns and only care about a subset.
108
+ */
109
+ filterDimensions?: string[];
226
110
  }
227
- declare function createKnowledgeEvent(input: {
228
- type: KnowledgeEventType;
229
- actor?: string;
230
- target?: string;
231
- metadata?: Record<string, unknown>;
232
- now?: () => Date;
233
- }): KnowledgeEvent;
111
+ declare function detectChanges(prev: KnowledgeFragment[], next: KnowledgeFragment[], options?: DetectChangesOptions): DetectChangesResult;
234
112
 
235
- interface KbStore {
236
- putSource(source: SourceRecord): Promise<void>;
237
- getSource(id: string): Promise<SourceRecord | null>;
238
- listSources(): Promise<SourceRecord[]>;
239
- putPage(page: KnowledgePage): Promise<void>;
240
- getPage(idOrPath: string): Promise<KnowledgePage | null>;
241
- listPages(): Promise<KnowledgePage[]>;
242
- putIndex(index: KnowledgeIndex): Promise<void>;
243
- getIndex(): Promise<KnowledgeIndex | null>;
244
- putEvent(event: KnowledgeEvent): Promise<void>;
245
- listEvents(query?: KnowledgeEventQuery): Promise<KnowledgeEvent[]>;
246
- }
247
- declare class MemoryKbStore implements KbStore {
248
- private readonly sources;
249
- private readonly pages;
250
- private readonly events;
251
- private index;
252
- putSource(source: SourceRecord): Promise<void>;
253
- getSource(id: string): Promise<SourceRecord | null>;
254
- listSources(): Promise<SourceRecord[]>;
255
- putPage(page: KnowledgePage): Promise<void>;
256
- getPage(idOrPath: string): Promise<KnowledgePage | null>;
257
- listPages(): Promise<KnowledgePage[]>;
258
- putIndex(index: KnowledgeIndex): Promise<void>;
259
- getIndex(): Promise<KnowledgeIndex | null>;
260
- putEvent(event: KnowledgeEvent): Promise<void>;
261
- listEvents(query?: KnowledgeEventQuery): Promise<KnowledgeEvent[]>;
113
+ interface ChunkingOptions {
114
+ targetChars: number;
115
+ maxChars: number;
116
+ minChars: number;
117
+ overlapChars: number;
262
118
  }
263
- declare class FileSystemKbStore extends MemoryKbStore {
264
- private readonly dir;
265
- constructor(dir: string);
266
- putIndex(index: KnowledgeIndex): Promise<void>;
267
- getIndex(): Promise<KnowledgeIndex | null>;
268
- putEvent(event: KnowledgeEvent): Promise<void>;
119
+ interface KnowledgeChunk {
120
+ index: number;
121
+ text: string;
122
+ headingPath: string;
123
+ charStart: number;
124
+ charEnd: number;
125
+ oversized: boolean;
269
126
  }
127
+ declare function chunkMarkdown(content: string, options?: Partial<ChunkingOptions>): KnowledgeChunk[];
128
+ declare function stripFrontmatter(content: string): {
129
+ body: string;
130
+ bodyOffset: number;
131
+ };
270
132
 
271
133
  interface DiscoveryTask {
272
134
  id: string;
@@ -290,96 +152,241 @@ interface DiscoveryResult {
290
152
  interface KnowledgeDiscoveryWorker {
291
153
  run(task: DiscoveryTask, signal?: AbortSignal): Promise<DiscoveryResult> | DiscoveryResult;
292
154
  }
293
- interface KnowledgeDiscoveryDispatcher {
294
- dispatch(tasks: DiscoveryTask[], options?: {
295
- concurrency?: number;
296
- signal?: AbortSignal;
297
- }): Promise<DiscoveryResult[]>;
155
+ interface KnowledgeDiscoveryDispatcher {
156
+ dispatch(tasks: DiscoveryTask[], options?: {
157
+ concurrency?: number;
158
+ signal?: AbortSignal;
159
+ }): Promise<DiscoveryResult[]>;
160
+ }
161
+ declare function createLocalDiscoveryDispatcher(worker: KnowledgeDiscoveryWorker): KnowledgeDiscoveryDispatcher;
162
+
163
+ interface KnowledgeReadinessSpec {
164
+ id: string;
165
+ description: string;
166
+ query: string;
167
+ requiredFor: string[];
168
+ category: KnowledgeRequirementCategory;
169
+ acquisitionMode: KnowledgeAcquisitionMode;
170
+ importance: KnowledgeImportance;
171
+ freshness: KnowledgeFreshness;
172
+ sensitivity: KnowledgeSensitivity;
173
+ confidenceNeeded: number;
174
+ fallbackPolicy?: KnowledgeRequirement['fallbackPolicy'];
175
+ minSources?: number;
176
+ minHits?: number;
177
+ metadata?: Record<string, unknown>;
178
+ }
179
+ /**
180
+ * Defaults applied by `defineReadinessSpec` when the caller omits the field.
181
+ *
182
+ * These are deliberately conservative: a domain-specific topic that an agent
183
+ * needs grounded to a high-confidence threshold from at least one authoritative
184
+ * source. Override any field to specialise (e.g. `freshness: 'daily'` for a
185
+ * topic that must reflect today's regulatory state).
186
+ */
187
+ declare const READINESS_SPEC_DEFAULTS: {
188
+ readonly category: "domain_specific";
189
+ readonly acquisitionMode: "search_web";
190
+ readonly importance: "high";
191
+ readonly freshness: "monthly";
192
+ readonly sensitivity: "public";
193
+ readonly confidenceNeeded: 0.7;
194
+ readonly minSources: 1;
195
+ readonly minHits: 2;
196
+ };
197
+ /**
198
+ * Inputs accepted by `defineReadinessSpec`. The four fields the caller cannot
199
+ * sanely default (id, description, query, requiredFor) are required; everything
200
+ * else is optional and pulls from `READINESS_SPEC_DEFAULTS`.
201
+ */
202
+ type DefineReadinessSpecInput = Pick<KnowledgeReadinessSpec, 'id' | 'description' | 'query' | 'requiredFor'> & Partial<Omit<KnowledgeReadinessSpec, 'id' | 'description' | 'query' | 'requiredFor'>>;
203
+ /**
204
+ * Builder that returns a fully-typed `KnowledgeReadinessSpec` from a slim input.
205
+ *
206
+ * Motivation: `KnowledgeReadinessSpec` has eleven required fields. Most of them
207
+ * (category, acquisition mode, importance, freshness, sensitivity, confidence
208
+ * threshold, source/hit minima) have a clear default for domain-specific KB
209
+ * topics — agents end up copy-pasting the same boilerplate across every spec.
210
+ * This helper collapses that boilerplate while keeping every field overridable.
211
+ *
212
+ * @example
213
+ * defineReadinessSpec({
214
+ * id: 'coop/intent-grounding',
215
+ * description: 'Required grounding for coop pack intent stage',
216
+ * query: 'flock size space ventilation predator',
217
+ * requiredFor: ['IntentIntakeAgent', 'requirements'],
218
+ * })
219
+ *
220
+ * @example // override defaults where the topic demands it
221
+ * defineReadinessSpec({
222
+ * id: 'medical/dosing',
223
+ * description: 'Dosing guidance for compounding pharmacy',
224
+ * query: 'compounding dose schedule',
225
+ * requiredFor: ['DosingAgent'],
226
+ * importance: 'blocking',
227
+ * freshness: 'daily',
228
+ * sensitivity: 'private',
229
+ * confidenceNeeded: 0.95,
230
+ * minSources: 3,
231
+ * })
232
+ */
233
+ declare function defineReadinessSpec(input: DefineReadinessSpecInput): KnowledgeReadinessSpec;
234
+ interface BuildEvalKnowledgeBundleOptions {
235
+ taskId: string;
236
+ index: KnowledgeIndex;
237
+ specs: KnowledgeReadinessSpec[];
238
+ userAnswers?: Record<string, string>;
239
+ searchLimit?: number;
240
+ metadata?: Record<string, unknown>;
241
+ now?: Date;
242
+ }
243
+ interface EvalKnowledgeBundleBuildResult {
244
+ bundle: KnowledgeBundle;
245
+ report: KnowledgeReadinessReport;
246
+ requirements: KnowledgeRequirement[];
247
+ searchResultsByRequirement: Record<string, KnowledgeSearchResult[]>;
248
+ questions: UserQuestion[];
249
+ acquisitionPlans: DataAcquisitionPlan[];
298
250
  }
299
- declare function createLocalDiscoveryDispatcher(worker: KnowledgeDiscoveryWorker): KnowledgeDiscoveryDispatcher;
251
+ declare function buildEvalKnowledgeBundle(options: BuildEvalKnowledgeBundleOptions): EvalKnowledgeBundleBuildResult;
300
252
 
301
- interface ChunkingOptions {
302
- targetChars: number;
303
- maxChars: number;
304
- minChars: number;
305
- overlapChars: number;
306
- }
307
- interface KnowledgeChunk {
308
- index: number;
309
- text: string;
310
- headingPath: string;
311
- charStart: number;
312
- charEnd: number;
313
- oversized: boolean;
253
+ interface KnowledgeEventQuery {
254
+ type?: KnowledgeEventType;
255
+ target?: string;
256
+ limit?: number;
314
257
  }
315
- declare function chunkMarkdown(content: string, options?: Partial<ChunkingOptions>): KnowledgeChunk[];
316
- declare function stripFrontmatter(content: string): {
317
- body: string;
318
- bodyOffset: number;
319
- };
258
+ declare function createKnowledgeEvent(input: {
259
+ type: KnowledgeEventType;
260
+ actor?: string;
261
+ target?: string;
262
+ metadata?: Record<string, unknown>;
263
+ now?: () => Date;
264
+ }): KnowledgeEvent;
320
265
 
321
- interface KnowledgeLayout {
266
+ /**
267
+ * Knowledge freshness store: tracks when each `(workspaceId, sourceId)` pair
268
+ * was last successfully refreshed, and reports staleness against a TTL.
269
+ *
270
+ * The contract is intentionally minimal — just enough to drive a cron loop:
271
+ *
272
+ * ```ts
273
+ * const store = createFileSystemFreshnessStore({ root: '.agent-knowledge' })
274
+ * for (const source of sources) {
275
+ * if (await store.stale({ workspaceId, sourceId: source.id, ttlMs: DAY })) {
276
+ * const fragments = await source.fetch({ cacheDir })
277
+ * await persistFragments(fragments)
278
+ * await store.mark({ workspaceId, sourceId: source.id, when: new Date() })
279
+ * }
280
+ * }
281
+ * ```
282
+ *
283
+ * Per-tenant isolation is enforced by `workspaceId` keying — there is no
284
+ * global mutable state across workspaces.
285
+ *
286
+ * Two adapters ship in-package:
287
+ *
288
+ * - `createFileSystemFreshnessStore` — JSON file under the knowledge root,
289
+ * mirrors the layout convention already used by `sources.json`.
290
+ * - `createD1FreshnessStoreStub` — adapter scaffold for Cloudflare D1 /
291
+ * Postgres. Production consumers should implement the `D1Adapter`
292
+ * interface inside their own app; this stub exists to anchor the shape.
293
+ *
294
+ * @stable contract — interface is frozen at 0.x within this major.
295
+ * @stable filesystem adapter
296
+ * @experimental D1 stub — interface will evolve as real consumers wire it.
297
+ */
298
+ /** Identity for one freshness record. */
299
+ interface FreshnessKey {
300
+ workspaceId: string;
301
+ sourceId: string;
302
+ }
303
+ /** TTL bound for staleness checks. */
304
+ interface FreshnessTtl extends FreshnessKey {
305
+ /** Milliseconds — `Date.now() - last() > ttlMs` ⇒ stale. */
306
+ ttlMs: number;
307
+ /** Injected clock for deterministic tests; defaults to system time. */
308
+ now?: Date;
309
+ }
310
+ /** Mark argument. */
311
+ interface FreshnessMark extends FreshnessKey {
312
+ when: Date;
313
+ /** Optional content hash captured at refresh time; aids debugging. */
314
+ contentHash?: string;
315
+ }
316
+ interface KnowledgeFreshnessStore {
317
+ /** Last refresh time, or null if never refreshed. */
318
+ last(key: FreshnessKey): Promise<Date | null>;
319
+ /** Record a successful refresh. */
320
+ mark(input: FreshnessMark): Promise<void>;
321
+ /** True iff `last(key)` is null or older than `ttlMs`. */
322
+ stale(input: FreshnessTtl): Promise<boolean>;
323
+ /** All records for a workspace — useful for dashboards / debugging. */
324
+ list(workspaceId: string): Promise<FreshnessRecord[]>;
325
+ }
326
+ interface FreshnessRecord {
327
+ workspaceId: string;
328
+ sourceId: string;
329
+ lastRefreshedAt: string;
330
+ contentHash?: string;
331
+ }
332
+ interface FileSystemFreshnessStoreOptions {
333
+ /**
334
+ * Knowledge root. The store writes to `<root>/.agent-knowledge/freshness.json`,
335
+ * mirroring the convention used by `sources.json`.
336
+ */
322
337
  root: string;
323
- knowledgeDir: string;
324
- rawSourcesDir: string;
325
- sourceRegistryPath: string;
326
- indexPath: string;
327
- logPath: string;
328
- cacheDir: string;
329
338
  }
330
- declare function layoutFor(root: string): KnowledgeLayout;
331
339
  /**
332
- * Filenames that `initKnowledgeBase` writes as human-navigation scaffolding.
333
- * These are excluded from the page index — they exist on disk so authors can
334
- * curate their vault, but they are not searchable content.
340
+ * Filesystem-backed implementation. Single JSON file per knowledge root,
341
+ * indexed by `${workspaceId}::${sourceId}`. Reads parse on every call
342
+ * cron tick rate is well below the cost of one JSON parse.
335
343
  *
336
- * Add new scaffold filenames here (and only here) to keep lint, validate, viz,
337
- * and the indexer consistent.
344
+ * Concurrent writes from a single process serialize through `writeQueue`.
345
+ * Cross-process concurrency is undefined; the consuming app should run the
346
+ * cron in a single worker.
338
347
  */
339
- declare const SCAFFOLD_PAGE_BASENAMES: readonly string[];
348
+ declare function createFileSystemFreshnessStore(options: FileSystemFreshnessStoreOptions): KnowledgeFreshnessStore;
340
349
  /**
341
- * True when a knowledge-relative path points at a scaffold file rather than
342
- * authored content. Accepts both repo-relative paths (`knowledge/index.md`)
343
- * and any nested `<dir>/index.md` or `<dir>/log.md` (for example
344
- * `knowledge/concepts/index.md`) so subdirectory README-style scaffolds are
345
- * also excluded.
350
+ * D1 / Postgres adapter scaffold. Production consumers implement
351
+ * `D1Adapter` against their own driver (better-sqlite3, postgres,
352
+ * Cloudflare D1 binding, ...). This factory wires the adapter to the
353
+ * `KnowledgeFreshnessStore` interface.
354
+ *
355
+ * The expected schema:
356
+ *
357
+ * ```sql
358
+ * CREATE TABLE knowledge_freshness (
359
+ * workspace_id TEXT NOT NULL,
360
+ * source_id TEXT NOT NULL,
361
+ * last_refreshed_at TEXT NOT NULL,
362
+ * content_hash TEXT,
363
+ * PRIMARY KEY (workspace_id, source_id)
364
+ * );
365
+ * ```
346
366
  */
347
- declare function isScaffoldPath(path: string): boolean;
348
- declare function initKnowledgeBase(root: string): Promise<KnowledgeLayout>;
349
- declare function loadKnowledgePages(root: string): Promise<KnowledgePage[]>;
350
- declare function writeJson(path: string, value: unknown): Promise<void>;
351
-
352
- interface AddSourceOptions {
353
- copyIntoRaw?: boolean;
354
- adapters?: SourceAdapter[];
355
- now?: () => Date;
367
+ interface D1Adapter {
368
+ get(workspaceId: string, sourceId: string): Promise<FreshnessRecord | null>;
369
+ upsert(record: FreshnessRecord): Promise<void>;
370
+ listByWorkspace(workspaceId: string): Promise<FreshnessRecord[]>;
356
371
  }
357
- interface AddSourceTextInput {
358
- uri: string;
359
- text: string;
360
- title?: string;
361
- mediaType?: string;
362
- validUntil?: string;
363
- lastVerifiedAt?: string;
364
- metadata?: Record<string, unknown>;
372
+ declare function createD1FreshnessStoreStub(adapter: D1Adapter): KnowledgeFreshnessStore;
373
+
374
+ interface ParsedFrontmatter {
375
+ frontmatter: Record<string, unknown>;
376
+ body: string;
365
377
  }
366
- declare function loadSourceRegistry(root: string): Promise<SourceRegistry>;
367
- declare function writeSourceRegistry(root: string, registry: SourceRegistry): Promise<void>;
368
- declare function addSourcePath(root: string, sourcePath: string, options?: AddSourceOptions): Promise<SourceRecord[]>;
369
- declare function addSourceText(root: string, input: AddSourceTextInput, options?: Pick<AddSourceOptions, 'adapters' | 'now'>): Promise<SourceRecord>;
370
- declare function sourceRegistryPath(root: string): string;
378
+ declare function parseFrontmatter(content: string): ParsedFrontmatter;
379
+ declare function formatFrontmatter(frontmatter: Record<string, unknown>, body: string): string;
371
380
 
372
381
  declare function buildKnowledgeGraph(pages: KnowledgePage[]): KnowledgeGraph;
373
382
 
374
- declare function searchKnowledge(index: KnowledgeIndex, query: string, limit?: number): KnowledgeSearchResult[];
375
- declare function tokenizeQuery(query: string): string[];
376
- declare function reciprocalRankFusion(rankLists: string[][], k?: number): Map<string, number>;
383
+ declare function sha256(text: string): string;
384
+ declare function slugify(input: string): string;
385
+ declare function stableId(prefix: string, content: string): string;
377
386
 
378
387
  declare function buildKnowledgeIndex(root: string): Promise<KnowledgeIndex>;
379
388
  declare function writeKnowledgeIndex(root: string): Promise<KnowledgeIndex>;
380
389
 
381
- declare function lintKnowledgeIndex(index: KnowledgeIndex): KnowledgeLintFinding[];
382
-
383
390
  interface KnowledgeInspection {
384
391
  pageCount: number;
385
392
  sourceCount: number;
@@ -426,14 +433,43 @@ interface KnowledgeExplanation {
426
433
  }
427
434
  declare function explainKnowledgeTarget(index: KnowledgeIndex, target: string): KnowledgeExplanation;
428
435
 
429
- interface ValidateKnowledgeOptions {
430
- strict?: boolean;
436
+ interface KbStore {
437
+ putSource(source: SourceRecord): Promise<void>;
438
+ getSource(id: string): Promise<SourceRecord | null>;
439
+ listSources(): Promise<SourceRecord[]>;
440
+ putPage(page: KnowledgePage): Promise<void>;
441
+ getPage(idOrPath: string): Promise<KnowledgePage | null>;
442
+ listPages(): Promise<KnowledgePage[]>;
443
+ putIndex(index: KnowledgeIndex): Promise<void>;
444
+ getIndex(): Promise<KnowledgeIndex | null>;
445
+ putEvent(event: KnowledgeEvent): Promise<void>;
446
+ listEvents(query?: KnowledgeEventQuery): Promise<KnowledgeEvent[]>;
431
447
  }
432
- interface ValidateKnowledgeResult {
433
- ok: boolean;
434
- findings: KnowledgeLintFinding[];
448
+ declare class MemoryKbStore implements KbStore {
449
+ private readonly sources;
450
+ private readonly pages;
451
+ private readonly events;
452
+ private index;
453
+ putSource(source: SourceRecord): Promise<void>;
454
+ getSource(id: string): Promise<SourceRecord | null>;
455
+ listSources(): Promise<SourceRecord[]>;
456
+ putPage(page: KnowledgePage): Promise<void>;
457
+ getPage(idOrPath: string): Promise<KnowledgePage | null>;
458
+ listPages(): Promise<KnowledgePage[]>;
459
+ putIndex(index: KnowledgeIndex): Promise<void>;
460
+ getIndex(): Promise<KnowledgeIndex | null>;
461
+ putEvent(event: KnowledgeEvent): Promise<void>;
462
+ listEvents(query?: KnowledgeEventQuery): Promise<KnowledgeEvent[]>;
463
+ }
464
+ declare class FileSystemKbStore extends MemoryKbStore {
465
+ private readonly dir;
466
+ constructor(dir: string);
467
+ putIndex(index: KnowledgeIndex): Promise<void>;
468
+ getIndex(): Promise<KnowledgeIndex | null>;
469
+ putEvent(event: KnowledgeEvent): Promise<void>;
435
470
  }
436
- declare function validateKnowledgeIndex(index: KnowledgeIndex, options?: ValidateKnowledgeOptions): ValidateKnowledgeResult;
471
+
472
+ declare function lintKnowledgeIndex(index: KnowledgeIndex): KnowledgeLintFinding[];
437
473
 
438
474
  type KnowledgeBaseVariant = MultiShotVariant<KnowledgeBaseCandidate>;
439
475
  interface KnowledgeOptimizationConfig extends Omit<MultiShotOptimizationConfig<KnowledgeBaseCandidate>, 'runner' | 'scorer' | 'mutateAdapter' | 'target'> {
@@ -449,107 +485,139 @@ declare function knowledgeVariantFromCandidate(candidate: KnowledgeBaseCandidate
449
485
  generation?: number;
450
486
  }): KnowledgeBaseVariant;
451
487
 
452
- interface KnowledgeReleaseReport {
453
- release: KnowledgeRelease;
454
- scorecard: ReleaseConfidenceScorecard;
455
- candidateRuns: RunRecord[];
456
- baselineRuns: RunRecord[];
488
+ interface ApplyWriteBlocksResult {
489
+ written: string[];
490
+ warnings: string[];
457
491
  }
458
- declare function knowledgeReleaseReportFromOptimization(result: MultiShotOptimizationResult<KnowledgeBaseCandidate>, options?: {
459
- runRecords?: RunRecord[];
460
- createdAt?: string;
461
- minScore?: number;
462
- }): KnowledgeReleaseReport;
492
+ declare function applyKnowledgeWriteBlocks(root: string, proposalText: string): Promise<ApplyWriteBlocksResult>;
493
+ declare function applyKnowledgeWriteBlocksFile(root: string, proposalPath: string): Promise<ApplyWriteBlocksResult>;
463
494
 
464
- interface KnowledgeReadinessSpec {
465
- id: string;
466
- description: string;
467
- query: string;
468
- requiredFor: string[];
469
- category: KnowledgeRequirementCategory;
470
- acquisitionMode: KnowledgeAcquisitionMode;
471
- importance: KnowledgeImportance;
472
- freshness: KnowledgeFreshness;
473
- sensitivity: KnowledgeSensitivity;
474
- confidenceNeeded: number;
475
- fallbackPolicy?: KnowledgeRequirement['fallbackPolicy'];
476
- minSources?: number;
477
- minHits?: number;
478
- metadata?: Record<string, unknown>;
479
- }
480
495
  /**
481
- * Defaults applied by `defineReadinessSpec` when the caller omits the field.
496
+ * Bridge from `AnalystFinding` (agent-eval) to knowledge proposals.
482
497
  *
483
- * These are deliberately conservative: a domain-specific topic that an agent
484
- * needs grounded to a high-confidence threshold from at least one authoritative
485
- * source. Override any field to specialise (e.g. `freshness: 'daily'` for a
486
- * topic that must reflect today's regulatory state).
498
+ * Closes the failure wiki side of the recursive-self-improvement
499
+ * loop: a knowledge-gap or knowledge-poisoning finding produced by an
500
+ * analyst becomes a concrete proposal an operator (or auto-merge bot)
501
+ * can review and apply. The bridge is intentionally lossless on the
502
+ * fail-loud side — a finding the parser can't classify returns a
503
+ * `KnowledgeProposalParseError` rather than a silent skip, so the
504
+ * loop never accepts an underspecified edit.
505
+ *
506
+ * Subject grammar this bridge understands (analyst-side convention,
507
+ * stamped in the kind prompts):
508
+ *
509
+ * agent-knowledge:wiki:<page-slug> create / update page
510
+ * agent-knowledge:wiki:<page-slug>#<heading> insert section under page
511
+ * agent-knowledge:claim:<topic> draft claim row
512
+ * agent-knowledge:raw:<source-id> lift raw → curated
513
+ * agent-knowledge:stale:<page-slug> mark page superseded
514
+ *
515
+ * Anything else (websearch:outdated:*, tool-doc:*, system-prompt:*,
516
+ * memory:*) is NOT a knowledge-base concern and returns `null` so the
517
+ * loop's improvement-applier handles it.
487
518
  */
488
- declare const READINESS_SPEC_DEFAULTS: {
489
- readonly category: "domain_specific";
490
- readonly acquisitionMode: "search_web";
491
- readonly importance: "high";
492
- readonly freshness: "monthly";
493
- readonly sensitivity: "public";
494
- readonly confidenceNeeded: 0.7;
495
- readonly minSources: 1;
496
- readonly minHits: 2;
497
- };
519
+
520
+ interface KnowledgeProposal {
521
+ /**
522
+ * Stable id derived from the finding so cross-run diffs share an
523
+ * identity. Re-proposing the same finding produces the same id.
524
+ */
525
+ id: string;
526
+ /** The finding that generated this proposal — useful for audit + revert. */
527
+ sourceFindingId: string;
528
+ /** What the proposal does. */
529
+ kind: 'create-page' | 'update-page' | 'append-section' | 'create-claim' | 'lift-raw' | 'mark-stale';
530
+ /** Locus on disk (page slug or claim topic). */
531
+ locus: string;
532
+ /**
533
+ * Page write blocks the standard `applyKnowledgeWriteBlocks` consumer
534
+ * accepts. Empty for proposals that don't change page text (e.g.
535
+ * `create-claim` produces a `claim` field instead).
536
+ */
537
+ writeBlocks: KnowledgeWriteBlock[];
538
+ /**
539
+ * Granular claim draft for proposals whose unit-of-change is a claim
540
+ * row rather than a whole page. `status: 'draft'` until reviewed.
541
+ */
542
+ claim?: KnowledgeClaim;
543
+ /** Per-proposal metadata: severity, confidence, source span. */
544
+ metadata: {
545
+ severity: AnalystSeverity;
546
+ confidence: number;
547
+ evidence_uri?: string;
548
+ analyst_id: string;
549
+ };
550
+ }
551
+ declare class KnowledgeProposalParseError extends Error {
552
+ readonly findingId: string;
553
+ readonly subject: string;
554
+ constructor(findingId: string, subject: string, message: string);
555
+ }
498
556
  /**
499
- * Inputs accepted by `defineReadinessSpec`. The four fields the caller cannot
500
- * sanely default (id, description, query, requiredFor) are required; everything
501
- * else is optional and pulls from `READINESS_SPEC_DEFAULTS`.
557
+ * Convert one `AnalystFinding` into a knowledge proposal. Returns
558
+ * `null` when the finding's locus isn't a knowledge-base concern
559
+ * (`websearch:outdated:*`, `tool-doc:*`, `system-prompt:*`,
560
+ * `memory:*`, missing subject). Throws when the locus IS a
561
+ * knowledge-base concern but is malformed — that's a bug in the
562
+ * analyst prompt and should fail loud.
563
+ *
564
+ * Caller convention: feed the function the analyst's full findings
565
+ * list and filter out the `null`s; the orchestrator passes the
566
+ * remaining proposals to the existing review / apply pipeline.
502
567
  */
503
- type DefineReadinessSpecInput = Pick<KnowledgeReadinessSpec, 'id' | 'description' | 'query' | 'requiredFor'> & Partial<Omit<KnowledgeReadinessSpec, 'id' | 'description' | 'query' | 'requiredFor'>>;
568
+ declare function proposeFromFinding(finding: AnalystFinding): KnowledgeProposal | null;
504
569
  /**
505
- * Builder that returns a fully-typed `KnowledgeReadinessSpec` from a slim input.
506
- *
507
- * Motivation: `KnowledgeReadinessSpec` has eleven required fields. Most of them
508
- * (category, acquisition mode, importance, freshness, sensitivity, confidence
509
- * threshold, source/hit minima) have a clear default for domain-specific KB
510
- * topics — agents end up copy-pasting the same boilerplate across every spec.
511
- * This helper collapses that boilerplate while keeping every field overridable.
512
- *
513
- * @example
514
- * defineReadinessSpec({
515
- * id: 'coop/intent-grounding',
516
- * description: 'Required grounding for coop pack intent stage',
517
- * query: 'flock size space ventilation predator',
518
- * requiredFor: ['IntentIntakeAgent', 'requirements'],
519
- * })
520
- *
521
- * @example // override defaults where the topic demands it
522
- * defineReadinessSpec({
523
- * id: 'medical/dosing',
524
- * description: 'Dosing guidance for compounding pharmacy',
525
- * query: 'compounding dose schedule',
526
- * requiredFor: ['DosingAgent'],
527
- * importance: 'blocking',
528
- * freshness: 'daily',
529
- * sensitivity: 'private',
530
- * confidenceNeeded: 0.95,
531
- * minSources: 3,
532
- * })
570
+ * Plural convenience: filter + map across an entire findings batch
571
+ * with one call. Parse errors collect into `errors[]`; the loop
572
+ * decides per-error whether to abort or continue.
533
573
  */
534
- declare function defineReadinessSpec(input: DefineReadinessSpecInput): KnowledgeReadinessSpec;
535
- interface BuildEvalKnowledgeBundleOptions {
536
- taskId: string;
537
- index: KnowledgeIndex;
538
- specs: KnowledgeReadinessSpec[];
539
- userAnswers?: Record<string, string>;
540
- searchLimit?: number;
574
+ interface ProposeFromFindingsResult {
575
+ proposals: KnowledgeProposal[];
576
+ skipped: number;
577
+ errors: KnowledgeProposalParseError[];
578
+ }
579
+ declare function proposeFromFindings(findings: ReadonlyArray<AnalystFinding>): ProposeFromFindingsResult;
580
+
581
+ interface KnowledgeReleaseReport {
582
+ release: KnowledgeRelease;
583
+ scorecard: ReleaseConfidenceScorecard;
584
+ candidateRuns: RunRecord[];
585
+ baselineRuns: RunRecord[];
586
+ }
587
+ declare function knowledgeReleaseReportFromOptimization(result: MultiShotOptimizationResult<KnowledgeBaseCandidate>, options?: {
588
+ runRecords?: RunRecord[];
589
+ createdAt?: string;
590
+ minScore?: number;
591
+ }): KnowledgeReleaseReport;
592
+
593
+ interface AddSourceOptions {
594
+ copyIntoRaw?: boolean;
595
+ adapters?: SourceAdapter[];
596
+ now?: () => Date;
597
+ }
598
+ interface AddSourceTextInput {
599
+ uri: string;
600
+ text: string;
601
+ title?: string;
602
+ mediaType?: string;
603
+ validUntil?: string;
604
+ lastVerifiedAt?: string;
541
605
  metadata?: Record<string, unknown>;
542
- now?: Date;
543
606
  }
544
- interface EvalKnowledgeBundleBuildResult {
545
- bundle: KnowledgeBundle;
546
- report: KnowledgeReadinessReport;
547
- requirements: KnowledgeRequirement[];
548
- searchResultsByRequirement: Record<string, KnowledgeSearchResult[]>;
549
- questions: UserQuestion[];
550
- acquisitionPlans: DataAcquisitionPlan[];
607
+ declare function loadSourceRegistry(root: string): Promise<SourceRegistry>;
608
+ declare function writeSourceRegistry(root: string, registry: SourceRegistry): Promise<void>;
609
+ declare function addSourcePath(root: string, sourcePath: string, options?: AddSourceOptions): Promise<SourceRecord[]>;
610
+ declare function addSourceText(root: string, input: AddSourceTextInput, options?: Pick<AddSourceOptions, 'adapters' | 'now'>): Promise<SourceRecord>;
611
+ declare function sourceRegistryPath(root: string): string;
612
+
613
+ interface ValidateKnowledgeOptions {
614
+ strict?: boolean;
551
615
  }
552
- declare function buildEvalKnowledgeBundle(options: BuildEvalKnowledgeBundleOptions): EvalKnowledgeBundleBuildResult;
616
+ interface ValidateKnowledgeResult {
617
+ ok: boolean;
618
+ findings: KnowledgeLintFinding[];
619
+ }
620
+ declare function validateKnowledgeIndex(index: KnowledgeIndex, options?: ValidateKnowledgeOptions): ValidateKnowledgeResult;
553
621
 
554
622
  interface KnowledgeResearchLoopContext {
555
623
  root: string;
@@ -648,4 +716,216 @@ type KnowledgeControlLoopAdapter = Pick<ControlRuntimeConfig<KnowledgeControlLoo
648
716
  declare function createKnowledgeControlLoopAdapter(options: KnowledgeControlLoopAdapterOptions): KnowledgeControlLoopAdapter;
649
717
  declare function runKnowledgeResearchLoop(options: RunKnowledgeResearchLoopOptions): Promise<KnowledgeResearchLoopResult>;
650
718
 
651
- export { type AddSourceOptions, type AddSourceTextInput, type ApplyWriteBlocksResult, type BuildEvalKnowledgeBundleOptions, type ChunkingOptions, type DefineReadinessSpecInput, type DiscoveryResult, type DiscoveryTask, type EvalKnowledgeBundleBuildResult, FileSystemKbStore, type KbStore, KnowledgeBaseCandidate, KnowledgeBaseCandidateSchema, type KnowledgeBaseVariant, type KnowledgeChunk, type KnowledgeControlLoopAction, type KnowledgeControlLoopActionResult, type KnowledgeControlLoopAdapter, type KnowledgeControlLoopAdapterOptions, type KnowledgeControlLoopState, type KnowledgeDiscoveryDispatcher, type KnowledgeDiscoveryWorker, KnowledgeEvent, type KnowledgeEventQuery, KnowledgeEventSchema, KnowledgeEventType, type KnowledgeExplanation, KnowledgeGraph, KnowledgeGraphEdgeSchema, KnowledgeGraphNodeSchema, KnowledgeIndex, KnowledgeIndexSchema, type KnowledgeInspection, type KnowledgeLayout, KnowledgeLintFinding, type KnowledgeOptimizationConfig, KnowledgePage, KnowledgePageSchema, type KnowledgeReadinessSpec, KnowledgeRelease, type KnowledgeReleaseReport, type KnowledgeResearchLoopContext, type KnowledgeResearchLoopDecision, type KnowledgeResearchLoopResult, type KnowledgeResearchLoopStep, KnowledgeSearchResult, KnowledgeWriteParseResult, MemoryKbStore, type ParsedFrontmatter, READINESS_SPEC_DEFAULTS, type RunKnowledgeResearchLoopOptions, SCAFFOLD_PAGE_BASENAMES, type SourceAdapter, type SourceAdapterInput, type SourceAdapterOutput, SourceAnchorSchema, type SourceFreshnessInspection, SourceRecord, SourceRecordSchema, SourceRegistry, type ValidateKnowledgeOptions, type ValidateKnowledgeResult, WIKILINK_REGEX, addSourcePath, addSourceText, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, buildEvalKnowledgeBundle, buildKnowledgeGraph, buildKnowledgeIndex, chunkMarkdown, createKnowledgeControlLoopAdapter, createKnowledgeEvent, createLocalDiscoveryDispatcher, defineReadinessSpec, explainKnowledgeTarget, extractWikilinks, formatFrontmatter, initKnowledgeBase, inspectKnowledgeIndex, isSafeKnowledgePath, isScaffoldPath, knowledgeReleaseReportFromOptimization, knowledgeVariantFromCandidate, layoutFor, lintKnowledgeIndex, loadKnowledgePages, loadSourceRegistry, mediaTypeFor, normalizeLinkTarget, parseFrontmatter, parseKnowledgeWriteBlocks, reciprocalRankFusion, runKnowledgeBaseOptimization, runKnowledgeResearchLoop, searchKnowledge, sha256, slugify, sourceRegistryPath, stableId, stripFrontmatter, textSourceAdapter, tokenizeQuery, validateKnowledgeIndex, writeJson, writeKnowledgeIndex, writeSourceRegistry };
719
+ declare const SourceAnchorSchema: z.ZodObject<{
720
+ id: z.ZodString;
721
+ sourceId: z.ZodString;
722
+ label: z.ZodOptional<z.ZodString>;
723
+ page: z.ZodOptional<z.ZodNumber>;
724
+ lineStart: z.ZodOptional<z.ZodNumber>;
725
+ lineEnd: z.ZodOptional<z.ZodNumber>;
726
+ charStart: z.ZodOptional<z.ZodNumber>;
727
+ charEnd: z.ZodOptional<z.ZodNumber>;
728
+ timestampMs: z.ZodOptional<z.ZodNumber>;
729
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
730
+ }, z.core.$strip>;
731
+ declare const SourceRecordSchema: z.ZodObject<{
732
+ id: z.ZodString;
733
+ uri: z.ZodString;
734
+ title: z.ZodOptional<z.ZodString>;
735
+ mediaType: z.ZodOptional<z.ZodString>;
736
+ contentHash: z.ZodString;
737
+ text: z.ZodOptional<z.ZodString>;
738
+ anchors: z.ZodOptional<z.ZodArray<z.ZodObject<{
739
+ id: z.ZodString;
740
+ sourceId: z.ZodString;
741
+ label: z.ZodOptional<z.ZodString>;
742
+ page: z.ZodOptional<z.ZodNumber>;
743
+ lineStart: z.ZodOptional<z.ZodNumber>;
744
+ lineEnd: z.ZodOptional<z.ZodNumber>;
745
+ charStart: z.ZodOptional<z.ZodNumber>;
746
+ charEnd: z.ZodOptional<z.ZodNumber>;
747
+ timestampMs: z.ZodOptional<z.ZodNumber>;
748
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
749
+ }, z.core.$strip>>>;
750
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
751
+ createdAt: z.ZodString;
752
+ }, z.core.$strip>;
753
+ declare const KnowledgePageSchema: z.ZodObject<{
754
+ id: z.ZodString;
755
+ path: z.ZodString;
756
+ title: z.ZodString;
757
+ text: z.ZodString;
758
+ frontmatter: z.ZodRecord<z.ZodString, z.ZodUnknown>;
759
+ sourceIds: z.ZodArray<z.ZodString>;
760
+ tags: z.ZodArray<z.ZodString>;
761
+ outLinks: z.ZodArray<z.ZodString>;
762
+ }, z.core.$strip>;
763
+ declare const KnowledgeGraphNodeSchema: z.ZodObject<{
764
+ id: z.ZodString;
765
+ title: z.ZodString;
766
+ path: z.ZodString;
767
+ tags: z.ZodArray<z.ZodString>;
768
+ sourceIds: z.ZodArray<z.ZodString>;
769
+ outDegree: z.ZodNumber;
770
+ inDegree: z.ZodNumber;
771
+ }, z.core.$strip>;
772
+ declare const KnowledgeGraphEdgeSchema: z.ZodObject<{
773
+ source: z.ZodString;
774
+ target: z.ZodString;
775
+ weight: z.ZodNumber;
776
+ reasons: z.ZodArray<z.ZodString>;
777
+ }, z.core.$strip>;
778
+ declare const KnowledgeIndexSchema: z.ZodObject<{
779
+ root: z.ZodString;
780
+ generatedAt: z.ZodString;
781
+ sources: z.ZodArray<z.ZodObject<{
782
+ id: z.ZodString;
783
+ uri: z.ZodString;
784
+ title: z.ZodOptional<z.ZodString>;
785
+ mediaType: z.ZodOptional<z.ZodString>;
786
+ contentHash: z.ZodString;
787
+ text: z.ZodOptional<z.ZodString>;
788
+ anchors: z.ZodOptional<z.ZodArray<z.ZodObject<{
789
+ id: z.ZodString;
790
+ sourceId: z.ZodString;
791
+ label: z.ZodOptional<z.ZodString>;
792
+ page: z.ZodOptional<z.ZodNumber>;
793
+ lineStart: z.ZodOptional<z.ZodNumber>;
794
+ lineEnd: z.ZodOptional<z.ZodNumber>;
795
+ charStart: z.ZodOptional<z.ZodNumber>;
796
+ charEnd: z.ZodOptional<z.ZodNumber>;
797
+ timestampMs: z.ZodOptional<z.ZodNumber>;
798
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
799
+ }, z.core.$strip>>>;
800
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
801
+ createdAt: z.ZodString;
802
+ }, z.core.$strip>>;
803
+ pages: z.ZodArray<z.ZodObject<{
804
+ id: z.ZodString;
805
+ path: z.ZodString;
806
+ title: z.ZodString;
807
+ text: z.ZodString;
808
+ frontmatter: z.ZodRecord<z.ZodString, z.ZodUnknown>;
809
+ sourceIds: z.ZodArray<z.ZodString>;
810
+ tags: z.ZodArray<z.ZodString>;
811
+ outLinks: z.ZodArray<z.ZodString>;
812
+ }, z.core.$strip>>;
813
+ graph: z.ZodObject<{
814
+ nodes: z.ZodArray<z.ZodObject<{
815
+ id: z.ZodString;
816
+ title: z.ZodString;
817
+ path: z.ZodString;
818
+ tags: z.ZodArray<z.ZodString>;
819
+ sourceIds: z.ZodArray<z.ZodString>;
820
+ outDegree: z.ZodNumber;
821
+ inDegree: z.ZodNumber;
822
+ }, z.core.$strip>>;
823
+ edges: z.ZodArray<z.ZodObject<{
824
+ source: z.ZodString;
825
+ target: z.ZodString;
826
+ weight: z.ZodNumber;
827
+ reasons: z.ZodArray<z.ZodString>;
828
+ }, z.core.$strip>>;
829
+ }, z.core.$strip>;
830
+ }, z.core.$strip>;
831
+ declare const KnowledgeEventSchema: z.ZodObject<{
832
+ id: z.ZodString;
833
+ type: z.ZodEnum<{
834
+ "source.added": "source.added";
835
+ "proposal.applied": "proposal.applied";
836
+ "index.built": "index.built";
837
+ "lint.run": "lint.run";
838
+ "optimization.run": "optimization.run";
839
+ "release.promoted": "release.promoted";
840
+ "release.rejected": "release.rejected";
841
+ }>;
842
+ createdAt: z.ZodString;
843
+ actor: z.ZodOptional<z.ZodString>;
844
+ target: z.ZodOptional<z.ZodString>;
845
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
846
+ }, z.core.$strip>;
847
+ declare const KnowledgeBaseCandidateSchema: z.ZodObject<{
848
+ id: z.ZodString;
849
+ units: z.ZodArray<z.ZodObject<{
850
+ id: z.ZodString;
851
+ title: z.ZodString;
852
+ text: z.ZodString;
853
+ claims: z.ZodOptional<z.ZodArray<z.ZodObject<{
854
+ id: z.ZodString;
855
+ text: z.ZodString;
856
+ refs: z.ZodArray<z.ZodObject<{
857
+ sourceId: z.ZodString;
858
+ anchorId: z.ZodOptional<z.ZodString>;
859
+ quote: z.ZodOptional<z.ZodString>;
860
+ }, z.core.$strip>>;
861
+ confidence: z.ZodOptional<z.ZodNumber>;
862
+ status: z.ZodOptional<z.ZodEnum<{
863
+ draft: "draft";
864
+ active: "active";
865
+ superseded: "superseded";
866
+ rejected: "rejected";
867
+ }>>;
868
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
869
+ }, z.core.$strip>>>;
870
+ relations: z.ZodOptional<z.ZodArray<z.ZodObject<{
871
+ sourceId: z.ZodString;
872
+ targetId: z.ZodString;
873
+ predicate: z.ZodString;
874
+ weight: z.ZodOptional<z.ZodNumber>;
875
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
876
+ }, z.core.$strip>>>;
877
+ sourceIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
878
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
879
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
880
+ updatedAt: z.ZodOptional<z.ZodString>;
881
+ }, z.core.$strip>>;
882
+ retrievalPolicy: z.ZodOptional<z.ZodString>;
883
+ synthesisPolicy: z.ZodOptional<z.ZodString>;
884
+ questionPolicy: z.ZodOptional<z.ZodString>;
885
+ updatePolicy: z.ZodOptional<z.ZodString>;
886
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
887
+ }, z.core.$strip>;
888
+
889
+ declare function searchKnowledge(index: KnowledgeIndex, query: string, limit?: number): KnowledgeSearchResult[];
890
+ declare function tokenizeQuery(query: string): string[];
891
+ declare function reciprocalRankFusion(rankLists: string[][], k?: number): Map<string, number>;
892
+
893
+ interface KnowledgeLayout {
894
+ root: string;
895
+ knowledgeDir: string;
896
+ rawSourcesDir: string;
897
+ sourceRegistryPath: string;
898
+ indexPath: string;
899
+ logPath: string;
900
+ cacheDir: string;
901
+ }
902
+ declare function layoutFor(root: string): KnowledgeLayout;
903
+ /**
904
+ * Filenames that `initKnowledgeBase` writes as human-navigation scaffolding.
905
+ * These are excluded from the page index — they exist on disk so authors can
906
+ * curate their vault, but they are not searchable content.
907
+ *
908
+ * Add new scaffold filenames here (and only here) to keep lint, validate, viz,
909
+ * and the indexer consistent.
910
+ */
911
+ declare const SCAFFOLD_PAGE_BASENAMES: readonly string[];
912
+ /**
913
+ * True when a knowledge-relative path points at a scaffold file rather than
914
+ * authored content. Accepts both repo-relative paths (`knowledge/index.md`)
915
+ * and any nested `<dir>/index.md` or `<dir>/log.md` (for example
916
+ * `knowledge/concepts/index.md`) so subdirectory README-style scaffolds are
917
+ * also excluded.
918
+ */
919
+ declare function isScaffoldPath(path: string): boolean;
920
+ declare function initKnowledgeBase(root: string): Promise<KnowledgeLayout>;
921
+ declare function loadKnowledgePages(root: string): Promise<KnowledgePage[]>;
922
+ declare function writeJson(path: string, value: unknown): Promise<void>;
923
+
924
+ declare const WIKILINK_REGEX: RegExp;
925
+ declare function extractWikilinks(content: string): string[];
926
+ declare function normalizeLinkTarget(target: string): string;
927
+
928
+ declare function isSafeKnowledgePath(path: string, allowedPrefixes?: string[]): boolean;
929
+ declare function parseKnowledgeWriteBlocks(text: string, allowedPrefixes?: string[]): KnowledgeWriteParseResult;
930
+
931
+ export { type AddSourceOptions, type AddSourceTextInput, type ApplyWriteBlocksResult, type BuildEvalKnowledgeBundleOptions, type ChunkingOptions, type D1Adapter, type DefineReadinessSpecInput, type DetectChangesOptions, type DetectChangesResult, type DiscoveryResult, type DiscoveryTask, type EvalKnowledgeBundleBuildResult, type FileSystemFreshnessStoreOptions, FileSystemKbStore, type FreshnessKey, type FreshnessMark, type FreshnessRecord, type FreshnessTtl, type KbStore, KnowledgeBaseCandidate, KnowledgeBaseCandidateSchema, type KnowledgeBaseVariant, type KnowledgeChange, type KnowledgeChangeKind, type KnowledgeChunk, KnowledgeClaim, type KnowledgeControlLoopAction, type KnowledgeControlLoopActionResult, type KnowledgeControlLoopAdapter, type KnowledgeControlLoopAdapterOptions, type KnowledgeControlLoopState, type KnowledgeDiscoveryDispatcher, type KnowledgeDiscoveryWorker, KnowledgeEvent, type KnowledgeEventQuery, KnowledgeEventSchema, KnowledgeEventType, type KnowledgeExplanation, KnowledgeFragment, type KnowledgeFreshnessStore, KnowledgeGraph, KnowledgeGraphEdgeSchema, KnowledgeGraphNodeSchema, KnowledgeIndex, KnowledgeIndexSchema, type KnowledgeInspection, type KnowledgeLayout, KnowledgeLintFinding, type KnowledgeOptimizationConfig, KnowledgePage, KnowledgePageSchema, type KnowledgeProposal, KnowledgeProposalParseError, type KnowledgeReadinessSpec, KnowledgeRelease, type KnowledgeReleaseReport, type KnowledgeResearchLoopContext, type KnowledgeResearchLoopDecision, type KnowledgeResearchLoopResult, type KnowledgeResearchLoopStep, KnowledgeSearchResult, KnowledgeWriteBlock, KnowledgeWriteParseResult, MemoryKbStore, type ParsedFrontmatter, type ProposeFromFindingsResult, READINESS_SPEC_DEFAULTS, type RunKnowledgeResearchLoopOptions, SCAFFOLD_PAGE_BASENAMES, type SourceAdapter, type SourceAdapterInput, type SourceAdapterOutput, SourceAnchorSchema, type SourceFreshnessInspection, SourceRecord, SourceRecordSchema, SourceRegistry, type ValidateKnowledgeOptions, type ValidateKnowledgeResult, WIKILINK_REGEX, addSourcePath, addSourceText, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, buildEvalKnowledgeBundle, buildKnowledgeGraph, buildKnowledgeIndex, chunkMarkdown, createD1FreshnessStoreStub, createFileSystemFreshnessStore, createKnowledgeControlLoopAdapter, createKnowledgeEvent, createLocalDiscoveryDispatcher, defineReadinessSpec, detectChanges, explainKnowledgeTarget, extractWikilinks, formatFrontmatter, initKnowledgeBase, inspectKnowledgeIndex, isSafeKnowledgePath, isScaffoldPath, knowledgeReleaseReportFromOptimization, knowledgeVariantFromCandidate, layoutFor, lintKnowledgeIndex, loadKnowledgePages, loadSourceRegistry, mediaTypeFor, normalizeLinkTarget, parseFrontmatter, parseKnowledgeWriteBlocks, proposeFromFinding, proposeFromFindings, reciprocalRankFusion, runKnowledgeBaseOptimization, runKnowledgeResearchLoop, searchKnowledge, sha256, slugify, sourceRegistryPath, stableId, stripFrontmatter, textSourceAdapter, tokenizeQuery, validateKnowledgeIndex, writeJson, writeKnowledgeIndex, writeSourceRegistry };