@akanjs/devkit 3.3.0-rc.1 → 3.3.0-rc.10

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 (85) hide show
  1. package/CHANGELOG.md +229 -2
  2. package/README.ko.md +3 -2
  3. package/README.md +3 -3
  4. package/akanApp/akanApp.host.test.ts +22 -5
  5. package/akanApp/akanApp.host.ts +46 -9
  6. package/akanApp/akanApp.host.wiring.test.ts +206 -2
  7. package/akanApp/devBackend.ts +3 -1
  8. package/akanApp/devBuilder.ts +5 -1
  9. package/akanApp/devStartTimeline.test.ts +115 -0
  10. package/akanApp/devStartTimeline.ts +69 -0
  11. package/akanConfig/akanConfig.test.ts +57 -8
  12. package/akanConfig/akanConfig.ts +12 -65
  13. package/akanConfig/dockerImage.ts +17 -0
  14. package/akanConfig/nativeKeys.ts +52 -0
  15. package/app/applicationBuildRunner.test.ts +49 -1
  16. package/app/applicationBuildRunner.ts +3 -1
  17. package/codeAgent/agent/CodeAgent.ts +36 -16
  18. package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
  19. package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
  20. package/codeAgent/agent/CodeAgentGate.ts +23 -4
  21. package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
  22. package/codeAgent/agent/codeAgent.test.ts +62 -0
  23. package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
  24. package/codeAgent/agent/codeAgentContract.test.ts +117 -5
  25. package/codeAgent/skills/akan-agent/SKILL.md +8 -1
  26. package/codeAgent/skills/akan-code/SKILL.md +38 -3
  27. package/codeAgent/skills/akan-page/SKILL.md +18 -13
  28. package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
  29. package/codeAgent/skills/akan-service/SKILL.md +2 -2
  30. package/docs/apiReference.test.ts +5 -0
  31. package/docs/apiReference.ts +7 -3
  32. package/docs/declarationReader.ts +28 -1
  33. package/executors/appExecutor.ts +35 -11
  34. package/executors/executors.test.ts +30 -3
  35. package/frontendBuild/buildCacheStamp.test.ts +42 -0
  36. package/frontendBuild/buildCacheStamp.ts +23 -0
  37. package/frontendBuild/buildRouteClient.test.ts +2 -7
  38. package/frontendBuild/clientEntryDiscovery.ts +2 -2
  39. package/frontendBuild/cssCandidateCache.test.ts +70 -1
  40. package/frontendBuild/cssCandidateCache.ts +17 -10
  41. package/frontendBuild/cssCompiler.test.ts +112 -0
  42. package/frontendBuild/cssCompiler.ts +41 -21
  43. package/frontendBuild/devBarrelImports.test.ts +30 -0
  44. package/frontendBuild/devBarrelImports.ts +2 -2
  45. package/frontendBuild/fontOptimizer.test.ts +144 -3
  46. package/frontendBuild/fontOptimizer.ts +103 -18
  47. package/frontendBuild/pagesBundleBuilder.ts +3 -1
  48. package/frontendBuild/plainStylesheet.test.ts +155 -0
  49. package/frontendBuild/plainStylesheet.ts +197 -0
  50. package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
  51. package/frontendBuild/rscServerRendererGuard.ts +68 -0
  52. package/frontendBuild/ssrBaseArtifactBuilder.test.ts +30 -1
  53. package/frontendBuild/ssrBaseArtifactBuilder.ts +40 -12
  54. package/guideline/agentAssets.test.ts +10 -0
  55. package/guideline/agentAssets.ts +52 -11
  56. package/incrementalBuilder/buildBatch.proc.ts +11 -10
  57. package/incrementalBuilder/buildBatchProtocol.ts +2 -1
  58. package/incrementalBuilder/builderBoot.ts +14 -7
  59. package/incrementalBuilder/builderChannel.ts +8 -2
  60. package/incrementalBuilder/builderGraphPayloads.ts +4 -4
  61. package/incrementalBuilder/builderLanes.ts +2 -2
  62. package/incrementalBuilder/builderWatch.ts +8 -8
  63. package/incrementalBuilder/csrRegistry.ts +4 -4
  64. package/incrementalBuilder/incrementalBuilder.host.test.ts +16 -0
  65. package/incrementalBuilder/incrementalBuilder.host.ts +7 -1
  66. package/incrementalBuilder/incrementalBuilder.proc.test.ts +41 -0
  67. package/incrementalBuilder/incrementalBuilder.proc.ts +9 -8
  68. package/incrementalBuilder/ssrRegistry.ts +6 -6
  69. package/index.ts +1 -1
  70. package/integration/renderAdmissionSoak.test.ts +99 -0
  71. package/integration/renderAdmissionSoak.ts +609 -0
  72. package/mobile/nativeConfig.test.ts +100 -0
  73. package/mobile/nativeConfig.ts +55 -16
  74. package/mobile/nativePublicEnv.ts +2 -1
  75. package/package.json +14 -169
  76. package/packageExports.test.ts +38 -24
  77. package/transforms/barrelAnalyzer.ts +2 -2
  78. package/transforms/transforms.test.ts +3 -3
  79. package/tunnel/createTunnel.test.ts +29 -8
  80. package/tunnel/createTunnel.ts +18 -11
  81. package/util/fileEditor.ts +1 -0
  82. package/util/fileSys.test.ts +13 -0
  83. package/util/fileSys.ts +2 -2
  84. package/util/selectModel.ts +1 -0
  85. package/workspace/getRelatedCnsts.ts +7 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,234 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
