@akanjs/cli 3.1.0-rc.9 → 3.1.1-rc.0

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 (91) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-rkjyxgec.js → CodeAgent-4pnxwptq.js} +2 -2
  3. package/{CodeAgentRpcHost-p7h6n2hp.js → CodeAgentRpcHost-9g27hmer.js} +1 -1
  4. package/{CodeTui-h7pyj6xa.js → CodeTui-hhndze8h.js} +47 -4
  5. package/README.ko.md +1 -1
  6. package/README.md +1 -1
  7. package/TunnelShare-zmq6bbar.js +14 -0
  8. package/{agent.command-3qxf4xcj.js → agent.command-p02330r6.js} +5 -5
  9. package/akanCode.js +7 -5
  10. package/{application.command-m1kcd7jf.js → application.command-ywks5ywm.js} +35 -9
  11. package/{applicationBuildRunner-dj0xkrep.js → applicationBuildRunner-9cnnsdm5.js} +23 -8
  12. package/buildBatch.proc.js +9 -9
  13. package/{cloud.command-9cp1t0f5.js → cloud.command-1tzkvje1.js} +13 -13
  14. package/cloud.script-8g83xqdg.js +24 -0
  15. package/{code.command-0ad6gw2a.js → code.command-16pm1p2v.js} +25 -12
  16. package/commandManifest.json +1 -1
  17. package/{context.command-0qx447mb.js → context.command-6ys86sqf.js} +16 -16
  18. package/context.runner-3jrypwe3.js +25 -0
  19. package/{guideline.command-cv5bmrx2.js → guideline.command-3zay3d8g.js} +2 -2
  20. package/guidelines/agentRule/agentRule.instruction.md +25 -10
  21. package/guidelines/conventions/conventions.instruction.md +71 -24
  22. package/guidelines/fieldRule/fieldRule.instruction.md +17 -0
  23. package/guidelines/mcpRule/mcpRule.instruction.md +93 -48
  24. package/guidelines/modelDocument/modelDocument.instruction.md +2 -1
  25. package/guidelines/modelStore/modelStore.instruction.md +7 -0
  26. package/guidelines/pageRule/pageRule.instruction.md +55 -8
  27. package/guidelines/queryRule/queryRule.instruction.md +24 -10
  28. package/guidelines/runtimeRule/runtimeRule.instruction.md +12 -4
  29. package/guidelines/ssrRule/ssrRule.instruction.md +9 -6
  30. package/guidelines/transportRule/transportRule.instruction.md +36 -5
  31. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +5 -3
  32. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +28 -8
  33. package/incrementalBuilder.proc.js +3 -3
  34. package/{index-cpb3nvma.js → index-1f33g2z5.js} +2 -2
  35. package/{index-tamvyvj3.js → index-1mfyyxh5.js} +3 -3
  36. package/{index-wa5jbxj1.js → index-2mrn1mrg.js} +1 -0
  37. package/{index-8fp3b47h.js → index-4w3skd33.js} +281 -46
  38. package/{index-bspm21y1.js → index-68c3gzvg.js} +7 -7
  39. package/{index-20bxxyvn.js → index-9hbhm6cs.js} +40 -2
  40. package/{index-d2242ksy.js → index-at7bz0xq.js} +3 -0
  41. package/{index-fmzcs8v6.js → index-b5vptvnt.js} +4 -4
  42. package/{index-d72hfmdm.js → index-bb4hj03s.js} +8 -8
  43. package/{index-9z426msb.js → index-e9e9cebg.js} +78 -27
  44. package/{index-vk0pa0mn.js → index-ekpp5tax.js} +2 -1
  45. package/{index-35hc95h5.js → index-fmder14z.js} +1 -1
  46. package/{index-86jt2a0e.js → index-g2s33373.js} +1 -1
  47. package/{index-4mhy6qme.js → index-jaa81e9r.js} +4 -4
  48. package/{index-192ha4xh.js → index-jgs8z8xb.js} +3 -3
  49. package/{index-qwa5k1j8.js → index-kcbq2qcf.js} +1 -1
  50. package/{index-w44cy4vs.js → index-ngpn9hzy.js} +6 -4
  51. package/{index-jw1zm273.js → index-p4dnj2wc.js} +54 -10
  52. package/index-q8age5az.js +643 -0
  53. package/{index-j4mkhz93.js → index-qfzfaq96.js} +3 -3
  54. package/{index-pydbnfez.js → index-qkcwsg6r.js} +35 -9
  55. package/{index-d47ypebv.js → index-qtkycaqn.js} +75 -19
  56. package/{index-va06nr10.js → index-rr7jk14m.js} +65 -20
  57. package/{index-1xj2t7cb.js → index-sh9mmp5v.js} +7 -7
  58. package/{index-1p98exm2.js → index-sng3vt0p.js} +2 -2
  59. package/{index-j237xtew.js → index-tk3jg2bm.js} +25 -8
  60. package/{index-fyq1z6kt.js → index-vg28jsf9.js} +3 -3
  61. package/{index-trpasv9q.js → index-ynqxpwx6.js} +1 -1
  62. package/{index-5edzv8fn.js → index-z6v7k9sb.js} +2 -2
  63. package/{index-g1mbppa9.js → index-z9xepn8t.js} +5 -5
  64. package/{index-awbdfcf2.js → index-zn6bn1s2.js} +4 -4
  65. package/index.js +40 -22
  66. package/{library.command-erp2f56n.js → library.command-a8n9h8j4.js} +3 -3
  67. package/{localRegistry.command-y176p558.js → localRegistry.command-1e6m7w2f.js} +12 -12
  68. package/{module.command-gs2r615e.js → module.command-b6f1p1xa.js} +5 -5
  69. package/{package.command-j10r76ax.js → package.command-tc27ftmy.js} +3 -3
  70. package/package.json +16 -16
  71. package/{page.command-4h4a8pnh.js → page.command-m5wyqfkd.js} +3 -3
  72. package/{pipeline.command-a2nrk26m.js → pipeline.command-4qxyafpz.js} +2 -2
  73. package/{primitive.command-w6t0asqz.js → primitive.command-9yaatk0d.js} +6 -6
  74. package/{projectTypecheck-f534enqj.js → projectTypecheck-87k6z6ab.js} +1 -1
  75. package/{quality.command-77x7vbbx.js → quality.command-ht1wjhv8.js} +2 -2
  76. package/{repair.command-y6sstev7.js → repair.command-evg9g911.js} +5 -5
  77. package/{routeSourceValidator-7ycnfz0e.js → routeSourceValidator-6jd0q6r6.js} +47 -14
  78. package/{scalar.command-20b8cy0k.js → scalar.command-xsejjeq1.js} +4 -4
  79. package/skills/akan-code/SKILL.md +4 -0
  80. package/skills/akan-store/SKILL.md +4 -2
  81. package/{subspace.command-5c7yasd7.js → subspace.command-ps12q5y7.js} +8 -17
  82. package/templates/migration/__migrationId__.ts +23 -0
  83. package/templates/server.ts +8 -1
  84. package/templates/workspaceRoot/biome.json.template +1 -1
  85. package/{tunnel.command-2kw8vt9g.js → tunnel.command-khzgvrj8.js} +7 -7
  86. package/{workflow.command-2djwmpqf.js → workflow.command-qpyq0ya5.js} +10 -10
  87. package/{workspace.command-ms84ykse.js → workspace.command-3dq7e9g2.js} +30 -28
  88. package/TunnelShare-661cxz5e.js +0 -14
  89. package/cloud.script-dgstqt1m.js +0 -24
  90. package/context.runner-1vsjztjg.js +0 -25
  91. package/index-665zp9rs.js +0 -271
