@akanjs/devkit 3.2.0-rc.9 → 3.3.0-rc.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 +57 -516
  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,143 +1,46 @@
1
- import path from "node:path";
2
- import { Logger, RestartSchedule } from "akanjs/common";
3
- import type { BuilderMessage, BuilderMetrics, BuildPhase, ChangeBatch, DevBuildStatus } from "akanjs/server";
1
+ import { Logger } from "akanjs/common";
2
+ import type { BuilderMessage } from "akanjs/server";
4
3
  import type { App } from "../commandDecorators";
5
- import { createTunnel } from "../createTunnel";
6
4
  import { WorkspaceExecutor } from "../executors";
7
- // Not via `../frontendBuild`: that barrel loads typescript and tailwind, which a suspended dev host must not hold.
8
- import { HmrWatcher } from "../frontendBuild/hmrWatcher";
9
- import { WatchRootResolver } from "../frontendBuild/watchRootResolver";
10
- import { type DevStdioMode, IncrementalBuilderHost } from "../incrementalBuilder";
11
- import { BuilderRequestRouter } from "../incrementalBuilder/builderRequestRouter";
5
+ import type { DevStdioMode } from "../incrementalBuilder";
6
+ import { createTunnel } from "../tunnel/createTunnel";
12
7
  import { BackendImportGraph } from "./BackendImportGraph";
8
+ import { BuilderGap } from "./builderGap";
9
+ import { BuilderRequestRelay } from "./builderRequestRelay";
10
+ import { BuilderRssRecycler } from "./builderRssRecycler";
11
+ import { DevBackend } from "./devBackend";
13
12
  import { DevBootLatch } from "./devBootLatch";
13
+ import { DevBuilder } from "./devBuilder";
14
+ import { DevBuildStatusBoard } from "./devBuildStatusBoard";
14
15
  import {
15
- type BackendLifecycleState,
16
- type BackendRestartReason,
17
- BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS,
18
- backendRecoveryPolicy,
19
- backendRestartReasonFromMessage,
20
- buildStatusReplaySequence,
21
- createBackendBuildStatus,
22
16
  type DevHostEvent,
23
17
  type DevHostState,
24
- decideBuilderRssRecycle,
25
- decideBuilderRssSettle,
26
- decideIdleSuspend,
27
18
  devHostStateOf,
28
- filesChangedSince,
29
- hasAnyBuildFailure,
30
- hasBuildFailureForGeneration,
31
- isLegacyBackendFallbackFile,
32
- isRssCeilingUnreachable,
33
- mergeBackendRestartReasons,
34
- mergeInvalidateMessages,
35
- normalizeBackendReportedGeneration,
36
19
  redisTunnelPolicy,
37
- resolveIdleSuspendMs,
38
- type SourceFingerprints,
39
- shouldHoldForReturningBuilder,
40
- shouldKeepBuildFailure,
41
- shouldMarkBuildPhaseRecovered,
42
- shouldQueueBuildStatusReplay,
43
- shouldRefreshConfigOnIdleWake,
44
- shouldRelayRecycledFrontendState,
45
- shouldReplaceLastGoodMessage,
46
- shouldRestartBackendByDevPlan,
47
- shouldRestartBuilderByDevPlan,
48
- shouldRestartDevHostByDevPlan,
49
- shouldWarnBuilderRssCeilingTight,
50
20
  UNAVAILABLE_REDIS_HOST,
51
21
  } from "./devHostPolicy";
52
-
53
- const backendMsgTypeSet = new Set<BuilderMessage["type"]>(["build-route", "build-csr", "build-graph"]);
54
-
55
- const asMib = (bytes: number) => Math.round(bytes / 1024 / 1024);
56
-
57
- const BACKEND_RESTART_DEBOUNCE_MS = 120;
58
-
59
- // Above the gateway's ~5s child-shutdown wait: a gateway SIGKILLed mid-shutdown strands orphan replicas.
60
- const BACKEND_GRACEFUL_TIMEOUT_MS = 8_000;
61
-
62
- const BACKEND_STDERR_TAIL_LIMIT = 40;
63
-
64
- const BUILDER_READY_TIMEOUT_MS = 150000;
65
-
66
- const BUILDER_START_MAX_ATTEMPTS = 3;
67
-
68
- // Recycling mid-burst of saves would drop watcher events still on their way to the builder.
69
- const BUILDER_RSS_RECYCLE_QUIET_MS = 750;
70
-
71
- // Linux returns about half of the bundler arenas after ~10-15s idle (macOS none), so re-read the peak before recycling.
72
- const BUILDER_RSS_SETTLE_MS = 20_000;
73
-
74
- const PS_RSS_TIMEOUT_MS = 2_000;
75
-
76
- interface LastGoodFrontendState {
77
- pages?: Extract<BuilderMessage, { type: "pages-updated" }>;
78
- css?: Extract<BuilderMessage, { type: "css-updated" }>;
79
- }
22
+ import { DevIdleSuspend } from "./devIdleSuspend";
23
+ import { DevRecycler } from "./devRecycler";
24
+ import { ProcessRss } from "./processRss";
80
25
 
81
26
  export class AkanAppHost {
82
- logger = new Logger("AkanAppHost");
27
+ readonly logger = new Logger("AkanAppHost");
83
28
  readonly stdio: DevStdioMode;
84
29
  readonly env: Record<string, string>;
85
30
  readonly #onDevEvent: ((event: DevHostEvent) => void) | null;
86
31
  #lastDevState: DevHostState | null = null;
87
32
  readonly #bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
88
- #backend: Bun.Subprocess<"ignore", "inherit" | "pipe", "inherit" | "pipe"> | null = null;
89
- #builder: IncrementalBuilderHost | null = null;
90
- //? Outlives the builder host, which idle wake and recovery replace; a config or metadata restart clears it.
91
- #patcherOff = false;
92
- #backendReady = false;
93
- #plannedBackendStops = new WeakSet<Bun.Subprocess<"ignore", "inherit", "inherit">>();
94
- #restartTimer: ReturnType<typeof setTimeout> | null = null;
95
- readonly #backendRecovery = new RestartSchedule(backendRecoveryPolicy);
96
- #backendGaveUp = false;
97
- #backendLifecycleState: BackendLifecycleState = "stopped";
98
- #pendingRestartReason: BackendRestartReason | null = null;
99
- //? One replacement at a time: `#stopBackend` clears `#backend` only once the old process exits, so a second restart
100
- //? inside that wait signals the same pid and spawns a second backend, and the one the host stops tracking keeps the port.
101
- #backendRestart: Promise<void> | null = null;
102
- #pendingRecycle: {
103
- message: Extract<BuilderMessage, { type: "invalidate" }>;
104
- refreshConfig: boolean;
105
- failed?: boolean;
106
- failedGeneration?: number;
107
- } | null = null;
108
- //? A restart that failed after its change applied (the builder or backend did not come up): the builder's return is
109
- //? its recovery, reported past the failure's generation so the scan overlay clears.
110
- #restartFailedAfterApply: number | null = null;
111
33
  #stopping = false;
112
- //? The builder is the file watcher, so unlike the backend its recovery never gives up; it only backs off.
113
- readonly #builderRecovery = new RestartSchedule({ min: 2_000, max: 60_000 });
114
- #abandonBuilderStart: ((error: Error) => void) | null = null;
115
- #backendStartStatus: { generation?: number; files: string[] } | null = null;
116
- #backendBuildStatusGeneration = 0;
117
- #backendStderrTail: string[] = [];
118
- #lastGoodFrontend: LastGoodFrontendState = {};
119
- #rssRecycleTimer: ReturnType<typeof setTimeout> | null = null;
120
- #rssRecycleReason: string | null = null;
121
- #lastRssRecycleAtMono: number | null = null;
122
- #rssCeilingTightReports = 0;
123
- #rssCeilingTightWarned = false;
124
- #rssSettleToken = 0;
125
- #rssRecycleOver: { rssBytes: number; ceilingBytes: number } | null = null;
126
- #rssCeilingAbandoned = false;
127
- #buildStatusByPhase = new Map<BuildPhase, DevBuildStatus>();
128
- #pendingBuildStatusReplay: DevBuildStatus[] = [];
129
34
  #builderMessageQueue: Promise<void> = Promise.resolve();
