@akanjs/devkit 3.3.0-rc.69 → 3.3.0-rc.70

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 (101) hide show
  1. package/README.ko.md +2 -1
  2. package/README.md +2 -1
  3. package/akanApp/akanApp.host.ts +15 -2
  4. package/akanApp/akanApp.host.wiring.test.ts +111 -0
  5. package/akanApp/devHostPolicy.ts +5 -0
  6. package/akanApp/devMetadataRestart.ts +93 -0
  7. package/akanApp/devRecycler.test.ts +2 -0
  8. package/akanApp/devRecycler.ts +9 -0
  9. package/codeAgent/index.ts +1 -34
  10. package/codeAgent/skills/akan-page/SKILL.md +9 -4
  11. package/codeAgent/skills/akan-service/SKILL.md +11 -9
  12. package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
  13. package/executors/executors.test.ts +15 -0
  14. package/executors/pkgExecutor.ts +2 -1
  15. package/frontendBuild/csrDevPatcher.test.ts +3 -4
  16. package/frontendBuild/csrDevPatcher.ts +4 -4
  17. package/frontendBuild/devChangePlanner.ts +0 -1
  18. package/frontendBuild/frontendBuild.test.ts +5 -3
  19. package/frontendBuild/ssrBaseArtifactBuilder.ts +12 -7
  20. package/frontendBuild/vendorNarrowing.test.ts +47 -3
  21. package/frontendBuild/vendorNarrowing.ts +10 -2
  22. package/incrementalBuilder/buildBatch.proc.ts +27 -1
  23. package/incrementalBuilder/buildBatchProtocol.ts +1 -0
  24. package/incrementalBuilder/builderWatch.ts +11 -1
  25. package/incrementalBuilder/incrementalBuilder.proc.test.ts +80 -0
  26. package/incrementalBuilder/incrementalBuilder.proc.ts +11 -2
  27. package/incrementalBuilder/pendingMetadata.test.ts +27 -0
  28. package/incrementalBuilder/pendingMetadata.ts +19 -0
  29. package/integration/devStability.integration.test.ts +46 -21
  30. package/package.json +5 -10
  31. package/packageExports.test.ts +3 -2
  32. package/test/fakeTerminal.ts +45 -0
  33. package/tunnel/ssh2Module.ts +2 -6
  34. package/util/devInstallCommand.ts +7 -0
  35. package/workspace/slicePlanner.ts +1 -0
  36. package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
  37. package/codeAgent/agent/AkanCodeServices.ts +0 -122
  38. package/codeAgent/agent/AkanContextFiles.ts +0 -94
  39. package/codeAgent/agent/CodeAgent.ts +0 -626
  40. package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
  41. package/codeAgent/agent/CodeAgentAsks.ts +0 -66
  42. package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
  43. package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
  44. package/codeAgent/agent/CodeAgentGate.ts +0 -258
  45. package/codeAgent/agent/CodeAgentProxy.ts +0 -83
  46. package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
  47. package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
  48. package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
  49. package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
  50. package/codeAgent/agent/CodeAgentUi.ts +0 -47
  51. package/codeAgent/agent/CodeMailbox.ts +0 -148
  52. package/codeAgent/agent/CodeSessionFork.ts +0 -56
  53. package/codeAgent/agent/CodeSessionIndex.ts +0 -78
  54. package/codeAgent/agent/SubagentPool.ts +0 -219
  55. package/codeAgent/agent/WorkspaceTrust.ts +0 -200
  56. package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
  57. package/codeAgent/agent/akanCodeModel.ts +0 -47
  58. package/codeAgent/agent/akanCodeServices.test.ts +0 -54
  59. package/codeAgent/agent/akanContextFiles.test.ts +0 -116
  60. package/codeAgent/agent/akanSystemPrompt.ts +0 -50
  61. package/codeAgent/agent/codeAgent.test.ts +0 -337
  62. package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
  63. package/codeAgent/agent/codeAgentContract.test.ts +0 -755
  64. package/codeAgent/agent/codeAgentHosts.ts +0 -30
  65. package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
  66. package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
  67. package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
  68. package/codeAgent/agent/codeMailbox.test.ts +0 -76
  69. package/codeAgent/agent/codeSessionFork.test.ts +0 -58
  70. package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
  71. package/codeAgent/agent/consoleToStderr.ts +0 -8
  72. package/codeAgent/agent/jsonLines.ts +0 -29
  73. package/codeAgent/agent/stringArg.ts +0 -5
  74. package/codeAgent/feedback/DevLogFeedback.ts +0 -82
  75. package/codeAgent/feedback/PreviewFeedback.ts +0 -46
  76. package/codeAgent/feedback/TurnFeedback.ts +0 -98
  77. package/codeAgent/feedback/VerifyFeedback.ts +0 -39
  78. package/codeAgent/tools/AkanCli.ts +0 -51
  79. package/codeAgent/tools/AkanCodePlugins.ts +0 -142
  80. package/codeAgent/tools/AkanEditScope.ts +0 -53
  81. package/codeAgent/tools/AkanEnvKeys.ts +0 -50
  82. package/codeAgent/tools/AkanToolPack.ts +0 -86
  83. package/codeAgent/tools/AkanVerifier.ts +0 -30
  84. package/codeAgent/tools/AskToolPack.ts +0 -99
  85. package/codeAgent/tools/DeepSeekWeb.ts +0 -127
  86. package/codeAgent/tools/MailToolPack.ts +0 -76
  87. package/codeAgent/tools/McpClient.ts +0 -209
  88. package/codeAgent/tools/McpOAuth.ts +0 -233
  89. package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
  90. package/codeAgent/tools/McpServerConfig.ts +0 -131
  91. package/codeAgent/tools/McpSignIn.ts +0 -158
  92. package/codeAgent/tools/McpTokenStore.ts +0 -128
  93. package/codeAgent/tools/McpToolPack.ts +0 -206
  94. package/codeAgent/tools/SessionToolPack.ts +0 -91
  95. package/codeAgent/tools/WebToolPack.ts +0 -315
  96. package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
  97. package/codeAgent/tools/askToolPack.test.ts +0 -116
  98. package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
  99. package/codeAgent/tools/mcpOAuth.test.ts +0 -648
  100. package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
  101. package/piDependencyPins.test.ts +0 -45
