codefactory-cli 0.20.2__tar.gz → 0.21.0__tar.gz

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 (106) hide show
  1. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/PKG-INFO +13 -9
  2. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/README.md +12 -8
  3. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/__init__.py +1 -1
  4. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/generic.py +69 -20
  5. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/parallel.py +23 -9
  6. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/treewalk.py +20 -2
  7. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/ts_helper.js +9 -1
  8. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/typescript.py +53 -22
  9. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/audit.py +25 -7
  10. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/baseline.py +4 -4
  11. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/cache.py +33 -12
  12. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/checks.py +92 -26
  13. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/cli.py +105 -14
  14. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/config.py +22 -3
  15. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/deps.py +51 -21
  16. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/diff.py +75 -29
  17. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/efficiency.py +2 -1
  18. codefactory_cli-0.21.0/codefactory/export.py +254 -0
  19. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/flags.py +6 -1
  20. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/hotspots.py +10 -2
  21. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/infra.py +4 -2
  22. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/org.py +6 -1
  23. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/patch.py +5 -2
  24. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/paths.py +78 -1
  25. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/plan.py +5 -3
  26. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/profile.py +30 -3
  27. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/rerank.py +29 -0
  28. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/review.py +111 -62
  29. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/sarif.py +16 -4
  30. codefactory_cli-0.21.0/codefactory/scope.py +42 -0
  31. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/security.py +32 -16
  32. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/similar.py +9 -4
  33. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/skill.py +15 -3
  34. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/skill_template/SKILL.md +4 -1
  35. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/sqlgraph.py +27 -6
  36. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/viewer/__init__.py +9 -2
  37. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/viewer/factory.css +18 -2
  38. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/viewer/factory.js +31 -12
  39. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/viewer/template.html +7 -2
  40. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory_cli.egg-info/PKG-INFO +13 -9
  41. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory_cli.egg-info/SOURCES.txt +7 -0
  42. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/pyproject.toml +1 -1
  43. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_agent.py +6 -0
  44. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_audit.py +2 -1
  45. codefactory_cli-0.21.0/tests/test_export.py +135 -0
  46. codefactory_cli-0.21.0/tests/test_go_service.py +150 -0
  47. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_profile.py +36 -0
  48. codefactory_cli-0.21.0/tests/test_scope.py +103 -0
  49. codefactory_cli-0.21.0/tests/test_security_audit.py +216 -0
  50. codefactory_cli-0.21.0/tests/test_security_audit2.py +197 -0
  51. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_workflow.py +1 -1
  52. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/LICENSE +0 -0
  53. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/__main__.py +0 -0
  54. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/accept.py +0 -0
  55. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/__init__.py +0 -0
  56. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/python.py +0 -0
  57. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/analyzers/python_parse.py +0 -0
  58. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/apple.py +0 -0
  59. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/brief.py +0 -0
  60. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/coverage.py +0 -0
  61. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/graph.py +0 -0
  62. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/intent.py +0 -0
  63. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/layers.py +0 -0
  64. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/owners.py +0 -0
  65. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/privacy.py +0 -0
  66. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/rules.py +0 -0
  67. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/sbom.py +0 -0
  68. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/skill_template/__init__.py +0 -0
  69. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/suppress.py +0 -0
  70. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/taint.py +0 -0
  71. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/trace.py +0 -0
  72. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory/viewer/dashboard.html +0 -0
  73. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory_cli.egg-info/dependency_links.txt +0 -0
  74. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory_cli.egg-info/entry_points.txt +0 -0
  75. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory_cli.egg-info/requires.txt +0 -0
  76. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/codefactory_cli.egg-info/top_level.txt +0 -0
  77. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/setup.cfg +0 -0
  78. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_accept.py +0 -0
  79. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_apple.py +0 -0
  80. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_bench.py +0 -0
  81. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_cache.py +0 -0
  82. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_cli_errors.py +0 -0
  83. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_coverage.py +0 -0
  84. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_diff.py +0 -0
  85. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_efficiency.py +0 -0
  86. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_findings_review.py +0 -0
  87. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_generic.py +0 -0
  88. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_golden.py +0 -0
  89. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_hotspots.py +0 -0
  90. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_intent.py +0 -0
  91. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_org.py +0 -0
  92. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_parallel.py +0 -0
  93. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_patch.py +0 -0
  94. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_privacy.py +0 -0
  95. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_public_repos.py +0 -0
  96. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_python_scopes.py +0 -0
  97. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_release.py +0 -0
  98. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_review.py +0 -0
  99. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_rules.py +0 -0
  100. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_sarif.py +0 -0
  101. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_security.py +0 -0
  102. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_shop.py +0 -0
  103. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_skill.py +0 -0
  104. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_sql_trace.py +0 -0
  105. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_taint.py +0 -0
  106. {codefactory_cli-0.20.2 → codefactory_cli-0.21.0}/tests/test_typescript.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codefactory-cli
3
- Version: 0.20.2
3
+ Version: 0.21.0
4
4
  Summary: See a codebase as a factory floor, find what's wrong with it (copies, N+1 loops, dead code, import loops, security and reliability problems), and turn it into ranked work.
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/dominickkubica/codefactory
@@ -59,9 +59,10 @@ the number of calls it carries. Dashed orange conveyors run backwards, from a lo
59
59
  pip install "codefactory-cli[languages]"
