@whaaaley/crush 0.0.0-stage → 0.2.7

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 (358) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +185 -2
  3. package/SKILL.md +187 -0
  4. package/THIRD_PARTY_NOTICES.md +277 -0
  5. package/dist/capture/capture.operations.d.ts +23 -0
  6. package/dist/capture/capture.operations.js +231 -0
  7. package/dist/capture/capture.schema.d.ts +73 -0
  8. package/dist/capture/capture.schema.js +28 -0
  9. package/dist/collapse/collapse.operations.d.ts +2 -0
  10. package/dist/collapse/collapse.operations.js +82 -0
  11. package/dist/collapse/collapse.schema.d.ts +40 -0
  12. package/dist/collapse/collapse.schema.js +35 -0
  13. package/dist/crush.tables.d.ts +3583 -0
  14. package/dist/crush.tables.js +456 -0
  15. package/dist/crushes/callback.crush.d.ts +2 -0
  16. package/dist/crushes/callback.crush.js +19 -0
  17. package/dist/crushes/crush.d.ts +36 -0
  18. package/dist/crushes/crush.js +12 -0
  19. package/dist/crushes/crush.names.d.ts +1 -0
  20. package/dist/crushes/crush.names.js +2 -0
  21. package/dist/crushes/crushes.d.ts +2 -0
  22. package/dist/crushes/crushes.js +9 -0
  23. package/dist/crushes/default-value.crush.d.ts +2 -0
  24. package/dist/crushes/default-value.crush.js +29 -0
  25. package/dist/crushes/drop-operand.crush.d.ts +2 -0
  26. package/dist/crushes/drop-operand.crush.js +37 -0
  27. package/dist/crushes/fold.d.ts +64 -0
  28. package/dist/crushes/fold.js +366 -0
  29. package/dist/crushes/force-fork.crush.d.ts +2 -0
  30. package/dist/crushes/force-fork.crush.js +79 -0
  31. package/dist/crushes/loop-once.crush.d.ts +2 -0
  32. package/dist/crushes/loop-once.crush.js +71 -0
  33. package/dist/crushes/optional-chain.crush.d.ts +2 -0
  34. package/dist/crushes/optional-chain.crush.js +30 -0
  35. package/dist/crushes/switch-case.crush.d.ts +2 -0
  36. package/dist/crushes/switch-case.crush.js +19 -0
  37. package/dist/decisions/decide.d.ts +61 -0
  38. package/dist/decisions/decide.js +161 -0
  39. package/dist/decisions/decisions.d.ts +24 -0
  40. package/dist/decisions/decisions.js +62 -0
  41. package/dist/decisions/forks.decision.d.ts +4 -0
  42. package/dist/decisions/forks.decision.js +32 -0
  43. package/dist/decisions/kinds.d.ts +101 -0
  44. package/dist/decisions/kinds.js +38 -0
  45. package/dist/decisions/loops.decision.d.ts +4 -0
  46. package/dist/decisions/loops.decision.js +39 -0
  47. package/dist/decisions/shorts.decision.d.ts +3 -0
  48. package/dist/decisions/shorts.decision.js +66 -0
  49. package/dist/decisions/switches.decision.d.ts +3 -0
  50. package/dist/decisions/switches.decision.js +20 -0
  51. package/dist/decisions/throws.decision.d.ts +3 -0
  52. package/dist/decisions/throws.decision.js +35 -0
  53. package/dist/decisions/values.decision.d.ts +3 -0
  54. package/dist/decisions/values.decision.js +67 -0
  55. package/dist/explore/edges/explore.d.ts +60 -0
  56. package/dist/explore/edges/explore.db.d.ts +22 -0
  57. package/dist/explore/edges/explore.db.js +55 -0
  58. package/dist/explore/edges/explore.js +305 -0
  59. package/dist/explore/edges/random.d.ts +2 -0
  60. package/dist/explore/edges/random.js +32 -0
  61. package/dist/explore/explore.operations.d.ts +30 -0
  62. package/dist/explore/explore.operations.js +117 -0
  63. package/dist/explore/limits.operations.d.ts +14 -0
  64. package/dist/explore/limits.operations.js +20 -0
  65. package/dist/explore/targets.operations.d.ts +36 -0
  66. package/dist/explore/targets.operations.js +32 -0
  67. package/dist/explore/utils/draws.d.ts +6 -0
  68. package/dist/explore/utils/draws.js +2 -0
  69. package/dist/explore/utils/edits.d.ts +15 -0
  70. package/dist/explore/utils/edits.js +151 -0
  71. package/dist/explore/utils/guide.d.ts +23 -0
  72. package/dist/explore/utils/guide.js +35 -0
  73. package/dist/explore/utils/keep.d.ts +10 -0
  74. package/dist/explore/utils/keep.js +61 -0
  75. package/dist/explore/utils/pools.d.ts +17 -0
  76. package/dist/explore/utils/pools.js +121 -0
  77. package/dist/explore/utils/reads.d.ts +19 -0
  78. package/dist/explore/utils/reads.js +118 -0
  79. package/dist/explore/utils/twin.d.ts +21 -0
  80. package/dist/explore/utils/twin.js +55 -0
  81. package/dist/forks/forks.operations.d.ts +32 -0
  82. package/dist/forks/forks.operations.js +134 -0
  83. package/dist/forks/forks.schema.d.ts +20 -0
  84. package/dist/forks/forks.schema.js +14 -0
  85. package/dist/graph/cfg/cfg.d.ts +28 -0
  86. package/dist/graph/cfg/cfg.js +31 -0
  87. package/dist/graph/cfg/code-paths/analyzer.d.ts +27 -0
  88. package/dist/graph/cfg/code-paths/analyzer.js +358 -0
  89. package/dist/graph/cfg/code-paths/segments.d.ts +44 -0
  90. package/dist/graph/cfg/code-paths/segments.js +105 -0
  91. package/dist/graph/cfg/code-paths/state.d.ts +121 -0
  92. package/dist/graph/cfg/code-paths/state.js +611 -0
  93. package/dist/graph/cfg/entries.d.ts +13 -0
  94. package/dist/graph/cfg/entries.js +120 -0
  95. package/dist/graph/cfg/functions.d.ts +6 -0
  96. package/dist/graph/cfg/functions.js +47 -0
  97. package/dist/graph/cfg/paths.d.ts +27 -0
  98. package/dist/graph/cfg/paths.js +91 -0
  99. package/dist/graph/cfg/scopes/scopes.d.ts +40 -0
  100. package/dist/graph/cfg/scopes/scopes.js +375 -0
  101. package/dist/graph/symbols/file.d.ts +90 -0
  102. package/dist/graph/symbols/file.js +427 -0
  103. package/dist/graph/symbols/keys.d.ts +13 -0
  104. package/dist/graph/symbols/keys.js +22 -0
  105. package/dist/graph/symbols/resolve.operations.d.ts +4 -0
  106. package/dist/graph/symbols/resolve.operations.js +33 -0
  107. package/dist/graph/symbols/symbols.d.ts +12 -0
  108. package/dist/graph/symbols/symbols.js +155 -0
  109. package/dist/graph/symbols/symbols.schema.d.ts +32 -0
  110. package/dist/graph/symbols/symbols.schema.js +19 -0
  111. package/dist/graph/unused/tests.d.ts +7 -0
  112. package/dist/graph/unused/tests.js +95 -0
  113. package/dist/graph/unused/unused.d.ts +53 -0
  114. package/dist/graph/unused/unused.js +319 -0
  115. package/dist/graph/walk/walk.d.ts +7 -0
  116. package/dist/graph/walk/walk.js +39 -0
  117. package/dist/instrument/instrument.operations.d.ts +72 -0
  118. package/dist/instrument/instrument.operations.js +786 -0
  119. package/dist/instrument/instrument.schema.d.ts +257 -0
  120. package/dist/instrument/instrument.schema.js +100 -0
  121. package/dist/judge/counters.d.ts +86 -0
  122. package/dist/judge/counters.js +402 -0
  123. package/dist/judge/edges/api.d.ts +14 -0
  124. package/dist/judge/edges/api.js +80 -0
  125. package/dist/judge/edges/completion.reporter.d.ts +9 -0
  126. package/dist/judge/edges/completion.reporter.js +51 -0
  127. package/dist/judge/edges/hints.reporter.d.ts +13 -0
  128. package/dist/judge/edges/hints.reporter.js +29 -0
  129. package/dist/judge/edges/judge.edges.d.ts +52 -0
  130. package/dist/judge/edges/judge.edges.js +59 -0
  131. package/dist/judge/edges/judge.fs.d.ts +8 -0
  132. package/dist/judge/edges/judge.fs.js +45 -0
  133. package/dist/judge/edges/merge.d.ts +11 -0
  134. package/dist/judge/edges/merge.js +60 -0
  135. package/dist/judge/edges/plugin.d.ts +132 -0
  136. package/dist/judge/edges/plugin.js +441 -0
  137. package/dist/judge/edges/reach.d.ts +68 -0
  138. package/dist/judge/edges/reach.js +132 -0
  139. package/dist/judge/edges/speed.d.ts +32 -0
  140. package/dist/judge/edges/speed.js +34 -0
  141. package/dist/judge/edges/strays.d.ts +1 -0
  142. package/dist/judge/edges/strays.js +14 -0
  143. package/dist/judge/edges/vitest.d.ts +20 -0
  144. package/dist/judge/edges/vitest.js +36 -0
  145. package/dist/judge/edges/vitest.schema.d.ts +14 -0
  146. package/dist/judge/edges/vitest.schema.js +16 -0
  147. package/dist/judge/explore.test.d.ts +1 -0
  148. package/dist/judge/explore.test.js +101 -0
  149. package/dist/judge/hints.d.ts +11 -0
  150. package/dist/judge/hints.js +44 -0
  151. package/dist/judge/judge.operations.d.ts +218 -0
  152. package/dist/judge/judge.operations.js +464 -0
  153. package/dist/judge/judge.schema.d.ts +135 -0
  154. package/dist/judge/judge.schema.js +129 -0
  155. package/dist/judge/judge.shard-1.test.d.ts +1 -0
  156. package/dist/judge/judge.shard-1.test.js +3 -0
  157. package/dist/judge/judge.shard-2.test.d.ts +1 -0
  158. package/dist/judge/judge.shard-2.test.js +3 -0
  159. package/dist/judge/judge.test.d.ts +1 -0
  160. package/dist/judge/judge.test.js +3 -0
  161. package/dist/judge/refusals.d.ts +14 -0
  162. package/dist/judge/refusals.js +10 -0
  163. package/dist/judge/report.test.d.ts +1 -0
  164. package/dist/judge/report.test.js +432 -0
  165. package/dist/judge/runner.d.ts +3 -0
  166. package/dist/judge/runner.js +1602 -0
  167. package/dist/judge/stresses.test.d.ts +1 -0
  168. package/dist/judge/stresses.test.js +12 -0
  169. package/dist/judge/task-meta.d.ts +14 -0
  170. package/dist/judge/task-meta.js +1 -0
  171. package/dist/justify/edges/load.d.ts +7 -0
  172. package/dist/justify/edges/load.js +40 -0
  173. package/dist/justify/edges/refresh.fs.d.ts +8 -0
  174. package/dist/justify/edges/refresh.fs.js +15 -0
  175. package/dist/justify/justify.operations.d.ts +46 -0
  176. package/dist/justify/justify.operations.js +80 -0
  177. package/dist/justify/justify.schema.d.ts +21 -0
  178. package/dist/justify/justify.schema.js +11 -0
  179. package/dist/mutators/arithmetic-operator.mutator.d.ts +2 -0
  180. package/dist/mutators/arithmetic-operator.mutator.js +22 -0
  181. package/dist/mutators/array-declaration.mutator.d.ts +2 -0
  182. package/dist/mutators/array-declaration.mutator.js +12 -0
  183. package/dist/mutators/arrow-function.mutator.d.ts +2 -0
  184. package/dist/mutators/arrow-function.mutator.js +10 -0
  185. package/dist/mutators/assignment-operator.mutator.d.ts +2 -0
  186. package/dist/mutators/assignment-operator.mutator.js +29 -0
  187. package/dist/mutators/await-expression.mutator.d.ts +2 -0
  188. package/dist/mutators/await-expression.mutator.js +7 -0
  189. package/dist/mutators/bitwise-operator.mutator.d.ts +2 -0
  190. package/dist/mutators/bitwise-operator.mutator.js +19 -0
  191. package/dist/mutators/block-statement.mutator.d.ts +2 -0
  192. package/dist/mutators/block-statement.mutator.js +30 -0
  193. package/dist/mutators/boolean-literal.mutator.d.ts +2 -0
  194. package/dist/mutators/boolean-literal.mutator.js +5 -0
  195. package/dist/mutators/coercion.mutator.d.ts +2 -0
  196. package/dist/mutators/coercion.mutator.js +28 -0
  197. package/dist/mutators/conditional-expression.mutator.d.ts +2 -0
  198. package/dist/mutators/conditional-expression.mutator.js +36 -0
  199. package/dist/mutators/disposal.mutator.d.ts +2 -0
  200. package/dist/mutators/disposal.mutator.js +13 -0
  201. package/dist/mutators/empty-destructuring.mutator.d.ts +2 -0
  202. package/dist/mutators/empty-destructuring.mutator.js +35 -0
  203. package/dist/mutators/empty-return.mutator.d.ts +2 -0
  204. package/dist/mutators/empty-return.mutator.js +35 -0
  205. package/dist/mutators/equality-operator.mutator.d.ts +2 -0
  206. package/dist/mutators/equality-operator.mutator.js +16 -0
  207. package/dist/mutators/loop-exit.mutator.d.ts +2 -0
  208. package/dist/mutators/loop-exit.mutator.js +5 -0
  209. package/dist/mutators/method-expression.mutator.d.ts +2 -0
  210. package/dist/mutators/method-expression.mutator.js +59 -0
  211. package/dist/mutators/missing-lookup.mutator.d.ts +2 -0
  212. package/dist/mutators/missing-lookup.mutator.js +25 -0
  213. package/dist/mutators/mutator.d.ts +40 -0
  214. package/dist/mutators/mutator.js +49 -0
  215. package/dist/mutators/mutator.names.d.ts +3 -0
  216. package/dist/mutators/mutator.names.js +43 -0
  217. package/dist/mutators/mutators.d.ts +8 -0
  218. package/dist/mutators/mutators.js +84 -0
  219. package/dist/mutators/nested-condition.mutator.d.ts +2 -0
  220. package/dist/mutators/nested-condition.mutator.js +16 -0
  221. package/dist/mutators/number-literal.mutator.d.ts +3 -0
  222. package/dist/mutators/number-literal.mutator.js +13 -0
  223. package/dist/mutators/object-literal.mutator.d.ts +2 -0
  224. package/dist/mutators/object-literal.mutator.js +6 -0
  225. package/dist/mutators/odd-number.mutator.d.ts +2 -0
  226. package/dist/mutators/odd-number.mutator.js +15 -0
  227. package/dist/mutators/operand-deletion.mutator.d.ts +2 -0
  228. package/dist/mutators/operand-deletion.mutator.js +9 -0
  229. package/dist/mutators/outcome.mutator.d.ts +3 -0
  230. package/dist/mutators/outcome.mutator.js +45 -0
  231. package/dist/mutators/plain-assignment.mutator.d.ts +2 -0
  232. package/dist/mutators/plain-assignment.mutator.js +7 -0
  233. package/dist/mutators/power-operator.mutator.d.ts +2 -0
  234. package/dist/mutators/power-operator.mutator.js +13 -0
  235. package/dist/mutators/private-brand.mutator.d.ts +2 -0
  236. package/dist/mutators/private-brand.mutator.js +7 -0
  237. package/dist/mutators/regex.mutator.d.ts +2 -0
  238. package/dist/mutators/regex.mutator.js +29 -0
  239. package/dist/mutators/short-iteration.mutator.d.ts +2 -0
  240. package/dist/mutators/short-iteration.mutator.js +8 -0
  241. package/dist/mutators/string-literal.mutator.d.ts +3 -0
  242. package/dist/mutators/string-literal.mutator.js +149 -0
  243. package/dist/mutators/switch-default.mutator.d.ts +2 -0
  244. package/dist/mutators/switch-default.mutator.js +13 -0
  245. package/dist/mutators/sync-iteration.mutator.d.ts +3 -0
  246. package/dist/mutators/sync-iteration.mutator.js +9 -0
  247. package/dist/mutators/thrown-call.mutator.d.ts +2 -0
  248. package/dist/mutators/thrown-call.mutator.js +7 -0
  249. package/dist/mutators/unary-operator.mutator.d.ts +2 -0
  250. package/dist/mutators/unary-operator.mutator.js +18 -0
  251. package/dist/mutators/unbound-call.mutator.d.ts +2 -0
  252. package/dist/mutators/unbound-call.mutator.js +14 -0
  253. package/dist/mutators/update-operator.mutator.d.ts +2 -0
  254. package/dist/mutators/update-operator.mutator.js +15 -0
  255. package/dist/mutators/yield-value.mutator.d.ts +2 -0
  256. package/dist/mutators/yield-value.mutator.js +7 -0
  257. package/dist/parity/compare.d.ts +27 -0
  258. package/dist/parity/compare.js +26 -0
  259. package/dist/parity/corpus.parity.d.ts +1 -0
  260. package/dist/parity/corpus.parity.js +97 -0
  261. package/dist/parity/edges/corpus.fs.d.ts +3 -0
  262. package/dist/parity/edges/corpus.fs.js +30 -0
  263. package/dist/parity/edges/ports.d.ts +2 -0
  264. package/dist/parity/edges/ports.js +21 -0
  265. package/dist/parity/edges/vitest.d.ts +2 -0
  266. package/dist/parity/edges/vitest.js +3 -0
  267. package/dist/parity/parity.operations.d.ts +33 -0
  268. package/dist/parity/parity.operations.js +60 -0
  269. package/dist/parity/parity.schema.d.ts +5 -0
  270. package/dist/parity/parity.schema.js +6 -0
  271. package/dist/parity/stryker/compare.d.ts +14 -0
  272. package/dist/parity/stryker/compare.js +52 -0
  273. package/dist/parity/stryker/edges/ports.d.ts +12 -0
  274. package/dist/parity/stryker/edges/ports.js +28 -0
  275. package/dist/parity/stryker/equivalence.d.ts +1 -0
  276. package/dist/parity/stryker/equivalence.js +42 -0
  277. package/dist/parity/stryker/intended.d.ts +29 -0
  278. package/dist/parity/stryker/intended.js +152 -0
  279. package/dist/parity/stryker/normalize.d.ts +27 -0
  280. package/dist/parity/stryker/normalize.js +181 -0
  281. package/dist/parity/stryker/rules.d.ts +6 -0
  282. package/dist/parity/stryker/rules.js +116 -0
  283. package/dist/parity/stryker/sides.d.ts +46 -0
  284. package/dist/parity/stryker/sides.js +199 -0
  285. package/dist/parity/stryker/stryker.parity.d.ts +1 -0
  286. package/dist/parity/stryker/stryker.parity.js +147 -0
  287. package/dist/parity/stryker/stryker.schema.d.ts +6 -0
  288. package/dist/parity/stryker/stryker.schema.js +7 -0
  289. package/dist/parity/views.d.ts +21 -0
  290. package/dist/parity/views.js +119 -0
  291. package/dist/questions/questions.operations.d.ts +110 -0
  292. package/dist/questions/questions.operations.js +446 -0
  293. package/dist/questions/questions.schema.d.ts +57 -0
  294. package/dist/questions/questions.schema.js +28 -0
  295. package/dist/record/edges/calls.db.d.ts +10 -0
  296. package/dist/record/edges/calls.db.js +91 -0
  297. package/dist/record/edges/hits.db.d.ts +3 -0
  298. package/dist/record/edges/hits.db.js +5 -0
  299. package/dist/record/edges/holds.db.d.ts +4 -0
  300. package/dist/record/edges/holds.db.js +31 -0
  301. package/dist/record/edges/judged-state.db.d.ts +5 -0
  302. package/dist/record/edges/judged-state.db.js +25 -0
  303. package/dist/record/edges/markers.db.d.ts +11 -0
  304. package/dist/record/edges/markers.db.js +55 -0
  305. package/dist/record/edges/merge.db.d.ts +7 -0
  306. package/dist/record/edges/merge.db.js +46 -0
  307. package/dist/record/edges/parts.db.d.ts +42 -0
  308. package/dist/record/edges/parts.db.js +389 -0
  309. package/dist/record/edges/parts.edges.d.ts +2 -0
  310. package/dist/record/edges/parts.edges.js +7 -0
  311. package/dist/record/edges/parts.fs.d.ts +1 -0
  312. package/dist/record/edges/parts.fs.js +11 -0
  313. package/dist/record/edges/parts.writer.d.ts +1 -0
  314. package/dist/record/edges/parts.writer.js +85 -0
  315. package/dist/record/edges/passes.db.d.ts +19 -0
  316. package/dist/record/edges/passes.db.js +31 -0
  317. package/dist/record/edges/plan.db.d.ts +21 -0
  318. package/dist/record/edges/plan.db.js +174 -0
  319. package/dist/record/edges/reach.db.d.ts +6 -0
  320. package/dist/record/edges/reach.db.js +62 -0
  321. package/dist/record/edges/record.db.d.ts +22 -0
  322. package/dist/record/edges/record.db.js +176 -0
  323. package/dist/record/edges/record.fs.d.ts +3 -0
  324. package/dist/record/edges/record.fs.js +7 -0
  325. package/dist/record/edges/site-verdicts.db.d.ts +11 -0
  326. package/dist/record/edges/site-verdicts.db.js +66 -0
  327. package/dist/record/edges/verified.db.d.ts +7 -0
  328. package/dist/record/edges/verified.db.js +71 -0
  329. package/dist/record/parts.operations.d.ts +26 -0
  330. package/dist/record/parts.operations.js +31 -0
  331. package/dist/record/path-checks.operations.d.ts +15 -0
  332. package/dist/record/path-checks.operations.js +84 -0
  333. package/dist/record/record.operations.d.ts +36 -0
  334. package/dist/record/record.operations.js +11 -0
  335. package/dist/stresses/edges/stresses.record.d.ts +4 -0
  336. package/dist/stresses/edges/stresses.record.js +37 -0
  337. package/dist/stresses/stresses.operations.d.ts +28 -0
  338. package/dist/stresses/stresses.operations.js +22 -0
  339. package/dist/utils/ast.d.ts +55 -0
  340. package/dist/utils/ast.js +181 -0
  341. package/dist/utils/errors.d.ts +8 -0
  342. package/dist/utils/errors.js +12 -0
  343. package/dist/utils/faults.d.ts +6 -0
  344. package/dist/utils/faults.js +10 -0
  345. package/dist/utils/lookup.d.ts +4 -0
  346. package/dist/utils/lookup.js +27 -0
  347. package/dist/utils/order.d.ts +2 -0
  348. package/dist/utils/order.js +17 -0
  349. package/dist/utils/retry.d.ts +14 -0
  350. package/dist/utils/retry.js +15 -0
  351. package/dist/utils/safe.d.ts +11 -0
  352. package/dist/utils/safe.js +31 -0
  353. package/migrations/main/20261129123324_initial/migration.sql +418 -0
  354. package/migrations/main/20261129123324_initial/snapshot.json +3641 -0
  355. package/package.json +89 -4
  356. package/references/consumer-setup.md +92 -0
  357. package/src/graph/cfg/code-paths/LICENSE +21 -0
  358. package/src/graph/cfg/scopes/LICENSE +24 -0
