@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.
@@ -23,6 +23,8 @@ npx bitakit add plugin about
23
23
  check), and `app` is the app's own plugin ID, so `bitakit generate` rejects it as a duplicate.
24
24
  `npx bitakit info` lists the existing plugin IDs.
25
25
  - The CLI never overwrites. It stops when the folder or file already exists.
26
+ - Every `add plugin` mode also writes `AGENTS.md` and a `CLAUDE.md` importing it. Update the
27
+ plugin's local guide as its starter becomes a feature; see [plugin-guides.md](plugin-guides.md).
26
28
 
27
29
  ## Folder = feature, file path = ID
28
30
 
@@ -121,18 +123,13 @@ export default function TodoPage({ params }: { params: { id: string } }) {
121
123
 
122
124
  ## Choose a layout
123
125
 
124
- ```sh
125
- npx bitakit add layout full-page
126
- ```
127
-
128
- Replace the template in `src/layouts/full-page.tsx` with `import { AppShell } from '@bitakit/shell';`
129
- and `export default AppShell.FullPage;`. A page opts in with one export:
126
+ A page names its layout family with one export; the family's layout wraps the page:
130
127
 
131
128
  ```tsx
132
129
  'use client';
133
130
  import { PageHeader } from '@bitakit/ui/components';
134
131
 
135
- // The name of src/layouts/full-page.tsx: this page renders without the sidebar and header.
132
+ // This page renders without the sidebar and header, with the normal page spacing.
136
133
  export const layout = 'full-page';
137
134
 
138
135
  export default function AboutTeamPage() {
@@ -140,13 +137,15 @@ export default function AboutTeamPage() {
140
137
  }
141
138
  ```
142
139
 
143
- - Values: no export or `'app'` for the normal frame, `'blank'` for a bare page, or the file name
144
- of a layout in `src/layouts/<name>.tsx`. An unknown name stops startup with an error that names the
145
- missing `src/layouts/<name>.tsx` and the valid choices.
140
+ - Values: no export or `'app'` for the normal frame, `'blank'` for a bare page, Shell's
141
+ `'auth'`, `'error'` and `'full-page'`, or a family of the app such as `'onboarding'`
142
+ (`src/layouts/onboarding.tsx`). An unknown name stops startup with an error that names the
143
+ files to add and the known families.
146
144
  - Shell's `AppShell` applies the choice. In an app without Shell, read its layout before relying
147
145
  on `export const layout`.
148
- - `AppShell.FullPage` keeps Shell's page spacing and the `shell.content.before/after` regions;
149
- `'blank'` keeps nothing.
146
+ - To change how a family looks, replace its layout: `npx bitakit add layout full-page` writes
147
+ `src/layouts/full-page.tsx`, which wins over Shell's default. Variants, choosing between them
148
+ and replacing the whole frame are in [layouts-and-screens.md](layouts-and-screens.md).
150
149
 
151
150
  ## Link the page in the sidebar
152
151
 
@@ -35,9 +35,11 @@ export default defineSlot({ accepts: 'actions' });
35
35
  `slots/row.menu.ts` are both `todos.row.menu`.
36
36
  - The command writes `accepts: 'component'`. Set `accepts` to what the slot takes: `'actions'`
37
37
  (buttons, links, menu items), `'component'` (React widgets) or `'data'` (needs a `schema`).
38
- - `policy` is `'list'` by default. `'single'` allows one occupant; a second one fails as a
39
- conflict. `'keyed'` requires a unique `key` per contribution (a repeated key fails as a
40
- conflict); the outlet picks one with `entryKey`.
38
+ - `policy` is `'list'` by default: every contribution renders. `'single'` is a replaceable
39
+ part: several plugins may offer a candidate, one renders (the app's `choose` entry, else the
40
+ app's own file, else the only candidate) and the outlet's `fallback` is the default; see
41
+ [layouts-and-screens.md](layouts-and-screens.md). `'keyed'` requires a unique `key` per
42
+ contribution (a repeated key fails as a conflict); the outlet picks one with `entryKey`.
41
43
  - `payload` is a schema for context the owner passes to every outlet, such as a row ID.
42
44
  - A declaration renders nothing. The owner also mounts an outlet (next section).
43
45
 
@@ -68,8 +70,11 @@ function TodosToolbar() {
68
70
  - Each item has `key`, `plugin`, `order`, `actionId`, `input` and `action` (the live control).
69
71
  Use `item.key` as the React key and pass `item.action` to `<Action id>`.
70
72
  - An empty `<Button />` gets the Action's icon, title, disabled and pending state.
71
- - `useSlot` also returns `payload`, `pending`, `phase`, `error` and `diagnostics`. Items stay
72
- empty while the slot is pending.
73
+ - `useSlot` also returns `payload`, `pending`, `phase`, `policy`, `error` and `diagnostics`.
74
+ Items stay empty while the slot is pending, except that a single slot already shows its
75
+ selected file candidate.
76
+ - `<PluginSlot name fallback={<Default />}>{children}</PluginSlot>`: `fallback` renders while
77
+ nothing is placed, and `children` reach the contribution (a layout wraps the page).
73
78
  - For a slot with a payload, pass it at every outlet:
74
79
  `useSlot('todos.row.menu', { payload: { todoId: todo.id } })` or
75
80
  `<PluginSlot name="sidebar.footer" payload={{ collapsed }} />`. Memoize payload objects
@@ -129,16 +134,18 @@ export default defineAction({
129
134
 
130
135
  The Shell layout is the `shell.layout` setting (`sidebar` or `navbar`).
131
136
 
132
- | Slot | Accepts | Where it renders |
133
- | -------------------------------------------------- | ------------------------------------------- | ---------------------------------------------------- |
134
- | `shell.navigation` | Actions, usually with `href` (`todos.open`) | Sidebar menu, or the top menu in `navbar` |
135
- | `shell.toolbar` | Actions | Header, right side, both layouts |
136
- | `app-bar.end` | component | Header, right side, before the toolbar, both layouts |
137
- | `shell.header.end` | component | Header, right side, after the toolbar, both layouts |
138
- | `shell.header.start`, `shell.header.center` | component | Header left / center, both layouts |
139
- | `shell.content.before`, `shell.content.after` | component | Above / below every page, both layouts |
140
- | `shell.footer` | component | Page footer, both layouts |
141
- | `sidebar.header`, `sidebar.body`, `sidebar.footer` | component, payload `{ collapsed }` | `sidebar` layout only |
137
+ | Slot | Accepts | Where it renders |
138
+ | ------------------------------------------------------------------------ | ------------------------------------------- | ---------------------------------------------------- |
139
+ | `shell.navigation` | Actions, usually with `href` (`todos.open`) | Sidebar menu, or the top menu in `navbar` |
140
+ | `shell.toolbar` | Actions | Header, right side, both layouts |
141
+ | `app-bar.end` | component | Header, right side, before the toolbar, both layouts |
142
+ | `shell.header.end` | component | Header, right side, after the toolbar, both layouts |
143
+ | `shell.header.start`, `shell.header.center` | component | Header left / center, both layouts |
144
+ | `shell.content.before`, `shell.content.after` | component | Above / below every page, both layouts |
145
+ | `shell.footer` | component | Page footer, both layouts |
146
+ | `sidebar.header`, `sidebar.body`, `sidebar.footer` | component, payload `{ collapsed }` | `sidebar` layout only |
147
+ | `layout.app`, `layout.auth`, `layout.error`, `layout.full-page` | component, single (replaceable) | The frame of a layout family |
148
+ | `screen.not-found`, `screen.error`, `screen.forbidden`, `screen.loading` | component, single | Shell's page states, everywhere they render |
142
149
 
143
150
  - Put header widgets in `shell.header.end` (the summary example). Use `shell.toolbar` for
144
151
  header buttons, so they keep the Shell's standard Button.
@@ -153,8 +160,10 @@ The Shell layout is the `shell.layout` setting (`sidebar` or `navbar`).
153
160
  page is open, and the selected Shell layout renders that slot.
154
161
  - Log `useSlot('todos.toolbar').diagnostics` in the outlet. `reason` is `ready`, `empty`,
155
162
  `filtered`, `initializing`, `validating-payload`, `update-pending`, `owner-unavailable`,
156
- `invalid-payload` or `binding-error`. `excluded` lists each skipped entry with its `id`,
157
- `plugin` and `reason` (`key`, `condition`, `action-hidden` or `action-unavailable`).
163
+ `invalid-payload`, `binding-error`, or for a single slot `ambiguous` (several candidates, no
164
+ decision) and `choice-unavailable`. `excluded` lists each skipped entry with its `id`,
165
+ `plugin` and `reason` (`key`, `condition`, `action-hidden`, `action-unavailable` or
166
+ `not-selected`); `candidates` lists a single slot's candidates by the names `choose` accepts.
158
167
  - Run `npx bitakit doctor`: it warns when a `ui/slots` file targets a slot nobody declares.
159
168
  - Use only declared names: `npx bitakit slots` lists them. When no outlet exists where the user
160
169
  wants content, the owning plugin declares a slot and renders it.
@@ -1,9 +1,9 @@
1
1
  # Check the work: typecheck, doctor, tests and preview
2
2
 
3
- Use this after every change and before telling the user it works. Report only the checks you
4
- actually ran.
3
+ Use this to verify changed behavior, runnable examples or UI. For prose-only changes, check
4
+ links and claims against source instead. Report only the checks you actually ran.
5
5
 
6
- ## Run typecheck and doctor (always)
6
+ ## Run typecheck and Doctor for implementation changes
7
7
 
8
8
  ```sh
9
9
  npm run typecheck
@@ -15,16 +15,19 @@ npx bitakit doctor --json
15
15
  same three steps yourself: `npx bitakit generate`, the framework step, `npx tsc --noEmit`.
16
16
  - Doctor prints `{ project, results: [{ status, title, details?, fix? }], errors, warnings }`.
17
17
  `status` is `ok`, `warn` or `error`; `details` is a list of strings. It exits 1 when `errors` is
18
- above 0; warnings keep exit 0. Apply the `fix` it names before guessing.
18
+ above 0; warnings keep exit 0. Inspect its suggested fix against the requested scope; report
19
+ unrelated findings separately instead of expanding the task to repair the whole app.
19
20
  - Doctor checks wiring statically (versions, provider, routes, links, service names, styles, slot
20
21
  file targets). It renders nothing.
21
22
  - When the starting state is unknown, run both before editing, so an existing error is not
22
23
  blamed on your change.
23
24
 
24
- ## Add a test runner (ask first)
25
+ ## Use or add the test setup
25
26
 
26
- Generated apps have no test runner and no `test` script. Tell the user, and ask before adding
27
- test files or dependencies. When they agree, generate the first test:
27
+ Inspect the app's scripts first and reuse an existing runner. A fresh create-app app has no
28
+ `test` script; standalone plugin packages already have one. If the requested work authorizes
29
+ tests and their setup, proceed without asking again. Otherwise resolve any missing approval
30
+ for new dependencies. Generate the first test in an app with:
28
31
 
29
32
  ```sh
30
33
  npx bitakit add test <plugin>
@@ -136,8 +139,8 @@ when missing:
136
139
  runtime state (`ready` when startup finished), `[bitakit]` errors, console and page errors
137
140
  and failed requests. Exit code 1 means it saw an error. Add `--base-url http://localhost:<port>`
138
141
  when the server uses another port. It needs Playwright in the project: when it exits with 2,
139
- ask the user before running the install commands it prints. It does not click, so give the
140
- user the clicks and the expected result and report interactions as not verified.
142
+ follow the user's existing installation authorization or obtain it if missing. It does not
143
+ click, so give the user the clicks and expected result and report interactions as not verified.
141
144
 
142
145
  - An HTTP 200 or the server HTML proves nothing. The catch-all route
143
146
  `src/app/(app)/[...path]/page.tsx` answers every path, and plugin pages and slots render only
@@ -0,0 +1,312 @@
1
+ # Worked example: a Bookmarks feature from scratch
2
+
3
+ Use this as the model for a new feature: plan it, create the files, check it and report. The
4
+ feature lets users save links, open them and remove them. Every file below passes
5
+ `npm run typecheck` and `npx bitakit doctor` in a create-app app with Shell and App Preferences.
6
+
7
+ ## 1. Plan before writing code
8
+
9
+ Map what the user asked for to BitaKit mechanisms, then tell the user the plan in one or two
10
+ sentences.
11
+
12
+ | The user wants | Mechanism | File in `src/plugins/bookmarks/` |
13
+ | -------------------------------- | ---------------------------- | -------------------------------- |
14
+ | A page listing saved links | Page | `ui/pages/index.tsx` |
15
+ | The list, shared by page/Actions | Service with a `store()` | `services/list.ts` |
16
+ | Save and Remove buttons | Actions | `actions/add.ts`, `remove.ts` |
17
+ | A link in the navigation | Navigation Action | `actions/open.ts` |
18
+ | "Open links in a new tab" | Setting | `settings.ts` |
19
+ | Other features may react | Events `added` and `removed` | `events.ts` |
20
+
21
+ ## 2. Create the files
22
+
23
+ ```sh
24
+ npx bitakit add plugin bookmarks
25
+ npx bitakit add service bookmarks/list
26
+ npx bitakit add events bookmarks
27
+ npx bitakit add action bookmarks/add
28
+ npx bitakit add action bookmarks/remove
29
+ npx bitakit add settings bookmarks
30
+ ```
31
+
32
+ The commands write templates; replace each body with the code below and remove the tutorial
33
+ comments.
34
+
35
+ ## 3. Events
36
+
37
+ `src/plugins/bookmarks/events.ts`:
38
+
39
+ ```ts
40
+ import { defineEvents, event } from '@bitakit/core';
41
+
42
+ // Other plugins listen with events.on('bookmarks.added', ...); payloads carry what changed.
43
+ export default defineEvents({
44
+ added: event<{ id: string; url: string }>(),
45
+ removed: event<{ id: string }>(),
46
+ });
47
+ ```
48
+
49
+ ## 4. Service
50
+
51
+ `src/plugins/bookmarks/services/list.ts`:
52
+
53
+ ```ts
54
+ import { defineService } from '@bitakit/core';
55
+
56
+ export type Bookmark = { id: string; title: string; url: string };
57
+
58
+ // Saved links. They live in memory until the service loads and saves them through an API.
59
+ export default defineService(({ store, events }) => {
60
+ const state = store<{ bookmarks: Bookmark[] }>({ bookmarks: [] });
61
+ return {
62
+ state,
63
+ add(url: string) {
64
+ const address = new URL(url);
65
+ const bookmark = { id: crypto.randomUUID(), title: address.hostname, url: address.href };
66
+ state.set((current) => ({ bookmarks: [...current.bookmarks, bookmark] }));
67
+ events.emit('bookmarks.added', { id: bookmark.id, url: bookmark.url });
68
+ },
69
+ remove(id: string) {
70
+ state.set((current) => ({
71
+ bookmarks: current.bookmarks.filter((bookmark) => bookmark.id !== id),
72
+ }));
73
+ events.emit('bookmarks.removed', { id });
74
+ },
75
+ };
76
+ });
77
+ ```
78
+
79
+ - The service owns the data; pages and Actions only read it and call its methods.
80
+ - `state.set` builds a new array each time; events go out after the change.
81
+
82
+ ## 5. Actions
83
+
84
+ `src/plugins/bookmarks/actions/add.ts`:
85
+
86
+ ```ts
87
+ import { defineAction } from '@bitakit/core';
88
+
89
+ export default defineAction<string>({
90
+ title: 'Save',
91
+ // The button stays disabled until the field holds a full URL such as https://example.com.
92
+ enabled: ({ input }) => URL.canParse(input?.trim() ?? ''),
93
+ execute: ({ services, input }) => services.bookmarks.list.add(input.trim()),
94
+ success: 'Bookmark saved',
95
+ });
96
+ ```
97
+
98
+ `src/plugins/bookmarks/actions/remove.ts`:
99
+
100
+ ```ts
101
+ import { defineAction } from '@bitakit/core';
102
+
103
+ export default defineAction<string>({
104
+ title: 'Remove',
105
+ // Each row has its own pending state.
106
+ concurrency: 'per-input',
107
+ confirm: ({ input, services }) => ({
108
+ title: `Remove ${
109
+ services.bookmarks.list.state.get().bookmarks.find((bookmark) => bookmark.id === input)
110
+ ?.title ?? 'this bookmark'
111
+ }?`,
112
+ description: 'The link is deleted from your bookmarks.',
113
+ destructive: true,
114
+ }),
115
+ execute: ({ services, input }) => services.bookmarks.list.remove(input),
116
+ });
117
+ ```
118
+
119
+ `src/plugins/bookmarks/actions/open.ts` (written by `add plugin`; shown tidied):
120
+
121
+ ```ts
122
+ import { defineAction } from '@bitakit/core';
123
+
124
+ // The navigation entry; the page is ui/pages/index.tsx.
125
+ export default defineAction({
126
+ title: 'Bookmarks',
127
+ href: '/bookmarks',
128
+ slots: ['shell.navigation'],
129
+ });
130
+ ```
131
+
132
+ - A confirmation object needs both `title` and `description`.
133
+ - `per-input` lets two rows be removed at once; the default `exclusive` would block the second.
134
+
135
+ ## 6. Setting
136
+
137
+ `src/plugins/bookmarks/settings.ts`:
138
+
139
+ ```ts
140
+ import { defineSettings, setting } from '@bitakit/core';
141
+
142
+ export default defineSettings(
143
+ { openInNewTab: setting({ default: true, label: 'Open bookmarks in a new tab' }) },
144
+ { title: 'Bookmarks' },
145
+ );
146
+ ```
147
+
148
+ This adds the page `/settings/bookmarks` with a switch; no UI code is needed.
149
+
150
+ ## 7. Page
151
+
152
+ `src/plugins/bookmarks/ui/pages/index.tsx`:
153
+
154
+ ```tsx
155
+ 'use client';
156
+ import { useState } from 'react';
157
+ import { Action, useServiceState, useSetting } from '@bitakit/ui';
158
+ import {
159
+ Button,
160
+ Input,
161
+ Item,
162
+ ItemActions,
163
+ ItemContent,
164
+ ItemDescription,
165
+ ItemGroup,
166
+ ItemTitle,
167
+ PageHeader,
168
+ } from '@bitakit/ui/components';
169
+
170
+ // Served at /bookmarks. State comes from the bookmarks.list service; buttons run Actions.
171
+ export default function BookmarksPage() {
172
+ const [url, setUrl] = useState('');
173
+ const bookmarks = useServiceState('bookmarks.list', (state) => state.bookmarks, []);
174
+ const openInNewTab = useSetting('bookmarks.openInNewTab').value;
175
+ return (
176
+ <div className="flex flex-col gap-6">
177
+ <PageHeader title="Bookmarks" subtitle="Links you want to come back to." />
178
+ <form className="flex gap-2" onSubmit={(event) => event.preventDefault()}>
179
+ <Input
180
+ value={url}
181
+ type="url"
182
+ placeholder="https://example.com"
183
+ aria-label="Link to save"
184
+ onChange={(event) => setUrl(event.target.value)}
185
+ />
186
+ {/* Clear the field only when the bookmark was saved. */}
187
+ <Action
188
+ id="bookmarks.add"
189
+ input={url}
190
+ onExecuted={(result) => result.status === 'completed' && setUrl('')}
191
+ >
192
+ <Button type="submit" />
193
+ </Action>
194
+ </form>
195
+ {bookmarks.length ? (
196
+ <ItemGroup>
197
+ {bookmarks.map((bookmark) => (
198
+ <Item key={bookmark.id} variant="outline">
199
+ <ItemContent>
200
+ <ItemTitle>
201
+ <a
202
+ href={bookmark.url}
203
+ {...(openInNewTab ? { target: '_blank', rel: 'noreferrer' } : {})}
204
+ >
205
+ {bookmark.title}
206
+ </a>
207
+ </ItemTitle>
208
+ <ItemDescription>{bookmark.url}</ItemDescription>
209
+ </ItemContent>
210
+ <ItemActions>
211
+ <Action id="bookmarks.remove" input={bookmark.id}>
212
+ <Button variant="outline" size="sm" />
213
+ </Action>
214
+ </ItemActions>
215
+ </Item>
216
+ ))}
217
+ </ItemGroup>
218
+ ) : (
219
+ <p className="text-sm text-muted-foreground">No bookmarks yet. Paste a link above.</p>
220
+ )}
221
+ </div>
222
+ );
223
+ }
224
+ ```
225
+
226
+ - A submit button inside a `<form>` lets Enter save; the Action supplies the label, the disabled
227
+ state and the pending state, so the page sets none of them.
228
+ - The empty `<Button />` children get the Action titles ("Save", "Remove").
229
+ - The page has an empty state; with an API it also needs loading and error states
230
+ ([data-and-api.md](data-and-api.md)).
231
+
232
+ ## 8. Check it
233
+
234
+ 1. `npm run typecheck`, then `npx bitakit doctor`.
235
+ 2. Open `/bookmarks` in the running app. Type `https://nextjs.org/docs` and press Enter: the row
236
+ appears and the field clears. With an empty field, Save is disabled.
237
+ 3. Click Remove: a dialog asks "Remove nextjs.org?"; Confirm empties the list.
238
+ 4. Open `/settings/bookmarks` and switch off "Open bookmarks in a new tab"; links now open in the
239
+ same tab.
240
+
241
+ ## 9. Test it (when the app has a test runner)
242
+
243
+ Reuse the app's runner or complete its authorized setup
244
+ ([testing-and-preview.md](testing-and-preview.md)), then run
245
+ `npx bitakit add test bookmarks` and replace the body. `tests/bookmarks.test.ts`:
246
+
247
+ ```ts
248
+ import assert from 'node:assert/strict';
249
+ import test from 'node:test';
250
+ import { defineContract, definePlugin, defineSlot, getService } from '@bitakit/core';
251
+ import { mountPlugin } from '@bitakit/core/testing';
252
+ import type list from '../src/plugins/bookmarks/services/list';
253
+
254
+ const bookmarks = defineContract('bookmarks.list').of<ReturnType<typeof list.create>>();
255
+ // bookmarks.open targets shell.navigation; this stand-in owns that slot so the plugin starts without Shell.
256
+ const shell = definePlugin({
257
+ id: 'shell',
258
+ slots: { navigation: defineSlot({ accepts: 'actions' }) },
259
+ });
260
+
261
+ test('saving and removing a bookmark updates the list and emits events', async () => {
262
+ const plugin = await mountPlugin('src/plugins/bookmarks', { plugins: [shell] });
263
+ try {
264
+ const list = getService(plugin.services, bookmarks);
265
+
266
+ assert.equal((await plugin.execute('add', 'https://example.com/docs')).status, 'completed');
267
+ const [saved] = list.state.get().bookmarks;
268
+ assert.equal(saved?.title, 'example.com');
269
+ assert.deepEqual(plugin.events.recorded.at(-1), {
270
+ type: 'bookmarks.added',
271
+ data: { id: saved?.id, url: 'https://example.com/docs' },
272
+ });
273
+
274
+ // The enabled rule blocks text that is not a URL, so nothing is saved.
275
+ assert.equal((await plugin.execute('add', 'not a link')).status, 'skipped');
276
+ assert.equal(list.state.get().bookmarks.length, 1);
277
+
278
+ list.remove(saved!.id);
279
+ assert.deepEqual(list.state.get().bookmarks, []);
280
+ assert.equal(plugin.events.recorded.at(-1)?.type, 'bookmarks.removed');
281
+ } finally {
282
+ await plugin.stop();
283
+ }
284
+ });
285
+ ```
286
+
287
+ - A disabled Action resolves to `{ status: 'skipped' }`; a failing one rejects.
288
+ - `remove` has a confirmation, so the test calls the service method directly.
289
+
290
+ ## 10. Update the plugin guide and report
291
+
292
+ Replace the starter description in `src/plugins/bookmarks/AGENTS.md` with the implemented
293
+ contracts and checks, following [plugin-guides.md](plugin-guides.md). Keep `CLAUDE.md` as
294
+ the import; do not copy this feature's specification into the general app skill.
295
+
296
+ A good report names what changed, where it appears, how it connects and what was checked:
297
+
298
+ > I added a **Bookmarks** feature in `src/plugins/bookmarks`. It appears as "Bookmarks" in the
299
+ > navigation and at `/bookmarks`: paste a link and press Enter to save it, and use Remove to
300
+ > delete it after a confirmation. The `bookmarks.list` service holds the links, the Save and
301
+ > Remove buttons are the Actions `bookmarks.add` and `bookmarks.remove`, and other features can
302
+ > react to `bookmarks.added` and `bookmarks.removed`. "Open bookmarks in a new tab" is under
303
+ > Settings → Bookmarks. Typecheck and doctor pass, and I tried save, remove and the setting in the
304
+ > browser. The links live in memory, so a reload clears them until we save them through an API.
305
+
306
+ ## Extend it
307
+
308
+ - Save the links on a server: [data-and-api.md](data-and-api.md) continues this example.
309
+ - Show the count in the Shell header: contribute `ui/slots/shell.header.end.tsx`
310
+ ([slots.md](slots.md)).
311
+ - React in another feature: listen to `bookmarks.added` in that feature's service
312
+ ([services-and-events.md](services-and-events.md)).
package/src/add.mjs CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import ts from 'typescript';
4
4
  import { contributionSegments, describeBitaKit, describeModule } from '@bitakit/discovery';
5
5
  import { exists, findProject } from './project.mjs';
6
+ import { appPluginAgentRules, claudeFileFor } from './agent-rules.mjs';
6
7
  import {
7
8
  actionFile,
8
9
  configFile,
@@ -67,7 +68,11 @@ export async function addPlugin(name, { cwd, minimal = false, example = false }
67
68
  : example
68
69
  ? pluginFiles(name, { navigationSlot })
69
70
  : starterFiles(name, { navigationSlot });
70
- const created = await writeNewFiles(root, files);
71
+ const created = await writeNewFiles(root, {
72
+ ...files,
73
+ 'AGENTS.md': appPluginAgentRules(name, files, { navigationSlot }),
74
+ 'CLAUDE.md': claudeFileFor(),
75
+ });
71
76
  return {
72
77
  project,
73
78
  root,
@@ -108,21 +113,12 @@ const singleFile = {
108
113
  * `events` takes only the plugin: a plugin declares its events once in `events.ts`. `test` also
109
114
  * takes only an existing plugin of an app and writes `tests/<plugin>.test.ts` at the app root.
110
115
  */
111
- export async function addContribution(kind, target, { cwd } = {}) {
116
+ export async function addContribution(kind, target, { cwd, plugin: layoutPlugin } = {}) {
112
117
  if (!contributionKinds.includes(kind))
113
118
  throw new Error(`Unknown kind "${kind}". Use ${contributionKinds.join(', ')}.`);
114
119
  const project = await configuredProject(cwd);
115
120
  if (kind === 'test') return addTest(project, target);
116
- if (kind === 'layout') {
117
- if (project.kind !== 'app')
118
- throw new Error('Layouts belong to the app: run "bitakit add layout <name>" inside an app.');
119
- if (!target) throw new Error('Name the layout, for example "bitakit add layout admin".');
120
- validateName(target, 'layout name');
121
- const created = await writeNewFiles(project.appDirectory, {
122
- [`layouts/${target}.tsx`]: layoutFile(target),
123
- });
124
- return { project, created, id: target, path: undefined };
125
- }
121
+ if (kind === 'layout') return addLayout(project, target, layoutPlugin);
126
122
  const single = Object.hasOwn(singleFile, kind);
127
123
  const example = single
128
124
  ? `bitakit add ${kind} notes`
@@ -194,6 +190,43 @@ export async function addContribution(kind, target, { cwd } = {}) {
194
190
  };
195
191
  }
196
192
 
193
+ /**
194
+ * `bitakit add layout <family>[/<variant>]`: a candidate for the `layout.<family>` slot, in the
195
+ * app's `src/layouts`, an app plugin's `ui/layouts` (`--plugin`) or a plugin package's `ui/layouts`.
196
+ */
197
+ async function addLayout(project, target, plugin) {
198
+ if (!target)
199
+ throw new Error(
200
+ 'Name the layout family, for example "bitakit add layout auth" or "bitakit add layout auth/split".',
201
+ );
202
+ const [family, variant, ...rest] = target.split('/');
203
+ if (rest.length) throw new Error(`Use "<family>" or "<family>/<variant>", not "${target}".`);
204
+ validateName(family, 'layout family');
205
+ if (variant !== undefined) validateName(variant, 'layout variant');
206
+ const file = `${variant === undefined ? family : `${family}/${variant}`}.tsx`;
207
+ let root;
208
+ let folder = 'ui/layouts';
209
+ if (project.kind === 'plugin') {
210
+ if (plugin)
211
+ throw new Error('Inside a plugin package, run "bitakit add layout" without --plugin.');
212
+ root = project.moduleRoot;
213
+ } else if (plugin) {
214
+ validateName(plugin, 'plugin name');
215
+ root = path.join(project.pluginsDirectory, plugin);
216
+ if (!(await exists(root)))
217
+ throw new Error(
218
+ `There is no plugin "${plugin}". Create it first: bitakit add plugin ${plugin}.`,
219
+ );
220
+ } else {
221
+ root = project.appDirectory;
222
+ folder = 'layouts';
223
+ }
224
+ const created = await writeNewFiles(root, {
225
+ [`${folder}/${file}`]: layoutFile(family, variant),
226
+ });
227
+ return { project, created, id: `layout.${family}`, plugin, path: undefined };
228
+ }
229
+
197
230
  /** What `mountPlugin` needs under Node besides `@bitakit/core`, as the testing guide lists it. */
198
231
  const testDependencies = ['@bitakit/discovery', 'jiti', 'typescript', '@types/node'];
199
232
 
@@ -45,8 +45,8 @@ export async function projectAgentRules(project) {
45
45
  }
46
46
 
47
47
  /**
48
- * Claude Code reads `CLAUDE.md`, not `AGENTS.md`, so the app's `CLAUDE.md` imports the rules with
49
- * `@AGENTS.md`. Returns the file to write: a new one, or `existing` with the import appended;
48
+ * Import the shared rules for Claude Code sessions that do not load `AGENTS.md` directly.
49
+ * Returns the file to write: a new one, or `existing` with the import appended;
50
50
  * `existing` is returned unchanged when it already imports AGENTS.md.
51
51
  */
52
52
  export function claudeFileFor(existing) {
@@ -55,6 +55,47 @@ export function claudeFileFor(existing) {
55
55
  return /^@AGENTS\.md\s*$/m.test(text) ? existing : `${text.trimEnd()}\n\n@AGENTS.md\n`;
56
56
  }
57
57
 
58
+ /** A new app plugin's editable guide; file paths come from its actual scaffold. */
59
+ export function appPluginAgentRules(id, files, { navigationSlot } = {}) {
60
+ const details = {
61
+ 'services/list.ts': `Service \`${id}.list\` owns in-memory \`entries\` (\`id\`, \`title\`) and the \`add\`/\`remove\` methods.`,
62
+ 'events.ts': `Declares \`${id}.changed\` with \`{ kind: 'added' | 'removed' }\`.`,
63
+ 'actions/add.ts': `Action \`${id}.add\` takes a title string and adds an entry.`,
64
+ 'actions/remove.ts': `Action \`${id}.remove\` takes an entry ID and removes it.`,
65
+ 'actions/clear.ts': `Action \`${id}.clear\` confirms before removing all entries.`,
66
+ 'actions/open.ts': `Action \`${id}.open\` links to \`/${id}\`${navigationSlot ? ` through \`${navigationSlot}\`` : ''}.`,
67
+ 'ui/pages/index.tsx': `Page at \`/${id}\`.`,
68
+ };
69
+ return `# ${id} plugin
70
+
71
+ This folder owns the \`${id}\` feature. ${Object.hasOwn(files, 'services/list.ts') ? 'The starter manages an in-memory entry list; data is lost on reload.' : 'The starter provides a page to build the feature on.'}
72
+ Follow the app's root \`AGENTS.md\` and \`bitakit-app-development\` skill for shared conventions.
73
+
74
+ ## Files and contracts
75
+
76
+ Paths are relative to this folder; discovery connects these files automatically.
77
+
78
+ ${Object.keys(files)
79
+ .sort()
80
+ .map((file) => `- \`${file}\`: ${details[file]}`)
81
+ .join('\n')}
82
+
83
+ ## Maintenance
84
+
85
+ Replace the starter description as the feature develops. Keep this plugin's purpose, public
86
+ contracts, extension points, constraints and test instructions here, alongside its code.
87
+ Update this guide when they change; document other plugins in their own folders.
88
+ \`CLAUDE.md\` imports this file, so maintain the instructions only here.
89
+
90
+ ## Checks
91
+
92
+ From the app root, run \`npx bitakit generate\`, \`npx bitakit doctor\`, and the app's existing
93
+ typecheck and test scripts from \`package.json\`.
94
+ To add a headless test, run \`npx bitakit add test ${id}\` and follow its printed setup and test
95
+ commands.${Object.hasOwn(files, 'ui/pages/index.tsx') ? ' Exercise changed UI in the running app.' : ''}
96
+ `;
97
+ }
98
+
58
99
  /**
59
100
  * The guidance block for coding assistants in an app's AGENTS.md, shared by create-app and
60
101
  * `bitakit init`. Ordered by learning level: where each task goes first, then the rules, then
@@ -88,7 +129,8 @@ the file path is the ID. Discovery generates \`src/bitakit.gen.*\`; there is no
88
129
  React only under \`ui/\`. Use \`@bitakit/ui/components\` and the app theme; do not restyle locally or
89
130
  import package CSS from JavaScript (discovery writes \`src/bitakit.gen.css\`).
90
131
  - Do not rebuild what BitaKit provides: no own registries, event buses, settings stores or button state.
91
- ${shell ? "- Shell: place an Action with `slots: ['shell.navigation']` or `['shell.toolbar']`; header content goes in `ui/slots/shell.header.end.tsx`.\n" : ''}- App-owned routes stay native framework routes in \`${routes}\`; layouts live in \`src/layouts/<name>.tsx\`.
132
+ ${shell ? "- Shell: place an Action with `slots: ['shell.navigation']` or `['shell.toolbar']`; header content goes in `ui/slots/shell.header.end.tsx`.\n" : ''}- App-owned routes stay native framework routes in \`${routes}\`; layouts live in \`src/layouts/<family>.tsx\` (pages pick one with \`export const layout\`).
133
+ - Each installed \`@bitakit/*\` package explains itself in \`node_modules/@bitakit/<name>/AGENTS.md\`; read it before using the package.
92
134
  - Create files with \`npx bitakit add plugin <name>\` and \`npx bitakit add <kind> <name>/<file>\` (\`events\` and
93
135
  \`settings\` take only \`<name>\`); list IDs with \`npx bitakit info --json\` and slots with \`npx bitakit slots\`; check with \`npx bitakit doctor\` and \`npm run typecheck\`.
94
136
  - For feature work, use the project-local \`bitakit-app-development\` skill (\`$bitakit-app-development\` in Codex,