@agent-wiki/mcp 0.17.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +7 -0
- package/README.md +171 -0
- package/architecture.svg +58 -0
- package/dist/atlassian.d.ts +63 -0
- package/dist/atlassian.d.ts.map +1 -0
- package/dist/atlassian.js +596 -0
- package/dist/atlassian.js.map +1 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +391 -0
- package/dist/cli.js.map +1 -0
- package/dist/cobol/__tests__/call-boundary-lineage.test.d.ts +2 -0
- package/dist/cobol/__tests__/call-boundary-lineage.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/call-boundary-lineage.test.js +505 -0
- package/dist/cobol/__tests__/call-boundary-lineage.test.js.map +1 -0
- package/dist/cobol/__tests__/code-analysis.test.d.ts +2 -0
- package/dist/cobol/__tests__/code-analysis.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/code-analysis.test.js +465 -0
- package/dist/cobol/__tests__/code-analysis.test.js.map +1 -0
- package/dist/cobol/__tests__/db2-table-lineage.test.d.ts +2 -0
- package/dist/cobol/__tests__/db2-table-lineage.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/db2-table-lineage.test.js +182 -0
- package/dist/cobol/__tests__/db2-table-lineage.test.js.map +1 -0
- package/dist/cobol/__tests__/evidence-mapping.test.d.ts +2 -0
- package/dist/cobol/__tests__/evidence-mapping.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/evidence-mapping.test.js +49 -0
- package/dist/cobol/__tests__/evidence-mapping.test.js.map +1 -0
- package/dist/cobol/__tests__/extractors.test.d.ts +2 -0
- package/dist/cobol/__tests__/extractors.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/extractors.test.js +189 -0
- package/dist/cobol/__tests__/extractors.test.js.map +1 -0
- package/dist/cobol/__tests__/field-lineage.test.d.ts +2 -0
- package/dist/cobol/__tests__/field-lineage.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/field-lineage.test.js +329 -0
- package/dist/cobol/__tests__/field-lineage.test.js.map +1 -0
- package/dist/cobol/__tests__/graph.test.d.ts +2 -0
- package/dist/cobol/__tests__/graph.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/graph.test.js +456 -0
- package/dist/cobol/__tests__/graph.test.js.map +1 -0
- package/dist/cobol/__tests__/integration.test.d.ts +2 -0
- package/dist/cobol/__tests__/integration.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/integration.test.js +971 -0
- package/dist/cobol/__tests__/integration.test.js.map +1 -0
- package/dist/cobol/__tests__/lexer.test.d.ts +2 -0
- package/dist/cobol/__tests__/lexer.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/lexer.test.js +111 -0
- package/dist/cobol/__tests__/lexer.test.js.map +1 -0
- package/dist/cobol/__tests__/parser.test.d.ts +2 -0
- package/dist/cobol/__tests__/parser.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/parser.test.js +180 -0
- package/dist/cobol/__tests__/parser.test.js.map +1 -0
- package/dist/cobol/__tests__/variable-tracer.test.d.ts +2 -0
- package/dist/cobol/__tests__/variable-tracer.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/variable-tracer.test.js +256 -0
- package/dist/cobol/__tests__/variable-tracer.test.js.map +1 -0
- package/dist/cobol/__tests__/wiki-gen.test.d.ts +2 -0
- package/dist/cobol/__tests__/wiki-gen.test.d.ts.map +1 -0
- package/dist/cobol/__tests__/wiki-gen.test.js +76 -0
- package/dist/cobol/__tests__/wiki-gen.test.js.map +1 -0
- package/dist/cobol/call-boundary-lineage.d.ts +49 -0
- package/dist/cobol/call-boundary-lineage.d.ts.map +1 -0
- package/dist/cobol/call-boundary-lineage.js +159 -0
- package/dist/cobol/call-boundary-lineage.js.map +1 -0
- package/dist/cobol/db2-table-lineage.d.ts +45 -0
- package/dist/cobol/db2-table-lineage.d.ts.map +1 -0
- package/dist/cobol/db2-table-lineage.js +127 -0
- package/dist/cobol/db2-table-lineage.js.map +1 -0
- package/dist/cobol/evidence-mapping.d.ts +31 -0
- package/dist/cobol/evidence-mapping.d.ts.map +1 -0
- package/dist/cobol/evidence-mapping.js +27 -0
- package/dist/cobol/evidence-mapping.js.map +1 -0
- package/dist/cobol/extractors.d.ts +88 -0
- package/dist/cobol/extractors.d.ts.map +1 -0
- package/dist/cobol/extractors.js +297 -0
- package/dist/cobol/extractors.js.map +1 -0
- package/dist/cobol/field-lineage.d.ts +101 -0
- package/dist/cobol/field-lineage.d.ts.map +1 -0
- package/dist/cobol/field-lineage.js +603 -0
- package/dist/cobol/field-lineage.js.map +1 -0
- package/dist/cobol/graph.d.ts +182 -0
- package/dist/cobol/graph.d.ts.map +1 -0
- package/dist/cobol/graph.js +453 -0
- package/dist/cobol/graph.js.map +1 -0
- package/dist/cobol/lexer.d.ts +15 -0
- package/dist/cobol/lexer.d.ts.map +1 -0
- package/dist/cobol/lexer.js +251 -0
- package/dist/cobol/lexer.js.map +1 -0
- package/dist/cobol/parser.d.ts +13 -0
- package/dist/cobol/parser.d.ts.map +1 -0
- package/dist/cobol/parser.js +584 -0
- package/dist/cobol/parser.js.map +1 -0
- package/dist/cobol/plugin.d.ts +23 -0
- package/dist/cobol/plugin.d.ts.map +1 -0
- package/dist/cobol/plugin.js +507 -0
- package/dist/cobol/plugin.js.map +1 -0
- package/dist/cobol/types.d.ts +73 -0
- package/dist/cobol/types.d.ts.map +1 -0
- package/dist/cobol/types.js +9 -0
- package/dist/cobol/types.js.map +1 -0
- package/dist/cobol/variable-tracer.d.ts +31 -0
- package/dist/cobol/variable-tracer.d.ts.map +1 -0
- package/dist/cobol/variable-tracer.js +361 -0
- package/dist/cobol/variable-tracer.js.map +1 -0
- package/dist/cobol/wiki-gen.d.ts +18 -0
- package/dist/cobol/wiki-gen.d.ts.map +1 -0
- package/dist/cobol/wiki-gen.js +222 -0
- package/dist/cobol/wiki-gen.js.map +1 -0
- package/dist/code-analysis.d.ts +160 -0
- package/dist/code-analysis.d.ts.map +1 -0
- package/dist/code-analysis.js +53 -0
- package/dist/code-analysis.js.map +1 -0
- package/dist/evidence-search.d.ts +43 -0
- package/dist/evidence-search.d.ts.map +1 -0
- package/dist/evidence-search.js +112 -0
- package/dist/evidence-search.js.map +1 -0
- package/dist/evidence-search.test.d.ts +2 -0
- package/dist/evidence-search.test.d.ts.map +1 -0
- package/dist/evidence-search.test.js +98 -0
- package/dist/evidence-search.test.js.map +1 -0
- package/dist/evidence.d.ts +32 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +16 -0
- package/dist/evidence.js.map +1 -0
- package/dist/evidence.test.d.ts +2 -0
- package/dist/evidence.test.d.ts.map +1 -0
- package/dist/evidence.test.js +51 -0
- package/dist/evidence.test.js.map +1 -0
- package/dist/extraction.d.ts +40 -0
- package/dist/extraction.d.ts.map +1 -0
- package/dist/extraction.js +283 -0
- package/dist/extraction.js.map +1 -0
- package/dist/extraction.test.d.ts +5 -0
- package/dist/extraction.test.d.ts.map +1 -0
- package/dist/extraction.test.js +137 -0
- package/dist/extraction.test.js.map +1 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +35 -0
- package/dist/index.js.map +1 -0
- package/dist/queue.d.ts +52 -0
- package/dist/queue.d.ts.map +1 -0
- package/dist/queue.js +139 -0
- package/dist/queue.js.map +1 -0
- package/dist/queue.test.d.ts +2 -0
- package/dist/queue.test.d.ts.map +1 -0
- package/dist/queue.test.js +161 -0
- package/dist/queue.test.js.map +1 -0
- package/dist/search.d.ts +163 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +653 -0
- package/dist/search.js.map +1 -0
- package/dist/search.test.d.ts +6 -0
- package/dist/search.test.d.ts.map +1 -0
- package/dist/search.test.js +551 -0
- package/dist/search.test.js.map +1 -0
- package/dist/server.d.ts +33 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2530 -0
- package/dist/server.js.map +1 -0
- package/dist/server.test.d.ts +8 -0
- package/dist/server.test.d.ts.map +1 -0
- package/dist/server.test.js +2397 -0
- package/dist/server.test.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/dist/wiki.d.ts +496 -0
- package/dist/wiki.d.ts.map +1 -0
- package/dist/wiki.js +2677 -0
- package/dist/wiki.js.map +1 -0
- package/dist/wiki.test.d.ts +8 -0
- package/dist/wiki.test.d.ts.map +1 -0
- package/dist/wiki.test.js +1881 -0
- package/dist/wiki.test.js.map +1 -0
- package/docs/code-analysis-plugins.md +169 -0
- package/docs/configuration.md +135 -0
- package/docs/diagrams/cobol-analysis-flow.png +0 -0
- package/docs/diagrams/cobol-analysis-flow.svg +156 -0
- package/docs/evidence-envelope.md +176 -0
- package/docs/graph-1.gif +0 -0
- package/docs/legacy-code-knowledge-compiler-prd.md +511 -0
- package/docs/product-direction.md +120 -0
- package/docs/request-optimization.md +201 -0
- package/docs/search.md +266 -0
- package/docs/tools.md +269 -0
- package/graph-viewer/dist/cli.d.ts +3 -0
- package/graph-viewer/dist/cli.d.ts.map +1 -0
- package/graph-viewer/dist/cli.js +97 -0
- package/graph-viewer/dist/cli.js.map +1 -0
- package/graph-viewer/dist/graph.d.ts +14 -0
- package/graph-viewer/dist/graph.d.ts.map +1 -0
- package/graph-viewer/dist/graph.js +96 -0
- package/graph-viewer/dist/graph.js.map +1 -0
- package/graph-viewer/dist/index.d.ts +6 -0
- package/graph-viewer/dist/index.d.ts.map +1 -0
- package/graph-viewer/dist/index.js +4 -0
- package/graph-viewer/dist/index.js.map +1 -0
- package/graph-viewer/dist/parse.d.ts +10 -0
- package/graph-viewer/dist/parse.d.ts.map +1 -0
- package/graph-viewer/dist/parse.js +62 -0
- package/graph-viewer/dist/parse.js.map +1 -0
- package/graph-viewer/dist/server.d.ts +15 -0
- package/graph-viewer/dist/server.d.ts.map +1 -0
- package/graph-viewer/dist/server.js +168 -0
- package/graph-viewer/dist/server.js.map +1 -0
- package/graph-viewer/dist/types.d.ts +48 -0
- package/graph-viewer/dist/types.d.ts.map +1 -0
- package/graph-viewer/dist/types.js +2 -0
- package/graph-viewer/dist/types.js.map +1 -0
- package/graph-viewer/public/app.js +525 -0
- package/graph-viewer/public/index.html +68 -0
- package/graph-viewer/public/style.css +68 -0
- package/package.json +73 -0
- package/skills/aceclaw/SKILL.md +173 -0
- package/skills/agent-wiki/SKILL.md +184 -0
- package/skills/agent-wiki/references/tools-reference.md +368 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,2530 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Server — Exposes Agent Wiki as tools to any MCP-compatible agent.
|
|
3
|
+
*
|
|
4
|
+
* Architecture (Karpathy LLM Wiki, upgraded):
|
|
5
|
+
*
|
|
6
|
+
* raw/ → Immutable source layer (raw_add, raw_list, raw_read, raw_verify)
|
|
7
|
+
* wiki/ → Mutable knowledge layer (read, write, delete, search, lint, synthesize)
|
|
8
|
+
*
|
|
9
|
+
* The agent IS the LLM. This server is pure data operations.
|
|
10
|
+
*/
|
|
11
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
12
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
13
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
14
|
+
import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
15
|
+
import { buildSearchEnvelope, downgradeForReadPage } from "./evidence-search.js";
|
|
16
|
+
import { join, resolve, basename, extname } from "node:path";
|
|
17
|
+
import { Wiki, splitSections, buildToc, findSectionByHeading, matchSimpleGlob, safePath } from "./wiki.js";
|
|
18
|
+
import { extractDocument, chunkSegments, guessMime } from "./extraction.js";
|
|
19
|
+
import matter from "gray-matter";
|
|
20
|
+
import { VERSION } from "./version.js";
|
|
21
|
+
import { RequestQueue } from "./queue.js";
|
|
22
|
+
import { registerPlugin, getPlugin, getPluginForFile, listPlugins, summarizeModel } from "./code-analysis.js";
|
|
23
|
+
import { cobolPlugin } from "./cobol/plugin.js";
|
|
24
|
+
import { canonicalNodeId, deserializeGraph, displayLabel, graphEdgesFrom, graphImpactOf } from "./cobol/graph.js";
|
|
25
|
+
// Register built-in plugins
|
|
26
|
+
registerPlugin(cobolPlugin);
|
|
27
|
+
export function createServer(wikiPath, workspace) {
|
|
28
|
+
const wiki = new Wiki(wikiPath, workspace);
|
|
29
|
+
const server = new Server({ name: "agent-wiki", version: VERSION }, { capabilities: { tools: {} } });
|
|
30
|
+
// ── List Tools ──────────────────────────────────────────────
|
|
31
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
32
|
+
tools: [
|
|
33
|
+
// ═══════════════════════════════════════════════════════
|
|
34
|
+
// RAW LAYER — Immutable source documents
|
|
35
|
+
// ═══════════════════════════════════════════════════════
|
|
36
|
+
{
|
|
37
|
+
name: "raw_ingest",
|
|
38
|
+
description: "Ingest raw source documents into the knowledge base. Select `mode` to control the ingestion method:\n" +
|
|
39
|
+
"- `add`: Add a local file or content string (immutable, SHA-256 verified). Supports directory imports. Single images (<10MB) returned inline — you MUST immediately call wiki_write to describe them.\n" +
|
|
40
|
+
"- `fetch`: Download a file from a URL into raw/ (arXiv abstract URLs auto-converted to PDF). Single images returned inline — you MUST immediately call wiki_write to describe them.\n" +
|
|
41
|
+
"- `import_confluence`: Recursively import Confluence pages with attachments and hierarchy. Supports both Cloud (`*.atlassian.net/wiki/...`) and Server / Data Center (`{host}/spaces/...`). Defaults to reading the CONFLUENCE_API_TOKEN env var; pass `auth_env` to point at any other variable. Token format accepted: `email:api-token` (Cloud Basic), `Bearer <pat>` (explicit), or a bare PAT (Bearer prefix added automatically).\n" +
|
|
42
|
+
"- `import_jira`: Import a Jira issue with comments, attachments, and linked issues. Supports both Cloud and Server / Data Center; auto-falls-back to REST API v2 on older Server / DC. Defaults to reading the JIRA_API_TOKEN env var; pass `auth_env` to point at any other variable. Token format accepted: `email:api-token` (Cloud Basic), `Bearer <pat>` (explicit), or a bare PAT (Bearer prefix added automatically).",
|
|
43
|
+
inputSchema: {
|
|
44
|
+
type: "object",
|
|
45
|
+
properties: {
|
|
46
|
+
mode: {
|
|
47
|
+
type: "string",
|
|
48
|
+
enum: ["add", "fetch", "import_confluence", "import_jira"],
|
|
49
|
+
description: "Ingestion mode: add (local file/content), fetch (URL download), import_confluence (Confluence pages), import_jira (Jira issues)",
|
|
50
|
+
},
|
|
51
|
+
filename: {
|
|
52
|
+
type: "string",
|
|
53
|
+
description: "[add] Filename in raw/ (e.g. 'paper.pdf'). For directory imports, becomes subdirectory prefix (e.g. 'my-docs').",
|
|
54
|
+
},
|
|
55
|
+
content: {
|
|
56
|
+
type: "string",
|
|
57
|
+
description: "[add] File content as string. Either content or source_path is required.",
|
|
58
|
+
},
|
|
59
|
+
source_path: {
|
|
60
|
+
type: "string",
|
|
61
|
+
description: "[add] Absolute path to local file or directory to copy into raw/. If directory, all files imported recursively. Either content or source_path is required.",
|
|
62
|
+
},
|
|
63
|
+
source_url: {
|
|
64
|
+
type: "string",
|
|
65
|
+
description: "[add/fetch] Original URL where the document was downloaded from",
|
|
66
|
+
},
|
|
67
|
+
description: {
|
|
68
|
+
type: "string",
|
|
69
|
+
description: "[add/fetch] Brief description of what this source contains",
|
|
70
|
+
},
|
|
71
|
+
tags: {
|
|
72
|
+
type: "array",
|
|
73
|
+
items: { type: "string" },
|
|
74
|
+
description: "[add/fetch] Tags for categorization",
|
|
75
|
+
},
|
|
76
|
+
auto_version: {
|
|
77
|
+
type: "boolean",
|
|
78
|
+
description: "[add] If true and file already exists, create a versioned copy (e.g. report_v2.xlsx) instead of failing. Default: false.",
|
|
79
|
+
},
|
|
80
|
+
pattern: {
|
|
81
|
+
type: "string",
|
|
82
|
+
description: "[add] File pattern filter for directory imports (e.g. '*.html', '*.{html,css}'). Ignored for single files.",
|
|
83
|
+
},
|
|
84
|
+
url: {
|
|
85
|
+
type: "string",
|
|
86
|
+
description: "[fetch] URL to download from. arXiv abs URLs auto-converted to PDF links. [import_confluence] Confluence page URL. [import_jira] Jira issue URL.",
|
|
87
|
+
},
|
|
88
|
+
recursive: {
|
|
89
|
+
type: "boolean",
|
|
90
|
+
description: "[import_confluence] Import child pages recursively (default: false)",
|
|
91
|
+
},
|
|
92
|
+
depth: {
|
|
93
|
+
type: "number",
|
|
94
|
+
description: "[import_confluence] Max recursion depth (-1 = unlimited, default: 50 when recursive=true)",
|
|
95
|
+
},
|
|
96
|
+
auth_env: {
|
|
97
|
+
type: "string",
|
|
98
|
+
description: "[import_confluence] Auth env var name (default: CONFLUENCE_API_TOKEN). [import_jira] Auth env var name (default: JIRA_API_TOKEN)",
|
|
99
|
+
},
|
|
100
|
+
include_comments: {
|
|
101
|
+
type: "boolean",
|
|
102
|
+
description: "[import_jira] Include issue comments (default: true)",
|
|
103
|
+
},
|
|
104
|
+
include_attachments: {
|
|
105
|
+
type: "boolean",
|
|
106
|
+
description: "[import_jira] Download attachments (default: true)",
|
|
107
|
+
},
|
|
108
|
+
include_links: {
|
|
109
|
+
type: "boolean",
|
|
110
|
+
description: "[import_jira] Import linked issues (default: true)",
|
|
111
|
+
},
|
|
112
|
+
link_depth: {
|
|
113
|
+
type: "number",
|
|
114
|
+
description: "[import_jira] Levels of linked issues to follow (default: 1)",
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
required: ["mode"],
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: "raw_versions",
|
|
122
|
+
description: "List all versions of a raw file, sorted by version number, with the latest version marked. Given a base filename (e.g. 'report.xlsx'), returns all matching versions (report.xlsx as v1, report_v2.xlsx, report_v3.xlsx, etc.) with metadata and a 'latest' field pointing to the newest file.",
|
|
123
|
+
inputSchema: {
|
|
124
|
+
type: "object",
|
|
125
|
+
properties: {
|
|
126
|
+
filename: {
|
|
127
|
+
type: "string",
|
|
128
|
+
description: "Base filename to list versions of (e.g. 'report.xlsx')",
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
required: ["filename"],
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
name: "raw_list",
|
|
136
|
+
description: "List all raw source documents with metadata (path, source URL, download time, hash, size).",
|
|
137
|
+
inputSchema: {
|
|
138
|
+
type: "object",
|
|
139
|
+
properties: {},
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
name: "raw_coverage",
|
|
144
|
+
description: "Report which raw/ files are not yet referenced by any wiki page. Answers 'what should I compile next?' — returns uncovered files sorted by recency/size, plus overall coverage ratio. Matches frontmatter 'sources' and inline 'raw/...' body references. Parsed artifacts (raw/parsed/) are excluded.",
|
|
145
|
+
inputSchema: {
|
|
146
|
+
type: "object",
|
|
147
|
+
properties: {
|
|
148
|
+
limit: {
|
|
149
|
+
type: "number",
|
|
150
|
+
description: "Max uncovered entries to return. Default: 50.",
|
|
151
|
+
},
|
|
152
|
+
sort: {
|
|
153
|
+
type: "string",
|
|
154
|
+
enum: ["newest", "oldest", "largest"],
|
|
155
|
+
description: "Sort order for uncovered entries. Default: 'newest'.",
|
|
156
|
+
},
|
|
157
|
+
tag: {
|
|
158
|
+
type: "string",
|
|
159
|
+
description: "Only consider raw files with this tag.",
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
name: "raw_read",
|
|
166
|
+
description: "Read a raw source document's content and metadata. Raw files are immutable — this is read-only. Text/SVG files return content as string; document files (PDF, DOCX, XLSX, PPTX) have text extracted automatically; other binary files (images, etc.) return metadata only.\n\nPagination by format:\n- PDF: use 'pages' for page ranges (e.g. '1-5')\n- PPTX: use 'pages' for slide ranges (e.g. '1-10')\n- XLSX: use 'sheet' to read a specific sheet; response always includes 'sheet_names'\n- DOCX / text: use 'offset' + 'limit' for line-based pagination (default limit: 200)\n\nFor large documents, paginate rather than reading all at once.",
|
|
167
|
+
inputSchema: {
|
|
168
|
+
type: "object",
|
|
169
|
+
properties: {
|
|
170
|
+
filename: {
|
|
171
|
+
type: "string",
|
|
172
|
+
description: "Filename relative to raw/ (e.g. 'article-yolo.md')",
|
|
173
|
+
},
|
|
174
|
+
pages: {
|
|
175
|
+
type: "string",
|
|
176
|
+
description: "Page/slide range (e.g. '1-5', '3', '1-3,7-10'). Applies to PDF and PPTX. Omit to read all.",
|
|
177
|
+
},
|
|
178
|
+
sheet: {
|
|
179
|
+
type: "string",
|
|
180
|
+
description: "Sheet name for XLSX files. Omit to read all sheets (response always includes sheet_names list).",
|
|
181
|
+
},
|
|
182
|
+
offset: {
|
|
183
|
+
type: "number",
|
|
184
|
+
description: "Line offset for paginating text/DOCX files. Default: 0.",
|
|
185
|
+
},
|
|
186
|
+
limit: {
|
|
187
|
+
type: "number",
|
|
188
|
+
description: "Max lines to return for text/DOCX pagination. Default: 200, max: 500.",
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
required: ["filename"],
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
// raw_verify removed — wiki_lint already includes SHA-256 integrity checks
|
|
195
|
+
// raw_fetch, raw_import_confluence, raw_import_jira folded into raw_ingest
|
|
196
|
+
// ═══════════════════════════════════════════════════════
|
|
197
|
+
// WIKI LAYER — Mutable compiled knowledge
|
|
198
|
+
// ═══════════════════════════════════════════════════════
|
|
199
|
+
{
|
|
200
|
+
name: "wiki_read",
|
|
201
|
+
description: "Read one or more wiki pages. Single page: pass `page`. Multiple pages: pass `pages` array — reads all in one request, saving N-1 round trips. " +
|
|
202
|
+
"RECOMMENDED WORKFLOW: (1) call without 'section' to get the TOC for large pages, " +
|
|
203
|
+
"(2) use wiki_search 'section' field to jump directly to the relevant heading, " +
|
|
204
|
+
"(3) call with 'section' to read only that part. " +
|
|
205
|
+
"Large pages without 'section' are truncated at 200 lines — check 'truncated' and 'toc' in the response.",
|
|
206
|
+
inputSchema: {
|
|
207
|
+
type: "object",
|
|
208
|
+
properties: {
|
|
209
|
+
page: {
|
|
210
|
+
type: "string",
|
|
211
|
+
description: "Page path relative to wiki/ (e.g. 'concept-gil.md'). Use for single-page reads.",
|
|
212
|
+
},
|
|
213
|
+
pages: {
|
|
214
|
+
type: "array",
|
|
215
|
+
items: { type: "string" },
|
|
216
|
+
description: "Array of page paths for multi-page reads. Returns an array of results in one request.",
|
|
217
|
+
},
|
|
218
|
+
section: {
|
|
219
|
+
type: "string",
|
|
220
|
+
description: "Heading to read (e.g. '## Installation'). Case-insensitive partial match. Returns that section and its sub-sections only. Use the 'section' field from wiki_search results to navigate directly.",
|
|
221
|
+
},
|
|
222
|
+
offset: {
|
|
223
|
+
type: "number",
|
|
224
|
+
description: "First line to return, 0-indexed (default: 0). Fallback for line-based paging when section navigation is insufficient.",
|
|
225
|
+
},
|
|
226
|
+
limit: {
|
|
227
|
+
type: "number",
|
|
228
|
+
description: "Max lines to return (default: 200, max: 500).",
|
|
229
|
+
},
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
name: "wiki_write",
|
|
235
|
+
description: "Create or update a wiki page. Content should include YAML frontmatter (title, type, tags, sources) and Markdown body. Timestamps (created/updated) are auto-managed. Auto-routes root-level pages to matching topic subdirectories (via frontmatter `topic` field or tag matching). Auto-links: scans body for mentions of existing page titles and injects [[slug|text]] links automatically (skips code blocks, existing links, URLs). Wiki pages are MUTABLE — they represent compiled knowledge that improves over time. " +
|
|
236
|
+
"Set `return_content: true` to include the final written content in the response — eliminates the follow-up wiki_read call in write-then-reference workflows.",
|
|
237
|
+
inputSchema: {
|
|
238
|
+
type: "object",
|
|
239
|
+
properties: {
|
|
240
|
+
page: {
|
|
241
|
+
type: "string",
|
|
242
|
+
description: "Page path relative to wiki/",
|
|
243
|
+
},
|
|
244
|
+
content: {
|
|
245
|
+
type: "string",
|
|
246
|
+
description: "Full page content including YAML frontmatter and Markdown body",
|
|
247
|
+
},
|
|
248
|
+
source: {
|
|
249
|
+
type: "string",
|
|
250
|
+
description: "Provenance — why this write is happening",
|
|
251
|
+
},
|
|
252
|
+
return_content: {
|
|
253
|
+
type: "boolean",
|
|
254
|
+
description: "If true, include the final written content in the response. Eliminates a follow-up wiki_read call. Default: false.",
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
required: ["page", "content"],
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
name: "wiki_delete",
|
|
262
|
+
description: "Delete a wiki page. Cannot delete system pages (index.md, log.md, timeline.md).",
|
|
263
|
+
inputSchema: {
|
|
264
|
+
type: "object",
|
|
265
|
+
properties: {
|
|
266
|
+
page: {
|
|
267
|
+
type: "string",
|
|
268
|
+
description: "Page path relative to wiki/",
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
required: ["page"],
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
name: "wiki_list",
|
|
276
|
+
description: "List all wiki pages, optionally filtered by entity type or tag.",
|
|
277
|
+
inputSchema: {
|
|
278
|
+
type: "object",
|
|
279
|
+
properties: {
|
|
280
|
+
type: {
|
|
281
|
+
type: "string",
|
|
282
|
+
description: "Filter by entity type (person, concept, event, artifact, code, comparison, summary, how-to, note, synthesis)",
|
|
283
|
+
},
|
|
284
|
+
tag: {
|
|
285
|
+
type: "string",
|
|
286
|
+
description: "Filter by tag",
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
},
|
|
291
|
+
{
|
|
292
|
+
name: "wiki_search",
|
|
293
|
+
description: "Full-text keyword search across all wiki pages. Returns paths, scores, and snippets sorted by relevance. " +
|
|
294
|
+
"Uses BM25 by default; switches to hybrid BM25+vector re-ranking when `search.hybrid: true` is set in " +
|
|
295
|
+
".agent-wiki.yaml (requires wiki_admin action:rebuild to build the vector index first). " +
|
|
296
|
+
"Set include_content=true for simple inline content (with optional inline_budget cap). " +
|
|
297
|
+
"Set read_top_n to additionally read the top N unique matching pages (deduplicated) — enables combined search+read in one call; " +
|
|
298
|
+
"returns a `pages` array with full content and `nextReads` for unread matches. " +
|
|
299
|
+
"Use `type` or `tags` to narrow results without a separate wiki_list call. " +
|
|
300
|
+
"When no results are found, returns a `knowledge_gap` field with a suggested page slug, title, type, and tags — use it to decide what to create with wiki_write.",
|
|
301
|
+
inputSchema: {
|
|
302
|
+
type: "object",
|
|
303
|
+
properties: {
|
|
304
|
+
query: {
|
|
305
|
+
type: "string",
|
|
306
|
+
description: "Search query (keywords)",
|
|
307
|
+
},
|
|
308
|
+
limit: {
|
|
309
|
+
type: "number",
|
|
310
|
+
description: "Max results (default: 10)",
|
|
311
|
+
},
|
|
312
|
+
type: {
|
|
313
|
+
type: "string",
|
|
314
|
+
description: "Filter results to a specific entity type (person, concept, event, artifact, code, comparison, summary, how-to, note, synthesis). Applied after BM25 ranking.",
|
|
315
|
+
},
|
|
316
|
+
tags: {
|
|
317
|
+
type: "array",
|
|
318
|
+
items: { type: "string" },
|
|
319
|
+
description: "Filter results to pages that have at least one of these tags. Applied after BM25 ranking.",
|
|
320
|
+
},
|
|
321
|
+
include_content: {
|
|
322
|
+
type: "boolean",
|
|
323
|
+
description: "If true, include page content inline in results. When a section matched, returns that section; otherwise returns first 200 lines. Saves a follow-up batch read. Default: false.",
|
|
324
|
+
},
|
|
325
|
+
inline_budget: {
|
|
326
|
+
type: "number",
|
|
327
|
+
description: "Max total characters of inlined content across all results (only with include_content=true). Greedy — top-scoring results get content first; lower-scoring ones fall back to snippet-only when budget is exhausted. Omit for no limit.",
|
|
328
|
+
},
|
|
329
|
+
read_top_n: {
|
|
330
|
+
type: "number",
|
|
331
|
+
description: "How many unique top-scoring pages to read in full (default: unset). When set, activates combined search+read mode: deduplicates search hits, reads up to N unique pages, and returns a `pages` array alongside `results`. Max: 10.",
|
|
332
|
+
},
|
|
333
|
+
section: {
|
|
334
|
+
type: "string",
|
|
335
|
+
description: "Section heading filter applied to all page reads when read_top_n is set (e.g. '## Installation'). Case-insensitive partial match.",
|
|
336
|
+
},
|
|
337
|
+
per_page_limit: {
|
|
338
|
+
type: "number",
|
|
339
|
+
description: "Max lines per page when read_top_n is set (default: 200, max: 500). Pages exceeding this are truncated with metadata.",
|
|
340
|
+
},
|
|
341
|
+
include_toc: {
|
|
342
|
+
type: "boolean",
|
|
343
|
+
description: "Include table of contents for truncated pages when read_top_n is set (default: false).",
|
|
344
|
+
},
|
|
345
|
+
},
|
|
346
|
+
required: ["query"],
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
// wiki_search_read folded into wiki_search (read_top_n parameter)
|
|
350
|
+
{
|
|
351
|
+
name: "wiki_admin",
|
|
352
|
+
description: "Wiki administration and maintenance. Select `action` to control behavior:\n" +
|
|
353
|
+
"- `init`: Initialize a new knowledge base — creates wiki/, raw/, schemas/ directories and default templates.\n" +
|
|
354
|
+
"- `config`: Show current workspace configuration: directories, lint settings, search settings, entity templates.\n" +
|
|
355
|
+
"- `rebuild`: Rebuild index.md, timeline.md, code knowledge graphs, and optionally the vector index (when search.hybrid is enabled).\n" +
|
|
356
|
+
"- `lint`: Run comprehensive health checks: contradictions, orphan pages, broken links, raw file integrity (SHA-256), synthesis page integrity. Set apply_fixes=true to auto-repair fixable issues.",
|
|
357
|
+
inputSchema: {
|
|
358
|
+
type: "object",
|
|
359
|
+
properties: {
|
|
360
|
+
action: {
|
|
361
|
+
type: "string",
|
|
362
|
+
enum: ["init", "config", "rebuild", "lint"],
|
|
363
|
+
description: "Administration action to perform",
|
|
364
|
+
},
|
|
365
|
+
path: {
|
|
366
|
+
type: "string",
|
|
367
|
+
description: "[init] Config root — where .agent-wiki.yaml is created (default: current directory)",
|
|
368
|
+
},
|
|
369
|
+
workspace: {
|
|
370
|
+
type: "string",
|
|
371
|
+
description: "[init] Separate workspace directory for wiki/, raw/, schemas/. If omitted, data goes in path.",
|
|
372
|
+
},
|
|
373
|
+
apply_fixes: {
|
|
374
|
+
type: "boolean",
|
|
375
|
+
description: "[lint] If true, automatically fix auto-fixable issues (missing frontmatter → inject title/type/tags). Default: false.",
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
required: ["action"],
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
// wiki_log removed — use wiki_read("log.md") instead
|
|
382
|
+
// wiki_lint, wiki_init, wiki_config, wiki_rebuild folded into wiki_admin
|
|
383
|
+
// wiki_classify removed — wiki_write auto-classifies internally
|
|
384
|
+
// wiki_synthesize removed — agent can call wiki_read on multiple pages directly
|
|
385
|
+
// ═══════════════════════════════════════════════════════
|
|
386
|
+
// BATCH — Combine multiple tool calls into one request
|
|
387
|
+
// ═══════════════════════════════════════════════════════
|
|
388
|
+
{
|
|
389
|
+
name: "batch",
|
|
390
|
+
description: "Execute multiple tool calls in a single request. Reduces tool-call count for LLM subscriptions " +
|
|
391
|
+
"that bill per-request (e.g. GitHub Copilot). Supports ANY combination of tools — " +
|
|
392
|
+
"e.g. read 5 wiki pages, write 3 pages, add 2 raw files, search, all in one call. " +
|
|
393
|
+
"Wiki index rebuild is automatically deduplicated (runs once at the end, not per-write). " +
|
|
394
|
+
"Each operation is independent — one failure does not abort the batch. Nested batch calls are not allowed.",
|
|
395
|
+
inputSchema: {
|
|
396
|
+
type: "object",
|
|
397
|
+
properties: {
|
|
398
|
+
operations: {
|
|
399
|
+
type: "array",
|
|
400
|
+
items: {
|
|
401
|
+
type: "object",
|
|
402
|
+
properties: {
|
|
403
|
+
tool: {
|
|
404
|
+
type: "string",
|
|
405
|
+
description: "Tool name (e.g. 'wiki_read', 'wiki_write', 'raw_add', 'raw_read', 'wiki_search')",
|
|
406
|
+
},
|
|
407
|
+
args: {
|
|
408
|
+
type: "object",
|
|
409
|
+
description: "Tool arguments — same as calling the tool individually",
|
|
410
|
+
},
|
|
411
|
+
},
|
|
412
|
+
required: ["tool"],
|
|
413
|
+
},
|
|
414
|
+
description: "Array of operations to execute sequentially",
|
|
415
|
+
},
|
|
416
|
+
},
|
|
417
|
+
required: ["operations"],
|
|
418
|
+
},
|
|
419
|
+
},
|
|
420
|
+
// ═══════════════════════════════════════════════════════
|
|
421
|
+
// KNOWLEDGE INGESTION — Batch import, extract, chunk, pack
|
|
422
|
+
// ═══════════════════════════════════════════════════════
|
|
423
|
+
{
|
|
424
|
+
name: "knowledge_ingest",
|
|
425
|
+
description: "Knowledge ingestion pipeline. Select `mode` to control behavior:\n" +
|
|
426
|
+
"- `batch`: Batch import, extract, chunk, and pack source documents into digest packs. " +
|
|
427
|
+
"Scans a directory (or single file), imports to raw/, extracts text with structural provenance " +
|
|
428
|
+
"(per-page PDF, per-sheet XLSX, per-slide PPTX), chunks into fixed-line segments, then packs " +
|
|
429
|
+
"into markdown digest packs under raw/digest-packs/{topic}/. Files already in raw/ are skipped.\n" +
|
|
430
|
+
"- `digest_write`: Write LLM-generated digest summaries to wiki with structured provenance. " +
|
|
431
|
+
"Creates or updates one or more wiki pages from digested content, linking back to source raw files and digest packs. " +
|
|
432
|
+
"Index is rebuilt once at the end. Each page gets auto-classified, auto-routed, and timestamped.",
|
|
433
|
+
inputSchema: {
|
|
434
|
+
type: "object",
|
|
435
|
+
properties: {
|
|
436
|
+
mode: {
|
|
437
|
+
type: "string",
|
|
438
|
+
enum: ["batch", "digest_write"],
|
|
439
|
+
description: "Ingestion mode: batch (import and pack source documents) or digest_write (write LLM summaries to wiki)",
|
|
440
|
+
},
|
|
441
|
+
source_path: {
|
|
442
|
+
type: "string",
|
|
443
|
+
description: "[batch] Absolute path to a directory or single file to ingest",
|
|
444
|
+
},
|
|
445
|
+
pattern: {
|
|
446
|
+
type: "string",
|
|
447
|
+
description: "[batch] Glob filter when source_path is a directory (e.g. '*.pdf', '*.{xlsx,docx}')",
|
|
448
|
+
},
|
|
449
|
+
maxFiles: {
|
|
450
|
+
type: "number",
|
|
451
|
+
description: "[batch] Maximum files to process (default: 100, max: 1000)",
|
|
452
|
+
},
|
|
453
|
+
topic: {
|
|
454
|
+
type: "string",
|
|
455
|
+
description: "[batch] Topic name for organizing digest packs (default: 'general')",
|
|
456
|
+
},
|
|
457
|
+
chunkLines: {
|
|
458
|
+
type: "number",
|
|
459
|
+
description: "[batch] Maximum lines per chunk (default: 100)",
|
|
460
|
+
},
|
|
461
|
+
packLines: {
|
|
462
|
+
type: "number",
|
|
463
|
+
description: "[batch] Maximum lines per digest pack (default: 500)",
|
|
464
|
+
},
|
|
465
|
+
continueOnError: {
|
|
466
|
+
type: "boolean",
|
|
467
|
+
description: "[batch] Continue processing on individual file errors (default: true)",
|
|
468
|
+
},
|
|
469
|
+
pages: {
|
|
470
|
+
type: "array",
|
|
471
|
+
items: {
|
|
472
|
+
type: "object",
|
|
473
|
+
properties: {
|
|
474
|
+
page: {
|
|
475
|
+
type: "string",
|
|
476
|
+
description: "Page path relative to wiki/ (e.g. 'concept-transformer.md')",
|
|
477
|
+
},
|
|
478
|
+
title: {
|
|
479
|
+
type: "string",
|
|
480
|
+
description: "Page title",
|
|
481
|
+
},
|
|
482
|
+
body: {
|
|
483
|
+
type: "string",
|
|
484
|
+
description: "Markdown body content (without frontmatter — auto-generated)",
|
|
485
|
+
},
|
|
486
|
+
type: {
|
|
487
|
+
type: "string",
|
|
488
|
+
description: "Entity type (concept, person, event, how-to, summary, synthesis, etc.). Auto-classified if omitted.",
|
|
489
|
+
},
|
|
490
|
+
tags: {
|
|
491
|
+
type: "array",
|
|
492
|
+
items: { type: "string" },
|
|
493
|
+
description: "Tags for categorization. Auto-classified if omitted.",
|
|
494
|
+
},
|
|
495
|
+
topic: {
|
|
496
|
+
type: "string",
|
|
497
|
+
description: "Topic subdirectory for auto-routing (e.g. 'trade-lifecycle')",
|
|
498
|
+
},
|
|
499
|
+
sources: {
|
|
500
|
+
type: "array",
|
|
501
|
+
items: { type: "string" },
|
|
502
|
+
description: "Source raw file paths (e.g. ['raw/topic/doc.pdf'])",
|
|
503
|
+
},
|
|
504
|
+
sourcePacks: {
|
|
505
|
+
type: "array",
|
|
506
|
+
items: { type: "string" },
|
|
507
|
+
description: "Digest pack paths used to generate this page",
|
|
508
|
+
},
|
|
509
|
+
},
|
|
510
|
+
required: ["page", "title", "body"],
|
|
511
|
+
},
|
|
512
|
+
description: "[digest_write] Array of wiki pages to write",
|
|
513
|
+
},
|
|
514
|
+
},
|
|
515
|
+
required: ["mode"],
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
// knowledge_ingest_batch, knowledge_digest_write folded into knowledge_ingest
|
|
519
|
+
// ═══════════════════════════════════════════════════════
|
|
520
|
+
// CODE ANALYSIS — Parse source files into structured knowledge
|
|
521
|
+
// ═══════════════════════════════════════════════════════
|
|
522
|
+
{
|
|
523
|
+
name: "code_parse",
|
|
524
|
+
description: "Parse a source file from raw/ into structured code knowledge (AST, normalized model, summary). Currently supports COBOL (.cbl, .cob, .cpy). Persists artifacts under raw/parsed/cobol/. Optionally traces all references to a variable.",
|
|
525
|
+
inputSchema: {
|
|
526
|
+
type: "object",
|
|
527
|
+
properties: {
|
|
528
|
+
path: {
|
|
529
|
+
type: "string",
|
|
530
|
+
description: "Path to source file in raw/ (e.g. 'PAYROLL.cbl')",
|
|
531
|
+
},
|
|
532
|
+
trace_variable: {
|
|
533
|
+
type: "string",
|
|
534
|
+
description: "Optional: variable name to trace (e.g. 'WS-TOTAL-SALARY')",
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
required: ["path"],
|
|
538
|
+
},
|
|
539
|
+
},
|
|
540
|
+
{
|
|
541
|
+
name: "code_query",
|
|
542
|
+
description: "Query parsed code knowledge. Select `query_type` to control behavior:\n" +
|
|
543
|
+
"- `trace_variable`: Trace all references to a variable in a parsed source file — shows where it is read, written, or passed, grouped by section/paragraph.\n" +
|
|
544
|
+
"- `impact`: Query the compiled knowledge graph for downstream impact — returns affected programs, copybooks, or datasets grouped by dependency depth, with evidence and uncertainty markers.\n" +
|
|
545
|
+
"- `procedure_flow`: Query parsed procedure/section PERFORM flow for one source file — returns section-level and paragraph-level flow, optionally focused on one procedure.\n" +
|
|
546
|
+
"- `field_lineage`: Query compiled field-lineage artifacts — returns deterministic and inferred matches for one field, optionally narrowed to a copybook or qualified name.\n" +
|
|
547
|
+
"- `dataflow_edges`: Query field-level dataflow edges — MOVE/COMPUTE/ADD assignment, EXEC SQL host-variable, and CALL USING parameter edges. Filter by `from`/`to`, or set `field`+`transitive: true` to follow chains across the full graph.",
|
|
548
|
+
inputSchema: {
|
|
549
|
+
type: "object",
|
|
550
|
+
properties: {
|
|
551
|
+
query_type: {
|
|
552
|
+
type: "string",
|
|
553
|
+
enum: ["trace_variable", "impact", "procedure_flow", "field_lineage", "dataflow_edges"],
|
|
554
|
+
description: "Query type: trace_variable, impact, procedure_flow, field_lineage, or dataflow_edges",
|
|
555
|
+
},
|
|
556
|
+
path: {
|
|
557
|
+
type: "string",
|
|
558
|
+
description: "[trace_variable/procedure_flow/dataflow_edges] Path to source file in raw/ (e.g. 'PAYROLL.cbl')",
|
|
559
|
+
},
|
|
560
|
+
variable: {
|
|
561
|
+
type: "string",
|
|
562
|
+
description: "[trace_variable] Variable name to trace (e.g. 'WS-TOTAL-SALARY')",
|
|
563
|
+
},
|
|
564
|
+
node_id: {
|
|
565
|
+
type: "string",
|
|
566
|
+
description: "[impact] Canonical node ID or logical name (e.g. 'copybook:DATE-UTILS' or 'DATE-UTILS')",
|
|
567
|
+
},
|
|
568
|
+
kind: {
|
|
569
|
+
type: "string",
|
|
570
|
+
description: "[impact] Optional node kind: program, copybook, dataset, job, or step",
|
|
571
|
+
},
|
|
572
|
+
max_depth: {
|
|
573
|
+
type: "number",
|
|
574
|
+
description: "[impact/dataflow_edges] Maximum traversal depth (default: 10)",
|
|
575
|
+
},
|
|
576
|
+
language: {
|
|
577
|
+
type: "string",
|
|
578
|
+
description: "[impact/field_lineage] Compiled language artifact set to read (default: 'cobol')",
|
|
579
|
+
},
|
|
580
|
+
procedure: {
|
|
581
|
+
type: "string",
|
|
582
|
+
description: "[procedure_flow] Optional procedure/section/paragraph name to focus traversal from (e.g. 'A100-INIT')",
|
|
583
|
+
},
|
|
584
|
+
procedure_kind: {
|
|
585
|
+
type: "string",
|
|
586
|
+
description: "[procedure_flow] Optional procedure kind filter: section or paragraph",
|
|
587
|
+
},
|
|
588
|
+
field_name: {
|
|
589
|
+
type: "string",
|
|
590
|
+
description: "[field_lineage] Field name to query (e.g. 'CUSTOMER-ID')",
|
|
591
|
+
},
|
|
592
|
+
qualified_name: {
|
|
593
|
+
type: "string",
|
|
594
|
+
description: "[field_lineage] Optional qualified field path (e.g. 'CUSTOMER-REC.CUSTOMER-ID')",
|
|
595
|
+
},
|
|
596
|
+
copybook: {
|
|
597
|
+
type: "string",
|
|
598
|
+
description: "[field_lineage] Optional copybook canonical id or logical name (e.g. 'copybook:CUSTOMER-A' or 'CUSTOMER-A')",
|
|
599
|
+
},
|
|
600
|
+
from: {
|
|
601
|
+
type: "string",
|
|
602
|
+
description: "[dataflow_edges] Filter: only edges whose source field matches (e.g. 'EMP-SALARY')",
|
|
603
|
+
},
|
|
604
|
+
to: {
|
|
605
|
+
type: "string",
|
|
606
|
+
description: "[dataflow_edges] Filter: only edges whose target field matches (e.g. 'WS-TOTAL-SALARY')",
|
|
607
|
+
},
|
|
608
|
+
field: {
|
|
609
|
+
type: "string",
|
|
610
|
+
description: "[dataflow_edges] Starting field for transitive traversal (requires transitive: true)",
|
|
611
|
+
},
|
|
612
|
+
transitive: {
|
|
613
|
+
type: "boolean",
|
|
614
|
+
description: "[dataflow_edges] Follow edges transitively from `field` (default: false)",
|
|
615
|
+
},
|
|
616
|
+
direction: {
|
|
617
|
+
type: "string",
|
|
618
|
+
enum: ["downstream", "upstream", "both"],
|
|
619
|
+
description: "[dataflow_edges] Traversal direction when transitive: true — downstream (default), upstream, or both",
|
|
620
|
+
},
|
|
621
|
+
},
|
|
622
|
+
required: ["query_type"],
|
|
623
|
+
},
|
|
624
|
+
},
|
|
625
|
+
// code_trace_variable, code_impact folded into code_query
|
|
626
|
+
],
|
|
627
|
+
}));
|
|
628
|
+
// ── Call Tool (with concurrency control) ────────────────────
|
|
629
|
+
const queue = new RequestQueue();
|
|
630
|
+
// Tools that mutate state — serialized through the write queue
|
|
631
|
+
const WRITE_TOOLS = new Set([
|
|
632
|
+
// Consolidated public tools
|
|
633
|
+
"raw_ingest", // add/fetch/import_confluence/import_jira all mutate raw/
|
|
634
|
+
"wiki_admin", // init/rebuild/lint all mutate state (config is read-only but routed through write queue for safety)
|
|
635
|
+
"knowledge_ingest", // batch/digest_write both mutate state
|
|
636
|
+
// Public tools retained from the original surface (write classification unchanged)
|
|
637
|
+
"wiki_write", "wiki_delete",
|
|
638
|
+
// Legacy aliases (not in public surface but remain functional for backward compatibility)
|
|
639
|
+
"raw_add", "raw_fetch", "raw_import_confluence", "raw_import_jira",
|
|
640
|
+
"wiki_init", "wiki_rebuild",
|
|
641
|
+
"wiki_lint", // writes .lint-cache.json + log.md
|
|
642
|
+
"code_parse", // writes parsed artifacts under raw/parsed/
|
|
643
|
+
"knowledge_ingest_batch", // writes to raw/ and raw/digest-packs/
|
|
644
|
+
"knowledge_digest_write", // writes to wiki/
|
|
645
|
+
]);
|
|
646
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
647
|
+
const { name, arguments: args = {} } = request.params;
|
|
648
|
+
const params = args;
|
|
649
|
+
// batch: route dynamically — write queue only if any op mutates state
|
|
650
|
+
let isWrite;
|
|
651
|
+
if (name === "batch") {
|
|
652
|
+
const ops = params.operations;
|
|
653
|
+
// Malformed args → route through read queue; handleTool will return validation error
|
|
654
|
+
isWrite = Array.isArray(ops) && ops.some((op) => WRITE_TOOLS.has(op?.tool));
|
|
655
|
+
}
|
|
656
|
+
else {
|
|
657
|
+
isWrite = WRITE_TOOLS.has(name);
|
|
658
|
+
}
|
|
659
|
+
const run = async () => {
|
|
660
|
+
try {
|
|
661
|
+
const result = await handleTool(wiki, name, params);
|
|
662
|
+
if (typeof result === "string") {
|
|
663
|
+
return { content: [{ type: "text", text: result }] };
|
|
664
|
+
}
|
|
665
|
+
return { content: result };
|
|
666
|
+
}
|
|
667
|
+
catch (err) {
|
|
668
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
669
|
+
return {
|
|
670
|
+
content: [{ type: "text", text: `Error: ${msg}` }],
|
|
671
|
+
isError: true,
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
return isWrite ? queue.write(run) : queue.read(run);
|
|
676
|
+
});
|
|
677
|
+
return server;
|
|
678
|
+
}
|
|
679
|
+
const IMAGE_MIME_TYPES = new Set([
|
|
680
|
+
"image/png", "image/jpeg", "image/gif", "image/webp",
|
|
681
|
+
"image/avif", "image/bmp", "image/tiff",
|
|
682
|
+
]);
|
|
683
|
+
const MAX_INLINE_IMAGE_BYTES = 10 * 1024 * 1024; // 10 MB
|
|
684
|
+
/** If filePath is a displayable image under the size limit, return an image ContentBlock; else null. */
|
|
685
|
+
export function tryImageBlock(filePath, mimeType) {
|
|
686
|
+
if (!IMAGE_MIME_TYPES.has(mimeType))
|
|
687
|
+
return null;
|
|
688
|
+
if (!existsSync(filePath))
|
|
689
|
+
return null;
|
|
690
|
+
const size = statSync(filePath).size;
|
|
691
|
+
if (size > MAX_INLINE_IMAGE_BYTES)
|
|
692
|
+
return null;
|
|
693
|
+
const data = readFileSync(filePath).toString("base64");
|
|
694
|
+
return { type: "image", data, mimeType };
|
|
695
|
+
}
|
|
696
|
+
/** Recursively walk a directory, returning relative file paths (skips dotfiles). */
|
|
697
|
+
function walkSourceDir(dir) {
|
|
698
|
+
const result = [];
|
|
699
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
700
|
+
if (entry.name.startsWith("."))
|
|
701
|
+
continue;
|
|
702
|
+
const full = join(dir, entry.name);
|
|
703
|
+
if (entry.isDirectory()) {
|
|
704
|
+
result.push(...walkSourceDir(full).map(f => join(entry.name, f)));
|
|
705
|
+
}
|
|
706
|
+
else {
|
|
707
|
+
result.push(entry.name);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return result.sort();
|
|
711
|
+
}
|
|
712
|
+
/** Validate and sanitize a topic string to a safe path slug. */
|
|
713
|
+
function sanitizeTopic(raw) {
|
|
714
|
+
if (!raw || /\.\.|^\/|^\\|\x00/.test(raw)) {
|
|
715
|
+
throw new Error(`Invalid topic: "${raw}". Must not contain "..", absolute paths, or null bytes.`);
|
|
716
|
+
}
|
|
717
|
+
return raw.replace(/[^a-zA-Z0-9_\-/]/g, "-").replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "");
|
|
718
|
+
}
|
|
719
|
+
function normalizeImpactKind(raw) {
|
|
720
|
+
if (!raw)
|
|
721
|
+
return undefined;
|
|
722
|
+
switch (raw.trim().toLowerCase()) {
|
|
723
|
+
case "program":
|
|
724
|
+
return "Program";
|
|
725
|
+
case "copybook":
|
|
726
|
+
return "Copybook";
|
|
727
|
+
case "dataset":
|
|
728
|
+
return "Dataset";
|
|
729
|
+
case "job":
|
|
730
|
+
return "Job";
|
|
731
|
+
case "step":
|
|
732
|
+
return "Step";
|
|
733
|
+
default:
|
|
734
|
+
throw new Error(`Unsupported node kind: ${raw}. Expected one of: program, copybook, dataset, job, step.`);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
function normalizeProcedureKind(raw) {
|
|
738
|
+
if (!raw)
|
|
739
|
+
return undefined;
|
|
740
|
+
const kind = raw.trim().toLowerCase();
|
|
741
|
+
if (kind === "section" || kind === "paragraph")
|
|
742
|
+
return kind;
|
|
743
|
+
throw new Error(`Unsupported procedure_kind: ${raw}. Expected one of: section, paragraph.`);
|
|
744
|
+
}
|
|
745
|
+
function parsedArtifactStem(filePath) {
|
|
746
|
+
return filePath.replace(/\.[^.]+$/, "");
|
|
747
|
+
}
|
|
748
|
+
async function loadParsedNormalizedModel(wiki, filePath) {
|
|
749
|
+
const plugin = getPluginForFile(filePath);
|
|
750
|
+
if (!plugin) {
|
|
751
|
+
const supported = listPlugins().flatMap((p) => p.extensions).join(", ");
|
|
752
|
+
throw new Error(`Unsupported file type: ${filePath}. Supported extensions: ${supported}`);
|
|
753
|
+
}
|
|
754
|
+
const rawResult = await wiki.rawRead(`parsed/${plugin.id}/${parsedArtifactStem(filePath)}.normalized.json`);
|
|
755
|
+
if (!rawResult || rawResult.content === null) {
|
|
756
|
+
throw new Error(`Parsed normalized model not found for "${filePath}". Run code_parse on that source file first.`);
|
|
757
|
+
}
|
|
758
|
+
try {
|
|
759
|
+
return JSON.parse(rawResult.content);
|
|
760
|
+
}
|
|
761
|
+
catch (err) {
|
|
762
|
+
throw new Error(`Failed to parse normalized model for "${filePath}": ${err instanceof Error ? err.message : String(err)}`);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
async function loadFieldLineageArtifact(wiki, language) {
|
|
766
|
+
const plugin = getPlugin(language);
|
|
767
|
+
if (!plugin) {
|
|
768
|
+
const available = listPlugins().map((p) => p.id).join(", ");
|
|
769
|
+
throw new Error(`Unknown code-analysis plugin: ${language}. Available plugins: ${available}`);
|
|
770
|
+
}
|
|
771
|
+
const rawResult = await wiki.rawRead(`parsed/${plugin.id}/field-lineage.json`);
|
|
772
|
+
if (!rawResult || rawResult.content === null) {
|
|
773
|
+
throw new Error(`Compiled field lineage not found for "${plugin.id}". Run code_parse on both ${plugin.id.toUpperCase()} program files (.cbl/.cob) AND copybook files (.cpy) — field lineage requires data from both to build the cross-file index.`);
|
|
774
|
+
}
|
|
775
|
+
try {
|
|
776
|
+
return JSON.parse(rawResult.content);
|
|
777
|
+
}
|
|
778
|
+
catch (err) {
|
|
779
|
+
throw new Error(`Failed to parse compiled field lineage for "${plugin.id}": ${err instanceof Error ? err.message : String(err)}`);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function procedureSectionName(procedure) {
|
|
783
|
+
if (!procedure)
|
|
784
|
+
return null;
|
|
785
|
+
return procedure.kind === "section" ? procedure.name : procedure.parentProcedure ?? null;
|
|
786
|
+
}
|
|
787
|
+
function procedureSummary(procedure) {
|
|
788
|
+
if (!procedure)
|
|
789
|
+
return null;
|
|
790
|
+
return {
|
|
791
|
+
name: procedure.name,
|
|
792
|
+
kind: procedure.kind,
|
|
793
|
+
parentUnit: procedure.parentUnit ?? null,
|
|
794
|
+
parentProcedure: procedure.parentProcedure ?? null,
|
|
795
|
+
section: procedureSectionName(procedure),
|
|
796
|
+
loc: procedure.loc,
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
function resolveProcedure(procedures, requested, kind) {
|
|
800
|
+
const needle = requested.trim().toLowerCase();
|
|
801
|
+
if (!needle)
|
|
802
|
+
throw new Error("procedure must not be empty");
|
|
803
|
+
const matches = procedures.filter((procedure) => {
|
|
804
|
+
if (kind && procedure.kind !== kind)
|
|
805
|
+
return false;
|
|
806
|
+
return procedure.name.toLowerCase() === needle;
|
|
807
|
+
});
|
|
808
|
+
if (matches.length === 1)
|
|
809
|
+
return matches[0];
|
|
810
|
+
if (matches.length > 1) {
|
|
811
|
+
throw new Error(`Procedure "${requested}" is ambiguous. Use procedure_kind to narrow it. Matches: ${matches.map((p) => `${p.kind}:${p.name}`).join(", ")}`);
|
|
812
|
+
}
|
|
813
|
+
throw new Error(`Procedure not found in parsed model: ${requested}`);
|
|
814
|
+
}
|
|
815
|
+
function buildProcedureFlowResponse(model, query) {
|
|
816
|
+
const procedures = model.procedures.filter((procedure) => procedure.kind === "section" || procedure.kind === "paragraph");
|
|
817
|
+
const procedureByName = new Map();
|
|
818
|
+
for (const procedure of procedures) {
|
|
819
|
+
const key = procedure.name.toLowerCase();
|
|
820
|
+
if (!procedureByName.has(key))
|
|
821
|
+
procedureByName.set(key, procedure);
|
|
822
|
+
}
|
|
823
|
+
const performRelations = model.relations.filter((relation) => relation.type === "perform");
|
|
824
|
+
const performs = performRelations.map((relation) => {
|
|
825
|
+
const fromProcedure = procedureByName.get(relation.from.toLowerCase());
|
|
826
|
+
const toProcedure = procedureByName.get(relation.to.toLowerCase());
|
|
827
|
+
return {
|
|
828
|
+
from: {
|
|
829
|
+
name: relation.from,
|
|
830
|
+
kind: fromProcedure?.kind ?? null,
|
|
831
|
+
section: procedureSectionName(fromProcedure),
|
|
832
|
+
},
|
|
833
|
+
to: {
|
|
834
|
+
name: relation.to,
|
|
835
|
+
kind: toProcedure?.kind ?? null,
|
|
836
|
+
section: procedureSectionName(toProcedure),
|
|
837
|
+
},
|
|
838
|
+
line: relation.loc.line,
|
|
839
|
+
thru: typeof relation.metadata?.thru === "string" ? relation.metadata.thru : null,
|
|
840
|
+
};
|
|
841
|
+
});
|
|
842
|
+
const sectionCallMap = new Map();
|
|
843
|
+
for (const perform of performs) {
|
|
844
|
+
const fromSection = perform.from.section;
|
|
845
|
+
const toSection = perform.to.section;
|
|
846
|
+
if (!fromSection || !toSection)
|
|
847
|
+
continue;
|
|
848
|
+
const key = `${fromSection}→${toSection}`;
|
|
849
|
+
const aggregate = sectionCallMap.get(key) ?? {
|
|
850
|
+
fromSection,
|
|
851
|
+
toSection,
|
|
852
|
+
callers: new Set(),
|
|
853
|
+
targets: new Set(),
|
|
854
|
+
count: 0,
|
|
855
|
+
};
|
|
856
|
+
aggregate.callers.add(perform.from.name);
|
|
857
|
+
aggregate.targets.add(perform.to.name);
|
|
858
|
+
aggregate.count += 1;
|
|
859
|
+
sectionCallMap.set(key, aggregate);
|
|
860
|
+
}
|
|
861
|
+
const sectionCalls = [...sectionCallMap.values()]
|
|
862
|
+
.map((entry) => ({
|
|
863
|
+
fromSection: entry.fromSection,
|
|
864
|
+
toSection: entry.toSection,
|
|
865
|
+
count: entry.count,
|
|
866
|
+
callers: [...entry.callers].sort((a, b) => a.localeCompare(b)),
|
|
867
|
+
targets: [...entry.targets].sort((a, b) => a.localeCompare(b)),
|
|
868
|
+
}))
|
|
869
|
+
.sort((a, b) => a.fromSection.localeCompare(b.fromSection) || a.toSection.localeCompare(b.toSection));
|
|
870
|
+
const response = {
|
|
871
|
+
query: {
|
|
872
|
+
type: "procedure_flow",
|
|
873
|
+
path: query.path,
|
|
874
|
+
procedure: query.procedure ?? null,
|
|
875
|
+
procedure_kind: query.procedureKind ?? null,
|
|
876
|
+
maxDepth: query.maxDepth,
|
|
877
|
+
},
|
|
878
|
+
unit: model.units[0] ?? null,
|
|
879
|
+
summary: {
|
|
880
|
+
sections: procedures.filter((procedure) => procedure.kind === "section").length,
|
|
881
|
+
paragraphs: procedures.filter((procedure) => procedure.kind === "paragraph").length,
|
|
882
|
+
performRelations: performs.length,
|
|
883
|
+
sectionCalls: sectionCalls.length,
|
|
884
|
+
},
|
|
885
|
+
procedures: {
|
|
886
|
+
sections: procedures
|
|
887
|
+
.filter((procedure) => procedure.kind === "section")
|
|
888
|
+
.map((procedure) => procedureSummary(procedure)),
|
|
889
|
+
paragraphs: procedures
|
|
890
|
+
.filter((procedure) => procedure.kind === "paragraph")
|
|
891
|
+
.map((procedure) => procedureSummary(procedure)),
|
|
892
|
+
},
|
|
893
|
+
performs,
|
|
894
|
+
sectionCalls,
|
|
895
|
+
};
|
|
896
|
+
if (!query.procedure)
|
|
897
|
+
return response;
|
|
898
|
+
const focus = resolveProcedure(procedures, query.procedure, query.procedureKind);
|
|
899
|
+
const adjacency = new Map();
|
|
900
|
+
for (const relation of performRelations) {
|
|
901
|
+
const fromKey = relation.from.toLowerCase();
|
|
902
|
+
const fromList = adjacency.get(fromKey) ?? [];
|
|
903
|
+
fromList.push(relation);
|
|
904
|
+
adjacency.set(fromKey, fromList);
|
|
905
|
+
const fromProcedure = procedureByName.get(fromKey);
|
|
906
|
+
const fromSection = procedureSectionName(fromProcedure);
|
|
907
|
+
if (fromSection) {
|
|
908
|
+
const sectionKey = fromSection.toLowerCase();
|
|
909
|
+
const sectionList = adjacency.get(sectionKey) ?? [];
|
|
910
|
+
sectionList.push({
|
|
911
|
+
...relation,
|
|
912
|
+
from: fromSection,
|
|
913
|
+
metadata: {
|
|
914
|
+
...(relation.metadata ?? {}),
|
|
915
|
+
viaParagraph: relation.from,
|
|
916
|
+
},
|
|
917
|
+
});
|
|
918
|
+
adjacency.set(sectionKey, sectionList);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
const flowByDepth = [];
|
|
922
|
+
const visited = new Set([focus.name.toLowerCase()]);
|
|
923
|
+
let frontier = new Set([focus.name.toLowerCase()]);
|
|
924
|
+
for (let depth = 1; depth <= query.maxDepth; depth++) {
|
|
925
|
+
const edges = [...frontier].flatMap((name) => adjacency.get(name) ?? []);
|
|
926
|
+
const currentLevelTargets = new Set();
|
|
927
|
+
for (const edge of edges) {
|
|
928
|
+
const targetKey = edge.to.toLowerCase();
|
|
929
|
+
if (visited.has(targetKey))
|
|
930
|
+
continue;
|
|
931
|
+
currentLevelTargets.add(targetKey);
|
|
932
|
+
}
|
|
933
|
+
if (currentLevelTargets.size === 0)
|
|
934
|
+
break;
|
|
935
|
+
const nodes = [...currentLevelTargets]
|
|
936
|
+
.sort((a, b) => a.localeCompare(b))
|
|
937
|
+
.map((targetKey) => {
|
|
938
|
+
visited.add(targetKey);
|
|
939
|
+
const targetProcedure = procedureByName.get(targetKey);
|
|
940
|
+
const via = edges
|
|
941
|
+
.filter((edge) => edge.to.toLowerCase() === targetKey)
|
|
942
|
+
.map((edge) => {
|
|
943
|
+
const fromProcedure = procedureByName.get(edge.from.toLowerCase());
|
|
944
|
+
return {
|
|
945
|
+
from: edge.from,
|
|
946
|
+
fromKind: fromProcedure?.kind ?? null,
|
|
947
|
+
fromSection: procedureSectionName(fromProcedure),
|
|
948
|
+
viaParagraph: typeof edge.metadata?.viaParagraph === "string" ? edge.metadata.viaParagraph : null,
|
|
949
|
+
line: edge.loc.line,
|
|
950
|
+
thru: typeof edge.metadata?.thru === "string" ? edge.metadata.thru : null,
|
|
951
|
+
};
|
|
952
|
+
});
|
|
953
|
+
return {
|
|
954
|
+
name: targetProcedure?.name ?? targetKey,
|
|
955
|
+
kind: targetProcedure?.kind ?? null,
|
|
956
|
+
parentUnit: targetProcedure?.parentUnit ?? null,
|
|
957
|
+
parentProcedure: targetProcedure?.parentProcedure ?? null,
|
|
958
|
+
section: procedureSectionName(targetProcedure),
|
|
959
|
+
resolved: Boolean(targetProcedure),
|
|
960
|
+
loc: targetProcedure?.loc ?? null,
|
|
961
|
+
via,
|
|
962
|
+
};
|
|
963
|
+
});
|
|
964
|
+
flowByDepth.push({ depth, nodes });
|
|
965
|
+
frontier = currentLevelTargets;
|
|
966
|
+
}
|
|
967
|
+
response.focus = procedureSummary(focus);
|
|
968
|
+
response.flowByDepth = flowByDepth;
|
|
969
|
+
response.summary = {
|
|
970
|
+
...response.summary,
|
|
971
|
+
reachableProcedures: flowByDepth.reduce((count, level) => count + ((level.nodes?.length) ?? 0), 0),
|
|
972
|
+
focusDepths: flowByDepth.length,
|
|
973
|
+
};
|
|
974
|
+
return response;
|
|
975
|
+
}
|
|
976
|
+
function normalizeLineageCopybookQuery(raw) {
|
|
977
|
+
if (!raw)
|
|
978
|
+
return undefined;
|
|
979
|
+
const trimmed = raw.trim();
|
|
980
|
+
if (!trimmed)
|
|
981
|
+
throw new Error("copybook must not be empty");
|
|
982
|
+
return (trimmed.includes(":") ? trimmed : canonicalNodeId("Copybook", trimmed)).toUpperCase();
|
|
983
|
+
}
|
|
984
|
+
function copybookMatches(copybook, requestedCopybook) {
|
|
985
|
+
if (!requestedCopybook)
|
|
986
|
+
return true;
|
|
987
|
+
const canonical = copybook.id.toUpperCase();
|
|
988
|
+
if (canonical === requestedCopybook)
|
|
989
|
+
return true;
|
|
990
|
+
return displayLabel(copybook.id).toUpperCase() === displayLabel(requestedCopybook).toUpperCase();
|
|
991
|
+
}
|
|
992
|
+
function qualifiedNameMatches(candidate, requested) {
|
|
993
|
+
if (!requested)
|
|
994
|
+
return true;
|
|
995
|
+
if (!candidate)
|
|
996
|
+
return false;
|
|
997
|
+
return candidate.trim().toUpperCase() === requested.trim().toUpperCase();
|
|
998
|
+
}
|
|
999
|
+
function inferredEntryMatches(entry, requestedFieldName, requestedQualifiedName, requestedCopybook) {
|
|
1000
|
+
if (requestedFieldName && entry.fieldName.toUpperCase() !== requestedFieldName.toUpperCase())
|
|
1001
|
+
return false;
|
|
1002
|
+
if (!requestedQualifiedName && !requestedCopybook)
|
|
1003
|
+
return true;
|
|
1004
|
+
const leftMatches = copybookMatches(entry.left.copybook, requestedCopybook)
|
|
1005
|
+
&& qualifiedNameMatches(entry.left.qualifiedName, requestedQualifiedName);
|
|
1006
|
+
const rightMatches = copybookMatches(entry.right.copybook, requestedCopybook)
|
|
1007
|
+
&& qualifiedNameMatches(entry.right.qualifiedName, requestedQualifiedName);
|
|
1008
|
+
return leftMatches || rightMatches;
|
|
1009
|
+
}
|
|
1010
|
+
function buildFieldLineageResponse(lineage, query) {
|
|
1011
|
+
const fieldName = query.fieldName?.trim();
|
|
1012
|
+
const qualifiedName = query.qualifiedName?.trim();
|
|
1013
|
+
const copybook = normalizeLineageCopybookQuery(query.copybook);
|
|
1014
|
+
if (!fieldName && !qualifiedName) {
|
|
1015
|
+
throw new Error("field_lineage requires field_name or qualified_name");
|
|
1016
|
+
}
|
|
1017
|
+
const deterministic = lineage.deterministic.filter((entry) => {
|
|
1018
|
+
if (fieldName && entry.fieldName.toUpperCase() !== fieldName.toUpperCase())
|
|
1019
|
+
return false;
|
|
1020
|
+
if (qualifiedName && !entry.qualifiedNames.some((name) => qualifiedNameMatches(name, qualifiedName)))
|
|
1021
|
+
return false;
|
|
1022
|
+
if (copybook && !entry.copybooks.some((item) => copybookMatches(item, copybook)))
|
|
1023
|
+
return false;
|
|
1024
|
+
return true;
|
|
1025
|
+
});
|
|
1026
|
+
const inferredHighConfidence = lineage.inferredHighConfidence.filter((entry) => inferredEntryMatches(entry, fieldName, qualifiedName, copybook));
|
|
1027
|
+
const inferredAmbiguous = lineage.inferredAmbiguous.filter((entry) => inferredEntryMatches(entry, fieldName, qualifiedName, copybook));
|
|
1028
|
+
return {
|
|
1029
|
+
query: {
|
|
1030
|
+
type: "field_lineage",
|
|
1031
|
+
language: query.language,
|
|
1032
|
+
field_name: fieldName ?? null,
|
|
1033
|
+
qualified_name: qualifiedName ?? null,
|
|
1034
|
+
copybook: copybook ?? null,
|
|
1035
|
+
},
|
|
1036
|
+
summary: {
|
|
1037
|
+
deterministicMatches: deterministic.length,
|
|
1038
|
+
inferredHighConfidenceMatches: inferredHighConfidence.length,
|
|
1039
|
+
inferredAmbiguousMatches: inferredAmbiguous.length,
|
|
1040
|
+
},
|
|
1041
|
+
deterministic,
|
|
1042
|
+
inferredHighConfidence,
|
|
1043
|
+
inferredAmbiguous,
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
function codeQueryConsumesCompiledArtifacts(args) {
|
|
1047
|
+
const queryType = args.query_type;
|
|
1048
|
+
return queryType === "impact" || queryType === "field_lineage";
|
|
1049
|
+
}
|
|
1050
|
+
async function loadCompiledGraph(wiki, language) {
|
|
1051
|
+
const plugin = getPlugin(language);
|
|
1052
|
+
if (!plugin) {
|
|
1053
|
+
const available = listPlugins().map((p) => p.id).join(", ");
|
|
1054
|
+
throw new Error(`Unknown code-analysis plugin: ${language}. Available plugins: ${available}`);
|
|
1055
|
+
}
|
|
1056
|
+
const rawResult = await wiki.rawRead(`parsed/${plugin.id}/knowledge-graph.json`);
|
|
1057
|
+
if (!rawResult || rawResult.content === null) {
|
|
1058
|
+
throw new Error(`Compiled knowledge graph not found for "${plugin.id}". Run code_parse on one or more ${plugin.id.toUpperCase()} files, or run wiki_rebuild after parsing.`);
|
|
1059
|
+
}
|
|
1060
|
+
let parsed;
|
|
1061
|
+
try {
|
|
1062
|
+
parsed = JSON.parse(rawResult.content);
|
|
1063
|
+
}
|
|
1064
|
+
catch (err) {
|
|
1065
|
+
throw new Error(`Failed to parse compiled knowledge graph for "${plugin.id}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1066
|
+
}
|
|
1067
|
+
return deserializeGraph(parsed);
|
|
1068
|
+
}
|
|
1069
|
+
function removeParsedArtifactIfExists(wiki, relativePath) {
|
|
1070
|
+
const fullPath = safePath(wiki.config.rawDir, relativePath);
|
|
1071
|
+
if (existsSync(fullPath))
|
|
1072
|
+
rmSync(fullPath, { force: true });
|
|
1073
|
+
if (existsSync(`${fullPath}.meta.yaml`))
|
|
1074
|
+
rmSync(`${fullPath}.meta.yaml`, { force: true });
|
|
1075
|
+
}
|
|
1076
|
+
function removeWikiPageIfExists(wiki, pagePath) {
|
|
1077
|
+
if (wiki.read(pagePath)) {
|
|
1078
|
+
wiki.delete(pagePath);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
function applyDerivedArtifacts(wiki, pluginId, derived) {
|
|
1082
|
+
const writtenArtifacts = [];
|
|
1083
|
+
const currentArtifactPaths = new Set(derived.artifacts.map((artifact) => artifact.path));
|
|
1084
|
+
const currentWikiPagePaths = new Set(derived.wikiPages.map((page) => page.path));
|
|
1085
|
+
for (const artifactPath of derived.staleArtifacts ?? []) {
|
|
1086
|
+
if (!currentArtifactPaths.has(artifactPath)) {
|
|
1087
|
+
removeParsedArtifactIfExists(wiki, `parsed/${pluginId}/${artifactPath}`);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
for (const pagePath of derived.staleWikiPages ?? []) {
|
|
1091
|
+
if (!currentWikiPagePaths.has(pagePath)) {
|
|
1092
|
+
removeWikiPageIfExists(wiki, pagePath);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
for (const artifact of derived.artifacts) {
|
|
1096
|
+
wiki.rawAddParsedArtifact(`parsed/${pluginId}/${artifact.path}`, artifact.content);
|
|
1097
|
+
writtenArtifacts.push(`raw/parsed/${pluginId}/${artifact.path}`);
|
|
1098
|
+
}
|
|
1099
|
+
for (const page of derived.wikiPages) {
|
|
1100
|
+
wiki.write(page.path, page.content);
|
|
1101
|
+
}
|
|
1102
|
+
return writtenArtifacts;
|
|
1103
|
+
}
|
|
1104
|
+
function rebuildDeferredGraphs(wiki) {
|
|
1105
|
+
for (const plugin of listPlugins()) {
|
|
1106
|
+
const parsedDir = join(wiki.config.rawDir, "parsed", plugin.id);
|
|
1107
|
+
if (plugin.rebuildAggregatePages) {
|
|
1108
|
+
for (const page of plugin.rebuildAggregatePages(parsedDir)) {
|
|
1109
|
+
wiki.write(page.path, page.content);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
if (plugin.buildKnowledgeGraph) {
|
|
1113
|
+
const graphResult = plugin.buildKnowledgeGraph(parsedDir);
|
|
1114
|
+
if (graphResult) {
|
|
1115
|
+
wiki.rawAddParsedArtifact(`parsed/${plugin.id}/knowledge-graph.json`, JSON.stringify(graphResult.serialized, null, 2));
|
|
1116
|
+
for (const page of graphResult.wikiPages) {
|
|
1117
|
+
wiki.write(page.path, page.content);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
if (plugin.buildDerivedArtifacts) {
|
|
1122
|
+
const derived = plugin.buildDerivedArtifacts(parsedDir);
|
|
1123
|
+
if (derived) {
|
|
1124
|
+
applyDerivedArtifacts(wiki, plugin.id, derived);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
function resolveImpactNode(graph, requested, kind) {
|
|
1130
|
+
const trimmed = requested.trim();
|
|
1131
|
+
if (!trimmed) {
|
|
1132
|
+
throw new Error("node_id must not be empty");
|
|
1133
|
+
}
|
|
1134
|
+
const needle = trimmed.toLowerCase();
|
|
1135
|
+
const exactMatches = Array.from(graph.nodes.values()).filter((node) => {
|
|
1136
|
+
if (kind && node.kind !== kind)
|
|
1137
|
+
return false;
|
|
1138
|
+
return node.id.toLowerCase() === needle;
|
|
1139
|
+
});
|
|
1140
|
+
if (exactMatches.length === 1)
|
|
1141
|
+
return exactMatches[0];
|
|
1142
|
+
if (exactMatches.length > 1) {
|
|
1143
|
+
throw new Error(`Ambiguous node_id "${requested}" matched multiple nodes: ${exactMatches.map((n) => n.id).join(", ")}`);
|
|
1144
|
+
}
|
|
1145
|
+
const labelMatches = Array.from(graph.nodes.values()).filter((node) => {
|
|
1146
|
+
if (kind && node.kind !== kind)
|
|
1147
|
+
return false;
|
|
1148
|
+
return displayLabel(node.id).toLowerCase() === needle;
|
|
1149
|
+
});
|
|
1150
|
+
if (labelMatches.length === 1)
|
|
1151
|
+
return labelMatches[0];
|
|
1152
|
+
if (labelMatches.length > 1) {
|
|
1153
|
+
throw new Error(`Logical name "${requested}" is ambiguous. Use a canonical node ID or pass kind. Matches: ${labelMatches.map((n) => n.id).join(", ")}`);
|
|
1154
|
+
}
|
|
1155
|
+
if (kind) {
|
|
1156
|
+
const canonical = canonicalNodeId(kind, trimmed);
|
|
1157
|
+
const canonicalMatch = Array.from(graph.nodes.values()).find((node) => node.id.toLowerCase() === canonical.toLowerCase());
|
|
1158
|
+
if (canonicalMatch)
|
|
1159
|
+
return canonicalMatch;
|
|
1160
|
+
}
|
|
1161
|
+
throw new Error(`Node not found in compiled graph: ${requested}`);
|
|
1162
|
+
}
|
|
1163
|
+
function summarizeEvidence(edge) {
|
|
1164
|
+
return {
|
|
1165
|
+
to: edge.to,
|
|
1166
|
+
toLabel: displayLabel(edge.to),
|
|
1167
|
+
relationship: edge.kind,
|
|
1168
|
+
confidence: edge.confidence,
|
|
1169
|
+
sourceFile: edge.evidence.sourceFile,
|
|
1170
|
+
line: edge.evidence.line,
|
|
1171
|
+
reason: edge.evidence.reason,
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
function diagnosticNodeIds(diag) {
|
|
1175
|
+
const matches = diag.message.match(/\b(?:program|copybook|dataset|job|step):[^\s"'`\],)]+/g) ?? [];
|
|
1176
|
+
return new Set(matches);
|
|
1177
|
+
}
|
|
1178
|
+
function buildImpactResponse(graph, sourceNode, maxDepth) {
|
|
1179
|
+
const levels = graphImpactOf(graph, sourceNode.id, maxDepth);
|
|
1180
|
+
const impactedIds = new Set();
|
|
1181
|
+
let previousLevelIds = new Set([sourceNode.id]);
|
|
1182
|
+
const impactedByDepth = [];
|
|
1183
|
+
let unresolvedNodes = 0;
|
|
1184
|
+
let lowerConfidencePaths = 0;
|
|
1185
|
+
for (let depth = 1; depth <= maxDepth; depth++) {
|
|
1186
|
+
const levelNodes = levels.get(depth) ?? [];
|
|
1187
|
+
if (levelNodes.length === 0)
|
|
1188
|
+
continue;
|
|
1189
|
+
const currentIds = new Set(levelNodes.map((node) => node.id));
|
|
1190
|
+
const nodes = levelNodes.map((node) => {
|
|
1191
|
+
impactedIds.add(node.id);
|
|
1192
|
+
if (!node.resolved)
|
|
1193
|
+
unresolvedNodes++;
|
|
1194
|
+
const viaEdges = graphEdgesFrom(graph, node.id).filter((edge) => previousLevelIds.has(edge.to));
|
|
1195
|
+
const hasLowerConfidence = viaEdges.some((edge) => edge.confidence !== "deterministic");
|
|
1196
|
+
if (hasLowerConfidence)
|
|
1197
|
+
lowerConfidencePaths++;
|
|
1198
|
+
const warnings = [];
|
|
1199
|
+
if (!node.resolved)
|
|
1200
|
+
warnings.push("unresolved-node");
|
|
1201
|
+
if (hasLowerConfidence)
|
|
1202
|
+
warnings.push("lower-confidence-path");
|
|
1203
|
+
return {
|
|
1204
|
+
node_id: node.id,
|
|
1205
|
+
label: displayLabel(node.id),
|
|
1206
|
+
kind: node.kind,
|
|
1207
|
+
resolved: node.resolved ?? false,
|
|
1208
|
+
sourceFile: node.sourceFile ?? null,
|
|
1209
|
+
metadata: node.metadata ?? {},
|
|
1210
|
+
via: viaEdges.map(summarizeEvidence),
|
|
1211
|
+
warnings,
|
|
1212
|
+
};
|
|
1213
|
+
});
|
|
1214
|
+
impactedByDepth.push({ depth, nodes });
|
|
1215
|
+
previousLevelIds = currentIds;
|
|
1216
|
+
}
|
|
1217
|
+
const relevantNodeIds = new Set([sourceNode.id, ...impactedIds]);
|
|
1218
|
+
const relevantDiagnostics = graph.diagnostics.filter((diag) => Array.from(diagnosticNodeIds(diag)).some((id) => relevantNodeIds.has(id)));
|
|
1219
|
+
return {
|
|
1220
|
+
query: {
|
|
1221
|
+
requested: sourceNode.id,
|
|
1222
|
+
maxDepth,
|
|
1223
|
+
},
|
|
1224
|
+
source: {
|
|
1225
|
+
node_id: sourceNode.id,
|
|
1226
|
+
label: displayLabel(sourceNode.id),
|
|
1227
|
+
kind: sourceNode.kind,
|
|
1228
|
+
resolved: sourceNode.resolved ?? false,
|
|
1229
|
+
sourceFile: sourceNode.sourceFile ?? null,
|
|
1230
|
+
metadata: sourceNode.metadata ?? {},
|
|
1231
|
+
},
|
|
1232
|
+
summary: {
|
|
1233
|
+
affectedNodes: impactedIds.size,
|
|
1234
|
+
depths: impactedByDepth.length,
|
|
1235
|
+
unresolvedNodes,
|
|
1236
|
+
lowerConfidencePaths,
|
|
1237
|
+
diagnostics: relevantDiagnostics.length,
|
|
1238
|
+
},
|
|
1239
|
+
impactedByDepth,
|
|
1240
|
+
diagnostics: relevantDiagnostics,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Build a knowledge_gap suggestion when a search returns no results.
|
|
1245
|
+
* Derives suggested_page, suggested_title, type, and tags from the query
|
|
1246
|
+
* using the same heuristics as wiki_write auto-classification.
|
|
1247
|
+
*
|
|
1248
|
+
* @param forceType When the caller searched with a type filter, use that type
|
|
1249
|
+
* instead of the classify() guess (avoids inconsistency).
|
|
1250
|
+
*/
|
|
1251
|
+
function buildKnowledgeGap(query, wiki, forceType) {
|
|
1252
|
+
const classification = wiki.classify(query);
|
|
1253
|
+
const type = forceType ?? classification.type;
|
|
1254
|
+
// Title-case each word of the query
|
|
1255
|
+
const suggestedTitle = query
|
|
1256
|
+
.split(/\s+/)
|
|
1257
|
+
.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
|
|
1258
|
+
.join(" ");
|
|
1259
|
+
// Slug: lowercase ASCII, collapse spaces to hyphens, max 50 chars.
|
|
1260
|
+
// Falls back to a hex digest of the query for non-ASCII (CJK etc.) text.
|
|
1261
|
+
let slug = query
|
|
1262
|
+
.toLowerCase()
|
|
1263
|
+
.replace(/[^a-z0-9\s]/g, "")
|
|
1264
|
+
.trim()
|
|
1265
|
+
.replace(/\s+/g, "-")
|
|
1266
|
+
.replace(/-+/g, "-")
|
|
1267
|
+
.slice(0, 50)
|
|
1268
|
+
.replace(/-$/, "");
|
|
1269
|
+
if (!slug) {
|
|
1270
|
+
// Non-ASCII query (e.g. CJK) — use a short hash to avoid "concept-.md"
|
|
1271
|
+
let h = 0;
|
|
1272
|
+
for (let i = 0; i < query.length; i++)
|
|
1273
|
+
h = (Math.imul(31, h) + query.charCodeAt(i)) | 0;
|
|
1274
|
+
slug = (h >>> 0).toString(16).slice(0, 8);
|
|
1275
|
+
}
|
|
1276
|
+
const suggestedPage = `${type}-${slug}.md`;
|
|
1277
|
+
return {
|
|
1278
|
+
query,
|
|
1279
|
+
suggested_page: suggestedPage,
|
|
1280
|
+
suggested_title: suggestedTitle,
|
|
1281
|
+
suggested_type: type,
|
|
1282
|
+
suggested_tags: classification.tags,
|
|
1283
|
+
hint: `No pages found for "${query}". Use wiki_write to create "${suggestedPage}".`,
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
/** Shared page-content reader used by wiki_search (read_top_n mode) and wiki_search_read. */
|
|
1287
|
+
function readPagesContent(wiki, paths, sectionFilter, perPageLimit, includeToc) {
|
|
1288
|
+
const pages = [];
|
|
1289
|
+
for (const pagePath of paths) {
|
|
1290
|
+
try {
|
|
1291
|
+
const page = wiki.read(pagePath);
|
|
1292
|
+
if (!page)
|
|
1293
|
+
throw new Error(`Page not found: ${pagePath}`);
|
|
1294
|
+
const fullPath = join(wiki.config.wikiDir, page.path);
|
|
1295
|
+
const raw = readFileSync(fullPath, "utf-8");
|
|
1296
|
+
if (sectionFilter) {
|
|
1297
|
+
const sections = splitSections(raw);
|
|
1298
|
+
const target = findSectionByHeading(sections, sectionFilter);
|
|
1299
|
+
if (!target) {
|
|
1300
|
+
pages.push({
|
|
1301
|
+
path: pagePath,
|
|
1302
|
+
content: null,
|
|
1303
|
+
error: `Section "${sectionFilter}" not found`,
|
|
1304
|
+
toc: buildToc(sections) || null,
|
|
1305
|
+
});
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
const targetIdx = sections.indexOf(target);
|
|
1309
|
+
let hasSubsections = false;
|
|
1310
|
+
const parts = [target.content];
|
|
1311
|
+
for (let i = targetIdx + 1; i < sections.length; i++) {
|
|
1312
|
+
const s = sections[i];
|
|
1313
|
+
if (s.level <= target.level && s.heading !== "")
|
|
1314
|
+
break;
|
|
1315
|
+
if (s.heading !== "")
|
|
1316
|
+
hasSubsections = true;
|
|
1317
|
+
parts.push(s.content);
|
|
1318
|
+
}
|
|
1319
|
+
const sectionText = parts.join("\n");
|
|
1320
|
+
const sectionLines = sectionText.split("\n");
|
|
1321
|
+
const truncated = sectionLines.length > perPageLimit;
|
|
1322
|
+
pages.push({
|
|
1323
|
+
path: pagePath,
|
|
1324
|
+
content: truncated ? sectionLines.slice(0, perPageLimit).join("\n") : sectionText,
|
|
1325
|
+
truncated,
|
|
1326
|
+
...(truncated ? { total_lines: sectionLines.length } : {}),
|
|
1327
|
+
...(truncated && hasSubsections ? { has_subsections: true } : {}),
|
|
1328
|
+
...(truncated && includeToc ? { toc: buildToc(sections) } : {}),
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
else {
|
|
1332
|
+
const lines = raw.split("\n");
|
|
1333
|
+
const truncated = lines.length > perPageLimit;
|
|
1334
|
+
pages.push({
|
|
1335
|
+
path: pagePath,
|
|
1336
|
+
content: truncated ? lines.slice(0, perPageLimit).join("\n") : raw,
|
|
1337
|
+
truncated,
|
|
1338
|
+
...(truncated ? { total_lines: lines.length } : {}),
|
|
1339
|
+
...(truncated && includeToc ? { toc: buildToc(splitSections(raw)) } : {}),
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
catch (err) {
|
|
1344
|
+
pages.push({
|
|
1345
|
+
path: pagePath,
|
|
1346
|
+
content: null,
|
|
1347
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
return pages;
|
|
1352
|
+
}
|
|
1353
|
+
export async function handleTool(wiki, name, args, opts) {
|
|
1354
|
+
switch (name) {
|
|
1355
|
+
// ═══ RAW LAYER ═══
|
|
1356
|
+
case "raw_add": {
|
|
1357
|
+
const result = wiki.rawAdd(args.filename, {
|
|
1358
|
+
content: args.content,
|
|
1359
|
+
sourcePath: args.source_path,
|
|
1360
|
+
sourceUrl: args.source_url,
|
|
1361
|
+
description: args.description,
|
|
1362
|
+
tags: args.tags,
|
|
1363
|
+
autoVersion: args.auto_version,
|
|
1364
|
+
pattern: args.pattern,
|
|
1365
|
+
});
|
|
1366
|
+
// Directory import returns array — no inline image for batch imports
|
|
1367
|
+
if (Array.isArray(result)) {
|
|
1368
|
+
return JSON.stringify({ ok: true, imported: result.length, documents: result }, null, 2);
|
|
1369
|
+
}
|
|
1370
|
+
const text = JSON.stringify({ ok: true, document: result }, null, 2);
|
|
1371
|
+
// For single image files, include image content block so agent can describe it
|
|
1372
|
+
const imgBlock = tryImageBlock(join(wiki.config.rawDir, result.path), result.mimeType ?? "");
|
|
1373
|
+
return imgBlock ? [{ type: "text", text }, imgBlock] : text;
|
|
1374
|
+
}
|
|
1375
|
+
case "raw_list": {
|
|
1376
|
+
const docs = wiki.rawList();
|
|
1377
|
+
return JSON.stringify({ documents: docs, count: docs.length }, null, 2);
|
|
1378
|
+
}
|
|
1379
|
+
case "raw_coverage": {
|
|
1380
|
+
const sortArg = args.sort;
|
|
1381
|
+
if (sortArg !== undefined && sortArg !== "newest" && sortArg !== "oldest" && sortArg !== "largest") {
|
|
1382
|
+
throw new Error(`Invalid sort: ${String(sortArg)}. Must be 'newest', 'oldest', or 'largest'.`);
|
|
1383
|
+
}
|
|
1384
|
+
const report = wiki.rawCoverage({
|
|
1385
|
+
limit: args.limit,
|
|
1386
|
+
sort: sortArg,
|
|
1387
|
+
tag: args.tag,
|
|
1388
|
+
});
|
|
1389
|
+
return JSON.stringify(report, null, 2);
|
|
1390
|
+
}
|
|
1391
|
+
case "raw_versions": {
|
|
1392
|
+
const result = wiki.rawVersions(args.filename);
|
|
1393
|
+
return JSON.stringify({ versions: result.versions, latest: result.latest, count: result.versions.length }, null, 2);
|
|
1394
|
+
}
|
|
1395
|
+
case "raw_read": {
|
|
1396
|
+
const result = await wiki.rawRead(args.filename, {
|
|
1397
|
+
pages: args.pages,
|
|
1398
|
+
sheet: args.sheet,
|
|
1399
|
+
offset: args.offset,
|
|
1400
|
+
limit: args.limit,
|
|
1401
|
+
});
|
|
1402
|
+
if (!result)
|
|
1403
|
+
throw new Error(`Raw file not found: ${args.filename}`);
|
|
1404
|
+
if (result.binary) {
|
|
1405
|
+
if (result.imageData) {
|
|
1406
|
+
// Return text first (consistent with raw_add/raw_fetch), then image block
|
|
1407
|
+
return [
|
|
1408
|
+
{ type: "text", text: JSON.stringify({ meta: result.meta, binary: true }, null, 2) },
|
|
1409
|
+
{ type: "image", data: result.imageData.data, mimeType: result.imageData.mimeType },
|
|
1410
|
+
];
|
|
1411
|
+
}
|
|
1412
|
+
return JSON.stringify({
|
|
1413
|
+
meta: result.meta,
|
|
1414
|
+
binary: true,
|
|
1415
|
+
note: result.note ?? `Binary file (${result.meta?.mimeType ?? "unknown type"}, ${result.meta?.size != null ? result.meta.size + " bytes" : "unknown size"}). Content cannot be read as text. Use the file path directly if you need to process it.`,
|
|
1416
|
+
}, null, 2);
|
|
1417
|
+
}
|
|
1418
|
+
const content = result.content;
|
|
1419
|
+
// Paginated responses (sheet/offset/pages specified) skip the 10K truncation
|
|
1420
|
+
const isPaginated = result.paginationMeta !== undefined;
|
|
1421
|
+
const finalContent = isPaginated
|
|
1422
|
+
? content
|
|
1423
|
+
: content.length > 10000
|
|
1424
|
+
? content.slice(0, 10000) + "\n\n... (truncated, " + content.length + " chars total)"
|
|
1425
|
+
: content;
|
|
1426
|
+
return JSON.stringify({
|
|
1427
|
+
meta: result.meta,
|
|
1428
|
+
binary: false,
|
|
1429
|
+
content: finalContent,
|
|
1430
|
+
...(result.paginationMeta ? { pagination: result.paginationMeta } : {}),
|
|
1431
|
+
}, null, 2);
|
|
1432
|
+
}
|
|
1433
|
+
// raw_verify removed — use wiki_lint instead (includes SHA-256 checks)
|
|
1434
|
+
case "raw_fetch": {
|
|
1435
|
+
const doc = await wiki.rawFetch(args.url, {
|
|
1436
|
+
filename: args.filename,
|
|
1437
|
+
description: args.description,
|
|
1438
|
+
tags: args.tags,
|
|
1439
|
+
});
|
|
1440
|
+
const text = JSON.stringify({ ok: true, document: doc }, null, 2);
|
|
1441
|
+
// For image files, include image content block so agent can describe it
|
|
1442
|
+
const imgBlock = tryImageBlock(join(wiki.config.rawDir, doc.path), doc.mimeType ?? "");
|
|
1443
|
+
return imgBlock ? [{ type: "text", text }, imgBlock] : text;
|
|
1444
|
+
}
|
|
1445
|
+
// ═══ ATLASSIAN ═══
|
|
1446
|
+
case "raw_import_confluence": {
|
|
1447
|
+
const result = await wiki.confluenceImport(args.url, {
|
|
1448
|
+
recursive: args.recursive,
|
|
1449
|
+
depth: args.depth,
|
|
1450
|
+
authEnv: args.auth_env,
|
|
1451
|
+
});
|
|
1452
|
+
return JSON.stringify({
|
|
1453
|
+
ok: true,
|
|
1454
|
+
pages: result.pages,
|
|
1455
|
+
files: result.files,
|
|
1456
|
+
tree: result.tree,
|
|
1457
|
+
}, null, 2);
|
|
1458
|
+
}
|
|
1459
|
+
case "raw_import_jira": {
|
|
1460
|
+
const result = await wiki.jiraImport(args.url, {
|
|
1461
|
+
includeComments: args.include_comments,
|
|
1462
|
+
includeAttachments: args.include_attachments,
|
|
1463
|
+
includeLinks: args.include_links,
|
|
1464
|
+
linkDepth: args.link_depth,
|
|
1465
|
+
authEnv: args.auth_env,
|
|
1466
|
+
});
|
|
1467
|
+
return JSON.stringify({
|
|
1468
|
+
ok: true,
|
|
1469
|
+
issueKey: result.issueKey,
|
|
1470
|
+
summary: result.summary,
|
|
1471
|
+
files: result.files,
|
|
1472
|
+
linkedIssues: result.linkedIssues,
|
|
1473
|
+
importedCount: result.importedCount,
|
|
1474
|
+
}, null, 2);
|
|
1475
|
+
}
|
|
1476
|
+
// ═══ WIKI LAYER ═══
|
|
1477
|
+
case "wiki_read": {
|
|
1478
|
+
// ── Multi-page read ──────────────────────────────────────
|
|
1479
|
+
const multiPaths = args.pages;
|
|
1480
|
+
if (multiPaths && multiPaths.length > 0) {
|
|
1481
|
+
const readOnePage = (pagePath) => {
|
|
1482
|
+
const p = wiki.read(pagePath);
|
|
1483
|
+
if (!p)
|
|
1484
|
+
return { page: pagePath, not_found: true };
|
|
1485
|
+
const fullPath = join(wiki.config.wikiDir, p.path);
|
|
1486
|
+
let raw;
|
|
1487
|
+
try {
|
|
1488
|
+
raw = readFileSync(fullPath, "utf-8");
|
|
1489
|
+
}
|
|
1490
|
+
catch {
|
|
1491
|
+
return { page: pagePath, not_found: true };
|
|
1492
|
+
}
|
|
1493
|
+
const lines = raw.split("\n");
|
|
1494
|
+
const total = lines.length;
|
|
1495
|
+
const DEFAULT_LIMIT = 200;
|
|
1496
|
+
const MAX_LIMIT = 500;
|
|
1497
|
+
const offset2 = Math.max(0, Math.floor(args.offset ?? 0));
|
|
1498
|
+
const limit2 = Math.min(MAX_LIMIT, Math.max(1, Math.floor(args.limit ?? DEFAULT_LIMIT)));
|
|
1499
|
+
const slice = lines.slice(offset2, offset2 + limit2);
|
|
1500
|
+
const truncated = offset2 + limit2 < total;
|
|
1501
|
+
if (!truncated && offset2 === 0)
|
|
1502
|
+
return { page: pagePath, content: raw };
|
|
1503
|
+
const toc = buildToc(splitSections(raw));
|
|
1504
|
+
return { page: pagePath, content: slice.join("\n"), offset: offset2, lines_returned: slice.length, total_lines: total, truncated, next_offset: truncated ? offset2 + limit2 : null, toc: toc || null };
|
|
1505
|
+
};
|
|
1506
|
+
const pages2 = multiPaths.map(readOnePage);
|
|
1507
|
+
return JSON.stringify({ pages: pages2, count: pages2.length }, null, 2);
|
|
1508
|
+
}
|
|
1509
|
+
// ── Single-page read (original behaviour) ───────────────
|
|
1510
|
+
if (!args.page)
|
|
1511
|
+
throw new Error("wiki_read requires 'page' or 'pages'");
|
|
1512
|
+
const page = wiki.read(args.page);
|
|
1513
|
+
if (!page)
|
|
1514
|
+
throw new Error(`Page not found: ${args.page}`);
|
|
1515
|
+
const fullPath = join(wiki.config.wikiDir, page.path);
|
|
1516
|
+
let raw;
|
|
1517
|
+
try {
|
|
1518
|
+
raw = readFileSync(fullPath, "utf-8");
|
|
1519
|
+
}
|
|
1520
|
+
catch {
|
|
1521
|
+
throw new Error(`Page not found: ${args.page}`);
|
|
1522
|
+
}
|
|
1523
|
+
// ── Section-based read ──────────────────────────────────
|
|
1524
|
+
if (args.section) {
|
|
1525
|
+
const sections = splitSections(raw);
|
|
1526
|
+
const target = findSectionByHeading(sections, args.section);
|
|
1527
|
+
if (!target) {
|
|
1528
|
+
const toc = buildToc(sections);
|
|
1529
|
+
throw new Error(`Section "${args.section}" not found in ${args.page}.\nAvailable sections:\n${toc}`);
|
|
1530
|
+
}
|
|
1531
|
+
// Include sub-sections (higher heading level) that follow immediately
|
|
1532
|
+
const targetIdx = sections.indexOf(target);
|
|
1533
|
+
const parts = [target.content];
|
|
1534
|
+
for (let i = targetIdx + 1; i < sections.length; i++) {
|
|
1535
|
+
const s = sections[i];
|
|
1536
|
+
if (s.level <= target.level && s.heading !== "")
|
|
1537
|
+
break;
|
|
1538
|
+
parts.push(s.content);
|
|
1539
|
+
}
|
|
1540
|
+
const content = parts.join("\n");
|
|
1541
|
+
return JSON.stringify({
|
|
1542
|
+
section: target.heading,
|
|
1543
|
+
content,
|
|
1544
|
+
total_lines: content.split("\n").length,
|
|
1545
|
+
}, null, 2);
|
|
1546
|
+
}
|
|
1547
|
+
// ── Line-based read (fallback / small pages) ────────────
|
|
1548
|
+
const lines = raw.split("\n");
|
|
1549
|
+
const total = lines.length;
|
|
1550
|
+
const DEFAULT_LIMIT = 200;
|
|
1551
|
+
const MAX_LIMIT = 500;
|
|
1552
|
+
const offset = Math.max(0, Math.floor(args.offset ?? 0));
|
|
1553
|
+
const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(args.limit ?? DEFAULT_LIMIT)));
|
|
1554
|
+
const slice = lines.slice(offset, offset + limit);
|
|
1555
|
+
const truncated = offset + limit < total;
|
|
1556
|
+
if (!truncated && offset === 0) {
|
|
1557
|
+
// Small page — return as plain text for backwards compatibility
|
|
1558
|
+
return raw;
|
|
1559
|
+
}
|
|
1560
|
+
// Large page — include TOC so agent can navigate by section
|
|
1561
|
+
const toc = buildToc(splitSections(raw));
|
|
1562
|
+
return JSON.stringify({
|
|
1563
|
+
content: slice.join("\n"),
|
|
1564
|
+
offset,
|
|
1565
|
+
lines_returned: slice.length,
|
|
1566
|
+
total_lines: total,
|
|
1567
|
+
truncated,
|
|
1568
|
+
next_offset: truncated ? offset + limit : null,
|
|
1569
|
+
toc: toc || null,
|
|
1570
|
+
}, null, 2);
|
|
1571
|
+
}
|
|
1572
|
+
case "wiki_write": {
|
|
1573
|
+
// Auto-classify if type/tags are missing
|
|
1574
|
+
const enrichedContent = wiki.autoClassifyContent(args.content);
|
|
1575
|
+
// Auto-link: inject [[slug|text]] for mentioned page titles in body
|
|
1576
|
+
const { content: linkedContent, linksAdded } = wiki.config.autoLink.enabled
|
|
1577
|
+
? wiki.autoLink(enrichedContent, args.page)
|
|
1578
|
+
: { content: enrichedContent, linksAdded: 0 };
|
|
1579
|
+
// Auto-route to matching topic subdirectory
|
|
1580
|
+
const resolvedPage = wiki.resolvePagePath(args.page, linkedContent);
|
|
1581
|
+
const writtenContent = wiki.write(resolvedPage, linkedContent, args.source);
|
|
1582
|
+
// Auto-rebuild indexes (skipped when called from batch — batch rebuilds once at end)
|
|
1583
|
+
if (!opts?.skipRebuild)
|
|
1584
|
+
wiki.rebuildIndex();
|
|
1585
|
+
// Update vector embedding if hybrid search is enabled
|
|
1586
|
+
if (wiki.config.search.hybrid) {
|
|
1587
|
+
await wiki.updatePageVector(resolvedPage).catch(() => { });
|
|
1588
|
+
}
|
|
1589
|
+
const classification = wiki.classify(linkedContent);
|
|
1590
|
+
const writeResult = {
|
|
1591
|
+
ok: true,
|
|
1592
|
+
page: resolvedPage,
|
|
1593
|
+
routed: resolvedPage !== args.page,
|
|
1594
|
+
autoClassified: { type: classification.type, tags: classification.tags, confidence: classification.confidence },
|
|
1595
|
+
autoLinked: linksAdded,
|
|
1596
|
+
};
|
|
1597
|
+
if (args.return_content) {
|
|
1598
|
+
// Return the content actually written to disk (includes injected timestamps)
|
|
1599
|
+
writeResult.content = writtenContent;
|
|
1600
|
+
}
|
|
1601
|
+
return JSON.stringify(writeResult);
|
|
1602
|
+
}
|
|
1603
|
+
case "wiki_delete": {
|
|
1604
|
+
const existed = wiki.delete(args.page);
|
|
1605
|
+
if (existed && !opts?.skipRebuild)
|
|
1606
|
+
wiki.rebuildIndex();
|
|
1607
|
+
// Remove vector embedding if hybrid search is enabled
|
|
1608
|
+
if (existed && wiki.config.search.hybrid) {
|
|
1609
|
+
wiki.removePageVector(args.page);
|
|
1610
|
+
}
|
|
1611
|
+
return JSON.stringify({ ok: existed, page: args.page });
|
|
1612
|
+
}
|
|
1613
|
+
case "wiki_list": {
|
|
1614
|
+
const pages = wiki.list(args.type, args.tag);
|
|
1615
|
+
return JSON.stringify({ pages, count: pages.length }, null, 2);
|
|
1616
|
+
}
|
|
1617
|
+
case "wiki_search": {
|
|
1618
|
+
const searchQuery = args.query;
|
|
1619
|
+
const searchLimit = args.limit ?? 10;
|
|
1620
|
+
const filterType = args.type;
|
|
1621
|
+
const filterTags = args.tags;
|
|
1622
|
+
// Fetch extra candidates so post-filter doesn't starve results
|
|
1623
|
+
const fetchLimit = (filterType || filterTags?.length) ? searchLimit * 3 : searchLimit;
|
|
1624
|
+
const rawResults = wiki.config.search.hybrid
|
|
1625
|
+
? await wiki.searchHybrid(searchQuery, fetchLimit)
|
|
1626
|
+
: wiki.search(searchQuery, fetchLimit);
|
|
1627
|
+
// Apply type / tags filters (post-ranking — BM25 scores are unaffected)
|
|
1628
|
+
const results = (filterType || filterTags?.length)
|
|
1629
|
+
? rawResults.filter(r => {
|
|
1630
|
+
const p = wiki.read(r.path);
|
|
1631
|
+
if (!p)
|
|
1632
|
+
return false;
|
|
1633
|
+
if (filterType && p.type !== filterType)
|
|
1634
|
+
return false;
|
|
1635
|
+
if (filterTags?.length && !filterTags.some(t => p.tags.includes(t)))
|
|
1636
|
+
return false;
|
|
1637
|
+
return true;
|
|
1638
|
+
}).slice(0, searchLimit)
|
|
1639
|
+
: rawResults;
|
|
1640
|
+
const envelope = buildSearchEnvelope(results, searchQuery);
|
|
1641
|
+
// Knowledge gap: guide the agent when the search finds nothing
|
|
1642
|
+
if (results.length === 0) {
|
|
1643
|
+
return JSON.stringify({
|
|
1644
|
+
results: [],
|
|
1645
|
+
count: 0,
|
|
1646
|
+
knowledge_gap: buildKnowledgeGap(searchQuery, wiki, filterType),
|
|
1647
|
+
evidence: envelope,
|
|
1648
|
+
}, null, 2);
|
|
1649
|
+
}
|
|
1650
|
+
// Combined search+read mode (read_top_n) — supersedes include_content when both are set
|
|
1651
|
+
if (args.read_top_n != null) {
|
|
1652
|
+
const readTopN = Math.min(Math.max(1, Math.floor(args.read_top_n)), 10);
|
|
1653
|
+
const sectionFilter = args.section;
|
|
1654
|
+
const perPageLimit = Math.min(500, Math.max(1, Math.floor(args.per_page_limit ?? 200)));
|
|
1655
|
+
const includeToc = args.include_toc ?? false;
|
|
1656
|
+
// Deduplicate — preserve score order, first occurrence wins
|
|
1657
|
+
const seen = new Set();
|
|
1658
|
+
const uniquePaths = [];
|
|
1659
|
+
for (const r of results) {
|
|
1660
|
+
if (!seen.has(r.path)) {
|
|
1661
|
+
seen.add(r.path);
|
|
1662
|
+
uniquePaths.push(r.path);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
const toRead = uniquePaths.slice(0, readTopN);
|
|
1666
|
+
const nextReads = uniquePaths.slice(readTopN);
|
|
1667
|
+
const pages = readPagesContent(wiki, toRead, sectionFilter, perPageLimit, includeToc);
|
|
1668
|
+
// Downgrade envelope based on the top read page's metadata.
|
|
1669
|
+
const topPage = toRead.length > 0 ? wiki.read(toRead[0]) : null;
|
|
1670
|
+
const readEnvelope = topPage
|
|
1671
|
+
? downgradeForReadPage(envelope, {
|
|
1672
|
+
sources: topPage.sources,
|
|
1673
|
+
synthesis: topPage.frontmatter.synthesis === true,
|
|
1674
|
+
legacyUnsupported: topPage.frontmatter.legacyUnsupported === true,
|
|
1675
|
+
lastEditISO: topPage.updated,
|
|
1676
|
+
})
|
|
1677
|
+
: envelope;
|
|
1678
|
+
return JSON.stringify({
|
|
1679
|
+
results,
|
|
1680
|
+
count: results.length,
|
|
1681
|
+
pages,
|
|
1682
|
+
pagesRead: pages.length,
|
|
1683
|
+
nextReads,
|
|
1684
|
+
evidence: readEnvelope,
|
|
1685
|
+
}, null, 2);
|
|
1686
|
+
}
|
|
1687
|
+
if (!args.include_content) {
|
|
1688
|
+
return JSON.stringify({ results, count: results.length, evidence: envelope }, null, 2);
|
|
1689
|
+
}
|
|
1690
|
+
// Inline page content — eliminates follow-up wiki_read calls
|
|
1691
|
+
const inlineBudget = args.inline_budget != null ? args.inline_budget : Infinity;
|
|
1692
|
+
let budgetRemaining = inlineBudget;
|
|
1693
|
+
const enriched = results.map((r) => {
|
|
1694
|
+
try {
|
|
1695
|
+
const fullPath = join(wiki.config.wikiDir, r.path);
|
|
1696
|
+
const raw = readFileSync(fullPath, "utf-8");
|
|
1697
|
+
if (r.section) {
|
|
1698
|
+
// Return the matched section only, capped at 200 lines
|
|
1699
|
+
const sections = splitSections(raw);
|
|
1700
|
+
const target = findSectionByHeading(sections, r.section);
|
|
1701
|
+
if (target) {
|
|
1702
|
+
const targetIdx = sections.indexOf(target);
|
|
1703
|
+
let hasSubsections = false;
|
|
1704
|
+
const parts = [target.content];
|
|
1705
|
+
for (let i = targetIdx + 1; i < sections.length; i++) {
|
|
1706
|
+
const s = sections[i];
|
|
1707
|
+
if (s.level <= target.level && s.heading !== "")
|
|
1708
|
+
break;
|
|
1709
|
+
if (s.heading !== "")
|
|
1710
|
+
hasSubsections = true;
|
|
1711
|
+
parts.push(s.content);
|
|
1712
|
+
}
|
|
1713
|
+
const sectionText = parts.join("\n");
|
|
1714
|
+
const sectionLines = sectionText.split("\n");
|
|
1715
|
+
const sectionTruncated = sectionLines.length > 200;
|
|
1716
|
+
const content = sectionTruncated ? sectionLines.slice(0, 200).join("\n") : sectionText;
|
|
1717
|
+
if (content.length > budgetRemaining) {
|
|
1718
|
+
return { ...r, budget_exceeded: true };
|
|
1719
|
+
}
|
|
1720
|
+
budgetRemaining -= content.length;
|
|
1721
|
+
return {
|
|
1722
|
+
...r,
|
|
1723
|
+
content,
|
|
1724
|
+
...(sectionTruncated ? { truncated: true, total_lines: sectionLines.length } : {}),
|
|
1725
|
+
...(sectionTruncated && hasSubsections ? { has_subsections: true } : {}),
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
// No section match — return first 200 lines
|
|
1730
|
+
const lines = raw.split("\n");
|
|
1731
|
+
const truncated = lines.length > 200;
|
|
1732
|
+
const content = truncated ? lines.slice(0, 200).join("\n") : raw;
|
|
1733
|
+
if (content.length > budgetRemaining) {
|
|
1734
|
+
return { ...r, budget_exceeded: true };
|
|
1735
|
+
}
|
|
1736
|
+
budgetRemaining -= content.length;
|
|
1737
|
+
return {
|
|
1738
|
+
...r,
|
|
1739
|
+
content,
|
|
1740
|
+
...(truncated ? { truncated: true, total_lines: lines.length } : {}),
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
catch {
|
|
1744
|
+
return { ...r, content: null };
|
|
1745
|
+
}
|
|
1746
|
+
});
|
|
1747
|
+
return JSON.stringify({ results: enriched, count: enriched.length, evidence: envelope }, null, 2);
|
|
1748
|
+
}
|
|
1749
|
+
case "wiki_search_read": {
|
|
1750
|
+
const query = args.query;
|
|
1751
|
+
const limit = args.limit ?? 10;
|
|
1752
|
+
const readTopN = Math.min(Math.max(1, Math.floor(args.readTopN ?? 3)), 10);
|
|
1753
|
+
const sectionFilter = args.section;
|
|
1754
|
+
const perPageLimit = Math.min(500, Math.max(1, Math.floor(args.perPageLimit ?? 200)));
|
|
1755
|
+
const includeToc = args.includeToc ?? false;
|
|
1756
|
+
// Step 1: Search
|
|
1757
|
+
const results = wiki.config.search.hybrid
|
|
1758
|
+
? await wiki.searchHybrid(query, limit)
|
|
1759
|
+
: wiki.search(query, limit);
|
|
1760
|
+
const envelope = buildSearchEnvelope(results, query);
|
|
1761
|
+
// Knowledge gap: guide the agent when the search finds nothing
|
|
1762
|
+
if (results.length === 0) {
|
|
1763
|
+
return JSON.stringify({
|
|
1764
|
+
results: [],
|
|
1765
|
+
pages: [],
|
|
1766
|
+
nextReads: [],
|
|
1767
|
+
count: 0,
|
|
1768
|
+
pagesRead: 0,
|
|
1769
|
+
knowledge_gap: buildKnowledgeGap(query, wiki),
|
|
1770
|
+
evidence: envelope,
|
|
1771
|
+
}, null, 2);
|
|
1772
|
+
}
|
|
1773
|
+
// Deduplicate — preserve score order, first occurrence wins
|
|
1774
|
+
const seen = new Set();
|
|
1775
|
+
const uniquePaths = [];
|
|
1776
|
+
for (const r of results) {
|
|
1777
|
+
if (!seen.has(r.path)) {
|
|
1778
|
+
seen.add(r.path);
|
|
1779
|
+
uniquePaths.push(r.path);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
const toRead = uniquePaths.slice(0, readTopN);
|
|
1783
|
+
const nextReads = uniquePaths.slice(readTopN);
|
|
1784
|
+
const pages = readPagesContent(wiki, toRead, sectionFilter, perPageLimit, includeToc);
|
|
1785
|
+
// Downgrade envelope based on the top read page's metadata.
|
|
1786
|
+
const topPage = toRead.length > 0 ? wiki.read(toRead[0]) : null;
|
|
1787
|
+
const readEnvelope = topPage
|
|
1788
|
+
? downgradeForReadPage(envelope, {
|
|
1789
|
+
sources: topPage.sources,
|
|
1790
|
+
synthesis: topPage.frontmatter.synthesis === true,
|
|
1791
|
+
legacyUnsupported: topPage.frontmatter.legacyUnsupported === true,
|
|
1792
|
+
lastEditISO: topPage.updated,
|
|
1793
|
+
})
|
|
1794
|
+
: envelope;
|
|
1795
|
+
return JSON.stringify({
|
|
1796
|
+
results,
|
|
1797
|
+
count: results.length,
|
|
1798
|
+
pages,
|
|
1799
|
+
pagesRead: pages.length,
|
|
1800
|
+
nextReads,
|
|
1801
|
+
evidence: readEnvelope,
|
|
1802
|
+
}, null, 2);
|
|
1803
|
+
}
|
|
1804
|
+
case "wiki_lint": {
|
|
1805
|
+
const applyFixes = args.apply_fixes ?? false;
|
|
1806
|
+
const report = wiki.lint(applyFixes);
|
|
1807
|
+
return JSON.stringify(report, null, 2);
|
|
1808
|
+
}
|
|
1809
|
+
// wiki_log removed — use wiki_read("log.md") instead
|
|
1810
|
+
case "wiki_init": {
|
|
1811
|
+
const path = args.path ?? ".";
|
|
1812
|
+
const ws = args.workspace;
|
|
1813
|
+
Wiki.init(path, ws);
|
|
1814
|
+
return JSON.stringify({
|
|
1815
|
+
ok: true,
|
|
1816
|
+
configRoot: path,
|
|
1817
|
+
workspace: ws ?? path,
|
|
1818
|
+
message: ws
|
|
1819
|
+
? `Knowledge base initialized. Config at ${path}, data at ${ws}`
|
|
1820
|
+
: `Knowledge base initialized at ${path} with wiki/, raw/, schemas/`,
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
case "wiki_config": {
|
|
1824
|
+
const cfg = wiki.config;
|
|
1825
|
+
const schemas = wiki.schemas();
|
|
1826
|
+
const searchInfo = { ...cfg.search };
|
|
1827
|
+
if (cfg.search.hybrid) {
|
|
1828
|
+
searchInfo.vectorCount = wiki.getVectorCount();
|
|
1829
|
+
}
|
|
1830
|
+
return JSON.stringify({
|
|
1831
|
+
configRoot: cfg.configRoot,
|
|
1832
|
+
workspace: cfg.workspace,
|
|
1833
|
+
wikiDir: cfg.wikiDir,
|
|
1834
|
+
rawDir: cfg.rawDir,
|
|
1835
|
+
schemasDir: cfg.schemasDir,
|
|
1836
|
+
lint: cfg.lint,
|
|
1837
|
+
search: searchInfo,
|
|
1838
|
+
separateWorkspace: cfg.configRoot !== cfg.workspace,
|
|
1839
|
+
schemas: schemas.map(s => s.name),
|
|
1840
|
+
}, null, 2);
|
|
1841
|
+
}
|
|
1842
|
+
// wiki_schemas removed — merged into wiki_config
|
|
1843
|
+
case "wiki_rebuild": {
|
|
1844
|
+
// Rebuild code knowledge graphs for all registered plugins FIRST,
|
|
1845
|
+
// so that generated pages (system-map.md, call-graph.md) are included
|
|
1846
|
+
// in the index and timeline built afterwards. This matches the batch
|
|
1847
|
+
// handler ordering (graph pages → index/timeline).
|
|
1848
|
+
let graphStats;
|
|
1849
|
+
for (const plugin of listPlugins()) {
|
|
1850
|
+
const parsedDir = join(wiki.config.rawDir, "parsed", plugin.id);
|
|
1851
|
+
if (plugin.rebuildAggregatePages) {
|
|
1852
|
+
for (const page of plugin.rebuildAggregatePages(parsedDir)) {
|
|
1853
|
+
wiki.write(page.path, page.content);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
if (plugin.buildKnowledgeGraph) {
|
|
1857
|
+
const graphResult = plugin.buildKnowledgeGraph(parsedDir);
|
|
1858
|
+
if (graphResult) {
|
|
1859
|
+
wiki.rawAddParsedArtifact(`parsed/${plugin.id}/knowledge-graph.json`, JSON.stringify(graphResult.serialized, null, 2));
|
|
1860
|
+
for (const page of graphResult.wikiPages) {
|
|
1861
|
+
wiki.write(page.path, page.content);
|
|
1862
|
+
}
|
|
1863
|
+
const ser = graphResult.serialized;
|
|
1864
|
+
graphStats = {
|
|
1865
|
+
plugins: (graphStats?.plugins ?? 0) + 1,
|
|
1866
|
+
nodes: ser.nodes?.length ?? 0,
|
|
1867
|
+
edges: ser.edges?.length ?? 0,
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
if (plugin.buildDerivedArtifacts) {
|
|
1872
|
+
const derived = plugin.buildDerivedArtifacts(parsedDir);
|
|
1873
|
+
if (derived) {
|
|
1874
|
+
applyDerivedArtifacts(wiki, plugin.id, derived);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
// Now build page cache AFTER graph pages are written, so they are
|
|
1879
|
+
// included in the index and timeline.
|
|
1880
|
+
const pageCache = wiki.buildPageCache();
|
|
1881
|
+
wiki.rebuildIndex(pageCache);
|
|
1882
|
+
// Yield event loop so MCP transport can respond to client pings.
|
|
1883
|
+
await new Promise((r) => setImmediate(r));
|
|
1884
|
+
wiki.rebuildTimeline(pageCache);
|
|
1885
|
+
// Rebuild vector index if hybrid search is enabled
|
|
1886
|
+
let vectorStats;
|
|
1887
|
+
if (wiki.config.search.hybrid) {
|
|
1888
|
+
vectorStats = await wiki.rebuildVectorIndex().catch(() => undefined);
|
|
1889
|
+
}
|
|
1890
|
+
const parts = ["Index and timeline rebuilt"];
|
|
1891
|
+
if (graphStats) {
|
|
1892
|
+
parts.push(`Knowledge graph: ${graphStats.nodes} nodes, ${graphStats.edges} edges`);
|
|
1893
|
+
}
|
|
1894
|
+
if (vectorStats) {
|
|
1895
|
+
parts.push(`Vector index: ${vectorStats.pagesProcessed} pages embedded${vectorStats.errors > 0 ? `, ${vectorStats.errors} errors` : ""}`);
|
|
1896
|
+
}
|
|
1897
|
+
return JSON.stringify({ ok: true, message: parts.join(". ") + "." });
|
|
1898
|
+
}
|
|
1899
|
+
// wiki_classify removed — wiki_write auto-classifies
|
|
1900
|
+
// wiki_synthesize removed — agent can wiki_read multiple pages
|
|
1901
|
+
case "code_parse": {
|
|
1902
|
+
const filePath = args.path;
|
|
1903
|
+
const plugin = getPluginForFile(filePath);
|
|
1904
|
+
if (!plugin) {
|
|
1905
|
+
const supported = listPlugins().flatMap((p) => p.extensions).join(", ");
|
|
1906
|
+
throw new Error(`Unsupported file type: ${filePath}. Supported extensions: ${supported}`);
|
|
1907
|
+
}
|
|
1908
|
+
const rawResult = await wiki.rawRead(filePath);
|
|
1909
|
+
if (!rawResult || rawResult.content === null) {
|
|
1910
|
+
throw new Error(`Cannot read raw/${filePath}`);
|
|
1911
|
+
}
|
|
1912
|
+
// All dispatch goes through the plugin interface
|
|
1913
|
+
const ast = plugin.parse(rawResult.content, filePath);
|
|
1914
|
+
const normalized = plugin.normalize(ast);
|
|
1915
|
+
const summary = summarizeModel(normalized);
|
|
1916
|
+
const wikiPages = plugin.generateWikiPages(normalized, filePath, ast);
|
|
1917
|
+
// Persist parsed artifacts
|
|
1918
|
+
const stem = filePath.replace(/\.[^.]+$/, "");
|
|
1919
|
+
const lang = plugin.id;
|
|
1920
|
+
wiki.rawAddParsedArtifact(`parsed/${lang}/${stem}.ast.json`, JSON.stringify(ast, null, 2));
|
|
1921
|
+
wiki.rawAddParsedArtifact(`parsed/${lang}/${stem}.normalized.json`, JSON.stringify(normalized, null, 2));
|
|
1922
|
+
wiki.rawAddParsedArtifact(`parsed/${lang}/${stem}.summary.json`, JSON.stringify(summary, null, 2));
|
|
1923
|
+
// Language-specific model (richer than normalized — e.g. COBOL PIC clauses)
|
|
1924
|
+
if (plugin.extractLanguageModel) {
|
|
1925
|
+
const langModel = plugin.extractLanguageModel(ast);
|
|
1926
|
+
wiki.rawAddParsedArtifact(`parsed/${lang}/${stem}.model.json`, JSON.stringify(langModel, null, 2));
|
|
1927
|
+
}
|
|
1928
|
+
// Write wiki pages
|
|
1929
|
+
const writtenPages = [];
|
|
1930
|
+
for (const page of wikiPages) {
|
|
1931
|
+
wiki.write(page.path, page.content, `raw/${filePath}`);
|
|
1932
|
+
writtenPages.push(page.path);
|
|
1933
|
+
}
|
|
1934
|
+
// Rebuild aggregate pages (e.g. call graph) from all parsed models
|
|
1935
|
+
// Skipped when called from batch — batch rebuilds once at end.
|
|
1936
|
+
if (plugin.rebuildAggregatePages && !opts?.skipGraphRebuild) {
|
|
1937
|
+
const parsedDir = join(wiki.config.rawDir, "parsed", lang);
|
|
1938
|
+
const aggPages = plugin.rebuildAggregatePages(parsedDir);
|
|
1939
|
+
for (const page of aggPages) {
|
|
1940
|
+
wiki.write(page.path, page.content);
|
|
1941
|
+
writtenPages.push(page.path);
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
// Optional variable trace
|
|
1945
|
+
const traceVar = args.trace_variable;
|
|
1946
|
+
let variableTrace;
|
|
1947
|
+
if (traceVar && plugin.traceVariable) {
|
|
1948
|
+
variableTrace = plugin.traceVariable(ast, traceVar);
|
|
1949
|
+
}
|
|
1950
|
+
const artifacts = [
|
|
1951
|
+
`raw/parsed/${lang}/${stem}.ast.json`,
|
|
1952
|
+
`raw/parsed/${lang}/${stem}.normalized.json`,
|
|
1953
|
+
`raw/parsed/${lang}/${stem}.summary.json`,
|
|
1954
|
+
];
|
|
1955
|
+
if (plugin.extractLanguageModel) {
|
|
1956
|
+
artifacts.push(`raw/parsed/${lang}/${stem}.model.json`);
|
|
1957
|
+
}
|
|
1958
|
+
// Build knowledge graph from all parsed models
|
|
1959
|
+
// Skipped when called from batch — batch rebuilds once at end.
|
|
1960
|
+
let graphSummary;
|
|
1961
|
+
if (plugin.buildKnowledgeGraph && !opts?.skipGraphRebuild) {
|
|
1962
|
+
const parsedDir = join(wiki.config.rawDir, "parsed", lang);
|
|
1963
|
+
const graphResult = plugin.buildKnowledgeGraph(parsedDir);
|
|
1964
|
+
if (graphResult) {
|
|
1965
|
+
wiki.rawAddParsedArtifact(`parsed/${lang}/knowledge-graph.json`, JSON.stringify(graphResult.serialized, null, 2));
|
|
1966
|
+
artifacts.push(`raw/parsed/${lang}/knowledge-graph.json`);
|
|
1967
|
+
for (const page of graphResult.wikiPages) {
|
|
1968
|
+
wiki.write(page.path, page.content);
|
|
1969
|
+
writtenPages.push(page.path);
|
|
1970
|
+
}
|
|
1971
|
+
const ser = graphResult.serialized;
|
|
1972
|
+
graphSummary = {
|
|
1973
|
+
nodes: ser.nodes?.length ?? 0,
|
|
1974
|
+
edges: ser.edges?.length ?? 0,
|
|
1975
|
+
diagnostics: ser.diagnostics?.length ?? 0,
|
|
1976
|
+
};
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
if (plugin.buildDerivedArtifacts && !opts?.skipGraphRebuild) {
|
|
1980
|
+
const parsedDir = join(wiki.config.rawDir, "parsed", lang);
|
|
1981
|
+
const derived = plugin.buildDerivedArtifacts(parsedDir);
|
|
1982
|
+
if (derived) {
|
|
1983
|
+
artifacts.push(...applyDerivedArtifacts(wiki, lang, derived));
|
|
1984
|
+
for (const page of derived.wikiPages) {
|
|
1985
|
+
writtenPages.push(page.path);
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
const output = {
|
|
1990
|
+
summary,
|
|
1991
|
+
normalizedModel: {
|
|
1992
|
+
units: normalized.units.length,
|
|
1993
|
+
procedures: normalized.procedures.length,
|
|
1994
|
+
symbols: normalized.symbols.length,
|
|
1995
|
+
relations: normalized.relations.length,
|
|
1996
|
+
},
|
|
1997
|
+
artifacts,
|
|
1998
|
+
wikiPages: writtenPages,
|
|
1999
|
+
};
|
|
2000
|
+
if (variableTrace) {
|
|
2001
|
+
output.variableTrace = variableTrace;
|
|
2002
|
+
}
|
|
2003
|
+
if (graphSummary) {
|
|
2004
|
+
output.knowledgeGraph = graphSummary;
|
|
2005
|
+
}
|
|
2006
|
+
return JSON.stringify(output, null, 2);
|
|
2007
|
+
}
|
|
2008
|
+
case "code_trace_variable": {
|
|
2009
|
+
const filePath = args.path;
|
|
2010
|
+
const varName = args.variable;
|
|
2011
|
+
if (!filePath)
|
|
2012
|
+
throw new Error("code_trace_variable requires 'path'");
|
|
2013
|
+
if (!varName)
|
|
2014
|
+
throw new Error("code_trace_variable requires 'variable'");
|
|
2015
|
+
const plugin = getPluginForFile(filePath);
|
|
2016
|
+
if (!plugin) {
|
|
2017
|
+
const supported = listPlugins().flatMap((p) => p.extensions).join(", ");
|
|
2018
|
+
throw new Error(`Unsupported file type: ${filePath}. Supported extensions: ${supported}`);
|
|
2019
|
+
}
|
|
2020
|
+
if (!plugin.traceVariable) {
|
|
2021
|
+
throw new Error(`Plugin "${plugin.id}" does not support variable tracing`);
|
|
2022
|
+
}
|
|
2023
|
+
const rawResult = await wiki.rawRead(filePath);
|
|
2024
|
+
if (!rawResult || rawResult.content === null) {
|
|
2025
|
+
throw new Error(`Cannot read raw/${filePath}`);
|
|
2026
|
+
}
|
|
2027
|
+
const ast = plugin.parse(rawResult.content, filePath);
|
|
2028
|
+
const refs = plugin.traceVariable(ast, varName);
|
|
2029
|
+
return JSON.stringify({ variable: varName, file: filePath, references: refs }, null, 2);
|
|
2030
|
+
}
|
|
2031
|
+
case "code_impact": {
|
|
2032
|
+
const language = (args.language ?? "cobol").trim().toLowerCase();
|
|
2033
|
+
const requestedNode = args.node_id;
|
|
2034
|
+
if (!requestedNode)
|
|
2035
|
+
throw new Error("code_impact requires 'node_id'");
|
|
2036
|
+
const kind = normalizeImpactKind(args.kind);
|
|
2037
|
+
const maxDepth = Math.min(50, Math.max(1, Math.floor(args.max_depth ?? 10)));
|
|
2038
|
+
const graph = await loadCompiledGraph(wiki, language);
|
|
2039
|
+
const sourceNode = resolveImpactNode(graph, requestedNode, kind);
|
|
2040
|
+
const response = buildImpactResponse(graph, sourceNode, maxDepth);
|
|
2041
|
+
return JSON.stringify(response, null, 2);
|
|
2042
|
+
}
|
|
2043
|
+
case "code_procedure_flow": {
|
|
2044
|
+
const filePath = args.path;
|
|
2045
|
+
if (!filePath)
|
|
2046
|
+
throw new Error("code_procedure_flow requires 'path'");
|
|
2047
|
+
const procedure = args.procedure;
|
|
2048
|
+
const procedureKind = normalizeProcedureKind(args.procedure_kind);
|
|
2049
|
+
const maxDepth = Math.min(50, Math.max(1, Math.floor(args.max_depth ?? 10)));
|
|
2050
|
+
const model = await loadParsedNormalizedModel(wiki, filePath);
|
|
2051
|
+
const response = buildProcedureFlowResponse(model, { path: filePath, procedure, procedureKind, maxDepth });
|
|
2052
|
+
return JSON.stringify(response, null, 2);
|
|
2053
|
+
}
|
|
2054
|
+
case "code_field_lineage": {
|
|
2055
|
+
const language = (args.language ?? "cobol").trim().toLowerCase();
|
|
2056
|
+
const fieldName = args.field_name;
|
|
2057
|
+
const qualifiedName = args.qualified_name;
|
|
2058
|
+
const copybook = args.copybook;
|
|
2059
|
+
const lineage = await loadFieldLineageArtifact(wiki, language);
|
|
2060
|
+
const response = buildFieldLineageResponse(lineage, {
|
|
2061
|
+
language,
|
|
2062
|
+
fieldName,
|
|
2063
|
+
qualifiedName,
|
|
2064
|
+
copybook,
|
|
2065
|
+
});
|
|
2066
|
+
return JSON.stringify(response, null, 2);
|
|
2067
|
+
}
|
|
2068
|
+
case "code_dataflow_edges": {
|
|
2069
|
+
const filePath = args.path;
|
|
2070
|
+
if (!filePath)
|
|
2071
|
+
throw new Error("code_dataflow_edges requires 'path'");
|
|
2072
|
+
const fromField = args.from?.toUpperCase();
|
|
2073
|
+
const toField = args.to?.toUpperCase();
|
|
2074
|
+
const startField = args.field?.toUpperCase();
|
|
2075
|
+
const transitive = args.transitive ?? false;
|
|
2076
|
+
const direction = args.direction ?? "downstream";
|
|
2077
|
+
const maxDepth = Math.min(50, Math.max(1, Math.floor(args.max_depth ?? 10)));
|
|
2078
|
+
const model = await loadParsedNormalizedModel(wiki, filePath);
|
|
2079
|
+
const allEdges = model.relations.filter((r) => r.type === "dataflow" || r.type === "call-param");
|
|
2080
|
+
const formatEdge = (r) => ({
|
|
2081
|
+
from: r.from,
|
|
2082
|
+
to: r.to,
|
|
2083
|
+
via: r.metadata?.via,
|
|
2084
|
+
line: r.loc.line,
|
|
2085
|
+
procedure: r.metadata?.procedure,
|
|
2086
|
+
section: r.metadata?.section,
|
|
2087
|
+
});
|
|
2088
|
+
if (transitive && startField) {
|
|
2089
|
+
const visited = new Set([startField]);
|
|
2090
|
+
let frontier = [startField];
|
|
2091
|
+
const levels = [];
|
|
2092
|
+
for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {
|
|
2093
|
+
const levelEdges = [];
|
|
2094
|
+
const nextFields = [];
|
|
2095
|
+
for (const field of frontier) {
|
|
2096
|
+
if (direction === "downstream" || direction === "both") {
|
|
2097
|
+
for (const e of allEdges.filter((e) => e.from === field)) {
|
|
2098
|
+
if (!visited.has(e.to)) {
|
|
2099
|
+
visited.add(e.to);
|
|
2100
|
+
nextFields.push(e.to);
|
|
2101
|
+
levelEdges.push(e);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
if (direction === "upstream" || direction === "both") {
|
|
2106
|
+
for (const e of allEdges.filter((e) => e.to === field)) {
|
|
2107
|
+
if (!visited.has(e.from)) {
|
|
2108
|
+
visited.add(e.from);
|
|
2109
|
+
nextFields.push(e.from);
|
|
2110
|
+
levelEdges.push(e);
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
if (levelEdges.length > 0) {
|
|
2116
|
+
levels.push({ depth, fields: nextFields, edges: levelEdges.map(formatEdge) });
|
|
2117
|
+
}
|
|
2118
|
+
frontier = nextFields;
|
|
2119
|
+
}
|
|
2120
|
+
const allVisited = [...visited].filter((f) => f !== startField);
|
|
2121
|
+
return JSON.stringify({
|
|
2122
|
+
file: filePath,
|
|
2123
|
+
field: startField,
|
|
2124
|
+
direction,
|
|
2125
|
+
transitive: true,
|
|
2126
|
+
total_fields: allVisited.length,
|
|
2127
|
+
total_edges: levels.reduce((s, l) => s + l.edges.length, 0),
|
|
2128
|
+
levels,
|
|
2129
|
+
}, null, 2);
|
|
2130
|
+
}
|
|
2131
|
+
let edges = allEdges;
|
|
2132
|
+
if (fromField)
|
|
2133
|
+
edges = edges.filter((r) => r.from === fromField);
|
|
2134
|
+
if (toField)
|
|
2135
|
+
edges = edges.filter((r) => r.to === toField);
|
|
2136
|
+
return JSON.stringify({
|
|
2137
|
+
file: filePath,
|
|
2138
|
+
total: edges.length,
|
|
2139
|
+
edges: edges.map(formatEdge),
|
|
2140
|
+
}, null, 2);
|
|
2141
|
+
}
|
|
2142
|
+
// ═══ KNOWLEDGE INGESTION ═══
|
|
2143
|
+
case "knowledge_ingest_batch": {
|
|
2144
|
+
const sourcePath = resolve(args.source_path);
|
|
2145
|
+
const pattern = args.pattern;
|
|
2146
|
+
const maxFiles = Math.min(Math.max(1, Math.floor(args.maxFiles ?? 100)), 1000);
|
|
2147
|
+
const topic = sanitizeTopic(args.topic ?? "general");
|
|
2148
|
+
const packLinesLimit = Math.max(50, Math.floor(args.packLines ?? 500));
|
|
2149
|
+
const chunkLinesLimit = Math.min(Math.max(10, Math.floor(args.chunkLines ?? 100)), packLinesLimit);
|
|
2150
|
+
const continueOnError = args.continueOnError ?? true;
|
|
2151
|
+
// Step 0: Validate source_path against allowed source directories
|
|
2152
|
+
const allowed = wiki.config.allowedSourceDirs.some(dir => sourcePath.startsWith(resolve(dir) + "/") || sourcePath === resolve(dir));
|
|
2153
|
+
if (!allowed) {
|
|
2154
|
+
throw new Error(`source_path "${args.source_path}" is outside allowed directories. ` +
|
|
2155
|
+
`Allowed: [${wiki.config.allowedSourceDirs.join(", ")}]. ` +
|
|
2156
|
+
`Configure security.allowed_source_dirs in .agent-wiki.yaml to widen access.`);
|
|
2157
|
+
}
|
|
2158
|
+
// Step 1: Scan
|
|
2159
|
+
let filePaths;
|
|
2160
|
+
const srcStat = statSync(sourcePath);
|
|
2161
|
+
if (srcStat.isDirectory()) {
|
|
2162
|
+
filePaths = walkSourceDir(sourcePath);
|
|
2163
|
+
if (pattern) {
|
|
2164
|
+
filePaths = filePaths.filter(f => matchSimpleGlob(f, pattern));
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
else {
|
|
2168
|
+
filePaths = [basename(sourcePath)];
|
|
2169
|
+
}
|
|
2170
|
+
filePaths = filePaths.slice(0, maxFiles);
|
|
2171
|
+
const matched = filePaths.length;
|
|
2172
|
+
let imported = 0, skipped = 0, extracted = 0, totalChunks = 0;
|
|
2173
|
+
const errors = [];
|
|
2174
|
+
// Extractable document formats
|
|
2175
|
+
const EXTRACTABLE = new Set([".pdf", ".docx", ".xlsx", ".pptx", ".html", ".htm"]);
|
|
2176
|
+
const TEXT_LIKE = (mime) => mime.startsWith("text/") || mime === "application/json" || mime === "application/xml"
|
|
2177
|
+
|| mime === "application/sql" || mime === "application/x-yaml";
|
|
2178
|
+
// Clean stale packs from previous runs of this topic (safePath prevents escape)
|
|
2179
|
+
const packsDir = safePath(wiki.config.rawDir, join("digest-packs", topic));
|
|
2180
|
+
if (existsSync(packsDir)) {
|
|
2181
|
+
for (const f of readdirSync(packsDir)) {
|
|
2182
|
+
if (f.startsWith("pack-") && f.endsWith(".md")) {
|
|
2183
|
+
const p = join(packsDir, f);
|
|
2184
|
+
rmSync(p, { force: true });
|
|
2185
|
+
const meta = p + ".meta.yaml";
|
|
2186
|
+
if (existsSync(meta))
|
|
2187
|
+
rmSync(meta, { force: true });
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
// Streaming packer — flushes packs as chunks arrive, bounded memory
|
|
2192
|
+
const packs = [];
|
|
2193
|
+
let packNum = 1;
|
|
2194
|
+
let currentPackLines = 0;
|
|
2195
|
+
let currentPackChunks = [];
|
|
2196
|
+
const flushPack = () => {
|
|
2197
|
+
if (currentPackChunks.length === 0)
|
|
2198
|
+
return;
|
|
2199
|
+
const packSources = [...new Set(currentPackChunks.map(c => `raw/${c.source.file}`))];
|
|
2200
|
+
let md = "---\n";
|
|
2201
|
+
md += `title: "Digest Pack ${String(packNum).padStart(3, "0")}"\n`;
|
|
2202
|
+
md += `topic: "${topic}"\n`;
|
|
2203
|
+
md += `sources: ${JSON.stringify(packSources)}\n`;
|
|
2204
|
+
md += `totalChunks: ${currentPackChunks.length}\n`;
|
|
2205
|
+
md += "---\n\n";
|
|
2206
|
+
for (const chunk of currentPackChunks) {
|
|
2207
|
+
let header = `## raw/${chunk.source.file}`;
|
|
2208
|
+
if (chunk.source.page !== undefined)
|
|
2209
|
+
header += ` [Page ${chunk.source.page}]`;
|
|
2210
|
+
if (chunk.source.sheet)
|
|
2211
|
+
header += ` [Sheet: ${chunk.source.sheet}]`;
|
|
2212
|
+
if (chunk.source.slide !== undefined)
|
|
2213
|
+
header += ` [Slide ${chunk.source.slide}]`;
|
|
2214
|
+
md += `${header}\n\n${chunk.text}\n\n`;
|
|
2215
|
+
}
|
|
2216
|
+
const packPath = `digest-packs/${topic}/pack-${String(packNum).padStart(3, "0")}.md`;
|
|
2217
|
+
wiki.rawAddParsedArtifact(packPath, md.trimEnd(), {
|
|
2218
|
+
mimeType: "text/markdown",
|
|
2219
|
+
description: `Digest pack ${packNum} for topic "${topic}"`,
|
|
2220
|
+
});
|
|
2221
|
+
packs.push({ path: packPath, chunks: currentPackChunks.length, sources: packSources });
|
|
2222
|
+
packNum++;
|
|
2223
|
+
currentPackChunks = [];
|
|
2224
|
+
currentPackLines = 0;
|
|
2225
|
+
};
|
|
2226
|
+
const addChunkToPack = (chunk) => {
|
|
2227
|
+
const lines = chunk.text.split("\n").length;
|
|
2228
|
+
if (currentPackLines + lines > packLinesLimit && currentPackChunks.length > 0) {
|
|
2229
|
+
flushPack();
|
|
2230
|
+
}
|
|
2231
|
+
currentPackChunks.push(chunk);
|
|
2232
|
+
currentPackLines += lines;
|
|
2233
|
+
totalChunks++;
|
|
2234
|
+
};
|
|
2235
|
+
// Step 2-3: Import + Extract + Stream into packs
|
|
2236
|
+
for (const relPath of filePaths) {
|
|
2237
|
+
const rawFilename = `${topic}/${relPath}`;
|
|
2238
|
+
const fullSourcePath = srcStat.isDirectory()
|
|
2239
|
+
? join(sourcePath, relPath)
|
|
2240
|
+
: sourcePath;
|
|
2241
|
+
// Import to raw/
|
|
2242
|
+
try {
|
|
2243
|
+
wiki.rawAdd(rawFilename, { sourcePath: fullSourcePath });
|
|
2244
|
+
imported++;
|
|
2245
|
+
}
|
|
2246
|
+
catch (e) {
|
|
2247
|
+
if (e.message.includes("already exists")) {
|
|
2248
|
+
skipped++;
|
|
2249
|
+
}
|
|
2250
|
+
else if (continueOnError) {
|
|
2251
|
+
errors.push({ file: relPath, stage: "import", error: e.message });
|
|
2252
|
+
continue;
|
|
2253
|
+
}
|
|
2254
|
+
else {
|
|
2255
|
+
throw e;
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
// Extract + chunk + stream into packs
|
|
2259
|
+
const ext = extname(relPath).toLowerCase();
|
|
2260
|
+
const rawFullPath = join(wiki.config.rawDir, rawFilename);
|
|
2261
|
+
try {
|
|
2262
|
+
let segments;
|
|
2263
|
+
if (EXTRACTABLE.has(ext)) {
|
|
2264
|
+
const result = await extractDocument(rawFullPath);
|
|
2265
|
+
segments = result.segments;
|
|
2266
|
+
}
|
|
2267
|
+
else {
|
|
2268
|
+
const mime = guessMime(relPath);
|
|
2269
|
+
if (TEXT_LIKE(mime)) {
|
|
2270
|
+
const content = readFileSync(rawFullPath, "utf-8");
|
|
2271
|
+
// Semantic chunking: split by headings first so each chunk is a
|
|
2272
|
+
// coherent logical unit. Falls back to a single segment for files
|
|
2273
|
+
// with no headings (e.g. plain CSV, config files).
|
|
2274
|
+
const mdSections = splitSections(content);
|
|
2275
|
+
const nonEmpty = mdSections.filter(s => s.content.trim().length > 0);
|
|
2276
|
+
segments = nonEmpty.length > 1
|
|
2277
|
+
? nonEmpty.map(s => ({ text: s.content, source: { file: rawFilename } }))
|
|
2278
|
+
: [{ text: content, source: { file: rawFilename } }];
|
|
2279
|
+
}
|
|
2280
|
+
else {
|
|
2281
|
+
continue; // Binary file — skip extraction
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
// Normalize file path in source coordinates
|
|
2285
|
+
for (const seg of segments) {
|
|
2286
|
+
seg.source.file = rawFilename;
|
|
2287
|
+
}
|
|
2288
|
+
// Chunk and stream directly into packs (bounded memory)
|
|
2289
|
+
const chunked = chunkSegments(segments, chunkLinesLimit);
|
|
2290
|
+
for (const chunk of chunked) {
|
|
2291
|
+
addChunkToPack(chunk);
|
|
2292
|
+
}
|
|
2293
|
+
extracted++;
|
|
2294
|
+
}
|
|
2295
|
+
catch (e) {
|
|
2296
|
+
if (continueOnError) {
|
|
2297
|
+
errors.push({ file: relPath, stage: "extract", error: e.message });
|
|
2298
|
+
}
|
|
2299
|
+
else {
|
|
2300
|
+
throw e;
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
flushPack(); // flush remaining
|
|
2305
|
+
const nextRecommendedReads = packs.slice(0, 5).map(p => `raw/${p.path}`);
|
|
2306
|
+
return JSON.stringify({
|
|
2307
|
+
ok: true,
|
|
2308
|
+
matched,
|
|
2309
|
+
imported,
|
|
2310
|
+
skipped,
|
|
2311
|
+
extracted,
|
|
2312
|
+
chunks: totalChunks,
|
|
2313
|
+
packs: packs.length,
|
|
2314
|
+
failed: errors.length,
|
|
2315
|
+
...(errors.length > 0 ? { errors: errors.slice(0, 10) } : {}),
|
|
2316
|
+
packPaths: packs.map(p => `raw/${p.path}`),
|
|
2317
|
+
nextRecommendedReads,
|
|
2318
|
+
}, null, 2);
|
|
2319
|
+
}
|
|
2320
|
+
case "knowledge_digest_write": {
|
|
2321
|
+
const MAX_DIGEST_PAGES = 100;
|
|
2322
|
+
const items = args.pages;
|
|
2323
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
2324
|
+
throw new Error("pages must be a non-empty array");
|
|
2325
|
+
}
|
|
2326
|
+
if (items.length > MAX_DIGEST_PAGES) {
|
|
2327
|
+
throw new Error(`Too many pages: ${items.length} exceeds limit of ${MAX_DIGEST_PAGES}`);
|
|
2328
|
+
}
|
|
2329
|
+
const results = [];
|
|
2330
|
+
for (let idx = 0; idx < items.length; idx++) {
|
|
2331
|
+
const item = items[idx];
|
|
2332
|
+
const pageLabel = (item && typeof item === "object" && typeof item.page === "string")
|
|
2333
|
+
? item.page : `(item ${idx})`;
|
|
2334
|
+
try {
|
|
2335
|
+
// Validate required fields
|
|
2336
|
+
if (!item || typeof item !== "object" || typeof item.page !== "string"
|
|
2337
|
+
|| typeof item.title !== "string" || typeof item.body !== "string") {
|
|
2338
|
+
throw new Error("Each page must have string page, title, and body fields");
|
|
2339
|
+
}
|
|
2340
|
+
const topicField = item.topic ? sanitizeTopic(item.topic) : undefined;
|
|
2341
|
+
// Build frontmatter + body using gray-matter for safe YAML serialization
|
|
2342
|
+
const fm = { title: item.title };
|
|
2343
|
+
if (item.type)
|
|
2344
|
+
fm.type = item.type;
|
|
2345
|
+
if (item.tags && item.tags.length > 0)
|
|
2346
|
+
fm.tags = item.tags;
|
|
2347
|
+
if (topicField)
|
|
2348
|
+
fm.topic = topicField;
|
|
2349
|
+
if (item.sources && item.sources.length > 0)
|
|
2350
|
+
fm.sources = item.sources;
|
|
2351
|
+
if (item.sourcePacks && item.sourcePacks.length > 0)
|
|
2352
|
+
fm.source_packs = item.sourcePacks;
|
|
2353
|
+
const content = matter.stringify("\n" + item.body, fm);
|
|
2354
|
+
// Auto-classify if type/tags missing
|
|
2355
|
+
const enrichedContent = wiki.autoClassifyContent(content);
|
|
2356
|
+
// Auto-route to topic subdirectory
|
|
2357
|
+
const resolvedPage = wiki.resolvePagePath(item.page, enrichedContent);
|
|
2358
|
+
wiki.write(resolvedPage, enrichedContent, item.sourcePacks?.[0] ?? item.sources?.[0]);
|
|
2359
|
+
const classification = wiki.classify(enrichedContent);
|
|
2360
|
+
results.push({
|
|
2361
|
+
ok: true,
|
|
2362
|
+
page: resolvedPage,
|
|
2363
|
+
routed: resolvedPage !== item.page,
|
|
2364
|
+
autoClassified: { type: classification.type, tags: classification.tags, confidence: classification.confidence },
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
catch (err) {
|
|
2368
|
+
results.push({ ok: false, page: pageLabel, error: err instanceof Error ? err.message : String(err) });
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
// Rebuild index once after all writes
|
|
2372
|
+
wiki.rebuildIndex();
|
|
2373
|
+
return JSON.stringify({
|
|
2374
|
+
results,
|
|
2375
|
+
count: results.length,
|
|
2376
|
+
written: results.filter(r => r.ok).length,
|
|
2377
|
+
}, null, 2);
|
|
2378
|
+
}
|
|
2379
|
+
// ═══ BATCH ═══
|
|
2380
|
+
case "batch": {
|
|
2381
|
+
const MAX_BATCH_OPS = 50;
|
|
2382
|
+
const ops = args.operations;
|
|
2383
|
+
if (!Array.isArray(ops) || ops.length === 0) {
|
|
2384
|
+
throw new Error("operations must be a non-empty array");
|
|
2385
|
+
}
|
|
2386
|
+
if (ops.length > MAX_BATCH_OPS) {
|
|
2387
|
+
throw new Error(`Batch too large: ${ops.length} operations exceeds limit of ${MAX_BATCH_OPS}`);
|
|
2388
|
+
}
|
|
2389
|
+
// Tools whose per-call rebuildIndex should be deferred to end of batch
|
|
2390
|
+
const REBUILD_TOOLS = new Set(["wiki_write", "wiki_delete"]);
|
|
2391
|
+
// Tools whose per-call graph/aggregate rebuild should be deferred
|
|
2392
|
+
const GRAPH_REBUILD_TOOLS = new Set(["code_parse"]);
|
|
2393
|
+
let needsRebuild = false;
|
|
2394
|
+
let needsTimeline = false;
|
|
2395
|
+
let needsGraphRebuild = false;
|
|
2396
|
+
const results = [];
|
|
2397
|
+
for (const op of ops) {
|
|
2398
|
+
if (op.tool === "batch") {
|
|
2399
|
+
results.push({ tool: op.tool, error: "Cannot nest batch operations" });
|
|
2400
|
+
continue;
|
|
2401
|
+
}
|
|
2402
|
+
// Deduplicate wiki_rebuild / wiki_admin action:rebuild — defer to end-of-batch full rebuild
|
|
2403
|
+
const isRebuild = op.tool === "wiki_rebuild" ||
|
|
2404
|
+
(op.tool === "wiki_admin" && (op.args?.action === "rebuild"));
|
|
2405
|
+
if (isRebuild) {
|
|
2406
|
+
needsRebuild = true;
|
|
2407
|
+
needsTimeline = true;
|
|
2408
|
+
results.push({ tool: op.tool, result: { ok: true, deferred: "merged into end-of-batch rebuild" } });
|
|
2409
|
+
continue;
|
|
2410
|
+
}
|
|
2411
|
+
try {
|
|
2412
|
+
if (needsGraphRebuild && (op.tool === "code_impact" ||
|
|
2413
|
+
(op.tool === "code_query" && codeQueryConsumesCompiledArtifacts(op.args ?? {})))) {
|
|
2414
|
+
rebuildDeferredGraphs(wiki);
|
|
2415
|
+
needsGraphRebuild = false;
|
|
2416
|
+
}
|
|
2417
|
+
const opOpts = {};
|
|
2418
|
+
if (REBUILD_TOOLS.has(op.tool))
|
|
2419
|
+
opOpts.skipRebuild = true;
|
|
2420
|
+
if (GRAPH_REBUILD_TOOLS.has(op.tool))
|
|
2421
|
+
opOpts.skipGraphRebuild = true;
|
|
2422
|
+
const result = await handleTool(wiki, op.tool, op.args ?? {}, opOpts);
|
|
2423
|
+
if (REBUILD_TOOLS.has(op.tool)) {
|
|
2424
|
+
// Check if the operation actually changed something worth rebuilding for
|
|
2425
|
+
if (op.tool === "wiki_write") {
|
|
2426
|
+
needsRebuild = true;
|
|
2427
|
+
}
|
|
2428
|
+
else if (op.tool === "wiki_delete") {
|
|
2429
|
+
const parsed = JSON.parse(typeof result === "string" ? result : "{}");
|
|
2430
|
+
if (parsed.ok)
|
|
2431
|
+
needsRebuild = true;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
if (GRAPH_REBUILD_TOOLS.has(op.tool)) {
|
|
2435
|
+
needsGraphRebuild = true;
|
|
2436
|
+
needsRebuild = true; // graph pages are wiki pages
|
|
2437
|
+
needsTimeline = true; // graph pages have timestamps → must appear in timeline
|
|
2438
|
+
}
|
|
2439
|
+
if (typeof result === "string") {
|
|
2440
|
+
try {
|
|
2441
|
+
results.push({ tool: op.tool, result: JSON.parse(result) });
|
|
2442
|
+
}
|
|
2443
|
+
catch {
|
|
2444
|
+
results.push({ tool: op.tool, result });
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
else {
|
|
2448
|
+
// ContentBlock[] — preserve full blocks including inline images
|
|
2449
|
+
results.push({ tool: op.tool, result });
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
catch (err) {
|
|
2453
|
+
results.push({ tool: op.tool, error: err instanceof Error ? err.message : String(err) });
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
// Deferred graph rebuild: run once at end of batch for all plugins that parsed files
|
|
2457
|
+
if (needsGraphRebuild) {
|
|
2458
|
+
rebuildDeferredGraphs(wiki);
|
|
2459
|
+
}
|
|
2460
|
+
if (needsRebuild) {
|
|
2461
|
+
const pageCache = wiki.buildPageCache();
|
|
2462
|
+
wiki.rebuildIndex(pageCache);
|
|
2463
|
+
if (needsTimeline)
|
|
2464
|
+
wiki.rebuildTimeline(pageCache);
|
|
2465
|
+
}
|
|
2466
|
+
return JSON.stringify({ results, count: results.length }, null, 2);
|
|
2467
|
+
}
|
|
2468
|
+
// ═══ CONSOLIDATED PUBLIC TOOLS (delegate to legacy handlers) ═══
|
|
2469
|
+
case "raw_ingest": {
|
|
2470
|
+
const mode = args.mode;
|
|
2471
|
+
switch (mode) {
|
|
2472
|
+
case "add": return handleTool(wiki, "raw_add", args, opts);
|
|
2473
|
+
case "fetch": return handleTool(wiki, "raw_fetch", args, opts);
|
|
2474
|
+
case "import_confluence": return handleTool(wiki, "raw_import_confluence", args, opts);
|
|
2475
|
+
case "import_jira": return handleTool(wiki, "raw_import_jira", args, opts);
|
|
2476
|
+
default: throw new Error(`Unknown raw_ingest mode: "${mode}". Expected: add | fetch | import_confluence | import_jira`);
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
case "wiki_admin": {
|
|
2480
|
+
const action = args.action;
|
|
2481
|
+
switch (action) {
|
|
2482
|
+
case "init": return handleTool(wiki, "wiki_init", args, opts);
|
|
2483
|
+
case "config": return handleTool(wiki, "wiki_config", args, opts);
|
|
2484
|
+
case "rebuild": return handleTool(wiki, "wiki_rebuild", args, opts);
|
|
2485
|
+
case "lint": return handleTool(wiki, "wiki_lint", args, opts);
|
|
2486
|
+
default: throw new Error(`Unknown wiki_admin action: "${action}". Expected: init | config | rebuild | lint`);
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
case "code_query": {
|
|
2490
|
+
const queryType = args.query_type;
|
|
2491
|
+
switch (queryType) {
|
|
2492
|
+
case "trace_variable": return handleTool(wiki, "code_trace_variable", args, opts);
|
|
2493
|
+
case "impact": return handleTool(wiki, "code_impact", args, opts);
|
|
2494
|
+
case "procedure_flow": return handleTool(wiki, "code_procedure_flow", args, opts);
|
|
2495
|
+
case "field_lineage": return handleTool(wiki, "code_field_lineage", args, opts);
|
|
2496
|
+
case "dataflow_edges": return handleTool(wiki, "code_dataflow_edges", args, opts);
|
|
2497
|
+
default: throw new Error(`Unknown code_query query_type: "${queryType}". Expected: trace_variable | impact | procedure_flow | field_lineage | dataflow_edges`);
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
case "knowledge_ingest": {
|
|
2501
|
+
const mode = args.mode;
|
|
2502
|
+
switch (mode) {
|
|
2503
|
+
case "batch": return handleTool(wiki, "knowledge_ingest_batch", args, opts);
|
|
2504
|
+
case "digest_write": return handleTool(wiki, "knowledge_digest_write", args, opts);
|
|
2505
|
+
default: throw new Error(`Unknown knowledge_ingest mode: "${mode}". Expected: batch | digest_write`);
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
default:
|
|
2509
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
// ── Entry point for stdio transport ───────────────────────────
|
|
2513
|
+
export async function runServer(wikiPath, workspace) {
|
|
2514
|
+
const server = createServer(wikiPath, workspace);
|
|
2515
|
+
const transport = new StdioServerTransport();
|
|
2516
|
+
// Handle transport/process errors gracefully instead of crashing
|
|
2517
|
+
process.on("SIGPIPE", () => {
|
|
2518
|
+
// Client disconnected — ignore, let transport handle cleanup
|
|
2519
|
+
});
|
|
2520
|
+
process.stdin.on("error", () => { });
|
|
2521
|
+
process.stdout.on("error", () => { });
|
|
2522
|
+
server.onerror = (err) => {
|
|
2523
|
+
console.error(`[agent-wiki] MCP error: ${err instanceof Error ? err.message : String(err)}`);
|
|
2524
|
+
};
|
|
2525
|
+
server.onclose = () => {
|
|
2526
|
+
process.exit(0);
|
|
2527
|
+
};
|
|
2528
|
+
await server.connect(transport);
|
|
2529
|
+
}
|
|
2530
|
+
//# sourceMappingURL=server.js.map
|