pi-lens 4.4.3 → 4.4.5

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 (185) hide show
  1. package/CHANGELOG.md +721 -0
  2. package/README.md +25 -3
  3. package/config/dependency-cruiser-eager-allowlist.json +1 -0
  4. package/dist/chunk-22Y2BM7H.js +23 -0
  5. package/dist/{chunk-WU567RSC.js → chunk-27VWVB23.js} +16 -14
  6. package/dist/{chunk-FLKWCIZH.js → chunk-2FYKETQJ.js} +10 -6
  7. package/dist/{chunk-MQLUAEOC.js → chunk-2LDMXL2M.js} +2 -2
  8. package/dist/{chunk-YSZNHOBY.js → chunk-2SDHYHHO.js} +17 -17
  9. package/dist/chunk-2Y6OJRSI.js +38 -0
  10. package/dist/chunk-3SNDVPOR.js +507 -0
  11. package/dist/{chunk-EJIUXPBX.js → chunk-3WCEHYOI.js} +1 -1
  12. package/dist/chunk-44X7VIKR.js +73 -0
  13. package/dist/{chunk-Q7DUK4LX.js → chunk-4FHUGDKU.js} +16 -14
  14. package/dist/{chunk-H6MF6EVN.js → chunk-4ODSZ35Z.js} +1498 -534
  15. package/dist/{chunk-ZGDGW2V3.js → chunk-4U7GDSZQ.js} +2 -2
  16. package/dist/chunk-54NIOJJZ.js +25 -0
  17. package/dist/{chunk-ZWFS3OEF.js → chunk-5DKE4HGX.js} +38 -37
  18. package/dist/{chunk-VRZP76YM.js → chunk-5LRUKYFA.js} +34 -4
  19. package/dist/{chunk-QOBUHWHX.js → chunk-63NMUNYP.js} +12 -16
  20. package/dist/{chunk-VWCXW2E7.js → chunk-6XSESGWD.js} +13 -6
  21. package/dist/{chunk-QGQ5CCCG.js → chunk-72J27ICO.js} +2 -3
  22. package/dist/{chunk-CSHFH5IN.js → chunk-7FLRUH6B.js} +1 -1
  23. package/dist/chunk-7IYC4ENJ.js +297 -0
  24. package/dist/chunk-7WWQAW5P.js +30 -0
  25. package/dist/{chunk-EU63SDCG.js → chunk-7ZS7MC24.js} +885 -451
  26. package/dist/{chunk-KBG47GHP.js → chunk-AHWA4AKM.js} +18 -12
  27. package/dist/{chunk-FMSO6RDZ.js → chunk-AI3GP74G.js} +17 -19
  28. package/dist/chunk-APFJKOP6.js +67 -0
  29. package/dist/{chunk-RXCOMYPY.js → chunk-ASRAO7KG.js} +31 -33
  30. package/dist/{chunk-BW5KFIQC.js → chunk-AWQWXSW4.js} +1 -0
  31. package/dist/{chunk-QILIYSJF.js → chunk-CG5V25HX.js} +1 -1
  32. package/dist/chunk-CKEQFGLT.js +32 -0
  33. package/dist/{chunk-RPLINGVB.js → chunk-COOUUC5W.js} +6 -6
  34. package/dist/{chunk-GBPP5P7X.js → chunk-CPZ5JJW6.js} +4 -4
  35. package/dist/{chunk-OCAGUNBC.js → chunk-DS2USX5G.js} +13 -15
  36. package/dist/chunk-EA2ZRG44.js +27 -0
  37. package/dist/{chunk-ZHFZWTZV.js → chunk-EDMLIW6W.js} +13 -14
  38. package/dist/{chunk-2EECBNC5.js → chunk-EIKRZ32J.js} +75 -0
  39. package/dist/chunk-EKNWOL2I.js +27 -0
  40. package/dist/{chunk-CMMHNUZ2.js → chunk-ELZRSR5N.js} +65 -43
  41. package/dist/{chunk-BKE7E7TC.js → chunk-EN5AM7PX.js} +11 -12
  42. package/dist/{chunk-N2H3ZPZY.js → chunk-EWXXLS26.js} +227 -24
  43. package/dist/chunk-EX4EXBW7.js +37 -0
  44. package/dist/{chunk-YYOIQFRS.js → chunk-EXVXBSGN.js} +130 -52
  45. package/dist/{chunk-6GFRNVYR.js → chunk-F7BO6FWH.js} +12 -13
  46. package/dist/chunk-FEDWAYDS.js +2485 -0
  47. package/dist/{chunk-JAU72XNY.js → chunk-FWZRGGGY.js} +73 -9
  48. package/dist/{chunk-GXW6K4YJ.js → chunk-G224FADB.js} +1 -1
  49. package/dist/chunk-G5UCJFT7.js +26 -0
  50. package/dist/{chunk-67WMNWEE.js → chunk-GLW3YDZZ.js} +22 -13
  51. package/dist/{chunk-724UL2TJ.js → chunk-GTDSYEA2.js} +72 -39
  52. package/dist/{chunk-PHDMFAKM.js → chunk-GYRZ72R4.js} +10 -4
  53. package/dist/chunk-HYVXA3BB.js +49 -0
  54. package/dist/{chunk-SAEFPSB6.js → chunk-IEBJF3PN.js} +23 -15
  55. package/dist/chunk-IJYGIDF4.js +186 -0
  56. package/dist/{chunk-ACXEQZOU.js → chunk-IL7K66ZQ.js} +101 -109
  57. package/dist/{chunk-ZXYDQ3TZ.js → chunk-JWOVP5BL.js} +50 -19
  58. package/dist/{chunk-OXXKQCSV.js → chunk-K2GUZ4DN.js} +4 -4
  59. package/dist/{chunk-AW7R2GWG.js → chunk-K4SZB56V.js} +39 -39
  60. package/dist/{chunk-WOA4LN2R.js → chunk-KCBRHV5E.js} +3 -3
  61. package/dist/{chunk-3W7IEVVL.js → chunk-KFXCL4OV.js} +47 -45
  62. package/dist/{chunk-2BBLFX75.js → chunk-KJJAVH3X.js} +81 -15
  63. package/dist/{chunk-VCHXCQFG.js → chunk-KPVLQHCZ.js} +4 -6
  64. package/dist/{chunk-P7266HLM.js → chunk-KX56K73G.js} +10 -13
  65. package/dist/{chunk-VSSBEUFT.js → chunk-LMCTHJ2H.js} +19 -19
  66. package/dist/{chunk-IBGIOBEE.js → chunk-MEFLGBCS.js} +69 -8
  67. package/dist/{chunk-TYM6OUIT.js → chunk-MKPCELNI.js} +17 -17
  68. package/dist/{chunk-XTMJ7XDT.js → chunk-N3PLNNCW.js} +1 -1
  69. package/dist/chunk-N5FBM25N.js +22 -0
  70. package/dist/{chunk-CHOW74WE.js → chunk-NFNVDDGB.js} +7 -12
  71. package/dist/{chunk-52FUZI6K.js → chunk-NLIVE7L6.js} +2 -30
  72. package/dist/{chunk-SS36ZX4J.js → chunk-OMJ3OFBJ.js} +6 -6
  73. package/dist/{chunk-4W4VLAPJ.js → chunk-OZNCKLOX.js} +13 -14
  74. package/dist/chunk-P5XUGPIX.js +31 -0
  75. package/dist/{chunk-5UCAH366.js → chunk-PJXNTPB2.js} +253 -33
  76. package/dist/chunk-PKOXJIVT.js +88 -0
  77. package/dist/{chunk-6C7JWPCP.js → chunk-PP2A5V2T.js} +27 -26
  78. package/dist/{chunk-L3BLXZG7.js → chunk-Q42LJANT.js} +31 -70
  79. package/dist/{chunk-AB3YYG6N.js → chunk-Q4BKKOVC.js} +8 -8
  80. package/dist/{chunk-3EFKIGZN.js → chunk-QT66NEYN.js} +4 -4
  81. package/dist/{chunk-3VPVG5SU.js → chunk-RCHO5W7M.js} +19 -18
  82. package/dist/{chunk-77M37OKR.js → chunk-RG3MXTRI.js} +7 -7
  83. package/dist/chunk-RG7OODGM.js +57 -0
  84. package/dist/{chunk-T6CPIZNT.js → chunk-RU34BA4D.js} +44 -39
  85. package/dist/{chunk-JMYYOTQG.js → chunk-S26LC76R.js} +13 -1
  86. package/dist/{chunk-5NGR67U5.js → chunk-S55TEC7I.js} +33 -5
  87. package/dist/{chunk-M6HSLBWY.js → chunk-SJHC3BCZ.js} +7956 -8047
  88. package/dist/{chunk-XCJN5IJU.js → chunk-SNEUMLM7.js} +4 -4
  89. package/dist/{chunk-UZ3TUTRV.js → chunk-T4NGVFYI.js} +2 -2
  90. package/dist/{chunk-2VUQMUMT.js → chunk-THEXI2QO.js} +49 -43
  91. package/dist/{chunk-R3PCY3YS.js → chunk-TL2TCJYL.js} +15 -16
  92. package/dist/{chunk-C34ZXZ7O.js → chunk-TPYYEDP5.js} +838 -352
  93. package/dist/{chunk-AOHZU2BM.js → chunk-TVZRLTG6.js} +8 -1
  94. package/dist/{chunk-XMSXXAHW.js → chunk-UCVMSOXF.js} +2 -2
  95. package/dist/chunk-UL5SXQVX.js +32 -0
  96. package/dist/{chunk-GAEGEPOC.js → chunk-UO66IMVP.js} +2 -2
  97. package/dist/{chunk-N3X6Q4YT.js → chunk-UVY4TOJH.js} +3 -3
  98. package/dist/{chunk-2CD5RS6M.js → chunk-VIDEKABZ.js} +23 -2
  99. package/dist/{chunk-JSQFTSC6.js → chunk-VITFDI3O.js} +13 -14
  100. package/dist/{chunk-YIUAVF7E.js → chunk-VUAVE3QC.js} +42 -42
  101. package/dist/{chunk-QOZXJ4NA.js → chunk-WUY4BZEP.js} +21 -20
  102. package/dist/{chunk-VCO24T4L.js → chunk-X3UTCXAA.js} +43 -53
  103. package/dist/chunk-XHDBJODR.js +45 -0
  104. package/dist/{chunk-MXGY6KPT.js → chunk-XHLK33VM.js} +28 -21
  105. package/dist/{chunk-RWWYJ623.js → chunk-XI34NWDI.js} +2 -2
  106. package/dist/{chunk-QQNQ7SJW.js → chunk-XWFIHYCH.js} +12 -4
  107. package/dist/{chunk-6SDEP3AJ.js → chunk-Y2TPADJR.js} +10 -11
  108. package/dist/{chunk-MRXKYPCS.js → chunk-Y5KTA2OB.js} +17 -17
  109. package/dist/{chunk-7DYBLXYA.js → chunk-YKVDBNPO.js} +11 -5
  110. package/dist/{chunk-2B73ZPOK.js → chunk-YSDPVDFC.js} +3 -3
  111. package/dist/chunk-YWNO5Q4R.js +44 -0
  112. package/dist/{chunk-QHJ6DQ2R.js → chunk-YWWG4AQA.js} +165 -32
  113. package/dist/{chunk-3JNKMP3B.js → chunk-YXDCRUKQ.js} +4 -4
  114. package/dist/{chunk-UXGETRP4.js → chunk-YXGRRORB.js} +16 -17
  115. package/dist/{chunk-SQ4TVJBR.js → chunk-ZAPSUBLU.js} +13 -7
  116. package/dist/{chunk-76MWC2K6.js → chunk-ZPJM7DID.js} +90 -97
  117. package/dist/{chunk-XVF2VVXP.js → chunk-ZSUX7KEM.js} +16 -15
  118. package/dist/index.js +31038 -20893
  119. package/dist/mcp/analyze-cli.js +11 -11
  120. package/dist/mcp/cli.js +47 -43
  121. package/dist/mcp/server.js +2188 -906
  122. package/dist/mcp/worker.js +66 -63
  123. package/dist/probes/installer.js +21 -23
  124. package/dist/workers/project-snapshot-persist-worker.js +28 -9
  125. package/dist/workers/review-graph-persist-worker.js +1 -1
  126. package/docs/adr/0010-trace-validation-session-lifecycle.md +390 -0
  127. package/docs/adr/README.md +1 -0
  128. package/docs/ast-grep_rules_catalog.md +5 -3
  129. package/docs/configuration.md +20 -0
  130. package/docs/engineering-principles.md +44 -0
  131. package/docs/environment-variables.md +20 -0
  132. package/docs/features.md +16 -1
  133. package/docs/globalconfig.md +37 -8
  134. package/docs/lsp-capability-matrix.md +105 -12
  135. package/docs/lsp-idle-eviction.md +44 -36
  136. package/docs/pi-lens-fixer.md +139 -14
  137. package/docs/pi-lens-investigator.md +14 -0
  138. package/docs/pi-lens-merge-policy.md +120 -17
  139. package/docs/pi-lens-monitor.md +71 -9
  140. package/docs/pi-lens-retro.md +6 -3
  141. package/docs/pi-lens-reviewer.md +160 -5
  142. package/docs/pi-lens-subagent.md +29 -14
  143. package/docs/release-qa-baseline.md +21 -7
  144. package/docs/servercapabilities.md +53 -63
  145. package/docs/settings.md +9 -5
  146. package/docs/subagent-compat.md +1 -1
  147. package/docs/usage.md +1 -0
  148. package/package.json +9 -5
  149. package/rules/ast-grep-rules/rule-tests/no-return-value-in-generator-test.yml +17 -0
  150. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-js-test.yml +86 -0
  151. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-test.yml +86 -0
  152. package/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +15 -0
  153. package/rules/ast-grep-rules/rules/no-return-value-in-generator.yml +9 -4
  154. package/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +119 -0
  155. package/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +119 -0
  156. package/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +13 -2
  157. package/rules/rule-catalog.json +25 -1
  158. package/scripts/analyze-pi-lens-logs.mjs +15 -5
  159. package/scripts/download-grammars.js +40 -7
  160. package/scripts/lib/is-main-module.mjs +27 -0
  161. package/scripts/lib/latency-log-phases.mjs +95 -0
  162. package/scripts/lib/scratch-home-env.mjs +21 -0
  163. package/scripts/rpc-load-check.mjs +568 -81
  164. package/scripts/warm-loader-cache.mjs +2 -5
  165. package/dist/chunk-23WOO7TX.js +0 -23
  166. package/dist/chunk-3YN6V5TV.js +0 -85
  167. package/dist/chunk-466Z26MG.js +0 -30
  168. package/dist/chunk-4UNXBNE2.js +0 -24
  169. package/dist/chunk-6STA6Z7I.js +0 -47
  170. package/dist/chunk-ABBOA7UD.js +0 -157
  171. package/dist/chunk-BRGDSBJE.js +0 -28
  172. package/dist/chunk-EC47DWFA.js +0 -56
  173. package/dist/chunk-FCSOVF55.js +0 -273
  174. package/dist/chunk-IZSHAIJ7.js +0 -26
  175. package/dist/chunk-KDERNTCQ.js +0 -28
  176. package/dist/chunk-KSX3TXSZ.js +0 -69
  177. package/dist/chunk-LOP6GRPH.js +0 -31
  178. package/dist/chunk-PNQDPDRC.js +0 -184
  179. package/dist/chunk-UOPVJQ4N.js +0 -103
  180. package/dist/chunk-XAGLWMJ4.js +0 -51
  181. package/dist/chunk-XIJZVPD5.js +0 -39
  182. package/dist/chunk-Z3CCVDUB.js +0 -76
  183. package/dist/chunk-Z527N6YQ.js +0 -28
  184. package/dist/chunk-ZANLILYD.js +0 -79
  185. /package/dist/{chunk-FC4RP4I2.js → chunk-6HWVI6MI.js} +0 -0
