@akanjs/cli 3.0.0-alpha.8 → 3.0.0-alpha.80

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 (152) hide show
  1. package/.build-stamp +1 -1
  2. package/README.ko.md +1 -1
  3. package/README.md +1 -1
  4. package/{abstractCompactor-e5yq60qz.js → abstractCompactor-pwc6d6yk.js} +3 -5
  5. package/{agent.command-pggr92jj.js → agent.command-180hh0ye.js} +11 -12
  6. package/{application.command-692yap1d.js → application.command-gmcgen9y.js} +59 -35
  7. package/{applicationBuildRunner-ha3y8ew8.js → applicationBuildRunner-tavpx3fv.js} +22 -20
  8. package/{applicationReleasePackager-gg8ccbeh.js → applicationReleasePackager-ktjt0erc.js} +8 -9
  9. package/buildBatch.proc.js +12 -13
  10. package/capacitorApp-kwa67kzs.js +12 -0
  11. package/{cloud.command-wqfsyzv2.js → cloud.command-gpq7qxrc.js} +15 -17
  12. package/commandManifest.json +1 -1
  13. package/{context.command-9bxtdn0w.js → context.command-dk2m2sjx.js} +19 -22
  14. package/dependencyScanner-c64m6fxp.js +8 -0
  15. package/fleet.command-3bkyyd3a.js +836 -0
  16. package/getDirname-dr3jz1xg.js +7 -0
  17. package/{guideline.command-nfqahxex.js → guideline.command-w6ddv13r.js} +16 -17
  18. package/guidelines/agentRule/agentRule.generate.json +31 -0
  19. package/guidelines/agentRule/agentRule.instruction.md +525 -0
  20. package/guidelines/conventions/conventions.generate.json +25 -0
  21. package/guidelines/conventions/conventions.instruction.md +847 -0
  22. package/guidelines/cssRule/cssRule.instruction.md +7 -0
  23. package/guidelines/framework/framework.generate.json +3 -2
  24. package/guidelines/framework/framework.instruction.md +1 -9
  25. package/guidelines/mcpRule/mcpRule.generate.json +25 -0
  26. package/guidelines/mcpRule/mcpRule.instruction.md +217 -0
  27. package/guidelines/queryRule/queryRule.generate.json +31 -0
  28. package/guidelines/queryRule/queryRule.instruction.md +143 -0
  29. package/guidelines/runtimeRule/runtimeRule.generate.json +25 -0
  30. package/guidelines/runtimeRule/runtimeRule.instruction.md +176 -0
  31. package/guidelines/ssrRule/ssrRule.instruction.md +49 -5
  32. package/guidelines/transportRule/transportRule.generate.json +31 -0
  33. package/guidelines/transportRule/transportRule.instruction.md +60 -0
  34. package/guidelines/workspaceOnboarding/workspaceOnboarding.generate.json +24 -0
  35. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +263 -0
  36. package/guidelines/workspaceRecipes/workspaceRecipes.generate.json +33 -0
  37. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +402 -0
  38. package/incrementalBuilder.proc.js +21 -22
  39. package/{index-4hek879p.js → index-1kzsn94d.js} +1 -1
  40. package/{index-p3f4q532.js → index-3c9n3nt8.js} +31 -30
  41. package/index-3d9y066c.js +76 -0
  42. package/{index-76rn3g2c.js → index-47pj3aee.js} +4 -4
  43. package/{index-gex7c8kd.js → index-5n0hf8r9.js} +65 -38
  44. package/{index-mssqn2sq.js → index-5y7qba1c.js} +79 -33
  45. package/index-6wwzs1bc.js +7 -0
  46. package/{index-wnp7hwq7.js → index-92zztqy1.js} +7 -7
  47. package/{index-fgc8r6dj.js → index-a5vmm6x4.js} +3 -1
  48. package/{index-azv0xjb5.js → index-a8h184wr.js} +15 -11
  49. package/{index-67546d0j.js → index-ayy5ecax.js} +1 -1
  50. package/{index-xhgtkekh.js → index-b2nt0w0k.js} +27 -27
  51. package/{index-xys926f2.js → index-by5gpp8x.js} +4 -4
  52. package/{index-bz2sfzzt.js → index-cd5x18qh.js} +32 -32
  53. package/{index-bjpxzr6s.js → index-ctphds8v.js} +1 -1
  54. package/{index-w6wbb612.js → index-dq6wq1tv.js} +94 -61
  55. package/{index-js368gk9.js → index-ee8z8adx.js} +13 -13
  56. package/{index-5dw57f0d.js → index-f7wewj2v.js} +155 -76
  57. package/{index-6rhabeev.js → index-ft1sfjz0.js} +36 -25
  58. package/{index-7myvn0f0.js → index-h7yw2z9n.js} +7 -7
  59. package/{index-5pmx7bkg.js → index-j9vnq8tr.js} +18 -18
  60. package/{index-vg0sj9nc.js → index-k1n0h7dk.js} +840 -201
  61. package/{index-vtj3zps1.js → index-k86zc21w.js} +57 -57
  62. package/{index-46tjzh6s.js → index-mfm35dhh.js} +29 -29
  63. package/{index-xjd3rqzj.js → index-n68jx79w.js} +6 -15
  64. package/{index-ztpw544k.js → index-qcracvc9.js} +8 -8
  65. package/{index-2c3e2xh8.js → index-saheq2bs.js} +4 -4
  66. package/{index-gmy45vz2.js → index-v0s24t8j.js} +14 -14
  67. package/{index-0cj2zxbm.js → index-wet2ytnr.js} +12 -11
  68. package/{index-j9cxndc0.js → index-x23688ar.js} +12 -7
  69. package/index-xnhf8tr9.js +109 -0
  70. package/{index-a1e0j63x.js → index-xxe90kqy.js} +58 -25
  71. package/{index-qb61h0k7.js → index-z3c9mmw4.js} +1098 -1360
  72. package/index.js +22 -24
  73. package/{library.command-md9715jz.js → library.command-wpedct6c.js} +11 -9
  74. package/{localRegistry.command-exkbamyj.js → localRegistry.command-pjdxa01g.js} +20 -22
  75. package/{module.command-w5aaddxk.js → module.command-8n4kct3e.js} +13 -15
  76. package/{package.command-yfkrcy0z.js → package.command-fcbd0b1d.js} +8 -9
  77. package/package.json +5 -7
  78. package/{page.command-echbavp4.js → page.command-x4379grq.js} +7 -8
  79. package/{primitive.command-9fbhspw2.js → primitive.command-8etmnqhq.js} +13 -15
  80. package/{quality.command-3pnt9yep.js → quality.command-hfx7z8yr.js} +226 -104
  81. package/recipeScanner-fpagtgc1.js +11 -0
  82. package/{repair.command-carj4vax.js → repair.command-j0fs5qkz.js} +12 -13
  83. package/{routeSourceValidator-e4jmbfcx.js → routeSourceValidator-ze6x894c.js} +0 -2
  84. package/{scalar.command-51ryzypc.js → scalar.command-2emk89eh.js} +11 -13
  85. package/templates/app/env/env.client.debug.ts.template +1 -5
  86. package/templates/app/env/env.client.develop.ts.template +1 -5
  87. package/templates/app/env/env.client.local.ts.template +1 -5
  88. package/templates/app/env/env.client.main.ts.template +1 -5
  89. package/templates/app/env/env.client.testing.ts.template +1 -5
  90. package/templates/app/env/env.client.type.ts +2 -6
  91. package/templates/app/env/env.server.debug.ts.template +1 -5
  92. package/templates/app/env/env.server.develop.ts.template +1 -5
  93. package/templates/app/env/env.server.local.ts.template +1 -5
  94. package/templates/app/env/env.server.main.ts.template +1 -5
  95. package/templates/app/main.ts +3 -1
  96. package/templates/appSample/lib/task/task.signal.ts +11 -6
  97. package/templates/appSample/srvkit/AuthGuard.ts +9 -5
  98. package/templates/appSample/srvkit/SessionInternalArg.ts +4 -3
  99. package/templates/crudPages/[__model__Id]/edit/page.tsx +6 -6
  100. package/templates/crudPages/[__model__Id]/page.tsx +10 -13
  101. package/templates/crudPages/new/page.tsx +6 -6
  102. package/templates/crudPages/page.tsx +9 -9
  103. package/templates/crudSinglePage/page.tsx +11 -7
  104. package/templates/env/_env.server.type.ts +7 -5
  105. package/templates/lib/db.ts +1 -1
  106. package/templates/lib/dict.ts +1 -1
  107. package/templates/lib/sig.ts +1 -1
  108. package/templates/lib/srv.ts +6 -2
  109. package/templates/module/__Model__.Util.tsx +1 -1
  110. package/templates/module/__Model__.Zone.tsx +3 -5
  111. package/templates/module/__model__.dictionary.ts +4 -1
  112. package/templates/module/__model__.signal.ts +2 -3
  113. package/templates/module/__model__.store.ts +1 -2
  114. package/templates/workspaceRoot/.gitignore.template +0 -1
  115. package/templates/workspaceRoot/AGENTS.md.template +4 -972
  116. package/templates/workspaceRoot/CLAUDE.md.template +19 -0
  117. package/templates/workspaceRoot/biome.json.template +4 -244
  118. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +10 -14
  119. package/templates/workspaceRoot/docs/GENERATED.md.template +12 -10
  120. package/templates/workspaceRoot/package.json.template +2 -4
  121. package/typeChecker-3xgrzc2v.js +7 -0
  122. package/typecheck.proc.js +4 -5
  123. package/{workflow.command-91wmvm8k.js → workflow.command-cvpmzwjg.js} +21 -23
  124. package/{workspace.command-wa10mfd9.js → workspace.command-mbb5s3wx.js} +108 -91
  125. package/capacitorApp-p0z5yab2.js +0 -60
  126. package/dependencyScanner-f6grrep3.js +0 -9
  127. package/index-mxvakhsm.js +0 -66
  128. package/index-r24hmh0q.js +0 -4
  129. package/recipeScanner-tghkzrrt.js +0 -12
  130. package/templates/workspaceRoot/.cursor/rules/akan-page-routing.mdc.template +0 -43
  131. package/templates/workspaceRoot/.cursor/rules/akan-sync-conventions.mdc.template +0 -34
  132. package/templates/workspaceRoot/.cursor/rules/application-test-commands.mdc.template +0 -16
  133. package/templates/workspaceRoot/.cursor/rules/change-scope.mdc.template +0 -12
  134. package/templates/workspaceRoot/.cursor/rules/client-server-boundaries.mdc.template +0 -18
  135. package/templates/workspaceRoot/.cursor/rules/coding-comments.mdc.template +0 -25
  136. package/templates/workspaceRoot/.cursor/rules/coding-style.mdc.template +0 -44
  137. package/templates/workspaceRoot/.cursor/rules/domain-module-conventions.mdc.template +0 -17
  138. package/templates/workspaceRoot/.cursor/rules/format-lint.mdc.template +0 -12
  139. package/templates/workspaceRoot/.cursor/rules/lint-enforced-rules.mdc.template +0 -19
  140. package/templates/workspaceRoot/.cursor/rules/module-file-playbook.mdc.template +0 -62
  141. package/templates/workspaceRoot/.cursor/rules/naming-conventions.mdc.template +0 -15
  142. package/templates/workspaceRoot/.cursor/rules/react-component-style.mdc.template +0 -21
  143. package/templates/workspaceRoot/.cursor/rules/repo-overview.mdc.template +0 -17
  144. package/templates/workspaceRoot/.cursor/rules/scalar-modeling.mdc.template +0 -99
  145. package/templates/workspaceRoot/.cursor/rules/secrets-and-env.mdc.template +0 -13
  146. package/templates/workspaceRoot/.cursor/rules/service-signal-conventions.mdc.template +0 -83
  147. package/templates/workspaceRoot/.cursor/rules/srvkit-adapters-and-guards.mdc.template +0 -50
  148. package/templates/workspaceRoot/.cursor/rules/ssr-first.mdc.template +0 -59
  149. package/templates/workspaceRoot/.cursor/rules/typescript-imports.mdc.template +0 -16
  150. package/typeChecker-kravn7ns.js +0 -8
  151. /package/{index-0wae5ebk.js → index-meh558jy.js} +0 -0
  152. /package/{index-ss469dec.js → index-nz8prx9g.js} +0 -0
