@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/wiki.js
ADDED
|
@@ -0,0 +1,2677 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core Wiki engine — pure data layer, zero LLM dependency.
|
|
3
|
+
*
|
|
4
|
+
* Architecture (Karpathy LLM Wiki pattern):
|
|
5
|
+
*
|
|
6
|
+
* raw/ — Immutable source documents. Write-once, never modified.
|
|
7
|
+
* Each file has a .meta.yaml sidecar with provenance.
|
|
8
|
+
*
|
|
9
|
+
* wiki/ — Mutable Markdown layer. Three kinds of files:
|
|
10
|
+
* 1. System: index.md, log.md, timeline.md (auto-maintained)
|
|
11
|
+
* 2. Entity pages: concept-*, person-*, artifact-*, etc.
|
|
12
|
+
* 3. Synthesis pages: synthesis-* (distilled from multiple pages)
|
|
13
|
+
*
|
|
14
|
+
* schemas/ — Entity templates (person, concept, event, etc.)
|
|
15
|
+
*
|
|
16
|
+
* Key principles:
|
|
17
|
+
* - Raw files are IMMUTABLE — the source of truth
|
|
18
|
+
* - Wiki pages are MUTABLE — compiled knowledge, continuously refined
|
|
19
|
+
* - Self-checking: lint detects contradictions, broken links, stale claims
|
|
20
|
+
* - Knowledge compounds: every write improves the whole
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, unlinkSync, rmdirSync, statSync, copyFileSync, createWriteStream, appendFileSync } from "node:fs";
|
|
23
|
+
import { pipeline } from "node:stream/promises";
|
|
24
|
+
import { Readable } from "node:stream";
|
|
25
|
+
import { join, relative, resolve, basename, extname, dirname } from "node:path";
|
|
26
|
+
import { createHash } from "node:crypto";
|
|
27
|
+
import matter from "gray-matter";
|
|
28
|
+
import yaml from "js-yaml";
|
|
29
|
+
import { VERSION } from "./version.js";
|
|
30
|
+
import { SearchEngine, DEFAULT_SEARCH_CONFIG } from "./search.js";
|
|
31
|
+
import { extractText, extractDocument, guessMime } from "./extraction.js";
|
|
32
|
+
// System pages that lint should treat specially
|
|
33
|
+
const SYSTEM_PAGES = new Set(["index.md", "log.md", "timeline.md"]);
|
|
34
|
+
/** Check if a page path is a system page.
|
|
35
|
+
* Root-level: index.md, log.md, timeline.md.
|
|
36
|
+
* Nested: any * /index.md — reserved for auto-generated directory indexes. */
|
|
37
|
+
function isSystemPage(pagePath) {
|
|
38
|
+
const normalized = pagePath.replace(/\\/g, "/");
|
|
39
|
+
if (SYSTEM_PAGES.has(normalized))
|
|
40
|
+
return true;
|
|
41
|
+
return normalized.endsWith("/index.md");
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Validate that a user-supplied relative path stays within the base directory.
|
|
45
|
+
* Prevents directory traversal attacks (e.g. "../../etc/passwd").
|
|
46
|
+
* Returns the resolved absolute path if safe, throws otherwise.
|
|
47
|
+
*/
|
|
48
|
+
export function safePath(base, userPath) {
|
|
49
|
+
if (!userPath || typeof userPath !== "string") {
|
|
50
|
+
throw new Error("Path must be a non-empty string");
|
|
51
|
+
}
|
|
52
|
+
// Reject absolute paths outright
|
|
53
|
+
if (userPath.startsWith("/") || userPath.startsWith("\\")) {
|
|
54
|
+
throw new Error(`Absolute paths are not allowed: "${userPath}"`);
|
|
55
|
+
}
|
|
56
|
+
// Reject null bytes (poison byte attack)
|
|
57
|
+
if (userPath.includes("\0")) {
|
|
58
|
+
throw new Error("Path contains null bytes");
|
|
59
|
+
}
|
|
60
|
+
const resolved = resolve(base, userPath);
|
|
61
|
+
const normalizedBase = resolve(base);
|
|
62
|
+
if (!resolved.startsWith(normalizedBase + "/")) {
|
|
63
|
+
throw new Error(`Path traversal detected: "${userPath}" escapes the allowed directory`);
|
|
64
|
+
}
|
|
65
|
+
return resolved;
|
|
66
|
+
}
|
|
67
|
+
/** Split markdown into sections by headings.
|
|
68
|
+
* Correctly skips heading-like lines inside fenced code blocks (``` or ~~~).
|
|
69
|
+
* The leading frontmatter block (--- ... ---) is returned as the first section
|
|
70
|
+
* with heading "" and level 0. */
|
|
71
|
+
export function splitSections(markdown) {
|
|
72
|
+
const lines = markdown.split("\n");
|
|
73
|
+
const sections = [];
|
|
74
|
+
let buf = [];
|
|
75
|
+
let currentHeading = "";
|
|
76
|
+
let currentLevel = 0;
|
|
77
|
+
let inFrontmatter = false;
|
|
78
|
+
let inCodeBlock = false;
|
|
79
|
+
for (let i = 0; i < lines.length; i++) {
|
|
80
|
+
const line = lines[i];
|
|
81
|
+
// Frontmatter: first line must be exactly "---"
|
|
82
|
+
if (i === 0 && line.trim() === "---") {
|
|
83
|
+
inFrontmatter = true;
|
|
84
|
+
buf.push(line);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (inFrontmatter) {
|
|
88
|
+
buf.push(line);
|
|
89
|
+
if (line.trim() === "---" && i > 0)
|
|
90
|
+
inFrontmatter = false;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
// Code fence toggle (``` or ~~~, optionally with language tag)
|
|
94
|
+
if (/^(`{3,}|~{3,})/.test(line)) {
|
|
95
|
+
inCodeBlock = !inCodeBlock;
|
|
96
|
+
buf.push(line);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
// Only detect headings outside code blocks
|
|
100
|
+
const headingMatch = !inCodeBlock && line.match(/^(#{1,6})\s+(.*)/);
|
|
101
|
+
if (headingMatch) {
|
|
102
|
+
sections.push({ heading: currentHeading, level: currentLevel, content: buf.join("\n") });
|
|
103
|
+
buf = [line];
|
|
104
|
+
currentHeading = line.trimEnd();
|
|
105
|
+
currentLevel = headingMatch[1].length;
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
buf.push(line);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (buf.length > 0) {
|
|
112
|
+
sections.push({ heading: currentHeading, level: currentLevel, content: buf.join("\n") });
|
|
113
|
+
}
|
|
114
|
+
return sections;
|
|
115
|
+
}
|
|
116
|
+
/** Build a TOC string from sections. Indented relative to the shallowest heading level. */
|
|
117
|
+
export function buildToc(sections) {
|
|
118
|
+
const headingSections = sections.filter(s => s.heading !== "");
|
|
119
|
+
if (headingSections.length === 0)
|
|
120
|
+
return "";
|
|
121
|
+
const minLevel = Math.min(...headingSections.map(s => s.level));
|
|
122
|
+
return headingSections
|
|
123
|
+
.map(s => " ".repeat(s.level - minLevel) + s.heading)
|
|
124
|
+
.join("\n");
|
|
125
|
+
}
|
|
126
|
+
/** Find a section by heading text. Case-insensitive, partial match, `##` prefix optional. */
|
|
127
|
+
export function findSectionByHeading(sections, query) {
|
|
128
|
+
const q = query.toLowerCase().replace(/^#{1,6}\s*/, "").trim();
|
|
129
|
+
return sections.find(s => s.heading.toLowerCase().replace(/^#{1,6}\s*/, "").trim().includes(q));
|
|
130
|
+
}
|
|
131
|
+
// ── Wiki Class ────────────────────────────────────────────────────
|
|
132
|
+
export class Wiki {
|
|
133
|
+
config;
|
|
134
|
+
searchEngine;
|
|
135
|
+
/** Lazy cache of title→slug pairs for autoLink. Invalidated incrementally on write/delete. */
|
|
136
|
+
titleIndexCache = null;
|
|
137
|
+
/**
|
|
138
|
+
* @param root — path to config root (where .agent-wiki.yaml lives)
|
|
139
|
+
* @param workspace — override workspace directory (all data: wiki/, raw/, schemas/).
|
|
140
|
+
* If not set, falls back to: AGENT_WIKI_WORKSPACE env → config file → root.
|
|
141
|
+
*/
|
|
142
|
+
constructor(root, workspace) {
|
|
143
|
+
const resolvedRoot = resolve(root ?? ".");
|
|
144
|
+
this.config = Wiki.loadConfig(resolvedRoot, workspace);
|
|
145
|
+
this.searchEngine = new SearchEngine();
|
|
146
|
+
this.searchEngine.setLoader(() => this.loadAllPages());
|
|
147
|
+
this.searchEngine.setConfig(this.config.search);
|
|
148
|
+
// Load persisted vector index if hybrid mode is enabled
|
|
149
|
+
if (this.config.search.hybrid) {
|
|
150
|
+
this.loadVectorIndex();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** Load and parse all wiki pages from disk. Used as search index loader. */
|
|
154
|
+
loadAllPages() {
|
|
155
|
+
return this.listAllPages()
|
|
156
|
+
.map((p) => this.read(p))
|
|
157
|
+
.filter((p) => p !== null);
|
|
158
|
+
}
|
|
159
|
+
// ── Init ──────────────────────────────────────────────────────
|
|
160
|
+
/**
|
|
161
|
+
* Initialize a new knowledge base.
|
|
162
|
+
* @param path — config root (where .agent-wiki.yaml is created)
|
|
163
|
+
* @param workspace — optional separate workspace directory for all data.
|
|
164
|
+
* If set, wiki/, raw/, schemas/ go there instead of path.
|
|
165
|
+
*/
|
|
166
|
+
static init(path, workspace) {
|
|
167
|
+
const configRoot = resolve(path);
|
|
168
|
+
const wsRoot = workspace ? resolve(workspace) : configRoot;
|
|
169
|
+
const wikiDir = join(wsRoot, "wiki");
|
|
170
|
+
const rawDir = join(wsRoot, "raw");
|
|
171
|
+
const schemasDir = join(wsRoot, "schemas");
|
|
172
|
+
for (const dir of [configRoot, wsRoot, wikiDir, rawDir, schemasDir]) {
|
|
173
|
+
mkdirSync(dir, { recursive: true });
|
|
174
|
+
}
|
|
175
|
+
const now = new Date().toISOString();
|
|
176
|
+
const nowShort = now.replace("T", " ").slice(0, 16) + " UTC";
|
|
177
|
+
// index.md
|
|
178
|
+
writeFileSync(join(wikiDir, "index.md"), `---
|
|
179
|
+
title: Knowledge Base Index
|
|
180
|
+
type: index
|
|
181
|
+
created: "${now}"
|
|
182
|
+
updated: "${now}"
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
# Knowledge Base Index
|
|
186
|
+
|
|
187
|
+
## Categories
|
|
188
|
+
|
|
189
|
+
_No pages yet. Use your agent to add knowledge._
|
|
190
|
+
|
|
191
|
+
## Recent Updates
|
|
192
|
+
|
|
193
|
+
_No updates yet._
|
|
194
|
+
`);
|
|
195
|
+
// log.md
|
|
196
|
+
writeFileSync(join(wikiDir, "log.md"), `---
|
|
197
|
+
title: Operation Log
|
|
198
|
+
type: log
|
|
199
|
+
created: "${now}"
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
# Operation Log
|
|
203
|
+
|
|
204
|
+
| Time | Operation | Page | Summary |
|
|
205
|
+
|------|-----------|------|---------|
|
|
206
|
+
| ${nowShort} | init | — | Knowledge base initialized |
|
|
207
|
+
`);
|
|
208
|
+
// timeline.md
|
|
209
|
+
writeFileSync(join(wikiDir, "timeline.md"), `---
|
|
210
|
+
title: Knowledge Timeline
|
|
211
|
+
type: timeline
|
|
212
|
+
created: "${now}"
|
|
213
|
+
updated: "${now}"
|
|
214
|
+
---
|
|
215
|
+
|
|
216
|
+
# Knowledge Timeline
|
|
217
|
+
|
|
218
|
+
_Chronological view of all knowledge in this wiki._
|
|
219
|
+
|
|
220
|
+
## ${now.slice(0, 10)}
|
|
221
|
+
|
|
222
|
+
- **init** — Knowledge base created
|
|
223
|
+
`);
|
|
224
|
+
// default config — include workspace if separate from config root
|
|
225
|
+
const configData = {
|
|
226
|
+
version: "2",
|
|
227
|
+
wiki: {
|
|
228
|
+
...(workspace ? { workspace: wsRoot } : {}),
|
|
229
|
+
path: "wiki/",
|
|
230
|
+
raw_path: "raw/",
|
|
231
|
+
schemas_path: "schemas/",
|
|
232
|
+
},
|
|
233
|
+
lint: {
|
|
234
|
+
check_orphans: true,
|
|
235
|
+
check_stale_days: 30,
|
|
236
|
+
check_missing_sources: true,
|
|
237
|
+
check_contradictions: true,
|
|
238
|
+
check_integrity: true,
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
writeFileSync(join(configRoot, ".agent-wiki.yaml"), yaml.dump(configData, { lineWidth: 100 }));
|
|
242
|
+
// default schemas
|
|
243
|
+
writeDefaultSchemas(schemasDir);
|
|
244
|
+
// .gitignore in workspace (if separate, also add one there)
|
|
245
|
+
writeFileSync(join(configRoot, ".gitignore"), "node_modules/\ndist/\n.env\n.lint-cache.json\n");
|
|
246
|
+
if (workspace && wsRoot !== configRoot) {
|
|
247
|
+
writeFileSync(join(wsRoot, ".gitignore"), "# Agent Wiki workspace data\n.lint-cache.json\n");
|
|
248
|
+
}
|
|
249
|
+
return new Wiki(configRoot, workspace);
|
|
250
|
+
}
|
|
251
|
+
// ── Config ────────────────────────────────────────────────────
|
|
252
|
+
/**
|
|
253
|
+
* Load config from .agent-wiki.yaml.
|
|
254
|
+
*
|
|
255
|
+
* Workspace resolution priority:
|
|
256
|
+
* 1. Explicit `workspaceOverride` parameter (from CLI --workspace)
|
|
257
|
+
* 2. `AGENT_WIKI_WORKSPACE` environment variable
|
|
258
|
+
* 3. `workspace` field in .agent-wiki.yaml (absolute, or relative to config file)
|
|
259
|
+
* 4. Fall back to config root itself
|
|
260
|
+
*
|
|
261
|
+
* All data dirs (wiki/, raw/, schemas/) resolve relative to workspace.
|
|
262
|
+
*/
|
|
263
|
+
static loadConfig(root, workspaceOverride) {
|
|
264
|
+
let raw = {};
|
|
265
|
+
const configPath = join(root, ".agent-wiki.yaml");
|
|
266
|
+
const homeConfigPath = join(process.env.HOME ?? "~", ".agent-wiki.yaml");
|
|
267
|
+
if (existsSync(configPath)) {
|
|
268
|
+
raw = yaml.load(readFileSync(configPath, "utf-8")) ?? {};
|
|
269
|
+
}
|
|
270
|
+
else if (existsSync(homeConfigPath)) {
|
|
271
|
+
raw = yaml.load(readFileSync(homeConfigPath, "utf-8")) ?? {};
|
|
272
|
+
}
|
|
273
|
+
const wikiData = (raw.wiki ?? {});
|
|
274
|
+
const lintData = (raw.lint ?? {});
|
|
275
|
+
const securityData = (raw.security ?? {});
|
|
276
|
+
const atlassianData = (raw.atlassian ?? {});
|
|
277
|
+
const searchData = (raw.search ?? {});
|
|
278
|
+
const autoLinkData = (raw.auto_link ?? {});
|
|
279
|
+
// Resolve workspace directory (priority: override > env > config > root)
|
|
280
|
+
let workspace;
|
|
281
|
+
if (workspaceOverride) {
|
|
282
|
+
workspace = resolve(workspaceOverride);
|
|
283
|
+
}
|
|
284
|
+
else if (process.env.AGENT_WIKI_WORKSPACE) {
|
|
285
|
+
workspace = resolve(process.env.AGENT_WIKI_WORKSPACE);
|
|
286
|
+
}
|
|
287
|
+
else if (wikiData.workspace) {
|
|
288
|
+
// Relative paths in config resolve against the config file's directory
|
|
289
|
+
workspace = resolve(root, wikiData.workspace);
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
workspace = root;
|
|
293
|
+
}
|
|
294
|
+
// Ensure workspace exists
|
|
295
|
+
mkdirSync(workspace, { recursive: true });
|
|
296
|
+
// Resolve allowed source directories for rawAdd sourcePath.
|
|
297
|
+
// Default: only the workspace itself. Config can widen to explicit dirs.
|
|
298
|
+
const configuredDirs = securityData.allowed_source_dirs;
|
|
299
|
+
const allowedSourceDirs = Array.isArray(configuredDirs)
|
|
300
|
+
? configuredDirs.map(d => resolve(root, d)) // relative to config root
|
|
301
|
+
: [workspace]; // secure default
|
|
302
|
+
return {
|
|
303
|
+
configRoot: root,
|
|
304
|
+
workspace,
|
|
305
|
+
wikiDir: join(workspace, wikiData.path ?? "wiki"),
|
|
306
|
+
rawDir: join(workspace, wikiData.raw_path ?? "raw"),
|
|
307
|
+
schemasDir: join(workspace, wikiData.schemas_path ?? "schemas"),
|
|
308
|
+
lint: {
|
|
309
|
+
checkOrphans: lintData.check_orphans ?? true,
|
|
310
|
+
checkStaleDays: lintData.check_stale_days ?? 30,
|
|
311
|
+
checkMissingSources: lintData.check_missing_sources ?? true,
|
|
312
|
+
checkContradictions: lintData.check_contradictions ?? true,
|
|
313
|
+
checkIntegrity: lintData.check_integrity ?? true,
|
|
314
|
+
},
|
|
315
|
+
allowedSourceDirs,
|
|
316
|
+
atlassian: {
|
|
317
|
+
allowedHosts: Array.isArray(atlassianData.allowed_hosts) ? atlassianData.allowed_hosts : [],
|
|
318
|
+
maxPages: atlassianData.max_pages ?? 100,
|
|
319
|
+
maxAttachmentSize: atlassianData.max_attachment_size ?? 10 * 1024 * 1024,
|
|
320
|
+
},
|
|
321
|
+
search: {
|
|
322
|
+
hybrid: searchData.hybrid ?? DEFAULT_SEARCH_CONFIG.hybrid,
|
|
323
|
+
bm25Weight: searchData.bm25_weight ?? DEFAULT_SEARCH_CONFIG.bm25Weight,
|
|
324
|
+
vectorWeight: searchData.vector_weight ?? DEFAULT_SEARCH_CONFIG.vectorWeight,
|
|
325
|
+
model: searchData.model ?? DEFAULT_SEARCH_CONFIG.model,
|
|
326
|
+
},
|
|
327
|
+
autoLink: {
|
|
328
|
+
enabled: autoLinkData.enabled ?? true,
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
// ═══════════════════════════════════════════════════════════════
|
|
333
|
+
// RAW LAYER — Immutable source documents
|
|
334
|
+
// ═══════════════════════════════════════════════════════════════
|
|
335
|
+
/** Register a raw document. Copies file to raw/ with metadata sidecar.
|
|
336
|
+
* If content is provided as string, writes it directly.
|
|
337
|
+
* If sourcePath is an existing file, copies it.
|
|
338
|
+
* Raw files are IMMUTABLE — re-adding the same path is an error. */
|
|
339
|
+
rawAdd(filename, opts) {
|
|
340
|
+
// ── Directory detection: if sourcePath is a directory, import all files ──
|
|
341
|
+
if (opts.sourcePath) {
|
|
342
|
+
const resolvedSource = resolve(opts.sourcePath);
|
|
343
|
+
this._validateSourcePath(resolvedSource, opts.sourcePath);
|
|
344
|
+
if (existsSync(resolvedSource) && statSync(resolvedSource).isDirectory()) {
|
|
345
|
+
return this._rawAddDirectory(filename, resolvedSource, opts);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
// ── Single file path ──
|
|
349
|
+
return this._rawAddSingleFile(filename, opts);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Validate that a sourcePath is within allowed directories.
|
|
353
|
+
*/
|
|
354
|
+
_validateSourcePath(resolvedSource, originalPath) {
|
|
355
|
+
const allowed = this.config.allowedSourceDirs.some(dir => resolvedSource.startsWith(resolve(dir) + "/") || resolvedSource === resolve(dir));
|
|
356
|
+
if (!allowed) {
|
|
357
|
+
throw new Error(`sourcePath "${originalPath}" is outside allowed directories. ` +
|
|
358
|
+
`Allowed: [${this.config.allowedSourceDirs.join(", ")}]. ` +
|
|
359
|
+
`Configure security.allowed_source_dirs in .agent-wiki.yaml to widen access.`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Import all files from a directory into raw/<filename>/.
|
|
364
|
+
* Preserves subdirectory structure. Optionally filters by glob pattern.
|
|
365
|
+
*/
|
|
366
|
+
_rawAddDirectory(prefix, dirPath, opts) {
|
|
367
|
+
const files = this._walkDirectory(dirPath, dirPath);
|
|
368
|
+
// Filter by pattern (simple glob: *.html, *.xlsx, etc.)
|
|
369
|
+
const filtered = opts.pattern
|
|
370
|
+
? files.filter(f => matchSimpleGlob(f, opts.pattern))
|
|
371
|
+
: files;
|
|
372
|
+
if (filtered.length === 0) {
|
|
373
|
+
throw new Error(`No files found in directory "${dirPath}"` +
|
|
374
|
+
(opts.pattern ? ` matching pattern "${opts.pattern}"` : ""));
|
|
375
|
+
}
|
|
376
|
+
const docs = [];
|
|
377
|
+
for (const relFile of filtered) {
|
|
378
|
+
const targetFilename = join(prefix, relFile);
|
|
379
|
+
const srcFile = join(dirPath, relFile);
|
|
380
|
+
const doc = this._rawAddSingleFile(targetFilename, {
|
|
381
|
+
sourcePath: srcFile,
|
|
382
|
+
sourceUrl: opts.sourceUrl,
|
|
383
|
+
description: opts.description,
|
|
384
|
+
tags: opts.tags,
|
|
385
|
+
autoVersion: opts.autoVersion,
|
|
386
|
+
});
|
|
387
|
+
docs.push(doc);
|
|
388
|
+
}
|
|
389
|
+
this.log("raw-add-dir", prefix, `Imported directory: ${docs.length} files into raw/${prefix}/`);
|
|
390
|
+
return docs;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Walk a directory recursively, returning relative file paths.
|
|
394
|
+
*/
|
|
395
|
+
_walkDirectory(dir, root) {
|
|
396
|
+
const result = [];
|
|
397
|
+
if (!existsSync(dir))
|
|
398
|
+
return result;
|
|
399
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
400
|
+
if (entry.name.startsWith("."))
|
|
401
|
+
continue;
|
|
402
|
+
const full = join(dir, entry.name);
|
|
403
|
+
if (entry.isDirectory()) {
|
|
404
|
+
result.push(...this._walkDirectory(full, root));
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
result.push(relative(root, full));
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return result.sort();
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Add a single file to raw/. Core logic extracted from rawAdd.
|
|
414
|
+
*/
|
|
415
|
+
_rawAddSingleFile(filename, opts) {
|
|
416
|
+
let actualFilename = filename;
|
|
417
|
+
// Auto-version: if file exists and autoVersion is true, find next version
|
|
418
|
+
if (opts.autoVersion && existsSync(safePath(this.config.rawDir, filename))) {
|
|
419
|
+
actualFilename = this.nextVersionFilename(filename);
|
|
420
|
+
}
|
|
421
|
+
const rawPath = safePath(this.config.rawDir, actualFilename);
|
|
422
|
+
const metaPath = rawPath + ".meta.yaml";
|
|
423
|
+
// Immutability guard — never overwrite existing raw files
|
|
424
|
+
if (existsSync(rawPath)) {
|
|
425
|
+
throw new Error(`Raw file already exists: ${actualFilename}. Raw files are immutable.`);
|
|
426
|
+
}
|
|
427
|
+
mkdirSync(dirname(rawPath), { recursive: true });
|
|
428
|
+
// Write content
|
|
429
|
+
if (opts.content !== undefined) {
|
|
430
|
+
writeFileSync(rawPath, opts.content);
|
|
431
|
+
}
|
|
432
|
+
else if (opts.sourcePath) {
|
|
433
|
+
// Security: restrict sourcePath to allowed directories BEFORE any filesystem access
|
|
434
|
+
const resolvedSource = resolve(opts.sourcePath);
|
|
435
|
+
this._validateSourcePath(resolvedSource, opts.sourcePath);
|
|
436
|
+
if (!existsSync(resolvedSource)) {
|
|
437
|
+
throw new Error("Either content or a valid sourcePath is required");
|
|
438
|
+
}
|
|
439
|
+
copyFileSync(resolvedSource, rawPath);
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
throw new Error("Either content or a valid sourcePath is required");
|
|
443
|
+
}
|
|
444
|
+
// Compute hash and size
|
|
445
|
+
const buf = readFileSync(rawPath);
|
|
446
|
+
const sha256 = createHash("sha256").update(buf).digest("hex");
|
|
447
|
+
const size = buf.length;
|
|
448
|
+
const now = new Date().toISOString();
|
|
449
|
+
const doc = {
|
|
450
|
+
path: actualFilename,
|
|
451
|
+
sourceUrl: opts.sourceUrl,
|
|
452
|
+
downloadedAt: now,
|
|
453
|
+
sha256,
|
|
454
|
+
size,
|
|
455
|
+
mimeType: opts.mimeType ?? guessMime(filename),
|
|
456
|
+
description: opts.description,
|
|
457
|
+
tags: opts.tags,
|
|
458
|
+
};
|
|
459
|
+
// Write metadata sidecar
|
|
460
|
+
writeFileSync(metaPath, yaml.dump(doc, { lineWidth: 100 }));
|
|
461
|
+
this.log("raw-add", actualFilename, `Added raw: ${actualFilename} (${formatBytes(size)}, sha256:${sha256.slice(0, 12)}...)`);
|
|
462
|
+
return doc;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Compute the next versioned filename for auto-versioning.
|
|
466
|
+
* report.xlsx → report_v2.xlsx, report_v2.xlsx → report_v3.xlsx, etc.
|
|
467
|
+
*/
|
|
468
|
+
nextVersionFilename(filename) {
|
|
469
|
+
const ext = extname(filename);
|
|
470
|
+
const base = filename.slice(0, filename.length - ext.length);
|
|
471
|
+
// Strip existing _vN suffix to find the root name
|
|
472
|
+
const vMatch = base.match(/^(.+?)(_v(\d+))?$/);
|
|
473
|
+
const root = vMatch?.[1] ?? base;
|
|
474
|
+
// Scan existing files to find highest version
|
|
475
|
+
let maxVersion = 1; // original file counts as v1
|
|
476
|
+
if (!existsSync(this.config.rawDir))
|
|
477
|
+
return `${root}_v2${ext}`;
|
|
478
|
+
for (const file of listAllFiles(this.config.rawDir, this.config.rawDir)) {
|
|
479
|
+
if (file.endsWith(".meta.yaml"))
|
|
480
|
+
continue;
|
|
481
|
+
const fExt = extname(file);
|
|
482
|
+
const fBase = file.slice(0, file.length - fExt.length);
|
|
483
|
+
if (fExt !== ext)
|
|
484
|
+
continue;
|
|
485
|
+
// Check if this file matches root or root_vN pattern
|
|
486
|
+
if (fBase === root) {
|
|
487
|
+
maxVersion = Math.max(maxVersion, 1);
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
const m = fBase.match(new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}_v(\\d+)$`));
|
|
491
|
+
if (m) {
|
|
492
|
+
maxVersion = Math.max(maxVersion, parseInt(m[1], 10));
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return `${root}_v${maxVersion + 1}${ext}`;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Write a parsed artifact under raw/parsed/. Unlike rawAdd, these are
|
|
500
|
+
* idempotent — re-parsing the same source overwrites the previous output.
|
|
501
|
+
* A .meta.yaml sidecar is written so lint/integrity checks pass.
|
|
502
|
+
*/
|
|
503
|
+
rawAddParsedArtifact(relativePath, content, opts) {
|
|
504
|
+
const fullPath = safePath(this.config.rawDir, relativePath);
|
|
505
|
+
mkdirSync(dirname(fullPath), { recursive: true });
|
|
506
|
+
writeFileSync(fullPath, content, "utf-8");
|
|
507
|
+
const buf = Buffer.from(content, "utf-8");
|
|
508
|
+
const sha256 = createHash("sha256").update(buf).digest("hex");
|
|
509
|
+
const doc = {
|
|
510
|
+
path: relativePath,
|
|
511
|
+
downloadedAt: new Date().toISOString(),
|
|
512
|
+
sha256,
|
|
513
|
+
size: buf.length,
|
|
514
|
+
mimeType: opts?.mimeType ?? "application/json",
|
|
515
|
+
description: opts?.description ?? "Parsed artifact generated by code_parse",
|
|
516
|
+
};
|
|
517
|
+
writeFileSync(fullPath + ".meta.yaml", yaml.dump(doc, { lineWidth: 100 }));
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* List all versions of a raw file, sorted by version number, with the latest marked.
|
|
521
|
+
* rawVersions("report.xlsx") → { versions: [...], latest: "report_v3.xlsx" }
|
|
522
|
+
*/
|
|
523
|
+
rawVersions(filename) {
|
|
524
|
+
const ext = extname(filename);
|
|
525
|
+
const base = filename.slice(0, filename.length - ext.length);
|
|
526
|
+
const vMatch = base.match(/^(.+?)(_v(\d+))?$/);
|
|
527
|
+
const root = vMatch?.[1] ?? base;
|
|
528
|
+
const versions = [];
|
|
529
|
+
if (!existsSync(this.config.rawDir))
|
|
530
|
+
return { versions, latest: null };
|
|
531
|
+
for (const file of listAllFiles(this.config.rawDir, this.config.rawDir)) {
|
|
532
|
+
if (file.endsWith(".meta.yaml"))
|
|
533
|
+
continue;
|
|
534
|
+
const fExt = extname(file);
|
|
535
|
+
const fBase = file.slice(0, file.length - fExt.length);
|
|
536
|
+
if (fExt !== ext)
|
|
537
|
+
continue;
|
|
538
|
+
let version = -1;
|
|
539
|
+
if (fBase === root) {
|
|
540
|
+
version = 1;
|
|
541
|
+
}
|
|
542
|
+
else {
|
|
543
|
+
const m = fBase.match(new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}_v(\\d+)$`));
|
|
544
|
+
if (m)
|
|
545
|
+
version = parseInt(m[1], 10);
|
|
546
|
+
}
|
|
547
|
+
if (version < 0)
|
|
548
|
+
continue;
|
|
549
|
+
const metaPath = join(this.config.rawDir, file) + ".meta.yaml";
|
|
550
|
+
if (existsSync(metaPath)) {
|
|
551
|
+
const meta = yaml.load(readFileSync(metaPath, "utf-8"));
|
|
552
|
+
versions.push({ path: meta.path, version, downloadedAt: meta.downloadedAt, size: meta.size, sha256: meta.sha256 });
|
|
553
|
+
}
|
|
554
|
+
else {
|
|
555
|
+
const fullPath = join(this.config.rawDir, file);
|
|
556
|
+
const buf = readFileSync(fullPath);
|
|
557
|
+
versions.push({
|
|
558
|
+
path: file,
|
|
559
|
+
version,
|
|
560
|
+
downloadedAt: statSync(fullPath).mtime.toISOString(),
|
|
561
|
+
size: buf.length,
|
|
562
|
+
sha256: createHash("sha256").update(buf).digest("hex"),
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
versions.sort((a, b) => a.version - b.version);
|
|
567
|
+
const latest = versions.length > 0 ? versions[versions.length - 1].path : null;
|
|
568
|
+
return { versions, latest };
|
|
569
|
+
}
|
|
570
|
+
/** List all raw documents with metadata. */
|
|
571
|
+
rawList() {
|
|
572
|
+
if (!existsSync(this.config.rawDir))
|
|
573
|
+
return [];
|
|
574
|
+
const docs = [];
|
|
575
|
+
for (const file of listAllFiles(this.config.rawDir, this.config.rawDir)) {
|
|
576
|
+
if (file.endsWith(".meta.yaml"))
|
|
577
|
+
continue; // skip sidecars
|
|
578
|
+
const metaPath = join(this.config.rawDir, file) + ".meta.yaml";
|
|
579
|
+
if (existsSync(metaPath)) {
|
|
580
|
+
const meta = yaml.load(readFileSync(metaPath, "utf-8"));
|
|
581
|
+
docs.push(meta);
|
|
582
|
+
}
|
|
583
|
+
else {
|
|
584
|
+
// raw file without metadata — create minimal entry
|
|
585
|
+
const fullPath = join(this.config.rawDir, file);
|
|
586
|
+
const buf = readFileSync(fullPath);
|
|
587
|
+
docs.push({
|
|
588
|
+
path: file,
|
|
589
|
+
downloadedAt: statSync(fullPath).mtime.toISOString(),
|
|
590
|
+
sha256: createHash("sha256").update(buf).digest("hex"),
|
|
591
|
+
size: buf.length,
|
|
592
|
+
mimeType: guessMime(file),
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return docs;
|
|
597
|
+
}
|
|
598
|
+
/** Fast count of raw files (skips YAML/meta parsing — O(readdir) only).
|
|
599
|
+
* Used by rebuildIndex where only the count is needed. */
|
|
600
|
+
rawCount() {
|
|
601
|
+
if (!existsSync(this.config.rawDir))
|
|
602
|
+
return 0;
|
|
603
|
+
return countNonMetaFiles(this.config.rawDir);
|
|
604
|
+
}
|
|
605
|
+
/** Report which raw/ files are not yet referenced by any wiki page.
|
|
606
|
+
* Matches against frontmatter `sources` and inline `raw/...` body references.
|
|
607
|
+
* Parsed-artifact directory `parsed/` is excluded — those are derived, not source.
|
|
608
|
+
* URL sources are normalized (lowercased scheme+host, trailing slash stripped)
|
|
609
|
+
* before matching against each raw's `sourceUrl`. */
|
|
610
|
+
rawCoverage(opts) {
|
|
611
|
+
const raws = this.rawList().filter(r => !r.path.startsWith("parsed/"));
|
|
612
|
+
const pages = this.listAllPages();
|
|
613
|
+
const referencedPaths = new Set();
|
|
614
|
+
const referencedUrls = new Set();
|
|
615
|
+
const normalizePath = (s) => s.trim().replace(/^\.\//, "").replace(/^raw\//, "");
|
|
616
|
+
const normalizeUrl = (u) => {
|
|
617
|
+
try {
|
|
618
|
+
const p = new URL(u.trim());
|
|
619
|
+
let path = p.pathname;
|
|
620
|
+
if (path.length > 1 && path.endsWith("/"))
|
|
621
|
+
path = path.slice(0, -1);
|
|
622
|
+
// URL ctor already lowercases protocol + host per WHATWG.
|
|
623
|
+
return `${p.protocol}//${p.host}${path}${p.search}${p.hash}`;
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
return u.trim();
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
for (const pagePath of pages) {
|
|
630
|
+
const page = this.read(pagePath);
|
|
631
|
+
if (!page)
|
|
632
|
+
continue;
|
|
633
|
+
for (const src of page.sources) {
|
|
634
|
+
const t = src.trim();
|
|
635
|
+
if (/^https?:\/\//i.test(t))
|
|
636
|
+
referencedUrls.add(normalizeUrl(t));
|
|
637
|
+
else
|
|
638
|
+
referencedPaths.add(normalizePath(t));
|
|
639
|
+
}
|
|
640
|
+
// Body references: match raw/<path> and strip trailing punctuation
|
|
641
|
+
// so "See raw/foo.pdf." captures "foo.pdf", not "foo.pdf.".
|
|
642
|
+
for (const m of page.content.matchAll(/\braw\/(\S+)/g)) {
|
|
643
|
+
const cleaned = m[1].replace(/[.,;:!?)\]`"'*]+$/, "");
|
|
644
|
+
if (cleaned)
|
|
645
|
+
referencedPaths.add(cleaned);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
const filtered = opts?.tag
|
|
649
|
+
? raws.filter(r => r.tags?.includes(opts.tag))
|
|
650
|
+
: raws;
|
|
651
|
+
const uncovered = filtered.filter(r => {
|
|
652
|
+
if (referencedPaths.has(r.path))
|
|
653
|
+
return false;
|
|
654
|
+
if (r.sourceUrl && referencedUrls.has(normalizeUrl(r.sourceUrl)))
|
|
655
|
+
return false;
|
|
656
|
+
return true;
|
|
657
|
+
});
|
|
658
|
+
const sort = opts?.sort ?? "newest";
|
|
659
|
+
uncovered.sort((a, b) => {
|
|
660
|
+
if (sort === "largest")
|
|
661
|
+
return b.size - a.size;
|
|
662
|
+
if (sort === "oldest")
|
|
663
|
+
return a.downloadedAt.localeCompare(b.downloadedAt);
|
|
664
|
+
return b.downloadedAt.localeCompare(a.downloadedAt);
|
|
665
|
+
});
|
|
666
|
+
const limit = opts?.limit ?? 50;
|
|
667
|
+
const totalFiltered = filtered.length;
|
|
668
|
+
const uncoveredCount = uncovered.length;
|
|
669
|
+
const truncated = uncoveredCount > limit;
|
|
670
|
+
return {
|
|
671
|
+
totalRaw: totalFiltered,
|
|
672
|
+
coveredRaw: totalFiltered - uncoveredCount,
|
|
673
|
+
uncoveredRaw: uncoveredCount,
|
|
674
|
+
coverageRatio: totalFiltered > 0 ? (totalFiltered - uncoveredCount) / totalFiltered : 1,
|
|
675
|
+
uncovered: uncovered.slice(0, limit).map(r => ({
|
|
676
|
+
path: r.path,
|
|
677
|
+
size: r.size,
|
|
678
|
+
mimeType: r.mimeType,
|
|
679
|
+
downloadedAt: r.downloadedAt,
|
|
680
|
+
tags: r.tags,
|
|
681
|
+
sourceUrl: r.sourceUrl,
|
|
682
|
+
description: r.description,
|
|
683
|
+
})),
|
|
684
|
+
truncated,
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
/** Read a raw document's content and metadata.
|
|
688
|
+
* Text/SVG/JSON/XML files return content as UTF-8 string.
|
|
689
|
+
* Document files (PDF, DOCX, XLSX, PPTX) are extracted via Node.js libraries.
|
|
690
|
+
* For PDFs, optional `pages` parameter limits extraction to specific pages (e.g. "1-5").
|
|
691
|
+
* Image files (PNG, JPEG, GIF, WEBP, etc.) return base64-encoded data for display.
|
|
692
|
+
* Other binary files return metadata only. */
|
|
693
|
+
async rawRead(filename, opts) {
|
|
694
|
+
const fullPath = safePath(this.config.rawDir, filename);
|
|
695
|
+
if (!existsSync(fullPath))
|
|
696
|
+
return null;
|
|
697
|
+
const metaPath = fullPath + ".meta.yaml";
|
|
698
|
+
const meta = existsSync(metaPath)
|
|
699
|
+
? yaml.load(readFileSync(metaPath, "utf-8"))
|
|
700
|
+
: null;
|
|
701
|
+
const mime = meta?.mimeType ?? guessMime(filename);
|
|
702
|
+
const isText = mime.startsWith("text/")
|
|
703
|
+
|| mime === "application/json"
|
|
704
|
+
|| mime === "application/xml"
|
|
705
|
+
|| mime === "application/sql"
|
|
706
|
+
|| mime === "application/rtf"
|
|
707
|
+
|| mime === "application/x-yaml"
|
|
708
|
+
|| mime === "image/svg+xml"; // SVG is XML text
|
|
709
|
+
if (isText) {
|
|
710
|
+
const raw = readFileSync(fullPath, "utf-8");
|
|
711
|
+
if (opts?.offset !== undefined || opts?.limit !== undefined) {
|
|
712
|
+
const lines = raw.split("\n");
|
|
713
|
+
const total_lines = lines.length;
|
|
714
|
+
const offset = Math.max(0, opts.offset ?? 0);
|
|
715
|
+
const limit = Math.min(500, Math.max(1, opts.limit ?? 200));
|
|
716
|
+
const slice = lines.slice(offset, offset + limit);
|
|
717
|
+
const truncated = offset + limit < total_lines;
|
|
718
|
+
return {
|
|
719
|
+
content: slice.join("\n"), meta, binary: false,
|
|
720
|
+
paginationMeta: { total_lines, offset, lines_returned: slice.length, truncated, next_offset: truncated ? offset + limit : null },
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
return { content: raw, meta, binary: false };
|
|
724
|
+
}
|
|
725
|
+
// Document formats — extract text via Node.js libraries
|
|
726
|
+
const ext = extname(filename).toLowerCase();
|
|
727
|
+
const extractable = new Set([".pdf", ".docx", ".xlsx", ".pptx", ".html", ".htm"]);
|
|
728
|
+
if (extractable.has(ext)) {
|
|
729
|
+
try {
|
|
730
|
+
if (ext === ".xlsx") {
|
|
731
|
+
const result = await extractDocument(fullPath, undefined, opts?.sheet);
|
|
732
|
+
const sheetNames = result.metadata?.sheetNames ?? [];
|
|
733
|
+
const content = result.segments.map(s => `--- Sheet: ${s.source.sheet} ---\n${s.text}`).join("\n\n");
|
|
734
|
+
return {
|
|
735
|
+
content: content || "(no content)",
|
|
736
|
+
meta, binary: false,
|
|
737
|
+
paginationMeta: { sheet_names: sheetNames, total_sheets: sheetNames.length, current_sheet: opts?.sheet },
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
if (ext === ".pptx") {
|
|
741
|
+
const result = await extractDocument(fullPath, opts?.pages);
|
|
742
|
+
const totalSlides = result.metadata?.totalSlides;
|
|
743
|
+
const content = result.segments.map(s => `--- Slide ${s.source.slide} ---\n${s.text}`).join("\n\n");
|
|
744
|
+
return {
|
|
745
|
+
content: content || "(no content)",
|
|
746
|
+
meta, binary: false,
|
|
747
|
+
paginationMeta: { total_slides: totalSlides },
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
// PDF — use extractDocument to get totalPages metadata
|
|
751
|
+
if (ext === ".pdf") {
|
|
752
|
+
const result = await extractDocument(fullPath, opts?.pages);
|
|
753
|
+
const totalPages = result.metadata?.totalPages;
|
|
754
|
+
if (result.segments.length === 0 && opts?.pages) {
|
|
755
|
+
return {
|
|
756
|
+
content: `(no pages matched range "${opts.pages}" — PDF has ${totalPages ?? "?"} pages)`,
|
|
757
|
+
meta, binary: false,
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
const prefix = opts?.pages ? `[Pages ${opts.pages} of ${totalPages ?? "?"}]\n` : "";
|
|
761
|
+
const body = result.segments.map(s => s.text).join("\n\n");
|
|
762
|
+
return {
|
|
763
|
+
content: prefix + body,
|
|
764
|
+
meta, binary: false,
|
|
765
|
+
...(opts?.pages ? { paginationMeta: { total_pages: totalPages } } : {}),
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
// DOCX / HTML — flat text extraction with optional line-based pagination
|
|
769
|
+
const text = await extractText(fullPath);
|
|
770
|
+
if (opts?.offset !== undefined || opts?.limit !== undefined) {
|
|
771
|
+
const lines = text.split("\n");
|
|
772
|
+
const total_lines = lines.length;
|
|
773
|
+
const offset = Math.max(0, opts.offset ?? 0);
|
|
774
|
+
const limit = Math.min(500, Math.max(1, opts.limit ?? 200));
|
|
775
|
+
const slice = lines.slice(offset, offset + limit);
|
|
776
|
+
const truncated = offset + limit < total_lines;
|
|
777
|
+
return {
|
|
778
|
+
content: slice.join("\n"), meta, binary: false,
|
|
779
|
+
paginationMeta: { total_lines, offset, lines_returned: slice.length, truncated, next_offset: truncated ? offset + limit : null },
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
return { content: text, meta, binary: false };
|
|
783
|
+
}
|
|
784
|
+
catch (e) {
|
|
785
|
+
const stat = statSync(fullPath);
|
|
786
|
+
return {
|
|
787
|
+
content: null, meta, binary: true,
|
|
788
|
+
note: `Text extraction failed: ${e.message}. File size: ${formatBytes(stat.size)}.`,
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// Image files — return base64-encoded data for display (max 10MB)
|
|
793
|
+
const isImage = mime.startsWith("image/") && mime !== "image/svg+xml";
|
|
794
|
+
if (isImage) {
|
|
795
|
+
const stat = statSync(fullPath);
|
|
796
|
+
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
797
|
+
if (stat.size <= MAX_IMAGE_BYTES) {
|
|
798
|
+
const data = readFileSync(fullPath).toString("base64");
|
|
799
|
+
return { content: null, meta, binary: true, imageData: { data, mimeType: mime } };
|
|
800
|
+
}
|
|
801
|
+
return {
|
|
802
|
+
content: null, meta, binary: true,
|
|
803
|
+
note: `Image too large to display (${formatBytes(stat.size)}). Maximum supported size is 10 MB.`,
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
// Other binary files — metadata only
|
|
807
|
+
return { content: null, meta, binary: true };
|
|
808
|
+
}
|
|
809
|
+
/** Verify integrity of all raw files against their stored hashes.
|
|
810
|
+
* When a `cache` is provided, files whose mtime+size haven't changed
|
|
811
|
+
* since the last check are skipped (cache hit). Cache entries are
|
|
812
|
+
* updated in-place for misses; the caller persists the cache. */
|
|
813
|
+
rawVerify(cache) {
|
|
814
|
+
const results = [];
|
|
815
|
+
if (!existsSync(this.config.rawDir))
|
|
816
|
+
return results;
|
|
817
|
+
for (const file of listAllFiles(this.config.rawDir, this.config.rawDir)) {
|
|
818
|
+
if (file.endsWith(".meta.yaml"))
|
|
819
|
+
continue;
|
|
820
|
+
const fullPath = join(this.config.rawDir, file);
|
|
821
|
+
const metaPath = fullPath + ".meta.yaml";
|
|
822
|
+
if (!existsSync(metaPath)) {
|
|
823
|
+
results.push({ path: file, status: "missing-meta" });
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
// Stat both files (cheap metadata-only I/O)
|
|
827
|
+
const fileStat = statSync(fullPath);
|
|
828
|
+
const metaStat = statSync(metaPath);
|
|
829
|
+
// Cache hit — mtime+size of both file and sidecar unchanged
|
|
830
|
+
const cached = cache?.entries[file];
|
|
831
|
+
if (cached &&
|
|
832
|
+
cached.fileMtimeMs === fileStat.mtimeMs &&
|
|
833
|
+
cached.fileSize === fileStat.size &&
|
|
834
|
+
cached.metaMtimeMs === metaStat.mtimeMs) {
|
|
835
|
+
results.push({ path: file, status: cached.status });
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
// Cache miss — full hash computation
|
|
839
|
+
const meta = yaml.load(readFileSync(metaPath, "utf-8"));
|
|
840
|
+
const buf = readFileSync(fullPath);
|
|
841
|
+
const actualHash = createHash("sha256").update(buf).digest("hex");
|
|
842
|
+
const status = actualHash === meta.sha256 ? "ok" : "corrupted";
|
|
843
|
+
results.push({ path: file, status });
|
|
844
|
+
// Update cache entry in-place
|
|
845
|
+
if (cache) {
|
|
846
|
+
cache.entries[file] = {
|
|
847
|
+
fileMtimeMs: fileStat.mtimeMs,
|
|
848
|
+
fileSize: fileStat.size,
|
|
849
|
+
metaMtimeMs: metaStat.mtimeMs,
|
|
850
|
+
status,
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return results;
|
|
855
|
+
}
|
|
856
|
+
loadLintCache() {
|
|
857
|
+
const cachePath = join(this.config.workspace, ".lint-cache.json");
|
|
858
|
+
if (!existsSync(cachePath))
|
|
859
|
+
return null;
|
|
860
|
+
try {
|
|
861
|
+
const raw = JSON.parse(readFileSync(cachePath, "utf-8"));
|
|
862
|
+
if (raw?.version !== 1)
|
|
863
|
+
return null;
|
|
864
|
+
return raw;
|
|
865
|
+
}
|
|
866
|
+
catch {
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
saveLintCache(cache) {
|
|
871
|
+
writeFileSync(join(this.config.workspace, ".lint-cache.json"), JSON.stringify(cache));
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Fetch a file from a URL and save it to raw/.
|
|
875
|
+
* Supports arXiv smart resolution: arxiv.org/abs/XXXX → arxiv.org/pdf/XXXX.pdf
|
|
876
|
+
* Returns the RawDocument metadata.
|
|
877
|
+
*/
|
|
878
|
+
async rawFetch(url, opts = {}) {
|
|
879
|
+
// ── arXiv smart URL resolution ──
|
|
880
|
+
let resolvedUrl = url;
|
|
881
|
+
let inferredFilename = opts.filename;
|
|
882
|
+
const arxivAbsMatch = url.match(/arxiv\.org\/abs\/(\d+\.\d+)(v\d+)?/);
|
|
883
|
+
const arxivPdfMatch = url.match(/arxiv\.org\/pdf\/(\d+\.\d+)(v\d+)?/);
|
|
884
|
+
if (arxivAbsMatch) {
|
|
885
|
+
const id = arxivAbsMatch[1] + (arxivAbsMatch[2] ?? "");
|
|
886
|
+
resolvedUrl = `https://arxiv.org/pdf/${id}.pdf`;
|
|
887
|
+
if (!inferredFilename)
|
|
888
|
+
inferredFilename = `arxiv-${id.replace(/\./g, "-")}.pdf`;
|
|
889
|
+
}
|
|
890
|
+
else if (arxivPdfMatch && !inferredFilename) {
|
|
891
|
+
const id = arxivPdfMatch[1] + (arxivPdfMatch[2] ?? "");
|
|
892
|
+
inferredFilename = `arxiv-${id.replace(/\./g, "-")}.pdf`;
|
|
893
|
+
}
|
|
894
|
+
// ── Infer filename from URL if not provided ──
|
|
895
|
+
if (!inferredFilename) {
|
|
896
|
+
const urlObj = new URL(resolvedUrl);
|
|
897
|
+
const pathParts = urlObj.pathname.split("/").filter(Boolean);
|
|
898
|
+
const lastPart = pathParts[pathParts.length - 1] ?? "download";
|
|
899
|
+
// Clean up query params and fragments
|
|
900
|
+
inferredFilename = lastPart.split("?")[0].split("#")[0];
|
|
901
|
+
// If no extension, try to add one based on content-type later
|
|
902
|
+
if (!inferredFilename.includes(".")) {
|
|
903
|
+
inferredFilename += ".bin";
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
// ── Immutability guard ──
|
|
907
|
+
const rawPath = safePath(this.config.rawDir, inferredFilename);
|
|
908
|
+
if (existsSync(rawPath)) {
|
|
909
|
+
throw new Error(`Raw file already exists: ${inferredFilename}. Raw files are immutable.`);
|
|
910
|
+
}
|
|
911
|
+
mkdirSync(dirname(rawPath), { recursive: true });
|
|
912
|
+
// ── Download ──
|
|
913
|
+
const response = await fetch(resolvedUrl, {
|
|
914
|
+
headers: {
|
|
915
|
+
"User-Agent": `agent-wiki/${VERSION}`,
|
|
916
|
+
},
|
|
917
|
+
redirect: "follow",
|
|
918
|
+
});
|
|
919
|
+
if (!response.ok) {
|
|
920
|
+
throw new Error(`Download failed: HTTP ${response.status} ${response.statusText} — ${resolvedUrl}`);
|
|
921
|
+
}
|
|
922
|
+
// Update filename extension based on content-type if it was generic
|
|
923
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
924
|
+
if (inferredFilename.endsWith(".bin")) {
|
|
925
|
+
const extMap = {
|
|
926
|
+
// Text
|
|
927
|
+
"text/html": ".html",
|
|
928
|
+
"text/plain": ".txt",
|
|
929
|
+
"text/markdown": ".md",
|
|
930
|
+
"text/csv": ".csv",
|
|
931
|
+
"text/xml": ".xml",
|
|
932
|
+
"text/css": ".css",
|
|
933
|
+
"text/javascript": ".js",
|
|
934
|
+
// Application — documents
|
|
935
|
+
"application/pdf": ".pdf",
|
|
936
|
+
"application/json": ".json",
|
|
937
|
+
"application/xml": ".xml",
|
|
938
|
+
"application/rtf": ".rtf",
|
|
939
|
+
"application/epub+zip": ".epub",
|
|
940
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
|
|
941
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
|
|
942
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
|
|
943
|
+
"application/msword": ".doc",
|
|
944
|
+
"application/vnd.ms-excel": ".xls",
|
|
945
|
+
"application/vnd.ms-powerpoint": ".ppt",
|
|
946
|
+
// Application — archives
|
|
947
|
+
"application/zip": ".zip",
|
|
948
|
+
"application/gzip": ".gz",
|
|
949
|
+
"application/x-tar": ".tar",
|
|
950
|
+
"application/x-7z-compressed": ".7z",
|
|
951
|
+
"application/x-rar-compressed": ".rar",
|
|
952
|
+
// Images
|
|
953
|
+
"image/png": ".png",
|
|
954
|
+
"image/jpeg": ".jpg",
|
|
955
|
+
"image/gif": ".gif",
|
|
956
|
+
"image/svg+xml": ".svg",
|
|
957
|
+
"image/webp": ".webp",
|
|
958
|
+
"image/avif": ".avif",
|
|
959
|
+
"image/bmp": ".bmp",
|
|
960
|
+
"image/tiff": ".tiff",
|
|
961
|
+
// Audio
|
|
962
|
+
"audio/mpeg": ".mp3",
|
|
963
|
+
"audio/wav": ".wav",
|
|
964
|
+
"audio/ogg": ".ogg",
|
|
965
|
+
"audio/flac": ".flac",
|
|
966
|
+
"audio/aac": ".aac",
|
|
967
|
+
// Video
|
|
968
|
+
"video/mp4": ".mp4",
|
|
969
|
+
"video/webm": ".webm",
|
|
970
|
+
"video/x-matroska": ".mkv",
|
|
971
|
+
"video/quicktime": ".mov",
|
|
972
|
+
// Data / other
|
|
973
|
+
"application/wasm": ".wasm",
|
|
974
|
+
"application/x-sqlite3": ".sqlite",
|
|
975
|
+
"application/sql": ".sql",
|
|
976
|
+
"application/x-yaml": ".yaml",
|
|
977
|
+
};
|
|
978
|
+
for (const [mime, ext] of Object.entries(extMap)) {
|
|
979
|
+
if (contentType.includes(mime)) {
|
|
980
|
+
inferredFilename = inferredFilename.replace(/\.bin$/, ext);
|
|
981
|
+
break;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
// Re-check with potentially updated filename
|
|
986
|
+
const finalPath = safePath(this.config.rawDir, inferredFilename);
|
|
987
|
+
if (finalPath !== rawPath && existsSync(finalPath)) {
|
|
988
|
+
throw new Error(`Raw file already exists: ${inferredFilename}. Raw files are immutable.`);
|
|
989
|
+
}
|
|
990
|
+
// Stream to file
|
|
991
|
+
const body = response.body;
|
|
992
|
+
if (!body)
|
|
993
|
+
throw new Error("Empty response body");
|
|
994
|
+
const nodeStream = Readable.fromWeb(body);
|
|
995
|
+
const fileStream = createWriteStream(finalPath);
|
|
996
|
+
await pipeline(nodeStream, fileStream);
|
|
997
|
+
// ── Compute hash and create metadata ──
|
|
998
|
+
const buf = readFileSync(finalPath);
|
|
999
|
+
const sha256 = createHash("sha256").update(buf).digest("hex");
|
|
1000
|
+
const now = new Date().toISOString();
|
|
1001
|
+
const mime = contentType.split(";")[0]?.trim() || guessMime(inferredFilename);
|
|
1002
|
+
const doc = {
|
|
1003
|
+
path: inferredFilename,
|
|
1004
|
+
sourceUrl: url, // original URL, not resolved
|
|
1005
|
+
downloadedAt: now,
|
|
1006
|
+
sha256,
|
|
1007
|
+
size: buf.length,
|
|
1008
|
+
mimeType: mime,
|
|
1009
|
+
description: opts.description,
|
|
1010
|
+
tags: opts.tags,
|
|
1011
|
+
};
|
|
1012
|
+
// Write metadata sidecar
|
|
1013
|
+
writeFileSync(finalPath + ".meta.yaml", yaml.dump(doc, { lineWidth: 100 }));
|
|
1014
|
+
this.log("raw-fetch", inferredFilename, `Downloaded from ${url} (${formatBytes(buf.length)}, ${mime})`);
|
|
1015
|
+
return doc;
|
|
1016
|
+
}
|
|
1017
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1018
|
+
// ATLASSIAN — Confluence & Jira import
|
|
1019
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1020
|
+
/** Import a Confluence page (and optionally all child pages) into raw/. */
|
|
1021
|
+
async confluenceImport(url, opts = {}) {
|
|
1022
|
+
const { confluenceImport: doImport } = await import("./atlassian.js");
|
|
1023
|
+
const result = await doImport(url, this.config.rawDir, this.config.atlassian, opts);
|
|
1024
|
+
this.log("confluence-import", `confluence/${result.tree.file}`, `Imported ${result.pages} page(s) from Confluence`);
|
|
1025
|
+
return result;
|
|
1026
|
+
}
|
|
1027
|
+
/** Import a Jira issue (with comments, attachments, linked issues) into raw/. */
|
|
1028
|
+
async jiraImport(url, opts = {}) {
|
|
1029
|
+
const { jiraImport: doImport } = await import("./atlassian.js");
|
|
1030
|
+
const result = await doImport(url, this.config.rawDir, this.config.atlassian, opts);
|
|
1031
|
+
this.log("jira-import", result.issueKey, `Imported ${result.importedCount} issue(s), ${result.files.length} file(s)`);
|
|
1032
|
+
return result;
|
|
1033
|
+
}
|
|
1034
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1035
|
+
// WIKI LAYER — Mutable compiled knowledge
|
|
1036
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1037
|
+
// ── CRUD ──────────────────────────────────────────────────────
|
|
1038
|
+
/** Read a wiki page. Returns null if not found. */
|
|
1039
|
+
read(pagePath) {
|
|
1040
|
+
const fullPath = safePath(this.config.wikiDir, pagePath);
|
|
1041
|
+
if (!existsSync(fullPath)) {
|
|
1042
|
+
const withMd = fullPath.endsWith(".md") ? fullPath : fullPath + ".md";
|
|
1043
|
+
// withMd is derived from already-validated fullPath, so no re-check needed
|
|
1044
|
+
if (!existsSync(withMd))
|
|
1045
|
+
return null;
|
|
1046
|
+
return this.parsePage(relative(this.config.wikiDir, withMd), readFileSync(withMd, "utf-8"));
|
|
1047
|
+
}
|
|
1048
|
+
return this.parsePage(pagePath, readFileSync(fullPath, "utf-8"));
|
|
1049
|
+
}
|
|
1050
|
+
/** Write (create or update) a wiki page. Content must include frontmatter.
|
|
1051
|
+
* Automatically injects/updates created and updated timestamps. */
|
|
1052
|
+
write(pagePath, content, source) {
|
|
1053
|
+
// Guard: nested */index.md paths are reserved for auto-generated directory indexes
|
|
1054
|
+
if (isSystemPage(pagePath) && !SYSTEM_PAGES.has(pagePath)) {
|
|
1055
|
+
throw new Error(`Cannot write to reserved path: ${pagePath}. Nested */index.md is auto-generated by wiki_rebuild.`);
|
|
1056
|
+
}
|
|
1057
|
+
const fullPath = safePath(this.config.wikiDir, pagePath);
|
|
1058
|
+
const dir = dirname(fullPath);
|
|
1059
|
+
mkdirSync(dir, { recursive: true });
|
|
1060
|
+
const now = new Date().toISOString();
|
|
1061
|
+
// Parse incoming content to inject timestamps
|
|
1062
|
+
const parsed = matter(content);
|
|
1063
|
+
if (!parsed.data.created) {
|
|
1064
|
+
// Check if page already exists — preserve original created time
|
|
1065
|
+
if (existsSync(fullPath)) {
|
|
1066
|
+
const existing = matter(readFileSync(fullPath, "utf-8"));
|
|
1067
|
+
const ec = existing.data.created;
|
|
1068
|
+
parsed.data.created = ec instanceof Date ? ec.toISOString() : ec ?? now;
|
|
1069
|
+
}
|
|
1070
|
+
else {
|
|
1071
|
+
parsed.data.created = now;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
parsed.data.updated = now;
|
|
1075
|
+
// Reconstruct content with updated frontmatter
|
|
1076
|
+
const finalContent = matter.stringify(parsed.content, parsed.data);
|
|
1077
|
+
writeFileSync(fullPath, finalContent.trimEnd() + "\n");
|
|
1078
|
+
this.searchEngine.invalidate();
|
|
1079
|
+
// Incrementally update the title index cache (avoid full rebuild on next autoLink)
|
|
1080
|
+
if (this.titleIndexCache !== null) {
|
|
1081
|
+
const slug = basename(pagePath, ".md");
|
|
1082
|
+
const title = (parsed.data.title ?? slug.replace(/-/g, " ")).trim();
|
|
1083
|
+
const idx = this.titleIndexCache.findIndex(c => c.slug === slug);
|
|
1084
|
+
if (idx !== -1)
|
|
1085
|
+
this.titleIndexCache.splice(idx, 1);
|
|
1086
|
+
if (title.length >= 4 && !isSystemPage(pagePath)) {
|
|
1087
|
+
// Insert at the correct sorted position (longest-first)
|
|
1088
|
+
let insertAt = this.titleIndexCache.findIndex(c => c.title.length <= title.length);
|
|
1089
|
+
if (insertAt === -1)
|
|
1090
|
+
insertAt = this.titleIndexCache.length;
|
|
1091
|
+
this.titleIndexCache.splice(insertAt, 0, { title, slug });
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
this.log("write", pagePath, `Wrote ${pagePath}${source ? ` (${source})` : ""}`);
|
|
1095
|
+
return finalContent.trimEnd() + "\n";
|
|
1096
|
+
}
|
|
1097
|
+
/** Resolve page path to the correct topic subdirectory.
|
|
1098
|
+
* If the path already has a subdirectory, returns as-is.
|
|
1099
|
+
* Otherwise, routes based on: (1) explicit `topic` frontmatter field,
|
|
1100
|
+
* (2) tag/title matching against existing nested directories (deepest match wins). */
|
|
1101
|
+
resolvePagePath(pagePath, content) {
|
|
1102
|
+
// Already in a subdirectory? Use as-is.
|
|
1103
|
+
if (pagePath.includes("/"))
|
|
1104
|
+
return pagePath;
|
|
1105
|
+
// No existing dirs → nothing to route to
|
|
1106
|
+
const allDirs = this.listAllDirPaths();
|
|
1107
|
+
if (allDirs.length === 0)
|
|
1108
|
+
return pagePath;
|
|
1109
|
+
const parsed = matter(content);
|
|
1110
|
+
// 1. Explicit `topic` frontmatter field
|
|
1111
|
+
const explicitTopic = parsed.data.topic;
|
|
1112
|
+
if (explicitTopic && typeof explicitTopic === "string") {
|
|
1113
|
+
const normalized = explicitTopic.toLowerCase().replace(/\s+/g, "-");
|
|
1114
|
+
// Exact path match first (e.g. topic: "lang/js")
|
|
1115
|
+
if (allDirs.includes(normalized)) {
|
|
1116
|
+
return `${normalized}/${pagePath}`;
|
|
1117
|
+
}
|
|
1118
|
+
// Match against last segment of each dir, prefer deepest
|
|
1119
|
+
const match = allDirs
|
|
1120
|
+
.filter((d) => d.split("/").pop().toLowerCase() === normalized)
|
|
1121
|
+
.sort((a, b) => b.split("/").length - a.split("/").length)[0];
|
|
1122
|
+
if (match) {
|
|
1123
|
+
return `${match}/${pagePath}`;
|
|
1124
|
+
}
|
|
1125
|
+
// Fallback: create new directory at root
|
|
1126
|
+
return `${normalized}/${pagePath}`;
|
|
1127
|
+
}
|
|
1128
|
+
// 2. Match tags/title against directory names (deepest match wins)
|
|
1129
|
+
const classification = this.classify(content);
|
|
1130
|
+
const title = (parsed.data.title ?? "").toLowerCase();
|
|
1131
|
+
const signals = [
|
|
1132
|
+
...classification.tags.map((t) => t.toLowerCase()),
|
|
1133
|
+
...title.split(/[\s\-_]+/).filter(Boolean),
|
|
1134
|
+
];
|
|
1135
|
+
// Sort dirs by depth (deepest first) so we prefer more specific matches
|
|
1136
|
+
const sortedDirs = [...allDirs].sort((a, b) => b.split("/").length - a.split("/").length);
|
|
1137
|
+
for (const dirPath of sortedDirs) {
|
|
1138
|
+
const dirName = dirPath.split("/").pop().toLowerCase();
|
|
1139
|
+
if (signals.some((s) => s === dirName || s.includes(dirName) || dirName.includes(s))) {
|
|
1140
|
+
return `${dirPath}/${pagePath}`;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return pagePath;
|
|
1144
|
+
}
|
|
1145
|
+
/** List existing topic subdirectories under wiki/ (first-level only). */
|
|
1146
|
+
listTopicDirs() {
|
|
1147
|
+
const dir = this.config.wikiDir;
|
|
1148
|
+
if (!existsSync(dir))
|
|
1149
|
+
return [];
|
|
1150
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
1151
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith("."))
|
|
1152
|
+
.map((e) => e.name)
|
|
1153
|
+
.sort();
|
|
1154
|
+
}
|
|
1155
|
+
/** List all directory paths recursively under wiki/ (relative, e.g. "lang", "lang/js"). */
|
|
1156
|
+
listAllDirPaths() {
|
|
1157
|
+
const result = [];
|
|
1158
|
+
const walk = (dir, prefix) => {
|
|
1159
|
+
if (!existsSync(dir))
|
|
1160
|
+
return;
|
|
1161
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
1162
|
+
if (entry.isDirectory() && !entry.name.startsWith(".")) {
|
|
1163
|
+
const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
1164
|
+
result.push(relPath);
|
|
1165
|
+
walk(join(dir, entry.name), relPath);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
walk(this.config.wikiDir, "");
|
|
1170
|
+
return result.sort();
|
|
1171
|
+
}
|
|
1172
|
+
/** Delete a wiki page. Returns true if it existed. */
|
|
1173
|
+
delete(pagePath) {
|
|
1174
|
+
// Guard: never delete system pages
|
|
1175
|
+
if (isSystemPage(pagePath)) {
|
|
1176
|
+
throw new Error(`Cannot delete system page: ${pagePath}`);
|
|
1177
|
+
}
|
|
1178
|
+
const fullPath = safePath(this.config.wikiDir, pagePath);
|
|
1179
|
+
if (!existsSync(fullPath))
|
|
1180
|
+
return false;
|
|
1181
|
+
unlinkSync(fullPath);
|
|
1182
|
+
this.searchEngine.invalidate();
|
|
1183
|
+
// Remove from title index cache
|
|
1184
|
+
if (this.titleIndexCache !== null) {
|
|
1185
|
+
const slug = basename(pagePath, ".md");
|
|
1186
|
+
const idx = this.titleIndexCache.findIndex(c => c.slug === slug);
|
|
1187
|
+
if (idx !== -1)
|
|
1188
|
+
this.titleIndexCache.splice(idx, 1);
|
|
1189
|
+
}
|
|
1190
|
+
this.log("delete", pagePath, `Deleted ${pagePath}`);
|
|
1191
|
+
return true;
|
|
1192
|
+
}
|
|
1193
|
+
/** List all wiki pages, optionally filtered by type or tag. */
|
|
1194
|
+
list(filterType, filterTag) {
|
|
1195
|
+
const pages = this.listAllPages();
|
|
1196
|
+
if (!filterType && !filterTag)
|
|
1197
|
+
return pages;
|
|
1198
|
+
return pages.filter((p) => {
|
|
1199
|
+
const page = this.read(p);
|
|
1200
|
+
if (!page)
|
|
1201
|
+
return false;
|
|
1202
|
+
if (filterType && page.type !== filterType)
|
|
1203
|
+
return false;
|
|
1204
|
+
if (filterTag && !page.tags.includes(filterTag))
|
|
1205
|
+
return false;
|
|
1206
|
+
return true;
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
// ── Search ────────────────────────────────────────────────────
|
|
1210
|
+
/** BM25 search across all wiki pages (synchronous, pure BM25).
|
|
1211
|
+
* Index is built lazily on first search and cached until invalidated by write/delete. */
|
|
1212
|
+
search(query, limit = 10) {
|
|
1213
|
+
return this.searchEngine.search(query, limit);
|
|
1214
|
+
}
|
|
1215
|
+
/** Hybrid BM25+vector search (async).
|
|
1216
|
+
* When `config.search.hybrid` is true, re-ranks BM25 candidates using vector
|
|
1217
|
+
* cosine similarity. Falls back to pure BM25 if embeddings are unavailable. */
|
|
1218
|
+
async searchHybrid(query, limit = 10) {
|
|
1219
|
+
return this.searchEngine.searchHybrid(query, limit);
|
|
1220
|
+
}
|
|
1221
|
+
// ── Vector index persistence (hybrid search) ─────────────────
|
|
1222
|
+
/** Path where the vector index is persisted. */
|
|
1223
|
+
get vectorIndexPath() {
|
|
1224
|
+
return join(this.config.wikiDir, ".search-vectors.json");
|
|
1225
|
+
}
|
|
1226
|
+
/** Load the persisted vector index from disk into the search engine.
|
|
1227
|
+
* No-op if the file doesn't exist. */
|
|
1228
|
+
loadVectorIndex() {
|
|
1229
|
+
const p = this.vectorIndexPath;
|
|
1230
|
+
if (!existsSync(p))
|
|
1231
|
+
return;
|
|
1232
|
+
try {
|
|
1233
|
+
const raw = JSON.parse(readFileSync(p, "utf-8"));
|
|
1234
|
+
if (raw.model !== this.config.search.model)
|
|
1235
|
+
return; // stale model — discard
|
|
1236
|
+
const map = new Map();
|
|
1237
|
+
for (const [path, vec] of Object.entries(raw.vectors ?? {})) {
|
|
1238
|
+
if (Array.isArray(vec))
|
|
1239
|
+
map.set(path, vec);
|
|
1240
|
+
}
|
|
1241
|
+
this.searchEngine.setVectors(map);
|
|
1242
|
+
}
|
|
1243
|
+
catch {
|
|
1244
|
+
// Corrupted index — ignore, will be rebuilt on next write/rebuild
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
/** Persist the current in-memory vector index to disk. */
|
|
1248
|
+
saveVectorIndex() {
|
|
1249
|
+
const vectors = {};
|
|
1250
|
+
for (const [path, vec] of this.searchEngine.getVectors()) {
|
|
1251
|
+
vectors[path] = vec;
|
|
1252
|
+
}
|
|
1253
|
+
const p = this.vectorIndexPath;
|
|
1254
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
1255
|
+
writeFileSync(p, JSON.stringify({ model: this.config.search.model, vectors }, null, 0));
|
|
1256
|
+
}
|
|
1257
|
+
/** Compute and store the embedding for a single wiki page.
|
|
1258
|
+
* Intended to be called by the server after wiki_write when hybrid mode is on. */
|
|
1259
|
+
async updatePageVector(pagePath) {
|
|
1260
|
+
const page = this.read(pagePath);
|
|
1261
|
+
if (!page)
|
|
1262
|
+
return;
|
|
1263
|
+
const text = `${page.title} ${page.tags.join(" ")} ${page.content}`.slice(0, 2000);
|
|
1264
|
+
const embedding = await this.searchEngine.embedText(text);
|
|
1265
|
+
this.searchEngine.updateVector(pagePath, embedding);
|
|
1266
|
+
this.saveVectorIndex();
|
|
1267
|
+
}
|
|
1268
|
+
/** Remove the stored embedding for a deleted page and persist the change. */
|
|
1269
|
+
removePageVector(pagePath) {
|
|
1270
|
+
this.searchEngine.removeVector(pagePath);
|
|
1271
|
+
this.saveVectorIndex();
|
|
1272
|
+
}
|
|
1273
|
+
/** Rebuild the full vector index for all pages (used by wiki_rebuild when hybrid is on).
|
|
1274
|
+
* Returns counts of pages processed and pages that failed (e.g. embedding errors). */
|
|
1275
|
+
async rebuildVectorIndex() {
|
|
1276
|
+
const pages = this.listAllPages();
|
|
1277
|
+
let pagesProcessed = 0;
|
|
1278
|
+
let errors = 0;
|
|
1279
|
+
for (const pagePath of pages) {
|
|
1280
|
+
const page = this.read(pagePath);
|
|
1281
|
+
if (!page)
|
|
1282
|
+
continue;
|
|
1283
|
+
const text = `${page.title} ${page.tags.join(" ")} ${page.content}`.slice(0, 2000);
|
|
1284
|
+
try {
|
|
1285
|
+
const embedding = await this.searchEngine.embedText(text);
|
|
1286
|
+
this.searchEngine.updateVector(pagePath, embedding);
|
|
1287
|
+
pagesProcessed++;
|
|
1288
|
+
}
|
|
1289
|
+
catch {
|
|
1290
|
+
errors++;
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
this.saveVectorIndex();
|
|
1294
|
+
return { pagesProcessed, errors };
|
|
1295
|
+
}
|
|
1296
|
+
/** Return the number of pages currently in the vector index. */
|
|
1297
|
+
getVectorCount() {
|
|
1298
|
+
return this.searchEngine.getVectorCount();
|
|
1299
|
+
}
|
|
1300
|
+
// ── Lint — Self-checking & error detection ────────────────────
|
|
1301
|
+
/** Run comprehensive health checks. Pure rules, no LLM.
|
|
1302
|
+
* Detects: contradictions, orphans, broken links, missing sources,
|
|
1303
|
+
* stale content, structural issues, integrity problems.
|
|
1304
|
+
*
|
|
1305
|
+
* @param applyFixes When true, automatically fix `autoFixable` issues:
|
|
1306
|
+
* - Missing frontmatter → auto-classify + inject title/type/tags
|
|
1307
|
+
* Returns `fixed` count of pages that were automatically repaired. */
|
|
1308
|
+
lint(applyFixes = false) {
|
|
1309
|
+
const pages = this.listAllPages();
|
|
1310
|
+
const report = {
|
|
1311
|
+
pagesChecked: pages.length,
|
|
1312
|
+
rawChecked: 0,
|
|
1313
|
+
issues: [],
|
|
1314
|
+
contradictions: [],
|
|
1315
|
+
};
|
|
1316
|
+
let fixed = 0;
|
|
1317
|
+
const fixedPages = [];
|
|
1318
|
+
// Build a map of all pages for cross-referencing
|
|
1319
|
+
const pageMap = new Map();
|
|
1320
|
+
for (const pagePath of pages) {
|
|
1321
|
+
const page = this.read(pagePath);
|
|
1322
|
+
if (page)
|
|
1323
|
+
pageMap.set(pagePath, page);
|
|
1324
|
+
}
|
|
1325
|
+
// ── O(1) lookup indexes ──
|
|
1326
|
+
const pageSet = new Set(pages);
|
|
1327
|
+
const basenameToPages = new Map();
|
|
1328
|
+
for (const p of pages) {
|
|
1329
|
+
const bn = basename(p, extname(p));
|
|
1330
|
+
const existing = basenameToPages.get(bn);
|
|
1331
|
+
if (existing)
|
|
1332
|
+
existing.push(p);
|
|
1333
|
+
else
|
|
1334
|
+
basenameToPages.set(bn, [p]);
|
|
1335
|
+
}
|
|
1336
|
+
// Reverse link index: slug → set of pages that link TO this slug
|
|
1337
|
+
const incomingLinks = new Map();
|
|
1338
|
+
for (const [sourcePath, page] of pageMap) {
|
|
1339
|
+
for (const link of page.links) {
|
|
1340
|
+
let targets = incomingLinks.get(link);
|
|
1341
|
+
if (!targets) {
|
|
1342
|
+
targets = new Set();
|
|
1343
|
+
incomingLinks.set(link, targets);
|
|
1344
|
+
}
|
|
1345
|
+
targets.add(sourcePath);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
for (const [pagePath, page] of pageMap) {
|
|
1349
|
+
// ── Missing frontmatter ──
|
|
1350
|
+
if (Object.keys(page.frontmatter).length === 0) {
|
|
1351
|
+
if (applyFixes) {
|
|
1352
|
+
// Auto-fix: derive title from filename, auto-classify type + tags
|
|
1353
|
+
const titleFromFilename = basename(pagePath, ".md")
|
|
1354
|
+
.replace(/-/g, " ")
|
|
1355
|
+
.replace(/\b\w/g, c => c.toUpperCase());
|
|
1356
|
+
const rawContent = `---\ntitle: ${titleFromFilename}\n---\n${page.content}`;
|
|
1357
|
+
const enriched = this.autoClassifyContent(rawContent);
|
|
1358
|
+
this.write(pagePath, enriched);
|
|
1359
|
+
fixed++;
|
|
1360
|
+
fixedPages.push(pagePath);
|
|
1361
|
+
}
|
|
1362
|
+
else {
|
|
1363
|
+
report.issues.push({
|
|
1364
|
+
severity: "warning",
|
|
1365
|
+
page: pagePath,
|
|
1366
|
+
message: "Missing YAML frontmatter",
|
|
1367
|
+
suggestion: "Add frontmatter with title, type, tags, and sources",
|
|
1368
|
+
autoFixable: true,
|
|
1369
|
+
category: "structure",
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
// ── Missing title ──
|
|
1374
|
+
if (!page.title || page.title === basename(pagePath, extname(pagePath))) {
|
|
1375
|
+
report.issues.push({
|
|
1376
|
+
severity: "warning",
|
|
1377
|
+
page: pagePath,
|
|
1378
|
+
message: "Missing or auto-generated title",
|
|
1379
|
+
suggestion: "Add a meaningful title in frontmatter",
|
|
1380
|
+
autoFixable: false,
|
|
1381
|
+
category: "structure",
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
// ── Orphan pages ──
|
|
1385
|
+
if (this.config.lint.checkOrphans && !isSystemPage(pagePath)) {
|
|
1386
|
+
const slug = basename(pagePath, extname(pagePath));
|
|
1387
|
+
// Full relative slug: "topic/page-name" (without .md)
|
|
1388
|
+
const fullSlug = pagePath.endsWith(".md") ? pagePath.slice(0, -3) : pagePath;
|
|
1389
|
+
const slugIncoming = incomingLinks.get(slug);
|
|
1390
|
+
const fullSlugIncoming = incomingLinks.get(fullSlug);
|
|
1391
|
+
// Check that at least one *other* page links here (exclude self-links)
|
|
1392
|
+
const hasIncoming = (slugIncoming !== undefined && (slugIncoming.size > 1 || !slugIncoming.has(pagePath))) ||
|
|
1393
|
+
(fullSlugIncoming !== undefined && (fullSlugIncoming.size > 1 || !fullSlugIncoming.has(pagePath)));
|
|
1394
|
+
if (!hasIncoming) {
|
|
1395
|
+
report.issues.push({
|
|
1396
|
+
severity: "warning",
|
|
1397
|
+
page: pagePath,
|
|
1398
|
+
message: "Orphan page — no other pages link here",
|
|
1399
|
+
suggestion: `Add [[${fullSlug}]] to related pages or index.md`,
|
|
1400
|
+
autoFixable: true,
|
|
1401
|
+
category: "orphan",
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
// ── Broken links ──
|
|
1406
|
+
for (const link of page.links) {
|
|
1407
|
+
const linkPath = link.endsWith(".md") ? link : link + ".md";
|
|
1408
|
+
// O(1) direct-path check
|
|
1409
|
+
if (pageSet.has(linkPath) || pageSet.has(link))
|
|
1410
|
+
continue;
|
|
1411
|
+
// O(1) basename check
|
|
1412
|
+
const bareLink = link.replace(/\.md$/, "");
|
|
1413
|
+
if (basenameToPages.has(link) || basenameToPages.has(bareLink))
|
|
1414
|
+
continue;
|
|
1415
|
+
// BM25 "did you mean?" — search for similar page names
|
|
1416
|
+
const searchQuery = bareLink.replace(/-/g, " ");
|
|
1417
|
+
const candidates = this.search(searchQuery, 3).map(r => r.path);
|
|
1418
|
+
const suggestion = candidates.length > 0
|
|
1419
|
+
? `Did you mean: ${candidates.join(", ")}? Or create ${link}.md`
|
|
1420
|
+
: `Create ${link}.md or fix the link`;
|
|
1421
|
+
report.issues.push({
|
|
1422
|
+
severity: "error",
|
|
1423
|
+
page: pagePath,
|
|
1424
|
+
message: `Broken link: [[${link}]]`,
|
|
1425
|
+
suggestion,
|
|
1426
|
+
autoFixable: false,
|
|
1427
|
+
category: "broken-link",
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
// ── Missing sources (non-system pages) ──
|
|
1431
|
+
if (this.config.lint.checkMissingSources && !isSystemPage(pagePath)) {
|
|
1432
|
+
if (page.sources.length === 0 && page.type && page.type !== "index" && page.type !== "log" && page.type !== "timeline") {
|
|
1433
|
+
report.issues.push({
|
|
1434
|
+
severity: "info",
|
|
1435
|
+
page: pagePath,
|
|
1436
|
+
message: "No sources listed — claims are not traceable to raw documents",
|
|
1437
|
+
suggestion: "Add sources to frontmatter linking to raw/ files or URLs",
|
|
1438
|
+
autoFixable: false,
|
|
1439
|
+
category: "missing-source",
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
// ── Synthesis page integrity ──
|
|
1444
|
+
if (page.type === "synthesis" && page.derivedFrom) {
|
|
1445
|
+
for (const src of page.derivedFrom) {
|
|
1446
|
+
const srcPath = src.endsWith(".md") ? src : src + ".md";
|
|
1447
|
+
const bareSrc = src.replace(/\.md$/, "");
|
|
1448
|
+
const found = pageSet.has(srcPath) ||
|
|
1449
|
+
pageSet.has(src) ||
|
|
1450
|
+
basenameToPages.has(src) ||
|
|
1451
|
+
basenameToPages.has(bareSrc);
|
|
1452
|
+
if (!found) {
|
|
1453
|
+
report.issues.push({
|
|
1454
|
+
severity: "error",
|
|
1455
|
+
page: pagePath,
|
|
1456
|
+
message: `Synthesis source missing: ${src}`,
|
|
1457
|
+
suggestion: `The page this synthesis derives from no longer exists. Review and update.`,
|
|
1458
|
+
autoFixable: false,
|
|
1459
|
+
category: "integrity",
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
// ── Stale content ──
|
|
1465
|
+
if (this.config.lint.checkStaleDays > 0) {
|
|
1466
|
+
try {
|
|
1467
|
+
const fullPath = join(this.config.wikiDir, pagePath);
|
|
1468
|
+
const stat = statSync(fullPath);
|
|
1469
|
+
const ageDays = Math.floor((Date.now() - stat.mtimeMs) / (1000 * 60 * 60 * 24));
|
|
1470
|
+
if (ageDays > this.config.lint.checkStaleDays) {
|
|
1471
|
+
report.issues.push({
|
|
1472
|
+
severity: "info",
|
|
1473
|
+
page: pagePath,
|
|
1474
|
+
message: `Stale content — last modified ${ageDays} days ago`,
|
|
1475
|
+
suggestion: "Review and update if needed",
|
|
1476
|
+
autoFixable: false,
|
|
1477
|
+
category: "stale",
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
catch {
|
|
1482
|
+
// stat failed, skip
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
// ── Cross-page contradiction detection ──
|
|
1487
|
+
if (this.config.lint.checkContradictions) {
|
|
1488
|
+
const contradictions = this.detectContradictions(pageMap);
|
|
1489
|
+
report.contradictions = contradictions;
|
|
1490
|
+
for (const c of contradictions) {
|
|
1491
|
+
report.issues.push({
|
|
1492
|
+
severity: c.severity,
|
|
1493
|
+
page: c.pageA,
|
|
1494
|
+
message: `Contradiction with [[${basename(c.pageB, ".md")}]]: ${c.claim}`,
|
|
1495
|
+
suggestion: `"${c.excerptA}" vs "${c.excerptB}" — review and resolve`,
|
|
1496
|
+
autoFixable: false,
|
|
1497
|
+
category: "contradiction",
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
// ── Raw file integrity (incremental — cached by mtime+size) ──
|
|
1502
|
+
if (this.config.lint.checkIntegrity) {
|
|
1503
|
+
const lintCache = this.loadLintCache() ?? { version: 1, entries: {} };
|
|
1504
|
+
const rawResults = this.rawVerify(lintCache);
|
|
1505
|
+
report.rawChecked = rawResults.length;
|
|
1506
|
+
for (const r of rawResults) {
|
|
1507
|
+
if (r.status === "corrupted") {
|
|
1508
|
+
report.issues.push({
|
|
1509
|
+
severity: "error",
|
|
1510
|
+
page: `raw/${r.path}`,
|
|
1511
|
+
message: "Raw file corrupted — SHA-256 mismatch",
|
|
1512
|
+
suggestion: "Re-download the original source",
|
|
1513
|
+
autoFixable: false,
|
|
1514
|
+
category: "integrity",
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
else if (r.status === "missing-meta") {
|
|
1518
|
+
report.issues.push({
|
|
1519
|
+
severity: "warning",
|
|
1520
|
+
page: `raw/${r.path}`,
|
|
1521
|
+
message: "Raw file has no metadata sidecar (.meta.yaml)",
|
|
1522
|
+
suggestion: "Use raw_add to properly register this file",
|
|
1523
|
+
autoFixable: true,
|
|
1524
|
+
category: "integrity",
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
this.saveLintCache(lintCache);
|
|
1529
|
+
}
|
|
1530
|
+
this.log("lint", "—", `Checked ${report.pagesChecked} pages + ${report.rawChecked} raw files, found ${report.issues.length} issues (${report.contradictions.length} contradictions)${fixed > 0 ? `, auto-fixed ${fixed} pages` : ""}`);
|
|
1531
|
+
return { ...report, fixed, fixedPages };
|
|
1532
|
+
}
|
|
1533
|
+
// ── Contradiction detection ───────────────────────────────────
|
|
1534
|
+
/** Normalize a numeric value + unit to a canonical (value, unit) pair.
|
|
1535
|
+
* Collapses scale suffixes (million/billion/k) and ms→s so that
|
|
1536
|
+
* "1000 ms" and "1 s", or "5 billion" and "5000 million", are not
|
|
1537
|
+
* falsely reported as contradictions. */
|
|
1538
|
+
static normalizeUnit(rawValue, rawUnit) {
|
|
1539
|
+
const v = parseFloat(rawValue);
|
|
1540
|
+
const u = rawUnit.toLowerCase().trim();
|
|
1541
|
+
if (u === "ms")
|
|
1542
|
+
return { value: v / 1000, unit: "s" };
|
|
1543
|
+
if (u === "million")
|
|
1544
|
+
return { value: v * 1e6, unit: "count" };
|
|
1545
|
+
if (u === "billion")
|
|
1546
|
+
return { value: v * 1e9, unit: "count" };
|
|
1547
|
+
if (u === "k")
|
|
1548
|
+
return { value: v * 1e3, unit: "count" };
|
|
1549
|
+
return { value: v, unit: u };
|
|
1550
|
+
}
|
|
1551
|
+
/** Normalize unit abbreviations in a context string so that keys
|
|
1552
|
+
* derived from "1000 ms latency" and "1 s latency" are identical. */
|
|
1553
|
+
static normalizeUnitText(text) {
|
|
1554
|
+
return text
|
|
1555
|
+
.replace(/\bms\b/gi, "s")
|
|
1556
|
+
.replace(/\bmillion\b/gi, "count")
|
|
1557
|
+
.replace(/\bbillion\b/gi, "count")
|
|
1558
|
+
.replace(/\bk\b/g, "count");
|
|
1559
|
+
}
|
|
1560
|
+
/** Detect contradictions between pages.
|
|
1561
|
+
* Looks for numeric claims, date claims, and factual statements
|
|
1562
|
+
* that conflict across pages about the same entity/topic.
|
|
1563
|
+
*
|
|
1564
|
+
* Improvements over baseline:
|
|
1565
|
+
* - Bug fix: uses match.index instead of indexOf (correct context for repeated values)
|
|
1566
|
+
* - Unit normalization: "1000 ms" and "1 s" are not reported as contradictions
|
|
1567
|
+
* - Topic isolation: only compares pages that share a tag or link to each other
|
|
1568
|
+
* - Extended date patterns: ISO dates and "Month YYYY" in addition to bare years
|
|
1569
|
+
*/
|
|
1570
|
+
detectContradictions(pageMap) {
|
|
1571
|
+
const contradictions = [];
|
|
1572
|
+
// Extract claims from pages — look for patterns like "X is Y", dates, numbers
|
|
1573
|
+
const claims = new Map();
|
|
1574
|
+
for (const [pagePath, page] of pageMap) {
|
|
1575
|
+
if (isSystemPage(pagePath))
|
|
1576
|
+
continue;
|
|
1577
|
+
// Extract date claims: "published in 2021", "released March 2021", "born 2021-03-15"
|
|
1578
|
+
const datePatterns = page.content.matchAll(/(?:published|released|founded|created|introduced|launched|announced|born|died)\s+(?:in\s+|on\s+)?(?:(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+)?(\d{4}(?:-\d{2}-\d{2})?)/gi);
|
|
1579
|
+
for (const m of datePatterns) {
|
|
1580
|
+
const year = m[1].slice(0, 4); // normalize ISO dates to year only for key
|
|
1581
|
+
const key = m[0].replace(/\d{4}(?:-\d{2}-\d{2})?/, "YEAR").toLowerCase().trim();
|
|
1582
|
+
const entry = { page: pagePath, excerpt: m[0], value: parseFloat(year), rawValue: m[1] };
|
|
1583
|
+
if (!claims.has(key))
|
|
1584
|
+
claims.set(key, []);
|
|
1585
|
+
claims.get(key).push(entry);
|
|
1586
|
+
}
|
|
1587
|
+
// Extract numeric claims: "achieved XX% mAP", "XX FPS", "XX parameters"
|
|
1588
|
+
const numericPatterns = page.content.matchAll(/(\d+\.?\d*)\s*(%|fps|ms|s\b|map|ap|parameters|params|layers|million|billion|k\b)/gi);
|
|
1589
|
+
for (const m of numericPatterns) {
|
|
1590
|
+
// Bug fix: use match.index (correct position for repeated patterns)
|
|
1591
|
+
const idx = m.index ?? page.content.indexOf(m[0]);
|
|
1592
|
+
const ctxStart = Math.max(0, idx - 30);
|
|
1593
|
+
const ctxEnd = Math.min(page.content.length, idx + m[0].length + 30);
|
|
1594
|
+
const context = page.content.slice(ctxStart, ctxEnd).replace(/\n/g, " ").trim();
|
|
1595
|
+
// Key = unit-normalized context with numbers replaced by "N"
|
|
1596
|
+
const key = Wiki.normalizeUnitText(context)
|
|
1597
|
+
.replace(/\d+\.?\d*/g, "N")
|
|
1598
|
+
.toLowerCase()
|
|
1599
|
+
.slice(0, 60);
|
|
1600
|
+
// Value = unit-normalized number for accurate comparison
|
|
1601
|
+
const { value: normValue } = Wiki.normalizeUnit(m[1], m[2]);
|
|
1602
|
+
const entry = { page: pagePath, excerpt: context, value: normValue, rawValue: m[1] };
|
|
1603
|
+
if (!claims.has(key))
|
|
1604
|
+
claims.set(key, []);
|
|
1605
|
+
claims.get(key).push(entry);
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
// Compare claims from different pages
|
|
1609
|
+
for (const [claimKey, entries] of claims) {
|
|
1610
|
+
if (entries.length < 2)
|
|
1611
|
+
continue;
|
|
1612
|
+
// Group by page — keep only the first occurrence per page
|
|
1613
|
+
const byPage = new Map();
|
|
1614
|
+
for (const e of entries) {
|
|
1615
|
+
if (!byPage.has(e.page))
|
|
1616
|
+
byPage.set(e.page, e);
|
|
1617
|
+
}
|
|
1618
|
+
const uniquePages = [...byPage.values()];
|
|
1619
|
+
if (uniquePages.length < 2)
|
|
1620
|
+
continue;
|
|
1621
|
+
// Check if values differ across pairs
|
|
1622
|
+
for (let i = 0; i < uniquePages.length; i++) {
|
|
1623
|
+
for (let j = i + 1; j < uniquePages.length; j++) {
|
|
1624
|
+
const a = uniquePages[i];
|
|
1625
|
+
const b = uniquePages[j];
|
|
1626
|
+
if (a.value === b.value)
|
|
1627
|
+
continue;
|
|
1628
|
+
// Topic isolation: only report contradictions between related pages
|
|
1629
|
+
// (pages that share a tag or have a direct [[link]] between them).
|
|
1630
|
+
// Unrelated pages sharing a number are almost never a real contradiction.
|
|
1631
|
+
const pA = pageMap.get(a.page);
|
|
1632
|
+
const pB = pageMap.get(b.page);
|
|
1633
|
+
const sharedTag = pA.tags.some(t => pB.tags.includes(t));
|
|
1634
|
+
const slugB = basename(b.page, ".md");
|
|
1635
|
+
const slugA = basename(a.page, ".md");
|
|
1636
|
+
const linkedAtoB = pA.links.includes(slugB) || pA.links.includes(b.page.replace(/\.md$/, ""));
|
|
1637
|
+
const linkedBtoA = pB.links.includes(slugA) || pB.links.includes(a.page.replace(/\.md$/, ""));
|
|
1638
|
+
if (!sharedTag && !linkedAtoB && !linkedBtoA)
|
|
1639
|
+
continue;
|
|
1640
|
+
contradictions.push({
|
|
1641
|
+
claim: claimKey.replace(/\bn\b/gi, "?"),
|
|
1642
|
+
pageA: a.page,
|
|
1643
|
+
excerptA: a.excerpt,
|
|
1644
|
+
pageB: b.page,
|
|
1645
|
+
excerptB: b.excerpt,
|
|
1646
|
+
severity: Math.abs(a.value - b.value) > 10 ? "error" : "warning",
|
|
1647
|
+
});
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
return contradictions;
|
|
1652
|
+
}
|
|
1653
|
+
// ── Synthesis — Knowledge distillation ────────────────────────
|
|
1654
|
+
/** Get context for synthesis: reads multiple pages and returns
|
|
1655
|
+
* their content for the agent to distill into a new page. */
|
|
1656
|
+
synthesizeContext(pagePaths) {
|
|
1657
|
+
const pages = [];
|
|
1658
|
+
const allTags = new Set();
|
|
1659
|
+
const allLinks = new Set();
|
|
1660
|
+
for (const p of pagePaths) {
|
|
1661
|
+
const page = this.read(p) ?? this.read(p + ".md");
|
|
1662
|
+
if (page) {
|
|
1663
|
+
pages.push({ path: page.path, title: page.title, content: page.content });
|
|
1664
|
+
page.tags.forEach((t) => allTags.add(t));
|
|
1665
|
+
page.links.forEach((l) => allLinks.add(l));
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
// Generate suggestions for the synthesis
|
|
1669
|
+
const suggestions = [];
|
|
1670
|
+
if (pages.length >= 2) {
|
|
1671
|
+
suggestions.push(`Combine insights from ${pages.map((p) => p.title).join(", ")}`);
|
|
1672
|
+
suggestions.push("Look for common themes, contradictions, and gaps");
|
|
1673
|
+
suggestions.push("Create cross-references using [[page-name]] syntax");
|
|
1674
|
+
}
|
|
1675
|
+
if (allTags.size > 0) {
|
|
1676
|
+
suggestions.push(`Suggested tags: ${[...allTags].join(", ")}`);
|
|
1677
|
+
}
|
|
1678
|
+
return { pages, suggestions };
|
|
1679
|
+
}
|
|
1680
|
+
// ── Auto-Classification ───────────────────────────────────────
|
|
1681
|
+
/** Auto-classify content into entity type and suggested tags.
|
|
1682
|
+
* Pure heuristic — zero LLM dependency. Analyzes title, body,
|
|
1683
|
+
* and structure to determine the best type and relevant tags.
|
|
1684
|
+
* If frontmatter already has a type, respects it. */
|
|
1685
|
+
classify(content) {
|
|
1686
|
+
const parsed = matter(content);
|
|
1687
|
+
const body = parsed.content.toLowerCase();
|
|
1688
|
+
const title = (parsed.data.title ?? "").toLowerCase();
|
|
1689
|
+
const combined = title + " " + body;
|
|
1690
|
+
// If frontmatter already specifies type, respect it but still suggest tags
|
|
1691
|
+
if (parsed.data.type && typeof parsed.data.type === "string" && parsed.data.type !== "note") {
|
|
1692
|
+
const existingTags = Array.isArray(parsed.data.tags) ? parsed.data.tags.map(String) : [];
|
|
1693
|
+
const suggestedTags = existingTags.length > 0 ? existingTags : this.extractTags(combined);
|
|
1694
|
+
return { type: parsed.data.type, tags: suggestedTags, confidence: 1.0 };
|
|
1695
|
+
}
|
|
1696
|
+
// Score each entity type based on keyword signals
|
|
1697
|
+
const scores = {
|
|
1698
|
+
person: 0, concept: 0, event: 0, artifact: 0, code: 0,
|
|
1699
|
+
comparison: 0, summary: 0, "how-to": 0, synthesis: 0, note: 0,
|
|
1700
|
+
};
|
|
1701
|
+
// Person signals
|
|
1702
|
+
for (const w of ["born", "career", "biography", "researcher", "professor", "author",
|
|
1703
|
+
"founder", "role:", "affiliat", "人物", "创始人", "研究员"]) {
|
|
1704
|
+
if (combined.includes(w))
|
|
1705
|
+
scores.person += 2;
|
|
1706
|
+
}
|
|
1707
|
+
// Concept signals
|
|
1708
|
+
for (const w of ["definition", "theory", "concept", "principle", "paradigm",
|
|
1709
|
+
"what is", "核心思想", "定义", "概念", "理论", "原理"]) {
|
|
1710
|
+
if (combined.includes(w))
|
|
1711
|
+
scores.concept += 2;
|
|
1712
|
+
}
|
|
1713
|
+
// Event signals
|
|
1714
|
+
for (const w of ["happened", "occurred", "conference", "launched", "announced",
|
|
1715
|
+
"event", "发布会", "事件", "会议"]) {
|
|
1716
|
+
if (combined.includes(w))
|
|
1717
|
+
scores.event += 2;
|
|
1718
|
+
}
|
|
1719
|
+
// Artifact signals (papers, tools, models)
|
|
1720
|
+
for (const w of ["paper", "论文", "tool", "library", "framework", "model",
|
|
1721
|
+
"version", "release", "arxiv", "github", "引用", "doi"]) {
|
|
1722
|
+
if (combined.includes(w))
|
|
1723
|
+
scores.artifact += 2;
|
|
1724
|
+
}
|
|
1725
|
+
// Code signals (source code with business logic)
|
|
1726
|
+
for (const w of ["procedure division", "identification division", "data division",
|
|
1727
|
+
"working-storage", "copybook", "program-id", "perform", "evaluate",
|
|
1728
|
+
"cobol", "jcl", "cics", "db2", "vsam", "pic x", "pic 9",
|
|
1729
|
+
"function ", "def ", "class ", "import ", "module", "subroutine",
|
|
1730
|
+
"源代码", "程序", "代码", "子程序", "调用关系"]) {
|
|
1731
|
+
if (combined.includes(w))
|
|
1732
|
+
scores.code += 2;
|
|
1733
|
+
}
|
|
1734
|
+
// Code blocks strongly suggest code type
|
|
1735
|
+
const codeBlockCount = (body.match(/```/g) ?? []).length / 2;
|
|
1736
|
+
if (codeBlockCount >= 1)
|
|
1737
|
+
scores.code += 2;
|
|
1738
|
+
if (codeBlockCount >= 3)
|
|
1739
|
+
scores.code += 3;
|
|
1740
|
+
// Comparison signals
|
|
1741
|
+
for (const w of ["vs", "versus", "compared", "comparison", "benchmark",
|
|
1742
|
+
"对比", "比较", "横评"]) {
|
|
1743
|
+
if (combined.includes(w))
|
|
1744
|
+
scores.comparison += 2;
|
|
1745
|
+
}
|
|
1746
|
+
// Many table rows strongly suggest comparison
|
|
1747
|
+
if ((body.match(/\|/g) ?? []).length > 15)
|
|
1748
|
+
scores.comparison += 3;
|
|
1749
|
+
// Summary signals
|
|
1750
|
+
for (const w of ["summary", "overview", "timeline", "history", "evolution",
|
|
1751
|
+
"演进", "总结", "概述", "版本", "时间线", "回顾"]) {
|
|
1752
|
+
if (combined.includes(w))
|
|
1753
|
+
scores.summary += 2;
|
|
1754
|
+
}
|
|
1755
|
+
// How-to signals
|
|
1756
|
+
for (const w of ["step", "guide", "tutorial", "how to", "procedure",
|
|
1757
|
+
"install", "setup", "步骤", "指南", "教程", "安装"]) {
|
|
1758
|
+
if (combined.includes(w))
|
|
1759
|
+
scores["how-to"] += 2;
|
|
1760
|
+
}
|
|
1761
|
+
// Synthesis signals
|
|
1762
|
+
for (const w of ["synthesis", "derived from", "combining", "integrat",
|
|
1763
|
+
"综合", "提炼", "整合"]) {
|
|
1764
|
+
if (combined.includes(w))
|
|
1765
|
+
scores.synthesis += 2;
|
|
1766
|
+
}
|
|
1767
|
+
// Pick the highest-scoring type
|
|
1768
|
+
let bestType = "note";
|
|
1769
|
+
let bestScore = 0;
|
|
1770
|
+
for (const [type, score] of Object.entries(scores)) {
|
|
1771
|
+
if (score > bestScore) {
|
|
1772
|
+
bestScore = score;
|
|
1773
|
+
bestType = type;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
const confidence = bestScore > 0 ? Math.min(bestScore / 10, 1.0) : 0.3;
|
|
1777
|
+
const tags = this.extractTags(combined);
|
|
1778
|
+
return { type: bestType, tags, confidence };
|
|
1779
|
+
}
|
|
1780
|
+
/**
|
|
1781
|
+
* Return the title→slug index used by autoLink, building it lazily.
|
|
1782
|
+
* Results are cached in `titleIndexCache` and updated incrementally by
|
|
1783
|
+
* `write()` and `delete()` — so the first call is O(n file reads) but
|
|
1784
|
+
* subsequent calls are O(1) even across a batch of writes.
|
|
1785
|
+
*/
|
|
1786
|
+
getTitleIndex() {
|
|
1787
|
+
if (this.titleIndexCache !== null)
|
|
1788
|
+
return this.titleIndexCache;
|
|
1789
|
+
const candidates = [];
|
|
1790
|
+
for (const p of this.listAllPages()) {
|
|
1791
|
+
if (isSystemPage(p))
|
|
1792
|
+
continue;
|
|
1793
|
+
const slug = basename(p, ".md");
|
|
1794
|
+
try {
|
|
1795
|
+
const raw = readFileSync(join(this.config.wikiDir, p), "utf-8");
|
|
1796
|
+
const fm = matter(raw).data;
|
|
1797
|
+
const title = (fm.title ?? slug.replace(/-/g, " ")).trim();
|
|
1798
|
+
if (title.length >= 4)
|
|
1799
|
+
candidates.push({ title, slug });
|
|
1800
|
+
}
|
|
1801
|
+
catch { /* skip unreadable pages */ }
|
|
1802
|
+
}
|
|
1803
|
+
candidates.sort((a, b) => b.title.length - a.title.length);
|
|
1804
|
+
this.titleIndexCache = candidates;
|
|
1805
|
+
return this.titleIndexCache;
|
|
1806
|
+
}
|
|
1807
|
+
/**
|
|
1808
|
+
* Scan content body for mentions of existing page titles and inject `[[slug|text]]` links.
|
|
1809
|
+
*
|
|
1810
|
+
* Skipped zones (unchanged):
|
|
1811
|
+
* - Fenced code blocks (``` or ~~~)
|
|
1812
|
+
* - Inline code (`...`)
|
|
1813
|
+
* - Existing `[[wiki links]]`
|
|
1814
|
+
* - Markdown `[text](url)` links
|
|
1815
|
+
* - Bare URLs (https?://...)
|
|
1816
|
+
*
|
|
1817
|
+
* Rules:
|
|
1818
|
+
* - Only titles ≥ 4 chars are considered (avoids noise from short tokens)
|
|
1819
|
+
* - Each page is linked at most once — first occurrence wins
|
|
1820
|
+
* - Longest title wins when two candidates overlap
|
|
1821
|
+
* - Self-references (same slug as `selfPath`) are excluded
|
|
1822
|
+
*
|
|
1823
|
+
* Returns `{ content, linksAdded }`. Content is unchanged when linksAdded === 0.
|
|
1824
|
+
*/
|
|
1825
|
+
autoLink(content, selfPath) {
|
|
1826
|
+
const parsed = matter(content);
|
|
1827
|
+
const body = parsed.content;
|
|
1828
|
+
const selfSlug = basename(selfPath, ".md");
|
|
1829
|
+
// Exclude self — filter from the shared (cached) index without mutating it
|
|
1830
|
+
const candidates = this.getTitleIndex().filter(c => c.slug !== selfSlug);
|
|
1831
|
+
if (candidates.length === 0)
|
|
1832
|
+
return { content, linksAdded: 0 };
|
|
1833
|
+
// Split body into skip zones (code, existing links, urls) and safe zones
|
|
1834
|
+
const SKIP_RE = /(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`]*`|\[\[[^\]]*\]\]|\[[^\]]*\]\([^)]*\)|https?:\/\/\S+)/g;
|
|
1835
|
+
const segments = [];
|
|
1836
|
+
let last = 0;
|
|
1837
|
+
let m;
|
|
1838
|
+
while ((m = SKIP_RE.exec(body)) !== null) {
|
|
1839
|
+
if (m.index > last)
|
|
1840
|
+
segments.push({ text: body.slice(last, m.index), skip: false });
|
|
1841
|
+
segments.push({ text: m[0], skip: true });
|
|
1842
|
+
last = m.index + m[0].length;
|
|
1843
|
+
}
|
|
1844
|
+
if (last < body.length)
|
|
1845
|
+
segments.push({ text: body.slice(last), skip: false });
|
|
1846
|
+
const linked = new Set();
|
|
1847
|
+
let linksAdded = 0;
|
|
1848
|
+
const newSegments = segments.map(seg => {
|
|
1849
|
+
if (seg.skip)
|
|
1850
|
+
return seg.text;
|
|
1851
|
+
const text = seg.text;
|
|
1852
|
+
// Collect every candidate occurrence in this segment
|
|
1853
|
+
const allMatches = [];
|
|
1854
|
+
for (const { title, slug } of candidates) {
|
|
1855
|
+
if (linked.has(slug))
|
|
1856
|
+
continue;
|
|
1857
|
+
const escaped = title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1858
|
+
const re = new RegExp(`(?<![\\p{L}\\p{N}\\[])${escaped}(?![\\p{L}\\p{N}\\]])`, "giu");
|
|
1859
|
+
let m2;
|
|
1860
|
+
while ((m2 = re.exec(text)) !== null) {
|
|
1861
|
+
allMatches.push({ start: m2.index, end: m2.index + m2[0].length, matchText: m2[0], slug });
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
if (allMatches.length === 0)
|
|
1865
|
+
return text;
|
|
1866
|
+
// Sort by position asc, then by match length desc (longer wins at same start)
|
|
1867
|
+
allMatches.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));
|
|
1868
|
+
// Greedy selection: non-overlapping, one link per slug
|
|
1869
|
+
const selected = [];
|
|
1870
|
+
let lastEnd = 0;
|
|
1871
|
+
const usedSlugs = new Set();
|
|
1872
|
+
for (const m2 of allMatches) {
|
|
1873
|
+
if (m2.start < lastEnd)
|
|
1874
|
+
continue; // overlaps a previous match
|
|
1875
|
+
if (usedSlugs.has(m2.slug))
|
|
1876
|
+
continue; // slug already linked in this segment
|
|
1877
|
+
// (slugs in linked were pre-filtered when building allMatches above)
|
|
1878
|
+
selected.push(m2);
|
|
1879
|
+
lastEnd = m2.end;
|
|
1880
|
+
usedSlugs.add(m2.slug);
|
|
1881
|
+
}
|
|
1882
|
+
if (selected.length === 0)
|
|
1883
|
+
return text;
|
|
1884
|
+
// Apply replacements right-to-left (preserves earlier positions)
|
|
1885
|
+
let result = text;
|
|
1886
|
+
for (const m2 of [...selected].reverse()) {
|
|
1887
|
+
linked.add(m2.slug);
|
|
1888
|
+
linksAdded++;
|
|
1889
|
+
result = result.slice(0, m2.start) + `[[${m2.slug}|${m2.matchText}]]` + result.slice(m2.end);
|
|
1890
|
+
}
|
|
1891
|
+
return result;
|
|
1892
|
+
});
|
|
1893
|
+
if (linksAdded === 0)
|
|
1894
|
+
return { content, linksAdded: 0 };
|
|
1895
|
+
const newBody = newSegments.join("");
|
|
1896
|
+
return { content: matter.stringify(newBody, parsed.data), linksAdded };
|
|
1897
|
+
}
|
|
1898
|
+
/** Auto-classify and inject type/tags into content if missing.
|
|
1899
|
+
* Returns the enriched content string. */
|
|
1900
|
+
autoClassifyContent(content) {
|
|
1901
|
+
const parsed = matter(content);
|
|
1902
|
+
// Only auto-classify if type is missing or is generic "note"
|
|
1903
|
+
if (parsed.data.type && parsed.data.type !== "note")
|
|
1904
|
+
return content;
|
|
1905
|
+
const classification = this.classify(content);
|
|
1906
|
+
if (!parsed.data.type || parsed.data.type === "note") {
|
|
1907
|
+
parsed.data.type = classification.type;
|
|
1908
|
+
}
|
|
1909
|
+
// Merge tags: keep existing + add new suggestions (deduplicated)
|
|
1910
|
+
const existingTags = Array.isArray(parsed.data.tags) ? parsed.data.tags.map(String) : [];
|
|
1911
|
+
const merged = [...new Set([...existingTags, ...classification.tags])];
|
|
1912
|
+
if (merged.length > 0)
|
|
1913
|
+
parsed.data.tags = merged;
|
|
1914
|
+
return matter.stringify(parsed.content, parsed.data);
|
|
1915
|
+
}
|
|
1916
|
+
/** Extract relevant tags from text using keyword matching. */
|
|
1917
|
+
extractTags(text) {
|
|
1918
|
+
const knownTags = {
|
|
1919
|
+
"yolo": "yolo", "object detection": "object-detection", "目标检测": "object-detection",
|
|
1920
|
+
"computer vision": "computer-vision", "计算机视觉": "computer-vision",
|
|
1921
|
+
"deep learning": "deep-learning", "深度学习": "deep-learning",
|
|
1922
|
+
"machine learning": "machine-learning", "机器学习": "machine-learning",
|
|
1923
|
+
"transformer": "transformer", "attention": "attention-mechanism",
|
|
1924
|
+
"cnn": "cnn", "卷积": "cnn", "real-time": "real-time", "实时": "real-time",
|
|
1925
|
+
"python": "python", "pytorch": "pytorch", "tensorflow": "tensorflow",
|
|
1926
|
+
"arxiv": "academic", "论文": "academic", "paper": "academic",
|
|
1927
|
+
"benchmark": "benchmark", "基准": "benchmark",
|
|
1928
|
+
"neural network": "neural-network", "神经网络": "neural-network",
|
|
1929
|
+
"nlp": "nlp", "自然语言": "nlp", "language model": "llm", "大模型": "llm",
|
|
1930
|
+
"gan": "gan", "diffusion": "diffusion", "stable diffusion": "stable-diffusion",
|
|
1931
|
+
"reinforcement learning": "reinforcement-learning", "强化学习": "reinforcement-learning",
|
|
1932
|
+
"autonomous driving": "autonomous-driving", "自动驾驶": "autonomous-driving",
|
|
1933
|
+
"segmentation": "segmentation", "分割": "segmentation",
|
|
1934
|
+
"detection": "detection", "检测": "detection",
|
|
1935
|
+
"classification": "classification", "分类": "classification",
|
|
1936
|
+
"training": "training", "inference": "inference", "推理": "inference",
|
|
1937
|
+
"edge deploy": "edge-deployment", "边缘部署": "edge-deployment",
|
|
1938
|
+
"anchor": "anchor", "backbone": "backbone", "fpn": "feature-pyramid",
|
|
1939
|
+
"docker": "docker", "kubernetes": "kubernetes",
|
|
1940
|
+
"api": "api", "rest": "rest-api", "mcp": "mcp",
|
|
1941
|
+
};
|
|
1942
|
+
const tags = new Set();
|
|
1943
|
+
const lower = text.toLowerCase();
|
|
1944
|
+
for (const [keyword, tag] of Object.entries(knownTags)) {
|
|
1945
|
+
if (lower.includes(keyword))
|
|
1946
|
+
tags.add(tag);
|
|
1947
|
+
}
|
|
1948
|
+
return [...tags];
|
|
1949
|
+
}
|
|
1950
|
+
// ── Schemas ───────────────────────────────────────────────────
|
|
1951
|
+
/** List available entity type schemas. */
|
|
1952
|
+
schemas() {
|
|
1953
|
+
const dir = this.config.schemasDir;
|
|
1954
|
+
if (!existsSync(dir))
|
|
1955
|
+
return [];
|
|
1956
|
+
const result = [];
|
|
1957
|
+
for (const file of readdirSync(dir).filter((f) => f.endsWith(".md"))) {
|
|
1958
|
+
const content = readFileSync(join(dir, file), "utf-8");
|
|
1959
|
+
const parsed = matter(content);
|
|
1960
|
+
result.push({
|
|
1961
|
+
name: basename(file, ".md"),
|
|
1962
|
+
description: parsed.data.description ?? "",
|
|
1963
|
+
template: content,
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
return result;
|
|
1967
|
+
}
|
|
1968
|
+
// ── Log ───────────────────────────────────────────────────────
|
|
1969
|
+
/** Get operation log entries. */
|
|
1970
|
+
getLog(limit = 20) {
|
|
1971
|
+
const logPath = join(this.config.wikiDir, "log.md");
|
|
1972
|
+
if (!existsSync(logPath))
|
|
1973
|
+
return [];
|
|
1974
|
+
const content = readFileSync(logPath, "utf-8");
|
|
1975
|
+
const lines = content.split("\n").filter((l) => l.startsWith("|") && !l.startsWith("| Time") && !l.startsWith("|---"));
|
|
1976
|
+
const entries = [];
|
|
1977
|
+
for (const line of lines) {
|
|
1978
|
+
const cols = line.split("|").map((c) => c.trim()).filter(Boolean);
|
|
1979
|
+
if (cols.length >= 4) {
|
|
1980
|
+
entries.push({ time: cols[0], operation: cols[1], page: cols[2], summary: cols[3] });
|
|
1981
|
+
}
|
|
1982
|
+
else if (cols.length >= 3) {
|
|
1983
|
+
entries.push({ time: cols[0], operation: cols[1], page: "—", summary: cols[2] });
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
return entries.slice(-limit);
|
|
1987
|
+
}
|
|
1988
|
+
// ── Index rebuild ─────────────────────────────────────────────
|
|
1989
|
+
/** Rebuild index.md from all pages.
|
|
1990
|
+
* If topic subdirectories exist, generates per-topic sub-indexes and
|
|
1991
|
+
* a top-level hub. Otherwise falls back to flat type-based grouping. */
|
|
1992
|
+
/** Build a page cache to avoid reading each page multiple times during rebuild. */
|
|
1993
|
+
buildPageCache() {
|
|
1994
|
+
const pages = this.listAllPages().filter((p) => !isSystemPage(p));
|
|
1995
|
+
const cache = new Map();
|
|
1996
|
+
for (const pagePath of pages) {
|
|
1997
|
+
const page = this.read(pagePath);
|
|
1998
|
+
if (page)
|
|
1999
|
+
cache.set(pagePath, page);
|
|
2000
|
+
}
|
|
2001
|
+
return cache;
|
|
2002
|
+
}
|
|
2003
|
+
rebuildIndex(pageCache) {
|
|
2004
|
+
// Single listAllPages() call — reused for both content pages and stale sub-index cleanup
|
|
2005
|
+
const allPages = pageCache
|
|
2006
|
+
? [...pageCache.keys(), ...this.listAllPages().filter((p) => isSystemPage(p))]
|
|
2007
|
+
: this.listAllPages();
|
|
2008
|
+
const pages = allPages.filter((p) => !isSystemPage(p));
|
|
2009
|
+
let rawCount = 0;
|
|
2010
|
+
try {
|
|
2011
|
+
rawCount = this.rawCount();
|
|
2012
|
+
}
|
|
2013
|
+
catch { /* no raw dir */ }
|
|
2014
|
+
// Collect existing sub-indexes before rebuild so we can remove stale ones
|
|
2015
|
+
// (uses allPages from above — no extra listAllPages() traversal)
|
|
2016
|
+
const existingSubIndexes = allPages
|
|
2017
|
+
.filter((p) => p !== "index.md" && p.endsWith("/index.md"));
|
|
2018
|
+
// Compute the set of sub-indexes that should exist based on current pages
|
|
2019
|
+
const expectedSubIndexes = new Set();
|
|
2020
|
+
for (const pagePath of pages) {
|
|
2021
|
+
const parts = pagePath.split("/");
|
|
2022
|
+
for (let i = 1; i < parts.length; i++) {
|
|
2023
|
+
expectedSubIndexes.add(parts.slice(0, i).join("/") + "/index.md");
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
// Remove stale sub-indexes (and empty parent dirs)
|
|
2027
|
+
for (const staleIndex of existingSubIndexes) {
|
|
2028
|
+
if (!expectedSubIndexes.has(staleIndex)) {
|
|
2029
|
+
const fullPath = join(this.config.wikiDir, staleIndex);
|
|
2030
|
+
if (existsSync(fullPath))
|
|
2031
|
+
unlinkSync(fullPath);
|
|
2032
|
+
// Clean up empty parent directories up to wiki root
|
|
2033
|
+
let dir = dirname(fullPath);
|
|
2034
|
+
const wikiRoot = resolve(this.config.wikiDir);
|
|
2035
|
+
while (dir !== wikiRoot && dir.startsWith(wikiRoot)) {
|
|
2036
|
+
try {
|
|
2037
|
+
rmdirSync(dir); // only succeeds if empty
|
|
2038
|
+
dir = dirname(dir);
|
|
2039
|
+
}
|
|
2040
|
+
catch {
|
|
2041
|
+
break; // not empty, stop
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
// Partition pages into topic dirs vs root-level
|
|
2047
|
+
const topicPages = {}; // topic -> page paths
|
|
2048
|
+
const rootPages = [];
|
|
2049
|
+
for (const pagePath of pages) {
|
|
2050
|
+
const parts = pagePath.split("/");
|
|
2051
|
+
if (parts.length >= 2) {
|
|
2052
|
+
const topic = parts[0];
|
|
2053
|
+
if (!topicPages[topic])
|
|
2054
|
+
topicPages[topic] = [];
|
|
2055
|
+
topicPages[topic].push(pagePath);
|
|
2056
|
+
}
|
|
2057
|
+
else {
|
|
2058
|
+
rootPages.push(pagePath);
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
const hasTopics = Object.keys(topicPages).length > 0;
|
|
2062
|
+
const now = new Date().toISOString();
|
|
2063
|
+
if (hasTopics) {
|
|
2064
|
+
// ── Build per-topic sub-indexes ──
|
|
2065
|
+
for (const [topic, tPages] of Object.entries(topicPages)) {
|
|
2066
|
+
this.rebuildTopicIndex(topic, tPages, now, pageCache);
|
|
2067
|
+
}
|
|
2068
|
+
// ── Build top-level hub index ──
|
|
2069
|
+
const topicCount = Object.keys(topicPages).length;
|
|
2070
|
+
let lines = [
|
|
2071
|
+
"---",
|
|
2072
|
+
"title: Knowledge Base Index",
|
|
2073
|
+
"type: index",
|
|
2074
|
+
`created: "${this.read("index.md")?.created ?? now}"`,
|
|
2075
|
+
`updated: "${now}"`,
|
|
2076
|
+
"---",
|
|
2077
|
+
"",
|
|
2078
|
+
"# Knowledge Base Index",
|
|
2079
|
+
"",
|
|
2080
|
+
`**${pages.length} pages** across **${topicCount} topics** | **${rawCount} raw sources**`,
|
|
2081
|
+
"",
|
|
2082
|
+
"## Topics",
|
|
2083
|
+
"",
|
|
2084
|
+
];
|
|
2085
|
+
const sortedTopics = Object.keys(topicPages).sort();
|
|
2086
|
+
for (const topic of sortedTopics) {
|
|
2087
|
+
const count = topicPages[topic].length;
|
|
2088
|
+
// Try to read topic sub-index title for a description
|
|
2089
|
+
const subIndex = this.read(`${topic}/index.md`);
|
|
2090
|
+
const desc = subIndex?.frontmatter?.description;
|
|
2091
|
+
const suffix = desc ? ` — ${desc}` : "";
|
|
2092
|
+
lines.push(`- [[${topic}/index]] — ${topic} (${count} pages)${suffix}`);
|
|
2093
|
+
}
|
|
2094
|
+
lines.push("");
|
|
2095
|
+
// Root-level pages (not in any topic dir)
|
|
2096
|
+
if (rootPages.length > 0) {
|
|
2097
|
+
const categories = {};
|
|
2098
|
+
for (const pagePath of rootPages) {
|
|
2099
|
+
const page = pageCache?.get(pagePath) ?? this.read(pagePath);
|
|
2100
|
+
if (!page)
|
|
2101
|
+
continue;
|
|
2102
|
+
const type = page.type ?? "uncategorized";
|
|
2103
|
+
if (!categories[type])
|
|
2104
|
+
categories[type] = [];
|
|
2105
|
+
const slug = basename(pagePath, extname(pagePath));
|
|
2106
|
+
const updated = page.updated ? ` _(${page.updated.slice(0, 10)})_` : "";
|
|
2107
|
+
categories[type].push(`- [[${slug}]] — ${page.title}${updated}`);
|
|
2108
|
+
}
|
|
2109
|
+
for (const type of Object.keys(categories).sort()) {
|
|
2110
|
+
const label = type.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2111
|
+
lines.push(`## ${label} (${categories[type].length})`, "");
|
|
2112
|
+
lines.push(...categories[type], "");
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
lines.push("---", "", `_Last rebuilt: ${now.replace("T", " ").slice(0, 16)} UTC_`, "");
|
|
2116
|
+
writeFileSync(join(this.config.wikiDir, "index.md"), lines.join("\n"));
|
|
2117
|
+
}
|
|
2118
|
+
else {
|
|
2119
|
+
// ── Flat mode: group by type (backward compatible) ──
|
|
2120
|
+
const categories = {};
|
|
2121
|
+
for (const pagePath of pages) {
|
|
2122
|
+
const page = pageCache?.get(pagePath) ?? this.read(pagePath);
|
|
2123
|
+
if (!page)
|
|
2124
|
+
continue;
|
|
2125
|
+
const type = page.type ?? "uncategorized";
|
|
2126
|
+
if (!categories[type])
|
|
2127
|
+
categories[type] = [];
|
|
2128
|
+
const slug = basename(pagePath, extname(pagePath));
|
|
2129
|
+
const updated = page.updated ? ` _(${page.updated.slice(0, 10)})_` : "";
|
|
2130
|
+
categories[type].push(`- [[${slug}]] — ${page.title}${updated}`);
|
|
2131
|
+
}
|
|
2132
|
+
let lines = [
|
|
2133
|
+
"---",
|
|
2134
|
+
"title: Knowledge Base Index",
|
|
2135
|
+
"type: index",
|
|
2136
|
+
`created: "${this.read("index.md")?.created ?? now}"`,
|
|
2137
|
+
`updated: "${now}"`,
|
|
2138
|
+
"---",
|
|
2139
|
+
"",
|
|
2140
|
+
"# Knowledge Base Index",
|
|
2141
|
+
"",
|
|
2142
|
+
`**${pages.length} pages** across **${Object.keys(categories).length} categories** | **${rawCount} raw sources**`,
|
|
2143
|
+
"",
|
|
2144
|
+
];
|
|
2145
|
+
const sortedTypes = Object.keys(categories).sort();
|
|
2146
|
+
if (sortedTypes.length > 0) {
|
|
2147
|
+
for (const type of sortedTypes) {
|
|
2148
|
+
const label = type.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2149
|
+
lines.push(`## ${label} (${categories[type].length})`, "");
|
|
2150
|
+
lines.push(...categories[type], "");
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
else {
|
|
2154
|
+
lines.push("_No pages yet._", "");
|
|
2155
|
+
}
|
|
2156
|
+
lines.push("---", "", `_Last rebuilt: ${now.replace("T", " ").slice(0, 16)} UTC_`, "");
|
|
2157
|
+
writeFileSync(join(this.config.wikiDir, "index.md"), lines.join("\n"));
|
|
2158
|
+
}
|
|
2159
|
+
this.searchEngine.invalidate();
|
|
2160
|
+
this.log("rebuild-index", "index.md", `Rebuilt index with ${pages.length} pages`);
|
|
2161
|
+
}
|
|
2162
|
+
/** Rebuild a directory sub-index at {dirPath}/index.md.
|
|
2163
|
+
* Recursively creates indexes for nested sub-directories. */
|
|
2164
|
+
rebuildTopicIndex(dirPath, allPages, now, pageCache) {
|
|
2165
|
+
// Separate into direct pages vs sub-directory pages
|
|
2166
|
+
const directPages = [];
|
|
2167
|
+
const subDirPages = {};
|
|
2168
|
+
const depth = dirPath.split("/").length;
|
|
2169
|
+
for (const pagePath of allPages) {
|
|
2170
|
+
const parts = pagePath.split("/");
|
|
2171
|
+
if (parts.length === depth + 1) {
|
|
2172
|
+
directPages.push(pagePath);
|
|
2173
|
+
}
|
|
2174
|
+
else if (parts.length > depth + 1) {
|
|
2175
|
+
const subDir = parts[depth];
|
|
2176
|
+
if (!subDirPages[subDir])
|
|
2177
|
+
subDirPages[subDir] = [];
|
|
2178
|
+
subDirPages[subDir].push(pagePath);
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
// Recursively build sub-directory indexes
|
|
2182
|
+
for (const [subDir, subPages] of Object.entries(subDirPages)) {
|
|
2183
|
+
this.rebuildTopicIndex(`${dirPath}/${subDir}`, subPages, now, pageCache);
|
|
2184
|
+
}
|
|
2185
|
+
const indexPath = `${dirPath}/index.md`;
|
|
2186
|
+
const existing = this.read(indexPath);
|
|
2187
|
+
const hasSubDirs = Object.keys(subDirPages).length > 0;
|
|
2188
|
+
const label = dirPath.split("/").pop().replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2189
|
+
let lines = [
|
|
2190
|
+
"---",
|
|
2191
|
+
`title: "${label}"`,
|
|
2192
|
+
"type: index",
|
|
2193
|
+
`created: "${existing?.created ?? now}"`,
|
|
2194
|
+
`updated: "${now}"`,
|
|
2195
|
+
"---",
|
|
2196
|
+
"",
|
|
2197
|
+
`# ${label}`,
|
|
2198
|
+
"",
|
|
2199
|
+
`_${allPages.length} pages_`,
|
|
2200
|
+
"",
|
|
2201
|
+
];
|
|
2202
|
+
// List sub-directories first
|
|
2203
|
+
if (hasSubDirs) {
|
|
2204
|
+
lines.push("## Sub-topics", "");
|
|
2205
|
+
const sortedSubDirs = Object.keys(subDirPages).sort();
|
|
2206
|
+
for (const subDir of sortedSubDirs) {
|
|
2207
|
+
const count = subDirPages[subDir].length;
|
|
2208
|
+
const subLabel = subDir.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2209
|
+
lines.push(`- [[${dirPath}/${subDir}/index]] — ${subLabel} (${count} pages)`);
|
|
2210
|
+
}
|
|
2211
|
+
lines.push("");
|
|
2212
|
+
}
|
|
2213
|
+
// List direct pages by type
|
|
2214
|
+
if (directPages.length > 0) {
|
|
2215
|
+
const categories = {};
|
|
2216
|
+
for (const pagePath of directPages) {
|
|
2217
|
+
const page = pageCache?.get(pagePath) ?? this.read(pagePath);
|
|
2218
|
+
if (!page)
|
|
2219
|
+
continue;
|
|
2220
|
+
const type = page.type ?? "uncategorized";
|
|
2221
|
+
if (!categories[type])
|
|
2222
|
+
categories[type] = [];
|
|
2223
|
+
const slug = basename(pagePath, extname(pagePath));
|
|
2224
|
+
const updated = page.updated ? ` _(${page.updated.slice(0, 10)})_` : "";
|
|
2225
|
+
categories[type].push(`- [[${dirPath}/${slug}]] — ${page.title}${updated}`);
|
|
2226
|
+
}
|
|
2227
|
+
for (const type of Object.keys(categories).sort()) {
|
|
2228
|
+
const typeLabel = type.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2229
|
+
lines.push(`## ${typeLabel} (${categories[type].length})`, "");
|
|
2230
|
+
lines.push(...categories[type], "");
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
lines.push("---", "", `_Last rebuilt: ${now.replace("T", " ").slice(0, 16)} UTC_`, "");
|
|
2234
|
+
const fullPath = join(this.config.wikiDir, indexPath);
|
|
2235
|
+
mkdirSync(dirname(fullPath), { recursive: true });
|
|
2236
|
+
writeFileSync(fullPath, lines.join("\n"));
|
|
2237
|
+
}
|
|
2238
|
+
// ── Timeline ──────────────────────────────────────────────────
|
|
2239
|
+
/** Rebuild timeline.md — chronological view of all knowledge. */
|
|
2240
|
+
rebuildTimeline(pageCache) {
|
|
2241
|
+
const pages = pageCache
|
|
2242
|
+
? [...pageCache.keys()]
|
|
2243
|
+
: this.listAllPages().filter((p) => !isSystemPage(p));
|
|
2244
|
+
const entries = [];
|
|
2245
|
+
for (const pagePath of pages) {
|
|
2246
|
+
const page = pageCache?.get(pagePath) ?? this.read(pagePath);
|
|
2247
|
+
if (!page)
|
|
2248
|
+
continue;
|
|
2249
|
+
const date = page.created ?? page.updated ?? "unknown";
|
|
2250
|
+
// Use full relative path (without .md) as link slug for subdirectory support
|
|
2251
|
+
const slug = pagePath.endsWith(".md") ? pagePath.slice(0, -3) : pagePath;
|
|
2252
|
+
entries.push({
|
|
2253
|
+
date: date.slice(0, 10),
|
|
2254
|
+
page: slug,
|
|
2255
|
+
title: page.title,
|
|
2256
|
+
type: page.type ?? "note",
|
|
2257
|
+
});
|
|
2258
|
+
}
|
|
2259
|
+
entries.sort((a, b) => b.date.localeCompare(a.date));
|
|
2260
|
+
const now = new Date().toISOString();
|
|
2261
|
+
let lines = [
|
|
2262
|
+
"---",
|
|
2263
|
+
"title: Knowledge Timeline",
|
|
2264
|
+
"type: timeline",
|
|
2265
|
+
`updated: "${now}"`,
|
|
2266
|
+
"---",
|
|
2267
|
+
"",
|
|
2268
|
+
"# Knowledge Timeline",
|
|
2269
|
+
"",
|
|
2270
|
+
`_${entries.length} entries — last rebuilt: ${now.replace("T", " ").slice(0, 16)} UTC_`,
|
|
2271
|
+
"",
|
|
2272
|
+
];
|
|
2273
|
+
// Group by date
|
|
2274
|
+
let currentDate = "";
|
|
2275
|
+
for (const e of entries) {
|
|
2276
|
+
if (e.date !== currentDate) {
|
|
2277
|
+
currentDate = e.date;
|
|
2278
|
+
lines.push(`## ${currentDate}`, "");
|
|
2279
|
+
}
|
|
2280
|
+
lines.push(`- **[${e.type}]** [[${e.page}]] — ${e.title}`);
|
|
2281
|
+
}
|
|
2282
|
+
lines.push("");
|
|
2283
|
+
writeFileSync(join(this.config.wikiDir, "timeline.md"), lines.join("\n"));
|
|
2284
|
+
this.searchEngine.invalidate();
|
|
2285
|
+
this.log("rebuild-timeline", "timeline.md", `Rebuilt timeline with ${entries.length} entries`);
|
|
2286
|
+
}
|
|
2287
|
+
// ── Internal helpers ──────────────────────────────────────────
|
|
2288
|
+
listAllPages() {
|
|
2289
|
+
const dir = this.config.wikiDir;
|
|
2290
|
+
if (!existsSync(dir))
|
|
2291
|
+
return [];
|
|
2292
|
+
return listMdFiles(dir, dir);
|
|
2293
|
+
}
|
|
2294
|
+
parsePage(pagePath, raw) {
|
|
2295
|
+
const parsed = matter(raw);
|
|
2296
|
+
const fm = parsed.data;
|
|
2297
|
+
const body = parsed.content.trim();
|
|
2298
|
+
const linkMatches = body.matchAll(/\[\[([^\]]+)\]\]/g);
|
|
2299
|
+
// Support [[slug|display text]] format — extract slug part only
|
|
2300
|
+
const links = [...linkMatches].map((m) => m[1].split("|")[0].trim());
|
|
2301
|
+
return {
|
|
2302
|
+
path: pagePath,
|
|
2303
|
+
title: fm.title ?? basename(pagePath, extname(pagePath)),
|
|
2304
|
+
type: fm.type,
|
|
2305
|
+
tags: Array.isArray(fm.tags) ? fm.tags.map(String) : [],
|
|
2306
|
+
sources: Array.isArray(fm.sources) ? fm.sources.map(String) : [],
|
|
2307
|
+
content: body,
|
|
2308
|
+
frontmatter: fm,
|
|
2309
|
+
links,
|
|
2310
|
+
created: fm.created instanceof Date ? fm.created.toISOString() : fm.created,
|
|
2311
|
+
updated: fm.updated instanceof Date ? fm.updated.toISOString() : fm.updated,
|
|
2312
|
+
derivedFrom: Array.isArray(fm.derived_from) ? fm.derived_from.map(String) : undefined,
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
log(operation, page, summary) {
|
|
2316
|
+
const logPath = join(this.config.wikiDir, "log.md");
|
|
2317
|
+
const now = new Date().toISOString().replace("T", " ").slice(0, 16) + " UTC";
|
|
2318
|
+
const entry = `| ${now} | ${operation} | ${page} | ${summary} |\n`;
|
|
2319
|
+
if (existsSync(logPath)) {
|
|
2320
|
+
// Append-only — O(1) instead of O(file-size) read+write
|
|
2321
|
+
appendFileSync(logPath, entry);
|
|
2322
|
+
}
|
|
2323
|
+
else {
|
|
2324
|
+
const header = "---\ntitle: Operation Log\ntype: log\n---\n\n" +
|
|
2325
|
+
"# Operation Log\n\n" +
|
|
2326
|
+
"| Time | Operation | Page | Summary |\n" +
|
|
2327
|
+
"|------|-----------|------|--------|\n" +
|
|
2328
|
+
entry;
|
|
2329
|
+
writeFileSync(logPath, header);
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
// ── File helpers ──────────────────────────────────────────────────
|
|
2334
|
+
function listMdFiles(dir, root) {
|
|
2335
|
+
const result = [];
|
|
2336
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
2337
|
+
if (entry.name.startsWith("."))
|
|
2338
|
+
continue;
|
|
2339
|
+
const full = join(dir, entry.name);
|
|
2340
|
+
if (entry.isDirectory()) {
|
|
2341
|
+
result.push(...listMdFiles(full, root));
|
|
2342
|
+
}
|
|
2343
|
+
else if (entry.name.endsWith(".md")) {
|
|
2344
|
+
// Normalize to forward slashes for cross-platform consistency
|
|
2345
|
+
result.push(relative(root, full).replace(/\\/g, "/"));
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
return result.sort();
|
|
2349
|
+
}
|
|
2350
|
+
function listAllFiles(dir, root) {
|
|
2351
|
+
const result = [];
|
|
2352
|
+
if (!existsSync(dir))
|
|
2353
|
+
return result;
|
|
2354
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
2355
|
+
if (entry.name.startsWith("."))
|
|
2356
|
+
continue;
|
|
2357
|
+
const full = join(dir, entry.name);
|
|
2358
|
+
if (entry.isDirectory()) {
|
|
2359
|
+
result.push(...listAllFiles(full, root));
|
|
2360
|
+
}
|
|
2361
|
+
else {
|
|
2362
|
+
result.push(relative(root, full).replace(/\\/g, "/"));
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
return result.sort();
|
|
2366
|
+
}
|
|
2367
|
+
/** Recursively count files excluding .meta.yaml sidecars (fast — no stat/read). */
|
|
2368
|
+
function countNonMetaFiles(dir) {
|
|
2369
|
+
let count = 0;
|
|
2370
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
2371
|
+
if (entry.name.startsWith("."))
|
|
2372
|
+
continue;
|
|
2373
|
+
const full = join(dir, entry.name);
|
|
2374
|
+
if (entry.isDirectory()) {
|
|
2375
|
+
count += countNonMetaFiles(full);
|
|
2376
|
+
}
|
|
2377
|
+
else if (!entry.name.endsWith(".meta.yaml")) {
|
|
2378
|
+
count++;
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
return count;
|
|
2382
|
+
}
|
|
2383
|
+
function formatBytes(bytes) {
|
|
2384
|
+
if (bytes < 1024)
|
|
2385
|
+
return `${bytes} B`;
|
|
2386
|
+
if (bytes < 1024 * 1024)
|
|
2387
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
2388
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
2389
|
+
}
|
|
2390
|
+
function writeDefaultSchemas(dir) {
|
|
2391
|
+
const schemas = {
|
|
2392
|
+
"person.md": `---
|
|
2393
|
+
template: person
|
|
2394
|
+
description: Profile of a person
|
|
2395
|
+
---
|
|
2396
|
+
|
|
2397
|
+
# {{title}}
|
|
2398
|
+
|
|
2399
|
+
**Role:** [TODO]
|
|
2400
|
+
**Affiliations:** [TODO]
|
|
2401
|
+
|
|
2402
|
+
## Key Contributions
|
|
2403
|
+
|
|
2404
|
+
- [TODO]
|
|
2405
|
+
|
|
2406
|
+
## Relationships
|
|
2407
|
+
|
|
2408
|
+
- [TODO]
|
|
2409
|
+
|
|
2410
|
+
## Sources
|
|
2411
|
+
|
|
2412
|
+
- [TODO]
|
|
2413
|
+
`,
|
|
2414
|
+
"concept.md": `---
|
|
2415
|
+
template: concept
|
|
2416
|
+
description: An idea, theory, or abstract concept
|
|
2417
|
+
---
|
|
2418
|
+
|
|
2419
|
+
# {{title}}
|
|
2420
|
+
|
|
2421
|
+
## Definition
|
|
2422
|
+
|
|
2423
|
+
[TODO]
|
|
2424
|
+
|
|
2425
|
+
## Properties
|
|
2426
|
+
|
|
2427
|
+
- [TODO]
|
|
2428
|
+
|
|
2429
|
+
## Relationships
|
|
2430
|
+
|
|
2431
|
+
- [TODO]
|
|
2432
|
+
|
|
2433
|
+
## Examples
|
|
2434
|
+
|
|
2435
|
+
- [TODO]
|
|
2436
|
+
|
|
2437
|
+
## Sources
|
|
2438
|
+
|
|
2439
|
+
- [TODO]
|
|
2440
|
+
`,
|
|
2441
|
+
"event.md": `---
|
|
2442
|
+
template: event
|
|
2443
|
+
description: Something that happened at a specific time
|
|
2444
|
+
---
|
|
2445
|
+
|
|
2446
|
+
# {{title}}
|
|
2447
|
+
|
|
2448
|
+
**Date:** [TODO]
|
|
2449
|
+
**Location:** [TODO]
|
|
2450
|
+
|
|
2451
|
+
## Participants
|
|
2452
|
+
|
|
2453
|
+
- [TODO]
|
|
2454
|
+
|
|
2455
|
+
## What Happened
|
|
2456
|
+
|
|
2457
|
+
[TODO]
|
|
2458
|
+
|
|
2459
|
+
## Outcomes & Impact
|
|
2460
|
+
|
|
2461
|
+
[TODO]
|
|
2462
|
+
|
|
2463
|
+
## Sources
|
|
2464
|
+
|
|
2465
|
+
- [TODO]
|
|
2466
|
+
`,
|
|
2467
|
+
"artifact.md": `---
|
|
2468
|
+
template: artifact
|
|
2469
|
+
description: A tool, paper, product, or created thing
|
|
2470
|
+
---
|
|
2471
|
+
|
|
2472
|
+
# {{title}}
|
|
2473
|
+
|
|
2474
|
+
**Type:** [TODO]
|
|
2475
|
+
**Creator:** [TODO]
|
|
2476
|
+
**Date:** [TODO]
|
|
2477
|
+
|
|
2478
|
+
## Purpose
|
|
2479
|
+
|
|
2480
|
+
[TODO]
|
|
2481
|
+
|
|
2482
|
+
## Key Features
|
|
2483
|
+
|
|
2484
|
+
- [TODO]
|
|
2485
|
+
|
|
2486
|
+
## Sources
|
|
2487
|
+
|
|
2488
|
+
- [TODO]
|
|
2489
|
+
`,
|
|
2490
|
+
"comparison.md": `---
|
|
2491
|
+
template: comparison
|
|
2492
|
+
description: Side-by-side analysis of two or more items
|
|
2493
|
+
---
|
|
2494
|
+
|
|
2495
|
+
# {{title}}
|
|
2496
|
+
|
|
2497
|
+
## Items Compared
|
|
2498
|
+
|
|
2499
|
+
| Dimension | Item A | Item B |
|
|
2500
|
+
|-----------|--------|--------|
|
|
2501
|
+
| [TODO] | [TODO] | [TODO] |
|
|
2502
|
+
|
|
2503
|
+
## Analysis
|
|
2504
|
+
|
|
2505
|
+
[TODO]
|
|
2506
|
+
|
|
2507
|
+
## Verdict
|
|
2508
|
+
|
|
2509
|
+
[TODO]
|
|
2510
|
+
|
|
2511
|
+
## Sources
|
|
2512
|
+
|
|
2513
|
+
- [TODO]
|
|
2514
|
+
`,
|
|
2515
|
+
"summary.md": `---
|
|
2516
|
+
template: summary
|
|
2517
|
+
description: Summary of a source document
|
|
2518
|
+
---
|
|
2519
|
+
|
|
2520
|
+
# {{title}}
|
|
2521
|
+
|
|
2522
|
+
**Source:** [TODO]
|
|
2523
|
+
**Date:** [TODO]
|
|
2524
|
+
|
|
2525
|
+
## Key Points
|
|
2526
|
+
|
|
2527
|
+
1. [TODO]
|
|
2528
|
+
|
|
2529
|
+
## Detailed Summary
|
|
2530
|
+
|
|
2531
|
+
[TODO]
|
|
2532
|
+
|
|
2533
|
+
## Sources
|
|
2534
|
+
|
|
2535
|
+
- [TODO]
|
|
2536
|
+
`,
|
|
2537
|
+
"how-to.md": `---
|
|
2538
|
+
template: how-to
|
|
2539
|
+
description: A procedure or guide
|
|
2540
|
+
---
|
|
2541
|
+
|
|
2542
|
+
# {{title}}
|
|
2543
|
+
|
|
2544
|
+
## Goal
|
|
2545
|
+
|
|
2546
|
+
[TODO]
|
|
2547
|
+
|
|
2548
|
+
## Prerequisites
|
|
2549
|
+
|
|
2550
|
+
- [TODO]
|
|
2551
|
+
|
|
2552
|
+
## Steps
|
|
2553
|
+
|
|
2554
|
+
1. [TODO]
|
|
2555
|
+
|
|
2556
|
+
## Pitfalls
|
|
2557
|
+
|
|
2558
|
+
- [TODO]
|
|
2559
|
+
|
|
2560
|
+
## Sources
|
|
2561
|
+
|
|
2562
|
+
- [TODO]
|
|
2563
|
+
`,
|
|
2564
|
+
"note.md": `---
|
|
2565
|
+
template: note
|
|
2566
|
+
description: Freeform knowledge — anything that does not fit other templates
|
|
2567
|
+
---
|
|
2568
|
+
|
|
2569
|
+
# {{title}}
|
|
2570
|
+
|
|
2571
|
+
{{content}}
|
|
2572
|
+
|
|
2573
|
+
## Sources
|
|
2574
|
+
|
|
2575
|
+
- [TODO]
|
|
2576
|
+
`,
|
|
2577
|
+
"code.md": `---
|
|
2578
|
+
template: code
|
|
2579
|
+
description: Source code with business logic explanation
|
|
2580
|
+
---
|
|
2581
|
+
|
|
2582
|
+
# {{title}}
|
|
2583
|
+
|
|
2584
|
+
**Language:** [TODO]
|
|
2585
|
+
**Source:** [TODO: path in raw/]
|
|
2586
|
+
|
|
2587
|
+
## Business Logic
|
|
2588
|
+
|
|
2589
|
+
[TODO: What does this code do in business terms?]
|
|
2590
|
+
|
|
2591
|
+
## Input / Output
|
|
2592
|
+
|
|
2593
|
+
| Variable | Direction | Description |
|
|
2594
|
+
|----------|-----------|-------------|
|
|
2595
|
+
| [TODO] | in | [TODO] |
|
|
2596
|
+
| [TODO] | out | [TODO] |
|
|
2597
|
+
|
|
2598
|
+
## Dependencies
|
|
2599
|
+
|
|
2600
|
+
- [TODO: COPYBOOK, imports, called programs]
|
|
2601
|
+
|
|
2602
|
+
## Call Graph
|
|
2603
|
+
|
|
2604
|
+
- **Calls:** [TODO: [[other-programs]]]
|
|
2605
|
+
- **Called by:** [TODO: [[parent-programs]]]
|
|
2606
|
+
|
|
2607
|
+
## Source Code
|
|
2608
|
+
|
|
2609
|
+
\`\`\`
|
|
2610
|
+
[TODO: key code sections or link to raw/]
|
|
2611
|
+
\`\`\`
|
|
2612
|
+
|
|
2613
|
+
## Sources
|
|
2614
|
+
|
|
2615
|
+
- [TODO]
|
|
2616
|
+
`,
|
|
2617
|
+
"synthesis.md": `---
|
|
2618
|
+
template: synthesis
|
|
2619
|
+
description: Distilled knowledge combining insights from multiple pages
|
|
2620
|
+
---
|
|
2621
|
+
|
|
2622
|
+
# {{title}}
|
|
2623
|
+
|
|
2624
|
+
**Derived from:** [TODO: list source pages with [[links]]]
|
|
2625
|
+
**Date:** [TODO]
|
|
2626
|
+
|
|
2627
|
+
## Key Insights
|
|
2628
|
+
|
|
2629
|
+
[TODO: What emerges from combining these sources?]
|
|
2630
|
+
|
|
2631
|
+
## Connections
|
|
2632
|
+
|
|
2633
|
+
[TODO: How do these sources relate to each other?]
|
|
2634
|
+
|
|
2635
|
+
## Contradictions & Open Questions
|
|
2636
|
+
|
|
2637
|
+
[TODO: Where do sources disagree? What remains unclear?]
|
|
2638
|
+
|
|
2639
|
+
## Synthesis
|
|
2640
|
+
|
|
2641
|
+
[TODO: The integrated understanding]
|
|
2642
|
+
|
|
2643
|
+
## Sources
|
|
2644
|
+
|
|
2645
|
+
- [TODO]
|
|
2646
|
+
`,
|
|
2647
|
+
};
|
|
2648
|
+
for (const [filename, content] of Object.entries(schemas)) {
|
|
2649
|
+
writeFileSync(join(dir, filename), content);
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
/**
|
|
2653
|
+
* Simple glob matching for file filtering.
|
|
2654
|
+
* Supports: *.html, *.xlsx, *.{html,css}, **\/*.html
|
|
2655
|
+
* Not a full glob — just enough for pattern filtering.
|
|
2656
|
+
*/
|
|
2657
|
+
export function matchSimpleGlob(filepath, pattern) {
|
|
2658
|
+
// Handle brace expansion: *.{html,css} → [html, css]
|
|
2659
|
+
const braceMatch = pattern.match(/\.\{([^}]+)\}$/);
|
|
2660
|
+
if (braceMatch) {
|
|
2661
|
+
const exts = braceMatch[1].split(",").map(e => e.trim());
|
|
2662
|
+
const fileExt = extname(filepath).slice(1).toLowerCase();
|
|
2663
|
+
return exts.some(e => e.toLowerCase() === fileExt);
|
|
2664
|
+
}
|
|
2665
|
+
// Handle simple extension pattern: *.html
|
|
2666
|
+
if (pattern.startsWith("*.")) {
|
|
2667
|
+
const ext = pattern.slice(1).toLowerCase(); // ".html"
|
|
2668
|
+
return filepath.toLowerCase().endsWith(ext);
|
|
2669
|
+
}
|
|
2670
|
+
// Handle recursive pattern: **/*.html → just match extension
|
|
2671
|
+
if (pattern.startsWith("**/")) {
|
|
2672
|
+
return matchSimpleGlob(filepath, pattern.slice(3));
|
|
2673
|
+
}
|
|
2674
|
+
// Fallback: exact match
|
|
2675
|
+
return filepath === pattern;
|
|
2676
|
+
}
|
|
2677
|
+
//# sourceMappingURL=wiki.js.map
|