@akanjs/devkit 3.2.0 → 3.2.1-rc.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,99 @@
1
1
  # @akanjs/devkit
2
2
 
3
+ ## 3.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 1d8c8c2: An app with `basePaths` keeps every base path's CSS class scan in the candidate cache, so a start or build no longer rescans the sources of all but one of them. An entry is dropped only once its source file is deleted.
8
+ - 4732186: `akan --version` loads no command module, and `akan tunnel`, `akan subspace` and the package commands such as `akan version` no longer load the TypeScript compiler unless a step compiles.
9
+ - 98931e4: `akan start` boots the backend while the first base build runs: the backend loads its server graph beside the build and mounts the web surface as soon as the build's artifact is on disk, so the dev server is ready sooner.
10
+
11
+ The port now answers from the start of the build. A request to `localhost` or an IP address, page or API, waits for the first artifact; a build longer than the 15 s the gateway holds a request ends the wait with a 503 "Backend is starting" page that reloads itself. A request to one of the app's own domains (a custom local domain) gets that 503 at once until the backend is ready, because the build has not written the app's hosts yet; after that it is served as before, and any other Host is refused as before.
12
+
13
+ - 1d8c8c2: `akan start` keeps `apps/<app>/.akan/cache` between runs, so a restart reuses the CSS class scan and the subset fonts instead of redoing them. Each entry names the akanjs and Bun versions and the build of the cache code that wrote it, and an entry another one wrote, or one cut short, is rebuilt.
14
+ - 98931e4: `akan start` prints one line when the dev server is ready that says where the start's time went: what the CLI did before the builder, the base build and its parts, the backend's boot, and when the first artifact was on disk.
15
+ - Updated dependencies [bf582c1]
16
+ - Updated dependencies [c10f7cf]
17
+ - Updated dependencies [c10f7cf]
18
+ - Updated dependencies [5c7e083]
19
+ - Updated dependencies [aead1aa]
20
+ - Updated dependencies [5c6d039]
21
+ - Updated dependencies [0492e0b]
22
+ - Updated dependencies [0492e0b]
23
+ - Updated dependencies [5c7e083]
24
+ - Updated dependencies [98931e4]
25
+ - akanjs@3.2.1
26
+ - @akanjs/language@3.2.1
27
+
28
+ ## 3.2.0
29
+
30
+ ### Minor Changes
31
+
32
+ - 038d918: Akan.js 3.2.0. Read **Upgrade notes** before deploying an app that runs 3.1.1: unguarded endpoints, log levels, the `Err` class, loaders, SQLite transactions, exit codes and a CLI version check change behaviour.
33
+
34
+ **Highlights**
35
+
36
+ - **`agentService.loop`.** A server-side agent run over the `/mcp` tool catalogue, in-process, with `toolkits`, `remotes` (other MCP servers), `clientTools` (a screen the member has open), `ask` (a question parked between runs), `answer`, overflow retry, and a read rule that counts what a run reads as untrusted. `plug(AgentToolsRole)` runs the catalogue as a given account; `mcp: "agent"` keeps an entry off `/mcp` for the in-process agent only.
37
+ - **Akan Graph and Akan Studio.** `get_graph` (MCP) returns the Akan Graph, read from source with no dev server: models, scalars, slices, endpoints with guards, services, jobs, adaptors, routes, layouts, the framework itself, and the Change Map for `since: <revision>`. `akan start` serves Studio at `/_akan/studio`, and it opens from the CLI and the editor.
38
+ - **Editor support.** `@akanjs/language` resolves names Akan.js derives (`fetch.initMemoInPublic`, `st.do.setNameOnMemo`, `this.memoService.listByName`) and ships `akan-language-server`. The VS Code / Cursor extension opens a module side by side, runs `akan verify` and workflows, and publishes from CI to the VS Marketplace and Open VSX.
39
+ - **Secure defaults.** Signals, websocket rooms, MCP, OAuth, the agent relay, the server edge, the ops channel, native builds, `akan code`, the CLI's tunnels and workflows, and the in-page agent each take the narrower default. Every change names how to get the old behaviour back.
40
+ - **Faster pages.** Every SSR page loads 72K less framework JS (22K less Brotli); client modules preload from `<head>`; Link prefetch; Flight rows share inline scripts; one preloaded font face per family; faster RSC decoding and store writes; a route JS budget (`akan build --check-budget`).
41
+ - **Realtime.** Per-socket, per-caller and per-model room limits, subscribe budgets, gateway subscribe acks, per-model live-sync routing, Redis room sharding, resync after a Redis outage, and an outbox limit for a down socket.
42
+ - **Native.** `external-view` on Linux (Wayland and X11) with `sendKey`; Android 12 launch crash fixed; AppImage relaunch; tighter CSP, external-link, temp-folder and update defaults.
43
+
44
+ **Upgrade notes**
45
+
46
+ - **Guards.** An endpoint, slice query or pubsub room that declares no guards is refused with 403; open it with `[Public]`. Outside local operation a server whose signals declare a guardless endpoint stops at boot and names each one. `AKAN_UNGUARDED_ENDPOINTS=open` answers them as before. A slice whose `guards` leaves out `root` mounts no root list or insight. `guard(name)` refuses until `canPass` is overridden.
47
+ - **`Err`.** Every `Err` is one class, `Err` from `akanjs/common`, and an `AkanError`. `err.code` is always set (a generalized failure's code, else its status's code), so `{ ...err }` now holds it. `Err.NotFound.is(error)` also requires status 404. Check across a page bundle and the framework with `Err.is`, not `instanceof`. `setErrorConstructor`, `HttpClientOptions.ErrorCls` and `FetchClient.build`'s `Err` option are deprecated.
48
+ - **Coded failures.** The signal, service, server, route-tree, RSC and client facets throw coded `AkanError`s instead of a bare `Error`; messages and statuses are unchanged. A production 500 shows the status reason and code only. `bun run error:codes` lists the codes. A failed tool call and a failed agent turn carry a `code`.
49
+ - **Log levels.** A failure under 500 logs at `warn`, a 5xx is one `error` record with `type` and `stack`, a declared error, a 429 and a by-id read of a missing id log at `debug`, and a crashed RSC worker logs at `warn`. Alerts and `--level error` filters see fewer lines. A page `redirect()` is `ok` at `info` with its 3xx status, and `notFound()` is `warn` with 404. Every log record reaches ndjson stdout, and a request line is never folded.
50
+ - **Loaders.** A loader no longer shares a batch between a transaction and the requests outside it, and each caller gets its own document. A loader that keeps its keys forgets them when the model is written; a write by query clears every kept key of the model, and `cache: true` keeps the 10,000 most recent keys. A custom `DatabaseAdaptor` can implement `transactionKey()`; a `batchScheduleFn` must run its callback in the caller's async context.
51
+ - **SQLite.** Work outside an open `this.transaction()` no longer sees its uncommitted rows, on `:memory:` or a non-WAL file either. `SqliteDatabase.getMeta` and `listMeta` return promises, so await them. A reader pays one database copy per transaction on `:memory:`; past a few tens of megabytes, put the database in a file.
52
+ - **Indexes.** A boot keeps an index the release no longer declares and warns about it. After every instance runs this release, run `akan migrate <app> prune-indexes` once. `migrationActions` gains `indexes` and `prune-indexes`, so code that switches over every action needs the two cases.
53
+ - **Websockets.** A socket holds at most 256 rooms, a caller 2,000 per process, a model 50,000 evaluated live rooms; a subscribe past a limit gets a 429 frame coded `liveRoomLimit`. Subscribes are budgeted at 1,000 a minute per socket and 10,000 per caller. A `pubsub` room's `onResync` also runs after Redis returns; a custom `WebsocketAdaptor.onRecovered` handler now takes the held rooms. A down socket keeps at most 100 emits.
54
+ - **Gateway.** `/_akan/app/ready` answers 503 while no replica's RSC worker can render. A subscribe is acknowledged once the gateway routes the room.
55
+ - **CLI.** A CLI whose major.minor differs from the workspace's `akanjs` refuses every command that writes, with exit 2; run `akan update`, or set `AKAN_ALLOW_VERSION_MISMATCH=1`. Exit codes: 2 for usage and unknown targets, 3 for failed checks (`verify`, `typecheck`), 130 for an interrupted prompt; a script that tested for exit 1 tests for non-zero. With `--json`, a failure ends stdout with `{"ok":false,"error":"<message>","code":"<code>"}`. `akan doctor` exits 1 on `"status": "failed"`; `akan workflow plan`, `apply` and `validate` exit non-zero on failure. A shell `AKAN_PUBLIC_ENV` now outranks the workspace `.env`, and `akan build --env <env>` builds another environment.
56
+ - **Package budget.** `akan lint` and `akan verify` hold each package under `pkgs/` to the file, function and class budget. Run `akan quality baseline` once in a workspace whose packages are over it. `akan verify` also typechecks every app and lib that uses a changed lib.
57
+ - **Secure defaults.**
58
+ - Write tools in the in-page agent confirm by default (`submit`, `create`, `update`, `send`, `export` and the rest, not only `remove`); opt out with `{ confirm: false }`. Page text reaches the model fenced as data, and a transcript belongs to one account.
59
+ - A `FetchClient` sends its session token only to its own origin; pass `clone({ origin, jwt })` to send one elsewhere.
60
+ - A connection idle for 120 s closes (`AKAN_IDLE_TIMEOUT`), a body is capped at 128 MiB (`AKAN_MAX_UPLOAD_BODY`) and 16 MiB for a non-multipart one (`AKAN_MAX_REQUEST_BODY`), `akan start` binds 127.0.0.1 (`AKAN_LISTEN_HOST=*` restores it), and HTML carries `Cache-Control`, HSTS and a `frame-ancestors` policy.
61
+ - The dev server answers only `localhost`, `*.localhost` and IP hosts unless `AKAN_ALLOWED_HOSTS` is set.
62
+ - A 500 shows its message and stack only under `akan start`, `NODE_ENV` `development` or `test`, or `AKAN_ERROR_DETAIL=1`.
63
+ - `ops snapshot` outside local operation needs `AKAN_BACKUP_RECIPIENT` or `--allow-plaintext`; the ops key must differ from `AKAN_MACHINE_PUBLIC_KEY`.
64
+ - `/__rsc/manifest` is dev-only (`AKAN_EXPOSE_RSC_MANIFEST=1`), and health detail, metrics and devtools need a local dev runtime.
65
+ - Filter arguments are parsed against their declared type and an `Any` filter argument throws at declaration; `q.search()` text is capped at 32 terms and 1000 characters.
66
+ - The image optimizer refuses non-public remote hosts (`images.dangerouslyAllowLocalIP`).
67
+ - The CLI's tunnels listen on loopback and check the SSH host key, workflow commands run without a shell, `akan download-env` copies only env and secret files, a Dockerfile built with `AKAN_PUBLIC_ENV=local` needs `--build-arg AKAN_ALLOW_LOCAL_IMAGE=1`, and `akan code` asks before network access and trusts a repository's MCP servers and extensions only after one terminal approval.
68
+ - MCP rate-limits an unverified bearer by address, checks the browser Origin, and bounds client registration; the agent relay refuses a request past fixed limits with `agent.error.requestRefused` (413) unless a policy sets its own.
69
+ - Native builds ship a Content-Security-Policy, open only `https:`, `mailto:` and `tel:` links, and recheck a downloaded desktop update before installing it; `updates.windowsSigners` and `updates.expiresIn` are new.
70
+ - **UI.** `Field.Switch`'s on position is `primary` (pass `variant="accent"` for the old look), and two `Data.Item` status tags change color. `useCamera` and `useGeoLocation` no longer send the user to Settings after a denial. A page `.head()` can set `theme-color`, and a level that writes an image no longer inherits the image tags above it. `--akan-theme-color` drives the browser's `theme-color`.
71
+ - **Libraries.** The `shared` and `util` libraries `akan install-library` copies are refreshed; compare your copy. In `util`, `security` and `security.jwtSecret` are optional in `ModulesOptions`. `libs/shared` keeps its SSO and refresh cookies on `__Host-` names outside local.
72
+ - **Other.** `LLM` stream endings are read more completely: a cut tool call ends as `length`, and unparseable arguments in a finished answer get `argsError` and the code `invalidArgument`. `ConformanceEnv.has` fails instead of skipping when `AKAN_TEST_REQUIRE_BACKENDS=1`. A new workspace has no `patches/` folder, no `agent:sample:*` scripts and one `setup:agent` script; `create-akan-workspace` no longer hangs when `akan` is not on PATH.
73
+
74
+ **Features**
75
+
76
+ - **Agent.** `Agent.Chat` modals and toasts stack above the panel and its header takes a node; the tool row is the `AgentToolRow` override slot; a restored transcript that ends on an unanswered `askUser` reopens on it; a turn its caller stops is billed at what the provider plausibly charged, and every turn the quota passes is billed.
77
+ - **Rendering and navigation.** `{ static: true }` page apps answer a host that asks for script-less HTML; `i18n.localePrefix: "as-needed"` serves the default locale unprefixed; a route guard receives `{ path }` and `signedIn({ path })` adds `?redirect=`; a failed route level or `Load.Stream` draws a notice with "Try again" in its own place; `router.refresh()` in CSR no longer reloads the document; a lazy chunk the server no longer serves reloads the page once; `forwardVisitor: false` keeps a render cacheable; a query takes `signal` and identical in-flight queries share one request.
78
+ - **Data.** `create<Model>Many(rows)` runs every row through `_preCreate`, `_postCreate` and the document hooks; `bulkWrite` runs in one transaction; a cascade removes a long array's documents 200 ids at a time; `Binary` arguments are typed `Uint8Array<ArrayBuffer>`; a hidden `.optional()` field is optional in create inputs; store form setters and writes cost about one copy of the state; `onError` on store writes receives the failed request's dictionary error.
79
+ - **Server and ops.** `/_akan/app/ready`; `RestartSchedule` shared by every child-restart loop; a single-flight `cache` endpoint; stopped or failed starts tear down what they brought up; the Redis WebSocket adaptor shards channels per room and model and flushes publishes on shutdown; a log stream stops growing for a client that stops reading; missing assets answer `no-store`.
80
+ - **CLI.** `akan test --parallel=<n>`, `--junit <path>` and `--coverage`; `akan build --env`; a `rename-key` workflow; `akan remove-module pokedex:_billing` removes a service module; `akan create-workspace` works in an existing folder, without sample code, and without a git identity; `akan preview` opens `/_akan/studio`, `/openapi.json` and `/mcp` as written and restarts a dead browser; `akan verify` reports step durations and gives a dictionary hint for a missing key; commands without a terminal take the workspace's only app, lib or package, and remove commands never pick a target themselves; release candidates publish from CI with npm provenance.
81
+ - **Native.** `external-view` and `sendKey` on Linux; Android 12 and 12L launch fix; AppImage relaunch; a `single-instance` pipe that another account cannot own on Windows.
82
+ - **Types and styling.** A new app's default style is Pretendard with -3% letter spacing, even sizes from 12px, 150% line height for wrapping text and `leading-auto` for one line.
83
+
84
+ **Fixes**
85
+
86
+ - A dev page keeps its styles after a stylesheet change arrives with a pages rebuild; idle-suspended dev servers apply every save, stay awake when work arrives, and stop cleanly; `[BarrelAnalyzer] ERROR scan failed` is gone; a backend replica's builder answer no longer reaches its replacement.
87
+ - A page that renders a string of 1024 characters or more renders and hydrates whatever its lines say; a page cut off by a disconnected client, or one that streamed an error, is no longer cached; partial RSC commit (`AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`) patches real pages, replays patches from cache and cancels overtaken navigations.
88
+ - In production, a render error no longer reaches the browser as its message; reading the client address from a crafted forwarded header no longer stalls the server; `happy-dom` peers ask for `^21.0.4`; the pi agent packages move to 1.5.2, dropping undici and minimatch advisories.
89
+ - The build lock records its host and survives a dead remover, a Windows antivirus hold and a devcontainer; `akan` no longer rebuilds the dev CLI from a command it runs; the typecheck behind `akan verify` and `akan build` uses its incremental cache.
90
+ - Internal: the largest classes and methods in `akanjs`, `@akanjs/devkit` and `@akanjs/cli` are split by concern with unchanged public members, and the `akanjs` facets import sibling files instead of their own barrel and list every export by name.
91
+
92
+ ### Patch Changes
93
+
94
+ - Updated dependencies [038d918]
95
+ - akanjs@3.2.0
96
+
3
97
  ## 3.1.1
