@bitakit/cli 0.2.9 → 0.2.11

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/AGENTS.md CHANGED
@@ -29,6 +29,19 @@ doctor exits 1 on errors and names the fix.
29
29
  and a `CLAUDE.md` importing it. Read the local guide before editing the plugin. Keep its purpose,
30
30
  contracts and checks there and update them with the code; shared rules stay in the app guide.
31
31
 
32
+ ## Explicit updates
33
+
34
+ Plain `npx bitakit doctor` reports local health and available updates without installing.
35
+ Use `npx bitakit doctor --check-updates` for a focused update report; it is
36
+ read-only and supports `--json`. For an authorized BitaKit update, use `npx bitakit doctor
37
+ --update` (also `--json`), then run the project's checks. Registry failures do not suppress local health diagnostics; update status is unavailable.
38
+ The commands distinguish installed/running versions, latest and range/peer-filtered candidates;
39
+ unavailable results are unknown, not current. The native project package manager owns installation.
40
+ Updates preserve constraints, skip non-registry specifications and refuse ambiguous release-line
41
+ or peer selections. Existing `init --update-agent-files` refreshes through the project-local CLI,
42
+ preserving custom skills. External/global CLIs are never overwritten. Do not duplicate lookup
43
+ logic in a skill, schedule recurring checks, or ask again for authorization already given.
44
+
32
45
  ## Rules
33
46
 
34
47
  - Replace template bodies and tutorial comments with the real implementation.
package/README.md CHANGED
@@ -152,6 +152,37 @@ npx bitakit info [--json] # the plugins, services, actions, events and pages d
152
152
  npx bitakit slots [--json] # every slot you can fill: owner, accepts and this app's contributions
