@akanjs/cli 3.2.0-rc.9 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/.build-stamp +2 -2
  2. package/CodeAgent-fx6088tv.js +11 -0
  3. package/{CodeTui-qstk5vpj.js → CodeTui-zee8atsr.js} +822 -666
  4. package/README.ko.md +7 -0
  5. package/README.md +7 -0
  6. package/TunnelShare-9ry4vh0y.js +18 -0
  7. package/agent.command-x65f2ags.js +61 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-79azsb2w.js +11 -0
  10. package/{application.command-m4rq4wc2.js → application.command-azbd1pb2.js} +83 -37
  11. package/{applicationBuildRunner-df7rx3ra.js → applicationBuildRunner-trfxv3pd.js} +49 -18
  12. package/buildBatch.proc.js +25 -11
  13. package/{cloud.command-a0gy0qq2.js → cloud.command-gapp4634.js} +33 -29
  14. package/cloud.script-3b401efv.js +35 -0
  15. package/{code.command-5rsdqw8s.js → code.command-5smx61yf.js} +13 -9
  16. package/context.command-ym5jbkny.js +64 -0
  17. package/context.runner-kctbfsde.js +34 -0
  18. package/{dependencyScanner-78sq8m4q.js → dependencyScanner-ge10gb52.js} +2 -2
  19. package/{devTui-h77zrjv5.js → devTui-rf374y2w.js} +1 -1
  20. package/{fileSys-zpvt5gtf.js → fileSys-q22646yc.js} +1 -1
  21. package/{guideline.command-mffxknbr.js → guideline.command-zwypaqsh.js} +9 -5
  22. package/guidelines/agentRule/agentRule.instruction.md +25 -9
  23. package/guidelines/akanApi/akanApi.instruction.md +6 -4
  24. package/guidelines/conventions/core.md +23 -5
  25. package/guidelines/conventions/rules/app.md +4 -1
  26. package/guidelines/conventions/rules/page.md +5 -4
  27. package/guidelines/conventions/rules/ts.md +3 -3
  28. package/guidelines/errorCodes/errorCodes.instruction.md +165 -0
  29. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  30. package/guidelines/mcpRule/mcpRule.instruction.md +225 -5
  31. package/guidelines/pageRule/pageRule.instruction.md +10 -1
  32. package/guidelines/queryRule/queryRule.instruction.md +3 -1
  33. package/guidelines/runtimeRule/runtimeRule.instruction.md +14 -8
  34. package/guidelines/transportRule/transportRule.instruction.md +31 -1
  35. package/incrementalBuilder.proc.js +577 -411
  36. package/{index-w15mg3km.js → index-0dm25wvf.js} +1 -1
  37. package/{index-0gg15zwa.js → index-0s7w2085.js} +6 -6
  38. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  39. package/{index-swwjakt0.js → index-275a4r3n.js} +11 -11
  40. package/{index-j6gc8n14.js → index-2jmvfa62.js} +11 -9
  41. package/{index-qd7xn2bk.js → index-2ny1e95c.js} +2 -2
  42. package/{index-exn38bzx.js → index-2yn3r67f.js} +116 -54
  43. package/{index-34792nh7.js → index-3txdtztz.js} +1 -1
  44. package/{index-28x1aszt.js → index-41a03gkj.js} +149 -53
  45. package/{index-2mf1aen9.js → index-4ss4gkv3.js} +2 -2
  46. package/{index-an76bdrv.js → index-612fdtbk.js} +1 -1
  47. package/{index-5radqwn2.js → index-67sd09ag.js} +12 -12
  48. package/{index-0hbtve0a.js → index-6dzjer7p.js} +32 -28
  49. package/{index-3ghdb7p5.js → index-71y6176j.js} +2777 -3676
  50. package/{index-xyn02k0w.js → index-78y75t0a.js} +662 -433
  51. package/index-7wf8snar.js +80 -0
  52. package/{index-skmtj8rm.js → index-8jtqfye2.js} +27 -10
  53. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  54. package/{index-nmvhjn8c.js → index-9wh04mqy.js} +93 -82
  55. package/{index-xvk2a75m.js → index-a860mx0m.js} +3 -3
  56. package/{index-5zwr4n6k.js → index-baccvws5.js} +65 -8
  57. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  58. package/{index-bns3wcpc.js → index-by2tvsq6.js} +1 -1
  59. package/{index-r0a604h4.js → index-c669pbyb.js} +5 -4
  60. package/{index-x40bdsca.js → index-dadwp2aw.js} +33 -98
  61. package/{index-vm0dn0mt.js → index-dmcpetwe.js} +200 -138
  62. package/{index-43f4h4cm.js → index-ebn9kgea.js} +6 -6
  63. package/{index-hqv34wzq.js → index-gt8phqpt.js} +10 -10
  64. package/{index-yckz5t8b.js → index-h901f24n.js} +516 -434
  65. package/{index-j3v29pq7.js → index-j0wr4e32.js} +219 -175
  66. package/{index-gcx48get.js → index-j592zfqc.js} +2 -2
  67. package/{index-grxs6fts.js → index-j6jjmn2r.js} +57 -31
  68. package/{index-w8yasvpc.js → index-jek2re5k.js} +2136 -2175
  69. package/{index-ny2k80mv.js → index-jf4vk1s0.js} +9 -2
  70. package/{index-gxav1bjz.js → index-k6vwww45.js} +9 -9
  71. package/{index-99qvtff2.js → index-kfvjzk8r.js} +5 -5
  72. package/{index-j6eeh5d7.js → index-knpm8sdm.js} +5 -5
  73. package/{index-2r9ff9qm.js → index-nc3br31y.js} +2 -2
  74. package/{index-35j83zkd.js → index-p5zh7pmc.js} +2 -2
  75. package/{index-cmg5ngqa.js → index-p7beqww9.js} +2 -2
  76. package/{index-b4qq3rq0.js → index-rwgqba9p.js} +1 -1
  77. package/{index-rfzp4pqs.js → index-s885g0jj.js} +3 -3
  78. package/{index-9p260r4e.js → index-trffs83s.js} +538 -250
  79. package/{index-k92x3vne.js → index-v7ajmsh3.js} +1 -1
  80. package/index-w1zexzpx.js +127 -0
  81. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  82. package/{index-39jz41jb.js → index-xs9a3ddt.js} +3 -3
  83. package/{index-rp4yf32g.js → index-xwwex8rf.js} +36 -29
  84. package/{index-ra9fvn7s.js → index-ybcb9wc8.js} +74 -38
  85. package/index-z92zm3wd.js +788 -0
  86. package/{index-j9790rhk.js → index-z96ks033.js} +1509 -1121
  87. package/index-zfnz878d.js +30 -0
  88. package/{index-2vgv7fs7.js → index-zmd9xxgd.js} +727 -693
  89. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  90. package/index.js +28 -24
  91. package/libExecutor-jc6f8hm6.js +10 -0
  92. package/{library.command-bmd7zc5m.js → library.command-nxvesvhb.js} +12 -5
  93. package/{localRegistry.command-y6en1599.js → localRegistry.command-xz62e4ng.js} +29 -24
  94. package/{module.command-7exfffqw.js → module.command-aaws9byg.js} +11 -7
  95. package/{package.command-adskw2rj.js → package.command-j7hv26p0.js} +14 -10
  96. package/package.json +8 -8
  97. package/{page.command-dw01272p.js → page.command-7yffs7n9.js} +8 -4
  98. package/{pipeline.command-0b1r3y5r.js → pipeline.command-7yk0zcng.js} +15 -9
  99. package/pkgExecutor-arxmvx4t.js +10 -0
  100. package/{primitive.command-byw6vc04.js → primitive.command-7a1pt715.js} +12 -8
  101. package/{projectTypecheck-kkrpq60a.js → projectTypecheck-f4qhbecd.js} +1 -1
  102. package/{prompter-qrwx1p17.js → prompter-qyggfhqd.js} +2 -2
  103. package/{quality.command-6rqnhzct.js → quality.command-c6mvrjh1.js} +25 -16
  104. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  105. package/{repair.command-rw5zymak.js → repair.command-093adzt9.js} +12 -8
  106. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  107. package/{scalar.command-2dyp9nh9.js → scalar.command-2ex84spb.js} +10 -6
  108. package/skills/akan-debug/SKILL.md +8 -5
  109. package/skills/akan-err/SKILL.md +7 -0
  110. package/skills/akan-mcp/SKILL.md +19 -1
  111. package/skills/akan-scaffold/SKILL.md +1 -1
  112. package/skills/akan-validate/SKILL.md +3 -3
  113. package/{subspace.command-111ynwv1.js → subspace.command-4n4n4jpv.js} +32 -24
  114. package/templates/app/page/_layout.tsx +13 -0
  115. package/templates/app/page/styles.css.template +40 -0
  116. package/templates/appSample/page/_index.tsx +9 -9
  117. package/templates/appSample/page/_layout.tsx +1 -0
  118. package/templates/appSample/page/styles.css.template +40 -5
  119. package/templates/appSample/ui/Recipe/jellyButton.ts +1 -1
  120. package/templates/biomeForm.ts +1 -1
  121. package/templates/env/_env.server.type.ts +1 -1
  122. package/templates/facetIndex/index.ts +2 -37
  123. package/templates/lib/sig.ts +0 -4
  124. package/templates/lib/useClient.ts +1 -1
  125. package/templates/workspaceRoot/.devcontainer/devcontainer.json.template +1 -1
  126. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  127. package/templates/workspaceRoot/README.ts +4 -2
  128. package/{tunnel.command-2gcpfbdj.js → tunnel.command-f7ep1qfa.js} +17 -13
  129. package/{typeChecker-s640r6c0.js → typeChecker-7jt6abrs.js} +1 -1
  130. package/typecheck.proc.js +3 -2
  131. package/{verify.command-djgs86ma.js → verify.command-zrkxnvct.js} +21 -17
  132. package/{workflow.command-n0k2mxr5.js → workflow.command-ks16jegk.js} +21 -14
  133. package/{workspace.command-fh1qwxfx.js → workspace.command-ahhfpaag.js} +60 -54
  134. package/CodeAgent-x2p3a3e0.js +0 -11
  135. package/TunnelShare-c4xsfzg5.js +0 -15
  136. package/agent.command-9et2e27p.js +0 -52
  137. package/cloud.script-xze4zh7n.js +0 -31
  138. package/context.command-rk1dwrg4.js +0 -57
  139. package/context.runner-83ky5m1b.js +0 -30
  140. /package/templates/{appSample → app}/public/fonts/Pretendard-Bold.woff2 +0 -0
  141. /package/templates/{appSample → app}/public/fonts/Pretendard-Medium.woff2 +0 -0
  142. /package/templates/{appSample → app}/public/fonts/Pretendard-Regular.woff2 +0 -0
  143. /package/templates/{appSample → app}/public/fonts/Pretendard-SemiBold.woff2 +0 -0
@@ -1,19 +1,25 @@
1
1
  // @bun
2
2
  import {
3
- AppInfo,
4
3
  CommandExecutionError,
5
- WorkspaceExecutor,
6
4
  SysExecutor,
7
- AppExecutor,
8
- LibExecutor,
9
- PkgExecutor
10
- } from "./index-3ghdb7p5.js";
5
+ AppInfo,
6
+ WorkspaceExecutor
7
+ } from "./index-71y6176j.js";
11
8
  import {
12
9
  FileSys2
13
- } from "./index-bns3wcpc.js";
10
+ } from "./index-by2tvsq6.js";
14
11
  import {
15
12
  CliError
16
13
  } from "./index-j4yvgfhr.js";
14
+ import {
15
+ AppExecutor2
16
+ } from "./index-z92zm3wd.js";
17
+ import {
18
+ LibExecutor2
19
+ } from "./index-zfnz878d.js";
20
+ import {
21
+ PkgExecutor2
22
+ } from "./index-w1zexzpx.js";
17
23
  import {
18
24
  UNAVAILABLE_REDIS_HOST,
19
25
  redisTunnelPolicy,
@@ -49,33 +55,33 @@ import {
49
55
  filesChangedSince,
50
56
  HmrWatcher,
51
57
  WatchRootResolver
52
- } from "./index-vm0dn0mt.js";
58
+ } from "./index-dmcpetwe.js";
53
59
  import {
54
60
  runner,
55
61
  assertPromptable
56
- } from "./index-exn38bzx.js";
62
+ } from "./index-2yn3r67f.js";
57
63
  import {
58
64
  UpdatePackFolder,
59
65
  UpdateUploader,
60
66
  NativePublicEnv,
61
67
  NativeApp
62
- } from "./index-43f4h4cm.js";
68
+ } from "./index-ebn9kgea.js";
63
69
  import {
64
70
  DesktopServerStage
65
- } from "./index-an76bdrv.js";
71
+ } from "./index-612fdtbk.js";
66
72
  import {
67
73
  resolveMobileTargets,
68
74
  resolveAppId
69
75
  } from "./index-m9jj544v.js";
70
76
  import {
71
77
  SlicePlanner
72
- } from "./index-gcx48get.js";
78
+ } from "./index-j592zfqc.js";
73
79
  import {
74
80
  openBrowser
75
81
  } from "./index-9dp031by.js";
76
82
  import {
77
83
  ShellOnlyEnv
78
- } from "./index-yf9wc28h.js";
84
+ } from "./index-bejy9zyc.js";
79
85
  import {
80
86
  ConfigLock
81
87
  } from "./index-bqbf654f.js";
@@ -85,13 +91,12 @@ import { existsSync, realpathSync as realpathSync2 } from "fs";
85
91
  import path7 from "path";
86
92
 
87
93
  // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
88
- import path4 from "path";
89
- import { Logger as Logger2, RestartSchedule as RestartSchedule2 } from "akanjs/common";
94
+ import { Logger as Logger2 } from "akanjs/common";
90
95
 
91
- // pkgs/@akanjs/devkit/createTunnel.ts
96
+ // pkgs/@akanjs/devkit/tunnel/createTunnel.ts
92
97
  import { readFileSync } from "fs";
93
98
 
94
- // pkgs/@akanjs/devkit/sshHostKeys.ts
99
+ // pkgs/@akanjs/devkit/tunnel/sshHostKeys.ts
95
100
  import { createHash } from "crypto";
96
101
  import { mkdir, rm, writeFile } from "fs/promises";
97
102
  import path from "path";
@@ -138,7 +143,7 @@ class SshHostKeys {
138
143
  }
139
144
  }
140
145
 
141
- // pkgs/@akanjs/devkit/sshTunnel.ts
146
+ // pkgs/@akanjs/devkit/tunnel/sshTunnel.ts
142
147
  import { Client } from "ssh2";