@@ -0,0 +1,847 @@
1
+ ## Repo Overview
2
+
3
+ - Akan.js is a full-stack TypeScript framework for building all-stack applications at once.
4
+ - Write one line and deploy across web, app, server, database, and infrastructure.
5
+ - Akan prioritizes actual business code by abstracting technical implementation details as much as possible.
6
+ - The goal is minimal code, high performance, and type-safe services that can deploy to web, mobile, server, and DB infrastructure together.
7
+ - This is a Bun-first Akan.js monorepo.
8
+ - Main top-level areas are `apps/`, `libs/`, `pkgs/`, and `infra/`.
9
+ - `apps/<app>` contains app-level pages, domain code, UI, env files, and `akan.config.ts`.
10
+ - `libs/*` contains shared domain and utility libraries.
11
+ - `pkgs/akanjs/*` contains framework, runtime, and tooling facets published through the single `akanjs` package. Prefer extending existing Akan facets before adding new framework-level patterns.
12
+ - `infra/` contains Helm, deployment templates, edge configs, and Jenkins env/secret scripts.
13
+
14
+ ## Change Scope
15
+
16
+ - Keep edits scoped to the requested task and the directly related files.
17
+ - Do not reformat unrelated files or rewrite nearby code just for style.
18
+ - Do not revert or overwrite unrelated user changes in a dirty working tree.
19
+ - Prefer established nearby patterns over introducing a new abstraction.
20
+ - Add new abstractions only when they remove real duplication or match an existing project pattern.
21
+
22
+ ## Deep-Dive Guidelines
23
+
24
+ This file carries the rules. The reasoning, the measurements, and the per-feature edge cases live in guidelines
25
+ you fetch on demand — `get_guideline` with the name, or `akan guideline show <name>`. Fetch the relevant one
26
+ **before** a deep pass on that area; a section below that points at one is a summary, not the whole contract.
27
+
28
+ | name | covers |
29
+ |---|---|
30
+ | `ssrRule` | server-share targets, the `akan.ssr.*` warnings, the client-boundary playbook |
31
+ | `runtimeRule` | `web` / `csr` surfaces, gateway vs solo processes, logging, the generated image, shipped assets |
32
+ | `queryRule` | slices and hydration, the generated filter methods, full-text search, cascade removal |
33
+ | `transportRule` | guards across HTTP and websocket, socket identity and cleanup, binary pubsub, mutation verbs |
34
+ | `mcpRule` | MCP configuration, wire behaviour, resource URIs, OAuth metadata, protocol revisions |
35
+ | `agentRule` | the in-page agent's chat options, zones, slash commands, transcript compaction |
36
+ | `cssRule` | the full semantic token set for a theme pass |
37
+ | `componentRule` | the `_overrides.tsx` slot list and drop-in component patterns |
38
+ | `recipeRule` | authoring and consuming Tailwind-variant recipes |
39
+ | `workspaceRecipes` | worked step-by-step recipes and the auto-generated API reference |
40
+
41
+ ## Lint-Enforced Rules (These Break The Build)
42
+
43
+ Enforced by `biome.json`, which extends `@akanjs/devkit/biome.base.json` — that file scopes every grit plugin in
44
+ `@akanjs/devkit/lint/` to the paths it applies to. Several rules produce output that looks wrong; do not "fix" it
45
+ back.
46
+
47
+ - **Never hand-order Tailwind classes.** `nursery/useSortedClasses` is an error and also sorts the string
48
+ arguments to `cn()`. Sorter output such as `font-bold text-2xl text-foreground` or `border-foreground/5 border-t`
49
+ is correct. Write the classes in any order, run the formatter, leave the result.
50
+ - **Stay inside the color vocabulary.** Vocabulary closure strips the raw Tailwind palette, so these render as no
51
+ CSS and fail lint: raw palette classes (`bg-blue-500`), arbitrary color values (`bg-[#3b82f6]`), an arbitrary
52
+ class built by interpolation, daisyUI legacy classes (`btn-primary`, `card-body`) and its dropped color slots
53
+ (`bg-base-100`, `text-base-content`, `text-primary-content`, `bg-error` — use `background`/`muted`/`border`,
54
+ `foreground`, `<color>-foreground`, `destructive`), and color literals in `style={{...}}`. Use semantic tokens
55
+ (`bg-primary`, `text-foreground/70`). A legitimate fixed color (OS-chrome mockups, data-viz) takes a
56
+ `// biome-ignore lint/plugin: <reason>`. (`no-raw-palette-class`, `no-arbitrary-color`, `no-daisyui-legacy-class`,
57
+ `no-inline-color`, `no-interpolated-arbitrary-class`)
58
+ - **Never `throw new Error`.** Throw `new Err("<module>.error.<key>")` and register the key as `[en, ko]` in that
59
+ module's dictionary `.error({})`. Import `Err` from `"../dict"` on the server and from `"@libs/<lib>/client"` or
60
+ `"@apps/<app>/client"` in UI. `no-throw-raw-error.grit` exempts tests, `*.constant.ts`, `common/**`, and `env/**`
61
+ — the last two have no legal `Err` import path, so keep throwing code out of them.
62
+ - **Never import a third-party package** from `page/**`, from any barrel, or from any
63
+ `*.{constant,dictionary,document,service,signal,store}.ts` / `*.{Template,Unit,Util,View,Zone}.tsx`
64
+ (`no-import-external-library.grit`). Re-export the symbol through a lib first. One-line re-export shims in a lib's
65
+ `common/`, `webkit/`, or `ui/` exist for exactly this reason — they are load-bearing, not cruft.
66
+ - **`#private` is banned in exactly four file suffixes:** `*.constant.ts`, `*.document.ts`, `*.service.ts`, and
67
+ `*.store.ts` (`no-js-private-class-method.grit`). The rule is scoped by file path, not by class shape, so
68
+ `#private` remains the house style everywhere under `srvkit/`, including `adapt()` adapter classes.
69
+ - **No `console.log` / `console.debug`.** Only `assert`, `error`, `info`, and `warn` are allowed. Server code uses
70
+ the injected `this.logger.*` or `new Logger("ClassName")`.
71
+ - **Never call `logger.log()` / `Logger.log()`** (`no-deprecated-log-level.grit`). The ladder is `trace verbose
72
+ debug info warn error`; `log` was a seventh tier *below* `info` that `AKAN_PUBLIC_LOG_LEVEL=info` silently
73
+ dropped. The method is kept and emits at `info`, so a call reads like a distinct level and is not one — write
74
+ `.info()`.
75
+ - **Never write a `//!` marker in browser-reachable code** — `ui/`, `webkit/`, `common/`, `page/**/*.tsx`,
76
+ `*.constant.ts`, `*.store.ts`, and the five module component suffixes (`no-bang-comment-in-client.grit`). Bun
77
+ classifies `//!` and `/*!` as legal comments and keeps them through minification, so the note ships to every
78
+ visitor. Use `// FIXME:` there; `//!` stays legal in server, `srvkit/`, and CLI files.
79
+ - **Never return a value from a store action** (`no-return-in-store-action.grit`). Every method of a `store(...)`
80
+ class dispatches through `st.do.<action>()`, typed `void` / `Promise<void>`, so the value is unreachable — write
81
+ it into state with `this.set({ ... })`. A bare `return;` guard, a `return` inside a nested callback, a getter,
82
+ and a `static` helper are all still fine.
83
+ - **Never redeclare a generated CRUD endpoint name** in `*.signal.ts` (`no-redeclare-predefined-endpoint.grit`).
84
+ - **Never type a `*.Util.tsx` / `*.Zone.tsx` prop as a `cnst` model** (`no-model-type-in-util-zone.grit`). Those two
85
+ roles are always client components, so a `cnst.Banner` / `cnst.LightBanner` prop is a class instance the server
86
+ has to hand across the boundary; take `bannerId: string` and read the model from the store instead. Only prop
87
+ positions are read, and only shapes that are actually an instance. Exempt: an indexed enum access
88
+ (`cnst.<Enum>["value"]`), a `ClientInit` / `ClientView` / `ClientEdit` or `ModelsProps<…>` type argument, a
89
+ function-typed prop, and any `cnst` type that never leaves the file. Other indexed accesses
90
+ (`ModelProps<"setting", cnst.LightSetting>`, `cnst.Banner["image"]`) stay flagged.
91
+ - **Never wrap a form setter in a pass-through arrow** (`no-unpublished-form-setter.grit`).
92
+ `onChange={(type) => st.do.setTypeOnTicket(type)}` runs identically to `onChange={st.do.setTypeOnTicket}`, but
93
+ the arrow is a fresh anonymous closure, so the control emits no `data-akan-action` and publishes no agent tool
94
+ for the field — a silent failure in two lines that read the same. A wrapper that transforms the value, adds a
95
+ statement, or writes a nested path with `writeOnX` stays legal; publish that one with an explicit `st.tool`.
96
+ - **No deep imports past a barrel** (`no-deep-internal-import.grit`). Cross-module constant references such as
97
+ `../map/map.constant` are the sanctioned exception.
98
+ - **Never import across the client/server boundary.** Client files (`ui/`, `webkit/`, `page/`, `*.store.ts`, every
99
+ `.tsx`) may not import a `*.document.ts` / `*.dictionary.ts` / `*.service.ts` / `*.signal.ts`, `srvkit/`, a
100
+ package `server` entrypoint, or the `db` / `srv` / `sig` / `dict` / `option` / `useServer` barrels
101
+ (`no-import-server-in-client.grit`). Server files (those four suffixes plus `srvkit/`) may not import a
102
+ `*.store.ts`, a module component, `ui/`, `webkit/`, a package `client` entrypoint, or the `st` / `store` /
103
+ `useClient` barrels (`no-import-client-in-server.grit`). Shared files — `common/` and `*.constant.ts` — are held
104
+ to **both**, so they reach neither side. `import type` is erased before bundling and stays legal in every
105
+ direction; a mixed value-and-type import is not exempt. Scoped to `apps/**` and `libs/**`.
106
+ - **Server-component discipline** is enforced on `page/**`, `*.Unit.tsx`, and `*.View.tsx`
107
+ (`no-import-client-functions.grit`, `no-use-client-in-server.grit`, `non-scalar-props-restricted.grit`).
108
+ - **Never write an async component outside `page/`** (`no-async-component-in-ui.grit`, scoped to
109
+ `{apps,libs}/**/ui/**/*.tsx`). React has no async client component, so a `ui/` component that awaits breaks as
110
+ soon as a client parent renders it, and the load drops below the route, which could have started it before the
111
+ first byte. Await in the page — or hand an unawaited `fetch.*` field to a `Zone` as an `init` / `view` prop, or
112
+ to a `<Load.Stream of={…}>` that awaits it behind a boundary of its own — and take the resolved data as a prop.
113
+ Only a PascalCase binding whose own initializer is `async` is matched, so an async handler inside a synchronous
114
+ component and `lazy(async () => import(…))` are untouched.
115
+ - **Never call `fetch.init*` from a client file** (`no-init-fetch-in-client.grit`). `fetch.init<Model><Suffix>` and
116
+ `fetch.get<Model>Init<Suffix>` compose the slice's list and insight queries into the hydration snapshot that
117
+ `Load.Units` / `Load.View` seed the store from. From a route it resolves before the first byte; after hydration
118
+ it is two extra round-trips for a shell the browser already painted. Load it in the page and pass the result
119
+ down as an `init` prop — or hand the unawaited `x<Model>Init<Suffix>` promise across — and reload from the client
120
+ through the generated `st.do.init<Model><Suffix>()`. Gated on the real `"use client"` directive plus
121
+ `*.store.ts`, and matched by shape (`init` + `Capitalize<refName>` + `Capitalize<suffix>`), so a hand-written
122
+ `initPayment` is out.
123
+ - `noArrayIndexKey` and `useExhaustiveDependencies` are **off** on purpose: `key={idx}` for embedded scalars and
124
+ short dependency arrays are intentional, not oversights.
125
+ - **A grit plugin diagnostic is suppressed as `lint/plugin`, not `plugin`** — `// biome-ignore lint/plugin: <reason>`
126
+ for one line, `// biome-ignore-all lint/plugin: <reason>` for a file. The bare `// biome-ignore plugin:` form
127
+ Biome's own category name suggests does nothing. The module-convention plugins apply to `apps/**` and `libs/**`
128
+ only, so a plain package under `pkgs/` never needs the escape hatch.
129
+ - **`biome.json` is strict JSON — a comment in it breaks config resolution.** Biome does not report the parse
130
+ error; it falls back to discovery and aborts on whatever nested config the walk finds. Rename the file to
131
+ `biome.jsonc` to document a disabled rule.
132
+ - **`akan lint` prints up to 200 diagnostics** (`--max-diagnostics <n>`, `0` for no limit). Biome's own default is
133
+ 20 with no count, which reads as progress when the mix of findings merely changed.
134
+
135
+ ## Coding Style (`**/*.{ts,tsx}`)
136
+
137
+ - For large units of work, prefer declaring a class and running the flow through an instance instead of scattering many standalone functions.
138
+ - Prefer class methods or `static` methods over unrelated top-level helper functions when the logic belongs to a class-level workflow.
139
+ - Prefer ECMAScript `#private` fields and methods over TypeScript `private`, except in the four suffixes where `#private` is lint-banned (`*.constant.ts`, `*.document.ts`, `*.service.ts`, `*.store.ts`) — those use TypeScript `private`. `#private` is the house style under `srvkit/`, including `adapt()` classes.
140
+ - In files that declare a class, avoid top-level functions or variables when they can reasonably live inside the class.
141
+ - Prefer `const` function expressions over `function` declarations unless hoisting, overloads, generators, or framework conventions make `function` the better fit.
142
+ - Prefer declaring only one class per file; split the file when two or more class declarations are needed.
143
+ - For class-centered modules, prefer noun-style filenames that match the primary class name, such as `RouteClientBuilder.ts`, instead of verb-style wrapper filenames like `buildRouteClient.ts`.
144
+ - Avoid keeping exported functions that only instantiate a class and immediately call one method. Prefer migrating callers to instantiate the class directly.
145
+ - Except for React component files or convention files, TypeScript filenames should use camelCase.
146
+ - In React components, keep one-off `className` strings inline. Only extract class name constants when the class is reused, conditionally composed, or too large to read comfortably in JSX.
147
+
148
+ ### File Size And Duplication
149
+
150
+ - Keep files small. The house median is well under 50 lines; split a component before it reaches ~150 lines rather than adding section comments.
151
+ - Ship every scaffold file even when it is empty — `export class XInternal extends internal(srv.x, () => ({})) {}`, empty dictionary stages, the `// state` / `// action` markers in an empty store. They mark where things go.
152
+ - Never add a sibling helper file inside `lib/<model>/`. Helpers go to `common/`, `webkit/`, `srvkit/`, or `ui/`.
153
+ - Prefer duplication to premature abstraction at the leaf. Near-identical sibling modules and per-vendor pages are deliberately copied, not parameterised. Copy the file and change the literals; share enums by import only.
154
+
155
+ ### TypeScript Shape
156
+
157
+ - Use `interface` for object shapes and `type` only for unions and aliases.
158
+ - Declare `interface <ComponentName>Props` immediately above the component with no blank line between, and put `className?: string` first. Name it for the component (`CardProps`, `WorldProps`), never for the model. Do not export it unless a sibling imports it.
159
+ - Never use a non-null assertion. Narrow with `?.`, an early return, or a type predicate such as `.filter((id): id is string => !!id)`.
160
+ - Escape with `as unknown as T`. Never `as any`.
161
+ - Never annotate a component's return type. Annotate a helper only when the return is a union, a tuple, or a type predicate.
162
+ - Use `as const` on every `enumOf(...)` array, every `via(Model, [...] as const, …)` Light tuple, and every module-scope lookup map. Never use the TypeScript `enum` keyword.
163
+ - Async functions carry no `Async` suffix.
164
+
165
+ ### Test Code
166
+
167
+ - Write TypeScript tests with Bun's test runner and import `describe`, `expect`, and `test` from `bun:test`.
168
+ - Keep tests colocated with the source they cover using `*.test.ts` or `*.spec.ts`, following the existing nearby pattern.
169
+ - Prefer focused behavior tests for public contracts and edge cases over implementation-detail assertions.
170
+ - Run package suites with `bun run akan test <pkg>` from the repo root, or `cd <pkg> && bun test --isolate`. Plain `bun test` without `--isolate` shares one global object across test files and fails dozens of tests from cross-file state pollution (`bunfig.toml` `[test] isolate` is not honored as of Bun 1.3), and running `bun test` from the repo root breaks subprocess stdio pipes.
171
+ - Split signal tests in two. `<model>.signal.spec.ts` holds reusable fixtures built on `sampleOf(cnst.XInput)` with explicit `Promise<cnst.X>` return types and **no assertions**. `<model>.signal.test.ts` holds the assertions: `describe("<Model> Signal")`, `let` fixtures at describe scope, one `beforeAll`, story-ordered `it`s, and negatives via `await expect(p).rejects.toThrow()`.
172
+ - `lib/user/user.signal.spec.ts` is the one place agent types are re-exported and re-typed; import `UserAgent` / `AdminAgent` from there rather than from the owning lib directly.
173
+ - A placeholder `it` with a descriptive title is an acceptable floor. Write a real suite when the behaviour is security-relevant.
174
+
175
+ ## Comments
176
+
177
+ Do not narrate code. Do document the thing the code cannot say. Both halves are the rule.
178
+
179
+ - Never add a comment that restates the identifier, the signature, or the control flow.
180
+ - Prefer clear names and structure so ordinary logic needs no explanation.
181
+ - Do not add JSDoc, section banners, or "why/how" comments for ordinary logic.
182
+ - Comment density tracks the layer, not the author: pages carry none, product `lib/` and `ui/` code stays under 1 %, and `srvkit/` adapters and `guards.ts` carry as much as the external constraints require.
183
+ - A comment is warranted for: a vendor spec or protocol quirk; an infrastructure constraint; a third-party library gotcha; security reasoning; why a rule that looks arbitrary is correct; a math derivation; a domain field's business meaning; a state transition above a document chain method; why an obvious alternative was rejected.
184
+ - In-code markers:
185
+ 1. `TODO` — unfinished work that must be tracked in-code
186
+ 2. `FIXME` — known broken or incorrect behavior that must be fixed
187
+ 3. `XXX` — dangerous / surprising hazard that a reader must not miss
188
+ 4. `//!` — disabled or must-fix code. **Server, `srvkit/`, and CLI files only.** Bun's bundler treats `//!`
189
+ (and `/*!`) as a legal comment and keeps it through minification, so in browser-reachable code the note
190
+ ships verbatim to every visitor. Use `// FIXME:` there instead; `no-bang-comment-in-client.grit` enforces it.
191
+ 5. `//?` — an explanatory aside
192
+ 6. `//*` — a design note
193
+ 7. Deletion caution — warn why removing a line or block would break something non-obvious
194
+ - Keep allowed comments one short line when possible.
195
+ - Every suppression carries a reason: `// biome-ignore lint/<rule>: <why>`. Never a bare disable block.
196
+ - Match nearby file style: if the surrounding code has few comments, keep it that way.
197
+
198
+ ## TypeScript And Imports (`**/*.{ts,tsx}`)
199
+
200
+ - Use Bun and ESM assumptions from the root `tsconfig.json`.
201
+ - Prefer path aliases over deep relative imports when crossing package boundaries.
202
+ - Use `akanjs/*` for framework facets, `@apps/*` for apps, `@libs/*` for shared libs, and `@contract/*` for contract code.
203
+ - Respect existing client/server entrypoints — `@libs/<lib>/client` / `@libs/<lib>/server` and `@apps/<app>/client` / `@apps/<app>/server`.
204
+ - Let Biome organize imports instead of manually reshuffling unrelated imports.
205
+ - Namespace the generated barrels in backend `.ts` files: `import * as cnst from "../cnst"`, `* as db`, `* as srv`. Use `import type * as srv` in services so the runtime graph stays lazy, and a value import in signals.
206
+ - In `.tsx` files use one flat named import from the package client path (`import { cnst, fetch, st, Ticket, usePage } from "@apps/<app>/client"`) — never a relative `../` import.
207
+
208
+ ## Formatting And Linting
209
+
210
+ - Use Biome as the formatter and linter.
211
+ - Format with `bun run akan lint <appName>` from the repo root.
212
+ - Keep formatting consistent with `biome.json`: 2-space indentation, 120 line width, and double quotes for JS/TS.
213
+ - Avoid adding new `console` usage except accepted methods such as `console.error`, `console.info`, and `console.warn`.
214
+ - Do not make broad formatting-only changes in unrelated files.
215
+
216
+ ## Client / Server Boundaries (`apps/**`, `libs/**`, `pkgs/akanjs/**`)
217
+
218
+ - Use `"use client";` at the top of client component files.
219
+ - Be careful when importing client-only code from page or layout modules.
220
+ - Keep page props serializable unless the existing route pattern clearly allows otherwise.
221
+ - In domain UI the boundary is mechanical, not a judgment call: `Template`, `Zone`, and `Util` are always client components with `"use client"` on line 1; `Unit` and `View` are always server components and never carry the directive.
222
+ - Preserve established domain file roles such as `.document.ts`, `.service.ts`, `.store.ts`, `.constant.ts`, and `.client.ts`.
223
+ - When unsure, inspect nearby files in the same app or package before introducing a new boundary pattern.
224
+
225
+ ## SSR First — Server Rendering Is The Default
226
+
227
+ Akan is SSR-first. Every JSX element that renders on the server ships as HTML and costs nothing to hydrate;
228
+ every element behind `"use client"` ships twice — as markup and as bundled JS that must re-run in the browser.
229
+ The boundary is not about which file *may* be client, it is about **how little** ends up on the client side.
230
+
231
+ **The default is server. `"use client"` is a cost you justify per component, not a habit.** A component earns the
232
+ directive only by using a client-only capability: a React hook, a JSX event handler, the store (`st.use.*` /
233
+ `st.do.*`), a browser global, or a client-only third-party package. Rendering markup, reading a param, calling
234
+ `l()`, and mapping over data are all server work.
235
+
236
+ Measure before and after with `akan quality ssr` (`--format json` for tooling). It prints the server render share
237
+ per app and lib — server-rendered JSX elements over total — and the SSR warnings below. Treat **50% server share
238
+ as the floor** for an app or lib and a **falling share as a regression**: if a change moves markup to the client,
239
+ say why in the PR or move it back.
240
+
241
+ ### What `akan quality ssr` Flags
242
+
243
+ | Rule | Means |
244
+ |---|---|
245
+ | `akan.ssr.unnecessary-use-client` | The directive is there but nothing in the file needs it. Delete it. |
246
+ | `akan.ssr.client-static-component` | A component in a client file renders real markup with zero client-only capability — pure server work sitting in the bundle. |
247
+ | `akan.ssr.client-static-markup` | A large subtree wraps one or two interactive touches. Split it: interaction stays client, markup goes server. |
248
+ | `akan.ssr.client-mount-load` | A `useEffect(…, [])` loads server data. The route can fetch it before the first byte. |
249
+ | `akan.ssr.module-missing-server-view` | A module renders only from `Template`/`Zone`/`Util` and has no `Unit`/`View` at all. |
250
+ | `akan.ssr.template-client-state` | A `Template` holds form state in `useState` instead of the store. |
251
+
252
+ A third-party client package or an `index_.tsx` `lazy()` boundary is a legitimate reason for the directive and is
253
+ not flagged. Interaction-driven `fetch.*` (a lookup inside `onClick`) is not flagged either — only mount-time loads
254
+ are, because those are the ones the server could have done.
255
+
256
+ ### Server-Side Implementation Playbook
257
+
258
+ 1. **Wrap the interaction, not the UI.** The smallest useful client component adds one behaviour and renders
259
+ `children` untouched, so the markup inside never reaches the bundle.
260
+ 2. **Split compound components so panels stay on the server.** `Tab` / `Tab.Menus` / `Tab.Menu` / `Tab.Panel` in
261
+ `akanjs/ui` is the shape: only the provider and menu hold state. Never one `"use client"` file with a mode
262
+ `useState` and every panel body inlined.
263
+ 3. **Sync state instead of fetching it.** The route calls `fetch.initXInY(...)` / `fetch.viewX(...)` and passes the
264
+ result into a `Zone` as an `init` / `view` prop; `Load.Units` / `Load.View` hydrate the store from it. Never a
265
+ `useEffect(…, [])` that fetches on mount.
266
+ 4. **Push the boundary down to the leaf that needs it.** A store-reading `Zone` should hold zero markup and
267
+ delegate to a server `View`.
268
+ 5. **Hand each promise across, not the awaited value.** `fetch.init<Model><Suffix>` / `view<Model>` / `edit<Model>`
269
+ are awaitable *and* destructurable: `const { xInitInY, xListInY } = fetch.initXInY(id)` hands out one promise
270
+ per field with both queries already in flight. Give `xInitInY` to a `Zone` and `xListInY` to a
271
+ `<Load.Stream of={…}>`; each renders behind its own boundary as its own data lands, so the page never waits
272
+ for the slowest. `await` still returns the old shape and keeps the whole section in the shell — which is what
273
+ SEO snapshots, prerendering and pre-hydration E2E read, so await what the page needs immediately and stream
274
+ the rest. `xListInY` / `xInsightInY` hold hydrated model instances that React Flight refuses as client props:
275
+ consume them in a server component, never as a `Zone` prop.
276
+ 6. **Use named `ReactNode` slots, not just `children`** — `Layout.Navbar` takes `title`, `back`, `left`, `right`,
277
+ and `children`, so a client shell composes server content in five places instead of absorbing it.
278
+ 7. **Let the server do the derived work.** Display and predicate logic belongs on `Light<Model>`; enum→class
279
+ lookups belong in a module-scope `as const` map.
280
+ 8. **Gate auth on the server** — `getSelf({ unauthorize: "/signin" })` in `_layout.tsx`, before any HTML is sent.
281
+ 9. **Prefer CSS over client state for pure visibility.** A `data-*` attribute plus `group-data-[…]` variants, or
282
+ `<details>`/`<summary>`, keeps both branches server-rendered.
283
+ 10. **Keep the heavy island out of the first load** — behind the `ui/<Folder>/index_.tsx` + `lazy()` pair.
284
+ `usePage()` and `l()` work in server components, so translation never forces a boundary.
285
+
286
+ Full version with code, the `Tab` composition example, and a review checklist: `get_guideline` with `ssrRule`.
287
+
288
+ ## Runtime & Build Configuration
289
+
290
+ What an app serves, how many processes it runs, where its logs go, and what ships in its image. All of it is
291
+ declared in `akan.config.ts` and narrowed — never widened — by an env at boot. Domain code reaches none of it.
292
+ Full contract: `get_guideline` with `runtimeRule`, or `akan guideline show runtimeRule`.
293
+
294
+ - **Web surfaces are `web: true | false | { csr: boolean }`.** `{ csr: false }` drops the mobile/CSR bundle,
295
+ `false` is an API-only build that serves nothing under `page/`. There is no CSR-without-SSR option, by type —
296
+ the CSR bundle inlines the stylesheet the SSR base artifact compiles. `AKAN_SSR` / `AKAN_CSR` narrow further at
297
+ runtime and can never switch a surface the build left out back on. `akan start` ignores `web` and keeps the
298
+ whole dev surface.
299
+ - **One traffic replica runs in the container's only process.** `AKAN_REPLICA=0,0,1` — the default everywhere —
300
+ has nothing to balance, so there is no gateway and no unix-socket proxy hop. Two or more replicas, a batch-only
301
+ replica, `AKAN_SOLO=false`, passing `replica` to `new AkanApp(...)`, or `akan start` all bring the gateway back.
302
+ The RSC worker is always its own process (`--conditions react-server`). A solo process answers
303
+ `/_akan/app/health`, `/_akan/app/metrics` and `/_akan/bench/ping` in the gateway's own shape, and owns the
304
+ rotating log file; nothing supervises it but the orchestrator's probes.
305
+ - **`main.ts` imports `AkanApp` from `akanjs/server/akanApp`, not the barrel** — the barrel re-exports
306
+ `AkanServer`, whose graph the gateway never runs. Keep entrypoint imports at the leaf.
307
+ - **Every `Logger` call builds a `LogRecord`** carrying `traceId`, `endpoint` and `origin` alongside the message,
308
+ so one request's lines share a trace. Request context is on by default, production included
309
+ (`AKAN_LOG_CONTEXT=0` opts out). **Give every sink a floor** — `Logger.addSink(sink, { minLevel })`; a sink with
310
+ none makes every `verbose` call render. **Never log per delivered record in anything that delivers records.**
311
+ Tail a running server with `akan logs <app>` (`--level --grep --endpoint --trace --child --role --origin
312
+ --since`, `--json`) or `.tail` / `.trace <id>` inside `akan console`.
313
+ - **`AKAN_LOG_FORMAT=ndjson` makes the container's stdout one JSON record per line, and the hub owner (gateway or
314
+ solo replica) its only writer** — every other server process turns its console off and forwards from
315
+ `AKAN_LOG_STDOUT_LEVEL` (default: the console level); a child's or the RSC worker's crash stack is wrapped as a
316
+ `raw=true` record instead of breaking the stream. Text stays the default; turn it on in the deployment.
317
+ `AKAN_LOG_STREAM_TOKEN` mounts `/_akan/app/logs` (SSE, `Last-Event-ID` resume, explicit `gap` events); unset,
318
+ the route does not exist. `AKAN_LOG_CANONICAL=1|slow` writes one `ok|error <endpoint> ms= status=` line per call;
319
+ `AKAN_LOG_FLIGHT=1` keeps each call's last 64 sub-level records and promotes them (`flight=true`) only when it
320
+ failed or ran past `AKAN_LOG_FLIGHT_MS`; `x-akan-debug` lowers one request to `trace` — in `local`, or with the
321
+ `AKAN_LOG_DEBUG_HEADER` secret. Structured values go in `LogRecord.attrs` via `Logger.emit(...)`; a key naming a
322
+ secret is `[redacted]` before the record exists.
323
+ - **`docker` is `string | { image, preRuns, postRuns, command }`** — a whole Dockerfile, or the parts Akan
324
+ assembles one from; the string form takes no contributions. The generated image installs `ca-certificates` and
325
+ `tzdata` and nothing else, so an app needing `ffmpeg` or Chromium declares it in `preRuns` / `postRuns`. A lib
326
+ declares the steps its own runtime needs and every mounting app inherits them.
327
+ - **`assets: { pruneFonts, keepFonts }`** trims from the `dist` copy of `public/` the fonts nothing reads; source
328
+ trees are never touched. A font with `optimize` on is a build input, not a runtime asset. `keepFonts` belongs to
329
+ the `akan.config.ts` that owns the font, written against that scope's own `public/`.
330
+
331
+ ## React Components And Styling (`**/*.tsx`)
332
+
333
+ - Components are `export const X = ({ … }: XProps) => { return (…); };` — arrow const with a block body. `export default` is reserved for pages, layouts, and `lazy()` targets.
334
+ - Never `React.FC`, never `defaultProps`, never `PropsWithChildren`. Defaults go in the destructuring (`prefix = ""`); children are typed `children: ReactNode`.
335
+ - `"use client"` on line 1 above the imports is mechanical by file role: every `.Zone.tsx`, `.Template.tsx`, and `.Util.tsx` has it; no `.Unit.tsx` or `.View.tsx` ever does. `usePage()` is legal in server files.
336
+ - Conditional render is `cond ? <X/> : null`. Never `{cond && <X/>}` — in a `className` context it renders the literal string `"false"`. Early `return null` is for guard clauses only.
337
+ - Never hand-roll loading, empty, or list states. Use `Load.Units` / `Load.View` / `Load.Edit` with `renderItem`, `renderList`, `renderView`, and `renderEmpty`; `<Empty />` for a bare placeholder; and `Model.New` / `Model.Edit` / `Model.SureToRemove` for CRUD modals. For data no `Load.*` covers, `<Load.Stream of={promise} fallback={…}>{(value) => …}</Load.Stream>` awaits one promise behind its own Suspense boundary; a resolved value renders in the shell with no boundary at all, so the same call site works either way.
338
+ - Avoid hooks. `useState` is for modal-open, tab, draft-input, and drag state only — never for server data. `useEffect` must be a genuine effect such as subscribe-with-cleanup or one-shot init. Prefer `Tab` over a `useState` mode switch. `.Template.tsx` files contain zero `useState`.
339
+ - Forms are entirely store-driven: `value={xForm.field}` with `onChange={st.do.setFieldOnX}`, the setter passed by reference. Always use `Field.*`, never a bare `<input>` for a model field. Nested rows use `st.do.writeOnX("payments.3.name", v)` plus the generated `add<Field>OnX` / `sub<Field>OnX`. **Passing the setter by reference is also what makes the framework emit `data-akan-action` / `data-akan-state`** on the control — the annotation an in-page agent, an E2E selector, and an external browser agent all read. Wrapping it in an inline arrow (`onChange={(v) => st.do.setFieldOnX(v)}`) silently drops that: a closure the caller wrote says nothing about what it does. Never hand-write a `data-akan-*` attribute.
340
+ - Read with `st.use.*` and write with `st.do.*`. Client components do not call `fetch.*`.
341
+ - Static class strings stay plain strings. Reach for `cn` only for a conditional or to merge an incoming `className`, and merge the caller last: `cn("base classes", cond && "extra", className)`. `cn` comes from `akanjs/client` (token-aware tailwind-merge) and is the only class-combining function — no `clsx` (removed), no raw `twMerge` imports, no object syntax (`{ x: cond }` → `cond && "x"`).
342
+ - Multi-slot components take extra named props (`wrapperClassName`, `bodyClassName`), never a `classNames` object.
343
+ - Hoist enum→class lookups to a module-scope `as const` map typed `{ [key in cnst.XStatus["value"]]: string }`. Do not use `Record<...>`. Escalate the map to `webkit/` when a second module needs it.
344
+ - Use `<Link>` from `akanjs/ui` for internal navigation; `<a>` only for `mailto:` and external links.
345
+
346
+ ## Naming And Language
347
+
348
+ - Component exports are role names — `Card`, `Sticker`, `General`, `Preview`, `Admin`, `World`, `Mesh`, `Remove`. The model comes from the namespace (`<Floor.Unit.Card>`), so never write `FloorCard`. `Util` exports are the endpoint verb minus the model noun (`Serve`, `Refund`, `Complete`, `Terminate`).
349
+ - Layer the verbs: the document chain method drops the model (`sign()`, `approve()`), the service keeps the bare verb, and the signal, store, and dictionary re-add it (`signScContract`). This keeps custom endpoints clear of generated CRUD and makes `st.do.X` read the same as `fetch.X`.
350
+ - Slice and filter names are prepositional: `inOrg`, `inProject`, `inPeriod`, `byStatuses`, `ofPortfolio`. Never `getXInY`, never `listX`.
351
+ - Handlers are `onX` props taking inline arrows. Do not extract a `handleX`.
352
+ - Booleans are `is*` / `has*` / `can*` / `show*` / `disable*`. Counters are `*Num`, indices are `idx`, collections are `*List` or plural. `SCREAMING_SNAKE` is unused; module-scope tables are camelCase + `as const`.
353
+ - Keep existing domain vocabulary and its typos. Transliterated domain terms and misspelled identifiers already in use are load-bearing — renaming them silently breaks callers that match on the name.
354
+ - Identifiers, type names, endpoint names, and log messages are **English, always**. Everything a user reads goes through `l("model.field")` or `l.trans({ en, ko })` — never a hard-coded string in JSX, never `window.alert`.
355
+ - Dictionary entries are `[en, ko]` pairs, and nearly every label also carries a `.desc([en, ko])` even when it repeats the label. English labels are Title Case, Korean is the plain domain term, and `.error()` Korean ends in `다.`.
356
+
357
+ ## Domain Module Conventions (`apps/**/lib/**`, `libs/**/lib/**`)
358
+
359
+ - Organize business concepts as domain folders under `lib/`; keep related schema, service, signal, store, and UI files together.
360
+ - Use lowercase logic files such as `<model>.constant.ts`, `<model>.document.ts`, `<model>.service.ts`, `<model>.signal.ts`, `<model>.dictionary.ts`, and `<model>.store.ts`.
361
+ - Use PascalCase React component files such as `<Model>.Template.tsx`, `<Model>.Unit.tsx`, `<Model>.View.tsx`, `<Model>.Zone.tsx`, and `<Model>.Util.tsx`.
362
+ - Treat `constant.ts`, `dictionary.ts`, and `signal.ts` as shared contract files that should avoid platform-specific dependencies.
363
+ - Keep backend persistence/query logic in `.document.ts` and domain business orchestration in `.service.ts`.
364
+ - Keep frontend state in `.store.ts`; use `Template` for forms, `Unit` for list/card items, `View` for details, `Zone` for composed page sections, and `Util` for domain-specific UI helpers.
365
+
366
+ ### Module File Playbook
367
+
368
+ **`<model>.constant.ts`** — five classes in order with one blank line between them and `enumOf("camelName", [...] as const)`
369
+ classes above: `XInput → XObject → LightX → X → XInsight`. Write `XInsight` even when it is empty. Put display and
370
+ predicate logic on `LightX` (`isNew()`, `canWrite(user?)`, `formatTimes()`) — the Light class is the one both server
371
+ and client hold, so shared logic belongs there instead of in a util module. **This is the most commonly missed rule
372
+ in the codebase.** Collection-level helpers go `static` on the full model. Give any field whose business meaning is
373
+ not obvious a short trailing comment.
374
+
375
+ **A model instance's `Date` fields are prototype accessors, not own properties.** `user.createdAt` is still a `Dayjs`,
376
+ built on first read from a native `Date` the instance holds under a symbol. So `Object.keys(user)` and `{ ...user }`
377
+ do **not** include them, while `"createdAt" in user`, `for...in`, `JSON.stringify(user)`, `plainFieldsOf(user)`
378
+ (`akanjs/common`), `immerify`, and `deepObjectify` all do. To copy a model, `new cnst.X().set(user)`, never a spread.
379
+
380
+ **`<model>.document.ts`** — fixed order: `XFilter extends from(...)` → `X extends by(...)` → `XModel extends into(...)`,
381
+ with `sort: {}` always present. Chain methods validate → mutate → `return this`, and never `save()`; the caller saves,
382
+ so chains compose (`org.removeUser(id).removeInvite(id).save()`). Put a one-line comment above each stating the
383
+ transition. Atomic counters live on the Model class with the updater-callback form, returning `!!modifiedCount`.
384
+ Indexes and derived totals go in `static override _onSchema`, not in the service. **Removal is always soft** — the
385
+ framework has no hard delete for a model table, and `delete` is deliberately left unused so it can mean one later.
386
+ The facade spells `Many`/`One` out on its writes (`updateOne` / `updateMany` / `removeOne` / `removeMany`); only the
387
+ count was shortened to `count(query)`, with `countDocuments` kept as `@deprecated`. `updateById(id, update)` and
388
+ `removeById(id)` are those same query-level writes narrowed to one id, **not** the document path: they fire no hooks,
389
+ so a model whose removal cascades or carries a `_postRemove` still goes through `remove<Model>(id)`.
390
+
391
+ **`<model>.service.ts`** — keep methods to a few lines: load → chain → `return await ….save()`. Write `return await`
392
+ explicitly in tail position; do not "optimize" it away. Side effects belong in `override async _preUpdate` /
393
+ `_postCreate`, not inline. Fire-and-forget is explicitly `void`-ed. Order deliberately: load every referenced document,
394
+ then save, then notify. Return `null` / `false` for "not allowed" or "not found" and let the signal decide whether that
395
+ is an error.
396
+
397
+ **`<model>.signal.ts`** — `XInternal` → `XSlice` → `XEndpoint`, all three declared even when empty. `exec` is a one-liner
398
+ delegating to the service.
399
+
400
+ **`<model>.store.ts`** — write a custom action only for a toast, an optimistic update, or a multi-field write; most
401
+ stores need none, because state and CRUD actions are generated. The body is three lines: `await fetch.X` →
402
+ `this.setX(...)` → toast. The optimistic shape is mutate the client model, `void fetch.*`, then commit. Use
403
+ `this.pick(...)` when the value must exist, `this.get()` when it may not, and `this.set({...})` to write. Mutate lists
404
+ through the collection API (`this.set({ xList: xList.set(x).save() })`), not array spread. **An action returns
405
+ nothing** (`no-return-in-store-action.grit`). **Never `import type { RootStore } from "../st"`** — it crashes
406
+ `akan build` with a Bun SSR segfault.
407
+
408
+ **`<model>.dictionary.ts`** — fixed chain, with empty stages still written:
409
+ `.of() → .model() → .insight() → .query() → .sort() → .enum() → .slice() → .endpoint() → .error() → .translate()`.
410
+ Name every argument in `.arg()`, including framework-supplied `skip` / `limit` / `sort`. Use `modelDictionary`,
411
+ `scalarDictionary`, or `serviceDictionary` to match the module kind.
412
+
413
+ **`<module>.abstract.md`** — a title line, one declarative sentence naming what the module owns, a `## Rules` list of
414
+ two to five invariants the code cannot show, and an optional workflow arrow chain
415
+ (`draft -> signed -> active -> completed`). Never restate field lists or types. Update it whenever an invariant or
416
+ workflow changes.
417
+
418
+ ## Service And Signal Conventions (`*.{service,signal}.ts`, `server/**`)
419
+
420
+ - Keep domain business operations in `.service.ts` classes built with `serve(...)`.
421
+ - Keep execution contracts and triggers in `.signal.ts` classes built with `internal(...)`, `slice(...)`, and `endpoint(...)`.
422
+ - Use `Internal` for internal triggers such as init, interval, cron, or queue jobs.
423
+ - Use `Slice` for typed data views that feed client stores and zones; keep each slice focused on one purpose.
424
+ - Use `Endpoint` for query and mutation contracts exposed to callers.
425
+ - Connect external APIs or infrastructure through adapters, usually under `srvkit/`, and inject them into services instead of importing vendor clients directly into domain logic.
426
+
427
+ ### Guards And Transports
428
+
429
+ Full contract — credential handshake, room revalidation, socket cleanup scoping: `get_guideline` with
430
+ `transportRule`, or `akan guideline show transportRule`.
431
+
432
+ - Guards run on both HTTP and websocket calls. Read the caller with `context.get<T>("account")` instead of
433
+ branching on `getHttpContext()` / `getWebSocketContext()`, and keep them side-effect free and safe to re-run —
434
+ a pubsub room's guards are re-run whenever the socket's credential changes.
435
+ - Slice-level `guards` only reach the generated query/mutation endpoints. A `pubsub`/`message` endpoint is
436
+ unguarded unless it declares its own `guards` in its signal option.
437
+ - **Never read the caller's IP off the socket or the request peer — take `.with(Ip)`** (`context.getClientIp()`
438
+ inside a guard or middleware). Behind a federation gateway, `ws.remoteAddress` and the child's own peer are the
439
+ *gateway* (`127.0.0.1`) for every caller and for the whole life of every socket. `Ip` reads what a proxy
440
+ recorded, is unwrapped from its `::ffff:` form, and is `null` rather than a placeholder when genuinely unknown.
441
+ - **Every socket carries a `socketId`, and only the framework mints one** — read it off the `Ws` internal arg
442
+ (`.with(Ws)` hands `{ ws, socketId, subscribe, on, off }`). Never mint your own from `ws.data`: the room
443
+ bookkeeping keys on the framework's id and a second one fails to match it silently. It identifies a
444
+ **connection**, not a caller, so per-user state keys on the account.
445
+ - **A cleanup registered with `ws.on("disconnect" | "unsubscribe", fn)` is scoped to the call that registered it**
446
+ — a room for a `pubsub` subscribe, the socket for a `message` handler. Cleanup that must happen either way
447
+ registers for both.
448
+
449
+ ### Authorization Defaults
450
+
451
+ - **Every `slice()` takes an explicit `{ guards: {…} }` second argument, and `root:` is always `Admin`.**
452
+ - **Every custom `mutation` / `query` / `message` names its own `guards: [...]` array.** Never rely on the slice default. `Public` belongs on a slice `get:`, never on a mutation.
453
+ - **The guards are also the MCP exposure decision** — see MCP Exposure. An endpoint that names none is not published to agents at all, and a mutation whose only guard is `Public` is refused, so a missing `guards` array now costs visibility as well as authorization.
454
+ - Resource guards are `Can<Verb><Model>` classes in `srvkit/guards.ts` that `implements Guard` with an `async canPass(context)`. They **fail closed**: no resource named ⇒ `false`; a load that throws ⇒ `logger.warn` then `false`. Admin bypass goes first.
455
+ - Keep `static name = "User";` on guard classes. `fetch` serializes guard names and the API explorer filters on them; it looks like dead code, and deleting it breaks the UI. Comment it so the next reader knows.
456
+ - **Every guard class also declares `static scope: GuardScope`, and it is required with no default.** `"account"` means the verdict reads the caller and nothing about the call, so it can be evaluated with no arguments — which is what lets an MCP listing hide what this caller certainly cannot use. `"resource"` means it needs the call's arguments (`context.getArg()`) and fails closed without them, so it is never evaluated for a listing: the entry stays visible and is stopped at call time. Getting it wrong is not a type error, so the marker is mandatory rather than defaulted — `SignedIn` / `Admin` / role checks are `"account"`, and every `Can<Verb><Model>` is `"resource"`.
457
+ - The acting user arrives via `.with(Self)` / `.with(CurrentUserId)` / `.with(Me)`. Never trust a client-supplied id.
458
+ - Guards ship with the library that owns the model and are imported by its own signals through the package path, so a mounting app inherits authorization and cannot forget it.
459
+ - Services re-check ownership even when a guard already gated the call — two independent gates.
460
+ - `srvkit/guards.ts` earns real comments: explain what would leak without each guard.
461
+
462
+ ### Signal Body Types
463
+
464
+ - `.body(...)` / `.param(...)` args accept `ConstantFieldTypeInput` only: scalars, model refs, or `enumOf(...)`.
465
+ - Numbers must use `Int` or `Float` — `Number` is rejected (`pkgs/akanjs/signal/endpointInfo.ts`).
466
+ - `Upload` is valid only inside a mutation flagged for file upload: `mutation([cnst.File], { fileUpload: true }).body("files", [Upload])`, as the `file` module does. It is not a model field type.
467
+ - Bytes are `Binary`, never `Any` — see Scalar & Field Type Reference.
468
+
469
+ ### Binary Pubsub And Mutation Verbs
470
+
471
+ Full contract — backpressure modes, the `Any`-carrying-bytes fallback, multi-verb paths: `get_guideline` with
472
+ `transportRule`.
473
+
474
+ - **`pubsub(Binary)` sends its payload in a websocket binary frame**, skipping the JSON envelope and the base64 a
475
+ JSON wire would need; the client's subscribe callback receives a `Uint8Array`. The optimization applies only
476
+ when the **whole** return is `Binary`. A declared `Binary` room **coalesces under backpressure** — keeping only
477
+ the newest frame — which is what telemetry and video want; declare `{ backpressure: "queue" }` when the frames
478
+ are a sequence a subscriber must see in full. A `pubsub(Any)` carrying bytes is framed too and warns once;
479
+ declare `Binary`.
480
+ - **A `mutation` is `POST`.** `{ method: "PATCH" | "PUT" | "DELETE" }` moves it, and one path may carry several
481
+ verbs; two endpoints claiming the same path **and** verb fail the boot. Reach for it only when a foreign wire
482
+ protocol forces the verb — Akan's own `fetch.*` client, the OpenAPI document, and the API explorer all follow
483
+ whatever is declared.
484
+
485
+ ### Reserved Endpoint Names
486
+
487
+ - Auto-generated CRUD endpoints (e.g. `create<Model>`, `update<Model>`, `remove<Model>`) already exist for every model. Do not declare an `Endpoint`/`Slice` with a name that collides with them.
488
+ - The service layer surfaces such a collision as a typecheck error, but the signal layer can pass sync/typecheck/build and fail only at runtime — so treat name collisions as errors regardless of whether the build is green.
489
+
490
+ ### Slices, Queries, and Hydration
491
+
492
+ Full contract — filter-arg `ref` pickers, `getQueryMeta` summary counters, `labelOf`, and the `q.exists` /
493
+ `q.missing` / `q.empty` split: `get_guideline` with `queryRule`, or `akan guideline show queryRule`.
494
+
495
+ - **The root slice (`""`, generated by `slice()`) takes `queryKey` and `args`, not a query.** `initX("byOwner",
496
+ [ownerId])` names one of the model's own filters and passes that filter's args; no key at all is the `any`
497
+ filter every model carries. A raw query descriptor could not survive the query string — `String(value)` sends
498
+ `[object Object]`. It is an admin API: `root:` is always `Admin`.
499
+ - A slice's `exec` returns a `QueryOf` (an opaque query descriptor); you **cannot** chain `.sort()`/`.limit()` on
500
+ it. Apply ordering/paging via the store `init` fetch option instead: `initX(..., { sort, page, limit })`. For a
501
+ chainable builder use the model facade's `findMany`/`findOne`.
502
+ - **Hydrated vs raw:** server queries return hydrated `cnst.<Model>` instances (with `set`/`save`/`refresh`);
503
+ client fetch results are raw `GetStateObject` plain data, functions stripped.
504
+ - Every filter generates fourteen methods: `list` · `listIds` · `find` · `findId` · `pick` · `pickId` · `exists` ·
505
+ `count` · `insight` · `query` · **`remove`** · **`removeOne`** · **`update`** · **`updateOne`**. The last four
506
+ are query-level writes — one atomic UPDATE, **no hooks**, and therefore no `_postRemove` and no cascade. Use
507
+ them on a model that carries no removal side effect; otherwise remove documents one at a time.
508
+ - **`update<Filter>` / `updateOne<Filter>` are chains, not calls:** `await updateInRoot(rootId).set({ status:
509
+ "archived" })`. The patch cannot trail the filter args, so it lands on a terminal `.set()`; building the chain
510
+ touches nothing.
511
+ - `removeOne` / `updateOne` hit the **newest** match, always, and report only counts — they are for "there is at
512
+ most one of these", not for claiming the next item off a queue.
513
+ - **A filter may not be keyed after its own model.** A filter `chat` on model `chat` would silently swap the
514
+ single-document `removeChat`/`updateChat` for a hookless query-level one; it throws at boot instead.
515
+ - **"Has no value" is `q.empty`, never `q.missing`.** `q.missing` is the key being *absent from the stored JSON*,
516
+ which a document written once and saved again no longer is. Reach for it only to find rows written before the
517
+ field was declared.
518
+
519
+ ### Text Search In A Filter — `q.search()`
520
+
521
+ Full contract — relevance ordering, `columns` / `weights`: `get_guideline` with `queryRule`.
522
+
523
+ - Text search is a filter query node like any other: `bySearch: filter().arg("text", String).query((text, q) =>
524
+ q.search(text, { prefix: true }))`. The generated `listBySearch` / `countBySearch` / `queryBySearch` /
525
+ `insightBySearch` come for free — you do **not** need a slice to make search usable.
526
+ - **Only add a search slice when the model's data is safe to enumerate.** A filter is server-side; a slice is a
527
+ client-callable endpoint, so on a model whose slice `get:` is `Public` a search slice hands anyone a way to walk
528
+ the table. Leave that decision to the mounting app.
529
+ - `q.search()` compiles to a JOIN, not a WHERE fragment, so it **must sit at an AND position**. Nesting it under
530
+ `q.any()` or `q.not()` throws, and it is rejected in `updateOneByQuery` / `updateManyByQuery`.
531
+ - Blank or whitespace-only input matches **nothing**. Never "fix" that into a passthrough: a passthrough turns a
532
+ search endpoint into a full listing.
533
+ - Order by relevance with the built-in `relevance` sort key. A slice endpoint never reaches the unspecified
534
+ fallback — leaving `sort` off gets `latest`, so a client wanting score order has to name `relevance`.
535
+
536
+ ### Service / Signal Injection
537
+
538
+ - Injected dependencies resolve by field-name convention: a field named `<refName>Service` resolves to the service registered under `<refName>`, and `<refName>Signal` likewise (`pkgs/akanjs/service/injectInfo.ts`).
539
+ - The `Service`/`Signal` suffix is required — the injector strips it to derive the registry lookup key. Name the field after the target refName plus the suffix, not arbitrarily.
540
+ - Preference order inside a service: `service<srv.XService>()` for another module's service · `plug(AdapterClass)` or `plug(StorageAdaptorRole)` for an adapter · `use<T>()` only to reach an `option.ts`-registered legacy singleton · `env(...)` for config.
541
+
542
+ ### Adapters — `adapt()` And `plug()`
543
+
544
+ An injected singleton is an `adapt()` class in `srvkit/`. Write new adapters this way.
545
+
546
+ ```ts
547
+ export class AdminNoti extends adapt("adminNoti" as const, ({ use, env, plug, memory }) => ({
548
+ discordApi: use<DiscordApi>(),
549
+ workspaceRoot: env(() => `~/build/${getEnv().environment}`),
550
+ masterHost: plug(MasterHost),
551
+ tokenMap: memory(Map, { of: String }),
552
+ })) {}
553
+ ```
554
+
555
+ - Inject it with `plug(TheClass)` from a service or from another adapter. Destructure only the injectors you use, and write the registration key `as const`.
556
+ - **Do not register an `adapt()` class in `lib/option.ts`.** It self-registers, and `plug(Class)` uses the class itself as the token. `option.ts` is now only for legacy constructor-style adapters and for widening the options type.
557
+ - `this.logger` is provided; never construct a `Logger` inside an `adapt()` class. Lifecycle work goes in `override async onInit()`.
558
+ - **`adapt()` is for singletons only.** A per-use value object stays a plain class you `new` at the call site. If there is not exactly one per process that a service needs injected, it is a plain class.
559
+ - **Legacy shape — recognise it, do not copy it.** Plain classes with `constructor(options: XOptions)`, registered in `lib/option.ts` and injected with `use<T>()`, still work. Migrate one to `adapt()` only when you are already changing it.
560
+
561
+ Conventions that hold for both shapes:
562
+
563
+ - Route every remote call through one private `#api<T>(path, init?)` with `signal: AbortSignal.timeout(20_000)`.
564
+ - Paginate with `for (let page = 1; ; page += 1)` broken by `if (pageItems.length < 100) break;`.
565
+ - Resolve secrets as `process.env.X ?? options.x ?? deterministicGenerator(...)` **inside a function**, never at module scope.
566
+ - Extend a function by appending an optional trailing parameter with a default, never by changing arity.
567
+ - Parameters: up to three required primitives positional; optional flags in a trailing `{ … } = {}`; four or more parameters, or any two same-typed strings, in one named destructured object.
568
+ - Release locks in `finally`. Load heavy optional dependencies through a module-level memoized promise (`puppeteerLoad ??= import("puppeteer")`).
569
+
570
+ ### Error Placement
571
+
572
+ - State-machine preconditions throw in `document.ts`; cross-document rules throw in `service.ts`; request-level policy belongs in `signal.ts` guards.
573
+ - Best-effort code returns a sentinel (`null`, `undefined`, `[0, 0]`, `{}`). There are no Result/Either wrappers.
574
+ - `try/catch` is rare and always converts an exception into a decision, never swallows one. Guards catch → `logger.warn` → `return false`; adapters catch → `logger.error` → `return null`; UI uses `try/finally` to reset a spinner. A bodyless `catch {}` is acceptable only with a one-line reason.
575
+ - Store actions do not `try/catch` — let the framework toast the `Err`. Client-side validation failure is `msg.error("<key>")` plus an early return, never a throw.
576
+
577
+ ### MCP Exposure
578
+
579
+ Every signal is served to AI agents as an MCP server on `POST /mcp`. **`/mcp` is mounted by default and exposure
580
+ follows an endpoint's guards — there is no per-endpoint opt-in, and nothing to write in a signal file.** An
581
+ endpoint that declares a real guard is published; one that declares none is refused, and so is a mutation whose
582
+ only guard is `Public`. The guards are already the authorization decision, so a second switch would say nothing
583
+ they do not — while guaranteeing that every endpoint added later is invisible to agents until somebody remembers
584
+ it.
585
+
586
+ - **`mcp: false` keeps an endpoint off the shelf without touching its guards.** Guards answer "may an agent call
587
+ this"; they cannot answer "does this belong on a shelf", and a step of a UI-driven state machine
588
+ (`requestPhoneCodeForSignin`) is perfectly guarded and still a mistake for a model to reach. Write it in the
589
+ signal option (`mutation(Boolean, { guards: [Every], mcp: false })`, `init({ guards: [SignedIn], mcp: false })`),
590
+ or as an `mcp` map on `slice()` that **mirrors the `guards` map key for key** (`mcp: { cru: false }`) — root
591
+ slice and generated CRUD only, never a named slice or a custom endpoint. It is an opt-**out**, and it is
592
+ curation, not authorization: HTTP serves the endpoint exactly as before.
593
+ - **Narrow by cost, and read the boot log first.** MCP forbids a `$ref` across entries, so every entry inlines the
594
+ full schema of every model it mentions and the listing is re-sent whole to every agent that connects. A plain
595
+ 21-field model costs 12.6KB over eight entries; `mcp: { cru: false }` takes it to 4.7KB. `MCP catalogue: … ·
596
+ listing 214KB` plus a per-signal `MCP catalogue cost:` line says where it went.
597
+ - Settings live in the app's `lib/option.ts` — `option.setMcp({ enabled, readOnly, path, version, instructions,
598
+ allowedOrigins, pageSize, language, auth })`, **not `main.ts`**. Each field has an `AKAN_MCP_*` env spelling.
599
+ `AKAN_MCP_READONLY=true` is the read-only-deployment valve, not the exposure switch; `AKAN_MCP=false` takes the
600
+ whole surface off.
601
+ - **The refusals are fail-closed**: a declared `mcp: false`, an endpoint with no `guards`, a mutation with no real
602
+ guard, `pubsub` and `message`, an `Any` or `Upload` return, a file upload, a required `Any` argument, and the
603
+ generated `light<Model>` read. A `prompt` also refuses a list argument and any `Any` argument. **Every refusal
604
+ is named in the boot log**, along with every published entry missing a dictionary `.desc()` — an agent picks a
605
+ tool by its description.
606
+ - A refused endpoint answers the *same* "unknown tool" as one that does not exist, and a guard's refusal is
607
+ generalized. Never make either message more helpful — the difference is what enumerates your private surface.
608
+ - **A `field.visual` field is stripped from every MCP result** and from the readable schema so the two agree.
609
+ - **A structured result ships twice by default** — as `structuredContent` and as the same JSON in the text block.
610
+ `option.setMcp({ legacyTextBlock: false })` leaves a pointer there instead.
611
+ - **`prompt()`** is invoked by the *user* as a slash command, never chosen by the model. `exec` returns
612
+ `PromptMessage[]` built with `Msg.user` / `Msg.assistant` / `Msg.resource` / `Msg.image`; an embedded payload is
613
+ masked by the model you name, and one whose `hidden`/`secret` fields are populated with no model named is
614
+ refused. It is also mounted as a plain HTTP `GET` whether or not MCP is enabled, so guard it like any other read.
615
+
616
+ Full contract — configuration, wire behaviour, resource URIs, OAuth metadata, protocol revisions, and
617
+ `McpProgress.report`: `get_guideline` with `mcpRule`, or `akan guideline show mcpRule`.
618
+
619
+ ## In-Page Agent
620
+
621
+ Every akan app can host a component-level agent that reads the rendered screen and drives it. **A component
622
+ declaration is the surface, exactly**: `st.tool` publishes one action, and `st.use` / `st.sel` / `st.ref` make one
623
+ store key readable while the reading component is mounted. Nothing is derived from a store class — a lever the
624
+ screen does not offer the user is not one an agent may pull in their place. The React core is the `use-agentic`
625
+ package; apps and libs never import it directly (`no-import-external-library`) — everything reaches them through
626
+ `st.*` and `akanjs/ui`.
627
+
628
+ Read the full contract before building an agent surface — the chat's own options, `st.tool` / `st.expose` /
629
+ `st.useState` in full, zones and namespaces, attachments and speech, slash commands, transcript compaction, and
630
+ the built-in tool semantics: `get_guideline` with `agentRule`, or `akan guideline show agentRule`. What follows is
631
+ what every developer must know even when not building one.
632
+
633
+ - **Mount `<Agent.Chat />` once in a layout.** The endpoint is a stateless relay that **never executes tools**:
634
+ every tool runs in the caller's own browser session, gated by guards and the approval card. Its guard is
635
+ `AgentRelayAccess`, which refuses every call until the app names a guard of its own —
636
+ `option.setAgentAccess(SignedIn)`. **The LLM is configured in `option.ts`, never through the environment**
637
+ (`option.setLlm({ apiKey, model, host })`).
638
+ - **Declare the tool beside the control that already does it**, never as a separate surface:
639
+ `st.tool("x").desc("…").arg("id", ID).exec(fn)` returns the callable to hand to `onClick` — one handler for the
640
+ person and the agent. Publish it only where the screen already renders the control; a falsy name declares the
641
+ tool without publishing it, and a `disabled` control publishes nothing.
642
+ - **Forms publish themselves**: a `Field.*` / `Input.*` / `Select` / `Switch` handed `onChange={st.do.setXOnY}`
643
+ **by reference** publishes that setter, and `st.use.yForm()` adds `fillYForm(patch)`. An inline arrow publishes
644
+ nothing — normalize with the control's `transform` prop, and multi-write with a `_postSet<Field>` store method.
645
+ This is the same rule `no-unpublished-form-setter.grit` enforces.
646
+ - **Reading is per key, not per store.** `st.use.x({ agent: false })` keeps a subscribed key off the surface; a key
647
+ no component reads is unreadable. A value with populated `hidden`/`secret` fields is refused at read.
648
+ - **Return what answers the question, not the record.** A tool's value is capped at 20,000 characters before it
649
+ enters the transcript, and once there it rides *every* later turn. A field that is bulky and useless to a model
650
+ is fixed once at the model instead: `field.visual(String)`.
651
+ - **Route guidance is `<Agent.Guide instructions="..." />`** rendered from a `_layout.tsx` or page — the render
652
+ tree is the cascade. It is a component, not a `pageConfig` field, and `*.abstract.md` is never served to agents.
653
+ - **Model-facing text is English, always** — every `.desc()`, `instructions`, Guide text. The `l()` rule covers
654
+ strings a *user* reads.
655
+
656
+ ## Scalar Modeling (`**/*.constant.ts`)
657
+
658
+ - Define Akan models in `.constant.ts` files with `via` from `akanjs/constant`.
659
+ - Use `Int` for whole-number counts and quantities; use `Float` only for values that need decimals.
660
+ - Use `ID` for document references and prefer explicit structured fields over `Any` unless the content is genuinely flexible.
661
+ - For date defaults, prefer a function such as `default: () => dayjs()` so the value is created at runtime.
662
+ - Follow the established model layering pattern in this order: `Input`, `Object`, `Light<Model>`, full `<Model>`, and `<Model>Insight`. Write all five, and write `<Model>Insight` even when it is empty.
663
+ - Put display and predicate logic on the `Light<Model>` class rather than in a util module — see Module File Playbook.
664
+ - Defaults are a literal for scalars and a thunk for anything constructed. Arrays are `field([T])`; optional is the postfix `.optional()`.
665
+ - **`field.visual(T)` is a field the page renders and an agent never sees** — a blur placeholder, a rendered HTML body, a serialized geometry. It stays an ordinary stored `property` (persistence, search, forms and the page response untouched) and is stripped wherever a value is masked for an AI caller: every in-page-agent read and every MCP result, along with the MCP readable schema. Unlike `hidden`/`secret` it is cost, not secrecy — nothing is refused over one. Reach for it whenever a field is bulky and useless to a model; that is cheaper than every tool learning to avoid it.
666
+
667
+ ### Scalar & Field Type Reference
668
+
669
+ - **Import from `akanjs/base`** (real classes/helpers, not globals): `Int`, `Float`, `ID`, `Any`, `Binary`, `Upload`, `enumOf`, and the `dayjs` factory. There is **no `JSON` scalar** — use `Any` for open/flexible payloads.
670
+ - **Use the JS globals directly (no import needed)**: `String`, `Boolean`, `Date`. They are monkey-patched to behave like scalars, so `field(String)` typechecks.
671
+ - **`Number` is not a valid field/body type.** `NumberConstructor` is intentionally not augmented, so `field(Number)` / `.body("x", Number)` fails to typecheck. Use `Int` or `Float` instead.
672
+ - Runtime resolution of every scalar (globals included) goes through `PrimitiveRegistry` by `refName` (`pkgs/akanjs/base/primitiveRegistry.ts`).
673
+ - **`Binary` is raw bytes on the wire, and never a model field.** It is `Uint8Array` on both sides — a Node
674
+ `Buffer` is one, so a server handler may pass one straight in — and it accepts base64 in either direction, so
675
+ the same declaration serves a JSON body and a binary frame. It is **not storable**: the class build refuses
676
+ `field(Binary)` naming the `File` model instead, because every non-base field lives in the `_doc` JSON column
677
+ and bytes would sit there as base64 and ride every read of the row. Never send bytes as `Any` — `Any` passes a
678
+ `Buffer` through untouched and `JSON.stringify` then spells it `{ type: "Buffer", data: number[] }`, which
679
+ `JSON.parse` never restores; the result is 3.6x the wire and a shape that only breaks at the first byte-offset
680
+ read. MCP refuses a `Binary` return for the same reason it refuses `Any`.
681
+
682
+ ### Text Search Fields — the `text` role
683
+
684
+ Full contract — the trigger-maintained mirror, tokenizer changes, `AKAN_SEARCH_ENABLED`: `get_guideline` with
685
+ `queryRule`.
686
+
687
+ - A field joins the full-text index by declaring one of five roles: `field(String, { text: "title" })`, and
688
+ likewise `"desc"`, `"tag"`, `"thumb"`, `"filter"`. Nothing else opts a field in, and there is no per-model
689
+ switch. Declaring roles is all the wiring there is.
690
+ - Pick the role by what the value *is*, because `bm25` weights them positionally (`title` 10, `tag` 3, `desc` 1,
691
+ `filter` 0): `title` is the one line a human scans for, `desc` is prose, `tag` is a keyword list, `filter` is a
692
+ scoping value (status, owner, role) that must be matchable but must never outrank a real title hit. `thumb` is
693
+ mirrored for rendering a hit and is **not** indexed — never expect it to match.
694
+ - **`field.secret`, `field.hidden` and `resolve()` take no `text` role — it is a compile error**, because the
695
+ mirror is plaintext and an indexed secret would leak through search. The same refusal throws at runtime as a
696
+ backstop, including for a `text` field *underneath* one of those. Do not work around either.
697
+ - The role works on a relation (`image: field(File, { text: "thumb" })`) and on an array; an array of objects
698
+ indexes by leaf key. A field inside a `Map` indexes nothing — there is no fixed path to extract it from.
699
+ - Search runs on sqlite/libsql only. `q.search()` against Postgres throws, loudly, rather than returning every row.
700
+
701
+ ### Image & File Fields
702
+
703
+ - **Do not declare `Upload` as a model field.** `Upload` is a signal-body-only primitive (see Service And Signal Conventions). Models reference the `File` model instead.
704
+ - Declare an image/file field as a relation to `File`: `image: field(File).optional()` for one, `images: field([File])` for many.
705
+ - The store then auto-generates an `upload<Field>On<Model>(fileList)` action that calls the framework upload mutation and polls file status until it leaves `"uploading"` (`pkgs/akanjs/store/action.ts`).
706
+ - Storage is wired through the `StorageAdaptor` DI role (default `BlobStorage`, `pkgs/akanjs/service/predefinedAdaptor/storage.adaptor.ts`); the reference implementation is the `file` module. Do not hand-roll data-URL fallbacks.
707
+
708
+ ### Cascade Remove — the `cascade` option
709
+
710
+ Full contract — bulk planning, the auto-created index, cycle cutting, boot-time validation: `get_guideline` with
711
+ `queryRule`.
712
+
713
+ **The value names the direction, and getting it wrong is a data loss.** The two actions can sit on the same field
714
+ shape, so `cascade` never means "related" — it means one of exactly these:
715
+
716
+ - `removeRef` — *when I am removed, remove what this field points at.* Declared on the relation the owner holds:
717
+ `image: field(File, { cascade: "removeRef" })`, arrays included. Only a relation accepts it.
718
+ - `removeWith` — *when what this field points at is removed, remove me.* Declared on the child's own reference to
719
+ its owner, so the owner never learns about its children and a lib model can be extended by an app's. Three
720
+ forms: a relation, an id with `ref`, or a polymorphic id with `refPath`. An array, a Map, `ref` together with
721
+ `refPath`, and a field naming no owner each fail the class build.
722
+ - **A `refPath` must name an `enumOf` field** — a free-form owner type is unknowable at build time.
723
+ - **A cascade goes through the target's service, never its model** — that path is what runs the target's
724
+ `_postRemove`, where a module puts the side effect the removal has to carry.
725
+ - **Nothing checks whether another document still references the same target.** `File` in particular is deduped by
726
+ `origin`, so two parents can share one row; `removeRef` claims the field owns its target exclusively.
727
+ - Removal is soft (`removedAt`), but the storage delete a `_postRemove` performs is not — a cascade is not
728
+ restorable, and reviving the owner does not revive what went with it.
729
+ - **Query-level removes fire no hooks and therefore no cascade** — `removeManyByQuery` / `updateManyByQuery`, the
730
+ generated `remove<Filter>` / `update<Filter>`, and the facade's `removeById` / `updateById`. Remove one document
731
+ at a time when it cascades.
732
+
733
+ ## Akan Page Routing (`apps/**/page/**`)
734
+
735
+ - `apps/<app>/page` may contain route modules only. Do not add helper logic or component-only files there.
736
+ - Route source files under `page/` must use `.tsx`. Do not add `logic.ts`, `.js`, or `.jsx` files under `page/`.
737
+ - A route page is either `<routeName>.tsx` (serving `/routeName`) or a directory's `_index.tsx`; layouts use `_layout.tsx`; per-route UI overrides use `_overrides.tsx`.
738
+ - Reserved `_*.tsx` route filenames are limited to `_index.tsx`, `_layout.tsx`, and `_overrides.tsx`; do not add files like `_Component.tsx` or `_helper.tsx`.
739
+ - Page filenames must not start with an uppercase letter. Move helper components like `Component.tsx` to app `ui`, `common`, or `lib` instead.
740
+ - Dynamic segments use `[id]`; route groups use directories like `(user)`, `(public)`, `(tab)`, or `(detail)`.
741
+ - Page modules should usually export `default`, `pageConfig`, `head`, `generateHead`, or `Loading`.
742
+ - `_overrides.tsx` is a logic-free UI-override manifest: imports plus a single `export default override({ Slot: AppComponent })` (from `akanjs/ui`), no `"use client"`. It re-skins framework `akanjs/ui` components for its route subtree; nested manifests merge over ancestors slot-by-slot (closest wins). See the UI Customization reference for the slot list.
743
+ - Prefer `export default function Page` or `export default async function Page` for page components.
744
+ - `libs/<lib>/page` follows the same rules and ships routes to apps that opt in with `syncPageLibs` in `akan.config.ts`: `true` takes every lib dep that has a `page` folder, an array takes the libs listed, `false` (the default) syncs nothing.
745
+ - `akan sync` links those routes into `apps/<app>/page/(libs)/(<lib>)` — once per basePath when the app declares subRoutes. The folder is generated and gitignored; edit the lib source, never the link.
746
+ - Both path segments are route groups, so a lib route mounts at its own path (`libs/<lib>/page/login/_index.tsx` serves `/login`). Two synced routes that resolve to the same pattern are a sync-time error.
747
+ - `export const pageConfig = { devOnly: true }` keeps a route out of `akan build` while it keeps serving under `akan start` and keeps being typechecked. On a `_layout.tsx` it excludes every route under that directory too. Write it as a literal `true`/`false` — the build reads it off the source without evaluating the module.
748
+ - Before changing route behavior, check `pkgs/akanjs/server/routeTreeBuilder.ts` and nearby routes for the expected pattern.
749
+
750
+ ### Page Body Shape
751
+
752
+ ```tsx
753
+ interface PageProps {
754
+ params: { orgId: string };
755
+ }
756
+
757
+ export default async function Page({ params }: PageProps) {
758
+ const { l } = usePage();
759
+ getSelf({ unauthorize: "/signin" });
760
+ const { orgId } = params;
761
+ const [{ org }, { taskInitInOrg }] = await Promise.all([fetch.viewOrg(orgId), fetch.initTaskInOrg(orgId)]);
762
+ return <Task.Zone.Card init={taskInitInOrg} prefix={`/org/${orgId}`} />;
763
+ }
764
+
765
+ export const pageConfig = { transition: "stack" } satisfies PageConfig;
766
+ ```
767
+
768
+ - There is no `loader=` / `render=` page prop. Pages are `export default async function Page`.
769
+ - Declare `interface PageProps { params: {...}; searchParams?: {...} }` immediately above the default export.
770
+ - Body order: `usePage()`, auth, destructure params, fetch, return.
771
+ - Run independent fetches through `Promise.all`, even when there is only one.
772
+ - Gate auth at `_layout.tsx`; repeating `getSelf({ unauthorize: "/signin" })` in the page is fine and common.
773
+ - Keep `async` even when nothing is awaited — it marks a real server page.
774
+ - No `useState`, no `useEffect`, and no comments in page files.
775
+
776
+ ## Akan Sync Conventions (`apps/**`, `libs/**`)
777
+
778
+ - `apps/<appName>` root may only contain these files: `AGENTS.md`, `CLAUDE.md`, `akan.app.json`, `akan.config.ts`, `capacitor.config.ts`, `client.ts`, `main.ts`, `package.json`, `server.ts`, `tsconfig.json`, `tsconfig.tsbuildinfo`.
779
+ - `apps/<appName>` root may only contain these folders: `.akan`, `android`, `common`, `env`, `ios`, `lib`, `mobile`, `page`, `plugin`, `private`, `public`, `script`, `secrets`, `srvkit`, `ui`, `webkit`.
780
+ - `libs/<libName>` root may only contain these files: `AGENTS.md`, `CLAUDE.md`, `README.md`, `akan.config.ts`, `akan.lib.json`, `client.ts`, `index.ts`, `package.json`, `server.ts`, `tsconfig.json`, `tsconfig.spec.json`, `tsconfig.tsbuildinfo`.
781
+ - `libs/<libName>` root may only contain these folders: `common`, `env`, `lib`, `page`, `plugin`, `private`, `public`, `srvkit`, `ui`, `webkit`. A library is never booted or packaged as an app, so the run and mobile entries an app carries (`main.ts`, `capacitor.config.ts`, `.akan`, `android`, `ios`, `mobile`, `script`, `secrets`) are rejected there.
782
+ - Both allowlists have one source — `pkgs/@akanjs/devkit/workspaceLayout.ts`. `akan sync` (error), `akan doctor`
783
+ (diagnostic), and `akan quality scan` (warning) all read it, so add a new root entry there and mirror it into this
784
+ list, never into one of the three call sites.
785
+ - `akan sync` maintains a scoped agent guide per app/lib: `apps/<app>/AGENTS.md` / `libs/<lib>/AGENTS.md`. The
786
+ section between the `akan:agent` markers (the `## Recipes In Scope` index) is generated — do not hand-edit it;
787
+ content outside the markers is yours. `akan lint` fails when the generated section is stale.
788
+ - The `plugin/` facet holds Akan plugin declarations; files use the `<name>.plugin.ts` convention (e.g. `pushNotification.plugin.ts`) and are re-exported from the generated `plugin/index.ts` barrel.
789
+ - Do not add `apps/*/base` or `libs/*/base`; place shared utilities under that app or lib's own `common/`.
790
+ - `apps/*/lib` and `libs/*/lib` root files are limited to generated/support files: `cnst.ts`, `db.ts`, `dict.ts`, `option.ts`, `sig.ts`, `srv.ts`, `st.ts`, `useClient.ts`, `useServer.ts` — plus a `<model>.signal.test.ts` / `.spec.ts`, the one hand-written file that belongs there because the suite boots the whole barrel.
791
+ - Domain module folders are `lib/<model>` for database modules, `lib/_<service>` for service modules, and `lib/__scalar/<scalar>` for scalar modules.
792
+ - Database module UI files are limited to `<Model>.Template.tsx`, `<Model>.Unit.tsx`, `<Model>.Util.tsx`, `<Model>.View.tsx`, and `<Model>.Zone.tsx`.
793
+ - Service module UI files are limited to `<Service>.Util.tsx` and `<Service>.Zone.tsx`.
794
+ - Scalar module UI files are limited to `<Scalar>.Template.tsx` and `<Scalar>.Unit.tsx`.
795
+ - Module `*.test.ts`, `*.test.tsx`, `*.spec.ts`, and `*.spec.tsx` files are allowed.
796
+ - `ui/index.ts`, `webkit/index.ts`, `srvkit/index.ts`, `common/index.ts`, `plugin/index.ts`, and module `lib/**/index.ts` files are generated by scanSync; do not hand-edit or track them.
797
+ - Generated facet indexes export only 1-depth files/folders with `export * from "./name";`.
798
+ - `libs/<libName>` may hold a `page` folder of route modules; scanSync links it into every app that opts in with `syncPageLibs`, so `apps/*/page/**/(libs)` is generated and gitignored like `public/libs`.
799
+
800
+ ## Layer Placement (`common/`, `webkit/`, `srvkit/`, `ui/`)
801
+
802
+ | Folder | Admission test | Naming |
803
+ |---|---|---|
804
+ | `common/` | pure, isomorphic, zero-dependency; may import only sibling `common/*` and `akanjs/base`. Cannot import `Err`, so keep throwing code out of it. | camelCase file, filename equals the single export |
805
+ | `webkit/` | touches `window` / `navigator` / Capacitor, or is a React hook | `use<Thing>.tsx` — `.tsx` even with no JSX |
806
+ | `srvkit/` | touches `node:*`, `Bun`, `process.env`, a secret, or a server SDK | camelCase file, PascalCase class |
807
+ | `ui/` | renders JSX and is not bound to one model | PascalCase component, camelCase sidecar (`swipeCard.util.ts`) |
808
+ | `plugin/` | build- or CLI-time `AkanPlugin` | `<name>.plugin.ts`, registered in `akan.config.ts` |
809
+
810
+ - Hooks return a named object of async closures, never a tuple.
811
+ - `libs/<lib>/ui/tokens.css` is the one CSS file a lib owns: plain `:root` custom properties for colors that must **not** follow the theme (a vendor brand color, a fixed surface). Every app whose pages reach that lib compiles it automatically, ahead of the app's own stylesheets, so nothing is imported by hand and no app can forget it. Reference them as `bg-[var(--kakao)]`; `@theme` extensions stay in the app stylesheet, because the color vocabulary is closed per stylesheet. Theme-following colors are the app's, not the lib's.
812
+ - A layer-root `index.ts` is generated, but a `ui/<Folder>/index.tsx` that builds a namespace is hand-written source. The distinguishing test is that a generated barrel contains nothing but `export * from "./X";` lines.
813
+ - `ui/<Folder>/index_.tsx` (trailing underscore) is the `"use client"` + `lazy()` boundary, with a server-safe `index.tsx` beside it. Collapsing the pair into one file breaks RSC.
814
+
815
+ ## Present In The Code — Do Not Imitate
816
+
817
+ Older files contain these. They are warts, not conventions: do not copy them forward, and prefer the newer neighbour
818
+ when two shapes disagree.
819
+
820
+ - `children: any` — newer files use `children: ReactNode`.
821
+ - Hard-coded API keys or secrets in source; they belong in `option.ts` or env.
822
+ - Large blocks of commented-out code left in place.
823
+ - Cross-store writes through a `RootStore` cast — it collides with the Bun SSR-bundler segfault.
824
+ - Stale `// TODO: Implement …` comments above implemented methods.
825
+ - `{cond && <X/>}` in JSX, hard-coded Korean bypassing `l()`, and `window.alert(...)` for user feedback.
826
+ - Bare `/* eslint-disable */` blocks — use `// biome-ignore lint/<rule>: <why>`.
827
+ - Raw palette grays such as `text-gray-400` instead of the semantic tokens (`text-foreground/70`).
828
+
829
+ ## Secrets And Env Safety (`.env`, `infra/**`, `*secret*`, `*credential*`)
830
+
831
+ - Never print, summarize, commit, or expose real secret values, credentials, tokens, private keys, or `.env` contents.
832
+ - If env keys are needed for documentation, list only key names and example placeholders, not live values.
833
+ - Preserve the existing env/secret flow through root scripts such as `bun run downloadEnv`, `bun run uploadEnv`, `bun run downloadSecret`, and `bun run uploadSecret`.
834
+ - When editing infra env or secret scripts, keep Jenkins and deployment assumptions intact unless the task explicitly asks to change them.
835
+ - Treat generated env/secret artifacts as sensitive even when they are not named `.env`.
836
+
837
+ ## Application Test Commands
838
+
839
+ - After changing application source code, test the app with `bun run akan start <appName>`.
840
+ - Test production build generation with `bun run akan build <appName>`.
841
+ - To test a built artifact locally, run it from the generated app directory with the required Akan runtime environment variables.
842
+
843
+ ```bash
844
+ cd dist/apps/<appName> && USE_AKANJS_PKGS=true AKAN_PUBLIC_REPO_NAME=<repo> AKAN_PUBLIC_SERVE_DOMAIN="<domain>" \
845
+ AKAN_PUBLIC_APP_NAME=<appName> AKAN_PUBLIC_ENV=local AKAN_PUBLIC_OPERATION_MODE=local SERVER_MODE=federation \
846
+ AKAN_PUBLIC_BASE_PATHS=<basePaths> bun main.js
847
+ ```