@akanjs/devkit 3.2.0-rc.17 → 3.2.0-rc.19

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 (82) hide show
  1. package/CHANGELOG.md +74 -5
  2. package/DEV_RUNTIME_KNOBS.md +4 -3
  3. package/akanApp/akanApp.host.test.ts +18 -2
  4. package/akanApp/akanApp.host.wiring.test.ts +723 -0
  5. package/akanApp/devIdleSuspend.test.ts +107 -20
  6. package/akanApp/devIdleSuspend.ts +31 -14
  7. package/akanApp/devIdleSuspend.watcher.test.ts +77 -0
  8. package/apiReport/apiReport.test.ts +29 -0
  9. package/apiReport/apiReportDiff.ts +35 -1
  10. package/app/applicationBuildReporter.ts +2 -49
  11. package/app/routeSourceValidator.test.ts +17 -0
  12. package/app/routeSourceValidator.ts +5 -1
  13. package/artifact/implicitRootLayout.test.ts +67 -3
  14. package/artifact/implicitRootLayout.ts +9 -4
  15. package/artifact/implicitRootLayoutRender.test.tsx +297 -0
  16. package/codeAgent/agent/akanSystemPrompt.ts +1 -1
  17. package/codeAgent/skills/akan-scaffold/SKILL.md +1 -1
  18. package/commandDecorators/command.ts +2 -1
  19. package/commandDecorators/commandBuilder.ts +1 -1
  20. package/commandDecorators/commandDecorators.test.ts +28 -4
  21. package/context/akanContext.ts +20 -527
  22. package/context/akanContextInspection.ts +296 -0
  23. package/context/akanMcpContract.ts +13 -253
  24. package/context/doctor/agentGuideCheck.ts +81 -0
  25. package/context/doctor/configLeftoverCheck.ts +35 -0
  26. package/context/doctor/doctorFindings.ts +70 -0
  27. package/context/doctor/generatedFreshness.ts +56 -0
  28. package/context/doctor/moduleShapeCheck.ts +88 -0
  29. package/context/doctor/recipeDuplicateCheck.ts +39 -0
  30. package/context/doctor/recipeIndexCheck.ts +87 -0
  31. package/context/doctor/rootShapeCheck.ts +55 -0
  32. package/context/doctor/workflowScope.ts +97 -0
  33. package/context/safeRead.ts +9 -0
  34. package/devkitUtils.test.ts +34 -0
  35. package/executors/executors.test.ts +28 -4
  36. package/executors/workspaceExecutor.ts +1 -2
  37. package/frontendBuild/devGeneratedIndexSync.ts +5 -36
  38. package/frontendBuild/hmrWatcher.stop.test.ts +36 -0
  39. package/frontendBuild/hmrWatcher.ts +2 -0
  40. package/frontendBuild/optionalPeers.test.ts +35 -7
  41. package/incrementalBuilder/buildBatch.proc.ts +13 -3
  42. package/incrementalBuilder/buildBatchProtocol.ts +2 -0
  43. package/incrementalBuilder/buildBatchRunner.test.ts +61 -0
  44. package/incrementalBuilder/buildBatchRunner.ts +6 -3
  45. package/incrementalBuilder/builderBoot.ts +106 -0
  46. package/incrementalBuilder/builderBuildStatus.ts +23 -0
  47. package/incrementalBuilder/builderChannel.ts +11 -0
  48. package/incrementalBuilder/builderLanes.ts +157 -0
  49. package/incrementalBuilder/builderWatch.ts +213 -0
  50. package/incrementalBuilder/csrRegistry.ts +234 -0
  51. package/incrementalBuilder/incrementalBuilder.proc.test.ts +92 -1
  52. package/incrementalBuilder/incrementalBuilder.proc.ts +80 -822
  53. package/incrementalBuilder/ssrRegistry.ts +278 -0
  54. package/integration/devStability.integration.test.ts +62 -56
  55. package/package.json +3 -3
  56. package/test/testHelpers.ts +36 -0
  57. package/util/errorReport.ts +66 -0
  58. package/workflow/constantSource.ts +187 -0
  59. package/workflow/dictionarySource.ts +184 -0
  60. package/workflow/executor.ts +5 -8
  61. package/workflow/fieldExpression.ts +153 -0
  62. package/workflow/fieldLabel.ts +61 -0
  63. package/workflow/fieldOrder.ts +117 -0
  64. package/workflow/fieldType.ts +2 -1
  65. package/workflow/keyRename.ts +1 -1
  66. package/workflow/moduleIndex.ts +1 -1
  67. package/workflow/modulePaths.ts +27 -0
  68. package/workflow/mutationScaffold.ts +7 -15
  69. package/workflow/mutationSource.ts +2 -1
  70. package/workflow/plan.ts +2 -1
  71. package/workflow/primitiveReport.ts +78 -0
  72. package/workflow/serviceSource.ts +33 -0
  73. package/workflow/signalSource.ts +96 -0
  74. package/workflow/source.ts +50 -1100
  75. package/workflow/sourceAst.ts +30 -0
  76. package/workflow/sourceImports.ts +105 -0
  77. package/workflow/sourceText.ts +13 -0
  78. package/workflow/templateSource.ts +30 -0
  79. package/workflow/testSource.ts +31 -0
  80. package/workflow/types.ts +1 -1
  81. package/workflow/uiPolicy.ts +1 -1
  82. package/workspace/workspaceLayout.ts +3 -1
