loadwise 0.6.2 → 0.8.0

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 (278) hide show
  1. package/README.md +175 -115
  2. package/dist/bin/loadwise.js +132 -67
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/frontend-detect.js +6 -5
  10. package/dist/lib/accessibility/jsx-elements.js +13 -3
  11. package/dist/lib/accessibility/markup-files.js +7 -2
  12. package/dist/lib/accessibility/rule-ids.js +3 -0
  13. package/dist/lib/accessibility/rules.js +128 -41
  14. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  15. package/dist/lib/accessibility/template-attributes.js +5 -3
  16. package/dist/lib/accessibility/template-elements.js +25 -6
  17. package/dist/lib/accessibility/template-file.js +40 -25
  18. package/dist/lib/accessibility/usage.js +10 -2
  19. package/dist/lib/editor/accessibility-examples.js +6 -1
  20. package/dist/lib/editor/actions.js +46 -7
  21. package/dist/lib/editor/apply-fix.js +69 -4
  22. package/dist/lib/editor/configured-setup.js +63 -0
  23. package/dist/lib/editor/diagnostics.js +206 -17
  24. package/dist/lib/editor/dismissals.js +85 -26
  25. package/dist/lib/editor/editor-document.js +5 -2
  26. package/dist/lib/editor/editor-launcher.js +170 -0
  27. package/dist/lib/editor/fix-edits.js +19 -0
  28. package/dist/lib/editor/jetbrains-setup.js +53 -0
  29. package/dist/lib/editor/language-server.js +80 -24
  30. package/dist/lib/editor/managed-config.js +37 -0
  31. package/dist/lib/editor/native-setup.js +86 -0
  32. package/dist/lib/editor/perf-watch.js +8 -6
  33. package/dist/lib/editor/release-vsix.js +61 -0
  34. package/dist/lib/editor/reliability-examples.js +15 -0
  35. package/dist/lib/editor/scan-session.js +29 -8
  36. package/dist/lib/editor/server-commands.js +38 -9
  37. package/dist/lib/editor/setup-server.js +87 -0
  38. package/dist/lib/editor/setup-vim.js +63 -0
  39. package/dist/lib/editor/setup.js +131 -0
  40. package/dist/lib/editor/stdio-setup.js +6 -0
  41. package/dist/lib/editor/workspace-files.js +61 -7
  42. package/dist/lib/editor/workspace-paths.js +41 -1
  43. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  44. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  45. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  46. package/dist/lib/maintainability/cli/inputs.js +12 -3
  47. package/dist/lib/maintainability/cli.js +18 -5
  48. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  49. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  50. package/dist/lib/maintainability/examples.js +4 -0
  51. package/dist/lib/maintainability/quality/functions.js +9 -6
  52. package/dist/lib/maintainability/quality/limits.js +19 -0
  53. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  54. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  55. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  56. package/dist/lib/maintainability/rule-ids.js +3 -0
  57. package/dist/lib/maintainability/scan-changed.js +4 -1
  58. package/dist/lib/maintainability/scan-worker.js +6 -2
  59. package/dist/lib/maintainability/scan.js +21 -8
  60. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  61. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  62. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  63. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  64. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  65. package/dist/lib/performance/analysis/source-options.js +7 -6
  66. package/dist/lib/performance/analyze.js +16 -3
  67. package/dist/lib/performance/cli/changed-lines.js +8 -1
  68. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  69. package/dist/lib/performance/cli/cli-output.js +4 -0
  70. package/dist/lib/performance/cli/cli-scan.js +21 -2
  71. package/dist/lib/performance/cli.js +16 -7
  72. package/dist/lib/performance/collections/memory-growth.js +55 -12
  73. package/dist/lib/performance/contracts/openapi.js +13 -4
  74. package/dist/lib/performance/datastores/pg-integrity.js +68 -22
  75. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  76. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  77. package/dist/lib/performance/datastores/pooling.js +62 -3
  78. package/dist/lib/performance/datastores/redis.js +94 -18
  79. package/dist/lib/performance/datastores/session-store.js +2 -1
  80. package/dist/lib/performance/db/checks.js +19 -8
  81. package/dist/lib/performance/db/gateway.js +3 -1
  82. package/dist/lib/performance/db/plan-estimates.js +4 -4
  83. package/dist/lib/performance/engine/native-syntax.js +3 -0
  84. package/dist/lib/performance/engine/native.js +11 -7
  85. package/dist/lib/performance/evidence/plans.js +7 -5
  86. package/dist/lib/performance/evidence/traces.js +21 -1
  87. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  88. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  89. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  90. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  91. package/dist/lib/performance/frontend/frontend-perf.js +149 -74
  92. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  93. package/dist/lib/performance/migrations/extract-code.js +13 -5
  94. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  95. package/dist/lib/performance/migrations/operations.js +56 -13
  96. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  97. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  98. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  99. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  100. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  101. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  102. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  103. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  104. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  105. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  106. package/dist/lib/performance/polyglot.js +111 -14
  107. package/dist/lib/performance/projects.js +3 -3
  108. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  109. package/dist/lib/performance/request/backend-mastery.js +151 -42
  110. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  111. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  112. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  113. package/dist/lib/performance/request/mongoose-lean.js +298 -46
  114. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  115. package/dist/lib/performance/request/phase5-ast.js +6 -7
  116. package/dist/lib/performance/request/phase5-rules.js +204 -23
  117. package/dist/lib/performance/request/request-handlers.js +120 -23
  118. package/dist/lib/performance/request/sql-select-star.js +150 -0
  119. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  120. package/dist/lib/performance/request/upload-limits.js +5 -1
  121. package/dist/lib/performance/site-fix.js +4 -4
  122. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  123. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  124. package/dist/lib/performance/site-fixes/collections.js +1 -2
  125. package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
  126. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  127. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  128. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  129. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  130. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  131. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  132. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  133. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  134. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  135. package/dist/lib/reliability/boundary-access.js +114 -57
  136. package/dist/lib/reliability/react-bugs.js +29 -7
  137. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  138. package/dist/lib/reliability/resource-leaks.js +209 -195
  139. package/dist/lib/reliability/rule-ids.js +10 -1
  140. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  141. package/dist/lib/reliability/swallowed-errors.js +107 -21
  142. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  143. package/dist/lib/reliability/usage.js +16 -5
  144. package/dist/lib/reliability/walk.js +3 -2
  145. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  146. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  147. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  148. package/dist/lib/security/auth-crypto/shared.js +3 -1
  149. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  150. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  151. package/dist/lib/security/cli.js +21 -6
  152. package/dist/lib/security/cookie-credentials.js +115 -0
  153. package/dist/lib/security/cookie-csrf.js +241 -0
  154. package/dist/lib/security/deps/advisory.js +50 -109
  155. package/dist/lib/security/deps/cli.js +1 -1
  156. package/dist/lib/security/deps/cvss-score.js +14 -0
  157. package/dist/lib/security/deps/fixed-version.js +97 -0
  158. package/dist/lib/security/deps/lockfiles.js +135 -74
  159. package/dist/lib/security/deps/osv.js +11 -3
  160. package/dist/lib/security/deps/scan.js +47 -20
  161. package/dist/lib/security/deps/yarn-lock.js +158 -0
  162. package/dist/lib/security/examples/injection.cjs +4 -0
  163. package/dist/lib/security/exposure/cookies.js +17 -2
  164. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  165. package/dist/lib/security/exposure/frontend-security.js +21 -14
  166. package/dist/lib/security/exposure/jsx-url.js +18 -33
  167. package/dist/lib/security/exposure/logging.js +49 -10
  168. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  169. package/dist/lib/security/exposure/react-html.js +26 -0
  170. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  171. package/dist/lib/security/files/compose.js +126 -1
  172. package/dist/lib/security/files/dockerfile.js +62 -4
  173. package/dist/lib/security/files/index.js +1 -1
  174. package/dist/lib/security/injection/command.js +46 -18
  175. package/dist/lib/security/injection/index.js +2 -0
  176. package/dist/lib/security/injection/ldap.js +86 -0
  177. package/dist/lib/security/injection/nosql.js +28 -4
  178. package/dist/lib/security/injection/redos.js +1 -1
  179. package/dist/lib/security/injection/rule-ids.js +1 -0
  180. package/dist/lib/security/injection/shared.js +5 -1
  181. package/dist/lib/security/injection/sql.js +28 -13
  182. package/dist/lib/security/lexical-declaration.js +113 -0
  183. package/dist/lib/security/pg-dynamic-query.js +28 -1
  184. package/dist/lib/security/pg-identifier-guards.js +107 -3
  185. package/dist/lib/security/phase5-rules.js +26 -135
  186. package/dist/lib/security/polyglot.js +2 -2
  187. package/dist/lib/security/redirect-settings.js +98 -0
  188. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  189. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  190. package/dist/lib/security/request-forgery/shared.js +1 -7
  191. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  192. package/dist/lib/security/rule-descriptions.js +5 -1
  193. package/dist/lib/security/rule-ids.js +7 -0
  194. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  195. package/dist/lib/security/site-fixes/exposure.js +21 -3
  196. package/dist/lib/security/site-fixes/files.js +11 -13
  197. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  198. package/dist/lib/security/site-fixes/injection.js +17 -4
  199. package/dist/lib/security/site-fixes/jwt.js +1 -20
  200. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  201. package/dist/lib/security/taint/binding-inputs.js +236 -0
  202. package/dist/lib/security/taint/filename-guard.js +45 -45
  203. package/dist/lib/security/taint/guards.js +14 -8
  204. package/dist/lib/security/taint/index.js +126 -154
  205. package/dist/lib/security/taint/propagate.js +43 -9
  206. package/dist/lib/security/taint/record-writes.js +161 -0
  207. package/dist/lib/security/taint/resolution-cache.js +13 -7
  208. package/dist/lib/security/taint/sanitizers.js +89 -5
  209. package/dist/lib/security/taint/trace-nodes.js +61 -0
  210. package/dist/lib/security/taint/validators.js +89 -9
  211. package/dist/lib/shared/agent/agent-init.js +28 -5
  212. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  213. package/dist/lib/shared/agent/agent-session.js +6 -1
  214. package/dist/lib/shared/agent/agent-verify.js +58 -11
  215. package/dist/lib/shared/agent/git-hook.js +17 -6
  216. package/dist/lib/shared/agent/review-delivery.js +1 -1
  217. package/dist/lib/shared/agent/review-mcp.js +8 -2
  218. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  219. package/dist/lib/shared/analysis/scan-cache.js +99 -14
  220. package/dist/lib/shared/check.js +172 -20
  221. package/dist/lib/shared/cli-dispatch.js +17 -0
  222. package/dist/lib/shared/config.js +27 -10
  223. package/dist/lib/shared/explain.js +1 -1
  224. package/dist/lib/shared/fix/fix-convergence.js +19 -31
  225. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  226. package/dist/lib/shared/fix/fix-imports.js +4 -162
  227. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  228. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  229. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  230. package/dist/lib/shared/fix/fix-presentation.js +9 -6
  231. package/dist/lib/shared/fix/fix-safety.js +32 -1
  232. package/dist/lib/shared/fix/fix-scope.js +82 -0
  233. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  234. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  235. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  236. package/dist/lib/shared/fix/project-file-access.js +17 -26
  237. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  238. package/dist/lib/shared/fix.js +241 -104
  239. package/dist/lib/shared/formats/finding-location.js +4 -1
  240. package/dist/lib/shared/formats/github.js +3 -3
  241. package/dist/lib/shared/formats/sarif.js +9 -3
  242. package/dist/lib/shared/report-fp.js +97 -0
  243. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  244. package/dist/lib/shared/reporting/baseline.js +7 -5
  245. package/dist/lib/shared/reporting/check-text.js +50 -0
  246. package/dist/lib/shared/reporting/pillars.js +54 -19
  247. package/dist/lib/shared/reporting/source-report.js +3 -0
  248. package/dist/lib/shared/system/atomic-write.js +5 -2
  249. package/dist/lib/shared/system/glob.js +34 -8
  250. package/dist/lib/shared/system/sentry.js +222 -0
  251. package/dist/lib/shared/system/shell-argument.js +5 -1
  252. package/dist/lib/shared/system/terminal-safe.js +3 -2
  253. package/dist/lib/shared/system/terminal-style.js +131 -0
  254. package/dist/lib/shared/workspaces.js +15 -3
  255. package/docs/assets/cli-workflow.gif +0 -0
  256. package/integrations/sublime/plugin.py +22 -0
  257. package/integrations/zed/Cargo.lock +845 -0
  258. package/integrations/zed/Cargo.toml +11 -0
  259. package/integrations/zed/extension.toml +11 -0
  260. package/integrations/zed/src/lib.rs +25 -0
  261. package/package.json +15 -3
  262. package/plugin/.claude-plugin/plugin.json +1 -1
  263. package/plugin/commands/loadwise.md +11 -6
  264. package/plugin/hooks/check-edited-file.mjs +27 -5
  265. package/polyglot/performance/rules/csharp.yml +34 -5
  266. package/polyglot/performance/rules/java.yml +24 -1
  267. package/polyglot/performance/rules/python.yml +74 -2
  268. package/polyglot/performance/sgconfig.yml +1 -0
  269. package/polyglot/reliability/rules/csharp.yml +12 -6
  270. package/polyglot/reliability/rules/go.yml +86 -6
  271. package/polyglot/reliability/rules/java.yml +22 -1
  272. package/polyglot/reliability/sgconfig.yml +1 -0
  273. package/polyglot/security/rules/go.yml +100 -22
  274. package/polyglot/security/rules/python.yml +74 -6
  275. package/polyglot/security/rules/rust.yml +65 -0
  276. package/polyglot/security/sgconfig.yml +1 -0
  277. package/schema/loadwise.config.schema.json +556 -76
  278. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -0,0 +1,74 @@