@@ -40,9 +40,9 @@ export class FileSlice extends slice(srv.file, {
40
40
  `update`, `remove`), same fallbacks (`create`/`update`/`remove` inherit `cru`), and the same scope: it narrows
41
41
  the root slice and the generated CRUD, and never reaches a named slice or a custom endpoint. Those declare
42
42
  their own `mcp` beside their own `guards`. The bare `mcp: false` is every key at once, still within that scope.
43
- - **A screen keeps reaching it.** To a host that renders MCP Apps views, an endpoint refused for `mcp: false` alone
44
- is published with `visibility: ["app"]`: the view the page tool opens may call it, the model is never shown it
45
- (below). Every other refusal still holds there.
43
+ - **A view keeps reaching it.** To a host that renders MCP Apps views, an endpoint refused for `mcp: false` alone
44
+ is published with `visibility: ["app"]`: an app's view may call it, the model is never shown it (below). Every
45
+ other refusal still holds there.
46
46
  - **`mcp: true` is the default and is a no-op**; write it only to say out loud that an entry is deliberately on
47
47
  the shelf. It does not override a shape refusal (an `Any` return stays refused) and it cannot publish something
48
48
  the guard rules keep out.
@@ -203,7 +203,8 @@ export default page()
203
203
  - The `readOnly` / `destructive` / `idempotent` hints a client renders are derived from the endpoint type and key
204
204
  and are not configurable. Clients are told to distrust hints; they are never a gate.
205
205
  - **`AKAN_MCP_READONLY=true` is the read-only-deployment valve, not the exposure switch.** It drops every mutation
206
- whatever it declared, and reports each one in the boot log like any other refusal.
206
+ whatever it declared, and reports each one in the boot log like any other refusal. It also drops each `.prompt()`
207
+ page's text tool, whose run renders the whole page; the prompts, the `.app()` tools and their views stay.
207
208
  - OAuth resource metadata is published at `/.well-known/oauth-protected-resource` (and at that path plus the mount
208
209
  path, the spelling most clients try first). `auth.authorizationServers` / `AKAN_MCP_AUTH_SERVERS`,
209
210
  `auth.scopes` / `AKAN_MCP_SCOPES`, `auth.resource` / `AKAN_MCP_RESOURCE` and `auth.verify` configure it;
@@ -238,15 +239,19 @@ export default page()
238
239
  - **A caller's own mistake is reported as one** and never as a server failure: an argument that is missing,
239
240
  unparseable, outside its `enumOf`, or **undeclared** comes back as `isError` naming it — `additionalProperties: false` travels in the
240
241
  published schema and nothing on the wire enforces it — and so does a document that is not there, as
241
- `No <model> found for the arguments given.` A prompt, having no `isError` to carry a refusal, answers `-32602`.
242
+ `No <model> found for the arguments given.`, and an MCP App view also receives the 404 `base.error.documentNotFound`
243
+ `Err` a browser would get. A prompt, having no `isError` to carry a refusal, answers `-32602`.
244
+ A document missing on another server this one called (`fetch.clone({ origin })`) arrives as that server's 404
245
+ `base.error.documentNotFound`, so a tool reads its dictionary sentence (`The requested item does not exist.`) and an
246
+ MCP App view receives that `Err`; a prompt whose page reads it is `No screen exists for these arguments.`
242
247
  Only a real failure logs a stack; an agent can drive the rest at will.
243
248
  - **Three revisions are spoken**: the modern `2026-07-28` and the legacy `2025-11-25` / `2025-06-18`, which are
244
249
  wire-identical over the POST-only surface this implements — a client whose proposal is not listed is told to
245
250
  disconnect. An unknown proposal is answered at whichever end of that list it is closer to, and an unimplemented
246
251
  method answers `404` to a modern client but `200` to a legacy one, whose era spends `404` on "your session is
247
- gone". **While a `.prompt()` page may show as a view only the legacy pair is spoken**: `server/discover` answers
252
+ gone". **While an `.app()` may show as a view only the legacy pair is spoken**: `server/discover` answers
248
253
  `-32601` and `initialize` settles on `2025-11-25`, because claude.ai renders a view only for a server it reached
249
- through `initialize`. An app that renders no view, or whose RSC worker lists no `.prompt()` page, speaks all three.
254
+ through `initialize`. An app that renders no view, or whose RSC worker lists no `.app()`, speaks all three.
250
255
  `modern: true` / `AKAN_MCP_MODERN=true` offers `2026-07-28` anyway; `false` withholds it everywhere.
251
256
  - **A modern-era request mirrors `MCP-Protocol-Version` and `Mcp-Method` into headers** (plus `Mcp-Name` when the
252
257
  body names one), and one that leaves a mirror out is refused just like one that contradicts the body: a gateway
@@ -345,8 +350,10 @@ delegates to lives in `akanjs/server` (`OAuthAuthorize`, `OAuthToken`, `OAuthReg
345
350
  board of one project.").render(…)` — and that is the whole surface. `prompts/list` is every page carrying
346
351
  `.prompt()`; its `.param()` stages are the required arguments and its `.search()` stages the optional ones, a list
347
352
  argument is comma-separated on the wire and its description says so, and an `ID`/`Int`/`enumOf` value is checked by
348
- the page's own declaration. **`prompts/get` runs the page's body** — root layouts, layouts, then the page's
349
- `.render()` — in the RSC worker under the caller's bearer token, the way a tab would open it. Nothing is rendered:
353
+ the page's own declaration. `prompts/list` shows only the screens whose route `.guard()`s admit the caller; a listing
354
+ knows no arguments, so a guard that reads one admits there and is checked again on the call. **`prompts/get` runs the
355
+ route's guards, then the page's body** — root layouts, layouts, then the page's `.render()` — in the RSC worker under
356
+ the caller's bearer token, the way a tab would open it. Nothing is rendered:
350
357
  the JSX comes back as an element tree nobody walks, no client component runs, and the screen's data footprint is
351
358
  exactly the `fetch.*` queries its body made, with the arguments it made them with. The answer is the description as
352
359
  the first message (priority 1), one embedded `resource` per query masked by that endpoint's return model and
@@ -362,74 +369,109 @@ pass. A layout's own queries (a project selector's `projectListInOrg`) are part
362
369
  attached too. **No argument fallback**: a required argument left out answers one message — `No projectId was named for
363
370
  "briefProjectTickets". Find it with \`projectListBySearch\`, then run this prompt again with projectId=<id>.` —
364
371
  and runs nothing, because a prompt cannot re-run itself and context filled in on a guess would never be used. A
365
- page that redirects (`getSelf({ unauthorize })`), or whose `fetch.*` a guard refuses with 401/403, answers the 401
372
+ page that redirects (a `.guard()`, `getSelf({ unauthorize })`), or whose `fetch.*` a guard refuses with 401/403, answers the 401
366
373
  credential challenge when the call carried no token and `This screen is not available to the signed-in account.`
367
374
  when it did — the same sentence for both, so a refused id is never confirmed to exist; `router.notFound()` and a
368
375
  404 from a query are `No screen exists for these arguments.`; anything else the body throws is `The page failed to
369
376
  load.`, with the cause in the server log only. **The description is the only instruction.** `<Agent.Guide>` is for the in-page agent, whose
370
377
  levers are the screen's controls, and is never read here, where the levers are the API — so write the description
371
378
  in English, in the API's vocabulary, and put a computed rule (the legal status transitions) into it as a static
372
- table the model combines with the attached state. Names match `^[A-Za-z0-9_-]{1,64}$` and are unique across pages;
373
- two pages claiming one name fail the listing. An API-only build (`web: false`) publishes no prompts, and the
379
+ table the model combines with the attached state. Names match `^[A-Za-z0-9_-]{1,64}$` and share one namespace with
380
+ every page's `.app()`s; two pages claiming one name fail the listing. An API-only build (`web: false`) publishes no prompts, and the
374
381
  in-page chat lists none of them: its `/` menu is its six built-in commands. Pick which screens to publish by this
375
382
  rule: a page taking no arguments is the most useful prompt, since MCP has no completion — one taking an id is for
376
383
  when the id is already in hand.
377
384
 
378
- ## MCP Apps — The Page, Rendered In The Chat
379
- **A `.prompt()` page is also a tool**, of the same name and arguments, marked `readOnlyHint: false`, since running
380
- the page makes its own `fetch.*` calls, mutations included. Its result is the
381
- prompt's briefing plus `Open this screen in a browser: <url>` — what a client without the
382
- `io.modelcontextprotocol/ui` extension (Claude Code, Codex) reads. A host that declares the extension (claude.ai,
383
- Claude Desktop, ChatGPT, VS Code, Goose) is also given `_meta.ui.resourceUri` (`ui://<app>/app`, or
384
- `ui://<app>/app/<basePath>`) and renders the screen in place of the result: the app's CSR bundle, one HTML document,
385
- in a sandboxed iframe started on the page the tool ran. Its first queries are answered from that run — carried in
386
- the result's `_meta`, the one part no host shows the model — so the first paint costs no round trip; every later
387
- call is relayed by the host as `tools/call` under the host's token. Nothing is declared for any of it.
385
+ ## MCP Apps — One Component Of A Page, Drawn In The Chat
386
+ **`page().app(name, description, load)` publishes one component of a screen.** `load` takes the page's typed
387
+ arguments and `lang` and returns the element — usually a `Zone` fed by unawaited `fetch.*` fields — and on the web that
388
+ element reaches `.render()` as the argument named `name`, so the page draws it where it belongs:
388
389
 
390
+ ```tsx
391
+ export default page()
392
+ .param("ticketId", ID, { desc: "The ticket to show." })
393
+ .app("showTicket", "Show one ticket with its status and assignee.", ({ ticketId }) => {
394
+ const { ticketView } = fetch.viewTicket(ticketId);
395
+ return <Ticket.Zone.View view={ticketView} />;
396
+ })
397
+ .render(({ ticketId, showTicket }) => (
398
+ <div className="flex flex-col gap-4">
399
+ {showTicket}
400
+ <Ticket.Util.Close ticketId={ticketId} />
401
+ </div>
402
+ ));
403
+ ```
404
+
405
+ - **Each app is a read-only tool** of its name, whose arguments are the page's `.param()` (required) and `.search()`
406
+ (optional) stages, marked `readOnlyHint: true`. A call checks the arguments, runs the route's `.guard()`s, then the
407
+ app's `load` alone — no layout body, no `.render()` — and answers the briefing a prompt would give for what that load
408
+ fetched, plus `Open the full screen: <url>`: what a client without the `io.modelcontextprotocol/ui` extension
409
+ (Claude Code, Codex) reads. A refusal is a tool error with the prompt's sentences. Several apps may sit on one page;
410
+ names share one namespace with the prompts, and an endpoint keeps its name over an app's, with a boot warning.
411
+ - **`load` may only query.** A mutation, a file upload, a room subscription or a message sent while it runs throws
412
+ `base.error.mutationInApp` before anything is sent — on the server through every `await`, in a browser for its
413
+ synchronous part. Writes stay in `.render()` around the element (the `Close` above), and gating stays in
414
+ `.guard()`: a `getSelf({ unauthorize })` inside `load` would redirect a view.
415
+ - **A host that declares the extension** (claude.ai, Claude Desktop, ChatGPT, VS Code, Goose) is also given
416
+ `_meta.ui.resourceUri` (`ui://<app>/apps/<name>`) and draws the app's own view in place of the result: one HTML
417
+ document per app, which `akan build` writes to `mcp-apps/<name>.html` beside `csr/` and `akan start` writes to
418
+ `.akan/artifact/mcp-apps/` when a host first reads it. The view runs `load` again with the route values the result
419
+ names in `structuredContent`, and its first queries are answered from that call — carried in the result's `_meta`,
420
+ the one part no host shows the model — so the first paint costs no round trip; every later call is relayed by the
421
+ host as `tools/call` under the host's token.
422
+ - **The view is the component, not the page.** It bundles the page with `.render()`, `.head()`, `.loading()` and
423
+ `.guard()` blanked, so it carries what the loads reach and nothing else, and draws the element inside the
424
+ `_overrides.tsx` over the page and the root layout's `McpAppRoot` (`System.App`: its theme, fonts and providers, with
425
+ no frame, router or websocket). An `_overrides.tsx` the web draws outside the root layout (on its folder, or on one
426
+ above it with no layout of its own) wraps `McpAppRoot`, so the toasts and approvals it draws take it too. No layout
427
+ body runs there, so a layout's `<Agent.Guide>` never reaches the host; one inside the element does. A view never
428
+ moves: a link or `router.push` to one of the app's screens opens that screen's web page through the host (basePath
429
+ kept), a fragment of its own screen scrolls it, and `router.back()` / `router.refresh()` do nothing. A host loads one
430
+ file, so every `lazy(() => import(…))` the loads render is inlined; the view build marks a `const X = lazy(…)` pure,
431
+ so a barrel's, the page's own that only `.render()` drew, or an override manifest's that nothing renders is dropped,
432
+ while a `lazy()` called anywhere else stays.
389
433
  - **What a view may call** is every published tool, and every endpoint kept off the shelf by `mcp: false` alone or
