loadwise 0.7.0 → 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 (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  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/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -0,0 +1,161 @@
1
+ // Ordering rules for the field writes to a local record (`record.name = value`): which write a read
2
+ // can see, and how a write changes the field taint of the record.
3
+ import { stripExpression as strip } from '../bindings.js';
4
+ import { isUnshadowedGlobal } from '../../shared/analysis/ast-semantics.js';
5
+ import { ts } from '../../performance/engine/compiler.js';
6
+ import { declarationOf, eitherField, partOf } from './trace-nodes.js';
7
+ import { alwaysOverwrites } from './guards.js';
8
+ // `Object.create(null)`: a record with no fields until one is written.
9
+ export function isNullRecordCall(initializer, checker) {
10
+ if (!initializer || !ts.isCallExpression(initializer) || !ts.isPropertyAccessExpression(initializer.expression))
11
+ return false;
12
+ return (initializer.expression.name.text === 'create' &&
13
+ isUnshadowedGlobal(initializer.expression.expression, 'Object', checker) &&
14
+ initializer.arguments.length === 1 &&
15
+ strip(initializer.arguments[0]).kind === ts.SyntaxKind.NullKeyword);
16
+ }
17
+ export function escapedBefore(declaration, scope, use, checker) {
18
+ function escaped(node) {
19
+ if (node.pos >= use.pos)
20
+ return;
21
+ if (ts.isIdentifier(node) &&
22
+ node !== declaration.name &&
23
+ node.text === use.text &&
24
+ declarationOf(node, checker) === declaration) {
25
+ const parent = node.parent;
26
+ if ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === node)
27
+ return;
28
+ if (ts.isBinaryExpression(parent) && parent.left === node)
29
+ return;
30
+ return true;
31
+ }
32
+ return ts.forEachChild(node, escaped);
33
+ }
34
+ return !!escaped(scope);
35
+ }
36
+ // True when `block` contains `use` with no function boundary between them: a later write in an
37
+ // enclosing block cannot reach a read in a nested block, but can reach one inside a callback.
38
+ export function enclosesWithoutCallback(block, use) {
39
+ for (let node = use.parent; node; node = node.parent) {
40
+ if (node === block)
41
+ return true;
42
+ if (ts.isFunctionLike(node))
43
+ return false;
44
+ }
45
+ return false;
46
+ }
47
+ // A hoisted `var` read before its initializer in a loop sees the previous iteration's write.
48
+ export function loopCarriedBeforeInitializer(declaration, assignment, use) {
49
+ if (declaration.pos < use.end)
50
+ return false;
51
+ for (let node = use.parent; node && !ts.isFunctionLike(node); node = node.parent) {
52
+ if (ts.isIterationStatement(node, false) && node.pos <= assignment.pos && assignment.end <= node.end)
53
+ return true;
54
+ }
55
+ return false;
56
+ }
57
+ // True when an unconditional write to the same field runs earlier in the loop body than the read,
58
+ // so every iteration's read sees that write rather than the previous iteration's loop-carried one.
59
+ export function overwrittenBeforeReadInLoop(writes, carried, declaration, use) {
60
+ const loop = ts.findAncestor(use, (node) => ts.isIterationStatement(node, false) && node.pos <= carried.assignment.pos && carried.assignment.end <= node.end);
61
+ return writes.some(({ path, assignment }) => assignment !== carried.assignment &&
62
+ path.length === carried.path.length &&
63
+ path.every((name, index) => name !== undefined && name === carried.path[index]) &&
64
+ loop !== undefined &&
65
+ loop.pos <= assignment.pos &&
66
+ assignment.end <= use.pos &&
67
+ alwaysOverwrites(assignment, declaration) &&
68
+ enclosesWithoutCallback(assignment.parent.parent, use));
69
+ }
70
+ export function updateField(previous, path, value, replace) {
71
+ const [name, ...remaining] = path;
72
+ if (name === undefined)
73
+ return value ? partOf(value) : previous;
74
+ const unknownObjectField = previous?.objectFields ? previous.unknownObjectField : previous;
75
+ const existing = previous?.objectFields?.get(name) ?? (previous?.cleanObjectFields?.has(name) ? undefined : unknownObjectField);
76
+ const updated = remaining.length ? updateField(existing, remaining, value, replace) : value;
77
+ const base = previous ?? (updated && partOf(updated));
78
+ if (!base)
79
+ return;
80
+ const fields = new Map(previous?.objectFields);
81
+ const clean = new Set(previous?.cleanObjectFields);
82
+ if (updated) {
83
+ fields.set(name, replace ? updated : eitherField(existing, updated));
84
+ clean.delete(name);
85
+ }
86
+ else if (replace) {
87
+ fields.delete(name);
88
+ clean.add(name);
89
+ }
90
+ return {
91
+ ...base,
92
+ objectFields: fields,
93
+ cleanObjectFields: clean,
94
+ unknownObjectField,
95
+ objectSteps: previous?.objectSteps ?? base.steps.length,
96
+ };
97
+ }
98
+ function propertyKey(name) {
99
+ if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name))
100
+ return name.text;
101
+ }
102
+ // The object is tainted as a whole (for sinks that take it), and each named field keeps its own
103
+ // taint, so
104
+ // `{ filename: tainted, sourcePath }` read back as `.sourcePath` is clean. A tainted spread or
105
+ // computed key taints every field.
106
+ export function objectLiteralResult(expression, next) {
107
+ const fields = new Map();
108
+ let whole;
109
+ let unknownField;
110
+ const clean = new Set();
111
+ for (const property of expression.properties) {
112
+ if (ts.isSpreadAssignment(property)) {
113
+ const spread = partOf(next(property.expression), true);
114
+ if (!spread)
115
+ continue;
116
+ if (!spread.objectFields || spread.unknownObjectField) {
117
+ fields.clear();
118
+ clean.clear();
119
+ unknownField = spread.unknownObjectField ?? spread;
120
+ }
121
+ whole ??= { ...spread, objectFields: undefined };
122
+ for (const name of spread.cleanObjectFields ?? []) {
123
+ fields.delete(name);
124
+ clean.add(name);
125
+ }
126
+ for (const [name, field] of spread.objectFields ?? []) {
127
+ fields.set(name, field);
128
+ clean.delete(name);
129
+ }
130
+ continue;
131
+ }
132
+ const value = ts.isPropertyAssignment(property)
133
+ ? property.initializer
134
+ : ts.isShorthandPropertyAssignment(property)
135
+ ? property.name
136
+ : undefined;
137
+ const result = value && partOf(next(value), true);
138
+ const name = propertyKey(property.name);
139
+ if (!result) {
140
+ // A clean later property overrides the same field of an earlier spread. A getter or method
141
+ // is not modelled, so the spread's taint for that field stays.
142
+ if (value && name !== undefined) {
143
+ fields.delete(name);
144
+ clean.add(name);
145
+ }
146
+ continue;
147
+ }
148
+ whole ??= partOf(result);
149
+ if (name === undefined)
150
+ return whole;
151
+ fields.set(name, result);
152
+ clean.delete(name);
153
+ }
154
+ return (whole && {
155
+ ...whole,
156
+ objectFields: fields,
157
+ unknownObjectField: unknownField,
158
+ cleanObjectFields: clean,
159
+ objectSteps: whole.steps.length,
160
+ });
161
+ }
@@ -30,15 +30,15 @@ function createResolutionCache(evaluate) {
30
30
  const traversal = new Map();
31
31
  let current;
32
32
  let generation = 0;
33
- const summaryFnIds = new WeakMap();
34
- let nextSummaryFnId = 1;
35
- function summaryFnId(fn) {
33
+ const nodeIds = new WeakMap();
34
+ let nextNodeId = 1;
35
+ function nodeId(fn) {
36
36
  if (!fn)
37
37
  return '';
38
- let id = summaryFnIds.get(fn);
38
+ let id = nodeIds.get(fn);
39
39
  if (id === undefined) {
40
- id = nextSummaryFnId++;
41
- summaryFnIds.set(fn, id);
40
+ id = nextNodeId++;
41
+ nodeIds.set(fn, id);
42
42
  }
43
43
  return String(id);
44
44
  }
@@ -57,7 +57,13 @@ function createResolutionCache(evaluate) {
57
57
  return true;
58
58
  }
59
59
  return (expression, state) => {
60
- const key = `${state.sinkKind}:${state.hops}:${summaryFnId(state.summary?.fn)}:${state.summary?.index ?? ''}`;
60
+ const key = [
61
+ state.sinkKind,
62
+ state.hops,
63
+ nodeId(state.summary?.fn),
64
+ state.summary?.index,
65
+ nodeId(state.defaultCall?.call),
66
+ ].join(':');
61
67
  const result = results.get(expression)?.get(key);
62
68
  if (result)
63
69
  return result.value;
@@ -1,9 +1,10 @@
1
1
  // Values that cannot carry injectable text (design section 2.4).
2
2
  import { ts } from '../../performance/engine/compiler.js';
3
+ import { importedFrom } from '../bindings.js';
3
4
  import { isBuiltinReference, isGuardedUse } from './guards.js';
4
5
  // Functions whose result is a number or boolean for every input.
5
6
  const numericFunctions = new Set(['Number', 'parseInt', 'parseFloat', 'BigInt', 'Boolean']);
6
- const regexMetacharacters = /[.*+?^${}()|[\]\\]/g;
7
+ const rfc4515RequiredEscapes = ['\\', '*', '(', ')'];
7
8
  // A name that a project declaration shadows (`const parseInt = (v) => v`) is not the built-in and
8
9
  // earns no credit.
9
10
  function isNumericCall(call, checker) {
@@ -54,18 +55,101 @@ function couldBeString(node, checker) {
54
55
  const stringFlags = ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown;
55
56
  return (type.isUnion() ? (type.types ?? []) : [type]).some((member) => member.flags & stringFlags);
56
57
  }
57
- // Recognize the full metacharacter escape without evaluating a regex from source under review.
58
+ const REQUIRED_REGEX_METACHARS = [...'.*+?^${}()|[]\\'];
59
+ function hasAllRegexMetacharacters(literalText) {
60
+ const lastSlash = literalText.lastIndexOf('/');
61
+ if (lastSlash <= 1)
62
+ return false;
63
+ const body = literalText.slice(1, lastSlash);
64
+ const flags = literalText.slice(lastSlash + 1);
65
+ if (!flags.includes('g') || flags.includes('y') || !body.startsWith('[') || !body.endsWith(']'))
66
+ return false;
67
+ const inner = body.slice(1, -1);
68
+ if (!inner || inner.startsWith('^'))
69
+ return false;
70
+ const covered = new Set();
71
+ for (let i = 0; i < inner.length;) {
72
+ const ch = inner[i];
73
+ if (ch === '\\') {
74
+ if (i + 1 >= inner.length)
75
+ return false;
76
+ covered.add(inner[i + 1]);
77
+ i += 2;
78
+ continue;
79
+ }
80
+ if (ch === ']')
81
+ return false;
82
+ if (ch === '-' && i > 0 && i + 1 < inner.length)
83
+ return false;
84
+ covered.add(ch);
85
+ i += 1;
86
+ }
87
+ return REQUIRED_REGEX_METACHARS.every((meta) => covered.has(meta));
88
+ }
89
+ // Recognize `RegExp.escape(...)` and full metacharacter `.replace()` / `.replaceAll()` escapes
90
+ // without evaluating a regex from source under review.
58
91
  function isRegexEscape(call, checker) {
59
92
  const callee = ts.skipOuterExpressions(call.expression);
60
- if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'replace')
93
+ if (!ts.isPropertyAccessExpression(callee))
94
+ return false;
95
+ if (callee.name.text === 'escape' &&
96
+ ts.isIdentifier(callee.expression) &&
97
+ callee.expression.text === 'RegExp' &&
98
+ call.arguments.length >= 1 &&
99
+ isBuiltinReference(callee.expression, checker)) {
100
+ return true;
101
+ }
102
+ if (callee.name.text !== 'replace' && callee.name.text !== 'replaceAll')
61
103
  return false;
62
104
  const [pattern, replacement] = call.arguments;
63
105
  return (pattern &&
64
106
  ts.isRegularExpressionLiteral(pattern) &&
65
- pattern.text === regexMetacharacters.toString() &&
107
+ hasAllRegexMetacharacters(pattern.text) &&
66
108
  replacement &&
67
109
  ts.isStringLiteralLike(replacement) &&
68
110
  replacement.text === '\\$&' &&
69
111
  couldBeString(callee.expression, checker));
70
112
  }
71
- export { isNumericCall, isPrunedType, isGuarded, stringIsSafe, couldBeString, isRegexEscape };
113
+ // Recognize RFC 4515 LDAP filter escaping: global .replace() covering \, *, (, ), and NUL (\0/\x00/\u0000),
114
+ // or ldap-escape's `filter` helper (distinct from `dn` escaping).
115
+ function isRfc4515CharClass(patternText) {
116
+ const match = patternText.match(/^\/\[(.+)\]\/([a-z]*)$/);
117
+ if (!match || !match[2].includes('g'))
118
+ return false;
119
+ const body = match[1];
120
+ if (body.startsWith('^'))
121
+ return false;
122
+ const hasNul = /\\(?:0|x00|u0000|u\{0+\})/.test(body);
123
+ if (!hasNul)
124
+ return false;
125
+ const unescaped = body.replaceAll('\\\\', '\u0001');
126
+ return rfc4515RequiredEscapes.every((ch) => (ch === '\\' ? body.includes('\\\\') : unescaped.includes(ch)));
127
+ }
128
+ function isLdapEscapeModuleMember(expression, member, checker) {
129
+ const node = ts.skipOuterExpressions(expression);
130
+ if (ts.isIdentifier(node)) {
131
+ const binding = importedFrom(node, checker);
132
+ return binding?.module === 'ldap-escape' && binding.exported === member;
133
+ }
134
+ if (ts.isPropertyAccessExpression(node) && node.name.text === member && ts.isIdentifier(node.expression)) {
135
+ const binding = importedFrom(node.expression, checker);
136
+ return binding?.module === 'ldap-escape' && (binding.exported === '*' || binding.exported === 'default');
137
+ }
138
+ return false;
139
+ }
140
+ function isLdapFilterTag(tag, checker) {
141
+ return isLdapEscapeModuleMember(tag, 'filter', checker);
142
+ }
143
+ function isLdapFilterEscape(call, checker) {
144
+ const callee = ts.skipOuterExpressions(call.expression);
145
+ if (isLdapEscapeModuleMember(callee, 'filter', checker))
146
+ return true;
147
+ if (!ts.isPropertyAccessExpression(callee) || (callee.name.text !== 'replace' && callee.name.text !== 'replaceAll'))
148
+ return false;
149
+ const [pattern] = call.arguments;
150
+ return Boolean(pattern &&
151
+ ts.isRegularExpressionLiteral(pattern) &&
152
+ isRfc4515CharClass(pattern.text) &&
153
+ couldBeString(callee.expression, checker));
154
+ }
155
+ export { isNumericCall, isPrunedType, isGuarded, stringIsSafe, couldBeString, isRegexEscape, isLdapFilterEscape, isLdapFilterTag, };
@@ -0,0 +1,61 @@
1
+ import path from 'node:path';
2
+ import { stripExpression as strip } from '../bindings.js';
3
+ import { ts } from '../../performance/engine/compiler.js';
4
+ const maxStepTextLength = 80;
5
+ export function oneLine(text, limit) {
6
+ const line = text.replaceAll(/\s+/g, ' ').trim();
7
+ return line.length > limit ? line.slice(0, limit - 3) + '...' : line;
8
+ }
9
+ // The value read through a member access: a container yields nothing, and a non-parameter result
10
+ // loses its object shape unless `keepWhole`.
11
+ export function partOf(result, keepWhole) {
12
+ if (!result || result.container)
13
+ return result?.container ? undefined : result;
14
+ return keepWhole || result.parameter !== undefined ? result : { ...result, taint: 'scalar', objectFields: undefined };
15
+ }
16
+ // The taint of a field that holds either its earlier value or the written one.
17
+ export function eitherField(earlier, written) {
18
+ if (!earlier?.objectFields)
19
+ return earlier ?? written;
20
+ if (!written.objectFields)
21
+ return written;
22
+ const fields = new Map(earlier.objectFields);
23
+ for (const [name, field] of written.objectFields)
24
+ fields.set(name, eitherField(fields.get(name), field));
25
+ const unknownObjectField = earlier.unknownObjectField ?? written.unknownObjectField;
26
+ const cleanObjectFields = new Set([...(earlier.cleanObjectFields ?? []), ...(written.cleanObjectFields ?? [])].filter((name) => !fields.has(name) &&
27
+ (!earlier.unknownObjectField || earlier.cleanObjectFields?.has(name)) &&
28
+ (!written.unknownObjectField || written.cleanObjectFields?.has(name))));
29
+ return { ...written, objectFields: fields, unknownObjectField, cleanObjectFields };
30
+ }
31
+ export function step(node) {
32
+ const sourceFile = node.getSourceFile();
33
+ const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
34
+ const file = path.relative(process.cwd(), sourceFile.fileName).split(path.sep).join('/');
35
+ return { file, line: line + 1, text: oneLine(node.getText(sourceFile), maxStepTextLength) };
36
+ }
37
+ export function propertyName(access) {
38
+ if (ts.isPropertyAccessExpression(access))
39
+ return access.name.text;
40
+ const argument = strip(access.argumentExpression);
41
+ return argument && (ts.isStringLiteralLike(argument) || ts.isNumericLiteral(argument)) ? argument.text : undefined;
42
+ }
43
+ export function declarationOf(identifier, checker) {
44
+ const symbol = ts.isShorthandPropertyAssignment(identifier.parent)
45
+ ? checker.getShorthandAssignmentValueSymbol(identifier.parent)
46
+ : checker.getSymbolAtLocation(identifier);
47
+ if (!symbol || symbol.flags & ts.SymbolFlags.Alias)
48
+ return;
49
+ return symbol.valueDeclaration ?? symbol.declarations?.[0];
50
+ }
51
+ // `promise.then((value) => ...)`: the promise whose settled value the callback's first parameter
52
+ // receives.
53
+ export function promiseOfThenCallback(fn) {
54
+ if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn))
55
+ return;
56
+ const call = fn.parent;
57
+ if (!ts.isCallExpression(call) || call.arguments[0] !== fn)
58
+ return;
59
+ const callee = strip(call.expression);
60
+ return ts.isPropertyAccessExpression(callee) && callee.name.text === 'then' ? callee.expression : undefined;
61
+ }
@@ -2,6 +2,7 @@
2
2
  // ValidationPipe, and zod, joi, yup and valibot schemas. Everything is read from project syntax and
3
3
  // import bindings, never from package types, so a project without node_modules gets the same
4
4
  // sanitizers.
5
+ import { staticPropertyName } from '../../shared/analysis/ast-semantics.js';
5
6
  import { ts } from '../../performance/engine/compiler.js';
6
7
  import { importedFrom } from '../bindings.js';
7
8
  import { isClosedAnchoredRegex } from '../pg-identifier-guards.js';
@@ -211,6 +212,20 @@ const closedRefinements = new Set([
211
212
  ]);
212
213
  const patternRefinements = new Set(['regex', 'matches', 'pattern']);
213
214
  // Modifiers that keep the schema's output alphabet.
215
+ const numericConstraints = new Set([
216
+ 'positive',
217
+ 'negative',
218
+ 'nonpositive',
219
+ 'nonnegative',
220
+ 'multipleOf',
221
+ 'step',
222
+ 'gt',
223
+ 'gte',
224
+ 'lt',
225
+ 'lte',
226
+ 'finite',
227
+ 'safe',
228
+ ]);
214
229
  const neutralModifiers = new Set([
215
230
  'min',
216
231
  'max',
@@ -290,7 +305,7 @@ function chainLibrary(node, checker) {
290
305
  if (ts.isCallExpression(current))
291
306
  current = ts.skipOuterExpressions(current.expression);
292
307
  else if (ts.isPropertyAccessExpression(current))
293
- current = ts.skipOuterExpressions(current.expression);
308
+ current = schemaExpression(current.expression, checker);
294
309
  else
295
310
  return;
296
311
  }
@@ -299,7 +314,12 @@ function literalArguments(call) {
299
314
  const values = call.arguments.length === 1 && ts.isArrayLiteralExpression(call.arguments[0])
300
315
  ? call.arguments[0].elements
301
316
  : call.arguments;
302
- return values.length > 0 && values.every((value) => ts.isStringLiteralLike(value) || ts.isNumericLiteral(value));
317
+ return (values.length > 0 &&
318
+ values.every((value) => ts.isStringLiteralLike(value) ||
319
+ ts.isNumericLiteral(value) ||
320
+ value.kind === ts.SyntaxKind.NullKeyword ||
321
+ value.kind === ts.SyntaxKind.TrueKeyword ||
322
+ value.kind === ts.SyntaxKind.FalseKeyword));
303
323
  }
304
324
  function objectFields(literal, checker) {
305
325
  if (!literal)
@@ -312,7 +332,10 @@ function objectFields(literal, checker) {
312
332
  if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
313
333
  return;
314
334
  const node = ts.isPropertyAssignment(property) ? property.initializer : property.name;
315
- fields.set(property.name.getText().replaceAll(/^['"]|['"]$/g, ''), node);
335
+ const name = staticPropertyName(property.name);
336
+ if (name === undefined)
337
+ return;
338
+ fields.set(name, node);
316
339
  }
317
340
  return fields;
318
341
  }
@@ -330,7 +353,7 @@ function baseShape(name, call, checker, depth) {
330
353
  return { kind: 'closed' };
331
354
  if (name === 'object' || name === 'strictObject' || name === 'looseObject') {
332
355
  const fields = call.arguments.length ? objectFields(call.arguments[0], checker) : new Map();
333
- return fields && { kind: 'object', fields };
356
+ return fields && { kind: 'object', fields, keepsUnknownFields: name === 'looseObject' };
334
357
  }
335
358
  if (name === 'array') {
336
359
  const element = call.arguments[0] && schemaShape(call.arguments[0], checker, depth + 1);
@@ -356,9 +379,46 @@ function baseShape(name, call, checker, depth) {
356
379
  return closing ? { kind: 'closed' } : shape;
357
380
  }
358
381
  }
359
- // { kind: 'open' }, { kind: 'closed' }, { kind: 'object', fields }, or undefined when the schema is
360
- // not understood (which the caller treats as clean, like any unknown call).
382
+ const joiOutputMethods = new Set(['strip', 'raw', 'result']);
383
+ const joiConversionMethods = new Set(['strict', 'prefs', 'preferences', 'options']);
384
+ function lastSchemaSetting(node, methods, checker) {
385
+ let current = schemaExpression(node, checker);
386
+ for (let depth = 0; current && ts.isCallExpression(current) && depth < maxSchemaDepth; depth++) {
387
+ const callee = ts.skipOuterExpressions(current.expression);
388
+ if (!ts.isPropertyAccessExpression(callee))
389
+ return;
390
+ const name = callee.name.text;
391
+ if (methods.has(name))
392
+ return { name, argument: current.arguments[0] && ts.skipOuterExpressions(current.arguments[0]) };
393
+ current = schemaExpression(callee.expression, checker);
394
+ }
395
+ }
396
+ // These Joi methods share one output flag. Raw input satisfies a closed scalar constraint only
397
+ // when conversion was disabled; it can otherwise differ from the validated value.
361
398
  function schemaShape(node, checker, depth = 0) {
399
+ const shape = schemaValueShape(node, checker, depth);
400
+ if (chainLibrary(node, checker) !== 'joi')
401
+ return shape;
402
+ const setting = lastSchemaSetting(node, joiOutputMethods, checker);
403
+ if (!setting)
404
+ return shape;
405
+ const { name, argument } = setting;
406
+ if (name === 'result' && argument && ts.isStringLiteralLike(argument) && argument.text === 'strip')
407
+ return { kind: 'closed' };
408
+ if (name !== 'result' && argument?.kind === ts.SyntaxKind.FalseKeyword)
409
+ return shape;
410
+ if (name === 'strip')
411
+ return !argument || argument.kind === ts.SyntaxKind.TrueKeyword ? { kind: 'closed' } : shape;
412
+ const conversion = lastSchemaSetting(node, joiConversionMethods, checker);
413
+ if (shape?.kind === 'closed' &&
414
+ conversion?.name === 'strict' &&
415
+ (!conversion.argument || conversion.argument.kind === ts.SyntaxKind.TrueKeyword))
416
+ return shape;
417
+ return { kind: 'open' };
418
+ }
419
+ // { kind: 'open' }, { kind: 'closed' }, { kind: 'object', fields }, or undefined when the schema is
420
+ // not understood. A recognized parser then propagates the input conservatively.
421
+ function schemaValueShape(node, checker, depth) {
362
422
  if (depth > maxSchemaDepth)
363
423
  return;
364
424
  const expression = schemaExpression(node, checker);
@@ -373,14 +433,34 @@ function schemaShape(node, checker, depth = 0) {
373
433
  const root = ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'coerce' ? receiver.expression : receiver;
374
434
  if (ts.isIdentifier(root) && schemaLibrary(root, checker))
375
435
  return baseShape(name, expression, checker, depth);
376
- const shape = schemaShape(receiver, checker, depth + 1);
377
- if (!shape || shape.kind === 'closed')
436
+ const shape = schemaValueShape(receiver, checker, depth + 1);
437
+ if (!shape)
438
+ return chainLibrary(receiver, checker) && closedRefinement(name, expression, checker)
439
+ ? { kind: 'closed' }
440
+ : undefined;
441
+ // Joi checks allowed references before its ordinary refinements. A sibling value admitted this
442
+ // way keeps its provenance even when the base and the following numeric rules look closed.
443
+ if (shape.kind === 'dynamic-allowlist')
444
+ return shape;
445
+ if (['raw', 'result', 'strip'].includes(name) && chainLibrary(receiver, checker) === 'joi')
378
446
  return shape;
447
+ if (name === 'allow' && chainLibrary(receiver, checker) === 'joi' && !literalArguments(expression))
448
+ return { kind: 'dynamic-allowlist' };
449
+ if (shape.kind === 'closed' && numericConstraints.has(name))
450
+ return shape;
451
+ if (shape.kind === 'object' && name === 'unknown' && chainLibrary(receiver, checker) === 'joi') {
452
+ const argument = expression.arguments[0] && ts.skipOuterExpressions(expression.arguments[0]);
453
+ return { ...shape, keepsUnknownFields: argument?.kind !== ts.SyntaxKind.FalseKeyword };
454
+ }
455
+ if (shape.kind === 'object' && name === 'passthrough')
456
+ return { ...shape, keepsUnknownFields: true };
457
+ if (shape.kind === 'object' && (name === 'strict' || name === 'strip') && chainLibrary(receiver, checker) === 'zod')
458
+ return { ...shape, keepsUnknownFields: false };
379
459
  if (closedRefinement(name, expression, checker))
380
460
  return { kind: 'closed' };
381
461
  if (shape.kind === 'object' && (name === 'extend' || name === 'keys' || name === 'shape')) {
382
462
  const added = objectFields(expression.arguments[0], checker);
383
- return added && { kind: 'object', fields: new Map([...(shape.fields ?? []), ...added]) };
463
+ return added && { ...shape, fields: new Map([...(shape.fields ?? []), ...added]) };
384
464
  }
385
465
  return neutralModifiers.has(name) || patternRefinements.has(name) ? shape : undefined;
386
466
  }
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { parseArgs } from 'node:util';
7
+ import { packagePath } from '../package-root.js';
7
8
  import { writeFileAtomic } from '../system/atomic-write.js';
8
9
  import { isTempRoot, safeExists } from '../project-root.js';
9
10
  import { realTarget } from '../system/real-target.js';
@@ -234,7 +235,7 @@ function runMcp(args) {
234
235
  throw new Error('Expected a project directory.');
235
236
  if (values['print-config']) {
236
237
  const command = process.execPath;
237
- const args = [path.resolve(import.meta.dirname, '../../../bin/loadwise.js'), 'agent', 'mcp', directory];
238
+ const args = [packagePath('dist/bin/loadwise.js'), 'agent', 'mcp', directory];
238
239
  console.log(JSON.stringify({ type: 'stdio', command, args }, null, 2));
239
240
  return 0;
240
241
  }
@@ -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) {
@@ -162,7 +165,7 @@ function recordReport(report, source, state, selectedChecker) {
162
165
  if (!isRecord(report))
163
166
  throw new Error(source + ' must be a report object.');
164
167
  const isHistory = 'runs' in report || 'enabled' in report;
165
- 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;
166
169
  const isScan = Object.keys(report).some((name) => checkerNames.has(name));
167
170
  const isStandalone = 'findings' in report;
168
171
  if ([isHistory, isFix, isScan, isStandalone].filter(Boolean).length !== 1)
@@ -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
  }
@@ -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,