+ - 217b061: `akan code` on the default `local` profile now asks before it runs a shell command, as it already did before reaching an unlisted host. File reads, writes and edits are not asked about.
8
+
9
+ **Upgrading.** An interactive `akan code` session shows `approve? run: <command> [y/n/a]` before each shell command; `a` answers yes and stops asking about that command until the session ends. Pass `--no-ask-commands` to run them unasked as before, or `--no-ask` to stop the network questions as well. A one-shot `akan code "<prompt>"` and a sub-agent have nobody to ask, so their commands run as before. A program that drives `akan code --rpc` on the `local` profile receives an `approval` event for each command and answers it with `approve`, as it does for the `web` profile's writes; `codeAgentPresets.local(root).approval` is now `"commands"`.
10
+
11
+ - e704d16: The Dockerfile `akan build` writes runs the server as oven/bun's `bun` user (uid 1000) on a base image pinned by digest, and the Helm chart in `infra/app` runs the pod as that user with no privilege escalation and holds the Ingress to the app's own body limit and CORS answer.
12
+
13
+ **Image**
14
+
15
+ - The base is `oven/bun:1.4.4-slim@sha256:…`, the multi-arch index's digest, so every build of a release, amd64 and arm64 alike, starts from the same Bun the workspace pins. A test fails when the image tag and the repo's Bun version disagree.
16
+ - `apt-get`, `preRuns`, `bun install` and `postRuns` still run as root, and the app files, `node_modules` included, stay root's and read-only to the server. uid 1000 owns only the directories the server writes: `/workspace/sqlite`, `/workspace/local`, `/workspace/runtime` (the control socket), `/workspace/data` and `/workspace/.akan/artifact/image-cache`. An empty named volume mounted at `/workspace/sqlite` or `/workspace/local` starts out owned by uid 1000.
17
+
18
+ **Chart** (`infra/app`, not an npm package; its defaults now live in `infra/app/values.yaml`)
19
+
20
+ - `podSecurityContext`: `runAsNonRoot: true`, uid and gid 1000, `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and seccomp `RuntimeDefault`.
21
+ - `securityContext` (the container's): `allowPrivilegeEscalation: false` and every capability dropped. `readOnlyRootFilesystem` stays off, because the server writes `/workspace/runtime`, `/workspace/.akan`, `/workspace/data` and `/tmp` inside the image.
22
+ - A values file replaces single keys of either, and `null` on a key drops that key. A block that is left out or `null`, as in a release upgraded with `helm upgrade --reuse-values` from values that predate it, renders these defaults; so do the `ingress` keys below.
23
+ - `volumePermissions.enabled: true`: in single mode, an init container from the app's own image runs as root with only `CHOWN`, `FOWNER` and `DAC_READ_SEARCH` before the app starts, and hands every file on the `sqlite-data` claim that another uid or gid owns to `podSecurityContext`'s `runAsUser:runAsGroup`. Once ownership is right it changes nothing. Cluster mode has no such claim, and a `sharedClaim` is not touched.
24
+ - `ingress.proxyBodySize: 128m`: the Ingress passes a body up to the server's upload limit (`AKAN_MAX_UPLOAD_BODY`, 128 MiB) and answers a larger one 413 itself, as the server would.
25
+ - `ingress.cors.enabled: false`: the app's own CORS answer reaches the browser. Its native shells and the origins in `option.setCrossSite({ allowedOrigins })` get their origin back, a preflight gets every header it asked for (`idempotency-key` and the MCP headers included), and fonts keep `Access-Control-Allow-Origin: *`. Nothing else carries it, since `allowedOrigins` covers `/api` only.
26
+
27
+ **Upgrading.**
28
+
29
+ - A Docker volume or bind mount that an image of 3.2.0 or earlier already wrote is owned by root, so the new image stops at boot with `directoryNotWritable`, which names the directory, its owner and the `chown` that fixes it. Change its owner once, for example `docker run --rm -u 0 -v <volume>:/workspace/sqlite <image> chown -R 1000:1000 /workspace/sqlite`, and the same for a volume at `/workspace/local`. A new named volume mounted anywhere else, such as `/data`, starts out owned by root: mount it at `/workspace/sqlite` or `/workspace/local`, or `chown` it once the same way. To keep running as root, start the container with `--user 0:0` (compose: `user: "0:0"`), or declare `docker` as a whole Dockerfile string.
30
+ - A directory a `postRuns` step creates for the server to write needs `chown 1000:1000` in that step.
31
+ - On the chart, the `volumePermissions` init container hands the `sqlite-data` claim a root image wrote to uid 1000 at the first start, hostPath, NFS and CSI volumes the kubelet's `fsGroup` skips included. A cluster's `sharedClaim` needs the one-time `chown -R 1000:1000`. An image without `sh` and `find` needs `volumePermissions: { enabled: false }`.
32
+ - The chart runs the pod as uid 1000, so it needs an image whose server can run as that user. An image built with akanjs 3.2 or earlier (a rollback to one through `image.tag` included), a declared `docker` Dockerfile string that runs the server as root, or a custom `docker.image` whose files uid 1000 cannot read, needs these lines in the app's values file, which run the pod as root as before:
33
+
34
+ ```yaml
35
+ podSecurityContext: { runAsUser: 0, runAsGroup: 0, runAsNonRoot: false }
36
+ securityContext: { capabilities: null }
37
+ volumePermissions: { enabled: false }
38
+ ```
39
+
40
+ - A request body over 128 MiB, which the server refused after the Ingress read it, now gets 413 from the Ingress. An app that raised `AKAN_MAX_UPLOAD_BODY` raises `ingress.proxyBodySize` with it; `ingress.proxyBodySize: "0"` passes any size again.
41
+ - The Ingress no longer answers a preflight itself or adds `Access-Control-Allow-Origin: *` to every response. A page on an origin the app does not list could read the app's GET responses through that header, and now cannot: add its origin to `option.setCrossSite({ allowedOrigins })`, or write `ingress: { cors: { enabled: true } }` in the app's values file for the old annotations. `allowedOrigins` covers `/api` only: a page on another origin that `fetch`es a public file, such as a JSON file under `public/`, or draws an `/_akan/image` response onto a canvas, now fails, since only fonts keep `Access-Control-Allow-Origin: *`; for those, `ingress: { cors: { enabled: true } }` is the remedy.
42
+
43
+ - aff1ba2: An external view opens only origins the app's config lists, in `native.desktop.externalView.allowOrigins`: a view's own `allowOrigins` narrow within them, and an origin outside them is `NOT_ALLOWED`, naming that key. `evaluate` and `initScript` need their own permission, granted by `desktop.externalView.evaluate: true`, and `sendKey` its own, granted by `desktop.externalView.sendKey: true`; both are off by default. While a view is open, opening its id again keeps its origins or narrows them, and refuses one it was not opened for; once closed, the id opens again for any origins the config lists, with the same browser profile, which belongs to the id. Origins compare exactly as the URL parser reads them: scheme, host and port, the host in punycode without a trailing dot, the default port left out, and an origin with user info refused; there are no wildcards. A view loads a URL as the URL parser writes it, so the engine never reads the page's text another way. A page opens a view only over its own window. The desktop shell checks all of this itself on macOS, Windows and Linux, and grants nothing when the build carries no permission list; on Windows a view now takes only the two DevTools calls `sendKey` and `capture` make. A top-level navigation or redirect off a view's origins stays refused, as before.
44
+
45
+ A plugin manifest's `scope` can say `required: true`: then every grant of the plugin, not only `<plugin>:default`, is within its `defaultScope` unless the grant gives its own `allow`, and a scope entry naming no field is a build error. `external-view` says so.
46
+
47
+ **Upgrading.** An app that lists `external-view` opens no view until its `akan.config.ts` names the origins, and needs `evaluate` and `sendKey` only for the calls it makes:
48
+
49
+ ```ts
50
+ native: {
51
+ plugins: ["external-view"],
52
+ desktop: {
53
+ externalView: {
54
+ allowOrigins: ["https://board.example"], // every origin a view's allowOrigins names
55
+ evaluate: true, // when it calls evaluate or opens with initScript
56
+ sendKey: true, // when it calls sendKey
57
+ },
58
+ },
59
+ },
60
+ ```
61
+
62
+ An app built with the akan-native CLI's own config grants the same in its capabilities: `{ identifier: "external-view:default", allow: [{ origin: "https://board.example" }] }`, `"external-view:allow-evaluate"` and `"external-view:allow-sendKey"`. A grant of `external-view:all` or `external-view:allow-open` opens no origin unless its own `allow` lists them. A page that passed `window` to `open` passes its own window or leaves it out.
63
+
64
+ - 8d75f2b: The public surface 3.2.0 deprecated is removed. `akanjs` and `@akanjs/devkit` publish only the subpaths their `exports` name, with no wildcard, so a file becomes public only when an entry names it.
65
+
66
+ - **`@akanjs/devkit` has no root aliases and no `./*` or `./*.ts`.** It publishes `@akanjs/devkit` (types only), `biome.base.json`, the facets `akanApp`, `akanConfig`, `artifact`, `cloud`, `codeAgent`, `commandDecorators`, `executors`, `frontendBuild`, `incrementalBuilder`, `mobile`, `pipeline`, `preview`, `transforms` and `workflow`, and the files `app/applicationBuildRunner`, `cloud/cloudApi`, `cloud/cloudUpdates`, `commandDecorators/exitCodeError`, `mobile/desktopRelease`, `mobile/serverBundleSecrets` and `transforms/serverEnvProfile`. `util/fileEditor`, `util/selectModel` and `workspace/getRelatedCnsts` are named too, and deprecated: nothing in akanjs uses them.
67
+ - **`akanjs` drops `akanjs/common/*`, `akanjs/server/*`, `akanjs/ui/*`, `akanjs/webkit/*` and `akanjs/client/native/*`.** Every `akanjs/client/native/<plugin>` path still resolves, now as its own entry, and so does `akanjs/webkit/usePurchase`. The layouts `akan` generates import `akanjs/ui/System/index.tsx`, `akanjs/ui/System/SSR.tsx`, `akanjs/ui/UiOverride/UiOverride.tsx` and `akanjs/webkit/RouteLevelBoundary.tsx`, and the `akan` command's bundled `@akanjs/language` imports `akanjs/common/akanNames.ts`, `akanjs/common/facetBarrel.ts` and `akanjs/common/routeConvention.ts`: these stay as named entries. `@akanjs/language`'s declarations now import their types from `akanjs/common`. Barrel imports in an installed workspace's build now resolve to files on disk instead of package subpaths.
68
+ - **The error-constructor plumbing is gone**: `setErrorConstructor` on `FetchClient`, `HttpClient` and `WsClient`, `HttpClientOptions.ErrorCls`, and `FetchClient.build`'s `Err` option. Every restored error is `akanjs/common`'s `Err`, as it already was. `registerClientRuntime` no longer re-points the shared client at the runtime's `Err`.
69
+ - **Thirteen deprecated exports are deleted, and eleven internals are no longer exported.**
70
+
71
+ **Upgrading.**
72
+
73
+ - `@akanjs/devkit/<name>` and `@akanjs/devkit/<name>.ts`, for 81 root names, and `@akanjs/devkit/executors.ts` (`@akanjs/devkit/executors` stays, as a facet):
74
+ - `applicationBuildRunner` → `@akanjs/devkit/app/applicationBuildRunner`, `fileEditor` → `@akanjs/devkit/util/fileEditor`, `selectModel` → `@akanjs/devkit/util/selectModel` and `getRelatedCnsts` → `@akanjs/devkit/workspace/getRelatedCnsts` (the last three are deprecated).
75
+ - Import the types of `akanContext`, `akanMcpContract`, `applicationBuildReporter`, `applicationTestPreload`, `createTunnel`, `dependencyScanner`, `fileSys`, `maintainabilityContract`, `packageExportsMap`, `prompter`, `qualityScanner`, `recipeScanner`, `scanInfo`, `spinner`, `stripAnsi`, `typeChecker` and `types` from `@akanjs/devkit`. Their values have no public entry.
76
+ - `abstractDoc`, `agentAssets`, `agentsIndex`, `akanMcpToolError`, `apiReference`, `appSelectionMemory`, `bareErrorScanner`, `biomeBase`, `codegenLock`, `commentDensityScanner`, `componentSizeScanner`, `componentWriteChainScanner`, `conventionSet`, `declarationReader`, `deprecatedCommentScanner`, `endpointReach`, `envSeed`, `errorCodeReference`, `errorCodeScan`, `formSetterScanner`, `frameworkGraph`, `gitRevision`, `jsonFormatter`, `kindBranchScanner`, `libSource`, `linter`, `maintainabilityBaseline`, `maintainabilityExceptionScanner`, `maintainabilityLimits`, `maintainabilityReport`, `manifestDependencies`, `moduleFieldNames`, `renderMutationScanner`, `repoIdentity`, `routeJsBudget`, `routeSourceValidator`, `semver`, `serviceLoopCallScanner`, `shellOnlyEnv`, `signalMutationIndex`, `slicePlanner`, `sourceComments`, `sshHostKeys`, `sshTunnel`, `ssrScanner`, `storeAccessScanner`, `storeSource`, `storeWriteScanner`, `structureScanner`, `subspace`, `subspaceClone`, `subspaceConfig`, `subspaceReport`, `testHelpers`, `testOnlyExportScanner`, `workspaceGraph`, `workspaceLayout`, `writePath`, `writePlacementScanner` and `writingActionIndex` have no replacement: they are the `akan` command's internals, which its build inlines.
77
+ - Any other `@akanjs/devkit/<dir>/<file>` that only `./*` reached: import its types from `@akanjs/devkit` where that barrel exports them; it is otherwise internal, with no replacement.
78
+ - `akanjs/<common|server|ui|webkit>/<file>`: import from the barrel, `akanjs/common`, `akanjs/server`, `akanjs/ui` or `akanjs/webkit` (`akanjs/server/machine/machineToken` → `akanjs/server`; `akanjs/ui/Constant/schemaDoc` → `akanjs/ui`), or from a named entry such as `akanjs/server/tunnel` for `akanjs/server/tunnel/index.ts`. A file no barrel re-exports is internal, `SignalResolver` and `akanjs/ui/Agent/RichInput` included, with no replacement: check which routes an endpoint serves with a signal test (`akan test <app>`) rather than through `SignalResolver.resolveEndpoint`. These 28 were public only through a wildcard and are internal now: `isIndexable`; `DEFAULT_HTML_CONTENT_SECURITY_POLICY`, `htmlContentSecurityPolicy`, `DEFAULT_STRICT_TRANSPORT_SECURITY`, `CONTENT_ENCODINGS`, `topologicalStages`, `traceCycle`, `getSystemPageErrorDetails`, `SYSTEM_PAGE_STYLE`, `getSameOriginHref`, `carriesCredentials`, `DEFAULT_ROUTE_CACHE_TTL_SECONDS`, `isAkanRouterStateV1`, `countCommonRouteSegments`, `AKAN_RSC_STATE_VERSION`, `decodeAkanRedirectDigest` and `validateRscSegmentPatch` (server); `getKeyboardAccessorySlots`, `blurActiveElement`, `KEYBOARD_SHOW_ANIMATION_DURATION_MS`, `KEYBOARD_HIDE_ANIMATION_DURATION_MS`, `KEYBOARD_SHOW_ANIMATION_EASING`, `KEYBOARD_HIDE_ANIMATION_EASING` and `clonePageState` (webkit); `DefaultPagination`, `DefaultTable`, `DefaultUnauthorized` and `isPublicEndpoint` (ui).
79
+ - `fetch.setErrorConstructor(Err)` in an older `lib/sig.ts`, and `{ Err: pageProto.Err }` passed to `FetchClient.build` in an older `lib/useClient.ts`: run `akan sync`, which rewrites both. Elsewhere, drop the `setErrorConstructor` call, the `ErrorCls` option and the `Err` option. A `FetchClient` constructed with its own error class still restores its WebSocket, bridge, refusal and abort errors into it, but an HTTP response error is always `Err`.
80
+ - `MAX_INT` → `2 ** 31 - 1`. `isFilterModel(ref)` → `getFilterMeta(ref, { allowEmpty: true }) !== undefined`. `setFilterInfoByKey` → declare the query with `from(model, (filter) => …)`. `getDefaultSchemaOptions()` → `new DocumentSchema()`. `runWithTrace` → `runTraced`, only where the caller owns the trace, since it finalizes it. `traceDbQuery(ms)` → `getCurrentTrace()?.countDbQuery(ms)`. `isSitemapPath(pathname, basePaths)` → `getSitemapBasePath(pathname, basePaths, headerBasePath) !== undefined`. `useRscNavigation` → `navigateRsc`, `clearRscNavigationCache` and `isRscNavigationFromCache`. `getSearchParam` and `getBaseSearchParam` → read `searchParams[key]`, taking the first value of an array. `dictionaryContext`, `groupByOwner` and `ServiceRegistry` have no replacement.
81
+ - No longer exported, with no replacement: `setFilterMeta` and `getFilterArgInfo` (`akanjs/document`), `isDebugHeaderAllowed` (`akanjs/signal`), `parseAkanConsoleQuery`, `createAkanConsoleLogCommands` and `createAkanConsoleContext` (`akanjs/server`), `isResponsiveInset`, `getClientRuntime`, `colorTokens` and `radiusTokens` (`akanjs/client`), and `isStateBuilderMarker` (`akanjs/store`).
82
+
83
+ ### Patch Changes
84
+
85
+ - 4a568b2: What an agent turn carries beside the conversation reaches the model as marked data in a user turn, outside the system prompt.
86
+
87
+ - **A turn's `context` is no longer written into the system prompt.** `OpenaiDialect` and `AnthropicLlm` send it as a `<turn-context …>` block that ends the turn's last user-role content, after that turn's tool results: a text block on the Messages API, and on the chat-completions wire the end of the user message the turn closes on, or a user message of its own after tool messages. The block closes on a delimiter chosen so that its content cannot contain it, in any case or width or with characters that do not show between its letters. The delimiter is keyed with a secret of the process: the same text gets the same one in every request a process sends, and another process gives it another. The system prompt is the instructions alone, so it is the same text on every turn of a conversation and a provider's prefix cache keeps it.
88
+ - **A compaction summary is history in a user turn on both dialects.** It is sent as a `<conversation-summary …>` block. The chat-completions dialect used to send it with the system role, and the Messages API mapping with no fence. When the user's message follows the summary, the block opens that message, so neither dialect sends two user turns in a row.
89
+ - **`LlmContext`** (`akanjs/service`) is what an adaptor of the app's own calls: `LlmContext.of(request.context)` is the context text, empty when there is none, and `LlmContext.summary(text)` the summary block.
90
+ - **A context block can be marked `untrusted: true`** (`AgentWireContext`, and `ContextBlock` in the page) when it holds text someone other than the developer or the user may have written. Both dialects fence marked blocks apart from the app's own, in a `<page-content …>` block, the one a `readScreen` result arrives in. A turn that carries one counts as an untrusted read. In the page the first change after it asks the user first, as after `readScreen`. In `agentService.loop` the run is tainted from its first round: `approve` hears `tainted: true`, and with no `approve` a write is answered with the code `writeAfterPageText` and a sentence for the model, and the loop logs once per run that `approve` is what decides such a call. The run stores `tainted: true` on each assistant message it writes while tainted, so a resume and the next ask in that conversation keep the taint when the block is not passed again.
91
+ - **Text from a mentioned record is treated like text a tool read.** An `@` mention's reference reaches the model with its pointer, label, value and note together in one `<page-content …>` block under the "Referenced data" heading; before, only the value was fenced. The token in the user's message is sent as `@[pointer](mention:pointer)`, so the record's title is in that block only; the chat still draws the title. When the id or the path is not a token, as a slug is not, the token is sent as `@[ref-1a2b3c4d](mention:ref-1a2b3c4d)` and the block spells the pointer under that name. A message that carries a reference counts as an untrusted read: in `Agent.Chat` the first change after it shows the approval card a change after `readScreen` shows, and an `agentService.loop` run whose messages carry `references` is tainted from its first round. A loop's compaction digest names a pointed-at record by its pointer.
92
+ - **The page's default context keeps ids, enum members, numbers and booleans inline, and leaves free text to a read tool.**
93
+ - A string rides inline only when it is one token: up to 40 letters, digits, `.`, `_` or `-`, of at most three words. A word ends at a separator or at a lower-to-upper case change, so `created-at-desc` and `createdAtDesc` pass and `archive-every-note-now` does not. More parts pass only as an id's: each hex, with a digit or eight characters long, as in a UUID. A run of over sixteen letters with no digit never passes. It used to ride inline up to 200 characters.
94
+ - In the `state` block any other string is listed by key and type with no value.
95
+ - The `route` block applies the rule to each path segment and path param, and keeps at most twelve words of each. A search param rides inline when a store declares its key with `search("key", …)` and its value is a token. Of the others at most four ride, key and value both tokens, so `?tab=settings&page=2&sort=created-at-desc` reads the same on a page whose stores declare none; the rest are left out, key and value. A page's typed `search` is read on the server and does not count as a declaration. What is left out reads `…` in the path, the block names the keys to read in `withheld` and the number of search params left out in `searchParamsWithheld`. `readState` answers `pathname`, `params` and `searchParams` whether or not a component subscribes them, as page content.
96
+ - In the `screen` block a `Load` scope's label, which is its record's title, and the ids and labels of a list scope's `items` follow the rule; the block then says to read the scope with `readScreen`.
97
+ - Not covered: an `Agent.Zone`'s `label` and a value published with `st.expose`, `st.useState` or `useAgentResource` still ride whole, as no read tool returns them. Publish an id or an enum member there, not text a user wrote.
98
+ - The MCP App view names its screen to the host by origin and path under the same rule, without the query string or the hash.
99
+ - `AgentService.preamble` and each adaptor's fallback prompt say what a `<turn-context …>` block is, and that a `<page-content …>` block may also end a user turn.
100
+ - The agent and MCP guidelines and the `akan-agent` skill describe all of the above.
101
+
102
+ **Upgrading.**
103
+
104
+ An `LlmAdaptor` of your own that builds its whole request with `OpenaiDialect.requestBody` or `AnthropicLlm.requestBody` needs no change. One that builds its own messages must change, also when it takes its system prompt from `OpenaiDialect.systemPrompt(request)` or `AnthropicLlm.systemPrompt(request)`: those now return the instructions without the context, so such an adaptor would send no context at all. Append the context to the last user-role content, and map a `summary` message to a user turn:
105
+
106
+ ```ts
107
+ // before
108
+ const system = OpenaiDialect.systemPrompt(request); // held the context
109
+ const turns = request.messages.map((message) =>
110
+ message.summary
111
+ ? { role: "system", content: message.text }
112
+ : toTurn(message)
113
+ );
114
+ // after
115
+ const system = OpenaiDialect.systemPrompt(request); // the instructions alone
116
+ const turns = request.messages.map((message) =>
117
+ message.summary
118
+ ? { role: "user", content: LlmContext.summary(message.text ?? "") }
119
+ : toTurn(message)
120
+ );
121
+ const context = LlmContext.of(request.context); // "" when the turn carries none
122
+ if (context) turns.push({ role: "user", content: context }); // or append it to the last user turn
123
+ ```
124
+
125
+ Marked blocks come fenced by the same call. A test that looked for a context value in `body.system`, or in the first chat-completions message, finds it in the last user-role content, and one that looked for a summary in a system message finds it in a user message.
126
+
127
+ A loop request or a page context that already used a field named `untrusted` on a block for something else must rename it: any value but `false` or `undefined` now marks the block.
128
+
129
+ A store for `agentService.loop` messages must keep `tainted` on assistant messages too. Store each message `onMessage` hands over whole, as before; a store that picks fields adds this one. A loop that passes user messages with `references` and has no `approve` no longer writes: each write is answered with the code `writeAfterPageText`. Pass `approve`, or send the message without `references`. This lasts for the rest of the conversation, not for one run, because the stored messages keep the reference; a marked context block lasts as long through the mark on what the model said. Passing `untrusted` does not lift it.
130
+
131
+ A loop that passes messages with `references` and has an `approve` hears `tainted: true` on every call from that message on, in that run and in every later ask of the conversation. An approver that allows untainted calls by itself and holds tainted ones for a person will hold them all.
132
+
133
+ In a loop the model reads a mention in the user's words as `@[ticket/t1](mention:ticket/t1)`, or as `@[ref-1a2b3c4d](mention:ref-1a2b3c4d)` when the id or path is not a token, and finds the title only in that message's "Referenced data" block. A compaction summary names a mentioned record by its pointer and no longer by its title, so after a compaction the model reads the record again to name it. A prompt or a test that expected the title in the user's text looks in the block.
134
+
135
+ An app that relied on the model seeing a search param, a path param, a short store string or a list row's title in its context now has the model read it with `readState` or `readScreen`. The model is told which to call, so most apps change nothing. To keep a search param in the context whatever else the link carries, declare it in a store (`search("status", String, { default: "" })`); an undeclared one rides only as one of the first four whose key and value are tokens.
136
+
137
+ An id that is not a token is left out like other free text: a slug of more than three words (`my-first-blog-post`) or a mixed-case random id such as a nanoid (`V1StGXR8_Z5jdHi6B-myT`). A list scope's `items` then lists the other rows only, a list whose ids are all such lists none, and the block's `note` says to call `readScreen` with the scope's path, where every row is. A live store key holding such an id is listed with no value. A 24-character hex id, a UUID, a ULID and a number ride as before.
138
+
139
+ The URL an MCP App view reports to its host as model context no longer has the query string or the hash, and a path segment of free text reads `…`. A host prompt or a test that read a search param from that URL gets it from a tool the view publishes.
140
+
141
+ Two cases need an edit. Instructions that point at the context point at the tool instead:
142
+
143
+ ```tsx
144
+ // before
145
+ <Agent.Chat instructions="The search box's text is searchParams.q in the route context." />
146
+ // after
147
+ <Agent.Chat instructions="The search box's text is the q search param: call readState with key searchParams." />
148
+ ```
149
+
150
+ And a chat or zone that withholds a read tool gives it back when its agent needs such a value:
151
+
152
+ ```tsx
153
+ // before
154
+ <Agent.Zone builtins={["highlight"]}>
155
+ // after
156
+ <Agent.Zone builtins={["highlight", "readState", "readScreen"]}>
157
+ ```
158
+
159
+ What `readState` and `readScreen` return is page content, so the first change after one asks the user first.
160
+
161
+ A chat where the user mentions a record now asks before the first change that follows. `AgentConfirm.set({ afterScreenRead: false })` turns that off together with the ask after `readScreen`.
162
+
163
+ - c44d068: A coding agent reads less to build its first app: the `akanjs` README keeps the path to a first app and links the rest on akanjs.com (17 KB to 7 KB), the `akan-page` and `akan-service` skills ship the API reference one section at a time with every entry named in the skill's index (`Link` now lists the anchor attributes it takes and `Link.Back`, `Link.Close` and `Link.Lang`), the `akan-page` skill holds what a first page looks up while `pageRule` keeps the deeper contract, and each rule is stated once across AGENTS.md, the path rules and the skills. Run `akan agent install` in a workspace to pick up the new files.
164
+ - 19c6fa7: `akan code` on the `local` profile can be told to stop asking about a command for the rest of the session, and one option turns asking off for a run.
165
+
166
+ - **A third answer.** The prompt before a shell command is now `approve? run: <command> [y/n/a]`. `a` runs the command and stops asking about it until the session ends. What is remembered is the program, and the sub-command too for `git`, `bun`, `bunx`, `npm`, `npx`, `pnpm`, `yarn`, `akan`, `docker`, `kubectl`, `helm`, `cargo` and `go`: allowing `git status` leaves `git diff` asked about, and allowing `bun test` leaves `bun x` asked about. `gh` is remembered two words deep, so allowing `gh pr view` leaves `gh pr merge` asked about. A line of several commands (`&&`, `;`, `|`, `$(…)`, a subshell) runs unasked only once every command in it is allowed. `/allowed` lists what the session has allowed and `/allowed clear` forgets it. Nothing is written to disk, so a resumed, forked or reloaded session asks again.
167
+ - **Still asked every time**, with a prompt that offers only `[y/n]`: a networking command (`curl`, `wget`, `nc`, `ssh`, `scp`, `rsync`, …) and a redirection to or from `/dev/tcp/…` or `/dev/udp/…`; a command that sends something out of the machine (`git push`, `npm publish`, `pnpm publish`, `yarn publish`, `yarn npm`, `bun publish`, `cargo publish`, `gh api`, and a `docker` line with `push` or `--push` in it); `rm`; a command that runs another or sets what a later one runs (`sudo`, `env`, `timeout`, `xargs`, `sh`, `bash`, `eval`, `builtin`, `source`, `.`, `trap`, `alias`, `export`, `declare`, `find -exec`, …); a variable set in front of a command other than `CI`, `NODE_ENV`, `FORCE_COLOR`, `NO_COLOR`, `TZ`, `LANG`, `LC_ALL`, `TERM`, `DEBUG` or `PORT` given one plain word; a line that writes a file with `>` or `>>`; and a line that cannot be split into its commands with confidence (a loop or `if`, backticks, a here-document, a program named by a variable).
168
+ - **`--no-ask`.** `akan code --no-ask` runs the session without asking before a shell command or a network request: the same as `--no-ask-commands --no-ask-network`. It prints one line at start saying so. It changes nothing else: secret files stay refused, this repo's MCP servers and extensions still wait for their own approval (`--trust-workspace`), the agent's own questions are still asked, and the `pod`, `review` and `web` profiles behave as before.
169
+
170
+ A program that drives `akan code --rpc` sees `remember: string[]` on an `approval` request when the session answer is offered, sends `{ "type": "approve", "approvalId": …, "approved": true, "remember": "session" }` to give it, and reads the names on `approval_resolved.remembered`. A host that sends only `approved` keeps working as before.
171
+
172
+ **Upgrading.** No step is needed: the three wire fields in `akanjs/common` (`CodeAgentApprovalRequest.remember`, the `approve` command's `remember`, `approval_resolved.remembered`) and `CodeTranscriptPart`'s `remembered` are optional additions.
173
+
174
+ - 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.
175
+ - 90d740f: `native.ios.hideFormAccessoryBar: true` (or a target's `ios.hideFormAccessoryBar`) leaves out the bar WebKit shows above the keyboard while a page field is focused. The iOS shell already had the switch, but `akan.config.ts` refused the key and the native config never carried it, so every iOS app showed the bar.
176
+
177
+ The key defaults to false, so existing apps are unchanged. The api report lists one new optional `AkanNativeIosConfig` property; no upgrade step is needed.
178
+
179
+ - 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.
180
+ - 6ea7242: `akan build`, `akan verify` and `akan start` stop with an error naming the import chain when the server pages bundle would import `react-dom/server` as it loads, instead of building a bundle whose RSC worker throws "react-dom/server is not supported in React Server Components" at boot. A module in the page graph that dynamically imports the app's `server.ts` is the usual cause: it brings the whole server, SSR renderer included, into the pages bundle.
181
+ - 0d5e75e: A stylesheet whose imports use no Tailwind (no `@import "tailwindcss"`, Tailwind at-rule or `theme()` function anywhere in its import graph) is no longer run through the Tailwind compiler: its imports are inlined and it ships without the `/*! tailwindcss … */` banner. A stylesheet that uses Tailwind compiles exactly as before.
182
+ - 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.
183
+
184
+ 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.
185
+
186
+ - 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.
187
+ - 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.
188
+ - 8bbe7c8: A Redis or Postgres tunnel to a cluster environment needs a configured credential: `SSH_TUNNEL_PRIVATE_KEY_PATH` (with `SSH_TUNNEL_PASSPHRASE` if the key has one), exported in the shell, or `SSH_TUNNEL_PASSWORD`. Without either, the tunnel fails before it dials, with an error naming both settings, instead of signing in with a built-in default credential and a warning. This removes an unsafe default. A key file the tunnel cannot read fails with an error naming the tunnel, `SSH_TUNNEL_PRIVATE_KEY_PATH` and the path.
189
+
190
+ **Upgrading.** If `akan start` against a cluster environment opened its tunnel with neither setting, it now stops with that error in every database mode but `single`, where it logs the error and runs without Redis. Export `SSH_TUNNEL_PRIVATE_KEY_PATH` in the shell (a repository's dotenv file cannot set it), or set `SSH_TUNNEL_PASSWORD` to the password the cluster's tunnel endpoint expects. `SSH_TUNNEL_USERNAME` still defaults to `root`.
191
+
192
+ - 694444d: `akan verify` writes its build check to `dist/verify/<app>` and leaves `dist/apps/<app>` as `akan build` left it, so running `akan verify` after `akan build` no longer stops `cd dist/apps/<app> && bun main.js` from starting. The check no longer copies the app's `public/` and `private/` folders either.
193
+ - Updated dependencies [4a568b2]
194
+ - Updated dependencies [c44d068]
195
+ - Updated dependencies [af09c4f]
196
+ - Updated dependencies [24315d1]
197
+ - Updated dependencies [19c6fa7]
198
+ - Updated dependencies [217b061]
199
+ - Updated dependencies [0baacae]
200
+ - Updated dependencies [e704d16]
201
+ - Updated dependencies [aff1ba2]
202
+ - Updated dependencies [bf582c1]
203
+ - Updated dependencies [8bbe7c8]
204
+ - Updated dependencies [90d740f]
205
+ - Updated dependencies [e9598f3]
206
+ - Updated dependencies [1885caf]
207
+ - Updated dependencies [45e3ffa]
208
+ - Updated dependencies [3032627]
209
+ - Updated dependencies [c10f7cf]
210
+ - Updated dependencies [c10f7cf]
211
+ - Updated dependencies [10641a0]
212
+ - Updated dependencies [045699c]
213
+ - Updated dependencies [5c7e083]
214
+ - Updated dependencies [4040f2d]
215
+ - Updated dependencies [9a7a9d5]
216
+ - Updated dependencies [8d75f2b]
217
+ - Updated dependencies [d5e60f2]
218
+ - Updated dependencies [aead1aa]
219
+ - Updated dependencies [4225827]
220
+ - Updated dependencies [4225827]
221
+ - Updated dependencies [fb5e77e]
222
+ - Updated dependencies [5c6d039]
223
+ - Updated dependencies [0492e0b]
224
+ - Updated dependencies [0492e0b]
225
+ - Updated dependencies [5c7e083]
226
+ - Updated dependencies [98931e4]
227
+ - Updated dependencies [4225827]
228
+ - akanjs@3.3.0
229
+ - @akanjs/language@3.3.0
230
+
231
+ ## 3.2.0
232
+
233
+ ### Minor Changes
234
+
7
235
  - 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.
8
236
 
9
237
  **Highlights**
@@ -67,8 +295,7 @@
67
295
  ### Patch Changes
68
296
 
69
297
  - Updated dependencies [038d918]
70
- - akanjs@3.3.0
71
- - @akanjs/language@3.3.0
298
+ - akanjs@3.2.0
72
299
 
73
300
  ## 3.1.1
74
301
 
package/README.ko.md CHANGED
@@ -39,8 +39,9 @@ await runner.build();
39
39
 
40
40
  값은 그것을 가진 facet에서 import합니다(`@akanjs/devkit/executors`, `@akanjs/devkit/akanConfig`,
41
41
  `@akanjs/devkit/workflow` 등). 루트 `@akanjs/devkit` 진입점은 타입만 내보내므로, 도구 하나를 불러도 모든 facet이
42
- 프로세스에 올라오지 않습니다. facet이 따로 없는 도구는 그 폴더에서 import합니다(`@akanjs/devkit/app/…`, `quality/`,
43
- `workspace/`, `util/` 등). 이 도구들이 패키지 루트에 있던 시절의 경로는 다음 minor 릴리스까지 계속 동작합니다.
42
+ 프로세스에 올라오지 않습니다. facet 외에는 `exports`가 이름을 붙인 몇몇 파일(`app/applicationBuildRunner`,
43
+ `cloud/cloudApi`, `mobile/desktopRelease` 등)만 공개되며, 그 밖의 파일은 `akan` 명령의 내부 구현이라 패키지 밖에서
44
+ resolve되지 않습니다.
44
45
 
45
46
  ## 제공하는 것
46
47
 
package/README.md CHANGED
@@ -38,9 +38,9 @@ await runner.build();
38
38
 
39
39
  Import values from the facet that owns them (`@akanjs/devkit/executors`, `@akanjs/devkit/akanConfig`,
40
40
  `@akanjs/devkit/workflow`, …). The root `@akanjs/devkit` entry exports types only, so loading a tool does not pull
41
- every facet into the process. A tool with no facet of its own is imported from its folder (`@akanjs/devkit/app/…`,
42
- `quality/`, `workspace/`, `util/`, …); the paths these tools had at the package root still resolve until the next
43
- minor release.
41
+ every facet into the process. Besides the facets, `exports` names a few files (`app/applicationBuildRunner`,
42
+ `cloud/cloudApi`, `mobile/desktopRelease`, …); any other file is internal to the `akan` command and does not resolve
43
+ from outside the package.
44
44
 
45
45
  ## What It Provides
46
46
 
@@ -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();
@@ -47,14 +52,17 @@ describe("Redis tunnels during dev startup", () => {
47
52
  const listener = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } });
48
53
  const port = listener.port;
49
54
  listener.stop(true);
50
- process.env.SSH_TUNNEL_PORT = String(port);
55
+ Object.assign(process.env, { SSH_TUNNEL_PORT: String(port), SSH_TUNNEL_PASSWORD: "test-password" });
51
56
  if (mode === "local") process.env.AKAN_PUBLIC_ENV = "local";
52
57
  const create = IncrementalBuilderHost.create;
53
58
  IncrementalBuilderHost.create = async () =>
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
  }