390
434
  the generated `light<Model>` read, listed with `visibility: ["app"]` — which a host offers to the view and never to
391
435
  the model; a `Person` guard still refuses one. Visibility is a host's UX, not authorization: the guards decide, as
392
436
  everywhere. A client that did not declare the extension is listed neither those tools nor the `ui://` resources, a
393
- call to one answers `Unknown tool`, and a page tool's result carries none of the view's data for it.
437
+ call to one answers `Unknown tool`, and an app tool's result carries none of the view's data for it.
394
438
  - **The capability is read per request.** A legacy client declares it once at `initialize` and is issued an
395
439
  `Mcp-Session-Id` (`ui.<nonce>.<signature>`) that stores nothing: the app signs it, and an id the app did not sign is
396
440
  served as a client without views. With `modern: true` a modern request carries the capability in `_meta`. A client
397
441
  that declares nothing is issued no session, exactly as before.
398
- - **A read-only deployment has no MCP Apps.** With `readOnly` / `AKAN_MCP_READONLY` there are no page tools, app-only
399
- tools, views or UI sessions, since running a page makes its own `fetch.*` calls, mutations included.
400
- - **The view is the page, not the app around it.** Each layout above it still runs — guards, providers,
401
- `<Agent.Guide>` — but what it draws around `{children}` is hidden, with its frame chrome (`Layout.Navbar`,
402
- `TopInset`, `BottomInset`, `BottomTab`), the `topInset` / `bottomInset` it reserves and the tools its controls
403
- publish. A layout that draws no page, like a gate, is the screen then and is shown. The screen the view opened on
404
- has no back button: there is nothing behind it.
442
+ - **A read-only deployment keeps its apps.** With `readOnly` / `AKAN_MCP_READONLY` the app tools, their resources and
443
+ views stay, since a load may only query, and the result says so in `_meta`; the view refuses a write before it
444
+ reaches the host with `base.error.readOnlyDeployment`, toasted in the person's language. A `.prompt()` page's text
445
+ tool is dropped, since its run renders the whole page; the prompt stays.
446
+ - **`.prompt()` is a briefing, never a view.** Its page is also a text tool of the same name, marked
447
+ `readOnlyHint: false`, since running the page makes its own `fetch.*` calls, mutations included. To have a host draw
448
+ part of that screen, declare an `.app()` beside it.
405
449
  - **The view has no network.** `connect-src` stays closed; the app's own origin is opened for what a page loads by