@@ -199,8 +199,9 @@ async function writeGeneratedRootLayoutFile(opts: {
199
199
  ? await UserLayout({ params, searchParams, children })
200
200
  : ${userLayoutElement};
201
201
  `
202
- : "";
203
- const layoutChild = isAsyncUserLayout ? "{layout}" : userLayoutElement;
202
+ : opts.includeSystemProvider
203
+ ? ` const layout = ${userLayoutElement};\n`
204
+ : "";
204
205
  const layoutReturn = isAsyncUserLayout ? "layout" : userLayoutElement;
205
206
  //? Under an ancestor root boundary the route tree merges that root's head itself; merging it here would repeat it.
206
207
  const headLayouts = opts.includeSystemProvider ? "[inheritedLayout, userLayout]" : "[userLayout]";
@@ -225,12 +226,16 @@ ${layoutSignature}({ children, params, searchParams }: LayoutProps) {
225
226
  ${layoutBinding} return `;
226
227
  //? System from its file, not the barrel: a dev registry compiles every module the barrel names, and with them the
227
228
  //? optional peers (react-icons) an app drawing none of those components never installs.
229
+ //? The root level's boundary sits inside System.Provider, beside the bridge that starts the router its retry calls.
230
+ //? A CSR render has none: RenderLayer draws a failed level there, and a route control also carries a digest.
231
+ //? Its export is undefined there too, so the `import * as root` of an MCP App view, built as CSR, drops it.
228
232
  const source = opts.includeSystemProvider
229
233
  ? `import type { LayoutModule, LayoutProps, PageProps } from "akanjs/client";
230
234
  import { assertGuardOnChain, loadFonts, RouteGuards, resolveRouteModule, RouteHead } from "akanjs/client";
231
235
  import type { ReactNode } from "react";
232
236
  import { System } from "${ROOT_LAYOUT_SYSTEM.specifier}";
233
237
  import type { McpAppRootProps } from "akanjs/webkit";
238
+ import { RouteLevelBoundary } from "akanjs/webkit/RouteLevelBoundary.tsx";
234
239
  import { env } from "@apps/${opts.appName}/env/env.client";
235
240
  import { allDictionary } from ${JSON.stringify(dictMacroSpecifier)};
236
241
  ${storeImport}${inheritedImport}${userImport}
@@ -242,7 +247,7 @@ const defaultFontClassName = defaultFont ? (defaultFont.className ?? \`font-\${d
242
247
  export const theme = userLayout.theme ?? inheritedLayout.theme;
243
248
  export const viewport = userLayout.viewport ?? inheritedLayout.viewport;
244
249
  export const manifest = userLayout.manifest ?? inheritedLayout.manifest;
245
- export { RouteLevelBoundary as LevelBoundary } from "akanjs/webkit/RouteLevelBoundary.tsx";
250
+ export const LevelBoundary = process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? undefined : RouteLevelBoundary;
246
251
 
247
252
  ${layoutExports}(
248
253
  <System.Provider
@@ -260,7 +265,7 @@ ${layoutExports}(
260
265
  wsConnect={userLayout.wsConnect ?? inheritedLayout.wsConnect}
261
266
  allDictionary={process.env.AKAN_PUBLIC_RENDER_ENV === "ssr" ? allDictionary : undefined}
262
267
  >
263
- ${layoutChild}
268
+ {process.env.AKAN_PUBLIC_RENDER_ENV === "csr" ? layout : <RouteLevelBoundary>{layout}</RouteLevelBoundary>}
264
269
  </System.Provider>
265
270
  );
266
271
  }
@@ -0,0 +1,297 @@
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
+ import { mkdir, readdir, rm, symlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { Readable } from "node:stream";
5
+ import { act, Children, createElement, Fragment, isValidElement, type ReactElement, type ReactNode } from "react";
6
+ import { renderToReadableStream } from "react-dom/server.edge";
7
+ import { createFromNodeStream } from "react-server-dom-webpack/client.node";
8
+ import { PagesBundleBuilder } from "../frontendBuild/pagesBundleBuilder";
9
+ import { tempDirs, writeText as write } from "../test/testHelpers";
10
+ import { resolveSsrPageEntries } from "./implicitRootLayout";
11
+
12
+ Object.assign(process.env, {
13
+ AKAN_PUBLIC_APP_NAME: "demo",
14
+ AKAN_PUBLIC_REPO_NAME: "demo",
15
+ AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
16
+ AKAN_PUBLIC_ENV: "testing",
17
+ AKAN_PUBLIC_OPERATION_MODE: "cloud",
18
+ });
19
+ const akanjsRoot = path.resolve(import.meta.dir, "../../../akanjs");
20
+ process.env.AKAN_RSC_WORKER_PATH = path.join(akanjsRoot, "server/rscWorker.tsx");
21
+ const { RscWorker } = await import("akanjs/server/rscWorkerHost.ts");
22
+ const { SsrFromRscRenderer } = await import("akanjs/server/ssrFromRscRenderer.tsx");
23
+ const { resetEnvCache } = await import("akanjs/base");
24
+ const { Logger } = await import("akanjs/common");
25
+ const { makePageProto, registerClientRuntime, router } = await import("akanjs/client");
26
+ //? What the app's client bundle registers in a browser; the hydrated System.Provider reads it.
27
+ const socket = { connect: () => undefined, connectOnUse: () => undefined };
28
+ registerClientRuntime({ ...makePageProto({ en: {} }), fetch: { instance: socket } } as never);
29
+
30
+ const makeTempRoot = tempDirs("akan-root-level-render-");
31
+ const boundedLayout = "<RouteLevelBoundary>{layout}</RouteLevelBoundary>";
32
+ const pageSource = 'import { page } from "akanjs/client";\nexport default page().render(() => <p>page</p>);\n';
33
+ const idsLayoutSource = `import { rootLayout } from "akanjs/client";
34
+ import { UsesId } from "../usesId";
35
+ export default rootLayout().render(({ children }) => <section id="user"><UsesId />{children}</section>);
36
+ `;
37
+ //? Throws only once the test has read the shell's body, so the boundary streams pending whatever the payload's size.
38
+ const lateLayoutSource = `import { rootLayout } from "akanjs/client";
39
+ export default rootLayout()
40
+ .loading(() => <i>root loading</i>)
41
+ .render(async () => {
42
+ while (!(await Bun.file(process.env.AKAN_TEST_SHELL_READ ?? "").exists())) await Bun.sleep(5);
43
+ throw new Error("root layout broke");
44
+ });
45
+ `;
46
+
47
+ const linkPackage = async (root: string, name: string, dir: string) => {
48
+ await mkdir(path.dirname(path.join(root, "node_modules", name)), { recursive: true });
49
+ await symlink(dir, path.join(root, "node_modules", name));
50
+ };
51
+
52
+ const writeApp = async (routes: Record<string, string>) => {
53
+ const root = await makeTempRoot();
54
+ const appDir = path.join(root, "apps/demo");
55
+ await linkPackage(root, "akanjs", akanjsRoot);
56
+ for (const name of ["react", "react-dom", "react-server-dom-webpack"])
57
+ await linkPackage(root, name, path.dirname(Bun.resolveSync(`${name}/package.json`, akanjsRoot)));
58
+ await write(
59
+ path.join(root, "tsconfig.json"),
60
+ JSON.stringify({ compilerOptions: { paths: { "@apps/*": ["./apps/*"] } } }),
61
+ );
62
+ await write(path.join(appDir, "env/env.client.ts"), "export const env = {};\n");
63
+ await write(path.join(appDir, "lib/dict.ts"), "export const getAllDictionary = () => ({});\n");
64
+ //? With lib/st.ts present the generated layout imports both, and the worker's System.Provider reads this runtime.
65
+ await write(
66
+ path.join(appDir, "lib/useClient.ts"),
67
+ 'import { makePageProto, registerClientRuntime } from "akanjs/client";\nregisterClientRuntime(makePageProto({}) as never);\n',
68
+ );
69
+ await write(path.join(appDir, "lib/st.ts"), "export {};\n");
70
+ await write(
71
+ path.join(appDir, "page/usesId.tsx"),
72
+ '"use client";\nimport { useId } from "react";\nexport const UsesId = () => <b id={useId()}>uses id</b>;\n',
73
+ );
74
+ for (const [file, source] of Object.entries(routes)) await write(path.join(appDir, "page", file), source);
75
+ return { root, appDir, pageKeys: Object.keys(routes).map((file) => `./${file}`) };
76
+ };
77
+
78
+ //? Each client reference's stub names its workspace-relative path in the error it throws when called on the server.
79
+ const clientReferenceIds = async (serverDir: string) => {
80
+ const ids = new Set<string>();
81
+ for (const file of await readdir(serverDir, { recursive: true })) {
82
+ if (!file.endsWith(".js")) continue;
83
+ const source = await Bun.file(path.join(serverDir, file)).text();
84
+ for (const [, id] of source.matchAll(/Attempted to call '[^']+' from '([^']+)' on the server/g))
85
+ if (id) ids.add(id);
86
+ }
87
+ return [...ids];
88
+ };
89
+
90
+ const ssrManifest: { moduleLoading: null; moduleMap: Record<string, unknown> } = { moduleLoading: null, moduleMap: {} };
91
+
92
+ const readHtml = async (stream: ReadableStream<Uint8Array>, onBody: () => Promise<unknown>) => {
93
+ const reader = stream.getReader();
94
+ const decoder = new TextDecoder();
95
+ let html = "";
96
+ let bodyRead = false;
97
+ for (;;) {
98
+ const { value, done } = await reader.read();
99
+ if (done) return html + decoder.decode();
100
+ html += decoder.decode(value, { stream: true });
101
+ if (bodyRead || !html.includes("<body")) continue;
102
+ bodyRead = true;
103
+ await onBody();
104
+ }
105
+ };
106
+
107
+ interface Rendered {
108
+ html: string;
109
+ status: number;
110
+ payload: Uint8Array;
111
+ }
112
+
113
+ const withBuiltPages = async (
114
+ { routes, unbounded }: { routes: Record<string, string>; unbounded?: string },
115
+ run: (render: (route: string) => Promise<Rendered>) => Promise<void>,
116
+ ) => {
117
+ const { root, appDir, pageKeys } = await writeApp(routes);
118
+ const app = {
119
+ name: "demo",
120
+ cwdPath: appDir,
121
+ dist: { cwdPath: path.join(root, "dist/apps/demo") },
122
+ workspace: { workspaceRoot: root },
123
+ getConfig: async () => ({ basePaths: [], barrelImports: [], externalLibs: [] }),
124
+ getTsConfig: async () => ({ compilerOptions: { paths: { "@apps/*": ["./apps/*"] } } }),
125
+ getPublicEnv: () => ({}),
126
+ verbose: () => undefined,
127
+ };
128
+ const entries = await resolveSsrPageEntries({ appCwdPath: appDir, appName: "demo", pageKeys });
129
+ if (unbounded) {
130
+ const generated = entries.find((entry) => entry.key === `./${unbounded}/__root_layout.tsx`);
131
+ if (!generated) throw new Error(`no generated root layout for ${unbounded}`);
132
+ const source = await Bun.file(generated.moduleAbsPath).text();
133
+ expect(source).toContain(boundedLayout);
134
+ await Bun.write(generated.moduleAbsPath, source.replace(boundedLayout, "layout"));
135
+ }
136
+ const { bundlePath } = await new PagesBundleBuilder(app as never, "build", entries).build();
137
+ const ids = await clientReferenceIds(path.dirname(bundlePath));
138
+ ssrManifest.moduleMap = Object.fromEntries(
139
+ ids.map((id) => {
140
+ const file = path.resolve(root, id);
141
+ return [id, { "*": { id: file, chunks: [file, file], name: "*" } }];
142
+ }),
143
+ );
144
+ const shellRead = path.join(root, "shell-read");
145
+ process.env.AKAN_TEST_SHELL_READ = shellRead;
146
+ const rsc = new RscWorker({
147
+ pagesBundlePath: bundlePath,
148
+ pagesBundleBuildId: 1,
149
+ rscRuntimeClientManifest: Object.fromEntries(ids.map((id) => [id, { id, chunks: [], name: "" }])),
150
+ } as never);
151
+ try {
152
+ await rsc.ready;
153
+ await run(async (route) => {
154
+ const request = new Request(`http://localhost/en/${route}`);
155
+ const result = await rsc.renderWithMeta(request);
156
+ if (result.type !== "stream") throw new Error(`expected a rendered page, got ${result.type}`);
157
+ const [rscStream, payloadStream] = result.stream.tee();
158
+ const payload = new Response(payloadStream).arrayBuffer();
159
+ payload.catch(() => undefined);
160
+ const stream = await new SsrFromRscRenderer().render({
161
+ request,
162
+ rscStream,
163
+ ssrManifest,
164
+ lateControl: result.lateControl,
165
+ } as never);
166
+ const html = await readHtml(stream, () => Bun.write(shellRead, ""));
167
+ await rm(shellRead, { force: true });
168
+ return { html, status: result.status ?? 200, payload: new Uint8Array(await payload) };
169
+ });
170
+ } finally {
171
+ rsc.kill();
172
+ delete process.env.AKAN_TEST_SHELL_READ;
173
+ }
174
+ };
175
+
176
+ const bodyOf = async (payload: Uint8Array): Promise<ReactNode> => {
177
+ const html = await createFromNodeStream<ReactElement<{ children: ReactNode }>>(
178
+ Readable.from([payload]),
179
+ ssrManifest as never,
180
+ );
181
+ const body = Children.toArray(html.props.children).find(
182
+ (child): child is ReactElement<{ children: ReactNode }> => isValidElement(child) && child.type === "body",
183
+ );
184
+ return createElement(Fragment, null, body?.props.children);
185
+ };
186
+
187
+ const markupOf = async (node: ReactNode) => {
188
+ const stream = await renderToReadableStream(node, { onError: () => undefined });
189
+ await stream.allReady;
190
+ return await new Response(stream).text();
191
+ };
192
+
193
+ const hydrated = async (
194
+ payload: Uint8Array,
195
+ keptSelectors: string[],
196
+ run: (container: HTMLElement, uncaught: unknown[], recoverable: unknown[]) => void | Promise<void>,
197
+ ) => {
198
+ const markup = await markupOf(await bodyOf(payload));
199
+ const { GlobalRegistrator } = await import("@happy-dom/global-registrator");
200
+ GlobalRegistrator.register({ url: "http://localhost/en/" });
201
+ //? getEnv() caches its side, and the SSR render above ran with no window.
202
+ resetEnvCache();
203
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
204
+ const { hydrateRoot } = await import("react-dom/client");
205
+ const container = document.createElement("div");
206
+ container.innerHTML = markup;
207
+ document.body.appendChild(container);
208
+ const uncaught: unknown[] = [];
209
+ const recoverable: unknown[] = [];
210
+ const kept = keptSelectors.map((selector) => [selector, container.querySelector(selector)] as const);
211
+ //? React's dev check tags a context with the last renderer to provide it, and Fizz rendered these in this process.
212
+ const logged = console.error;
213
+ const quiet = spyOn(console, "error").mockImplementation((...args: unknown[]) => {
214
+ if (!String(args[0]).startsWith("Detected multiple renderers concurrently")) logged(...args);
215
+ });
216
+ let root: ReturnType<typeof hydrateRoot> | undefined;
217
+ try {
218
+ const tree = await bodyOf(payload);
219
+ await act(async () => {
220
+ root = hydrateRoot(container, tree, {
221
+ onUncaughtError: (error) => void uncaught.push(error),
222
+ onCaughtError: () => undefined,
223
+ onRecoverableError: (error) => void recoverable.push(error),
224
+ });
225
+ });
226
+ await act(async () => {});
227
+ for (const [selector, node] of kept) expect(container.querySelector(selector)).toBe(node);
228
+ await run(container, uncaught, recoverable);
229
+ } finally {
230
+ await act(async () => {
231
+ root?.unmount();
232
+ });
233
+ quiet.mockRestore();
234
+ await GlobalRegistrator.unregister();
235
+ resetEnvCache();
236
+ }
237
+ };
238
+
239
+ const withLoggedErrors = async (run: () => Promise<void>) => {
240
+ const logged = spyOn(Logger.prototype, "error").mockImplementation(() => undefined);
241
+ try {
242
+ await run();
243
+ } finally {
244
+ logged.mockRestore();
245
+ }
246
+ };
247
+
248
+ describe("The generated System root layout, built and rendered", () => {
249
+ test("draws a late root failure's notice inside System.Provider, whose bridge started the router its retry calls", async () => {
250
+ const refreshes: string[] = [];
251
+ globalThis.__AKAN_RSC_REFRESH__ = async () => void refreshes.push("refresh");
252
+ try {
253
+ await withLoggedErrors(async () => {
254
+ const routes = { "(late)/_layout.tsx": lateLayoutSource, "(late)/late.tsx": pageSource };
255
+ await withBuiltPages({ routes }, async (render) => {
256
+ const late = await render("late");
257
+ expect(late.status).toBe(200);
258
+ expect(late.html).toContain('<body><!--$?--><template id="B:0"></template><i>root loading</i><!--/$-->');
259
+ expect(late.html).toContain('$RX("B:0"');
260
+
261
+ //? Only the hydrated ClientSsrBridge can start it: the server's own init ran in the worker.
262
+ expect(router.isInitialized).toBe(false);
263
+ await hydrated(late.payload, [], async (container, uncaught) => {
264
+ expect(uncaught).toEqual([]);
265
+ const notice = container.querySelector("#pageContent > [role='alert']");
266
+ expect(notice).not.toBeNull();
267
+ await act(async () => notice?.querySelector("button")?.click());
268
+ expect(refreshes).toEqual(["refresh"]);
269
+ });
270
+ });
271
+ });
272
+ } finally {
273
+ globalThis.__AKAN_RSC_REFRESH__ = undefined;
274
+ }
275
+ }, 30_000);
276
+
277
+ test("keeps the markup and useId values the template had without the boundary, and hydrates them in place", async () => {
278
+ const routes = {
279
+ "(ids)/_layout.tsx": idsLayoutSource,
280
+ "(ids)/ids.tsx": pageSource,
281
+ "(bare)/_layout.tsx": idsLayoutSource,
282
+ "(bare)/bar.tsx": pageSource,
283
+ };
284
+ await withBuiltPages({ routes, unbounded: "(bare)" }, async (render) => {
285
+ const beforeScripts = (html: string) => html.slice(html.indexOf("<body>"), html.indexOf("<script"));
286
+ const bounded = await render("ids");
287
+ const bare = beforeScripts((await render("bar")).html);
288
+ expect(beforeScripts(bounded.html)).toContain('<section id="user"><b id="_R_');
289
+ expect(beforeScripts(bounded.html).replace('data-firstpath="ids"', 'data-firstpath="bar"')).toBe(bare);
290
+
291
+ await hydrated(bounded.payload, ["#pageContent", "#user", "#user b"], (container, uncaught, recoverable) => {
292
+ expect(container.querySelector("#user b")?.id).toStartWith("_R_");
293
+ expect({ uncaught, recoverable }).toEqual({ uncaught: [], recoverable: [] });
294
+ });
295
+ });
296
+ }, 30_000);
297
+ });
@@ -41,7 +41,7 @@ export const akanSystemPrompt = (profile: CodeAgentProfile) => {
41
41
  "## How to answer",
42
42
  "",
43
43
  "- Answer in as few words as carry the answer. A short question gets one sentence with no heading.",
44
- "- Do not open with what you are about to do, and do not close with a summary of what you did. The tool calls are already on the user's screen.",
44
+ "- Do not open with what you are about to do, and do not retell the tool calls at the end; they are already on the user's screen. A turn that changed files closes with those files and what `akan_verify` said.",
45
45
  "- Skip headings, bold labels and bullet lists unless the answer is genuinely a list. Prose is shorter.",
46
46
  "- State a file as `path:line`. Do not paste a file back that the user can open.",
47
47
  "- Say what you could not do, and why, in one line. Do not offer alternatives nobody asked for.",
@@ -16,7 +16,7 @@ Everything else is pages, sections, and props.
16
16
  - A page or section whose content you can write as static JSX or props is not an entity. "A self-intro page
17
17
  with two detail pages" is pages only — no `profile` module.
18
18
  - Never invent a supporting entity (profile, category, tag, author, like) to round out a design. If one looks
19
- genuinely necessary, say so in your reply and let the user decide.
19
+ genuinely necessary, build the request without it and say in your reply why it may be needed; the user decides.
20
20
  - "… plus a comment zone that saves to a database" is exactly one new module: `comment`.
21
21
  - Check what exists first (`list_modules`) and extend it when it already fits — `add-field` / `add-slice` /
22
22
  `create-ui` beat a whole new module.
@@ -17,6 +17,7 @@ import {
17
17
  type SysExecutor,
18
18
  WorkspaceExecutor,
19
19
  } from "../executors";
20
+ import { ErrorReport } from "../util/errorReport";
20
21
  // Never the root barrel: it drags ink, ssh2 and the cloud stack into every command process.
21
22
  import { FileSys, getDirname } from "../util/fileSys";
22
23
  import { AppSelectionMemory } from "../workspace/appSelectionMemory";
@@ -57,7 +58,7 @@ const printCliError = (error: unknown, stream: "log" | "error" = "log") => {
57
58
  if (loggedCliErrorObjects.has(error)) return;
58
59
  loggedCliErrorObjects.add(error);
59
60
  }
60
- const message = CliError.messageOf(error);
61
+ const message = error instanceof Error ? ErrorReport.format(error) || error.name : CliError.messageOf(error);
61
62
  if (loggedCliErrorMessages.has(message)) return;
62
63
  loggedCliErrorMessages.add(message);
63
64
  Logger.rawLog(`\n${chalk.red(message)}`, undefined, stream);
@@ -137,7 +137,7 @@ class TargetBuilder<Deps extends readonly DependencyCls[], Params extends unknow
137
137
  }
