@boyingliu01/xp-gate 0.38.126 → 0.39.1

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 (291) hide show
  1. package/README.md +93 -0
  2. package/adapters/gate-3.sh +13 -2
  3. package/adapters/python.sh +36 -38
  4. package/bin/xp-gate.js +11 -0
  5. package/build-integrity/gate-10-lines.ts +98 -0
  6. package/build-integrity/gate-10.ts +98 -109
  7. package/build-integrity/quote-masker.ts +17 -3
  8. package/gate-3.sh +13 -2
  9. package/gates/common-process.ts +116 -34
  10. package/gates/common.ts +51 -15
  11. package/gates/gate-3.ts +166 -61
  12. package/gates/gate-8.ts +76 -24
  13. package/gates/gate-9.ts +276 -82
  14. package/gates/pbt-detect.ts +70 -39
  15. package/gates/python-health.ts +236 -98
  16. package/gates/test-layers.ts +103 -30
  17. package/hooks/gate-3.sh +13 -2
  18. package/hooks/gate-entries/gate-1-entry.sh +10 -1
  19. package/hooks/gate-entries/gate-5-entry.sh +5 -1
  20. package/hooks/lib/validate-code-walkthrough.cjs +324 -99
  21. package/hooks/pre-commit +52 -0
  22. package/hooks/pre-push +54 -3
  23. package/lib/agent-runtime-journal.js +104 -37
  24. package/lib/arch.js +6 -0
  25. package/lib/baseline.js +329 -201
  26. package/lib/check.js +38 -2
  27. package/lib/doctor-constants.js +43 -0
  28. package/lib/doctor.js +2008 -1001
  29. package/lib/flaky.js +178 -79
  30. package/lib/gate-runner.js +110 -63
  31. package/lib/init.js +6 -0
  32. package/lib/language-capability-surfaces.js +5 -2
  33. package/lib/language-registry.js +608 -0
  34. package/lib/language-tools.js +487 -1018
  35. package/lib/phase-transition.js +646 -446
  36. package/lib/prepush-evidence.js +174 -0
  37. package/lib/sprint-audit.js +52 -22
  38. package/lib/sprint-discovery.js +66 -35
  39. package/lib/sprint-format.js +114 -0
  40. package/lib/sprint-init.js +372 -118
  41. package/lib/sprint-status.js +134 -90
  42. package/lib/star-notice.js +346 -0
  43. package/lib/tool-display.js +52 -0
  44. package/lib/tool-install.js +179 -0
  45. package/lib/uninstall.js +331 -188
  46. package/mock-policy/gate-m3.ts +74 -23
  47. package/mock-policy/mock-decision-engine.ts +21 -7
  48. package/mock-policy/scope-scanner.ts +128 -69
  49. package/mutation/detect-ai-test.ts +20 -12
  50. package/mutation/gate-m.ts +6 -2
  51. package/mutation/init-baseline.ts +49 -13
  52. package/mutation/runners/go-mutant-runner.ts +7 -49
  53. package/mutation/runners/gremlins-runner.ts +53 -18
  54. package/mutation/runners/mutmut-runner.ts +455 -163
  55. package/mutation/runners/pitest-runner.ts +85 -131
  56. package/mutation/runners/spawn-with-capture.ts +304 -0
  57. package/mutation/runners/stryker-runner.ts +14 -55
  58. package/mutation/update-baseline.ts +25 -18
  59. package/package.json +20 -8
  60. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  61. package/plugins/claude-code/bin/delphi-review-guard.sh +12 -61
  62. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +6 -11
  63. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  64. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  65. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  66. package/plugins/dsh/package.json +1 -1
  67. package/plugins/dsh/scripts/prepack.cjs +43 -18
  68. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  69. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  70. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  71. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  72. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  73. package/plugins/opencode/index.ts +337 -123
  74. package/plugins/opencode/package.json +1 -1
  75. package/plugins/opencode/scripts/prepack.cjs +41 -16
  76. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  77. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  78. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  79. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  80. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  81. package/plugins/qoder/plugin.json +1 -1
  82. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  83. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/shared/README.md +3 -0
  87. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  88. package/principles/adapters/control-nesting.ts +481 -168
  89. package/principles/adapters/cpp.ts +61 -22
  90. package/principles/adapters/csharp.ts +183 -66
  91. package/principles/adapters/dart.ts +11 -1
  92. package/principles/adapters/duplication.ts +49 -16
  93. package/principles/adapters/import-clause.ts +62 -15
  94. package/principles/adapters/java.ts +199 -70
  95. package/principles/adapters/line-comment.ts +18 -0
  96. package/principles/adapters/member-scan.ts +50 -8
  97. package/principles/adapters/php.ts +232 -103
  98. package/principles/adapters/python.ts +25 -18
  99. package/principles/adapters/quote-state.ts +21 -8
  100. package/principles/adapters/typescript-mask.ts +276 -0
  101. package/principles/adapters/typescript.ts +206 -200
  102. package/principles/analyzer.ts +16 -6
  103. package/principles/baseline-prune.ts +18 -8
  104. package/principles/baseline.ts +28 -11
  105. package/principles/boy-scout-usage.ts +26 -0
  106. package/principles/boy-scout.ts +261 -180
  107. package/principles/config.ts +183 -57
  108. package/principles/direct-execution.ts +24 -12
  109. package/principles/lint-baseline.ts +235 -122
  110. package/principles/rules/arch/dependency.ts +34 -25
  111. package/principles/rules/arch/shared.ts +24 -20
  112. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  113. package/principles/rules/clean-code/god-class.ts +67 -41
  114. package/principles/rules/clean-code/large-file.ts +30 -23
  115. package/principles/rules/clean-code/long-function.ts +51 -37
  116. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  117. package/principles/rules/clean-code/many-exports.ts +46 -29
  118. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  119. package/principles/rules/clean-code/too-many-params.ts +41 -22
  120. package/principles/rules/function-source.ts +62 -0
  121. package/principles/rules/solid/dip.ts +10 -6
  122. package/principles/rules/solid/isp.ts +64 -24
  123. package/principles/rules/solid/lsp.ts +66 -18
  124. package/principles/rules/solid/ocp.ts +29 -13
  125. package/principles/rules/solid/srp.ts +34 -18
  126. package/principles/warnings-count.ts +43 -0
  127. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  128. package/scripts/delphi-config-read.cjs +245 -0
  129. package/scripts/delphi-external-review.cjs +410 -585
  130. package/scripts/delphi-json-extract.cjs +108 -0
  131. package/scripts/delphi-model-validation.cjs +297 -0
  132. package/scripts/delphi-prompts.cjs +55 -0
  133. package/scripts/delphi-repo-tools.cjs +273 -0
  134. package/scripts/delphi-seat-calibration.cjs +204 -0
  135. package/scripts/run-bats-ci.cjs +240 -97
  136. package/scripts/sync-package-content.js +18 -2
  137. package/skills/delphi-review/.delphi-config.json.example +6 -11
  138. package/skills/delphi-review/AGENTS.md +1 -1
  139. package/skills/sprint-flow/AGENTS.md +1 -1
  140. package/skills/test-specification-alignment/AGENTS.md +1 -1
  141. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  142. package/lib/__tests__/arch-config-template.test.js +0 -190
  143. package/lib/__tests__/arch.test.js +0 -430
  144. package/lib/__tests__/assertion-debt.test.js +0 -99
  145. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  146. package/lib/__tests__/audit-log.test.ts +0 -107
  147. package/lib/__tests__/audit-skip-reasons.test.ts +0 -143
  148. package/lib/__tests__/baseline-completeness.test.js +0 -264
  149. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  150. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  151. package/lib/__tests__/baseline.test.js +0 -212
  152. package/lib/__tests__/bootstrap.test.js +0 -60
  153. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  154. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  155. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  156. package/lib/__tests__/check-changed-brief.test.js +0 -63
  157. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  158. package/lib/__tests__/check-single-file.test.js +0 -114
  159. package/lib/__tests__/check-tools-list.test.js +0 -155
  160. package/lib/__tests__/check-version.test.js +0 -463
  161. package/lib/__tests__/coverage-scope.test.js +0 -140
  162. package/lib/__tests__/coverage-threshold.test.js +0 -80
  163. package/lib/__tests__/crap-cli.test.js +0 -87
  164. package/lib/__tests__/crap.test.js +0 -494
  165. package/lib/__tests__/debt-classify.test.js +0 -78
  166. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  167. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  168. package/lib/__tests__/delphi-channel.test.js +0 -109
  169. package/lib/__tests__/delphi-setup.test.js +0 -203
  170. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  171. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  172. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  173. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  174. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  175. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  176. package/lib/__tests__/deploy-manifest.test.js +0 -97
  177. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  178. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  179. package/lib/__tests__/detect-deps.test.js +0 -655
  180. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  181. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  182. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  183. package/lib/__tests__/doctor-brief.test.js +0 -59
  184. package/lib/__tests__/doctor-delphi.test.js +0 -628
  185. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  186. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  187. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  188. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  189. package/lib/__tests__/doctor-helpers.test.js +0 -139
  190. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  191. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  192. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  193. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  194. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  195. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  196. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  197. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  198. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  199. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  200. package/lib/__tests__/doctor-tool-delegation.test.js +0 -156
  201. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  202. package/lib/__tests__/doctor.test.js +0 -1320
  203. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  204. package/lib/__tests__/flaky.test.js +0 -128
  205. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  206. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  207. package/lib/__tests__/gate-audit.test.ts +0 -440
  208. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  209. package/lib/__tests__/gate-coverage.test.js +0 -204
  210. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  211. package/lib/__tests__/gate-numbering.test.js +0 -79
  212. package/lib/__tests__/gate-rules.test.js +0 -58
  213. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  214. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  215. package/lib/__tests__/gate-runner.test.js +0 -371
  216. package/lib/__tests__/gate2-verdict.test.js +0 -183
  217. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  218. package/lib/__tests__/hook-health-path.test.js +0 -109
  219. package/lib/__tests__/hook-health.test.js +0 -85
  220. package/lib/__tests__/init-gitignore.test.js +0 -204
  221. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  222. package/lib/__tests__/init.test.js +0 -530
  223. package/lib/__tests__/install-cmd.test.js +0 -6
  224. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  225. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  226. package/lib/__tests__/install-skill.test.js +0 -416
  227. package/lib/__tests__/install-tools-repair.test.js +0 -263
  228. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  229. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  230. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  231. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  232. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  233. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  234. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  235. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  236. package/lib/__tests__/language-capability.test.js +0 -318
  237. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  238. package/lib/__tests__/language-tools-detect.test.js +0 -301
  239. package/lib/__tests__/migrate.test.js +0 -232
  240. package/lib/__tests__/mirror-manifest.test.js +0 -64
  241. package/lib/__tests__/mirror-sync.test.js +0 -803
  242. package/lib/__tests__/next-sprint.test.js +0 -231
  243. package/lib/__tests__/npm-package.test.js +0 -140
  244. package/lib/__tests__/phase-transition.test.js +0 -1136
  245. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  246. package/lib/__tests__/principles-directory.test.js +0 -87
  247. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  248. package/lib/__tests__/retro-gate-m.test.js +0 -144
  249. package/lib/__tests__/retro.test.js +0 -131
  250. package/lib/__tests__/rework.test.js +0 -127
  251. package/lib/__tests__/rollback.test.js +0 -183
  252. package/lib/__tests__/runtime-journal.test.js +0 -164
  253. package/lib/__tests__/sastd-client.test.js +0 -514
  254. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  255. package/lib/__tests__/shared-paths.test.js +0 -130
  256. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  257. package/lib/__tests__/shared-utils.test.js +0 -180
  258. package/lib/__tests__/skill-flags.test.js +0 -48
  259. package/lib/__tests__/slo.test.js +0 -89
  260. package/lib/__tests__/sprint-audit.test.js +0 -207
  261. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  262. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  263. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  264. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  265. package/lib/__tests__/sprint-status.test.js +0 -193
  266. package/lib/__tests__/sprint-status.test.ts +0 -213
  267. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  268. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  269. package/lib/__tests__/test-alignment.test.ts +0 -853
  270. package/lib/__tests__/tool-audit-collect.test.js +0 -184
  271. package/lib/__tests__/tool-audit-fixtures.js +0 -87
  272. package/lib/__tests__/tool-audit-latest.test.js +0 -84
  273. package/lib/__tests__/tool-audit.test.js +0 -428
  274. package/lib/__tests__/tsconfig.json +0 -8
  275. package/lib/__tests__/tsx-resolution.test.js +0 -89
  276. package/lib/__tests__/ui-detector.test.ts +0 -459
  277. package/lib/__tests__/ui-review.test.ts +0 -132
  278. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  279. package/lib/__tests__/uninstall-skill.test.js +0 -189
  280. package/lib/__tests__/uninstall.test.js +0 -717
  281. package/lib/__tests__/update-hooks.test.js +0 -737
  282. package/lib/__tests__/update-skill-flags.test.js +0 -78
  283. package/lib/__tests__/update-skill.test.js +0 -644
  284. package/lib/__tests__/upgrade-exec.test.js +0 -273
  285. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  286. package/lib/__tests__/upgrade.test.js +0 -78
  287. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  288. package/lib/check-alignment-runner.cjs +0 -97
  289. package/lib/coverage-total.sh +0 -92
  290. package/lib/layer-baseline.cjs +0 -94
  291. package/lib/mattpocock-license-verdict.json +0 -7