406
450
  URL — fonts (served with `Access-Control-Allow-Origin: *`) and stored images — and every root-relative URL the
407
451
  page writes is pointed at it, since a host may block the document's `<base>` (Claude does).
408
- Cookies and Web Storage are in-memory, history is in-memory, and the websocket, live sync, pubsub, the reconnect
409
- overlay and `<Agent.Chat />` are off. A path link routes inside the view; any other link opens through the host.
452
+ Cookies and Web Storage are in-memory, and the websocket, live sync, pubsub, the reconnect overlay and
453
+ `<Agent.Chat />` are off.
410
454
  - **The view looks like the host.** Its neutrals (`--background`, `--foreground`, `--muted`, `--border`, `--ring`) and
411
455
  `--font-sans` / `--font-mono` follow the host's theme variables, its theme follows the host's, and so does its
412
456
  language when the app speaks it; the app's brand colors and radii stay its own.
413
- - **The host's model drives the screen too.** The view offers the host the screen's own tools — the surface
414
- `<Agent.Chat />` reads: `st.tool`, the form setters, `fill<Model>Form`, `navigate` / `readScreen` / `readState` /
415
- `highlight` — and, to a host that takes it, the screen's context (route, live state, `<Agent.Guide>`) through
457
+ - **The host's model drives the component too.** The view offers the host the tools the element publishes — the
458
+ surface `<Agent.Chat />` reads: `st.tool`, the form setters, `fill<Model>Form`, `readScreen` / `readState` /
459
+ `highlight` — and, to a host that takes it, the view's context (route, live state, `<Agent.Guide>`) through
416
460
  `ui/update-model-context` whenever it moves. A tool that declares `confirm` asks the person in the view through
417
461
  the `AgentApproval` slot, whatever the host asks on its own; a card tool, which a person answers in a chat, is not
418
462
  offered.
419
463
  - **A person tapping in the view acts with the agent's token**, so `isAgentCall` is true and a `Person` act is
420
464
  refused there. That act belongs on the web page the result links to. The view holds no token: it is handed the
421
- caller's claims, so `getSelf({ unauthorize })` in a layout renders the screen instead of a sign-in page, and each
422
- call it makes is relayed and judged by the guards.
465
+ caller's claims, and each call it makes is relayed and judged by the guards.
423
466
  - **A view's call answers what a browser would get**, in `_meta` beside the masked result: the value with its
424
467
  `visual` fields, or the domain `Err` with its key and data, toasted in the user's language. A refusal and a crash
