feat: DSH bot-instruction parser + dedupe + DSH panel project picker
Browse filesFiles changed (10)
68 unmodified lines69707172737481 unmodified lines15615715815916016137 unmodified lines19920020120220320420520620720820921021121268 unmodified linesreturn String(d.text || '');}async function callInstall() {const r = await fetch('/agentlens/install', { method: 'POST', credentials: 'same-origin' });const d = await r.json();81 unmodified linesfunction MigratePanel() {const [path, setPath] = useState(rememberedPath());const [from, setFrom] = useState('claude');const [to, setTo] = useState('cursor');const [busy, setBusy] = useState('');37 unmodified linesh('p',{ className: 'agentlens-hint' },'把 AI Agent 的规则配置在 Claude Code / Cursor / Codex / Windsurf / Copilot 之间一键迁移;也可以先扫描项目里现有的配置。所有操作都在本机完成。'),h('div',{ className: 'row' },h('input', {type: 'text',placeholder: '项目路径(留空扫描默认目录)',value: path,onChange: (e) => savePath(e.target.value),}),68 unmodified lines697071727374757677787980818283848581 unmodified lines16716816917017117217317417517617717817918018118218318418518618718818919037 unmodified lines22822923023123223323423523623723823924024124224324424524624724824925025125268 unmodified linesreturn String(d.text || '');}async function fetchWorkspaces() {try {const r = await fetch('/agentlens/workspaces', { credentials: 'same-origin' });const d = await r.json();if (r.ok && d.ok !== false && Array.isArray(d.workspaces)) return d.workspaces;} catch {/* ignore */}return [];}async function callInstall() {const r = await fetch('/agentlens/install', { method: 'POST', credentials: 'same-origin' });const d = await r.json();81 unmodified linesfunction MigratePanel() {const [path, setPath] = useState(rememberedPath());const [workspaces, setWorkspaces] = useState([]);useEffect(() => {let alive = true;fetchWorkspaces().then((list) => {if (!alive) return;setWorkspaces(list);setPath((current) => {if (current) return current;const first = list[0] || '';if (first) rememberPath(first);return first;});});return () => {alive = false;};}, []);const [from, setFrom] = useState('claude');const [to, setTo] = useState('cursor');const [busy, setBusy] = useState('');37 unmodified linesh('p',{ className: 'agentlens-hint' },'把项目里的规则文件(CLAUDE.md / AGENTS.md / .cursor/rules 等)在 9 个 Agent 之间一键迁移。先选择你的项目目录,再选源/目标 Agent。所有操作都在本机完成。'),h('div',{ className: 'row' },workspaces.length > 0? h('select', {value: workspaces.includes(path) ? path : '',onChange: (e) => {if (e.target.value) savePath(e.target.value);},title: '从 DSH 最近打开的项目中选择',},h('option', { value: '' }, '选择项目目录…'),workspaces.map((w) => h('option', { key: w, value: w }, w))): null,h('input', {type: 'text',placeholder: '或手动输入项目路径,例如 ~/你的项目',value: path,onChange: (e) => savePath(e.target.value),}),
11 unmodified lines1213141516171819202122232493 unmodified lines1181191201211221238 unmodified lines1321331341351361371389 unmodified lines14814915015115215315411 unmodified lines*/import { execFile } from "node:child_process";import { promisify } from "node:util";import { existsSync, accessSync, constants } from "node:fs";const execFileAsync = promisify(execFile);export const inject = ["tools", "webServer"];const DEFAULT_ENTRY = '/Users/apple/agentlens/dist/cli/index.js';/*** Resolve a real Node.js binary. Inside the Electron host `process.execPath`93 unmodified lines},};const installRoute = {kind: "exact",path: "/agentlens/install",8 unmodified lines};const disposers = [];for (const route of [scanRoute, migrateRoute, installRoute]) {try {disposers.push(server.register(route));} catch (error) {9 unmodified lines*/export function apply(ctx, config = {}) {const entry = resolveEntry(config);const fallbackCwd = process.cwd();// --- Local HTTP routes for the client UI ---ctx.effect(() => {11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545593 unmodified lines1491501511521531541551561571581591601611621631641651668 unmodified lines1751761771781791801819 unmodified lines19119219319419519619711 unmodified lines*/import { execFile } from "node:child_process";import { promisify } from "node:util";import { existsSync, accessSync, constants, readFileSync } from "node:fs";const execFileAsync = promisify(execFile);export const inject = ["tools", "webServer"];const DEFAULT_ENTRY = '/Users/apple/agentlens/dist/cli/index.js';const HOME = process.env.HOME || "/Users/apple";/*** Read recent workspace paths from DSH's own storage so the panel can default* to a real project instead of the profile directory (the host's cwd).*/function recentWorkspaces() {const paths = [];try {const raw = readFileSync(joinHome(".dsh", "storages", "workspace.json"), "utf8");const data = JSON.parse(raw);const workspaces = data?.tables?.workspaces ?? {};for (const entry of Object.values(workspaces)) {const p = entry?.path;if (typeof p === "string" && p && !paths.includes(p)) paths.push(p);}} catch {// storage missing or not JSON — fall through}return paths;}function joinHome(...parts) {return [HOME, ...parts].join("/");}/** Pick a sensible default project root: first DSH workspace, else home. */function defaultProjectPath() {const workspaces = recentWorkspaces();return workspaces[0] || HOME;}/*** Resolve a real Node.js binary. Inside the Electron host `process.execPath`93 unmodified lines},};const workspacesRoute = {kind: "exact",path: "/agentlens/workspaces",async handler(req, res) {try {json(res, 200, { ok: true, workspaces: recentWorkspaces(), fallback: fallbackCwd });} catch (error) {json(res, 500, { ok: false, error: String((error && error.message) || error) });}},};const installRoute = {kind: "exact",path: "/agentlens/install",8 unmodified lines};const disposers = [];for (const route of [scanRoute, migrateRoute, installRoute, workspacesRoute]) {try {disposers.push(server.register(route));} catch (error) {9 unmodified lines*/export function apply(ctx, config = {}) {const entry = resolveEntry(config);const fallbackCwd = defaultProjectPath();// --- Local HTTP routes for the client UI ---ctx.effect(() => {
2 unmodified lines345678910111213141516171819202122232425262728293031322 unmodified linesimport type { Rule } from "../../core/types.js";import { parsers } from "../../parsers/index.js";import { detectDriftEntries, findMissingRules } from "../../drift/detect.js";function findAgentFiles(root: string, agent: string): string[] {const parser = parsers[agent];if (!parser) return [];const files: string[] = [];for (const pattern of parser.filePatterns) {if (pattern.includes("*")) {const parts = pattern.split("/");const dirParts = parts.slice(0, -1);const filePattern = parts[parts.length - 1];const dir = resolve(root, ...dirParts);if (existsSync(dir) && statSync(dir).isDirectory()) {const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");for (const f of readdirSync(dir)) {if (regex.test(f)) files.push(join(dir, f));}}} else {const filePath = resolve(root, pattern);if (existsSync(filePath)) files.push(filePath);}}return files;}export async function detectDrift(root: string): Promise<void> {const absRoot = resolve(root);2 unmodified lines3456789102 unmodified linesimport type { Rule } from "../../core/types.js";import { parsers } from "../../parsers/index.js";import { detectDriftEntries, findMissingRules } from "../../drift/detect.js";import { findAgentFiles } from "../../core/files.js";export async function detectDrift(root: string): Promise<void> {const absRoot = resolve(root);
2 unmodified lines3456783 unmodified lines1213141516171819202122232425262728293031323334353637383940414216 unmodified lines596061626364656616 unmodified lines838485868788892 unmodified linesimport type { Rule, AgentKind } from "../../core/types.js";import { parsers } from "../../parsers/index.js";import { generateConfig, outputFileFor } from "../../migrator/generate.js";interface MoveOpts {from: string;3 unmodified lines}/** Find all config files for a given agent in the project. */function findAgentFiles(root: string, agent: string): string[] {const parser = parsers[agent];if (!parser) return [];const files: string[] = [];for (const pattern of parser.filePatterns) {if (pattern.includes("*")) {// Glob like ".cursor/rules/*.mdc"const parts = pattern.split("/");const dirParts = parts.slice(0, -1);const filePattern = parts[parts.length - 1];const dir = resolve(root, ...dirParts);if (existsSync(dir) && statSync(dir).isDirectory()) {const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");for (const f of readdirSync(dir)) {if (regex.test(f)) files.push(join(dir, f));}}} else {const filePath = resolve(root, pattern);if (existsSync(filePath)) files.push(filePath);}}return files;}/** Parse all rules from source agent files. */function parseRules(root: string, agent: string): Rule[] {16 unmodified linesconsole.log(`Migrating rules: ${opts.from} → ${opts.to}\n`);// Parse source rulesconst rules = parseRules(root, opts.from);if (rules.length === 0) {console.log(`⚠ No rules found for agent "${opts.from}" in ${root}`);const files = findAgentFiles(root, opts.from);16 unmodified lineswriteFileSync(outputPath, output, "utf-8");console.log(` ✅ Generated ${outputPath}`);console.log(` ${rules.length} rules converted from ${opts.from} format to ${opts.to} format\n`);// Show previewconst preview = output.split("\n").slice(0, 15).join("\n");2 unmodified lines3456789103 unmodified lines14151617181916 unmodified lines363738394041424316 unmodified lines60616263646566676869707172732 unmodified linesimport type { Rule, AgentKind } from "../../core/types.js";import { parsers } from "../../parsers/index.js";import { generateConfig, outputFileFor } from "../../migrator/generate.js";import { dedupeRules } from "../../core/dedupe.js";import { findAgentFiles } from "../../core/files.js";interface MoveOpts {from: string;3 unmodified lines}/** Find all config files for a given agent in the project. *//** Parse all rules from source agent files. */function parseRules(root: string, agent: string): Rule[] {16 unmodified linesconsole.log(`Migrating rules: ${opts.from} → ${opts.to}\n`);// Parse source rules (dedupe: an agent may expose several rule sources)const rules = dedupeRules(parseRules(root, opts.from));if (rules.length === 0) {console.log(`⚠ No rules found for agent "${opts.from}" in ${root}`);const files = findAgentFiles(root, opts.from);16 unmodified lineswriteFileSync(outputPath, output, "utf-8");console.log(` ✅ Generated ${outputPath}`);// True same-file case: the rules were read from the very file we just wrote.const sourceFile = rules[0]?.source.file;const sameFile = sourceFile !== undefined && resolve(sourceFile) === outputPath;if (sameFile) {console.log(` ${opts.from} 和 ${opts.to} 使用同一个规则文件 ${outputFileFor(toAgent)}——迁移会原地整理(幂等,不重复添加规则)\n`);} else {console.log(` ${rules.length} rules converted from ${opts.from} format to ${opts.to} format\n`);}// Show previewconst preview = output.split("\n").slice(0, 15).join("\n");
1 unmodified line23456789101112131415161718192021222324252627282930313229 unmodified lines626364656667681 unmodified lineimport { resolve, join } from "node:path";import type { Rule } from "../../core/types.js";import { parsers } from "../../parsers/index.js";function findAgentFiles(root: string, agent: string): string[] {const parser = parsers[agent];if (!parser) return [];const files: string[] = [];for (const pattern of parser.filePatterns) {if (pattern.includes("*")) {const parts = pattern.split("/");const dirParts = parts.slice(0, -1);const filePattern = parts[parts.length - 1];const dir = resolve(root, ...dirParts);if (existsSync(dir) && statSync(dir).isDirectory()) {const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");for (const f of readdirSync(dir)) {if (regex.test(f)) files.push(join(dir, f));}}} else {const filePath = resolve(root, pattern);if (existsSync(filePath)) files.push(filePath);}}return files;}export async function scanProject(root: string): Promise<void> {const absRoot = resolve(root);29 unmodified lines}if (!foundAny) {console.log(" No agent configs found. Supported:");for (const [name, parser] of Object.entries(parsers)) {console.log(` ${name}: ${parser.filePatterns.join(", ")}`);}1 unmodified line2345678929 unmodified lines3940414243444546471 unmodified lineimport { resolve, join } from "node:path";import type { Rule } from "../../core/types.js";import { parsers } from "../../parsers/index.js";import { findAgentFiles } from "../../core/files.js";export async function scanProject(root: string): Promise<void> {const absRoot = resolve(root);29 unmodified lines}if (!foundAny) {console.log(" 这个目录里没有找到任何 Agent 规则文件。");console.log(" 请换一个项目目录(通常包含 CLAUDE.md / AGENTS.md / .cursor/rules)。");console.log(" Supported:");for (const [name, parser] of Object.entries(parsers)) {console.log(` ${name}: ${parser.filePatterns.join(", ")}`);}
12345678910111213141516171819import type { Rule } from "./types.js";
/** * Collapse rules with identical normalized content, keeping the first. * Needed because some agents expose more than one rule source (e.g. DSH reads * both the project AGENTS.md and the global bot-team state file), and writing * every duplicate back would grow the file on each migration. */export function dedupeRules(rules: Rule[]): Rule[] { const seen = new Set<string>(); const out: Rule[] = []; for (const rule of rules) { const key = rule.content.replace(/\s+/g, " ").trim(); if (key.length === 0 || seen.has(key)) continue; seen.add(key); out.push(rule); } return out;}12345678910111213141516171819202122232425262728293031323334353637383940414243import { existsSync, readdirSync, statSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { homedir } from "node:os";import { parsers } from "../parsers/index.js";
/** * Resolve every config file for an agent under a project root. * * Most agents keep rules in project files (CLAUDE.md, AGENTS.md, …). DSH is * special: its bot-team instructions live in the global state file * `$HOME/.dsh/bot/state.json`, so that file is always included for `dsh`. */export function findAgentFiles(root: string, agent: string): string[] { const parser = parsers[agent]; if (!parser) return []; const files: string[] = [];
for (const pattern of parser.filePatterns) { if (pattern.includes("*")) { const parts = pattern.split("/"); const dirParts = parts.slice(0, -1); const filePattern = parts[parts.length - 1]; const dir = resolve(root, ...dirParts); if (existsSync(dir) && statSync(dir).isDirectory()) { const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$"); for (const f of readdirSync(dir)) { if (regex.test(f)) files.push(join(dir, f)); } } } else { const filePath = resolve(root, pattern); if (existsSync(filePath)) files.push(filePath); } }
// DSH global bot-team instructions. if (agent === "dsh") { const statePath = join(homedir(), ".dsh", "bot", "state.json"); if (existsSync(statePath)) files.push(statePath); }
return files;}3 unmodified lines4567891011121314151617181920212223242526272829303132333435363762 unmodified lines1001011021031041051061071081093 unmodified linesimport { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";import { resolve, join, dirname } from "node:path";import { parsers } from "../parsers/index.js";import { generateConfig, outputFileFor } from "../migrator/generate.js";import { detectDriftEntries } from "../drift/detect.js";import { generateReport, formatReport } from "../checker/engine.js";import type { Rule, AgentKind } from "../core/types.js";function findAgentFiles(root: string, agent: string): string[] {const parser = parsers[agent];if (!parser) return [];const files: string[] = [];for (const pattern of parser.filePatterns) {if (pattern.includes("*")) {const parts = pattern.split("/");const dirParts = parts.slice(0, -1);const filePattern = parts[parts.length - 1];const dir = resolve(root, ...dirParts);if (existsSync(dir) && statSync(dir).isDirectory()) {const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$");for (const f of readdirSync(dir)) {if (regex.test(f)) files.push(join(dir, f));}}} else {const filePath = resolve(root, pattern);if (existsSync(filePath)) files.push(filePath);}}return files;}function collectRules(root: string): Array<{ agent: string; rules: Rule[]; files: string[] }> {const results: Array<{ agent: string; rules: Rule[]; files: string[] }> = [];62 unmodified linesif (!parser) return { content: [{ type: "text", text: `Unknown agent: ${from}` }] };const files = findAgentFiles(root, from);const rules: Rule[] = [];for (const file of files) {rules.push(...parser.parse(readFileSync(file, "utf-8"), file));}if (rules.length === 0) {return { content: [{ type: "text", text: `No ${from} rules found in ${root}` }] };3 unmodified lines4567891011121314151662 unmodified lines79808182838485868788893 unmodified linesimport { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";import { resolve, join, dirname } from "node:path";import { parsers } from "../parsers/index.js";import { dedupeRules } from "../core/dedupe.js";import { generateConfig, outputFileFor } from "../migrator/generate.js";import { detectDriftEntries } from "../drift/detect.js";import { generateReport, formatReport } from "../checker/engine.js";import type { Rule, AgentKind } from "../core/types.js";import { findAgentFiles } from "../core/files.js";function collectRules(root: string): Array<{ agent: string; rules: Rule[]; files: string[] }> {const results: Array<{ agent: string; rules: Rule[]; files: string[] }> = [];62 unmodified linesif (!parser) return { content: [{ type: "text", text: `Unknown agent: ${from}` }] };const files = findAgentFiles(root, from);const parsed: Rule[] = [];for (const file of files) {parsed.push(...parser.parse(readFileSync(file, "utf-8"), file));}const rules = dedupeRules(parsed);if (rules.length === 0) {return { content: [{ type: "text", text: `No ${from} rules found in ${root}` }] };
24 unmodified lines2526272829303124 unmodified lines};}export const dshParser = makeAgentsMdParser("dsh");export const workbuddyParser = makeAgentsMdParser("workbuddy");export const zcodeParser = makeAgentsMdParser("zcode");export const mimoParser = makeAgentsMdParser("mimo");24 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798024 unmodified lines};}/*** DSH parser: reads both AGENTS.md (project-level, shared standard) and the* global bot-team state file `~/.dsh/bot/state.json`, where each bot's* `instructions` field is the user's accumulated DSH rules.*/export const dshParser: ConfigParser = {agent: "dsh",filePatterns: ["AGENTS.md"],parse(content: string, filePath: string): Rule[] {if (filePath.endsWith("state.json")) {return parseBotState(content, filePath);}const blocks = extractRuleBlocks(content);return blocks.map((block) => ({id: nextRuleId(),category: classifyRule(block),content: block,scope: "project" as const,source: { agent: "dsh" as const, file: filePath },status: "active" as const,}));},};/** Extract each bot's instructions from the DSH bot-team state file. */function parseBotState(content: string, filePath: string): Rule[] {let data: any;try {data = JSON.parse(content);} catch {return [];}const bots = data?.bots ?? {};const rules: Rule[] = [];for (const bot of Object.values<any>(bots)) {const name = typeof bot?.name === "string" ? bot.name : "bot";const instructions = typeof bot?.instructions === "string" ? bot.instructions.trim() : "";if (instructions.length < 10) continue;rules.push({id: nextRuleId(),category: "context",content: `【${name}】${instructions}`,scope: "global",source: { agent: "dsh", file: filePath },status: "active",});}return rules;}export const workbuddyParser = makeAgentsMdParser("workbuddy");export const zcodeParser = makeAgentsMdParser("zcode");export const mimoParser = makeAgentsMdParser("mimo");
1234539 unmodified lines454647import { describe, it, expect } from "vitest";import { windsurfParser } from "../src/parsers/windsurf.js";import { copilotParser } from "../src/parsers/copilot.js";describe("windsurfParser", () => {39 unmodified lines]);});});12345639 unmodified lines46474849505152535455565758596061626364656667686970import { describe, it, expect } from "vitest";import { windsurfParser } from "../src/parsers/windsurf.js";import { dshParser } from "../src/parsers/agents-md.js";import { copilotParser } from "../src/parsers/copilot.js";describe("windsurfParser", () => {39 unmodified lines]);});});describe("dshParser bot state", () => {it("extracts bot instructions from state.json", () => {const state = JSON.stringify({bots: {a: { name: "代码 bot", instructions: "你是团队的代码 Bot,负责写代码和加测试。" },b: { name: "计划 bot", instructions: "你是计划 Bot,负责拆解计划。" },c: { name: "empty", instructions: "" },},});const rules = dshParser.parse(state, "/Users/x/.dsh/bot/state.json");expect(rules.length).toBe(2);expect(rules[0].content).toContain("代码 bot");expect(rules[0].scope).toBe("global");expect(rules[0].source.agent).toBe("dsh");});it("falls back to markdown parsing for AGENTS.md", () => {const rules = dshParser.parse("- Use TypeScript\n- Run tests first", "AGENTS.md");expect(rules.length).toBe(2);});});
ext/dsh-plugin/client.js+42-2
ext/dsh-plugin/index.js+46-3
src/cli/commands/drift.ts+1-23
src/cli/commands/move.ts+12-28
src/cli/commands/scan.ts+4-25
src/core/dedupe.tsAdded+19
src/core/files.tsAdded+43
src/mcp/server.ts+5-25
src/parsers/agents-md.ts+50-1
tests/parsers-extra.test.ts+23