[module_id|query]\n');
+ process.exitCode = 1;
+ }
+ sharedCache.close();
+}
+
+// Compare real file paths: URL.pathname would give `/C:/...` on Windows and `%20` for spaces,
+// so the server would never start there.
+const realOrSelf = (p) => {
+ try {
+ return realpathSync(p);
+ } catch {
+ return path.resolve(p);
+ }
+};
+const isMain = Boolean(process.argv[1]) && realOrSelf(process.argv[1]) === realOrSelf(fileURLToPath(import.meta.url));
+if (isMain) {
+ if (process.argv[2] === '--cli') {
+ runCli(process.argv.slice(3)).catch((err) => {
+ process.stderr.write(`Error: ${err.message}\n`);
+ process.exit(1);
+ });
+ } else {
+ startStdioServer();
+ }
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/server/parser.mjs b/plugins/Jialei-03/mcode-repowiki/server/parser.mjs
new file mode 100644
index 00000000..4bba132b
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/parser.mjs
@@ -0,0 +1,860 @@
+const COMMON_STOP_WORDS = new Set([
+ // JS / TS
+ 'const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while', 'do',
+ 'switch', 'case', 'break', 'continue', 'default', 'try', 'catch', 'finally', 'throw',
+ 'new', 'this', 'super', 'class', 'extends', 'implements', 'interface', 'type', 'enum',
+ 'import', 'export', 'from', 'as', 'async', 'await', 'yield', 'typeof', 'instanceof',
+ 'in', 'of', 'void', 'delete', 'true', 'false', 'null', 'undefined', 'NaN', 'Infinity',
+ 'public', 'private', 'protected', 'readonly', 'static', 'abstract', 'override', 'declare',
+ 'namespace', 'module', 'keyof', 'infer', 'satisfies', 'is', 'asserts',
+ 'string', 'number', 'boolean', 'object', 'symbol', 'bigint', 'any', 'unknown', 'never',
+ 'Promise', 'Array', 'Map', 'Set', 'Record', 'Partial', 'Required', 'Readonly', 'Omit', 'Pick',
+ 'Error', 'Object', 'String', 'Number', 'Boolean', 'Math', 'JSON', 'Date', 'RegExp', 'Buffer',
+ 'console', 'process', 'window', 'document', 'globalThis', 'setTimeout', 'clearTimeout',
+ // Python
+ 'def', 'lambda', 'pass', 'None', 'True', 'False', 'and', 'or', 'not', 'elif', 'with',
+ 'global', 'nonlocal', 'assert', 'del', 'raise', 'except', 'self', 'cls', 'print', 'len',
+ 'range', 'dict', 'list', 'tuple', 'set', 'str', 'int', 'float', 'bool', 'bytes', 'Optional',
+ 'Union', 'Any', 'List', 'Dict', 'Tuple', 'Callable', 'Sequence', 'Iterable', 'TypeVar',
+ // Go / Rust / Java / C++
+ 'func', 'package', 'defer', 'go', 'chan', 'select', 'map', 'struct', 'fallthrough',
+ 'fn', 'pub', 'mut', 'impl', 'trait', 'where', 'crate', 'use', 'mod', 'match', ' ref',
+ 'let', ' loop', 'move', 'unsafe', 'extern', 'dyn', 'Self', 'Option', 'Result', 'Some', 'Ok', 'Err',
+ 'Vec', 'Box', 'Arc', 'Rc', 'String', 'usize', 'isize', 'u8', 'u16', 'u32', 'u64', 'i32', 'i64', 'f32', 'f64',
+ 'final', 'synchronized', 'volatile', 'transient', 'throws', 'package', 'include', 'template',
+ 'typename', 'constexpr', 'virtual', 'inline', 'nullptr', 'std', 'auto', 'using',
+]);
+
+const GENERIC_METHOD_NOISE = new Set([
+ 'get', 'set', 'has', 'add', 'clear', 'keys', 'values', 'entries', 'forEach', 'map',
+ 'filter', 'reduce', 'find', 'some', 'every', 'includes', 'indexOf', 'slice', 'splice',
+ 'push', 'pop', 'shift', 'unshift', 'join', 'split', 'replace', 'trim', 'match', 'test',
+ 'toString', 'valueOf', 'toLowerCase', 'toUpperCase', 'startsWith', 'endsWith',
+ 'resolve', 'reject', 'then', 'catch', 'finally', 'parse', 'stringify', 'log', 'warn', 'error',
+ 'info', 'debug', 'init', '__init__', 'main', 'run', 'start', 'stop', 'close', 'open', 'read', 'write',
+]);
+
+/**
+ * Strip comments and string literal payloads while preserving exact byte offsets and newlines.
+ * Inside JS/TS template literals (`...${expr}...`), static text is blanked while `${expr}` is preserved!
+ */
+export function sanitizeCode(source, lang) {
+ const n = source.length;
+ const chars = new Array(n);
+ const hashLineComment = lang === 'python' || lang === 'ruby' || lang === 'php';
+ const cStyleComment = lang !== 'python' && lang !== 'ruby';
+ const pyTriple = lang === 'python';
+ const jsTemplate = lang === 'typescript' || lang === 'javascript';
+ const goBacktick = lang === 'go';
+
+ let i = 0;
+ const templateBraceStack = [];
+
+ const blankRange = (start, end) => {
+ for (let k = start; k < end; k += 1) {
+ chars[k] = source[k] === '\n' ? '\n' : ' ';
+ }
+ };
+
+ while (i < n) {
+ const ch = source[i];
+ const next = source[i + 1];
+
+ // Resume template literal after closing `}` of `${...}`
+ if (jsTemplate && templateBraceStack.length > 0) {
+ const top = templateBraceStack[templateBraceStack.length - 1];
+ if (ch === '{') {
+ top.depth += 1;
+ chars[i] = ch;
+ i += 1;
+ continue;
+ }
+ if (ch === '}') {
+ if (top.depth === 0) {
+ templateBraceStack.pop();
+ chars[i] = ' ';
+ i += 1;
+ // Continue scanning static tail of template literal
+ i = scanJsTemplateTail(source, chars, i, templateBraceStack);
+ continue;
+ }
+ top.depth -= 1;
+ chars[i] = ch;
+ i += 1;
+ continue;
+ }
+ }
+
+ // Line comments: //
+ if (cStyleComment && ch === '/' && next === '/') {
+ const start = i;
+ i += 2;
+ while (i < n && source[i] !== '\n') i += 1;
+ blankRange(start, i);
+ continue;
+ }
+
+ // Block comments: /* ... */
+ if (cStyleComment && ch === '/' && next === '*') {
+ const start = i;
+ i += 2;
+ while (i < n && !(source[i] === '*' && source[i + 1] === '/')) i += 1;
+ i = Math.min(n, i + 2);
+ blankRange(start, i);
+ continue;
+ }
+
+ // Hash line comments: # ... (Python / Ruby / PHP)
+ if (hashLineComment && ch === '#') {
+ const start = i;
+ i += 1;
+ while (i < n && source[i] !== '\n') i += 1;
+ blankRange(start, i);
+ continue;
+ }
+
+ // Python triple-quoted strings: """...""" or '''...'''
+ if (
+ pyTriple &&
+ (ch === '"' || ch === "'") &&
+ source[i + 1] === ch &&
+ source[i + 2] === ch
+ ) {
+ const quote = ch;
+ const start = i;
+ i += 3;
+ while (
+ i < n &&
+ !(source[i] === quote && source[i + 1] === quote && source[i + 2] === quote)
+ ) {
+ if (source[i] === '\\') i += 2;
+ else i += 1;
+ }
+ i = Math.min(n, i + 3);
+ blankRange(start, i);
+ continue;
+ }
+
+ // JS/TS template literals: `...${expr}...`
+ if (jsTemplate && ch === '`') {
+ chars[i] = ' ';
+ i = scanJsTemplateTail(source, chars, i + 1, templateBraceStack);
+ continue;
+ }
+
+ // Go raw string literals: `...`
+ if (goBacktick && ch === '`') {
+ const start = i;
+ i += 1;
+ while (i < n && source[i] !== '`') i += 1;
+ i = Math.min(n, i + 1);
+ blankRange(start, i);
+ continue;
+ }
+
+ // Standard single or double quoted string literals
+ // Note: in Rust, `'a` is a lifetime! Only treat `'...'` as char literal if closed within 6 chars on same line
+ if (ch === '"' || (ch === "'" && lang !== 'rust')) {
+ const quote = ch;
+ chars[i] = quote;
+ i += 1;
+ const start = i;
+ while (i < n && source[i] !== quote && source[i] !== '\n') {
+ if (source[i] === '\\') i += 2;
+ else i += 1;
+ }
+ blankRange(start, i);
+ if (i < n && source[i] === quote) {
+ chars[i] = quote;
+ i += 1;
+ }
+ continue;
+ }
+
+ chars[i] = ch;
+ i += 1;
+ }
+
+ return chars.join('');
+}
+
+function scanJsTemplateTail(source, chars, startIdx, templateBraceStack) {
+ const n = source.length;
+ let i = startIdx;
+ while (i < n) {
+ const ch = source[i];
+ if (ch === '\\') {
+ chars[i] = ' ';
+ if (i + 1 < n) chars[i + 1] = source[i + 1] === '\n' ? '\n' : ' ';
+ i += 2;
+ continue;
+ }
+ if (ch === '`') {
+ chars[i] = ' ';
+ return i + 1;
+ }
+ if (ch === '$' && source[i + 1] === '{') {
+ chars[i] = ' ';
+ chars[i + 1] = ' ';
+ templateBraceStack.push({ depth: 0 });
+ return i + 2;
+ }
+ chars[i] = ch === '\n' ? '\n' : ' ';
+ i += 1;
+ }
+ return i;
+}
+
+function collapseSignature(lines, startIdx, maxContinuation = 5, maxLen = 140, cleanLines = null) {
+ let acc = '';
+ for (let idx = startIdx; idx < Math.min(lines.length, startIdx + maxContinuation); idx += 1) {
+ // Strip trailing inline comments via cleanLines length/structure or safe comment strip
+ let rawPart = lines[idx];
+ if (cleanLines && cleanLines[idx]) {
+ // Trim trailing whitespace-blanked comment region from raw line
+ const trimmedCleanLen = cleanLines[idx].trimEnd().length;
+ if (trimmedCleanLen > 0 && trimmedCleanLen < rawPart.length) {
+ rawPart = rawPart.slice(0, trimmedCleanLen);
+ }
+ }
+ const part = rawPart.trim();
+ if (!part) break;
+ acc = acc ? `${acc} ${part}` : part;
+ // Stop once signature opens body or terminates statement
+ if (/[{;]\s*$/u.test(part) || /:\s*$/u.test(part)) break;
+ }
+ acc = acc
+ .replace(/\s+/gu, ' ')
+ .replace(/\s*\{\s*$/u, '')
+ .replace(/\s*;\s*$/u, '')
+ .trim();
+ if (acc.length > maxLen) {
+ return `${acc.slice(0, maxLen - 3).trimEnd()}...`;
+ }
+ return acc;
+}
+
+function countBracesOnLine(cleanLine) {
+ let opens = 0;
+ let closes = 0;
+ for (let i = 0; i < cleanLine.length; i += 1) {
+ const c = cleanLine[i];
+ if (c === '{') opens += 1;
+ else if (c === '}') closes += 1;
+ }
+ return { opens, closes, delta: opens - closes };
+}
+
+/**
+ * Parse a single source file into symbols (defs), imports, exports, and identifier references.
+ */
+export function parseSourceFile(source, lang, relPath = '') {
+ const normalized = source.replace(/\r\n/gu, '\n');
+ const clean = sanitizeCode(normalized, lang);
+ const rawLines = normalized.split('\n');
+ const cleanLines = clean.split('\n');
+
+ const imports = extractImports(normalized, clean, lang);
+ const symbols = lang === 'python'
+ ? extractPythonSymbols(rawLines, cleanLines)
+ : extractBraceLangSymbols(rawLines, cleanLines, lang);
+
+ const { fileRefs, symbolCalls } = extractReferences(cleanLines, symbols);
+
+ // Attach top outgoing identifier references to each symbol for call-graph edges
+ for (let idx = 0; idx < symbols.length; idx += 1) {
+ const calls = symbolCalls.get(idx);
+ if (calls && calls.size > 0) {
+ symbols[idx].calls = [...calls.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 24)
+ .map(([ident]) => ident);
+ } else {
+ symbols[idx].calls = [];
+ }
+ }
+
+ return {
+ lang,
+ lineCount: rawLines.length,
+ imports,
+ symbols,
+ refs: fileRefs,
+ };
+}
+
+// ─── Import Extraction Across Languages ─────────────────────────────────────
+
+function extractImports(raw, clean, lang) {
+ const results = [];
+ const seen = new Set();
+ const addImport = (specifier, symbols = [], kind = 'import') => {
+ const spec = specifier.trim();
+ if (!spec) return;
+ const key = `${kind}:${spec}:${symbols.join(',')}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ results.push({ specifier: spec, symbols, kind });
+ };
+
+ if (lang === 'typescript' || lang === 'javascript') {
+ // Static ESM imports & re-exports (supports multiline `{ \n a, \n b \n }`)
+ const esmRe = /\b(import|export)\s+(?:type\s+)?(?:([\s\S]{1,420}?)\s+from\s+)?['"]([^'"\n]+)['"]/gu;
+ let m;
+ while ((m = esmRe.exec(raw)) !== null) {
+ const kw = m[1];
+ const clause = (m[2] ?? '').trim();
+ const spec = m[3];
+ const importedNames = [];
+ const braceMatch = clause.match(/\{([^}]+)\}/u);
+ if (braceMatch) {
+ for (const tok of braceMatch[1].split(',')) {
+ const cleaned = tok.replace(/\btype\s+/u, '').trim();
+ if (!cleaned) continue;
+ const parts = cleaned.split(/\s+as\s+/u);
+ importedNames.push(parts[0].trim());
+ }
+ }
+ const defaultMatch = clause.replace(/\{[^}]*\}/u, '').replace(/,/gu, '').trim();
+ if (defaultMatch && !defaultMatch.startsWith('*') && /^[A-Za-z_$][\w$]*$/u.test(defaultMatch)) {
+ importedNames.push(defaultMatch);
+ }
+ addImport(spec, importedNames, kw === 'export' ? 'reexport' : 'import');
+ }
+ // CommonJS require('...') and dynamic import('...')
+ const dynRe = /\b(?:require|import)\s*\(\s*['"]([^'"\n]+)['"]\s*\)/gu;
+ while ((m = dynRe.exec(raw)) !== null) {
+ addImport(m[1], [], 'dynamic');
+ }
+ } else if (lang === 'python') {
+ // Strip comments/docstrings line-wise but keep real module strings? Python imports don't use quotes!
+ // So `clean` has exact bare `from a.b import c, d` and `import x.y` without comment/docstring false positives!
+ const fromParensRe = /^\s*from\s+(\.*[A-Za-z0-9_.]*)\s+import\s*\(([^)]*)\)/gmu;
+ let m;
+ while ((m = fromParensRe.exec(clean)) !== null) {
+ const mod = m[1];
+ const syms = m[2]
+ .split(',')
+ .map((s) => s.trim().split(/\s+as\s+/u)[0].trim())
+ .filter((s) => /^[A-Za-z_]\w*$/u.test(s));
+ addImport(mod, syms, 'from');
+ }
+ const fromLineRe = /^\s*from\s+(\.*[A-Za-z0-9_.]*)\s+import\s+([^\n(]+)/gmu;
+ while ((m = fromLineRe.exec(clean)) !== null) {
+ const mod = m[1];
+ const syms = m[2]
+ .split(',')
+ .map((s) => s.trim().split(/\s+as\s+/u)[0].trim())
+ .filter((s) => /^[A-Za-z_]\w*$/u.test(s));
+ addImport(mod, syms, 'from');
+ }
+ const impLineRe = /^\s*import\s+([A-Za-z0-9_.,\s]+)$/gmu;
+ while ((m = impLineRe.exec(clean)) !== null) {
+ for (const part of m[1].split(',')) {
+ const mod = part.trim().split(/\s+as\s+/u)[0].trim();
+ if (/^[A-Za-z_][A-Za-z0-9_.]*$/u.test(mod)) {
+ addImport(mod, [], 'import');
+ }
+ }
+ }
+ } else if (lang === 'go') {
+ const blockRe = /\bimport\s*\(([\s\S]*?)\)/gu;
+ let m;
+ while ((m = blockRe.exec(raw)) !== null) {
+ const strRe = /"([^"\n]+)"/gu;
+ let sm;
+ while ((sm = strRe.exec(m[1])) !== null) addImport(sm[1], [], 'import');
+ }
+ const singleRe = /^\s*import\s+(?:[A-Za-z0-9_.]+\s+)?"([^"\n]+)"/gmu;
+ while ((m = singleRe.exec(raw)) !== null) addImport(m[1], [], 'import');
+ } else if (lang === 'rust') {
+ const useRe = /^\s*(?:pub\s+)?use\s+([^;]+);/gmu;
+ let m;
+ while ((m = useRe.exec(clean)) !== null) {
+ addImport(m[1].replace(/\s+/gu, ''), [], 'use');
+ }
+ const modRe = /^\s*(?:pub\s+)?mod\s+([A-Za-z_]\w*)\s*;/gmu;
+ while ((m = modRe.exec(clean)) !== null) {
+ addImport(`mod::${m[1]}`, [m[1]], 'mod');
+ }
+ } else if (lang === 'c' || lang === 'cpp') {
+ const incRe = /^\s*#\s*include\s*[<"]([^>"]+)[>"]/gmu;
+ let m;
+ while ((m = incRe.exec(raw)) !== null) addImport(m[1], [], 'include');
+ } else if (lang === 'java' || lang === 'kotlin' || lang === 'csharp') {
+ const impRe = /^\s*(?:import|using)\s+(?:static\s+)?([A-Za-z0-9_.*]+)\s*;?/gmu;
+ let m;
+ while ((m = impRe.exec(clean)) !== null) addImport(m[1], [], 'import');
+ }
+
+ return results;
+}
+
+// ─── Python Indentation-Aware AST Extractor ─────────────────────────────────
+
+function extractPythonSymbols(rawLines, cleanLines) {
+ const symbols = [];
+ const scopeStack = []; // { name, kind, indent, symIndex }
+ let pendingDecorators = [];
+
+ for (let i = 0; i < cleanLines.length; i += 1) {
+ const cleanLine = cleanLines[i];
+ const trimmed = cleanLine.trim();
+ if (!trimmed) continue;
+
+ const indent = cleanLine.match(/^(\s*)/u)[1].replace(/\t/gu, ' ').length;
+
+ // Close any Python scopes whose indentation is >= current non-empty line
+ while (scopeStack.length > 0 && indent <= scopeStack[scopeStack.length - 1].indent) {
+ const closed = scopeStack.pop();
+ symbols[closed.symIndex].lineEnd = i; // previous 1-indexed line
+ }
+
+ // Decorator tracking
+ const decMatch = rawLines[i].match(/^\s*@([A-Za-z_][A-Za-z0-9_.]*)/u);
+ if (decMatch) {
+ pendingDecorators.push(decMatch[1]);
+ continue;
+ }
+
+ // Class definition
+ const classMatch = cleanLine.match(/^\s*class\s+([A-Za-z_]\w*)\s*(?:\(([^)]*)\))?\s*:/u);
+ if (classMatch) {
+ const name = classMatch[1];
+ const parent = findEnclosingClass(scopeStack);
+ const sig = collapseSignature(rawLines, i, 4, 130, cleanLines).replace(/:\s*$/u, '');
+ const symIndex = symbols.length;
+ symbols.push({
+ name,
+ kind: 'class',
+ signature: pendingDecorators.length > 0 ? `@${pendingDecorators[0]} ${sig}` : sig,
+ lineStart: i + 1,
+ lineEnd: rawLines.length,
+ parent,
+ exported: !name.startsWith('_'),
+ });
+ scopeStack.push({ name, kind: 'class', indent, symIndex });
+ pendingDecorators = [];
+ continue;
+ }
+
+ // Function or method definition
+ const defMatch = cleanLine.match(/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/u);
+ if (defMatch) {
+ const name = defMatch[1];
+ const enclosingClass = findEnclosingClass(scopeStack);
+ const enclosingFn = scopeStack.find((s) => s.kind === 'function' || s.kind === 'method');
+ // Skip deeply nested closure helpers unless top-level or direct class method
+ if (!enclosingFn) {
+ const kind = enclosingClass ? 'method' : 'function';
+ const sig = collapseSignature(rawLines, i, 6, 135, cleanLines).replace(/:\s*$/u, '');
+ const symIndex = symbols.length;
+ symbols.push({
+ name,
+ kind,
+ signature: sig,
+ lineStart: i + 1,
+ lineEnd: rawLines.length,
+ parent: enclosingClass,
+ exported: !name.startsWith('_') || name === '__init__' || name === '__call__',
+ });
+ scopeStack.push({ name, kind, indent, symIndex });
+ }
+ pendingDecorators = [];
+ continue;
+ }
+
+ pendingDecorators = [];
+
+ // Top-level exported constants / TypeAliases
+ if (indent === 0) {
+ const constMatch = cleanLine.match(/^([A-Z][A-Z0-9_]{2,})\s*(?::\s*[^=]+)?=/u);
+ if (constMatch) {
+ symbols.push({
+ name: constMatch[1],
+ kind: 'constant',
+ signature: rawLines[i].trim().slice(0, 100),
+ lineStart: i + 1,
+ lineEnd: i + 1,
+ parent: null,
+ exported: true,
+ });
+ }
+ }
+ }
+
+ return symbols;
+}
+
+function findEnclosingClass(scopeStack) {
+ for (let i = scopeStack.length - 1; i >= 0; i -= 1) {
+ if (scopeStack[i].kind === 'class' || scopeStack[i].kind === 'struct' || scopeStack[i].kind === 'interface' || scopeStack[i].kind === 'impl') {
+ return scopeStack[i].name;
+ }
+ }
+ return null;
+}
+
+// ─── Brace-Scoped Languages AST Extractor (TS/JS, Go, Rust, Java, C++) ──────
+
+const JS_CONTROL_KEYWORDS = new Set([
+ 'if', 'for', 'while', 'switch', 'catch', 'with', 'function', 'return', 'typeof', 'delete', 'await', 'import', 'super',
+]);
+
+function countParensDelta(line) {
+ let d = 0;
+ for (const ch of line) {
+ if (ch === '(') d += 1;
+ else if (ch === ')') d -= 1;
+ }
+ return d;
+}
+
+function extractBraceLangSymbols(rawLines, cleanLines, lang) {
+ const symbols = [];
+ const scopeStack = []; // { name, kind, closeDepth, symIndex }
+ let braceDepth = 0;
+ let pendingScope = null; // When `{` appears on the next line after class/fn header
+
+ for (let i = 0; i < cleanLines.length; i += 1) {
+ const cleanLine = cleanLines[i];
+ const trimmed = cleanLine.trim();
+ const { opens, closes, delta } = countBracesOnLine(cleanLine);
+ const depthAtLineStart = braceDepth;
+
+ // A multi-line signature can contain balanced braces before the body, e.g. a default
+ // `options: Opts = {},` — only an unmatched `{` (or one after the parameter list closes) starts the body.
+ if (pendingScope) pendingScope.paren += countParensDelta(cleanLine);
+ if (pendingScope && opens > 0 && opens === closes && pendingScope.paren <= 0 && /\}\s*;?\s*$/u.test(trimmed)) {
+ // `): void {}` — signature and empty body close on the same line
+ symbols[pendingScope.symIndex].lineEnd = i + 1;
+ pendingScope = null;
+ }
+ // Attach pending scope if `{` opens on this line
+ if (pendingScope && opens > closes) {
+ scopeStack.push({
+ name: pendingScope.name,
+ kind: pendingScope.kind,
+ closeDepth: depthAtLineStart,
+ symIndex: pendingScope.symIndex,
+ });
+ pendingScope = null;
+ } else if (pendingScope && trimmed && !trimmed.startsWith('//') && trimmed.endsWith(';')) {
+ symbols[pendingScope.symIndex].lineEnd = i + 1;
+ pendingScope = null;
+ }
+
+ if (trimmed) {
+ const enclosingContainer = findEnclosingClass(scopeStack);
+ const isTopOrContainerLevel =
+ depthAtLineStart === 0 ||
+ (scopeStack.length === 1 && ['class', 'interface', 'impl', 'namespace', 'struct', 'trait'].includes(scopeStack[0].kind));
+
+ if (isTopOrContainerLevel) {
+ const extracted = matchBraceLanguageDeclaration(
+ rawLines,
+ cleanLine,
+ i,
+ lang,
+ depthAtLineStart,
+ enclosingContainer,
+ );
+ if (extracted) {
+ const symIndex = symbols.length;
+ symbols.push({
+ ...extracted,
+ lineStart: i + 1,
+ lineEnd: i + 1,
+ });
+ if (opens > closes) {
+ scopeStack.push({
+ name: extracted.scopeName ?? extracted.name,
+ kind: extracted.kind,
+ closeDepth: depthAtLineStart,
+ symIndex,
+ });
+ } else if (opens === 0 && !trimmed.endsWith(';')) {
+ pendingScope = {
+ name: extracted.scopeName ?? extracted.name,
+ kind: extracted.kind,
+ symIndex,
+ paren: countParensDelta(cleanLine),
+ };
+ }
+ }
+ }
+ }
+
+ braceDepth = Math.max(0, braceDepth + delta);
+
+ // Pop completed brace scopes
+ while (scopeStack.length > 0 && braceDepth <= scopeStack[scopeStack.length - 1].closeDepth) {
+ const closed = scopeStack.pop();
+ symbols[closed.symIndex].lineEnd = i + 1;
+ }
+ }
+
+ // Close any unclosed scopes cleanly at EOF
+ while (scopeStack.length > 0) {
+ const closed = scopeStack.pop();
+ symbols[closed.symIndex].lineEnd = rawLines.length;
+ }
+
+ // Filter pure `impl` container wrappers from leaf display if methods inside were captured,
+ // unless the impl block itself is a trait implementation worth showing
+ return symbols.filter((s) => !(s.kind === 'impl' && !s.isTraitImpl));
+}
+
+function matchBraceLanguageDeclaration(rawLines, cleanLine, idx, lang, depth, enclosingContainer) {
+ if (lang === 'typescript' || lang === 'javascript') {
+ const exported = /^\s*export\b/u.test(cleanLine);
+
+ // class / interface / enum / namespace
+ const containerMatch = cleanLine.match(
+ /^\s*(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(class|interface|enum|namespace)\s+([A-Za-z_$][\w$]*)/u,
+ );
+ if (containerMatch) {
+ return {
+ name: containerMatch[2],
+ kind: containerMatch[1],
+ signature: collapseSignature(rawLines, idx, 3, 130),
+ parent: enclosingContainer,
+ exported: exported || depth === 0,
+ };
+ }
+
+ // type alias
+ const typeMatch = cleanLine.match(
+ /^\s*(?:export\s+)?(?:declare\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*=/u,
+ );
+ if (typeMatch) {
+ return {
+ name: typeMatch[1],
+ kind: 'type',
+ signature: collapseSignature(rawLines, idx, 2, 120),
+ parent: enclosingContainer,
+ exported,
+ };
+ }
+
+ // Standard function declaration
+ const fnMatch = cleanLine.match(
+ /^\s*(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*[<(]/u,
+ );
+ if (fnMatch) {
+ return {
+ name: fnMatch[1],
+ kind: 'function',
+ signature: collapseSignature(rawLines, idx, 5, 135),
+ parent: enclosingContainer,
+ exported,
+ };
+ }
+
+ // Arrow function or function expression assigned to const/let: `export const foo = async (...) =>`
+ if (depth === 0) {
+ const arrowMatch = cleanLine.match(
+ /^\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?=>/u,
+ );
+ if (arrowMatch) {
+ return {
+ name: arrowMatch[1],
+ kind: 'function',
+ signature: collapseSignature(rawLines, idx, 3, 135).replace(/\s*=>.*$/u, ' => ...'),
+ parent: null,
+ exported,
+ };
+ }
+ // Multi-line arrow or wrapped HOC/memo/defineTool (`export const FooDef = {` or `export const X = memo((...) =>`)
+ const exportedConstObj = cleanLine.match(
+ /^\s*export\s+const\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?=/u,
+ );
+ if (exportedConstObj) {
+ return {
+ name: exportedConstObj[1],
+ kind: 'constant',
+ signature: collapseSignature(rawLines, idx, 2, 120),
+ parent: null,
+ exported: true,
+ };
+ }
+ }
+
+ // Class / Interface methods
+ if (enclosingContainer && depth > 0) {
+ const methodMatch = cleanLine.match(
+ /^\s*(?:(?:public|private|protected|static|readonly|abstract|override|async|get|set)\s+)*(#?[A-Za-z_$][\w$]*)\s*\??\s*(?:<[^>]{1,80}>)?\s*\(/u,
+ );
+ if (methodMatch && !JS_CONTROL_KEYWORDS.has(methodMatch[1])) {
+ const name = methodMatch[1];
+ const isPrivate = name.startsWith('#') || /^\s*private\b/u.test(cleanLine);
+ return {
+ name,
+ kind: 'method',
+ signature: collapseSignature(rawLines, idx, 4, 130),
+ parent: enclosingContainer,
+ exported: !isPrivate,
+ };
+ }
+ }
+ return null;
+ }
+
+ if (lang === 'go') {
+ const typeMatch = cleanLine.match(/^\s*type\s+([A-Za-z_]\w*)\s+(struct|interface)\b/u);
+ if (typeMatch) {
+ return {
+ name: typeMatch[1],
+ kind: typeMatch[2],
+ signature: collapseSignature(rawLines, idx, 2, 120),
+ parent: null,
+ exported: /^[A-Z]/u.test(typeMatch[1]),
+ };
+ }
+ const methodMatch = cleanLine.match(/^\s*func\s*\(\s*(?:\w+\s+)?\*?([A-Za-z_]\w*)(?:\[[^\]]+\])?\s*\)\s*([A-Za-z_]\w*)\s*[([[]/u);
+ if (methodMatch) {
+ return {
+ name: methodMatch[2],
+ kind: 'method',
+ signature: collapseSignature(rawLines, idx, 4, 135),
+ parent: methodMatch[1],
+ exported: /^[A-Z]/u.test(methodMatch[2]),
+ };
+ }
+ const fnMatch = cleanLine.match(/^\s*func\s+([A-Za-z_]\w*)\s*[([[]/u);
+ if (fnMatch) {
+ return {
+ name: fnMatch[1],
+ kind: 'function',
+ signature: collapseSignature(rawLines, idx, 4, 135),
+ parent: null,
+ exported: /^[A-Z]/u.test(fnMatch[1]) || fnMatch[1] === 'main',
+ };
+ }
+ return null;
+ }
+
+ if (lang === 'rust') {
+ const pub = /^\s*pub\b/u.test(cleanLine);
+ const typeMatch = cleanLine.match(/^\s*(?:pub(?:\([^)]*\))?\s+)?(struct|enum|trait|mod)\s+([A-Za-z_]\w*)/u);
+ if (typeMatch) {
+ // External `pub mod weights;` is already captured as a module import edge, not an inline container
+ if (typeMatch[1] === 'mod' && cleanLine.trim().endsWith(';')) {
+ return null;
+ }
+ return {
+ name: typeMatch[2],
+ kind: typeMatch[1],
+ signature: collapseSignature(rawLines, idx, 3, 125),
+ parent: enclosingContainer,
+ exported: pub,
+ };
+ }
+ const implMatch = cleanLine.match(
+ /^\s*(?:unsafe\s+)?impl(?:\s*<[^>]*>)?\s+(?:([A-Za-z_][\w:]*)\s+for\s+)?([A-Za-z_]\w*)/u,
+ );
+ if (implMatch) {
+ const traitName = implMatch[1] ?? null;
+ const targetType = implMatch[2];
+ return {
+ name: traitName ? `impl ${traitName} for ${targetType}` : targetType,
+ scopeName: targetType,
+ kind: 'impl',
+ isTraitImpl: Boolean(traitName),
+ signature: collapseSignature(rawLines, idx, 2, 125),
+ parent: null,
+ exported: true,
+ };
+ }
+ const fnMatch = cleanLine.match(
+ /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)\s*[<(]/u,
+ );
+ if (fnMatch) {
+ return {
+ name: fnMatch[1],
+ kind: enclosingContainer ? 'method' : 'function',
+ signature: collapseSignature(rawLines, idx, 4, 135),
+ parent: enclosingContainer,
+ exported: pub || Boolean(enclosingContainer),
+ };
+ }
+ return null;
+ }
+
+ // Java / Kotlin / C / C++ / C# / Swift / PHP
+ const clsMatch = cleanLine.match(
+ /^\s*(?:(?:public|private|protected|internal|open|abstract|final|sealed|data|static|export)\s+)*(class|interface|struct|enum|record|namespace|protocol|actor)\s+([A-Za-z_]\w*)/u,
+ );
+ if (clsMatch) {
+ return {
+ name: clsMatch[2],
+ kind: clsMatch[1],
+ signature: collapseSignature(rawLines, idx, 3, 130),
+ parent: enclosingContainer,
+ exported: !/^\s*private\b/u.test(cleanLine),
+ };
+ }
+ const cFnMatch = cleanLine.match(
+ /^\s*(?:(?:public|private|protected|static|virtual|inline|constexpr|async|override|fun|func|function)\s+)*(?:[A-Za-z_][\w:<>,*\s&]{0,48}\s+)?([A-Za-z_]\w*)\s*\([^;]*$/u,
+ );
+ if (cFnMatch && !JS_CONTROL_KEYWORDS.has(cFnMatch[1])) {
+ return {
+ name: cFnMatch[1],
+ kind: enclosingContainer ? 'method' : 'function',
+ signature: collapseSignature(rawLines, idx, 4, 130),
+ parent: enclosingContainer,
+ exported: !/^\s*private\b/u.test(cleanLine),
+ };
+ }
+ return null;
+}
+
+// ─── Reference & Symbol-Level Call Extraction ───────────────────────────────
+
+function extractReferences(cleanLines, symbols) {
+ const fileRefs = Object.create(null);
+ const symbolCalls = new Map();
+
+ // Build line -> innermost symbol index lookup
+ const lineToSym = new Int32Array(cleanLines.length).fill(-1);
+ for (let idx = 0; idx < symbols.length; idx += 1) {
+ const s = symbols[idx];
+ const start = Math.max(0, s.lineStart - 1);
+ const end = Math.min(cleanLines.length - 1, s.lineEnd - 1);
+ for (let ln = start; ln <= end; ln += 1) {
+ // Innermost (later, narrower) symbol wins over enclosing class
+ lineToSym[ln] = idx;
+ }
+ }
+
+ const identRe = /[A-Za-z_$][A-Za-z0-9_$]{2,}/gu;
+ for (let ln = 0; ln < cleanLines.length; ln += 1) {
+ const line = cleanLines[ln];
+ const ownerSymIdx = lineToSym[ln];
+ let m;
+ identRe.lastIndex = 0;
+ while ((m = identRe.exec(line)) !== null) {
+ const tok = m[0];
+ if (COMMON_STOP_WORDS.has(tok)) continue;
+ fileRefs[tok] = (fileRefs[tok] ?? 0) + 1;
+
+ if (ownerSymIdx >= 0) {
+ const owner = symbols[ownerSymIdx];
+ if (tok !== owner.name && !GENERIC_METHOD_NOISE.has(tok)) {
+ let map = symbolCalls.get(ownerSymIdx);
+ if (!map) {
+ map = new Map();
+ symbolCalls.set(ownerSymIdx, map);
+ }
+ map.set(tok, (map.get(tok) ?? 0) + 1);
+ }
+ }
+ }
+ }
+
+ return { fileRefs, symbolCalls };
+}
+
+export function isNoisySymbolName(name) {
+ return name.length < 3 || COMMON_STOP_WORDS.has(name) || GENERIC_METHOD_NOISE.has(name);
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/server/planner.mjs b/plugins/Jialei-03/mcode-repowiki/server/planner.mjs
new file mode 100644
index 00000000..0725159f
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/planner.mjs
@@ -0,0 +1,558 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+
+function slugify(input) {
+ return (
+ String(input)
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/gu, '-')
+ .replace(/^-+|-+$/gu, '')
+ .slice(0, 48) || 'module'
+ );
+}
+
+function humanizeModuleTitle(key, workspaceMeta) {
+ if (key === '(root)' || key === 'root') return '根目录';
+ // Check if a monorepo package lives at exact `dir === key`
+ const matchedPkg = (workspaceMeta?.packages ?? []).find((p) => p.dir === key);
+ if (matchedPkg?.name) {
+ // Strip npm scope like `@earendil-works/pi-agent-core` -> `pi-agent-core` (keep readable!)
+ const shortPkg = matchedPkg.name.replace(/^@[^/]+\//u, '');
+ return shortPkg; // the path is shown under the title; keep the title itself a plain name
+ }
+ return key;
+}
+
+/**
+ * Partition repository files into 3..9 cohesive, human-meaningful architectural modules.
+ * Scores modules by Top-K Hub Centrality + Cross-Module Fan-In (preventing 200-file leaf folders
+ * from drowning out concise 15-file core packages like `packages/agent`!).
+ */
+export const DEFAULT_MAX_MODULES = 10;
+
+export function partitionIntoModules(index, ranks, maxModules = DEFAULT_MAX_MODULES) {
+ const prodFiles = [];
+ for (let i = 0; i < index.files.length; i += 1) {
+ const rel = index.files[i].relPath;
+ if (index.files[i].isTest) continue;
+ // Exclude example/demo sandboxes from dominating core module clustering
+ if (rel.includes('/examples/') || rel.startsWith('examples/')) continue;
+ prodFiles.push(i);
+ }
+ const activeIndices = prodFiles.length > 0 ? prodFiles : index.files.map((_, i) => i);
+
+ const coarseKey = (relPath) => {
+ const parts = relPath.split('/');
+ if (['packages', 'apps', 'crates', 'services', 'libs', 'modules', 'plugins'].includes(parts[0])) {
+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
+ }
+ if (['src', 'lib', 'internal', 'pkg'].includes(parts[0])) {
+ return parts.length >= 3 ? `${parts[0]}/${parts[1]}` : parts[0];
+ }
+ return parts.length >= 2 ? parts[0] : 'root';
+ };
+
+ const groups = new Map();
+ for (const idx of activeIndices) {
+ const k = coarseKey(index.files[idx].relPath);
+ if (!groups.has(k)) groups.set(k, []);
+ groups.get(k).push(idx);
+ }
+
+ // Sub-cluster if a single folder holds >72% of all production files
+ const largestEntry = [...groups.entries()].sort((a, b) => b[1].length - a[1].length)[0];
+ if (largestEntry && largestEntry[1].length >= Math.max(5, Math.ceil(activeIndices.length * 0.72))) {
+ const [dominantKey, domFiles] = largestEntry;
+ const subGroups = new Map();
+ for (const idx of domFiles) {
+ const f = index.files[idx];
+ const rel = f.relPath;
+ const afterPrefix = dominantKey === 'root' ? rel : rel.slice(dominantKey.length + 1);
+ const segs = afterPrefix.split('/');
+ const subKey =
+ segs.length >= 2
+ ? dominantKey === 'root'
+ ? segs[0]
+ : `${dominantKey}/${segs[0]}`
+ : domFiles.length <= 10
+ ? rel
+ : `${dominantKey} (${f.role})`;
+ if (!subGroups.has(subKey)) subGroups.set(subKey, []);
+ subGroups.get(subKey).push(idx);
+ }
+ if (subGroups.size >= 2) {
+ groups.delete(dominantKey);
+ for (const [sk, sFiles] of subGroups.entries()) groups.set(sk, sFiles);
+ }
+ }
+
+ // First pass: map file -> initial group to measure cross-group afferent coupling (who is depended on!)
+ const groupKeys = [...groups.keys()];
+ const fileToRawGroup = new Int32Array(index.files.length).fill(-1);
+ groupKeys.forEach((gk, gIdx) => {
+ for (const fIdx of groups.get(gk)) fileToRawGroup[fIdx] = gIdx;
+ });
+
+ const rawCrossIn = new Int32Array(groupKeys.length);
+ const rawDistinctCallers = Array.from({ length: groupKeys.length }, () => new Set());
+ for (let u = 0; u < index.files.length; u += 1) {
+ const gu = fileToRawGroup[u];
+ if (gu === -1) continue;
+ for (const v of index.importAdj[u]) {
+ const gv = fileToRawGroup[v];
+ if (gv !== -1 && gv !== gu) {
+ rawCrossIn[gv] += 1;
+ rawDistinctCallers[gv].add(gu);
+ }
+ }
+ }
+
+ let rawList = groupKeys.map((key, gIdx) => {
+ const fileIdxs = groups.get(key);
+ const fileRanks = fileIdxs.map((i) => ranks[i] ?? 0).sort((a, b) => b - a);
+ const rankSum = fileRanks.reduce((a, b) => a + b, 0);
+ // Max-hub + Top-3 hub score prevents 200-file folders from drowning out a razor-sharp 6-file core package!
+ const peakRank = fileRanks[0] ?? 0;
+ const top3Rank = fileRanks.slice(0, 3).reduce((a, b) => a + b, 0);
+ const callerPkgCount = rawDistinctCallers[gIdx].size;
+ const architecturalScore =
+ (peakRank * 2.2 + top3Rank) * (1 + 0.55 * callerPkgCount + 0.2 * Math.log1p(rawCrossIn[gIdx])) +
+ rankSum * 0.15;
+
+ let lineSum = 0;
+ let symSum = 0;
+ for (const i of fileIdxs) {
+ lineSum += index.parsedFiles[i].lineCount;
+ symSum += index.parsedFiles[i].symbols.length;
+ }
+ return { key, fileIdxs, rankSum, architecturalScore, lineSum, symSum };
+ });
+
+ rawList.sort((a, b) => b.architecturalScore - a.architecturalScore || b.lineSum - a.lineSum);
+
+ if (rawList.length > maxModules) {
+ // The dependency score favours low-level packages everything imports; big product packages
+ // (CLIs, apps) are imported by nothing and would sink. Any package holding >= 10% of the
+ // code always gets its own chapter, and the "other" bucket does not use up a module slot.
+ const totalLines = rawList.reduce((s, m) => s + m.lineSum, 0) || 1;
+ const isBig = (m) => m.lineSum / totalLines >= 0.1;
+ const head = rawList.slice(0, maxModules);
+ for (const m of rawList.slice(maxModules)) if (isBig(m)) head.push(m);
+ const headSet = new Set(head);
+ const tail = rawList.filter((m) => !headSet.has(m));
+ rawList = [
+ ...head,
+ {
+ key: 'supporting-modules',
+ titleOverride: '其他包',
+ fileIdxs: tail.flatMap((t) => t.fileIdxs),
+ rankSum: tail.reduce((s, t) => s + t.rankSum, 0),
+ architecturalScore: 0,
+ lineSum: tail.reduce((s, t) => s + t.lineSum, 0),
+ symSum: tail.reduce((s, t) => s + t.symSum, 0),
+ },
+ ];
+ }
+
+ const fileToMod = new Int32Array(index.files.length).fill(-1);
+ rawList.forEach((m, mIdx) => {
+ for (const fIdx of m.fileIdxs) fileToMod[fIdx] = mIdx;
+ });
+
+ const modules = rawList.map((m, mIdx) => {
+ const padNum = String(mIdx + 1).padStart(2, '0');
+ const cleanSlug = slugify(m.key.replace(/^(packages|apps|crates|services|src)\//u, '').replace(/\.[^/.]+$/u, ''));
+ const moduleId = `${padNum}-${cleanSlug}`;
+ const sortedFiles = [...m.fileIdxs].sort((a, b) => (ranks[b] ?? 0) - (ranks[a] ?? 0));
+
+ const upstreamMods = new Map();
+ const downstreamMods = new Map();
+
+ for (const u of m.fileIdxs) {
+ for (const v of index.importAdj[u]) {
+ const mv = fileToMod[v];
+ if (mv !== -1 && mv !== mIdx) downstreamMods.set(mv, (downstreamMods.get(mv) ?? 0) + 1);
+ }
+ for (const caller of index.reverseImportAdj[u]) {
+ const mc = fileToMod[caller];
+ if (mc !== -1 && mc !== mIdx) upstreamMods.set(mc, (upstreamMods.get(mc) ?? 0) + 1);
+ }
+ }
+
+ const fanIn = [...upstreamMods.values()].reduce((a, b) => a + b, 0);
+ const fanOut = [...downstreamMods.values()].reduce((a, b) => a + b, 0);
+ const instability = fanIn + fanOut === 0 ? 0 : +(fanOut / (fanIn + fanOut)).toFixed(2);
+
+ let layerKind = 'Domain Core';
+ if (fanIn === 0 && fanOut > 0) layerKind = 'Entrypoint / Application Layer';
+ else if (instability <= 0.3 && fanIn >= 2) layerKind = 'Foundation / Contract Layer';
+ else if (fanIn >= 1 && fanOut >= 1) layerKind = 'Orchestration / Runtime Layer';
+
+ return {
+ index: mIdx,
+ id: moduleId,
+ key: m.key,
+ title: m.titleOverride || humanizeModuleTitle(m.key, index.workspaceMeta),
+ docPath: `02-modules/${moduleId}.md`,
+ layerKind,
+ fileCount: m.fileIdxs.length,
+ lineCount: m.lineSum,
+ symbolCount: m.symSum,
+ pageRankPct: +(m.rankSum * 100).toFixed(1),
+ fanIn,
+ fanOut,
+ instability,
+ topFiles: sortedFiles.slice(0, 12).map((idx) => index.files[idx].relPath),
+ allFiles: sortedFiles.map((idx) => index.files[idx].relPath),
+ _upstreamMods: upstreamMods,
+ _downstreamMods: downstreamMods,
+ };
+ });
+
+ for (const mod of modules) {
+ mod.dependsOnModules = [...mod._downstreamMods.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([idx, count]) => ({ id: modules[idx].id, title: modules[idx].title, edges: count }));
+ mod.dependedByModules = [...mod._upstreamMods.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map(([idx, count]) => ({ id: modules[idx].id, title: modules[idx].title, edges: count }));
+ delete mod._upstreamMods;
+ delete mod._downstreamMods;
+ }
+
+ return modules;
+}
+
+export function buildArchitectureMermaid(modules) {
+ const lines = ['flowchart TD'];
+ const nodeIds = modules.map((_, idx) => `M${idx}`);
+
+ const surface = [];
+ const middle = [];
+ const foundation = [];
+
+ modules.forEach((m, idx) => {
+ const shortTitle = m.title.replace(/\s*\([^)]*\)\s*$/u, '').replace(/"/gu, "'");
+ const decl = `${nodeIds[idx]}["${shortTitle}"]`;
+ if (m.layerKind.startsWith('Entrypoint')) surface.push(decl);
+ else if (m.layerKind.startsWith('Foundation')) foundation.push(decl);
+ else middle.push(decl);
+ });
+
+ if (surface.length > 0) {
+ lines.push(' subgraph Entry["Application & Entry Surfaces"]');
+ for (const d of surface) lines.push(` ${d}`);
+ lines.push(' end');
+ }
+ if (middle.length > 0) {
+ lines.push(' subgraph Core["Runtime & Agent Orchestration"]');
+ for (const d of middle) lines.push(` ${d}`);
+ lines.push(' end');
+ }
+ if (foundation.length > 0) {
+ lines.push(' subgraph Base["Foundation SDKs & Primitives"]');
+ for (const d of foundation) lines.push(` ${d}`);
+ lines.push(' end');
+ }
+
+ const idToIdx = new Map(modules.map((m, idx) => [m.id, idx]));
+ let edgeCount = 0;
+ for (let i = 0; i < modules.length; i += 1) {
+ for (const dep of modules[i].dependsOnModules.slice(0, 4)) {
+ const j = idToIdx.get(dep.id);
+ if (j !== undefined) {
+ lines.push(` ${nodeIds[i]} -->|"${dep.edges} 处引用"| ${nodeIds[j]}`);
+ edgeCount += 1;
+ }
+ }
+ }
+
+ if (edgeCount === 0 && modules.length >= 2) {
+ for (let i = 0; i + 1 < Math.min(4, modules.length); i += 1) {
+ lines.push(` ${nodeIds[i]} -.-> ${nodeIds[i + 1]}`);
+ }
+ }
+
+ return lines.join('\n');
+}
+
+export function createWikiBlueprint(index, arch, pprResult, options = {}) {
+ const maxModules = Math.max(2, Math.min(10, options.maxModules ?? DEFAULT_MAX_MODULES));
+ const modules = partitionIntoModules(index, pprResult.ranks, maxModules);
+ const archMermaid = buildArchitectureMermaid(modules);
+
+ let rootReadmePreview = '';
+ for (const candidate of ['README.zh-CN.md', 'README.md', 'AGENTS.md']) {
+ const abs = path.join(index.repoRoot, candidate);
+ if (existsSync(abs)) {
+ try {
+ rootReadmePreview = readFileSync(abs, 'utf8').slice(0, 2400).trim();
+ break;
+ } catch {
+ // Ignore unreadable file
+ }
+ }
+ }
+
+ const pages = [
+ {
+ level: 1,
+ section: 'Overview',
+ docPath: 'README.md',
+ title: '项目概览',
+ purpose:
+ 'Overview: what the repository is, mental model (layers), module map table linking every module chapter, "where to change what" task table with entry-file citations, glossary of project terms, reading route.',
+ sourceFiles: arch.entrypoints.slice(0, 4).map((e) => e.relPath),
+ },
+ {
+ level: 2,
+ section: 'Architecture',
+ docPath: '01-architecture/01-system-overview.md',
+ title: '整体架构',
+ purpose:
+ 'Layers and subsystem boundaries, the main design decisions and why, one flowchart TD of the system; cite the files that define each boundary.',
+ sourceFiles: arch.topHubs.slice(0, 6).map((h) => h.relPath),
+ },
+ {
+ level: 2,
+ section: 'Architecture',
+ docPath: '01-architecture/02-core-workflows.md',
+ title: '核心流程',
+ purpose:
+ 'The 2-3 main runtime flows end to end, each as a sequenceDiagram plus a numbered list where every step names and cites the function that runs.',
+ sourceFiles: [
+ ...arch.entrypoints.slice(0, 3).map((e) => e.relPath),
+ ...arch.topHubs.slice(0, 4).map((h) => h.relPath),
+ ],
+ },
+ {
+ level: 2,
+ section: 'Architecture',
+ docPath: '01-architecture/03-dependencies-and-boundaries.md',
+ title: '模块依赖',
+ purpose:
+ 'Inter-module coupling metrics (Fan-In, Fan-Out, Instability I), package dependency rules, and circular dependency audit.',
+ sourceFiles: arch.cycles.flatMap((c) => c.witnessCycle.slice(0, 3)).slice(0, 6),
+ },
+ ...modules.map((m) => ({
+ level: 3,
+ section: 'Core Modules',
+ moduleId: m.id,
+ docPath: m.docPath,
+ title: m.title,
+ purpose: `Module chapter for ${m.key} (${m.layerKind}). Six sections: what it does · where it sits · core concepts · one call step by step (cite every step) · how to change it (recipes, invariants, tests) · key files.`,
+ sourceFiles: m.topFiles.slice(0, 6),
+ })),
+ {
+ level: 4,
+ section: 'Developer Guides',
+ docPath: '03-guides/01-getting-started.md',
+ title: '快速上手',
+ purpose:
+ 'Getting started: prerequisites, install/build/test/run commands copied from the repo scripts, configuration, where logs and common errors show up.',
+ sourceFiles: index.workspaceMeta.packages.slice(0, 4).map((p) => p.manifest),
+ },
+ {
+ level: 4,
+ section: 'Developer Guides',
+ docPath: '03-guides/02-extension-playbook.md',
+ title: '扩展开发',
+ purpose:
+ 'Recipes for the most common changes (which files, in which order, with citations) and the checks/tests to run afterwards.',
+ sourceFiles: arch.topHubs.slice(0, 5).map((h) => h.relPath),
+ },
+ ];
+
+ return {
+ repoName: index.repoName,
+ repoRoot: index.repoRoot,
+ stats: index.stats,
+ languageCounts: index.languageCounts,
+ workspaceMeta: index.workspaceMeta,
+ entrypoints: arch.entrypoints,
+ topHubs: arch.topHubs,
+ cycles: arch.cycles,
+ modules,
+ architectureMermaid: archMermaid,
+ pages,
+ rootReadmePreview,
+ };
+}
+
+export function extractModuleEvidencePack(index, pprResult, blueprint, targetId, options = {}) {
+ const maxExcerptChars = Math.max(3000, Math.min(36000, options.maxExcerptChars ?? 15000));
+ const ranks = pprResult.ranks;
+
+ const q = String(targetId).trim().toLowerCase();
+ let mod = blueprint.modules.find(
+ (m) =>
+ m.id.toLowerCase() === q ||
+ m.key.toLowerCase() === q ||
+ slugify(m.key) === q ||
+ m.docPath.toLowerCase() === q ||
+ m.id.toLowerCase().includes(q) ||
+ m.key.toLowerCase().includes(q) ||
+ slugify(m.key).includes(q),
+ );
+
+ if (!mod && (q.includes('arch') || q.includes('overview') || q.includes('workflow') || q.includes('guide'))) {
+ const keyFiles = [
+ ...blueprint.entrypoints.slice(0, 3).map((e) => e.relPath),
+ ...blueprint.topHubs.slice(0, 6).map((h) => h.relPath),
+ ];
+ const uniqueFiles = [...new Set(keyFiles)];
+ mod = {
+ id: 'architecture-core',
+ key: 'architecture-core',
+ title: 'System Architecture & Core Lifecycle',
+ docPath: '01-architecture/01-system-overview.md',
+ layerKind: 'Cross-Cutting System View',
+ fileCount: uniqueFiles.length,
+ lineCount: 0,
+ symbolCount: 0,
+ pageRankPct: 100,
+ dependsOnModules: [],
+ dependedByModules: [],
+ topFiles: uniqueFiles,
+ allFiles: uniqueFiles,
+ };
+ }
+
+ if (!mod) {
+ throw new Error(
+ `Unknown module "${targetId}". Available module IDs: ${blueprint.modules.map((m) => m.id).join(', ')}`,
+ );
+ }
+
+ const lines = [];
+ lines.push(`# Grounded Evidence Pack: ${mod.title} (\`${mod.id}\`)`);
+ lines.push(`- **Target Wiki Page**: \`${mod.docPath}\``);
+ lines.push(`- **Architectural Layer**: ${mod.layerKind} (PageRank Share: ${mod.pageRankPct}%)`);
+ lines.push(`- **Scope**: ${mod.fileCount} files`);
+
+ if (mod.dependedByModules.length > 0) {
+ lines.push(
+ `- **Upstream Callers (Who depends on this module)**: ${mod.dependedByModules.map((u) => `\`${u.title}\` (${u.edges} imports)`).join(', ')}`,
+ );
+ }
+ if (mod.dependsOnModules.length > 0) {
+ lines.push(
+ `- **Downstream Dependencies (What this module imports)**: ${mod.dependsOnModules.map((d) => `\`${d.title}\` (${d.edges} imports)`).join(', ')}`,
+ );
+ }
+ lines.push('');
+
+ lines.push('## Verified Module Relationship Diagram (Mermaid)');
+ lines.push('```mermaid');
+ lines.push('flowchart LR');
+ const topFileSet = new Set(mod.topFiles.slice(0, 7));
+ const fIdMap = new Map();
+ mod.topFiles.slice(0, 7).forEach((fp, idx) => {
+ fIdMap.set(fp, `F${idx}`);
+ lines.push(` F${idx}["${path.posix.basename(fp)}"]`);
+ });
+ let intraEdges = 0;
+ for (const fp of mod.topFiles.slice(0, 7)) {
+ const u = index.pathToIdx.get(fp);
+ if (u === undefined) continue;
+ for (const v of index.importAdj[u]) {
+ const targetFp = index.files[v].relPath;
+ if (topFileSet.has(targetFp)) {
+ lines.push(` ${fIdMap.get(fp)} --> ${fIdMap.get(targetFp)}`);
+ intraEdges += 1;
+ }
+ }
+ }
+ if (intraEdges === 0 && mod.dependsOnModules.length > 0) {
+ mod.dependsOnModules.slice(0, 3).forEach((d, idx) => {
+ const shortDep = d.title.replace(/\s*\([^)]*\)\s*$/u, '').replace(/"/gu, "'");
+ lines.push(` F0 --> EXT${idx}["${shortDep}"]`);
+ });
+ }
+ lines.push('```');
+ lines.push('');
+
+ lines.push('## Complete AST Symbol Inventory (Use These Exact `[path:Lstart-Lend]` Citations!)');
+ for (const fp of mod.topFiles.slice(0, 10)) {
+ const fIdx = index.pathToIdx.get(fp);
+ if (fIdx === undefined) continue;
+ const pf = index.parsedFiles[fIdx];
+ const rPct = ((ranks[fIdx] ?? 0) * 100).toFixed(2);
+ lines.push(`### \`${fp}\` (${pf.lineCount} lines, PageRank ${rPct}%)`);
+ if (pf.symbols.length === 0) {
+ lines.push('- _(Module without top-level class/function declarations)_');
+ } else {
+ for (const s of pf.symbols.slice(0, 26)) {
+ const span = `L${s.lineStart}-L${s.lineEnd}`;
+ const prefix = s.parent ? ' - ' : '- ';
+ const callHint = s.calls?.length > 0 ? ` → calls: \`${s.calls.slice(0, 5).join('`, `')}\`` : '';
+ lines.push(`${prefix}\`${s.signature}\` — cite as \`[${path.posix.basename(fp)}:${span}](${fp}#${span})\`${callHint}`);
+ }
+ }
+ lines.push('');
+ }
+
+ lines.push('## Grounded Source Code Excerpts (Line-Numbered)');
+ let remainingChars = maxExcerptChars;
+ for (const fp of mod.topFiles.slice(0, 6)) {
+ if (remainingChars < 600) break;
+ const fIdx = index.pathToIdx.get(fp);
+ if (fIdx === undefined) continue;
+ const fMeta = index.files[fIdx];
+ const pf = index.parsedFiles[fIdx];
+ let raw;
+ try {
+ raw = readFileSync(fMeta.absPath, 'utf8').replace(/\r\n/gu, '\n');
+ } catch {
+ continue;
+ }
+ const rawLines = raw.split('\n');
+ const perFileCap = Math.min(
+ remainingChars,
+ Math.max(1800, Math.floor(maxExcerptChars / Math.min(4, mod.topFiles.length || 1))),
+ );
+
+ const selectedWindows = [[1, Math.min(rawLines.length, 40)]];
+ for (const sym of pf.symbols.slice(0, 5)) {
+ selectedWindows.push([sym.lineStart, Math.min(sym.lineEnd, sym.lineStart + 45)]);
+ }
+ const mergedWindows = mergeLineWindows(selectedWindows);
+
+ let snippet = `### Excerpt: \`${fp}\`\n\`\`\`${fMeta.lang}\n`;
+ for (const [wStart, wEnd] of mergedWindows) {
+ for (let ln = wStart; ln <= wEnd; ln += 1) {
+ const lineStr = `${String(ln).padStart(4, ' ')} | ${rawLines[ln - 1] ?? ''}\n`;
+ if (snippet.length + lineStr.length > perFileCap) break;
+ snippet += lineStr;
+ }
+ if (snippet.length >= perFileCap) break;
+ if (wEnd < rawLines.length) snippet += ' ... |\n';
+ }
+ snippet += '```\n\n';
+ lines.push(snippet);
+ remainingChars -= snippet.length;
+ }
+
+ // Said here as well as in the blueprint: agents often ask for an evidence pack directly.
+ lines.push('## How to save this chapter');
+ lines.push(
+ `Save \`${mod.docPath}\` with \`wiki_write_page\`, not a plain file write: it checks every citation against the code, records the anchors that keep line numbers and freshness checks working after the code changes, and returns writing checks to fix. Use the chapter structure from the \`mcode-repowiki\` skill.`,
+ );
+ return lines.join('\n');
+}
+
+function mergeLineWindows(windows) {
+ if (windows.length === 0) return [];
+ const sorted = [...windows].sort((a, b) => a[0] - b[0]);
+ const out = [sorted[0].slice()];
+ for (let i = 1; i < sorted.length; i += 1) {
+ const prev = out[out.length - 1];
+ const cur = sorted[i];
+ if (cur[0] <= prev[1] + 5) {
+ prev[1] = Math.max(prev[1], cur[1]);
+ } else {
+ out.push(cur.slice());
+ }
+ }
+ return out;
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/server/portal-client.js b/plugins/Jialei-03/mcode-repowiki/server/portal-client.js
new file mode 100644
index 00000000..e6d71d88
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/portal-client.js
@@ -0,0 +1,2255 @@
+(() => {
+ // ─── Precision 1.6px Stroke Geometric Vector Icon System (Zero Emoji) ───
+ const ICON_PATHS = {
+ prism:
+ '',
+ book:
+ '',
+ network:
+ '',
+ activity:
+ '',
+ search:
+ '',
+ sun:
+ '',
+ moon:
+ '',
+ sidebar:
+ '',
+ fileCode:
+ '',
+ fileText:
+ '',
+ arrowUpRight:
+ '',
+ chevronLeft:
+ '',
+ chevronRight:
+ '',
+ copy:
+ '',
+ check:
+ '',
+ refresh:
+ '',
+ plus:
+ '',
+ minus:
+ '',
+ maximize:
+ '',
+ minimize:
+ '',
+ close:
+ '',
+ info:
+ '',
+ layers:
+ '',
+ terminal:
+ '',
+ alert:
+ '',
+ gitCommit:
+ '',
+ clock:
+ '',
+ code:
+ '',
+ folder:
+ '',
+ listTree:
+ '',
+ checkCircle:
+ '',
+ };
+
+ function icon(name, size = 14) {
+ const body = ICON_PATHS[name] || ICON_PATHS.info;
+ return (
+ ''
+ );
+ }
+
+ function esc(s) {
+ return String(s)
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"');
+ }
+
+ function cleanPlainTitle(raw) {
+ return String(raw || '')
+ .replace(/`([^`]+)`/g, '$1')
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
+ .replace(/\s*\([a-z0-9_./-]+\/[a-z0-9_./-]+\)\s*$/iu, '')
+ .trim();
+ }
+
+ // Sidebar label: the page heading stays full; the nav only needs the name.
+ // "pi-schema — 零开销 JSON Schema 类型构建器" -> "pi-schema"
+ // "earendil-works/pi — 仓库全景导览(80.9 万行…)" -> "仓库全景导览"
+ function navShortTitle(page, isFirstPage) {
+ const plain = cleanPlainTitle(page.title).replace(/\s*[((][^()()]*[))]\s*$/u, '');
+ const parts = plain.split(/\s+[—–]\s+/u);
+ if (parts.length < 2) return plain;
+ return isFirstPage ? parts.slice(1).join(' — ') : parts[0];
+ }
+
+ // Notion-style page icon: one colour + glyph per page, stable across renders.
+ const MODULE_COLORS = ['orange', 'green', 'pink', 'yellow', 'red', 'brown', 'blue', 'purple'];
+ function pageStyle(page) {
+ const g = page.group;
+ if (g === '概览') return { color: 'blue', icon: 'book' };
+ if (g === '系统架构') return { color: 'purple', icon: 'layers' };
+ if (g === '开发指南') return { color: 'green', icon: 'terminal' };
+ if (g === '核心模块') {
+ const mods = PORTAL.pages.filter((p) => p.group === '核心模块');
+ const i = Math.max(0, mods.findIndex((p) => p.id === page.id));
+ return { color: MODULE_COLORS[i % MODULE_COLORS.length], icon: 'code' };
+ }
+ return { color: 'gray', icon: 'fileText' };
+ }
+
+ // Same grouping as server/describe.mjs#moduleGroupOf.
+ function moduleGroupOfPath(relPath) {
+ const parts = String(relPath).split('/');
+ if (['packages', 'apps', 'crates', 'services'].includes(parts[0]) && parts.length >= 2) return parts[0] + '/' + parts[1];
+ if (parts[0] === 'src' && parts.length >= 3) return 'src/' + parts[1];
+ if (parts.length >= 2) return parts[0];
+ return 'root';
+ }
+
+ // The module a chapter is about: the module most of its cited files live in (>= 60%).
+ function pageModuleGroup(page) {
+ const refs = page.referencedFiles || [];
+ if (!refs.length) return '';
+ const counts = new Map();
+ for (const f of refs) counts.set(moduleGroupOfPath(f), (counts.get(moduleGroupOfPath(f)) || 0) + 1);
+ const [best, n] = [...counts.entries()].sort((a, b) => b[1] - a[1])[0];
+ return n / refs.length >= 0.6 ? best : '';
+ }
+
+ // Under the title: a one-line summary (module pages) and Notion-style property tags.
+ // Stats live here, never in the title.
+ function pageHeaderMetaHtml(page, ps) {
+ const tag = (text, color) =>
+ '' + esc(text) + '';
+ const tags = [tag(page.group || '文档', ps.color)];
+ let subtitle = '';
+ const isOverview = PORTAL.pages.indexOf(page) === 0;
+ if (isOverview) {
+ const st = PORTAL.stats || {};
+ if (st.fileCount) tags.push(tag(st.fileCount.toLocaleString() + ' 个文件', 'gray'));
+ if (st.totalLines) {
+ const lines = st.totalLines >= 10000 ? (st.totalLines / 10000).toFixed(1) + ' 万行' : st.totalLines.toLocaleString() + ' 行';
+ tags.push(tag(lines, 'gray'));
+ }
+ if (PORTAL.packageCount > 1) tags.push(tag(PORTAL.packageCount + ' 个子包', 'gray'));
+ } else {
+ const g = page.group === '核心模块' ? pageModuleGroup(page) : '';
+ if (g) {
+ tags.push(tag(g, 'gray'));
+ const d = PORTAL.descriptions && PORTAL.descriptions.modules && PORTAL.descriptions.modules[g];
+ if (d) subtitle = '' + esc(d) + '
';
+ }
+ if (page.referencedFiles && page.referencedFiles.length) tags.push(tag(page.referencedFiles.length + ' 个源码文件', 'gray'));
+ }
+ return subtitle + '' + tags.join('') + '
';
+ }
+
+ function compactDirMiddle(dirPath, maxLen = 27) {
+ const clean = String(dirPath || '').replace(/\/+$/g, '');
+ if (!clean || clean === '.') return './';
+ if (clean.length <= maxLen) return clean;
+ const parts = clean.split('/');
+ if (parts.length <= 2) return clean;
+ return parts[0] + '/…/' + parts.slice(-2).join('/');
+ }
+
+ function renderTitleHtml(raw) {
+ let out = esc(String(raw || '').trim());
+ out = out.replace(/`([^`]+)`/g, '$1');
+ return out;
+ }
+
+ function formatLineRangeLabel(start, end) {
+ if (!start) return '';
+ if (!end || end <= start) return 'L' + start;
+ return 'L' + start + '–' + end;
+ }
+
+ function inferLangFromPath(relPath) {
+ const ext = (relPath.split('.').pop() || '').toLowerCase();
+ if (['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'ts';
+ if (ext === 'py') return 'py';
+ if (ext === 'go') return 'go';
+ if (ext === 'rs') return 'rs';
+ return ext || 'text';
+ }
+
+ // ─── State & Initial Hydration ───
+ if (!PORTAL.sync) {
+ PORTAL.sync = { stalePages: [], changedSourceFiles: [], freshCount: PORTAL.pages.length, lastScanMs: 0 };
+ }
+ if (!PORTAL.activityLog) PORTAL.activityLog = [];
+
+ const isHttpProtocol = window.location.protocol === 'http:' || window.location.protocol === 'https:';
+ let liveConnected = false;
+ let activeView = 'wiki'; // 'wiki' | 'graph' | 'sync'
+ let activePageIdx = 0;
+ let activeDrawerCtx = null;
+ let toastTimer = null;
+
+ // Hydrate Static Controls in Minimal Topbar (null-guarded)
+ const setHtml = (id, html) => {
+ const el = document.getElementById(id);
+ if (el) el.innerHTML = html;
+ };
+ const setText = (id, txt) => {
+ const el = document.getElementById(id);
+ if (el) el.textContent = txt;
+ };
+ setHtml('mobileMenuBtn', icon('sidebar', 15));
+ const tabIco = (name, color) =>
+ '' + icon(name, 14) + '';
+ setHtml('tabWikiBtn', tabIco('book', 'blue') + '文档');
+ setHtml('tabGraphBtn', tabIco('network', 'purple') + '图谱');
+ setHtml(
+ 'tabSyncBtn',
+ tabIco('refresh', 'green') + '同步0',
+ );
+ setHtml('brandMark', icon('prism', 13));
+ setHtml('cmdkTriggerBtn', icon('search', 13) + '⌘K');
+ setHtml('cmdkSearchIcon', icon('search', 15));
+ setText('expandFullFileBtn', '完整');
+ setText('copyPromptBtn', '复制');
+ setHtml('closeDrawerBtn', icon('close', 14));
+
+ function refreshHeaderMeta() {
+ setText('repoNameLabel', PORTAL.repoName);
+
+ const staleLen = (PORTAL.sync?.stalePages || []).length;
+ const countBadge = document.getElementById('staleCountBadge');
+ if (countBadge) {
+ countBadge.textContent = String(staleLen);
+ countBadge.classList.toggle('visible', staleLen > 0);
+ }
+
+ const pill = document.getElementById('liveStatusPill');
+ if (pill) {
+ pill.classList.remove('is-live', 'is-stale');
+ pill.innerHTML = '';
+ if (liveConnected) {
+ if (staleLen > 0) {
+ pill.classList.add('is-stale');
+ pill.title = staleLen + ' 篇待同步';
+ } else {
+ pill.classList.add('is-live');
+ pill.title = '已同步';
+ }
+ } else if (isHttpProtocol && PORTAL.liveMode) {
+ pill.title = '重连中';
+ } else {
+ pill.title = '静态快照';
+ }
+ }
+ }
+
+ function showToast(msg) {
+ const el = document.getElementById('liveToast');
+ if (!el) return;
+ el.innerHTML = '' + esc(msg) + '';
+ el.classList.add('show');
+ if (toastTimer) clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => el.classList.remove('show'), 2200);
+ }
+
+ // ─── Theme Toggle (Default: Dark Matte Charcoal, Persisted via localStorage) ───
+ const themeBtn = document.getElementById('themeToggleBtn');
+ function syncThemeButton() {
+ if (!themeBtn) return;
+ const isDark = document.documentElement.getAttribute('data-theme') !== 'light';
+ themeBtn.innerHTML = isDark ? icon('sun', 14) : icon('moon', 14);
+ }
+ syncThemeButton();
+ if (themeBtn) {
+ themeBtn.onclick = () => {
+ const cur = document.documentElement.getAttribute('data-theme');
+ const next = cur === 'light' ? 'dark' : 'light';
+ document.documentElement.setAttribute('data-theme', next);
+ try {
+ localStorage.setItem('repowiki-theme', next);
+ } catch {
+ // Ignore storage restrictions
+ }
+ syncThemeButton();
+ renderCurrentPage(true);
+ if (window.RepoWikiGraph) window.RepoWikiGraph.redraw();
+ };
+ }
+
+ // ─── Overlays & View Switching ───
+ const overlayBackdrop = document.getElementById('overlayBackdrop');
+ const sidebarShell = document.getElementById('sidebarShell');
+ const leftNav = document.getElementById('leftNav');
+ const codeDrawer = document.getElementById('codeDrawer');
+ const cmdkBackdrop = document.getElementById('cmdkBackdrop');
+ const mobileDrawerEl = sidebarShell || leftNav;
+
+ function syncBackdropVisibility() {
+ const anyOpen = codeDrawer.classList.contains('open') || mobileDrawerEl.classList.contains('mobile-open');
+ overlayBackdrop.classList.toggle('visible', anyOpen);
+ }
+
+ function closeAllOverlays() {
+ codeDrawer.classList.remove('open');
+ mobileDrawerEl.classList.remove('mobile-open');
+ cmdkBackdrop.classList.remove('open');
+ document.querySelectorAll('.diagram-card.expanded').forEach((d) => {
+ d.classList.remove('expanded');
+ const btn = d.querySelector('.diag-expand-btn');
+ if (btn) btn.textContent = '全屏';
+ });
+ if (document.activeElement && typeof document.activeElement.blur === 'function') {
+ document.activeElement.blur();
+ }
+ syncBackdropVisibility();
+ }
+
+ const mobileMenuBtn = document.getElementById('mobileMenuBtn');
+ if (mobileMenuBtn) {
+ mobileMenuBtn.onclick = () => {
+ mobileDrawerEl.classList.toggle('mobile-open');
+ syncBackdropVisibility();
+ };
+ }
+ overlayBackdrop.onclick = closeAllOverlays;
+ document.getElementById('closeDrawerBtn').onclick = () => {
+ codeDrawer.classList.remove('open');
+ syncBackdropVisibility();
+ };
+
+ const tabWikiBtn = document.getElementById('tabWikiBtn');
+ const tabGraphBtn = document.getElementById('tabGraphBtn');
+ const tabSyncBtn = document.getElementById('tabSyncBtn');
+ const wikiView = document.getElementById('wikiView');
+ const graphView = document.getElementById('graphView');
+ const syncView = document.getElementById('syncView');
+
+ function switchView(next) {
+ activeView = next;
+ tabWikiBtn.classList.toggle('active', next === 'wiki');
+ tabGraphBtn.classList.toggle('active', next === 'graph');
+ tabSyncBtn.classList.toggle('active', next === 'sync');
+ wikiView.classList.toggle('hidden', next !== 'wiki');
+ graphView.classList.toggle('active', next === 'graph');
+ syncView.classList.toggle('active', next === 'sync');
+ if (next === 'graph') window.RepoWikiGraph && window.RepoWikiGraph.show();
+ else window.RepoWikiGraph && window.RepoWikiGraph.hide();
+ if (next === 'sync') renderSyncDashboard();
+ }
+
+ tabWikiBtn.onclick = () => switchView('wiki');
+ tabGraphBtn.onclick = () => switchView('graph');
+ tabSyncBtn.onclick = () => switchView('sync');
+ document.getElementById('liveStatusPill').onclick = () => switchView('sync');
+
+ // ─── Left Sidebar Navigation ───
+ function getStaleEntryForPage(pageId) {
+ return (PORTAL.sync?.stalePages || []).find((s) => s.page === pageId) || null;
+ }
+
+ function renderSidebar() {
+ leftNav.innerHTML = '';
+ const groups = new Map();
+ PORTAL.pages.forEach((p, idx) => {
+ if (!groups.has(p.group)) groups.set(p.group, []);
+ groups.get(p.group).push({ p, idx });
+ });
+
+ for (const [gName, items] of groups.entries()) {
+ const grp = document.createElement('div');
+ grp.className = 'nav-group';
+ const lbl = document.createElement('div');
+ lbl.className = 'nav-group-label';
+ lbl.textContent = gName;
+ grp.appendChild(lbl);
+
+ items.forEach(({ p, idx }) => {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'nav-item' + (idx === activePageIdx ? ' active' : '');
+ const isStale = Boolean(getStaleEntryForPage(p.id));
+ btn.title = cleanPlainTitle(p.title);
+ const ps = pageStyle(p);
+ btn.innerHTML =
+ '' +
+ icon(ps.icon, 15) +
+ '' +
+ '' +
+ esc(navShortTitle(p, idx === 0)) +
+ '' +
+ (isStale ? '' : '');
+ btn.onclick = () => selectPage(idx);
+ grp.appendChild(btn);
+ });
+ leftNav.appendChild(grp);
+ }
+ }
+
+ function selectPage(idx) {
+ if (idx < 0 || idx >= PORTAL.pages.length) return;
+ activePageIdx = idx;
+ mobileDrawerEl.classList.remove('mobile-open');
+ syncBackdropVisibility();
+ if (activeView !== 'wiki') switchView('wiki');
+ renderSidebar();
+ renderCurrentPage(false);
+ const scroller = document.getElementById('docScroll');
+ scroller.scrollTo({ top: 0, behavior: 'instant' });
+ scroller.scrollTop = 0;
+ }
+
+ // ─── Syntax Highlighter & Inline Math ───
+ function highlightCodeHtml(rawCode, lang) {
+ const normalized = String(rawCode).replace(/\t/g, ' ');
+ if (!lang || lang === 'text' || lang === 'plaintext') return esc(normalized);
+ const tokRe =
+ /(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`])*`)|\b(import|export|from|const|let|var|function|async|await|return|class|interface|type|extends|implements|new|if|else|for|while|switch|case|try|catch|throw|def|self|None|True|False|pub|fn|struct|enum|impl|trait|func|package|readonly|private|protected|public)\b|\b(\d+(?:\.\d+)?)\b/g;
+ let last = 0;
+ let out = '';
+ let m;
+ while ((m = tokRe.exec(normalized)) !== null) {
+ out += esc(normalized.slice(last, m.index));
+ if (m[1]) out += '' + esc(m[1]) + '';
+ else if (m[2]) out += '' + esc(m[2]) + '';
+ else if (m[3]) out += '' + esc(m[3]) + '';
+ else if (m[4]) out += '' + esc(m[4]) + '';
+ last = tokRe.lastIndex;
+ }
+ out += esc(normalized.slice(last));
+ return out;
+ }
+
+ function renderMathExpr(tex) {
+ let s = esc(tex.trim());
+ s = s
+ .replace(
+ /\\frac\{([^{}]+)\}\{([^{}]+)\}/g,
+ '$1$2',
+ )
+ .replace(/\\le\b/g, '≤')
+ .replace(/\\ge\b/g, '≥')
+ .replace(/\\neq\b/g, '≠')
+ .replace(/\\approx\b/g, '≈')
+ .replace(/\\times\b/g, '×')
+ .replace(/\\cdot\b/g, '·')
+ .replace(/\\to\b/g, '→')
+ .replace(/\\sum\b/g, '∑')
+ .replace(/\\ln\b/g, 'ln')
+ .replace(/\\log\b/g, 'log')
+ .replace(/_\{([^{}]+)\}/g, '$1')
+ .replace(/_([A-Za-z0-9])/g, '$1')
+ .replace(/\^\{([^{}]+)\}/g, '$1')
+ .replace(/\^([A-Za-z0-9])/g, '$1');
+ return '' + s + '';
+ }
+
+ function resolveWikiDocIndex(href) {
+ const cleanDoc = href.split('#')[0].replace(/^\.\//, '').replace(/^\.\.\//, '');
+ let idx = PORTAL.pages.findIndex((p) => p.id === cleanDoc || p.id.endsWith('/' + cleanDoc));
+ if (idx >= 0) return idx;
+ const tailSlug = cleanDoc
+ .split('/')
+ .pop()
+ .replace(/^\d+-/, '');
+ if (tailSlug) {
+ idx = PORTAL.pages.findIndex((p) => p.id.endsWith('-' + tailSlug) || p.id.endsWith('/' + tailSlug));
+ }
+ return idx;
+ }
+
+ function renderSourcePillHtml(fp, s, e) {
+ const base = fp.split('/').pop();
+ const lnLabel = formatLineRangeLabel(s, e);
+ return (
+ ''
+ );
+ }
+
+ function renderInline(text) {
+ const slots = [];
+ const stash = (html) => {
+ slots.push(html);
+ return '\u0000SLOT' + (slots.length - 1) + '\u0000';
+ };
+
+ let working = String(text).replace(/`([^`]+)`/g, (_, inner) => {
+ const cm = inner.match(/^\[?([A-Za-z0-9_./-]+\.[A-Za-z0-9]{1,5}):L?(\d+)(?:-L?(\d+))?\]?$/);
+ if (cm) {
+ const fp = cm[1].replace(/^\.\//, '');
+ const s = parseInt(cm[2], 10);
+ const e = cm[3] ? parseInt(cm[3], 10) : s;
+ return stash(renderSourcePillHtml(fp, s, e));
+ }
+ return stash('' + esc(inner) + '');
+ });
+
+ working = working.replace(/\$([^$\n]{1,120})\$/g, (full, expr) => {
+ if (/^\d/.test(expr) && expr.includes(' ')) return full;
+ return stash(renderMathExpr(expr));
+ });
+
+ let out = esc(working);
+
+ out = out.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, href) => {
+ if (href.endsWith('.md') || href.includes('.md#')) {
+ const targetIdx = resolveWikiDocIndex(href);
+ if (targetIdx >= 0) {
+ return (
+ ''
+ );
+ }
+ return '' + label + '';
+ }
+ const m = href.match(/^([^#]+)(?:#L?(\d+)(?:-L?(\d+))?)?$/);
+ if (m && !href.startsWith('http')) {
+ const fp = m[1].replace(/^\.\//, '');
+ const s = m[2] ? parseInt(m[2], 10) : 1;
+ const e = m[3] ? parseInt(m[3], 10) : s;
+ return renderSourcePillHtml(fp, s, e);
+ }
+ return '' + label + '';
+ });
+
+ out = out.replace(/\[([A-Za-z0-9_./-]+\.[A-Za-z0-9]{1,5}):L?(\d+)(?:-L?(\d+))?\]/g, (_, fp, sStr, eStr) => {
+ const cleanFp = fp.replace(/^\.\//, '');
+ const s = parseInt(sStr, 10);
+ const e = eStr ? parseInt(eStr, 10) : s;
+ return renderSourcePillHtml(cleanFp, s, e);
+ });
+
+ out = out.replace(/\*\*([^*]+)\*\*/g, '$1');
+ out = out.replace(/\u0000SLOT(\d+)\u0000/g, (_, idx) => slots[Number(idx)] || '');
+ return out;
+ }
+
+ // ─── Offline Geist-Blueprint Vector Diagram Renderer ───
+ function measureTextPx(str, fontPx = 12.5) {
+ let units = 0;
+ for (const ch of String(str)) {
+ units += ch.charCodeAt(0) > 255 ? 1.02 : 0.58;
+ }
+ return Math.ceil(units * fontPx);
+ }
+
+ function splitTwoLines(label, maxCharsPerLine = 20) {
+ const raw = String(label).trim();
+ if (/
/i.test(raw)) {
+ const parts = raw
+ .split(/
/i)
+ .map((s) => s.trim())
+ .filter(Boolean);
+ if (parts.length >= 2) return [parts[0], parts.slice(1).join(' · ')];
+ if (parts.length === 1) return [parts[0]];
+ }
+ const clean = raw;
+ const parenIdx = clean.indexOf(' (');
+ const cnParenIdx = clean.indexOf('(');
+ if (parenIdx > 2 && clean.length > maxCharsPerLine - 3) {
+ return [clean.slice(0, parenIdx).trim(), clean.slice(parenIdx).trim()];
+ }
+ if (cnParenIdx > 2 && clean.length > maxCharsPerLine - 3) {
+ return [clean.slice(0, cnParenIdx).trim(), clean.slice(cnParenIdx).trim()];
+ }
+ if (clean.length <= maxCharsPerLine) return [clean];
+ const spaceIdx = clean.lastIndexOf(' ', maxCharsPerLine);
+ if (spaceIdx > 5) {
+ return [clean.slice(0, spaceIdx).trim(), clean.slice(spaceIdx + 1).trim()];
+ }
+ return [clean.slice(0, maxCharsPerLine), clean.slice(maxCharsPerLine, maxCharsPerLine * 2 - 2)];
+ }
+
+ let diagramSeq = 0;
+ window.__toggleDiagramExpand = (id, btnEl) => {
+ const el = document.getElementById(id);
+ if (!el) return;
+ const isExp = el.classList.toggle('expanded');
+ const btn = btnEl || el.querySelector('.diag-expand-btn');
+ if (btn) {
+ btn.textContent = isExp ? '收起' : '全屏';
+ btn.blur();
+ }
+ };
+
+ function wrapDiagramCard(svgHtml) {
+ const id = 'diag_' + ++diagramSeq;
+ return (
+ '' +
+ svgHtml +
+ '
'
+ );
+ }
+
+ function renderOfflineMermaidSvg(code) {
+ const trimmed = code.trim();
+ const lines = trimmed
+ .split('\n')
+ .map((l) => l.trim())
+ .filter((l) => l && !l.startsWith('%%'));
+ const isDark = document.documentElement.getAttribute('data-theme') !== 'light';
+
+ const boxFill = isDark ? '#242424' : '#ffffff';
+ const boxStroke = isDark ? 'rgba(255,255,255,0.14)' : '#d4d4d4';
+ const textCol = isDark ? '#e5e5e5' : '#171717';
+ const mutedCol = isDark ? '#9a9a9a' : '#737373';
+ const edgeStroke = isDark ? '#666666' : '#a3a3a3';
+ const SUBGRAPH_COLORS = ['blue', 'purple', 'green', 'orange', 'pink', 'yellow', 'brown', 'red'];
+ const groupBg = isDark ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.015)';
+ const groupBorder = isDark ? 'rgba(255,255,255,0.10)' : '#e5e5e5';
+ const noteBg = isDark ? '#1c1c1c' : '#ffffff';
+ const svgFont = '-apple-system, BlinkMacSystemFont, Inter, PingFang SC, sans-serif';
+ const seqMarkerId = 'seqArr_' + (diagramSeq + 1);
+ const flMarkerId = 'flArr_' + (diagramSeq + 1);
+
+ // Sequence Diagram
+ if (/^sequenceDiagram\b/.test(lines[0])) {
+ const actors = [];
+ const actorMap = new Map();
+ const msgs = [];
+ const ensureActor = (id, label) => {
+ if (!actorMap.has(id)) {
+ actorMap.set(id, { id, label: label || id, idx: actors.length });
+ actors.push(actorMap.get(id));
+ }
+ };
+ for (let i = 1; i < lines.length; i++) {
+ const l = lines[i];
+ const pm = l.match(/^(?:participant|actor)\s+([A-Za-z0-9_.-]+)(?:\s+as\s+(.+))?$/);
+ if (pm) {
+ ensureActor(pm[1], (pm[2] || pm[1]).replace(/^"|"$/g, ''));
+ continue;
+ }
+ const noteMatch = l.match(/^Note\s+(?:over|left of|right of)\s+([^:]+):\s*(.+)$/i);
+ if (noteMatch) {
+ msgs.push({ isNote: true, text: noteMatch[2].trim() });
+ continue;
+ }
+ const mm = l.match(/^([A-Za-z0-9_.-]+)\s*(->>|-->>|->|-->)\s*([A-Za-z0-9_.-]+)\s*:\s*(.+)$/);
+ if (mm) {
+ ensureActor(mm[1]);
+ ensureActor(mm[3]);
+ msgs.push({ from: mm[1], to: mm[3], dashed: mm[2].startsWith('--'), text: mm[4].trim() });
+ }
+ }
+ if (actors.length >= 2) {
+ const colW = actors.length >= 6 ? 152 : 168;
+ const padX = 20;
+ const W = Math.max(580, actors.length * colW + padX * 2);
+ const H = 96 + msgs.length * 46;
+ const minRenderW = Math.max(560, actors.length * 134);
+ let svg =
+ '';
+ return wrapDiagramCard(svg);
+ }
+ }
+
+ // Layered Flowchart / Subgraph Architecture DAG
+ if (/^(?:flowchart|graph)\b/.test(lines[0])) {
+ const isLR = /\bLR\b/.test(lines[0]);
+ const nodes = new Map();
+ const edges = [];
+ const subgraphs = [];
+ let currentSubgraph = null;
+
+ const parseNodeToken = (rawToken) => {
+ if (!rawToken) return null;
+ const clean = rawToken.trim().replace(/:::[\w-]+$/, '');
+ const m = clean.match(
+ /^([A-Za-z0-9_.-]+)(?:\s*(?:\["([^"]+)"\]|\("([^"]+)"\)|\{\{"([^"]+)"\}\}|\[([^\]]+)\]|\(([^)]+)\)|\{([^}]+)\}))?$/,
+ );
+ if (!m) return null;
+ const id = m[1];
+ if (id === 'subgraph' || id === 'end') return null;
+ const rawLabel = m[2] || m[3] || m[4] || m[5] || m[6] || m[7];
+ const label = (rawLabel || id).replace(/^"|"$/g, '').trim();
+ if (!nodes.has(id)) {
+ nodes.set(id, {
+ id,
+ label,
+ layer: currentSubgraph ? currentSubgraph.idx : 0,
+ subgraphIdx: currentSubgraph ? currentSubgraph.idx : -1,
+ });
+ } else {
+ if (rawLabel) nodes.get(id).label = label;
+ if (currentSubgraph && nodes.get(id).subgraphIdx === -1) {
+ nodes.get(id).subgraphIdx = currentSubgraph.idx;
+ nodes.get(id).layer = currentSubgraph.idx;
+ }
+ }
+ return id;
+ };
+
+ for (let i = 1; i < lines.length; i++) {
+ const l = lines[i];
+ if (
+ l.startsWith('style ') ||
+ l.startsWith('classDef ') ||
+ l.startsWith('class ') ||
+ l.startsWith('direction ')
+ ) {
+ continue;
+ }
+ const sgMatch = l.match(/^subgraph\s+([A-Za-z0-9_.-]+)(?:\s*\["?([^"\]]+)"?\])?(?:\s+(.+))?$/);
+ if (sgMatch) {
+ const title = (sgMatch[2] || sgMatch[3] || sgMatch[1]).replace(/^"|"$/g, '').trim();
+ currentSubgraph = { idx: subgraphs.length, id: sgMatch[1], title };
+ subgraphs.push(currentSubgraph);
+ continue;
+ }
+ if (l === 'end') {
+ currentSubgraph = null;
+ continue;
+ }
+
+ const edgeMatch = l.match(
+ /^(.+?)\s*(?:-->|-\.->|==>|---)\s*(?:\|"([^"]*)"\|\s*|\|([^|]*)\|\s*)?(.+)$/,
+ );
+ if (edgeMatch) {
+ const u = parseNodeToken(edgeMatch[1]);
+ const lbl = (edgeMatch[2] || edgeMatch[3] || '').trim();
+ const v = parseNodeToken(edgeMatch[4]);
+ if (u && v) edges.push({ u, v, label: lbl, dashed: l.includes('-.->') });
+ } else {
+ parseNodeToken(l);
+ }
+ }
+
+ if (nodes.size >= 2) {
+ const nodeArr = [...nodes.values()];
+ if (isLR || subgraphs.length < 2) {
+ for (let pass = 0; pass < 8; pass++) {
+ for (const e of edges) {
+ const nu = nodes.get(e.u);
+ const nv = nodes.get(e.v);
+ if (nu !== nv && nv.layer <= nu.layer && nv.layer < 7) nv.layer = nu.layer + 1;
+ }
+ }
+ } else {
+ for (const e of edges) {
+ const nu = nodes.get(e.u);
+ const nv = nodes.get(e.v);
+ if (nu !== nv && nv.subgraphIdx === -1 && nv.layer <= nu.layer) {
+ nv.layer = nu.layer + 1;
+ }
+ }
+ }
+
+ for (const n of nodeArr) {
+ n.lines = splitTwoLines(n.label, 19);
+ const widest = Math.max(...n.lines.map((ln) => measureTextPx(ln, 12.25)));
+ n.w = Math.max(138, Math.min(228, widest + 30));
+ n.h = n.lines.length > 1 ? 52 : 40;
+ }
+
+ const byLayer = new Map();
+ for (const n of nodeArr) {
+ if (!byLayer.has(n.layer)) byLayer.set(n.layer, []);
+ byLayer.get(n.layer).push(n);
+ }
+ const layers = [...byLayer.keys()].sort((a, b) => a - b);
+ const gapMain = subgraphs.length > 0 ? 106 : 78;
+ const gapCross = 24;
+
+ let W = 620;
+ let H = 300;
+
+ if (isLR) {
+ const layerWidths = layers.map((ly) => Math.max(...byLayer.get(ly).map((n) => n.w)));
+ const maxColH = Math.max(
+ ...layers.map((ly) => {
+ const items = byLayer.get(ly);
+ return items.reduce((s, n) => s + n.h, 0) + (items.length - 1) * gapCross;
+ }),
+ );
+ W = layerWidths.reduce((a, b) => a + b, 0) + (layers.length - 1) * gapMain + 64;
+ H = maxColH + 64;
+ let curX = 32;
+ layers.forEach((ly, lIdx) => {
+ const items = byLayer.get(ly);
+ const lw = layerWidths[lIdx];
+ const colH = items.reduce((s, n) => s + n.h, 0) + (items.length - 1) * gapCross;
+ let curY = (H - colH) / 2;
+ items.forEach((n) => {
+ n.x = curX + lw / 2;
+ n.y = curY + n.h / 2;
+ curY += n.h + gapCross;
+ });
+ curX += lw + gapMain;
+ });
+ } else {
+ const layerHeights = layers.map((ly) => Math.max(...byLayer.get(ly).map((n) => n.h)));
+ const maxRowW = Math.max(
+ ...layers.map((ly) => {
+ const items = byLayer.get(ly);
+ return items.reduce((s, n) => s + n.w, 0) + (items.length - 1) * gapCross;
+ }),
+ );
+ W = Math.max(580, maxRowW + 84);
+ H = layerHeights.reduce((a, b) => a + b, 0) + (layers.length - 1) * gapMain + 92;
+ let curY = 44;
+ layers.forEach((ly, lIdx) => {
+ const items = byLayer.get(ly);
+ const lh = layerHeights[lIdx];
+ const rowW = items.reduce((s, n) => s + n.w, 0) + (items.length - 1) * gapCross;
+ let curX = (W - rowW) / 2;
+ items.forEach((n) => {
+ n.x = curX + n.w / 2;
+ n.y = curY + lh / 2;
+ curX += n.w + gapCross;
+ });
+ curY += lh + gapMain;
+ });
+ }
+
+ const minRenderW = Math.min(W, Math.max(520, Math.round(W * 0.85)));
+ let svg =
+ '';
+ return wrapDiagramCard(svg);
+ }
+ }
+
+ return '' + esc(trimmed) + '
';
+ }
+
+ let codeBlockSeq = 0;
+ const codeBlockStore = new Map();
+ window.__copyCodeBlock = (id, btnEl) => {
+ const raw = codeBlockStore.get(id) || '';
+ if (navigator.clipboard) navigator.clipboard.writeText(raw);
+ btnEl.innerHTML = icon('check', 11) + '已复制';
+ setTimeout(() => {
+ btnEl.innerHTML = icon('copy', 11) + '复制';
+ }, 1400);
+ };
+
+ function renderListBlock(lines, startIdx) {
+ const items = [];
+ let i = startIdx;
+ const firstMatch = lines[i].match(/^(\s*)([-*]|\d+\.)\s+(.*)$/);
+ const isOrdered = /^\d+\./.test(firstMatch[2]);
+
+ while (i < lines.length) {
+ const m = lines[i].match(/^(\s*)([-*]|\d+\.)\s+(.*)$/);
+ if (!m) break;
+ const indent = m[1].length;
+ if (indent > 0 && items.length > 0) {
+ const subLines = [];
+ while (i < lines.length) {
+ const sm = lines[i].match(/^(\s+)([-*]|\d+\.)\s+(.*)$/);
+ if (!sm) break;
+ subLines.push('' + renderInline(sm[3]) + '');
+ i++;
+ }
+ items[items.length - 1].subHtml = '' + subLines.join('') + '
';
+ continue;
+ }
+ items.push({ html: renderInline(m[3]), subHtml: '' });
+ i++;
+ }
+ const tag = isOrdered ? 'ol' : 'ul';
+ const html =
+ '<' +
+ tag +
+ '>' +
+ items.map((it) => '' + it.html + (it.subHtml || '') + '').join('') +
+ '' +
+ tag +
+ '>';
+ return { html, nextIdx: i };
+ }
+
+ function renderMarkdownToHtml(md) {
+ const lines = md.replace(/\r\n/g, '\n').split('\n');
+ const out = [];
+ const toc = [];
+ let i = 0;
+
+ while (i < lines.length) {
+ const line = lines[i];
+
+ if (line.trim().startsWith('```')) {
+ const lang = line.trim().slice(3).trim().toLowerCase();
+ const buf = [];
+ i++;
+ while (i < lines.length && !lines[i].trim().startsWith('```')) {
+ buf.push(lines[i]);
+ i++;
+ }
+ i++;
+ if (lang === 'mermaid') {
+ out.push(renderOfflineMermaidSvg(buf.join('\n')));
+ } else {
+ const rawCode = buf.join('\n');
+ const id = 'cb_' + ++codeBlockSeq;
+ codeBlockStore.set(id, rawCode);
+ const langLabel = lang || '';
+ out.push(
+ '' +
+ (langLabel ? '' + esc(langLabel) + '' : '') +
+ '
' +
+ highlightCodeHtml(rawCode, lang) +
+ '
',
+ );
+ }
+ continue;
+ }
+
+ if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1])) {
+ const parseRow = (r) =>
+ r
+ .trim()
+ .replace(/^\||\|$/g, '')
+ .split('|')
+ .map((c) => c.trim());
+ const headers = parseRow(line);
+ i += 2;
+ const rows = [];
+ while (i < lines.length && lines[i].includes('|') && lines[i].trim() !== '') {
+ rows.push(parseRow(lines[i]));
+ i++;
+ }
+ let tbl = '';
+ headers.forEach((h) => {
+ tbl += '| ' + renderInline(h) + ' | ';
+ });
+ tbl += '
';
+ rows.forEach((r) => {
+ tbl += '';
+ headers.forEach((_, cIdx) => {
+ const cell = r[cIdx] ?? '';
+ const cls = cIdx === 0 || cell.length <= 14 ? ' class="td-nowrap"' : '';
+ tbl += '| ' + renderInline(cell) + ' | ';
+ });
+ tbl += '
';
+ });
+ tbl += '
';
+ out.push(tbl);
+ continue;
+ }
+
+ if (line.startsWith('>')) {
+ const qLines = [];
+ while (i < lines.length && lines[i].startsWith('>')) {
+ qLines.push(lines[i].replace(/^>\s?/, ''));
+ i++;
+ }
+ const alertMatch = qLines[0]?.match(/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*)$/i);
+ if (alertMatch) {
+ const kind = alertMatch[1].toUpperCase();
+ const labelMap = {
+ NOTE: '说明',
+ TIP: '提示',
+ IMPORTANT: '要点',
+ WARNING: '注意',
+ CAUTION: '警告',
+ };
+ const label = labelMap[kind] || '说明';
+ const bodyLines = [alertMatch[2], ...qLines.slice(1)].filter(Boolean);
+ const calloutIcon = { NOTE: 'info', TIP: 'checkCircle', IMPORTANT: 'alert', WARNING: 'alert', CAUTION: 'alert' };
+ out.push(
+ '' +
+ icon(calloutIcon[kind] || 'info', 18) +
+ '
' +
+ label +
+ '
' +
+ renderInline(bodyLines.join(' ')) +
+ '
',
+ );
+ } else {
+ out.push('' + renderInline(qLines.join(' ')) + '
');
+ }
+ continue;
+ }
+
+ if (/^#\s+/.test(line)) {
+ i++;
+ continue;
+ }
+
+ const hm = line.match(/^(#{2,4})\s+(.+)$/);
+ if (hm) {
+ const lvl = hm[1].length;
+ const rawText = hm[2].trim();
+ const cleanTocText = cleanPlainTitle(rawText);
+ const hid = 'sec-' + toc.length;
+ if (lvl <= 3) toc.push({ id: hid, level: lvl, text: cleanTocText });
+ out.push('' + renderInline(rawText) + '');
+ i++;
+ continue;
+ }
+
+ if (/^\s*([-*]|\d+\.)\s+/.test(line)) {
+ const { html, nextIdx } = renderListBlock(lines, i);
+ out.push(html);
+ i = nextIdx;
+ continue;
+ }
+
+ if (/^---+$/.test(line.trim())) {
+ out.push('
');
+ i++;
+ continue;
+ }
+
+ if (!line.trim()) {
+ i++;
+ continue;
+ }
+
+ const pBuf = [];
+ while (
+ i < lines.length &&
+ lines[i].trim() &&
+ !lines[i].startsWith('#') &&
+ !lines[i].startsWith('```') &&
+ !lines[i].startsWith('>') &&
+ !/^\s*([-*]|\d+\.)\s+/.test(lines[i])
+ ) {
+ pBuf.push(lines[i].trim());
+ i++;
+ }
+ out.push('' + renderInline(pBuf.join(' ')) + '
');
+ }
+ return { html: out.join('\n'), toc };
+ }
+
+ function estimateReadMins(md) {
+ const cjk = (md.match(/[\u4e00-\u9fa5]/g) || []).length;
+ const words = md.split(/\s+/).length;
+ return Math.max(2, Math.round((cjk + words * 1.2) / 380));
+ }
+
+ window.__copySyncPromptForPage = (pageId) => {
+ const entry = getStaleEntryForPage(pageId);
+ const cites = entry
+ ? [...(entry.changedCitations || []), ...(entry.brokenCitations || [])]
+ .map((c) => (c.symbol ? c.symbol + ' ' : '') + c.file + ':' + c.lines)
+ .join(';')
+ : '';
+ const prompt =
+ '用 mcode-repowiki 更新 Wiki 章节 `' +
+ pageId +
+ '`:先 wiki_plan sync 修正行号;它引用的这些代码已经改了:' +
+ (cites || (entry ? entry.dirtySourceFiles.join('、') : '')) +
+ '。逐条用 wiki_locate 看现在的代码,只改说错了的段落,再用 wiki_write_page 保存整章。';
+ if (navigator.clipboard) navigator.clipboard.writeText(prompt);
+ showToast('已复制');
+ };
+
+ window.__ackSyncNow = async (pageId) => {
+ if (!liveConnected && !isHttpProtocol) return;
+ try {
+ const res = await fetch('/api/ack-sync' + (pageId ? '?page=' + encodeURIComponent(pageId) : ''), { method: 'POST' });
+ if (res.ok) showToast('已核对');
+ } catch {
+ // Ignore offline
+ }
+ };
+
+ function renderCurrentPage(preserveScroll = false) {
+ const scroller = document.getElementById('docScroll');
+ const prevTop = preserveScroll ? scroller.scrollTop : 0;
+
+ const page = PORTAL.pages[activePageIdx];
+ if (!page) return;
+ codeBlockStore.clear();
+ const { html, toc } = renderMarkdownToHtml(page.markdown);
+ const staleEntry = getStaleEntryForPage(page.id);
+
+ const staleCites = staleEntry
+ ? [...(staleEntry.changedCitations || []), ...(staleEntry.brokenCitations || [])]
+ : [];
+ const driftHtml = staleEntry
+ ? '' +
+ '本章引用的代码改过了,文字可能过时:' +
+ (staleCites.length
+ ? staleCites
+ .slice(0, 4)
+ .map((c) => '' + esc((c.symbol ? c.symbol + ' · ' : '') + c.file.split('/').pop() + ':' + c.lines) + '')
+ .join(' ') + (staleCites.length > 4 ? ' 等 ' + staleCites.length + ' 处' : '')
+ : '' + staleEntry.dirtySourceFiles.length + ' 个文件') +
+ '
' +
+ '' +
+ (liveConnected
+ ? ''
+ : '') +
+ '
'
+ : '';
+
+ const ps = pageStyle(page);
+ const heroHtml =
+ '' +
+ icon(ps.icon, 28) +
+ '
' +
+ '' +
+ renderTitleHtml(page.title) +
+ '
' +
+ pageHeaderMetaHtml(page, ps) +
+ driftHtml;
+
+ document.getElementById('docArticle').innerHTML = heroHtml + html;
+
+ const pager = document.getElementById('docPager');
+ const prev = activePageIdx > 0 ? PORTAL.pages[activePageIdx - 1] : null;
+ const next = activePageIdx + 1 < PORTAL.pages.length ? PORTAL.pages[activePageIdx + 1] : null;
+ pager.innerHTML =
+ (prev
+ ? ''
+ : '') +
+ (next
+ ? ''
+ : '');
+
+ const rtoc = document.getElementById('rightToc');
+ let rHtml = '';
+ if (toc.length > 0) {
+ rHtml += '';
+ toc.forEach((t, tIdx) => {
+ rHtml +=
+ '' +
+ esc(t.text) +
+ '';
+ });
+ }
+ if (page.referencedFiles.length > 0) {
+ rHtml += '';
+ page.referencedFiles.slice(0, 14).forEach((rf) => {
+ const base = rf.split('/').pop();
+ rHtml +=
+ '';
+ });
+ }
+ rtoc.innerHTML = rHtml;
+
+ if (preserveScroll) {
+ scroller.scrollTop = prevTop;
+ }
+ }
+
+ document.getElementById('docScroll').addEventListener('scroll', () => {
+ const links = [...document.querySelectorAll('#rightToc .toc-link')];
+ if (links.length === 0) return;
+ let activeId = links[0].getAttribute('data-sec');
+ for (const l of links) {
+ const secId = l.getAttribute('data-sec');
+ const el = document.getElementById(secId);
+ if (el && el.getBoundingClientRect().top <= 128) activeId = secId;
+ }
+ links.forEach((l) => l.classList.toggle('active', l.getAttribute('data-sec') === activeId));
+ });
+
+ window.__goPage = (idx) => selectPage(idx);
+
+ // ─── Live Disk + Snapshot Fallback Source Code Drawer ───
+ function renderDrawerRows(relPath, linesArr, start, end, isLiveDisk, totalLines) {
+ const lang = inferLangFromPath(relPath);
+ const baseName = relPath.split('/').pop();
+ const rangeLabel = formatLineRangeLabel(start, end);
+ const titleEl = document.getElementById('drawerTitle');
+ if (titleEl) {
+ titleEl.title = relPath;
+ titleEl.innerHTML =
+ '' +
+ esc(baseName) +
+ '' +
+ (rangeLabel
+ ? ' ' + esc(rangeLabel) + ''
+ : '');
+ }
+
+ const badge = document.getElementById('drawerSourceBadge');
+ if (badge) {
+ badge.textContent = '';
+ }
+
+ // Track multi-line /* ... */ JSDoc block comments across rows so keywords inside comments aren't bolded!
+ let inBlockComment = false;
+ const body = document.getElementById('drawerBody');
+ body.innerHTML = linesArr
+ .map(([ln, txt]) => {
+ const hl = ln >= start && ln <= end ? ' hl' : '';
+ const normTxt = String(txt).replace(/\t/g, ' ');
+ let codeHtml = '';
+ if (inBlockComment) {
+ const closeIdx = normTxt.indexOf('*/');
+ if (closeIdx === -1) {
+ codeHtml = '' + esc(normTxt) + '';
+ } else {
+ inBlockComment = false;
+ codeHtml =
+ '' +
+ esc(normTxt.slice(0, closeIdx + 2)) +
+ '' +
+ highlightCodeHtml(normTxt.slice(closeIdx + 2), lang);
+ }
+ } else {
+ const openIdx = normTxt.indexOf('/*');
+ const lineCmtIdx = normTxt.indexOf('//');
+ if (openIdx >= 0 && (lineCmtIdx === -1 || openIdx < lineCmtIdx) && !normTxt.includes('*/', openIdx + 2)) {
+ inBlockComment = true;
+ codeHtml =
+ highlightCodeHtml(normTxt.slice(0, openIdx), lang) +
+ '' +
+ esc(normTxt.slice(openIdx)) +
+ '';
+ } else {
+ codeHtml = highlightCodeHtml(normTxt, lang);
+ }
+ }
+ return (
+ '' +
+ ln +
+ '' +
+ codeHtml +
+ '
'
+ );
+ })
+ .join('');
+
+ requestAnimationFrame(() => {
+ const targetRow = body.querySelector('.src-row.hl');
+ if (targetRow) targetRow.scrollIntoView({ block: 'center', behavior: 'instant' });
+ });
+ }
+
+ async function openSourceDrawer(relPath, start, end, fullFile = false) {
+ activeDrawerCtx = { relPath, start, end, fullFile };
+ codeDrawer.classList.add('open');
+ syncBackdropVisibility();
+
+ document.getElementById('copyPromptBtn').onclick = () => {
+ const prompt = '请结合 `@' + relPath + '` (第 ' + start + '-' + end + ' 行) 进一步解析其实现细节与边界情况。';
+ if (navigator.clipboard) navigator.clipboard.writeText(prompt);
+ showToast('已复制');
+ };
+
+ const fullBtn = document.getElementById('expandFullFileBtn');
+ fullBtn.style.display = isHttpProtocol ? 'inline-flex' : 'none';
+ fullBtn.onclick = () => openSourceDrawer(relPath, start, end, !activeDrawerCtx.fullFile);
+ fullBtn.textContent = fullFile ? '片段' : '完整';
+
+ // Try real-time disk read first when served over HTTP
+ if (isHttpProtocol) {
+ try {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 1600);
+ const url =
+ '/api/file?path=' +
+ encodeURIComponent(relPath) +
+ '&start=' +
+ start +
+ '&end=' +
+ end +
+ (fullFile ? '&full=1' : '');
+ const res = await fetch(url, { signal: ctrl.signal });
+ clearTimeout(timer);
+ if (res.ok) {
+ const data = await res.json();
+ if (Array.isArray(data.lines)) {
+ renderDrawerRows(relPath, data.lines, start, end, true, data.totalLines);
+ return;
+ }
+ }
+ } catch {
+ // Fallback to embedded snapshot below
+ }
+ }
+
+ const exactKey = relPath + ':' + start + '-' + end;
+ let snip = PORTAL.codeSnippets[exactKey] || PORTAL.codeSnippets[relPath];
+ if (!snip) {
+ const prefix = relPath + ':';
+ const k = Object.keys(PORTAL.codeSnippets).find((key) => key.startsWith(prefix));
+ if (k) snip = PORTAL.codeSnippets[k];
+ }
+
+ if (!snip) {
+ const titleEl = document.getElementById('drawerTitle');
+ if (titleEl) {
+ titleEl.title = relPath;
+ titleEl.textContent = relPath.split('/').pop();
+ }
+ const badgeEl = document.getElementById('drawerSourceBadge');
+ if (badgeEl) badgeEl.textContent = '';
+ document.getElementById('drawerBody').innerHTML =
+ '离线快照未内嵌此片段
';
+ return;
+ }
+ renderDrawerRows(relPath, snip.lines, start, end, false, snip.totalLines);
+ }
+
+ window.__openSource = (relPath, start, end) => openSourceDrawer(relPath, start, end, false);
+
+ // ─── Command-K (⌘K / /) Universal Search Palette ───
+ const cmdkInput = document.getElementById('cmdkInput');
+ const cmdkList = document.getElementById('cmdkList');
+ let cmdkActions = [];
+ let cmdkSelectedIdx = 0;
+
+ function openCmdk() {
+ cmdkBackdrop.classList.add('open');
+ cmdkInput.value = '';
+ renderCmdkResults('');
+ setTimeout(() => cmdkInput.focus(), 10);
+ }
+
+ document.getElementById('cmdkTriggerBtn').onclick = openCmdk;
+ cmdkBackdrop.addEventListener('mousedown', (e) => {
+ if (e.target === cmdkBackdrop) cmdkBackdrop.classList.remove('open');
+ });
+
+ function stripMarkdownForSnippet(mdSlice) {
+ return String(mdSlice)
+ .replace(/```mermaid[\s\S]*?```/g, ' ')
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
+ .replace(/\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]/gi, '')
+ .replace(/[#*`>|]/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+ }
+
+ function renderCmdkResults(rawQuery) {
+ const q = rawQuery.trim().toLowerCase();
+ const hits = [];
+
+ // 1. Wiki Chapters (with clean stripped Markdown snippets & relevance score)
+ PORTAL.pages.forEach((p, idx) => {
+ const cleanT = cleanPlainTitle(p.title);
+ if (!q) {
+ hits.push({
+ score: 100 - idx,
+ kind: '章节',
+ icon: 'book',
+ title: cleanT,
+ sub: p.group + ' · ' + p.id,
+ run: () => selectPage(idx),
+ });
+ return;
+ }
+ const titleHit = cleanT.toLowerCase().includes(q) || p.id.toLowerCase().includes(q);
+ const cleanDocText = stripMarkdownForSnippet(p.markdown);
+ const pos = cleanDocText.toLowerCase().indexOf(q);
+ if (titleHit || pos >= 0) {
+ const snippet =
+ pos >= 0
+ ? cleanDocText.slice(Math.max(0, pos - 20), pos + 64)
+ : p.group + ' · ' + p.id;
+ hits.push({
+ score: titleHit ? 92 : 50,
+ kind: '章节',
+ icon: 'book',
+ title: cleanT,
+ sub: snippet,
+ run: () => selectPage(idx),
+ });
+ }
+ });
+
+ // 2. Graph & Cited Source Files + AST Symbols (ranked above generic body prose hits!)
+ if (q.length >= 2) {
+ for (const n of PORTAL.graph.nodes) {
+ const lowerPath = n.path.toLowerCase();
+ const lowerBase = n.label.toLowerCase();
+ if (lowerPath.includes(q)) {
+ hits.push({
+ score: lowerBase.startsWith(q) ? 98 : 84,
+ kind: '源码',
+ icon: 'fileCode',
+ title: n.label,
+ sub: n.path,
+ run: () => openSourceDrawer(n.path, 1, 45, false),
+ });
+ }
+ for (const s of n.symbols) {
+ const lowerSig = s.sig.toLowerCase();
+ if (lowerSig.includes(q)) {
+ const lnMatch = s.span.match(/L(\d+)(?:-L(\d+))?/);
+ const st = lnMatch ? parseInt(lnMatch[1], 10) : 1;
+ const ed = lnMatch && lnMatch[2] ? parseInt(lnMatch[2], 10) : st + 25;
+ hits.push({
+ score: 88,
+ kind: '符号',
+ icon: 'code',
+ title: s.sig.slice(0, 68),
+ sub: n.path + ':' + s.span.replace(/^L(\d+)-L\1$/, 'L$1'),
+ run: () => openSourceDrawer(n.path, st, ed, false),
+ });
+ }
+ }
+ }
+ }
+
+ hits.sort((a, b) => b.score - a.score);
+ cmdkActions = hits.slice(0, 18);
+ cmdkSelectedIdx = 0;
+ const countEl = document.getElementById('cmdkResultCount');
+ if (countEl) countEl.textContent = String(cmdkActions.length);
+
+ if (cmdkActions.length === 0) {
+ cmdkList.innerHTML = '无匹配结果
';
+ return;
+ }
+
+ cmdkList.innerHTML = cmdkActions
+ .map(
+ (item, idx) =>
+ '' +
+ icon(item.icon, 13) +
+ '' +
+ esc(item.title) +
+ '
' +
+ esc(item.sub) +
+ '
' +
+ esc(item.kind) +
+ ' ',
+ )
+ .join('');
+
+ cmdkList.querySelectorAll('.cmdk-item').forEach((el) => {
+ el.onclick = () => {
+ const idx = Number(el.getAttribute('data-cidx'));
+ cmdkBackdrop.classList.remove('open');
+ cmdkActions[idx]?.run();
+ };
+ });
+ }
+
+ cmdkInput.addEventListener('input', () => renderCmdkResults(cmdkInput.value));
+ cmdkInput.addEventListener('keydown', (e) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ if (cmdkActions.length > 0) {
+ cmdkSelectedIdx = (cmdkSelectedIdx + 1) % cmdkActions.length;
+ cmdkList.querySelectorAll('.cmdk-item').forEach((el, idx) => el.classList.toggle('selected', idx === cmdkSelectedIdx));
+ }
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ if (cmdkActions.length > 0) {
+ cmdkSelectedIdx = (cmdkSelectedIdx - 1 + cmdkActions.length) % cmdkActions.length;
+ cmdkList.querySelectorAll('.cmdk-item').forEach((el, idx) => el.classList.toggle('selected', idx === cmdkSelectedIdx));
+ }
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ if (cmdkActions[cmdkSelectedIdx]) {
+ cmdkBackdrop.classList.remove('open');
+ cmdkActions[cmdkSelectedIdx].run();
+ }
+ }
+ });
+
+ window.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
+ e.preventDefault();
+ openCmdk();
+ return;
+ }
+ if (e.key === '/' && document.activeElement !== cmdkInput && document.activeElement?.tagName !== 'INPUT') {
+ e.preventDefault();
+ openCmdk();
+ return;
+ }
+ if (e.key === 'Escape') {
+ closeAllOverlays();
+ }
+ });
+
+ // ─── Ultra-Minimal Sync View ───
+ window.__triggerRescan = async () => {
+ if (!isHttpProtocol) return;
+ try {
+ const res = await fetch('/api/rescan', { method: 'POST' });
+ if (res.ok) {
+ const d = await res.json();
+ showToast((d.elapsedMs ?? 0) + 'ms');
+ }
+ } catch {
+ showToast('离线模式');
+ }
+ };
+
+ function renderSyncDashboard() {
+ const shell = document.getElementById('syncShell');
+ const stalePages = PORTAL.sync?.stalePages || [];
+ const scanMs = PORTAL.sync?.lastScanMs ?? PORTAL.stats.elapsedMs ?? 0;
+
+ const staleSectionHtml =
+ stalePages.length > 0
+ ? '待同步
' +
+ stalePages
+ .map((sp) => {
+ const pIdx = PORTAL.pages.findIndex((p) => p.id === sp.page);
+ return (
+ '' +
+ '
' +
+ esc(sp.page) +
+ '
' +
+ '
' +
+ '' +
+ (pIdx >= 0
+ ? ''
+ : '') +
+ '
'
+ );
+ })
+ .join('') +
+ ''
+ : '';
+
+ // "feat(tui): add X" -> [feat] [tui] add X, with Notion-coloured tags per commit type.
+ const COMMIT_COLORS = {
+ feat: 'green', fix: 'red', refactor: 'purple', perf: 'orange', test: 'yellow',
+ docs: 'blue', style: 'pink', build: 'brown', ci: 'brown', chore: 'gray', revert: 'red',
+ };
+ const commitSubjectHtml = (subject) => {
+ if (!subject) return '';
+ const m = String(subject).match(/^(\w+)(?:\(([^)]+)\))?!?:\s*(.*)$/);
+ const textSpan = (t) =>
+ '' + esc(t) + '';
+ if (!m) return textSpan(subject);
+ const c = COMMIT_COLORS[m[1].toLowerCase()] || 'gray';
+ return (
+ '' + esc(m[1]) + '' +
+ (m[2] ? '' + esc(m[2]) + '' : '') +
+ textSpan(m[3])
+ );
+ };
+ // One row per commit: older manifests may hold several entries for the same HEAD.
+ const historyItems = [];
+ const seenHeads = new Set();
+ for (const h of PORTAL.sync?.syncHistory || []) {
+ if (seenHeads.has(h.gitHead)) continue;
+ seenHeads.add(h.gitHead);
+ historyItems.push(h);
+ }
+ // "L116-L191" -> "116–191", "L12-L12" -> "12"
+ const spanText = (span) => {
+ const m = String(span || '').match(/^L(\d+)(?:-L(\d+))?$/);
+ if (!m) return '';
+ return !m[2] || m[2] === m[1] ? m[1] : m[1] + '–' + m[2];
+ };
+ const historyHtml =
+ historyItems.length === 0
+ ? '已同步
'
+ : historyItems
+ .slice(0, 10)
+ .map((h) => {
+ const seenChip = new Set();
+ const uniqueDetails = (h.reanchoredDetails || []).filter((d) => {
+ const k = d.file + ':' + d.symbol + ':' + d.to;
+ if (seenChip.has(k)) return false;
+ seenChip.add(k);
+ return true;
+ });
+ const details = uniqueDetails
+ .slice(0, 8)
+ .map((d) => {
+ const fileName = d.file.split('/').pop();
+ if (d.symbol === '(renamed)') {
+ return (
+ ''
+ );
+ }
+ const fromText = spanText(d.from);
+ const toText = spanText(d.to);
+ const st = parseInt(String(d.to).slice(1), 10) || 1;
+ const ed = parseInt(String(d.to).split('-L')[1], 10) || st + 30;
+ const symbolText = d.symbol && !String(d.symbol).startsWith('(') ? d.symbol : '';
+ return (
+ ''
+ );
+ })
+ .join('');
+ return (
+ '' +
+ '
' +
+ '
' +
+ '' +
+ esc(h.gitHead) +
+ '' +
+ commitSubjectHtml(h.commitSubject) +
+ '
' +
+ esc((h.elapsedMs ?? 0) + 'ms') +
+ '' +
+ (details ? '
' + details + '
' : '') +
+ '
'
+ );
+ })
+ .join('');
+
+ const logItems = PORTAL.activityLog || [];
+ const logSectionHtml =
+ logItems.length > 0
+ ? '动态
' +
+ logItems
+ .slice(0, 12)
+ .map(
+ (ev) =>
+ '' +
+ esc(ev.message) +
+ '' +
+ esc(ev.time) +
+ '
',
+ )
+ .join('') +
+ ''
+ : '';
+
+ const dotColor = liveConnected
+ ? stalePages.length > 0
+ ? 'var(--live-warn)'
+ : 'var(--live-ok)'
+ : 'var(--text-faint)';
+
+ shell.innerHTML =
+ '' +
+ '
' +
+ '' +
+ (liveConnected ? '在线' : '离线') +
+ '' +
+ '/' +
+ '' +
+ PORTAL.stats.fileCount.toLocaleString() +
+ ' 文件' +
+ '/' +
+ '' +
+ (PORTAL.pages.length - stalePages.length) +
+ ' / ' +
+ PORTAL.pages.length +
+ '' +
+ '/' +
+ '' +
+ scanMs +
+ 'ms' +
+ '
' +
+ '
' +
+ (liveConnected
+ ? '' +
+ (stalePages.length > 0
+ ? ''
+ : '')
+ : '') +
+ '
' +
+ staleSectionHtml +
+ '记录
' +
+ historyHtml +
+ '' +
+ logSectionHtml;
+ }
+
+ // ─── Server-Sent Events (SSE) Real-Time Client ───
+ function connectLiveEventStream() {
+ if (!isHttpProtocol) return;
+ let es;
+ try {
+ es = new EventSource('/api/events');
+ } catch {
+ return;
+ }
+
+ es.addEventListener('connected', (ev) => {
+ liveConnected = true;
+ try {
+ const data = JSON.parse(ev.data);
+ if (data.sync) PORTAL.sync = data.sync;
+ if (data.gitHead) PORTAL.gitHead = data.gitHead;
+ if (Array.isArray(data.activityLog)) PORTAL.activityLog = data.activityLog;
+ } catch {
+ // Ignore malformed
+ }
+ refreshHeaderMeta();
+ renderSidebar();
+ if (activeView === 'sync') renderSyncDashboard();
+ });
+
+ es.addEventListener('repo_changed', (ev) => {
+ try {
+ const data = JSON.parse(ev.data);
+ if (data.stats) PORTAL.stats = data.stats;
+ if (data.gitHead) PORTAL.gitHead = data.gitHead;
+ if (data.sync) PORTAL.sync = data.sync;
+ if (data.activityEntry) PORTAL.activityLog.unshift(data.activityEntry);
+ if (data.graph || data.descriptions) {
+ if (data.graph) PORTAL.graph = data.graph;
+ if (data.descriptions) PORTAL.descriptions = data.descriptions;
+ if (window.RepoWikiGraph) window.RepoWikiGraph.update({ graph: data.graph, descriptions: data.descriptions });
+ }
+ refreshHeaderMeta();
+ renderSidebar();
+ if (activeView === 'wiki') renderCurrentPage(true);
+ if (activeView === 'sync') renderSyncDashboard();
+ if (activeDrawerCtx && codeDrawer.classList.contains('open')) {
+ openSourceDrawer(
+ activeDrawerCtx.relPath,
+ activeDrawerCtx.start,
+ activeDrawerCtx.end,
+ activeDrawerCtx.fullFile,
+ );
+ }
+ if (data.toast) showToast(data.toast);
+ } catch {
+ // Ignore parse error
+ }
+ });
+
+ es.addEventListener('wiki_updated', (ev) => {
+ try {
+ const data = JSON.parse(ev.data);
+ const curPageId = PORTAL.pages[activePageIdx]?.id;
+ if (Array.isArray(data.pages) && data.pages.length > 0) {
+ PORTAL.pages = data.pages;
+ const newIdx = PORTAL.pages.findIndex((p) => p.id === curPageId);
+ activePageIdx = newIdx >= 0 ? newIdx : 0;
+ }
+ if (data.sync) PORTAL.sync = data.sync;
+ if (data.activityEntry) PORTAL.activityLog.unshift(data.activityEntry);
+ if (data.descriptions) {
+ PORTAL.descriptions = data.descriptions;
+ if (window.RepoWikiGraph) window.RepoWikiGraph.update({ descriptions: data.descriptions });
+ }
+ refreshHeaderMeta();
+ renderSidebar();
+ if (activeView === 'wiki') renderCurrentPage(true);
+ if (activeView === 'sync') renderSyncDashboard();
+ if (data.toast) showToast(data.toast);
+ } catch {
+ // Ignore parse error
+ }
+ });
+
+ es.onerror = () => {
+ liveConnected = false;
+ refreshHeaderMeta();
+ };
+ }
+
+ refreshHeaderMeta();
+ renderSidebar();
+ renderCurrentPage(false);
+ connectLiveEventStream();
+})();
diff --git a/plugins/Jialei-03/mcode-repowiki/server/portal-graph.js b/plugins/Jialei-03/mcode-repowiki/server/portal-graph.js
new file mode 100644
index 00000000..e4d9a7cb
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/portal-graph.js
@@ -0,0 +1,822 @@
+/*
+ * RepoWiki dependency graph — standalone front-end module.
+ *
+ * Reads PORTAL.graph (nodes/links) and, when present, PORTAL.descriptions
+ * ({ files, modules }). Owns #graphToolbar, #depCanvas, #graphLegend and
+ * #graphInspector. The reader shell talks to it only through:
+ * window.RepoWikiGraph.show() — graph tab became visible
+ * window.RepoWikiGraph.redraw() — theme changed
+ * window.RepoWikiGraph.update(d) — live data ({ graph?, descriptions? })
+ * and it calls back only window.__openSource(path, start, end) / window.__goPage(idx).
+ */
+(() => {
+ // One clear hue per module; brightness encodes importance (see nodeColor).
+ const PALETTE = ['blue', 'orange', 'purple', 'green', 'pink', 'yellow', 'red', 'brown', 'gray']; // Notion colour names (--n-*)
+ const hueVar = (g) => 'var(--n-' + PALETTE[groups.indexOf(g) % PALETTE.length] + ')';
+ const hexRgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
+ const mixHex = (a, b, t) => {
+ const A = hexRgb(a);
+ const B = hexRgb(b);
+ return 'rgb(' + A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(',') + ')';
+ };
+ const SVG = {
+ plus: '',
+ minus: '',
+ fit: '',
+ back: '',
+ search: '',
+ };
+ const svg = (name, size = 13) =>
+ '';
+ const esc = (s) =>
+ String(s ?? '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
+ const jsArg = (s) => String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'");
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
+ const easeOut = (t) => 1 - Math.pow(1 - t, 3);
+
+ // ─── Data ───
+ let nodes = [];
+ let links = [];
+ let byPath = new Map();
+ let groups = [];
+ let desc = { files: {}, modules: {} };
+
+ function load(graph, keepPositions) {
+ const old = keepPositions ? byPath : new Map();
+ nodes = (graph.nodes || []).map((n) => {
+ const prev = old.get(n.path);
+ return Object.assign({}, n, {
+ x: prev ? prev.x : 0,
+ y: prev ? prev.y : 0,
+ vx: 0,
+ vy: 0,
+ fx: null,
+ fy: null,
+ nbrs: new Set(),
+ placed: Boolean(prev),
+ });
+ });
+ byPath = new Map(nodes.map((n) => [n.path, n]));
+ links = (graph.links || [])
+ .map((l) => ({ s: nodes[l.source], t: nodes[l.target] }))
+ .filter((l) => l.s && l.t && l.s !== l.t);
+ for (const l of links) {
+ l.s.nbrs.add(l.t);
+ l.t.nbrs.add(l.s);
+ }
+ groups = [...new Set(nodes.map((n) => n.group))];
+ const counts = new Map();
+ for (const n of nodes) counts.set(n.group + '|' + n.label, (counts.get(n.group + '|' + n.label) || 0) + 1);
+ const maxFan = Math.max(1, ...nodes.map((n) => n.fanIn));
+ for (const n of nodes) {
+ if (counts.get(n.group + '|' + n.label) > 1) n.label = n.path.split('/').slice(-2).join('/');
+ n.r = 3.2 + Math.sqrt(n.fanIn / maxFan) * 9;
+ n.hueIdx = groups.indexOf(n.group) % PALETTE.length;
+ // 0..1, log-scaled: a file imported 600 times should not wash every other file out
+ n.weight = Math.log1p(n.fanIn) / Math.log1p(maxFan);
+ if (!n.placed) {
+ const a = (groups.indexOf(n.group) / Math.max(1, groups.length)) * Math.PI * 2;
+ const rad = 160 + Math.random() * 60;
+ n.x = Math.cos(a) * rad + (Math.random() - 0.5) * 60;
+ n.y = Math.sin(a) * rad + (Math.random() - 0.5) * 60;
+ }
+ }
+ // Labels always shown when zoomed out: the most depended-on files.
+ const top = [...nodes].sort((a, b) => b.fanIn - a.fanIn).slice(0, 10);
+ for (const n of nodes) n.landmark = top.includes(n);
+ }
+
+ const fileDesc = (p) => (desc.files && desc.files[p]) || '';
+ const moduleDesc = (g) => (desc.modules && desc.modules[g]) || '';
+ function exportsHint(n) {
+ if (!n || !n.symbols) return '';
+ const names = [];
+ for (const s of n.symbols) {
+ const m = String(s.sig).match(/\b(?:function|class|interface|type|enum|const|let|var|def|struct|trait|fn)\s+([A-Za-z_$][\w$]*)/);
+ if (m && !names.includes(m[1])) names.push(m[1]);
+ if (names.length >= 4) break;
+ }
+ return names.length ? '导出 ' + names.join('、') : '';
+ }
+
+ // ─── Force simulation (live, d3-style) ───
+ let alpha = 1;
+ const ALPHA_MIN = 0.002;
+ const ALPHA_DECAY = 0.022;
+
+ function tick() {
+ const n = nodes.length;
+ const cent = new Map();
+ for (const g of groups) cent.set(g, { x: 0, y: 0, c: 0 });
+ for (const a of nodes) {
+ const c = cent.get(a.group);
+ c.x += a.x;
+ c.y += a.y;
+ c.c += 1;
+ }
+ for (let i = 0; i < n; i++) {
+ const a = nodes[i];
+ // weak gravity + pull toward own module centre (clusters, like Obsidian groups)
+ const c = cent.get(a.group);
+ a.vx += (-a.x * 0.006 + (c.x / c.c - a.x) * 0.02) * alpha;
+ a.vy += (-a.y * 0.006 + (c.y / c.c - a.y) * 0.02) * alpha;
+ for (let j = i + 1; j < n; j++) {
+ const b = nodes[j];
+ let dx = b.x - a.x;
+ let dy = b.y - a.y;
+ if (dx === 0 && dy === 0) {
+ dx = Math.random() - 0.5;
+ dy = Math.random() - 0.5;
+ }
+ const d2 = dx * dx + dy * dy;
+ if (d2 > 160000) continue;
+ const d = Math.sqrt(d2);
+ const f = (-900 * alpha) / Math.max(d2, 64);
+ a.vx += (dx / d) * f;
+ a.vy += (dy / d) * f;
+ b.vx -= (dx / d) * f;
+ b.vy -= (dy / d) * f;
+ const minD = a.r + b.r + 6;
+ if (d < minD) {
+ const push = ((minD - d) / d) * 0.5;
+ a.x -= dx * push;
+ a.y -= dy * push;
+ b.x += dx * push;
+ b.y += dy * push;
+ }
+ }
+ }
+ for (const l of links) {
+ const dx = l.t.x - l.s.x;
+ const dy = l.t.y - l.s.y;
+ const d = Math.sqrt(dx * dx + dy * dy) || 1;
+ const target = l.s.group === l.t.group ? 46 : 110;
+ const k = ((d - target) / d) * 0.06 * alpha;
+ l.s.vx += dx * k;
+ l.s.vy += dy * k;
+ l.t.vx -= dx * k;
+ l.t.vy -= dy * k;
+ }
+ for (const a of nodes) {
+ if (a.fx !== null) {
+ a.x = a.fx;
+ a.y = a.fy;
+ a.vx = a.vy = 0;
+ continue;
+ }
+ a.vx *= 0.58;
+ a.vy *= 0.58;
+ a.x += a.vx;
+ a.y += a.vy;
+ }
+ alpha = Math.max(0, alpha - alpha * ALPHA_DECAY);
+ }
+
+ // ─── View state ───
+ let canvas = null;
+ let ctx = null;
+ let W = 0;
+ let H = 0;
+ let cam = { x: 0, y: 0, k: 1 };
+ let camAnim = null;
+ let selected = null; // node
+ let hovered = null; // node
+ let hoverGroup = ''; // legend / list hover
+ let activeGroup = ''; // locked module filter
+ let query = '';
+ let fade = 0; // 0..1 highlight strength (animated)
+ let fadeTarget = 0;
+ let theme = {};
+ let raf = 0;
+ let mounted = false;
+ let visible = false;
+
+ function readTheme() {
+ const cs = getComputedStyle(document.documentElement);
+ const v = (name, fb) => (cs.getPropertyValue(name) || '').trim() || fb;
+ const dark = document.documentElement.getAttribute('data-theme') !== 'light';
+ theme = {
+ dark,
+ bg: v('--diagram-bg', dark ? '#181818' : '#fafafa'),
+ strong: dark ? '#f2f2f2' : '#141414',
+ text: dark ? '#d4d4d4' : '#262626',
+ faint: dark ? '#737373' : '#8a8a8a',
+ link: dark ? 'rgba(255,255,255,' : 'rgba(0,0,0,',
+ palette: PALETTE.map((name) => v('--n-' + name, '#888888')),
+ };
+ }
+
+ // Module hue, faded toward the canvas background for rarely-imported files.
+ function nodeColor(n) {
+ const bg = /^#[0-9a-f]{6}$/i.test(theme.bg) ? theme.bg : theme.dark ? '#181818' : '#fafafa';
+ return mixHex(bg, theme.palette[n.hueIdx] || '#888888', 0.28 + 0.72 * n.weight);
+ }
+
+ function resize() {
+ const rect = canvas.parentElement.getBoundingClientRect();
+ if (rect.width === 0) return false;
+ const dpr = window.devicePixelRatio || 1;
+ W = rect.width;
+ H = rect.height;
+ canvas.width = Math.round(W * dpr);
+ canvas.height = Math.round(H * dpr);
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ return true;
+ }
+
+ const toScreen = (x, y) => ({ x: W / 2 + cam.x + x * cam.k, y: H / 2 + cam.y + y * cam.k });
+ const toWorld = (sx, sy) => ({ x: (sx - W / 2 - cam.x) / cam.k, y: (sy - H / 2 - cam.y) / cam.k });
+
+ function boundsOf(list) {
+ if (!list.length) return null;
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const n of list) {
+ x0 = Math.min(x0, n.x - n.r);
+ y0 = Math.min(y0, n.y - n.r);
+ x1 = Math.max(x1, n.x + n.r);
+ y1 = Math.max(y1, n.y + n.r + 14);
+ }
+ return { x0, y0, x1, y1 };
+ }
+
+ function glideTo(target, ms = 420) {
+ camAnim = { from: Object.assign({}, cam), to: target, t0: performance.now(), ms };
+ loop();
+ }
+
+ function fitTo(list, animate = true) {
+ const b = boundsOf(list);
+ if (!b || !W) return;
+ const pad = 70;
+ const k = Math.max(0.3, Math.min(2.2, Math.min((W - pad * 2) / Math.max(60, b.x1 - b.x0), (H - pad * 2 - 40) / Math.max(60, b.y1 - b.y0))));
+ const target = { k, x: -((b.x0 + b.x1) / 2) * k, y: -((b.y0 + b.y1) / 2) * k - 16 };
+ if (animate) glideTo(target);
+ else cam = target;
+ }
+
+ function focusNode(n) {
+ const k = Math.max(cam.k, 1.25);
+ glideTo({ k, x: -n.x * k, y: -n.y * k });
+ }
+
+ // ─── Highlight logic ───
+ function emphasis() {
+ // Returns a predicate for "fully visible" nodes, or null when nothing is emphasised.
+ const focus = hovered || selected;
+ if (focus) {
+ return (n) => n === focus || focus.nbrs.has(n);
+ }
+ const g = hoverGroup || activeGroup;
+ if (g) return (n) => n.group === g;
+ if (query) {
+ const q = query.toLowerCase();
+ return (n) => n.path.toLowerCase().includes(q) || fileDesc(n.path).toLowerCase().includes(q);
+ }
+ return null;
+ }
+
+ function draw() {
+ if (!ctx || !W) return;
+ ctx.clearRect(0, 0, W, H);
+ const isOn = emphasis();
+ const focus = hovered || selected;
+ const f = fade;
+ const dimNode = 1 - 0.85 * f;
+ const dimLink = 1 - 0.9 * f;
+
+ ctx.save();
+ ctx.translate(W / 2 + cam.x, H / 2 + cam.y);
+ ctx.scale(cam.k, cam.k);
+
+ // links
+ ctx.lineWidth = 0.7 / cam.k;
+ for (const l of links) {
+ const hot = isOn && (focus ? l.s === focus || l.t === focus : isOn(l.s) && isOn(l.t));
+ const a = hot ? 0.16 + 0.5 * f : 0.12 * (isOn ? dimLink : 1);
+ ctx.strokeStyle = (hot && focus ? (theme.dark ? 'rgba(242,242,242,' : 'rgba(20,20,20,') : theme.link) + a + ')';
+ ctx.lineWidth = (hot && focus ? 1.2 : 0.7) / cam.k;
+ ctx.beginPath();
+ ctx.moveTo(l.s.x, l.s.y);
+ ctx.lineTo(l.t.x, l.t.y);
+ ctx.stroke();
+ }
+
+ // nodes
+ for (const n of nodes) {
+ const on = !isOn || isOn(n);
+ ctx.globalAlpha = on ? 1 : dimNode;
+ ctx.beginPath();
+ ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
+ ctx.fillStyle = n === focus ? theme.strong : nodeColor(n);
+ ctx.fill();
+ if (n === selected) {
+ ctx.lineWidth = 2 / cam.k;
+ ctx.strokeStyle = theme.strong;
+ ctx.beginPath();
+ ctx.arc(n.x, n.y, n.r + 3 / cam.k, 0, Math.PI * 2);
+ ctx.stroke();
+ }
+ }
+ ctx.globalAlpha = 1;
+ ctx.restore();
+
+ // module names at cluster centres when zoomed out (semantic zoom)
+ const modAlpha = clamp01((1.1 - cam.k) / 0.35);
+ if (modAlpha > 0.02 && !focus) {
+ ctx.font = '500 12.5px Inter, -apple-system, sans-serif';
+ ctx.textAlign = 'center';
+ for (const g of groups) {
+ const members = nodes.filter((n) => n.group === g);
+ if (members.length < 2) continue;
+ const cx = members.reduce((s, n) => s + n.x, 0) / members.length;
+ const cy = members.reduce((s, n) => s + n.y, 0) / members.length;
+ const p = toScreen(cx, cy);
+ const on = !isOn || members.some(isOn);
+ ctx.globalAlpha = modAlpha * (on ? 0.9 : 0.25);
+ ctx.fillStyle = theme.strong;
+ ctx.fillText(g.split('/').pop(), p.x, p.y);
+ }
+ ctx.globalAlpha = 1;
+ }
+
+ // file labels (fixed screen size, below the node like Obsidian)
+ ctx.textAlign = 'center';
+ const zoomAlpha = clamp01((cam.k - 1.15) / 0.4);
+ const placed = [];
+ const order = [...nodes].sort((a, b) => b.fanIn - a.fanIn);
+ if (focus) order.sort((a, b) => Number(b === focus) - Number(a === focus));
+ for (const n of order) {
+ const on = !isOn || isOn(n);
+ let a;
+ if (isOn && on && (focus || hoverGroup || activeGroup || query)) a = 1;
+ else if (n.landmark && cam.k > 0.55 && !focus) a = Math.max(zoomAlpha, 1 - modAlpha);
+ else a = zoomAlpha;
+ if (!on) a *= 0.15;
+ if (a < 0.04) continue;
+ const p = toScreen(n.x, n.y + n.r);
+ const isFocus = n === focus;
+ ctx.font = (isFocus ? '600 12px' : '400 11px') + ' Inter, -apple-system, sans-serif';
+ const w = ctx.measureText(n.label).width;
+ const box = { x0: p.x - w / 2 - 3, x1: p.x + w / 2 + 3, y0: p.y + 3, y1: p.y + 17 };
+ if (box.x1 < 0 || box.x0 > W || box.y0 > H || box.y1 < 0) continue;
+ if (!isFocus && placed.some((q) => box.x0 < q.x1 && box.x1 > q.x0 && box.y0 < q.y1 && box.y1 > q.y0)) continue;
+ placed.push(box);
+ ctx.globalAlpha = a;
+ ctx.fillStyle = isFocus ? theme.strong : theme.text;
+ ctx.fillText(n.label, p.x, p.y + 14);
+ }
+ ctx.globalAlpha = 1;
+ ctx.textAlign = 'start';
+ }
+
+ function loop() {
+ if (raf) return;
+ const step = (now) => {
+ raf = 0;
+ let busy = false;
+ if (alpha > ALPHA_MIN) {
+ tick();
+ busy = true;
+ }
+ if (camAnim) {
+ const t = clamp01((now - camAnim.t0) / camAnim.ms);
+ const e = easeOut(t);
+ cam = {
+ k: camAnim.from.k + (camAnim.to.k - camAnim.from.k) * e,
+ x: camAnim.from.x + (camAnim.to.x - camAnim.from.x) * e,
+ y: camAnim.from.y + (camAnim.to.y - camAnim.from.y) * e,
+ };
+ if (t >= 1) camAnim = null;
+ busy = true;
+ }
+ fadeTarget = emphasis() ? 1 : 0;
+ if (Math.abs(fade - fadeTarget) > 0.01) {
+ fade += (fadeTarget - fade) * 0.25;
+ busy = true;
+ } else fade = fadeTarget;
+ if (visible) draw();
+ if (busy && visible) raf = requestAnimationFrame(step);
+ };
+ raf = requestAnimationFrame(step);
+ }
+
+ const reheat = (a = 0.3) => {
+ alpha = Math.max(alpha, a);
+ loop();
+ };
+
+ // ─── Toolbar & legend ───
+ function renderToolbar() {
+ const el = document.getElementById('graphToolbar');
+ el.innerHTML =
+ '' +
+ '' +
+ '' +
+ '';
+ el.querySelector('[data-act=in]').onclick = () => glideTo({ k: Math.min(4, cam.k * 1.3), x: cam.x * 1.3, y: cam.y * 1.3 }, 220);
+ el.querySelector('[data-act=out]').onclick = () => glideTo({ k: Math.max(0.2, cam.k / 1.3), x: cam.x / 1.3, y: cam.y / 1.3 }, 220);
+ el.querySelector('[data-act=fit]').onclick = () => fitTo(activeGroup ? nodes.filter((n) => n.group === activeGroup) : nodes);
+ const input = el.querySelector('#graphSearch');
+ input.oninput = () => {
+ query = input.value.trim();
+ if (query) {
+ selected = null;
+ activeGroup = '';
+ }
+ renderLegend();
+ renderInspector();
+ loop();
+ };
+ input.onkeydown = (e) => {
+ if (e.key === 'Escape') {
+ input.value = '';
+ input.oninput();
+ input.blur();
+ }
+ if (e.key === 'Enter') {
+ const q = query.toLowerCase();
+ const hit = nodes.filter((n) => n.path.toLowerCase().includes(q)).sort((a, b) => b.fanIn - a.fanIn)[0];
+ if (hit) selectNode(hit, true);
+ }
+ e.stopPropagation();
+ };
+ }
+
+ function renderLegend() {
+ const el = document.getElementById('graphLegend');
+ el.innerHTML = groups
+ .map(
+ (g) =>
+ '',
+ )
+ .join('');
+ el.querySelectorAll('.g-pill').forEach((b) => {
+ const g = b.getAttribute('data-g');
+ b.onmouseenter = () => {
+ hoverGroup = g;
+ loop();
+ };
+ b.onmouseleave = () => {
+ hoverGroup = '';
+ loop();
+ };
+ b.onclick = () => (activeGroup === g ? showOverview() : openModule(g));
+ });
+ }
+
+ // ─── Inspector (lists) ───
+ function row(path, opts = {}) {
+ const n = byPath.get(path);
+ const parts = path.split('/');
+ const name = parts.pop();
+ const dir = parts.slice(-2).join('/');
+ const d = fileDesc(path) || (n ? exportsHint(n) : '');
+ return (
+ ''
+ );
+ }
+
+ function bindRows(el) {
+ el.querySelectorAll('.gi-row[data-path]').forEach((b) => {
+ const p = b.getAttribute('data-path');
+ const n = byPath.get(p);
+ b.onmouseenter = () => {
+ if (n) {
+ hovered = n;
+ loop();
+ }
+ };
+ b.onmouseleave = () => {
+ if (hovered === n) {
+ hovered = null;
+ loop();
+ }
+ };
+ b.onclick = () => {
+ if (n) selectNode(n, true);
+ else window.__openSource && window.__openSource(p, 1, 60);
+ };
+ });
+ el.querySelectorAll('[data-module]').forEach((b) => {
+ const g = b.getAttribute('data-module');
+ b.onmouseenter = () => {
+ hoverGroup = g;
+ loop();
+ };
+ b.onmouseleave = () => {
+ hoverGroup = '';
+ loop();
+ };
+ b.onclick = () => openModule(g);
+ });
+ const back = el.querySelector('[data-back]');
+ if (back) back.onclick = () => (back.getAttribute('data-back') ? openModule(back.getAttribute('data-back')) : showOverview());
+ }
+
+ function moduleStats(g) {
+ const out = new Set();
+ const inn = new Set();
+ for (const l of links) {
+ if (l.s.group === g && l.t.group !== g) out.add(l.t.group);
+ if (l.t.group === g && l.s.group !== g) inn.add(l.s.group);
+ }
+ return { dependsOn: out.size, dependedBy: inn.size };
+ }
+
+ function renderInspector() {
+ const el = document.getElementById('graphInspector');
+ if (!el) return;
+ let html = '';
+ if (selected) {
+ const n = selected;
+ const d = fileDesc(n.path);
+ const linkedPageIdx = (PORTAL.pages || []).findIndex((p) => p.referencedFiles && p.referencedFiles.includes(n.path));
+ const importedBy = n.importedBy || [];
+ const imports = n.imports || [];
+ html +=
+ '' +
+ '' + esc(n.path.split('/').pop()) + '
' +
+ '' + esc(n.path) + '
' +
+ (d ? '' + esc(d) + '
' : exportsHint(n) ? '' + esc(exportsHint(n)) + '
' : '') +
+ '' +
+ '' +
+ (linkedPageIdx >= 0 ? '' : '') +
+ '
' +
+ '被引用' + n.fanIn + '
' +
+ (importedBy.length ? importedBy.map((p) => row(p)).join('') : '没有文件引用它
') +
+ (n.fanIn > importedBy.length ? '还有 ' + (n.fanIn - importedBy.length) + ' 个
' : '') +
+ '引用' + n.fanOut + '
' +
+ (imports.length ? imports.map((p) => row(p)).join('') : '不依赖仓库内其他文件
') +
+ (n.fanOut > imports.length ? '还有 ' + (n.fanOut - imports.length) + ' 个
' : '') +
+ (n.symbols && n.symbols.length
+ ? '符号' + n.symbols.length + '
' +
+ n.symbols
+ .map((s) => {
+ const m = String(s.span).match(/L(\d+)(?:-L(\d+))?/);
+ const st = m ? +m[1] : 1;
+ const ed = m && m[2] ? +m[2] : st + 25;
+ return '';
+ })
+ .join('') +
+ ' '
+ : '');
+ el.innerHTML = html;
+ el.querySelector('[data-open-source]').onclick = () => window.__openSource(n.path, 1, 60);
+ const pg = el.querySelector('[data-open-page]');
+ if (pg) pg.onclick = () => window.__goPage(+pg.getAttribute('data-open-page'));
+ el.querySelectorAll('[data-sym]').forEach((b) => {
+ const [st, ed] = b.getAttribute('data-sym').split(',').map(Number);
+ b.onclick = () => window.__openSource(n.path, st, ed);
+ });
+ } else if (activeGroup) {
+ const g = activeGroup;
+ const files = nodes.filter((n) => n.group === g).sort((a, b) => b.fanIn - a.fanIn);
+ const st = moduleStats(g);
+ html +=
+ '' +
+ '' + esc(g) + '
' +
+ (moduleDesc(g) ? '' + esc(moduleDesc(g)) + '
' : '') +
+ '' + files.length + ' 个文件 · 依赖 ' + st.dependsOn + ' 个模块 · 被 ' + st.dependedBy + ' 个模块依赖
' +
+ '文件' + files.length + '
' +
+ files.map((n) => row(n.path, { badge: n.fanIn ? '被引用 ' + n.fanIn : '' })).join('');
+ el.innerHTML = html;
+ } else if (query) {
+ const q = query.toLowerCase();
+ const hits = nodes
+ .filter((n) => n.path.toLowerCase().includes(q) || fileDesc(n.path).toLowerCase().includes(q))
+ .sort((a, b) => b.fanIn - a.fanIn);
+ html +=
+ '匹配' + hits.length + '
' +
+ (hits.length ? hits.slice(0, 60).map((n) => row(n.path)).join('') : '没有匹配的文件
');
+ el.innerHTML = html;
+ } else {
+ const sorted = [...groups].sort((a, b) => nodes.filter((n) => n.group === b).length - nodes.filter((n) => n.group === a).length);
+ html +=
+ '模块' + groups.length + '
' +
+ sorted
+ .map((g) => {
+ const c = nodes.filter((n) => n.group === g).length;
+ return (
+ ''
+ );
+ })
+ .join('');
+ el.innerHTML = html;
+ }
+ bindRows(el);
+ el.scrollTop = 0;
+ }
+
+ // ─── Navigation ───
+ function selectNode(n, glide) {
+ selected = n;
+ hovered = null;
+ activeGroup = '';
+ renderLegend();
+ renderInspector();
+ if (glide) focusNode(n);
+ loop();
+ }
+
+ function openModule(g) {
+ selected = null;
+ hovered = null;
+ activeGroup = g;
+ renderLegend();
+ renderInspector();
+ fitTo(nodes.filter((n) => n.group === g));
+ }
+
+ function showOverview() {
+ selected = null;
+ hovered = null;
+ activeGroup = '';
+ renderLegend();
+ renderInspector();
+ fitTo(nodes);
+ }
+
+ // ─── Pointer interaction ───
+ function hitTest(sx, sy) {
+ const w = toWorld(sx, sy);
+ let best = null;
+ let bestD = Infinity;
+ for (const n of nodes) {
+ const d = Math.hypot(w.x - n.x, w.y - n.y);
+ if (d <= n.r + 5 / cam.k && d < bestD) {
+ best = n;
+ bestD = d;
+ }
+ }
+ return best;
+ }
+
+ function bindPointer() {
+ let drag = null; // { node?, sx, sy, moved, camX, camY }
+ const local = (e) => {
+ const r = canvas.getBoundingClientRect();
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
+ };
+ canvas.addEventListener('pointerdown', (e) => {
+ const p = local(e);
+ const n = hitTest(p.x, p.y);
+ drag = { node: n, sx: p.x, sy: p.y, moved: false, camX: cam.x, camY: cam.y };
+ camAnim = null;
+ canvas.setPointerCapture(e.pointerId);
+ if (n) {
+ n.fx = n.x;
+ n.fy = n.y;
+ }
+ canvas.style.cursor = 'grabbing';
+ });
+ canvas.addEventListener('pointermove', (e) => {
+ const p = local(e);
+ if (drag) {
+ if (Math.hypot(p.x - drag.sx, p.y - drag.sy) > 3) drag.moved = true;
+ if (drag.node) {
+ const w = toWorld(p.x, p.y);
+ drag.node.fx = w.x;
+ drag.node.fy = w.y;
+ if (drag.moved) reheat(0.25);
+ } else {
+ cam.x = drag.camX + (p.x - drag.sx);
+ cam.y = drag.camY + (p.y - drag.sy);
+ loop();
+ }
+ return;
+ }
+ const h = hitTest(p.x, p.y);
+ if (h !== hovered) {
+ hovered = h;
+ canvas.style.cursor = h ? 'pointer' : 'grab';
+ loop();
+ }
+ });
+ const end = (e) => {
+ if (!drag) return;
+ const d = drag;
+ drag = null;
+ if (d.node) {
+ d.node.fx = null;
+ d.node.fy = null;
+ }
+ canvas.style.cursor = hovered ? 'pointer' : 'grab';
+ if (!d.moved) {
+ if (d.node) selectNode(d.node, false);
+ else if (selected) {
+ // click on empty canvas: drop the selection, keep the current zoom
+ selected = null;
+ renderInspector();
+ loop();
+ }
+ }
+ if (e && e.pointerId !== undefined && canvas.hasPointerCapture(e.pointerId)) canvas.releasePointerCapture(e.pointerId);
+ };
+ canvas.addEventListener('pointerup', end);
+ canvas.addEventListener('pointercancel', end);
+ canvas.addEventListener('pointerleave', () => {
+ if (!drag && hovered) {
+ hovered = null;
+ loop();
+ }
+ });
+ canvas.addEventListener('dblclick', (e) => {
+ const p = local(e);
+ const n = hitTest(p.x, p.y);
+ if (n && window.__openSource) window.__openSource(n.path, 1, 60);
+ });
+ canvas.addEventListener(
+ 'wheel',
+ (e) => {
+ e.preventDefault();
+ camAnim = null;
+ const p = local(e);
+ const before = toWorld(p.x, p.y);
+ const factor = Math.exp(-e.deltaY * 0.0016);
+ cam.k = Math.max(0.2, Math.min(5, cam.k * factor));
+ const after = toScreen(before.x, before.y);
+ cam.x += p.x - after.x;
+ cam.y += p.y - after.y;
+ loop();
+ },
+ { passive: false },
+ );
+ window.addEventListener('resize', () => {
+ if (visible && resize()) loop();
+ });
+ }
+
+ // ─── Public API ───
+ function mount() {
+ canvas = document.getElementById('depCanvas');
+ if (!canvas) return false;
+ ctx = canvas.getContext('2d');
+ canvas.style.cursor = 'grab';
+ canvas.style.touchAction = 'none';
+ desc = PORTAL.descriptions || { files: {}, modules: {} };
+ load(PORTAL.graph || { nodes: [], links: [] }, false);
+ // settle the layout before the first frame, then keep it live
+ for (let i = 0; i < 260 && alpha > 0.03; i++) tick();
+ renderToolbar();
+ renderLegend();
+ bindPointer();
+ mounted = true;
+ return true;
+ }
+
+ window.RepoWikiGraph = {
+ show() {
+ visible = true;
+ if (!mounted && !mount()) return;
+ readTheme();
+ if (!resize()) return;
+ if (!this._fitted) {
+ fitTo(nodes, false);
+ this._fitted = true;
+ }
+ renderInspector();
+ loop();
+ },
+ hide() {
+ visible = false;
+ },
+ redraw() {
+ if (!mounted) return;
+ readTheme();
+ loop();
+ },
+ update(data) {
+ if (data && data.descriptions) desc = data.descriptions;
+ if (!mounted) {
+ if (data && data.graph) PORTAL.graph = data.graph;
+ if (data && data.descriptions) PORTAL.descriptions = data.descriptions;
+ return;
+ }
+ if (data && data.graph) {
+ const keepSel = selected && selected.path;
+ load(data.graph, true);
+ selected = keepSel ? byPath.get(keepSel) || null : null;
+ hovered = null;
+ reheat(0.2);
+ }
+ renderLegend();
+ if (visible) renderInspector();
+ loop();
+ },
+ };
+})();
diff --git a/plugins/Jialei-03/mcode-repowiki/server/resolver.mjs b/plugins/Jialei-03/mcode-repowiki/server/resolver.mjs
new file mode 100644
index 00000000..957f5fe9
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/resolver.mjs
@@ -0,0 +1,289 @@
+import path from 'node:path';
+
+const JS_TS_EXTS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.d.ts'];
+
+export function createImportResolver(codeFiles, workspaceMeta) {
+ const exactSet = new Set();
+ const byDir = new Map(); // dir -> [relPath]
+ const byBasename = new Map(); // filename -> [relPath]
+ const bySuffix = []; // for Java/C++ suffix matching
+
+ for (const f of codeFiles) {
+ exactSet.add(f.relPath);
+ const dir = path.posix.dirname(f.relPath);
+ const normDir = dir === '.' ? '' : dir;
+ if (!byDir.has(normDir)) byDir.set(normDir, []);
+ byDir.get(normDir).push(f.relPath);
+
+ const base = path.posix.basename(f.relPath);
+ if (!byBasename.has(base)) byBasename.set(base, []);
+ byBasename.get(base).push(f.relPath);
+ bySuffix.push(f.relPath);
+ }
+
+ // Index monorepo packages by name
+ const npmPkgMap = new Map();
+ const goModules = [];
+ const pythonSubRoots = [];
+ for (const pkg of workspaceMeta?.packages ?? []) {
+ if (pkg.kind === 'npm' && pkg.name) {
+ npmPkgMap.set(pkg.name, pkg);
+ } else if (pkg.kind === 'go' && pkg.name) {
+ goModules.push(pkg);
+ } else if (pkg.kind === 'python' && pkg.dir) {
+ pythonSubRoots.push(pkg.dir);
+ }
+ }
+ // Sort deeper Python subroots first so nearest enclosing subproject wins!
+ pythonSubRoots.sort((a, b) => b.length - a.length);
+ const tsAliases = workspaceMeta?.tsAliases ?? [];
+
+ function tryProbeJsTs(candidateBase) {
+ const clean = path.posix.normalize(candidateBase).replace(/^\.\//u, '');
+ if (exactSet.has(clean)) return clean;
+
+ // Handle TypeScript ESM `.js` / `.mjs` -> `.ts` / `.tsx`
+ const ext = path.posix.extname(clean);
+ if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
+ const stem = clean.slice(0, -ext.length);
+ const tsCandidates = ext === '.jsx'
+ ? ['.tsx', '.ts', '.jsx']
+ : ['.ts', '.tsx', '.mts', '.cts', '.d.ts'];
+ for (const te of tsCandidates) {
+ if (exactSet.has(`${stem}${te}`)) return `${stem}${te}`;
+ }
+ }
+
+ if (!ext) {
+ for (const e of JS_TS_EXTS) {
+ if (exactSet.has(`${clean}${e}`)) return `${clean}${e}`;
+ }
+ for (const e of JS_TS_EXTS) {
+ if (exactSet.has(`${clean}/index${e}`)) return `${clean}/index${e}`;
+ }
+ }
+ return null;
+ }
+
+ function tryProbePython(dottedParts, baseDir = '', fromRelPath = '') {
+ const joined = dottedParts.filter(Boolean).join('/');
+ if (!joined) {
+ const initCandidate = baseDir ? `${baseDir}/__init__.py` : '__init__.py';
+ return exactSet.has(initCandidate) ? initCandidate : null;
+ }
+ const prefixes = [];
+ if (baseDir !== '') {
+ prefixes.push(baseDir);
+ } else {
+ // Check nearest enclosing Python subproject root first (for monorepos / nested projects)
+ if (fromRelPath) {
+ const enclosing = pythonSubRoots.find((sr) => fromRelPath.startsWith(`${sr}/`));
+ if (enclosing) {
+ prefixes.push(`${enclosing}/src`, enclosing);
+ }
+ }
+ prefixes.push('', 'src', 'lib', 'app');
+ }
+ for (const pre of prefixes) {
+ const target = pre ? `${pre}/${joined}` : joined;
+ if (exactSet.has(`${target}.py`)) return `${target}.py`;
+ if (exactSet.has(`${target}.pyi`)) return `${target}.pyi`;
+ if (exactSet.has(`${target}/__init__.py`)) return `${target}/__init__.py`;
+ }
+ return null;
+ }
+
+ /**
+ * Resolve an import entry from `fromFile` into 0..N repository `relPath` targets.
+ */
+ function resolveImport(fromFile, imp) {
+ const spec = imp.specifier;
+ if (!spec) return [];
+ const fromDir = path.posix.dirname(fromFile.relPath);
+ const normFromDir = fromDir === '.' ? '' : fromDir;
+ const lang = fromFile.lang;
+
+ // ── TypeScript / JavaScript ──
+ if (lang === 'typescript' || lang === 'javascript') {
+ if (spec.startsWith('node:') || spec.startsWith('http://') || spec.startsWith('https://')) {
+ return [];
+ }
+ if (spec.startsWith('.')) {
+ const joined = normFromDir ? `${normFromDir}/${spec}` : spec;
+ const hit = tryProbeJsTs(joined);
+ return hit ? [hit] : [];
+ }
+ // tsconfig `paths` aliases (e.g., `@/*` -> `src/*`)
+ for (const alias of tsAliases) {
+ if (alias.aliasPattern.endsWith('/*')) {
+ const prefix = alias.aliasPattern.slice(0, -1); // `@/`
+ if (spec.startsWith(prefix)) {
+ const rest = spec.slice(prefix.length);
+ const targetBase = alias.targetPattern.replace(/\*$/u, rest);
+ const hit = tryProbeJsTs(targetBase);
+ if (hit) return [hit];
+ }
+ } else if (alias.aliasPattern === spec) {
+ const hit = tryProbeJsTs(alias.targetPattern);
+ if (hit) return [hit];
+ }
+ }
+ // Common `@/` convention even if tsconfig omitted
+ if (spec.startsWith('@/')) {
+ const hit = tryProbeJsTs(`src/${spec.slice(2)}`) ?? tryProbeJsTs(spec.slice(2));
+ if (hit) return [hit];
+ }
+ // Monorepo workspace package resolution (`@scope/pkg` or `@scope/pkg/subpath`)
+ for (const [pkgName, pkg] of npmPkgMap.entries()) {
+ if (spec === pkgName) {
+ for (const ep of pkg.entrypoints) {
+ const hit = tryProbeJsTs(ep);
+ if (hit) return [hit];
+ }
+ const fallback =
+ tryProbeJsTs(pkg.dir ? `${pkg.dir}/src/index` : 'src/index') ??
+ tryProbeJsTs(pkg.dir ? `${pkg.dir}/index` : 'index');
+ if (fallback) return [fallback];
+ } else if (spec.startsWith(`${pkgName}/`)) {
+ const sub = spec.slice(pkgName.length + 1);
+ const hit =
+ tryProbeJsTs(pkg.dir ? `${pkg.dir}/src/${sub}` : `src/${sub}`) ??
+ tryProbeJsTs(pkg.dir ? `${pkg.dir}/${sub}` : sub);
+ if (hit) return [hit];
+ }
+ }
+ return [];
+ }
+
+ // ── Python ──
+ if (lang === 'python') {
+ const leadDots = spec.match(/^(\.+)(.*)$/u);
+ if (leadDots) {
+ const upCount = leadDots[1].length - 1;
+ const rest = leadDots[2];
+ let anchor = normFromDir;
+ for (let k = 0; k < upCount; k += 1) {
+ anchor = path.posix.dirname(anchor);
+ if (anchor === '.') anchor = '';
+ }
+ const parts = rest ? rest.split('.') : [];
+ const direct = tryProbePython(parts, anchor);
+ if (direct) return [direct];
+ // Maybe imported symbol is a submodule: `from . import utils`
+ const subHits = [];
+ for (const sym of imp.symbols ?? []) {
+ const sub = tryProbePython([...parts, sym], anchor);
+ if (sub) subHits.push(sub);
+ }
+ return subHits;
+ }
+ const parts = spec.split('.');
+ const direct =
+ tryProbePython(parts, '', fromFile.relPath) ??
+ (normFromDir ? tryProbePython(parts, normFromDir, fromFile.relPath) : null);
+ if (direct) return [direct];
+
+ // `from pkg.sub import module_name`
+ const subHits = [];
+ for (const sym of imp.symbols ?? []) {
+ const sub = tryProbePython([...parts, sym], '', fromFile.relPath);
+ if (sub) subHits.push(sub);
+ }
+ if (subHits.length > 0) return subHits;
+
+ // Progressive prefix fallback: `from pkg.mod import ClassName`
+ if (parts.length > 1) {
+ const parentHit = tryProbePython(parts.slice(0, -1), '', fromFile.relPath);
+ if (parentHit) return [parentHit];
+ }
+ return [];
+ }
+
+ // ── Go ──
+ if (lang === 'go') {
+ for (const gm of goModules) {
+ if (spec === gm.name || spec.startsWith(`${gm.name}/`)) {
+ const sub = spec === gm.name ? '' : spec.slice(gm.name.length + 1);
+ const targetDir = gm.dir ? (sub ? `${gm.dir}/${sub}` : gm.dir) : sub;
+ const files = (byDir.get(targetDir) ?? []).filter((p) => !p.endsWith('_test.go'));
+ return files.slice(0, 6);
+ }
+ }
+ return [];
+ }
+
+ // ── Rust ──
+ if (lang === 'rust') {
+ if (spec.startsWith('mod::')) {
+ const modName = spec.slice(5);
+ const crateSrc = normFromDir || 'src';
+ for (const cand of [
+ `${crateSrc}/${modName}.rs`,
+ `${crateSrc}/${modName}/mod.rs`,
+ `src/${modName}.rs`,
+ `src/${modName}/mod.rs`,
+ ]) {
+ if (exactSet.has(cand)) return [cand];
+ }
+ return [];
+ }
+ const cleaned = spec.replace(/^::/u, '');
+ let anchor = null;
+ let rest = '';
+ if (cleaned.startsWith('crate::')) {
+ // Find nearest `src` ancestor of `fromFile`
+ const srcIdx = fromFile.relPath.lastIndexOf('/src/');
+ anchor = srcIdx >= 0 ? `${fromFile.relPath.slice(0, srcIdx)}/src` : 'src';
+ rest = cleaned.slice(7);
+ } else if (cleaned.startsWith('self::')) {
+ anchor = normFromDir;
+ rest = cleaned.slice(6);
+ } else if (cleaned.startsWith('super::')) {
+ const parent = path.posix.dirname(normFromDir);
+ anchor = parent === '.' ? '' : parent;
+ rest = cleaned.slice(7);
+ }
+ if (anchor !== null) {
+ const segs = rest.split(/::|\{/u)[0].split('::').filter(Boolean);
+ for (let len = segs.length; len >= 1; len -= 1) {
+ const sub = segs.slice(0, len).join('/');
+ const base = anchor ? `${anchor}/${sub}` : sub;
+ if (exactSet.has(`${base}.rs`)) return [`${base}.rs`];
+ if (exactSet.has(`${base}/mod.rs`)) return [`${base}/mod.rs`];
+ }
+ }
+ return [];
+ }
+
+ // ── C / C++ ──
+ if (lang === 'c' || lang === 'cpp') {
+ const relCand = path.posix.normalize(normFromDir ? `${normFromDir}/${spec}` : spec).replace(/^\.\//u, '');
+ if (exactSet.has(relCand)) return [relCand];
+ for (const pre of ['include', 'src', '']) {
+ const c = pre ? `${pre}/${spec}` : spec;
+ if (exactSet.has(c)) return [c];
+ }
+ const base = path.posix.basename(spec);
+ const matches = byBasename.get(base);
+ return matches && matches.length <= 3 ? [matches[0]] : [];
+ }
+
+ // ── Java / Kotlin / C# ──
+ if (lang === 'java' || lang === 'kotlin' || lang === 'csharp') {
+ const cleanSpec = spec.replace(/\.\*$/u, '');
+ const suffixPath = cleanSpec.replace(/\./gu, '/');
+ const exts = lang === 'java' ? ['.java'] : lang === 'kotlin' ? ['.kt', '.kts'] : ['.cs'];
+ for (const e of exts) {
+ const want = `${suffixPath}${e}`;
+ for (const candidate of bySuffix) {
+ if (candidate === want || candidate.endsWith(`/${want}`)) return [candidate];
+ }
+ }
+ return [];
+ }
+
+ return [];
+ }
+
+ return { resolveImport };
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/server/scanner.mjs b/plugins/Jialei-03/mcode-repowiki/server/scanner.mjs
new file mode 100644
index 00000000..458d9ddf
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/scanner.mjs
@@ -0,0 +1,527 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+export const EXT_TO_LANG = Object.freeze({
+ '.ts': 'typescript',
+ '.tsx': 'typescript',
+ '.mts': 'typescript',
+ '.cts': 'typescript',
+ '.js': 'javascript',
+ '.jsx': 'javascript',
+ '.mjs': 'javascript',
+ '.cjs': 'javascript',
+ '.py': 'python',
+ '.pyi': 'python',
+ '.go': 'go',
+ '.rs': 'rust',
+ '.java': 'java',
+ '.kt': 'kotlin',
+ '.kts': 'kotlin',
+ '.c': 'c',
+ '.h': 'c',
+ '.cc': 'cpp',
+ '.cpp': 'cpp',
+ '.cxx': 'cpp',
+ '.hpp': 'cpp',
+ '.hh': 'cpp',
+ '.cs': 'csharp',
+ '.rb': 'ruby',
+ '.swift': 'swift',
+ '.php': 'php',
+});
+
+const IGNORED_DIRS = new Set([
+ '.git',
+ '.hg',
+ '.svn',
+ 'node_modules',
+ 'bower_components',
+ 'vendor',
+ 'third_party',
+ '3rdparty',
+ 'external',
+ 'dist',
+ 'build',
+ 'out',
+ 'target',
+ '.next',
+ '.nuxt',
+ '.svelte-kit',
+ '.turbo',
+ '.cache',
+ '.parcel-cache',
+ 'coverage',
+ '.nyc_output',
+ '__pycache__',
+ '.pytest_cache',
+ '.mypy_cache',
+ '.ruff_cache',
+ '.tox',
+ '.venv',
+ 'venv',
+ 'env',
+ '.eggs',
+ '.gradle',
+ '.idea',
+ '.vscode',
+ '.minimax',
+ '.claude',
+ '.codex',
+ 'pods',
+ 'deriveddata',
+]);
+
+const IGNORED_SUFFIXES = [
+ '.min.js',
+ '.min.mjs',
+ '.bundle.js',
+ '.chunk.js',
+ '.generated.ts',
+ '.generated.js',
+ '.gen.ts',
+ '.gen.go',
+ '.pb.go',
+ '_pb2.py',
+ '.lock',
+];
+
+const MAX_FILE_BYTES = 768 * 1024; // 768 KiB cap to skip generated mega-bundles
+
+export function normalizeRelPath(p) {
+ return p.split(path.sep).join('/').replace(/^\.\//, '');
+}
+
+export function isTestFile(relPath) {
+ const lower = relPath.toLowerCase();
+ const base = path.posix.basename(lower);
+ if (
+ lower.startsWith('test/') ||
+ lower.startsWith('tests/') ||
+ lower.startsWith('__tests__/') ||
+ lower.includes('/test/') ||
+ lower.includes('/tests/') ||
+ lower.includes('/__tests__/') ||
+ lower.includes('/fixtures/') ||
+ lower.includes('/test-fixtures/') ||
+ lower.includes('/testdata/') ||
+ lower.includes('/e2e/')
+ ) {
+ return true;
+ }
+ return (
+ /\.(test|spec|e2e)\.[a-z0-9]+$/u.test(base) ||
+ /^test_.*\.(py|rb|rs|c|cpp)$/u.test(base) ||
+ /.*_test\.(py|go|rs|cpp|cc)$/u.test(base) ||
+ base === 'conftest.py'
+ );
+}
+
+export function classifyRole(relPath) {
+ if (isTestFile(relPath)) return 'test';
+ const lower = relPath.toLowerCase();
+ const base = path.posix.basename(lower);
+ const stem = base.replace(/\.[^.]+$/u, '');
+
+ if (
+ /^(main|cli|index|app|server|wsgi|asgi|manage|program|bootstrap|launcher)$/u.test(stem) &&
+ relPath.split('/').length <= 3
+ ) {
+ return 'entrypoint';
+ }
+ if (lower.includes('/cli/') || lower.startsWith('cli/') || lower.startsWith('bin/') || lower.includes('/cmd/')) {
+ return 'cli';
+ }
+ if (
+ lower.includes('/api/') ||
+ lower.includes('/routes/') ||
+ lower.includes('/router') ||
+ lower.includes('/controllers/') ||
+ lower.includes('/handlers/') ||
+ lower.includes('/http/') ||
+ lower.includes('/rpc/') ||
+ lower.includes('/graphql/')
+ ) {
+ return 'api';
+ }
+ if (
+ lower.includes('/components/') ||
+ lower.includes('/views/') ||
+ lower.includes('/pages/') ||
+ lower.includes('/ui/') ||
+ lower.includes('/tui/') ||
+ lower.includes('/widgets/') ||
+ lower.endsWith('.tsx') ||
+ lower.endsWith('.jsx')
+ ) {
+ return 'ui';
+ }
+ if (lower.startsWith('scripts/') || lower.includes('/scripts/') || lower.startsWith('tools/')) {
+ return 'script';
+ }
+ if (lower.includes('config') || lower.includes('settings') || lower.includes('env')) {
+ return 'config';
+ }
+ return 'core';
+}
+
+function shouldSkipRelPath(relPath, includeTests = true) {
+ if (!relPath) return true;
+ const lower = relPath.toLowerCase();
+ for (const suffix of IGNORED_SUFFIXES) {
+ if (lower.endsWith(suffix)) return true;
+ }
+ const parts = lower.split('/');
+ for (let i = 0; i < parts.length - 1; i += 1) {
+ if (IGNORED_DIRS.has(parts[i])) return true;
+ }
+ // Skip declaration-only outputs if compiled alongside source, except ambient types
+ if (lower.endsWith('.d.ts') && (lower.includes('dist/') || lower.includes('build/'))) {
+ return true;
+ }
+ if (!includeTests && isTestFile(relPath)) return true;
+ return false;
+}
+
+function listFilesViaGit(repoRoot) {
+ try {
+ if (!existsSync(path.join(repoRoot, '.git'))) return null;
+ const out = execFileSync(
+ 'git',
+ ['-C', repoRoot, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'],
+ { maxBuffer: 32 * 1024 * 1024, timeout: 6000, stdio: ['ignore', 'pipe', 'ignore'] },
+ );
+ return out
+ .toString('utf8')
+ .split('\0')
+ .filter(Boolean)
+ .map((p) => p.replace(/\\/gu, '/'));
+ } catch {
+ return null;
+ }
+}
+
+function listFilesViaWalk(repoRoot, maxFiles = 10000) {
+ const results = [];
+ const stack = [''];
+ while (stack.length > 0 && results.length < maxFiles) {
+ const relDir = stack.pop();
+ const absDir = relDir ? path.join(repoRoot, relDir) : repoRoot;
+ let entries;
+ try {
+ entries = readdirSync(absDir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ entries.sort((a, b) => b.name.localeCompare(a.name));
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) continue;
+ if (entry.isDirectory()) {
+ if (IGNORED_DIRS.has(entry.name.toLowerCase()) || entry.name.startsWith('.')) continue;
+ stack.push(relDir ? `${relDir}/${entry.name}` : entry.name);
+ } else if (entry.isFile()) {
+ results.push(relDir ? `${relDir}/${entry.name}` : entry.name);
+ if (results.length >= maxFiles) break;
+ }
+ }
+ }
+ return results;
+}
+
+export function discoverWorkspace(repoRoot, options = {}) {
+ const absRoot = path.resolve(repoRoot);
+ const includeTests = options.includeTests !== false;
+ const maxFiles = options.maxFiles ?? 6000;
+ const scopePrefix = options.scope
+ ? normalizeRelPath(options.scope).replace(/\/+$/u, '')
+ : '';
+
+ const rawFiles = listFilesViaGit(absRoot) ?? listFilesViaWalk(absRoot, maxFiles * 2);
+ const codeFiles = [];
+ const manifestFiles = [];
+ const languageCounts = {};
+
+ for (const rel of rawFiles) {
+ if (scopePrefix && rel !== scopePrefix && !rel.startsWith(`${scopePrefix}/`)) {
+ // Still collect root manifests for alias resolution
+ const base = path.posix.basename(rel);
+ if (['package.json', 'tsconfig.json', 'jsconfig.json', 'pyproject.toml', 'Cargo.toml', 'go.mod'].includes(base)) {
+ manifestFiles.push(rel);
+ }
+ continue;
+ }
+
+ const base = path.posix.basename(rel);
+ if (
+ [
+ 'package.json',
+ 'pnpm-workspace.yaml',
+ 'tsconfig.json',
+ 'tsconfig.base.json',
+ 'jsconfig.json',
+ 'pyproject.toml',
+ 'setup.py',
+ 'Cargo.toml',
+ 'go.mod',
+ 'CMakeLists.txt',
+ 'pom.xml',
+ ].includes(base)
+ ) {
+ const parts = rel.toLowerCase().split('/');
+ if (!parts.some((seg) => IGNORED_DIRS.has(seg))) {
+ manifestFiles.push(rel);
+ }
+ }
+
+ if (shouldSkipRelPath(rel, includeTests)) continue;
+ const ext = path.posix.extname(rel).toLowerCase();
+ const lang = EXT_TO_LANG[ext];
+ if (!lang) continue;
+
+ const absPath = path.join(absRoot, rel);
+ let st;
+ try {
+ st = statSync(absPath);
+ } catch {
+ continue;
+ }
+ if (!st.isFile() || st.size === 0 || st.size > MAX_FILE_BYTES) continue;
+
+ const role = classifyRole(rel);
+ codeFiles.push({
+ relPath: rel,
+ absPath,
+ lang,
+ ext,
+ role,
+ isTest: role === 'test',
+ size: st.size,
+ mtimeMs: Math.trunc(st.mtimeMs),
+ });
+ languageCounts[lang] = (languageCounts[lang] ?? 0) + 1;
+
+ if (codeFiles.length >= maxFiles) break;
+ }
+
+ codeFiles.sort((a, b) => a.relPath.localeCompare(b.relPath));
+ const workspaceMeta = parseWorkspaceManifests(absRoot, manifestFiles);
+
+ return {
+ repoRoot: absRoot,
+ repoName: detectRepoName(absRoot),
+ codeFiles,
+ languageCounts,
+ workspaceMeta,
+ };
+}
+
+/**
+ * Human-facing project name. The checkout folder is often a throwaway name
+ * (`tmp-clone`, `foo-long-test`), so prefer the hosted remote, then the root
+ * package name, and only then the folder name.
+ */
+export function detectRepoName(absRoot) {
+ try {
+ const url = execFileSync('git', ['-C', absRoot, 'remote', 'get-url', 'origin'], {
+ timeout: 1500,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ .toString('utf8')
+ .trim();
+ // Only hosted remotes (https://… or git@host:…); a local-path remote says nothing about the project.
+ if (/^[a-z]+:\/\//iu.test(url) || /^[^/\\]+@[^:]+:/u.test(url)) {
+ const name = url.replace(/\.git$/u, '').split(/[/:]/u).pop();
+ if (name) return name;
+ }
+ } catch {
+ // not a git repo or no origin
+ }
+ try {
+ const pkg = JSON.parse(readFileSync(path.join(absRoot, 'package.json'), 'utf8'));
+ const name = String(pkg.name || '')
+ .replace(/^@[^/]+\//u, '')
+ .replace(/[-_](monorepo|workspace|workspaces|root)$/iu, '');
+ if (name && !/^(root|workspace|workspaces|monorepo|app)$/iu.test(name)) return name;
+ } catch {
+ // no package.json
+ }
+ return path.basename(absRoot);
+}
+
+function stripJsonComments(raw) {
+ // Safely strip // and /* */ comments outside JSON strings (for tsconfig.json)
+ let out = '';
+ let inStr = false;
+ let escaped = false;
+ for (let i = 0; i < raw.length; i += 1) {
+ const ch = raw[i];
+ const next = raw[i + 1];
+ if (inStr) {
+ out += ch;
+ if (escaped) escaped = false;
+ else if (ch === '\\') escaped = true;
+ else if (ch === '"') inStr = false;
+ continue;
+ }
+ if (ch === '"') {
+ inStr = true;
+ out += ch;
+ } else if (ch === '/' && next === '/') {
+ while (i < raw.length && raw[i] !== '\n') i += 1;
+ out += '\n';
+ } else if (ch === '/' && next === '*') {
+ i += 2;
+ while (i < raw.length && !(raw[i] === '*' && raw[i + 1] === '/')) {
+ if (raw[i] === '\n') out += '\n';
+ i += 1;
+ }
+ i += 1;
+ } else {
+ out += ch;
+ }
+ }
+ return out.replace(/,\s*([}\]])/gu, '$1');
+}
+
+function parseWorkspaceManifests(repoRoot, manifestFiles) {
+ const packages = [];
+ const tsAliases = [];
+ const entrypoints = new Set();
+ let projectDescription = '';
+ let primaryTechStack = [];
+
+ for (const rel of manifestFiles) {
+ const abs = path.join(repoRoot, rel);
+ const dir = path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel);
+ let content;
+ try {
+ content = readFileSync(abs, 'utf8');
+ } catch {
+ continue;
+ }
+ const base = path.posix.basename(rel);
+
+ if (base === 'package.json') {
+ try {
+ const pkg = JSON.parse(content);
+ if (!dir && pkg.description && !projectDescription) {
+ projectDescription = String(pkg.description).trim();
+ }
+ if (pkg.name) {
+ const entryCandidates = [];
+ if (typeof pkg.main === 'string') entryCandidates.push(pkg.main);
+ if (typeof pkg.module === 'string') entryCandidates.push(pkg.module);
+ if (typeof pkg.types === 'string') entryCandidates.push(pkg.types);
+ if (typeof pkg.exports === 'string') entryCandidates.push(pkg.exports);
+ else if (pkg.exports && typeof pkg.exports === 'object') {
+ const dot = pkg.exports['.'];
+ if (typeof dot === 'string') entryCandidates.push(dot);
+ else if (dot && typeof dot === 'object') {
+ for (const k of ['import', 'default', 'require', 'types']) {
+ if (typeof dot[k] === 'string') entryCandidates.push(dot[k]);
+ }
+ }
+ }
+ if (typeof pkg.bin === 'string') entryCandidates.push(pkg.bin);
+ else if (pkg.bin && typeof pkg.bin === 'object') {
+ for (const v of Object.values(pkg.bin)) {
+ if (typeof v === 'string') entryCandidates.push(v);
+ }
+ }
+ const resolvedEntries = entryCandidates
+ .map((e) => path.posix.normalize(dir ? `${dir}/${e}` : e).replace(/^\.\//u, ''))
+ .filter((e) => !e.startsWith('..'));
+ for (const e of resolvedEntries) entrypoints.add(e);
+
+ packages.push({
+ kind: 'npm',
+ name: String(pkg.name),
+ dir,
+ manifest: rel,
+ scripts: pkg.scripts ? Object.keys(pkg.scripts).slice(0, 12) : [],
+ entrypoints: resolvedEntries,
+ });
+ }
+ if (!dir) {
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
+ for (const fw of ['react', 'next', 'vue', 'svelte', 'express', 'fastify', 'hono', 'electron', 'typescript', 'vitest', 'jest', '@modelcontextprotocol/sdk']) {
+ if (deps[fw]) primaryTechStack.push(fw);
+ }
+ }
+ } catch {
+ // Ignore malformed package.json
+ }
+ } else if (base === 'tsconfig.json' || base === 'tsconfig.base.json' || base === 'jsconfig.json') {
+ try {
+ const cfg = JSON.parse(stripJsonComments(content));
+ const co = cfg?.compilerOptions;
+ if (co?.paths && typeof co.paths === 'object') {
+ const baseUrl = co.baseUrl ? path.posix.normalize(dir ? `${dir}/${co.baseUrl}` : co.baseUrl) : dir;
+ for (const [aliasPattern, targets] of Object.entries(co.paths)) {
+ if (!Array.isArray(targets) || targets.length === 0) continue;
+ const cleanBase = baseUrl === '.' ? '' : baseUrl;
+ for (const target of targets) {
+ if (typeof target !== 'string') continue;
+ const targetPattern = path.posix.normalize(cleanBase ? `${cleanBase}/${target}` : target).replace(/^\.\//u, '');
+ tsAliases.push({ aliasPattern, targetPattern, scopeDir: dir });
+ }
+ }
+ }
+ } catch {
+ // Ignore non-standard tsconfig
+ }
+ } else if (base === 'pyproject.toml') {
+ const nameMatch = content.match(/^\s*name\s*=\s*["']([^"']+)["']/mu);
+ const descMatch = content.match(/^\s*description\s*=\s*["']([^"']+)["']/mu);
+ if (!dir && descMatch && !projectDescription) projectDescription = descMatch[1].trim();
+ if (nameMatch) {
+ packages.push({
+ kind: 'python',
+ name: nameMatch[1],
+ dir,
+ manifest: rel,
+ scripts: [],
+ entrypoints: [],
+ });
+ }
+ for (const fw of ['fastapi', 'django', 'flask', 'torch', 'pytorch', 'transformers', 'vllm', 'langchain', 'pydantic', 'pytest']) {
+ if (new RegExp(`\\b${fw}\\b`, 'iu').test(content)) primaryTechStack.push(fw);
+ }
+ } else if (base === 'Cargo.toml') {
+ const nameMatch = content.match(/^\s*name\s*=\s*["']([^"']+)["']/mu);
+ const descMatch = content.match(/^\s*description\s*=\s*["']([^"']+)["']/mu);
+ if (!dir && descMatch && !projectDescription) projectDescription = descMatch[1].trim();
+ if (nameMatch) {
+ packages.push({
+ kind: 'cargo',
+ name: nameMatch[1],
+ dir,
+ manifest: rel,
+ scripts: [],
+ entrypoints: [dir ? `${dir}/src/main.rs` : 'src/main.rs', dir ? `${dir}/src/lib.rs` : 'src/lib.rs'],
+ });
+ }
+ } else if (base === 'go.mod') {
+ const modMatch = content.match(/^\s*module\s+(\S+)/mu);
+ if (modMatch) {
+ packages.push({
+ kind: 'go',
+ name: modMatch[1],
+ dir,
+ manifest: rel,
+ scripts: [],
+ entrypoints: [],
+ });
+ }
+ }
+ }
+
+ primaryTechStack = [...new Set(primaryTechStack)];
+ return {
+ packages,
+ tsAliases,
+ entrypoints: [...entrypoints],
+ projectDescription,
+ primaryTechStack,
+ };
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/server/site-builder.mjs b/plugins/Jialei-03/mcode-repowiki/server/site-builder.mjs
new file mode 100644
index 00000000..44dc4aa8
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/site-builder.mjs
@@ -0,0 +1,1574 @@
+import { readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import {
+ extractAndVerifyCitations,
+ getGitHeadCommit,
+ hashFileSha1,
+ inspectAndQueryWiki,
+ listMarkdownWikiPages,
+ loadManifest,
+ saveImpactIndex,
+ saveManifest,
+ indexSymbolLookup,
+ reconcileCitationAnchors,
+} from './sync.mjs';
+import { buildDescriptions, moduleGroupOf } from './describe.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+function inferGroupLabel(relDocPath) {
+ if (relDocPath === 'README.md') return { order: 0, group: '概览' };
+ if (relDocPath.startsWith('01-architecture/')) return { order: 1, group: '系统架构' };
+ if (relDocPath.startsWith('02-modules/')) return { order: 2, group: '核心模块' };
+ if (relDocPath.startsWith('03-guides/')) return { order: 3, group: '开发指南' };
+ const dir = path.posix.dirname(relDocPath);
+ return { order: 4, group: dir === '.' ? '附录章节' : dir };
+}
+
+/**
+ * Build the complete structured JSON payload for both static `index.html` bundles
+ * and live real-time SSE server snapshots (`server/live-server.mjs`).
+ */
+export function buildPortalPayload(index, arch, pprResult, wikiDir, options = {}) {
+ const mdPaths = listMarkdownWikiPages(wikiDir);
+ if (mdPaths.length === 0) {
+ throw new Error(
+ `No Markdown pages found in ${wikiDir}. Write Wiki pages or run repowiki init first.`,
+ );
+ }
+
+ const manifest = loadManifest(wikiDir);
+ const currentHead = getGitHeadCommit(index.repoRoot);
+ if (!options.preserveBaselineHashes) {
+ manifest.repoName = index.repoName;
+ manifest.gitHead = currentHead;
+ manifest.updatedAt = new Date().toISOString();
+ }
+
+ const pages = [];
+ const allWarnings = [];
+ const codeSnippets = {};
+ const snippetBudgetBytes = 560 * 1024;
+ let usedSnippetBytes = 0;
+
+ const captureSourceWindow = (relPath, lineStart, lineEnd) => {
+ const abs = path.join(index.repoRoot, relPath);
+ let raw;
+ try {
+ raw = readFileSync(abs, 'utf8').replace(/\r\n/gu, '\n');
+ } catch {
+ return;
+ }
+ const allLines = raw.split('\n');
+ const padStart = Math.max(1, lineStart - 4);
+ const padEnd = Math.min(allLines.length, Math.max(lineEnd + 4, lineStart + 30));
+ const sliceKey = `${relPath}:${lineStart}-${lineEnd}`;
+ if (codeSnippets[sliceKey] || usedSnippetBytes >= snippetBudgetBytes) return;
+
+ const sliceLines = [];
+ for (let ln = padStart; ln <= padEnd; ln += 1) {
+ sliceLines.push([ln, (allLines[ln - 1] ?? '').slice(0, 220)]);
+ }
+ const entry = {
+ relPath,
+ totalLines: allLines.length,
+ highlightStart: lineStart,
+ highlightEnd: lineEnd,
+ lines: sliceLines,
+ };
+ const est = JSON.stringify(entry).length;
+ if (usedSnippetBytes + est <= snippetBudgetBytes) {
+ codeSnippets[sliceKey] = entry;
+ if (!codeSnippets[relPath]) codeSnippets[relPath] = entry;
+ usedSnippetBytes += est;
+ }
+ };
+
+ for (const relDoc of mdPaths) {
+ const absDoc = path.join(wikiDir, relDoc);
+ const markdown = readFileSync(absDoc, 'utf8').replace(/\r\n/gu, '\n');
+ const { validCitations, warnings } = extractAndVerifyCitations(markdown, index);
+ for (const w of warnings) allWarnings.push(`${relDoc}: ${w}`);
+
+ const referencedFiles = [...new Set(validCitations.map((c) => c.relPath))];
+ if (!options.skipEmbeddedSnippets) {
+ for (const c of validCitations.slice(0, 45)) {
+ captureSourceWindow(c.relPath, c.lineStart, c.lineEnd);
+ }
+ }
+
+ if (!options.preserveBaselineHashes) {
+ for (const rf of referencedFiles) {
+ const h = hashFileSha1(path.join(index.repoRoot, rf));
+ if (h) manifest.fileHashes[rf] = h;
+ }
+ } else {
+ // Even when preserving baseline hashes for live drift detection, seed missing newly added files
+ for (const rf of referencedFiles) {
+ if (!manifest.fileHashes[rf]) {
+ const h = hashFileSha1(path.join(index.repoRoot, rf));
+ if (h) manifest.fileHashes[rf] = h;
+ }
+ }
+ }
+
+ const title =
+ markdown.match(/^#\s+([^\n]+)/mu)?.[1]?.trim() ||
+ manifest.pages?.[relDoc]?.title ||
+ path.posix.basename(relDoc, '.md');
+
+ const { order, group } = inferGroupLabel(relDoc);
+
+ if (!options.preserveBaselineHashes) {
+ manifest.pages[relDoc] = {
+ ...(manifest.pages[relDoc] || {}),
+ path: relDoc,
+ title,
+ updatedAt: manifest.updatedAt,
+ referencedFiles,
+ citationCount: validCitations.length,
+ wordCount: markdown.split(/\s+/u).filter(Boolean).length,
+ };
+ } else if (!manifest.pages[relDoc]) {
+ manifest.pages[relDoc] = {
+ path: relDoc,
+ title,
+ updatedAt: new Date().toISOString(),
+ referencedFiles,
+ citationCount: validCitations.length,
+ wordCount: markdown.split(/\s+/u).filter(Boolean).length,
+ };
+ }
+
+ // Keep anchors in step with the chapter's text: pages written before anchors existed, or
+ // edited without wiki_write_page, get anchors for their current citations (see
+ // reconcileCitationAnchors in sync.mjs); unchanged citations keep their original hash.
+ manifest.pages[relDoc].anchors = reconcileCitationAnchors(
+ index.repoRoot,
+ validCitations,
+ manifest.pages[relDoc]?.anchors,
+ indexSymbolLookup(index),
+ );
+
+ pages.push({
+ id: relDoc,
+ title,
+ group,
+ groupOrder: order,
+ markdown,
+ referencedFiles,
+ citationCount: validCitations.length,
+ updatedAt: manifest.pages?.[relDoc]?.updatedAt || manifest.updatedAt,
+ });
+ }
+
+ pages.sort((a, b) => a.groupOrder - b.groupOrder || a.id.localeCompare(b.id));
+ saveManifest(wikiDir, manifest, index.repoRoot);
+ saveImpactIndex(wikiDir, index, pprResult.ranks);
+
+ const ranks = pprResult.ranks;
+ const citedRelSet = new Set(pages.flatMap((p) => p.referencedFiles));
+ const citedItems = [];
+ const otherProdItems = [];
+ for (let i = 0; i < index.files.length; i += 1) {
+ const f = index.files[i];
+ if (f.isTest) continue;
+ const entry = { f, i, r: ranks[i] ?? 0 };
+ if (citedRelSet.has(f.relPath)) citedItems.push(entry);
+ else otherProdItems.push(entry);
+ }
+ citedItems.sort((a, b) => b.r - a.r);
+ otherProdItems.sort((a, b) => b.r - a.r);
+ const prodCandidates = [...citedItems, ...otherProdItems].slice(0, Math.max(105, citedItems.length));
+
+ const selectedMap = new Map();
+ const graphNodes = prodCandidates.map((item, gIdx) => {
+ selectedMap.set(item.i, gIdx);
+ const modGroup = moduleGroupOf(item.f.relPath);
+ return {
+ id: gIdx,
+ path: item.f.relPath,
+ label: path.posix.basename(item.f.relPath),
+ group: modGroup,
+ lines: index.parsedFiles[item.i].lineCount,
+ rank: +(item.r * 100).toFixed(2),
+ fanIn: index.reverseImportAdj[item.i].size,
+ fanOut: index.importAdj[item.i].size,
+ // Full neighbour lists (capped) for the inspector; graph links only cover the shown nodes.
+ imports: [...index.importAdj[item.i]].slice(0, NEIGHBOUR_CAP).map((j) => index.files[j].relPath),
+ importedBy: [...index.reverseImportAdj[item.i]]
+ .sort((a, b) => (ranks[b] ?? 0) - (ranks[a] ?? 0))
+ .slice(0, NEIGHBOUR_CAP)
+ .map((j) => index.files[j].relPath),
+ symbols: index.parsedFiles[item.i].symbols.slice(0, 20).map((s) => ({
+ sig: s.signature,
+ span: s.lineEnd > s.lineStart ? `L${s.lineStart}-L${s.lineEnd}` : `L${s.lineStart}`,
+ })),
+ };
+ });
+
+ const graphLinks = [];
+ for (const item of prodCandidates) {
+ const u = item.i;
+ const su = selectedMap.get(u);
+ for (const v of index.importAdj[u]) {
+ const sv = selectedMap.get(v);
+ if (sv !== undefined) graphLinks.push({ source: su, target: sv });
+ }
+ }
+
+ const syncCheck = inspectAndQueryWiki(index.repoRoot, wikiDir, index, '');
+ const describedPaths = graphNodes.flatMap((n) => [n.path, ...n.imports, ...n.importedBy]);
+ const descriptions = buildDescriptions(index.repoRoot, wikiDir, describedPaths, pages);
+
+ const payload = {
+ repoName: index.repoName,
+ repoRoot: index.repoRoot,
+ wikiDir,
+ gitHead: currentHead || manifest.gitHead || 'working-tree',
+ recordedGitHead: manifest.gitHead || currentHead || 'working-tree',
+ generatedAt: manifest.updatedAt || new Date().toISOString(),
+ liveMode: Boolean(options.liveMode),
+ stats: index.stats,
+ packageCount: index.workspaceMeta?.packages?.length || 0,
+ pages,
+ codeSnippets,
+ graph: { nodes: graphNodes, links: graphLinks, cycleCount: arch.cycles.length },
+ descriptions,
+ sync: {
+ stalePages: syncCheck.stalePages || [],
+ changedSourceFiles: syncCheck.changedSourceFiles || [],
+ freshCount: (syncCheck.freshPages || []).length,
+ lastScanMs: index.stats.elapsedMs ?? 0,
+ syncHistory: manifest.syncHistory || [],
+ },
+ activityLog: options.activityLog || [],
+ };
+
+ return { payload, warnings: allWarnings };
+}
+
+const NEIGHBOUR_CAP = 24;
+
+export function renderPortalHtmlFromPayload(portalPayload) {
+ // The graph is its own front-end module; the reader shell only talks to it via window.RepoWikiGraph.
+ const portalClientJs = ['portal-graph.js', 'portal-client.js']
+ .map((f) => readFileSync(path.join(__dirname, f), 'utf8'))
+ .join('\n');
+ const safeJson = JSON.stringify(portalPayload).replace(//gu, '>');
+}
+
+function renderPortalHtmlShell(repoName, safeJson, clientJs) {
+ return `
+
+
+
+
+
+${escapeTitle(repoName)} — RepoWiki
+
+
+
+
+
+
+
+
+
+
+
+`;
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/server/sync.mjs b/plugins/Jialei-03/mcode-repowiki/server/sync.mjs
new file mode 100644
index 00000000..d03292a6
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/server/sync.mjs
@@ -0,0 +1,2084 @@
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { createSpecifierResolver, formatImporters, traceImporters } from './importers.mjs';
+import { parseSourceFile } from './parser.mjs';
+import { EXT_TO_LANG } from './scanner.mjs';
+
+const REGISTRY_FILE = path.join(os.homedir(), '.repowiki', 'registry.json');
+
+function readWikiRegistry() {
+ try {
+ if (!existsSync(REGISTRY_FILE)) return {};
+ return JSON.parse(readFileSync(REGISTRY_FILE, 'utf8')) || {};
+ } catch {
+ return {};
+ }
+}
+
+export function registerRepoWikiMapping(repoRoot, wikiDir) {
+ try {
+ const absRepo = path.resolve(repoRoot);
+ const absWiki = path.resolve(wikiDir);
+ const reg = readWikiRegistry();
+ reg[absRepo] = absWiki;
+ mkdirSync(path.dirname(REGISTRY_FILE), { recursive: true });
+ writeFileSync(REGISTRY_FILE, `${JSON.stringify(reg, null, 2)}\n`, 'utf8');
+ } catch {
+ // Non-fatal if home dir is read-only
+ }
+}
+
+export function resolveWikiDir(repoRoot, customWikiDir) {
+ const absRoot = path.resolve(repoRoot);
+ if (customWikiDir) {
+ return path.isAbsolute(customWikiDir)
+ ? path.resolve(customWikiDir)
+ : path.resolve(absRoot, customWikiDir);
+ }
+ const inRepo = path.join(absRoot, '.repowiki');
+ if (existsSync(path.join(inRepo, 'manifest.json')) || existsSync(inRepo)) {
+ return inRepo;
+ }
+ const reg = readWikiRegistry();
+ const mapped = reg[absRoot];
+ if (mapped && existsSync(path.join(mapped, 'manifest.json'))) {
+ return mapped;
+ }
+ return inRepo;
+}
+
+export function assertContainedPagePath(wikiDir, pagePath) {
+ const cleanRel = String(pagePath)
+ .replace(/\\/gu, '/')
+ .replace(/^\/+/u, '')
+ .replace(/^\.\/+/u, '');
+ if (!cleanRel || cleanRel.includes('..') || !cleanRel.endsWith('.md')) {
+ throw new Error(`Invalid wiki page path "${pagePath}": must be a relative .md path inside wiki directory.`);
+ }
+ const absTarget = path.resolve(wikiDir, cleanRel);
+ const relBack = path.relative(wikiDir, absTarget);
+ if (relBack.startsWith('..') || path.isAbsolute(relBack)) {
+ throw new Error(`Page path "${pagePath}" escapes wiki directory.`);
+ }
+ return { cleanRel, absTarget };
+}
+
+export function getGitHeadCommit(repoRoot) {
+ try {
+ return execFileSync('git', ['-C', repoRoot, 'rev-parse', '--short=10', 'HEAD'], {
+ timeout: 2500,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ .toString('utf8')
+ .trim();
+ } catch {
+ return null;
+ }
+}
+
+export function hashFileSha1(absPath) {
+ try {
+ const buf = readFileSync(absPath);
+ return createHash('sha1').update(buf).digest('hex').slice(0, 16);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Extract and verify source code citations against real repository files and line counts.
+ * Supports:
+ * - Markdown links: `[label](src/foo.ts#L10-L45)` or `[label](src/foo.ts)`
+ * - Bracket spans: `[src/foo.ts:L10-L45]` or `[src/foo.ts:10-45]`
+ * - Backtick spans: `` `src/foo.ts:L10-L45` `` or `` `src/foo.ts` ``
+ */
+export function extractAndVerifyCitations(markdown, index) {
+ const validCitations = [];
+ const warnings = [];
+ const seen = new Set();
+
+ const recordCandidate = (rawPath, startStr, endStr) => {
+ let cleanPath = rawPath
+ .trim()
+ .replace(/^\.\//u, '')
+ .replace(/^\/+/u, '');
+ if (
+ !cleanPath ||
+ cleanPath.startsWith('http://') ||
+ cleanPath.startsWith('https://') ||
+ cleanPath.startsWith('mailto:') ||
+ cleanPath.endsWith('.md') // intra-wiki doc link
+ ) {
+ return;
+ }
+
+ let fIdx = index.pathToIdx.get(cleanPath);
+ if (fIdx === undefined) {
+ // Try suffix resolution if unique
+ const suffixHits = [];
+ for (let i = 0; i < index.files.length; i += 1) {
+ if (index.files[i].relPath.endsWith(`/${cleanPath}`)) suffixHits.push(i);
+ }
+ if (suffixHits.length === 1) {
+ fIdx = suffixHits[0];
+ cleanPath = index.files[fIdx].relPath;
+ }
+ }
+
+ if (fIdx === undefined) {
+ // Check if non-code repo file exists on disk (like package.json / pyproject.toml)
+ const absNonCode = path.join(index.repoRoot, cleanPath);
+ if (existsSync(absNonCode)) {
+ const key = `${cleanPath}:1:1`;
+ if (!seen.has(key)) {
+ seen.add(key);
+ validCitations.push({ relPath: cleanPath, lineStart: 1, lineEnd: 40, nonCode: true });
+ }
+ return;
+ }
+ warnings.push(`Unresolved file reference: "${rawPath}" does not exist in repository.`);
+ return;
+ }
+
+ const maxLines = index.parsedFiles[fIdx].lineCount || 1;
+ const lineStart = startStr ? Math.max(1, Number.parseInt(startStr, 10)) : 1;
+ const lineEnd = endStr ? Math.max(lineStart, Number.parseInt(endStr, 10)) : Math.min(maxLines, lineStart + 35);
+
+ if (lineStart > maxLines + 5) {
+ warnings.push(
+ `Out-of-range citation [${cleanPath}:L${lineStart}]: file only has ${maxLines} lines.`,
+ );
+ }
+
+ const clampedStart = Math.min(lineStart, maxLines);
+ const clampedEnd = Math.min(lineEnd, maxLines);
+ const key = `${cleanPath}:${clampedStart}:${clampedEnd}`;
+ if (!seen.has(key)) {
+ seen.add(key);
+ validCitations.push({
+ relPath: cleanPath,
+ lineStart: clampedStart,
+ lineEnd: clampedEnd,
+ // A bare `path/file.ts` mention, not a line-range citation: no anchor is recorded for it.
+ mention: !startStr,
+ });
+ }
+ };
+
+ // 1. Markdown links: [text](path#L10-L20)
+ const mdLinkRe = /\[([^\]]+)\]\(([^)\s#]+)(?:#L?(\d+)(?:-L?(\d+))?)?\)/gu;
+ let m;
+ while ((m = mdLinkRe.exec(markdown)) !== null) {
+ if (m[2].includes('/') || /\.[a-z0-9]{1,5}$/iu.test(m[2])) {
+ recordCandidate(m[2], m[3], m[4]);
+ }
+ }
+
+ // Blank already-parsed [label](href) links so label text like `[engine.ts:L2-L6]` isn't double-parsed
+ const withoutMdLinks = markdown.replace(mdLinkRe, ' ');
+
+ // 2. Bracket or backtick `path/to/file.ext:L10-L45`
+ const colonCiteRe = /[`[]?([A-Za-z0-9_./-]+\.[A-Za-z0-9]{1,5}):L?(\d+)(?:-L?(\d+))?[\]`]?/gu;
+ while ((m = colonCiteRe.exec(withoutMdLinks)) !== null) {
+ recordCandidate(m[1], m[2], m[3]);
+ }
+
+ // 3. Inline code paths matching known repository files: `src/foo/bar.ts`
+ const inlineCodeRe = /`([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+\.[A-Za-z0-9]{1,5})`/gu;
+ while ((m = inlineCodeRe.exec(withoutMdLinks)) !== null) {
+ if (index.pathToIdx.has(m[1])) {
+ recordCandidate(m[1], null, null);
+ }
+ }
+
+ // Validate Mermaid fence syntax basics
+ const mermaidRe = /```mermaid\s*\n([\s\S]*?)```/gu;
+ while ((m = mermaidRe.exec(markdown)) !== null) {
+ const body = m[1].trim();
+ if (!/^(flowchart|graph|sequenceDiagram|classDiagram|stateDiagram|erDiagram)\b/u.test(body)) {
+ warnings.push(
+ `Mermaid diagram starts with "${body.split('\n')[0]?.slice(0, 30)}"; prefer flowchart TD/LR, sequenceDiagram, classDiagram, or stateDiagram-v2.`,
+ );
+ }
+ }
+
+ return { validCitations, warnings };
+}
+
+// ─── Citation anchors ───────────────────────────────────────────────────────
+// When a chapter is written, every `[file:Lx-Ly]` citation is recorded with the symbol it
+// points into and a hash of the cited lines. Line sync uses the symbol to follow code that
+// moved; freshness checks use the hash to tell "the code only moved" from "the code this
+// paragraph describes has changed", so the second case can be reported per citation.
+
+function readLinesSafe(absPath) {
+ try {
+ return readFileSync(absPath, 'utf8').replace(/\r\n/gu, '\n').split('\n');
+ } catch {
+ return null;
+ }
+}
+
+export function hashLineRange(lines, start, end) {
+ const body = lines
+ .slice(start - 1, end)
+ .map((l) => l.trimEnd())
+ .join('\n');
+ return createHash('sha1').update(body).digest('hex').slice(0, 16);
+}
+
+/** The symbol whose range best overlaps [start, end] (intersection over union). */
+function bestSymbolFor(symbols, start, end) {
+ let best = null;
+ let bestScore = 0;
+ for (const sym of symbols || []) {
+ const overlap = Math.min(end, sym.lineEnd) - Math.max(start, sym.lineStart) + 1;
+ if (overlap <= 0) continue;
+ const union = Math.max(end, sym.lineEnd) - Math.min(start, sym.lineStart) + 1;
+ const score = overlap / union;
+ if (score > bestScore) {
+ best = sym;
+ bestScore = score;
+ }
+ }
+ return best;
+}
+
+export function indexSymbolLookup(index) {
+ return (relPath) => {
+ const i = index.pathToIdx.get(relPath);
+ return i === undefined ? null : index.parsedFiles[i]?.symbols || null;
+ };
+}
+
+export function buildCitationAnchors(repoRoot, citations, symbolsForFile) {
+ const anchors = [];
+ const cache = new Map();
+ for (const c of citations) {
+ if (c.nonCode || c.mention) continue;
+ if (!cache.has(c.relPath)) cache.set(c.relPath, readLinesSafe(path.join(repoRoot, c.relPath)));
+ const lines = cache.get(c.relPath);
+ if (!lines) continue;
+ const sym = bestSymbolFor(symbolsForFile(c.relPath), c.lineStart, c.lineEnd);
+ anchors.push({
+ file: c.relPath,
+ start: c.lineStart,
+ end: c.lineEnd,
+ symbol: sym?.name ?? null,
+ symStart: sym?.lineStart ?? null,
+ symEnd: sym?.lineEnd ?? null,
+ hash: hashLineRange(lines, c.lineStart, c.lineEnd),
+ });
+ }
+ return anchors;
+}
+
+/**
+ * Line a chapter's stored anchors up with the citations its text has now. A chapter may have
+ * been edited outside `wiki_write_page` (a plain file write, a person's edit): citations that
+ * are still there keep their anchor, and with it the hash from when they were written, so a
+ * code change is still reported; new citations get an anchor against the current code; anchors
+ * of citations that were removed are dropped.
+ */
+export function reconcileCitationAnchors(repoRoot, citations, previous, symbolsForFile) {
+ if (!Array.isArray(previous)) return buildCitationAnchors(repoRoot, citations, symbolsForFile);
+ const old = new Map(previous.map((a) => [`${a.file}:${a.start}-${a.end}`, a]));
+ const fresh = citations.filter((c) => !c.nonCode && !c.mention && !old.has(`${c.relPath}:${c.lineStart}-${c.lineEnd}`));
+ const built = new Map(
+ buildCitationAnchors(repoRoot, fresh, symbolsForFile).map((a) => [`${a.file}:${a.start}-${a.end}`, a]),
+ );
+ const out = [];
+ for (const c of citations) {
+ if (c.nonCode || c.mention) continue;
+ const k = `${c.relPath}:${c.lineStart}-${c.lineEnd}`;
+ const a = old.get(k) || built.get(k);
+ if (a) out.push(a);
+ }
+ return out;
+}
+
+/**
+ * Where an anchored citation should point now, given the file's current symbols.
+ * A citation of a whole symbol follows the symbol's new range (it may have grown);
+ * a citation of part of a symbol keeps its length and shifts with the symbol.
+ */
+export function relocateAnchor(anchor, symbols) {
+ if (!anchor.symbol || !Array.isArray(symbols)) return null;
+ const cands = symbols.filter((s) => s.name === anchor.symbol);
+ if (cands.length === 0) return null;
+ cands.sort((a, b) => Math.abs(a.lineStart - anchor.symStart) - Math.abs(b.lineStart - anchor.symStart));
+ const sym = cands[0];
+ if (anchor.start === anchor.symStart && anchor.end === anchor.symEnd) {
+ return { start: sym.lineStart, end: sym.lineEnd, sym };
+ }
+ const shift = sym.lineStart - anchor.symStart;
+ return { start: Math.max(1, anchor.start + shift), end: Math.max(1, anchor.end + shift), sym };
+}
+
+const langOfPath = (relPath) => EXT_TO_LANG[path.extname(relPath).toLowerCase()];
+
+/**
+ * Compare each anchored citation with the code on disk now.
+ * - moved: same code, different lines (run line sync; the prose is still right)
+ * - changed: the cited code itself changed (the paragraph around it may be out of date)
+ * - broken: the file is gone or the range is past its end
+ */
+export function checkPageAnchors(repoRoot, anchors) {
+ const moved = [];
+ const changed = [];
+ const broken = [];
+ const linesCache = new Map();
+ const symCache = new Map();
+ for (const a of anchors || []) {
+ if (!linesCache.has(a.file)) linesCache.set(a.file, readLinesSafe(path.join(repoRoot, a.file)));
+ const lines = linesCache.get(a.file);
+ if (!lines) {
+ broken.push({ ...a, reason: 'file-missing' });
+ continue;
+ }
+ if (a.end <= lines.length && hashLineRange(lines, a.start, a.end) === a.hash) continue;
+ // Not at the recorded lines: did the symbol only move?
+ if (a.symbol && !symCache.has(a.file)) {
+ const lang = langOfPath(a.file);
+ let syms = null;
+ if (lang) {
+ try {
+ syms = parseSourceFile(lines.join('\n'), lang, a.file).symbols;
+ } catch {
+ syms = null;
+ }
+ }
+ symCache.set(a.file, syms);
+ }
+ const loc = a.symbol ? relocateAnchor(a, symCache.get(a.file)) : null;
+ if (loc && loc.end <= lines.length && hashLineRange(lines, loc.start, loc.end) === a.hash) {
+ moved.push({ ...a, now: `L${loc.start}-L${loc.end}` });
+ } else if (a.end > lines.length && !loc) {
+ broken.push({ ...a, reason: 'out-of-range' });
+ } else {
+ changed.push(a);
+ }
+ }
+ return { moved, changed, broken };
+}
+
+const describeAnchor = (a) => ({
+ file: a.file,
+ lines: `L${a.start}-L${a.end}`,
+ symbol: a.symbol,
+ ...(a.reason ? { reason: a.reason } : {}),
+ ...(a.now ? { now: a.now } : {}),
+});
+
+/**
+ * Mark chapters as reviewed against the current code: re-record their citation anchors.
+ * Use after a person or the agent confirmed the prose is still right, or after editing it.
+ */
+export function acceptWikiPages(repoRoot, wikiDir, index, pages = null) {
+ const manifest = loadManifest(wikiDir);
+ const lookup = indexSymbolLookup(index);
+ const accepted = [];
+ const nowIso = new Date().toISOString();
+ for (const p of listMarkdownWikiPages(wikiDir)) {
+ if (pages && !pages.includes(p)) continue;
+ let md;
+ try {
+ md = readFileSync(path.join(wikiDir, p), 'utf8');
+ } catch {
+ continue;
+ }
+ const { validCitations } = extractAndVerifyCitations(md, index);
+ const referencedFiles = [...new Set(validCitations.map((c) => c.relPath))];
+ for (const rf of referencedFiles) {
+ const h = hashFileSha1(path.join(repoRoot, rf));
+ if (h) manifest.fileHashes[rf] = h;
+ }
+ manifest.pages[p] = {
+ ...(manifest.pages[p] || { path: p }),
+ referencedFiles,
+ anchors: buildCitationAnchors(repoRoot, validCitations, lookup),
+ reviewedAt: nowIso,
+ };
+ accepted.push(p);
+ }
+ saveManifest(wikiDir, manifest, repoRoot);
+ return accepted;
+}
+
+export function loadManifest(wikiDir) {
+ const manifestPath = path.join(wikiDir, 'manifest.json');
+ if (!existsSync(manifestPath)) {
+ return {
+ schemaVersion: 1,
+ repoName: '',
+ gitHead: null,
+ updatedAt: null,
+ pages: {},
+ fileHashes: {},
+ };
+ }
+ try {
+ return JSON.parse(readFileSync(manifestPath, 'utf8'));
+ } catch {
+ return {
+ schemaVersion: 1,
+ repoName: '',
+ gitHead: null,
+ updatedAt: null,
+ pages: {},
+ fileHashes: {},
+ };
+ }
+}
+
+function resolveGitDir(repoRoot) {
+ const dotGit = path.join(path.resolve(repoRoot), '.git');
+ if (!existsSync(dotGit)) return null;
+ try {
+ const st = statSync(dotGit);
+ if (st.isDirectory()) return dotGit;
+ if (st.isFile()) {
+ const raw = readFileSync(dotGit, 'utf8').trim();
+ const m = raw.match(/^gitdir:\s*(.+)$/mu);
+ if (m) return path.resolve(path.resolve(repoRoot), m[1].trim());
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+/**
+ * Keep `.repowiki/` out of `git status` and PR diffs using local `.git/info/exclude`
+ * without ever modifying the repository's tracked `.gitignore`.
+ */
+export function ensureGitExclude(repoRoot, wikiDir) {
+ try {
+ const absRepo = path.resolve(repoRoot);
+ const absWiki = path.resolve(wikiDir);
+ const rel = path.relative(absRepo, absWiki).replace(/\\/gu, '/');
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
+ return { excluded: false, reason: 'outside-repo' };
+ }
+ const gitDir = resolveGitDir(absRepo);
+ if (!gitDir) return { excluded: false, reason: 'not-git' };
+ const infoDir = path.join(gitDir, 'info');
+ const excludeFile = path.join(infoDir, 'exclude');
+ mkdirSync(infoDir, { recursive: true });
+ const pattern = `${rel.replace(/\/+$/u, '')}/`;
+ const cur = existsSync(excludeFile) ? readFileSync(excludeFile, 'utf8') : '';
+ const lines = cur.split(/\r?\n/u).map((l) => l.trim());
+ if (lines.includes(pattern) || lines.includes(rel.replace(/\/+$/u, ''))) {
+ return { excluded: true, alreadyExcluded: true, excludeFile, pattern };
+ }
+ const prefix = cur.length > 0 && !cur.endsWith('\n') ? '\n' : '';
+ writeFileSync(excludeFile, `${cur}${prefix}${pattern}\n`, 'utf8');
+ return { excluded: true, alreadyExcluded: false, excludeFile, pattern };
+ } catch {
+ return { excluded: false, reason: 'error' };
+ }
+}
+
+const HOOK_MARKER_START = '# >>> repowiki auto-sync >>>';
+const HOOK_MARKER_END = '# <<< repowiki auto-sync <<<';
+
+export function installPostCommitHook(repoRoot, cliScriptPath = null) {
+ const absRepo = path.resolve(repoRoot);
+ const gitDir = resolveGitDir(absRepo);
+ if (!gitDir) return { installed: false, reason: 'not-git' };
+ const hooksDir = path.join(gitDir, 'hooks');
+ mkdirSync(hooksDir, { recursive: true });
+ const hookFile = path.join(hooksDir, 'post-commit');
+ const resolvedCli = cliScriptPath || path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'cli.mjs');
+
+ // The Node that installed the hook may live in a versioned folder (MiniMax Code bundles its
+ // own runtime) that disappears on upgrade; fall back to `node` on PATH, and skip quietly if
+ // the plugin itself was removed. A commit must never fail because of this hook.
+ const block = [
+ HOOK_MARKER_START,
+ `REPOWIKI_NODE="${process.execPath}"`,
+ `[ -x "$REPOWIKI_NODE" ] || REPOWIKI_NODE="$(command -v node 2>/dev/null)"`,
+ `if [ -n "$REPOWIKI_NODE" ] && [ -f "${resolvedCli}" ]; then`,
+ ` "$REPOWIKI_NODE" "${resolvedCli}" sync "${absRepo}" --quiet >/dev/null 2>&1 || true`,
+ 'fi',
+ HOOK_MARKER_END,
+ ].join('\n');
+
+ let nextContent = `#!/bin/sh\n${block}\n`;
+ let alreadyInstalled = false;
+ if (existsSync(hookFile)) {
+ const existing = readFileSync(hookFile, 'utf8');
+ if (existing.includes(HOOK_MARKER_START)) {
+ alreadyInstalled = true;
+ nextContent = existing.replace(new RegExp(`${HOOK_MARKER_START}[\\s\\S]*?${HOOK_MARKER_END}`, 'u'), block);
+ } else {
+ nextContent = `${existing.trimEnd()}\n\n${block}\n`;
+ }
+ }
+ writeFileSync(hookFile, nextContent, { mode: 0o755 });
+ chmodSync(hookFile, 0o755);
+ return { installed: true, alreadyInstalled, hookFile };
+}
+
+export function removePostCommitHook(repoRoot) {
+ const absRepo = path.resolve(repoRoot);
+ const gitDir = resolveGitDir(absRepo);
+ if (!gitDir) return { removed: false, reason: 'not-git' };
+ const hookFile = path.join(gitDir, 'hooks', 'post-commit');
+ if (existsSync(hookFile)) {
+ const cur = readFileSync(hookFile, 'utf8');
+ const stripped = cur.replace(new RegExp(`${HOOK_MARKER_START}[\\s\\S]*?${HOOK_MARKER_END}\\n?`, 'u'), '');
+ if (!stripped.replace(/^#!.*\n?/u, '').trim()) rmSync(hookFile, { force: true });
+ else writeFileSync(hookFile, stripped, 'utf8');
+ }
+ return { removed: true, hookFile };
+}
+
+/**
+ * Persist a compact reverse-dependency map (`impact.json`) so `wiki_locate` can report
+ * downstream blast radius (direct importers ranked by PageRank) in <2ms without re-scanning.
+ */
+export function saveImpactIndex(wikiDir, index, ranks = []) {
+ try {
+ mkdirSync(wikiDir, { recursive: true });
+ const impact = {};
+ for (let i = 0; i < index.files.length; i += 1) {
+ const importersSet = index.reverseImportAdj?.[i];
+ if (!importersSet || importersSet.size === 0) continue;
+ const prodImporters = [];
+ let testImporters = 0;
+ for (const u of importersSet) {
+ const f = index.files[u];
+ if (!f) continue;
+ if (f.isTest) {
+ testImporters += 1;
+ } else {
+ prodImporters.push({ relPath: f.relPath, rank: ranks[u] ?? 0 });
+ }
+ }
+ prodImporters.sort((a, b) => b.rank - a.rank || a.relPath.localeCompare(b.relPath));
+ impact[index.files[i].relPath] = {
+ fanIn: importersSet.size,
+ prodCount: prodImporters.length,
+ testCount: testImporters,
+ importers: prodImporters.slice(0, 20).map((x) => x.relPath),
+ };
+ }
+ writeFileSync(path.join(wikiDir, 'impact.json'), `${JSON.stringify(impact)}\n`, 'utf8');
+ return Object.keys(impact).length;
+ } catch {
+ return 0;
+ }
+}
+
+export function loadImpactIndex(wikiDir) {
+ try {
+ const p = path.join(wikiDir, 'impact.json');
+ if (!existsSync(p)) return {};
+ return JSON.parse(readFileSync(p, 'utf8')) || {};
+ } catch {
+ return {};
+ }
+}
+
+const LEGACY_DELTA_MD_PAGE = '03-guides/00-live-delta.md';
+const DELTA_INDEX_FILE = 'delta-index.json';
+
+export function loadDeltaIndex(wikiDir) {
+ try {
+ const p = path.join(wikiDir, DELTA_INDEX_FILE);
+ if (!existsSync(p)) return null;
+ const parsed = JSON.parse(readFileSync(p, 'utf8'));
+ return parsed && Array.isArray(parsed.files) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+export function saveManifest(wikiDir, manifest, repoRoot = null) {
+ mkdirSync(wikiDir, { recursive: true });
+ writeFileSync(path.join(wikiDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
+ if (repoRoot) {
+ registerRepoWikiMapping(repoRoot, wikiDir);
+ ensureGitExclude(repoRoot, wikiDir);
+ }
+}
+
+export function writeVerifiedWikiPage(options, index) {
+ const { repoRoot, wikiDir, pagePath, content, title } = options;
+ const { cleanRel, absTarget } = assertContainedPagePath(wikiDir, pagePath);
+
+ mkdirSync(path.dirname(absTarget), { recursive: true });
+ const normalized = `${String(content).replace(/\r\n/gu, '\n').trim()}\n`;
+ writeFileSync(absTarget, normalized, 'utf8');
+
+ const { validCitations, warnings } = extractAndVerifyCitations(normalized, index);
+
+ // Extract first H1 heading if title omitted
+ const inferredTitle =
+ title ||
+ normalized.match(/^#\s+([^\n]+)/mu)?.[1]?.trim() ||
+ path.posix.basename(cleanRel, '.md');
+
+ const manifest = loadManifest(wikiDir);
+ manifest.repoName = index.repoName;
+ manifest.gitHead = getGitHeadCommit(repoRoot);
+ manifest.updatedAt = new Date().toISOString();
+
+ const referencedFiles = [...new Set(validCitations.map((c) => c.relPath))];
+ for (const rf of referencedFiles) {
+ const h = hashFileSha1(path.join(repoRoot, rf));
+ if (h) manifest.fileHashes[rf] = h;
+ }
+
+ const anchors = buildCitationAnchors(repoRoot, validCitations, indexSymbolLookup(index));
+ manifest.pages[cleanRel] = {
+ path: cleanRel,
+ title: inferredTitle,
+ updatedAt: manifest.updatedAt,
+ referencedFiles,
+ citationCount: validCitations.length,
+ wordCount: normalized.split(/\s+/u).filter(Boolean).length,
+ anchors,
+ };
+ saveManifest(wikiDir, manifest, repoRoot);
+
+ return {
+ pagePath: cleanRel,
+ absPath: absTarget,
+ title: inferredTitle,
+ citationCount: validCitations.length,
+ referencedFiles,
+ warnings,
+ validCitations,
+ anchors,
+ markdown: normalized,
+ };
+}
+
+export function listMarkdownWikiPages(wikiDir) {
+ if (!existsSync(wikiDir)) return [];
+ const results = [];
+ const walk = (relDir) => {
+ const absDir = relDir ? path.join(wikiDir, relDir) : wikiDir;
+ let entries = [];
+ try {
+ entries = readdirSync(absDir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const e of entries) {
+ if (e.isSymbolicLink() || e.name.startsWith('.')) continue;
+ const rel = relDir ? `${relDir}/${e.name}` : e.name;
+ if (e.isDirectory()) walk(rel);
+ else if (e.isFile() && e.name.endsWith('.md')) results.push(rel);
+ }
+ };
+ walk('');
+ // Order: README.md first, then sorted path (`01-architecture/...`, `02-modules/...`, `03-guides/...`)
+ results.sort((a, b) => {
+ if (a === 'README.md') return -1;
+ if (b === 'README.md') return 1;
+ return a.localeCompare(b);
+ });
+ return results;
+}
+
+const BILINGUAL_TECH_BRIDGE = {
+ transaction: ['事务', 'tx'],
+ tx: ['事务', 'harness'],
+ persistence: ['持久化', 'durable'],
+ durable: ['持久化', '事务'],
+ extension: ['扩展', 'extensions'],
+ extensions: ['扩展', 'extension'],
+ render: ['渲染', 'tui'],
+ terminal: ['终端', 'tui'],
+ tui: ['终端', '渲染'],
+ component: ['组件', 'tui'],
+ session: ['会话', 'session-manager'],
+ compaction: ['压缩', 'compactionentry'],
+ branch: ['分支', 'summary'],
+ queue: ['队列', '插话', 'steering'],
+ steering: ['插话', '队列', 'pending'],
+ guard: ['守卫', '拦截', '熔断'],
+ breaker: ['熔断', '死循环', 'doom'],
+ loop: ['循环', 'agent-loop'],
+ hook: ['钩子', '拦截'],
+ schema: ['契约', '构建器', 'builders', 'annotations'],
+ builder: ['构建器', 'schema', 'builders'],
+ annotation: ['注解', '元信息', 'annotations'],
+ telemetry: ['可观测', '追踪', '指标', 'span'],
+ span: ['追踪', '链路', 'telemetry', 'storedspan'],
+ trace: ['追踪', '链路', 'telemetry', 'span'],
+ status: ['状态', '侧边栏', 'workstep', 'statusstore'],
+ sidebar: ['侧边栏', '状态', 'status'],
+ sharing: ['分享', '访客', 'share', 'guest'],
+ share: ['分享', '访客', 'sharing', 'guest'],
+ principal: ['权限', '主体', '访客', 'principals', 'owner', 'guest'],
+ guest: ['访客', '分享', '权限', 'principals'],
+ subagent: ['子智能体', '子agent', 'subagents'],
+ facet: ['微内核', '插件', 'chord'],
+ policy: ['策略', '拦截', '守卫', 'loop-policy'],
+ audit: ['审计', '追踪', 'policy'],
+ '事务': ['transaction', 'tx', 'durable'],
+ '持久化': ['durable', 'persistence', 'harness'],
+ '扩展': ['extension', 'extensions'],
+ '渲染': ['render', 'tui', 'component'],
+ '终端': ['tui', 'terminal'],
+ '会话': ['session', 'session-manager'],
+ '压缩': ['compaction', 'compactionentry'],
+ '插话': ['steering', 'pending', 'queue'],
+ '熔断': ['doom', 'guard', 'breaker'],
+ '死循环': ['doom', 'loop', 'guard'],
+ '契约': ['schema', 'contract', 'builders', 'annotations'],
+ '构建器': ['builders', 'schema'],
+ '注解': ['annotations', 'schema', 'builders'],
+ '追踪': ['telemetry', 'span', 'trace'],
+ '可观测': ['telemetry', 'span', 'metrics'],
+ '侧边栏': ['status', 'sidebar', 'workstep'],
+ '状态': ['status', 'workstep', 'statusstore'],
+ '分享': ['sharing', 'share', 'guest', 'principals'],
+ '访客': ['guest', 'sharing', 'principals'],
+ '权限': ['principals', 'owner', 'guest', 'sharing'],
+ '微内核': ['p2', 'facet', 'chord'],
+ '子智能体': ['subagents', 'subagent'],
+ '策略': ['policy', 'guard', 'loop-policy'],
+ '审计': ['audit', 'telemetry', 'policy'],
+};
+
+function tokenizeMixedQuery(rawQuery) {
+ const q = String(rawQuery || '').trim();
+ const tokens = new Set();
+ // 1. ASCII identifiers + camelCase / kebab / snake sub-parts
+ const asciiMatches = q.match(/[A-Za-z0-9_.-]{2,}/gu) || [];
+ for (const m of asciiMatches) {
+ tokens.add(m.toLowerCase());
+ const splitCamel = m
+ .replace(/([a-z0-9])([A-Z])/gu, '$1 $2')
+ .split(/[\s_./-]+/u)
+ .filter((s) => s.length >= 2);
+ for (const part of splitCamel) tokens.add(part.toLowerCase());
+ }
+ // 2. CJK runs + 2-gram / 3-gram sliding tokens (handles unspaced Chinese sentences!)
+ const stopCjk = new Set(['什么', '怎么', '如何', '哪里', '哪个', '哪些', '为什么', '实现', '代码', '文件', '函数', '可以', '一个', '这个', '是在']);
+ const cjkRuns = q.match(/[\u4e00-\u9fff]{2,}/gu) || [];
+ for (const run of cjkRuns) {
+ if (run.length <= 5 && !stopCjk.has(run)) tokens.add(run);
+ for (let len = 2; len <= 3; len += 1) {
+ for (let i = 0; i + len <= run.length; i += 1) {
+ const gram = run.slice(i, i + len);
+ if (!stopCjk.has(gram)) tokens.add(gram);
+ }
+ }
+ }
+ // 3. Bilingual engineering term expansion (bridges EN queries <-> ZH Wiki chapters!)
+ for (const t of [...tokens]) {
+ const mapped = BILINGUAL_TECH_BRIDGE[t];
+ if (mapped) {
+ for (const syn of mapped) tokens.add(syn);
+ }
+ }
+ return [...tokens];
+}
+
+/**
+ * Inspect incremental Git/hash staleness AND optionally search across Wiki sections.
+ */
+export function inspectAndQueryWiki(repoRoot, wikiDir, index, query = '') {
+ const mdPages = listMarkdownWikiPages(wikiDir);
+ if (mdPages.length === 0) {
+ return {
+ exists: false,
+ wikiDir,
+ message: `No Repo Wiki found at ${wikiDir}. Call wiki_plan first to generate the multi-level documentation blueprint.`,
+ };
+ }
+
+ const manifest = loadManifest(wikiDir);
+ const currentHead = getGitHeadCommit(repoRoot);
+
+ // Detect changed source files by comparing current SHA-1 against recorded manifest hashes
+ const changedFiles = new Set();
+ for (const [relPath, oldHash] of Object.entries(manifest.fileHashes ?? {})) {
+ const abs = path.join(repoRoot, relPath);
+ const curHash = hashFileSha1(abs);
+ if (curHash !== oldHash) {
+ changedFiles.add(relPath);
+ }
+ }
+
+ // Propagate 1-hop upstream dependents so callers of modified interfaces are also flagged
+ const impactedFiles = new Set(changedFiles);
+ if (index) {
+ for (const cf of changedFiles) {
+ const idx = index.pathToIdx.get(cf);
+ if (idx !== undefined) {
+ for (const callerIdx of index.reverseImportAdj[idx]) {
+ impactedFiles.add(index.files[callerIdx].relPath);
+ }
+ }
+ }
+ }
+
+ const freshPages = [];
+ const stalePages = [];
+ const linesNeedingSync = [];
+ const lookup = index ? indexSymbolLookup(index) : null;
+ for (const p of mdPages) {
+ const meta = manifest.pages?.[p];
+ let anchors = meta?.anchors;
+ if (lookup && Array.isArray(anchors)) {
+ // Check the citations the chapter has now, not ones a later plain edit removed.
+ try {
+ const { validCitations } = extractAndVerifyCitations(readFileSync(path.join(wikiDir, p), 'utf8'), index);
+ anchors = reconcileCitationAnchors(repoRoot, validCitations, anchors, lookup);
+ } catch {
+ // keep the stored anchors
+ }
+ }
+ if (Array.isArray(anchors)) {
+ const { moved, changed, broken } = checkPageAnchors(repoRoot, anchors);
+ if (moved.length > 0) linesNeedingSync.push({ page: p, citations: moved.map(describeAnchor) });
+ if (changed.length > 0 || broken.length > 0) {
+ stalePages.push({
+ page: p,
+ dirtySourceFiles: [...new Set([...changed, ...broken].map((a) => a.file))],
+ changedCitations: changed.map(describeAnchor),
+ brokenCitations: broken.map(describeAnchor),
+ });
+ } else {
+ freshPages.push(p);
+ }
+ continue;
+ }
+ const refs = meta?.referencedFiles ?? [];
+ const dirtyRefs = refs.filter((r) => impactedFiles.has(r));
+ if (dirtyRefs.length > 0) {
+ stalePages.push({ page: p, dirtySourceFiles: dirtyRefs });
+ } else {
+ freshPages.push(p);
+ }
+ }
+
+ // Mixed CJK + Identifier ranked section search
+ const searchHits = [];
+ const q = query.trim().toLowerCase();
+ if (q) {
+ const qTerms = tokenizeMixedQuery(query);
+ for (const p of mdPages) {
+ let text = '';
+ try {
+ text = readFileSync(path.join(wikiDir, p), 'utf8');
+ } catch {
+ continue;
+ }
+ const docTitle = text.match(/^#\s+([^\n]+)/mu)?.[1]?.trim() || p;
+ const sections = text.split(/\n(?=##\s+)/u);
+ for (const sec of sections) {
+ const heading = sec.match(/^#+\s*([^\n]+)/u)?.[1]?.trim() || docTitle;
+ const lowerHead = `${docTitle} ${heading}`.toLowerCase();
+ const lowerBody = sec.toLowerCase();
+ let score = 0;
+ if (lowerBody.includes(q)) score += 16;
+ for (const t of qTerms) {
+ if (lowerHead.includes(t)) score += t.length >= 3 ? 7 : 4;
+ else if (lowerBody.includes(t)) score += t.length >= 3 ? 3.5 : 1.8;
+ }
+ if (score >= 3) {
+ searchHits.push({
+ page: p,
+ heading,
+ score: +score.toFixed(1),
+ snippet: sec.replace(/```mermaid[\s\S]*?```/gu, '').trim().slice(0, 560),
+ rawSection: sec,
+ });
+ }
+ }
+ }
+ searchHits.sort((a, b) => b.score - a.score);
+ }
+
+ return {
+ exists: true,
+ wikiDir,
+ recordedGitHead: manifest.gitHead,
+ currentGitHead: currentHead,
+ totalPages: mdPages.length,
+ freshPages,
+ stalePages,
+ linesNeedingSync,
+ changedSourceFiles: [...changedFiles],
+ searchHits: searchHits.slice(0, 8),
+ };
+}
+
+function collectGitDeltaFilesSince(repoRoot, baseCommit) {
+ const deltaSet = new Set();
+ try {
+ if (baseCommit && /^[0-9a-f]{6,40}$/iu.test(baseCommit)) {
+ const diffOut = execFileSync('git', ['-C', repoRoot, 'diff', '--name-only', baseCommit], {
+ timeout: 1800,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).toString('utf8');
+ for (const ln of diffOut.split('\n')) {
+ const clean = ln.trim().replace(/\\/gu, '/');
+ if (clean) deltaSet.add(clean);
+ }
+ }
+ const statusOut = execFileSync('git', ['-C', repoRoot, 'status', '--porcelain', '-uall'], {
+ timeout: 1800,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).toString('utf8');
+ for (const ln of statusOut.split('\n')) {
+ if (ln.length < 4) continue;
+ const rawPath = ln.slice(3).split(' -> ').pop()?.trim().replace(/^"|"$/gu, '').replace(/\\/gu, '/');
+ if (rawPath) deltaSet.add(rawPath);
+ }
+ } catch {
+ // Non-git directory or git unavailable
+ }
+ return [...deltaSet].filter(
+ (rel) =>
+ !rel.startsWith('.repowiki/') &&
+ !rel.includes('/node_modules/') &&
+ !rel.includes('/dist/') &&
+ Boolean(EXT_TO_LANG[path.extname(rel).toLowerCase()]),
+ );
+}
+
+function extractCandidateSymbols(query, explicitSymbol = '') {
+ const syms = [];
+ const seen = new Set();
+ const add = (raw) => {
+ const s = String(raw || '').trim();
+ if (!s || s.length < 3 || s.length > 80 || seen.has(s)) return;
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(s)) return;
+ seen.add(s);
+ syms.push(s);
+ };
+ if (explicitSymbol) {
+ for (const part of String(explicitSymbol).split(/[\s,]+/u)) add(part);
+ }
+ const matches =
+ String(query || '').match(
+ /\b(?:[A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*|[a-z]+[A-Z][A-Za-z0-9]*|[A-Z][A-Z0-9_]{3,}|[a-z0-9]+_[a-z0-9_]+)\b/gu,
+ ) || [];
+ for (const m of matches) add(m);
+ return syms.slice(0, 3);
+}
+
+/**
+ * Zero-dependency targeted symbol reference tracer:
+ * Scans ONLY the direct importers of matched target files (from `.repowiki/impact.json`)
+ * in <8ms so agents see exact downstream usage lines before editing a shared symbol.
+ */
+function findSymbolReferencesInImporters(repoRoot, importerPaths, symbols, maxHits = 10) {
+ if (!symbols.length || !importerPaths.length) return [];
+ const hits = [];
+ const escaped = symbols.map((s) => s.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&'));
+ const re = new RegExp(`\\b(${escaped.join('|')})\\b`, 'u');
+
+ for (const rel of importerPaths.slice(0, 16)) {
+ let raw;
+ try {
+ raw = readFileSync(path.join(repoRoot, rel), 'utf8').replace(/\r\n/gu, '\n');
+ } catch {
+ continue;
+ }
+ const lines = raw.split('\n');
+ let fileHits = 0;
+ let inImportBlock = false;
+ const deferredImports = [];
+ for (let i = 0; i < lines.length; i += 1) {
+ const ln = lines[i];
+ const trimmed = ln.trim();
+ if (/^import\b/u.test(trimmed)) {
+ inImportBlock = !trimmed.includes(';') && !/\bfrom\s+['"`]/u.test(trimmed);
+ }
+ const isImportLine = /^import\b/u.test(trimmed) || inImportBlock;
+ if (inImportBlock && (trimmed.includes(';') || /\bfrom\s+['"`]/u.test(trimmed))) {
+ inImportBlock = false;
+ }
+ if (!re.test(ln)) continue;
+ if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*')) continue;
+ const entry = {
+ relPath: rel,
+ line: i + 1,
+ text: trimmed.slice(0, 120),
+ isImport: isImportLine,
+ };
+ if (entry.isImport) {
+ deferredImports.push(entry);
+ } else {
+ hits.push(entry);
+ fileHits += 1;
+ if (fileHits >= 3 || hits.length >= maxHits) break;
+ }
+ }
+ if (fileHits === 0 && deferredImports.length > 0 && hits.length < maxHits) {
+ hits.push(deferredImports[0]);
+ }
+ if (hits.length >= maxHits) break;
+ }
+ return hits;
+}
+
+const CODE_PATHSPECS = [
+ '*.ts', '*.tsx', '*.mts', '*.cts', '*.js', '*.jsx', '*.mjs', '*.cjs', '*.py', '*.go', '*.rs',
+ '*.java', '*.kt', '*.swift', '*.c', '*.h', '*.cc', '*.cpp', '*.hpp', '*.cs', '*.rb', '*.php',
+];
+const IGNORED_DIR_RE = /(^|\/)(node_modules|\.git|\.repowiki|dist|build|out|target|vendor|\.next|coverage)(\/|$)/u;
+
+/**
+ * Every file that mentions `symbol` as a whole word, repo-wide — not just the importers of the
+ * defining file, so re-exports through barrels/package entries and test files are included.
+ * Uses `git grep` (tracked + untracked, honours .gitignore); falls back to a file walk.
+ * Returns [{ relPath, line, text, isTest }] with one representative line per file
+ * (first non-import, non-comment use; else the import line).
+ */
+export function findSymbolUsagesRepoWide(repoRoot, symbol) {
+ if (!/^[A-Za-z_$][\w$]*$/u.test(symbol)) return [];
+ const byFile = new Map();
+ const consider = (rel, line, text) => {
+ if (IGNORED_DIR_RE.test(rel)) return;
+ const trimmed = text.trim();
+ if (!trimmed || /^(\/\/|\*|\/\*|#)/u.test(trimmed)) return;
+ const isImport = /^(import\b|export\s+(type\s+)?\{[^}]*\}\s+from\b|export\s+\*\s+from\b|from\s+\S+\s+import\b|use\s)/u.test(trimmed);
+ const prev = byFile.get(rel);
+ if (!prev || (prev.isImport && !isImport)) {
+ byFile.set(rel, { relPath: rel, line, text: trimmed.slice(0, 120), isImport });
+ }
+ };
+
+ let usedGit = false;
+ try {
+ const out = execFileSync(
+ 'git',
+ ['-C', repoRoot, 'grep', '-n', '-I', '-w', '--untracked', '--exclude-standard', '-e', symbol, '--', ...CODE_PATHSPECS],
+ { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 },
+ );
+ usedGit = true;
+ for (const row of out.split('\n')) {
+ const m = row.match(/^(.+?):(\d+):(.*)$/u);
+ if (m) consider(m[1].replace(/\\/gu, '/'), Number(m[2]), m[3]);
+ }
+ } catch (err) {
+ // exit code 1 = no matches in a git repo
+ if (err && err.status === 1) usedGit = true;
+ }
+
+ if (!usedGit) {
+ const word = new RegExp(`(^|[^\\w$])${symbol.replace(/\$/gu, '\\$')}([^\\w$]|$)`, 'u');
+ const exts = new Set(CODE_PATHSPECS.map((p) => p.slice(1)));
+ const walk = (dir, depth) => {
+ if (depth > 24) return;
+ let entries = [];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ const abs = path.join(dir, e.name);
+ const rel = path.relative(repoRoot, abs).replace(/\\/gu, '/');
+ if (IGNORED_DIR_RE.test(rel)) continue;
+ if (e.isDirectory()) walk(abs, depth + 1);
+ else if (exts.has(path.extname(e.name))) {
+ let raw = '';
+ try {
+ raw = readFileSync(abs, 'utf8');
+ } catch {
+ continue;
+ }
+ if (!raw.includes(symbol)) continue;
+ raw.split(/\r?\n/u).forEach((ln, i) => {
+ if (word.test(ln)) consider(rel, i + 1, ln);
+ });
+ }
+ }
+ };
+ walk(repoRoot, 0);
+ }
+
+ return [...byFile.values()]
+ .map((h) => ({ ...h, isTest: /(^|\/)(test|tests|__tests__|spec)(\/|$)|\.(test|spec)\.[a-z]+$/iu.test(h.relPath) }))
+ .sort((a, b) => Number(a.isTest) - Number(b.isTest) || a.relPath.localeCompare(b.relPath));
+}
+
+function formatSymbolUsages(symbol, usages, maxFiles) {
+ const out = [];
+ const src = usages.filter((u) => !u.isTest);
+ const tests = usages.filter((u) => u.isTest);
+ out.push(
+ `## Every File Using \`${symbol}\` (${usages.length} files: ${src.length} source, ${tests.length} tests — repo-wide whole-word search, includes re-exports)`,
+ );
+ const shown = usages.slice(0, maxFiles);
+ for (const h of shown) {
+ out.push(`- \`${h.relPath}:L${h.line}\`${h.isTest ? ' [test]' : ''}: \`${h.text.replace(/`/gu, "'")}\``);
+ }
+ if (usages.length > shown.length) {
+ out.push(`- … ${usages.length - shown.length} more: \`git grep -n -w ${symbol}\` lists them all.`);
+ }
+ out.push('- Same-named but unrelated symbols in other modules also match; check the import line of each file outside the defining package.');
+ out.push('');
+ return out;
+}
+
+/**
+ * Ultra-fast (<30ms), token-minimal LSM-Style Semantic Code Router (`wiki_locate`).
+ * Combines:
+ * - L1 Base Layer: Pre-computed `.repowiki/` architectural sections, citations, and `impact.json`
+ * - L0.5 Synced Machine Delta Index: `.repowiki/delta-index.json` (`[SYNCED-DELTA]`)
+ * - L0 Live Delta Overlay:
+ * 1) Automatic AST symbol line re-anchoring (`[AST-REANCHORED]`)
+ * 2) Real-time Git working-tree & post-baseline commit delta scan (`[LIVE-NEW-FILE]`)
+ * 3) Targeted downstream importer symbol reference lines (<8ms)
+ */
+export function locateCodeFromWikiFast(repoRoot, wikiDir, query, maxTargets = 6, options = {}) {
+ const t0 = Date.now();
+ const mdPages = listMarkdownWikiPages(wikiDir);
+ const deltaIndex = loadDeltaIndex(wikiDir);
+ if (mdPages.length === 0 && !deltaIndex) {
+ return null;
+ }
+
+ const manifest = loadManifest(wikiDir);
+ const qTerms = tokenizeMixedQuery(query);
+ const qLower = String(query || '').trim().toLowerCase();
+ const parsedLiveMemo = new Map();
+
+ const parseLiveOnce = (relPath) => {
+ if (parsedLiveMemo.has(relPath)) return parsedLiveMemo.get(relPath);
+ const lang = EXT_TO_LANG[path.extname(relPath).toLowerCase()];
+ if (!lang) {
+ parsedLiveMemo.set(relPath, null);
+ return null;
+ }
+ try {
+ const src = readFileSync(path.join(repoRoot, relPath), 'utf8');
+ const parsed = parseSourceFile(src, lang, relPath);
+ parsedLiveMemo.set(relPath, parsed);
+ return parsed;
+ } catch {
+ parsedLiveMemo.set(relPath, null);
+ return null;
+ }
+ };
+
+ const sectionCandidates = [];
+ for (const p of mdPages) {
+ let text = '';
+ try {
+ text = readFileSync(path.join(wikiDir, p), 'utf8');
+ } catch {
+ continue;
+ }
+ const docTitle = text.match(/^#\s+([^\n]+)/mu)?.[1]?.trim() || p;
+ const sections = text.split(/\n(?=###?\s+)/u);
+ for (const sec of sections) {
+ const cleanSec = sec.replace(/```mermaid[\s\S]*?```/gu, '').trim();
+ if (!cleanSec) continue;
+ const heading = cleanSec.match(/^#+\s*([^\n]+)/u)?.[1]?.trim() || docTitle;
+ const headLower = `${p} ${docTitle} ${heading}`.toLowerCase();
+ const bodyLower = cleanSec.toLowerCase();
+ let score = 0;
+ if (qLower && bodyLower.includes(qLower)) score += 18;
+ for (const term of qTerms) {
+ if (headLower.includes(term)) score += term.length >= 3 ? 7.5 : 4.5;
+ else if (bodyLower.includes(term)) score += term.length >= 3 ? 3.5 : 1.8;
+ }
+ if (score > 0) {
+ const isRawDelta = p === LEGACY_DELTA_MD_PAGE;
+ sectionCandidates.push({
+ page: p,
+ docTitle,
+ heading,
+ score: isRawDelta ? score * 0.72 : score,
+ cleanSec,
+ });
+ }
+ }
+ }
+
+ sectionCandidates.sort((a, b) => b.score - a.score);
+ const topSections = sectionCandidates.slice(0, 4);
+
+ // Extract & score individual `[label](path#Lstart-Lend)` citations with their surrounding sentence
+ const targetMap = new Map();
+ const linkRe = /\[([^\]]+)\]\(([^)\s#]+)(?:#L?(\d+)(?:-L?(\d+))?)?\)/gu;
+
+ for (const sec of topSections) {
+ for (const line of sec.cleanSec.split('\n')) {
+ let m;
+ linkRe.lastIndex = 0;
+ while ((m = linkRe.exec(line)) !== null) {
+ const hrefPath = m[2].replace(/^\.\//u, '');
+ if (hrefPath.endsWith('.md') || hrefPath.startsWith('http')) continue;
+ const lStart = m[3] ? Number.parseInt(m[3], 10) : 1;
+ const lEnd = m[4] ? Number.parseInt(m[4], 10) : lStart + 35;
+ const key = `${hrefPath}:${lStart}-${lEnd}`;
+
+ let lineBonus = 0;
+ const lineLower = line.toLowerCase();
+ for (const term of qTerms) {
+ if (hrefPath.toLowerCase().includes(term)) lineBonus += 6;
+ if (lineLower.includes(term)) lineBonus += 3;
+ }
+ const totalScore = sec.score + lineBonus;
+ const cleanContext = line
+ .replace(/\[([^\]]+)\]\([^)]+\)/gu, '$1')
+ .replace(/^[-*\d.\s>#]+/u, '')
+ .trim()
+ .slice(0, 150);
+
+ const prev = targetMap.get(key);
+ if (!prev || totalScore > prev.score) {
+ targetMap.set(key, {
+ relPath: hrefPath,
+ lineStart: lStart,
+ lineEnd: lEnd,
+ score: totalScore,
+ context: cleanContext,
+ fromPage: sec.page,
+ });
+ }
+ }
+ }
+ }
+
+ // Diversify targets: cap each file to at most 2 slices so one verbose file never crowds out other modules!
+ const filePickCount = new Map();
+ const rankedTargets = [];
+ for (const item of [...targetMap.values()].sort((a, b) => b.score - a.score)) {
+ const cnt = filePickCount.get(item.relPath) || 0;
+ if (cnt >= 2) continue;
+ filePickCount.set(item.relPath, cnt + 1);
+ rankedTargets.push(item);
+ if (rankedTargets.length >= maxTargets) break;
+ }
+
+ // Verify live SHA-1 & dynamically re-anchor shifted AST symbol line ranges on modified files!
+ for (const t of rankedTargets) {
+ const recHash = manifest.fileHashes?.[t.relPath];
+ const curHash = hashFileSha1(path.join(repoRoot, t.relPath));
+ t.exists = Boolean(curHash);
+ t.fresh = Boolean(curHash && (!recHash || curHash === recHash));
+
+ if (t.exists && !t.fresh) {
+ const parsed = parseLiveOnce(t.relPath);
+ if (parsed && parsed.symbols.length > 0) {
+ const hintIdents = new Set(
+ (`${t.context} ${query}`.match(/[A-Za-z_$][A-Za-z0-9_$]{2,}/gu) || []).map((s) => s.toLowerCase()),
+ );
+ let bestSym = null;
+ let bestSymScore = 0;
+ for (const sym of parsed.symbols) {
+ const sLower = sym.name.toLowerCase();
+ let sc = 0;
+ if (hintIdents.has(sLower)) sc += 20;
+ for (const term of qTerms) {
+ if (sLower.includes(term)) sc += 8;
+ }
+ if (sc > bestSymScore) {
+ bestSymScore = sc;
+ bestSym = sym;
+ }
+ }
+ if (bestSym && (bestSym.lineStart !== t.lineStart || bestSym.lineEnd !== t.lineEnd)) {
+ t.oldSpan = `L${t.lineStart}-L${t.lineEnd}`;
+ t.lineStart = bestSym.lineStart;
+ t.lineEnd = bestSym.lineEnd;
+ t.reanchored = true;
+ } else if (parsed.lineCount < t.lineEnd) {
+ t.lineStart = Math.min(t.lineStart, parsed.lineCount);
+ t.lineEnd = parsed.lineCount;
+ }
+ }
+ }
+ }
+
+ // L0 Live Git-Delta Overlay + L0.5 Synced Machine Delta Index (`.repowiki/delta-index.json`)
+ const scoreDeltaEntry = (relPath, lineCount, symbols, tag) => {
+ const dfLower = relPath.toLowerCase();
+ let fileScore = 0;
+ if (qLower && dfLower.includes(qLower)) fileScore += 12;
+ for (const term of qTerms) {
+ if (dfLower.includes(term)) fileScore += 10;
+ }
+ const symMatches = [];
+ for (const sym of symbols || []) {
+ const sigLower = `${sym.name} ${sym.signature || ''}`.toLowerCase();
+ let symOnlyScore = 0;
+ if (qLower && sigLower.includes(qLower)) symOnlyScore += 14;
+ for (const term of qTerms) {
+ if (sigLower.includes(term)) symOnlyScore += 9;
+ }
+ if (symOnlyScore > 0) {
+ symMatches.push({
+ relPath,
+ lineStart: sym.lineStart,
+ lineEnd: sym.lineEnd,
+ sig: sym.signature || sym.name,
+ score: fileScore + symOnlyScore,
+ tag,
+ });
+ }
+ }
+ if (symMatches.length > 0) {
+ symMatches.sort((a, b) => b.score - a.score);
+ return symMatches.slice(0, 2);
+ }
+ if (fileScore >= 10) {
+ return [
+ {
+ relPath,
+ lineStart: 1,
+ lineEnd: Math.min(60, lineCount || 60),
+ sig: `${relPath} (${lineCount || 0} lines)`,
+ score: fileScore,
+ tag,
+ },
+ ];
+ }
+ return [];
+ };
+
+ const syncedDeltaByPath = new Map();
+ if (deltaIndex?.files) {
+ for (const entry of deltaIndex.files) {
+ if (entry?.relPath) syncedDeltaByPath.set(entry.relPath, entry);
+ }
+ }
+
+ const liveDeltaHits = [];
+ const handledDeltaPaths = new Set();
+ const deltaFiles = collectGitDeltaFilesSince(repoRoot, manifest.gitHead).slice(0, 24);
+ for (const df of deltaFiles) {
+ const absDf = path.join(repoRoot, df);
+ if (!existsSync(absDf)) continue;
+ const syncedEntry = syncedDeltaByPath.get(df);
+ const recHash = manifest.fileHashes?.[df];
+ const curHash = hashFileSha1(absDf);
+
+ // Reuse pre-parsed machine delta-index.json without re-parsing if unchanged since sync
+ if (syncedEntry && recHash && curHash && curHash === recHash) {
+ continue;
+ }
+
+ handledDeltaPaths.add(df);
+ const parsed = parseLiveOnce(df);
+ if (!parsed) continue;
+ const tag = !recHash ? 'LIVE-NEW-FILE' : 'LIVE-MODIFIED-AST';
+ liveDeltaHits.push(...scoreDeltaEntry(df, parsed.lineCount, parsed.symbols, tag));
+ }
+
+ for (const [relPath, entry] of syncedDeltaByPath.entries()) {
+ if (handledDeltaPaths.has(relPath)) continue;
+ const absDf = path.join(repoRoot, relPath);
+ if (!existsSync(absDf)) continue;
+
+ const recHash = manifest.fileHashes?.[relPath];
+ const curHash = hashFileSha1(absDf);
+ let lineCount = entry.lineCount;
+ let symbols = entry.symbols || [];
+ let tag = 'SYNCED-DELTA';
+
+ if (recHash && curHash && curHash !== recHash) {
+ const parsed = parseLiveOnce(relPath);
+ if (parsed) {
+ lineCount = parsed.lineCount;
+ symbols = parsed.symbols;
+ tag = 'LIVE-MODIFIED-AST';
+ }
+ }
+
+ const hits = scoreDeltaEntry(relPath, lineCount, symbols, tag);
+ for (const h of hits) {
+ const alreadyInWikiTargets = rankedTargets.some(
+ (t) => t.exists && t.relPath === h.relPath && t.lineStart <= h.lineStart && t.lineEnd >= h.lineEnd,
+ );
+ if (!alreadyInWikiTargets) {
+ liveDeltaHits.push(h);
+ }
+ }
+ }
+ liveDeltaHits.sort((a, b) => b.score - a.score);
+
+ const elapsedMs = Date.now() - t0;
+ const out = [];
+ out.push(`# RepoWiki Fast Code Router (${elapsedMs}ms)`);
+
+ if (liveDeltaHits.length > 0) {
+ out.push('## Live Working-Tree & Synced Delta Hits (Recent / Unindexed Changes)');
+ for (const d of liveDeltaHits.slice(0, 4)) {
+ out.push(`- \`${d.relPath}\` **L${d.lineStart}-L${d.lineEnd}** [${d.tag}] — \`${d.sig}\``);
+ }
+ out.push('');
+ }
+
+ if (rankedTargets.length > 0) {
+ out.push('## Verified Source Jump Targets (Read ONLY these line ranges directly)');
+ for (const t of rankedTargets) {
+ const statusTag = !t.exists
+ ? 'MISSING'
+ : t.fresh
+ ? 'SHA1-FRESH'
+ : t.reanchored
+ ? `AST-REANCHORED from ${t.oldSpan}`
+ : 'MODIFIED';
+ out.push(
+ `- \`${t.relPath}\` **L${t.lineStart}-L${t.lineEnd}** [${statusTag}] — ${t.context}`,
+ );
+ }
+ out.push('');
+ }
+
+ // Downstream Blast Radius (Direct Importers) — answers "who breaks if I edit this file?" in <2ms
+ const impactIndex = loadImpactIndex(wikiDir);
+ const impactLines = [];
+ const seenImpactFiles = new Set();
+ const collectedImporters = [];
+ for (const rel of [
+ ...liveDeltaHits.slice(0, 2).map((d) => d.relPath),
+ ...rankedTargets.filter((t) => t.exists).map((t) => t.relPath),
+ ]) {
+ if (seenImpactFiles.has(rel)) continue;
+ seenImpactFiles.add(rel);
+ const info = impactIndex[rel];
+ if (!info || info.fanIn <= 0) continue;
+ for (const imp of info.importers || []) {
+ if (!collectedImporters.includes(imp)) collectedImporters.push(imp);
+ }
+ const topImporters = (info.importers || []).slice(0, 5).map((p) => `\`${p}\``).join(', ');
+ const more = info.prodCount > 5 ? ` (+${info.prodCount - 5} more)` : '';
+ const noun = info.fanIn === 1 ? 'importer' : 'importers';
+ const testsNote = info.testCount > 0 ? `, ${info.testCount} ${info.testCount === 1 ? 'test' : 'tests'}` : '';
+ impactLines.push(
+ `- \`${rel}\` (**${info.fanIn}** ${noun}${testsNote}) ← ${topImporters || '(tests only)'}${more}`,
+ );
+ if (impactLines.length >= 4) break;
+ }
+ if (impactLines.length > 0) {
+ out.push('## Downstream Impact Radius (Direct Importers — check before changing exported types)');
+ for (const ln of impactLines) out.push(ln);
+ out.push('');
+ }
+
+ // Targeted Downstream Symbol Reference Lines (scans ONLY direct importers in <8ms!)
+ const candidateSymbols = extractCandidateSymbols(query, options.symbol || '');
+ if (options.symbol && /^[A-Za-z_$][\w$]*$/u.test(options.symbol)) {
+ // An explicit symbol asks "who uses this?": answer completely, repo-wide.
+ const usages = findSymbolUsagesRepoWide(repoRoot, options.symbol);
+ if (usages.length > 0) out.push(...formatSymbolUsages(options.symbol, usages, 150));
+ } else if (candidateSymbols.length > 0 && collectedImporters.length > 0) {
+ const refHits = findSymbolReferencesInImporters(repoRoot, collectedImporters, candidateSymbols, 10);
+ if (refHits.length > 0) {
+ out.push(`## Exact Downstream Symbol References (${candidateSymbols.map((s) => `\`${s}\``).join(', ')})`);
+ for (const h of refHits) {
+ out.push(`- \`${h.relPath}:L${h.line}\`: \`${h.text.replace(/`/gu, "'")}\``);
+ }
+ out.push('');
+ }
+ }
+
+ if (topSections.length > 0) {
+ out.push('## Key Architectural Context');
+ for (const s of topSections.slice(0, 2)) {
+ const condensed = s.cleanSec
+ .split('\n')
+ .filter((ln) => ln.trim() && !ln.trim().startsWith('#'))
+ .slice(0, 4)
+ .map((ln) => ln.replace(/\[([^\]]+)\]\([^)]+\)/gu, '`$1`').trim())
+ .join(' ');
+ out.push(`- **[${s.page} · ${s.heading}]**: ${condensed.slice(0, 280)}`);
+ }
+ out.push('');
+ } else if (liveDeltaHits.length === 0) {
+ out.push('- No direct Wiki section matched query; fall back to targeted symbol grep.');
+ }
+
+ // Inline Live Disk Code Slices for Top 3 Targets (eliminates extra read round-trips before edit!)
+ const combinedSliceCandidates = [
+ ...liveDeltaHits.slice(0, 2).map((d) => ({ relPath: d.relPath, lineStart: d.lineStart, lineEnd: d.lineEnd })),
+ ...rankedTargets.filter((t) => t.exists).slice(0, 3),
+ ];
+ const seenSliceFiles = new Set();
+ const inlineSlices = [];
+ for (const cand of combinedSliceCandidates) {
+ const winKey = `${cand.relPath}:${cand.lineStart}`;
+ if (seenSliceFiles.has(winKey)) continue;
+ seenSliceFiles.add(winKey);
+ try {
+ const raw = readFileSync(path.join(repoRoot, cand.relPath), 'utf8').replace(/\r\n/gu, '\n');
+ const allLines = raw.split('\n');
+ const s = Math.max(1, cand.lineStart - 2);
+ const e = Math.min(allLines.length, Math.min(cand.lineEnd + 3, cand.lineStart + 36));
+ const body = [];
+ for (let ln = s; ln <= e; ln += 1) {
+ body.push(`${String(ln).padStart(4, ' ')} | ${allLines[ln - 1] ?? ''}`);
+ }
+ inlineSlices.push(`### Live Disk Slice: \`${cand.relPath}\` (L${s}-L${e} of ${allLines.length})\n\`\`\`\n${body.join('\n')}\n\`\`\``);
+ } catch {
+ // Skip unreadable file
+ }
+ if (inlineSlices.length >= 3) break;
+ }
+
+ if (inlineSlices.length > 0) {
+ out.push('## Live Disk Code Windows (Exact current lines — edit directly without re-reading if sufficient)');
+ out.push(...inlineSlices);
+ }
+
+ return out.join('\n');
+}
+
+/**
+ * Zero-dependency File Symbol Outline & Exact Symbol Body Inspector (`wiki_locate` with `file`):
+ * - Without `symbol`: returns compact AST symbol outline (`Lstart-Lend`) + downstream importers
+ * (saves ~95% tokens vs reading a 2,000-line file in full).
+ * - With `symbol`: extracts exact complete symbol body + downstream reference lines (<8ms).
+ */
+export function inspectFileSymbolsFast(repoRoot, wikiDir, relFile, symbolName = '') {
+ const t0 = Date.now();
+ const absRepo = path.resolve(repoRoot);
+ const cleanRel = String(relFile || '')
+ .trim()
+ .replace(/\\/gu, '/')
+ .replace(/^\.\//u, '')
+ .replace(/^\/+/u, '');
+ if (!cleanRel) throw new Error('`file` must be a non-empty relative path.');
+ const absFile = path.resolve(absRepo, cleanRel);
+ const relBack = path.relative(absRepo, absFile);
+ if (relBack.startsWith('..') || path.isAbsolute(relBack)) {
+ throw new Error(`File path "${relFile}" escapes repository root.`);
+ }
+ if (!existsSync(absFile)) {
+ throw new Error(`File not found: ${cleanRel}`);
+ }
+ if (statSync(absFile).isDirectory()) {
+ const dir = cleanRel.replace(/\/+$/u, '');
+ const def = symbolName ? findDefinitionIn(absRepo, dir, String(symbolName).trim()) : null;
+ if (def) return inspectFileSymbolsFast(repoRoot, wikiDir, def, symbolName);
+ return describeDirectory(absRepo, dir);
+ }
+
+ const raw = readFileSync(absFile, 'utf8').replace(/\r\n/gu, '\n');
+ const allLines = raw.split('\n');
+ const lang = EXT_TO_LANG[path.extname(cleanRel).toLowerCase()] || 'text';
+ const parsed = lang !== 'text' ? parseSourceFile(raw, lang, cleanRel) : { lineCount: allLines.length, symbols: [] };
+ const symQuery = String(symbolName || '').trim();
+ const isJs = lang === 'typescript' || lang === 'javascript';
+
+ const out = [];
+ out.push(
+ `# File Symbol Inspector: \`${cleanRel}\` (${allLines.length} lines, ${parsed.symbols.length} symbols)`,
+ );
+ const pkgLine = isJs ? describePackageLine(absRepo, cleanRel) : '';
+ if (pkgLine) out.push(pkgLine);
+ if (!isJs) {
+ const impactInfo = loadImpactIndex(wikiDir)[cleanRel];
+ if (impactInfo && impactInfo.fanIn > 0) {
+ const topImporters = (impactInfo.importers || []).slice(0, 5).map((p) => `\`${p}\``).join(', ');
+ const more = impactInfo.prodCount > 5 ? ` (+${impactInfo.prodCount - 5} more)` : '';
+ out.push(`- **Imported by**: ${impactInfo.fanIn} files ← ${topImporters || '(tests only)'}${more}`);
+ }
+ }
+ out.push('');
+
+ if (symQuery) {
+ const qLower = symQuery.toLowerCase();
+ const exact = parsed.symbols.filter((s) => s.name.toLowerCase() === qLower);
+ const matched =
+ exact.length > 0
+ ? exact
+ : parsed.symbols.filter((s) => s.name.toLowerCase().includes(qLower) || s.signature.toLowerCase().includes(qLower));
+
+ if (matched.length === 0) {
+ out.push(`- Symbol \`${symQuery}\` not found in \`${cleanRel}\`. Available top symbols:`);
+ for (const s of parsed.symbols.slice(0, 20)) {
+ out.push(` - \`${s.signature}\` (L${s.lineStart}-L${s.lineEnd})`);
+ }
+ return `${out.join('\n')}\n`;
+ }
+
+ for (const sym of matched.slice(0, 3)) {
+ const start = Math.max(1, sym.lineStart);
+ const end = Math.min(allLines.length, Math.min(sym.lineEnd, sym.lineStart + 119));
+ const truncated = sym.lineEnd > end ? ` (truncated at +120 lines; full ends at L${sym.lineEnd})` : '';
+ out.push(`## Symbol Body: \`${sym.name}\` (\`${cleanRel}:L${sym.lineStart}-L${sym.lineEnd}\`)${truncated}`);
+ out.push('```');
+ for (let ln = start; ln <= end; ln += 1) {
+ out.push(`${String(ln).padStart(4, ' ')} | ${allLines[ln - 1] ?? ''}`);
+ }
+ out.push('```');
+ out.push('');
+ }
+
+ const usages = findSymbolUsagesRepoWide(absRepo, matched[0].name);
+ const trace = isJs && matched[0].exported !== false ? traceImporters(absRepo, cleanRel, [matched[0].name]) : null;
+ if (trace && trace.importers.length > 0) {
+ out.push(
+ ...formatImporters(`Who imports \`${matched[0].name}\``, trace, {
+ maxTotal: 50,
+ wordMatches: usages.map((u) => u.relPath),
+ word: matched[0].name,
+ }),
+ );
+ } else if (usages.length > 0) {
+ out.push(...formatSymbolUsages(matched[0].name, usages, 150));
+ }
+ out.push(`(${Date.now() - t0}ms)`);
+ return `${out.join('\n')}\n`;
+ }
+
+ if (isJs) {
+ const exported = parsed.symbols.filter((s) => s.exported && !s.parent).map((s) => s.name);
+ if (exported.length > 0) {
+ out.push(...formatImporters('Who imports this file', traceImporters(absRepo, cleanRel, exported), { maxTotal: 40 }));
+ }
+ }
+
+ out.push('## Symbol Outline (Call `wiki_locate` with `file` + `symbol` to inspect a full body)');
+ if (parsed.symbols.length === 0) {
+ out.push('- No structured top-level symbols detected.');
+ } else {
+ for (const s of parsed.symbols.slice(0, 60)) {
+ const span = s.lineEnd > s.lineStart ? `L${s.lineStart}-L${s.lineEnd}` : `L${s.lineStart}`;
+ out.push(`- **${span}** \`${s.signature.replace(/`/gu, "'").slice(0, 120)}\``);
+ }
+ if (parsed.symbols.length > 60) {
+ out.push(`- *(+${parsed.symbols.length - 60} more symbols)*`);
+ }
+ }
+ out.push(`(${Date.now() - t0}ms)`);
+ return `${out.join('\n')}\n`;
+}
+
+/** One line on the package a file belongs to: its import name, entry and how to test/check it. */
+function describePackageLine(absRepo, relFile) {
+ const info = createSpecifierResolver(absRepo).packageOf(relFile);
+ if (!info || !info.dir) return '';
+ const scripts = ['test', 'check', 'typecheck', 'lint', 'build']
+ .filter((k) => info.scripts[k])
+ .map((k) => `\`${k}\`: \`${String(info.scripts[k]).slice(0, 60)}\``);
+ return `- **Package**: \`${info.name}\` (\`${info.dir}/\`)${scripts.length ? ` — scripts run from \`${info.dir}/\`: ${scripts.join(', ')}` : ''}`;
+}
+
+/** The file under `relDir` that declares `symbol` (source before tests), or null. */
+function findDefinitionIn(absRepo, relDir, symbol) {
+ if (!/^[A-Za-z_$][\w$]*$/u.test(symbol)) return null;
+ // POSIX ERE (git grep -E): no \\s or \\b.
+ const sp = '[[:space:]]';
+ const re = `^${sp}*(export${sp}+)?(declare${sp}+)?(default${sp}+)?(abstract${sp}+)?(type|interface|class|function|const|let|var|enum|def|struct|fn|func)${sp}+${symbol.replace(/\$/gu, '[$]')}([^A-Za-z0-9_$,}]|$)`;
+ let hits = [];
+ try {
+ hits = execFileSync('git', ['-C', absRepo, 'grep', '-l', '-E', '--untracked', '--exclude-standard', '-e', re, '--', relDir || '.'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 4000,
+ })
+ .split('\n')
+ .filter((f) => f && EXT_TO_LANG[path.extname(f).toLowerCase()] && !/(^|\/)(node_modules|dist|examples?)\//u.test(f));
+ } catch {
+ return null;
+ }
+ const isTest = (f) => /(^|\/)(test|tests|__tests__|spec)(\/|$)|\.(test|spec)\.[a-z]+$/iu.test(f);
+ hits.sort((a, b) => Number(isTest(a)) - Number(isTest(b)) || a.length - b.length);
+ // A line like `type X,` inside an export list also matches; keep files whose parse declares it.
+ for (const f of hits.slice(0, 20)) {
+ try {
+ const parsed = parseSourceFile(readFileSync(path.join(absRepo, f), 'utf8'), EXT_TO_LANG[path.extname(f).toLowerCase()], f);
+ if (parsed.symbols.some((s) => s.name === symbol)) return f;
+ } catch {
+ // unreadable: skip
+ }
+ }
+ return null;
+}
+
+/** `file` pointing at a folder: its package, entry files and the code files in it with their symbols. */
+function describeDirectory(absRepo, relDir) {
+ const out = [`# Folder: \`${relDir}/\``];
+ const resolver = createSpecifierResolver(absRepo);
+ const info = resolver.packageOf(`${relDir}/x`);
+ if (info && info.dir === relDir) {
+ const entries = [];
+ for (const spec of [info.name]) {
+ const hit = resolver.resolve(`${relDir}/x.ts`, spec);
+ if (hit) entries.push(`\`${spec}\` → \`${hit}\``);
+ }
+ out.push(describePackageLine(absRepo, `${relDir}/x`));
+ if (entries.length) out.push(`- **Entry**: ${entries.join(', ')}`);
+ }
+ let files = [];
+ try {
+ files = execFileSync('git', ['-C', absRepo, 'ls-files', '--cached', '--others', '--exclude-standard', '--', relDir], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 4000,
+ })
+ .split('\n')
+ .filter((f) => f && EXT_TO_LANG[path.extname(f).toLowerCase()]);
+ } catch {
+ files = [];
+ }
+ out.push(`- ${files.length} code files. Call \`wiki_locate\` with one of them as \`file\` (and a \`symbol\`) for bodies and importers.`);
+ for (const f of files.slice(0, 40)) {
+ let names = '';
+ try {
+ const parsed = parseSourceFile(readFileSync(path.join(absRepo, f), 'utf8'), EXT_TO_LANG[path.extname(f).toLowerCase()], f);
+ const top = parsed.symbols.filter((s) => !s.parent && s.exported !== false).map((s) => s.name);
+ names = top.length ? `: ${top.slice(0, 12).join(', ')}${top.length > 12 ? ` +${top.length - 12}` : ''}` : '';
+ } catch {
+ names = '';
+ }
+ out.push(`- \`${f}\`${names}`);
+ }
+ if (files.length > 40) out.push(`- … ${files.length - 40} more`);
+ return `${out.join('\n')}\n`;
+}
+
+function collectGitRenamesSince(repoRoot, baseHead) {
+ const renames = new Map();
+ const applyRename = (oldP, newP) => {
+ if (!oldP || !newP || oldP === newP) return;
+ // Compose rename chains (A -> B then B -> C becomes A -> C)
+ let chained = false;
+ for (const [k, v] of renames.entries()) {
+ if (v === oldP) {
+ renames.set(k, newP);
+ chained = true;
+ }
+ }
+ if (!chained) renames.set(oldP, newP);
+ };
+ const parseLines = (raw) => {
+ for (const ln of raw.split('\n')) {
+ if (!ln) continue;
+ const parts = ln.split('\t');
+ if (parts.length >= 3 && parts[0].startsWith('R')) {
+ applyRename(parts[1].replace(/\\/gu, '/').trim(), parts[2].replace(/\\/gu, '/').trim());
+ }
+ }
+ };
+ const runGit = (args) => {
+ try {
+ const raw = execFileSync('git', ['-C', repoRoot, ...args], {
+ timeout: 2500,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ .toString('utf8')
+ .trim();
+ if (raw) parseLines(raw);
+ } catch {
+ // Ignore non-git or invalid baseHead
+ }
+ };
+ if (baseHead) {
+ // Replay per-commit renames in chronological order so heavy edits prior to `git mv` still resolve cleanly
+ runGit(['log', '-M', '--diff-filter=R', '--name-status', '--format=', '--reverse', `${baseHead}..HEAD`]);
+ }
+ runGit(['diff', '-M', '--name-status', '--cached']);
+ return renames;
+}
+
+/**
+ * Zero-Token Deterministic AST Wiki Sync (`repowiki sync` — <80ms, 0 LLM tokens!).
+ * Replaces expensive LLM prose rewrites during active coding sprints by:
+ * 1) Following `git mv` file renames/moves and rewriting old citation paths automatically;
+ * 2) Re-anchoring shifted `[label](path#Lstart-Lend)` citations in existing `.md` pages via live AST;
+ * 3) Indexing newly created/modified files & symbols into hidden machine index `.repowiki/delta-index.json`
+ * (and removing legacy `03-guides/00-live-delta.md` so human Wiki navigation stays clean);
+ * 4) Updating `manifest.json` SHA-1 fingerprints and Git HEAD baseline.
+ */
+/** Replace the line span inside a citation label: `x.ts:L10-L20` / `x.ts:10-20` / `Foo (L3)`. */
+function relabelSpan(label, newSpan) {
+ if (/L\d+(?:-L?\d+)?/u.test(label)) return label.replace(/L\d+(?:-L?\d+)?/u, newSpan);
+ if (/:\d+(?:-\d+)?/u.test(label)) return label.replace(/:\d+(?:-\d+)?/u, `:${newSpan}`);
+ return label;
+}
+
+export function syncWikiAstDeterministic(repoRoot, wikiDir) {
+ const t0 = Date.now();
+ const manifest = loadManifest(wikiDir);
+
+ // Remove legacy human-facing 03-guides/00-live-delta.md so the human Wiki sidebar stays 100% clean
+ const legacyDeltaAbs = path.join(wikiDir, LEGACY_DELTA_MD_PAGE);
+ if (existsSync(legacyDeltaAbs)) {
+ try {
+ rmSync(legacyDeltaAbs, { force: true });
+ } catch {
+ // Non-fatal cleanup
+ }
+ }
+ if (manifest.pages && Object.prototype.hasOwnProperty.call(manifest.pages, LEGACY_DELTA_MD_PAGE)) {
+ delete manifest.pages[LEGACY_DELTA_MD_PAGE];
+ }
+
+ if (!manifest.baselineGitHead && manifest.gitHead) {
+ manifest.baselineGitHead = manifest.gitHead;
+ }
+ const diffBase = manifest.baselineGitHead || manifest.gitHead;
+ const renameMap = collectGitRenamesSince(repoRoot, diffBase);
+ if (manifest.gitHead && manifest.gitHead !== diffBase) {
+ for (const [k, v] of collectGitRenamesSince(repoRoot, manifest.gitHead)) {
+ renameMap.set(k, v);
+ }
+ }
+ const deltaSet = new Set([
+ ...(manifest.deltaTrackedFiles || []).map((f) => renameMap.get(f) || f),
+ ...collectGitDeltaFilesSince(repoRoot, diffBase),
+ ...collectGitDeltaFilesSince(repoRoot, manifest.gitHead),
+ ...renameMap.values(),
+ ]);
+
+ // Also include any file in manifest.fileHashes whose SHA-1 changed
+ for (const [relPath, oldHash] of Object.entries(manifest.fileHashes ?? {})) {
+ const curHash = hashFileSha1(path.join(repoRoot, relPath));
+ if (curHash && curHash !== oldHash) {
+ deltaSet.add(relPath);
+ }
+ }
+ const deltaFiles = [...deltaSet];
+ manifest.deltaTrackedFiles = deltaFiles;
+
+ const parsedMap = new Map();
+ for (const rel of deltaFiles) {
+ const lang = EXT_TO_LANG[path.extname(rel).toLowerCase()];
+ if (!lang) continue;
+ try {
+ const raw = readFileSync(path.join(repoRoot, rel), 'utf8');
+ parsedMap.set(rel, parseSourceFile(raw, lang, rel));
+ } catch {
+ // Ignore deleted or unreadable file
+ }
+ }
+
+ let reanchoredCount = 0;
+ const reanchoredDetails = [];
+ const mdPages = listMarkdownWikiPages(wikiDir).filter((p) => p !== LEGACY_DELTA_MD_PAGE);
+
+ for (const relDoc of mdPages) {
+ const absDoc = path.join(wikiDir, relDoc);
+ let md;
+ try {
+ md = readFileSync(absDoc, 'utf8').replace(/\r\n/gu, '\n');
+ } catch {
+ continue;
+ }
+ let changedDoc = false;
+ const anchorBySpan = new Map();
+ for (const a of manifest.pages?.[relDoc]?.anchors || []) {
+ const k = `${a.file}:${a.start}-${a.end}`;
+ if (!anchorBySpan.has(k)) anchorBySpan.set(k, a);
+ }
+ const updatedLines = md.split('\n').map((line) => {
+ return line.replace(
+ /\[([^\]]+)\]\(([^)\s#]+)#L?(\d+)(?:-L?(\d+))?\)/gu,
+ (fullMatch, label, hrefPath, sStr, eStr, matchOffset) => {
+ const origRel = hrefPath.replace(/^\.\//u, '');
+ const renamedTo = renameMap.get(origRel);
+ const cleanRel = renamedTo || origRel;
+ let nextHref = renamedTo ? (hrefPath.startsWith('./') ? `./${renamedTo}` : renamedTo) : hrefPath;
+ let nextLabel = label;
+ let didRename = false;
+ if (renamedTo) {
+ const oldBase = path.posix.basename(origRel);
+ const newBase = path.posix.basename(renamedTo);
+ if (nextLabel.includes(origRel)) nextLabel = nextLabel.replace(origRel, renamedTo);
+ else if (nextLabel.includes(oldBase)) nextLabel = nextLabel.replace(oldBase, newBase);
+ didRename = true;
+ changedDoc = true;
+ reanchoredCount += 1;
+ reanchoredDetails.push({
+ doc: relDoc,
+ file: renamedTo,
+ symbol: '(renamed)',
+ from: origRel,
+ to: renamedTo,
+ });
+ }
+
+ const oldS = Number.parseInt(sStr, 10);
+ const oldE = eStr ? Number.parseInt(eStr, 10) : oldS;
+ const oldSpan = eStr ? `L${oldS}-L${oldE}` : `L${oldS}`;
+ // Look anchors up by where they were before this sync: updating one anchor must
+ // not make it match another citation that sits at its new lines.
+ const anchor =
+ anchorBySpan.get(`${origRel}:${oldS}-${oldE}`) || anchorBySpan.get(`${cleanRel}:${oldS}-${oldE}`);
+ if (anchor) anchor.file = cleanRel;
+ const parsed = parsedMap.get(cleanRel);
+ if (!parsed || parsed.symbols.length === 0) {
+ return didRename ? `[${nextLabel}](${nextHref}#${oldSpan})` : fullMatch;
+ }
+ // Prefer the symbol recorded when the chapter was written: it works even when the
+ // citation label does not name the symbol, and keeps part-of-symbol ranges precise.
+ const loc = anchor ? relocateAnchor(anchor, parsed.symbols) : null;
+ if (loc) {
+ anchor.start = loc.start;
+ anchor.end = loc.end;
+ anchor.symStart = loc.sym.lineStart;
+ anchor.symEnd = loc.sym.lineEnd;
+ if (loc.start === oldS && loc.end === oldE) {
+ return didRename ? `[${nextLabel}](${nextHref}#${oldSpan})` : fullMatch;
+ }
+ changedDoc = true;
+ if (!didRename) reanchoredCount += 1;
+ const newSpan = `L${loc.start}-L${loc.end}`;
+ reanchoredDetails.push({ doc: relDoc, file: cleanRel, symbol: anchor.symbol, from: `L${oldS}-L${oldE}`, to: newSpan });
+ nextLabel = relabelSpan(nextLabel, newSpan);
+ return `[${nextLabel}](${nextHref}#${newSpan})`;
+ }
+ // Match identifiers in the immediate local window (~48 chars before citation + label itself)
+ // and pick the symbol closest to oldS within a sane drift window (<= 250 lines)!
+ const localPrefix = line.slice(Math.max(0, matchOffset - 48), matchOffset) + ' ' + nextLabel;
+ const localIdents = new Set(
+ (localPrefix.match(/[A-Za-z_$][A-Za-z0-9_$]{2,}/gu) || []).map((x) => x.toLowerCase()),
+ );
+ const candidates = parsed.symbols.filter(
+ (sym) => localIdents.has(sym.name.toLowerCase()) && Math.abs(sym.lineStart - oldS) <= 250,
+ );
+ if (candidates.length === 0) {
+ return didRename ? `[${nextLabel}](${nextHref}#${oldSpan})` : fullMatch;
+ }
+ candidates.sort((a, b) => Math.abs(a.lineStart - oldS) - Math.abs(b.lineStart - oldS));
+ const matchedSym = candidates[0];
+ if (matchedSym.lineStart === oldS && matchedSym.lineEnd === oldE) {
+ return didRename ? `[${nextLabel}](${nextHref}#${oldSpan})` : fullMatch;
+ }
+ changedDoc = true;
+ if (!didRename) reanchoredCount += 1;
+ const newSpan = `L${matchedSym.lineStart}-L${matchedSym.lineEnd}`;
+ if (anchor) {
+ anchor.start = matchedSym.lineStart;
+ anchor.end = matchedSym.lineEnd;
+ anchor.symbol = matchedSym.name;
+ anchor.symStart = matchedSym.lineStart;
+ anchor.symEnd = matchedSym.lineEnd;
+ }
+ reanchoredDetails.push({
+ doc: relDoc,
+ file: cleanRel,
+ symbol: matchedSym.name,
+ from: `L${oldS}-L${oldE}`,
+ to: newSpan,
+ });
+ nextLabel = relabelSpan(nextLabel, newSpan);
+ return `[${nextLabel}](${nextHref}#${newSpan})`;
+ },
+ );
+ });
+ if (changedDoc) {
+ writeFileSync(absDoc, updatedLines.join('\n'), 'utf8');
+ }
+ }
+
+ const newHead = getGitHeadCommit(repoRoot);
+ const nowIso = new Date().toISOString();
+
+ // Write/update hidden machine delta index for newly created / modified symbols
+ let deltaPagePath = null;
+ if (parsedMap.size > 0) {
+ const files = [...parsedMap.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([relPath, parsed]) => ({
+ relPath,
+ lineCount: parsed.lineCount,
+ symbols: [...parsed.symbols]
+ .sort((a, b) => a.lineStart - b.lineStart || a.name.localeCompare(b.name))
+ .slice(0, 32)
+ .map((s) => ({
+ name: s.name,
+ kind: s.kind,
+ signature: s.signature,
+ lineStart: s.lineStart,
+ lineEnd: s.lineEnd,
+ })),
+ }));
+
+ deltaPagePath = DELTA_INDEX_FILE;
+ mkdirSync(wikiDir, { recursive: true });
+ writeFileSync(
+ path.join(wikiDir, DELTA_INDEX_FILE),
+ `${JSON.stringify({ updatedAt: nowIso, gitHead: newHead, files }, null, 2)}\n`,
+ 'utf8',
+ );
+ }
+
+ let headSubject = '';
+ try {
+ headSubject = execFileSync('git', ['-C', repoRoot, 'log', '-1', '--format=%s'], {
+ timeout: 1500,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ .toString('utf8')
+ .trim();
+ } catch {
+ // Ignore non-git
+ }
+
+ if (!Array.isArray(manifest.syncHistory)) manifest.syncHistory = [];
+ if (parsedMap.size > 0 || reanchoredCount > 0) {
+ const entry = {
+ at: nowIso,
+ gitHead: newHead || 'working-tree',
+ commitSubject: headSubject,
+ elapsedMs: Date.now() - t0,
+ syncedFiles: [...parsedMap.keys()],
+ reanchoredCount,
+ reanchoredDetails: reanchoredDetails.slice(0, 16),
+ };
+ // Re-syncing the same HEAD (e.g. a manual rescan) must not add a second row for one commit.
+ const prev = manifest.syncHistory[0];
+ if (prev && prev.gitHead === entry.gitHead) {
+ const seen = new Set();
+ entry.reanchoredDetails = [...entry.reanchoredDetails, ...(prev.reanchoredDetails || [])]
+ .filter((d) => {
+ const k = `${d.file}:${d.symbol}:${d.to}`;
+ if (seen.has(k)) return false;
+ seen.add(k);
+ return true;
+ })
+ .slice(0, 16);
+ entry.reanchoredCount = Math.max(reanchoredCount, prev.reanchoredCount || 0);
+ manifest.syncHistory[0] = entry;
+ } else {
+ manifest.syncHistory.unshift(entry);
+ }
+ if (manifest.syncHistory.length > 25) manifest.syncHistory.length = 25;
+ }
+
+ manifest.gitHead = newHead;
+ manifest.updatedAt = nowIso;
+ for (const oldRel of renameMap.keys()) {
+ delete manifest.fileHashes[oldRel];
+ }
+ for (const rel of new Set([...Object.keys(manifest.fileHashes ?? {}), ...parsedMap.keys()])) {
+ const h = hashFileSha1(path.join(repoRoot, rel));
+ if (h) manifest.fileHashes[rel] = h;
+ }
+ saveManifest(wikiDir, manifest, repoRoot);
+
+ return {
+ elapsedMs: Date.now() - t0,
+ syncedFiles: [...parsedMap.keys()],
+ reanchoredCitations: reanchoredCount,
+ reanchoredDetails,
+ deltaPagePath,
+ };
+}
diff --git a/plugins/Jialei-03/mcode-repowiki/skills/SKILL.md b/plugins/Jialei-03/mcode-repowiki/skills/SKILL.md
new file mode 100644
index 00000000..cc5df1a2
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/skills/SKILL.md
@@ -0,0 +1,95 @@
+---
+name: mcode-repowiki
+description: Local project Wiki & fast code router (`.repowiki/`). In a repo that has `.repowiki/`, call `wiki_locate` FIRST for any question about the code AND before any code change — adding a feature, fixing a bug, refactoring, or asking what a change would affect — even when the user already named the package or folder. One call returns the exact file and line range, the existing sibling code to copy, where it is exported, and every file that imports it; it replaces 5–20 rounds of grep/glob/read. Use `wiki_plan`, `wiki_write_page`, and `wiki_serve` to generate the Wiki, and to update only the chapters whose cited code changed when the user asks to update it.
+---
+
+# RepoWiki — Local Project Wiki & Fast Code Router
+
+Always match the user's conversation language (write all Wiki chapters and Mermaid labels in **Simplified Chinese** when the user asks in Chinese). Always pass the absolute target repository path as `repo_path`.
+
+## 1. Daily Coding: `wiki_locate` Before Reading or Editing
+
+Whenever a `.repowiki/` exists in the workspace, make `wiki_locate` your first tool call for **every** code task — questions *and* changes. Skip it only when the user gave an exact file **and** line number.
+
+| Task | First call |
+|---|---|
+| "How does X work?" / "Where is X?" | `wiki_locate` with `query` (or `queries: [...]` for 2–4 subsystems at once) |
+| Add a feature next to existing code ("add a `uuid()` like `str()`") | `wiki_locate` with `file` + `symbol` of the sibling to copy (or `query` if you don't know the file yet) — you get its exact current body, the line where it is exported from the package entry, and the files that import it |
+| Change or rename a shared type/function, or "what would this change affect?" | `wiki_locate` with `file` + `symbol` — returns every importer and the exact reference lines |
+| A big file you only need part of | `wiki_locate` with `file` alone — a symbol outline with line ranges instead of reading the whole file |
+
+Then:
+1. Read only the `Lstart-Lend` windows you still need; the returned slices are live from disk.
+2. When editing, also update the places `wiki_locate` listed: the package entry that re-exports the symbol, and the importers/tests that use it.
+3. Targets marked `[AST-REANCHORED]` or `[LIVE-NEW-FILE]` are already resolved against live disk files and Git deltas.
+
+## 2. Building or Updating the Local Project Wiki
+
+### Step 1 — Inspect Architecture & Freshness (`wiki_plan`)
+Call `wiki_plan` (`repo_path`) first.
+- **A Wiki already exists** → do not regenerate it. The result starts with a **Wiki Freshness** report: which chapters cite code that has changed since they were written, citation by citation. Follow Step 4 for those chapters only.
+- **No Wiki yet, or the user asked for a full rebuild** → follow the blueprint:
+ - **Level 1 (`README.md`)** — overview, see "Overview chapter" below.
+ - **Level 2 (`01-architecture/`)** — `01-system-overview.md` (layers, one `flowchart TD`), `02-core-workflows.md` (the 2–3 main runtime flows, `sequenceDiagram`, every step cited), `03-dependencies-and-boundaries.md` (which package may depend on which, cycles).
+ - **Level 3 (`02-modules/.md`)** — one chapter per module, see "Module chapter" below.
+ - **Level 4 (`03-guides/`)** — `01-getting-started.md` (install, build, test, run — commands copied from the repo's own scripts) and `02-extension-playbook.md` (recipes: "to add an X, touch these files in this order", with citations).
+- Call `wiki_serve` early so the user can watch chapters appear in the browser while you write.
+
+### Step 2 — Gather Evidence (`wiki_plan` with `module_id`) and Write (`wiki_write_page`)
+1. Call `wiki_plan` with `module_id: "architecture"` for Levels 1, 2 and 4, and `module_id: ""` for each module. Read the key files it lists before writing; never write a chapter from the file list alone. On large repos, delegate modules to `worker` subagents in parallel when available.
+2. Save each chapter with `wiki_write_page`. Its result ends with **Writing Checks**; fix every item and save the whole chapter again until they pass.
+
+### Write for two readers
+Every chapter is read by a person in the browser **and** returned section by section to an AI by `wiki_locate`. Both need the same things:
+- **Plain language first.** Open each chapter and each `##` section with what it is for, in one or two sentences, before any symbol names. Explain a project term the first time it appears. Short paragraphs (≤ 5 sentences); use a numbered list for a sequence and a table for a lookup.
+- **Self-contained sections.** `wiki_locate` returns one `##` section at a time, so each section must make sense alone: name the package and the exact symbols it talks about instead of "it" / "this module" / "see above".
+- **Precise citations.** Cite the specific function, method or type you describe, as `[Symbol · file.ts:L10-L45](path/to/file.ts#L10-L45)`, using the repo-relative path. Keep ranges under ~200 lines — cite `AgentSession.prompt`, not the whole 4,000-line class. Citations are re-anchored to their symbol when code moves, so prefer ranges that cover a declaration.
+- **No numbers that go stale.** Do not write line counts, file counts or version numbers in prose ("4,579 lines", "269 files", "version 3"); the reader shows live counts, and a cited line shows the current value. Describe size in words ("the largest package").
+- **Say what you could not confirm.** If a step or behaviour is not visible in the code you read, write "(not confirmed in code)" rather than guessing.
+- **Titles are plain names**: use the `title` from `wiki_plan` as the H1 (`# 项目概览`, `# pi-schema`). No repo-name prefix, numbers, file paths or adjectives ("零开销", "新一代", "全景") in titles.
+- **Diagrams**: one small Mermaid diagram where it helps; quote labels with parentheses (`A["pi-tui (UI)"]`).
+- Match the user's language (Simplified Chinese when the user writes Chinese), including headings and diagram labels.
+
+### Overview chapter (`README.md`)
+Sections, in order:
+1. **What this repository is** — the problem it solves and who uses it, in 3–4 sentences.
+2. **Mental model** — the layers, bottom to top, one line each.
+3. **Module map** — a table: module · one-line purpose · link to its chapter (`[pi-ai](02-modules/01-ai.md)`).
+4. **Where to change what** — a table of 5–10 common tasks ("add an LLM provider", "add a CLI command") → the chapter and the entry file to open, with a citation.
+5. **Glossary** — 5–12 project terms a newcomer will meet, one line each.
+6. **Reading route** — what to read first for "run it", "understand the core", "change it".
+
+### Module chapter (`02-modules/`)
+A module chapter teaches a newcomer the module well enough to change it. Use these six `##` sections, in this order (headings in the user's language):
+1. **What it does** — 2–3 plain sentences: the problem it solves and what would break without it.
+2. **Where it sits** — who calls it and what it depends on (from the evidence pack's upstream/downstream lists), with one small `flowchart`.
+3. **Core concepts** — the 3–5 types/classes/functions a reader must know. For each: what it represents, how it is used, one citation.
+4. **One call, step by step** — follow one real, typical call through the module (entry → internal steps → result) as a numbered list. **Every step names the function that runs and cites it.**
+5. **How to change it** — recipes for the 2–4 most likely changes (which files, in which order), the invariants that must hold, and the tests that cover it (cite the test file).
+6. **Key files** — a table: file · one-line responsibility · main symbols.
+Aim for roughly 80–160 lines.
+
+### Before you save a chapter, check
+- [ ] Each `##` section opens with a plain sentence and makes sense on its own.
+- [ ] Every walkthrough step and every core concept has a citation; no citation spans a whole large class or file.
+- [ ] No line counts, file counts or version numbers in prose.
+- [ ] Module chapters have the six sections; the overview links every module chapter.
+
+### Step 2b — One-Line File & Module Descriptions (no extra tool)
+The graph view shows a one-sentence description next to each file and module. After writing the chapters, use your normal file-write tool to create `.repowiki/descriptions.json`:
+```json
+{ "modules": { "packages/schema": "用普通对象描述 JSON Schema,并推导出 TypeScript 类型" },
+ "files": { "packages/schema/src/builders.ts": "导出 str/num 等构建函数,返回带静态类型的普通 JSON Schema" } }
+```
+Keys are repo-relative paths; module keys are the graph groups (`packages/`, `apps/`, top-level folder). One plain sentence each, in the user's language, saying what the file is for — no adjectives. Cover every module and the files you cited; skip files you have not read. The reader hot-reloads this file.
+
+### Step 3 — Compile and Open the Reader (`wiki_serve`)
+Call `wiki_serve` (`repo_path`). It builds `.repowiki/index.html`, hides `.repowiki/` from `git status` via `.git/info/exclude`, installs a post-commit hook that re-syncs line numbers after every commit (0 tokens), and starts the reader at `http://127.0.0.1:`. Pass `build_only: true` to build without starting a server.
+
+### Step 4 — Keeping the Wiki Current
+Line numbers follow the code automatically (post-commit hook, or `wiki_plan` with `sync: true`). Prose does not, so when `wiki_plan` reports chapters whose cited code changed:
+1. `wiki_plan` with `sync: true`, so every line number is current.
+2. For each changed citation it lists, `wiki_locate` with `file` + `symbol` to read the code as it is now, and compare it with the paragraph that cites it.
+3. Edit only what is now wrong (a renamed function, a new step, a removed option, a deleted file); keep every other sentence as it was. Save the whole chapter with `wiki_write_page`.
+4. If a flagged chapter is still correct, call `wiki_plan` with `mark_reviewed: [""]` instead of rewriting it.
+5. Tell the user which chapters you changed and what changed in each.
diff --git a/plugins/Jialei-03/mcode-repowiki/skills/mcode-repowiki/SKILL.md b/plugins/Jialei-03/mcode-repowiki/skills/mcode-repowiki/SKILL.md
new file mode 100644
index 00000000..cc5df1a2
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/skills/mcode-repowiki/SKILL.md
@@ -0,0 +1,95 @@
+---
+name: mcode-repowiki
+description: Local project Wiki & fast code router (`.repowiki/`). In a repo that has `.repowiki/`, call `wiki_locate` FIRST for any question about the code AND before any code change — adding a feature, fixing a bug, refactoring, or asking what a change would affect — even when the user already named the package or folder. One call returns the exact file and line range, the existing sibling code to copy, where it is exported, and every file that imports it; it replaces 5–20 rounds of grep/glob/read. Use `wiki_plan`, `wiki_write_page`, and `wiki_serve` to generate the Wiki, and to update only the chapters whose cited code changed when the user asks to update it.
+---
+
+# RepoWiki — Local Project Wiki & Fast Code Router
+
+Always match the user's conversation language (write all Wiki chapters and Mermaid labels in **Simplified Chinese** when the user asks in Chinese). Always pass the absolute target repository path as `repo_path`.
+
+## 1. Daily Coding: `wiki_locate` Before Reading or Editing
+
+Whenever a `.repowiki/` exists in the workspace, make `wiki_locate` your first tool call for **every** code task — questions *and* changes. Skip it only when the user gave an exact file **and** line number.
+
+| Task | First call |
+|---|---|
+| "How does X work?" / "Where is X?" | `wiki_locate` with `query` (or `queries: [...]` for 2–4 subsystems at once) |
+| Add a feature next to existing code ("add a `uuid()` like `str()`") | `wiki_locate` with `file` + `symbol` of the sibling to copy (or `query` if you don't know the file yet) — you get its exact current body, the line where it is exported from the package entry, and the files that import it |
+| Change or rename a shared type/function, or "what would this change affect?" | `wiki_locate` with `file` + `symbol` — returns every importer and the exact reference lines |
+| A big file you only need part of | `wiki_locate` with `file` alone — a symbol outline with line ranges instead of reading the whole file |
+
+Then:
+1. Read only the `Lstart-Lend` windows you still need; the returned slices are live from disk.
+2. When editing, also update the places `wiki_locate` listed: the package entry that re-exports the symbol, and the importers/tests that use it.
+3. Targets marked `[AST-REANCHORED]` or `[LIVE-NEW-FILE]` are already resolved against live disk files and Git deltas.
+
+## 2. Building or Updating the Local Project Wiki
+
+### Step 1 — Inspect Architecture & Freshness (`wiki_plan`)
+Call `wiki_plan` (`repo_path`) first.
+- **A Wiki already exists** → do not regenerate it. The result starts with a **Wiki Freshness** report: which chapters cite code that has changed since they were written, citation by citation. Follow Step 4 for those chapters only.
+- **No Wiki yet, or the user asked for a full rebuild** → follow the blueprint:
+ - **Level 1 (`README.md`)** — overview, see "Overview chapter" below.
+ - **Level 2 (`01-architecture/`)** — `01-system-overview.md` (layers, one `flowchart TD`), `02-core-workflows.md` (the 2–3 main runtime flows, `sequenceDiagram`, every step cited), `03-dependencies-and-boundaries.md` (which package may depend on which, cycles).
+ - **Level 3 (`02-modules/.md`)** — one chapter per module, see "Module chapter" below.
+ - **Level 4 (`03-guides/`)** — `01-getting-started.md` (install, build, test, run — commands copied from the repo's own scripts) and `02-extension-playbook.md` (recipes: "to add an X, touch these files in this order", with citations).
+- Call `wiki_serve` early so the user can watch chapters appear in the browser while you write.
+
+### Step 2 — Gather Evidence (`wiki_plan` with `module_id`) and Write (`wiki_write_page`)
+1. Call `wiki_plan` with `module_id: "architecture"` for Levels 1, 2 and 4, and `module_id: ""` for each module. Read the key files it lists before writing; never write a chapter from the file list alone. On large repos, delegate modules to `worker` subagents in parallel when available.
+2. Save each chapter with `wiki_write_page`. Its result ends with **Writing Checks**; fix every item and save the whole chapter again until they pass.
+
+### Write for two readers
+Every chapter is read by a person in the browser **and** returned section by section to an AI by `wiki_locate`. Both need the same things:
+- **Plain language first.** Open each chapter and each `##` section with what it is for, in one or two sentences, before any symbol names. Explain a project term the first time it appears. Short paragraphs (≤ 5 sentences); use a numbered list for a sequence and a table for a lookup.
+- **Self-contained sections.** `wiki_locate` returns one `##` section at a time, so each section must make sense alone: name the package and the exact symbols it talks about instead of "it" / "this module" / "see above".
+- **Precise citations.** Cite the specific function, method or type you describe, as `[Symbol · file.ts:L10-L45](path/to/file.ts#L10-L45)`, using the repo-relative path. Keep ranges under ~200 lines — cite `AgentSession.prompt`, not the whole 4,000-line class. Citations are re-anchored to their symbol when code moves, so prefer ranges that cover a declaration.
+- **No numbers that go stale.** Do not write line counts, file counts or version numbers in prose ("4,579 lines", "269 files", "version 3"); the reader shows live counts, and a cited line shows the current value. Describe size in words ("the largest package").
+- **Say what you could not confirm.** If a step or behaviour is not visible in the code you read, write "(not confirmed in code)" rather than guessing.
+- **Titles are plain names**: use the `title` from `wiki_plan` as the H1 (`# 项目概览`, `# pi-schema`). No repo-name prefix, numbers, file paths or adjectives ("零开销", "新一代", "全景") in titles.
+- **Diagrams**: one small Mermaid diagram where it helps; quote labels with parentheses (`A["pi-tui (UI)"]`).
+- Match the user's language (Simplified Chinese when the user writes Chinese), including headings and diagram labels.
+
+### Overview chapter (`README.md`)
+Sections, in order:
+1. **What this repository is** — the problem it solves and who uses it, in 3–4 sentences.
+2. **Mental model** — the layers, bottom to top, one line each.
+3. **Module map** — a table: module · one-line purpose · link to its chapter (`[pi-ai](02-modules/01-ai.md)`).
+4. **Where to change what** — a table of 5–10 common tasks ("add an LLM provider", "add a CLI command") → the chapter and the entry file to open, with a citation.
+5. **Glossary** — 5–12 project terms a newcomer will meet, one line each.
+6. **Reading route** — what to read first for "run it", "understand the core", "change it".
+
+### Module chapter (`02-modules/`)
+A module chapter teaches a newcomer the module well enough to change it. Use these six `##` sections, in this order (headings in the user's language):
+1. **What it does** — 2–3 plain sentences: the problem it solves and what would break without it.
+2. **Where it sits** — who calls it and what it depends on (from the evidence pack's upstream/downstream lists), with one small `flowchart`.
+3. **Core concepts** — the 3–5 types/classes/functions a reader must know. For each: what it represents, how it is used, one citation.
+4. **One call, step by step** — follow one real, typical call through the module (entry → internal steps → result) as a numbered list. **Every step names the function that runs and cites it.**
+5. **How to change it** — recipes for the 2–4 most likely changes (which files, in which order), the invariants that must hold, and the tests that cover it (cite the test file).
+6. **Key files** — a table: file · one-line responsibility · main symbols.
+Aim for roughly 80–160 lines.
+
+### Before you save a chapter, check
+- [ ] Each `##` section opens with a plain sentence and makes sense on its own.
+- [ ] Every walkthrough step and every core concept has a citation; no citation spans a whole large class or file.
+- [ ] No line counts, file counts or version numbers in prose.
+- [ ] Module chapters have the six sections; the overview links every module chapter.
+
+### Step 2b — One-Line File & Module Descriptions (no extra tool)
+The graph view shows a one-sentence description next to each file and module. After writing the chapters, use your normal file-write tool to create `.repowiki/descriptions.json`:
+```json
+{ "modules": { "packages/schema": "用普通对象描述 JSON Schema,并推导出 TypeScript 类型" },
+ "files": { "packages/schema/src/builders.ts": "导出 str/num 等构建函数,返回带静态类型的普通 JSON Schema" } }
+```
+Keys are repo-relative paths; module keys are the graph groups (`packages/`, `apps/`, top-level folder). One plain sentence each, in the user's language, saying what the file is for — no adjectives. Cover every module and the files you cited; skip files you have not read. The reader hot-reloads this file.
+
+### Step 3 — Compile and Open the Reader (`wiki_serve`)
+Call `wiki_serve` (`repo_path`). It builds `.repowiki/index.html`, hides `.repowiki/` from `git status` via `.git/info/exclude`, installs a post-commit hook that re-syncs line numbers after every commit (0 tokens), and starts the reader at `http://127.0.0.1:`. Pass `build_only: true` to build without starting a server.
+
+### Step 4 — Keeping the Wiki Current
+Line numbers follow the code automatically (post-commit hook, or `wiki_plan` with `sync: true`). Prose does not, so when `wiki_plan` reports chapters whose cited code changed:
+1. `wiki_plan` with `sync: true`, so every line number is current.
+2. For each changed citation it lists, `wiki_locate` with `file` + `symbol` to read the code as it is now, and compare it with the paragraph that cites it.
+3. Edit only what is now wrong (a renamed function, a new step, a removed option, a deleted file); keep every other sentence as it was. Save the whole chapter with `wiki_write_page`.
+4. If a flagged chapter is still correct, call `wiki_plan` with `mark_reviewed: [""]` instead of rewriting it.
+5. Tell the user which chapters you changed and what changed in each.
diff --git a/plugins/Jialei-03/mcode-repowiki/test/describe.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/describe.test.mjs
new file mode 100644
index 00000000..8d642911
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/describe.test.mjs
@@ -0,0 +1,84 @@
+import assert from 'node:assert/strict';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import { buildDescriptions, clampSentence, extractLeadingComment } from '../server/describe.mjs';
+
+function makeRepo(files) {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'repowiki-describe-'));
+ for (const [rel, body] of Object.entries(files)) {
+ mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
+ writeFileSync(path.join(root, rel), body);
+ }
+ return root;
+}
+
+test('leading doc comments become a one-sentence description; licenses and code do not', () => {
+ const root = makeRepo({
+ 'a.ts': '/**\n * Parses session files. Second sentence is dropped.\n * @param x\n */\nexport const a = 1;\n',
+ 'b.ts': '// Copyright 2024 Someone\n// SPDX-License-Identifier: MIT\n\nexport const b = 1;\n',
+ 'c.ts': '// Copyright 2024 Someone\n\n/** Renders the status banner */\nexport const c = 1;\n',
+ 'd.py': '#!/usr/bin/env python\n"""Command line entry for the indexer."""\nimport os\n',
+ 'e.ts': 'export const noComment = 1;\n',
+ 'f.c': '#include \nint main() {}\n',
+ });
+ try {
+ assert.equal(extractLeadingComment(path.join(root, 'a.ts')), 'Parses session files');
+ assert.equal(extractLeadingComment(path.join(root, 'b.ts')), '');
+ assert.equal(extractLeadingComment(path.join(root, 'c.ts')), 'Renders the status banner');
+ assert.equal(extractLeadingComment(path.join(root, 'd.py')), 'Command line entry for the indexer');
+ assert.equal(extractLeadingComment(path.join(root, 'e.ts')), '');
+ assert.equal(extractLeadingComment(path.join(root, 'f.c')), '');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('descriptions.json overrides beat comments, chapter subtitles beat package.json', () => {
+ const root = makeRepo({
+ 'packages/core/package.json': JSON.stringify({ name: 'core', description: 'Core package.' }),
+ 'packages/core/src/a.ts': '/** From the comment */\nexport const a = 1;\n',
+ 'packages/core/src/b.ts': 'export const b = 1;\n',
+ 'packages/ui/package.json': JSON.stringify({ name: 'ui', description: 'UI widgets for the app.' }),
+ 'packages/ui/src/c.ts': 'export const c = 1;\n',
+ '.repowiki/descriptions.json': JSON.stringify({ files: { 'packages/core/src/b.ts': '手写的描述' } }),
+ });
+ try {
+ const pages = [
+ { title: 'core — 核心运行时(3 个文件)', referencedFiles: ['packages/core/src/a.ts', 'packages/core/src/b.ts'] },
+ // an overview page citing several modules must not claim any of them
+ { title: 'repo — 全景导览', referencedFiles: ['packages/core/src/a.ts', 'packages/ui/src/c.ts'] },
+ ];
+ const d = buildDescriptions(
+ root,
+ path.join(root, '.repowiki'),
+ ['packages/core/src/a.ts', 'packages/core/src/b.ts', 'packages/ui/src/c.ts'],
+ pages,
+ );
+ assert.equal(d.files['packages/core/src/a.ts'], 'From the comment');
+ assert.equal(d.files['packages/core/src/b.ts'], '手写的描述');
+ assert.equal(d.files['packages/ui/src/c.ts'], undefined);
+ assert.equal(d.modules['packages/core'], '核心运行时');
+ assert.equal(d.modules['packages/ui'], 'UI widgets for the app');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('a broken descriptions.json is ignored instead of failing the build', () => {
+ const root = makeRepo({ 'a.ts': '/** Hello world */\n', '.repowiki/descriptions.json': '{ not json' });
+ try {
+ const d = buildDescriptions(root, path.join(root, '.repowiki'), ['a.ts']);
+ assert.equal(d.files['a.ts'], 'Hello world');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('clampSentence caps long text by visual width', () => {
+ assert.ok(clampSentence('很'.repeat(100)).endsWith('…'));
+ assert.ok(clampSentence('很'.repeat(100)).length <= 56);
+ assert.equal(clampSentence('ab'), '');
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/entry.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/entry.test.mjs
new file mode 100644
index 00000000..55174097
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/entry.test.mjs
@@ -0,0 +1,34 @@
+// The MCP server must start no matter where the plugin is installed: a Windows drive path
+// or a folder with spaces used to fail the "am I the entry script" check, so it exited silently.
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { cpSync, mkdtempSync, rmSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+const pluginRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+test('MCP server starts from a folder whose path contains spaces', async () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'repowiki entry '));
+ try {
+ const copy = path.join(dir, 'my plugins', 'mcode-repowiki');
+ cpSync(path.join(pluginRoot, 'server'), path.join(copy, 'server'), { recursive: true });
+ cpSync(path.join(pluginRoot, 'package.json'), path.join(copy, 'package.json'));
+ const child = spawn(process.execPath, [path.join(copy, 'server', 'main.mjs')], { stdio: ['pipe', 'pipe', 'inherit'] });
+ const reply = await new Promise((resolve, reject) => {
+ let out = '';
+ child.stdout.on('data', (d) => {
+ out += d;
+ if (out.includes('\n')) resolve(out.split('\n')[0]);
+ });
+ child.on('exit', (code) => reject(new Error(`server exited with code ${code} before answering`)));
+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } })}\n`);
+ });
+ child.kill();
+ assert.equal(JSON.parse(reply).result.serverInfo.name, 'mcode-repowiki');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/freshness.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/freshness.test.mjs
new file mode 100644
index 00000000..dfacb321
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/freshness.test.mjs
@@ -0,0 +1,168 @@
+// Citation anchors: line numbers follow moved code, and a chapter is flagged (citation by
+// citation) only when the code it cites actually changed.
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import { lintWikiPage } from '../server/lint.mjs';
+import { executeTool } from '../server/main.mjs';
+
+const git = (cwd, ...args) => execFileSync('git', ['-C', cwd, ...args], { stdio: 'pipe' }).toString();
+
+const SRC = [
+ 'export function parseInput(raw: string): string[] {',
+ ' return raw.split(",");',
+ '}',
+ '',
+ 'export function renderOutput(items: string[]): string {',
+ ' return items.join("\\n");',
+ '}',
+ '',
+].join('\n');
+
+test('citations follow moved code; changed and deleted code is reported per citation', async () => {
+ const repo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-fresh-'));
+ try {
+ mkdirSync(path.join(repo, 'src'));
+ writeFileSync(path.join(repo, 'src', 'io.ts'), SRC);
+ writeFileSync(path.join(repo, 'src', 'main.ts'), 'import { parseInput } from "./io.js";\nexport const run = () => parseInput("a,b");\n');
+ git(repo, 'init', '-q');
+ git(repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qam', 'init', '--allow-empty');
+ git(repo, 'add', '-A');
+ git(repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'code');
+
+ // Labels deliberately do not name the symbols: the anchor recorded at write time must do it.
+ const page = [
+ '# io',
+ '',
+ '## 读取',
+ '',
+ '输入先被切开:[第一步](src/io.ts#L1-L3)。',
+ '',
+ '## 输出',
+ '',
+ '然后拼回去:[第二步](src/io.ts#L5-L7)。',
+ ].join('\n');
+ await executeTool('wiki_write_page', { repo_path: repo, page_path: '02-modules/io.md', content: page });
+ const manifest = JSON.parse(readFileSync(path.join(repo, '.repowiki', 'manifest.json'), 'utf8'));
+ assert.deepEqual(
+ manifest.pages['02-modules/io.md'].anchors.map((a) => a.symbol),
+ ['parseInput', 'renderOutput'],
+ );
+
+ // 1. Move: four new lines on top. Sync must re-anchor both citations; nothing is stale.
+ writeFileSync(path.join(repo, 'src', 'io.ts'), `// a\n// b\n// c\n// d\n${SRC}`);
+ const synced = await executeTool('wiki_plan', { repo_path: repo, sync: true });
+ assert.match(synced, /Citations moved to their code's new lines\*\*: 2/u);
+ assert.match(synced, /1\/1 chapters match the code they cite/u);
+ const md1 = readFileSync(path.join(repo, '.repowiki', '02-modules', 'io.md'), 'utf8');
+ assert.match(md1, /\(src\/io\.ts#L5-L7\)/u);
+ assert.match(md1, /\(src\/io\.ts#L9-L11\)/u);
+
+ // 2. Change the body of renderOutput only: exactly that citation is reported.
+ writeFileSync(
+ path.join(repo, 'src', 'io.ts'),
+ `// a\n// b\n// c\n// d\n${SRC.replace('items.join("\\n")', 'items.join(", ")')}`,
+ );
+ const status = await executeTool('wiki_plan', { repo_path: repo });
+ assert.match(status, /1 chapter\(s\) cite code that has changed/u);
+ assert.match(status, /changed: `renderOutput` `src\/io\.ts:L9-L11`/u);
+ assert.doesNotMatch(status, /changed: `parseInput`/u);
+ assert.match(status, /mark_reviewed/u);
+
+ // 3. A person confirms the prose still holds: the flag clears without rewriting the page.
+ const reviewed = await executeTool('wiki_plan', { repo_path: repo, mark_reviewed: ['02-modules/io.md'] });
+ assert.match(reviewed, /Marked 1 chapter/u);
+ assert.match(reviewed, /1\/1 chapters match the code they cite/u);
+
+ // 4. Delete the file: every citation into it is reported as gone.
+ rmSync(path.join(repo, 'src', 'io.ts'));
+ const gone = await executeTool('wiki_plan', { repo_path: repo });
+ assert.match(gone, /file gone: `src\/io\.ts:L5-L7`/u);
+ assert.match(gone, /file gone: `src\/io\.ts:L9-L11`/u);
+ } finally {
+ rmSync(repo, { recursive: true, force: true });
+ }
+});
+
+test('a chapter rewritten without wiki_write_page gets anchors for the citations it has now', async () => {
+ const repo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-plainwrite-'));
+ try {
+ mkdirSync(path.join(repo, 'src'));
+ writeFileSync(path.join(repo, 'src', 'io.ts'), SRC);
+ git(repo, 'init', '-q');
+ git(repo, 'add', '-A');
+ git(repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'code');
+ const page = '02-modules/io.md';
+ await executeTool('wiki_write_page', { repo_path: repo, page_path: page, content: '# io\n\n## a\n\n[parseInput](src/io.ts#L1-L3)\n' });
+
+ // The agent (or a person) overwrites the chapter with a plain file write: the old
+ // citation is gone, a new one appears.
+ writeFileSync(path.join(repo, '.repowiki', page), '# io\n\n## b\n\n[renderOutput](src/io.ts#L5-L7)\n');
+ const status = await executeTool('wiki_plan', { repo_path: repo });
+ assert.match(status, /1\/1 chapters match the code they cite/u);
+
+ await executeTool('wiki_serve', { repo_path: repo, build_only: true });
+ const manifest = JSON.parse(readFileSync(path.join(repo, '.repowiki', 'manifest.json'), 'utf8'));
+ assert.deepEqual(manifest.pages[page].anchors.map((a) => a.symbol), ['renderOutput']);
+
+ // Changing the code the chapter cites now is reported; the removed citation is not.
+ writeFileSync(path.join(repo, 'src', 'io.ts'), SRC.replace('items.join("\\n")', 'items.join(", ")').replace('raw.split(",")', 'raw.split(";")'));
+ const after = await executeTool('wiki_plan', { repo_path: repo });
+ assert.match(after, /changed: `renderOutput`/u);
+ assert.doesNotMatch(after, /parseInput/u);
+ } finally {
+ rmSync(repo, { recursive: true, force: true });
+ }
+});
+
+test('writing checks flag the problems seen in generated chapters', () => {
+ const md = [
+ '# pi-x',
+ '## 它做什么',
+ '它有 269 个文件、81,556 行。',
+ '## 它处在哪',
+ 'x',
+ '## 核心概念',
+ '[AgentSession · a.ts:L1-L4000](src/a.ts#L1-L4000)',
+ '## 一次调用,逐步来',
+ '1. **输入进入。** 交给 `AgentSession`。',
+ '2. **发请求。** [run · a.ts:L5-L9](src/a.ts#L5-L9)',
+ '## 怎么改它',
+ 'x',
+ '## 关键文件',
+ 'x',
+ ].join('\n');
+ const w = lintWikiPage('02-modules/x.md', md, [{ file: 'src/a.ts', start: 1, end: 4000, symbol: 'AgentSession' }]);
+ assert.ok(w.some((x) => /1 of 2 steps .* cite no code/u.test(x)));
+ assert.ok(w.some((x) => /span more than 200 lines/u.test(x)));
+ assert.ok(w.some((x) => /269 个文件/u.test(x)));
+
+ const ok = lintWikiPage('README.md', '# 项目概览\n\n## 模块\n\n见 [pi-ai](02-modules/01-ai.md),入口 [main · cli.ts:L1-L9](src/cli.ts#L1-L9)。\n');
+ assert.deepEqual(ok, []);
+});
+
+test('post-commit hook still syncs when the Node that installed it is gone', async () => {
+ const { installPostCommitHook } = await import('../server/sync.mjs');
+ const repo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-hook-'));
+ try {
+ mkdirSync(path.join(repo, 'src'));
+ writeFileSync(path.join(repo, 'src', 'io.ts'), SRC);
+ git(repo, 'init', '-q');
+ git(repo, 'add', '-A');
+ git(repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'code');
+ await executeTool('wiki_write_page', { repo_path: repo, page_path: 'README.md', content: '# x\n\n## a\n\n[parseInput · io.ts:L1-L3](src/io.ts#L1-L3)\n' });
+ const { hookFile } = installPostCommitHook(repo);
+ // Simulate a MiniMax Code upgrade removing its bundled Node.
+ writeFileSync(hookFile, readFileSync(hookFile, 'utf8').replace(/^REPOWIKI_NODE=".*"$/mu, 'REPOWIKI_NODE="/no/such/node"'));
+ writeFileSync(path.join(repo, 'src', 'io.ts'), `// moved\n${SRC}`);
+ git(repo, 'add', '-A');
+ git(repo, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-qm', 'move');
+ assert.match(readFileSync(path.join(repo, '.repowiki', 'README.md'), 'utf8'), /\(src\/io\.ts#L2-L4\)/u);
+ } finally {
+ rmSync(repo, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/importers.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/importers.test.mjs
new file mode 100644
index 00000000..d0802950
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/importers.test.mjs
@@ -0,0 +1,70 @@
+// wiki_locate lists who really imports a symbol: through package entries and re-exports, with the
+// import line, and without the files that merely contain the same word.
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import { executeTool } from '../server/main.mjs';
+
+function write(root, rel, text) {
+ mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
+ writeFileSync(path.join(root, rel), text);
+}
+
+test('importers are resolved through package entries and re-exports; same-named words are left out', async () => {
+ const repo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-importers-'));
+ try {
+ write(repo, 'package.json', JSON.stringify({ name: 'mono', private: true, workspaces: ['packages/*'] }));
+ write(repo, 'packages/schema/package.json', JSON.stringify({
+ name: '@acme/schema',
+ exports: { '.': { types: './dist/index.d.ts', import: './dist/index.js' } },
+ scripts: { test: 'vitest --run' },
+ }));
+ write(repo, 'packages/schema/src/builders.ts', 'export type Schema = { type: string };\nexport function str(): Schema {\n return { type: "string" };\n}\n');
+ write(repo, 'packages/schema/src/index.ts', 'export {\n str,\n type Schema,\n} from "./builders.ts";\n');
+ write(repo, 'packages/schema/test/builders.test.ts', 'import { str } from "../src/index.ts";\nstr();\n');
+ // Another package uses it through the package name, and re-exports it under its own entry.
+ write(repo, 'packages/chord/package.json', JSON.stringify({ name: '@acme/chord', main: './src/index.ts' }));
+ write(repo, 'packages/chord/src/contracts.ts', 'import type { Schema } from "@acme/schema";\nexport type { Schema } from "@acme/schema";\nexport const c = (s: Schema) => s;\n');
+ write(repo, 'packages/chord/src/index.ts', 'export * from "./contracts.ts";\n');
+ write(repo, 'packages/chord/src/store.ts', 'import { type Schema } from "./index.ts";\nexport const keep: Schema[] = [];\n');
+ write(repo, 'apps/web/main.ts', 'import type { Schema } from "@acme/chord";\nexport const s: Schema = { type: "x" };\n');
+ // Same word, unrelated: a local type and a string.
+ write(repo, 'packages/telemetry/src/metrics.ts', 'type MetricsOf = Schema;\nexport const note = "JSON Schema";\n');
+ execFileSync('git', ['-C', repo, 'init', '-q']);
+ execFileSync('git', ['-C', repo, 'add', '-A']);
+
+ const out = await executeTool('wiki_locate', { repo_path: repo, file: 'packages/schema/src/builders.ts', symbol: 'Schema' });
+ assert.match(out, /Who imports `Schema`: 5 files/u);
+ assert.match(out, /`packages\/schema\/src\/index\.ts:L3` \[re-export\]/u);
+ assert.match(out, /Re-exported by .*`packages\/schema\/src\/index\.ts:L3` \(= `@acme\/schema`\)/u);
+ assert.match(out, /`packages\/chord\/src\/contracts\.ts:L1` \[re-export\] ← `@acme\/schema`/u);
+ assert.match(out, /`apps\/web\/main\.ts:L1` through `packages\/chord` ← `@acme\/chord`/u);
+ assert.match(out, /`packages\/chord\/src\/store\.ts:L1`/u);
+ assert.doesNotMatch(out, /- `packages\/telemetry/u);
+ assert.match(out, /Not listed: 1 other files contain the word `Schema`/u);
+ assert.match(out, /\*\*Package\*\*: `@acme\/schema` \(`packages\/schema\/`\).*`test`: `vitest --run`/u);
+
+ // The test file imports `str` through the package entry by a relative path.
+ const strOut = await executeTool('wiki_locate', { repo_path: repo, file: 'packages/schema/src/builders.ts', symbol: 'str' });
+ assert.match(strOut, /`packages\/schema\/test\/builders\.test\.ts:L1` \[test\] ← `\.\.\/src\/index\.ts`: str/u);
+
+ // Without a symbol: everything importing anything the file exports.
+ const fileOut = await executeTool('wiki_locate', { repo_path: repo, file: 'packages/schema/src/builders.ts' });
+ assert.match(fileOut, /Who imports this file: 6 files in 3 packages/u);
+
+ // A folder plus a symbol: the declaring file is found first (not the barrel that lists it).
+ const folderSym = await executeTool('wiki_locate', { repo_path: repo, file: 'packages/schema', symbol: 'Schema' });
+ assert.match(folderSym, /Symbol Body: `Schema` \(`packages\/schema\/src\/builders\.ts:L1-L1`\)/u);
+
+ // A folder: package, entry and files with their symbols.
+ const dirOut = await executeTool('wiki_locate', { repo_path: repo, file: 'packages/schema' });
+ assert.match(dirOut, /\*\*Entry\*\*: `@acme\/schema` → `packages\/schema\/src\/index\.ts`/u);
+ assert.match(dirOut, /`packages\/schema\/src\/builders\.ts`: Schema, str/u);
+ } finally {
+ rmSync(repo, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/live-realtime.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/live-realtime.test.mjs
new file mode 100644
index 00000000..3a4f661a
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/live-realtime.test.mjs
@@ -0,0 +1,146 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+import { startLiveWikiServer } from '../server/live-server.mjs';
+import { executeTool } from '../server/main.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_PATH = path.resolve(__dirname, '..', 'server', 'cli.mjs');
+
+function collectNextSseEvent(url, expectedEvent, onConnected, timeoutMs = 4500) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ req.destroy();
+ reject(new Error(`Timed out waiting for SSE event "${expectedEvent}"`));
+ }, timeoutMs);
+
+ const req = http.get(`${url}/api/events`, (res) => {
+ let buf = '';
+ res.setEncoding('utf8');
+ res.on('data', (chunk) => {
+ buf += chunk;
+ const frames = buf.split('\n\n');
+ buf = frames.pop() || '';
+ for (const frame of frames) {
+ const evLine = frame.split('\n').find((l) => l.startsWith('event: '));
+ const dataLine = frame.split('\n').find((l) => l.startsWith('data: '));
+ if (!evLine || !dataLine) continue;
+ const evName = evLine.slice(7).trim();
+ const payload = JSON.parse(dataLine.slice(6));
+ if (evName === 'connected' && onConnected) {
+ onConnected(payload);
+ }
+ if (evName === expectedEvent) {
+ clearTimeout(timer);
+ req.destroy();
+ resolve(payload);
+ return;
+ }
+ }
+ });
+ });
+ req.on('error', (err) => {
+ if (err.code !== 'ECONNRESET') {
+ clearTimeout(timer);
+ reject(err);
+ }
+ });
+ });
+}
+
+test('Universal CLI (repowiki init & status --json) + Real-Time SSE Live Server end-to-end', async () => {
+ const tmpRepo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-live-test-'));
+ try {
+ mkdirSync(path.join(tmpRepo, 'src'), { recursive: true });
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'core.ts'),
+ 'export interface TurnContext {\n id: string;\n}\nexport function runTurn(ctx: TurnContext): string {\n return ctx.id;\n}\n',
+ 'utf8',
+ );
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'cli.ts'),
+ "import { runTurn } from './core.js';\nexport function boot() {\n return runTurn({ id: 'live' });\n}\n",
+ 'utf8',
+ );
+
+ // 1. Test standalone CLI `repowiki init` (zero LLM required)
+ const initOut = execFileSync(process.execPath, [CLI_PATH, 'init', tmpRepo], { encoding: 'utf8' });
+ assert.match(initOut, /Initialized RepoWiki/u);
+
+ const statusJson = JSON.parse(
+ execFileSync(process.execPath, [CLI_PATH, 'status', tmpRepo, '--json'], { encoding: 'utf8' }),
+ );
+ assert.equal(statusJson.exists, true);
+ assert.equal(statusJson.stalePages.length, 0);
+
+ // 2. Start Real-Time SSE Server on OS-assigned port
+ const srv = await startLiveWikiServer({ repoRoot: tmpRepo, port: 0 });
+ try {
+ // Verify HTML portal design constraints: zero gradients, zero emoji chrome
+ const htmlRes = await fetch(`${srv.url}/index.html`);
+ assert.equal(htmlRes.status, 200);
+ const htmlText = await htmlRes.text();
+ assert.equal(htmlText.includes('linear-gradient'), false, 'Portal CSS must contain zero gradients');
+ assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(htmlText), false, 'Portal chrome must contain zero emojis');
+
+ // Verify live disk `/api/file` endpoint & path traversal guard
+ const fileRes = await fetch(`${srv.url}/api/file?path=src/core.ts&start=1&end=6`);
+ assert.equal(fileRes.status, 200);
+ const fileJson = await fileRes.json();
+ assert.equal(fileJson.totalLines, 7);
+
+ const travRes = await fetch(`${srv.url}/api/file?path=../../etc/passwd`);
+ assert.equal(travRes.status, 403);
+
+ // 3. Verify Real-Time `repo_changed` SSE push when a source file is edited on disk
+ const repoChangedPromise = collectNextSseEvent(srv.url, 'repo_changed', () => {
+ setTimeout(() => {
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'core.ts'),
+ 'export interface TurnContext {\n id: string;\n streaming: boolean;\n}\nexport function runTurn(ctx: TurnContext): string {\n return ctx.id;\n}\n',
+ 'utf8',
+ );
+ }, 60);
+ });
+
+ const changedEvent = await repoChangedPromise;
+ assert.ok(changedEvent.sync.stalePages.length >= 1, 'Modifying cited source file must flag stale chapters in real time');
+ assert.ok(changedEvent.sync.changedSourceFiles.includes('src/core.ts'));
+
+ // 4. Verify `POST /api/ack-sync` clears staleness & broadcasts `wiki_updated` over SSE
+ const wikiUpdatedPromise = collectNextSseEvent(srv.url, 'wiki_updated', () => {
+ setTimeout(() => {
+ fetch(`${srv.url}/api/ack-sync`, { method: 'POST' }).catch(() => {});
+ }, 50);
+ });
+
+ const ackEvent = await wikiUpdatedPromise;
+ assert.equal(ackEvent.sync.stalePages.length, 0, 'Acknowledging sync must reset stalePages to 0');
+
+ // 5. Verify MCP `wiki_write_page` triggers live `wiki_updated` hot-reload over SSE
+ const hotReloadPromise = collectNextSseEvent(srv.url, 'wiki_updated', () => {
+ setTimeout(() => {
+ executeTool('wiki_write_page', {
+ repo_path: tmpRepo,
+ page_path: 'README.md',
+ title: 'Live Hot Reloaded Overview',
+ content: '# Live Hot Reloaded Overview\n\nVerified live cite [core.ts:L1-L6](src/core.ts#L1-L6).\n',
+ }).catch(() => {});
+ }, 50);
+ });
+
+ const hotReloadEvent = await hotReloadPromise;
+ assert.ok(hotReloadEvent.pages.some((p) => p.title === 'Live Hot Reloaded Overview'));
+ } finally {
+ await srv.close();
+ }
+ } finally {
+ rmSync(tmpRepo, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/long-horizon-drift.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/long-horizon-drift.test.mjs
new file mode 100644
index 00000000..450e4007
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/long-horizon-drift.test.mjs
@@ -0,0 +1,237 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import { executeTool, getAdvertisedTools } from '../server/main.mjs';
+
+test('Long-horizon LSM overlay: wiki_locate dynamically heals +60 line shifts and discovers unindexed new git files', async () => {
+ const tmpRepo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-longhorizon-'));
+ try {
+ mkdirSync(path.join(tmpRepo, 'src'), { recursive: true });
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'loop.ts'),
+ [
+ 'export interface LoopOptions {',
+ ' maxTurns: number;',
+ '}',
+ 'export function runAgentLoop(opts: LoopOptions): number {',
+ ' let step = 0;',
+ ' while (step < opts.maxTurns) step += 1;',
+ ' return step;',
+ '}',
+ '',
+ ].join('\n'),
+ 'utf8',
+ );
+
+ execFileSync('git', ['init'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['add', '-A'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-m', 'init'], { cwd: tmpRepo, stdio: 'ignore' });
+
+ await executeTool('wiki_write_page', {
+ repo_path: tmpRepo,
+ page_path: 'README.md',
+ title: 'Agent Loop Overview',
+ content:
+ '# Agent Loop Overview\n\n## Core Execution\nThe primary turn loop is implemented in `runAgentLoop` ([loop.ts:L4-L8](src/loop.ts#L4-L8)).\n',
+ });
+
+ // Fresh state check
+ const freshOut = await executeTool('wiki_locate', {
+ repo_path: tmpRepo,
+ query: 'runAgentLoop',
+ });
+ assert.match(freshOut, /L4-L8.*\[SHA1-FRESH\]/u);
+
+ // Simulate long-horizon coding WITHOUT updating .repowiki:
+ // 1. Insert 60 lines at top of src/loop.ts -> shifts runAgentLoop from L4-L8 down to L64-L68!
+ const sixtyHeaderLines = Array.from({ length: 60 }, (_, idx) => `// Header instrumentation line ${idx + 1}`).join('\n');
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'loop.ts'),
+ `${sixtyHeaderLines}\n` +
+ [
+ 'export interface LoopOptions {',
+ ' maxTurns: number;',
+ '}',
+ 'export function runAgentLoop(opts: LoopOptions): number {',
+ ' let step = 0;',
+ ' while (step < opts.maxTurns) step += 1;',
+ ' return step;',
+ '}',
+ '',
+ ].join('\n'),
+ 'utf8',
+ );
+
+ // 2. Create a brand-new file src/turn-budget.ts not mentioned anywhere in .repowiki!
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'turn-budget.ts'),
+ [
+ 'export class TurnBudgetGuard {',
+ ' constructor(public readonly maxToolCalls: number) {}',
+ ' canProceed(used: number): boolean {',
+ ' return used < this.maxToolCalls;',
+ ' }',
+ '}',
+ '',
+ ].join('\n'),
+ 'utf8',
+ );
+
+ const driftedOut = await executeTool('wiki_locate', {
+ repo_path: tmpRepo,
+ query: 'runAgentLoop TurnBudgetGuard',
+ });
+
+ // Verify self-healing AST line relocation, unindexed git-delta file discovery, AND inline live disk code slices!
+ assert.match(driftedOut, /src\/loop\.ts.*L64-L68.*\[AST-REANCHORED from L4-L8\]/u);
+ assert.match(driftedOut, /src\/turn-budget\.ts.*\[LIVE-NEW-FILE\].*TurnBudgetGuard/u);
+ assert.match(driftedOut, /Live Disk Slice: `src\/turn-budget\.ts`/u);
+
+ // Verify 0-token deterministic AST sync (`wiki_plan` with `sync: true`) rewrites shifted markdown citations!
+ const syncOut = await executeTool('wiki_plan', {
+ repo_path: tmpRepo,
+ sync: true,
+ });
+ assert.match(syncOut, /Citations moved to their code's new lines\*\*: 1/u);
+
+ // Verify clean separation: hidden machine `.repowiki/delta-index.json` exists AND human `03-guides/00-live-delta.md` does NOT exist
+ const deltaIndexPath = path.join(tmpRepo, '.repowiki', 'delta-index.json');
+ const legacyDeltaPath = path.join(tmpRepo, '.repowiki', '03-guides', '00-live-delta.md');
+ assert.equal(existsSync(deltaIndexPath), true, '.repowiki/delta-index.json should exist after sync');
+ assert.equal(existsSync(legacyDeltaPath), false, '.repowiki/03-guides/00-live-delta.md should not exist after sync');
+ const deltaIndex = JSON.parse(readFileSync(deltaIndexPath, 'utf8'));
+ assert.ok(
+ Array.isArray(deltaIndex.files) &&
+ deltaIndex.files.some(
+ (f) => f.relPath === 'src/turn-budget.ts' && f.symbols.some((s) => s.name === 'TurnBudgetGuard'),
+ ),
+ 'delta-index.json should index TurnBudgetGuard in src/turn-budget.ts',
+ );
+
+ // Verify git mv (file rename) is also automatically followed and rewritten in Wiki chapters with 0 LLM tokens!
+ execFileSync('git', ['add', '-A'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-m', 'shift loop'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['mv', 'src/loop.ts', 'src/agent-runner.ts'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-m', 'rename loop.ts to agent-runner.ts'], { cwd: tmpRepo, stdio: 'ignore' });
+
+ // Seed a legacy 03-guides/00-live-delta.md file & manifest entry to verify sync auto-cleans it
+ mkdirSync(path.dirname(legacyDeltaPath), { recursive: true });
+ writeFileSync(legacyDeltaPath, '# Legacy Live Delta\n', 'utf8');
+ const manifestPath = path.join(tmpRepo, '.repowiki', 'manifest.json');
+ const seededManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ seededManifest.pages['03-guides/00-live-delta.md'] = {
+ path: '03-guides/00-live-delta.md',
+ title: 'Legacy Live Delta',
+ };
+ writeFileSync(manifestPath, `${JSON.stringify(seededManifest, null, 2)}\n`, 'utf8');
+
+ await executeTool('wiki_plan', { repo_path: tmpRepo, sync: true });
+ assert.equal(existsSync(deltaIndexPath), true, '.repowiki/delta-index.json should exist after rename sync');
+ assert.equal(existsSync(legacyDeltaPath), false, 'legacy 03-guides/00-live-delta.md should be removed on sync');
+ const cleanedManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ assert.equal(
+ Object.prototype.hasOwnProperty.call(cleanedManifest.pages || {}, '03-guides/00-live-delta.md'),
+ false,
+ 'manifest.pages should not retain 03-guides/00-live-delta.md after sync',
+ );
+ const updatedReadme = readFileSync(path.join(tmpRepo, '.repowiki', 'README.md'), 'utf8');
+ assert.match(updatedReadme, /\[agent-runner\.ts:L64-L68\]\(src\/agent-runner\.ts#L64-L68\)/u);
+
+ // After git commit + sync (clean working tree), wiki_locate still finds TurnBudgetGuard from delta-index.json!
+ const syncedLocateOut = await executeTool('wiki_locate', {
+ repo_path: tmpRepo,
+ query: 'TurnBudgetGuard',
+ });
+ assert.match(syncedLocateOut, /src\/turn-budget\.ts.*\[SYNCED-DELTA\].*TurnBudgetGuard/u);
+ assert.match(syncedLocateOut, /Live Disk Slice: `src\/turn-budget\.ts`/u);
+ } finally {
+ rmSync(tmpRepo, { recursive: true, force: true });
+ }
+});
+
+test('Developer essentials: wiki_locate surfaces blast-radius importers, .repowiki stays out of git status, and router MCP mode is lean', async () => {
+ const tmpRepo = mkdtempSync(path.join(os.tmpdir(), 'repowiki-essentials-'));
+ try {
+ mkdirSync(path.join(tmpRepo, 'src'), { recursive: true });
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'types.ts'),
+ 'export interface SessionEntry {\n type: string;\n id: string;\n}\n',
+ 'utf8',
+ );
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'consumer-a.ts'),
+ 'import type { SessionEntry } from "./types.ts";\nexport function readEntry(e: SessionEntry) { return e.id; }\n',
+ 'utf8',
+ );
+ writeFileSync(
+ path.join(tmpRepo, 'src', 'consumer-b.ts'),
+ 'import type { SessionEntry } from "./types.ts";\nexport function formatEntry(e: SessionEntry) { return e.type; }\n',
+ 'utf8',
+ );
+
+ execFileSync('git', ['init'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['add', '-A'], { cwd: tmpRepo, stdio: 'ignore' });
+ execFileSync('git', ['commit', '-m', 'init'], { cwd: tmpRepo, stdio: 'ignore' });
+
+ await executeTool('wiki_write_page', {
+ repo_path: tmpRepo,
+ page_path: 'README.md',
+ title: 'Session Types',
+ content: '# Session Types\n\n`SessionEntry` is defined in [types.ts:L1-L4](src/types.ts#L1-L4).\n',
+ });
+ await executeTool('wiki_build_site', { repo_path: tmpRepo });
+
+ // 1. Git hygiene: .repowiki/ is automatically excluded via .git/info/exclude without touching .gitignore
+ const gitStatus = execFileSync('git', ['status', '--porcelain'], { cwd: tmpRepo, encoding: 'utf8' }).trim();
+ assert.equal(gitStatus, '', 'git status should stay clean after building .repowiki');
+
+ // 2. Blast radius + Exact Downstream Symbol Reference Lines: wiki_locate surfaces direct importers AND usage lines!
+ const locOut = await executeTool('wiki_locate', { repo_path: tmpRepo, query: 'SessionEntry' });
+ assert.match(locOut, /Downstream Impact Radius/u);
+ assert.match(locOut, /src\/types\.ts.*2.*importers/u);
+ assert.match(locOut, /src\/consumer-a\.ts/u);
+ assert.match(locOut, /src\/consumer-b\.ts/u);
+ assert.match(locOut, /Exact Downstream Symbol References.*SessionEntry/u);
+ assert.match(locOut, /src\/consumer-a\.ts:L2.*readEntry\(e: SessionEntry\)/u);
+ assert.match(locOut, /src\/consumer-b\.ts:L2.*formatEntry\(e: SessionEntry\)/u);
+
+ // 2b. File Symbol Outline & Exact Full Symbol Body Inspector (zero-dep Serena-style file read!)
+ const outlineOut = await executeTool('wiki_locate', { repo_path: tmpRepo, file: 'src/types.ts' });
+ assert.match(outlineOut, /Symbol Outline/u);
+ assert.match(outlineOut, /L1-L4.*SessionEntry/u);
+ assert.match(outlineOut, /Who imports this file: 2 files/u);
+
+ const bodyOut = await executeTool('wiki_locate', {
+ repo_path: tmpRepo,
+ file: 'src/types.ts',
+ symbol: 'SessionEntry',
+ });
+ assert.match(bodyOut, /Symbol Body: `SessionEntry`/u);
+ assert.match(bodyOut, /export interface SessionEntry/u);
+ // file + symbol lists every file that imports the symbol, with the import line
+ assert.match(bodyOut, /Who imports `SessionEntry`: 2 files/u);
+ assert.match(bodyOut, /src\/consumer-a\.ts:L1/u);
+ assert.match(bodyOut, /src\/consumer-b\.ts:L1/u);
+
+ // 3. Lean MCP router profile: REPOWIKI_MCP_MODE=router exposes only 2 daily tools
+ const prevMode = process.env.REPOWIKI_MCP_MODE;
+ try {
+ process.env.REPOWIKI_MCP_MODE = 'router';
+ const leanTools = getAdvertisedTools().map((t) => t.name);
+ assert.deepEqual(leanTools, ['wiki_locate', 'wiki_plan']);
+ } finally {
+ if (prevMode === undefined) delete process.env.REPOWIKI_MCP_MODE;
+ else process.env.REPOWIKI_MCP_MODE = prevMode;
+ }
+ } finally {
+ rmSync(tmpRepo, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/parser.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/parser.test.mjs
new file mode 100644
index 00000000..5f1cd781
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/parser.test.mjs
@@ -0,0 +1,197 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { parseSourceFile, sanitizeCode } from '../server/parser.mjs';
+
+test('sanitizeCode strips comments and strings while preserving template ${expr} and exact line numbers', () => {
+ const src = [
+ '// function fakeInLineComment() {}',
+ '/* class FakeInBlockComment {',
+ ' methodFake() {}',
+ '} */',
+ 'const msg = `hello ${realCallInsideTemplate(alpha)} world`;',
+ 'export function realFunction(x: number): string {',
+ ' return "function fakeInString() {}";',
+ '}',
+ ].join('\n');
+
+ const clean = sanitizeCode(src, 'typescript');
+ assert.equal(clean.split('\n').length, src.split('\n').length);
+ assert.ok(!clean.includes('fakeInLineComment'));
+ assert.ok(!clean.includes('FakeInBlockComment'));
+ assert.ok(!clean.includes('fakeInString'));
+ assert.ok(clean.includes('realCallInsideTemplate'));
+
+ const parsed = parseSourceFile(src, 'typescript', 'src/sample.ts');
+ assert.equal(parsed.symbols.length, 1);
+ assert.equal(parsed.symbols[0].name, 'realFunction');
+ assert.equal(parsed.symbols[0].lineStart, 6);
+ assert.equal(parsed.symbols[0].lineEnd, 8);
+ assert.ok(parsed.refs.realCallInsideTemplate >= 1);
+});
+
+test('TypeScript class hierarchy, multiline methods, arrow exports, and ESM imports', () => {
+ const tsCode = `
+import { type TurnConfig, SessionStore } from './session/store.js';
+import * as metrics from '@/telemetry/metrics';
+
+export interface RunnerResult {
+ ok: boolean;
+}
+
+export class PiTurnRunner extends BaseRunner {
+ constructor(
+ private readonly store: SessionStore,
+ private readonly cfg: TurnConfig,
+ ) {
+ super();
+ }
+
+ async executeTurn(turnId: string): Promise {
+ const snap = this.store.captureSnapshot(turnId);
+ metrics.recordTurn(snap);
+ return { ok: true };
+ }
+}
+
+export const createDefaultRunner = (store: SessionStore) => {
+ return new PiTurnRunner(store, {});
+};
+`;
+
+ const parsed = parseSourceFile(tsCode, 'typescript', 'src/runner.ts');
+ const names = parsed.symbols.map((s) => (s.parent ? `${s.parent}.${s.name}` : s.name));
+ assert.deepEqual(names, [
+ 'RunnerResult',
+ 'PiTurnRunner',
+ 'PiTurnRunner.constructor',
+ 'PiTurnRunner.executeTurn',
+ 'createDefaultRunner',
+ ]);
+
+ const execMethod = parsed.symbols.find((s) => s.name === 'executeTurn');
+ assert.ok(execMethod.calls.includes('captureSnapshot'));
+ assert.ok(execMethod.calls.includes('recordTurn'));
+
+ assert.equal(parsed.imports.length, 2);
+ assert.equal(parsed.imports[0].specifier, './session/store.js');
+ assert.ok(parsed.imports[0].symbols.includes('SessionStore'));
+});
+
+test('Python indentation AST: decorators, multiline signatures, docstrings, and relative imports', () => {
+ const pyCode = `
+"""
+class FakeDocstringClass:
+ def fake_method(self): pass
+"""
+from ..core.reward import (
+ compute_advantage,
+ RewardConfig,
+)
+import torch
+
+MAX_ROLLOUT_STEPS = 512
+
+@dataclass
+class RolloutWorker(BaseWorker):
+ """Worker docstring with def ignored_fn(): pass"""
+
+ def __init__(
+ self,
+ cfg: RewardConfig,
+ device: str = "cuda",
+ ) -> None:
+ self.cfg = cfg
+
+ async def run_episode(self, prompt: str) -> float:
+ def inner_closure_ignored(x):
+ return x + 1
+ adv = compute_advantage(prompt, self.cfg)
+ return adv
+
+def build_worker(cfg: RewardConfig) -> RolloutWorker:
+ return RolloutWorker(cfg)
+`;
+
+ const parsed = parseSourceFile(pyCode, 'python', 'trainer/worker.py');
+ const qualified = parsed.symbols.map((s) => (s.parent ? `${s.parent}.${s.name}` : s.name));
+ assert.deepEqual(qualified, [
+ 'MAX_ROLLOUT_STEPS',
+ 'RolloutWorker',
+ 'RolloutWorker.__init__',
+ 'RolloutWorker.run_episode',
+ 'build_worker',
+ ]);
+ const runEp = parsed.symbols.find((s) => s.name === 'run_episode');
+ assert.ok(runEp.calls.includes('compute_advantage'));
+ assert.equal(parsed.imports[0].specifier, '..core.reward');
+ assert.deepEqual(parsed.imports[0].symbols, ['compute_advantage', 'RewardConfig']);
+});
+
+test('Go structs/receiver methods and Rust trait impls', () => {
+ const goCode = `
+package engine
+import (
+ "context"
+ "github.com/acme/proj/internal/store"
+)
+type Scheduler struct {
+ db *store.Client
+}
+func (s *Scheduler) Dispatch(ctx context.Context, jobID string) error {
+ return s.db.SaveJob(jobID)
+}
+`;
+ const goParsed = parseSourceFile(goCode, 'go', 'internal/engine/scheduler.go');
+ assert.deepEqual(
+ goParsed.symbols.map((s) => (s.parent ? `${s.parent}.${s.name}` : s.name)),
+ ['Scheduler', 'Scheduler.Dispatch'],
+ );
+
+ const rsCode = `
+use crate::graph::NodeId;
+pub mod weights;
+
+pub struct PageRanker {
+ pub alpha: f64,
+}
+
+impl PageRanker {
+ pub fn compute(&self, root: NodeId) -> Vec {
+ vec![]
+ }
+}
+`;
+ const rsParsed = parseSourceFile(rsCode, 'rust', 'src/ranker.rs');
+ assert.deepEqual(
+ rsParsed.symbols.map((s) => (s.parent ? `${s.parent}.${s.name}` : s.name)),
+ ['PageRanker', 'PageRanker.compute'],
+ );
+ assert.equal(rsParsed.imports.length, 2);
+});
+
+test('multi-line TS signature with a `= {}` default: the body, not the default, closes the symbol', () => {
+ const src = [
+ 'export function str(',
+ ' options: Annotations & { readonly pattern?: string } = {},',
+ '): Schema {',
+ ' return { type: "string", ...options };',
+ '}',
+ '',
+ 'export function noop(',
+ ' a: number,',
+ '): void {}',
+ '',
+ 'export function after() {',
+ ' return 1;',
+ '}',
+ ].join('\n');
+ const { symbols } = parseSourceFile(src, 'typescript', 'b.ts');
+ const span = (name) => {
+ const s = symbols.find((x) => x.name === name);
+ return s && [s.lineStart, s.lineEnd];
+ };
+ assert.deepEqual(span('str'), [1, 5]);
+ assert.deepEqual(span('noop'), [7, 9]);
+ assert.deepEqual(span('after'), [11, 13]);
+});
diff --git a/plugins/Jialei-03/mcode-repowiki/test/repowiki-e2e.test.mjs b/plugins/Jialei-03/mcode-repowiki/test/repowiki-e2e.test.mjs
new file mode 100644
index 00000000..16bfd81e
--- /dev/null
+++ b/plugins/Jialei-03/mcode-repowiki/test/repowiki-e2e.test.mjs
@@ -0,0 +1,196 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+import { validateRepoWikiPlugin } from '../scripts/validate-plugin.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const PLUGIN_ROOT = path.resolve(__dirname, '..');
+const SERVER_ENTRY = path.join(PLUGIN_ROOT, 'server', 'main.mjs');
+
+function createFixtureRepo() {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'repowiki-fixture-'));
+ mkdirSync(path.join(dir, 'packages', 'core', 'src'), { recursive: true });
+ mkdirSync(path.join(dir, 'packages', 'cli', 'src'), { recursive: true });
+
+ writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({ name: 'mini-agent-suite', version: '1.0.0', description: 'Modular agent runtime' }),
+ );
+
+ writeFileSync(
+ path.join(dir, 'packages', 'core', 'src', 'engine.ts'),
+ [
+ 'export interface StepResult { ok: boolean; output: string; }',
+ 'export class AgentEngine {',
+ ' async runStep(prompt: string): Promise {',
+ ' return { ok: true, output: prompt };',
+ ' }',
+ '}',
+ ].join('\n'),
+ );
+
+ writeFileSync(
+ path.join(dir, 'packages', 'cli', 'src', 'index.ts'),
+ [
+ "import { AgentEngine } from '../../core/src/engine.js';",
+ 'export async function runCliMain(argv: string[]) {',
+ ' const engine = new AgentEngine();',
+ ' return engine.runStep(argv.join(" "));',
+ '}',
+ ].join('\n'),
+ );
+
+ return dir;
+}
+
+test('Official MiniMax-Code-Plugins contract validation passes cleanly', async () => {
+ const res = await validateRepoWikiPlugin(PLUGIN_ROOT);
+ assert.equal(res.name, 'mcode-repowiki');
+ assert.deepEqual(res.mcpServers, ['mcode-repowiki']);
+});
+
+test('Full 4-step Repo Wiki MCP pipeline: plan -> context -> write (citation check) -> build site -> incremental diff sync', async () => {
+ const fixtureDir = createFixtureRepo();
+ const child = spawn(process.execPath, [SERVER_ENTRY], {
+ cwd: PLUGIN_ROOT,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+
+ let stdoutBuf = '';
+ const pending = new Map();
+ let nextId = 1;
+
+ child.stdout.on('data', (chunk) => {
+ stdoutBuf += chunk.toString('utf8');
+ let nl;
+ while ((nl = stdoutBuf.indexOf('\n')) !== -1) {
+ const line = stdoutBuf.slice(0, nl).trim();
+ stdoutBuf = stdoutBuf.slice(nl + 1);
+ if (!line) continue;
+ const msg = JSON.parse(line);
+ const entry = pending.get(msg.id);
+ if (entry) {
+ pending.delete(msg.id);
+ entry.resolve(msg);
+ }
+ }
+ });
+
+ const rpc = (method, params = {}) =>
+ new Promise((resolve, reject) => {
+ const id = nextId++;
+ pending.set(id, { resolve, reject });
+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
+ });
+
+ child.on('exit', (code) => {
+ for (const [, p] of pending.entries()) {
+ p.reject(new Error(`MCP server exited early with code ${code}`));
+ }
+ pending.clear();
+ });
+
+ try {
+ const initRes = await rpc('initialize', { protocolVersion: '2025-06-18' });
+ assert.equal(initRes.result.serverInfo.name, 'mcode-repowiki');
+
+ const toolsRes = await rpc('tools/list');
+ assert.deepEqual(
+ toolsRes.result.tools.map((t) => t.name),
+ ['wiki_locate', 'wiki_plan', 'wiki_write_page', 'wiki_serve'],
+ );
+
+ // Step 1: wiki_plan (blueprint)
+ const planRes = await rpc('tools/call', {
+ name: 'wiki_plan',
+ arguments: { repo_path: fixtureDir },
+ });
+ const planText = planRes.result.content[0].text;
+ assert.ok(planText.includes('Repo Wiki Blueprint:'));
+ assert.ok(planText.includes('01-architecture/01-system-overview.md'));
+ assert.ok(planText.includes('flowchart TD'));
+
+ // Step 2: wiki_plan with module_id (evidence pack)
+ const ctxRes = await rpc('tools/call', {
+ name: 'wiki_plan',
+ arguments: { repo_path: fixtureDir, module_id: 'packages-core' },
+ });
+ const ctxText = ctxRes.result.content[0].text;
+ assert.ok(ctxText.includes('AgentEngine'));
+ assert.ok(ctxText.includes('packages/core/src/engine.ts'));
+
+ // Step 3: wiki_write_page (valid citation + intentional bogus citation warning check)
+ const writeOverview = await rpc('tools/call', {
+ name: 'wiki_write_page',
+ arguments: {
+ repo_path: fixtureDir,
+ page_path: 'README.md',
+ title: 'Mini Agent Suite — 全景导览',
+ content: [
+ '# Mini Agent Suite — 全景导览',
+ '',
+ '核心执行引擎位于 [engine.ts:L2-L6](packages/core/src/engine.ts#L2-L6),命令行入口位于 [index.ts:L2-L5](packages/cli/src/index.ts#L2-L5)。',
+ '',
+ '```mermaid',
+ 'flowchart LR',
+ ' CLI["CLI Entry"] --> Core["AgentEngine Core"]',
+ '```',
+ ].join('\n'),
+ },
+ });
+ assert.ok(writeOverview.result.content[0].text.includes('**Verified Source Citations**: 2'));
+
+ const writeWarn = await rpc('tools/call', {
+ name: 'wiki_write_page',
+ arguments: {
+ repo_path: fixtureDir,
+ page_path: '01-architecture/01-system-overview.md',
+ title: '系统总体架构',
+ content: '# 系统总体架构\n\n引用不存在的文件 [ghost.ts:L1-L5](packages/ghost.ts#L1-L5)。',
+ },
+ });
+ assert.ok(writeWarn.result.content[0].text.includes('Unresolved file reference'));
+
+ // Step 4: wiki_serve (build_only: true)
+ const buildRes = await rpc('tools/call', {
+ name: 'wiki_serve',
+ arguments: { repo_path: fixtureDir, build_only: true },
+ });
+ const buildText = buildRes.result.content[0].text;
+ assert.ok(buildText.includes('Interactive Repo Wiki Compiled Successfully'));
+ const portalHtmlPath = path.join(fixtureDir, '.repowiki', 'index.html');
+ assert.ok(existsSync(portalHtmlPath));
+ const htmlContent = readFileSync(portalHtmlPath, 'utf8');
+ assert.ok(htmlContent.includes('Mini Agent Suite — 全景导览'));
+ assert.ok(htmlContent.includes('AgentEngine'));
+
+ // Step 5a: wiki_plan detects fresh existing Wiki
+ const planFresh = await rpc('tools/call', {
+ name: 'wiki_plan',
+ arguments: { repo_path: fixtureDir },
+ });
+ assert.ok(planFresh.result.content[0].text.includes('Existing RepoWiki Detected'));
+ assert.ok(planFresh.result.content[0].text.includes('all 2 chapters fresh'));
+
+ // Step 5b: Modify `engine.ts` -> verify incremental staleness propagates to `README.md`!
+ writeFileSync(
+ path.join(fixtureDir, 'packages', 'core', 'src', 'engine.ts'),
+ 'export class AgentEngine { async runStep() { return { ok: false, output: "changed" }; } }\n',
+ );
+ const statusStale = await rpc('tools/call', {
+ name: 'wiki_status',
+ arguments: { repo_path: fixtureDir },
+ });
+ const staleText = statusStale.result.content[0].text;
+ assert.ok(staleText.includes('cite code that has changed'));
+ assert.ok(staleText.includes('README.md'));
+ } finally {
+ child.stdin.end();
+ rmSync(fixtureDir, { recursive: true, force: true });
+ }
+});