425
- stay generalized.
426
- - **What a document load would do, the view does in place.** `router.refresh()` renders the route afresh, a
427
- download (`<a download>`, a data table's export) goes to a host that saves files, and a full navigation off the
428
- app shows a notice instead of a blank frame.
429
- - **A page named like an endpoint stays a prompt only**, published or not, and the boot log says so: the endpoint
430
- keeps its name. A refused screen answers as a tool error (`isError`), which the model reads.
431
- - `option.setMcp({ apps: false })` / `AKAN_MCP_APPS=false` keeps every page a prompt only. `web: { csr: false }`
432
- publishes the tool with no view, and an API-only build (`web: false`) has no pages to publish.
468
+ stay generalized. A load that throws, or a read that fails while the element draws, shows what the call would have
469
+ answered: `No screen exists for these arguments.` for a 404 (a record removed since the call), `This screen is not
470
+ available to the signed-in account.` for a 401 or 403, and `The page failed to load.` for anything else; a download
471
+ (`<a download>`, a data table's export) goes to a host that saves files.
472
+ - `option.setMcp({ apps: false })` / `AKAN_MCP_APPS=false` publishes no page tools: no app is published and every
473
+ prompt stays a prompt only. `web: { csr: false }` publishes the app tools with no view, and an API-only build
474
+ (`web: false`) has no pages to publish.
433
475
 
434
476
  ## Progress Reporting
435
477
  **`McpProgress.report(n, { total, message })`** reports progress from anywhere inside a call, a service or adapter
@@ -499,9 +541,9 @@ the same guards.** What stays closed is closed because no agent has a reason to
499
541
 
500
542
  ## Writing `instructions`
501
543
 
502
- `*.abstract.md` never reaches an MCP client, and `<Agent.Guide>` only through an MCP Apps view, beside the screen's own
503
- tools it explains. Exactly three texts reach every client: `instructions`, every published entry's `.desc()`, and a
504
- page's `.prompt()` description. All three are English, whatever the users speak
544
+ `*.abstract.md` never reaches an MCP client, and `<Agent.Guide>` only through an MCP App's view, from inside the app's
545
+ element, beside the tools it explains. Exactly these texts reach every client: `instructions`, every published entry's
546
+ `.desc()`, and a page's `.prompt()` and `.app()` descriptions. All are English, whatever the users speak
505
547
  — the reader is a model, and the catalogue is built once in one `language` and cached by clients.
506
548
 
507
549
  - **`instructions` is the workflow.** Five to eight sentences, in this order: what the app is and what its nouns
@@ -525,6 +567,9 @@ page's `.prompt()` description. All three are English, whatever the users speak
525
567
  report, an onboarding check. Its instruction is the `.prompt()` description alone and its attachments are what
526
568
  the screen fetched, masked by their return models — so to change what a prompt hands the model, change what the
527
569
  screen loads, and keep the description to the ask.
570
+ - **An app is a tool the model picks**, like a read endpoint: its description says what the component shows and for
571
+ which arguments (`Show one ticket with its status and assignee.`), and the model reads the briefing of what its load
572
+ fetched whether or not the host draws the view.
528
573
 
529
574
  ## Verifying An App
530
575
 
@@ -13,7 +13,8 @@ Generate persistence behavior for a collection-backed Akan module. This file tur
13
13
  ## Current Akan Patterns
14
14
  - Query names become generated helpers such as list, find, pick, exists, count, and insight variants.
15
15
  - Use filter args for required query inputs and optional args only when absence has a clear query meaning.
16
- - Use schema indexes for fields that are frequently filtered, sorted, uniquely constrained, or text searched.
16
+ - Use schema indexes for fields that are frequently filtered, sorted, or uniquely constrained; a `"text"` index builds
17
+ nothing, so give a searched field a `text` role (`field(String, { text: "title" })`) instead.
17
18
  - Use hooks for persistence lifecycle behavior that must always run with document saves.
18
19
 
19
20
  ## Codegen Rules
@@ -42,6 +42,13 @@ Generate client state coordination for a module. Store connects generated fetch
42
42
  - A model whose form holds a large `field.visual` body can pass the 256KB per-draft cap, and a draft over it is
43
43
  dropped with a warning rather than truncated.
44
44
 
45
+ ## File Uploads
46
+ - `upload<Field>On<Model>(fileList, idx?)` is generated for every `File` field. `Field.Img` / `Imgs` / `File` /
47
+ `Files` handed the generated `set<Field>On<Model>` upload through it, so do not write an upload action.
48
+ - `<model>FormUploading` holds the uploads in flight per field (`{}` when idle). The generated submit paths save
49
+ nothing until it is empty; a hand-written submit reads `Object.keys(st.use.<model>FormUploading()).length`. Full
50
+ contract: `fieldRule`.
51
+
45
52
  ## Review Checklist
46
53
  - The instruction points to current docs pages, not removed docs routes.
47
54
  - Generated examples use current Akan builder APIs and scanner-friendly filenames.
@@ -1,7 +1,7 @@
1
1
  # Page Rule — Route Files, The Route Chain, Heads, Lib Pages
2
2
 
3
- What a file under `page/` may be, how a route declares its arguments and settings, how heads merge, what a CSR
4
- bundle shows of a root layout, and how a lib's routes reach an app. `conventions` carries the invariants and the page
3
+ What a file under `page/` may be, how a route declares its arguments and settings, how a route guards itself, how
4
+ heads merge, what a CSR bundle shows of a root layout, and how a lib's routes reach an app. `conventions` carries the invariants and the page
5
5
  body shape — this is the full contract behind them. Before changing route behavior, check
6
6
  `pkgs/akanjs/server/routeTreeBuilder.ts` and nearby routes for the expected pattern.
7
7
 
@@ -25,15 +25,16 @@ body shape — this is the full contract behind them. Before changing route beha
25
25
 
26
26
  - **A route file exports one thing**: `export default page()…render(…)` for a page, `layout()…render(…)` for a
27
27
  `_layout.tsx`, `rootLayout()…render(…)` for the app's (or a basePath's) root `_layout.tsx`. Every route setting is
28
- a stage of the chain — `.param()`, `.search()`, `.config()`, `.head()`, `.loading()`; `.notFound()` / `.error()` on
29
- a layout; `.fonts()` / `.theme()` / `.manifest()` / `.reconnect()` / `.wsConnect()` / `.layoutStyle()` /
30
- `.viewport()` on the root layout; `.prompt()` on a page. A named export beside the chain, or `page()` in a
31
- `_layout.tsx`, fails the build.
28
+ a stage of the chain — `.param()`, `.search()`, `.config()`, `.guard()`, `.head()`, `.loading()`; `.notFound()` /
29
+ `.error()` on a layout; `.fonts()` / `.theme()` / `.manifest()` / `.reconnect()` / `.wsConnect()` /
30
+ `.layoutStyle()` / `.viewport()` on the root layout; `.prompt()` and `.app()` on a page. A named export beside the
31
+ chain, or `page()` in a `_layout.tsx`, fails the build.
32
32
  - **A page names every `[x]` segment of its path with `.param("x", Type)`** and reads a query key only through
33
33
  `.search("k", Type)`. Values arrive typed — `ID`/`String` → string, `Int`/`Float` → number, `Boolean`, `Date` →
34
34
  Dayjs, an `enumOf` class → its union, `[T]` → array — a path value the type refuses answers not-found, and a
35
35
  search value that fails is dropped. A layout may declare a subset. Names are string literals: `akan sync` reads
36
- them off the source and refuses a `[projectId]` folder whose page declares no `.param("projectId")`.
36
+ them off the source and refuses a `[projectId]` folder whose page declares no `.param("projectId")`, so the chain
37
+ is the `export default` expression itself — one bound to a variable first is refused.
37
38
  - **`lang` is never declared**: every route sits under `/:lang`, and the locale segment reaches every stage as
38
39
  `lang`.
39
40
  - **On a web page's first render `st.use.searchParams()` is still the server's empty snapshot**, synced right after
@@ -41,6 +42,52 @@ body shape — this is the full contract behind them. Before changing route beha
41
42
  - There is no `loader=` / `render=` page prop and no `PageProps` interface: the chain declares the arguments and
42
43
  `.render()` receives them flat, typed, with `lang` on every route and `children` added for a layout.
43
44
 
45
+ ## Route Guards — `.guard()`
46
+
47
+ - **`.guard(fn)` decides who may open a route before any of it renders.** Every chain takes it, once: a second
48
+ `.guard()` throws when the module loads. `fn` receives the route's typed arguments and `lang` (a layout's gets no
49
+ `children`) and may be `async`. It refuses by moving the router — `router.redirect(href)`, `router.notFound()` — or
50
+ with `getSelf({ unauthorize })`; `signedIn()` from `@libs/shared/webkit` is that last one, called inside an arrow
51
+ (`.guard(() => signedIn())`), because `.guard(signedIn)` would hand the route's arguments to `unauthorize`.
52
+ - **On the server every guard of the chain runs before any layout body starts**, root layout first and before the
53
+ route's arguments are checked, so a redirect is a real 307 even after an awaited query, and a not-found is a 404 —
54
+ where a `getSelf({ unauthorize })` inside a layout body after I/O redirects late, inside the stream. A query in a
55
+ guard that the server refuses with 403 or 404 (an owner check) answers not-found, so the page never confirms the
56
+ record exists. A refusal's not-found keeps only the layouts above the refusing guard, and a path no page matches
57
+ asks the guards of the layouts its not-found would sit under first.
58
+ - **On a client navigation a page's layers wait for its guards.** The verdict is kept by what the guards read (a
59
+ query only the page reads keeps it) and lasts while a layer of that location is on screen. Only the page in front
60
+ asks — never a parked one, nor the one under it during a swipe back; back in front, a cached page included, it asks
61
+ again in the background while what it drew stays, and a refusal moves the router and blanks it. A guard that moves
62
+ the router ends the chain and the page draws nothing; a refused or failed check runs again when its layer is
63
+ retried. Root layouts are drawn once for every page and are not gated
64
+ themselves; their guards still run in each page's chain, and a legacy page under them waits too. In a CSR bundle a
65
+ path no page matches draws the deepest `.notFound()` of the layouts it sits under, or a default page, once those
66
+ layouts' guards let it in, and `router.notFound()` moves to `/404`, drawn the same way. `guard` is a stage
67
+ only: a legacy module that exports one, a root layout's included, fails to load and fails `akan build`.
68
+ - **MCP runs them too**: a prompt or an app tool runs its route's guards before anything else, and `prompts/list` and
69
+ the page tools in `tools/list` show only the screens whose guards admit the caller (a listing knows no arguments,
70
+ so a guard that reads one admits there and is checked again on the call).
71
+ - **A route guard is not authorization for data.** It keeps a person off a screen and redirects early; every query
72
+ the screen makes is still judged by that endpoint's own `guards`. Write both: the signal guard is the gate, the
73
+ route guard is the courtesy that answers before the screen draws.
74
+
75
+ ## MCP Apps — `.app()`
76
+
77
+ - **`.app(name, description, load)` publishes one component of a page as an MCP App**: a read-only tool of that name,
78
+ whose arguments are the page's `.param()` and `.search()` stages, and a single-file view of its own. `load` receives
79
+ the page's typed arguments and `lang` and returns the element (usually a `Zone` fed by unawaited `fetch.*` fields);
80
+ on the web that element reaches `.render()` as the argument named `name`, so the page places it.
81
+ - A page may declare several. A name matches `^[A-Za-z0-9_-]{1,64}$`, is a string literal (the build reads it off the
82
+ source), shares one namespace with every page's prompts and apps, and needs an English description. A name
83
+ `.render()` already receives (`lang`, a `.param()` / `.search()` name, another app) fails to compile and throws when
84
+ the module loads, as does an app named like the page's `.prompt()`.
85
+ - **`load` may only query** (`base.error.mutationInApp` otherwise): keep writes in `.render()` around the element, and
86
+ gating in `.guard()`. The view runs `load` with no layout body and no `.render()`: it gets the root layout's theme,
87
+ fonts and framework providers through the generated `McpAppRoot` and the `_overrides.tsx` over the page (one the web
88
+ draws outside the root layout wraps `McpAppRoot`, its toasts included), and nothing a layout body provides. The
89
+ chain is the `export default` expression itself: one bound to a name fails the build. Full contract: `mcpRule`.
90
+
44
91
  ## Heads
