@akanjs/cli 3.2.0-rc.18 → 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 (90) hide show
  1. package/.build-stamp +2 -2
  2. package/{CodeAgent-w96z7fm7.js → CodeAgent-q0xkt4at.js} +2 -2
  3. package/{CodeTui-496f55hh.js → CodeTui-n56kpaca.js} +819 -663
  4. package/TunnelShare-844s9te4.js +18 -0
  5. package/{agent.command-81h65wcv.js → agent.command-k07raqft.js} +20 -20
  6. package/akanCode.js +8 -8
  7. package/{appExecutor-g4wq24v1.js → appExecutor-xav1zemr.js} +3 -3
  8. package/{application.command-rcw4h1gh.js → application.command-dv8y8r12.js} +52 -25
  9. package/{applicationBuildRunner-emhp6rh0.js → applicationBuildRunner-vhx7zq97.js} +9 -10
  10. package/buildBatch.proc.js +20 -11
  11. package/{cloud.command-k47h3kma.js → cloud.command-0vjy3x96.js} +22 -22
  12. package/cloud.script-jp48r0kw.js +35 -0
  13. package/{code.command-dam01a2f.js → code.command-xc5exq4b.js} +10 -10
  14. package/{context.command-44carkt5.js → context.command-etsat8yk.js} +22 -22
  15. package/context.runner-e52ak0cx.js +34 -0
  16. package/{guideline.command-ccxs69br.js → guideline.command-zqkntk7b.js} +6 -6
  17. package/guidelines/agentRule/agentRule.instruction.md +5 -4
  18. package/guidelines/conventions/core.md +18 -0
  19. package/guidelines/errorCodes/errorCodes.instruction.md +6 -0
  20. package/guidelines/mcpRule/mcpRule.instruction.md +4 -2
  21. package/guidelines/transportRule/transportRule.instruction.md +3 -1
  22. package/incrementalBuilder.proc.js +559 -409
  23. package/{index-aw7at6j6.js → index-12js5pj4.js} +1 -1
  24. package/{index-tpr9nqkj.js → index-12vv4g80.js} +1 -1
  25. package/index-4zqebbqb.js +80 -0
  26. package/{index-rxxjkbj2.js → index-6bryy19d.js} +499 -421
  27. package/{index-2hwjhe8r.js → index-6pzncry1.js} +4 -4
  28. package/{index-jeqq717b.js → index-6rrh0ffr.js} +44 -32
  29. package/{index-a42cf737.js → index-7jr9mfp2.js} +235 -105
  30. package/{index-pcqr0r0m.js → index-81qt1jyj.js} +1 -1
  31. package/{index-2mrn1mrg.js → index-9f3reh2y.js} +1 -1
  32. package/{index-h9356zmz.js → index-a05ewnnp.js} +1 -1
  33. package/{index-ptpdd9hw.js → index-bxevbjw7.js} +8 -8
  34. package/{index-g95rbz83.js → index-c1vym3gx.js} +2 -2
  35. package/{index-vh8q7mrq.js → index-c9hd79py.js} +4 -4
  36. package/{index-wy7qcqsd.js → index-c9mnfy9r.js} +38 -23
  37. package/{index-a85n83t6.js → index-cc9pevta.js} +1 -1
  38. package/{index-4279crca.js → index-cet2s7xk.js} +2 -2
  39. package/{index-k1p29hdp.js → index-dasa0kbj.js} +2 -2
  40. package/{index-y27cxjd6.js → index-ddc2zjj5.js} +1 -1
  41. package/{index-r790hx48.js → index-dz7z9n9t.js} +25 -25
  42. package/{index-mgvvtjp1.js → index-e4vna9dn.js} +4 -4
  43. package/{index-ggmwp14t.js → index-ean2tff1.js} +723 -691
  44. package/{index-s21zxj7p.js → index-fgp04fh7.js} +6 -6
  45. package/{index-cef0fxf2.js → index-g541mhzw.js} +3 -3
  46. package/{index-rj406y9n.js → index-gh741qft.js} +8 -8
  47. package/{index-sa8g94se.js → index-k51718xz.js} +2138 -2138
  48. package/{index-286djj0d.js → index-m6r3pvf5.js} +2 -2
  49. package/{index-kqf2s304.js → index-my17308p.js} +7 -7
  50. package/{index-pqf6d5ff.js → index-nd8bq17n.js} +6 -6
  51. package/{index-her656ng.js → index-nxcmgqk3.js} +3 -3
  52. package/{index-gd9tkq2k.js → index-pkgha3rt.js} +5 -5
  53. package/{index-tkrg58qv.js → index-q2t2w996.js} +1 -1
  54. package/{index-b061e6fn.js → index-qtqhsb33.js} +204 -160
  55. package/{index-nwbdpnna.js → index-rj2n5kfk.js} +67 -67
  56. package/{index-ktvyva62.js → index-s5gvwvkb.js} +103 -138
  57. package/{index-bbd1727m.js → index-sh3yzse2.js} +8 -7
  58. package/{index-y71v7grx.js → index-syn4vm3y.js} +1 -1
  59. package/{index-gkfpqdm8.js → index-t00xrkey.js} +1 -1
  60. package/{index-hw2eammf.js → index-v72mh89f.js} +5 -6
  61. package/{index-qrh7kdb1.js → index-wq8pnev4.js} +3 -3
  62. package/{index-1j1jmmac.js → index-wxr3941g.js} +8 -8
  63. package/{index-e4w015qt.js → index-y8mqkhcf.js} +1 -1
  64. package/{index-ctrx7asj.js → index-zk1gjk46.js} +4 -4
  65. package/index.js +27 -27
  66. package/{libExecutor-mmrzd606.js → libExecutor-mr3vxtnr.js} +2 -2
  67. package/{library.command-brkcat13.js → library.command-ps9q5t37.js} +7 -7
  68. package/{localRegistry.command-qwzy3t7w.js → localRegistry.command-rszxmvd0.js} +21 -21
  69. package/{module.command-t5emqxkr.js → module.command-fcybnn1a.js} +10 -10
  70. package/{package.command-xv04dbxf.js → package.command-zen3rhye.js} +10 -10
  71. package/package.json +2 -2
  72. package/{page.command-yhgq9tj8.js → page.command-gwrxymms.js} +7 -7
  73. package/{pipeline.command-x3nkf9kc.js → pipeline.command-m1brkqqw.js} +6 -6
  74. package/{pkgExecutor-4cbe3sgr.js → pkgExecutor-x51agavp.js} +2 -2
  75. package/{primitive.command-jv60b759.js → primitive.command-5vkxvvmk.js} +11 -11
  76. package/{projectTypecheck-fbfq9rm9.js → projectTypecheck-9dzfah37.js} +1 -1
  77. package/{quality.command-mdjardf1.js → quality.command-gqry7eas.js} +9 -9
  78. package/{repair.command-s22j5xbe.js → repair.command-qs4ejcrg.js} +10 -10
  79. package/{scalar.command-a6qs7012.js → scalar.command-ny0vchqq.js} +9 -9
  80. package/skills/akan-scaffold/SKILL.md +1 -1
  81. package/{subspace.command-26hkjqf9.js → subspace.command-5pxqjgmw.js} +12 -12
  82. package/templates/workspaceRoot/AGENTS.md.template +2 -1
  83. package/{tunnel.command-83sfgz5z.js → tunnel.command-ndajt0xk.js} +11 -11
  84. package/{verify.command-krm1rrf1.js → verify.command-m59ashc7.js} +17 -17
  85. package/{workflow.command-z05y7amj.js → workflow.command-jchqey88.js} +15 -15
  86. package/{workspace.command-qga6cn1n.js → workspace.command-g0gzxkpd.js} +36 -36
  87. package/TunnelShare-tyj8nb0z.js +0 -19
  88. package/cloud.script-b4smdpa5.js +0 -35
  89. package/context.runner-xtr9ngpa.js +0 -34
  90. package/index-k2kr1wd4.js +0 -18
@@ -8,21 +8,21 @@ import {
8
8
  isScannedRootEntry,
9
9
  extractBlockVersion,
10
10
  readDevkitVersion
11
- } from "./index-hw2eammf.js";
11
+ } from "./index-v72mh89f.js";
12
12
  import {
13
13
  FileSys2
14
14
  } from "./index-by2tvsq6.js";
