@akanjs/cli 3.1.1-rc.15 → 3.1.1-rc.17

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 (120) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-gtwn7tmb.js → CodeAgent-fbcq8vks.js} +2 -2
  3. package/{CodeTui-v941fqdh.js → CodeTui-0626gxqd.js} +1 -1
  4. package/TunnelShare-2p24xxza.js +14 -0
  5. package/agent.command-hpza0pg9.js +46 -0
  6. package/akanCode.js +5 -3
  7. package/{application.command-j1reb9p1.js → application.command-3a7q1hs2.js} +11 -10
  8. package/{applicationBuildRunner-w20x63mz.js → applicationBuildRunner-s7yt71j4.js} +6 -5
  9. package/buildBatch.proc.js +6 -6
  10. package/{cloud.command-zd2mfkm0.js → cloud.command-4vg0pcea.js} +15 -14
  11. package/cloud.script-nkmeyhet.js +25 -0
  12. package/{code.command-dyet4xn6.js → code.command-fbntb67p.js} +6 -6
  13. package/commandManifest.json +1 -1
  14. package/{context.command-79gxczm4.js → context.command-31rm54v0.js} +18 -17
  15. package/context.runner-w01a32ph.js +26 -0
  16. package/{guideline.command-xwkskvky.js → guideline.command-cv3by2ng.js} +3 -3
  17. package/guidelines/conventions/core.md +104 -0
  18. package/guidelines/conventions/rules/app.md +83 -0
  19. package/guidelines/conventions/rules/auth.md +45 -0
  20. package/guidelines/conventions/rules/config.md +56 -0
  21. package/guidelines/conventions/rules/constant.md +24 -0
  22. package/guidelines/conventions/rules/gates.md +31 -0
  23. package/guidelines/conventions/rules/layer.md +25 -0
  24. package/guidelines/conventions/rules/migration.md +27 -0
  25. package/guidelines/conventions/rules/module.md +90 -0
  26. package/guidelines/conventions/rules/page.md +56 -0
  27. package/guidelines/conventions/rules/sensitive.md +16 -0
  28. package/guidelines/conventions/rules/server.md +86 -0
  29. package/guidelines/conventions/rules/ssr.md +47 -0
  30. package/guidelines/conventions/rules/style.md +43 -0
  31. package/guidelines/conventions/rules/test.md +34 -0
  32. package/guidelines/conventions/rules/ts.md +95 -0
  33. package/guidelines/conventions/rules/tsx.md +75 -0
  34. package/guidelines/mcpRule/mcpRule.instruction.md +1 -1
  35. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +3 -3
  36. package/incrementalBuilder.proc.js +6 -6
  37. package/{index-pqdz7rat.js → index-05nxx4m5.js} +952 -47
  38. package/{index-41d3zx66.js → index-0ht91675.js} +37 -59
  39. package/{index-cz9g85xh.js → index-0zwznvv1.js} +1 -1
  40. package/{index-7ktk2hnz.js → index-0zyatd10.js} +2 -2
  41. package/{index-8jb5ep2e.js → index-12kzwak1.js} +3 -3
  42. package/{index-yknrmkmt.js → index-1dhf8ymv.js} +2 -2
  43. package/{index-qmeh0s05.js → index-3gccwenr.js} +2 -2
  44. package/{index-hdzjaq7s.js → index-3txrjt6n.js} +2 -2
  45. package/{index-tzzs52h0.js → index-57q1ayd2.js} +18 -1240
  46. package/index-5kh9scvs.js +514 -0
  47. package/index-5n5hds19.js +1246 -0
  48. package/{index-pc9ps0hx.js → index-6269mf2s.js} +10 -9
  49. package/{index-1e2955yd.js → index-64g9fsjy.js} +43 -12
  50. package/index-7zeb5r1p.js +653 -0
  51. package/{index-kr62ph5a.js → index-8s8b4eba.js} +45 -4
  52. package/{index-wvvwdzfw.js → index-922k2zwq.js} +3 -3
  53. package/{index-brpk7gd8.js → index-9ndw5d8j.js} +7 -7
  54. package/{index-xeh7m2j5.js → index-et6ce601.js} +1 -1
  55. package/{index-jtydvvq7.js → index-f5adsa58.js} +4 -4
  56. package/index-fbewhg4g.js +590 -0
  57. package/{index-7abjzny1.js → index-hm7x0c11.js} +33 -37
  58. package/{index-rshwdv9w.js → index-hvv5rnaq.js} +2 -2
  59. package/index-jje9qzyq.js +27 -0
  60. package/index-js1gj6f6.js +410 -0
  61. package/{index-2qzzp0c9.js → index-kjrvwzav.js} +3 -3
  62. package/index-m5n3ka0p.js +18 -0
  63. package/index-m6r88hhr.js +3582 -0
  64. package/{index-4rwfh2de.js → index-mt0wa941.js} +4 -4
  65. package/{index-553xyb55.js → index-mwj9q2ya.js} +1 -1
  66. package/{index-5nd1wtkv.js → index-p6x5b7hr.js} +1 -1
  67. package/index-r2wedvqn.js +138 -0
  68. package/{index-ygy8c12j.js → index-rvynj5gz.js} +1 -1
  69. package/{index-nmy1rana.js → index-tdv66eah.js} +4 -4
  70. package/{index-8rvwgd1r.js → index-w134p86k.js} +1 -1
  71. package/{index-jjd97ya6.js → index-wfczhj1z.js} +14 -36
  72. package/{index-dy0jx9ay.js → index-wwe9rsrx.js} +14 -0
  73. package/{index-kbbyzs6j.js → index-x5ecanqh.js} +2 -2
  74. package/{index-ch1sv7ke.js → index-zre4m2ce.js} +9 -21
  75. package/index.js +23 -22
  76. package/{library.command-td8t85kb.js → library.command-sh70fyvy.js} +3 -3
  77. package/{localRegistry.command-jx9zkmxf.js → localRegistry.command-2nbyy84d.js} +17 -14
  78. package/{module.command-j70mqgpp.js → module.command-n0bmtzwy.js} +5 -5
  79. package/{package.command-1b1v6k5v.js → package.command-7h9r51bz.js} +3 -3
  80. package/package.json +2 -2
  81. package/{page.command-m31w2tsz.js → page.command-vjtpfbb1.js} +3 -3
  82. package/{pipeline.command-q7b8wy55.js → pipeline.command-c93se3ar.js} +2 -2
  83. package/{primitive.command-4zrbhkb9.js → primitive.command-a3075qp2.js} +6 -6
  84. package/{projectTypecheck-synx6qff.js → projectTypecheck-sf9xwaga.js} +1 -1
  85. package/{prompter-76k56b37.js → prompter-hgcta8pb.js} +1 -1
  86. package/quality.command-dw1y9hmy.js +76 -0
  87. package/{repair.command-98n6zxg7.js → repair.command-tg57d8yt.js} +5 -5
  88. package/{scalar.command-rak5pjk3.js → scalar.command-cwzge353.js} +4 -4
  89. package/skills/akan-agent/SKILL.md +36 -0
  90. package/skills/akan-debug/SKILL.md +3 -3
  91. package/skills/akan-deps/SKILL.md +1 -2
  92. package/skills/akan-mcp/SKILL.md +40 -0
  93. package/skills/akan-page/SKILL.md +44 -0
  94. package/skills/akan-query/SKILL.md +38 -0
  95. package/skills/akan-runtime/SKILL.md +40 -0
  96. package/skills/akan-scaffold/SKILL.md +16 -6
  97. package/skills/akan-transport/SKILL.md +40 -0
  98. package/skills/akan-validate/SKILL.md +13 -11
  99. package/{subspace.command-ej0rk116.js → subspace.command-3h03c7kc.js} +8 -8
  100. package/templates/workspaceRoot/.gitignore.template +3 -0
  101. package/templates/workspaceRoot/AGENTS.md.template +4 -10
  102. package/{tunnel.command-kdx3amrc.js → tunnel.command-czaz6ys4.js} +7 -7
  103. package/{typeChecker-px49mezc.js → typeChecker-j2jdnqsr.js} +1 -1
  104. package/typecheck.proc.js +6 -1
  105. package/verify.command-nzwhtz71.js +91 -0
  106. package/{workflow.command-gffk9nj9.js → workflow.command-srhky88x.js} +47 -13
  107. package/workspace.command-9stchcd2.js +262 -0
  108. package/TunnelShare-26ty9skr.js +0 -14
  109. package/agent.command-h82gepwn.js +0 -25
  110. package/cloud.script-vdj8ymch.js +0 -24
  111. package/context.runner-ejag7mhr.js +0 -25
  112. package/guidelines/conventions/conventions.instruction.md +0 -617
  113. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +0 -291
  114. package/index-6pzt55w3.js +0 -279
  115. package/index-y5m4j2w6.js +0 -856
  116. package/index-zzvvc845.js +0 -74
  117. package/quality.command-cy0pgqjz.js +0 -1478
  118. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +0 -69
  119. package/templates/workspaceRoot/docs/GENERATED.md.template +0 -55
  120. package/workspace.command-097hv6n1.js +0 -521
