@akanjs/devkit 3.2.0-rc.9 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (341) hide show
  1. package/CHANGELOG.md +0 -529
  2. package/DEV_RUNTIME_KNOBS.md +4 -3
  3. package/README.ko.md +3 -2
  4. package/README.md +4 -2
  5. package/akanApp/BackendImportGraph.test.ts +1 -1
  6. package/akanApp/akanApp.host.test.ts +132 -3
  7. package/akanApp/akanApp.host.ts +146 -1216
  8. package/akanApp/akanApp.host.wiring.test.ts +727 -0
  9. package/akanApp/builderGap.ts +68 -0
  10. package/akanApp/builderRequestRelay.test.ts +93 -0
  11. package/akanApp/builderRequestRelay.ts +100 -0
  12. package/akanApp/builderRssRecycler.ts +182 -0
  13. package/akanApp/devBackend.ts +392 -0
  14. package/akanApp/devBuildStatusBoard.ts +128 -0
  15. package/akanApp/devBuilder.ts +196 -0
  16. package/akanApp/devIdleSuspend.test.ts +221 -0
  17. package/akanApp/devIdleSuspend.ts +192 -0
  18. package/akanApp/devIdleSuspend.watcher.test.ts +120 -0
  19. package/akanApp/devRecycler.test.ts +66 -0
  20. package/akanApp/devRecycler.ts +305 -0
  21. package/akanApp/processRss.ts +61 -0
  22. package/akanConfig/akanConfig.test.ts +45 -17
  23. package/akanConfig/akanConfig.ts +10 -10
  24. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  25. package/akanConfig/productionLockfile.ts +1 -1
  26. package/apiReport/apiReport.test.ts +34 -3
  27. package/apiReport/apiReportDiff.ts +35 -1
  28. package/apiReport/apiReportPolicy.ts +3 -2
  29. package/{applicationBuildReporter.ts → app/applicationBuildReporter.ts} +2 -49
  30. package/{applicationBuildRunner.test.ts → app/applicationBuildRunner.test.ts} +71 -8
  31. package/{applicationBuildRunner.ts → app/applicationBuildRunner.ts} +60 -21
  32. package/{applicationTestPreload.ts → app/applicationTestPreload.ts} +1 -1
  33. package/{routeJsBudget.test.ts → app/routeJsBudget.test.ts} +17 -1
  34. package/{routeJsBudget.ts → app/routeJsBudget.ts} +9 -3
  35. package/{routeSourceValidator.test.ts → app/routeSourceValidator.test.ts} +17 -0
  36. package/{routeSourceValidator.ts → app/routeSourceValidator.ts} +5 -1
  37. package/artifact/implicitRootLayout.test.ts +71 -3
  38. package/artifact/implicitRootLayout.ts +9 -3
  39. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  40. package/biome.base.json +2 -1
  41. package/cloud/cloudApi.test.ts +1 -1
  42. package/cloud/configLock.test.ts +1 -1
  43. package/cloud/globalConfig.test.ts +1 -1
  44. package/cloud/globalConfig.ts +1 -1
  45. package/cloud/updatePackUpload.test.ts +1 -1
  46. package/codeAgent/agent/AkanCodeEnv.ts +1 -1
  47. package/codeAgent/agent/AkanCodeServices.ts +23 -0
  48. package/codeAgent/agent/akanCodePaths.ts +1 -1
  49. package/codeAgent/agent/akanCodeServices.test.ts +54 -0
  50. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  51. package/codeAgent/agent/codeAgent.test.ts +1 -1
  52. package/codeAgent/skills/akan-debug/SKILL.md +8 -5
  53. package/codeAgent/skills/akan-err/SKILL.md +7 -0
  54. package/codeAgent/skills/akan-mcp/SKILL.md +19 -1
  55. package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
  56. package/codeAgent/skills/akan-validate/SKILL.md +3 -3
  57. package/codeAgent/tools/AkanCli.ts +1 -1
  58. package/codeAgent/tools/AkanToolPack.ts +2 -2
  59. package/codeAgent/tools/akanCodePlugins.test.ts +1 -1
  60. package/commandDecorators/command.ts +35 -6
  61. package/commandDecorators/commandBuilder.ts +1 -1
  62. package/commandDecorators/commandDecorators.test.ts +107 -6
  63. package/commandDecorators/targetMeta.ts +2 -0
  64. package/commandDecorators/workspaceVersionCheck.test.ts +70 -1
  65. package/commandDecorators/workspaceVersionCheck.ts +64 -14
  66. package/context/akanContext.ts +576 -0
  67. package/context/akanContextInspection.ts +296 -0
  68. package/{akanMcpContract.test.ts → context/akanMcpContract.test.ts} +1 -1
  69. package/{akanMcpContract.ts → context/akanMcpContract.ts} +16 -256
  70. package/context/doctor/agentGuideCheck.ts +81 -0
  71. package/context/doctor/configLeftoverCheck.ts +35 -0
  72. package/context/doctor/doctorFindings.ts +70 -0
  73. package/context/doctor/generatedFreshness.ts +56 -0
  74. package/context/doctor/moduleShapeCheck.ts +88 -0
  75. package/context/doctor/recipeDuplicateCheck.ts +42 -0
  76. package/context/doctor/recipeIndexCheck.ts +87 -0
  77. package/context/doctor/rootShapeCheck.ts +55 -0
  78. package/context/doctor/workflowScope.ts +97 -0
  79. package/{recipeScanner.test.ts → context/recipeScanner.test.ts} +1 -1
  80. package/context/safeRead.ts +9 -0
  81. package/csrE2e/csrE2eHarness.fixture.ts +1 -1
  82. package/devkitUtils.test.ts +39 -5
  83. package/{apiReference.test.ts → docs/apiReference.test.ts} +4 -4
  84. package/{apiReference.ts → docs/apiReference.ts} +2 -2
  85. package/docs/errorCodeReference.test.ts +282 -0
  86. package/docs/errorCodeReference.ts +71 -0
  87. package/docs/errorCodeScan.ts +551 -0
  88. package/{frameworkGraph.test.ts → docs/frameworkGraph.test.ts} +1 -1
  89. package/executors/appExecutor.ts +448 -0
  90. package/executors/commandExecutionError.ts +53 -0
  91. package/executors/executor.ts +527 -0
  92. package/{executors.linkFallback.test.ts → executors/executors.linkFallback.test.ts} +1 -1
  93. package/{executors.test.ts → executors/executors.test.ts} +76 -15
  94. package/executors/index.ts +8 -0
  95. package/executors/libExecutor.ts +23 -0
  96. package/executors/moduleExecutor.ts +18 -0
  97. package/executors/pkgExecutor.ts +129 -0
  98. package/executors/sysExecutor.ts +301 -0
  99. package/executors/workspaceExecutor.ts +277 -0
  100. package/frontendBuild/allRoutesBuilder.test.ts +1 -1
  101. package/frontendBuild/autoImportSync.test.ts +1 -1
  102. package/frontendBuild/autoImportSync.ts +1 -1
  103. package/frontendBuild/buildRouteClient.test.ts +1 -1
  104. package/frontendBuild/clientEntriesBundler.test.ts +1 -1
  105. package/frontendBuild/csrArtifactBuilder.test.ts +1 -1
  106. package/frontendBuild/csrDevArtifactWriter.ts +1 -1
  107. package/frontendBuild/cssCompiler.test.ts +3 -2
  108. package/frontendBuild/devGeneratedIndexSync.test.ts +1 -1
  109. package/frontendBuild/devGeneratedIndexSync.ts +7 -38
  110. package/frontendBuild/dictionaryAssetBuilder.test.ts +1 -1
  111. package/frontendBuild/fontOptimizer.test.ts +1 -1
  112. package/frontendBuild/fontPruner.test.ts +1 -1
  113. package/frontendBuild/frontendBuild.test.ts +3 -3
  114. package/frontendBuild/hmrWatcher.stop.test.ts +63 -0
  115. package/frontendBuild/hmrWatcher.test.ts +1 -1
  116. package/frontendBuild/hmrWatcher.ts +22 -1
  117. package/frontendBuild/mcpAppViewBuilder.test.ts +1 -1
  118. package/frontendBuild/mcpAppViewBuilder.ts +1 -1
  119. package/frontendBuild/nativeCore.test.ts +1 -1
  120. package/frontendBuild/optionalPeers.test.ts +36 -8
  121. package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
  122. package/frontendBuild/pagesBundleBuilder.ts +1 -1
  123. package/frontendBuild/precompressArtifacts.test.ts +1 -1
  124. package/frontendBuild/precompressArtifacts.ts +19 -6
  125. package/frontendBuild/serverGraphFile.ts +1 -1
  126. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  127. package/frontendBuild/ssrDevBundler.test.ts +1 -1
  128. package/frontendBuild/vendorImportScanner.test.ts +1 -1
  129. package/frontendBuild/vendorNarrowing.test.ts +1 -1
  130. package/frontendBuild/watchRootResolver.test.ts +1 -1
  131. package/{agentAssets.test.ts → guideline/agentAssets.test.ts} +1 -1
  132. package/{agentAssets.ts → guideline/agentAssets.ts} +2 -2
  133. package/{agentsIndex.test.ts → guideline/agentsIndex.test.ts} +2 -2
  134. package/{agentsIndex.ts → guideline/agentsIndex.ts} +13 -10
  135. package/{conventionSet.test.ts → guideline/conventionSet.test.ts} +7 -4
  136. package/{conventionSet.ts → guideline/conventionSet.ts} +1 -1
  137. package/{prompter.ts → guideline/prompter.ts} +2 -3
  138. package/incrementalBuilder/buildBatch.proc.ts +14 -4
  139. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  140. package/incrementalBuilder/buildBatchRunner.test.ts +122 -2
  141. package/incrementalBuilder/buildBatchRunner.ts +17 -4
  142. package/incrementalBuilder/builderBoot.ts +106 -0
  143. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  144. package/incrementalBuilder/builderChannel.test.ts +1 -1
  145. package/incrementalBuilder/builderChannel.ts +11 -0
  146. package/incrementalBuilder/builderGraphPayloads.ts +3 -3
  147. package/incrementalBuilder/builderLanes.ts +157 -0
  148. package/incrementalBuilder/builderWatch.ts +213 -0
  149. package/incrementalBuilder/csrRegistry.ts +234 -0
  150. package/incrementalBuilder/incrementalBuilder.proc.test.ts +101 -7
  151. package/incrementalBuilder/incrementalBuilder.proc.ts +81 -823
  152. package/incrementalBuilder/ssrRegistry.ts +282 -0
  153. package/index.ts +22 -22
  154. package/integration/devStability.integration.test.ts +62 -56
  155. package/integration/devStabilityHarness.test.ts +1 -1
  156. package/lint/__fixtures__/no-import-common-err/bad.tsx +13 -0
  157. package/lint/__fixtures__/no-import-common-err/good.tsx +12 -0
  158. package/{biomeBase.test.ts → lint/biomeBase.test.ts} +1 -1
  159. package/lint/gritRules.test.ts +1 -1
  160. package/{linter.test.ts → lint/linter.test.ts} +1 -1
  161. package/lint/no-import-common-err.grit +31 -0
  162. package/lint/no-init-fetch-in-client.grit +1 -1
  163. package/mobile/desktopBin.test.ts +1 -1
  164. package/mobile/desktopRelease.test.ts +1 -1
  165. package/mobile/desktopServerStage.test.ts +2 -2
  166. package/mobile/desktopServerStage.ts +1 -1
  167. package/mobile/nativeApi.test.ts +1 -1
  168. package/mobile/nativeApp.test.ts +1 -1
  169. package/mobile/nativeConfig.test.ts +1 -1
  170. package/mobile/nativePluginFolders.test.ts +1 -1
  171. package/mobile/nativePublicEnv.test.ts +1 -1
  172. package/mobile/nativeWebDir.test.ts +1 -1
  173. package/mobile/serverBundleSecrets.test.ts +1 -1
  174. package/mobile/tarWriter.test.ts +1 -1
  175. package/mobile/updatePackFolder.test.ts +1 -1
  176. package/package.json +173 -9
  177. package/packageExports.test.ts +20 -2
  178. package/piDependencyPins.test.ts +1 -1
  179. package/pipeline/PipelineDefinition.ts +1 -1
  180. package/platformTest/IdleWatchedProcess.test.ts +1 -1
  181. package/platformTest/LinuxDockerTarget.ts +1 -1
  182. package/platformTest/PlatformTestRun.test.ts +1 -1
  183. package/platformTest/TestSnapshot.test.ts +1 -1
  184. package/platformTest/WindowsSshTarget.ts +1 -1
  185. package/preview/previewView.test.ts +23 -1
  186. package/{abstractDoc.test.ts → quality/abstractDoc.test.ts} +2 -2
  187. package/{abstractDoc.ts → quality/abstractDoc.ts} +1 -1
  188. package/quality/bareErrorScanner.ts +126 -0
  189. package/{maintainabilityBaseline.test.ts → quality/maintainabilityBaseline.test.ts} +73 -0
  190. package/{maintainabilityBaseline.ts → quality/maintainabilityBaseline.ts} +97 -9
  191. package/{maintainabilityContract.test.ts → quality/maintainabilityContract.test.ts} +383 -2
  192. package/{maintainabilityContract.ts → quality/maintainabilityContract.ts} +151 -29
  193. package/{maintainabilityExceptionScanner.test.ts → quality/maintainabilityExceptionScanner.test.ts} +15 -1
  194. package/{maintainabilityExceptionScanner.ts → quality/maintainabilityExceptionScanner.ts} +5 -1
  195. package/{maintainabilityLimits.ts → quality/maintainabilityLimits.ts} +12 -0
  196. package/{maintainabilityReport.ts → quality/maintainabilityReport.ts} +20 -3
  197. package/{qualityScanner.test.ts → quality/qualityScanner.test.ts} +41 -1
  198. package/{qualityScanner.ts → quality/qualityScanner.ts} +25 -91
  199. package/{storeAccessScanner.ts → quality/storeAccessScanner.ts} +15 -2
  200. package/quality/workspaceSourceFiles.ts +82 -0
  201. package/{subspace.test.ts → subspace/subspace.test.ts} +25 -4
  202. package/{subspace.ts → subspace/subspace.ts} +5 -5
  203. package/{subspaceClone.ts → subspace/subspaceClone.ts} +8 -8
  204. package/{subspaceConfig.ts → subspace/subspaceConfig.ts} +5 -1
  205. package/{testHelpers.ts → test/testHelpers.ts} +37 -1
  206. package/transforms/barrelAnalyzer.ts +31 -10
  207. package/transforms/browserDirnamePlugin.test.ts +1 -1
  208. package/transforms/externalizeFrameworkPlugin.test.ts +1 -1
  209. package/transforms/mcpAppPageTrimmer.test.ts +1 -1
  210. package/transforms/pureLazyMarker.test.ts +1 -1
  211. package/transforms/serverEnvPlugin.test.ts +1 -1
  212. package/transforms/serverEnvProfile.test.ts +1 -1
  213. package/transforms/sideEffectImportOrder.test.ts +1 -1
  214. package/transforms/transforms.test.ts +52 -2
  215. package/transforms/tsconfigPackageResolver.test.ts +1 -1
  216. package/{createTunnel.test.ts → tunnel/createTunnel.test.ts} +1 -1
  217. package/{createTunnel.ts → tunnel/createTunnel.ts} +2 -2
  218. package/{sshHostKeys.ts → tunnel/sshHostKeys.ts} +2 -2
  219. package/typecheck/projectTypecheck.test.ts +23 -1
  220. package/typecheck/projectTypecheck.ts +10 -2
  221. package/{typeChecker.test.ts → typecheck/typeChecker.test.ts} +1 -1
  222. package/{typeChecker.ts → typecheck/typeChecker.ts} +5 -4
  223. package/typecheck/typecheck.proc.ts +6 -2
  224. package/typecheck/typecheckFailure.ts +1 -1
  225. package/util/errorReport.ts +66 -0
  226. package/{jsonFormatter.test.ts → util/jsonFormatter.test.ts} +1 -1
  227. package/workflow/constantSource.ts +187 -0
  228. package/workflow/dictionarySource.ts +184 -0
  229. package/workflow/executor.ts +6 -9
  230. package/workflow/fieldExpression.ts +153 -0
  231. package/workflow/fieldLabel.ts +61 -0
  232. package/workflow/fieldOrder.ts +117 -0
  233. package/workflow/fieldType.ts +2 -1
  234. package/workflow/guardCatalog.test.ts +1 -1
  235. package/workflow/keyRename.ts +1 -1
  236. package/workflow/moduleIndex.test.ts +2 -2
  237. package/workflow/moduleIndex.ts +2 -2
  238. package/workflow/modulePaths.ts +27 -0
  239. package/workflow/mutationScaffold.ts +7 -15
  240. package/workflow/mutationSource.ts +2 -1
  241. package/workflow/plan.ts +2 -1
  242. package/workflow/primitiveReport.ts +78 -0
  243. package/workflow/rolloutGate.test.ts +1 -1
  244. package/workflow/rolloutGate.ts +1 -1
  245. package/workflow/serviceSource.ts +33 -0
  246. package/workflow/signalSource.ts +96 -0
  247. package/workflow/source.ts +50 -1100
  248. package/workflow/sourceAst.ts +30 -0
  249. package/workflow/sourceImports.ts +105 -0
  250. package/workflow/sourceText.ts +13 -0
  251. package/workflow/templateSource.ts +30 -0
  252. package/workflow/testSource.ts +31 -0
  253. package/workflow/types.ts +1 -1
  254. package/workflow/uiPolicy.ts +1 -1
  255. package/{appSelectionMemory.ts → workspace/appSelectionMemory.ts} +1 -1
  256. package/{codegenLock.test.ts → workspace/codegenLock.test.ts} +1 -1
  257. package/{dependencyScanner.test.ts → workspace/dependencyScanner.test.ts} +1 -1
  258. package/{dependencyScanner.ts → workspace/dependencyScanner.ts} +2 -2
  259. package/{envSeed.test.ts → workspace/envSeed.test.ts} +2 -2
  260. package/{envSeed.ts → workspace/envSeed.ts} +1 -1
  261. package/{libSource.test.ts → workspace/libSource.test.ts} +2 -2
  262. package/{libSource.ts → workspace/libSource.ts} +1 -1
  263. package/{scanInfo.ts → workspace/scanInfo.ts} +21 -10
  264. package/{slicePlanner.test.ts → workspace/slicePlanner.test.ts} +2 -2
  265. package/{slicePlanner.ts → workspace/slicePlanner.ts} +1 -1
  266. package/{workspaceGraph.test.ts → workspace/workspaceGraph.test.ts} +1 -1
  267. package/{workspaceGraph.ts → workspace/workspaceGraph.ts} +1 -1
  268. package/{workspaceLayout.test.ts → workspace/workspaceLayout.test.ts} +1 -1
  269. package/{workspaceLayout.ts → workspace/workspaceLayout.ts} +3 -1
  270. package/akanContext.ts +0 -1083
  271. package/executors.ts +0 -1749
  272. /package/{applicationBuildReporter.test.ts → app/applicationBuildReporter.test.ts} +0 -0
  273. /package/{akanMcpToolError.ts → context/akanMcpToolError.ts} +0 -0
  274. /package/{moduleFieldNames.test.ts → context/moduleFieldNames.test.ts} +0 -0
  275. /package/{moduleFieldNames.ts → context/moduleFieldNames.ts} +0 -0
  276. /package/{recipeScanner.ts → context/recipeScanner.ts} +0 -0
  277. /package/{declarationReader.ts → docs/declarationReader.ts} +0 -0
  278. /package/{frameworkGraph.ts → docs/frameworkGraph.ts} +0 -0
  279. /package/{biomeBase.ts → lint/biomeBase.ts} +0 -0
  280. /package/{linter.ts → lint/linter.ts} +0 -0
  281. /package/{commentDensityScanner.test.ts → quality/commentDensityScanner.test.ts} +0 -0
  282. /package/{commentDensityScanner.ts → quality/commentDensityScanner.ts} +0 -0
  283. /package/{componentSizeScanner.test.ts → quality/componentSizeScanner.test.ts} +0 -0
  284. /package/{componentSizeScanner.ts → quality/componentSizeScanner.ts} +0 -0
  285. /package/{componentWriteChainScanner.test.ts → quality/componentWriteChainScanner.test.ts} +0 -0
  286. /package/{componentWriteChainScanner.ts → quality/componentWriteChainScanner.ts} +0 -0
  287. /package/{deprecatedCommentScanner.test.ts → quality/deprecatedCommentScanner.test.ts} +0 -0
  288. /package/{deprecatedCommentScanner.ts → quality/deprecatedCommentScanner.ts} +0 -0
  289. /package/{endpointReach.test.ts → quality/endpointReach.test.ts} +0 -0
  290. /package/{endpointReach.ts → quality/endpointReach.ts} +0 -0
  291. /package/{formSetterScanner.test.ts → quality/formSetterScanner.test.ts} +0 -0
  292. /package/{formSetterScanner.ts → quality/formSetterScanner.ts} +0 -0
  293. /package/{kindBranchScanner.test.ts → quality/kindBranchScanner.test.ts} +0 -0
  294. /package/{kindBranchScanner.ts → quality/kindBranchScanner.ts} +0 -0
  295. /package/{maintainabilityReport.test.ts → quality/maintainabilityReport.test.ts} +0 -0
  296. /package/{renderMutationScanner.test.ts → quality/renderMutationScanner.test.ts} +0 -0
  297. /package/{renderMutationScanner.ts → quality/renderMutationScanner.ts} +0 -0
  298. /package/{serviceLoopCallScanner.test.ts → quality/serviceLoopCallScanner.test.ts} +0 -0
  299. /package/{serviceLoopCallScanner.ts → quality/serviceLoopCallScanner.ts} +0 -0
  300. /package/{signalMutationIndex.test.ts → quality/signalMutationIndex.test.ts} +0 -0
  301. /package/{signalMutationIndex.ts → quality/signalMutationIndex.ts} +0 -0
  302. /package/{sourceComments.test.ts → quality/sourceComments.test.ts} +0 -0
  303. /package/{sourceComments.ts → quality/sourceComments.ts} +0 -0
  304. /package/{ssrScanner.test.ts → quality/ssrScanner.test.ts} +0 -0
  305. /package/{ssrScanner.ts → quality/ssrScanner.ts} +0 -0
  306. /package/{storeAccessScanner.test.ts → quality/storeAccessScanner.test.ts} +0 -0
  307. /package/{storeSource.ts → quality/storeSource.ts} +0 -0
  308. /package/{storeWriteScanner.test.ts → quality/storeWriteScanner.test.ts} +0 -0
  309. /package/{storeWriteScanner.ts → quality/storeWriteScanner.ts} +0 -0
  310. /package/{structureScanner.test.ts → quality/structureScanner.test.ts} +0 -0
  311. /package/{structureScanner.ts → quality/structureScanner.ts} +0 -0
  312. /package/{testOnlyExportScanner.test.ts → quality/testOnlyExportScanner.test.ts} +0 -0
  313. /package/{testOnlyExportScanner.ts → quality/testOnlyExportScanner.ts} +0 -0
  314. /package/{writePath.test.ts → quality/writePath.test.ts} +0 -0
  315. /package/{writePath.ts → quality/writePath.ts} +0 -0
  316. /package/{writePlacementScanner.test.ts → quality/writePlacementScanner.test.ts} +0 -0
  317. /package/{writePlacementScanner.ts → quality/writePlacementScanner.ts} +0 -0
  318. /package/{writingActionIndex.test.ts → quality/writingActionIndex.test.ts} +0 -0
  319. /package/{writingActionIndex.ts → quality/writingActionIndex.ts} +0 -0
  320. /package/{subspaceReport.ts → subspace/subspaceReport.ts} +0 -0
  321. /package/{sshTunnel.ts → tunnel/sshTunnel.ts} +0 -0
  322. /package/{fileEditor.ts → util/fileEditor.ts} +0 -0
  323. /package/{fileSys.test.ts → util/fileSys.test.ts} +0 -0
  324. /package/{fileSys.ts → util/fileSys.ts} +0 -0
  325. /package/{jsonFormatter.ts → util/jsonFormatter.ts} +0 -0
  326. /package/{selectModel.ts → util/selectModel.ts} +0 -0
  327. /package/{semver.test.ts → util/semver.test.ts} +0 -0
  328. /package/{semver.ts → util/semver.ts} +0 -0
  329. /package/{shellOnlyEnv.test.ts → util/shellOnlyEnv.test.ts} +0 -0
  330. /package/{shellOnlyEnv.ts → util/shellOnlyEnv.ts} +0 -0
  331. /package/{spinner.test.ts → util/spinner.test.ts} +0 -0
  332. /package/{spinner.ts → util/spinner.ts} +0 -0
  333. /package/{stripAnsi.ts → util/stripAnsi.ts} +0 -0
  334. /package/{codegenLock.ts → workspace/codegenLock.ts} +0 -0
  335. /package/{getRelatedCnsts.ts → workspace/getRelatedCnsts.ts} +0 -0
  336. /package/{gitRevision.test.ts → workspace/gitRevision.test.ts} +0 -0
  337. /package/{gitRevision.ts → workspace/gitRevision.ts} +0 -0
  338. /package/{manifestDependencies.ts → workspace/manifestDependencies.ts} +0 -0
  339. /package/{packageExportsMap.ts → workspace/packageExportsMap.ts} +0 -0
  340. /package/{repoIdentity.ts → workspace/repoIdentity.ts} +0 -0
  341. /package/{types.ts → workspace/types.ts} +0 -0
