@akanjs/cli 3.2.0-rc.9 → 3.2.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/.build-stamp +2 -2
  2. package/CodeAgent-xdw73nbz.js +11 -0
  3. package/{CodeTui-qstk5vpj.js → CodeTui-0gewm71c.js} +822 -666
  4. package/README.ko.md +7 -0
  5. package/README.md +7 -0
  6. package/TunnelShare-cccfdgbm.js +16 -0
  7. package/agent.command-g1mj34wz.js +59 -0
  8. package/akanCode.js +12 -12
  9. package/appExecutor-rrx10jya.js +11 -0
  10. package/{application.command-m4rq4wc2.js → application.command-3w4v7t40.js} +84 -40
  11. package/{applicationBuildRunner-df7rx3ra.js → applicationBuildRunner-y5xbetyz.js} +51 -20
  12. package/buildBatch.proc.js +31 -16
  13. package/{cloud.command-a0gy0qq2.js → cloud.command-ph0rz6sw.js} +28 -29
  14. package/cloud.script-8bs9tp4j.js +30 -0
  15. package/{code.command-5rsdqw8s.js → code.command-9b967qpg.js} +13 -9
  16. package/context.command-ndzs5rbf.js +62 -0
  17. package/context.runner-bmstpng2.js +32 -0
  18. package/csrArtifactBuilder-gtvff6k7.js +10 -0
  19. package/{index-qd7xn2bk.js → dependencyScanner-93g8tk0r.js} +7 -6
  20. package/{devTui-h77zrjv5.js → devTui-rf374y2w.js} +1 -1
  21. package/{fileSys-zpvt5gtf.js → fileSys-e5mwt73x.js} +1 -1
  22. package/frameworkGraph-aneq2nwy.js +8 -0
  23. package/{guideline.command-mffxknbr.js → guideline.command-y8qz9kxy.js} +9 -5
  24. package/guidelines/agentRule/agentRule.instruction.md +25 -9
  25. package/guidelines/akanApi/akanApi.instruction.md +6 -4
  26. package/guidelines/conventions/core.md +23 -5
  27. package/guidelines/conventions/rules/app.md +4 -1
  28. package/guidelines/conventions/rules/page.md +5 -4
  29. package/guidelines/conventions/rules/ts.md +3 -3
  30. package/guidelines/errorCodes/errorCodes.instruction.md +165 -0
  31. package/guidelines/fieldRule/fieldRule.instruction.md +2 -1
  32. package/guidelines/mcpRule/mcpRule.instruction.md +225 -5
  33. package/guidelines/pageRule/pageRule.instruction.md +10 -1
  34. package/guidelines/queryRule/queryRule.instruction.md +3 -1
  35. package/guidelines/runtimeRule/runtimeRule.instruction.md +14 -8
  36. package/guidelines/transportRule/transportRule.instruction.md +31 -1
  37. package/incrementalBuilder.proc.js +609 -437
  38. package/{index-skmtj8rm.js → index-02v45hh9.js} +27 -10
  39. package/{index-j6gc8n14.js → index-0csk6jqm.js} +11 -9
  40. package/{index-2r9ff9qm.js → index-0wa5z6rm.js} +2 -2
  41. package/{index-nmvhjn8c.js → index-0z8sbdme.js} +93 -82
  42. package/{index-2vgv7fs7.js → index-1c2807kg.js} +727 -693
  43. package/{index-hj6w4ka1.js → index-1p81ecbz.js} +1 -1
  44. package/{index-2mf1aen9.js → index-1p9bxjmt.js} +2 -2
  45. package/{index-an76bdrv.js → index-2kh4xj3m.js} +1 -1
  46. package/{index-99qvtff2.js → index-2vn0m9z5.js} +5 -5
  47. package/{index-rp4yf32g.js → index-3569fr49.js} +36 -29
  48. package/{index-xvk2a75m.js → index-38x8ynrx.js} +25 -25
  49. package/{index-cmg5ngqa.js → index-3fmzz9sf.js} +20 -20
  50. package/{index-rfzp4pqs.js → index-45aprybg.js} +3 -3
  51. package/{index-k92x3vne.js → index-4a1n0nym.js} +1 -1
  52. package/{index-ra9fvn7s.js → index-4zgm54wf.js} +76 -40
  53. package/{index-exn38bzx.js → index-652f3bs8.js} +116 -54
  54. package/{index-grxs6fts.js → index-6gepp8yn.js} +57 -31
  55. package/{index-vm0dn0mt.js → index-6j351de4.js} +294 -157
  56. package/{index-w15mg3km.js → index-7ssr7wq4.js} +1 -1
  57. package/{index-gxav1bjz.js → index-82cmbpxc.js} +9 -9
  58. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  59. package/{index-gcx48get.js → index-9rymt8d6.js} +2 -2
  60. package/{index-swwjakt0.js → index-ankyx6dj.js} +14 -18
  61. package/{index-28x1aszt.js → index-b0t92k71.js} +154 -58
  62. package/index-b372rck5.js +799 -0
  63. package/{index-yf9wc28h.js → index-bejy9zyc.js} +1 -1
  64. package/{index-r0a604h4.js → index-c669pbyb.js} +5 -4
  65. package/{index-xyn02k0w.js → index-cm9rb480.js} +662 -433
  66. package/{index-j9790rhk.js → index-d0n78fzc.js} +1635 -1139
  67. package/{index-hqv34wzq.js → index-dr1carpr.js} +10 -10
  68. package/index-f2arv0mv.js +30 -0
  69. package/{index-5radqwn2.js → index-gtydr9qc.js} +12 -12
  70. package/{index-j6eeh5d7.js → index-j3fqs8rc.js} +5 -5
  71. package/{index-yckz5t8b.js → index-jdw9m5c4.js} +516 -434
  72. package/{index-ny2k80mv.js → index-jf4vk1s0.js} +9 -2
  73. package/{index-x40bdsca.js → index-jg5rwrf7.js} +77 -115
  74. package/{index-5zwr4n6k.js → index-ktxdfqg5.js} +65 -8
  75. package/index-mnhrqjjq.js +127 -0
  76. package/{index-3ghdb7p5.js → index-pc42gxa5.js} +2777 -3676
  77. package/{index-0hbtve0a.js → index-q8h4eg5y.js} +32 -28
  78. package/{index-j3v29pq7.js → index-qh81drde.js} +219 -175
  79. package/{index-b4qq3rq0.js → index-rwgqba9p.js} +1 -1
  80. package/{index-w8yasvpc.js → index-scfsqen7.js} +2136 -2175
  81. package/{index-9p260r4e.js → index-trffs83s.js} +538 -250
  82. package/{index-0gg15zwa.js → index-twjgmryg.js} +6 -6
  83. package/index-whvhsb5f.js +80 -0
  84. package/{index-h7hehkw6.js → index-xczjdng6.js} +3 -1
  85. package/{index-39jz41jb.js → index-xs9a3ddt.js} +3 -3
  86. package/{index-35j83zkd.js → index-xv3pvdw4.js} +2 -2
  87. package/{index-34792nh7.js → index-y2g0s9tn.js} +1 -1
  88. package/{index-43f4h4cm.js → index-ymgsvhc5.js} +7 -8
  89. package/{index-ygdbn9jn.js → index-zyb0ebm4.js} +1 -1
  90. package/{index-bns3wcpc.js → index-zyjztrvc.js} +2 -2
  91. package/index.js +30 -24
  92. package/libExecutor-nstr00s7.js +10 -0
  93. package/{library.command-bmd7zc5m.js → library.command-b02aw1hm.js} +12 -5
  94. package/{localRegistry.command-y6en1599.js → localRegistry.command-3hg1p4aj.js} +24 -24
  95. package/{module.command-7exfffqw.js → module.command-bd9gz6cv.js} +11 -7
  96. package/{package.command-adskw2rj.js → package.command-xmr0mxze.js} +11 -10
  97. package/package.json +8 -8
  98. package/{page.command-dw01272p.js → page.command-x94qf58g.js} +8 -4
  99. package/{pipeline.command-0b1r3y5r.js → pipeline.command-n2843k6t.js} +15 -9
  100. package/pkgExecutor-cka27e3c.js +10 -0
  101. package/{primitive.command-byw6vc04.js → primitive.command-cs7v376h.js} +12 -8
  102. package/{projectTypecheck-kkrpq60a.js → projectTypecheck-za2n3nbr.js} +1 -1
  103. package/{prompter-qrwx1p17.js → prompter-d33wmdpa.js} +2 -2
  104. package/{quality.command-6rqnhzct.js → quality.command-nqngh1jd.js} +25 -16
  105. package/{recipeScanner-4b69ybe0.js → recipeScanner-rrx69awy.js} +1 -1
  106. package/{repair.command-rw5zymak.js → repair.command-v2medwsm.js} +12 -8
  107. package/{routeSourceValidator-4h947v7c.js → routeSourceValidator-8n6j1vn7.js} +4 -2
  108. package/{scalar.command-2dyp9nh9.js → scalar.command-61cjmxn1.js} +10 -6
  109. package/skills/akan-debug/SKILL.md +8 -5
  110. package/skills/akan-err/SKILL.md +7 -0
  111. package/skills/akan-mcp/SKILL.md +19 -1
  112. package/skills/akan-scaffold/SKILL.md +1 -1
  113. package/skills/akan-validate/SKILL.md +3 -3
  114. package/{subspace.command-111ynwv1.js → subspace.command-dtv8nfh7.js} +30 -24
  115. package/templates/app/page/_layout.tsx +13 -0
  116. package/templates/app/page/styles.css.template +40 -0
  117. package/templates/appSample/page/_index.tsx +9 -9
  118. package/templates/appSample/page/_layout.tsx +1 -0
  119. package/templates/appSample/page/styles.css.template +40 -5
  120. package/templates/appSample/ui/Recipe/jellyButton.ts +1 -1
  121. package/templates/biomeForm.ts +1 -1
  122. package/templates/env/_env.server.type.ts +1 -1
  123. package/templates/facetIndex/index.ts +2 -37
  124. package/templates/lib/sig.ts +0 -4
  125. package/templates/lib/useClient.ts +1 -1
  126. package/templates/workspaceRoot/.devcontainer/devcontainer.json.template +1 -1
  127. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  128. package/templates/workspaceRoot/README.ts +4 -2
  129. package/{tunnel.command-2gcpfbdj.js → tunnel.command-fmwm5fgb.js} +15 -13
  130. package/{typeChecker-s640r6c0.js → typeChecker-7jt6abrs.js} +1 -1
  131. package/typecheck.proc.js +3 -2
  132. package/{verify.command-djgs86ma.js → verify.command-4f260t53.js} +19 -17
  133. package/{workflow.command-n0k2mxr5.js → workflow.command-tm5q9xsm.js} +21 -14
  134. package/{workspace.command-fh1qwxfx.js → workspace.command-75gc280j.js} +56 -54
  135. package/CodeAgent-x2p3a3e0.js +0 -11
  136. package/TunnelShare-c4xsfzg5.js +0 -15
  137. package/agent.command-9et2e27p.js +0 -52
  138. package/cloud.script-xze4zh7n.js +0 -31
  139. package/context.command-rk1dwrg4.js +0 -57
  140. package/context.runner-83ky5m1b.js +0 -30
  141. package/dependencyScanner-78sq8m4q.js +0 -8
  142. /package/templates/{appSample → app}/public/fonts/Pretendard-Bold.woff2 +0 -0
  143. /package/templates/{appSample → app}/public/fonts/Pretendard-Medium.woff2 +0 -0
  144. /package/templates/{appSample → app}/public/fonts/Pretendard-Regular.woff2 +0 -0
  145. /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-pc42gxa5.js";
11
8
  import {
12
9
  FileSys2
13
- } from "./index-bns3wcpc.js";
10
+ } from "./index-zyjztrvc.js";
14
11
  import {
15
12
  CliError
16
13
  } from "./index-j4yvgfhr.js";
14
+ import {
15
+ AppExecutor2
16
+ } from "./index-b372rck5.js";
17
+ import {
18
+ LibExecutor2
19
+ } from "./index-f2arv0mv.js";
20
+ import {
21
+ PkgExecutor2
22
+ } from "./index-mnhrqjjq.js";
17
23
  import {
18
24
  UNAVAILABLE_REDIS_HOST,
19
25
  redisTunnelPolicy,
@@ -49,49 +55,50 @@ import {
49
55
  filesChangedSince,
50
56
  HmrWatcher,
51
57
  WatchRootResolver
52
- } from "./index-vm0dn0mt.js";
58
+ } from "./index-6j351de4.js";
53
59
  import {
54
60
  runner,
55
61
  assertPromptable
56
- } from "./index-exn38bzx.js";
62
+ } from "./index-652f3bs8.js";
57
63
  import {
58
64
  UpdatePackFolder,
59
65
  UpdateUploader,
60
66
  NativePublicEnv,
61
67
  NativeApp
62
- } from "./index-43f4h4cm.js";
68
+ } from "./index-ymgsvhc5.js";
63
69
  import {
64
70
  DesktopServerStage
65
- } from "./index-an76bdrv.js";
71
+ } from "./index-2kh4xj3m.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-9rymt8d6.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";
82
88
 
83
89
  // pkgs/@akanjs/cli/application/application.runner.ts
84
90
  import { existsSync, realpathSync as realpathSync2 } from "fs";
85
- import path7 from "path";
91
+ import path8 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 fs2 from "fs";
95
+ import path5 from "path";
96
+ import { Logger as Logger2 } from "akanjs/common";
90
97
 
91
- // pkgs/@akanjs/devkit/createTunnel.ts
98
+ // pkgs/@akanjs/devkit/tunnel/createTunnel.ts
92
99
  import { readFileSync } from "fs";
93
100
 
94
- // pkgs/@akanjs/devkit/sshHostKeys.ts
101
+ // pkgs/@akanjs/devkit/tunnel/sshHostKeys.ts
95
102
  import { createHash } from "crypto";
96
103
  import { mkdir, rm, writeFile } from "fs/promises";
97
104
  import path from "path";
@@ -138,7 +145,7 @@ class SshHostKeys {
138
145
  }
139
146
  }
140
147
 
141
- // pkgs/@akanjs/devkit/sshTunnel.ts
148
+ // pkgs/@akanjs/devkit/tunnel/sshTunnel.ts
142
149
  import { Client } from "ssh2";