45
92
 
46
93
  - **`.head()` takes JSX — `<title>`, `<meta>`, `<link>` — or a function of the route's args returning it.** One that
@@ -58,7 +105,7 @@ body shape — this is the full contract behind them. Before changing route beha
58
105
  second screen beside the frame. Its components still mount and their effects run (`<Auth.User />` works).
59
106
  - Anything a person must see from a root layout — an overlay, a gate, a banner — renders through
60
107
  `createPortal(…, document.body)`, as `<Agent.Chat />` and the dialogs already do. A non-root `_layout.tsx` has no
61
- such limit.
108
+ such limit. A gate belongs in the root layout's `.guard()`, which runs in every page's chain.
62
109
 
63
110
  ## Lib Pages — `syncPageLibs`
64
111
 
@@ -59,10 +59,10 @@ this is the full contract behind them.
59
59
  `Unknown document field path`. The facade's third argument is the scope (`{ withRemoved: true }`), never a field.
60
60
  This is the only way to read a `field.secret(...)` value, which is otherwise stripped.
61
61
  - **Hydrated vs raw:** server queries return hydrated `cnst.<Model>` instances (with `set`/`save`/`refresh`), and so do client fetch results — `FetchClient` parses every return with `crystalize` defaulting to **true** (`pkgs/akanjs/fetch/client/fetchClient.ts`). The raw `GetStateObject` shape (functions stripped, `pkgs/akanjs/base/types.ts`) is what the `<ref>Obj` / `<ref>ObjList` / `<ref>ObjInsight` handles carry, because those pass `crystalize: false` on purpose so the value can cross the RSC boundary as a client prop.
62
- - Every filter generates fourteen methods: `list` · `listIds` · `find` · `findId` · `pick` · `pickId` · `exists` ·
63
- `count` · `insight` · `query` · **`remove`** · **`removeOne`** · **`update`** · **`updateOne`**. The last four are
64
- query-level writes — one atomic UPDATE, **no hooks**, and therefore no `_postRemove` and no cascade. Use them on a
65
- model that carries no removal side effect; otherwise remove documents one at a time.
62
+ - Every filter generates fifteen methods: `list` · `listIds` · `find` · `findId` · `pick` · `pickId` · `exists` ·
63
+ `count` · `insight` · `query` · **`remove`** · **`removeOne`** · **`purge`** · **`update`** · **`updateOne`**. The
64
+ last five are query-level writes — one atomic UPDATE, a DELETE for `purge` — with **no hooks**, so no `_postRemove`
65
+ and no cascade. Use them on a model that carries no removal side effect; otherwise remove documents one at a time.
66
66
  - **`update<Filter>` / `updateOne<Filter>` are chains, not calls:** `await updateInRoot(rootId).set({ status:
67
67
  "archived" })`. The patch cannot trail the filter args — a filter's own args may be optional and no tuple type
68
68
  puts a required element after those — so it lands on a terminal `.set()`, mirroring the `UPDATE … SET …` it
@@ -88,14 +88,24 @@ this is the full contract behind them.
88
88
 
89
89
  ## Soft Removal And The Facade's Writes
90
90
 
91
- - **Removal is always soft** — the framework has no hard delete for a model table, and `delete` is deliberately
92
- left unused so it can mean one later. Every read and query-level write sees live rows only (`removedAt IS NULL`).
91
+ - **Removal is soft** — every remove stamps `removedAt`, and every read and every query-level write but `purge` sees
92
+ live rows only (`removedAt IS NULL`).
93
+ - **`purge<Filter>(...)` / `purgeMany(query)` is the one hard delete**, for data you mean to lose, such as logs past
94
+ their retention. It deletes every row the query matches, removed rows too (`{ removedAt: q.lt(cutoff) }` clears old
95
+ removals), and returns the count. The search mirror's rows go with each row, and it runs no hook, cascade or live
96
+ event and has no undo. It deletes 1,000 rows per statement and refuses `q.search()` and a query empty in shape —
97
+ `{}` (a fallen-through `q.when` builds one), a `q.all()` of only those or nothing, a `q.any()` holding one or
98
+ nothing — but not a condition that happens to match every row: `{ id: q.notOneOf([]) }` deletes them all.
93
99
  - **`{ withRemoved: true }` reaches removed rows**: the third argument of `find` / `findOne` / `findById`
94
100
  (projection second, `null` when none), the last of `count` / `exists` / `updateMany`, or inside `updateOne` /
95
101
  `updateById`'s options. Without it, a `removedAt` condition only a removed row can meet (`q.exists("removedAt")`,
96
102
  a comparison) throws `can never match`.
97
103
  - Removes, slices, filter methods, loaders and `pickById` stay live-only, a removed document is read-only
98
104
  (`save()` throws), and `updateById(id, { removedAt: null }, { withRemoved: true })` revives one without hooks.
105
+ - **A `pick` that finds no live row throws `NoDocumentError`**, so the generated `get<Model>` of a missing or
106
+ removed id answers an HTTP or websocket caller 404 `base.error.documentNotFound`, and an agent `No <model> found
107
+ for the arguments given.` The message, which names the table and the id or query, stays on the server. Throw
108
+ your own `Err.NotFound` only where a nullable load decides that nothing found is an error.
99
109
  - The facade spells `Many`/`One` out on its writes (`updateOne` / `updateMany` / `removeOne` / `removeMany`); only
100
110
  the count was shortened to `count(query)`, with `countDocuments` kept as `@deprecated`.
101
111
  - **`updateById(id, update)` and `removeById(id)` are those same query-level writes narrowed to one id, not the
@@ -217,7 +227,9 @@ shape, so `cascade` never means "related" — it means one of exactly these:
217
227
  and an unmounted `removeRef` target or `removeWith` owner fails the boot rather than the first removal. An
218
228
  unmounted `refPath` candidate only warns, since that list spans optional modules by design.
219
229
  - **Nothing checks whether another document still references the same target.** `File` in particular is deduped
220
- by `origin`, so two parents can share one row; `removeRef` claims the field owns its target exclusively.
230
+ by `origin`, so two parents can share one row; `removeRef` claims the field owns its target exclusively. Removing
231
+ the first parent removes the shared row; the second parent's cascade later skips it, since a live-row lookup per
232
+ edge (200 ids at a time) drops a target that is already gone, and still runs the rest of its edges.
221
233
  - **A reference no cascade removes keeps pointing at the removed row, and a response reads it live-only**: a list
222
234
  leaves the target out, an optional field reads `null`, and a required one answers 404
