@akanjs/cli 3.0.0-alpha.3 → 3.0.0-alpha.31

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 (105) 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-20e0cwbs.js} +2 -2
  5. package/{agent.command-yv00p0s0.js → agent.command-e835fjem.js} +8 -7
  6. package/{application.command-0qsczf4k.js → application.command-sjtbk6tr.js} +6 -5
  7. package/{applicationBuildRunner-ct2pxyvw.js → applicationBuildRunner-7gnfz7ww.js} +6 -7
  8. package/{applicationReleasePackager-gg8ccbeh.js → applicationReleasePackager-93nzdfsy.js} +1 -1
  9. package/buildBatch.proc.js +5 -4
  10. package/{capacitorApp-4r9sm3qg.js → capacitorApp-qv7g3dp2.js} +29 -26
  11. package/{cloud.command-dxfv18sa.js → cloud.command-y0e4eyqz.js} +10 -9
  12. package/{context.command-8d9e3k6b.js → context.command-vn87jb08.js} +16 -15
  13. package/{dependencyScanner-f6grrep3.js → dependencyScanner-rbs2407b.js} +1 -1
  14. package/getDirname-ka11hm7e.js +8 -0
  15. package/{guideline.command-3jbkxzh6.js → guideline.command-s4hn2bsy.js} +7 -6
  16. package/guidelines/conventions/conventions.generate.json +25 -0
  17. package/guidelines/conventions/conventions.instruction.md +986 -0
  18. package/guidelines/cssRule/cssRule.instruction.md +7 -0
  19. package/guidelines/framework/framework.instruction.md +1 -0
  20. package/guidelines/workspaceOnboarding/workspaceOnboarding.generate.json +24 -0
  21. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +972 -0
  22. package/incrementalBuilder.proc.js +6 -5
  23. package/{index-1pvex4az.js → index-0h212yqe.js} +13 -13
  24. package/index-1577bej2.js +7 -0
  25. package/{index-k95xkh4p.js → index-33zce8gt.js} +8 -4
  26. package/{index-2q1f5j9k.js → index-3dp7x6rc.js} +3 -3
  27. package/{index-7c6k4yvg.js → index-73rnbwgg.js} +15 -7
  28. package/{index-e16gnn26.js → index-8d2sv6pw.js} +13 -13
  29. package/{index-hgna5rjy.js → index-8vkkm7v0.js} +124 -65
  30. package/{index-bekddz9q.js → index-9jsnb4vw.js} +4 -4
  31. package/{index-nm6wghb6.js → index-becx1t0k.js} +6 -6
  32. package/{index-a00jg8x8.js → index-g9e2fhw2.js} +49 -32
  33. package/{index-pyt2b4nw.js → index-hg0qvhmx.js} +152 -241
  34. package/{index-tdbas9r0.js → index-j37qq1f2.js} +1 -1
  35. package/{index-ej426mcr.js → index-k6fvbcj1.js} +37 -6
  36. package/{index-yzmhasdb.js → index-mykmf6wd.js} +8 -8
  37. package/{index-t3723f99.js → index-mz5jtaq7.js} +86 -17
  38. package/{index-8hsbnyes.js → index-n706txcv.js} +5 -3
  39. package/{index-bbkek1bp.js → index-qc0tnhs2.js} +1 -1
  40. package/{index-rh16j3c7.js → index-qnv0aqmm.js} +12 -8
  41. package/{index-0cj2zxbm.js → index-sh01r3pm.js} +1 -1
  42. package/{index-zasydjxd.js → index-t71zvmt9.js} +9 -11
  43. package/{index-rzwcpcc3.js → index-tsmjxph2.js} +1 -1
  44. package/{index-ec09pws3.js → index-x33gnap3.js} +4 -4
  45. package/{index-mr5s7mqd.js → index-xyrb7pk5.js} +3 -3
  46. package/index.js +20 -19
  47. package/{library.command-ebdj1vnm.js → library.command-v5cyaw9t.js} +5 -4
  48. package/{localRegistry.command-gb178ne8.js → localRegistry.command-53t758pt.js} +9 -8
  49. package/{module.command-9c1bnsx4.js → module.command-pq6w84xg.js} +9 -8
  50. package/{package.command-t93p4jkj.js → package.command-qkcs60ts.js} +5 -4
  51. package/package.json +3 -4
  52. package/{page.command-k3k0meh2.js → page.command-qj5bfnh9.js} +5 -4
  53. package/{primitive.command-de6nktdt.js → primitive.command-bw0nes6x.js} +10 -9
  54. package/{quality.command-z5kth2wa.js → quality.command-f8drhx6c.js} +11 -41
  55. package/{recipeScanner-tghkzrrt.js → recipeScanner-zrzev25x.js} +3 -3
  56. package/{repair.command-ehf2g112.js → repair.command-mzwtejpk.js} +7 -6
  57. package/{routeSourceValidator-cncd92fv.js → routeSourceValidator-7fycdqyv.js} +3 -39
  58. package/{scalar.command-7a2jtv33.js → scalar.command-rm6k3c65.js} +8 -7
  59. package/templates/app/env/env.server.debug.ts.template +1 -5
  60. package/templates/app/env/env.server.develop.ts.template +1 -5
  61. package/templates/app/env/env.server.local.ts.template +1 -5
  62. package/templates/app/env/env.server.main.ts.template +1 -5
  63. package/templates/app/page/styles.css.template +3 -3
  64. package/templates/appSample/srvkit/AuthGuard.ts +9 -5
  65. package/templates/appSample/srvkit/SessionInternalArg.ts +4 -3
  66. package/templates/crudPages/[__model__Id]/edit/page.tsx +1 -1
  67. package/templates/crudPages/new/page.tsx +1 -1
  68. package/templates/crudSinglePage/page.tsx +1 -1
  69. package/templates/env/_env.server.type.ts +7 -5
  70. package/templates/lib/db.ts +1 -1
  71. package/templates/lib/dict.ts +1 -1
  72. package/templates/lib/sig.ts +1 -1
  73. package/templates/lib/srv.ts +6 -2
  74. package/templates/lib/useClient.ts +9 -3
  75. package/templates/module/__Model__.Util.tsx +1 -1
  76. package/templates/module/__Model__.Zone.tsx +3 -5
  77. package/templates/workspaceRoot/AGENTS.md.template +0 -963
  78. package/templates/workspaceRoot/CLAUDE.md.template +19 -0
  79. package/templates/workspaceRoot/biome.json.template +4 -198
  80. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +4 -1
  81. package/{typeChecker-kravn7ns.js → typeChecker-g6bh0xfv.js} +1 -1
  82. package/typecheck.proc.js +1 -1
  83. package/{workflow.command-e0tt0vk2.js → workflow.command-g2cgcgxn.js} +15 -14
  84. package/{workspace.command-fpda0evj.js → workspace.command-f7jerqb2.js} +69 -51
  85. package/templates/workspaceRoot/.cursor/rules/akan-page-routing.mdc.template +0 -43
  86. package/templates/workspaceRoot/.cursor/rules/akan-sync-conventions.mdc.template +0 -33
  87. package/templates/workspaceRoot/.cursor/rules/application-test-commands.mdc.template +0 -16
  88. package/templates/workspaceRoot/.cursor/rules/change-scope.mdc.template +0 -12
  89. package/templates/workspaceRoot/.cursor/rules/client-server-boundaries.mdc.template +0 -18
  90. package/templates/workspaceRoot/.cursor/rules/coding-comments.mdc.template +0 -25
  91. package/templates/workspaceRoot/.cursor/rules/coding-style.mdc.template +0 -44
  92. package/templates/workspaceRoot/.cursor/rules/domain-module-conventions.mdc.template +0 -17
  93. package/templates/workspaceRoot/.cursor/rules/format-lint.mdc.template +0 -12
  94. package/templates/workspaceRoot/.cursor/rules/lint-enforced-rules.mdc.template +0 -18
  95. package/templates/workspaceRoot/.cursor/rules/module-file-playbook.mdc.template +0 -61
  96. package/templates/workspaceRoot/.cursor/rules/naming-conventions.mdc.template +0 -15
  97. package/templates/workspaceRoot/.cursor/rules/react-component-style.mdc.template +0 -21
  98. package/templates/workspaceRoot/.cursor/rules/repo-overview.mdc.template +0 -17
  99. package/templates/workspaceRoot/.cursor/rules/scalar-modeling.mdc.template +0 -58
  100. package/templates/workspaceRoot/.cursor/rules/secrets-and-env.mdc.template +0 -13
  101. package/templates/workspaceRoot/.cursor/rules/service-signal-conventions.mdc.template +0 -83
  102. package/templates/workspaceRoot/.cursor/rules/srvkit-adapters-and-guards.mdc.template +0 -50
  103. package/templates/workspaceRoot/.cursor/rules/ssr-first.mdc.template +0 -59
  104. package/templates/workspaceRoot/.cursor/rules/typescript-imports.mdc.template +0 -16
  105. /package/{index-r24hmh0q.js → index-yb2wsc7f.js} +0 -0
