pi-lens 3.6.2 → 3.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/CHANGELOG.md +10 -2
  2. package/package.json +4 -4
  3. package/tsconfig.json +1 -1
  4. package/clients/__tests__/file-time.test.js +0 -216
  5. package/clients/__tests__/file-time.test.ts +0 -276
  6. package/clients/__tests__/format-service.test.js +0 -245
  7. package/clients/__tests__/format-service.test.ts +0 -339
  8. package/clients/__tests__/formatters.test.js +0 -271
  9. package/clients/__tests__/formatters.test.ts +0 -401
  10. package/clients/agent-behavior-client.js +0 -110
  11. package/clients/agent-behavior-client.test.js +0 -94
  12. package/clients/agent-behavior-client.test.ts +0 -116
  13. package/clients/amain-types.js +0 -164
  14. package/clients/architect-client.js +0 -291
  15. package/clients/ast-grep-client.js +0 -253
  16. package/clients/ast-grep-parser.js +0 -84
  17. package/clients/ast-grep-rule-manager.js +0 -89
  18. package/clients/ast-grep-types.js +0 -9
  19. package/clients/auto-loop.js +0 -131
  20. package/clients/biome-client.js +0 -420
  21. package/clients/biome-client.test.js +0 -144
  22. package/clients/biome-client.test.ts +0 -163
  23. package/clients/cache/rule-cache.js +0 -72
  24. package/clients/cache-manager.js +0 -245
  25. package/clients/cache-manager.test.js +0 -197
  26. package/clients/cache-manager.test.ts +0 -299
  27. package/clients/complexity-client.js +0 -675
  28. package/clients/complexity-client.test.js +0 -234
  29. package/clients/complexity-client.test.ts +0 -255
  30. package/clients/config-validator.js +0 -465
  31. package/clients/dependency-checker.js +0 -325
  32. package/clients/dependency-checker.test.js +0 -60
  33. package/clients/dependency-checker.test.ts +0 -71
  34. package/clients/dispatch/__tests__/autofix-integration.test.js +0 -245
  35. package/clients/dispatch/__tests__/autofix-integration.test.ts +0 -300
  36. package/clients/dispatch/__tests__/runner-registration.test.js +0 -234
  37. package/clients/dispatch/__tests__/runner-registration.test.ts +0 -286
  38. package/clients/dispatch/debug.log +0 -1
  39. package/clients/dispatch/dispatcher.edge.test.js +0 -82
  40. package/clients/dispatch/dispatcher.edge.test.ts +0 -100
  41. package/clients/dispatch/dispatcher.format.test.js +0 -46
  42. package/clients/dispatch/dispatcher.format.test.ts +0 -58
  43. package/clients/dispatch/dispatcher.inline.test.js +0 -74
  44. package/clients/dispatch/dispatcher.inline.test.ts +0 -93
  45. package/clients/dispatch/dispatcher.js +0 -381
  46. package/clients/dispatch/dispatcher.test.js +0 -116
  47. package/clients/dispatch/dispatcher.test.ts +0 -149
  48. package/clients/dispatch/integration.js +0 -108
  49. package/clients/dispatch/plan.js +0 -183
  50. package/clients/dispatch/runners/architect.js +0 -83
  51. package/clients/dispatch/runners/architect.test.js +0 -138
  52. package/clients/dispatch/runners/architect.test.ts +0 -162
  53. package/clients/dispatch/runners/ast-grep-napi.js +0 -405
  54. package/clients/dispatch/runners/ast-grep-napi.test.js +0 -107
  55. package/clients/dispatch/runners/ast-grep-napi.test.ts +0 -129
  56. package/clients/dispatch/runners/ast-grep.js +0 -157
  57. package/clients/dispatch/runners/biome.js +0 -55
  58. package/clients/dispatch/runners/config-validation.js +0 -67
  59. package/clients/dispatch/runners/go-vet.js +0 -48
  60. package/clients/dispatch/runners/index.js +0 -47
  61. package/clients/dispatch/runners/lsp.js +0 -102
  62. package/clients/dispatch/runners/oxlint.js +0 -67
  63. package/clients/dispatch/runners/oxlint.test.js +0 -230
  64. package/clients/dispatch/runners/oxlint.test.ts +0 -303
  65. package/clients/dispatch/runners/pyright.js +0 -100
  66. package/clients/dispatch/runners/pyright.test.js +0 -98
  67. package/clients/dispatch/runners/pyright.test.ts +0 -121
  68. package/clients/dispatch/runners/python-slop.js +0 -97
  69. package/clients/dispatch/runners/python-slop.test.js +0 -203
  70. package/clients/dispatch/runners/python-slop.test.ts +0 -298
  71. package/clients/dispatch/runners/ruff.js +0 -48
  72. package/clients/dispatch/runners/rust-clippy.js +0 -102
  73. package/clients/dispatch/runners/scan_codebase.test.js +0 -89
  74. package/clients/dispatch/runners/scan_codebase.test.ts +0 -105
  75. package/clients/dispatch/runners/shellcheck.js +0 -147
  76. package/clients/dispatch/runners/shellcheck.test.js +0 -98
  77. package/clients/dispatch/runners/shellcheck.test.ts +0 -129
  78. package/clients/dispatch/runners/similarity.js +0 -230
  79. package/clients/dispatch/runners/spellcheck.js +0 -106
  80. package/clients/dispatch/runners/spellcheck.test.js +0 -158
  81. package/clients/dispatch/runners/spellcheck.test.ts +0 -214
  82. package/clients/dispatch/runners/tree-sitter.js +0 -246
  83. package/clients/dispatch/runners/ts-lsp.js +0 -125
  84. package/clients/dispatch/runners/ts-slop.js +0 -113
  85. package/clients/dispatch/runners/type-safety.js +0 -142
  86. package/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -134
  87. package/clients/dispatch/runners/utils/runner-helpers.js +0 -115
  88. package/clients/dispatch/runners/utils.js +0 -51
  89. package/clients/dispatch/runners/yaml-rule-parser.js +0 -360
  90. package/clients/dispatch/types.js +0 -16
  91. package/clients/dispatch/utils/format-utils.js +0 -44
  92. package/clients/dogfood.test.js +0 -201
  93. package/clients/dogfood.test.ts +0 -269
  94. package/clients/file-kinds.js +0 -177
  95. package/clients/file-kinds.test.js +0 -169
  96. package/clients/file-kinds.test.ts +0 -210
  97. package/clients/file-time.js +0 -152
  98. package/clients/file-utils.js +0 -40
  99. package/clients/fix-scanners.js +0 -204
  100. package/clients/format-service.js +0 -184
  101. package/clients/formatters.js +0 -488
  102. package/clients/go-client.js +0 -203
  103. package/clients/go-client.test.js +0 -127
  104. package/clients/go-client.test.ts +0 -143
  105. package/clients/installer/index.js +0 -403
  106. package/clients/interviewer-templates.js +0 -75
  107. package/clients/interviewer.js +0 -173
  108. package/clients/jscpd-client.js +0 -196
  109. package/clients/jscpd-client.test.js +0 -127
  110. package/clients/jscpd-client.test.ts +0 -145
  111. package/clients/knip-client.js +0 -239
  112. package/clients/knip-client.test.js +0 -112
  113. package/clients/knip-client.test.ts +0 -128
  114. package/clients/latency-logger.js +0 -40
  115. package/clients/lsp/__tests__/client.test.js +0 -310
  116. package/clients/lsp/__tests__/client.test.ts +0 -412
  117. package/clients/lsp/__tests__/config.test.js +0 -167
  118. package/clients/lsp/__tests__/config.test.ts +0 -217
  119. package/clients/lsp/__tests__/error-recovery.test.js +0 -213
  120. package/clients/lsp/__tests__/error-recovery.test.ts +0 -279
  121. package/clients/lsp/__tests__/integration.test.js +0 -127
  122. package/clients/lsp/__tests__/integration.test.ts +0 -160
  123. package/clients/lsp/__tests__/launch.test.js +0 -313
  124. package/clients/lsp/__tests__/launch.test.ts +0 -394
  125. package/clients/lsp/__tests__/server.test.js +0 -259
  126. package/clients/lsp/__tests__/server.test.ts +0 -332
  127. package/clients/lsp/__tests__/service.test.js +0 -438
  128. package/clients/lsp/__tests__/service.test.ts +0 -530
  129. package/clients/lsp/client.js +0 -350
  130. package/clients/lsp/config.js +0 -112
  131. package/clients/lsp/index.js +0 -318
  132. package/clients/lsp/installer/index.js +0 -391
  133. package/clients/lsp/interactive-install.js +0 -221
  134. package/clients/lsp/language.js +0 -170
  135. package/clients/lsp/launch.js +0 -329
  136. package/clients/lsp/lsp/launch.js +0 -116
  137. package/clients/lsp/lsp/server.js +0 -532
  138. package/clients/lsp/lsp-index.js +0 -10
  139. package/clients/lsp/path-utils.js +0 -5
  140. package/clients/lsp/server.js +0 -725
  141. package/clients/lsp/test-py-spawn/requirements.txt +0 -1
  142. package/clients/lsp/test-py-spawn/test.py +0 -3
  143. package/clients/lsp/test-py-svc/requirements.txt +0 -1
  144. package/clients/lsp/test-py-svc/test.py +0 -3
  145. package/clients/lsp/test-python-project/requirements.txt +0 -1
  146. package/clients/lsp/test-python-project/test.py +0 -5
  147. package/clients/metrics-client.js +0 -107
  148. package/clients/metrics-client.test.js +0 -128
  149. package/clients/metrics-client.test.ts +0 -163
  150. package/clients/metrics-history.js +0 -367
  151. package/clients/path-utils.js +0 -142
  152. package/clients/pipeline.js +0 -272
  153. package/clients/production-readiness.js +0 -522
  154. package/clients/project-index.js +0 -255
  155. package/clients/project-metadata.js +0 -531
  156. package/clients/ruff-client.js +0 -325
  157. package/clients/ruff-client.test.js +0 -132
  158. package/clients/ruff-client.test.ts +0 -153
  159. package/clients/rules-scanner.js +0 -97
  160. package/clients/runner-tracker.js +0 -152
  161. package/clients/rust-client.js +0 -205
  162. package/clients/rust-client.test.js +0 -108
  163. package/clients/rust-client.test.ts +0 -130
  164. package/clients/safe-spawn-async.js +0 -163
  165. package/clients/safe-spawn.js +0 -241
  166. package/clients/sanitize.js +0 -291
  167. package/clients/sanitize.test.js +0 -177
  168. package/clients/sanitize.test.ts +0 -223
  169. package/clients/scan-architectural-debt.js +0 -167
  170. package/clients/scan-utils.js +0 -83
  171. package/clients/secrets-scanner.js +0 -119
  172. package/clients/secrets-scanner.test.js +0 -100
  173. package/clients/secrets-scanner.test.ts +0 -113
  174. package/clients/sg-runner.js +0 -292
  175. package/clients/state-matrix.js +0 -160
  176. package/clients/subprocess-client.js +0 -65
  177. package/clients/symbol-types.js +0 -5
  178. package/clients/test-runner-client.js +0 -523
  179. package/clients/test-runner-client.test.js +0 -192
  180. package/clients/test-runner-client.test.ts +0 -253
  181. package/clients/test-utils.js +0 -27
  182. package/clients/test-utils.ts +0 -36
  183. package/clients/todo-scanner.js +0 -200
  184. package/clients/todo-scanner.test.js +0 -301
  185. package/clients/todo-scanner.test.ts +0 -352
  186. package/clients/tool-availability.js +0 -207
  187. package/clients/tree-sitter-client.js +0 -601
  188. package/clients/tree-sitter-query-loader.js +0 -355
  189. package/clients/tree-sitter-symbol-extractor.js +0 -289
  190. package/clients/ts-service.js +0 -129
  191. package/clients/type-coverage-client.js +0 -127
  192. package/clients/type-coverage-client.test.js +0 -105
  193. package/clients/type-coverage-client.test.ts +0 -125
  194. package/clients/type-safety-client.js +0 -138
  195. package/clients/types.js +0 -11
  196. package/clients/typescript-client.codefix.test.js +0 -157
  197. package/clients/typescript-client.codefix.test.ts +0 -186
  198. package/clients/typescript-client.js +0 -509
  199. package/clients/typescript-client.test.js +0 -105
  200. package/clients/typescript-client.test.ts +0 -126
  201. package/commands/booboo.js +0 -1007
  202. package/commands/fix-from-booboo.js +0 -398
  203. package/commands/fix-simplified.js +0 -618
  204. package/commands/rate.js +0 -281
  205. package/commands/rate.test.js +0 -119
  206. package/commands/rate.test.ts +0 -131
  207. package/commands/refactor.js +0 -130