130
- #backendGraph: BackendImportGraph;
131
- #idleSuspendTimer: ReturnType<typeof setTimeout> | null = null;
132
- #suspended: boolean = false;
133
- #waking: boolean = false;
134
- #wokeAtMono: number | null = null;
135
- #idleWatcher: HmrWatcher | null = null;
136
- #suspendedChanges: ChangeBatch | null = null;
137
- #builderGapStamp: Promise<SourceFingerprints | null> | null = null;
138
- #pendingBuilderMessages: BuilderMessage[] = [];
139
- readonly #builderRequests = new BuilderRequestRouter();
140
- #builderGeneration = 0;
35
+ readonly #backendGraph: BackendImportGraph;
36
+ readonly #statuses: DevBuildStatusBoard;
37
+ readonly #backend: DevBackend;
38
+ readonly #gap: BuilderGap;
39
+ readonly #requests: BuilderRequestRelay;
40
+ readonly #rss: BuilderRssRecycler;
41
+ readonly #builder: DevBuilder;
42
+ readonly #idle: DevIdleSuspend;
43
+ readonly #recycler: DevRecycler;
141
44
  constructor(
142
45
  private readonly app: App,
143
46
  {
@@ -150,6 +53,97 @@ export class AkanAppHost {
150
53
  this.stdio = stdio;
151
54
  this.#onDevEvent = onDevEvent ?? null;
152
55
  this.#backendGraph = new BackendImportGraph(app, this.logger);
56
+ const { logger } = this;
57
+ const graph = this.#backendGraph;
58
+ const isStopping = () => this.#stopping;
59
+ const statuses = new DevBuildStatusBoard(logger);
60
+ this.#statuses = statuses;
61
+ this.#backend = new DevBackend(
62
+ app,
63
+ { env, stdio, logger, statuses, graph },
64
+ {
65
+ isStopping,
66
+ emit: (state, detail) => this.#emitDevEvent(state, detail),
67
+ beforeSpawn: () => {
68
+ // Before the spawn: the new backend numbers its requests from 1 again, so old answers must not reach it.
69
+ this.#requests.startGeneration();
70
+ this.#requests.discard("the backend restarted while the builder was away");
71
+ },
72
+ toBuilder: (message) => this.#requests.send(message),
73
+ },
74
+ );
75
+ this.#gap = new BuilderGap({ graph, backend: this.#backend, logger });
76
+ this.#requests = new BuilderRequestRelay(
77
+ { logger, env },
78
+ {
79
+ builder: () => this.#builder.current,
80
+ toBackend: (message) => this.#backend.send(message),
81
+ markActivity: () => this.#idle.markActivity(),
82
+ away: () => this.#idle.away,
83
+ wake: (reason) => void this.#idle.wake(reason),
84
+ },
85
+ );
86
+ this.#rss = new BuilderRssRecycler(
87
+ { logger, statuses },
88
+ {
89
+ builder: () => this.#builder.current,
90
+ away: () => this.#idle.away,
91
+ restartQueued: () => this.#recycler.pending || this.#backend.restartScheduled,
92
+ onRecycle: () => this.#gap.open("builder recycle"),
93
+ },
94
+ );
95
+ this.#builder = new DevBuilder(
96
+ app,
97
+ { env, stdio, logger },
98
+ {
99
+ isStopping,
100
+ onMessage: (message) => this.#enqueueBuilderMessage(message),
101
+ onAway: () => this.#gap.open("builder replacement"),
102
+ onReady: () => this.#requests.flush(),
103
+ onRestartReady: () => {
104
+ this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
105
+ this.#backend.replay();
106
+ this.#requests.flush();
107
+ void this.#gap.restartBackendForChanges();
108
+ void this.#rss.checkRecycledFloor();
109
+ },
110
+ onStartFailed: () => this.#requests.fail("builder failed to start"),
111
+ onStop: () => this.#rss.cancel(),
112
+ onRecovered: (reason) => this.#recycler.builderRecovered(reason),
113
+ },
114
+ );
115
+ this.#idle = new DevIdleSuspend(
116
+ app,
117
+ { logger },
118
+ {
119
+ readiness: () => ({
120
+ builderReady: this.#builder.current?.status === "ready",
121
+ backendReady: this.#backend.ready,
122
+ buildFailed: this.#statuses.failing,
123
+ restartPending: this.#restartPending,
124
+ }),
125
+ release: (detail) => {
126
+ this.#emitDevEvent("suspended", detail);
127
+ this.#builder.stop();
128
+ this.#gap.open("idle suspend");
129
+ },
130
+ wake: (batch) => this.#recycler.applyIdleWake(batch),
131
+ wakeFailed: (files) => this.#builder.scheduleRecovery({ files }),
132
+ flushHeld: () => this.#requests.flush(),
133
+ awake: () => this.#emitDevEvent(devHostStateOf(this.#backend.lifecycleState, this.#backend.gaveUp)),
134
+ },
135
+ );
136
+ this.#recycler = new DevRecycler(app, {
137
+ env,
138
+ logger,
139
+ isStopping,
140
+ graph,
141
+ statuses,
142
+ backend: this.#backend,
143
+ builder: this.#builder,
144
+ gap: this.#gap,
145
+ rss: this.#rss,
146
+ });
153
147
  }
154
148
  #emitDevEvent(state: DevHostState, detail?: string) {
