@bitakit/cli 0.2.1 → 0.2.3

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/src/doctor.mjs CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  cssImports,
9
9
  navigationPlacement,
10
10
  } from '@bitakit/discovery';
11
+ import { checkAgentFiles } from './doctor-agent-files.mjs';
11
12
  import { exists, findProject } from './project.mjs';
12
13
  import { appRoutes, catchAllRoute, rootLayouts, shellGroup } from './routes.mjs';
13
14
 
@@ -15,7 +16,7 @@ import { appRoutes, catchAllRoute, rootLayouts, shellGroup } from './routes.mjs'
15
16
  * Checks a project for the problems that most often break a BitaKit app: mixed package
16
17
  * versions, duplicate Core copies, missing wiring, unreachable plugin pages and links,
17
18
  * colliding service aliases, `requires` nobody satisfies, plugin dependency cycles, missing
18
- * styles and deprecated layouts.
19
+ * styles, deprecated layouts and agent files that are out of sync.
19
20
  * Each result: `{ status: 'ok' | 'warn' | 'error', title, details, fix }`.
20
21
  */
21
22
  export async function doctor({ cwd } = {}) {
@@ -114,6 +115,8 @@ export async function doctor({ cwd } = {}) {
114
115
  fix: 'Choose the intended owner slot. For the default Shell run bitakit migrate --navigation-slot shell.navigation --dry-run, review it, then apply. Logical groups alone do not place UI.',
115
116
  });
116
117
  }
118
+ const agentFiles = await checkAgentFiles(project);
119
+ if (agentFiles) results.push(agentFiles);
117
120
  return { project, results };
118
121
  }
119
122
 
