@tangle-network/agent-knowledge 0.1.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +9 -0
- package/README.md +7 -0
- package/dist/{chunk-XDXIBHPS.js → chunk-WCUKMCAY.js} +228 -68
- package/dist/chunk-WCUKMCAY.js.map +1 -0
- package/dist/cli.js +26 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +275 -4
- package/dist/index.js +178 -1
- package/dist/index.js.map +1 -1
- package/dist/{types-C1FBNRIN.d.ts → types-CFylueZb.d.ts} +20 -2
- package/dist/viz/index.d.ts +1 -1
- package/docs/architecture.md +8 -0
- package/package.json +1 -1
- package/dist/chunk-XDXIBHPS.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport { buildKnowledgeIndex, writeKnowledgeIndex } from './indexer'\nimport { explainKnowledgeTarget, inspectKnowledgeIndex } from './inspect'\nimport { lintKnowledgeIndex } from './lint'\nimport { applyKnowledgeWriteBlocksFile } from './proposals'\nimport { searchKnowledge } from './search'\nimport { addSourcePath, loadSourceRegistry } from './sources'\nimport { initKnowledgeBase, layoutFor } from './store'\nimport { detectKnowledgeGaps, findSurprisingConnections, toKnowledgeVizGraph } from './viz/index'\n\ninterface Args {\n command: string\n positional: string[]\n flags: Record<string, string>\n}\n\nfunction parseArgs(argv: string[]): Args {\n const [command, ...rest] = argv\n const positional: string[] = []\n const flags: Record<string, string> = {}\n for (let i = 0; i < rest.length; i++) {\n const token = rest[i]!\n if (token.startsWith('--')) {\n const key = token.slice(2)\n const next = rest[i + 1]\n if (next && !next.startsWith('--')) {\n flags[key] = next\n i++\n } else {\n flags[key] = 'true'\n }\n } else {\n positional.push(token)\n }\n }\n return { command: command ?? 'help', positional, flags }\n}\n\nconst HELP = `agent-knowledge — source-grounded knowledge graph CLI.\n\nCommands:\n init [--root .]\n Create raw/sources, knowledge, and cache directories.\n index [--root .] [--json]\n Build .agent-knowledge/index.json from knowledge/**/*.md.\n source-add <path> [--root .] [--json]\n Copy a file or directory into raw/sources and register immutable source records.\n sources [--root .] [--json]\n List registered sources.\n apply-write-blocks <proposal-file> [--root .] [--json]\n Apply safe ---FILE: knowledge/...--- blocks emitted by an agent.\n inspect [--root .] [--json]\n Summarize page/source/edge counts, top pages, and lint state.\n explain <page|id|query> [--root .] [--json]\n Explain sources, links, inbound links, and related pages.\n search <query> [--root .] [--limit 10] [--json]\n Fast local token+graph search over the generated knowledge index.\n graph [--root .] [--format summary|json]\n Emit graph summary or JSON.\n lint [--root .] [--json]\n Run deterministic structural lint.\n viz [--root .] [--json]\n Emit graph gaps and surprising connections.\n version\n Print package version.\n`\n\nasync function main(): Promise<number> {\n const args = parseArgs(process.argv.slice(2))\n const root = resolve(args.flags.root ?? '.')\n switch (args.command) {\n case 'init': {\n const layout = await initKnowledgeBase(root)\n process.stdout.write(`initialized knowledge base at ${layout.root}\\n`)\n return 0\n }\n case 'index': {\n const index = await writeKnowledgeIndex(root)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(index, null, 2) + '\\n')\n else process.stdout.write(`indexed ${index.pages.length} pages, ${index.graph.edges.length} edges\\n`)\n return 0\n }\n case 'source-add': {\n const [path] = args.positional\n if (!path) {\n process.stderr.write('source-add requires a file or directory path\\n')\n return 1\n }\n await initKnowledgeBase(root)\n const sources = await addSourcePath(root, resolve(path))\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(sources, null, 2) + '\\n')\n else for (const source of sources) process.stdout.write(`${source.id} ${source.uri}\\n`)\n return 0\n }\n case 'sources': {\n const registry = await loadSourceRegistry(root)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(registry.sources, null, 2) + '\\n')\n else {\n for (const source of registry.sources) process.stdout.write(`${source.id} ${source.title ?? source.uri} ${source.uri}\\n`)\n }\n return 0\n }\n case 'apply-write-blocks': {\n const [proposalPath] = args.positional\n if (!proposalPath) {\n process.stderr.write('apply-write-blocks requires a proposal file\\n')\n return 1\n }\n await initKnowledgeBase(root)\n const result = await applyKnowledgeWriteBlocksFile(root, resolve(proposalPath))\n await writeKnowledgeIndex(root)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n else {\n for (const path of result.written) process.stdout.write(`wrote ${path}\\n`)\n for (const warning of result.warnings) process.stderr.write(`warning: ${warning}\\n`)\n }\n return result.warnings.length > 0 ? 2 : 0\n }\n case 'inspect': {\n const index = await loadOrBuildIndex(root)\n const inspection = inspectKnowledgeIndex(index)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(inspection, null, 2) + '\\n')\n else {\n process.stdout.write(`pages=${inspection.pageCount} sources=${inspection.sourceCount} edges=${inspection.edgeCount} findings=${inspection.findingCount} blocking=${inspection.blockingFindingCount}\\n`)\n for (const page of inspection.topPages.slice(0, 5)) process.stdout.write(`${page.degree} ${page.path} sources=${page.sources}\\n`)\n }\n return inspection.blockingFindingCount > 0 ? 2 : 0\n }\n case 'explain': {\n const target = args.positional.join(' ')\n if (!target) {\n process.stderr.write('explain requires a page path, id, title, or query\\n')\n return 1\n }\n const explanation = explainKnowledgeTarget(await loadOrBuildIndex(root), target)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(explanation, null, 2) + '\\n')\n else {\n process.stdout.write(`${explanation.page ? explanation.page.title : target}\\n`)\n for (const source of explanation.sources) process.stdout.write(`source ${source.id} ${source.title ?? source.uri}\\n`)\n for (const link of explanation.links) process.stdout.write(`out ${link}\\n`)\n for (const inbound of explanation.inbound) process.stdout.write(`in ${inbound}\\n`)\n for (const related of explanation.related.slice(0, 5)) process.stdout.write(`related ${related.path} score=${related.score.toFixed(5)}\\n`)\n }\n return 0\n }\n case 'search': {\n const query = args.positional.join(' ')\n if (!query) {\n process.stderr.write('search requires a query\\n')\n return 1\n }\n const index = await loadOrBuildIndex(root)\n const results = searchKnowledge(index, query, Number(args.flags.limit ?? 10))\n if (args.flags.json === 'true') {\n process.stdout.write(JSON.stringify(results, null, 2) + '\\n')\n } else {\n for (const result of results) {\n process.stdout.write(`${result.rank}. ${result.page.title} (${result.page.path}) score=${result.score.toFixed(5)}\\n`)\n if (result.snippet) process.stdout.write(` ${result.snippet}\\n`)\n }\n }\n return 0\n }\n case 'graph': {\n const index = await loadOrBuildIndex(root)\n if ((args.flags.format ?? 'summary') === 'json') process.stdout.write(JSON.stringify(index.graph, null, 2) + '\\n')\n else process.stdout.write(`nodes=${index.graph.nodes.length} edges=${index.graph.edges.length}\\n`)\n return 0\n }\n case 'lint': {\n const index = await loadOrBuildIndex(root)\n const findings = lintKnowledgeIndex(index)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(findings, null, 2) + '\\n')\n else {\n if (findings.length === 0) process.stdout.write('no findings\\n')\n for (const finding of findings) {\n process.stdout.write(`${finding.severity.toUpperCase()} ${finding.type}${finding.page ? ` ${finding.page}` : ''}: ${finding.message}\\n`)\n }\n }\n return findings.some((finding) => finding.severity === 'error') ? 2 : 0\n }\n case 'viz': {\n const index = await loadOrBuildIndex(root)\n const viz = toKnowledgeVizGraph(index.graph)\n const payload = {\n graph: viz,\n gaps: detectKnowledgeGaps(viz),\n surprisingConnections: findSurprisingConnections(viz),\n }\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(payload, null, 2) + '\\n')\n else {\n process.stdout.write(`communities=${viz.communities.length} gaps=${payload.gaps.length} surprising=${payload.surprisingConnections.length}\\n`)\n }\n return 0\n }\n case 'version': {\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }\n process.stdout.write(`${pkg.version}\\n`)\n return 0\n }\n case 'help':\n case '--help':\n case '-h':\n process.stdout.write(HELP)\n return 0\n default:\n process.stderr.write(`unknown command: ${args.command}\\n${HELP}`)\n return 1\n }\n}\n\nasync function loadOrBuildIndex(root: string) {\n const path = join(layoutFor(root).cacheDir, 'index.json')\n if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Awaited<ReturnType<typeof buildKnowledgeIndex>>\n return await writeKnowledgeIndex(root)\n}\n\nmain()\n .then((code) => process.exit(code))\n .catch((err) => {\n process.stderr.write(`agent-knowledge error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\\n`)\n process.exit(1)\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AACA,SAAS,YAAY,oBAAoB;AACzC,SAAS,MAAM,eAAe;AAiB9B,SAAS,UAAU,MAAsB;AACvC,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAC3B,QAAM,aAAuB,CAAC;AAC9B,QAAM,QAAgC,CAAC;AACvC,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,QAAQ,KAAK,CAAC;AACpB,QAAI,MAAM,WAAW,IAAI,GAAG;AAC1B,YAAM,MAAM,MAAM,MAAM,CAAC;AACzB,YAAM,OAAO,KAAK,IAAI,CAAC;AACvB,UAAI,QAAQ,CAAC,KAAK,WAAW,IAAI,GAAG;AAClC,cAAM,GAAG,IAAI;AACb;AAAA,MACF,OAAO;AACL,cAAM,GAAG,IAAI;AAAA,MACf;AAAA,IACF,OAAO;AACL,iBAAW,KAAK,KAAK;AAAA,IACvB;AAAA,EACF;AACA,SAAO,EAAE,SAAS,WAAW,QAAQ,YAAY,MAAM;AACzD;AAEA,IAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6Bb,eAAe,OAAwB;AACrC,QAAM,OAAO,UAAU,QAAQ,KAAK,MAAM,CAAC,CAAC;AAC5C,QAAM,OAAO,QAAQ,KAAK,MAAM,QAAQ,GAAG;AAC3C,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;AACA,UAAI,KAAK,MAAM,SAAS,OAAQ,SAAQ,OAAO,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,IAAI,IAAI;AAAA,WACvF;AACH,gBAAQ,OAAO,MAAM,eAAe,IAAI,YAAY,MAAM,SAAS,QAAQ,KAAK,MAAM,eAAe,QAAQ,sBAAsB,MAAM;AAAA,CAAI;AAAA,MAC/I;AACA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,WAAW;AACd,YAAM,MAAM,KAAK,MAAM,aAAa,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG,MAAM,CAAC;AACxF,cAAQ,OAAO,MAAM,GAAG,IAAI,OAAO;AAAA,CAAI;AACvC,aAAO;AAAA,IACT;AAAA,IACA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,cAAQ,OAAO,MAAM,IAAI;AACzB,aAAO;AAAA,IACT;AACE,cAAQ,OAAO,MAAM,oBAAoB,KAAK,OAAO;AAAA,EAAK,IAAI,EAAE;AAChE,aAAO;AAAA,EACX;AACF;AAEA,eAAe,iBAAiB,MAAc;AAC5C,QAAM,OAAO,KAAK,UAAU,IAAI,EAAE,UAAU,YAAY;AACxD,MAAI,WAAW,IAAI,EAAG,QAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAClE,SAAO,MAAM,oBAAoB,IAAI;AACvC;AAEA,KAAK,EACF,KAAK,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC,EACjC,MAAM,CAAC,QAAQ;AACd,UAAQ,OAAO,MAAM,0BAA0B,eAAe,QAAQ,IAAI,SAAS,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAChH,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport { buildKnowledgeIndex, writeKnowledgeIndex } from './indexer'\nimport { explainKnowledgeTarget, inspectKnowledgeIndex } from './inspect'\nimport { lintKnowledgeIndex } from './lint'\nimport { applyKnowledgeWriteBlocksFile } from './proposals'\nimport { searchKnowledge } from './search'\nimport { addSourcePath, loadSourceRegistry } from './sources'\nimport { initKnowledgeBase, layoutFor } from './store'\nimport { validateKnowledgeIndex } from './validate'\nimport { detectKnowledgeGaps, findSurprisingConnections, toKnowledgeVizGraph } from './viz/index'\n\ninterface Args {\n command: string\n positional: string[]\n flags: Record<string, string>\n}\n\nfunction parseArgs(argv: string[]): Args {\n const [command, ...rest] = argv\n const positional: string[] = []\n const flags: Record<string, string> = {}\n for (let i = 0; i < rest.length; i++) {\n const token = rest[i]!\n if (token.startsWith('--')) {\n const key = token.slice(2)\n const next = rest[i + 1]\n if (next && !next.startsWith('--')) {\n flags[key] = next\n i++\n } else {\n flags[key] = 'true'\n }\n } else {\n positional.push(token)\n }\n }\n return { command: command ?? 'help', positional, flags }\n}\n\nconst HELP = `agent-knowledge — source-grounded knowledge graph CLI.\n\nCommands:\n init [--root .]\n Create raw/sources, knowledge, and cache directories.\n index [--root .] [--json]\n Build .agent-knowledge/index.json from knowledge/**/*.md.\n source-add <path> [--root .] [--json]\n Copy a file or directory into raw/sources and register immutable source records.\n sources [--root .] [--json]\n List registered sources.\n apply-write-blocks <proposal-file> [--root .] [--json]\n Apply safe ---FILE: knowledge/...--- blocks emitted by an agent.\n inspect [--root .] [--json]\n Summarize page/source/edge counts, top pages, and lint state.\n explain <page|id|query> [--root .] [--json]\n Explain sources, links, inbound links, and related pages.\n search <query> [--root .] [--limit 10] [--json]\n Fast local token+graph search over the generated knowledge index.\n graph [--root .] [--format summary|json]\n Emit graph summary or JSON.\n lint [--root .] [--json]\n Run deterministic structural lint.\n validate [--root .] [--strict] [--json]\n Run schema + lint validation. Exits non-zero on blocking findings.\n export [--root .] [--format json]\n Export the current index.\n viz [--root .] [--json]\n Emit graph gaps and surprising connections.\n version\n Print package version.\n`\n\nasync function main(): Promise<number> {\n const args = parseArgs(process.argv.slice(2))\n const root = resolve(args.flags.root ?? '.')\n switch (args.command) {\n case 'init': {\n const layout = await initKnowledgeBase(root)\n process.stdout.write(`initialized knowledge base at ${layout.root}\\n`)\n return 0\n }\n case 'index': {\n const index = await writeKnowledgeIndex(root)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(index, null, 2) + '\\n')\n else process.stdout.write(`indexed ${index.pages.length} pages, ${index.graph.edges.length} edges\\n`)\n return 0\n }\n case 'source-add': {\n const [path] = args.positional\n if (!path) {\n process.stderr.write('source-add requires a file or directory path\\n')\n return 1\n }\n await initKnowledgeBase(root)\n const sources = await addSourcePath(root, resolve(path))\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(sources, null, 2) + '\\n')\n else for (const source of sources) process.stdout.write(`${source.id} ${source.uri}\\n`)\n return 0\n }\n case 'sources': {\n const registry = await loadSourceRegistry(root)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(registry.sources, null, 2) + '\\n')\n else {\n for (const source of registry.sources) process.stdout.write(`${source.id} ${source.title ?? source.uri} ${source.uri}\\n`)\n }\n return 0\n }\n case 'apply-write-blocks': {\n const [proposalPath] = args.positional\n if (!proposalPath) {\n process.stderr.write('apply-write-blocks requires a proposal file\\n')\n return 1\n }\n await initKnowledgeBase(root)\n const result = await applyKnowledgeWriteBlocksFile(root, resolve(proposalPath))\n await writeKnowledgeIndex(root)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n else {\n for (const path of result.written) process.stdout.write(`wrote ${path}\\n`)\n for (const warning of result.warnings) process.stderr.write(`warning: ${warning}\\n`)\n }\n return result.warnings.length > 0 ? 2 : 0\n }\n case 'inspect': {\n const index = await loadOrBuildIndex(root)\n const inspection = inspectKnowledgeIndex(index)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(inspection, null, 2) + '\\n')\n else {\n process.stdout.write(`pages=${inspection.pageCount} sources=${inspection.sourceCount} edges=${inspection.edgeCount} findings=${inspection.findingCount} blocking=${inspection.blockingFindingCount}\\n`)\n for (const page of inspection.topPages.slice(0, 5)) process.stdout.write(`${page.degree} ${page.path} sources=${page.sources}\\n`)\n }\n return inspection.blockingFindingCount > 0 ? 2 : 0\n }\n case 'explain': {\n const target = args.positional.join(' ')\n if (!target) {\n process.stderr.write('explain requires a page path, id, title, or query\\n')\n return 1\n }\n const explanation = explainKnowledgeTarget(await loadOrBuildIndex(root), target)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(explanation, null, 2) + '\\n')\n else {\n process.stdout.write(`${explanation.page ? explanation.page.title : target}\\n`)\n for (const source of explanation.sources) process.stdout.write(`source ${source.id} ${source.title ?? source.uri}\\n`)\n for (const link of explanation.links) process.stdout.write(`out ${link}\\n`)\n for (const inbound of explanation.inbound) process.stdout.write(`in ${inbound}\\n`)\n for (const related of explanation.related.slice(0, 5)) process.stdout.write(`related ${related.path} score=${related.score.toFixed(5)}\\n`)\n }\n return 0\n }\n case 'search': {\n const query = args.positional.join(' ')\n if (!query) {\n process.stderr.write('search requires a query\\n')\n return 1\n }\n const index = await loadOrBuildIndex(root)\n const results = searchKnowledge(index, query, Number(args.flags.limit ?? 10))\n if (args.flags.json === 'true') {\n process.stdout.write(JSON.stringify(results, null, 2) + '\\n')\n } else {\n for (const result of results) {\n process.stdout.write(`${result.rank}. ${result.page.title} (${result.page.path}) score=${result.score.toFixed(5)}\\n`)\n if (result.snippet) process.stdout.write(` ${result.snippet}\\n`)\n }\n }\n return 0\n }\n case 'graph': {\n const index = await loadOrBuildIndex(root)\n if ((args.flags.format ?? 'summary') === 'json') process.stdout.write(JSON.stringify(index.graph, null, 2) + '\\n')\n else process.stdout.write(`nodes=${index.graph.nodes.length} edges=${index.graph.edges.length}\\n`)\n return 0\n }\n case 'lint': {\n const index = await loadOrBuildIndex(root)\n const findings = lintKnowledgeIndex(index)\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(findings, null, 2) + '\\n')\n else {\n if (findings.length === 0) process.stdout.write('no findings\\n')\n for (const finding of findings) {\n process.stdout.write(`${finding.severity.toUpperCase()} ${finding.type}${finding.page ? ` ${finding.page}` : ''}: ${finding.message}\\n`)\n }\n }\n return findings.some((finding) => finding.severity === 'error') ? 2 : 0\n }\n case 'validate': {\n const result = validateKnowledgeIndex(await loadOrBuildIndex(root), { strict: args.flags.strict === 'true' })\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(result, null, 2) + '\\n')\n else {\n process.stdout.write(result.ok ? 'valid\\n' : 'invalid\\n')\n for (const finding of result.findings) process.stdout.write(`${finding.severity.toUpperCase()} ${finding.type}${finding.page ? ` ${finding.page}` : ''}: ${finding.message}\\n`)\n }\n return result.ok ? 0 : 2\n }\n case 'export': {\n const index = await loadOrBuildIndex(root)\n const format = args.flags.format ?? 'json'\n if (format !== 'json') {\n process.stderr.write('export currently supports --format json\\n')\n return 1\n }\n process.stdout.write(JSON.stringify(index, null, 2) + '\\n')\n return 0\n }\n case 'viz': {\n const index = await loadOrBuildIndex(root)\n const viz = toKnowledgeVizGraph(index.graph)\n const payload = {\n graph: viz,\n gaps: detectKnowledgeGaps(viz),\n surprisingConnections: findSurprisingConnections(viz),\n }\n if (args.flags.json === 'true') process.stdout.write(JSON.stringify(payload, null, 2) + '\\n')\n else {\n process.stdout.write(`communities=${viz.communities.length} gaps=${payload.gaps.length} surprising=${payload.surprisingConnections.length}\\n`)\n }\n return 0\n }\n case 'version': {\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }\n process.stdout.write(`${pkg.version}\\n`)\n return 0\n }\n case 'help':\n case '--help':\n case '-h':\n process.stdout.write(HELP)\n return 0\n default:\n process.stderr.write(`unknown command: ${args.command}\\n${HELP}`)\n return 1\n }\n}\n\nasync function loadOrBuildIndex(root: string) {\n const path = join(layoutFor(root).cacheDir, 'index.json')\n if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Awaited<ReturnType<typeof buildKnowledgeIndex>>\n return await writeKnowledgeIndex(root)\n}\n\nmain()\n .then((code) => process.exit(code))\n .catch((err) => {\n process.stderr.write(`agent-knowledge error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\\n`)\n process.exit(1)\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,SAAS,YAAY,oBAAoB;AACzC,SAAS,MAAM,eAAe;AAkB9B,SAAS,UAAU,MAAsB;AACvC,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAC3B,QAAM,aAAuB,CAAC;AAC9B,QAAM,QAAgC,CAAC;AACvC,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,QAAQ,KAAK,CAAC;AACpB,QAAI,MAAM,WAAW,IAAI,GAAG;AAC1B,YAAM,MAAM,MAAM,MAAM,CAAC;AACzB,YAAM,OAAO,KAAK,IAAI,CAAC;AACvB,UAAI,QAAQ,CAAC,KAAK,WAAW,IAAI,GAAG;AAClC,cAAM,GAAG,IAAI;AACb;AAAA,MACF,OAAO;AACL,cAAM,GAAG,IAAI;AAAA,MACf;AAAA,IACF,OAAO;AACL,iBAAW,KAAK,KAAK;AAAA,IACvB;AAAA,EACF;AACA,SAAO,EAAE,SAAS,WAAW,QAAQ,YAAY,MAAM;AACzD;AAEA,IAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCb,eAAe,OAAwB;AACrC,QAAM,OAAO,UAAU,QAAQ,KAAK,MAAM,CAAC,CAAC;AAC5C,QAAM,OAAO,QAAQ,KAAK,MAAM,QAAQ,GAAG;AAC3C,UAAQ,KAAK,SAAS;AAAA,IACpB,KAAK,QAAQ;AACX,YAAM,SAAS,MAAM,kBAAkB,IAAI;AAC3C,cAAQ,OAAO,MAAM,iCAAiC,OAA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O,MAAM,oBAAoB,KAAK,OAAO;AAAA,EAAK,IAAI,EAAE;AAChE,aAAO;AAAA,EACX;AACF;AAEA,eAAe,iBAAiB,MAAc;AAC5C,QAAM,OAAO,KAAK,UAAU,IAAI,EAAE,UAAU,YAAY;AACxD,MAAI,WAAW,IAAI,EAAG,QAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAClE,SAAO,MAAM,oBAAoB,IAAI;AACvC;AAEA,KAAK,EACF,KAAK,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC,EACjC,MAAM,CAAC,QAAQ;AACd,UAAQ,OAAO,MAAM,0BAA0B,eAAe,QAAQ,IAAI,SAAS,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAChH,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { c as KnowledgeWriteParseResult, S as SourceRecord, d as
|
|
2
|
-
export { C as ClaimRef,
|
|
3
|
-
import {
|
|
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-CFylueZb.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-CFylueZb.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { MultiShotVariant, MultiShotOptimizationConfig, MultiShotRunner, MultiShotScorer, MultiShotMutateAdapter, MultiShotOptimizationResult, ReleaseConfidenceScorecard, RunRecord } from '@tangle-network/agent-eval';
|
|
4
5
|
|
|
5
6
|
declare function sha256(text: string): string;
|
|
6
7
|
declare function slugify(input: string): string;
|
|
@@ -48,6 +49,255 @@ interface ApplyWriteBlocksResult {
|
|
|
48
49
|
declare function applyKnowledgeWriteBlocks(root: string, proposalText: string): Promise<ApplyWriteBlocksResult>;
|
|
49
50
|
declare function applyKnowledgeWriteBlocksFile(root: string, proposalPath: string): Promise<ApplyWriteBlocksResult>;
|
|
50
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;
|
|
226
|
+
}
|
|
227
|
+
declare function createKnowledgeEvent(input: {
|
|
228
|
+
type: KnowledgeEventType;
|
|
229
|
+
actor?: string;
|
|
230
|
+
target?: string;
|
|
231
|
+
metadata?: Record<string, unknown>;
|
|
232
|
+
now?: () => Date;
|
|
233
|
+
}): KnowledgeEvent;
|
|
234
|
+
|
|
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[]>;
|
|
262
|
+
}
|
|
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>;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
interface DiscoveryTask {
|
|
272
|
+
id: string;
|
|
273
|
+
goal: string;
|
|
274
|
+
query?: string;
|
|
275
|
+
sourceHints?: string[];
|
|
276
|
+
metadata?: Record<string, unknown>;
|
|
277
|
+
}
|
|
278
|
+
interface DiscoveryResult {
|
|
279
|
+
taskId: string;
|
|
280
|
+
summary: string;
|
|
281
|
+
sourceUris?: string[];
|
|
282
|
+
claims?: Array<{
|
|
283
|
+
text: string;
|
|
284
|
+
sourceUri?: string;
|
|
285
|
+
confidence?: number;
|
|
286
|
+
}>;
|
|
287
|
+
followUpTasks?: DiscoveryTask[];
|
|
288
|
+
metadata?: Record<string, unknown>;
|
|
289
|
+
}
|
|
290
|
+
interface KnowledgeDiscoveryWorker {
|
|
291
|
+
run(task: DiscoveryTask, signal?: AbortSignal): Promise<DiscoveryResult> | DiscoveryResult;
|
|
292
|
+
}
|
|
293
|
+
interface KnowledgeDiscoveryDispatcher {
|
|
294
|
+
dispatch(tasks: DiscoveryTask[], options?: {
|
|
295
|
+
concurrency?: number;
|
|
296
|
+
signal?: AbortSignal;
|
|
297
|
+
}): Promise<DiscoveryResult[]>;
|
|
298
|
+
}
|
|
299
|
+
declare function createLocalDiscoveryDispatcher(worker: KnowledgeDiscoveryWorker): KnowledgeDiscoveryDispatcher;
|
|
300
|
+
|
|
51
301
|
interface ChunkingOptions {
|
|
52
302
|
targetChars: number;
|
|
53
303
|
maxChars: number;
|
|
@@ -136,6 +386,15 @@ interface KnowledgeExplanation {
|
|
|
136
386
|
}
|
|
137
387
|
declare function explainKnowledgeTarget(index: KnowledgeIndex, target: string): KnowledgeExplanation;
|
|
138
388
|
|
|
389
|
+
interface ValidateKnowledgeOptions {
|
|
390
|
+
strict?: boolean;
|
|
391
|
+
}
|
|
392
|
+
interface ValidateKnowledgeResult {
|
|
393
|
+
ok: boolean;
|
|
394
|
+
findings: KnowledgeLintFinding[];
|
|
395
|
+
}
|
|
396
|
+
declare function validateKnowledgeIndex(index: KnowledgeIndex, options?: ValidateKnowledgeOptions): ValidateKnowledgeResult;
|
|
397
|
+
|
|
139
398
|
type KnowledgeBaseVariant = MultiShotVariant<KnowledgeBaseCandidate>;
|
|
140
399
|
interface KnowledgeOptimizationConfig extends Omit<MultiShotOptimizationConfig<KnowledgeBaseCandidate>, 'runner' | 'scorer' | 'mutateAdapter' | 'target'> {
|
|
141
400
|
target?: string;
|
|
@@ -150,4 +409,16 @@ declare function knowledgeVariantFromCandidate(candidate: KnowledgeBaseCandidate
|
|
|
150
409
|
generation?: number;
|
|
151
410
|
}): KnowledgeBaseVariant;
|
|
152
411
|
|
|
153
|
-
|
|
412
|
+
interface KnowledgeReleaseReport {
|
|
413
|
+
release: KnowledgeRelease;
|
|
414
|
+
scorecard: ReleaseConfidenceScorecard;
|
|
415
|
+
candidateRuns: RunRecord[];
|
|
416
|
+
baselineRuns: RunRecord[];
|
|
417
|
+
}
|
|
418
|
+
declare function knowledgeReleaseReportFromOptimization(result: MultiShotOptimizationResult<KnowledgeBaseCandidate>, options?: {
|
|
419
|
+
runRecords?: RunRecord[];
|
|
420
|
+
createdAt?: string;
|
|
421
|
+
minScore?: number;
|
|
422
|
+
}): KnowledgeReleaseReport;
|
|
423
|
+
|
|
424
|
+
export { type AddSourceOptions, type ApplyWriteBlocksResult, type ChunkingOptions, type DiscoveryResult, type DiscoveryTask, FileSystemKbStore, type KbStore, KnowledgeBaseCandidate, KnowledgeBaseCandidateSchema, type KnowledgeBaseVariant, type KnowledgeChunk, 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, KnowledgeRelease, type KnowledgeReleaseReport, KnowledgeSearchResult, KnowledgeWriteParseResult, MemoryKbStore, type ParsedFrontmatter, type SourceAdapter, type SourceAdapterInput, type SourceAdapterOutput, SourceAnchorSchema, SourceRecord, SourceRecordSchema, SourceRegistry, type ValidateKnowledgeOptions, type ValidateKnowledgeResult, WIKILINK_REGEX, addSourcePath, applyKnowledgeWriteBlocks, applyKnowledgeWriteBlocksFile, buildKnowledgeGraph, buildKnowledgeIndex, chunkMarkdown, createKnowledgeEvent, createLocalDiscoveryDispatcher, explainKnowledgeTarget, extractWikilinks, formatFrontmatter, initKnowledgeBase, inspectKnowledgeIndex, isSafeKnowledgePath, knowledgeReleaseReportFromOptimization, knowledgeVariantFromCandidate, layoutFor, lintKnowledgeIndex, loadKnowledgePages, loadSourceRegistry, mediaTypeFor, normalizeLinkTarget, parseFrontmatter, parseKnowledgeWriteBlocks, reciprocalRankFusion, runKnowledgeBaseOptimization, searchKnowledge, sha256, slugify, sourceRegistryPath, stableId, stripFrontmatter, textSourceAdapter, tokenizeQuery, validateKnowledgeIndex, writeJson, writeKnowledgeIndex, writeSourceRegistry };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
+
KnowledgeBaseCandidateSchema,
|
|
3
|
+
KnowledgeEventSchema,
|
|
4
|
+
KnowledgeGraphEdgeSchema,
|
|
5
|
+
KnowledgeGraphNodeSchema,
|
|
6
|
+
KnowledgeIndexSchema,
|
|
7
|
+
KnowledgePageSchema,
|
|
8
|
+
SourceAnchorSchema,
|
|
9
|
+
SourceRecordSchema,
|
|
2
10
|
WIKILINK_REGEX,
|
|
3
11
|
addSourcePath,
|
|
4
12
|
applyKnowledgeWriteBlocks,
|
|
@@ -27,10 +35,121 @@ import {
|
|
|
27
35
|
stableId,
|
|
28
36
|
textSourceAdapter,
|
|
29
37
|
tokenizeQuery,
|
|
38
|
+
validateKnowledgeIndex,
|
|
30
39
|
writeJson,
|
|
31
40
|
writeKnowledgeIndex,
|
|
32
41
|
writeSourceRegistry
|
|
33
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-WCUKMCAY.js";
|
|
43
|
+
|
|
44
|
+
// src/events.ts
|
|
45
|
+
function createKnowledgeEvent(input) {
|
|
46
|
+
const createdAt = (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
47
|
+
return {
|
|
48
|
+
id: stableId("evt", `${input.type}:${input.target ?? ""}:${createdAt}:${JSON.stringify(input.metadata ?? {})}`),
|
|
49
|
+
type: input.type,
|
|
50
|
+
createdAt,
|
|
51
|
+
actor: input.actor,
|
|
52
|
+
target: input.target,
|
|
53
|
+
metadata: input.metadata
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/kb-store.ts
|
|
58
|
+
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
59
|
+
import { dirname, join } from "path";
|
|
60
|
+
var MemoryKbStore = class {
|
|
61
|
+
sources = /* @__PURE__ */ new Map();
|
|
62
|
+
pages = /* @__PURE__ */ new Map();
|
|
63
|
+
events = [];
|
|
64
|
+
index = null;
|
|
65
|
+
async putSource(source) {
|
|
66
|
+
this.sources.set(source.id, clone(source));
|
|
67
|
+
}
|
|
68
|
+
async getSource(id) {
|
|
69
|
+
return clone(this.sources.get(id) ?? null);
|
|
70
|
+
}
|
|
71
|
+
async listSources() {
|
|
72
|
+
return [...this.sources.values()].map(clone);
|
|
73
|
+
}
|
|
74
|
+
async putPage(page) {
|
|
75
|
+
this.pages.set(page.id, clone(page));
|
|
76
|
+
}
|
|
77
|
+
async getPage(idOrPath) {
|
|
78
|
+
return clone(this.pages.get(idOrPath) ?? [...this.pages.values()].find((page) => page.path === idOrPath) ?? null);
|
|
79
|
+
}
|
|
80
|
+
async listPages() {
|
|
81
|
+
return [...this.pages.values()].map(clone);
|
|
82
|
+
}
|
|
83
|
+
async putIndex(index) {
|
|
84
|
+
this.index = clone(index);
|
|
85
|
+
}
|
|
86
|
+
async getIndex() {
|
|
87
|
+
if (this.index) return clone(this.index);
|
|
88
|
+
const pages = await this.listPages();
|
|
89
|
+
const sources = await this.listSources();
|
|
90
|
+
return { root: "memory", generatedAt: (/* @__PURE__ */ new Date()).toISOString(), sources, pages, graph: buildKnowledgeGraph(pages) };
|
|
91
|
+
}
|
|
92
|
+
async putEvent(event) {
|
|
93
|
+
this.events.push(clone(event));
|
|
94
|
+
}
|
|
95
|
+
async listEvents(query = {}) {
|
|
96
|
+
let out = this.events;
|
|
97
|
+
if (query.type) out = out.filter((event) => event.type === query.type);
|
|
98
|
+
if (query.target) out = out.filter((event) => event.target === query.target);
|
|
99
|
+
out = [...out].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
100
|
+
return out.slice(-(query.limit ?? out.length)).map(clone);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
var FileSystemKbStore = class extends MemoryKbStore {
|
|
104
|
+
constructor(dir) {
|
|
105
|
+
super();
|
|
106
|
+
this.dir = dir;
|
|
107
|
+
}
|
|
108
|
+
dir;
|
|
109
|
+
async putIndex(index) {
|
|
110
|
+
await super.putIndex(index);
|
|
111
|
+
await writeJson2(join(this.dir, "index.json"), index);
|
|
112
|
+
}
|
|
113
|
+
async getIndex() {
|
|
114
|
+
try {
|
|
115
|
+
return JSON.parse(await readFile(join(this.dir, "index.json"), "utf8"));
|
|
116
|
+
} catch {
|
|
117
|
+
return await super.getIndex();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async putEvent(event) {
|
|
121
|
+
await super.putEvent(event);
|
|
122
|
+
const events = await this.listEvents();
|
|
123
|
+
await writeJson2(join(this.dir, "events.json"), events);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
async function writeJson2(path, value) {
|
|
127
|
+
await mkdir(dirname(path), { recursive: true });
|
|
128
|
+
await writeFile(path, JSON.stringify(value, null, 2) + "\n", "utf8");
|
|
129
|
+
}
|
|
130
|
+
function clone(value) {
|
|
131
|
+
return value == null ? value : JSON.parse(JSON.stringify(value));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/discovery.ts
|
|
135
|
+
function createLocalDiscoveryDispatcher(worker) {
|
|
136
|
+
return {
|
|
137
|
+
async dispatch(tasks, options = {}) {
|
|
138
|
+
const concurrency = Math.max(1, options.concurrency ?? 4);
|
|
139
|
+
const results = [];
|
|
140
|
+
let cursor = 0;
|
|
141
|
+
async function runNext() {
|
|
142
|
+
while (cursor < tasks.length) {
|
|
143
|
+
if (options.signal?.aborted) throw new Error("Discovery dispatch aborted");
|
|
144
|
+
const task = tasks[cursor++];
|
|
145
|
+
results.push(await worker.run(task, options.signal));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, runNext));
|
|
149
|
+
return results.sort((a, b) => tasks.findIndex((task) => task.id === a.taskId) - tasks.findIndex((task) => task.id === b.taskId));
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
34
153
|
|
|
35
154
|
// src/chunking.ts
|
|
36
155
|
var DEFAULT_OPTIONS = {
|
|
@@ -179,7 +298,61 @@ function knowledgeVariantFromCandidate(candidate, options = {}) {
|
|
|
179
298
|
payload: candidate
|
|
180
299
|
};
|
|
181
300
|
}
|
|
301
|
+
|
|
302
|
+
// src/release.ts
|
|
303
|
+
import {
|
|
304
|
+
evaluateReleaseConfidence,
|
|
305
|
+
releaseTraceEvidenceFromMultiShotTrials,
|
|
306
|
+
validateRunRecord
|
|
307
|
+
} from "@tangle-network/agent-eval";
|
|
308
|
+
function knowledgeReleaseReportFromOptimization(result, options = {}) {
|
|
309
|
+
const trials = result.evolution.generations.flatMap((generation) => generation.trials);
|
|
310
|
+
const traceEvidence = releaseTraceEvidenceFromMultiShotTrials(trials);
|
|
311
|
+
const runRecords = (options.runRecords ?? [
|
|
312
|
+
...result.gate?.candidateRuns ?? [],
|
|
313
|
+
...result.gate?.baselineRuns ?? []
|
|
314
|
+
]).map(validateRunRecord);
|
|
315
|
+
const scorecard = evaluateReleaseConfidence({
|
|
316
|
+
target: "agent-knowledge-base",
|
|
317
|
+
candidateId: result.promotedVariant.id,
|
|
318
|
+
baselineId: "baseline",
|
|
319
|
+
traces: traceEvidence,
|
|
320
|
+
runs: runRecords,
|
|
321
|
+
gateDecision: result.gate?.decision ?? null,
|
|
322
|
+
thresholds: {
|
|
323
|
+
requireCorpus: false,
|
|
324
|
+
requireHoldout: Boolean(result.gate),
|
|
325
|
+
minHoldoutRuns: result.gate ? 1 : 0,
|
|
326
|
+
minSearchRuns: 1,
|
|
327
|
+
minMeanScore: options.minScore ?? 0.7
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
const release = {
|
|
331
|
+
id: stableId("krel", `${result.promotedVariant.id}:${options.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()}`),
|
|
332
|
+
candidateId: result.promotedVariant.id,
|
|
333
|
+
createdAt: options.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
334
|
+
promoted: scorecard.status !== "fail" && result.promotedVariant.id === result.searchBestVariant.id,
|
|
335
|
+
scorecard,
|
|
336
|
+
runRecordIds: runRecords.map((record) => record.runId)
|
|
337
|
+
};
|
|
338
|
+
return {
|
|
339
|
+
release,
|
|
340
|
+
scorecard,
|
|
341
|
+
candidateRuns: result.gate?.candidateRuns ?? [],
|
|
342
|
+
baselineRuns: result.gate?.baselineRuns ?? []
|
|
343
|
+
};
|
|
344
|
+
}
|
|
182
345
|
export {
|
|
346
|
+
FileSystemKbStore,
|
|
347
|
+
KnowledgeBaseCandidateSchema,
|
|
348
|
+
KnowledgeEventSchema,
|
|
349
|
+
KnowledgeGraphEdgeSchema,
|
|
350
|
+
KnowledgeGraphNodeSchema,
|
|
351
|
+
KnowledgeIndexSchema,
|
|
352
|
+
KnowledgePageSchema,
|
|
353
|
+
MemoryKbStore,
|
|
354
|
+
SourceAnchorSchema,
|
|
355
|
+
SourceRecordSchema,
|
|
183
356
|
WIKILINK_REGEX,
|
|
184
357
|
addSourcePath,
|
|
185
358
|
applyKnowledgeWriteBlocks,
|
|
@@ -187,12 +360,15 @@ export {
|
|
|
187
360
|
buildKnowledgeGraph,
|
|
188
361
|
buildKnowledgeIndex,
|
|
189
362
|
chunkMarkdown,
|
|
363
|
+
createKnowledgeEvent,
|
|
364
|
+
createLocalDiscoveryDispatcher,
|
|
190
365
|
explainKnowledgeTarget,
|
|
191
366
|
extractWikilinks,
|
|
192
367
|
formatFrontmatter,
|
|
193
368
|
initKnowledgeBase,
|
|
194
369
|
inspectKnowledgeIndex,
|
|
195
370
|
isSafeKnowledgePath,
|
|
371
|
+
knowledgeReleaseReportFromOptimization,
|
|
196
372
|
knowledgeVariantFromCandidate,
|
|
197
373
|
layoutFor,
|
|
198
374
|
lintKnowledgeIndex,
|
|
@@ -212,6 +388,7 @@ export {
|
|
|
212
388
|
stripFrontmatter,
|
|
213
389
|
textSourceAdapter,
|
|
214
390
|
tokenizeQuery,
|
|
391
|
+
validateKnowledgeIndex,
|
|
215
392
|
writeJson,
|
|
216
393
|
writeKnowledgeIndex,
|
|
217
394
|
writeSourceRegistry
|