223
235
  `base.error.relationNotFound` naming the model and the field path. Make a reference whose target can go first
@@ -230,7 +242,9 @@ shape, so `cascade` never means "related" — it means one of exactly these:
230
242
  generated `remove<Filter>` / `update<Filter>`, and the facade's `removeById` / `updateById`. Remove one document
231
243
  at a time when it cascades.
232
244
  - Cascades are **idempotent**: `removedAt IS NULL` is ANDed into every query-level write, and a remove never takes
233
- `{ withRemoved: true }`, so an already-removed row keeps its original `removedAt`. Cycles are cut by a visited set
234
- carried down the whole chain, with a depth cap of 16. `q.search()` cannot see removed rows (the mirror drops
235
- them), so search with the flag throws, as does `upsert` with it.
245
+ `{ withRemoved: true }`, so an already-removed row keeps its original `removedAt`. Every document a cascade
246
+ removes one at a time joins a visited set carried down the whole chain (a bulk target never does), so a target held
247
+ by two `removeRef` fields (or twice in one array) is removed once and cycles are cut; the depth cap is 16.
248
+ `q.search()` cannot see removed rows (the mirror drops them), so search with the flag throws, as does `upsert` with
249
+ it.
236
250
 
@@ -228,7 +228,7 @@ assembles one from. There is no `content` field; the string *is* the content.
228
228
  const config: AppConfig = {
229
229
  docker: { preRuns: ["apt-get update && apt-get install -y --no-install-recommends ffmpeg"] },
230
230
  };