@@ -160,6 +163,13 @@ async function checkVersions(project) {
160
163
  const versions = [...new Set(packages.map((item) => item.version))];
161
164
  if (versions.length === 1)
162
165
  return { status: 'ok', title: `All ${packages.length} @bitakit packages are ${versions[0]}` };
166
+ // Only changed packages get a patch release, so patch versions may differ within one line.
167
+ const lines = [...new Set(packages.map((item) => releaseLine(item.version)))];
168
+ if (lines.length === 1)
169
+ return {
170
+ status: 'ok',
171
+ title: `All ${packages.length} @bitakit packages are on the ${lines[0]}.x release line`,
172
+ };
163
173
  return {
164
174
  status: 'error',
165
175
  title: 'Mixed @bitakit versions',
@@ -167,6 +177,11 @@ async function checkVersions(project) {
167
177
  fix: `Install one release for all of them: npm install ${packages.map((item) => `${item.name}@latest`).join(' ')}`,
168
178
  };
169
179
  }
180
+ /** The versions a caret range accepts together: `0.2` for 0.2.x, `1` for 1.x. */
181
+ function releaseLine(version) {
182
+ const [major, minor] = version.split('.');
183
+ return major === '0' ? `0.${minor}` : major;
184
+ }
170
185
  /** Linked plugins with their own node_modules load a second copy of Core. */
171
186
  async function checkCopies(project) {
172
187
  const copies = new Set();
@@ -884,7 +899,7 @@ function checkSlots(description) {
884
899
  if (!problems.length)
885
900
  return {
886
901
  status: 'ok',
887
- // A clean run stays short; `bitakit info` lists the slots.
902
+ // A clean run stays short; `bitakit slots` lists the slots.
888
903
  title: declared.size
889
904
  ? `Slot files target declared slots (${plural(declared.size, 'slot')} available)`
890
905
  : 'No layout slots are declared',
package/src/index.mjs CHANGED
@@ -6,7 +6,15 @@ export {
6
6
  agentRulesEnd,
7
7
  bitakitIdentity,
8
8
  claudeFileFor,
9
+ projectAgentRules,
10
+ refreshAgentRules,
9
11
  } from './agent-rules.mjs';
12
+ export {
13
+ appDevelopmentSkillPaths,
14
+ bundledSkillFiles,
15
+ readSkillFiles,
16
+ writeAppDevelopmentSkills,
17
+ } from './agent-skill.mjs';
10
18
  export { buildPlugin } from './build.mjs';
11
19
  export { doctor } from './doctor.mjs';
12
20
  export {
@@ -20,6 +28,7 @@ export {
20
28
  } from './init.mjs';
21
29
  export { findProject, findProjectRoot, packagePluginId } from './project.mjs';
22
30
  export { appRoutes, catchAllRoute } from './routes.mjs';
31
+ export { describeSlots, formatSlots } from './slots.mjs';
23
32
  export {
24
33
  actionFile,
25
34
  configFile,
package/src/init.mjs CHANGED
@@ -1,7 +1,13 @@
1
1
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import ts from 'typescript';
4
- import { agentRules, agentRulesBegin, claudeFileFor } from './agent-rules.mjs';
4
+ import {
5
+ agentRulesBegin,
6
+ claudeFileFor,
7
+ projectAgentRules,
8
+ refreshAgentRules,
9
+ } from './agent-rules.mjs';
10
+ import { cliVersion, writeAppDevelopmentSkills } from './agent-skill.mjs';
5
11
  import { exists, findProject } from './project.mjs';
6
12
  import { appRoutes, catchAllRoute, rootLayouts, shellGroup } from './routes.mjs';
7
13
 
@@ -121,11 +127,14 @@ function wrapLayout(source, fileName, specifier, framework) {
121
127
  * Vite plugin, the provider in the root layout, the catch-all route for plugin pages, the
122
128
  * `.gitignore` entry and the agent rules in `AGENTS.md` (the same block create-app writes), which
123
129
  * `CLAUDE.md` imports.
124
- * Files that already carry the wiring are never touched.
125
- * Returns `written` (absolute paths; `created` is false for an edited file), `skipped` with the
126
- * reason for each, and the BitaKit packages the app still has to install.
130
+ * Files that already carry the wiring are never touched. With `updateAgentFiles`, the BitaKit
131
+ * block of `AGENTS.md` is replaced with the current rules and unedited skill copies are updated
132
+ * (see `writeAppDevelopmentSkills`); edited copies are kept.
133
+ * Returns `written` (absolute paths; `created` is false for an edited file; `note` says what an
134
+ * update changed), `skipped` with the reason for each, and the BitaKit packages the app still has
135
+ * to install.
127
136
  */
128
- export async function initProject({ cwd } = {}) {
137
+ export async function initProject({ cwd, updateAgentFiles = false } = {}) {
129
138
  const project = await findProject(cwd);
130
139
  if (project.kind !== 'app') throw new Error('Run "bitakit init" inside an app.');
131
140
  if (!project.framework)
@@ -139,10 +148,10 @@ export async function initProject({ cwd } = {}) {
139
148
  const first = async (files) => {
140
149
  for (const file of files) if (await exists(file)) return file;
141
150
  };
142
- const put = async (file, content, created = false) => {
151
+ const put = async (file, content, created = false, note) => {
143
152
  await mkdir(path.dirname(file), { recursive: true });
144
153
  await writeFile(file, content);
145
- written.push({ file, created });
154
+ written.push(note ? { file, created, note } : { file, created });
146
155
  };
147
156
  const skip = (file, reason) => skipped.push({ file, reason });
148
157
 
@@ -228,34 +237,69 @@ export async function initProject({ cwd } = {}) {
228
237
  );
229
238
 
230
239
  const dependencies = { ...project.manifest.dependencies, ...project.manifest.devDependencies };
231
- const agents = await read(at('AGENTS.md'));
232
- if (agents?.includes(agentRulesBegin)) skip(at('AGENTS.md'), 'already has the BitaKit rules');
233
- else {
234
- // The framework's own route folder: src/app or app for Next.js, src/routes for TanStack Start.
235
- const routes =
236
- project.framework === 'next'
237
- ? (await exists(at('src/app')))
238
- ? 'src/app'
239
- : 'app'
240
- : 'src/routes';
241
- const rules = agentRules({ routes, shell: Boolean(dependencies['@bitakit/shell']) });
240
+ const agentsFile = at('AGENTS.md');
241
+ const agents = await read(agentsFile);
242
+ const rules = await projectAgentRules(project);
243
+ const refreshed = refreshAgentRules(agents, rules);
244
+ if (!agents?.includes(agentRulesBegin))
242
245
  await put(
243
- at('AGENTS.md'),
246
+ agentsFile,
244
247
  agents === undefined ? rules : `${agents.trimEnd()}\n\n${rules}`,
245
248
  agents === undefined,
246
249
  );
247
- }
250
+ else if (refreshed === agents)
251
+ skip(
252
+ agentsFile,
253
+ updateAgentFiles ? 'the BitaKit rules are up to date' : 'already has the BitaKit rules',
254
+ );
255
+ else if (refreshed === undefined)
256
+ skip(agentsFile, 'the BitaKit block has no end marker; restore it by hand');
257
+ else if (!updateAgentFiles)
258
+ skip(agentsFile, 'already has the BitaKit rules; --update-agent-files refreshes them');
259
+ else await put(agentsFile, refreshed, false, 'refreshed the BitaKit rules');
248
260
  // Claude Code loads CLAUDE.md, so it imports the rules; an existing file only gets the import line.
249
261
  const claudeFile = at('CLAUDE.md');
250
262
  const claude = await read(claudeFile);
251
263
  const claudeNext = claudeFileFor(claude);
252
264
  if (claudeNext === claude) skip(claudeFile, 'already imports AGENTS.md');
253
265
  else await put(claudeFile, claudeNext, claude === undefined);
266
+
267
+ for (const skill of await writeAppDevelopmentSkills(project.root, {
268
+ update: updateAgentFiles,
269
+ })) {
270
+ if (skill.change === 'installed') written.push({ file: skill.file, created: true });
271
+ else if (skill.change)
272
+ written.push({
273
+ file: skill.file,
274
+ created: false,
275
+ note:
276
+ skill.change === 'updated'
277
+ ? `updated from ${skill.version}`
278
+ : `up to date; stamped with ${cliVersion}`,
279
+ });
280
+ else skip(skill.file, skillReason(skill, updateAgentFiles));
281
+ }
282
+
254
283
  const install = [
255
284
  '@bitakit/core',
256
285
  '@bitakit/discovery',
257
286
  '@bitakit/ui',
258
287
  project.framework === 'next' ? '@bitakit/next' : '@bitakit/tanstack',
259
288
  ].filter((name) => !dependencies[name]);
260
- return { project, written, skipped, install };
289
+ // The rules and the skill tell agents to run `npx bitakit ...`, which needs the local CLI; a
290
+ // one-off `npx @bitakit/cli init` does not install it.
291
+ const installDev = ['@bitakit/cli'].filter((name) => !dependencies[name]);
292
+ return { project, written, skipped, install, installDev };
293
+ }
294
+
295
+ /** Why `init` left an existing skill copy alone. */
296
+ function skillReason(skill, update) {
297
+ if (!update)
298
+ return skill.state === 'outdated'
299
+ ? `already exists; preserved; --update-agent-files updates it from ${skill.version} to ${cliVersion}`
300
+ : 'already exists; preserved';
301
+ if (skill.state === 'current') return 'up to date';
302
+ if (skill.state === 'newer')
303
+ return `from @bitakit/cli ${skill.version}, newer than this CLI; kept`;
304
+ return `edited locally; kept. Delete its folder and run again to get ${cliVersion}`;
261
305
  }
package/src/slots.mjs ADDED
@@ -0,0 +1,227 @@
1
+ import path from 'node:path';
2
+ import { describeDefinitions } from '@bitakit/discovery';
3
+
4
+ const objectHelpers = new Set(['object', 'strictObject', 'looseObject']);
5
+
6
+ /**
7
+ * Keys of a `z.object({ ... })`/`v.object({ ... })` payload; any other schema keeps them unknown.
8
+ * Nodes come from discovery's parser, so they are classified with its `ts`, not a local import.
9
+ */
10
+ function payloadOf(fields, { unwrap, ts }) {
11
+ if (!fields.has('payload')) return { payload: false, payloadKeys: [] };
12
+ const schema = unwrap(fields.get('payload'));
13
+ const callee =
14
+ schema && ts.isCallExpression(schema)
15
+ ? ts.isPropertyAccessExpression(schema.expression)
16
+ ? schema.expression.name.text
17
+ : ts.isIdentifier(schema.expression) && schema.expression.text
18
+ : undefined;
19
+ const shape = objectHelpers.has(callee) ? unwrap(schema.arguments[0]) : undefined;
20
+ if (!shape || !ts.isObjectLiteralExpression(shape)) return { payload: true, payloadKeys: null };
21
+ const keys = [];
22
+ for (const item of shape.properties) {
23
+ if (!item.name || ts.isComputedPropertyName(item.name))
24
+ return { payload: true, payloadKeys: null };
25
+ keys.push(item.name.text);
26
+ }
27
+ return { payload: true, payloadKeys: keys };
28
+ }
29
+
30
+ /**
31
+ * Slot names of an Action's literal `slots` list; `resolved` is false when any entry is not
32
+ * literal.
33
+ */
34
+ function placementsOf(fields, { unwrap, literal, ts }) {
35
+ if (!fields.has('slots')) return { placements: [], resolved: true };
36
+ const list = unwrap(fields.get('slots'));
37
+ if (!list || !ts.isArrayLiteralExpression(list)) return { placements: [], resolved: false };
38
+ const placements = [];
39
+ let resolved = true;
40
+ for (const element of list.elements) {
41
+ const object = unwrap(element);
42
+ const slot =
43
+ object && ts.isObjectLiteralExpression(object)
44
+ ? object.properties.find(
45
+ (item) =>
46
+ (ts.isPropertyAssignment(item) || ts.isShorthandPropertyAssignment(item)) &&
47
+ !ts.isComputedPropertyName(item.name) &&
48
+ item.name.text === 'slot',
49
+ )
50
+ : undefined;
51
+ const name = slot
52
+ ? literal(ts.isPropertyAssignment(slot) ? slot.initializer : slot.name)
53
+ : literal(element);
54
+ if (name === undefined) resolved = false;
55
+ else placements.push(name);
56
+ }
57
+ return { placements, resolved };
58
+ }
59
+
60
+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
61
+
62
+ /**
63
+ * Every slot the app knows, answering "where can I put this?": the owned contracts of the app,
64
+ * its enabled plugins and installed packages (their derived `*.slots.json`), plus name hints from
65
+ * package manifests and `bitakit.config.ts`; the same set doctor counts. Contributions come from
66
+ * the app's own files only: `ui/slots` components and Actions whose literal `slots` place them.
67
+ * Packages and `setup()` attach more at runtime. Nothing is executed; a field a file does not
68
+ * state literally is `null` (unknown), and files that could not be read are listed in `unresolved`.
69
+ * Contributions to IDs that are neither declared nor hinted are listed in `unknownTargets`.
70
+ */
71
+ export async function describeSlots(description) {
72
+ const modules = [
73
+ description.app,
74
+ ...description.plugins.filter((plugin) => plugin.enabled !== false),
75
+ ];
76
+ const absolute = (entries) =>
77
+ (entries ?? []).map((entry) => ({ ...entry, file: path.join(description.root, entry.file) }));
78
+ const relative = (file) => path.relative(description.root, file).split(path.sep).join('/');
79
+ const moduleId = (module) => (module === description.app ? '' : module.id);
80
+ const unresolved = new Set(description.unresolvedSlots ?? []);
81
+
82
+ const owners = new Map();
83
+ const payloads = new Map();
84
+ for (const module of modules) {
85
+ for (const entry of module.slotDefinitions ?? []) owners.set(entry.file, module.id);
86
+ const { definitions } = await describeDefinitions(absolute(module.slotDefinitions), {
87
+ helper: 'defineSlot',
88
+ moduleId: moduleId(module),
89
+ inspect: payloadOf,
90
+ });
91
+ for (const item of definitions) payloads.set(`${relative(item.file)}\0${item.id}`, item);
92
+ }
93
+
94
+ const contributions = new Map();
95
+ const contribute = (slot, entry) =>
96
+ contributions.set(slot, [...(contributions.get(slot) ?? []), entry]);
97
+ for (const module of modules) {
98
+ for (const entry of module.slots ?? [])
99
+ contribute(entry.path, {
100
+ kind: 'component',
101
+ id: null,
102
+ plugin: module.id,
103
+ source: entry.file,
104
+ });
105
+ const actions = await describeDefinitions(absolute(module.actions), {
106
+ helper: 'defineAction',
107
+ moduleId: moduleId(module),
108
+ inspect: placementsOf,
109
+ });
110
+ actions.unresolved.forEach((file) => unresolved.add(relative(file)));
111
+ for (const action of actions.definitions) {
112
+ if (!action.resolved) unresolved.add(relative(action.file));
113
+ for (const slot of new Set(action.placements))
114
+ contribute(slot, {
115
+ kind: 'action',
116
+ id: action.id,
117
+ plugin: module.id,
118
+ source: relative(action.file),
119
+ });
120
+ }
121
+ }
122
+
123
+ const slots = (description.slotDeclarations ?? []).map((declaration) => {
124
+ const local = owners.get(declaration.file);
125
+ const details = payloads.get(`${declaration.file}\0${declaration.id}`);
126
+ return {
127
+ id: declaration.id,
128
+ owner:
129
+ local ??
130
+ (description.installedPackages ?? []).find((name) =>
131
+ declaration.file.startsWith(`${name}/`),
132
+ ) ??
133
+ declaration.plugin ??
134
+ null,
135
+ plugin: declaration.plugin ?? null,
136
+ contract: true,
137
+ accepts: declaration.accepts ?? null,
138
+ policy: declaration.policy ?? null,
139
+ // Package sidecars carry no payload description.
140
+ payload: local !== undefined && details ? details.payload : null,
141
+ payloadKeys: local !== undefined && details ? details.payloadKeys : null,
142
+ source: local !== undefined ? declaration.file : null,
143
+ contributions: contributions.get(declaration.id) ?? [],
144
+ };
145
+ });
146
+ const declared = new Set(slots.map((slot) => slot.id));
147
+ for (const id of description.slots ?? [])
148
+ if (!declared.has(id)) {
149
+ declared.add(id);
150
+ slots.push({
151
+ id,
152
+ owner: null,
153
+ plugin: null,
154
+ contract: false,
155
+ accepts: null,
156
+ policy: null,
157
+ payload: null,
158
+ payloadKeys: null,
159
+ source: null,
160
+ contributions: contributions.get(id) ?? [],
161
+ });
162
+ }
163
+ // A placement on a slot nobody declares renders nowhere; list it instead of dropping it.
164
+ const unknownTargets = [...contributions]
165
+ .filter(([slot]) => !declared.has(slot))
166
+ .flatMap(([slot, entries]) => entries.map((entry) => ({ slot, ...entry })));
167
+
168
+ // Group the app and its plugins first, then packages, then contract-less name hints.
169
+ const order = [...modules.map((module) => module.id), ...(description.installedPackages ?? [])];
170
+ const rank = (slot) => {
171
+ const index = slot.contract ? order.indexOf(slot.owner) : -1;
172
+ return index >= 0 ? index : order.length + (slot.contract ? 0 : 1);
173
+ };
174
+ return {
175
+ version: 1,
176
+ slots: slots
177
+ .map((slot, index) => ({ slot, index }))
178
+ .sort((a, b) => rank(a.slot) - rank(b.slot) || a.index - b.index)
179
+ .map(({ slot }) => slot),
180
+ unresolved: [...unresolved],
181
+ unknownTargets,
182
+ };
183
+ }
184
+
185
+ /** The short human listing: one line per slot under its owner. */
186
+ export function formatSlots(result, { dim = (text) => text } = {}) {
187
+ const lines = result.slots.length ? [] : ['No slots are declared.'];
188
+ const width = Math.max(0, ...result.slots.map((slot) => slot.id.length));
189
+ let group;
190
+ for (const slot of result.slots) {
191
+ // Only local declarations have a source file in the app.
192
+ const title = !slot.contract
193
+ ? 'Name hints without a slot contract'
194
+ : slot.source
195
+ ? `Plugin "${slot.owner}"`
196
+ : `Package "${slot.owner}"`;
197
+ if (title !== group) lines.push('', title);
198
+ group = title;
199
+ lines.push(
200
+ ` ${slot.id.padEnd(width)} ${(slot.accepts ?? 'unknown').padEnd(9)} ${plural(slot.contributions.length, 'contribution')}`,
201
+ );
202
+ }
203
+ if (result.slots.length)
204
+ lines.push(
205
+ '',
206
+ dim(
207
+ "Contributions count this app's ui/slots files and Action slots; packages add theirs at runtime.",
208
+ ),
209
+ dim('Payload keys, sources and contributors: npx bitakit slots --json'),
210
+ );
211
+ if (result.unknownTargets?.length)
212
+ lines.push(
213
+ '',
214
+ `${plural(result.unknownTargets.length, 'contribution')} to undeclared slots:`,
215
+ ...result.unknownTargets.map(
216
+ (entry) =>
217
+ ` ${entry.slot} ${entry.kind === 'action' ? `Action ${entry.id}` : 'component'} ${entry.source}`,
218
+ ),
219
+ );
220
+ if (result.unresolved.length)
221
+ lines.push(
222
+ '',
223
+ `${plural(result.unresolved.length, 'file')} could not be read statically:`,
224
+ ...result.unresolved.map((file) => ` ${file}`),
225
+ );
226
+ return lines;
227
+ }