opencode-rag-plugin 2.13.4 → 2.13.6

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.
@@ -0,0 +1,25 @@
1
+ import type { ToolDefinition } from "@opencode-ai/plugin";
2
+ /** Shared construction options for the wiki tools. */
3
+ export interface WikiToolOptions {
4
+ /** Workspace root — the wiki lives at `<worktree>/.opencode/wiki`. */
5
+ worktree: string;
6
+ /** Live accessor for `wikiMode.maxPages` (config hot-reload aware). */
7
+ getMaxPages?: () => number | undefined;
8
+ }
9
+ /**
10
+ * Create the `wiki_graph` tool.
11
+ *
12
+ * Purpose: answer every link-structure question in one call — backlinks of a
13
+ * page, its neighborhood, the orphan list, dangling targets, or a whole-wiki
14
+ * overview. Use instead of grepping the wiki for `[[...]]`.
15
+ */
16
+ export declare function createWikiGraphTool(options: WikiToolOptions): ToolDefinition;
17
+ /**
18
+ * Create the `wiki_lint` tool.
19
+ *
20
+ * Purpose: the deterministic health report — structure (orphans/dangling/
21
+ * catalog) plus staleness (sourceRefs committed after lastReviewed, dead
22
+ * refs, uncommitted drift) in one call. Run it FIRST for any lint request,
23
+ * then handle the judgment checks it cannot compute.
24
+ */
25
+ export declare function createWikiLintTool(options: WikiToolOptions): ToolDefinition;
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @fileoverview Agent tools for wiki structure and health: `wiki_graph` and
3
+ * `wiki_lint`.
4
+ *
5
+ * These move the deterministic half of wiki maintenance out of the LLM:
6
+ * backlink/orphan/dangling questions become one call instead of a grep sweep,
7
+ * and staleness (git vs. lastReviewed) becomes one call instead of manual git
8
+ * archaeology. The report is only as good as the files — there is no
9
+ * persisted graph to go stale.
10
+ */
11
+ import { tool } from "@opencode-ai/plugin/tool";
12
+ import * as path from "node:path";
13
+ import { getWikiGraph, findPage, graphNeighbors } from "../wiki/graph.js";
14
+ import { lintWiki, formatLintReport } from "../wiki/lint.js";
15
+ /** Modes of `wiki_graph`. */
16
+ const GRAPH_MODES = ["overview", "backlinks", "outlinks", "neighbors", "orphans", "dangling"];
17
+ function noWikiOutput(wikiDir) {
18
+ return {
19
+ title: "Wiki graph",
20
+ output: `No wiki yet at \`${path.relative(process.cwd(), wikiDir).replace(/\\/g, "/") || ".opencode/wiki"}\`. Run \`/wiki seed\` to generate the initial pages.`,
21
+ metadata: { tool: "wiki_graph", wikiFound: false },
22
+ };
23
+ }
24
+ function pageLine(graph, id) {
25
+ const node = graph.pages.get(id);
26
+ if (!node)
27
+ return `- \`${id}\``;
28
+ const inb = node.inbound.length;
29
+ const outb = node.outbound.length;
30
+ return `- \`${node.id}\` — ${node.title} _(in ${inb}, out ${outb})_`;
31
+ }
32
+ /**
33
+ * Create the `wiki_graph` tool.
34
+ *
35
+ * Purpose: answer every link-structure question in one call — backlinks of a
36
+ * page, its neighborhood, the orphan list, dangling targets, or a whole-wiki
37
+ * overview. Use instead of grepping the wiki for `[[...]]`.
38
+ */
39
+ export function createWikiGraphTool(options) {
40
+ const wikiDir = path.join(options.worktree, ".opencode", "wiki");
41
+ return tool({
42
+ description: "Wiki link-graph queries over `.opencode/wiki/` — the tool version of `/wiki` structure questions. " +
43
+ "Modes: `overview` (counts: pages, orphans, dangling, index coverage), " +
44
+ "`backlinks` / `outlinks` / `neighbors` (needs `page`; find WHERE a page is referenced instead of grepping), " +
45
+ "`orphans` (content pages with no inbound content link), `dangling` (links that resolve to no page). " +
46
+ "Computed from the files on every call — never stale. Pair with `wiki_lint` for health (staleness vs git).",
47
+ args: {
48
+ mode: tool.schema.string().optional().describe("One of: overview | backlinks | outlinks | neighbors | orphans | dangling. Default: overview."),
49
+ page: tool.schema.string().optional().describe("Page id or unique basename (e.g. `entities/config-system` or `clickhouse-store`) — required for backlinks/outlinks/neighbors."),
50
+ depth: tool.schema.number().int().min(1).max(3).optional().describe("neighbor mode: hops to expand (1–3, default 1)."),
51
+ },
52
+ async execute(args) {
53
+ const mode = (args.mode ?? "overview").toLowerCase();
54
+ if (!GRAPH_MODES.includes(mode)) {
55
+ return {
56
+ title: "Wiki graph",
57
+ output: `Unknown mode "${args.mode}". Use one of: ${GRAPH_MODES.join(", ")}.`,
58
+ metadata: { tool: "wiki_graph", error: "bad-mode" },
59
+ };
60
+ }
61
+ const graph = getWikiGraph(wikiDir, { maxPages: options.getMaxPages?.() });
62
+ if (!graph.exists)
63
+ return noWikiOutput(wikiDir);
64
+ if (mode === "backlinks" || mode === "outlinks" || mode === "neighbors") {
65
+ if (!args.page) {
66
+ return {
67
+ title: "Wiki graph",
68
+ output: `Mode "${mode}" needs a \`page\` argument (e.g. "entities/config-system" or a unique basename).`,
69
+ metadata: { tool: "wiki_graph", mode, error: "page-required" },
70
+ };
71
+ }
72
+ const node = findPage(graph, args.page);
73
+ if (!node) {
74
+ const hint = graph.pageCount > 0 ? `Run mode "overview" to list pages.` : "";
75
+ return {
76
+ title: "Wiki graph",
77
+ output: `No wiki page matches "${args.page}" (ambiguous or unknown). ${hint}`,
78
+ metadata: { tool: "wiki_graph", mode, page: args.page, error: "page-not-found" },
79
+ };
80
+ }
81
+ const lines = [`## ${node.title}`, `\`${node.id}\` (${node.relPath})`, ""];
82
+ if (mode === "backlinks" || mode === "neighbors") {
83
+ lines.push(`**Backlinks (${node.inbound.length}):**`);
84
+ lines.push(node.inbound.length === 0 ? "_none — this page is an orphan_" : node.inbound.map((i) => pageLine(graph, i)).join("\n"));
85
+ lines.push("");
86
+ }
87
+ if (mode === "outlinks" || mode === "neighbors") {
88
+ lines.push(`**Outbound links (${node.outbound.length}):**`);
89
+ lines.push(node.outbound.length === 0 ? "_none_" : node.outbound.map((i) => pageLine(graph, i)).join("\n"));
90
+ if (node.unresolved.length > 0) {
91
+ lines.push("");
92
+ lines.push(`**Dangling (${node.unresolved.length}):** ` + node.unresolved.map((l) => `[[${l.target}]]`).join(", "));
93
+ }
94
+ lines.push("");
95
+ }
96
+ if (mode === "neighbors") {
97
+ const neigh = graphNeighbors(graph, node.id, args.depth ?? 1);
98
+ lines.push(`**Neighborhood within ${args.depth ?? 1} hop(s) (${neigh.length}):**`);
99
+ lines.push(neigh.length === 0 ? "_nobody_" : neigh.map((i) => pageLine(graph, i)).join("\n"));
100
+ }
101
+ return {
102
+ title: `Wiki graph — ${node.id}`,
103
+ output: lines.join("\n"),
104
+ metadata: { tool: "wiki_graph", mode, page: node.id, in: node.inbound.length, out: node.outbound.length },
105
+ };
106
+ }
107
+ if (mode === "orphans") {
108
+ return {
109
+ title: `Wiki graph — orphans (${graph.orphans.length})`,
110
+ output: graph.orphans.length === 0
111
+ ? "No orphan pages — every content page has at least one inbound content link."
112
+ : `**Orphan pages (${graph.orphans.length})** — no inbound [[link]] from a content page:\n\n` +
113
+ graph.orphans.map((i) => pageLine(graph, i)).join("\n"),
114
+ metadata: { tool: "wiki_graph", mode, count: graph.orphans.length },
115
+ };
116
+ }
117
+ if (mode === "dangling") {
118
+ return {
119
+ title: `Wiki graph — dangling (${graph.dangling.length})`,
120
+ output: graph.dangling.length === 0
121
+ ? "No dangling links — every [[link]] resolves to an existing page."
122
+ : `**Dangling links (${graph.dangling.length})** — written but resolving to no page:\n\n` +
123
+ graph.dangling.map((d) => `- \`${d.fromId}\` → [[${d.raw}]]`).join("\n"),
124
+ metadata: { tool: "wiki_graph", mode, count: graph.dangling.length },
125
+ };
126
+ }
127
+ // overview
128
+ const dirs = new Map();
129
+ for (const node of graph.pages.values()) {
130
+ const idx = node.id.lastIndexOf("/");
131
+ const dir = idx >= 0 ? node.id.slice(0, idx) : "(root)";
132
+ dirs.set(dir, (dirs.get(dir) ?? 0) + 1);
133
+ }
134
+ const degree = [...graph.pages.values()].map((n) => n.inbound.length + n.outbound.length);
135
+ degree.sort((a, b) => a - b);
136
+ const median = degree.length > 0 ? degree[Math.floor(degree.length / 2)] : 0;
137
+ const hub = [...graph.pages.values()].sort((a, b) => b.inbound.length - a.inbound.length)[0];
138
+ const lines = [
139
+ `## Wiki overview`,
140
+ `Pages: ${graph.pageCount} (content: ${[...graph.pages.values()].filter((n) => n.isContent).length})${graph.truncated ? " — **scan hit the page cap; counts are floors**" : ""}`,
141
+ `By directory: ${[...dirs.entries()].sort().map(([d, n]) => `${d}/${n}`).join(", ")}`,
142
+ `Links: outbound ${[...graph.pages.values()].reduce((s, n) => s + n.outbound.length, 0)} | inbound-median degree ${median} | most linked: ${hub ? `\`${hub.id}\` (${hub.inbound.length}×)` : "—"}`,
143
+ `Health: orphans ${graph.orphans.length} | dangling ${graph.dangling.length} | uncataloged ${graph.uncataloged.length} | missing frontmatter ${graph.pagesMissingFrontmatter.length}`,
144
+ graph.orphans.length > 0 ? `Orphans: ${graph.orphans.slice(0, 15).map((i) => `\`${i}\``).join(", ")}${graph.orphans.length > 15 ? ` (+${graph.orphans.length - 15})` : ""}` : "",
145
+ graph.dangling.length > 0 ? `Dangling: ${graph.dangling.slice(0, 15).map((d) => `${d.fromId}→[[${d.raw}]]`).join(", ")}${graph.dangling.length > 15 ? ` (+${graph.dangling.length - 15})` : ""}` : "",
146
+ ``,
147
+ `Per-page detail: \`wiki_graph { page: "<id>", mode: "backlinks" }\`. Health incl. git staleness: \`wiki_lint\`.`,
148
+ ].filter((l) => l.length > 0);
149
+ return {
150
+ title: `Wiki graph — overview (${graph.pageCount} pages)`,
151
+ output: lines.join("\n"),
152
+ metadata: {
153
+ tool: "wiki_graph",
154
+ mode: "overview",
155
+ pages: graph.pageCount,
156
+ orphans: graph.orphans.length,
157
+ dangling: graph.dangling.length,
158
+ uncataloged: graph.uncataloged.length,
159
+ },
160
+ };
161
+ },
162
+ });
163
+ }
164
+ /**
165
+ * Create the `wiki_lint` tool.
166
+ *
167
+ * Purpose: the deterministic health report — structure (orphans/dangling/
168
+ * catalog) plus staleness (sourceRefs committed after lastReviewed, dead
169
+ * refs, uncommitted drift) in one call. Run it FIRST for any lint request,
170
+ * then handle the judgment checks it cannot compute.
171
+ */
172
+ export function createWikiLintTool(options) {
173
+ const wikiDir = path.join(options.worktree, ".opencode", "wiki");
174
+ return tool({
175
+ description: "Deterministic wiki health report for `.opencode/wiki/`: stale pages (each page's git-verified `sourceRefs` newer than `lastReviewed`), dead sourceRefs, orphan/dangling link structure, frontmatter and index.md coverage. " +
176
+ "One `git log` walk, day-granular review cutoff, AGENTS.md/README churn reported as low-signal. Run this FIRST when asked to lint or review the wiki, then fix the findings and append them to `log.md`; only the judgment checks (contradictions, missing concepts) remain manual. " +
177
+ "Returns `format: \"json\"` data verbatim in metadata when requested.",
178
+ args: {
179
+ staleDays: tool.schema.number().int().min(1).optional().describe("Also flag pages not reviewed for more than this many days (reported separately as aging)."),
180
+ maxCommits: tool.schema.number().int().min(10).max(5000).optional().describe("Cap on commits in the single git-history walk (default 500). Raise for long histories; the report says when it truncated."),
181
+ format: tool.schema.string().optional().describe('"markdown" (default) or "json" (full report in metadata).'),
182
+ },
183
+ async execute(args) {
184
+ const report = lintWiki(wikiDir, options.worktree, {
185
+ maxPages: options.getMaxPages?.(),
186
+ maxCommits: args.maxCommits,
187
+ });
188
+ if (!report.exists) {
189
+ return {
190
+ title: "Wiki lint",
191
+ output: `No wiki yet at \`.opencode/wiki/\`. Run \`/wiki seed\` to generate the initial pages.`,
192
+ metadata: { tool: "wiki_lint", wikiFound: false },
193
+ };
194
+ }
195
+ const staleDays = args.staleDays;
196
+ const aging = staleDays
197
+ ? report.staleness.pages.filter((p) => p.state === "fresh" && p.lastReviewedMs !== undefined &&
198
+ p.lastReviewedMs < Date.now() - staleDays * 24 * 3600_000)
199
+ : [];
200
+ let output = formatLintReport(report);
201
+ if (aging.length > 0) {
202
+ output += `\n- **Aging** (unreviewed > ${args.staleDays} days, sources unchanged): ${aging.length}\n ` +
203
+ aging.slice(0, 25).map((p) => `\`${p.id}\` (${p.lastReviewedRaw})`).join(", ");
204
+ }
205
+ const wantJson = String(args.format ?? "").toLowerCase() === "json";
206
+ return {
207
+ title: `Wiki lint — ${report.findingCount} findings (${report.pageCount} pages)`,
208
+ output,
209
+ metadata: {
210
+ tool: "wiki_lint",
211
+ pages: report.pageCount,
212
+ findings: report.findingCount,
213
+ stale: report.staleness.pages.filter((p) => p.state === "stale").length,
214
+ deadRefs: report.staleness.pages.filter((p) => p.state === "missing-refs").length,
215
+ orphans: report.orphans.length,
216
+ dangling: report.dangling.length,
217
+ uncataloged: report.uncataloged.length,
218
+ ...(wantJson ? { report } : {}),
219
+ },
220
+ };
221
+ },
222
+ });
223
+ }
224
+ //# sourceMappingURL=wiki-tools.js.map
package/dist/plugin.js CHANGED
@@ -21,6 +21,9 @@ import { loadRuntimeOverrides, applyRuntimeOverrides } from "./core/runtime-over
21
21
  import { createBackgroundIndexer } from "./watcher.js";