231
- const config: AppConfig = { docker: "FROM oven/bun:1-slim\n…" }; // verbatim, nothing merged in
231
+ const config: AppConfig = { docker: "FROM oven/bun:1.4.4-slim\n…" }; // verbatim, nothing merged in
232
232
  ```
233
233
 
234
234
  - `image` and each run entry take `string | { amd64?, arm64? }`; the object form compiles to a
@@ -585,6 +585,8 @@ serving without a key. Everything else is behind the ops channel.
585
585
  | `GET /_akan/ops/info` | the public info plus `akanVersion`, `buildId`, `serverMode`, `databaseMode`, `solo`, `startedAt`, `replicaIdx` |
586
586
  | `POST /_akan/ops/snapshot` `{ id, includeSolid?, uploadUrls: { main, solid?, manifest } }` | 202; a child process snapshots, then PUTs each file and the manifest **last** |
587
587
  | `GET /_akan/ops/snapshot/:id` | `running` → `uploading` → `done` \| `failed`; kept in memory, so a restart answers 404 |
588
+ | `POST /_akan/ops/migrate` `{ id, action, target?, params?, expect?, items? }` | 202; a child runs `ops migrate <action> … --json` for the token's `sub` |
589
+ | `GET /_akan/ops/migrate/:id` | `running` → `done` (`exitCode`, and `result`: the line `--json` printed last) \| `failed` (it printed none) |
588
590
 
589
591
  - **The entry is the image's own `main.js`** — a production image carries no `akan` CLI. `AkanApp.start()` hands
590
592
  `argv[2] === "ops"` to the command before it boots anything. It reads the container's env — the `AKAN_PUBLIC_*`
@@ -593,10 +595,15 @@ serving without a key. Everything else is behind the ops channel.
593
595
  `--force` is for a port some other app holds.
594
596
  - **The channel exists only when `AKAN_OPS_PUBLIC_KEY` is set** (Ed25519: PEM, JWK, base64 SPKI or raw 32 bytes).
595
597
  The control plane signs a short EdDSA JWS — `aud`, `iat`, `exp` at most 300s after `iat`, a `jti` the process
596
- refuses twice — and the host holds only the public half, so a machine someone carries off mints nothing.
598
+ refuses twice, and optionally `sub`, whom it acts for — and the host holds only the public half, so a machine
599
+ someone carries off mints nothing.
597
600
  `aud` is `<appName>/<environment>`, or `<appName>/<environment>/<AKAN_OPS_INSTANCE>` when that is set, and then
598
601
  only that: a token minted for the app as a whole would replay across every host sharing the name. 30 calls a
599
602
  minute per process; every refusal is the same 401. A malformed key leaves the app serving with the channel off.
603
+ - **A migrate job runs for the token's `sub`**, which the run records as its actor: apply and rollback refuse a
604
+ token without one, and a body naming `actor` is refused. Each option reaches the command as `--name=value`. One
605
+ job runs at a time per process (409 meanwhile); the run's own lease keeps two hosts on one database apart. Jobs
606
+ live in memory, so after a restart read the outcome from `list`. Polls count toward the 30 a minute.
600
607
  - **The app holds no storage credential.** It PUTs to the presigned URLs it was handed (`application/octet-stream`,
601
608
  the manifest `application/json`), plain http only to loopback. The manifest landing is the commit marker.
602
609
  - **Snapshots cover the SQLite modes only.** `single` copies the main file and, with `includeSolid`, the Solid file;
@@ -611,8 +618,9 @@ serving without a key. Everything else is behind the ops channel.
611
618
  - **`buildId` is `AKAN_BUILD_ID` when the deployment sets it**, else the git sha `akan build` wrote into
612
619
  `akan.build.json` beside `main.js` (`-dirty` when the tree was).
613
620
  - **`operationMode` does not gate any of this** — the key does. `edge` means a production host outside the
614
- cluster: the console refuses it like `cloud`, and `init` / `interval` / `cron` take `operationMode: ["edge"]` to
615
- run only there. Everything else behaves as `cloud`; `local` is a developer machine.
621
+ cluster: the console refuses it like `cloud`, `/mcp` starts off unless `AKAN_MCP=true` or `setMcp(true)`, and
622
+ `operationMode: ["edge"]` on a `serve()` (the whole module, endpoints included) or an `init` / `interval` / `cron`
623
+ runs it only there; `local` is a developer machine.
616
624
 
617
625
  ## Shipped Assets — `assets` In `akan.config.ts`
618
626
 
@@ -141,10 +141,11 @@ eight queries threw; per-section boundaries put each rejection at its own bounda
141
141
  **Know which redirects are real.** A streaming response starts while layout and page bodies still run, so a redirect
142
142
  is a real 3xx only when it was raised before any I/O was awaited, the body's own or a layout's above it (a layout that
143
143
  awaits `fetch.viewOrg` makes every page under it late); after one — `getSelf({ unauthorize: "/signin" })` fetches —
144
- it reaches the browser as an HTTP 200 that navigates in the page, which a crawler or `curl` does not
145
- follow. Either way no markup below the redirect is sent. A route that must answer a real 3xx after I/O — a gate an
146
- external client hits, a moved URL — takes `.config({ ssr: "block" })`: the response waits for the whole render.
147
- Never redirect from inside a streamed section.
144
+ a browser gets an HTTP 200 that navigates in the page, which `curl` does not follow, while a crawler, whose response
145
+ waits for the whole render, gets the real 3xx. Either way no markup below the redirect is sent. A route's `.guard()`
146
+ runs before any layout body starts, so a redirect from it is a real 3xx even after the guard's own awaited query:
147
+ gate there. A route that must answer a real 3xx from its body after I/O — a moved URL found by a query — takes
148
+ `.config({ ssr: "block" })`: the response waits for the whole render. Never redirect from inside a streamed section.
148
149
 
149
150
  **⑥ Use named `ReactNode` slots, not just `children`.** A client shell that takes one slot per region lets a
150
151
  server component supply each of them, instead of absorbing the whole subtree into the bundle. `Layout.Navbar`
@@ -154,8 +155,10 @@ is the shape: `title` / `left` / `right` beside `back` and `children`, each fill
154
155
  `canWrite(user?)`, `formatTimes()`), and enum→class lookups belong in a module-scope `as const` map. Both sides call
155
156
  the same method, so a client component that exists only to compute a label is markup in the wrong place.
156
157
 
157
- **⑧ Gate auth on the server.** `getSelf({ unauthorize: "/signin" })` in `_layout.tsx` redirects before any of the
158
- page's markup is rendered. A client-side check costs a hydration round-trip and flashes the wrong UI first.
158
+ **⑧ Gate auth on the server.** `.guard(() => signedIn())` (`@libs/shared/webkit`, which a new workspace has only
159
+ with `create-workspace --libs true`) on `_layout.tsx` runs before any of the route renders, so the redirect is a
160
+ real 3xx; `getSelf({ unauthorize: "/signin" })` in a layout body still redirects before any of the page's markup,
161
+ in-page after I/O. A client-side check costs a hydration round-trip and flashes the wrong UI first.
159
162
 
160
163
  **⑨ Prefer CSS over client state for pure visibility.** A `data-*` attribute plus `group-data-[…]` variants (see
161
164
  `libs/util/ui/Grid/*`) or `<details>`/`<summary>` keeps both branches server-rendered. Reach for `useState` when the
@@ -130,6 +130,37 @@ HTTP verb a mutation is mounted under. `conventions` carries the invariants —
130
130
  the declared model, not the service's document: a method only the document has is not there on a hit, and a return
131
131
  declared as a `Light` model shows `resolveField` its light fields only. The entry still holds `hidden` and `secret`
132
132
  values for its TTL, as the handler returned them.
133
+ - **A write drops the answers it made stale.** Plug the adaptor into the service and call it after the write:
134
+
135
+ ```ts
136
+ export class BannerService extends serve(db.banner, ({ plug }) => ({
137
+ endpointCache: plug(EndpointCacheControl),
138
+ })) {
139
+ override async _postUpdate(banner: db.Banner) {
140
+ await this.endpointCache.invalidate("bannerListInPublic");
141
+ await this.endpointCache.invalidate("bannerInsightInPublic");
142
+ return banner;
143
+ }
144
+ }
145
+ ```
146
+
147
+ `invalidate(endpoint)` drops every cached answer of that endpoint, across instances. A slice's `init({ cache })`
148
+ caches its `<model>Insight<Slice>` as well as its list, so drop both or the count stays stale.
149
+ `invalidate(endpoint, args)` drops the one call with those arguments: pass every declared argument in order as the
150
+ endpoint receives it, `null` for an omitted search argument (search arguments are nullable, so an omitted one is
151
+ stored as `null`). A slice list also carries `skip` / `limit` / `sort`, so drop it with the endpoint-wide form.
152
+ A mismatched list misses silently and still answers `true`.
153
+ - **How it is keyed:** every entry key carries its endpoint's generation, a random token the endpoint-wide form
154
+ replaces in one write. Nothing is scanned, and a miss already running when you invalidate writes under the old
155
+ token, where nobody reads it. A token is never reused, so a generation that expires (after a day) or is evicted
156
+ starts a fresh one instead of reviving dropped answers, and an endpoint name nothing serves leaves no key behind for
157
+ good. **A `{ cache }` TTL is capped at one day**, the generation's life: an entry outliving its token could never be
158
+ read, so a longer TTL is written as a day. Entries under an old token stay in the cache until their own TTL, and a
159
+ Redis that BullMQ shares has to run `noeviction`, so nothing frees them early: give an endpoint you invalidate often
160
+ a short TTL. The one-call form
161
+ deletes that entry, so a miss for those arguments already running can write it back; reach for the endpoint-wide
162
+ form when that matters. It answers `false` (logged as an error) when the cache failed. A cached call reads the
163
+ generation before its entry.
133
164
  - **A cache backend that is down does not take the endpoint down.** A failed read is warned and the call runs
134
165
  uncached; a failed write is warned and dropped.
135
166
  - A call runs the cross-site check and an `ip` rate limit, then the body read, then the default middleware chain
@@ -195,11 +226,11 @@ HTTP verb a mutation is mounted under. `conventions` carries the invariants —
195
226
  nobody to close it. It never carries the visitor's session either: a call to another origin sends only the `jwt`
196
227
  its caller gave the clone.
197
228
  - **Retry a call with `retry`, never with a loop of your own.** `fetch.clone({ origin, retry: {} })` (or a call's
198
- own `{ retry }`) tries again on an unreachable server, a 502/503/504 and a 429 after its Retry-After, backing off
199
- with jitter until the call's one deadline runs out. A mutation retries under one `Idempotency-Key` it mints, or
200
- the `idempotencyKey` you name, and the server runs it once per key, caller and arguments (Repeated Mutations
201
- above); a signed-out call, one whose handler returns a `Response`, and a call through MCP run every time. A 4xx
202
- is never retried.
229
+ own `{ retry }`) tries again on an unreachable server, a 408/502/503/504, a 429 after its Retry-After and a 409
230
+ `idempotencyInFlight`, backing off with jitter until the call's one deadline runs out. A mutation retries under
231
+ one `Idempotency-Key` it mints, or the `idempotencyKey` you name, and the server runs it once per key, caller and
232
+ arguments (Repeated Mutations above); a signed-out call, one whose handler returns a `Response`, and a call
233
+ through MCP run every time. No other error is retried.
203
234
  - **A failure another process reported travels as itself.** A server-to-server `fetch.<endpoint>(..., { origin })`
204
235
  restores the remote `Err` — the same class, key and `data` — so a hop that rethrows it answers its own caller
205
236
  with that error and the dictionary translates it. Never wrap the catch in a `new Error`, and never re-key it as a
@@ -127,7 +127,7 @@ akan start-ios <%= appName %> # Run it in a simulator or o
127
127
  akan build-desktop <%= appName %> # Build it for this computer into dist/native/<%= appName %>/<target>/build
128
128
  akan build-desktop <%= appName %> --installer true # Windows: add a per-user setup program
129
129
  akan update-keygen <%= appName %> # Make the update signing key once; print its public key
130
- akan publish-update <%= appName %> # Build and sign a desktop release to upload to updates.url
130
+ akan publish-update <%= appName %> # Build a key-signed release for updates.url; --sign true also code-signs it
131
131
  ```
132
132
 
133
133
  ### The Essential Loop: Workflow -> Sync -> Check
@@ -283,6 +283,8 @@ core framework. The core framework gives you the composition points below; wire
283
283
  - **Auto-generated CRUD and `serve()` service methods / lifecycle hooks do not receive session context.** If an
284
284
  operation needs the acting user, expose a custom endpoint that takes it via `.with(CurrentUserId)` — never trust a
285
285
  client-supplied user id.
286
- - **SSR auth-gated pages: guard at the layout.** Check the session inside the `_layout.tsx` chain's `.render()` and
287
- redirect when it is absent, so nested pages never render for signed-out users.
286
+ - **SSR auth-gated pages: guard at the layout.** `.guard(() => signedIn())` on the `_layout.tsx` chain answers a
287
+ real 307 before any of it renders, so nested pages never render for signed-out users; a check in `.render()`
288
+ after awaited I/O redirects in-page, as an HTTP 200. `signedIn()` comes from `@libs/shared/webkit`, which a new
289
+ workspace has only with `create-workspace --libs true`.
288
290