60
60
  cd path/to/your/repo
61
61
 
62
- codefactory review -o review.md # a technical review of the repository (--online: also vulnerable dependencies)
62
+ codefactory review # a technical review, saved as codefactory-review-<date>.md (--online: also vulnerable dependencies)
63
63
  codefactory view # the interactive map, in your browser
64
64
  codefactory plan # what to fix first, ranked; then: codefactory prompt 1
65
+ codefactory export # every finding as one audit file: give it to Claude to triage into fixes
65
66
  codefactory profile # what kind of project it thinks this is (findings are ranked for it)
66
67
  codefactory hotspots # where change happens: complex code that keeps changing
67
68
  ```
@@ -71,9 +72,9 @@ codefactory hotspots # where change happens: complex code that keeps
71
72
  - **Python 3.11 or newer.** On Windows, run the same commands in PowerShell; use `py -m pip` if `pip` isn't found.
72
73
  On a Mac, `brew install pipx` and then `pipx install "codefactory-cli[languages]"` (Homebrew's Python refuses a
73
74
  plain `pip install`, and the built-in `python3` is too old).
74
- - **TypeScript/JavaScript projects:** run `npm install` in the project first, because codefactory uses the project's
75
- own TypeScript compiler (needs [Node.js](https://nodejs.org)). Without it, those files are still analyzed, less
76
- precisely.
75
+ - **TypeScript/JavaScript projects:** install TypeScript once, `npm install -g typescript@5` (needs
76
+ [Node.js](https://nodejs.org)). codefactory never runs the compiler inside a repository's `node_modules`, since
77
+ that's the repository's code. Without it, those files are still analyzed, less precisely.
77
78
  - **`[languages]`** adds the tree-sitter language pack for everything beyond Python and TypeScript. Leave it out for
78
79
  a dependency-free install.
79
80
  - **Upgrade any time** with `codefactory update`.
@@ -120,7 +121,7 @@ codefactory hotspots # where change happens: complex code that keeps
120
121
  | Language | How calls are resolved | Notes |
121
122
  |---|---|---|
122
123
  | Python | Precisely: imports, `self`/`cls`, classes, re-exports, dispatch tables, `getattr` | Standard library only |
123
- | TypeScript, JavaScript | Precisely: the project's own TypeScript type checker (path aliases, hooks, JSX, lazy `require`) | Needs Node.js and `npm install` |
124
+ | TypeScript, JavaScript | Precisely: the TypeScript type checker, with the project's tsconfig (path aliases, hooks, JSX, lazy `require`) | Needs Node.js and `npm install -g typescript@5` |
124
125
  | Go, Java, Kotlin, Swift, Rust, C, C++, C#, Ruby, PHP, Scala, Dart, Lua, Elixir and more | By name, plus declared types, through tree-sitter | `[languages]` install; grammars download once, then work offline |
125
126
  | Shell, Makefiles, YAML (docker-compose, Kubernetes, GitHub Actions), HTML, Pkl, TOML, Terraform, `.diff`/`.patch` | Not a call graph: line checks for credentials, unsafe commands and configuration | No install needed |
126
127
 
@@ -137,6 +138,7 @@ For the by-name languages, call, impact and unused-code findings are leads to co
137
138
  | `diff` | What a change adds and fixes, compared with the base branch: a pull-request comment, annotations or JSON; `--patch file.diff` checks a patch on its own, no repository needed |
138
139
  | `profile` | What kind of project this is (mobile app, web service, CLI, library…), where it runs, who uses it, what sensitive data it holds, with evidence; the review ranks findings for it |
139
140
  | `hotspots` | From git history: complex code that changes often, files that change together without importing each other, code only one person knows |
141
+ | `export` | Every finding as one audit file (Markdown, or `--json`): ids, severity, complexity, confidence, every location, impact, fix, how to verify, and ready-made fixes; opens with instructions for an AI to triage it into fixes |
140
142
  | `sbom` | A CycloneDX software bill of materials of every pinned dependency |
141
143
  | `org` | A dashboard across many repositories: health, findings, trends, and findings per owning team |
142
144
  | `surface` | The attack surface: every HTTP endpoint, its auth check, and whether it changes data or reaches risky code |
@@ -150,8 +152,10 @@ For the by-name languages, call, impact and unused-code findings are leads to co
150
152
  | `skill` | Teach Claude Code in a repository when and how to use all of the above (`--hook`: keep it current) |
151
153
  | `update` | Upgrade codefactory to the latest version |
152
154
 
153
- Commands that take a name work from inside the repository: `codefactory context checkout`. `codefactory --help` and
154
- `codefactory <command> --help` list every option.
155
+ Commands that take a name work from inside the repository: `codefactory context checkout`. `--no-tests` (or
156
+ `tests = false` in factory.toml) leaves test code out of findings, the plan and the map; copies that exist only between
157
+ tests are listed as info and aren't plan tasks either way. `codefactory --help` and `codefactory <command> --help` list
158
+ every option.
155
159
 
156
160
  ## With Claude Code
157
161
 
@@ -182,7 +186,7 @@ jobs:
182
186
  steps:
183
187
  - uses: actions/checkout@v4
184
188
  with: { fetch-depth: 0 }
185
- - uses: dominickkubica/codefactory@v0 # follows releases; or pin v0.20.2 or a commit SHA
189
+ - uses: dominickkubica/codefactory@v0 # follows releases; or pin v0.21.0 or a commit SHA
186
190
  with: { fail-on: high }
187
191
  ```