@@ -0,0 +1,119 @@
1
+ id: no-sql-in-code-execute-js
2
+ language: JavaScript
3
+ message: "Raw SQL string in code — use query builder or ORM"
4
+ severity: warning
5
+ note: |
6
+ Raw SQL strings built via concatenation or template substitution are
7
+ error-prone and open to injection. Use a query builder (knex, drizzle)
8
+ or ORM (prisma, typeorm), or pass the value as a bind parameter.
9
+
10
+ This rule holds only the `.execute` arms; `.query` stays in
11
+ `no-sql-in-code` / `no-sql-in-code-js` with master's keyword gate. Both
12
+ read `$SQL` the same way: a `binary_expression` (string concatenation,
13
+ e.g. `"SELECT ... " + id`) or a template string with at least one
14
+ `${...}` substitution — the shapes that interpolate a runtime value into
15
+ the query text. A plain string literal, including one with a `?`
16
+ placeholder passed beside a params array, is not flagged (#1806).
17
+
18
+ 2026-10-24 (#1828): `$DB.execute(...)` is the same sink as
19
+ `$DB.query(...)` (mysql2 and oracledb both take `execute(sql, params)`),
20
+ so it gets 1-arg and `, $$$REST` arms, plus their `?.` forms. `execute`
21
+ is also a common task, command and job method name, and the keyword
22
+ `has` on the `.query` arms matches a keyword anywhere in the call: the
23
+ callee-name false-positive class #2909 fixed in the tree-sitter
24
+ `sql-injection` rule. The `.execute` arms therefore use that fix's
25
+ prefix test instead (`ts_sql_injection_sink` in
26
+ clients/tree-sitter-client.ts): the first argument's text (the first
27
+ child of `arguments` that is not a comment) must start with a quote or
28
+ backtick, then optional whitespace and SQL comments, then a statement
29
+ from the sibling's alternation. The test reads the first argument only,
30
+ as the sibling reads only the template, so a later `{ set: ... }` or
31
+ `from` cannot complete an `UPDATE` or `SELECT`.
32
+
33
+ Severity is `warning`, not `error` (#4804 review): statement-shaped
34
+ English still matches, because the alternation accepts it and an
35
+ ast-grep rule has no receiver test. `acl.execute("grant " + role)`,
36
+ `search.execute("create index " + field)`,
37
+ `config.execute("merge into " + base)`, `"delete from " + cacheKey` and
38
+ `"select " + label + " from the list"` all flag. All five are pinned as
39
+ `invalid:` rows, so a later narrowing has a red row to work against.
40
+ Nothing here blocks an edit: this body measures 22 against
41
+ `MAX_BLOCKING_RULE_COMPLEXITY` (8) in
42
+ clients/dispatch/runners/yaml-rule-parser.ts, as master's `.query` body
43
+ already did at 15, so a per-edit dispatch skips the rule. These findings
44
+ arrive from the full-analysis path (`blockingOnly: false`, e.g.
45
+ `pilens_analyze`), where `error` used to present them as blockers.
46
+
47
+ Three edits diverge from the sibling's text
48
+ (clients/tree-sitter-client.ts:4703): a `\b` after `SELECT` and after
49
+ `WITH`, so `"selected from "` and `"Within the select list "` do not
50
+ open a statement; the skip also accepts exactly the `\n`, `\r` and `\t`
51
+ escapes as written in source, case-sensitively so that `\N` does not
52
+ count, which catches `"\nSELECT ..."`; and a `--` comment also ends at
53
+ an escaped `\n` or `\r`, as Postgres ends one at either, so
54
+ `"-- c\nSELECT ..."` is caught (the comment may also run on to a later
55
+ escape).
56
+
57
+ The two differences this leaves against the sibling are accepted
58
+ residuals of this change, not a planned follow-up: the sibling's
59
+ `SELECT` and `WITH` arms carry no word boundary, so
60
+ `job.execute("selected from " + source)` still flags there, and its
61
+ skip accepts real whitespace only, so an escaped `"\nSELECT ..."` is a
62
+ miss there. tests/config/sql-injection-alternation-drift.test.ts keeps
63
+ the rest of the alternation byte-identical to the sibling's copy.
64
+
65
+ Cost (#4804 review, measured on this head for the shared statement
66
+ test): 2.2 to 23.7 ms per scanned file, 231 to 468 of 2,687 JS/TS files
67
+ admitted by the literal prefilter, and 0.46 s to 11.7 s for a
68
+ full-tree scan. The per-file cost does not depend on file size, so it is
69
+ rule compilation per `findAll` call, not traversal; #4807 tracks it and
70
+ does not block this rule. A re-measurement of this split reproduces both
71
+ facts (0.9 to 1.6 ms per file for the `.query` rule, 11 to 12 ms for
72
+ this one, at 28 KiB and 155 KiB).
73
+
74
+ The sibling's other test is out of reach for an ast-grep rule: when the
75
+ prefix test fails, it still flags a template whose receiver it follows
76
+ through same-file declarations to an import from a known SQL package, so
77
+ that is a second way to flag, not a filter.
78
+
79
+ Not caught through `execute`: a statement split between its first two
80
+ tokens (`"DELETE " + "FROM t ..."`), SQL text that opens with `${...}`,
81
+ a parenthesized argument or one that starts with a variable, whitespace
82
+ written as `\u000a`, `\x0a` or a backslash line continuation, a
83
+ FROM-less SELECT built by concatenation (`"SELECT pg_sleep(" + n + ")"`),
84
+ and statements the alternation does not list (`INSERT IGNORE INTO`,
85
+ `INSERT OR REPLACE INTO`).
86
+ rule:
87
+ all:
88
+ - any:
89
+ - pattern: $DB.execute($SQL)
90
+ - pattern: $DB.execute($SQL, $$$REST)
91
+ - pattern: $DB?.execute($SQL)
92
+ - pattern: $DB?.execute($SQL, $$$REST)
93
+ - has:
94
+ field: arguments
95
+ has:
96
+ nthChild:
97
+ position: 1
98
+ ofRule:
99
+ not:
100
+ kind: comment
101
+ regex: >-
102
+ (?i)^["'`](?:\s|(?-i:\\[nrt])|/\*[\s\S]*?\*/|--[^\n]*(?:\n|(?-i:\\[nr])|$))*(?:SELECT\b[\s\S]*(?:\bFROM\b|\$\{)|INSERT\s+INTO\b|UPDATE\s+[\s\S]*\bSET\b|DELETE\s+FROM\b|CREATE\s+(?:OR\s+REPLACE\s+|TEMP(?:ORARY)?\s+|UNIQUE\s+|MATERIALIZED\s+)*(?:TABLE|INDEX|VIEW|SCHEMA|DATABASE|TRIGGER|FUNCTION|PROCEDURE|SEQUENCE|TYPE|EXTENSION)\b|DROP\s+(?:OR\s+REPLACE\s+|TEMP(?:ORARY)?\s+|UNIQUE\s+|MATERIALIZED\s+)*(?:TABLE|INDEX|VIEW|SCHEMA|DATABASE|TRIGGER|FUNCTION|PROCEDURE|SEQUENCE|TYPE|EXTENSION)\b|ALTER\s+(?:OR\s+REPLACE\s+|TEMP(?:ORARY)?\s+|UNIQUE\s+|MATERIALIZED\s+)*(?:TABLE|INDEX|VIEW|SCHEMA|DATABASE|TRIGGER|FUNCTION|PROCEDURE|SEQUENCE|TYPE|EXTENSION)\b|GRANT\b|REVOKE\b|WITH\b[\s\S]*\bSELECT\b|MERGE\s+INTO\b|TRUNCATE\s+TABLE\b|REPLACE\s+INTO\b)
103
+ constraints:
104
+ SQL:
105
+ any:
106
+ - all:
107
+ - kind: binary_expression
108
+ - not:
109
+ all:
110
+ - has:
111
+ field: left
112
+ kind: string
113
+ - has:
114
+ field: right
115
+ kind: string
116
+ - all:
117
+ - kind: template_string
118
+ - has:
119
+ kind: template_substitution
@@ -0,0 +1,119 @@
1
+ id: no-sql-in-code-execute
2
+ language: TypeScript
3
+ message: "Raw SQL string in code — use query builder or ORM"
4
+ severity: warning
5
+ note: |
6
+ Raw SQL strings built via concatenation or template substitution are
7
+ error-prone and open to injection. Use a query builder (knex, drizzle)
8
+ or ORM (prisma, typeorm), or pass the value as a bind parameter.
9
+
10
+ This rule holds only the `.execute` arms; `.query` stays in
11
+ `no-sql-in-code` / `no-sql-in-code-js` with master's keyword gate. Both
12
+ read `$SQL` the same way: a `binary_expression` (string concatenation,
13
+ e.g. `"SELECT ... " + id`) or a template string with at least one
14
+ `${...}` substitution — the shapes that interpolate a runtime value into
15
+ the query text. A plain string literal, including one with a `?`
16
+ placeholder passed beside a params array, is not flagged (#1806).
17
+
18
+ 2026-10-24 (#1828): `$DB.execute(...)` is the same sink as
19
+ `$DB.query(...)` (mysql2 and oracledb both take `execute(sql, params)`),
20
+ so it gets 1-arg and `, $$$REST` arms, plus their `?.` forms. `execute`
21
+ is also a common task, command and job method name, and the keyword
22
+ `has` on the `.query` arms matches a keyword anywhere in the call: the
23
+ callee-name false-positive class #2909 fixed in the tree-sitter
24
+ `sql-injection` rule. The `.execute` arms therefore use that fix's
25
+ prefix test instead (`ts_sql_injection_sink` in
26
+ clients/tree-sitter-client.ts): the first argument's text (the first
27
+ child of `arguments` that is not a comment) must start with a quote or
28
+ backtick, then optional whitespace and SQL comments, then a statement
29
+ from the sibling's alternation. The test reads the first argument only,
30
+ as the sibling reads only the template, so a later `{ set: ... }` or
31
+ `from` cannot complete an `UPDATE` or `SELECT`.
32
+
33
+ Severity is `warning`, not `error` (#4804 review): statement-shaped
34
+ English still matches, because the alternation accepts it and an
35
+ ast-grep rule has no receiver test. `acl.execute("grant " + role)`,
36
+ `search.execute("create index " + field)`,
37
+ `config.execute("merge into " + base)`, `"delete from " + cacheKey` and
38
+ `"select " + label + " from the list"` all flag. All five are pinned as
39
+ `invalid:` rows, so a later narrowing has a red row to work against.
40
+ Nothing here blocks an edit: this body measures 22 against
41
+ `MAX_BLOCKING_RULE_COMPLEXITY` (8) in
42
+ clients/dispatch/runners/yaml-rule-parser.ts, as master's `.query` body
43
+ already did at 15, so a per-edit dispatch skips the rule. These findings
44
+ arrive from the full-analysis path (`blockingOnly: false`, e.g.
45
+ `pilens_analyze`), where `error` used to present them as blockers.
46
+
47
+ Three edits diverge from the sibling's text
48
+ (clients/tree-sitter-client.ts:4703): a `\b` after `SELECT` and after
49
+ `WITH`, so `"selected from "` and `"Within the select list "` do not
50
+ open a statement; the skip also accepts exactly the `\n`, `\r` and `\t`
51
+ escapes as written in source, case-sensitively so that `\N` does not
52
+ count, which catches `"\nSELECT ..."`; and a `--` comment also ends at
53
+ an escaped `\n` or `\r`, as Postgres ends one at either, so
54
+ `"-- c\nSELECT ..."` is caught (the comment may also run on to a later
55
+ escape).
56
+
57
+ The two differences this leaves against the sibling are accepted
58
+ residuals of this change, not a planned follow-up: the sibling's
59
+ `SELECT` and `WITH` arms carry no word boundary, so
60
+ `job.execute("selected from " + source)` still flags there, and its
61
+ skip accepts real whitespace only, so an escaped `"\nSELECT ..."` is a
62
+ miss there. tests/config/sql-injection-alternation-drift.test.ts keeps
63
+ the rest of the alternation byte-identical to the sibling's copy.
64
+
65
+ Cost (#4804 review, measured on this head for the shared statement
66
+ test): 2.2 to 23.7 ms per scanned file, 231 to 468 of 2,687 JS/TS files
67
+ admitted by the literal prefilter, and 0.46 s to 11.7 s for a
68
+ full-tree scan. The per-file cost does not depend on file size, so it is
69
+ rule compilation per `findAll` call, not traversal; #4807 tracks it and
70
+ does not block this rule. A re-measurement of this split reproduces both
71
+ facts (0.9 to 1.6 ms per file for the `.query` rule, 11 to 12 ms for
72
+ this one, at 28 KiB and 155 KiB).
73
+
74
+ The sibling's other test is out of reach for an ast-grep rule: when the
75
+ prefix test fails, it still flags a template whose receiver it follows
76
+ through same-file declarations to an import from a known SQL package, so
77
+ that is a second way to flag, not a filter.
78
+
79
+ Not caught through `execute`: a statement split between its first two
80
+ tokens (`"DELETE " + "FROM t ..."`), SQL text that opens with `${...}`,
81
+ a parenthesized argument or one that starts with a variable, whitespace
82
+ written as `\u000a`, `\x0a` or a backslash line continuation, a
83
+ FROM-less SELECT built by concatenation (`"SELECT pg_sleep(" + n + ")"`),
84
+ and statements the alternation does not list (`INSERT IGNORE INTO`,
85
+ `INSERT OR REPLACE INTO`).
86
+ rule:
87
+ all:
88
+ - any:
89
+ - pattern: $DB.execute($SQL)
90
+ - pattern: $DB.execute($SQL, $$$REST)
91
+ - pattern: $DB?.execute($SQL)
92
+ - pattern: $DB?.execute($SQL, $$$REST)
93
+ - has:
94
+ field: arguments
95
+ has:
96
+ nthChild:
97
+ position: 1
98
+ ofRule:
99
+ not:
100
+ kind: comment
101
+ regex: >-
102
+ (?i)^["'`](?:\s|(?-i:\\[nrt])|/\*[\s\S]*?\*/|--[^\n]*(?:\n|(?-i:\\[nr])|$))*(?:SELECT\b[\s\S]*(?:\bFROM\b|\$\{)|INSERT\s+INTO\b|UPDATE\s+[\s\S]*\bSET\b|DELETE\s+FROM\b|CREATE\s+(?:OR\s+REPLACE\s+|TEMP(?:ORARY)?\s+|UNIQUE\s+|MATERIALIZED\s+)*(?:TABLE|INDEX|VIEW|SCHEMA|DATABASE|TRIGGER|FUNCTION|PROCEDURE|SEQUENCE|TYPE|EXTENSION)\b|DROP\s+(?:OR\s+REPLACE\s+|TEMP(?:ORARY)?\s+|UNIQUE\s+|MATERIALIZED\s+)*(?:TABLE|INDEX|VIEW|SCHEMA|DATABASE|TRIGGER|FUNCTION|PROCEDURE|SEQUENCE|TYPE|EXTENSION)\b|ALTER\s+(?:OR\s+REPLACE\s+|TEMP(?:ORARY)?\s+|UNIQUE\s+|MATERIALIZED\s+)*(?:TABLE|INDEX|VIEW|SCHEMA|DATABASE|TRIGGER|FUNCTION|PROCEDURE|SEQUENCE|TYPE|EXTENSION)\b|GRANT\b|REVOKE\b|WITH\b[\s\S]*\bSELECT\b|MERGE\s+INTO\b|TRUNCATE\s+TABLE\b|REPLACE\s+INTO\b)
103
+ constraints:
104
+ SQL:
105
+ any:
106
+ - all:
107
+ - kind: binary_expression
108
+ - not:
109
+ all:
110
+ - has:
111
+ field: left
112
+ kind: string
113
+ - has:
114
+ field: right
115
+ kind: string
116
+ - all:
117
+ - kind: template_string
118
+ - has:
119
+ kind: template_substitution
@@ -10,9 +10,12 @@ note: |
10
10
  syntactically-certain `error`-level calls (open/json/os/shutil).
11
11
 
12
12
  Excluded as already-safe by construction: a numeric literal argument
13
- (`int(3.7)`), and an argument that is itself a call to `int()`/
13
+ (`int(3.7)`), an argument that is itself a call to `int()`/
14
14
  `float()`/`Decimal()` (already-converted, or a `Decimal` — which raises
15
- `decimal.InvalidOperation`, not `ValueError`, and is out of scope here).
15
+ `decimal.InvalidOperation`, not `ValueError`, and is out of scope here),
16
+ and a call to a builtin that returns a number or raises `TypeError`:
17
+ `round()`, `len()`, `abs()`, `sum()`, `ord()` (#4840). The match is by
18
+ name, so a local that shadows one of these names is exempt too.
16
19
 
17
20
  Residual, undecidable false positive: a call whose argument is a typed
18
21
  parameter already known to be numeric, e.g.
@@ -42,3 +45,11 @@ rule:
42
45
  - pattern: Decimal($$$)
43
46
  - pattern: int($$$)
44
47
  - pattern: float($$$)
48
+ # #4840: round() and len() always return a number; abs(), sum()
49
+ # and ord() too (#4841 review F4). min()/max() are not: they
50
+ # return their argument's type.
51
+ - pattern: round($$$)
52
+ - pattern: len($$$)
53
+ - pattern: abs($$$)
54
+ - pattern: sum($$$)
55
+ - pattern: ord($$$)
@@ -417,7 +417,8 @@
417
417
  "canonical_concept": "sql-in-code-literal",
418
418
  "severity_default": "warning",
419
419
  "confidence": "medium",
420
- "status": "active"
420
+ "status": "active",
421
+ "allow_overlap": true
421
422
  },
422
423
  {
423
424
  "rule_id": "no-sql-in-code-js",
@@ -428,6 +429,29 @@
428
429
  "canonical_concept": "sql-in-code-literal",
429
430
  "severity_default": "warning",
430
431
  "confidence": "medium",
432
+ "status": "active",
433
+ "allow_overlap": true
434
+ },
435
+ {
436
+ "rule_id": "no-sql-in-code-execute",
437
+ "engine": "ast-grep",
438
+ "language": "typescript",
439
+ "family": "security",
440
+ "scope": "file",
441
+ "canonical_concept": "sql-in-code-literal",
442
+ "severity_default": "warning",
443
+ "confidence": "medium",
444
+ "status": "active"
445
+ },
446
+ {
447
+ "rule_id": "no-sql-in-code-execute-js",
448
+ "engine": "ast-grep",
449
+ "language": "javascript",
450
+ "family": "security",
451
+ "scope": "file",
452
+ "canonical_concept": "sql-in-code-literal",
453
+ "severity_default": "warning",
454
+ "confidence": "medium",
431
455
  "status": "active"
432
456
  },
433
457
  {
@@ -19,7 +19,6 @@ import fs from "node:fs";
19
19
  import os from "node:os";
20
20
  import path from "node:path";
21
21
  import readline from "node:readline";
22
- import { fileURLToPath } from "node:url";
23
22
  import { minimatch } from "minimatch";
24
23
 
25
24
  const DEFAULT_ROOT = path.join(os.homedir(), ".pi-lens");
@@ -222,6 +221,7 @@ function createState(files) {
222
221
  toolResults: counter(),
223
222
  phaseCounts: counter(),
224
223
  phaseTimeouts: counter(),
224
+ skillsResolved: counter(),
225
225
  // D1: every latency row timestamp (ms) in window, for the coverage-gap
226
226
  // scan. Sorted after all files are read.
227
227
  rowTs: [],
@@ -475,6 +475,14 @@ async function analyzeLatency(files, state) {
475
475
  } else if (entry.type === "phase") {
476
476
  const phase = entry.phase ?? "unknown";
477
477
  state.latency.phaseCounts.inc(phase);
478
+ if (phase === "skills_resolved") {
479
+ // A non-string or empty status is malformed: count it as unknown rather
480
+ // than render a blank label or [object Object].
481
+ const status = entry.metadata?.status;
482
+ state.latency.skillsResolved.inc(
483
+ typeof status === "string" && status !== "" ? status : "unknown",
484
+ );
485
+ }
478
486
  if (phase.endsWith("_timeout")) state.latency.phaseTimeouts.inc(phase);
479
487
  if (phase === "test_runner_verdict_delivery") {
480
488
  const sessionId = entry.metadata?.sessionId ?? "unknown";
@@ -2631,6 +2639,7 @@ function buildReport(state) {
2631
2639
  toolResults: state.latency.toolResults.toJSON(),
2632
2640
  phaseCounts: state.latency.phaseCounts.top(limit),
2633
2641
  phaseTimeouts: state.latency.phaseTimeouts.toJSON(),
2642
+ skillsResolved: state.latency.skillsResolved.toJSON(),
2634
2643
  workspaceDiagnostics: {
2635
2644
  started: ws.started,
2636
2645
  completed: ws.completed,
@@ -2872,6 +2881,11 @@ function printReport(report) {
2872
2881
  report.diagnostics.byFile,
2873
2882
  (x) => `${x.count.toString().padStart(5)} ${x.key}`,
2874
2883
  );
2884
+ section(
2885
+ "Skills resolution",
2886
+ Object.entries(report.latency.skillsResolved),
2887
+ ([status, count]) => `${count.toString().padStart(5)} ${status}`,
2888
+ );
2875
2889
  section(
2876
2890
  "Runner statuses",
2877
2891
  report.latency.runnerStatus,
@@ -3025,7 +3039,3 @@ function formatExample(ex) {
3025
3039
  if (!bits.length && ex.key) bits.push(`${ex.count} × ${ex.key}`);
3026
3040
  return bits.join(" ");
3027
3041
  }
3028
-
3029
- if (process.argv[1] === fileURLToPath(import.meta.url) && args.help) {
3030
- printHelp();
3031
- }
@@ -172,11 +172,44 @@ function baseUrl(version) {
172
172
  function grammarUrl(version, filename) {
173
173
  return SOURCE_OVERRIDES[filename]?.url ?? `${baseUrl(version)}/${filename}`;
174
174
  }
175
- async function fetchGrammar(version, filename) {
176
- const res = await fetch(grammarUrl(version, filename));
177
- if (!res.ok)
178
- throw new Error(`HTTP ${res.status} fetching ${filename}`);
179
- return Buffer.from(await res.arrayBuffer());
175
+ /**
176
+ * Abort a fetch that receives no bytes for this long, headers included; each
177
+ * chunk restarts the count, so a slow link that keeps delivering completes.
178
+ * Mirrors `GRAMMAR_STALL_MS` in clients/grammar-source.ts, which this script
179
+ * cannot import before the TS build; `tests/clients/grammar-source.test.ts`
180
+ * pins the two together (#4425).
181
+ */
182
+ export const GRAMMAR_STALL_MS = 15_000;
183
+ async function fetchGrammar(version, filename, stallMs = GRAMMAR_STALL_MS) {
184
+ const controller = new AbortController();
185
+ const timer = setTimeout(() => controller.abort(), stallMs);
186
+ try {
187
+ const res = await fetch(grammarUrl(version, filename), {
188
+ signal: controller.signal,
189
+ });
190
+ if (!res.ok)
191
+ throw new Error(`HTTP ${res.status} fetching ${filename}`);
192
+ const reader = res.body?.getReader();
193
+ if (!reader)
194
+ return Buffer.from(await res.arrayBuffer());
195
+ const chunks = [];
196
+ for (;;) {
197
+ const { done, value } = await reader.read();
198
+ if (done)
199
+ return Buffer.concat(chunks);
200
+ timer.refresh();
201
+ chunks.push(value);
202
+ }
203
+ }
204
+ catch (err) {
205
+ if (controller.signal.aborted) {
206
+ throw new Error(`no bytes arrived for ${stallMs} ms fetching ${filename}`);
207
+ }
208
+ throw err;
209
+ }
210
+ finally {
211
+ clearTimeout(timer);
212
+ }
180
213
  }
181
214
  /**
182
215
  * Download `filename` into `destDir` (if it isn't already verified), checking its
@@ -184,12 +217,12 @@ async function fetchGrammar(version, filename) {
184
217
  * integrity mismatch — a grammar whose bytes don't match the pinned manifest is
185
218
  * never written (guards CDN corruption / tampering / ABI drift).
186
219
  */
187
- async function downloadGrammar(destDir, filename, manifest) {
220
+ export async function downloadGrammar(destDir, filename, manifest, stallMs = GRAMMAR_STALL_MS) {
188
221
  if (!needsDownload(destDir, filename, manifest)) {
189
222
  console.error(` skip ${filename} (verified)`);
190
223
  return;
191
224
  }
192
- const buf = await fetchGrammar(manifest.version, filename);
225
+ const buf = await fetchGrammar(manifest.version, filename, stallMs);
193
226
  const actual = sha256(buf);
194
227
  const expected = manifest.grammars[filename];
195
228
  if (expected && actual !== expected) {
@@ -0,0 +1,27 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ // Whether selfUrl (import.meta.url) is the process entry point. Resolve both
5
+ // paths: Node normally resolves the module URL but leaves argv[1] symlinked;
6
+ // --preserve-symlinks-main keeps the URL symlinked too (#4086, #4096).
7
+ // native realpath also canonicalises Windows casing and short-name spellings.
8
+ // An absent argv path means an import (node -e, stdin, or a removed launcher).
9
+ // An unresolvable module URL throws so a broken CLI cannot silently succeed.
10
+ export function isMainModule(
11
+ selfUrl,
12
+ { argv1 = process.argv[1], realpath = realpathSync.native } = {},
13
+ ) {
14
+ let invoked;
15
+ try {
16
+ invoked = realpath(argv1);
17
+ } catch {
18
+ return false;
19
+ }
20
+ try {
21
+ return invoked === realpath(fileURLToPath(selfUrl));
22
+ } catch (error) {
23
+ throw new Error(
24
+ `[is-main-module] cannot resolve the entry-point path of ${selfUrl}: ${error instanceof Error ? error.message : error}`,
25
+ );
26
+ }
27
+ }
@@ -0,0 +1,95 @@
1
+ // Pure NDJSON latency-log phase parsing for scripts/compat-smoke-behavioral.mjs
2
+ // (#476, Layer B).
3
+ //
4
+ // `clients/latency-logger.ts` writes one JSON object per line to
5
+ // `~/.pi-lens/latency.log` (see `createNdjsonLogger`). Layer B launches real
6
+ // `pi` processes and needs to assert (or assert the ABSENCE of) specific
7
+ // `type: "phase"` entries that landed during a bounded time window — this
8
+ // module is the pure parsing/filtering half, kept separate from the
9
+ // file-reading/process-spawning orchestration so it is unit-testable without
10
+ // touching the filesystem or spawning anything.
11
+
12
+ /**
13
+ * Parse NDJSON text into an array of entries. Malformed lines (partial write,
14
+ * truncation mid-append) are skipped rather than throwing — the log is
15
+ * best-effort by construction (ndjson-logger.ts swallows write errors), so a
16
+ * single bad line must never abort the whole read.
17
+ *
18
+ * @param {string} text raw latency.log contents
19
+ * @returns {Array<Record<string, unknown>>}
20
+ */
21
+ export function parseNdjsonEntries(text) {
22
+ const entries = [];
23
+ for (const line of text.split(/\r?\n/)) {
24
+ const trimmed = line.trim();
25
+ if (!trimmed) continue;
26
+ try {
27
+ const parsed = JSON.parse(trimmed);
28
+ if (parsed && typeof parsed === "object") entries.push(parsed);
29
+ } catch {
30
+ // partial/corrupt line — skip
31
+ }
32
+ }
33
+ return entries;
34
+ }
35
+
36
+ /**
37
+ * Filter entries to `type: "phase"` records with the given `phase` name,
38
+ * optionally restricted to entries whose `ts` (ISO timestamp) falls at or
39
+ * after `sinceIso`. Used to scope a check to "phases logged by THIS run" when
40
+ * the log file is long-lived and shared across sessions.
41
+ *
42
+ * @param {Array<Record<string, unknown>>} entries
43
+ * @param {string} phase
44
+ * @param {string} [sinceIso] ISO timestamp lower bound (inclusive)
45
+ */
46
+ export function findPhaseEntries(entries, phase, sinceIso) {
47
+ const sinceMs = sinceIso ? Date.parse(sinceIso) : undefined;
48
+ return entries.filter((e) => {
49
+ if (e.type !== "phase" || e.phase !== phase) return false;
50
+ if (sinceMs === undefined) return true;
51
+ const ts = typeof e.ts === "string" ? Date.parse(e.ts) : Number.NaN;
52
+ return Number.isFinite(ts) && ts >= sinceMs;
53
+ });
54
+ }
55
+
56
+ /**
57
+ * True iff at least one `findPhaseEntries` match exists.
58
+ *
59
+ * @param {Array<Record<string, unknown>>} entries
60
+ * @param {string} phase
61
+ * @param {string} [sinceIso]
62
+ */
63
+ export function phaseWasLogged(entries, phase, sinceIso) {
64
+ return findPhaseEntries(entries, phase, sinceIso).length > 0;
65
+ }
66
+
67
+ /**
68
+ * True iff NO phase in `phases` was logged since `sinceIso` — used to assert
69
+ * a degraded/skip path did NOT engage (e.g. heavyweight scans must be absent
70
+ * under subagent light mode).
71
+ *
72
+ * @param {Array<Record<string, unknown>>} entries
73
+ * @param {string[]} phases
74
+ * @param {string} [sinceIso]
75
+ */
76
+ export function noPhasesLogged(entries, phases, sinceIso) {
77
+ return phases.every((phase) => !phaseWasLogged(entries, phase, sinceIso));
78
+ }
79
+
80
+ /**
81
+ * Number of entries (any type) whose `ts` falls at or after `sinceIso`.
82
+ * Positive control for the absence assertions: "no heavyweight phase logged"
83
+ * is only evidence when the run wrote SOMETHING to the log the smoke is
84
+ * reading — an empty or mis-located log made those pass vacuously (#2570).
85
+ *
86
+ * @param {Array<Record<string, unknown>>} entries
87
+ * @param {string} sinceIso ISO timestamp lower bound (inclusive)
88
+ */
89
+ export function countEntriesSince(entries, sinceIso) {
90
+ const sinceMs = Date.parse(sinceIso);
91
+ return entries.filter((e) => {
92
+ const ts = typeof e.ts === "string" ? Date.parse(e.ts) : Number.NaN;
93
+ return Number.isFinite(ts) && ts >= sinceMs;
94
+ }).length;
95
+ }
@@ -0,0 +1,21 @@
1
+ import * as path from "node:path";
2
+
3
+ /**
4
+ * The home pin an operator script or gate gives every child it spawns (#4789,
5
+ * AGENTS.md shape 82: one home variable pinned, the rest left at the real
6
+ * home). `home` becomes HOME and USERPROFILE (`os.homedir()`'s source on
7
+ * Windows), the three XDG base directories sit under it, and `lensHome` is
8
+ * PI_LENS_HOME (default: `home`). Pure: no I/O and no `process.env` reads, so
9
+ * the caller decides whether the pin lands in a child env object or in
10
+ * `process.env` itself.
11
+ */
12
+ export function scratchHomeEnv(home, lensHome = home) {
13
+ return {
14
+ HOME: home,
15
+ USERPROFILE: home,
16
+ XDG_CONFIG_HOME: path.join(home, ".config"),
17
+ XDG_CACHE_HOME: path.join(home, ".cache"),
18
+ XDG_DATA_HOME: path.join(home, ".local", "share"),
19
+ PI_LENS_HOME: lensHome,
20
+ };
21
+ }