@@ -19,6 +19,8 @@ const registryManifest = path.join(workspaceRoot, "apps/minimal/.akan/artifact/s
19
19
  const configFile = path.join(workspaceRoot, "apps/minimal/akan.config.ts");
20
20
  const sharedFile = path.join(workspaceRoot, "apps/minimal/common/registrySharedText.ts");
21
21
  const signalFile = path.join(workspaceRoot, "apps/minimal/lib/_minimal/minimal.signal.ts");
22
+ const dictionaryFile = path.join(workspaceRoot, "apps/minimal/lib/_minimal/minimal.dictionary.ts");
23
+ const baseArtifact = path.join(workspaceRoot, "apps/minimal/.akan/artifact/base-artifact.json");
22
24
  const serviceFile = path.join(workspaceRoot, "apps/minimal/lib/_minimal/minimal.service.ts");
23
25
  const bootLogPrefix = "akan-e2e-boots:";
24
26
  const workerEntry = path.join(workspaceRoot, "pkgs/@akanjs/devkit/incrementalBuilder/buildBatch.proc.ts");
@@ -93,10 +95,10 @@ describe.skipIf(!CsrE2eHarness.enabled)("SSR dev registry (minimal)", () => {
93
95
  executed: w.__AKAN_CSR_LAST_UPDATE__?.executed ?? [],
94
96
  };
95
97
  });
96
- const textIs = async (selector: string, expected: string) =>
98
+ const textIs = async (selector: string, expected: string, timeout = 20_000) =>
97
99
  await ssr.waitFor((target: string, text: string) => document.querySelector(target)?.textContent === text, {
98
100
  args: [selector, expected],
99
- timeout: 20_000,
101
+ timeout,
100
102
  });
101
103
  const probeMarked = (marked: boolean) =>