155
149
  if (!this.#onDevEvent || state === this.#lastDevState) return;
@@ -158,41 +152,35 @@ export class AkanAppHost {
158
152
  if (state === "ready") this.#bootLatch.ready();
159
153
  }
160
154
  async start() {
161
- if (this.#backend) await this.#stopBackend();
162
- if (this.#builder) this.#stopBuilder();
155
+ if (this.#backend.running) await this.#backend.stop();
156
+ if (this.#builder.current) this.#builder.stop();
163
157
  const [redisHost] = await Promise.all([
164
158
  this.#prepareDatabase("redis"),
165
159
  this.#backendGraph.refresh(),
166
- this.#startBuilder(),
160
+ this.#builder.start(),
167
161
  ]);
168
162
  Object.assign(this.env, { REDIS_HOST: redisHost });
169
- this.#startBackend();
170
- this.#armIdleSuspend();
163
+ this.#backend.start();
164
+ this.#idle.arm();
171
165
  return this;
172
166
  }
173
167
  async stop() {
174
168
  //? Nothing reapplies once it stops: a pages ok received meanwhile would bring children back after it.
175
169
  this.#stopping = true;
176
- this.#pendingRecycle = null;
177
- this.#cancelIdleSuspend();
178
- this.#stopIdleWatcher();
179
- this.#clearRestartTimers();
170
+ this.#recycler.drop();
171
+ this.#idle.stop();
172
+ this.#backend.cancelTimers();
173
+ this.#builder.cancelRecovery();
180
174
  //? A stopped builder sends no exit: a start waiting for its ready would sit out the ready timeout, then retry.
181
- this.#abandonBuilderStart?.(new Error("dev server stopped before the builder was ready"));
182
- this.#pendingRestartReason = null;
175
+ this.#builder.abandonStart(new Error("dev server stopped before the builder was ready"));
176
+ this.#backend.dropPendingRestart();
183
177
  // Before the backend goes away, while it can still receive the answer.
184
- this.#failPendingBuilderMessages("dev server is shutting down");
185
- await this.#backendRestart;
186
- await this.#stopBackend();
187
- this.#stopBuilder();
178
+ this.#requests.fail("dev server is shutting down");
179
+ await this.#backend.restarting;
180
+ await this.#backend.stop();
181
+ this.#builder.stop();
188
182
  return this;
189
183
  }
190
- #clearRestartTimers() {
191
- if (this.#restartTimer) clearTimeout(this.#restartTimer);
192
- this.#restartTimer = null;
193
- this.#backendRecovery.cancel();
194
- this.#builderRecovery.cancel();
195
- }
196
184
  kill() {
197
185
  void this.stop();
198
186
  }
@@ -211,251 +199,6 @@ export class AkanAppHost {
211
199
  return UNAVAILABLE_REDIS_HOST;
212
200
  }
213
201
  }
214
- #startBackend(startStatus: { generation?: number; files: string[] } | null = null) {
215
- if (this.#stopping) return;
216
- if (this.#backend) {
217
- this.logger.warn(`backend pid=${this.#backend.pid} is still running; not starting a second one`);
218
- return;
219
- }
220
- // Before the spawn: the new backend numbers its requests from 1 again, so old answers must not reach it.
221
- this.#builderRequests.startGeneration();
222
- this.#discardPendingBuilderMessages("the backend restarted while the builder was away");
223
- this.#backendStartStatus = startStatus;
224
- this.#backendGaveUp = false;
225
- this.#setBackendLifecycleState("starting");
226
- this.#backendReady = false;
227
- this.#backendStderrTail = [];
228
- const backend = Bun.spawn(["bun", `apps/${this.app.name}/main.ts`], {
229
- cwd: this.app.workspace.workspaceRoot,
230
- stdio: this.stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
231
- env: this.env,
232
- ipc: (msg: BuilderMessage) => {
233
- if (!msg || typeof msg !== "object") return;
234
- if (msg.type === "backend-ready") {
235
- this.#backendReady = true;
236
- this.#backendRecovery.reset();
237
- this.#setBackendLifecycleState("ready", `pid=${msg.pid}`);
238
- this.#recordBackendReadyStatus();
239
- this.logger.verbose(`backend ready pid=${msg.pid}`);
240
- this.#forgetRouteBuildStatus();
241
- this.#replayBuilderState();
242
- return;
243
- }
244
- if (msg.type === "build-status") {
245
- // The gateway reports replica boot failures (crash loops, port conflicts) as build-status.
246
- const status = this.#recordBackendBuildStatus({
247
- generation: normalizeBackendReportedGeneration(msg.data.generation),
248
- ok: msg.data.ok,
249
- files: msg.data.files,
250
- message: msg.data.message,
251
- });
252
- this.#sendOrQueueBuildStatus(status);
253
- //? A replica crash loop leaves the gateway up, waiting for an edit: no exit reaches the host's own give-up.
254
- if (!status.ok) this.#emitDevEvent("failed", status.message);
255
- return;
256
- }
257
- if (backendMsgTypeSet.has(msg.type)) this.#sendToBuilder(msg);
258
- },
259
- serialization: "advanced",
260
- onExit: () => {
261
- this.#backendReady = false;
262
- if (this.#backend === backend) this.#backend = null;
263
- if (this.#plannedBackendStops.has(backend)) {
264
- this.#plannedBackendStops.delete(backend);
265
- return;
266
- }
267
- this.#scheduleBackendRecovery("backend-exit");
268
- },
269
- });
270
- this.#backend = backend;
271
- this.logger.verbose(`backend spawned pid=${backend.pid}`);
272
- if (this.stdio === "pipe") {
273
- // Undrained pipes swallow runtime errors and leave the crash-loop stderr tail empty.
274
- void this.#forwardBackendStream(backend.stderr as unknown as ReadableStream<Uint8Array> | undefined, "stderr");
275
- void this.#forwardBackendStream(backend.stdout as unknown as ReadableStream<Uint8Array> | undefined, "stdout");
276
- }
277
- }
278
- #recordBackendStderr(chunk: string) {
279
- const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
280
- if (lines.length === 0) return;
281
- this.#backendStderrTail.push(...lines);
282
- if (this.#backendStderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
283
- this.#backendStderrTail.splice(0, this.#backendStderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
284
- }
285
- }
286
- // Verbatim, not re-logged: a level floor would swallow runtime output and re-rendering doubles the timestamp.
287
- async #forwardBackendStream(stream: ReadableStream<Uint8Array> | undefined | null, kind: "stdout" | "stderr") {
288
- if (!stream) return;
289
- const decoder = new TextDecoder();
290
- try {
291
- for await (const chunk of stream) {
292
- const text = decoder.decode(chunk, { stream: true });
293
- if (!text) continue;
294
- if (kind === "stderr") {
295
- this.#recordBackendStderr(text);
296
- process.stderr.write(text);
297
- } else process.stdout.write(text);
298
- }
299
- } catch {
300
- // The stream closes when the backend exits; nothing further to surface here.
301
- }
302
- }
303
- #nextBackendBuildStatusGeneration(generation?: number): number {
304
- if (typeof generation === "number") {
305
- this.#backendBuildStatusGeneration = Math.max(this.#backendBuildStatusGeneration, generation);
306
- return generation;
307
- }
308
- this.#backendBuildStatusGeneration += 1;
309
- return this.#backendBuildStatusGeneration;
310
- }
311
- #recordBackendBuildStatus({
312
- generation,
313
- ok,
314
- files,
315
- message,
316
- }: {
317
- generation?: number;
318
- ok: boolean;
319
- files?: string[];
320
- message?: string;
321
- }): DevBuildStatus {
322
- const status = createBackendBuildStatus({
323
- generation: this.#nextBackendBuildStatusGeneration(generation),
324
- ok,
325
- files,
326
- message,
327
- });
328
- this.#recordBuildStatus(status);
329
- return status;
330
- }
331
- #recordBackendReadyStatus(): void {
332
- const previous = this.#buildStatusByPhase.get("backend");
333
- const startStatus = this.#backendStartStatus;
334
- if (startStatus || previous?.ok === false) {
335
- const status = this.#recordBackendBuildStatus({
336
- generation: startStatus?.generation ?? previous?.generation,
337
- ok: true,
338
- files: startStatus?.files ?? previous?.files ?? [],
339
- message: "Backend ready",
340
- });
341
- this.#sendOrQueueBuildStatus(status);
342
- }
343
- this.#backendStartStatus = null;
344
- }
345
- #setBackendLifecycleState(next: BackendLifecycleState, detail?: string): void {
346
- if (this.#backendLifecycleState === next && !detail) return;
347
- const prev = this.#backendLifecycleState;
348
- this.#backendLifecycleState = next;
349
- this.logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
350
- this.#emitDevEvent(devHostStateOf(next, this.#backendGaveUp), detail);
351
- }
352
- #sendToBackend(message: BuilderMessage) {
353
- if (!this.#backend || !this.#backendReady) {
354
- if (message.type === "css-updated" || message.type === "pages-updated" || message.type === "build-status") {
355
- this.logger.verbose(`backend is not ready; will replay ${message.type}`);
356
- return;
357
- }
358
- if (message.type !== "builder-ready") this.logger.warn(`backend is not ready; dropping ${message.type}`);
359
- return;
360
- }
361
- try {
362
- this.#backend.send(message);
363
- } catch (err) {
364
- this.logger.warn(
365
- `failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`,
366
- );
367
- }
368
- }
369
- async #stopBackend() {
370
- if (!this.#backend) return;
371
- const backend = this.#backend;
372
- this.#plannedBackendStops.add(backend);
373
- this.#backendReady = false;
374
- this.#setBackendLifecycleState("stopping", `pid=${backend.pid}`);
375
- this.logger.verbose(`stopping backend pid=${backend.pid}`);
376
- try {
377
- backend.kill("SIGTERM");
378
- const timeout = new Promise<"timeout">((resolve) =>
379
- setTimeout(() => resolve("timeout"), BACKEND_GRACEFUL_TIMEOUT_MS),
380
- );
381
- const result = await Promise.race([backend.exited, timeout]);
382
- if (result === "timeout") {
383
- this.logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
384
- backend.kill("SIGKILL");
385
- await backend.exited.catch(() => undefined);
386
- }
387
- } finally {
388
- if (this.#backend === backend) this.#backend = null;
389
- this.#setBackendLifecycleState("stopped", `pid=${backend.pid}`);
390
- }
391
- }
392
- #scheduleBackendRestart(reason: BackendRestartReason) {
393
- this.#pendingRestartReason = mergeBackendRestartReasons(this.#pendingRestartReason, reason);
394
- const pending = this.#pendingRestartReason;
395
- this.#setBackendLifecycleState(
396
- "restart-pending",
397
- `generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`,
398
- );
399
- this.#backendRecovery.cancel();
400
- if (this.#restartTimer) clearTimeout(this.#restartTimer);
401
- this.#restartTimer = setTimeout(() => {
402
- this.#restartTimer = null;
403
- this.#backendRestart ??= this.#drainBackendRestarts().finally(() => {
404
- this.#backendRestart = null;
405
- });
406
- }, BACKEND_RESTART_DEBOUNCE_MS);
407
- }
408
- //? A reason that arrived during a restart runs after it; one whose debounce is still pending waits for its timer.
409
- async #drainBackendRestarts() {
410
- while (this.#pendingRestartReason && !this.#restartTimer && !this.#stopping) {
411
- const next = this.#pendingRestartReason;
412
- this.#pendingRestartReason = null;
413
- await this.#restartBackend(next);
414
- }
415
- }
416
- async #restartBackend(reason: BackendRestartReason) {
417
- this.logger.verbose(
418
- `[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`,
419
- );
420
- this.#backendRecovery.reset();
421
- await Promise.all([this.#stopBackend(), this.#backendGraph.refresh()]);
422
- this.#startBackend({ generation: reason.generation, files: reason.files });
423
- }
424
- #scheduleBackendRecovery(reason: string) {
425
- if (this.#backendRecovery.pending || this.#backend) return;
426
- if (this.#backendRecovery.exhausted) {
427
- const message = `Backend exited ${this.#backendRecovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
428
- this.#backendGaveUp = true;
429
- this.#setBackendLifecycleState("stopped", `gave up after ${this.#backendRecovery.attempts} recovery attempts`);
430
- this.logger.error(`[backend-recovery] ${message}`);
431
- if (this.#backendStderrTail.length > 0) {
432
- this.logger.error(`[backend-recovery] recent backend stderr:\n${this.#backendStderrTail.join("\n")}`);
433
- }
434
- const abandonedStatus = this.#recordBackendBuildStatus({ ok: false, files: [], message });
435
- this.#sendOrQueueBuildStatus(abandonedStatus);
436
- return;
437
- }
438
- this.#setBackendLifecycleState("recovering", reason);
439
- const delay = this.#backendRecovery.next();
440
- const failureStatus = this.#recordBackendBuildStatus({
441
- ok: false,
442
- files: [],
443
- message: `Backend exited unexpectedly (${reason}); restarting in ${delay}ms`,
444
- });
445
- this.#sendOrQueueBuildStatus(failureStatus);
446
- this.logger.warn(
447
- `[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#backendRecovery.attempts})`,
448
- );
449
- if (this.#backendStderrTail.length > 0) {
450
- this.logger.warn(`[backend-recovery] recent backend stderr:\n${this.#backendStderrTail.join("\n")}`);
451
- }
452
- this.#backendRecovery.arm(delay, () => {
453
- if (this.#backend) return;
454
- void this.#backendGraph.refresh().finally(() => {
455
- if (!this.#backend) this.#startBackend({ generation: failureStatus.generation, files: failureStatus.files });
456
- });
457
- });
458
- }
459
202
  #enqueueBuilderMessage(message: BuilderMessage) {
