@bitakit/cli 0.2.5 → 0.2.7

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.
@@ -0,0 +1,57 @@
1
+ # Create an app or a standalone plugin package
2
+
3
+ Use this for a new project. Extend an existing app with its installed CLI instead of
4
+ scaffolding another app around it.
5
+
6
+ ## New application
7
+
8
+ Default to Next.js; use TanStack Start (experimental) when the user requests it.
9
+
10
+ ```sh
11
+ npx @bitakit/create-app@latest <directory> --framework next --features <list|none> --yes
12
+ ```
13
+
14
+ - `--features` is a comma-separated subset of `preferences`, `shell` and `quick-search`, or
15
+ `none`. Without it the app gets `shell,quick-search` (a sidebar frame, Settings and search).
16
+ Choose features from the user's requirements; add `--sample` for the working Todo sample.
17
+ - `--yes` skips interactive prompts. In an empty session folder, or one containing only `.git`
18
+ and agent/editor files, use `.` as the directory. The generator preserves and merges those
19
+ files so the app and its skill land in the folder the agent can see.
20
+ - Otherwise use a new directory. Continue from that app folder and read its `AGENTS.md` and
21
+ `.agents/skills/bitakit-app-development/SKILL.md`. A session that started before the skill
22
+ existed may need a restart to discover it automatically.
23
+ - Follow existing network/install authorization and environment approval controls. If a command
24
+ is blocked, report the blocker; do not imitate the generator by hand.
25
+
26
+ The generator installs with the package manager that started it; the `npx` form uses npm.
27
+ For pnpm, Yarn or Bun, start it with that tool and the same arguments, or pass
28
+ `--package-manager <npm|pnpm|yarn|bun>`. Keep that package manager for later installs; a
29
+ standalone plugin package always uses npm.
30
+
31
+ ```sh
32
+ pnpm create @bitakit/app <directory> --framework next --features <list|none> --yes
33
+ yarn create @bitakit/app <directory> --framework next --features <list|none> --yes
34
+ bunx @bitakit/create-app@latest <directory> --framework next --features <list|none> --yes
35
+ ```
36
+
37
+ For a learning app with the sample:
38
+
39
+ ```sh
40
+ npx @bitakit/create-app@latest my-todos --framework next --sample --yes
41
+ ```
42
+
43
+ The `todos` plugin owns the list; `activity` listens to `todos.changed` and fills `todos.footer`.
44
+ Run the app's dev script, open `/todos`, add a todo and confirm it appears in both the list and
45
+ the activity feed. The other recipes extend this sample, with prerequisites named in each one.
46
+
47
+ ## Standalone plugin package
48
+
49
+ ```sh
50
+ npx @bitakit/create-app@latest notes-plugin --plugin --framework next --yes
51
+ ```
52
+
53
+ This creates a plugin with source under `src/`, its own `AGENTS.md` and Claude import, headless
54
+ tests and a playground app. Follow its generated package guide: add contributions with
55
+ `npx bitakit add action <name>` (no app plugin prefix), run `npm test`, `npm run typecheck`
56
+ and `npm run build`, and try it with `npm run dev`. Do not run `bitakit add plugin` inside
57
+ the package. App-specific paths in other recipes must be adapted to this package layout.
@@ -0,0 +1,321 @@
1
+ # Load and save data through an API
2
+
3
+ Use this when data must survive a reload, be shared across devices or users, or needs the
4
+ server (a database, secrets, permission checks). Service stores live in browser memory, so the
5
+ server owns the data and the service keeps the client's copy. The example continues the
6
+ Bookmarks feature from [worked-example.md](worked-example.md); all code type-checks in a
7
+ create-app Next.js app.
8
+
9
+ ## Who does what
10
+
11
+ | Part | File | Responsibility |
12
+ | ------------------ | ------------------------------------------ | ------------------------------------------------------ |
13
+ | API route (server) | `src/app/api/bookmarks/route.ts` | Validate input, check permissions, read and write data |
14
+ | Service (browser) | `src/plugins/bookmarks/services/list.ts` | Call the API, hold the list and its loading state |
15
+ | Actions | `src/plugins/bookmarks/actions/*.ts` | Run operations: pending state, failure message |
16
+ | Page | `src/plugins/bookmarks/ui/pages/index.tsx` | Show loading, error, empty and loaded states |
17
+
18
+ API routes are native framework routes in `src/app`, not plugin files; plugins have no server
19
+ part yet. Keep secrets and database code there only.
20
+
21
+ ## The API route
22
+
23
+ `src/app/api/bookmarks/route.ts`:
24
+
25
+ ```ts
26
+ import { randomUUID } from 'node:crypto';
27
+
28
+ type Bookmark = { id: string; title: string; url: string };
29
+
30
+ // Example storage: one list in server memory, lost on restart and shared by every visitor.
31
+ // Replace it with your database, and check the signed-in user before reading or changing data.
32
+ const bookmarks: Bookmark[] = [];
33
+
34
+ export async function GET() {
35
+ return Response.json({ bookmarks });
36
+ }
37
+
38
+ export async function POST(request: Request) {
39
+ // The client's enabled rule is a convenience; the server validates again.
40
+ const { url } = (await request.json().catch(() => ({}))) as { url?: unknown };
41
+ if (typeof url !== 'string' || !URL.canParse(url))
42
+ return new Response('Send a full URL such as https://example.com.', { status: 400 });
43
+ const address = new URL(url);
44
+ const bookmark = { id: randomUUID(), title: address.hostname, url: address.href };
45
+ bookmarks.push(bookmark);
46
+ return Response.json({ bookmark }, { status: 201 });
47
+ }
48
+
49
+ export async function DELETE(request: Request) {
50
+ const id = new URL(request.url).searchParams.get('id');
51
+ const index = bookmarks.findIndex((bookmark) => bookmark.id === id);
52
+ if (index === -1) return new Response('This bookmark no longer exists.', { status: 404 });
53
+ bookmarks.splice(index, 1);
54
+ return new Response(null, { status: 204 });
55
+ }
56
+ ```
57
+
58
+ - The example list also resets whenever the dev server reloads after a file change; a database
59
+ does not.
60
+ - Answer errors with a short, user-readable text: the service passes it on and the Action shows it.
61
+ - Use the schema library the app already has (for example zod) for larger inputs; follow
62
+ existing dependency authorization when adding one.
63
+ - For per-user data, read the session in the route and filter by the user. Client rules
64
+ (`enabled`, `visible`, interceptors) only shape the UI.
65
+
66
+ ## The service
67
+
68
+ `src/plugins/bookmarks/services/list.ts`:
69
+
70
+ ```ts
71
+ import { defineService } from '@bitakit/core';
72
+
73
+ export type Bookmark = { id: string; title: string; url: string };
74
+
75
+ type State = { bookmarks: Bookmark[]; status: 'loading' | 'ready' | 'error'; error: string };
76
+
77
+ /** Throws the server's message so a failing Action shows it. */
78
+ async function send(path: string, init?: RequestInit): Promise<Response> {
79
+ const response = await fetch(path, init);
80
+ if (!response.ok) throw new Error((await response.text()) || response.statusText);
81
+ return response;
82
+ }
83
+
84
+ // Bookmarks stored by the app's API route, src/app/api/bookmarks/route.ts.
85
+ export default defineService(({ store, events, onStart }) => {
86
+ const state = store<State>({ bookmarks: [], status: 'loading', error: '' });
87
+
88
+ async function load(signal?: AbortSignal) {
89
+ state.set((current) => ({ ...current, status: 'loading', error: '' }));
90
+ try {
91
+ const response = await send('/api/bookmarks', { signal });
92
+ const { bookmarks } = (await response.json()) as { bookmarks: Bookmark[] };
93
+ state.set({ bookmarks, status: 'ready', error: '' });
94
+ } catch (error) {
95
+ if (signal?.aborted) return;
96
+ const message = error instanceof Error ? error.message : String(error);
97
+ state.set((current) => ({ ...current, status: 'error', error: message }));
98
+ }
99
+ }
100
+
101
+ // Startup does not wait for the network; pages show `status` while the list loads.
102
+ onStart(({ signal }) => {
103
+ void load(signal);
104
+ });
105
+
106
+ return {
107
+ state,
108
+ reload: () => load(),
109
+ async add(url: string) {
110
+ const response = await send('/api/bookmarks', {
111
+ method: 'POST',
112
+ headers: { 'content-type': 'application/json' },
113
+ body: JSON.stringify({ url }),
114
+ });
115
+ const { bookmark } = (await response.json()) as { bookmark: Bookmark };
116
+ state.set((current) => ({ ...current, bookmarks: [...current.bookmarks, bookmark] }));
117
+ events.emit('bookmarks.added', { id: bookmark.id, url: bookmark.url });
118
+ },
119
+ async remove(id: string) {
120
+ await send(`/api/bookmarks?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
121
+ state.set((current) => ({
122
+ ...current,
123
+ bookmarks: current.bookmarks.filter((bookmark) => bookmark.id !== id),
124
+ }));
125
+ events.emit('bookmarks.removed', { id });
126
+ },
127
+ };
128
+ });
129
+ ```
130
+
131
+ - Start loading with `void load(signal)` in `onStart`. Awaiting it would hold up the whole
132
+ app's startup until the network answers.
133
+ - Keep `status` and `error` in the store, next to the data, so every page shows the same state.
134
+ - Change the store only after the server confirmed the change, and emit events after that. On
135
+ a failure the list stays as it was.
136
+ - The `signal` is aborted when the runtime stops; a cancelled load leaves the store alone.
137
+
138
+ ## The Actions
139
+
140
+ `src/plugins/bookmarks/actions/add.ts` returns the service's promise:
141
+
142
+ ```ts
143
+ import { defineAction } from '@bitakit/core';
144
+
145
+ export default defineAction<string>({
146
+ title: 'Save',
147
+ enabled: ({ input }) => URL.canParse(input?.trim() ?? ''),
148
+ // Return the promise: the button stays pending until the server answers, and a throw fails the run.
149
+ execute: ({ services, input }) => services.bookmarks.list.add(input.trim()),
150
+ success: 'Bookmark saved',
151
+ failure: ({ error }) => (error instanceof Error ? error.message : 'Could not save the bookmark.'),
152
+ });
153
+ ```
154
+
155
+ `src/plugins/bookmarks/actions/reload.ts` (`npx bitakit add action bookmarks/reload`):
156
+
157
+ ```ts
158
+ import { defineAction } from '@bitakit/core';
159
+
160
+ export default defineAction({
161
+ title: 'Try again',
162
+ execute: ({ services }) => services.bookmarks.list.reload(),
163
+ });
164
+ ```
165
+
166
+ - Without `failure`, a failed run still shows the error's message. Set it to word the message
167
+ for users.
168
+ - `remove.ts` stays as in the worked example; returning `remove(input)` already returns the promise.
169
+
170
+ ## The page states
171
+
172
+ The worked example's page with a loading placeholder and an error state.
173
+ `src/plugins/bookmarks/ui/pages/index.tsx`:
174
+
175
+ ```tsx
176
+ 'use client';
177
+ import { useState } from 'react';
178
+ import { Action, useServiceState, useSetting } from '@bitakit/ui';
179
+ import {
180
+ Button,
181
+ Input,
182
+ Item,
183
+ ItemActions,
184
+ ItemContent,
185
+ ItemDescription,
186
+ ItemGroup,
187
+ ItemTitle,
188
+ PageHeader,
189
+ Skeleton,
190
+ } from '@bitakit/ui/components';
191
+
192
+ // Served at /bookmarks. State comes from the bookmarks.list service; buttons run Actions.
193
+ export default function BookmarksPage() {
194
+ const [url, setUrl] = useState('');
195
+ const bookmarks = useServiceState('bookmarks.list', (state) => state.bookmarks, []);
196
+ const status = useServiceState('bookmarks.list', (state) => state.status, 'loading');
197
+ const error = useServiceState('bookmarks.list', (state) => state.error, '');
198
+ const openInNewTab = useSetting('bookmarks.openInNewTab').value;
199
+ return (
200
+ <div className="flex flex-col gap-6">
201
+ <PageHeader title="Bookmarks" subtitle="Links you want to come back to." />
202
+ <form className="flex gap-2" onSubmit={(event) => event.preventDefault()}>
203
+ <Input
204
+ value={url}
205
+ type="url"
206
+ placeholder="https://example.com"
207
+ aria-label="Link to save"
208
+ onChange={(event) => setUrl(event.target.value)}
209
+ />
210
+ {/* Clear the field only when the bookmark was saved. */}
211
+ <Action
212
+ id="bookmarks.add"
213
+ input={url}
214
+ onExecuted={(result) => result.status === 'completed' && setUrl('')}
215
+ >
216
+ <Button type="submit" />
217
+ </Action>
218
+ </form>
219
+ {status === 'loading' ? (
220
+ <Skeleton className="h-16 w-full" />
221
+ ) : status === 'error' ? (
222
+ <div role="alert" className="flex items-center gap-3 text-sm text-destructive">
223
+ Could not load bookmarks: {error}
224
+ <Action id="bookmarks.reload">
225
+ <Button variant="outline" size="sm" />
226
+ </Action>
227
+ </div>
228
+ ) : bookmarks.length ? (
229
+ <ItemGroup>
230
+ {bookmarks.map((bookmark) => (
231
+ <Item key={bookmark.id} variant="outline">
232
+ <ItemContent>
233
+ <ItemTitle>
234
+ <a
235
+ href={bookmark.url}
236
+ {...(openInNewTab ? { target: '_blank', rel: 'noreferrer' } : {})}
237
+ >
238
+ {bookmark.title}
239
+ </a>
240
+ </ItemTitle>
241
+ <ItemDescription>{bookmark.url}</ItemDescription>
242
+ </ItemContent>
243
+ <ItemActions>
244
+ <Action id="bookmarks.remove" input={bookmark.id}>
245
+ <Button variant="outline" size="sm" />
246
+ </Action>
247
+ </ItemActions>
248
+ </Item>
249
+ ))}
250
+ </ItemGroup>
251
+ ) : (
252
+ <p className="text-sm text-muted-foreground">No bookmarks yet. Paste a link above.</p>
253
+ )}
254
+ </div>
255
+ );
256
+ }
257
+ ```
258
+
259
+ - The selectors fall back to `'loading'` and `[]` until the service is ready, so the first
260
+ render already shows the placeholder.
261
+ - The error state offers the `bookmarks.reload` Action instead of asking for a page reload.
262
+
263
+ ## Test without a server
264
+
265
+ `mountPlugin` runs no server, so answer `fetch` in the test. This replaces the worked example's
266
+ test, which calls the in-memory service.
267
+ `tests/bookmarks-api.test.ts`:
268
+
269
+ ```ts
270
+ import assert from 'node:assert/strict';
271
+ import test from 'node:test';
272
+ import { defineContract, definePlugin, defineSlot, getService } from '@bitakit/core';
273
+ import { mountPlugin } from '@bitakit/core/testing';
274
+ import type list from '../src/plugins/bookmarks/services/list';
275
+
276
+ const bookmarks = defineContract('bookmarks.list').of<ReturnType<typeof list.create>>();
277
+ const shell = definePlugin({
278
+ id: 'shell',
279
+ slots: { navigation: defineSlot({ accepts: 'actions' }) },
280
+ });
281
+
282
+ test('the list loads from the API and shows server errors on save', async (t) => {
283
+ // No server runs in a headless test: answer the service's requests here.
284
+ t.mock.method(globalThis, 'fetch', async (_url: string, init?: RequestInit) =>
285
+ init?.method === 'POST'
286
+ ? new Response('Send a full URL such as https://example.com.', { status: 400 })
287
+ : Response.json({
288
+ bookmarks: [{ id: '1', title: 'example.com', url: 'https://example.com/' }],
289
+ }),
290
+ );
291
+ const plugin = await mountPlugin('src/plugins/bookmarks', { plugins: [shell] });
292
+ try {
293
+ const list = getService(plugin.services, bookmarks);
294
+ await list.reload();
295
+ assert.equal(list.state.get().status, 'ready');
296
+ assert.equal(list.state.get().bookmarks.length, 1);
297
+
298
+ // A failed run rejects with the Action's failure message; the list stays unchanged.
299
+ await assert.rejects(plugin.execute('add', 'https://example.org'), /full URL/);
300
+ assert.equal(list.state.get().bookmarks.length, 1);
301
+ } finally {
302
+ await plugin.stop();
303
+ }
304
+ });
305
+ ```
306
+
307
+ ## Data that belongs to the signed-in user
308
+
309
+ - The route reads the session and returns only that user's data; it rejects requests without
310
+ one (401) or without access (403).
311
+ - When the user or organization can change while the app is open, reload in the service when
312
+ the `auth` service reports a different identity, and ignore answers that arrive for the
313
+ previous one. Check `app.has('auth')` (Actions) or declare `requires` (services) first.
314
+ - Never decide access from client state alone, such as an organization ID kept in a store.
315
+
316
+ ## Explain it to the user
317
+
318
+ Say where the data lives ("the server keeps the bookmarks in `src/app/api/bookmarks/route.ts`;
319
+ the `bookmarks.list` service loads them when the app starts"), what the user sees while it loads
320
+ or fails ("a placeholder, then the list; on an error a message with Try again"), and what still
321
+ needs work, such as replacing the example's in-memory storage with the app's database.
@@ -0,0 +1,219 @@
1
+ # Layouts, screens and other replaceable parts
2
+
3
+ Use this when the user wants another look for a group of pages (sign-in, onboarding, error
4
+ pages), a different frame for the whole app, their own 404 or error screen, or a part of a
5
+ feature that other plugins may replace. One mechanism covers all of them: a **single slot** is a
6
+ replaceable part. Its owner renders a default; a file in your app or plugin replaces it.
7
+
8
+ ## Which part to replace
9
+
10
+ | The user wants | Part (single slot) | File |
11
+ | ---------------------------------------------- | ------------------------------------ | ------------------------------------------------------------- |
12
+ | Another frame for sign-in, sign-up and similar | `layout.auth` | `src/layouts/auth.tsx` |
13
+ | Another frame for every normal page | `layout.app` | `src/layouts/app.tsx` |
14
+ | Another frame for error pages | `layout.error` | `src/layouts/error.tsx` |
15
+ | A new kind of page, such as onboarding | `layout.onboarding` | `src/layouts/onboarding.tsx` (declared automatically) |
16
+ | Their own 404 page | `screen.not-found` | `src/ui/slots/screen.not-found.tsx` or a plugin's `ui/slots/` |
17
+ | Their own error page | `screen.error` | `ui/slots/screen.error.tsx` |
18
+ | Their own access-denied or loading page | `screen.forbidden`, `screen.loading` | `ui/slots/screen.<name>.tsx` |
19
+ | A part of a feature that others may replace | `<plugin>.<part>` | `slots/<part>.ts` with `policy: 'single'` |
20
+
21
+ The `layout.*` and `screen.*` parts come from `@bitakit/shell`; its `AGENTS.md` lists the
22
+ defaults. Run `npx bitakit slots` to see every part and which candidate renders it.
23
+
24
+ ## Put pages into a layout family
25
+
26
+ A page names its family; the family's layout wraps it.
27
+
28
+ ```tsx
29
+ // src/plugins/account/ui/pages/login.tsx — served at /account/login
30
+ 'use client';
31
+ import { PageHeader } from '@bitakit/ui/components';
32
+
33
+ export const layout = 'auth';
34
+
35
+ export default function LoginPage() {
36
+ return <PageHeader title="Sign in" subtitle="Welcome back." />;
37
+ }
38
+ ```
39
+
40
+ - Shell ships defaults for `auth` (a centered column with the brand), `error` and
41
+ `full-page`; `app` (or no export) is the normal frame and `blank` renders the page bare.
42
+ - Any other name is a new family: add `src/layouts/<family>.tsx`, and discovery declares it.
43
+ A page that names a family nobody provides stops startup with the files to add.
44
+
45
+ ## Replace a layout
46
+
47
+ ```sh
48
+ npx bitakit add layout auth/split
49
+ ```
50
+
51
+ ```tsx
52
+ // src/layouts/auth/split.tsx — a variant of the auth family
53
+ import type { ReactNode } from 'react';
54
+
55
+ // The sign-in frame: a brand panel next to the form on wide screens.
56
+ export default function AuthSplitLayout({ children }: { children?: ReactNode }) {
57
+ return (
58
+ <div className="grid min-h-svh lg:grid-cols-2">
59
+ <div className="hidden bg-primary lg:block" />
60
+ <div className="flex items-center justify-center p-6">
61
+ <div className="w-full max-w-sm">{children}</div>
62
+ </div>
63
+ </div>
64
+ );
65
+ }
66
+ ```
67
+
68
+ - A layout receives the page as `children`; give `children` an optional type.
69
+ - `src/layouts/auth.tsx` is the variant `default`; `src/layouts/auth/<variant>.tsx` adds named
70
+ variants. A plugin keeps its layouts in `ui/layouts/` (`--plugin <id>`).
71
+ - One candidate renders automatically. With several, choose one:
72
+
73
+ ```ts
74
+ // bitakit.config.ts
75
+ import { defineBitaKit } from '@bitakit/discovery';
76
+
77
+ export default defineBitaKit({ choose: { 'layout.auth': 'split' } });
78
+ ```
79
+
80
+ ## Replace the whole frame
81
+
82
+ `src/layouts/app.tsx` replaces Shell's sidebar or navbar frame for every normal page. Compose
83
+ Shell's parts so navigation, slots and the page spacing keep working:
84
+
85
+ ```tsx
86
+ // src/layouts/app.tsx
87
+ 'use client';
88
+ import type { ReactNode } from 'react';
89
+ import { AppShell } from '@bitakit/shell';
90
+
91
+ // The frame of every normal page: the sidebar and the page, without the header bar.
92
+ export default function AppFrame({ children }: { children?: ReactNode }) {
93
+ return (
94
+ <>
95
+ <AppShell.Sidebar />
96
+ <AppShell.Content>{children}</AppShell.Content>
97
+ </>
98
+ );
99
+ }
100
+ ```
101
+
102
+ Parts: `AppShell.Sidebar`, `AppShell.TopBar`, `AppShell.Content` (takes `topBar`),
103
+ `AppShell.Surface`, `AppShell.Footer`, `AppShell.AuthLayout`, `AppShell.ErrorLayout`. A header
104
+ widget of another plugin keeps working as long as the frame renders its slot (`TopBar` renders
105
+ `shell.header.end` and `shell.toolbar`); check the pages that use header slots after replacing
106
+ the frame.
107
+
108
+ ## Replace a screen
109
+
110
+ ```tsx
111
+ // src/plugins/brand/ui/slots/screen.not-found.tsx
112
+ 'use client';
113
+ import { Button } from '@bitakit/ui/components';
114
+ import {
115
+ Empty,
116
+ EmptyContent,
117
+ EmptyDescription,
118
+ EmptyHeader,
119
+ EmptyTitle,
120
+ } from '@bitakit/shell/pages';
121
+
122
+ // Replaces Shell's not-found screen in every place it appears.
123
+ export default function NotFoundScreen() {
124
+ return (
125
+ <Empty>
126
+ <EmptyHeader>
127
+ <EmptyTitle>Nothing here</EmptyTitle>
128
+ <EmptyDescription>The page moved or never existed.</EmptyDescription>
129
+ </EmptyHeader>
130
+ <EmptyContent>
131
+ <Button asChild>
132
+ <a href="/">Go to the start page</a>
133
+ </Button>
134
+ </EmptyContent>
135
+ </Empty>
136
+ );
137
+ }
138
+ ```
139
+
140
+ The error screen receives `reset` when the framework can retry:
141
+
142
+ ```tsx
143
+ // src/plugins/brand/ui/slots/screen.error.tsx
144
+ 'use client';
145
+ import type { SlotProps } from '@bitakit/ui';
146
+ import { Button } from '@bitakit/ui/components';
147
+ import {
148
+ Empty,
149
+ EmptyContent,
150
+ EmptyDescription,
151
+ EmptyHeader,
152
+ EmptyTitle,
153
+ } from '@bitakit/shell/pages';
154
+
155
+ // Replaces Shell's error screen; reset retries when the framework offers it.
156
+ export default function ErrorScreen({ payload }: SlotProps<'screen.error'>) {
157
+ return (
158
+ <Empty>
159
+ <EmptyHeader>
160
+ <EmptyTitle>That did not work</EmptyTitle>
161
+ <EmptyDescription>Try again in a moment.</EmptyDescription>
162
+ </EmptyHeader>
163
+ {payload.reset && (
164
+ <EmptyContent>
165
+ <Button onClick={payload.reset}>Try again</Button>
166
+ </EmptyContent>
167
+ )}
168
+ </Empty>
169
+ );
170
+ }
171
+ ```
172
+
173
+ - Screens render wherever Shell's page states render: the catch-all route for unknown paths,
174
+ `src/app/(app)/error.tsx` and `src/app/not-found.tsx`.
175
+ - If a replacement throws, the default renders instead and the console names it.
176
+ - Never render raw error messages; they can leak server details.
177
+
178
+ ## Make a part of your feature replaceable
179
+
180
+ Declare the part as a single slot and render it with your default:
181
+
182
+ ```ts
183
+ // src/plugins/billing/slots/plan-card.ts
184
+ import { defineSlot } from '@bitakit/core';
185
+
186
+ // A replaceable part: one plugin may render the plan card instead of billing's default.
187
+ export default defineSlot({ accepts: 'component', policy: 'single' });
188
+ ```
189
+
190
+ ```tsx
191
+ // in src/plugins/billing/ui/pages/index.tsx
192
+ <PluginSlot name="billing.plan-card" fallback={<DefaultPlanCard />} />
193
+ ```
194
+
195
+ Another plugin replaces it with `ui/slots/billing.plan-card.tsx`; the billing folder stays
196
+ unchanged. Add `payload` to the slot when the replacement needs data, and memoize the payload
197
+ object at the outlet.
198
+
199
+ ## Who wins
200
+
201
+ 1. `choose` in `bitakit.config.ts` (`'<plugin>'`, `'<plugin>:<variant>'` or `'<variant>'`).
202
+ 2. The app's own file (`src/layouts/...`, `src/ui/slots/...`) beats plugins and packages.
203
+ 3. The only remaining candidate.
204
+ 4. Several candidates and no decision: the owner's default renders, the console reports the
205
+ candidates once and `npx bitakit doctor` asks for a decision.
206
+
207
+ ## Check it
208
+
209
+ 1. `npm run typecheck`, `npx bitakit slots` (each part says which candidate renders) and
210
+ `npx bitakit doctor` ("Replaceable parts are decided").
211
+ 2. Open a page of the family (`/account/login`), an unknown path (`/nowhere`) for the
212
+ not-found screen, and every page that uses header slots after replacing the frame.
213
+
214
+ ## Explain it to the user
215
+
216
+ Name the part and the file: "the sign-in pages use the `auth` layout family; `src/layouts/
217
+ auth/split.tsx` replaces Shell's default, chosen in `bitakit.config.ts`." Say what still uses
218
+ the default and how to switch back: delete the file (or the `choose` entry) and Shell's
219
+ default returns.
@@ -0,0 +1,63 @@
1
+ # Keep a plugin's guide with its code
2
+
3
+ Read the owning plugin's `AGENTS.md` before extending it. `bitakit add plugin` writes one
4
+ beside its source and a `CLAUDE.md` containing only `@AGENTS.md`. Standalone plugin packages
5
+ have these files at the package root. Discovery ignores both Markdown files.
6
+
7
+ ## What to maintain
8
+
9
+ Keep the actual purpose, public IDs and payloads, extension points, non-obvious constraints
10
+ and relevant checks with that plugin. Update changed facts in the same task as the code.
11
+ Remove superseded descriptions rather than appending a second version of the contract.
12
+
13
+ Do not invent contracts to fill headings. A page-only plugin needs no service documentation.
14
+ An internal refactor that preserves the documented behavior may need no guide change.
15
+ Preserve team-authored instructions and keep shared BitaKit rules in the app's guide and skill.
16
+ The app-root `init --update-agent-files` refresh does not maintain plugin guides for you.
17
+
18
+ ## Example: document the Bookmarks feature
19
+
20
+ After implementing [worked-example.md](worked-example.md), replace the generated starter
21
+ description in `src/plugins/bookmarks/AGENTS.md` with the implemented feature's facts:
22
+
23
+ ```markdown
24
+ # Bookmarks
25
+
26
+ Save links, open them and remove them from `/bookmarks`.
27
+
28
+ ## Public contracts
29
+
30
+ - `bookmarks.list` (`services/list.ts`) owns in-memory `bookmarks` with `id`, `title` and
31
+ `url`. Its `add(url)` and `remove(id)` methods update the store and emit events.
32
+ - `bookmarks.add` takes a URL string; `bookmarks.remove` takes an ID and asks for confirmation.
33
+ `bookmarks.open` links to `/bookmarks` in `shell.navigation`.
34
+ - `bookmarks.added` carries `{ id, url }`; `bookmarks.removed` carries `{ id }`.
35
+ - `bookmarks.openInNewTab` controls how links open; App Preferences renders the setting at
36
+ `/settings/bookmarks`.
37
+
38
+ ## Constraints and checks
39
+
40
+ The list is in browser memory and resets on reload. The `openInNewTab` preference uses the
41
+ app's settings storage. This version has no server persistence or access-control contract.
42
+
43
+ From the app root, run its typecheck and `npx bitakit doctor`; run the Bookmarks test when
44
+ the documented test setup is installed. In `/bookmarks`, save a URL and confirm removal.
45
+ Change `openInNewTab` in Settings and check the link's target.
46
+ ```
47
+
48
+ The example describes only the in-memory version. After following the API recipe, update
49
+ the ownership and persistence paragraph, the `reload` Action and its checks to match that
50
+ implementation. A server-memory example still resets on server restart; do not call it a
51
+ durable database.
52
+
53
+ ## Example: extend one feature from another
54
+
55
+ If a new `sharing` plugin calls `bookmarks.list` and contributes a toolbar Action:
56
+
57
+ - `sharing/AGENTS.md` describes its Action, required service, target slot and checks.
58
+ - `bookmarks/AGENTS.md` changes only if Bookmarks gains a public contract, such as a new
59
+ owned slot with an actual outlet. Document the slot's ID and accepted contribution there.
60
+ - The general app guide and skill keep the ownership rule; neither becomes a catalog of
61
+ `sharing` or `bookmarks` internals.
62
+
63
+ Keep `CLAUDE.md` as the import; edit the shared instructions in `AGENTS.md` once.