@@ -0,0 +1,986 @@
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
+ ## Lint-Enforced Rules (These Break The Build)
23
+
24
+ Enforced by `biome.json` and the grit plugins in `pkgs/@akanjs/devkit/lint/`. Several of them produce output
25
+ that looks wrong; do not "fix" it back.
26
+
27
+ - **Never hand-order Tailwind classes.** `nursery/useSortedClasses` is an error and also sorts the string
28
+ arguments to `cn()`. Sorter output such as `font-bold text-2xl text-foreground` or
29
+ `border-foreground/5 border-t` is correct. Write the classes in any order, run the formatter, leave the result.
30
+ - **Stay inside the color vocabulary.** Vocabulary closure strips the raw Tailwind palette, so these render as
31
+ no CSS and fail lint (`no-raw-palette-class.grit`, `no-arbitrary-color.grit`, `no-daisyui-legacy-class.grit`,
32
+ `no-inline-color.grit`): raw palette classes (`bg-blue-500`), arbitrary color values (`bg-[#3b82f6]`), daisyUI
33
+ legacy classes (`btn-primary`, `card-body`), and color literals in `style={{...}}`. Use semantic tokens
34
+ (`bg-primary`, `text-foreground/70`). A legitimate fixed color (OS-chrome mockups, data-viz) takes a
35
+ `// biome-ignore lint/plugin: <reason>` with the reason spelled out. `apps/akan/page/v1/**` is excluded.
36
+ - **Never `throw new Error`.** Throw `new Err("<module>.error.<key>")` and register the key as `[en, ko]` in that
37
+ module's dictionary `.error({})`. Import `Err` from `"../dict"` on the server and from `"@libs/<lib>/client"` or
38
+ `"@apps/<app>/client"` in UI. `no-throw-raw-error.grit` exempts `*.test.ts`, `*.spec.ts`, `*.constant.ts`,
39
+ `common/**`, and `apps/akan/env/**` — `common/` and `env/` have no legal `Err` import path, so keep throwing code
40
+ out of them.
41
+ - **Never import a third-party package** from `page/**`, from any barrel, or from any
42
+ `*.{constant,dictionary,document,service,signal,store}.ts` / `*.{Template,Unit,Util,View,Zone}.tsx`
43
+ (`no-import-external-library.grit`). Re-export the symbol through a lib first. One-line re-export shims such as
44
+ `libs/<lib>/base/<pkg>.ts` and `libs/<lib>/webkit/<hook>.ts` exist for exactly this reason — they are
45
+ load-bearing, not cruft. Do not delete them.
46
+ - **`#private` is banned in exactly four file suffixes:** `*.constant.ts`, `*.document.ts`, `*.service.ts`, and
47
+ `*.store.ts` (`no-js-private-class-method.grit`). The rule is scoped by file path, not by class shape, so
48
+ `#private` remains the house style everywhere under `srvkit/`, including `adapt()` adapter classes.
49
+ - **No `console.log` / `console.debug`.** Only `assert`, `error`, `info`, and `warn` are allowed. Server code uses
50
+ the injected `this.logger.*` or `new Logger("ClassName")`.
51
+ - **Never write a `//!` marker in browser-reachable code** — `ui/`, `webkit/`, `common/`, `page/**/*.tsx`,
52
+ `*.constant.ts`, `*.store.ts`, and the five module component suffixes (`no-bang-comment-in-client.grit`). Bun
53
+ classifies `//!` and `/*!` as legal comments and keeps them through minification, so the note ships to every
54
+ visitor. Use `// FIXME:` there; `//!` stays legal in server, `srvkit/`, and CLI files.
55
+ - **Never return a value from a store action** (`no-return-in-store-action.grit`). Every method of a `store(...)`
56
+ class dispatches through `st.do.<action>()`, which is typed `void` / `Promise<void>`, so the value is
57
+ unreachable — write it into state with `this.set({ ... })`. A bare `return;` guard, a `return` inside a nested
58
+ callback, a getter, and a `static` helper are all still fine.
59
+ - **Never redeclare a generated CRUD endpoint name** in `*.signal.ts` (`no-redeclare-predefined-endpoint.grit`).
60
+ - **Never type a `*.Util.tsx` / `*.Zone.tsx` prop as a `cnst` model** (`no-model-type-in-util-zone.grit`). Those two
61
+ roles are always client components, so a `cnst.Banner` / `cnst.LightBanner` prop is a class instance the server has
62
+ to hand across the boundary; take `bannerId: string` and read the model from the store instead. Two shapes are
63
+ exempt because neither is an instance: `cnst.<Enum>["value"]`, whose indexed access resolves to a string union, and
64
+ a `ClientInit` / `ClientView` / `ClientEdit` type argument, which the framework maps to `GetStateObject<…>` plain
65
+ data. Any *other* indexed access is still flagged — `cnst.Banner["image"]` is a `File`.
66
+ - **No deep imports past a barrel** (`no-deep-internal-import.grit`). Cross-module constant references such as
67
+ `../map/map.constant` are the sanctioned exception.
68
+ - **Never import across the client/server boundary.** Client files (`ui/`, `webkit/`, `page/`, `*.store.ts`, every
69
+ `.tsx`) may not import a `*.document.ts` / `*.dictionary.ts` / `*.service.ts` / `*.signal.ts`, `srvkit/`, a
70
+ package `server` entrypoint, or the `db` / `srv` / `sig` / `dict` / `option` / `useServer` barrels
71
+ (`no-import-server-in-client.grit`). Server files (those four suffixes plus `srvkit/`) may not import a
72
+ `*.store.ts`, a module component, `ui/`, `webkit/`, a package `client` entrypoint, or the `st` / `store` /
73
+ `useClient` barrels (`no-import-client-in-server.grit`). Shared files — `common/` and `*.constant.ts` — are held
74
+ to **both**, so they reach neither side. `import type` is erased before bundling and stays legal in every
75
+ direction; a mixed value-and-type import is not exempt. Scoped to `apps/**` and `libs/**`: `pkgs/akanjs/**`
76
+ implements the boundary and is where the two graphs legitimately meet.
77
+ - **Server-component discipline** is enforced on `page/**`, `*.Unit.tsx`, and `*.View.tsx`
78
+ (`no-import-client-functions.grit`, `no-use-client-in-server.grit`, `non-scalar-props-restricted.grit`).
79
+ - `noArrayIndexKey` and `useExhaustiveDependencies` are **off** on purpose: `key={idx}` for embedded scalars and
80
+ short dependency arrays are intentional, not oversights.
81
+ - **A grit plugin diagnostic is suppressed as `lint/plugin`, not `plugin`** — `// biome-ignore lint/plugin: <reason>`
82
+ for one line, `// biome-ignore-all lint/plugin: <reason>` for a file. The bare `// biome-ignore plugin:` form Biome's
83
+ own category name suggests does nothing. Suppress a plugin only where the rule is genuinely wrong for the file, and
84
+ say why: the module-convention plugins (`no-import-external-library`, `no-deep-internal-import`, the store/signal
85
+ ones) apply to `apps/**` and `libs/**` only, so a plain package under `pkgs/` never needs the escape hatch.
86
+ - **`biome.json` is strict JSON — a comment in it breaks config resolution.** Biome 2.5.8 does not report the parse
87
+ error; it falls back to discovery and aborts on whatever nested config the walk finds, typically inside a directory
88
+ `files.includes` excludes. Rename the file to `biome.jsonc` to document a disabled rule; `akan lint` pins the config
89
+ path either way, so it reports the parse error on the offending line.
90
+ - **`akan lint` prints up to 200 diagnostics** (`--maxDiagnostics <n>`, `0` for no limit). Biome's own default is 20
91
+ with no count, which reads as progress when the mix of findings merely changed.
92
+
93
+ ## Coding Style (`**/*.{ts,tsx}`)
94
+
95
+ - For large units of work, prefer declaring a class and running the flow through an instance instead of scattering many standalone functions.
96
+ - Prefer class methods or `static` methods over unrelated top-level helper functions when the logic belongs to a class-level workflow.
97
+ - 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.
98
+ - In files that declare a class, avoid top-level functions or variables when they can reasonably live inside the class.
99
+ - Prefer `const` function expressions over `function` declarations unless hoisting, overloads, generators, or framework conventions make `function` the better fit.
100
+ - Prefer declaring only one class per file; split the file when two or more class declarations are needed.
101
+ - 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`.
102
+ - Avoid keeping exported functions that only instantiate a class and immediately call one method. Prefer migrating callers to instantiate the class directly.
103
+ - Except for React component files or convention files, TypeScript filenames should use camelCase.
104
+ - 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.
105
+
106
+ ### File Size And Duplication
107
+
108
+ - Keep files small. The house median is well under 50 lines; split a component before it reaches ~150 lines rather than adding section comments.
109
+ - 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.
110
+ - Never add a sibling helper file inside `lib/<model>/`. Helpers go to `common/`, `webkit/`, `srvkit/`, or `ui/`.
111
+ - 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.
112
+
113
+ ### TypeScript Shape
114
+
115
+ - Use `interface` for object shapes and `type` only for unions and aliases.
116
+ - 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.
117
+ - Never use a non-null assertion. Narrow with `?.`, an early return, or a type predicate such as `.filter((id): id is string => !!id)`.
118
+ - Escape with `as unknown as T`. Never `as any`.
119
+ - Never annotate a component's return type. Annotate a helper only when the return is a union, a tuple, or a type predicate.
120
+ - 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.
121
+ - Async functions carry no `Async` suffix.
122
+
123
+ ### Test Code
124
+
125
+ - Write TypeScript tests with Bun's test runner and import `describe`, `expect`, and `test` from `bun:test`.
126
+ - Keep tests colocated with the source they cover using `*.test.ts` or `*.spec.ts`, following the existing nearby pattern.
127
+ - Prefer focused behavior tests for public contracts and edge cases over implementation-detail assertions.
128
+ - 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.
129
+ - 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()`.
130
+ - `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 shared lib directly.
131
+ - A placeholder `it` with a descriptive title is an acceptable floor. Write a real suite when the behaviour is security-relevant.
132
+
133
+ ## Comments
134
+
135
+ Do not narrate code. Do document the thing the code cannot say. Both halves are the rule.
136
+
137
+ - Never add a comment that restates the identifier, the signature, or the control flow.
138
+ - Prefer clear names and structure so ordinary logic needs no explanation.
139
+ - Do not add JSDoc, section banners, or "why/how" comments for ordinary logic.
140
+ - 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.
141
+ - 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.
142
+ - In-code markers:
143
+ 1. `TODO` — unfinished work that must be tracked in-code
144
+ 2. `FIXME` — known broken or incorrect behavior that must be fixed
145
+ 3. `XXX` — dangerous / surprising hazard that a reader must not miss
146
+ 4. `//!` — disabled or must-fix code. **Server, `srvkit/`, and CLI files only.** Bun's bundler treats `//!`
147
+ (and `/*!`) as a legal comment and keeps it through minification, so in browser-reachable code the note
148
+ ships verbatim to every visitor. Use `// FIXME:` there instead; `no-bang-comment-in-client.grit` enforces it.
149
+ 5. `//?` — an explanatory aside
150
+ 6. `//*` — a design note
151
+ 7. Deletion caution — warn why removing a line or block would break something non-obvious
152
+ - Keep allowed comments one short line when possible.
153
+ - Every suppression carries a reason: `// biome-ignore lint/<rule>: <why>`. Never a bare disable block.
154
+ - Match nearby file style: if the surrounding code has few comments, keep it that way.
155
+
156
+ ## TypeScript And Imports (`**/*.{ts,tsx}`)
157
+
158
+ - Use Bun and ESM assumptions from the root `tsconfig.json`.
159
+ - Prefer path aliases over deep relative imports when crossing package boundaries.
160
+ - Use `akanjs/*` for framework facets, `@apps/*` for apps, `@libs/*` for shared libs, and `@contract/*` for contract code.
161
+ - Respect existing client/server entrypoints such as `@libs/shared/client`, `@libs/shared/server`, `@apps/akasys/client`, and `@apps/akasys/server`.
162
+ - Let Biome organize imports instead of manually reshuffling unrelated imports.
163
+ - 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.
164
+ - 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.
165
+
166
+ ## Formatting And Linting
167
+
168
+ - Use Biome as the formatter and linter.
169
+ - Format with `bun run akan lint <appName>` from the repo root.
170
+ - Keep formatting consistent with `biome.json`: 2-space indentation, 120 line width, and double quotes for JS/TS.
171
+ - Avoid adding new `console` usage except accepted methods such as `console.error`, `console.info`, and `console.warn`.
172
+ - Do not make broad formatting-only changes in unrelated files.
173
+
174
+ ## Client / Server Boundaries (`apps/**`, `libs/**`, `pkgs/akanjs/**`)
175
+
176
+ - Use `"use client";` at the top of client component files.
177
+ - Be careful when importing client-only code from page or layout modules.
178
+ - Keep page props serializable unless the existing route pattern clearly allows otherwise.
179
+ - 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.
180
+ - Preserve established domain file roles such as `.document.ts`, `.service.ts`, `.store.ts`, `.constant.ts`, and `.client.ts`.
181
+ - When unsure, inspect nearby files in the same app or package before introducing a new boundary pattern.
182
+
183
+ ## SSR First — Server Rendering Is The Default
184
+
185
+ Akan is SSR-first. Every JSX element that renders on the server ships as HTML and costs nothing to hydrate;
186
+ every element behind `"use client"` ships twice — as markup and as bundled JS that must re-run in the browser.
187
+ The boundary is not about which file *may* be client, it is about **how little** ends up on the client side.
188
+
189
+ **The default is server. `"use client"` is a cost you justify per component, not a habit.** A component earns the
190
+ directive only by using a client-only capability: a React hook, a JSX event handler, the store (`st.use.*` /
191
+ `st.do.*`), a browser global, or a client-only third-party package. Rendering markup, reading a param, calling
192
+ `l()`, and mapping over data are all server work.
193
+
194
+ Measure before and after with `akan quality ssr` (`--format json` for tooling). It prints the server render share
195
+ per app and lib — server-rendered JSX elements over total — and the SSR warnings below. Treat **50% server share
196
+ as the floor** for an app or lib and a **falling share as a regression**: if a change moves markup to the client,
197
+ say why in the PR or move it back.
198
+
199
+ ### What `akan quality ssr` Flags
200
+
201
+ | Rule | Means |
202
+ |---|---|
203
+ | `akan.ssr.unnecessary-use-client` | The directive is there but nothing in the file needs it. Delete it. |
204
+ | `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. |
205
+ | `akan.ssr.client-static-markup` | A large subtree wraps one or two interactive touches. Split it: interaction stays client, markup goes server. |
206
+ | `akan.ssr.client-mount-load` | A `useEffect(…, [])` loads server data. The route can fetch it before the first byte. |
207
+ | `akan.ssr.module-missing-server-view` | A module renders only from `Template`/`Zone`/`Util` and has no `Unit`/`View` at all. |
208
+ | `akan.ssr.template-client-state` | A `Template` holds form state in `useState` instead of the store. |
209
+
210
+ A third-party client package or an `index_.tsx` `lazy()` boundary is a legitimate reason for the directive and is
211
+ not flagged. Interaction-driven `fetch.*` (a lookup inside `onClick`) is not flagged either — only mount-time loads
212
+ are, because those are the ones the server could have done.
213
+
214
+ ### Server-Side Implementation Playbook
215
+
216
+ **① Wrap the interaction, not the UI.** The smallest useful client component is a shell that adds one behaviour and
217
+ renders `children` untouched. The children stay server components, so the markup inside them never reaches the
218
+ bundle. `libs/shared/ui/Only/User.tsx` is the shape: it reads auth state on the client and returns `{children}`.
219
+
220
+ ```tsx
221
+ "use client";
222
+ export const ClickWrapper = ({ children, onPick }: ClickWrapperProps) => (
223
+ <div onClick={onPick}>{children}</div>
224
+ );
225
+ ```
226
+
227
+ **② Split compound components so panels stay on the server.** A tab, accordion, or disclosure needs client state
228
+ only for *which* part is visible — never for what the parts contain. Split into a context provider plus menu and
229
+ panel pieces, and take panel content as `children`. `Tab` / `Tab.Menus` / `Tab.Menu` / `Tab.Panel` in `akanjs/ui`
230
+ is exactly this: only the provider and the menu hold state, and `<Tab.Panel>` renders its children as-is, so a
231
+ server `Unit`/`View` passed in stays server-rendered. Never reach for one `"use client"` file with a mode
232
+ `useState` and every panel body inlined.
233
+
234
+ **③ Sync state instead of fetching it.** A server component cannot hold state, so render the initial data on the
235
+ server and hand it across the boundary as a serializable object. That is what `init` / `view` props are: the route
236
+ calls `fetch.initXInY(...)` / `fetch.viewX(...)`, passes the result into a `Zone`, and `Load.Units` / `Load.View`
237
+ hydrate the store from it. Never replace that with a `useEffect(…, [])` that fetches on mount — it renders an empty
238
+ shell, hydrates, then round-trips for data the server already had.
239
+
240
+ **④ Push the boundary down to the leaf that needs it.** When a `Zone` reads the store, it should hold *zero*
241
+ markup and delegate to a server `View`. `User.Zone.Self` is one line — `st.use.self()` into
242
+ `<User.View.General user={self} />` — so the whole detail surface renders server-side wherever a route uses the
243
+ `View` directly.
244
+
245
+ **⑤ Hand the promise across, not the awaited value.** `ClientInit` / `ClientView` are `PromiseOrObject<T>`, so a
246
+ route may pass an unawaited `fetch.initX(...)`; `Load.*` renders a skeleton and resolves it. `await` in the route
247
+ blocks the shell for data the page needs immediately; passing the promise streams the rest. Independent fetches
248
+ still go through one `Promise.all`.
249
+
250
+ **⑥ Use named `ReactNode` slots, not just `children`.** A client shell can take several server-rendered subtrees:
251
+ `Layout.Navbar` accepts `title`, `back`, `left`, `right`, and `children`, so a client navbar composes server
252
+ content in five places instead of absorbing it.
253
+
254
+ **⑦ Let the server do the derived work.** Display and predicate logic belongs on `Light<Model>` (`isNew()`,
255
+ `canWrite(user?)`, `formatTimes()`), and enum→class lookups belong in a module-scope `as const` map. Both sides
256
+ call the same method, so the server can render the result — a client component that exists only to compute a label
257
+ is markup in the wrong place.
258
+
259
+ **⑧ Gate auth on the server.** `getSelf({ unauthorize: "/signin" })` in `_layout.tsx` redirects before any HTML is
260
+ sent. A client-side auth check costs a hydration round-trip and flashes the wrong UI first.
261
+
262
+ **⑨ Prefer CSS over client state for pure visibility.** Toggling with a `data-*` attribute plus `group-data-[…]`
263
+ variants (see `libs/util/ui/Grid/*`) or with `<details>`/`<summary>` keeps both branches server-rendered. Reach for
264
+ `useState` when the state is real, not when a variant would do.
265
+
266
+ **⑩ Keep the heavy island out of the first load.** A large client-only widget goes behind the
267
+ `ui/<Folder>/index_.tsx` + `lazy()` pair so the server renders the page around it. `usePage()` and `l()` work in
268
+ server components, so translation never forces a boundary.
269
+
270
+ Full version with code, the `Tab` composition example, and a review checklist: `get_guideline` with `ssrRule`, or
271
+ `akan guideline show ssrRule`.
272
+
273
+ ## React Components And Styling (`**/*.tsx`)
274
+
275
+ - Components are `export const X = ({ … }: XProps) => { return (…); };` — arrow const with a block body. `export default` is reserved for pages, layouts, and `lazy()` targets.
276
+ - Never `React.FC`, never `defaultProps`, never `PropsWithChildren`. Defaults go in the destructuring (`prefix = ""`); children are typed `children: ReactNode`.
277
+ - `"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.
278
+ - 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.
279
+ - 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.
280
+ - 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`.
281
+ - 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.
282
+ - Read with `st.use.*` and write with `st.do.*`. Client components do not call `fetch.*`.
283
+ - 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"`).
284
+ - Multi-slot components take extra named props (`wrapperClassName`, `bodyClassName`), never a `classNames` object.
285
+ - 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.
286
+ - Use `<Link>` from `akanjs/ui` for internal navigation; `<a>` only for `mailto:` and external links.
287
+
288
+ ## Naming And Language
289
+
290
+ - 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`).
291
+ - 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`.
292
+ - Slice and filter names are prepositional: `inOrg`, `inProject`, `inPeriod`, `byStatuses`, `ofPortfolio`. Never `getXInY`, never `listX`.
293
+ - Handlers are `onX` props taking inline arrows. Do not extract a `handleX`.
294
+ - 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`.
295
+ - 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.
296
+ - 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`.
297
+ - 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 `다.`.
298
+
299
+ ## Domain Module Conventions (`apps/**/lib/**`, `libs/**/lib/**`)
300
+
301
+ - Organize business concepts as domain folders under `lib/`; keep related schema, service, signal, store, and UI files together.
302
+ - 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`.
303
+ - Use PascalCase React component files such as `<Model>.Template.tsx`, `<Model>.Unit.tsx`, `<Model>.View.tsx`, `<Model>.Zone.tsx`, and `<Model>.Util.tsx`.
304
+ - Treat `constant.ts`, `dictionary.ts`, and `signal.ts` as shared contract files that should avoid platform-specific dependencies.
305
+ - Keep backend persistence/query logic in `.document.ts` and domain business orchestration in `.service.ts`.
306
+ - 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.
307
+
308
+ ### Module File Playbook
309
+
310
+ **`<model>.constant.ts`** — five classes in order with one blank line between them and `enumOf("camelName", [...] as const)`
311
+ classes above: `XInput → XObject → LightX → X → XInsight`. Write `XInsight` even when it is empty. Put display and
312
+ predicate logic on `LightX` (`isNew()`, `canWrite(user?)`, `formatTimes()`, `isCancellable()`) — the Light class is the
313
+ one both server and client hold, so shared logic belongs there instead of in a util module. This is the most commonly
314
+ missed rule in the codebase. Collection-level helpers go `static` on the full model. Give any field whose business
315
+ meaning is not obvious a short trailing comment.
316
+
317
+ **`<model>.document.ts`** — fixed order: `XFilter extends from(...)` → `X extends by(...)` → `XModel extends into(...)`,
318
+ with `sort: {}` always present. Chain methods validate → mutate → `return this`, and never `save()`; the caller saves,
319
+ so chains compose (`org.removeUser(id).removeInvite(id).save()`). Put a one-line comment above each stating the
320
+ transition. Atomic counters live on the Model class with the updater-callback form, returning `!!modifiedCount`.
321
+ Indexes and derived totals go in `static override _onSchema`, not in the service. **Removal is always soft** — the
322
+ model facade's `removeMany(query)` and the store's `removeManyByQuery` stamp `removedAt` like `remove(id)` does; the
323
+ framework has no hard delete for a model table, and `delete` is deliberately left unused so it can mean one later.
324
+ The facade keeps `Many`/`One` spelled out on its writes (`updateOne` / `updateMany` / `removeOne` / `removeMany`):
325
+ a bare `update`/`remove` would read like the document-path `update(id)` / `doc.remove()` while hitting every match.
326
+ Only the count was shortened — `count(query)`, with `countDocuments` kept as `@deprecated`. `updateById(id, update)`
327
+ and `removeById(id)` are those same query-level writes narrowed to one id, **not** the document path: they fire no
328
+ hooks either, so a model whose removal cascades or carries a `_postRemove` still goes through `remove<Model>(id)`.
329
+
330
+ **`<model>.service.ts`** — keep methods to a few lines: load → chain → `return await ….save()`. Write `return await`
331
+ explicitly in tail position; do not "optimize" it away. Side effects belong in `override async _preUpdate` /
332
+ `_postCreate`, not inline. Fire-and-forget is explicitly `void`-ed. Order deliberately: load every referenced document,
333
+ then save, then notify. Return `null` / `false` for "not allowed" or "not found" and let the signal decide whether that
334
+ is an error.
335
+
336
+ **`<model>.signal.ts`** — `XInternal` → `XSlice` → `XEndpoint`, all three declared even when empty. `exec` is a one-liner
337
+ delegating to the service.
338
+
339
+ **`<model>.store.ts`** — write a custom action only for a toast, an optimistic update, or a multi-field write; most
340
+ stores need none, because state and CRUD actions are generated. The body is three lines: `await fetch.X` →
341
+ `this.setX(...)` → toast. The optimistic shape is mutate the client model, `void fetch.*`, then commit. Use
342
+ `this.pick(...)` when the value must exist, `this.get()` when it may not, and `this.set({...})` to write. Mutate lists
343
+ through the collection API (`this.set({ xList: xList.set(x).save() })`), not array spread. **An action returns
344
+ nothing** — `st.do.<action>()` is typed `void` / `Promise<void>`, so hand the result to `this.set({...})` rather
345
+ than returning it (`no-return-in-store-action.grit`); a bare `return;` guard stays fine. **Never
346
+ `import type { RootStore } from "../st"`** — it crashes `akan build` with a Bun SSR segfault.
347
+
348
+ **`<model>.dictionary.ts`** — fixed chain, with empty stages still written:
349
+ `.of() → .model() → .insight() → .query() → .sort() → .enum() → .slice() → .endpoint() → .error() → .translate()`.
350
+ Name every argument in `.arg()`, including framework-supplied `skip` / `limit` / `sort`. Use `modelDictionary`,
351
+ `scalarDictionary`, or `serviceDictionary` to match the module kind.
352
+
353
+ **`<module>.abstract.md`** — a title line, one declarative sentence naming what the module owns, a `## Rules` list of
354
+ two to five invariants the code cannot show, and an optional workflow arrow chain
355
+ (`draft -> signed -> active -> completed`). Never restate field lists or types. Update it whenever an invariant or
356
+ workflow changes.
357
+
358
+ ## Service And Signal Conventions (`*.{service,signal}.ts`, `server/**`)
359
+
360
+ - Keep domain business operations in `.service.ts` classes built with `serve(...)`.
361
+ - Keep execution contracts and triggers in `.signal.ts` classes built with `internal(...)`, `slice(...)`, and `endpoint(...)`.
362
+ - Use `Internal` for internal triggers such as init, interval, cron, or queue jobs.
363
+ - Use `Slice` for typed data views that feed client stores and zones; keep each slice focused on one purpose.
364
+ - Use `Endpoint` for query and mutation contracts exposed to callers.
365
+ - Connect external APIs or infrastructure through adapters, usually under `srvkit/`, and inject them into services instead of importing vendor clients directly into domain logic.
366
+
367
+ ### Guards And Transports
368
+
369
+ - Guards run on both HTTP and websocket calls. Read the caller with `context.get<T>("account")` (`pkgs/akanjs/signal/signalContext.ts`) instead of branching on `getHttpContext()` / `getWebSocketContext()`.
370
+ - Slice-level `guards` only reach the generated query/mutation endpoints. A `pubsub`/`message` endpoint is unguarded unless it declares its own `guards` in its signal option.
371
+ - A pubsub room is authorized once, at subscribe. When a socket's credential changes the framework re-runs each room's guards and unsubscribes the ones that now fail (`SignalResolver.revalidateWsRooms`), so guards must stay side-effect free and safe to re-run.
372
+ - A websocket carries its credential in the handshake snapshot on `ws.data` (`AppWsData`); clients that hold the token in memory send it with `fetch.setJwt(...)`, which forwards an auth frame over the socket.
373
+
374
+ ### Authorization Defaults
375
+
376
+ - **Every `slice()` takes an explicit `{ guards: {…} }` second argument, and `root:` is always `Admin`.**
377
+ - **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.
378
+ - **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.
379
+ - 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.
380
+ - 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.
381
+ - **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"`.
382
+ - The acting user arrives via `.with(Self)` / `.with(CurrentUserId)` / `.with(Me)`. Never trust a client-supplied id.
383
+ - 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.
384
+ - Services re-check ownership even when a guard already gated the call — two independent gates.
385
+ - `srvkit/guards.ts` earns real comments: explain what would leak without each guard.
386
+
387
+ ### Signal Body Types
388
+
389
+ - `.body(...)` / `.param(...)` args accept `ConstantFieldTypeInput` only: scalars, model refs, or `enumOf(...)`.
390
+ - Numbers must use `Int` or `Float` — `Number` is rejected (`pkgs/akanjs/signal/endpointInfo.ts`).
391
+ - `Upload` is valid only inside a mutation flagged for file upload: `mutation([cnst.File], { fileUpload: true }).body("files", [Upload])` (see `libs/shared/lib/file/file.signal.ts`). It is not a model field type.
392
+
393
+ ### Reserved Endpoint Names
394
+
395
+ - 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.
396
+ - 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.
397
+
398
+ ### Slices, Queries, and Hydration
399
+
400
+ - A slice's `exec` returns a `QueryOf` (an opaque query descriptor, `pkgs/akanjs/constant/types.ts`); you **cannot** chain `.sort()`/`.limit()` on it.
401
+ - Apply ordering/paging via the store `init` fetch option instead: `initX(..., { sort, page, limit })` (`pkgs/akanjs/fetch/fetchType/sliceFetch.type.ts`).
402
+ - Generated list accessors like `listBy(...)` return `Promise<Doc[]>`. For a chainable builder (`.sort().skip().limit().select()`) use the model facade's `findMany`/`findOne` (`FindManyChain`, `pkgs/akanjs/document/into.ts`).
403
+ - **Hydrated vs raw:** server queries return hydrated `cnst.<Model>` instances (with `set`/`save`/`refresh`); client fetch results are raw `GetStateObject` plain data (functions stripped, `pkgs/akanjs/base/types.ts`).
404
+ - Every filter generates fourteen methods: `list` · `listIds` · `find` · `findId` · `pick` · `pickId` · `exists` ·
405
+ `count` · `insight` · `query` · **`remove`** · **`removeOne`** · **`update`** · **`updateOne`**. The last four are
406
+ query-level writes — one atomic UPDATE, **no hooks**, and therefore no `_postRemove` and no cascade. Use them on a
407
+ model that carries no removal side effect; otherwise remove documents one at a time.
408
+ - **`update<Filter>` / `updateOne<Filter>` are chains, not calls:** `await updateInRoot(rootId).set({ status:
409
+ "archived" })`. The patch cannot trail the filter args — a filter's own args may be optional and no tuple type
410
+ puts a required element after those — so it lands on a terminal `.set()`, mirroring the `UPDATE … SET …` it
411
+ compiles to. Building the chain touches nothing; only `.set()` runs a query.
412
+ - `removeOne` / `updateOne` hit the **newest** match — the subquery they compile to is ordered `createdAt` descending
413
+ and there is no way to change that. They also report only counts, never which row they touched, so they are for
414
+ "there is at most one of these", not for claiming the next item off a queue. Pass a query that matches one row.
415
+ - **A filter may not be keyed after its own model.** Filter methods are assigned after CRUD, so a filter `chat` on
416
+ model `chat` would silently swap the single-document `removeChat`/`updateChat` for a hookless query-level one. It
417
+ throws at boot instead (`assertFilterFitsCrud`).
418
+
419
+ ### Text Search In A Filter — `q.search()`
420
+
421
+ - Text search is a filter query node like any other: `bySearch: filter().arg("text", String).query((text, q) =>
422
+ q.search(text, { prefix: true }))`. The generated `listBySearch` / `countBySearch` / `queryBySearch` /
423
+ `insightBySearch` come for free — you do **not** need a slice to make search usable.
424
+ - **Only add a search slice when the model's data is safe to enumerate.** A filter is server-side; a slice is a
425
+ client-callable endpoint, so on a model whose slice `get:` is `Public` a search slice hands anyone a way to walk the
426
+ table. Leave that decision to the mounting app.
427
+ - `q.search()` compiles to a JOIN, not a WHERE fragment, so it **must sit at an AND position**. Nesting it under
428
+ `q.any()` or `q.not()` throws, and it is rejected in `updateOneByQuery` / `updateManyByQuery` — a query-level write
429
+ takes no join, so ignoring the node would silently widen the write to every other matching row.
430
+ - Blank or whitespace-only input matches **nothing**. Never "fix" that into a passthrough: a passthrough turns a
431
+ search endpoint into a full listing.
432
+ - Order by relevance with the built-in `relevance` sort key. It is an empty sort map, which the store reads as
433
+ "unspecified": score order when a search join is present, `createdAt` descending otherwise. That fallback is the
434
+ compiler's own, not a model-defined default — redefining `latest` on the model does not change it.
435
+ - **A slice endpoint never reaches "unspecified".** The resolver fills `latest` before the query is built, so a
436
+ client asking for the score order has to name `relevance`; leaving `sort` off gets `latest`, not relevance.
437
+ - Scope a search with `columns` (`q.search(text, { columns: ["title"] })`) and re-weight with `weights`, a tuple of
438
+ finite numbers positional over `["title", "desc", "tag", "filter"]`.
439
+
440
+ ### Service / Signal Injection
441
+
442
+ - 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`).
443
+ - 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.
444
+ - 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.
445
+
446
+ ### Adapters — `adapt()` And `plug()`
447
+
448
+ An injected singleton is an `adapt()` class in `srvkit/`. Write new adapters this way.
449
+
450
+ ```ts
451
+ export class AdminNoti extends adapt("adminNoti" as const, ({ use, env, plug, memory }) => ({
452
+ discordApi: use<DiscordApi>(),
453
+ workspaceRoot: env(() => `~/build/${getEnv().environment}`),
454
+ masterHost: plug(MasterHost),
455
+ tokenMap: memory(Map, { of: String }),
456
+ })) {}
457
+ ```
458
+
459
+ - 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`.
460
+ - **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.
461
+ - `this.logger` is provided; never construct a `Logger` inside an `adapt()` class. Lifecycle work goes in `override async onInit()`.
462
+ - **`adapt()` is for singletons only.** A per-use value object stays a plain class you `new` at the call site. Ask whether there is exactly one per process that a service needs injected; if not, it is a plain class.
463
+ - **Legacy shape — recognise it, do not copy it.** Plain classes with `constructor(options: XOptions)`, registered in `lib/option.ts` as `options.x ? new XApi(options.x) : null` and injected with `use<T>()`, still work. Migrate one to `adapt()` only when you are already changing it.
464
+
465
+ Conventions that hold for both shapes:
466
+
467
+ - Route every remote call through one private `#api<T>(path, init?)` with `signal: AbortSignal.timeout(20_000)`.
468
+ - Paginate with `for (let page = 1; ; page += 1)` broken by `if (pageItems.length < 100) break;`.
469
+ - Resolve secrets as `process.env.X ?? options.x ?? deterministicGenerator(...)` **inside a function**, never at module scope.
470
+ - Extend a function by appending an optional trailing parameter with a default, never by changing arity.
471
+ - 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.
472
+ - Release locks in `finally`. Load heavy optional dependencies through a module-level memoized promise (`puppeteerLoad ??= import("puppeteer")`).
473
+
474
+ ### Error Placement
475
+
476
+ - State-machine preconditions throw in `document.ts`; cross-document rules throw in `service.ts`; request-level policy belongs in `signal.ts` guards.
477
+ - Best-effort code returns a sentinel (`null`, `undefined`, `[0, 0]`, `{}`). There are no Result/Either wrappers.
478
+ - `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.
479
+ - 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.
480
+
481
+ ### MCP Exposure
482
+
483
+ Every signal is served to AI agents as an MCP server on `POST /mcp`. **`/mcp` is mounted by default and exposure
484
+ follows an endpoint's guards — there is no per-endpoint opt-in, and nothing to write in a signal file.** An endpoint
485
+ that declares a real guard is published; one that declares none is refused, and so is a mutation whose only guard is
486
+ `Public`. `AKAN_MCP=false` takes the whole surface off. The reasoning is that the guards are already the
487
+ authorization decision and `filterForAccount` re-reads them per caller on every listing, so a second per-endpoint
488
+ switch says nothing the guards do not — while guaranteeing that every endpoint added later is invisible to agents
489
+ until somebody remembers it.
490
+
491
+ Settings live in the app's `lib/option.ts` — `option.setMcp({ … })`, taking `enabled`, `readOnly`, `path`,
492
+ `version`, `instructions`, `allowedOrigins`, `pageSize`, `language`, and `auth`. **Not `main.ts`**: the gateway
493
+ there only spawns children, and `option.ts` is the app-authored file `server.ts` already hands to the process that
494
+ mounts `/mcp`. Every lib's option is read in mount order with the app's last, so an app tightens what a library
495
+ declared without restating it. Each field also has an env spelling (`AKAN_MCP`, `AKAN_MCP_READONLY`,
496
+ `AKAN_MCP_PATH`, `AKAN_MCP_VERSION`, `AKAN_MCP_INSTRUCTIONS`, `AKAN_MCP_ALLOWED_ORIGINS`, `AKAN_MCP_PAGE_SIZE`,
497
+ `AKAN_MCP_LANGUAGE`, `AKAN_MCP_AUTH_SERVERS`, `AKAN_MCP_SCOPES`, `AKAN_MCP_RESOURCE`) for a deployment that
498
+ configures what the source does not, which the option overrides.
499
+ The two booleans answer to `AKAN_PUBLIC_MCP` / `AKAN_PUBLIC_MCP_READONLY` too, the same pairing `AKAN_OPENAPI`
500
+ has, and a value written in code wins over the env of the same name — an explicit `undefined` is not a value.
501
+ `AKAN_MCP_PATH` is normalized to a leading `/`, because the route key and the OAuth metadata path are both built by
502
+ concatenation.
503
+
504
+ ```typescript
505
+ // apps/<app>/lib/option.ts
506
+ export const option = new AkanOption<ModulesOptions>().setMcp({
507
+ instructions: "Domain tools for the akan app. Start from taskInTodo.",
508
+ language: "en",
509
+ });
510
+ ```
511
+
512
+ ```typescript
513
+ // <model>.signal.ts — every one of these is an MCP tool or prompt, with no `mcp:` option anywhere
514
+ export class TaskSlice extends slice(
515
+ srv.task,
516
+ { guards: { root: Admin, get: SignedIn, cru: SignedIn } },
517
+ (init) => ({
518
+ // its own guards: the map above reaches base CRUD and the root slice, never a named slice — so a named slice
519
+ // that names none is refused rather than published, which is the one shape to watch for.
520
+ inTodo: init({ guards: [SignedIn] }).exec(function () {
521
+ return this.taskService.queryByStatuses(["todo"]);
522
+ }),
523
+ }),
524
+ ) {}
525
+
526
+ export class TaskEndpoint extends endpoint(srv.task, ({ mutation, prompt }) => ({
527
+ startTask: mutation(cnst.Task, { guards: [SignedIn] })
528
+ .param("taskId", ID)
529
+ .exec(async function (taskId) {
530
+ return await this.taskService.startTask(taskId);
531
+ }),
532
+ reviewTask: prompt({ guards: [SignedIn] })
533
+ .param("taskId", ID)
534
+ .exec(async function (taskId) {
535
+ const task = await this.taskService.getTask(taskId);
536
+ return [Msg.user(`Review this task and suggest next steps.`), Msg.resource(`akan://task/${taskId}`, task)];
537
+ }),
538
+ })) {}
539
+ ```
540
+
541
+ - **The refusals are fail-closed**: **an endpoint that declares no `guards` at all** (nobody decided who may reach
542
+ it), **a mutation with no real `guards`** (`[Public]` is having none, spelled out — it answers true
543
+ unconditionally), `pubsub` and `message` (their internal args read a socket an MCP request does not have), an
544
+ `Any` or `Upload` return, a file upload, and **an argument typed `Any` that must be filled**.
545
+ A `prompt` refuses two more, because its `arguments` is one string per name with no schema beside it: a **list
546
+ argument**, which could never carry a second value, and **any `Any` argument** — a tool leaves that out of its
547
+ schema, and a prompt has no schema to leave it out of.
548
+ - **Every refusal is named in the boot log**: one `warn` per endpoint plus a `MCP catalogue: tools=… prompts=…`
549
+ count. Read that line first when a tool you expected is missing — and it is the *only* place the answer exists,
550
+ because there is no absent opt-in to notice. The API explorer badges the same rule per endpoint (`MCP` /
551
+ `MCP refused`), from the same shared implementation the catalogue runs.
552
+ - **An `Any` argument is left out of the published schema** rather than described as `{}` — it tells a model
553
+ nothing — and a value sent for one is refused by name, so the endpoint reads it as omitted. That is what happens
554
+ to the root list's raw `query` descriptor: read as sent, it would be an arbitrary filter over every model you
555
+ publish. Declare a named filter slice when an agent should narrow a list.
556
+ - **A nullable model return publishes no `outputSchema`**, and its empty answer ships as the text `null` with no
557
+ `structuredContent`. That field is an object by definition, so `null` cannot ride in it any more than an array
558
+ can — a list is wrapped as `{ items: … }` for the same reason — and a declared schema obliges every result to
559
+ match it, so a client SDK throws on the first call that finds nothing. A nullable *list* keeps its schema, and a
560
+ scalar return has no structured half at all: it ships as the value itself, not as JSON.
561
+ - **An `outputSchema` names no `hidden` or `secret` field.** Every response has both stripped, so publishing them
562
+ promises a property no answer can carry — and on a model like `user` the names are the leak. Your *input* schema
563
+ keeps them: they are legal to send, and the same model describes a request body.
564
+ - A refused endpoint answers the *same* "unknown tool" as one that does not exist. Never make that
565
+ message more helpful — the difference is what enumerates your private surface. A guard's refusal is generalized
566
+ the same way: the caller reads `You are not permitted to perform this action.`, never `Access denied by guard:
567
+ Admin`, which names your authorization structure to the one caller barred from it. A domain `Err` resolves
568
+ through the dictionary first and keeps its own words.
569
+ - The `readOnly` / `destructive` / `idempotent` hints a client renders are derived from the endpoint type and key
570
+ and are not configurable. Clients are told to distrust hints; they are never a gate.
571
+ - **`AKAN_MCP_READONLY=true` is the read-only-deployment valve, not the exposure switch.** It drops every mutation
572
+ whatever it declared, and reports each one in the boot log like any other refusal.
573
+ - OAuth resource metadata is published at `/.well-known/oauth-protected-resource` (and at that path plus the mount
574
+ path, the spelling most clients try first). `AKAN_MCP_AUTH_SERVERS`, `AKAN_MCP_SCOPES`, and `AKAN_MCP_RESOURCE`
575
+ configure it; `insufficient_scope` is enforced only once `AKAN_MCP_SCOPES` is set. A token carrying no `aud` at
576
+ all is refused once `AKAN_MCP_AUTH_SERVERS` names an issuer — that issuer mints tokens for its other resources
577
+ too — and accepted while none is named, because a first-party Akan token is bound by app and environment.
578
+ - **The boot log names every published entry with no dictionary `.desc()`.** An agent picks a tool by its
579
+ description, so a missing one is a broken tool. What the framework generates has no text of its own and borrows
580
+ the model's: the generated list reads the `.of()` label, and the base CRUD tools append the model's `.desc()` to
581
+ their generated `Get X`. Write that model `.desc()` — it is the only text those entries can carry. There is no
582
+ `akan quality scan` rule for this any more: a source scanner found the exposure only as an `mcp:` literal, and
583
+ with exposure derived from the guards the resolved catalogue is the only place that can answer.
584
+ - A browser-hosted client needs `allowedOrigins` **and** the CORS answer the server sends back for those origins.
585
+ Every other MCP client sends no `Origin` at all, and the one that does is matched against the forwarded host so
586
+ a proxy does not turn each call into a 403 — which is only as trustworthy as an edge that *overwrites* that
587
+ header. `AKAN_MCP_RESOURCE` pins the resource identifier where you cannot guarantee it.
588
+ - **A `resources/read` uri that does not decode** — a stray `%` — is `Unknown resource`, not a server failure.
589
+ - **A caller's own mistake is reported as one** and never as a server failure: an argument that is missing,
590
+ unparseable or **undeclared** comes back as `isError` naming it — `additionalProperties: false` travels in the
591
+ published schema and nothing on the wire enforces it — and so does a document that is not there, as
592
+ `No <model> found for the arguments given.` A `prompt`, having no `isError` to carry a refusal, answers `-32602`.
593
+ Only a real failure logs a stack; an agent can drive the rest at will.
594
+ - **Three revisions are spoken**: the modern `2026-07-28` and the legacy `2025-11-25` / `2025-06-18`, which are
595
+ wire-identical over the POST-only surface this implements — a client whose proposal is not listed is told to
596
+ disconnect. An unknown proposal is answered at whichever end of that list it is closer to, and an unimplemented
597
+ method answers `404` to a modern client but `200` to a legacy one, whose era spends `404` on "your session is
598
+ gone".
599
+ - **A modern-era request mirrors `MCP-Protocol-Version` and `Mcp-Method` into headers** (plus `Mcp-Name` when the
600
+ body names one), and one that leaves a mirror out is refused just like one that contradicts the body: a gateway
601
+ rule keyed on a header never fires for the request that omitted it. Legacy requests are not checked. Capabilities
602
+ are derived from the catalogue, so a server with no prompts does not advertise `prompts`.
603
+ - **An expired or wrongly-audienced bearer token is refused up front**, so an agent is told to authenticate rather
604
+ than that the tool does not exist. Its **signature is not checked** — that needs your app's own secret — so a
605
+ token signed wrong, like an opaque one, still degrades to an anonymous caller.
606
+ - **Resource URIs**: `akan://<model>/{id}`, `akan://<model>/light/{id}`, `akan://<model>/list` for the model's own
607
+ list, and `akan://<model>/list/<sliceKey>` for a slice's. The root list takes no third segment on purpose — any
608
+ token there is one a slice could also be named. **Those four are the whole set**, so only the generated reads are
609
+ addressable: a custom endpoint keeps its tool and gets no resource template.
610
+ - **The catalogue is one language**, `en` unless `language` says otherwise: it is built once at boot and cached by
611
+ clients, so there is no `Accept-Language` negotiation.
612
+
613
+ **`prompt()`** is invoked by the *user* — a client renders it as a slash command — not chosen by the model. `exec`
614
+ returns `PromptMessage[]`, or a bare string that is wrapped into one user message; build them with `Msg.user` /
615
+ `Msg.assistant` / `Msg.link` / `Msg.resource` / `Msg.image` / `Msg.imageOf`. It takes `.param()` and `.search()`
616
+ only, because `prompts/get` sends a flat string map. **An embedded payload is masked by the model you name** —
617
+ `Msg.resource(uri, task, { model: cnst.LightTask })`, or `Msg.mask(cnst.LightTask, task)` for one piece of an
618
+ assembly. Taking the model as an argument is what makes a `{ ...doc }` spread maskable, since that and `toJSON()`
619
+ arrive with the class already gone; a value with no model named whose `hidden`/`secret` fields are populated is
620
+ **refused**, one level into a plain object too. **A `prompt` is also mounted as a
621
+ plain HTTP `GET` whether or not you enabled MCP**, because that route is what lets a web UI preview one — and it
622
+ is in your OpenAPI document like any other `GET`, answering the one fixed `PromptMessage[]` shape. MCP exposure
623
+ gates the catalogue, not the surface, so guard it
624
+ like any other read — and a prompt declaring no
625
+ `guards` at all is named in the boot log, while an explicit `[Public]` is a decision and stays quiet. Every `Msg` builder takes
626
+ optional `annotations` last (`audience`, `priority` 0..1, `lastModified`) — give the instruction a high `priority`
627
+ and its attachments a low one, or a client with a full window drops blocks by position and keeps the attachment
628
+ over the ask.
629
+
630
+ **`McpProgress.report(n, { total, message })`** reports progress from anywhere inside a call, a service or adapter
631
+ frames down included, and is a no-op when nobody is streaming — so the same code runs unchanged over HTTP, a
632
+ websocket, and in tests. `McpProgress.streaming` says whether anyone is reading, for a report whose message
633
+ costs something to assemble.
634
+
635
+ ## In-Page Agent
636
+
637
+ Every akan app can host a component-level agent that reads the rendered screen and drives it. **A component
638
+ declaration is the surface, exactly**: `st.tool` publishes one action, and `st.use` / `st.sel` / `st.ref` make one
639
+ store key readable while the reading component is mounted. Nothing is derived from a store class — declaring a
640
+ method on a `store(...)` gives an agent nothing at all, because a lever the screen does not offer the user is not
641
+ one an agent may pull in their place, and a module's whole vocabulary published at once was noise the model paid
642
+ for. `Load` scopes, the route, and the live keys complete the context. The React core is the `use-agentic` package;
643
+ apps and libs never import it directly (`no-import-external-library`) — everything reaches them through `st.*` and
644
+ `akanjs/ui`.
645
+
646
+ - **Mount `<Agent.Chat />` once in a layout.** That is the floating chat, the approval card, and the client-side
647
+ loop. The default runner drives `runAgentTurn`, which the **framework serves on every app** — no lib to mount,
648
+ `AKAN_AGENT=false` takes it off — and negotiates streaming via `accept`, so assistant text arrives as it is
649
+ generated with zero app code. The endpoint is a stateless relay and **never executes tools**: every tool runs in
650
+ the caller's own browser session, gated by guards and the approval card. Its guard is `AgentRelayAccess`, which
651
+ **refuses every call until a policy is registered** — the same answer `None` gives, with no boot warning. A
652
+ product with accounts locks it in its `option.ts`, `option.setAgentAccess((ctx) => !!ctx.get("account"))`;
653
+ without a policy the chat cannot spend the LLM key.
654
+ `persist` keeps the transcript across reloads (sessionStorage; `{ storage: "local" }` to outlive the tab),
655
+ default off. Re-skin through the `AgentChat` slot in `_overrides.tsx`.
656
+ - **The LLM is configured in `option.ts`, never through the environment.** `option.setLlm({ apiKey, model, host })`
657
+ — or `setLlm((options) => …)` to read the key out of the app's own env object, which is where a secret belongs —
658
+ fills whichever adaptor holds `LlmAdaptorRole`, reaching it as the `llmOption` use. The settings are the role's
659
+ rather than one provider's, so they survive a swap. **DeepSeek is the built-in default** (`deepseek-v4-flash` at
660
+ `https://api.deepseek.com`); with no `apiKey` the app still boots and the chat answers `llmUnavailable`. Swap
661
+ providers the way middleware is applied: `option.applyAdaptor(LlmAdaptorRole, ClaudeLlm)`, where the
662
+ implementation is an `adapt()` class in a `srvkit/` implementing `LlmAdaptor.chat(request, onDelta?)` — ignore
663
+ `onDelta` and the chat still answers whole.
664
+ - **`<Agent.Zone id="comments">` runs a second agent over one section, in parallel with the root.** Everything
665
+ mounted inside — `st.use` subscriptions, hook tools, Guides — belongs to that zone's own conversation *and*
666
+ stays visible to the root agent: **zones are views, never walls**, so wrapping a section costs the root nothing.
667
+ An `Agent.Chat` inside binds to the zone session automatically; a zone's `readScreen` reads only its own
668
+ `data-agent-zone` container; guides follow the layout cascade (ancestors and own, never a sibling's). Zone
669
+ membership is positional — there is no per-declaration zone key, so a lib component joins whatever zone the app
670
+ mounts it in.
671
+ - **Route guidance is `<Agent.Guide instructions="..." />`** rendered from a `_layout.tsx` or a page — the render
672
+ tree is the cascade: nested Guides concatenate outer-to-inner and navigating away withdraws them. It is a
673
+ component, not a pageConfig field. Module `*.abstract.md` files are developer docs and are never served to the
674
+ agent.
675
+ - **Declare the tool beside the control that already does it.**
676
+ `st.tool("x", { desc }).arg("id", ID).exec(fn)` publishes one action and returns the callable to hand to
677
+ `onClick` — one handler for the person and the agent, which is the point: a button wired to an inline arrow can
678
+ be clicked by a person and by nobody else. `.exec()` is the only hook, so the chain completes in one
679
+ unconditional statement, and the callable carries `data-akan-action` like a store setter does. A `remove*` name
680
+ defaults to a confirm gate. Reach a store action from the body — `.exec((id) => st.do.removeX(id))` — which is
681
+ how an agent gets CRUD; `st.do` on its own reaches nobody.
682
+ - **A falsy name declares the tool without publishing it** — the callable still drives the click a person makes,
683
+ and the agent never learns the tool exists. That is the only way a conditional surface stays legal, because
684
+ `.exec()` is a hook and the declaration can never be skipped: withhold the name, not the call. `st.useState`
685
+ and `st.expose` take a falsy name the same way, and an unpublished callable carries no `data-akan-action` —
686
+ that attribute names a tool an agent can reach. **Publish a tool only where the screen already renders the
687
+ control**: a lever no one can pull by hand is not one to hand an agent, and every published tool is paid for in
688
+ every turn's prompt. The mirror of the same rule is why the control gets a tool at all.
689
+ - **An `enumOf` class is a complete argument type on its own**: `.arg("mode", TaskStatus)` publishes the values as
690
+ the argument's `enum`, refuses anything off them by name at call time, and narrows the `.exec` parameter to the
691
+ value union — nothing else to write, and the scalar (`string` / `integer` / `number`) comes from the values.
692
+ **A value set the *render* decides takes `.arg(name, type, { oneOf })`** instead, because `enumOf` registers
693
+ globally and a component cannot build one per render: pass the list it has — a slice's sort keys, the options a
694
+ prop carried — and it is published and enforced the same way. Neither reaches a set that fills in *after* the
695
+ first render, since a declaration is mount-static; put that in the tool's `guard`, which is re-read per call and
696
+ can name the current values in its refusal.
697
+ - **A component that renders once per row publishes nothing.** A tool registered under one name by fifty rows is
698
+ forty-nine collisions and one survivor. The container publishes one tool taking the id instead —
699
+ `removeTask(taskId)`, never fifty `removeTask` — and the agent reads the ids from the `<slice>.items` resource
700
+ `Load.Units` and `Data.ListContainer` already expose.
701
+ - **`akanjs/ui` publishes its own controls, so an app writes nothing for them.** `Data.ListContainer` (and every
702
+ `Model.AdminPanel`) publishes its toolbar and its row and modal verbs; `Load.Units`, `Load.Pagination` and
703
+ `Data.Pagination` publish `setPageOf<Model>`; `Layout.Sider`, `System.SelectLanguage`, `Link.Back` and
704
+ `System.ThemeToggle` publish the shell. **A component that can render twice on one screen takes a
705
+ `namespace` prop and publishes nothing without it** — `Tab`, `Dialog`, `ScreenNavigator`. Pass one
706
+ (`<Tab namespace="detail">`) and the tool becomes `switchTabInDetail`; leave it off and that tab is invisible to
707
+ the agent, because two tabs answering to `switchTab` would mean the first to mount loses.
708
+ - **A form control publishes its own setter, and reading a form publishes one tool that fills several at once.**
709
+ Both are free: an app writes no `st.tool` for a form. A `Field.*` / `Input.*` / `Select` / `Switch` handed
710
+ `onChange={st.do.setTitleOnTask}` **by reference** publishes `setTitleOnTask` while it is on screen — the same
711
+ reference that earns `data-akan-action`, so the tool and the person press one function and an inline arrow
712
+ still publishes nothing. `st.use.taskForm()` adds `fillTaskForm(patch)`, which takes several fields in one call
713
+ and is the only way to reach a list, a map, or an embedded object, whose rows are written through
714
+ `writeOnTask(path, value)` and can carry no annotation. It is a patch: a field left out keeps its value.
715
+ `fillTaskForm` refuses a plain field whose control is not on screen and names the ones that are; a composite it
716
+ cannot see is let through, which is the one place an agent reaches a field the screen may not draw. Never a
717
+ relation (picked or uploaded, not typed), a base document field, or a `hidden`/`secret` one at any depth —
718
+ their reads are masked and a writer would be the door around that. `st.use.taskForm({ agent: false })`
719
+ withholds the patch tool; an inline arrow withholds a control's own.
720
+ - **Reading is per key, not per store.** `st.useState(name, initial, meta)` publishes local state (read-only
721
+ unless `set:` names a type) and `st.expose(name, value)` a derived value. A subscribed store key is listed in
722
+ the state context block by name and pulled with `readState(key)`, masked by the model that key declares — while
723
+ a key the screen does not read stays unreadable even when a sibling key of the same store is live. **There is no
724
+ store-level exposure declaration**: a store class says nothing about agents, and `st.use.x({ agent: false })` is
725
+ how the component that subscribes a value keeps it off the surface. Base-store plumbing does the same at the
726
+ call site — `st.use.path({ agent: false })`, `st.use.tryJwt({ agent: false })` — so routing and the caller's
727
+ credential stay off the surface unless a component opts a key in, as ThemeToggle does for `theme`.
728
+ - **Model-facing text is English, always** — tool `desc`, `instructions`, Guide text. The `l()` rule covers
729
+ strings a *user* reads: Chat's own buttons go through `l("base.*")`, the model's text never does.
730
+ - A masked model never crosses the boundary: a value whose `hidden`/`secret` fields are populated is refused at
731
+ read unless a `mask:` model is named — the same rule and wording as `AgentBridge.read`.
732
+ - **`prompt()` endpoints double as the chat's slash commands.** There is no listing endpoint — the client reads
733
+ its own serialized signals — so a prompt's dictionary `.desc()` is what the menu shows, and its guards are
734
+ enforced by the prompt's own GET at call time.
735
+ - The framework publishes five built-ins on every store surface: `navigate` (internal paths only, the same
736
+ router `Link` rides), `goBack` (this session's history — global, because history is not a control a page owns and
737
+ a page that draws no back link is not one you may not leave), `readScreen` (the rendered DOM as compact text —
738
+ headings, links, control values; the chat's own UI is skipped via `data-agent-ui`, and a password value is never
739
+ read), `readState(key)` (one masked store key), and `highlight(target)`. Declaring a hook tool under one of those
740
+ names shadows the built-in, so reuse them only to mean that.
741
+ - **A tool that changes the screen waits for the screen before it answers.** `router.push` returns while the RSC
742
+ payload is still in flight and a store action that fires `void fetch.*` commits a tick later, so `navigate`
743
+ awaits `ScreenSettle.wait()` — DOM quiescence, bounded, because the client router hands its promise to nobody —
744
+ and the session awaits it after every non-`query` tool before taking the change report. Without it the report
745
+ describes the moment before the change landed and the `readScreen` that follows reads the page the user left.
746
+ New tools and state from a fresh route are still only listed from the next turn: the catalogue is snapshotted
747
+ when the turn starts.
748
+ - **`readScreen` takes a `section`, and `highlight` a `target`.** Both resolve a name the agent has already seen —
749
+ a `data-akan-action` / `data-akan-state` annotation, an `Agent.Zone` or `useScreenScope` container
750
+ (`data-agent-scope`, which `Load.Units` / `Load.View` / `Data.ListContainer` put on the container they render),
751
+ an element id, or **a heading by its own text**, matched on letters and digits so the slug an agent writes for a
752
+ heading it read resolves. That tolerance stops at headings: a heading is a landmark and scrolling to the wrong
753
+ one costs nothing, while two buttons reading "Save" are not the same control. **Nothing hidden ever resolves** —
754
+ a ring nobody can see reads as a broken tool, not as a miss. A section named by a heading is read to the next
755
+ heading of its level or higher.
756
+ - **A screen is only aimable if its names are printed.** `readScreen` writes `(#anchor)` beside a heading that
757
+ opens an id'd or scoped container, and a truncated read ends with the headings below the cut — otherwise
758
+ everything past the 8000-character limit is unreachable, because nothing names it, and an agent asked to point
759
+ at a section it cannot name guesses a slug and is refused. A refusal lists the sections actually on screen.
760
+ `highlight` scrolls its target into view and flashes it **once the scroll lands**, since a smooth scroll across a
761
+ long page outlasts the flash; it is the one built-in that exists for the *user's* benefit, because showing where
762
+ a control is beats writing directions to it.
763
+ - **A slow tool reports its own progress with `AgentProgress.report(message, { done, total })`** from wherever the
764
+ work is — a store action, an upload loop, an adapter — reached through a module slot rather than a parameter, and
765
+ a no-op when nobody is rendering it. The chat shows it on that call's row until the row resolves. It is the
766
+ browser twin of `McpProgress.report`.
767
+ - **The turn cap is a question, not a dead end.** At `maxTurns` the session asks whether to keep going through the
768
+ same card `askUser` uses, and the answer rides as the user's own turn — so a steer typed instead of the
769
+ keep-going choice reaches the model as guidance. A host that renders no `pendingQuestion` passes no
770
+ `continueAsk` and keeps the old failure, because asking with nobody listening would hang.
771
+ - **`askUser` is a fourth built-in the *session* owns, not the surface.** The answer comes from the conversation
772
+ rather than the screen, so it rides on every turn whatever the page declares, and a zone agent asks inside its
773
+ own transcript. `choices` offers a pick (`multiple` for several) and omitting them asks for free text; the card
774
+ keeps a free-text row either way, because the model wrote the options and only the user knows whether the answer
775
+ is among them. The loop parks on the question exactly as it parks on an approval, a dismissal is the tool's
776
+ error result rather than a silent empty answer, and the settled exchange renders as question-and-answer instead
777
+ of a tool row. **Never re-implement it per screen** — a `st.tool("askAboutX")` that opens a modal is the same
778
+ thing with a worse transcript — and a hook tool named `askUser` shadows it like any other built-in.
779
+
780
+ ## Scalar Modeling (`**/*.constant.ts`)
781
+
782
+ - Define Akan models in `.constant.ts` files with `via` from `akanjs/constant`.
783
+ - Use `Int` for whole-number counts and quantities; use `Float` only for values that need decimals.
784
+ - Use `ID` for document references and prefer explicit structured fields over `Any` unless the content is genuinely flexible.
785
+ - For date defaults, prefer a function such as `default: () => dayjs()` so the value is created at runtime.
786
+ - 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.
787
+ - Put display and predicate logic on the `Light<Model>` class rather than in a util module — see Module File Playbook.
788
+ - Defaults are a literal for scalars and a thunk for anything constructed. Arrays are `field([T])`; optional is the postfix `.optional()`.
789
+
790
+ ### Scalar & Field Type Reference
791
+
792
+ - **Import from `akanjs/base`** (real classes/helpers, not globals): `Int`, `Float`, `ID`, `Any`, `Upload`, `enumOf`, and the `dayjs` factory. There is **no `JSON` scalar** — use `Any` for open/flexible payloads.
793
+ - **Use the JS globals directly (no import needed)**: `String`, `Boolean`, `Date`. They are monkey-patched to behave like scalars, so `field(String)` typechecks.
794
+ - **`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.
795
+ - Runtime resolution of every scalar (globals included) goes through `PrimitiveRegistry` by `refName` (`pkgs/akanjs/base/primitiveRegistry.ts`).
796
+
797
+ ### Text Search Fields — the `text` role
798
+
799
+ - A field joins the full-text index by declaring one of five roles: `field(String, { text: "title" })`, and likewise
800
+ `"desc"`, `"tag"`, `"thumb"`, `"filter"`. Nothing else opts a field in, and there is no per-model switch.
801
+ - Pick the role by what the value *is*, because `bm25` weights them positionally (`title` 10, `tag` 3, `desc` 1,
802
+ `filter` 0): `title` is the one line a human scans for, `desc` is prose, `tag` is a keyword list, `filter` is a
803
+ scoping value (status, owner, role) that must be matchable but must never outrank a real title hit.
804
+ - `thumb` is mirrored for rendering a hit and is **not** indexed — never expect it to match.
805
+ - **A `secret`, `hidden`, or `resolve()` field with `text` throws at class-build time**, not at query time. That is
806
+ deliberate: the mirror is plaintext, so an indexed secret would leak through search. Do not work around it. The
807
+ same throw covers a `text` field *underneath* one of those — a scalar's own field is reachable through its parent,
808
+ so `f.secret(Noti)` where `Noti.label` carries a role is rejected at the parent, not silently indexed.
809
+ - The role works on a relation too (`image: field(File, { text: "thumb" })`) and on an array (`playing: field([String],
810
+ { text: "tag" })`); an array of objects indexes by leaf key, including an array leaf (`works[*].tags`). A field
811
+ inside a `Map` indexes nothing: there is no fixed path to extract it from.
812
+ - Declaring roles is all the wiring there is. Mirror rows are maintained by SQL triggers — not document hooks —
813
+ because `updateOneByQuery` and friends fire no hooks, and most searchable-field mutations go through exactly that
814
+ path.
815
+ - Search runs on sqlite/libsql only. `q.search()` against Postgres throws, loudly, rather than returning every row.
816
+ - `AKAN_SEARCH_ENABLED=0` switches the index off process-wide; unset means on. It never deletes mirror data, and
817
+ re-enabling reconciles every ref. **Give every process the same value** — a process cannot drop triggers for models
818
+ it does not mount, so a mixed fleet leaves stale triggers behind.
819
+ - The tokenizer is `AKAN_SEARCH_TOKENIZER` (or `database.search.tokenizer`, which wins), defaulting to
820
+ `unicode61 remove_diacritics 2`. Changing it rebuilds the index from the mirror on the next boot — the model
821
+ tables are never re-read — so it is a safe knob, unlike a `text` role change, which re-reads every row. The
822
+ rebuild takes no cross-process claim, so a fleet restarted at once repeats it in every process; stagger the
823
+ restart when the mirror is large.
824
+
825
+ ### Image & File Fields
826
+
827
+ - **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.
828
+ - Declare an image/file field as a relation to `File`: `image: field(File).optional()` for one, `images: field([File])` for many (see `libs/shared/lib/user/user.constant.ts`, `libs/shared/lib/banner/banner.constant.ts`).
829
+ - 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`).
830
+ - Storage is wired through the `StorageAdaptor` DI role (default `BlobStorage`, `pkgs/akanjs/service/predefinedAdaptor/storage.adaptor.ts`); the reference implementation is the `file` lib (`libs/shared/lib/file/*`). Do not hand-roll data-URL fallbacks.
831
+
832
+ ### Cascade Remove — the `cascade` option
833
+
834
+ **The value names the direction, and getting it wrong is a data loss.** The two actions can sit on the same field
835
+ shape, so `cascade` never means "related" — it means one of exactly these:
836
+
837
+ - `removeRef` — *when I am removed, remove what this field points at.* Declared on the relation the owner holds:
838
+ `image: field(File, { cascade: "removeRef" })`, arrays included. Only a relation accepts it; a primitive, a bare
839
+ `ID`, and a scalar each fail the class build, because none of them names a document to remove.
840
+ - `removeWith` — *when what this field points at is removed, remove me.* Declared on the child's own reference to
841
+ its owner, so the owner never learns about its children and a lib model can be extended by an app's. Three forms:
842
+ a relation (`agentSession: field(AgentSession, { cascade: "removeWith" })`), an id with `ref`
843
+ (`field(ID, { ref: "agentSession", cascade: "removeWith" })`), or a polymorphic id with `refPath`
844
+ (`field(ID, { refPath: "parentType", cascade: "removeWith" })`). An array, a Map, `ref` together with `refPath`,
845
+ and a field naming no owner each fail the class build.
846
+ - **A `refPath` must name an `enumOf` field.** A free-form owner type is unknowable at build time, so every model's
847
+ removal would have to sweep the polymorphic table on the chance it is the owner. The enum names the candidates and
848
+ the reverse index reaches only them.
849
+ - **A cascade goes through the target's service, never its model** — unless it provably makes no difference. The
850
+ service path is what runs the target's `_postRemove`, which is where a module puts the side effect the removal has
851
+ to carry (`FileService._postRemove` deletes the stored blob there).
852
+ - **Bulk is decided at boot, per target model, for both directions.** When the target has no `remove` schema hook, no
853
+ `_pre`/`_postRemove` (its own or a lib's), no cascade of its own, and no children, one `removeManyByQuery` leaves
854
+ exactly the rows the loop would, so the framework takes it. Adding a `_postRemove` to that model silently flips it
855
+ back to one document at a time — the boot log (`info` summary, `verbose` per edge) is the only place that shows.
856
+ - **The plan is sealed after every service is live**, so a `listenPost("remove")` registered in `onInit` still counts
857
+ and a `removeRef` target the app never mounted fails the boot rather than the first removal. An unmounted
858
+ `removeWith` owner fails the boot too; an unmounted `refPath` candidate only warns, since that list spans optional
859
+ modules by design.
860
+ - **Nothing checks whether another document still references the same target.** `File` in particular is deduped by
861
+ `origin`, so two parents can share one row; declaring `removeRef` says the field owns its target exclusively, and
862
+ that judgement is the declaring model's to make.
863
+ - Removal is soft (`removedAt`) but the storage delete a `_postRemove` performs is not — a cascade is not
864
+ restorable, and reviving the owner does not revive what went with it.
865
+ - A `removeWith` declaration **auto-creates its index** (`{ removedAt, fk }`, or `{ removedAt, typeKey, fk }` when
866
+ polymorphic). Every non-base field lives in the `_doc` JSON column, so the lookup would otherwise scan the table
867
+ on every owner removal.
868
+ - **Query-level removes fire no hooks and therefore no cascade.** `removeManyByQuery` / `updateManyByQuery`, the
869
+ generated `remove<Filter>` / `update<Filter>`, and the facade's `removeById` / `updateById` stamp
870
+ `removedAt` in one atomic UPDATE, so nothing downstream runs. Remove one document at a time when it cascades.
871
+ - Cascades are **idempotent**: `removedAt IS NULL` is ANDed into every query-level write, so a retry after a partial
872
+ failure re-stamps nothing. Cycles are cut by a visited set carried down the whole chain, with a depth cap of 16.
873
+
874
+ ## Akan Page Routing (`apps/**/page/**`)
875
+
876
+ - `apps/<app>/page` may contain route modules only. Do not add helper logic or component-only files there.
877
+ - Route source files under `page/` must use `.tsx`. Do not add `logic.ts`, `.js`, or `.jsx` files under `page/`.
878
+ - Route pages use `_index.tsx`; layouts use `_layout.tsx`; per-route UI overrides use `_overrides.tsx`.
879
+ - Reserved `_*.tsx` route filenames are limited to `_index.tsx`, `_layout.tsx`, and `_overrides.tsx`; do not add files like `_Component.tsx` or `_helper.tsx`.
880
+ - Page filenames must not start with an uppercase letter. Move helper components like `Component.tsx` to app `ui`, `common`, or `lib` instead.
881
+ - Dynamic segments use `[id]`; route groups use directories like `(user)`, `(public)`, `(tab)`, or `(detail)`.
882
+ - Page modules should usually export `default`, `pageConfig`, `head`, `generateHead`, or `Loading`.
883
+ - `_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.
884
+ - Prefer `export default function Page` or `export default async function Page` for page components.
885
+ - `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.
886
+ - `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.
887
+ - Both path segments are route groups, so a lib route mounts at its own path (`libs/shared/page/login/_index.tsx` serves `/login`). Two synced routes that resolve to the same pattern are a sync-time error.
888
+ - `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.
889
+ - Before changing route behavior, check `pkgs/akanjs/server/src/routeTree.tsx` and nearby routes for the expected pattern.
890
+
891
+ ### Page Body Shape
892
+
893
+ ```tsx
894
+ interface PageProps {
895
+ params: { orgId: string };
896
+ }
897
+
898
+ export default async function Page({ params }: PageProps) {
899
+ const { l } = usePage();
900
+ getSelf({ unauthorize: "/signin" });
901
+ const { orgId } = params;
902
+ const [{ org }, { taskInitInOrg }] = await Promise.all([fetch.viewOrg(orgId), fetch.initTaskInOrg(orgId)]);
903
+ return <Task.Zone.Card init={taskInitInOrg} prefix={`/org/${orgId}`} />;
904
+ }
905
+
906
+ export const pageConfig = { transition: "stack" } satisfies PageConfig;
907
+ ```
908
+
909
+ - There is no `loader=` / `render=` page prop. Pages are `export default async function Page`.
910
+ - Declare `interface PageProps { params: {...}; searchParams?: {...} }` immediately above the default export.
911
+ - Body order: `usePage()`, auth, destructure params, fetch, return.
912
+ - Run independent fetches through `Promise.all`, even when there is only one.
913
+ - Gate auth at `_layout.tsx`; repeating `getSelf({ unauthorize: "/signin" })` in the page is fine and common.
914
+ - Keep `async` even when nothing is awaited — it marks a real server page.
915
+ - No `useState`, no `useEffect`, and no comments in page files.
916
+
917
+ ## Akan Sync Conventions (`apps/**`, `libs/**`)
918
+
919
+ - `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`.
920
+ - `apps/<appName>` root may only contain these folders: `.akan`, `android`, `common`, `env`, `ios`, `lib`, `mobile`, `page`, `plugin`, `private`, `public`, `script`, `secrets`, `srvkit`, `ui`, `webkit`.
921
+ - That allowlist has one source — `pkgs/@akanjs/devkit/workspaceLayout.ts`. `akan sync` (error), `akan doctor`
922
+ (diagnostic), and `akan quality scan` (warning) all read it, so add a new root entry there and mirror it into this
923
+ list, never into one of the three call sites.
924
+ - `akan sync` maintains a scoped agent guide per app/lib: `apps/<app>/AGENTS.md` / `libs/<lib>/AGENTS.md`. The
925
+ section between the `akan:agent` markers (the `## Recipes In Scope` index) is generated — do not hand-edit it;
926
+ content outside the markers is yours. `akan lint` fails when the generated section is stale.
927
+ - 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.
928
+ - Do not add `apps/*/base`; place shared app utilities under `apps/*/common`.
929
+ - `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`.
930
+ - Domain module folders are `lib/<model>` for database modules, `lib/_<service>` for service modules, and `lib/__scalar/<scalar>` for scalar modules.
931
+ - Database module UI files are limited to `<Model>.Template.tsx`, `<Model>.Unit.tsx`, `<Model>.Util.tsx`, `<Model>.View.tsx`, and `<Model>.Zone.tsx`.
932
+ - Service module UI files are limited to `<Service>.Util.tsx` and `<Service>.Zone.tsx`.
933
+ - Scalar module UI files are limited to `<Scalar>.Template.tsx` and `<Scalar>.Unit.tsx`.
934
+ - Module `*.test.ts`, `*.test.tsx`, `*.spec.ts`, and `*.spec.tsx` files are allowed.
935
+ - `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.
936
+ - Generated facet indexes export only 1-depth files/folders with `export * from "./name";`.
937
+ - `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`.
938
+
939
+ ## Layer Placement (`common/`, `webkit/`, `srvkit/`, `ui/`)
940
+
941
+ | Folder | Admission test | Naming |
942
+ |---|---|---|
943
+ | `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 |
944
+ | `webkit/` | touches `window` / `navigator` / Capacitor, or is a React hook | `use<Thing>.tsx` — `.tsx` even with no JSX |
945
+ | `srvkit/` | touches `node:*`, `Bun`, `process.env`, a secret, or a server SDK | camelCase file, PascalCase class |
946
+ | `ui/` | renders JSX and is not bound to one model | PascalCase component, camelCase sidecar (`swipeCard.util.ts`) |
947
+ | `plugin/` | build- or CLI-time `AkanPlugin` | `<name>.plugin.ts`, registered in `akan.config.ts` |
948
+
949
+ - Hooks return a named object of async closures, never a tuple.
950
+ - `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.
951
+ - 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.
952
+ - `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.
953
+
954
+ ## Present In The Code — Do Not Imitate
955
+
956
+ Older files contain these. They are warts, not conventions: do not copy them forward, and prefer the newer neighbour
957
+ when two shapes disagree.
958
+
959
+ - `children: any` — newer files use `children: ReactNode`.
960
+ - Hard-coded API keys or secrets in source; they belong in `option.ts` or env.
961
+ - Large blocks of commented-out code left in place.
962
+ - Cross-store writes through a `RootStore` cast — it collides with the Bun SSR-bundler segfault.
963
+ - Stale `// TODO: Implement …` comments above implemented methods.
964
+ - `{cond && <X/>}` in JSX, hard-coded Korean bypassing `l()`, and `window.alert(...)` for user feedback.
965
+ - Bare `/* eslint-disable */` blocks — use `// biome-ignore lint/<rule>: <why>`.
966
+ - Raw palette grays such as `text-gray-400` instead of daisyUI semantic tokens.
967
+
968
+ ## Secrets And Env Safety (`.env`, `infra/**`, `*secret*`, `*credential*`)
969
+
970
+ - Never print, summarize, commit, or expose real secret values, credentials, tokens, private keys, or `.env` contents.
971
+ - If env keys are needed for documentation, list only key names and example placeholders, not live values.
972
+ - Preserve the existing env/secret flow through root scripts such as `bun run downloadEnv`, `bun run uploadEnv`, `bun run downloadSecret`, and `bun run uploadSecret`.
973
+ - When editing infra env or secret scripts, keep Jenkins and deployment assumptions intact unless the task explicitly asks to change them.
974
+ - Treat generated env/secret artifacts as sensitive even when they are not named `.env`.
975
+
976
+ ## Application Test Commands
977
+
978
+ - After changing application source code, test the app with `bun run akan start <appName>`.
979
+ - Test production build generation with `bun run akan build <appName>`.
980
+ - To test a built artifact locally, run it from the generated app directory with the required Akan runtime environment variables.
981
+
982
+ ```bash
983
+ cd dist/apps/akan && USE_AKANJS_PKGS=true AKAN_PUBLIC_REPO_NAME=akanjs AKAN_PUBLIC_SERVE_DOMAIN="akanjs.com" AKAN_PUBLIC_APP_NAME=akan AKAN_PUBLIC_ENV=local AKAN_PUBLIC_OPERATION_MODE=local SERVER_MODE=federation AKAN_PUBLIC_BASE_PATHS=akanjs,soft,office bun main.js
984
+ ```
985
+
986
+ - Adjust `<appName>`, `AKAN_PUBLIC_APP_NAME`, and `AKAN_PUBLIC_BASE_PATHS` to match the app being tested.