@@ -1,75 +0,0 @@
1
- export const CONFIRMATION_HTML = (question, plan, diff, esc, mdToHtml, diffHtml, addCount, delCount) => `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
2
- <title>🏗️ Changes Applied</title>
3
- <style>
4
- *{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#0d1117;color:#e6edf3;padding:28px 32px;max-width:960px;margin:0 auto;line-height:1.5}
5
- h2{font-size:16px;color:#58a6ff;margin-bottom:14px}
6
- .plan{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:14px 18px;margin-bottom:18px;font-size:13px;line-height:1.6}
7
- .plan h3{color:#f0f6fc;font-size:14px;margin:10px 0 4px}.plan h4{color:#c9d1d9;font-size:13px;margin:8px 0 3px}
8
- .plan li{margin:2px 0 2px 16px;list-style:disc}.plan code{background:#21262d;padding:1px 5px;border-radius:3px;font-size:12px}
9
- .diff-wrap{background:#161b22;border:1px solid #30363d;border-radius:8px;margin-bottom:18px;overflow:hidden}
10
- .diff-hdr{padding:7px 14px;font-size:11px;color:#8b949e;border-bottom:1px solid #30363d;font-family:monospace;display:flex;justify-content:space-between}
11
- .diff-stats{display:flex;gap:10px}.stat-add{color:#3fb950}.stat-del{color:#ff7b72}
12
- .diff-pre{padding:12px;font-family:'Fira Code',Consolas,monospace;font-size:12px;line-height:1.55;overflow-x:auto;white-space:pre;margin:0}
13
- .da{color:#3fb950;display:block}.dd{color:#ff7b72;display:block}.dh{color:#79c0ff;display:block}.df{color:#8b949e;display:block}.dc{color:#e6edf3;display:block}
14
- .actions{display:flex;gap:10px;flex-wrap:wrap}
15
- .btn-c{background:#238636;color:#fff;border:1px solid #2ea043;padding:10px 24px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer}.btn-c:hover{background:#2ea043}
16
- .btn-chat{background:#1a2332;color:#79c0ff;border:1px solid #1f6feb;padding:10px 24px;border-radius:6px;font-size:14px;cursor:pointer}.btn-chat:hover{background:#1f3050}
17
- .chat-area{display:none;margin-top:12px}
18
- textarea{width:100%;background:#161b22;border:1px solid #30363d;color:#e6edf3;padding:9px;border-radius:6px;font-family:inherit;font-size:13px;resize:vertical;min-height:72px;outline:none}
19
- textarea:focus{border-color:#58a6ff}
20
- .hint{color:#6e7681;font-size:12px;margin-top:10px}
21
- </style></head><body>
22
- <h2>${esc(question)}</h2>
23
- <div class="plan"><p>${mdToHtml(plan)}</p></div>
24
- ${diff ? `<div class="diff-wrap"><div class="diff-hdr"><span>Changes</span><div class="diff-stats"><span class="stat-add">+${addCount}</span><span class="stat-del">−${delCount}</span></div></div><pre class="diff-pre">${diffHtml}</pre></div>` : ""}
25
- <form method="POST" id="f">
26
- <input type="hidden" name="choice" id="c" value="Looks good">
27
- <div class="actions">
28
- <button class="btn-c" type="submit">✅ Looks good — move to next offender</button>
29
- <button class="btn-chat" type="button" onclick="toggleChat()">💬 Request changes</button>
30
- </div>
31
- <div class="chat-area" id="ca"><textarea name="freeText" placeholder="Describe what you'd like changed..."></textarea>
32
- <div style="margin-top:8px"><button class="btn-c" type="submit" onclick="document.getElementById('c').value='Redo'">Submit</button></div></div>
33
- </form>
34
- <p class="hint">Tab closes after submit · Ctrl+Enter to confirm</p>
35
- <script>
36
- function toggleChat(){const r=document.getElementById('ca');r.style.display=r.style.display==='none'?'block':'none';if(r.style.display==='block')r.querySelector('textarea').focus();}
37
- document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key==='Enter'){document.getElementById('f').submit();}});
38
- </script>
39
- </body></html>`;
40
- export const INTERVIEW_HTML = (question, optionsHtml, hasFreeText, esc) => `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
41
- <title>🏗️ Decision</title>
42
- <style>
43
- *{box-sizing:border-box;margin:0;padding:0}body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#0d1117;color:#e6edf3;padding:28px 32px;max-width:880px;margin:0 auto;line-height:1.5}
44
- .question{font-size:15px;font-weight:600;color:#f0f6fc;margin-bottom:12px}
45
- .opts{display:flex;flex-direction:column;gap:8px;margin-bottom:16px}
46
- .card{border:1px solid #30363d;border-radius:8px;padding:11px 14px;cursor:pointer;transition:border-color .12s,background .12s;display:flex;align-items:flex-start;gap:10px}
47
- .card:hover,.card.selected{border-color:#58a6ff;background:#0d1f30}.card.rec{border-color:#1f6feb}
48
- .card input{margin-top:3px;accent-color:#58a6ff;flex-shrink:0}.card-body{flex:1}
49
- .card-top{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
50
- .num{color:#6e7681;font-size:13px;min-width:18px}.lbl{font-size:13.5px;font-weight:500}
51
- .badge-rec{background:#1f4e2e;color:#3fb950;font-size:10px;padding:1px 7px;border-radius:10px;margin-left:4px;font-weight:600}
52
- .ctx{color:#8b949e;font-size:12px;margin-top:3px;padding-left:22px}
53
- .impact{display:flex;gap:6px;margin-top:5px;padding-left:22px;flex-wrap:wrap}
54
- .ib{font-size:11px;padding:2px 8px;border-radius:10px;font-family:monospace;font-weight:600}
55
- .ib.up{background:#1a3a2a;color:#3fb950;border:1px solid #238636}
56
- .ib.dn{background:#3a1a1a;color:#ff7b72;border:1px solid #f85149}
57
- .ib.proj{background:#1a2a3a;color:#79c0ff;border:1px solid #1f6feb}
58
- .free-area{display:none;margin-top:10px;padding-left:22px}
59
- textarea{width:100%;background:#161b22;border:1px solid #30363d;color:#e6edf3;padding:9px;border-radius:6px;font-family:inherit;font-size:13px;resize:vertical;min-height:72px;outline:none}
60
- textarea:focus{border-color:#58a6ff}
61
- .submit-row{display:flex;align-items:center;gap:12px;margin-top:4px}
62
- button{background:#238636;color:#fff;border:1px solid #2ea043;padding:9px 22px;border-radius:6px;font-size:13.5px;font-weight:600;cursor:pointer;transition:background .12s}
63
- button:hover{background:#2ea043}.hint{color:#6e7681;font-size:12px}
64
- </style></head><body>
65
- <div class="question">${esc(question)}</div>
66
- <form method="POST" id="f">
67
- <div class="opts">${optionsHtml}</div>
68
- ${hasFreeText ? '<div class="free-area" id="fa"><textarea name="freeText" placeholder="Describe your preferred approach..."></textarea></div>' : ""}
69
- <div class="submit-row"><button type="submit">Submit</button><span class="hint">Ctrl+Enter</span></div>
70
- </form>
71
- <script>
72
- const cards=document.querySelectorAll('.card');function sel(c){cards.forEach(x=>{x.classList.remove('selected');x.querySelector('input').checked=false});c.classList.add('selected');c.querySelector('input').checked=true;const fa=document.getElementById('fa');if(fa)fa.style.display=c.querySelector('input').value==='__free__'?'block':'none';}
73
- cards.forEach(c=>c.addEventListener('click',()=>sel(c)));const rec=document.querySelector('.card.rec');if(rec)sel(rec);else if(cards.length)sel(cards[0]);
74
- document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key==='Enter')document.getElementById('f').submit();});
75
- </script></body></html>`;
@@ -1,173 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import * as http from "node:http";
3
- import * as net from "node:net";
4
- import { Type } from "@sinclair/typebox";
5
- import { CONFIRMATION_HTML, INTERVIEW_HTML } from "./interviewer-templates.js";
6
- export function buildInterviewer(pi, _dbg) {
7
- let interviewHandler = null;
8
- const esc = (s) => s
9
- .replace(/&/g, "&amp;")
10
- .replace(/</g, "&lt;")
11
- .replace(/>/g, "&gt;")
12
- .replace(/"/g, "&quot;");
13
- const mdToHtml = (md) => md
14
- .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
15
- .replace(/`([^`]+)`/g, "<code>$1</code>")
16
- .replace(/^### (.+)/gm, "<h4>$1</h4>")
17
- .replace(/^## (.+)/gm, "<h3>$1</h3>")
18
- .replace(/^# (.+)/gm, "<h2>$1</h2>")
19
- .replace(/^- (.+)/gm, "<li>$1</li>")
20
- .replace(/\n\n/g, "</p><p>");
21
- const confirmationHTML = (question, plan, diff) => {
22
- const diffLines = diff.split("\n");
23
- const diffHtml = diffLines
24
- .map((line) => {
25
- if (line.startsWith("+++") || line.startsWith("---"))
26
- return `<span class="df">${esc(line)}</span>`;
27
- if (line.startsWith("@@"))
28
- return `<span class="dh">${esc(line)}</span>`;
29
- if (line.startsWith("+"))
30
- return `<span class="da">${esc(line)}</span>`;
31
- if (line.startsWith("-"))
32
- return `<span class="dd">${esc(line)}</span>`;
33
- return `<span class="dc">${esc(line)}</span>`;
34
- })
35
- .join("\n");
36
- const addCount = (diff.match(/^\+/gm) || []).length;
37
- const delCount = (diff.match(/^-/gm) || []).length - (diff.match(/^---/gm) || []).length;
38
- return CONFIRMATION_HTML(question, plan, diff, esc, mdToHtml, diffHtml, addCount, delCount);
39
- };
40
- const interviewHTML = (question, options, _timeoutSeconds, _plan, _diff, _confirmationMode) => {
41
- if (_confirmationMode && _plan && _diff)
42
- return confirmationHTML(question, _plan, _diff);
43
- const optionsHtml = options
44
- .map((opt, idx) => {
45
- const impactBadge = (val, label, good) => `<span class="ib ${good ? "up" : "dn"}">${val > 0 ? "+" : ""}${val} ${label}</span>`;
46
- let impactHtml = "";
47
- if (opt.impact) {
48
- const parts = [];
49
- if (opt.impact.linesReduced !== undefined)
50
- parts.push(impactBadge(opt.impact.linesReduced, "lines", true));
51
- if (opt.impact.miProjection)
52
- parts.push(`<span class="ib proj">MI ${opt.impact.miProjection}</span>`);
53
- if (opt.impact.cognitiveProjection)
54
- parts.push(`<span class="ib proj">Cognitive ${opt.impact.cognitiveProjection}</span>`);
55
- if (parts.length)
56
- impactHtml = `<div class="impact">${parts.join("")}</div>`;
57
- }
58
- return `<label class="card${opt.recommended ? " rec" : ""}"><input type="radio" name="choice" value="${esc(opt.value)}"${opt.recommended ? " checked" : ""}><div class="card-body"><div class="card-top"><span class="num">${idx + 1}.</span><span class="lbl">${esc(opt.label)}</span>${opt.recommended ? '<span class="badge-rec">Recommended</span>' : ""}</div>${impactHtml}${opt.context ? `<div class="ctx">${esc(opt.context)}</div>` : ""}</div></label>`;
59
- })
60
- .join("\n");
61
- const hasFreeText = options.some((o) => o.value === "__free__");
62
- return INTERVIEW_HTML(question, optionsHtml, hasFreeText, esc);
63
- };
64
- const openBrowserInterview = (html, timeoutSeconds) => {
65
- return new Promise((resolve) => {
66
- const getPort = (cb) => {
67
- const s = net.createServer();
68
- s.listen(0, () => {
69
- const p = s.address().port;
70
- s.close(() => cb(p));
71
- });
72
- s.on("error", () => cb(-1));
73
- };
74
- getPort((port) => {
75
- if (port < 0) {
76
- resolve(null);
77
- return;
78
- }
79
- const server = http.createServer((req, res) => {
80
- if (req.method === "GET") {
81
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
82
- res.end(html);
83
- }
84
- else if (req.method === "POST") {
85
- let body = "";
86
- req.on("data", (c) => {
87
- body += c.toString();
88
- });
89
- req.on("end", () => {
90
- const p = new URLSearchParams(body);
91
- const choice = p.get("choice") ?? "";
92
- const freeText = p.get("freeText") ?? "";
93
- const final = choice === "__free__" || choice === "Redo"
94
- ? freeText.trim()
95
- : choice;
96
- res.writeHead(200, {
97
- "Content-Type": "text/html; charset=utf-8",
98
- });
99
- res.end(`<!DOCTYPE html><html><head><meta charset='UTF-8'><style>body{font-family:system-ui;background:#0d1117;color:#e6edf3;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;text-align:center}.fade{transition:opacity 0.5s}</style></head><body><div class="fade"><h2>✅ Response received</h2><p style='color:#8b949e;margin-top:8px'>Closing tab...</p><p id="count" style='color:#58a6ff;margin-top:4px'></p></div><script>let s=3;const el=document.getElementById('count');const tick=()=>{el.textContent=s+'s';if(s<=0){window.close();}else{s--;setTimeout(tick,1000);}};tick();</script></body></html>`);
100
- clearTimeout(timer);
101
- server.close();
102
- resolve(final || null);
103
- });
104
- }
105
- });
106
- server.listen(port);
107
- const url = `http://localhost:${port}`;
108
- if (process.platform === "win32")
109
- spawnSync("cmd", ["/c", "start", "", url], { shell: false });
110
- else if (process.platform === "darwin")
111
- spawnSync("open", [url]);
112
- else
113
- spawnSync("xdg-open", [url]);
114
- const timer = setTimeout(() => {
115
- server.close();
116
- resolve(null);
117
- }, timeoutSeconds * 1000);
118
- });
119
- });
120
- };
121
- interviewHandler = (question, options, timeoutSeconds, plan, diff, confirmationMode) => openBrowserInterview(interviewHTML(question, options, timeoutSeconds, plan, diff, confirmationMode), timeoutSeconds);
122
- pi.registerTool({
123
- name: "interviewer",
124
- label: "Interview",
125
- description: "Present a multiple-choice interview to the user via browser form. Use this when you need the user to make a decision with options. Returns their choice or null on timeout. Supports confirmation mode with plan+diff display.",
126
- parameters: Type.Object({
127
- question: Type.String({
128
- description: "The question to present to the user",
129
- }),
130
- options: Type.Optional(Type.Array(Type.Object({
131
- value: Type.String(),
132
- label: Type.String(),
133
- context: Type.Optional(Type.String()),
134
- recommended: Type.Optional(Type.Boolean()),
135
- impact: Type.Optional(Type.Object({
136
- linesReduced: Type.Optional(Type.Number()),
137
- miProjection: Type.Optional(Type.String()),
138
- cognitiveProjection: Type.Optional(Type.String()),
139
- })),
140
- }))),
141
- plan: Type.Optional(Type.String({
142
- description: "Refactoring plan (markdown) — shows in confirmation mode",
143
- })),
144
- diff: Type.Optional(Type.String({
145
- description: "Unified diff text — shows in confirmation mode",
146
- })),
147
- confirmationMode: Type.Optional(Type.Boolean({ description: "Show plan+diff confirmation screen" })),
148
- timeoutSeconds: Type.Optional(Type.Number({
149
- description: "Auto-close after this many seconds (default 600)",
150
- })),
151
- }),
152
- async execute(_toolCallId, input, _signal, _onUpdate, _ctx) {
153
- if (!interviewHandler)
154
- return {
155
- content: [
156
- { type: "text", text: "Interview tool not initialized" },
157
- ],
158
- details: null,
159
- };
160
- const result = await interviewHandler(input.question, input.options ?? [], input.timeoutSeconds ?? 600, input.plan, input.diff, input.confirmationMode);
161
- return {
162
- content: [
163
- {
164
- type: "text",
165
- text: result ?? "No response (timed out or dismissed)",
166
- },
167
- ],
168
- details: result ?? null,
169
- };
170
- },
171
- });
172
- return interviewHandler;
173
- }
@@ -1,196 +0,0 @@
1
- /**
2
- * jscpd Client for pi-lens
3
- *
4
- * Detects copy-paste / duplicate code blocks across the project.
5
- * Helps the agent avoid unknowingly duplicating logic that already exists.
6
- *
7
- * Requires: npm install -D jscpd
8
- * Docs: https://github.com/kucherenko/jscpd
9
- */
10
- import * as fs from "node:fs";
11
- import * as os from "node:os";
12
- import * as path from "node:path";
13
- import { safeSpawn } from "./safe-spawn.js";
14
- // --- Client ---
15
- export class JscpdClient {
16
- constructor(verbose = false) {
17
- this.available = null;
18
- this.log = verbose ? (msg) => console.error(`[jscpd] ${msg}`) : () => { };
19
- }
20
- /**
21
- * Check if jscpd is available, auto-install if not
22
- */
23
- async ensureAvailable() {
24
- // Fast path: already checked
25
- if (this.available !== null)
26
- return this.available;
27
- // Check if available in PATH
28
- const result = safeSpawn("jscpd", ["--version"], {
29
- timeout: 5000,
30
- });
31
- this.available = !result.error && result.status === 0;
32
- if (this.available) {
33
- return true;
34
- }
35
- // Auto-install via pi-lens installer
36
- const { ensureTool } = await import("./installer/index.js");
37
- const installedPath = await ensureTool("jscpd");
38
- if (installedPath) {
39
- this.available = true;
40
- return true;
41
- }
42
- return false;
43
- }
44
- /**
45
- * Check if jscpd is available (legacy sync method)
46
- * Prefer ensureAvailable() for auto-install behavior
47
- */
48
- isAvailable() {
49
- if (this.available !== null)
50
- return this.available;
51
- const result = safeSpawn("npx", ["jscpd", "--version"], {
52
- timeout: 5000,
53
- });
54
- this.available = !result.error && result.status === 0;
55
- return this.available;
56
- }
57
- /**
58
- * Scan a directory for duplicate code blocks.
59
- * Uses a temp output dir to capture JSON report.
60
- * @param isTsProject - If true, excludes .js files (they're compiled artifacts in TS projects)
61
- */
62
- scan(cwd, minLines = 5, minTokens = 50, isTsProject = false) {
63
- // Return early for non-existent or empty directories
64
- if (!fs.existsSync(cwd)) {
65
- return {
66
- success: false,
67
- clones: [],
68
- duplicatedLines: 0,
69
- totalLines: 0,
70
- percentage: 0,
71
- };
72
- }
73
- const entries = fs.readdirSync(cwd);
74
- const hasSourceFiles = entries.some((e) => /\.(ts|tsx|js|jsx)$/.test(e) && !e.endsWith(".d.ts"));
75
- if (!hasSourceFiles) {
76
- return {
77
- success: true,
78
- clones: [],
79
- duplicatedLines: 0,
80
- totalLines: 0,
81
- percentage: 0,
82
- };
83
- }
84
- if (!this.isAvailable()) {
85
- return {
86
- success: false,
87
- clones: [],
88
- duplicatedLines: 0,
89
- totalLines: 0,
90
- percentage: 0,
91
- };
92
- }
93
- const outDir = path.join(os.tmpdir(), `pi-lens-jscpd-${Date.now()}`);
94
- fs.mkdirSync(outDir, { recursive: true });
95
- // Build ignore pattern - exclude .js in TS projects (compiled artifacts)
96
- const baseIgnores = "**/node_modules/**,**/dist/**,**/build/**,**/.git/**,**/.pi-lens/**,**/*.md,**/*.txt,**/*.json,**/*.yaml,**/*.yml,**/*.toml,**/*.lock,**/*.test.*,**/*.spec.*,**/*.poc.test.*,**/__tests__/**,**/tests/**";
97
- const ignorePattern = isTsProject
98
- ? `${baseIgnores},**/*.js,**/*.jsx`
99
- : baseIgnores;
100
- try {
101
- safeSpawn("npx", [
102
- "jscpd",
103
- ".",
104
- "--min-lines",
105
- String(minLines),
106
- "--min-tokens",
107
- String(minTokens),
108
- "--reporters",
109
- "json",
110
- "--output",
111
- outDir,
112
- "--ignore",
113
- ignorePattern,
114
- ], {
115
- timeout: 30000,
116
- cwd,
117
- });
118
- const reportPath = path.join(outDir, "jscpd-report.json");
119
- if (!fs.existsSync(reportPath)) {
120
- return {
121
- success: true,
122
- clones: [],
123
- duplicatedLines: 0,
124
- totalLines: 0,
125
- percentage: 0,
126
- };
127
- }
128
- return this.parseReport(reportPath);
129
- }
130
- catch (err) {
131
- this.log(`Scan error: ${err.message}`);
132
- return {
133
- success: false,
134
- clones: [],
135
- duplicatedLines: 0,
136
- totalLines: 0,
137
- percentage: 0,
138
- };
139
- }
140
- finally {
141
- try {
142
- fs.rmSync(outDir, { recursive: true, force: true });
143
- }
144
- catch (err) {
145
- void err;
146
- }
147
- }
148
- }
149
- formatResult(result, maxClones = 8) {
150
- if (!result.success || result.clones.length === 0)
151
- return "";
152
- const pct = result.percentage.toFixed(1);
153
- let output = `[jscpd] ${result.clones.length} duplicate block(s) — ${pct}% of codebase (${result.duplicatedLines}/${result.totalLines} lines):\n`;
154
- for (const clone of result.clones.slice(0, maxClones)) {
155
- const a = `${path.basename(clone.fileA)}:${clone.startA}`;
156
- const b = `${path.basename(clone.fileB)}:${clone.startB}`;
157
- output += ` ${clone.lines} lines — ${a} ↔ ${b}\n`;
158
- }
159
- if (result.clones.length > maxClones) {
160
- output += ` ... and ${result.clones.length - maxClones} more\n`;
161
- }
162
- return output;
163
- }
164
- // --- Internal ---
165
- parseReport(reportPath) {
166
- try {
167
- const data = JSON.parse(fs.readFileSync(reportPath, "utf-8"));
168
- // Stats live in statistics.total, not statistics.clones
169
- const total = data.statistics?.total ?? {};
170
- const duplicatedLines = total.duplicatedLines ?? 0;
171
- const totalLines = total.lines ?? 0;
172
- const percentage = total.percentage ??
173
- (totalLines > 0 ? (duplicatedLines / totalLines) * 100 : 0);
174
- const rawClones = data.duplicates ?? [];
175
- const clones = rawClones.map((c) => ({
176
- fileA: c.firstFile?.name ?? "",
177
- startA: c.firstFile?.start ?? 0,
178
- fileB: c.secondFile?.name ?? "",
179
- startB: c.secondFile?.start ?? 0,
180
- lines: c.lines ?? 0,
181
- tokens: c.tokens ?? 0,
182
- }));
183
- return { success: true, clones, duplicatedLines, totalLines, percentage };
184
- }
185
- catch (err) {
186
- void err;
187
- return {
188
- success: false,
189
- clones: [],
190
- duplicatedLines: 0,
191
- totalLines: 0,
192
- percentage: 0,
193
- };
194
- }
195
- }
196
- }
@@ -1,127 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
2
- import { JscpdClient } from "./jscpd-client.js";
3
- import { createTempFile, setupTestEnvironment } from "./test-utils.js";
4
- describe("JscpdClient", () => {
5
- let client;
6
- let tmpDir;
7
- let cleanup;
8
- beforeEach(() => {
9
- client = new JscpdClient();
10
- ({ tmpDir, cleanup } = setupTestEnvironment("pi-lens-jscpd-test-"));
11
- });
12
- afterEach(() => {
13
- cleanup();
14
- });
15
- afterEach(() => {
16
- cleanup();
17
- });
18
- describe("isAvailable", () => {
19
- it("should check jscpd availability", () => {
20
- const available = client.isAvailable();
21
- expect(typeof available).toBe("boolean");
22
- });
23
- });
24
- describe("scan", () => {
25
- it("should return success=false when not available", () => {
26
- // Create a mock that returns false
27
- const mockClient = new JscpdClient();
28
- if (mockClient.isAvailable())
29
- return; // Skip if available
30
- const result = mockClient.scan(tmpDir);
31
- expect(result.success).toBe(false);
32
- expect(result.clones).toEqual([]);
33
- });
34
- it("should detect duplicate code blocks", { timeout: 15000 }, () => {
35
- if (!client.isAvailable())
36
- return;
37
- // Create identical code blocks in different files
38
- const duplicateCode = `
39
- function processData(data: number[]): number {
40
- let sum = 0;
41
- for (let i = 0; i < data.length; i++) {
42
- sum += data[i];
43
- }
44
- return sum;
45
- }
46
- `;
47
- createTempFile(tmpDir, "file1.ts", duplicateCode);
48
- createTempFile(tmpDir, "file2.ts", duplicateCode);
49
- const result = client.scan(tmpDir, 3, 20); // Lower thresholds for test
50
- expect(result.success).toBe(true);
51
- // May or may not detect clones depending on jscpd behavior
52
- });
53
- });
54
- describe("formatResult", () => {
55
- it("should return empty string for no success", () => {
56
- const result = {
57
- success: false,
58
- clones: [],
59
- duplicatedLines: 0,
60
- totalLines: 100,
61
- percentage: 0,
62
- };
63
- expect(client.formatResult(result)).toBe("");
64
- });
65
- it("should return empty string for no clones", () => {
66
- const result = {
67
- success: true,
68
- clones: [],
69
- duplicatedLines: 0,
70
- totalLines: 100,
71
- percentage: 0,
72
- };
73
- expect(client.formatResult(result)).toBe("");
74
- });
75
- it("should format clones for display", () => {
76
- const result = {
77
- success: true,
78
- clones: [
79
- {
80
- fileA: "src/file1.ts",
81
- startA: 10,
82
- fileB: "src/file2.ts",
83
- startB: 20,
84
- lines: 15,
85
- tokens: 50,
86
- },
87
- {
88
- fileA: "src/file3.ts",
89
- startA: 5,
90
- fileB: "src/file4.ts",
91
- startB: 12,
92
- lines: 8,
93
- tokens: 30,
94
- },
95
- ],
96
- duplicatedLines: 23,
97
- totalLines: 500,
98
- percentage: 4.6,
99
- };
100
- const formatted = client.formatResult(result);
101
- expect(formatted).toContain("jscpd");
102
- expect(formatted).toContain("2 duplicate block(s)");
103
- expect(formatted).toContain("4.6%");
104
- expect(formatted).toContain("15 lines");
105
- });
106
- it("should truncate long clone lists", () => {
107
- const clones = Array.from({ length: 10 }, (_, i) => ({
108
- fileA: `file${i}a.ts`,
109
- startA: 1,
110
- fileB: `file${i}b.ts`,
111
- startB: 1,
112
- lines: 5,
113
- tokens: 20,
114
- }));
115
- const result = {
116
- success: true,
117
- clones,
118
- duplicatedLines: 50,
119
- totalLines: 1000,
120
- percentage: 5,
121
- };
122
- const formatted = client.formatResult(result, 8);
123
- expect(formatted).toContain("...");
124
- expect(formatted).toContain("2 more");
125
- });
126
- });
127
- });