460
203
  this.#builderMessageQueue = this.#builderMessageQueue
461
204
  .then(() => this.#handleBuilderMessage(message))
@@ -465,17 +208,17 @@ export class AkanAppHost {
465
208
  }
466
209
  async #handleBuilderMessage(message: BuilderMessage) {
467
210
  if (this.#stopping) return;
468
- this.#markDevActivity();
469
- this.#trackBuilderGeneration(message);
211
+ this.#idle.markActivity();
212
+ this.#builder.trackGeneration(message);
470
213
  if (message.type === "build-status") {
471
- this.#recordBuildStatus(message.data);
472
- this.#sendOrQueueBuildStatus(message.data);
473
- this.#reviveBackendAfterGreenBuild(message.data);
474
- await this.#resumeFailedRecycle(message.data);
214
+ this.#statuses.record(message.data);
215
+ this.#backend.sendOrQueueStatus(message.data);
216
+ this.#backend.reviveAfterGreenBuild(message.data);
217
+ await this.#recycler.resumeFailed(message.data);
475
218
  return;
476
219
  }
477
220
  if (message.type === "builder-metrics") {
478
- this.#handleBuilderMetrics(message.data);
221
+ this.#rss.handleMetrics(message.data);
479
222
  return;
480
223
  }
481
224
  if (message.type === "boot-armed") {
@@ -485,846 +228,33 @@ export class AkanAppHost {
485
228
  }
486
229
  if (message.type === "pages-updated" || message.type === "css-updated") {
487
230
  const recycled = message.data.reason === "builder-recycle";
488
- if (recycled && !this.#shouldRelayRecycledState(message)) return;
489
- this.#recordLastGood(message, { supersede: recycled });
231
+ if (recycled && !this.#statuses.shouldRelayRecycled(message)) return;
232
+ this.#statuses.recordLastGood(message, { supersede: recycled });
490
233
  }
491
234
  if (message.type === "invalidate") {
492
- await this.#handleInvalidate(message);
235
+ await this.#recycler.handleInvalidate(message);
493
236
  return;
494
237
  }
495
238
  if (message.type === "build-route-res" || message.type === "build-csr-res" || message.type === "build-graph-res") {
496
- const answer = this.#builderRequests.settle(message);
239
+ const answer = this.#requests.settle(message);
497
240
  if (!answer) {
498
241
  this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
499
242
  return;
500
243
  }
501
- this.#sendToBackend(answer);
244
+ this.#backend.send(answer);
502
245
  return;
503
246
  }
504
- this.#sendToBackend(message);
505
- }
506
- // In `env`, which every builder spawn re-reads: a replacement (recycled, crashed, restarted) continues from here.
507
- #trackBuilderGeneration(message: BuilderMessage): void {
508
- const generation = AkanAppHost.#builderGenerationOf(message);
509
- if (generation === undefined || generation <= this.#builderGeneration) return;
510
- this.#builderGeneration = generation;
511
- Object.assign(this.env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
512
- }
513
- // Not `csr-updated` / `ssr-updated`: their generation is the registry's.
514
- static #builderGenerationOf(message: BuilderMessage): number | undefined {
515
- if (message.type === "invalidate") return message.generation;
516
- if (message.type === "build-status" || message.type === "builder-metrics") return message.data.generation;
517
- if (message.type === "pages-updated" || message.type === "css-updated") return message.data.generation;
518
- return undefined;
519
- }
520
- // The backend reads `base-artifact.json` once, so a recycled builder re-announces it; unchanged hashes are dropped.
521
- #shouldRelayRecycledState(
522
- message: Extract<BuilderMessage, { type: "pages-updated" }> | Extract<BuilderMessage, { type: "css-updated" }>,
523
- ): boolean {
524
- const current = message.type === "pages-updated" ? this.#lastGoodFrontend.pages : this.#lastGoodFrontend.css;
525
- if (shouldRelayRecycledFrontendState(current, message)) {
526
- this.logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
527
- return true;
528
- }
529
- this.logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
530
- return false;
247
+ this.#backend.send(message);
531
248
  }
532
- #handleBuilderMetrics(metrics: BuilderMetrics): void {
533
- if (this.#rssCeilingAbandoned) return;
534
- const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
535
- const decision = decideBuilderRssRecycle({
536
- rssBytes: metrics.rssBytes,
537
- ceilingBytes,
538
- buildFailed: hasBuildFailureForGeneration(this.#buildStatusByPhase, metrics.generation),
539
- msSinceLastRecycle: this.#lastRssRecycleAtMono === null ? null : performance.now() - this.#lastRssRecycleAtMono,
540
- });
541
- if (decision === "below-ceiling") {
542
- this.#rssCeilingTightReports = 0;
543
- return;
544
- }
545
- if (decision === "unbounded") return;
546
- if (decision === "build-failed") {
547
- this.logger.verbose(
548
- `[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`,
549
- );
550
- return;
551
- }
552
- if (decision === "too-soon") {
553
- this.#rssCeilingTightReports += 1;
554
- if (this.#rssCeilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#rssCeilingTightReports)) return;
555
- this.#rssCeilingTightWarned = true;
556
- // Warn only: the per-interval recycle is the one bound between the bundler's arenas and the sandbox limit.
557
- this.logger.warn(
558
- `[builder-recycle] the builder is back at ${asMib(metrics.rssBytes)}MiB within ${Math.round(BUILDER_MIN_RSS_RECYCLE_INTERVAL_MS / 1000)}s of a recycle, so the ${asMib(ceilingBytes ?? 0)}MiB ceiling costs about one boot build per interval while you keep building. Raise AKAN_BUILDER_MAX_RSS_MB if that trade is wrong for this app, or set it to 0 to leave the builder unbounded.`,
559
- );
560
- return;
561
- }
562
- this.#armRssRecycle(
563
- `rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`,
564
- { rssBytes: metrics.rssBytes, ceilingBytes: ceilingBytes ?? 0 },
565
- );
566
- }
567
- // Read from the OS at ready: a metrics report arrives only after a build, measuring the work, not the floor.
568
- async #checkRecycledBuilderFloor(): Promise<void> {
569
- if (this.#rssCeilingAbandoned || this.#lastRssRecycleAtMono === null) return;
570
- const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
571
- const pid = this.#builder?.pid;
572
- if (!ceilingBytes || !pid) return;
573
- const freshRssBytes = await AkanAppHost.readProcessRssBytes(pid);
574
- if (!isRssCeilingUnreachable(freshRssBytes, ceilingBytes)) return;
575
- this.#rssCeilingAbandoned = true;
576
- this.logger.error(
577
- `[builder-recycle] a freshly recycled builder is already at ${asMib(freshRssBytes ?? 0)}MiB with nothing built on demand, so the ${asMib(ceilingBytes)}MiB ceiling cannot be met for this app; no longer enforcing it this session. Raise AKAN_BUILDER_MAX_RSS_MB, or set it to 0 to leave the builder unbounded.`,
578
- );
579
- }
580
- #armRssRecycle(reason: string, over?: { rssBytes: number; ceilingBytes: number }): void {
581
- if (this.#rssRecycleReason !== reason)
582
- this.logger.verbose(`[builder-recycle] armed (${reason}); replacing the builder once it stays quiet`);
583
- this.#rssRecycleReason = reason;
584
- // A field, not the closure: `#handleInvalidate` re-arms with the reason alone and must keep the sample.
585
- if (over) this.#rssRecycleOver = over;
586
- if (this.#rssRecycleTimer) clearTimeout(this.#rssRecycleTimer);
587
- this.#rssRecycleTimer = setTimeout(() => {
588
- this.#rssRecycleTimer = null;
589
- const pendingReason = this.#rssRecycleReason;
590
- const pendingOver = this.#rssRecycleOver;
591
- this.#rssRecycleReason = null;
592
- this.#rssRecycleOver = null;
593
- if (!pendingReason) return;
594
- if (!pendingOver) {
595
- this.#recycleBuilderForRss(pendingReason);
596
- return;
597
- }
598
- void this.#recycleBuilderForRssWhenStillOver(pendingReason, pendingOver);
599
- }, BUILDER_RSS_RECYCLE_QUIET_MS);
600
- }
601
- async #recycleBuilderForRssWhenStillOver(
602
- reason: string,
603
- { rssBytes, ceilingBytes }: { rssBytes: number; ceilingBytes: number },
604
- ): Promise<void> {
605
- if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
606
- this.#recycleBuilderForRss(reason);
607
- return;
608
- }
609
- const pid = this.#builder?.pid;
610
- if (!pid) {
611
- this.#recycleBuilderForRss(reason);
612
- return;
613
- }
614
- this.#rssSettleToken += 1;
615
- const token = this.#rssSettleToken;
616
- this.logger.verbose(
617
- `[builder-recycle] holding ${Math.round(BUILDER_RSS_SETTLE_MS / 1000)}s to see whether the allocator returns it (${reason})`,
618
- );
619
- await Bun.sleep(BUILDER_RSS_SETTLE_MS);
620
- if (token !== this.#rssSettleToken || this.#builder?.pid !== pid || this.#suspended || this.#waking) {
621
- this.logger.verbose("[builder-recycle] settle check abandoned; the builder moved on");
622
- return;
623
- }
624
- const settledBytes = await AkanAppHost.readProcessRssBytes(pid);
625
- if (settledBytes !== null && settledBytes < ceilingBytes) {
626
- this.logger.info(
627
- `[builder-recycle] skipped: the builder fell to ${asMib(settledBytes)}MiB (ceiling ${asMib(ceilingBytes)}MiB) on its own, so a recycle would have cost a boot build for nothing`,
628
- );
629
- return;
630
- }
631
- this.#recycleBuilderForRss(
632
- settledBytes === null ? reason : `${reason}; still ${asMib(settledBytes)}MiB after settling`,
633
- );
249
+ get #restartPending(): boolean {
250
+ return this.#recycler.pending || this.#backend.restartPending || this.#builder.recovering || this.#rss.armed;
634
251
  }
