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74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import * as vscode from "vscode";
import { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs";
import { resolve, join, dirname } from "node:path";
import { homedir } from "node:os";
import {
  parsers,
  generateConfig,
  outputFileFor,
  detectDriftEntries,
  findMissingRules,
  generateReport,
  type Rule,
} from "../../../src/index.js";

let panel: vscode.WebviewPanel | undefined;
let outputChannel: vscode.OutputChannel;

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[] }> = [];
  for (const [agentName, parser] of Object.entries(parsers)) {
    const files = findAgentFiles(root, agentName);
    if (files.length === 0) continue;
    const rules: Rule[] = [];
    for (const file of files) {
      rules.push(...parser.parse(readFileSync(file, "utf-8"), file));
    }
    results.push({ agent: agentName, rules, files });
  }
  return results;
}

function getWorkspaceRoot(): string | undefined {
  return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
}

export function activate(context: vscode.ExtensionContext) {
  outputChannel = vscode.window.createOutputChannel("AgentLens");
  context.subscriptions.push(outputChannel);

  // === Scan ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.scan", async () => {
      const root = getWorkspaceRoot();
      if (!root) {
        vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
        return;
      }
      const results = collectRules(root);
      outputChannel.clear();
      outputChannel.appendLine(`扫描 ${root}`);
      outputChannel.appendLine("");
      if (results.length === 0) {
        outputChannel.appendLine("未发现 Agent 配置。");
        vscode.window.showInformationMessage("AgentLens: 未发现 Agent 配置");
        return;
      }
      for (const r of results) {
        const cats = new Map<string, number>();
        for (const rule of r.rules) cats.set(rule.category, (cats.get(rule.category) ?? 0) + 1);
        const catStr = [...cats.entries()].map(([c, n]) => `${c}(${n})`).join(", ");
        outputChannel.appendLine(`✅ ${r.agent.toUpperCase()} — ${r.rules.length} 条规则 [${catStr}]`);
        for (const f of r.files) outputChannel.appendLine(`   📄 ${f.replace(root, ".")}`);
      }
      outputChannel.show();
      vscode.window.showInformationMessage(
        `AgentLens: 发现 ${results.length} 个 Agent 配置,共 ${results.reduce((a, r) => a + r.rules.length, 0)} 条规则`
      );
      updatePanelContent(root);
    })
  );

  // === Move (quick pick flow) ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.move", async () => {
      const root = getWorkspaceRoot();
      if (!root) {
        vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
        return;
      }
      const found = collectRules(root);
      if (found.length === 0) {
        vscode.window.showWarningMessage("AgentLens: 未发现任何 Agent 配置");
        return;
      }
      const from = await vscode.window.showQuickPick(
        found.map((f) => f.agent),
        { placeHolder: "从哪个 Agent 迁移规则?" }
      );
      if (!from) return;
      const allAgents = Object.keys(parsers);
      const to = await vscode.window.showQuickPick(
        allAgents.filter((a) => a !== from),
        { placeHolder: "迁移到哪个 Agent?" }
      );
      if (!to) return;

      const sourceRules = found.find((f) => f.agent === from)?.rules ?? [];
      const content = generateConfig(sourceRules, to as any);
      const outPath = resolve(root, outputFileFor(to as any));
      mkdirSync(dirname(outPath), { recursive: true });
      writeFileSync(outPath, content, "utf-8");
      vscode.window.showInformationMessage(
        `AgentLens: ${sourceRules.length} 条规则已迁移 ${from} → ${to}(${outPath.replace(root, ".")})`
      );
      outputChannel.appendLine(`迁移完成: ${from} → ${to}, ${sourceRules.length} 条规则 → ${outPath}`);
    })
  );

  // === Drift ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.drift", async () => {
      const root = getWorkspaceRoot();
      if (!root) {
        vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
        return;
      }
      const found = collectRules(root);
      const allRules = found.flatMap((f) => f.rules);
      if (allRules.length === 0) {
        vscode.window.showInformationMessage("AgentLens: 没有可比较的规则");
        return;
      }
      const drifts = detectDriftEntries(allRules);
      if (found.length >= 2) {
        const base = found[0];
        for (let i = 1; i < found.length; i++) {
          drifts.push(...findMissingRules(base.rules, found[i].rules, base.agent as any, found[i].agent as any));
        }
      }
      outputChannel.clear();
      if (drifts.length === 0) {
        outputChannel.appendLine("✅ 未发现配置漂移");
        vscode.window.showInformationMessage("AgentLens: 未发现配置漂移");
      } else {
        outputChannel.appendLine(`⚠ 发现 ${drifts.length} 处漂移:`);
        for (const d of drifts) {
          outputChannel.appendLine(`[${d.type}] ${d.description}`);
        }
        vscode.window.showWarningMessage(`AgentLens: 发现 ${drifts.length} 处配置漂移`);
      }
      outputChannel.show();
      updatePanelContent(root);
    })
  );

  // === Check current file ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.checkFile", async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) {
        vscode.window.showWarningMessage("AgentLens: 没有打开的文件");
        return;
      }
      const filePath = editor.document.uri.fsPath;
      const content = editor.document.getText();
      const ext = filePath.split(".").pop()?.toLowerCase();
      const langMap: Record<string, string> = {
        ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
        py: "python", go: "go", rs: "rust", java: "java",
      };
      const report = generateReport([{ path: filePath, content, language: ext ? langMap[ext] : undefined }]);
      outputChannel.clear();
      outputChannel.appendLine(`体检: ${filePath}`);
      outputChannel.appendLine(`🔴 ${report.summary.critical} critical  🟡 ${report.summary.warning} warning  ⚪ ${report.summary.info} info`);
      outputChannel.appendLine("");
      for (const f of report.findings) {
        outputChannel.appendLine(`[${f.severity}] ${f.file}:${f.line ?? "?"} — ${f.message}`);
        if (f.suggestion) outputChannel.appendLine(`   💡 ${f.suggestion}`);
      }
      outputChannel.show();
      if (report.summary.critical > 0) {
        vscode.window.showErrorMessage(`AgentLens: ${report.summary.critical} 个严重问题!`);
      } else if (report.summary.warning > 0) {
        vscode.window.showWarningMessage(`AgentLens: ${report.summary.warning} 个警告`);
      } else {
        vscode.window.showInformationMessage("AgentLens: 体检通过 ✅");
      }
    })
  );

  // === Check workspace changes ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.checkWorkspace", async () => {
      const root = getWorkspaceRoot();
      if (!root) {
        vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹");
        return;
      }
      const { execSync } = await import("node:child_process");
      let files: string[] = [];
      try {
        files = execSync("git diff --name-only HEAD", { cwd: root, encoding: "utf-8" })
          .trim()
          .split("\n")
          .filter(Boolean);
      } catch {
        vscode.window.showWarningMessage("AgentLens: 无法读取 git 变更");
        return;
      }
      if (files.length === 0) {
        vscode.window.showInformationMessage("AgentLens: 没有未提交的变更");
        return;
      }
      outputChannel.clear();
      outputChannel.appendLine(`体检工作区变更 (${files.length} 个文件)`);
      let totalCritical = 0;
      let totalWarning = 0;
      for (const f of files) {
        const full = resolve(root, f);
        if (!existsSync(full)) continue;
        const ext = f.split(".").pop()?.toLowerCase();
        const langMap: Record<string, string> = {
          ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
          py: "python", go: "go", rs: "rust", java: "java",
        };
        const report = generateReport([{ path: f, content: readFileSync(full, "utf-8"), language: ext ? langMap[ext] : undefined }]);
        totalCritical += report.summary.critical;
        totalWarning += report.summary.warning;
        for (const finding of report.findings) {
          outputChannel.appendLine(`[${finding.severity}] ${finding.file}:${finding.line ?? "?"} — ${finding.message}`);
        }
      }
      outputChannel.show();
      if (totalCritical > 0) {
        vscode.window.showErrorMessage(`AgentLens: ${totalCritical} 个严重问题!`);
      } else if (totalWarning > 0) {
        vscode.window.showWarningMessage(`AgentLens: ${totalWarning} 个警告`);
      } else {
        vscode.window.showInformationMessage("AgentLens: 变更体检通过 ✅");
      }
    })
  );

  // === Open settings panel ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.openPanel", async () => {
      if (panel) {
        panel.reveal();
      } else {
        panel = vscode.window.createWebviewPanel(
          "agentlens.panel",
          "AgentLens 设置",
          vscode.ViewColumn.One,
          { enableScripts: true }
        );
        panel.onDidDispose(() => { panel = undefined; });
        panel.webview.html = getPanelHtml();

        // Wire the panel buttons to real commands — without this the buttons do nothing.
        panel.webview.onDidReceiveMessage(async (msg) => {
          switch (msg?.command) {
            case "scan":
              await vscode.commands.executeCommand("agentlens.scan");
              break;
            case "move":
              await vscode.commands.executeCommand("agentlens.move");
              break;
            case "drift":
              await vscode.commands.executeCommand("agentlens.drift");
              break;
            case "check":
              await vscode.commands.executeCommand("agentlens.checkFile");
              break;
            case "install":
              await vscode.commands.executeCommand("agentlens.installAll");
              break;
            default:
              break;
          }
        });

        const root = getWorkspaceRoot();
        if (root) updatePanelContent(root);
      }
    })
  );

  // === One-click install into every detected AI app ===
  context.subscriptions.push(
    vscode.commands.registerCommand("agentlens.installAll", async () => {
      const { execFile } = await import("node:child_process");
      const { promisify } = await import("node:util");
      const execFileAsync = promisify(execFile);
      const entry = (context as any).extensionPath
        ? resolve((context as any).extensionPath, "agentlens-cli", "index.js")
        : undefined;
      const cli = entry && existsSync(entry) ? entry : join(homedir(), "Downloads", "mimo", "agentlens", "dist", "cli", "index.js");
      if (!existsSync(cli)) {
        vscode.window.showWarningMessage("AgentLens: 找不到安装器入口(需要先构建 agentlens 项目)");
        return;
      }
      try {
        let nodeBin = process.env.AGENTLENS_NODE || "";
        if (!nodeBin) {
          for (const c of ["/usr/local/bin/node", "/opt/homebrew/bin/node", "/usr/bin/node"]) {
            if (existsSync(c)) { nodeBin = c; break; }
          }
        }
        if (!nodeBin) nodeBin = "node";
        const { stdout, stderr } = await execFileAsync(nodeBin, [cli, "install", "--target", "all"], { timeout: 120_000 });
        outputChannel.clear();
        outputChannel.appendLine(stdout || "");
        if (stderr) outputChannel.appendLine(stderr);
        outputChannel.show();
        vscode.window.showInformationMessage("AgentLens: 已接入所有检测到的 AI 工具(重启对应 App 生效)");
      } catch (err: any) {
        vscode.window.showErrorMessage(`AgentLens 接入失败: ${err?.message ?? err}`);
      }
    })
  );

  // === Auto check on save (if enabled) ===
  context.subscriptions.push(
    vscode.workspace.onDidSaveTextDocument(async (doc) => {
      const config = vscode.workspace.getConfiguration("agentlens");
      if (config.get<boolean>("autoCheckOnSave")) {
        await vscode.commands.executeCommand("agentlens.checkFile");
      }
    })
  );

  outputChannel.appendLine("AgentLens 已激活。命令面板输入 'AgentLens' 查看所有命令。");
}