@@ -1,5 +1,5 @@
1
1
  // @no-test-required: mutmut wrapper — tested via gate-m integration + pre-push Gate M
2
- import { spawn, execSync, type ChildProcess } from 'child_process';
2
+ import { execSync } from 'child_process';
3
3
  import { writeFileSync, unlinkSync, readFileSync, existsSync } from 'fs';
4
4
  import { join, dirname } from 'path';
5
5
  import type {
@@ -8,6 +8,7 @@ import type {
8
8
  MutationRunOutcome,
9
9
  MutationRunResult,
10
10
  } from './types';
11
+ import { runMutationCommand } from './spawn-with-capture';
11
12
 
12
13
  type Platform = NodeJS.Platform;
13
14
  type MutmutRoute = 'native' | 'wsl' | 'unavailable' | 'unresolved';
@@ -31,17 +32,7 @@ type MutmutRoute = 'native' | 'wsl' | 'unavailable' | 'unresolved';
31
32
  * accumulation inside an already-long Promise body, and their nesting was part
32
33
  * of what made that method exceed both the length and the nesting budget.
33
34
  */
34
- function collectOutput(
35
- child: ChildProcess,
36
- onChunk: (chunk: string, isStderr: boolean) => void,
37
- ): void {
38
- child.stdout?.on('data', (data: Buffer) => onChunk(data.toString(), false));
39
- child.stderr?.on('data', (data: Buffer) => onChunk(data.toString(), true));
40
- }
41
-
42
35
  /** How long a SIGTERMed mutmut gets before it is killed outright. */
43
- const ESCALATION_DELAY_MS = 5000;
44
-
45
36
  /** Where the pre-run copy of pyproject.toml lives. */
46
37
  function pyprojectBackupPath(pyprojectPath: string): string {
47
38
  return `${pyprojectPath}.xp-gate-backup`;
@@ -57,52 +48,87 @@ function pyprojectBackupPath(pyprojectPath: string): string {
57
48
  */
58
49
  function restorePyproject(pyprojectPath: string, hadExisting: boolean): void {
59
50
  const backupPath = pyprojectBackupPath(pyprojectPath);
60
- try {
61
- if (hadExisting && existsSync(backupPath)) {
62
- writeFileSync(pyprojectPath, readFileSync(backupPath, 'utf-8'), { encoding: 'utf-8' });
63
- unlinkSync(backupPath);
64
- } else if (!hadExisting && existsSync(pyprojectPath)) {
65
- unlinkSync(pyprojectPath);
66
- }
67
- } catch {
68
- // Best effort cleanup
69
- }
51
+ restoreFromBackup({ pyprojectPath, backupPath, hadExisting });
52
+ }
53
+
54
+ /**
55
+ * Put `pyproject.toml` back the way it was.
56
+ *
57
+ * Two cases, because the file may not have EXISTED before: restoring a backup that was
58
+ * never taken would leave an empty file, and deleting a file we did not create would
59
+ * destroy the project's own configuration.
60
+ */
61
+ /** What a restore needs: the file, its backup, and whether the file pre-existed. */
62
+ interface RestoreTarget {
63
+ pyprojectPath: string;
64
+ backupPath: string;
65
+ hadExisting: boolean;
70
66
  }
71
67
 
72
- /** The tracker shape `settleTracker` returns; only the timeout path uses these. */
73
- interface SettleTracker {
74
- didTimeOut: () => boolean;
75
- markTimedOut: () => void;
76
- settle: (outcome: MutationRunOutcome) => void;
77
- isSettled: () => boolean;
68
+ /** The two paths a backup restore needs. */
69
+ type BackupPair = Omit<RestoreTarget, 'hadExisting'>;
70
+
71
+ function restoreFromBackup({ pyprojectPath, backupPath, hadExisting }: RestoreTarget): void {
72
+ try {
73
+ if (hadExisting) restoreExisting({ pyprojectPath, backupPath });
74
+ else removeCreated(pyprojectPath);
75
+ } catch (err) {
76
+ // LOUD, not silent: a failed restore leaves `pyproject.toml` as MUTMUT rewrote it, in
77
+ // the user's working tree. Swallowing that would let them commit a mutated manifest.
78
+ // Not thrown, because that would turn a mutation RESULT into a crash -- but the
79
+ // backup path is named so the content can still be recovered by hand.
80
+ console.error(
81
+ `[mutmut] WARNING: could not restore ${pyprojectPath}; it may still carry the `
82
+ + `mutmut edit. Backup: ${backupPath} (${String(err)})`,
83
+ );
84
+ }
78
85
  }
79
86
 
80
87
  /**
81
- * Arm the run timeout, escalating SIGTERM to SIGKILL once.
88
+ * Restore the backed-up content, then drop the backup.
82
89
  *
83
- * Extracted from `runMutmut` for the same reason as `collectOutput`: the
84
- * two-step kill sequence is twelve lines of policy that pushed the method past
85
- * both budgets. The escalation timer id is handed back through `setEscalation`
86
- * so the caller's `cancelTimers` closure can still reach it.
87
- *
88
- * @returns the primary timer id, to be cleared by the caller.
90
+ * Best-effort: the workspace is left as mutmut left it, and throwing here would turn a
91
+ * mutation RESULT into a crash.
89
92
  */
90
- function armTimeout(
91
- child: ChildProcess,
92
- timeoutMs: number,
93
- tracker: SettleTracker,
94
- setEscalation: (id: NodeJS.Timeout) => void,
95
- ): NodeJS.Timeout {
96
- const escalationMs = ESCALATION_DELAY_MS;
97
- return setTimeout(() => {
98
- tracker.markTimedOut();
99
- child.kill('SIGTERM');
100
- if (tracker.isSettled()) return;
101
- // SIGTERM may be ignored; escalate once.
102
- setEscalation(setTimeout(() => {
103
- if (!tracker.isSettled()) child.kill('SIGKILL');
104
- }, escalationMs));
105
- }, timeoutMs);
93
+ function restoreExisting({ pyprojectPath, backupPath }: BackupPair): void {
94
+ // A MISSING backup is not "nothing to do". `pyproject.toml` pre-existed (that is why a
95
+ // backup was taken), so whatever mutmut wrote into it is still there and nothing can put
96
+ // it back -- the caller must say so instead of returning as though the restore succeeded
97
+ // (review feasibility FC-01: this was a silent fail-open).
98
+ if (!existsSync(backupPath)) {
99
+ throw new Error(`backup ${backupPath} is gone, so ${pyprojectPath} cannot be restored`);
100
+ }
101
+ // Each step is guarded on its own rather than wrapped in one try/catch, because they
102
+ // fail differently and only the CALLER can report usefully (it knows the backup path):
103
+ //
104
+ // - an unreadable backup leaves the workspace untouched -- nothing was written, so
105
+ // there is nothing to report beyond the caller's warning;
106
+ // - a failed WRITE is the serious one: pyproject.toml still carries mutmut's edit,
107
+ // and the backup must survive so the content can be recovered by hand;
108
+ // - the backup is unlinked only after the write succeeded, since deleting it first
109
+ // would destroy the only copy if the write then failed.
110
+ //
111
+ // Failures PROPAGATE to `restoreFromBackup`, which is the one place that can name the
112
+ // backup path and print a warning.
113
+ const content = readFileSync(backupPath, 'utf-8');
114
+ try {
115
+ writeFileSync(pyprojectPath, content, { encoding: 'utf-8' });
116
+ } catch (err) {
117
+ // The write is the step that leaves DAMAGE behind: pyproject.toml keeps mutmut's
118
+ // edit. Add the backup path here, so the caller's warning tells the reader how to
119
+ // recover even after the file is gone from the log.
120
+ throw new Error(`restore of ${pyprojectPath} failed (backup kept at ${backupPath}): ${String(err)}`);
121
+ }
122
+ unlinkSync(backupPath);
123
+ }
124
+
125
+ /** Delete the file this run created, if it is still there. */
126
+ function removeCreated(pyprojectPath: string): void {
127
+ try {
128
+ if (existsSync(pyprojectPath)) unlinkSync(pyprojectPath);
129
+ } catch {
130
+ // Best effort -- see `restoreExisting`.
131
+ }
106
132
  }
107
133
 
108
134
  export class MutmutRunner implements MutationRunner {
@@ -153,10 +179,26 @@ export class MutmutRunner implements MutationRunner {
153
179
  const sourceDirs = this.extractUniqueDirs(options.files);
154
180
 
155
181
  const pyprojectPath = join(options.cwd, 'pyproject.toml');
156
- const hadExisting = this.backupPyproject(pyprojectPath);
157
-
182
+ // Backing up and writing are OUTSIDE the `finally` on purpose, and both are caught:
183
+ // a failure to prepare the workspace is a TOOL failure, and this module's contract is
184
+ // that tool failures arrive as an outcome with `error`, never as a rejected promise
185
+ // (a rejection reaches the caller's `catch` and reads as "no mutants found").
186
+ let hadExisting = false;
187
+ let backedUp = false;
158
188
  try {
189
+ hadExisting = this.backupPyproject(pyprojectPath);
190
+ backedUp = true;
159
191
  this.writeMutmutConfig(pyprojectPath, sourceDirs);
192
+ } catch (err) {
193
+ // Roll back ONLY what was done. `backedUp` distinguishes "the backup ran but the
194
+ // write failed" from "the backup itself failed": with `restorePyproject(path,
195
+ // false)` hardcoded, the first case DELETES a pyproject.toml that was there all
196
+ // along -- the user's own file -- because `hadExisting` was never consulted.
197
+ if (backedUp) restorePyproject(pyprojectPath, hadExisting);
198
+ return { report: null, timedOut: false, error: err instanceof Error ? err.message : String(err) };
199
+ }
200
+
201
+ try {
160
202
  return await this.runMutmut(options);
161
203
  } finally {
162
204
  restorePyproject(pyprojectPath, hadExisting);
@@ -190,31 +232,7 @@ export class MutmutRunner implements MutationRunner {
190
232
  * back the right shape. Factoring that into a single small object keeps
191
233
  * `runMutmut` down to spawning and wiring, which is all it should express.
192
234
  */
193
- private settleTracker(
194
- resolve: (outcome: MutationRunOutcome) => void,
195
- cancelTimers: () => void,
196
- ): {
197
- didTimeOut: () => boolean;
198
- markTimedOut: () => void;
199
- settle: (outcome: MutationRunOutcome) => void;
200
- isSettled: () => boolean;
201
- } {
202
- let settled = false;
203
- let timedOut = false;
204
- return {
205
- didTimeOut: () => timedOut,
206
- markTimedOut: () => {
207
- timedOut = true;
208
- },
209
- isSettled: () => settled,
210
- settle: (outcome) => {
211
- if (settled) return;
212
- settled = true;
213
- cancelTimers();
214
- resolve(outcome);
215
- },
216
- };
217
- }
235
+
218
236
 
219
237
  /**
220
238
  * How to invoke `mutmut run` for the current route, or null when a WSL path
@@ -229,73 +247,26 @@ export class MutmutRunner implements MutationRunner {
229
247
  return { command: 'wsl', args: ['--cd', wslPath, 'mutmut', 'run'] };
230
248
  }
231
249
 
232
- private async runMutmut(options: RunMutationOptions): Promise<MutationRunOutcome> {
233
- return new Promise((resolve) => {
234
- const invocation = this.buildInvocation(options.cwd);
235
- if (invocation === null) {
236
- resolve({ report: null, timedOut: false });
237
- return;
238
- }
239
-
240
- const child = spawn(invocation.command, invocation.args, {
241
- stdio: 'pipe',
242
- cwd: options.cwd,
243
- });
244
-
245
- let stdout = '';
246
- let stderr = '';
247
- let escalationId: NodeJS.Timeout | undefined;
248
-
249
- // Both timers must be cancelled from three different terminal events
250
- // (close, error, timeout). Keeping the pair in one place is what stops the
251
- // settle path from drifting out of step with the timeout path.
252
- const cancelTimers = (): void => {
253
- clearTimeout(timeoutId);
254
- if (escalationId) clearTimeout(escalationId);
255
- };
256
-
257
- const tracker = this.settleTracker(resolve, cancelTimers);
258
-
259
- const timeoutId = armTimeout(child, options.timeoutMs, tracker, (id) => {
260
- escalationId = id;
261
- });
262
-
263
- collectOutput(child, (chunk, isErr) => {
264
- if (isErr) stderr += chunk;
265
- else stdout += chunk;
266
- });
267
-
268
- child.on('close', (code) => {
269
- tracker.settle(this.outcomeFor(code, stdout, stderr, tracker));
270
- });
271
-
272
- child.on('error', (err) => {
273
- tracker.settle({ report: null, timedOut: tracker.didTimeOut(), error: err.message });
274
- });
275
- });
276
- }
277
-
278
250
  /**
279
- * Turn one `mutmut run` exit into the outcome the caller expects.
251
+ * Run mutmut through the SHARED spawn/timeout/capture path.
280
252
  *
281
- * Extracted from `runMutmut`'s close handler to bring that method back under
282
- * the length and nesting budgets. A null exit code means the process was
283
- * killed -- "timed out" when we did it, "unknown" otherwise -- and there is no
284
- * report to parse either way.
253
+ * This runner used to carry its own `spawn` + `armTimeout` + `collectOutput` +
254
+ * `settleTracker`: a second definition of the timeout policy, which is how the two
255
+ * could disagree (and did -- one guarded the SIGKILL escalation on `child.killed`,
256
+ * which Node sets when `kill()` is CALLED, so the escalation never fired).
257
+ *
258
+ * The report parser stays local: reading mutmut's emoji progress is this runner's
259
+ * business, and the shared path takes it as a callback.
285
260
  */
286
- private outcomeFor(
287
- code: number | null,
288
- stdout: string,
289
- stderr: string,
290
- tracker: SettleTracker,
291
- ): MutationRunOutcome {
292
- if (code === null) return { report: null, timedOut: tracker.didTimeOut() };
293
- return {
294
- // Parse results from mutmut run stdout (v3.x emoji progress)
295
- report: this.parseEmojiProgress(stdout),
296
- timedOut: tracker.didTimeOut(),
297
- error: code !== 0 ? stderr || stdout : undefined,
298
- };
261
+ private async runMutmut(options: RunMutationOptions): Promise<MutationRunOutcome> {
262
+ const invocation = this.buildInvocation(options.cwd);
263
+ if (invocation === null) return { report: null, timedOut: false };
264
+ return runMutationCommand(
265
+ invocation.command,
266
+ invocation.args,
267
+ { cwd: options.cwd, timeoutMs: options.timeoutMs },
268
+ (stdout: string) => this.parseEmojiProgress(stdout),
269
+ );
299
270
  }
300
271
 
301
272
  private toWslPath(path: string): string | null {
@@ -342,9 +313,15 @@ export class MutmutRunner implements MutationRunner {
342
313
  const unknown1 = this.extractEmojiCount(progressLine, '🔇');
343
314
  const unknown2 = this.extractEmojiCount(progressLine, '🧙');
344
315
 
345
- const nrOfKilledMutants = killed;
316
+ // Any UNREADABLE count makes the whole line untrustworthy: reporting a score built
317
+ // from a partial parse is worse than reporting that the run could not be read.
318
+ const counts = [killed, untested, timeout, suspicious, survived, unknown1, unknown2];
319
+ if (counts.some((n) => n === null)) return null;
320
+
321
+ const nrOfKilledMutants = killed as number;
346
322
  const nrOfSurvivedMutants =
347
- survived + timeout + suspicious + untested + unknown1 + unknown2;
323
+ (survived as number) + (timeout as number) + (suspicious as number)
324
+ + (untested as number) + (unknown1 as number) + (unknown2 as number);
348
325
  const nrOfMutants = nrOfKilledMutants + nrOfSurvivedMutants;
349
326
 
350
327
  if (nrOfMutants === 0) return null;
@@ -361,10 +338,21 @@ export class MutmutRunner implements MutationRunner {
361
338
  * Extract count after an emoji in a progress line.
362
339
  * e.g., "🎉 9" → 9
363
340
  */
364
- private extractEmojiCount(line: string, emoji: string): number {
365
- const escapedEmoji = emoji.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
366
- const match = line.match(new RegExp(`${escapedEmoji}\\s*(\\d+)`));
367
- return parseInt(match?.[1] ?? '0', 10);
341
+ /**
342
+ * The count after an emoji on mutmut's progress line.
343
+ *
344
+ * ABSENT means zero: mutmut omits an emoji whose count is 0, so a line without `🫥`
345
+ * really did have no untested mutants. That is a measured zero, not an unknown.
346
+ *
347
+ * PRESENT BUT UNREADABLE is different, and returns null: if the emoji is there and the
348
+ * number after it is not, the line was not understood, and calling that 0 would report
349
+ * a clean run on a parse failure.
350
+ */
351
+ private extractEmojiCount(line: string, emoji: string): number | null {
352
+ const at = line.indexOf(emoji);
353
+ if (at === -1) return 0;
354
+ const after = line.slice(at + emoji.length).match(/^\s*(\d+)/);
355
+ return after ? parseInt(after[1], 10) : null;
368
356
  }
369
357
 
370
358
  /**
@@ -384,12 +372,11 @@ export class MutmutRunner implements MutationRunner {
384
372
  }
385
373
 
386
374
  private writeMutmutConfig(pyprojectPath: string, sourceDirs: string[]): void {
387
- const sourcePathsLine = `source_paths = [${sourceDirs.map((d) => `"${d}"`).join(', ')}]`;
388
375
  try {
389
376
  // Read here so the content builder stays pure: it then has no I/O to
390
377
  // fail on, and the one place that can fail is the one that explains why.
391
378
  const existing = existsSync(pyprojectPath) ? readFileSync(pyprojectPath, 'utf-8') : null;
392
- writeFileSync(pyprojectPath, mutmutConfigContent(existing, sourcePathsLine), {
379
+ writeFileSync(pyprojectPath, mutmutConfigContent(existing, sourceDirs), {
393
380
  encoding: 'utf-8',
394
381
  });
395
382
  } catch (err) {
@@ -400,23 +387,328 @@ export class MutmutRunner implements MutationRunner {
400
387
  }
401
388
  }
402
389
 
390
+ import { parse as parseToml } from 'smol-toml';
391
+
392
+ /**
393
+ * pyproject.toml content with `[tool.mutmut] source_paths` set to `sourceDirs`.
394
+ *
395
+ * THE PARSER DECIDES, THE TEXT IS EDITED. A real TOML parser answers "is there a
396
+ * `[tool.mutmut]` table, and is its `source_paths` an array?" -- questions that five
397
+ * rounds of review showed cannot be answered by pattern-matching. A commented header, a
398
+ * string containing the key, a multi-line string body, an array whose path holds a `]`,
399
+ * and a scalar followed by another array each defeated a textual check; two of them by
400
+ * DELETING user content (all measured).
401
+ *
402
+ * Serialising the parsed document would answer them too, but it rewrites the whole file
403
+ * -- comments, ordering and spacing included -- which is not ours to discard. So the
404
+ * parser only SELECTS the branch, and the edit is applied to the original text.
405
+ *
406
+ * @param existing the current file content, or null when the file does not exist.
407
+ */
408
+ export function mutmutConfigContent(existing: string | null, sourceDirs: string[]): string {
409
+ const line = arrayLine(sourceDirs);
410
+ if (existing === null) return `[tool.mutmut]\n${line}\n`;
411
+ const table = findMutmutTable(parseDocument(existing));
412
+ if (table === null) return withoutTable(existing, line);
413
+ if (table.source_paths === undefined) return insertKey(existing, line);
414
+ if (!Array.isArray(table.source_paths)) return existing;
415
+ return replaceArrayText(existing, line);
416
+ }
417
+
418
+ /**
419
+ * Handle a document with no USABLE `[tool.mutmut]` table.
420
+ *
421
+ * Two reasons to get here, and they need opposite answers: the file parses and simply has
422
+ * no table (append one), or it does NOT parse -- in which case a header may well be there
423
+ * and appending a second `[tool.mutmut]` would leave two, so the text is left alone.
424
+ */
425
+ function withoutTable(existing: string, line: string): string {
426
+ return hasMutmutHeader(existing) ? existing : appendTable(existing, line);
427
+ }
428
+
403
429
  /**
404
- * pyproject.toml content with `[tool.mutmut] source_paths` set as requested.
430
+ * A `[tool.mutmut]` header LINE.
405
431
  *
406
- * Pure by design: the caller reads the existing file and passes it in, so this
407
- * function has no I/O that could fail partway through. Three shapes have to be
408
- * preserved -- an existing `source_paths` is rewritten in place, a bare
409
- * `[tool.mutmut]` table gets the key added, and a file without the table gets
410
- * one appended (a fresh file passes `null`).
432
+ * `[ ]` may hold whitespace and a trailing `#` comment is legal TOML --
433
+ * `[ tool.mutmut ] # note` is a valid header, and a stricter pattern reported "no table"
434
+ * for it, leaving the array unrewritten (measured). The parser has already confirmed the
435
+ * table EXISTS; this only has to find where its body starts.
436
+ */
437
+ const MUTMUT_HEADER = /^[^\S\n]*\[[^\S\n]*tool[^\S\n]*\.[^\S\n]*mutmut[^\S\n]*\][^\n]*$/m;
438
+
439
+ /** Whether the TEXT has a `[tool.mutmut]` header, parseable or not. */
440
+ function hasMutmutHeader(existing: string): boolean {
441
+ return MUTMUT_HEADER.test(existing);
442
+ }
443
+
444
+ /** The `source_paths = [...]` line, as TOML with quoted entries. */
445
+ function arrayLine(sourceDirs: string[]): string {
446
+ return `source_paths = [${sourceDirs.map((d) => JSON.stringify(d)).join(', ')}]`;
447
+ }
448
+
449
+ /** The parsed document, or `UNPARSEABLE` when the file is not valid TOML. */
450
+ const UNPARSEABLE = Symbol('unparseable');
451
+
452
+ /**
453
+ * Parse the document, tolerating an invalid one.
411
454
  *
412
- * @param existing current file content, or null when the file does not exist.
455
+ * A pyproject.toml that does not parse is a file mutmut cannot use either. Returning a
456
+ * sentinel rather than throwing keeps this function total: the caller appends its table
457
+ * to whatever is there, which is the same thing a hand edit would do.
413
458
  */
414
- function mutmutConfigContent(existing: string | null, sourcePathsLine: string): string {
415
- if (existing === null) return `[tool.mutmut]\n${sourcePathsLine}\n`;
416
- if (!existing.includes('[tool.mutmut]')) {
417
- return existing.trimEnd() + `\n\n[tool.mutmut]\n${sourcePathsLine}\n`;
459
+ function parseDocument(existing: string): Record<string, unknown> | typeof UNPARSEABLE {
460
+ try {
461
+ return parseToml(existing) as Record<string, unknown>;
462
+ } catch {
463
+ return UNPARSEABLE;
464
+ }
465
+ }
466
+
467
+ /**
468
+ * The `[tool.mutmut]` table from a parsed document, or null when there is none.
469
+ *
470
+ * Read STRUCTURALLY: `tool.mutmut` is a path in the parsed tree, so a commented header,
471
+ * a string that mentions the table name, or a `[tool.other]` entry cannot be mistaken
472
+ * for it. That is the whole reason this function takes a parsed document.
473
+ */
474
+ function findMutmutTable(parsed: Record<string, unknown> | typeof UNPARSEABLE): Record<string, unknown> | null {
475
+ if (parsed === UNPARSEABLE) return null;
476
+ const tool = parsed.tool;
477
+ if (!isRecord(tool)) return null;
478
+ const mutmut = tool.mutmut;
479
+ return isRecord(mutmut) ? mutmut : null;
480
+ }
481
+
482
+ /** Whether a parsed value is a TOML table. */
483
+ function isRecord(value: unknown): value is Record<string, unknown> {
484
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
485
+ }
486
+
487
+ /**
488
+ * Append a fresh `[tool.mutmut]` table.
489
+ *
490
+ * The table is appended rather than merged because there is no table to merge INTO --
491
+ * either the file has none, or it does not parse and guessing where a table belongs in
492
+ * an invalid document is worse than adding one at the end.
493
+ */
494
+ function appendTable(existing: string, line: string): string {
495
+ const trimmed = existing.trimEnd();
496
+ // No stacked blank lines in an otherwise empty file.
497
+ return trimmed === '' ? `[tool.mutmut]\n${line}\n` : `${trimmed}\n\n[tool.mutmut]\n${line}\n`;
498
+ }
499
+
500
+ /**
501
+ * Add `source_paths` to an existing table that does not have it yet.
502
+ *
503
+ * Inserted directly after the header, which keeps it inside the table no matter what
504
+ * follows -- no scan for the next header, so there is nothing to get wrong.
505
+ */
506
+ function insertKey(existing: string, line: string): string {
507
+ // The SAME pattern the body scan uses. A second, stricter copy here meant a header
508
+ // like `[ tool.mutmut ]` was found by one and missed by the other.
509
+ const header = MUTMUT_HEADER.exec(existing);
510
+ if (!header) return appendTable(existing, line);
511
+ const at = header.index + header[0].length;
512
+ return `${existing.slice(0, at)}\n${line}${existing.slice(at)}`;
513
+ }
514
+
515
+ /**
516
+ * Replace the array literal with `line`, keeping the rest of the file byte for byte.
517
+ *
518
+ * Only reached when the parser has already confirmed the table and that its
519
+ * `source_paths` IS an array, so all that remains is finding that array's text. The
520
+ * search is bounded to the key's own line for the opening bracket and balanced
521
+ * afterwards, which is what makes a `]` inside a path safe.
522
+ */
523
+ function replaceArrayText(existing: string, line: string): string {
524
+ const span = arraySpan(existing);
525
+ if (span === null) return existing;
526
+ return existing.slice(0, span.start) + line + existing.slice(span.end);
527
+ }
528
+
529
+ /** A line that assigns `source_paths`. */
530
+ const KEY_LINE = /^[^\S\n]*source_paths[^\S\n]*=/;
531
+
532
+ /**
533
+ * Index where a REAL `source_paths =` key starts, or -1.
534
+ *
535
+ * The parser has already confirmed the table HAS the key; this finds its TEXT. A plain
536
+ * regex cannot, because a multi-line string can hold a line that looks exactly like the
537
+ * key -- measured: the STRING was rewritten and the real key below it left alone.
538
+ *
539
+ * All four TOML string forms are tracked, the multi-line ones included: they legitimately
540
+ * span the newlines a `^`-anchored regex relies on.
541
+ */
542
+ function findKeyOutsideStrings(doc: string, from: number, to: number): number {
543
+ let quote: string | null = null;
544
+ let offset = from;
545
+ for (const line of doc.slice(from, to).split('\n')) {
546
+ if (quote === null && KEY_LINE.test(line)) return offset;
547
+ quote = scanLineForQuote(line, quote);
548
+ offset += line.length + 1;
549
+ }
550
+ return -1;
551
+ }
552
+
553
+ /** The string delimiter still open after this line, or null when outside one. */
554
+ function scanLineForQuote(line: string, quote: string | null): string | null {
555
+ let open: string | null = quote;
556
+ let i = 0;
557
+ while (i < line.length) {
558
+ const skipped = escapedCharacter(line, i, open);
559
+ if (skipped > 0) { i += skipped; continue; }
560
+ // A `#` OUTSIDE a string starts a comment to end of line: nothing after it is code,
561
+ // so a `'` in `# don't touch this` must not open a string -- measured, it swallowed
562
+ // the rest of the line and the real key below was never found.
563
+ if (open === null && line[i] === '#') return null;
564
+ const delimiter = delimiterAt(line, i);
565
+ open = delimiter === null ? open : nextDelimiter(open, delimiter);
566
+ i += delimiter === null ? 1 : delimiter.length;
418
567
  }
419
- const sourcePathsRegex = /source_paths\s*=\s*\[.*?\]/;
420
- if (sourcePathsRegex.test(existing)) return existing.replace(sourcePathsRegex, sourcePathsLine);
421
- return existing.replace('[tool.mutmut]', `[tool.mutmut]\n${sourcePathsLine}`);
568
+ return open;
569
+ }
570
+
571
+ /**
572
+ * Characters to skip at `i`, or 0 when the character is ordinary.
573
+ *
574
+ * A backslash inside a BASIC string (`"`) escapes the next character, so `\"` is data.
575
+ * Without this the escaped quote ENDED the string, everything after it read as outside,
576
+ * and a valid key was skipped (measured with a real file).
577
+ */
578
+ function escapedCharacter(line: string, i: number, open: string | null): number {
579
+ return open === '"' && line[i] === '\\' ? 2 : 0;
422
580
  }
581
+
582
+ /** The delimiter still open after one is encountered. */
583
+ function nextDelimiter(open: string | null, delimiter: string): string | null {
584
+ if (open === null) return delimiter;
585
+ return open === delimiter ? null : open;
586
+ }
587
+
588
+ /** The TOML string delimiter starting at `i`, or null. LONGEST first, so `\"\"\"` wins. */
589
+ function delimiterAt(line: string, i: number): string | null {
590
+ return QUOTE_DELIMITERS.find((d) => line.startsWith(d, i)) ?? null;
591
+ }
592
+
593
+ /** The TOML string delimiters, longest first so the triple forms win. */
594
+ const QUOTE_DELIMITERS = ['"""', "'''", '"', "'"];
595
+
596
+ /** Where the `source_paths = [...]` value sits in the text, or null. */
597
+ function arraySpan(doc: string): { start: number; end: number } | null {
598
+ const body = mutmutBodyRange(doc);
599
+ if (body === null) return null;
600
+ const keyIndex = findKeyOutsideStrings(doc, body.start, body.end);
601
+ if (keyIndex === -1) return null;
602
+ const close = bracketOnKeyLine(doc, keyIndex);
603
+ return close === -1 ? null : { start: keyIndex, end: close + 1 };
604
+ }
605
+
606
+ /**
607
+ * Where the table body ends: the next TABLE HEADER, skipping string content.
608
+ *
609
+ * A plain `^\[` scan stops at a `[x]` line INSIDE a multi-line string, so the body was
610
+ * cut short and the real key fell outside it -- the array was never rewritten (measured).
611
+ * The line is only a header when it is not inside a string.
612
+ */
613
+ function nextTableStart(doc: string, from: number): number {
614
+ let quote: string | null = null;
615
+ let offset = from;
616
+ for (const line of doc.slice(from).split('\n')) {
617
+ const isHeader = quote === null && TABLE_HEADER.test(line);
618
+ quote = scanLineForQuote(line, quote);
619
+ if (isHeader && quote === null) return offset;
620
+ offset += line.length + 1;
621
+ }
622
+ return doc.length;
623
+ }
624
+
625
+ /** Any TOML table header line. */
626
+ const TABLE_HEADER = /^[^\S\n]*\[/;
627
+
628
+ /**
629
+ * The character range of the `[tool.mutmut]` table body.
630
+ *
631
+ * BOTH bounds matter: without them the search finds the first `source_paths` in the FILE
632
+ * -- another table's, or a fake one inside a multi-line string -- and rewrote the wrong
633
+ * value (measured).
634
+ */
635
+ function mutmutBodyRange(doc: string): { start: number; end: number } | null {
636
+ const header = MUTMUT_HEADER.exec(doc);
637
+ if (!header) return null;
638
+ const start = header.index + header[0].length;
639
+ return { start, end: nextTableStart(doc, start) };
640
+ }
641
+
642
+ /**
643
+ * Index of the `]` closing the array that starts on the key's own line; -1 when there is
644
+ * no array there.
645
+ *
646
+ * The bracket must be on THAT line: searching forward found the next assignment's `[`
647
+ * and replaced everything up to its `]`, DELETING `other = ["a", "b"]` (measured).
648
+ */
649
+ function bracketOnKeyLine(doc: string, keyIndex: number): number {
650
+ const open = doc.indexOf('[', keyIndex);
651
+ if (open === -1) return -1;
652
+ const lineEnd = doc.indexOf('\n', keyIndex);
653
+ if (lineEnd !== -1 && open > lineEnd) return -1;
654
+ return matchingBracket(doc, open);
655
+ }
656
+
657
+ /** Index of the `]` balancing the `[` at `open`, skipping quoted strings; -1 if none. */
658
+ function matchingBracket(doc: string, open: number): number {
659
+ let depth = 0;
660
+ let quote: string | null = null;
661
+ for (let i = open; i < doc.length; i += 1) {
662
+ const step = bracketStep(doc, i, quote);
663
+ if (step.escape) i += 1;
664
+ else quote = endCommentAt(doc[i], step.quote);
665
+ depth += step.delta;
666
+ if (depth === 0) return i;
667
+ }
668
+ return -1;
669
+ }
670
+
671
+ /** What one character does to the bracket scan. */
672
+ interface BracketStep {
673
+ quote: string | null;
674
+ /** +1 for `[`, -1 for `]`, 0 otherwise. */
675
+ delta: number;
676
+ /** A backslash inside a string, so the NEXT character is data. */
677
+ escape: boolean;
678
+ }
679
+
680
+ /** Classify one character for the bracket scan. */
681
+ function bracketStep(doc: string, i: number, quote: string | null): BracketStep {
682
+ const ch = doc[i];
683
+ if (quote === COMMENT) return { quote: COMMENT, delta: 0, escape: false };
684
+ if (quote === null) return outsideString(ch);
685
+ return { quote: ch === quote ? null : quote, delta: 0, escape: ch === '\\' };
686
+ }
687
+
688
+ /** What a character does when the scan is OUTSIDE a string. */
689
+ function outsideString(ch: string): BracketStep {
690
+ if (isQuote(ch)) return { quote: ch, delta: 0, escape: false };
691
+ // A `#` starts a comment that runs to the end of the LINE, and a `]` inside one is
692
+ // prose. Without this the array closed EARLY and the rest of it was left in the file as
693
+ // garbage -- measured: `source_paths = ["new"] tricky` followed by orphaned entries.
694
+ if (ch === '#') return { quote: COMMENT, delta: 0, escape: false };
695
+ return { quote: null, delta: BRACKET_DELTA[ch] ?? 0, escape: false };
696
+ }
697
+
698
+ /** Pseudo-quote standing for "inside a comment", cleared at the newline. */
699
+ const COMMENT = '#';
700
+
701
+ /** End the comment pseudo-quote at a newline; comments do not span lines. */
702
+ function endCommentAt(lineBreak: string, quote: string | null): string | null {
703
+ return quote === COMMENT && lineBreak === '\n' ? null : quote;
704
+ }
705
+
706
+ /** Whether a character opens a TOML string. */
707
+ function isQuote(ch: string): boolean {
708
+ return ch === '"' || ch === "'";
709
+ }
710
+
711
+ /** How each bracket moves the depth, in one place. */
712
+ const BRACKET_DELTA: Record<string, number> = { '[': 1, ']': -1 };
713
+
714
+ /** How each bracket moves the depth, in one place. */