4
98
 
5
99
  ### Patch Changes
@@ -32,6 +32,11 @@ describe("readProcessRssBytes", () => {
32
32
  });
33
33
  });
34
34
 
35
+ interface BuilderStart {
36
+ onBaseBuilt?: (phaseMs: Record<string, number>) => void;
37
+ onReady?: () => void;
38
+ }
39
+
35
40
  describe("Redis tunnels during dev startup", () => {
36
41
  isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "testing" });
37
42
  const track = tempRoots();
@@ -54,7 +59,10 @@ describe("Redis tunnels during dev startup", () => {
54
59
  ({
55
60
  status: "ready",
56
61
  patcherOff: false,
57
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
62
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
63
+ onBaseBuilt?.({});
64
+ onReady?.();
65
+ },
58
66
  send: () => true,
59
67
  stop: () => undefined,
60
68
  }) as unknown as IncrementalBuilderHost;
@@ -101,7 +109,10 @@ describe("a gateway whose replica crash-loops", () => {
101
109
  const readyBuilder = {
102
110
  status: "ready",
103
111
  patcherOff: false,
104
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
112
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
113
+ onBaseBuilt?.({});
114
+ onReady?.();
115
+ },
105
116
  send: () => true,
106
117
  stop: () => undefined,
107
118
  } as unknown as IncrementalBuilderHost;
@@ -151,7 +162,10 @@ describe("a builder request while no builder is running", () => {
151
162
  const stoppedBuilder = {
152
163
  status: "stopped",
153
164
  patcherOff: false,
154
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
165
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
166
+ onBaseBuilt?.({});
167
+ onReady?.();
168
+ },
155
169
  send: () => false,
156
170
  stop: () => undefined,
157
171
  } as unknown as IncrementalBuilderHost;
@@ -208,7 +222,10 @@ describe("the builder's answers and a returning builder", () => {
208
222
  ({
209
223
  status: "ready",
210
224
  patcherOff: false,
211
- start: ({ onReady }: { onReady?: () => void }) => onReady?.(),
225
+ start: ({ onBaseBuilt, onReady }: BuilderStart) => {
226
+ onBaseBuilt?.({});
227
+ onReady?.();
228
+ },
212
229
  send: (message: BuilderMessage) => {
213
230
  sent.push(message);
214
231
  return true;
@@ -1,3 +1,5 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import { Logger } from "akanjs/common";
2
4
  import type { BuilderMessage } from "akanjs/server";
3
5
  import type { App } from "../commandDecorators";
@@ -21,6 +23,7 @@ import {
21
23
  } from "./devHostPolicy";
22
24
  import { DevIdleSuspend } from "./devIdleSuspend";
23
25
  import { DevRecycler } from "./devRecycler";
26
+ import { DevStartTimeline } from "./devStartTimeline";
24
27
  import { ProcessRss } from "./processRss";
25
28
 
26
29
  export class AkanAppHost {
@@ -31,6 +34,8 @@ export class AkanAppHost {
31
34
  #lastDevState: DevHostState | null = null;
32
35
  readonly #bootLatch = new DevBootLatch(() => this.#onDevEvent?.({ app: this.app.name, booted: true }));
33
36
  #stopping = false;
37
+ //? `pending`: a start is building its first artifact and nothing is on disk; `built`: it is; `settled`: no start runs.
38
+ #firstArtifact: "pending" | "built" | "settled" = "settled";
34
39
  #builderMessageQueue: Promise<void> = Promise.resolve();
35
40
  readonly #backendGraph: BackendImportGraph;
36
41
  readonly #statuses: DevBuildStatusBoard;
@@ -41,6 +46,7 @@ export class AkanAppHost {
41
46
  readonly #builder: DevBuilder;
42
47
  readonly #idle: DevIdleSuspend;
43
48
  readonly #recycler: DevRecycler;
49
+ readonly #timeline: DevStartTimeline;
44
50
  constructor(
45
51
  private readonly app: App,
46
52
  {
@@ -58,17 +64,23 @@ export class AkanAppHost {
58
64
  const isStopping = () => this.#stopping;
59
65
  const statuses = new DevBuildStatusBoard(logger);
60
66
  this.#statuses = statuses;
67
+ this.#timeline = new DevStartTimeline(logger);
61
68
  this.#backend = new DevBackend(
62
69
  app,
63
70
  { env, stdio, logger, statuses, graph },
64
71
  {
65
72
  isStopping,
66
- emit: (state, detail) => this.#emitDevEvent(state, detail),
73
+ emit: (state, detail) => {
74
+ if (state === "ready") this.#timeline.mark("backendReady");
75
+ this.#emitDevEvent(state, detail);
76
+ },
67
77
  beforeSpawn: () => {
78
+ this.#timeline.mark("backendSpawned");
68
79
  // Before the spawn: the new backend numbers its requests from 1 again, so old answers must not reach it.
69
80
  this.#requests.startGeneration();
70
81
  this.#requests.discard("the backend restarted while the builder was away");
71
82
  },
83
+ awaitsArtifact: () => this.#firstArtifact === "pending",
72
84
  toBuilder: (message) => this.#requests.send(message),
73
85
  },
74
86
  );
@@ -99,7 +111,16 @@ export class AkanAppHost {
99
111
  isStopping,
100
112
  onMessage: (message) => this.#enqueueBuilderMessage(message),
101
113
  onAway: () => this.#gap.open("builder replacement"),
102
- onReady: () => this.#requests.flush(),
114
+ onReady: () => {
115
+ this.#timeline.mark("builderReady");
116
+ this.#requests.flush();
117
+ },
118
+ onBaseBuilt: (phaseMs) => {
119
+ this.#timeline.baseBuilt(phaseMs);
120
+ //? A builder retried inside one start wrote the artifact again, under a backend that booted on the first.
121
+ if (this.#firstArtifact === "built") this.#backend.scheduleRestart({ files: [], roles: [] });
122
+ else if (this.#firstArtifact === "pending") this.#firstArtifact = "built";
123
+ },
103
124
  onRestartReady: () => {
104
125
  this.logger.verbose("[builder-recovery] builder ready after restart; replaying latest state");
105
126
  this.#backend.replay();
@@ -154,13 +175,29 @@ export class AkanAppHost {
154
175
  async start() {
155
176
  if (this.#backend.running) await this.#backend.stop();
156
177
  if (this.#builder.current) this.#builder.stop();
157
- const [redisHost] = await Promise.all([
158
- this.#prepareDatabase("redis"),
159
- this.#backendGraph.refresh(),
160
- this.#builder.start(),
161
- ]);
162
- Object.assign(this.env, { REDIS_HOST: redisHost });
163
- this.#backend.start();
178
+ this.#timeline.begin();
179
+ const artifactFile = path.join(this.app.cwdPath, ".akan/artifact/base-artifact.json");
180
+ //? Beside the build only when nothing is on disk: the backend would boot on an artifact an earlier start left.
181
+ this.#firstArtifact = fs.existsSync(artifactFile) ? "settled" : "pending";
182
+ const prepared = Promise.all([this.#prepareDatabase("redis"), this.#backendGraph.refresh()]).then(([redisHost]) => {
183
+ Object.assign(this.env, { REDIS_HOST: redisHost });
184
+ if (this.#firstArtifact !== "settled") this.#backend.start();
185
+ });
186
+ try {
187
+ await Promise.all([this.#builder.start(), prepared]);
188
+ } catch (error) {
189
+ this.#firstArtifact = "settled";
190
+ if (!this.#stopping) await this.#backend.stop();
191
+ throw error;
192
+ }
193
+ const artifactMissing = this.#firstArtifact === "pending" && !fs.existsSync(artifactFile);
194
+ this.#firstArtifact = "settled";
195
+ //? The boot build failed and its builder waits for the fix: a backend holding out for the artifact serves no API.
196
+ if (artifactMissing && !this.#stopping) {
197
+ await this.#backend.restarting;
198
+ await this.#backend.stop();
199
+ }
200
+ if (!this.#backend.running) this.#backend.start();
164
201
  this.#idle.arm();
165
202
  return this;
166
203
  }
@@ -44,6 +44,7 @@ type Boot = "ready" | "exit" | "hold" | "starting";
44
44
  interface BuilderStartOptions {
45
45
  onExit?: () => void;
46
46
  onReady?: () => void;
47
+ onBaseBuilt?: (phaseMs: Record<string, number>) => void;
47
48
  onRestartReady?: () => void;
48
49
  onAway?: () => void;
49
50
  }
@@ -54,12 +55,15 @@ interface FakeBuilder {
54
55
  recycled: string[];
55
56
  stopped: number;
56
57
  toHost: (message: BuilderMessage) => void;
58
+ baseBuilt: (phaseMs?: Record<string, number>) => void;
59
+ exit: () => void;
57
60
  ready: () => void;
58
61
  away: () => void;
59
62
  restartReady: () => void;
60
63
  }
61
64
 
62
65
  interface FakeBackend {
66
+ awaitsArtifact: boolean;
63
67
  sent: BuilderMessage[];
64
68
  signals: string[];
65
69
  lingers: boolean;
@@ -69,6 +73,7 @@ interface FakeBackend {
69
73
  }
70
74
 
71
75
  interface BackendSpawnOptions {
76
+ env?: Record<string, string>;
72
77
  ipc: (message: BuilderMessage) => void;
73
78
  onExit?: (proc: unknown, code: number | null, signal: string | null) => void;
74
79
  }
@@ -100,6 +105,11 @@ const fakeBuilder = (toHost: (message: BuilderMessage) => void, boot: Boot) => {
100
105
  recycled: [],
101
106
  stopped: 0,
102
107
  toHost,
108
+ baseBuilt: (phaseMs = {}) => options.onBaseBuilt?.(phaseMs),
109
+ exit: () => {
110
+ builder.status = "stopped";
111
+ options.onExit?.();
112
+ },
103
113
  ready: () => {
104
114
  builder.status = "ready";
105
115
  options.onReady?.();
@@ -124,8 +134,10 @@ const fakeBuilder = (toHost: (message: BuilderMessage) => void, boot: Boot) => {
124
134
  if (boot === "exit") {
125
135
  builder.status = "stopped";
126
136
  options.onExit?.();
127
- } else if (boot === "ready") builder.ready();
128
- else {
137
+ } else if (boot === "ready") {
138
+ builder.baseBuilt();
139
+ builder.ready();
140
+ } else {
129
141
  builder.status = "starting";
130
142
  if (boot === "starting") options.onReady?.();
131
143
  }
@@ -163,6 +175,7 @@ const fakeBackends = () => {
163
175
  queueMicrotask(() => options.onExit?.(proc, code, signal));
164
176
  };
165
177
  const backend: FakeBackend = {
178
+ awaitsArtifact: options.env?.AKAN_DEV_AWAIT_ARTIFACT === "1",
166
179
  sent: [],
167
180
  signals: [],
168
181
  lingers: false,
@@ -681,6 +694,26 @@ describe("AkanAppHost start and stop", () => {
681
694
  expect(dev.events.slice(seen)).toEqual([]);
682
695
  });
683
696
 
697
+ test("says where a start's time went in one line, once the builder and the backend are both ready", async () => {
698
+ const dev = await devHost(["hold"]);
699
+ const starting = dev.host.start();
700
+ expect(await until(() => dev.builders.length === 1)).toBe(true);
701
+ dev.builder().baseBuilt({ runtime: 1, routes: 2, styles: 3, dictionary: 4, pages: 5, total: 15 });
702
+ dev.builder().ready();
703
+ await starting;
704
+ const timelines = () => dev.logs.filter((line) => line.startsWith("ready in "));
705
+ expect(timelines()).toEqual([]);
706
+
707
+ readyBackend(dev);
708
+
709
+ expect(timelines()).toHaveLength(1);
710
+ expect(timelines()[0]).toContain("base build 15 [runtime 1 · routes 2 · styles 3 · dictionary 4 · pages 5]");
711
+ expect(timelines()[0]).toMatch(/prepare \d+ · builder \d+: spawn \d+ .* · backend \d+ · first artifact at \d+\)$/);
712
+
713
+ dev.backend().say({ type: "backend-ready", pid: 1 });
714
+ expect(timelines()).toHaveLength(1);
715
+ });
716
+
684
717
  test("a second start replaces the backend and the builder the first one started", async () => {
685
718
  const dev = await startedHost();
686
719
 
@@ -691,6 +724,177 @@ describe("AkanAppHost start and stop", () => {
691
724
  });
692
725
  });
693
726
 
727
+ describe("AkanAppHost boots the backend beside the first base build", () => {
728
+ isolateEnv({ AKAN_PUBLIC_REPO_NAME: "repo", AKAN_PUBLIC_SERVE_DOMAIN: "localhost", AKAN_PUBLIC_ENV: "local" });
729
+
730
+ const building = async (boots: Boot[] = ["hold"]) => {
731
+ const dev = await devHost(boots);
732
+ const outcome = { error: null as unknown, settled: false };
733
+ const starting = dev.host.start().then(
734
+ () => void Object.assign(outcome, { settled: true }),
735
+ (error: unknown) => void Object.assign(outcome, { error, settled: true }),
736
+ );
737
+ return { dev, starting, outcome };
738
+ };
739
+ const artifactOf = (dev: DevHost) => path.join(dev.root, "apps/demo/.akan/artifact/base-artifact.json");
740
+ const quiet = () => Bun.sleep(60);
741
+
742
+ test("starts the backend while the builder still builds, told to hold its web surface for the artifact", async () => {
743
+ const { dev, starting, outcome } = await building();
744
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
745
+ expect(dev.backend().awaitsArtifact).toBe(true);
746
+ expect(outcome.settled).toBe(false);
747
+
748
+ dev.builder().baseBuilt();
749
+ dev.builder().ready();
750
+ await starting;
751
+ readyBackend(dev);
752
+
753
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([[]]);
754
+ expect(dev.lastState()).toBe("ready");
755
+ });
756
+
757
+ test("a backend ready before the builder has its requests held, and gets its answers once the builder is ready", async () => {
758
+ const { dev, starting } = await building();
759
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
760
+ dev.builder().baseBuilt();
761
+ readyBackend(dev);
762
+ expect(dev.lastState()).toBe("ready");
763
+ dev.backend().say({ type: "build-graph", id: 7 });
764
+ await quiet();
765
+ expect(dev.builder().sent).toEqual([]);
766
+ expect(dev.backend().sent).toEqual([]);
767
+
768
+ dev.builder().ready();
769
+ await starting;
770
+
771
+ expect(sentOf(dev.builder().sent, "build-graph")).toHaveLength(1);
772
+ expect(dev.backends).toHaveLength(1);
773
+ });
774
+
775
+ test("a builder ready before the backend keeps what it built meanwhile, and the backend gets it at its ready", async () => {
776
+ const { dev, starting } = await building();
777
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
778
+ dev.builder().baseBuilt();
779
+ dev.builder().ready();
780
+ await starting;
781
+ dev.builder().toHost(pages(3));
782
+ dev.builder().toHost({ type: "build-status", data: status(3, false) });
783
+ await quiet();
784
+ expect(dev.backend().sent).toEqual([]);
785
+
786
+ readyBackend(dev);
787
+
788
+ expect(sentOf(dev.backend().sent, "pages-updated")).toEqual([pages(3)]);
789
+ expect(statusesOf(dev.backend().sent)).toContainEqual(status(3, false));
790
+ });
791
+
792
+ test("a save that restarts the backend during start-up replaces it with one that no longer waits", async () => {
793
+ const { dev, starting } = await building();
794
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
795
+ dev.builder().baseBuilt();
796
+ dev.builder().ready();
797
+ await starting;
798
+
799
+ dev.builder().toHost(invalidate(2, ["restart-backend"]));
800
+
801
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
802
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"], []]);
803
+ expect(dev.backend().awaitsArtifact).toBe(false);
804
+ });
805
+
806
+ test("a boot build that wrote no artifact gets a backend that serves the API without waiting for one", async () => {
807
+ const { dev, starting } = await building();
808
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
809
+
810
+ dev.builder().ready();
811
+ await starting;
812
+
813
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"], []]);
814
+ expect(dev.backends.map((backend) => backend.awaitsArtifact)).toEqual([true, false]);
815
+ });
816
+
817
+ test("a builder that never comes up takes the waiting backend down with the failed start", async () => {
818
+ const { dev, starting, outcome } = await building(["hold", "exit", "exit"]);
819
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
820
+
821
+ dev.builder().exit();
822
+ await starting;
823
+
824
+ expect(outcome.error).toBeInstanceOf(Error);
825
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"]]);
826
+ await quiet();
827
+ expect(dev.backends).toHaveLength(1);
828
+ });
829
+
830
+ test("a backend that dies while the builder builds comes back still waiting for the artifact", async () => {
831
+ const { dev, starting } = await building();
832
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
833
+
834
+ dev.backend().crash();
835
+
836
+ expect(await until(() => dev.backends.length === 2, (backendRecoveryPolicy.min ?? 0) + 2_000)).toBe(true);
837
+ expect(dev.backend().awaitsArtifact).toBe(true);
838
+ dev.builder().baseBuilt();
839
+ dev.builder().ready();
840
+ await starting;
841
+ expect(dev.backends).toHaveLength(2);
842
+ expect(dev.backend().signals).toEqual([]);
843
+ });
844
+
845
+ test("a builder retried inside one start restarts a backend that booted on the artifact the first try wrote", async () => {
846
+ const { dev, starting } = await building();
847
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
848
+ dev.builder().baseBuilt();
849
+
850
+ dev.builder().baseBuilt();
851
+
852
+ expect(await until(() => dev.backends.length === 2)).toBe(true);
853
+ expect(dev.backends.map((backend) => backend.awaitsArtifact)).toEqual([true, false]);
854
+ dev.builder().ready();
855
+ await starting;
856
+ });
857
+
858
+ test("a stop during start-up signals the waiting backend once, stops the builder, and starts nothing after", async () => {
859
+ const { dev, starting, outcome } = await building();
860
+ expect(await until(() => dev.backends.length === 1)).toBe(true);
861
+
862
+ await dev.host.stop();
863
+ await starting;
864
+
865
+ expect(outcome.error).toBeInstanceOf(Error);
866
+ expect(dev.backends.map((backend) => backend.signals)).toEqual([["SIGTERM"]]);
867
+ expect(dev.builder().stopped).toBeGreaterThanOrEqual(1);
868
+ await quiet();
869
+ expect(dev.backends).toHaveLength(1);
870
+ });
871
+
872
+ test("a stop before the backend was spawned never spawns it", async () => {
873
+ const { dev, starting } = await building();
874
+
875
+ await dev.host.stop();
876
+ await starting;
877
+ await quiet();
878
+
879
+ expect(dev.backends).toEqual([]);
880
+ });
881
+
882
+ test("an artifact already on disk keeps the backend behind the builder, so it never boots on the old one", async () => {
883
+ const dev = await devHost(["hold"]);
884
+ await writeText(artifactOf(dev), "{}\n");
885
+ const starting = dev.host.start();
886
+ expect(await until(() => dev.builders.length === 1)).toBe(true);
887
+ await quiet();
888
+ expect(dev.backends).toEqual([]);
889
+
890
+ dev.builder().ready();
891
+ await starting;
892
+
893
+ expect(dev.backends).toHaveLength(1);
894
+ expect(dev.backend().awaitsArtifact).toBe(false);
895
+ });
896
+ });
897
+
694
898
  describe("AkanAppHost on a fake clock", () => {
695
899
  isolateEnv({
696
900
  AKAN_PUBLIC_REPO_NAME: "repo",
@@ -30,6 +30,7 @@ interface DevBackendLinks {
30
30
  isStopping: () => boolean;
31
31
  emit: (state: DevHostState, detail?: string) => void;
32
32
  beforeSpawn: () => void;
33
+ awaitsArtifact: () => boolean;
33
34
  toBuilder: (message: BuilderMessage) => void;
34
35
  }
35
36
 
@@ -129,7 +130,8 @@ export class DevBackend {
129
130
  const backend = Bun.spawn(["bun", `apps/${this.#app.name}/main.ts`], {
130
131
  cwd: this.#app.workspace.workspaceRoot,
131
132
  stdio: this.#stdio === "pipe" ? ["ignore", "pipe", "pipe"] : ["inherit", "inherit", "inherit"],
132
- env: this.#env,
133
+ //? The first base build is still running: the backend boots beside it and holds its web surface for the artifact.
134
+ env: this.#links.awaitsArtifact() ? { ...this.#env, AKAN_DEV_AWAIT_ARTIFACT: "1" } : this.#env,
133
135
  ipc: (msg: BuilderMessage) => {
134
136
  if (!msg || typeof msg !== "object") return;
135
137
  if (msg.type === "backend-ready") {
@@ -17,6 +17,7 @@ interface DevBuilderLinks {
17
17
  onMessage: (message: BuilderMessage) => void;
18
18
  onAway: () => void;
19
19
  onReady: () => void;
20
+ onBaseBuilt: (phaseMs: Record<string, number>) => void;
20
21
  onRestartReady: () => void;
21
22
  onStartFailed: () => void;
22
23
  onStop: () => void;
@@ -81,7 +82,7 @@ export class DevBuilder {
81
82
  this.#host = builder;
82
83
  try {
83
84
  await this.#waitForReady(attempt, { announceBootState });
84
- this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms — starting backend`);
85
+ this.#app.verbose(`[cli] base build ready in ${Date.now() - startTime}ms`);
85
86
  return this.#host;
86
87
  } catch (err) {
87
88
  lastError = err;
@@ -187,6 +188,9 @@ export class DevBuilder {
187
188
  settle(resolve);
188
189
  this.#links.onReady();
189
190
  },
191
+ onBaseBuilt: (phaseMs) => {
192
+ this.#links.onBaseBuilt(phaseMs);
193
+ },
190
194
  onRestartReady: () => {
191
195
  this.#links.onRestartReady();
192
196
  },