@@ -1,11 +1,13 @@
1
1
  import { existsSync } from "node:fs";
2
- import { readFile, rm, writeFile } from "node:fs/promises";
2
+ import { copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
3
4
  import path from "node:path";
4
5
  import ts from "typescript";
6
+ import { GitRevision } from "../workspace/gitRevision";
7
+ import { BareErrorScanner } from "./bareErrorScanner";
5
8
  import { ComponentSizeScanner } from "./componentSizeScanner";
6
9
  import { ComponentWriteChainScanner } from "./componentWriteChainScanner";
7
10
  import { EndpointReach } from "./endpointReach";
8
- import { GitRevision } from "./gitRevision";
9
11
  import { MaintainabilityBaseline } from "./maintainabilityBaseline";
10
12
  import { MaintainabilityLimits } from "./maintainabilityLimits";
11
13
  import { MaintainabilityReport } from "./maintainabilityReport";
@@ -97,6 +99,16 @@ export interface StoreAccessViolation {
97
99
  recorded?: number;
98
100
  }
99
101
 
102
+ export interface BareErrorViolation {
103
+ kind: "bareError";
104
+ rule: "akan.error.bare-error";
105
+ key: string;
106
+ file: string;
107
+ line: number;
108
+ lines: number[];
109
+ recorded?: number;
110
+ }
111
+
100
112
  export interface BaselineGrowth {
101
113
  kind: "baselineGrowth";
102
114
  rule: "akan.baseline.growth";
@@ -110,14 +122,25 @@ export interface BaselineGrowth {
110
122
  measured?: boolean;
111
123
  }
112
124
 
125
+ export interface StaleTotal {
126
+ kind: "staleTotal";
127
+ rule: DebtRuleId;
128
+ key: string;
129
+ file: string;
130
+ line: number;
131
+ count: number;
132
+ recorded: number;
133
+ }
134
+
113
135
  export type MaintainabilityViolation =
114
136
  | SizeViolation
115
137
  | ClassSizeViolation
116
138
  | MultiWriteViolation
117
139
  | StoreAccessViolation
118
140
  | WritePlacementViolation
119
- | LoopCallViolation;
120
- export type MaintainabilityFailure = MaintainabilityViolation | BaselineGrowth;
141
+ | LoopCallViolation
142
+ | BareErrorViolation;
143
+ export type MaintainabilityFailure = MaintainabilityViolation | BaselineGrowth | StaleTotal;
121
144
 
122
145
  export type BaselineSeed = "written" | "kept" | "removed" | "clean";
123
146
 
@@ -133,6 +156,7 @@ export class MaintainabilityContract {
133
156
  "akan.component.store-access",
134
157
  "akan.write.placement",
135
158
  "akan.service.call-in-loop",
159
+ "akan.error.bare-error",
136
160
  "akan.baseline.growth",
137
161
  ] as const;
138
162
  static readonly #measuredFiles = "{lib,ui,webkit,srvkit,common,plugin}/**/*.{ts,tsx,md}";
@@ -176,28 +200,41 @@ export class MaintainabilityContract {
176
200
  this.#readBaseline(),
177
201
  this.#readReferenceBaseline(),
178
202
  ]);
179
- const baseline =
203
+ const moves = await this.#movesSince(reference.ref);
204
+ const onDisk =
180
205
  existing === null ? new MaintainabilityBaseline() : MaintainabilityBaseline.parse(existing, this.baselinePath);
206
+ const baseline = fix ? onDisk.movedBy(moves) : onDisk;
181
207
  const tightened = baseline.tightenedBy(violations);
182
- if (fix && existing !== null) await this.#tighten(baseline, tightened);
183
- const failures: MaintainabilityFailure[] = violations
184
- .filter((violation) => !baseline.allows(violation))
185
- .map((violation) => {
186
- const recorded = baseline.recordedOf(violation);
187
- return recorded === undefined ? violation : { ...violation, recorded };
188
- });
208
+ if (fix && existing !== null) await this.#tighten(onDisk, tightened);
189
209
  //? Without fix the file on disk is what merges, so an entry it holds above the measured count is checked as written.
190
210
  const working = fix ? tightened : baseline;
191
- const source = `${reference.label}:${this.sysPath}/${MaintainabilityBaseline.fileName}`;
192
- const committed =
193
- reference.text !== null
194
- ? MaintainabilityBaseline.parse(reference.text, source, { lenient: true })
195
- : working.isEmpty
196
- ? null
197
- : await this.#measuredAt(reference.ref);
198
- if (committed === null) return failures;
199
211
  const lines = ((await this.#readBaseline()) ?? "").split(/\r?\n/);
200
- const growths = working
212
+ const failures: MaintainabilityFailure[] = [
213
+ ...working.staleTotals(violations).map(
214
+ ({ rule, count, recorded }): StaleTotal => ({
215
+ kind: "staleTotal",
216
+ rule,
217
+ key: MaintainabilityBaseline.totalKey,
218
+ file: MaintainabilityBaseline.fileName,
219
+ line: MaintainabilityContract.#lineOf(lines, rule, MaintainabilityBaseline.totalKey),
220
+ count,
221
+ recorded,
222
+ }),
223
+ ),
224
+ ...baseline.unallowed(violations).map((violation) => {
225
+ const recorded = baseline.recordedOf(violation);
226
+ return recorded === undefined ? violation : { ...violation, recorded };
227
+ }),
228
+ ];
229
+ const source = `${reference.label}:${this.sysPath}/${MaintainabilityBaseline.fileName}`;
230
+ const recorded =
231
+ reference.text !== null ? MaintainabilityBaseline.parse(reference.text, source, { lenient: true }) : null;
232
+ const unrecorded = new Set(working.rulesOutside(recorded));
233
+ const measured = unrecorded.size ? await this.#measuredAt(reference.ref) : null;
234
+ if (recorded === null && measured === null) return failures;
235
+ const committed = (recorded ?? new MaintainabilityBaseline()).withSectionsOf(measured, unrecorded).movedBy(moves);
236
+ //? Without fix the entries on disk keep their old keys, so they are compared under the moved ones the reference took.
237
+ const growths = (fix ? working : working.movedBy(moves))
201
238
  .grownFrom(committed)
202
239
  .map(
203
240
  ({ rule, ...growth }): BaselineGrowth => ({
@@ -207,7 +244,7 @@ export class MaintainabilityContract {
207
244
  line: MaintainabilityContract.#lineOf(lines, rule, growth.key),
208
245
  debtRule: rule,
209
246
  reference: reference.label,
210
- ...(reference.text === null ? { measured: true } : {}),
247
+ ...(unrecorded.has(rule) ? { measured: true } : {}),
211
248
  ...growth,
212
249
  }),
213
250
  )
@@ -234,17 +271,37 @@ export class MaintainabilityContract {
234
271
 
235
272
  async #measurePackage() {
236
273
  const files = (await this.#packageFiles()).filter(MaintainabilityLimits.isPackageSource);
274
+ const packageName = await this.#packageName();
237
275
  const violations = await Promise.all(
238
276
  files.map(async (file) => {
239
277
  const workspaceFile = `${this.sysPath}/${file}`;
240
278
  const content = await this.#read(workspaceFile);
241
- return MaintainabilityContract.#measurePackageFile(file, this.#sourceOf(workspaceFile, content).sourceFile);
279
+ return MaintainabilityContract.#measurePackageFile(
280
+ file,
281
+ this.#sourceOf(workspaceFile, content).sourceFile,
282
+ MaintainabilityLimits.holdsBareErrors(packageName, file),
283
+ );
242
284
  }),
243
285
  );
244
286
  return violations.flat();
245
287
  }
246
288
 
247
- static #measurePackageFile(file: string, sourceFile: ts.SourceFile) {
289
+ async #packageName() {
290
+ const manifest = `${this.sysPath}/package.json`;
291
+ const text = this.#tree
292
+ ? this.#tree.get(manifest)
293
+ : existsSync(path.join(this.#workspaceRoot, manifest))
294
+ ? await this.#read(manifest)
295
+ : undefined;
296
+ try {
297
+ const { name } = JSON.parse(text ?? "{}") as { name?: unknown };
298
+ return typeof name === "string" ? name : null;
299
+ } catch {
300
+ return null;
301
+ }
302
+ }
303
+
304
+ static #measurePackageFile(file: string, sourceFile: ts.SourceFile, holdsBareErrors: boolean) {
248
305
  const violations: MaintainabilityViolation[] = [];
249
306
  const maxLines = MaintainabilityLimits.packageFileMaxLines;
250
307
  const lineCount = MaintainabilityLimits.lineCountOf(sourceFile.text);
@@ -275,6 +332,16 @@ export class MaintainabilityContract {
275
332
  memberCount,
276
333
  maxMembers: MaintainabilityLimits.classMaxMembers,
277
334
  });
335
+ const bareErrors = holdsBareErrors ? new BareErrorScanner().lines(sourceFile) : [];
336
+ if (bareErrors.length)
337
+ violations.push({
338
+ kind: "bareError",
339
+ rule: "akan.error.bare-error",
340
+ key: file,
341
+ file,
342
+ line: bareErrors[0] ?? 1,
343
+ lines: bareErrors,
344
+ });
278
345
  return violations;
279
346
  }
280
347
 
@@ -426,15 +493,16 @@ export class MaintainabilityContract {
426
493
  return { ref, label: ref === "HEAD" ? ref : ref.slice(0, 12), text };
427
494
  }
428
495
 
429
- //* With no baseline file at the reference, the debt its code already holds is the floor: none for a scope new to the
430
- //* branch or one whose paid-off file was removed, and the breaches it had for a scope that adopts the gate here.
496
+ //* With no baseline file at the reference, or no section there for a rule, the debt its code already holds is the
497
+ //* floor: none for a scope new to the branch or one whose paid-off file was removed, and the breaches it had for a
498
+ //* scope that adopts the gate here or a rule this version adds.
431
499
  async #measuredAt(ref: string) {
432
500
  if ((await this.#git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])) === null) return null;
433
501
  const roots = [this.sysPath, ...this.#libNames.map((libName) => `libs/${libName}`)];
434
502
  const contract = new MaintainabilityContract(this.#workspaceRoot, this.#scope, this.#libNames);
435
503
  contract.#tree = await new GitRevision(this.#workspaceRoot).filesAt(
436
504
  ref,
437
- (file) => /\.(tsx?|md)$/.test(file),
505
+ (file) => /\.(tsx?|md)$/.test(file) || file === `${this.sysPath}/package.json`,
438
506
  roots,
439
507
  );
440
508
  return MaintainabilityBaseline.of(await contract.measure());
@@ -455,6 +523,53 @@ export class MaintainabilityContract {
455
523
  return "HEAD";
456
524
  }
457
525
 
526
+ //? A move that also rewrote more than half the file, or left a file at the old path, reads as an add and fails as new.
527
+ async #movesSince(ref: string) {
528
+ const staged = await this.#stagedScope();
529
+ try {
530
+ const diff = ["diff", ...(staged ? ["--cached"] : []), "--relative", "--name-status", "-z", "-M", ref];
531
+ const fields = (await this.#git([...diff, "--", this.sysPath], staged?.env))?.split("\0") ?? [];
532
+ const prefix = `${this.sysPath}/`;
533
+ const moves = new Map<string, string>();
534
+ for (let idx = 0; idx < fields.length; idx += fields[idx]?.startsWith("R") ? 3 : 2) {
535
+ const [from, to] = [fields[idx + 1], fields[idx + 2]];
536
+ if (!fields[idx]?.startsWith("R") || !from?.startsWith(prefix) || !to?.startsWith(prefix)) continue;
537
+ moves.set(from.slice(prefix.length), to.slice(prefix.length));
538
+ }
539
+ return moves;
540
+ } finally {
541
+ if (staged) await rm(staged.dir, { recursive: true, force: true });
542
+ }
543
+ }
544
+
545
+ //? Git pairs moves only between staged paths, so a plain rename is staged too, in a copy of the user's index.
546
+ async #stagedScope() {
547
+ const indexPath = (await this.#git(["rev-parse", "--git-path", "index"]))?.trim();
548
+ //? Only sources: staging writes each file into .git/objects, where a local database or a log would pile up.
549
+ const untracked = (await this.#git(["ls-files", "-o", "--exclude-standard", "-z", "--", this.sysPath]))
550
+ ?.split("\0")
551
+ .filter((file) => /\.(tsx?|md)$/.test(file));
552
+ if (!indexPath || !untracked) return null;
553
+ const dir = await mkdtemp(path.join(tmpdir(), "akan-moves-")).catch(() => null);
554
+ if (!dir) return null;
555
+ const env = { GIT_INDEX_FILE: path.join(dir, "index") };
556
+ const listPath = path.join(dir, "untracked");
557
+ try {
558
+ const indexFile = path.resolve(this.#workspaceRoot, indexPath);
559
+ if (existsSync(indexFile)) await copyFile(indexFile, env.GIT_INDEX_FILE);
560
+ await writeFile(listPath, untracked.join("\0"));
561
+ const added =
562
+ (await this.#git(["add", "-u", "--", this.sysPath], env)) !== null &&
563
+ (!untracked.length ||
564
+ (await this.#git(["add", "--pathspec-from-file", listPath, "--pathspec-file-nul"], env)) !== null);
565
+ if (added) return { dir, env };
566
+ } catch {
567
+ //? A full or read-only temp dir: fall back to the moves the user's own index holds.
568
+ }
569
+ await rm(dir, { recursive: true, force: true });
570
+ return null;
571
+ }
572
+
458
573
  static #missingHistory(sysPath: string, cause: string) {
459
574
  return (
460
575
  `${sysPath}/${MaintainabilityBaseline.fileName} is compared with its copy where this branch forked from the default branch, ` +
@@ -462,9 +577,15 @@ export class MaintainabilityContract {
462
577
  );
463
578
  }
464
579
 
465
- async #git(args: string[]) {
580
+ //? GIT_OPTIONAL_LOCKS=0 keeps a read from refreshing the index under the user's own git, which would then fail on index.lock.
581
+ async #git(args: string[], env: Record<string, string> = {}) {
466
582
  try {
467
- const proc = Bun.spawn(["git", ...args], { cwd: this.#workspaceRoot, stdout: "pipe", stderr: "ignore" });
583
+ const proc = Bun.spawn(["git", ...args], {
584
+ cwd: this.#workspaceRoot,
585
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", ...env },
586
+ stdout: "pipe",
587
+ stderr: "ignore",
588
+ });
468
589
  const [text, exitCode] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
469
590
  return exitCode === 0 ? text : null;
470
591
  } catch {
@@ -492,6 +613,7 @@ export class MaintainabilityContract {
492
613
  lines.findIndex((line) => line.includes(`${JSON.stringify(rule)}:`)),
493
614
  0,
494
615
  );
616
+ if (key === MaintainabilityBaseline.totalKey) return from + 1;
495
617
  const idx = lines.findIndex((line, lineIdx) => lineIdx >= from && line.includes(`${JSON.stringify(key)}:`));
496
618
  return Math.max(idx + 1, 1);
497
619
  }
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import path from "node:path";
3
+ import { tempDirs, writeText } from "../test/testHelpers";
3
4
  import { MaintainabilityExceptionScanner } from "./maintainabilityExceptionScanner";
4
- import { tempDirs, writeText } from "./testHelpers";
5
5
 
6
6
  const makeTempRoot = tempDirs("akan-maintainability-exceptions-");
7
7
 
@@ -98,4 +98,18 @@ describe("MaintainabilityExceptionScanner", () => {
98
98
  expect(byRule("apps/demo/akan.baseline.json", "akan.size.component")?.fix).toContain("threshold is wrong");
99
99
  expect(byRule("apps/demo/akan.baseline.json", "akan.store.multi-write")?.fix).toContain("add-mutation");
100
100
  });
101
+
102
+ test("tells a bare Error entry to construct a coded error, since the rule takes no exception", async () => {
103
+ const root = await makeWorkspace({
104
+ "pkgs/akanjs/akan.baseline.json": baselineOf({ "akan.error.bare-error": { "server/host.ts": 2 } }),
105
+ });
106
+
107
+ expect(await new MaintainabilityExceptionScanner().scan(root)).toMatchObject([
108
+ {
109
+ message:
110
+ "pkgs/akanjs carries 0 reasoned exceptions and 1 adopted-debt entry for akan.error.bare-error: server/host.ts.",
111
+ fix: expect.stringContaining("construct an `AkanError` subclass"),
112
+ },
113
+ ]);
114
+ });
101
115
  });
@@ -11,6 +11,8 @@ export class MaintainabilityExceptionScanner {
11
11
  "Many reasoned exceptions under one rule mean its threshold is wrong: fix the limit in MaintainabilityLimits rather than record another. Otherwise shrink the code, and `akan lint` lowers each entry and drops it once it passes.";
12
12
  static readonly #correctnessFix =
13
13
  "A write rule takes no exception: send the writes through one store action and one endpoint (`akan workflow plan add-mutation`), and `akan lint` drops the entry.";
14
+ static readonly #bareErrorFix =
15
+ "A bare Error takes no exception: construct an `AkanError` subclass with a code, and `akan lint` lowers the entries as they go.";
14
16
 
15
17
  async scan(workspaceRoot: string): Promise<QualityWarning[]> {
16
18
  const sysPaths = await Promise.all(
@@ -81,7 +83,9 @@ export class MaintainabilityExceptionScanner {
81
83
  locations,
82
84
  fix: MaintainabilityBaseline.reasonedRules.has(rule)
83
85
  ? MaintainabilityExceptionScanner.#shapeFix
84
- : MaintainabilityExceptionScanner.#correctnessFix,
86
+ : rule === "akan.error.bare-error"
87
+ ? MaintainabilityExceptionScanner.#bareErrorFix
88
+ : MaintainabilityExceptionScanner.#correctnessFix,
85
89
  };
86
90
  }
87
91
 
@@ -25,6 +25,18 @@ export class MaintainabilityLimits {
25
25
  static readonly packageFileMaxLines = 800;
26
26
  static readonly functionMaxLines = 150;
27
27
  static readonly classMaxMembers = 60;
28
+ //? The request-path facets: a failure there reaches a caller, who branches on its code rather than its message.
29
+ static readonly bareErrorRoots: ReadonlyMap<string, readonly string[]> = new Map([
30
+ ["akanjs", ["server/", "service/", "signal/"]],
31
+ ]);
32
+
33
+ //? Rules this repository holds its own framework to: no workspace has a package they measure, so none is told of them.
34
+ static readonly repoOnlyRules: ReadonlySet<string> = new Set(["akan.error.bare-error"]);
35
+
36
+ static holdsBareErrors(pkgName: string | null, pkgRelativePath: string) {
37
+ const roots = pkgName === null ? undefined : MaintainabilityLimits.bareErrorRoots.get(pkgName);
38
+ return (roots ?? []).some((root) => pkgRelativePath.startsWith(root));
39
+ }
28
40
 
29
41
  static fileKindOf(sysRelativePath: string): FileKind | null {
30
42
  const kinds = Object.keys(MaintainabilityLimits.#maxLinesByKind) as FileKind[];
@@ -1,4 +1,5 @@
1
1
  import { AbstractDoc } from "./abstractDoc";
2
+ import { MaintainabilityBaseline } from "./maintainabilityBaseline";
2
3
  import type {
3
4
  DebtRuleId,
4
5
  MaintainabilityCommands,
@@ -7,7 +8,7 @@ import type {
7
8
  } from "./maintainabilityContract";
8
9
  import { type FileKind, MaintainabilityLimits } from "./maintainabilityLimits";
9
10
 
10
- type FixKey = FileKind | "package" | Exclude<MaintainabilityRuleId, "akan.size.file">;
11
+ type FixKey = FileKind | "package" | "staleTotal" | Exclude<MaintainabilityRuleId, "akan.size.file">;
11
12
 
12
13
  export class MaintainabilityReport {
13
14
  static readonly #clientSplitFix =
@@ -48,8 +49,12 @@ export class MaintainabilityReport {
48
49
  "A server write leaves the browser through one store action, started by one module component. Move a `fetch.<mutation>` into a store action, and hand `ui/` and `webkit/` code the write as an `onX` prop or hook argument from the module's `Zone` or `Util`: they stay free of any one model, and an agent or another screen reaches the write through the store.",
49
50
  "akan.service.call-in-loop":
50
51
  "Load the set once (`load<Model>Many(ids)`, one filter query) or write it once (`create<Model>Many(rows)`, one batch method), then loop in memory: a call per item is a round trip per item, so the endpoint slows as its input grows.",
52
+ "akan.error.bare-error":
53
+ "Construct an `AkanError` subclass from `akanjs/base` with a code the caller can branch on, and a `statusCode` when it answers a request: an existing class whose code fits, or a new one beside the code that fails; a class extending a built-in Error extends `AkanError` instead. A failure another process reported travels as itself. The package's total is what is held, so moving a bare Error between files passes and `akan lint` rewrites the entries.",
51
54
  "akan.baseline.growth":
52
55
  "Restore the entry from the default branch, then split the file or move the writes instead: `akan lint` lowers an entry as the code shrinks and never raises one.",
56
+ staleTotal:
57
+ "Run `akan verify <package>`, which lowers the section, and commit `akan.baseline.json` in this change: a recorded total above the code is room for a new failure anywhere. A bare `akan verify` covers only uncommitted files.",
53
58
  };
54
59
 
55
60
  static readonly #labels: { [key in FixKey]?: string } = {
@@ -65,7 +70,9 @@ export class MaintainabilityReport {
65
70
  "akan.component.store-access": "component or hook reaching the store often",
66
71
  "akan.write.placement": "write sent outside a store action or module component",
67
72
  "akan.service.call-in-loop": "service call per item",
73
+ "akan.error.bare-error": "bare Error",
68
74
  "akan.baseline.growth": "baseline entry",
75
+ staleTotal: "baseline total",
69
76
  };
70
77
 
71
78
  static readonly #units: { [rule in DebtRuleId]: string } = {
@@ -79,6 +86,7 @@ export class MaintainabilityReport {
79
86
  "akan.component.write-chain": "writes",
80
87
  "akan.write.placement": "writes",
81
88
  "akan.service.call-in-loop": "calls per item",
89
+ "akan.error.bare-error": "bare Errors",
82
90
  };
83
91
 
84
92
  static describe(sysPath: string, failures: MaintainabilityFailure[], commands: MaintainabilityCommands = {}) {
@@ -118,13 +126,17 @@ export class MaintainabilityReport {
118
126
  }
119
127
 
120
128
  static #problemOf(failure: MaintainabilityFailure) {
129
+ if (failure.kind === "staleTotal")
130
+ return `records ${failure.recorded} ${MaintainabilityReport.#units[failure.rule]} in all, above the ${failure.count} the code holds`;
121
131
  if (failure.kind === "baselineGrowth") {
122
132
  const entry = `entry "${failure.key}" under ${failure.debtRule}`;
123
133
  const units = MaintainabilityReport.#units[failure.debtRule];
134
+ if (failure.key === MaintainabilityBaseline.totalKey)
135
+ return `${failure.debtRule} allows ${failure.count} ${units} in all, above the ${failure.committed ?? 0} ${failure.measured ? `the code at ${failure.reference} holds with no entry for its rule recorded there` : `at ${failure.reference}`}; the baseline may only shrink`;
124
136
  if (failure.measured)
125
137
  return failure.committed === undefined
126
- ? `${entry} is debt the code at ${failure.reference} does not hold, and with no baseline there the baseline may only shrink from that code`
127
- : `${entry} allows ${failure.count} ${units}, above the ${failure.committed} the code at ${failure.reference} holds with no baseline there; the baseline may only shrink`;
138
+ ? `${entry} is debt the code at ${failure.reference} does not hold, and with no entry for its rule recorded there the baseline may only shrink from that code`
139
+ : `${entry} allows ${failure.count} ${units}, above the ${failure.committed} the code at ${failure.reference} holds with no entry for its rule recorded there; the baseline may only shrink`;
128
140
  return failure.committed === undefined
129
141
  ? `${entry} is not in the baseline at ${failure.reference}, which may only shrink`
130
142
  : `${entry} allows ${failure.count} ${units}, above the ${failure.committed} at ${failure.reference}; the baseline may only shrink`;
@@ -143,6 +155,10 @@ export class MaintainabilityReport {
143
155
  }
144
156
  if (failure.kind === "writePlacement")
145
157
  return `sends ${failure.writes.length} server write(s) from outside a store action or a module component: ${failure.writes.join(", ")}${grown}`;
158
+ if (failure.kind === "bareError") {
159
+ const plural = failure.lines.length === 1 ? "" : "s";
160
+ return `constructs or extends ${failure.lines.length} bare Error${plural}, on line${plural} ${failure.lines.join(", ")}${grown}, and the package's total grew`;
161
+ }
146
162
  if (failure.kind === "loopCall")
147
163
  return `service method ${failure.owner} calls once per item: ${failure.calls.join(", ")}${grown}`;
148
164
  if (failure.kind === "classSize")
@@ -163,6 +179,7 @@ export class MaintainabilityReport {
163
179
  }
164
180
 
165
181
  static #fixKeyOf(sysPath: string, failure: MaintainabilityFailure): FixKey {
182
+ if (failure.kind === "staleTotal") return "staleTotal";
166
183
  if (failure.rule !== "akan.size.file") return failure.rule;
167
184
  if (sysPath.startsWith("pkgs/")) return "package";
168
185
  return MaintainabilityLimits.fileKindOf(failure.file) ?? "akan.size.component";
@@ -1,8 +1,9 @@
1
1
  import { describe, expect, test } from "bun:test";
2
+ import { chmod } from "node:fs/promises";
2
3
  import path from "node:path";
4
+ import { tempDirs, writeText } from "../test/testHelpers";
3
5
  import { AbstractDoc } from "./abstractDoc";
4
6
  import { AkanQualityScanner, type QualityScanResult } from "./qualityScanner";
5
- import { tempDirs, writeText } from "./testHelpers";
6
7
 
7
8
  const makeTempRoot = tempDirs("akan-quality-scanner-");
8
9
 
@@ -174,6 +175,45 @@ describe("AkanQualityScanner ssr rules", () => {
174
175
  expect(ssrBalance[1]).toMatchObject({ serverMass: 0, clientMass: 1 });
175
176
  expect(ssrBalance[2]).toMatchObject({ scope: "workspace", serverMass: 3, clientMass: 1 });
176
177
  });
178
+
179
+ test("an SSR scan of some folders reads only them and the libs' signals, and warns there as the full scan does", async () => {
180
+ const root = await makeWorkspace({
181
+ "libs/shared/lib/item/item.signal.ts": [
182
+ "export class ItemEndpoint extends endpoint(srv.item, ({ mutation }) => ({",
183
+ ' approveItem: mutation(cnst.Item, { guards: [User] }).param("itemId", ID).exec(async function (itemId) {',
184
+ " return await this.itemService.approve(itemId);",
185
+ " }),",
186
+ "})) {}",
187
+ "",
188
+ ].join("\n"),
189
+ "apps/demo/page/item/[itemId].tsx": [
190
+ 'import { fetch } from "@apps/demo/client";',
191
+ 'import { ID } from "akanjs/base";',
192
+ 'import { page } from "akanjs/client";',
193
+ "",
194
+ 'export default page().param("itemId", ID).render(async ({ itemId }) => {',
195
+ " await fetch.approveItem(itemId);",
196
+ " return <p>{itemId}</p>;",
197
+ "});",
198
+ "",
199
+ ].join("\n"),
200
+ "apps/demo/ui/Plain.tsx": `"use client";\nexport const Plain = () => <div>plain</div>;\n`,
201
+ "apps/other/ui/Plain.tsx": `"use client";\nexport const Plain = () => <div>plain</div>;\n`,
202
+ });
203
+ const scanner = new AkanQualityScanner();
204
+ const full = (await scanner.scan(root)).warnings.filter(
205
+ (warning) => warning.scope === "ssr" && warning.file?.startsWith("apps/demo/"),
206
+ );
207
+ await chmod(path.join(root, "apps/other/ui/Plain.tsx"), 0);
208
+
209
+ const scoped = await scanner.scanSsr(root, ["apps/demo"]);
210
+
211
+ expect(scoped.map(({ rule, file }) => [rule, file])).toEqual([
212
+ ["akan.ssr.render-mutation", "apps/demo/page/item/[itemId].tsx"],
213
+ ["akan.ssr.unnecessary-use-client", "apps/demo/ui/Plain.tsx"],
214
+ ]);
215
+ expect(scoped).toEqual(full);
216
+ });
177
217
  });
178
218
 
179
219
  describe("AkanQualityScanner layout rules", () => {
@@ -1,9 +1,16 @@
1
1
  import { createHash } from "node:crypto";
2
- import { readdir, readFile, stat } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { RESERVED_ROUTE_CONFIG_EXPORTS } from "akanjs/common";
5
- import ignore from "ignore";
6
5
  import ts from "typescript";
6
+ import {
7
+ facetIndexShadowOf,
8
+ isAllowedLibFacetRootFile,
9
+ libFacetRootHintOf,
10
+ rootAllowedDirs,
11
+ rootAllowedFiles,
12
+ rootEntryHintOf,
13
+ } from "../workspace/workspaceLayout";
7
14
  import { AbstractDoc } from "./abstractDoc";
8
15
  import { CommentDensityScanner } from "./commentDensityScanner";
9
16
  import { DeprecatedCommentScanner } from "./deprecatedCommentScanner";
@@ -12,14 +19,7 @@ import { KindBranchScanner } from "./kindBranchScanner";
12
19
  import { MaintainabilityExceptionScanner } from "./maintainabilityExceptionScanner";
13
20
  import { fileWarning, formatSsrBalance, type SsrBalanceEntry, SsrScanner } from "./ssrScanner";
14
21
  import { TestOnlyExportScanner } from "./testOnlyExportScanner";
15
- import {
16
- facetIndexShadowOf,
17
- isAllowedLibFacetRootFile,
18
- libFacetRootHintOf,
19
- rootAllowedDirs,
20
- rootAllowedFiles,
21
- rootEntryHintOf,
22
- } from "./workspaceLayout";
22
+ import { WorkspaceSourceFiles } from "./workspaceSourceFiles";
23
23
 
24
24
  type QualitySeverity = "warning";
25
25
  type QualityScope = "global" | "file" | "convention" | "layout" | "ssr" | "agent" | "comment";
@@ -184,11 +184,10 @@ function getRuleFix(rule: string): string | undefined {
184
184
 
185
185
  export class AkanQualityScanner {
186
186
  async scan(workspaceRoot: string): Promise<QualityScanResult> {
187
- const targetFiles = await this.#collectTargetFiles(workspaceRoot);
187
+ const workspaceFiles = new WorkspaceSourceFiles(workspaceRoot);
188
+ const targetFiles = await workspaceFiles.collect();
188
189
  const sourceFiles = await Promise.all(
189
- targetFiles
190
- .filter((file) => !AbstractDoc.isAbstractPath(file))
191
- .map((file) => this.#readSourceFile(workspaceRoot, file)),
190
+ targetFiles.filter((file) => !AbstractDoc.isAbstractPath(file)).map((file) => workspaceFiles.read(file)),
192
191
  );
193
192
  const abstractFiles = await Promise.all(
194
193
  targetFiles
@@ -221,56 +220,18 @@ export class AkanQualityScanner {
221
220
  };
222
221
  }
223
222
 
224
- async #collectTargetFiles(workspaceRoot: string) {
225
- const ignoreFilter = ignore().add(await this.#readGitIgnore(workspaceRoot));
226
- const files: string[] = [];
227
- for (const targetRoot of ["apps", "libs"]) {
228
- const absoluteTargetRoot = path.join(workspaceRoot, targetRoot);
229
- if (!(await isDirectory(absoluteTargetRoot))) continue;
230
- await this.#walkTargetFiles(workspaceRoot, absoluteTargetRoot, ignoreFilter, files);
231
- }
232
- return files.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
233
- }
234
-
235
- async #readGitIgnore(workspaceRoot: string) {
236
- const gitIgnorePath = path.join(workspaceRoot, ".gitignore");
237
- if (!(await Bun.file(gitIgnorePath).exists())) return [];
238
- return (await readFile(gitIgnorePath, "utf8")).split(/\r?\n/);
239
- }
240
-
241
- async #walkTargetFiles(
242
- workspaceRoot: string,
243
- currentPath: string,
244
- ignoreFilter: ReturnType<typeof ignore>,
245
- files: string[],
246
- ) {
247
- const entries = await readdir(currentPath, { withFileTypes: true });
248
- for (const entry of entries) {
249
- const absolutePath = path.join(currentPath, entry.name);
250
- const relativePath = toPosix(path.relative(workspaceRoot, absolutePath));
251
- if (shouldSkipPath(relativePath, entry.isDirectory(), ignoreFilter)) continue;
252
-
253
- if (entry.isDirectory()) {
254
- await this.#walkTargetFiles(workspaceRoot, absolutePath, ignoreFilter, files);
255
- continue;
256
- }
257
- if ((relativePath.endsWith(".ts") || relativePath.endsWith(".tsx")) && !relativePath.endsWith(".d.ts")) {
258
- files.push(relativePath);
259
- } else if (AbstractDoc.isAbstractPath(relativePath)) {
260
- files.push(relativePath);
261
- }
262
- }
263
- }
264
-
265
- async #readSourceFile(workspaceRoot: string, file: string): Promise<SourceFileInfo> {
266
- const absolutePath = path.join(workspaceRoot, file);
267
- const content = await readFile(absolutePath, "utf8");
268
- return {
269
- file,
270
- absolutePath,
271
- content,
272
- sourceFile: ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, getScriptKind(file)),
273
- };
223
+ //? An SSR rule reads the file, its module folder and the signals its fetch calls name, which sit in its own app or
224
+ //? lib or under libs/, so no other file can change a warning on a file under `dirs`.
225
+ async scanSsr(workspaceRoot: string, dirs: string[]): Promise<QualityWarning[]> {
226
+ const workspaceFiles = new WorkspaceSourceFiles(workspaceRoot);
227
+ const read = (file: string) =>
228
+ !AbstractDoc.isAbstractPath(file) &&
229
+ (dirs.some((dir) => file.startsWith(`${dir}/`)) || /^libs\/[^/]+\/lib\/.+\.signal\.ts$/.test(file));
230
+ const files = (await workspaceFiles.collect([...dirs, "libs"])).filter(read);
231
+ const { warnings } = new SsrScanner().scan(await Promise.all(files.map((file) => workspaceFiles.read(file))));
232
+ return warnings
233
+ .map((warning) => ({ ...warning, fix: warning.fix ?? getRuleFix(warning.rule) }))
234
+ .sort(compareWarnings);
274
235
  }
275
236
 
276
237
  async #readTextFile(workspaceRoot: string, file: string): Promise<TextFileInfo> {
@@ -918,29 +879,6 @@ function getBodyFingerprint(sourceFile: ts.SourceFile, node: ts.Node | undefined
918
879
  return createHash("sha256").update(normalizedBody).digest("hex");
919
880
  }
920
881
 
921
- function shouldSkipPath(relativePath: string, isDirectory: boolean, ignoreFilter: ReturnType<typeof ignore>) {
922
- const ignorePath = isDirectory ? `${relativePath}/` : relativePath;
923
- return (
924
- relativePath === ".git" ||
925
- relativePath.includes("/.git/") ||
926
- relativePath.includes("/node_modules/") ||
927
- ignoreFilter.ignores(relativePath) ||
928
- ignoreFilter.ignores(ignorePath)
929
- );
930
- }
931
-
932
- async function isDirectory(absolutePath: string) {
933
- try {
934
- return (await stat(absolutePath)).isDirectory();
935
- } catch {
936
- return false;
937
- }
938
- }
939
-
940
- function getScriptKind(file: string) {
941
- return file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
942
- }
943
-
944
882
  function getLine(sourceFile: ts.SourceFile, node: ts.Node) {
945
883
  return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
946
884
  }
@@ -960,10 +898,6 @@ function toPascalCase(value: string) {
960
898
  return value.replace(/(^|[-_./])([a-zA-Z0-9])/g, (_, __, char: string) => char.toUpperCase()).replace(/[-_./]/g, "");
961
899
  }
962
900
 
963
- function toPosix(value: string) {
964
- return value.split(path.sep).join("/");
965
- }
966
-
967
901
  function groupBy<T>(items: T[], getKey: (item: T) => string) {
968
902
  const grouped = new Map<string, T[]>();
969
903
  for (const item of items) {