diff --git a/plugins/Jialei-03/mcode-repowiki/.claude-plugin/plugin.json b/plugins/Jialei-03/mcode-repowiki/.claude-plugin/plugin.json new file mode 100644 index 00000000..97de6c68 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/.claude-plugin/plugin.json @@ -0,0 +1,38 @@ +{ + "name": "mcode-repowiki", + "version": "0.6.0", + "description": "Turn any codebase into an always-up-to-date local Wiki. Helps you and MiniMax Code understand unfamiliar projects fast, jump straight to the right files, see dependent files before editing, and save tokens.", + "author": { + "name": "Jialei-03", + "url": "https://github.com/Jialei-03" + }, + "homepage": "https://github.com/MiniMax-AI/MiniMax-Code-Plugins/tree/main/plugins/Jialei-03/mcode-repowiki", + "repository": "https://github.com/MiniMax-AI/MiniMax-Code-Plugins.git", + "license": "Apache-2.0", + "keywords": [ + "wiki", + "codebase", + "documentation", + "onboarding", + "read-code", + "code-map", + "save-tokens", + "architecture", + "repowiki", + "mcp" + ], + "skills": [ + "./skills/SKILL.md", + "./skills/mcode-repowiki/SKILL.md" + ], + "mcpServers": { + "mcode-repowiki": { + "type": "stdio", + "command": "node", + "args": [ + "./server/main.mjs" + ], + "cwd": "${PLUGIN_ROOT}" + } + } +} diff --git a/plugins/Jialei-03/mcode-repowiki/CHANGELOG.md b/plugins/Jialei-03/mcode-repowiki/CHANGELOG.md new file mode 100644 index 00000000..c597f367 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/CHANGELOG.md @@ -0,0 +1,60 @@ +# Changelog + +## 0.6.0 + +Keeping the Wiki current +- Every citation is recorded with the symbol it points into and a hash of the cited lines. Line sync follows the symbol, so citations whose label does not name the symbol now move with the code too, and part-of-symbol ranges keep their length. +- Freshness is checked per citation: code that only moved is fixed silently; code whose content changed, or a deleted file, is reported with the chapter and the exact citation. Before, the post-commit sync refreshed the stored hashes, so chapters with out-of-date prose stopped being reported after the first commit. +- `wiki_plan` reports which chapters cite changed code and how to update them; `mark_reviewed` confirms a chapter is still correct. `repowiki status` prints the same report for people, with a prompt to paste into MiniMax Code; `--reviewed` marks chapters as checked. +- `wiki_serve` installs the post-commit hook. Before, only the terminal commands did, so Wikis built inside MiniMax Code never re-synced on commit. +- The reader shows which citations changed at the top of an affected chapter, with "copy update prompt" and "mark as checked" buttons. +- Fixed: when one citation moved onto the lines another citation used to have, sync could give both the same range. +- The post-commit hook falls back to `node` on `PATH` when the Node that installed it is gone (for example after a MiniMax Code upgrade), and skips quietly if the plugin was removed. +- Chapters edited without `wiki_write_page` (a plain file write, a person's edit) keep their anchors in step with their text: citations still present keep their original anchor, new ones get one, removed ones are dropped. Before, such chapters kept the anchors of the text they replaced, so freshness checks watched citations that no longer existed and missed the real ones. +- Each module evidence pack from `wiki_plan` ends with how to save the chapter (`wiki_write_page`, not a plain file write), for agents that skip the blueprint or the skill. + +Code lookup +- `wiki_locate` lists who imports a symbol from resolved import statements, following package entries (`exports`, `dist/*.js` → `src/*.ts`) and re-exports, grouped by package with the import line; files that only contain the same word (comments, same-named parameters) are counted, not listed. Before, a whole-word search returned them all, the AI distrusted the list and grepped again: on earendil-works/pi impact analysis went from +5% tokens with the plugin to −14%. +- `wiki_locate` with only `file` lists every file importing anything that file exports; each result names the package and its test/build scripts. +- `file` may be a folder: its package, entry and each file's symbols; with `symbol`, the declaring file in that folder is found first. + +Windows +- Fixed: the MCP server never started on Windows, or from any folder whose path has spaces: its "am I the entry script" check compared a URL path (`/C:/...`, `%20`) with a file path, so it exited silently. +- `scripts/install-local.mjs` installs a `repowiki.cmd` launcher on Windows, finds `mcode` on `PATH` (where npm puts it), and says when the launcher folder is not on `PATH`. Before, it printed "installed" without installing the command or enabling the plugin. +- `repowiki --open` opens URLs with `&` correctly on Windows. + +Wiki writing +- `wiki_write_page` returns writing checks for the agent to fix: missing module sections, walkthrough steps without citations, citations over 200 lines, citations that point at no declaration, exact line or file counts in prose, very long paragraphs, an overview without chapter links or code citations, unquoted Mermaid labels. +- The skill now asks for chapters written for two readers (plain sentences first, self-contained sections, `[Symbol · file:Lx-Ly]` citations, no numbers that go stale) and adds an overview structure with a "where to change what" table and a glossary. + +Docs +- README and DESIGN list every file the plugin writes outside `.repowiki/` (hook block, `~/.repowiki/registry.json`, parse cache). +- The graph animation is 0.3 MB instead of 2.5 MB (shared palette, changed regions only). +- README: install steps, the four tools, what happens to the Wiki when code changes, uninstalling; the measured table now also shows all runs with the plugin, including those where the AI did not query the Wiki. + +## 0.5.0 + +Reader +- Notion-style look: warm neutrals, page icons, coloured callouts, tags and diagram groups; short titles in the sidebar, stats as tags, module summary under the title. +- Dependency graph rewritten as a separate module: live layout you can drag, neighbours highlighted on hover, labels that appear as you zoom, colour by module and brightness by how often a file is imported. Clicking a file lists who imports it and what it imports, each with a one-line description. +- One-line descriptions for files and modules (`.repowiki/descriptions.json`, falling back to chapter subtitles, doc comments and package manifests), hot-reloaded. +- Sync page shows one row per commit and readable line moves (`116–191 → 162–164 行`). + +Wiki writing +- Plain chapter titles (项目概览, 整体架构, module name); no repo name, stats, paths or adjectives. +- Module chapters follow six sections: what it does, where it sits, core concepts, one call step by step, how to change it, key files. +- Packages holding at least 10% of the code always get their own chapter; up to 10 modules plus one "other packages" chapter. +- `wiki_plan` no longer points agents at removed tools. + +Code lookup +- `wiki_locate` with `symbol` lists every file that uses it (repo-wide whole-word search, test files marked). Before: 7 of 27 files for `SessionEntry` in earendil-works/pi; now 27/27. +- Multi-line function signatures with a `= {}` default are parsed to their real end. +- Clearer guidance on when to call `wiki_locate`, including before code changes. + +Docs +- README: measured results from 43 MiniMax Code runs with and without the plugin. +- DESIGN rewritten in plain language, with a Chinese version. + +## 0.4.0 and earlier + +See the git history of `plugins/Jialei-03/mcode-repowiki`. diff --git a/plugins/Jialei-03/mcode-repowiki/DESIGN.md b/plugins/Jialei-03/mcode-repowiki/DESIGN.md new file mode 100644 index 00000000..2c8a982b --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/DESIGN.md @@ -0,0 +1,135 @@ +# How mcode-repowiki works + +[简体中文](DESIGN.zh-CN.md) · [README](README.md) + +This document explains what the plugin computes, what it stores, how it follows the code, and what we measured. The plugin runs entirely locally in Node.js with no third-party packages. + +## 1. Pipeline + +```mermaid +flowchart LR + A["1 Index (no model)
scan · symbols · import graph"] --> B["2 Plan (no model)
modules · evidence per module"] + B --> C["3 Write (MiniMax Code)
wiki_write_page checks citations, records anchors, writing checks"] + C --> D["4 Read and keep fresh (no model)
local reader · line sync on commit · freshness check"] + D -- "cited code changed" --> C +``` + +Only step 3 uses a model, and it is the model you already run in MiniMax Code. Steps 1, 2 and 4 are deterministic and cost no tokens. + +### Step 1 — Index +- `scanner.mjs` lists source files (git-aware, skips build output and `node_modules`) and finds the project name from the git remote or `package.json`. +- `parser.mjs` extracts symbols (functions, classes, class methods, types, interfaces) with exact start and end lines for TypeScript/JavaScript, Python, Go, Rust, Java and other brace languages, using a comment- and string-aware scanner rather than a full compiler. +- `resolver.mjs` turns import statements into file paths, including monorepo package names. +- `graph.mjs` builds the import graph, ranks files with PageRank (heavily imported files rank higher) and finds import cycles with Tarjan's algorithm. +- `cache.mjs` keeps parse results in SQLite (`node:sqlite`, skipped when unavailable), keyed by file content, so re-indexing an 810k-line repo takes well under a second when little changed. + +### Step 2 — Plan +- `planner.mjs` groups files by package or top-level folder and ranks the groups by how much the rest of the code depends on them. Product packages (CLIs, apps) are imported by nothing and would rank low, so any package holding at least 10% of the code also gets its own chapter. Up to 10 modules get chapters; the rest share one "other packages" chapter. +- For each module, `wiki_plan` with `module_id` returns its evidence: key files, their symbols with line ranges, who depends on the module and what it depends on. + +### Step 3 — Write +The skill (`skills/SKILL.md`) tells the agent how to write; `wiki_write_page` checks the result when it saves. +- **Structure**: the overview has six sections (what the repository is, mental model, module map, where to change what, glossary, reading route). Module chapters have six too (what it does, where it sits, core concepts, one call step by step, how to change it, key files). +- **Written for two readers**: each section opens with a plain sentence before naming symbols; each `##` section must make sense alone, because `wiki_locate` returns sections one at a time to the AI; citations look like `[Symbol · file:Lx-Ly](path#Lx-Ly)` and cover the function being described, not a whole large class; no line counts, file counts or version numbers in prose; say so when something could not be confirmed in the code. +- **Citation check**: every citation is checked against the code; a missing file or out-of-range lines comes back as a warning for the agent to fix. +- **Anchors**: for each citation the plugin records the symbol it points into (the function, method or type that overlaps the range most) and a hash of the cited lines, in `manifest.json`. Step 4 uses them for line sync and freshness. +- **Writing checks** (`lint.mjs`): missing module sections, walkthrough steps without a citation, citations over 200 lines, citations that point at no declaration, exact counts in prose, very long paragraphs, an overview without chapter links or code citations, and Mermaid labels with unquoted parentheses are returned as warnings. The agent fixes them and saves the whole chapter again. The checks never block a save. +- The agent also writes `.repowiki/descriptions.json`: one sentence per file and module. `describe.mjs` falls back to chapter subtitles, leading doc comments and package manifests when an entry is missing. + +### Step 4 — Read and keep fresh +- `site-builder.mjs` renders `.repowiki/` into one offline `index.html`: chapters, a source drawer that reads the real file, a dependency graph (`portal-graph.js`) and a sync page. +- `live-server.mjs` serves it on `127.0.0.1`, watches the repo and the Wiki, and pushes updates to the page over server-sent events. +- `wiki_serve` installs a git post-commit hook that runs `sync` after every commit. +- `sync.mjs` re-anchors citations after code moves: it re-parses the changed files, finds the anchored symbol's new position and rewrites the line range. A citation of a whole symbol follows the symbol's new range; a citation of part of a symbol keeps its length and shifts with it. Renamed files are followed through `git log -M`. Citations without an anchor fall back to symbol names in the nearby text. +- **Freshness check**: for each anchor, the hash of the cited lines now is compared with the hash recorded at write time: + - same: unchanged. + - different, but the same code is found where the symbol now is: it only moved; a line sync fixes it and the prose is fine. + - different, and no identical code is found: the code changed, so the paragraph may be out of date; the chapter and the citation are reported. + - the file is gone or the range is past its end: reported as "file gone" or "range gone". +- **Updating**: `wiki_plan` (no arguments) and `repowiki status` list the affected chapters and citations with the steps to update them: sync line numbers, read the current code for each citation with `wiki_locate`, edit only what is now wrong, save with `wiki_write_page` (which re-records the anchors). If a chapter is still correct, `wiki_plan` with `mark_reviewed` or `repowiki status --reviewed` re-records its anchors against the current code. The reader's "mark as checked" button does the same. +- `wiki_locate` answers code questions from the Wiki and the index: matching chapters and citations, live code slices, a symbol outline for one file, or the full body of one symbol plus every file that imports it. Importers come from `importers.mjs`, which resolves import statements: relative paths, workspace package names (reading `exports` in `package.json` and mapping `dist/*.js` back to `src/*.ts`), re-exports and `export *`, followed to the end and grouped by package with the import line. Files that merely contain the same word are counted, not listed. A folder returns its package, entry and each file's symbols; a folder plus a symbol first finds the file in it that declares the symbol. + +### An example +The `pi-coding-agent` chapter contains: + +> The session file format has a version, `CURRENT_SESSION_VERSION`: [session-manager.ts:L41-L41](packages/coding-agent/src/core/session-manager.ts#L41-L41) + +1. On save, the anchor records the symbol `CURRENT_SESSION_VERSION`, line 41, and the hash of `export const CURRENT_SESSION_VERSION = 3;`. +2. Someone adds five lines at the top of the file and commits: the hook runs `sync`, finds the symbol on line 46 and rewrites the link to `#L46-L46`. The hash still matches, so nothing is reported. +3. Someone changes 3 to 4 and commits: the line stays, but the hash differs, and `repowiki status` reports `CURRENT_SESSION_VERSION · session-manager.ts:L46-L46` as changed in that chapter. +4. Given the update prompt, MiniMax Code reads the new value, changes "version 3" to 4 in the prose and saves with `wiki_write_page`; the anchors are re-recorded and the chapter is current again. + +## 2. What is stored + +Everything lives in `.repowiki/` inside the repo and is hidden through `.git/info/exclude`, so `git status` stays clean and the team's `.gitignore` is untouched. + +| File | Contents | +|---|---| +| `README.md`, `01-architecture/`, `02-modules/`, `03-guides/` | the chapters, plain Markdown | +| `descriptions.json` | one-line descriptions of files and modules | +| `manifest.json` | each chapter's citation anchors (symbol, lines, content hash), hashes of cited files, sync history | +| `impact.json` | for each file, how many files import it and the main importers | +| `delta-index.json` | symbols changed since the Wiki was written, used by `wiki_locate` | +| `index.html` | the offline reader | + +Outside `.repowiki/` the plugin writes: a marked block in `.git/hooks/post-commit` (removed by `repowiki hook remove`); `~/.repowiki/registry.json`, mapping repositories to their Wiki folder; and the parse cache in `$PLUGIN_DATA`, or `mcode-repomap-cache/` in the system temp folder. + +## 3. Measured results + +The measurements of MiniMax Code with and without the plugin — 66 runs on earendil-works/pi — are in the [README](README.md#measured-minimax-code-with-vs-without-the-plugin). In short: tokens went down on all 6 tasks, by about 20% on average, and time by about 21%; finding code and tracing calls across modules saved the most, about 35% of tokens and 29–37% of time, and the number of tool calls per task became much steadier. + +The test of the Wiki following code changes (move, edit, rename, delete, then MiniMax Code updating from the report) is in the [README](README.md#when-the-code-changes) too. + +### Writing checks in practice +With the current skill and writing checks, MiniMax Code wrote pi's overview and `pi-coding-agent` chapters (about 8 minutes, 157k input and 31k output tokens). After the first save of the module chapter the writing checks reported two problems (a step without a citation; two citations pointing at a file-header comment rather than a declaration); the agent fixed them and the second save passed. + +| | Overview | pi-coding-agent | +|---|---|---| +| Code citations | 10 | 29 | +| Citations over 200 lines | 0 | 0 | +| Line or file counts in prose | 0 | 0 | +| Walkthrough steps without a citation | — | 0/8 | +| Writing-check warnings | 0 | 0 | + +The overview has "where to change what" (10 common tasks, each with an entry file and a citation) and a glossary (11 terms). In the module chapter every step names the function that runs and cites it, and "how to change it" is a set of step-by-step recipes. + +### Windows +On Windows 11 (MiniMax Code 0.7.7 installed with npm, Node 24, Git for Windows with `core.autocrlf=true`), on the same pi commit: +- The plugin's tests pass (20/20); the repository's `npm run check` fails only in other plugins' tests that need `bash` or Pillow. +- Installing from source as the README says, then asking MiniMax Code to generate the Wiki: 16 chapters and 424 citations in about 9 minutes, `git status` clean, the post-commit hook installed and run by Git for Windows. +- Inserting 5 lines above cited code and committing: the hook moved both citations into the file (L43→L48, L183→L188) and nothing was reported. Adding a field to `SessionHeader` and committing: exactly that citation was reported. Pasting the update prompt from `repowiki status` into MiniMax Code: it saved the chapter twice with `wiki_write_page` (the first save reported 7 citations pointing at no declaration) and the Wiki was 17/17 current again, in about 6 minutes. +- The reader listens on `127.0.0.1` only, and its source endpoint refused `..\`, `../`, drive-letter, `.git` and UNC paths. + +## 4. Known limits +- The agent decides whether to call `wiki_locate`. MiniMax Code 0.7.7 does not load hooks for locally installed plugins and does not use MCP server instructions, so the plugin cannot make the agent consult the Wiki first. +- Prose is not rewritten automatically. The plugin points at citations whose code changed; an agent or a person updates the text. +- Freshness compares the cited lines verbatim, so a comment or formatting change is reported as "code changed"; conversely, a behaviour change in code that no citation covers goes unnoticed. +- A citation that covers no declaration (an import, a top-level statement) has no symbol to follow; after the code moves it can only be found through symbol names in the nearby text. +- Symbol extraction is a fast scanner, not a type checker: it finds declarations and their line ranges, not overloads, inferred types or dynamic imports. +- Import tracing reads `import` and `export … from` statements only, not `require()` or dynamic `import()`; for languages other than JavaScript/TypeScript it falls back to a whole-word search, which also matches unrelated symbols with the same name. +- Chapters are only as good as the agent that wrote them. The writing checks catch structural and citation problems, not whether an explanation is right. +- Citation checks and writing checks run in `wiki_write_page`. If the agent skips the skill and writes chapters as plain files (seen once in four generation runs), anchors are still recorded at build time, but nobody reports the writing problems until the chapter is saved through `wiki_write_page`. + +## 5. For developers: command line, minimal tool mode and tests + +In everyday use you just ask MiniMax Code in plain words; the following is for debugging and automation. + +**Command line**: run `node scripts/install-local.mjs` once in the plugin folder to install the `repowiki` command (`~/.local/bin/repowiki`, or `repowiki.cmd` on Windows), or use `node server/cli.mjs` instead. + +| Command | What it does | +|---|---| +| `repowiki /path/to/repo --open` | Start the local reader and open it; if there is no Wiki yet, first write a basic one without a model (structure and symbols only) | +| `repowiki locate /path/to/repo "session storage"` | Look up code from the terminal | +| `repowiki status /path/to/repo` | Which chapters cite changed code, plus a prompt to update them | +| `repowiki status /path/to/repo --reviewed ` | Confirm chapters are still correct | +| `repowiki sync /path/to/repo` | Fix line numbers by hand (0 tokens) | +| `repowiki hook install\|remove /path/to/repo` | Install or remove the post-commit hook | + +**Minimal tool mode**: with `REPOWIKI_MCP_MODE=router` only `wiki_locate` and `wiki_plan` are exposed to the AI. Lookups and freshness checks still work; it cannot write chapters or start the reader. + +**Tests**: + +```bash +node --test ./test/*.test.mjs +node ./scripts/validate-plugin.mjs +``` diff --git a/plugins/Jialei-03/mcode-repowiki/DESIGN.zh-CN.md b/plugins/Jialei-03/mcode-repowiki/DESIGN.zh-CN.md new file mode 100644 index 00000000..d9d4fd1a --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/DESIGN.zh-CN.md @@ -0,0 +1,135 @@ +# mcode-repowiki 是怎么工作的 + +[English](DESIGN.md) · [README](README.zh-CN.md) + +这份文档说明插件算了什么、存了什么、怎么跟着代码更新,以及测出了什么。插件全部在本地用 Node.js 运行,不依赖任何第三方包。 + +## 1. 整体流程 + +```mermaid +flowchart LR + A["1 建索引(不调模型)
扫描 · 解析符号 · 依赖图"] --> B["2 做规划(不调模型)
分模块 · 每个模块的证据材料"] + B --> C["3 写文档(MiniMax Code)
wiki_write_page 核对引用、记录锚点、写作检查"] + C --> D["4 阅读与保鲜(不调模型)
本地网页 · 提交后同步行号 · 过期检测"] + D -- "引用的代码变了" --> C +``` + +只有第 3 步用到模型,用的就是你在 MiniMax Code 里正在用的那个模型。第 1、2、4 步都是确定性计算,不花 Token。 + +### 第 1 步:建索引 +- `scanner.mjs` 列出源码文件(认 git,跳过构建产物和 `node_modules`),并从 git 远程地址或 `package.json` 读出项目名。 +- `parser.mjs` 提取符号(函数、类、类方法、类型、接口)及精确的起止行号,支持 TypeScript/JavaScript、Python、Go、Rust、Java 等用大括号的语言。它是一个能识别注释和字符串的扫描器,不是完整的编译器。 +- `resolver.mjs` 把 import 语句解析成真实文件路径,包括 monorepo 里的包名。 +- `graph.mjs` 建立导入关系图,用 PageRank 给文件排序(被引用越多排越前),用 Tarjan 算法找循环依赖。 +- `cache.mjs` 把解析结果按文件内容存进 SQLite(`node:sqlite`,不可用时跳过)。81 万行的仓库改动不多时,重建索引远不到一秒。 + +### 第 2 步:做规划 +- `planner.mjs` 按包或顶层目录给文件分组,再按“其他代码有多依赖它”给分组排序。CLI、应用这类产品包没人引用,排名会很低,所以规定:代码量占全仓 10% 以上的包一定单独成章。最多 10 个模块各写一章,其余合成一章“其他包”。 +- 对每个模块,`wiki_plan` 传 `module_id` 会返回这个模块的证据材料:关键文件、带行号的符号、谁依赖它、它依赖谁。 + +### 第 3 步:写文档 +技能说明(`skills/SKILL.md`)告诉 AI 怎么写,`wiki_write_page` 在保存时检查写得怎么样。 +- **章节结构**:概览章节有六段(仓库是什么、心智模型、模块地图、想改什么去哪里改、术语表、阅读路线)。模块章节也有六段(它做什么、它在哪一层、核心概念、一次调用逐步走一遍、怎么修改它、关键文件)。 +- **同时写给人和 AI 看**:每段先用一两句白话说清楚,再讲符号;每个 `##` 小节要能单独看懂,因为 `wiki_locate` 是按小节返回给 AI 的;引用写成 `[符号 · 文件:Lx-Ly](路径#Lx-Ly)`,只引用正在讲的那个函数,不要一次引用整个大类;正文里不写行数、文件数、版本号这种很快会过时的数字;代码里确认不了的地方要明说。 +- **核对引用**:每条引用都对照源码检查,文件不存在或行号越界会返回警告让 AI 修正。 +- **记录锚点**:每条引用记下它指向的符号(与引用范围重叠最多的那个函数、方法或类型),以及被引用那几行的内容哈希,存进 `manifest.json`。第 4 步靠它们同步和检测过期。 +- **写作检查**(`lint.mjs`):缺了模块小节、逐步讲解里有步骤没给引用、引用超过 200 行、引用没落在任何声明上、正文里写死了数字、段落太长、概览没链接到章节或没引用代码、Mermaid 标签里的括号没加引号,都会作为警告返回。AI 修正后重新保存整章。这些检查只提示,不会拒绝保存。 +- AI 还会写 `.repowiki/descriptions.json`:每个文件、每个模块一句话说明。缺的条目由 `describe.mjs` 依次从章节副标题、文件开头的注释、包清单里补。 + +### 第 4 步:阅读与保鲜 +- `site-builder.mjs` 把 `.repowiki/` 编译成一个离线的 `index.html`:章节、直接读真实文件的源码抽屉、依赖图谱(`portal-graph.js`)和同步页。 +- `live-server.mjs` 在 `127.0.0.1` 上提供这个页面,监听仓库和 Wiki 的改动,通过 SSE 推送给页面。 +- `wiki_serve` 会安装一个 git 提交后钩子:每次提交后运行 `sync`。 +- `sync.mjs` 在代码移动后修正引用:重新解析改动过的文件,按锚点记下的符号找到它的新位置,改写行号;引用整个符号的就跟着符号的新范围走,引用符号一部分的就保持长度、跟着平移。文件改名通过 `git log -M` 跟上。没有锚点的引用,退回到在引用附近的文字里找符号名。 +- **过期检测**:对每条锚点,比较被引用那几行现在的哈希和写入时的哈希: + - 一致:没变。 + - 不一致,但顺着符号在别处找到了一模一样的代码:只是移动了,同步一下行号就好,文字不用改。 + - 不一致,也找不到一样的代码:代码内容变了,这段文字可能过时,报告这一章和这条引用。 + - 文件不存在或行号超出文件末尾:报告“文件已删”或“行号失效”。 +- **更新办法**:`wiki_plan`(不带参数)和 `repowiki status` 会列出过期的章节和引用,并给出更新步骤:先同步行号,再用 `wiki_locate` 逐条看现在的代码,只改说错了的段落,用 `wiki_write_page` 保存(同时重新记录锚点)。如果文字仍然正确,用 `wiki_plan` 的 `mark_reviewed` 或 `repowiki status --reviewed` 标记为已核对,也就是按当前代码重新记录锚点。阅读网页里的“标记已核对”按钮做的是同一件事。 +- `wiki_locate` 用 Wiki 和索引回答代码问题:相关章节和引用、实时代码片段、单个文件的符号大纲,或者某个符号的完整代码加上所有导入它的文件。导入方由 `importers.mjs` 按 import 语句解析得到:相对路径、工作区包名(读 `package.json` 的 `exports`,把 `dist/*.js` 对应回 `src/*.ts`)、再导出和 `export *` 都会一路跟下去,按包分组给出导入所在行;只是含有同名单词的文件不列出,只报个数。传入文件夹时返回所属包、入口和各文件的符号;文件夹加符号时,先在文件夹里找到声明它的文件。 + +### 一个例子 +`pi-coding-agent` 一章里有这样一句: + +> 会话文件格式有版本号 `CURRENT_SESSION_VERSION`:[session-manager.ts:L41-L41](packages/coding-agent/src/core/session-manager.ts#L41-L41) + +1. 保存时记下锚点:符号 `CURRENT_SESSION_VERSION`、第 41 行,以及 `export const CURRENT_SESSION_VERSION = 3;` 的哈希。 +2. 有人在文件开头加了 5 行并提交:钩子运行 `sync`,找到符号现在在第 46 行,把链接改成 `#L46-L46`。哈希仍然一致,所以不报过期。 +3. 又有人把 3 改成 4 并提交:行号不用动,但哈希变了,`repowiki status` 报告这一章的 `CURRENT_SESSION_VERSION · session-manager.ts:L46-L46` 代码已改。 +4. 把更新指令发给 MiniMax Code,它读到新值,把正文里的“版本是 3”改成 4,用 `wiki_write_page` 保存,锚点按新代码重新记录,这一章又回到一致状态。 + +## 2. 存了什么 + +所有内容都在仓库里的 `.repowiki/` 目录,通过 `.git/info/exclude` 隐藏,所以 `git status` 保持干净,也不会改团队的 `.gitignore`。 + +| 文件 | 内容 | +|---|---| +| `README.md`、`01-architecture/`、`02-modules/`、`03-guides/` | 各章节,普通 Markdown | +| `descriptions.json` | 文件和模块的一句话说明 | +| `manifest.json` | 每章的引用锚点(符号、行号、内容哈希)、被引用文件的哈希、同步记录 | +| `impact.json` | 每个文件被多少文件引用、主要引用方 | +| `delta-index.json` | Wiki 写完之后改过的符号,供 `wiki_locate` 使用 | +| `index.html` | 离线阅读页面 | + +仓库外写的东西:`.git/hooks/post-commit` 里一段带标记的代码(`repowiki hook remove` 可以删掉);`~/.repowiki/registry.json`,记录仓库和 Wiki 目录的对应关系;解析缓存,放在 `$PLUGIN_DATA`,没有这个变量时放在系统临时目录的 `mcode-repomap-cache/`。 + +## 3. 实测结果 + +在 earendil-works/pi 上让 MiniMax Code 用插件和不用插件分别跑,共 66 次(不用插件每类任务 6 次),结果见 [README](README.zh-CN.md#实测minimax-code-用插件-vs-不用插件)。简单说:6 类任务的 Token 全部下降,平均降约 20%,耗时平均降约 21%;跨模块找代码、追调用链省得最多,Token 降约 35%、耗时降 29%~37%,同一任务的工具调用次数也稳定了很多。 + +文档跟着代码更新的实测(移动、修改、改名、删除,再让 MiniMax Code 按报告更新)也写在 [README](README.zh-CN.md#代码改了文档怎么办) 里。 + +### 写作检查的实测 +让 MiniMax Code 按现在的技能说明和写作检查写 pi 的“项目概览”和“pi-coding-agent”两章(约 8 分钟,输入 15.7 万、输出 3.1 万 Token)。AI 第一次保存模块章节后,写作检查报了 2 个问题(一个步骤没给引用;两条引用指向文件开头的注释,没落在任何声明上),它修正后第二次全部通过。 + +| | 项目概览 | pi-coding-agent | +|---|---|---| +| 代码引用 | 10 | 29 | +| 超过 200 行的引用 | 0 | 0 | +| 正文里写死的行数、文件数 | 0 | 0 | +| “逐步走一遍”里没有引用的步骤 | — | 0/8 | +| 写作检查警告 | 0 | 0 | + +概览里有“想改什么,去哪里改”(10 个常见任务,每个都给了入口文件和引用)和术语表(11 个术语)。模块章节的每一步都写明了运行的函数并给了引用,“怎么修改它”一节是按步骤写的操作说明。 + +### Windows +在 Windows 11(npm 安装的 MiniMax Code 0.7.7、Node 24、Git for Windows,`core.autocrlf=true`)上,用同一个 pi 提交: +- 插件测试全部通过(20/20);整仓 `npm run check` 只有别的插件里需要 `bash` 或 Pillow 的测试失败。 +- 按 README 从源码安装,再让 MiniMax Code 生成文档:约 9 分钟写出 16 章、424 条引用,`git status` 干净,提交后钩子装好并由 Git for Windows 正常执行。 +- 在被引用代码上方插入 5 行并提交:钩子把这个文件里的两条引用都移到了新行号(L43→L48,L183→L188),没有误报。给 `SessionHeader` 加一个字段并提交:只报了这一条引用。把 `repowiki status` 给出的更新指令交给 MiniMax Code:它用 `wiki_write_page` 保存了两次(第一次写作检查报了 7 条引用没指向声明),约 6 分钟后回到 17/17 篇一致。 +- 阅读服务只监听 `127.0.0.1`,源码接口拒绝了 `..\`、`../`、盘符、`.git` 和 UNC 路径。 + +## 4. 已知局限 +- 要不要调用 `wiki_locate` 由 AI 自己决定。MiniMax Code 0.7.7 不加载本地插件的钩子,也不使用 MCP 服务器的 instructions,所以插件没法强制 AI 先查 Wiki。 +- 文字不会自动改。插件能指出哪条引用对应的代码变了,但要由 AI 或人去更新文字。 +- 过期检测比较的是被引用那几行的原文,所以只改了注释或格式也会被标成“代码已改”;反过来,如果某段文字讲的行为在没被引用的代码里变了,就检测不到。 +- 没落在任何声明上的引用(比如 import 语句、顶层语句)记不了符号,代码移动后只能靠引用附近文字里的符号名去找。 +- 符号提取用的是快速扫描器,不是类型检查器:能找到声明和起止行号,找不到重载、推断出来的类型和动态 import。 +- 导入追踪只认 `import`/`export … from` 语句,`require()` 和动态 `import()` 不在其中;非 JavaScript/TypeScript 语言退回到按整词搜索,这时同名但无关的符号也会被列出来。 +- 章节质量取决于写它的 AI。写作检查能发现结构和引用上的问题,判断不了讲得对不对。 +- 引用校验和写作检查是在 `wiki_write_page` 里做的。如果 AI 跳过 Skill、直接把章节当普通文件写(四次生成里出现过一次),构建时仍会补上锚点,但写作上的问题要等章节经 `wiki_write_page` 保存时才会报出来。 + +## 5. 给开发者:命令行、精简工具模式与测试 + +日常使用直接对 MiniMax Code 说中文就行,下面这些主要用于调试和自动化。 + +**命令行**:先在插件目录运行一次 `node scripts/install-local.mjs`,会装好 `repowiki` 命令(`~/.local/bin/repowiki`,Windows 上是 `repowiki.cmd`);也可以不装,用 `node server/cli.mjs` 代替。 + +| 命令 | 作用 | +|---|---| +| `repowiki /path/to/repo --open` | 启动本地阅读服务并打开网页;还没有文档时,先生成一份不调模型的基础版(只有目录结构和符号列表) | +| `repowiki locate /path/to/repo "会话存储"` | 在终端里定位代码 | +| `repowiki status /path/to/repo` | 哪些章节引用的代码改了,以及一句更新指令 | +| `repowiki status /path/to/repo --reviewed <章节\|all>` | 确认章节仍然正确 | +| `repowiki sync /path/to/repo` | 手动修正行号(0 Token) | +| `repowiki hook install\|remove /path/to/repo` | 安装或移除提交后自动同步的钩子 | + +**精简工具模式**:设置环境变量 `REPOWIKI_MCP_MODE=router` 后,只向 AI 暴露 `wiki_locate` 和 `wiki_plan`,查代码和检查新鲜度照常可用,但不能写章节,也不能启动阅读服务。 + +**运行测试**: + +```bash +node --test ./test/*.test.mjs +node ./scripts/validate-plugin.mjs +``` diff --git a/plugins/Jialei-03/mcode-repowiki/LICENSE b/plugins/Jialei-03/mcode-repowiki/LICENSE new file mode 100644 index 00000000..91319e50 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/LICENSE @@ -0,0 +1,103 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work. + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + patent license to make, have made, use, offer to sell, sell, import, + and otherwise transfer the Work. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work on an "AS IS" + BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. + + 8. Limitation of Liability. In no event and under no legal theory + shall any Contributor be liable to You for damages, including any + direct, indirect, special, incidental, or consequential damages. + + END OF TERMS AND CONDITIONS + + Copyright 2026 jialei + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 diff --git a/plugins/Jialei-03/mcode-repowiki/README.md b/plugins/Jialei-03/mcode-repowiki/README.md new file mode 100644 index 00000000..74e8254f --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/README.md @@ -0,0 +1,201 @@ +# mcode-repowiki + +[简体中文](README.zh-CN.md) · [How it works (`DESIGN.md`)](DESIGN.md) · [Changelog](CHANGELOG.md) · [License (Apache-2.0)](LICENSE) + +**`mcode-repowiki` has MiniMax Code read your repository once and write a local project Wiki. With it installed:** + +- **People understand the project faster**: open the browser and you get an overview, the architecture, one chapter per module and a dependency graph; every code reference opens the real source, so there is no more clicking through folder after folder. +- **The AI uses fewer tokens and less time**: it checks the Wiki first and goes straight to the right files and lines instead of searching the whole repository. Measured on the 810k-line pi repository, tokens went down on all 6 everyday tasks; locating code across modules took **36% fewer tokens and 29% less time**, tracing a call chain **35% fewer tokens and 37% less time**. +- **The Wiki follows the code**: after every commit line numbers move with the code at no token cost, and chapters whose explanation may be out of date are flagged so the AI rewrites only those paragraphs. + +![Dependency graph: coloured by module, neighbours highlighted on hover; clicking a file lists who imports it and what it imports](assets/graph-demo.png) + +--- + +## What does it do? + +When you open a large or unfamiliar repository, two things waste time: +- **For you**: clicking through folder after folder to find the main flow and how the modules relate. +- **For the AI**: searching and opening dozens of files to find one piece of logic, which is slow and burns tokens. + +`mcode-repowiki` has MiniMax Code read your code once and write a project Wiki into `.repowiki/` inside the repository: +1. **For people**: a local web page with an overview, the architecture, one chapter per module, getting-started guides and a dependency graph. Every code reference in the text opens the real file from disk. +2. **For the AI**: when looking for code it calls `wiki_locate` and gets, in well under a second, the matching chapters, exact files and line ranges, and every file that imports a given function or type (followed through package entries and re-exports). On cross-module lookups and call tracing this cut tokens by about a third (see the measurements below). +3. **Follows the code**: after every `git commit`, line numbers in the Wiki move to where the code now is, with no model call and no tokens. If the cited code itself changed, the plugin lists the affected chapters and citations, and MiniMax Code can rewrite just the paragraphs that are out of date. + +| One chapter per module, six fixed sections | Click a citation to read the real source | +|---|---| +| ![Module chapter](assets/reader-module.png) | ![Source drawer](assets/reader-source-drawer.png) | + +Screenshots come from the Wiki MiniMax Code generated with this plugin for [earendil-works/pi](https://github.com/earendil-works/pi) (810k lines of TypeScript). + +How it fits together: only the writing step calls a model; everything else is computed locally. + +![Architecture: indexing and planning run locally; writing uses your MiniMax Code model; the resulting .repowiki/ feeds both the local reader and wiki_locate; after every git commit line numbers are fixed and stale chapters are flagged](assets/architecture-en.svg) + +--- + +## Install + +**From the official plugin marketplace (once the plugin is listed)** + +```bash +mcode plugin add mcode-repowiki +``` + +**From source** + +Copy this folder into MiniMax Code's local plugin folder, then enable it. On macOS or Linux: + +```bash +cp -R plugins/Jialei-03/mcode-repowiki ~/.minimax/plugins/mcode-repowiki +``` + +On Windows (PowerShell): + +```powershell +Copy-Item -Recurse plugins\Jialei-03\mcode-repowiki "$env:USERPROFILE\.minimax\plugins\mcode-repowiki" +``` + +Then, on any system: + +```bash +mcode plugin enable mcode-repowiki@local +``` + +Start a new MiniMax Code session; `mcode plugin list` should show `mcode-repowiki` as enabled. Only Node.js `>= 22.5` is needed — no `npm install`. + +--- + +## Getting started + +### 1. Generate the Wiki + +Ask MiniMax Code: +```text +Analyze this repository with mcode-repowiki, generate a project Wiki, and open the local reading page. +``` + +You get: +- Markdown chapters in `.repowiki/`: overview, architecture, core flows, module dependencies, one chapter per module, getting started, extension recipes. +- A local web page (default `http://127.0.0.1:4321`) with search, the graph and clickable citations; chapters appear as they are written. +- A git post-commit hook that re-syncs line numbers after every commit. +- A clean `git status`: `.repowiki/` is hidden through the local `.git/info/exclude`, and the team's `.gitignore` is untouched. + +One-time cost for reference: on pi, 17 chapters plus 108 file descriptions took about 9.5 minutes (255k input, 49k output, 9.2M cache-read tokens). + +### 2. Find code and see what a change affects + +Ask MiniMax Code: +```text +Find where session storage is implemented in this repo, and which other files depend on it before I change it. +``` + +The AI calls `wiki_locate` first and gets the matching chapter, the exact file and line range, the current code, and the files that import it, instead of searching the whole repository. + +When the AI asked who a change to the `Schema` type affects on pi, `wiki_locate` answered in 289 ms with where `Schema` is defined, which two package entries export it, where each of the 31 files that really import it does so (across 5 packages, 2 of them tests), and how to run each package's tests. The 13 files that merely contain the word `Schema` without importing it are left out. + +### 3. Update the Wiki after the code has moved on + +Ask MiniMax Code: +```text +Update the out-of-date Wiki chapters with mcode-repowiki. +``` + +The AI fixes line numbers first, then checks each citation the plugin flagged as changed and edits only the paragraphs that are now wrong. See "When the code changes" below. + +--- + +## Tools + +MiniMax Code calls these four MCP tools; you do not need to remember them — just ask in plain words. + +| Tool | What it does | Used when | +|---|---|---| +| `wiki_locate` | Looks up code by question, file or symbol: matching chapters, live code with line ranges, a file's or folder's outline with its package and test scripts, or one symbol's full body plus every file that imports it, grouped by package | before answering a code question or changing code | +| `wiki_plan` | No arguments: the repository blueprint and a freshness report. `module_id`: the evidence for one module (key files, symbols, who depends on it). `sync: true`: fix line numbers. `mark_reviewed`: confirm a chapter is still correct | generating or updating the Wiki | +| `wiki_write_page` | Saves a chapter: checks every citation, records the symbol each one points at, and returns writing checks for the AI to fix | generating or updating the Wiki | +| `wiki_serve` | Builds the offline page `.repowiki/index.html`, starts the local reader, installs the commit hook | after writing | + +--- + +## When the code changes + +| What changed | What the plugin does | What you do | +|---|---|---| +| Code moved (lines inserted above it, functions reordered) | The post-commit hook moves citations to the new lines, 0 tokens | nothing | +| A file was renamed | Followed through `git log -M` | nothing | +| The cited code itself changed | The chapter and the exact citation are flagged "code changed" | ask the AI to update it, or mark it as checked | +| A cited file was deleted | The citation is flagged "file gone" | ask the AI to update it | + +How: when a chapter is saved, the plugin records, for each citation, the function or type it points at and a hash of those lines. If the code only moved, the symbol leads to the new lines; if the hash no longer matches, the paragraph may be out of date. + +**Seeing what is out of date**: in the reader, an affected chapter shows a banner listing the changed citations, with "copy update prompt" and "mark as checked" buttons: + +![Stale banner: lists the citations whose code changed, with "copy update prompt" and "mark as checked" buttons](assets/reader-stale.png) + +You can also just ask MiniMax Code "which Wiki chapters are out of date?" and it lists the changed citations in each affected chapter. If you read a chapter and it is still right, click "mark as checked" on the banner, or ask MiniMax Code to mark that chapter as checked. + +**Tested** on a copy of pi with three commits: +1. Insert 14 lines into `agent-session.ts`: 7 citations in 2 chapters moved to the new lines; nothing was reported as out of date. +2. Change `CURRENT_SESSION_VERSION` from 3 to 4, edit the body of `markRuntimeStreamFunction`, rename `theme-tokens.ts`: exactly those two citations were reported (the chapter said "version 3"), and the rename was followed. +3. Delete `mcp/runtime.ts`: the 3 chapters citing it were reported as "file gone". + +We then pasted the plugin's update prompt into MiniMax Code. It fixed line numbers, checked each flagged citation and edited 4 chapters (about 10.6 minutes, 112k input and 49k output tokens), after which all 17 chapters matched the code again. It corrected the version number, rewrote the paragraphs about the deleted file to describe the current implementation, updated the renamed file everywhere, and also fixed a description that had been wrong from the start. It pointed out that the test commits left stale imports, without touching the source. + +**Without the hook** (for example outside git), ask MiniMax Code to "sync the Wiki line numbers with mcode-repowiki". + +--- + +## Measured: MiniMax Code with vs. without the plugin + +On [earendil-works/pi](https://github.com/earendil-works/pi) (810k lines, 137 packages) we ran 6 everyday tasks through local MiniMax Code (model MiniMax-M3.1-Flash), 66 runs in total, and compared average tokens and time with and without the plugin. Prompts were identical and never told the AI to use the plugin. + +![Token and time change with the plugin installed: locate code −36% / −29%, trace a call chain −35% / −37%, architecture overview −25% / +4%, impact of a change −14% / 0%, small edit −6% / −14%, rename a shared type −7% / −53%](assets/measured-en.svg) + +| Task | Without plugin | With plugin | Change (tokens · time) | +|---|---|---|---| +| Locate code: how sessions are saved and restored | 1.23M · 100s | 0.79M · 71s | **−36% · −29%** | +| Trace a call chain: from a message to the streamed model reply | 1.68M · 151s | 1.09M · 96s | **−35% · −37%** | +| Architecture overview in 12 lines | 0.19M · 36s | 0.14M · 37s | −25% · +4% | +| Impact of changing the `Schema` type | 0.51M · 93s | 0.44M · 93s | −14% · 0% | +| Small edit: add a `uuid()` builder | 1.02M · 146s | 0.96M · 125s | −6% · −14% | +| Rename a shared type: which files `SessionEntry` touches (27) | 0.40M · 146s | 0.37M · 69s | −7% · **−53%** | + +Cells are average total tokens (including cache reads) · average time. + +**What this shows** +- **Tokens went down on all 6 tasks**, by about 20% on average; time went down by about 21% on average. +- **The biggest savings are on finding code and tracing calls across modules**: about 35% fewer tokens and 29–37% less time. Tool calls went from 32 to 25 (locate) and from 51 to 36 (trace). +- **The AI stops wandering**: without the plugin the same locate task took 22 to 72 tool calls and 0.61M to 3.0M tokens; with it, a steady 22 to 27 calls and at most 0.95M tokens. Trace narrowed from 31–84 calls to 28–46. +- **Impact analysis in one step**: the AI gets the list of importers grouped by package (31 files) instead of searching for each one. +- **Answers are just as correct**: every locate run found `session-manager.ts`, every rename run listed 27/27 files, every edit added `uuid()` and exported it. + +> Note: results vary somewhat from run to run (4–6 runs per group). All runs were made on 1–2 December 2026 with the same MiniMax Code version (0.7.7), model and repository commit. + +--- + +## Regenerate or uninstall + +- **Regenerate**: ask MiniMax Code to "regenerate the whole Wiki with mcode-repowiki". To refresh only what changed, ask it to "update the out-of-date Wiki chapters" — faster and cheaper. +- **Delete the Wiki**: delete `.repowiki/` in the repository; to remove every trace, also delete `~/.repowiki/` and the parse cache folder. +- **Remove the hook**: delete the lines between `# >>> repowiki auto-sync >>>` and `# <<< repowiki auto-sync <<<` in `.git/hooks/post-commit`; the rest of that file is yours and stays as it is. +- **Uninstall the plugin**: `mcode plugin remove mcode-repowiki` (`mcode-repowiki@local` if installed from source). + +--- + +## Requirements and privacy + +- **Requirements**: Node.js `>= 22.5`, no third-party npm packages. `git` is needed for automatic line sync and for hiding `.repowiki/`. +- **Platforms**: macOS, Linux and Windows. Tested by hand on macOS (Apple Silicon) and Windows 11 (MiniMax Code 0.7.7 installed with npm, Git for Windows): generating the Wiki, the reader, the post-commit sync and the freshness report all work the same. Linux is covered by the automated tests only. +- **Accounts and cost**: no extra account or API key. Writing the Wiki uses the model you already use in MiniMax Code and is billed like any conversation; line sync, freshness checks and `wiki_locate` call no model. +- **Files outside the repository**: `~/.repowiki/registry.json` maps each repository to its Wiki folder; the parse cache lives in `$PLUGIN_DATA`, or `mcode-repomap-cache/` in the system temp folder, and is safe to delete. Plus the marked block the hook adds to `.git/hooks/post-commit`. +- **Network and privacy**: the plugin itself runs entirely locally — no external requests, no telemetry, no code uploaded; the reader only listens on `127.0.0.1`. (MiniMax Code goes online to call its model, as it always does.) + +--- + +How it indexes code, keeps line numbers right and where its limits are, plus the command line and tests for developers: see [`DESIGN.md`](DESIGN.md). + +## License + +Apache-2.0 — see [`LICENSE`](LICENSE). diff --git a/plugins/Jialei-03/mcode-repowiki/README.zh-CN.md b/plugins/Jialei-03/mcode-repowiki/README.zh-CN.md new file mode 100644 index 00000000..2732adc6 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/README.zh-CN.md @@ -0,0 +1,201 @@ +# mcode-repowiki + +[English](README.md) · [工作原理 (`DESIGN.zh-CN.md`)](DESIGN.zh-CN.md) · [更新记录 (`CHANGELOG.md`)](CHANGELOG.md) · [Apache-2.0 协议](LICENSE) + +**`mcode-repowiki` 让 MiniMax Code 读一遍你的仓库,写出一份本地项目文档(Wiki)。装上之后:** + +- **人更快看懂整个项目**:浏览器里打开就有项目概览、整体架构、每个模块一章和依赖图谱,每处代码引用都能点开看真实源码,不用再一层层翻文件夹。 +- **AI 更省 Token、更快**:AI 找代码时先查 Wiki,直接拿到相关文件和行号,不必全仓搜索。在 81 万行的 pi 仓库上实测,6 类日常任务的 Token 全部下降;跨模块定位代码 **Token −36%、耗时 −29%**,追调用链 **Token −35%、耗时 −37%**。 +- **代码改了,文档跟着走**:每次提交后行号自动对齐,不花 Token;说明过时的章节会被单独标出来,让 AI 只改那几段。 + +![依赖图谱:按模块着色、悬停高亮邻居,点一个文件就列出谁引用它、它引用谁](assets/graph-demo.png) + +--- + +## 它是干嘛的? + +接手一个陌生或者很大的代码仓库时,最头疼的两件事通常是: +- **人看代码累**:文件夹一层套一层,翻半天都搞不清主流程在哪、模块之间是什么关系。 +- **AI 找代码贵**:为了找一段逻辑,AI 常常要反复搜索、打开几十个文件,既慢又烧 Token。 + +`mcode-repowiki` 让 MiniMax Code 读一遍你的代码,在仓库里的 `.repowiki/` 目录写一份项目文档: +1. **给人看**:本地网页里有项目概览、架构、每个模块一章、上手指南和依赖图谱。文档里每一处代码引用都能点开,直接看磁盘上的真实源码。 +2. **给 AI 用**:AI 找代码时调用 `wiki_locate`,一秒内拿到相关章节、准确的文件和行号,以及导入某个函数或类型的所有文件(会穿过包入口和再导出去追踪)。实测跨模块找代码、追调用链时,Token 降了约三分之一(见下方实测)。 +3. **跟着代码更新**:每次 `git commit` 之后,文档里的行号自动对齐到代码的新位置,不调模型、不花 Token。如果被引用的代码内容变了,插件会列出受影响的章节和具体引用,你可以让 MiniMax Code 只改过时的段落。 + +| 每个模块一章,固定六段讲清楚 | 点文档里的引用,直接看真实源码 | +|---|---| +| ![模块章节](assets/reader-module.png) | ![源码抽屉](assets/reader-source-drawer.png) | + +截图来自 MiniMax Code 用本插件为 [earendil-works/pi](https://github.com/earendil-works/pi)(81 万行 TypeScript)生成的 Wiki。 + +整体框架:只有写文档这一步调用模型,其余都在本地计算。 + +![整体框架:建索引、做规划在本地完成;写文档用 MiniMax Code 的模型;生成的 .repowiki/ 同时供本地阅读网页和 wiki_locate 使用;每次 git commit 后自动修正行号并标出过期章节](assets/architecture-zh.svg) + +--- + +## 安装 + +**方式一:从官方插件市场安装(插件上架后可用)** + +```bash +mcode plugin add mcode-repowiki +``` + +**方式二:从源码安装到本机** + +把本目录复制到 MiniMax Code 的本地插件目录,然后启用。macOS 或 Linux: + +```bash +cp -R plugins/Jialei-03/mcode-repowiki ~/.minimax/plugins/mcode-repowiki +``` + +Windows(PowerShell): + +```powershell +Copy-Item -Recurse plugins\Jialei-03\mcode-repowiki "$env:USERPROFILE\.minimax\plugins\mcode-repowiki" +``` + +然后在任何系统上: + +```bash +mcode plugin enable mcode-repowiki@local +``` + +装好后重新打开 MiniMax Code 会话,用 `mcode plugin list` 能看到 `mcode-repowiki` 显示为 enabled。只需要 Node.js `>= 22.5`,不用 `npm install`。 + +--- + +## 上手示例 + +### 1. 给项目生成文档 + +对 MiniMax Code 说: +```text +用 mcode-repowiki 帮我分析当前项目,生成一份本地文档并打开阅读页面。 +``` + +你会得到: +- `.repowiki/` 里的一组 Markdown 章节:项目概览、整体架构、核心流程、模块依赖、每个模块一章、快速上手、扩展开发。 +- 一个本地网页(默认 `http://127.0.0.1:4321`),可以搜索、看图谱、点引用看源码;章节写好一篇就出现一篇。 +- 一个 git 提交钩子:之后每次提交都会自动修正行号。 +- `git status` 保持干净:`.repowiki/` 通过本地的 `.git/info/exclude` 隐藏,不改团队的 `.gitignore`。 + +一次性成本参考:pi 仓库生成 17 章加 108 条文件说明,约 9.5 分钟(输入 25.5 万、输出 4.9 万、缓存读取 920 万 Token)。 + +### 2. 找代码、看改动会影响谁 + +对 MiniMax Code 说: +```text +帮我找一下这个项目里“会话存储”的代码在哪,改它之前有哪些其他文件会受影响? +``` + +AI 会先调用 `wiki_locate`:拿到相关章节、准确的文件和行号、当前的源码片段,以及引用这个文件的其他文件,不必全仓乱搜。 + +实测中 AI 问“改 `Schema` 类型会影响谁”时,`wiki_locate` 在 289 毫秒内返回:`Schema` 定义在哪一行、从哪两个包入口导出、31 个真正导入它的文件(分布在 5 个包里,其中 2 个是测试)各在哪一行,以及每个包跑测试的命令。只是碰巧含有 `Schema` 这个词、并没有导入它的 13 个文件不会混进来。 + +### 3. 代码改了一阵之后,更新文档 + +对 MiniMax Code 说: +```text +用 mcode-repowiki 更新过期的 Wiki 章节。 +``` + +AI 会先修正行号,再逐条核对插件列出的“代码已改”的引用,只改说错了的段落。详见下面的“代码改了,文档怎么办”。 + +--- + +## 插件提供的工具 + +MiniMax Code 通过 MCP 调用这四个工具,平时你不用记它们,直接用中文提需求就行: + +| 工具 | 做什么 | 什么时候用 | +|---|---|---| +| `wiki_locate` | 按问题、文件或符号查代码:返回相关章节、带行号的实时代码片段、文件或文件夹的大纲(附所属包和测试命令),或者某个符号的完整代码和所有导入它的文件(按包分组) | 每次问代码、改代码之前 | +| `wiki_plan` | 不带参数:项目蓝图和文档新鲜度报告;带 `module_id`:某个模块的取证材料(关键文件、符号、上下游);`sync: true`:修正行号;`mark_reviewed`:确认某章仍然正确 | 生成和更新文档时 | +| `wiki_write_page` | 保存一章:核对每条引用,记下每条引用对应的符号,返回写作检查结果让 AI 修正 | 生成和更新文档时 | +| `wiki_serve` | 生成离线网页 `.repowiki/index.html`,启动本地阅读服务,安装提交钩子 | 写完文档后 | + +--- + +## 代码改了,文档怎么办 + +| 代码的变化 | 插件怎么处理 | 需要你做什么 | +|---|---|---| +| 代码挪了位置(上面插了几行、函数换了顺序) | 提交后钩子自动把引用改到新行号,0 Token | 不用管 | +| 文件改名 | 通过 `git log -M` 跟到新文件名 | 不用管 | +| 被引用的代码内容变了 | 标出“代码已改”的章节和具体引用 | 让 AI 更新,或确认后标记“已核对” | +| 被引用的文件删了 | 标出“文件已删”的引用 | 让 AI 更新 | + +原理:每章保存时,插件为每条引用记下它指向的函数或类型,以及那几行代码的哈希。代码挪了位置,就顺着符号找到新行号;代码内容变了,哈希对不上,就说明这段文字可能过时。 + +**怎么看哪些章节过时了**:阅读网页里,过时的章节顶部会出现提示条,列出改过的引用,并提供“复制更新指令”和“标记已核对”两个按钮: + +![过期提示条:列出代码已改的引用,以及“复制更新指令”和“标记已核对”按钮](assets/reader-stale.png) + +也可以直接对 MiniMax Code 说“看看 Wiki 有哪些章节过时了”,它会列出每篇过时章节里改过的引用。看过之后觉得文字仍然正确,点提示条上的“标记已核对”,或者对它说“把这一章标记为已核对”。 + +**实测**(在 pi 仓库副本上连续做了 3 次提交): +1. 在 `agent-session.ts` 里插入 14 行:2 个章节里的 7 处引用自动移到新行号,没有误报过期。 +2. 把 `CURRENT_SESSION_VERSION` 从 3 改成 4,改了 `markRuntimeStreamFunction` 的函数体,并给 `theme-tokens.ts` 改名:只标出了这两处引用(章节原文写着“版本是 3”),改名的文件被自动跟上。 +3. 删除 `mcp/runtime.ts`:引用它的 3 个章节都被标成“文件已删”。 + +然后把插件给出的那句更新指令原样发给 MiniMax Code:它先修正行号,再逐条核对被标出的引用,改了 4 章(约 10.6 分钟,输入 11.2 万、输出 4.9 万 Token),最后状态回到 17/17 篇一致。它改对了版本号,把讲已删除文件的段落改成了现在的实现,同步了改名后的文件名,还顺手纠正了一处原本就写错的描述。它也指出这几次测试提交留下了没改过来的 import,但没有动源码。 + +**没有提交钩子时**(比如仓库不是 git 仓库),对 MiniMax Code 说“用 mcode-repowiki 同步一下 Wiki 行号”即可。 + +--- + +## 实测:MiniMax Code 用插件 vs 不用插件 + +在 [earendil-works/pi](https://github.com/earendil-works/pi)(81 万行、137 个子包)上,用本机 MiniMax Code(模型 MiniMax-M3.1-Flash)跑 6 类日常任务,共 66 次,比较装插件前后的平均 Token 和耗时。两边提示词完全相同,没有特意提示 AI 去用插件。 + +![装上插件后 6 类任务的 Token 和耗时变化:定位代码 −36% / −29%,追调用链 −35% / −37%,架构概览 −25% / +4%,改动影响面 −14% / 0%,小功能修改 −6% / −14%,公共类型改名 −7% / −53%](assets/measured-zh.svg) + +| 任务 | 不用插件 | 装了插件 | 变化(Token · 耗时) | +|---|---|---|---| +| 定位代码:会话怎么存盘和恢复 | 123 万 · 100s | 79 万 · 71s | **−36% · −29%** | +| 追调用链:消息到模型流式返回经过哪些函数 | 168 万 · 151s | 109 万 · 96s | **−35% · −37%** | +| 架构概览:12 行讲清整体结构 | 19 万 · 36s | 14 万 · 37s | −25% · +4% | +| 改动影响面:改 `Schema` 类型会影响谁 | 51 万 · 93s | 44 万 · 93s | −14% · 0% | +| 小功能修改:新增 `uuid()` 构建函数 | 102 万 · 146s | 96 万 · 125s | −6% · −14% | +| 公共类型改名:`SessionEntry` 要改哪些文件(共 27 个) | 40 万 · 146s | 37 万 · 69s | −7% · **−53%** | + +表中是平均总 Token(含缓存读取)· 平均耗时。 + +**结论** +- **6 类任务的 Token 全部下降**,平均降约 20%;耗时平均降约 21%。 +- **跨模块找代码、追调用链省得最多**:Token 降约 35%,耗时降 29%~37%。工具调用从 32 次降到 25 次(定位)、从 51 次降到 36 次(追调用链)。 +- **AI 不再跑偏**:不用插件时,同一个定位任务要 22~72 次工具调用、61 万~300 万 Token;装了插件稳定在 22~27 次、最多 95 万 Token。追调用链从 31~84 次收窄到 28~46 次。 +- **改动影响面一步到位**:AI 直接拿到按包分组的导入名单(31 个文件),不用自己一个个搜。 +- **答案质量不打折**:每次定位都找到了 `session-manager.ts`,每次改名任务都列全了 27/27 个文件,每次修改都加了 `uuid()` 并从入口导出。 + +> 说明:不同运行之间存在一定波动(每组 4~6 次)。所有运行都在 2026 年 12 月 1~2 日完成,MiniMax Code 0.7.7、模型和仓库提交都相同。 + +--- + +## 重新生成与卸载 + +- **重新生成**:对 MiniMax Code 说“用 mcode-repowiki 重新生成整份 Wiki”。只想更新改过的部分,就说“更新过期的 Wiki 章节”,这样更快、更省。 +- **删除文档**:直接删掉仓库里的 `.repowiki/` 目录;想清干净的话,再删掉 `~/.repowiki/` 和解析缓存目录。 +- **移除提交钩子**:删掉 `.git/hooks/post-commit` 里 `# >>> repowiki auto-sync >>>` 和 `# <<< repowiki auto-sync <<<` 之间的几行即可,你自己的钩子内容不受影响。 +- **卸载插件**:`mcode plugin remove mcode-repowiki`(从源码安装的,写 `mcode-repowiki@local`)。 + +--- + +## 环境要求与隐私 + +- **运行环境**:Node.js `>= 22.5`,不用装任何第三方 npm 包。有 `git` 才能自动同步行号、隐藏 `.repowiki/`。 +- **支持系统**:macOS、Linux、Windows。在 macOS(Apple Silicon)和 Windows 11(npm 安装的 MiniMax Code 0.7.7、Git for Windows)上实际测过:生成文档、阅读页面、提交后自动同步和过期检测都和 macOS 上一样。Linux 只跑过自动测试。 +- **账号与费用**:不需要额外账号或 API Key。写文档用的是你在 MiniMax Code 里正在用的模型,按正常对话计费;行号同步、过期检测和 `wiki_locate` 都不调模型。 +- **写到仓库外的文件**:`~/.repowiki/registry.json` 记录哪个仓库对应哪个 Wiki 目录;代码解析缓存放在 `$PLUGIN_DATA`,没有这个变量时放在系统临时目录的 `mcode-repomap-cache/` 下,删掉不影响使用。还有提交钩子写进 `.git/hooks/post-commit` 的那几行。 +- **网络与隐私**:插件本身完全在本地运行,不发任何外网请求、不做数据统计、不上传源码;本地阅读服务只监听 `127.0.0.1`。(MiniMax Code 调用模型时会联网,这和平时使用 MiniMax Code 一样。) + +--- + +想了解插件怎么建索引、怎么保持行号正确、已知有哪些局限,以及给开发者用的命令行和测试,详见 [`DESIGN.zh-CN.md`](DESIGN.zh-CN.md)。 + +## 开源协议 + +Apache-2.0,详见 [`LICENSE`](LICENSE)。 diff --git a/plugins/Jialei-03/mcode-repowiki/assets/architecture-en.svg b/plugins/Jialei-03/mcode-repowiki/assets/architecture-en.svg new file mode 100644 index 00000000..714dc9ca --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/assets/architecture-en.svg @@ -0,0 +1,6 @@ + + +How mcode-repowiki fits togetherOnly step 3 calls a model (the one you already use in MiniMax Code); everything else runs locally and costs no tokensYour repository +source + +git history1Indexscan files, parse symbolsimport graph and PageRanklocal · 0 tokens2Plansplit the repo into modulesan evidence pack per modulelocal · 0 tokens3WriteMiniMax Code reads code, writeschapters; wiki_write_page checksyour MiniMax Code model.repowiki/each citation stores its symbol and a code hashchapters *.mdmanifest.jsonimpact.jsondescriptions.jsonwritesonly stale paragraphsFor people: local readerchapters · dependency graph · sourcerefreshes live as the code changesFor the AI: wiki_locatematching chapters + live codewho imports it, grouped by package4Keep it currentafter every git commit · 0 tokenscode moved, file renamed→citations follow to new linescited code changed→chapter and citation flaggedcited file deleted→flagged as “file gone”Stale chapters go back to MiniMax Code to rewritegit commit diff --git a/plugins/Jialei-03/mcode-repowiki/assets/architecture-zh.svg b/plugins/Jialei-03/mcode-repowiki/assets/architecture-zh.svg new file mode 100644 index 00000000..d9e0fcb9 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/assets/architecture-zh.svg @@ -0,0 +1,6 @@ + + +mcode-repowiki 的整体框架只有第 3 步调用模型(就是你在 MiniMax Code 里正在用的那个),其余都在本地计算,不花 Token你的代码仓库 +源码 + +git 历史1建索引扫描文件,解析符号和行号算 import 依赖图和 PageRank本地 · 0 Token2做规划把仓库分成模块每个模块配一份证据包本地 · 0 Token3写文档MiniMax Code 读代码、写章节wiki_write_page 逐条核对引用用你的 MiniMax Code 模型.repowiki/每条引用都记下它指向的符号和那几行代码的哈希章节 *.mdmanifest.jsonimpact.jsondescriptions.json写入只改过时的段落给人看:本地阅读网页章节 · 依赖图谱 · 点引用看源码代码一改,网页实时刷新给 AI 用:wiki_locate相关章节 + 带行号的最新代码谁导入了它,按包分组列出4跟着代码更新每次 git commit 后 · 0 Token代码挪了位置、文件改名→自动改到新行号被引用的代码内容变了→标出过期的章节和引用被引用的文件删了→标出“文件已删”过期的章节交给 MiniMax Code,只改过时的段落git commit diff --git a/plugins/Jialei-03/mcode-repowiki/assets/graph-demo.png b/plugins/Jialei-03/mcode-repowiki/assets/graph-demo.png new file mode 100644 index 00000000..1e37c03a Binary files /dev/null and b/plugins/Jialei-03/mcode-repowiki/assets/graph-demo.png differ diff --git a/plugins/Jialei-03/mcode-repowiki/assets/measured-en.svg b/plugins/Jialei-03/mcode-repowiki/assets/measured-en.svg new file mode 100644 index 00000000..91deabb8 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/assets/measured-en.svg @@ -0,0 +1,3 @@ + + +How tokens and time changed with the plugin installed6 everyday tasks, 66 MiniMax Code runs on earendil-works/pi (810k lines); average change versus no pluginTokens down on all 6 taskstokens −20% on averagetime −21% on averageTokensTime-60%-40%-20%0%-60%-40%-20%0%Locate codewithout plugin: 1.23M tokens · 100s−36%−29%Trace a call chainwithout plugin: 1.68M tokens · 151s−35%−37%Architecture overviewwithout plugin: 0.19M tokens · 36s−25%+4%Impact of a changewithout plugin: 0.51M tokens · 93s−14%0%Small editwithout plugin: 1.02M tokens · 146s−6%−14%Rename a shared typewithout plugin: 0.40M tokens · 146s−7%−53%← further left is cheaper← further left is cheaperResults vary somewhat from run to run (4–6 runs per group) · model MiniMax-M3.1-Flash · MiniMax Code 0.7.7 · Dec 2026 diff --git a/plugins/Jialei-03/mcode-repowiki/assets/measured-zh.svg b/plugins/Jialei-03/mcode-repowiki/assets/measured-zh.svg new file mode 100644 index 00000000..6beaf6a5 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/assets/measured-zh.svg @@ -0,0 +1,3 @@ + + +装上插件后,Token 和耗时变化了多少在 earendil-works/pi(81 万行)上跑 6 类日常任务、共 66 次 MiniMax Code,与不用插件相比的平均变化6 类任务 Token 全部下降Token 平均 −20%耗时平均 −21%Token耗时-60%-40%-20%0%-60%-40%-20%0%定位代码不用插件:123 万 Token · 100s−36%−29%追调用链不用插件:168 万 Token · 151s−35%−37%架构概览不用插件:19 万 Token · 36s−25%+4%改动影响面不用插件:51 万 Token · 93s−14%0%小功能修改不用插件:102 万 Token · 146s−6%−14%公共类型改名不用插件:40 万 Token · 146s−7%−53%← 越往左越省← 越往左越省不同运行之间存在一定波动(每组 4~6 次)· 模型 MiniMax-M3.1-Flash · MiniMax Code 0.7.7 · 2026 年 12 月 diff --git a/plugins/Jialei-03/mcode-repowiki/assets/reader-module.png b/plugins/Jialei-03/mcode-repowiki/assets/reader-module.png new file mode 100644 index 00000000..0c2ccb8f Binary files /dev/null and b/plugins/Jialei-03/mcode-repowiki/assets/reader-module.png differ diff --git a/plugins/Jialei-03/mcode-repowiki/assets/reader-source-drawer.png b/plugins/Jialei-03/mcode-repowiki/assets/reader-source-drawer.png new file mode 100644 index 00000000..e5b62226 Binary files /dev/null and b/plugins/Jialei-03/mcode-repowiki/assets/reader-source-drawer.png differ diff --git a/plugins/Jialei-03/mcode-repowiki/assets/reader-stale.png b/plugins/Jialei-03/mcode-repowiki/assets/reader-stale.png new file mode 100644 index 00000000..3306182c Binary files /dev/null and b/plugins/Jialei-03/mcode-repowiki/assets/reader-stale.png differ diff --git a/plugins/Jialei-03/mcode-repowiki/icon-dark.png b/plugins/Jialei-03/mcode-repowiki/icon-dark.png new file mode 100644 index 00000000..dd09f36b Binary files /dev/null and b/plugins/Jialei-03/mcode-repowiki/icon-dark.png differ diff --git a/plugins/Jialei-03/mcode-repowiki/icon.png b/plugins/Jialei-03/mcode-repowiki/icon.png new file mode 100644 index 00000000..7d846d9b Binary files /dev/null and b/plugins/Jialei-03/mcode-repowiki/icon.png differ diff --git a/plugins/Jialei-03/mcode-repowiki/mcp.json b/plugins/Jialei-03/mcode-repowiki/mcp.json new file mode 100644 index 00000000..9959ebd7 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/mcp.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "mcpServers": { + "mcode-repowiki": { + "type": "stdio", + "command": "node", + "args": [ + "./server/main.mjs" + ], + "cwd": "${PLUGIN_ROOT}" + } + } +} diff --git a/plugins/Jialei-03/mcode-repowiki/package.json b/plugins/Jialei-03/mcode-repowiki/package.json new file mode 100644 index 00000000..107f6539 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/package.json @@ -0,0 +1,36 @@ +{ + "name": "repowiki", + "version": "0.6.0", + "description": "Universal Real-Time Repository Architecture Wiki & MCP Engine (CLI + SSE Live Watcher + MiniMax Code / Claude / Cursor Adapter)", + "type": "module", + "license": "Apache-2.0", + "author": "jialei", + "bin": { + "repowiki": "./server/cli.mjs" + }, + "exports": { + ".": "./server/main.mjs", + "./live-server": "./server/live-server.mjs", + "./auto-init": "./server/auto-init.mjs" + }, + "engines": { + "node": ">=22.5.0" + }, + "scripts": { + "start": "node ./server/cli.mjs serve", + "test": "node --test ./test/*.test.mjs", + "validate": "node ./scripts/validate-plugin.mjs", + "install:mcode": "node ./scripts/install-local.mjs" + }, + "keywords": [ + "repowiki", + "deepwiki", + "architecture", + "ast", + "pagerank", + "sse", + "mcp", + "minimax-code", + "mcode" + ] +} diff --git a/plugins/Jialei-03/mcode-repowiki/plugin.json b/plugins/Jialei-03/mcode-repowiki/plugin.json new file mode 100644 index 00000000..103fdf52 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/plugin.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "mcode-repowiki", + "version": "0.6.0", + "description": "Turn any codebase into an always-up-to-date local Wiki. Helps you and MiniMax Code understand unfamiliar projects fast, jump straight to the right files, see dependent files before editing, and save tokens.", + "author": { + "name": "Jialei-03", + "url": "https://github.com/Jialei-03" + }, + "homepage": "https://github.com/MiniMax-AI/MiniMax-Code-Plugins/tree/main/plugins/Jialei-03/mcode-repowiki", + "repository": "https://github.com/MiniMax-AI/MiniMax-Code-Plugins.git", + "license": "Apache-2.0", + "keywords": [ + "wiki", + "codebase", + "documentation", + "onboarding", + "read-code", + "code-map", + "save-tokens", + "architecture", + "repowiki", + "mcp" + ] +} diff --git a/plugins/Jialei-03/mcode-repowiki/scripts/install-local.mjs b/plugins/Jialei-03/mcode-repowiki/scripts/install-local.mjs new file mode 100644 index 00000000..953767c5 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/scripts/install-local.mjs @@ -0,0 +1,110 @@ +import { spawnSync } from 'node:child_process'; +import { chmodSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const SOURCE_ROOT = path.resolve(__dirname, '..'); +const HOME = os.homedir(); +const TARGET_PLUGINS_DIR = process.env.MINIMAX_PLUGINS_DIR || path.join(HOME, '.minimax', 'plugins'); +const TARGET_DIR = path.join(TARGET_PLUGINS_DIR, 'mcode-repowiki'); +const LEGACY_REPOMAP_DIR = path.join(TARGET_PLUGINS_DIR, 'mcode-repomap'); + +const DEPLOY_ITEMS = [ + 'package.json', + 'plugin.json', + 'mcp.json', + '.claude-plugin', + 'icon.png', + 'icon-dark.png', + 'LICENSE', + 'README.md', + 'README.zh-CN.md', + 'server', + 'skills', +]; + +mkdirSync(TARGET_PLUGINS_DIR, { recursive: true }); + +if (existsSync(LEGACY_REPOMAP_DIR)) { + rmSync(LEGACY_REPOMAP_DIR, { recursive: true, force: true }); +} + +if (existsSync(TARGET_DIR)) { + rmSync(TARGET_DIR, { recursive: true, force: true }); +} +mkdirSync(TARGET_DIR, { recursive: true }); + +for (const item of DEPLOY_ITEMS) { + const src = path.join(SOURCE_ROOT, item); + if (!existsSync(src)) continue; + cpSync(src, path.join(TARGET_DIR, item), { recursive: true }); +} + +const isWindows = process.platform === 'win32'; +const localBin = path.join(HOME, '.local', 'bin'); +const cliTarget = path.join(TARGET_DIR, 'server', 'cli.mjs'); +mkdirSync(localBin, { recursive: true }); +let launcherPath; + +if (isWindows) { + // A .cmd launcher; Windows runs it from cmd.exe and PowerShell alike. + launcherPath = path.join(localBin, 'repowiki.cmd'); + writeFileSync(launcherPath, ['@echo off', `node "${cliTarget}" %*`, ''].join('\r\n')); +} else { + for (const exe of [path.join(TARGET_DIR, 'server', 'cli.mjs'), path.join(TARGET_DIR, 'server', 'main.mjs')]) { + try { + chmodSync(exe, 0o755); + } catch { + // Non-fatal + } + } + + const localNode = path.join(localBin, 'node'); + const mcodeBundledNode = path.join(HOME, '.minimax-code', 'runtime', 'node', 'bin', 'node'); + if (!existsSync(localNode) && existsSync(mcodeBundledNode)) { + try { + symlinkSync(mcodeBundledNode, localNode); + } catch { + // Non-fatal + } + } + + launcherPath = path.join(localBin, 'repowiki'); + const launcherScript = [ + '#!/bin/sh', + 'set -e', + 'if command -v node >/dev/null 2>&1; then', + ' NODE_BIN="$(command -v node)"', + 'elif [ -x "$HOME/.local/bin/node" ]; then', + ' NODE_BIN="$HOME/.local/bin/node"', + 'elif [ -x "$HOME/.minimax-code/runtime/node/bin/node" ]; then', + ' NODE_BIN="$HOME/.minimax-code/runtime/node/bin/node"', + 'else', + ' echo "repowiki: Node.js (>=22.5) not found" >&2', + ' exit 1', + 'fi', + `exec "$NODE_BIN" "${cliTarget}" "$@"`, + '', + ].join('\n'); + rmSync(launcherPath, { force: true }); + writeFileSync(launcherPath, launcherScript, { mode: 0o755 }); +} + +// Re-enable the plugin so MiniMax Code picks up the new files. The installer puts `mcode` in +// ~/.minimax-code/bin; an npm install (the usual way on Windows) puts it on PATH. +const bundledMcode = path.join(HOME, '.minimax-code', 'bin', isWindows ? 'mcode.cmd' : 'mcode'); +const mcode = existsSync(bundledMcode) ? bundledMcode : 'mcode'; +const runMcode = (...args) => + spawnSync(isWindows ? `"${mcode}" ${args.join(' ')}` : mcode, isWindows ? [] : args, { stdio: 'ignore', shell: isWindows }); +runMcode('plugin', 'disable', 'mcode-repowiki@local'); +const enabled = runMcode('plugin', 'enable', 'mcode-repowiki@local').status === 0; + +const onPath = (process.env.PATH || '') + .split(path.delimiter) + .some((dir) => dir && path.resolve(dir).toLowerCase() === localBin.toLowerCase()); +console.log(`Installed the plugin: ${TARGET_DIR}`); +console.log(enabled ? 'Enabled it in MiniMax Code (mcode-repowiki@local).' : 'MiniMax Code not found: run `mcode plugin enable mcode-repowiki@local` yourself.'); +console.log(`Installed the repowiki command: ${launcherPath}`); +if (!onPath) console.log(`${localBin} is not on your PATH; add it, or run \`node "${cliTarget}"\` instead.`); diff --git a/plugins/Jialei-03/mcode-repowiki/scripts/validate-plugin.mjs b/plugins/Jialei-03/mcode-repowiki/scripts/validate-plugin.mjs new file mode 100644 index 00000000..981da324 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/scripts/validate-plugin.mjs @@ -0,0 +1,115 @@ +import { readdir, readFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const PLUGIN_SCHEMA = 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json'; +const MCP_SCHEMA = 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json'; +const PLUGIN_NAME = /^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u; +const SKILL_NAME = /^(?!.*--)[a-z0-9]+(?:-[a-z0-9]+)*$/u; +const PLUGIN_FIELDS = new Set([ + '$schema', + 'name', + 'version', + 'description', + 'author', + 'homepage', + 'repository', + 'license', + 'keywords', + 'extensions', +]); + +function assert(cond, msg) { + if (!cond) throw new Error(msg); +} + +function isRecord(v) { + return v !== null && typeof v === 'object' && !Array.isArray(v); +} + +async function assertNoSymlinks(dir) { + for (const entry of await readdir(dir, { withFileTypes: true })) { + if (entry.name === '.git' || entry.name === '.repowiki') continue; + const full = path.join(dir, entry.name); + assert(!entry.isSymbolicLink(), `${full}: symlinks are forbidden`); + if (entry.isDirectory()) await assertNoSymlinks(full); + } +} + +async function listContractTextFiles(dir) { + const out = []; + for (const entry of await readdir(dir, { withFileTypes: true })) { + if (entry.name === '.git' || entry.name === '.repowiki') continue; + const full = path.join(dir, entry.name); + if (entry.isDirectory()) out.push(...(await listContractTextFiles(full))); + else if (entry.isFile() && (entry.name.endsWith('.md') || ['plugin.json', 'mcp.json'].includes(entry.name))) { + out.push(full); + } + } + return out; +} + +export async function validateRepoWikiPlugin(rootDir) { + await assertNoSymlinks(rootDir); + + const manifestPath = path.join(rootDir, 'plugin.json'); + const rawManifest = await readFile(manifestPath, 'utf8'); + assert(!rawManifest.startsWith('\uFEFF'), 'plugin.json: BOM not allowed'); + const manifest = JSON.parse(rawManifest); + assert(isRecord(manifest), 'plugin.json: must be object'); + assert(manifest.$schema === PLUGIN_SCHEMA, 'plugin.json: invalid $schema'); + assert(PLUGIN_NAME.test(manifest.name), 'plugin.json: invalid name'); + assert(manifest.name === path.basename(rootDir), `plugin.json: name "${manifest.name}" must match directory "${path.basename(rootDir)}"`); + for (const k of Object.keys(manifest)) { + assert(PLUGIN_FIELDS.has(k), `plugin.json: unknown field ${k}`); + } + assert(typeof manifest.license === 'string' && manifest.license.length > 0, 'plugin.json: license required'); + + const mcpPath = path.join(rootDir, 'mcp.json'); + const mcp = JSON.parse(await readFile(mcpPath, 'utf8')); + assert(mcp.$schema === MCP_SCHEMA, 'mcp.json: invalid $schema'); + assert(isRecord(mcp.mcpServers) && Object.keys(mcp.mcpServers).length > 0, 'mcp.json: missing mcpServers'); + for (const [srvName, srv] of Object.entries(mcp.mcpServers)) { + assert(PLUGIN_NAME.test(srvName), `mcp.json: invalid server name ${srvName}`); + assert(srv.type === 'stdio', 'mcp.json: expected stdio'); + assert(srv.command === 'node', 'mcp.json: expected bare command "node"'); + assert(Array.isArray(srv.args) && srv.args[0] === './server/main.mjs', 'mcp.json: invalid args'); + assert(srv.cwd === '${PLUGIN_ROOT}', 'mcp.json: cwd must be ${PLUGIN_ROOT}'); + } + + const v04Path = path.join(rootDir, '.claude-plugin', 'plugin.json'); + const v04 = JSON.parse(await readFile(v04Path, 'utf8')); + assert(v04.name === manifest.name, '.claude-plugin/plugin.json: name mismatch'); + assert(v04.version === manifest.version, '.claude-plugin/plugin.json: version mismatch'); + assert(Array.isArray(v04.skills) && v04.skills.includes('./skills/mcode-repowiki/SKILL.md'), '.claude-plugin/plugin.json: skills missing'); + + const skillPath = path.join(rootDir, 'skills', 'mcode-repowiki', 'SKILL.md'); + const skillText = (await readFile(skillPath, 'utf8')).replace(/\r\n/gu, '\n'); + assert(skillText.startsWith('---\n'), 'SKILL.md: missing frontmatter'); + const fmEnd = skillText.indexOf('\n---\n', 4); + assert(fmEnd > 4, 'SKILL.md: unclosed frontmatter'); + const fm = skillText.slice(4, fmEnd); + const sName = fm.match(/^name:\s*([^\n]+)$/mu)?.[1]?.trim(); + const sDesc = fm.match(/^description:\s*([^\n]+)$/mu)?.[1]?.trim(); + assert(sName === 'mcode-repowiki' && SKILL_NAME.test(sName), 'SKILL.md: invalid name'); + assert(Boolean(sDesc) && sDesc.length <= 1024, 'SKILL.md: invalid description'); + + for (const req of ['README.md', 'LICENSE']) { + const c = await readFile(path.join(rootDir, req), 'utf8'); + assert(c.trim().length > 0, `${req}: must not be empty`); + } + const forbiddenMarker = new RegExp(`\\b${'TO' + 'DO'}\\b`, 'u'); + for (const f of await listContractTextFiles(rootDir)) { + const c = await readFile(f, 'utf8'); + assert(!forbiddenMarker.test(c), `${f}: contains unfinished placeholder marker`); + } + + return { name: manifest.name, version: manifest.version, mcpServers: Object.keys(mcp.mcpServers), skill: sName }; +} + +const isMain = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url)); +if (isMain) { + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + const res = await validateRepoWikiPlugin(root); + console.log('PASS Official MiniMax-Code-Plugins validation:', JSON.stringify(res)); +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/auto-init.mjs b/plugins/Jialei-03/mcode-repowiki/server/auto-init.mjs new file mode 100644 index 00000000..776f0236 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/auto-init.mjs @@ -0,0 +1,262 @@ +import path from 'node:path'; + +import { listMarkdownWikiPages, writeVerifiedWikiPage } from './sync.mjs'; + +/** + * Deterministically scaffold a grounded multi-chapter starter Repo Wiki using pure AST + + * Personalized PageRank + Tarjan SCC + Martin Coupling analysis (zero LLM API required). + * Makes `repowiki init` and `repowiki serve` work out-of-the-box in <1s on any repository, + * while remaining 100% compatible with AI agent prose enrichment via `wiki_write_page`. + */ +export function generateStarterWiki(repoRoot, wikiDir, analyzed, options = {}) { + const { index, arch, ppr, blueprint } = analyzed; + const existing = listMarkdownWikiPages(wikiDir); + if (existing.length > 0 && !options.force) { + return { skipped: true, pageCount: existing.length, pages: existing }; + } + + const written = []; + const langs = Object.entries(blueprint.languageCounts) + .sort((a, b) => b[1] - a[1]) + .map(([l, c]) => `${l} (${c})`) + .join(', '); + + // 1. Root Overview (README.md) + const moduleRows = blueprint.modules + .map( + (m) => + `| \`${m.key}\` | ${m.layerKind} | ${m.fileCount} | ${m.pageRankPct}% | [${m.title}](${m.docPath}) |`, + ) + .join('\n'); + + const topHubBullets = arch.topHubs + .slice(0, 5) + .map( + (h) => + `- **\`${path.posix.basename(h.relPath)}\`** ([${path.posix.basename(h.relPath)}:L1-L40](${h.relPath}#L1-L40)) — ${h.role} · 被依赖 ${h.fanIn} 次 · 依赖 ${h.fanOut} 处 · PageRank ${(h.rank * 100).toFixed(2)}%`, + ) + .join('\n'); + + const readmeMd = `# 项目概览 + +> [!IMPORTANT] +> **自动化静态拓扑基线**:本知识库由 \`repowiki\` 基于 AST 符号提取、跨文件导入解析、Personalized PageRank 与 Tarjan 强连通分量静态生成,共覆盖 **${index.stats.fileCount} 个源码文件**、**${index.stats.totalLines.toLocaleString()} 行代码** 与 **${index.stats.totalSymbols.toLocaleString()} 个导出符号**。所有源码引用均绑定真实行号并支持实时联动。 + +## 工程技术栈与规模概览 + +- **主要语言分布**:${langs || 'Unknown'} +- **识别技术栈**:${blueprint.workspaceMeta.primaryTechStack.join(' · ') || '通用源码工程'} +- **工作区子包数**:${blueprint.workspaceMeta.packages.length} 个 + +## 全局分层拓扑图 + +\`\`\`mermaid +${blueprint.architectureMermaid} +\`\`\` + +## 核心模块地图 + +| 模块路径 | 架构角色 | 文件数 | 核心权重 | 深度章节入口 | +| :--- | :--- | ---: | ---: | :--- | +${moduleRows} + +## 全仓高权重枢纽文件(Top PageRank Hubs) + +${topHubBullets || '- 暂无跨文件依赖枢纽'} +`; + + written.push( + writeVerifiedWikiPage( + { + repoRoot, + wikiDir, + pagePath: 'README.md', + title: '项目概览', + content: readmeMd, + }, + index, + ), + ); + + // 2. System Overview (01-architecture/01-system-overview.md) + const entryBullets = arch.entrypoints + .slice(0, 6) + .map( + (e) => + `- [${path.posix.basename(e.relPath)}:L1-L35](${e.relPath}#L1-L35) — \`${e.relPath}\`(${e.lineCount} 行,扇出 ${e.fanOut} 个下游文件)`, + ) + .join('\n'); + + const sysMd = `# 整体架构 + +本章节梳理 \`${index.repoName}\` 的宏观模块职责分层、启动入口点以及跨层调用方向。 + +## 分层依赖视图 + +\`\`\`mermaid +${blueprint.architectureMermaid} +\`\`\` + +## 系统启动与交互入口(Entrypoints) + +${entryBullets || '- 未检测到显式 CLI / Server 启动入口文件,仓库以库模块导出为主。'} + +> [!TIP] +> 点击任意源码引用标签可在右侧直接滑出实时源码抽屉,支持对照代码阅读架构说明。 +`; + + written.push( + writeVerifiedWikiPage( + { + repoRoot, + wikiDir, + pagePath: '01-architecture/01-system-overview.md', + title: '整体架构', + content: sysMd, + }, + index, + ), + ); + + // 3. Coupling & Cycles Audit (01-architecture/02-dependencies-and-boundaries.md) + const couplingRows = blueprint.modules + .map( + (m) => + `| \`${m.key}\` | ${m.fanIn} | ${m.fanOut} | **${m.instability.toFixed(2)}** | ${m.layerKind} |`, + ) + .join('\n'); + + const cycleSection = + blueprint.cycles.length === 0 + ? '> [!NOTE]\n> **零循环依赖(Clean DAG)**:经 Tarjan 强连通分量检测,全仓未发现跨文件循环导入环。' + : blueprint.cycles + .slice(0, 6) + .map( + (c, idx) => + `${idx + 1}. **${c.size} 节点强连通环**:${c.witnessCycle.map((p) => `[${path.posix.basename(p)}:L1-L25](${p}#L1-L25)`).join(' → ')}`, + ) + .join('\n'); + + const depMd = `# 模块依赖 + +通过静态导入图计算的马丁耦合度指标(不稳定性 $I = \\frac{C_e}{C_a + C_e}$,$I$ 越接近 $0$ 代表越稳定、越处于底层基座;越接近 $1$ 代表越偏向上层业务编排)如下: + +## 模块耦合度矩阵 + +| 模块 | 传入依赖 ($C_a$) | 传出依赖 ($C_e$) | 不稳定性 ($I$) | 层级判定 | +| :--- | ---: | ---: | ---: | :--- | +${couplingRows} + +## 循环依赖审计(Tarjan SCC) + +${cycleSection} +`; + + written.push( + writeVerifiedWikiPage( + { + repoRoot, + wikiDir, + pagePath: '01-architecture/02-dependencies-and-boundaries.md', + title: '模块依赖', + content: depMd, + }, + index, + ), + ); + + // 4. Core Module Pages (02-modules/*) + for (const mod of blueprint.modules) { + const topSet = new Set(mod.topFiles.slice(0, 7)); + const mermaidLines = ['flowchart LR']; + const fIdMap = new Map(); + mod.topFiles.slice(0, 7).forEach((fp, idx) => { + fIdMap.set(fp, `F${idx}`); + mermaidLines.push(` F${idx}["${path.posix.basename(fp)}"]`); + }); + let edgeCnt = 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 tfp = index.files[v].relPath; + if (topSet.has(tfp)) { + mermaidLines.push(` ${fIdMap.get(fp)} --> ${fIdMap.get(tfp)}`); + edgeCnt += 1; + } + } + } + if (edgeCnt === 0 && mod.dependsOnModules.length > 0) { + mod.dependsOnModules.slice(0, 3).forEach((d, idx) => { + const shortDep = d.title.replace(/\s*\([^)]*\)\s*$/u, '').replace(/"/gu, "'"); + mermaidLines.push(` F0 --> EXT${idx}["${shortDep}"]`); + }); + } + + const symSections = mod.topFiles + .slice(0, 8) + .map((fp) => { + const fIdx = index.pathToIdx.get(fp); + if (fIdx === undefined) return ''; + const pf = index.parsedFiles[fIdx]; + const fanIn = index.reverseImportAdj[fIdx].size; + const fanOut = index.importAdj[fIdx].size; + const syms = pf.symbols + .slice(0, 8) + .map( + (s) => + ` - \`${s.signature.replace(/`/gu, "'").slice(0, 110)}\` ([${path.posix.basename(fp)}:L${s.lineStart}-L${s.lineEnd}](${fp}#L${s.lineStart}-L${s.lineEnd}))`, + ) + .join('\n'); + return `- **\`${fp}\`**(${pf.lineCount} 行 · 被引 ${fanIn} / 引用 ${fanOut})\n${syms || ` - [${path.posix.basename(fp)}:L1-L${Math.min(40, pf.lineCount)}](${fp}#L1-L${Math.min(40, pf.lineCount)})`}`; + }) + .filter(Boolean) + .join('\n'); + + const upDeps = + mod.dependedByModules.length > 0 + ? mod.dependedByModules.map((d) => `\`${d.title}\` (${d.edges} 处引用)`).join('、') + : '顶层模块(无上层模块直接依赖)'; + const downDeps = + mod.dependsOnModules.length > 0 + ? mod.dependsOnModules.map((d) => `\`${d.title}\` (${d.edges} 处引用)`).join('、') + : '零内部模块依赖(纯净底层基座)'; + + const modMd = `# ${mod.title} + +- **模块路径**:\`${mod.key}\` +- **架构定位**:${mod.layerKind}(文件数 ${mod.fileCount} · 代码量 ${mod.lineCount.toLocaleString()} 行 · 不稳定性 $I = ${mod.instability.toFixed(2)}$) +- **上游调用方**:${upDeps} +- **下游依赖项**:${downDeps} + +## 模块内部文件依赖拓扑 + +\`\`\`mermaid +${mermaidLines.join('\n')} +\`\`\` + +## 核心文件与导出符号清单 + +${symSections} +`; + + written.push( + writeVerifiedWikiPage( + { + repoRoot, + wikiDir, + pagePath: mod.docPath, + title: mod.title, + content: modMd, + }, + index, + ), + ); + } + + return { + skipped: false, + pageCount: written.length, + pages: written.map((w) => w.pagePath), + }; +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/cache.mjs b/plugins/Jialei-03/mcode-repowiki/server/cache.mjs new file mode 100644 index 00000000..18c60a22 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/cache.mjs @@ -0,0 +1,117 @@ +import { createHash } from 'node:crypto'; +import { mkdirSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const PARSER_SCHEMA_VERSION = 'repomap-ast-v3'; + +let sqliteModulePromise = null; +async function loadNodeSqlite() { + if (!sqliteModulePromise) { + sqliteModulePromise = import('node:sqlite').catch(() => null); + } + return sqliteModulePromise; +} + +export class ParseCache { + constructor(options = {}) { + this.memory = new Map(); + this.db = null; + this.stmtGet = null; + this.stmtPut = null; + this.enabled = options.enabled !== false; + this.cacheDir = options.cacheDir || process.env.PLUGIN_DATA || path.join(os.tmpdir(), 'mcode-repomap-cache'); + } + + async init() { + if (!this.enabled || this.db) return; + const sqlite = await loadNodeSqlite(); + if (!sqlite?.DatabaseSync) return; + try { + mkdirSync(this.cacheDir, { recursive: true }); + const dbPath = path.join(this.cacheDir, 'ast-index-v1.sqlite'); + const db = new sqlite.DatabaseSync(dbPath); + db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + CREATE TABLE IF NOT EXISTS file_ast_cache ( + cache_key TEXT PRIMARY KEY, + mtime_ms INTEGER NOT NULL, + size INTEGER NOT NULL, + payload_json TEXT NOT NULL, + updated_at INTEGER NOT NULL + ); + `); + this.db = db; + this.stmtGet = db.prepare( + 'SELECT mtime_ms, size, payload_json FROM file_ast_cache WHERE cache_key = ?', + ); + this.stmtPut = db.prepare(` + INSERT INTO file_ast_cache (cache_key, mtime_ms, size, payload_json, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(cache_key) DO UPDATE SET + mtime_ms = excluded.mtime_ms, + size = excluded.size, + payload_json = excluded.payload_json, + updated_at = excluded.updated_at + `); + } catch { + this.db = null; + } + } + + makeKey(repoRoot, relPath) { + const repoHash = createHash('sha1').update(repoRoot).digest('hex').slice(0, 12); + return `${PARSER_SCHEMA_VERSION}:${repoHash}:${relPath}`; + } + + get(repoRoot, fileMeta) { + const key = this.makeKey(repoRoot, fileMeta.relPath); + const mem = this.memory.get(key); + if (mem && mem.mtimeMs === fileMeta.mtimeMs && mem.size === fileMeta.size) { + return mem.parsed; + } + if (this.stmtGet) { + try { + const row = this.stmtGet.get(key); + if (row && row.mtime_ms === fileMeta.mtimeMs && row.size === fileMeta.size) { + const parsed = JSON.parse(row.payload_json); + this.memory.set(key, { mtimeMs: fileMeta.mtimeMs, size: fileMeta.size, parsed }); + return parsed; + } + } catch { + // Fallback cleanly on cache corruption + } + } + return null; + } + + set(repoRoot, fileMeta, parsed) { + const key = this.makeKey(repoRoot, fileMeta.relPath); + this.memory.set(key, { mtimeMs: fileMeta.mtimeMs, size: fileMeta.size, parsed }); + if (this.stmtPut) { + try { + this.stmtPut.run( + key, + fileMeta.mtimeMs, + fileMeta.size, + JSON.stringify(parsed), + Date.now(), + ); + } catch { + // Ignore SQLite write contention + } + } + } + + close() { + if (this.db) { + try { + this.db.close(); + } catch { + // Ignore close error + } + this.db = null; + } + } +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/cli.mjs b/plugins/Jialei-03/mcode-repowiki/server/cli.mjs new file mode 100755 index 00000000..e5d61952 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/cli.mjs @@ -0,0 +1,316 @@ +#!/usr/bin/env node +import { execFile } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { generateStarterWiki } from './auto-init.mjs'; +import { ParseCache } from './cache.mjs'; +import { + analyzeArchitectureMetrics, + buildRepositoryIndex, + computePersonalizedPageRank, +} from './graph.mjs'; +import { startLiveWikiServer } from './live-server.mjs'; +import { executeTool, startStdioServer } from './main.mjs'; +import { createWikiBlueprint, DEFAULT_MAX_MODULES } from './planner.mjs'; +import { compileInteractiveWikiSite } from './site-builder.mjs'; +import { + acceptWikiPages, + ensureGitExclude, + inspectAndQueryWiki, + installPostCommitHook, + removePostCommitHook, + resolveWikiDir, + syncWikiAstDeterministic, +} from './sync.mjs'; + +const CLI_VERSION = '0.6.0'; + +function parseCliArgs(argv) { + const positionals = []; + const flags = {}; + for (let i = 0; i < argv.length; i += 1) { + const tok = argv[i]; + if (tok === '-h' || tok === '--help') { + flags.help = true; + } else if (tok === '-v' || tok === '--version') { + flags.version = true; + } else if (tok.startsWith('--')) { + const eq = tok.indexOf('='); + if (eq > 0) { + flags[tok.slice(2, eq)] = tok.slice(eq + 1); + } else { + const key = tok.slice(2); + const next = argv[i + 1]; + if (next && !next.startsWith('-')) { + flags[key] = next; + i += 1; + } else { + flags[key] = true; + } + } + } else if (tok === '-p' && argv[i + 1]) { + flags.port = argv[++i]; + } else if (tok === '-w' && argv[i + 1]) { + flags.wiki = argv[++i]; + } else { + positionals.push(tok); + } + } + return { positionals, flags }; +} + +function printHelp() { + process.stdout.write(`repowiki v${CLI_VERSION} — Real-Time Repository Wiki & Fast Code Router + +Everyday Commands: + repowiki [repo_path] [--port 4321] [--open] + Start the live Wiki server (auto-initializes docs, keeps git status clean, enables 0-token post-commit sync). + + repowiki init [repo_path] [--force] [--no-hook] + Generate grounded architecture Wiki + blast-radius index (<1s), hide .repowiki/ from git status, and install post-commit sync. + + repowiki locate [repo_path] "" + Jump directly to verified [file:L-L] code slices + downstream importers (blast radius). + +Advanced: + repowiki sync [repo_path] Fix line numbers after code moved (0 tokens), then list chapters whose cited code changed. + repowiki build [repo_path] Recompile .repowiki/index.html + impact.json. + repowiki status [repo_path] [--json] Which chapters cite code that changed, and a prompt to update them. + repowiki status [repo_path] --reviewed + Mark chapters as checked against the current code. + repowiki hook [repo] Manage the 0-token post-commit auto-sync hook. + repowiki mcp Run MCP stdio server (set REPOWIKI_MCP_MODE=router for minimal 2-tool mode). +`); +} + +/** Freshness report for a person at the terminal, ending with a prompt to paste into MiniMax Code. */ +function formatFreshnessForPeople(status, repoRoot) { + if (!status.exists) return `${status.message}\n`; + const out = []; + const stale = status.stalePages || []; + const moved = status.linesNeedingSync || []; + out.push(`Wiki 状态:${status.freshPages.length}/${status.totalPages} 篇与它引用的代码一致。`); + if (moved.length > 0) { + const n = moved.reduce((a, m) => a + m.citations.length, 0); + out.push(`- ${n} 处引用只是行号变了:运行 \`repowiki sync ${repoRoot}\` 即可修正(不花 Token)。`); + } + if (stale.length === 0) { + out.push(moved.length ? '' : '- 自章节写成以来,被引用的代码都没有变。', ''); + return out.join('\n'); + } + out.push(`- ${stale.length} 篇引用的代码已经改了,文字说明可能过时:`); + for (const sp of stale) { + out.push(` · ${sp.page}`); + for (const c of (sp.changedCitations || []).slice(0, 5)) out.push(` 代码已改 ${c.symbol ? `${c.symbol} ` : ''}${c.file}:${c.lines}`); + for (const c of (sp.brokenCitations || []).slice(0, 5)) out.push(` ${c.reason === 'file-missing' ? '文件已删' : '行号失效'} ${c.file}:${c.lines}`); + } + out.push( + '', + '更新方法(二选一):', + '1. 让 MiniMax Code 更新,把下面这句话发给它:', + ` 用 mcode-repowiki 更新 ${repoRoot} 里过期的 Wiki 章节:先 wiki_plan sync,再按 wiki_plan 列出的变更逐条核对、只改过时的段落,用 wiki_write_page 保存。`, + `2. 自己看过、确认文字仍然正确:repowiki status ${repoRoot} --reviewed <章节路径|all>`, + '', + ); + return out.join('\n'); +} + +function maybeOpenBrowser(url) { + const cmd = + process.platform === 'darwin' + ? 'open' + : process.platform === 'win32' + ? 'cmd' + : 'xdg-open'; + // `start` takes its first quoted argument as a window title, so pass an empty one. + const args = process.platform === 'win32' ? ['/c', 'start', '""', url.replace(/&/gu, '^&')] : [url]; + execFile(cmd, args, () => {}); +} + +async function main() { + const { positionals, flags } = parseCliArgs(process.argv.slice(2)); + if (flags.version) { + process.stdout.write(`${CLI_VERSION}\n`); + return; + } + const KNOWN_CMDS = new Set(['serve', 'init', 'build', 'plan', 'sync', 'locate', 'status', 'hook', 'mcp', 'help']); + const firstPos = positionals[0]; + const isBareRepoArg = Boolean(firstPos && !KNOWN_CMDS.has(firstPos)); + const cmd = flags.help ? 'help' : isBareRepoArg ? 'serve' : firstPos || 'serve'; + const targetPos = isBareRepoArg ? firstPos : positionals[1]; + if (flags.help || cmd === 'help') { + printHelp(); + return; + } + + if (cmd === 'mcp') { + startStdioServer(); + return; + } + + if (cmd === 'hook') { + const sub = positionals[1] === 'remove' ? 'remove' : 'install'; + const targetArg = positionals[1] === 'install' || positionals[1] === 'remove' ? positionals[2] : positionals[1]; + const targetRepo = path.resolve(targetArg || process.cwd()); + const selfCli = path.resolve(fileURLToPath(import.meta.url)); + if (sub === 'remove') { + const r = removePostCommitHook(targetRepo); + if (!r.removed) throw new Error(`Not a Git repository: ${targetRepo}`); + process.stdout.write(`Removed repowiki post-commit hook from ${r.hookFile}\n`); + return; + } + const r = installPostCommitHook(targetRepo, selfCli); + if (!r.installed) throw new Error(`Not a Git repository: ${targetRepo}`); + ensureGitExclude(targetRepo, resolveWikiDir(targetRepo, flags.wiki)); + process.stdout.write(`Installed automatic 0-token post-commit AST sync hook -> ${r.hookFile}\n`); + return; + } + + const repoRoot = path.resolve(targetPos || process.cwd()); + const wikiDir = resolveWikiDir(repoRoot, flags.wiki); + const selfCli = path.resolve(fileURLToPath(import.meta.url)); + + if (cmd === 'serve') { + const port = flags.port ? Number.parseInt(String(flags.port), 10) : 4321; + const srv = await startLiveWikiServer({ + repoRoot, + wikiDir, + port, + host: String(flags.host || '127.0.0.1'), + autoInit: true, + writeDiskHtml: true, + }); + const ex = ensureGitExclude(repoRoot, wikiDir); + const hk = flags['no-hook'] ? { installed: false } : installPostCommitHook(repoRoot, selfCli); + const snap = srv.getSnapshot(); + process.stdout.write( + [ + `RepoWiki v${CLI_VERSION} — Real-Time Engine Running`, + ` Live URL : ${srv.url}`, + ` Repository : ${srv.repoRoot} (${snap.stats.fileCount} files, ${snap.stats.totalSymbols} AST symbols)`, + ` Wiki Dir : ${srv.wikiDir} (${snap.pages.length} chapters)`, + ` Git Hygiene: ${ex.excluded ? 'Clean (.git/info/exclude)' : 'Non-git / external dir'} · Auto-Sync: ${hk.installed ? 'ON (post-commit, 0 tokens)' : 'OFF'}`, + ` Watching : Source files + Markdown chapters via fs.watch & SSE`, + `Press Ctrl+C to stop.\n`, + ].join('\n'), + ); + if (flags.open) maybeOpenBrowser(srv.url); + + const shutdown = async () => { + await srv.close(); + process.exit(0); + }; + process.on('SIGINT', shutdown); + process.on('SIGTERM', shutdown); + return; + } + + const cache = new ParseCache(); + try { + if (cmd === 'init') { + const t0 = Date.now(); + const index = await buildRepositoryIndex(repoRoot, { includeTests: true }, cache); + const ppr = computePersonalizedPageRank(index); + const arch = analyzeArchitectureMetrics(index, ppr.ranks); + const blueprint = createWikiBlueprint(index, arch, ppr, { maxModules: DEFAULT_MAX_MODULES }); + index.stats.elapsedMs = Date.now() - t0; + + const initRes = generateStarterWiki( + repoRoot, + wikiDir, + { index, ppr, arch, blueprint }, + { force: Boolean(flags.force) }, + ); + const built = compileInteractiveWikiSite(index, arch, ppr, wikiDir); + const ex = ensureGitExclude(repoRoot, wikiDir); + const hk = flags['no-hook'] ? { installed: false } : installPostCommitHook(repoRoot, selfCli); + process.stdout.write( + [ + `Initialized RepoWiki (${built.pageCount} chapters, ${initRes.skipped ? 'reused existing' : 'generated fresh'}) -> ${built.htmlPath}`, + ` Git Hygiene: ${ex.excluded ? 'Clean (.git/info/exclude)' : 'N/A'} · Auto-Sync: ${hk.installed ? 'ON (post-commit, 0 tokens)' : 'OFF'}`, + ].join('\n') + '\n', + ); + return; + } + + if (cmd === 'build') { + const out = await executeTool('wiki_build_site', { repo_path: repoRoot, wiki_dir: wikiDir }); + process.stdout.write(out); + return; + } + + if (cmd === 'plan') { + const maxMods = flags['max-modules'] ? Number.parseInt(String(flags['max-modules']), 10) : DEFAULT_MAX_MODULES; + const out = await executeTool('wiki_plan', { + repo_path: repoRoot, + wiki_dir: wikiDir, + max_modules: maxMods, + }); + process.stdout.write(out); + return; + } + + if (cmd === 'sync') { + const res = syncWikiAstDeterministic(repoRoot, wikiDir); + process.stdout.write( + `Synced RepoWiki AST delta in ${res.elapsedMs}ms (${res.syncedFiles.length} files, ${res.reanchoredCitations} shifted citations healed, 0 LLM tokens).\n`, + ); + if (!flags.quiet) { + const index = await buildRepositoryIndex(repoRoot, { includeTests: true }, cache); + process.stdout.write(formatFreshnessForPeople(inspectAndQueryWiki(repoRoot, wikiDir, index, ''), repoRoot)); + } + return; + } + + if (cmd === 'locate') { + const q = positionals.slice(2).join(' ') || String(flags.query || ''); + const out = await executeTool('wiki_locate', { + repo_path: repoRoot, + wiki_dir: flags.wiki ? wikiDir : undefined, + query: q, + }); + process.stdout.write(out); + return; + } + + if (cmd === 'status') { + if (flags.reviewed) { + const index = await buildRepositoryIndex(repoRoot, { includeTests: true }, cache); + const which = String(flags.reviewed); + const accepted = acceptWikiPages(repoRoot, wikiDir, index, which === 'all' || which === 'true' ? null : which.split(',')); + process.stdout.write(`已标记为“已核对” ${accepted.length} 篇:${accepted.join('、') || '无(检查章节路径)'}\n`); + process.stdout.write(formatFreshnessForPeople(inspectAndQueryWiki(repoRoot, wikiDir, index, ''), repoRoot)); + return; + } + if (!flags.json && !flags.query) { + const index = await buildRepositoryIndex(repoRoot, { includeTests: true }, cache); + process.stdout.write(formatFreshnessForPeople(inspectAndQueryWiki(repoRoot, wikiDir, index, ''), repoRoot)); + return; + } + if (flags.json) { + const index = await buildRepositoryIndex(repoRoot, { includeTests: true }, cache); + const st = inspectAndQueryWiki(repoRoot, wikiDir, index, String(flags.query || '')); + process.stdout.write(`${JSON.stringify(st, null, 2)}\n`); + } else { + const out = await executeTool('wiki_status', { + repo_path: repoRoot, + wiki_dir: wikiDir, + query: flags.query ? String(flags.query) : undefined, + }); + process.stdout.write(out); + } + return; + } + + process.stderr.write(`Unknown command "${cmd}". Run "repowiki --help" for usage.\n`); + process.exitCode = 1; + } finally { + cache.close(); + } +} + +main().catch((err) => { + process.stderr.write(`repowiki error: ${err instanceof Error ? err.message : String(err)}\n`); + process.exit(1); +}); diff --git a/plugins/Jialei-03/mcode-repowiki/server/describe.mjs b/plugins/Jialei-03/mcode-repowiki/server/describe.mjs new file mode 100644 index 00000000..1a344543 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/describe.mjs @@ -0,0 +1,223 @@ +/** + * One-line descriptions for files and modules ("这个文件是干嘛的"). + * + * Independent of the graph and of any LLM. Sources, highest priority first: + * 1. `.repowiki/descriptions.json` — written by the AI (see SKILL.md) or by hand + * 2. the subtitle of a module chapter ("pi-schema — 零开销 JSON Schema 类型构建器") + * 3. the file's own leading doc comment / docstring + * 4. the module's package manifest description (package.json / Cargo.toml / pyproject.toml) + * Anything without a real source gets no description rather than a made-up one. + */ +import { existsSync, readFileSync, openSync, readSync, closeSync } from 'node:fs'; +import path from 'node:path'; + +export const DESCRIPTIONS_FILE = 'descriptions.json'; +const MAX_WIDTH = 110; + +/** Read `.repowiki/descriptions.json` → { files: {path: text}, modules: {group: text} }. */ +export function loadDescriptionOverrides(wikiDir) { + const out = { files: {}, modules: {} }; + const p = path.join(wikiDir, DESCRIPTIONS_FILE); + if (!existsSync(p)) return out; + try { + const raw = JSON.parse(readFileSync(p, 'utf8')); + for (const key of ['files', 'modules']) { + const src = raw && typeof raw[key] === 'object' ? raw[key] : {}; + for (const [k, v] of Object.entries(src)) { + const text = clampSentence(String(v ?? '')); + if (text) out[key][k.replace(/\\/gu, '/')] = text; + } + } + } catch { + // A half-written or invalid file must never break the build. + } + return out; +} + +/** Module group for a repo-relative path; must match the graph's grouping. */ +export function moduleGroupOf(relPath) { + const parts = 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'; +} + +/** + * @param {string} repoRoot + * @param {string} wikiDir + * @param {string[]} relPaths files that need a description + * @param {Array<{title: string, referencedFiles?: string[], group?: string}>} pages wiki pages + */ +export function buildDescriptions(repoRoot, wikiDir, relPaths, pages = []) { + const overrides = loadDescriptionOverrides(wikiDir); + const files = {}; + for (const rel of new Set(relPaths)) { + const text = overrides.files[rel] || extractLeadingComment(path.join(repoRoot, rel)); + if (text) files[rel] = text; + } + + const modules = {}; + const groups = new Set(relPaths.map(moduleGroupOf)); + for (const g of Object.keys(overrides.modules)) groups.add(g); + const fromPages = moduleSubtitlesFromPages(pages); + for (const g of groups) { + const text = overrides.modules[g] || fromPages.get(g) || manifestDescription(repoRoot, g); + if (text) modules[g] = text; + } + return { files, modules }; +} + +/** "pi-schema — 零开销 JSON Schema 类型构建器" → module of most cited files → subtitle. */ +function moduleSubtitlesFromPages(pages) { + const out = new Map(); + for (const p of pages) { + const title = String(p.title || '').replace(/`/gu, ''); + const m = title.match(/\s[—–]\s(.+)$/u); + if (!m || !Array.isArray(p.referencedFiles) || p.referencedFiles.length === 0) continue; + const counts = new Map(); + for (const f of p.referencedFiles) counts.set(moduleGroupOf(f), (counts.get(moduleGroupOf(f)) || 0) + 1); + const [best, n] = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]; + // Only trust it when the chapter is clearly about one module (overview pages cite everything). + if (n / p.referencedFiles.length >= 0.6 && !out.has(best)) { + const text = clampSentence(m[1].replace(/[((][^()()]*[))]\s*$/u, '')); + if (text) out.set(best, text); + } + } + return out; +} + +function manifestDescription(repoRoot, group) { + if (group === 'root') return ''; + const dir = path.join(repoRoot, group); + try { + const pkg = path.join(dir, 'package.json'); + if (existsSync(pkg)) { + const d = JSON.parse(readFileSync(pkg, 'utf8')).description; + if (d) return clampSentence(String(d)); + } + for (const f of ['Cargo.toml', 'pyproject.toml']) { + const p = path.join(dir, f); + if (!existsSync(p)) continue; + const m = readFileSync(p, 'utf8').match(/^\s*description\s*=\s*"([^"]+)"/mu); + if (m) return clampSentence(m[1]); + } + } catch { + // ignore unreadable manifests + } + return ''; +} + +function readHead(absPath, bytes = 4096) { + let fd; + try { + fd = openSync(absPath, 'r'); + const buf = Buffer.alloc(bytes); + const n = readSync(fd, buf, 0, bytes, 0); + return buf.subarray(0, n).toString('utf8'); + } catch { + return ''; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + +const NOISE = + /^(copyright|\(c\)|license|licensed|spdx|eslint|prettier|@ts-|tslint|jshint|biome|#!|@flow|@format|@jsx|@vitest|@jest|deno-|noinspection|istanbul|c8 |type: ?ignore|pylint|noqa|mypy|-\*-|go:build|\+build|auto-?generated|generated by|do not edit)/iu; + +/** First sentence of the file's leading comment / docstring, or '' when there is none. */ +export function extractLeadingComment(absPath) { + const head = readHead(absPath); + if (!head) return ''; + const lines = head.split(/\r?\n/u); + let i = 0; + const skipBlank = () => { + while (i < lines.length && lines[i].trim() === '') i += 1; + }; + skipBlank(); + if (lines[i]?.startsWith('#!')) i += 1; + + // Walk past license headers and tool directives until the first real comment block. + for (let guard = 0; guard < 6 && i < lines.length; guard += 1) { + skipBlank(); + const line = lines[i]?.trim() ?? ''; + let block = []; + if (line.startsWith('/*')) { + const start = i; + while (i < lines.length && !lines[i].includes('*/')) i += 1; + block = lines.slice(start, i + 1); + i += 1; + block = block.map((l) => l.replace(/^\s*\/\*+!?|\*+\/\s*$|^\s*\*\s?/gu, '').trim()); + } else if (/^(\/\/[/!]?|#(?=\s|$))/u.test(line)) { + while (i < lines.length && /^\s*(\/\/[/!]?|#(?=\s|$))/u.test(lines[i])) { + block.push(lines[i].replace(/^\s*(\/\/[/!]?|#)\s?/u, '').trim()); + i += 1; + } + } else if (/^[rRbBuU]?("""|''')/u.test(line)) { + const q = line.match(/("""|''')/u)[1]; + const rest = line.slice(line.indexOf(q) + 3); + if (rest.includes(q)) { + block = [rest.slice(0, rest.indexOf(q))]; + i += 1; + } else { + block = [rest]; + i += 1; + while (i < lines.length && !lines[i].includes(q)) { + block.push(lines[i].trim()); + i += 1; + } + if (i < lines.length) block.push(lines[i].slice(0, lines[i].indexOf(q)).trim()); + i += 1; + } + } else if (/^(package|import|from|use|export|const|let|var|function|class|module|namespace|"use |'use )/u.test(line)) { + // Go: "// Package foo ..." sits right above `package`; already handled as a // block. + return ''; + } else { + return ''; + } + const text = cleanCommentBlock(block); + if (text) return text; + } + return ''; +} + +function cleanCommentBlock(block) { + const kept = []; + for (const raw of block) { + const l = raw.trim(); + if (!l) { + if (kept.length) break; // first paragraph only + continue; + } + if (NOISE.test(l)) return ''; // license / directive block: not a description + if (/^[@=\-*#_~─━]{2,}|^@\w+/u.test(l)) { + if (kept.length) break; // JSDoc tags end the summary + continue; + } + kept.push(l.replace(/^[─━=\-\s]+|[─━=\-\s]+$/gu, '')); + } + return clampSentence(kept.join(' ')); +} + +/** Keep only the first sentence, strip markdown, cap the length. */ +export function clampSentence(s) { + let t = String(s || '') + .replace(/`([^`]+)`/gu, '$1') + .replace(/\*\*([^*]+)\*\*/gu, '$1') + .replace(/\{@link\s+([^}]+)\}/gu, '$1') + .replace(/\s+/gu, ' ') + .trim(); + const m = t.match(/^(.+?[。!?]|.+?[.!?](?=\s|$))/u); + if (m) t = m[1]; + t = t.replace(/[\s。.,,;;::/\\|-]+$/u, '').trim(); + if (t.length < 4) return ''; + // Cap by visual width: a CJK character is about two Latin letters wide. + let width = 0; + for (let k = 0; k < t.length; k += 1) { + width += /[⺀-￿]/u.test(t[k]) ? 2 : 1; + if (width > MAX_WIDTH) return t.slice(0, k).trimEnd() + '…'; + } + return t; +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/graph.mjs b/plugins/Jialei-03/mcode-repowiki/server/graph.mjs new file mode 100644 index 00000000..8233b914 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/graph.mjs @@ -0,0 +1,853 @@ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +import { discoverWorkspace, normalizeRelPath } from './scanner.mjs'; +import { isNoisySymbolName, parseSourceFile } from './parser.mjs'; +import { createImportResolver } from './resolver.mjs'; + +function splitIdentifierTokens(text) { + if (!text) return []; + return text + .replace(/([a-z0-9])([A-Z])/gu, '$1 $2') + .split(/[^A-Za-z0-9_]+/u) + .flatMap((part) => [part.toLowerCase(), ...part.split('_').map((p) => p.toLowerCase())]) + .filter((t) => t.length >= 2); +} + +/** + * Build full AST symbol index + weighted cross-file dependency graph for a repository. + */ +export async function buildRepositoryIndex(repoRoot, options = {}, cache = null) { + const t0 = performance.now(); + if (cache) await cache.init(); + + const workspace = discoverWorkspace(repoRoot, options); + const files = workspace.codeFiles; + const N = files.length; + + const pathToIdx = new Map(); + for (let i = 0; i < N; i += 1) { + pathToIdx.set(files[i].relPath, i); + } + + // 1. Parse all files (hitting SQLite / memory cache for unchanged files) + let cacheHits = 0; + let totalLines = 0; + let totalSymbols = 0; + const parsedFiles = new Array(N); + + for (let i = 0; i < N; i += 1) { + const f = files[i]; + let parsed = cache ? cache.get(workspace.repoRoot, f) : null; + if (parsed) { + cacheHits += 1; + } else { + let raw = ''; + try { + raw = readFileSync(f.absPath, 'utf8'); + } catch { + raw = ''; + } + parsed = parseSourceFile(raw, f.lang, f.relPath); + if (cache) cache.set(workspace.repoRoot, f, parsed); + } + parsedFiles[i] = parsed; + totalLines += parsed.lineCount ?? 0; + totalSymbols += parsed.symbols?.length ?? 0; + } + + // 2. Build global symbol definition table & document frequencies + const symbolDefs = new Map(); // symbolName -> [{ fileIdx, symIdx, symbol }] + const docFreq = new Map(); // ident -> number of files referencing ident + + for (let i = 0; i < N; i += 1) { + const pf = parsedFiles[i]; + for (let sIdx = 0; sIdx < pf.symbols.length; sIdx += 1) { + const sym = pf.symbols[sIdx]; + let arr = symbolDefs.get(sym.name); + if (!arr) { + arr = []; + symbolDefs.set(sym.name, arr); + } + arr.push({ fileIdx: i, symIdx: sIdx, symbol: sym }); + } + for (const ident of Object.keys(pf.refs)) { + docFreq.set(ident, (docFreq.get(ident) ?? 0) + 1); + } + } + + // 3. Resolve explicit imports & build weighted directed graph + const resolver = createImportResolver(files, workspace.workspaceMeta); + const importAdj = Array.from({ length: N }, () => new Set()); + const reverseImportAdj = Array.from({ length: N }, () => new Set()); + const weightedOut = Array.from({ length: N }, () => new Map()); // u -> Map + + const addEdgeWeight = (u, v, delta, isDirect = false, symName = null) => { + if (u === v || delta <= 0) return; + const row = weightedOut[u]; + let cell = row.get(v); + if (!cell) { + cell = { weight: 0, direct: false, symbols: new Set() }; + row.set(v, cell); + } + cell.weight += delta; + if (isDirect) cell.direct = true; + if (symName && cell.symbols.size < 8) cell.symbols.add(symName); + }; + + for (let u = 0; u < N; u += 1) { + const f = files[u]; + const pf = parsedFiles[u]; + const explicitTargets = new Set(); + + // 3a. Explicit import / include / use edges + for (const imp of pf.imports) { + const resolvedPaths = resolver.resolveImport(f, imp); + for (const targetPath of resolvedPaths) { + const v = pathToIdx.get(targetPath); + if (v === undefined || v === u) continue; + importAdj[u].add(v); + reverseImportAdj[v].add(u); + explicitTargets.add(v); + + let usedImportedSyms = 0; + for (const symName of imp.symbols ?? []) { + if (pf.refs[symName]) { + usedImportedSyms += 1; + addEdgeWeight(u, v, 1.8, true, symName); + } + } + addEdgeWeight(u, v, 3.0 + Math.min(4.5, usedImportedSyms * 0.8), true); + } + } + + // 3b. Aider-style IDF-weighted cross-file symbol reference edges + for (const [ident, count] of Object.entries(pf.refs)) { + if (isNoisySymbolName(ident)) continue; + const defs = symbolDefs.get(ident); + if (!defs || defs.length === 0) continue; + + // Avoid quadratic blowup on ultra-common method names unless explicitly imported + const nonTestDefs = defs.filter((d) => !files[d.fileIdx].isTest); + const activeDefs = nonTestDefs.length > 0 ? nonTestDefs : defs; + if (activeDefs.length > 10) { + // Keep only explicitly imported targets for ambiguous names + for (const d of activeDefs) { + if (explicitTargets.has(d.fileIdx)) { + addEdgeWeight(u, d.fileIdx, 1.5 * Math.sqrt(count), true, ident); + } + } + continue; + } + + const df = docFreq.get(ident) ?? 1; + const idf = Math.log((N + 1) / (df + 1)) + 0.5; + const isSpecific = + ident.length >= 6 && + (/[A-Z]/u.test(ident) || ident.includes('_')); + const specificity = isSpecific ? 1.6 : 0.85; + const baseWeight = (specificity * Math.sqrt(count) * idf) / activeDefs.length; + + for (const d of activeDefs) { + const v = d.fileIdx; + if (v === u) continue; + const targetDiscount = files[v].isTest ? 0.2 : 1.0; + const importBoost = explicitTargets.has(v) ? 2.2 : 1.0; + const exportedBoost = d.symbol.exported ? 1.25 : 0.65; + addEdgeWeight(u, v, baseWeight * targetDiscount * importBoost * exportedBoost, false, ident); + } + } + } + + const elapsedMs = Math.round((performance.now() - t0) * 10) / 10; + + return { + repoRoot: workspace.repoRoot, + repoName: workspace.repoName, + workspaceMeta: workspace.workspaceMeta, + languageCounts: workspace.languageCounts, + files, + parsedFiles, + pathToIdx, + symbolDefs, + docFreq, + importAdj, + reverseImportAdj, + weightedOut, + stats: { + fileCount: N, + totalLines, + totalSymbols, + cacheHits, + elapsedMs, + }, + }; +} + +// ─── Personalized PageRank (Power Iteration + Dangling Redistribution) ────── + +export function computePersonalizedPageRank(index, options = {}) { + const N = index.files.length; + if (N === 0) return { ranks: new Float64Array(0), seedScores: new Float64Array(0), isFocused: false }; + + const alpha = options.alpha ?? 0.85; + const query = (options.query ?? '').trim(); + const focusFiles = (options.focusFiles ?? []).map(normalizeRelPath).filter(Boolean); + const queryLower = query.toLowerCase(); + const queryTokens = splitIdentifierTokens(query); + + const personalization = new Float64Array(N); + const seedScores = new Float64Array(N); + const focusIdxSet = new Set(); + + for (const fp of focusFiles) { + const exact = index.pathToIdx.get(fp); + if (exact !== undefined) { + focusIdxSet.add(exact); + } else { + // Suffix or partial path match + for (let i = 0; i < N; i += 1) { + if (index.files[i].relPath.endsWith(fp) || index.files[i].relPath.includes(fp)) { + focusIdxSet.add(i); + } + } + } + } + + const hasFocus = focusIdxSet.size > 0 || queryTokens.length > 0; + const manifestEntries = new Set(index.workspaceMeta?.entrypoints ?? []); + + // Precompute SCC membership on direct imports to prevent Spider-Trap rank hoarding in isolated cycles + const sccOfNode = new Int32Array(N).fill(-1); + const cycles = detectCircularDependencies(index); + cycles.forEach((cyc, sccIdx) => { + for (const rel of cyc.members) { + const idx = index.pathToIdx.get(rel); + if (idx !== undefined) sccOfNode[idx] = sccIdx; + } + }); + + for (let i = 0; i < N; i += 1) { + const f = index.files[i]; + const pf = index.parsedFiles[i]; + + if (!hasFocus) { + // Cold-start global architecture prior (dampening unreferenced isolated islands) + const sccId = sccOfNode[i]; + let extFanIn = 0; + for (const caller of index.reverseImportAdj[i]) { + if (sccId === -1 || sccOfNode[caller] !== sccId) extFanIn += 1; + } + let prior = f.isTest ? 0.12 : 1.0 + Math.log1p(extFanIn) * 0.65; + if (f.role === 'entrypoint' || manifestEntries.has(f.relPath)) prior = Math.max(prior, 2.4); + else if (f.role === 'core' || f.role === 'api') prior *= 1.15; + if (sccId !== -1 && extFanIn === 0) prior *= 0.35; // Isolated cycle island penalty + personalization[i] = prior; + } else { + let score = f.isTest ? 0.02 : 0.08; // tiny background floor + if (focusIdxSet.has(i)) { + score += 60.0; + seedScores[i] += 60.0; + } + if (queryLower) { + const pathLower = f.relPath.toLowerCase(); + if (pathLower.includes(queryLower)) { + score += 22.0; + seedScores[i] += 22.0; + } + for (const qt of queryTokens) { + if (qt.length >= 3 && pathLower.includes(qt)) { + score += 5.5; + seedScores[i] += 5.5; + } + } + for (const sym of pf.symbols) { + const symLower = sym.name.toLowerCase(); + if (symLower === queryLower) { + score += 32.0; + seedScores[i] += 32.0; + } else if (queryLower.length >= 3 && symLower.includes(queryLower)) { + score += 12.0; + seedScores[i] += 12.0; + } else { + for (const qt of queryTokens) { + if (qt.length >= 3 && symLower.includes(qt)) { + score += 4.0; + seedScores[i] += 4.0; + } + } + } + } + } + personalization[i] = score; + } + } + + // Normalize personalization vector p to sum to 1 + let pSum = 0; + for (let i = 0; i < N; i += 1) pSum += personalization[i]; + if (pSum <= 0) { + for (let i = 0; i < N; i += 1) personalization[i] = 1 / N; + } else { + for (let i = 0; i < N; i += 1) personalization[i] /= pSum; + } + + // Build transition edges: + // In Global Mode: `u imports/calls v` means `u` votes for `v`'s architectural importance (`u -> v`!). + // Intra-SCC cycle edges are dampened (0.25x) + leaked to teleportation to eliminate Spider-Trap rank sinks! + // In Focused Mode: we want BOTH dependencies (`u -> v`) AND callers (`v -> u`, at 0.5x) around seeds! + const adj = Array.from({ length: N }, () => new Map()); + const rawOutTotals = new Float64Array(N); + for (let u = 0; u < N; u += 1) { + for (const [v, cell] of index.weightedOut[u].entries()) { + const sameCycle = sccOfNode[u] !== -1 && sccOfNode[u] === sccOfNode[v]; + const effectiveWeight = !hasFocus && sameCycle ? cell.weight * 0.25 : cell.weight; + rawOutTotals[u] += cell.weight; + adj[u].set(v, (adj[u].get(v) ?? 0) + effectiveWeight); + if (hasFocus) { + rawOutTotals[v] += cell.weight * 0.5; + adj[v].set(u, (adj[v].get(u) ?? 0) + cell.weight * 0.5); + } + } + } + + const outTotals = new Float64Array(N); + for (let u = 0; u < N; u += 1) { + let s = 0; + for (const w of adj[u].values()) s += w; + // Using max(s, rawOutTotals[u]) leaks dampened cycle energy cleanly back to personalization! + outTotals[u] = Math.max(s, rawOutTotals[u]); + } + + let ranks = new Float64Array(personalization); + let next = new Float64Array(N); + + for (let iter = 0; iter < 65; iter += 1) { + next.fill(0); + let leakedMass = 0; + for (let u = 0; u < N; u += 1) { + if (outTotals[u] === 0) { + leakedMass += ranks[u]; + } else { + let actualSum = 0; + for (const w of adj[u].values()) actualSum += w; + if (actualSum < outTotals[u]) { + leakedMass += ranks[u] * ((outTotals[u] - actualSum) / outTotals[u]); + } + } + } + + const baseFactor = 1 - alpha; + for (let i = 0; i < N; i += 1) { + next[i] = (baseFactor + alpha * leakedMass) * personalization[i]; + } + + for (let u = 0; u < N; u += 1) { + const total = outTotals[u]; + if (total === 0) continue; + const share = (alpha * ranks[u]) / total; + for (const [v, w] of adj[u].entries()) { + next[v] += share * w; + } + } + + let diff = 0; + for (let i = 0; i < N; i += 1) { + diff += Math.abs(next[i] - ranks[i]); + } + const tmp = ranks; + ranks = next; + next = tmp; + if (diff < 1e-7) break; + } + + return { ranks, seedScores, isFocused: hasFocus }; +} + +// ─── Tarjan's Strongly Connected Components (Circular Dependency Detection) ─ + +export function detectCircularDependencies(index) { + const N = index.files.length; + const disc = new Int32Array(N).fill(-1); + const low = new Int32Array(N).fill(-1); + const onStack = new Uint8Array(N); + const tarjanStack = []; + let timer = 0; + const sccs = []; + + // Iterative Tarjan DFS to guarantee zero call-stack overflow on deep repos + const callStack = []; + for (let start = 0; start < N; start += 1) { + if (disc[start] !== -1) continue; + disc[start] = low[start] = timer++; + onStack[start] = 1; + tarjanStack.push(start); + callStack.push({ u: start, neighbors: [...index.importAdj[start]], idx: 0 }); + + while (callStack.length > 0) { + const frame = callStack[callStack.length - 1]; + const { u, neighbors } = frame; + if (frame.idx < neighbors.length) { + const v = neighbors[frame.idx++]; + if (disc[v] === -1) { + disc[v] = low[v] = timer++; + onStack[v] = 1; + tarjanStack.push(v); + callStack.push({ u: v, neighbors: [...index.importAdj[v]], idx: 0 }); + } else if (onStack[v]) { + low[u] = Math.min(low[u], disc[v]); + } + } else { + callStack.pop(); + if (callStack.length > 0) { + const parent = callStack[callStack.length - 1].u; + low[parent] = Math.min(low[parent], low[u]); + } + if (low[u] === disc[u]) { + const component = []; + while (true) { + const w = tarjanStack.pop(); + onStack[w] = 0; + component.push(w); + if (w === u) break; + } + if (component.length >= 2) { + sccs.push(component); + } + } + } + } + } + + // Extract a concrete shortest cycle witness path inside each SCC + const cycles = sccs.map((comp) => { + const memberSet = new Set(comp); + comp.sort((a, b) => index.files[a].relPath.localeCompare(index.files[b].relPath)); + const root = comp[0]; + const parent = new Map(); + const queue = [root]; + let backSource = -1; + + outer: while (queue.length > 0) { + const curr = queue.shift(); + for (const nxt of index.importAdj[curr]) { + if (!memberSet.has(nxt)) continue; + if (nxt === root) { + backSource = curr; + break outer; + } + if (!parent.has(nxt)) { + parent.set(nxt, curr); + queue.push(nxt); + } + } + } + + const cycleNodes = []; + if (backSource !== -1) { + let cur = backSource; + while (cur !== undefined && cur !== root) { + cycleNodes.push(cur); + cur = parent.get(cur); + } + cycleNodes.push(root); + cycleNodes.reverse(); + cycleNodes.push(root); + } + + return { + size: comp.length, + members: comp.map((idx) => index.files[idx].relPath), + witnessCycle: cycleNodes.map((idx) => index.files[idx].relPath), + }; + }); + + cycles.sort((a, b) => b.size - a.size); + return cycles; +} + +// ─── Coupling & Module Architecture Summary ───────────────────────────────── + +export function analyzeArchitectureMetrics(index, ranks) { + const N = index.files.length; + const cycles = detectCircularDependencies(index); + + // Directory / Package module clustering + const modules = new Map(); + for (let i = 0; i < N; i += 1) { + const f = index.files[i]; + const parts = f.relPath.split('/'); + let modKey; + if (parts[0] === 'packages' || parts[0] === 'apps' || parts[0] === 'crates' || parts[0] === 'services') { + modKey = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0]; + } else if (parts[0] === 'src' && parts.length >= 3) { + modKey = `src/${parts[1]}`; + } else { + modKey = parts.length >= 2 ? parts[0] : '(root)'; + } + + let m = modules.get(modKey); + if (!m) { + m = { + name: modKey, + fileCount: 0, + testCount: 0, + lineCount: 0, + symbolCount: 0, + pageRankSum: 0, + externalIn: 0, + externalOut: 0, + topFile: null, + topFileRank: -1, + }; + modules.set(modKey, m); + } + m.fileCount += 1; + if (f.isTest) m.testCount += 1; + m.lineCount += index.parsedFiles[i].lineCount; + m.symbolCount += index.parsedFiles[i].symbols.length; + m.pageRankSum += ranks[i] ?? 0; + if ((ranks[i] ?? 0) > m.topFileRank && !f.isTest) { + m.topFileRank = ranks[i] ?? 0; + m.topFile = f.relPath; + } + } + + const getModKey = (relPath) => { + const parts = relPath.split('/'); + if (parts[0] === 'packages' || parts[0] === 'apps' || parts[0] === 'crates' || parts[0] === 'services') { + return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0]; + } + if (parts[0] === 'src' && parts.length >= 3) return `src/${parts[1]}`; + return parts.length >= 2 ? parts[0] : '(root)'; + }; + + const crossModuleEdges = new Map(); + for (let u = 0; u < N; u += 1) { + const mu = getModKey(index.files[u].relPath); + for (const v of index.importAdj[u]) { + const mv = getModKey(index.files[v].relPath); + if (mu !== mv) { + modules.get(mu).externalOut += 1; + modules.get(mv).externalIn += 1; + const ek = `${mu} -> ${mv}`; + crossModuleEdges.set(ek, (crossModuleEdges.get(ek) ?? 0) + 1); + } + } + } + + const moduleList = [...modules.values()] + .map((m) => { + const totalCoupling = m.externalIn + m.externalOut; + const instability = totalCoupling === 0 ? 0 : +(m.externalOut / totalCoupling).toFixed(2); + return { ...m, instability }; + }) + .sort((a, b) => b.pageRankSum - a.pageRankSum); + + // Classify hub files, entrypoints, and foundation modules + const fileMetrics = []; + const declaredEntries = new Set(index.workspaceMeta?.entrypoints ?? []); + for (let i = 0; i < N; i += 1) { + const f = index.files[i]; + if (f.isTest) continue; + const fanIn = index.reverseImportAdj[i].size; + const fanOut = index.importAdj[i].size; + const instability = fanIn + fanOut === 0 ? 0 : +(fanOut / (fanIn + fanOut)).toFixed(2); + fileMetrics.push({ + fileIdx: i, + relPath: f.relPath, + role: f.role, + lang: f.lang, + lines: index.parsedFiles[i].lineCount, + symbolCount: index.parsedFiles[i].symbols.length, + fanIn, + fanOut, + instability, + rank: ranks[i] ?? 0, + isEntrypoint: f.role === 'entrypoint' || declaredEntries.has(f.relPath) || (fanIn === 0 && fanOut >= 2 && f.role === 'cli'), + }); + } + + const sortedMetrics = [...fileMetrics].sort((a, b) => b.rank - a.rank); + const seenCloneSig = new Set(); + const topHubs = []; + for (const m of sortedMetrics) { + const cloneSig = `${path.posix.basename(m.relPath)}:${m.lines}:${m.symbolCount}`; + if (seenCloneSig.has(cloneSig) && m.lines > 30) continue; + seenCloneSig.add(cloneSig); + topHubs.push(m); + if (topHubs.length >= 12) break; + } + const entrypoints = fileMetrics + .filter((m) => m.isEntrypoint) + .sort((a, b) => b.fanOut - a.fanOut || b.rank - a.rank) + .slice(0, 10); + + const topCrossModuleFlows = [...crossModuleEdges.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, 12) + .map(([flow, count]) => ({ flow, count })); + + return { + modules: moduleList, + topHubs, + entrypoints, + cycles, + topCrossModuleFlows, + }; +} + +// ─── Symbol Lookup & Call-Site Resolution ─────────────────────────────────── + +export function lookupSymbols(index, ranks, query, limit = 15) { + const q = query.trim(); + const qLower = q.toLowerCase(); + const [ownerFilter, memberFilter] = qLower.includes('.') + ? qLower.split('.', 2) + : qLower.includes('::') + ? qLower.split('::', 2) + : [null, qLower]; + + const candidates = []; + for (let i = 0; i < index.files.length; i += 1) { + const f = index.files[i]; + const pf = index.parsedFiles[i]; + for (const sym of pf.symbols) { + const nameLower = sym.name.toLowerCase(); + const parentLower = (sym.parent ?? '').toLowerCase(); + + let matchScore = 0; + if (ownerFilter) { + if (parentLower.includes(ownerFilter) && nameLower === memberFilter) matchScore = 100; + else if (parentLower.includes(ownerFilter) && nameLower.includes(memberFilter)) matchScore = 70; + } else { + if (nameLower === qLower) matchScore = 100; + else if (nameLower.startsWith(qLower)) matchScore = 75; + else if (nameLower.includes(qLower)) matchScore = 50; + } + if (matchScore === 0) continue; + if (!f.isTest) matchScore += 15; + if (sym.exported) matchScore += 8; + + candidates.push({ + relPath: f.relPath, + fileIdx: i, + symbol: sym, + rank: ranks[i] ?? 0, + score: matchScore + (ranks[i] ?? 0) * 100, + }); + } + } + + candidates.sort((a, b) => b.score - a.score); + const top = candidates.slice(0, limit); + + // Enrich each matched symbol with concrete callers & callees + return top.map((item) => { + const symName = item.symbol.name; + const callers = []; + + for (let u = 0; u < index.files.length; u += 1) { + const pf = index.parsedFiles[u]; + if (!pf.refs[symName]) continue; + // Check symbol-level callers inside file u + let matchedCallerFn = false; + for (const callerSym of pf.symbols) { + if (u === item.fileIdx && callerSym.name === symName && callerSym.lineStart === item.symbol.lineStart) { + continue; + } + if (callerSym.calls?.includes(symName)) { + matchedCallerFn = true; + callers.push({ + relPath: index.files[u].relPath, + callerSymbol: callerSym.parent ? `${callerSym.parent}.${callerSym.name}` : callerSym.name, + lineStart: callerSym.lineStart, + isDirectImport: index.importAdj[u].has(item.fileIdx), + isTest: index.files[u].isTest, + }); + } + } + if (!matchedCallerFn && u !== item.fileIdx && index.importAdj[u].has(item.fileIdx)) { + callers.push({ + relPath: index.files[u].relPath, + callerSymbol: '(module scope)', + lineStart: 1, + isDirectImport: true, + isTest: index.files[u].isTest, + }); + } + } + + callers.sort((a, b) => Number(b.isDirectImport) - Number(a.isDirectImport) || Number(a.isTest) - Number(b.isTest)); + + const callees = []; + for (const calleeIdent of item.symbol.calls ?? []) { + const defs = index.symbolDefs.get(calleeIdent); + if (!defs) continue; + const bestDef = + defs.find((d) => index.importAdj[item.fileIdx].has(d.fileIdx)) ?? + defs.find((d) => d.fileIdx === item.fileIdx) ?? + defs.find((d) => !index.files[d.fileIdx].isTest) ?? + defs[0]; + if (bestDef) { + callees.push({ + symbol: bestDef.symbol.parent ? `${bestDef.symbol.parent}.${bestDef.symbol.name}` : bestDef.symbol.name, + kind: bestDef.symbol.kind, + relPath: index.files[bestDef.fileIdx].relPath, + lineStart: bestDef.symbol.lineStart, + }); + } + if (callees.length >= 12) break; + } + + return { + ...item, + callers: callers.slice(0, 15), + totalCallerCount: callers.length, + callees, + }; + }); +} + +// ─── Blast Radius / Change Impact Analysis ────────────────────────────────── + +export function computeImpactRadius(index, ranks, rawTargets, maxDepth = 3) { + const seedFileIdxs = new Set(); + const matchedSymbols = []; + + for (const raw of rawTargets) { + const cleaned = normalizeRelPath(raw.trim()); + if (!cleaned) continue; + + // 1. Try exact or suffix file match + const exactIdx = index.pathToIdx.get(cleaned); + if (exactIdx !== undefined) { + seedFileIdxs.add(exactIdx); + continue; + } + let foundPath = false; + for (let i = 0; i < index.files.length; i += 1) { + if (index.files[i].relPath.endsWith(`/${cleaned}`) || index.files[i].relPath === cleaned) { + seedFileIdxs.add(i); + foundPath = true; + } + } + if (foundPath) continue; + + // 2. Otherwise resolve as symbol name + const defs = index.symbolDefs.get(cleaned) ?? []; + if (defs.length > 0) { + for (const d of defs) { + if (!index.files[d.fileIdx].isTest || defs.length === 1) { + seedFileIdxs.add(d.fileIdx); + matchedSymbols.push({ + name: d.symbol.name, + relPath: index.files[d.fileIdx].relPath, + lineStart: d.symbol.lineStart, + }); + } + } + } else { + // Partial path or symbol fallback + const lower = cleaned.toLowerCase(); + for (let i = 0; i < index.files.length; i += 1) { + if (index.files[i].relPath.toLowerCase().includes(lower)) { + seedFileIdxs.add(i); + } + } + } + } + + // Reverse BFS over BOTH explicit import graph AND high-confidence symbol reference edges + const reverseAll = Array.from({ length: index.files.length }, () => new Set()); + for (let u = 0; u < index.files.length; u += 1) { + for (const v of index.importAdj[u]) reverseAll[v].add(u); + for (const [v, cell] of index.weightedOut[u].entries()) { + if (cell.weight >= 2.2) reverseAll[v].add(u); + } + } + + const depthMap = new Map(); // fileIdx -> hop distance (1..maxDepth) + const viaMap = new Map(); // fileIdx -> upstream step + const queue = []; + + for (const seed of seedFileIdxs) { + depthMap.set(seed, 0); + queue.push(seed); + } + + while (queue.length > 0) { + const curr = queue.shift(); + const d = depthMap.get(curr); + if (d >= maxDepth) continue; + for (const dependent of reverseAll[curr]) { + if (!depthMap.has(dependent)) { + depthMap.set(dependent, d + 1); + viaMap.set(dependent, index.files[curr].relPath); + queue.push(dependent); + } + } + } + + const directDependents = []; + const transitiveDependents = []; + const affectedTests = new Set(); + + for (const [idx, hop] of depthMap.entries()) { + if (hop === 0) continue; + const f = index.files[idx]; + if (f.isTest) { + affectedTests.add(f.relPath); + continue; + } + const entry = { + relPath: f.relPath, + hop, + via: viaMap.get(idx), + rank: ranks[idx] ?? 0, + }; + if (hop === 1) directDependents.push(entry); + else transitiveDependents.push(entry); + } + + // Heuristic test-file discovery by stem matching (e.g. `parser.mjs` -> `test/parser.test.mjs`) + const seedStems = [...seedFileIdxs].map((idx) => + path.posix.basename(index.files[idx].relPath).replace(/\.[^.]+$/u, '').toLowerCase(), + ); + for (const f of index.files) { + if (!f.isTest) continue; + const baseLower = path.posix.basename(f.relPath).toLowerCase(); + if (seedStems.some((stem) => stem.length >= 3 && baseLower.includes(stem))) { + affectedTests.add(f.relPath); + } + } + + // Direct downstream dependencies of target files + const downstreamDeps = new Set(); + for (const seed of seedFileIdxs) { + for (const depIdx of index.importAdj[seed]) { + if (!seedFileIdxs.has(depIdx)) { + downstreamDeps.add(index.files[depIdx].relPath); + } + } + } + + directDependents.sort((a, b) => b.rank - a.rank); + transitiveDependents.sort((a, b) => a.hop - b.hop || b.rank - a.rank); + + const totalProdAffected = directDependents.length + transitiveDependents.length; + let riskLevel = 'LOW'; + if (totalProdAffected >= 20 || directDependents.length >= 10) riskLevel = 'CRITICAL'; + else if (totalProdAffected >= 8 || directDependents.length >= 4) riskLevel = 'HIGH'; + else if (totalProdAffected >= 2) riskLevel = 'MEDIUM'; + + return { + seeds: [...seedFileIdxs].map((idx) => index.files[idx].relPath), + matchedSymbols, + riskLevel, + directDependents, + transitiveDependents, + downstreamDeps: [...downstreamDeps].slice(0, 20), + affectedTests: [...affectedTests].sort(), + }; +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/importers.mjs b/plugins/Jialei-03/mcode-repowiki/server/importers.mjs new file mode 100644 index 00000000..9a44f504 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/importers.mjs @@ -0,0 +1,359 @@ +// Who really imports a symbol (or a file): follows import statements, re-exports and package +// entries (`@scope/pkg` → `packages/pkg/src/index.ts`), so the answer to "what does changing this +// break" is a list of import lines, not every file that happens to contain the same word. +import { execFileSync } from 'node:child_process'; +import { readFileSync, statSync } from 'node:fs'; +import path from 'node:path'; + +const JS_EXTS = ['.ts', '.tsx', '.mts', '.cts', '.d.ts', '.js', '.jsx', '.mjs', '.cjs']; +const JS_FILE_RE = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/u; +const IGNORED_DIR_RE = /(^|\/)(node_modules|\.git|\.repowiki|dist|build|out|coverage)(\/|$)/u; +const TEST_RE = /(^|\/)(test|tests|__tests__|spec)(\/|$)|\.(test|spec)\.[a-z]+$/iu; +const ESM_RE = /\b(import|export)\s+(type\s+)?(?:([\w$]+\s*,?\s*)?(\*\s*(?:as\s+[\w$]+)?|\{[^}]*\})?\s*from\s+)?['"]([^'"\n]+)['"]/gu; + +function gitLines(repoRoot, args) { + try { + return execFileSync('git', ['-C', repoRoot, ...args], { + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, + stdio: ['ignore', 'pipe', 'ignore'], + timeout: 8000, + }) + .split('\n') + .map((s) => s.trim().replace(/\\/gu, '/')) + .filter(Boolean); + } catch { + return []; + } +} + +const isFile = (abs) => { + try { + return statSync(abs).isFile(); + } catch { + return false; + } +}; + +/** Workspace packages: name → { dir, exports, fields }. */ +function loadPackages(repoRoot) { + const pkgs = []; + const files = gitLines(repoRoot, ['ls-files', '--', 'package.json', '*/package.json']); + for (const rel of files) { + if (IGNORED_DIR_RE.test(rel)) continue; + try { + const json = JSON.parse(readFileSync(path.join(repoRoot, rel), 'utf8')); + if (!json.name) continue; + const dir = path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel); + pkgs.push({ name: json.name, dir, json }); + } catch { + // not a usable manifest + } + } + pkgs.sort((a, b) => b.name.length - a.name.length); + return pkgs; +} + +function exportTargets(value) { + if (!value) return []; + if (typeof value === 'string') return [value]; + if (Array.isArray(value)) return value.flatMap(exportTargets); + if (typeof value === 'object') { + const order = ['source', 'types', 'import', 'module', 'default', 'require', 'node']; + const keys = [...order.filter((k) => k in value), ...Object.keys(value).filter((k) => !order.includes(k))]; + return keys.flatMap((k) => exportTargets(value[k])); + } + return []; +} + +export function createSpecifierResolver(repoRoot) { + const pkgs = loadPackages(repoRoot); + const cache = new Map(); + + const probe = (relBase) => { + const clean = path.posix.normalize(relBase).replace(/^\.\//u, ''); + if (clean.startsWith('..')) return null; + const abs = (r) => path.join(repoRoot, r); + if (JS_FILE_RE.test(clean) && isFile(abs(clean))) return clean; + const ext = path.posix.extname(clean); + if (['.js', '.jsx', '.mjs', '.cjs'].includes(ext)) { + const stem = clean.slice(0, -ext.length); + for (const e of ['.ts', '.tsx', '.mts', '.cts', '.d.ts']) if (isFile(abs(stem + e))) return stem + e; + } + for (const e of JS_EXTS) if (isFile(abs(clean + e))) return clean + e; + for (const e of JS_EXTS) if (isFile(abs(`${clean}/index${e}`))) return `${clean}/index${e}`; + return null; + }; + + // dist/x.js or dist/x.d.ts in a manifest usually stands for src/x.ts in a source checkout. + const probeTarget = (pkgDir, target) => { + const t = target.replace(/^\.\//u, ''); + const join = (p) => (pkgDir ? `${pkgDir}/${p}` : p); + const direct = probe(join(t)); + if (direct) return direct; + const asSrc = t.replace(/^(dist|lib|build|out)\//u, 'src/').replace(/\.d\.ts$/u, '.ts'); + return probe(join(asSrc)); + }; + + const resolvePackage = (pkg, sub) => { + const join = (p) => (pkg.dir ? `${pkg.dir}/${p}` : p); + const exp = pkg.json.exports; + const key = sub ? `./${sub}` : '.'; + let targets = []; + if (exp && typeof exp === 'object' && !Array.isArray(exp) && Object.keys(exp).some((k) => k.startsWith('.'))) { + targets = exportTargets(exp[key]); + } else if (!sub && exp) { + targets = exportTargets(exp); + } + if (!sub) targets.push(...[pkg.json.source, pkg.json.types, pkg.json.typings, pkg.json.module, pkg.json.main].filter(Boolean)); + for (const t of targets) { + const hit = probeTarget(pkg.dir, t); + if (hit) return hit; + } + return sub ? probe(join(`src/${sub}`)) ?? probe(join(sub)) : probe(join('src/index')) ?? probe(join('index')); + }; + + /** Resolve `spec` imported from `fromRel` to a repo-relative file, or null. */ + function resolve(fromRel, spec) { + const dir = path.posix.dirname(fromRel); + const key = spec.startsWith('.') ? `${dir}\0${spec}` : spec; + if (cache.has(key)) return cache.get(key); + let hit = null; + if (spec.startsWith('.')) { + hit = probe(dir === '.' ? spec : `${dir}/${spec}`); + } else { + const pkg = pkgs.find((p) => spec === p.name || spec.startsWith(`${p.name}/`)); + if (pkg) hit = resolvePackage(pkg, spec === pkg.name ? '' : spec.slice(pkg.name.length + 1)); + } + cache.set(key, hit); + return hit; + } + + /** The package a file belongs to, and the import specifier that names `rel` (if it is an entry). */ + function packageOf(rel) { + const owner = pkgs + .filter((p) => !p.dir || rel.startsWith(`${p.dir}/`)) + .sort((a, b) => b.dir.length - a.dir.length)[0]; + if (!owner) return null; + const specs = []; + const exp = owner.json.exports; + const subKeys = exp && typeof exp === 'object' && !Array.isArray(exp) + ? Object.keys(exp).filter((k) => k.startsWith('.') && !k.includes('*')) + : []; + for (const k of subKeys.length ? subKeys : ['.']) { + const sub = k === '.' ? '' : k.slice(2); + if (resolvePackage(owner, sub) === rel) specs.push(sub ? `${owner.name}/${sub}` : owner.name); + } + return { name: owner.name, dir: owner.dir, specs, scripts: owner.json.scripts ?? {} }; + } + + /** Outermost workspace package holding `rel` (nested example/plugin packages fold into it). */ + function groupOf(rel) { + const outer = pkgs + .filter((p) => p.dir && rel.startsWith(`${p.dir}/`)) + .sort((a, b) => a.dir.length - b.dir.length)[0]; + return outer?.dir ?? (rel.includes('/') ? rel.split('/')[0] : '.'); + } + + return { resolve, packageOf, groupOf }; +} + +/** ESM import / re-export statements with line numbers. */ +function readImports(text) { + const out = []; + ESM_RE.lastIndex = 0; + let m; + while ((m = ESM_RE.exec(text)) !== null) { + const lineStart = text.lastIndexOf('\n', m.index) + 1; + const prefix = text.slice(lineStart, m.index).trim(); + if (prefix.startsWith('//') || prefix.startsWith('*') || prefix.startsWith('/*')) continue; + const [, kw, , def, clause = '', spec] = m; + const names = []; // { imported, local } + let namespace = null; + let star = false; + const c = clause.trim(); + if (c.startsWith('{')) { + for (const tok of c.slice(1, -1).split(',')) { + const t = tok.replace(/^\s*type\s+/u, '').trim(); + if (!t) continue; + const [imported, local] = t.split(/\s+as\s+/u).map((s) => s.trim()); + names.push({ imported, local: local || imported }); + } + } else if (c.startsWith('*')) { + const asName = c.match(/as\s+([\w$]+)/u)?.[1]; + if (kw === 'export' && !asName) star = true; + else namespace = asName ?? null; + } + if (def && kw === 'import') names.push({ imported: 'default', local: def.replace(/[\s,]/gu, '') }); + const line = text.slice(0, m.index).split('\n').length; + out.push({ kind: kw === 'export' ? 'reexport' : 'import', spec, names, namespace, star, line, raw: m[0] }); + } + return out; +} + +/** + * Trace who imports `symbols` defined in `defRel`, through any chain of re-exports. + * Returns { importers: [{ relPath, line, spec, symbols, via, isTest, reexport }], reexporters, pkg }. + */ +export function traceImporters(repoRoot, defRel, symbols) { + const resolver = createSpecifierResolver(repoRoot); + // provider file → Map(exported name → original symbol) + const providers = new Map([[defRel, new Map(symbols.map((s) => [s, s]))]]); + const viaOf = new Map([[defRel, null]]); + const texts = new Map(); + const importsOf = (rel) => { + if (!texts.has(rel)) { + let t = ''; + try { + t = readFileSync(path.join(repoRoot, rel), 'utf8'); + } catch { + // unreadable + } + texts.set(rel, { text: t, imports: t ? readImports(t) : [] }); + } + return texts.get(rel); + }; + + const candidates = new Set(); + const grepped = new Set(); + const addCandidates = (names) => { + const fresh = names.filter((n) => /^[A-Za-z_$][\w$]*$/u.test(n) && !grepped.has(n)); + if (fresh.length === 0) return; + fresh.forEach((n) => grepped.add(n)); + for (let i = 0; i < fresh.length; i += 40) { + const args = ['grep', '-l', '-I', '-w', '--untracked', '--exclude-standard']; + for (const n of fresh.slice(i, i + 40)) args.push('-e', n); + for (const rel of gitLines(repoRoot, args)) if (JS_FILE_RE.test(rel) && !IGNORED_DIR_RE.test(rel)) candidates.add(rel); + } + }; + addCandidates(symbols); + for (const rel of gitLines(repoRoot, ['grep', '-l', '-I', '-E', '--untracked', '--exclude-standard', '-e', 'export \\* from', '-e', 'import \\* as'])) { + if (JS_FILE_RE.test(rel) && !IGNORED_DIR_RE.test(rel)) candidates.add(rel); + } + + const records = new Map(); // rel → record + let changed = true; + let rounds = 0; + while (changed && rounds < 8) { + changed = false; + rounds += 1; + for (const rel of candidates) { + if (rel === defRel) continue; + const { text, imports } = importsOf(rel); + for (const imp of imports) { + const target = resolver.resolve(rel, imp.spec); + const provided = target ? providers.get(target) : null; + if (!provided) continue; + const used = new Map(); // local name → original + if (imp.star) for (const [n, o] of provided) used.set(n, o); + for (const { imported, local } of imp.names) if (provided.has(imported)) used.set(local, provided.get(imported)); + if (imp.namespace) { + for (const [n, o] of provided) if (new RegExp(`\\b${imp.namespace}\\.${n.replace(/\$/gu, '\\$')}\\b`, 'u').test(text)) used.set(n, o); + } + if (used.size === 0) continue; + // Point at the line naming the symbol inside a multi-line import, not the `import` keyword. + const firstName = [...used.keys()][0]; + const at = imp.raw.search(new RegExp(`\\b${firstName.replace(/\$/gu, '\\$')}\\b`, 'u')); + const line = at > 0 ? imp.line + (imp.raw.slice(0, at).match(/\n/gu)?.length ?? 0) : imp.line; + const rec = records.get(rel) ?? { + relPath: rel, + line, + spec: imp.spec, + symbols: new Set(), + via: target === defRel ? null : target, + isTest: TEST_RE.test(rel), + reexport: false, + }; + for (const o of used.values()) rec.symbols.add(o); + if (imp.kind === 'reexport') rec.reexport = true; + // Prefer the most direct route as the representative line. + if (target === defRel && rec.via) Object.assign(rec, { line, spec: imp.spec, via: null }); + records.set(rel, rec); + if (imp.kind === 'reexport') { + const mine = providers.get(rel) ?? new Map(); + const before = mine.size; + for (const [n, o] of used) mine.set(n, o); + if (mine.size > before) { + providers.set(rel, mine); + viaOf.set(rel, target); + addCandidates([...mine.keys()]); + changed = true; + } + } + } + } + } + + const importers = [...records.values()] + .map((r) => ({ ...r, symbols: [...r.symbols] })) + .sort((a, b) => Number(a.isTest) - Number(b.isTest) || a.relPath.localeCompare(b.relPath)); + const reexporters = importers + .filter((r) => r.reexport) + .map((r) => ({ relPath: r.relPath, line: r.line, pkg: resolver.packageOf(r.relPath) })); + // "through": reached only via a re-export that lives in a different package than the definition. + const home = resolver.groupOf(defRel); + for (const r of importers) { + let hop = r.via; + let through = null; + while (hop && hop !== defRel) { + if (resolver.groupOf(hop) !== home) through = resolver.groupOf(hop); + hop = viaOf.get(hop); + } + r.through = through; + } + return { defRel, importers, reexporters, pkg: resolver.packageOf(defRel), groupOf: resolver.groupOf }; +} + +/** Agent-facing section: resolved importers grouped by top-level package, with the line to look at. */ +export function formatImporters(title, trace, { maxTotal = 60, wordMatches = null, word = '' } = {}) { + const { importers, reexporters, pkg, groupOf } = trace; + const out = []; + const home = pkg ? groupOf(pkg.dir ? `${pkg.dir}/x` : 'x') : ''; + const groups = new Map(); + for (const r of importers) { + const k = groupOf(r.relPath); + if (!groups.has(k)) groups.set(k, []); + groups.get(k).push(r); + } + const tests = importers.filter((r) => r.isTest).length; + const indirect = importers.filter((r) => r.through).length; + out.push( + `## ${title}: ${importers.length} files in ${groups.size} packages (${tests} tests) — from resolved import statements, not a text search`, + ); + if (importers.length === 0) out.push('- Nothing in the repo imports it.'); + if (reexporters.length > 0) { + const shown = reexporters.slice(0, 6).map((r) => { + const entry = r.pkg?.specs?.length ? ` (= \`${r.pkg.specs.join('`, `')}\`)` : ''; + return `\`${r.relPath}:L${r.line}\`${entry}`; + }); + out.push(`- Re-exported by ${shown.join(', ')}${reexporters.length > 6 ? ` and ${reexporters.length - 6} more` : ''}; files importing through them are included.`); + } + if (indirect > 0) { + out.push(`- ${importers.length - indirect} files import it directly (the defining file or its own package entry); ${indirect} only through another package's re-export (marked "through …").`); + } + out.push(`- By package: ${[...groups.entries()].sort((a, b) => b[1].length - a[1].length).map(([k, rows]) => `\`${k}\` ${rows.length}`).join(', ')}`); + // Its own package first (where it is exported and tested), then other packages' source, then their tests. + const rank = (r) => (groupOf(r.relPath) === home ? 0 : r.isTest ? 2 : 1); + const ordered = [...importers].sort( + (a, b) => rank(a) - rank(b) || Number(a.isTest) - Number(b.isTest) || a.relPath.localeCompare(b.relPath), + ); + for (const r of ordered.slice(0, maxTotal)) { + const syms = r.symbols.length <= 5 ? r.symbols.join(', ') : `${r.symbols.slice(0, 5).join(', ')} +${r.symbols.length - 5}`; + const tags = `${r.isTest ? ' [test]' : ''}${r.reexport ? ' [re-export]' : ''}${r.through ? ` through \`${r.through}\`` : ''}`; + out.push(`- \`${r.relPath}:L${r.line}\`${tags} ← \`${r.spec}\`: ${syms}`); + } + if (ordered.length > maxTotal) { + out.push(`- … ${ordered.length - maxTotal} more (${ordered.slice(maxTotal).filter((r) => r.isTest).length} of them tests); call again with \`symbol\` to narrow to one export.`); + } + if (wordMatches !== null && word) { + const listed = new Set(importers.map((r) => r.relPath)); + const others = wordMatches.filter((rel) => !listed.has(rel) && rel !== trace.defRel); + if (others.length > 0) { + out.push( + `- Not listed: ${others.length} other files contain the word \`${word}\` but do not import this one (own same-named types, parameters, comments, strings), e.g. ${others.slice(0, 3).map((x) => `\`${x}\``).join(', ')}.`, + ); + } + } + out.push(''); + return out; +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/lint.mjs b/plugins/Jialei-03/mcode-repowiki/server/lint.mjs new file mode 100644 index 00000000..335af5b3 --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/lint.mjs @@ -0,0 +1,130 @@ +/** + * Writing checks run by `wiki_write_page`. They never block a write: they return short, + * actionable warnings that the agent reads in the tool result and fixes in the next call. + * Each rule targets a problem seen in real generated chapters, for either reader: + * people (walls of text, vague steps) or tools (citations that cannot follow code moves, + * numbers that silently go stale, sections `wiki_locate` cannot match). + */ + +const CITE_RE = /\[([^\]]+)\]\(([^)\s#]+)#L?(\d+)(?:-L?(\d+))?\)/gu; +const MAX_CITE_SPAN = 200; +const MAX_PARAGRAPH_WIDTH = 520; // CJK chars count 2, roughly 260 Chinese characters or ~90 English words + +function stripCode(md) { + return md.replace(/```[\s\S]*?```/gu, ''); +} + +function splitSections(md) { + const parts = []; + let current = null; + for (const line of md.split('\n')) { + const h = line.match(/^##\s+(.+)$/u); + if (h) { + current = { heading: h[1].trim(), body: [] }; + parts.push(current); + } else if (current) { + current.body.push(line); + } + } + return parts.map((p) => ({ heading: p.heading, body: p.body.join('\n') })); +} + +const displayWidth = (s) => [...s].reduce((w, ch) => w + (/[⺀-鿿＀-￯]/u.test(ch) ? 2 : 1), 0); + +export function lintWikiPage(pagePath, markdown, anchors = []) { + const warnings = []; + const prose = stripCode(markdown); + const isModule = pagePath.startsWith('02-modules/'); + const isOverview = pagePath === 'README.md'; + const sections = splitSections(prose); + + if (!/^#\s+\S/mu.test(markdown)) warnings.push('No `# Title` line: start the chapter with an H1 title.'); + if (sections.length === 0) { + warnings.push('No `##` sections: split the chapter into `##` sections; `wiki_locate` searches and returns one section at a time.'); + } + + if (isModule) { + if (sections.length < 6) { + warnings.push( + `Module chapter has ${sections.length} \`##\` sections; use the six from the skill: what it does · where it sits · core concepts · one call step by step · how to change it · key files.`, + ); + } + const walk = sections[3]; + if (walk) { + // A step runs from its "N." line up to the next step (continuation lines included). + const steps = []; + for (const line of walk.body.split('\n')) { + if (/^\s*\d+\.\s/u.test(line)) steps.push(line); + else if (steps.length > 0 && !/^#{1,6}\s/u.test(line)) steps[steps.length - 1] += `\n${line}`; + } + const bare = steps.filter((l) => !/\]\([^)]+#L\d+/u.test(l)); + if (steps.length > 0 && bare.length > 0) { + warnings.push( + `${bare.length} of ${steps.length} steps in "${walk.heading}" cite no code (e.g. "${bare[0].trim().split('\n')[0].slice(0, 60)}"). Cite the function each step runs (\`[name · file.ts:Lx-Ly](…)\`); if you could not confirm a step in the code, say so in the step.`, + ); + } + } + } + + if (isOverview) { + if (!/\]\((?:\.\/)?0[1-3]-[^)]+\.md\)/u.test(markdown)) { + warnings.push('The overview links to no chapter: link each module in the map table to its `02-modules/…` chapter.'); + } + if (!/\]\([^)]+#L\d+/u.test(markdown)) { + warnings.push('The overview cites no code: cite the entry point(s) a reader should open first.'); + } + } + + // Citations + const wide = []; + let m; + CITE_RE.lastIndex = 0; + while ((m = CITE_RE.exec(markdown)) !== null) { + const s = Number(m[3]); + const e = m[4] ? Number(m[4]) : s; + if (e - s + 1 > MAX_CITE_SPAN) wide.push(`${m[2].split('/').pop()}:L${s}-L${e}`); + } + if (wide.length > 0) { + warnings.push( + `${wide.length} citation(s) span more than ${MAX_CITE_SPAN} lines (${wide.slice(0, 3).join(', ')}): cite the specific method or type you are describing, not the whole class or file.`, + ); + } + const loose = anchors.filter((a) => !a.symbol); + if (loose.length > 0) { + warnings.push( + `${loose.length} citation(s) point at no function, class or type (${loose + .slice(0, 3) + .map((a) => `${a.file.split('/').pop()}:L${a.start}`) + .join(', ')}); they cannot follow the code when it moves. Prefer ranges that cover a declaration.`, + ); + } + + // Numbers that go stale without anyone noticing + const volatile = [ + ...prose.matchAll(/\d[\d,.]*\s*(?:万|k|K)?\s*(?:行代码|行|个文件|个符号|lines?\b|files?\b|symbols?\b)/gu), + ] + .map((x) => x[0].trim()) + .filter((x) => !/^L?\d+$/u.test(x)); + if (volatile.length > 0) { + warnings.push( + `Exact sizes in prose go stale silently (${[...new Set(volatile)].slice(0, 3).join(', ')}). Describe size in words ("the largest package", "a few hundred lines") — the reader shows live counts.`, + ); + } + + // Readability + const longParas = prose + .split(/\n{2,}/u) + .map((p) => p.trim()) + .filter((p) => p && !/^(?:[|#>-]|\d+\.|\*)/u.test(p) && displayWidth(p) > MAX_PARAGRAPH_WIDTH); + if (longParas.length > 0) { + warnings.push( + `${longParas.length} paragraph(s) are very long (starts "${longParas[0].slice(0, 30)}…"): split them, or turn a sequence into a numbered list or a table.`, + ); + } + + const mermaid = [...markdown.matchAll(/```mermaid\s*\n([\s\S]*?)```/gu)].map((x) => x[1]); + const unquoted = mermaid.some((body) => /\[[^"\]\n]*[()][^\]\n]*\]/u.test(body)); + if (unquoted) warnings.push('A Mermaid label contains parentheses without quotes; write `A["name (detail)"]`.'); + + return warnings; +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/live-server.mjs b/plugins/Jialei-03/mcode-repowiki/server/live-server.mjs new file mode 100644 index 00000000..3e368c7a --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/live-server.mjs @@ -0,0 +1,450 @@ +import { existsSync, mkdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; + +import { generateStarterWiki } from './auto-init.mjs'; +import { ParseCache } from './cache.mjs'; +import { + analyzeArchitectureMetrics, + buildRepositoryIndex, + computePersonalizedPageRank, +} from './graph.mjs'; +import { createWikiBlueprint } from './planner.mjs'; +import { buildPortalPayload, renderPortalHtmlFromPayload } from './site-builder.mjs'; +import { + getGitHeadCommit, + hashFileSha1, + listMarkdownWikiPages, + loadManifest, + resolveWikiDir, + saveManifest, + syncWikiAstDeterministic, + acceptWikiPages, +} from './sync.mjs'; + +const IGNORED_SEGMENTS = new Set([ + '.git', + 'node_modules', + 'dist', + 'build', + 'out', + '.next', + '.nuxt', + '.turbo', + 'coverage', + 'target', + '.venv', + 'venv', + '__pycache__', + '.pytest_cache', + '.mypy_cache', + '.cache', + '.idea', +]); + +function formatClockTime(date = new Date()) { + return date.toTimeString().slice(0, 8); +} + +function shouldIgnoreRepoWatchPath(relPath, relWikiInsideRepo) { + if (!relPath) return true; + const norm = relPath.replace(/\\/gu, '/'); + if (relWikiInsideRepo && (norm === relWikiInsideRepo || norm.startsWith(`${relWikiInsideRepo}/`))) { + return true; + } + const parts = norm.split('/'); + for (const seg of parts) { + if (!seg) continue; + if (IGNORED_SEGMENTS.has(seg)) return true; + if (seg === '.DS_Store' || seg.endsWith('.swp') || seg.endsWith('.tmp') || seg.endsWith('~')) { + return true; + } + } + return false; +} + +/** + * Start a Real-Time RepoWiki HTTP + Server-Sent Events (SSE) Live Server. + * Watches both the repository source tree and the Wiki Markdown directory for sub-second updates. + */ +export async function startLiveWikiServer(options = {}) { + const repoRoot = path.resolve(options.repoRoot || process.cwd()); + if (!existsSync(repoRoot) || !statSync(repoRoot).isDirectory()) { + throw new Error(`Repository directory does not exist: ${repoRoot}`); + } + const wikiDir = resolveWikiDir(repoRoot, options.wikiDir); + mkdirSync(wikiDir, { recursive: true }); + + const host = options.host || '127.0.0.1'; + const requestedPort = options.port ?? 4321; + const allowPortFallback = options.allowPortFallback !== false; + + const cache = options.cache || new ParseCache(); + const sseClients = new Set(); + const activityLog = []; + let suppressWikiWatchUntil = 0; + + const pushActivity = (kind, message) => { + const entry = { kind, message, time: formatClockTime() }; + activityLog.unshift(entry); + if (activityLog.length > 40) activityLog.length = 40; + return entry; + }; + + async function analyzeCurrentRepo() { + const t0 = Date.now(); + const index = await buildRepositoryIndex(repoRoot, { includeTests: true }, cache); + const ppr = computePersonalizedPageRank(index); + const arch = analyzeArchitectureMetrics(index, ppr.ranks); + const blueprint = createWikiBlueprint(index, arch, ppr, { maxModules: 7 }); + const elapsedMs = Date.now() - t0; + index.stats.elapsedMs = elapsedMs; + return { index, ppr, arch, blueprint, elapsedMs }; + } + + let currentAnalyzed = await analyzeCurrentRepo(); + + // Auto-scaffold grounded starter Wiki if directory has zero Markdown pages + if (listMarkdownWikiPages(wikiDir).length === 0 && options.autoInit !== false) { + suppressWikiWatchUntil = Date.now() + 500; + const initRes = generateStarterWiki(repoRoot, wikiDir, currentAnalyzed); + pushActivity('wiki', `自动初始化 ${initRes.pageCount} 篇静态拓扑基线文档`); + } + + let currentPortal = null; + + function rebuildSnapshot({ preserveBaselineHashes = true, writeDiskHtml = false } = {}) { + suppressWikiWatchUntil = Date.now() + 350; + const { payload } = buildPortalPayload( + currentAnalyzed.index, + currentAnalyzed.arch, + currentAnalyzed.ppr, + wikiDir, + { + liveMode: true, + preserveBaselineHashes, + skipEmbeddedSnippets: false, + activityLog, + }, + ); + payload.sync.lastScanMs = currentAnalyzed.elapsedMs; + currentPortal = payload; + if (writeDiskHtml) { + const staticPayload = { ...payload, liveMode: false }; + writeFileSync(path.join(wikiDir, 'index.html'), renderPortalHtmlFromPayload(staticPayload), 'utf8'); + } + return payload; + } + + pushActivity( + 'repo', + `实时监听已就绪 · 索引 ${currentAnalyzed.index.stats.fileCount} 个文件 (${currentAnalyzed.elapsedMs}ms)`, + ); + rebuildSnapshot({ preserveBaselineHashes: true, writeDiskHtml: Boolean(options.writeDiskHtml) }); + + function broadcastSse(eventName, dataObj) { + const frame = `event: ${eventName}\ndata: ${JSON.stringify(dataObj)}\n\n`; + for (const res of sseClients) { + try { + res.write(frame); + } catch { + sseClients.delete(res); + } + } + } + + // ─── HTTP + SSE Request Router ─── + const server = http.createServer(async (req, res) => { + try { + const urlObj = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`); + const pathname = urlObj.pathname; + + if (req.method === 'GET' && (pathname === '/' || pathname === '/index.html')) { + const html = renderPortalHtmlFromPayload(currentPortal); + res.writeHead(200, { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + }); + res.end(html); + return; + } + + if (req.method === 'GET' && pathname === '/api/events') { + res.writeHead(200, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive', + 'X-Accel-Buffering': 'no', + }); + res.write( + `event: connected\ndata: ${JSON.stringify({ + mode: 'live', + repoName: currentPortal.repoName, + gitHead: currentPortal.gitHead, + sync: currentPortal.sync, + activityLog, + })}\n\n`, + ); + sseClients.add(res); + req.on('close', () => sseClients.delete(res)); + return; + } + + if (req.method === 'GET' && pathname === '/api/state') { + res.writeHead(200, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + }); + res.end(JSON.stringify(currentPortal)); + return; + } + + if (req.method === 'GET' && pathname === '/api/file') { + const rawRel = (urlObj.searchParams.get('path') || '').replace(/\\/gu, '/').replace(/^\/+/u, ''); + const absFile = path.resolve(repoRoot, rawRel); + const relBack = path.relative(repoRoot, absFile); + if (!rawRel || relBack.startsWith('..') || path.isAbsolute(relBack) || relBack.startsWith('.git')) { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Forbidden path outside repository root.' })); + return; + } + if (!existsSync(absFile) || !statSync(absFile).isFile()) { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'File not found on disk.' })); + return; + } + + const rawText = readFileSync(absFile, 'utf8').replace(/\r\n/gu, '\n'); + const allLines = rawText.split('\n'); + const full = urlObj.searchParams.get('full') === '1'; + const reqStart = Math.max(1, Number.parseInt(urlObj.searchParams.get('start') || '1', 10)); + const reqEnd = Math.max(reqStart, Number.parseInt(urlObj.searchParams.get('end') || String(reqStart + 35), 10)); + + const padStart = full ? 1 : Math.max(1, reqStart - 16); + const padEnd = full ? Math.min(allLines.length, 2500) : Math.min(allLines.length, Math.max(reqEnd + 24, reqStart + 45)); + const lines = []; + for (let ln = padStart; ln <= padEnd; ln += 1) { + lines.push([ln, (allLines[ln - 1] ?? '').slice(0, 320)]); + } + + res.writeHead(200, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + }); + res.end( + JSON.stringify({ + relPath: rawRel, + totalLines: allLines.length, + start: reqStart, + end: reqEnd, + full, + lines, + }), + ); + return; + } + + if (req.method === 'POST' && pathname === '/api/rescan') { + currentAnalyzed = await analyzeCurrentRepo(); + const snap = rebuildSnapshot({ preserveBaselineHashes: true }); + const activityEntry = pushActivity( + 'repo', + `手动触发增量重扫完成 (${currentAnalyzed.elapsedMs}ms · 待同步 ${snap.sync.stalePages.length} 篇)`, + ); + broadcastSse('repo_changed', { + stats: snap.stats, + gitHead: snap.gitHead, + sync: snap.sync, + graph: snap.graph, + descriptions: snap.descriptions, + activityEntry, + elapsedMs: currentAnalyzed.elapsedMs, + }); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ ok: true, elapsedMs: currentAnalyzed.elapsedMs, sync: snap.sync })); + return; + } + + if (req.method === 'POST' && pathname === '/api/ack-sync') { + suppressWikiWatchUntil = Date.now() + 400; + const syncRes = syncWikiAstDeterministic(repoRoot, wikiDir); + currentAnalyzed = await analyzeCurrentRepo(); + // "核验" = a person checked the prose against the new code: fix line numbers first, + // then re-record the anchors of the chapter(s) they confirmed (?page=… or every stale one). + const onlyPage = new URL(req.url, 'http://x').searchParams.get('page'); + const accepted = acceptWikiPages(repoRoot, wikiDir, currentAnalyzed.index, onlyPage ? [onlyPage] : null); + const snap = rebuildSnapshot({ preserveBaselineHashes: true }); + const activityEntry = pushActivity( + 'wiki', + `行号同步 ${syncRes.reanchoredCitations} 处,已核对 ${onlyPage ? onlyPage : `${accepted.length} 篇`}(${syncRes.elapsedMs}ms,0 Token)`, + ); + broadcastSse('wiki_updated', { + pages: snap.pages, + sync: snap.sync, + activityEntry, + toast: `AST 自愈同步完成 · 修复 ${syncRes.reanchoredCitations} 处偏移行号`, + }); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ ok: true, syncRes, sync: snap.sync })); + return; + } + + res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); + res.end('Not Found'); + } catch (err) { + res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify({ error: err instanceof Error ? err.message : String(err) })); + } + }); + + // ─── File Watchers (Repo Source Tree + Wiki Markdown Tree) ─── + const relWiki = path.relative(repoRoot, wikiDir).replace(/\\/gu, '/'); + const relWikiInsideRepo = !relWiki.startsWith('..') && !path.isAbsolute(relWiki) ? relWiki : null; + + let repoDebounceTimer = null; + const pendingRepoFiles = new Set(); + let wikiDebounceTimer = null; + const pendingWikiDocs = new Set(); + + const watchers = []; + + try { + const repoWatcher = watch(repoRoot, { recursive: true }, (_eventType, filename) => { + if (!filename) return; + const norm = String(filename).replace(/\\/gu, '/'); + if (shouldIgnoreRepoWatchPath(norm, relWikiInsideRepo)) return; + pendingRepoFiles.add(norm); + if (repoDebounceTimer) clearTimeout(repoDebounceTimer); + repoDebounceTimer = setTimeout(async () => { + const batch = [...pendingRepoFiles]; + pendingRepoFiles.clear(); + try { + currentAnalyzed = await analyzeCurrentRepo(); + const snap = rebuildSnapshot({ preserveBaselineHashes: true }); + const shortList = batch.slice(0, 2).map((f) => path.posix.basename(f)).join(', '); + const staleLen = snap.sync.stalePages.length; + const activityEntry = pushActivity( + 'repo', + `源码变更 ${shortList}${batch.length > 2 ? ` 等 ${batch.length} 项` : ''} · 增量重算 ${currentAnalyzed.elapsedMs}ms${staleLen > 0 ? ` · ${staleLen} 篇章节受影响` : ''}`, + ); + broadcastSse('repo_changed', { + changedBatch: batch, + stats: snap.stats, + gitHead: snap.gitHead, + sync: snap.sync, + graph: snap.graph, + descriptions: snap.descriptions, + descriptions: snap.descriptions, + activityEntry, + elapsedMs: currentAnalyzed.elapsedMs, + toast: `源码已重索引 (${currentAnalyzed.elapsedMs}ms) · ${shortList}`, + }); + } catch { + // Ignore transient partial file writes + } + }, 170); + }); + watchers.push(repoWatcher); + } catch { + // Platform fallback if recursive fs.watch unsupported + } + + try { + const wikiWatcher = watch(wikiDir, { recursive: true }, (_eventType, filename) => { + if (!filename) return; + const norm = String(filename).replace(/\\/gu, '/'); + // Markdown chapters and the optional one-line descriptions file both hot-reload. + if (!norm.endsWith('.md') && norm !== 'descriptions.json') return; + pendingWikiDocs.add(norm); + if (wikiDebounceTimer) clearTimeout(wikiDebounceTimer); + wikiDebounceTimer = setTimeout(() => { + const docs = [...pendingWikiDocs]; + pendingWikiDocs.clear(); + try { + if (listMarkdownWikiPages(wikiDir).length === 0) return; + const snap = rebuildSnapshot({ preserveBaselineHashes: true }); + const label = docs[0]; + const activityEntry = pushActivity('wiki', `文档热重载 · ${label}`); + broadcastSse('wiki_updated', { + updatedDocs: docs, + pages: snap.pages, + sync: snap.sync, + descriptions: snap.descriptions, + activityEntry, + toast: `文档已实时热更新 · ${label}`, + }); + } catch { + // Ignore transient write + } + }, 95); + }); + watchers.push(wikiWatcher); + } catch { + // Non-fatal + } + + const heartbeatInterval = setInterval(() => { + broadcastSse('ping', { ts: Date.now() }); + }, 15000); + heartbeatInterval.unref?.(); + + // Bind port (with optional automatic fallback if requested port is busy) + const actualPort = await new Promise((resolve, reject) => { + let attemptPort = requestedPort; + let tries = 0; + const tryListen = () => { + const onError = (err) => { + server.removeListener('listening', onListening); + if (err && err.code === 'EADDRINUSE' && allowPortFallback && requestedPort !== 0 && tries < 10) { + tries += 1; + attemptPort += 1; + tryListen(); + } else { + reject(err); + } + }; + const onListening = () => { + server.removeListener('error', onError); + const addr = server.address(); + resolve(typeof addr === 'object' && addr ? addr.port : attemptPort); + }; + server.once('error', onError); + server.once('listening', onListening); + server.listen(attemptPort, host); + }; + tryListen(); + }); + + const url = `http://${host}:${actualPort}`; + + return { + url, + host, + port: actualPort, + repoRoot, + wikiDir, + getSnapshot: () => currentPortal, + close: () => + new Promise((resolve) => { + clearInterval(heartbeatInterval); + if (repoDebounceTimer) clearTimeout(repoDebounceTimer); + if (wikiDebounceTimer) clearTimeout(wikiDebounceTimer); + for (const w of watchers) { + try { + w.close(); + } catch { + // Ignore + } + } + for (const client of sseClients) { + try { + client.end(); + } catch { + // Ignore + } + } + sseClients.clear(); + server.close(() => resolve()); + }), + }; +} diff --git a/plugins/Jialei-03/mcode-repowiki/server/main.mjs b/plugins/Jialei-03/mcode-repowiki/server/main.mjs new file mode 100755 index 00000000..0eca2eda --- /dev/null +++ b/plugins/Jialei-03/mcode-repowiki/server/main.mjs @@ -0,0 +1,725 @@ +#!/usr/bin/env node +import { existsSync, mkdirSync, realpathSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { ParseCache } from './cache.mjs'; +import { + analyzeArchitectureMetrics, + buildRepositoryIndex, + computePersonalizedPageRank, +} from './graph.mjs'; +import { startLiveWikiServer } from './live-server.mjs'; +import { createWikiBlueprint, DEFAULT_MAX_MODULES, extractModuleEvidencePack } from './planner.mjs'; +import { compileInteractiveWikiSite } from './site-builder.mjs'; +import { lintWikiPage } from './lint.mjs'; +import { + acceptWikiPages, + ensureGitExclude, + inspectAndQueryWiki, + installPostCommitHook, + inspectFileSymbolsFast, + locateCodeFromWikiFast, + resolveWikiDir, + syncWikiAstDeterministic, + writeVerifiedWikiPage, +} from './sync.mjs'; + +const SERVER_NAME = 'mcode-repowiki'; +const SERVER_VERSION = '0.6.0'; + +const sharedCache = new ParseCache(); +const contextMemo = new Map(); +const activeLiveServers = new Map(); +const MEMO_TTL_MS = 12000; + +async function getAnalyzedRepo(repoRoot, options = {}) { + const absRoot = path.resolve(repoRoot); + if (!existsSync(absRoot) || !statSync(absRoot).isDirectory()) { + throw new Error(`Repository path does not exist or is not a directory: ${absRoot}`); + } + const key = `${absRoot}::${options.maxModules ?? DEFAULT_MAX_MODULES}`; + const now = Date.now(); + const hit = contextMemo.get(key); + if (hit && now - hit.ts < MEMO_TTL_MS && !options.forceRefresh) { + return hit.value; + } + + const index = await buildRepositoryIndex(absRoot, { includeTests: true }, sharedCache); + const ppr = computePersonalizedPageRank(index); + const arch = analyzeArchitectureMetrics(index, ppr.ranks); + const blueprint = createWikiBlueprint(index, arch, ppr, { + maxModules: options.maxModules ?? DEFAULT_MAX_MODULES, + }); + + const value = { index, ppr, arch, blueprint }; + contextMemo.set(key, { ts: now, value }); + if (contextMemo.size > 6) { + contextMemo.delete(contextMemo.keys().next().value); + } + return value; +} + +function resolveTargetRepoPath(args = {}) { + for (const cand of [args.repo_path, process.env.MINIMAX_PROJECT_DIR, process.cwd()]) { + if (typeof cand === 'string' && cand.trim()) return path.resolve(cand.trim()); + } + return process.cwd(); +} + +// ─── MCP Tool Schema Definitions ──────────────────────────────────────────── + +export const TOOL_DEFINITIONS = [ + { + name: 'wiki_locate', + description: + 'Call FIRST for any code question and before any code change (adding a feature, fixing, refactoring, impact analysis), even if the package or folder is known; replaces rounds of grep/glob/read. `query`: verified [file:L-L] targets with live code. `file` (a file or folder): symbol outline, its package and test scripts, and every file that imports it, grouped by package. `file` + `symbol`: the exact current body, where it is re-exported, and every file that imports it (resolved through package entries and re-exports, with line numbers; same-named words that are not imports are left out) — use it to copy an existing sibling or to list what a change breaks.', + inputSchema: { + type: 'object', + properties: { + repo_path: { type: 'string', description: 'Absolute repo root path.' }, + query: { type: 'string', description: 'Search query (keywords, question, or symbol).' }, + queries: { + type: 'array', + items: { type: 'string' }, + description: 'Batch multiple subsystem queries in one call.', + }, + file: { + type: 'string', + description: 'Relative file or folder path: omit symbol for the outline and importers; pass symbol for its body and importers.', + }, + symbol: { + type: 'string', + description: 'Optional exact symbol name (e.g. "SessionEntry") to inspect body or trace downstream reference lines.', + }, + wiki_dir: { type: 'string', description: 'Optional Wiki directory.' }, + }, + required: ['repo_path'], + additionalProperties: false, + }, + }, + { + name: 'wiki_plan', + description: + 'Inspect architecture & Wiki freshness: omit module_id for repo blueprint + freshness report (which chapter cites code that changed, and how to update it); pass module_id ("architecture" or a module ID) for its grounded code evidence pack; pass sync:true for 0-token line-number healing; pass mark_reviewed to confirm chapters are still correct.', + inputSchema: { + type: 'object', + properties: { + repo_path: { type: 'string', description: 'Absolute repo root path.' }, + module_id: { type: 'string', description: 'Optional module ID (or "architecture") to fetch code evidence.' }, + sync: { type: 'boolean', description: 'Run 0-token AST line-drift sync and update delta symbol index, then report chapters whose cited code changed.' }, + mark_reviewed: { + type: 'array', + items: { type: 'string' }, + description: 'Chapter paths (or ["all"]) you checked against the current code and found still correct; clears their "cited code changed" flag without rewriting them.', + }, + max_modules: { type: 'integer', minimum: 2, maximum: 10, description: 'Max L3 modules (default 10; packages with >= 10% of the code always get their own chapter).' }, + max_excerpt_chars: { type: 'integer', minimum: 3000, maximum: 36000, description: 'Excerpt char budget.' }, + wiki_dir: { type: 'string', description: 'Optional Wiki directory.' }, + }, + required: ['repo_path'], + additionalProperties: false, + }, + }, + { + name: 'wiki_write_page', + description: 'Write a `.repowiki/*.md` chapter. Checks every `[file:L-L]` citation against the code, records which symbol each one points at (so line numbers follow later code moves), and returns writing-quality warnings to fix in a follow-up call.', + inputSchema: { + type: 'object', + properties: { + repo_path: { type: 'string', description: 'Absolute repo root path.' }, + page_path: { type: 'string', description: 'Relative .md path inside Wiki.' }, + title: { type: 'string', description: 'Chapter title.' }, + content: { type: 'string', description: 'Markdown content.' }, + wiki_dir: { type: 'string', description: 'Optional Wiki directory.' }, + }, + required: ['repo_path', 'page_path', 'content'], + additionalProperties: false, + }, + }, + { + name: 'wiki_serve', + description: + 'Compile `.repowiki/index.html` + blast-radius index and start/stop the local real-time Wiki server (`http://127.0.0.1:`). Set build_only:true to compile without starting a server.', + inputSchema: { + type: 'object', + properties: { + repo_path: { type: 'string', description: 'Absolute repo root path.' }, + port: { type: 'integer', minimum: 1024, maximum: 65535, description: 'Port (default 4321).' }, + build_only: { type: 'boolean', description: 'Compile HTML + impact index only without starting a server.' }, + stop: { type: 'boolean', description: 'Stop running server.' }, + wiki_dir: { type: 'string', description: 'Optional Wiki directory.' }, + }, + required: ['repo_path'], + additionalProperties: false, + }, + }, +]; + +export function getAdvertisedTools() { + if (String(process.env.REPOWIKI_MCP_MODE || '').toLowerCase() === 'router') { + return TOOL_DEFINITIONS.filter((t) => t.name === 'wiki_locate' || t.name === 'wiki_plan'); + } + return TOOL_DEFINITIONS; +} + +// ─── Tool Execution Dispatcher ────────────────────────────────────────────── + +/** Agent-facing freshness report: which chapters cite code that changed, and what to do. */ +function formatFreshness(status) { + if (!status?.exists || !status.totalPages) return []; + const stale = status.stalePages || []; + const moved = status.linesNeedingSync || []; + const lines = [ + '## Wiki Freshness', + `- ${status.freshPages.length}/${status.totalPages} chapters match the code they cite.`, + ]; + if (moved.length > 0) { + const n = moved.reduce((a, m) => a + m.citations.length, 0); + lines.push(`- ${n} citation(s) in ${moved.length} chapter(s) only moved lines: \`wiki_plan\` with \`sync: true\` fixes them (0 tokens).`); + } + if (stale.length === 0) { + if (moved.length === 0) lines.push('- No cited code has changed since the chapters were written.'); + return lines; + } + lines.push(`- ${stale.length} chapter(s) cite code that has changed since they were written; their prose may be out of date:`); + for (const sp of stale.slice(0, 12)) { + lines.push(` - \`${sp.page}\``); + const items = [ + ...(sp.changedCitations || []).map((c) => `changed: ${c.symbol ? `\`${c.symbol}\` ` : ''}\`${c.file}:${c.lines}\``), + ...(sp.brokenCitations || []).map((c) => `${c.reason === 'file-missing' ? 'file gone' : 'range gone'}: \`${c.file}:${c.lines}\``), + ]; + if (items.length === 0) items.push(`source changed: ${sp.dirtySourceFiles.map((f) => `\`${f}\``).join(', ')}`); + for (const it of items.slice(0, 6)) lines.push(` - ${it}`); + if (items.length > 6) lines.push(` - … ${items.length - 6} more`); + } + lines.push( + '', + '### How to update these chapters', + '1. `wiki_plan` with `sync: true` first, so every line number is current.', + '2. For each changed citation: `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, keep everything else, and save the whole chapter with `wiki_write_page` (this re-records its citations).', + '4. If a chapter is still correct as written, call `wiki_plan` with `mark_reviewed: [""]` instead of rewriting it.', + ); + return lines; +} + +function enableAutoSync(repoRoot, wikiDir) { + try { + ensureGitExclude(repoRoot, wikiDir); + return installPostCommitHook(repoRoot); + } catch { + return { installed: false }; + } +} + +function formatBlueprintOutput(bp, wikiDir) { + const lines = []; + lines.push(`# Repo Wiki Blueprint: ${bp.repoName}`); + lines.push(`- **Repository Root**: \`${bp.repoRoot}\``); + lines.push(`- **Wiki Output Directory**: \`${wikiDir}\``); + lines.push(`- **Scale**: ${bp.stats.fileCount} files · ${bp.stats.totalLines.toLocaleString()} LOC · ${bp.stats.totalSymbols.toLocaleString()} AST symbols (analyzed in ${bp.stats.elapsedMs}ms)`); + const langs = Object.entries(bp.languageCounts) + .sort((a, b) => b[1] - a[1]) + .map(([l, c]) => `${l} (${c})`) + .join(', '); + lines.push(`- **Languages**: ${langs}`); + if (bp.workspaceMeta.primaryTechStack.length > 0) { + lines.push(`- **Tech Stack**: ${bp.workspaceMeta.primaryTechStack.join(', ')}`); + } + if (bp.workspaceMeta.packages.length > 1) { + lines.push( + `- **Monorepo Packages (${bp.workspaceMeta.packages.length})**: ${bp.workspaceMeta.packages.slice(0, 12).map((p) => `\`${p.name}\` (${p.dir || '.'})`).join(', ')}`, + ); + } + lines.push(''); + + if (bp.rootReadmePreview) { + lines.push('## Existing Project README Excerpt'); + lines.push('```text'); + lines.push(bp.rootReadmePreview.slice(0, 1100)); + lines.push('```'); + lines.push(''); + } + + lines.push('## Grounded System Architecture Diagram (Embed & Refine in `01-architecture/01-system-overview.md`)'); + lines.push('```mermaid'); + lines.push(bp.architectureMermaid); + lines.push('```'); + lines.push(''); + + lines.push('## Partitioned Core Modules (Call `wiki_plan` with `module_id` for Each)'); + for (const m of bp.modules) { + lines.push( + `- **\`${m.id}\` (${m.title})** — ${m.layerKind} · ${m.fileCount} files, ${m.lineCount.toLocaleString()} LOC, PageRank ${m.pageRankPct}%, in:${m.fanIn}/out:${m.fanOut}, $I=${m.instability}$ · key files: ${m.topFiles.slice(0, 4).map((f) => `\`${f}\``).join(', ')}`, + ); + } + lines.push(''); + + if (bp.cycles.length > 0) { + lines.push(`## Circular Dependency Findings (${bp.cycles.length} cycle(s) — Document in \`01-architecture/03-dependencies-and-boundaries.md\`)`); + for (const c of bp.cycles.slice(0, 5)) { + lines.push(`- Cycle (${c.size} files): ${c.witnessCycle.map((p) => `\`${p}\``).join(' → ')}`); + } + lines.push(''); + } else { + lines.push('## Circular Dependency Findings\n- **0 circular import cycles detected** (Clean DAG).\n'); + } + + lines.push(`## Planned 4-Level Hierarchical Wiki Pages (${bp.pages.length} Chapters)`); + for (const p of bp.pages) { + const modTag = p.moduleId ? ` [module_id: \`${p.moduleId}\`]` : ''; + lines.push(`- **[L${p.level} · ${p.section}]** \`${p.docPath}\` — **${p.title}**${modTag}\n _${p.purpose}_`); + } + lines.push(''); + lines.push( + '> **Next Step**: Call `wiki_plan` with `module_id: "architecture"` and then with each `module_id` above to get its code evidence pack (delegate modules in parallel to subagents on large repos). Read the key files it lists, write every planned page via `wiki_write_page` in the user\'s language — follow the overview and module chapter structures in the skill, and fix the **Writing Checks** each `wiki_write_page` call returns — then compile and open the reader via `wiki_serve`.', + ); + + return `${lines.join('\n')}\n`; +} + +export async function executeTool(name, rawArgs = {}) { + const repoRoot = resolveTargetRepoPath(rawArgs); + const wikiDir = resolveWikiDir(repoRoot, rawArgs.wiki_dir); + + if (name === 'wiki_locate') { + const explicitSymbol = rawArgs.symbol ? String(rawArgs.symbol).trim() : ''; + if (rawArgs.file) { + return inspectFileSymbolsFast(repoRoot, wikiDir, String(rawArgs.file), explicitSymbol); + } + const batch = Array.isArray(rawArgs.queries) && rawArgs.queries.length > 0 + ? rawArgs.queries.map((x) => String(x).trim()).filter(Boolean) + : rawArgs.query + ? [String(rawArgs.query).trim()] + : explicitSymbol + ? [explicitSymbol] + : []; + if (batch.length === 0) throw new Error('`query`, `queries`, or `symbol` is required for wiki_locate.'); + + if (batch.length > 1) { + const parts = batch.slice(0, 6).map((qItem, idx) => { + const hit = locateCodeFromWikiFast(repoRoot, wikiDir, qItem, 3, { symbol: explicitSymbol }); + return `## Batch Query ${idx + 1}: "${qItem}"\n${hit || 'No Wiki index found.'}`; + }); + return `${parts.join('\n\n---\n\n')}\n`; + } + + const q = batch[0]; + const fastHit = locateCodeFromWikiFast(repoRoot, wikiDir, q, 6, { symbol: explicitSymbol }); + if (fastHit) return `${fastHit}\n`; + + // Fallback when no .repowiki exists yet: rank AST symbols & PageRank hubs directly! + const { index, ppr } = await getAnalyzedRepo(repoRoot); + const qLower = q.toLowerCase(); + const hits = []; + for (let i = 0; i < index.files.length; i += 1) { + const f = index.files[i]; + if (f.isTest) continue; + const pf = index.parsedFiles[i]; + const baseBoost = f.relPath.toLowerCase().includes(qLower) ? 10 : 0; + for (const s of pf.symbols) { + if (baseBoost > 0 || s.signature.toLowerCase().includes(qLower)) { + hits.push({ + relPath: f.relPath, + lineStart: s.lineStart, + lineEnd: s.lineEnd, + sig: s.signature, + score: baseBoost + (ppr.ranks[i] ?? 0) * 100, + }); + } + } + } + hits.sort((a, b) => b.score - a.score); + const lines = [`# RepoWiki AST Fallback Router (No .repowiki built yet)`]; + for (const h of hits.slice(0, 6)) { + lines.push(`- \`${h.relPath}\` **L${h.lineStart}-L${h.lineEnd}** — \`${h.sig}\``); + } + return `${lines.join('\n')}\n`; + } + + if (name === 'wiki_plan') { + if (Array.isArray(rawArgs.mark_reviewed) && rawArgs.mark_reviewed.length > 0) { + const { index } = await getAnalyzedRepo(repoRoot, { forceRefresh: true }); + const all = rawArgs.mark_reviewed.includes('all'); + const accepted = acceptWikiPages(repoRoot, wikiDir, index, all ? null : rawArgs.mark_reviewed); + const status = inspectAndQueryWiki(repoRoot, wikiDir, index, ''); + return [ + `Marked ${accepted.length} chapter(s) as checked against the current code: ${accepted.map((p) => `\`${p}\``).join(', ') || 'none (check the paths)'}.`, + '', + ...formatFreshness(status), + '', + ].join('\n'); + } + if (rawArgs.sync) { + const syncRes = syncWikiAstDeterministic(repoRoot, wikiDir); + const { index } = await getAnalyzedRepo(repoRoot, { forceRefresh: true }); + const status = inspectAndQueryWiki(repoRoot, wikiDir, index, ''); + return [ + `# Line Sync Completed (${syncRes.elapsedMs}ms, 0 tokens)`, + `- **Changed files re-parsed**: ${syncRes.syncedFiles.length} (${syncRes.syncedFiles.slice(0, 6).join(', ') || 'none'})`, + `- **Citations moved to their code's new lines**: ${syncRes.reanchoredCitations}`, + '', + ...formatFreshness(status), + '', + ].join('\n'); + } + if (rawArgs.module_id) { + const { index, ppr, blueprint } = await getAnalyzedRepo(repoRoot, { maxModules: rawArgs.max_modules }); + return extractModuleEvidencePack(index, ppr, blueprint, rawArgs.module_id, { + maxExcerptChars: rawArgs.max_excerpt_chars, + }); + } + mkdirSync(wikiDir, { recursive: true }); + const { index, blueprint } = await getAnalyzedRepo(repoRoot, { maxModules: rawArgs.max_modules }); + const status = inspectAndQueryWiki(repoRoot, wikiDir, index, ''); + let prefix = ''; + if (status.exists && status.totalPages > 0) { + const staleNote = + status.stalePages.length > 0 + ? `${status.stalePages.length} stale (${status.stalePages.map((s) => `\`${s.page}\``).slice(0, 5).join(', ')})` + : `all ${status.totalPages} chapters fresh`; + prefix = [ + `> **Existing RepoWiki Detected**: ${status.freshPages.length}/${status.totalPages} fresh — ${staleNote}. Update only the chapters listed below instead of regenerating the Wiki.`, + '', + ...formatFreshness(status), + '', + '---', + '', + ].join('\n'); + } + return `${prefix}${formatBlueprintOutput(blueprint, wikiDir)}`; + } + + if (name === 'wiki_module_context') { + if (!rawArgs.module_id) throw new Error('`module_id` is required.'); + const { index, ppr, blueprint } = await getAnalyzedRepo(repoRoot); + return extractModuleEvidencePack(index, ppr, blueprint, rawArgs.module_id, { + maxExcerptChars: rawArgs.max_excerpt_chars, + }); + } + + if (name === 'wiki_write_page') { + if (!rawArgs.page_path || !rawArgs.content) { + throw new Error('Both `page_path` and `content` are required.'); + } + const { index } = await getAnalyzedRepo(repoRoot); + const res = writeVerifiedWikiPage( + { + repoRoot, + wikiDir, + pagePath: rawArgs.page_path, + title: rawArgs.title, + content: rawArgs.content, + }, + index, + ); + const lines = [ + `Saved Wiki chapter: \`${res.pagePath}\` ("${res.title}")`, + `- **Location**: \`${res.absPath}\``, + `- **Verified Source Citations**: ${res.citationCount} (${res.referencedFiles.length} distinct repo files linked in manifest.json)`, + ]; + if (res.warnings.length > 0) { + lines.push(`- **Citation / Diagram Warnings (${res.warnings.length})**:`); + for (const w of res.warnings.slice(0, 8)) lines.push(` - ${w}`); + } + const quality = lintWikiPage(res.pagePath, res.markdown, res.anchors); + if (quality.length > 0) { + lines.push(`- **Writing Checks (${quality.length})** — fix these and call \`wiki_write_page\` again with the whole chapter:`); + for (const w of quality.slice(0, 8)) lines.push(` - ${w}`); + } else { + lines.push('- **Writing Checks**: passed.'); + } + return `${lines.join('\n')}\n`; + } + + if (name === 'wiki_build_site') { + const { index, arch, ppr } = await getAnalyzedRepo(repoRoot); + const built = compileInteractiveWikiSite(index, arch, ppr, wikiDir); + const fileUrl = pathToFileURL(built.htmlPath).href; + const lines = [ + `# Interactive Repo Wiki Compiled Successfully`, + `- **Portal HTML**: \`${built.htmlPath}\``, + `- **Browser URL**: ${fileUrl}`, + `- **Chapters Bundled**: ${built.pageCount} multi-level Markdown documents`, + `- **Embedded Source Citation Windows**: ${built.snippetCount} clickable code previews`, + ]; + if (built.warnings.length > 0) { + lines.push(`- **Citation Audit Notes (${built.warnings.length})**:`); + for (const w of built.warnings.slice(0, 6)) lines.push(` - ${w}`); + } + lines.push(''); + lines.push( + `Open \`${fileUrl}\` in the MiniMax Code Built-in Browser (or any browser) to read the multi-level Repo Wiki, inspect clickable \`[file:Lstart-Lend]\` source drawers, view SVG architecture/sequence diagrams, and explore the interactive dependency graph.`, + ); + return `${lines.join('\n')}\n`; + } + + if (name === 'wiki_status') { + if (rawArgs.auto_sync) { + const syncRes = syncWikiAstDeterministic(repoRoot, wikiDir); + return [ + `# Deterministic Zero-Token AST Sync Completed (${syncRes.elapsedMs}ms)`, + `- **Synced Changed/New Files**: ${syncRes.syncedFiles.length} (${syncRes.syncedFiles.slice(0, 6).join(', ') || 'none'})`, + `- **Re-anchored Shifted Markdown Citations**: ${syncRes.reanchoredCitations}`, + `- **Delta Symbol Index Page**: ${syncRes.deltaPagePath || 'unchanged'}`, + '', + ].join('\n'); + } + const { index } = await getAnalyzedRepo(repoRoot); + const status = inspectAndQueryWiki(repoRoot, wikiDir, index, rawArgs.query ?? ''); + if (!status.exists) return `${status.message}\n`; + + const lines = [ + `# Repo Wiki Status: ${index.repoName}`, + `- **Wiki Directory**: \`${status.wikiDir}\``, + `- **Git Sync**: recorded \`${status.recordedGitHead ?? 'n/a'}\` vs current \`${status.currentGitHead ?? 'n/a'}\``, + `- **Fresh Chapters**: ${status.freshPages.length} / ${status.totalPages}`, + ]; + lines.push('', ...formatFreshness(status)); + if (status.searchHits.length > 0) { + lines.push('', `## Wiki Search Matches (${status.searchHits.length})`); + for (const h of status.searchHits) { + lines.push(`### \`${h.page}\` — ${h.heading}`); + lines.push(h.snippet); + lines.push(''); + } + } + return `${lines.join('\n')}\n`; + } + + if (name === 'wiki_serve') { + // Line numbers are re-synced after every commit by a post-commit hook (0 tokens). + const hook = rawArgs.stop ? null : enableAutoSync(repoRoot, wikiDir); + const hookLine = hook + ? hook.installed + ? '- **Auto-Sync After Commit**: on (`.git/hooks/post-commit`; remove with `node server/cli.mjs hook remove `).' + : '- **Auto-Sync After Commit**: off (not a Git repository) — run `wiki_plan` with `sync: true` after code changes.' + : ''; + if (rawArgs.build_only) { + const built = await executeTool('wiki_build_site', { repo_path: repoRoot, wiki_dir: wikiDir }); + return `${built}${hookLine}\n`; + } + const srvKey = `${repoRoot}::${wikiDir}`; + if (rawArgs.stop) { + const existing = activeLiveServers.get(srvKey); + if (!existing) return `No active RepoWiki Live Server was running for \`${repoRoot}\`.\n`; + await existing.close(); + activeLiveServers.delete(srvKey); + return `Stopped RepoWiki Live Server for \`${repoRoot}\`.\n`; + } + + let inst = activeLiveServers.get(srvKey); + if (!inst) { + inst = await startLiveWikiServer({ + repoRoot, + wikiDir, + port: rawArgs.port ?? 4321, + cache: sharedCache, + autoInit: true, + writeDiskHtml: true, + }); + activeLiveServers.set(srvKey, inst); + } + + const snap = inst.getSnapshot(); + return [ + `# RepoWiki Real-Time Server Active`, + `- **Live URL**: ${inst.url}`, + `- **Repository Watched**: \`${inst.repoRoot}\` (${snap.stats.fileCount} files)`, + `- **Wiki Directory**: \`${inst.wikiDir}\` (${snap.pages.length} chapters)`, + `- **Real-Time Capabilities**:`, + ` 1. Editing any repository source file triggers incremental AST + PageRank + SHA-1 drift tracking over SSE in <50ms.`, + ` 2. Writing or editing any \`.md\` chapter via \`wiki_write_page\` hot-reloads open browsers in place without page refresh.`, + ` 3. Clicking any source citation pill streams live lines directly from disk (\`/api/file\`).`, + hookLine, + '', + ].join('\n'); + } + + throw new Error(`Unknown tool: ${name}`); +} + +// ─── JSON-RPC 2.0 Dual-Framing Stdio Server ───────────────────────────────── + +async function handleJsonRpcMessage(msg) { + if (!msg || typeof msg !== 'object') return null; + if (msg.id === undefined || msg.id === null) return null; + + const { id, method, params } = msg; + + try { + if (method === 'initialize') { + const clientProto = params?.protocolVersion; + const supported = ['2025-06-18', '2025-03-26', '2024-11-05']; + const protocolVersion = supported.includes(clientProto) ? clientProto : '2024-11-05'; + return { + jsonrpc: '2.0', + id, + result: { + protocolVersion, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: SERVER_NAME, version: SERVER_VERSION }, + }, + }; + } + + if (method === 'ping') return { jsonrpc: '2.0', id, result: {} }; + if (method === 'tools/list') return { jsonrpc: '2.0', id, result: { tools: getAdvertisedTools() } }; + + if (method === 'tools/call') { + try { + const text = await executeTool(params?.name, params?.arguments ?? {}); + return { + jsonrpc: '2.0', + id, + result: { content: [{ type: 'text', text }], isError: false }, + }; + } catch (toolErr) { + return { + jsonrpc: '2.0', + id, + result: { content: [{ type: 'text', text: `RepoWiki error: ${toolErr.message}` }], isError: true }, + }; + } + } + + if (method === 'resources/list') return { jsonrpc: '2.0', id, result: { resources: [] } }; + if (method === 'prompts/list') return { jsonrpc: '2.0', id, result: { prompts: [] } }; + + return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${String(method)}` } }; + } catch (err) { + return { jsonrpc: '2.0', id, error: { code: -32603, message: err?.message ?? 'Internal server error' } }; + } +} + +export function startStdioServer() { + let buffer = Buffer.alloc(0); + let framingMode = null; + let chain = Promise.resolve(); + + const sendResponse = (payload) => { + if (!payload) return; + const json = JSON.stringify(payload); + if (framingMode === 'content-length') { + process.stdout.write(`Content-Length: ${Buffer.byteLength(json, 'utf8')}\r\n\r\n${json}`); + } else { + process.stdout.write(`${json}\n`); + } + }; + + const dispatchParsed = (rawJson) => { + let parsed; + try { + parsed = JSON.parse(rawJson); + } catch { + return; + } + chain = chain.then(async () => { + if (Array.isArray(parsed)) { + const replies = (await Promise.all(parsed.map(handleJsonRpcMessage))).filter(Boolean); + if (replies.length > 0) sendResponse(replies); + } else { + const reply = await handleJsonRpcMessage(parsed); + if (reply) sendResponse(reply); + } + }); + }; + + const drain = () => { + while (buffer.length > 0) { + if (!framingMode) { + const preview = buffer.subarray(0, Math.min(buffer.length, 32)).toString('utf8').trimStart(); + if (!preview) return; + framingMode = /^Content-Length:/iu.test(preview) ? 'content-length' : 'line'; + } + if (framingMode === 'content-length') { + const idxCR = buffer.indexOf('\r\n\r\n'); + const idxLF = buffer.indexOf('\n\n'); + let sepIdx = -1; + let sepLen = 4; + if (idxCR !== -1 && (idxLF === -1 || idxCR < idxLF)) { + sepIdx = idxCR; + sepLen = 4; + } else if (idxLF !== -1) { + sepIdx = idxLF; + sepLen = 2; + } + if (sepIdx === -1) return; + const m = buffer.subarray(0, sepIdx).toString('utf8').match(/Content-Length:\s*(\d+)/iu); + if (!m) { + buffer = buffer.subarray(sepIdx + sepLen); + continue; + } + const len = Number.parseInt(m[1], 10); + const start = sepIdx + sepLen; + if (buffer.length < start + len) return; + const body = buffer.subarray(start, start + len).toString('utf8'); + buffer = buffer.subarray(start + len); + dispatchParsed(body); + } else { + const nl = buffer.indexOf('\n'); + if (nl === -1) return; + const line = buffer.subarray(0, nl).toString('utf8').trim(); + buffer = buffer.subarray(nl + 1); + if (line) dispatchParsed(line); + } + } + }; + + process.stdin.on('data', (c) => { + buffer = Buffer.concat([buffer, c]); + drain(); + }); + process.stdin.on('end', () => { + chain.finally(async () => { + for (const srv of activeLiveServers.values()) { + await srv.close(); + } + activeLiveServers.clear(); + sharedCache.close(); + process.exit(0); + }); + }); +} + +// ─── CLI Mode (`node ./server/main.mjs --cli `) ─── + +async function runCli(argv) { + const [cmd = 'plan', target = process.cwd(), arg3] = argv; + const repoPath = path.resolve(target); + if (cmd === 'plan') { + process.stdout.write(await executeTool('wiki_plan', { repo_path: repoPath })); + } else if (cmd === 'context') { + process.stdout.write(await executeTool('wiki_module_context', { repo_path: repoPath, module_id: arg3 || 'architecture' })); + } else if (cmd === 'status') { + process.stdout.write(await executeTool('wiki_status', { repo_path: repoPath, query: arg3 })); + } else if (cmd === 'build') { + process.stdout.write(`${await executeTool('wiki_build_site', { repo_path: repoPath })}\n`); + } else { + process.stderr.write('Usage: node ./server/main.mjs --cli [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 = + ''; + svg += + ''; + actors.forEach((a, idx) => { + const cx = padX + colW * idx + colW / 2; + const boxW = Math.min(colW - 14, Math.max(96, measureTextPx(a.label, 12) + 22)); + svg += + ''; + svg += + ''; + svg += + '' + + esc(a.label) + + ''; + }); + msgs.forEach((m, idx) => { + const y = 80 + idx * 46; + if (m.isNote) { + const nw = Math.min(W - 60, Math.max(240, measureTextPx(m.text, 11.25) + 32)); + svg += + '' + + '' + + esc(m.text) + + ''; + return; + } + const a1 = actorMap.get(m.from); + const a2 = actorMap.get(m.to); + const x1 = padX + colW * a1.idx + colW / 2; + const x2 = padX + colW * a2.idx + colW / 2; + if (x1 === x2) { + svg += + ''; + svg += + '' + + esc(m.text) + + ''; + } else { + const midX = (x1 + x2) / 2; + const tw = measureTextPx(m.text, 11.25) + 12; + svg += + ''; + svg += + ''; + svg += + '' + + esc(m.text) + + ''; + } + }); + 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 = + ''; + svg += + ''; + + const subgraphHeaders = []; + subgraphs.forEach((sg) => { + const members = nodeArr.filter((n) => n.subgraphIdx === sg.idx); + if (members.length === 0) return; + const minX = Math.min(...members.map((m) => m.x - m.w / 2)) - 20; + const maxX = Math.max(...members.map((m) => m.x + m.w / 2)) + 20; + const minY = Math.min(...members.map((m) => m.y - m.h / 2)) - 26; + const maxY = Math.max(...members.map((m) => m.y + m.h / 2)) + 14; + const pillW = measureTextPx(sg.title, 11) + 16; + subgraphHeaders.push({ + cx: minX + 6 + pillW / 2, + cy: minY + 13, + w: pillW + 8, + h: 20, + pillX: minX + 6, + pillY: minY + 4, + pillW, + title: sg.title, + color: SUBGRAPH_COLORS[sg.idx % SUBGRAPH_COLORS.length], + }); + svg += + ''; + }); + + const edgeBadges = []; + edges.forEach((e, eIdx) => { + const a = nodes.get(e.u); + const b = nodes.get(e.v); + if (!a || !b || a === b) return; + let x1; + let y1; + let x2; + let y2; + if (isLR) { + const forward = b.x >= a.x; + x1 = forward ? a.x + a.w / 2 : a.x - a.w / 2; + y1 = a.y; + x2 = forward ? b.x - b.w / 2 : b.x + b.w / 2; + y2 = b.y; + } else { + const sameRow = Math.abs(a.y - b.y) < 10; + if (sameRow) { + const right = b.x >= a.x; + x1 = right ? a.x + a.w / 2 : a.x - a.w / 2; + y1 = a.y; + x2 = right ? b.x - b.w / 2 : b.x + b.w / 2; + y2 = b.y; + } else { + const downward = b.y >= a.y; + const portOffset = ((eIdx % 3) - 1) * 12; + x1 = a.x + portOffset; + y1 = downward ? a.y + a.h / 2 : a.y - a.h / 2; + x2 = b.x + portOffset * 0.5; + y2 = downward ? b.y - b.h / 2 : b.y + b.h / 2; + } + } + const cx1 = isLR ? (x1 + x2) / 2 : x1; + const cy1 = isLR ? y1 : (y1 + y2) / 2; + const cx2 = isLR ? (x1 + x2) / 2 : x2; + const cy2 = isLR ? y2 : (y1 + y2) / 2; + + svg += + ''; + + if (e.label) { + const evalBez = (tt) => { + const mt = 1 - tt; + return { + x: mt * mt * mt * x1 + 3 * mt * mt * tt * cx1 + 3 * mt * tt * tt * cx2 + tt * tt * tt * x2, + y: mt * mt * mt * y1 + 3 * mt * mt * tt * cy1 + 3 * mt * tt * tt * cy2 + tt * tt * tt * y2, + }; + }; + const spansMultipleLayers = Math.abs(b.layer - a.layer) > 1; + const candidateTs = spansMultipleLayers + ? eIdx % 2 === 0 + ? [0.22, 0.72, 0.30, 0.64] + : [0.72, 0.22, 0.64, 0.30] + : [0.32 + (eIdx % 3) * 0.08, 0.26, 0.44]; + const lw = measureTextPx(e.label, 10.25) + 12; + let chosen = evalBez(candidateTs[0]); + for (const tt of candidateTs) { + const pt = evalBez(tt); + const hitsNode = nodeArr.some( + (nd) => + Math.abs(pt.x - nd.x) < (lw + nd.w) / 2 + 4 && + Math.abs(pt.y - nd.y) < (18 + nd.h) / 2 + 4, + ); + const hitsHeader = subgraphHeaders.some( + (sh) => + Math.abs(pt.x - sh.cx) < (lw + sh.w) / 2 && + Math.abs(pt.y - sh.cy) < (18 + sh.h) / 2, + ); + const hitsBadge = edgeBadges.some( + (prev) => Math.abs(pt.x - prev.mx) < (lw + prev.lw) / 2 + 6 && Math.abs(pt.y - prev.my) < 19, + ); + if (!hitsNode && !hitsHeader && !hitsBadge) { + chosen = pt; + break; + } + } + let mx = chosen.x; + let my = chosen.y; + for (const prev of edgeBadges) { + if (Math.abs(mx - prev.mx) < (lw + prev.lw) / 2 + 4 && Math.abs(my - prev.my) < 18) { + my += 19; + } + } + edgeBadges.push({ mx, my, lw, label: e.label }); + } + }); + + for (const n of nodeArr) { + svg += + ''; + if (n.lines.length === 1) { + svg += + '' + + esc(n.lines[0]) + + ''; + } else { + svg += + '' + + esc(n.lines[0]) + + '' + + '' + + esc(n.lines[1]) + + ''; + } + } + + // Render subgraph title labels ON TOP of crossing connector lines so text is never crossed + for (const sh of subgraphHeaders) { + svg += + '' + + '' + + esc(sh.title) + + ''; + } + + for (const b of edgeBadges) { + svg += + '' + + '' + + esc(b.label) + + ''; + } + 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('') + + ''; + 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 += ''; + }); + 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 += '
    ' + renderInline(h) + '
    '; + 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 + ? '
    ' + + icon('chevronLeft', 12) + + '上一篇
    ' + + esc(cleanPlainTitle(prev.title)) + + '
    ' + : '
    ') + + (next + ? '
    下一篇' + + icon('chevronRight', 12) + + '
    ' + + esc(cleanPlainTitle(next.title)) + + '
    ' + : '
    '); + + 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) => + '' + SVG[name] + ''; + 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 }); + } +});