22
22
  import { createRagReadTool } from "./opencode/create-read-tool.js";
23
23
  import { createFileSkeletonTool, createFindUsagesTool, createDescribeImageTool, createRecallQuirksTool, createAddQuirkTool, createUpdateQuirkTool, createDeleteQuirkTool, createMakeDecisionTool, } from "./opencode/tools.js";
24
+ import { createWikiGraphTool, createWikiLintTool } from "./opencode/wiki-tools.js";
25
+ import { lintWiki, formatLintReport } from "./wiki/lint.js";
26
+ import { getWikiGraph } from "./wiki/graph.js";
24
27
  import { resolveApiKey } from "./core/resolve-api-key.js";
25
28
  import { consumePendingRagInjection, peekPendingRagInjection } from "./core/rag-injection-flag.js";
26
29
  import { loadDocProgress, markSubdirectoryDocumented } from "./core/doc-progress.js";
@@ -1033,6 +1036,39 @@ export function createRagHooks(options) {
1033
1036
  });
1034
1037
  }
1035
1038
  }
1039
+ // Wiki tools — structure and health queries over .opencode/wiki/.
1040
+ // Read-only and provider-free: they need no store, no embedder, and work
1041
+ // before any indexing. Gated on wikiMode itself, exactly like the prompt
1042
+ // and the /wiki slash command; `wikiMode.tools: false` keeps the prompt
1043
+ // protocol while hiding the tools.
1044
+ if (effectiveCfg.wikiMode?.enabled && effectiveCfg.wikiMode.tools !== false) {
1045
+ try {
1046
+ tools["wiki_graph"] = createWikiGraphTool({
1047
+ worktree: options.worktree,
1048
+ getMaxPages: () => getEffectiveCfg().wikiMode?.maxPages,
1049
+ });
1050
+ }
1051
+ catch (err) {
1052
+ appendDebugLog(options.logFilePath, {
1053
+ scope: "plugin",
1054
+ message: "Failed to register wiki_graph tool",
1055
+ error: err,
1056
+ });
1057
+ }
1058
+ try {
1059
+ tools["wiki_lint"] = createWikiLintTool({
1060
+ worktree: options.worktree,
1061
+ getMaxPages: () => getEffectiveCfg().wikiMode?.maxPages,
1062
+ });
1063
+ }
1064
+ catch (err) {
1065
+ appendDebugLog(options.logFilePath, {
1066
+ scope: "plugin",
1067
+ message: "Failed to register wiki_lint tool",
1068
+ error: err,
1069
+ });
1070
+ }
1071
+ }
1036
1072
  if (readOverride) {
1037
1073
  const readTool = createRagReadTool({
1038
1074
  worktree: options.worktree,
@@ -1759,32 +1795,68 @@ export function createRagHooks(options) {
1759
1795
  const wikiDir = path.join(options.worktree, ".opencode", "wiki");
1760
1796
  const lines = [];
1761
1797
  if (arg === "lint") {
1762
- lines.push("## Wiki Lint", "", "Run a health check on the wiki. Check for:", "- Orphan pages with no inbound [[links]]", "- Stale pages whose sourceRefs files changed since lastReviewed", "- Contradictions between pages", "- Important concepts mentioned but lacking their own page", "", "Append findings to .opencode/wiki/log.md and fix any issues found.");
1798
+ lines.push("## Wiki Lint", "", "Run a health check on the wiki. Call `wiki_lint` first — it computes stale sourceRefs (git-checked),", "orphan pages, dangling links, frontmatter and index coverage in one pass. Then handle the judgment", "checks the tool cannot compute:", "- Contradictions between pages", "- Important concepts mentioned but lacking their own page", "", "Append findings to .opencode/wiki/log.md and fix any issues found.");
1799
+ // Attach the deterministic report when it can be computed here.
1800
+ try {
1801
+ const report = lintWiki(wikiDir, options.worktree, { maxPages: slashCommandConfig().wikiMode?.maxPages });
1802
+ if (report.exists) {
1803
+ lines.push("", "---", "", formatLintReport(report));
1804
+ }
1805
+ }
1806
+ catch (err) {
1807
+ appendDebugLog(options.logFilePath, {
1808
+ scope: "chat.message",
1809
+ message: "wiki_lint computed report unavailable (agent still runs the checks manually)",
1810
+ error: err,
1811
+ });
1812
+ }
1763
1813
  }
1764
1814
  else if (arg === "seed") {
1765
1815
  lines.push("## Wiki Seed", "", "Generate the initial wiki from existing sources:", "1. Read README and top-level docs for project overview → create overview page", "2. Scan file structure with get_file_skeleton for major modules → create entity pages", "3. Identify common conventions from code patterns → create concept pages", "4. Create .opencode/wiki/index.md listing all pages", "5. Create .opencode/wiki/log.md with initial entry", "6. Keep pages focused — one concept per page, short prose, cross-referenced with [[links]]");
1766
1816
  }
1767
1817
  else {
1768
1818
  if (existsSync(wikiDir)) {
1769
- const entries = readdirSync(wikiDir);
1770
- const pages = entries.filter((e) => e.endsWith(".md") && e !== "log.md").length;
1771
- const hasIndex = entries.includes("index.md");
1772
- const hasLog = entries.includes("log.md");
1773
- const dirs = entries.filter((e) => !e.includes(".")).length;
1774
1819
  let lastLogEntry = "";
1775
1820
  const logPath = path.join(wikiDir, "log.md");
1776
- if (hasLog && existsSync(logPath)) {
1821
+ if (existsSync(logPath)) {
1777
1822
  const logContent = readFileSync(logPath, "utf-8");
1778
1823
  const logLines = logContent.trim().split("\n").filter((l) => l.startsWith("## ["));
1779
1824
  if (logLines.length > 0) {
1780
1825
  lastLogEntry = logLines[logLines.length - 1] ?? "";
1781
1826
  }
1782
1827
  }
1783
- lines.push("## Wiki Status", "", `Wiki: \`.opencode/wiki/\``, `Pages: ~${pages} (.md files)`, `Subdirectories: \`${dirs}\``, `Index: ${hasIndex ? "yes" : "no"} | Log: ${hasLog ? "yes" : "no"}`);
1828
+ // Real structure numbers from the graph (recursive, link-aware);
1829
+ // fall back to a flat file count when the graph cannot build.
1830
+ let pages = 0;
1831
+ let dirs = 0;
1832
+ let healthLine = "";
1833
+ try {
1834
+ const graph = getWikiGraph(wikiDir, { maxPages: slashCommandConfig().wikiMode?.maxPages });
1835
+ pages = graph.pageCount;
1836
+ const dirSet = new Set();
1837
+ for (const node of graph.pages.values()) {
1838
+ const idx = node.id.lastIndexOf("/");
1839
+ dirSet.add(idx >= 0 ? node.id.slice(0, idx) : "(root)");
1840
+ }
1841
+ dirs = dirSet.size;
1842
+ const contentCount = [...graph.pages.values()].filter((n) => n.isContent).length;
1843
+ healthLine = `Health: orphans ${graph.orphans.length} | dangling ${graph.dangling.length} | uncataloged ${graph.uncataloged.length} (of ${contentCount} content pages)${graph.truncated ? " | **page cap hit**" : ""}`;
1844
+ }
1845
+ catch (err) {
1846
+ appendDebugLog(options.logFilePath, { scope: "chat.message", message: "wiki status graph build failed", error: err });
1847
+ const entries = readdirSync(wikiDir);
1848
+ pages = entries.filter((e) => e.endsWith(".md") && e !== "log.md").length;
1849
+ dirs = entries.filter((e) => !e.includes(".")).length;
1850
+ }
1851
+ const hasIndex = existsSync(path.join(wikiDir, "index.md"));
1852
+ const hasLog = existsSync(logPath);
1853
+ lines.push("## Wiki Status", "", `Wiki: \`.opencode/wiki/\``, `Pages: ${pages} (.md files, recursive)`, `Subdirectories: \`${dirs}\``, `Index: ${hasIndex ? "yes" : "no"} | Log: ${hasLog ? "yes" : "no"}`);
1854
+ if (healthLine)
1855
+ lines.push(healthLine);
1784
1856
  if (lastLogEntry) {
1785
1857
  lines.push(`Latest log: \`${lastLogEntry}\``);
1786
1858
  }
1787
- lines.push("", "Commands:", "- `/wiki` — show this status", "- `/wiki lint` — health-check the wiki", "- `/wiki seed` — generate initial wiki pages from the codebase");
1859
+ lines.push("", "Commands:", "- `/wiki` — show this status", "- `/wiki lint` — computed health report + manual judgment checks", "- `/wiki seed` — generate initial wiki pages from the codebase", "", "Tools: `wiki_graph` (backlinks/orphans/dangling/neighbors), `wiki_lint` (staleness vs git).");
1788
1860
  }
1789
1861
  else {
1790
1862
  lines.push("## Wiki Status", "", "No wiki yet at `.opencode/wiki/`.", "Use `/wiki seed` to generate the initial wiki from existing sources.");
@@ -1029,6 +1029,13 @@ export const SETTINGS_SECTIONS = [
1029
1029
  boolean(["wikiMode", "enabled"], "Wiki mode enabled", {
1030
1030
  description: "Turn the agent into a wiki maintainer that keeps a structured knowledge wiki under .opencode/wiki.",
1031
1031
  }),
1032
+ boolean(["wikiMode", "tools"], "Wiki agent tools", {
1033
+ description: "Register the `wiki_graph` and `wiki_lint` tools so the agent answers link-structure and health questions in one call. Turn off to keep the protocol without the tools.",
1034
+ }),
1035
+ number(["wikiMode", "maxPages"], "Max pages scanned", {
1036
+ advanced: true,
1037
+ description: "Safety cap on wiki pages scanned per report. When hit, counts become floors and the report says so.",
1038
+ }),
1032
1039
  string(["wikiMode", "systemPrompt"], "System prompt", {
1033
1040
  advanced: true,
1034
1041
  multiline: true,
@@ -0,0 +1,114 @@
1
+ import { type ParsedWikiPage, type WikiLink } from "./page-parse.js";
2
+ /** Bookkeeping pages: excluded from orphan analysis and inbound counting. */
3
+ export declare const NON_CONTENT_PAGE_IDS: ReadonlySet<string>;
4
+ /** A resolved wiki page with its graph edges. */
5
+ export interface WikiPageNode {
6
+ /** Normalized id (posix, lowercase, no `.md`), e.g. `entities/plugin`. */
7
+ id: string;
8
+ /** Path relative to the wiki root, posix, with suffix (display). */
9
+ relPath: string;
10
+ /** Absolute path on disk. */
11
+ absPath: string;
12
+ /** Best display title. */
13
+ title: string;
14
+ parsed: ParsedWikiPage;
15
+ /** Page-level is a content page (not index/log). */
16
+ isContent: boolean;
17
+ /** Resolved outbound links (page ids), document order, no self-links. */
18
+ outbound: string[];
19
+ /** Links that resolved to no page. */
20
+ unresolved: WikiLink[];
21
+ /** Page ids linking TO this page (content pages only), sorted. */
22
+ inbound: string[];
23
+ /** Whether index.md links to this page. */
24
+ cataloged: boolean;
25
+ }
26
+ /** A `[[link]]` written on a page that resolves to no existing page. */
27
+ export interface DanglingLink {
28
+ /** Page id the link was written on. */
29
+ fromId: string;
30
+ /** Link target as written. */
31
+ raw: string;
32
+ /** Normalized target id (what the resolver looked for). */
33
+ target: string;
34
+ }
35
+ /** A complete snapshot of the wiki graph. */
36
+ export interface WikiGraph {
37
+ /** Absolute wiki directory. */
38
+ wikiDir: string;
39
+ /** True when the wiki directory exists at all. */
40
+ exists: boolean;
41
+ /** Pages by normalized id. */
42
+ pages: Map<string, WikiPageNode>;
43
+ /** Content pages with zero inbound links from other content pages. */
44
+ orphans: string[];
45
+ /** Links that resolve to nothing. */
46
+ dangling: DanglingLink[];
47
+ /** Content pages NOT linked from index.md. */
48
+ uncataloged: string[];
49
+ /** Links written in index.md that resolve to nothing. */
50
+ indexEntriesMissingFile: DanglingLink[];
51
+ /** Content pages with no frontmatter block at all. */
52
+ pagesMissingFrontmatter: string[];
53
+ /** Content pages whose frontmatter carries parse issues. */
54
+ frontmatterIssues: {
55
+ id: string;
56
+ message: string;
57
+ }[];
58
+ /** True when the scan stopped at the page limit. */
59
+ truncated: boolean;
60
+ /** Pages scanned (== pages.size). */
61
+ pageCount: number;
62
+ }
63
+ /** Options for a graph build. */
64
+ export interface WikiGraphOptions {
65
+ /** Safety cap on pages scanned (config `wikiMode.maxPages`). Default 500. */
66
+ maxPages?: number;
67
+ }
68
+ /**
69
+ * Resolve a raw link target against the page set.
70
+ * Order: exact id → unique basename. Case-insensitive on both.
71
+ *
72
+ * @param raw - The link target as written.
73
+ * @param idIndex - Map of normalized id → id.
74
+ * @param basenameIndex - Map of lowercased basename → ids with that basename.
75
+ * @returns The resolved page id, or undefined when dangling.
76
+ */
77
+ export declare function resolveLinkTarget(raw: string, idIndex: Map<string, string>, basenameIndex: Map<string, string[]>): string | undefined;
78
+ /**
79
+ * Build the wiki graph, reading every page.
80
+ *
81
+ * @param wikiDir - Absolute path of the wiki root (`.opencode/wiki`).
82
+ * @param options - Scan limits.
83
+ * @returns The graph snapshot; `exists: false` when the directory is absent.
84
+ */
85
+ export declare function buildWikiGraph(wikiDir: string, options?: WikiGraphOptions): WikiGraph;
86
+ /**
87
+ * Cached wrapper around {@link buildWikiGraph}: returns the cached graph while
88
+ * the (path, mtime, size) fingerprint of the file set is unchanged, so
89
+ * repeated tool calls in one session cost one disk read.
90
+ *
91
+ * @param wikiDir - Absolute path of the wiki root.
92
+ * @param options - Scan limits (part of the cache key).
93
+ * @returns The graph snapshot.
94
+ */
95
+ export declare function getWikiGraph(wikiDir: string, options?: WikiGraphOptions): WikiGraph;
96
+ /**
97
+ * BFS neighborhood of a page over both edge directions.
98
+ *
99
+ * @param graph - The wiki graph.
100
+ * @param pageId - Normalized id of the center page.
101
+ * @param depth - Hops to expand (1–3).
102
+ * @returns Page ids within `depth` hops, center excluded, sorted.
103
+ */
104
+ export declare function graphNeighbors(graph: WikiGraph, pageId: string, depth: number): string[];
105
+ /**
106
+ * Find the page a user-facing `page` argument refers to.
107
+ * Accepts an exact id or a unique basename (mirrors link resolution),
108
+ * case-insensitively, with or without the `.opencode/wiki/` prefix.
109
+ *
110
+ * @param graph - The wiki graph.
111
+ * @param page - User-provided page reference.
112
+ * @returns The matching node, or undefined when unknown or ambiguous.
113
+ */
114
+ export declare function findPage(graph: WikiGraph, page: string): WikiPageNode | undefined;