@akanjs/devkit 3.2.0-rc.3 → 3.2.0-rc.31

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 (365) hide show
  1. package/CHANGELOG.md +369 -11
  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 +257 -1
  7. package/akanApp/akanApp.host.ts +146 -1223
  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/devHostPolicy.test.ts +11 -11
  17. package/akanApp/devHostPolicy.ts +2 -4
  18. package/akanApp/devIdleSuspend.test.ts +221 -0
  19. package/akanApp/devIdleSuspend.ts +192 -0
  20. package/akanApp/devIdleSuspend.watcher.test.ts +120 -0
  21. package/akanApp/devRecycler.test.ts +66 -0
  22. package/akanApp/devRecycler.ts +305 -0
  23. package/akanApp/processRss.ts +61 -0
  24. package/akanConfig/akanConfig.test.ts +24 -1
  25. package/akanConfig/akanConfig.ts +10 -10
  26. package/akanConfig/akanWorkspaceConfig.ts +1 -1
  27. package/akanConfig/productionLockfile.ts +1 -1
  28. package/apiReport/apiDeclarationPrinter.ts +120 -0
  29. package/apiReport/apiReport.test.ts +526 -0
  30. package/apiReport/apiReport.ts +232 -0
  31. package/apiReport/apiReportDiff.ts +160 -0
  32. package/apiReport/apiReportPolicy.ts +65 -0
  33. package/apiReport/apiTargets.ts +311 -0
  34. package/apiReport/changesetBump.ts +19 -0
  35. package/{applicationBuildReporter.test.ts → app/applicationBuildReporter.test.ts} +21 -0
  36. package/{applicationBuildReporter.ts → app/applicationBuildReporter.ts} +10 -49
  37. package/{applicationBuildRunner.test.ts → app/applicationBuildRunner.test.ts} +74 -7
  38. package/{applicationBuildRunner.ts → app/applicationBuildRunner.ts} +20 -15
  39. package/{applicationTestPreload.ts → app/applicationTestPreload.ts} +1 -1
  40. package/{routeJsBudget.test.ts → app/routeJsBudget.test.ts} +48 -12
  41. package/{routeJsBudget.ts → app/routeJsBudget.ts} +90 -27
  42. package/{routeSourceValidator.test.ts → app/routeSourceValidator.test.ts} +17 -0
  43. package/{routeSourceValidator.ts → app/routeSourceValidator.ts} +5 -1
  44. package/artifact/implicitRootLayout.test.ts +71 -3
  45. package/artifact/implicitRootLayout.ts +21 -4
  46. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  47. package/biome.base.json +2 -1
  48. package/cloud/cloudApi.test.ts +1 -1
  49. package/cloud/configLock.test.ts +1 -1
  50. package/cloud/globalConfig.test.ts +1 -1
  51. package/cloud/globalConfig.ts +1 -1
  52. package/cloud/updatePackUpload.test.ts +1 -1
  53. package/codeAgent/agent/AkanCodeEnv.ts +1 -1
  54. package/codeAgent/agent/akanCodePaths.ts +1 -1
  55. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  56. package/codeAgent/agent/codeAgent.test.ts +1 -1
  57. package/codeAgent/skills/akan-debug/SKILL.md +10 -3
  58. package/codeAgent/skills/akan-err/SKILL.md +7 -0
  59. package/codeAgent/skills/akan-mcp/SKILL.md +17 -2
  60. package/codeAgent/skills/akan-scaffold/SKILL.md +2 -2
  61. package/codeAgent/skills/akan-transport/SKILL.md +2 -0
  62. package/codeAgent/skills/akan-validate/SKILL.md +1 -0
  63. package/codeAgent/tools/AkanCli.ts +1 -1
  64. package/codeAgent/tools/AkanToolPack.ts +1 -1
  65. package/codeAgent/tools/McpClient.ts +28 -6
  66. package/codeAgent/tools/McpToolPack.ts +1 -1
  67. package/codeAgent/tools/akanCodePlugins.test.ts +14 -2
  68. package/commandDecorators/argMeta.ts +4 -0
  69. package/commandDecorators/cliError.ts +72 -0
  70. package/commandDecorators/command.ts +165 -91
  71. package/commandDecorators/commandBuilder.ts +1 -1
  72. package/commandDecorators/commandDecorators.test.ts +191 -16
  73. package/commandDecorators/exitCodeError.ts +6 -7
  74. package/commandDecorators/index.ts +1 -0
  75. package/commandDecorators/targetMeta.ts +1 -0
  76. package/commandDecorators/workspaceVersionCheck.test.ts +1 -1
  77. package/commandDecorators/workspaceVersionCheck.ts +1 -1
  78. package/context/akanContext.ts +576 -0
  79. package/context/akanContextInspection.ts +296 -0
  80. package/{akanMcpContract.test.ts → context/akanMcpContract.test.ts} +1 -1
  81. package/{akanMcpContract.ts → context/akanMcpContract.ts} +32 -262
  82. package/context/akanMcpToolError.ts +16 -0
  83. package/context/doctor/agentGuideCheck.ts +81 -0
  84. package/context/doctor/configLeftoverCheck.ts +35 -0
  85. package/context/doctor/doctorFindings.ts +70 -0
  86. package/context/doctor/generatedFreshness.ts +56 -0
  87. package/context/doctor/moduleShapeCheck.ts +88 -0
  88. package/context/doctor/recipeDuplicateCheck.ts +39 -0
  89. package/context/doctor/recipeIndexCheck.ts +87 -0
  90. package/context/doctor/rootShapeCheck.ts +55 -0
  91. package/context/doctor/workflowScope.ts +97 -0
  92. package/{constantFieldNames.test.ts → context/moduleFieldNames.test.ts} +24 -2
  93. package/context/moduleFieldNames.ts +25 -0
  94. package/{recipeScanner.test.ts → context/recipeScanner.test.ts} +1 -1
  95. package/context/safeRead.ts +9 -0
  96. package/csrE2e/csrE2eHarness.fixture.ts +1 -1
  97. package/devkitUtils.test.ts +39 -5
  98. package/{apiReference.test.ts → docs/apiReference.test.ts} +4 -4
  99. package/{apiReference.ts → docs/apiReference.ts} +2 -2
  100. package/docs/errorCodeReference.test.ts +282 -0
  101. package/docs/errorCodeReference.ts +71 -0
  102. package/docs/errorCodeScan.ts +551 -0
  103. package/{frameworkGraph.test.ts → docs/frameworkGraph.test.ts} +1 -1
  104. package/executors/appExecutor.ts +448 -0
  105. package/executors/commandExecutionError.ts +53 -0
  106. package/executors/executor.ts +527 -0
  107. package/{executors.linkFallback.test.ts → executors/executors.linkFallback.test.ts} +1 -1
  108. package/{executors.test.ts → executors/executors.test.ts} +76 -15
  109. package/executors/index.ts +8 -0
  110. package/executors/libExecutor.ts +23 -0
  111. package/executors/moduleExecutor.ts +18 -0
  112. package/executors/pkgExecutor.ts +129 -0
  113. package/executors/sysExecutor.ts +301 -0
  114. package/executors/workspaceExecutor.ts +277 -0
  115. package/frontendBuild/allRoutesBuilder.test.ts +17 -5
  116. package/frontendBuild/allRoutesBuilder.ts +24 -6
  117. package/frontendBuild/autoImportSync.test.ts +1 -1
  118. package/frontendBuild/autoImportSync.ts +1 -1
  119. package/frontendBuild/buildRouteClient.test.ts +1 -1
  120. package/frontendBuild/bundleDefine.ts +2 -0
  121. package/frontendBuild/clientBuildTypes.ts +5 -2
  122. package/frontendBuild/clientEntriesBundler.test.ts +1 -1
  123. package/frontendBuild/clientEntryDiscovery.test.ts +28 -0
  124. package/frontendBuild/clientEntryDiscovery.ts +25 -6
  125. package/frontendBuild/csrArtifactBuilder.test.ts +1 -1
  126. package/frontendBuild/csrDevArtifactWriter.ts +1 -1
  127. package/frontendBuild/cssCompiler.test.ts +1 -1
  128. package/frontendBuild/devGeneratedIndexSync.test.ts +1 -1
  129. package/frontendBuild/devGeneratedIndexSync.ts +7 -38
  130. package/frontendBuild/dictionaryAssetBuilder.test.ts +1 -1
  131. package/frontendBuild/fontOptimizer.test.ts +1 -1
  132. package/frontendBuild/fontPruner.test.ts +1 -1
  133. package/frontendBuild/frontendBuild.test.ts +3 -3
  134. package/frontendBuild/hmrWatcher.stop.test.ts +63 -0
  135. package/frontendBuild/hmrWatcher.test.ts +1 -1
  136. package/frontendBuild/hmrWatcher.ts +22 -1
  137. package/frontendBuild/mcpAppViewBuilder.test.ts +1 -1
  138. package/frontendBuild/mcpAppViewBuilder.ts +1 -1
  139. package/frontendBuild/nativeCore.test.ts +148 -0
  140. package/frontendBuild/optionalPeers.test.ts +36 -8
  141. package/frontendBuild/pagesBundleBuilder.test.ts +2 -3
  142. package/frontendBuild/pagesBundleBuilder.ts +1 -1
  143. package/frontendBuild/precompressArtifacts.test.ts +1 -1
  144. package/frontendBuild/precompressArtifacts.ts +1 -1
  145. package/frontendBuild/serverGraphFile.ts +1 -1
  146. package/frontendBuild/sourceMtimeIndex.test.ts +1 -1
  147. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +26 -0
  148. package/frontendBuild/ssrBaseArtifactBuilder.ts +23 -19
  149. package/frontendBuild/ssrDevBundler.test.ts +1 -1
  150. package/frontendBuild/vendorImportScanner.test.ts +25 -4
  151. package/frontendBuild/vendorImportScanner.ts +25 -10
  152. package/frontendBuild/vendorNarrowing.test.ts +1 -1
  153. package/frontendBuild/watchRootResolver.test.ts +1 -1
  154. package/{agentAssets.test.ts → guideline/agentAssets.test.ts} +1 -1
  155. package/{agentAssets.ts → guideline/agentAssets.ts} +2 -2
  156. package/{agentsIndex.test.ts → guideline/agentsIndex.test.ts} +2 -2
  157. package/{agentsIndex.ts → guideline/agentsIndex.ts} +13 -10
  158. package/{conventionSet.test.ts → guideline/conventionSet.test.ts} +7 -4
  159. package/{conventionSet.ts → guideline/conventionSet.ts} +1 -1
  160. package/{prompter.ts → guideline/prompter.ts} +2 -3
  161. package/incrementalBuilder/buildBatch.proc.ts +14 -4
  162. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  163. package/incrementalBuilder/buildBatchRunner.test.ts +108 -1
  164. package/incrementalBuilder/buildBatchRunner.ts +17 -4
  165. package/incrementalBuilder/builderBoot.ts +106 -0
  166. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  167. package/incrementalBuilder/builderChannel.test.ts +1 -1
  168. package/incrementalBuilder/builderChannel.ts +11 -0
  169. package/incrementalBuilder/builderGraphPayloads.ts +3 -3
  170. package/incrementalBuilder/builderLanes.ts +157 -0
  171. package/incrementalBuilder/builderWatch.ts +213 -0
  172. package/incrementalBuilder/csrRegistry.ts +234 -0
  173. package/incrementalBuilder/incrementalBuilder.host.test.ts +30 -1
  174. package/incrementalBuilder/incrementalBuilder.host.ts +10 -22
  175. package/incrementalBuilder/incrementalBuilder.proc.test.ts +93 -2
  176. package/incrementalBuilder/incrementalBuilder.proc.ts +81 -823
  177. package/incrementalBuilder/ssrRegistry.ts +278 -0
  178. package/index.ts +22 -22
  179. package/integration/devStability.integration.test.ts +62 -56
  180. package/integration/devStabilityHarness.test.ts +1 -1
  181. package/lint/__fixtures__/no-import-common-err/bad.tsx +13 -0
  182. package/lint/__fixtures__/no-import-common-err/good.tsx +12 -0
  183. package/{biomeBase.test.ts → lint/biomeBase.test.ts} +1 -1
  184. package/lint/gritRules.test.ts +1 -1
  185. package/{linter.test.ts → lint/linter.test.ts} +1 -1
  186. package/lint/no-import-common-err.grit +31 -0
  187. package/lint/no-init-fetch-in-client.grit +1 -1
  188. package/lint/no-web-only-api-outside-webkit.grit +3 -3
  189. package/mobile/desktopBin.test.ts +1 -1
  190. package/mobile/desktopRelease.test.ts +1 -1
  191. package/mobile/desktopServerStage.test.ts +2 -2
  192. package/mobile/desktopServerStage.ts +1 -1
  193. package/mobile/nativeApi.test.ts +1 -1
  194. package/mobile/nativeApp.test.ts +1 -1
  195. package/mobile/nativeConfig.test.ts +1 -1
  196. package/mobile/nativePluginFolders.test.ts +1 -1
  197. package/mobile/nativePublicEnv.test.ts +1 -1
  198. package/mobile/nativeWebDir.test.ts +1 -1
  199. package/mobile/serverBundleSecrets.test.ts +1 -1
  200. package/mobile/tarWriter.test.ts +1 -1
  201. package/mobile/updatePackFolder.test.ts +1 -1
  202. package/package.json +167 -3
  203. package/packageExports.test.ts +20 -2
  204. package/piDependencyPins.test.ts +1 -1
  205. package/pipeline/PipelineDefinition.ts +1 -1
  206. package/platformTest/IdleWatchedProcess.test.ts +1 -1
  207. package/platformTest/PlatformTestRun.test.ts +1 -1
  208. package/platformTest/TestSnapshot.test.ts +1 -1
  209. package/preview/PreviewView.ts +32 -13
  210. package/preview/previewView.test.ts +33 -3
  211. package/{abstractDoc.test.ts → quality/abstractDoc.test.ts} +2 -2
  212. package/{abstractDoc.ts → quality/abstractDoc.ts} +1 -1
  213. package/quality/bareErrorScanner.ts +126 -0
  214. package/{maintainabilityBaseline.test.ts → quality/maintainabilityBaseline.test.ts} +73 -0
  215. package/{maintainabilityBaseline.ts → quality/maintainabilityBaseline.ts} +97 -9
  216. package/{maintainabilityContract.test.ts → quality/maintainabilityContract.test.ts} +383 -2
  217. package/{maintainabilityContract.ts → quality/maintainabilityContract.ts} +151 -29
  218. package/{maintainabilityExceptionScanner.test.ts → quality/maintainabilityExceptionScanner.test.ts} +15 -1
  219. package/{maintainabilityExceptionScanner.ts → quality/maintainabilityExceptionScanner.ts} +5 -1
  220. package/{maintainabilityLimits.ts → quality/maintainabilityLimits.ts} +12 -0
  221. package/{maintainabilityReport.ts → quality/maintainabilityReport.ts} +20 -3
  222. package/{qualityScanner.test.ts → quality/qualityScanner.test.ts} +1 -1
  223. package/{qualityScanner.ts → quality/qualityScanner.ts} +8 -8
  224. package/{storeAccessScanner.ts → quality/storeAccessScanner.ts} +15 -2
  225. package/{subspace.test.ts → subspace/subspace.test.ts} +25 -4
  226. package/{subspace.ts → subspace/subspace.ts} +5 -5
  227. package/{subspaceClone.ts → subspace/subspaceClone.ts} +8 -8
  228. package/{subspaceConfig.ts → subspace/subspaceConfig.ts} +5 -1
  229. package/{testHelpers.ts → test/testHelpers.ts} +37 -1
  230. package/transforms/barrelAnalyzer.ts +31 -10
  231. package/transforms/browserDirnamePlugin.test.ts +1 -1
  232. package/transforms/externalizeFrameworkPlugin.test.ts +1 -1
  233. package/transforms/mcpAppPageTrimmer.test.ts +1 -1
  234. package/transforms/pureLazyMarker.test.ts +1 -1
  235. package/transforms/serverEnvPlugin.test.ts +1 -1
  236. package/transforms/serverEnvProfile.test.ts +1 -1
  237. package/transforms/sideEffectImportOrder.test.ts +1 -1
  238. package/transforms/transforms.test.ts +52 -2
  239. package/transforms/tsconfigPackageResolver.test.ts +1 -1
  240. package/{createTunnel.test.ts → tunnel/createTunnel.test.ts} +1 -1
  241. package/{createTunnel.ts → tunnel/createTunnel.ts} +2 -2
  242. package/{sshHostKeys.ts → tunnel/sshHostKeys.ts} +2 -2
  243. package/typecheck/projectTypecheck.test.ts +1 -1
  244. package/typecheck/projectTypecheck.ts +6 -2
  245. package/{typeChecker.test.ts → typecheck/typeChecker.test.ts} +1 -1
  246. package/{typeChecker.ts → typecheck/typeChecker.ts} +1 -1
  247. package/typecheck/typecheck.proc.ts +4 -3
  248. package/typecheck/typecheckFailure.ts +7 -2
  249. package/util/errorReport.ts +66 -0
  250. package/{jsonFormatter.test.ts → util/jsonFormatter.test.ts} +1 -1
  251. package/workflow/artifacts.ts +8 -7
  252. package/workflow/constantSource.ts +187 -0
  253. package/workflow/dictionarySource.ts +184 -0
  254. package/workflow/executor.ts +6 -9
  255. package/workflow/fieldExpression.ts +153 -0
  256. package/workflow/fieldLabel.ts +61 -0
  257. package/workflow/fieldOrder.ts +117 -0
  258. package/workflow/fieldType.ts +93 -0
  259. package/workflow/guardCatalog.test.ts +1 -1
  260. package/workflow/index.ts +1 -0
  261. package/workflow/keyRename.ts +1 -1
  262. package/workflow/moduleIndex.test.ts +2 -2
  263. package/workflow/moduleIndex.ts +2 -2
  264. package/workflow/modulePaths.ts +27 -0
  265. package/workflow/mutationScaffold.ts +7 -15
  266. package/workflow/mutationSource.ts +2 -1
  267. package/workflow/plainName.ts +16 -3
  268. package/workflow/plan.ts +14 -2
  269. package/workflow/primitiveReport.ts +78 -0
  270. package/workflow/rolloutGate.test.ts +1 -1
  271. package/workflow/rolloutGate.ts +1 -1
  272. package/workflow/serviceSource.ts +33 -0
  273. package/workflow/signalSource.ts +96 -0
  274. package/workflow/source.ts +50 -1105
  275. package/workflow/sourceAst.ts +30 -0
  276. package/workflow/sourceImports.ts +105 -0
  277. package/workflow/sourceText.ts +13 -0
  278. package/workflow/templateSource.ts +30 -0
  279. package/workflow/testSource.ts +31 -0
  280. package/workflow/types.ts +1 -1
  281. package/workflow/uiPolicy.ts +1 -1
  282. package/{appSelectionMemory.ts → workspace/appSelectionMemory.ts} +1 -1
  283. package/{codegenLock.test.ts → workspace/codegenLock.test.ts} +1 -1
  284. package/{dependencyScanner.test.ts → workspace/dependencyScanner.test.ts} +1 -1
  285. package/{dependencyScanner.ts → workspace/dependencyScanner.ts} +2 -2
  286. package/{envSeed.test.ts → workspace/envSeed.test.ts} +2 -2
  287. package/{envSeed.ts → workspace/envSeed.ts} +1 -1
  288. package/{libSource.test.ts → workspace/libSource.test.ts} +2 -2
  289. package/{libSource.ts → workspace/libSource.ts} +1 -1
  290. package/{scanInfo.ts → workspace/scanInfo.ts} +21 -10
  291. package/{slicePlanner.test.ts → workspace/slicePlanner.test.ts} +2 -2
  292. package/{slicePlanner.ts → workspace/slicePlanner.ts} +1 -1
  293. package/{workspaceGraph.test.ts → workspace/workspaceGraph.test.ts} +1 -1
  294. package/{workspaceGraph.ts → workspace/workspaceGraph.ts} +1 -1
  295. package/{workspaceLayout.test.ts → workspace/workspaceLayout.test.ts} +1 -1
  296. package/{workspaceLayout.ts → workspace/workspaceLayout.ts} +3 -1
  297. package/akanContext.ts +0 -1084
  298. package/constantFieldNames.ts +0 -18
  299. package/executors.ts +0 -1749
  300. /package/{recipeScanner.ts → context/recipeScanner.ts} +0 -0
  301. /package/{declarationReader.ts → docs/declarationReader.ts} +0 -0
  302. /package/{frameworkGraph.ts → docs/frameworkGraph.ts} +0 -0
  303. /package/{biomeBase.ts → lint/biomeBase.ts} +0 -0
  304. /package/{linter.ts → lint/linter.ts} +0 -0
  305. /package/{commentDensityScanner.test.ts → quality/commentDensityScanner.test.ts} +0 -0
  306. /package/{commentDensityScanner.ts → quality/commentDensityScanner.ts} +0 -0
  307. /package/{componentSizeScanner.test.ts → quality/componentSizeScanner.test.ts} +0 -0
  308. /package/{componentSizeScanner.ts → quality/componentSizeScanner.ts} +0 -0
  309. /package/{componentWriteChainScanner.test.ts → quality/componentWriteChainScanner.test.ts} +0 -0
  310. /package/{componentWriteChainScanner.ts → quality/componentWriteChainScanner.ts} +0 -0
  311. /package/{deprecatedCommentScanner.test.ts → quality/deprecatedCommentScanner.test.ts} +0 -0
  312. /package/{deprecatedCommentScanner.ts → quality/deprecatedCommentScanner.ts} +0 -0
  313. /package/{endpointReach.test.ts → quality/endpointReach.test.ts} +0 -0
  314. /package/{endpointReach.ts → quality/endpointReach.ts} +0 -0
  315. /package/{formSetterScanner.test.ts → quality/formSetterScanner.test.ts} +0 -0
  316. /package/{formSetterScanner.ts → quality/formSetterScanner.ts} +0 -0
  317. /package/{kindBranchScanner.test.ts → quality/kindBranchScanner.test.ts} +0 -0
  318. /package/{kindBranchScanner.ts → quality/kindBranchScanner.ts} +0 -0
  319. /package/{maintainabilityReport.test.ts → quality/maintainabilityReport.test.ts} +0 -0
  320. /package/{renderMutationScanner.test.ts → quality/renderMutationScanner.test.ts} +0 -0
  321. /package/{renderMutationScanner.ts → quality/renderMutationScanner.ts} +0 -0
  322. /package/{serviceLoopCallScanner.test.ts → quality/serviceLoopCallScanner.test.ts} +0 -0
  323. /package/{serviceLoopCallScanner.ts → quality/serviceLoopCallScanner.ts} +0 -0
  324. /package/{signalMutationIndex.test.ts → quality/signalMutationIndex.test.ts} +0 -0
  325. /package/{signalMutationIndex.ts → quality/signalMutationIndex.ts} +0 -0
  326. /package/{sourceComments.test.ts → quality/sourceComments.test.ts} +0 -0
  327. /package/{sourceComments.ts → quality/sourceComments.ts} +0 -0
  328. /package/{ssrScanner.test.ts → quality/ssrScanner.test.ts} +0 -0
  329. /package/{ssrScanner.ts → quality/ssrScanner.ts} +0 -0
  330. /package/{storeAccessScanner.test.ts → quality/storeAccessScanner.test.ts} +0 -0
  331. /package/{storeSource.ts → quality/storeSource.ts} +0 -0
  332. /package/{storeWriteScanner.test.ts → quality/storeWriteScanner.test.ts} +0 -0
  333. /package/{storeWriteScanner.ts → quality/storeWriteScanner.ts} +0 -0
  334. /package/{structureScanner.test.ts → quality/structureScanner.test.ts} +0 -0
  335. /package/{structureScanner.ts → quality/structureScanner.ts} +0 -0
  336. /package/{testOnlyExportScanner.test.ts → quality/testOnlyExportScanner.test.ts} +0 -0
  337. /package/{testOnlyExportScanner.ts → quality/testOnlyExportScanner.ts} +0 -0
  338. /package/{writePath.test.ts → quality/writePath.test.ts} +0 -0
  339. /package/{writePath.ts → quality/writePath.ts} +0 -0
  340. /package/{writePlacementScanner.test.ts → quality/writePlacementScanner.test.ts} +0 -0
  341. /package/{writePlacementScanner.ts → quality/writePlacementScanner.ts} +0 -0
  342. /package/{writingActionIndex.test.ts → quality/writingActionIndex.test.ts} +0 -0
  343. /package/{writingActionIndex.ts → quality/writingActionIndex.ts} +0 -0
  344. /package/{subspaceReport.ts → subspace/subspaceReport.ts} +0 -0
  345. /package/{sshTunnel.ts → tunnel/sshTunnel.ts} +0 -0
  346. /package/{fileEditor.ts → util/fileEditor.ts} +0 -0
  347. /package/{fileSys.test.ts → util/fileSys.test.ts} +0 -0
  348. /package/{fileSys.ts → util/fileSys.ts} +0 -0
  349. /package/{jsonFormatter.ts → util/jsonFormatter.ts} +0 -0
  350. /package/{selectModel.ts → util/selectModel.ts} +0 -0
  351. /package/{semver.test.ts → util/semver.test.ts} +0 -0
  352. /package/{semver.ts → util/semver.ts} +0 -0
  353. /package/{shellOnlyEnv.test.ts → util/shellOnlyEnv.test.ts} +0 -0
  354. /package/{shellOnlyEnv.ts → util/shellOnlyEnv.ts} +0 -0
  355. /package/{spinner.test.ts → util/spinner.test.ts} +0 -0
  356. /package/{spinner.ts → util/spinner.ts} +0 -0
  357. /package/{stripAnsi.ts → util/stripAnsi.ts} +0 -0
  358. /package/{codegenLock.ts → workspace/codegenLock.ts} +0 -0
  359. /package/{getRelatedCnsts.ts → workspace/getRelatedCnsts.ts} +0 -0
  360. /package/{gitRevision.test.ts → workspace/gitRevision.test.ts} +0 -0
  361. /package/{gitRevision.ts → workspace/gitRevision.ts} +0 -0
  362. /package/{manifestDependencies.ts → workspace/manifestDependencies.ts} +0 -0
  363. /package/{packageExportsMap.ts → workspace/packageExportsMap.ts} +0 -0
  364. /package/{repoIdentity.ts → workspace/repoIdentity.ts} +0 -0
  365. /package/{types.ts → workspace/types.ts} +0 -0