138
138
 
139
139
  type TargetDefinition = ReturnType<TargetBuilder<readonly DependencyCls[], unknown[]>["exec"]>;
140
- type CommandBuilderContext<Deps extends readonly DependencyCls[]> = {
140
+ export type CommandBuilderContext<Deps extends readonly DependencyCls[]> = {
141
141
  public: (targetOption?: Omit<TargetOption, "type">) => TargetBuilder<Deps>;
142
142
  cloud: (targetOption?: Omit<TargetOption, "type">) => TargetBuilder<Deps>;
143
143
  dev: (targetOption?: Omit<TargetOption, "type">) => TargetBuilder<Deps>;
@@ -440,7 +440,6 @@ describe("enum arg type inference", () => {
440
440
 
441
441
  describe("a Sys that defaults to the only app", () => {
442
442
  const ownIsTTY = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");
443
- const ownCwd = process.cwd();
444
443
  const asked: unknown[] = [];
445
444
  let answer = "";
446
445
  const setTTY = (isTTY: boolean | undefined) =>
@@ -456,7 +455,6 @@ describe("a Sys that defaults to the only app", () => {
456
455
  });
457
456
  afterEach(() => {
458
457
  CommandContainer.clear();
459
- process.chdir(ownCwd);
460
458
  if (ownIsTTY) Object.defineProperty(process.stdin, "isTTY", ownIsTTY);
461
459
  else Reflect.deleteProperty(process.stdin, "isTTY");
462
460
  });
@@ -479,10 +477,8 @@ describe("a Sys that defaults to the only app", () => {
479
477
  return meta;
480
478
  };
481
479
  const track = tempRoots();
482
- //? From the workspace root, as the CLI runs: getDirInModule stats its entries relative to the process directory.
483
480
  const moduleWorkspace = async () => {
484
481
  const { root, workspace } = track(await makeCliTempWorkspace());
485
- process.chdir(root);
486
482
  for (const [sys, name] of [
487
483
  ["apps/web", "card"],
488
484
  ["libs/util", "photo"],
@@ -926,6 +922,34 @@ describe("the exit code of a command that failed", () => {
926
922
  expect(rejected.code).toBe(2);
927
923
  }, 60_000);
928
924
 
925
+ test("ends with each reason an aggregate holds, where a bundler log names its file and line", async () => {
926
+ const graphFailure = [
927
+ "await (async () => {",
928
+ ' await Bun.write("graph/server.ts", \'import { env } from "./env.server.debug";\\nexport default env;\\n\');',
929
+ ' const result = await Bun.build({ entrypoints: ["graph/server.ts"], target: "bun", throw: false });',
930
+ ' return new AggregateError(result.logs, "[licenseNotices] server graph failed");',
931
+ "})()",
932
+ ].join("\n");
933
+ const reason = ' Could not resolve: "./env.server.debug" (graph/server.ts:1:21)';
934
+ const json = ' }).option("json", Boolean, { default: false';
935
+ const [text, asJson] = await Promise.all([
936
+ run(graphFailure),
937
+ run(graphFailure, { option: json, args: ["--json"] }),
938
+ ]);
939
+ expect(text.code).toBe(1);
940
+ expect(stripAnsi(text.stdout).trimEnd().split("\n").slice(-2)).toEqual([
941
+ "[licenseNotices] server graph failed",
942
+ reason,
943
+ ]);
944
+ expect(asJson.code).toBe(1);
945
+ expect(JSON.parse(asJson.stdout)).toEqual({
946
+ ok: false,
947
+ error: "[licenseNotices] server graph failed",
948
+ code: "failed",
949
+ });
950
+ expect(stripAnsi(asJson.stderr).trimEnd().split("\n").at(-1)).toBe(reason);
951
+ }, 30_000);
952
+
929
953
  test("prints nothing more for an error the command marked as printed", async () => {
930
954
  const marked = await run(
931
955
  '(() => { const error = new Error("printed already"); markCliErrorPrinted(error); return error; })()',