@akanjs/cli 3.0.0-alpha.70 → 3.0.0-alpha.71

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 (55) hide show
  1. package/.build-stamp +1 -1
  2. package/{agent.command-964bf8qg.js → agent.command-xdvw642m.js} +5 -5
  3. package/{application.command-n45n18sc.js → application.command-g3f7xj25.js} +27 -4
  4. package/buildBatch.proc.js +1 -1
  5. package/{capacitorApp-vnvnvdhf.js → capacitorApp-b0ppke3m.js} +2 -2
  6. package/{cloud.command-kx1bh5yq.js → cloud.command-0hmsv44q.js} +7 -7
  7. package/commandManifest.json +1 -1
  8. package/{context.command-g1a65x6j.js → context.command-x92afrnf.js} +12 -12
  9. package/{guideline.command-xphyhvwh.js → guideline.command-hpq08q66.js} +2 -2
  10. package/guidelines/conventions/conventions.instruction.md +255 -436
  11. package/guidelines/framework/framework.generate.json +3 -2
  12. package/guidelines/framework/framework.instruction.md +0 -9
  13. package/guidelines/mcpRule/mcpRule.instruction.md +5 -8
  14. package/guidelines/queryRule/queryRule.generate.json +31 -0
  15. package/guidelines/queryRule/queryRule.instruction.md +143 -0
  16. package/guidelines/runtimeRule/runtimeRule.generate.json +25 -0
  17. package/guidelines/runtimeRule/runtimeRule.instruction.md +176 -0
  18. package/guidelines/transportRule/transportRule.generate.json +31 -0
  19. package/guidelines/transportRule/transportRule.instruction.md +60 -0
  20. package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +17 -392
  21. package/guidelines/workspaceRecipes/workspaceRecipes.generate.json +33 -0
  22. package/guidelines/workspaceRecipes/workspaceRecipes.instruction.md +402 -0
  23. package/incrementalBuilder.proc.js +1 -1
  24. package/{index-nkwmnqwn.js → index-5f4gnt4c.js} +1 -0
  25. package/{index-va15r8h5.js → index-6d5r8q6k.js} +2 -2
  26. package/{index-4rw4qhe6.js → index-737aj4fm.js} +3 -3
  27. package/{index-ytaqtc04.js → index-8besc14m.js} +1 -1
  28. package/{index-hee7egtm.js → index-cbfp5wyp.js} +1 -1
  29. package/{index-mkn5qagt.js → index-cp00yns2.js} +70 -4
  30. package/{index-nj3w0r34.js → index-ety6takb.js} +3 -3
  31. package/{index-e31ghfp5.js → index-gvq17wqn.js} +1 -1
  32. package/{index-8gybxemv.js → index-hs70d8ed.js} +5 -5
  33. package/{index-0ngvvgry.js → index-jybbmwed.js} +2 -2
  34. package/{index-bqqts262.js → index-m5gfc86a.js} +1 -1
  35. package/{index-qt4nfr0n.js → index-nq3avsf6.js} +10 -10
  36. package/{index-yg3hxk2k.js → index-p27h7535.js} +4 -4
  37. package/{index-fahkq20v.js → index-pehn44hr.js} +3 -3
  38. package/{index-v5fdxdre.js → index-r691v756.js} +2 -2
  39. package/{index-p681w089.js → index-sqsfv8wg.js} +2 -2
  40. package/{index-rbnpe8cp.js → index-wbbswwqt.js} +17 -21
  41. package/{index-rb65xnw9.js → index-wybbcgxn.js} +4 -4
  42. package/index.js +18 -18
  43. package/{library.command-rfpd27yv.js → library.command-8vgrdtwy.js} +3 -3
  44. package/{localRegistry.command-pyxfe0fs.js → localRegistry.command-0gtqj0r0.js} +6 -6
  45. package/{module.command-qhaxad0p.js → module.command-rama4zya.js} +5 -5
  46. package/{package.command-2k22q9nt.js → package.command-6jxapdsg.js} +3 -3
  47. package/package.json +2 -2
  48. package/{page.command-ymk9dqh4.js → page.command-hxy7x525.js} +3 -3
  49. package/{primitive.command-9k45zpc1.js → primitive.command-4bf6xcc3.js} +6 -6
  50. package/{quality.command-bf6vkxe5.js → quality.command-h5edwegz.js} +2 -2
  51. package/{repair.command-egvvm6xf.js → repair.command-rgqf6px6.js} +5 -5
  52. package/{scalar.command-bt1facyj.js → scalar.command-6krkz6tw.js} +4 -4
  53. package/templates/workspaceRoot/AGENTS.md.template +4 -0
  54. package/{workflow.command-v1n3wg7v.js → workflow.command-dwhwrqhd.js} +9 -9
  55. package/{workspace.command-yvvqvhzz.js → workspace.command-f5h11gjn.js} +18 -18