143
150
  var closeQuietly = (close) => {
144
151
  try {
@@ -246,7 +253,7 @@ var closeBunSocket = (socket, error) => {
246
253
  closeQuietly(() => socket.end());
247
254
  };
248
255
 
249
- // pkgs/@akanjs/devkit/createTunnel.ts
256
+ // pkgs/@akanjs/devkit/tunnel/createTunnel.ts
250
257
  var tunnelEnv = new ShellOnlyEnv([
251
258
  "SSH_TUNNEL_PRIVATE_KEY_PATH",
252
259
  "SSH_TUNNEL_PASSPHRASE",
@@ -324,9 +331,322 @@ var createTunnel = async (service, { app, environment, port = service === "postg
324
331
  }
325
332
  return `localhost:${port}`;
326
333
  };
334
+
335
+ // pkgs/@akanjs/devkit/akanApp/BackendImportGraph.ts
336
+ import { stat } from "fs/promises";
337
+ import path2 from "path";
338
+ 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;
339
+ var GRAPH_IMPORT_KINDS = new Set([
340
+ "import-statement",
341
+ "require-call",
342
+ "require-resolve",
343
+ "dynamic-import"
344
+ ]);
345
+
346
+ class BackendImportGraph {
347
+ #app;
348
+ #logger;
349
+ #tsTranspiler = new Bun.Transpiler({ loader: "ts" });
350
+ #tsxTranspiler = new Bun.Transpiler({ loader: "tsx" });
351
+ #jsTranspiler = new Bun.Transpiler({ loader: "js" });
352
+ #jsxTranspiler = new Bun.Transpiler({ loader: "jsx" });
353
+ #files = new Set;
354
+ #scanCache = new Map;
355
+ #ready = false;
356
+ #lastRefreshSucceeded = false;
357
+ constructor(app, logger) {
358
+ this.#app = app;
359
+ this.#logger = logger;
360
+ }
361
+ get ready() {
362
+ return this.#ready;
363
+ }
364
+ get lastRefreshSucceeded() {
365
+ return this.#lastRefreshSucceeded;
366
+ }
367
+ has(file) {
368
+ return this.#files.has(path2.resolve(file));
369
+ }
370
+ async fingerprint() {
371
+ const stamps = await Promise.all([...this.#files].map(async (file) => {
372
+ const stats = await stat(file).catch(() => null);
373
+ return [file, stats ? `${Math.round(stats.mtimeMs)}:${stats.size}` : "(gone)"];
374
+ }));
375
+ return new Map(stamps);
376
+ }
377
+ async refresh() {
378
+ try {
379
+ const files = await this.#build();
380
+ this.#files = files;
381
+ this.#ready = true;
382
+ this.#lastRefreshSucceeded = true;
383
+ this.#logger.verbose(`[backend-graph] scanned ${files.size} files`);
384
+ return true;
385
+ } catch (err) {
386
+ this.#ready = this.#files.size > 0;
387
+ this.#lastRefreshSucceeded = false;
388
+ this.#logger.warn(`[backend-graph] scan failed; ${this.#ready ? "using previous graph" : "using fallback rules"}: ${err instanceof Error ? err.message : String(err)}`);
389
+ return this.#ready;
390
+ }
391
+ }
392
+ async#build() {
393
+ const roots = await this.#entrypoints();
394
+ const files = new Set;
395
+ const queue = [...roots];
396
+ const workspaceRoot = path2.resolve(this.#app.workspace.workspaceRoot);
397
+ while (queue.length > 0) {
398
+ const current = path2.resolve(queue.pop());
399
+ if (files.has(current))
400
+ continue;
401
+ if (!this.#isWorkspaceSource(current, workspaceRoot))
402
+ continue;
403
+ const imports = await this.#importsOf(current);
404
+ if (!imports)
405
+ continue;
406
+ files.add(current);
407
+ const importerDir = path2.dirname(current);
408
+ for (const imp of imports) {
409
+ if (!GRAPH_IMPORT_KINDS.has(imp.kind) || !imp.path || NON_SOURCE_EXT_RE.test(imp.path))
410
+ continue;
411
+ const resolved = this.#resolve(imp.path, importerDir);
412
+ if (!resolved || files.has(resolved))
413
+ continue;
414
+ queue.push(resolved);
415
+ }
416
+ }
417
+ for (const cached of this.#scanCache.keys())
418
+ if (!files.has(cached))
419
+ this.#scanCache.delete(cached);
420
+ return files;
421
+ }
422
+ async#importsOf(file) {
423
+ const stats = await stat(file).catch(() => null);
424
+ if (!stats?.isFile())
425
+ return null;
426
+ const mtimeMs = Math.round(stats.mtimeMs);
427
+ const cached = this.#scanCache.get(file);
428
+ if (cached && cached.mtimeMs === mtimeMs && cached.size === stats.size)
429
+ return cached.specifiers;
430
+ const specifiers = this.#scanImports(file, await Bun.file(file).text());
431
+ this.#scanCache.set(file, { mtimeMs, size: stats.size, specifiers });
432
+ return specifiers;
433
+ }
434
+ async#entrypoints() {
435
+ const roots = [`${this.#app.cwdPath}/main.ts`, `${this.#app.cwdPath}/server.ts`];
436
+ const existing = [];
437
+ for (const root of roots) {
438
+ const abs = path2.resolve(root);
439
+ if (await Bun.file(abs).exists())
440
+ existing.push(abs);
441
+ }
442
+ return existing;
443
+ }
444
+ #resolve(specifier, importerDir) {
445
+ try {
446
+ const resolved = Bun.resolveSync(specifier, importerDir);
447
+ if (!path2.isAbsolute(resolved))
448
+ return null;
449
+ if (!SOURCE_EXTS.has(path2.extname(resolved).toLowerCase()))
450
+ return null;
451
+ return path2.resolve(resolved);
452
+ } catch {
453
+ return null;
454
+ }
455
+ }
456
+ #isWorkspaceSource(file, workspaceRoot) {
457
+ const rel = path2.relative(workspaceRoot, file);
458
+ if (rel.startsWith("..") || path2.isAbsolute(rel))
459
+ return false;
460
+ if (rel.includes(`${path2.sep}node_modules${path2.sep}`) || rel.includes(`${path2.sep}.akan${path2.sep}`))
461
+ return false;
462
+ return SOURCE_EXTS.has(path2.extname(file).toLowerCase());
463
+ }
464
+ #scanImports(file, source) {
465
+ const ext = path2.extname(file).toLowerCase();
466
+ if (ext === ".tsx")
467
+ return this.#tsxTranspiler.scanImports(source);
468
+ if (ext === ".jsx")
469
+ return this.#jsxTranspiler.scanImports(source);
470
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
471
+ return this.#jsTranspiler.scanImports(source);
472
+ return this.#tsTranspiler.scanImports(source);
473
+ }
474
+ }
475
+
476
+ // pkgs/@akanjs/devkit/akanApp/builderGap.ts
477
+ class BuilderGap {
478
+ #graph;
479
+ #backend;
480
+ #logger;
481
+ #stamp = null;
482
+ constructor({ graph, backend, logger }) {
483
+ this.#graph = graph;
484
+ this.#backend = backend;
485
+ this.#logger = logger;
486
+ }
487
+ open(reason) {
488
+ if (this.#stamp)
489
+ return;
490
+ if (!this.#graph.ready) {
491
+ this.#logger.verbose(`[builder-gap] no backend graph yet; a save during this ${reason} goes unnoticed`);
492
+ return;
493
+ }
494
+ this.#stamp = this.#graph.fingerprint().then((stamps) => {
495
+ this.#logger.verbose(`[builder-gap] stamped ${stamps.size} backend file(s) (${reason})`);
496
+ return stamps;
497
+ }).catch((err) => {
498
+ this.#logger.warn(`[builder-gap] could not stamp the backend files: ${err instanceof Error ? err.message : String(err)}`);
499
+ return null;
500
+ });
501
+ }
502
+ async take() {
503
+ const stamping = this.#stamp;
504
+ this.#stamp = null;
505
+ const before = stamping ? await stamping : null;
506
+ if (!before)
507
+ return [];
508
+ const moved = filesChangedSince(before, await this.#graph.fingerprint());
509
+ if (moved.length === 0) {
510
+ this.#logger.verbose(`[builder-gap] none of the ${before.size} stamped backend file(s) moved`);
511
+ return moved;
512
+ }
513
+ this.#logger.info(`[builder-gap] ${moved.length} backend file(s) changed while the builder was away; the backend is running the old ones`);
514
+ return moved;
515
+ }
516
+ discard(reason) {
517
+ if (!this.#stamp)
518
+ return;
519
+ this.#stamp = null;
520
+ this.#logger.verbose(`[builder-gap] stamps dropped (${reason})`);
521
+ }
522
+ async restartBackendForChanges() {
523
+ const moved = await this.take();
524
+ if (moved.length === 0)
525
+ return;
526
+ this.#backend.scheduleRestart({ files: moved, roles: [] });
527
+ }
528
+ }
529
+
530
+ // pkgs/@akanjs/devkit/incrementalBuilder/builderRequestRouter.ts
531
+ class BuilderRequestRouter {
532
+ #generation = 0;
533
+ #nextId = 1;
534
+ #inFlight = new Map;
535
+ get generation() {
536
+ return this.#generation;
537
+ }
538
+ get inFlightCount() {
539
+ return this.#inFlight.size;
540
+ }
541
+ startGeneration() {
542
+ this.#generation += 1;
543
+ this.#inFlight.clear();
544
+ return this.#generation;
545
+ }
546
+ issue(message) {
547
+ const id = this.#nextId++;
548
+ this.#inFlight.set(id, { backendId: message.id, generation: this.#generation });
549
+ return { ...message, id };
550
+ }
551
+ withdraw(id) {
552
+ this.#inFlight.delete(id);
553
+ }
554
+ settle(message) {
555
+ const request = this.#inFlight.get(message.id);
556
+ if (!request)
557
+ return null;
558
+ this.#inFlight.delete(message.id);
559
+ if (request.generation !== this.#generation)
560
+ return null;
561
+ return { ...message, id: request.backendId };
562
+ }
563
+ }
564
+
565
+ // pkgs/@akanjs/devkit/akanApp/builderRequestRelay.ts
566
+ class BuilderRequestRelay {
567
+ #logger;
568
+ #env;
569
+ #links;
570
+ #requests = new BuilderRequestRouter;
571
+ #held = [];
572
+ constructor({ logger, env }, links) {
573
+ this.#logger = logger;
574
+ this.#env = env;
575
+ this.#links = links;
576
+ }
577
+ startGeneration() {
578
+ this.#requests.startGeneration();
579
+ }
580
+ settle(message) {
581
+ return this.#requests.settle(message);
582
+ }
583
+ send(message) {
584
+ this.#links.markActivity();
585
+ if (this.#links.away()) {
586
+ this.#held.push(message);
587
+ this.#links.wake(`${message.type} arrived while suspended`);
588
+ return;
589
+ }
590
+ if (message.type === "build-csr" && !message.shell && this.#env.AKAN_DEV_CSR_REBUILD !== "1") {
591
+ Object.assign(this.#env, { AKAN_DEV_CSR_REBUILD: "1" });
592
+ this.#logger.verbose(`[csr] armed dev CSR rebuilds (${message.reason})`);
593
+ }
594
+ const builder = this.#links.builder();
595
+ if (message.type === "build-route" || message.type === "build-csr" || message.type === "build-graph") {
596
+ const outgoing = this.#requests.issue(message);
597
+ if (builder?.send(outgoing))
598
+ return;
599
+ this.#requests.withdraw(outgoing.id);
600
+ } else if (builder?.send(message))
601
+ return;
602
+ const status = builder?.status ?? "stopped";
603
+ if (shouldHoldForReturningBuilder({ status, heldCount: this.#held.length })) {
604
+ this.#held.push(message);
605
+ const request = message.type === "build-route" ? `build-route ${message.routeId}` : message.type;
606
+ this.#logger.verbose(`[builder] holding ${request} until the builder is ready (${this.#held.length} waiting)`);
607
+ return;
608
+ }
609
+ if (this.#failRequest(message, `builder is ${status}; reload after the builder is ready`))
610
+ return;
611
+ this.#logger.warn("akanAppHost builder is not running");
612
+ }
613
+ flush() {
614
+ const pending = this.#held.splice(0);
615
+ if (pending.length === 0)
616
+ return;
617
+ this.#logger.verbose(`[builder] replaying ${pending.length} request(s) held while the builder was away`);
618
+ for (const message of pending)
619
+ this.send(message);
620
+ }
621
+ discard(reason) {
622
+ const held = this.#held.splice(0);
623
+ if (held.length === 0)
624
+ return;
625
+ this.#logger.verbose(`[builder] dropped ${held.length} held builder request(s): ${reason}`);
626
+ }
627
+ fail(reason) {
628
+ const held = this.#held.splice(0);
629
+ if (held.length === 0)
630
+ return;
631
+ this.#logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
632
+ for (const message of held)
633
+ this.#failRequest(message, reason);
634
+ }
635
+ #failRequest(message, error) {
636
+ if (message.type === "build-route")
637
+ this.#links.toBackend({ type: "build-route-res", id: message.id, ok: false, error, kind: "unavailable" });
638
+ else if (message.type === "build-csr")
639
+ this.#links.toBackend({ type: "build-csr-res", id: message.id, ok: false, error, kind: "unavailable" });
640
+ else if (message.type === "build-graph")
641
+ this.#links.toBackend({ type: "build-graph-res", id: message.id, ok: false, error, kind: "unavailable" });
642
+ else
643
+ return false;
644
+ return true;
645
+ }
646
+ }
327
647
  // pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.host.ts
328
648
  import fs from "fs";
329
- import path2 from "path";
649
+ import path3 from "path";
330
650
  import { Logger, RestartSchedule } from "akanjs/common";
331
651
  import { CSR_DEV_DIRNAME, CSR_DEV_PATCHING_MARKER, SSR_DEV_DIRNAME } from "akanjs/server/hmr/csrDevManifest";
332
652
  import { MemoryLimit } from "akanjs/server/memoryLimit";
@@ -422,6 +742,10 @@ class IncrementalBuilderHost {
422
742
  return;
423
743
  if (!msg || typeof msg !== "object")
424
744
  return;
745
+ if (msg.type === "base-built") {
746
+ this.#startOptions.onBaseBuilt?.(msg.phaseMs);
747
+ return;
748
+ }
425
749
  if (msg.type === "build-route-res" || msg.type === "build-csr-res" || msg.type === "build-graph-res")
426
750
  this.#inFlight.delete(msg.id);
427
751
  if (builderMsgTypeSet.has(msg.type))
@@ -471,7 +795,7 @@ class IncrementalBuilderHost {
471
795
  this.logger.verbose(`builder spawned pid=${proc.pid} entry=${this.entry}${isRestart ? " restart=1" : ""}`);
472
796
  }
473
797
  #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));
798
+ 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
799
  if (markers.length === 0)
476
800
  return;
477
801
  if (afterCrash && !this.#patcherOff) {
@@ -583,10 +907,10 @@ class IncrementalBuilderHost {
583
907
  patcherOff = false
584
908
  } = {}) {
585
909
  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")
910
+ path3.join(app.workspace.workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
911
+ path3.join(app.workspace.workspaceRoot, "node_modules/@akanjs/devkit/incrementalBuilder/incrementalBuilder.proc.ts"),
912
+ path3.join(import.meta.dir, "incrementalBuilder.proc.js"),
913
+ path3.join(import.meta.dir, "incrementalBuilder.proc.ts")
590
914
  ];
591
915
  for (const c of candidates)
592
916
  if (await Bun.file(c).exists())
@@ -594,650 +918,664 @@ class IncrementalBuilderHost {
594
918
  throw new Error(`[cli] frontend builder entry not found; looked in: ${candidates.join(", ")}`);
595
919
  }
596
920
  }
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;
604
- }
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)
624
- return null;
625
- this.#inFlight.delete(message.id);
626
- if (request.generation !== this.#generation)
627
- return null;
628
- return { ...message, id: request.backendId };
629
- }
630
- }
631
-
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
- ]);
921
+ // pkgs/@akanjs/devkit/akanApp/processRss.ts
922
+ var PS_RSS_TIMEOUT_MS = 2000;
642
923
 
643
- class BackendImportGraph {
644
- #app;
645
- #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;
656
- this.#logger = logger;
657
- }
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));
666
- }
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;
687
- }
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
- }
924
+ class ProcessRss {
925
+ static async bytesOf(pid) {
926
+ if (process.platform === "win32")
927
+ return await ProcessRss.#readRssKbVia(["tasklist", "/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], ProcessRss.#tasklistRssKb);
928
+ if (process.platform === "darwin") {
929
+ const footprintBytes = await ProcessRss.#readRssKbVia(["footprint", "-p", String(pid), "-f", "bytes"], ProcessRss.#footprintKb);
930
+ if (footprintBytes !== null)
931
+ return footprintBytes;
713
932
  }
714
- for (const cached of this.#scanCache.keys())
715
- if (!files.has(cached))
716
- this.#scanCache.delete(cached);
717
- return files;
933
+ const status = await Bun.file(`/proc/${pid}/status`).text().catch(() => null);
934
+ const vmRssKb = status === null ? null : /VmRSS:\s+(\d+) kB/.exec(status)?.[1];
935
+ if (vmRssKb)
936
+ return Number(vmRssKb) * 1024;
937
+ return await ProcessRss.#readRssKbVia(["ps", "-o", "rss=", "-p", String(pid)], (output) => Number(output.trim()));
718
938
  }
719
- async#importsOf(file) {
720
- const stats = await stat(file).catch(() => null);
721
- if (!stats?.isFile())
939
+ static async#readRssKbVia(command, parseKb, timeoutMs = PS_RSS_TIMEOUT_MS) {
940
+ let proc;
941
+ try {
942
+ proc = Bun.spawn(command, { stdio: ["ignore", "pipe", "ignore"] });
943
+ } catch {
722
944
  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);
738
945
  }
739
- return existing;
740
- }
741
- #resolve(specifier, importerDir) {
946
+ const killer = setTimeout(() => proc.kill("SIGKILL"), timeoutMs);
742
947
  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);