635
252
  /** Null when unreadable, meaning "no new information", never zero. */
636
253
  static async readProcessRssBytes(pid: number): Promise<number | null> {
637
- if (process.platform === "win32")
638
- return await AkanAppHost.#readRssKbVia(
639
- ["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"],
640
- AkanAppHost.#tasklistRssKb,
641
- );
642
- if (process.platform === "darwin") {
643
- const footprintBytes = await AkanAppHost.#readRssKbVia(
644
- ["footprint", "-p", String(pid), "-f", "bytes"],
645
- AkanAppHost.#footprintKb,
646
- );
647
- if (footprintBytes !== null) return footprintBytes;
648
- }
649
- const status = await Bun.file(`/proc/${pid}/status`)
650
- .text()
651
- .catch(() => null);
652
- const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
653
- if (vmRssKb) return Number(vmRssKb) * 1024;
654
- return await AkanAppHost.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
655
- }
656
- // Bounded: a `ps` that hangs under load would silently cancel the recycle awaiting it.
657
- static async #readRssKbVia(
658
- command: string[],
659
- parseKb: (output: string) => number,
660
- timeoutMs = PS_RSS_TIMEOUT_MS,
661
- ): Promise<number | null> {
662
- let proc: Bun.Subprocess<"ignore", "pipe", "ignore">;
663
- try {
664
- proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
665
- } catch {
666
- return null;
667
- }
668
- const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
669
- try {
670
- const output = await new Response(proc.stdout).text();
671
- await proc.exited;
672
- const rssKb = parseKb(output);
673
- return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
674
- } catch {
675
- return null;
676
- } finally {
677
- clearTimeout(killer);
678
- }
679
- }
680
- // `Mem Usage` is the working set (what `process.memoryUsage.rss()` reports on Windows) in locale-grouped KB.
681
- static #tasklistRssKb(output: string): number {
682
- const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
683
- return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
684
- }
685
- // The footprint is what `process.memoryUsage.rss()` reports on macOS; `ps` also counts pages freed for reuse.
686
- static #footprintKb(output: string): number {
687
- const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
688
- return bytes ? Number(bytes) / 1024 : Number.NaN;
689
- }
690
- #cancelRssRecycle(): void {
691
- this.#rssRecycleReason = null;
692
- this.#rssRecycleOver = null;
693
- // Also drops any settle check already waiting, which would otherwise recycle after the cancel.
694
- this.#rssSettleToken += 1;
695
- if (!this.#rssRecycleTimer) return;
696
- clearTimeout(this.#rssRecycleTimer);
697
- this.#rssRecycleTimer = null;
254
+ return await ProcessRss.bytesOf(pid);
698
255
  }
699
256
  /** `AKAN_DEV_IDLE_SUSPEND_MS=0` keeps the builder resident for the whole session. */
700
257
  static idleSuspendMs(): number | null {
701
- return resolveIdleSuspendMs(process.env.AKAN_DEV_IDLE_SUSPEND_MS);
702
- }
703
- #markDevActivity(): void {
704
- if (this.#suspended || this.#waking) return;
705
- this.#armIdleSuspend();
706
- }
707
- #armIdleSuspend(): void {
708
- const idleMs = AkanAppHost.idleSuspendMs();
709
- this.#cancelIdleSuspend();
710
- if (idleMs === null) return;
711
- this.#idleSuspendTimer = setTimeout(() => {
712
- this.#idleSuspendTimer = null;
713
- void this.#suspendWhenIdle(idleMs);
714
- }, idleMs);
715
- }
716
- #cancelIdleSuspend(): void {
717
- if (!this.#idleSuspendTimer) return;
718
- clearTimeout(this.#idleSuspendTimer);
719
- this.#idleSuspendTimer = null;
720
- }
721
- async #suspendWhenIdle(idleMs: number): Promise<void> {
722
- const decision = decideIdleSuspend({
723
- enabled: true,
724
- suspended: this.#suspended,
725
- builderReady: this.#builder?.status === "ready",
726
- backendReady: this.#backendReady,
727
- buildFailed: hasAnyBuildFailure(this.#buildStatusByPhase),
728
- restartPending: this.#restartPending,
729
- msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono,
730
- });
731
- if (decision !== "suspend") {
732
- this.logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
733
- this.#armIdleSuspend();
734
- return;
735
- }
736
- // Watch before stopping: an edit in the gap would be lost, and nothing would wake the dev server.
737
- if (!(await this.#startIdleWatcher())) {
738
- this.#armIdleSuspend();
739
- return;
740
- }
741
- this.#suspended = true;
742
- this.#emitDevEvent("suspended", `idle ${Math.round(idleMs / 1000)}s`);
743
- this.#stopBuilder();
744
- this.#openBuilderGap("idle suspend");
745
- this.logger.info(
746
- `[idle-suspend] no build activity for ${Math.round(idleMs / 1000)}s; released the builder — the next edit or route request brings it back`,
747
- );
748
- }
749
- get #restartPending(): boolean {
750
- return !!(
751
- this.#pendingRecycle ||
752
- this.#restartTimer ||
753
- this.#backendRestart ||
754
- this.#backendRecovery.pending ||
755
- this.#builderRecovery.pending ||
756
- this.#rssRecycleReason
757
- );
758
- }
759
- async #startIdleWatcher(): Promise<boolean> {
760
- try {
761
- const roots = await new WatchRootResolver(this.app).resolve();
762
- const watcher = new HmrWatcher({
763
- roots,
764
- logger: this.logger,
765
- onBatch: (batch) => {
766
- this.#recordSuspendedChange(batch);
767
- void this.#wakeFromIdle(`${batch.files.length} file(s) changed`);
768
- },
769
- });
770
- // Awaited so the mtime baseline exists before the first edit; a file missing from the batch is never rebuilt.
771
- await watcher.start();
772
- this.#idleWatcher = watcher;
773
- return true;
774
- } catch (err) {
775
- this.logger.warn(
776
- `[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`,
777
- );
778
- this.#stopIdleWatcher();
779
- return false;
780
- }
781
- }
782
- #stopIdleWatcher(): void {
783
- this.#idleWatcher?.stop();
784
- this.#idleWatcher = null;
785
- }
786
- #recordSuspendedChange(batch: ChangeBatch): void {
787
- const current = this.#suspendedChanges;
788
- if (!current) {
789
- this.#suspendedChanges = { files: [...batch.files], kinds: new Set(batch.kinds) };
790
- return;
791
- }
792
- this.#suspendedChanges = {
793
- files: [...new Set([...current.files, ...batch.files])],
794
- kinds: new Set([...current.kinds, ...batch.kinds]),
795
- };
796
- }
797
- async #wakeFromIdle(reason: string): Promise<void> {
798
- if (!this.#suspended || this.#waking) return;
799
- this.#waking = true;
800
- this.#cancelIdleSuspend();
801
- this.#stopIdleWatcher();
802
- const batch = this.#suspendedChanges;
803
- this.#suspendedChanges = null;
804
- const startedAtMono = performance.now();
805
- this.logger.info(`[idle-suspend] waking (${reason})`);
806
- try {
807
- await this.#applyIdleWake(batch);
808
- this.logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
809
- } catch (err) {
810
- this.logger.error(
811
- `[idle-suspend] wake failed; recovering the builder: ${err instanceof Error ? err.message : String(err)}`,
812
- );
813
- this.#scheduleBuilderRecovery({ files: batch?.files ?? [] });
814
- } finally {
815
- this.#suspended = false;
816
- this.#waking = false;
817
- this.#wokeAtMono = performance.now();
818
- this.#flushPendingBuilderMessages();
819
- this.#armIdleSuspend();
820
- // A wake often leaves the backend state untouched, so nothing else would tell a supervisor it came back.
821
- this.#emitDevEvent(devHostStateOf(this.#backendLifecycleState, this.#backendGaveUp));
822
- }
823
- }
824
- async #applyIdleWake(batch: ChangeBatch | null): Promise<void> {
825
- const files = batch?.files ?? [];
826
- if (shouldRefreshConfigOnIdleWake(batch)) {
827
- this.logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
828
- // Replaces the backend too, and a baseline kept past its own gap costs a restart at the next one.
829
- this.#discardBuilderGap("config change replaces the backend anyway");
830
- //? Through the same path as a save's: a failure is reported and stays pending, as one would be awake.
831
- await this.#applyRecycle({ type: "invalidate", kinds: [...(batch?.kinds ?? [])], files }, true);
832
- return;
833
- }
834
- // Refresh before deciding: a file created while suspended is not in the graph yet.
835
- if (files.length > 0) await this.#backendGraph.refresh();
836
- await this.#startBuilder({ announceBootState: true });
837
- // Merged: the watcher's batch and the stamps overlap on the ordinary one-save-during-suspend case.
838
- const missed = await this.#takeBuilderGapChanges();
839
- const backendFiles = [...new Set([...files.filter((file) => this.#backendGraph.has(file)), ...missed])];
840
- if (backendFiles.length === 0) return;
841
- this.logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
842
- this.#scheduleBackendRestart({ files: backendFiles, roles: [] });
843
- }
844
- // Until a builder is back nothing watches (Bun's `fs.watch` drops events, a new builder primes from disk), so
845
- // stamp the backend graph now. Earliest open wins: over-reporting costs a restart, under-reporting stale code.
846
- #openBuilderGap(reason: string): void {
847
- if (this.#builderGapStamp) return;
848
- if (!this.#backendGraph.ready) {
849
- this.logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
850
- return;
851
- }
852
- this.#builderGapStamp = this.#backendGraph
853
- .fingerprint()
854
- .then((stamps) => {
855
- this.logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
856
- return stamps;
857
- })
858
- .catch((err) => {
859
- this.logger.warn(
860
- `[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`,
861
- );
862
- return null;
863
- });
864
- }
865
- async #takeBuilderGapChanges(): Promise<string[]> {
866
- const stamping = this.#builderGapStamp;
867
- this.#builderGapStamp = null;
868
- const before = stamping ? await stamping : null;
869
- if (!before) return [];
870
- const moved = filesChangedSince(before, await this.#backendGraph.fingerprint());
871
- if (moved.length === 0) {
872
- this.logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
873
- return moved;
874
- }
875
- this.logger.info(
876
- `[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`,
877
- );
878
- return moved;
879
- }
880
- // A baseline left open is compared against the next gap, where everything saved since reads as changed.
881
- #discardBuilderGap(reason: string): void {
882
- if (!this.#builderGapStamp) return;
883
- this.#builderGapStamp = null;
884
- this.logger.verbose(`[builder-gap] stamps dropped (${reason})`);
885
- }
886
- async #restartBackendForGapChanges(): Promise<void> {
887
- const moved = await this.#takeBuilderGapChanges();
888
- if (moved.length === 0) return;
889
- this.#scheduleBackendRestart({ files: moved, roles: [] });
890
- }
891
- #flushPendingBuilderMessages(): void {
892
- const pending = this.#pendingBuilderMessages.splice(0);
893
- if (pending.length === 0) return;
894
- this.logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
895
- for (const message of pending) this.#sendToBuilder(message);
896
- }
897
-
898
- // Held requests carry the departing backend's ids, which the new one reissues from 1, so a replay would
899
- // misdeliver answers; nothing is answered because the old backend is already stopped.
900
- #discardPendingBuilderMessages(reason: string): void {
901
- const held = this.#pendingBuilderMessages.splice(0);
902
- if (held.length === 0) return;
903
- this.logger.verbose(`[builder] dropped ${held.length} held builder request(s): ${reason}`);
904
- }
905
- #failPendingBuilderMessages(reason: string): void {
906
- const held = this.#pendingBuilderMessages.splice(0);
907
- if (held.length === 0) return;
908
- this.logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
909
- for (const message of held) this.#failBuilderRequest(message, reason);
910
- }
911
- #failBuilderRequest(message: BuilderMessage, error: string): boolean {
912
- if (message.type === "build-route")
913
- this.#sendToBackend({ type: "build-route-res", id: message.id, ok: false, error, kind: "unavailable" });
914
- else if (message.type === "build-csr")
915
- this.#sendToBackend({ type: "build-csr-res", id: message.id, ok: false, error, kind: "unavailable" });
916
- else if (message.type === "build-graph")
917
- this.#sendToBackend({ type: "build-graph-res", id: message.id, ok: false, error, kind: "unavailable" });
918
- else return false;
919
- return true;
920
- }
921
- #recycleBuilderForRss(reason: string): void {
922
- // Dropping the recycle costs nothing: the next build re-reports an over-ceiling rss and re-arms it.
923
- if (this.#pendingRecycle || this.#restartTimer) {
924
- this.logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
925
- return;
926
- }
927
- if (!this.#builder?.recycle(reason)) return;
928
- this.#lastRssRecycleAtMono = performance.now();
929
- // Stamped at the request, not the exit: a draining builder has already stopped taking work.
930
- this.#openBuilderGap("builder recycle");
931
- }
932
- async #handleInvalidate(message: Extract<BuilderMessage, { type: "invalidate" }>) {
933
- this.#logDevPlan(message);
934
- if (this.#rssRecycleReason) this.#armRssRecycle(this.#rssRecycleReason);
935
- // Checked first: a dev-host restart also recycles the builder and backend.
936
- const wantsDevHostRestart = shouldRestartDevHostByDevPlan(message);
937
- const pending = this.#pendingRecycle;
938
- // A deferred recycle resumes on the next code batch; a css-only batch cannot heal a compile error.
939
- const resumes = !!pending && message.kinds.includes("code") && this.#touchesFailedRecycle(message.files);
940
- if (wantsDevHostRestart || shouldRestartBuilderByDevPlan(message) || resumes) {
941
- const refreshConfig = wantsDevHostRestart || (pending?.refreshConfig ?? false);
942
- const merged = pending ? mergeInvalidateMessages(pending.message, message) : message;
943
- const generation = message.devPlan?.generation ?? message.generation;
944
- if (hasBuildFailureForGeneration(this.#buildStatusByPhase, generation)) {
945
- this.#deferRecycle(merged, { refreshConfig, generation });
946
- return;
947
- }
948
- await this.#applyRecycle(merged, refreshConfig);
949
- return;
950
- }
951
- if (await this.#shouldRestartBackend(message)) {
952
- this.#scheduleBackendRestart(backendRestartReasonFromMessage(message));
953
- return;
954
- }
955
- this.#sendToBackend(message);
956
- }
957
- async #applyRecycle(message: Extract<BuilderMessage, { type: "invalidate" }>, refreshConfig: boolean): Promise<void> {
958
- if (this.#stopping) return;
959
- this.#pendingRecycle = null;
960
- const progress = { applied: !refreshConfig };
961
- try {
962
- if (refreshConfig) await this.#restartDevHost(message, progress);
963
- else await this.#restartDevChildren(message);
964
- } catch (err) {
965
- const kind = refreshConfig ? "Config" : "Runtime metadata";
966
- const generation = this.#recordDevHostRestartFailure(message, err, kind, { applied: progress.applied });
967
- //? Kept only when the change itself did not apply: a builder that booted degraded (a broken akan.config.ts)
968
- //? takes the fixing save itself and sends no invalidate, so without this the old config would keep running.
969
- if (progress.applied) this.#restartFailedAfterApply = generation;
970
- else this.#pendingRecycle = { message, refreshConfig, failed: true, failedGeneration: generation };
971
- this.#resurrectDevChildren(message);
972
- }
973
- }
974
- //? The first green pages build after a failed restart that touches its change is the fix: the change applies then. A
975
- //? cause no save fixes (an env value) waits for the next change of those files, not for every green save.
976
- async #resumeFailedRecycle(status: DevBuildStatus): Promise<void> {
977
- const pending = this.#pendingRecycle;
978
- if (!pending?.failed || !status.ok || status.phase !== "pages" || !this.#touchesFailedRecycle(status.files)) return;
979
- //? Newer than the failure: the batch that carried the change reports its own pages ok while the restart runs.
980
- if (status.generation <= (pending.failedGeneration ?? -1)) return;
981
- await this.#applyRecycle(pending.message, pending.refreshConfig);
982
- }
983
- #touchesFailedRecycle(files: string[]): boolean {
984
- const pending = this.#pendingRecycle;
985
- if (!pending?.failed) return true;
986
- const changed = new Set(pending.message.files);
987
- return files.some((file) => changed.has(file));
988
- }
989
- #deferRecycle(
990
- message: Extract<BuilderMessage, { type: "invalidate" }>,
991
- { refreshConfig, generation }: { refreshConfig: boolean; generation?: number },
992
- ): void {
993
- this.#pendingRecycle = { message, refreshConfig };
994
- const kind = refreshConfig ? "Config" : "Runtime metadata";
995
- this.logger.warn(
996
- `[dev-host] ${kind.toLowerCase()} restart deferred generation=${generation ?? "(unknown)"}; keeping the running dev server until the build error is fixed`,
997
- );
998
- const status: DevBuildStatus = {
999
- generation: generation ?? this.#nextBackendBuildStatusGeneration(),
1000
- phase: "scan",
1001
- ok: false,
1002
- files: message.files,
1003
- message: `${kind} change is on hold while the build is failing; it will apply automatically once the error is fixed.`,
1004
- };
1005
- this.#recordBuildStatus(status);
1006
- this.#sendOrQueueBuildStatus(status);
1007
- }
1008
- // The backend returns on the last-good artifact so the error overlay stays reachable.
1009
- #resurrectDevChildren(message: Extract<BuilderMessage, { type: "invalidate" }>): void {
1010
- const generation = message.devPlan?.generation ?? message.generation;
1011
- if (!this.#backend) this.#startBackend({ generation, files: message.files });
1012
- this.#scheduleBuilderRecovery({ generation, files: message.files });
1013
- }
1014
- #scheduleBuilderRecovery(reason: { generation?: number; files: string[] }): void {
1015
- if (this.#stopping || this.#builderRecovery.pending || this.#builder) return;
1016
- const delay = this.#builderRecovery.schedule(() => {
1017
- if (this.#stopping || this.#builder) return;
1018
- void this.#recoverBuilder(reason);
1019
- });
1020
- this.logger.warn(
1021
- `[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#builderRecovery.attempts})`,
1022
- );
1023
- }
1024
- async #recoverBuilder(reason: { generation?: number; files: string[] }): Promise<void> {
1025
- try {
1026
- await this.#startBuilder();
1027
- } catch (err) {
1028
- if (this.#stopping) return;
1029
- this.logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
1030
- this.#scheduleBuilderRecovery(reason);
1031
- return;
1032
- }
1033
- this.#builderRecovery.reset();
1034
- this.logger.info("[builder-recovery] builder recovered");
1035
- void this.#restartBackendForGapChanges();
1036
- const failedAfterApply = this.#restartFailedAfterApply;
1037
- this.#restartFailedAfterApply = null;
1038
- const status: DevBuildStatus = {
1039
- generation:
1040
- failedAfterApply !== null
1041
- ? this.#nextBackendBuildStatusGeneration(failedAfterApply + 1)
1042
- : (reason.generation ?? this.#nextBackendBuildStatusGeneration()),
1043
- phase: "scan",
1044
- ok: true,
1045
- files: reason.files,
1046
- message: "Builder recovered",
1047
- };
1048
- this.#recordBuildStatus(status);
1049
- this.#sendOrQueueBuildStatus(status);
1050
- if (!this.#backend && !this.#backendRecovery.pending) {
1051
- this.#startBackend({ generation: reason.generation, files: reason.files });
1052
- }
1053
- }
1054
- #reviveBackendAfterGreenBuild(status: DevBuildStatus): void {
1055
- if (!status.ok || !this.#backendGaveUp || this.#backend || this.#backendRecovery.pending) return;
1056
- this.logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
1057
- this.#backendRecovery.reset();
1058
- this.#startBackend({ generation: status.generation, files: status.files });
1059
- }
1060
- async #restartDevChildren(message: Extract<BuilderMessage, { type: "invalidate" }>): Promise<void> {
1061
- const generation = message.devPlan?.generation ?? message.generation;
1062
- this.logger.warn(
1063
- `[dev-host] recycling builder/backend for runtime metadata generation=${generation ?? "(unknown)"} files=${message.files.length}`,
1064
- );
1065
- await this.#recycleDevChildren(message);
1066
- }
1067
- // The config is re-imported with a cache-busting query, but modules it imports stay cached: a change inside an
1068
- // imported plugin file still needs a manual `akan start` restart.
1069
- async #restartDevHost(
1070
- message: Extract<BuilderMessage, { type: "invalidate" }>,
1071
- progress?: { applied: boolean },
1072
- ): Promise<void> {
1073
- const generation = message.devPlan?.generation ?? message.generation;
1074
- this.logger.warn(
1075
- `[dev-host] config change detected; restarting dev host generation=${generation ?? "(unknown)"} files=${message.files.length}`,
1076
- );
1077
- await this.#recycleDevChildren(message, { refreshConfig: true, progress });
1078
- }
1079
- async #recycleDevChildren(
1080
- message: Extract<BuilderMessage, { type: "invalidate" }>,
1081
- { refreshConfig = false, progress }: { refreshConfig?: boolean; progress?: { applied: boolean } } = {},
1082
- ): Promise<void> {
1083
- const generation = message.devPlan?.generation ?? message.generation;
1084
- this.#clearRestartTimers();
1085
- this.#builderRecovery.reset();
1086
- this.#pendingRestartReason = null;
1087
- await this.#backendRestart;
1088
- this.#lastGoodFrontend = {};
1089
- this.#buildStatusByPhase.clear();
1090
- this.#pendingBuildStatusReplay = [];
1091
- await this.#stopBackend();
1092
- this.#stopBuilder();
1093
- this.#patcherOff = false;
1094
- if (refreshConfig) {
1095
- await this.app.getConfig({ refresh: true });
1096
- // Merge, not replace: `start()` added values prepare does not produce (REDIS_HOST from the tunnel).
1097
- const { env } = await this.app.prepareCommand("start");
1098
- Object.assign(this.env, env);
1099
- if (progress) progress.applied = true;
1100
- }
1101
- await this.#backendGraph.refresh();
1102
- await this.#startBuilder();
1103
- this.#startBackend({ generation, files: message.files });
1104
- }
1105
- // `supersede`: a recycled builder's re-announcement is what is on disk now, whatever generation it carries.
1106
- #recordLastGood(
1107
- message: Extract<BuilderMessage, { type: "pages-updated" }> | Extract<BuilderMessage, { type: "css-updated" }>,
1108
- { supersede = false }: { supersede?: boolean } = {},
1109
- ): void {
1110
- if (message.type === "pages-updated") {
1111
- if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.pages, message)) return;
1112
- this.#lastGoodFrontend.pages = message;
1113
- this.logger.verbose(
1114
- `[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`,
1115
- );
1116
- return;
1117
- }
1118
- if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.css, message)) return;
1119
- this.#lastGoodFrontend.css = message;
1120
- this.logger.verbose(
1121
- `[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`,
1122
- );
1123
- }
1124
- #recordDevHostRestartFailure(
1125
- message: Extract<BuilderMessage, { type: "invalidate" }>,
1126
- err: unknown,
1127
- kind: "Config" | "Runtime metadata",
1128
- { applied }: { applied: boolean },
1129
- ): number {
1130
- const generation = message.devPlan?.generation ?? message.generation ?? this.#nextBackendBuildStatusGeneration();
1131
- const detail = err instanceof Error ? err.message : String(err);
1132
- this.logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
1133
- const names = message.files.slice(0, 3).map((file) => path.basename(file));
1134
- const saved = names.length > 0 ? names.join(", ") : "the changed file";
1135
- const status: DevBuildStatus = {
1136
- generation,
1137
- phase: "scan",
1138
- ok: false,
1139
- files: message.files,
1140
- message: applied
1141
- ? `${kind} change applied, but the dev server failed to restart: ${detail}. It is recovering on its own.`
1142
- : `${kind} change failed to apply: ${detail}. The dev server keeps running on the previous ${kind.toLowerCase()}; once it is fixed, save ${saved} again or restart the dev server to apply it.`,
1143
- };
1144
- this.#recordBuildStatus(status);
1145
- this.#sendOrQueueBuildStatus(status);
1146
- return generation;
1147
- }
1148
- #recordBuildStatus(status: DevBuildStatus): void {
1149
- const recovered = shouldMarkBuildPhaseRecovered(this.#buildStatusByPhase, status);
1150
- if (shouldKeepBuildFailure(this.#buildStatusByPhase, status)) return;
1151
- this.#buildStatusByPhase.set(status.phase, status);
1152
- const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
1153
- if (status.ok) this.logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
1154
- else this.logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
1155
- }
1156
- #sendOrQueueBuildStatus(status: DevBuildStatus): void {
1157
- if (!this.#backend || shouldQueueBuildStatusReplay(this.#backendReady, this.#pendingBuildStatusReplay.length)) {
1158
- this.#pendingBuildStatusReplay.push(status);
1159
- this.logger.verbose(
1160
- `backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`,
1161
- );
1162
- return;
1163
- }
1164
- this.#sendToBackend({ type: "build-status", data: status });
1165
- }
1166
- //? A route status belongs to the route cache of the backend that asked for the build: a new backend builds its routes
1167
- //? again, and reports each one itself.
1168
- #forgetRouteBuildStatus(): void {
1169
- this.#buildStatusByPhase.delete("route");
1170
- this.#pendingBuildStatusReplay = this.#pendingBuildStatusReplay.filter((status) => status.phase !== "route");
1171
- }
1172
- #replayBuilderState(): void {
1173
- if (!this.#backendReady) return;
1174
- if (this.#lastGoodFrontend.css) this.#sendToBackend(this.#lastGoodFrontend.css);
1175
- if (this.#lastGoodFrontend.pages) this.#sendToBackend(this.#lastGoodFrontend.pages);
1176
- const queuedStatuses = this.#pendingBuildStatusReplay.splice(0);
1177
- for (const status of buildStatusReplaySequence(queuedStatuses, this.#buildStatusByPhase)) {
1178
- this.#sendToBackend({ type: "build-status", data: status });
1179
- }
1180
- }
1181
- #logDevPlan(message: Extract<BuilderMessage, { type: "invalidate" }>): void {
1182
- if (!message.devPlan) return;
1183
- const { generation, roles, actions, reasonByFile } = message.devPlan;
1184
- this.logger.verbose(
1185
- `[dev-plan] generation=${generation} roles=${roles.join(",") || "(none)"} actions=${actions.join(",") || "(none)"} reasons=${Object.keys(reasonByFile).length}`,
1186
- );
1187
- }
1188
-
1189
- async #shouldRestartBackend(message: Extract<BuilderMessage, { type: "invalidate" }>): Promise<boolean> {
1190
- if (message.kinds.length === 1 && message.kinds[0] === "css") return false;
1191
- if (message.devPlan) {
1192
- const shouldRestart = shouldRestartBackendByDevPlan(message) ?? false;
1193
- if (shouldRestart && message.kinds.includes("code")) await this.#backendGraph.refresh();
1194
- return shouldRestart;
1195
- }
1196
- if (message.kinds.includes("code")) await this.#backendGraph.refresh();
1197
- if (message.files.some((file) => this.#backendGraph.has(file))) return true;
1198
- if (!this.#backendGraph.lastRefreshSucceeded) {
1199
- const fallbackFiles = message.files.filter((file) =>
1200
- isLegacyBackendFallbackFile(file, this.app.workspace.workspaceRoot),
1201
- );
1202
- if (fallbackFiles.length > 0) {
1203
- this.logger.warn(
1204
- `[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`,
1205
- );
1206
- return true;
1207
- }
1208
- }
1209
- return false;
1210
- }
1211
- async #startBuilder({
1212
- announceBootState = false,
1213
- }: {
1214
- announceBootState?: boolean;
1215
- } = {}): Promise<IncrementalBuilderHost> {
1216
- const startTime = Date.now();
1217
- this.app.verbose(`[cli] waiting for builder to complete initial base build…`);
1218
- let lastError: unknown;
1219
- for (let attempt = 1; attempt <= BUILDER_START_MAX_ATTEMPTS; attempt++) {
1220
- const builder = await IncrementalBuilderHost.create(
1221
- this.app,
1222
- this.env,
1223
- (msg) => {
1224
- this.#enqueueBuilderMessage(msg);
1225
- },
1226
- {
1227
- stdio: this.stdio,
1228
- onOutput: (kind, text) => void (kind === "stderr" ? process.stderr : process.stdout).write(text),
1229
- patcherOff: this.#patcherOff,
1230
- },
1231
- );
1232
- if (this.#stopping) {
1233
- builder.stop();
1234
- throw new Error("dev server stopped before the builder started");
1235
- }
1236
- this.#builder = builder;
1237
- try {
1238
- await this.#waitForBuilderReady(attempt, { announceBootState });
1239
- this.app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms — starting backend`);
1240
- return this.#builder;
1241
- } catch (err) {
1242
- lastError = err;
1243
- this.#stopBuilder();
1244
- if (attempt >= BUILDER_START_MAX_ATTEMPTS || this.#stopping) break;
1245
- this.app.verbose(`[cli] builder failed before ready; retrying (${attempt + 1}/${BUILDER_START_MAX_ATTEMPTS})`);
1246
- }
1247
- }
1248
- this.#failPendingBuilderMessages("builder failed to start");
1249
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
1250
- }
1251
- #waitForBuilderReady(
1252
- attempt: number,
1253
- { announceBootState = false }: { announceBootState?: boolean } = {},
1254
- ): Promise<void> {
1255
- return new Promise<void>((resolve, reject) => {
1256
- if (!this.#builder) throw new Error("Builder Not Found");
1257
- let settled = false;
1258
- const settle = (fn: () => void) => {
1259
- if (settled) return;
1260
- settled = true;
1261
- clearTimeout(timeout);
1262
- if (this.#abandonBuilderStart === abandon) this.#abandonBuilderStart = null;
1263
- fn();
1264
- };
1265
- const abandon = (error: Error) => settle(() => reject(error));
1266
- this.#abandonBuilderStart = abandon;
1267
- const timeout = setTimeout(() => {
1268
- settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
1269
- }, BUILDER_READY_TIMEOUT_MS);
1270
- this.#builder.start({
1271
- announceBootState,
1272
- onExit: () => {
1273
- settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
1274
- },
1275
- onAway: () => {
1276
- this.#openBuilderGap("builder replacement");
1277
- },
1278
- onReady: () => {
1279
- settle(resolve);
1280
- this.#flushPendingBuilderMessages();
1281
- },
1282
- onRestartReady: () => {
1283
- this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
1284
- this.#replayBuilderState();
1285
- this.#flushPendingBuilderMessages();
1286
- void this.#restartBackendForGapChanges();
1287
- void this.#checkRecycledBuilderFloor();
1288
- },
1289
- });
1290
- });
1291
- }
1292
- #sendToBuilder(message: BuilderMessage): void {
1293
- this.#markDevActivity();
1294
- if (this.#suspended || this.#waking) {
1295
- this.#pendingBuilderMessages.push(message);
1296
- void this.#wakeFromIdle(`${message.type} arrived while suspended`);
1297
- return;
1298
- }
1299
- // In `env`, which every builder spawn re-reads, so a restarted builder stays armed for a mobile dev session. A view's
1300
- // shell is asked for per read, so it arms nothing.
1301
- if (message.type === "build-csr" && !message.shell && this.env.AKAN_DEV_CSR_REBUILD !== "1") {
1302
- Object.assign(this.env, { AKAN_DEV_CSR_REBUILD: "1" });
1303
- this.logger.verbose(`[csr] armed dev CSR rebuilds (${message.reason})`);
1304
- }
1305
- // Renumbered per backend generation; the failure replies below use that backend's own `message.id`.
1306
- if (message.type === "build-route" || message.type === "build-csr" || message.type === "build-graph") {
1307
- const outgoing = this.#builderRequests.issue(message);
1308
- if (this.#builder?.send(outgoing)) return;
1309
- this.#builderRequests.withdraw(outgoing.id);
1310
- } else if (this.#builder?.send(message)) return;
1311
- const status = this.#builder?.status ?? "stopped";
1312
- // A returning builder is a gap, not a failure: hold the request (`BuilderRpc`'s timeout still bounds it).
1313
- if (shouldHoldForReturningBuilder({ status, heldCount: this.#pendingBuilderMessages.length })) {
1314
- this.#pendingBuilderMessages.push(message);
1315
- this.logger.verbose(
1316
- `[builder] holding ${message.type} until the builder is ready (${this.#pendingBuilderMessages.length} waiting)`,
1317
- );
1318
- return;
1319
- }
1320
- if (this.#failBuilderRequest(message, `builder is ${status}; reload after the builder is ready`)) return;
1321
- this.logger.warn("akanAppHost builder is not running");
1322
- }
1323
- #stopBuilder(): void {
1324
- this.#cancelRssRecycle();
1325
- if (!this.#builder) return;
1326
- if (this.#builder.patcherOff) this.#patcherOff = true;
1327
- this.#builder.stop();
1328
- this.#builder = null;
258
+ return DevIdleSuspend.idleMs();
1329
259
  }
1330
260
  }