@@ -0,0 +1,402 @@
1
+ # Workspace Recipes — Worked Examples And The Auto-Generated API
2
+
3
+ Step-by-step recipes for the most frequent Akan.js changes, and the reference of what `akan sync` generates for
4
+ you at each layer. `workspaceOnboarding` carries the index and the rules; this is the worked code behind them.
5
+ Read the whole recipe before editing, and change only the sections it names — do not rewrite a file.
6
+
7
+ ## Workflow Recipes
8
+
9
+ Concrete step-by-step recipes for the most frequent Akan.js changes. Each recipe shows which files to edit
10
+ and in what order. The code examples reference the `task` module in `apps/<app>/lib/task/` as a
11
+ template; replace `task` with your model name and `Task` with your PascalCase model name.
12
+
13
+ When editing a file, always read the existing content first. Only change the relevant sections — do not
14
+ rewrite the entire file.
15
+
16
+ ---
17
+
18
+ ### Recipe 1: Adding a New Field to a Model
19
+
20
+ **Files to edit (in order):** `constant.ts` → `dictionary.ts` → `Template.tsx` → `Unit.tsx` → `akan sync`
21
+
22
+ ```typescript
23
+ // 1. apps/<app>/lib/<model>/<model>.constant.ts
24
+ // Add field to the Input class. Use field() builder with optional defaults
25
+ export class TaskInput extends via((field) => ({
26
+ title: field(String),
27
+ priority: field(TaskPriority, { default: "medium" }), // NEW FIELD
28
+ })) {}
29
+
30
+ // If the new field should appear in list views, also add it to LightTask:
31
+ export class LightTask extends via(TaskObject, ["title", "priority", "status", "due"] as const, () => ({})) {}
32
+
33
+ // 2. apps/<app>/lib/<model>/<model>.dictionary.ts
34
+ // Add i18n labels for the new field (and its enum values if any).
35
+ // Labels are [en, ko] pairs, and nearly every one also carries a .desc([en, ko]).
36
+ .model<Task>((t) => ({
37
+ priority: t(["Priority", "우선순위"]).desc(["How urgent the task is", "할 일의 긴급도"]),
38
+ }))
39
+ .enum<TaskPriority>("taskPriority", (t) => ({
40
+ low: t(["Low", "낮음"]),
41
+ medium: t(["Medium", "보통"]),
42
+ high: t(["High", "높음"]),
43
+ }))
44
+
45
+ // 3. apps/<app>/lib/<model>/<Model>.Template.tsx
46
+ // Add a form field using st.do.setXxxOnYyy (auto-generated setter)
47
+ const form = st.use.taskForm();
48
+ <Field.ToggleSelect
49
+ label={l("task.priority")}
50
+ items={cnst.TaskPriority}
51
+ value={form.priority}
52
+ onChange={st.do.setPriorityOnTask}
53
+ />
54
+
55
+ // 4. apps/<app>/lib/<model>/<Model>.Unit.tsx
56
+ // Display the new field in card/list views
57
+ <Badge variant={task.priority === "high" ? "error" : task.priority === "medium" ? "warning" : "default"}>
58
+ {task.priority}
59
+ </Badge>
60
+
61
+ // 5. Regenerate barrels
62
+ // akan sync <name>
63
+ ```
64
+
65
+ ---
66
+
67
+ ### Recipe 2: Injecting a Dependency into a Service
68
+
69
+ Three patterns: injecting an **external adapter** (`use<>()`), another **module's service** (`service<>()`),
70
+ or a **predefined framework adapter** (`plug()`). A field named `<refName>Service` resolves to the service
71
+ registered under `<refName>` — the `Service`/`Signal` suffix is required and stripped to derive the lookup key.
72
+
73
+ > **For a new adapter you own, prefer the `adapt()` shape in pattern C over the `option.ts` registration in
74
+ > pattern A.** An `adapt()` class self-registers and is injected with `plug(TheClass)`, so it never touches
75
+ > `option.ts`. Pattern A is the legacy constructor-style shape: recognise it, keep it working, and migrate one
76
+ > only when you are already changing it.
77
+
78
+ > `apps/<app>/lib/option.ts` is a **user-owned** file scaffolded once — edit it to register adapters/DI. Unlike the
79
+ > barrels (`cnst.ts`, `db.ts`, `srv.ts`, …) it is **not** overwritten by `akan sync`, so your `.use(...)` registrations
80
+ > are safe.
81
+
82
+ **A. Adapter injection via `use<>()` (for external clients / global singletons)**
83
+
84
+ ```typescript
85
+ // 1. Create the adapter class in apps/<app>/srvkit/
86
+ // apps/<app>/srvkit/EmailClient.ts
87
+ export class EmailClient {
88
+ constructor(readonly apiKey: string) {}
89
+ async send(opts: { to: string; subject: string; body: string }) { /* ... */ }
90
+ }
91
+
92
+ // 2. Register in apps/<app>/lib/option.ts
93
+ export const option = new AkanOption()
94
+ .use((options) => ({
95
+ emailClient: new EmailClient(options.mailerApiKey),
96
+ }));
97
+
98
+ // 3. Inject via use<>() in <model>.service.ts
99
+ export class TaskService extends serve(db.task, ({ use }) => ({
100
+ emailClient: use<EmailClient>(),
101
+ })) {
102
+ async _postCreate(task: cnst.Task) {
103
+ await this.emailClient.send({ to: "...", subject: "Task Created", body: `Task "${task.title}" created.` });
104
+ }
105
+ }
106
+ ```
107
+
108
+ **B. Cross-module service injection via `service<>()` (for other Akan services)**
109
+
110
+ ```typescript
111
+ // In <model>.service.ts — inject another module's service
112
+ import * as srv from "../srv";
113
+
114
+ export class TaskService extends serve(db.task, ({ service }) => ({
115
+ notiService: service<srv.NotiService>(),
116
+ })) {
117
+ async _postCreate(task: cnst.Task) {
118
+ await this.notiService.send("info", `Task "${task.title}" created`);
119
+ }
120
+ }
121
+ ```
122
+
123
+ **C. Predefined framework adapter injection via `plug()` (storage, cache, queue, schedule, …)**
124
+
125
+ Akan ships predefined adapter roles from `akanjs/service`: `StorageAdaptorRole`, `CacheAdaptorRole`,
126
+ `QueueAdaptorRole`, `ScheduleAdaptorRole`, `DatabaseAdaptorRole`, `WebsocketAdaptorRole`,
127
+ `LoggingAdaptorRole`, `CompressAdaptorRole`. `plug()` injects the concrete adapter bound to that role (the
128
+ default `StorageAdaptor` binding is `BlobStorage`). `plug()` also accepts a concrete adapter class directly.
129
+
130
+ ```typescript
131
+ // In <model>.service.ts — inject the framework storage adapter by role
132
+ import { plug, serve, StorageAdaptorRole } from "akanjs/service";
133
+
134
+ export class TaskService extends serve(db.task, ({ plug }) => ({
135
+ storage: plug(StorageAdaptorRole),
136
+ })) {
137
+ async attach(taskId: string, path: string, localPath: string) {
138
+ // BlobStorage returns a URL under blobStorage.urlPrefix (default "/api/localFile/getBlob").
139
+ return await this.storage.uploadDataFromLocal({ path, localPath });
140
+ }
141
+ }
142
+ ```
143
+
144
+ For a custom adapter class (not a predefined role), pass the class itself, e.g. `ipfsApi: plug(IpfsApi)`.
145
+ Injecting a file/image field is usually simpler than calling
146
+ storage directly: declare `image: field(File).optional()` (or `images: field([File])`) on the model and let the
147
+ store's generated `upload<Field>On<Model>(fileList)` action handle the upload. Add `{ cascade: "removeRef" }` to that
148
+ field when the file belongs to the model alone, and removing the model removes the file and its stored object.
149
+
150
+ ---
151
+
152
+ ### Recipe 3: Creating and Using a Slice
153
+
154
+ A Slice is a named, filtered data view. Add file entries and connect from a page.
155
+
156
+ > **Silent failure — a slice `exec` must return a query descriptor, never an executed list.**
157
+ > Return `this.taskService.queryByStatuses(...)` (the `query<Filter>` builder), **not**
158
+ > `this.taskService.listByStatuses(...)` / `listBy...(...)` (which returns a `Promise<Doc[]>`).
159
+ > Returning an array type-checks but throws at runtime during insight aggregation with the opaque
160
+ > `Error: Unknown document field path: 0`. If you see that error, your slice is returning a list, not a query.
161
+
162
+ ```typescript
163
+ // 1. apps/<app>/lib/<model>/<model>.signal.ts — Define the slice
164
+ export class TaskSlice extends slice(srv.task, { guards: { root: Admin, get: SignedIn, cru: SignedIn } }, (init) => ({
165
+ inTodo: init({ guards: [SignedIn] })
166
+ .search("statuses", [cnst.TaskStatus])
167
+ .exec(function (statuses?) {
168
+ // ✅ query<Filter> — a query descriptor. ❌ listByStatuses(...) returns an array and fails at runtime.
169
+ return this.taskService.queryByStatuses(statuses ?? ["todo", "inProgress"]);
170
+ }),
171
+ })) {}
172
+
173
+ // 2. apps/<app>/lib/<model>/<model>.document.ts — Add query filter for slice
174
+ export class TaskFilter extends from(cnst.Task, (filter) => ({
175
+ query: {
176
+ byStatuses: filter()
177
+ .arg("statuses", [cnst.TaskStatus])
178
+ .query((statuses) => ({ status: { $in: statuses } })),
179
+ },
180
+ })) {}
181
+
182
+ // 3. apps/<app>/lib/<model>/<model>.dictionary.ts — Slice labels
183
+ .slice<TaskSlice>((fn) => ({
184
+ inTodo: fn(["Tasks In Todo", "할 일"]).arg((t) => ({
185
+ statuses: t(["Statuses", "상태"]),
186
+ })),
187
+ }))
188
+
189
+ // 4. In page — Init the slice in an async Page and hand the init to a Zone.
190
+ export default async function Page() {
191
+ const [{ taskInitInTodo }] = await Promise.all([fetch.initTaskInTodo()]);
192
+ return <Task.Zone.Card init={taskInitInTodo} sliceName="taskInTodo" />;
193
+ }
194
+ ```
195
+
196
+ The slice name in code uses camelCase (`inTodo`). In dictionary and components it becomes `"taskInTodo"`.
197
+
198
+ ---
199
+
200
+ ### Recipe 4: Creating a Mutation Endpoint (with Status Workflow)
201
+
202
+ **Files to edit (in order):** `document.ts` → `service.ts` → `signal.ts` → `dictionary.ts` → `store.ts` → `Util.tsx`
203
+
204
+ ```typescript
205
+ // 1. <model>.document.ts — Document chain method with state validation
206
+ export class TaskDocument extends by(cnst.Task) {
207
+ start() {
208
+ if (this.status !== "todo") throw new Err("task.error.cannotStartFromNonTodo");
209
+ this.status = "inProgress";
210
+ return this; // Return this for chaining: task.start().save()
211
+ }
212
+ }
213
+
214
+ // 2. <model>.service.ts — Service method wrapping document
215
+ async startTask(taskId: string) {
216
+ const task = await this.getTask(taskId);
217
+ return task.start().save();
218
+ }
219
+
220
+ // 3. <model>.signal.ts — Mutation endpoint
221
+ export class TaskEndpoint extends endpoint(srv.task, ({ mutation }) => ({
222
+ startTask: mutation(cnst.Task, { guards: [SignedIn] })
223
+ .param("taskId", ID)
224
+ .exec(async function (taskId) {
225
+ return await this.taskService.startTask(taskId);
226
+ }),
227
+ })) {}
228
+
229
+ // 4. <model>.dictionary.ts — Endpoint + error labels
230
+ .endpoint<TaskEndpoint>((fn) => ({
231
+ startTask: fn(["Start Task", "작업시작"])
232
+ .arg((t) => ({ taskId: t(["Task ID", "할 일 ID"]) })),
233
+ }))
234
+ .error({
235
+ cannotStartFromNonTodo: ["Task can only start from todo status", "할 일 상태에서만 시작 가능"],
236
+ })
237
+
238
+ // 5. <model>.store.ts — Client-side action with toast feedback
239
+ async startTask(taskId: string) {
240
+ msg.loading("task.startTaskLoading", { key: "startTask" });
241
+ const task = await fetch.startTask(taskId);
242
+ this.setTask(task); // Auto-generated: updates task state in store
243
+ msg.success("task.startTaskSuccess", { key: "startTask" });
244
+ }
245
+
246
+ // 6. <Model>.Util.tsx — Reusable button component
247
+ export const Start = ({ taskId }: { taskId: string }) => (
248
+ <button className={buttonRecipe({ variant: "primary", size: "xs" })} onClick={() => st.do.startTask(taskId)}>
249
+ Start
250
+ </button>
251
+ );
252
+ ```
253
+
254
+ ---
255
+
256
+ ### Recipe 5: Internal Triggers — Interval & Cron
257
+
258
+ Server-side background jobs. Defined in `internal()` signal, implemented in service.
259
+
260
+ ```typescript
261
+ // 1. <model>.signal.ts — Define triggers
262
+ export class TaskInternal extends internal(srv.task, ({ interval, cron }) => ({
263
+ cleanupStaleTasks: interval(10000).exec(async function () {
264
+ await this.taskService.cleanupStaleTasks();
265
+ }),
266
+
267
+ dailyDigest: cron("0 0 * * *").exec(async function () {
268
+ await this.taskService.sendDailyDigest();
269
+ }),
270
+ })) {}
271
+
272
+ // 2. <model>.service.ts — Implement the logic
273
+ async cleanupStaleTasks() {
274
+ const weekAgo = dayjs().subtract(7, "day").toDate();
275
+ const stale = await this.taskModel.listDueBefore(weekAgo);
276
+ for (const task of stale) {
277
+ await task.remove();
278
+ }
279
+ }
280
+ ```
281
+
282
+ **Available trigger types:**
283
+ - `interval(ms)` — runs repeatedly at the given interval
284
+ - `cron("min hour dom month dow")` — runs on a schedule
285
+ - `initialize()` — runs once on service startup
286
+ - `process(Return).msg(Type)` — message queue consumer
287
+
288
+ ---
289
+
290
+ ### Recipe 6: Creating an Insight (Aggregation / Dashboard Stats)
291
+
292
+ Insights display aggregated statistics across model data.
293
+
294
+ ```typescript
295
+ // 1. <model>.constant.ts — Insight class with accumulate rules
296
+ export class TaskInsight extends via(Task, (field) => ({
297
+ totalCount: field(Int, { default: 0, accumulate: {} }),
298
+ completedCount: field(Int, { default: 0, accumulate: { status: "completed" } }),
299
+ })) {}
300
+
301
+ // 2. <model>.dictionary.ts — Insight field labels
302
+ .insight<TaskInsight>((t) => ({
303
+ totalCount: t(["Total Tasks", "전체 할 일"]),
304
+ completedCount: t(["Completed", "완료됨"]),
305
+ }))
306
+
307
+ // 3. <Model>.View.tsx — Display component consuming an Insight model
308
+ export const Stats = ({ taskInsight }: { taskInsight: cnst.TaskInsight }) => (
309
+ <div className="grid grid-cols-2 gap-4">
310
+ <div className="rounded-lg border border-border bg-card p-4">
311
+ <div className="text-muted-foreground text-sm">{l("task.totalCount")}</div>
312
+ <div className="font-bold text-2xl text-primary">{taskInsight.totalCount}</div>
313
+ </div>
314
+ <div className="rounded-lg border border-border bg-card p-4">
315
+ <div className="text-muted-foreground text-sm">{l("task.completedCount")}</div>
316
+ <div className="font-bold text-2xl text-success">{taskInsight.completedCount}</div>
317
+ </div>
318
+ </div>
319
+ );
320
+
321
+ // 4. <Model>.Zone.tsx — Mount in page via Load.Insight bound to a slice
322
+ export const Insight = ({ sliceName }: { sliceName: string }) => {
323
+ const insight = st.slice[sliceName].use.taskInsight();
324
+ if (!insight) return null;
325
+ return <Task.View.Stats taskInsight={insight} />;
326
+ };
327
+ ```
328
+
329
+ ---
330
+
331
+ ### Data Flow Summary
332
+
333
+ For each business question, follow this chain:
334
+
335
+ | Question | File Pattern |
336
+ |----------|-------------|
337
+ | What fields does it have? | `constant.ts` — `via()` layers: Input → Object → Light → Model → Insight |
338
+ | How is it stored/searched? | `document.ts` — `from()` filters + `by()` document methods + `into()` model |
339
+ | What business rule should run? | `service.ts` — `serve()` with DI (`use`, `service`, `plug`, `env`, `memory`) |
340
+ | What should a page call? | `signal.ts` — `internal()` (jobs), `endpoint()` (APIs), `slice()` (data views) |
341
+ | What client state is shared? | `store.ts` — `store()` with auto-generated form/insight state + custom actions |
342
+ | What should users see? | `View.tsx` + `Zone.tsx` (detail/container), `Template.tsx` (forms), `Unit.tsx` (cards), `Util.tsx` (buttons) |
343
+
344
+
345
+ ## Auto-Generated API Reference
346
+
347
+ akan sync automatically generates APIs across all layers. Only write custom logic — never hand-write what the framework generates.
348
+
349
+ ### Signal — Endpoint Auto-Generation
350
+
351
+ | Auto-Generated | Signature | Description |
352
+ |---------------|-----------|-------------|
353
+ | `view[Model](id)` | `fetch.viewTask(id)` | Fetch single model for detail view |
354
+ | `edit[Model](id)` | `fetch.editTask(id)` | Fetch model for edit view |
355
+ | `merge[Model](id, data)` | `fetch.mergeTask(data)` | Create (no id) or update (with id) model |
356
+ | `[model]List[Suffix](args, skip, limit, sort)` | `fetch.taskListInTodo(args)` | Paginated list from slice filter |
357
+ | `[model]Insight[Suffix](args)` | `fetch.taskInsightInTodo(args)` | Aggregated insight from slice query |
358
+ | `init[Model][Suffix](args)` | `fetch.initTaskInTodo(args)` | Initialize slice with list + insight |
359
+
360
+ **Rule**: Only define `query()`, `mutation()`, `message()`, `pubsub()` endpoints manually when the endpoint needs custom business logic. Standard CRUD is already auto-generated.
361
+
362
+ ### Service — CRUD & Query Auto-Generation
363
+
364
+ | Auto-Generated | Description |
365
+ |---------------|-------------|
366
+ | `this.<model>Model` | Auto-injected model adaptor |
367
+ | `get<Model>(id)`, `load<Model>(id)` | Single document lookup |
368
+ | `create<Model>(data)`, `update<Model>(id, data)`, `remove<Model>(id)` | CRUD operations — named after the model, e.g. `createTask`/`updateTask`/`removeTask` (there is no literal `createModel`) |
369
+ | `list<Query>(args)`, `find<Query>(args)`, `pick<Query>(args)` | Filter-based queries |
370
+ | `exists<Query>(args)`, `count<Query>(args)`, `insight<Query>(args)` | Filter-based helpers |
371
+ | `_preCreate`, `_postCreate`, `_preUpdate`, `_postUpdate`, `_preRemove`, `_postRemove` | Lifecycle hooks (override to add logic) |
372
+
373
+ **Rule**: Use `_preCreate`/`_postCreate` lifecycle hooks for side effects (e.g., push workHistory entries). Write custom service methods only for multi-model orchestration.
374
+
375
+ ### Store — State & Action Auto-Generation
376
+
377
+ | Auto-Generated | Description |
378
+ |---------------|-------------|
379
+ | `[model]` (cached full model), `[model]Loading`, `[model]Form`, `[model]Modal` | Base model states |
380
+ | `create[Model](data)`, `update[Model](id, data)`, `remove[Model](id)` | CRUD actions |
381
+ | `new[Model](partial)`, `edit[Model](model)`, `view[Model](model)` | Form/view state actions |
382
+ | `[slice]List`, `[slice]InitList`, `[slice]Insight`, `[slice]Selection` | Slice states |
383
+ | `init[Slice](args)`, `refresh[Slice]()`, `setPageOf[Slice](page)` | Slice actions |
384
+ | `set[Field]On[Model](value)` | Auto-setters for each model field |
385
+
386
+ **Rule**: Write custom store actions only for toast messages (`msg.loading`/`msg.success`) or multi-step workflows. State fields and CRUD actions are already auto-generated.
387
+
388
+ ### Document — Filter Query Auto-Generation
389
+
390
+ | Auto-Generated (from Filter definition) | Description |
391
+ |----------------------------------------|-------------|
392
+ | `list[Query](args)`, `listIds[Query](args)` | List documents matching filter |
393
+ | `find[Query](args)`, `findId[Query](args)` | Find one (null if not found) |
394
+ | `pick[Query](args)`, `pickId[Query](args)` | Find one (throw if not found) |
395
+ | `exists[Query](args)`, `count[Query](args)` | Existence check and count |
396
+ | `insight[Query](args)`, `query[Query](args)` | Insight and raw query |
397
+ | `remove[Query](args)`, `removeOne[Query](args)` | Query-level soft remove — all matches, or the newest one (`createdAt` desc, not caller-chosen) |
398
+ | `update[Query](args).set(patch)`, `updateOne[Query](args).set(patch)` | Query-level update — the patch lands on a terminal `.set()`, because a filter's trailing args may be optional |
399
+
400
+ **Rule**: Define `Filter` with `.query()` conditions in `document.ts`. akan sync auto-generates all 14 query helper methods per filter. Write `Document` chain methods only for state transitions with validation.
401
+
402
+ **The four query-level writes fire no hooks**, so no `_pre`/`_postRemove` and no cascade run — same as `updateManyByQuery`. Reach for them when the model carries no removal side effect; otherwise remove documents one at a time. A filter keyed after its own model (filter `chat` on model `chat`) is rejected at boot, because `removeChat`/`updateChat` would otherwise shadow the generated single-document CRUD.
@@ -16,7 +16,7 @@ import {
16
16
  import {
17
17
  AppExecutor,
18
18
  WorkspaceExecutor
19
- } from "./index-nkwmnqwn.js";
19
+ } from "./index-5f4gnt4c.js";
20
20
  import"./index-f39512t6.js";