153
153
  ```
154
154
 
155
+ ### Explicit update checks
156
+
157
+ ```sh
158
+ npx bitakit doctor --check-updates # read-only registry lookup
159
+ npx bitakit doctor --update # authorized BitaKit updates and agent-file refresh
160
+ ```
161
+
162
+ Both accept `--json`; the two flags cannot be combined. Plain `doctor` reports local health
163
+ and available updates without installing anything. `--check-updates` focuses on updates only.
164
+ Registry failures leave local diagnostics and their exit status intact; JSON includes
165
+ `updateStatus: "unavailable"`. Each lookup has a bounded timeout and no retries.
166
+ The check reports the running CLI, project-declared
167
+ `@bitakit/*` packages, installed versions, registry `latest`, range/peer-filtered candidates,
168
+ and both skill copies. `latest` can belong to another release line. Candidates are advisory:
169
+ `npm-check-updates` filters declared ranges and peer constraints, while the package manager
170
+ and project tests validate the installed graph. Inaccessible results stay `unknown`, with a
171
+ nonzero exit status in `--check-updates`. Registry/auth settings remain with the detected npm, pnpm, Yarn or Bun
172
+ configuration; credentials are not printed. Peer inspection can also read other dependencies.
173
+
174
+ `--update` performs one fresh check, then uses the project's package manager to upgrade only
175
+ eligible declared BitaKit dependencies within their constraints. It refuses ranges allowing a
176
+ new release line and peer-filtered candidates a native range update cannot enforce. Native
177
+ resolution may update necessary transitive dependencies. It then runs the project-local CLI's
178
+ existing `init --update-agent-files`, preserving edited skills and user text outside managed
179
+ agent blocks. A failed install stops before that refresh; inspect the project diff before
180
+ retrying. The result includes `installedAfter` without another registry lookup. Run project
181
+ checks afterward. An external/global CLI is reported but never silently replaced; without a
182
+ project-local CLI, agent files are preserved and the report explains how to refresh them.
183
+ Workspace/catalog/file/URL dependency specifications are reported as unsupported rather than
184
+ rewritten. Unknown package managers or incomplete registry checks prevent mutation.
185
+
155
186
  For a replaceable (`single`) slot, `slots` also prints which candidate renders, from the app's
156
187
  files and `choose` in `bitakit.config.ts` (`renders app:split`, or `renders the default: choose
157
188
  one of ...`); `--json` adds `selection: { candidates, renders, reason, choice }`. Layout files
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/cli",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "description": "BitaKit project commands: add plugins and contributions, check a project with doctor.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,6 +28,9 @@
28
28
  "@bitakit/core": "^0.2.9",
29
29
  "@bitakit/discovery": "^0.2.6",
30
30
  "commander": "15.0.0",
31
+ "npm-check-updates": "^22.2.9",
32
+ "package-manager-detector": "^1.9.0",
33
+ "semver": "^7.8.5",
31
34
  "typescript": "^5.9.3"
32
35
  },
33
36
  "license": "MIT",
@@ -24,6 +24,18 @@ and explain in plain words what you built and why.
24
24
  - This skill targets consumer apps. Changes to BitaKit packages themselves follow the
25
25
  repository's development guide, release rules and tests.
26
26
 
27
+ ## Explicit update requests
28
+
29
+ Plain Doctor reports local health and available updates without installing.
30
+ When the user asks for a focused update check, run `npx bitakit doctor --check-updates` (read-only).
31
+ When they authorize updating BitaKit tooling, packages and skills, run
32
+ `npx bitakit doctor --update`, then the relevant project checks. Both support `--json`.
33
+ Doctor owns version lookup, package-manager integration and safe agent-file refresh; follow
34
+ its report for unavailable results, constraints or an external CLI. Do not duplicate that
35
+ logic, add recurring checks outside Doctor, refresh skills automatically, or repeat an authorization
36
+ already given. “Update everything” here covers BitaKit, not unrelated dependencies or a new
37
+ release line.
38
+
27
39
  ## Pick the recipe
28
40
 
29
41
  Read the reference needed for the task, then follow its links only when needed. Each has
@@ -79,6 +91,30 @@ Inspect what the task needs; reuse findings while the app's configuration remain
79
91
  and which component actually renders the slot you want. A declared slot shows nothing until an
80
92
  outlet renders it.
81
93
 
94
+ Before implementing a new project, plugin or capability, check for an existing solution.
95
+ At project planning, identify the needed capabilities and check each before implementing it;
96
+ check later additions when they arise. This check is mandatory, not conditional on uncertainty
97
+ or remembered package knowledge. First inspect local code and installed packages. If none
98
+ satisfies the need, search npm directly for suitable official `@bitakit/*` packages before
99
+ writing equivalent functionality. A `bitakit` keyword alone does not establish official
100
+ provenance; third-party package discovery is outside this workflow.
101
+
102
+ Descriptions and keywords identify candidates; verify suitability through their README,
103
+ package `AGENTS.md`, public contracts, compatible published versions and peer dependencies.
104
+ Reuse a suitable solution and implement only the necessary product composition, preserving
105
+ existing dependency authorization. Reuse verified findings during the task; refresh only when
106
+ relevant requirements or package state change, or the evidence becomes stale. Avoid repeated
107
+ npm/network calls for the same query or each edit; capabilities already satisfied by an inspected
108
+ package need no registry search. These are agent lookups during development, not application
109
+ runtime requests; add no application network behavior or caching infrastructure for discovery.
110
+ No search results do not prove absence: explain the
111
+ concrete gap before proposing a custom alternative and obtain explicit approval under the
112
+ existing policy before implementing it.
113
+
114
+ Keep discovery in this workflow, without a separate catalog, service or exhaustive package
115
+ list. When authoring a package, maintain its accurate description, relevant keywords and usage
116
+ documentation alongside it.
117
+
82
118
  ## Choose the mechanism
83
119
 
84
120
  Decide before writing code, and tell the user the plan in a sentence or two.
package/src/cli.mjs CHANGED
@@ -215,16 +215,48 @@ program
215
215
  program
216
216
  .command('doctor')
217
217
  .option('--json', 'machine-readable output')
218
+ .option('--check-updates', 'check published BitaKit updates (read-only, uses the registry)')
219
+ .option('--update', 'update compatible project BitaKit packages and refresh unedited agent files')
218
220
  .description(
219
- 'Check versions, wiring, routes, links, service names, styles and deprecated layouts.',
221
+ 'Check local project health and available BitaKit updates; never installs without --update.',
220
222
  )
221
223
  .action(async (options) => {
222
- const { project, results } = await doctor();
224
+ if (options.checkUpdates && options.update)
225
+ throw new Error('Use either --check-updates (read-only) or --update.');
226
+ if (options.checkUpdates || options.update) {
227
+ const { checkUpdates, updatePackages, formatUpdates } = await import('./doctor-updates.mjs');
228
+ const report = await (options.update ? updatePackages() : checkUpdates());
229
+ console.log(options.json ? JSON.stringify(report, null, 2) : formatUpdates(report));
230
+ if (!report.supportedManager || report.packages.some((item) => item.status === 'unknown'))
231
+ process.exitCode = 1;
232
+ return;
233
+ }
234
+ const { checkUpdates, formatUpdates } = await import('./doctor-updates.mjs');
235
+ const [{ project, results }, updates] = await Promise.all([
236
+ doctor(),
237
+ checkUpdates().catch(() => null),
238
+ ]);
223
239
  const errors = results.filter((result) => result.status === 'error').length;
224
240
  const warnings = results.filter((result) => result.status === 'warn').length;
225
241
  if (options.json) {
226
242
  console.log(
227
- JSON.stringify({ project: project.manifest.name, results, errors, warnings }, null, 2),
243
+ JSON.stringify(
244
+ {
245
+ project: project.manifest.name,
246
+ results,
247
+ errors,
248
+ warnings,
249
+ updates,
250
+ updateStatus:
251
+ !updates ||
252
+ !updates.supportedManager ||
253
+ updates.packages.some((item) => item.status === 'unknown')
254
+ ? 'unavailable'
255
+ : 'checked',
256
+ },
257
+ null,
258
+ 2,
259
+ ),
228
260
  );
229
261
  if (errors) process.exitCode = 1;
230
262
  return;
@@ -244,6 +276,11 @@ program
244
276
  console.log(
245
277
  `\n${errors ? `${errors} problem${errors === 1 ? '' : 's'}` : 'No problems'}${warnings ? `, ${warnings} warning${warnings === 1 ? '' : 's'}` : ''}.\n`,
246
278
  );
279
+ console.log(
280
+ updates
281
+ ? formatUpdates(updates)
282
+ : 'Update status unavailable; local health checks above are unaffected.',
283
+ );
247
284
  if (errors) process.exitCode = 1;
248
285
  });
249
286
 
@@ -0,0 +1,265 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import { readFile } from 'node:fs/promises';
5
+ import semver from 'semver';
6
+ import { detect, resolveCommand } from 'package-manager-detector';
7
+ import { appDevelopmentSkillPaths, cliVersion, inspectSkillCopy } from './agent-skill.mjs';
8
+ import { findProjectRoot } from './project.mjs';
9
+
10
+ const sections = ['dependencies', 'devDependencies', 'optionalDependencies'];
11
+ const official = (name) => name.startsWith('@bitakit/');
12
+
13
+ async function installedPackage(root, name) {
14
+ try {
15
+ const file = createRequire(path.join(root, 'package.json')).resolve(`${name}/package.json`);
16
+ return { file, manifest: JSON.parse(await readFile(file, 'utf8')) };
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+
22
+ /** Read-only registry checks for Doctor. The standard updater owns registry/auth and peer filtering. */
23
+ export async function checkUpdates({ cwd, lookup } = {}) {
24
+ const project = await findProjectRoot(cwd);
25
+ const manager = await detect({
26
+ cwd: project.root,
27
+ strategies: ['packageManager-field', 'devEngines-field', 'lockfile', 'install-metadata'],
28
+ });
29
+ const dependencies = Object.assign({}, ...sections.map((section) => project.manifest[section]));
30
+ const packages = await Promise.all(
31
+ Object.entries(dependencies)
32
+ .filter(([name]) => official(name))
33
+ .map(async ([name, range]) => {
34
+ const installed = await installedPackage(project.root, name);
35
+ return {
36
+ name,
37
+ range,
38
+ installed: installed?.manifest.version ?? null,
39
+ latest: null,
40
+ candidate: null,
41
+ status: 'unknown',
42
+ };
43
+ }),
44
+ );
45
+ const skills = await Promise.all(
46
+ appDevelopmentSkillPaths.map(async (file) => ({
47
+ file,
48
+ ...(await inspectSkillCopy(path.dirname(path.join(project.root, file)))),
49
+ })),
50
+ );
51
+ const report = {
52
+ project: project.manifest.name,
53
+ root: project.root,
54
+ manager: manager ?? null,
55
+ supportedManager: Boolean(manager && ['npm', 'pnpm', 'yarn', 'bun'].includes(manager.name)),
56
+ runningCli: cliVersion,
57
+ packages,
58
+ skills,
59
+ checkedAt: new Date().toISOString(),
60
+ notes: [],
61
+ };
62
+ if (!report.supportedManager) {
63
+ report.notes.push(
64
+ 'Package manager is unknown or unsupported; no registry requests or updates were made.',
65
+ );
66
+ return report;
67
+ }
68
+ // Include the executing CLI even when it came from npx rather than this project's dependencies.
69
+ if (!packages.some(({ name }) => name === '@bitakit/cli'))
70
+ packages.push({
71
+ name: '@bitakit/cli',
72
+ range: `~${cliVersion}`,
73
+ installed: null,
74
+ running: cliVersion,
75
+ latest: null,
76
+ candidate: null,
77
+ status: 'unknown',
78
+ external: true,
79
+ });
80
+ const eligible = packages.filter((item) => semver.validRange(item.range));
81
+ for (const item of packages.filter((item) => !eligible.includes(item)))
82
+ item.status = 'unsupported-spec';
83
+ const data = {
84
+ ...project.manifest,
85
+ dependencies: {
86
+ ...dependencies,
87
+ ...Object.fromEntries(
88
+ eligible.filter((item) => item.external).map((item) => [item.name, item.range]),
89
+ ),
90
+ },
91
+ };
92
+ const run = lookup ?? (await import('npm-check-updates')).run;
93
+ const common = {
94
+ cwd: project.root,
95
+ packageFile: path.join(project.root, 'package.json'),
96
+ packageData: data,
97
+ packageManager: manager.name,
98
+ dep: 'prod,dev,optional',
99
+ filter: eligible.map(({ name }) => name),
100
+ upgrade: false,
101
+ install: 'never',
102
+ interactive: false,
103
+ cache: false,
104
+ retry: 0,
105
+ timeout: 10000,
106
+ silent: true,
107
+ jsonUpgraded: true,
108
+ configFileName: '.bitakit-unused-ncu-config',
109
+ };
110
+ try {
111
+ const observed = new Map();
112
+ await run({
113
+ ...common,
114
+ target: 'latest',
115
+ peer: false,
116
+ filterResults: (name, result) => {
117
+ observed.set(name, result.upgradedVersion);
118
+ return true;
119
+ },
120
+ });
121
+ const ranged = new Map();
122
+ const upgrades = await run({
123
+ ...common,
124
+ target: 'semver',
125
+ peer: true,
126
+ filter: Object.keys(dependencies).concat(eligible.map(({ name }) => name)),
127
+ filterResults: (name, result) => {
128
+ if (!ranged.has(name) || semver.gt(result.upgradedVersion, ranged.get(name)))
129
+ ranged.set(name, result.upgradedVersion);
130
+ return eligible.some((item) => item.name === name);
131
+ },
132
+ });
133
+ for (const item of eligible) {
134
+ item.latest = observed.get(item.name) ?? null;
135
+ if (!item.latest || !ranged.has(item.name)) continue;
136
+ item.rangeLatest = ranged.get(item.name);
137
+ const candidate = semver.minVersion(upgrades?.[item.name] ?? item.range)?.version;
138
+ const current = item.installed ?? item.running;
139
+ item.candidate = candidate && current && semver.gt(current, candidate) ? current : candidate;
140
+ item.status =
141
+ item.candidate && current && semver.gt(item.candidate, current) ? 'update' : 'current';
142
+ if (!current) item.status = 'not-installed';
143
+ }
144
+ report.notes.push(
145
+ 'Candidates satisfy declared ranges and npm-check-updates peer filtering; they are not a guarantee that the complete installed graph or application is compatible. The package manager and project checks remain authoritative.',
146
+ );
147
+ if (eligible.some(({ status }) => status === 'unknown'))
148
+ report.notes.push(
149
+ 'Some registry results are unavailable; offline, authentication or registry failures must not be interpreted as up to date.',
150
+ );
151
+ } catch {
152
+ report.notes.push(
153
+ 'Update lookup did not complete. Check connectivity, registry access and authentication; no project files were changed.',
154
+ );
155
+ }
156
+ return report;
157
+ }
158
+
159
+ /** Native package-manager upgrades retain ranges; broad ranges need an explicit migration decision. */
160
+ export function updateCommand(report) {
161
+ const selected = report.packages.filter((item) => item.status === 'update' && !item.external);
162
+ for (const item of selected) {
163
+ if (item.rangeLatest && semver.gt(item.rangeLatest, item.candidate))
164
+ throw new Error(
165
+ `${item.name}: the native range update may select a peer-incompatible version. Resolve the peer constraints before updating.`,
166
+ );
167
+ const current = semver.parse(item.installed);
168
+ const line =
169
+ current.major === 0 ? `~${current.major}.${current.minor}.0` : `^${current.major}.0.0`;
170
+ if (!semver.subset(item.range, line))
171
+ throw new Error(
172
+ `${item.name}: ${item.range} permits another release line. Narrow the project constraint explicitly before updating.`,
173
+ );
174
+ }
175
+ if (!selected.length) return null;
176
+ const specs = selected.map((item) =>
177
+ report.manager.agent === 'yarn@berry' ? `${item.name}@${item.range}` : item.name,
178
+ );
179
+ const command = resolveCommand(report.manager.agent, 'upgrade', specs);
180
+ if (!command) throw new Error('This package manager has no supported upgrade command.');
181
+ if (report.manager.name === 'npm') command.args.push('--strict-peer-deps');
182
+ if (report.manager.name === 'pnpm') command.args.push('--strict-peer-dependencies');
183
+ return command;
184
+ }
185
+
186
+ function runCommand(command, args, cwd) {
187
+ return new Promise((resolve, reject) => {
188
+ const child = spawn(command, args, {
189
+ cwd,
190
+ stdio: ['inherit', 'ignore', 'ignore'],
191
+ shell: false,
192
+ });
193
+ child.once('error', () =>
194
+ reject(
195
+ new Error(
196
+ `Could not start ${command}; check that the project package manager is installed.`,
197
+ ),
198
+ ),
199
+ );
200
+ child.once('exit', (code) =>
201
+ code === 0
202
+ ? resolve()
203
+ : reject(
204
+ new Error(
205
+ `${command} failed (exit ${code}). Inspect the package manager's local logs and project diff before retrying. Agent files were not refreshed.`,
206
+ ),
207
+ ),
208
+ );
209
+ });
210
+ }
211
+
212
+ /** Explicit mutation only. Never rewrites custom skills or updates a shared/global CLI. */
213
+ export async function updatePackages({ cwd, check = checkUpdates, execute = runCommand } = {}) {
214
+ const report = await check({ cwd });
215
+ if (!report.supportedManager || report.packages.some(({ status }) => status === 'unknown'))
216
+ throw new Error(
217
+ 'Update check is incomplete; no packages or agent files were changed. Run doctor --check-updates first.',
218
+ );
219
+ const command = updateCommand(report);
220
+ if (command) await execute(command.command, command.args, report.root);
221
+ for (const item of report.packages)
222
+ item.installedAfter =
223
+ (await installedPackage(report.root, item.name))?.manifest.version ?? null;
224
+ const local = await installedPackage(report.root, '@bitakit/cli');
225
+ if (!local) {
226
+ report.notes.push(
227
+ 'No project-local CLI is installed. The external/global CLI and agent files were preserved; rerun with the desired compatible CLI version to refresh them using init --update-agent-files.',
228
+ );
229
+ } else {
230
+ await execute(
231
+ process.execPath,
232
+ [path.join(path.dirname(local.file), 'src/cli.mjs'), 'init', '--update-agent-files'],
233
+ report.root,
234
+ );
235
+ report.skills = await Promise.all(
236
+ appDevelopmentSkillPaths.map(async (file) => ({
237
+ file,
238
+ ...(await inspectSkillCopy(path.dirname(path.join(report.root, file)))),
239
+ })),
240
+ );
241
+ report.notes.push(
242
+ 'The project-local CLI ran init --update-agent-files. Edited skills are preserved. Run project tests and Doctor after the update.',
243
+ );
244
+ }
245
+ report.updated = Boolean(command);
246
+ report.notes.push(
247
+ 'Registry candidates above describe the pre-update check; installedAfter records the local result without another registry lookup.',
248
+ );
249
+ return report;
250
+ }
251
+
252
+ export function formatUpdates(report) {
253
+ return [
254
+ `BitaKit updates · running CLI ${report.runningCli} · package manager ${report.manager?.agent ?? 'unknown'}`,
255
+ ...report.packages.map(
256
+ (item) =>
257
+ `${item.name}: installed ${item.installed ?? (item.running ? `external CLI ${item.running}` : 'missing')}; latest ${item.latest ?? 'unknown'}; range/peer-filtered candidate ${item.candidate ?? 'unknown'} (${item.status})${'installedAfter' in item ? `; installed after update ${item.installedAfter ?? 'missing'}` : ''}`,
258
+ ),
259
+ ...report.skills.map(
260
+ (item) =>
261
+ `${item.file}: ${item.state}${item.version ? ` (CLI ${item.version})` : ''}; compared with running CLI ${report.runningCli}`,
262
+ ),
263
+ ...report.notes,
264
+ ].join('\n');
265
+ }