102
104
  ssr.waitFor(
@@ -469,30 +471,51 @@ describe.skipIf(!CsrE2eHarness.enabled)("SSR dev registry (minimal)", () => {
469
471
  return typeof runtime?.runtime?.fetch?.[name] === "function";
470
472
  }, endpoint)
471
473
  .catch(() => false);
472
- //? A new tab, reopened until one passes: after a metadata save's restart the dev server serves the registry before
473
- //? until its builder rebuilds it, and a restarting backend refuses connections for a moment.
474
- const reopenUntil = async (check: () => Promise<boolean>, timeout = 120_000) => {
474
+ const pongs = async (endpoint: string) =>
475
+ await ssr
476
+ .evaluate(async (name: string) => {
477
+ const runtime = (globalThis as unknown as Record<symbol, { runtime?: { fetch?: Record<string, unknown> } }>)[
478
+ Symbol.for("akanjs.client.runtime")
479
+ ];
480
+ const call = runtime?.runtime?.fetch?.[name];
481
+ return typeof call === "function" && (await (call as () => Promise<unknown>)()) === "pong";
482
+ }, endpoint)
483
+ .catch(() => false);
484
+ //? A new tab, reopened until one passes: until a metadata save's pages build is green the backend from before the
485
+ //? save answers, and a restarting backend refuses connections for a moment.
486
+ const reopenUntil = async (check: () => Promise<boolean>, { csr = false, timeout = 120_000 } = {}) => {
475
487
  const deadline = Date.now() + timeout;
476
- while (!(await ssr.open(REGISTRY, { csr: false }).then(check, () => false))) {
488
+ while (!(await ssr.open(REGISTRY, { csr }).then(check, () => false))) {
477
489
  if (Date.now() > deadline) throw new Error("[ssr-registry-e2e] no page opened within the wait passed the check");
478
490
  await Bun.sleep(1_000);
479
491
  }
480
492
  };
481
493
 
494
+ //? This suite's process group only: another session's dev server in the same worktree runs a builder too.
495
+ const builderPids = () =>
496
+ Bun.spawnSync(["ps", "-axo", "pid=,pgid=,command="])
497
+ .stdout.toString()
498
+ .split("\n")
499
+ .filter((line) => line.includes("incrementalBuilder.proc"))
500
+ .map((line) => line.trim().split(/\s+/))
501
+ .filter(([, pgid]) => ssr.serverGroup === null || pgid === String(ssr.serverGroup))
502
+ .map(([pid]) => pid);
503
+
482
504
  const addEndpoint = (source: string) =>
483
505
  source.replace(
484
506
  " benchPing: query(",
485
507
  ' e2eRegistryPing: query(String, { guards: [Public], mcp: false }).exec(() => "pong"),\n benchPing: query(',
486
508
  );
487
509
 
488
- test("a signal save restarts the builder, and the open tab and a new one both get the new endpoint", async () => {
510
+ test("a signal save restarts only the backend, and the open tab and a new one both get the new endpoint", async () => {
489
511
  await open();
512
+ const builders = builderPids();
490
513
  const orphans = sampleOrphanWorkers(ssr.serverGroup);
491
- //? The component save first keeps the slow lane busy, so the restart lands while a batch is in flight.
514
+ //? The component save first keeps the slow lane busy, so the signal save's batch queues behind one in flight.
492
515
  await ssr.editSource(probeFile, markProbe, async () => {
493
516
  await Bun.sleep(200);
494
517
  await ssr.editSource(signalFile, addEndpoint, async () => {
495
- //? Not reopened: the rebuilt registry's reload, or hello's epoch once the backend is back, moves it on.
518
+ //? Not reopened: hello's epoch, once the restarted backend is back, moves it on.
496
519
  await ssr.waitFor(
497
520
  () =>
498
521
  typeof (globalThis as unknown as Record<symbol, { runtime?: { fetch?: Record<string, unknown> } }>)[
@@ -505,6 +528,64 @@ describe.skipIf(!CsrE2eHarness.enabled)("SSR dev registry (minimal)", () => {
505
528
  });
506
529
  await reopenUntil(async () => !(await fetchHas("e2eRegistryPing")) && (await fetchHas("benchPing")));
507
530
  expect(await orphans()).toEqual([]);
531
+ expect(builderPids()).toEqual(builders);
532
+ }, 300_000);
533
+
534
+ test("a new signal field reaches a CSR and an SSR page, answered by the restarted backend under the same builder", async () => {
535
+ await ssr.open(REGISTRY, { csr: true });
536
+ await ssr.waitFor(() => document.querySelector('[data-e2e="ping"]') !== null, { timeout: 60_000 });
537
+ await open();
538
+ const builders = builderPids();
539
+ await ssr.editSource(signalFile, addEndpoint, async () => {
540
+ await reopenUntil(async () => await pongs("e2eRegistryPing"));
541
+ await reopenUntil(async () => await pongs("e2eRegistryPing"), { csr: true });
542
+ });
543
+ await reopenUntil(async () => !(await fetchHas("e2eRegistryPing")) && (await fetchHas("benchPing")));
544
+ expect(builderPids()).toEqual(builders);
545
+ }, 300_000);
546
+
547
+ const dictionaryUrls = async () => {
548
+ const { dictAssets } = (await Bun.file(baseArtifact).json()) as {
549
+ dictAssets: Record<string, { url: string; parts?: Record<string, { url: string }> }>;
550
+ };
551
+ return Object.values(dictAssets).flatMap((asset) => [
552
+ asset.url,
553
+ ...Object.values(asset.parts ?? {}).map(({ url }) => url),
554
+ ]);
555
+ };
556
+ const dictionaryShows = async (text: string) =>
557
+ await ssr
558
+ .waitFor(
559
+ (want: string) =>
560
+ ['[data-e2e="dict-server"]', '[data-e2e="dict-client"]'].every(
561
+ (selector) => document.querySelector(selector)?.textContent === want,
562
+ ),
563
+ { args: [text], timeout: 15_000 },
564
+ )
565
+ .then(
566
+ () => true,
567
+ () => false,
568
+ );
569
+ const retext = (source: string) => source.replace('healthy: ["Healthy", "정상"]', 'healthy: ["Healthy e2e", "정상"]');
570
+
571
+ test("a dictionary text reaches the open page, a CSR one and /_akan/dict/* under the same builder", async () => {
572
+ await open();
573
+ expect(await dictionaryShows("Healthy")).toBe(true);
574
+ const builders = builderPids();
575
+ const before = await dictionaryUrls();
576
+ await ssr.editSource(dictionaryFile, retext, async () => {
577
+ await textIs('[data-e2e="dict-server"]', "Healthy e2e", 120_000);
578
+ await textIs('[data-e2e="dict-client"]', "Healthy e2e", 30_000);
579
+ const after = await dictionaryUrls();
580
+ expect(after).not.toEqual(before);
581
+ const served = await Promise.all(
582
+ after.map(async (url) => await fetch(new URL(url, ssr.origin)).then((res) => res.text())),
583
+ );
584
+ expect(served.some((text) => text.includes("Healthy e2e"))).toBe(true);
585
+ await reopenUntil(async () => await dictionaryShows("Healthy e2e"), { csr: true });
586
+ });
587
+ await reopenUntil(async () => await dictionaryShows("Healthy"));
588
+ expect(builderPids()).toEqual(builders);
508
589
  }, 300_000);
509
590
 
510
591
  test("a whole build that fails on a broken client module keeps the registry, and the fix brings the endpoint", async () => {
@@ -519,9 +600,11 @@ describe.skipIf(!CsrE2eHarness.enabled)("SSR dev registry (minimal)", () => {
519
600
  });
520
601
  const mark = await ssr.serverLogMark();
521
602
  await ssr.editSource(signalFile, addEndpoint, async () => {
522
- //? The replacement builder's whole build fails on the broken module, and says so before anything is written.
523
- await waitForServerLog(mark, /ssr-registry boot build failed/);
603
+ //? The save's whole build fails on the broken module before anything is written, and the backend from before
604
+ //? the save keeps answering until the fix builds.
605
+ await waitForServerLog(mark, /ssr-dev failed/);
524
606
  expect(((await Bun.file(registryManifest).json()) as { epoch: number }).epoch).toBe(epoch);
607
+ expect(await ssr.serverLogSince(mark)).not.toMatch(/restarting the backend onto it/);
525
608
  await Bun.write(
526
609
  contextFile,
527
610
  (await Bun.file(contextFile).text()).replace("\nexport const registryBroken = ;\n", ""),
@@ -572,17 +655,20 @@ describe.skipIf(!CsrE2eHarness.enabled)("SSR dev registry (minimal)", () => {
572
655
  //? A tab that stopped hydrating shows the label but never counts: a new document is tried until one does. Within
573
656
  //? the save's own patch and pages build, not whenever a later build happens to heal the registry.
574
657
  const hydratesWith = async (label: string) =>
575
- await reopenUntil(async () => {
576
- const hydrated = async () => {
577
- await textIs('[data-e2e="label-client"]', label);
578
- await ssr.evaluate(() => document.querySelector<HTMLButtonElement>('[data-e2e="bump"]')?.click());
579
- await textIs('[data-e2e="count"]', "1");
580
- };
581
- return await hydrated().then(
582
- () => true,
583
- () => false,
584
- );
585
- }, 15_000);
658
+ await reopenUntil(
659
+ async () => {
660
+ const hydrated = async () => {
661
+ await textIs('[data-e2e="label-client"]', label);
662
+ await ssr.evaluate(() => document.querySelector<HTMLButtonElement>('[data-e2e="bump"]')?.click());
663
+ await textIs('[data-e2e="count"]', "1");
664
+ };
665
+ return await hydrated().then(
666
+ () => true,
667
+ () => false,
668
+ );
669
+ },
670
+ { timeout: 15_000 },
671
+ );
586
672
  try {
587
673
  await rm(labelFile);
588
674
  await Bun.write(
@@ -1354,6 +1354,21 @@ describe("PkgExecutor package generation", () => {
1354
1354
  expect(await Bun.file(path.join(root, "dist/pkgs/@sample/tool/package.json")).json()).toEqual(distPackageJson);
1355
1355
  expect(await Bun.file(path.join(root, "pkgs/@sample/tool/package.json")).json()).toEqual(distPackageJson);
1356
1356
  });
1357
+
1358
+ test("names a sibling the root links as workspace:* at the sibling's own version", async () => {
1359
+ const root = await makeTempRoot();
1360
+ await writeJson(
1361
+ path.join(root, "package.json"),
1362
+ rootPackageJson({ devDependencies: { typescript: "6.0.0", "@sample/core": "workspace:*" } }),
1363
+ );
1364
+ await writeJson(path.join(root, "pkgs/@sample/core/package.json"), { name: "@sample/core", version: "0.2.0" });
1365
+ await writeJson(path.join(root, "pkgs/@sample/tool/package.json"), { name: "@sample/tool", version: "0.2.0" });
1366
+
1367
+ const workspace = new WorkspaceExecutor({ workspaceRoot: root, repoName: "repo" });
1368
+ const distPackageJson = await PkgExecutor.from(workspace, "@sample/tool").generateDistPackageJson(["@sample/core"]);
1369
+
1370
+ expect(distPackageJson.dependencies).toEqual({ "@sample/core": "0.2.0" });
1371
+ });
1357
1372
  });
1358
1373
 
1359
1374
  describe("scan info construction", () => {
@@ -33,7 +33,8 @@ export class PkgExecutor extends Executor {
33
33
  ...rootPackageJson.devDependencies,
34
34
  };
35
35
  const rootVersion = rootDeps[dep];
36
- if (rootVersion) return rootVersion;
36
+ //? A `workspace:` range resolves only inside this repo, so a sibling package is published at its own version.
37
+ if (rootVersion && !rootVersion.startsWith("workspace:")) return rootVersion;
37
38
  // Overrides never reach a consumer's install, so a pinned transitive dep is published as a dependency.
38
39
  const overrideVersion = rootPackageJson.overrides?.[dep];
39
40
  if (typeof overrideVersion === "string") return overrideVersion;
@@ -84,14 +84,13 @@ describe("CsrDevPatcher", () => {
84
84
  expect((await new CsrDevPatcher(unstamped.bundler).update([])).kind).toBe("delegate");
85
85
  });
86
86
 
87
- test("a resident patcher checks the stamp once, when it reads the registry", async () => {
87
+ test("a resident patcher checks the stamp of the registry it holds in memory too", async () => {
88
88
  const { bundler, stamp } = await makeRegistry("same");
89
89
  const patcher = new CsrDevPatcher(bundler, { resident: true });
90
90
  expect(await patcher.update([])).toEqual({ kind: "unchanged" });
91
- stamp.current = "moved";
92
91
  expect(await patcher.update([])).toEqual({ kind: "unchanged" });
93
- patcher.forget();
94
- expect((await patcher.update([])).kind).toBe("delegate");
92
+ stamp.current = "moved";
93
+ expect(await patcher.update([])).toMatchObject({ kind: "delegate", generation: 5 });
95
94
  });
96
95
 
97
96
  test("a saved metadata file goes to a whole build even when the stamp matches", async () => {
@@ -60,8 +60,7 @@ export class CsrDevPatcher {
60
60
  ): Promise<CsrDevPatchResult> {
61
61
  const context = await this.#bundler.context();
62
62
  if (!context) return { kind: "unchanged" };
63
- const resident = this.#state;
64
- const state = resident ?? (await this.#load());
63
+ const state = this.#state ?? (await this.#load());
65
64
  if (!state) {
66
65
  const manifest = await this.#bundler.writer.readJson<CsrDevManifest>(CSR_DEV_MANIFEST_FILE);
67
66
  const reason = !manifest
@@ -77,8 +76,9 @@ export class CsrDevPatcher {
77
76
  const metadataFile = changedFiles.find((file) => this.#bundler.isMetadataFile(file));
78
77
  // `lib/useClient.ts` and `lib/usePage.ts` inline signal and dictionary metadata through macros at build time.
79
78
  if (metadataFile) return this.#handBack(`${path.basename(metadataFile)} changed`, generation, context);
80
- //? Only a registry read from disk: one held in memory saw every save since, and a metadata save was handed back.
81
- if (!resident && state.graph.metadata !== (await this.#bundler.metadataFingerprint()))
79
+ //? One held in memory too: the builder outlives a metadata save, so a save that reached this registry through no
80
+ //? changed-file list would otherwise last as long as the builder. The stat of each file costs under a millisecond.
81
+ if (state.graph.metadata !== (await this.#bundler.metadataFingerprint()))
82
82
  return this.#handBack("signal or dictionary metadata changed since the registry was built", generation, context);
83
83
  this.#state = this.#resident ? state : null;
84
84
  //? Not over a module whose factory file is missing: this patch compiles it, and its commit writes app.js whole.
@@ -50,7 +50,6 @@ export class DevChangePlanner {
50
50
  const reasons = new Set<string>();
51
51
  const fileRoles = this.#rolesForFile(file, { isGenerated: generatedSet.has(path.resolve(file)), reasons });
52
52
  for (const role of fileRoles) roles.add(role);
53
- if (reasons.has("runtime-metadata")) actions.add("restart-builder");
54
53
  if (reasons.size > 0) reasonByFile[path.resolve(file)] = [...reasons].sort();
55
54
  }
56
55
 
@@ -3,6 +3,7 @@ import { readFile, rm } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import type { RoutesManifest } from "akanjs/server";
6
+ import { runtimeMetadataFilesOf } from "../akanApp/devHostPolicy";
6
7
  import { tempDirs, writeText as write } from "../test/testHelpers";
7
8
  import { CsrArtifactBuilder } from "./csrArtifactBuilder";
8
9
  import { CssCompiler, declaredCustomProperties, isIgnoredNodeModuleSource } from "./cssCompiler";
@@ -434,7 +435,7 @@ describe("DevChangePlanner", () => {
434
435
  ).toEqual(["restart-dev-host"]);
435
436
  });
436
437
 
437
- test("recycles builder for macro-backed dictionary and signal metadata changes", () => {
438
+ test("restarts only the backend for macro-backed dictionary and signal metadata, which the plan marks", () => {
438
439
  const root = path.resolve("/repo");
439
440
  const planner = new DevChangePlanner({ workspaceRoot: root });
440
441
  const dictionaryFile = path.join(root, "apps/demo/lib/_demo/demo.dictionary.ts");
@@ -449,9 +450,10 @@ describe("DevChangePlanner", () => {
449
450
  kinds: ["code"],
450
451
  });
451
452
 
452
- expect(dictionaryPlan.actions).toEqual(["rebuild-client", "restart-backend", "restart-builder"]);
453
+ expect(dictionaryPlan.actions).toEqual(["rebuild-client", "restart-backend"]);
453
454
  expect(dictionaryPlan.reasonByFile[dictionaryFile]).toContain("runtime-metadata");
454
- expect(signalPlan.actions).toContain("restart-builder");
455
+ expect(signalPlan.actions).toEqual(["rebuild-client", "restart-backend"]);
456
+ expect(runtimeMetadataFilesOf(signalPlan)).toEqual([path.join(root, "libs/shared/lib/admin/admin.signal.ts")]);
455
457
  });
456
458
  });
457
459
 
@@ -100,13 +100,7 @@ export class SsrBaseArtifactBuilder {
100
100
  assets: dictAssets,
101
101
  routes: dictRoutes,
102
102
  groups: dictGroups,
103
- } = await timed("dictionary", () =>
104
- new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).buildAll(akanConfig.i18n, {
105
- splitApi: true,
106
- routes: this.#dictionaryRoutes,
107
- everyGroupAlone: this.#command === "start",
108
- }),
109
- );
103
+ } = await timed("dictionary", () => this.buildDictionaries());
110
104
  const pagesBundle = await timed("pages", () =>
111
105
  new PagesBundleBuilder(this.#app, this.#command, pageEntries, this.#serverEnv).build(),
112
106
  );
@@ -163,6 +157,17 @@ export class SsrBaseArtifactBuilder {
163
157
  return { artifact, seedIndex, cssCompiler, optimizedFonts, runtimeChunks, phaseMs };
164
158
  }
165
159
 
160
+ //? A dev build worker runs it again for a signal or dictionary save, in a process of its own: `lib/dict.ts` imported
161
+ //? into a long-lived one stays cached after its file changes.
162
+ async buildDictionaries(): ReturnType<DictionaryAssetBuilder["buildAll"]> {
163
+ const akanConfig = await this.#app.getConfig();
164
+ return await new DictionaryAssetBuilder(this.#app, this.#absArtifactDir).buildAll(akanConfig.i18n, {
165
+ splitApi: true,
166
+ routes: this.#dictionaryRoutes,
167
+ everyGroupAlone: this.#command === "start",
168
+ });
169
+ }
170
+
166
171
  //? Renamed into place, last: a dev backend booted beside this build starts on the file the moment it exists.
167
172
  static async writeArtifact(absArtifactDir: string, artifact: BaseBuildArtifact): Promise<void> {
168
173
  const artifactPath = path.join(absArtifactDir, "base-artifact.json");
@@ -9,6 +9,8 @@ const makeTempRoot = tempDirs("akan-vendor-narrowing-");
9
9
  const akanjsRoot = path.resolve(import.meta.dir, "../../../akanjs");
10
10
  const vendorFile = (name: string) => path.join(akanjsRoot, "server/vendor", `${name}.ts`);
11
11
  const agentOnlyText = "path must be an internal path starting with /.";
12
+ const formFieldsText = "does not take null.";
13
+ const fieldToolsText = "Leaves every existing row untouched.";
12
14
 
13
15
  const staticClosure = (absPath: string, seen = new Set<string>()): Set<string> => {
14
16
  if (seen.has(absPath)) return seen;
@@ -42,7 +44,11 @@ const buildVendors = async (storeNames: string[], plugins: Awaited<ReturnType<Ve
42
44
  if (!output) throw new Error(`no ${name}.js output`);
43
45
  return output.path;
44
46
  };
45
- return { store: closureText(outputOf("store")), agent: closureText(outputOf("agent")) };
47
+ return {
48
+ store: closureText(outputOf("store")),
49
+ agent: closureText(outputOf("agent")),
50
+ all: result.outputs.map((output) => readFileSync(output.path, "utf8")).join("\n"),
51
+ };
46
52
  };
47
53
 
48
54
  describe("VendorNarrowing", () => {
@@ -58,8 +64,9 @@ describe("VendorNarrowing", () => {
58
64
  ).toEqual({ "/v/akanjs-store.ts": ["st"], "/v/akanjs-base.ts": [] });
59
65
  });
60
66
 
61
- test("keeps the deprecated agent re-export when a route imports one of its names, or reads the store whole", async () => {
62
- expect(await new VendorNarrowing(akanjsRoot, { "akanjs/store": ["AgentContext", "st"] }).plugins()).toEqual([]);
67
+ test("keeps each blankable re-export when a route imports one of its names, or reads the store whole", async () => {
68
+ const names = ["AgentContext", "FormFields", "st"];
69
+ expect(await new VendorNarrowing(akanjsRoot, { "akanjs/store": names }).plugins()).toEqual([]);
63
70
  expect(await new VendorNarrowing(akanjsRoot, {}).plugins()).toEqual([]);
64
71
  });
65
72
 
@@ -74,6 +81,29 @@ describe("VendorNarrowing", () => {
74
81
  expect(agent).toContain(agentOnlyText);
75
82
  }, 60_000);
76
83
 
84
+ test("a store vendor no route reads `FormFields` from loads the field tools only through a dynamic import", async () => {
85
+ const names = ["StoreRegistry", "store", "useFieldTool"];
86
+ const { store, all } = await buildVendors(
87
+ names,
88
+ await new VendorNarrowing(akanjsRoot, { "akanjs/store": names }).plugins(),
89
+ );
90
+
91
+ expect(store).not.toContain(formFieldsText);
92
+ expect(store).not.toContain(fieldToolsText);
93
+ expect(all).toContain(fieldToolsText);
94
+ }, 60_000);
95
+
96
+ test("a route that names `FormFields` keeps it in the store vendor, and the field tools still load apart", async () => {
97
+ const names = ["FormFields", "StoreRegistry", "store"];
98
+ const { store } = await buildVendors(
99
+ names,
100
+ await new VendorNarrowing(akanjsRoot, { "akanjs/store": names }).plugins(),
101
+ );
102
+
103
+ expect(store).toContain(formFieldsText);
104
+ expect(store).not.toContain(fieldToolsText);
105
+ }, 60_000);
106
+
77
107
  test("without the blanking, the deprecated re-export drags the agent runtime into the store vendor", async () => {
78
108
  const { store } = await buildVendors(["StoreRegistry", "store"], []);
79
109
 
@@ -95,6 +125,20 @@ describe("VendorNarrowing", () => {
95
125
  );
96
126
  });
97
127
 
128
+ test("an akanjs from before the lazy field tools has nothing there to blank but its deprecated re-export", async () => {
129
+ const root = await makeTempRoot();
130
+ await write(path.join(root, "store/deprecatedAgent.ts"), 'export { AgentContext } from "./agent";\n');
131
+ await write(path.join(root, "store/agentic/formFields.ts"), "export class FormFields {}\n");
132
+
133
+ const [plugin, ...rest] = await new VendorNarrowing(root, { "akanjs/store": ["st"] }).plugins();
134
+ const filters: RegExp[] = [];
135
+ void plugin?.setup({ onLoad: ({ filter }: { filter: RegExp }) => void filters.push(filter) } as never);
136
+
137
+ expect(rest).toEqual([]);
138
+ expect(filters.map((filter) => filter.test("/w/node_modules/akanjs/store/deprecatedAgent.ts"))).toEqual([true]);
139
+ expect(filters.map((filter) => filter.test("/w/node_modules/akanjs/store/agentic/formFields.ts"))).toEqual([false]);
140
+ });
141
+
98
142
  test("an alias narrowed to no names still loads its entry, so the entry's side effects run", () => {
99
143
  expect(ClientEntriesBundler.narrowedAliasSource("/v/akanjs-fetch.ts", [])).toBe(
100
144
  `export {} from ${JSON.stringify(path.resolve("/v/akanjs-fetch.ts"))};\n`,
@@ -6,6 +6,10 @@ import { VENDOR_SPECIFIERS, type VendorSpecifier } from "./vendorSpecifiers";
6
6
  //? Bun puts a module in the chunk of every entry that reaches it, read or not, so a deprecated re-export would keep
7
7
  //? its target in a vendor every page loads; a narrowed build blanks it unless a route imports one of its names.
8
8
  const deprecatedReexports: Partial<Record<VendorSpecifier, string>> = { "akanjs/store": "store/deprecatedAgent.ts" };
9
+ //? Blanked the same way, but kept out of the guard below: an akanjs older than the lazy field tools lacks the file.
10
+ const lazyReexports: Partial<Record<VendorSpecifier, string>> = {
11
+ "akanjs/store": "store/agentic/formFieldsReexport.ts",
12
+ };
9
13
 
10
14
  export interface VendorEntry {
11
15
  specifier: VendorSpecifier;
@@ -70,9 +74,13 @@ export class VendorNarrowing {
70
74
 
71
75
  async plugins(): Promise<BunPlugin[]> {
72
76
  const blanked: string[] = [];
73
- for (const [specifier, file] of Object.entries(deprecatedReexports) as [VendorSpecifier, string][]) {
77
+ const reexports = [...Object.entries(deprecatedReexports), ...Object.entries(lazyReexports)] as [
78
+ VendorSpecifier,
79
+ string,
80
+ ][];
81
+ for (const [specifier, file] of reexports) {
74
82
  const used = this.#vendorExports[specifier];
75
- if (!used) continue;
83
+ if (!used || !fs.existsSync(path.join(this.#akanjsRoot, file))) continue;
76
84
  const source = await Bun.file(path.join(this.#akanjsRoot, file)).text();
77
85
  const names = new Bun.Transpiler({ loader: "ts" }).scan(source).exports;
78
86
  if (!names.some((name) => used.includes(name))) blanked.push(`akanjs/${file}`);
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { Logger } from "akanjs/common";
3
- import type { BuilderMessage, BuildPhase, HmrTrace } from "akanjs/server";
3
+ import type { BaseBuildArtifact, BuilderMessage, BuildPhase, HmrTrace } from "akanjs/server";
4
4
  import { resolveDevCsrMode } from "akanjs/server/hmr/csrDevManifest";
5
5
  import { ApplicationBuildReporter } from "../app/applicationBuildReporter";
6
6
  import { resolveSsrPageEntriesForApp } from "../artifact/implicitRootLayout";
@@ -202,8 +202,12 @@ class BuildBatch {
202
202
  const pageEntries = await resolveSsrPageEntriesForApp(this.#app, await this.#app.getPageKeys());
203
203
  const seedIndex = computeRouteSeedIndex(pageEntries);
204
204
  const previousGraph = await ServerGraphFile.read(this.#request.artifactDir);
205
+ const dictionaries = this.#request.metadata
206
+ ? await new SsrBaseArtifactBuilder(this.#app).buildDictionaries()
207
+ : null;
205
208
  const next = await new PagesBundleBuilder(this.#app, "start", pageEntries).build();
206
209
  await saveRouteSeedIndex(this.#request.artifactDir, seedIndex);
210
+ if (dictionaries) await this.#rewriteBaseArtifact(next, dictionaries);
207
211
  const nextGraph = await ServerGraphFile.read(this.#request.artifactDir);
208
212
  const serverTouched = await ServerGraphFile.touches(
209
213
  previousGraph,
@@ -232,6 +236,28 @@ class BuildBatch {
232
236
  }
233
237
  }
234
238
 
239
+ //? Before `pages-updated` and the pages status: the dev host restarts the backend on that status, and the backend
240
+ //? reads this file once, at its boot.
241
+ async #rewriteBaseArtifact(
242
+ pages: { bundlePath: string; buildId: number },
243
+ { assets, routes, groups }: Awaited<ReturnType<SsrBaseArtifactBuilder["buildDictionaries"]>>,
244
+ ): Promise<void> {
245
+ const artifactPath = path.join(this.#request.artifactDir, "base-artifact.json");
246
+ const { dictRoutes, dictGroups, ...artifact } = (await Bun.file(artifactPath).json()) as BaseBuildArtifact;
247
+ await SsrBaseArtifactBuilder.writeArtifact(this.#request.artifactDir, {
248
+ ...artifact,
249
+ cssAssets: this.#result.cssAssets ?? this.#request.cssAssets ?? artifact.cssAssets,
250
+ dictAssets: assets,
251
+ ...(routes ? { dictRoutes: routes } : {}),
252
+ ...(groups ? { dictGroups: groups } : {}),
253
+ pagesBundlePath: pages.bundlePath,
254
+ pagesBundleBuildId: pages.buildId,
255
+ });
256
+ this.#logger.verbose(
257
+ `base-artifact rewritten for ${this.#request.metadata?.length ?? 0} metadata file(s) buildId=${pages.buildId}`,
258
+ );
259
+ }
260
+
235
261
  async #buildCss(): Promise<void> {
236
262
  const started = Date.now();
237
263
  try {
@@ -20,6 +20,7 @@ export interface BuildBatchRequest {
20
20
  cssAssets: PagesBatchCssAssets | null; // an unchanged compile skips the broadcast instead of busting hashes
21
21
  artifactDir: string;
22
22
  trace?: HmrTrace;
23
+ metadata?: string[]; // signal and dictionary saves no batch has built green yet; `pages` batches only
23
24
  }
24
25
 
25
26
  export type BatchWork = Pick<BuildBatchRequest, "generation" | "needs" | "changedFiles" | "trace">;
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
  import type { Logger } from "akanjs/common";
3
3
  import type { ChangeBatch } from "akanjs/server";
4
+ import { runtimeMetadataFilesOf } from "../akanApp/devHostPolicy";
4
5
  import type { App } from "../commandDecorators";
5
6
  import type { PageRoot } from "../executors";
6
7
  import { AutoImportSync } from "../frontendBuild/autoImportSync";
@@ -17,6 +18,7 @@ import type { BuilderLanes } from "./builderLanes";
17
18
  import type { BatchJob, DiscoveryJob } from "./builderWorkQueue";
18
19
  import type { CsrRegistry } from "./csrRegistry";
19
20
  import { prepareDevWatchBatch } from "./devWatchBatch";
21
+ import type { PendingMetadata } from "./pendingMetadata";
20
22
  import type { SsrRegistry } from "./ssrRegistry";
21
23
 
22
24
  interface BuilderWatchParts {
@@ -25,6 +27,7 @@ interface BuilderWatchParts {
25
27
  csr: CsrRegistry;
26
28
  ssr: SsrRegistry;
27
29
  graphPayloads: BuilderGraphPayloads;
30
+ metadata: PendingMetadata;
28
31
  }
29
32
 
30
33
  interface BuilderWatchLinks {
@@ -39,6 +42,7 @@ export class BuilderWatch {
39
42
  readonly #csr: CsrRegistry;
40
43
  readonly #ssr: SsrRegistry;
41
44
  readonly #graphPayloads: BuilderGraphPayloads;
45
+ readonly #metadata: PendingMetadata;
42
46
  readonly #links: BuilderWatchLinks;
43
47
  #changePlanner: DevChangePlanner;
44
48
  #generatedIndexSync: DevGeneratedIndexSync;
@@ -46,13 +50,18 @@ export class BuilderWatch {
46
50
  #watcher: HmrWatcher | null = null;
47
51
  #barrelFailed = false;
48
52
 
49
- constructor(app: App, { logger, lanes, csr, ssr, graphPayloads }: BuilderWatchParts, links: BuilderWatchLinks) {
53
+ constructor(
54
+ app: App,
55
+ { logger, lanes, csr, ssr, graphPayloads, metadata }: BuilderWatchParts,
56
+ links: BuilderWatchLinks,
57
+ ) {
50
58
  this.#app = app;
51
59
  this.#logger = logger;
52
60
  this.#lanes = lanes;
53
61
  this.#csr = csr;
54
62
  this.#ssr = ssr;
55
63
  this.#graphPayloads = graphPayloads;
64
+ this.#metadata = metadata;
56
65
  this.#links = links;
57
66
  this.#changePlanner = new DevChangePlanner({ workspaceRoot: app.workspace.workspaceRoot });
58
67
  this.#generatedIndexSync = new DevGeneratedIndexSync({ workspaceRoot: app.workspace.workspaceRoot });
@@ -131,6 +140,7 @@ export class BuilderWatch {
131
140
  indexSync,
132
141
  changePlanner: this.#changePlanner,
133
142
  });
143
+ this.#metadata.note(runtimeMetadataFilesOf(devPlan), generation);
134
144
  this.#logger.verbose(
135
145
  `[hmr] batch generation=${generation} kinds=${kinds.join(",")} files=${files.length} generated=${indexSync.changedFiles.length} roles=${devPlan.roles.join(",") || "(none)"} actions=${devPlan.actions.join(",") || "(none)"}`,
136
146
  );