@bitakit/cli 0.2.1 → 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.
@@ -0,0 +1,385 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+
5
+ /** Set by `@bitakit/ui`'s provider (runtime-state-attribute.ts): `starting`, `ready`, `failed`. */
6
+ const runtimeAttribute = 'data-bitakit-runtime';
7
+ /** After network idle, a page that has not set the attribute within this time has no provider. */
8
+ const runtimeAppearMs = 5000;
9
+ const excerptLength = 500;
10
+ const messageLength = 2000;
11
+
12
+ export const playwrightInstall = [
13
+ 'npm install --save-dev playwright',
14
+ 'npx playwright install chromium',
15
+ ];
16
+ // Linux hosts (containers, CI) also need Chromium's system libraries.
17
+ const browserInstall =
18
+ process.platform === 'linux'
19
+ ? 'npx playwright install --with-deps chromium'
20
+ : playwrightInstall[1];
21
+
22
+ /** The check could not run in this environment; `commands` fix it. The CLI exits with 2. */
23
+ export class CheckPageSetupError extends Error {
24
+ constructor(message, commands) {
25
+ super(message);
26
+ this.name = 'CheckPageSetupError';
27
+ this.commands = commands;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Playwright's Chromium as the project resolves it. The CLI never depends on or installs
33
+ * Playwright, so a project opts in by installing `playwright` or `@playwright/test` itself.
34
+ */
35
+ export function loadChromium(cwd = process.cwd()) {
36
+ const require = createRequire(path.join(path.resolve(cwd), 'package.json'));
37
+ for (const name of ['playwright', '@playwright/test']) {
38
+ let chromium;
39
+ try {
40
+ ({ chromium } = require(name));
41
+ } catch (error) {
42
+ if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') continue;
43
+ throw error;
44
+ }
45
+ let executable;
46
+ try {
47
+ executable = chromium.executablePath();
48
+ } catch {}
49
+ if (!executable || !existsSync(executable))
50
+ throw new CheckPageSetupError(
51
+ `Playwright is installed (${name}), but its Chromium browser is not.`,
52
+ [browserInstall],
53
+ );
54
+ return chromium;
55
+ }
56
+ throw new CheckPageSetupError(
57
+ 'check-page needs Playwright, and this project does not install it.',
58
+ playwrightInstall,
59
+ );
60
+ }
61
+
62
+ /** `/todos` against the base URL; an absolute http(s) URL stays as it is. */
63
+ export function pageUrl(target, baseUrl = 'http://localhost:3000') {
64
+ if (/^https?:\/\//i.test(target)) return new URL(target).href;
65
+ if (!target.startsWith('/') || target.startsWith('//'))
66
+ throw new Error(`Pass a path that starts with one "/" (/todos) or a full http:// URL.`);
67
+ let base;
68
+ try {
69
+ base = new URL(baseUrl);
70
+ } catch {}
71
+ if (!base || !/^https?:$/.test(base.protocol))
72
+ throw new Error(
73
+ `--base-url takes a full URL such as http://localhost:3000 (got "${baseUrl}").`,
74
+ );
75
+ return new URL(target, base).href;
76
+ }
77
+
78
+ /**
79
+ * Loads one page in headless Chromium and reports what HTTP alone cannot show: the rendered
80
+ * headings and text, the BitaKit runtime state, `[bitakit]` errors, console and page errors and
81
+ * failed same-origin requests. `ok` is false when any error was seen; warnings do not count.
82
+ */
83
+ export async function checkPage(
84
+ target,
85
+ { baseUrl, timeout = 30000, screenshot, cwd = process.cwd() } = {},
86
+ ) {
87
+ const url = pageUrl(target, baseUrl);
88
+ const chromium = loadChromium(cwd);
89
+ const origin = new URL(url).origin;
90
+ const deadline = Date.now() + timeout;
91
+ // Playwright treats a timeout of 0 as "no timeout"; an exhausted budget must still end.
92
+ const remaining = () => Math.max(1, deadline - Date.now());
93
+ const logged = [];
94
+ const pageErrors = [];
95
+ const failedRequests = [];
96
+ const sameOrigin = (address) => {
97
+ try {
98
+ return new URL(address).origin === origin;
99
+ } catch {
100
+ return false;
101
+ }
102
+ };
103
+
104
+ let browser;
105
+ try {
106
+ browser = await chromium.launch();
107
+ } catch (error) {
108
+ throw new CheckPageSetupError(`Chromium did not start: ${error.message.split('\n')[0]}`, [
109
+ browserInstall,
110
+ ]);
111
+ }
112
+ try {
113
+ const page = await browser.newPage();
114
+ // Record every runtime state the page passes through: a failed production startup can hand
115
+ // the document to Next's error page, which drops the attribute from <html> again.
116
+ await page.addInitScript((name) => {
117
+ const seen = (window.__bitakitRuntimeSeen = []);
118
+ new MutationObserver((records) => {
119
+ for (const record of records) {
120
+ const value = record.target.getAttribute?.(name);
121
+ if (record.oldValue) seen.push(record.oldValue);
122
+ if (value) seen.push(value);
123
+ }
124
+ }).observe(document, {
125
+ subtree: true,
126
+ attributes: true,
127
+ attributeOldValue: true,
128
+ attributeFilter: [name],
129
+ });
130
+ }, runtimeAttribute);
131
+ page.on('console', (message) => {
132
+ const type = message.type();
133
+ if (type !== 'error' && type !== 'warning') return;
134
+ const { url: source, lineNumber } = message.location();
135
+ logged.push({
136
+ type,
137
+ text: consoleText(message.text()),
138
+ source: source ? `${source}:${lineNumber + 1}` : undefined,
139
+ url: source,
140
+ });
141
+ });
142
+ page.on('pageerror', (error) =>
143
+ pageErrors.push({ message: clip(`${error.name}: ${error.message}`) }),
144
+ );
145
+ // The document itself is reported as `status` or `loadError`.
146
+ const isDocument = (request) =>
147
+ request.isNavigationRequest() && request.frame() === page.mainFrame();
148
+ page.on('response', (response) => {
149
+ const request = response.request();
150
+ if (isDocument(request)) return;
151
+ if (response.status() >= 400 && sameOrigin(response.url()))
152
+ failedRequests.push({
153
+ method: request.method(),
154
+ url: response.url(),
155
+ status: response.status(),
156
+ });
157
+ });
158
+ page.on('requestfailed', (request) => {
159
+ const error = request.failure()?.errorText ?? 'failed';
160
+ // Aborts are navigation and prefetch cancellations, not broken resources.
161
+ if (!isDocument(request) && sameOrigin(request.url()) && !error.includes('ERR_ABORTED'))
162
+ failedRequests.push({ method: request.method(), url: request.url(), error });
163
+ });
164
+
165
+ let response = null;
166
+ let loadError = null;
167
+ let networkIdle = false;
168
+ try {
169
+ response = await page.goto(url, { waitUntil: 'load', timeout: remaining() });
170
+ networkIdle = await page.waitForLoadState('networkidle', { timeout: remaining() }).then(
171
+ () => true,
172
+ () => false,
173
+ );
174
+ } catch (error) {
175
+ loadError = clip(error.message.split('\n')[0].replace(/^page\.goto: /, ''));
176
+ }
177
+
178
+ let runtime = null;
179
+ if (!loadError) {
180
+ runtime = await waitForRuntime(page, Math.min(runtimeAppearMs, remaining()), remaining);
181
+ // Let React commit what readiness unlocked (plugin pages and slots) before reading the DOM.
182
+ await page
183
+ .evaluate(
184
+ () =>
185
+ new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
186
+ )
187
+ .catch(() => {});
188
+ }
189
+ const content = loadError
190
+ ? { title: '', headings: [], text: '', textSource: 'body' }
191
+ : await page.evaluate(readContent, excerptLength).catch(() => ({
192
+ title: '',
193
+ headings: [],
194
+ text: '',
195
+ textSource: 'body',
196
+ }));
197
+ let screenshotFile = null;
198
+ if (screenshot && !loadError) {
199
+ screenshotFile = path.resolve(cwd, screenshot);
200
+ await page.screenshot({ path: screenshotFile, fullPage: true });
201
+ }
202
+
203
+ const status = response?.status() ?? null;
204
+ // Chromium also logs each failed load as a console error; report it once, as a request.
205
+ const reported = new Set(failedRequests.map((request) => request.url));
206
+ if (status !== null && status >= 400) reported.add(response.url());
207
+ const errors = logged.filter(
208
+ (entry) =>
209
+ entry.type === 'error' &&
210
+ !(entry.text.startsWith('Failed to load resource:') && reported.has(entry.url)),
211
+ );
212
+ const bitakitErrors = errors
213
+ .filter((entry) => entry.text.startsWith('[bitakit] '))
214
+ .map((entry) => entry.text.slice('[bitakit] '.length));
215
+ const report = {
216
+ version: 1,
217
+ url,
218
+ finalUrl: loadError ? null : page.url(),
219
+ status,
220
+ title: content.title,
221
+ headings: content.headings,
222
+ text: content.text,
223
+ textSource: content.textSource,
224
+ runtime,
225
+ networkIdle,
226
+ loadError,
227
+ bitakitErrors: unique(bitakitErrors),
228
+ consoleErrors: messages(errors.filter((entry) => !entry.text.startsWith('[bitakit] '))),
229
+ consoleWarnings: messages(logged.filter((entry) => entry.type === 'warning')),
230
+ pageErrors,
231
+ failedRequests,
232
+ screenshot: screenshotFile,
233
+ };
234
+ const problems =
235
+ (loadError ? 1 : 0) +
236
+ (status !== null && status >= 400 ? 1 : 0) +
237
+ (runtime === 'failed' || runtime === 'starting' ? 1 : 0) +
238
+ report.bitakitErrors.length +
239
+ report.consoleErrors.length +
240
+ report.pageErrors.length +
241
+ report.failedRequests.length;
242
+ return { ...report, errors: problems, ok: problems === 0 };
243
+ } finally {
244
+ await browser.close();
245
+ }
246
+ }
247
+
248
+ /**
249
+ * `null` without a BitaKit provider; `failed` when startup failed at any point; otherwise the
250
+ * current state, or the last one seen when the attribute is gone.
251
+ */
252
+ async function waitForRuntime(page, appearMs, remaining) {
253
+ const states = (name) => ({
254
+ current: document.documentElement?.getAttribute(name) ?? null,
255
+ seen: window.__bitakitRuntimeSeen ?? [],
256
+ });
257
+ const appeared = await page
258
+ .waitForFunction(
259
+ (name) =>
260
+ document.documentElement?.hasAttribute(name) || window.__bitakitRuntimeSeen?.length > 0,
261
+ runtimeAttribute,
262
+ { timeout: appearMs },
263
+ )
264
+ .then(
265
+ () => true,
266
+ () => false,
267
+ );
268
+ if (!appeared) return null;
269
+ await page
270
+ .waitForFunction(
271
+ (name) =>
272
+ ['ready', 'failed'].includes(document.documentElement?.getAttribute(name)) ||
273
+ window.__bitakitRuntimeSeen?.includes('failed'),
274
+ runtimeAttribute,
275
+ { timeout: remaining() },
276
+ )
277
+ .catch(() => {});
278
+ const { current, seen } = await page
279
+ .evaluate(states, runtimeAttribute)
280
+ .catch(() => ({ current: null, seen: [] }));
281
+ if (seen.includes('failed')) return 'failed';
282
+ return current ?? seen.at(-1) ?? null;
283
+ }
284
+
285
+ /** Runs in the page: visible text only, so hidden dialogs and templates stay out. */
286
+ function readContent(limit) {
287
+ const clean = (text) => (text ?? '').replace(/\s+/g, ' ').trim();
288
+ const main = document.querySelector('main');
289
+ const text = clean((main ?? document.body)?.innerText);
290
+ return {
291
+ title: document.title,
292
+ // Component libraries also mark headings with role="heading" (Shell's page states do).
293
+ headings: [...document.querySelectorAll('h1, h2, h3, [role="heading"][aria-level]')]
294
+ .map((heading) => ({
295
+ level: Number(heading.getAttribute('aria-level') ?? heading.tagName[1]),
296
+ text: clean(heading.innerText),
297
+ }))
298
+ .filter((heading) => heading.level <= 3 && heading.text),
299
+ text: text.length > limit ? `${text.slice(0, limit)}…` : text,
300
+ textSource: main ? 'main' : 'body',
301
+ };
302
+ }
303
+
304
+ const clip = (text) => (text.length > messageLength ? `${text.slice(0, messageLength)}…` : text);
305
+ /**
306
+ * React logs errors with format specifiers (`%o`, `%s`) and a long component stack; agents need
307
+ * the message, so drop the specifiers and keep the first lines.
308
+ */
309
+ function consoleText(text) {
310
+ if (!/%[sdifoOc]/.test(text)) return text;
311
+ const lines = text
312
+ .replace(/%[sdifoOc]/g, '')
313
+ .split('\n')
314
+ .map((line) => line.trim())
315
+ .filter(Boolean);
316
+ return lines.slice(0, 6).join('\n');
317
+ }
318
+ const unique = (texts) => [...new Set(texts)];
319
+ /** StrictMode and retries repeat messages; each text is listed once with how often it appeared. */
320
+ function messages(entries) {
321
+ const byText = new Map();
322
+ for (const entry of entries) {
323
+ const existing = byText.get(entry.text);
324
+ if (existing) existing.count++;
325
+ else byText.set(entry.text, { text: clip(entry.text), source: entry.source, count: 1 });
326
+ }
327
+ return [...byText.values()];
328
+ }
329
+
330
+ /** The human-readable report: what rendered first, then every error with its source. */
331
+ export function formatPageReport(report) {
332
+ const lines = [`\nBitaKit check-page · ${report.url}\n`];
333
+ if (report.loadError) {
334
+ lines.push(`✖ The page did not load: ${report.loadError}`);
335
+ if (/ERR_CONNECTION_REFUSED|ECONNREFUSED/.test(report.loadError))
336
+ lines.push(' Is the dev server running? Start it with "npm run dev", or pass --base-url.');
337
+ } else {
338
+ const redirected = report.finalUrl !== report.url ? ` (${report.finalUrl})` : '';
339
+ const headings = report.headings.map((heading) => `h${heading.level} ${heading.text}`);
340
+ lines.push(
341
+ ` Status ${report.status ?? 'none'}${redirected}`,
342
+ ` Title ${report.title || '(none)'}`,
343
+ ` Runtime ${describeRuntime(report)}`,
344
+ ` Headings ${headings.join(' · ') || '(none)'}`,
345
+ ` ${report.textSource === 'main' ? 'Main' : 'Body'} ${report.text || '(empty)'}`,
346
+ );
347
+ if (!report.networkIdle) lines.push(' Network still busy when the timeout ended');
348
+ }
349
+ const section = (title, items, format) => {
350
+ if (!items.length) return;
351
+ lines.push(`\n${title} (${items.length})`);
352
+ for (const item of items) lines.push(` ${format(item).replaceAll('\n', '\n ')}`);
353
+ };
354
+ const counted = (entry) =>
355
+ entry.text +
356
+ (entry.count > 1 ? ` (×${entry.count})` : '') +
357
+ (entry.source ? `\n at ${entry.source}` : '');
358
+ section('BitaKit errors', report.bitakitErrors, (text) => text);
359
+ section('Page errors', report.pageErrors, (error) => error.message);
360
+ section('Console errors', report.consoleErrors, counted);
361
+ section(
362
+ 'Failed requests',
363
+ report.failedRequests,
364
+ (request) => `${request.status ?? request.error} ${request.method} ${request.url}`,
365
+ );
366
+ section('Console warnings', report.consoleWarnings, counted);
367
+ if (report.screenshot) lines.push(`\nScreenshot: ${report.screenshot}`);
368
+ const warnings = report.consoleWarnings.length;
369
+ lines.push(
370
+ `\n${report.ok ? '✔ No errors' : `✖ ${plural(report.errors, 'error')}`}` +
371
+ `${warnings ? `, ${plural(warnings, 'warning')}` : ''}.\n`,
372
+ );
373
+ return lines.join('\n');
374
+ }
375
+
376
+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
377
+
378
+ function describeRuntime({ runtime, pageErrors }) {
379
+ if (runtime === null)
380
+ return pageErrors.length
381
+ ? 'not found (the app may have crashed before startup; see page errors)'
382
+ : 'not found (no <html data-bitakit-runtime>: no provider, or an older @bitakit/ui)';
383
+ if (runtime === 'starting') return 'starting: did not become ready before the timeout';
384
+ return runtime;
385
+ }
package/src/cli.mjs CHANGED
@@ -3,18 +3,15 @@ import { readFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { styleText } from 'node:util';
5
5
  import { Command } from 'commander';
6
- import {
7
- describeBitaKit,
8
- generateBitaKit,
9
- migrateProject,
10
- watchBitaKit,
11
- } from '@bitakit/discovery';
6
+ import { describeBitaKit, generateBitaKit, migrateProject, watchBitaKit } from '@bitakit/discovery';
12
7
  import { addContribution, addPlugin, contributionKinds } from './add.mjs';
13
8
  import { inspectionFromDescription } from './inventory.mjs';
14
9
  import { buildPlugin } from './build.mjs';
10
+ import { CheckPageSetupError, checkPage, formatPageReport } from './check-page.mjs';
15
11
  import { doctor } from './doctor.mjs';
16
12
  import { initProject } from './init.mjs';
17
13
  import { findProject, findProjectRoot } from './project.mjs';
14
+ import { describeSlots, formatSlots } from './slots.mjs';
18
15
 
19
16
  const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
20
17
  const relative = (file) => path.relative(process.cwd(), file) || '.';
@@ -48,7 +45,7 @@ add
48
45
  created(result.created);
49
46
  console.log(
50
47
  result.navigation
51
- ? `\n"${result.title}" now appears in the navigation and opens ${result.path}.\nThe dev server picks it up automatically; no registration needed.\nNext: npx bitakit add service ${name}/items, then npx bitakit add action ${name}/<name>.\n`
48
+ ? `\n"${result.title}" now appears in the navigation and opens ${result.path}.\nThe dev server picks it up automatically; no registration needed.\nNext: shared state with npx bitakit add service ${name}/<name>, a button with npx bitakit add action ${name}/<name>.\n`
52
49
  : result.path
53
50
  ? `\n"${result.title}" opens ${result.path}.\nThe dev server picks it up automatically; no registration needed.\n`
54
51
  : `\nThe dev server picks it up automatically; no registration needed.\n`,
@@ -62,14 +59,18 @@ for (const kind of contributionKinds)
62
59
  ? '[plugin]'
63
60
  : kind === 'layout'
64
61
  ? '<name>'
65
- : '<target>',
62
+ : kind === 'test'
63
+ ? '<plugin>'
64
+ : '<target>',
66
65
  kind === 'events' || kind === 'settings' || kind === 'settings-page'
67
66
  ? `the plugin that owns the ${kind}; omit it inside a plugin package`
68
67
  : kind === 'layout'
69
68
  ? 'the layout name; pages choose it with export const layout'
70
- : kind === 'slot'
71
- ? '"<plugin>/<slot path>": "activity/projects/sidebar" adds a component of plugin "activity" to slot "projects.sidebar"'
72
- : `"<plugin>/<name>" in an app (nested names allowed), or "<name>" inside a plugin package`,
69
+ : kind === 'test'
70
+ ? 'an existing plugin of the app, for example "notes"'
71
+ : kind === 'slot'
72
+ ? '"<plugin>/<slot path>": "activity/todos.footer" adds a component of plugin "activity" to slot "todos.footer"'
73
+ : `"<plugin>/<name>" in an app (nested names allowed), or "<name>" inside a plugin package`,
73
74
  )
74
75
  .description(
75
76
  kind === 'events' || kind === 'settings'
@@ -78,7 +79,9 @@ for (const kind of contributionKinds)
78
79
  ? "Create ui/settings/page.tsx, which replaces the plugin's generated settings page."
79
80
  : kind === 'layout'
80
81
  ? 'Create src/layouts/<name>.tsx of the app.'
81
- : `Create ${/^[aeiou]/.test(kind) ? 'an' : 'a'} ${kind} file. Its ID comes from the file path.`,
82
+ : kind === 'test'
83
+ ? 'Create tests/<plugin>.test.ts, a headless test that mounts the plugin, and list what running it still needs.'
84
+ : `Create ${/^[aeiou]/.test(kind) ? 'an' : 'a'} ${kind} file. Its ID comes from the file path.`,
82
85
  )
83
86
  .action(async (target) => {
84
87
  const result = await addContribution(kind, target);
@@ -86,23 +89,39 @@ for (const kind of contributionKinds)
86
89
  console.log(
87
90
  kind === 'slot'
88
91
  ? `\nCreated a component of plugin "${result.plugin}" for slot "${result.id}":`
89
- : `\nCreated ${kind} ${kind === 'page' ? result.path : `"${result.id}"`}:`,
92
+ : kind === 'test'
93
+ ? `\nCreated a test for plugin "${result.plugin}":`
94
+ : `\nCreated ${kind} ${kind === 'page' ? result.path : `"${result.id}"`}:`,
90
95
  );
91
96
  created(result.created);
97
+ if (result.setup?.length)
98
+ console.log(
99
+ `\nBefore the first run:\n${result.setup.map((line) => ` ${line}`).join('\n')}`,
100
+ );
101
+ if (result.run)
102
+ console.log(`\nRun it from the app root with ${result.run} (Node.js 24 or newer).`);
92
103
  console.log('');
93
104
  });
94
105
 
95
106
  program
96
107
  .command('init')
97
108
  .description(
98
- 'Wire an existing Next.js or TanStack Start app: bitakit.config.ts, the config wrapper or Vite plugin, the provider, the catch-all route and .gitignore.',
109
+ 'Wire an existing Next.js or TanStack Start app: bitakit.config.ts, the config wrapper or Vite plugin, the provider, the catch-all route, .gitignore, and the agent files (AGENTS.md, CLAUDE.md and the bitakit-app-development skill).',
99
110
  )
100
- .action(async () => {
101
- const { written, skipped, install } = await initProject();
111
+ .option(
112
+ '--update-agent-files',
113
+ 'also refresh the BitaKit block in AGENTS.md and replace unedited skill copies with this version; edited copies are kept',
114
+ )
115
+ .action(async (options) => {
116
+ const { written, skipped, install, installDev } = await initProject({
117
+ updateAgentFiles: options.updateAgentFiles,
118
+ });
102
119
  if (written.length) {
103
120
  console.log('\nWritten:');
104
- for (const { file, created } of written)
105
- console.log(` ${styleText('green', created ? '+' : '~')} ${relative(file)}`);
121
+ for (const { file, created, note } of written)
122
+ console.log(
123
+ ` ${styleText('green', created ? '+' : '~')} ${relative(file)}${note ? ` ${styleText('dim', `(${note})`)}` : ''}`,
124
+ );
106
125
  }
107
126
  if (skipped.length) {
108
127
  console.log('\nSkipped:');
@@ -114,6 +133,10 @@ program
114
133
  if (!written.length) console.log('\nNothing to write: the app is already wired.');
115
134
  if (install.length)
116
135
  console.log(`\nInstall the packages the wiring imports:\n npm install ${install.join(' ')}`);
136
+ if (installDev.length)
137
+ console.log(
138
+ `\nInstall the bitakit command for this app:\n npm install --save-dev ${installDev.join(' ')}`,
139
+ );
117
140
  console.log('\nThen run "npx bitakit generate" and "npx bitakit doctor".\n');
118
141
  });
119
142
 
@@ -218,6 +241,55 @@ program
218
241
  if (errors) process.exitCode = 1;
219
242
  });
220
243
 
244
+ program
245
+ .command('check-page')
246
+ .argument('<target>', 'a path such as /todos, or a full http:// URL')
247
+ .option('--base-url <url>', 'where a path is resolved', 'http://localhost:3000')
248
+ .option('--json', 'machine-readable output')
249
+ .option('--screenshot <file>', 'also save a full-page PNG')
250
+ .option('--timeout <ms>', 'time budget for loading the page and runtime startup', '30000')
251
+ .description(
252
+ 'Open a page of the running app in headless Chromium and report what rendered and every error. Needs Playwright in the project.',
253
+ )
254
+ .action(async (target, options) => {
255
+ const timeout = Number(options.timeout);
256
+ if (!Number.isInteger(timeout) || timeout <= 0)
257
+ throw new Error(
258
+ `--timeout takes milliseconds, for example 30000 (got "${options.timeout}").`,
259
+ );
260
+ let report;
261
+ try {
262
+ report = await checkPage(target, {
263
+ baseUrl: options.baseUrl,
264
+ timeout,
265
+ screenshot: options.screenshot,
266
+ });
267
+ } catch (error) {
268
+ if (!(error instanceof CheckPageSetupError)) throw error;
269
+ // Exit code 2: the check could not run; nothing about the page is known.
270
+ process.exitCode = 2;
271
+ if (options.json)
272
+ console.log(
273
+ JSON.stringify(
274
+ {
275
+ version: 1,
276
+ ok: false,
277
+ setupError: { message: error.message, commands: error.commands },
278
+ },
279
+ null,
280
+ 2,
281
+ ),
282
+ );
283
+ else
284
+ console.error(
285
+ `${styleText('red', error.message)}\nRun in the project, then check again:\n${error.commands.map((command) => ` ${command}`).join('\n')}`,
286
+ );
287
+ return;
288
+ }
289
+ console.log(options.json ? JSON.stringify(report, null, 2) : formatPageReport(report));
290
+ if (!report.ok) process.exitCode = 1;
291
+ });
292
+
221
293
  program
222
294
  .command('info')
223
295
  .option('--json', 'machine-readable output')
@@ -258,6 +330,25 @@ program
258
330
  console.log('');
259
331
  });
260
332
 
333
+ program
334
+ .command('slots')
335
+ .option('--json', 'machine-readable output')
336
+ .description(
337
+ 'List the slots you can fill: owner, what each accepts and what this app already puts there.',
338
+ )
339
+ .action(async (options) => {
340
+ const project = await findProject();
341
+ if (project.kind !== 'app') throw new Error('Run "bitakit slots" inside an app.');
342
+ const result = await describeSlots(await describeBitaKit(project.root));
343
+ if (options.json) {
344
+ console.log(JSON.stringify(result, null, 2));
345
+ return;
346
+ }
347
+ for (const line of formatSlots(result, { dim: (text) => styleText('dim', text) }))
348
+ console.log(line);
349
+ console.log('');
350
+ });
351
+
261
352
  try {
262
353
  await program.parseAsync();
263
354
  } catch (error) {
@@ -0,0 +1,66 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {
4
+ agentRulesBegin,
5
+ agentRulesEnd,
6
+ projectAgentRules,
7
+ refreshAgentRules,
8
+ } from './agent-rules.mjs';
9
+ import { appDevelopmentSkillPaths, cliVersion, inspectSkillCopy } from './agent-skill.mjs';
10
+ import { exists } from './project.mjs';
11
+
12
+ /**
13
+ * The agent files create-app and `bitakit init` write: both skill copies present and equal,
14
+ * unedited copies current with this CLI, and the AGENTS.md BitaKit block equal to the rules init
15
+ * writes for this app. Edited copies are the team's and only count when the two folders differ.
16
+ * Undefined for an app without the BitaKit block or a skill folder.
17
+ */
18
+ export async function checkAgentFiles(project) {
19
+ const agents = await readFile(path.join(project.root, 'AGENTS.md'), 'utf8').catch(
20
+ () => undefined,
21
+ );
22
+ const hasRules = Boolean(agents?.includes(agentRulesBegin));
23
+ const folders = appDevelopmentSkillPaths.map((file) => path.dirname(file));
24
+ const present = await Promise.all(
25
+ folders.map((folder) => exists(path.join(project.root, folder))),
26
+ );
27
+ if (!hasRules && !present.includes(true)) return undefined;
28
+
29
+ const details = [];
30
+ let unterminated = false;
31
+ const copies = await Promise.all(
32
+ folders.map((folder) => inspectSkillCopy(path.join(project.root, folder))),
33
+ );
34
+ copies.forEach((copy, index) => {
35
+ if (copy.state === 'missing') details.push(`${folders[index]} is missing.`);
36
+ if (copy.state === 'outdated')
37
+ details.push(
38
+ `${folders[index]} is from @bitakit/cli ${copy.version}; this CLI ships ${cliVersion}.`,
39
+ );
40
+ });
41
+ if (copies.every((copy) => copy.state !== 'missing') && copies[0].checksum !== copies[1].checksum)
42
+ details.push(`${folders[0]} and ${folders[1]} differ.`);
43
+ if (!hasRules) details.push('AGENTS.md has no BitaKit block.');
44
+ else {
45
+ const rules = await projectAgentRules(project);
46
+ const refreshed = rules && refreshAgentRules(agents, rules);
47
+ // init only replaces a complete block, so a lost end marker has to be restored first.
48
+ unterminated = Boolean(rules) && refreshed === undefined;
49
+ if (unterminated)
50
+ details.push(`The BitaKit block in AGENTS.md has no ${agentRulesEnd} marker.`);
51
+ else if (rules && refreshed !== agents)
52
+ details.push('The BitaKit block in AGENTS.md differs from the rules of this CLI.');
53
+ }
54
+
55
+ if (!details.length) return { status: 'ok', title: 'Agent files are in sync' };
56
+ const update =
57
+ 'Run "npx bitakit init --update-agent-files". It keeps skill folders you edited; delete such a folder first to get the current skill.';
58
+ return {
59
+ status: 'warn',
60
+ title: 'Agent files are out of sync',
61
+ details,
62
+ fix: unterminated
63
+ ? `Add the ${agentRulesEnd} line where the BitaKit block in AGENTS.md ends.\n${update}`
64
+ : update,
65
+ };
66
+ }
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
 
@@ -884,7 +887,7 @@ function checkSlots(description) {
884
887
  if (!problems.length)
885
888
  return {
886
889
  status: 'ok',
887
- // A clean run stays short; `bitakit info` lists the slots.
890
+ // A clean run stays short; `bitakit slots` lists the slots.
888
891
  title: declared.size
889
892
  ? `Slot files target declared slots (${plural(declared.size, 'slot')} available)`
890
893
  : 'No layout slots are declared',