21
21
  import"./index-mxvakhsm.js";
22
22
  import"./index-1577bej2.js";
@@ -551,6 +551,7 @@ ${this.basePaths.size ? `ENV AKAN_PUBLIC_BASE_PATHS=${[...this.basePaths].join("
551
551
  ENV AKAN_PUBLIC_DEFAULT_LOCALE=${this.i18n.defaultLocale}
552
552
  ENV AKAN_PUBLIC_LOCALES=${this.i18n.locales.join(",")}
553
553
  ENV AKAN_PUBLIC_OPERATION_MODE=cloud
554
+ ENV AKAN_LOG_TO_FILE=0
554
555
  ${webEnvLines}
555
556
  CMD [${command.map((c) => `"${c}"`).join(",")}]`;
556
557
  }
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  workflowRunArtifactPath,
4
4
  workflowSyncDir
5
- } from "./index-ytaqtc04.js";
5
+ } from "./index-8besc14m.js";
6
6
  import {
7
7
  AppExecutor,
8
8
  LibExecutor,
@@ -11,7 +11,7 @@ import {
11
11
  readDevkitVersion,
12
12
  rootAllowedDirs,
13
13
  rootAllowedFiles
14
- } from "./index-nkwmnqwn.js";
14
+ } from "./index-5f4gnt4c.js";
15
15
  import {
16
16
  collectRecipeSources,
17
17
  findInlineRecipeDuplicates,
@@ -7,14 +7,14 @@ import {
7
7
  } from "./index-sh01r3pm.js";
8
8
  import {
9
9
  openBrowser
10
- } from "./index-mkn5qagt.js";
10
+ } from "./index-cp00yns2.js";
11
11
  import {
12
12
  runner
13
- } from "./index-e31ghfp5.js";
13
+ } from "./index-gvq17wqn.js";
14
14
  import {
15
15
  AppExecutor,
16
16
  WorkspaceExecutor
17
- } from "./index-nkwmnqwn.js";
17
+ } from "./index-5f4gnt4c.js";
18
18
 