@@ -1,617 +0,0 @@
1
- ## Repo Overview
2
-
3
- - Akan.js is a full-stack TypeScript framework: write one line and deploy across web, app, server, database, and
4
- infrastructure. It abstracts the technical implementation so what remains is business code — minimal, fast, and
5
- type-safe everywhere at once.
6
- - This is a Bun-first monorepo: `apps/<app>` (pages, domain code, UI, env files, `akan.config.ts`), `libs/*` (shared
7
- domain and utility libraries), `pkgs/akanjs/*` (framework, runtime, and tooling facets published through the single
8
- `akanjs` package — extend an existing facet before adding a framework-level pattern), and `infra/` (Helm,
9
- deployment templates, edge configs, Jenkins env/secret scripts).
10
-
11
- ## Change Scope
12
-
13
- - Keep edits scoped to the requested task and the directly related files.
14
- - Do not reformat unrelated files or rewrite nearby code just for style.
15
- - Do not revert or overwrite unrelated user changes in a dirty working tree.
16
- - Prefer established nearby patterns over introducing a new abstraction.
17
- - Add new abstractions only when they remove real duplication or match an existing project pattern.
18
-
19
- ## Deep-Dive Guidelines
20
-
21
- This file carries the rules. The reasoning, the measurements, and the per-feature edge cases live in guidelines
22
- you fetch on demand — `get_guideline` with the name, or `akan guideline show <name>`. Fetch the relevant one
23
- **before** a deep pass on that area; a section below that points at one is a summary, not the whole contract.
24
-
25
- | name | covers |
26
- |---|---|
27
- | `ssrRule` | server-share targets, the `akan.ssr.*` warnings, the client-boundary playbook |
28
- | `pageRule` | route files, the route chain, heads, root layouts in a CSR bundle, lib pages |
29
- | `runtimeRule` | web surfaces, gateway vs solo, the dev server, logging, the image, native apps and a desktop server, database modes |
30
- | `queryRule` | slices and hydration, filter methods, soft removal and the facade's writes, full-text search, cascade |
31
- | `transportRule` | guards and writing one, deadlines, cache, rate limits, server-to-server calls, bytes, binary pubsub, verbs |
32
- | `mcpRule` | MCP exposure, configuration, wire behaviour, OAuth, page prompts, MCP Apps |
33
- | `agentRule` | the in-page agent: chat options, tools, forms, zones, slash commands, compaction |
34
- | `fieldRule` | field types, `hidden` / `secret` / `visual`, immutable and `Date` fields, image and file fields |
35
- | `cssRule` | the semantic token set, the color vocabulary lint enforces, lib-owned tokens |
36
- | `componentRule` / `recipeRule` | `_overrides.tsx` slots and drop-in components / authoring and consuming recipes |
37
- | `workspaceRecipes` | worked recipes (fields, injection and `adapt()`, slices, endpoints, internals, insights), the generated API |
38
-
39
- Module structure and each module file have their own guide (`moduleOverview`, `modelConstant` … `modelZone`,
40
- `scalarConstant`, `scalarDictionary`, `scalarModule`).
41
-
42
- ## Lint-Enforced Rules (These Break The Build)
43
-
44
- `biome.json` extends `@akanjs/devkit/biome.base.json`, which scopes every grit plugin in `@akanjs/devkit/lint/`;
45
- each plugin's header and diagnostic carry its full reasoning. Several rules produce output that looks wrong — do
46
- not "fix" it back.
47
-
48
- - **Never hand-order Tailwind classes** — `nursery/useSortedClasses` sorts them, `cn()` arguments included, and its
49
- output (`font-bold text-2xl text-foreground`) is correct.
50
- - **Stay inside the color vocabulary**: no raw palette (`bg-blue-500`), arbitrary or interpolated color classes
51
- (`bg-[#3b82f6]`), daisyUI classes or slots (`btn-primary`, `bg-base-100`), or color literals in `style={{}}` —
52
- they render no CSS. Use semantic tokens (`bg-primary`, `text-foreground/70`); a legitimate fixed color takes
53
- `// biome-ignore lint/plugin: <reason>`. Slot replacements, SVG / `el.style` warnings, legal values: `cssRule`.
54
- - **Never construct a raw `Error`.** Throw `new Err("<module>.error.<key>")` with the key registered as `[en, ko]` in
55
- the module dictionary's `.error({})` — imported from `"../dict"` on the server, from `"@libs/<lib>/client"` /
56
- `"@apps/<app>/client"` in UI. A `throw` is an error; a raw `Error` rejected, returned or stored loses the key and
57
- status too (a warning for now). Exempt: tests, `*.constant.ts`, a root `native/` folder (plugins throw
58
- `AkanNativeError`), `script/migration/**` (an operator reads its message), and `common/**` / `env/**`, which have
59
- no legal `Err` import — keep throwing code out of them.
60
- - **Never import a third-party package** from `page/**`, any barrel, a module logic file
61
- (`*.{constant,dictionary,document,service,signal,store}.ts`) or module component
62
- (`*.{Template,Unit,Util,View,Zone}.tsx`) — re-export it through a lib first (one-line shims in a lib's `common/`,
63
- `webkit/`, `ui/` are load-bearing). `*.signal.test.ts` / `*.service.test.ts` too, though they may import `node:*`
64
- and `bun:*`.
65
- - **`#private` is banned in exactly `*.constant.ts`, `*.document.ts`, `*.service.ts`, `*.store.ts`** (by path, so it
66
- stays the house style everywhere else, `srvkit/` and `adapt()` classes included).
67
- - **No `console.log` / `console.debug`** (only `assert`, `error`, `info`, `warn`; server code uses `this.logger` or
68
- `new Logger("ClassName")`), and **never `logger.log()` / `Logger.log()`** — it emits at `info` while reading like
69
- its own level; write `.info()`. The ladder is `trace verbose debug info warn error`.
70
- - **No `//!` or `/*!` in browser-reachable code** (`ui/`, `webkit/`, `common/`, `page/**/*.tsx`, `*.constant.ts`,
71
- `*.store.ts`, module components) — Bun keeps both through minification. Use `// FIXME:`.
72
- - **`{name}`, never `{{name}}`**, in a dictionary `.error()` / `.translate()` entry — only single braces interpolate.
73
- - **Every endpoint and named slice names its guards** (warning) — a `query` / `mutation` / `pubsub` / `message`, a
74
- named slice's `init()`, or a `slice()` map without `root` that names none (or `guards: []`) answers every caller.
75
- Write `guards: [Public]` when anonymous access is the intent.
76
- - **Never touch `document.cookie`, `localStorage` or `sessionStorage`** — a native shell's page keeps no cookies on
77
- iOS, macOS and Linux, and Web Storage throws during SSR. Use `getCookie` / `setCookie` / `removeCookie`,
78
- `storage`, `secretStorage` from `akanjs/client`. Browser APIs a WebView lacks (`navigator.share`, `serviceWorker`,
79
- `Notification`, `geolocation`, `vibrate`) live in a `webkit/` hook behind `isNativeApp()` (warning). Both in full:
80
- `runtimeRule`.
81
- - **Never return a value from a store action** — actions dispatch through `st.do.*` as `void`; write state with
82
- `this.set({ ... })`. A bare `return;`, a nested callback's `return`, a getter, and a `static` helper are fine.
83
- - **No `static` on an `XObject` or `LightX` class** — `via()` mixes in their prototypes only; use `XInput` (or a
84
- scalar), `X`, or `XInsight`.
85
- - **Never redeclare a generated CRUD endpoint name** in `*.signal.ts`.
86
- - **Never type a `*.Util.tsx` / `*.Zone.tsx` prop as a `cnst` model** — the server would hand a class instance to a
87
- client component; take `bannerId: string` and read the model from the store. Exempt: `cnst.<Enum>["value"]`, a
88
- `ClientInit` / `ClientView` / `ClientEdit` / `ModelsProps<…>` type argument, a function-typed prop, a `cnst` type
89
- that never leaves the file; `ModelProps<…>` and other indexed accesses stay flagged.
90
- - **Never wrap a form setter in a pass-through arrow** — `(v) => st.do.setTypeOnTicket(v)` emits no
91
- `data-akan-action` and publishes no agent tool. A wrapper that transforms, adds a statement, or calls `writeOnX`
92
- is legal; publish it with an explicit `st.tool`.
93
- - **Never call a hook conditionally** — a skipped call shifts every later hook, and production React crashes
94
- elsewhere. Biome's `useHookAtTopLevel` checks plain hooks (`useState`, `useEffect`), early returns included.
95
- `no-conditional-st-hook` checks the `st` hooks it cannot see — `st.use.*`, `st.slice.<x>.use.*`, `st.sel`, `st.ref`,
96
- `st.tool(…).exec()` / `.card()`, `st.useState(…).init()`, `st.expose(…).value()` — behind `||` / `&&` / `??`, in a
97
- ternary, an `if`, a `switch`, a loop, a `catch`, a default value, an optional call or a callback; not after an early
98
- `return` or inside a helper the component calls. Read each into its own `const` at the top, then combine.
99
- - **No deep imports past a barrel**, except cross-module constants (`../map/map.constant`).
100
- - **Never import across the client/server boundary** (`apps/**`, `libs/**`). Client files (`ui/`, `webkit/`,
101
- `page/`, `*.store.ts`, every `.tsx`) never import a `*.document|dictionary|service|signal.ts`, `srvkit/`, a
102
- package `server` entrypoint, or the `db` / `srv` / `sig` / `dict` / `option` / `useServer` barrels. Server files
103
- (those four suffixes, `srvkit/`) never import a `*.store.ts`, a module component, `ui/`, `webkit/`, a package
104
- `client` entrypoint, or the `st` / `store` / `useClient` barrels. `common/` and `*.constant.ts` obey both.
105
- `import type` is legal everywhere; a mixed value-and-type import is not.
106
- - **Server-component discipline** on `page/**`, `*.Unit.tsx`, `*.View.tsx` (`no-import-client-functions`,
107
- `no-use-client-in-server`, `non-scalar-props-restricted`).
108
- - **No async component under `ui/`** — React has no async client component. Await in the page, or hand an
109
- unawaited `fetch.*` field to a `Zone` / `<Load.Stream of={…}>`, and take the data as a prop. An async handler in a
110
- synchronous component and `lazy(async () => import(…))` are untouched.
111
- - **Never call `fetch.init<Model><Suffix>` / `fetch.get<Model>Init<Suffix>` from a client file** (`"use client"` or
112
- `*.store.ts`) — it is the hydration snapshot. Load it in the page and pass `init` down; reload with
113
- `st.do.init<Model><Suffix>()`.
114
- - `noArrayIndexKey` and `useExhaustiveDependencies` are **off** on purpose — `key={idx}` for embedded scalars and
115
- short dependency arrays are intentional.
116
- - **Suppress a grit diagnostic as `lint/plugin`** (`// biome-ignore lint/plugin: <reason>`,
117
- `// biome-ignore-all lint/plugin: <reason>`); bare `plugin:` does nothing. `pkgs/` is out of scope.
118
- - **`biome.json` is strict JSON** — a comment breaks config resolution without an error (Biome falls back to
119
- discovery and aborts on a nested config); rename it `biome.jsonc` to document a disabled rule.
120
- - **`akan lint` prints up to 200 diagnostics** (`--max-diagnostics <n>`, `0` = all); Biome's own uncounted 20 reads
121
- as progress when the mix merely changed.
122
-
123
- ## Coding Style (`**/*.{ts,tsx}`)
124
-
125
- - Run a large unit of work through a class instance; prefer class or `static` methods over unrelated top-level
126
- helpers, and keep a class file's functions and variables inside the class when they reasonably can be.
127
- - `#private` over TypeScript `private`, except in the four lint-banned suffixes, which use `private`.
128
- - `const` function expressions over `function` declarations, unless hoisting, overloads, generators, or a framework
129
- convention make `function` the better fit.
130
- - One class per file, named after it (`RouteClientBuilder.ts`, not `buildRouteClient.ts`). Migrate callers off an
131
- exported function that only instantiates a class and calls one method.
132
- - TypeScript filenames are camelCase, except React component and convention files.
133
- - One-off `className` strings stay inline; extract a constant only when reused, conditionally composed, or too large
134
- to read in JSX.
135
-
136
- ### File Size And Duplication
137
-
138
- - Keep files small (house median well under 50 lines); split a component before ~150 lines rather than adding
139
- section comments.
140
- - Ship every scaffold file even when empty — `export class XInternal extends internal(srv.x, () => ({})) {}`, empty
141
- dictionary stages, the `// state` / `// action` markers. They mark where things go.
142
- - Never add a sibling helper file inside `lib/<model>/`; helpers go to `common/`, `webkit/`, `srvkit/`, or `ui/`.
143
- - Prefer duplication to premature abstraction at the leaf: near-identical sibling modules and per-vendor pages are
144
- copied with changed literals, not parameterised; share enums by import only.
145
-
146
- ### TypeScript Shape
147
-
148
- - `interface` for object shapes, `type` only for unions and aliases.
149
- - `interface <ComponentName>Props` sits directly above the component (no blank line), `className?: string` first,
150
- named for the component (`CardProps`), never the model; exported only when a sibling imports it.
151
- - No non-null assertions — narrow with `?.`, an early return, or a type predicate
152
- (`.filter((id): id is string => !!id)`). Escape with `as unknown as T`, never `as any`.
153
- - Never annotate a component's return type; annotate a helper only for a union, tuple, or type predicate.
154
- - `as const` on every `enumOf(...)` array (even though `enumOf` infers its literals, so a typo already fails to
155
- compile), `via(Model, [...] as const, …)` Light tuple, and module-scope lookup map; never the `enum` keyword.
156
- - Async functions carry no `Async` suffix.
157
-
158
- ### Test Code
159
-
160
- - Bun's runner (`describe`, `expect`, `test` from `bun:test`); colocated `*.test.ts` / `*.spec.ts`; focused behavior
161
- tests of public contracts and edge cases. A placeholder `it` with a descriptive title is the floor; a
162
- security-relevant behaviour gets a real suite.
163
- - Run `bun run akan test <pkg> [files]` from the root (`files`: comma-separated paths from the target or the root;
164
- the only way a signal test runs), or `cd <pkg> && bun test --isolate ./<file>`. Plain `bun test` shares one global
165
- object across files and fails dozens of tests from that pollution (`bunfig.toml` `[test] isolate` is not honored as
166
- of Bun 1.4.4); from the repo root it breaks subprocess stdio pipes.
167
- - Signal tests split in two: `<model>.signal.spec.ts` holds fixtures on `sampleOf(cnst.XInput)` with explicit
168
- `Promise<cnst.X>` returns and **no assertions**; `<model>.signal.test.ts` holds `describe("<Model> Signal")`,
169
- describe-scope `let` fixtures, one `beforeAll`, story-ordered `it`s, negatives via
170
- `await expect(p).rejects.toThrow()`. Each `fetch.clone()` reports its own address (`198.18.x.y`), so an `ip` rate
171
- limit counts it apart: clone once per simulated user, signup included (`clone({ clientIp })` names one).
172
- - **One suite per module file**: `<model>.<role>.test.ts` beside the file it covers — never topic splits
173
- (`chatMessage.trim.signal.test.ts`); add a `describe`. A suite spanning modules goes in `srvkit/`
174
- (`libs/shared/srvkit/guards.signal.test.ts`), never the `lib/` root; `akan sync` refuses all three shapes. Only
175
- `akan typecheck <app-or-lib>` typechecks tests (`bun:test` types included).
176
- - Import `UserAgent` / `AdminAgent` from `lib/user/user.signal.spec.ts`, the one place agent types are re-typed.
177
-
178
- ## Comments
179
-
180
- Do not narrate code. Do document the thing the code cannot say. Both halves are the rule.
181
-
182
- - Never restate the identifier, the signature, or the control flow; prefer names and structure. No JSDoc, section
183
- banners, or "why/how" comments on ordinary logic.
184
- - Density tracks the layer: pages carry none, product `lib/` and `ui/` stay under 1 %, `srvkit/` adapters and
185
- `guards.ts` (what would leak without each guard) carry what the external constraints require.
186
- - Warranted for: a vendor or protocol quirk; an infrastructure constraint; a library gotcha; security reasoning; why
187
- an arbitrary-looking rule is correct; a math derivation; a domain field's business meaning; a state transition above
188
- a document chain method; why an obvious alternative was rejected.
189
- - Markers: `TODO` (tracked unfinished work), `FIXME` (known broken), `XXX` (a hazard a reader must not miss), `//!`
190
- (disabled or must-fix — server, `srvkit/`, CLI only), `//?` (an aside), `//*` (a design note), and a deletion
191
- caution saying why removing a line would break something non-obvious.
192
- - One short line each. Every suppression carries a reason (`// biome-ignore lint/<rule>: <why>`), never a bare
193
- disable block. Match the nearby density.
194
-
195
- ## TypeScript And Imports (`**/*.{ts,tsx}`)
196
-
197
- - Bun and ESM per the root `tsconfig.json`. Path aliases across packages: `akanjs/*`, `@apps/*`, `@libs/*`,
198
- `@contract/*`, respecting the `/client` and `/server` entrypoints. Let Biome organize imports.
199
- - Backend `.ts` namespaces the generated barrels — `import * as cnst from "../cnst"`, `* as db`, `* as srv` —
200
- with `import type * as srv` in services (keeps the runtime graph lazy) and a value import in signals.
201
- - `.tsx` uses one flat named import from the package client path
202
- (`import { cnst, fetch, st, Ticket, usePage } from "@apps/<app>/client"`), never a relative `../` import.
203
-
204
- ## Formatting And Linting
205
-
206
- - Biome formats and lints: `bun run akan lint <appName>` from the root; 2-space indent, 120 columns, double quotes.
207
- No broad formatting-only changes in unrelated files.
208
-
209
- ## Client / Server Boundaries (`apps/**`, `libs/**`, `pkgs/akanjs/**`)
210
-
211
- - `"use client";` tops client component files. It is mechanical by role: `Template`, `Zone`, `Util` always carry it
212
- on line 1; `Unit`, `View` never do. `usePage()` is legal in server files.
213
- - A `"use client"` file re-exports by name (`export { A, B } from "./x"`), never `export *` — the server knows a
214
- client module only by the names it spells out, so `akan start` / `akan build` stop on a star re-export.
215
- - Keep page props serializable unless the route pattern clearly allows otherwise; be careful importing client-only
216
- code into pages and layouts. Preserve file roles (`.document.ts`, `.service.ts`, `.store.ts`, `.constant.ts`,
217
- `.client.ts`), and inspect nearby files before introducing a new boundary pattern.
218
-
219
- ## SSR First — Server Rendering Is The Default
220
-
221
- Server-rendered JSX ships as HTML and costs nothing to hydrate; `"use client"` ships it twice (markup plus JS that
222
- re-runs). **The default is server; the directive is a cost justified per component** by a React hook, a JSX event
223
- handler, the store, a browser global, or a client-only package — never by markup, params, `l()` or mapping data.
224
- `akan quality ssr` (`--format json`) prints each app's and lib's server share: **50% is the floor, and a falling
225
- share is a regression** to justify in the PR or revert. A client package or an `index_.tsx` `lazy()` boundary
226
- justifies the directive; a `fetch.*` inside `onClick` is not flagged, only mount-time loads.
227
-
228
- Playbook (warning table, code, checklist: `ssrRule`): ① wrap the interaction and render `children` untouched;
229
- ② split compound components (`Tab` / `Tab.Menus` / `Tab.Menu` / `Tab.Panel`) — never one client file with a mode
230
- `useState` and every panel inlined; ③ fetch in the route and pass `init` / `view` to a `Zone`, never a
231
- `useEffect(…, [])` load; ④ a store-reading `Zone` holds no markup and delegates to a server `View`; ⑤ hand each
232
- promise across — `const { xInitInY, xListInY } = fetch.initXInY(id)`, `xInitInY` to a `Zone`, `xListInY` to
233
- `<Load.Stream>` (model instances, server-only) — and `await` only what the shell must contain; ⑥ named `ReactNode`
234
- slots (`Layout.Navbar`); ⑦ derived display logic on `Light<Model>`; ⑧ `.guard(() => signedIn())`
235
- (`@libs/shared/webkit`) on `_layout.tsx` (a real 3xx before anything renders; `getSelf({ unauthorize })` in a body
236
- redirects in-page after I/O); ⑨ CSS (`data-*` + `group-data-[…]`, `<details>`) over client state for visibility;
237
- ⑩ heavy islands behind `index_.tsx` + `lazy()`.
238
-
239
- ## Runtime & Build Configuration
240
-
241
- Declared in `akan.config.ts`, narrowed — never widened — by an env at boot; domain code reaches none of it
242
- (`runtimeRule`).
243
-
244
- - **`web: true | false | { csr: boolean }`** — `{ csr: false }` drops the CSR bundle native apps ship, `false` is
245
- API-only.
246
- - **Route prefixes move together**: `new AkanApp({ prefix, websocketPrefix })` in `main.ts`, mirrored in
247
- `api: { … }` in `akan.config.ts` for a CSR shell or native bundle. Read them with `getApiPrefix()` /
248
- `getWsPrefix()` (`akanjs/base`); never write `/api` or `/ws`, never pass one as a prop.
249
- - **`main.ts` imports `AkanApp` from `akanjs/server/akanApp`**, not the barrel.
250
- - Give every log sink a floor (`Logger.addSink(sink, { minLevel })`), never log per delivered record in anything
251
- that delivers records, and tail with `akan logs <app>`.
252
- - **`docker` is `string | { image, preRuns, postRuns, command }`**; the generated image installs only
253
- `ca-certificates` and `tzdata`.
254
- - **Native apps are the `native` section** (iOS, Android, desktop). A desktop app's carried server listens on a
255
- loopback port any local program can call — guard it as a network server — and ships `private/` and its env
256
- readable on the user's computer; read runtime files from `AKAN_APP_DIR`, and keep a secret the user gives it with
257
- `NativeSecret` (the OS credential store), never in a file.
258
- - **`database: { modes: [...] }`** (`single`, `multiple`, `cluster`), chosen by `AKAN_DATABASE_MODE`; an app running
259
- in two modes avoids `q.raw`.
260
-
261
- ## React Components And Styling (`**/*.tsx`)
262
-
263
- - `export const X = ({ … }: XProps) => { return (…); };` — `export default` only for pages, layouts, `lazy()`
264
- targets. No `React.FC`, `defaultProps`, `PropsWithChildren`; defaults in the destructuring, `children: ReactNode`.
265
- - `cond ? <X/> : null`, never `{cond && <X/>}` (renders `"false"` in a `className`); early `return null` only for
266
- guard clauses.
267
- - Never hand-roll loading, empty, or list states: `Load.Units` / `Load.View` / `Load.Edit` (`renderItem`,
268
- `renderList`, `renderView`, `renderEmpty`), `<Empty />`, `Model.New` / `Model.Edit` / `Model.SureToRemove`.
269
- Otherwise `<Load.Stream of={promise} fallback={…}>{(value) => …}</Load.Stream>` awaits one promise behind its own
270
- boundary (a resolved value renders in the shell).
271
- - Avoid hooks. `useState` only for modal-open, tab, draft-input, and drag state, never server data; `useEffect` only
272
- for a genuine effect (subscribe-with-cleanup, one-shot init); `Tab` over a mode switch; zero `useState` in a
273
- `.Template.tsx`.
274
- - Forms are store-driven: `value={xForm.field}`, `onChange={st.do.setFieldOnX}` **by reference** — that emits the
275
- `data-akan-action` / `data-akan-state` the in-page agent, E2E selectors and browser agents read. Always `Field.*`,
276
- never a bare `<input>` for a model field; nested rows use `st.do.writeOnX("payments.3.name", v)` and the generated
277
- `add<Field>OnX` / `sub<Field>OnX`. Never hand-write `data-akan-*`.
278
- - Read with `st.use.*`, write with `st.do.*`; client components never call `fetch.*`.
279
- - A raw `<button>` defaults to `type="submit"`, so a click inside any `<form>` also submits it. Write
280
- `type="button"` on every raw `<button>` that does not submit; `<Button>` from `akanjs/ui` already defaults to it.
281
- - **Never persist form values yourself** — `Load.Edit`, `Model.EditModal` and `Model.New` save and recover the whole
282
- `<model>Form` per record or route and user (`draft={false}` off, `draft="<scope>"` to name it; secret and hidden
283
- values never saved; field `cache` / `cacheKey` props are deprecated no-ops — `modelStore`).
284
- - Static class strings stay plain. `cn` (from `akanjs/client`) only for a conditional or to merge an incoming
285
- `className`, caller last: `cn("base", cond && "extra", className)` — the only combiner: no `clsx`, raw `twMerge`,
286
- or object syntax.
287
- - Multi-slot components take named props (`wrapperClassName`), never a `classNames` object.
288
- - Enum→class lookups: a module-scope `as const` map typed `{ [key in cnst.XStatus["value"]]: string }`, not
289
- `Record<...>`. Shared by a second module, the classes become a recipe variant in `ui/Recipe/`; only an enum→variant
290
- name map (`BadgeVariants["variant"]`) moves to `webkit/`.
291
- - `<Link>` from `akanjs/ui` for internal navigation; `<a>` only for `mailto:` and external links. A `<Link>` handed
292
- an absolute URL (any scheme, any case) or a `//host` path passes it through untouched and opens it outside the app;
293
- only an app path gets the locale and basePath. `Href.isExternal(href)` from `akanjs/client` is that test.
294
-
295
- ## Naming And Language
296
-
297
- - Component exports are role names (`Card`, `General`, `Preview`, `Admin`, `Remove`) — the namespace carries the
298
- model (`<Floor.Unit.Card>`, never `FloorCard`). `Util` exports are the endpoint verb minus the noun (`Serve`,
299
- `Refund`).
300
- - Layer the verbs: the document chain method drops the model (`sign()`), the service keeps the bare verb, signal,
301
- store and dictionary re-add it (`signScContract`) — clear of generated CRUD, and `st.do.X` reads like `fetch.X`.
302
- - Slice and filter names are prepositional (`inOrg`, `byStatuses`, `ofPortfolio`), never `getXInY` or `listX`.
303
- - Handlers are `onX` props taking inline arrows, never an extracted `handleX`.
304
- - Booleans `is*` / `has*` / `can*` / `show*` / `disable*`; counters `*Num`; indices `idx`; collections `*List` or
305
- plural; no `SCREAMING_SNAKE` — module-scope tables are camelCase + `as const`.
306
- - Keep existing domain vocabulary and its typos — transliterated terms and misspellings in use are load-bearing, and
307
- renaming silently breaks callers that match on the name.
308
- - Identifiers, type names, endpoint names, and log messages are **English**. Everything a user reads goes through
309
- `l("model.field")` or `l.trans({ en, ko })` — never a hard-coded JSX string, never `window.alert`.
310
- - Dictionary entries are `[en, ko]` pairs, nearly every label with a `.desc([en, ko])` even when repetitive; English
311
- in Title Case, Korean the plain domain term, `.error()` Korean ending in `다.`.
312
-
313
- ## Domain Module Conventions (`apps/**/lib/**`, `libs/**/lib/**`)
314
-
315
- A business concept is one `lib/` folder holding its logic files
316
- (`<model>.constant|dictionary|document|service|signal|store.ts`) and components
317
- (`<Model>.Template|Unit|View|Zone|Util.tsx`). `constant`, `dictionary` and
318
- `signal` are shared contracts with no platform-specific dependency; persistence and queries live in `document`,
319
- orchestration in `service`, client state in `store`; `Template` is forms, `Unit` list/card items, `View` details,
320
- `Zone` page sections, `Util` domain UI helpers.
321
-
322
- - **`<model>.constant.ts`** — `enumOf("camelName", [...] as const)` classes, then
323
- `XInput → XObject → LightX → X → XInsight`, one blank line apart, `XInsight` even when empty. **Display and
324
- predicate logic goes on `LightX`** (`isNew()`, `canWrite(user?)`), which server and client both hold, never a util
325
- module — the most commonly missed rule. Collection helpers are `static` on `X`; a non-obvious field gets a short
326
- trailing comment. `Date` fields are prototype accessors that a spread drops — copy with `new cnst.X().set(user)`
327
- (`fieldRule`).
328
- - **`<model>.document.ts`** — `XFilter extends from(...)` → `X extends by(...)` → `XModel extends into(...)`,
329
- `sort: {}` always present. Chain methods validate → mutate → `return this`, never `save()` (the caller saves, so
330
- `org.removeUser(id).removeInvite(id).save()` composes), with a one-line transition comment above each. Atomic
331
- counters live on the Model class with the updater callback, returning `!!modifiedCount`; indexes and derived
332
- totals go in `static override _onSchema`. **Removal is soft** and reads see live rows unless
333
- `{ withRemoved: true }`; the one hard delete is `purge<Filter>` / `purgeMany`, for data past retention.
334
- `updateById` / `removeById` fire no hooks — a cascading or `_postRemove` model removes through
335
- `remove<Model>(id)`, and `pickAndWrite` writes through the save hooks (`queryRule`).
336
- - **`<model>.service.ts`** — a few lines: load → chain → `return await ….save()` (keep the `return await`). Side
337
- effects go in `override async _preUpdate` / `_postCreate`; fire-and-forget is `void`-ed. Load every referenced
338
- document, then save, then notify; writes that must land together go in `this.transaction(async () => …)` and
339
- their notification in `this.afterCommit(…)` (`queryRule`). Return `null` / `false` for not allowed or not found;
340
- the signal decides whether that is an error.
341
- - **`<model>.signal.ts`** — `XInternal` → `XSlice` → `XEndpoint`, all three even when empty; `exec` is a one-liner
342
- calling the service.
343
- - **`<model>.store.ts`** — custom actions only for a toast, an optimistic update, or a multi-field write:
344
- `await fetch.X` → `this.setX(...)` → toast, or mutate the client model, `void fetch.*`, then commit.
345
- `this.pick(...)` when the value must exist, `this.get()` when it may not, `this.set({...})` to write; lists through
346
- the collection API (`xList.set(x).save()`), not spread. **Another store is reached through `this`**:
347
- `import type { RootStore } from "../st"` (type-only — `st.ts` imports every store), then
348
- `(this as unknown as RootStore).logout()` or `.set({ … })` / `.get()`; every store is mixed into one root at
349
- runtime, so the cast only names what `this` already is.
350
- - **`<model>.dictionary.ts`** — empty stages still written:
351
- `.of() → .model() → .insight() → .query() → .sort() → .enum() → .slice() → .endpoint() → .error() → .translate()`;
352
- every `.arg()` named, framework `skip` / `limit` / `sort` included; `modelDictionary` / `scalarDictionary` /
353
- `serviceDictionary` by module kind.
354
- - **`<module>.abstract.md`** — a title, one sentence naming what the module owns, a `## Rules` list of two to five
355
- invariants the code cannot show, an optional workflow chain (`draft -> signed -> active`). Never restate fields or
356
- types; update it when an invariant or workflow changes.
357
-
358
- ## Service And Signal Conventions (`*.{service,signal}.ts`, `server/**`)
359
-
360
- - `serve(...)` services hold business operations. Signals hold contracts: `internal(...)` for init, interval, cron
361
- and queue jobs (retries, dead letter: `workspaceRecipes` Recipe 5), `slice(...)` for focused data views feeding
362
- stores and zones, `endpoint(...)` for queries and mutations. External APIs and infrastructure go through
363
- `srvkit/` adapters injected into services, never vendor clients in domain logic.
364
-
365
- ### Authorization
366
-
367
- - **Every `slice()` takes an explicit `{ guards: {…} }` second argument, and `root:` is always `Admin`.**
368
- `guards: { cru: false }` (or per verb) takes a generated verb off HTTP; `mcp: { cru: false }` only keeps it off the
369
- agent shelf.
370
- - **Every custom `mutation` / `query` / `message` names its own `guards: [...]`** — the slice map reaches only
371
- generated endpoints, and a `pubsub` / `message` without its own is unguarded. `Public` belongs on a slice `get:`;
372
- on a mutation only for an act that must work signed out (sign-up/in, token refresh, an OAuth route), which also
373
- declares a `rateLimit`. A guardless endpoint is warned at boot and never published to MCP, which also refuses a
374
- mutation guarded only by `Public`.
375
- - Guards serve HTTP and websocket alike: read `context.get<T>("account")`, never `getHttpContext()` /
376
- `getWebSocketContext()`; keep them side-effect free and re-runnable. The acting user comes from `.with(Self)` /
377
- `.with(CurrentUserId)` / `.with(Me)` (never a client-supplied id) and the caller's address from `.with(Ip)`.
378
- - Keep `static name = "User";` on guard classes — `fetch` serializes it and the API explorer filters on it. It looks
379
- dead, so comment it.
380
- - **Every guard declares `static scope: GuardScope`, no default**: `"account"` reads only the caller (MCP listings
381
- evaluate it to hide entries), `"resource"` needs the call's arguments and fails closed without them. `SignedIn` /
382
- `Admin` / roles are `"account"`, every `Can<Verb><Model>` is `"resource"`; `Person` adds `static agents = false`.
383
- - `Can<Verb><Model>` guards in `srvkit/guards.ts` fail closed and ship with the model's library (`transportRule`).
384
- Services re-check ownership behind a guard — two independent gates.
385
-
386
- ### Calls, Queries, Agents (summaries)
387
-
388
- - **Wire (`transportRule`)**: a deadline is the endpoint's `{ timeout: <ms> }` (undeclared, the client quits at
389
- 30 s; the handler is not cancelled); `{ cache }` only on a `query` with no internal argument, capped at one day,
390
- dropped early by `invalidate(endpoint, args?)` on a plugged `EndpointCacheControl`; `{ rateLimit }` per endpoint,
391
- `option.setRateLimit` per app, `plug(RateLimit)` for a business key. `socketId` names a connection, not a caller. A
392
- device proves itself with a `MachineToken`. Server to server, `fetch.clone({ origin })` opens no socket
393
- without `connect: true`, retries through `retry`, and rethrows a remote `Err` as is — never wrapped or re-keyed.
394
- - **Body types**: `.body()` / `.param()` take scalars, model refs, or `enumOf(...)`; `Int` / `Float`, never
395
- `Number` (`pkgs/akanjs/signal/endpointInfo.ts`); `Upload` only in a `fileUpload: true` mutation; bytes are
396
- `Binary`, never `Any`. A model or scalar argument is checked against the request schema on every transport: a
397
- wrong JSON type, a value outside its enum or a missing required field answers 400 with `data.name` naming the
398
- path (`data.items.2.price`); a defaulted field may be left out, an undeclared key is dropped, and a stored model's
399
- input keeps an absent field absent.
400
- - **Reserved names**: generated CRUD (`create<Model>`, `update<Model>`, `remove<Model>`, …) exists for every model
401
- whose slice mounts the verb. `fetch.*` is one namespace across modules and a pubsub or message is routed by its bare
402
- name, so the server refuses to boot on two claims of one name (`[DI:fetch]`, `[DI:socket]`), naming both.
403
- - **Queries (`queryRule`)**: the root slice takes `queryKey` + `args`, never a raw query. A slice `exec` returns a
404
- `query<Filter>(…)` descriptor (never a `list<Filter>` array) and is paged through `initX(…, { sort, page, limit })`.
405
- A projection is bare on the facade (`pickById(id, { secret: true })`), under `select` on a filter accessor — the
406
- only way to read a `field.secret`. More rows: `loadMoreOf<Model>()` / `hasMoreOf<Model>`, never
407
- `count > page * limit`. A filter's `remove*` / `update*` are hookless (no cascade). No value is `q.empty`, never
408
- `q.missing`.
409
- - **Search**: `q.search(text, { prefix: true })` in a filter, at an AND position, over `text`-role fields; a search
410
- *slice* only on data safe to enumerate; blank input matches nothing — never a passthrough.
411
- - **`cascade` names a direction; the wrong one loses data**: `removeRef` on the owner's relation, `removeWith` on
412
- the child's reference to its owner. A query-level removal runs no cascade.
413
- - **MCP (`mcpRule`)**: `/mcp` publishes every guarded endpoint by default; `mcp: false` (or a `slice()` `mcp` map
414
- mirroring `guards`) is curation, not authorization. `guards: [Every, Person]` reserves an act for a person;
415
- `.with(AgentCall)` narrows an agent's call. Settings are `option.setMcp` in `lib/option.ts`; `JWT_SECRET` is
416
- required outside `local`. Never make a refusal message more helpful. Every entry needs a `.desc()`; brief a
417
- screen with `page().prompt(name, description)`, and publish one component a host draws with
418
- `page().app(name, description, load)` — a read-only tool whose `load` may only query.
419
- - **In-page agent (`agentRule`)**: mount `<Agent.Chat />` once in a layout; it never executes tools and refuses
420
- every call until `option.setAgentAccess(<guard>)`, which decides who — what a turn may ask is
421
- `option.setAgentRequestPolicy`; the LLM is `option.setLlm({ apiKey, model, host })`, never env.
422
- The surface is what components declare — `st.tool(…).exec(fn)` beside its control, `st.use` / `st.sel` /
423
- `st.ref` keys — never a store class. `st.use.x({ agent: false })` hides a key; its model's `hidden` / `secret` /
424
- `visual` fields are stripped at read. A tool value is capped at 20,000 characters. Route guidance is
425
- `<Agent.Guide instructions="…" />`; model-facing text is English.
426
-
427
- ### Injection And Adapters
428
-
429
- - A field named `<refName>Service` / `<refName>Signal` resolves to that registration — the suffix is required
430
- (`pkgs/akanjs/service/injectInfo.ts`). In a service: `service<srv.XService>()` · `plug(AdapterClass)` /
431
- `plug(StorageAdaptorRole)` · `use<T>()` only for a legacy `option.ts` singleton · `env(...)` for config.
432
- - `memory(...)` takes a scalar or model class (`memory(Map, { of: CallStateInput })`); never hand-encode JSON into a
433
- `String` memory.
434
- - A file your own code stored through `plug(StorageAdaptorRole)` has its disk path at
435
- `storage.resolveLocalPath?.(path, access)` (`fieldRule`): `null` means refused (answer 404, never fall back to
436
- `readData()`), `undefined` means the adaptor keeps no local files, and a key that comes from a request passes
437
- `access: "public"`. A `File` field is not one: `libs/shared` stores it through its own `StorageApi`.
438
- - **A new adapter is an `adapt()` singleton in `srvkit/`**, injected with `plug(TheClass)`, key `as const`. Never
439
- register it in `lib/option.ts` (it self-registers); never construct a `Logger` in it (`this.logger` exists);
440
- lifecycle work in `override async onInit()`. A per-use value object is a plain class. Legacy
441
- `constructor(options)` adapters migrate only when already being changed. Example and adapter conventions (one
442
- `#api<T>` with a timeout, pagination, secrets, parameter shapes): `workspaceRecipes` Recipe 2.
443
-
444
- ### Error Placement
445
-
446
- - State-machine preconditions throw in `document.ts`, cross-document rules in `service.ts`, request policy in
447
- `signal.ts` guards. Best-effort code returns a sentinel (`null`, `undefined`, `[0, 0]`, `{}`) — no Result types.
448
- - A `pick` or generated `get<Model>` that finds no live row answers 404 `base.error.documentNotFound` by itself
449
- (`NoDocumentError`); load with a nullable `load<Model>` and throw `Err.NotFound` only to say more than that.
450
- - An endpoint names the errors it throws on purpose — `errors: { 409: ["ticket.error.locked"] }` in its signal
451
- option, with keys its dictionary defines and never `base.error.*`. That is the status's OpenAPI response and a line
452
- of the MCP tool's description; outside production a thrown key it leaves out warns once. A caller narrows with
453
- `Err.is(error, "ticket.error.locked")`.
454
- - `try/catch` turns an exception into a decision: guards → `logger.warn` → `false`; adapters → `logger.error` →
455
- `null`; UI `try/finally` resets a spinner. A bodyless `catch {}` needs a one-line reason.
456
- - Store actions do not `try/catch` (the framework toasts the `Err`); client validation is `msg.error("<key>")` plus
457
- an early return, never a throw.
458
-
459
- ## Scalar Modeling (`**/*.constant.ts`)
460
-
461
- - Models use `via` from `akanjs/constant`, all five layers (`Input`, `Object`, `Light<Model>`, `<Model>`,
462
- `<Model>Insight`). `Int` for counts, `Float` only for decimals, `ID` for references; structured fields over `Any`.
463
- - Import `Int`, `Float`, `ID`, `Any`, `Binary`, `Upload`, `ImageResult`, `enumOf`, `dayjs` from `akanjs/base`;
464
- `String` / `Boolean` / `Date` are globals. No `JSON` scalar (use `Any`), no `Number`, and `Binary` / `Upload` are
465
- never fields — a file is `field(File).optional()` / `field([File])`, uploaded by the generated
466
- `upload<Field>On<Model>` (which `Field.Img` / `Files` and siblings use when handed the generated setter); it marks
467
- the field in `<model>FormUploading` while the request runs and drops a result whose form was set whole meanwhile
468
- (or, on a single field, re-picked) — gate a hand-written submit on it.
469
- - Defaults: a literal for scalars, a thunk for anything constructed (`default: () => dayjs()`). Arrays
470
- `field([T])`; optional `.optional()`.
471
- - **`field.hidden` / `field.secret` read `null` on the client while the type declares them** — guard with `??` or
472
- `== null`, never `=== undefined` or a default. `field.visual(T)` is rendered but stripped from every agent and MCP
473
- read. Full contract: `fieldRule`.
474
-
475
- ## Akan Page Routing (`apps/**/page/**`)
476
-
477
- Full contract — guards, apps, heads, CSR root layouts, typed params, lib pages, `devOnly`: `pageRule`.
478
-
479
- - `page/` holds `.tsx` route modules only: `<routeName>.tsx` or `_index.tsx`, `_layout.tsx`, `_overrides.tsx` — no
480
- other `_*.tsx`, helpers, `.ts` / `.js` files, or uppercase filenames. `[id]` is a dynamic segment, `(group)` a
481
- route group.
482
- - **A route file exports one chain** — `page()`, `layout()` in a `_layout.tsx`, `rootLayout()` in a root
483
- `_layout.tsx` — and every setting is a stage (`.param`, `.search`, `.config`, `.guard`, `.head`, `.loading`;
484
- `.notFound` / `.error` on layouts; `.fonts` / `.theme` / `.manifest` / … on the root; `.prompt` / `.app` on a page).
485
- A named export beside it fails the build.
486
- - **Name every `[x]` segment with `.param("x", Type)`** and read query keys only via `.search("k", Type)`; values
487
- arrive typed. `lang` is never declared — every stage receives it.
488
- - `.head()` takes JSX or a function returning it — never a metadata object; deeper heads replace by tag identity,
489
- and a canonical link / `og:url` comes only from the page's own `.head()`.
490
- - In a CSR bundle a root layout's own markup is hidden: what a person must see from it renders through
491
- `createPortal(…, document.body)`.
492
- - `_overrides.tsx` is one `export default override({ Slot: AppComponent })` (`akanjs/ui`), no logic, no
493
- `"use client"`. The legacy `export default async function Page` shape is never written anew.
494
- - `libs/<lib>/page` reaches an app through `syncPageLibs`, linked into the generated `page/(libs)/(<lib>)`; edit the
495
- lib source, never the link. `.config({ devOnly: true })` (a literal) keeps a route out of `akan build`.
496
-
497
- ```tsx
498
- export default page()
499
- .param("orgId", ID)
500
- .config({ transition: "stack" })
501
- .guard(() => signedIn())
502
- .render(({ orgId }) => {
503
- const { l } = usePage();
504
- const { taskInitInOrg } = fetch.initTaskInOrg(orgId);
505
- return <Task.Zone.Card init={taskInitInOrg} prefix={`/org/${orgId}`} />;
506
- });
507
- ```
508
-
509
- - `.render()` gets the declared args flat and typed (no `PageProps`, no `loader=` prop). Order: `usePage()`, fetch,
510
- return; auth is the chain's `.guard()`, which runs before anything renders. Hand `fetch.init*` / `view*` / `edit*` fields to sections unawaited; await only what the shell reads
511
- (title, redirect, link id) in one `Promise.all`.
512
- - **A route never writes while it renders**: a `fetch.<mutation>()` in a stage or a component it renders throws
513
- `base.error.mutationInRender`, since opening a link would perform it. Send it from a user action;
514
- `{ duringRender: true }` only for a write harmless to repeat and safe for anyone to trigger (`ssrRule`).
515
- - Gate auth with `.guard(() => signedIn())` (`@libs/shared/webkit`; a new workspace has that lib only with
516
- `create-workspace --libs true`) at `_layout.tsx`, and repeat it on a page that needs more; it is a courtesy, the
517
- endpoint guards are the gate. `getSelf({ unauthorize })` in a body still works. `async` only when the body awaits;
518
- the callback is not a React component, so it takes no name and no return type. No `useState`, `useEffect`, or
519
- comments in page files.
520
-
521
- ## Akan Sync Conventions (`apps/**`, `libs/**`)
522
-
523
- - App root files: `AGENTS.md`, `CLAUDE.md`, `akan.app.json`, `akan.config.ts`, `client.ts`, `main.ts`,
524
- `package.json`, `server.ts`, `tsconfig.json`, `tsconfig.tsbuildinfo`; folders: `.akan`, `common`, `env`, `lib`,
525
- `native`, `page`, `plugin`, `private`, `public`, `script`, `secrets`, `srvkit`, `ui`, `webkit`. A Capacitor-era
526
- `ios` / `android` / `mobile` folder or `capacitor.config.*` in an app root is refused as a leftover (native
527
- projects live under `dist/native/<app>/<target>`).
528
- - Lib root files: `AGENTS.md`, `CLAUDE.md`, `README.md`, `akan.config.ts`, `akan.lib.json`, `client.ts`, `index.ts`,
529
- `package.json`, `server.ts`, `tsconfig.json`, `tsconfig.spec.json`, `tsconfig.tsbuildinfo`; folders: the app's
530
- minus `.akan`, `script`, `secrets` (no `main.ts` either — a lib is never booted).
531
- - The allowlists' one source is `pkgs/@akanjs/devkit/workspaceLayout.ts`, read by `akan sync` (error), `akan doctor`
532
- and `akan quality scan` — add an entry there and mirror it here.
533
- - `apps/<app>/AGENTS.md` / `libs/<lib>/AGENTS.md` carry a generated `## Recipes In Scope` block between the
534
- `akan:agent` markers — never hand-edit it (outside the markers is yours); `akan lint` fails when it is stale.
535
- - `plugin/<name>.plugin.ts` declares an Akan plugin. No `apps/*/base` or `libs/*/base` — use `common/`.
536
- - `lib/` root holds only `cnst.ts`, `db.ts`, `dict.ts`, `option.ts`, `sig.ts`, `srv.ts`, `st.ts`, `useClient.ts`,
537
- `useServer.ts` — no hand-written file or test.
538
- - Modules are `lib/<model>`, `lib/_<service>`, `lib/__scalar/<scalar>`; their UI files are
539
- `<Model>.Template|Unit|Util|View|Zone.tsx`, `<Service>.Util|Zone.tsx`, `<Scalar>.Template|Unit.tsx`. A test is
540
- named after the one file it covers, so `<model>.<topic>.signal.test.ts` is refused like `<model>.<topic>.signal.ts`.
541
- - `ui/`, `webkit/`, `srvkit/`, `common/`, `plugin/` and module `index.ts` barrels are generated
542
- (`export * from "./name";` per 1-depth entry, `export {};` when empty, so a stale one heals on sync;
543
- `akan create-library` starts `common/`, `srvkit/`, `webkit/`, `ui/` with that empty barrel) — never hand-edit or
544
- track them. **Never hand-write an
545
- `index.tsx` / `.jsx` / `.mts` at those roots**: Bun resolves it before the generated `index.ts`, so new exports are
546
- `undefined` at runtime (`akan sync` refuses it, `akan doctor` reports `facet-index-shadowed`); a namespace belongs
547
- in `ui/<Folder>/index.tsx`.
548
- - Sync writes barrels, module indexes and `akan.*.json` exactly as Biome prints them (`akan lint --no-fix` passes
549
- right after a sync), so a lint diff in one is a generator bug — fix the generator.
550
- - **`akan sync` owns package.json `dependencies`**: it adds imports at the root's version, realigns root-declared
551
- entries, and drops unimported ones (logged); undeclared-at-root entries are kept with a warning. Keep a package no
552
- TS file imports (a CSS `@plugin`, a runtime-only package) with `akan.keepDependencies`; `externalLibs` and
553
- `trustedDependencies` always stay; devDependencies are realigned, never pruned. `akan install-library` lets the
554
- root win — it adds only what the root lacks and warns when the lib wants a newer version.
555
-
556
- ## Layer Placement (`common/`, `webkit/`, `srvkit/`, `ui/`)
557
-
558
- | Folder | Admission test | Naming |
559
- |---|---|---|
560
- | `common/` | pure, isomorphic, zero-dependency; imports only sibling `common/*` and `akanjs/base` (so no `Err`, and no throwing code) | camelCase file named after its single export |
561
- | `webkit/` | touches `window` / `navigator` / the native bridge (`akanjs/client/native[/<plugin id>]`), or is a React hook | `use<Thing>.tsx`, `.tsx` even without JSX |
562
- | `srvkit/` | touches `node:*`, `Bun`, `process.env`, a secret, or a server SDK | camelCase file, PascalCase class |
563
- | `ui/` | renders JSX or defines a look (`Recipe/`, a lib's `tokens.css`), not bound to one model | PascalCase component, camelCase sidecar, `Recipe/<name>.ts` |
564
- | `plugin/` | a build- or CLI-time `AkanPlugin` | `<name>.plugin.ts`, registered in `akan.config.ts` |
565
- | `native/` | a native plugin the app or lib owns — its page API reached only through a `webkit/` hook (`runtimeRule`) | `native/<id>/` |
566
-
567
- - Hooks return a named object of async closures, never a tuple.
568
- - Recipes live in `ui/`: `webkit/` hooks are `"use client"`, and `common/` cannot import `akanjs/ui`.
569
- - A layer-root `index.ts` is generated; a `ui/<Folder>/index.tsx` building a namespace is hand-written (a generated
570
- barrel holds only `export *` lines). `ui/<Folder>/index_.tsx` is the `"use client"` + `lazy()` boundary beside a
571
- server-safe `index.tsx` — merging the pair breaks RSC.
572
-
573
- ## Data Migrations (`apps/*/script/migration/**`)
574
-
575
- A change that reshapes stored documents ships a migration: `akan create-migration <name> <app>` writes
576
- `script/migration/<yyyyMMddHHmm>_<name>.ts`, a default-exported `migration(title)` from `akanjs/server`, which
577
- `akan migrate <app>` runs locally and `bun main.js ops migrate` in a built container (the `cheatsheet/dev/migration`
578
- docs page).
579
-
580
- - The new code reads both shapes until every environment has applied it — a deploy serves traffic first.
581
- - Write only through `table(refName)`, never a service, a document or raw `sql` — a service write runs the model's
582
- hooks, and none of them reaches the change log a rollback reverts. Call nothing outside the database.
583
- - `plan` reads only and must hash the same on unchanged data: a timestamp, `createId()` or random value in it makes
584
- every `apply --expect <planHash>` refuse as `planChanged`.
585
- - Past about five seconds on SQLite, an apply's one transaction makes the live server's writes fail. Take
586
- `.config({ transaction: false })`, which commits each `rewrite` batch and resumes a `partial` run from the top of
587
- `apply` — so a second run must change nothing (a `where` the new shape no longer matches).
588
- - `$ne` leaves out rows whose path is missing or `null` (match them with `{ path: null }`; `$exists: false` misses a
589
- stored `null`); `find`, `count` and `rewrite` include removed rows unless `{ withRemoved: false }`; a `table()` write
590
- leaves `updatedAt` alone.
591
- - Throw a plain `Error` an operator can act on. Never edit a migration an environment has applied — write another;
592
- delete it once every environment has, unless its `.rollback(fn)` may still be needed: without the file a rollback
593
- runs the default undo.
594
-
595
- ## Present In The Code — Do Not Imitate
596
-
597
- Warts in older files — never copy them; when two shapes disagree, follow the newer neighbour: `children: any`
598
- (use `ReactNode`); hard-coded API keys or secrets (they belong in `option.ts` or env); large commented-out blocks;
599
- stale `// TODO: Implement …` above implemented methods; `{cond && <X/>}`, hard-coded Korean bypassing `l()`,
600
- `window.alert(...)`; bare `/* eslint-disable */` blocks; raw palette grays like `text-gray-400`. A store reaching
601
- another through `(this as unknown as RootStore)` is **not** a wart — it is the sanctioned way.
602
-
603
- ## Secrets And Env Safety (`.env`, `infra/**`, `*secret*`, `*credential*`)
604
-
605
- - Never print, summarize, commit, or expose real secret values, credentials, tokens, private keys, or `.env`
606
- contents; document env keys by name with placeholders only.
607
- - Preserve the env/secret flow through `bun run downloadEnv`, `uploadEnv`, `downloadSecret`, `uploadSecret`, and
608
- keep Jenkins and deployment assumptions intact unless the task asks otherwise.
609
- - Treat generated env/secret artifacts as sensitive even when they are not named `.env`.
610
-
611
- ## Application Test Commands
612
-
613
- - After changing application code, run `bun run akan start <appName>` (`a,b`, `a b`, or `all` for several); check
614
- the production build with `bun run akan build <appName>`.
615
- - A supervised session writes `local/apps/<app>/runtime/dev.log` (previous: `dev.prev.log`) — hand over that path,
616
- not a paste of the repainting full-screen view. Keys, `--plain`, boot waves, `--kill`, watch scope, running a
617
- built artifact, booting a server in a test: `runtimeRule`.