1
+ // `loadwise agent prompt`: prints a concise, tool-agnostic prompt you can paste into any AI coding tool
2
+ // (Claude Code, Cursor, Codex, Copilot, Windsurf, Gemini CLI, etc.) to get high-signal Loadwise reviews.
3
+ import { parseArgs } from 'node:util';
4
+ const promptUsage = 'Usage: loadwise agent prompt [--pr] [--changed-since git-ref] [--checkers perf,rel] [--report-fp]';
5
+ const checkersRe = /^[a-z0-9]+(,[a-z0-9]+)*$/i;
6
+ const changedSinceRe = /^[\w./~^@{}+-]+$/;
7
+ /** Builds the copy-pasteable AI review prompt grounded in Loadwise's highest-signal workflow. */
8
+ function buildAgentPrompt(options = {}) {
9
+ const checkers = (options.checkers ?? 'perf,rel').trim() || 'perf,rel';
10
+ if (!checkersRe.test(checkers))
11
+ throw new Error(promptUsage);
12
+ const changedSince = options.changedSince ?? (options.pr ? 'origin/main' : undefined);
13
+ if (changedSince !== undefined && !changedSinceRe.test(changedSince))
14
+ throw new Error(promptUsage);
15
+ const scanCmd = [
16
+ 'npx loadwise check',
17
+ `--only ${checkers}`,
18
+ ...(changedSince ? [`--changed-since ${changedSince}`] : []),
19
+ '--min-impact high',
20
+ '--json',
21
+ ].join(' ');
22
+ const lines = [
23
+ 'Review this repository with Loadwise using the following workflow:',
24
+ '',
25
+ '1. Run a read-only JSON scan first (do not edit files yet; if you do not have shell access, ask the user to run this command and paste the output):',
26
+ ` ${scanCmd}`,
27
+ ' If database migrations changed, also run: npx loadwise rel migrations --json',
28
+ ' Check stderr for any skipped checks (for example, missing node_modules or type definitions).',
29
+ '',
30
+ '2. Prioritize high-signal runtime bugs that tsc and ESLint miss:',
31
+ ' - Transaction & pool leaks: pg-transaction-on-pool, prisma-transaction-client-escape, typeorm-transaction-client-escape',
32
+ ' - Database & N+1 work: prisma-query-in-loop, orm-query-in-loop, index-missing-filter, index-missing-foreign-key',
33
+ ' - Quadratic lookups & async resilience: array-repeated-find, http-call-without-timeout, floating-promise',
34
+ '',
35
+ '3. Verify every finding against callers, ordering, duplicate-key semantics, and tests before editing:',
36
+ ' - For check-only requests, report recommended fixes vs. false positives and wait for the user to choose before editing.',
37
+ ' - Never run blind bulk fixes (`--fix --all`). Apply only verified IDs with per-ID `--fix --only <id>` (or write a manual fix if that preserves behavior better).',
38
+ ' - Use judgment on context-sensitive rules: leave intentional small-object merges (`reduce-copy-accumulator` on 2-4 keys), intentional per-row JSON formatting (`json-stringify-in-loop`), and static/build-time `Promise.all` (`unbounded-promise-all`) alone unless they are on a real hot path.',
39
+ '',
40
+ '4. Verify after any edit:',
41
+ ' - Run the project tests and typecheck, then re-run the same scoped Loadwise scan to confirm the targeted findings cleared with no regressions.',
42
+ ];
43
+ if (options.reportFp) {
44
+ lines.push('', '5. Optional false-positive reporting (opt-in only, privacy-safe):', ' - If you hit a clear false positive worth reporting upstream, ask the user for confirmation first.', ' - Only if approved, generate an anonymized GitHub issue link (never include proprietary code, file paths, or project names):', ' npx loadwise report-fp --rule <rule-id> --note "<generic pattern description>"');
45
+ }
46
+ return lines.join('\n');
47
+ }
48
+ function runAgentPrompt(args) {
49
+ const { values, positionals } = parseArgs({
50
+ args,
51
+ allowPositionals: true,
52
+ options: {
53
+ help: { type: 'boolean', short: 'h' },
54
+ pr: { type: 'boolean' },
55
+ 'changed-since': { type: 'string' },
56
+ checkers: { type: 'string' },
57
+ 'report-fp': { type: 'boolean' },
58
+ },
59
+ });
60
+ if (values.help) {
61
+ console.log(promptUsage);
62
+ return 0;
63
+ }
64
+ if (positionals.length > 0)
65
+ throw new Error(promptUsage);
66
+ console.log(buildAgentPrompt({
67
+ pr: values.pr,
68
+ changedSince: values['changed-since'],
69
+ checkers: values.checkers,
70
+ reportFp: values['report-fp'],
71
+ }));
72
+ return 0;
73
+ }
74
+ export { runAgentPrompt };
@@ -7,7 +7,12 @@ function isAgentSession(env = process.env) {
7
7
  return true;
8
8
  return Boolean((env.CODEX_TOOL_CALL_ID?.trim() && env.CODEX_THREAD_ID?.trim()) ||
9
9
  env.CLAUDE_CODE_CHILD_SESSION === '1' ||
10
+ env.CLAUDECODE === '1' ||
10
11
  env.CURSOR_AGENT === '1' ||
12
+ env.WINDSURF_AGENT === '1' ||
13
+ env.CLINE_ACTIVE === '1' ||
14
+ env.ROO_CODE === '1' ||
15
+ env.AIDER === '1' ||
11
16
  env.GEMINI_CLI === '1' ||
12
17
  env.COPILOT_AGENT === '1');
13
18
  }