@@ -0,0 +1,446 @@
1
+ import { outcomeMutatorName } from '../mutators/mutator.names.js';
2
+ import { groupedBooleanReplacements } from '../mutators/mutator.js';
3
+ import { stepLimitFactor, stepLimitFloor } from '../judge/counters.js';
4
+ import { unitKeyOf } from '../record/record.operations.js';
5
+ import { entryAt, itemAt } from '../utils/lookup.js';
6
+ // Matches a run of backticks.
7
+ const backtickRunPattern = /`+/g;
8
+ // Matches a line break with the indentation around it.
9
+ const lineBreakPattern = /\s*\n\s*/g;
10
+ // Quotes code on one line the way Markdown does, fenced by one backtick more than its longest run and padded when it starts or ends with one.
11
+ export const quote = (code) => {
12
+ const flat = code.replace(lineBreakPattern, ' ').trim();
13
+ const longest = Math.max(0, ...(flat.match(backtickRunPattern) ?? []).map((run) => run.length));
14
+ const fence = '`'.repeat(longest + 1);
15
+ const pad = flat.startsWith('`') || flat.endsWith('`') ? ' ' : '';
16
+ return `${fence}${pad}${flat}${pad}${fence}`;
17
+ };
18
+ // The function a question sits in, or the module's top level when it sits in none.
19
+ const ownerOf = (name) => (name ? quote(name) : 'the module');
20
+ // Each kind's ask and its two answers, yes first.
21
+ const wordings = {
22
+ crush: ({ function: name, code }) => ({ ask: `No test fails without ${quote(code)} in ${ownerOf(name)}. Remove it?`, answers: ['yes: remove it', 'no: add a test that fails without it'] }),
23
+ reach: ({ function: name, code }) => ({ ask: `Can any input run ${quote(code)} in ${ownerOf(name)}?`, answers: ['yes: add that input', 'no: delete it'] }),
24
+ call: ({ code }) => ({ ask: `Can any input call ${quote(code)}?`, answers: ['yes: add a test that calls it', 'no: delete it'] }),
25
+ matter: ({ function: name, code }) => ({ ask: `Should ${quote(code)} matter in ${ownerOf(name)}?`, answers: ['yes: add an input where its value changes the result', 'no: remove it'] }),
26
+ side: ({ function: name, code, replacement: side }) => {
27
+ // A loop's second pass is no truth of its test, so it asks for a pass rather than a value.
28
+ if (side === 'repeat')
29
+ return { ask: `Can any input run ${quote(code)} more than once in ${ownerOf(name)}?`, answers: ['yes: add that input', 'no: let it run once'] };
30
+ return { ask: `Can any input make ${quote(code)} ${side} in ${ownerOf(name)}?`, answers: ['yes: add that input', `no: remove what runs when it is ${side}`] };
31
+ },
32
+ tell: ({ function: name, code, replacement }) => {
33
+ // A mutant replacing its code with nothing deletes it, so the question names the removal rather than an empty fence.
34
+ if (!replacement)
35
+ return { ask: `Can any input tell ${quote(code)} from its removal in ${ownerOf(name)}?`, answers: ['yes: add that input', 'no: remove it'] };
36
+ return { ask: `Can any input tell ${quote(code)} from ${quote(replacement)} in ${ownerOf(name)}?`, answers: ['yes: add that input', `no: use ${quote(replacement)}`] };
37
+ },
38
+ test: ({ code }) => ({ ask: `Every change ${quote(code)} catches, a kept test also catches, and it is nowhere the only test. Remove it?`, answers: ['yes: remove it', 'no: keep it with `{ meta: { keeps: <reason> } }`'] }),
39
+ // A file names itself, where an export or a function is named in its file.
40
+ // A removal that leaves imports unread names them, so removing them together compiles.
41
+ unused: ({ file, code, replacement: alongside }) => {
42
+ const what = code === file ? quote(file) : `${quote(code)} in ${quote(file)}`;
43
+ const removal = alongside ? `Remove it and its import of ${alongside.split(', ').map(quote).join(', ')}?` : 'Remove it?';
44
+ return { ask: `Nothing reaches ${what} from the entries or tests. ${removal}`, answers: ['yes: remove it', 'no: add it to the entries or a test'] };
45
+ },
46
+ unexport: ({ file, code }) => ({ ask: `Only ${quote(file)} itself reads ${quote(code)}. Unexport it?`, answers: ['yes: drop its `export`', 'no: import it where it is needed, or add a test that does'] }),
47
+ // A shared test file is never removed whole: the tests reaching only this code go with it, and those also reaching live code drop their use of it.
48
+ testonly: ({ file, code, replacement }) => {
49
+ const [only = '', shared = '', unnamed = ''] = replacement.split('\0');
50
+ const listed = (tests) => tests.split('\n').filter(Boolean).map(quote).join(', ');
51
+ const removal = only ? `the tests, hooks and groups that reach only it (${listed(only)})` : 'its import in the tests';
52
+ const dropping = shared ? `, dropping it from ${listed(shared)}` : '';
53
+ // A test crush cannot name, as an `each` row, still reaches the code, so its file is named rather than left out.
54
+ const unnamedNote = unnamed ? ` Tests crush could not name call it: ${listed(unnamed)}.` : '';
55
+ return {
56
+ ask: `Only tests reach ${code === file ? quote(file) : `${quote(code)} in ${quote(file)}`}. Remove it and ${removal}${dropping}, or add it to the entries?${unnamedNote}`,
57
+ answers: ['yes: remove it and the tests, hooks and groups that reach only it', 'no: add it to the entries'],
58
+ };
59
+ },
60
+ untested: ({ file, code }) => ({ ask: `No test reads the pattern ${quote(code)} in ${quote(file)}. Test it?`, answers: ['yes: add a test that reads it', 'no: drop its `export`'] }),
61
+ // An explore question names the input that failed and what it failed, a throw site or a property, since a varied seed made it.
62
+ explore: ({ function: name, code, replacement: input }) => ({
63
+ ask: `Explore called ${ownerOf(name)} with ${quote(input)} and it failed ${quote(code)}, which no test covers. Is that input one a caller can send?`,
64
+ answers: ['yes: fix the code, with a test that fails before the fix, then run explore again', 'no: refuse the input where it enters with a parse or guard, or justify it'],
65
+ }),
66
+ behavior: ({ function: name, code }) => ({ ask: `What should ${ownerOf(name)} give at ${quote(code)}?`, answers: ['yes: add a case answering this question with its output', 'no: remove that outcome'] }),
67
+ 'same-result': ({ function: name, code }) => ({
68
+ ask: `The recorded paths parting at ${quote(code)} in ${ownerOf(name)} give the same result. Can any input tell them apart?`,
69
+ answers: ['yes: add a test with an input that tells them apart', 'no: justify why the paths give the same result'],
70
+ }),
71
+ 'no-split': ({ function: name, code }) => ({
72
+ ask: `Both recorded sides of ${quote(code)} in ${ownerOf(name)} give the same result. Can any input make them differ?`,
73
+ answers: ['yes: add a test with an input that makes them differ', 'no: justify why the sides give the same result'],
74
+ }),
75
+ };
76
+ // Source snippets can span several lines. Test titles and graph names are identifiers.
77
+ const sourceQuestionKinds = new Set(['crush', 'reach', 'side', 'tell', 'matter', 'behavior', 'same-result', 'no-split']);
78
+ // Matches a JavaScript line terminator.
79
+ const multilinePattern = /[\r\n\u2028\u2029]/;
80
+ // One question per open item, numbered by occurrence of the same code in one function.
81
+ const idsOf = (items) => {
82
+ const seen = new Map();
83
+ return items.map(({ kind, file, function: owner, code: source }) => {
84
+ let code = source;
85
+ if (sourceQuestionKinds.has(kind) && multilinePattern.test(source))
86
+ code = owner && !multilinePattern.test(owner) ? owner : '{…}';
87
+ const key = JSON.stringify([kind, file, owner, code]);
88
+ const occurrence = seen.get(key) ?? 0;
89
+ seen.set(key, occurrence + 1);
90
+ return [kind, file, owner, String(occurrence), code].map((field) => field.replaceAll('%', '%25').replaceAll('|', '%7C')).join('|');
91
+ });
92
+ };
93
+ export const questionsOf = (items) => {
94
+ const ids = idsOf(items);
95
+ return items.map((item, index) => ({ id: itemAt(ids, index), kind: item.kind, ...wordings[item.kind](item) }));
96
+ };
97
+ const crushWordingOf = ({ crush, code, owner, side, forcedEffect }) => {
98
+ const named = quote(code);
99
+ const where = ownerOf(owner);
100
+ const forced = side === 'false' ? 'true' : 'false';
101
+ switch (crush) {
102
+ case 'loop-once':
103
+ return { ask: `Does any input need a second pass through the loop on ${named} in ${where}?`, answers: ['yes: add that input', 'no: limit the loop to one pass'] };
104
+ case 'force-fork': {
105
+ if (forcedEffect) {
106
+ const { code: expression, kind, always } = forcedEffect;
107
+ const frequency = always ? 'always' : 'never';
108
+ const what = `${quote(expression)} in ${where} ${frequency}`;
109
+ if (kind === 'logicalAssign')
110
+ return { ask: `Can any input tell if ${what} writes?`, answers: ['yes: add that input', always ? 'no: always assign' : 'no: omit the write'] };
111
+ return { ask: `Can any input tell if ${what} evaluates its right operand?`, answers: ['yes: add that input', `no: ${frequency} evaluate the right operand`] };
112
+ }
113
+ return { ask: `Can any input tell when ${named} is always ${forced} in ${where}?`, answers: ['yes: add that input', `no: treat it as always ${forced}`] };
114
+ }
115
+ case 'callback':
116
+ return { ask: `Can any input tell when the callback with body ${named} in ${where} always returns ${forced}?`, answers: ['yes: add that input', `no: always return ${forced}`] };
117
+ case 'default-value':
118
+ return { ask: `Can any input tell when ${named} has no default in ${where}?`, answers: ['yes: add that input', 'no: drop the default'] };
119
+ case 'optional-chain':
120
+ return side === 'true'
121
+ ? { ask: `Can any input tell when ${named} in ${where} always continues the chain?`, answers: ['yes: add that input', 'no: make the link non-optional'] }
122
+ : { ask: `Can any input tell when ${named} in ${where} always short-circuits?`, answers: ['yes: add that input', 'no: always short-circuit the chain'] };
123
+ default:
124
+ return undefined;
125
+ }
126
+ };
127
+ // The span a site sits on, the code at one place in its file.
128
+ const spanOf = ({ file, start, code }) => JSON.stringify([file, start, code]);
129
+ // No named function, none entered and no fork point taken.
130
+ const noFunctions = { named: new Set(), enteredBy: new Map(), taken: new Set() };
131
+ // Every question each site could ask, ids built over all sites whatever their status, so closing one question never moves another's id; then the open ones.
132
+ // A survived crush asks whether to crush it, a survived mutant whether any input tells it apart, and unreached code asks once per span whether any input runs it.
133
+ // A held crush asks nothing, since a test fails with it forced alongside the others.
134
+ // A span ran once a site on it was reached, or once a test took a loop's fork point, whose first pass no loop-once crush rides.
135
+ export const siteQuestionsOf = (sites, held = new Set(), takenPoints = new Set(), functions = noFunctions) => {
136
+ // An outcome asks what its function should give, and numbers apart from tell questions, so adding outcomes moves no other question's id.
137
+ const kindOf = (site) => (site.mutator === outcomeMutatorName ? 'behavior' : site.kind);
138
+ const asking = sites.map((site) => ({ kind: kindOf(site), file: site.file, function: site.owner, code: site.code, replacement: site.replacement }));
139
+ const own = questionsOf(asking).map((question, index) => {
140
+ const site = itemAt(sites, index);
141
+ return Object.assign(question, site.kind === 'crush' ? crushWordingOf(site) : undefined, { sites: [site.key], file: site.file, line: site.line });
142
+ });
143
+ // A fork side no test takes asks for that side, where the rest of its code ran; it asks nothing of its own when nothing on its span ran, which the reach question covers.
144
+ // Only a crush names a side, a mutant's being empty.
145
+ const sideSites = sites.flatMap((site, index) => (site.side && site.side !== 'repeat' ? [{ site, item: itemAt(asking, index) }] : []));
146
+ const side = questionsOf(sideSites.map(({ site, item }) => ({ ...item, kind: 'side', replacement: site.side }))).map((question, index) => {
147
+ const { site } = itemAt(sideSites, index);
148
+ return Object.assign(question, { sites: [site.key], file: site.file, line: site.line });
149
+ });
150
+ const reachBySpan = new Map();
151
+ for (const [index, site] of sites.entries()) {
152
+ const span = spanOf(site);
153
+ const kept = reachBySpan.get(span) ?? { item: { ...itemAt(asking, index), kind: 'reach', replacement: '' }, sites: [], line: site.line };
154
+ kept.sites.push(site);
155
+ reachBySpan.set(span, kept);
156
+ }
157
+ const spans = [...reachBySpan.values()];
158
+ const reach = questionsOf(spans.map(({ item }) => item)).map((question, index) => {
159
+ const span = itemAt(spans, index);
160
+ return Object.assign(question, { sites: span.sites.map(({ key }) => key), file: span.item.file, line: span.line });
161
+ });
162
+ // A loop's first pass, and a dropped operand taken either way, ran code no crush on the span rides; a forced fork's point is its whole test, which proves no side.
163
+ const isPointProof = (site) => (site.side === 'repeat' || site.crush === 'drop-operand') && takenPoints.has(site.point);
164
+ const ranSpans = new Set(sites.filter((site) => site.status !== 'unreached' || isPointProof(site)).map(spanOf));
165
+ const isOpenOwn = (site) => site.status === 'survived' && !held.has(site.key);
166
+ const isOpenSide = (site) => site.status === 'unreached' && ranSpans.has(spanOf(site));
167
+ const isOpenReach = (site) => site.status === 'unreached' && !(site.side && ranSpans.has(spanOf(site)));
168
+ const isAsked = [...own.map((_, index) => isOpenOwn(itemAt(sites, index))), ...side.map((_, index) => isOpenSide(itemAt(sideSites, index).site)), ...reach.map((_, index) => itemAt(spans, index).sites.some(isOpenReach))];
169
+ const calls = callQuestionsOf(sites, functions, (site) => site.status !== 'unreached' || functions.taken.has(site.point));
170
+ const matters = matterQuestionsOf(sites);
171
+ const byKey = new Map(sites.map((site) => [site.key, site]));
172
+ const siteAt = (key) => entryAt(byKey, key, `the site ${key}`);
173
+ // One question stands for several: code in an uncalled function asks only its call question, code inside a longer span no test reached asks only that span's, and an expression surviving forced both ways asks only whether it matters.
174
+ // A site is checked only against its own file's dead spans in its own function or one holding it, so a project's many files never multiply the check.
175
+ const deadIn = Map.groupBy(sites.filter((site) => site.status === 'unreached' && !ranSpans.has(spanOf(site))), ({ file }) => file);
176
+ const endOf = (site) => site.start + site.code.length;
177
+ const isHeldBy = (site, span) => site.owner === span.owner || site.owner.startsWith(`${span.owner}.`);
178
+ const isInDead = (site) => (deadIn.get(site.file) ?? []).some((span) => span.code.length > site.code.length && span.start <= site.start && endOf(site) <= endOf(span) && isHeldBy(site, span));
179
+ const covered = new Set(calls.open.flatMap(({ sites: keys }) => keys));
180
+ const matterKeys = new Set(matters.open.flatMap(({ sites: keys }) => keys));
181
+ const isFolded = (question) => question.sites.every((key) => covered.has(key) || isInDead(siteAt(key)) || matterKeys.has(key));
182
+ // Two questions asking the very same thing of one span, as two mutators making one edit do, are one question naming both sites, whatever either's status, so its id and sites hold as either closes.
183
+ const merged = new Map();
184
+ for (const [index, question] of [...own, ...side, ...reach].entries()) {
185
+ const isOpen = itemAt(isAsked, index) && !isFolded(question);
186
+ const key = JSON.stringify([question.kind, question.ask, question.file, siteAt(itemAt(question.sites, 0)).start]);
187
+ const kept = merged.get(key);
188
+ if (!kept) {
189
+ merged.set(key, { question: { ...question, sites: [...question.sites] }, isOpen });
190
+ continue;
191
+ }
192
+ kept.question.sites.push(...question.sites);
193
+ kept.isOpen ||= isOpen;
194
+ }
195
+ const asked = [...merged.values()];
196
+ const all = [...asked.map(({ question }) => question), ...calls.all, ...matters.all];
197
+ const open = [...calls.open, ...asked.filter(({ isOpen }) => isOpen).map(({ question }) => question), ...matters.open];
198
+ // Planned operand sites identify the test's operands. The force-fork edit identifies the text its dead side would remove.
199
+ const operands = new Set(sites.filter(({ crush }) => crush === 'drop-operand').map(spanOf));
200
+ const openWith = (justified) => {
201
+ const forks = Map.groupBy(open.filter(({ kind, id }) => (kind === 'side' || kind === 'crush') && !justified.has(id)).flatMap(({ sites: keys }) => keys.map(siteAt).filter(({ crush }) => crush === 'force-fork')), ({ file }) => file);
202
+ const forkCovers = (site) => {
203
+ const span = spanOf(site);
204
+ return (forks.get(site.file) ?? []).some((fork) => {
205
+ const isTested = site.kind === 'tell' && (span === spanOf(fork) || (operands.has(span) && fork.start <= site.start && endOf(site) <= endOf(fork)));
206
+ const isDeadSide = fork.status === 'unreached' && site.status === 'unreached' && fork.edits?.some(({ start, end }) => start <= site.start && endOf(site) <= end);
207
+ return isTested || isDeadSide;
208
+ });
209
+ };
210
+ return open.filter((question) => {
211
+ const { kind, sites: keys } = question;
212
+ return (kind !== 'tell' && kind !== 'behavior' && kind !== 'reach' && kind !== 'matter') || !keys.every((key) => forkCovers(siteAt(key)));
213
+ });
214
+ };
215
+ return { all, open: openWith(new Set()), openWith, enteredFor: calls.entering };
216
+ };
217
+ // The functions holding an owner, outermost first: each prefix of its path that names a function, and the owner itself, since a class in the path holds a method without calling it.
218
+ const holdersOf = (file, owner, named) => {
219
+ const parts = owner.split('.');
220
+ return parts.map((_, at) => parts.slice(0, at + 1).join('.')).filter((name) => name === owner || named.has(unitKeyOf(file, name)));
221
+ };
222
+ // A call question for every function holding a site, naming every site it holds, those of the functions it makes included, ids built over all of them so closing one never moves another's; then the ones it asks, each the outermost function no test entered.
223
+ // A function was entered once a baseline entered it, or once any site in it, or in a function it makes, was reached or a test took a fork point there.
224
+ // A site at the module's top level sits in no function, so it is never folded into a call question.
225
+ // Each test that entered a function reaches what its call question asks, though one returning first reaches none of its sites, so the tests entering it are kept by the question's id alone, never as reaching its sites, which other questions ask of.
226
+ const callQuestionsOf = (sites, { named, enteredBy }, hasRun) => {
227
+ const byHolder = Map.groupBy(sites.filter(({ owner }) => owner).flatMap((site) => holdersOf(site.file, site.owner, named).map((holder) => ({ holder, site }))), ({ site, holder }) => JSON.stringify([site.file, holder]));
228
+ const groups = [...byHolder.values()];
229
+ const all = questionsOf(groups.map((group) => ({ kind: 'call', file: itemAt(group, 0).site.file, function: itemAt(group, 0).holder, code: itemAt(group, 0).holder, replacement: '' }))).map((question, index) => {
230
+ const group = itemAt(groups, index);
231
+ return Object.assign(question, { sites: group.map(({ site }) => site.key), file: itemAt(group, 0).site.file, line: Math.min(...group.map(({ site }) => site.line)) });
232
+ });
233
+ const isEntered = (group) => {
234
+ const { site, holder } = itemAt(group, 0);
235
+ return enteredBy.has(unitKeyOf(site.file, holder)) || group.some((each) => hasRun(each.site));
236
+ };
237
+ const entering = new Map(groups.flatMap((group, index) => {
238
+ const { site, holder } = itemAt(group, 0);
239
+ const tests = enteredBy.get(unitKeyOf(site.file, holder));
240
+ return tests ? [[itemAt(all, index).id, tests]] : [];
241
+ }));
242
+ const uncalled = new Set([...byHolder.keys()].filter((_, index) => !isEntered(itemAt(groups, index))));
243
+ // A function is asked of only when no function holding it is, so the outermost uncalled one asks for all inside it.
244
+ const isAskedAt = (index) => {
245
+ const { site, holder } = itemAt(itemAt(groups, index), 0);
246
+ return holdersOf(site.file, holder, named).every((name) => uncalled.has(JSON.stringify([site.file, name])) === (name === holder));
247
+ };
248
+ return { all, open: all.filter((_, index) => isAskedAt(index)), entering };
249
+ };
250
+ // A matter question for every expression with ConditionalExpression mutants forcing it both true and false, ids built over all of them; then the ones it asks, both mutants surviving, rather than two tell questions.
251
+ const matterQuestionsOf = (sites) => {
252
+ const forced = sites.filter(({ mutator, replacement }) => mutator === 'ConditionalExpression' && groupedBooleanReplacements.has(replacement));
253
+ const pairs = [...Map.groupBy(forced, spanOf).values()].filter((group) => new Set(group.map(({ replacement }) => replacement)).size === 2);
254
+ const all = questionsOf(pairs.map((group) => ({ kind: 'matter', file: itemAt(group, 0).file, function: itemAt(group, 0).owner, code: itemAt(group, 0).code, replacement: '' }))).map((question, index) => {
255
+ const group = itemAt(pairs, index);
256
+ return Object.assign(question, { sites: group.map(({ key }) => key), file: itemAt(group, 0).file, line: itemAt(group, 0).line });
257
+ });
258
+ return { all, open: all.filter((_, index) => itemAt(pairs, index).every(({ status }) => status === 'survived')) };
259
+ };
260
+ // The question kind each of the graph's asks raises.
261
+ const askKinds = { remove: 'unused', unexport: 'unexport', test: 'untested', tests: 'testonly' };
262
+ // Every question the whole-project graph could ask of a file, an export or a binding, ids built over all of them so closing one never moves another's; then the ones it asks.
263
+ export const unusedQuestionsOf = (nodes) => {
264
+ const named = nodes.filter(({ kind, name }) => kind !== 'function' && name !== '*');
265
+ const asks = Object.entries(askKinds).map(([ask, kind]) => {
266
+ // A test-only question carries the tests that go with its code and those that only drop it, apart by a NUL, which no test title holds.
267
+ const replacementOf = (node) => (kind === 'testonly' ? `${node.onlyTests}\0${node.sharedTests}\0${node.unnamedTests}` : node.alongside);
268
+ const all = questionsOf(named.map((node) => ({ kind, file: node.file, function: '', code: node.name, replacement: replacementOf(node) }))).map((question, index) => {
269
+ const node = itemAt(named, index);
270
+ return Object.assign(question, { sites: [node.key], file: node.file, line: node.line });
271
+ });
272
+ const askedKeys = new Set(named.filter((node) => node.ask === ask).map(({ key }) => key));
273
+ return { all, open: all.filter(({ sites }) => sites.some((key) => askedKeys.has(key))) };
274
+ });
275
+ return { all: asks.flatMap(({ all }) => all), open: asks.flatMap(({ open }) => open) };
276
+ };
277
+ // One question per finding's site, open until an explore no longer finds it or a justification answers it; a site two targets found is asked once, of the first.
278
+ // Its id names the site alone, never the function that found it, so refreshing which target found a shared site keeps the id an answer names.
279
+ export const exploreQuestionsOf = (all) => {
280
+ const seen = new Set();
281
+ const findings = all.filter(({ key }) => !seen.has(key) && Boolean(seen.add(key)));
282
+ const inputs = findings.map((finding) => ({ kind: 'explore', file: finding.file, function: finding.function, code: finding.key, replacement: finding.input.slice(0, 1024) }));
283
+ const ids = questionsOf(inputs.map((input) => ({ ...input, function: '' })));
284
+ return questionsOf(inputs).map((question, index) => {
285
+ const finding = itemAt(findings, index);
286
+ return Object.assign(question, { id: itemAt(ids, index).id, sites: [finding.key], file: finding.file, line: finding.line });
287
+ });
288
+ };
289
+ export const pathQuestionsOf = (findings) => {
290
+ return questionsOf(findings.map(({ kind, file, function: name, code }) => ({ kind, file, function: name, code, replacement: '' }))).map((question, index) => {
291
+ const { file, line, siteKey, uncompared } = itemAt(findings, index);
292
+ // A justification resting on calls crush never compared is unproven, so the question says how many it left out.
293
+ const note = `note: ${uncompared} ${uncompared === 1 ? 'call' : 'calls'} passed an argument crush could not copy, so a no rests on calls it never compared`;
294
+ const answers = uncompared ? [...question.answers, note] : question.answers;
295
+ return Object.assign(question, { file, line, sites: [siteKey], answers });
296
+ });
297
+ };
298
+ // Which tests catch each explore finding's key: a throw finding by a test whose call threw from its site, as a regression test for it does, and a property finding by a test that calls the property.
299
+ // Only an export explore has run as a property counts as one, so a test calling a helper of its own file answers nothing.
300
+ export const exploreCaughtOf = ({ calls, properties }) => {
301
+ const caught = new Map();
302
+ const note = (key, test) => {
303
+ caught.set(key, (caught.get(key) ?? new Set()).add(test));
304
+ };
305
+ for (const { exportKey, testKey, thrownAt } of calls) {
306
+ if (thrownAt)
307
+ note(thrownAt, testKey);
308
+ if (properties.has(exportKey))
309
+ note(exportKey, testKey);
310
+ }
311
+ return caught;
312
+ };
313
+ // The question kinds a test answers by reaching what they name, its code or a node of the graph.
314
+ // A test-only question is answered in the entries or by removal, never by a test, which reaching it already does.
315
+ export const reachingKinds = new Set(['reach', 'call', 'side', askKinds.remove, askKinds.unexport, askKinds.test]);
316
+ const evidenceFor = (question, { caughtBy, reachedBy, enteredFor }) => {
317
+ if (question.kind === 'call')
318
+ return { keys: [question.id], testsByKey: enteredFor };
319
+ return { keys: question.sites, testsByKey: reachingKinds.has(question.kind) ? reachedBy : caughtBy };
320
+ };
321
+ export const answerProblemsOf = (answers, all, evidence) => {
322
+ const byId = new Map(all.map((question) => [question.id, question]));
323
+ return answers.flatMap((answer) => {
324
+ const question = byId.get(answer.id);
325
+ if (!question)
326
+ return [{ ...answer, problem: 'names no question crush asks, so remove this meta.answers declaration' }];
327
+ const { keys, testsByKey } = evidenceFor(question, evidence);
328
+ if (keys.some((key) => testsByKey.get(key)?.has(answer.test)))
329
+ return [];
330
+ const isReaching = reachingKinds.has(question.kind);
331
+ return [{ ...answer, problem: isReaching ? 'does not reach the code it answers for' : 'does not catch the change it answers for' }];
332
+ });
333
+ };
334
+ export const testTitleOf = ({ title, occurrence }) => (occurrence ? `${title} #${occurrence + 1}` : title);
335
+ // Offer answers the validator accepts.
336
+ export const answerChoicesOf = (tests, all, evidence) => {
337
+ const byTest = new Map();
338
+ for (const question of all) {
339
+ const { keys, testsByKey } = evidenceFor(question, evidence);
340
+ const eligible = new Set();
341
+ for (const key of keys) {
342
+ for (const test of testsByKey.get(key) ?? [])
343
+ if (tests.has(test))
344
+ eligible.add(test);
345
+ }
346
+ if (!eligible.size)
347
+ continue;
348
+ const choice = quote(`answers: ${JSON.stringify(question.id)}`);
349
+ for (const test of eligible) {
350
+ const choices = byTest.get(test) ?? ["Write one of these in the test's meta, then record again."];
351
+ choices.push(choice);
352
+ byTest.set(test, choices);
353
+ }
354
+ }
355
+ return byTest;
356
+ };
357
+ // One question per test that holds nothing up, its id built from the test file, its describe groups and its title, as a site question's from its file, function and code.
358
+ export const testQuestionsOf = (removable, names) => {
359
+ const questions = questionsOf([...names.values()].map((name) => ({ kind: 'test', file: name.file, function: name.groups.join(' > '), code: testTitleOf(name), replacement: '' })));
360
+ const byKey = new Map([...names.keys()].map((key, index) => [key, itemAt(questions, index)]));
361
+ const titleOf = (key) => testTitleOf(entryAt(names, key, `the name of test ${key}`));
362
+ return removable.map(({ key, firsts, backups }) => {
363
+ const question = entryAt(byKey, key, `the question for test ${key}`);
364
+ if (!firsts)
365
+ return { ...question, ask: `${quote(titleOf(key))} catches no change first and is nowhere the only test. Remove it?` };
366
+ const also = backups.map(({ key, count }) => `${quote(titleOf(key))} (${count})`).join(', ');
367
+ return { ...question, ask: `${question.ask}\n catches ${firsts} changes first, also caught by ${also}` };
368
+ });
369
+ };
370
+ const medianOf = (values) => {
371
+ const sorted = values.toSorted((left, right) => left - right);
372
+ const middle = Math.floor(sorted.length / 2);
373
+ // An odd count's middle value stands alone, and an even count's two middle values average.
374
+ const center = sorted.slice(sorted.length % 2 ? middle : middle - 1, middle + 1);
375
+ return center.reduce((total, each) => total + each, 0) / center.length;
376
+ };
377
+ const written = (steps) => `yes: write \`steps: ${steps}\` in the test's meta, then record again`;
378
+ // A count question asks of the stated count, grown, then fallen, then missing.
379
+ const countQuestionsOf = (tests) => {
380
+ const grew = [];
381
+ const fell = [];
382
+ const missing = [];
383
+ const unsteady = [];
384
+ for (const test of tests) {
385
+ const { key, steps, statedSteps, outside, isSteady } = test;
386
+ const name = quote(testTitleOf(test));
387
+ // A count two runs with nothing forced disagree on holds on no run, so the test is asked to steady its work rather than whether the count grew or fell.
388
+ if (!isSteady) {
389
+ unsteady.push({
390
+ key,
391
+ topic: 'count',
392
+ ask: `${name} does different work on two runs with nothing forced, so its count of steps is unsteady. Can it do the same work on every run?`,
393
+ answers: ['yes: make it do the same work on every run, as by resetting state it keeps between calls, then record again', 'no: leave its steps unstated, since no count holds across runs'],
394
+ });
395
+ }
396
+ else if (statedSteps === null) {
397
+ missing.push({ key, topic: 'count', ask: `${name} took ${steps} steps and its test states no count. Is that the work it needs?`, answers: [written(steps), `no: make the code ${name} runs do less work`] });
398
+ }
399
+ else if (steps > statedSteps) {
400
+ grew.push({ key, topic: 'count', ask: `${name} took ${steps} steps, its test states ${statedSteps}. Should it take more?`, answers: [written(steps), 'no: make the code do less work, back to its stated steps'] });
401
+ }
402
+ else if (steps < statedSteps && outside.length) {
403
+ // Work moved into a file crush leaves uninstrumented takes no steps there, so a fall beside one asks whether it moved.
404
+ fell.push({
405
+ key,
406
+ topic: 'count',
407
+ ask: `${name} took ${steps} steps, its test states ${statedSteps}, and it reaches ${outside.map(quote).join(', ')}, where no step counts. Did the work move there rather than shrink?`,
408
+ answers: ['yes: move that work into a file crush instruments, then state the count in the test', `no: write \`steps: ${steps}\` in the test's meta, then record again`],
409
+ });
410
+ }
411
+ else if (steps < statedSteps) {
412
+ fell.push({ key, topic: 'count', ask: `${name} took ${steps} steps, its test states ${statedSteps}. Should it take fewer?`, answers: [written(steps), 'no: find where the work went, as into a file crush leaves uninstrumented'] });
413
+ }
414
+ }
415
+ return [...grew, ...fell, ...missing, ...unsteady];
416
+ };
417
+ const heavyQuestionsOf = (tests) => {
418
+ return [...Map.groupBy(tests, ({ file }) => file).values()].flatMap((group) => {
419
+ const middle = medianOf(group.map(({ steps }) => steps));
420
+ return group
421
+ .filter(({ steps, statedSteps, stepsReason }) => steps > stepLimitFloor && steps > middle * stepLimitFactor && !(stepsReason && statedSteps === steps))
422
+ .map((test) => {
423
+ const { key, steps } = test;
424
+ const name = quote(testTitleOf(test));
425
+ return {
426
+ key,
427
+ topic: 'heavy',
428
+ ask: `${name} takes ${steps.toLocaleString('en-US')} steps, more than ${stepLimitFactor} times its file's median of ${middle.toLocaleString('en-US')}. Is its input or code larger than it needs?`,
429
+ answers: ['yes: shrink the input or simplify the code, then record again', `no: write \`steps: ${steps}\` and \`stepsReason\` in the test's meta, then record again`],
430
+ };
431
+ });
432
+ });
433
+ };
434
+ // Matches a generated folder in a path, whose tests no agent writes.
435
+ export const generatedFolderPattern = /(^|\/)generated\//;
436
+ // A test's stated count against the steps it took, a fork test's pass each, then each test far heavier than the rest of its file.
437
+ export const stepsQuestionsOf = (counted) => {
438
+ const tests = counted.filter(({ file }) => !generatedFolderPattern.test(file));
439
+ const asked = [...countQuestionsOf(tests), ...heavyQuestionsOf(tests)];
440
+ const idsFor = (topic) => {
441
+ const ids = idsOf(tests.map((test) => ({ kind: 'steps', file: test.file, function: test.groups.join(' > '), code: `${testTitleOf(test)}|${topic}`, replacement: '' })));
442
+ return new Map(tests.map(({ key }, index) => [key, itemAt(ids, index)]));
443
+ };
444
+ const ids = { count: idsFor('count'), heavy: idsFor('heavy') };
445
+ return asked.map(({ key, topic, ask, answers }) => ({ id: entryAt(ids[topic], key, `the steps question for test ${key}`), kind: 'steps', ask, answers }));
446
+ };
@@ -0,0 +1,57 @@
1
+ import { z } from 'zod';
2
+ export declare const questionKinds: readonly ['crush', 'reach', 'call', 'side', 'tell', 'matter', 'behavior', 'test', 'unused', 'unexport', 'untested', 'testonly', 'steps', 'answers', 'explore', 'same-result', 'no-split'];
3
+ export declare const questionIdPattern: RegExp;
4
+ export declare const encodedQuestionIdLength: number;
5
+ export declare const questionId: z.ZodString;
6
+ export declare const questionInput: z.ZodObject<{
7
+ kind: z.ZodEnum<{
8
+ answers: "answers";
9
+ behavior: "behavior";
10
+ call: "call";
11
+ crush: "crush";
12
+ explore: "explore";
13
+ matter: "matter";
14
+ "no-split": "no-split";
15
+ reach: "reach";
16
+ "same-result": "same-result";
17
+ side: "side";
18
+ steps: "steps";
19
+ tell: "tell";
20
+ test: "test";
21
+ testonly: "testonly";
22
+ unexport: "unexport";
23
+ untested: "untested";
24
+ unused: "unused";
25
+ }>;
26
+ file: z.ZodString;
27
+ function: z.ZodString;
28
+ code: z.ZodString;
29
+ replacement: z.ZodString;
30
+ }, z.core.$strip>;
31
+ declare const questionOutput: z.ZodObject<{
32
+ id: z.ZodString;
33
+ kind: z.ZodEnum<{
34
+ answers: "answers";
35
+ behavior: "behavior";
36
+ call: "call";
37
+ crush: "crush";
38
+ explore: "explore";
39
+ matter: "matter";
40
+ "no-split": "no-split";
41
+ reach: "reach";
42
+ "same-result": "same-result";
43
+ side: "side";
44
+ steps: "steps";
45
+ tell: "tell";
46
+ test: "test";
47
+ testonly: "testonly";
48
+ unexport: "unexport";
49
+ untested: "untested";
50
+ unused: "unused";
51
+ }>;
52
+ ask: z.ZodString;
53
+ answers: z.ZodArray<z.ZodString>;
54
+ }, z.core.$strip>;
55
+ export type QuestionInput = z.infer<typeof questionInput>;
56
+ export type QuestionOutput = z.infer<typeof questionOutput>;
57
+ export {};
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod';
2
+ export const questionKinds = ['crush', 'reach', 'call', 'side', 'tell', 'matter', 'behavior', 'test', 'unused', 'unexport', 'untested', 'testonly', 'steps', 'answers', 'explore', 'same-result', 'no-split'];
3
+ // Matches a question id with pipes and percent signs escaped inside its fields.
4
+ export const questionIdPattern = /^(crush|reach|call|side|tell|matter|behavior|test|unused|unexport|untested|testonly|steps|answers|explore|same-result|no-split)\|(?:[^|%]|%25|%7C)+\|(?:[^|%]|%25|%7C)*\|\d+\|(?:[^|%]|%25|%7C)+$/;
5
+ const questionIdLength = 2048;
6
+ export const encodedQuestionIdLength = questionIdLength * 3;
7
+ // A question id names its kind, file, function and code, never a line, so edits around the code leave it as it was.
8
+ export const questionId = z
9
+ .string()
10
+ .max(encodedQuestionIdLength)
11
+ .regex(questionIdPattern)
12
+ .refine((id) => id.replaceAll('%25', ' ').replaceAll('%7C', ' ').length <= questionIdLength, 'Too big: question id exceeds its unescaped length limit');
13
+ // One open item a question asks about: the code it is about, the function holding it, for a tell question the code that replaces it, and for a side question the side no test takes, empty for any other.
14
+ // A source path or function name is bounded as a path and a name; the code is capped at a short span's length.
15
+ export const questionInput = z.object({
16
+ kind: z.enum(questionKinds),
17
+ file: z.string().min(1).max(512),
18
+ function: z.string().max(256),
19
+ code: z.string().min(1).max(1024),
20
+ replacement: z.string().max(1024),
21
+ });
22
+ // A question as the agent reads it: its id, kind, ask and the answers it takes.
23
+ const questionOutput = z.object({
24
+ id: questionId,
25
+ kind: z.enum(questionKinds),
26
+ ask: z.string(),
27
+ answers: z.array(z.string()),
28
+ });
@@ -0,0 +1,10 @@
1
+ import { type ExportCallInput, type ExportCallOutput } from '../../capture/capture.schema.ts';
2
+ import { type Record, type WriteTransaction } from './record.db.ts';
3
+ type PreparedCall = Omit<ExportCallInput, 'args' | 'result'> & {
4
+ args: string;
5
+ result: string;
6
+ };
7
+ export declare const prepareExportCalls: (calls: ExportCallInput[]) => PreparedCall[];
8
+ export declare const writeExportCalls: (tx: WriteTransaction, testFile: number, calls: PreparedCall[], siteOf: ReadonlyMap<string, number>) => void;
9
+ export declare const getExportCalls: (db: Record) => ExportCallOutput[];
10
+ export {};
@@ -0,0 +1,91 @@
1
+ import { asc, eq, inArray, sql } from 'drizzle-orm';
2
+ import { decodedOf, encodedOf } from '../../capture/capture.operations.js';
3
+ import { exportCallOutput } from '../../capture/capture.schema.js';
4
+ import { exportCallSteps, exportCalls, testFiles } from '../../crush.tables.js';
5
+ import { entryAt } from '../../utils/lookup.js';
6
+ import { siteKeysOf } from './plan.db.js';
7
+ import { chunksOf } from './record.db.js';
8
+ // The id after the largest the calls table holds, from which a file's calls are numbered before they are written.
9
+ // A call's parent is an earlier call of the same write, so its id must be known before the chunk holding both is inserted, which a returned id cannot give.
10
+ const firstCallIdOf = (db) => {
11
+ const [row] = db
12
+ .select({ last: sql `max(${exportCalls.id})` })
13
+ .from(exportCalls)
14
+ .all();
15
+ return (row?.last ?? 0) + 1;
16
+ };
17
+ export const prepareExportCalls = (calls) => calls.map(({ args, result, ...call }) => ({ ...call, args: encodedOf(args), result: encodedOf(result) }));
18
+ // Replaces one file's calls and steps within the same transaction as its part.
19
+ export const writeExportCalls = (tx, testFile, calls, siteOf) => {
20
+ // Delete the steps as one list before deleting the calls, so the cascade has no steps to walk per call.
21
+ const previous = tx.select({ id: exportCalls.id }).from(exportCalls).where(eq(exportCalls.testFile, testFile));
22
+ tx.delete(exportCallSteps).where(inArray(exportCallSteps.call, previous)).run();
23
+ tx.delete(exportCalls).where(eq(exportCalls.testFile, testFile)).run();
24
+ if (!calls.length)
25
+ return;
26
+ const firstCall = firstCallIdOf(tx);
27
+ const callRows = calls.map(({ steps: _steps, parent, ...call }, position) => ({
28
+ id: firstCall + position,
29
+ testFile,
30
+ position,
31
+ ...call,
32
+ parent: parent === null ? null : firstCall + parent,
33
+ }));
34
+ // A step at a site the plan no longer names cannot be stored, so it goes, and the steps after it keep their numbers.
35
+ const stepRows = calls.flatMap(({ steps }, position) => {
36
+ return steps.flatMap(({ step, siteKey, side, passes }) => {
37
+ const site = siteOf.get(siteKey);
38
+ return site ? [{ call: firstCall + position, step, site, side, passes }] : [];
39
+ });
40
+ });
41
+ for (const chunk of chunksOf(callRows))
42
+ tx.insert(exportCalls).values(chunk).run();
43
+ for (const chunk of chunksOf(stepRows))
44
+ tx.insert(exportCallSteps).values(chunk).run();
45
+ };
46
+ // Every call the record's baselines kept, by test file and position, each value decoded and parsed where it leaves the record, its whole path its own steps merged with every descendant's by step.
47
+ export const getExportCalls = (db) => {
48
+ return db.transaction((tx) => {
49
+ const siteKeyOf = siteKeysOf(tx);
50
+ const stepRows = tx.select().from(exportCallSteps).orderBy(asc(exportCallSteps.call), asc(exportCallSteps.step)).all();
51
+ const stepsOf = Map.groupBy(stepRows.map(({ call, step, site, side, passes }) => ({ call, step, siteKey: entryAt(siteKeyOf, site, `the site ${site}`), side, passes })), ({ call }) => call);
52
+ const rows = tx
53
+ .select({
54
+ id: exportCalls.id,
55
+ file: testFiles.path,
56
+ position: exportCalls.position,
57
+ exportKey: exportCalls.exportKey,
58
+ testKey: exportCalls.testKey,
59
+ parent: exportCalls.parent,
60
+ depth: exportCalls.depth,
61
+ args: exportCalls.args,
62
+ outcome: exportCalls.outcome,
63
+ result: exportCalls.result,
64
+ thrownAt: exportCalls.thrownAt,
65
+ isPathCut: exportCalls.isPathCut,
66
+ })
67
+ .from(exportCalls)
68
+ .innerJoin(testFiles, eq(exportCalls.testFile, testFiles.id))
69
+ .orderBy(asc(testFiles.path), asc(exportCalls.position))
70
+ .all();
71
+ const positionOf = new Map(rows.map(({ id, position }) => [id, position]));
72
+ const childrenOf = Map.groupBy(rows, ({ parent }) => parent);
73
+ const ownOf = (id) => (stepsOf.get(id) ?? []).map(({ call: _call, ...step }) => step);
74
+ // A child always began after its parent, so a walk down the children ends.
75
+ const pathOf = (id) => [...ownOf(id), ...(childrenOf.get(id) ?? []).flatMap((child) => pathOf(child.id))];
76
+ // A merged path is cut wherever any call inside it stopped keeping steps.
77
+ const isCutOf = (row) => row.isPathCut || (childrenOf.get(row.id) ?? []).some(isCutOf);
78
+ return rows.map((row) => {
79
+ const { id, parent, args, result, ...call } = row;
80
+ return exportCallOutput.parse({
81
+ ...call,
82
+ isPathCut: isCutOf(row),
83
+ parent: parent === null ? null : entryAt(positionOf, parent, `the parent call ${parent}`),
84
+ args: decodedOf(args),
85
+ result: decodedOf(result),
86
+ steps: ownOf(id),
87
+ path: pathOf(id).toSorted((left, right) => left.step - right.step),
88
+ });
89
+ });
90
+ });
91
+ };