188
192
 
@@ -25,9 +25,10 @@ the number of calls it carries. Dashed orange conveyors run backwards, from a lo
25
25
  pip install "codefactory-cli[languages]"
26
26
  cd path/to/your/repo
27
27
 
28
- codefactory review -o review.md # a technical review of the repository (--online: also vulnerable dependencies)
28
+ codefactory review # a technical review, saved as codefactory-review-<date>.md (--online: also vulnerable dependencies)
29
29
  codefactory view # the interactive map, in your browser
30
30
  codefactory plan # what to fix first, ranked; then: codefactory prompt 1
31
+ codefactory export # every finding as one audit file: give it to Claude to triage into fixes
31
32
  codefactory profile # what kind of project it thinks this is (findings are ranked for it)
32
33
  codefactory hotspots # where change happens: complex code that keeps changing
33
34
  ```
@@ -37,9 +38,9 @@ codefactory hotspots # where change happens: complex code that keeps
37
38
  - **Python 3.11 or newer.** On Windows, run the same commands in PowerShell; use `py -m pip` if `pip` isn't found.
38
39
  On a Mac, `brew install pipx` and then `pipx install "codefactory-cli[languages]"` (Homebrew's Python refuses a
39
40
  plain `pip install`, and the built-in `python3` is too old).
40
- - **TypeScript/JavaScript projects:** run `npm install` in the project first, because codefactory uses the project's
41
- own TypeScript compiler (needs [Node.js](https://nodejs.org)). Without it, those files are still analyzed, less
42
- precisely.
41
+ - **TypeScript/JavaScript projects:** install TypeScript once, `npm install -g typescript@5` (needs
42
+ [Node.js](https://nodejs.org)). codefactory never runs the compiler inside a repository's `node_modules`, since
43
+ that's the repository's code. Without it, those files are still analyzed, less precisely.
43
44
  - **`[languages]`** adds the tree-sitter language pack for everything beyond Python and TypeScript. Leave it out for
44
45
  a dependency-free install.
45
46
  - **Upgrade any time** with `codefactory update`.
@@ -86,7 +87,7 @@ codefactory hotspots # where change happens: complex code that keeps
86
87
  | Language | How calls are resolved | Notes |
87
88
  |---|---|---|
88
89
  | Python | Precisely: imports, `self`/`cls`, classes, re-exports, dispatch tables, `getattr` | Standard library only |
89
- | TypeScript, JavaScript | Precisely: the project's own TypeScript type checker (path aliases, hooks, JSX, lazy `require`) | Needs Node.js and `npm install` |
90
+ | TypeScript, JavaScript | Precisely: the TypeScript type checker, with the project's tsconfig (path aliases, hooks, JSX, lazy `require`) | Needs Node.js and `npm install -g typescript@5` |
90
91
  | Go, Java, Kotlin, Swift, Rust, C, C++, C#, Ruby, PHP, Scala, Dart, Lua, Elixir and more | By name, plus declared types, through tree-sitter | `[languages]` install; grammars download once, then work offline |
91
92
  | Shell, Makefiles, YAML (docker-compose, Kubernetes, GitHub Actions), HTML, Pkl, TOML, Terraform, `.diff`/`.patch` | Not a call graph: line checks for credentials, unsafe commands and configuration | No install needed |
92
93
 
@@ -103,6 +104,7 @@ For the by-name languages, call, impact and unused-code findings are leads to co
103
104
  | `diff` | What a change adds and fixes, compared with the base branch: a pull-request comment, annotations or JSON; `--patch file.diff` checks a patch on its own, no repository needed |
104
105
  | `profile` | What kind of project this is (mobile app, web service, CLI, library…), where it runs, who uses it, what sensitive data it holds, with evidence; the review ranks findings for it |
105
106
  | `hotspots` | From git history: complex code that changes often, files that change together without importing each other, code only one person knows |
107
+ | `export` | Every finding as one audit file (Markdown, or `--json`): ids, severity, complexity, confidence, every location, impact, fix, how to verify, and ready-made fixes; opens with instructions for an AI to triage it into fixes |
106
108
  | `sbom` | A CycloneDX software bill of materials of every pinned dependency |
107
109
  | `org` | A dashboard across many repositories: health, findings, trends, and findings per owning team |
108
110
  | `surface` | The attack surface: every HTTP endpoint, its auth check, and whether it changes data or reaches risky code |
@@ -116,8 +118,10 @@ For the by-name languages, call, impact and unused-code findings are leads to co
116
118
  | `skill` | Teach Claude Code in a repository when and how to use all of the above (`--hook`: keep it current) |
117
119
  | `update` | Upgrade codefactory to the latest version |
118
120
 
119
- Commands that take a name work from inside the repository: `codefactory context checkout`. `codefactory --help` and
120
- `codefactory <command> --help` list every option.
121
+ Commands that take a name work from inside the repository: `codefactory context checkout`. `--no-tests` (or
122
+ `tests = false` in factory.toml) leaves test code out of findings, the plan and the map; copies that exist only between
123
+ tests are listed as info and aren't plan tasks either way. `codefactory --help` and `codefactory <command> --help` list
124
+ every option.
121
125
 
122
126
  ## With Claude Code
123
127
 
@@ -148,7 +152,7 @@ jobs:
148
152
  steps:
149
153
  - uses: actions/checkout@v4
150
154
  with: { fetch-depth: 0 }
151
- - uses: dominickkubica/codefactory@v0 # follows releases; or pin v0.20.2 or a commit SHA
155
+ - uses: dominickkubica/codefactory@v0 # follows releases; or pin v0.21.0 or a commit SHA
152
156
  with: { fail-on: high }
153
157
  ```