19
19
  // pkgs/@akanjs/cli/npmRegistry.ts
20
20
  var defaultNpmRegistry = "https://registry.npmjs.org";
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  AppExecutor,
4
4
  LibExecutor
5
- } from "./index-nkwmnqwn.js";
5
+ } from "./index-5f4gnt4c.js";
6
6
 
7
7
  // pkgs/@akanjs/devkit/workflow/utils.ts
8
8
  var jsonText = (value, { trailingNewline = true } = {}) => `${JSON.stringify(value, null, 2)}${trailingNewline ? `
@@ -5,7 +5,7 @@ import {
5
5
  } from "./index-76rn3g2c.js";
6
6
  import {
7
7
  CommandExecutionError
8
- } from "./index-nkwmnqwn.js";
8
+ } from "./index-5f4gnt4c.js";
9
9
 
10
10
  // pkgs/@akanjs/devkit/capacitorApp.ts
11
11
  import { cp, mkdir, readFile, rm, writeFile } from "fs/promises";
@@ -1,14 +1,14 @@
1
1
  // @bun
2
2
  import {
3
3
  LibraryScript
4
- } from "./index-p681w089.js";
4
+ } from "./index-sqsfv8wg.js";
5
5
  import {
6
6
  resolveMobileTargets
7
7
  } from "./index-76rn3g2c.js";