15
15
  import {
16
16
  AppExecutor2
17
- } from "./index-4279crca.js";
17
+ } from "./index-cet2s7xk.js";
18
18
  import {
19
19
  LibExecutor2
20
- } from "./index-gkfpqdm8.js";
20
+ } from "./index-t00xrkey.js";
21
21
  import {
22
22
  workflowPathsForPlan,
23
23
  workflowRunArtifactPath,
24
24
  workflowSyncDir
25
- } from "./index-ggmwp14t.js";
25
+ } from "./index-ean2tff1.js";
26
26
  import {
27
27
  collectRecipeSources2,
28
28
  scanRecipes2,
@@ -30,9 +30,249 @@ import {
30
30
  } from "./index-1p81ecbz.js";
31
31
 
32
32
  // pkgs/@akanjs/devkit/context/akanContext.ts
33
+ import path9 from "path";
34
+ import { parseRouteModuleKey } from "akanjs/common";
35
+
36
+ // pkgs/@akanjs/devkit/context/doctor/agentGuideCheck.ts
37
+ import path3 from "path";
38
+
39
+ // pkgs/@akanjs/devkit/context/safeRead.ts
33
40
  import { readdir } from "fs/promises";
41
+ var safeReadDir = async (dirPath) => (await readdir(dirPath, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name));
42
+ var safeReadText = (filePath) => FileSys2.readText(filePath).catch(() => null);
43
+ var safeReadJson = (filePath) => FileSys2.readJson(filePath).catch(() => null);
44
+
45
+ // pkgs/@akanjs/devkit/context/doctor/generatedFreshness.ts
34
46
  import path from "path";
35
- import { capitalize, isRecord, parseRouteModuleKey } from "akanjs/common";
47
+ var unknownGeneratedFilesFreshness = {
48
+ status: "unknown",
49
+ message: "Run sync before validation so generated Akan files match the current source conventions.",
50
+ refreshCommand: "akan sync <app-or-lib>",
51
+ verifyingCommands: ["akan verify <app-or-lib>"]
52
+ };
53
+ var readGeneratedSyncStates = async (workspace) => {
54
+ const syncDir = path.join(workspace.workspaceRoot, workflowSyncDir);
55
+ const entries = await safeReadDir(syncDir);
56
+ const states = await Promise.all(entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => safeReadJson(path.join(syncDir, entry.name))));
57
+ return states.filter((state) => !!state && state.schemaVersion === 1 && typeof state.target === "string" && typeof state.syncedAt === "string");
58
+ };
59
+ var generatedFreshnessFromStates = async (workspace) => {
60
+ const states = await readGeneratedSyncStates(workspace);
61
+ if (states.length === 0)
62
+ return unknownGeneratedFilesFreshness;
63
+ const targets = states.sort((a, b) => a.target.localeCompare(b.target)).map((state) => ({
64
+ target: state.target,
65
+ status: state.status === "passed" ? "fresh" : "stale",
66
+ lastSyncedAt: state.syncedAt,
67
+ runId: state.runId,
68
+ generatedFiles: state.generatedFiles.map((file) => file.path),
69
+ reason: state.status === "passed" ? `Generated files were refreshed by ${state.command}.` : `Last generated repair command failed: ${state.command}.`
70
+ }));
71
+ const lastFresh = targets.filter((target) => target.status === "fresh" && target.lastSyncedAt).sort((a, b) => (b.lastSyncedAt ?? "").localeCompare(a.lastSyncedAt ?? ""))[0];
72
+ return {
73
+ status: targets.some((target) => target.status === "fresh") ? "fresh" : "stale",
74
+ message: lastFresh ? `Generated files were refreshed for ${lastFresh.target} at ${lastFresh.lastSyncedAt}.` : "Generated sync state exists, but the last recorded repair did not pass.",
75
+ refreshCommand: "akan sync <app-or-lib>",
76
+ verifyingCommands: ["akan verify <app-or-lib>"],
77
+ targets
78
+ };
79
+ };
80
+
81
+ // pkgs/@akanjs/devkit/context/doctor/workflowScope.ts
82
+ import path2 from "path";
83
+ import { isRecord } from "akanjs/common";
84
+ var isWorkflowPlan = (value) => typeof value === "object" && value !== null && ("schemaVersion" in value) && value.schemaVersion === 1 && ("mode" in value) && value.mode === "plan" && ("inputs" in value) && isRecord(value.inputs) && ("predictedChanges" in value) && Array.isArray(value.predictedChanges) && value.predictedChanges.every((change) => isRecord(change) && typeof change.target === "string");
85
+ var isPathList = (value) => Array.isArray(value) && value.every((file) => isRecord(file) && typeof file.path === "string");
86
+ var isWorkflowApplyReport = (value) => typeof value === "object" && value !== null && ("schemaVersion" in value) && value.schemaVersion === 1 && ("mode" in value) && (value.mode === "apply" || value.mode === "dry-run") && ("changedFiles" in value) && isPathList(value.changedFiles) && ("generatedFiles" in value) && isPathList(value.generatedFiles) && ("plan" in value) && isWorkflowPlan(value.plan);
87
+ var isWorkflowRunArtifact = (value) => typeof value === "object" && value !== null && ("schemaVersion" in value) && value.schemaVersion === 1;
88
+ var workflowPathsForArtifact = (artifact) => {
89
+ if (isWorkflowPlan(artifact))
90
+ return workflowPathsForPlan(artifact);
91
+ if (isWorkflowApplyReport(artifact)) {
92
+ return [
93
+ ...artifact.changedFiles.map((file) => file.path),
94
+ ...artifact.generatedFiles.map((file) => file.path),
95
+ ...workflowPathsForPlan(artifact.plan)
96
+ ];
97
+ }
98
+ if ("mode" in artifact && artifact.mode === "validate" && isWorkflowPlan(artifact.plan))
99
+ return workflowPathsForPlan(artifact.plan);
100
+ return [];
101
+ };
102
+ var loadWorkflowContextPaths = async (workspace, runIdOrPlan, changedFiles) => {
103
+ const paths = [...changedFiles];
104
+ if (!runIdOrPlan)
105
+ return paths;
106
+ const inputPath = path2.isAbsolute(runIdOrPlan) ? runIdOrPlan : path2.join(workspace.workspaceRoot, runIdOrPlan);
107
+ const artifact = await safeReadJson(inputPath) ?? await safeReadJson(path2.join(workspace.workspaceRoot, workflowRunArtifactPath(runIdOrPlan)));
108
+ if (artifact && isWorkflowRunArtifact(artifact))
109
+ paths.push(...workflowPathsForArtifact(artifact));
110
+ return [...new Set(paths.filter(Boolean))];
111
+ };
112
+ var withoutPlaceholders = (value) => value.split("<").map((part, index) => index === 0 ? part : part.slice(part.indexOf(">") + 1)).join("");
113
+ var pathKey = (value) => withoutPlaceholders(value.replaceAll("\\", "/").replaceAll("*", "")).replace(/\/+/g, "/").replace(/^\/|\/$/g, "");
114
+ var isWorkflowRelatedDiagnostic = (diagnostic, workflowPaths) => {
115
+ if (!diagnostic.path)
116
+ return false;
117
+ const diagnosticPath = pathKey(diagnostic.path);
118
+ return workflowPaths.some((workflowPath) => {
119
+ const candidate = pathKey(workflowPath);
120
+ if (!candidate)
121
+ return false;
122
+ return diagnosticPath.startsWith(candidate) || candidate.startsWith(diagnosticPath) || diagnosticPath.includes(candidate);
123
+ });
124
+ };
125
+
126
+ // pkgs/@akanjs/devkit/context/doctor/doctorFindings.ts
127
+ var repairAction = (kind, command, reason, safeToRun) => ({
128
+ kind,
129
+ command,
130
+ reason,
131
+ safeToRun
132
+ });
133
+
134
+ class DoctorFindings {
135
+ #diagnostics = [];
136
+ #repairActions = [
137
+ repairAction("generated", "akan repair generated --app <app-or-lib>", "Refresh generated Akan files.", true),
138
+ repairAction("format", "akan repair format --target <app-or-lib-or-pkg>", "Run the formatter/linter repair path.", true)
139
+ ];
140
+ report(diagnostic, action) {
141
+ this.#diagnostics.push({ ...diagnostic, repairActions: [action] });
142
+ this.#repairActions.push(action);
143
+ }
144
+ push(diagnostic) {
145
+ this.#diagnostics.push(diagnostic);
146
+ }
147
+ async result(workspace, context, { strict, workflowPaths }) {
148
+ const scopedDiagnostics = this.#diagnostics.map((diagnostic) => ({
149
+ ...diagnostic,
150
+ scope: workflowPaths.length ? isWorkflowRelatedDiagnostic(diagnostic, workflowPaths) ? "workflow" : "baseline" : diagnostic.scope,
151
+ context: workflowPaths.length ? { ...diagnostic.context, paths: workflowPaths } : diagnostic.context
152
+ }));
153
+ const workflowDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "workflow");
154
+ const baselineDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "baseline");
155
+ return {
156
+ schemaVersion: 1,
157
+ repoName: context.repoName,
158
+ root: context.root,
159
+ strict,
160
+ status: scopedDiagnostics.some((diagnostic) => diagnostic.severity === "error") ? "failed" : "passed",
161
+ diagnostics: scopedDiagnostics,
162
+ generatedFiles: context.generatedFiles,
163
+ generatedFilesFreshness: await generatedFreshnessFromStates(workspace),
164
+ validationCommands: context.validationCommands,
165
+ repairActions: this.#repairActions,
166
+ ...workflowPaths.length ? { baselineDiagnostics, workflowDiagnostics } : {}
167
+ };
168
+ }
169
+ }
170
+
171
+ // pkgs/@akanjs/devkit/context/doctor/agentGuideCheck.ts
172
+ class AgentGuideCheck {
173
+ static async run(workspace, systems, findings) {
174
+ const agentDrift = await AgentGuideCheck.#drift(workspace);
175
+ if (agentDrift)
176
+ findings.report({ severity: "warning", code: agentDrift.code, path: "AGENTS.md", message: agentDrift.message }, repairAction("generated", "akan agent install agents-md", agentDrift.hint, true));
177
+ const sysPaths = systems.map((sys) => sys.path);
178
+ const oversize = await AgentGuideCheck.#oversize(workspace, sysPaths);
179
+ if (oversize)
180
+ findings.push({ severity: "warning", code: "agent-guide-oversized", path: "AGENTS.md", message: oversize });
181
+ for (const leftover of await AgentGuideCheck.#leftovers(workspace))
182
+ findings.push({ severity: "warning", code: "agent-guide-leftover", ...leftover });
183
+ }
184
+ static async#drift(workspace) {
185
+ const installed = await readDevkitVersion();
186
+ if (!installed)
187
+ return null;
188
+ const content = await safeReadText(path3.join(workspace.workspaceRoot, "AGENTS.md"));
189
+ if (content === null)
190
+ return null;
191
+ const stamped = extractBlockVersion(content);
192
+ if (stamped === installed)
193
+ return null;
194
+ const hint = "Re-render the AGENTS.md managed block from the installed framework release.";
195
+ if (!stamped)
196
+ return {
197
+ code: "agent-guide-unstamped",
198
+ message: `AGENTS.md carries no generated-version stamp, so its conventions may predate @akanjs/devkit ${installed}`,
199
+ hint
200
+ };
201
+ return {
202
+ code: "agent-guide-stale",
203
+ message: `AGENTS.md was generated by @akanjs/devkit ${stamped}, but ${installed} is installed`,
204
+ hint
205
+ };
206
+ }
207
+ static async#oversize(workspace, sysPaths) {
208
+ const sizeOf = async (file) => {
209
+ const content = await safeReadText(path3.join(workspace.workspaceRoot, file));
210
+ return { file, bytes: content === null ? 0 : Buffer.byteLength(content) };
211
+ };
212
+ const root = await sizeOf("AGENTS.md");
213
+ if (root.bytes === 0)
214
+ return null;
215
+ const scoped = await Promise.all(sysPaths.map((sysPath) => sizeOf(`${sysPath}/AGENTS.md`)));
216
+ const largest = scoped.reduce((max, entry) => entry.bytes > max.bytes ? entry : max, { file: "", bytes: 0 });
217
+ const total = root.bytes + largest.bytes;
218
+ if (total <= 32 * 1024 * 0.8)
219
+ return null;
220
+ const subject = largest.bytes ? `AGENTS.md and ${largest.file} add up to` : "AGENTS.md is";
221
+ return `${subject} ${Math.ceil(total / 1024)} KiB of the 32 KiB Codex reads \u2014 run \`akan agent install\`, then shorten the text outside the akan:agent markers or move it into a skill.`;
222
+ }
223
+ static async#leftovers(workspace) {
224
+ const root = workspace.workspaceRoot;
225
+ const guide = await safeReadText(path3.join(root, "AGENTS.md")) ?? "";
226
+ const leftovers = [];
227
+ for (const doc of ["docs/AI-DEVELOPMENT.md", "docs/GENERATED.md"]) {
228
+ const pointer = guide.includes(doc);
229
+ if (await safeReadText(path3.join(root, doc)) !== null)
230
+ leftovers.push({
231
+ path: doc,
232
+ message: `${doc} is an older template's copy of the agent guide, and nothing reads it now \u2014 delete it${pointer ? " and the AGENTS.md sentence that points to it" : ""}.`
233
+ });
234
+ else if (pointer)
235
+ leftovers.push({
236
+ path: "AGENTS.md",
237
+ message: `AGENTS.md points to ${doc}, which is gone \u2014 delete that sentence.`
238
+ });
239
+ }
240
+ return leftovers;
241
+ }
242
+ }
243
+
244
+ // pkgs/@akanjs/devkit/context/doctor/configLeftoverCheck.ts
245
+ import path4 from "path";
246
+ class ConfigLeftoverCheck {
247
+ static async run(workspace, systems, findings) {
248
+ const sysPaths = systems.map((sys) => sys.path);
249
+ for (const leftover of await ConfigLeftoverCheck.#leftovers(workspace, sysPaths))
250
+ findings.push({ severity: "warning", code: "config-leftover", ...leftover });
251
+ }
252
+ static async#leftovers(workspace, sysPaths) {
253
+ const leftovers = [];
254
+ for (const sysPath of sysPaths) {
255
+ const tsconfigPath = `${sysPath}/tsconfig.json`;
256
+ const tsconfig = await safeReadText(path4.join(workspace.workspaceRoot, tsconfigPath));
257
+ if (tsconfig && (/"name"\s*:\s*"next"/.test(tsconfig) || tsconfig.includes(".next/types")))
258
+ leftovers.push({
259
+ path: tsconfigPath,
260
+ message: `${tsconfigPath} still names the Next.js TS plugin or .next/types, which Akan never uses \u2014 delete the "next" plugin entry and the ".next/types/**/*.ts" include.`
261
+ });
262
+ }
263
+ const bunfig = await safeReadText(path4.join(workspace.workspaceRoot, "bunfig.toml"));
264
+ if (bunfig?.includes("bun-plugin-tailwind"))
265
+ leftovers.push({
266
+ path: "bunfig.toml",
267
+ message: "bunfig.toml still loads bun-plugin-tailwind, which is not installed and which Akan never uses (it compiles Tailwind itself) \u2014 delete the [serve.static] section, which Akan never reads."
268
+ });
269
+ return leftovers;
270
+ }
271
+ }
272
+
273
+ // pkgs/@akanjs/devkit/context/doctor/moduleShapeCheck.ts
274
+ import path5 from "path";
275
+ import { capitalize } from "akanjs/common";
36
276
 
