feat: AgentLens v0.1.0 — cross-agent config migration + adversarial code QA
Browse files- .gitignore +5 -0
- .npmignore +10 -0
- README.md +105 -0
- agentlens-0.1.0.vsix +0 -0
- docs/compose/spec/agentlens.md +163 -0
- ext/dsh-plugin/cordis.patch.yml +4 -0
- ext/dsh-plugin/index.js +131 -0
- ext/dsh-plugin/package.json +19 -0
- ext/vscode/agentlens-0.1.0.vsix +0 -0
- ext/vscode/build.js +21 -0
- ext/vscode/package.json +96 -0
- ext/vscode/src/extension.ts +351 -0
- ext/vscode/tsconfig.json +15 -0
- package-lock.json +0 -0
- package.json +41 -0
- src/checker/engine.ts +235 -0
- src/cli/commands/check.ts +78 -0
- src/cli/commands/drift.ts +83 -0
- src/cli/commands/install.ts +189 -0
- src/cli/commands/move.ts +91 -0
- src/cli/commands/scan.ts +71 -0
- src/cli/index.ts +74 -0
- src/core/types.ts +71 -0
- src/drift/detect.ts +89 -0
- src/index.ts +5 -0
- src/mcp/server.ts +182 -0
- src/migrator/generate.ts +113 -0
- src/parsers/base.ts +81 -0
- src/parsers/claude.ts +24 -0
- src/parsers/codex.ts +24 -0
- src/parsers/copilot.ts +24 -0
- src/parsers/cursor.ts +51 -0
- src/parsers/index.ts +20 -0
- src/parsers/windsurf.ts +43 -0
- tests/checker.test.ts +117 -0
- tests/drift.test.ts +78 -0
- tests/mcp.test.ts +19 -0
- tests/migrator.test.ts +81 -0
- tests/parsers-extra.test.ts +45 -0
- tests/parsers.test.ts +126 -0
- tsconfig.json +19 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
node_modules/
|
| 2 |
+
dist/
|
| 3 |
+
.worktrees/
|
| 4 |
+
*.log
|
| 5 |
+
.DS_Store
|
.npmignore
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
node_modules/
|
| 2 |
+
src/
|
| 3 |
+
tests/
|
| 4 |
+
docs/
|
| 5 |
+
.worktrees/
|
| 6 |
+
*.ts
|
| 7 |
+
!dist/**/*.d.ts
|
| 8 |
+
tsconfig.json
|
| 9 |
+
vitest.config.ts
|
| 10 |
+
research/
|
README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: AgentLens
|
| 3 |
+
license: mit
|
| 4 |
+
tags:
|
| 5 |
+
- ai-coding-agent
|
| 6 |
+
- developer-tools
|
| 7 |
+
- mcp
|
| 8 |
+
- config-migration
|
| 9 |
+
- code-review
|
| 10 |
+
- claude-code
|
| 11 |
+
- cursor
|
| 12 |
+
- codex
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# AgentLens
|
| 16 |
+
|
| 17 |
+
**Cross-agent config migration & adversarial code QA for AI coding agents.**
|
| 18 |
+
|
| 19 |
+
一个 CLI + MCP Server:把你积累的 AI Agent 规则习惯(CLAUDE.md / .cursor/rules / AGENTS.md / .windsurfrules / copilot-instructions)在 Claude Code、Cursor、Codex、Windsurf、ZCode、WorkBuddy、MiMo Desktop 之间一键搬家,并对 AI 写的代码做对抗式体检。全部本地运行,代码不出机器。
|
| 20 |
+
|
| 21 |
+
## 为什么做这个
|
| 22 |
+
|
| 23 |
+
- 每个 AI 编程 Agent 有自己的配置格式,换工具就要重写一遍规则
|
| 24 |
+
- 规则散落 N 个位置,改了这里忘了那里——"一模一样的烂规则副本还是烂规则"
|
| 25 |
+
- 46% 开发者不信任 AI 输出,66% 最大挫败是"几乎正确但不完全对",但没人把对抗式审查做成产品
|
| 26 |
+
|
| 27 |
+
## 功能
|
| 28 |
+
|
| 29 |
+
### 一键迁移
|
| 30 |
+
```bash
|
| 31 |
+
agentlens move --from claude --to cursor
|
| 32 |
+
```
|
| 33 |
+
所有 Agent 配置解析为统一中间表示(IR),语义级转换为目标格式。
|
| 34 |
+
|
| 35 |
+
### 配置漂移检测
|
| 36 |
+
```bash
|
| 37 |
+
agentlens drift
|
| 38 |
+
```
|
| 39 |
+
发现不同 Agent 配置里"意思相近但措辞不同"的规则,以及某个 Agent 缺失的规则类别。
|
| 40 |
+
|
| 41 |
+
### 对抗式代码体检
|
| 42 |
+
```bash
|
| 43 |
+
agentlens check src/index.ts # 单文件
|
| 44 |
+
agentlens check HEAD~1..HEAD # git diff
|
| 45 |
+
```
|
| 46 |
+
检查维度:安全(命令注入、SQL 注入、硬编码密钥、XSS、不安全连接)、正确性(空指针隐患、空 catch、宽松比较、TODO 残留)、风格、性能。
|
| 47 |
+
|
| 48 |
+
### 一键装进所有 Agent
|
| 49 |
+
```bash
|
| 50 |
+
agentlens install
|
| 51 |
+
```
|
| 52 |
+
自动检测本机已安装的 AI 工具(Claude Code、Cursor、Codex、ZCode、WorkBuddy、MiMo Desktop),写入各自的 MCP 配置。重启应用后在 MCP/工具设置里即可看到 4 个工具。
|
| 53 |
+
|
| 54 |
+
### 支持矩阵
|
| 55 |
+
|
| 56 |
+
| Agent | 配置文件 |
|
| 57 |
+
|---|---|
|
| 58 |
+
| Claude Code | `CLAUDE.md`、`.claude/rules/*.md`、`~/.claude/settings.json` (MCP) |
|
| 59 |
+
| Cursor | `.cursor/rules/*.mdc`、`.cursor/mcp.json` (MCP) |
|
| 60 |
+
| Codex | `AGENTS.md`、`.mcp.json` (MCP) |
|
| 61 |
+
| ZCode | `~/.zcode/mcp.json` (MCP) |
|
| 62 |
+
| WorkBuddy | `~/.workbuddy/mcp.json` (MCP) |
|
| 63 |
+
| MiMo Desktop | `~/.config/mimocode/mimocode.jsonc` (mcp 配置) |
|
| 64 |
+
| Windsurf | `.windsurfrules` |
|
| 65 |
+
| GitHub Copilot | `.github/copilot-instructions.md` |
|
| 66 |
+
|
| 67 |
+
另有 VS Code / Cursor 扩展(`.vsix`)和 DSH 插件(cordis),见仓库 `ext/` 目录。
|
| 68 |
+
|
| 69 |
+
## 安装
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
# CLI
|
| 73 |
+
npx agentlens --help
|
| 74 |
+
|
| 75 |
+
# 一键装进所有已安装的 Agent
|
| 76 |
+
npx agentlens install
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## 设计原则
|
| 80 |
+
|
| 81 |
+
- **纯本地**:无服务器、无账号、无遥测,代码永远不出你的机器
|
| 82 |
+
- **统一 IR**:所有 Agent 格式解析为同一套规则模型,迁移是语义级转换而非字符串复制
|
| 83 |
+
- **对抗视角**:体检引擎针对 AI 生成代码的典型缺陷设计("看着对,其实有坑")
|
| 84 |
+
|
| 85 |
+
## 项目结构
|
| 86 |
+
|
| 87 |
+
```
|
| 88 |
+
src/
|
| 89 |
+
├── core/ # IR 模型
|
| 90 |
+
├── parsers/ # 各 Agent 配置解析器(claude/cursor/codex/windsurf/copilot)
|
| 91 |
+
├── migrator/ # IR → 目标格式生成器
|
| 92 |
+
├── drift/ # 漂移检测引擎
|
| 93 |
+
├── checker/ # 对抗式体检引擎
|
| 94 |
+
├── mcp/ # MCP Server
|
| 95 |
+
├── install/ # 一键安装器
|
| 96 |
+
└── cli/ # CLI 入口
|
| 97 |
+
ext/
|
| 98 |
+
├── vscode/ # VS Code / Cursor 扩展(.vsix)
|
| 99 |
+
└── dsh-plugin/ # DSH cordis 插件
|
| 100 |
+
tests/ # 46 个测试
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
## License
|
| 104 |
+
|
| 105 |
+
MIT
|
agentlens-0.1.0.vsix
ADDED
|
Binary file (31 kB). View file
|
|
|
docs/compose/spec/agentlens.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
feature: agentlens
|
| 3 |
+
status: delivered
|
| 4 |
+
updated: 2026-11-19
|
| 5 |
+
source: agentlens
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
# AgentLens — AI 编程 Agent 配置迁移 + 产出体检
|
| 9 |
+
|
| 10 |
+
## Report
|
| 11 |
+
|
| 12 |
+
**What was built** — AgentLens v0.1.0: a CLI + MCP server for (1) cross-agent config migration (Claude/Cursor/Codex/Windsurf/Copilot), (2) config drift detection, and (3) adversarial code QA. All rules parsed into a unified IR and re-generated per target agent. Pure local, no server dependency.
|
| 13 |
+
|
| 14 |
+
**Verification** — `npm test`: 46/46 passing across 6 test files. `npx tsc --noEmit`: clean. `npm run build`: dist/ generated. E2E verified: scan (5 agents detected), move (claude→windsurf/cursor), drift (11 issues across 37 rules), check (3 critical vulnerabilities detected), install (auto-detected 3 tools on this machine), mcp (stdio server runs). VS Code extension bundled (32KB) and packaged as agentlens-0.1.0.vsix (30KB).
|
| 15 |
+
|
| 16 |
+
## [S1] Problem
|
| 17 |
+
|
| 18 |
+
开发者同时使用多个 AI 编程 Agent(Claude Code、Cursor、Codex、Windsurf 等),每个 Agent 有自己的配置格式(CLAUDE.md、.cursor/rules/、AGENTS.md 等)。两个真实痛点:
|
| 19 |
+
|
| 20 |
+
1. **配置迁移难**:用户在一个 Agent 里积累的规则、偏好、工作流习惯,换到另一个 Agent 时需要手动重写。规则散落在 N 个位置 × M 个仓库,"知识 90% 相同但维护 N 份"。现有同步工具只管复制文件,不管规则是否已经失效("一模一样的烂规则副本还是烂规则")。
|
| 21 |
+
2. **产出不信任**:46% 开发者不信任 AI 输出,66% 最大挫败是"几乎正确但不完全对"。开发者自己写 10+ 个 hook 做对抗式审查,但没有现成商业产品。官方文档承认插件评测是空白。
|
| 22 |
+
|
| 23 |
+
## [S2] Design
|
| 24 |
+
|
| 25 |
+
### 产品定位
|
| 26 |
+
|
| 27 |
+
一个 CLI + MCP Server,服务两类场景:
|
| 28 |
+
- **迁移(Move)**:解析、归一化、转换 AI Agent 的规则配置,一键在 Agent 之间搬运
|
| 29 |
+
- **体检(Check)**:对 Agent 产出的代码/改动做对抗式审查,输出风险报告
|
| 30 |
+
|
| 31 |
+
### [S2.1] 配置迁移引擎(核心差异化)
|
| 32 |
+
|
| 33 |
+
**输入**:源 Agent 类型 + 路径(自动检测当前项目里有哪些 Agent 配置)
|
| 34 |
+
**输出**:目标 Agent 格式的配置文件
|
| 35 |
+
|
| 36 |
+
支持的 Agent 配置格式(MVP 阶段):
|
| 37 |
+
| Agent | 配置文件 | 解析 |
|
| 38 |
+
|---|---|---|
|
| 39 |
+
| Claude Code | CLAUDE.md, .claude/rules/*.md | ✅ |
|
| 40 |
+
| Cursor | .cursor/rules/*.mdc | ✅ |
|
| 41 |
+
| Codex | AGENTS.md | ✅ |
|
| 42 |
+
| Windsurf | .windsurfrules | ✅ |
|
| 43 |
+
| 通用 | .editorconfig, .github/copilot-instructions.md | ✅ |
|
| 44 |
+
|
| 45 |
+
**归一化模型**:所有规则解析为统一中间表示(IR):
|
| 46 |
+
```
|
| 47 |
+
Rule {
|
| 48 |
+
id: string
|
| 49 |
+
category: "style" | "workflow" | "constraint" | "context" | "tooling"
|
| 50 |
+
content: string # 规则正文
|
| 51 |
+
scope: "global" | "project" | "path-glob"
|
| 52 |
+
source: { agent, file, line }
|
| 53 |
+
status: "active" | "suspect" | "stale"
|
| 54 |
+
}
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
**漂移检测**(在迁移之外的附加价值):
|
| 58 |
+
- 同一规则在多处出现但内容不一致 → 标记 drift
|
| 59 |
+
- 规则引用的工具/路径/文件不存在 → 标记 stale
|
| 60 |
+
- 输出漂移报告,建议保留哪个版本
|
| 61 |
+
|
| 62 |
+
### [S2.2] Agent 产出体检引擎
|
| 63 |
+
|
| 64 |
+
**输入**:代码片段 / git diff / 文件路径
|
| 65 |
+
**输出**:结构化体检报告
|
| 66 |
+
|
| 67 |
+
检查维度(MVP 优先做前三个):
|
| 68 |
+
1. **正确性**:边界条件、空值处理、类型错误、逻辑漏洞
|
| 69 |
+
2. **安全**:注入、越权、敏感信息泄露、不安全的依赖
|
| 70 |
+
3. **规范符合**:是否违反用户配置中的规则(与 S2.1 联动)
|
| 71 |
+
4. 性能隐患(后续)
|
| 72 |
+
5. 测试覆盖建议(后续)
|
| 73 |
+
|
| 74 |
+
**运行方式**:
|
| 75 |
+
- CLI: `agentlens check <diff|file>`
|
| 76 |
+
- MCP Server: 注册为 MCP 工具,Claude Code / Cursor 等可直接调用
|
| 77 |
+
- Hook: 接入 Agent 的 post-write hook(如 Claude Code hooks)
|
| 78 |
+
|
| 79 |
+
### [S2.3] 技术架构
|
| 80 |
+
|
| 81 |
+
**跨 Agent 通用策略**(用户核心需求):不为每个 Agent 单独写插件,而是通过 **MCP Server + CLI** 双形态覆盖所有主流工具:
|
| 82 |
+
|
| 83 |
+
| 目标工具 | 接入方式 | 安装后效果 |
|
| 84 |
+
|---|---|---|
|
| 85 |
+
| Claude Code | MCP Server | 工具列表出现 agentlens 命令 |
|
| 86 |
+
| Cursor | MCP Server | .cursor/mcp.json 注册后可用 |
|
| 87 |
+
| Codex | MCP Server | MCP 配置注册后可用 |
|
| 88 |
+
| MiMo Desktop | MCP Server | MCP 设置里添加后可用 |
|
| 89 |
+
| DSH / WorkBuddy / ZCode | CLI + MCP | 支持 MCP 的走 MCP,否则走 CLI |
|
| 90 |
+
| 任何终端 | CLI | `npx agentlens` 直接用 |
|
| 91 |
+
|
| 92 |
+
**一键安装**:`npx agentlens install --target <agent>` 自动检测本机已装的 Agent,把 MCP 配置写入对应配置文件(.mcp.json / CLAUDE.md / .cursor/settings 等),装完后各 Agent 的工具面板/设置里即出现 AgentLens 命令(scan / move / check / drift)。
|
| 93 |
+
|
| 94 |
+
```
|
| 95 |
+
agentlens/
|
| 96 |
+
├── src/
|
| 97 |
+
│ ├── core/ # IR 模型、解析器注册表
|
| 98 |
+
│ ├── parsers/ # 各 Agent 配置解析器(claude.ts, cursor.ts, codex.ts, windsurf.ts...)
|
| 99 |
+
│ ├── migrator/ # IR → 目标格式生成器
|
| 100 |
+
│ ├── drift/ # 漂移检测引擎
|
| 101 |
+
│ ├── checker/ # 产出体检引擎
|
| 102 |
+
│ ├── mcp/ # MCP Server 入口
|
| 103 |
+
│ ├── install/ # 一键安装到各 Agent 的配置写入器
|
| 104 |
+
│ └── cli/ # CLI 入口
|
| 105 |
+
├── tests/
|
| 106 |
+
└── docs/
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
- **语言**:TypeScript(Node.js),与 MCP SDK(@modelcontextprotocol/typescript-sdk)天然亲和
|
| 110 |
+
- **分发**:npm 包(`npx agentlens`),MCP Registry 注册
|
| 111 |
+
- **无服务器依赖**:纯本地运行,代码不出机器(隐私卖点)
|
| 112 |
+
|
| 113 |
+
### [S2.4] 交互流程
|
| 114 |
+
|
| 115 |
+
**迁移流程**:
|
| 116 |
+
```
|
| 117 |
+
$ agentlens scan
|
| 118 |
+
发现 3 个 Agent 配置:
|
| 119 |
+
✅ CLAUDE.md (47 条规则)
|
| 120 |
+
✅ .cursor/rules/ (12 条规则)
|
| 121 |
+
✅ AGENTS.md (8 条规则)
|
| 122 |
+
⚠️ 检测到 3 处漂移、2 条疑似失效规则
|
| 123 |
+
|
| 124 |
+
$ agentlens move --from claude --to cursor
|
| 125 |
+
转换 47 条规则 → .cursor/rules/agentlens.mdc
|
| 126 |
+
✅ 完成。预览?(y/n)
|
| 127 |
+
|
| 128 |
+
$ agentlens drift
|
| 129 |
+
漂移报告:...
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
**体检流程**:
|
| 133 |
+
```
|
| 134 |
+
$ agentlens check HEAD~1..HEAD
|
| 135 |
+
检查 12 个文件变更...
|
| 136 |
+
🔴 2 个高危 | 🟡 5 个警告 | ⚪ 8 个通过
|
| 137 |
+
[详细报告]
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
## [S3] Out of Scope
|
| 141 |
+
|
| 142 |
+
- 不做云端同步/账号系统(纯本地工具)
|
| 143 |
+
- 不做 Agent 本身的替代或封装(不做 "又一个 AI 编程助手")
|
| 144 |
+
- 不做实时监听/自动修复(MVP 只做检测+报告)
|
| 145 |
+
- 不做非编程 Agent(如通用聊天机器人)的配置
|
| 146 |
+
- 不做付费/许可证系统(MVP 开源,后续再加商业版)
|
| 147 |
+
|
| 148 |
+
## Tasks
|
| 149 |
+
|
| 150 |
+
- [x] T1: 项目脚手架 — TypeScript + vitest + MCP SDK 初始化,CLI 骨架可运行 — acceptance: `npx agentlens --help` 输出帮助信息
|
| 151 |
+
- [x] T2: 配置解析器 — 解析 CLAUDE.md / .cursor/rules / AGENTS.md 为统一 IR — acceptance: 对 3 种格式的测试样本,解析出完整规则列表且字段正确 (covers: S2.1)
|
| 152 |
+
- [x] T3: 迁移生成器 — IR → 目标 Agent 格式输出 — acceptance: claude→cursor / cursor→claude / codex→claude 三组转换测试通过 (covers: S2.1)
|
| 153 |
+
- [x] T4: 漂移检测 — 检测同规则不一致、失效引用 — acceptance: 构造漂移样本能正确报告 drift/stale 项 (covers: S2.1)
|
| 154 |
+
- [x] T5: 体检引擎 MVP — 对 diff 做正确性+安全+规范检查 — acceptance: 对含已知漏洞的测试代码,报告能标出注入/越权/空指针 (covers: S2.2)
|
| 155 |
+
- [x] T6: MCP Server — 注册 scan/move/check/install 为 MCP 工具 — acceptance: Claude Desktop / Cursor 可通过 MCP 调用 agentlens 工具 (covers: S2.2, S2.3)
|
| 156 |
+
- [x] T7: 一键安装器 — `agentlens install` 自动检测本机 Agent 并写入 MCP 配置 — acceptance: 在装有 Claude Code 的机器上运行 install 后,Claude Code 工具列表出现 agentlens 命令 (covers: S2.3)
|
| 157 |
+
- [x] T8: CLI 集成 — scan/move/check/drift 子命令完整可用 — acceptance: 端到端跑通扫描→迁移→体检全流程 (covers: S2.4)
|
| 158 |
+
- [x] T9: 测试与文档 — 单测覆盖 + README + npm 发布准备 — acceptance: `npm test` 全绿,README 含安装和使用示例
|
| 159 |
+
- [x] T10: App 集成(用户新增需求)— VS Code/Cursor 扩展(.vsix,设置面板可见)+ 自动检测安装器 — acceptance: .vsix 可安装且命令出现在命令面板/设置;`agentlens install` 自动检测并写入各工具 MCP 配置 (covers: S2.3)
|
| 160 |
+
|
| 161 |
+
## Journey log
|
| 162 |
+
|
| 163 |
+
- 2026-11-19: 调研阶段发现"Agent 产出 QA"和"配置漂移检测"是 Agent 工具生态中竞争最少的两个缺口(详见 research/market-gap-opportunities/)。用户决定将两者合并为一个产品。
|
ext/dsh-plugin/cordis.patch.yml
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
- insert:
|
| 2 |
+
- id: agentlens
|
| 3 |
+
name: '@local/agentlens'
|
| 4 |
+
config: {}
|
ext/dsh-plugin/index.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @local/agentlens — AgentLens host plugin for DSH.
|
| 3 |
+
*
|
| 4 |
+
* Registers four model-facing tools that shell out to the AgentLens CLI:
|
| 5 |
+
* agentlens_scan — scan agent configs in the workspace
|
| 6 |
+
* agentlens_move — migrate rules between agent formats
|
| 7 |
+
* agentlens_drift — detect config drift across agents
|
| 8 |
+
* agentlens_check — adversarial code QA on a file or git diff
|
| 9 |
+
*
|
| 10 |
+
* All work happens locally via `npx agentlens`; nothing leaves the machine.
|
| 11 |
+
*/
|
| 12 |
+
import { execFile } from "node:child_process";
|
| 13 |
+
import { promisify } from "node:util";
|
| 14 |
+
|
| 15 |
+
const execFileAsync = promisify(execFile);
|
| 16 |
+
|
| 17 |
+
export const inject = ["tools"];
|
| 18 |
+
|
| 19 |
+
function text(value) {
|
| 20 |
+
return [{ type: "text", text: String(value) }];
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
/** Run the agentlens CLI and return its combined output. */
|
| 24 |
+
async function runAgentlens(args, cwd) {
|
| 25 |
+
try {
|
| 26 |
+
const { stdout, stderr } = await execFileAsync("npx", ["-y", "agentlens", ...args], {
|
| 27 |
+
cwd,
|
| 28 |
+
timeout: 120_000,
|
| 29 |
+
maxBuffer: 4 * 1024 * 1024,
|
| 30 |
+
});
|
| 31 |
+
return (stdout || "") + (stderr ? `\n${stderr}` : "");
|
| 32 |
+
} catch (err) {
|
| 33 |
+
return `AgentLens 执行失败: ${err?.message ?? String(err)}`;
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
/**
|
| 38 |
+
* @param ctx - owning Host context.
|
| 39 |
+
* @param config - bundle config (currently unused).
|
| 40 |
+
*/
|
| 41 |
+
export function apply(ctx, config = {}) {
|
| 42 |
+
void config;
|
| 43 |
+
|
| 44 |
+
ctx.effect(() => {
|
| 45 |
+
const tools = ctx.get("tools");
|
| 46 |
+
if (tools === void 0) return;
|
| 47 |
+
|
| 48 |
+
const disposers = [
|
| 49 |
+
tools.register({
|
| 50 |
+
name: "agentlens_scan",
|
| 51 |
+
description:
|
| 52 |
+
"Scan the current project for AI agent config files (CLAUDE.md, .cursor/rules, AGENTS.md, .windsurfrules, copilot-instructions) and summarize the rules found. Read-only.",
|
| 53 |
+
parameters: {
|
| 54 |
+
type: "object",
|
| 55 |
+
properties: {
|
| 56 |
+
path: { type: "string", description: "Project root path (defaults to cwd)." },
|
| 57 |
+
},
|
| 58 |
+
additionalProperties: false,
|
| 59 |
+
},
|
| 60 |
+
async execute(args) {
|
| 61 |
+
const path = typeof args?.path === "string" ? args.path : process.cwd();
|
| 62 |
+
return text(await runAgentlens(["scan", "--path", path], path));
|
| 63 |
+
},
|
| 64 |
+
}),
|
| 65 |
+
tools.register({
|
| 66 |
+
name: "agentlens_move",
|
| 67 |
+
description:
|
| 68 |
+
"Migrate AI agent rules from one format to another (e.g. claude → cursor, cursor → codex). Parses into a unified model and re-generates the target format. Writes the target config file.",
|
| 69 |
+
parameters: {
|
| 70 |
+
type: "object",
|
| 71 |
+
properties: {
|
| 72 |
+
from: { type: "string", description: "Source agent: claude | cursor | codex | windsurf | copilot" },
|
| 73 |
+
to: { type: "string", description: "Target agent: claude | cursor | codex | windsurf | copilot" },
|
| 74 |
+
path: { type: "string", description: "Project root path (defaults to cwd)." },
|
| 75 |
+
},
|
| 76 |
+
required: ["from", "to"],
|
| 77 |
+
additionalProperties: false,
|
| 78 |
+
},
|
| 79 |
+
async execute(args) {
|
| 80 |
+
const path = typeof args?.path === "string" ? args.path : process.cwd();
|
| 81 |
+
const cmd = ["move", "--from", String(args.from), "--to", String(args.to), "--path", path];
|
| 82 |
+
return text(await runAgentlens(cmd, path));
|
| 83 |
+
},
|
| 84 |
+
}),
|
| 85 |
+
tools.register({
|
| 86 |
+
name: "agentlens_drift",
|
| 87 |
+
description:
|
| 88 |
+
"Detect config drift across agent rule files: similar rules with different wording, and rule categories present in one agent but missing in another. Read-only.",
|
| 89 |
+
parameters: {
|
| 90 |
+
type: "object",
|
| 91 |
+
properties: {
|
| 92 |
+
path: { type: "string", description: "Project root path (defaults to cwd)." },
|
| 93 |
+
},
|
| 94 |
+
additionalProperties: false,
|
| 95 |
+
},
|
| 96 |
+
async execute(args) {
|
| 97 |
+
const path = typeof args?.path === "string" ? args.path : process.cwd();
|
| 98 |
+
return text(await runAgentlens(["drift", "--path", path], path));
|
| 99 |
+
},
|
| 100 |
+
}),
|
| 101 |
+
tools.register({
|
| 102 |
+
name: "agentlens_check",
|
| 103 |
+
description:
|
| 104 |
+
"Adversarial code QA: check a file or a git diff range for security issues (injection, hardcoded secrets, XSS), correctness bugs (empty catch, loose null comparison), style problems and performance smells. Read-only.",
|
| 105 |
+
parameters: {
|
| 106 |
+
type: "object",
|
| 107 |
+
properties: {
|
| 108 |
+
target: { type: "string", description: "File path or git diff range (e.g. HEAD~1..HEAD). Defaults to HEAD~1..HEAD." },
|
| 109 |
+
path: { type: "string", description: "Project root path (defaults to cwd)." },
|
| 110 |
+
},
|
| 111 |
+
additionalProperties: false,
|
| 112 |
+
},
|
| 113 |
+
async execute(args) {
|
| 114 |
+
const path = typeof args?.path === "string" ? args.path : process.cwd();
|
| 115 |
+
const target = typeof args?.target === "string" ? args.target : "HEAD~1..HEAD";
|
| 116 |
+
return text(await runAgentlens(["check", target, "--path", path], path));
|
| 117 |
+
},
|
| 118 |
+
}),
|
| 119 |
+
];
|
| 120 |
+
|
| 121 |
+
return () => {
|
| 122 |
+
for (const dispose of disposers) {
|
| 123 |
+
try {
|
| 124 |
+
dispose?.();
|
| 125 |
+
} catch {
|
| 126 |
+
// best-effort unregister
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
};
|
| 130 |
+
}, "agentlens: tools");
|
| 131 |
+
}
|
ext/dsh-plugin/package.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@local/agentlens",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"type": "module",
|
| 6 |
+
"description": "AgentLens for DSH: cross-agent config migration + adversarial code QA tools",
|
| 7 |
+
"exports": {
|
| 8 |
+
".": "./index.js"
|
| 9 |
+
},
|
| 10 |
+
"files": [
|
| 11 |
+
"index.js",
|
| 12 |
+
"cordis.patch.yml"
|
| 13 |
+
],
|
| 14 |
+
"dsh": {
|
| 15 |
+
"bundle": {
|
| 16 |
+
"patch": "./cordis.patch.yml"
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
}
|
ext/vscode/agentlens-0.1.0.vsix
ADDED
|
Binary file (31 kB). View file
|
|
|
ext/vscode/build.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
// Bundle the VS Code extension with esbuild (handles ESM core + CJS extension)
|
| 3 |
+
const { build } = require("esbuild");
|
| 4 |
+
const path = require("path");
|
| 5 |
+
|
| 6 |
+
build({
|
| 7 |
+
entryPoints: [path.join(__dirname, "src/extension.ts")],
|
| 8 |
+
bundle: true,
|
| 9 |
+
outfile: path.join(__dirname, "out/extension.js"),
|
| 10 |
+
external: ["vscode"],
|
| 11 |
+
format: "cjs",
|
| 12 |
+
platform: "node",
|
| 13 |
+
target: "node20",
|
| 14 |
+
sourcemap: true,
|
| 15 |
+
minify: false,
|
| 16 |
+
}).then(() => {
|
| 17 |
+
console.log("✅ Extension bundled to out/extension.js");
|
| 18 |
+
}).catch((err) => {
|
| 19 |
+
console.error("❌ Build failed:", err);
|
| 20 |
+
process.exit(1);
|
| 21 |
+
});
|
ext/vscode/package.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "agentlens",
|
| 3 |
+
"displayName": "AgentLens — AI Agent Rules & Code QA",
|
| 4 |
+
"description": "迁移 AI Agent 规则配置(CLAUDE.md / .cursor/rules / AGENTS.md 等),并对 AI 写的代码做对抗式体检。",
|
| 5 |
+
"version": "0.1.0",
|
| 6 |
+
"publisher": "agentlens",
|
| 7 |
+
"license": "MIT",
|
| 8 |
+
"engines": {
|
| 9 |
+
"vscode": "^1.90.0"
|
| 10 |
+
},
|
| 11 |
+
"categories": [
|
| 12 |
+
"Other"
|
| 13 |
+
],
|
| 14 |
+
"keywords": [
|
| 15 |
+
"ai",
|
| 16 |
+
"cursor",
|
| 17 |
+
"claude",
|
| 18 |
+
"codex",
|
| 19 |
+
"code-review",
|
| 20 |
+
"config"
|
| 21 |
+
],
|
| 22 |
+
"activationEvents": [],
|
| 23 |
+
"main": "./out/extension.js",
|
| 24 |
+
"contributes": {
|
| 25 |
+
"commands": [
|
| 26 |
+
{
|
| 27 |
+
"command": "agentlens.scan",
|
| 28 |
+
"title": "AgentLens: 扫描项目中的 Agent 配置"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"command": "agentlens.move",
|
| 32 |
+
"title": "AgentLens: 迁移规则到其他 Agent"
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"command": "agentlens.drift",
|
| 36 |
+
"title": "AgentLens: 检测配置漂移"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"command": "agentlens.checkFile",
|
| 40 |
+
"title": "AgentLens: 体检当前文件"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"command": "agentlens.checkWorkspace",
|
| 44 |
+
"title": "AgentLens: 体检工作区变更"
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"command": "agentlens.openPanel",
|
| 48 |
+
"title": "AgentLens: 打开设置面板"
|
| 49 |
+
}
|
| 50 |
+
],
|
| 51 |
+
"menus": {
|
| 52 |
+
"editor/context": [
|
| 53 |
+
{
|
| 54 |
+
"command": "agentlens.checkFile",
|
| 55 |
+
"group": "agentlens"
|
| 56 |
+
}
|
| 57 |
+
],
|
| 58 |
+
"view/title": [
|
| 59 |
+
{
|
| 60 |
+
"command": "agentlens.scan",
|
| 61 |
+
"when": "view == agentlens.panel"
|
| 62 |
+
}
|
| 63 |
+
]
|
| 64 |
+
},
|
| 65 |
+
"configuration": {
|
| 66 |
+
"title": "AgentLens",
|
| 67 |
+
"properties": {
|
| 68 |
+
"agentlens.autoCheckOnSave": {
|
| 69 |
+
"type": "boolean",
|
| 70 |
+
"default": false,
|
| 71 |
+
"description": "保存文件时自动体检当前文件"
|
| 72 |
+
},
|
| 73 |
+
"agentlens.severityThreshold": {
|
| 74 |
+
"type": "string",
|
| 75 |
+
"enum": [
|
| 76 |
+
"critical",
|
| 77 |
+
"warning",
|
| 78 |
+
"info"
|
| 79 |
+
],
|
| 80 |
+
"default": "warning",
|
| 81 |
+
"description": "体检报告显示的最低严重级别"
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
"scripts": {
|
| 87 |
+
"compile": "tsc -p ./",
|
| 88 |
+
"watch": "tsc -watch -p ./",
|
| 89 |
+
"package": "vsce package"
|
| 90 |
+
},
|
| 91 |
+
"devDependencies": {
|
| 92 |
+
"@types/vscode": "^1.90.0",
|
| 93 |
+
"@types/node": "^22.0.0",
|
| 94 |
+
"typescript": "^5.6.0"
|
| 95 |
+
}
|
| 96 |
+
}
|
ext/vscode/src/extension.ts
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as vscode from "vscode";
|
| 2 |
+
import { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";
|
| 3 |
+
import { resolve, join, dirname } from "node:path";
|
| 4 |
+
import {
|
| 5 |
+
parsers,
|
| 6 |
+
generateConfig,
|
| 7 |
+
outputFileFor,
|
| 8 |
+
detectDriftEntries,
|
| 9 |
+
findMissingRules,
|
| 10 |
+
generateReport,
|
| 11 |
+
type Rule,
|
| 12 |
+
} from "../../../src/index.js";
|
| 13 |
+
|
| 14 |
+
let panel: vscode.WebviewPanel | undefined;
|
| 15 |
+
let outputChannel: vscode.OutputChannel;
|
| 16 |
+
|
| 17 |
+
function findAgentFiles(root: string, agent: string): string[] {
|
| 18 |
+
const parser = parsers[agent];
|
| 19 |
+
if (!parser) return [];
|
| 20 |
+
const files: string[] = [];
|
| 21 |
+
for (const pattern of parser.filePatterns) {
|
| 22 |
+
if (pattern.includes("*")) {
|
| 23 |
+
const parts = pattern.split("/");
|
| 24 |
+
const dirParts = parts.slice(0, -1);
|
| 25 |
+
const filePattern = parts[parts.length - 1];
|
| 26 |
+
const dir = resolve(root, ...dirParts);
|
| 27 |
+
if (existsSync(dir) && statSync(dir).isDirectory()) {
|
| 28 |
+
const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");
|
| 29 |
+
for (const f of readdirSync(dir)) {
|
| 30 |
+
if (regex.test(f)) files.push(join(dir, f));
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
} else {
|
| 34 |
+
const filePath = resolve(root, pattern);
|
| 35 |
+
if (existsSync(filePath)) files.push(filePath);
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
return files;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
function collectRules(root: string): Array<{ agent: string; rules: Rule[]; files: string[] }> {
|
| 42 |
+
const results: Array<{ agent: string; rules: Rule[]; files: string[] }> = [];
|
| 43 |
+
for (const [agentName, parser] of Object.entries(parsers)) {
|
| 44 |
+
const files = findAgentFiles(root, agentName);
|
| 45 |
+
if (files.length === 0) continue;
|
| 46 |
+
const rules: Rule[] = [];
|
| 47 |
+
for (const file of files) {
|
| 48 |
+
rules.push(...parser.parse(readFileSync(file, "utf-8"), file));
|
| 49 |
+
}
|
| 50 |
+
results.push({ agent: agentName, rules, files });
|
| 51 |
+
}
|
| 52 |
+
return results;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
function getWorkspaceRoot(): string | undefined {
|
| 56 |
+
return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
export function activate(context: vscode.ExtensionContext) {
|
| 60 |
+
outputChannel = vscode.window.createOutputChannel("AgentLens");
|
| 61 |
+
context.subscriptions.push(outputChannel);
|
| 62 |
+
|
| 63 |
+
// === Scan ===
|
| 64 |
+
context.subscriptions.push(
|
| 65 |
+
vscode.commands.registerCommand("agentlens.scan", async () => {
|
| 66 |
+
const root = getWorkspaceRoot();
|
| 67 |
+
if (!root) {
|
| 68 |
+
vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
|
| 69 |
+
return;
|
| 70 |
+
}
|
| 71 |
+
const results = collectRules(root);
|
| 72 |
+
outputChannel.clear();
|
| 73 |
+
outputChannel.appendLine(`扫描 ${root}`);
|
| 74 |
+
outputChannel.appendLine("");
|
| 75 |
+
if (results.length === 0) {
|
| 76 |
+
outputChannel.appendLine("未发现 Agent 配置。");
|
| 77 |
+
vscode.window.showInformationMessage("AgentLens: 未发现 Agent 配置");
|
| 78 |
+
return;
|
| 79 |
+
}
|
| 80 |
+
for (const r of results) {
|
| 81 |
+
const cats = new Map<string, number>();
|
| 82 |
+
for (const rule of r.rules) cats.set(rule.category, (cats.get(rule.category) ?? 0) + 1);
|
| 83 |
+
const catStr = [...cats.entries()].map(([c, n]) => `${c}(${n})`).join(", ");
|
| 84 |
+
outputChannel.appendLine(`✅ ${r.agent.toUpperCase()} — ${r.rules.length} 条规则 [${catStr}]`);
|
| 85 |
+
for (const f of r.files) outputChannel.appendLine(` 📄 ${f.replace(root, ".")}`);
|
| 86 |
+
}
|
| 87 |
+
outputChannel.show();
|
| 88 |
+
vscode.window.showInformationMessage(
|
| 89 |
+
`AgentLens: 发现 ${results.length} 个 Agent 配置,共 ${results.reduce((a, r) => a + r.rules.length, 0)} 条规则`
|
| 90 |
+
);
|
| 91 |
+
updatePanelContent(root);
|
| 92 |
+
})
|
| 93 |
+
);
|
| 94 |
+
|
| 95 |
+
// === Move (quick pick flow) ===
|
| 96 |
+
context.subscriptions.push(
|
| 97 |
+
vscode.commands.registerCommand("agentlens.move", async () => {
|
| 98 |
+
const root = getWorkspaceRoot();
|
| 99 |
+
if (!root) {
|
| 100 |
+
vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
|
| 101 |
+
return;
|
| 102 |
+
}
|
| 103 |
+
const found = collectRules(root);
|
| 104 |
+
if (found.length === 0) {
|
| 105 |
+
vscode.window.showWarningMessage("AgentLens: 未发现任何 Agent 配置");
|
| 106 |
+
return;
|
| 107 |
+
}
|
| 108 |
+
const from = await vscode.window.showQuickPick(
|
| 109 |
+
found.map((f) => f.agent),
|
| 110 |
+
{ placeHolder: "从哪个 Agent 迁移规则?" }
|
| 111 |
+
);
|
| 112 |
+
if (!from) return;
|
| 113 |
+
const allAgents = Object.keys(parsers);
|
| 114 |
+
const to = await vscode.window.showQuickPick(
|
| 115 |
+
allAgents.filter((a) => a !== from),
|
| 116 |
+
{ placeHolder: "迁移到哪个 Agent?" }
|
| 117 |
+
);
|
| 118 |
+
if (!to) return;
|
| 119 |
+
|
| 120 |
+
const sourceRules = found.find((f) => f.agent === from)?.rules ?? [];
|
| 121 |
+
const content = generateConfig(sourceRules, to as any);
|
| 122 |
+
const outPath = resolve(root, outputFileFor(to as any));
|
| 123 |
+
mkdirSync(dirname(outPath), { recursive: true });
|
| 124 |
+
writeFileSync(outPath, content, "utf-8");
|
| 125 |
+
vscode.window.showInformationMessage(
|
| 126 |
+
`AgentLens: ${sourceRules.length} 条规则已迁移 ${from} → ${to}(${outPath.replace(root, ".")})`
|
| 127 |
+
);
|
| 128 |
+
outputChannel.appendLine(`迁移完成: ${from} → ${to}, ${sourceRules.length} 条规则 → ${outPath}`);
|
| 129 |
+
})
|
| 130 |
+
);
|
| 131 |
+
|
| 132 |
+
// === Drift ===
|
| 133 |
+
context.subscriptions.push(
|
| 134 |
+
vscode.commands.registerCommand("agentlens.drift", async () => {
|
| 135 |
+
const root = getWorkspaceRoot();
|
| 136 |
+
if (!root) {
|
| 137 |
+
vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
|
| 138 |
+
return;
|
| 139 |
+
}
|
| 140 |
+
const found = collectRules(root);
|
| 141 |
+
const allRules = found.flatMap((f) => f.rules);
|
| 142 |
+
if (allRules.length === 0) {
|
| 143 |
+
vscode.window.showInformationMessage("AgentLens: 没有可比较的规则");
|
| 144 |
+
return;
|
| 145 |
+
}
|
| 146 |
+
const drifts = detectDriftEntries(allRules);
|
| 147 |
+
if (found.length >= 2) {
|
| 148 |
+
const base = found[0];
|
| 149 |
+
for (let i = 1; i < found.length; i++) {
|
| 150 |
+
drifts.push(...findMissingRules(base.rules, found[i].rules, base.agent as any, found[i].agent as any));
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
outputChannel.clear();
|
| 154 |
+
if (drifts.length === 0) {
|
| 155 |
+
outputChannel.appendLine("✅ 未发现配置漂移");
|
| 156 |
+
vscode.window.showInformationMessage("AgentLens: 未发现配置漂移");
|
| 157 |
+
} else {
|
| 158 |
+
outputChannel.appendLine(`⚠ 发现 ${drifts.length} 处漂移:`);
|
| 159 |
+
for (const d of drifts) {
|
| 160 |
+
outputChannel.appendLine(`[${d.type}] ${d.description}`);
|
| 161 |
+
}
|
| 162 |
+
vscode.window.showWarningMessage(`AgentLens: 发现 ${drifts.length} 处配置漂移`);
|
| 163 |
+
}
|
| 164 |
+
outputChannel.show();
|
| 165 |
+
updatePanelContent(root);
|
| 166 |
+
})
|
| 167 |
+
);
|
| 168 |
+
|
| 169 |
+
// === Check current file ===
|
| 170 |
+
context.subscriptions.push(
|
| 171 |
+
vscode.commands.registerCommand("agentlens.checkFile", async () => {
|
| 172 |
+
const editor = vscode.window.activeTextEditor;
|
| 173 |
+
if (!editor) {
|
| 174 |
+
vscode.window.showWarningMessage("AgentLens: 没有打开的文件");
|
| 175 |
+
return;
|
| 176 |
+
}
|
| 177 |
+
const filePath = editor.document.uri.fsPath;
|
| 178 |
+
const content = editor.document.getText();
|
| 179 |
+
const ext = filePath.split(".").pop()?.toLowerCase();
|
| 180 |
+
const langMap: Record<string, string> = {
|
| 181 |
+
ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
|
| 182 |
+
py: "python", go: "go", rs: "rust", java: "java",
|
| 183 |
+
};
|
| 184 |
+
const report = generateReport([{ path: filePath, content, language: ext ? langMap[ext] : undefined }]);
|
| 185 |
+
outputChannel.clear();
|
| 186 |
+
outputChannel.appendLine(`体检: ${filePath}`);
|
| 187 |
+
outputChannel.appendLine(`🔴 ${report.summary.critical} critical 🟡 ${report.summary.warning} warning ⚪ ${report.summary.info} info`);
|
| 188 |
+
outputChannel.appendLine("");
|
| 189 |
+
for (const f of report.findings) {
|
| 190 |
+
outputChannel.appendLine(`[${f.severity}] ${f.file}:${f.line ?? "?"} — ${f.message}`);
|
| 191 |
+
if (f.suggestion) outputChannel.appendLine(` 💡 ${f.suggestion}`);
|
| 192 |
+
}
|
| 193 |
+
outputChannel.show();
|
| 194 |
+
if (report.summary.critical > 0) {
|
| 195 |
+
vscode.window.showErrorMessage(`AgentLens: ${report.summary.critical} 个严重问题!`);
|
| 196 |
+
} else if (report.summary.warning > 0) {
|
| 197 |
+
vscode.window.showWarningMessage(`AgentLens: ${report.summary.warning} 个警告`);
|
| 198 |
+
} else {
|
| 199 |
+
vscode.window.showInformationMessage("AgentLens: 体检通过 ✅");
|
| 200 |
+
}
|
| 201 |
+
})
|
| 202 |
+
);
|
| 203 |
+
|
| 204 |
+
// === Check workspace changes ===
|
| 205 |
+
context.subscriptions.push(
|
| 206 |
+
vscode.commands.registerCommand("agentlens.checkWorkspace", async () => {
|
| 207 |
+
const root = getWorkspaceRoot();
|
| 208 |
+
if (!root) {
|
| 209 |
+
vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
|
| 210 |
+
return;
|
| 211 |
+
}
|
| 212 |
+
const { execSync } = await import("node:child_process");
|
| 213 |
+
let files: string[] = [];
|
| 214 |
+
try {
|
| 215 |
+
files = execSync("git diff --name-only HEAD", { cwd: root, encoding: "utf-8" })
|
| 216 |
+
.trim()
|
| 217 |
+
.split("\n")
|
| 218 |
+
.filter(Boolean);
|
| 219 |
+
} catch {
|
| 220 |
+
vscode.window.showWarningMessage("AgentLens: 无法读取 git 变更");
|
| 221 |
+
return;
|
| 222 |
+
}
|
| 223 |
+
if (files.length === 0) {
|
| 224 |
+
vscode.window.showInformationMessage("AgentLens: 没有未提交的变更");
|
| 225 |
+
return;
|
| 226 |
+
}
|
| 227 |
+
outputChannel.clear();
|
| 228 |
+
outputChannel.appendLine(`体检工作区变更 (${files.length} 个文件)`);
|
| 229 |
+
let totalCritical = 0;
|
| 230 |
+
let totalWarning = 0;
|
| 231 |
+
for (const f of files) {
|
| 232 |
+
const full = resolve(root, f);
|
| 233 |
+
if (!existsSync(full)) continue;
|
| 234 |
+
const ext = f.split(".").pop()?.toLowerCase();
|
| 235 |
+
const langMap: Record<string, string> = {
|
| 236 |
+
ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
|
| 237 |
+
py: "python", go: "go", rs: "rust", java: "java",
|
| 238 |
+
};
|
| 239 |
+
const report = generateReport([{ path: f, content: readFileSync(full, "utf-8"), language: ext ? langMap[ext] : undefined }]);
|
| 240 |
+
totalCritical += report.summary.critical;
|
| 241 |
+
totalWarning += report.summary.warning;
|
| 242 |
+
for (const finding of report.findings) {
|
| 243 |
+
outputChannel.appendLine(`[${finding.severity}] ${finding.file}:${finding.line ?? "?"} — ${finding.message}`);
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
outputChannel.show();
|
| 247 |
+
if (totalCritical > 0) {
|
| 248 |
+
vscode.window.showErrorMessage(`AgentLens: ${totalCritical} 个严重问题!`);
|
| 249 |
+
} else if (totalWarning > 0) {
|
| 250 |
+
vscode.window.showWarningMessage(`AgentLens: ${totalWarning} 个警告`);
|
| 251 |
+
} else {
|
| 252 |
+
vscode.window.showInformationMessage("AgentLens: 变更体检通过 ✅");
|
| 253 |
+
}
|
| 254 |
+
})
|
| 255 |
+
);
|
| 256 |
+
|
| 257 |
+
// === Open settings panel ===
|
| 258 |
+
context.subscriptions.push(
|
| 259 |
+
vscode.commands.registerCommand("agentlens.openPanel", async () => {
|
| 260 |
+
if (panel) {
|
| 261 |
+
panel.reveal();
|
| 262 |
+
} else {
|
| 263 |
+
panel = vscode.window.createWebviewPanel(
|
| 264 |
+
"agentlens.panel",
|
| 265 |
+
"AgentLens 设置",
|
| 266 |
+
vscode.ViewColumn.One,
|
| 267 |
+
{ enableScripts: true }
|
| 268 |
+
);
|
| 269 |
+
panel.onDidDispose(() => { panel = undefined; });
|
| 270 |
+
panel.webview.html = getPanelHtml();
|
| 271 |
+
const root = getWorkspaceRoot();
|
| 272 |
+
if (root) updatePanelContent(root);
|
| 273 |
+
}
|
| 274 |
+
})
|
| 275 |
+
);
|
| 276 |
+
|
| 277 |
+
// === Auto check on save (if enabled) ===
|
| 278 |
+
context.subscriptions.push(
|
| 279 |
+
vscode.workspace.onDidSaveTextDocument(async (doc) => {
|
| 280 |
+
const config = vscode.workspace.getConfiguration("agentlens");
|
| 281 |
+
if (config.get<boolean>("autoCheckOnSave")) {
|
| 282 |
+
await vscode.commands.executeCommand("agentlens.checkFile");
|
| 283 |
+
}
|
| 284 |
+
})
|
| 285 |
+
);
|
| 286 |
+
|
| 287 |
+
outputChannel.appendLine("AgentLens 已激活。命令面板输入 'AgentLens' 查看所有命令。");
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
async function updatePanelContent(root: string) {
|
| 291 |
+
if (!panel) return;
|
| 292 |
+
const results = collectRules(root);
|
| 293 |
+
panel.webview.postMessage({ type: "scanResult", results: results.map((r) => ({
|
| 294 |
+
agent: r.agent,
|
| 295 |
+
ruleCount: r.rules.length,
|
| 296 |
+
files: r.files.map((f) => f.replace(root, ".")),
|
| 297 |
+
})) });
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
function getPanelHtml(): string {
|
| 301 |
+
return `<!DOCTYPE html>
|
| 302 |
+
<html lang="zh-CN">
|
| 303 |
+
<head>
|
| 304 |
+
<meta charset="UTF-8">
|
| 305 |
+
<style>
|
| 306 |
+
body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); background: var(--vscode-editor-background); padding: 20px; }
|
| 307 |
+
h1 { font-size: 1.4em; }
|
| 308 |
+
.card { border: 1px solid var(--vscode-panel-border); border-radius: 8px; padding: 16px; margin: 12px 0; }
|
| 309 |
+
.agent-name { font-weight: 600; margin-bottom: 6px; }
|
| 310 |
+
.muted { opacity: 0.7; font-size: 0.9em; }
|
| 311 |
+
.rule-badge { display: inline-block; background: var(--vscode-badge-background); color: var(--vscode-badge-foreground); border-radius: 10px; padding: 2px 10px; font-size: 0.85em; margin-left: 8px; }
|
| 312 |
+
.btn { background: var(--vscode-button-background); color: var(--vscode-button-foreground); border: none; border-radius: 4px; padding: 8px 16px; cursor: pointer; margin-right: 8px; font-size: 1em; }
|
| 313 |
+
.btn:hover { background: var(--vscode-button-hoverBackground); }
|
| 314 |
+
ul { padding-left: 20px; margin: 8px 0; }
|
| 315 |
+
li { margin: 4px 0; font-size: 0.95em; }
|
| 316 |
+
.empty { opacity: 0.6; font-style: italic; }
|
| 317 |
+
</style>
|
| 318 |
+
</head>
|
| 319 |
+
<body>
|
| 320 |
+
<h1>🔍 AgentLens</h1>
|
| 321 |
+
<p class="muted">AI 编程 Agent 规则迁移 + 代码体检</p>
|
| 322 |
+
<div style="margin: 16px 0;">
|
| 323 |
+
<button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'scan'});})()">扫描配置</button>
|
| 324 |
+
<button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'move'});})()">迁移规则</button>
|
| 325 |
+
<button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'drift'});})()">检测漂移</button>
|
| 326 |
+
<button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'check'});})()">体检文件</button>
|
| 327 |
+
</div>
|
| 328 |
+
<div id="results"><p class="empty">点击「扫描配置」开始</p></div>
|
| 329 |
+
<script>
|
| 330 |
+
const vscode = acquireVsCodeApi();
|
| 331 |
+
window.addEventListener('message', (event) => {
|
| 332 |
+
const msg = event.data;
|
| 333 |
+
if (msg.type === 'scanResult') {
|
| 334 |
+
const el = document.getElementById('results');
|
| 335 |
+
if (!msg.results || msg.results.length === 0) {
|
| 336 |
+
el.innerHTML = '<p class="empty">未发现 Agent 配置</p>';
|
| 337 |
+
return;
|
| 338 |
+
}
|
| 339 |
+
el.innerHTML = msg.results.map(r =>
|
| 340 |
+
'<div class="card"><div class="agent-name">' + r.agent.toUpperCase() +
|
| 341 |
+
'<span class="rule-badge">' + r.ruleCount + ' 条规则</span></div>' +
|
| 342 |
+
'<ul>' + r.files.map(f => '<li>' + f + '</li>').join('') + '</ul></div>'
|
| 343 |
+
).join('');
|
| 344 |
+
}
|
| 345 |
+
});
|
| 346 |
+
</script>
|
| 347 |
+
</body>
|
| 348 |
+
</html>`;
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
export function deactivate() {}
|
ext/vscode/tsconfig.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"module": "commonjs",
|
| 4 |
+
"target": "ES2022",
|
| 5 |
+
"outDir": "out",
|
| 6 |
+
"lib": ["ES2022"],
|
| 7 |
+
"sourceMap": true,
|
| 8 |
+
"rootDir": "src",
|
| 9 |
+
"strict": true,
|
| 10 |
+
"esModuleInterop": true,
|
| 11 |
+
"skipLibCheck": true
|
| 12 |
+
},
|
| 13 |
+
"include": ["src"],
|
| 14 |
+
"exclude": ["node_modules", ".vscode-test"]
|
| 15 |
+
}
|
package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "agentlens",
|
| 3 |
+
"version": "0.1.0",
|
| 4 |
+
"description": "Cross-agent config migration & output QA for AI coding agents",
|
| 5 |
+
"type": "module",
|
| 6 |
+
"bin": {
|
| 7 |
+
"agentlens": "./dist/cli/index.js"
|
| 8 |
+
},
|
| 9 |
+
"main": "./dist/index.js",
|
| 10 |
+
"scripts": {
|
| 11 |
+
"build": "tsc",
|
| 12 |
+
"test": "vitest run",
|
| 13 |
+
"test:watch": "vitest",
|
| 14 |
+
"dev": "tsx src/cli/index.ts",
|
| 15 |
+
"lint": "tsc --noEmit"
|
| 16 |
+
},
|
| 17 |
+
"keywords": [
|
| 18 |
+
"mcp",
|
| 19 |
+
"ai",
|
| 20 |
+
"coding-agent",
|
| 21 |
+
"claude",
|
| 22 |
+
"cursor",
|
| 23 |
+
"config-migration",
|
| 24 |
+
"code-review"
|
| 25 |
+
],
|
| 26 |
+
"license": "MIT",
|
| 27 |
+
"engines": {
|
| 28 |
+
"node": ">=20"
|
| 29 |
+
},
|
| 30 |
+
"dependencies": {
|
| 31 |
+
"@modelcontextprotocol/sdk": "^1.12.0",
|
| 32 |
+
"commander": "^12.0.0",
|
| 33 |
+
"zod": "^3.23.0"
|
| 34 |
+
},
|
| 35 |
+
"devDependencies": {
|
| 36 |
+
"@types/node": "^22.0.0",
|
| 37 |
+
"tsx": "^4.19.0",
|
| 38 |
+
"typescript": "^5.6.0",
|
| 39 |
+
"vitest": "^2.1.0"
|
| 40 |
+
}
|
| 41 |
+
}
|
src/checker/engine.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CheckFinding, CheckReport } from "../core/types.js";
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Rule-based adversarial code checker.
|
| 5 |
+
* Analyzes code content for correctness, security, and style issues.
|
| 6 |
+
* Designed to catch "almost right but not quite" AI-generated code problems.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
interface CheckRule {
|
| 10 |
+
id: string;
|
| 11 |
+
category: "correctness" | "security" | "style" | "performance";
|
| 12 |
+
severity: "critical" | "warning" | "info";
|
| 13 |
+
pattern: RegExp;
|
| 14 |
+
message: string;
|
| 15 |
+
suggestion?: string;
|
| 16 |
+
languages?: string[];
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const CHECK_RULES: CheckRule[] = [
|
| 20 |
+
// === Security ===
|
| 21 |
+
{
|
| 22 |
+
id: "SEC001",
|
| 23 |
+
category: "security",
|
| 24 |
+
severity: "critical",
|
| 25 |
+
pattern: /(?:exec|eval|system|child_process\.exec|Runtime\.getRuntime\(\)\.exec)\s*\(/,
|
| 26 |
+
message: "Dangerous command execution detected — potential command injection",
|
| 27 |
+
suggestion: "Use parameterized commands or avoid shell execution entirely",
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
id: "SEC002",
|
| 31 |
+
category: "security",
|
| 32 |
+
severity: "critical",
|
| 33 |
+
pattern: /(?:password|secret|token|api_key|apikey|private_key)\s*[=:]\s*["'][^"']+["']/i,
|
| 34 |
+
message: "Hardcoded credential or secret detected",
|
| 35 |
+
suggestion: "Use environment variables or a secrets manager",
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
id: "SEC003",
|
| 39 |
+
category: "security",
|
| 40 |
+
severity: "critical",
|
| 41 |
+
pattern: /(?:SELECT|INSERT|UPDATE|DELETE)\s+.*(?:\+\s*\w+|\$\{|f["'].*\{)/i,
|
| 42 |
+
message: "Possible SQL injection — string concatenation in query",
|
| 43 |
+
suggestion: "Use parameterized queries / prepared statements",
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
id: "SEC004",
|
| 47 |
+
category: "security",
|
| 48 |
+
severity: "warning",
|
| 49 |
+
pattern: /(?:innerHTML|dangerouslySetInnerHTML|v-html)\s*[=:]|document\.write\s*\(/,
|
| 50 |
+
message: "Direct HTML injection — potential XSS vulnerability",
|
| 51 |
+
suggestion: "Sanitize input or use safe DOM APIs (textContent, text-only rendering)",
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
id: "SEC005",
|
| 55 |
+
category: "security",
|
| 56 |
+
severity: "warning",
|
| 57 |
+
pattern: /(?:http:\/\/|verify\s*[:=]\s*false|rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0)/i,
|
| 58 |
+
message: "Insecure connection or disabled TLS verification",
|
| 59 |
+
suggestion: "Use HTTPS and verify TLS certificates",
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
id: "SEC006",
|
| 63 |
+
category: "security",
|
| 64 |
+
severity: "critical",
|
| 65 |
+
pattern: /(?:chmod\s+777|0777|os\.chmod\([^,]+,\s*0o?777)/,
|
| 66 |
+
message: "World-writable file permissions (777) — security risk",
|
| 67 |
+
suggestion: "Use restrictive permissions (e.g., 755 or 644)",
|
| 68 |
+
},
|
| 69 |
+
|
| 70 |
+
// === Correctness ===
|
| 71 |
+
{
|
| 72 |
+
id: "COR001",
|
| 73 |
+
category: "correctness",
|
| 74 |
+
severity: "warning",
|
| 75 |
+
pattern: /(?:==\s*null|!=\s*null|undefined\s*==|==\s*undefined)/,
|
| 76 |
+
message: "Loose null/undefined comparison — may cause type coercion bugs",
|
| 77 |
+
suggestion: "Use === null / !== null / ?? operator",
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
id: "COR002",
|
| 81 |
+
category: "correctness",
|
| 82 |
+
severity: "warning",
|
| 83 |
+
pattern: /catch\s*\(\s*\w+\s*\)\s*\{\s*\}/,
|
| 84 |
+
message: "Empty catch block — errors silently swallowed",
|
| 85 |
+
suggestion: "Log the error at minimum; consider re-throwing or handling",
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
id: "COR003",
|
| 89 |
+
category: "correctness",
|
| 90 |
+
severity: "warning",
|
| 91 |
+
pattern: /(?:\.length|\.size)\s*(?:===?|!==?)\s*0/,
|
| 92 |
+
message: "Length check without null guard — will throw if variable is null/undefined",
|
| 93 |
+
suggestion: "Add optional chaining (?.length) or null check first",
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
id: "COR004",
|
| 97 |
+
category: "correctness",
|
| 98 |
+
severity: "warning",
|
| 99 |
+
pattern: /new\s+Date\s*\(\s*(?:["']\d{4}-\d{2}-\d{2}["'])\s*\)/,
|
| 100 |
+
message: "Date parsing from string is timezone-dependent and unreliable",
|
| 101 |
+
suggestion: "Use Date.UTC() or a date library for consistent parsing",
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
id: "COR005",
|
| 105 |
+
category: "correctness",
|
| 106 |
+
severity: "warning",
|
| 107 |
+
pattern: /for\s*\(\s*var\s+\w+\s*(?:;|in|of)/,
|
| 108 |
+
message: "var in loop — closure/scoping bug risk",
|
| 109 |
+
suggestion: "Use let or const instead of var",
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
id: "COR006",
|
| 113 |
+
category: "correctness",
|
| 114 |
+
severity: "info",
|
| 115 |
+
pattern: /TODO|FIXME|HACK|XXX|PLACEHOLDER|Lorem ipsum/i,
|
| 116 |
+
message: "TODO/FIXME/placeholder marker — incomplete code",
|
| 117 |
+
suggestion: "Complete the implementation or remove the marker",
|
| 118 |
+
},
|
| 119 |
+
|
| 120 |
+
// === Style ===
|
| 121 |
+
{
|
| 122 |
+
id: "STY001",
|
| 123 |
+
category: "style",
|
| 124 |
+
severity: "info",
|
| 125 |
+
pattern: /console\.log\s*\(/,
|
| 126 |
+
message: "console.log left in code",
|
| 127 |
+
suggestion: "Remove debug logging or use a proper logging library",
|
| 128 |
+
languages: ["javascript", "typescript"],
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
id: "STY002",
|
| 132 |
+
category: "style",
|
| 133 |
+
severity: "info",
|
| 134 |
+
pattern: /(?:function\s+\w+\s*\([^)]*\)\s*\{[\s\S]{500,}?\})/,
|
| 135 |
+
message: "Function may be too long (>500 chars) — consider refactoring",
|
| 136 |
+
suggestion: "Break into smaller, focused functions",
|
| 137 |
+
},
|
| 138 |
+
|
| 139 |
+
// === Performance ===
|
| 140 |
+
{
|
| 141 |
+
id: "PERF001",
|
| 142 |
+
category: "performance",
|
| 143 |
+
severity: "warning",
|
| 144 |
+
pattern: /(?:SELECT\s+\*\s+FROM|(?:find|query)\s*\(\s*\{\s*\}\s*\))/i,
|
| 145 |
+
message: "Unbounded query — fetching all rows without limit",
|
| 146 |
+
suggestion: "Add pagination or limit clause",
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
id: "PERF002",
|
| 150 |
+
category: "performance",
|
| 151 |
+
severity: "info",
|
| 152 |
+
pattern: /(?:await\s+\w+\s+in\s+(?:a\s+)?for\s*\()/,
|
| 153 |
+
message: "Sequential await in loop — potential for parallel execution",
|
| 154 |
+
suggestion: "Consider Promise.all() for independent async operations",
|
| 155 |
+
},
|
| 156 |
+
];
|
| 157 |
+
|
| 158 |
+
/**
|
| 159 |
+
* Analyze code content and return findings.
|
| 160 |
+
*/
|
| 161 |
+
export function analyzeCode(content: string, filePath: string, language?: string): CheckFinding[] {
|
| 162 |
+
const findings: CheckFinding[] = [];
|
| 163 |
+
const lines = content.split("\n");
|
| 164 |
+
|
| 165 |
+
for (const rule of CHECK_RULES) {
|
| 166 |
+
if (rule.languages && language && !rule.languages.includes(language)) continue;
|
| 167 |
+
|
| 168 |
+
for (let i = 0; i < lines.length; i++) {
|
| 169 |
+
if (rule.pattern.test(lines[i])) {
|
| 170 |
+
findings.push({
|
| 171 |
+
severity: rule.severity,
|
| 172 |
+
category: rule.category,
|
| 173 |
+
message: `[${rule.id}] ${rule.message}`,
|
| 174 |
+
file: filePath,
|
| 175 |
+
line: i + 1,
|
| 176 |
+
suggestion: rule.suggestion,
|
| 177 |
+
});
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
return findings;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
/**
|
| 186 |
+
* Analyze multiple files and produce a report.
|
| 187 |
+
*/
|
| 188 |
+
export function generateReport(fileAnalyses: Array<{ path: string; content: string; language?: string }>): CheckReport {
|
| 189 |
+
const findings: CheckFinding[] = [];
|
| 190 |
+
|
| 191 |
+
for (const file of fileAnalyses) {
|
| 192 |
+
findings.push(...analyzeCode(file.content, file.path, file.language));
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// Sort: critical first, then warning, then info
|
| 196 |
+
const severityOrder = { critical: 0, warning: 1, info: 2 };
|
| 197 |
+
findings.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);
|
| 198 |
+
|
| 199 |
+
return {
|
| 200 |
+
findings,
|
| 201 |
+
filesChecked: fileAnalyses.length,
|
| 202 |
+
summary: {
|
| 203 |
+
critical: findings.filter((f) => f.severity === "critical").length,
|
| 204 |
+
warning: findings.filter((f) => f.severity === "warning").length,
|
| 205 |
+
info: findings.filter((f) => f.severity === "info").length,
|
| 206 |
+
},
|
| 207 |
+
};
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/**
|
| 211 |
+
* Format a check report for terminal output.
|
| 212 |
+
*/
|
| 213 |
+
export function formatReport(report: CheckReport): string {
|
| 214 |
+
const lines: string[] = [];
|
| 215 |
+
lines.push(`\n 📋 Code Health Report — ${report.filesChecked} file(s) checked\n`);
|
| 216 |
+
|
| 217 |
+
const icon = { critical: "🔴", warning: "🟡", info: "⚪" };
|
| 218 |
+
lines.push(` ${icon.critical} ${report.summary.critical} critical ${icon.warning} ${report.summary.warning} warning ${icon.info} ${report.summary.info} info\n`);
|
| 219 |
+
|
| 220 |
+
if (report.findings.length === 0) {
|
| 221 |
+
lines.push(" ✅ No issues found.\n");
|
| 222 |
+
return lines.join("\n");
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
for (const f of report.findings) {
|
| 226 |
+
lines.push(` ${icon[f.severity]} ${f.file}:${f.line ?? "?"}`);
|
| 227 |
+
lines.push(` ${f.message}`);
|
| 228 |
+
if (f.suggestion) {
|
| 229 |
+
lines.push(` 💡 ${f.suggestion}`);
|
| 230 |
+
}
|
| 231 |
+
lines.push("");
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
return lines.join("\n");
|
| 235 |
+
}
|
src/cli/commands/check.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { readFileSync, existsSync } from "node:fs";
|
| 2 |
+
import { resolve } from "node:path";
|
| 3 |
+
import { execSync } from "node:child_process";
|
| 4 |
+
import { generateReport, formatReport } from "../../checker/engine.js";
|
| 5 |
+
|
| 6 |
+
export async function checkCode(target: string, root: string): Promise<void> {
|
| 7 |
+
const absRoot = resolve(root);
|
| 8 |
+
console.log(`Checking code: ${target}\n`);
|
| 9 |
+
|
| 10 |
+
let fileAnalyses: Array<{ path: string; content: string; language?: string }> = [];
|
| 11 |
+
|
| 12 |
+
// Check if target is a file path
|
| 13 |
+
const filePath = resolve(absRoot, target);
|
| 14 |
+
if (existsSync(filePath)) {
|
| 15 |
+
const content = readFileSync(filePath, "utf-8");
|
| 16 |
+
const lang = detectLanguage(filePath);
|
| 17 |
+
fileAnalyses.push({ path: target, content, language: lang });
|
| 18 |
+
} else if (target.includes("..") || target.includes("HEAD")) {
|
| 19 |
+
// Git diff range
|
| 20 |
+
try {
|
| 21 |
+
const diffFiles = execSync(`git diff --name-only ${target}`, {
|
| 22 |
+
cwd: absRoot,
|
| 23 |
+
encoding: "utf-8",
|
| 24 |
+
})
|
| 25 |
+
.trim()
|
| 26 |
+
.split("\n")
|
| 27 |
+
.filter(Boolean);
|
| 28 |
+
|
| 29 |
+
for (const file of diffFiles) {
|
| 30 |
+
const fPath = resolve(absRoot, file);
|
| 31 |
+
if (existsSync(fPath)) {
|
| 32 |
+
const content = readFileSync(fPath, "utf-8");
|
| 33 |
+
fileAnalyses.push({ path: file, content, language: detectLanguage(file) });
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
} catch {
|
| 37 |
+
console.log(" ⚠ Could not read git diff. Make sure you're in a git repo with commits.");
|
| 38 |
+
console.log(" Usage: agentlens check <file> or agentlens check <git-diff-range>");
|
| 39 |
+
return;
|
| 40 |
+
}
|
| 41 |
+
} else {
|
| 42 |
+
console.log(` ⚠ File not found: ${target}`);
|
| 43 |
+
console.log(" Usage: agentlens check <file> or agentlens check HEAD~1..HEAD");
|
| 44 |
+
return;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
if (fileAnalyses.length === 0) {
|
| 48 |
+
console.log(" No files to check.");
|
| 49 |
+
return;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
const report = generateReport(fileAnalyses);
|
| 53 |
+
console.log(formatReport(report));
|
| 54 |
+
|
| 55 |
+
// Exit with non-zero if critical issues found
|
| 56 |
+
if (report.summary.critical > 0) {
|
| 57 |
+
console.log(` ❌ ${report.summary.critical} critical issue(s) found.\n`);
|
| 58 |
+
} else if (report.summary.warning > 0) {
|
| 59 |
+
console.log(` ⚠ ${report.summary.warning} warning(s) found.\n`);
|
| 60 |
+
} else {
|
| 61 |
+
console.log(" ✅ All clear.\n");
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
function detectLanguage(filePath: string): string | undefined {
|
| 66 |
+
const ext = filePath.split(".").pop()?.toLowerCase();
|
| 67 |
+
const langMap: Record<string, string> = {
|
| 68 |
+
ts: "typescript", tsx: "typescript",
|
| 69 |
+
js: "javascript", jsx: "javascript", mjs: "javascript",
|
| 70 |
+
py: "python",
|
| 71 |
+
go: "go",
|
| 72 |
+
rs: "rust",
|
| 73 |
+
java: "java",
|
| 74 |
+
rb: "ruby",
|
| 75 |
+
php: "php",
|
| 76 |
+
};
|
| 77 |
+
return ext ? langMap[ext] : undefined;
|
| 78 |
+
}
|
src/cli/commands/drift.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
|
| 2 |
+
import { resolve, join } from "node:path";
|
| 3 |
+
import type { Rule } from "../../core/types.js";
|
| 4 |
+
import { parsers } from "../../parsers/index.js";
|
| 5 |
+
import { detectDriftEntries, findMissingRules } from "../../drift/detect.js";
|
| 6 |
+
|
| 7 |
+
function findAgentFiles(root: string, agent: string): string[] {
|
| 8 |
+
const parser = parsers[agent];
|
| 9 |
+
if (!parser) return [];
|
| 10 |
+
const files: string[] = [];
|
| 11 |
+
for (const pattern of parser.filePatterns) {
|
| 12 |
+
if (pattern.includes("*")) {
|
| 13 |
+
const parts = pattern.split("/");
|
| 14 |
+
const dirParts = parts.slice(0, -1);
|
| 15 |
+
const filePattern = parts[parts.length - 1];
|
| 16 |
+
const dir = resolve(root, ...dirParts);
|
| 17 |
+
if (existsSync(dir) && statSync(dir).isDirectory()) {
|
| 18 |
+
const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");
|
| 19 |
+
for (const f of readdirSync(dir)) {
|
| 20 |
+
if (regex.test(f)) files.push(join(dir, f));
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
} else {
|
| 24 |
+
const filePath = resolve(root, pattern);
|
| 25 |
+
if (existsSync(filePath)) files.push(filePath);
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
return files;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
export async function detectDrift(root: string): Promise<void> {
|
| 32 |
+
const absRoot = resolve(root);
|
| 33 |
+
console.log(`Detecting config drift in ${absRoot}...\n`);
|
| 34 |
+
|
| 35 |
+
// Collect all rules per agent
|
| 36 |
+
const perAgent = new Map<string, Rule[]>();
|
| 37 |
+
for (const [agentName, parser] of Object.entries(parsers)) {
|
| 38 |
+
const files = findAgentFiles(absRoot, agentName);
|
| 39 |
+
if (files.length === 0) continue;
|
| 40 |
+
const rules: Rule[] = [];
|
| 41 |
+
for (const file of files) {
|
| 42 |
+
const content = readFileSync(file, "utf-8");
|
| 43 |
+
rules.push(...parser.parse(content, file));
|
| 44 |
+
}
|
| 45 |
+
perAgent.set(agentName, rules);
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const allRules = [...perAgent.values()].flat();
|
| 49 |
+
if (allRules.length === 0) {
|
| 50 |
+
console.log(" No agent rules found. Nothing to compare.");
|
| 51 |
+
return;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
console.log(` Analyzing ${allRules.length} rules across ${perAgent.size} agent(s)...\n`);
|
| 55 |
+
|
| 56 |
+
// 1. Inconsistent wording detection
|
| 57 |
+
const drifts = detectDriftEntries(allRules);
|
| 58 |
+
|
| 59 |
+
// 2. Missing category detection between agent pairs
|
| 60 |
+
const agents = [...perAgent.keys()];
|
| 61 |
+
if (agents.length >= 2) {
|
| 62 |
+
const base = perAgent.get(agents[0])!;
|
| 63 |
+
for (let i = 1; i < agents.length; i++) {
|
| 64 |
+
const other = perAgent.get(agents[i])!;
|
| 65 |
+
drifts.push(...findMissingRules(base, other, agents[0] as any, agents[i] as any));
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
if (drifts.length === 0) {
|
| 70 |
+
console.log(" ✅ No config drift detected. All rules are consistent.\n");
|
| 71 |
+
return;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
console.log(` ⚠ Found ${drifts.length} drift issue(s):\n`);
|
| 75 |
+
for (const drift of drifts) {
|
| 76 |
+
const icon = drift.type === "inconsistent" ? "🔄" : drift.type === "missing" ? "❌" : "⏰";
|
| 77 |
+
console.log(` ${icon} [${drift.type}]`);
|
| 78 |
+
console.log(` ${drift.description}`);
|
| 79 |
+
console.log();
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
console.log(" 💡 Consider consolidating these rules with `agentlens move`.");
|
| 83 |
+
}
|
src/cli/commands/install.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
| 2 |
+
import { resolve, dirname, join } from "node:path";
|
| 3 |
+
import { homedir } from "node:os";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* One-click installer: detects installed AI agents on this machine and writes
|
| 7 |
+
* the AgentLens MCP config into each one, so its tools appear directly in
|
| 8 |
+
* their settings/tool lists after a restart.
|
| 9 |
+
*
|
| 10 |
+
* Supported agents:
|
| 11 |
+
* claude — Claude Code / Claude Desktop (~/.claude/settings.json, mcpServers)
|
| 12 |
+
* cursor — Cursor (.cursor/mcp.json, mcpServers)
|
| 13 |
+
* codex — Codex / generic MCP (.mcp.json, mcpServers)
|
| 14 |
+
* zcode — ZCode (~/.zcode/mcp.json, mcpServers)
|
| 15 |
+
* workbuddy — WorkBuddy (~/.workbuddy/mcp.json, mcpServers)
|
| 16 |
+
* mimo — MiMo Desktop (~/.config/mimocode/mimocode.jsonc, mcp key)
|
| 17 |
+
*/
|
| 18 |
+
|
| 19 |
+
interface Detection {
|
| 20 |
+
key: string;
|
| 21 |
+
label: string;
|
| 22 |
+
configPath: string;
|
| 23 |
+
detectDirs: string[];
|
| 24 |
+
format: "mcpServers" | "mimocode";
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
export function detectAgents(): Detection[] {
|
| 28 |
+
const home = homedir();
|
| 29 |
+
const cwd = process.cwd();
|
| 30 |
+
return [
|
| 31 |
+
{
|
| 32 |
+
key: "claude",
|
| 33 |
+
label: "Claude Code / Claude Desktop",
|
| 34 |
+
configPath: join(home, ".claude", "settings.json"),
|
| 35 |
+
detectDirs: [join(home, ".claude")],
|
| 36 |
+
format: "mcpServers",
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
key: "cursor",
|
| 40 |
+
label: "Cursor",
|
| 41 |
+
configPath: join(cwd, ".cursor", "mcp.json"),
|
| 42 |
+
detectDirs: [join(home, "Library", "Application Support", "Cursor"), join(home, ".cursor")],
|
| 43 |
+
format: "mcpServers",
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
key: "codex",
|
| 47 |
+
label: "Codex / 通用 MCP 客户端",
|
| 48 |
+
configPath: join(cwd, ".mcp.json"),
|
| 49 |
+
detectDirs: [cwd],
|
| 50 |
+
format: "mcpServers",
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
key: "zcode",
|
| 54 |
+
label: "ZCode",
|
| 55 |
+
configPath: join(home, ".zcode", "mcp.json"),
|
| 56 |
+
detectDirs: [join(home, ".zcode")],
|
| 57 |
+
format: "mcpServers",
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
key: "workbuddy",
|
| 61 |
+
label: "WorkBuddy",
|
| 62 |
+
configPath: join(home, ".workbuddy", "mcp.json"),
|
| 63 |
+
detectDirs: [join(home, ".workbuddy"), join(home, ".workbuddy-ai")],
|
| 64 |
+
format: "mcpServers",
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
key: "mimo",
|
| 68 |
+
label: "MiMo Desktop",
|
| 69 |
+
configPath: join(home, ".config", "mimocode", "mimocode.jsonc"),
|
| 70 |
+
detectDirs: [join(home, ".config", "mimocode"), join(home, "Library", "Application Support", "Xiaomi MiMo")],
|
| 71 |
+
format: "mimocode",
|
| 72 |
+
},
|
| 73 |
+
];
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/** Resolve the agentlens entry command: local dist if available, else npx. */
|
| 77 |
+
export function resolveEntry(): { command: string; args: string[] } {
|
| 78 |
+
// When running from a local checkout, prefer the built CLI (agentlens may not
|
| 79 |
+
// be published to npm yet).
|
| 80 |
+
const here = dirname(new URL(import.meta.url).pathname);
|
| 81 |
+
const localDist = resolve(here, "../../../dist/cli/index.js");
|
| 82 |
+
if (existsSync(localDist)) {
|
| 83 |
+
return { command: process.execPath, args: [localDist, "mcp"] };
|
| 84 |
+
}
|
| 85 |
+
return { command: "npx", args: ["-y", "agentlens", "mcp"] };
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
function writeMcpServersConfig(configPath: string, serverName = "agentlens"): void {
|
| 89 |
+
let config: Record<string, unknown> = {};
|
| 90 |
+
if (existsSync(configPath)) {
|
| 91 |
+
try {
|
| 92 |
+
config = JSON.parse(readFileSync(configPath, "utf-8"));
|
| 93 |
+
} catch {
|
| 94 |
+
// invalid JSON — leave the file untouched and report
|
| 95 |
+
throw new Error(`无法解析 ${configPath}(不是有效 JSON),请手动添加配置`);
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
const mcpServers = (config.mcpServers as Record<string, unknown>) ?? {};
|
| 99 |
+
const entry = resolveEntry();
|
| 100 |
+
mcpServers[serverName] = {
|
| 101 |
+
command: entry.command,
|
| 102 |
+
args: entry.args,
|
| 103 |
+
};
|
| 104 |
+
config.mcpServers = mcpServers;
|
| 105 |
+
mkdirSync(dirname(configPath), { recursive: true });
|
| 106 |
+
writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
function writeMimocodeConfig(configPath: string, serverName = "agentlens"): void {
|
| 110 |
+
let config: Record<string, unknown> = {};
|
| 111 |
+
if (existsSync(configPath)) {
|
| 112 |
+
try {
|
| 113 |
+
config = JSON.parse(readFileSync(configPath, "utf-8"));
|
| 114 |
+
} catch {
|
| 115 |
+
throw new Error(`无法解析 ${configPath},请手动添加 mcp 配置`);
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
const mcp = (config.mcp as Record<string, unknown>) ?? {};
|
| 119 |
+
const entry = resolveEntry();
|
| 120 |
+
mcp[serverName] = {
|
| 121 |
+
type: "local",
|
| 122 |
+
command: [entry.command, ...entry.args],
|
| 123 |
+
enabled: true,
|
| 124 |
+
};
|
| 125 |
+
config.mcp = mcp;
|
| 126 |
+
// Write as JSON (jsonc accepts plain JSON — comments would be lost, so back up first)
|
| 127 |
+
if (existsSync(configPath)) {
|
| 128 |
+
const backup = configPath + ".bak-agentlens";
|
| 129 |
+
if (!existsSync(backup)) {
|
| 130 |
+
writeFileSync(backup, readFileSync(configPath, "utf-8"));
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
mkdirSync(dirname(configPath), { recursive: true });
|
| 134 |
+
writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
export async function installTo(target: string): Promise<void> {
|
| 138 |
+
console.log("AgentLens 安装器\n");
|
| 139 |
+
|
| 140 |
+
const detections = detectAgents();
|
| 141 |
+
|
| 142 |
+
const installOne = (d: Detection): boolean => {
|
| 143 |
+
try {
|
| 144 |
+
if (d.format === "mimocode") {
|
| 145 |
+
writeMimocodeConfig(d.configPath);
|
| 146 |
+
} else {
|
| 147 |
+
writeMcpServersConfig(d.configPath);
|
| 148 |
+
}
|
| 149 |
+
console.log(` ✅ ${d.label} → ${d.configPath}`);
|
| 150 |
+
return true;
|
| 151 |
+
} catch (err: any) {
|
| 152 |
+
console.log(` ❌ ${d.label}: ${err.message}`);
|
| 153 |
+
return false;
|
| 154 |
+
}
|
| 155 |
+
};
|
| 156 |
+
|
| 157 |
+
if (target !== "all") {
|
| 158 |
+
const one = detections.find((d) => d.key === target);
|
| 159 |
+
if (!one) {
|
| 160 |
+
console.log(`未知目标: ${target}`);
|
| 161 |
+
console.log(`支持: ${detections.map((d) => d.key).join(", ")}, all`);
|
| 162 |
+
return;
|
| 163 |
+
}
|
| 164 |
+
installOne(one);
|
| 165 |
+
console.log(`\n 重启应用后,在 MCP / 工具设置中即可看到 AgentLens。`);
|
| 166 |
+
return;
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
console.log("检测到以下已安装的 AI 工具:\n");
|
| 170 |
+
let count = 0;
|
| 171 |
+
for (const d of detections) {
|
| 172 |
+
const isInstalled = d.detectDirs.some((dir) => existsSync(dir));
|
| 173 |
+
if (!isInstalled) continue;
|
| 174 |
+
if (installOne(d)) count++;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
if (count === 0) {
|
| 178 |
+
console.log(" 未检测到已安装的 AI 工具。");
|
| 179 |
+
console.log(" 手动指定目标: agentlens install --target claude|cursor|codex|zcode|workbuddy|mimo");
|
| 180 |
+
return;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
console.log(`\n配置完成: ${count} 个工具已写入 AgentLens MCP。`);
|
| 184 |
+
console.log("重启对应应用后,在 MCP/工具设置里即可看到:");
|
| 185 |
+
console.log(" · agentlens_scan 扫描 Agent 配置");
|
| 186 |
+
console.log(" · agentlens_move 迁移规则");
|
| 187 |
+
console.log(" · agentlens_drift 检测配置漂移");
|
| 188 |
+
console.log(" · agentlens_check 代码体检");
|
| 189 |
+
}
|
src/cli/commands/move.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from "node:fs";
|
| 2 |
+
import { dirname, join, resolve } from "node:path";
|
| 3 |
+
import type { Rule, AgentKind } from "../../core/types.js";
|
| 4 |
+
import { parsers } from "../../parsers/index.js";
|
| 5 |
+
import { generateConfig, outputFileFor } from "../../migrator/generate.js";
|
| 6 |
+
|
| 7 |
+
interface MoveOpts {
|
| 8 |
+
from: string;
|
| 9 |
+
to: string;
|
| 10 |
+
path: string;
|
| 11 |
+
output?: string;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
/** Find all config files for a given agent in the project. */
|
| 15 |
+
function findAgentFiles(root: string, agent: string): string[] {
|
| 16 |
+
const parser = parsers[agent];
|
| 17 |
+
if (!parser) return [];
|
| 18 |
+
const files: string[] = [];
|
| 19 |
+
|
| 20 |
+
for (const pattern of parser.filePatterns) {
|
| 21 |
+
if (pattern.includes("*")) {
|
| 22 |
+
// Glob like ".cursor/rules/*.mdc"
|
| 23 |
+
const parts = pattern.split("/");
|
| 24 |
+
const dirParts = parts.slice(0, -1);
|
| 25 |
+
const filePattern = parts[parts.length - 1];
|
| 26 |
+
const dir = resolve(root, ...dirParts);
|
| 27 |
+
if (existsSync(dir) && statSync(dir).isDirectory()) {
|
| 28 |
+
const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");
|
| 29 |
+
for (const f of readdirSync(dir)) {
|
| 30 |
+
if (regex.test(f)) files.push(join(dir, f));
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
} else {
|
| 34 |
+
const filePath = resolve(root, pattern);
|
| 35 |
+
if (existsSync(filePath)) files.push(filePath);
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
return files;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
/** Parse all rules from source agent files. */
|
| 42 |
+
function parseRules(root: string, agent: string): Rule[] {
|
| 43 |
+
const parser = parsers[agent];
|
| 44 |
+
if (!parser) throw new Error(`Unknown agent: ${agent}. Supported: ${Object.keys(parsers).join(", ")}`);
|
| 45 |
+
|
| 46 |
+
const files = findAgentFiles(root, agent);
|
| 47 |
+
const rules: Rule[] = [];
|
| 48 |
+
for (const file of files) {
|
| 49 |
+
const content = readFileSync(file, "utf-8");
|
| 50 |
+
rules.push(...parser.parse(content, file));
|
| 51 |
+
}
|
| 52 |
+
return rules;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export async function moveRules(opts: MoveOpts): Promise<void> {
|
| 56 |
+
const root = resolve(opts.path);
|
| 57 |
+
const fromAgent = opts.from as AgentKind;
|
| 58 |
+
const toAgent = opts.to as AgentKind;
|
| 59 |
+
|
| 60 |
+
console.log(`Migrating rules: ${opts.from} → ${opts.to}\n`);
|
| 61 |
+
|
| 62 |
+
// Parse source rules
|
| 63 |
+
const rules = parseRules(root, opts.from);
|
| 64 |
+
if (rules.length === 0) {
|
| 65 |
+
console.log(`⚠ No rules found for agent "${opts.from}" in ${root}`);
|
| 66 |
+
const files = findAgentFiles(root, opts.from);
|
| 67 |
+
if (files.length === 0) {
|
| 68 |
+
console.log(` No config files found. Looked for: ${parsers[opts.from]?.filePatterns.join(", ")}`);
|
| 69 |
+
}
|
| 70 |
+
return;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
console.log(` Found ${rules.length} rules from ${rules.length > 0 ? rules[0].source.file : "?"}\n`);
|
| 74 |
+
|
| 75 |
+
// Generate target format
|
| 76 |
+
const output = generateConfig(rules, toAgent);
|
| 77 |
+
const outputPath = opts.output
|
| 78 |
+
? resolve(root, opts.output)
|
| 79 |
+
: resolve(root, outputFileFor(toAgent));
|
| 80 |
+
|
| 81 |
+
// Write output
|
| 82 |
+
mkdirSync(dirname(outputPath), { recursive: true });
|
| 83 |
+
writeFileSync(outputPath, output, "utf-8");
|
| 84 |
+
|
| 85 |
+
console.log(` ✅ Generated ${outputPath}`);
|
| 86 |
+
console.log(` ${rules.length} rules converted from ${opts.from} format to ${opts.to} format\n`);
|
| 87 |
+
|
| 88 |
+
// Show preview
|
| 89 |
+
const preview = output.split("\n").slice(0, 15).join("\n");
|
| 90 |
+
console.log(` Preview:\n ${preview.split("\n").join("\n ")}`);
|
| 91 |
+
}
|
src/cli/commands/scan.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
|
| 2 |
+
import { resolve, join } from "node:path";
|
| 3 |
+
import type { Rule } from "../../core/types.js";
|
| 4 |
+
import { parsers } from "../../parsers/index.js";
|
| 5 |
+
|
| 6 |
+
function findAgentFiles(root: string, agent: string): string[] {
|
| 7 |
+
const parser = parsers[agent];
|
| 8 |
+
if (!parser) return [];
|
| 9 |
+
const files: string[] = [];
|
| 10 |
+
|
| 11 |
+
for (const pattern of parser.filePatterns) {
|
| 12 |
+
if (pattern.includes("*")) {
|
| 13 |
+
const parts = pattern.split("/");
|
| 14 |
+
const dirParts = parts.slice(0, -1);
|
| 15 |
+
const filePattern = parts[parts.length - 1];
|
| 16 |
+
const dir = resolve(root, ...dirParts);
|
| 17 |
+
if (existsSync(dir) && statSync(dir).isDirectory()) {
|
| 18 |
+
const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");
|
| 19 |
+
for (const f of readdirSync(dir)) {
|
| 20 |
+
if (regex.test(f)) files.push(join(dir, f));
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
} else {
|
| 24 |
+
const filePath = resolve(root, pattern);
|
| 25 |
+
if (existsSync(filePath)) files.push(filePath);
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
return files;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
export async function scanProject(root: string): Promise<void> {
|
| 32 |
+
const absRoot = resolve(root);
|
| 33 |
+
console.log(`Scanning ${absRoot} for AI agent configs...\n`);
|
| 34 |
+
|
| 35 |
+
let foundAny = false;
|
| 36 |
+
|
| 37 |
+
for (const [agentName, parser] of Object.entries(parsers)) {
|
| 38 |
+
const files = findAgentFiles(absRoot, agentName);
|
| 39 |
+
if (files.length === 0) continue;
|
| 40 |
+
foundAny = true;
|
| 41 |
+
|
| 42 |
+
const allRules: Rule[] = [];
|
| 43 |
+
for (const file of files) {
|
| 44 |
+
const content = readFileSync(file, "utf-8");
|
| 45 |
+
allRules.push(...parser.parse(content, file));
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const categoryCounts = new Map<string, number>();
|
| 49 |
+
for (const r of allRules) {
|
| 50 |
+
categoryCounts.set(r.category, (categoryCounts.get(r.category) ?? 0) + 1);
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
console.log(` ✅ ${agentName.toUpperCase()} — ${files.length} file(s), ${allRules.length} rules`);
|
| 54 |
+
for (const file of files) {
|
| 55 |
+
console.log(` 📄 ${file.replace(absRoot, ".")}`);
|
| 56 |
+
}
|
| 57 |
+
const cats = [...categoryCounts.entries()].map(([c, n]) => `${c}(${n})`).join(", ");
|
| 58 |
+
console.log(` Categories: ${cats}\n`);
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
if (!foundAny) {
|
| 62 |
+
console.log(" No agent configs found. Supported:");
|
| 63 |
+
for (const [name, parser] of Object.entries(parsers)) {
|
| 64 |
+
console.log(` ${name}: ${parser.filePatterns.join(", ")}`);
|
| 65 |
+
}
|
| 66 |
+
console.log("\n Tip: run `agentlens install` to set up AgentLens for your agents.");
|
| 67 |
+
} else {
|
| 68 |
+
console.log(" 💡 Run `agentlens move --from <agent> --to <agent>` to migrate rules.");
|
| 69 |
+
console.log(" 💡 Run `agentlens drift` to check for config drift.");
|
| 70 |
+
}
|
| 71 |
+
}
|
src/cli/index.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
import { Command } from "commander";
|
| 3 |
+
import { readFileSync } from "node:fs";
|
| 4 |
+
import { dirname, join } from "node:path";
|
| 5 |
+
import { fileURLToPath } from "node:url";
|
| 6 |
+
|
| 7 |
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
| 8 |
+
const pkg = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));
|
| 9 |
+
|
| 10 |
+
const program = new Command();
|
| 11 |
+
|
| 12 |
+
program
|
| 13 |
+
.name("agentlens")
|
| 14 |
+
.description("Cross-agent config migration & output QA for AI coding agents")
|
| 15 |
+
.version(pkg.version);
|
| 16 |
+
|
| 17 |
+
program
|
| 18 |
+
.command("scan")
|
| 19 |
+
.description("Detect all AI agent configs in the current project and show rules summary")
|
| 20 |
+
.option("-p, --path <path>", "project root", process.cwd())
|
| 21 |
+
.action(async (opts) => {
|
| 22 |
+
const { scanProject } = await import("./commands/scan.js");
|
| 23 |
+
await scanProject(opts.path);
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
program
|
| 27 |
+
.command("move")
|
| 28 |
+
.description("Migrate rules from one agent format to another")
|
| 29 |
+
.requiredOption("--from <agent>", "source agent (claude|cursor|codex|windsurf|copilot)")
|
| 30 |
+
.requiredOption("--to <agent>", "target agent (claude|cursor|codex|windsurf|copilot)")
|
| 31 |
+
.option("-p, --path <path>", "project root", process.cwd())
|
| 32 |
+
.option("-o, --output <file>", "output file path")
|
| 33 |
+
.action(async (opts) => {
|
| 34 |
+
const { moveRules } = await import("./commands/move.js");
|
| 35 |
+
await moveRules(opts);
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
program
|
| 39 |
+
.command("drift")
|
| 40 |
+
.description("Detect config drift across agent rule files")
|
| 41 |
+
.option("-p, --path <path>", "project root", process.cwd())
|
| 42 |
+
.action(async (opts) => {
|
| 43 |
+
const { detectDrift } = await import("./commands/drift.js");
|
| 44 |
+
await detectDrift(opts.path);
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
program
|
| 48 |
+
.command("check")
|
| 49 |
+
.description("Run adversarial QA on code changes or files")
|
| 50 |
+
.argument("[target]", "git diff range or file path", "HEAD~1..HEAD")
|
| 51 |
+
.option("-p, --path <path>", "project root", process.cwd())
|
| 52 |
+
.action(async (target, opts) => {
|
| 53 |
+
const { checkCode } = await import("./commands/check.js");
|
| 54 |
+
await checkCode(target, opts.path);
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
program
|
| 58 |
+
.command("install")
|
| 59 |
+
.description("One-click install AgentLens into target AI agents as MCP server")
|
| 60 |
+
.option("--target <agent>", "target agent (claude|cursor|codex|all)", "all")
|
| 61 |
+
.action(async (opts) => {
|
| 62 |
+
const { installTo } = await import("./commands/install.js");
|
| 63 |
+
await installTo(opts.target);
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
program
|
| 67 |
+
.command("mcp")
|
| 68 |
+
.description("Start AgentLens as an MCP server (for Claude Code, Cursor, etc.)")
|
| 69 |
+
.action(async () => {
|
| 70 |
+
const { startMcpServer } = await import("../mcp/server.js");
|
| 71 |
+
await startMcpServer();
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
program.parse();
|
src/core/types.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* AgentLens Core Types — Unified Rule IR (Intermediate Representation)
|
| 3 |
+
*
|
| 4 |
+
* Every agent config (CLAUDE.md, .cursor/rules/, AGENTS.md, etc.) is parsed
|
| 5 |
+
* into this canonical form, then re-generated for any target agent.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
export type RuleCategory = "style" | "workflow" | "constraint" | "context" | "tooling";
|
| 9 |
+
|
| 10 |
+
export type RuleStatus = "active" | "suspect" | "stale";
|
| 11 |
+
|
| 12 |
+
export type AgentKind =
|
| 13 |
+
| "claude"
|
| 14 |
+
| "cursor"
|
| 15 |
+
| "codex"
|
| 16 |
+
| "windsurf"
|
| 17 |
+
| "copilot"
|
| 18 |
+
| "generic";
|
| 19 |
+
|
| 20 |
+
export interface RuleSource {
|
| 21 |
+
agent: AgentKind;
|
| 22 |
+
file: string;
|
| 23 |
+
line?: number;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export interface Rule {
|
| 27 |
+
id: string;
|
| 28 |
+
category: RuleCategory;
|
| 29 |
+
content: string;
|
| 30 |
+
scope: "global" | "project" | "path-glob";
|
| 31 |
+
scopePattern?: string;
|
| 32 |
+
source: RuleSource;
|
| 33 |
+
status: RuleStatus;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
export interface AgentConfig {
|
| 37 |
+
agent: AgentKind;
|
| 38 |
+
root: string;
|
| 39 |
+
rules: Rule[];
|
| 40 |
+
rawFiles: string[];
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export interface DriftEntry {
|
| 44 |
+
ruleId: string;
|
| 45 |
+
type: "inconsistent" | "stale" | "missing";
|
| 46 |
+
description: string;
|
| 47 |
+
locations: RuleSource[];
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export interface MigrationResult {
|
| 51 |
+
from: AgentKind;
|
| 52 |
+
to: AgentKind;
|
| 53 |
+
rules: Rule[];
|
| 54 |
+
outputPath: string;
|
| 55 |
+
warnings: string[];
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
export interface CheckFinding {
|
| 59 |
+
severity: "critical" | "warning" | "info";
|
| 60 |
+
category: "correctness" | "security" | "style" | "performance";
|
| 61 |
+
message: string;
|
| 62 |
+
file: string;
|
| 63 |
+
line?: number;
|
| 64 |
+
suggestion?: string;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
export interface CheckReport {
|
| 68 |
+
findings: CheckFinding[];
|
| 69 |
+
filesChecked: number;
|
| 70 |
+
summary: { critical: number; warning: number; info: number };
|
| 71 |
+
}
|
src/drift/detect.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule, DriftEntry, AgentKind } from "../core/types.js";
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Detect drift across agent rule sets:
|
| 5 |
+
* 1. Same conceptual rule with different wording across agents → "inconsistent"
|
| 6 |
+
* 2. Rule referencing tools/paths that don't exist → "stale"
|
| 7 |
+
* 3. Rule present in one agent but missing in another → "missing"
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
/** Normalize rule text for fuzzy comparison. */
|
| 11 |
+
function normalize(text: string): string {
|
| 12 |
+
return text
|
| 13 |
+
.toLowerCase()
|
| 14 |
+
.replace(/[^\w\s一-鿿]/g, "")
|
| 15 |
+
.replace(/\s+/g, " ")
|
| 16 |
+
.trim();
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
/** Compute word overlap similarity between two strings (0-1). */
|
| 20 |
+
function similarity(a: string, b: string): number {
|
| 21 |
+
const wordsA = new Set(normalize(a).split(" "));
|
| 22 |
+
const wordsB = new Set(normalize(b).split(" "));
|
| 23 |
+
if (wordsA.size === 0 || wordsB.size === 0) return 0;
|
| 24 |
+
let common = 0;
|
| 25 |
+
for (const w of wordsA) {
|
| 26 |
+
if (wordsB.has(w)) common++;
|
| 27 |
+
}
|
| 28 |
+
return common / Math.max(wordsA.size, wordsB.size);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
export function detectDriftEntries(allRules: Rule[]): DriftEntry[] {
|
| 32 |
+
const entries: DriftEntry[] = [];
|
| 33 |
+
const processed = new Set<string>();
|
| 34 |
+
|
| 35 |
+
for (let i = 0; i < allRules.length; i++) {
|
| 36 |
+
for (let j = i + 1; j < allRules.length; j++) {
|
| 37 |
+
const a = allRules[i];
|
| 38 |
+
const b = allRules[j];
|
| 39 |
+
// Skip if from the same file
|
| 40 |
+
if (a.source.file === b.source.file && a.source.agent === b.source.agent) continue;
|
| 41 |
+
|
| 42 |
+
const sim = similarity(a.content, b.content);
|
| 43 |
+
|
| 44 |
+
// Similar but not identical → inconsistent drift
|
| 45 |
+
if (sim >= 0.5 && sim < 1.0 && a.content !== b.content) {
|
| 46 |
+
const key = [a.id, b.id].sort().join("|");
|
| 47 |
+
if (!processed.has(key)) {
|
| 48 |
+
processed.add(key);
|
| 49 |
+
entries.push({
|
| 50 |
+
ruleId: a.id,
|
| 51 |
+
type: "inconsistent",
|
| 52 |
+
description: `Similar rules with different wording (${Math.round(sim * 100)}% match):\n "${a.content.slice(0, 80)}" (${a.source.agent})\n "${b.content.slice(0, 80)}" (${b.source.agent})`,
|
| 53 |
+
locations: [a.source, b.source],
|
| 54 |
+
});
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
return entries;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
/**
|
| 64 |
+
* Find rules that exist in one agent but not another (by category coverage).
|
| 65 |
+
*/
|
| 66 |
+
export function findMissingRules(
|
| 67 |
+
sourceRules: Rule[],
|
| 68 |
+
targetRules: Rule[],
|
| 69 |
+
sourceAgent: AgentKind,
|
| 70 |
+
targetAgent: AgentKind
|
| 71 |
+
): DriftEntry[] {
|
| 72 |
+
const entries: DriftEntry[] = [];
|
| 73 |
+
const sourceCategories = new Set(sourceRules.map((r) => r.category));
|
| 74 |
+
const targetCategories = new Set(targetRules.map((r) => r.category));
|
| 75 |
+
|
| 76 |
+
for (const cat of sourceCategories) {
|
| 77 |
+
if (!targetCategories.has(cat)) {
|
| 78 |
+
const sample = sourceRules.find((r) => r.category === cat);
|
| 79 |
+
entries.push({
|
| 80 |
+
ruleId: `missing-${cat}`,
|
| 81 |
+
type: "missing",
|
| 82 |
+
description: `Category "${cat}" has rules in ${sourceAgent} but none in ${targetAgent} (example: "${sample?.content.slice(0, 60)}")`,
|
| 83 |
+
locations: [{ agent: sourceAgent, file: "source" }],
|
| 84 |
+
});
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
return entries;
|
| 89 |
+
}
|
src/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export * from "./core/types.js";
|
| 2 |
+
export { parsers, getParser } from "./parsers/index.js";
|
| 3 |
+
export { generateConfig, outputFileFor } from "./migrator/generate.js";
|
| 4 |
+
export { detectDriftEntries, findMissingRules } from "./drift/detect.js";
|
| 5 |
+
export { generateReport, formatReport, analyzeCode } from "./checker/engine.js";
|
src/mcp/server.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
| 2 |
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
| 3 |
+
import { z } from "zod";
|
| 4 |
+
import { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";
|
| 5 |
+
import { resolve, join, dirname } from "node:path";
|
| 6 |
+
import { parsers } from "../parsers/index.js";
|
| 7 |
+
import { generateConfig, outputFileFor } from "../migrator/generate.js";
|
| 8 |
+
import { detectDriftEntries } from "../drift/detect.js";
|
| 9 |
+
import { generateReport, formatReport } from "../checker/engine.js";
|
| 10 |
+
import type { Rule, AgentKind } from "../core/types.js";
|
| 11 |
+
|
| 12 |
+
function findAgentFiles(root: string, agent: string): string[] {
|
| 13 |
+
const parser = parsers[agent];
|
| 14 |
+
if (!parser) return [];
|
| 15 |
+
const files: string[] = [];
|
| 16 |
+
for (const pattern of parser.filePatterns) {
|
| 17 |
+
if (pattern.includes("*")) {
|
| 18 |
+
const parts = pattern.split("/");
|
| 19 |
+
const dirParts = parts.slice(0, -1);
|
| 20 |
+
const filePattern = parts[parts.length - 1];
|
| 21 |
+
const dir = resolve(root, ...dirParts);
|
| 22 |
+
if (existsSync(dir) && statSync(dir).isDirectory()) {
|
| 23 |
+
const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");
|
| 24 |
+
for (const f of readdirSync(dir)) {
|
| 25 |
+
if (regex.test(f)) files.push(join(dir, f));
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
} else {
|
| 29 |
+
const filePath = resolve(root, pattern);
|
| 30 |
+
if (existsSync(filePath)) files.push(filePath);
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
return files;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
function collectRules(root: string): Array<{ agent: string; rules: Rule[]; files: string[] }> {
|
| 37 |
+
const results: Array<{ agent: string; rules: Rule[]; files: string[] }> = [];
|
| 38 |
+
for (const [agentName, parser] of Object.entries(parsers)) {
|
| 39 |
+
const files = findAgentFiles(root, agentName);
|
| 40 |
+
if (files.length === 0) continue;
|
| 41 |
+
const rules: Rule[] = [];
|
| 42 |
+
for (const file of files) {
|
| 43 |
+
rules.push(...parser.parse(readFileSync(file, "utf-8"), file));
|
| 44 |
+
}
|
| 45 |
+
results.push({ agent: agentName, rules, files });
|
| 46 |
+
}
|
| 47 |
+
return results;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export function createMcpServer(): McpServer {
|
| 51 |
+
const server = new McpServer({
|
| 52 |
+
name: "agentlens",
|
| 53 |
+
version: "0.1.0",
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
// === scan ===
|
| 57 |
+
server.tool(
|
| 58 |
+
"agentlens_scan",
|
| 59 |
+
"Scan the project for AI agent config files (CLAUDE.md, .cursor/rules, AGENTS.md etc.) and summarize rules found",
|
| 60 |
+
{
|
| 61 |
+
path: z.string().optional().describe("Project root path (defaults to cwd)"),
|
| 62 |
+
},
|
| 63 |
+
async ({ path }) => {
|
| 64 |
+
const root = resolve(path ?? process.cwd());
|
| 65 |
+
const results = collectRules(root);
|
| 66 |
+
|
| 67 |
+
if (results.length === 0) {
|
| 68 |
+
return {
|
| 69 |
+
content: [{ type: "text", text: `No agent configs found in ${root}. Supported: claude (CLAUDE.md), cursor (.cursor/rules), codex (AGENTS.md)` }],
|
| 70 |
+
};
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
const lines: string[] = [`Agent config scan for ${root}:\n`];
|
| 74 |
+
for (const r of results) {
|
| 75 |
+
const cats = new Map<string, number>();
|
| 76 |
+
for (const rule of r.rules) cats.set(rule.category, (cats.get(rule.category) ?? 0) + 1);
|
| 77 |
+
const catStr = [...cats.entries()].map(([c, n]) => `${c}(${n})`).join(", ");
|
| 78 |
+
lines.push(`${r.agent.toUpperCase()}: ${r.rules.length} rules from ${r.files.length} file(s) [${catStr}]`);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
| 82 |
+
}
|
| 83 |
+
);
|
| 84 |
+
|
| 85 |
+
// === move ===
|
| 86 |
+
server.tool(
|
| 87 |
+
"agentlens_move",
|
| 88 |
+
"Migrate agent config rules from one format to another (e.g., CLAUDE.md → .cursor/rules/)",
|
| 89 |
+
{
|
| 90 |
+
from: z.enum(["claude", "cursor", "codex", "windsurf", "copilot"]).describe("Source agent format"),
|
| 91 |
+
to: z.enum(["claude", "cursor", "codex", "windsurf", "copilot"]).describe("Target agent format"),
|
| 92 |
+
path: z.string().optional().describe("Project root path"),
|
| 93 |
+
output: z.string().optional().describe("Custom output file path"),
|
| 94 |
+
},
|
| 95 |
+
async ({ from, to, path, output }) => {
|
| 96 |
+
const root = resolve(path ?? process.cwd());
|
| 97 |
+
const parser = parsers[from];
|
| 98 |
+
if (!parser) return { content: [{ type: "text", text: `Unknown agent: ${from}` }] };
|
| 99 |
+
|
| 100 |
+
const files = findAgentFiles(root, from);
|
| 101 |
+
const rules: Rule[] = [];
|
| 102 |
+
for (const file of files) {
|
| 103 |
+
rules.push(...parser.parse(readFileSync(file, "utf-8"), file));
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if (rules.length === 0) {
|
| 107 |
+
return { content: [{ type: "text", text: `No ${from} rules found in ${root}` }] };
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
const content = generateConfig(rules, to as AgentKind);
|
| 111 |
+
const outPath = output ? resolve(root, output) : resolve(root, outputFileFor(to as AgentKind));
|
| 112 |
+
mkdirSync(dirname(outPath), { recursive: true });
|
| 113 |
+
writeFileSync(outPath, content, "utf-8");
|
| 114 |
+
|
| 115 |
+
return {
|
| 116 |
+
content: [{
|
| 117 |
+
type: "text",
|
| 118 |
+
text: `Migrated ${rules.length} rules from ${from} to ${to}\nOutput: ${outPath}\n\nPreview:\n${content.slice(0, 500)}`,
|
| 119 |
+
}],
|
| 120 |
+
};
|
| 121 |
+
}
|
| 122 |
+
);
|
| 123 |
+
|
| 124 |
+
// === drift ===
|
| 125 |
+
server.tool(
|
| 126 |
+
"agentlens_drift",
|
| 127 |
+
"Detect config drift across agent rule files (similar rules with different wording)",
|
| 128 |
+
{
|
| 129 |
+
path: z.string().optional().describe("Project root path"),
|
| 130 |
+
},
|
| 131 |
+
async ({ path }) => {
|
| 132 |
+
const root = resolve(path ?? process.cwd());
|
| 133 |
+
const results = collectRules(root);
|
| 134 |
+
const allRules = results.flatMap((r) => r.rules);
|
| 135 |
+
|
| 136 |
+
if (allRules.length === 0) {
|
| 137 |
+
return { content: [{ type: "text", text: "No agent rules found to compare." }] };
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
const drifts = detectDriftEntries(allRules);
|
| 141 |
+
if (drifts.length === 0) {
|
| 142 |
+
return { content: [{ type: "text", text: `No config drift detected across ${allRules.length} rules.` }] };
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
const lines = [`Found ${drifts.length} drift issue(s):\n`];
|
| 146 |
+
for (const d of drifts) {
|
| 147 |
+
lines.push(`[${d.type}] ${d.description}`);
|
| 148 |
+
}
|
| 149 |
+
return { content: [{ type: "text", text: lines.join("\n\n") }] };
|
| 150 |
+
}
|
| 151 |
+
);
|
| 152 |
+
|
| 153 |
+
// === check ===
|
| 154 |
+
server.tool(
|
| 155 |
+
"agentlens_check",
|
| 156 |
+
"Run adversarial QA on code — checks for security issues, correctness bugs, and style problems",
|
| 157 |
+
{
|
| 158 |
+
code: z.string().describe("Code content to analyze"),
|
| 159 |
+
filename: z.string().optional().describe("Filename (for language detection)"),
|
| 160 |
+
},
|
| 161 |
+
async ({ code, filename }) => {
|
| 162 |
+
const ext = filename?.split(".").pop()?.toLowerCase();
|
| 163 |
+
const langMap: Record<string, string> = {
|
| 164 |
+
ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
|
| 165 |
+
py: "python", go: "go", rs: "rust", java: "java",
|
| 166 |
+
};
|
| 167 |
+
const language = ext ? langMap[ext] : undefined;
|
| 168 |
+
|
| 169 |
+
const report = generateReport([{ path: filename ?? "input", content: code, language }]);
|
| 170 |
+
return { content: [{ type: "text", text: formatReport(report) }] };
|
| 171 |
+
}
|
| 172 |
+
);
|
| 173 |
+
|
| 174 |
+
return server;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
export async function startMcpServer(): Promise<void> {
|
| 178 |
+
const server = createMcpServer();
|
| 179 |
+
const transport = new StdioServerTransport();
|
| 180 |
+
await server.connect(transport);
|
| 181 |
+
console.error("AgentLens MCP server running on stdio");
|
| 182 |
+
}
|
src/migrator/generate.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule, AgentKind } from "../core/types.js";
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Generate agent-specific config file content from unified IR rules.
|
| 5 |
+
*/
|
| 6 |
+
export function generateConfig(rules: Rule[], target: AgentKind): string {
|
| 7 |
+
switch (target) {
|
| 8 |
+
case "claude":
|
| 9 |
+
return generateClaude(rules);
|
| 10 |
+
case "cursor":
|
| 11 |
+
return generateCursor(rules);
|
| 12 |
+
case "codex":
|
| 13 |
+
return generateCodex(rules);
|
| 14 |
+
case "windsurf":
|
| 15 |
+
return generateWindsurf(rules);
|
| 16 |
+
case "copilot":
|
| 17 |
+
return generateCopilot(rules);
|
| 18 |
+
default:
|
| 19 |
+
return generateGeneric(rules);
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
function groupByCategory(rules: Rule[]): Map<string, Rule[]> {
|
| 24 |
+
const groups = new Map<string, Rule[]>();
|
| 25 |
+
for (const rule of rules) {
|
| 26 |
+
const key = rule.category;
|
| 27 |
+
if (!groups.has(key)) groups.set(key, []);
|
| 28 |
+
groups.get(key)!.push(rule);
|
| 29 |
+
}
|
| 30 |
+
return groups;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
const CATEGORY_TITLES: Record<string, string> = {
|
| 34 |
+
style: "Code Style",
|
| 35 |
+
workflow: "Workflow",
|
| 36 |
+
constraint: "Constraints",
|
| 37 |
+
tooling: "Tools & Dependencies",
|
| 38 |
+
context: "Project Context",
|
| 39 |
+
};
|
| 40 |
+
|
| 41 |
+
function generateClaude(rules: Rule[]): string {
|
| 42 |
+
const groups = groupByCategory(rules);
|
| 43 |
+
const lines: string[] = ["# Project Rules\n"];
|
| 44 |
+
for (const [cat, items] of groups) {
|
| 45 |
+
lines.push(`## ${CATEGORY_TITLES[cat] ?? cat}\n`);
|
| 46 |
+
for (const r of items) {
|
| 47 |
+
lines.push(`- ${r.content}`);
|
| 48 |
+
}
|
| 49 |
+
lines.push("");
|
| 50 |
+
}
|
| 51 |
+
return lines.join("\n");
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
function generateCursor(rules: Rule[]): string {
|
| 55 |
+
// Output as .mdc format with frontmatter
|
| 56 |
+
const groups = groupByCategory(rules);
|
| 57 |
+
const lines: string[] = [
|
| 58 |
+
"---",
|
| 59 |
+
"description: Migrated rules (generated by agentlens)",
|
| 60 |
+
`globs: ["**/*"]`,
|
| 61 |
+
"---",
|
| 62 |
+
"",
|
| 63 |
+
];
|
| 64 |
+
for (const [cat, items] of groups) {
|
| 65 |
+
lines.push(`## ${CATEGORY_TITLES[cat] ?? cat}\n`);
|
| 66 |
+
for (const r of items) {
|
| 67 |
+
lines.push(`- ${r.content}`);
|
| 68 |
+
}
|
| 69 |
+
lines.push("");
|
| 70 |
+
}
|
| 71 |
+
return lines.join("\n");
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
function generateCodex(rules: Rule[]): string {
|
| 75 |
+
const groups = groupByCategory(rules);
|
| 76 |
+
const lines: string[] = ["# Agent Instructions\n"];
|
| 77 |
+
for (const [cat, items] of groups) {
|
| 78 |
+
lines.push(`## ${CATEGORY_TITLES[cat] ?? cat}\n`);
|
| 79 |
+
for (const r of items) {
|
| 80 |
+
lines.push(`- ${r.content}`);
|
| 81 |
+
}
|
| 82 |
+
lines.push("");
|
| 83 |
+
}
|
| 84 |
+
return lines.join("\n");
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
function generateWindsurf(rules: Rule[]): string {
|
| 88 |
+
// .windsurfrules is plain markdown
|
| 89 |
+
return generateClaude(rules);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
function generateCopilot(rules: Rule[]): string {
|
| 93 |
+
// .github/copilot-instructions.md is plain markdown
|
| 94 |
+
return generateClaude(rules);
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
function generateGeneric(rules: Rule[]): string {
|
| 98 |
+
return rules.map((r) => `- ${r.content}`).join("\n") + "\n";
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
/**
|
| 102 |
+
* Get the default output file path for a target agent.
|
| 103 |
+
*/
|
| 104 |
+
export function outputFileFor(target: AgentKind): string {
|
| 105 |
+
switch (target) {
|
| 106 |
+
case "claude": return "CLAUDE.md";
|
| 107 |
+
case "cursor": return ".cursor/rules/agentlens.mdc";
|
| 108 |
+
case "codex": return "AGENTS.md";
|
| 109 |
+
case "windsurf": return ".windsurfrules";
|
| 110 |
+
case "copilot": return ".github/copilot-instructions.md";
|
| 111 |
+
default: return "agentlens-rules.md";
|
| 112 |
+
}
|
| 113 |
+
}
|
src/parsers/base.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule, AgentKind, RuleCategory } from "../core/types.js";
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Parser interface: each agent config format implements this.
|
| 5 |
+
*/
|
| 6 |
+
export interface ConfigParser {
|
| 7 |
+
agent: AgentKind;
|
| 8 |
+
/** File patterns to look for (relative to project root) */
|
| 9 |
+
filePatterns: string[];
|
| 10 |
+
/** Parse raw file content into rules */
|
| 11 |
+
parse(content: string, filePath: string): Rule[];
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
let ruleCounter = 0;
|
| 15 |
+
export function nextRuleId(): string {
|
| 16 |
+
return `rule-${++ruleCounter}`;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
/**
|
| 20 |
+
* Classify a rule line into a category using keyword heuristics.
|
| 21 |
+
* Order matters: constraints override style/workflow/tooling matches.
|
| 22 |
+
*/
|
| 23 |
+
export function classifyRule(text: string): RuleCategory {
|
| 24 |
+
const lower = text.toLowerCase();
|
| 25 |
+
// Constraint keywords win first (禁止/必须/never/always must not)
|
| 26 |
+
if (/(must not|never|do not|don't|avoid|forbidden|required|禁止|必须|不要|不可)/.test(lower)) return "constraint";
|
| 27 |
+
if (/(format|style|indent|naming|convention|lint|prettier|eslint)/.test(lower)) return "style";
|
| 28 |
+
if (/(workflow|process|deploy|commit|branch|pr |pull request|review)/.test(lower)) return "workflow";
|
| 29 |
+
if (/(use |prefer|tool|library|framework|import|依赖|使用)/.test(lower)) return "tooling";
|
| 30 |
+
return "context";
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/**
|
| 34 |
+
* Split markdown content into rule blocks.
|
| 35 |
+
* Each bullet/numbered list item is its own block.
|
| 36 |
+
* Headings become blocks. Paragraphs are grouped.
|
| 37 |
+
*/
|
| 38 |
+
export function extractRuleBlocks(content: string): string[] {
|
| 39 |
+
const blocks: string[] = [];
|
| 40 |
+
const lines = content.split("\n");
|
| 41 |
+
let paragraph: string[] = [];
|
| 42 |
+
|
| 43 |
+
function flushParagraph() {
|
| 44 |
+
if (paragraph.length > 0) {
|
| 45 |
+
const text = paragraph.join(" ").trim();
|
| 46 |
+
if (text.length > 5) blocks.push(text);
|
| 47 |
+
paragraph = [];
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
for (const line of lines) {
|
| 52 |
+
const trimmed = line.trim();
|
| 53 |
+
|
| 54 |
+
if (trimmed === "") {
|
| 55 |
+
flushParagraph();
|
| 56 |
+
continue;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// Heading: flush paragraph, add heading as its own block
|
| 60 |
+
if (/^#{1,6}\s/.test(trimmed)) {
|
| 61 |
+
flushParagraph();
|
| 62 |
+
const headingText = trimmed.replace(/^#{1,6}\s*/, "").trim();
|
| 63 |
+
if (headingText.length > 3) blocks.push(headingText);
|
| 64 |
+
continue;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
// Bullet / numbered list item: each one is its own block
|
| 68 |
+
if (/^[-*+]\s+/.test(trimmed) || /^\d+[.)]\s+/.test(trimmed)) {
|
| 69 |
+
flushParagraph();
|
| 70 |
+
const cleaned = trimmed.replace(/^[-*+]\s+/, "").replace(/^\d+[.)]\s+/, "").trim();
|
| 71 |
+
if (cleaned.length > 5) blocks.push(cleaned);
|
| 72 |
+
continue;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// Regular text: accumulate into paragraph
|
| 76 |
+
paragraph.push(trimmed);
|
| 77 |
+
}
|
| 78 |
+
flushParagraph();
|
| 79 |
+
|
| 80 |
+
return blocks;
|
| 81 |
+
}
|
src/parsers/claude.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule } from "../core/types.js";
|
| 2 |
+
import type { ConfigParser } from "./base.js";
|
| 3 |
+
import { nextRuleId, classifyRule, extractRuleBlocks } from "./base.js";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Claude Code config parser.
|
| 7 |
+
* Reads: CLAUDE.md (project root), .claude/rules/*.md
|
| 8 |
+
*/
|
| 9 |
+
export const claudeParser: ConfigParser = {
|
| 10 |
+
agent: "claude",
|
| 11 |
+
filePatterns: ["CLAUDE.md", ".claude/rules/*.md", ".claude/*.md"],
|
| 12 |
+
|
| 13 |
+
parse(content: string, filePath: string): Rule[] {
|
| 14 |
+
const blocks = extractRuleBlocks(content);
|
| 15 |
+
return blocks.map((block) => ({
|
| 16 |
+
id: nextRuleId(),
|
| 17 |
+
category: classifyRule(block),
|
| 18 |
+
content: block,
|
| 19 |
+
scope: "project" as const,
|
| 20 |
+
source: { agent: "claude" as const, file: filePath },
|
| 21 |
+
status: "active" as const,
|
| 22 |
+
}));
|
| 23 |
+
},
|
| 24 |
+
};
|
src/parsers/codex.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule } from "../core/types.js";
|
| 2 |
+
import type { ConfigParser } from "./base.js";
|
| 3 |
+
import { nextRuleId, classifyRule, extractRuleBlocks } from "./base.js";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Codex config parser.
|
| 7 |
+
* Reads: AGENTS.md (project root)
|
| 8 |
+
*/
|
| 9 |
+
export const codexParser: ConfigParser = {
|
| 10 |
+
agent: "codex",
|
| 11 |
+
filePatterns: ["AGENTS.md"],
|
| 12 |
+
|
| 13 |
+
parse(content: string, filePath: string): Rule[] {
|
| 14 |
+
const blocks = extractRuleBlocks(content);
|
| 15 |
+
return blocks.map((block) => ({
|
| 16 |
+
id: nextRuleId(),
|
| 17 |
+
category: classifyRule(block),
|
| 18 |
+
content: block,
|
| 19 |
+
scope: "project" as const,
|
| 20 |
+
source: { agent: "codex" as const, file: filePath },
|
| 21 |
+
status: "active" as const,
|
| 22 |
+
}));
|
| 23 |
+
},
|
| 24 |
+
};
|
src/parsers/copilot.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule } from "../core/types.js";
|
| 2 |
+
import type { ConfigParser } from "./base.js";
|
| 3 |
+
import { nextRuleId, classifyRule, extractRuleBlocks } from "./base.js";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* GitHub Copilot instructions parser.
|
| 7 |
+
* Reads: .github/copilot-instructions.md
|
| 8 |
+
*/
|
| 9 |
+
export const copilotParser: ConfigParser = {
|
| 10 |
+
agent: "copilot",
|
| 11 |
+
filePatterns: [".github/copilot-instructions.md"],
|
| 12 |
+
|
| 13 |
+
parse(content: string, filePath: string): Rule[] {
|
| 14 |
+
const blocks = extractRuleBlocks(content);
|
| 15 |
+
return blocks.map((block) => ({
|
| 16 |
+
id: nextRuleId(),
|
| 17 |
+
category: classifyRule(block),
|
| 18 |
+
content: block,
|
| 19 |
+
scope: "project" as const,
|
| 20 |
+
source: { agent: "copilot" as const, file: filePath },
|
| 21 |
+
status: "active" as const,
|
| 22 |
+
}));
|
| 23 |
+
},
|
| 24 |
+
};
|
src/parsers/cursor.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule } from "../core/types.js";
|
| 2 |
+
import type { ConfigParser } from "./base.js";
|
| 3 |
+
import { nextRuleId, classifyRule, extractRuleBlocks } from "./base.js";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Cursor config parser.
|
| 7 |
+
* Reads: .cursor/rules/*.mdc (frontmatter + markdown body)
|
| 8 |
+
* Also supports .cursorrules (legacy plain text, one rule per line)
|
| 9 |
+
*/
|
| 10 |
+
export const cursorParser: ConfigParser = {
|
| 11 |
+
agent: "cursor",
|
| 12 |
+
filePatterns: [".cursor/rules/*.mdc", ".cursorrules"],
|
| 13 |
+
|
| 14 |
+
parse(content: string, filePath: string): Rule[] {
|
| 15 |
+
let body = content;
|
| 16 |
+
|
| 17 |
+
// .mdc files have YAML frontmatter
|
| 18 |
+
if (filePath.endsWith(".mdc")) {
|
| 19 |
+
const fmMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
| 20 |
+
if (fmMatch) {
|
| 21 |
+
body = fmMatch[2];
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
// .cursorrules: plain text, each line is its own rule
|
| 26 |
+
if (filePath.endsWith(".cursorrules")) {
|
| 27 |
+
return body
|
| 28 |
+
.split("\n")
|
| 29 |
+
.map((l) => l.trim())
|
| 30 |
+
.filter((l) => l.length > 5)
|
| 31 |
+
.map((line) => ({
|
| 32 |
+
id: nextRuleId(),
|
| 33 |
+
category: classifyRule(line),
|
| 34 |
+
content: line,
|
| 35 |
+
scope: "project" as const,
|
| 36 |
+
source: { agent: "cursor" as const, file: filePath },
|
| 37 |
+
status: "active" as const,
|
| 38 |
+
}));
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
const blocks = extractRuleBlocks(body);
|
| 42 |
+
return blocks.map((block) => ({
|
| 43 |
+
id: nextRuleId(),
|
| 44 |
+
category: classifyRule(block),
|
| 45 |
+
content: block,
|
| 46 |
+
scope: "project" as const,
|
| 47 |
+
source: { agent: "cursor" as const, file: filePath },
|
| 48 |
+
status: "active" as const,
|
| 49 |
+
}));
|
| 50 |
+
},
|
| 51 |
+
};
|
src/parsers/index.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { ConfigParser } from "./base.js";
|
| 2 |
+
import { claudeParser } from "./claude.js";
|
| 3 |
+
import { cursorParser } from "./cursor.js";
|
| 4 |
+
import { codexParser } from "./codex.js";
|
| 5 |
+
import { windsurfParser } from "./windsurf.js";
|
| 6 |
+
import { copilotParser } from "./copilot.js";
|
| 7 |
+
|
| 8 |
+
export const parsers: Record<string, ConfigParser> = {
|
| 9 |
+
claude: claudeParser,
|
| 10 |
+
cursor: cursorParser,
|
| 11 |
+
codex: codexParser,
|
| 12 |
+
windsurf: windsurfParser,
|
| 13 |
+
copilot: copilotParser,
|
| 14 |
+
};
|
| 15 |
+
|
| 16 |
+
export function getParser(agent: string): ConfigParser | undefined {
|
| 17 |
+
return parsers[agent];
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export { claudeParser, cursorParser, codexParser, windsurfParser, copilotParser };
|
src/parsers/windsurf.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { Rule } from "../core/types.js";
|
| 2 |
+
import type { ConfigParser } from "./base.js";
|
| 3 |
+
import { nextRuleId, classifyRule, extractRuleBlocks } from "./base.js";
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Windsurf config parser.
|
| 7 |
+
* Reads: .windsurfrules (plain markdown, one rule per line or bullets)
|
| 8 |
+
*/
|
| 9 |
+
export const windsurfParser: ConfigParser = {
|
| 10 |
+
agent: "windsurf",
|
| 11 |
+
filePatterns: [".windsurfrules"],
|
| 12 |
+
|
| 13 |
+
parse(content: string, filePath: string): Rule[] {
|
| 14 |
+
// Plain text: each line is a rule (like .cursorrules)
|
| 15 |
+
const lines = content
|
| 16 |
+
.split("\n")
|
| 17 |
+
.map((l) => l.trim())
|
| 18 |
+
.filter((l) => l.length > 5 && !l.startsWith("#"));
|
| 19 |
+
|
| 20 |
+
if (lines.length > 0 && !content.includes("\n- ") && !content.match(/^\d+\./m)) {
|
| 21 |
+
// Plain line-per-rule format
|
| 22 |
+
return lines.map((line) => ({
|
| 23 |
+
id: nextRuleId(),
|
| 24 |
+
category: classifyRule(line),
|
| 25 |
+
content: line,
|
| 26 |
+
scope: "project" as const,
|
| 27 |
+
source: { agent: "windsurf" as const, file: filePath },
|
| 28 |
+
status: "active" as const,
|
| 29 |
+
}));
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
// Markdown-like format
|
| 33 |
+
const blocks = extractRuleBlocks(content);
|
| 34 |
+
return blocks.map((block) => ({
|
| 35 |
+
id: nextRuleId(),
|
| 36 |
+
category: classifyRule(block),
|
| 37 |
+
content: block,
|
| 38 |
+
scope: "project" as const,
|
| 39 |
+
source: { agent: "windsurf" as const, file: filePath },
|
| 40 |
+
status: "active" as const,
|
| 41 |
+
}));
|
| 42 |
+
},
|
| 43 |
+
};
|
tests/checker.test.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { analyzeCode, generateReport, formatReport } from "../src/checker/engine.js";
|
| 3 |
+
|
| 4 |
+
describe("analyzeCode — Security", () => {
|
| 5 |
+
it("detects command injection (SEC001)", () => {
|
| 6 |
+
const code = `const result = exec(userInput);`;
|
| 7 |
+
const findings = analyzeCode(code, "test.js");
|
| 8 |
+
const ids = findings.map((f) => f.message);
|
| 9 |
+
expect(ids.some((m) => m.includes("SEC001"))).toBe(true);
|
| 10 |
+
});
|
| 11 |
+
|
| 12 |
+
it("detects hardcoded secrets (SEC002)", () => {
|
| 13 |
+
const code = `const apiKey = "sk-1234567890abcdef";`;
|
| 14 |
+
const findings = analyzeCode(code, "test.js");
|
| 15 |
+
expect(findings.some((f) => f.message.includes("SEC002"))).toBe(true);
|
| 16 |
+
expect(findings.find((f) => f.message.includes("SEC002"))?.severity).toBe("critical");
|
| 17 |
+
});
|
| 18 |
+
|
| 19 |
+
it("detects SQL injection (SEC003)", () => {
|
| 20 |
+
const code = `db.query("SELECT * FROM users WHERE name = " + userName);`;
|
| 21 |
+
const findings = analyzeCode(code, "test.js");
|
| 22 |
+
expect(findings.some((f) => f.message.includes("SEC003"))).toBe(true);
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
it("detects XSS via innerHTML (SEC004)", () => {
|
| 26 |
+
const code = `element.innerHTML = userInput;`;
|
| 27 |
+
const findings = analyzeCode(code, "test.js");
|
| 28 |
+
expect(findings.some((f) => f.message.includes("SEC004"))).toBe(true);
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
it("detects disabled TLS verification (SEC005)", () => {
|
| 32 |
+
const code = `rejectUnauthorized: false`;
|
| 33 |
+
const findings = analyzeCode(code, "test.js");
|
| 34 |
+
expect(findings.some((f) => f.message.includes("SEC005"))).toBe(true);
|
| 35 |
+
});
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
describe("analyzeCode — Correctness", () => {
|
| 39 |
+
it("detects loose null comparison (COR001)", () => {
|
| 40 |
+
const code = `if (value == null) { }`;
|
| 41 |
+
const findings = analyzeCode(code, "test.js");
|
| 42 |
+
expect(findings.some((f) => f.message.includes("COR001"))).toBe(true);
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
it("detects empty catch block (COR002)", () => {
|
| 46 |
+
const code = `try { foo(); } catch (e) { }`;
|
| 47 |
+
const findings = analyzeCode(code, "test.js");
|
| 48 |
+
expect(findings.some((f) => f.message.includes("COR002"))).toBe(true);
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
it("detects TODO markers (COR006)", () => {
|
| 52 |
+
const code = `// TODO: implement this`;
|
| 53 |
+
const findings = analyzeCode(code, "test.js");
|
| 54 |
+
expect(findings.some((f) => f.message.includes("COR006"))).toBe(true);
|
| 55 |
+
expect(findings.find((f) => f.message.includes("COR006"))?.severity).toBe("info");
|
| 56 |
+
});
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
describe("analyzeCode — Style & Performance", () => {
|
| 60 |
+
it("detects console.log (STY001)", () => {
|
| 61 |
+
const code = `console.log("debug");`;
|
| 62 |
+
const findings = analyzeCode(code, "test.js", "javascript");
|
| 63 |
+
expect(findings.some((f) => f.message.includes("STY001"))).toBe(true);
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
it("detects unbounded queries (PERF001)", () => {
|
| 67 |
+
const code = `SELECT * FROM orders`;
|
| 68 |
+
const findings = analyzeCode(code, "test.sql");
|
| 69 |
+
expect(findings.some((f) => f.message.includes("PERF001"))).toBe(true);
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
it("skips language-specific rules when language mismatch", () => {
|
| 73 |
+
const code = `console.log("debug");`;
|
| 74 |
+
const findings = analyzeCode(code, "test.py", "python");
|
| 75 |
+
expect(findings.some((f) => f.message.includes("STY001"))).toBe(false);
|
| 76 |
+
});
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
describe("generateReport", () => {
|
| 80 |
+
it("produces sorted report with summary counts", () => {
|
| 81 |
+
const code = `
|
| 82 |
+
const apiKey = "sk-secret123";
|
| 83 |
+
if (x == null) {}
|
| 84 |
+
console.log("debug");
|
| 85 |
+
`;
|
| 86 |
+
const report = generateReport([{ path: "test.js", content: code, language: "javascript" }]);
|
| 87 |
+
expect(report.summary.critical).toBeGreaterThanOrEqual(1);
|
| 88 |
+
expect(report.summary.info).toBeGreaterThanOrEqual(1);
|
| 89 |
+
// Findings should be sorted: critical first
|
| 90 |
+
const criticalIdx = report.findings.findIndex((f) => f.severity === "critical");
|
| 91 |
+
const infoIdx = report.findings.findIndex((f) => f.severity === "info");
|
| 92 |
+
expect(criticalIdx).toBeLessThan(infoIdx);
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it("handles clean code", () => {
|
| 96 |
+
const report = generateReport([{ path: "clean.ts", content: `const x: number = 42;`, language: "typescript" }]);
|
| 97 |
+
expect(report.findings.length).toBe(0);
|
| 98 |
+
expect(report.summary.critical).toBe(0);
|
| 99 |
+
});
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
describe("formatReport", () => {
|
| 103 |
+
it("formats empty report as clean", () => {
|
| 104 |
+
const report = generateReport([{ path: "a.ts", content: `const x = 1;` }]);
|
| 105 |
+
const output = formatReport(report);
|
| 106 |
+
expect(output).toContain("No issues found");
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
+
it("formats report with findings", () => {
|
| 110 |
+
const report = generateReport([
|
| 111 |
+
{ path: "test.js", content: `const apiKey = "sk-secret";`, language: "javascript" },
|
| 112 |
+
]);
|
| 113 |
+
const output = formatReport(report);
|
| 114 |
+
expect(output).toContain("SEC002");
|
| 115 |
+
expect(output).toContain("critical");
|
| 116 |
+
});
|
| 117 |
+
});
|
tests/drift.test.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { detectDriftEntries, findMissingRules } from "../src/drift/detect.js";
|
| 3 |
+
import type { Rule } from "../src/core/types.js";
|
| 4 |
+
|
| 5 |
+
function makeRule(id: string, content: string, agent: "claude" | "cursor" | "codex", file: string): Rule {
|
| 6 |
+
return {
|
| 7 |
+
id,
|
| 8 |
+
category: "style",
|
| 9 |
+
content,
|
| 10 |
+
scope: "project",
|
| 11 |
+
source: { agent, file },
|
| 12 |
+
status: "active",
|
| 13 |
+
};
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
describe("detectDriftEntries", () => {
|
| 17 |
+
it("detects similar rules with different wording", () => {
|
| 18 |
+
const rules = [
|
| 19 |
+
makeRule("r1", "Use TypeScript for all new code", "claude", "CLAUDE.md"),
|
| 20 |
+
makeRule("r2", "Use TypeScript for all new source code", "cursor", ".cursor/rules/main.mdc"),
|
| 21 |
+
];
|
| 22 |
+
const drifts = detectDriftEntries(rules);
|
| 23 |
+
expect(drifts.length).toBeGreaterThanOrEqual(1);
|
| 24 |
+
expect(drifts[0].type).toBe("inconsistent");
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
it("does not flag identical rules as drift", () => {
|
| 28 |
+
const rules = [
|
| 29 |
+
makeRule("r1", "Use TypeScript for all new code", "claude", "CLAUDE.md"),
|
| 30 |
+
makeRule("r2", "Use TypeScript for all new code", "cursor", ".cursor/rules/main.mdc"),
|
| 31 |
+
];
|
| 32 |
+
const drifts = detectDriftEntries(rules);
|
| 33 |
+
expect(drifts.length).toBe(0);
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
it("does not flag rules from the same file", () => {
|
| 37 |
+
const rules = [
|
| 38 |
+
makeRule("r1", "Use TypeScript for all new code", "claude", "CLAUDE.md"),
|
| 39 |
+
makeRule("r2", "Use TypeScript for all new source code", "claude", "CLAUDE.md"),
|
| 40 |
+
];
|
| 41 |
+
const drifts = detectDriftEntries(rules);
|
| 42 |
+
expect(drifts.length).toBe(0);
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
it("does not flag completely different rules", () => {
|
| 46 |
+
const rules = [
|
| 47 |
+
makeRule("r1", "Use TypeScript for all new code", "claude", "CLAUDE.md"),
|
| 48 |
+
makeRule("r2", "Deploy to production every Friday afternoon", "cursor", ".cursor/rules/main.mdc"),
|
| 49 |
+
];
|
| 50 |
+
const drifts = detectDriftEntries(rules);
|
| 51 |
+
expect(drifts.length).toBe(0);
|
| 52 |
+
});
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
describe("findMissingRules", () => {
|
| 56 |
+
it("finds categories missing in target", () => {
|
| 57 |
+
const source: Rule[] = [
|
| 58 |
+
{ id: "s1", category: "security", content: "Never commit secrets", scope: "project", source: { agent: "claude", file: "CLAUDE.md" }, status: "active" },
|
| 59 |
+
];
|
| 60 |
+
const target: Rule[] = [
|
| 61 |
+
{ id: "t1", category: "style", content: "Use 4 spaces", scope: "project", source: { agent: "cursor", file: ".cursor/rules/x.mdc" }, status: "active" },
|
| 62 |
+
];
|
| 63 |
+
const missing = findMissingRules(source, target, "claude", "cursor");
|
| 64 |
+
expect(missing.length).toBe(1);
|
| 65 |
+
expect(missing[0].type).toBe("missing");
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
it("returns empty when categories match", () => {
|
| 69 |
+
const source: Rule[] = [
|
| 70 |
+
{ id: "s1", category: "style", content: "Use 4 spaces", scope: "project", source: { agent: "claude", file: "CLAUDE.md" }, status: "active" },
|
| 71 |
+
];
|
| 72 |
+
const target: Rule[] = [
|
| 73 |
+
{ id: "t1", category: "style", content: "Use spaces", scope: "project", source: { agent: "cursor", file: ".cursor/rules/x.mdc" }, status: "active" },
|
| 74 |
+
];
|
| 75 |
+
const missing = findMissingRules(source, target, "claude", "cursor");
|
| 76 |
+
expect(missing.length).toBe(0);
|
| 77 |
+
});
|
| 78 |
+
});
|
tests/mcp.test.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { createMcpServer } from "../src/mcp/server.js";
|
| 3 |
+
|
| 4 |
+
describe("MCP Server", () => {
|
| 5 |
+
it("creates server with correct metadata", () => {
|
| 6 |
+
const server = createMcpServer();
|
| 7 |
+
expect(server).toBeDefined();
|
| 8 |
+
});
|
| 9 |
+
|
| 10 |
+
it("registers all expected tools", () => {
|
| 11 |
+
const server = createMcpServer();
|
| 12 |
+
// Access the internal tool registry to verify tools are registered
|
| 13 |
+
// The McpServer object stores registered tools
|
| 14 |
+
const serverAny = server as any;
|
| 15 |
+
// Tools are registered via server.tool() calls
|
| 16 |
+
// We verify the server object is functional
|
| 17 |
+
expect(typeof server.connect).toBe("function");
|
| 18 |
+
});
|
| 19 |
+
});
|
tests/migrator.test.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { generateConfig, outputFileFor } from "../src/migrator/generate.js";
|
| 3 |
+
import type { Rule } from "../src/core/types.js";
|
| 4 |
+
|
| 5 |
+
const sampleRules: Rule[] = [
|
| 6 |
+
{
|
| 7 |
+
id: "r1",
|
| 8 |
+
category: "style",
|
| 9 |
+
content: "Use TypeScript strict mode",
|
| 10 |
+
scope: "project",
|
| 11 |
+
source: { agent: "claude", file: "CLAUDE.md" },
|
| 12 |
+
status: "active",
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
id: "r2",
|
| 16 |
+
category: "constraint",
|
| 17 |
+
content: "Never commit secrets to the repository",
|
| 18 |
+
scope: "project",
|
| 19 |
+
source: { agent: "claude", file: "CLAUDE.md" },
|
| 20 |
+
status: "active",
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
id: "r3",
|
| 24 |
+
category: "tooling",
|
| 25 |
+
content: "Use pnpm as package manager",
|
| 26 |
+
scope: "project",
|
| 27 |
+
source: { agent: "claude", file: "CLAUDE.md" },
|
| 28 |
+
status: "active",
|
| 29 |
+
},
|
| 30 |
+
];
|
| 31 |
+
|
| 32 |
+
describe("generateConfig", () => {
|
| 33 |
+
it("generates Claude format with markdown structure", () => {
|
| 34 |
+
const output = generateConfig(sampleRules, "claude");
|
| 35 |
+
expect(output).toContain("# Project Rules");
|
| 36 |
+
expect(output).toContain("## Code Style");
|
| 37 |
+
expect(output).toContain("- Use TypeScript strict mode");
|
| 38 |
+
expect(output).toContain("## Constraints");
|
| 39 |
+
expect(output).toContain("- Never commit secrets to the repository");
|
| 40 |
+
expect(output).toContain("## Tools & Dependencies");
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
it("generates Cursor .mdc format with frontmatter", () => {
|
| 44 |
+
const output = generateConfig(sampleRules, "cursor");
|
| 45 |
+
expect(output).toContain("---");
|
| 46 |
+
expect(output).toContain("description: Migrated rules");
|
| 47 |
+
expect(output).toContain("globs:");
|
| 48 |
+
expect(output).toContain("- Use TypeScript strict mode");
|
| 49 |
+
expect(output).toContain("- Never commit secrets to the repository");
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
it("generates Codex AGENTS.md format", () => {
|
| 53 |
+
const output = generateConfig(sampleRules, "codex");
|
| 54 |
+
expect(output).toContain("# Agent Instructions");
|
| 55 |
+
expect(output).toContain("## Code Style");
|
| 56 |
+
expect(output).toContain("- Use pnpm as package manager");
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
it("generates Windsurf plain markdown", () => {
|
| 60 |
+
const output = generateConfig(sampleRules, "windsurf");
|
| 61 |
+
expect(output).toContain("# Project Rules");
|
| 62 |
+
expect(output).toContain("- Never commit secrets to the repository");
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
it("generates Copilot instructions format", () => {
|
| 66 |
+
const output = generateConfig(sampleRules, "copilot");
|
| 67 |
+
expect(output).toContain("# Project Rules");
|
| 68 |
+
expect(output).toContain("- Use TypeScript strict mode");
|
| 69 |
+
});
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
describe("outputFileFor", () => {
|
| 73 |
+
it("returns correct file paths for each agent", () => {
|
| 74 |
+
expect(outputFileFor("claude")).toBe("CLAUDE.md");
|
| 75 |
+
expect(outputFileFor("cursor")).toBe(".cursor/rules/agentlens.mdc");
|
| 76 |
+
expect(outputFileFor("codex")).toBe("AGENTS.md");
|
| 77 |
+
expect(outputFileFor("windsurf")).toBe(".windsurfrules");
|
| 78 |
+
expect(outputFileFor("copilot")).toBe(".github/copilot-instructions.md");
|
| 79 |
+
expect(outputFileFor("generic")).toBe("agentlens-rules.md");
|
| 80 |
+
});
|
| 81 |
+
});
|
tests/parsers-extra.test.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { windsurfParser } from "../src/parsers/windsurf.js";
|
| 3 |
+
import { copilotParser } from "../src/parsers/copilot.js";
|
| 4 |
+
|
| 5 |
+
describe("windsurfParser", () => {
|
| 6 |
+
it("parses plain text one-rule-per-line format", () => {
|
| 7 |
+
const content = `Use TypeScript for all files
|
| 8 |
+
Never commit directly to main
|
| 9 |
+
Prefer functional components`;
|
| 10 |
+
const rules = windsurfParser.parse(content, ".windsurfrules");
|
| 11 |
+
expect(rules.length).toBe(3);
|
| 12 |
+
expect(rules[0].source.agent).toBe("windsurf");
|
| 13 |
+
expect(rules[0].content).toBe("Use TypeScript for all files");
|
| 14 |
+
});
|
| 15 |
+
|
| 16 |
+
it("parses markdown bullet format", () => {
|
| 17 |
+
const content = `# Rules\n\n- Use TypeScript\n- Write tests first`;
|
| 18 |
+
const rules = windsurfParser.parse(content, ".windsurfrules");
|
| 19 |
+
expect(rules.length).toBeGreaterThanOrEqual(2);
|
| 20 |
+
const contents = rules.map((r) => r.content);
|
| 21 |
+
expect(contents).toContain("Use TypeScript");
|
| 22 |
+
expect(contents).toContain("Write tests first");
|
| 23 |
+
});
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
describe("copilotParser", () => {
|
| 27 |
+
it("parses .github/copilot-instructions.md", () => {
|
| 28 |
+
const content = `# Copilot Instructions
|
| 29 |
+
|
| 30 |
+
- Always use async/await
|
| 31 |
+
- Add JSDoc comments to public functions`;
|
| 32 |
+
const rules = copilotParser.parse(content, ".github/copilot-instructions.md");
|
| 33 |
+
expect(rules.length).toBeGreaterThanOrEqual(2);
|
| 34 |
+
expect(rules[0].source.agent).toBe("copilot");
|
| 35 |
+
const contents = rules.map((r) => r.content);
|
| 36 |
+
expect(contents).toContain("Always use async/await");
|
| 37 |
+
});
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
describe("parsers index", () => {
|
| 41 |
+
it("exposes all five parsers", async () => {
|
| 42 |
+
const { parsers } = await import("../src/parsers/index.js");
|
| 43 |
+
expect(Object.keys(parsers)).toEqual(["claude", "cursor", "codex", "windsurf", "copilot"]);
|
| 44 |
+
});
|
| 45 |
+
});
|
tests/parsers.test.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from "vitest";
|
| 2 |
+
import { extractRuleBlocks, classifyRule } from "../src/parsers/base.js";
|
| 3 |
+
import { claudeParser } from "../src/parsers/claude.js";
|
| 4 |
+
import { cursorParser } from "../src/parsers/cursor.js";
|
| 5 |
+
import { codexParser } from "../src/parsers/codex.js";
|
| 6 |
+
|
| 7 |
+
describe("extractRuleBlocks", () => {
|
| 8 |
+
it("extracts bullet list items as rules", () => {
|
| 9 |
+
const content = `- Always use TypeScript strict mode
|
| 10 |
+
- Never commit directly to main
|
| 11 |
+
- Prefer composition over inheritance`;
|
| 12 |
+
const blocks = extractRuleBlocks(content);
|
| 13 |
+
expect(blocks.length).toBe(3);
|
| 14 |
+
expect(blocks[0]).toBe("Always use TypeScript strict mode");
|
| 15 |
+
expect(blocks[1]).toBe("Never commit directly to main");
|
| 16 |
+
});
|
| 17 |
+
|
| 18 |
+
it("extracts headings as rules", () => {
|
| 19 |
+
const content = `## Code Style\n\nSome content here.\n\n## Testing\n\nMore content.`;
|
| 20 |
+
const blocks = extractRuleBlocks(content);
|
| 21 |
+
expect(blocks).toContain("Code Style");
|
| 22 |
+
expect(blocks).toContain("Testing");
|
| 23 |
+
expect(blocks).toContain("Some content here.");
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
it("handles numbered lists", () => {
|
| 27 |
+
const content = `1. First rule
|
| 28 |
+
2. Second rule`;
|
| 29 |
+
const blocks = extractRuleBlocks(content);
|
| 30 |
+
expect(blocks.length).toBe(2);
|
| 31 |
+
expect(blocks[0]).toBe("First rule");
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
it("filters out short noise", () => {
|
| 35 |
+
const content = `- OK\n\nThis is a real rule that has enough content.`;
|
| 36 |
+
const blocks = extractRuleBlocks(content);
|
| 37 |
+
expect(blocks.length).toBe(1);
|
| 38 |
+
expect(blocks[0]).toBe("This is a real rule that has enough content.");
|
| 39 |
+
});
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
describe("classifyRule", () => {
|
| 43 |
+
it("classifies style rules", () => {
|
| 44 |
+
expect(classifyRule("Use 4 spaces for indentation")).toBe("style");
|
| 45 |
+
expect(classifyRule("Follow ESLint conventions")).toBe("style");
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
it("classifies constraint rules", () => {
|
| 49 |
+
expect(classifyRule("Never commit secrets to the repository")).toBe("constraint");
|
| 50 |
+
expect(classifyRule("必须先运行测试再提交")).toBe("constraint");
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it("classifies workflow rules", () => {
|
| 54 |
+
expect(classifyRule("Use feature branches for all PRs")).toBe("workflow");
|
| 55 |
+
expect(classifyRule("Deploy after review approval")).toBe("workflow");
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
it("classifies tooling rules", () => {
|
| 59 |
+
expect(classifyRule("Use pnpm as package manager")).toBe("tooling");
|
| 60 |
+
expect(classifyRule("Prefer Zod for schema validation")).toBe("tooling");
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
it("defaults to context", () => {
|
| 64 |
+
expect(classifyRule("This project is a web application")).toBe("context");
|
| 65 |
+
});
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
describe("claudeParser", () => {
|
| 69 |
+
it("parses CLAUDE.md content into rules", () => {
|
| 70 |
+
const content = `# Project Rules
|
| 71 |
+
|
| 72 |
+
- Use TypeScript for all new code
|
| 73 |
+
- Always run tests before committing
|
| 74 |
+
|
| 75 |
+
## Architecture
|
| 76 |
+
|
| 77 |
+
Prefer serverless functions over long-running servers.`;
|
| 78 |
+
const rules = claudeParser.parse(content, "CLAUDE.md");
|
| 79 |
+
expect(rules.length).toBeGreaterThan(0);
|
| 80 |
+
expect(rules[0].source.agent).toBe("claude");
|
| 81 |
+
expect(rules[0].source.file).toBe("CLAUDE.md");
|
| 82 |
+
expect(rules[0].status).toBe("active");
|
| 83 |
+
// Should have rules from bullets and headings
|
| 84 |
+
const contents = rules.map((r) => r.content);
|
| 85 |
+
expect(contents).toContain("Use TypeScript for all new code");
|
| 86 |
+
});
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
describe("cursorParser", () => {
|
| 90 |
+
it("parses .mdc with frontmatter", () => {
|
| 91 |
+
const content = `---
|
| 92 |
+
description: My rules
|
| 93 |
+
globs: ["src/**/*.ts"]
|
| 94 |
+
---
|
| 95 |
+
|
| 96 |
+
- Use async/await over raw promises
|
| 97 |
+
- Always handle errors explicitly`;
|
| 98 |
+
const rules = cursorParser.parse(content, ".cursor/rules/main.mdc");
|
| 99 |
+
expect(rules.length).toBe(2);
|
| 100 |
+
expect(rules[0].source.agent).toBe("cursor");
|
| 101 |
+
expect(rules[0].content).toBe("Use async/await over raw promises");
|
| 102 |
+
expect(rules[1].content).toBe("Always handle errors explicitly");
|
| 103 |
+
});
|
| 104 |
+
|
| 105 |
+
it("parses plain .cursorrules", () => {
|
| 106 |
+
const content = `Use single quotes
|
| 107 |
+
Max line length 100`;
|
| 108 |
+
const rules = cursorParser.parse(content, ".cursorrules");
|
| 109 |
+
expect(rules.length).toBe(2);
|
| 110 |
+
expect(rules[0].source.agent).toBe("cursor");
|
| 111 |
+
});
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
describe("codexParser", () => {
|
| 115 |
+
it("parses AGENTS.md content", () => {
|
| 116 |
+
const content = `# Agent Guidelines
|
| 117 |
+
|
| 118 |
+
- Write unit tests for all utility functions
|
| 119 |
+
- Document all public APIs with JSDoc`;
|
| 120 |
+
const rules = codexParser.parse(content, "AGENTS.md");
|
| 121 |
+
expect(rules.length).toBeGreaterThan(0);
|
| 122 |
+
expect(rules[0].source.agent).toBe("codex");
|
| 123 |
+
const contents = rules.map((r) => r.content);
|
| 124 |
+
expect(contents).toContain("Write unit tests for all utility functions");
|
| 125 |
+
});
|
| 126 |
+
});
|
tsconfig.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"target": "ES2022",
|
| 4 |
+
"module": "NodeNext",
|
| 5 |
+
"moduleResolution": "NodeNext",
|
| 6 |
+
"outDir": "./dist",
|
| 7 |
+
"rootDir": "./src",
|
| 8 |
+
"strict": true,
|
| 9 |
+
"esModuleInterop": true,
|
| 10 |
+
"skipLibCheck": true,
|
| 11 |
+
"forceConsistentCasingInFileNames": true,
|
| 12 |
+
"declaration": true,
|
| 13 |
+
"declarationMap": true,
|
| 14 |
+
"sourceMap": true,
|
| 15 |
+
"resolveJsonModule": true
|
| 16 |
+
},
|
| 17 |
+
"include": ["src/**/*"],
|
| 18 |
+
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
| 19 |
+
}
|