8
8
  import {
9
9
  runner,
10
10
  script
11
- } from "./index-e31ghfp5.js";
11
+ } from "./index-gvq17wqn.js";
12
12
  import {
13
13
  HmrWatcher,
14
14
  WatchRootResolver
@@ -18,7 +18,7 @@ import {
18
18
  LibExecutor,
19
19
  PkgExecutor,
20
20
  WorkspaceExecutor
21
- } from "./index-nkwmnqwn.js";
21
+ } from "./index-5f4gnt4c.js";
22
22
  import {
23
23
  __require
24
24
  } from "./index-yb2wsc7f.js";
@@ -72,6 +72,9 @@ Caused by: ${ApplicationBuildReporter.formatError(error.cause)}` : "";
72
72
  import { confirm } from "@inquirer/prompts";
73
73
  import { Logger as Logger5 } from "akanjs/common";
74
74
 
75
+ // pkgs/@akanjs/cli/application/application.runner.ts
76
+ import path4 from "path";
77
+
75
78
  // pkgs/@akanjs/devkit/akanApp/akanApp.host.ts
76
79
  import { stat } from "fs/promises";
77
80
  import path2 from "path";
@@ -1900,7 +1903,7 @@ function openBrowser(url) {
1900
1903
  // pkgs/@akanjs/cli/application/application.runner.ts
1901
1904
  var loadBuildRunner = async () => (await import("./applicationBuildRunner-af0wtspv.js")).ApplicationBuildRunner;
1902
1905
  var loadReleasePackager = async () => (await import("./applicationReleasePackager-93nzdfsy.js")).ApplicationReleasePackager;
1903
- var loadCapacitorApp = async () => (await import("./capacitorApp-vnvnvdhf.js")).CapacitorApp;
1906
+ var loadCapacitorApp = async () => (await import("./capacitorApp-b0ppke3m.js")).CapacitorApp;
1904
1907
  var loadAbstractCompactor = async () => (await import("./abstractCompactor-20e0cwbs.js")).AbstractCompactor;
1905
1908
  var loadPrompts = async () => await import("@inquirer/prompts");
1906
1909
 
@@ -1945,10 +1948,69 @@ class ApplicationRunner extends runner("application") {
1945
1948
  stdio: "inherit"
1946
1949
  });
1947
1950
  }
1951
+ #runtimeDirOf(app, override) {
1952
+ return path4.resolve(override ?? process.env.AKAN_RUNTIME_DIR ?? path4.join(app.workspace.workspaceRoot, "local", "apps", app.name, "runtime"));
1953
+ }
1954
+ async runLogs(app, options) {
1955
+ const { LogControlUnavailableError, LogTailClient } = await import("akanjs/server/logging/logTailClient");
1956
+ const { LogQueryMatcher } = await import("akanjs/server/logging/logQuery");
1957
+ const runtimeDir = this.#runtimeDirOf(app, options.runtimeDir);
1958
+ const socketPath = LogTailClient.socketPath(runtimeDir);
1959
+ const { level, grep, endpoint, trace, child, role, origin, since } = options;
1960
+ const query = Object.fromEntries(Object.entries({ level, grep, endpoint, trace, child, role, origin, since }).filter(([, value]) => value !== undefined && value !== null && value !== ""));
1961
+ const print = (record) => process.stdout.write(options.json ? `${JSON.stringify(record)}
1962
+ ` : Logger4.render(record));
1963
+ const note = (text) => process.stderr.write(`[akan logs] ${text}
1964
+ `);
1965
+ let finish = null;
1966
+ const closed = new Promise((resolve) => {
1967
+ finish = resolve;
1968
+ });
1969
+ let client;
1970
+ try {
1971
+ client = await LogTailClient.connect(socketPath, {
1972
+ onRecord: (entry) => print(entry.record),
1973
+ onEvent: (response) => {
1974
+ if (response.type === "dropped")
1975
+ note(`${response.count} records dropped (reader too slow)`);
1976
+ },
1977
+ onClose: () => finish?.()
1978
+ });
1979
+ } catch (error) {
1980
+ if (error instanceof LogControlUnavailableError)
1981
+ throw new Error(`${app.name} is not running (no ${path4.basename(socketPath)} in ${runtimeDir}). Start it with \`akan start ${app.name}\`, or pass --runtime-dir for a built app.`);
1982
+ throw error;
1983
+ }
1984
+ const sinceMs = since ? LogQueryMatcher.parseSince(since) : undefined;
1985
+ const noteCoverage = (coverage) => {
1986
+ if (sinceMs !== undefined && coverage.from !== null && sinceMs < coverage.from)
1987
+ note(`${LogTailClient.describeCoverage(coverage)}; older records are not retained`);
1988
+ };
1989
+ if (endpoint)
1990
+ note("requests served by the primitive query fast path carry no endpoint and are not shown");
1991
+ if (options.follow === false) {
1992
+ const { entries, coverage } = await client.history({
1993
+ ...query,
1994
+ ...options.replay ? { limit: options.replay } : {}
1995
+ });
1996
+ for (const entry of entries)
1997
+ print(entry.record);
1998
+ noteCoverage(coverage);
1999
+ client.close();
2000
+ return;
2001
+ }
2002
+ const subscribed = await client.subscribe(query, { replay: options.replay });
2003
+ noteCoverage(subscribed.coverage);
2004
+ const stop = () => client.close();
2005
+ process.once("SIGINT", stop);
2006
+ process.once("SIGTERM", stop);
2007
+ await closed;
2008
+ }
1948
2009
  async runConsole(app) {
1949
2010
  const serverPath = `${app.cwdPath}/server.ts`;
1950
2011
  if (!await app.exists("server.ts"))
1951
2012
  throw new Error(`Server file not found: apps/${app.name}/server.ts`);
2013
+ const runtimeDir = this.#runtimeDirOf(app);
1952
2014
  const code = `
1953
2015
  const serverModule = await import(${JSON.stringify(serverPath)});
1954
2016
  const { assertAkanConsoleAllowed, startAkanConsole } = await import("akanjs/server");
@@ -1958,6 +2020,7 @@ assertAkanConsoleAllowed(server.env);
1958
2020
  await server.start({ listen: false, web: false });
1959
2021
  try {
1960
2022
  await startAkanConsole(server, {
2023
+ runtimeDir: ${JSON.stringify(runtimeDir)},
1961
2024
  globals: {
1962
2025
  srv: serverModule.srv,
1963
2026
  sig: serverModule.sig,
@@ -2355,6 +2418,9 @@ class ApplicationScript extends script("application", [ApplicationRunner, Librar
2355
2418
  await app.scanSync();
2356
2419
  await this.applicationRunner.runConsole(app);
2357
2420
  }
2421
+ async logs(app, options) {
2422
+ await this.applicationRunner.runLogs(app, options);
2423
+ }
2358
2424
  async build(app, { write = true, fast = false, quiet = false } = {}) {
2359
2425
  await app.scanSync({ write });
2360
2426
  if (!quiet)
@@ -1,17 +1,17 @@
1
1
  // @bun
2
2
  import {
3
3
  AkanContextAnalyzer
4
- } from "./index-va15r8h5.js";
4
+ } from "./index-6d5r8q6k.js";
5
5
  import {
6
6
  createRepairReport,
7
7
  generatedFilePathsForTarget,
8
8
  renderRepairReport,
9
9
  writeGeneratedSyncState,
10
10
  writeWorkflowRunArtifact
11
- } from "./index-ytaqtc04.js";
11
+ } from "./index-8besc14m.js";
12
12
  import {
13
13
  runner
14
- } from "./index-e31ghfp5.js";
14
+ } from "./index-gvq17wqn.js";
15
15
 
16
16
  // pkgs/@akanjs/cli/repair/repair.runner.ts
17
17
  var commandForShell = (command) => command.startsWith("akan ") ? `bun run ${command}` : command;
@@ -6,7 +6,7 @@ import {
6
6
  ModuleExecutor,
7
7
  PkgExecutor,
8
8
  WorkspaceExecutor
9
- } from "./index-nkwmnqwn.js";
9
+ } from "./index-5f4gnt4c.js";
10
10
  import {
11
11
  getDirname
12
12
  } from "./index-1577bej2.js";
@@ -1,10 +1,10 @@
1
1
  // @bun
2
2
  import {
3
3
  CloudRunner
4
- } from "./index-4rw4qhe6.js";
4
+ } from "./index-737aj4fm.js";
5
5
  import {
6
6
  PackageScript
7
- } from "./index-0ngvvgry.js";
7
+ } from "./index-jybbmwed.js";
8
8
  import {
9
9
  AiSession,
10
10
  CloudApi,
@@ -12,13 +12,13 @@ import {
12
12
  } from "./index-sh01r3pm.js";
13
13
  import {
14
14
  ApplicationScript
15
- } from "./index-mkn5qagt.js";
15
+ } from "./index-cp00yns2.js";
16
16
  import {
17
17
  script
18
- } from "./index-e31ghfp5.js";
18
+ } from "./index-gvq17wqn.js";
19
19
  import {
20
20
  PkgExecutor
21
- } from "./index-nkwmnqwn.js";
21
+ } from "./index-5f4gnt4c.js";
22
22
 
23
23
  // pkgs/@akanjs/cli/cloud/cloud.script.ts
24
24
  import { Logger } from "akanjs/common";