948
+ const output = await new Response(proc.stdout).text();
949
+ await proc.exited;
950
+ const rssKb = parseKb(output);
951
+ return Number.isFinite(rssKb) && rssKb > 0 ? rssKb * 1024 : null;
749
952
  } catch {
750
953
  return null;
954
+ } finally {
955
+ clearTimeout(killer);
751
956
  }
752
957
  }
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());
958
+ static #tasklistRssKb(output) {
959
+ const memUsage = /"([^"]*)"\s*$/m.exec(output)?.[1];
960
+ return memUsage ? Number(memUsage.replace(/\D/g, "")) : Number.NaN;
760
961
  }
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);
962
+ static #footprintKb(output) {
963
+ const bytes = /Footprint: (\d+) B\b/.exec(output)?.[1];
964
+ return bytes ? Number(bytes) / 1024 : Number.NaN;
770
965
  }
771
966
  }
772
967
 
773
- // pkgs/@akanjs/devkit/akanApp/devBootLatch.ts
774
- class DevBootLatch {
775
- #onBooted;
776
- #waitMs;
777
- #ready = false;
778
- #armed = false;
779
- #booted = false;
968
+ // pkgs/@akanjs/devkit/akanApp/builderRssRecycler.ts
969
+ var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
970
+ var BUILDER_RSS_RECYCLE_QUIET_MS = 750;
971
+ var BUILDER_RSS_SETTLE_MS = 20000;
972
+
973
+ class BuilderRssRecycler {
974
+ #logger;
975
+ #statuses;
976
+ #links;
780
977
  #timer = null;
781
- constructor(onBooted, { waitMs = 30000 } = {}) {
782
- this.#onBooted = onBooted;
783
- this.#waitMs = waitMs;
978
+ #reason = null;
979
+ #lastRecycleAtMono = null;
980
+ #ceilingTightReports = 0;
981
+ #ceilingTightWarned = false;
982
+ #settleToken = 0;
983
+ #over = null;
984
+ #ceilingAbandoned = false;
985
+ constructor({ logger, statuses }, links) {
986
+ this.#logger = logger;
987
+ this.#statuses = statuses;
988
+ this.#links = links;
784
989
  }
785
- ready() {
786
- this.#ready = true;
787
- if (!this.#armed && !this.#timer) {
788
- this.#timer = setTimeout(() => this.armed(), this.#waitMs);
789
- this.#timer.unref?.();
990
+ get armed() {
991
+ return !!this.#reason;
992
+ }
993
+ handleMetrics(metrics) {
994
+ if (this.#ceilingAbandoned)
995
+ return;
996
+ const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
997
+ const decision = decideBuilderRssRecycle({
998
+ rssBytes: metrics.rssBytes,
999
+ ceilingBytes,
1000
+ buildFailed: this.#statuses.failedAt(metrics.generation),
1001
+ msSinceLastRecycle: this.#lastRecycleAtMono === null ? null : performance.now() - this.#lastRecycleAtMono
1002
+ });
1003
+ if (decision === "below-ceiling") {
1004
+ this.#ceilingTightReports = 0;
1005
+ return;
790
1006
  }
791
- this.#release();
1007
+ if (decision === "unbounded")
1008
+ return;
1009
+ if (decision === "build-failed") {
1010
+ this.#logger.verbose(`[builder-recycle] deferred: generation=${metrics.generation} has a failing build, so a replacement would hit the same error`);
1011
+ return;
1012
+ }
1013
+ if (decision === "too-soon") {
1014
+ this.#ceilingTightReports += 1;
1015
+ if (this.#ceilingTightWarned || !shouldWarnBuilderRssCeilingTight(this.#ceilingTightReports))
1016
+ return;
1017
+ this.#ceilingTightWarned = true;
1018
+ 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.`);
1019
+ return;
1020
+ }
1021
+ this.#arm(`rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`, {
1022
+ rssBytes: metrics.rssBytes,
1023
+ ceilingBytes: ceilingBytes ?? 0
1024
+ });
792
1025
  }
793
- armed() {
794
- this.#armed = true;
795
- this.#release();
1026
+ async checkRecycledFloor() {
1027
+ if (this.#ceilingAbandoned || this.#lastRecycleAtMono === null)
1028
+ return;
1029
+ const ceilingBytes = IncrementalBuilderHost.maxRssBytes();
1030
+ const pid = this.#links.builder()?.pid;
1031
+ if (!ceilingBytes || !pid)
1032
+ return;
1033
+ const freshRssBytes = await ProcessRss.bytesOf(pid);
1034
+ if (!isRssCeilingUnreachable(freshRssBytes, ceilingBytes))
1035
+ return;
1036
+ this.#ceilingAbandoned = true;
1037
+ 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.`);
796
1038
  }
797
- #release() {
798
- if (this.#booted || !this.#ready || !this.#armed)
1039
+ rearm() {
1040
+ if (this.#reason)
1041
+ this.#arm(this.#reason);
1042
+ }
1043
+ cancel() {
1044
+ this.#reason = null;
1045
+ this.#over = null;
1046
+ this.#settleToken += 1;
1047
+ if (!this.#timer)
799
1048
  return;
800
- this.#booted = true;
1049
+ clearTimeout(this.#timer);
1050
+ this.#timer = null;
1051
+ }
1052
+ #arm(reason, over) {
1053
+ if (this.#reason !== reason)
1054
+ this.#logger.verbose(`[builder-recycle] armed (${reason}); replacing the builder once it stays quiet`);
1055
+ this.#reason = reason;
1056
+ if (over)
1057
+ this.#over = over;
801
1058
  if (this.#timer)
802
1059
  clearTimeout(this.#timer);
803
- this.#timer = null;
804
- this.#onBooted();
1060
+ this.#timer = setTimeout(() => {
1061
+ this.#timer = null;
1062
+ const pendingReason = this.#reason;
1063
+ const pendingOver = this.#over;
1064
+ this.#reason = null;
1065
+ this.#over = null;
1066
+ if (!pendingReason)
1067
+ return;
1068
+ if (!pendingOver) {
1069
+ this.#recycle(pendingReason);
1070
+ return;
1071
+ }
1072
+ this.#recycleWhenStillOver(pendingReason, pendingOver);
1073
+ }, BUILDER_RSS_RECYCLE_QUIET_MS);
1074
+ }
1075
+ async#recycleWhenStillOver(reason, { rssBytes, ceilingBytes }) {
1076
+ if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
1077
+ this.#recycle(reason);
1078
+ return;
1079
+ }
1080
+ const pid = this.#links.builder()?.pid;
1081
+ if (!pid) {
1082
+ this.#recycle(reason);
1083
+ return;
1084
+ }
1085
+ this.#settleToken += 1;
1086
+ const token = this.#settleToken;
1087
+ this.#logger.verbose(`[builder-recycle] holding ${Math.round(BUILDER_RSS_SETTLE_MS / 1000)}s to see whether the allocator returns it (${reason})`);
1088
+ await Bun.sleep(BUILDER_RSS_SETTLE_MS);
1089
+ if (token !== this.#settleToken || this.#links.builder()?.pid !== pid || this.#links.away()) {
1090
+ this.#logger.verbose("[builder-recycle] settle check abandoned; the builder moved on");
1091
+ return;
1092
+ }
1093
+ const settledBytes = await ProcessRss.bytesOf(pid);
1094
+ if (settledBytes !== null && settledBytes < ceilingBytes) {
1095
+ 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`);
1096
+ return;
1097
+ }
1098
+ this.#recycle(settledBytes === null ? reason : `${reason}; still ${asMib(settledBytes)}MiB after settling`);
1099
+ }
1100
+ #recycle(reason) {
1101
+ if (this.#links.restartQueued()) {
1102
+ this.#logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
1103
+ return;
1104
+ }
1105
+ if (!this.#links.builder()?.recycle(reason))
1106
+ return;
1107
+ this.#lastRecycleAtMono = performance.now();
1108
+ this.#links.onRecycle();
805
1109
  }
806
1110
  }
807
1111
 
808
- // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
1112
+ // pkgs/@akanjs/devkit/akanApp/devBackend.ts
1113
+ import { RestartSchedule as RestartSchedule2 } from "akanjs/common";
809
1114
  var backendMsgTypeSet = new Set(["build-route", "build-csr", "build-graph"]);
810
- var asMib = (bytes) => Math.round(bytes / 1024 / 1024);
811
1115
  var BACKEND_RESTART_DEBOUNCE_MS = 120;
812
1116
  var BACKEND_GRACEFUL_TIMEOUT_MS = 8000;
813
- 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
-
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;
1117
+ var BACKEND_STDERR_TAIL_LIMIT = 40;
1118
+
1119
+ class DevBackend {
1120
+ #app;
1121
+ #env;
1122
+ #stdio;
1123
+ #logger;
1124
+ #statuses;
1125
+ #graph;
1126
+ #links;
1127
+ #process = null;
1128
+ #ready = false;
1129
+ #plannedStops = new WeakSet;
833
1130
  #restartTimer = null;
834
- #backendRecovery = new RestartSchedule2(backendRecoveryPolicy);
835
- #backendGaveUp = false;
836
- #backendLifecycleState = "stopped";
1131
+ #recovery = new RestartSchedule2(backendRecoveryPolicy);
1132
+ #gaveUp = false;
1133
+ #lifecycleState = "stopped";
837
1134
  #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;
1135
+ #restart = null;
1136
+ #startStatus = null;
1137
+ #stderrTail = [];
1138
+ #queuedStatuses = [];
870
1139
  constructor(app, {
871
1140
  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);
1141
+ stdio,
1142
+ logger,
1143
+ statuses,
1144
+ graph
1145
+ }, links) {
1146
+ this.#app = app;
1147
+ this.#env = env;
1148
+ this.#stdio = stdio;
1149
+ this.#logger = logger;
1150
+ this.#statuses = statuses;
1151
+ this.#graph = graph;
1152
+ this.#links = links;
880
1153
  }
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();
1154
+ get running() {
1155
+ return !!this.#process;
888
1156
  }
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;
1157
+ get ready() {
1158
+ return this.#ready;
903
1159
  }
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;
1160
+ get gaveUp() {
1161
+ return this.#gaveUp;
917
1162
  }
918
- #clearRestartTimers() {
919
- if (this.#restartTimer)
920
- clearTimeout(this.#restartTimer);
921
- this.#restartTimer = null;
922
- this.#backendRecovery.cancel();
923
- this.#builderRecovery.cancel();
1163
+ get lifecycleState() {
1164
+ return this.#lifecycleState;
924
1165
  }
925
- kill() {
926
- this.stop();
1166
+ get restartScheduled() {
1167
+ return !!this.#restartTimer;
927
1168
  }
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
- }
1169
+ get recovering() {
1170
+ return this.#recovery.pending;
941
1171
  }
942
- #startBackend(startStatus = null) {
943
- if (this.#stopping)
1172
+ get restartPending() {
1173
+ return !!(this.#restartTimer || this.#restart || this.#recovery.pending);
1174
+ }
1175
+ get restarting() {
1176
+ return this.#restart;
1177
+ }
1178
+ start(startStatus = null) {
1179
+ if (this.#links.isStopping())
1180
+ return;
1181
+ if (this.#process) {
1182
+ this.#logger.warn(`backend pid=${this.#process.pid} is still running; not starting a second one`);
944
1183
  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,
1184
+ }
1185
+ this.#links.beforeSpawn();
1186
+ this.#startStatus = startStatus;
1187
+ this.#gaveUp = false;
1188
+ this.#setLifecycleState("starting");
1189
+ this.#ready = false;
1190
+ this.#stderrTail = [];
1191
+ const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
1192
+ cwd: this.#app.workspace.workspaceRoot,
1193
+ stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
1194
+ env: this.#links.awaitsArtifact() ? { ...this.#env, AKAN_DEV_AWAIT_ARTIFACT: "1" } : this.#env,
960
1195
  ipc: (msg) => {
961
1196
  if (!msg || typeof msg !== "object")
962
1197
  return;
963
1198
  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}`);
1199
+ this.#ready = true;
1200
+ this.#recovery.reset();
1201
+ this.#setLifecycleState("ready", `pid=${msg.pid}`);
1202
+ this.#recordReadyStatus();
1203
+ this.#logger.verbose(`backend ready pid=${msg.pid}`);
969
1204
  this.#forgetRouteBuildStatus();
970
- this.#replayBuilderState();
1205
+ this.replay();
971
1206
  return;
972
1207
  }
973
1208
  if (msg.type === "build-status") {
974
- const status = this.#recordBackendBuildStatus({
1209
+ const status = this.#statuses.recordBackend({
975
1210
  generation: normalizeBackendReportedGeneration(msg.data.generation),
976
1211
  ok: msg.data.ok,
977
1212
  files: msg.data.files,
978
1213
  message: msg.data.message
979
1214
  });
980
- this.#sendOrQueueBuildStatus(status);
1215
+ this.sendOrQueueStatus(status);
981
1216
  if (!status.ok)
982
- this.#emitDevEvent("failed", status.message);
1217
+ this.#links.emit("failed", status.message);
983
1218
  return;
984
1219
  }
985
1220
  if (backendMsgTypeSet.has(msg.type))
986
- this.#sendToBuilder(msg);
1221
+ this.#links.toBuilder(msg);
987
1222
  },
988
1223
  serialization: "advanced",
989
1224
  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);
1225
+ this.#ready = false;
1226
+ if (this.#process === backend)
1227
+ this.#process = null;
1228
+ if (this.#plannedStops.has(backend)) {
1229
+ this.#plannedStops.delete(backend);
995
1230
  return;
996
1231
  }
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);
1232
+ this.#scheduleRecovery("backend-exit");
1030
1233
  }
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
1234
  });
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);
1235
+ this.#process = backend;
1236
+ this.#logger.verbose(`backend spawned pid=${backend.pid}`);
1237
+ if (this.#stdio === "pipe") {
1238
+ this.#forwardStream(backend.stderr, "stderr");
1239
+ this.#forwardStream(backend.stdout, "stdout");
1067
1240
  }
1068
- this.#backendStartStatus = null;
1069
1241
  }
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
- }
1078
- #sendToBackend(message) {
1079
- if (!this.#backend || !this.#backendReady) {
1242
+ send(message) {
1243
+ if (!this.#process || !this.#ready) {
1080
1244
  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}`);
1245
+ this.#logger.verbose(`backend is not ready; will replay ${message.type}`);
1082
1246
  return;
1083
1247
  }
1084
1248
  if (message.type !== "builder-ready")
1085
- this.logger.warn(`backend is not ready; dropping ${message.type}`);
1249
+ this.#logger.warn(`backend is not ready; dropping ${message.type}`);
1086
1250
  return;
1087
1251
  }
1088
1252
  try {
1089
- this.#backend.send(message);
1253
+ this.#process.send(message);
1090
1254
  } catch (err) {
1091
- this.logger.warn(`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`);
1255
+ this.#logger.warn(`failed to send ${message.type} to backend: ${err instanceof Error ? err.message : String(err)}`);
1256
+ }
1257
+ }
1258
+ sendOrQueueStatus(status) {
1259
+ if (!this.#process || shouldQueueBuildStatusReplay(this.#ready, this.#queuedStatuses.length)) {
1260
+ this.#queuedStatuses.push(status);
1261
+ this.#logger.verbose(`backend is not ready; will replay build-status generation=${status.generation} phase=${status.phase}`);
1262
+ return;
1263
+ }
1264
+ this.send({ type: "build-status", data: status });
1265
+ }
1266
+ replay() {
1267
+ if (!this.#ready)
1268
+ return;
1269
+ const { css, pages } = this.#statuses.lastGood;
1270
+ if (css)
1271
+ this.send(css);
1272
+ if (pages)
1273
+ this.send(pages);
1274
+ const queuedStatuses = this.#queuedStatuses.splice(0);
1275
+ for (const status of this.#statuses.replaySequence(queuedStatuses)) {
1276
+ this.send({ type: "build-status", data: status });
1092
1277
  }
1093
1278
  }
1094
- async#stopBackend() {
1095
- if (!this.#backend)
1279
+ dropQueuedStatuses() {
1280
+ this.#queuedStatuses = [];
1281
+ }
1282
+ async stop() {
1283
+ if (!this.#process)
1096
1284
  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}`);
1285
+ const backend = this.#process;
1286
+ this.#plannedStops.add(backend);
1287
+ this.#ready = false;
1288
+ this.#setLifecycleState("stopping", `pid=${backend.pid}`);
1289
+ this.#logger.verbose(`stopping backend pid=${backend.pid}`);
1102
1290
  try {
1103
1291
  backend.kill("SIGTERM");
1104
1292
  const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), BACKEND_GRACEFUL_TIMEOUT_MS));
1105
1293
  const result = await Promise.race([backend.exited, timeout]);
1106
1294
  if (result === "timeout") {
1107
- this.logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
1295
+ this.#logger.warn(`backend pid=${backend.pid} did not exit in ${BACKEND_GRACEFUL_TIMEOUT_MS}ms; force killing`);
1108
1296
  backend.kill("SIGKILL");
1109
1297
  await backend.exited.catch(() => {
1110
1298
  return;
1111
1299
  });
1112
1300
  }
1113
1301
  } finally {
1114
- if (this.#backend === backend)
1115
- this.#backend = null;
1116
- this.#setBackendLifecycleState("stopped", `pid=${backend.pid}`);
1302
+ if (this.#process === backend)
1303
+ this.#process = null;
1304
+ this.#setLifecycleState("stopped", `pid=${backend.pid}`);
1117
1305
  }
1118
1306
  }
1119
- #scheduleBackendRestart(reason) {
1307
+ cancelTimers() {
1308
+ if (this.#restartTimer)
1309
+ clearTimeout(this.#restartTimer);
1310
+ this.#restartTimer = null;
1311
+ this.#recovery.cancel();
1312
+ }
1313
+ dropPendingRestart() {
1314
+ this.#pendingRestartReason = null;
1315
+ }
1316
+ scheduleRestart(reason) {
1120
1317
  this.#pendingRestartReason = mergeBackendRestartReasons(this.#pendingRestartReason, reason);
1121
1318
  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();
1319
+ this.#setLifecycleState("restart-pending", `generation=${pending.generation ?? "(unknown)"} files=${pending.files.length} roles=${pending.roles.join(",") || "(none)"}`);
1320
+ this.#recovery.cancel();
1124
1321
  if (this.#restartTimer)
1125
1322
  clearTimeout(this.#restartTimer);
1126
1323
  this.#restartTimer = setTimeout(() => {
1127
1324
  this.#restartTimer = null;
1128
- this.#backendRestart ??= this.#drainBackendRestarts().finally(() => {
1129
- this.#backendRestart = null;
1325
+ this.#restart ??= this.#drainRestarts().finally(() => {
1326
+ this.#restart = null;
1130
1327
  });
1131
1328
  }, BACKEND_RESTART_DEBOUNCE_MS);
1132
1329
  }
1133
- async#drainBackendRestarts() {
1134
- while (this.#pendingRestartReason && !this.#restartTimer && !this.#stopping) {
1330
+ reviveAfterGreenBuild(status) {
1331
+ if (!status.ok || !this.#gaveUp || this.#process || this.#recovery.pending)
1332
+ return;
1333
+ this.#logger.info(`[backend-recovery] build went green (generation=${status.generation}); retrying backend`);
1334
+ this.#recovery.reset();
1335
+ this.start({ generation: status.generation, files: status.files });
1336
+ }
1337
+ #recordStderr(chunk) {
1338
+ const lines = chunk.split(/\r?\n/).filter((line) => line.length > 0);
1339
+ if (lines.length === 0)
1340
+ return;
1341
+ this.#stderrTail.push(...lines);
1342
+ if (this.#stderrTail.length > BACKEND_STDERR_TAIL_LIMIT) {
1343
+ this.#stderrTail.splice(0, this.#stderrTail.length - BACKEND_STDERR_TAIL_LIMIT);
1344
+ }
1345
+ }
1346
+ async#forwardStream(stream, kind) {
1347
+ if (!stream)
1348
+ return;
1349
+ const decoder = new TextDecoder;
1350
+ try {
1351
+ for await (const chunk of stream) {
1352
+ const text = decoder.decode(chunk, { stream: true });
1353
+ if (!text)
1354
+ continue;
1355
+ if (kind === "stderr") {
1356
+ this.#recordStderr(text);
1357
+ process.stderr.write(text);
1358
+ } else
1359
+ process.stdout.write(text);
1360
+ }
1361
+ } catch {}
1362
+ }
1363
+ #recordReadyStatus() {
1364
+ const previous = this.#statuses.phase("backend");
1365
+ const startStatus = this.#startStatus;
1366
+ if (startStatus || previous?.ok === false) {
1367
+ const status = this.#statuses.recordBackend({
1368
+ generation: startStatus?.generation ?? previous?.generation,
1369
+ ok: true,
1370
+ files: startStatus?.files ?? previous?.files ?? [],
1371
+ message: "Backend ready"
1372
+ });
1373
+ this.sendOrQueueStatus(status);
1374
+ }
1375
+ this.#startStatus = null;
1376
+ }
1377
+ #forgetRouteBuildStatus() {
1378
+ this.#statuses.forgetRoute();
1379
+ this.#queuedStatuses = this.#queuedStatuses.filter((status) => status.phase !== "route");
1380
+ }
1381
+ #setLifecycleState(next, detail) {
1382
+ if (this.#lifecycleState === next && !detail)
1383
+ return;
1384
+ const prev = this.#lifecycleState;
1385
+ this.#lifecycleState = next;
1386
+ this.#logger.verbose(`[backend-lifecycle] ${prev} -> ${next}${detail ? ` ${detail}` : ""}`);
1387
+ this.#links.emit(devHostStateOf(next, this.#gaveUp), detail);
1388
+ }
1389
+ async#drainRestarts() {
1390
+ while (this.#pendingRestartReason && !this.#restartTimer && !this.#links.isStopping()) {
1135
1391
  const next = this.#pendingRestartReason;
1136
1392
  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(`
1393
+ await this.#restartWith(next);
1394
+ }
1395
+ }
1396
+ async#restartWith(reason) {
1397
+ this.#logger.verbose(`[backend-reload] restarting backend generation=${reason.generation ?? "(unknown)"} files=${reason.files.length} roles=${reason.roles.join(",") || "(none)"}`);
1398
+ this.#recovery.reset();
1399
+ await Promise.all([this.stop(), this.#graph.refresh()]);
1400
+ this.start({ generation: reason.generation, files: reason.files });
1401
+ }
1402
+ #scheduleRecovery(reason) {
1403
+ if (this.#recovery.pending || this.#process)
1404
+ return;
1405
+ if (this.#recovery.exhausted) {
1406
+ const message = `Backend exited ${this.#recovery.attempts} times in a row (${reason}); waiting for an edit or a green build to retry.`;
1407
+ this.#gaveUp = true;
1408
+ this.#setLifecycleState("stopped", `gave up after ${this.#recovery.attempts} recovery attempts`);
1409
+ this.#logger.error(`[backend-recovery] ${message}`);
1410
+ if (this.#stderrTail.length > 0) {
1411
+ this.#logger.error(`[backend-recovery] recent backend stderr:
1412
+ ${this.#stderrTail.join(`
1157
1413
  `)}`);
1158
1414
  }
1159
- const abandonedStatus = this.#recordBackendBuildStatus({ ok: false, files: [], message });
1160
- this.#sendOrQueueBuildStatus(abandonedStatus);
1415
+ const abandonedStatus = this.#statuses.recordBackend({ ok: false, files: [], message });
1416
+ this.sendOrQueueStatus(abandonedStatus);
1161
1417
  return;
1162
1418
  }
1163
- this.#setBackendLifecycleState("recovering", reason);
1164
- const delay = this.#backendRecovery.next();
1165
- const failureStatus = this.#recordBackendBuildStatus({
1419
+ this.#setLifecycleState("recovering", reason);
1420
+ const delay = this.#recovery.next();
1421
+ const failureStatus = this.#statuses.recordBackend({
1166
1422
  ok: false,
1167
1423
  files: [],
1168
1424
  message: `Backend exited unexpectedly (${reason}); restarting in ${delay}ms`
1169
1425
  });
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(`
1426
+ this.sendOrQueueStatus(failureStatus);
1427
+ this.#logger.warn(`[backend-recovery] backend exited unexpectedly (${reason}); restarting in ${delay}ms (attempt ${this.#recovery.attempts})`);
1428
+ if (this.#stderrTail.length > 0) {
1429
+ this.#logger.warn(`[backend-recovery] recent backend stderr:
1430
+ ${this.#stderrTail.join(`
1175
1431
  `)}`);
1176
1432
  }
1177
- this.#backendRecovery.arm(delay, () => {
1178
- if (this.#backend)
1433
+ this.#recovery.arm(delay, () => {
1434
+ if (this.#process)
1179
1435
  return;
1180
- this.#backendGraph.refresh().finally(() => {
1181
- if (!this.#backend)
1182
- this.#startBackend({ generation: failureStatus.generation, files: failureStatus.files });
1436
+ this.#graph.refresh().finally(() => {
1437
+ if (!this.#process)
1438
+ this.start({ generation: failureStatus.generation, files: failureStatus.files });
1183
1439
  });
1184
1440
  });
1185
1441
  }
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
- });
1442
+ }
1443
+
1444
+ // pkgs/@akanjs/devkit/akanApp/devBootLatch.ts
1445
+ class DevBootLatch {
1446
+ #onBooted;
1447
+ #waitMs;
1448
+ #ready = false;
1449
+ #armed = false;
1450
+ #booted = false;
1451
+ #timer = null;
1452
+ constructor(onBooted, { waitMs = 30000 } = {}) {
1453
+ this.#onBooted = onBooted;
1454
+ this.#waitMs = waitMs;
1190
1455
  }
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;
1456
+ ready() {
1457
+ this.#ready = true;
1458
+ if (!this.#armed && !this.#timer) {
1459
+ this.#timer = setTimeout(() => this.armed(), this.#waitMs);
1460
+ this.#timer.unref?.();
1206
1461
  }
1207
- if (message.type === "boot-armed") {
1208
- this.logger.verbose("[builder] boot builds settled");
1209
- this.#bootLatch.armed();
1462
+ this.#release();
1463
+ }
1464
+ armed() {
1465
+ this.#armed = true;
1466
+ this.#release();
1467
+ }
1468
+ #release() {
1469
+ if (this.#booted || !this.#ready || !this.#armed)
1210
1470
  return;
1471
+ this.#booted = true;
1472
+ if (this.#timer)
1473
+ clearTimeout(this.#timer);
1474
+ this.#timer = null;
1475
+ this.#onBooted();
1476
+ }
1477
+ }
1478
+
1479
+ // pkgs/@akanjs/devkit/akanApp/devBuilder.ts
1480
+ import { RestartSchedule as RestartSchedule3 } from "akanjs/common";
1481
+ var BUILDER_READY_TIMEOUT_MS = 150000;
1482
+ var BUILDER_START_MAX_ATTEMPTS = 3;
1483
+
1484
+ class DevBuilder {
1485
+ #app;
1486
+ #env;
1487
+ #stdio;
1488
+ #logger;
1489
+ #links;
1490
+ #host = null;
1491
+ #patcherOff = false;
1492
+ #recovery = new RestartSchedule3({ min: 2000, max: 60000 });
1493
+ #abandonStart = null;
1494
+ #generation = 0;
1495
+ constructor(app, { env, stdio, logger }, links) {
1496
+ this.#app = app;
1497
+ this.#env = env;
1498
+ this.#stdio = stdio;
1499
+ this.#logger = logger;
1500
+ this.#links = links;
1501
+ }
1502
+ get current() {
1503
+ return this.#host;
1504
+ }
1505
+ get recovering() {
1506
+ return this.#recovery.pending;
1507
+ }
1508
+ async start({ announceBootState = false } = {}) {
1509
+ const startTime = Date.now();
1510
+ this.#app.verbose(`[cli] waiting for builder to complete initial base build\u2026`);
1511
+ let lastError;
1512
+ for (let attempt = 1;attempt <= BUILDER_START_MAX_ATTEMPTS; attempt++) {
1513
+ const builder = await IncrementalBuilderHost.create(this.#app, this.#env, (msg) => {
1514
+ this.#links.onMessage(msg);
1515
+ }, {
1516
+ stdio: this.#stdio,
1517
+ onOutput: (kind, text) => void (kind === "stderr" ? process.stderr : process.stdout).write(text),
1518
+ patcherOff: this.#patcherOff
1519
+ });
1520
+ if (this.#links.isStopping()) {
1521
+ builder.stop();
1522
+ throw new Error("dev server stopped before the builder started");
1523
+ }
1524
+ this.#host = builder;
1525
+ try {
1526
+ await this.#waitForReady(attempt, { announceBootState });
1527
+ this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms`);
1528
+ return this.#host;
1529
+ } catch (err) {
1530
+ lastError = err;
1531
+ this.stop();
1532
+ if (attempt >= BUILDER_START_MAX_ATTEMPTS || this.#links.isStopping())
1533
+ break;
1534
+ this.#app.verbose(`[cli] builder failed before ready; retrying (${attempt + 1}/${BUILDER_START_MAX_ATTEMPTS})`);
1535
+ }
1211
1536
  }
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);
1537
+ this.#links.onStartFailed();
1538
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
1539
+ }
1540
+ stop() {
1541
+ this.#links.onStop();
1542
+ if (!this.#host)
1220
1543
  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);
1544
+ if (this.#host.patcherOff)
1545
+ this.#patcherOff = true;
1546
+ this.#host.stop();
1547
+ this.#host = null;
1548
+ }
1549
+ abandonStart(error) {
1550
+ this.#abandonStart?.(error);
1551
+ }
1552
+ cancelRecovery() {
1553
+ this.#recovery.cancel();
1554
+ }
1555
+ resetRecovery() {
1556
+ this.#recovery.reset();
1557
+ }
1558
+ clearPatcherOff() {
1559
+ this.#patcherOff = false;
1560
+ }
1561
+ scheduleRecovery(reason) {
1562
+ if (this.#links.isStopping() || this.#recovery.pending || this.#host)
1229
1563
  return;
1230
- }
1231
- this.#sendToBackend(message);
1564
+ const delay = this.#recovery.schedule(() => {
1565
+ if (this.#links.isStopping() || this.#host)
1566
+ return;
1567
+ this.#recover(reason);
1568
+ });
1569
+ this.#logger.warn(`[builder-recovery] builder is down; retrying start in ${delay}ms (attempt ${this.#recovery.attempts})`);
1232
1570
  }
1233
- #trackBuilderGeneration(message) {
1234
- const generation = AkanAppHost.#builderGenerationOf(message);
1235
- if (generation === undefined || generation <= this.#builderGeneration)
1571
+ trackGeneration(message) {
1572
+ const generation = DevBuilder.#generationOf(message);
1573
+ if (generation === undefined || generation <= this.#generation)
1236
1574
  return;
1237
- this.#builderGeneration = generation;
1238
- Object.assign(this.env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
1575
+ this.#generation = generation;
1576
+ Object.assign(this.#env, { AKAN_BUILDER_INITIAL_GENERATION: String(generation) });
1239
1577
  }
1240
- static #builderGenerationOf(message) {
1578
+ static #generationOf(message) {
1241
1579
  if (message.type === "invalidate")
1242
1580
  return message.generation;
1243
1581
  if (message.type === "build-status" || message.type === "builder-metrics")
@@ -1246,398 +1584,369 @@ ${this.#backendStderrTail.join(`
1246
1584
  return message.data.generation;
1247
1585
  return;
1248
1586
  }
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))
1587
+ async#recover(reason) {
1588
+ try {
1589
+ await this.start();
1590
+ } catch (err) {
1591
+ if (this.#links.isStopping())
1281
1592
  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.`);
1593
+ this.#logger.warn(`[builder-recovery] builder start failed: ${err instanceof Error ? err.message : String(err)}`);
1594
+ this.scheduleRecovery(reason);
1284
1595
  return;
1285
1596
  }
1286
- this.#armRssRecycle(`rss=${asMib(metrics.rssBytes)}MiB>=${asMib(ceilingBytes ?? 0)}MiB after ${metrics.workCount} build(s)`, { rssBytes: metrics.rssBytes, ceilingBytes: ceilingBytes ?? 0 });
1597
+ this.#recovery.reset();
1598
+ this.#logger.info("[builder-recovery] builder recovered");
1599
+ this.#links.onRecovered(reason);
1287
1600
  }
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.`);
1601
+ #waitForReady(attempt, { announceBootState = false } = {}) {
1602
+ return new Promise((resolve, reject) => {
1603
+ if (!this.#host)
1604
+ throw new Error("Builder Not Found");
1605
+ let settled = false;
1606
+ const settle = (fn) => {
1607
+ if (settled)
1608
+ return;
1609
+ settled = true;
1610
+ clearTimeout(timeout);
1611
+ if (this.#abandonStart === abandon)
1612
+ this.#abandonStart = null;
1613
+ fn();
1614
+ };
1615
+ const abandon = (error) => settle(() => reject(error));
1616
+ this.#abandonStart = abandon;
1617
+ const timeout = setTimeout(() => {
1618
+ settle(() => reject(new Error("[cli] builder timed out before emitting builder-ready")));
1619
+ }, BUILDER_READY_TIMEOUT_MS);
1620
+ this.#host.start({
1621
+ announceBootState,
1622
+ onExit: () => {
1623
+ settle(() => reject(new Error(`[cli] builder exited before emitting builder-ready (attempt ${attempt})`)));
1624
+ },
1625
+ onAway: () => {
1626
+ this.#links.onAway();
1627
+ },
1628
+ onReady: () => {
1629
+ settle(resolve);
1630
+ this.#links.onReady();
1631
+ },
1632
+ onBaseBuilt: (phaseMs) => {
1633
+ this.#links.onBaseBuilt(phaseMs);
1634
+ },
1635
+ onRestartReady: () => {
1636
+ this.#links.onRestartReady();
1637
+ }
1638
+ });
1639
+ });
1300
1640
  }
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);
1641
+ }
1642
+
1643
+ // pkgs/@akanjs/devkit/akanApp/devBuildStatusBoard.ts
1644
+ class DevBuildStatusBoard {
1645
+ #logger;
1646
+ #byPhase = new Map;
1647
+ #backendGeneration = 0;
1648
+ #lastGood = {};
1649
+ constructor(logger) {
1650
+ this.#logger = logger;
1323
1651
  }
1324
- async#recycleBuilderForRssWhenStillOver(reason, { rssBytes, ceilingBytes }) {
1325
- if (decideBuilderRssSettle({ rssBytes, ceilingBytes }) === "recycle-now") {
1326
- this.#recycleBuilderForRss(reason);
1327
- return;
1652
+ get lastGood() {
1653
+ return this.#lastGood;
1654
+ }
1655
+ get failing() {
1656
+ return hasAnyBuildFailure(this.#byPhase);
1657
+ }
1658
+ phase(phase) {
1659
+ return this.#byPhase.get(phase);
1660
+ }
1661
+ failedAt(generation) {
1662
+ return hasBuildFailureForGeneration(this.#byPhase, generation);
1663
+ }
1664
+ replaySequence(queued) {
1665
+ return buildStatusReplaySequence(queued, this.#byPhase);
1666
+ }
1667
+ nextBackendGeneration(generation) {
1668
+ if (typeof generation === "number") {
1669
+ this.#backendGeneration = Math.max(this.#backendGeneration, generation);
1670
+ return generation;
1328
1671
  }
1329
- const pid = this.#builder?.pid;
1330
- if (!pid) {
1331
- this.#recycleBuilderForRss(reason);
1672
+ this.#backendGeneration += 1;
1673
+ return this.#backendGeneration;
1674
+ }
1675
+ record(status) {
1676
+ const recovered = shouldMarkBuildPhaseRecovered(this.#byPhase, status);
1677
+ if (shouldKeepBuildFailure(this.#byPhase, status))
1332
1678
  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");
1679
+ this.#byPhase.set(status.phase, status);
1680
+ const label = `[build-status] generation=${status.generation} phase=${status.phase} ok=${status.ok} files=${status.files.length}`;
1681
+ if (status.ok)
1682
+ this.#logger.verbose(`${label}${recovered ? " recovered=1" : ""}`);
1683
+ else
1684
+ this.#logger.warn(`${label}${status.message ? ` message=${status.message}` : ""}`);
1685
+ }
1686
+ recordBackend({
1687
+ generation,
1688
+ ok,
1689
+ files,
1690
+ message
1691
+ }) {
1692
+ const status = createBackendBuildStatus({
1693
+ generation: this.nextBackendGeneration(generation),
1694
+ ok,
1695
+ files,
1696
+ message
1697
+ });
1698
+ this.record(status);
1699
+ return status;
1700
+ }
1701
+ forgetRoute() {
1702
+ this.#byPhase.delete("route");
1703
+ }
1704
+ reset() {
1705
+ this.#lastGood = {};
1706
+ this.#byPhase.clear();
1707
+ }
1708
+ recordLastGood(message, { supersede = false } = {}) {
1709
+ if (message.type === "pages-updated") {
1710
+ if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.pages, message))
1711
+ return;
1712
+ this.#lastGood.pages = message;
1713
+ this.#logger.verbose(`[last-good] pages generation=${message.data.generation ?? "(unknown)"} buildId=${message.data.buildId}`);
1340
1714
  return;
1341
1715
  }
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`);
1716
+ if (!supersede && !shouldReplaceLastGoodMessage(this.#lastGood.css, message))
1345
1717
  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()));
1718
+ this.#lastGood.css = message;
1719
+ this.#logger.verbose(`[last-good] css generation=${message.data.generation ?? "(unknown)"} assets=${Object.keys(message.data.cssAssets).length}`);
1362
1720
  }
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);
1721
+ shouldRelayRecycled(message) {
1722
+ const current = message.type === "pages-updated" ? this.#lastGood.pages : this.#lastGood.css;
1723
+ if (shouldRelayRecycledFrontendState(current, message)) {
1724
+ this.#logger.verbose(`[builder-recycle] ${message.type} moved during the recycle; pushing it to the backend`);
1725
+ return true;
1380
1726
  }
1727
+ this.#logger.verbose(`[builder-recycle] ${message.type} unchanged after the recycle; backend left as is`);
1728
+ return false;
1381
1729
  }
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;
1730
+ }
1731
+
1732
+ // pkgs/@akanjs/devkit/akanApp/devIdleSuspend.ts
1733
+ class DevIdleSuspend {
1734
+ #app;
1735
+ #logger;
1736
+ #links;
1737
+ #timer = null;
1738
+ #suspended = false;
1739
+ #waking = false;
1740
+ #stopped = false;
1741
+ #activity = 0;
1742
+ #wokeAtMono = null;
1743
+ #watcher = null;
1744
+ #suspendedChanges = null;
1745
+ constructor(app, { logger }, links) {
1746
+ this.#app = app;
1747
+ this.#logger = logger;
1748
+ this.#links = links;
1398
1749
  }
1399
- static idleSuspendMs() {
1750
+ static idleMs() {
1400
1751
  return resolveIdleSuspendMs(process.env.AKAN_DEV_IDLE_SUSPEND_MS);
1401
1752
  }
1402
- #markDevActivity() {
1753
+ get away() {
1754
+ return !this.#stopped && (this.#suspended || this.#waking);
1755
+ }
1756
+ markActivity() {
1757
+ this.#activity++;
1403
1758
  if (this.#suspended || this.#waking)
1404
1759
  return;
1405
- this.#armIdleSuspend();
1760
+ this.arm();
1406
1761
  }
1407
- #armIdleSuspend() {
1408
- const idleMs = AkanAppHost.idleSuspendMs();
1409
- this.#cancelIdleSuspend();
1410
- if (idleMs === null)
1762
+ arm() {
1763
+ const idleMs = DevIdleSuspend.idleMs();
1764
+ this.#cancel();
1765
+ if (idleMs === null || this.#stopped)
1411
1766
  return;
1412
- this.#idleSuspendTimer = setTimeout(() => {
1413
- this.#idleSuspendTimer = null;
1767
+ this.#timer = setTimeout(() => {
1768
+ this.#timer = null;
1414
1769
  this.#suspendWhenIdle(idleMs);
1415
1770
  }, idleMs);
1416
1771
  }
1417
- #cancelIdleSuspend() {
1418
- if (!this.#idleSuspendTimer)
1772
+ #cancel() {
1773
+ if (!this.#timer)
1419
1774
  return;
1420
- clearTimeout(this.#idleSuspendTimer);
1421
- this.#idleSuspendTimer = null;
1775
+ clearTimeout(this.#timer);
1776
+ this.#timer = null;
1422
1777
  }
1423
- async#suspendWhenIdle(idleMs) {
1424
- const decision = decideIdleSuspend({
1778
+ #stopWatcher() {
1779
+ this.#watcher?.stop();
1780
+ this.#watcher = null;
1781
+ }
1782
+ stop() {
1783
+ this.#stopped = true;
1784
+ this.#cancel();
1785
+ this.#stopWatcher();
1786
+ }
1787
+ async wake(reason) {
1788
+ if (!this.#suspended || this.#waking || this.#stopped)
1789
+ return;
1790
+ this.#waking = true;
1791
+ this.#cancel();
1792
+ const startedAtMono = performance.now();
1793
+ this.#logger.info(`[idle-suspend] waking (${reason})`);
1794
+ const watcher = this.#watcher;
1795
+ this.#watcher = null;
1796
+ let batch = null;
1797
+ try {
1798
+ const unreported = await watcher?.close();
1799
+ if (unreported)
1800
+ this.#recordSuspendedChange(unreported);
1801
+ batch = this.#suspendedChanges;
1802
+ this.#suspendedChanges = null;
1803
+ if (this.#stopped)
1804
+ return;
1805
+ await this.#links.wake(batch);
1806
+ this.#logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
1807
+ } catch (err) {
1808
+ this.#logger.error(`[idle-suspend] wake failed; recovering the builder: ${err instanceof Error ? err.message : String(err)}`);
1809
+ this.#links.wakeFailed(batch?.files ?? []);
1810
+ } finally {
1811
+ this.#suspended = false;
1812
+ this.#waking = false;
1813
+ this.#wokeAtMono = performance.now();
1814
+ this.#links.flushHeld();
1815
+ this.arm();
1816
+ if (!this.#stopped)
1817
+ this.#links.awake();
1818
+ }
1819
+ }
1820
+ #decide() {
1821
+ return decideIdleSuspend({
1425
1822
  enabled: true,
1426
1823
  suspended: this.#suspended,
1427
- builderReady: this.#builder?.status === "ready",
1428
- backendReady: this.#backendReady,
1429
- buildFailed: hasAnyBuildFailure(this.#buildStatusByPhase),
1430
- restartPending: this.#restartPending,
1824
+ ...this.#links.readiness(),
1431
1825
  msSinceWake: this.#wokeAtMono === null ? null : performance.now() - this.#wokeAtMono
1432
1826
  });
1827
+ }
1828
+ async#suspendWhenIdle(idleMs) {
1829
+ const decision = this.#decide();
1433
1830
  if (decision !== "suspend") {
1434
- this.logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
1435
- this.#armIdleSuspend();
1831
+ this.#logger.verbose(`[idle-suspend] skipped (${decision}); re-arming`);
1832
+ this.arm();
1833
+ return;
1834
+ }
1835
+ const activity = this.#activity;
1836
+ const watcher = await this.#startWatcher();
1837
+ if (!watcher) {
1838
+ this.arm();
1839
+ return;
1840
+ }
1841
+ if (this.#stopped) {
1842
+ watcher.stop();
1436
1843
  return;
1437
1844
  }
1438
- if (!await this.#startIdleWatcher()) {
1439
- this.#armIdleSuspend();
1845
+ const recheck = this.#activity === activity ? this.#decide() : "busy";
1846
+ if (recheck !== "suspend") {
1847
+ this.#logger.verbose(`[idle-suspend] skipped (${recheck} while the idle watcher started); re-arming`);
1848
+ watcher.stop();
1849
+ this.arm();
1440
1850
  return;
1441
1851
  }
1852
+ this.#watcher = watcher;
1442
1853
  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);
1854
+ this.#links.release(`idle ${Math.round(idleMs / 1000)}s`);
1855
+ 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`);
1450
1856
  }
1451
- async#startIdleWatcher() {
1857
+ async#startWatcher() {
1858
+ let watcher = null;
1452
1859
  try {
1453
- const roots = await new WatchRootResolver(this.app).resolve();
1454
- const watcher = new HmrWatcher({
1860
+ const roots = await new WatchRootResolver(this.#app).resolve();
1861
+ watcher = new HmrWatcher({
1455
1862
  roots,
1456
- logger: this.logger,
1863
+ logger: this.#logger,
1457
1864
  onBatch: (batch) => {
1458
1865
  this.#recordSuspendedChange(batch);
1459
- this.#wakeFromIdle(`${batch.files.length} file(s) changed`);
1866
+ this.wake(`${batch.files.length} file(s) changed`);
1460
1867
  }
1461
1868
  });
1462
1869
  await watcher.start();
1463
- this.#idleWatcher = watcher;
1464
- return true;
1870
+ return watcher;
1465
1871
  } 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;
1872
+ this.#logger.warn(`[idle-suspend] could not install the idle watcher; staying awake: ${err instanceof Error ? err.message : String(err)}`);
1873
+ watcher?.stop();
1874
+ return null;
1469
1875
  }
1470
1876
  }
1471
- #stopIdleWatcher() {
1472
- this.#idleWatcher?.stop();
1473
- this.#idleWatcher = null;
1474
- }
1475
1877
  #recordSuspendedChange(batch) {
1476
1878
  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
- };
1485
- }
1486
- async#wakeFromIdle(reason) {
1487
- if (!this.#suspended || this.#waking)
1488
- return;
1489
- this.#waking = true;
1490
- this.#cancelIdleSuspend();
1491
- this.#stopIdleWatcher();
1492
- const batch = this.#suspendedChanges;
1493
- this.#suspendedChanges = null;
1494
- const startedAtMono = performance.now();
1495
- this.logger.info(`[idle-suspend] waking (${reason})`);
1496
- try {
1497
- await this.#applyIdleWake(batch);
1498
- this.logger.info(`[idle-suspend] awake in ${Math.round(performance.now() - startedAtMono)}ms`);
1499
- } 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 ?? [] });
1502
- } finally {
1503
- this.#suspended = false;
1504
- this.#waking = false;
1505
- this.#wokeAtMono = performance.now();
1506
- this.#flushPendingBuilderMessages();
1507
- this.#armIdleSuspend();
1508
- this.#emitDevEvent(devHostStateOf(this.#backendLifecycleState, this.#backendGaveUp));
1509
- }
1510
- }
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;
1542
- });
1543
- }
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)
1567
- return;
1568
- this.#scheduleBackendRestart({ files: moved, roles: [] });
1569
- }
1570
- #flushPendingBuilderMessages() {
1571
- const pending = this.#pendingBuilderMessages.splice(0);
1572
- if (pending.length === 0)
1573
- 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)
1581
- 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)
1587
- return;
1588
- this.logger.warn(`failing ${held.length} held builder request(s): ${reason}`);
1589
- for (const message of held)
1590
- this.#failBuilderRequest(message, reason);
1591
- }
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;
1602
- }
1603
- #recycleBuilderForRss(reason) {
1604
- if (this.#pendingRecycle || this.#restartTimer) {
1605
- this.logger.verbose(`[builder-recycle] skipped (${reason}); a dev restart is already pending`);
1879
+ if (!current) {
1880
+ this.#suspendedChanges = { files: [...batch.files], kinds: new Set(batch.kinds) };
1606
1881
  return;
1607
1882
  }
1608
- if (!this.#builder?.recycle(reason))
1609
- return;
1610
- this.#lastRssRecycleAtMono = performance.now();
1611
- this.#openBuilderGap("builder recycle");
1883
+ this.#suspendedChanges = {
1884
+ files: [...new Set([...current.files, ...batch.files])],
1885
+ kinds: new Set([...current.kinds, ...batch.kinds])
1886
+ };
1612
1887
  }
1613
- async#handleInvalidate(message) {
1888
+ }
1889
+
1890
+ // pkgs/@akanjs/devkit/akanApp/devRecycler.ts
1891
+ import path4 from "path";
1892
+ class DevRecycler {
1893
+ #app;
1894
+ #env;
1895
+ #logger;
1896
+ #isStopping;
1897
+ #graph;
1898
+ #statuses;
1899
+ #backend;
1900
+ #builder;
1901
+ #gap;
1902
+ #rss;
1903
+ #pending = null;
1904
+ #restartFailedAfterApply = null;
1905
+ constructor(app, parts) {
1906
+ this.#app = app;
1907
+ this.#env = parts.env;
1908
+ this.#logger = parts.logger;
1909
+ this.#isStopping = parts.isStopping;
1910
+ this.#graph = parts.graph;
1911
+ this.#statuses = parts.statuses;
1912
+ this.#backend = parts.backend;
1913
+ this.#builder = parts.builder;
1914
+ this.#gap = parts.gap;
1915
+ this.#rss = parts.rss;
1916
+ }
1917
+ get pending() {
1918
+ return !!this.#pending;
1919
+ }
1920
+ drop() {
1921
+ this.#pending = null;
1922
+ }
1923
+ async handleInvalidate(message) {
1614
1924
  this.#logDevPlan(message);
1615
- if (this.#rssRecycleReason)
1616
- this.#armRssRecycle(this.#rssRecycleReason);
1925
+ this.#rss.rearm();
1617
1926
  const wantsDevHostRestart = shouldRestartDevHostByDevPlan(message);
1618
- const pending = this.#pendingRecycle;
1927
+ const pending = this.#pending;
1619
1928
  const resumes = !!pending && message.kinds.includes("code") && this.#touchesFailedRecycle(message.files);
1620
1929
  if (wantsDevHostRestart || shouldRestartBuilderByDevPlan(message) || resumes) {
1621
1930
  const refreshConfig = wantsDevHostRestart || (pending?.refreshConfig ?? false);
1622
1931
  const merged = pending ? mergeInvalidateMessages(pending.message, message) : message;
1623
1932
  const generation = message.devPlan?.generation ?? message.generation;
1624
- if (hasBuildFailureForGeneration(this.#buildStatusByPhase, generation)) {
1625
- this.#deferRecycle(merged, { refreshConfig, generation });
1933
+ if (this.#statuses.failedAt(generation)) {
1934
+ this.#defer(merged, { refreshConfig, generation });
1626
1935
  return;
1627
1936
  }
1628
- await this.#applyRecycle(merged, refreshConfig);
1937
+ await this.apply(merged, refreshConfig);
1629
1938
  return;
1630
1939
  }
1631
1940
  if (await this.#shouldRestartBackend(message)) {
1632
- this.#scheduleBackendRestart(backendRestartReasonFromMessage(message));
1941
+ this.#backend.scheduleRestart(backendRestartReasonFromMessage(message));
1633
1942
  return;
1634
1943
  }
1635
- this.#sendToBackend(message);
1944
+ this.#backend.send(message);
1636
1945
  }
1637
- async#applyRecycle(message, refreshConfig) {
1638
- if (this.#stopping)
1946
+ async apply(message, refreshConfig) {
1947
+ if (this.#isStopping())
1639
1948
  return;
1640
- this.#pendingRecycle = null;
1949
+ this.#pending = null;
1641
1950
  const progress = { applied: !refreshConfig };
1642
1951
  try {
1643
1952
  if (refreshConfig)
@@ -1646,144 +1955,121 @@ ${this.#backendStderrTail.join(`
1646
1955
  await this.#restartDevChildren(message);
1647
1956
  } catch (err) {
1648
1957
  const kind = refreshConfig ? "Config" : "Runtime metadata";
1649
- const generation = this.#recordDevHostRestartFailure(message, err, kind, { applied: progress.applied });
1958
+ const generation = this.#recordRestartFailure(message, err, kind, { applied: progress.applied });
1650
1959
  if (progress.applied)
1651
1960
  this.#restartFailedAfterApply = generation;
1652
1961
  else
1653
- this.#pendingRecycle = { message, refreshConfig, failed: true, failedGeneration: generation };
1962
+ this.#pending = { message, refreshConfig, failed: true, failedGeneration: generation };
1654
1963
  this.#resurrectDevChildren(message);
1655
1964
  }
1656
1965
  }
1657
- async#resumeFailedRecycle(status) {
1658
- const pending = this.#pendingRecycle;
1966
+ async resumeFailed(status) {
1967
+ const pending = this.#pending;
1659
1968
  if (!pending?.failed || !status.ok || status.phase !== "pages" || !this.#touchesFailedRecycle(status.files))
1660
1969
  return;
1661
1970
  if (status.generation <= (pending.failedGeneration ?? -1))
1662
1971
  return;
1663
- await this.#applyRecycle(pending.message, pending.refreshConfig);
1972
+ await this.apply(pending.message, pending.refreshConfig);
1973
+ }
1974
+ async applyIdleWake(batch) {
1975
+ const files = batch?.files ?? [];
1976
+ if (shouldRefreshConfigOnIdleWake(batch)) {
1977
+ this.#logger.verbose("[idle-suspend] config changed while suspended; restarting the dev host");
1978
+ this.#gap.discard("config change replaces the backend anyway");
1979
+ await this.apply({ type: "invalidate", kinds: [...batch?.kinds ?? []], files }, true);
1980
+ return;
1981
+ }
1982
+ if (files.length > 0)
1983
+ await this.#graph.refresh();
1984
+ await this.#builder.start({ announceBootState: true });
1985
+ const missed = await this.#gap.take();
1986
+ const backendFiles = [...new Set([...files.filter((file) => this.#graph.has(file)), ...missed])];
1987
+ if (backendFiles.length === 0)
1988
+ return;
1989
+ this.#logger.verbose(`[idle-suspend] ${backendFiles.length} backend file(s) changed while suspended`);
1990
+ this.#backend.scheduleRestart({ files: backendFiles, roles: [] });
1991
+ }
1992
+ builderRecovered(reason) {
1993
+ this.#gap.restartBackendForChanges();
1994
+ const failedAfterApply = this.#restartFailedAfterApply;
1995
+ this.#restartFailedAfterApply = null;
1996
+ const status = {
1997
+ generation: failedAfterApply !== null ? this.#statuses.nextBackendGeneration(failedAfterApply + 1) : reason.generation ?? this.#statuses.nextBackendGeneration(),
1998
+ phase: "scan",
1999
+ ok: true,
2000
+ files: reason.files,
2001
+ message: "Builder recovered"
2002
+ };
2003
+ this.#statuses.record(status);
2004
+ this.#backend.sendOrQueueStatus(status);
2005
+ if (!this.#backend.running && !this.#backend.recovering) {
2006
+ this.#backend.start({ generation: reason.generation, files: reason.files });
2007
+ }
1664
2008
  }
1665
2009
  #touchesFailedRecycle(files) {
1666
- const pending = this.#pendingRecycle;
2010
+ const pending = this.#pending;
1667
2011
  if (!pending?.failed)
1668
2012
  return true;
1669
2013
  const changed = new Set(pending.message.files);
1670
2014
  return files.some((file) => changed.has(file));
1671
2015
  }
1672
- #deferRecycle(message, { refreshConfig, generation }) {
1673
- this.#pendingRecycle = { message, refreshConfig };
2016
+ #defer(message, { refreshConfig, generation }) {
2017
+ this.#pending = { message, refreshConfig };
1674
2018
  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`);
2019
+ this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart deferred generation=${generation ?? "(unknown)"}; keeping the running dev server until the build error is fixed`);
1676
2020
  const status = {
1677
- generation: generation ?? this.#nextBackendBuildStatusGeneration(),
2021
+ generation: generation ?? this.#statuses.nextBackendGeneration(),
1678
2022
  phase: "scan",
1679
2023
  ok: false,
1680
2024
  files: message.files,
1681
2025
  message: `${kind} change is on hold while the build is failing; it will apply automatically once the error is fixed.`
1682
2026
  };
1683
- this.#recordBuildStatus(status);
1684
- this.#sendOrQueueBuildStatus(status);
2027
+ this.#statuses.record(status);
2028
+ this.#backend.sendOrQueueStatus(status);
1685
2029
  }
1686
2030
  #resurrectDevChildren(message) {
1687
2031
  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 });
2032
+ if (!this.#backend.running)
2033
+ this.#backend.start({ generation, files: message.files });
2034
+ this.#builder.scheduleRecovery({ generation, files: message.files });
1736
2035
  }
1737
2036
  async#restartDevChildren(message) {
1738
2037
  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}`);
2038
+ this.#logger.warn(`[dev-host] recycling builder/backend for runtime metadata generation=${generation ?? "(unknown)"} files=${message.files.length}`);
1740
2039
  await this.#recycleDevChildren(message);
1741
2040
  }
1742
2041
  async#restartDevHost(message, progress) {
1743
2042
  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}`);
2043
+ this.#logger.warn(`[dev-host] config change detected; restarting dev host generation=${generation ?? "(unknown)"} files=${message.files.length}`);
1745
2044
  await this.#recycleDevChildren(message, { refreshConfig: true, progress });
1746
2045
  }
1747
2046
  async#recycleDevChildren(message, { refreshConfig = false, progress } = {}) {
1748
2047
  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;
2048
+ this.#backend.cancelTimers();
2049
+ this.#builder.cancelRecovery();
2050
+ this.#builder.resetRecovery();
2051
+ this.#backend.dropPendingRestart();
2052
+ await this.#backend.restarting;
2053
+ this.#statuses.reset();
2054
+ this.#backend.dropQueuedStatuses();
2055
+ await this.#backend.stop();
2056
+ this.#builder.stop();
2057
+ this.#builder.clearPatcherOff();
1759
2058
  if (refreshConfig) {
1760
- await this.app.getConfig({ refresh: true });
1761
- const { env } = await this.app.prepareCommand("start");
1762
- Object.assign(this.env, env);
2059
+ await this.#app.getConfig({ refresh: true });
2060
+ const { env } = await this.#app.prepareCommand("start");
2061
+ Object.assign(this.#env, env);
1763
2062
  if (progress)
1764
2063
  progress.applied = true;
1765
2064
  }
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}`);
2065
+ await this.#graph.refresh();
2066
+ await this.#builder.start();
2067
+ this.#backend.start({ generation, files: message.files });
1782
2068
  }
1783
- #recordDevHostRestartFailure(message, err, kind, { applied }) {
1784
- const generation = message.devPlan?.generation ?? message.generation ?? this.#nextBackendBuildStatusGeneration();
2069
+ #recordRestartFailure(message, err, kind, { applied }) {
2070
+ const generation = message.devPlan?.generation ?? message.generation ?? this.#statuses.nextBackendGeneration();
1785
2071
  const detail = err instanceof Error ? err.message : String(err);
1786
- this.logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
2072
+ this.#logger.warn(`[dev-host] ${kind.toLowerCase()} restart failed generation=${generation}: ${detail}`);
1787
2073
  const names = message.files.slice(0, 3).map((file) => path4.basename(file));
1788
2074
  const saved = names.length > 0 ? names.join(", ") : "the changed file";
1789
2075
  const status = {
@@ -1793,50 +2079,15 @@ ${this.#backendStderrTail.join(`
1793
2079
  files: message.files,
1794
2080
  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
2081
  };
1796
- this.#recordBuildStatus(status);
1797
- this.#sendOrQueueBuildStatus(status);
2082
+ this.#statuses.record(status);
2083
+ this.#backend.sendOrQueueStatus(status);
1798
2084
  return generation;
1799
2085
  }
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
2086
  #logDevPlan(message) {
1836
2087
  if (!message.devPlan)
1837
2088
  return;
1838
2089
  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}`);
2090
+ this.#logger.verbose(`[dev-plan] generation=${generation} roles=${roles.join(",") || "(none)"} actions=${actions.join(",") || "(none)"} reasons=${Object.keys(reasonByFile).length}`);
1840
2091
  }
1841
2092
  async#shouldRestartBackend(message) {
1842
2093
  if (message.kinds.length === 1 && message.kinds[0] === "css")
@@ -1844,146 +2095,348 @@ ${this.#backendStderrTail.join(`
1844
2095
  if (message.devPlan) {
1845
2096
  const shouldRestart = shouldRestartBackendByDevPlan(message) ?? false;
1846
2097
  if (shouldRestart && message.kinds.includes("code"))
1847
- await this.#backendGraph.refresh();
2098
+ await this.#graph.refresh();
1848
2099
  return shouldRestart;
1849
2100
  }
1850
2101
  if (message.kinds.includes("code"))
1851
- await this.#backendGraph.refresh();
1852
- if (message.files.some((file) => this.#backendGraph.has(file)))
2102
+ await this.#graph.refresh();
2103
+ if (message.files.some((file) => this.#graph.has(file)))
1853
2104
  return true;
1854
- if (!this.#backendGraph.lastRefreshSucceeded) {
1855
- const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this.app.workspace.workspaceRoot));
2105
+ if (!this.#graph.lastRefreshSucceeded) {
2106
+ const fallbackFiles = message.files.filter((file) => isLegacyBackendFallbackFile(file, this.#app.workspace.workspaceRoot));
1856
2107
  if (fallbackFiles.length > 0) {
1857
- this.logger.warn(`[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`);
2108
+ this.#logger.warn(`[backend-graph] using path-role fallback for legacy invalidate; restart files=${fallbackFiles.length}`);
1858
2109
  return true;
1859
2110
  }
1860
2111
  }
1861
2112
  return false;
1862
2113
  }
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
- }
2114
+ }
2115
+
2116
+ // pkgs/@akanjs/devkit/akanApp/devStartTimeline.ts
2117
+ var BASE_BUILD_PARTS = ["runtime", "routes", "styles", "dictionary", "pages"];
2118
+
2119
+ class DevStartTimeline {
2120
+ #logger;
2121
+ #now;
2122
+ #marks = {};
2123
+ #basePhaseMs = {};
2124
+ #reported = true;
2125
+ constructor(logger, now = () => performance.now()) {
2126
+ this.#logger = logger;
2127
+ this.#now = now;
2128
+ }
2129
+ begin() {
2130
+ this.#marks = { started: this.#now() };
2131
+ this.#basePhaseMs = {};
2132
+ this.#reported = false;
2133
+ }
2134
+ baseBuilt(phaseMs) {
2135
+ if (this.#reported || this.#marks.baseBuilt !== undefined)
2136
+ return;
2137
+ this.#basePhaseMs = phaseMs;
2138
+ this.#marks.baseBuilt = this.#now();
2139
+ }
2140
+ mark(mark) {
2141
+ if (this.#reported)
2142
+ return;
2143
+ if (mark === "backendSpawned")
2144
+ this.#marks.backendSpawned = this.#now();
2145
+ else
2146
+ this.#marks[mark] ??= this.#now();
2147
+ this.#report();
2148
+ }
2149
+ #report() {
2150
+ const { started, baseBuilt, builderReady, backendSpawned, backendReady } = this.#marks;
2151
+ if (started === undefined || builderReady === undefined || backendReady === undefined)
2152
+ return;
2153
+ this.#reported = true;
2154
+ const ms = (value) => Math.round(value).toString();
2155
+ const parts = [`prepare ${ms(started)}`, `builder ${ms(builderReady - started)}${this.#builderParts()}`];
2156
+ if (backendSpawned !== undefined) {
2157
+ const afterArtifact = baseBuilt !== undefined && backendSpawned < baseBuilt && baseBuilt <= backendReady ? ` (${ms(backendReady - baseBuilt)} after the artifact)` : "";
2158
+ parts.push(`backend ${ms(backendReady - backendSpawned)}${afterArtifact}`);
2159
+ }
2160
+ if (baseBuilt !== undefined)
2161
+ parts.push(`first artifact at ${ms(baseBuilt)}`);
2162
+ this.#logger.info(`ready in ${ms(Math.max(builderReady, backendReady))}ms (${parts.join(" \xB7 ")})`);
2163
+ }
2164
+ #builderParts() {
2165
+ const { started, baseBuilt, builderReady } = this.#marks;
2166
+ if (started === undefined || baseBuilt === undefined || builderReady === undefined)
2167
+ return "";
2168
+ const total = this.#basePhaseMs.total ?? 0;
2169
+ const base = BASE_BUILD_PARTS.flatMap((part) => {
2170
+ const partMs = this.#basePhaseMs[part];
2171
+ return partMs === undefined ? [] : [`${part} ${Math.round(partMs)}`];
2172
+ });
2173
+ const spawn = Math.max(0, Math.round(baseBuilt - started - total));
2174
+ const watch = Math.max(0, Math.round(builderReady - baseBuilt));
2175
+ return `: spawn ${spawn} + base build ${Math.round(total)} [${base.join(" \xB7 ")}] + watch ${watch}`;
2176
+ }
2177
+ }
2178
+
2179
+ // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
2180
+ class AkanAppHost {
2181
+ app;
2182
+ logger = new Logger2("AkanAppHost");
2183
+ stdio;
2184
+ env;
2185
+ #onDevEvent;
2186
+ #lastDevState = null;
2187
+ #bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
2188
+ #stopping = false;
2189
+ #firstArtifact = "settled";
2190
+ #builderMessageQueue = Promise.resolve();
2191
+ #backendGraph;
2192
+ #statuses;
2193
+ #backend;
2194
+ #gap;
2195
+ #requests;
2196
+ #rss;
2197
+ #builder;
2198
+ #idle;
2199
+ #recycler;
2200
+ #timeline;
2201
+ constructor(app, {
2202
+ env,
2203
+ stdio = "inherit",
2204
+ onDevEvent
2205
+ }) {
2206
+ this.app = app;
2207
+ this.env = env;
2208
+ this.stdio = stdio;
2209
+ this.#onDevEvent = onDevEvent ?? null;
2210
+ this.#backendGraph = new BackendImportGraph(app, this.logger);
2211
+ const { logger } = this;
2212
+ const graph = this.#backendGraph;
2213
+ const isStopping = () => this.#stopping;
2214
+ const statuses = new DevBuildStatusBoard(logger);
2215
+ this.#statuses = statuses;
2216
+ this.#timeline = new DevStartTimeline(logger);
2217
+ this.#backend = new DevBackend(app, { env, stdio, logger, statuses, graph }, {
2218
+ isStopping,
2219
+ emit: (state, detail) => {
2220
+ if (state === "ready")
2221
+ this.#timeline.mark("backendReady");
2222
+ this.#emitDevEvent(state, detail);
2223
+ },
2224
+ beforeSpawn: () => {
2225
+ this.#timeline.mark("backendSpawned");
2226
+ this.#requests.startGeneration();
2227
+ this.#requests.discard("the backend restarted while the builder was away");
2228
+ },
2229
+ awaitsArtifact: () => this.#firstArtifact === "pending",
2230
+ toBuilder: (message) => this.#requests.send(message)
2231
+ });
2232
+ this.#gap = new BuilderGap({ graph, backend: this.#backend, logger });
2233
+ this.#requests = new BuilderRequestRelay({ logger, env }, {
2234
+ builder: () => this.#builder.current,
2235
+ toBackend: (message) => this.#backend.send(message),
2236
+ markActivity: () => this.#idle.markActivity(),
2237
+ away: () => this.#idle.away,
2238
+ wake: (reason) => void this.#idle.wake(reason)
2239
+ });
2240
+ this.#rss = new BuilderRssRecycler({ logger, statuses }, {
2241
+ builder: () => this.#builder.current,
2242
+ away: () => this.#idle.away,
2243
+ restartQueued: () => this.#recycler.pending || this.#backend.restartScheduled,
2244
+ onRecycle: () => this.#gap.open("builder recycle")
2245
+ });
2246
+ this.#builder = new DevBuilder(app, { env, stdio, logger }, {
2247
+ isStopping,
2248
+ onMessage: (message) => this.#enqueueBuilderMessage(message),
2249
+ onAway: () => this.#gap.open("builder replacement"),
2250
+ onReady: () => {
2251
+ this.#timeline.mark("builderReady");
2252
+ this.#requests.flush();
2253
+ },
2254
+ onBaseBuilt: (phaseMs) => {
2255
+ this.#timeline.baseBuilt(phaseMs);
2256
+ if (this.#firstArtifact === "built")
2257
+ this.#backend.scheduleRestart({ files: [], roles: [] });
2258
+ else if (this.#firstArtifact === "pending")
2259
+ this.#firstArtifact = "built";
2260
+ },
2261
+ onRestartReady: () => {
2262
+ this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
2263
+ this.#backend.replay();
2264
+ this.#requests.flush();
2265
+ this.#gap.restartBackendForChanges();
2266
+ this.#rss.checkRecycledFloor();
2267
+ },
2268
+ onStartFailed: () => this.#requests.fail("builder failed to start"),
2269
+ onStop: () => this.#rss.cancel(),
2270
+ onRecovered: (reason) => this.#recycler.builderRecovered(reason)
2271
+ });
2272
+ this.#idle = new DevIdleSuspend(app, { logger }, {
2273
+ readiness: () => ({
2274
+ builderReady: this.#builder.current?.status === "ready",
2275
+ backendReady: this.#backend.ready,
2276
+ buildFailed: this.#statuses.failing,
2277
+ restartPending: this.#restartPending
2278
+ }),
2279
+ release: (detail) => {
2280
+ this.#emitDevEvent("suspended", detail);
2281
+ this.#builder.stop();
2282
+ this.#gap.open("idle suspend");
2283
+ },
2284
+ wake: (batch) => this.#recycler.applyIdleWake(batch),
2285
+ wakeFailed: (files) => this.#builder.scheduleRecovery({ files }),
2286
+ flushHeld: () => this.#requests.flush(),
2287
+ awake: () => this.#emitDevEvent(devHostStateOf(this.#backend.lifecycleState, this.#backend.gaveUp))
2288
+ });
2289
+ this.#recycler = new DevRecycler(app, {
2290
+ env,
2291
+ logger,
2292
+ isStopping,
2293
+ graph,
2294
+ statuses,
2295
+ backend: this.#backend,
2296
+ builder: this.#builder,
2297
+ gap: this.#gap,
2298
+ rss: this.#rss
2299
+ });
2300
+ }
2301
+ #emitDevEvent(state, detail) {
2302
+ if (!this.#onDevEvent || state === this.#lastDevState)
2303
+ return;
2304
+ this.#lastDevState = state;
2305
+ this.#onDevEvent({ app: this.app.name, state, ...detail ? { detail } : {} });
2306
+ if (state === "ready")
2307
+ this.#bootLatch.ready();
2308
+ }
2309
+ async start() {
2310
+ if (this.#backend.running)
2311
+ await this.#backend.stop();
2312
+ if (this.#builder.current)
2313
+ this.#builder.stop();
2314
+ this.#timeline.begin();
2315
+ const artifactFile = path5.join(this.app.cwdPath, ".akan/artifact/base-artifact.json");
2316
+ this.#firstArtifact = fs2.existsSync(artifactFile) ? "settled" : "pending";
2317
+ const prepared = Promise.all([this.#prepareDatabase("redis"), this.#backendGraph.refresh()]).then(([redisHost]) => {
2318
+ Object.assign(this.env, { REDIS_HOST: redisHost });
2319
+ if (this.#firstArtifact !== "settled")
2320
+ this.#backend.start();
2321
+ });
2322
+ try {
2323
+ await Promise.all([this.#builder.start(), prepared]);
2324
+ } catch (error) {
2325
+ this.#firstArtifact = "settled";
2326
+ if (!this.#stopping)
2327
+ await this.#backend.stop();
2328
+ throw error;
1893
2329
  }
1894
- this.#failPendingBuilderMessages("builder failed to start");
1895
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
2330
+ const artifactMissing = this.#firstArtifact === "pending" && !fs2.existsSync(artifactFile);
2331
+ this.#firstArtifact = "settled";
2332
+ if (artifactMissing && !this.#stopping) {
2333
+ await this.#backend.restarting;
2334
+ await this.#backend.stop();
2335
+ }
2336
+ if (!this.#backend.running)
2337
+ this.#backend.start();
2338
+ this.#idle.arm();
2339
+ return this;
1896
2340
  }
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
- });
2341
+ async stop() {
2342
+ this.#stopping = true;
2343
+ this.#recycler.drop();
2344
+ this.#idle.stop();
2345
+ this.#backend.cancelTimers();
2346
+ this.#builder.cancelRecovery();
2347
+ this.#builder.abandonStart(new Error("dev server stopped before the builder was ready"));
2348
+ this.#backend.dropPendingRestart();
2349
+ this.#requests.fail("dev server is shutting down");
2350
+ await this.#backend.restarting;
2351
+ await this.#backend.stop();
2352
+ this.#builder.stop();
2353
+ return this;
2354
+ }
2355
+ kill() {
2356
+ this.stop();
2357
+ }
2358
+ async#prepareDatabase(type) {
2359
+ const environment = WorkspaceExecutor.getBaseDevEnv().env;
2360
+ const policy = redisTunnelPolicy({ environment, databaseMode: this.env.AKAN_DATABASE_MODE });
2361
+ if (policy === "none")
2362
+ return "localhost";
2363
+ if (policy === "required")
2364
+ return await createTunnel(type, { app: this.app, environment });
2365
+ try {
2366
+ return await createTunnel(type, { app: this.app, environment });
2367
+ } catch (error) {
2368
+ 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`);
2369
+ return UNAVAILABLE_REDIS_HOST;
2370
+ }
2371
+ }
2372
+ #enqueueBuilderMessage(message) {
2373
+ this.#builderMessageQueue = this.#builderMessageQueue.then(() => this.#handleBuilderMessage(message)).catch((err) => {
2374
+ this.logger.warn(`failed to handle builder message: ${err instanceof Error ? err.message : String(err)}`);
1936
2375
  });
1937
2376
  }
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`);
2377
+ async#handleBuilderMessage(message) {
2378
+ if (this.#stopping)
2379
+ return;
2380
+ this.#idle.markActivity();
2381
+ this.#builder.trackGeneration(message);
2382
+ if (message.type === "build-status") {
2383
+ this.#statuses.record(message.data);
2384
+ this.#backend.sendOrQueueStatus(message.data);
2385
+ this.#backend.reviveAfterGreenBuild(message.data);
2386
+ await this.#recycler.resumeFailed(message.data);
1943
2387
  return;
1944
2388
  }
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})`);
2389
+ if (message.type === "builder-metrics") {
2390
+ this.#rss.handleMetrics(message.data);
2391
+ return;
1948
2392
  }
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))
2393
+ if (message.type === "boot-armed") {
2394
+ this.logger.verbose("[builder] boot builds settled");
2395
+ this.#bootLatch.armed();
1955
2396
  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)`);
2397
+ }
2398
+ if (message.type === "pages-updated" || message.type === "css-updated") {
2399
+ const recycled = message.data.reason === "builder-recycle";
2400
+ if (recycled && !this.#statuses.shouldRelayRecycled(message))
2401
+ return;
2402
+ this.#statuses.recordLastGood(message, { supersede: recycled });
2403
+ }
2404
+ if (message.type === "invalidate") {
2405
+ await this.#recycler.handleInvalidate(message);
1960
2406
  return;
1961
2407
  }
1962
- if (this.#failBuilderRequest(message, `builder is ${status}; reload after the builder is ready`))
2408
+ if (message.type === "build-route-res" || message.type === "build-csr-res" || message.type === "build-graph-res") {
2409
+ const answer = this.#requests.settle(message);
2410
+ if (!answer) {
2411
+ this.logger.verbose(`[builder] dropped a ${message.type} no live backend is waiting for (id=${message.id})`);
2412
+ return;
2413
+ }
2414
+ this.#backend.send(answer);
1963
2415
  return;
1964
- this.logger.warn("akanAppHost builder is not running");
2416
+ }
2417
+ this.#backend.send(message);
1965
2418
  }
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;
2419
+ get #restartPending() {
2420
+ return this.#recycler.pending || this.#backend.restartPending || this.#builder.recovering || this.#rss.armed;
2421
+ }
2422
+ static async readProcessRssBytes(pid) {
2423
+ return await ProcessRss.bytesOf(pid);
2424
+ }
2425
+ static idleSuspendMs() {
2426
+ return DevIdleSuspend.idleMs();
1974
2427
  }
1975
2428
  }
1976
- // pkgs/@akanjs/devkit/applicationTestPreload.ts
1977
- import path5 from "path";
2429
+ // pkgs/@akanjs/devkit/app/applicationTestPreload.ts
2430
+ import path6 from "path";
1978
2431
  var SIGNAL_TEST_PRELOAD_PATH = "test/signalTest.preload.ts";
1979
2432
  async function resolveSignalTestPreloadPath(target) {
1980
2433
  const candidates = [];
1981
- for (const basePath of [target.cwdPath, process.cwd(), path5.dirname(Bun.main), import.meta.dir]) {
2434
+ for (const basePath of [target.cwdPath, process.cwd(), path6.dirname(Bun.main), import.meta.dir]) {
1982
2435
  try {
1983
- candidates.push(path5.join(path5.dirname(Bun.resolveSync("akanjs/package.json", basePath)), SIGNAL_TEST_PRELOAD_PATH));
2436
+ candidates.push(path6.join(path6.dirname(Bun.resolveSync("akanjs/package.json", basePath)), SIGNAL_TEST_PRELOAD_PATH));
1984
2437
  } catch {}
1985
2438
  }
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));
2439
+ candidates.push(path6.join(target.cwdPath, "../../node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path6.join(target.cwdPath, "../../pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path6.join(process.cwd(), "node_modules/akanjs", SIGNAL_TEST_PRELOAD_PATH), path6.join(process.cwd(), "pkgs/akanjs", SIGNAL_TEST_PRELOAD_PATH), path6.join(path6.dirname(Bun.main), "../../akanjs", SIGNAL_TEST_PRELOAD_PATH), path6.resolve(import.meta.dir, "../../../akanjs", SIGNAL_TEST_PRELOAD_PATH));
1987
2440
  const uniqueCandidates = [...new Set(candidates)];
1988
2441
  for (const candidate of uniqueCandidates)
1989
2442
  if (await Bun.file(candidate).exists())
@@ -1999,7 +2452,7 @@ import { Logger as Logger4, toError } from "akanjs/common";
1999
2452
 
2000
2453
  // pkgs/@akanjs/cli/application/testTarget.ts
2001
2454
  import { readdirSync, realpathSync, statSync } from "fs";
2002
- import path6 from "path";
2455
+ import path7 from "path";
2003
2456
  import { Logger as Logger3 } from "akanjs/common";
2004
2457
  var testFileName = /[._](test|spec)\.[cm]?[jt]sx?$/i;
2005
2458
  var hasTestFile = (dir, seen = new Set) => {
@@ -2008,7 +2461,7 @@ var hasTestFile = (dir, seen = new Set) => {
2008
2461
  return false;
2009
2462
  seen.add(real);
2010
2463
  return readdirSync(dir, { withFileTypes: true }).some((entry) => {
2011
- const entryPath = path6.join(dir, entry.name);
2464
+ const entryPath = path7.join(dir, entry.name);
2012
2465
  const isDir = entry.isDirectory() || entry.isSymbolicLink() && statSync(entryPath, { throwIfNoEntry: false })?.isDirectory();
2013
2466
  if (!isDir)
2014
2467
  return testFileName.test(entry.name);
@@ -2016,19 +2469,19 @@ var hasTestFile = (dir, seen = new Set) => {
2016
2469
  });
2017
2470
  };
2018
2471
  var testTargetOf = (exec) => {
2019
- const root = exec instanceof SysExecutor || exec instanceof PkgExecutor ? exec.workspace.workspaceRoot : process.cwd();
2020
- return { root, target: path6.relative(root, exec.cwdPath).split(path6.sep).join("/") };
2472
+ const root = exec instanceof SysExecutor || exec instanceof PkgExecutor2 ? exec.workspace.workspaceRoot : process.cwd();
2473
+ return { root, target: path7.relative(root, exec.cwdPath).split(path7.sep).join("/") };
2021
2474
  };
2022
2475
  var reportsNoTestFile = (exec) => {
2023
2476
  if (hasTestFile(exec.cwdPath))
2024
2477
  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." : "";
2478
+ const hint = exec instanceof AppExecutor2 || exec instanceof LibExecutor2 ? " A signal test goes beside its module, as lib/<model>/<model>.signal.test.ts." : "";
2026
2479
  Logger3.rawLog(`No *.test.ts or *.spec.ts file in ${testTargetOf(exec).target}, so no test ran.${hint}`);
2027
2480
  return true;
2028
2481
  };
2029
2482
 
2030
2483
  // pkgs/@akanjs/cli/application/application.runner.ts
2031
- var loadBuildRunner = async () => (await import("./applicationBuildRunner-df7rx3ra.js")).ApplicationBuildRunner;
2484
+ var loadBuildRunner = async () => (await import("./applicationBuildRunner-y5xbetyz.js")).ApplicationBuildRunner;
2032
2485
  var loadPrompts = async () => await import("@inquirer/prompts");
2033
2486
 
2034
2487
  class ApplicationRunner extends runner("application") {
@@ -2039,7 +2492,7 @@ class ApplicationRunner extends runner("application") {
2039
2492
  dict: { appName },
2040
2493
  options: { libs }
2041
2494
  });
2042
- return AppExecutor.from(workspace, appName);
2495
+ return AppExecutor2.from(workspace, appName);
2043
2496
  }
2044
2497
  async planSlice(app) {
2045
2498
  return await new SlicePlanner(app).plan();
@@ -2080,7 +2533,7 @@ class ApplicationRunner extends runner("application") {
2080
2533
  });
2081
2534
  }
2082
2535
  static runtimeDirOf(app, override) {
2083
- return path7.resolve(override ?? process.env.AKAN_RUNTIME_DIR ?? path7.join(app.workspace.workspaceRoot, "local", "apps", app.name, "runtime"));
2536
+ return path8.resolve(override ?? process.env.AKAN_RUNTIME_DIR ?? path8.join(app.workspace.workspaceRoot, "local", "apps", app.name, "runtime"));
2084
2537
  }
2085
2538
  async runLogs(app, options) {
2086
2539
  const { LogControlUnavailableError, LogTailClient } = await import("akanjs/server/logging/logTailClient");
@@ -2106,7 +2559,7 @@ class ApplicationRunner extends runner("application") {
2106
2559
  });
2107
2560
  } catch (error) {
2108
2561
  if (error instanceof LogControlUnavailableError)
2109
- throw new Error(`${app.name} is not running (no ${path7.basename(socketPath)} in ${runtimeDir}). Start it with \`akan start ${app.name}\`, or pass --runtime-dir for a built app.`);
2562
+ throw new Error(`${app.name} is not running (no ${path8.basename(socketPath)} in ${runtimeDir}). Start it with \`akan start ${app.name}\`, or pass --runtime-dir for a built app.`);
2110
2563
  throw error;
2111
2564
  }
2112
2565
  const sinceMs = since ? LogQueryMatcher.parseSince(since) : undefined;
@@ -2168,7 +2621,7 @@ try {
2168
2621
  const serverPath = `${app.cwdPath}/server.ts`;
2169
2622
  if (!await app.exists("server.ts"))
2170
2623
  throw new Error(`Server file not found: apps/${app.name}/server.ts`);
2171
- const target = path7.resolve(app.workspace.workspaceRoot, dir);
2624
+ const target = path8.resolve(app.workspace.workspaceRoot, dir);
2172
2625
  const code = `
2173
2626
  const { server } = await import(${JSON.stringify(serverPath)});
2174
2627
  const { DatabaseAdaptorRole, DocumentTransfer } = await import("akanjs/service");
@@ -2229,7 +2682,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2229
2682
  await new (await loadBuildRunner())(app).typecheck(options);
2230
2683
  }
2231
2684
  async typecheckLibrary(lib, options = {}) {
2232
- const { ProjectTypecheck } = await import("./projectTypecheck-kkrpq60a.js");
2685
+ const { ProjectTypecheck } = await import("./projectTypecheck-za2n3nbr.js");
2233
2686
  const root = lib.workspace.workspaceRoot;
2234
2687
  await new ProjectTypecheck(lib.cwdPath, root, { ...process.env, AKAN_WORKSPACE_ROOT: root }).run([
2235
2688
  "../../server.ts",
@@ -2242,18 +2695,18 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2242
2695
  }
2243
2696
  resolveTestPaths(exec, files) {
2244
2697
  const { root, target } = testTargetOf(exec);
2245
- const isInside = (relative) => relative !== ".." && !relative.startsWith(`..${path7.sep}`) && !path7.isAbsolute(relative);
2698
+ const isInside = (relative) => relative !== ".." && !relative.startsWith(`..${path8.sep}`) && !path8.isAbsolute(relative);
2246
2699
  return files.map((file) => {
2247
- const candidates = path7.isAbsolute(file) ? [file] : [path7.resolve(exec.cwdPath, file), path7.resolve(root, file)];
2248
- const existing = candidates.filter((candidate) => existsSync(candidate)).map((candidate) => path7.relative(exec.cwdPath, candidate));
2700
+ const candidates = path8.isAbsolute(file) ? [file] : [path8.resolve(exec.cwdPath, file), path8.resolve(root, file)];
2701
+ const existing = candidates.filter((candidate) => existsSync(candidate)).map((candidate) => path8.relative(exec.cwdPath, candidate));
2249
2702
  const found = existing.find(isInside);
2250
2703
  if (found === undefined)
2251
2704
  throw new Error(existing.length ? `${file} is outside ${target}: akan test ${exec.name} runs its own tests only` : `${file} names no file or folder in ${target}`);
2252
- return `./${found.split(path7.sep).join("/")}`;
2705
+ return `./${found.split(path8.sep).join("/")}`;
2253
2706
  });
2254
2707
  }
2255
2708
  async test(exec, testPaths = [], flags = []) {
2256
- const isSignalTarget = exec instanceof AppExecutor || exec instanceof LibExecutor;
2709
+ const isSignalTarget = exec instanceof AppExecutor2 || exec instanceof LibExecutor2;
2257
2710
  if (!testPaths.length && reportsNoTestFile(exec))
2258
2711
  return;
2259
2712
  const preloadPath = isSignalTarget ? await resolveSignalTestPreloadPath(exec) : null;
@@ -2262,7 +2715,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2262
2715
  AKAN_TEST_TARGET_TYPE: exec.type,
2263
2716
  AKAN_TEST_TARGET_NAME: exec.name,
2264
2717
  AKAN_TEST_LIBS: exec.getScanInfo({ allowEmpty: true })?.getLibs().join(",") ?? "",
2265
- AKAN_RUNTIME_DIR: path7.join(exec.workspace.workspaceRoot, "local", `${exec.type}s`, exec.name, "runtime")
2718
+ AKAN_RUNTIME_DIR: path8.join(exec.workspace.workspaceRoot, "local", `${exec.type}s`, exec.name, "runtime")
2266
2719
  } : {};
2267
2720
  const args = ["test", "--isolate", ...flags, ...preloadPath ? ["--preload", preloadPath] : [], ...testPaths];
2268
2721
  await exec.spawn("bun", args, {
@@ -2271,16 +2724,11 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2271
2724
  });
2272
2725
  }
2273
2726
  async build(app, {
2274
- fast = false,
2275
- reporter,
2276
2727
  spinner = false,
2277
2728
  envProfile,
2278
- environment,
2279
- budget
2729
+ ...options
2280
2730
  } = {}) {
2281
- return new (await loadBuildRunner())(app, { fast, reporter, profile: envProfile, environment, budget }).build({
2282
- spinner
2283
- });
2731
+ return new (await loadBuildRunner())(app, { ...options, profile: envProfile }).build({ spinner });
2284
2732
  }
2285
2733
  async start(app, {
2286
2734
  open = false,
@@ -2384,7 +2832,7 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2384
2832
  try {
2385
2833
  return realpathSync2.native(root);
2386
2834
  } catch {
2387
- return path7.resolve(root);
2835
+ return path8.resolve(root);
2388
2836
  }
2389
2837
  };
2390
2838
  return canonical(reported) === canonical(own);
@@ -2408,13 +2856,13 @@ if (loaded) process.exitCode = await loaded.migrations.command(loaded.server, ar
2408
2856
  if (!mobileTarget || targets.length > 1)
2409
2857
  throw new Error("pack-update packs one native target at a time; pass --target <name>.");
2410
2858
  const nativeApp = new NativeApp(app, mobileTarget, env);
2411
- await UpdatePackFolder.clear(path7.resolve(out ?? path7.join(nativeApp.updatesDir, platform)));
2859
+ await UpdatePackFolder.clear(path8.resolve(out ?? path8.join(nativeApp.updatesDir, platform)));
2412
2860
  const pinned = publicEnv ? await NativePublicEnv.load(publicEnv) : against ? await NativePublicEnv.recordedIn(against) : null;
2413
2861
  await this.#buildMobileCsr(app, env, undefined, pinned);
2414
2862
  const { pack } = await nativeApp.packUpdate(platform, { out });
2415
2863
  app.logger.info(`packed ${mobileTarget.name} ${platform} for channel '${pack.channel}' to ${pack.out}: ${pack.files} files, ${(pack.size / 1024).toFixed(0)} KiB, native API ${pack.nativeApi}`);
2416
2864
  if (against) {
2417
- const bundle = path7.join(pack.out, UpdatePackFolder.bundleFile);
2865
+ const bundle = path8.join(pack.out, UpdatePackFolder.bundleFile);
2418
2866
  const compat = await NativeApp.compareBundles(app.cwdPath, against, bundle);
2419
2867
  const envProblem = await NativePublicEnv.problemAgainst(against, bundle);
2420
2868
  await UpdatePackFolder.writeCompat(pack, {
@@ -2661,6 +3109,9 @@ ${detail}`
2661
3109
  }
2662
3110
 
2663
3111
  // pkgs/@akanjs/cli/verify/verifyScope.ts
3112
+ import path9 from "path";
3113
+ import ts from "typescript";
3114
+
2664
3115
  class VerifyScope {
2665
3116
  targets;
2666
3117
  constructor(targets) {
@@ -2672,6 +3123,51 @@ class VerifyScope {
2672
3123
  get changedFiles() {
2673
3124
  return new Set(this.targets.flatMap((target) => target.files));
2674
3125
  }
3126
+ get changedLibs() {
3127
+ return this.targets.filter((target) => target.type === "lib" && target.files.length).map((target) => target.name);
3128
+ }
3129
+ withDependents(names, libDeps) {
3130
+ const affected = new Set(this.changedLibs);
3131
+ if (!affected.size)
3132
+ return this;
3133
+ const known = VerifyScope.#knownTargets(names).filter((target) => target.type !== "pkg");
3134
+ const pulled = new Set;
3135
+ for (let grew = true;grew; ) {
3136
+ grew = false;
3137
+ for (const target of known) {
3138
+ if (pulled.has(target) || !(libDeps.get(target.dir) ?? []).some((lib) => affected.has(lib)))
3139
+ continue;
3140
+ pulled.add(target);
3141
+ if (target.type === "lib")
3142
+ affected.add(target.name);
3143
+ grew = true;
3144
+ }
3145
+ }
3146
+ const inScope = new Set(this.targets.map((target) => target.dir));
3147
+ const dependents = known.filter((target) => pulled.has(target) && !inScope.has(target.dir)).map((target) => ({ ...target, dependent: true }));
3148
+ return new VerifyScope([...this.targets, ...dependents]);
3149
+ }
3150
+ static async libDepsIn(workspaceRoot, { apps, libs }) {
3151
+ const dirs = [...apps.map((name) => `apps/${name}`), ...libs.map((name) => `libs/${name}`)];
3152
+ return new Map(await Promise.all(dirs.map(async (dir) => [dir, await VerifyScope.#libImportsIn(workspaceRoot, dir)])));
3153
+ }
3154
+ static async#libImportsIn(workspaceRoot, dir) {
3155
+ const libs = new Set;
3156
+ const cwd = path9.join(workspaceRoot, dir);
3157
+ for await (const file of new Bun.Glob("**/*.{ts,tsx}").scan({ cwd })) {
3158
+ if (/(^|[\\/])(node_modules|dist)[\\/]/.test(file))
3159
+ continue;
3160
+ const text = await Bun.file(path9.join(cwd, file)).text();
3161
+ if (!text.includes("@libs/"))
3162
+ continue;
3163
+ for (const { fileName } of ts.preProcessFile(text, true, true).importedFiles) {
3164
+ const lib = fileName.startsWith("@libs/") ? fileName.split("/")[1] : undefined;
3165
+ if (lib && `libs/${lib}` !== dir)
3166
+ libs.add(lib);
3167
+ }
3168
+ }
3169
+ return [...libs];
3170
+ }
2675
3171
  static async changesIn(workspaceRoot) {
2676
3172
  const prefix = await VerifyScope.#git(workspaceRoot, ["rev-parse", "--show-prefix"]);
2677
3173
  if (prefix === null)