@akanjs/cli 3.0.0-alpha.11 → 3.0.0-alpha.111

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 (140) 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-mjh5ppsq.js} +3 -5
  5. package/{agent.command-a3n15c6t.js → agent.command-d2gfxfck.js} +11 -13
  6. package/{application.command-rdm3et0g.js → application.command-pj2m7584.js} +65 -38
  7. package/{applicationBuildRunner-6m8n71w4.js → applicationBuildRunner-kxwbssgn.js} +27 -23
  8. package/{applicationReleasePackager-gg8ccbeh.js → applicationReleasePackager-4yasxwv9.js} +8 -9
  9. package/buildBatch.proc.js +12 -14
  10. package/capacitorApp-36rbr858.js +12 -0
  11. package/{cloud.command-56aeekqn.js → cloud.command-gxqp8xdv.js} +15 -18
  12. package/commandManifest.json +1 -1
  13. package/{context.command-ysxawe7h.js → context.command-ez8a0zyz.js} +19 -23
  14. package/dependencyScanner-shs82ynp.js +8 -0
  15. package/devTui-40ggmd99.js +553 -0
  16. package/devTuiView-c08ccbat.js +9 -0
  17. package/getDirname-dr3jz1xg.js +7 -0
  18. package/{guideline.command-yqf9a372.js → guideline.command-xmqwx8zm.js} +24 -22
  19. package/guidelines/agentRule/agentRule.generate.json +31 -0
  20. package/guidelines/agentRule/agentRule.instruction.md +531 -0
  21. package/guidelines/conventions/conventions.instruction.md +493 -369
  22. package/guidelines/framework/framework.generate.json +3 -2
  23. package/guidelines/framework/framework.instruction.md +0 -9
  24. package/guidelines/mcpRule/mcpRule.generate.json +35 -0
  25. package/guidelines/mcpRule/mcpRule.instruction.md +460 -0
  26. package/guidelines/modelStore/modelStore.instruction.md +12 -0
  27. package/guidelines/modelTemplate/modelTemplate.instruction.md +5 -0
  28. package/guidelines/queryRule/queryRule.generate.json +31 -0
  29. package/guidelines/queryRule/queryRule.instruction.md +178 -0
  30. package/guidelines/runtimeRule/runtimeRule.generate.json +25 -0
  31. package/guidelines/runtimeRule/runtimeRule.instruction.md +220 -0
  32. package/guidelines/ssrRule/ssrRule.instruction.md +51 -5
  33. package/guidelines/transportRule/transportRule.generate.json +31 -0
  34. package/guidelines/transportRule/transportRule.instruction.md +60 -0
  35. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +54 -764
  36. package/guidelines/workspaceRecipes/workspaceRecipes.generate.json +33 -0
  37. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +467 -0
  38. package/incrementalBuilder.proc.js +26 -25
  39. package/{index-8pd02prk.js → index-259dsnz3.js} +58 -25
  40. package/{index-yzsxc30b.js → index-2tv3fdx4.js} +975 -234
  41. package/index-3d9y066c.js +76 -0
  42. package/{index-76rn3g2c.js → index-47pj3aee.js} +4 -4
  43. package/{index-m90fn8xe.js → index-4edzf1gr.js} +32 -32
  44. package/{index-3789fdpg.js → index-600zhnve.js} +94 -61
  45. package/{index-1577bej2.js → index-6wwzs1bc.js} +2 -2
  46. package/{index-cv9cxs5k.js → index-7737gxcp.js} +18 -18
  47. package/{index-a5cs7d8r.js → index-8few9nyh.js} +13 -13
  48. package/{index-mewacxye.js → index-8pm30m73.js} +57 -57
  49. package/{index-wnp7hwq7.js → index-92zztqy1.js} +7 -7
  50. package/{index-fgc8r6dj.js → index-a5vmm6x4.js} +3 -1
  51. package/{index-cav1azma.js → index-a64esmtb.js} +1106 -1369
  52. package/{index-nwqqssnb.js → index-aj7tyh5w.js} +26 -23
  53. package/{index-xys926f2.js → index-by5gpp8x.js} +4 -4
  54. package/{index-yzmqvg23.js → index-fz5q3gd7.js} +8 -8
  55. package/{index-kcsa1zff.js → index-gyd220p2.js} +4 -4
  56. package/{index-j37qq1f2.js → index-h7yw2z9n.js} +7 -7
  57. package/{index-bjpxzr6s.js → index-hwkygn9s.js} +51 -3
  58. package/index-j9yhg404.js +159 -0
  59. package/{index-46tjzh6s.js → index-kcxmv48c.js} +29 -29
  60. package/{index-0cj2zxbm.js → index-kn1h7p1x.js} +12 -11
  61. package/{index-e4b2ae6b.js → index-ktb5njgy.js} +41 -34
  62. package/{index-etwh7sd3.js → index-mak3cd28.js} +100 -32
  63. package/{index-xjd3rqzj.js → index-n68jx79w.js} +6 -15
  64. package/{index-z1s5f4e0.js → index-ne2qy0nk.js} +36 -37
  65. package/{index-65aeh789.js → index-pnqbkf5p.js} +1 -1
  66. package/{index-67546d0j.js → index-q0y2jq9j.js} +14 -2
  67. package/{index-4mgkgba3.js → index-rwg2aa4f.js} +14 -14
  68. package/{index-bzznxgcx.js → index-v0qh106m.js} +1002 -128
  69. package/{index-j9cxndc0.js → index-w8kmx1b6.js} +20 -11
  70. package/{index-h5whaj26.js → index-ws5e0j51.js} +16 -12
  71. package/{index-9va8zayb.js → index-wt7qrtd4.js} +27 -27
  72. package/index.js +22 -25
  73. package/{library.command-x6t29a30.js → library.command-nbsky672.js} +11 -10
  74. package/{localRegistry.command-649g1n7b.js → localRegistry.command-ts6t5e5a.js} +20 -23
  75. package/{module.command-8w8ys5t3.js → module.command-29vqzrh8.js} +13 -16
  76. package/{package.command-zgy7f3fz.js → package.command-axv0abmn.js} +8 -10
  77. package/package.json +5 -7
  78. package/{page.command-yjmnkyk2.js → page.command-vs9s3zrh.js} +7 -9
  79. package/{primitive.command-gfqaagsg.js → primitive.command-cbxmqbtc.js} +13 -16
  80. package/{quality.command-ec8r1dn3.js → quality.command-gmbs7nws.js} +184 -334
  81. package/recipeScanner-fpagtgc1.js +11 -0
  82. package/{repair.command-p9ey6mkm.js → repair.command-bqsjptsj.js} +12 -14
  83. package/{routeSourceValidator-e4jmbfcx.js → routeSourceValidator-apyqw7wk.js} +90 -19
  84. package/{scalar.command-9dhmqhtm.js → scalar.command-6k1vhe9s.js} +11 -14
  85. package/subspace.command-35a3t6vv.js +755 -0
  86. package/templates/app/env/env.client.debug.ts.template +1 -5
  87. package/templates/app/env/env.client.develop.ts.template +1 -5
  88. package/templates/app/env/env.client.local.ts.template +1 -5
  89. package/templates/app/env/env.client.main.ts.template +1 -5
  90. package/templates/app/env/env.client.testing.ts.template +1 -5
  91. package/templates/app/env/env.client.type.ts +2 -6
  92. package/templates/app/env/env.server.debug.ts.template +1 -5
  93. package/templates/app/env/env.server.develop.ts.template +1 -5
  94. package/templates/app/env/env.server.local.ts.template +1 -5
  95. package/templates/app/env/env.server.main.ts.template +1 -5
  96. package/templates/app/main.ts +3 -1
  97. package/templates/app/page/_index.tsx +3 -3
  98. package/templates/app/page/_layout.tsx +31 -32
  99. package/templates/appSample/lib/task/task.signal.ts +11 -6
  100. package/templates/appSample/page/task/[taskId]/_index.tsx +22 -27
  101. package/templates/appSample/page/task/[taskId]/edit.tsx +25 -30
  102. package/templates/appSample/page/task/_index.tsx +3 -7
  103. package/templates/appSample/page/task/_layout.tsx +4 -15
  104. package/templates/appSample/page/task/new.tsx +4 -10
  105. package/templates/appSample/srvkit/AuthGuard.ts +2 -2
  106. package/templates/crudPages/[__model__Id]/edit/page.tsx +27 -29
  107. package/templates/crudPages/[__model__Id]/page.tsx +24 -32
  108. package/templates/crudPages/new/page.tsx +26 -25
  109. package/templates/crudPages/page.tsx +27 -26
  110. package/templates/crudSinglePage/page.tsx +26 -21
  111. package/templates/env/_env.server.type.ts +7 -5
  112. package/templates/lib/db.ts +1 -1
  113. package/templates/lib/dict.ts +1 -1
  114. package/templates/lib/sig.ts +5 -1
  115. package/templates/lib/srv.ts +6 -2
  116. package/templates/module/__model__.dictionary.ts +4 -1
  117. package/templates/module/__model__.signal.ts +2 -3
  118. package/templates/module/__model__.store.ts +1 -2
  119. package/templates/workspaceRoot/.gitignore.template +0 -1
  120. package/templates/workspaceRoot/.husky/pre-commit.template +16 -0
  121. package/templates/workspaceRoot/.vscode/settings.json.template +1 -1
  122. package/templates/workspaceRoot/AGENTS.md.template +4 -0
  123. package/templates/workspaceRoot/CLAUDE.md.template +19 -0
  124. package/templates/workspaceRoot/biome.json.template +1 -1
  125. package/templates/workspaceRoot/docs/AI-DEVELOPMENT.md.template +10 -14
  126. package/templates/workspaceRoot/docs/GENERATED.md.template +12 -10
  127. package/templates/workspaceRoot/package.json.template +2 -4
  128. package/typeChecker-3xgrzc2v.js +7 -0
  129. package/typecheck.proc.js +4 -5
  130. package/{workflow.command-ycwc6zr6.js → workflow.command-nwpcdc8p.js} +22 -25
  131. package/{workspace.command-xhyhajxa.js → workspace.command-aczjxzbf.js} +64 -66
  132. package/capacitorApp-mr81qdxq.js +0 -61
  133. package/dependencyScanner-f6grrep3.js +0 -9
  134. package/getDirname-m9s0cmhq.js +0 -8
  135. package/index-mxvakhsm.js +0 -66
  136. package/index-r24hmh0q.js +0 -4
  137. package/recipeScanner-tghkzrrt.js +0 -12
  138. package/typeChecker-kravn7ns.js +0 -8
  139. /package/{index-0wae5ebk.js → index-meh558jy.js} +0 -0
  140. /package/{index-ss469dec.js → index-nz8prx9g.js} +0 -0