async function updatePanelContent(root: string) {
  if (!panel) return;
  const results = collectRules(root);
  panel.webview.postMessage({ type: "scanResult", results: results.map((r) => ({
    agent: r.agent,
    ruleCount: r.rules.length,
    files: r.files.map((f) => f.replace(root, ".")),
  })) });
}

function getPanelHtml(): string {
  return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
  body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); background: var(--vscode-editor-background); padding: 20px; }
  h1 { font-size: 1.4em; }
  .card { border: 1px solid var(--vscode-panel-border); border-radius: 8px; padding: 16px; margin: 12px 0; }
  .agent-name { font-weight: 600; margin-bottom: 6px; }
  .muted { opacity: 0.7; font-size: 0.9em; }
  .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; }
  .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; }
  .btn:hover { background: var(--vscode-button-hoverBackground); }
  ul { padding-left: 20px; margin: 8px 0; }
  li { margin: 4px 0; font-size: 0.95em; }
  .empty { opacity: 0.6; font-style: italic; }
</style>
</head>
<body>
  <h1>🔍 AgentLens</h1>
  <p class="muted">AI 编程 Agent 规则迁移 + 代码体检</p>
  <div style="margin: 16px 0;">
    <button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'scan'});})()">扫描配置</button>
    <button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'move'});})()">迁移规则</button>
    <button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'drift'});})()">检测漂移</button>
    <button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'check'});})()">体检文件</button>
    <button class="btn" onclick="(function(){const v=acquireVsCodeApi();v.postMessage({command:'install'});})()">一键接入所有 App</button>
  </div>
  <div id="results"><p class="empty">点击「扫描配置」开始</p></div>
  <script>
    const vscode = acquireVsCodeApi();
    window.addEventListener('message', (event) => {
      const msg = event.data;
      if (msg.type === 'scanResult') {
        const el = document.getElementById('results');
        if (!msg.results || msg.results.length === 0) {
          el.innerHTML = '<p class="empty">未发现 Agent 配置</p>';
          return;
        }
        el.innerHTML = msg.results.map(r => 
          '<div class="card"><div class="agent-name">' + r.agent.toUpperCase() + 
          '<span class="rule-badge">' + r.ruleCount + ' 条规则</span></div>' +
          '<ul>' + r.files.map(f => '<li>' + f + '</li>').join('') + '</ul></div>'
        ).join('');
      }
    });
  </script>
</body>
</html>`;
}

export function deactivate() {}