package/akanContext.ts DELETED
@@ -1,1084 +0,0 @@
1
- import { readdir } from "node:fs/promises";
2
- import path from "node:path";
3
- import { capitalize, isRecord, parseRouteModuleKey } from "akanjs/common";
4
- import { extractBlockVersion, readDevkitVersion } from "./agentsIndex";
5
- import { constantFieldNames } from "./constantFieldNames";
6
- import { AppExecutor, LibExecutor, type SysExecutor, type WorkspaceExecutor } from "./executors";
7
- import { FileSys } from "./fileSys";
8
- import { collectRecipeSources, findInlineRecipeDuplicates, scanRecipes } from "./recipeScanner";
9
- import type { PackageJson } from "./types";
10
- import {
11
- type GeneratedSyncState,
12
- type RepairAction,
13
- type WorkflowApplyReport,
14
- type WorkflowPlan,
15
- type WorkflowRunArtifact,
16
- workflowPathsForPlan,
17
- workflowRunArtifactPath,
18
- workflowSyncDir,
19
- } from "./workflow";
20
- import {
21
- barrelFacetDirs,
22
- facetIndexShadowOf,
23
- isScannedRootEntry,
24
- rootAllowedDirs,
25
- rootAllowedFiles,
26
- rootEntryHintOf,
27
- } from "./workspaceLayout";
28
-
29
- export type AkanContextFormat = "json" | "markdown";
30
- export type AkanModuleKind = "domain" | "service" | "scalar";
31
- export type AkanDiagnosticSeverity = "warning" | "error";
32
-
33
- export interface AkanAbstractSummary {
34
- path: string;
35
- exists: boolean;
36
- title?: string;
37
- headings: string[];
38
- content?: string;
39
- }
40
-
41
- export interface AkanModuleContext {
42
- kind: AkanModuleKind;
43
- name: string;
44
- folderName: string;
45
- sysName: string;
46
- sysType: "app" | "lib";
47
- path: string;
48
- abstract: AkanAbstractSummary;
49
- files: string[];
50
- }
51
-
52
- export interface AkanRouteContext {
53
- /** The URL pattern without the `/:lang` segment every route starts with. */
54
- path: string;
55
- file: string;
56
- search: string[];
57
- /** The page or a layout above it calls `.guard()`. */
58
- guarded: boolean;
59
- devOnly: boolean;
60
- }
61
-
62
- export interface AkanSysContext {
63
- type: "app" | "lib";
64
- name: string;
65
- path: string;
66
- hasConfig: boolean;
67
- modules: AkanModuleContext[];
68
- /** Listed for the app `--app` names only; reading them parses every route file. */
69
- routes?: AkanRouteContext[];
70
- routeError?: string;
71
- }
72
-
73
- export interface AkanPackageContext {
74
- name: string;
75
- path: string;
76
- version?: string;
77
- }
78
-
79
- export interface AkanWorkspaceContext {
80
- schemaVersion: 1;
81
- repoName: string;
82
- root: string;
83
- packageVersion?: string;
84
- apps: AkanSysContext[];
85
- libs: AkanSysContext[];
86
- pkgs: AkanPackageContext[];
87
- generatedFiles: string[];
88
- validationCommands: string[];
89
- }
90
-
91
- export interface AkanDiagnostic {
92
- severity: AkanDiagnosticSeverity;
93
- code: string;
94
- message: string;
95
- path?: string;
96
- repairActions?: RepairAction[];
97
- scope?: "baseline" | "workflow" | "unknown";
98
- context?: {
99
- workflow?: string;
100
- planPath?: string;
101
- runId?: string;
102
- target?: string;
103
- paths?: string[];
104
- };
105
- }
106
-
107
- export interface GeneratedFilesFreshness {
108
- status: "fresh" | "stale" | "missing" | "unknown";
109
- message: string;
110
- refreshCommand: string;
111
- verifyingCommands: string[];
112
- targets?: {
113
- target: string;
114
- status: "fresh" | "stale" | "missing" | "unknown";
115
- lastSyncedAt?: string;
116
- runId?: string;
117
- generatedFiles: string[];
118
- reason: string;
119
- }[];
120
- }
121
-
122
- export interface AkanDoctorResult {
123
- schemaVersion: 1;
124
- repoName: string;
125
- root: string;
126
- strict: boolean;
127
- status: "passed" | "failed";
128
- diagnostics: AkanDiagnostic[];
129
- generatedFiles: string[];
130
- generatedFilesFreshness: GeneratedFilesFreshness;
131
- validationCommands: string[];
132
- repairActions: RepairAction[];
133
- baselineDiagnostics?: AkanDiagnostic[];
134
- workflowDiagnostics?: AkanDiagnostic[];
135
- }
136
-
137
- export type JsonRpcRequest = {
138
- jsonrpc?: "2.0";
139
- id?: string | number | null;
140
- method: string;
141
- params?: Record<string, unknown>;
142
- };
143
-
144
- export type McpFraming = "content-length" | "newline";
145
- export type AkanMcpMode = "readonly" | "plan" | "apply";
146
-
147
- // Cursor and Claude Code read a JSON `mcpServers` map; Codex reads a TOML `[mcp_servers.<name>]` table.
148
- export type AkanMcpInstallTarget = "cursor" | "claude" | "codex";
149
-
150
- export type CursorMcpConfig = {
151
- mcpServers?: Record<string, unknown>;
152
- };
153
-
154
- export const guidelineResourceUri = (name: string) => `akan://guidelines/${name}`;
155
-
156
- const staticResourceList = [
157
- { uri: "akan://docs/framework", name: "Akan framework guide", mimeType: "text/markdown" },
158
- { uri: "akan://workspace/summary", name: "Workspace summary", mimeType: "application/json" },
159
- { uri: "akan://workspace/apps", name: "Workspace apps", mimeType: "application/json" },
160
- { uri: "akan://workspace/modules", name: "Workspace modules", mimeType: "application/json" },
161
- ];
162
-
163
- export const buildResourceList = (guidelineNames: readonly string[]) => [
164
- ...staticResourceList,
165
- ...guidelineNames.map((name) => ({
166
- uri: guidelineResourceUri(name),
167
- name: `${name} guideline`,
168
- mimeType: "text/markdown",
169
- })),
170
- ];
171
-
172
- export const cursorMcpConfigPath = ".cursor/mcp.json";
173
- // Claude Code reads project-scoped MCP servers from `.mcp.json` at the workspace root.
174
- export const claudeMcpConfigPath = ".mcp.json";
175
- // Codex reads project-scoped config (trusted projects) from `.codex/config.toml`.
176
- export const codexMcpConfigPath = ".codex/config.toml";
177
-
178
- export const akanMcpInstallTargets: AkanMcpInstallTarget[] = ["cursor", "claude", "codex"];
179
-
180
- export const akanMcpInstallConfigPaths: Record<AkanMcpInstallTarget, string> = {
181
- cursor: cursorMcpConfigPath,
182
- claude: claudeMcpConfigPath,
183
- codex: codexMcpConfigPath,
184
- };
185
-
186
- // `akan mcp` resolves the workspace from its cwd: Cursor expands ${workspaceFolder}, Claude Code only sets
187
- // CLAUDE_PROJECT_DIR (its cwd is not guaranteed), and Codex runs from its own launch cwd.
188
- const cursorWorkspaceFolder = "$" + "{workspaceFolder}";
189
- const claudeProjectDir = "$CLAUDE_PROJECT_DIR";
190
-
191
- const akanMcpCommand = (mode: AkanMcpMode, { cd }: { cd?: string } = {}) =>
192
- cd ? `cd "${cd}" && akan mcp --mode ${mode}` : `akan mcp --mode ${mode}`;
193
-
194
- const bashMcpServer = (mode: AkanMcpMode, cd: string) => ({
195
- type: "stdio",
196
- command: "bash",
197
- args: ["-lc", akanMcpCommand(mode, { cd })],
198
- });
199
-
200
- export const createAkanCursorMcpServer = (mode: AkanMcpMode = "readonly") => bashMcpServer(mode, cursorWorkspaceFolder);
201
-
202
- export const createAkanClaudeMcpServer = (mode: AkanMcpMode = "readonly") => bashMcpServer(mode, claudeProjectDir);
203
-
204
- export const createAkanMcpServer = (target: "cursor" | "claude", mode: AkanMcpMode = "readonly") =>
205
- target === "cursor" ? createAkanCursorMcpServer(mode) : createAkanClaudeMcpServer(mode);
206
-
207
- export const akanCursorMcpServer = createAkanCursorMcpServer();
208
-
209
- // No TOML serializer is bundled, so the `[mcp_servers.akan]` table is written as text.
210
- export const codexMcpServerTableHeader = "[mcp_servers.akan]";
211
- export const createAkanCodexMcpServerBlock = (mode: AkanMcpMode = "readonly") =>
212
- `${codexMcpServerTableHeader}\ncommand = "bash"\nargs = ["-lc", "${akanMcpCommand(mode)}"]\n`;
213
-
214
- // A TOML table runs from its header until the next top-level `[header]` or EOF.
215
- const codexAkanTablePattern = /^\[mcp_servers\.akan\][^\n]*\n(?:(?!\[)[^\n]*(?:\n|$))*/m;
216
-
217
- export const upsertCodexMcpServerBlock = (
218
- existing: string,
219
- block: string,
220
- { force = false }: { force?: boolean } = {},
221
- ) => {
222
- const nextBlock = block.endsWith("\n") ? block : `${block}\n`;
223
- const match = existing.match(codexAkanTablePattern);
224
- if (!match) {
225
- if (!existing.trim()) return nextBlock;
226
- return `${existing.trimEnd()}\n\n${nextBlock}`;
227
- }
228
- if (match[0].trim() === nextBlock.trim()) return existing;
229
- if (!force)
230
- throw new Error(`${codexMcpConfigPath} already has an "akan" MCP server. Re-run with --force to overwrite it.`);
231
- const start = match.index ?? 0;
232
- const before = existing.slice(0, start);
233
- const after = existing.slice(start + match[0].length);
234
- // The matched table absorbed its trailing blank line, so re-insert one before any following table.
235
- const separator = after && !after.startsWith("\n") ? "\n" : "";
236
- return `${before}${nextBlock}${separator}${after}`;
237
- };
238
-
239
- export const renderDoctorText = (result: AkanDoctorResult) => {
240
- const lines = [`Akan doctor status: ${result.status}`];
241
- if (result.diagnostics.length === 0) {
242
- lines.push("", "No Akan workspace diagnostics found.");
243
- } else {
244
- lines.push(
245
- "",
246
- ...result.diagnostics.map((diagnostic) =>
247
- [
248
- `[${diagnostic.severity}] ${diagnostic.code}: ${diagnostic.message}`,
249
- diagnostic.path ? ` ${diagnostic.path}` : "",
250
- ]
251
- .filter(Boolean)
252
- .join("\n"),
253
- ),
254
- );
255
- }
256
- lines.push(
257
- "",
258
- "Generated file freshness:",
259
- `Status: ${result.generatedFilesFreshness.status}`,
260
- result.generatedFilesFreshness.message,
261
- `Refresh: ${result.generatedFilesFreshness.refreshCommand}`,
262
- "",
263
- "Repair actions:",
264
- ...(result.repairActions.length ? result.repairActions.map((action) => `- ${action.command}`) : ["- none"]),
265
- "",
266
- "Validation commands:",
267
- ...result.validationCommands.map((command) => `- ${command}`),
268
- );
269
- return `${lines.join("\n")}\n`;
270
- };
271
-
272
- export interface AkanContextOptions {
273
- app?: string | null;
274
- module?: string | null;
275
- includeAbstractContent?: boolean;
276
- }
277
-
278
- const generatedFiles = [
279
- "apps/*/client.ts",
280
- "apps/*/server.ts",
281
- "*/lib/cnst.ts",
282
- "*/lib/db.ts",
283
- "*/lib/dict.ts",
284
- "*/lib/sig.ts",
285
- "*/lib/srv.ts",
286
- "*/lib/st.ts",
287
- "*/lib/useClient.ts",
288
- "*/lib/useServer.ts",
289
- "*/lib/**/index.ts",
290
- "*/ui/index.ts",
291
- "*/webkit/index.ts",
292
- "*/srvkit/index.ts",
293
- "*/common/index.ts",
294
- ];
295
-
296
- const validationCommands = [
297
- "akan verify [<app-or-lib-or-pkg>]",
298
- "akan sync <app-or-lib>",
299
- "akan lint <app-or-lib-or-pkg>",
300
- "akan typecheck <app-or-lib>",
301
- "akan test <app-or-lib-or-pkg>",
302
- "akan build <app-name>",
303
- "akan doctor --strict --format json",
304
- "akan quality scan [--format json]",
305
- "akan quality ssr [--format json]",
306
- ];
307
-
308
- const unknownGeneratedFilesFreshness: GeneratedFilesFreshness = {
309
- status: "unknown" as const,
310
- message: "Run sync before validation so generated Akan files match the current source conventions.",
311
- refreshCommand: "akan sync <app-or-lib>",
312
- verifyingCommands: ["akan verify <app-or-lib>"],
313
- };
314
-
315
- const repairAction = (
316
- kind: RepairAction["kind"],
317
- command: string,
318
- reason: string,
319
- safeToRun: boolean,
320
- ): RepairAction => ({
321
- kind,
322
- command,
323
- reason,
324
- safeToRun,
325
- });
326
-
327
- const moduleShapeFiles = (module: AkanModuleContext) => {
328
- if (module.kind === "service") {
329
- return [`${module.name}.dictionary.ts`, `${module.name}.service.ts`, `${module.name}.signal.ts`];
330
- }
331
- if (module.kind === "scalar") return [`${module.name}.constant.ts`, `${module.name}.dictionary.ts`];
332
- return [
333
- `${module.name}.constant.ts`,
334
- `${module.name}.dictionary.ts`,
335
- `${module.name}.service.ts`,
336
- `${module.name}.store.ts`,
337
- `${module.name}.signal.ts`,
338
- ];
339
- };
340
-
341
- const safeReadDir = async (dirPath: string) =>
342
- (await readdir(dirPath, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name));
343
-
344
- const safeReadText = (filePath: string) => FileSys.readText(filePath).catch(() => null);
345
-
346
- const safeReadJson = <T>(filePath: string) => FileSys.readJson<T>(filePath).catch(() => null);
347
-
348
- const isWorkflowPlan = (value: unknown): value is WorkflowPlan =>
349
- typeof value === "object" &&
350
- value !== null &&
351
- "schemaVersion" in value &&
352
- value.schemaVersion === 1 &&
353
- "mode" in value &&
354
- value.mode === "plan" &&
355
- "inputs" in value &&
356
- isRecord(value.inputs) &&
357
- "predictedChanges" in value &&
358
- Array.isArray(value.predictedChanges) &&
359
- value.predictedChanges.every((change) => isRecord(change) && typeof change.target === "string");
360
-
361
- const isPathList = (value: unknown) =>
362
- Array.isArray(value) && value.every((file) => isRecord(file) && typeof file.path === "string");
363
-
364
- const isWorkflowApplyReport = (value: unknown): value is WorkflowApplyReport =>
365
- typeof value === "object" &&
366
- value !== null &&
367
- "schemaVersion" in value &&
368
- value.schemaVersion === 1 &&
369
- "mode" in value &&
370
- (value.mode === "apply" || value.mode === "dry-run") &&
371
- "changedFiles" in value &&
372
- isPathList(value.changedFiles) &&
373
- "generatedFiles" in value &&
374
- isPathList(value.generatedFiles) &&
375
- "plan" in value &&
376
- isWorkflowPlan(value.plan);
377
-
378
- const isWorkflowRunArtifact = (value: unknown): value is WorkflowRunArtifact =>
379
- typeof value === "object" && value !== null && "schemaVersion" in value && value.schemaVersion === 1;
380
-
381
- const workflowPathsForArtifact = (artifact: WorkflowRunArtifact) => {
382
- if (isWorkflowPlan(artifact)) return workflowPathsForPlan(artifact);
383
- if (isWorkflowApplyReport(artifact)) {
384
- return [
385
- ...artifact.changedFiles.map((file) => file.path),
386
- ...artifact.generatedFiles.map((file) => file.path),
387
- ...workflowPathsForPlan(artifact.plan),
388
- ];
389
- }
390
- if ("mode" in artifact && artifact.mode === "validate" && isWorkflowPlan(artifact.plan))
391
- return workflowPathsForPlan(artifact.plan);
392
- return [];
393
- };
394
-
395
- const loadWorkflowContextPaths = async (
396
- workspace: WorkspaceExecutor,
397
- runIdOrPlan: string | null,
398
- changedFiles: string[],
399
- ) => {
400
- const paths = [...changedFiles];
401
- if (!runIdOrPlan) return paths;
402
- const inputPath = path.isAbsolute(runIdOrPlan) ? runIdOrPlan : path.join(workspace.workspaceRoot, runIdOrPlan);
403
- const artifact =
404
- (await safeReadJson<WorkflowRunArtifact | WorkflowPlan>(inputPath)) ??
405
- (await safeReadJson<WorkflowRunArtifact>(path.join(workspace.workspaceRoot, workflowRunArtifactPath(runIdOrPlan))));
406
- if (artifact && isWorkflowRunArtifact(artifact)) paths.push(...workflowPathsForArtifact(artifact));
407
- return [...new Set(paths.filter(Boolean))];
408
- };
409
-
410
- const pathKey = (value: string) =>
411
- value
412
- .replaceAll("\\", "/")
413
- .replaceAll("*", "")
414
- .replace(/<[^>]+>/g, "")
415
- .replace(/\/+/g, "/")
416
- .replace(/^\/|\/$/g, "");
417
-
418
- const isWorkflowRelatedDiagnostic = (diagnostic: AkanDiagnostic, workflowPaths: string[]) => {
419
- if (!diagnostic.path) return false;
420
- const diagnosticPath = pathKey(diagnostic.path);
421
- return workflowPaths.some((workflowPath) => {
422
- const candidate = pathKey(workflowPath);
423
- if (!candidate) return false;
424
- return (
425
- diagnosticPath.startsWith(candidate) || candidate.startsWith(diagnosticPath) || diagnosticPath.includes(candidate)
426
- );
427
- });
428
- };
429
-
430
- const readGeneratedSyncStates = async (workspace: WorkspaceExecutor) => {
431
- const syncDir = path.join(workspace.workspaceRoot, workflowSyncDir);
432
- const entries = await safeReadDir(syncDir);
433
- const states = await Promise.all(
434
- entries
435
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
436
- .map((entry) => safeReadJson<GeneratedSyncState>(path.join(syncDir, entry.name))),
437
- );
438
- return states.filter(
439
- (state): state is GeneratedSyncState =>
440
- !!state && state.schemaVersion === 1 && typeof state.target === "string" && typeof state.syncedAt === "string",
441
- );
442
- };
443
-
444
- const generatedFreshnessFromStates = async (workspace: WorkspaceExecutor): Promise<GeneratedFilesFreshness> => {
445
- const states = await readGeneratedSyncStates(workspace);
446
- if (states.length === 0) return unknownGeneratedFilesFreshness;
447
- const targets = states
448
- .sort((a, b) => a.target.localeCompare(b.target))
449
- .map((state) => ({
450
- target: state.target,
451
- status: state.status === "passed" ? ("fresh" as const) : ("stale" as const),
452
- lastSyncedAt: state.syncedAt,
453
- runId: state.runId,
454
- generatedFiles: state.generatedFiles.map((file) => file.path),
455
- reason:
456
- state.status === "passed"
457
- ? `Generated files were refreshed by ${state.command}.`
458
- : `Last generated repair command failed: ${state.command}.`,
459
- }));
460
- const lastFresh = targets
461
- .filter((target) => target.status === "fresh" && target.lastSyncedAt)
462
- .sort((a, b) => (b.lastSyncedAt ?? "").localeCompare(a.lastSyncedAt ?? ""))[0];
463
- return {
464
- status: targets.some((target) => target.status === "fresh") ? "fresh" : "stale",
465
- message: lastFresh
466
- ? `Generated files were refreshed for ${lastFresh.target} at ${lastFresh.lastSyncedAt}.`
467
- : "Generated sync state exists, but the last recorded repair did not pass.",
468
- refreshCommand: "akan sync <app-or-lib>",
469
- verifyingCommands: ["akan verify <app-or-lib>"],
470
- targets,
471
- };
472
- };
473
-
474
- const parseAbstractSummary = (
475
- relativePath: string,
476
- content: string | null,
477
- includeContent: boolean,
478
- ): AkanAbstractSummary => {
479
- if (content === null) return { path: relativePath, exists: false, headings: [] };
480
- const headings = content
481
- .split(/\r?\n/)
482
- .map((line) => line.trim())
483
- .filter((line) => line.startsWith("#"))
484
- .map((line) => line.replace(/^#+\s*/, "").trim())
485
- .filter(Boolean);
486
- return {
487
- path: relativePath,
488
- exists: true,
489
- title: headings[0],
490
- headings: headings.slice(0, 8),
491
- ...(includeContent ? { content } : {}),
492
- };
493
- };
494
-
495
- const readFiles = async (dirPath: string) =>
496
- (await safeReadDir(dirPath))
497
- .filter((entry) => entry.isFile())
498
- .map((entry) => entry.name)
499
- .sort();
500
-
501
- const getRelative = (workspace: WorkspaceExecutor, absolutePath: string) =>
502
- path.relative(workspace.workspaceRoot, absolutePath).replaceAll(path.sep, "/");
503
-
504
- const createModuleContext = async (
505
- workspace: WorkspaceExecutor,
506
- sys: SysExecutor,
507
- kind: AkanModuleKind,
508
- folderName: string,
509
- moduleName: string,
510
- includeAbstractContent: boolean,
511
- ): Promise<AkanModuleContext> => {
512
- const modulePath =
513
- kind === "scalar"
514
- ? path.join(sys.cwdPath, "lib", "__scalar", moduleName)
515
- : path.join(sys.cwdPath, "lib", folderName);
516
- const relativePath = getRelative(workspace, modulePath);
517
- const abstractPath = `${relativePath}/${moduleName}.abstract.md`;
518
- const abstractContent = await safeReadText(path.join(workspace.workspaceRoot, abstractPath));
519
- return {
520
- kind,
521
- name: moduleName,
522
- folderName,
523
- sysName: sys.name,
524
- sysType: sys.type,
525
- path: relativePath,
526
- abstract: parseAbstractSummary(abstractPath, abstractContent, includeAbstractContent),
527
- files: await readFiles(modulePath),
528
- };
529
- };
530
-
531
- const getSysModules = async (
532
- workspace: WorkspaceExecutor,
533
- sys: SysExecutor,
534
- {
535
- includeAbstractContent = false,
536
- module: moduleFilter,
537
- }: { includeAbstractContent?: boolean; module?: string | null } = {},
538
- ) => {
539
- const libPath = path.join(sys.cwdPath, "lib");
540
- const entries = await safeReadDir(libPath);
541
- const modules: AkanModuleContext[] = [];
542
- for (const entry of entries) {
543
- if (!entry.isDirectory()) continue;
544
- if (entry.name === "__scalar") continue;
545
- if (entry.name.startsWith("__")) continue;
546
- if (entry.name.startsWith("_")) {
547
- const serviceName = entry.name.replace(/^_+/, "");
548
- if (moduleFilter && moduleFilter !== serviceName && moduleFilter !== entry.name) continue;
549
- if (!(await FileSys.fileExists(path.join(libPath, entry.name, `${serviceName}.service.ts`)))) continue;
550
- modules.push(
551
- await createModuleContext(workspace, sys, "service", entry.name, serviceName, includeAbstractContent),
552
- );
553
- } else {
554
- if (moduleFilter && moduleFilter !== entry.name) continue;
555
- if (!(await FileSys.fileExists(path.join(libPath, entry.name, `${entry.name}.constant.ts`)))) continue;
556
- modules.push(await createModuleContext(workspace, sys, "domain", entry.name, entry.name, includeAbstractContent));
557
- }
558
- }
559
-
560
- const scalarRoot = path.join(libPath, "__scalar");
561
- for (const entry of await safeReadDir(scalarRoot)) {
562
- if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
563
- if (moduleFilter && moduleFilter !== entry.name) continue;
564
- if (!(await FileSys.fileExists(path.join(scalarRoot, entry.name, `${entry.name}.constant.ts`)))) continue;
565
- modules.push(await createModuleContext(workspace, sys, "scalar", entry.name, entry.name, includeAbstractContent));
566
- }
567
-
568
- return modules.sort((a, b) => `${a.sysName}:${a.path}`.localeCompare(`${b.sysName}:${b.path}`));
569
- };
570
-
571
- const getAppRoutes = async (app: AppExecutor, workspaceRoot: string): Promise<AkanRouteContext[]> => {
572
- const sources = await app.getRouteSources();
573
- const guardedLayouts = new Set<string>();
574
- const pages: { source: (typeof sources)[number]; parsed: ReturnType<typeof parseRouteModuleKey> }[] = [];
575
- for (const source of sources) {
576
- const parsed = parseRouteModuleKey(source.key);
577
- if (parsed.kind === "layout" && source.info.chain?.guarded) guardedLayouts.add(parsed.routeSegments.join("/"));
578
- else if (parsed.kind === "page") pages.push({ source, parsed });
579
- }
580
- return pages
581
- .map(({ source, parsed }) => {
582
- const segments = parsed.routeSegments;
583
- //? The layouts that wrap a page, as the route seed index walks them: an `_index` sits inside its own folder.
584
- const reach = parsed.leaf === "_index" ? segments.length : segments.length - 1;
585
- const underGuard = Array.from({ length: reach + 1 }, (_, idx) => segments.slice(0, idx).join("/")).some(
586
- (prefix) => guardedLayouts.has(prefix),
587
- );
588
- return {
589
- path: parsed.pattern.replace(/^\/:lang/, "") || "/",
590
- file: path.relative(workspaceRoot, source.absPath).replaceAll(path.sep, "/"),
591
- search: source.info.chain?.search ?? [],
592
- guarded: !!source.info.chain?.guarded || underGuard,
593
- devOnly: source.info.devOnly,
594
- };
595
- })
596
- .sort((a, b) => a.path.localeCompare(b.path));
597
- };
598
-
599
- const getSysContext = async (
600
- workspace: WorkspaceExecutor,
601
- type: "app" | "lib",
602
- name: string,
603
- options: AkanContextOptions,
604
- ): Promise<AkanSysContext> => {
605
- const sys = type === "app" ? AppExecutor.from(workspace, name) : LibExecutor.from(workspace, name);
606
- const context: AkanSysContext = {
607
- type,
608
- name,
609
- path: `${type}s/${name}`,
610
- hasConfig: await FileSys.fileExists(path.join(sys.cwdPath, "akan.config.ts")),
611
- modules: await getSysModules(workspace, sys, {
612
- includeAbstractContent: options.includeAbstractContent,
613
- module: options.module,
614
- }),
615
- };
616
- if (sys instanceof AppExecutor && options.app === name)
617
- await getAppRoutes(sys, workspace.workspaceRoot).then(
618
- (routes) => (context.routes = routes),
619
- (error: unknown) => (context.routeError = error instanceof Error ? error.message : String(error)),
620
- );
621
- return context;
622
- };
623
-
624
- export class AkanContextAnalyzer {
625
- static async analyze(workspace: WorkspaceExecutor, options: AkanContextOptions = {}): Promise<AkanWorkspaceContext> {
626
- const [appNames, libNames, pkgNames] = await workspace.getExecs();
627
- const rootPackageJson = await safeReadJson<PackageJson>(path.join(workspace.workspaceRoot, "package.json"));
628
- const filteredApps = options.app ? appNames.filter((name) => name === options.app) : appNames;
629
- const [apps, libs, pkgs] = await Promise.all([
630
- Promise.all(filteredApps.map((name) => getSysContext(workspace, "app", name, options))),
631
- Promise.all(libNames.map((name) => getSysContext(workspace, "lib", name, options))),
632
- Promise.all(
633
- pkgNames.map(async (name) => {
634
- const packageJson = await safeReadJson<PackageJson>(
635
- path.join(workspace.workspaceRoot, "pkgs", name, "package.json"),
636
- );
637
- return {
638
- name,
639
- path: `pkgs/${name}`,
640
- ...(packageJson?.version ? { version: packageJson.version } : {}),
641
- };
642
- }),
643
- ),
644
- ]);
645
-
646
- return {
647
- schemaVersion: 1,
648
- repoName: workspace.repoName,
649
- root: workspace.workspaceRoot,
650
- packageVersion: rootPackageJson?.dependencies?.akanjs ?? rootPackageJson?.devDependencies?.["@akanjs/devkit"],
651
- apps,
652
- libs,
653
- pkgs,
654
- generatedFiles,
655
- validationCommands,
656
- };
657
- }
658
-
659
- // Nothing re-renders the AGENTS.md block on `bun update`, so the version stamp is the only staleness signal.
660
- static async #agentGuideDrift(workspace: WorkspaceExecutor) {
661
- const installed = await readDevkitVersion();
662
- if (!installed) return null;
663
- const content = await safeReadText(path.join(workspace.workspaceRoot, "AGENTS.md"));
664
- if (content === null) return null;
665
- const stamped = extractBlockVersion(content);
666
- if (stamped === installed) return null;
667
- const hint = "Re-render the AGENTS.md managed block from the installed framework release.";
668
- if (!stamped)
669
- return {
670
- code: "agent-guide-unstamped",
671
- message: `AGENTS.md carries no generated-version stamp, so its conventions may predate @akanjs/devkit ${installed}`,
672
- hint,
673
- };
674
- return {
675
- code: "agent-guide-stale",
676
- message: `AGENTS.md was generated by @akanjs/devkit ${stamped}, but ${installed} is installed`,
677
- hint,
678
- };
679
- }
680
-
681
- //? Codex joins every AGENTS.md from the repo root down to its folder and drops what passes 32 KiB (`project_doc_max_bytes`).
682
- static async #agentGuideOversize(workspace: WorkspaceExecutor, sysPaths: string[]) {
683
- const sizeOf = async (file: string) => {
684
- const content = await safeReadText(path.join(workspace.workspaceRoot, file));
685
- return { file, bytes: content === null ? 0 : Buffer.byteLength(content) };
686
- };
687
- const root = await sizeOf("AGENTS.md");
688
- if (root.bytes === 0) return null;
689
- const scoped = await Promise.all(sysPaths.map((sysPath) => sizeOf(`${sysPath}/AGENTS.md`)));
690
- const largest = scoped.reduce((max, entry) => (entry.bytes > max.bytes ? entry : max), { file: "", bytes: 0 });
691
- const total = root.bytes + largest.bytes;
692
- if (total <= 32 * 1024 * 0.8) return null;
693
- const subject = largest.bytes ? `AGENTS.md and ${largest.file} add up to` : "AGENTS.md is";
694
- return `${subject} ${Math.ceil(total / 1024)} KiB of the 32 KiB Codex reads — run \`akan agent install\`, then shorten the text outside the akan:agent markers or move it into a skill.`;
695
- }
696
-
697
- static async #agentGuideLeftovers(workspace: WorkspaceExecutor) {
698
- const root = workspace.workspaceRoot;
699
- const guide = (await safeReadText(path.join(root, "AGENTS.md"))) ?? "";
700
- const leftovers: { path: string; message: string }[] = [];
701
- for (const doc of ["docs/AI-DEVELOPMENT.md", "docs/GENERATED.md"]) {
702
- const pointer = guide.includes(doc);
703
- if ((await safeReadText(path.join(root, doc))) !== null)
704
- leftovers.push({
705
- path: doc,
706
- message: `${doc} is an older template's copy of the agent guide, and nothing reads it now — delete it${pointer ? " and the AGENTS.md sentence that points to it" : ""}.`,
707
- });
708
- else if (pointer)
709
- leftovers.push({
710
- path: "AGENTS.md",
711
- message: `AGENTS.md points to ${doc}, which is gone — delete that sentence.`,
712
- });
713
- }
714
- return leftovers;
715
- }
716
-
717
- //? Older templates wrote these for Next.js: nothing installs or reads them, and editors warn about the plugin.
718
- static async #configLeftovers(workspace: WorkspaceExecutor, sysPaths: string[]) {
719
- const leftovers: { path: string; message: string }[] = [];
720
- for (const sysPath of sysPaths) {
721
- const tsconfigPath = `${sysPath}/tsconfig.json`;
722
- const tsconfig = await safeReadText(path.join(workspace.workspaceRoot, tsconfigPath));
723
- if (tsconfig && (/"name"\s*:\s*"next"/.test(tsconfig) || tsconfig.includes(".next/types")))
724
- leftovers.push({
725
- path: tsconfigPath,
726
- message: `${tsconfigPath} still names the Next.js TS plugin or .next/types, which Akan never uses — delete the "next" plugin entry and the ".next/types/**/*.ts" include.`,
727
- });
728
- }
729
- const bunfig = await safeReadText(path.join(workspace.workspaceRoot, "bunfig.toml"));
730
- if (bunfig?.includes("bun-plugin-tailwind"))
731
- leftovers.push({
732
- path: "bunfig.toml",
733
- message:
734
- "bunfig.toml still loads bun-plugin-tailwind, which is not installed and which Akan never uses (it compiles Tailwind itself) — delete the [serve.static] section, which Akan never reads.",
735
- });
736
- return leftovers;
737
- }
738
-
739
- static async doctor(
740
- workspace: WorkspaceExecutor,
741
- {
742
- strict = false,
743
- runIdOrPlan = null,
744
- changedFiles = [],
745
- }: { strict?: boolean; runIdOrPlan?: string | null; changedFiles?: string[] } = {},
746
- ): Promise<AkanDoctorResult> {
747
- const context = await AkanContextAnalyzer.analyze(workspace);
748
- const workflowPaths = await loadWorkflowContextPaths(workspace, runIdOrPlan, changedFiles);
749
- const diagnostics: AkanDiagnostic[] = [];
750
- const repairActions: RepairAction[] = [
751
- repairAction("generated", "akan repair generated --app <app-or-lib>", "Refresh generated Akan files.", true),
752
- repairAction(
753
- "format",
754
- "akan repair format --target <app-or-lib-or-pkg>",
755
- "Run the formatter/linter repair path.",
756
- true,
757
- ),
758
- ];
759
- const report = (diagnostic: AkanDiagnostic, action: RepairAction) => {
760
- diagnostics.push({ ...diagnostic, repairActions: [action] });
761
- repairActions.push(action);
762
- };
763
-
764
- for (const sys of [...context.apps, ...context.libs]) {
765
- const sysPath = path.join(workspace.workspaceRoot, sys.path);
766
- for (const entry of await safeReadDir(sysPath)) {
767
- if (!isScannedRootEntry(sys.type, entry.name)) continue;
768
- const allowed = entry.isDirectory()
769
- ? rootAllowedDirs[sys.type].has(entry.name)
770
- : rootAllowedFiles[sys.type].has(entry.name);
771
- const rootEntryHint = rootEntryHintOf(sys.type, entry.name);
772
- if (!allowed)
773
- report(
774
- {
775
- severity: "error",
776
- code: `${sys.type}-root-unknown-entry`,
777
- path: `${sys.path}/${entry.name}`,
778
- message: `Unexpected ${entry.isDirectory() ? "folder" : "file"} in ${sys.type} root: ${sys.path}/${entry.name}${
779
- rootEntryHint ? ` (${rootEntryHint})` : ""
780
- }`,
781
- },
782
- repairAction(
783
- "module-shape",
784
- `akan repair module-shape --app ${sys.name}`,
785
- `Review ${sys.type} root shape and remove or move the unknown entry.`,
786
- false,
787
- ),
788
- );
789
- }
790
- for (const facet of barrelFacetDirs)
791
- for (const entry of await safeReadDir(path.join(sysPath, facet))) {
792
- const shadow = entry.isDirectory() ? null : facetIndexShadowOf(`${facet}/${entry.name}`);
793
- if (!shadow) continue;
794
- const entryPath = `${sys.path}/${facet}/${entry.name}`;
795
- report(
796
- { severity: "error", code: "facet-index-shadowed", path: entryPath, message: `${entryPath} ${shadow}` },
797
- repairAction("generated", `akan sync ${sys.name}`, `Delete ${entryPath} by hand, then sync.`, false),
798
- );
799
- }
800
- }
801
-
802
- const agentDrift = await AkanContextAnalyzer.#agentGuideDrift(workspace);
803
- if (agentDrift)
804
- report(
805
- { severity: "warning", code: agentDrift.code, path: "AGENTS.md", message: agentDrift.message },
806
- repairAction("generated", "akan agent install agents-md", agentDrift.hint, true),
807
- );
808
- const sysPaths = [...context.apps, ...context.libs].map((sys) => sys.path);
809
- const oversize = await AkanContextAnalyzer.#agentGuideOversize(workspace, sysPaths);
810
- if (oversize)
811
- diagnostics.push({ severity: "warning", code: "agent-guide-oversized", path: "AGENTS.md", message: oversize });
812
- for (const leftover of await AkanContextAnalyzer.#agentGuideLeftovers(workspace))
813
- diagnostics.push({ severity: "warning", code: "agent-guide-leftover", ...leftover });
814
- for (const leftover of await AkanContextAnalyzer.#configLeftovers(workspace, sysPaths))
815
- diagnostics.push({ severity: "warning", code: "config-leftover", ...leftover });
816
-
817
- for (const sys of [...context.apps, ...context.libs]) {
818
- for (const module of sys.modules) {
819
- const moduleShapeCommand = `akan repair module-shape --app ${sys.name} --module ${module.name}`;
820
- if (!module.abstract.exists)
821
- report(
822
- {
823
- severity: strict ? "error" : "warning",
824
- code: "module-abstract-missing",
825
- path: module.abstract.path,
826
- message: `${capitalize(module.kind)} module ${sys.name}:${module.name} should include ${module.abstract.path}`,
827
- },
828
- repairAction(
829
- "module-shape",
830
- moduleShapeCommand,
831
- "Create the missing module abstract or inspect required source files.",
832
- false,
833
- ),
834
- );
835
- const missingFiles = moduleShapeFiles(module).filter((filename) => !module.files.includes(filename));
836
- if (missingFiles.length)
837
- report(
838
- {
839
- severity: "error",
840
- code: "module-shape-invalid",
841
- path: module.path,
842
- message: `${capitalize(module.kind)} module ${sys.name}:${module.name} is missing required files: ${missingFiles.join(", ")}`,
843
- },
844
- repairAction("module-shape", moduleShapeCommand, "Review missing required module source files.", false),
845
- );
846
- if (module.kind !== "service" && module.files.includes(`${module.name}.dictionary.ts`)) {
847
- const constantPath = path.join(workspace.workspaceRoot, module.path, `${module.name}.constant.ts`);
848
- const dictionaryPath = path.join(workspace.workspaceRoot, module.path, `${module.name}.dictionary.ts`);
849
- const [constantContent, dictionaryContent] = await Promise.all([
850
- safeReadText(constantPath),
851
- safeReadText(dictionaryPath),
852
- ]);
853
- if (constantContent && dictionaryContent) {
854
- for (const fieldName of constantFieldNames(constantContent)) {
855
- if (new RegExp(`\\b${fieldName}\\s*:`).test(dictionaryContent)) continue;
856
- report(
857
- {
858
- severity: "warning",
859
- code: "dictionary-label-missing",
860
- path: `${module.path}/${module.name}.dictionary.ts`,
861
- message: `Dictionary labels for ${sys.name}:${module.name}.${fieldName} were not found.`,
862
- },
863
- repairAction(
864
- "dictionary",
865
- `akan repair dictionary --app ${sys.name} --module ${module.name}`,
866
- "Add missing dictionary labels for source constant fields.",
867
- false,
868
- ),
869
- );
870
- }
871
- }
872
- }
873
- }
874
- }
875
-
876
- //* Advisory only (warning): promoted to lint only if inline re-authoring actually recurs.
877
- for (const sys of [...context.apps, ...context.libs]) {
878
- const sources = await collectRecipeSources(path.join(workspace.workspaceRoot, sys.path, "ui"), "ui");
879
- if (sources.length === 0) continue;
880
- const recipes = scanRecipes(sources);
881
- const files: { path: string; content: string }[] = [];
882
- const glob = new Bun.Glob("**/*.tsx");
883
- for await (const abs of glob.scan({ cwd: path.join(workspace.workspaceRoot, sys.path), absolute: true })) {
884
- if (/[\\/](node_modules|\.akan|dist)[\\/]|[\\/]v1[\\/]/.test(abs) || /\.(test|spec)\.tsx$/.test(abs)) continue;
885
- files.push({
886
- path: abs,
887
- content: await Bun.file(abs)
888
- .text()
889
- .catch(() => ""),
890
- });
891
- }
892
- const duplicates = findInlineRecipeDuplicates(recipes, files);
893
- if (duplicates.length === 0) continue;
894
- const preview = duplicates
895
- .slice(0, 3)
896
- .map((duplicate) => `${path.relative(workspace.workspaceRoot, duplicate.path)}:${duplicate.line}`)
897
- .join(", ");
898
- diagnostics.push({
899
- severity: "warning",
900
- code: "recipe-inline-duplicate",
901
- path: path.join(sys.path, "ui/Recipe"),
902
- message: `${sys.name}: ${duplicates.length} inline className(s) re-author a recipe fingerprint (${preview}${duplicates.length > 3 ? ", …" : ""}) — consume the recipe instead.`,
903
- });
904
- }
905
-
906
- // Doctor never writes, so this is what catches a committed stale recipe index (lint and sync self-heal the tree).
907
- const scanNames = async (uiDirPath: string, basename?: string) =>
908
- new Set(scanRecipes(await collectRecipeSources(uiDirPath, "ui", basename)).map((info) => info.name));
909
- const declaredByImport = new Map<string, Set<string>>();
910
- declaredByImport.set("akanjs/ui", await scanNames(path.join(workspace.workspaceRoot, "pkgs/akanjs/ui"), "recipe"));
911
- for (const sys of [...context.apps, ...context.libs])
912
- declaredByImport.set(`@${sys.path}/ui`, await scanNames(path.join(workspace.workspaceRoot, sys.path, "ui")));
913
- // Section slice anchors the heading to a full line — the same string appears back-ticked in prose.
914
- const sectionOf = (content: string, heading: string) => {
915
- const match = new RegExp(`^${heading}$`, "m").exec(content);
916
- if (!match) return "";
917
- const section = content.slice(match.index);
918
- const sectionEnd = section.indexOf("\n## ", 1);
919
- return sectionEnd === -1 ? section : section.slice(0, sectionEnd);
920
- };
921
- // `Import from \`<path>\`:` groups with their `- \`name\`` items, so each name checks against its owner.
922
- const listedByImport = (body: string) => {
923
- const groups = new Map<string, Set<string>>();
924
- let current: Set<string> | null = null;
925
- for (const line of body.split("\n")) {
926
- const group = /^Import from `([^`]+)`:/.exec(line);
927
- if (group) {
928
- current = groups.get(group[1]) ?? new Set();
929
- groups.set(group[1], current);
930
- continue;
931
- }
932
- const item = /^- `([A-Za-z0-9_$]+)`/.exec(line);
933
- if (item && current) current.add(item[1]);
934
- else if (!item) current = null;
935
- }
936
- return groups;
937
- };
938
- const pushIndexDiagnostic = (indexPath: string, missing: string[], stale: string[], repairCommand: string) => {
939
- if (missing.length === 0 && stale.length === 0) return;
940
- const parts = [
941
- missing.length > 0 ? `${missing.length} declared but unlisted (${missing.slice(0, 5).join(", ")})` : "",
942
- stale.length > 0 ? `${stale.length} listed but gone (${stale.slice(0, 5).join(", ")})` : "",
943
- ].filter(Boolean);
944
- report(
945
- {
946
- severity: "error",
947
- code: "recipe-index-stale",
948
- path: indexPath,
949
- message: `${indexPath} recipe index is out of date — ${parts.join("; ")}. Agents read this list as authoritative.`,
950
- },
951
- repairAction("generated", repairCommand, "Regenerate the recipe index from the scanned recipes.", true),
952
- );
953
- };
954
- const frameworkDeclared = declaredByImport.get("akanjs/ui") ?? new Set<string>();
955
- if (frameworkDeclared.size > 0) {
956
- const agentsMd = await Bun.file(path.join(workspace.workspaceRoot, "AGENTS.md"))
957
- .text()
958
- .catch(() => "");
959
- const listed = listedByImport(sectionOf(agentsMd, "## Recipes")).get("akanjs/ui") ?? new Set<string>();
960
- pushIndexDiagnostic(
961
- "AGENTS.md",
962
- [...frameworkDeclared].filter((name) => !listed.has(name)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
963
- [...listed].filter((name) => !frameworkDeclared.has(name)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
964
- "akan agent install agents-md",
965
- );
966
- }
967
- for (const sys of [...context.apps, ...context.libs]) {
968
- const own = declaredByImport.get(`@${sys.path}/ui`) ?? new Set<string>();
969
- const scopeMd = await Bun.file(path.join(workspace.workspaceRoot, sys.path, "AGENTS.md"))
970
- .text()
971
- .catch(() => "");
972
- const groups = listedByImport(sectionOf(scopeMd, "## Recipes In Scope"));
973
- const ownListed = groups.get(`@${sys.path}/ui`) ?? new Set<string>();
974
- const missing = [...own].filter((name) => !ownListed.has(name)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
975
- // Every listed name — the scope's own and its dependency libs' — must still exist at its owner.
976
- const stale = [...groups.entries()]
977
- .flatMap(([importFrom, names]) =>
978
- [...names].filter((name) => !(declaredByImport.get(importFrom) ?? new Set()).has(name)),
979
- )
980
- .sort();
981
- pushIndexDiagnostic(`${sys.path}/AGENTS.md`, missing, stale, `akan sync ${sys.name}`);
982
- }
983
-
984
- const scopedDiagnostics = diagnostics.map((diagnostic) => ({
985
- ...diagnostic,
986
- scope: workflowPaths.length
987
- ? isWorkflowRelatedDiagnostic(diagnostic, workflowPaths)
988
- ? ("workflow" as const)
989
- : ("baseline" as const)
990
- : diagnostic.scope,
991
- context: workflowPaths.length ? { ...diagnostic.context, paths: workflowPaths } : diagnostic.context,
992
- }));
993
- const workflowDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "workflow");
994
- const baselineDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "baseline");
995
- return {
996
- schemaVersion: 1,
997
- repoName: context.repoName,
998
- root: context.root,
999
- strict,
1000
- status: scopedDiagnostics.some((diagnostic) => diagnostic.severity === "error") ? "failed" : "passed",
1001
- diagnostics: scopedDiagnostics,
1002
- generatedFiles: context.generatedFiles,
1003
- generatedFilesFreshness: await generatedFreshnessFromStates(workspace),
1004
- validationCommands: context.validationCommands,
1005
- repairActions,
1006
- ...(workflowPaths.length ? { baselineDiagnostics, workflowDiagnostics } : {}),
1007
- };
1008
- }
1009
-
1010
- static findModules(
1011
- context: AkanWorkspaceContext,
1012
- moduleName?: string | null,
1013
- { app = null }: { app?: string | null } = {},
1014
- ) {
1015
- const modules = [...context.apps, ...context.libs]
1016
- .filter((sys) => !app || sys.name === app)
1017
- .flatMap((sys) => sys.modules);
1018
- return moduleName
1019
- ? modules.filter((module) => module.name === moduleName || module.folderName === moduleName)
1020
- : modules;
1021
- }
1022
-
1023
- static renderMarkdown(context: AkanWorkspaceContext, { module: moduleName }: { module?: string | null } = {}) {
1024
- const lines = [`# Akan Workspace Context`, "", `- Repo: ${context.repoName}`, `- Root: ${context.root}`];
1025
- if (context.packageVersion) lines.push(`- Akan version: ${context.packageVersion}`);
1026
- lines.push("", "## Apps", ...context.apps.map((app) => `- ${app.name}: ${app.modules.length} module(s)`));
1027
- lines.push("", "## Libraries", ...context.libs.map((lib) => `- ${lib.name}: ${lib.modules.length} module(s)`));
1028
- lines.push(
1029
- "",
1030
- "## Packages",
1031
- ...context.pkgs.map((pkg) => `- ${pkg.name}${pkg.version ? ` (${pkg.version})` : ""}`),
1032
- );
1033
-
1034
- for (const app of context.apps) {
1035
- if (app.routeError) lines.push("", `## Routes: ${app.name}`, `- Not read: ${app.routeError}`);
1036
- else if (app.routes)
1037
- lines.push("", `## Routes: ${app.name}`, ...AkanContextAnalyzer.#routeLines(app.name, app.routes));
1038
- }
1039
-
1040
- const modules = AkanContextAnalyzer.findModules(context, moduleName);
1041
- lines.push("", "## Modules");
1042
- for (const module of modules) {
1043
- lines.push("", `### ${module.sysName}:${module.name} (${module.kind})`, `- Path: ${module.path}`);
1044
- lines.push(`- Abstract: ${module.abstract.exists ? module.abstract.path : "missing"}`);
1045
- if (module.abstract.exists && module.abstract.content) lines.push("", module.abstract.content.trim(), "");
1046
- else if (module.abstract.headings.length)
1047
- lines.push(`- Abstract headings: ${module.abstract.headings.join(", ")}`);
1048
- lines.push(`- Files: ${module.files.join(", ") || "none"}`);
1049
- }
1050
-
1051
- lines.push("", "## Validation", ...context.validationCommands.map((command) => `- \`${command}\``));
1052
- return `${lines.join("\n")}\n`;
1053
- }
1054
-
1055
- static readonly routeListLimit = 60;
1056
-
1057
- //? Past the limit the biggest top folders fold into one line each: a docs section alone would fill the context.
1058
- static #routeLines(appName: string, routes: AkanRouteContext[]) {
1059
- const folderOf = (route: AkanRouteContext) => route.file.split("/").slice(0, 4).join("/");
1060
- const groups = Map.groupBy(routes, folderOf);
1061
- const folded = new Set<string>();
1062
- let listed = routes.length;
1063
- for (const [folder, members] of [...groups].sort((a, b) => b[1].length - a[1].length)) {
1064
- if (listed <= AkanContextAnalyzer.routeListLimit) break;
1065
- folded.add(folder);
1066
- listed -= members.length;
1067
- }
1068
- const lines = [`Paths omit the \`/:lang\` prefix; \`akan preview ${appName} <path>\` opens one.`];
1069
- for (const route of routes) {
1070
- if (folded.has(folderOf(route))) continue;
1071
- const search = route.search.length ? ` ?${route.search.join("&")}` : "";
1072
- const marks = `${route.guarded ? " (guarded)" : ""}${route.devOnly ? " (dev only)" : ""}`;
1073
- lines.push(`- ${route.path}${search}${marks} — ${route.file}`);
1074
- }
1075
- for (const folder of folded) {
1076
- const members = groups.get(folder) ?? [];
1077
- const examples = members.slice(0, 3).map((route) => route.path);
1078
- lines.push(
1079
- `- ${folder}/: ${members.length} routes folded (${examples.join(", ")}, …); \`--format json\` lists every route`,
1080
- );
1081
- }
1082
- return lines;
1083
- }
1084
- }