@@ -0,0 +1,178 @@
1
+ # Query Rule — Filters, Slices, Hydration, Search, Cascade
2
+
3
+ How a model's data is queried, exposed to a client store, searched, and removed. Filters and slices are the two
4
+ query surfaces; `q.search()` and the `text` field roles are the search surface; `cascade` is what a removal takes
5
+ with it. `conventions` carries the invariants — this is the full contract behind them.
6
+
7
+ ## Slices, Queries, and Hydration
8
+
9
+ - **The root slice (`""`, generated by `slice()`) takes `queryKey` and `args`, not a query.** `initX("byOwner",
10
+ [ownerId])` names one of the model's own filters and passes that filter's args; no key at all is the `any`
11
+ filter every model carries. A raw query descriptor let a caller compose a query the model never declared, and
12
+ could not survive the query string at all — `String(value)` sends `[object Object]`. Args are parsed by the type
13
+ the filter declared, a missing required one is refused, and args past the declared ones are dropped
14
+ (`resolveFilterQuery`, `pkgs/akanjs/document/filterMeta.ts`). It is an admin API: `root:` is always `Admin`.
15
+ - **Give an id filter arg a `ref` and the admin panel stops asking for hex.** `filter().arg("ownerId", ID, { ref:
16
+ "user" })` names the model the id points at; the arg then renders a picker that runs the same query maker against
17
+ that model's own filters, so a ref of a ref keeps nesting. The picker holds its rows in local state rather than the
18
+ ref model's store — that store is a singleton, and loading into it would overwrite whatever listing of the same
19
+ model is already on screen. `ref` is the only UI hint a filter arg carries; there is no render callback, because a
20
+ function cannot cross to the client.
21
+ - **A summary counter names the listing it counts, on the field itself.** `field(Int).meta(getQueryMeta("user")
22
+ .query("byStatuses").args([["prepare"]]))` is what makes the dashboard tile clickable: clicking it applies that
23
+ filter to the listing in place — one request, no navigation — and fills the arg controls under the toolbar, so
24
+ the filter is visible and editable rather than opaque. `args` may be a thunk (`() => [dayjs().subtract(1,
25
+ "hour")]`), read at the click so a relative time is current. A meta naming a different model counts a different
26
+ listing, so its tile stays inert here. `AdminPanel`'s `queryMap` still overrides per column, and is now only for
27
+ a column whose field cannot declare one.
28
+ - **A picker row is labelled by `labelOf`, which reads `Light<Model>.label()` first.** Then the field carrying
29
+ `text: "title"`, then `title` / `name`, with the id as the floor. Write the method on the Light class — that is
30
+ where display logic belongs, and the same label is what `Load.Units` and the in-page agent's screen scope show.
31
+ A model with none renders ids and says so in the picker.
32
+ - A slice's `exec` returns a `QueryOf` (an opaque query descriptor, `pkgs/akanjs/constant/types.ts`); you **cannot** chain `.sort()`/`.limit()` on it.
33
+ - Apply ordering/paging via the store `init` fetch option instead: `initX(..., { sort, page, limit })` (`pkgs/akanjs/fetch/fetchType/sliceFetch.type.ts`).
34
+ - **A slice list is either one window or an accumulated one, and the store says which.** `setPageOf<Model>` swaps
35
+ the window and `pageOf<Model>` names it; `loadMoreOf<Model>()` appends the rows *after* the ones already loaded
36
+ and takes no page number, because in an accumulated list no page number names anything. It skips by
37
+ `<model>List.length` rather than by `page * limit`, which is what keeps the offset from drifting from what is on
38
+ screen: a live insertion at the front moves the server's baseline by one, so a page number asks for rows the
39
+ list already shows. It also leaves `pageOf<Model>` at 1 — live placement is refused anywhere but the first page,
40
+ so paging by number used to switch live sync off permanently on the first "more", silently. `isCumulativeOf<Model>`
41
+ is the mode, and it is what stops a live insertion from truncating an accumulated list back to one page's worth.
42
+ - **"Is there more" is `hasMoreOf<Model>`, never `count > page * limit`.** It is set from the length of the batch
43
+ the server just returned, so it survives `{ insight: false }` — which makes no count query at all — and cannot
44
+ drift from the count a live event moved. `loadMoreOf<Model>()` is a no-op once it is false, and `Load.Units`
45
+ draws no infinite-scroll sentinel.
46
+ - 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`).
47
+ - **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`).
48
+ - Every filter generates fourteen methods: `list` · `listIds` · `find` · `findId` · `pick` · `pickId` · `exists` ·
49
+ `count` · `insight` · `query` · **`remove`** · **`removeOne`** · **`update`** · **`updateOne`**. The last four are
50
+ query-level writes — one atomic UPDATE, **no hooks**, and therefore no `_postRemove` and no cascade. Use them on a
51
+ model that carries no removal side effect; otherwise remove documents one at a time.
52
+ - **`update<Filter>` / `updateOne<Filter>` are chains, not calls:** `await updateInRoot(rootId).set({ status:
53
+ "archived" })`. The patch cannot trail the filter args — a filter's own args may be optional and no tuple type
54
+ puts a required element after those — so it lands on a terminal `.set()`, mirroring the `UPDATE … SET …` it
55
+ compiles to. Building the chain touches nothing; only `.set()` runs a query.
56
+ - `removeOne` / `updateOne` hit the **newest** match — the subquery they compile to is ordered `createdAt` descending
57
+ and there is no way to change that. They also report only counts, never which row they touched, so they are for
58
+ "there is at most one of these", not for claiming the next item off a queue. Pass a query that matches one row.
59
+ - **A filter may not be keyed after its own model.** Filter methods are assigned after CRUD, so a filter `chat` on
60
+ model `chat` would silently swap the single-document `removeChat`/`updateChat` for a hookless query-level one. It
61
+ throws at boot instead (`assertFilterFitsCrud`).
62
+ - **"Has no value" is `q.empty`, never `q.missing`.** The three absence operators are distinct: `q.exists` is the
63
+ key being present, `q.missing` is the key being *absent from the stored JSON*, and `q.empty` is either — absent,
64
+ or present and null. An optional field is written both ways over its life: an insert that omits it leaves the key
65
+ out, while a document read back and saved carries the explicit `null` that the read materialized. So `q.missing`
66
+ matches a freshly inserted row and silently stops matching that same row after its first round-trip save. Reach
67
+ for it only to find rows written before the field was declared.
68
+
69
+ ## Text Search In A Filter — `q.search()`
70
+
71
+ - Text search is a filter query node like any other: `bySearch: filter().arg("text", String).query((text, q) =>
72
+ q.search(text, { prefix: true }))`. The generated `listBySearch` / `countBySearch` / `queryBySearch` /
73
+ `insightBySearch` come for free — you do **not** need a slice to make search usable.
74
+ - **Only add a search slice when the model's data is safe to enumerate.** A filter is server-side; a slice is a
75
+ client-callable endpoint, so on a model whose slice `get:` is `Public` a search slice hands anyone a way to walk the
76
+ table. Leave that decision to the mounting app.
77
+ - `q.search()` compiles to a JOIN, not a WHERE fragment, so it **must sit at an AND position**. Nesting it under
78
+ `q.any()` or `q.not()` throws, and it is rejected in `updateOneByQuery` / `updateManyByQuery` — a query-level write
79
+ takes no join, so ignoring the node would silently widen the write to every other matching row.
80
+ - Blank or whitespace-only input matches **nothing**. Never "fix" that into a passthrough: a passthrough turns a
81
+ search endpoint into a full listing.
82
+ - Order by relevance with the built-in `relevance` sort key. It is an empty sort map, which the store reads as
83
+ "unspecified": score order when a search join is present, `createdAt` descending otherwise. That fallback is the
84
+ compiler's own, not a model-defined default — redefining `latest` on the model does not change it.
85
+ - **A slice endpoint never reaches "unspecified".** The resolver fills `latest` before the query is built, so a
86
+ client asking for the score order has to name `relevance`; leaving `sort` off gets `latest`, not relevance.
87
+ - Scope a search with `columns` (`q.search(text, { columns: ["title"] })`) and re-weight with `weights`, a tuple of
88
+ finite numbers positional over `["title", "desc", "tag", "filter"]`.
89
+
90
+
91
+ ## Text Search Fields — the `text` role
92
+
93
+ - A field joins the full-text index by declaring one of five roles: `field(String, { text: "title" })`, and likewise
94
+ `"desc"`, `"tag"`, `"thumb"`, `"filter"`. Nothing else opts a field in, and there is no per-model switch.
95
+ - Pick the role by what the value *is*, because `bm25` weights them positionally (`title` 10, `tag` 3, `desc` 1,
96
+ `filter` 0): `title` is the one line a human scans for, `desc` is prose, `tag` is a keyword list, `filter` is a
97
+ scoping value (status, owner, role) that must be matchable but must never outrank a real title hit.
98
+ - `thumb` is mirrored for rendering a hit and is **not** indexed — never expect it to match.
99
+ - **`field.secret`, `field.hidden` and `resolve()` take no `text` role — it is a compile error**, because the
100
+ mirror is plaintext and an indexed secret would leak through search. The class build throws the same refusal as
101
+ a backstop, for an option object the excess-property check cannot see through, and names the way out: drop the
102
+ role, or leave the field unmasked. Do not work around either. The throw also covers a `text` field *underneath*
103
+ one of those — a scalar's own field is reachable through its parent, so `f.secret(Noti)` where `Noti.label`
104
+ carries a role is rejected at the parent, not silently indexed; that one is only reachable at runtime, since the
105
+ pairing spans two files.
106
+ - The role works on a relation too (`image: field(File, { text: "thumb" })`) and on an array (`playing: field([String],
107
+ { text: "tag" })`); an array of objects indexes by leaf key, including an array leaf (`works[*].tags`). A field
108
+ inside a `Map` indexes nothing: there is no fixed path to extract it from.
109
+ - Declaring roles is all the wiring there is. Mirror rows are maintained by SQL triggers — not document hooks —
110
+ because `updateOneByQuery` and friends fire no hooks, and most searchable-field mutations go through exactly that
111
+ path.
112
+ - Search runs on sqlite/libsql only. `q.search()` against Postgres throws, loudly, rather than returning every row.
113
+ - `AKAN_SEARCH_ENABLED=0` switches the index off process-wide; unset means on. It never deletes mirror data, and
114
+ re-enabling reconciles every ref. **Give every process the same value** — a process cannot drop triggers for models
115
+ it does not mount, so a mixed fleet leaves stale triggers behind.
116
+ - The tokenizer is `AKAN_SEARCH_TOKENIZER` (or `database.search.tokenizer`, which wins), defaulting to
117
+ `unicode61 remove_diacritics 2`. Changing it rebuilds the index from the mirror on the next boot — the model
118
+ tables are never re-read — so it is a safe knob, unlike a `text` role change, which re-reads every row. The
119
+ rebuild takes no cross-process claim, so a fleet restarted at once repeats it in every process; stagger the
120
+ restart when the mirror is large.
121
+
122
+ ## Cascade Remove — the `cascade` option
123
+
124
+ **The value names the direction, and getting it wrong is a data loss.** The two actions can sit on the same field
125
+ shape, so `cascade` never means "related" — it means one of exactly these:
126
+
127
+ - `removeRef` — *when I am removed, remove what this field points at.* Declared on the relation the owner holds:
128
+ `image: field(File, { cascade: "removeRef" })`, arrays included. Only a relation accepts it; a primitive, a bare
129
+ `ID`, and a scalar each fail the class build.
130
+ - `removeWith` — *when what this field points at is removed, remove me.* Declared on the child's own reference to
131
+ its owner, so the owner never learns about its children and a lib model can be extended by an app's. Three forms:
132
+ a relation (`field(AgentSession, { cascade: "removeWith" })`), an id with `ref`, or a polymorphic id with
133
+ `refPath`. An array, a Map, `ref` together with `refPath`, and a field naming no owner each fail the class build.
134
+ - **A `refPath` must name an `enumOf` field** — a free-form owner type is unknowable at build time, so every
135
+ model's removal would have to sweep the polymorphic table on the chance it is the owner.
136
+ - **`cascade: "removeWithAny"` buys that sweep on purpose**, for the one shape an enum cannot express: a child
137
+ whose owner is any model in the app, named by a free-form `String` holding the owner's refName. It is a third
138
+ action rather than a flag beside `removeWith`, because the widening and the direction are one decision — the
139
+ option type pairs the action with the `refPath` it reads the owner off, so neither can be declared alone.
140
+
141
+ ```ts
142
+ parent: field(ID, { refPath: "parentType", cascade: "removeWithAny" }),
143
+ parentType: field(String), // holds the owner's refName
144
+ ```
145
+
146
+ The lookup itself is cheap — the declaration auto-creates the same `{ removedAt, typeKey, fk }` index, so a
147
+ removal that owns nothing is one index probe returning zero rows, not a scan. **The price is bulk: one wildcard
148
+ edge anywhere turns every cascade in the app back to one document at a time**, because a query-level removal of
149
+ *any* model would be a removal whose wildcard children were never looked for. The boot log says so in one
150
+ `info` line naming the edges — that line is the answer to "why does this app remove everything per document".
151
+ The opt-in is what keeps an app that declared none on the fast path.
152
+
153
+ Refused at the class build: `removeWithAny` on a `refPath` that already names an `enumOf` (the enum names the
154
+ candidates and indexes better — use `removeWith`), a `typeKey` that is not a `String` (the sweep matches a
155
+ refName against that column, and a column that cannot hold one silently finds nothing), and the action with no
156
+ `refPath` at all — that last one is a typecheck error at the call site, and the class build keeps the same
157
+ refusal for the macro and bundled paths that reach it untyped. A wildcard owner is also exempt from the mount
158
+ check that a monomorphic owner fails at boot — it names no module to mount.
159
+ - **A cascade goes through the target's service, never its model** — that path is what runs the target's
160
+ `_postRemove`, where a module puts the side effect the removal has to carry.
161
+ - **Bulk is decided at boot, per target model, for both directions.** A target with no `remove` schema hook, no
162
+ `_pre`/`_postRemove`, no cascade of its own, and no children takes one `removeManyByQuery`. Adding a
163
+ `_postRemove` silently flips it back to one document at a time — the boot log is the only place that shows.
164
+ - **The plan is sealed after every service is live**, so a `listenPost("remove")` registered in `onInit` counts,
165
+ and an unmounted `removeRef` target or `removeWith` owner fails the boot rather than the first removal. An
166
+ unmounted `refPath` candidate only warns, since that list spans optional modules by design.
167
+ - **Nothing checks whether another document still references the same target.** `File` in particular is deduped
168
+ by `origin`, so two parents can share one row; `removeRef` claims the field owns its target exclusively.
169
+ - Removal is soft (`removedAt`), but the storage delete a `_postRemove` performs is not — a cascade is not
170
+ restorable, and reviving the owner does not revive what went with it.
171
+ - A `removeWith` declaration **auto-creates its index** (`{ removedAt, fk }`, or `{ removedAt, typeKey, fk }` when
172
+ polymorphic); every non-base field lives in the `_doc` JSON column, so the lookup would otherwise scan the table.
173
+ - **Query-level removes fire no hooks and therefore no cascade** — `removeManyByQuery` / `updateManyByQuery`, the
174
+ generated `remove<Filter>` / `update<Filter>`, and the facade's `removeById` / `updateById`. Remove one document
175
+ at a time when it cascades.
176
+ - Cascades are **idempotent**: `removedAt IS NULL` is ANDed into every query-level write. Cycles are cut by a
177
+ visited set carried down the whole chain, with a depth cap of 16.
178
+
@@ -0,0 +1,25 @@
1
+ {
2
+ "title": "Runtime Rule",
3
+ "description": "Akan build and runtime surfaces — web/csr toggles, the gateway/solo process model, logging, the generated image, and shipped assets",
4
+ "group": "core",
5
+ "codegenPriority": 4,
6
+ "deprecated": false,
7
+ "scans": [
8
+ {
9
+ "type": "example",
10
+ "description": "App and lib runtime declarations",
11
+ "path": "{apps,libs}/*/akan.config.ts",
12
+ "sample": 4
13
+ }
14
+ ],
15
+ "update": {
16
+ "filePath": "./runtimeRule.instruction.md",
17
+ "contents": ["web surface toggles", "process model", "logging and live tail", "generated image", "shipped assets"],
18
+ "rules": [
19
+ "Use current Akan APIs only",
20
+ "State the rule and the reason it exists, never restate a type signature",
21
+ "Name the env that narrows a build-time declaration wherever one exists",
22
+ "Keep it workspace-neutral — no app or repo names"
23
+ ]
24
+ }
25
+ }
@@ -0,0 +1,220 @@
1
+ # Runtime Rule — Serving, Processes, Logging, Image, Assets
2
+
3
+ How an Akan app is built, what it serves, how many processes it runs, where its logs go, and what ends up in
4
+ its image. Everything here is declared in `akan.config.ts` or narrowed by an env at boot; none of it is reached
5
+ from domain code. `conventions` carries the invariants — this is the full contract behind them.
6
+
7
+ ## Web Surfaces — Building And Serving Without SSR/CSR
8
+
9
+ An app serves three things: the API, the SSR/RSC web renderer, and the CSR single-file bundle. The API is always
10
+ on; the other two are declared in `akan.config.ts` as **`web: true | false | { csr: boolean }`** and can be
11
+ narrowed again per deployment.
12
+
13
+ ```ts
14
+ const config: AppConfig = { web: { csr: false } }; // web without the mobile bundle
15
+ const config: AppConfig = { web: false }; // api only
16
+ ```
17
+
18
+ - **`web: { csr: false }`** drops the CSR build phase and the `/__csr` + `?csr=true` routes. The CSR bundle is
19
+ what the Capacitor mobile build ships, so a web-only deployment never needs it — and an app that declares a
20
+ `mobile` section is refused, because `akan build-ios` copies `dist/apps/<app>/csr/<target>.html` into the
21
+ native project.
22
+ - **`web: false`** is an API-only build: no base artifact, no pages or client bundles, no RSC worker
23
+ entrypoint, and no `public/` in the image (the web router's catch-all is its only reader). Nothing under
24
+ `page/` is served, including routes a lib contributed through `syncPageLibs`.
25
+ - **There is no CSR-without-SSR option, by type.** The CSR bundle inlines the stylesheet the SSR base artifact
26
+ compiles, so it would ship an unstyled app — the object form therefore carries only `csr`, and SSR goes off
27
+ only through the whole-surface `false`.
28
+ - **At runtime, `AKAN_SSR` and `AKAN_CSR` narrow further and never widen** — `false` or `0` turns one off, and
29
+ `AKAN_SSR=false` takes CSR with it for the same reason the option has no such pair. A surface the build left
30
+ out cannot be switched back on, and the boot log names what the process ended up serving. The generated
31
+ Dockerfile writes the build's own answer as the image default.
32
+ - **A build with no web artifact boots the API instead of crashing.** `WebRouter.create` returns `null` when
33
+ `.akan/artifact/base-artifact.json` is absent — an api-only build, or a workspace with no `page/` at all.
34
+ - `akan start` ignores `web` and keeps the whole dev surface: the incremental builder is also the file watcher,
35
+ so switching it off would take server-code HMR with it. It warns once when the config and the dev server
36
+ disagree.
37
+ - The saving is mostly the RSC worker, which is a **separate process per web-serving replica**. Measured on
38
+ `apps/akan` at boot plus one render: 350MB across 3 processes with SSR on, 120MB across 2 with
39
+ `AKAN_SSR=false`, and the built image goes 86MB → 6.2MB when the artifacts are left out of it too.
40
+ - **The generated image installs `ca-certificates` and `tzdata` and nothing else.** It used to carry the whole
41
+ Chromium runtime, ffmpeg, `build-essential`, `python3` and `redis` in every app's image whether or not the app
42
+ reached for any of them. An app that needs one declares it in `docker.preRuns` / `docker.postRuns`, which are
43
+ emitted around the `bun install` — that is the migration for a `puppeteer` or `ffmpeg` app.
44
+
45
+ ## Route Prefixes — Where The API Is Mounted
46
+
47
+ Signal endpoints hang off `/api` and the websocket upgrade off `/api/ws`. Both move, and both have to move in
48
+ three places at once: the route table the replica builds, the gateway's own upgrade check, and the `fetchClient`
49
+ in every browser tab. That last one is the constraint the design is built around.
50
+
51
+ ```ts
52
+ // apps/<app>/main.ts — the deployment's answer
53
+ await new AkanApp({ prefix: "/backend", websocketPrefix: "/socket" }).start();
54
+ ```
55
+
56
+ ```ts
57
+ // apps/<app>/akan.config.ts — the build's answer, for the bundles a server never gets to correct
58
+ const config: AppConfig = { api: { prefix: "/backend", websocketPrefix: "/socket" } };
59
+ ```
60
+
61
+ - **Three sources, narrowest first.** `globalThis.__AKAN_PREFIX__`, then `AKAN_API_PREFIX` / `AKAN_WS_PREFIX`,
62
+ then `AKAN_PUBLIC_API_PREFIX` / `AKAN_PUBLIC_WS_PREFIX`, then `/api` and `/ws`. Read them through
63
+ `getApiPrefix()` / `getWsPrefix()` from `akanjs/base`; never write either literal again.
64
+ - **`AKAN_API_PREFIX` is deliberately outside the `AKAN_PUBLIC_*` namespace.** Only that namespace is inlined
65
+ into client bundles at build time, so a name inside it could never act as a runtime override — and only a name
66
+ inside it can reach a prebuilt bundle at all. The two jobs need two names.
67
+ - **`new AkanApp({ prefix })` reaches the browser through the page, not through a prop.** `FetchClient` fixes its
68
+ origin when the module graph initializes, before any component renders, so a React prop — a `System.Provider`
69
+ value, anything out of `implicitRootLayout` — is always too late. The value rides the SSR classic bootstrap
70
+ script instead, the one thing guaranteed to run ahead of every module script, and is omitted when it matches
71
+ what the bundle already assumes. `akan.config.ts` is what a Capacitor bundle or a statically served CSR shell
72
+ follows, because neither is rendered by a server that could tell it otherwise.
73
+ - **A prefix is a path segment.** A blank value or a bare `/` is refused: `/` would be mounted ahead of the SSR
74
+ catch-all and swallow every page route. A prefix whose first segment is a declared basePath is refused at
75
+ `init()` for the same reason in the other direction.
76
+ - **The prefix is fixed before `init()`.** `setPrefix` / `setWebsocketPrefix` throw once the server has started,
77
+ because `init()` is where the route table and the devtools routes are built.
78
+ - `robots.txt`, the locale redirect's API bypass and the OpenAPI `servers` URL all derive from it. The blob
79
+ storage default (`/api/localFile/getBlob`) does **not**: those URLs are stored in rows, so moving the prefix
80
+ does not move what was already written.
81
+
82
+ ## The Process Model — Gateway And Solo
83
+
84
+ A container runs one process per replica, a gateway in front of them when there is more than one, and one RSC
85
+ worker per web-serving replica.
86
+
87
+ - **One traffic replica runs in the container's only process.** `AKAN_REPLICA=0,0,1` — the default, and what
88
+ every environment in `infra/app/values` sets — means there is nothing to balance and nothing to fan pubsub out
89
+ to, so `AkanApp` starts that replica in-process rather than spawning it. Measured on `apps/akan`: 28MB less RSS
90
+ and twice the requests per second, because every request used to cross a unix-socket proxy hop. Declare two or
91
+ more and the gateway is back, spawning and proxying them.
92
+ - **`AKAN_SOLO=false` forces the gateway** for a single replica. Like `AKAN_SSR`, the env only narrows — it
93
+ cannot fold a real gateway's replicas into one process. Passing `replica` to `new AkanApp(...)` also keeps the
94
+ gateway: code that states a topology is asking for the thing that serves it.
95
+ - **`akan start` always runs the gateway**, whatever the replica count. It is also the dev host's builder relay,
96
+ its crash page, and what holds the port across a child restart.
97
+ - **A batch-only replica (`0,1,0`) keeps the gateway too**, because a batch server never listens and the gateway
98
+ is then the only thing bound to answer `/_akan/app/health`.
99
+ - **The RSC worker is never folded in.** It runs under `--conditions react-server`, which resolves the same
100
+ module graph differently, so it cannot share a process with the server that renders client components.
101
+ - **A solo process answers `/_akan/app/health`, `/_akan/app/metrics` and `/_akan/bench/ping` itself**, in the
102
+ gateway's own shape — a `children` array with one entry — so a probe reads one contract either way. It owns the
103
+ rotating log file the gateway would otherwise write, in the same `runtime/logs` directory.
104
+ - **Nothing supervises a solo process but the orchestrator**, since the gateway's crash-restart-with-backoff went
105
+ with it. `infra/app/templates/app.yaml` carries the liveness, readiness and startup probes that replace it.
106
+ - **`PORT` is the whole tree's port, and a server-side self-call follows it.** `AkanApp` resolves it once
107
+ (`new AkanApp({ port })`, else `PORT`, else 8282) and publishes it to the replica it runs in-process and to
108
+ every child it spawns — a federation child listens on a unix socket, but the loopback fetches its SSR and RSC
109
+ worker make still come back through the gateway. `getEnv().serverPort` reads it whenever the origin resolved to
110
+ `localhost`, so a container run with `PORT=80` calls itself on 80. Override the origin only when it is genuinely
111
+ not this process: `AKAN_PUBLIC_SERVER_PORT` outranks `PORT`, and a `SERVER_HOST` naming another host is not a
112
+ self-call and keeps its explicit port.
113
+ - **`main.ts` imports `AkanApp` from `akanjs/server/akanApp`, not the barrel.** The barrel re-exports
114
+ `AkanServer`, whose graph the gateway never runs; through it the process evaluated 35MB of SSR renderer and
115
+ SQLite driver to spawn children and relay bytes. Keep entrypoint imports at the leaf.
116
+
117
+ ## Logging — Records, Request Context And Live Tail
118
+
119
+ Every `Logger` call builds a `LogRecord` before any text exists: `at`, `level`, OTel `sev`, `name`, `message`,
120
+ `pid`, `replicaIdx`, `role` (`gateway` / `all` / `batch` / `rsc-worker`) and — inside a call — `traceId`,
121
+ `endpoint` (`mutation:signScContract`, `internal:cleanupJob`, `page:/org/[orgId]`) and `origin` (`http`,
122
+ `websocket`, `mcp`, `internal`, `page`). The console line is rendered from the record and is byte-identical to
123
+ what it was; a sink reads `entry.record` and renders only if it touches `entry.message`.
124
+
125
+ The level ladder is `trace verbose debug info warn error`. `log` was a seventh tier *below* `info` that
126
+ `AKAN_PUBLIC_LOG_LEVEL=info` silently dropped; the method is kept and emits at `info`, so
127
+ `no-deprecated-log-level.grit` refuses a call to it — write `.info()`. `AKAN_PUBLIC_LOG_LEVEL=log` still boots,
128
+ normalized to `info` with one warning.
129
+
130
+ - **Request context is on by default, production included.** `SignalContext.try` / `SignalContext.run` own the
131
+ `AsyncLocalStorage` scope for the whole call, including the 500 log, so every line of one request shares a
132
+ `traceId`. Internal triggers get `internal:<key>`, the RSC worker gets `page:<route>`, MCP calls are the
133
+ endpoint's own type with `origin: "mcp"`. `AKAN_LOG_CONTEXT=0` is the escape hatch; `AKAN_TRACE=1` is a
134
+ different switch that adds span and query aggregation. Measured cost: ~25ns per call.
135
+ - **Not everything carries context, by design.** The primitive query fast path (an unauthenticated GET of a
136
+ primitive with no args, guards or middlewares) skips it; the schedule adaptor's own `started/finished/error`
137
+ lines wrap the traced handler from outside; gateway-internal lines have none. `akan logs --endpoint` says so.
138
+ - **`Logger.addSink(sink, { minLevel })` — give a sink its floor.** A sink with none follows `AKAN_LOG_FILE_LEVEL`
139
+ (default `trace`), which is why a registered sink used to make every `verbose` call render (1,294ns against an
140
+ 11ns reject). The IPC forwarder and any sink that never reads the text pass a floor and cost a record literal.
141
+ - **The hub lives with whoever owns the surface**: the gateway when there is one, the replica itself under solo
142
+ (`AKAN_REPLICA=0,0,1`), the same rule as the rotating log file and `/_akan/app/*`. It keeps a ring
143
+ (`AKAN_LOG_BUFFER` records / `AKAN_LOG_BUFFER_MB`, default 2000 / 4), suppresses a line repeating more than 20
144
+ times a second into one counted line, and serves `<runtimeDir>/akan-control.sock` (`0600`, NDJSON). A child
145
+ forwards records only while a subscriber wants that level (`log.level` IPC), so an unwatched process sends
146
+ nothing; `AKAN_LOG_STREAM=1` keeps it on. The RSC worker forwards to its replica the same way.
147
+ - **`akan logs <app>`** is the client: `--level --grep --endpoint --trace --child --role --origin --since`
148
+ AND together, comma lists OR, `*` is the only glob; `--replay N` first, `--follow false` for history only,
149
+ `--json` for NDJSON, `--runtime-dir` for a built app. Inside `akan console`, `.tail level=warn grep=payment`,
150
+ `.tail off`, `.trace <id>` — the console is its own `listen: false` process, so these attach to the running
151
+ server's socket rather than reading their own logs.
152
+ - **The generated Dockerfile sets `AKAN_LOG_TO_FILE=0`.** A container's writable layer is ephemeral and nothing
153
+ collects a file from it; stdout is the collection path. A deployment that wants the files back sets
154
+ `AKAN_LOG_TO_FILE=1`.
155
+ - **Never log per delivered record in anything that delivers records.** The control socket and the hub do not,
156
+ and a subscriber asking for everything is the test.
157
+
158
+ ## The Generated Image — `docker` In `akan.config.ts`
159
+
160
+ **`docker` is `string | { image, preRuns, postRuns, command }`** — a whole Dockerfile, or the parts Akan
161
+ assembles one from. There is no `content` field; the string *is* the content.
162
+
163
+ ```ts
164
+ const config: AppConfig = {
165
+ docker: { preRuns: ["apt-get update && apt-get install -y --no-install-recommends ffmpeg"] },
166
+ };
167
+ const config: AppConfig = { docker: "FROM oven/bun:1-slim\n…" }; // verbatim, nothing merged in
168
+ ```
169
+
170
+ - `image` and each run entry take `string | { amd64?, arm64? }`; the object form compiles to a
171
+ `RUN if [ "$TARGETARCH" = "<arch>" ]` guard, so a multi-arch build runs it on one leg only. `preRuns` land
172
+ before `bun install --production` (where a native dependency's build tools have to be), `postRuns` after it
173
+ and before the app files are copied.
174
+ - **A lib declares the steps its own runtime needs**, and every app that mounts it inherits them:
175
+ `libs/<lib>/akan.config.ts` takes `docker: { preRuns, postRuns }` and nothing else — the base image and the
176
+ command belong to the app. Lib steps are emitted before the app's own, and an identical step declared twice
177
+ becomes one layer.
178
+ - **The string form takes no contributions.** A Dockerfile handed over whole is used exactly as written, so a
179
+ lib's `preRuns` are dropped rather than spliced into a file Akan does not own. An app that needs both writes
180
+ the parts instead.
181
+ - Like `externalLibs`, lib steps are collected from **every lib in the workspace**, not just this app's
182
+ dependency closure — narrowing that set needs the dependency scan, and this config is re-read on every file
183
+ change in dev. Keep a lib's steps to what its runtime genuinely requires.
184
+ - `AkanAppConfig.docker` is the resolved declaration; `AkanAppConfig.dockerfile` is the text `akan build` writes
185
+ to `dist/apps/<app>/Dockerfile`.
186
+
187
+ ## Shipped Assets — `assets` In `akan.config.ts`
188
+
189
+ `akan build` copies the whole `public/` tree into `dist`, lib assets dereferenced, and that copy is the image.
190
+ **`assets: { pruneFonts, keepFonts }`** trims the fonts out of it that nothing reads. **Source trees are never
191
+ touched** — an app's and a lib's own `public/` keep every file, because one shared font folder is picked over
192
+ differently by every app that mounts it and by other repos.
193
+
194
+ ```ts
195
+ const config: LibConfig = { assets: { keepFonts: ["fonts/Assistant-*.woff2"] } }; // libs/<lib>/akan.config.ts
196
+ const config: AppConfig = { assets: { pruneFonts: false } }; // emergency valve, not the normal escape hatch
197
+ ```
198
+
199
+ - **A font with `optimize` on is a build input, not a runtime asset.** `FontOptimizer` subsets it into
200
+ `.akan/artifact/fonts` and the emitted CSS points at `/_akan/fonts/*`, which `WebRouter` serves from the
201
+ artifact — so the source in `public/` is never opened again. That is the bulk of what this drops, and it
202
+ applies to the fonts the app *does* use, not only the ones it does not.
203
+ - **The keep-set is derived per app, per build; there is no list of fonts to drop.** An exclude list would rot
204
+ the moment another app or repo started using one of them, and nobody would know to update it. A font survives
205
+ because ① its font declares `optimize: false`, so `FontCss.getRuntimeCss` emits the raw src; ② something
206
+ references its filename — anything under `public/`, the compiled stylesheet, a client/server bundle, the CSR
207
+ shell; or ③ a `keepFonts` glob names it.
208
+ - **`keepFonts` belongs to the `akan.config.ts` that owns the font**, written against that lib's or app's own
209
+ `public/` (`"fonts/X.woff2"`, resolved to `libs/<lib>/fonts/X.woff2`). A lib shared across repos carries the
210
+ reason its own CSS needs a font, instead of every mounting app rediscovering it in production.
211
+ - **A reference from a build bundle is ignored for an already-subset font.** Every route file's `fonts`
212
+ declaration is inlined into the pages bundle, the client chunks and the CSR shell, so a declared source is in
213
+ all three whether or not anything loads it. `public/` and the compiled CSS are read as authoritative.
214
+ - **A generated manifest that lists every public asset keeps every font it names** — a service-worker precache
215
+ file is the usual one. That is a real reference, not a false positive, so the build reports it at `info`:
216
+ read the `[font-prune] kept …` line before concluding the prune does nothing.
217
+ - Matching is by filename, including the percent-encoded spelling, so a `url()` survives however it is written.
218
+ - The phase is `assets`, between `csr` and `compress`. An api-only build (`web: false`) copies no `public/` and
219
+ the phase finds nothing to do.
220
+
@@ -71,18 +71,64 @@ Never collapse this into one client file with a mode `useState` and every panel
71
71
 
72
72
  **③ Sync state instead of fetching it.** A server component cannot hold state, so render the initial data on the
73
73
  server and hand it across as a serializable object. The route calls `fetch.initXInY(...)` / `fetch.viewX(...)` and
74
- passes the result into a `Zone`; `Load.Units` / `Load.View` hydrate the store from it. A `useEffect(…, [])` that
75
- fetches on mount renders an empty shell, hydrates, then round-trips for data the server already had.
74
+ passes `xInitInY` / `xView` into a `Zone`; `Load.Units` / `Load.View` hydrate the store from it. A
75
+ `useEffect(…, [])` that fetches on mount renders an empty shell, hydrates, then round-trips for data the server
76
+ already had.
76
77
 
77
78
  **④ Push the boundary down to the leaf that needs it.** A store-reading `Zone` should hold zero markup and delegate
78
79
  to a server `View` — `User.Zone.Self` is one line, `st.use.self()` into `<User.View.General user={self} />`, so the
79
80
  whole detail surface renders server-side wherever a route uses the `View` directly.
80
81
 
81
- **⑤ Hand the promise across, not the awaited value.** `ClientInit` / `ClientView` are `PromiseOrObject<T>`, so a
82
- route may pass an unawaited `fetch.initX(...)` and `Load.*` resolves it behind a skeleton. `await` blocks the shell
83
- for data the page needs immediately; the promise streams the rest. Independent fetches still go through one
82
+ **⑤ Hand each promise across, not the awaited value.** `fetch.init<Model><Suffix>`, `fetch.view<Model>` and
83
+ `fetch.edit<Model>` are awaitable *and* destructurable, so a route can split one call into the promises its
84
+ sections actually need:
85
+
86
+ ```tsx
87
+ export default page()
88
+ .param("orgId", ID)
89
+ .render(async ({ orgId }) => {
90
+ const { taskInitInOrg, taskListInOrg } = fetch.initTaskInOrg(orgId);
91
+ const { orgView } = fetch.viewOrg(orgId);
92
+ return (
93
+ <>
94
+ <Org.Zone.Header view={orgView} />
95
+ <Task.Zone.Card init={taskInitInOrg} />
96
+ <Load.Stream of={taskListInOrg} fallback={<Loading.Skeleton active />}>
97
+ {(taskList) => taskList.map((task) => <Task.Unit.Row key={task.id} task={task} />)}
98
+ </Load.Stream>
99
+ </>
100
+ );
101
+ });
102
+ ```
103
+
104
+ Both queries leave immediately — splitting the result never serializes them — and each section renders behind its
105
+ own boundary as its own data lands, so one slow query no longer holds the page. `x<Slice>List` does not wait for
106
+ the aggregate the way `x<Slice>Init` must.
107
+
108
+ **`await` is still the right call for what the page needs immediately.** It returns the shape the helper always
109
+ gave and keeps that markup in the shell, which is what SEO snapshots, prerendering and pre-hydration E2E read; a
110
+ boundary moves its subtree out of the shell and into the stream. Independent awaited fetches still go through one
84
111
  `Promise.all`.
85
112
 
113
+ Three rules the shape enforces:
114
+
115
+ - **`x<Slice>List` and `x<Slice>Insight` are server-only.** They hold hydrated model instances, which React Flight
116
+ refuses as props to a client component. Consume them in a server component; `x<Slice>Init` (plain data) is the
117
+ one that crosses into a `Zone`.
118
+ - **Never hand the whole handle to a component** — pass the field. `<Zone init={xInitInY} />`, not
119
+ `<Zone init={fetch.initXInY(id)} />`.
120
+ - **Rendering the list on the server costs one extra hydration.** `Load.Stream` builds the model instances on the
121
+ server and `Load.Units` builds them again after hydration, so a large list is still better off going through
122
+ `x<Slice>Init` → `Zone` alone. Reach for `Load.Stream` when the markup is small and static enough that having
123
+ it in the HTML is worth more than the second pass.
124
+
125
+ **A failure now surfaces where it happened.** One `Promise.all` in the page body reports nothing about which of
126
+ eight queries threw; per-section boundaries put each rejection at its own boundary.
127
+
128
+ **Keep the auth gate in the shell.** A redirect thrown after the shell has flushed can only be delivered as a
129
+ soft-redirect script, so `getSelf({ unauthorize: "/signin" })` stays in `_layout.tsx` or the page body — never
130
+ inside a streamed section.
131
+
86
132
  **⑥ Use named `ReactNode` slots, not just `children`.** `Layout.Navbar` accepts `title`, `back`, `left`, `right`,
87
133
  and `children`, so a client shell composes server-rendered content in five places instead of absorbing it.
88
134
 
@@ -0,0 +1,31 @@
1
+ {
2
+ "title": "Transport Rule",
3
+ "description": "How a call reaches an Akan signal — guards across HTTP and websocket, socket identity and cleanup, binary pubsub frames, and mutation HTTP verbs",
4
+ "group": "core",
5
+ "codegenPriority": 4,
6
+ "deprecated": false,
7
+ "scans": [
8
+ {
9
+ "type": "example",
10
+ "description": "Guard classes and their scope markers",
11
+ "path": "{apps,libs}/*/srvkit/guards.ts",
12
+ "sample": 2
13
+ },
14
+ {
15
+ "type": "example",
16
+ "description": "Signal endpoints declaring guards, pubsub, and message handlers",
17
+ "path": "{apps,libs}/*/lib/*/*.signal.ts",
18
+ "sample": 4
19
+ }
20
+ ],
21
+ "update": {
22
+ "filePath": "./transportRule.instruction.md",
23
+ "contents": ["guards across transports", "signal body types", "binary pubsub", "mutation HTTP verbs"],
24
+ "rules": [
25
+ "Use current Akan APIs only",
26
+ "State the rule and the reason it exists, never restate a type signature",
27
+ "Say what leaks or breaks when a rule is ignored",
28
+ "Keep it workspace-neutral — no app or repo names"
29
+ ]
30
+ }
31
+ }
@@ -0,0 +1,60 @@
1
+ # Transport Rule — Guards, Sockets, Binary Frames, HTTP Verbs
2
+
3
+ How a call reaches a signal: what a guard may read on either transport, how a websocket carries its credential
4
+ and its per-connection state, when a pubsub payload leaves JSON for a binary frame, and which HTTP verb a
5
+ mutation is mounted under. `conventions` carries the invariants — this is the full contract behind them.
6
+
7
+ ## Guards And Transports
8
+
9
+ - 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()`.
10
+ - 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.
11
+ - 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.
12
+ - 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.
13
+ - **Never read the caller's IP off the socket or the request peer — take `.with(Ip)`.** Whenever a federation
14
+ gateway is in front, `ws.remoteAddress` and the child's own peer are the *gateway* (`127.0.0.1`) for every
15
+ caller and for the whole life of every socket. `Ip` reads what a proxy recorded (`x-real-ip`, then the first
16
+ `x-forwarded-for` entry) and falls back to the peer only when nothing proxied the call — which is the answer
17
+ for a solo process behind an ingress that sets neither; `context.getClientIp()` is the same answer inside a
18
+ guard or middleware. It arrives unwrapped from
19
+ its `::ffff:` IPv4-mapped form, so it can address a `udp4` socket as well as identify a caller, and it is
20
+ `null` rather than a placeholder when genuinely unknown — a loopback-looking address for an unknown caller
21
+ is the failure this replaced. The gateway also forwards the client port (`x-forwarded-port`, read with
22
+ `context.getClientPort()`) along with host and protocol.
23
+ - **Every socket carries a `socketId`, and only the framework mints one.** `AppWsData` assigns it at the handshake, and a `message` / `pubsub` handler reads it off the `Ws` internal arg — `.with(Ws)` hands `{ ws, socketId, subscribe, on, off }`. Never mint your own from `ws.data`: the room bookkeeping keys on the framework's id, and a second one fails to match it silently. It identifies a **connection**, not a caller — a reconnect gets a new id and the federation gateway's own socket is a different one — so per-user state keys on the account, never on this.
24
+
25
+ - **A cleanup registered with `ws.on("disconnect" | "unsubscribe", fn)` is scoped to the call that registered it.**
26
+ From a `pubsub` subscribe it belongs to that room — `unsubscribe` runs when the client leaves it or a credential
27
+ change revokes it, `disconnect` when the socket closes while still subscribed — so a room already left runs
28
+ neither again, and cleanup that must happen either way registers for both. From a `message` handler it belongs to
29
+ the socket and runs at close. A handler that throws is logged and never blocks the rest of the teardown.
30
+
31
+ ## Binary Pubsub
32
+
33
+ - **`pubsub(Binary)` sends its payload in a websocket binary frame**, skipping the JSON `{ type: "pub" }`
34
+ envelope and the base64 a JSON wire would need. The client's subscribe callback receives a `Uint8Array`.
35
+ Nothing else is declared: the return type is the whole switch, and text and binary frames coexist on one
36
+ socket, so every JSON endpoint is untouched. The optimization applies only when the **whole** return is
37
+ `Binary` — `[Binary]`, or a `Binary` inside a model, falls back to base64.
38
+ - **A declared `Binary` room coalesces under backpressure**: while a socket cannot keep up the room keeps only
39
+ its newest frame and drops the rest, which is what a telemetry or video stream wants. Declare
40
+ `pubsub(Binary, { backpressure: "queue" })` when the frames are a sequence a subscriber must see in full, such
41
+ as deltas against a base it already holds; the send buffer then grows with the slowest subscriber. Coalescing
42
+ is keyed by the endpoint, not carried with the frame, so this process, an IPC deliver and a Redis fan-out all
43
+ reach the same answer. Coalesced frames are counted in `pubsubCoalesceCount` on the replica's metrics report.
44
+ - **A `pubsub(Any)` that happens to carry bytes is framed too, and warns once.** `Any` passes a `Buffer` through
45
+ untouched, so the transport sees bytes and sends them whole rather than as a number array — an undeclared
46
+ publisher is fixed rather than left corrupt. It is still not the contract: it queues rather than coalescing
47
+ (nobody declared lossy delivery for that room), and a Redis fan-out still JSON-stringifies it. Declare
48
+ `Binary`.
49
+ - The federation gateway relays a binary frame unchanged, and Bun IPC carries bytes as bytes, so the only hop
50
+ that needed teaching was the socket itself. A cross-server (Redis) fan-out encodes it as protobuf `bytes`.
51
+
52
+ ## Mutation HTTP Verb
53
+
54
+ - A `mutation` is `POST`. `{ method: "PATCH" | "PUT" | "DELETE" }` moves it, and one path may carry several verbs
55
+ — a `query` GET and a `mutation` POST on the same custom `path` are mounted side by side. Two endpoints claiming
56
+ the same path **and** verb fail the boot rather than silently shadowing one another.
57
+ - Reach for it only when a foreign wire protocol forces the verb (a client you cannot change that sends
58
+ `PATCH /rest/v1/<table>`). Akan's own `fetch.*` client, the OpenAPI document, and the API explorer all follow
59
+ whatever is declared, so nothing needs restating per caller.
60
+