@@ -15,7 +20,7 @@ function promptReview(args) {
15
20
  if (!isAgentSession())
16
21
  return;
17
22
  const [command = '', subcommand = ''] = args;
18
- if (['agent', 'explain', 'lsp', '--version', '-v'].includes(command))
23
+ if (['agent', 'explain', 'report-fp', 'lsp', 'editor', '--version', '-v'].includes(command))
19
24
  return;
20
25
  if (['perf', 'maint'].includes(command) && subcommand === 'agent')
21
26
  return;
@@ -72,6 +72,9 @@ function recordFixRun(run, source, state) {
72
72
  const fields = isRecord(run) ? run : {};
73
73
  for (const field of ['applied', 'manual', 'pendingReview'])
74
74
  recordFindings(fields[field], source + '.' + field, state);
75
+ // History receipts predate notApplied and never store it.
76
+ if ('notApplied' in fields)
77
+ recordFindings(fields.notApplied, source + '.notApplied', state);
75
78
  if ('alreadyApplied' in fields)
76
79
  recordFindings(fields.alreadyApplied, source + '.alreadyApplied', state);
77
80
  if ('failed' in fields) {
@@ -113,17 +116,62 @@ function recordStandaloneScan(report, source, state, selectedChecker) {
113
116
  if (!checker || findings.some((finding) => checkerNamed(declaredChecker(finding)) === undefined))
114
117
  throw new Error(source + ' needs --checker perf|rel|maint|sec|a11y for an unlabelled standalone scan.');
115
118
  }
119
+ if (hasSkippedFiles(report, source))
120
+ state.unavailable.push({ source, checker });
116
121
  recordFindings(findings, source + '.findings', state, checker);
117
122
  }
123
+ function hasSkippedFiles(report, source) {
124
+ const skipped = report.skippedFiles;
125
+ if (skipped === undefined)
126
+ return false;
127
+ if (typeof skipped === 'number' && Number.isSafeInteger(skipped) && skipped >= 0)
128
+ return skipped > 0;
129
+ if (Array.isArray(skipped))
130
+ return skipped.length > 0;
131
+ throw new Error(source + '.skippedFiles must be a nonnegative count or an array.');
132
+ }
133
+ function recordCombinedScan(report, source, state) {
134
+ const coverage = report._coverage === undefined ? {} : report._coverage;
135
+ if (!isRecord(coverage) || Object.keys(coverage).some((name) => !checkerNamed(name) || !Object.hasOwn(report, name)))
136
+ throw new Error(source + ' declares coverage for an unknown or absent checker.');
137
+ for (const [name, result] of Object.entries(report)) {
138
+ if (name === '_coverage')
139
+ continue;
140
+ const checker = checkerNamed(name);
141
+ if (!checker)
142
+ throw new Error(source + ' has an unrecognized checker: ' + name);
143
+ const detail = coverage[name];
144
+ if (detail !== undefined) {
145
+ if (!isRecord(detail))
146
+ throw new Error(source + ' has invalid coverage for ' + name);
147
+ if (detail.status === 'not-applicable' &&
148
+ detail.reason === 'no-frontend-sources' &&
149
+ !('exitCode' in detail) &&
150
+ checker === 'a11y' &&
151
+ result === null) {
152
+ state.notApplicable.push({ source, checker, reason: detail.reason });
153
+ continue;
154
+ }
155
+ if (detail.status !== 'incomplete' || !Number.isInteger(detail.exitCode) || Number(detail.exitCode) < 2)
156
+ throw new Error(source + ' has invalid coverage for ' + name);
157
+ }
158
+ if (result === null || detail !== undefined || (isRecord(result) && hasSkippedFiles(result, source + '.' + name)))
159
+ state.unavailable.push({ source, checker });
160
+ if (result !== null)
161
+ recordFindings(isRecord(result) ? result.findings : undefined, source + '.' + name + '.findings', state, checker);
162
+ }
163
+ }
118
164
  function recordReport(report, source, state, selectedChecker) {
119
165
  if (!isRecord(report))
120
166
  throw new Error(source + ' must be a report object.');
121
167
  const isHistory = 'runs' in report || 'enabled' in report;
122
- const isFix = 'applied' in report || 'manual' in report || 'pendingReview' in report;
168
+ const isFix = 'applied' in report || 'manual' in report || 'pendingReview' in report || 'notApplied' in report;
123
169
  const isScan = Object.keys(report).some((name) => checkerNames.has(name));
124
170
  const isStandalone = 'findings' in report;
125
171
  if ([isHistory, isFix, isScan, isStandalone].filter(Boolean).length !== 1)
126
172
  throw new Error(source + ' must contain one scan, fix or history report.');
173
+ if ('_coverage' in report && !isScan)
174
+ throw new Error(source + ' declares coverage outside a combined scan.');
127
175
  if (isStandalone) {
128
176
  recordStandaloneScan(report, source, state, selectedChecker);
129
177
  return;
@@ -136,15 +184,7 @@ function recordReport(report, source, state, selectedChecker) {
136
184
  recordFixRun(report, source, state);
137
185
  return;
138
186
  }
139
- for (const [name, result] of Object.entries(report)) {
140
- const checker = checkerNamed(name);
141
- if (!checker)
142
- throw new Error(source + ' has an unrecognized checker: ' + name);
143
- if (result === null)
144
- state.unavailable.push({ source, checker });
145
- else
146
- recordFindings(isRecord(result) ? result.findings : undefined, source + '.' + name + '.findings', state, checker);
147
- }
187
+ recordCombinedScan(report, source, state);
148
188
  }
149
189
  function hasEvidence(value) {
150
190
  return typeof value === 'string' && /[\p{L}\p{N}]/u.test(value) && !emptyEvidence.test(value.trim());
@@ -193,6 +233,7 @@ function reviewCoverage(state, outcomes) {
193
233
  unexpected,
194
234
  invalid,
195
235
  unavailable: state.unavailable,
236
+ ...(state.notApplicable.length > 0 && { notApplicable: state.notApplicable }),
196
237
  failedApplications: state.failedApplications,
197
238
  history: state.history,
198
239
  };
@@ -225,7 +266,13 @@ function runAgentVerify(args) {
225
266
  throw new Error('Pass one checker name to --checker: perf, rel, maint, sec or a11y.');
226
267
  const outcomesDocument = readJson(values.outcomes);
227
268
  const outcomes = requireArray(isRecord(outcomesDocument) ? outcomesDocument.outcomes : undefined, values.outcomes + '.outcomes');
228
- const state = { expected: new Map(), unavailable: [], failedApplications: [], history: [] };
269
+ const state = {
270
+ expected: new Map(),
271
+ notApplicable: [],
272
+ unavailable: [],
273
+ failedApplications: [],
274
+ history: [],
275
+ };
229
276
  for (const report of positionals)
230
277
  recordReport(readJson(report), report, state, selectedChecker);
231
278
  const result = reviewCoverage(state, outcomes);
@@ -27,6 +27,9 @@ function gitOutput(directory, args) {
27
27
  function shellDoubleQuote(text) {
28
28
  return '"' + text.replaceAll(/[\\"$`]/g, '\\$&') + '"';
29
29
  }
30
+ function shellDirectoryTarget(projectPath) {
31
+ return projectPath.startsWith('-') ? './' + projectPath : projectPath;
32
+ }
30
33
  // The hook runs under sh, which needs forward slashes even on Windows.
31
34
  function projectPathFromGitRoot(gitRoot, projectRoot) {
32
35
  return path.relative(gitRoot, projectRoot).split(path.sep).join('/') || '.';
@@ -34,10 +37,17 @@ function projectPathFromGitRoot(gitRoot, projectRoot) {
34
37
  // The block never calls `exit 0`: other tools' blocks may follow it in the same hook.
35
38
  function hookBlock(mode, projectPath) {
36
39
  const onFindings = mode === 'block' ? '|| exit 1' : '|| true';
40
+ const rootBinary = projectPath === '.'
41
+ ? undefined
42
+ : `${projectPath
43
+ .split('/')
44
+ .map(() => '..')
45
+ .join('/')}/${binary}`;
37
46
  return [
38
47
  blockStart,
39
- `( cd ${shellDoubleQuote(projectPath)} && if [ -x ${binary} ]; then`,
48
+ `( cd ${shellDoubleQuote(shellDirectoryTarget(projectPath))} && if [ -x ${binary} ]; then`,
40
49
  ` ${checkCommand} ${onFindings}`,
50
+ ...(rootBinary ? [` elif [ -x ${rootBinary} ]; then`, ` ${rootBinary} check --staged ${onFindings}`] : []),
41
51
  ` else echo "${toolName}: not installed here, skipped"; fi )` + (mode === 'block' ? ' || exit 1' : ''),
42
52
  blockEnd,
43
53
  ].join('\n');
@@ -87,7 +97,8 @@ function lefthookInstructions(configName, mode, projectPath) {
87
97
  return [
88
98
  `${configName} found, so it was not edited. Add this under pre-commit.commands:`,
89
99
  ` ${toolName}:`,
90
- ` run: cd ${shellDoubleQuote(projectPath)} && ${checkCommand}` + (mode === 'block' ? '' : ' || true'),
100
+ ` run: cd ${shellDoubleQuote(shellDirectoryTarget(projectPath))} && ${checkCommand}` +
101
+ (mode === 'block' ? '' : ' || true'),
91
102
  ].join('\n');
92
103
  }
93
104
  function readIfPresent(filename) {
@@ -125,15 +136,15 @@ function isHookMode(mode) {
125
136
  function installHook(projectRoot, mode) {
126
137
  if (!isHookMode(mode))
127
138
  throw new Error('--hook must be block, warn or off.');
128
- const gitRoot = path.resolve(gitOutput(projectRoot, ['rev-parse', '--show-toplevel']));
129
- const projectPath = projectPathFromGitRoot(gitRoot, projectRoot);
139
+ const resolvedProject = realTarget(path.resolve(projectRoot));
140
+ const gitRoot = realTarget(gitOutput(resolvedProject, ['rev-parse', '--show-toplevel']));
141
+ const projectPath = projectPathFromGitRoot(gitRoot, resolvedProject);
130
142
  const lefthookName = lefthookFiles.find((name) => fs.existsSync(path.join(gitRoot, name)));
131
143
  if (mode !== 'off' && lefthookName)
132
144
  return { message: lefthookInstructions(lefthookName, mode, projectPath) };
133
145
  const filename = hookFilename(gitRoot);
134
- const resolvedRoot = realTarget(gitRoot);
135
146
  const resolvedHook = realTarget(filename);
136
- const relHook = path.relative(resolvedRoot, resolvedHook);
147
+ const relHook = path.relative(gitRoot, resolvedHook);
137
148
  if (!relHook || relHook === '..' || relHook.startsWith('..' + path.sep) || path.isAbsolute(relHook)) {
138
149
  throw new Error(`Refusing to write git hook outside repository root: ${filename}`);
139
150
  }
@@ -3,7 +3,7 @@ import { prepareReviewRequest } from './review-request.js';
3
3
  async function saveHandoff(event) {
4
4
  try {
5
5
  const receipt = await prepareReviewRequest(event, { pending: true });
6
- console.error('Saved for this project. Run `loadwise agent pending` to list pending reports.');
6
+ console.error('Saved for this project. Run `loadwise agent pending` from the checked project directory to list pending reports.');
7
7
  return { file: receipt.file, id: path.basename(path.dirname(receipt.file)) };
8
8
  }
9
9
  catch (error) {
@@ -96,8 +96,14 @@ function reportPage(document, args, offset) {
96
96
  return toolText('Offset exceeds the report length.', true);
97
97
  if (document.length <= pageLength && args.offset === undefined)
98
98
  return toolText(document);
99
- const text = document.slice(offset, offset + pageLength);
100
- const end = offset + text.length;
99
+ let end = Math.min(offset + pageLength, document.length);
100
+ if (end < document.length && end > offset) {
101
+ const last = document.charCodeAt(end - 1);
102
+ if (last >= 0xd800 && last <= 0xdbff) {
103
+ end = end - 1 > offset ? end - 1 : Math.min(end + 1, document.length);
104
+ }
105
+ }
106
+ const text = document.slice(offset, end);
101
107
  return toolText(JSON.stringify({
102
108
  id: args.id,
103
109
  offset,
@@ -77,7 +77,7 @@ function isUnshadowedGlobal(node, name, checker) {
77
77
  return declarations.every((declaration) => declaration.getSourceFile().isDeclarationFile);
78
78
  }
79
79
  function constInitializer(identifier, checker) {
80
- const declaration = checker.getSymbolAtLocation(identifier)?.declarations?.[0];
80
+ const declaration = symbolOf(identifier, checker)?.declarations?.[0];
81
81
  if (declaration &&
82
82
  ts.isVariableDeclaration(declaration) &&
83
83
  declaration.parent.flags & ts.NodeFlags.Const &&
@@ -450,4 +450,4 @@ function isEffectivelySet(object, key, checker) {
450
450
  }
451
451
  return true;
452
452
  }
453
- export { constInitializer, effectiveProperty, forEachExecutedNode, immediateInvocation, isEffectivelySet, isUnshadowedGlobal, literalKey, neverEvaluatesRight, resolveImportedBinding, resolveRequiredModule, staticFalsy, staticMemberName, staticPropertyName, symbolOf, unwrapExpression, };
453
+ export { constInitializer, effectiveProperty, forEachExecutedNode, immediateInvocation, isEffectivelySet, isUnshadowedGlobal, literalKey, neverEvaluatesRight, resolveImportedBinding, resolveRequiredModule, staticFalsy, staticMemberName, staticNullish, staticPropertyName, symbolOf, unwrapExpression, };
@@ -4,6 +4,7 @@ import crypto from 'node:crypto';
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { spawnSync } from 'node:child_process';
7
+ import * as ts from 'typescript';
7
8
  import { writeFileAtomic } from '../system/atomic-write.js';
8
9
  import { packageManifest, packagePath, packageRoot } from '../package-root.js';
9
10
  import { defaultCacheDirectory } from '../../security/deps/osv.js';
@@ -106,6 +107,7 @@ const installMarkers = [
106
107
  ];
107
108
  // Checkers read these from disk to select sources, so their contents count even when Git ignores them.
108
109
  const projectConfigNames = ['tsconfig.json', 'jsconfig.json', 'pnpm-workspace.yaml', 'lerna.json'];
110
+ const loadwiseConfigNames = ['loadwise-baseline.json', 'loadwise.config.json'];
109
111
  const projectInputs = /(?:^|\/)(?:package|[jt]sconfig)\.json$|\.[cm]?[jt]sx?$/i;
110
112
  function addConfigDirectories(directories, directory) {
111
113
  for (let folder = directory; !directories.has(folder); folder = path.posix.dirname(folder)) {
@@ -213,7 +215,7 @@ function inputFingerprint(cwd) {
213
215
  hashIgnoredProjectConfigs(hash, topLevel, relativeCwd.split(path.sep).join('/'), names);
214
216
  const unindexedConfigs = new Set();
215
217
  for (const directory of new Set([topLevel, path.resolve(cwd)])) {
216
- for (const configName of ['loadwise-baseline.json', 'loadwise.config.json']) {
218
+ for (const configName of loadwiseConfigNames) {
217
219
  const candidate = path.join(directory, configName);
218
220
  if (fs.statSync(candidate, { throwIfNoEntry: false })?.isFile())
219
221
  unindexedConfigs.add(candidate);
@@ -230,9 +232,26 @@ function inputFingerprint(cwd) {
230
232
  return { fingerprint: hash.digest('hex'), coversWorkspaces: workspaceCoverage(topLevel, names) };
231
233
  }
232
234
  const maxHashedFileBytes = 16 * 1024 * 1024;
233
- function fileHash(absolute, existingStat) {
235
+ // Use TypeScript's resolver for JSONC, arrays of bases and package-based inheritance. The
236
+ // repository snapshot covers source files already, so resolving configs must not glob the project.
237
+ function projectFingerprint(absolute) {
238
+ const hash = crypto.createHash('sha256');
239
+ const readFile = (filename) => {
240
+ const text = ts.sys.readFile(filename);
241
+ hash.update(JSON.stringify([filename, text ?? null]));
242
+ return text;
243
+ };
244
+ const config = ts.readJsonConfigFile(absolute, readFile);
245
+ ts.parseJsonSourceFileConfigFileContent(config, { ...ts.sys, readFile, readDirectory: () => [] }, path.dirname(absolute), {}, absolute);
246
+ return hash.digest('hex');
247
+ }
248
+ function fileHash(absolute, existingStat, namedConfig = false) {
234
249
  try {
235
250
  const stat = existingStat ?? fs.lstatSync(absolute);
251
+ if ((namedConfig || /^[jt]sconfig(?:\..+)?\.json$/i.test(path.basename(absolute))) &&
252
+ (stat.isFile() || stat.isSymbolicLink())) {
253
+ return projectFingerprint(absolute);
254
+ }
236
255
  if (stat.isSymbolicLink())
237
256
  return `symlink:${sha1(fs.readlinkSync(absolute))}`;
238
257
  if (stat.isDirectory())
@@ -249,6 +268,77 @@ function fileHash(absolute, existingStat) {
249
268
  return 'missing';
250
269
  }
251
270
  }
271
+ function configFileEntry(candidate) {
272
+ let stat;
273
+ try {
274
+ stat = fs.statSync(candidate, { throwIfNoEntry: false });
275
+ }
276
+ catch {
277
+ // An inaccessible config cannot be fingerprinted, so bypass the cache.
278
+ return { unfingerprintable: true };
279
+ }
280
+ if (!stat?.isFile())
281
+ return {};
282
+ // Pass the statSync result (which follows symlinks) so symlinked configs hash target contents.
283
+ const hash = fileHash(candidate, stat);
284
+ if (!hash || hash === 'missing')
285
+ return { unfingerprintable: true };
286
+ return { entry: `${candidate}${hash}` };
287
+ }
288
+ function directoryConfigFingerprint(directory, stopAt) {
289
+ const entries = [];
290
+ let current = path.resolve(directory);
291
+ const boundary = path.resolve(stopAt);
292
+ while (true) {
293
+ for (const configName of ['loadwise-baseline.json', 'loadwise.config.json']) {
294
+ const result = configFileEntry(path.join(current, configName));
295
+ if (result.unfingerprintable)
296
+ return undefined;
297
+ if (result.entry)
298
+ entries.push(result.entry);
299
+ }
300
+ if (current === boundary)
301
+ break;
302
+ const parent = path.dirname(current);
303
+ if (parent === current)
304
+ break;
305
+ current = parent;
306
+ }
307
+ return entries.join('');
308
+ }
309
+ // Returns the fingerprint entries for one argument, or undefined when the cache must be bypassed.
310
+ function namedArgumentEntries(args, index, cwd, directory, inputs) {
311
+ const arg = args[index];
312
+ const candidate = arg.startsWith('-') && arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : arg;
313
+ if (!candidate)
314
+ return [''];
315
+ const absolute = path.resolve(cwd, candidate);
316
+ // The checker opens the named input and reads its target when it is a symlink.
317
+ let stat;
318
+ try {
319
+ stat = fs.statSync(absolute, { throwIfNoEntry: false });
320
+ }
321
+ catch {
322
+ return undefined;
323
+ }
324
+ if (stat?.isDirectory() && !inputs.coversWorkspaces(absolute))
325
+ return undefined;
326
+ if (stat?.isDirectory()) {
327
+ const fingerprint = directoryConfigFingerprint(absolute, directory);
328
+ return fingerprint === undefined ? undefined : [fingerprint];
329
+ }
330
+ const flag = candidate === arg ? args[index - 1] : arg.split('=')[0];
331
+ const namedProject = flag === '-p' || flag === '--project';
332
+ if (!stat?.isFile() && !(namedProject && stat?.isSymbolicLink()))
333
+ return [''];
334
+ const entries = [fileHash(absolute, stat, namedProject) ?? ''];
335
+ // A selected subproject may read an ignored config or baseline beside its tsconfig.
336
+ const projectDirectory = path.dirname(absolute);
337
+ if (!stat?.isFile() || projectDirectory === directory)
338
+ return entries;
339
+ const fingerprint = directoryConfigFingerprint(projectDirectory, directory);
340
+ return fingerprint === undefined ? undefined : [...entries, fingerprint];
341
+ }
252
342
  function cacheKey(args, cwd) {
253
343
  const directory = path.resolve(cwd);
254
344
  if (launchFingerprints && !launchFingerprints.has(directory)) {
@@ -263,17 +353,11 @@ function cacheKey(args, cwd) {
263
353
  .map((name) => `${name}=${process.env[name]}`);
264
354
  // A config file named in the args may live outside the repository.
265
355
  const namedFiles = [];
266
- for (const arg of args) {
267
- const candidate = arg.startsWith('-') && arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : arg;
268
- if (!candidate) {
269
- namedFiles.push('');
270
- continue;
271
- }
272
- const absolute = path.resolve(cwd, candidate);
273
- const stat = fs.lstatSync(absolute, { throwIfNoEntry: false });
274
- if (stat?.isDirectory() && !inputs.coversWorkspaces(absolute))
356
+ for (const index of args.keys()) {
357
+ const entries = namedArgumentEntries(args, index, cwd, directory, inputs);
358
+ if (!entries)
275
359
  return undefined;
276
- namedFiles.push(stat?.isFile() ? (fileHash(absolute, stat) ?? '') : '');
360
+ namedFiles.push(...entries);
277
361
  }
278
362
  const parts = [formatVersion, loadwiseFingerprint(), directory, args, namedFiles, environment, inputs.fingerprint];
279
363
  return crypto.createHash('sha256').update(JSON.stringify(parts)).digest('hex');
@@ -289,7 +373,8 @@ function isStoredRun(value) {
289
373
  'stdout' in value &&
290
374
  typeof value.stdout === 'string' &&
291
375
  'stderr' in value &&
292
- typeof value.stderr === 'string');
376
+ typeof value.stderr === 'string' &&
377
+ (!('hasAutomaticFixes' in value) || value.hasAutomaticFixes === true));
293
378
  }
294
379
  function readEntry(filename) {
295
380
  try {
@@ -309,7 +394,7 @@ function readEntry(filename) {
309
394
  function writeEntry(filename, run) {
310
395
  try {
311
396
  fs.mkdirSync(path.dirname(filename), { recursive: true, mode: 0o700 });
312
- writeFileAtomic(filename, JSON.stringify({ code: run.code, stdout: run.stdout, stderr: run.stderr }), 0o600);
397
+ writeFileAtomic(filename, JSON.stringify(run), 0o600);
313
398
  prune(path.dirname(filename));
314
399
  }
315
400
  catch {