@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
@@ -0,0 +1,35 @@
1
+ import path from "node:path";
2
+ import type { WorkspaceExecutor } from "../../executors";
3
+ import type { AkanSysContext } from "../akanContext";
4
+ import { safeReadText } from "../safeRead";
5
+ import type { DoctorFindings } from "./doctorFindings";
6
+
7
+ export class ConfigLeftoverCheck {
8
+ static async run(workspace: WorkspaceExecutor, systems: AkanSysContext[], findings: DoctorFindings) {
9
+ const sysPaths = systems.map((sys) => sys.path);
10
+ for (const leftover of await ConfigLeftoverCheck.#leftovers(workspace, sysPaths))
11
+ findings.push({ severity: "warning", code: "config-leftover", ...leftover });
12
+ }
13
+
14
+ //? Older templates wrote these for Next.js: nothing installs or reads them, and editors warn about the plugin.
15
+ static async #leftovers(workspace: WorkspaceExecutor, sysPaths: string[]) {
16
+ const leftovers: { path: string; message: string }[] = [];
17
+ for (const sysPath of sysPaths) {
18
+ const tsconfigPath = `${sysPath}/tsconfig.json`;
19
+ const tsconfig = await safeReadText(path.join(workspace.workspaceRoot, tsconfigPath));
20
+ if (tsconfig && (/"name"\s*:\s*"next"/.test(tsconfig) || tsconfig.includes(".next/types")))
21
+ leftovers.push({
22
+ path: tsconfigPath,
23
+ message: `${tsconfigPath} still names the Next.js TS plugin or .next/types, which Akan never uses — delete the "next" plugin entry and the ".next/types/**/*.ts" include.`,
24
+ });
25
+ }
26
+ const bunfig = await safeReadText(path.join(workspace.workspaceRoot, "bunfig.toml"));
27
+ if (bunfig?.includes("bun-plugin-tailwind"))
28
+ leftovers.push({
29
+ path: "bunfig.toml",
30
+ message:
31
+ "bunfig.toml still loads bun-plugin-tailwind, which is not installed and which Akan never uses (it compiles Tailwind itself) — delete the [serve.static] section, which Akan never reads.",
32
+ });
33
+ return leftovers;
34
+ }
35
+ }
@@ -0,0 +1,70 @@
1
+ import type { WorkspaceExecutor } from "../../executors";
2
+ import type { RepairAction } from "../../workflow";
3
+ import type { AkanDiagnostic, AkanDoctorResult, AkanWorkspaceContext } from "../akanContext";
4
+ import { generatedFreshnessFromStates } from "./generatedFreshness";
5
+ import { isWorkflowRelatedDiagnostic } from "./workflowScope";
6
+
7
+ export const repairAction = (
8
+ kind: RepairAction["kind"],
9
+ command: string,
10
+ reason: string,
11
+ safeToRun: boolean,
12
+ ): RepairAction => ({
13
+ kind,
14
+ command,
15
+ reason,
16
+ safeToRun,
17
+ });
18
+
19
+ export class DoctorFindings {
20
+ readonly #diagnostics: AkanDiagnostic[] = [];
21
+ readonly #repairActions: RepairAction[] = [
22
+ repairAction("generated", "akan repair generated --app <app-or-lib>", "Refresh generated Akan files.", true),
23
+ repairAction(
24
+ "format",
25
+ "akan repair format --target <app-or-lib-or-pkg>",
26
+ "Run the formatter/linter repair path.",
27
+ true,
28
+ ),
29
+ ];
30
+
31
+ report(diagnostic: AkanDiagnostic, action: RepairAction) {
32
+ this.#diagnostics.push({ ...diagnostic, repairActions: [action] });
33
+ this.#repairActions.push(action);
34
+ }
35
+
36
+ push(diagnostic: AkanDiagnostic) {
37
+ this.#diagnostics.push(diagnostic);
38
+ }
39
+
40
+ async result(
41
+ workspace: WorkspaceExecutor,
42
+ context: AkanWorkspaceContext,
43
+ { strict, workflowPaths }: { strict: boolean; workflowPaths: string[] },
44
+ ): Promise<AkanDoctorResult> {
45
+ const scopedDiagnostics = this.#diagnostics.map((diagnostic) => ({
46
+ ...diagnostic,
47
+ scope: workflowPaths.length
48
+ ? isWorkflowRelatedDiagnostic(diagnostic, workflowPaths)
49
+ ? ("workflow" as const)
50
+ : ("baseline" as const)
51
+ : diagnostic.scope,
52
+ context: workflowPaths.length ? { ...diagnostic.context, paths: workflowPaths } : diagnostic.context,
53
+ }));
54
+ const workflowDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "workflow");
55
+ const baselineDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "baseline");
56
+ return {
57
+ schemaVersion: 1,
58
+ repoName: context.repoName,
59
+ root: context.root,
60
+ strict,
61
+ status: scopedDiagnostics.some((diagnostic) => diagnostic.severity === "error") ? "failed" : "passed",
62
+ diagnostics: scopedDiagnostics,
63
+ generatedFiles: context.generatedFiles,
64
+ generatedFilesFreshness: await generatedFreshnessFromStates(workspace),
65
+ validationCommands: context.validationCommands,
66
+ repairActions: this.#repairActions,
67
+ ...(workflowPaths.length ? { baselineDiagnostics, workflowDiagnostics } : {}),
68
+ };
69
+ }
70
+ }
@@ -0,0 +1,56 @@
1
+ import path from "node:path";
2
+ import type { WorkspaceExecutor } from "../../executors";
3
+ import { type GeneratedSyncState, workflowSyncDir } from "../../workflow";
4
+ import type { GeneratedFilesFreshness } from "../akanContext";
5
+ import { safeReadDir, safeReadJson } from "../safeRead";
6
+
7
+ const unknownGeneratedFilesFreshness: GeneratedFilesFreshness = {
8
+ status: "unknown" as const,
9
+ message: "Run sync before validation so generated Akan files match the current source conventions.",
10
+ refreshCommand: "akan sync <app-or-lib>",
11
+ verifyingCommands: ["akan verify <app-or-lib>"],
12
+ };
13
+
14
+ const readGeneratedSyncStates = async (workspace: WorkspaceExecutor) => {
15
+ const syncDir = path.join(workspace.workspaceRoot, workflowSyncDir);
16
+ const entries = await safeReadDir(syncDir);
17
+ const states = await Promise.all(
18
+ entries
19
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
20
+ .map((entry) => safeReadJson<GeneratedSyncState>(path.join(syncDir, entry.name))),
21
+ );
22
+ return states.filter(
23
+ (state): state is GeneratedSyncState =>
24
+ !!state && state.schemaVersion === 1 && typeof state.target === "string" && typeof state.syncedAt === "string",
25
+ );
26
+ };
27
+
28
+ export const generatedFreshnessFromStates = async (workspace: WorkspaceExecutor): Promise<GeneratedFilesFreshness> => {
29
+ const states = await readGeneratedSyncStates(workspace);
30
+ if (states.length === 0) return unknownGeneratedFilesFreshness;
31
+ const targets = states
32
+ .sort((a, b) => a.target.localeCompare(b.target))
33
+ .map((state) => ({
34
+ target: state.target,
35
+ status: state.status === "passed" ? ("fresh" as const) : ("stale" as const),
36
+ lastSyncedAt: state.syncedAt,
37
+ runId: state.runId,
38
+ generatedFiles: state.generatedFiles.map((file) => file.path),
39
+ reason:
40
+ state.status === "passed"
41
+ ? `Generated files were refreshed by ${state.command}.`
42
+ : `Last generated repair command failed: ${state.command}.`,
43
+ }));
44
+ const lastFresh = targets
45
+ .filter((target) => target.status === "fresh" && target.lastSyncedAt)
46
+ .sort((a, b) => (b.lastSyncedAt ?? "").localeCompare(a.lastSyncedAt ?? ""))[0];
47
+ return {
48
+ status: targets.some((target) => target.status === "fresh") ? "fresh" : "stale",
49
+ message: lastFresh
50
+ ? `Generated files were refreshed for ${lastFresh.target} at ${lastFresh.lastSyncedAt}.`
51
+ : "Generated sync state exists, but the last recorded repair did not pass.",
52
+ refreshCommand: "akan sync <app-or-lib>",
53
+ verifyingCommands: ["akan verify <app-or-lib>"],
54
+ targets,
55
+ };
56
+ };
@@ -0,0 +1,88 @@
1
+ import path from "node:path";
2
+ import { capitalize } from "akanjs/common";
3
+ import type { WorkspaceExecutor } from "../../executors";
4
+ import type { AkanModuleContext, AkanSysContext } from "../akanContext";
5
+ import { unlabeledFieldNames } from "../moduleFieldNames";
6
+ import { safeReadText } from "../safeRead";
7
+ import { type DoctorFindings, repairAction } from "./doctorFindings";
8
+
9
+ const moduleShapeFiles = (module: AkanModuleContext) => {
10
+ if (module.kind === "service") {
11
+ return [`${module.name}.dictionary.ts`, `${module.name}.service.ts`, `${module.name}.signal.ts`];
12
+ }
13
+ if (module.kind === "scalar") return [`${module.name}.constant.ts`, `${module.name}.dictionary.ts`];
14
+ return [
15
+ `${module.name}.constant.ts`,
16
+ `${module.name}.dictionary.ts`,
17
+ `${module.name}.service.ts`,
18
+ `${module.name}.store.ts`,
19
+ `${module.name}.signal.ts`,
20
+ ];
21
+ };
22
+
23
+ export class ModuleShapeCheck {
24
+ static async run(
25
+ workspace: WorkspaceExecutor,
26
+ systems: AkanSysContext[],
27
+ findings: DoctorFindings,
28
+ { strict }: { strict: boolean },
29
+ ) {
30
+ for (const sys of systems) {
31
+ for (const module of sys.modules) {
32
+ const moduleShapeCommand = `akan repair module-shape --app ${sys.name} --module ${module.name}`;
33
+ if (!module.abstract.exists)
34
+ findings.report(
35
+ {
36
+ severity: strict ? "error" : "warning",
37
+ code: "module-abstract-missing",
38
+ path: module.abstract.path,
39
+ message: `${capitalize(module.kind)} module ${sys.name}:${module.name} should include ${module.abstract.path}`,
40
+ },
41
+ repairAction(
42
+ "module-shape",
43
+ moduleShapeCommand,
44
+ "Create the missing module abstract or inspect required source files.",
45
+ false,
46
+ ),
47
+ );
48
+ const missingFiles = moduleShapeFiles(module).filter((filename) => !module.files.includes(filename));
49
+ if (missingFiles.length)
50
+ findings.report(
51
+ {
52
+ severity: "error",
53
+ code: "module-shape-invalid",
54
+ path: module.path,
55
+ message: `${capitalize(module.kind)} module ${sys.name}:${module.name} is missing required files: ${missingFiles.join(", ")}`,
56
+ },
57
+ repairAction("module-shape", moduleShapeCommand, "Review missing required module source files.", false),
58
+ );
59
+ if (module.kind !== "service" && module.files.includes(`${module.name}.dictionary.ts`)) {
60
+ const constantPath = path.join(workspace.workspaceRoot, module.path, `${module.name}.constant.ts`);
61
+ const dictionaryPath = path.join(workspace.workspaceRoot, module.path, `${module.name}.dictionary.ts`);
62
+ const [constantContent, dictionaryContent] = await Promise.all([
63
+ safeReadText(constantPath),
64
+ safeReadText(dictionaryPath),
65
+ ]);
66
+ if (constantContent && dictionaryContent) {
67
+ for (const fieldName of unlabeledFieldNames(constantContent, dictionaryContent)) {
68
+ findings.report(
69
+ {
70
+ severity: "warning",
71
+ code: "dictionary-label-missing",
72
+ path: `${module.path}/${module.name}.dictionary.ts`,
73
+ message: `Dictionary labels for ${sys.name}:${module.name}.${fieldName} were not found.`,
74
+ },
75
+ repairAction(
76
+ "dictionary",
77
+ `akan repair dictionary --app ${sys.name} --module ${module.name}`,
78
+ "Add missing dictionary labels for source constant fields.",
79
+ false,
80
+ ),
81
+ );
82
+ }
83
+ }
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
@@ -0,0 +1,39 @@
1
+ import path from "node:path";
2
+ import type { WorkspaceExecutor } from "../../executors";
3
+ import type { AkanSysContext } from "../akanContext";
4
+ import { collectRecipeSources, findInlineRecipeDuplicates, scanRecipes } from "../recipeScanner";
5
+ import type { DoctorFindings } from "./doctorFindings";
6
+
7
+ export class RecipeDuplicateCheck {
8
+ static async run(workspace: WorkspaceExecutor, systems: AkanSysContext[], findings: DoctorFindings) {
9
+ //* Advisory only (warning): promoted to lint only if inline re-authoring actually recurs.
10
+ for (const sys of systems) {
11
+ const sources = await collectRecipeSources(path.join(workspace.workspaceRoot, sys.path, "ui"), "ui");
12
+ if (sources.length === 0) continue;
13
+ const recipes = scanRecipes(sources);
14
+ const files: { path: string; content: string }[] = [];
15
+ const glob = new Bun.Glob("**/*.tsx");
16
+ for await (const abs of glob.scan({ cwd: path.join(workspace.workspaceRoot, sys.path), absolute: true })) {
17
+ if (/[\\/](node_modules|\.akan|dist)[\\/]|[\\/]v1[\\/]/.test(abs) || /\.(test|spec)\.tsx$/.test(abs)) continue;
18
+ files.push({
19
+ path: abs,
20
+ content: await Bun.file(abs)
21
+ .text()
22
+ .catch(() => ""),
23
+ });
24
+ }
25
+ const duplicates = findInlineRecipeDuplicates(recipes, files);
26
+ if (duplicates.length === 0) continue;
27
+ const preview = duplicates
28
+ .slice(0, 3)
29
+ .map((duplicate) => `${path.relative(workspace.workspaceRoot, duplicate.path)}:${duplicate.line}`)
30
+ .join(", ");
31
+ findings.push({
32
+ severity: "warning",
33
+ code: "recipe-inline-duplicate",
34
+ path: path.join(sys.path, "ui/Recipe"),
35
+ message: `${sys.name}: ${duplicates.length} inline className(s) re-author a recipe fingerprint (${preview}${duplicates.length > 3 ? ", …" : ""}) — consume the recipe instead.`,
36
+ });
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,87 @@
1
+ import path from "node:path";
2
+ import type { WorkspaceExecutor } from "../../executors";
3
+ import type { AkanSysContext } from "../akanContext";
4
+ import { collectRecipeSources, scanRecipes } from "../recipeScanner";
5
+ import { type DoctorFindings, repairAction } from "./doctorFindings";
6
+
7
+ export class RecipeIndexCheck {
8
+ static async run(workspace: WorkspaceExecutor, systems: AkanSysContext[], findings: DoctorFindings) {
9
+ // Doctor never writes, so this is what catches a committed stale recipe index (lint and sync self-heal the tree).
10
+ const scanNames = async (uiDirPath: string, basename?: string) =>
11
+ new Set(scanRecipes(await collectRecipeSources(uiDirPath, "ui", basename)).map((info) => info.name));
12
+ const declaredByImport = new Map<string, Set<string>>();
13
+ declaredByImport.set("akanjs/ui", await scanNames(path.join(workspace.workspaceRoot, "pkgs/akanjs/ui"), "recipe"));
14
+ for (const sys of systems)
15
+ declaredByImport.set(`@${sys.path}/ui`, await scanNames(path.join(workspace.workspaceRoot, sys.path, "ui")));
16
+ // Section slice anchors the heading to a full line — the same string appears back-ticked in prose.
17
+ const sectionOf = (content: string, heading: string) => {
18
+ const match = new RegExp(`^${heading}$`, "m").exec(content);
19
+ if (!match) return "";
20
+ const section = content.slice(match.index);
21
+ const sectionEnd = section.indexOf("\n## ", 1);
22
+ return sectionEnd === -1 ? section : section.slice(0, sectionEnd);
23
+ };
24
+ // `Import from \`<path>\`:` groups with their `- \`name\`` items, so each name checks against its owner.
25
+ const listedByImport = (body: string) => {
26
+ const groups = new Map<string, Set<string>>();
27
+ let current: Set<string> | null = null;
28
+ for (const line of body.split("\n")) {
29
+ const group = /^Import from `([^`]+)`:/.exec(line);
30
+ if (group) {
31
+ current = groups.get(group[1]) ?? new Set();
32
+ groups.set(group[1], current);
33
+ continue;
34
+ }
35
+ const item = /^- `([A-Za-z0-9_$]+)`/.exec(line);
36
+ if (item && current) current.add(item[1]);
37
+ else if (!item) current = null;
38
+ }
39
+ return groups;
40
+ };
41
+ const pushIndexDiagnostic = (indexPath: string, missing: string[], stale: string[], repairCommand: string) => {
42
+ if (missing.length === 0 && stale.length === 0) return;
43
+ const parts = [
44
+ missing.length > 0 ? `${missing.length} declared but unlisted (${missing.slice(0, 5).join(", ")})` : "",
45
+ stale.length > 0 ? `${stale.length} listed but gone (${stale.slice(0, 5).join(", ")})` : "",
46
+ ].filter(Boolean);
47
+ findings.report(
48
+ {
49
+ severity: "error",
50
+ code: "recipe-index-stale",
51
+ path: indexPath,
52
+ message: `${indexPath} recipe index is out of date — ${parts.join("; ")}. Agents read this list as authoritative.`,
53
+ },
54
+ repairAction("generated", repairCommand, "Regenerate the recipe index from the scanned recipes.", true),
55
+ );
56
+ };
57
+ const frameworkDeclared = declaredByImport.get("akanjs/ui") ?? new Set<string>();
58
+ if (frameworkDeclared.size > 0) {
59
+ const agentsMd = await Bun.file(path.join(workspace.workspaceRoot, "AGENTS.md"))
60
+ .text()
61
+ .catch(() => "");
62
+ const listed = listedByImport(sectionOf(agentsMd, "## Recipes")).get("akanjs/ui") ?? new Set<string>();
63
+ pushIndexDiagnostic(
64
+ "AGENTS.md",
65
+ [...frameworkDeclared].filter((name) => !listed.has(name)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
66
+ [...listed].filter((name) => !frameworkDeclared.has(name)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
67
+ "akan agent install agents-md",
68
+ );
69
+ }
70
+ for (const sys of systems) {
71
+ const own = declaredByImport.get(`@${sys.path}/ui`) ?? new Set<string>();
72
+ const scopeMd = await Bun.file(path.join(workspace.workspaceRoot, sys.path, "AGENTS.md"))
73
+ .text()
74
+ .catch(() => "");
75
+ const groups = listedByImport(sectionOf(scopeMd, "## Recipes In Scope"));
76
+ const ownListed = groups.get(`@${sys.path}/ui`) ?? new Set<string>();
77
+ const missing = [...own].filter((name) => !ownListed.has(name)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
78
+ // Every listed name — the scope's own and its dependency libs' — must still exist at its owner.
79
+ const stale = [...groups.entries()]
80
+ .flatMap(([importFrom, names]) =>
81
+ [...names].filter((name) => !(declaredByImport.get(importFrom) ?? new Set()).has(name)),
82
+ )
83
+ .sort();
84
+ pushIndexDiagnostic(`${sys.path}/AGENTS.md`, missing, stale, `akan sync ${sys.name}`);
85
+ }
86
+ }
87
+ }
@@ -0,0 +1,55 @@
1
+ import path from "node:path";
2
+ import type { WorkspaceExecutor } from "../../executors";
3
+ import {
4
+ barrelFacetDirs,
5
+ facetIndexShadowOf,
6
+ isScannedRootEntry,
7
+ rootAllowedDirs,
8
+ rootAllowedFiles,
9
+ rootEntryHintOf,
10
+ } from "../../workspace/workspaceLayout";
11
+ import type { AkanSysContext } from "../akanContext";
12
+ import { safeReadDir } from "../safeRead";
13
+ import { type DoctorFindings, repairAction } from "./doctorFindings";
14
+
15
+ export class RootShapeCheck {
16
+ static async run(workspace: WorkspaceExecutor, systems: AkanSysContext[], findings: DoctorFindings) {
17
+ for (const sys of systems) {
18
+ const sysPath = path.join(workspace.workspaceRoot, sys.path);
19
+ for (const entry of await safeReadDir(sysPath)) {
20
+ if (!isScannedRootEntry(sys.type, entry.name)) continue;
21
+ const allowed = entry.isDirectory()
22
+ ? rootAllowedDirs[sys.type].has(entry.name)
23
+ : rootAllowedFiles[sys.type].has(entry.name);
24
+ const rootEntryHint = rootEntryHintOf(sys.type, entry.name);
25
+ if (!allowed)
26
+ findings.report(
27
+ {
28
+ severity: "error",
29
+ code: `${sys.type}-root-unknown-entry`,
30
+ path: `${sys.path}/${entry.name}`,
31
+ message: `Unexpected ${entry.isDirectory() ? "folder" : "file"} in ${sys.type} root: ${sys.path}/${entry.name}${
32
+ rootEntryHint ? ` (${rootEntryHint})` : ""
33
+ }`,
34
+ },
35
+ repairAction(
36
+ "module-shape",
37
+ `akan repair module-shape --app ${sys.name}`,
38
+ `Review ${sys.type} root shape and remove or move the unknown entry.`,
39
+ false,
40
+ ),
41
+ );
42
+ }
43
+ for (const facet of barrelFacetDirs)
44
+ for (const entry of await safeReadDir(path.join(sysPath, facet))) {
45
+ const shadow = entry.isDirectory() ? null : facetIndexShadowOf(`${facet}/${entry.name}`);
46
+ if (!shadow) continue;
47
+ const entryPath = `${sys.path}/${facet}/${entry.name}`;
48
+ findings.report(
49
+ { severity: "error", code: "facet-index-shadowed", path: entryPath, message: `${entryPath} ${shadow}` },
50
+ repairAction("generated", `akan sync ${sys.name}`, `Delete ${entryPath} by hand, then sync.`, false),
51
+ );
52
+ }
53
+ }
54
+ }
55
+ }
@@ -0,0 +1,97 @@
1
+ import path from "node:path";
2
+ import { isRecord } from "akanjs/common";
3
+ import type { WorkspaceExecutor } from "../../executors";
4
+ import {
5
+ type WorkflowApplyReport,
6
+ type WorkflowPlan,
7
+ type WorkflowRunArtifact,
8
+ workflowPathsForPlan,
9
+ workflowRunArtifactPath,
10
+ } from "../../workflow";
11
+ import type { AkanDiagnostic } from "../akanContext";
12
+ import { safeReadJson } from "../safeRead";
13
+
14
+ const isWorkflowPlan = (value: unknown): value is WorkflowPlan =>
15
+ typeof value === "object" &&
16
+ value !== null &&
17
+ "schemaVersion" in value &&
18
+ value.schemaVersion === 1 &&
19
+ "mode" in value &&
20
+ value.mode === "plan" &&
21
+ "inputs" in value &&
22
+ isRecord(value.inputs) &&
23
+ "predictedChanges" in value &&
24
+ Array.isArray(value.predictedChanges) &&
25
+ value.predictedChanges.every((change) => isRecord(change) && typeof change.target === "string");
26
+
27
+ const isPathList = (value: unknown) =>
28
+ Array.isArray(value) && value.every((file) => isRecord(file) && typeof file.path === "string");
29
+
30
+ const isWorkflowApplyReport = (value: unknown): value is WorkflowApplyReport =>
31
+ typeof value === "object" &&
32
+ value !== null &&
33
+ "schemaVersion" in value &&
34
+ value.schemaVersion === 1 &&
35
+ "mode" in value &&
36
+ (value.mode === "apply" || value.mode === "dry-run") &&
37
+ "changedFiles" in value &&
38
+ isPathList(value.changedFiles) &&
39
+ "generatedFiles" in value &&
40
+ isPathList(value.generatedFiles) &&
41
+ "plan" in value &&
42
+ isWorkflowPlan(value.plan);
43
+
44
+ const isWorkflowRunArtifact = (value: unknown): value is WorkflowRunArtifact =>
45
+ typeof value === "object" && value !== null && "schemaVersion" in value && value.schemaVersion === 1;
46
+
47
+ const workflowPathsForArtifact = (artifact: WorkflowRunArtifact) => {
48
+ if (isWorkflowPlan(artifact)) return workflowPathsForPlan(artifact);
49
+ if (isWorkflowApplyReport(artifact)) {
50
+ return [
51
+ ...artifact.changedFiles.map((file) => file.path),
52
+ ...artifact.generatedFiles.map((file) => file.path),
53
+ ...workflowPathsForPlan(artifact.plan),
54
+ ];
55
+ }
56
+ if ("mode" in artifact && artifact.mode === "validate" && isWorkflowPlan(artifact.plan))
57
+ return workflowPathsForPlan(artifact.plan);
58
+ return [];
59
+ };
60
+
61
+ export const loadWorkflowContextPaths = async (
62
+ workspace: WorkspaceExecutor,
63
+ runIdOrPlan: string | null,
64
+ changedFiles: string[],
65
+ ) => {
66
+ const paths = [...changedFiles];
67
+ if (!runIdOrPlan) return paths;
68
+ const inputPath = path.isAbsolute(runIdOrPlan) ? runIdOrPlan : path.join(workspace.workspaceRoot, runIdOrPlan);
69
+ const artifact =
70
+ (await safeReadJson<WorkflowRunArtifact | WorkflowPlan>(inputPath)) ??
71
+ (await safeReadJson<WorkflowRunArtifact>(path.join(workspace.workspaceRoot, workflowRunArtifactPath(runIdOrPlan))));
72
+ if (artifact && isWorkflowRunArtifact(artifact)) paths.push(...workflowPathsForArtifact(artifact));
73
+ return [...new Set(paths.filter(Boolean))];
74
+ };
75
+
76
+ const withoutPlaceholders = (value: string) =>
77
+ value
78
+ .split("<")
79
+ .map((part, index) => (index === 0 ? part : part.slice(part.indexOf(">") + 1)))
80
+ .join("");
81
+
82
+ const pathKey = (value: string) =>
83
+ withoutPlaceholders(value.replaceAll("\\", "/").replaceAll("*", ""))
84
+ .replace(/\/+/g, "/")
85
+ .replace(/^\/|\/$/g, "");
86
+
87
+ export const isWorkflowRelatedDiagnostic = (diagnostic: AkanDiagnostic, workflowPaths: string[]) => {
88
+ if (!diagnostic.path) return false;
89
+ const diagnosticPath = pathKey(diagnostic.path);
90
+ return workflowPaths.some((workflowPath) => {
91
+ const candidate = pathKey(workflowPath);
92
+ if (!candidate) return false;
93
+ return (
94
+ diagnosticPath.startsWith(candidate) || candidate.startsWith(diagnosticPath) || diagnosticPath.includes(candidate)
95
+ );
96
+ });
97
+ };
@@ -0,0 +1,9 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { FileSys } from "../util/fileSys";
3
+
4
+ export const safeReadDir = async (dirPath: string) =>
5
+ (await readdir(dirPath, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name));
6
+
7
+ export const safeReadText = (filePath: string) => FileSys.readText(filePath).catch(() => null);
8
+
9
+ export const safeReadJson = <T>(filePath: string) => FileSys.readJson<T>(filePath).catch(() => null);
@@ -199,6 +199,40 @@ describe("ApplicationBuildReporter", () => {
199
199
  );
200
200
  });
201
201
 
202
+ test("shows the first 20 errors of an aggregate, counts the rest, and follows its cause", () => {
203
+ const many = new AggregateError(
204
+ Array.from({ length: 23 }, (_, index) => new Error(`log ${index + 1}`)),
205
+ "server graph failed",
206
+ { cause: new Error("plugin licenseNotices") },
207
+ );
208
+ expect(ApplicationBuildReporter.formatError(many).split("\n")).toEqual([
209
+ "server graph failed",
210
+ ...Array.from({ length: 20 }, (_, index) => ` log ${index + 1}`),
211
+ " …and 3 more",
212
+ "Caused by: plugin licenseNotices",
213
+ ]);
214
+ });
215
+
216
+ test("ends a cause or an aggregate that loops back on itself", () => {
217
+ const looped = new Error("upload failed");
218
+ looped.cause = new Error("socket closed", { cause: looped });
219
+ expect(ApplicationBuildReporter.formatError(looped).split("\n")).toEqual([
220
+ "upload failed",
221
+ "Caused by: socket closed",
222
+ "Caused by: [circular]",
223
+ ]);
224
+
225
+ const shared = new Error("disk full");
226
+ const aggregate = new AggregateError([shared, shared], "two writes failed");
227
+ aggregate.errors.push(aggregate);
228
+ expect(ApplicationBuildReporter.formatError(aggregate).split("\n")).toEqual([
229
+ "two writes failed",
230
+ " disk full",
231
+ " disk full",
232
+ " [circular]",
233
+ ]);
234
+ });
235
+
202
236
  test("says where the bundler placed each reason, relative to the workspace root", async () => {
203
237
  const root = await makeTempRoot();
204
238
  const refuseWith = (message: string) => ({
@@ -1041,6 +1041,33 @@ describe("Workspace and app executor environment contracts", () => {
1041
1041
 
1042
1042
  await expect(app.getPageKeys({ refresh: true })).resolves.toEqual(["./(docs)/_layout.tsx"]);
1043
1043
  });
1044
+
1045
+ const levelBoundaryLayout = [
1046
+ "export const LevelBoundary = ({ children }) => children;",
1047
+ "export default function Layout({ children }) { return children; }",
1048
+ "",
1049
+ ].join("\n");
1050
+
1051
+ test("refuses a LevelBoundary export on the app's root layout, which the generated one would ignore", async () => {
1052
+ const app = await makeRouteValidationApp("root-level-boundary", "export default {};\n", {
1053
+ "_layout.tsx": levelBoundaryLayout,
1054
+ });
1055
+
1056
+ await expect(app.getPageKeys({ refresh: true })).rejects.toThrow(
1057
+ /unsupported export "LevelBoundary" in .*page\/_layout\.tsx: LevelBoundary belongs to the root layout Akan\.js generates, which never reads one from an app's layout/,
1058
+ );
1059
+ });
1060
+
1061
+ test("refuses a LevelBoundary export on a grouped root layout under the app's own, naming the grouped file", async () => {
1062
+ const app = await makeRouteValidationApp("nested-root-level-boundary", "export default {};\n", {
1063
+ "_layout.tsx": "export default function Layout({ children }) { return children; }\n",
1064
+ "(home)/_layout.tsx": levelBoundaryLayout,
1065
+ });
1066
+
1067
+ await expect(app.getPageKeys({ refresh: true })).rejects.toThrow(
1068
+ /unsupported export "LevelBoundary" in .*page\/\(home\)\/_layout\.tsx: LevelBoundary belongs to the root layout Akan\.js generates/,
1069
+ );
1070
+ });
1044
1071
  });
1045
1072
 
1046
1073
  test("accepts head route exports during page key discovery", async () => {
@@ -1329,14 +1356,11 @@ describe("SysExecutor module listing", () => {
1329
1356
  const contents = (files: { content: string }[]) => files.map((file) => file.content);
1330
1357
 
1331
1358
  const scan = spyOn(AppInfo, "fromExecutor").mockResolvedValue({ getLibs: () => ["shared"] } as never);
1332
- const cwd = process.cwd();
1333
- // `getDirInModule` stats the workspace-relative path it just listed, so it resolves against the process cwd.
1334
- process.chdir(root);
1359
+ expect(process.cwd()).not.toBe(root);
1335
1360
  try {
1336
1361
  expect(contents(await workspace.getConstantFiles())).toEqual([appConstant, libConstant]);
1337
1362
  expect(contents(await app.getConstantFilesWithLibs())).toEqual([appConstant, libConstant]);
1338
1363
  } finally {
1339
- process.chdir(cwd);
1340
1364
  scan.mockRestore();
1341
1365
  }
1342
1366
  });
@@ -1,5 +1,4 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { stat } from "node:fs/promises";
3
2
  import path from "node:path";
4
3
  import { AkanWorkspaceConfig } from "../akanConfig";
5
4
  import { FileSys } from "../util/fileSys";
@@ -190,7 +189,7 @@ export class WorkspaceExecutor extends Executor {
190
189
  dirs.map(async (dir) => {
191
190
  if (dir.includes("_") || AVOID_DIRS.includes(dir)) return;
192
191
  const dirPath = path.join(dirname, dir);
193
- if ((await stat(dirPath)).isDirectory()) {
192
+ if (await FileSys.dirExists(this.getPath(dirPath))) {
194
193
  results.push(`${prefix}${dir}`);
195
194
  if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
196
195
  }