143
148
  var closeQuietly = (close) => {
144
149
  try {
@@ -246,7 +251,7 @@ var closeBunSocket = (socket, error) => {
246
251
  closeQuietly(() => socket.end());
247
252
  };
248
253
 
249
- // pkgs/@akanjs/devkit/createTunnel.ts
254
+ // pkgs/@akanjs/devkit/tunnel/createTunnel.ts
250
255
  var tunnelEnv = new ShellOnlyEnv([
251
256
  "SSH_TUNNEL_PRIVATE_KEY_PATH",
252
257
  "SSH_TUNNEL_PASSPHRASE",
@@ -324,9 +329,322 @@ var createTunnel = async (service, { app, environment, port = service === "postg
324
329
  }
325
330
  return `localhost:${port}`;
326
331
  };
332
+
333
+ // pkgs/@akanjs/devkit/akanApp/BackendImportGraph.ts
334
+ import { stat } from "fs/promises";
335
+ import path2 from "path";
336
+ var NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav|html)$/i;
337
+ var GRAPH_IMPORT_KINDS = new Set([
338
+ "import-statement",
339
+ "require-call",
340
+ "require-resolve",
341
+ "dynamic-import"
342
+ ]);
343
+
344
+ class BackendImportGraph {
345
+ #app;
346
+ #logger;
347
+ #tsTranspiler = new Bun.Transpiler({ loader: "ts" });
348
+ #tsxTranspiler = new Bun.Transpiler({ loader: "tsx" });
349
+ #jsTranspiler = new Bun.Transpiler({ loader: "js" });
350
+ #jsxTranspiler = new Bun.Transpiler({ loader: "jsx" });
351
+ #files = new Set;
352
+ #scanCache = new Map;
353
+ #ready = false;
354
+ #lastRefreshSucceeded = false;
355
+ constructor(app, logger) {
356
+ this.#app = app;
357
+ this.#logger = logger;
358
+ }
359
+ get ready() {
360
+ return this.#ready;
361
+ }
362
+ get lastRefreshSucceeded() {
363
+ return this.#lastRefreshSucceeded;
364
+ }
365
+ has(file) {
366
+ return this.#files.has(path2.resolve(file));
367
+ }
368
+ async fingerprint() {
369
+ const stamps = await Promise.all([...this.#files].map(async (file) => {
370
+ const stats = await stat(file).catch(() => null);
371
+ return [file, stats ? `${Math.round(stats.mtimeMs)}:${stats.size}` : "(gone)"];
372
+ }));
373
+ return new Map(stamps);
374
+ }
375
+ async refresh() {
376
+ try {
377
+ const files = await this.#build();
378
+ this.#files = files;
379
+ this.#ready = true;
380
+ this.#lastRefreshSucceeded = true;
381
+ this.#logger.verbose(`[backend-graph] scanned ${files.size} files`);
382
+ return true;
383
+ } catch (err) {
384
+ this.#ready = this.#files.size > 0;
385
+ this.#lastRefreshSucceeded = false;
386
+ this.#logger.warn(`[backend-graph] scan failed; ${this.#ready ? "using previous graph" : "using fallback rules"}: ${err instanceof Error ? err.message : String(err)}`);
387
+ return this.#ready;
388
+ }
389
+ }
390
+ async#build() {
391
+ const roots = await this.#entrypoints();
392
+ const files = new Set;
393
+ const queue = [...roots];
394
+ const workspaceRoot = path2.resolve(this.#app.workspace.workspaceRoot);
395
+ while (queue.length > 0) {
396
+ const current = path2.resolve(queue.pop());
397
+ if (files.has(current))
398
+ continue;
399
+ if (!this.#isWorkspaceSource(current, workspaceRoot))
400
+ continue;
401
+ const imports = await this.#importsOf(current);
402
+ if (!imports)
403
+ continue;
404
+ files.add(current);
405
+ const importerDir = path2.dirname(current);
406
+ for (const imp of imports) {
407
+ if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
408
+ continue;
409
+ const resolved = this.#resolve(imp.path, importerDir);
410
+ if (!resolved || files.has(resolved))
411
+ continue;
412
+ queue.push(resolved);
413
+ }
414
+ }
415
+ for (const cached of this.#scanCache.keys())
416
+ if (!files.has(cached))
417
+ this.#scanCache.delete(cached);
418
+ return files;
419
+ }
420
+ async#importsOf(file) {
421
+ const stats = await stat(file).catch(() => null);
422
+ if (!stats?.isFile())
423
+ return null;
424
+ const mtimeMs = Math.round(stats.mtimeMs);
425
+ const cached = this.#scanCache.get(file);
426
+ if (cached && cached.mtimeMs === mtimeMs && cached.size === stats.size)
427
+ return cached.specifiers;
428
+ const specifiers = this.#scanImports(file, await Bun.file(file).text());
429
+ this.#scanCache.set(file, { mtimeMs, size: stats.size, specifiers });
430
+ return specifiers;
431
+ }
432
+ async#entrypoints() {
433
+ const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
434
+ const existing = [];
435
+ for (const root of roots) {
436
+ const abs = path2.resolve(root);
437
+ if (await Bun.file(abs).exists())
438
+ existing.push(abs);
439
+ }
440
+ return existing;
441
+ }
442
+ #resolve(specifier, importerDir) {
443
+ try {
444
+ const resolved = Bun.resolveSync(specifier, importerDir);
445
+ if (!path2.isAbsolute(resolved))
446
+ return null;
447
+ if (!SOURCE_EXTS.has(path2.extname(resolved).toLowerCase()))
448
+ return null;
449
+ return path2.resolve(resolved);
450
+ } catch {
451
+ return null;
452
+ }
453
+ }
454
+ #isWorkspaceSource(file, workspaceRoot) {
455
+ const rel = path2.relative(workspaceRoot, file);
456
+ if (rel.startsWith("..") || path2.isAbsolute(rel))
457
+ return false;
458
+ if (rel.includes(`${path2.sep}node_modules${path2.sep}`) || rel.includes(`${path2.sep}.akan${path2.sep}`))
459
+ return false;
460
+ return SOURCE_EXTS.has(path2.extname(file).toLowerCase());
461
+ }
462
+ #scanImports(file, source) {
463
+ const ext = path2.extname(file).toLowerCase();
464
+ if (ext === ".tsx")
465
+ return this.#tsxTranspiler.scanImports(source);
466
+ if (ext === ".jsx")
467
+ return this.#jsxTranspiler.scanImports(source);
468
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
469
+ return this.#jsTranspiler.scanImports(source);
470
+ return this.#tsTranspiler.scanImports(source);
471
+ }
472
+ }
473
+
474
+ // pkgs/@akanjs/devkit/akanApp/builderGap.ts
475
+ class BuilderGap {
476
+ #graph;
477
+ #backend;
478
+ #logger;
479
+ #stamp = null;
480
+ constructor({ graph, backend, logger }) {
481
+ this.#graph = graph;
482
+ this.#backend = backend;
483
+ this.#logger = logger;
484
+ }
485
+ open(reason) {
486
+ if (this.#stamp)
487
+ return;
488
+ if (!this.#graph.ready) {
489
+ this.#logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
490
+ return;
491
+ }
492
+ this.#stamp = this.#graph.fingerprint().then((stamps) => {
493
+ this.#logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
494
+ return stamps;
495
+ }).catch((err) => {
496
+ this.#logger.warn(`[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`);
497
+ return null;
498
+ });
499
+ }
500
+ async take() {
501
+ const stamping = this.#stamp;
502
+ this.#stamp = null;
503
+ const before = stamping ? await stamping : null;
504
+ if (!before)
505
+ return [];
506
+ const moved = filesChangedSince(before, await this.#graph.fingerprint());
507
+ if (moved.length === 0) {
508
+ this.#logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
509
+ return moved;
510
+ }
511
+ this.#logger.info(`[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`);
512
+ return moved;
513
+ }
514
+ discard(reason) {
515
+ if (!this.#stamp)
516
+ return;
517
+ this.#stamp = null;
518
+ this.#logger.verbose(`[builder-gap] stamps dropped (${reason})`);
519
+ }
520
+ async restartBackendForChanges() {
521
+ const moved = await this.take();
522
+ if (moved.length === 0)
523
+ return;
524
+ this.#backend.scheduleRestart({ files: moved, roles: [] });
525
+ }
526
+ }
527
+
528
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderRequestRouter.ts
529
+ class BuilderRequestRouter {
530
+ #generation = 0;
531
+ #nextId = 1;
532
+ #inFlight = new Map;
533
+ get generation() {
534
+ return this.#generation;
535
+ }
536
+ get inFlightCount() {
537
+ return this.#inFlight.size;
538
+ }
539
+ startGeneration() {
540
+ this.#generation += 1;
541
+ this.#inFlight.clear();
542
+ return this.#generation;
543
+ }
544
+ issue(message) {
545
+ const id = this.#nextId++;
546
+ this.#inFlight.set(id, { backendId: message.id, generation: this.#generation });
547
+ return { ...message, id };
548
+ }
549
+ withdraw(id) {
550
+ this.#inFlight.delete(id);
551
+ }
552
+ settle(message) {
553
+ const request = this.#inFlight.get(message.id);
554
+ if (!request)
555
+ return null;
556
+ this.#inFlight.delete(message.id);
557
+ if (request.generation !== this.#generation)
558
+ return null;
559
+ return { ...message, id: request.backendId };
560
+ }
561
+ }
562
+
563
+ // pkgs/@akanjs/devkit/akanApp/builderRequestRelay.ts
564
+ class BuilderRequestRelay {
565
+ #logger;
566
+ #env;
567
+ #links;
568
+ #requests = new BuilderRequestRouter;
569
+ #held = [];
570
+ constructor({ logger, env }, links) {
571
+ this.#logger = logger;
572
+ this.#env = env;
573
+ this.#links = links;
574
+ }
575
+ startGeneration() {
576
+ this.#requests.startGeneration();
577
+ }
578
+ settle(message) {
579
+ return this.#requests.settle(message);
580
+ }
581
+ send(message) {
582
+ this.#links.markActivity();
583
+ if (this.#links.away()) {
584
+ this.#held.push(message);
585
+ this.#links.wake(`${message.type} arrived while suspended`);
586
+ return;
587
+ }
588
+ if (message.type === "build-csr" && !message.shell && this.#env.AKAN_DEV_CSR_REBUILD !== "1") {
589
+ Object.assign(this.#env, { AKAN_DEV_CSR_REBUILD: "1" });
590
+ this.#logger.verbose(`[csr] armed dev CSR rebuilds (${message.reason})`);
591
+ }
592
+ const builder = this.#links.builder();
593
+ if (message.type === "build-route" || message.type === "build-csr" || message.type === "build-graph") {
594
+ const outgoing = this.#requests.issue(message);
595
+ if (builder?.send(outgoing))
596
+ return;
597
+ this.#requests.withdraw(outgoing.id);
598
+ } else if (builder?.send(message))
599
+ return;
600
+ const status = builder?.status ?? "stopped";
601
+ if (shouldHoldForReturningBuilder({ status, heldCount: this.#held.length })) {
602
+ this.#held.push(message);
603
+ const request = message.type === "build-route" ? `build-route ${message.routeId}` : message.type;
604
+ this.#logger.verbose(`[builder] holding ${request} until the builder is ready (${this.#held.length} waiting)`);
605
+ return;
606
+ }
607
+ if (this.#failRequest(message, `builder is ${status}; reload after the builder is ready`))
608
+ return;
609
+ this.#logger.warn("akanAppHost builder is not running");
610
+ }
611
+ flush() {
612
+ const pending = this.#held.splice(0);
613
+ if (pending.length === 0)
614
+ return;
615
+ this.#logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
616
+ for (const message of pending)
617
+ this.send(message);
618
+ }
619
+ discard(reason) {
620
+ const held = this.#held.splice(0);
621
+ if (held.length === 0)
622
+ return;
623
+ this.#logger.verbose(`[builder] dropped ${held.length} held builder request(s): ${reason}`);
624
+ }
625
+ fail(reason) {
626
+ const held = this.#held.splice(0);
627
+ if (held.length === 0)
628
+ return;
629
+ this.#logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
630
+ for (const message of held)
631
+ this.#failRequest(message, reason);
632
+ }
633
+ #failRequest(message, error) {
634
+ if (message.type === "build-route")
635
+ this.#links.toBackend({ type: "build-route-res", id: message.id, ok: false, error, kind: "unavailable" });
636
+ else if (message.type === "build-csr")
637
+ this.#links.toBackend({ type: "build-csr-res", id: message.id, ok: false, error, kind: "unavailable" });
638
+ else if (message.type === "build-graph")
639
+ this.#links.toBackend({ type: "build-graph-res", id: message.id, ok: false, error, kind: "unavailable" });
640
+ else
641
+ return false;
642
+ return true;
643
+ }
644
+ }
327
645
  // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.host.ts
328
646
  import fs from "fs";
329
- import path2 from "path";
647
+ import path3 from "path";
330
648
  import { Logger, RestartSchedule } from "akanjs/common";
331
649
  import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
332
650
  import { MemoryLimit } from "akanjs/server/memoryLimit";
@@ -471,7 +789,7 @@ class IncrementalBuilderHost {
471
789
  this.logger.verbose(`builder spawned pid=${proc.pid} entry=${this.entry}${isRestart ? " restart=1" : ""}`);
472
790
  }
473
791
  #checkPatchingMarker(afterCrash) {
474
- const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) => path2.join(this.app.cwdPath, ".akan/artifact", dirName, CSR_DEV_PATCHING_MARKER)).filter((marker) => fs.existsSync(marker));
792
+ const markers = [CSR_DEV_DIRNAME, SSR_DEV_DIRNAME].map((dirName) => path3.join(this.app.cwdPath, ".akan/artifact", dirName, CSR_DEV_PATCHING_MARKER)).filter((marker) => fs.existsSync(marker));
475
793
  if (markers.length === 0)
476
794
  return;
477
795
  if (afterCrash && !this.#patcherOff) {
@@ -583,10 +901,10 @@ class IncrementalBuilderHost {
583
901
  patcherOff = false
584
902
  } = {}) {
585
903
  const candidates = [
586
- path2.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
587
- path2.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
588
- path2.join(import.meta.dir, "incrementalBuilder.proc.js"),
589
- path2.join(import.meta.dir, "incrementalBuilder.proc.ts")
904
+ path3.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
905
+ path3.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
906
+ path3.join(import.meta.dir, "incrementalBuilder.proc.js"),
907
+ path3.join(import.meta.dir, "incrementalBuilder.proc.ts")
590
908
  ];
591
909
  for (const c of candidates)
592
910
  if (await Bun.file(c).exists())
@@ -594,650 +912,664 @@ class IncrementalBuilderHost {
594
912
  throw new Error(`[cli] frontend builder entry not found; looked in: ${candidates.join(", ")}`);
595
913
  }
596
914
  }
597
- // pkgs/@akanjs/devkit/incrementalBuilder/builderRequestRouter.ts
598
- class BuilderRequestRouter {
599
- #generation = 0;
600
- #nextId = 1;
601
- #inFlight = new Map;
602
- get generation() {
603
- return this.#generation;
915
+ // pkgs/@akanjs/devkit/akanApp/processRss.ts
916
+ var PS_RSS_TIMEOUT_MS = 2000;
917
+
918
+ class ProcessRss {
919
+ static async bytesOf(pid) {
920
+ if (process.platform === "win32")
921
+ return await ProcessRss.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], ProcessRss.#tasklistRssKb);
922
+ if (process.platform === "darwin") {
923
+ const footprintBytes = await ProcessRss.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], ProcessRss.#footprintKb);
924
+ if (footprintBytes !== null)
925
+ return footprintBytes;
926
+ }
927
+ const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
928
+ const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
929
+ if (vmRssKb)
930
+ return Number(vmRssKb) * 1024;
931
+ return await ProcessRss.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
604
932
  }
605
- get inFlightCount() {
606
- return this.#inFlight.size;
607
- }
608
- startGeneration() {
609
- this.#generation += 1;
610
- this.#inFlight.clear();
611
- return this.#generation;
612
- }
613
- issue(message) {
614
- const id = this.#nextId++;
615
- this.#inFlight.set(id, { backendId: message.id, generation: this.#generation });
616
- return { ...message, id };
617
- }
618
- withdraw(id) {
619
- this.#inFlight.delete(id);
620
- }
621
- settle(message) {
622
- const request = this.#inFlight.get(message.id);
623
- if (!request)
933
+ static async#readRssKbVia(command, parseKb, timeoutMs = PS_RSS_TIMEOUT_MS) {
934
+ let proc;
935
+ try {
936
+ proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
937
+ } catch {
624
938
  return null;
625
- this.#inFlight.delete(message.id);
626
- if (request.generation !== this.#generation)
939
+ }
940
+ const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
941
+ try {
942
+ const output = await new Response(proc.stdout).text();
943
+ await proc.exited;
944
+ const rssKb = parseKb(output);
945
+ return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
946
+ } catch {
627
947
  return null;
628
- return { ...message, id: request.backendId };
948
+ } finally {
949
+ clearTimeout(killer);
950
+ }
951
+ }
952
+ static #tasklistRssKb(output) {
953
+ const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
954
+ return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
955
+ }
956
+ static #footprintKb(output) {
957
+ const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
958
+ return bytes ? Number(bytes) / 1024 : Number.NaN;
629
959
  }
630
960
  }
631
961
 
632
- // pkgs/@akanjs/devkit/akanApp/BackendImportGraph.ts
633
- import { stat } from "fs/promises";
634
- import path3 from "path";
635
- var NON_SOURCE_EXT_RE = /\.(css|scss|sass|less|json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav|html)$/i;
636
- var GRAPH_IMPORT_KINDS = new Set([
637
- "import-statement",
638
- "require-call",
639
- "require-resolve",
640
- "dynamic-import"
641
- ]);
962
+ // pkgs/@akanjs/devkit/akanApp/builderRssRecycler.ts
963
+ var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
964
+ var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
965
+ var BUILDER_RSS_SETTLE_MS = 20000;
642
966
 
643
- class BackendImportGraph {
644
- #app;
967
+ class BuilderRssRecycler {
645
968
  #logger;
646
- #tsTranspiler = new Bun.Transpiler({ loader: "ts" });
647
- #tsxTranspiler = new Bun.Transpiler({ loader: "tsx" });
648
- #jsTranspiler = new Bun.Transpiler({ loader: "js" });
649
- #jsxTranspiler = new Bun.Transpiler({ loader: "jsx" });
650
- #files = new Set;
651
- #scanCache = new Map;
652
- #ready = false;
653
- #lastRefreshSucceeded = false;
654
- constructor(app, logger) {
655
- this.#app = app;
969
+ #statuses;
970
+ #links;
971
+ #timer = null;
972
+ #reason = null;
973
+ #lastRecycleAtMono = null;
974
+ #ceilingTightReports = 0;
975
+ #ceilingTightWarned = false;
976
+ #settleToken = 0;
977
+ #over = null;
978
+ #ceilingAbandoned = false;
979
+ constructor({ logger, statuses }, links) {
656
980
  this.#logger = logger;
981
+ this.#statuses = statuses;
982
+ this.#links = links;
657
983
  }
658
- get ready() {
659
- return this.#ready;
660
- }
661
- get lastRefreshSucceeded() {
662
- return this.#lastRefreshSucceeded;
663
- }
664
- has(file) {
665
- return this.#files.has(path3.resolve(file));
984
+ get armed() {
985
+ return !!this.#reason;
666
986
  }
667
- async fingerprint() {
668
- const stamps = await Promise.all([...this.#files].map(async (file) => {
669
- const stats = await stat(file).catch(() => null);
670
- return [file, stats ? `${Math.round(stats.mtimeMs)}:${stats.size}` : "(gone)"];
671
- }));
672
- return new Map(stamps);
673
- }
674
- async refresh() {
675
- try {
676
- const files = await this.#build();
677
- this.#files = files;
678
- this.#ready = true;
679
- this.#lastRefreshSucceeded = true;
680
- this.#logger.verbose(`[backend-graph] scanned ${files.size} files`);
681
- return true;
682
- } catch (err) {
683
- this.#ready = this.#files.size > 0;
684
- this.#lastRefreshSucceeded = false;
685
- this.#logger.warn(`[backend-graph] scan failed; ${this.#ready ? "using previous graph" : "using fallback rules"}: ${err instanceof Error ? err.message : String(err)}`);
686
- return this.#ready;
987
+ handleMetrics(metrics) {
988
+ if (this.#ceilingAbandoned)
989
+ return;
990
+ const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
991
+ const decision = decideBuilderRssRecycle({
992
+ rssBytes: metrics.rssBytes,
993
+ ceilingBytes,
994
+ buildFailed: this.#statuses.failedAt(metrics.generation),
995
+ msSinceLastRecycle: this.#lastRecycleAtMono === null ? null : performance.now() - this.#lastRecycleAtMono
996
+ });
997
+ if (decision === "below-ceiling") {
998
+ this.#ceilingTightReports = 0;
999
+ return;
687
1000
  }
688
- }
689
- async#build() {
690
- const roots = await this.#entrypoints();
691
- const files = new Set;
692
- const queue = [...roots];
693
- const workspaceRoot = path3.resolve(this.#app.workspace.workspaceRoot);
694
- while (queue.length > 0) {
695
- const current = path3.resolve(queue.pop());
696
- if (files.has(current))
697
- continue;
698
- if (!this.#isWorkspaceSource(current, workspaceRoot))
699
- continue;
700
- const imports = await this.#importsOf(current);
701
- if (!imports)
702
- continue;
703
- files.add(current);
704
- const importerDir = path3.dirname(current);
705
- for (const imp of imports) {
706
- if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
707
- continue;
708
- const resolved = this.#resolve(imp.path, importerDir);
709
- if (!resolved || files.has(resolved))
710
- continue;
711
- queue.push(resolved);
712
- }
1001
+ if (decision === "unbounded")
1002
+ return;
1003
+ if (decision === "build-failed") {
1004
+ this.#logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
1005
+ return;
713
1006
  }
714
- for (const cached of this.#scanCache.keys())
715
- if (!files.has(cached))
716
- this.#scanCache.delete(cached);
717
- return files;
718
- }
719
- async#importsOf(file) {
720
- const stats = await stat(file).catch(() => null);
721
- if (!stats?.isFile())
722
- return null;
723
- const mtimeMs = Math.round(stats.mtimeMs);
724
- const cached = this.#scanCache.get(file);
725
- if (cached && cached.mtimeMs === mtimeMs && cached.size === stats.size)
726
- return cached.specifiers;
727
- const specifiers = this.#scanImports(file, await Bun.file(file).text());
728
- this.#scanCache.set(file, { mtimeMs, size: stats.size, specifiers });
729
- return specifiers;
730
- }
731
- async#entrypoints() {
732
- const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
733
- const existing = [];
734
- for (const root of roots) {
735
- const abs = path3.resolve(root);
736
- if (await Bun.file(abs).exists())
737
- existing.push(abs);
1007
+ if (decision === "too-soon") {
1008
+ this.#ceilingTightReports += 1;
1009
+ if (this.#ceilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#ceilingTightReports))
1010
+ return;
1011
+ this.#ceilingTightWarned = true;
1012
+ this.#logger.warn(`[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.`);
1013
+ return;
738
1014
  }
739
- return existing;
1015
+ this.#arm(`rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`, {
1016
+ rssBytes: metrics.rssBytes,
1017
+ ceilingBytes: ceilingBytes ?? 0
1018
+ });
740
1019
  }
741
- #resolve(specifier, importerDir) {
742
- try {
743
- const resolved = Bun.resolveSync(specifier, importerDir);
744
- if (!path3.isAbsolute(resolved))
745
- return null;
746
- if (!SOURCE_EXTS.has(path3.extname(resolved).toLowerCase()))
747
- return null;
748
- return path3.resolve(resolved);
749
- } catch {
750
- return null;
751
- }
1020
+ async checkRecycledFloor() {
1021
+ if (this.#ceilingAbandoned || this.#lastRecycleAtMono === null)
1022
+ return;
1023
+ const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
1024
+ const pid = this.#links.builder()?.pid;
1025
+ if (!ceilingBytes || !pid)
1026
+ return;
1027
+ const freshRssBytes = await ProcessRss.bytesOf(pid);
1028
+ if (!isRssCeilingUnreachable(freshRssBytes, ceilingBytes))
1029
+ return;
1030
+ this.#ceilingAbandoned = true;
1031
+ this.#logger.error(`[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.`);
752
1032
  }
753
- #isWorkspaceSource(file, workspaceRoot) {
754
- const rel = path3.relative(workspaceRoot, file);
755
- if (rel.startsWith("..") || path3.isAbsolute(rel))
756
- return false;
757
- if (rel.includes(`${path3.sep}node_modules${path3.sep}`) || rel.includes(`${path3.sep}.akan${path3.sep}`))
758
- return false;
759
- return SOURCE_EXTS.has(path3.extname(file).toLowerCase());
1033
+ rearm() {
1034
+ if (this.#reason)
1035
+ this.#arm(this.#reason);
760
1036
  }
761
- #scanImports(file, source) {
762
- const ext = path3.extname(file).toLowerCase();
763
- if (ext === ".tsx")
764
- return this.#tsxTranspiler.scanImports(source);
765
- if (ext === ".jsx")
766
- return this.#jsxTranspiler.scanImports(source);
767
- if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
768
- return this.#jsTranspiler.scanImports(source);
769
- return this.#tsTranspiler.scanImports(source);
1037
+ cancel() {
1038
+ this.#reason = null;
1039
+ this.#over = null;
1040
+ this.#settleToken += 1;
1041
+ if (!this.#timer)
1042
+ return;
1043
+ clearTimeout(this.#timer);
1044
+ this.#timer = null;
770
1045
  }
771
- }
772
-
773
- // pkgs/@akanjs/devkit/akanApp/devBootLatch.ts
774
- class DevBootLatch {
775
- #onBooted;
776
- #waitMs;
777
- #ready = false;
778
- #armed = false;
779
- #booted = false;
780
- #timer = null;
781
- constructor(onBooted, { waitMs = 30000 } = {}) {
782
- this.#onBooted = onBooted;
783
- this.#waitMs = waitMs;
1046
+ #arm(reason, over) {
1047
+ if (this.#reason !== reason)
1048
+ this.#logger.verbose(`[builder-recycle] armed (${reason}); replacing the builder once it stays quiet`);
1049
+ this.#reason = reason;
1050
+ if (over)
1051
+ this.#over = over;
1052
+ if (this.#timer)
1053
+ clearTimeout(this.#timer);
1054
+ this.#timer = setTimeout(() => {
1055
+ this.#timer = null;
1056
+ const pendingReason = this.#reason;
1057
+ const pendingOver = this.#over;
1058
+ this.#reason = null;
1059
+ this.#over = null;
1060
+ if (!pendingReason)
1061
+ return;
1062
+ if (!pendingOver) {
1063
+ this.#recycle(pendingReason);
1064
+ return;
1065
+ }
1066
+ this.#recycleWhenStillOver(pendingReason, pendingOver);
1067
+ }, BUILDER_RSS_RECYCLE_QUIET_MS);
784
1068
  }
785
- ready() {
786
- this.#ready = true;
787
- if (!this.#armed && !this.#timer) {
788
- this.#timer = setTimeout(() => this.armed(), this.#waitMs);
789
- this.#timer.unref?.();
1069
+ async#recycleWhenStillOver(reason, { rssBytes, ceilingBytes }) {
1070
+ if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
1071
+ this.#recycle(reason);
1072
+ return;
790
1073
  }
791
- this.#release();
792
- }
793
- armed() {
794
- this.#armed = true;
795
- this.#release();
1074
+ const pid = this.#links.builder()?.pid;
1075
+ if (!pid) {
1076
+ this.#recycle(reason);
1077
+ return;
1078
+ }
1079
+ this.#settleToken += 1;
1080
+ const token = this.#settleToken;
1081
+ this.#logger.verbose(`[builder-recycle] holding ${Math.round(BUILDER_RSS_SETTLE_MS / 1000)}s to see whether the allocator returns it (${reason})`);
1082
+ await Bun.sleep(BUILDER_RSS_SETTLE_MS);
1083
+ if (token !== this.#settleToken || this.#links.builder()?.pid !== pid || this.#links.away()) {
1084
+ this.#logger.verbose("[builder-recycle] settle check abandoned; the builder moved on");
1085
+ return;
1086
+ }
1087
+ const settledBytes = await ProcessRss.bytesOf(pid);
1088
+ if (settledBytes !== null && settledBytes < ceilingBytes) {
1089
+ this.#logger.info(`[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`);
1090
+ return;
1091
+ }
1092
+ this.#recycle(settledBytes === null ? reason : `${reason}; still ${asMib(settledBytes)}MiB after settling`);
796
1093
  }
797
- #release() {
798
- if (this.#booted || !this.#ready || !this.#armed)
1094
+ #recycle(reason) {
1095
+ if (this.#links.restartQueued()) {
1096
+ this.#logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
799
1097
  return;
800
- this.#booted = true;
801
- if (this.#timer)
802
- clearTimeout(this.#timer);
803
- this.#timer = null;
804
- this.#onBooted();
1098
+ }
1099
+ if (!this.#links.builder()?.recycle(reason))
1100
+ return;
1101
+ this.#lastRecycleAtMono = performance.now();
1102
+ this.#links.onRecycle();
805
1103
  }
806
1104
  }
807
1105
 
808
- // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
1106
+ // pkgs/@akanjs/devkit/akanApp/devBackend.ts
1107
+ import { RestartSchedule as RestartSchedule2 } from "akanjs/common";
809
1108
  var backendMsgTypeSet = new Set(["build-route", "build-csr", "build-graph"]);
810
- var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
811
1109
  var BACKEND_RESTART_DEBOUNCE_MS = 120;
812
1110
  var BACKEND_GRACEFUL_TIMEOUT_MS = 8000;
813
1111
  var BACKEND_STDERR_TAIL_LIMIT = 40;
814
- var BUILDER_READY_TIMEOUT_MS = 150000;
815
- var BUILDER_START_MAX_ATTEMPTS = 3;
816
- var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
817
- var BUILDER_RSS_SETTLE_MS = 20000;
818
- var PS_RSS_TIMEOUT_MS = 2000;
819
1112
 
820
- class AkanAppHost {
821
- app;
822
- logger = new Logger2("AkanAppHost");
823
- stdio;
824
- env;
825
- #onDevEvent;
826
- #lastDevState = null;
827
- #bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
828
- #backend = null;
829
- #builder = null;
830
- #patcherOff = false;
831
- #backendReady = false;
832
- #plannedBackendStops = new WeakSet;
1113
+ class DevBackend {
1114
+ #app;
1115
+ #env;
1116
+ #stdio;
1117
+ #logger;
1118
+ #statuses;
1119
+ #graph;
1120
+ #links;
1121
+ #process = null;
1122
+ #ready = false;
1123
+ #plannedStops = new WeakSet;
833
1124
  #restartTimer = null;
834
- #backendRecovery = new RestartSchedule2(backendRecoveryPolicy);
835
- #backendGaveUp = false;
836
- #backendLifecycleState = "stopped";
1125
+ #recovery = new RestartSchedule2(backendRecoveryPolicy);
1126
+ #gaveUp = false;
1127
+ #lifecycleState = "stopped";
837
1128
  #pendingRestartReason = null;
838
- #backendRestart = null;
839
- #pendingRecycle = null;
840
- #restartFailedAfterApply = null;
841
- #stopping = false;
842
- #builderRecovery = new RestartSchedule2({ min: 2000, max: 60000 });
843
- #abandonBuilderStart = null;
844
- #backendStartStatus = null;
845
- #backendBuildStatusGeneration = 0;
846
- #backendStderrTail = [];
847
- #lastGoodFrontend = {};
848
- #rssRecycleTimer = null;
849
- #rssRecycleReason = null;
850
- #lastRssRecycleAtMono = null;
851
- #rssCeilingTightReports = 0;
852
- #rssCeilingTightWarned = false;
853
- #rssSettleToken = 0;
854
- #rssRecycleOver = null;
855
- #rssCeilingAbandoned = false;
856
- #buildStatusByPhase = new Map;
857
- #pendingBuildStatusReplay = [];
858
- #builderMessageQueue = Promise.resolve();
859
- #backendGraph;
860
- #idleSuspendTimer = null;
861
- #suspended = false;
862
- #waking = false;
863
- #wokeAtMono = null;
864
- #idleWatcher = null;
865
- #suspendedChanges = null;
866
- #builderGapStamp = null;
867
- #pendingBuilderMessages = [];
868
- #builderRequests = new BuilderRequestRouter;
869
- #builderGeneration = 0;
1129
+ #restart = null;
1130
+ #startStatus = null;
1131
+ #stderrTail = [];
1132
+ #queuedStatuses = [];
870
1133
  constructor(app, {
871
1134
  env,
872
- stdio = "inherit",
873
- onDevEvent
874
- }) {
875
- this.app = app;
876
- this.env = env;
877
- this.stdio = stdio;
878
- this.#onDevEvent = onDevEvent ?? null;
879
- this.#backendGraph = new BackendImportGraph(app, this.logger);
1135
+ stdio,
1136
+ logger,
1137
+ statuses,
1138
+ graph
1139
+ }, links) {
1140
+ this.#app = app;
1141
+ this.#env = env;
1142
+ this.#stdio = stdio;
1143
+ this.#logger = logger;
1144
+ this.#statuses = statuses;
1145
+ this.#graph = graph;
1146
+ this.#links = links;
880
1147
  }
881
- #emitDevEvent(state, detail) {
882
- if (!this.#onDevEvent || state === this.#lastDevState)
883
- return;
884
- this.#lastDevState = state;
885
- this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
886
- if (state === "ready")
887
- this.#bootLatch.ready();
1148
+ get running() {
1149
+ return !!this.#process;
888
1150
  }
889
- async start() {
890
- if (this.#backend)
891
- await this.#stopBackend();
892
- if (this.#builder)
893
- this.#stopBuilder();
894
- const [redisHost] = await Promise.all([
895
- this.#prepareDatabase("redis"),
896
- this.#backendGraph.refresh(),
897
- this.#startBuilder()
898
- ]);
899
- Object.assign(this.env, { REDIS_HOST: redisHost });
900
- this.#startBackend();
901
- this.#armIdleSuspend();
902
- return this;
1151
+ get ready() {
1152
+ return this.#ready;
903
1153
  }
904
- async stop() {
905
- this.#stopping = true;
906
- this.#pendingRecycle = null;
907
- this.#cancelIdleSuspend();
908
- this.#stopIdleWatcher();
909
- this.#clearRestartTimers();
910
- this.#abandonBuilderStart?.(new Error("dev server stopped before the builder was ready"));
911
- this.#pendingRestartReason = null;
912
- this.#failPendingBuilderMessages("dev server is shutting down");
913
- await this.#backendRestart;
914
- await this.#stopBackend();
915
- this.#stopBuilder();
916
- return this;
1154
+ get gaveUp() {
1155
+ return this.#gaveUp;
917
1156
  }
918
- #clearRestartTimers() {
919
- if (this.#restartTimer)
920
- clearTimeout(this.#restartTimer);
921
- this.#restartTimer = null;
922
- this.#backendRecovery.cancel();
923
- this.#builderRecovery.cancel();
1157
+ get lifecycleState() {
1158
+ return this.#lifecycleState;
924
1159
  }
925
- kill() {
926
- this.stop();
1160
+ get restartScheduled() {
1161
+ return !!this.#restartTimer;
927
1162
  }
928
- async#prepareDatabase(type) {
929
- const environment = WorkspaceExecutor.getBaseDevEnv().env;
930
- const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
931
- if (policy === "none")
932
- return "localhost";
933
- if (policy === "required")
934
- return await createTunnel(type, { app: this.app, environment });
935
- try {
936
- return await createTunnel(type, { app: this.app, environment });
937
- } catch (error) {
938
- this.logger.warn(`${error instanceof Error ? error.message : String(error)} - continuing without Redis: the single database mode does not use it unless an app adaptor does`);
939
- return UNAVAILABLE_REDIS_HOST;
940
- }
1163
+ get recovering() {
1164
+ return this.#recovery.pending;
941
1165
  }
942
- #startBackend(startStatus = null) {
943
- if (this.#stopping)
1166
+ get restartPending() {
1167
+ return !!(this.#restartTimer || this.#restart || this.#recovery.pending);
1168
+ }
1169
+ get restarting() {
1170
+ return this.#restart;
1171
+ }
1172
+ start(startStatus = null) {
1173
+ if (this.#links.isStopping())
1174
+ return;
1175
+ if (this.#process) {
1176
+ this.#logger.warn(`backend pid=${this.#process.pid} is still running; not starting a second one`);
944
1177
  return;
945
- if (this.#backend) {
946
- this.logger.warn(`backend pid=${this.#backend.pid} is still running; not starting a second one`);
947
- return;
948
- }
949
- this.#builderRequests.startGeneration();
950
- this.#discardPendingBuilderMessages("the backend restarted while the builder was away");
951
- this.#backendStartStatus = startStatus;
952
- this.#backendGaveUp = false;
953
- this.#setBackendLifecycleState("starting");
954
- this.#backendReady = false;
955
- this.#backendStderrTail = [];
956
- const backend = Bun.spawn(["bun", `apps/${this.app.name}/main.ts`], {
957
- cwd: this.app.workspace.workspaceRoot,
958
- stdio: this.stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
959
- env: this.env,
1178
+ }
1179
+ this.#links.beforeSpawn();
1180
+ this.#startStatus = startStatus;
1181
+ this.#gaveUp = false;
1182
+ this.#setLifecycleState("starting");
1183
+ this.#ready = false;
1184
+ this.#stderrTail = [];
1185
+ const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
1186
+ cwd: this.#app.workspace.workspaceRoot,
1187
+ stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
1188
+ env: this.#env,
960
1189
  ipc: (msg) => {
961
1190
  if (!msg || typeof msg !== "object")
962
1191
  return;
963
1192
  if (msg.type === "backend-ready") {
964
- this.#backendReady = true;
965
- this.#backendRecovery.reset();
966
- this.#setBackendLifecycleState("ready", `pid=${msg.pid}`);
967
- this.#recordBackendReadyStatus();
968
- this.logger.verbose(`backend ready pid=${msg.pid}`);
1193
+ this.#ready = true;
1194
+ this.#recovery.reset();
1195
+ this.#setLifecycleState("ready", `pid=${msg.pid}`);
1196
+ this.#recordReadyStatus();
1197
+ this.#logger.verbose(`backend ready pid=${msg.pid}`);
969
1198
  this.#forgetRouteBuildStatus();
970
- this.#replayBuilderState();
1199
+ this.replay();
971
1200
  return;
972
1201
  }
973
1202
  if (msg.type === "build-status") {
974
- const status = this.#recordBackendBuildStatus({
1203
+ const status = this.#statuses.recordBackend({
975
1204
  generation: normalizeBackendReportedGeneration(msg.data.generation),
976
1205
  ok: msg.data.ok,
977
1206
  files: msg.data.files,
978
1207
  message: msg.data.message
979
1208
  });
980
- this.#sendOrQueueBuildStatus(status);
1209
+ this.sendOrQueueStatus(status);
981
1210
  if (!status.ok)
982
- this.#emitDevEvent("failed", status.message);
1211
+ this.#links.emit("failed", status.message);
983
1212
  return;
984
1213
  }
985
1214
  if (backendMsgTypeSet.has(msg.type))
986
- this.#sendToBuilder(msg);
1215
+ this.#links.toBuilder(msg);
987
1216
  },
988
1217
  serialization: "advanced",
989
1218
  onExit: () => {
990
- this.#backendReady = false;
991
- if (this.#backend === backend)
992
- this.#backend = null;
993
- if (this.#plannedBackendStops.has(backend)) {
994
- this.#plannedBackendStops.delete(backend);
1219
+ this.#ready = false;
1220
+ if (this.#process === backend)
1221
+ this.#process = null;
1222
+ if (this.#plannedStops.has(backend)) {
1223
+ this.#plannedStops.delete(backend);
995
1224
  return;
996
1225
  }
997
- this.#scheduleBackendRecovery("backend-exit");
998
- }
999
- });
1000
- this.#backend = backend;
1001
- this.logger.verbose(`backend spawned pid=${backend.pid}`);
1002
- if (this.stdio === "pipe") {
1003
- this.#forwardBackendStream(backend.stderr, "stderr");
1004
- this.#forwardBackendStream(backend.stdout, "stdout");
1005
- }
1006
- }
1007
- #recordBackendStderr(chunk) {
1008
- const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
1009
- if (lines.length === 0)
1010
- return;
1011
- this.#backendStderrTail.push(...lines);
1012
- if (this.#backendStderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
1013
- this.#backendStderrTail.splice(0, this.#backendStderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
1014
- }
1015
- }
1016
- async#forwardBackendStream(stream, kind) {
1017
- if (!stream)
1018
- return;
1019
- const decoder = new TextDecoder;
1020
- try {
1021
- for await (const chunk of stream) {
1022
- const text = decoder.decode(chunk, { stream: true });
1023
- if (!text)
1024
- continue;
1025
- if (kind === "stderr") {
1026
- this.#recordBackendStderr(text);
1027
- process.stderr.write(text);
1028
- } else
1029
- process.stdout.write(text);
1226
+ this.#scheduleRecovery("backend-exit");
1030
1227
  }
1031
- } catch {}
1032
- }
1033
- #nextBackendBuildStatusGeneration(generation) {
1034
- if (typeof generation === "number") {
1035
- this.#backendBuildStatusGeneration = Math.max(this.#backendBuildStatusGeneration, generation);
1036
- return generation;
1037
- }
1038
- this.#backendBuildStatusGeneration += 1;
1039
- return this.#backendBuildStatusGeneration;
1040
- }
1041
- #recordBackendBuildStatus({
1042
- generation,
1043
- ok,
1044
- files,
1045
- message
1046
- }) {
1047
- const status = createBackendBuildStatus({
1048
- generation: this.#nextBackendBuildStatusGeneration(generation),
1049
- ok,
1050
- files,
1051
- message
1052
1228
  });
1053
- this.#recordBuildStatus(status);
1054
- return status;
1055
- }
1056
- #recordBackendReadyStatus() {
1057
- const previous = this.#buildStatusByPhase.get("backend");
1058
- const startStatus = this.#backendStartStatus;
1059
- if (startStatus || previous?.ok === false) {
1060
- const status = this.#recordBackendBuildStatus({
1061
- generation: startStatus?.generation ?? previous?.generation,
1062
- ok: true,
1063
- files: startStatus?.files ?? previous?.files ?? [],
1064
- message: "Backend ready"
1065
- });
1066
- this.#sendOrQueueBuildStatus(status);
1229
+ this.#process = backend;
1230
+ this.#logger.verbose(`backend spawned pid=${backend.pid}`);
1231
+ if (this.#stdio === "pipe") {
1232
+ this.#forwardStream(backend.stderr, "stderr");
1233
+ this.#forwardStream(backend.stdout, "stdout");
1067
1234
  }
1068
- this.#backendStartStatus = null;
1069
- }
1070
- #setBackendLifecycleState(next, detail) {
1071
- if (this.#backendLifecycleState === next && !detail)
1072
- return;
1073
- const prev = this.#backendLifecycleState;
1074
- this.#backendLifecycleState = next;
1075
- this.logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
1076
- this.#emitDevEvent(devHostStateOf(next, this.#backendGaveUp), detail);
1077
1235
  }
1078
- #sendToBackend(message) {
1079
- if (!this.#backend || !this.#backendReady) {
1236
+ send(message) {
1237
+ if (!this.#process || !this.#ready) {
1080
1238
  if (message.type === "css-updated" || message.type === "pages-updated" || message.type === "build-status") {
1081
- this.logger.verbose(`backend is not ready; will replay ${message.type}`);
1239
+ this.#logger.verbose(`backend is not ready; will replay ${message.type}`);
1082
1240
  return;
1083
1241
  }
1084
1242
  if (message.type !== "builder-ready")
1085
- this.logger.warn(`backend is not ready; dropping ${message.type}`);
1243
+ this.#logger.warn(`backend is not ready; dropping ${message.type}`);
1086
1244
  return;
1087
1245
  }
1088
1246
  try {
1089
- this.#backend.send(message);
1247
+ this.#process.send(message);
1090
1248
  } catch (err) {
1091
- this.logger.warn(`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`);
1249
+ this.#logger.warn(`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`);
1250
+ }
1251
+ }
1252
+ sendOrQueueStatus(status) {
1253
+ if (!this.#process || shouldQueueBuildStatusReplay(this.#ready, this.#queuedStatuses.length)) {
1254
+ this.#queuedStatuses.push(status);
1255
+ this.#logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
1256
+ return;
1092
1257
  }
1258
+ this.send({ type: "build-status", data: status });
1093
1259
  }
1094
- async#stopBackend() {
1095
- if (!this.#backend)
1260
+ replay() {
1261
+ if (!this.#ready)
1096
1262
  return;
1097
- const backend = this.#backend;
1098
- this.#plannedBackendStops.add(backend);
1099
- this.#backendReady = false;
1100
- this.#setBackendLifecycleState("stopping", `pid=${backend.pid}`);
1101
- this.logger.verbose(`stopping backend pid=${backend.pid}`);
1263
+ const { css, pages } = this.#statuses.lastGood;
1264
+ if (css)
1265
+ this.send(css);
1266
+ if (pages)
1267
+ this.send(pages);
1268
+ const queuedStatuses = this.#queuedStatuses.splice(0);
1269
+ for (const status of this.#statuses.replaySequence(queuedStatuses)) {
1270
+ this.send({ type: "build-status", data: status });
1271
+ }
1272
+ }
1273
+ dropQueuedStatuses() {
1274
+ this.#queuedStatuses = [];
1275
+ }
1276
+ async stop() {
1277
+ if (!this.#process)
1278
+ return;
1279
+ const backend = this.#process;
1280
+ this.#plannedStops.add(backend);
1281
+ this.#ready = false;
1282
+ this.#setLifecycleState("stopping", `pid=${backend.pid}`);
1283
+ this.#logger.verbose(`stopping backend pid=${backend.pid}`);
1102
1284
  try {
1103
1285
  backend.kill("SIGTERM");
1104
1286
  const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), BACKEND_GRACEFUL_TIMEOUT_MS));
1105
1287
  const result = await Promise.race([backend.exited, timeout]);
1106
1288
  if (result === "timeout") {
1107
- this.logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
1289
+ this.#logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
1108
1290
  backend.kill("SIGKILL");
1109
1291
  await backend.exited.catch(() => {
1110
1292
  return;
1111
1293
  });
1112
1294
  }
1113
1295
  } finally {
1114
- if (this.#backend === backend)
1115
- this.#backend = null;
1116
- this.#setBackendLifecycleState("stopped", `pid=${backend.pid}`);
1296
+ if (this.#process === backend)
1297
+ this.#process = null;
1298
+ this.#setLifecycleState("stopped", `pid=${backend.pid}`);
1117
1299
  }
1118
1300
  }
1119
- #scheduleBackendRestart(reason) {
1301
+ cancelTimers() {
1302
+ if (this.#restartTimer)
1303
+ clearTimeout(this.#restartTimer);
1304
+ this.#restartTimer = null;
1305
+ this.#recovery.cancel();
1306
+ }
1307
+ dropPendingRestart() {
1308
+ this.#pendingRestartReason = null;
1309
+ }
1310
+ scheduleRestart(reason) {
1120
1311
  this.#pendingRestartReason = mergeBackendRestartReasons(this.#pendingRestartReason, reason);
1121
1312
  const pending = this.#pendingRestartReason;
1122
- this.#setBackendLifecycleState("restart-pending", `generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`);
1123
- this.#backendRecovery.cancel();
1313
+ this.#setLifecycleState("restart-pending", `generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`);
1314
+ this.#recovery.cancel();
1124
1315
  if (this.#restartTimer)
1125
1316
  clearTimeout(this.#restartTimer);
1126
1317
  this.#restartTimer = setTimeout(() => {
1127
1318
  this.#restartTimer = null;
1128
- this.#backendRestart ??= this.#drainBackendRestarts().finally(() => {
1129
- this.#backendRestart = null;
1319
+ this.#restart ??= this.#drainRestarts().finally(() => {
1320
+ this.#restart = null;
1130
1321
  });
1131
1322
  }, BACKEND_RESTART_DEBOUNCE_MS);
1132
1323
  }
1133
- async#drainBackendRestarts() {
1134
- while (this.#pendingRestartReason && !this.#restartTimer && !this.#stopping) {
1324
+ reviveAfterGreenBuild(status) {
1325
+ if (!status.ok || !this.#gaveUp || this.#process || this.#recovery.pending)
1326
+ return;
1327
+ this.#logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
1328
+ this.#recovery.reset();
1329
+ this.start({ generation: status.generation, files: status.files });
1330
+ }
1331
+ #recordStderr(chunk) {
1332
+ const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
1333
+ if (lines.length === 0)
1334
+ return;
1335
+ this.#stderrTail.push(...lines);
1336
+ if (this.#stderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
1337
+ this.#stderrTail.splice(0, this.#stderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
1338
+ }
1339
+ }
1340
+ async#forwardStream(stream, kind) {
1341
+ if (!stream)
1342
+ return;
1343
+ const decoder = new TextDecoder;
1344
+ try {
1345
+ for await (const chunk of stream) {
1346
+ const text = decoder.decode(chunk, { stream: true });
1347
+ if (!text)
1348
+ continue;
1349
+ if (kind === "stderr") {
1350
+ this.#recordStderr(text);
1351
+ process.stderr.write(text);
1352
+ } else
1353
+ process.stdout.write(text);
1354
+ }
1355
+ } catch {}
1356
+ }
1357
+ #recordReadyStatus() {
1358
+ const previous = this.#statuses.phase("backend");
1359
+ const startStatus = this.#startStatus;
1360
+ if (startStatus || previous?.ok === false) {
1361
+ const status = this.#statuses.recordBackend({
1362
+ generation: startStatus?.generation ?? previous?.generation,
1363
+ ok: true,
1364
+ files: startStatus?.files ?? previous?.files ?? [],
1365
+ message: "Backend ready"
1366
+ });
1367
+ this.sendOrQueueStatus(status);
1368
+ }
1369
+ this.#startStatus = null;
1370
+ }
1371
+ #forgetRouteBuildStatus() {
1372
+ this.#statuses.forgetRoute();
1373
+ this.#queuedStatuses = this.#queuedStatuses.filter((status) => status.phase !== "route");
1374
+ }
1375
+ #setLifecycleState(next, detail) {
1376
+ if (this.#lifecycleState === next && !detail)
1377
+ return;
1378
+ const prev = this.#lifecycleState;
1379
+ this.#lifecycleState = next;
1380
+ this.#logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
1381
+ this.#links.emit(devHostStateOf(next, this.#gaveUp), detail);
1382
+ }
1383
+ async#drainRestarts() {
1384
+ while (this.#pendingRestartReason && !this.#restartTimer && !this.#links.isStopping()) {
1135
1385
  const next = this.#pendingRestartReason;
1136
1386
  this.#pendingRestartReason = null;
1137
- await this.#restartBackend(next);
1138
- }
1139
- }
1140
- async#restartBackend(reason) {
1141
- this.logger.verbose(`[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`);
1142
- this.#backendRecovery.reset();
1143
- await Promise.all([this.#stopBackend(), this.#backendGraph.refresh()]);
1144
- this.#startBackend({ generation: reason.generation, files: reason.files });
1145
- }
1146
- #scheduleBackendRecovery(reason) {
1147
- if (this.#backendRecovery.pending || this.#backend)
1148
- return;
1149
- if (this.#backendRecovery.exhausted) {
1150
- const message = `Backend exited ${this.#backendRecovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
1151
- this.#backendGaveUp = true;
1152
- this.#setBackendLifecycleState("stopped", `gave up after ${this.#backendRecovery.attempts} recovery attempts`);
1153
- this.logger.error(`[backend-recovery] ${message}`);
1154
- if (this.#backendStderrTail.length > 0) {
1155
- this.logger.error(`[backend-recovery] recent backend stderr:
1156
- ${this.#backendStderrTail.join(`
1387
+ await this.#restartWith(next);
1388
+ }
1389
+ }
1390
+ async#restartWith(reason) {
1391
+ this.#logger.verbose(`[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`);
1392
+ this.#recovery.reset();
1393
+ await Promise.all([this.stop(), this.#graph.refresh()]);
1394
+ this.start({ generation: reason.generation, files: reason.files });
1395
+ }
1396
+ #scheduleRecovery(reason) {
1397
+ if (this.#recovery.pending || this.#process)
1398
+ return;
1399
+ if (this.#recovery.exhausted) {
1400
+ const message = `Backend exited ${this.#recovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
1401
+ this.#gaveUp = true;
1402
+ this.#setLifecycleState("stopped", `gave up after ${this.#recovery.attempts} recovery attempts`);
1403
+ this.#logger.error(`[backend-recovery] ${message}`);
1404
+ if (this.#stderrTail.length > 0) {
1405
+ this.#logger.error(`[backend-recovery] recent backend stderr:
1406
+ ${this.#stderrTail.join(`
1157
1407
  `)}`);
1158
1408
  }
1159
- const abandonedStatus = this.#recordBackendBuildStatus({ ok: false, files: [], message });
1160
- this.#sendOrQueueBuildStatus(abandonedStatus);
1409
+ const abandonedStatus = this.#statuses.recordBackend({ ok: false, files: [], message });
1410
+ this.sendOrQueueStatus(abandonedStatus);
1161
1411
  return;
1162
1412
  }
1163
- this.#setBackendLifecycleState("recovering", reason);
1164
- const delay = this.#backendRecovery.next();
1165
- const failureStatus = this.#recordBackendBuildStatus({
1413
+ this.#setLifecycleState("recovering", reason);
1414
+ const delay = this.#recovery.next();
1415
+ const failureStatus = this.#statuses.recordBackend({
1166
1416
  ok: false,
1167
1417
  files: [],
1168
1418
  message: `Backend exited unexpectedly (${reason}); restarting in ${delay}ms`
1169
1419
  });
1170
- this.#sendOrQueueBuildStatus(failureStatus);
1171
- this.logger.warn(`[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#backendRecovery.attempts})`);
1172
- if (this.#backendStderrTail.length > 0) {
1173
- this.logger.warn(`[backend-recovery] recent backend stderr:
1174
- ${this.#backendStderrTail.join(`
1420
+ this.sendOrQueueStatus(failureStatus);
1421
+ this.#logger.warn(`[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#recovery.attempts})`);
1422
+ if (this.#stderrTail.length > 0) {
1423
+ this.#logger.warn(`[backend-recovery] recent backend stderr:
1424
+ ${this.#stderrTail.join(`
1175
1425
  `)}`);
1176
1426
  }
1177
- this.#backendRecovery.arm(delay, () => {
1178
- if (this.#backend)
1427
+ this.#recovery.arm(delay, () => {
1428
+ if (this.#process)
1179
1429
  return;
1180
- this.#backendGraph.refresh().finally(() => {
1181
- if (!this.#backend)
1182
- this.#startBackend({ generation: failureStatus.generation, files: failureStatus.files });
1430
+ this.#graph.refresh().finally(() => {
1431
+ if (!this.#process)
1432
+ this.start({ generation: failureStatus.generation, files: failureStatus.files });
1183
1433
  });
1184
1434
  });
1185
1435
  }
1186
- #enqueueBuilderMessage(message) {
1187
- this.#builderMessageQueue = this.#builderMessageQueue.then(() => this.#handleBuilderMessage(message)).catch((err) => {
1188
- this.logger.warn(`failed to handle builder message: ${err instanceof Error ? err.message : String(err)}`);
1189
- });
1436
+ }
1437
+
1438
+ // pkgs/@akanjs/devkit/akanApp/devBootLatch.ts
1439
+ class DevBootLatch {
1440
+ #onBooted;
1441
+ #waitMs;
1442
+ #ready = false;
1443
+ #armed = false;
1444
+ #booted = false;
1445
+ #timer = null;
1446
+ constructor(onBooted, { waitMs = 30000 } = {}) {
1447
+ this.#onBooted = onBooted;
1448
+ this.#waitMs = waitMs;
1190
1449
  }
1191
- async#handleBuilderMessage(message) {
1192
- if (this.#stopping)
1193
- return;
1194
- this.#markDevActivity();
1195
- this.#trackBuilderGeneration(message);
1196
- if (message.type === "build-status") {
1197
- this.#recordBuildStatus(message.data);
1198
- this.#sendOrQueueBuildStatus(message.data);
1199
- this.#reviveBackendAfterGreenBuild(message.data);
1200
- await this.#resumeFailedRecycle(message.data);
1201
- return;
1202
- }
1203
- if (message.type === "builder-metrics") {
1204
- this.#handleBuilderMetrics(message.data);
1205
- return;
1450
+ ready() {
1451
+ this.#ready = true;
1452
+ if (!this.#armed && !this.#timer) {
1453
+ this.#timer = setTimeout(() => this.armed(), this.#waitMs);
1454
+ this.#timer.unref?.();
1206
1455
  }
1207
- if (message.type === "boot-armed") {
1208
- this.logger.verbose("[builder] boot builds settled");
1209
- this.#bootLatch.armed();
1456
+ this.#release();
1457
+ }
1458
+ armed() {
1459
+ this.#armed = true;
1460
+ this.#release();
1461
+ }
1462
+ #release() {
1463
+ if (this.#booted || !this.#ready || !this.#armed)
1210
1464
  return;
1465
+ this.#booted = true;
1466
+ if (this.#timer)
1467
+ clearTimeout(this.#timer);
1468
+ this.#timer = null;
1469
+ this.#onBooted();
1470
+ }
1471
+ }
1472
+
1473
+ // pkgs/@akanjs/devkit/akanApp/devBuilder.ts
1474
+ import { RestartSchedule as RestartSchedule3 } from "akanjs/common";
1475
+ var BUILDER_READY_TIMEOUT_MS = 150000;
1476
+ var BUILDER_START_MAX_ATTEMPTS = 3;
1477
+
1478
+ class DevBuilder {
1479
+ #app;
1480
+ #env;
1481
+ #stdio;
1482
+ #logger;
1483
+ #links;
1484
+ #host = null;
1485
+ #patcherOff = false;
1486
+ #recovery = new RestartSchedule3({ min: 2000, max: 60000 });
1487
+ #abandonStart = null;
1488
+ #generation = 0;
1489
+ constructor(app, { env, stdio, logger }, links) {
1490
+ this.#app = app;
1491
+ this.#env = env;
1492
+ this.#stdio = stdio;
1493
+ this.#logger = logger;
1494
+ this.#links = links;
1495
+ }
1496
+ get current() {
1497
+ return this.#host;
1498
+ }
1499
+ get recovering() {
1500
+ return this.#recovery.pending;
1501
+ }
1502
+ async start({ announceBootState = false } = {}) {
1503
+ const startTime = Date.now();
1504
+ this.#app.verbose(`[cli] waiting for builder to complete initial base build\u2026`);
1505
+ let lastError;
1506
+ for (let attempt = 1;attempt <= BUILDER_START_MAX_ATTEMPTS; attempt++) {
1507
+ const builder = await IncrementalBuilderHost.create(this.#app, this.#env, (msg) => {
1508
+ this.#links.onMessage(msg);
1509
+ }, {
1510
+ stdio: this.#stdio,
1511
+ onOutput: (kind, text) => void (kind === "stderr" ? process.stderr : process.stdout).write(text),
1512
+ patcherOff: this.#patcherOff
1513
+ });
1514
+ if (this.#links.isStopping()) {
1515
+ builder.stop();
1516
+ throw new Error("dev server stopped before the builder started");
1517
+ }
1518
+ this.#host = builder;
1519
+ try {
1520
+ await this.#waitForReady(attempt, { announceBootState });
1521
+ this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms \u2014 starting backend`);
1522
+ return this.#host;
1523
+ } catch (err) {
1524
+ lastError = err;
1525
+ this.stop();
1526
+ if (attempt >= BUILDER_START_MAX_ATTEMPTS || this.#links.isStopping())
1527
+ break;
1528
+ this.#app.verbose(`[cli] builder failed before ready; retrying (${attempt + 1}/${BUILDER_START_MAX_ATTEMPTS})`);
1529
+ }
1211
1530
  }
1212
- if (message.type === "pages-updated" || message.type === "css-updated") {
1213
- const recycled = message.data.reason === "builder-recycle";
1214
- if (recycled && !this.#shouldRelayRecycledState(message))
1215
- return;
1216
- this.#recordLastGood(message, { supersede: recycled });
1217
- }
1218
- if (message.type === "invalidate") {
1219
- await this.#handleInvalidate(message);
1531
+ this.#links.onStartFailed();
1532
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
1533
+ }
1534
+ stop() {
1535
+ this.#links.onStop();
1536
+ if (!this.#host)
1220
1537
  return;
1221
- }
1222
- if (message.type === "build-route-res" || message.type === "build-csr-res" || message.type === "build-graph-res") {
1223
- const answer = this.#builderRequests.settle(message);
1224
- if (!answer) {
1225
- this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
1226
- return;
1227
- }
1228
- this.#sendToBackend(answer);
1538
+ if (this.#host.patcherOff)
1539
+ this.#patcherOff = true;
1540
+ this.#host.stop();
1541
+ this.#host = null;
1542
+ }
1543
+ abandonStart(error) {
1544
+ this.#abandonStart?.(error);
1545
+ }
1546
+ cancelRecovery() {
1547
+ this.#recovery.cancel();
1548
+ }
1549
+ resetRecovery() {
1550
+ this.#recovery.reset();
1551
+ }
1552
+ clearPatcherOff() {
1553
+ this.#patcherOff = false;
1554
+ }
1555
+ scheduleRecovery(reason) {
1556
+ if (this.#links.isStopping() || this.#recovery.pending || this.#host)
1229
1557
  return;
1230
- }
1231
- this.#sendToBackend(message);
1558
+ const delay = this.#recovery.schedule(() => {
1559
+ if (this.#links.isStopping() || this.#host)
1560
+ return;
1561
+ this.#recover(reason);
1562
+ });
1563
+ this.#logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#recovery.attempts})`);
1232
1564
  }
1233
- #trackBuilderGeneration(message) {
1234
- const generation = AkanAppHost.#builderGenerationOf(message);
1235
- if (generation === undefined || generation <= this.#builderGeneration)
1565
+ trackGeneration(message) {
1566
+ const generation = DevBuilder.#generationOf(message);
1567
+ if (generation === undefined || generation <= this.#generation)
1236
1568
  return;
1237
- this.#builderGeneration = generation;
1238
- Object.assign(this.env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
1569
+ this.#generation = generation;
1570
+ Object.assign(this.#env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
1239
1571
  }
1240
- static #builderGenerationOf(message) {
1572
+ static #generationOf(message) {
1241
1573
  if (message.type === "invalidate")
1242
1574
  return message.generation;
1243
1575
  if (message.type === "build-status" || message.type === "builder-metrics")
@@ -1246,398 +1578,366 @@ ${this.#backendStderrTail.join(`
1246
1578
  return message.data.generation;
1247
1579
  return;
1248
1580
  }
1249
- #shouldRelayRecycledState(message) {
1250
- const current = message.type === "pages-updated" ? this.#lastGoodFrontend.pages : this.#lastGoodFrontend.css;
1251
- if (shouldRelayRecycledFrontendState(current, message)) {
1252
- this.logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
1253
- return true;
1254
- }
1255
- this.logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
1256
- return false;
1257
- }
1258
- #handleBuilderMetrics(metrics) {
1259
- if (this.#rssCeilingAbandoned)
1260
- return;
1261
- const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
1262
- const decision = decideBuilderRssRecycle({
1263
- rssBytes: metrics.rssBytes,
1264
- ceilingBytes,
1265
- buildFailed: hasBuildFailureForGeneration(this.#buildStatusByPhase, metrics.generation),
1266
- msSinceLastRecycle: this.#lastRssRecycleAtMono === null ? null : performance.now() - this.#lastRssRecycleAtMono
1267
- });
1268
- if (decision === "below-ceiling") {
1269
- this.#rssCeilingTightReports = 0;
1270
- return;
1271
- }
1272
- if (decision === "unbounded")
1273
- return;
1274
- if (decision === "build-failed") {
1275
- this.logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
1276
- return;
1277
- }
1278
- if (decision === "too-soon") {
1279
- this.#rssCeilingTightReports += 1;
1280
- if (this.#rssCeilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#rssCeilingTightReports))
1581
+ async#recover(reason) {
1582
+ try {
1583
+ await this.start();
1584
+ } catch (err) {
1585
+ if (this.#links.isStopping())
1281
1586
  return;
1282
- this.#rssCeilingTightWarned = true;
1283
- this.logger.warn(`[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.`);
1587
+ this.#logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
1588
+ this.scheduleRecovery(reason);
1284
1589
  return;
1285
1590
  }
1286
- this.#armRssRecycle(`rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`, { rssBytes: metrics.rssBytes, ceilingBytes: ceilingBytes ?? 0 });
1591
+ this.#recovery.reset();
1592
+ this.#logger.info("[builder-recovery] builder recovered");
1593
+ this.#links.onRecovered(reason);
1287
1594
  }
1288
- async#checkRecycledBuilderFloor() {
1289
- if (this.#rssCeilingAbandoned || this.#lastRssRecycleAtMono === null)
1290
- return;
1291
- const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
1292
- const pid = this.#builder?.pid;
1293
- if (!ceilingBytes || !pid)
1294
- return;
1295
- const freshRssBytes = await AkanAppHost.readProcessRssBytes(pid);
1296
- if (!isRssCeilingUnreachable(freshRssBytes, ceilingBytes))
1297
- return;
1298
- this.#rssCeilingAbandoned = true;
1299
- this.logger.error(`[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.`);
1595
+ #waitForReady(attempt, { announceBootState = false } = {}) {
1596
+ return new Promise((resolve, reject) => {
1597
+ if (!this.#host)
1598
+ throw new Error("Builder Not Found");
1599
+ let settled = false;
1600
+ const settle = (fn) => {
1601
+ if (settled)
1602
+ return;
1603
+ settled = true;
1604
+ clearTimeout(timeout);
1605
+ if (this.#abandonStart === abandon)
1606
+ this.#abandonStart = null;
1607
+ fn();
1608
+ };
1609
+ const abandon = (error) => settle(() => reject(error));
1610
+ this.#abandonStart = abandon;
1611
+ const timeout = setTimeout(() => {
1612
+ settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
1613
+ }, BUILDER_READY_TIMEOUT_MS);
1614
+ this.#host.start({
1615
+ announceBootState,
1616
+ onExit: () => {
1617
+ settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
1618
+ },
1619
+ onAway: () => {
1620
+ this.#links.onAway();
1621
+ },
1622
+ onReady: () => {
1623
+ settle(resolve);
1624
+ this.#links.onReady();
1625
+ },
1626
+ onRestartReady: () => {
1627
+ this.#links.onRestartReady();
1628
+ }
1629
+ });
1630
+ });
1300
1631
  }
1301
- #armRssRecycle(reason, over) {
1302
- if (this.#rssRecycleReason !== reason)
1303
- this.logger.verbose(`[builder-recycle] armed (${reason}); replacing the builder once it stays quiet`);
1304
- this.#rssRecycleReason = reason;
1305
- if (over)
1306
- this.#rssRecycleOver = over;
1307
- if (this.#rssRecycleTimer)
1308
- clearTimeout(this.#rssRecycleTimer);
1309
- this.#rssRecycleTimer = setTimeout(() => {
1310
- this.#rssRecycleTimer = null;
1311
- const pendingReason = this.#rssRecycleReason;
1312
- const pendingOver = this.#rssRecycleOver;
1313
- this.#rssRecycleReason = null;
1314
- this.#rssRecycleOver = null;
1315
- if (!pendingReason)
1316
- return;
1317
- if (!pendingOver) {
1318
- this.#recycleBuilderForRss(pendingReason);
1319
- return;
1320
- }
1321
- this.#recycleBuilderForRssWhenStillOver(pendingReason, pendingOver);
1322
- }, BUILDER_RSS_RECYCLE_QUIET_MS);
1632
+ }
1633
+
1634
+ // pkgs/@akanjs/devkit/akanApp/devBuildStatusBoard.ts
1635
+ class DevBuildStatusBoard {
1636
+ #logger;
1637
+ #byPhase = new Map;
1638
+ #backendGeneration = 0;
1639
+ #lastGood = {};
1640
+ constructor(logger) {
1641
+ this.#logger = logger;
1323
1642
  }
1324
- async#recycleBuilderForRssWhenStillOver(reason, { rssBytes, ceilingBytes }) {
1325
- if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
1326
- this.#recycleBuilderForRss(reason);
1327
- return;
1643
+ get lastGood() {
1644
+ return this.#lastGood;
1645
+ }
1646
+ get failing() {
1647
+ return hasAnyBuildFailure(this.#byPhase);
1648
+ }
1649
+ phase(phase) {
1650
+ return this.#byPhase.get(phase);
1651
+ }
1652
+ failedAt(generation) {
1653
+ return hasBuildFailureForGeneration(this.#byPhase, generation);
1654
+ }
1655
+ replaySequence(queued) {
1656
+ return buildStatusReplaySequence(queued, this.#byPhase);
1657
+ }
1658
+ nextBackendGeneration(generation) {
1659
+ if (typeof generation === "number") {
1660
+ this.#backendGeneration = Math.max(this.#backendGeneration, generation);
1661
+ return generation;
1328
1662
  }
1329
- const pid = this.#builder?.pid;
1330
- if (!pid) {
1331
- this.#recycleBuilderForRss(reason);
1663
+ this.#backendGeneration += 1;
1664
+ return this.#backendGeneration;
1665
+ }
1666
+ record(status) {
1667
+ const recovered = shouldMarkBuildPhaseRecovered(this.#byPhase, status);
1668
+ if (shouldKeepBuildFailure(this.#byPhase, status))
1332
1669
  return;
1333
- }
1334
- this.#rssSettleToken += 1;
1335
- const token = this.#rssSettleToken;
1336
- this.logger.verbose(`[builder-recycle] holding ${Math.round(BUILDER_RSS_SETTLE_MS / 1000)}s to see whether the allocator returns it (${reason})`);
1337
- await Bun.sleep(BUILDER_RSS_SETTLE_MS);
1338
- if (token !== this.#rssSettleToken || this.#builder?.pid !== pid || this.#suspended || this.#waking) {
1339
- this.logger.verbose("[builder-recycle] settle check abandoned; the builder moved on");
1670
+ this.#byPhase.set(status.phase, status);
1671
+ const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
1672
+ if (status.ok)
1673
+ this.#logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
1674
+ else
1675
+ this.#logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
1676
+ }
1677
+ recordBackend({
1678
+ generation,
1679
+ ok,
1680
+ files,
1681
+ message
1682
+ }) {
1683
+ const status = createBackendBuildStatus({
1684
+ generation: this.nextBackendGeneration(generation),
1685
+ ok,
1686
+ files,
1687
+ message
1688
+ });
1689
+ this.record(status);
1690
+ return status;
1691
+ }
1692
+ forgetRoute() {
1693
+ this.#byPhase.delete("route");
1694
+ }
1695
+ reset() {
1696
+ this.#lastGood = {};
1697
+ this.#byPhase.clear();
1698
+ }
1699
+ recordLastGood(message, { supersede = false } = {}) {
1700
+ if (message.type === "pages-updated") {
1701
+ if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.pages, message))
1702
+ return;
1703
+ this.#lastGood.pages = message;
1704
+ this.#logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
1340
1705
  return;
1341
1706
  }
1342
- const settledBytes = await AkanAppHost.readProcessRssBytes(pid);
1343
- if (settledBytes !== null && settledBytes < ceilingBytes) {
1344
- this.logger.info(`[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`);
1707
+ if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.css, message))
1345
1708
  return;
1346
- }
1347
- this.#recycleBuilderForRss(settledBytes === null ? reason : `${reason}; still ${asMib(settledBytes)}MiB after settling`);
1348
- }
1349
- static async readProcessRssBytes(pid) {
1350
- if (process.platform === "win32")
1351
- return await AkanAppHost.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], AkanAppHost.#tasklistRssKb);
1352
- if (process.platform === "darwin") {
1353
- const footprintBytes = await AkanAppHost.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], AkanAppHost.#footprintKb);
1354
- if (footprintBytes !== null)
1355
- return footprintBytes;
1356
- }
1357
- const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
1358
- const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
1359
- if (vmRssKb)
1360
- return Number(vmRssKb) * 1024;
1361
- return await AkanAppHost.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
1709
+ this.#lastGood.css = message;
1710
+ this.#logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
1362
1711
  }
1363
- static async#readRssKbVia(command, parseKb, timeoutMs = PS_RSS_TIMEOUT_MS) {
1364
- let proc;
1365
- try {
1366
- proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
1367
- } catch {
1368
- return null;
1369
- }
1370
- const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
1371
- try {
1372
- const output = await new Response(proc.stdout).text();
1373
- await proc.exited;
1374
- const rssKb = parseKb(output);
1375
- return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
1376
- } catch {
1377
- return null;
1378
- } finally {
1379
- clearTimeout(killer);
1712
+ shouldRelayRecycled(message) {
1713
+ const current = message.type === "pages-updated" ? this.#lastGood.pages : this.#lastGood.css;
1714
+ if (shouldRelayRecycledFrontendState(current, message)) {
1715
+ this.#logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
1716
+ return true;
1380
1717
  }
1718
+ this.#logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
1719
+ return false;
1381
1720
  }
1382
- static #tasklistRssKb(output) {
1383
- const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
1384
- return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
1385
- }
1386
- static #footprintKb(output) {
1387
- const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
1388
- return bytes ? Number(bytes) / 1024 : Number.NaN;
1389
- }
1390
- #cancelRssRecycle() {
1391
- this.#rssRecycleReason = null;
1392
- this.#rssRecycleOver = null;
1393
- this.#rssSettleToken += 1;
1394
- if (!this.#rssRecycleTimer)
1395
- return;
1396
- clearTimeout(this.#rssRecycleTimer);
1397
- this.#rssRecycleTimer = null;
1721
+ }
1722
+
1723
+ // pkgs/@akanjs/devkit/akanApp/devIdleSuspend.ts
1724
+ class DevIdleSuspend {
1725
+ #app;
1726
+ #logger;
1727
+ #links;
1728
+ #timer = null;
1729
+ #suspended = false;
1730
+ #waking = false;
1731
+ #stopped = false;
1732
+ #activity = 0;
1733
+ #wokeAtMono = null;
1734
+ #watcher = null;
1735
+ #suspendedChanges = null;
1736
+ constructor(app, { logger }, links) {
1737
+ this.#app = app;
1738
+ this.#logger = logger;
1739
+ this.#links = links;
1398
1740
  }
1399
- static idleSuspendMs() {
1741
+ static idleMs() {
1400
1742
  return resolveIdleSuspendMs(process.env.AKAN_DEV_IDLE_SUSPEND_MS);
1401
1743
  }
1402
- #markDevActivity() {
1744
+ get away() {
1745
+ return !this.#stopped && (this.#suspended || this.#waking);
1746
+ }
1747
+ markActivity() {
1748
+ this.#activity++;
1403
1749
  if (this.#suspended || this.#waking)
1404
1750
  return;
1405
- this.#armIdleSuspend();
1751
+ this.arm();
1406
1752
  }
1407
- #armIdleSuspend() {
1408
- const idleMs = AkanAppHost.idleSuspendMs();
1409
- this.#cancelIdleSuspend();
1410
- if (idleMs === null)
1753
+ arm() {
1754
+ const idleMs = DevIdleSuspend.idleMs();
1755
+ this.#cancel();
1756
+ if (idleMs === null || this.#stopped)
1411
1757
  return;
1412
- this.#idleSuspendTimer = setTimeout(() => {
1413
- this.#idleSuspendTimer = null;
1758
+ this.#timer = setTimeout(() => {
1759
+ this.#timer = null;
1414
1760
  this.#suspendWhenIdle(idleMs);
1415
1761
  }, idleMs);
1416
1762
  }
1417
- #cancelIdleSuspend() {
1418
- if (!this.#idleSuspendTimer)
1419
- return;
1420
- clearTimeout(this.#idleSuspendTimer);
1421
- this.#idleSuspendTimer = null;
1422
- }
1423
- async#suspendWhenIdle(idleMs) {
1424
- const decision = decideIdleSuspend({
1425
- enabled: true,
1426
- suspended: this.#suspended,
1427
- builderReady: this.#builder?.status === "ready",
1428
- backendReady: this.#backendReady,
1429
- buildFailed: hasAnyBuildFailure(this.#buildStatusByPhase),
1430
- restartPending: this.#restartPending,
1431
- msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
1432
- });
1433
- if (decision !== "suspend") {
1434
- this.logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
1435
- this.#armIdleSuspend();
1436
- return;
1437
- }
1438
- if (!await this.#startIdleWatcher()) {
1439
- this.#armIdleSuspend();
1763
+ #cancel() {
1764
+ if (!this.#timer)
1440
1765
  return;
1441
- }
1442
- this.#suspended = true;
1443
- this.#emitDevEvent("suspended", `idle ${Math.round(idleMs / 1000)}s`);
1444
- this.#stopBuilder();
1445
- this.#openBuilderGap("idle suspend");
1446
- this.logger.info(`[idle-suspend] no build activity for ${Math.round(idleMs / 1000)}s; released the builder \u2014 the next edit or route request brings it back`);
1447
- }
1448
- get #restartPending() {
1449
- return !!(this.#pendingRecycle || this.#restartTimer || this.#backendRestart || this.#backendRecovery.pending || this.#builderRecovery.pending || this.#rssRecycleReason);
1450
- }
1451
- async#startIdleWatcher() {
1452
- try {
1453
- const roots = await new WatchRootResolver(this.app).resolve();
1454
- const watcher = new HmrWatcher({
1455
- roots,
1456
- logger: this.logger,
1457
- onBatch: (batch) => {
1458
- this.#recordSuspendedChange(batch);
1459
- this.#wakeFromIdle(`${batch.files.length} file(s) changed`);
1460
- }
1461
- });
1462
- await watcher.start();
1463
- this.#idleWatcher = watcher;
1464
- return true;
1465
- } catch (err) {
1466
- this.logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
1467
- this.#stopIdleWatcher();
1468
- return false;
1469
- }
1766
+ clearTimeout(this.#timer);
1767
+ this.#timer = null;
1470
1768
  }
1471
- #stopIdleWatcher() {
1472
- this.#idleWatcher?.stop();
1473
- this.#idleWatcher = null;
1769
+ #stopWatcher() {
1770
+ this.#watcher?.stop();
1771
+ this.#watcher = null;
1474
1772
  }
1475
- #recordSuspendedChange(batch) {
1476
- const current = this.#suspendedChanges;
1477
- if (!current) {
1478
- this.#suspendedChanges = { files: [...batch.files], kinds: new Set(batch.kinds) };
1479
- return;
1480
- }
1481
- this.#suspendedChanges = {
1482
- files: [...new Set([...current.files, ...batch.files])],
1483
- kinds: new Set([...current.kinds, ...batch.kinds])
1484
- };
1773
+ stop() {
1774
+ this.#stopped = true;
1775
+ this.#cancel();
1776
+ this.#stopWatcher();
1485
1777
  }
1486
- async#wakeFromIdle(reason) {
1487
- if (!this.#suspended || this.#waking)
1778
+ async wake(reason) {
1779
+ if (!this.#suspended || this.#waking || this.#stopped)
1488
1780
  return;
1489
1781
  this.#waking = true;
1490
- this.#cancelIdleSuspend();
1491
- this.#stopIdleWatcher();
1492
- const batch = this.#suspendedChanges;
1493
- this.#suspendedChanges = null;
1782
+ this.#cancel();
1494
1783
  const startedAtMono = performance.now();
1495
- this.logger.info(`[idle-suspend] waking (${reason})`);
1784
+ this.#logger.info(`[idle-suspend] waking (${reason})`);
1785
+ const watcher = this.#watcher;
1786
+ this.#watcher = null;
1787
+ let batch = null;
1496
1788
  try {
1497
- await this.#applyIdleWake(batch);
1498
- this.logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
1789
+ const unreported = await watcher?.close();
1790
+ if (unreported)
1791
+ this.#recordSuspendedChange(unreported);
1792
+ batch = this.#suspendedChanges;
1793
+ this.#suspendedChanges = null;
1794
+ if (this.#stopped)
1795
+ return;
1796
+ await this.#links.wake(batch);
1797
+ this.#logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
1499
1798
  } catch (err) {
1500
- this.logger.error(`[idle-suspend] wake failed; recovering the builder: ${err instanceof Error ? err.message : String(err)}`);
1501
- this.#scheduleBuilderRecovery({ files: batch?.files ?? [] });
1799
+ this.#logger.error(`[idle-suspend] wake failed; recovering the builder: ${err instanceof Error ? err.message : String(err)}`);
1800
+ this.#links.wakeFailed(batch?.files ?? []);
1502
1801
  } finally {
1503
1802
  this.#suspended = false;
1504
1803
  this.#waking = false;
1505
1804
  this.#wokeAtMono = performance.now();
1506
- this.#flushPendingBuilderMessages();
1507
- this.#armIdleSuspend();
1508
- this.#emitDevEvent(devHostStateOf(this.#backendLifecycleState, this.#backendGaveUp));
1805
+ this.#links.flushHeld();
1806
+ this.arm();
1807
+ if (!this.#stopped)
1808
+ this.#links.awake();
1509
1809
  }
1510
1810
  }
1511
- async#applyIdleWake(batch) {
1512
- const files = batch?.files ?? [];
1513
- if (shouldRefreshConfigOnIdleWake(batch)) {
1514
- this.logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
1515
- this.#discardBuilderGap("config change replaces the backend anyway");
1516
- await this.#applyRecycle({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
1517
- return;
1518
- }
1519
- if (files.length > 0)
1520
- await this.#backendGraph.refresh();
1521
- await this.#startBuilder({ announceBootState: true });
1522
- const missed = await this.#takeBuilderGapChanges();
1523
- const backendFiles = [...new Set([...files.filter((file) => this.#backendGraph.has(file)), ...missed])];
1524
- if (backendFiles.length === 0)
1525
- return;
1526
- this.logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
1527
- this.#scheduleBackendRestart({ files: backendFiles, roles: [] });
1528
- }
1529
- #openBuilderGap(reason) {
1530
- if (this.#builderGapStamp)
1531
- return;
1532
- if (!this.#backendGraph.ready) {
1533
- this.logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
1534
- return;
1535
- }
1536
- this.#builderGapStamp = this.#backendGraph.fingerprint().then((stamps) => {
1537
- this.logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
1538
- return stamps;
1539
- }).catch((err) => {
1540
- this.logger.warn(`[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`);
1541
- return null;
1811
+ #decide() {
1812
+ return decideIdleSuspend({
1813
+ enabled: true,
1814
+ suspended: this.#suspended,
1815
+ ...this.#links.readiness(),
1816
+ msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
1542
1817
  });
1543
1818
  }
1544
- async#takeBuilderGapChanges() {
1545
- const stamping = this.#builderGapStamp;
1546
- this.#builderGapStamp = null;
1547
- const before = stamping ? await stamping : null;
1548
- if (!before)
1549
- return [];
1550
- const moved = filesChangedSince(before, await this.#backendGraph.fingerprint());
1551
- if (moved.length === 0) {
1552
- this.logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
1553
- return moved;
1554
- }
1555
- this.logger.info(`[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`);
1556
- return moved;
1557
- }
1558
- #discardBuilderGap(reason) {
1559
- if (!this.#builderGapStamp)
1560
- return;
1561
- this.#builderGapStamp = null;
1562
- this.logger.verbose(`[builder-gap] stamps dropped (${reason})`);
1563
- }
1564
- async#restartBackendForGapChanges() {
1565
- const moved = await this.#takeBuilderGapChanges();
1566
- if (moved.length === 0)
1819
+ async#suspendWhenIdle(idleMs) {
1820
+ const decision = this.#decide();
1821
+ if (decision !== "suspend") {
1822
+ this.#logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
1823
+ this.arm();
1567
1824
  return;
1568
- this.#scheduleBackendRestart({ files: moved, roles: [] });
1569
- }
1570
- #flushPendingBuilderMessages() {
1571
- const pending = this.#pendingBuilderMessages.splice(0);
1572
- if (pending.length === 0)
1825
+ }
1826
+ const activity = this.#activity;
1827
+ const watcher = await this.#startWatcher();
1828
+ if (!watcher) {
1829
+ this.arm();
1573
1830
  return;
1574
- this.logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
1575
- for (const message of pending)
1576
- this.#sendToBuilder(message);
1577
- }
1578
- #discardPendingBuilderMessages(reason) {
1579
- const held = this.#pendingBuilderMessages.splice(0);
1580
- if (held.length === 0)
1831
+ }
1832
+ if (this.#stopped) {
1833
+ watcher.stop();
1581
1834
  return;
1582
- this.logger.verbose(`[builder] dropped ${held.length} held builder request(s): ${reason}`);
1583
- }
1584
- #failPendingBuilderMessages(reason) {
1585
- const held = this.#pendingBuilderMessages.splice(0);
1586
- if (held.length === 0)
1835
+ }
1836
+ const recheck = this.#activity === activity ? this.#decide() : "busy";
1837
+ if (recheck !== "suspend") {
1838
+ this.#logger.verbose(`[idle-suspend] skipped (${recheck} while the idle watcher started); re-arming`);
1839
+ watcher.stop();
1840
+ this.arm();
1587
1841
  return;
1588
- this.logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
1589
- for (const message of held)
1590
- this.#failBuilderRequest(message, reason);
1842
+ }
1843
+ this.#watcher = watcher;
1844
+ this.#suspended = true;
1845
+ this.#links.release(`idle ${Math.round(idleMs / 1000)}s`);
1846
+ this.#logger.info(`[idle-suspend] no build activity for ${Math.round(idleMs / 1000)}s; released the builder \u2014 the next edit or route request brings it back`);
1591
1847
  }
1592
- #failBuilderRequest(message, error) {
1593
- if (message.type === "build-route")
1594
- this.#sendToBackend({ type: "build-route-res", id: message.id, ok: false, error, kind: "unavailable" });
1595
- else if (message.type === "build-csr")
1596
- this.#sendToBackend({ type: "build-csr-res", id: message.id, ok: false, error, kind: "unavailable" });
1597
- else if (message.type === "build-graph")
1598
- this.#sendToBackend({ type: "build-graph-res", id: message.id, ok: false, error, kind: "unavailable" });
1599
- else
1600
- return false;
1601
- return true;
1848
+ async#startWatcher() {
1849
+ let watcher = null;
1850
+ try {
1851
+ const roots = await new WatchRootResolver(this.#app).resolve();
1852
+ watcher = new HmrWatcher({
1853
+ roots,
1854
+ logger: this.#logger,
1855
+ onBatch: (batch) => {
1856
+ this.#recordSuspendedChange(batch);
1857
+ this.wake(`${batch.files.length} file(s) changed`);
1858
+ }
1859
+ });
1860
+ await watcher.start();
1861
+ return watcher;
1862
+ } catch (err) {
1863
+ this.#logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
1864
+ watcher?.stop();
1865
+ return null;
1866
+ }
1602
1867
  }
1603
- #recycleBuilderForRss(reason) {
1604
- if (this.#pendingRecycle || this.#restartTimer) {
1605
- this.logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
1868
+ #recordSuspendedChange(batch) {
1869
+ const current = this.#suspendedChanges;
1870
+ if (!current) {
1871
+ this.#suspendedChanges = { files: [...batch.files], kinds: new Set(batch.kinds) };
1606
1872
  return;
1607
1873
  }
1608
- if (!this.#builder?.recycle(reason))
1609
- return;
1610
- this.#lastRssRecycleAtMono = performance.now();
1611
- this.#openBuilderGap("builder recycle");
1874
+ this.#suspendedChanges = {
1875
+ files: [...new Set([...current.files, ...batch.files])],
1876
+ kinds: new Set([...current.kinds, ...batch.kinds])
1877
+ };
1612
1878
  }
1613
- async#handleInvalidate(message) {
1879
+ }
1880
+
1881
+ // pkgs/@akanjs/devkit/akanApp/devRecycler.ts
1882
+ import path4 from "path";
1883
+ class DevRecycler {
1884
+ #app;
1885
+ #env;
1886
+ #logger;
1887
+ #isStopping;
1888
+ #graph;
1889
+ #statuses;
1890
+ #backend;
1891
+ #builder;
1892
+ #gap;
1893
+ #rss;
1894
+ #pending = null;
1895
+ #restartFailedAfterApply = null;
1896
+ constructor(app, parts) {
1897
+ this.#app = app;
1898
+ this.#env = parts.env;
1899
+ this.#logger = parts.logger;
1900
+ this.#isStopping = parts.isStopping;
1901
+ this.#graph = parts.graph;
1902
+ this.#statuses = parts.statuses;
1903
+ this.#backend = parts.backend;
1904
+ this.#builder = parts.builder;
1905
+ this.#gap = parts.gap;
1906
+ this.#rss = parts.rss;
1907
+ }
1908
+ get pending() {
1909
+ return !!this.#pending;
1910
+ }
1911
+ drop() {
1912
+ this.#pending = null;
1913
+ }
1914
+ async handleInvalidate(message) {
1614
1915
  this.#logDevPlan(message);
1615
- if (this.#rssRecycleReason)
1616
- this.#armRssRecycle(this.#rssRecycleReason);
1916
+ this.#rss.rearm();
1617
1917
  const wantsDevHostRestart = shouldRestartDevHostByDevPlan(message);
1618
- const pending = this.#pendingRecycle;
1918
+ const pending = this.#pending;
1619
1919
  const resumes = !!pending && message.kinds.includes("code") && this.#touchesFailedRecycle(message.files);
1620
1920
  if (wantsDevHostRestart || shouldRestartBuilderByDevPlan(message) || resumes) {
1621
1921
  const refreshConfig = wantsDevHostRestart || (pending?.refreshConfig ?? false);
1622
1922
  const merged = pending ? mergeInvalidateMessages(pending.message, message) : message;
1623
1923
  const generation = message.devPlan?.generation ?? message.generation;
1624
- if (hasBuildFailureForGeneration(this.#buildStatusByPhase, generation)) {
1625
- this.#deferRecycle(merged, { refreshConfig, generation });
1924
+ if (this.#statuses.failedAt(generation)) {
1925
+ this.#defer(merged, { refreshConfig, generation });
1626
1926
  return;
1627
1927
  }
1628
- await this.#applyRecycle(merged, refreshConfig);
1928
+ await this.apply(merged, refreshConfig);
1629
1929
  return;
1630
1930
  }
1631
1931
  if (await this.#shouldRestartBackend(message)) {
1632
- this.#scheduleBackendRestart(backendRestartReasonFromMessage(message));
1932
+ this.#backend.scheduleRestart(backendRestartReasonFromMessage(message));
1633
1933
  return;
1634
1934
  }
1635
- this.#sendToBackend(message);
1935
+ this.#backend.send(message);
1636
1936
  }
1637
- async#applyRecycle(message, refreshConfig) {
1638
- if (this.#stopping)
1937
+ async apply(message, refreshConfig) {
1938
+ if (this.#isStopping())
1639
1939
  return;
1640
- this.#pendingRecycle = null;
1940
+ this.#pending = null;
1641
1941
  const progress = { applied: !refreshConfig };
1642
1942
  try {
1643
1943
  if (refreshConfig)
@@ -1646,144 +1946,121 @@ ${this.#backendStderrTail.join(`
1646
1946
  await this.#restartDevChildren(message);
1647
1947
  } catch (err) {
1648
1948
  const kind = refreshConfig ? "Config" : "Runtime metadata";
1649
- const generation = this.#recordDevHostRestartFailure(message, err, kind, { applied: progress.applied });
1949
+ const generation = this.#recordRestartFailure(message, err, kind, { applied: progress.applied });
1650
1950
  if (progress.applied)
1651
1951
  this.#restartFailedAfterApply = generation;
1652
1952
  else
1653
- this.#pendingRecycle = { message, refreshConfig, failed: true, failedGeneration: generation };
1953
+ this.#pending = { message, refreshConfig, failed: true, failedGeneration: generation };
1654
1954
  this.#resurrectDevChildren(message);
1655
1955
  }
1656
1956
  }
1657
- async#resumeFailedRecycle(status) {
1658
- const pending = this.#pendingRecycle;
1957
+ async resumeFailed(status) {
1958
+ const pending = this.#pending;
1659
1959
  if (!pending?.failed || !status.ok || status.phase !== "pages" || !this.#touchesFailedRecycle(status.files))
1660
1960
  return;
1661
1961
  if (status.generation <= (pending.failedGeneration ?? -1))
1662
1962
  return;
1663
- await this.#applyRecycle(pending.message, pending.refreshConfig);
1963
+ await this.apply(pending.message, pending.refreshConfig);
1964
+ }
1965
+ async applyIdleWake(batch) {
1966
+ const files = batch?.files ?? [];
1967
+ if (shouldRefreshConfigOnIdleWake(batch)) {
1968
+ this.#logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
1969
+ this.#gap.discard("config change replaces the backend anyway");
1970
+ await this.apply({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
1971
+ return;
1972
+ }
1973
+ if (files.length > 0)
1974
+ await this.#graph.refresh();
1975
+ await this.#builder.start({ announceBootState: true });
1976
+ const missed = await this.#gap.take();
1977
+ const backendFiles = [...new Set([...files.filter((file) => this.#graph.has(file)), ...missed])];
1978
+ if (backendFiles.length === 0)
1979
+ return;
1980
+ this.#logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
1981
+ this.#backend.scheduleRestart({ files: backendFiles, roles: [] });
1982
+ }
1983
+ builderRecovered(reason) {
1984
+ this.#gap.restartBackendForChanges();
1985
+ const failedAfterApply = this.#restartFailedAfterApply;
1986
+ this.#restartFailedAfterApply = null;
1987
+ const status = {
1988
+ generation: failedAfterApply !== null ? this.#statuses.nextBackendGeneration(failedAfterApply + 1) : reason.generation ?? this.#statuses.nextBackendGeneration(),
1989
+ phase: "scan",
1990
+ ok: true,
1991
+ files: reason.files,
1992
+ message: "Builder recovered"
1993
+ };
1994
+ this.#statuses.record(status);
1995
+ this.#backend.sendOrQueueStatus(status);
1996
+ if (!this.#backend.running && !this.#backend.recovering) {
1997
+ this.#backend.start({ generation: reason.generation, files: reason.files });
1998
+ }
1664
1999
  }
1665
2000
  #touchesFailedRecycle(files) {
1666
- const pending = this.#pendingRecycle;
2001
+ const pending = this.#pending;
1667
2002
  if (!pending?.failed)
1668
2003
  return true;
1669
2004
  const changed = new Set(pending.message.files);
1670
2005
  return files.some((file) => changed.has(file));
1671
2006
  }
1672
- #deferRecycle(message, { refreshConfig, generation }) {
1673
- this.#pendingRecycle = { message, refreshConfig };
2007
+ #defer(message, { refreshConfig, generation }) {
2008
+ this.#pending = { message, refreshConfig };
1674
2009
  const kind = refreshConfig ? "Config" : "Runtime metadata";
1675
- this.logger.warn(`[dev-host] ${kind.toLowerCase()} restart deferred generation=${generation ?? "(unknown)"}; keeping the running dev server until the build error is fixed`);
2010
+ this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart deferred generation=${generation ?? "(unknown)"}; keeping the running dev server until the build error is fixed`);
1676
2011
  const status = {
1677
- generation: generation ?? this.#nextBackendBuildStatusGeneration(),
2012
+ generation: generation ?? this.#statuses.nextBackendGeneration(),
1678
2013
  phase: "scan",
1679
2014
  ok: false,
1680
2015
  files: message.files,
1681
2016
  message: `${kind} change is on hold while the build is failing; it will apply automatically once the error is fixed.`
1682
2017
  };
1683
- this.#recordBuildStatus(status);
1684
- this.#sendOrQueueBuildStatus(status);
2018
+ this.#statuses.record(status);
2019
+ this.#backend.sendOrQueueStatus(status);
1685
2020
  }
1686
2021
  #resurrectDevChildren(message) {
1687
2022
  const generation = message.devPlan?.generation ?? message.generation;
1688
- if (!this.#backend)
1689
- this.#startBackend({ generation, files: message.files });
1690
- this.#scheduleBuilderRecovery({ generation, files: message.files });
1691
- }
1692
- #scheduleBuilderRecovery(reason) {
1693
- if (this.#stopping || this.#builderRecovery.pending || this.#builder)
1694
- return;
1695
- const delay = this.#builderRecovery.schedule(() => {
1696
- if (this.#stopping || this.#builder)
1697
- return;
1698
- this.#recoverBuilder(reason);
1699
- });
1700
- this.logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#builderRecovery.attempts})`);
1701
- }
1702
- async#recoverBuilder(reason) {
1703
- try {
1704
- await this.#startBuilder();
1705
- } catch (err) {
1706
- if (this.#stopping)
1707
- return;
1708
- this.logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
1709
- this.#scheduleBuilderRecovery(reason);
1710
- return;
1711
- }
1712
- this.#builderRecovery.reset();
1713
- this.logger.info("[builder-recovery] builder recovered");
1714
- this.#restartBackendForGapChanges();
1715
- const failedAfterApply = this.#restartFailedAfterApply;
1716
- this.#restartFailedAfterApply = null;
1717
- const status = {
1718
- generation: failedAfterApply !== null ? this.#nextBackendBuildStatusGeneration(failedAfterApply + 1) : reason.generation ?? this.#nextBackendBuildStatusGeneration(),
1719
- phase: "scan",
1720
- ok: true,
1721
- files: reason.files,
1722
- message: "Builder recovered"
1723
- };
1724
- this.#recordBuildStatus(status);
1725
- this.#sendOrQueueBuildStatus(status);
1726
- if (!this.#backend && !this.#backendRecovery.pending) {
1727
- this.#startBackend({ generation: reason.generation, files: reason.files });
1728
- }
1729
- }
1730
- #reviveBackendAfterGreenBuild(status) {
1731
- if (!status.ok || !this.#backendGaveUp || this.#backend || this.#backendRecovery.pending)
1732
- return;
1733
- this.logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
1734
- this.#backendRecovery.reset();
1735
- this.#startBackend({ generation: status.generation, files: status.files });
2023
+ if (!this.#backend.running)
2024
+ this.#backend.start({ generation, files: message.files });
2025
+ this.#builder.scheduleRecovery({ generation, files: message.files });
1736
2026
  }
1737
2027
  async#restartDevChildren(message) {
1738
2028
  const generation = message.devPlan?.generation ?? message.generation;
1739
- this.logger.warn(`[dev-host] recycling builder/backend for runtime metadata generation=${generation ?? "(unknown)"} files=${message.files.length}`);
2029
+ this.#logger.warn(`[dev-host] recycling builder/backend for runtime metadata generation=${generation ?? "(unknown)"} files=${message.files.length}`);
1740
2030
  await this.#recycleDevChildren(message);
1741
2031
  }
1742
2032
  async#restartDevHost(message, progress) {
1743
2033
  const generation = message.devPlan?.generation ?? message.generation;
1744
- this.logger.warn(`[dev-host] config change detected; restarting dev host generation=${generation ?? "(unknown)"} files=${message.files.length}`);
2034
+ this.#logger.warn(`[dev-host] config change detected; restarting dev host generation=${generation ?? "(unknown)"} files=${message.files.length}`);
1745
2035
  await this.#recycleDevChildren(message, { refreshConfig: true, progress });
1746
2036
  }
1747
2037
  async#recycleDevChildren(message, { refreshConfig = false, progress } = {}) {
1748
2038
  const generation = message.devPlan?.generation ?? message.generation;
1749
- this.#clearRestartTimers();
1750
- this.#builderRecovery.reset();
1751
- this.#pendingRestartReason = null;
1752
- await this.#backendRestart;
1753
- this.#lastGoodFrontend = {};
1754
- this.#buildStatusByPhase.clear();
1755
- this.#pendingBuildStatusReplay = [];
1756
- await this.#stopBackend();
1757
- this.#stopBuilder();
1758
- this.#patcherOff = false;
2039
+ this.#backend.cancelTimers();
2040
+ this.#builder.cancelRecovery();
2041
+ this.#builder.resetRecovery();
2042
+ this.#backend.dropPendingRestart();
2043
+ await this.#backend.restarting;
2044
+ this.#statuses.reset();
2045
+ this.#backend.dropQueuedStatuses();
2046
+ await this.#backend.stop();
2047
+ this.#builder.stop();
2048
+ this.#builder.clearPatcherOff();
1759
2049
  if (refreshConfig) {
1760
- await this.app.getConfig({ refresh: true });
1761
- const { env } = await this.app.prepareCommand("start");
1762
- Object.assign(this.env, env);
2050
+ await this.#app.getConfig({ refresh: true });
2051
+ const { env } = await this.#app.prepareCommand("start");
2052
+ Object.assign(this.#env, env);
1763
2053
  if (progress)
1764
2054
  progress.applied = true;
1765
2055
  }
1766
- await this.#backendGraph.refresh();
1767
- await this.#startBuilder();
1768
- this.#startBackend({ generation, files: message.files });
1769
- }
1770
- #recordLastGood(message, { supersede = false } = {}) {
1771
- if (message.type === "pages-updated") {
1772
- if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.pages, message))
1773
- return;
1774
- this.#lastGoodFrontend.pages = message;
1775
- this.logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
1776
- return;
1777
- }
1778
- if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGoodFrontend.css, message))
1779
- return;
1780
- this.#lastGoodFrontend.css = message;
1781
- this.logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
2056
+ await this.#graph.refresh();
2057
+ await this.#builder.start();
2058
+ this.#backend.start({ generation, files: message.files });
1782
2059
  }
1783
- #recordDevHostRestartFailure(message, err, kind, { applied }) {
1784
- const generation = message.devPlan?.generation ?? message.generation ?? this.#nextBackendBuildStatusGeneration();
2060
+ #recordRestartFailure(message, err, kind, { applied }) {
2061
+ const generation = message.devPlan?.generation ?? message.generation ?? this.#statuses.nextBackendGeneration();
1785
2062
  const detail = err instanceof Error ? err.message : String(err);
1786
- this.logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
2063
+ this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
1787
2064
  const names = message.files.slice(0, 3).map((file) => path4.basename(file));
1788
2065
  const saved = names.length > 0 ? names.join(", ") : "the changed file";
1789
2066
  const status = {
@@ -1793,50 +2070,15 @@ ${this.#backendStderrTail.join(`
1793
2070
  files: message.files,
1794
2071
  message: applied ? `${kind} change applied, but the dev server failed to restart: ${detail}. It is recovering on its own.` : `${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.`
1795
2072
  };
1796
- this.#recordBuildStatus(status);
1797
- this.#sendOrQueueBuildStatus(status);
2073
+ this.#statuses.record(status);
2074
+ this.#backend.sendOrQueueStatus(status);
1798
2075
  return generation;
1799
2076
  }
1800
- #recordBuildStatus(status) {
1801
- const recovered = shouldMarkBuildPhaseRecovered(this.#buildStatusByPhase, status);
1802
- if (shouldKeepBuildFailure(this.#buildStatusByPhase, status))
1803
- return;
1804
- this.#buildStatusByPhase.set(status.phase, status);
1805
- const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
1806
- if (status.ok)
1807
- this.logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
1808
- else
1809
- this.logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
1810
- }
1811
- #sendOrQueueBuildStatus(status) {
1812
- if (!this.#backend || shouldQueueBuildStatusReplay(this.#backendReady, this.#pendingBuildStatusReplay.length)) {
1813
- this.#pendingBuildStatusReplay.push(status);
1814
- this.logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
1815
- return;
1816
- }
1817
- this.#sendToBackend({ type: "build-status", data: status });
1818
- }
1819
- #forgetRouteBuildStatus() {
1820
- this.#buildStatusByPhase.delete("route");
1821
- this.#pendingBuildStatusReplay = this.#pendingBuildStatusReplay.filter((status) => status.phase !== "route");
1822
- }
1823
- #replayBuilderState() {
1824
- if (!this.#backendReady)
1825
- return;
1826
- if (this.#lastGoodFrontend.css)
1827
- this.#sendToBackend(this.#lastGoodFrontend.css);
1828
- if (this.#lastGoodFrontend.pages)
1829
- this.#sendToBackend(this.#lastGoodFrontend.pages);
1830
- const queuedStatuses = this.#pendingBuildStatusReplay.splice(0);
1831
- for (const status of buildStatusReplaySequence(queuedStatuses, this.#buildStatusByPhase)) {
1832
- this.#sendToBackend({ type: "build-status", data: status });
1833
- }
1834
- }
1835
2077
  #logDevPlan(message) {
1836
2078
  if (!message.devPlan)
1837
2079
  return;
1838
2080
  const { generation, roles, actions, reasonByFile } = message.devPlan;
1839
- this.logger.verbose(`[dev-plan] generation=${generation} roles=${roles.join(",") || "(none)"} actions=${actions.join(",") || "(none)"} reasons=${Object.keys(reasonByFile).length}`);
2081
+ this.#logger.verbose(`[dev-plan] generation=${generation} roles=${roles.join(",") || "(none)"} actions=${actions.join(",") || "(none)"} reasons=${Object.keys(reasonByFile).length}`);
1840
2082
  }
1841
2083
  async#shouldRestartBackend(message) {
1842
2084
  if (message.kinds.length === 1 && message.kinds[0] === "css")
@@ -1844,136 +2086,239 @@ ${this.#backendStderrTail.join(`
1844
2086
  if (message.devPlan) {
1845
2087
  const shouldRestart = shouldRestartBackendByDevPlan(message) ?? false;
1846
2088
  if (shouldRestart && message.kinds.includes("code"))
1847
- await this.#backendGraph.refresh();
2089
+ await this.#graph.refresh();
1848
2090
  return shouldRestart;
1849
2091
  }
1850
2092
  if (message.kinds.includes("code"))
1851
- await this.#backendGraph.refresh();
1852
- if (message.files.some((file) => this.#backendGraph.has(file)))
2093
+ await this.#graph.refresh();
2094
+ if (message.files.some((file) => this.#graph.has(file)))
1853
2095
  return true;
1854
- if (!this.#backendGraph.lastRefreshSucceeded) {
1855
- const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this.app.workspace.workspaceRoot));
2096
+ if (!this.#graph.lastRefreshSucceeded) {
2097
+ const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this.#app.workspace.workspaceRoot));
1856
2098
  if (fallbackFiles.length > 0) {
1857
- this.logger.warn(`[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`);
2099
+ this.#logger.warn(`[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`);
1858
2100
  return true;
1859
2101
  }
1860
2102
  }
1861
2103
  return false;
1862
2104
  }
1863
- async#startBuilder({
1864
- announceBootState = false
1865
- } = {}) {
1866
- const startTime = Date.now();
1867
- this.app.verbose(`[cli] waiting for builder to complete initial base build\u2026`);
1868
- let lastError;
1869
- for (let attempt = 1;attempt <= BUILDER_START_MAX_ATTEMPTS; attempt++) {
1870
- const builder = await IncrementalBuilderHost.create(this.app, this.env, (msg) => {
1871
- this.#enqueueBuilderMessage(msg);
1872
- }, {
1873
- stdio: this.stdio,
1874
- onOutput: (kind, text) => void (kind === "stderr" ? process.stderr : process.stdout).write(text),
1875
- patcherOff: this.#patcherOff
1876
- });
1877
- if (this.#stopping) {
1878
- builder.stop();
1879
- throw new Error("dev server stopped before the builder started");
1880
- }
1881
- this.#builder = builder;
1882
- try {
1883
- await this.#waitForBuilderReady(attempt, { announceBootState });
1884
- this.app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms \u2014 starting backend`);
1885
- return this.#builder;
1886
- } catch (err) {
1887
- lastError = err;
1888
- this.#stopBuilder();
1889
- if (attempt >= BUILDER_START_MAX_ATTEMPTS || this.#stopping)
1890
- break;
1891
- this.app.verbose(`[cli] builder failed before ready; retrying (${attempt + 1}/${BUILDER_START_MAX_ATTEMPTS})`);
1892
- }
2105
+ }
2106
+
2107
+ // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
2108
+ class AkanAppHost {
2109
+ app;
2110
+ logger = new Logger2("AkanAppHost");
2111
+ stdio;
2112
+ env;
2113
+ #onDevEvent;
2114
+ #lastDevState = null;
2115
+ #bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
2116
+ #stopping = false;
2117
+ #builderMessageQueue = Promise.resolve();
2118
+ #backendGraph;
2119
+ #statuses;
2120
+ #backend;
2121
+ #gap;
2122
+ #requests;
2123
+ #rss;
2124
+ #builder;
2125
+ #idle;
2126
+ #recycler;
2127
+ constructor(app, {
2128
+ env,
2129
+ stdio = "inherit",
2130
+ onDevEvent
2131
+ }) {
2132
+ this.app = app;
2133
+ this.env = env;
2134
+ this.stdio = stdio;
2135
+ this.#onDevEvent = onDevEvent ?? null;
2136
+ this.#backendGraph = new BackendImportGraph(app, this.logger);
2137
+ const { logger } = this;
2138
+ const graph = this.#backendGraph;
2139
+ const isStopping = () => this.#stopping;
2140
+ const statuses = new DevBuildStatusBoard(logger);
2141
+ this.#statuses = statuses;
2142
+ this.#backend = new DevBackend(app, { env, stdio, logger, statuses, graph }, {
2143
+ isStopping,
2144
+ emit: (state, detail) => this.#emitDevEvent(state, detail),
2145
+ beforeSpawn: () => {
2146
+ this.#requests.startGeneration();
2147
+ this.#requests.discard("the backend restarted while the builder was away");
2148
+ },
2149
+ toBuilder: (message) => this.#requests.send(message)
2150
+ });
2151
+ this.#gap = new BuilderGap({ graph, backend: this.#backend, logger });
2152
+ this.#requests = new BuilderRequestRelay({ logger, env }, {
2153
+ builder: () => this.#builder.current,
2154
+ toBackend: (message) => this.#backend.send(message),
2155
+ markActivity: () => this.#idle.markActivity(),
2156
+ away: () => this.#idle.away,
2157
+ wake: (reason) => void this.#idle.wake(reason)
2158
+ });
2159
+ this.#rss = new BuilderRssRecycler({ logger, statuses }, {
2160
+ builder: () => this.#builder.current,
2161
+ away: () => this.#idle.away,
2162
+ restartQueued: () => this.#recycler.pending || this.#backend.restartScheduled,
2163
+ onRecycle: () => this.#gap.open("builder recycle")
2164
+ });
2165
+ this.#builder = new DevBuilder(app, { env, stdio, logger }, {
2166
+ isStopping,
2167
+ onMessage: (message) => this.#enqueueBuilderMessage(message),
2168
+ onAway: () => this.#gap.open("builder replacement"),
2169
+ onReady: () => this.#requests.flush(),
2170
+ onRestartReady: () => {
2171
+ this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
2172
+ this.#backend.replay();
2173
+ this.#requests.flush();
2174
+ this.#gap.restartBackendForChanges();
2175
+ this.#rss.checkRecycledFloor();
2176
+ },
2177
+ onStartFailed: () => this.#requests.fail("builder failed to start"),
2178
+ onStop: () => this.#rss.cancel(),
2179
+ onRecovered: (reason) => this.#recycler.builderRecovered(reason)
2180
+ });
2181
+ this.#idle = new DevIdleSuspend(app, { logger }, {
2182
+ readiness: () => ({
2183
+ builderReady: this.#builder.current?.status === "ready",
2184
+ backendReady: this.#backend.ready,
2185
+ buildFailed: this.#statuses.failing,
2186
+ restartPending: this.#restartPending
2187
+ }),
2188
+ release: (detail) => {
2189
+ this.#emitDevEvent("suspended", detail);
2190
+ this.#builder.stop();
2191
+ this.#gap.open("idle suspend");
2192
+ },
2193
+ wake: (batch) => this.#recycler.applyIdleWake(batch),
2194
+ wakeFailed: (files) => this.#builder.scheduleRecovery({ files }),
2195
+ flushHeld: () => this.#requests.flush(),
2196
+ awake: () => this.#emitDevEvent(devHostStateOf(this.#backend.lifecycleState, this.#backend.gaveUp))
2197
+ });
2198
+ this.#recycler = new DevRecycler(app, {
2199
+ env,
2200
+ logger,
2201
+ isStopping,
2202
+ graph,
2203
+ statuses,
2204
+ backend: this.#backend,
2205
+ builder: this.#builder,
2206
+ gap: this.#gap,
2207
+ rss: this.#rss
2208
+ });
2209
+ }
2210
+ #emitDevEvent(state, detail) {
2211
+ if (!this.#onDevEvent || state === this.#lastDevState)
2212
+ return;
2213
+ this.#lastDevState = state;
2214
+ this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
2215
+ if (state === "ready")
2216
+ this.#bootLatch.ready();
2217
+ }
2218
+ async start() {
2219
+ if (this.#backend.running)
2220
+ await this.#backend.stop();
2221
+ if (this.#builder.current)
2222
+ this.#builder.stop();
2223
+ const [redisHost] = await Promise.all([
2224
+ this.#prepareDatabase("redis"),
2225
+ this.#backendGraph.refresh(),
2226
+ this.#builder.start()
2227
+ ]);
2228
+ Object.assign(this.env, { REDIS_HOST: redisHost });
2229
+ this.#backend.start();
2230
+ this.#idle.arm();
2231
+ return this;
2232
+ }
2233
+ async stop() {
2234
+ this.#stopping = true;
2235
+ this.#recycler.drop();
2236
+ this.#idle.stop();
2237
+ this.#backend.cancelTimers();
2238
+ this.#builder.cancelRecovery();
2239
+ this.#builder.abandonStart(new Error("dev server stopped before the builder was ready"));
2240
+ this.#backend.dropPendingRestart();
2241
+ this.#requests.fail("dev server is shutting down");
2242
+ await this.#backend.restarting;
2243
+ await this.#backend.stop();
2244
+ this.#builder.stop();
2245
+ return this;
2246
+ }
2247
+ kill() {
2248
+ this.stop();
2249
+ }
2250
+ async#prepareDatabase(type) {
2251
+ const environment = WorkspaceExecutor.getBaseDevEnv().env;
2252
+ const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
2253
+ if (policy === "none")
2254
+ return "localhost";
2255
+ if (policy === "required")
2256
+ return await createTunnel(type, { app: this.app, environment });
2257
+ try {
2258
+ return await createTunnel(type, { app: this.app, environment });
2259
+ } catch (error) {
2260
+ this.logger.warn(`${error instanceof Error ? error.message : String(error)} - continuing without Redis: the single database mode does not use it unless an app adaptor does`);
2261
+ return UNAVAILABLE_REDIS_HOST;
1893
2262
  }
1894
- this.#failPendingBuilderMessages("builder failed to start");
1895
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
1896
2263
  }
1897
- #waitForBuilderReady(attempt, { announceBootState = false } = {}) {
1898
- return new Promise((resolve, reject) => {
1899
- if (!this.#builder)
1900
- throw new Error("Builder Not Found");
1901
- let settled = false;
1902
- const settle = (fn) => {
1903
- if (settled)
1904
- return;
1905
- settled = true;
1906
- clearTimeout(timeout);
1907
- if (this.#abandonBuilderStart === abandon)
1908
- this.#abandonBuilderStart = null;
1909
- fn();
1910
- };
1911
- const abandon = (error) => settle(() => reject(error));
1912
- this.#abandonBuilderStart = abandon;
1913
- const timeout = setTimeout(() => {
1914
- settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
1915
- }, BUILDER_READY_TIMEOUT_MS);
1916
- this.#builder.start({
1917
- announceBootState,
1918
- onExit: () => {
1919
- settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
1920
- },
1921
- onAway: () => {
1922
- this.#openBuilderGap("builder replacement");
1923
- },
1924
- onReady: () => {
1925
- settle(resolve);
1926
- this.#flushPendingBuilderMessages();
1927
- },
1928
- onRestartReady: () => {
1929
- this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
1930
- this.#replayBuilderState();
1931
- this.#flushPendingBuilderMessages();
1932
- this.#restartBackendForGapChanges();
1933
- this.#checkRecycledBuilderFloor();
1934
- }
1935
- });
2264
+ #enqueueBuilderMessage(message) {
2265
+ this.#builderMessageQueue = this.#builderMessageQueue.then(() => this.#handleBuilderMessage(message)).catch((err) => {
2266
+ this.logger.warn(`failed to handle builder message: ${err instanceof Error ? err.message : String(err)}`);
1936
2267
  });
1937
2268
  }
1938
- #sendToBuilder(message) {
1939
- this.#markDevActivity();
1940
- if (this.#suspended || this.#waking) {
1941
- this.#pendingBuilderMessages.push(message);
1942
- this.#wakeFromIdle(`${message.type} arrived while suspended`);
2269
+ async#handleBuilderMessage(message) {
2270
+ if (this.#stopping)
2271
+ return;
2272
+ this.#idle.markActivity();
2273
+ this.#builder.trackGeneration(message);
2274
+ if (message.type === "build-status") {
2275
+ this.#statuses.record(message.data);
2276
+ this.#backend.sendOrQueueStatus(message.data);
2277
+ this.#backend.reviveAfterGreenBuild(message.data);
2278
+ await this.#recycler.resumeFailed(message.data);
1943
2279
  return;
1944
2280
  }
1945
- if (message.type === "build-csr" && !message.shell && this.env.AKAN_DEV_CSR_REBUILD !== "1") {
1946
- Object.assign(this.env, { AKAN_DEV_CSR_REBUILD: "1" });
1947
- this.logger.verbose(`[csr] armed dev CSR rebuilds (${message.reason})`);
2281
+ if (message.type === "builder-metrics") {
2282
+ this.#rss.handleMetrics(message.data);
2283
+ return;
1948
2284
  }
1949
- if (message.type === "build-route" || message.type === "build-csr" || message.type === "build-graph") {
1950
- const outgoing = this.#builderRequests.issue(message);
1951
- if (this.#builder?.send(outgoing))
1952
- return;
1953
- this.#builderRequests.withdraw(outgoing.id);
1954
- } else if (this.#builder?.send(message))
2285
+ if (message.type === "boot-armed") {
2286
+ this.logger.verbose("[builder] boot builds settled");
2287
+ this.#bootLatch.armed();
1955
2288
  return;
1956
- const status = this.#builder?.status ?? "stopped";
1957
- if (shouldHoldForReturningBuilder({ status, heldCount: this.#pendingBuilderMessages.length })) {
1958
- this.#pendingBuilderMessages.push(message);
1959
- this.logger.verbose(`[builder] holding ${message.type} until the builder is ready (${this.#pendingBuilderMessages.length} waiting)`);
2289
+ }
2290
+ if (message.type === "pages-updated" || message.type === "css-updated") {
2291
+ const recycled = message.data.reason === "builder-recycle";
2292
+ if (recycled && !this.#statuses.shouldRelayRecycled(message))
2293
+ return;
2294
+ this.#statuses.recordLastGood(message, { supersede: recycled });
2295
+ }
2296
+ if (message.type === "invalidate") {
2297
+ await this.#recycler.handleInvalidate(message);
1960
2298
  return;
1961
2299
  }
1962
- if (this.#failBuilderRequest(message, `builder is ${status}; reload after the builder is ready`))
2300
+ if (message.type === "build-route-res" || message.type === "build-csr-res" || message.type === "build-graph-res") {
2301
+ const answer = this.#requests.settle(message);
2302
+ if (!answer) {
2303
+ this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
2304
+ return;
2305
+ }
2306
+ this.#backend.send(answer);
1963
2307
  return;
1964
- this.logger.warn("akanAppHost builder is not running");
2308
+ }
2309
+ this.#backend.send(message);
1965
2310
  }
1966
- #stopBuilder() {
1967
- this.#cancelRssRecycle();
1968
- if (!this.#builder)
1969
- return;
1970
- if (this.#builder.patcherOff)
1971
- this.#patcherOff = true;
1972
- this.#builder.stop();
1973
- this.#builder = null;
2311
+ get #restartPending() {
2312
+ return this.#recycler.pending || this.#backend.restartPending || this.#builder.recovering || this.#rss.armed;
2313
+ }
2314
+ static async readProcessRssBytes(pid) {
2315
+ return await ProcessRss.bytesOf(pid);
2316
+ }
2317
+ static idleSuspendMs() {
2318
+ return DevIdleSuspend.idleMs();
1974
2319
  }
1975
2320
  }
1976
- // pkgs/@akanjs/devkit/applicationTestPreload.ts
2321
+ // pkgs/@akanjs/devkit/app/applicationTestPreload.ts
1977
2322
  import path5 from "path";
1978
2323
  var SIGNAL_TEST_PRELOAD_PATH = "test/signalTest.preload.ts";
1979
2324
  async function resolveSignalTestPreloadPath(target) {
@@ -1983,7 +2328,7 @@ async function resolveSignalTestPreloadPath(target) {
1983
2328
  candidates.push(path5.join(path5.dirname(Bun.resolveSync("akanjs/package.json", basePath)), SIGNAL_TEST_PRELOAD_PATH));
1984
2329
  } catch {}
1985
2330
  }
1986
- candidates.push(path5.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(path5.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.resolve(import.meta.dir, "../../akanjs", SIGNAL_TEST_PRELOAD_PATH));
2331
+ candidates.push(path5.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.join(path5.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path5.resolve(import.meta.dir, "../../../akanjs", SIGNAL_TEST_PRELOAD_PATH));
1987
2332
  const uniqueCandidates = [...new Set(candidates)];
1988
2333
  for (const candidate of uniqueCandidates)
1989
2334
  if (await Bun.file(candidate).exists())
@@ -2016,19 +2361,19 @@ var hasTestFile = (dir, seen = new Set) => {
2016
2361
  });
2017
2362
  };
2018
2363
  var testTargetOf = (exec) => {
2019
- const root = exec instanceof SysExecutor || exec instanceof PkgExecutor ? exec.workspace.workspaceRoot : process.cwd();
2364
+ const root = exec instanceof SysExecutor || exec instanceof PkgExecutor2 ? exec.workspace.workspaceRoot : process.cwd();
2020
2365
  return { root, target: path6.relative(root, exec.cwdPath).split(path6.sep).join("/") };
2021
2366
  };
2022
2367
  var reportsNoTestFile = (exec) => {
2023
2368
  if (hasTestFile(exec.cwdPath))
2024
2369
  return false;
2025
- const hint = exec instanceof AppExecutor || exec instanceof LibExecutor ? " A signal test goes beside its module, as lib/<model>/<model>.signal.test.ts." : "";
2370
+ const hint = exec instanceof AppExecutor2 || exec instanceof LibExecutor2 ? " A signal test goes beside its module, as lib/<model>/<model>.signal.test.ts." : "";
2026
2371
  Logger3.rawLog(`No *.test.ts or *.spec.ts file in ${testTargetOf(exec).target}, so no test ran.${hint}`);
2027
2372
  return true;
2028
2373
  };
2029
2374
 
2030
2375
  // pkgs/@akanjs/cli/application/application.runner.ts
2031
- var loadBuildRunner = async () => (await import("./applicationBuildRunner-df7rx3ra.js")).ApplicationBuildRunner;
2376
+ var loadBuildRunner = async () => (await import("./applicationBuildRunner-trfxv3pd.js")).ApplicationBuildRunner;
2032
2377
  var loadPrompts = async () => await import("@inquirer/prompts");
2033
2378
 
2034
2379
  class ApplicationRunner extends runner("application") {
@@ -2039,7 +2384,7 @@ class ApplicationRunner extends runner("application") {
2039
2384
  dict: { appName },
2040
2385
  options: { libs }
2041
2386
  });
2042
- return AppExecutor.from(workspace, appName);
2387
+ return AppExecutor2.from(workspace, appName);
2043
2388
  }
2044
2389
  async planSlice(app) {
2045
2390
  return await new SlicePlanner(app).plan();
@@ -2229,7 +2574,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2229
2574
  await new (await loadBuildRunner())(app).typecheck(options);
2230
2575
  }
2231
2576
  async typecheckLibrary(lib, options = {}) {
2232
- const { ProjectTypecheck } = await import("./projectTypecheck-kkrpq60a.js");
2577
+ const { ProjectTypecheck } = await import("./projectTypecheck-f4qhbecd.js");
2233
2578
  const root = lib.workspace.workspaceRoot;
2234
2579
  await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
2235
2580
  "../../server.ts",
@@ -2253,7 +2598,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2253
2598
  });
2254
2599
  }
2255
2600
  async test(exec, testPaths = [], flags = []) {
2256
- const isSignalTarget = exec instanceof AppExecutor || exec instanceof LibExecutor;
2601
+ const isSignalTarget = exec instanceof AppExecutor2 || exec instanceof LibExecutor2;
2257
2602
  if (!testPaths.length && reportsNoTestFile(exec))
2258
2603
  return;
2259
2604
  const preloadPath = isSignalTarget ? await resolveSignalTestPreloadPath(exec) : null;
@@ -2271,16 +2616,11 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2271
2616
  });
2272
2617
  }
2273
2618
  async build(app, {
2274
- fast = false,
2275
- reporter,
2276
2619
  spinner = false,
2277
2620
  envProfile,
2278
- environment,
2279
- budget
2621
+ ...options
2280
2622
  } = {}) {
2281
- return new (await loadBuildRunner())(app, { fast, reporter, profile: envProfile, environment, budget }).build({
2282
- spinner
2283
- });
2623
+ return new (await loadBuildRunner())(app, { ...options, profile: envProfile }).build({ spinner });
2284
2624
  }
2285
2625
  async start(app, {
2286
2626
  open = false,
@@ -2661,6 +3001,9 @@ ${detail}`
2661
3001
  }
2662
3002
 
2663
3003
  // pkgs/@akanjs/cli/verify/verifyScope.ts
3004
+ import path8 from "path";
3005
+ import ts from "typescript";
3006
+
2664
3007
  class VerifyScope {
2665
3008
  targets;
2666
3009
  constructor(targets) {
@@ -2672,6 +3015,51 @@ class VerifyScope {
2672
3015
  get changedFiles() {
2673
3016
  return new Set(this.targets.flatMap((target) => target.files));
2674
3017
  }
3018
+ get changedLibs() {
3019
+ return this.targets.filter((target) => target.type === "lib" && target.files.length).map((target) => target.name);
3020
+ }
3021
+ withDependents(names, libDeps) {
3022
+ const affected = new Set(this.changedLibs);
3023
+ if (!affected.size)
3024
+ return this;
3025
+ const known = VerifyScope.#knownTargets(names).filter((target) => target.type !== "pkg");
3026
+ const pulled = new Set;
3027
+ for (let grew = true;grew; ) {
3028
+ grew = false;
3029
+ for (const target of known) {
3030
+ if (pulled.has(target) || !(libDeps.get(target.dir) ?? []).some((lib) => affected.has(lib)))
3031
+ continue;
3032
+ pulled.add(target);
3033
+ if (target.type === "lib")
3034
+ affected.add(target.name);
3035
+ grew = true;
3036
+ }
3037
+ }
3038
+ const inScope = new Set(this.targets.map((target) => target.dir));
3039
+ const dependents = known.filter((target) => pulled.has(target) && !inScope.has(target.dir)).map((target) => ({ ...target, dependent: true }));
3040
+ return new VerifyScope([...this.targets, ...dependents]);
3041
+ }
3042
+ static async libDepsIn(workspaceRoot, { apps, libs }) {
3043
+ const dirs = [...apps.map((name) => `apps/${name}`), ...libs.map((name) => `libs/${name}`)];
3044
+ return new Map(await Promise.all(dirs.map(async (dir) => [dir, await VerifyScope.#libImportsIn(workspaceRoot, dir)])));
3045
+ }
3046
+ static async#libImportsIn(workspaceRoot, dir) {
3047
+ const libs = new Set;
3048
+ const cwd = path8.join(workspaceRoot, dir);
3049
+ for await (const file of new Bun.Glob("**/*.{ts,tsx}").scan({ cwd })) {
3050
+ if (/(^|[\\/])(node_modules|dist)[\\/]/.test(file))
3051
+ continue;
3052
+ const text = await Bun.file(path8.join(cwd, file)).text();
3053
+ if (!text.includes("@libs/"))
3054
+ continue;
3055
+ for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
3056
+ const lib = fileName.startsWith("@libs/") ? fileName.split("/")[1] : undefined;
3057
+ if (lib && `libs/${lib}` !== dir)
3058
+ libs.add(lib);
3059
+ }
3060
+ }
3061
+ return [...libs];
3062
+ }
2675
3063
  static async changesIn(workspaceRoot) {
2676
3064
  const prefix = await VerifyScope.#git(workspaceRoot, ["rev-parse", "--show-prefix"]);
2677
3065
  if (prefix === null)