154
158
 
@@ -1,3 +1,3 @@
1
1
  """codefactory: see a codebase as a factory floor and find dead code, duplicates, import loops and bottlenecks."""
2
2
 
3
- __version__ = "0.20.2"
3
+ __version__ = "0.21.0"
@@ -18,6 +18,7 @@ from collections import Counter, defaultdict
18
18
  from pathlib import Path
19
19
 
20
20
  from ..graph import Edge, File, Function, Graph, Site
21
+ from ..paths import links_outside
21
22
  from . import parallel
22
23
 
23
24
  # extension -> tree-sitter language. Python and TypeScript/JavaScript have their own analyzers.
@@ -81,11 +82,20 @@ JS_LANGS = {
81
82
  # I/O by the receiver's or callee's name: a database, the network, files. Matched on calls nothing in the codebase
82
83
  # defines, so the codebase's own functions are followed instead.
83
84
  IO_RECEIVER = re.compile(
84
- r"(?:^|[.:>])(?:db|database|conn|connection|cursor|session|repo|repository|dao|client|http|https|httpClient|api|"
85
+ r"(?:^|[.:>])(?:db|database|conn|connection|cursor|session|repo|repository|dao|client|httpClient|api|"
85
86
  r"redis|em|entityManager|jdbc|mongo|stmt|statement|pool|tx|s3|bucket|requests|"
86
- r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|Http|HttpClient)\s*(?:\.|->|::)\s*\w+$",
87
+ r"_db|_repo|_client|_http|\$db|\$pdo|pdo|DB|HttpClient)\s*(?:\.|->|::)\s*\w+$",
87
88
  re.I,
88
89
  )