37
277
  // pkgs/@akanjs/devkit/context/moduleFieldNames.ts
38
278
  import ts from "typescript";
@@ -53,6 +293,198 @@ var unlabeledFieldNames = (constantContent, dictionaryContent) => {
53
293
  return constantFieldNames(constantContent).filter((name) => !labels.has(name));
54
294
  };
55
295
 
296
+ // pkgs/@akanjs/devkit/context/doctor/moduleShapeCheck.ts
297
+ var moduleShapeFiles = (module) => {
298
+ if (module.kind === "service") {
299
+ return [`${module.name}.dictionary.ts`, `${module.name}.service.ts`, `${module.name}.signal.ts`];
300
+ }
301
+ if (module.kind === "scalar")
302
+ return [`${module.name}.constant.ts`, `${module.name}.dictionary.ts`];
303
+ return [
304
+ `${module.name}.constant.ts`,
305
+ `${module.name}.dictionary.ts`,
306
+ `${module.name}.service.ts`,
307
+ `${module.name}.store.ts`,
308
+ `${module.name}.signal.ts`
309
+ ];
310
+ };
311
+
312
+ class ModuleShapeCheck {
313
+ static async run(workspace, systems, findings, { strict }) {
314
+ for (const sys of systems) {
315
+ for (const module of sys.modules) {
316
+ const moduleShapeCommand = `akan repair module-shape --app ${sys.name} --module ${module.name}`;
317
+ if (!module.abstract.exists)
318
+ findings.report({
319
+ severity: strict ? "error" : "warning",
320
+ code: "module-abstract-missing",
321
+ path: module.abstract.path,
322
+ message: `${capitalize(module.kind)} module ${sys.name}:${module.name} should include ${module.abstract.path}`
323
+ }, repairAction("module-shape", moduleShapeCommand, "Create the missing module abstract or inspect required source files.", false));
324
+ const missingFiles = moduleShapeFiles(module).filter((filename) => !module.files.includes(filename));
325
+ if (missingFiles.length)
326
+ findings.report({
327
+ severity: "error",
328
+ code: "module-shape-invalid",
329
+ path: module.path,
330
+ message: `${capitalize(module.kind)} module ${sys.name}:${module.name} is missing required files: ${missingFiles.join(", ")}`
331
+ }, repairAction("module-shape", moduleShapeCommand, "Review missing required module source files.", false));
332
+ if (module.kind !== "service" && module.files.includes(`${module.name}.dictionary.ts`)) {
333
+ const constantPath = path5.join(workspace.workspaceRoot, module.path, `${module.name}.constant.ts`);
334
+ const dictionaryPath = path5.join(workspace.workspaceRoot, module.path, `${module.name}.dictionary.ts`);
335
+ const [constantContent, dictionaryContent] = await Promise.all([
336
+ safeReadText(constantPath),
337
+ safeReadText(dictionaryPath)
338
+ ]);
339
+ if (constantContent && dictionaryContent) {
340
+ for (const fieldName of unlabeledFieldNames(constantContent, dictionaryContent)) {
341
+ findings.report({
342
+ severity: "warning",
343
+ code: "dictionary-label-missing",
344
+ path: `${module.path}/${module.name}.dictionary.ts`,
345
+ message: `Dictionary labels for ${sys.name}:${module.name}.${fieldName} were not found.`
346
+ }, repairAction("dictionary", `akan repair dictionary --app ${sys.name} --module ${module.name}`, "Add missing dictionary labels for source constant fields.", false));
347
+ }
348
+ }
349
+ }
350
+ }
351
+ }
352
+ }
353
+ }
354
+
355
+ // pkgs/@akanjs/devkit/context/doctor/recipeDuplicateCheck.ts
356
+ import path6 from "path";
357
+ class RecipeDuplicateCheck {
358
+ static async run(workspace, systems, findings) {
359
+ for (const sys of systems) {
360
+ const sources = await collectRecipeSources2(path6.join(workspace.workspaceRoot, sys.path, "ui"), "ui");
361
+ if (sources.length === 0)
362
+ continue;
363
+ const recipes = scanRecipes2(sources);
364
+ const files = [];
365
+ const glob = new Bun.Glob("**/*.tsx");
366
+ for await (const abs of glob.scan({ cwd: path6.join(workspace.workspaceRoot, sys.path), absolute: true })) {
367
+ if (/[\\/](node_modules|\.akan|dist)[\\/]|[\\/]v1[\\/]/.test(abs) || /\.(test|spec)\.tsx$/.test(abs))
368
+ continue;
369
+ files.push({
370
+ path: abs,
371
+ content: await Bun.file(abs).text().catch(() => "")
372
+ });
373
+ }
374
+ const duplicates = findInlineRecipeDuplicates2(recipes, files);
375
+ if (duplicates.length === 0)
376
+ continue;
377
+ const preview = duplicates.slice(0, 3).map((duplicate) => `${path6.relative(workspace.workspaceRoot, duplicate.path)}:${duplicate.line}`).join(", ");
378
+ findings.push({
379
+ severity: "warning",
380
+ code: "recipe-inline-duplicate",
381
+ path: path6.join(sys.path, "ui/Recipe"),
382
+ message: `${sys.name}: ${duplicates.length} inline className(s) re-author a recipe fingerprint (${preview}${duplicates.length > 3 ? ", \u2026" : ""}) \u2014 consume the recipe instead.`
383
+ });
384
+ }
385
+ }
386
+ }
387
+
388
+ // pkgs/@akanjs/devkit/context/doctor/recipeIndexCheck.ts
389
+ import path7 from "path";
390
+ class RecipeIndexCheck {
391
+ static async run(workspace, systems, findings) {
392
+ const scanNames = async (uiDirPath, basename) => new Set(scanRecipes2(await collectRecipeSources2(uiDirPath, "ui", basename)).map((info) => info.name));
393
+ const declaredByImport = new Map;
394
+ declaredByImport.set("akanjs/ui", await scanNames(path7.join(workspace.workspaceRoot, "pkgs/akanjs/ui"), "recipe"));
395
+ for (const sys of systems)
396
+ declaredByImport.set(`@${sys.path}/ui`, await scanNames(path7.join(workspace.workspaceRoot, sys.path, "ui")));
397
+ const sectionOf = (content, heading) => {
398
+ const match = new RegExp(`^${heading}$`, "m").exec(content);
399
+ if (!match)
400
+ return "";
401
+ const section = content.slice(match.index);
402
+ const sectionEnd = section.indexOf(`
403
+ ## `, 1);
404
+ return sectionEnd === -1 ? section : section.slice(0, sectionEnd);
405
+ };
406
+ const listedByImport = (body) => {
407
+ const groups = new Map;
408
+ let current = null;
409
+ for (const line of body.split(`
410
+ `)) {
411
+ const group = /^Import from `([^`]+)`:/.exec(line);
412
+ if (group) {
413
+ current = groups.get(group[1]) ?? new Set;
414
+ groups.set(group[1], current);
415
+ continue;
416
+ }
417
+ const item = /^- `([A-Za-z0-9_$]+)`/.exec(line);
418
+ if (item && current)
419
+ current.add(item[1]);
420
+ else if (!item)
421
+ current = null;
422
+ }
423
+ return groups;
424
+ };
425
+ const pushIndexDiagnostic = (indexPath, missing, stale, repairCommand) => {
426
+ if (missing.length === 0 && stale.length === 0)
427
+ return;
428
+ const parts = [
429
+ missing.length > 0 ? `${missing.length} declared but unlisted (${missing.slice(0, 5).join(", ")})` : "",
430
+ stale.length > 0 ? `${stale.length} listed but gone (${stale.slice(0, 5).join(", ")})` : ""
431
+ ].filter(Boolean);
432
+ findings.report({
433
+ severity: "error",
434
+ code: "recipe-index-stale",
435
+ path: indexPath,
436
+ message: `${indexPath} recipe index is out of date \u2014 ${parts.join("; ")}. Agents read this list as authoritative.`
437
+ }, repairAction("generated", repairCommand, "Regenerate the recipe index from the scanned recipes.", true));
438
+ };
439
+ const frameworkDeclared = declaredByImport.get("akanjs/ui") ?? new Set;
440
+ if (frameworkDeclared.size > 0) {
441
+ const agentsMd = await Bun.file(path7.join(workspace.workspaceRoot, "AGENTS.md")).text().catch(() => "");
442
+ const listed = listedByImport(sectionOf(agentsMd, "## Recipes")).get("akanjs/ui") ?? new Set;
443
+ pushIndexDiagnostic("AGENTS.md", [...frameworkDeclared].filter((name) => !listed.has(name)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0), [...listed].filter((name) => !frameworkDeclared.has(name)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0), "akan agent install agents-md");
444
+ }
445
+ for (const sys of systems) {
446
+ const own = declaredByImport.get(`@${sys.path}/ui`) ?? new Set;
447
+ const scopeMd = await Bun.file(path7.join(workspace.workspaceRoot, sys.path, "AGENTS.md")).text().catch(() => "");
448
+ const groups = listedByImport(sectionOf(scopeMd, "## Recipes In Scope"));
449
+ const ownListed = groups.get(`@${sys.path}/ui`) ?? new Set;
450
+ const missing = [...own].filter((name) => !ownListed.has(name)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
451
+ const stale = [...groups.entries()].flatMap(([importFrom, names]) => [...names].filter((name) => !(declaredByImport.get(importFrom) ?? new Set).has(name))).sort();
452
+ pushIndexDiagnostic(`${sys.path}/AGENTS.md`, missing, stale, `akan sync ${sys.name}`);
453
+ }
454
+ }
455
+ }
456
+
457
+ // pkgs/@akanjs/devkit/context/doctor/rootShapeCheck.ts
458
+ import path8 from "path";
459
+ class RootShapeCheck {
460
+ static async run(workspace, systems, findings) {
461
+ for (const sys of systems) {
462
+ const sysPath = path8.join(workspace.workspaceRoot, sys.path);
463
+ for (const entry of await safeReadDir(sysPath)) {
464
+ if (!isScannedRootEntry(sys.type, entry.name))
465
+ continue;
466
+ const allowed = entry.isDirectory() ? rootAllowedDirs[sys.type].has(entry.name) : rootAllowedFiles[sys.type].has(entry.name);
467
+ const rootEntryHint = rootEntryHintOf(sys.type, entry.name);
468
+ if (!allowed)
469
+ findings.report({
470
+ severity: "error",
471
+ code: `${sys.type}-root-unknown-entry`,
472
+ path: `${sys.path}/${entry.name}`,
473
+ message: `Unexpected ${entry.isDirectory() ? "folder" : "file"} in ${sys.type} root: ${sys.path}/${entry.name}${rootEntryHint ? ` (${rootEntryHint})` : ""}`
474
+ }, repairAction("module-shape", `akan repair module-shape --app ${sys.name}`, `Review ${sys.type} root shape and remove or move the unknown entry.`, false));
475
+ }
476
+ for (const facet of barrelFacetDirs)
477
+ for (const entry of await safeReadDir(path8.join(sysPath, facet))) {
478
+ const shadow = entry.isDirectory() ? null : facetIndexShadowOf(`${facet}/${entry.name}`);
479
+ if (!shadow)
480
+ continue;
481
+ const entryPath = `${sys.path}/${facet}/${entry.name}`;
482
+ findings.report({ severity: "error", code: "facet-index-shadowed", path: entryPath, message: `${entryPath} ${shadow}` }, repairAction("generated", `akan sync ${sys.name}`, `Delete ${entryPath} by hand, then sync.`, false));
483
+ }
484
+ }
485
+ }
486
+ }
487
+
56
488
  // pkgs/@akanjs/devkit/context/akanContext.ts
57
489
  var guidelineResourceUri = (name) => `akan://guidelines/${name}`;
58
490
  var staticResourceList = [
@@ -122,144 +554,48 @@ ${nextBlock}`;
122
554
  };
123
555
  var renderDoctorText = (result) => {
124
556
  const lines = [`Akan doctor status: ${result.status}`];
125
- if (result.diagnostics.length === 0) {
126
- lines.push("", "No Akan workspace diagnostics found.");
127
- } else {
128
- lines.push("", ...result.diagnostics.map((diagnostic) => [
129
- `[${diagnostic.severity}] ${diagnostic.code}: ${diagnostic.message}`,
130
- diagnostic.path ? ` ${diagnostic.path}` : ""
131
- ].filter(Boolean).join(`
132
- `)));
133
- }
134
- lines.push("", "Generated file freshness:", `Status: ${result.generatedFilesFreshness.status}`, result.generatedFilesFreshness.message, `Refresh: ${result.generatedFilesFreshness.refreshCommand}`, "", "Repair actions:", ...result.repairActions.length ? result.repairActions.map((action) => `- ${action.command}`) : ["- none"], "", "Validation commands:", ...result.validationCommands.map((command) => `- ${command}`));
135
- return `${lines.join(`
136
- `)}
137
- `;
138
- };
139
- var generatedFiles = [
140
- "apps/*/client.ts",
141
- "apps/*/server.ts",
142
- "*/lib/cnst.ts",
143
- "*/lib/db.ts",
144
- "*/lib/dict.ts",
145
- "*/lib/sig.ts",
146
- "*/lib/srv.ts",
147
- "*/lib/st.ts",
148
- "*/lib/useClient.ts",
149
- "*/lib/useServer.ts",
150
- "*/lib/**/index.ts",
151
- "*/ui/index.ts",
152
- "*/webkit/index.ts",
153
- "*/srvkit/index.ts",
154
- "*/common/index.ts"
155
- ];
156
- var validationCommands = [
157
- "akan verify [<app-or-lib-or-pkg>]",
158
- "akan sync <app-or-lib>",
159
- "akan lint <app-or-lib-or-pkg>",
160
- "akan typecheck <app-or-lib>",
161
- "akan test <app-or-lib-or-pkg>",
162
- "akan build <app-name>",
163
- "akan doctor --strict --format json",
164
- "akan quality scan [--format json]",
165
- "akan quality ssr [--format json]"
166
- ];
167
- var unknownGeneratedFilesFreshness = {
168
- status: "unknown",
169
- message: "Run sync before validation so generated Akan files match the current source conventions.",
170
- refreshCommand: "akan sync <app-or-lib>",
171
- verifyingCommands: ["akan verify <app-or-lib>"]
172
- };
173
- var repairAction = (kind, command, reason, safeToRun) => ({
174
- kind,
175
- command,
176
- reason,
177
- safeToRun
178
- });
179
- var moduleShapeFiles = (module) => {
180
- if (module.kind === "service") {
181
- return [`${module.name}.dictionary.ts`, `${module.name}.service.ts`, `${module.name}.signal.ts`];
182
- }
183
- if (module.kind === "scalar")
184
- return [`${module.name}.constant.ts`, `${module.name}.dictionary.ts`];
185
- return [
186
- `${module.name}.constant.ts`,
187
- `${module.name}.dictionary.ts`,
188
- `${module.name}.service.ts`,
189
- `${module.name}.store.ts`,
190
- `${module.name}.signal.ts`
191
- ];
192
- };
193
- var safeReadDir = async (dirPath) => (await readdir(dirPath, { withFileTypes: true }).catch(() => [])).sort((a, b) => a.name.localeCompare(b.name));
194
- var safeReadText = (filePath) => FileSys2.readText(filePath).catch(() => null);
195
- var safeReadJson = (filePath) => FileSys2.readJson(filePath).catch(() => null);
196
- var isWorkflowPlan = (value) => typeof value === "object" && value !== null && ("schemaVersion" in value) && value.schemaVersion === 1 && ("mode" in value) && value.mode === "plan" && ("inputs" in value) && isRecord(value.inputs) && ("predictedChanges" in value) && Array.isArray(value.predictedChanges) && value.predictedChanges.every((change) => isRecord(change) && typeof change.target === "string");
197
- var isPathList = (value) => Array.isArray(value) && value.every((file) => isRecord(file) && typeof file.path === "string");
198
- var isWorkflowApplyReport = (value) => typeof value === "object" && value !== null && ("schemaVersion" in value) && value.schemaVersion === 1 && ("mode" in value) && (value.mode === "apply" || value.mode === "dry-run") && ("changedFiles" in value) && isPathList(value.changedFiles) && ("generatedFiles" in value) && isPathList(value.generatedFiles) && ("plan" in value) && isWorkflowPlan(value.plan);
199
- var isWorkflowRunArtifact = (value) => typeof value === "object" && value !== null && ("schemaVersion" in value) && value.schemaVersion === 1;
200
- var workflowPathsForArtifact = (artifact) => {
201
- if (isWorkflowPlan(artifact))
202
- return workflowPathsForPlan(artifact);
203
- if (isWorkflowApplyReport(artifact)) {
204
- return [
205
- ...artifact.changedFiles.map((file) => file.path),
206
- ...artifact.generatedFiles.map((file) => file.path),
207
- ...workflowPathsForPlan(artifact.plan)
208
- ];
209
- }
210
- if ("mode" in artifact && artifact.mode === "validate" && isWorkflowPlan(artifact.plan))
211
- return workflowPathsForPlan(artifact.plan);
212
- return [];
213
- };
214
- var loadWorkflowContextPaths = async (workspace, runIdOrPlan, changedFiles) => {
215
- const paths = [...changedFiles];
216
- if (!runIdOrPlan)
217
- return paths;
218
- const inputPath = path.isAbsolute(runIdOrPlan) ? runIdOrPlan : path.join(workspace.workspaceRoot, runIdOrPlan);
219
- const artifact = await safeReadJson(inputPath) ?? await safeReadJson(path.join(workspace.workspaceRoot, workflowRunArtifactPath(runIdOrPlan)));
220
- if (artifact && isWorkflowRunArtifact(artifact))
221
- paths.push(...workflowPathsForArtifact(artifact));
222
- return [...new Set(paths.filter(Boolean))];
223
- };
224
- var pathKey = (value) => value.replaceAll("\\", "/").replaceAll("*", "").replace(/<[^>]+>/g, "").replace(/\/+/g, "/").replace(/^\/|\/$/g, "");
225
- var isWorkflowRelatedDiagnostic = (diagnostic, workflowPaths) => {
226
- if (!diagnostic.path)
227
- return false;
228
- const diagnosticPath = pathKey(diagnostic.path);
229
- return workflowPaths.some((workflowPath) => {
230
- const candidate = pathKey(workflowPath);
231
- if (!candidate)
232
- return false;
233
- return diagnosticPath.startsWith(candidate) || candidate.startsWith(diagnosticPath) || diagnosticPath.includes(candidate);
234
- });
235
- };
236
- var readGeneratedSyncStates = async (workspace) => {
237
- const syncDir = path.join(workspace.workspaceRoot, workflowSyncDir);
238
- const entries = await safeReadDir(syncDir);
239
- const states = await Promise.all(entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => safeReadJson(path.join(syncDir, entry.name))));
240
- return states.filter((state) => !!state && state.schemaVersion === 1 && typeof state.target === "string" && typeof state.syncedAt === "string");
241
- };
242
- var generatedFreshnessFromStates = async (workspace) => {
243
- const states = await readGeneratedSyncStates(workspace);
244
- if (states.length === 0)
245
- return unknownGeneratedFilesFreshness;
246
- const targets = states.sort((a, b) => a.target.localeCompare(b.target)).map((state) => ({
247
- target: state.target,
248
- status: state.status === "passed" ? "fresh" : "stale",
249
- lastSyncedAt: state.syncedAt,
250
- runId: state.runId,
251
- generatedFiles: state.generatedFiles.map((file) => file.path),
252
- reason: state.status === "passed" ? `Generated files were refreshed by ${state.command}.` : `Last generated repair command failed: ${state.command}.`
253
- }));
254
- const lastFresh = targets.filter((target) => target.status === "fresh" && target.lastSyncedAt).sort((a, b) => (b.lastSyncedAt ?? "").localeCompare(a.lastSyncedAt ?? ""))[0];
255
- return {
256
- status: targets.some((target) => target.status === "fresh") ? "fresh" : "stale",
257
- message: lastFresh ? `Generated files were refreshed for ${lastFresh.target} at ${lastFresh.lastSyncedAt}.` : "Generated sync state exists, but the last recorded repair did not pass.",
258
- refreshCommand: "akan sync <app-or-lib>",
259
- verifyingCommands: ["akan verify <app-or-lib>"],
260
- targets
261
- };
557
+ if (result.diagnostics.length === 0) {
558
+ lines.push("", "No Akan workspace diagnostics found.");
559
+ } else {
560
+ lines.push("", ...result.diagnostics.map((diagnostic) => [
561
+ `[${diagnostic.severity}] ${diagnostic.code}: ${diagnostic.message}`,
562
+ diagnostic.path ? ` ${diagnostic.path}` : ""
563
+ ].filter(Boolean).join(`
564
+ `)));
565
+ }
566
+ lines.push("", "Generated file freshness:", `Status: ${result.generatedFilesFreshness.status}`, result.generatedFilesFreshness.message, `Refresh: ${result.generatedFilesFreshness.refreshCommand}`, "", "Repair actions:", ...result.repairActions.length ? result.repairActions.map((action) => `- ${action.command}`) : ["- none"], "", "Validation commands:", ...result.validationCommands.map((command) => `- ${command}`));
567
+ return `${lines.join(`
568
+ `)}
569
+ `;
262
570
  };
571
+ var generatedFiles = [
572
+ "apps/*/client.ts",
573
+ "apps/*/server.ts",
574
+ "*/lib/cnst.ts",
575
+ "*/lib/db.ts",
576
+ "*/lib/dict.ts",
577
+ "*/lib/sig.ts",
578
+ "*/lib/srv.ts",
579
+ "*/lib/st.ts",
580
+ "*/lib/useClient.ts",
581
+ "*/lib/useServer.ts",
582
+ "*/lib/**/index.ts",
583
+ "*/ui/index.ts",
584
+ "*/webkit/index.ts",
585
+ "*/srvkit/index.ts",
586
+ "*/common/index.ts"
587
+ ];
588
+ var validationCommands = [
589
+ "akan verify [<app-or-lib-or-pkg>]",
590
+ "akan sync <app-or-lib>",
591
+ "akan lint <app-or-lib-or-pkg>",
592
+ "akan typecheck <app-or-lib>",
593
+ "akan test <app-or-lib-or-pkg>",
594
+ "akan build <app-name>",
595
+ "akan doctor --strict --format json",
596
+ "akan quality scan [--format json]",
597
+ "akan quality ssr [--format json]"
598
+ ];
263
599
  var parseAbstractSummary = (relativePath, content, includeContent) => {
264
600
  if (content === null)
265
601
  return { path: relativePath, exists: false, headings: [] };
@@ -273,12 +609,12 @@ var parseAbstractSummary = (relativePath, content, includeContent) => {
273
609
  };
274
610
  };
275
611
  var readFiles = async (dirPath) => (await safeReadDir(dirPath)).filter((entry) => entry.isFile()).map((entry) => entry.name).sort();
276
- var getRelative = (workspace, absolutePath) => path.relative(workspace.workspaceRoot, absolutePath).replaceAll(path.sep, "/");
612
+ var getRelative = (workspace, absolutePath) => path9.relative(workspace.workspaceRoot, absolutePath).replaceAll(path9.sep, "/");
277
613
  var createModuleContext = async (workspace, sys, kind, folderName, moduleName, includeAbstractContent) => {
278
- const modulePath = kind === "scalar" ? path.join(sys.cwdPath, "lib", "__scalar", moduleName) : path.join(sys.cwdPath, "lib", folderName);
614
+ const modulePath = kind === "scalar" ? path9.join(sys.cwdPath, "lib", "__scalar", moduleName) : path9.join(sys.cwdPath, "lib", folderName);
279
615
  const relativePath = getRelative(workspace, modulePath);
280
616
  const abstractPath = `${relativePath}/${moduleName}.abstract.md`;
281
- const abstractContent = await safeReadText(path.join(workspace.workspaceRoot, abstractPath));
617
+ const abstractContent = await safeReadText(path9.join(workspace.workspaceRoot, abstractPath));
282
618
  return {
283
619
  kind,
284
620
  name: moduleName,
@@ -294,7 +630,7 @@ var getSysModules = async (workspace, sys, {
294
630
  includeAbstractContent = false,
295
631
  module: moduleFilter
296
632
  } = {}) => {
297
- const libPath = path.join(sys.cwdPath, "lib");
633
+ const libPath = path9.join(sys.cwdPath, "lib");
298
634
  const entries = await safeReadDir(libPath);
299
635
  const modules = [];
300
636
  for (const entry of entries) {
@@ -308,24 +644,24 @@ var getSysModules = async (workspace, sys, {
308
644
  const serviceName = entry.name.replace(/^_+/, "");
309
645
  if (moduleFilter && moduleFilter !== serviceName && moduleFilter !== entry.name)
310
646
  continue;
311
- if (!await FileSys2.fileExists(path.join(libPath, entry.name, `${serviceName}.service.ts`)))
647
+ if (!await FileSys2.fileExists(path9.join(libPath, entry.name, `${serviceName}.service.ts`)))
312
648
  continue;
313
649
  modules.push(await createModuleContext(workspace, sys, "service", entry.name, serviceName, includeAbstractContent));
314
650
  } else {
315
651
  if (moduleFilter && moduleFilter !== entry.name)
316
652
  continue;
317
- if (!await FileSys2.fileExists(path.join(libPath, entry.name, `${entry.name}.constant.ts`)))
653
+ if (!await FileSys2.fileExists(path9.join(libPath, entry.name, `${entry.name}.constant.ts`)))
318
654
  continue;
319
655
  modules.push(await createModuleContext(workspace, sys, "domain", entry.name, entry.name, includeAbstractContent));
320
656
  }
321
657
  }
322
- const scalarRoot = path.join(libPath, "__scalar");
658
+ const scalarRoot = path9.join(libPath, "__scalar");
323
659
  for (const entry of await safeReadDir(scalarRoot)) {
324
660
  if (!entry.isDirectory() || entry.name.startsWith("_"))
325
661
  continue;
326
662
  if (moduleFilter && moduleFilter !== entry.name)
327
663
  continue;
328
- if (!await FileSys2.fileExists(path.join(scalarRoot, entry.name, `${entry.name}.constant.ts`)))
664
+ if (!await FileSys2.fileExists(path9.join(scalarRoot, entry.name, `${entry.name}.constant.ts`)))
329
665
  continue;
330
666
  modules.push(await createModuleContext(workspace, sys, "scalar", entry.name, entry.name, includeAbstractContent));
331
667
  }
@@ -348,7 +684,7 @@ var getAppRoutes = async (app, workspaceRoot) => {
348
684
  const underGuard = Array.from({ length: reach + 1 }, (_, idx) => segments.slice(0, idx).join("/")).some((prefix) => guardedLayouts.has(prefix));
349
685
  return {
350
686
  path: parsed.pattern.replace(/^\/:lang/, "") || "/",
351
- file: path.relative(workspaceRoot, source.absPath).replaceAll(path.sep, "/"),
687
+ file: path9.relative(workspaceRoot, source.absPath).replaceAll(path9.sep, "/"),
352
688
  search: source.info.chain?.search ?? [],
353
689
  guarded: !!source.info.chain?.guarded || underGuard,
354
690
  devOnly: source.info.devOnly
@@ -361,7 +697,7 @@ var getSysContext = async (workspace, type, name, options) => {
361
697
  type,
362
698
  name,
363
699
  path: `${type}s/${name}`,
364
- hasConfig: await FileSys2.fileExists(path.join(sys.cwdPath, "akan.config.ts")),
700
+ hasConfig: await FileSys2.fileExists(path9.join(sys.cwdPath, "akan.config.ts")),
365
701
  modules: await getSysModules(workspace, sys, {
366
702
  includeAbstractContent: options.includeAbstractContent,
367
703
  module: options.module
@@ -375,13 +711,13 @@ var getSysContext = async (workspace, type, name, options) => {
375
711
  class AkanContextAnalyzer {
376
712
  static async analyze(workspace, options = {}) {
377
713
  const [appNames, libNames, pkgNames] = await workspace.getExecs();
378
- const rootPackageJson = await safeReadJson(path.join(workspace.workspaceRoot, "package.json"));
714
+ const rootPackageJson = await safeReadJson(path9.join(workspace.workspaceRoot, "package.json"));
379
715
  const filteredApps = options.app ? appNames.filter((name) => name === options.app) : appNames;
380
716
  const [apps, libs, pkgs] = await Promise.all([
381
717
  Promise.all(filteredApps.map((name) => getSysContext(workspace, "app", name, options))),
382
718
  Promise.all(libNames.map((name) => getSysContext(workspace, "lib", name, options))),
383
719
  Promise.all(pkgNames.map(async (name) => {
384
- const packageJson = await safeReadJson(path.join(workspace.workspaceRoot, "pkgs", name, "package.json"));
720
+ const packageJson = await safeReadJson(path9.join(workspace.workspaceRoot, "pkgs", name, "package.json"));
385
721
  return {
386
722
  name,
387
723
  path: `pkgs/${name}`,
@@ -401,83 +737,6 @@ class AkanContextAnalyzer {
401
737
  validationCommands
402
738
  };
403
739
  }
404
- static async#agentGuideDrift(workspace) {
405
- const installed = await readDevkitVersion();
406
- if (!installed)
407
- return null;
408
- const content = await safeReadText(path.join(workspace.workspaceRoot, "AGENTS.md"));
409
- if (content === null)
410
- return null;
411
- const stamped = extractBlockVersion(content);
412
- if (stamped === installed)
413
- return null;
414
- const hint = "Re-render the AGENTS.md managed block from the installed framework release.";
415
- if (!stamped)
416
- return {
417
- code: "agent-guide-unstamped",
418
- message: `AGENTS.md carries no generated-version stamp, so its conventions may predate @akanjs/devkit ${installed}`,
419
- hint
420
- };
421
- return {
422
- code: "agent-guide-stale",
423
- message: `AGENTS.md was generated by @akanjs/devkit ${stamped}, but ${installed} is installed`,
424
- hint
425
- };
426
- }
427
- static async#agentGuideOversize(workspace, sysPaths) {
428
- const sizeOf = async (file) => {
429
- const content = await safeReadText(path.join(workspace.workspaceRoot, file));
430
- return { file, bytes: content === null ? 0 : Buffer.byteLength(content) };
431
- };
432
- const root = await sizeOf("AGENTS.md");
433
- if (root.bytes === 0)
434
- return null;
435
- const scoped = await Promise.all(sysPaths.map((sysPath) => sizeOf(`${sysPath}/AGENTS.md`)));
436
- const largest = scoped.reduce((max, entry) => entry.bytes > max.bytes ? entry : max, { file: "", bytes: 0 });
437
- const total = root.bytes + largest.bytes;
438
- if (total <= 32 * 1024 * 0.8)
439
- return null;
440
- const subject = largest.bytes ? `AGENTS.md and ${largest.file} add up to` : "AGENTS.md is";
441
- return `${subject} ${Math.ceil(total / 1024)} KiB of the 32 KiB Codex reads \u2014 run \`akan agent install\`, then shorten the text outside the akan:agent markers or move it into a skill.`;
442
- }
443
- static async#agentGuideLeftovers(workspace) {
444
- const root = workspace.workspaceRoot;
445
- const guide = await safeReadText(path.join(root, "AGENTS.md")) ?? "";
446
- const leftovers = [];
447
- for (const doc of ["docs/AI-DEVELOPMENT.md", "docs/GENERATED.md"]) {
448
- const pointer = guide.includes(doc);
449
- if (await safeReadText(path.join(root, doc)) !== null)
450
- leftovers.push({
451
- path: doc,
452
- message: `${doc} is an older template's copy of the agent guide, and nothing reads it now \u2014 delete it${pointer ? " and the AGENTS.md sentence that points to it" : ""}.`
453
- });
454
- else if (pointer)
455
- leftovers.push({
456
- path: "AGENTS.md",
457
- message: `AGENTS.md points to ${doc}, which is gone \u2014 delete that sentence.`
458
- });
459
- }
460
- return leftovers;
461
- }
462
- static async#configLeftovers(workspace, sysPaths) {
463
- const leftovers = [];
464
- for (const sysPath of sysPaths) {
465
- const tsconfigPath = `${sysPath}/tsconfig.json`;
466
- const tsconfig = await safeReadText(path.join(workspace.workspaceRoot, tsconfigPath));
467
- if (tsconfig && (/"name"\s*:\s*"next"/.test(tsconfig) || tsconfig.includes(".next/types")))
468
- leftovers.push({
469
- path: tsconfigPath,
470
- message: `${tsconfigPath} still names the Next.js TS plugin or .next/types, which Akan never uses \u2014 delete the "next" plugin entry and the ".next/types/**/*.ts" include.`
471
- });
472
- }
473
- const bunfig = await safeReadText(path.join(workspace.workspaceRoot, "bunfig.toml"));
474
- if (bunfig?.includes("bun-plugin-tailwind"))
475
- leftovers.push({
476
- path: "bunfig.toml",
477
- message: "bunfig.toml still loads bun-plugin-tailwind, which is not installed and which Akan never uses (it compiles Tailwind itself) \u2014 delete the [serve.static] section, which Akan never reads."
478
- });
479
- return leftovers;
480
- }
481
740
  static async doctor(workspace, {
482
741
  strict = false,
483
742
  runIdOrPlan = null,
@@ -485,196 +744,15 @@ class AkanContextAnalyzer {
485
744
  } = {}) {
486
745
  const context = await AkanContextAnalyzer.analyze(workspace);
487
746
  const workflowPaths = await loadWorkflowContextPaths(workspace, runIdOrPlan, changedFiles);
488
- const diagnostics = [];
489
- const repairActions = [
490
- repairAction("generated", "akan repair generated --app <app-or-lib>", "Refresh generated Akan files.", true),
491
- repairAction("format", "akan repair format --target <app-or-lib-or-pkg>", "Run the formatter/linter repair path.", true)
492
- ];
493
- const report = (diagnostic, action) => {
494
- diagnostics.push({ ...diagnostic, repairActions: [action] });
495
- repairActions.push(action);
496
- };
497
- for (const sys of [...context.apps, ...context.libs]) {
498
- const sysPath = path.join(workspace.workspaceRoot, sys.path);
499
- for (const entry of await safeReadDir(sysPath)) {
500
- if (!isScannedRootEntry(sys.type, entry.name))
501
- continue;
502
- const allowed = entry.isDirectory() ? rootAllowedDirs[sys.type].has(entry.name) : rootAllowedFiles[sys.type].has(entry.name);
503
- const rootEntryHint = rootEntryHintOf(sys.type, entry.name);
504
- if (!allowed)
505
- report({
506
- severity: "error",
507
- code: `${sys.type}-root-unknown-entry`,
508
- path: `${sys.path}/${entry.name}`,
509
- message: `Unexpected ${entry.isDirectory() ? "folder" : "file"} in ${sys.type} root: ${sys.path}/${entry.name}${rootEntryHint ? ` (${rootEntryHint})` : ""}`
510
- }, repairAction("module-shape", `akan repair module-shape --app ${sys.name}`, `Review ${sys.type} root shape and remove or move the unknown entry.`, false));
511
- }
512
- for (const facet of barrelFacetDirs)
513
- for (const entry of await safeReadDir(path.join(sysPath, facet))) {
514
- const shadow = entry.isDirectory() ? null : facetIndexShadowOf(`${facet}/${entry.name}`);
515
- if (!shadow)
516
- continue;
517
- const entryPath = `${sys.path}/${facet}/${entry.name}`;
518
- report({ severity: "error", code: "facet-index-shadowed", path: entryPath, message: `${entryPath} ${shadow}` }, repairAction("generated", `akan sync ${sys.name}`, `Delete ${entryPath} by hand, then sync.`, false));
519
- }
520
- }
521
- const agentDrift = await AkanContextAnalyzer.#agentGuideDrift(workspace);
522
- if (agentDrift)
523
- report({ severity: "warning", code: agentDrift.code, path: "AGENTS.md", message: agentDrift.message }, repairAction("generated", "akan agent install agents-md", agentDrift.hint, true));
524
- const sysPaths = [...context.apps, ...context.libs].map((sys) => sys.path);
525
- const oversize = await AkanContextAnalyzer.#agentGuideOversize(workspace, sysPaths);
526
- if (oversize)
527
- diagnostics.push({ severity: "warning", code: "agent-guide-oversized", path: "AGENTS.md", message: oversize });
528
- for (const leftover of await AkanContextAnalyzer.#agentGuideLeftovers(workspace))
529
- diagnostics.push({ severity: "warning", code: "agent-guide-leftover", ...leftover });
530
- for (const leftover of await AkanContextAnalyzer.#configLeftovers(workspace, sysPaths))
531
- diagnostics.push({ severity: "warning", code: "config-leftover", ...leftover });
532
- for (const sys of [...context.apps, ...context.libs]) {
533
- for (const module of sys.modules) {
534
- const moduleShapeCommand = `akan repair module-shape --app ${sys.name} --module ${module.name}`;
535
- if (!module.abstract.exists)
536
- report({
537
- severity: strict ? "error" : "warning",
538
- code: "module-abstract-missing",
539
- path: module.abstract.path,
540
- message: `${capitalize(module.kind)} module ${sys.name}:${module.name} should include ${module.abstract.path}`
541
- }, repairAction("module-shape", moduleShapeCommand, "Create the missing module abstract or inspect required source files.", false));
542
- const missingFiles = moduleShapeFiles(module).filter((filename) => !module.files.includes(filename));
543
- if (missingFiles.length)
544
- report({
545
- severity: "error",
546
- code: "module-shape-invalid",
547
- path: module.path,
548
- message: `${capitalize(module.kind)} module ${sys.name}:${module.name} is missing required files: ${missingFiles.join(", ")}`
549
- }, repairAction("module-shape", moduleShapeCommand, "Review missing required module source files.", false));
550
- if (module.kind !== "service" && module.files.includes(`${module.name}.dictionary.ts`)) {
551
- const constantPath = path.join(workspace.workspaceRoot, module.path, `${module.name}.constant.ts`);
552
- const dictionaryPath = path.join(workspace.workspaceRoot, module.path, `${module.name}.dictionary.ts`);
553
- const [constantContent, dictionaryContent] = await Promise.all([
554
- safeReadText(constantPath),
555
- safeReadText(dictionaryPath)
556
- ]);
557
- if (constantContent && dictionaryContent) {
558
- for (const fieldName of unlabeledFieldNames(constantContent, dictionaryContent)) {
559
- report({
560
- severity: "warning",
561
- code: "dictionary-label-missing",
562
- path: `${module.path}/${module.name}.dictionary.ts`,
563
- message: `Dictionary labels for ${sys.name}:${module.name}.${fieldName} were not found.`
564
- }, repairAction("dictionary", `akan repair dictionary --app ${sys.name} --module ${module.name}`, "Add missing dictionary labels for source constant fields.", false));
565
- }
566
- }
567
- }
568
- }
569
- }
570
- for (const sys of [...context.apps, ...context.libs]) {
571
- const sources = await collectRecipeSources2(path.join(workspace.workspaceRoot, sys.path, "ui"), "ui");
572
- if (sources.length === 0)
573
- continue;
574
- const recipes = scanRecipes2(sources);
575
- const files = [];
576
- const glob = new Bun.Glob("**/*.tsx");
577
- for await (const abs of glob.scan({ cwd: path.join(workspace.workspaceRoot, sys.path), absolute: true })) {
578
- if (/[\\/](node_modules|\.akan|dist)[\\/]|[\\/]v1[\\/]/.test(abs) || /\.(test|spec)\.tsx$/.test(abs))
579
- continue;
580
- files.push({
581
- path: abs,
582
- content: await Bun.file(abs).text().catch(() => "")
583
- });
584
- }
585
- const duplicates = findInlineRecipeDuplicates2(recipes, files);
586
- if (duplicates.length === 0)
587
- continue;
588
- const preview = duplicates.slice(0, 3).map((duplicate) => `${path.relative(workspace.workspaceRoot, duplicate.path)}:${duplicate.line}`).join(", ");
589
- diagnostics.push({
590
- severity: "warning",
591
- code: "recipe-inline-duplicate",
592
- path: path.join(sys.path, "ui/Recipe"),
593
- message: `${sys.name}: ${duplicates.length} inline className(s) re-author a recipe fingerprint (${preview}${duplicates.length > 3 ? ", \u2026" : ""}) \u2014 consume the recipe instead.`
594
- });
595
- }
596
- const scanNames = async (uiDirPath, basename) => new Set(scanRecipes2(await collectRecipeSources2(uiDirPath, "ui", basename)).map((info) => info.name));
597
- const declaredByImport = new Map;
598
- declaredByImport.set("akanjs/ui", await scanNames(path.join(workspace.workspaceRoot, "pkgs/akanjs/ui"), "recipe"));
599
- for (const sys of [...context.apps, ...context.libs])
600
- declaredByImport.set(`@${sys.path}/ui`, await scanNames(path.join(workspace.workspaceRoot, sys.path, "ui")));
601
- const sectionOf = (content, heading) => {
602
- const match = new RegExp(`^${heading}$`, "m").exec(content);
603
- if (!match)
604
- return "";
605
- const section = content.slice(match.index);
606
- const sectionEnd = section.indexOf(`
607
- ## `, 1);
608
- return sectionEnd === -1 ? section : section.slice(0, sectionEnd);
609
- };
610
- const listedByImport = (body) => {
611
- const groups = new Map;
612
- let current = null;
613
- for (const line of body.split(`
614
- `)) {
615
- const group = /^Import from `([^`]+)`:/.exec(line);
616
- if (group) {
617
- current = groups.get(group[1]) ?? new Set;
618
- groups.set(group[1], current);
619
- continue;
620
- }
621
- const item = /^- `([A-Za-z0-9_$]+)`/.exec(line);
622
- if (item && current)
623
- current.add(item[1]);
624
- else if (!item)
625
- current = null;
626
- }
627
- return groups;
628
- };
629
- const pushIndexDiagnostic = (indexPath, missing, stale, repairCommand) => {
630
- if (missing.length === 0 && stale.length === 0)
631
- return;
632
- const parts = [
633
- missing.length > 0 ? `${missing.length} declared but unlisted (${missing.slice(0, 5).join(", ")})` : "",
634
- stale.length > 0 ? `${stale.length} listed but gone (${stale.slice(0, 5).join(", ")})` : ""
635
- ].filter(Boolean);
636
- report({
637
- severity: "error",
638
- code: "recipe-index-stale",
639
- path: indexPath,
640
- message: `${indexPath} recipe index is out of date \u2014 ${parts.join("; ")}. Agents read this list as authoritative.`
641
- }, repairAction("generated", repairCommand, "Regenerate the recipe index from the scanned recipes.", true));
642
- };
643
- const frameworkDeclared = declaredByImport.get("akanjs/ui") ?? new Set;
644
- if (frameworkDeclared.size > 0) {
645
- const agentsMd = await Bun.file(path.join(workspace.workspaceRoot, "AGENTS.md")).text().catch(() => "");
646
- const listed = listedByImport(sectionOf(agentsMd, "## Recipes")).get("akanjs/ui") ?? new Set;
647
- pushIndexDiagnostic("AGENTS.md", [...frameworkDeclared].filter((name) => !listed.has(name)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0), [...listed].filter((name) => !frameworkDeclared.has(name)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0), "akan agent install agents-md");
648
- }
649
- for (const sys of [...context.apps, ...context.libs]) {
650
- const own = declaredByImport.get(`@${sys.path}/ui`) ?? new Set;
651
- const scopeMd = await Bun.file(path.join(workspace.workspaceRoot, sys.path, "AGENTS.md")).text().catch(() => "");
652
- const groups = listedByImport(sectionOf(scopeMd, "## Recipes In Scope"));
653
- const ownListed = groups.get(`@${sys.path}/ui`) ?? new Set;
654
- const missing = [...own].filter((name) => !ownListed.has(name)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
655
- const stale = [...groups.entries()].flatMap(([importFrom, names]) => [...names].filter((name) => !(declaredByImport.get(importFrom) ?? new Set).has(name))).sort();
656
- pushIndexDiagnostic(`${sys.path}/AGENTS.md`, missing, stale, `akan sync ${sys.name}`);
657
- }
658
- const scopedDiagnostics = diagnostics.map((diagnostic) => ({
659
- ...diagnostic,
660
- scope: workflowPaths.length ? isWorkflowRelatedDiagnostic(diagnostic, workflowPaths) ? "workflow" : "baseline" : diagnostic.scope,
661
- context: workflowPaths.length ? { ...diagnostic.context, paths: workflowPaths } : diagnostic.context
662
- }));
663
- const workflowDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "workflow");
664
- const baselineDiagnostics = scopedDiagnostics.filter((diagnostic) => diagnostic.scope === "baseline");
665
- return {
666
- schemaVersion: 1,
667
- repoName: context.repoName,
668
- root: context.root,
669
- strict,
670
- status: scopedDiagnostics.some((diagnostic) => diagnostic.severity === "error") ? "failed" : "passed",
671
- diagnostics: scopedDiagnostics,
672
- generatedFiles: context.generatedFiles,
673
- generatedFilesFreshness: await generatedFreshnessFromStates(workspace),
674
- validationCommands: context.validationCommands,
675
- repairActions,
676
- ...workflowPaths.length ? { baselineDiagnostics, workflowDiagnostics } : {}
677
- };
747
+ const systems = [...context.apps, ...context.libs];
748
+ const findings = new DoctorFindings;
749
+ await RootShapeCheck.run(workspace, systems, findings);
750
+ await AgentGuideCheck.run(workspace, systems, findings);
751
+ await ConfigLeftoverCheck.run(workspace, systems, findings);
752
+ await ModuleShapeCheck.run(workspace, systems, findings, { strict });
753
+ await RecipeDuplicateCheck.run(workspace, systems, findings);
754
+ await RecipeIndexCheck.run(workspace, systems, findings);
755
+ return await findings.result(workspace, context, { strict, workflowPaths });
678
756
  }
679
757
  static findModules(context, moduleName, { app = null } = {}) {
680
758
  const modules = [...context.apps, ...context.libs].filter((sys) => !app || sys.name === app).flatMap((sys) => sys.modules);