@bitakit/cli 0.2.0 → 0.2.2
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.
- package/README.md +128 -11
- package/package.json +4 -3
- package/skills/bitakit-app-development/README.md +121 -0
- package/skills/bitakit-app-development/SKILL.md +144 -0
- package/skills/bitakit-app-development/references/actions.md +198 -0
- package/skills/bitakit-app-development/references/interceptors.md +164 -0
- package/skills/bitakit-app-development/references/plugins-and-pages.md +165 -0
- package/skills/bitakit-app-development/references/services-and-events.md +173 -0
- package/skills/bitakit-app-development/references/settings.md +183 -0
- package/skills/bitakit-app-development/references/slots.md +165 -0
- package/skills/bitakit-app-development/references/testing-and-preview.md +171 -0
- package/src/add.mjs +96 -4
- package/src/agent-rules.mjs +53 -3
- package/src/agent-skill.mjs +152 -0
- package/src/check-page.mjs +385 -0
- package/src/cli.mjs +109 -18
- package/src/doctor-agent-files.mjs +66 -0
- package/src/doctor.mjs +5 -2
- package/src/index.mjs +16 -1
- package/src/init.mjs +72 -21
- package/src/slots.mjs +227 -0
- package/src/templates.mjs +86 -45
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Check the work: typecheck, doctor, tests and preview
|
|
2
|
+
|
|
3
|
+
Use this after every change and before telling the user it works. Report only the checks you
|
|
4
|
+
actually ran.
|
|
5
|
+
|
|
6
|
+
## Run typecheck and doctor (always)
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm run typecheck
|
|
10
|
+
npx bitakit doctor --json
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- In a create-app app, `npm run typecheck` runs `bitakit generate`, the framework's type
|
|
14
|
+
generation (`next typegen` or `tsr generate`) and `tsc --noEmit`. Without that script, run the
|
|
15
|
+
same three steps yourself: `npx bitakit generate`, the framework step, `npx tsc --noEmit`.
|
|
16
|
+
- Doctor prints `{ project, results: [{ status, title, details?, fix? }], errors, warnings }`.
|
|
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.
|
|
19
|
+
- Doctor checks wiring statically (versions, provider, routes, links, service names, styles, slot
|
|
20
|
+
file targets). It renders nothing.
|
|
21
|
+
- When the starting state is unknown, run both before editing, so an existing error is not
|
|
22
|
+
blamed on your change.
|
|
23
|
+
|
|
24
|
+
## Add a test runner (ask first)
|
|
25
|
+
|
|
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:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npx bitakit add test <plugin>
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- It writes `tests/<plugin>.test.ts` at the app root, which mounts the plugin, checks that it
|
|
34
|
+
starts, then stops it. A Shell stand-in is included when the plugin's Actions use `shell.*` slots.
|
|
35
|
+
- It prints the setup the app still lacks as commands (dev dependencies, `type`, `test` script).
|
|
36
|
+
Run them, then `npm test`, and add the behavior to check, as in the activity test below.
|
|
37
|
+
|
|
38
|
+
Manual setup, for a test written by hand:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
npm install --save-dev @bitakit/discovery jiti typescript @types/node
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
- Use Node.js 24 or newer. Node strips the types; `npm run typecheck` still checks the test files.
|
|
45
|
+
- Add `"type": "module"` to `package.json`. Without it Node runs the test but prints a
|
|
46
|
+
`MODULE_TYPELESS_PACKAGE_JSON` warning.
|
|
47
|
+
- Add the script `"test": "node --test tests/*.test.ts"` and run it from the app root: plugin
|
|
48
|
+
folder paths resolve against the current directory.
|
|
49
|
+
- A create-app app already lists `@bitakit/discovery`, `typescript` and `@types/node`; `jiti` is
|
|
50
|
+
only present transitively, so add it.
|
|
51
|
+
|
|
52
|
+
## Test a plugin headlessly
|
|
53
|
+
|
|
54
|
+
File: `tests/activity.test.ts`
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import assert from 'node:assert/strict';
|
|
58
|
+
import test from 'node:test';
|
|
59
|
+
import { defineContract, definePlugin, defineSlot, getService } from '@bitakit/core';
|
|
60
|
+
import { mountPlugin } from '@bitakit/core/testing';
|
|
61
|
+
import type feed from '../src/plugins/activity/services/feed';
|
|
62
|
+
|
|
63
|
+
const feedService = defineContract('activity.feed').of<ReturnType<typeof feed.create>>();
|
|
64
|
+
// todos.open targets shell.navigation; this stand-in owns that slot so startup succeeds without Shell.
|
|
65
|
+
const shell = definePlugin({
|
|
66
|
+
id: 'shell',
|
|
67
|
+
slots: { navigation: defineSlot({ accepts: 'actions' }) },
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('adding a todo is recorded in the activity feed', async () => {
|
|
71
|
+
const plugin = await mountPlugin('src/plugins/activity', {
|
|
72
|
+
plugins: ['src/plugins/todos', shell],
|
|
73
|
+
});
|
|
74
|
+
try {
|
|
75
|
+
const result = await plugin.execute('todos.add', 'Buy milk');
|
|
76
|
+
assert.equal(result.status, 'completed');
|
|
77
|
+
assert.deepEqual(plugin.events.recorded.at(-1), {
|
|
78
|
+
type: 'todos.changed',
|
|
79
|
+
data: { kind: 'added', title: 'Buy milk' },
|
|
80
|
+
});
|
|
81
|
+
assert.deepEqual(getService(plugin.services, feedService).state.get().entries, [
|
|
82
|
+
'Added "Buy milk"',
|
|
83
|
+
]);
|
|
84
|
+
} finally {
|
|
85
|
+
await plugin.stop();
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `mountPlugin(folder, { plugins, services, configOverrides })` discovers the folder like the app
|
|
91
|
+
does, skips `ui/` and resolves after startup. `plugins` takes folder paths or `definePlugin`
|
|
92
|
+
stubs; `services` supplies host services such as a fake `auth`.
|
|
93
|
+
- `plugin.execute('add')` prefixes the mounted plugin's ID; for another plugin's Action pass the
|
|
94
|
+
full ID (`todos.add`). The result has `status: 'completed'` on success.
|
|
95
|
+
- Read state through `defineContract('<plugin>.<file>')` and `getService(plugin.services, key)`.
|
|
96
|
+
The `import type` only borrows the service type; keep it without `.ts` so `tsc` accepts it and
|
|
97
|
+
Node erases it.
|
|
98
|
+
- `plugin.events.recorded` holds `{ type, data }` for every event emitted while mounted. Always
|
|
99
|
+
`await plugin.stop()` in `finally`.
|
|
100
|
+
- Without the Shell stub, startup fails with `Slot "shell.navigation": no owning definition
|
|
101
|
+
exists`. Add a stub only for slots the mounted plugins target. Keep services and Actions free
|
|
102
|
+
of JSX; Node loads them without a bundler.
|
|
103
|
+
|
|
104
|
+
## Test React components
|
|
105
|
+
|
|
106
|
+
`renderWithBitaKit(element, { plugins, config, services, ui })` from `@bitakit/ui/testing` mounts
|
|
107
|
+
the provider and awaits readiness. Use it only when the project already has a DOM test setup
|
|
108
|
+
such as jsdom; the helper installs none. Otherwise verify the UI in the browser preview.
|
|
109
|
+
|
|
110
|
+
## Preview in the browser
|
|
111
|
+
|
|
112
|
+
Start the app's own dev script (`npm run dev`) as a long-running background process, wait for
|
|
113
|
+
its ready line and use the `Local:` URL it prints. The page path comes from `ui/pages`:
|
|
114
|
+
`src/plugins/todos/ui/pages/index.tsx` is `/todos`, `ui/pages/<path>.tsx` is `/<plugin>/<path>`.
|
|
115
|
+
|
|
116
|
+
In Claude Code desktop, the preview tool starts the server from `.claude/launch.json`. Create it
|
|
117
|
+
when missing:
|
|
118
|
+
|
|
119
|
+
```json
|
|
120
|
+
{
|
|
121
|
+
"version": "0.0.1",
|
|
122
|
+
"configurations": [
|
|
123
|
+
{ "name": "dev", "runtimeExecutable": "npm", "runtimeArgs": ["run", "dev"], "port": 3000 }
|
|
124
|
+
]
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
- In Codex and other hosts, use the available browser tool. Without one, check the page
|
|
129
|
+
headlessly while the dev server runs:
|
|
130
|
+
|
|
131
|
+
```sh
|
|
132
|
+
npx bitakit check-page /todos --json
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
It opens the page in headless Chromium and reports the headings, an excerpt of `<main>`, the
|
|
136
|
+
runtime state (`ready` when startup finished), `[bitakit]` errors, console and page errors
|
|
137
|
+
and failed requests. Exit code 1 means it saw an error. Add `--base-url http://localhost:<port>`
|
|
138
|
+
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.
|
|
141
|
+
|
|
142
|
+
- An HTTP 200 or the server HTML proves nothing. The catch-all route
|
|
143
|
+
`src/app/(app)/[...path]/page.tsx` answers every path, and plugin pages and slots render only
|
|
144
|
+
after the runtime starts in the browser.
|
|
145
|
+
- An unknown path also answers 200 (with Shell it shows the heading "Page not found"), so confirm
|
|
146
|
+
that the rendered headings name your page.
|
|
147
|
+
- Read the browser console. In development a plugin that fails to start is turned off and the
|
|
148
|
+
rest keeps running: the console shows `[bitakit] <cause>` and a dialog says
|
|
149
|
+
`Plugin "<id>" was turned off`. A page of that plugin may simply look empty.
|
|
150
|
+
- For an empty slot, confirm the visited page or layout renders that outlet (`PluginSlot` or
|
|
151
|
+
`useSlot`), the file is `ui/slots/<slot name>.tsx`, and doctor's "Slot files target declared
|
|
152
|
+
slots" passes. A custom `useSlot` renderer exposes `diagnostics.reason` and
|
|
153
|
+
`diagnostics.excluded`.
|
|
154
|
+
- When the change depends on the Shell layout, check both layouts: Settings, Appearance,
|
|
155
|
+
Navigation switches `shell.layout` between Sidebar and Navigation bar. `sidebar.*` slots do not
|
|
156
|
+
render in the navbar layout.
|
|
157
|
+
- Example run: open `/todos`, type "Buy milk", press Enter. The list shows it and Recent activity
|
|
158
|
+
shows `Added "Buy milk"`.
|
|
159
|
+
|
|
160
|
+
## Report the result
|
|
161
|
+
|
|
162
|
+
- Files changed, and the IDs involved (`todos.add`, `todos.list`, `todos.footer`, `todos.limit`).
|
|
163
|
+
- Where it appears: page path, slot, layout.
|
|
164
|
+
- Each check you ran and its exit code: typecheck, doctor (`errors`/`warnings`), tests.
|
|
165
|
+
- What you did not verify, such as the navbar layout or any UI without a browser.
|
|
166
|
+
|
|
167
|
+
## Explain it to the user
|
|
168
|
+
|
|
169
|
+
Say what ran and what it proved: "Typecheck and doctor pass; the activity test shows that adding
|
|
170
|
+
a todo emits `todos.changed` and the feed records it." Name the page to open and what to click,
|
|
171
|
+
then state plainly what was checked in a browser and what was not.
|
package/src/add.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { mkdir, writeFile } from 'node:fs/promises';
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { contributionSegments, describeBitaKit, describeModule } from '@bitakit/discovery';
|
|
4
5
|
import { exists, findProject } from './project.mjs';
|
|
5
6
|
import {
|
|
6
7
|
actionFile,
|
|
@@ -18,6 +19,7 @@ import {
|
|
|
18
19
|
pluginFiles,
|
|
19
20
|
serviceFile,
|
|
20
21
|
starterFiles,
|
|
22
|
+
testFile,
|
|
21
23
|
titleOf,
|
|
22
24
|
validateName,
|
|
23
25
|
} from './templates.mjs';
|
|
@@ -91,6 +93,7 @@ export const contributionKinds = [
|
|
|
91
93
|
'slot-definition',
|
|
92
94
|
'dialog',
|
|
93
95
|
'provider',
|
|
96
|
+
'test',
|
|
94
97
|
];
|
|
95
98
|
/** Declared once per plugin, in one root file. */
|
|
96
99
|
const singleFile = {
|
|
@@ -102,12 +105,14 @@ const singleFile = {
|
|
|
102
105
|
/**
|
|
103
106
|
* `bitakit add <kind> <plugin>/<name>` in an app, or `<name>` in a plugin package. Nested names
|
|
104
107
|
* such as `notes/team/invite` create `actions/team/invite.ts` with the ID `notes.team.invite`.
|
|
105
|
-
* `events` takes only the plugin: a plugin declares its events once in `events.ts`.
|
|
108
|
+
* `events` takes only the plugin: a plugin declares its events once in `events.ts`. `test` also
|
|
109
|
+
* takes only an existing plugin of an app and writes `tests/<plugin>.test.ts` at the app root.
|
|
106
110
|
*/
|
|
107
111
|
export async function addContribution(kind, target, { cwd } = {}) {
|
|
108
112
|
if (!contributionKinds.includes(kind))
|
|
109
113
|
throw new Error(`Unknown kind "${kind}". Use ${contributionKinds.join(', ')}.`);
|
|
110
114
|
const project = await configuredProject(cwd);
|
|
115
|
+
if (kind === 'test') return addTest(project, target);
|
|
111
116
|
if (kind === 'layout') {
|
|
112
117
|
if (project.kind !== 'app')
|
|
113
118
|
throw new Error('Layouts belong to the app: run "bitakit add layout <name>" inside an app.');
|
|
@@ -162,7 +167,7 @@ export async function addContribution(kind, target, { cwd } = {}) {
|
|
|
162
167
|
const pageSegments = segments.at(-1) === 'index' ? segments.slice(0, -1) : segments;
|
|
163
168
|
const pagePath = `/${plugin}${pageSegments.map((segment) => `/${segment}`).join('')}`;
|
|
164
169
|
const files = {
|
|
165
|
-
action: () => ({ [`actions/${name}.ts`]: actionFile(name) }),
|
|
170
|
+
action: () => ({ [`actions/${name}.ts`]: actionFile(name, plugin) }),
|
|
166
171
|
service: () => ({ [`services/${name}.ts`]: serviceFile(name, plugin) }),
|
|
167
172
|
page: () => ({
|
|
168
173
|
[`ui/pages/${name}.tsx`]: pageFile(plugin, pagePath, titleOf(pageSegments.at(-1) ?? plugin)),
|
|
@@ -188,3 +193,90 @@ export async function addContribution(kind, target, { cwd } = {}) {
|
|
|
188
193
|
path: kind === 'page' ? pagePath : undefined,
|
|
189
194
|
};
|
|
190
195
|
}
|
|
196
|
+
|
|
197
|
+
/** What `mountPlugin` needs under Node besides `@bitakit/core`, as the testing guide lists it. */
|
|
198
|
+
const testDependencies = ['@bitakit/discovery', 'jiti', 'typescript', '@types/node'];
|
|
199
|
+
|
|
200
|
+
const nameOf = (node) =>
|
|
201
|
+
ts.isIdentifier(node) || ts.isStringLiteralLike(node) ? node.text : undefined;
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* The Shell slots a plugin's Actions are placed in: the `'shell.…'` entries of every `slots: [...]`
|
|
205
|
+
* in its action files, written as a string or as `{ slot }`. Read from the syntax tree, never run.
|
|
206
|
+
*/
|
|
207
|
+
async function shellSlotsOf(directory) {
|
|
208
|
+
const slots = new Set();
|
|
209
|
+
for (const { file } of (await describeModule(directory)).actions) {
|
|
210
|
+
const visit = (node) => {
|
|
211
|
+
if (
|
|
212
|
+
ts.isPropertyAssignment(node) &&
|
|
213
|
+
nameOf(node.name) === 'slots' &&
|
|
214
|
+
ts.isArrayLiteralExpression(node.initializer)
|
|
215
|
+
)
|
|
216
|
+
for (const element of node.initializer.elements) {
|
|
217
|
+
const target = ts.isObjectLiteralExpression(element)
|
|
218
|
+
? element.properties.find(
|
|
219
|
+
(item) => ts.isPropertyAssignment(item) && nameOf(item.name) === 'slot',
|
|
220
|
+
)?.initializer
|
|
221
|
+
: element;
|
|
222
|
+
if (target && ts.isStringLiteralLike(target) && target.text.startsWith('shell.'))
|
|
223
|
+
slots.add(target.text.slice('shell.'.length));
|
|
224
|
+
}
|
|
225
|
+
ts.forEachChild(node, visit);
|
|
226
|
+
};
|
|
227
|
+
visit(ts.createSourceFile(file, await readFile(file, 'utf8'), ts.ScriptTarget.Latest, true));
|
|
228
|
+
}
|
|
229
|
+
return [...slots].sort();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** The commands an app still needs to run the test; the CLI never edits package.json itself. */
|
|
233
|
+
function testSetup(manifest, file) {
|
|
234
|
+
const installed = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
235
|
+
const missing = testDependencies.filter((name) => !installed[name]);
|
|
236
|
+
const script = manifest.scripts?.test;
|
|
237
|
+
// npm init writes a test script that only fails; it counts as missing.
|
|
238
|
+
const needsScript = !script || /no test specified/.test(script);
|
|
239
|
+
return {
|
|
240
|
+
setup: [
|
|
241
|
+
...(missing.length ? [`npm install --save-dev ${missing.join(' ')}`] : []),
|
|
242
|
+
...(manifest.type === 'module' ? [] : ['npm pkg set type=module']),
|
|
243
|
+
...(needsScript ? ['npm pkg set scripts.test="node --test tests/*.test.ts"'] : []),
|
|
244
|
+
],
|
|
245
|
+
run: needsScript || script.includes('node --test') ? 'npm test' : `node --test ${file}`,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** `bitakit add test <plugin>`: tests/<plugin>.test.ts at the app root, mounting that plugin folder. */
|
|
250
|
+
async function addTest(project, plugin) {
|
|
251
|
+
if (project.kind !== 'app')
|
|
252
|
+
throw new Error(
|
|
253
|
+
'Run "bitakit add test <plugin>" inside an app; a plugin package keeps its tests in tests/.',
|
|
254
|
+
);
|
|
255
|
+
if (!plugin) throw new Error('Name the plugin, for example "bitakit add test notes".');
|
|
256
|
+
if (plugin.includes('/'))
|
|
257
|
+
throw new Error(
|
|
258
|
+
`A test covers a whole plugin: run "bitakit add test ${plugin.slice(0, plugin.indexOf('/'))}" without a further name.`,
|
|
259
|
+
);
|
|
260
|
+
validateName(plugin, 'plugin name');
|
|
261
|
+
const directory = path.join(project.pluginsDirectory, plugin);
|
|
262
|
+
if (!(await exists(directory)))
|
|
263
|
+
throw new Error(
|
|
264
|
+
`${directory} does not exist. Create the plugin first, for example "bitakit add plugin ${plugin}". Nothing was changed.`,
|
|
265
|
+
);
|
|
266
|
+
const relativeDirectory = path.relative(project.root, directory).split(path.sep).join('/');
|
|
267
|
+
// The app's ID for the folder, so the test mounts the plugin as the app does.
|
|
268
|
+
const id =
|
|
269
|
+
(await describeBitaKit(project.root)).plugins.find(
|
|
270
|
+
(entry) => entry.directory === relativeDirectory,
|
|
271
|
+
)?.id ?? plugin;
|
|
272
|
+
const file = `tests/${plugin}.test.ts`;
|
|
273
|
+
const created = await writeNewFiles(project.root, {
|
|
274
|
+
[file]: testFile(plugin, {
|
|
275
|
+
directory: relativeDirectory,
|
|
276
|
+
// Under plugins/, mountPlugin reads the same ID from plugin.config.ts or the folder name.
|
|
277
|
+
id: path.basename(project.pluginsDirectory) === 'plugins' ? undefined : id,
|
|
278
|
+
shellSlots: await shellSlotsOf(directory),
|
|
279
|
+
}),
|
|
280
|
+
});
|
|
281
|
+
return { project, created, plugin, id, ...testSetup(project.manifest, file) };
|
|
282
|
+
}
|
package/src/agent-rules.mjs
CHANGED
|
@@ -1,13 +1,60 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { exists } from './project.mjs';
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
5
|
* The one identity sentence. The root README, the docs introduction, generated READMEs and agent
|
|
3
6
|
* rules repeat it verbatim; a test keeps those surfaces from drifting apart.
|
|
4
7
|
*/
|
|
5
8
|
export const bitakitIdentity = 'BitaKit is a composition layer for building apps with AI agents.';
|
|
6
9
|
|
|
7
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Markers around the BitaKit block. The block between them is BitaKit-owned: `bitakit init
|
|
12
|
+
* --update-agent-files` replaces it, so app rules belong above or below it.
|
|
13
|
+
*/
|
|
8
14
|
export const agentRulesBegin = '<!-- BEGIN:bitakit-agent-rules -->';
|
|
9
15
|
export const agentRulesEnd = '<!-- END:bitakit-agent-rules -->';
|
|
10
16
|
|
|
17
|
+
/**
|
|
18
|
+
* An AGENTS.md text with its BitaKit block replaced by `rules`. Returns `text` itself when the
|
|
19
|
+
* block already matches (line endings aside) and undefined when it has no complete block.
|
|
20
|
+
*/
|
|
21
|
+
export function refreshAgentRules(text, rules) {
|
|
22
|
+
const start = text?.indexOf(agentRulesBegin) ?? -1;
|
|
23
|
+
const end = start < 0 ? -1 : text.indexOf(agentRulesEnd, start);
|
|
24
|
+
if (end < 0) return undefined;
|
|
25
|
+
const next = text.slice(0, start) + rules.trimEnd() + text.slice(end + agentRulesEnd.length);
|
|
26
|
+
const lf = (value) => value.replaceAll('\r\n', '\n');
|
|
27
|
+
return lf(next) === lf(text) ? text : next;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The rules `bitakit init` writes for an app: its framework's route folder and the Shell line when
|
|
32
|
+
* `@bitakit/shell` is installed. Undefined for an app without a supported framework.
|
|
33
|
+
*/
|
|
34
|
+
export async function projectAgentRules(project) {
|
|
35
|
+
if (!project.framework) return undefined;
|
|
36
|
+
const dependencies = { ...project.manifest.dependencies, ...project.manifest.devDependencies };
|
|
37
|
+
// The framework's own route folder: src/app or app for Next.js, src/routes for TanStack Start.
|
|
38
|
+
const routes =
|
|
39
|
+
project.framework === 'next'
|
|
40
|
+
? (await exists(path.join(project.root, 'src/app')))
|
|
41
|
+
? 'src/app'
|
|
42
|
+
: 'app'
|
|
43
|
+
: 'src/routes';
|
|
44
|
+
return agentRules({ routes, shell: Boolean(dependencies['@bitakit/shell']) });
|
|
45
|
+
}
|
|
46
|
+
|
|
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;
|
|
50
|
+
* `existing` is returned unchanged when it already imports AGENTS.md.
|
|
51
|
+
*/
|
|
52
|
+
export function claudeFileFor(existing) {
|
|
53
|
+
const text = existing?.trim() ? existing : undefined;
|
|
54
|
+
if (!text) return '@AGENTS.md\n';
|
|
55
|
+
return /^@AGENTS\.md\s*$/m.test(text) ? existing : `${text.trimEnd()}\n\n@AGENTS.md\n`;
|
|
56
|
+
}
|
|
57
|
+
|
|
11
58
|
/**
|
|
12
59
|
* The guidance block for coding assistants in an app's AGENTS.md, shared by create-app and
|
|
13
60
|
* `bitakit init`. Ordered by learning level: where each task goes first, then the rules, then
|
|
@@ -42,8 +89,11 @@ the file path is the ID. Discovery generates \`src/bitakit.gen.*\`; there is no
|
|
|
42
89
|
import package CSS from JavaScript (discovery writes \`src/bitakit.gen.css\`).
|
|
43
90
|
- Do not rebuild what BitaKit provides: no own registries, event buses, settings stores or button state.
|
|
44
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\`.
|
|
45
|
-
- Create files with \`npx bitakit add plugin <name>\` and \`npx bitakit add <kind> <name>/<file
|
|
46
|
-
\`npx bitakit info --json\`; check with \`npx bitakit doctor\` and \`npm run typecheck\`.
|
|
92
|
+
- Create files with \`npx bitakit add plugin <name>\` and \`npx bitakit add <kind> <name>/<file>\` (\`events\` and
|
|
93
|
+
\`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
|
+
- For feature work, use the project-local \`bitakit-app-development\` skill (\`$bitakit-app-development\` in Codex,
|
|
95
|
+
\`/bitakit-app-development\` in Claude Code, otherwise read \`.agents/skills/bitakit-app-development/SKILL.md\`):
|
|
96
|
+
recipes for each task above, slot and layout choice, and checking the result in the browser.
|
|
47
97
|
- Advanced, only when needed: interceptors, configs, providers, dialogs, \`setup.ts\`, \`plugin.config.ts\`.
|
|
48
98
|
- Never edit generated files: \`src/bitakit.gen.*\`.
|
|
49
99
|
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Where the app-authoring skill is installed: `.agents/skills` is read by Codex and most other
|
|
8
|
+
* agents (Cursor, Copilot, Gemini CLI), `.claude/skills` by Claude Code.
|
|
9
|
+
*/
|
|
10
|
+
export const appDevelopmentSkillPaths = [
|
|
11
|
+
'.agents/skills/bitakit-app-development/SKILL.md',
|
|
12
|
+
'.claude/skills/bitakit-app-development/SKILL.md',
|
|
13
|
+
];
|
|
14
|
+
const skillSource = fileURLToPath(new URL('../skills/bitakit-app-development', import.meta.url));
|
|
15
|
+
/** The release whose skill this CLI installs; installed copies record it. */
|
|
16
|
+
export const { version: cliVersion } = JSON.parse(
|
|
17
|
+
await readFile(new URL('../package.json', import.meta.url), 'utf8'),
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
// The install stamp is a spec-valid frontmatter `metadata` map at the end of the frontmatter.
|
|
21
|
+
// Its checksum covers the files as shipped, so an unedited copy can be told apart from a team's
|
|
22
|
+
// edit and replaced safely. Text is compared with LF line endings, so a Git checkout with CRLF
|
|
23
|
+
// does not count as an edit.
|
|
24
|
+
const lf = (text) => text.replaceAll('\r\n', '\n');
|
|
25
|
+
const frontmatter = /^---\n[\s\S]*?\n(?=---\n)/;
|
|
26
|
+
const stampBlock =
|
|
27
|
+
/^metadata:\n {2}bitakit-version: "([^"\n]*)"\n {2}bitakit-checksum: "([0-9a-f]{64})"\n/m;
|
|
28
|
+
|
|
29
|
+
/** A SKILL.md as shipped with the install stamp added to its frontmatter. */
|
|
30
|
+
export function stampSkill(text, { version, checksum }) {
|
|
31
|
+
const head = frontmatter.exec(text)?.[0];
|
|
32
|
+
if (head === undefined) throw new Error('The bundled SKILL.md has no frontmatter.');
|
|
33
|
+
return `${head}metadata:\n bitakit-version: "${version}"\n bitakit-checksum: "${checksum}"\n${text.slice(head.length)}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The install stamp of a SKILL.md, `{ version, checksum }`, or undefined when it has none. */
|
|
37
|
+
export function readSkillStamp(text) {
|
|
38
|
+
const match = stampBlock.exec(frontmatter.exec(lf(text))?.[0] ?? '');
|
|
39
|
+
return match ? { version: match[1], checksum: match[2] } : undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A SKILL.md without its install stamp, with LF line endings: the text as shipped. */
|
|
43
|
+
export function unstampSkill(text) {
|
|
44
|
+
const normalized = lf(text);
|
|
45
|
+
const head = frontmatter.exec(normalized)?.[0];
|
|
46
|
+
if (head === undefined) return normalized;
|
|
47
|
+
return head.replace(stampBlock, '') + normalized.slice(head.length);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The files of a skill folder as shipped: `[path, content]` pairs sorted by relative POSIX path,
|
|
52
|
+
* with LF line endings and the stamp removed from SKILL.md. Compare an installed copy with
|
|
53
|
+
* `bundledSkillFiles()` through this rather than byte by byte. Dotfiles (`.DS_Store`, editor swap
|
|
54
|
+
* files) are not part of a skill and are ignored.
|
|
55
|
+
*/
|
|
56
|
+
export async function readSkillFiles(directory) {
|
|
57
|
+
const entries = await readdir(directory, { recursive: true, withFileTypes: true });
|
|
58
|
+
const files = entries
|
|
59
|
+
.filter((entry) => entry.isFile())
|
|
60
|
+
.map((entry) =>
|
|
61
|
+
path.relative(directory, path.join(entry.parentPath, entry.name)).split(path.sep).join('/'),
|
|
62
|
+
)
|
|
63
|
+
.filter((file) => !file.split('/').some((part) => part.startsWith('.')))
|
|
64
|
+
.sort();
|
|
65
|
+
return Promise.all(
|
|
66
|
+
files.map(async (file) => {
|
|
67
|
+
const content = lf(await readFile(path.join(directory, file), 'utf8'));
|
|
68
|
+
return [file, file === 'SKILL.md' ? unstampSkill(content) : content];
|
|
69
|
+
}),
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The files a skill source folder installs: everything but its README, which is for people
|
|
75
|
+
* browsing the package. Defaults to the skill bundled with this CLI.
|
|
76
|
+
*/
|
|
77
|
+
export async function bundledSkillFiles(source = skillSource) {
|
|
78
|
+
return (await readSkillFiles(source)).filter(([file]) => file !== 'README.md');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The `bitakit-checksum` of `[path, content]` pairs from `readSkillFiles`: sha256, hex. */
|
|
82
|
+
export function skillChecksum(files) {
|
|
83
|
+
const hash = createHash('sha256');
|
|
84
|
+
for (const [file, content] of files) hash.update(`${file}\0${content}\0`);
|
|
85
|
+
return hash.digest('hex');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Whether `version` is a newer release than `than`, by major.minor.patch. */
|
|
89
|
+
function newerRelease(version, than) {
|
|
90
|
+
const [a, b] = [version, than].map((value) => value.split('-')[0].split('.').map(Number));
|
|
91
|
+
const index = a.findIndex((part, position) => part !== b[position]);
|
|
92
|
+
return index >= 0 && a[index] > b[index];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* How the skill copy in `directory` relates to the bundled skill. `state` is `missing`,
|
|
97
|
+
* `current` (the files as shipped; `stamped` says whether its stamp records that), `outdated`
|
|
98
|
+
* (stamped and unedited, from an older or the same release, so it can be replaced), `newer`
|
|
99
|
+
* (stamped and unedited, from a newer CLI) or `edited` (changed since it was installed, or
|
|
100
|
+
* unstamped and different: it is never replaced). `version` is the release in the stamp and
|
|
101
|
+
* `checksum` the one recomputed from the files.
|
|
102
|
+
*/
|
|
103
|
+
export async function inspectSkillCopy(directory) {
|
|
104
|
+
const text = await readFile(path.join(directory, 'SKILL.md'), 'utf8').catch((error) => {
|
|
105
|
+
if (error.code === 'ENOENT') return undefined;
|
|
106
|
+
throw error;
|
|
107
|
+
});
|
|
108
|
+
if (text === undefined) return { state: 'missing' };
|
|
109
|
+
const checksum = skillChecksum(await readSkillFiles(directory));
|
|
110
|
+
const stamp = readSkillStamp(text);
|
|
111
|
+
const copy = { checksum, version: stamp?.version, stamped: stamp?.checksum === checksum };
|
|
112
|
+
if (checksum === skillChecksum(await bundledSkillFiles())) return { ...copy, state: 'current' };
|
|
113
|
+
if (!copy.stamped) return { ...copy, state: 'edited' };
|
|
114
|
+
return { ...copy, state: newerRelease(stamp.version, cliVersion) ? 'newer' : 'outdated' };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Installs the bundled app-authoring skill (SKILL.md and its references/) for every agent folder
|
|
119
|
+
* and stamps the installed SKILL.md with this CLI's version and the checksum of the files as
|
|
120
|
+
* shipped. An existing copy is left alone unless `update` is set: then an unedited older copy is
|
|
121
|
+
* replaced whole and a current unstamped one gets its stamp. An edited copy is always kept whole,
|
|
122
|
+
* so a team's changes are never mixed with newer files. Skill files are written as LF text, which
|
|
123
|
+
* is why the bundled skill holds Markdown only (a test enforces it).
|
|
124
|
+
* Returns, per SKILL.md path, the copy as found (`inspectSkillCopy`) plus `change`: `installed`,
|
|
125
|
+
* `updated`, `stamped` or undefined when nothing was written.
|
|
126
|
+
*/
|
|
127
|
+
export async function writeAppDevelopmentSkills(root, { update = false } = {}) {
|
|
128
|
+
const files = await bundledSkillFiles();
|
|
129
|
+
const stamp = { version: cliVersion, checksum: skillChecksum(files) };
|
|
130
|
+
const results = [];
|
|
131
|
+
for (const relative of appDevelopmentSkillPaths) {
|
|
132
|
+
const file = path.join(root, relative);
|
|
133
|
+
// A team may link one copy to the other so both agents share a folder: write through the link
|
|
134
|
+
// so it stays a link and the second copy then reads as up to date.
|
|
135
|
+
const directory = await realpath(path.dirname(file)).catch(() => path.dirname(file));
|
|
136
|
+
const copy = await inspectSkillCopy(directory);
|
|
137
|
+
let change;
|
|
138
|
+
if (copy.state === 'missing') change = 'installed';
|
|
139
|
+
else if (update && copy.state === 'outdated') change = 'updated';
|
|
140
|
+
else if (update && copy.state === 'current' && !copy.stamped) change = 'stamped';
|
|
141
|
+
// The whole folder goes, so files an older release shipped and this one dropped do not linger.
|
|
142
|
+
if (change === 'updated') await rm(directory, { recursive: true, force: true });
|
|
143
|
+
for (const [name, content] of change ? files : []) {
|
|
144
|
+
if (change === 'stamped' && name !== 'SKILL.md') continue;
|
|
145
|
+
const target = path.join(directory, name);
|
|
146
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
147
|
+
await writeFile(target, name === 'SKILL.md' ? stampSkill(content, stamp) : content);
|
|
148
|
+
}
|
|
149
|
+
results.push({ file, ...copy, change, created: change === 'installed' });
|
|
150
|
+
}
|
|
151
|
+
return results;
|
|
152
|
+
}
|