90
+ # `http.` / `https.` is a package or module: only its request functions talk to the network (Go's http.SetCookie,
91
+ # http.HandleFunc, http.Error and http.NewRequest don't)
92
+ HTTP_PACKAGE = re.compile(r"(?:^|[.:>])(?:http|https|Http)\s*(?:\.|->|::)\s*(?:get|post|put|patch|delete|head|"
93
+ r"request|do|send|fetch|postform|urlopen)\w*$", re.I) # fmt: skip
94
+ # migrations step through their changes one at a time on purpose (each its own statement, in order)
95
+ MIGRATION = re.compile(r"(?i)migrat|schema_?lock|upgrade_?schema")
96
+ # startup code runs once, over what's configured (a loop per server, per registry): not a loop over data
97
+ STARTUP = re.compile(r"(?:^|::|\.)(?:main|init|boot\w*|setup\w*|Setup\w*|New\w*|new_\w*|Register\w*|register\w*|"
98
+ r"Start\w*|start\w*|Init\w*|Configure\w*|configure\w*|Bootstrap\w*|Must\w*|Load\w*Config\w*)$") # fmt: skip
89
99
  IO_NAME = re.compile(
90
100
  r"(?:^|[.:>])(?:query|execute|executeQuery|executeUpdate|exec_query|rawQuery|QueryRow|QueryContext|ExecContext|"
91
101
  r"Exec|urlopen|fetch|findById|findOne|findAll|find_by|"
@@ -143,8 +153,9 @@ def find_files(root: Path, ignore: list[str], include_js: bool) -> list[tuple[st
143
153
  for name in sorted(filenames):
144
154
  ext = os.path.splitext(name)[1]
145
155
  lang = exts.get(ext) or exts.get(ext.lower())
146
- if lang and not name.endswith((".d.ts", ".min.js")):
147
- out.append((Path(dirpath, name).relative_to(root).as_posix(), lang))
156
+ rel = Path(dirpath, name).relative_to(root).as_posix()
157
+ if lang and not name.endswith((".d.ts", ".min.js")) and not links_outside(root, rel):
158
+ out.append((rel, lang))
148
159
  return out
149
160
 
150
161
 
@@ -190,10 +201,40 @@ def _import_index(rels: list[str]) -> dict[str, list[str]]:
190
201
  return idx
191
202
 
192
203
 
193
- def _resolve_import(source: str, idx: dict[str, list[str]], lang: str) -> list[str]:
204
+ def _go_modules(root: Path) -> list[tuple[str, str]]:
205
+ """(module path, its folder) for each go.mod: a Go import is the repository's own only under one of them."""
206
+ from ..paths import walk
207
+
208
+ out = []
209
+ for rel in walk(root, names=("go.mod",)):
210
+ try:
211
+ m = re.search(r"^module\s+(\S+)", (root / rel).read_text(encoding="utf-8", errors="replace"), re.M)
212
+ except OSError:
213
+ continue
214
+ if m:
215
+ out.append((m.group(1).strip('"'), rel.rsplit("/", 1)[0] if "/" in rel else ""))
216
+ return sorted(out, key=lambda x: -len(x[0])) # the longest (most specific) module first
217
+
218
+
219
+ def _go_package(source: str, idx: dict[str, list[str]], mods: list[tuple[str, str]]) -> list[str]:
220
+ """A Go import, by its full path: `example.com/app/internal/sync` is the folder internal/sync; `sync`, or anything
221
+ outside the module, is the standard library or a dependency, whatever folders the repository happens to have."""
222
+ source = source.strip().strip('"`')
223
+ for mod, folder in mods:
224
+ if source == mod or source.startswith(mod + "/"):
225
+ key = "/".join(p for p in (folder, source[len(mod) :].strip("/")) if p)
226
+ files = [f for f in idx.get(key + "/", []) if not _is_test(f) and f.rsplit("/", 1)[0] == key]
227
+ return sorted(files, key=lambda f: (Path(f).stem != key.rsplit("/", 1)[-1], f))[:1]
228
+ return []
229
+
230
+
231
+ def _resolve_import(source: str, idx: dict[str, list[str]], lang: str, go_mods: list | None = None) -> list[str]:
194
232
  """The file(s) an import names: the longest path suffix that is a file (C's "net/socket.h", Java's a.b.Orders),
195
- else a package folder, linked through one file (its namesake if there is one). Go imports always name packages.
196
- Among several equal matches the shallowest folder wins; more than three equal files is too ambiguous to link."""
233
+ else a package folder, linked through one file (its namesake if there is one). Go imports always name packages
234
+ (by their full path, when there's a go.mod). Among several equal matches the shallowest folder wins; more than
235
+ three equal files is too ambiguous to link."""
236
+ if lang == "go" and go_mods:
237
+ return _go_package(source, idx, go_mods)
197
238
  s = re.sub(r"\.(?:h|hpp|hh|rb|php|lua|dart|go|rs|java|kt|swift|cs|ex|js|ts)$", "", source.strip())
198
239
  parts = [p for p in re.split(r"[./\\:]+", s) if p and p not in ("crate", "self", "super", "~", "@", "..")]
199
240
  # the path as written, then without its last part: `import a.b.fn` (Kotlin, Java static) names something inside a.b
@@ -232,7 +273,7 @@ def analyze_generic(root: Path, ignore: list[str], include_js: bool = False, cac
232
273
  )
233
274
  return g
234
275
  items = [(rel, (str(root / rel), rel, lang)) for rel, lang in found]
235
- parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-4", cache=cache)
276
+ parsed = parallel.run(root, "generic", items, parse_file, tool="treewalk-5", cache=cache)
236
277
  return link(g, parsed, rails_associations(root, [rel for rel, _ in found if rel.endswith(".rb")]))
237
278
 
238
279
 
@@ -278,13 +319,14 @@ def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = No
278
319
  langs = Counter(d["lang"] for d in parsed.values())
279
320
  g.language = "+".join(sorted(langs))
280
321
  idx = _import_index(list(parsed))
322
+ go_mods = _go_modules(Path(g.root)) if g.root and any(d["lang"] == "go" for d in parsed.values()) else []
281
323
  defs: dict[str, list[str]] = defaultdict(list) # name -> function ids
282
324
  file_of: dict[str, str] = {}
283
325
  kind_of: dict[str, str] = {}
284
326
  imported: dict[str, set[str]] = {}
285
327
  for rel, d in sorted(parsed.items()):
286
328
  g.files.append(File(id=rel, module=rel.rsplit(".", 1)[0].replace("/", "."), loc=d["loc"]))
287
- imported[rel] = {dst for src in d["imports"] for dst in _resolve_import(src, idx, d["lang"]) if dst != rel}
329
+ imported[rel] = {dst for src in d["imports"] for dst in _resolve_import(src, idx, d["lang"], go_mods) if dst != rel}
288
330
  g.edges += [Edge(rel, dst, "import") for dst in sorted(imported[rel])]
289
331
  top = Function(id=f"{rel}::<module>", file=rel, name="<module>", qualname="<module>", line=1, end=1, loc=0, kind="module")
290
332
  g.functions.append(top)
@@ -357,30 +399,37 @@ def link(g: Graph, parsed: dict[str, dict], associations: re.Pattern | None = No
357
399
  target, cands = resolve(name, src)
358
400
  for c in [target] if target else cands if len(cands) <= 3 else ():
359
401
  refs[(src, c)] += 1
360
- for name, line, in_loop, callee in rec["calls"]:
402
+ startup = bool(STARTUP.search(src) or MIGRATION.search(src))
403
+ for name, line, in_loop, callee, *rest in rec["calls"]:
404
+ route = bool(rest and rest[0])
361
405
  target, cands = resolve(name, src, bare=not re.search(r"\.|->|::", callee), callee=callee)
362
406
  if target:
363
407
  calls[(src, target)] += 1
364
408
  if in_loop:
365
- g.sites.append(Site(src, "loop_call", line, target=target))
409
+ g.sites.append(Site(src, "loop_call", line, target=target, bounded=startup))
366
410
  continue
367
411
  if len(cands) <= 3:
368
412
  for c in cands:
369
413
  refs[(src, c)] += 1
370
414
  else: # called by a name many things define (String, Error, Read): any of them may be what runs
371
415
  ambiguous.add(name)
372
- if not cands and (
373
- IO_RECEIVER.search(callee)
374
- or IO_NAME.search(callee)
375
- or (src.split("::")[0].endswith(ORM_LANGS) and ORM_NAME.search(callee))
376
- or (src.split("::")[0].endswith(".swift") and SWIFT_STORE.search(callee))
377
- or (_typed_io(callee, types) and (ORM_NAME.search(callee) or IO_VERB.search(callee)))
378
- or (src.split("::")[0].endswith(".rb") and AR.search(callee))
379
- or (associations and src.split("::")[0].endswith(".rb") and associations.search(callee))
416
+ if (
417
+ not cands
418
+ and not route
419
+ and (
420
+ IO_RECEIVER.search(callee)
421
+ or HTTP_PACKAGE.search(callee)
422
+ or IO_NAME.search(callee)
423
+ or (src.split("::")[0].endswith(ORM_LANGS) and ORM_NAME.search(callee))
424
+ or (src.split("::")[0].endswith(".swift") and SWIFT_STORE.search(callee))
425
+ or (_typed_io(callee, types) and (ORM_NAME.search(callee) or IO_VERB.search(callee)))
426
+ or (src.split("::")[0].endswith(".rb") and AR.search(callee))
427
+ or (associations and src.split("::")[0].endswith(".rb") and associations.search(callee))
428
+ )
380
429
  ):
381
430
  io.add(callee)
382
431
  if in_loop:
383
- g.sites.append(Site(src, "loop_io", line, detail=callee))
432
+ g.sites.append(Site(src, "loop_io", line, detail=callee, bounded=startup))
384
433
  if src in by_id:
385
434
  by_id[src].io = sorted(io)
386
435
  framework = {f["id"] for d in parsed.values() for f in d["functions"] if f.get("framework")}
@@ -11,6 +11,7 @@ from __future__ import annotations
11
11
 
12
12
  import json
13
13
  import os
14
+ import time
14
15
  from collections.abc import Callable
15
16
  from concurrent.futures import ProcessPoolExecutor
16
17
  from pathlib import Path
@@ -28,29 +29,41 @@ def workers() -> int:
28
29
  return max(1, min(32, (os.cpu_count() or 1)))
29
30
 
30
31
 
31
- def _stamp(path: Path) -> str:
32
+ def _stamp(path: Path, now_ns: int = 0) -> str:
33
+ """The file's stamp; "" (never matches) when it changed too recently to trust (see paths.racy)."""
34
+ from ..paths import file_stamp, racy
35
+
32
36
  st = path.stat()
33
- return f"{st.st_size}:{st.st_mtime_ns}"
37
+ return "" if now_ns and racy(st, now_ns) else file_stamp(st)
38
+
34
39
 
40
+ def _cache_file(root: Path, name: str) -> Path | None:
41
+ from ..paths import cache_dir
35
42
 
36
- def _cache_file(root: Path, name: str) -> Path:
37
- return root / ".codefactory" / f"files-{name}.json"
43
+ d = cache_dir(root)
44
+ return d / f"files-{name}.json" if d else None
38
45
 
39
46
 
40
47
  def _load(root: Path, name: str, tool: str) -> dict:
48
+ path = _cache_file(root, name)
49
+ if path is None:
50
+ return {}
41
51
  try:
42
- data = json.loads(_cache_file(root, name).read_text(encoding="utf-8"))
52
+ data = json.loads(path.read_text(encoding="utf-8"))
43
53
  except (OSError, ValueError):
44
54
  return {}
45
55
  return data.get("files", {}) if data.get("tool") == tool else {}
46
56
 
47
57
 
48
58
  def _save(root: Path, name: str, tool: str, files: dict) -> None:
59
+ path = _cache_file(root, name)
60
+ if path is None:
61
+ return # untrusted cache folder
49
62
  try:
50
- d = root / ".codefactory"
63
+ d = path.parent
51
64
  d.mkdir(exist_ok=True)
52
65
  (d / ".gitignore").write_text("# codefactory's cache: never committed\n*\n", encoding="utf-8")
53
- _cache_file(root, name).write_text(json.dumps({"tool": tool, "files": files}), encoding="utf-8")
66
+ path.write_text(json.dumps({"tool": tool, "files": files}), encoding="utf-8")
54
67
  except OSError:
55
68
  pass # a read-only checkout: analyze in full each time
56
69
 
@@ -70,13 +83,14 @@ def run(
70
83
  out: dict[str, dict] = {}
71
84
  stamps: dict[str, str] = {}
72
85
  todo: list[tuple[str, tuple]] = []
86
+ now_ns = time.time_ns()
73
87
  for rel, args in items:
74
88
  try:
75
- stamps[rel] = _stamp(root / rel)
89
+ stamps[rel] = _stamp(root / rel, now_ns)
76
90
  except OSError:
77
91
  continue
78
92
  hit = old.get(rel)
79
- if hit and hit[0] == stamps[rel]:
93
+ if hit and stamps[rel] and hit[0] == stamps[rel]:
80
94
  if hit[1] is not None:
81
95
  out[rel] = hit[1]
82
96
  else:
@@ -108,6 +108,24 @@ def _last_ident(node, depth: int = 0) -> str:
108
108
  return ""
109
109
 
110
110
 
111
+ BATCHED = re.compile(r"(?i)\b(?:batch|chunk|page)\w*\b|\+=\s*(?:\w*(?:size|Size|limit|Limit|max|Max)\w*|\d{2,})")
112
+
113
+
114
+ def _batched(loop) -> bool:
115
+ """`for _, batch := range batches`, `for i := 0; i < n; i += 1000`: a loop over batches is the batching, one
116
+ call per batch is what the fix for one call per item looks like."""
117
+ head = loop.text.decode("utf-8", "replace").split("{", 1)[0].split("\n", 1)[0][:200]
118
+ return BATCHED.search(head) is not None
119
+
120
+
121
+ def _route_call(node) -> bool:
122
+ """`r.Get("/users", h)`, `r.Get("/api/"+p, h)`, `app.post('/x', …)`: registering a route (its first argument a
123
+ path), not making a request, though the method is named like one."""
124
+ args = node.child_by_field_name("arguments")
125
+ first = next(iter(args.named_children), None) if args is not None else None
126
+ return first is not None and re.match(r"""^[`"']/""", first.text.decode("utf-8", "replace")) is not None
127
+
128
+
111
129
  def _callee_text(node) -> str:
112
130
  """`repo.find`: the callee as written. Java, Ruby and PHP keep the receiver and the method name in separate fields
113
131
  (object/receiver + name/method); others have one function expression."""
@@ -250,14 +268,14 @@ def walk(source: bytes, parser, rel: str) -> dict:
250
268
  if fn is not None and (BRANCH.search(t) or t in ("&&", "||", "and", "or", "??", "orelse", "andalso")):
251
269
  fn["branches"] += 1
252
270
  in_loop = loops
253
- if LOOP.search(t) and not NOT_LOOP.search(t) and node.named_children:
271
+ if LOOP.search(t) and not NOT_LOOP.search(t) and node.named_children and not _batched(node):
254
272
  in_loop = loops + 1
255
273
  if CALL.match(t):
256
274
  name = _name(node, call=True)
257
275
  if name in REQUIRE and fn is None: # Ruby, Lua, PHP, Elixir: imports are calls
258
276
  out["imports"] += [s for s in _import_sources(node)[:1] if s != name]
259
277
  elif name:
260
- owner["calls"].append([name, node.start_point[0] + 1, loops > 0, _callee_text(node)])
278
+ owner["calls"].append([name, node.start_point[0] + 1, loops > 0, _callee_text(node), _route_call(node)])
261
279
  if name in ITER: # the closure it's given runs per item
262
280
  for c in node.named_children:
263
281
  if CLOSURE.search(c.type) or any(CLOSURE.search(g.type) for g in c.named_children):
@@ -12,9 +12,17 @@ const ts = require(tsPath);
12
12
  const ignore = new Set(JSON.parse(ignoreJson || "[]"));
13
13
  const EXT = /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;
14
14
  const rel = (f) => path.relative(root, f).split(path.sep).join("/");
15
+ const realRoot = fs.realpathSync(root);
16
+ // a link to somewhere outside the repository: not its code (a pull request can commit `a.ts -> ~/.npmrc`)
17
+ const outside = (f) => {
18
+ try {
19
+ const r = path.relative(realRoot, fs.realpathSync(f));
20
+ return r.startsWith("..") || path.isAbsolute(r);
21
+ } catch { return true; }
22
+ };
15
23
  const skipped = (f) => {
16
24
  const parts = rel(f).split("/");
17
- return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..");
25
+ return parts.slice(0, -1).some((p) => ignore.has(p) || (p.startsWith(".") && p !== "." && p !== "..")) || /\.d\.[mc]?ts$|\.min\.[mc]?js$/.test(f) || !EXT.test(f) || rel(f).startsWith("..") || outside(f);
18
26
  };
19
27
 
20
28
  function walkDir(dir, out) {
@@ -1,8 +1,10 @@
1
1
  """TypeScript / JavaScript analyzer. The parsing and call resolution run in Node (ts_helper.js) with the TypeScript
2
2
  compiler, because only the type checker can tell what `obj.method()` or a function from a React hook really is.
3
3
 
4
- Needs Node on PATH and the `typescript` package: the analyzed repo's own (node_modules/typescript) is used first,
5
- then a global install (npm install -g typescript), or CODEFACTORY_TYPESCRIPT pointing at one.
4
+ Needs Node on PATH and a TypeScript 5.x compiler the user installed: CODEFACTORY_TYPESCRIPT pointing at one, or a
5
+ global install (npm install -g typescript@5). Never the one inside the analyzed repository: its node_modules is the
6
+ repository's code (a pull request could commit one), and codefactory never runs the code it analyzes. The compiler
7
+ only parses and type-checks; module resolution (tsconfig paths, aliases) comes from the project's own files either way.
6
8
  """
7
9
 
8
10
  from __future__ import annotations
@@ -13,6 +15,7 @@ import os
13
15
  import shutil
14
16
  import subprocess
15
17
  import sys
18
+ import time
16
19
  from importlib.resources import files as pkg_files
17
20
  from pathlib import Path
18
21
 
@@ -26,10 +29,15 @@ class TypeScriptUnavailable(RuntimeError):
26
29
 
27
30
 
28
31
  def sources_stamp(root: Path, ignore: list[str]) -> str:
29
- """A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none)."""
32
+ """A fingerprint of every TypeScript/JavaScript file and tsconfig (empty when there are none; "racy" when one
33
+ changed too recently to trust, so the result isn't reused)."""
34
+ from ..paths import file_stamp
35
+ from ..paths import racy as too_recent
36
+
30
37
  skip = set(ignore)
31
38
  h = hashlib.sha1()
32
- found = False
39
+ found = racy = False
40
+ now_ns = time.time_ns()
33
41
  for dirpath, dirnames, filenames in os.walk(root):
34
42
  dirnames[:] = sorted(d for d in dirnames if d not in skip)
35
43
  for f in sorted(filenames):
@@ -39,32 +47,51 @@ def sources_stamp(root: Path, ignore: list[str]) -> str:
39
47
  st = os.stat(os.path.join(dirpath, f))
40
48
  except OSError:
41
49
  continue
42
- h.update(
43
- f"{os.path.relpath(os.path.join(dirpath, f), root)}|{st.st_size}|{st.st_mtime_ns}\n".encode(
44
- "utf-8", "surrogatepass"
45
- )
46
- )
47
- return h.hexdigest() if found else ""
50
+ racy = racy or too_recent(st, now_ns)
51
+ h.update(f"{os.path.relpath(os.path.join(dirpath, f), root)}|{file_stamp(st)}\n".encode("utf-8", "surrogatepass"))
52
+ return ("racy" if racy else h.hexdigest()) if found else ""
53
+
54
+
55
+ def has_api(folder) -> bool:
56
+ """A TypeScript package with the JavaScript compiler API (5.x and earlier). TypeScript 7, the native rewrite, ships
57
+ only an unstable API, so requiring it fails."""
58
+ return (Path(folder) / "lib" / "typescript.js").is_file()
59
+
60
+
61
+ def _outside(folder: Path, root: Path) -> bool:
62
+ """Not inside the analyzed repository (a global install can't be the repository's own code)."""
63
+ try:
64
+ return not folder.resolve().is_relative_to(Path(root).resolve())
65
+ except OSError:
66
+ return False
48
67
 
49
68
 
50
69
  def find_typescript(root: Path, node: str) -> str:
51
70
  env = os.environ.get("CODEFACTORY_TYPESCRIPT")
52
71
  if env:
72
+ if not has_api(env):
73
+ raise TypeScriptUnavailable(f"CODEFACTORY_TYPESCRIPT ({env}) isn't a TypeScript 5.x package (no lib/typescript.js).")
53
74
  return env
54
- local = root / "node_modules" / "typescript"
55
- if (local / "package.json").is_file():
56
- return str(local)
75
+ # a global install: next to node first (no subprocess); then npm, run from the home folder so the analyzed
76
+ # repository's .npmrc (which could set `prefix` to a folder inside it) isn't read
77
+ bin_dir = Path(node).resolve().parent if node else None
78
+ candidates = []
79
+ if bin_dir: # (Linux and macOS: <prefix>/lib/node_modules; Windows: next to node.exe)
80
+ candidates = [bin_dir.parent / "lib" / "node_modules" / "typescript", bin_dir / "node_modules" / "typescript"]
57
81
  try:
58
- npm_root = subprocess.run(
59
- ["npm", "root", "-g"], capture_output=True, text=True, timeout=30, shell=sys.platform == "win32"
60
- ).stdout.strip()
61
- if npm_root and (Path(npm_root) / "typescript" / "package.json").is_file():
62
- return str(Path(npm_root) / "typescript")
63
- except (OSError, subprocess.SubprocessError):
82
+ npm_root = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=30, cwd=Path.home(),
83
+ shell=sys.platform == "win32").stdout.strip() # fmt: skip
84
+ if npm_root:
85
+ candidates.append(Path(npm_root) / "typescript")
86
+ except (OSError, subprocess.SubprocessError, RuntimeError): # (RuntimeError: no home folder)
64
87
  pass
88
+ for c in candidates:
89
+ if has_api(c) and _outside(c, root):
90
+ return str(c)
65
91
  raise TypeScriptUnavailable(
66
- "TypeScript files found, but the typescript package isn't installed. Run `npm install` in the repo, "
67
- "or `npm install -g typescript`, or set CODEFACTORY_TYPESCRIPT to its folder."
92
+ "TypeScript files found, but no TypeScript compiler of your own is installed: `npm install -g typescript@5` (or "
93
+ "set CODEFACTORY_TYPESCRIPT to its folder). codefactory never runs the one in the repository's node_modules: "
94
+ "that's the repository's code."
68
95
  )
69
96
 
70
97
 
@@ -76,7 +103,11 @@ def analyze_typescript(root: Path, ignore: list[str], cache: bool = True) -> Gra
76
103
  from .parallel import _tool_hash
77
104
 
78
105
  stamp = f"{stamp}|{_tool_hash()}"
79
- saved = root / ".codefactory" / "typescript.json"
106
+ from ..paths import cache_dir
107
+
108
+ folder = cache_dir(root) if cache and not stamp.startswith("racy") else None # racy: nothing to reuse or keep
109
+ cache = folder is not None
110
+ saved = folder / "typescript.json" if folder else None
80
111
  data = None
81
112
  if cache:
82
113
  try: